ugene-1.9.8/0000755000175000017500000000000011651544337011323 5ustar ilyailyaugene-1.9.8/COPYRIGHT0000644000175000017500000000315711651544307012621 0ustar ilyailyaUnipro UGENE - Integrated Bioinformatics Suite Copyright (C) 2008-2011 Unipro, Novosibirsk, Russia This suite of programs is free software. You can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. In other words, you are free to modify, copy, or redistribute this source code and its documentation in any way you like, but you must distribute all derivative versions as free software under the same terms that I've provided my code to you (i.e. the GNU General Public License). This precludes any use of the code in proprietary or commercial software unless your source code is made freely available. If you wish to use Unipro UGENE code under a different Open Source license that's not compatible with the GPL (like the Artistic License, BSD license, or the Netscape Public License), please contact us (ugene@unipro.ru) for permission. Incorporation into commercial software under non-GPL terms is possible by obtaining a specially licensed version from Unipro. Contact 'ugene@unipro.ru' to arrange licensing terms. This software is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this Unipro UGENE release, in the file LICENSE; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. ugene-1.9.8/installer/0000755000175000017500000000000011654525446013323 5ustar ilyailyaugene-1.9.8/installer/_common_data/0000755000175000017500000000000011651544330015731 5ustar ilyailyaugene-1.9.8/installer/_common_data/ugene.xpm0000644000175000017500000001431011651544330017561 0ustar ilyailya/* XPM */ static char *ugene_32[] = { "32 32 257 2 0 0", " c #000000", "! c #001926", "# c #001D2B", "$ c #00202D", "% c #002230", "& c #082430", "' c #002532", "( c #002634", ") c #0E2A35", "* c #002836", "+ c #142C36", ", c #002A38", "- c #172F39", ". c #002D3A", "/ c #002E3C", "0 c #0A2F3C", "1 c #1E333C", "2 c #03303D", "3 c #0D313D", "4 c #16333D", "5 c #20343E", "6 c #053240", "7 c #1B3640", "8 c #0A3241", "9 c #073441", ": c #0A3442", "; c #163642", "< c #1E3842", "= c #0A3544", "> c #0E3644", "? c #0F3845", "@ c #113846", "A c #1E3B46", "B c #113948", "C c #143B49", "D c #223E49", "E c #153C4A", "F c #1C3C4A", "G c #2F444B", "H c #163E4C", "I c #193E4C", "J c #35434C", "K c #25414D", "L c #29434D", "M c #1A404E", "N c #1D404E", "O c #29444E", "P c #1A4250", "Q c #1D4250", "R c #204250", "S c #2B4651", "T c #2D4651", "U c #2F4851", "V c #3D4B51", "W c #1E4452", "X c #204452", "Y c #1E4554", "Z c #214654", "[ c #2D4954", "\ c #244755", "] c #314A55", "^ c #224856", "_ c #254856", "` c #264958", "a c #234A58", "b c #284A58", "c c #304B58", "d c #344D58", "e c #334E59", "f c #264C5A", "g c #294C5A", "h c #51565A", "i c #35505B", "j c #53585B", "k c #54585B", "l c #274D5C", "m c #2A4E5C", "n c #2C4E5C", "o c #38525C", "p c #29505D", "q c #55595D", "r c #2D505E", "s c #3B545E", "t c #30515F", "u c #3E555F", "v c #585B5F", "w c #585C5F", "x c #2E5260", "y c #305260", "z c #3A5360", "{ c #475960", "| c #595D60", "} c #2E5462", "~ c #325462", " ! c #345563", "!! c #5C5F63", "#! c #5D6063", "$! c #315564", "%! c #355665", "&! c #355866", "'! c #385866", "(! c #3E5966", ")! c #5E6366", "*! c #375A68", "+! c #3E5A68", ",! c #395A69", "-! c #4B5F69", ".! c #4D6069", "/! c #3B5C6A", "0! c #57656A", "1! c #3C5C6B", "2! c #59666B", "3! c #3B5C6C", "4! c #3D5E6C", "5! c #58676C", "6! c #405F6D", "7! c #3E606D", "8! c #616A6D", "9! c #41606E", ":! c #5A686F", ";! c #426170", "! c #4F6872", "?! c #626D72", "@! c #686F72", "A! c #466674", "B! c #486674", "C! c #616E75", "D! c #476876", "E! c #486876", "F! c #546D76", "G! c #617076", "H! c #667177", "I! c #6B7377", "J! c #486978", "K! c #566F79", "L! c #4B6C7A", "M! c #59717A", "N! c #6E767A", "O! c #4E6E7C", "P! c #6F787C", "Q! c #5C737D", "R! c #717A7D", "S! c #50707E", "T! c #5E757E", "U! c #737D80", "V! c #757D80", "W! c #537381", "X! c #627882", "Y! c #7F8082", "Z! c #577583", "[! c #768183", "\! c #657B85", "]! c #677C85", "^! c #788185", "_! c #7D8285", "`! c #5A7786", "a! c #687E87", "b! c #7D8487", "c! c #5C7A88", "d! c #6A7E88", "e! c #858788", "f! c #5E7C8A", "g! c #6C808A", "h! c #898C8C", "i! c #607F8D", "j! c #6F838D", "k! c #858C8D", "l! c #71858E", "m! c #6F858F", "n! c #929190", "o! c #758992", "p! c #888F92", "q! c #788B94", "r! c #8F9395", "s! c #7A8C96", "t! c #7C8E97", "u! c #7C8E98", "v! c #9CA0A0", "w! c #A2A1A0", "x! c #B0AFAE", "y! c #B5B2AF", "z! c #97A8B0", "{! c #BAB5B1", "|! c #BAB7B4", "}! c #A5B0B6", "~! c #B3B4B6", " # c #BAB8B6", "!# c #BFBAB6", "## c #B8B8B8", "$# c #C2BDB9", "%# c #BFBBBA", "&# c #C5BEBA", "'# c #B7B9BC", "(# c #C2BFBC", ")# c #B9BBBD", "*# c #BDBEBD", "+# c #C5C0BD", ",# c #C0C0BF", "-# c #C2C2C1", ".# c #CCC6C1", "/# c #C7C8C7", "0# c #C9C9C7", "1# c #D2CBC7", "2# c #CACAC9", "3# c #D5CEC9", "4# c #D9D1CC", "5# c #D0CFD1", "6# c #D8D5D3", "7# c #DCD7D3", "8# c #DFD8D3", "9# c #E1D9D3", ":# c #E0D9D4", ";# c #DAD8D5", "<# c #DED9D5", "=# c #DAD7D6", "># c #E5DDD7", "?# c #D8D8D9", "@# c #D7D9D9", "A# c #E2DCD9", "B# c #E4DED9", "C# c #E6E0DA", "D# c #E8E0DB", "E# c #D6D9DD", "F# c #E1DEDD", "G# c #E5E1DD", "H# c #E8E2DD", "I# c #D8DBDE", "J# c #DADCDF", "K# c #E3E1DF", "L# c #EAE4DF", "M# c #EDE5DF", "N# c #D9DDE0", "O# c #DDDFE0", "P# c #E0DFE0", "Q# c #EDE6E0", "R# c #DEE0E2", "S# c #EAE5E2", "T# c #E0E1E3", "U# c #E5E4E3", "V# c #EFE8E3", "W# c #E2E2E4", "X# c #DFE2E6", "Y# c #E4E5E6", "Z# c #E2E4E8", "[# c #E5E6E8", "\# c #E6E8E8", "]# c #E9E9E9", "^# c #EDEDEA", "_# c #EBECEB", "`# c #E8E9EC", "a# c #EDEDEC", "b# c #F0EFEC", "c# c #F1F1EE", "d# c #FFFFFF", "e# c None", "}!u!t!u!u!u!u!u!u!u!u!u!u!u!u!u!u!u!u!u!u!u!u!u!u!u!u!u!s!z!e#e#", "u!D!D!E!E!E!E!E!E!E!E!E!E!E!E!E!E!D!D!D!D!D!D!D!D!D!D!D!=!i!#!e#", "t!D!B!B!B!B!B!B!B!B!B!B!B!A!A!A!A!A!A!A!=!=!=!=!=!=!=!#9#:#C#_!y /!/!/!/!*!z {!D#8#B#&#u *!,!,!&!W!| e#", "o!,!,!,!,!r V!D#<#<#H#b!r ,!'!'!'!%!o #G#7#B#+#s &!&!&! !S!| e#", "l!&!'!'!'!m U!C#<#<#D#_!m %!%!%!%!} i |!C#7#A#+#o } ! !y O!| e#", "l!$! !%!%!g R!C#<#<#G#^!b ~ ~ ~ ~ x e ##G#7#A#+#i x y y r L!| e#", "j!x y y y ` R!C#<#;#Y#^!\ y t t t m c '#W#;#B#+#d m r r g J!| e#", "g!m r r r Z R!C#<#I#[#^!X r r n n f [ )#Z#?#B#+#] l m m b D!| e#", "g!l m m n W P!D#I#N#]#^!N g g g g ` S *#\#E#F#+#[ a b b \ =!| e#", "d!` b b b M N!G#I#O#^#^!I b b ` ` Z O *#]#I#P#+#T Z \ \ X ;!w e#", "a!\ _ _ _ H N!K#N#R#b#^!C \ \ \ \ W K ,#_#N#O#(#L Y Z Y Q 7!v e#", "]!W Z Z Z E I!K#N#R#b#[!@ X X X X M D ,#a#J#T#%#D P Q Q M /!q e#", "\!P Q W W @ ?!F#N#R#c#^!> Q N N M H D -#a#J#T# #A H M M E *!q e#", "X!M M M M > 0!A#N#O#c#k!8 I I I I B D 0#_#J#W#x!; E H E B &!q e#", "X!E E H H : { <#N#N#b#v!0 E E E E = L 6#\#I#U#w!3 B B B > $!q e#", "T!B B C C : U 3#P#I#Y#2#7 6 C B B ( 5!]#R#E#S#h!, > > > 8 } q e#", "T!> > ? ? = 3 y!H#E#N#_#r!) ( * ' G /#Z#I#I#D#2!* : : : 6 r q e#", "Q!: : : : = * N!Q#;#E#N#Y#~!U!H!p!5#[#E#?#H#.#< . 6 6 6 / p q e#", "M!6 6 9 9 9 / 4 $#H#;#@#J#[#]#[#`#X#E#;#<#M#@!' 2 2 2 / . l q e#", "M!/ 2 2 2 2 2 ( V 4#Q#<#=#?#?#?#?#=#;#B#V#n!& . / / / . , f k e#", "M!. / / / / / / % V !#M#L#B#A#A#A#D#Q#9#Y!& ( . , , , , ( a k e#", "K!, , . . , , , . $ + 8!w!$#1#3#.#y!e!J # ( , * * * * * ' ^ j e#", "F!* * * * * * * * , ' # # ) 1 5 - % ! # ( ( ( ( ( ( ( ( % Z j e#", "F!( ( ( ( ( ( ( ( ( ( ( ' ' % % % ' ' ' ' ' ' ' ' ' % % $ X j e#", ">!$ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ # # # # # # # # # ! I h e#", "m!N R R R R R R R R R N N N N N N N N N N N N N N N N N F 7!)!e#", "e#j h h h h h h h h h h h h h h h h h h h h h h h h h h h )!e#e#", "e#e#e#e#e#e#e#e#e#e#e#e#e#e#e#e#e#e#e#e#e#e#e#e#e#e#e#e#e#e#e#e#" }; ugene-1.9.8/installer/_common_data/README0000644000175000017500000000447211651544330016620 0ustar ilyailya ---------------- UNIPRO UGENE ---------------- ----------- What is it? ----------- Unipro UGENE is a free unified bioinformatics toolkit. The goal of the project is to integrate popular bioinformatics methods and algorithms within single visual interface. UGENE allows to construct custom analisys pipelines using powerful extension named Workflow Designer. These pipelines could be used as individual command line tools. UGENE main features: * Multiple sequence alignment using MUSCLE 3 and KAlign; * HMM profiles build and search, based on the source of HMMER; * PCR Primers design using Primer 3; * Protein secondary structure prediction using GOR IV and PSIPRED; * Phylogenetic analysis with Phylip; * Search for restriction enzymes and integration with REBASE; * Extremely fast repeat finder; * DNA reference assembly using Bowtie; * Search for transcription factor binding sites using SITECON; * Protein back translation; * ORF finder; * Complete Smith-Waterman algorithm implementation; * Comparing genomes using dotplot view. UGENE is licensed via GPLv2. Please, visit http://ugene.unipro.ru for more details. ----------------------------- Install and setup environment ----------------------------- You can launch UGENE right away from the unpacked binary snapshot directory. To make UGENE available from any location on your machine add the following lines to your .bash_profile: export PATH=$PATH:/path/to/ugene/ export MANPATH=$MANPATH:/path/to/ugene/ ------------- Running UGENE ------------- The GUI version: ./ugene -ui Command line version: ./ugene ------------- Documentation ------------- There is man page available for command-line version: man man1/ugene.1.gz For complete user documentation visit: http://ugene.unipro.ru/manual ------------------- Directory structure ------------------- README This file ugene UGENE executable script man1/ UGENE man page dir plugins/ Plugins dir ugenecl UGENE console executable file ugeneui UGENE GUI executable file data/ Sample data for supported formats, workflow samples, weight matrices, DNA back translation tables, enzymes data, list of known remtote databases etc. *.so.4 Shared libraries required by UGENE *.qm Translations of UGENE to various languages ugene-1.9.8/installer/_common_data/ugened0000755000175000017500000000100211651544330017117 0ustar ilyailya#!/bin/bash appname=ugenecld # Check if '-ui' parameter is present. # If it does exclude it from the list of parameters # and use ugeneui instead of ugenecl params=() while [[ $# -gt 0 ]]; do if [ "$1" = "-ui" ]; then appname=ugeneuid else params+=("$1") fi shift done dirname=$(dirname `readlink -f $0`) tmp="${dirname#?}" if [ "${dirname%$tmp}" != "/" ]; then dirname=$PWD/$dirname fi LD_LIBRARY_PATH=$dirname export LD_LIBRARY_PATH $dirname/$appname "${params[@]}" ugene-1.9.8/installer/_common_data/ugene0000755000175000017500000000100111651544330016752 0ustar ilyailya#!/bin/bash appname=ugenecl # Check if '-ui' parameter is present. # If it does exclude it from the list of parameters # and use ugeneui instead of ugenecl params=() while [[ $# -gt 0 ]]; do if [ "$1" = "-ui" ]; then appname=ugeneui else params+=("$1") fi shift done dirname=$(dirname `readlink -f $0`) tmp="${dirname#?}" if [ "${dirname%$tmp}" != "/" ]; then dirname=$PWD/$dirname fi LD_LIBRARY_PATH=$dirname export LD_LIBRARY_PATH $dirname/$appname "${params[@]}"ugene-1.9.8/installer/_common_data/ugene.1.gz0000644000175000017500000000301711651544330017536 0ustar ilyailya(2UMugene.1Wn7}߯M 年 B#KEjs-/V̐m$}.wgfPܾ^;pQ-YQͯ|<,>//Xr KP&ȕA6PVu `?ד|4/ +idQFPFUT'LoF9|I`6#ʃYN@~A{i py}492FijBosZtZm٢%ze UV6OQ_0WrC8;|Fʬذ_w]r0mU *O(K)BtryUT)Z|Tr cl@?=>>kbABo5 t[F:No47C?V kpX ׃~87WXUj1Dg'ws6c"J7,B8r&N6:tp%6ҙdkk'\d y?>WS͖뭶40؈nPz NyfD3 :Q߉kҪ|J@u N_;qؽ` SF.磛I2|۶2P?tΩ͆crY^b8}_Q4N.K]lzúzT %cٻy6y?䰱n&%8}7=⳵8 ;Gxt532:VaKAw:AVir(> au¡ʷY+dRdXKV[,%Uq>:W`HgT-Fzl4iGfXVIrMѭUvZEFQNa"{;@Jd6/-OD*0F=C*T{8cxY4 nPם2k Tʷ)Xp+u {}\*k~(J>!}:2$<H \vltx`WAutWjy/"J?(rz) 1UQwۓ8IEIO)kB<%K0CExȥ)lX} q#P'jJ@/ jlEuL pM5ܒ6cd<_&%R=ά 囦XlleNA޼¬"fY6}{QNj0^ho]е5l,(|m0ϯ/=\m3w{Yzwl%EK $ x!<" "K +#,G1ۻݙ*9US]ݳÃ3UuΩ|;#^~ܿk{YJ+BZCE0w:P\o< ?yEcpIt909fz;y4~~~>u (|Nto'IB)iQn%4{ǁ-lzc?c.*1 j7dGK\nMn;rp{) [If|@c' LFTtSBb= 1oC踿(rn}#gTEL!$*u.BTk`?ׂOl0IR`e:)Ӂa:Y¨\} $\cm ߭CڏsM<S+B. T!*\tO55ƜNrJRJ3f6 yx%,Ěa#ڍwwI 킎 Ic,,48qWĠڝ4\ .b8'"sU {\%DC%B%x캉K!Dpq.IwWm =,eHBc[OgCզJXEۋ>9`%^@B'1T喢]T**.%! \ 4vIlF̒EQi epgX`h-[:1񷃚v!zMr"C !馶D8ƪQmSy+8@5B*!3@円8=,dZsF) M?ǹ"2 Q29nVAprntg6KpFA3QgL)`VFL+b5'(2J9PQc〲,b՛A\H7\1n_H6FШ&t\Åc+Q_jg2D {)cE PBO3ǘl8UQ Mz%尬"Bf[_)i$SlȤv J~m0iVmĔg%kPrBԢ 7j:ux^pL' DF(ɲ}oc6Ǒ J ba 'TH6FaotQvY3W!66-toXj* 3LZ4WJ[ ܧ1 ?l!ӾF(m~x.q'l@{͖&NMPCg@kUCn"K2>t NPNQu!ȬF%u@2@ԫ/sx5^]o3GrkjIL%Faw{dҳiiՖVT^fbBN Zaie[Ɲ[;mZ}zbJmߏkVN%;Ea,..bh:*izi.[mxn*@,$7셶g>G^aqf{P`scm}c3NrId$s sx%]A27_g*+\"l6`"q1 ujh<4>~i]_Ba5Z@W`"ms9#{`yZeqsҭ.z! 58ƛps.LOMfiN4){KODC֬p$췞}S4)@å7ڭ\?|-Wȴ5^.簇qysS8j0WE ogC8Cv:jSHF ,!Tdr: :J%5p_+? Ay0SƲFHO$!04|J'j6 OO!;9hjrXknZ /Fk&8VuͨCWen3J:lM3B&{CN^L'$4&P. ,`Fn!_Wy.^E "$G(feP*VXfpμvzE~,N1ǩiy2T8S 6~'OF崇-Tb ]-՛$~&w|>֗x#r"l.ZD"|%0&-6v}ZUo!V{;@-aB Copyright (C) 19yy This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. Also add information on how to contact you by electronic and paper mail. If the program is interactive, make it output a short notice like this when it starts in an interactive mode: Gnomovision version 69, Copyright (C) 19yy name of author Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, the commands you use may be called something other than `show w' and `show c'; they could even be mouse-clicks or menu items--whatever suits your program. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the program, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the program `Gnomovision' (which makes passes at compilers) written by James Hacker. , 1 April 1989 Ty Coon, President of Vice This General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Library General Public License instead of this License. ugene-1.9.8/src/0000755000175000017500000000000011651544342012106 5ustar ilyailyaugene-1.9.8/src/ugene_version.pri0000644000175000017500000000030011651544307015464 0ustar ilyailya# This file contains UGENE version info # product version UGENE_VERSION=1.9.8 # int version levels for executables UGENE_VER_MAJOR=1 UGENE_VER_MINOR=9 UGENE_VER_BUILD=8 UGENE_VER_REVISION=0 ugene-1.9.8/src/plugins/0000755000175000017500000000000011651544325013570 5ustar ilyailyaugene-1.9.8/src/plugins/circular_view/0000755000175000017500000000000011651544321016422 5ustar ilyailyaugene-1.9.8/src/plugins/circular_view/circular_view.pro0000644000175000017500000000115711651544321022006 0ustar ilyailyainclude (circular_view.pri) # Input HEADERS += src/CircularItems.h \ src/CircularView.h \ src/CircularViewPlugin.h \ src/CircularViewSplitter.h \ src/ExportImageCircularViewDialog.h \ src/RestrictionMapWidget.h SOURCES += src/CircularItems.cpp \ src/CircularView.cpp \ src/CircularViewPlugin.cpp \ src/CircularViewSplitter.cpp \ src/ExportImageCircularViewDialog.cpp \ src/RestrictionMapWidget.cpp RESOURCES += circular_view.qrc TRANSLATIONS += transl/czech.ts transl/english.ts transl/russian.ts ugene-1.9.8/src/plugins/circular_view/circular_view.pri0000644000175000017500000000024011651544321021770 0ustar ilyailya# include (circular_view.pri) PLUGIN_ID=circular_view PLUGIN_NAME=Plasmid viewer PLUGIN_VENDOR=Unipro PLUGIN_MODE=ui include( ../../ugene_plugin_common.pri ) ugene-1.9.8/src/plugins/circular_view/circular_view.qrc0000644000175000017500000000036411651544321021772 0ustar ilyailya images/circular.png images/empty_folder.png images/folder.png images/side_list.png ugene-1.9.8/src/plugins/circular_view/images/0000755000175000017500000000000011651544321017667 5ustar ilyailyaugene-1.9.8/src/plugins/circular_view/images/side_list.png0000644000175000017500000000077611651544321022366 0ustar ilyailyaPNG  IHDRagAMA7tEXtSoftwareAdobe ImageReadyqe<IDATjTaQA[m-EqJ-&"&V ĔZb 4ށBA, (nDVrwnuypK #nq3Ldg+u4:/.p'<9<~ _}y'Gua#}i!Sǿα19/d;ag5fRIH) PMFhۖhTɐS&XA&Bu9ag fJ ȉBP%#,{%MӰT*! ($BږrNNNڎPD ksttS9%.\"TIO֘UR"* wB=}wٮ 03$am˭ǟ;.͑ 3̜~+QIENDB`ugene-1.9.8/src/plugins/circular_view/images/empty_folder.png0000644000175000017500000000100211651544321023057 0ustar ilyailyaPNG  IHDRagAMA7tEXtSoftwarePaint.NET v3.5.7IDAT8OSjPu}w~GqB ~T|Do#Fhp4jL4 xt]8\2sΙ3$O6[(L&xbz$8yxN@1 AJ>d@Vct]t:njArWp8p#]Dnw4*ڂ LT~r#cȲ,H$7x<a`jt zk4`&bA4=QzfUUU*e@S&J"ȍ D@͔>98YYWG+b#2BX4P#4/ l&0`{ A IK0|S xxÑ?qQIENDB`ugene-1.9.8/src/plugins/circular_view/images/folder.png0000644000175000017500000000103111651544321021643 0ustar ilyailyaPNG  IHDRagAMA7tEXtSoftwareAdobe ImageReadyqe<IDAT8œA[EtQg7wALCWA0P017p2=:A3cb2'pܪ$Vme@ ݬ2OTO1W/`z8% ;O;9P#9B}^nO;Ǫo~ d~E dpɳ__j@1|}5(*%J' [UnQFJG箿{3fb ~0Q*ΡӬ X86כqe?o>i[歯?Pr]HoKoY~33<檧@?ҿ9$.i3cLcKf}>$/'ޞ R .ߑUmI \O_;&ϼg?wgqA?ӿӞ4@絉 o3d$ƚn?Zhzmz"( bE EU*ACք4۴&I΀>Ǽ/v[3yBA>sHS``FҚXsU 8V(A{IENDB`ugene-1.9.8/src/plugins/circular_view/src/0000755000175000017500000000000011651544321017211 5ustar ilyailyaugene-1.9.8/src/plugins/circular_view/src/ExportImageCircularViewDialog.cpp0000644000175000017500000000546511651544321025613 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "ExportImageCircularViewDialog.h" #include "CircularView.h" #include #include #include #include #include #include #include #include #include namespace U2 { ExportImageCVDialog::ExportImageCVDialog(CircularView * widget ) : ExportImageDialog(widget,false,true), cvWidget(widget) { } bool ExportImageCVDialog::exportToSVG(){ QPainter painter; QSvgGenerator generator; generator.setFileName(getFilename()); generator.setSize(cvWidget->size()); generator.setViewBox(cvWidget->rect()); painter.begin(&generator); cvWidget->paint(painter); bool result = painter.end(); //fix for UGENE-76 QDomDocument doc("svg"); QFile file(getFilename()); bool ok=file.open(QIODevice::ReadOnly); if (!ok && !result){ result=false; } ok=doc.setContent(&file); if (!ok && !result) { file.close(); result=false; } if(result){ file.close(); QDomNodeList radialGradients=doc.elementsByTagName("radialGradient"); for(uint i=0;ipaint(painter); return painter.end(); } } // namespace ugene-1.9.8/src/plugins/circular_view/src/ExportImageCircularViewDialog.h0000644000175000017500000000241011651544321025243 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_EXPORT_IMAGE_CV_DIALOG_H_ #define _U2_EXPORT_IMAGE_CV_DIALOG_H_ #include namespace U2 { class CircularView; class ExportImageCVDialog : public ExportImageDialog { Q_OBJECT public: ExportImageCVDialog(CircularView* widget); virtual bool exportToSVG(); virtual bool exportToPDF(); private: CircularView* cvWidget; }; // class ExportImageCVDialog } // namespace #endif ugene-1.9.8/src/plugins/circular_view/src/CircularViewSplitter.h0000644000175000017500000000470111651544321023512 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_CIRCULAR_VIEW_SPLITTER_H_ #define _U2_CIRCULAR_VIEW_SPLITTER_H_ #include "CircularView.h" #include "CircularItems.h" #include #include #include #include class QScrollBar; namespace U2 { class CircularViewHeaderWidget; class HBar; class RestrctionMapWidget; class CircularViewSplitter : public ADVSplitWidget{ Q_OBJECT public: CircularViewSplitter( AnnotatedDNAView* view); // there are no special object handling with this view // it only shows existing AO only virtual bool acceptsGObject(GObject*) {return false;} virtual void updateState(const QVariantMap& m); virtual void saveState(QVariantMap& m); void addView(CircularView* view, RestrctionMapWidget* rmapWidget); void adaptSize(); void removeView(CircularView* view, RestrctionMapWidget* rmapWidget); bool isEmpty(); const QList& getViewList() const { return circularViewList; } protected slots: void sl_export(); void sl_horSliderMoved(int); void sl_moveSlider(int); void sl_updateZoomInAction(bool); void sl_updateZoomOutAction(bool); void sl_updateFitInViewAction(bool); void sl_toggleRestrictionMap(bool); private: QSplitter* splitter; HBar* toolBar; QScrollBar* horScroll; QToolButton* tbZoomIn; QToolButton* tbZoomOut; QToolButton* tbFitInView; QToolButton* tbExport; QToolButton* tbToggleRestrictionMap; QList circularViewList; QList restrictionMapWidgets; }; } //namespace U2 #endif //_U2_CIRCULAR_VIEW_SPLITTER_H_ ugene-1.9.8/src/plugins/circular_view/src/RestrictionMapWidget.h0000644000175000017500000000446711651544321023504 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_RESTRICTION_MAP_WIDGET_H_ #define _U2_RESTRICTION_MAP_WIDGET_H_ #include namespace U2 { class ADVSequenceObjectContext; class AnnotationTableObject; class AnnotationGroup; class Annotation; class EnzymeItem : public QTreeWidgetItem { public: EnzymeItem(const QString& locationStr, Annotation* a); Annotation* getEnzymeAnnotation() const {return annotation; } private: Annotation* annotation; }; class EnzymeFolderItem : public QTreeWidgetItem { QString enzymeName; public: EnzymeFolderItem(const QString& name); void addEnzymeItem(Annotation* enzAnn); void removeEnzymeItem(Annotation* enzAnn); const QString& getName() const { return enzymeName; } }; class RestrctionMapWidget : public QWidget { Q_OBJECT public: RestrctionMapWidget(ADVSequenceObjectContext* ctx, QWidget *p); private slots: void sl_onAnnotationsAdded(const QList& anns); void sl_onAnnotationsRemoved(const QList& anns); void sl_onAnnotationsInGroupRemoved(const QList& anns, AnnotationGroup* group); void sl_onAnnotationsGroupCreated(AnnotationGroup* g); void sl_itemSelectionChanged(); private: ADVSequenceObjectContext* ctx; QTreeWidget* treeWidget; EnzymeFolderItem* findEnzymeFolderByName(const QString& enzymeName); void registerAnnotationObjects(); void updateTreeWidget(); void initTreeWidget(); }; } //namespace #endif // _U2_RESTRICTION_MAP_WIDGET_H_ ugene-1.9.8/src/plugins/circular_view/src/CircularView.h0000644000175000017500000001372611651544321021772 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_CIRCULAR_PAN_VIEW_H_ #define _U2_CIRCULAR_PAN_VIEW_H_ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include namespace U2 { class CircularViewRenderArea; class Annotation; class CircularAnnotationItem; class CircularAnnotationLabel; class TextItem; class CircularView : public GSequenceLineViewAnnotated { Q_OBJECT public: CircularView(QWidget* p, ADVSequenceObjectContext* ctx); void pack(); void mousePressEvent(QMouseEvent * e); void mouseMoveEvent(QMouseEvent * e); void mouseReleaseEvent(QMouseEvent* e); void resizeEvent(QResizeEvent* e); void wheelEvent(QWheelEvent* we); virtual QSize sizeHint() const; virtual QList selectAnnotationByCoord(const QPoint& coord) const; static qreal coordToAngle(const QPoint point); const QMap& getCircularItems() const; const QList& getLabelList() const; bool isCircularTopology() { return true; } enum Direction {CW, CCW, UNKNOWN}; static const int MIN_OUTER_SIZE; static const int CV_REGION_ITEM_WIDTH; void setAngle(int angle); void updateMinHeight(); //used by export to file function void paint(QPainter& p); signals: void si_wheelMoved(int); void si_zoomInDisabled(bool); void si_zoomOutDisabled(bool); void si_fitInViewDisabled(bool); public slots: void sl_zoomIn(); void sl_zoomOut(); void sl_fitInView(); void sl_onSequenceObjectRenamed(const QString& oldName); protected slots: virtual void sl_onAnnotationSelectionChanged(AnnotationSelection*, const QList& added, const QList& removed); virtual void sl_onDNASelectionChanged(LRegionsSelection* thiz, const QVector& added, const QVector& removed); void sl_sequenceWidgetRemoved(ADVSequenceWidget*); protected: void adaptSizes(); void updateZoomActions(); Direction getDirection(float a, float b) const; QVBoxLayout *layout; int lastMovePos; int currectSelectionLen; int lastMouseY; CircularViewRenderArea* ra; bool clockwise, holdSelection; private: static const int graduation; }; class CircularViewRenderArea : public GSequenceLineViewAnnotatedRenderArea { friend class CircularView; friend class CircularAnnotationItem; friend class CircularAnnotationLabel; friend class CircurlarAnnotationRegionItem; Q_OBJECT public: CircularViewRenderArea(CircularView* d); ~CircularViewRenderArea(); int getAnnotationYLevel (Annotation* a) const { return annotationYLevel.value(a); } void adaptNumberOfLabels(int h); static const int MIDDLE_ELLIPSE_SIZE; int getCenterY() const { return verticalOffset; } protected: void resizeEvent(QResizeEvent *e); virtual void drawAll(QPaintDevice* pd); virtual U2Region getAnnotationYRange(Annotation* a, int ri, const AnnotationSettings* as) const; void buildAnnotationItem(DrawAnnotationPass pass, Annotation* a, bool selected = false, const AnnotationSettings* as = NULL); virtual void drawAnnotations(QPainter& p); void paintContent(QPainter& p); void buildAnnotationLabel(const QFont& font, Annotation* a, const AnnotationSettings* as); void drawSequenceName(QPainter& p); void drawRuler(QPainter& p); void drawRulerNotches(QPainter& p, int start, int span, int seqLen); void drawAnnotationsSelection(QPainter& p); void drawSequenceSelection(QPainter& p); void drawMarker(QPainter& p); void evaluateLabelPositions(); qreal getVisibleAngle() const; QPair getVisibleRange() const; private: static const int OUTER_ELLIPSE_SIZE; static const int ELLIPSE_DELTA; static const int INNER_ELLIPSE_SIZE; static const int RULER_ELLIPSE_SIZE; static const int ARROW_LENGTH; static const int ARROW_HEIGHT_DELTA; static const int MAX_DISPLAYING_LABELS; static const int MARKER_LEN; static const int ARR_LEN; static const int ARR_WIDTH; static const int NOTCH_SIZE; int outerEllipseSize; int ellipseDelta; int innerEllipseSize; int rulerEllipseSize; int middleEllipseSize; int arrowLength; int arrowHeightDelta; int maxDisplayingLabels; bool fitsInView; int verticalOffset; CircularView* circularView; QList< QVector > regionY; QMap< Annotation*, CircularAnnotationItem* > circItems; TextItem* seqNameItem; TextItem* seqLenItem; QMap< Annotation* , int > annotationYLevel; QList labelList; qreal rotationDegree; qreal mouseAngle; QVector labelEmptyPositions; QVector labelEmptyInnerPositions; int oldYlevel; }; }//namespace; #endif ugene-1.9.8/src/plugins/circular_view/src/CircularItems.cpp0000644000175000017500000003575111651544321022476 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "CircularItems.h" #include "CircularView.h" #include #include #include #include #include #include namespace U2 { /************************************************************************/ /* CircularAnnotationItem */ /************************************************************************/ CircularAnnotationItem::CircularAnnotationItem(Annotation* ann, CircurlarAnnotationRegionItem* region, CircularViewRenderArea* _ra) : ra(_ra) { assert(region->parent == NULL); region->parent = this; regions.append(region); this->annotation = ann; _boundingRect = region->boundingRect(); isSelected = false; } CircularAnnotationItem::CircularAnnotationItem(Annotation* ann, QList& _regions, CircularViewRenderArea* _ra) : regions(_regions), ra(_ra) { this->annotation = ann; isSelected = false; QPainterPath path; foreach(CircurlarAnnotationRegionItem* item, regions) { assert(item->parent == NULL); item->parent = this; path = path.united(item->path()); } _boundingRect = path.boundingRect(); } CircularAnnotationItem::~CircularAnnotationItem() { foreach(CircurlarAnnotationRegionItem* item, regions) { delete item->label; delete item; } regions.clear(); } void CircularAnnotationItem::paint(QPainter *p,const QStyleOptionGraphicsItem *item,QWidget *widget) { Q_UNUSED(item); AnnotationSettingsRegistry* asr = AppContext::getAnnotationsSettingsRegistry(); AnnotationSettings* as = asr->getAnnotationSettings(annotation->getAnnotationName()); this->color = as->color; foreach(CircurlarAnnotationRegionItem* item, regions) { item->paint(p, NULL, widget); } } QRectF CircularAnnotationItem::boundingRect() const{ return _boundingRect; } Annotation* CircularAnnotationItem::getAnnotation() const { return annotation; } bool CircularAnnotationItem::contains(const QPointF &point) { if(_boundingRect.contains(point)) { foreach(CircurlarAnnotationRegionItem* item, regions) if(item->contains(point)) { return true; } } return false; } int CircularAnnotationItem::containsRegion(const QPointF &point) { if(_boundingRect.contains(point)) { foreach(CircurlarAnnotationRegionItem* item, regions) { if(item->contains(point)) { return item->number; } } } return -1; } void CircularAnnotationItem::setSelected( bool isSelected ) { this->isSelected = isSelected; } const QList& CircularAnnotationItem::getRegions() { return regions; } /************************************************************************/ /* CircurlarAnnotationRegionItem */ /************************************************************************/ CircurlarAnnotationRegionItem::CircurlarAnnotationRegionItem(const QPainterPath& path, bool _isShort, int _number ) :QGraphicsPathItem(path), parent(NULL), label(NULL), number(_number), isShort(_isShort) { } void CircurlarAnnotationRegionItem::paint( QPainter *p, const QStyleOptionGraphicsItem *option, QWidget *widget /* = 0 */ ) { Q_UNUSED(widget); Q_UNUSED(option); assert(parent!=NULL); QPen pen(Qt::black); pen.setWidth(1); if(parent->isSelected) { pen.setWidth(2); } p->setPen(pen); CircularViewRenderArea* renderArea = parent->ra; int yLevel = renderArea->annotationYLevel[parent->annotation]; int innerRadius = renderArea->innerEllipseSize/2 + yLevel * renderArea->ellipseDelta/2; int outerRadius = renderArea->outerEllipseSize/2 + yLevel * renderArea->ellipseDelta/2; QColor &color(parent->color); QRadialGradient radialGrad(QPointF(0, 0), outerRadius ); radialGrad.setColorAt(1, color); radialGrad.setColorAt((float)innerRadius / (float)outerRadius, QColor(color.red()*0.7,color.green()*0.7,color.blue()*0.7)); radialGrad.setColorAt(0, Qt::black); p->fillPath(path(), radialGrad); if(!isShort || parent->isSelected) { p->drawPath(path()); } } CircularAnnotationLabel* CircurlarAnnotationRegionItem::getLabel() const { return label; } void CircurlarAnnotationRegionItem::setLabel( CircularAnnotationLabel* label ) { this->label = label; } /************************************************************************/ /* CircularAnnotationLabel */ /************************************************************************/ static bool labelLengthLessThan(CircularAnnotationLabel* l1, CircularAnnotationLabel* l2) { int length1 = l1->getAnnotation()->getRegions()[l1->getRegion()].length; int length2 = l2->getAnnotation()->getRegions()[l2->getRegion()].length; return length1 < length2; } CircularAnnotationLabel::CircularAnnotationLabel( Annotation* ann, int _region, int sequenceLength, const QFont& font, CircularViewRenderArea* renderArea ) : annotation(ann), labelFont(font), region(_region), ra(renderArea), hasPosition(false), inner(false), seqLen(sequenceLength) { const U2Region& r = annotation->getRegions()[region]; qreal startAngle = (float)r.startPos / (float)sequenceLength * 360; qreal spanAngle = qMin((float)r.length / (float)sequenceLength * 360, float(360 - startAngle)); startAngle+=renderArea->rotationDegree; float middleAngle = 360 - (startAngle + spanAngle /2.0); annotationAngle = middleAngle; if (annotationAngle<0) { annotationAngle+=360; } startA = startAngle*PI/180; endA = spanAngle*PI/180 + startA; spanA = spanAngle*PI/180; if(startA>2*PI) { startA -=2*PI; } else if(startA<0) { startA +=2*PI; } if(endA>2*PI) { endA -=2*PI; } else if(endA<0) { endA +=2*PI; } const int yLevel = renderArea->annotationYLevel[annotation]; //const int count = renderArea->regionY.count(); midRect = QRectF(-renderArea->middleEllipseSize/2 - yLevel * renderArea->ellipseDelta/2, -renderArea->middleEllipseSize/2 - yLevel * renderArea->ellipseDelta/2, renderArea->middleEllipseSize + yLevel * renderArea->ellipseDelta, renderArea->middleEllipseSize + yLevel * renderArea->ellipseDelta); setVisible(false); AnnotationSettingsRegistry* asr = AppContext::getAnnotationsSettingsRegistry(); AnnotationSettings* as = asr->getAnnotationSettings(annotation->getAnnotationName()); labelText=GSequenceLineViewAnnotated::prepareAnnotationText(annotation, as); } void CircularAnnotationLabel::prepareLabels(QList& labelItems) { qSort::iterator>(labelItems.begin(), labelItems.end(), labelLengthLessThan); foreach(CircularAnnotationLabel* l, labelItems) { l->setVisible(true); } } void CircularAnnotationLabel::setLabelPosition() { ////find closest empty label position QPointF midRegionPoint = QPointF (midRect.width()/2 * cos(annotationAngle / 180.0 * PI), -midRect.height()/2 * sin(annotationAngle / 180.0 * PI)).toPoint(); QVector& outerRects = ra->labelEmptyPositions; QVector indexes;//nearby points getVacantPositions(outerRects, indexes); int closest = findClosestPoint(midRegionPoint.toPoint(), outerRects, indexes); if(-1==closest) { //inner positions QVector& rects = ra->labelEmptyInnerPositions; QVector indexes2; getVacantInnerPositions(rects, indexes2); closest = findClosestPoint(midRegionPoint.toPoint(), rects, indexes2); if(-1==closest) { return; } QRect rect = rects.at(closest); labelPos = QPoint(rect.topLeft()); rects.remove(closest); inner=true; //assume innerPositions have predefined order: pos[i].x>0, pos[i+1]<0 if(labelPos.x()<0) { assert(rects.size()>closest-1); int prevWidth = rects[closest-1].width(); rects[closest-1].setWidth(prevWidth - rect.width()); } else { assert(rects.size()>closest); int prevWidth = rects[closest].width(); rects[closest].setWidth(prevWidth - rect.width()); } } else { QRect r = outerRects.at(closest); labelPos = QPoint(r.topLeft()); outerRects.remove(closest); } getConnectionPoint(); hasPosition=true; } int CircularAnnotationLabel::findClosestPoint(const QPoint& targetPoint, const QVector& rects, QVector indexes) { foreach(int idx, indexes) { assert(idx>=0 && idxrects.at(idx).width()) { int i = indexes.indexOf(idx); indexes.remove(i); } } int size = indexes.size(); if(0==size) { return -1; } int index = indexes.at(0); assert(index>=0&&index=0&&idxcurrDistance) { minDistance = currDistance; closest=idx; } } return closest; } void CircularAnnotationLabel::getVacantPositions(const QVector& rects, QVector& result) { foreach(QRect rect, rects) { qreal arcsin = CircularView::coordToAngle(rect.topLeft()); if(startA>endA) { //region contains 2*PI angle if(arcsin>startA - PI/16 || arcsinstartA - PI/16 && arcsin < endA + PI/16) { result << rects.indexOf(rect); } } } } void CircularAnnotationLabel::getVacantInnerPositions(const QVector& rects, QVector& result) { QPointF midRegionPoint = QPointF (midRect.width()/2 * cos(annotationAngle / 180.0 * PI), -midRect.height()/2 * sin(annotationAngle / 180.0 * PI)).toPoint(); foreach(QRect r, rects) { if(midRegionPoint.y()>0) { qreal delta = qAbs(midRegionPoint.y() - r.bottom()); if(deltaheight()/5.0) { result << rects.indexOf(r); } } else { qreal delta = qAbs(midRegionPoint.y() - r.top()); if(deltaheight()/5.0) { result << rects.indexOf(r); } } } } #define CONNECTION_POINT_PAD PI/36 void CircularAnnotationLabel::getConnectionPoint() { qreal arcsin = CircularView::coordToAngle(labelPos); if(spanAendA) { //region contains 2*PI angle if(arcsin>startA+CONNECTION_POINT_PAD || arcsinstartA+CONNECTION_POINT_PAD && arcsin < endA-CONNECTION_POINT_PAD) { connectionPoint = QPoint(midRect.width()/2 * cos(arcsin), midRect.width()/2 * sin(arcsin)); return; } } if(abs(startA-arcsin)circItems.value(annotation); QPen pen(Qt::black); pen.setWidth(1); labelFont.setBold(false); if(ai->isSelected) { labelFont.setBold(true); p->setFont(labelFont); pen.setWidth(2); } p->setPen(pen); QRectF bound = boundingRect(); p->fillRect(bound, Qt::white); p->drawText(bound, labelText); pen.setStyle(Qt::DotLine); p->setPen(pen); p->drawLine(labelPos, connectionPoint); pen.setStyle(Qt::SolidLine); p->setPen(pen); } Annotation* CircularAnnotationLabel::getAnnotation() const { return annotation; } QRectF CircularAnnotationLabel::boundingRect() const { QFontMetrics fm(labelFont); QRectF bound = fm.boundingRect(labelText+' '); if(!inner) { if(labelPos.x()>0 && labelPos.y()>=0) { bound.moveTopLeft(labelPos); } else if(labelPos.x()<0 && labelPos.y()>=0) { bound.moveTopRight(labelPos); } else if(labelPos.x()<0 && labelPos.y()<0) { bound.moveBottomRight(labelPos); } else { bound.moveBottomLeft(labelPos); } } else { if(labelPos.x()>0 && labelPos.y()>=0) { bound.moveBottomRight(labelPos); } else if(labelPos.x()<0 && labelPos.y()>=0) { bound.moveBottomLeft(labelPos); } else if(labelPos.x()<0 && labelPos.y()<0) { bound.moveTopLeft(labelPos); } else { bound.moveTopRight(labelPos); } } return bound; } bool CircularAnnotationLabel::contains( const QPointF &point ) { return boundingRect().contains(point) || QGraphicsLineItem(QLine(labelPos, connectionPoint)).contains(point); } int CircularAnnotationLabel::getRegion() const { return region; } } // namespace U2 ugene-1.9.8/src/plugins/circular_view/src/RestrictionMapWidget.cpp0000644000175000017500000001762011651544321024032 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include #include #include #include #include #include #include #include #include #include "RestrictionMapWidget.h" #define ENZYME_FOLDER_ITEM_TYPE 1022 #define ENZYME_ITEM_TYPE 1023 namespace U2 { ////////////////////////////////////////////////////////////////////////// ///EnzymeItem EnzymeItem::EnzymeItem( const QString& location, Annotation* a ) : QTreeWidgetItem(QStringList(location), ENZYME_ITEM_TYPE), annotation(a) { } ////////////////////////////////////////////////////////////////////////// ///EnzymeFolderItem EnzymeFolderItem::EnzymeFolderItem( const QString& name ) : QTreeWidgetItem(ENZYME_FOLDER_ITEM_TYPE), enzymeName(name) { setText(0, QString("%1 : %2 %3").arg(name).arg(0).arg("sites")); } void EnzymeFolderItem::addEnzymeItem( Annotation* enzAnn ) { QString location = Genbank::LocationParser::buildLocationString(enzAnn->data()); addChild(new EnzymeItem(location, enzAnn) ); setIcon(0, QIcon(":circular_view/images/folder.png")); int count = childCount(); QString site = count == 1 ? RestrctionMapWidget::tr("site") : RestrctionMapWidget::tr("sites"); setText(0, QString("%1 : %2 %3").arg(getName()).arg(count).arg(site)); } void EnzymeFolderItem::removeEnzymeItem( Annotation* enzAnn ) { int count = childCount(); for (int i = 0; i < count; ++i) { EnzymeItem* item = static_cast ( child(i) ); if (item->getEnzymeAnnotation() == enzAnn) { removeChild(item); QString site = --count == 1 ? RestrctionMapWidget::tr("site") : RestrctionMapWidget::tr("sites"); setText(0, QString("%1 : %2 %3").arg(getName()).arg(count).arg(site)); if (count == 0) { setIcon(0, QIcon(":circular_view/images/empty_folder.png")); } break; } } } ////////////////////////////////////////////////////////////////////////// ///RestrictionMapWidget RestrctionMapWidget::RestrctionMapWidget( ADVSequenceObjectContext* context, QWidget *p ) : QWidget(p), ctx(context) { assert(context != NULL); QVBoxLayout* layout = new QVBoxLayout(this); layout->setContentsMargins(0, 0, 0, 0); treeWidget = new QTreeWidget(this); treeWidget->setColumnCount(1); treeWidget->setHeaderLabel(tr("Restriction Sites Map")); connect(treeWidget,SIGNAL(itemSelectionChanged()), SLOT(sl_itemSelectionChanged())); layout->addWidget(treeWidget); registerAnnotationObjects(); updateTreeWidget(); initTreeWidget(); } void RestrctionMapWidget::updateTreeWidget() { treeWidget->clear(); QString selection = AppContext::getSettings()->getValue(EnzymeSettings::LAST_SELECTION).toString(); if (selection.isEmpty()) { selection = EnzymeSettings::COMMON_ENZYMES; } QStringList selectedEnzymes = selection.split(ENZYME_LIST_SEPARATOR, QString::SkipEmptyParts); QList items; foreach(const QString& enzyme, selectedEnzymes) { EnzymeFolderItem* item = new EnzymeFolderItem( enzyme ); item->setIcon(0, QIcon(":circular_view/images/empty_folder.png")); items.append(item); } treeWidget->insertTopLevelItems(0, items); } void RestrctionMapWidget::registerAnnotationObjects() { QSet aObjs = ctx->getAnnotationObjects(true); foreach (AnnotationTableObject* ao, aObjs) { connect(ao, SIGNAL(si_onAnnotationsAdded(const QList&)), SLOT(sl_onAnnotationsAdded(const QList&))); connect(ao, SIGNAL(si_onAnnotationsRemoved(const QList&)), SLOT(sl_onAnnotationsRemoved(const QList&))); connect(ao, SIGNAL(si_onAnnotationsInGroupRemoved(const QList&, AnnotationGroup*)), SLOT(sl_onAnnotationsInGroupRemoved(const QList&, AnnotationGroup*))); connect(ao, SIGNAL(si_onGroupCreated(AnnotationGroup* )), SLOT(sl_onAnnotationsGroupCreated(AnnotationGroup*))); } } void RestrctionMapWidget::sl_onAnnotationsAdded( const QList& anns ) { foreach (Annotation* a, anns) { QString aName = a->getAnnotationName(); EnzymeFolderItem* folderItem = findEnzymeFolderByName(aName); if (folderItem) { folderItem->addEnzymeItem(a); } } //TODO: enable "intelligent" sorting by reimplementing custom AbstractModel // Take into account number of items in each enzymes folder treeWidget->sortItems(0, Qt::AscendingOrder); } void RestrctionMapWidget::sl_onAnnotationsRemoved( const QList& anns ) { foreach (Annotation* a, anns) { EnzymeFolderItem* folderItem = findEnzymeFolderByName(a->getAnnotationName()); if (folderItem) { folderItem->removeEnzymeItem(a); } } } EnzymeFolderItem* RestrctionMapWidget::findEnzymeFolderByName( const QString& enzymeName ) { int count = treeWidget->topLevelItemCount(); for (int i = 0; i < count; i++) { assert(treeWidget->topLevelItem(i)->type() == ENZYME_FOLDER_ITEM_TYPE); EnzymeFolderItem* item = static_cast ( treeWidget->topLevelItem(i) ); if (item->getName() == enzymeName) { return item; } } return NULL; } void RestrctionMapWidget::sl_itemSelectionChanged() { QList selected = treeWidget->selectedItems(); foreach (QTreeWidgetItem* item, selected) { if (item->type() == ENZYME_ITEM_TYPE) { EnzymeItem* enzItem = static_cast (item); AnnotationSelection* sel = ctx->getAnnotationsSelection(); sel->clear(); sel->addToSelection( enzItem->getEnzymeAnnotation() ); } } } void RestrctionMapWidget::sl_onAnnotationsGroupCreated( AnnotationGroup* g ) { if (g->getGroupName() == ANNOTATION_GROUP_ENZYME) { updateTreeWidget(); } } void RestrctionMapWidget::initTreeWidget() { QSet aObjs = ctx->getAnnotationObjects(true); foreach (AnnotationTableObject* obj, aObjs) { QList anns = obj->getAnnotations(); foreach(Annotation* a, anns) { QString aName = a->getAnnotationName(); EnzymeFolderItem* folderItem = findEnzymeFolderByName(aName); if (folderItem) { folderItem->addEnzymeItem(a); } } } } void RestrctionMapWidget::sl_onAnnotationsInGroupRemoved( const QList& anns, AnnotationGroup* group ) { if (group->getGroupName() == ANNOTATION_GROUP_ENZYME) { foreach (Annotation* a, anns) { EnzymeFolderItem* folderItem = findEnzymeFolderByName(a->getAnnotationName()); if (folderItem) { folderItem->removeEnzymeItem(a); } } } group->getGObject()->releaseLocker(); } }//namespace ugene-1.9.8/src/plugins/circular_view/src/CircularViewSplitter.cpp0000644000175000017500000001760711651544321024056 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "CircularViewSplitter.h" #include "CircularView.h" #include "RestrictionMapWidget.h" #include "ExportImageCircularViewDialog.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include namespace U2 { CircularViewSplitter::CircularViewSplitter(AnnotatedDNAView* view) : ADVSplitWidget(view) { tbZoomIn = new QToolButton(this); tbZoomIn->setIcon(QIcon(":/core/images/zoom_in.png")); tbZoomIn->setToolTip(tr("Zoom In")); tbZoomIn->setFixedSize(20,20); tbZoomOut = new QToolButton(this); tbZoomOut->setIcon(QIcon(":/core/images/zoom_out.png")); tbZoomOut->setToolTip(tr("Zoom Out")); tbZoomOut->setFixedSize(20,20); tbFitInView = new QToolButton(this); tbFitInView->setIcon(QIcon(":/core/images/zoom_whole.png")); tbFitInView->setToolTip(tr("Fit To Full View")); tbFitInView->setFixedSize(20,20); tbExport = new QToolButton(this); tbExport->setIcon(QIcon(":/core/images/cam2.png")); tbExport->setToolTip(tr("Save circular view as image")); tbExport->setFixedSize(20,20); tbToggleRestrictionMap = new QToolButton(this); tbToggleRestrictionMap->setIcon(QIcon(":/circular_view/images/side_list.png")); tbToggleRestrictionMap->setToolTip(tr("Show/hide restriction sites map")); tbToggleRestrictionMap->setFixedSize(20,20); tbToggleRestrictionMap->setCheckable(true); tbToggleRestrictionMap->setChecked(true); connect(tbToggleRestrictionMap, SIGNAL(toggled(bool)),SLOT(sl_toggleRestrictionMap(bool))); toolBar = new HBar(this); toolBar->setOrientation(Qt::Vertical); toolBar->addWidget(tbZoomIn); toolBar->addWidget(tbZoomOut); toolBar->addWidget(tbFitInView); toolBar->addWidget(tbExport); toolBar->addWidget(tbToggleRestrictionMap); connect(tbExport, SIGNAL(pressed()), SLOT(sl_export())); splitter = new QSplitter(Qt::Horizontal); QHBoxLayout *layout = new QHBoxLayout; layout->setSpacing(0); layout->setContentsMargins(0,0,3,0); layout->addWidget(toolBar); layout->addWidget(splitter); setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred); setBaseSize(600,600); setAcceptDrops(false); QVBoxLayout* outerLayout = new QVBoxLayout(this); outerLayout->setSpacing(0); outerLayout->setContentsMargins(0,0,0,0); horScroll = new QScrollBar(Qt::Horizontal, this); horScroll->setMinimum(0); horScroll->setMaximum(360); horScroll->setSingleStep(5); connect(horScroll, SIGNAL(valueChanged(int)), SLOT(sl_horSliderMoved(int))); outerLayout->addLayout(layout); outerLayout->insertWidget(-1, horScroll); } void CircularViewSplitter::updateState( const QVariantMap& m) { Q_UNUSED(m); //TODO: } void CircularViewSplitter::saveState( QVariantMap& m ) { Q_UNUSED(m); //TODO: } void CircularViewSplitter::addView(CircularView* view, RestrctionMapWidget* rmapWidget) { tbFitInView->setDisabled(true); tbZoomOut->setDisabled(true); connect(tbZoomIn, SIGNAL(pressed()), view, SLOT(sl_zoomIn())); connect(tbZoomOut, SIGNAL(pressed()), view, SLOT(sl_zoomOut())); connect(tbFitInView, SIGNAL(pressed()), view, SLOT(sl_fitInView())); connect(view, SIGNAL(si_zoomInDisabled(bool)), SLOT(sl_updateZoomInAction(bool))); connect(view, SIGNAL(si_zoomOutDisabled(bool)), SLOT(sl_updateZoomOutAction(bool))); connect(view, SIGNAL(si_fitInViewDisabled(bool)), SLOT(sl_updateFitInViewAction(bool))); circularViewList.append(view); restrictionMapWidgets.append(rmapWidget); splitter->addWidget(view); splitter->addWidget(rmapWidget); splitter->setStretchFactor(splitter->indexOf(view), 10); splitter->setStretchFactor(splitter->indexOf(rmapWidget), 1); connect(view, SIGNAL(si_wheelMoved(int)), SLOT(sl_moveSlider(int))); } void CircularViewSplitter::sl_moveSlider(int delta) { delta*=-1; int oldPos = horScroll->sliderPosition(); int step = qMin(QApplication::wheelScrollLines() * horScroll->singleStep(), horScroll->pageStep()); int offset = delta/120 * step; if (qAbs(offset)<1) { return; } int newPos = oldPos + offset; horScroll->setSliderPosition(newPos); } void CircularViewSplitter::removeView(CircularView* view, RestrctionMapWidget* rmapWidget) { circularViewList.removeAll(view); restrictionMapWidgets.removeAll(rmapWidget); } bool CircularViewSplitter::isEmpty() { return circularViewList.isEmpty(); } bool noValidExtension(const QString& url) { QFileInfo fi(url); if (fi.suffix().isEmpty()) { return true; } QStringList validExtensions; validExtensions << "png" << "bmp" << "jpg" << "jpeg" << "ppm" << "xbm" << "xpm" << "svg" << "pdf" << "ps"; if (!validExtensions.contains(fi.suffix())) { return true; } return false; } void CircularViewSplitter::sl_export() { CircularView* cv = circularViewList.last(); ExportImageCVDialog dialog(cv); dialog.exec(); tbExport->setDown(false); } void CircularViewSplitter::sl_horSliderMoved(int newVal) { foreach(CircularView* cv, circularViewList) { cv->setAngle(newVal); } } void CircularViewSplitter::adaptSize() { QWidget* widget = parentWidget(); Q_ASSERT(widget != NULL); QSplitter* parentSplitter = qobject_cast (widget); int index = parentSplitter->indexOf(this); QList sizes = parentSplitter->sizes(); int splitterSize = 0; int psH = parentSplitter->height(); int psW = parentSplitter->width(); if (parentSplitter->orientation() == Qt::Horizontal) { splitterSize = psH; } else { splitterSize = psW; } if (!splitterSize) { return; } int midSize = splitterSize; if (splitterSize > CircularViewRenderArea::MIDDLE_ELLIPSE_SIZE) { sizes[index] = CircularViewRenderArea::MIDDLE_ELLIPSE_SIZE; midSize -= CircularViewRenderArea::MIDDLE_ELLIPSE_SIZE; if (sizes.count() > 1) { midSize /= (sizes.count() - 1); } } else { midSize /= sizes.count(); sizes[index] = midSize; } for (int i=0; isetSizes(sizes); } void CircularViewSplitter::sl_updateZoomInAction( bool disabled) { tbZoomIn->setDisabled(disabled); } void CircularViewSplitter::sl_updateZoomOutAction( bool disabled) { tbZoomOut->setDisabled(disabled); } void CircularViewSplitter::sl_updateFitInViewAction( bool disabled) { tbFitInView->setDisabled(disabled); } void CircularViewSplitter::sl_toggleRestrictionMap( bool toggle) { foreach (QWidget* w, restrictionMapWidgets) { w->setVisible(toggle); } } } //namespace U2 ugene-1.9.8/src/plugins/circular_view/src/CircularItems.h0000644000175000017500000001103311651544321022126 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _CIRCULAR_ITEMS_H_ #define _CIRCULAR_ITEMS_H_ #include #include namespace U2 { class Annotation; class AnnotationSettings; class CircularAnnotationItem; class CircularViewRenderArea; class CircularAnnotationLabel; class CircurlarAnnotationRegionItem; /************************************************************************/ /* CircularAnnotationItem */ /************************************************************************/ class CircularAnnotationItem : public QGraphicsItem { friend class CircurlarAnnotationRegionItem; friend class CircularAnnotationLabel; public: CircularAnnotationItem(Annotation* ann, CircurlarAnnotationRegionItem* region, CircularViewRenderArea* _ra); CircularAnnotationItem(Annotation* ann, QList& regions, CircularViewRenderArea* _ra); ~CircularAnnotationItem(); virtual void paint(QPainter *p,const QStyleOptionGraphicsItem *item,QWidget *widget); Annotation* getAnnotation() const; virtual QRectF boundingRect() const; virtual bool contains(const QPointF &point); int containsRegion(const QPointF &point); void setSelected(bool isSelected); const QList& getRegions(); protected: bool isSelected; QColor color; Annotation *annotation; QList regions; QRectF _boundingRect; CircularViewRenderArea* ra; }; /************************************************************************/ /* CircurlarAnnotationRegionItem */ /************************************************************************/ class CircurlarAnnotationRegionItem : public QGraphicsPathItem{ friend class CircularAnnotationItem; public: CircurlarAnnotationRegionItem(const QPainterPath& path, bool isShort, int number ); void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget /* = 0 */); CircularAnnotationLabel* getLabel() const; void setLabel(CircularAnnotationLabel* label); protected: CircularAnnotationItem *parent; CircularAnnotationLabel *label; int number; bool isShort; }; /************************************************************************/ /* CircularAnnotationLabel */ /************************************************************************/ class CircularAnnotationLabel : public QGraphicsItem { public: CircularAnnotationLabel(Annotation* ann, int _region, int sequenceLength, const QFont& font, CircularViewRenderArea* renderArea ); virtual void paint(QPainter *p,const QStyleOptionGraphicsItem *item,QWidget *widget); Annotation* getAnnotation() const; virtual QRectF boundingRect() const; virtual bool contains(const QPointF &point); int getRegion() const; void setLabelPosition(); static void prepareLabels(QList& labelItems); bool operator<(const CircularAnnotationLabel& a); private: int findClosestPoint(const QPoint& targetPoint, const QVector& rects, QVector indexes); void getVacantPositions(const QVector& rects, QVector& result); void getVacantInnerPositions(const QVector& rects, QVector& result); void getConnectionPoint(); Annotation* annotation; float annotationAngle; QFont labelFont; QRectF midRect; QPointF midRegionPoint; int region; qreal startA; qreal endA; qreal spanA; QPoint labelPos; QPoint connectionPoint; CircularViewRenderArea* ra; bool hasPosition; QString labelText; bool inner; int seqLen; }; } // namespace U2 #endif // _CIRCULAR_ITEMS_H_ ugene-1.9.8/src/plugins/circular_view/src/CircularViewPlugin.h0000644000175000017500000000406111651544321023141 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_CIRCULAR_VIEW_PLUGIN_H_ #define _U2_CIRCULAR_VIEW_PLUGIN_H_ #include #include #include #include #include #include namespace U2 { class CircularViewSplitter; class CircularView; class RestrctionMapWidget; class CircularViewPlugin : public Plugin { Q_OBJECT public: CircularViewPlugin(); ~CircularViewPlugin(); private: GObjectViewWindowContext* viewCtx; }; class CircularViewContext: public GObjectViewWindowContext { Q_OBJECT public: CircularViewContext(QObject* p); protected slots: void sl_showCircular(); void sl_sequenceWidgetAdded(ADVSequenceWidget*); protected: virtual void initViewContext(GObjectView* view); void buildMenu(GObjectView* v, QMenu* m); CircularViewSplitter* getView(GObjectView* view, bool create); void removeCircularView(GObjectView* view); private: GObjectViewAction* exportAction; }; class CircularViewAction : public ADVSequenceWidgetAction { Q_OBJECT public: CircularViewAction(); ~CircularViewAction(); CircularView* view; RestrctionMapWidget* rmapWidget; }; } //namespace #endif ugene-1.9.8/src/plugins/circular_view/src/CircularViewPlugin.cpp0000644000175000017500000001577111651544321023506 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "CircularViewPlugin.h" #include "CircularView.h" #include "CircularViewSplitter.h" #include "RestrictionMapWidget.h" #include #include #include #include #include #include #include #include #include #include #include #include #include namespace U2 { extern "C" Q_DECL_EXPORT Plugin* U2_PLUGIN_INIT_FUNC() { if (AppContext::getMainWindow()) { CircularViewPlugin* plug = new CircularViewPlugin(); return plug; } return NULL; } CircularViewPlugin::CircularViewPlugin() : Plugin(tr("CircularView"), tr("Enables drawing of DNA sequences using circular representation")) { viewCtx = new CircularViewContext(this); viewCtx->init(); } CircularViewPlugin::~CircularViewPlugin() { } #define CIRCULAR_ACTION_NAME "CIRCULAR_ACTION" #define CIRCULAR_VIEW_NAME "CIRCULAR_VIEW" CircularViewContext::CircularViewContext(QObject* p) : GObjectViewWindowContext(p, ANNOTATED_DNA_VIEW_FACTORY_ID), exportAction(NULL) { } void CircularViewContext::initViewContext(GObjectView* v) { exportAction = new GObjectViewAction(this, v, tr("Save circular view as image")); exportAction->setIcon(QIcon(":/core/images/cam2.png")); AnnotatedDNAView* av = qobject_cast(v); foreach(ADVSequenceWidget* w, av->getSequenceWidgets()) { sl_sequenceWidgetAdded(w); } connect(av, SIGNAL(si_sequenceWidgetAdded(ADVSequenceWidget*)), SLOT(sl_sequenceWidgetAdded(ADVSequenceWidget*))); } #define MIN_LENGTH_TO_AUTO_SHOW (1000*1000) void CircularViewContext::sl_sequenceWidgetAdded(ADVSequenceWidget* w) { ADVSingleSequenceWidget* sw = qobject_cast(w); if (sw == NULL || sw->getSequenceObject() == NULL || !sw->getSequenceObject()->getAlphabet()->isNucleic()) { return; } CircularViewAction* action = new CircularViewAction(); action->setIcon(QIcon(":circular_view/images/circular.png")); action->setCheckable(true); action->setChecked(false); action->addToMenu = true; action->addToBar = true; connect(action, SIGNAL(triggered()), SLOT(sl_showCircular())); sw->addADVSequenceWidgetAction(action); const DNASequence& dna = sw->getSequenceContext()->getSequenceObject()->getDNASequence(); if (dna.length() < MIN_LENGTH_TO_AUTO_SHOW) { if (dna.circular) { action->trigger(); } } } CircularViewSplitter* CircularViewContext::getView(GObjectView* view, bool create) { CircularViewSplitter* circularView = NULL; QList resources = viewResources.value(view); foreach(QObject* r, resources) { circularView = qobject_cast(r); if (circularView!=NULL) { return circularView; } } if (create) { AnnotatedDNAView* av = qobject_cast(view); circularView = new CircularViewSplitter(av); resources.append(circularView); viewResources.insert(view, resources); if (!exportAction) { initViewContext(view); } connect(exportAction, SIGNAL(triggered()), circularView, SLOT(sl_export())); } return circularView; } ////////////////////////////////////////////////////////////////////////// void CircularViewContext::buildMenu(U2::GObjectView *v, QMenu *m) { bool empty = true; QList resources = viewResources.value(v); foreach(QObject* r, resources) { CircularViewSplitter* circularView = qobject_cast(r); if (circularView!=NULL) { if(!circularView->isEmpty()) { empty = false; } break; } } if(empty) { return; } QMenu* exportMenu = GUIUtils::findSubMenu(m, ADV_MENU_EXPORT); assert(exportMenu!=NULL); exportMenu->addAction(exportAction); } ////////////////////////////////////////////////////////////////////////// void CircularViewContext::removeCircularView(GObjectView* view) { QList resources = viewResources.value(view); foreach(QObject* r, resources) { CircularViewSplitter* circularView = qobject_cast(r); if (circularView!=NULL) { assert(circularView->isEmpty()); AnnotatedDNAView* av = qobject_cast(view); av->unregisterSplitWidget(circularView); resources.removeOne(circularView); viewResources.insert(view, resources); delete circularView; } } } void CircularViewContext::sl_showCircular() { CircularViewAction* a = qobject_cast(sender()); ADVSingleSequenceWidget* sw = qobject_cast(a->seqWidget); assert(a!=NULL); if (a->isChecked()) { a->setText(tr("Remove circular view")); assert(a->view == NULL); CircularViewSplitter* splitter = getView(sw->getAnnotatedDNAView(), true); a->view = new CircularView(sw, sw->getSequenceContext()); a->rmapWidget=new RestrctionMapWidget(sw->getSequenceContext(),splitter); splitter->addView(a->view,a->rmapWidget); sw->getAnnotatedDNAView()->insertWidgetIntoSplitter(splitter); splitter->adaptSize(); } else { a->setText(tr("Show circular view")); assert(a->view!=NULL); CircularViewSplitter* splitter = getView(sw->getAnnotatedDNAView(), false); if(splitter != NULL) { splitter->removeView(a->view,a->rmapWidget); delete a->view; delete a->rmapWidget; if(splitter->isEmpty()) { removeCircularView(sw->getAnnotatedDNAView()); } } a->view = NULL; } } CircularViewAction::CircularViewAction() : ADVSequenceWidgetAction(CIRCULAR_ACTION_NAME, tr("Show circular view")), view(NULL) { } CircularViewAction::~CircularViewAction() { /*if (view!=NULL) { delete view; }*/ } }//namespace ugene-1.9.8/src/plugins/circular_view/src/CircularView.cpp0000644000175000017500000010757211651544321022330 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "CircularView.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "CircularItems.h" #include namespace U2 { const int CircularView::CV_REGION_ITEM_WIDTH = 20; const int CircularView::MIN_OUTER_SIZE = 100; const int CircularView::graduation = 16; CircularView::CircularView(QWidget* p, ADVSequenceObjectContext* ctx) : GSequenceLineViewAnnotated(p, ctx), clockwise(true), holdSelection(false) { connect (ctx->getAnnotatedDNAView(), SIGNAL(si_sequenceWidgetRemoved(ADVSequenceWidget*)), SLOT(sl_sequenceWidgetRemoved(ADVSequenceWidget*))); QSet anns = ctx->getAnnotationObjects(true); foreach(AnnotationTableObject* obj, anns ) { registerAnnotations(obj->getAnnotations()); } renderArea = new CircularViewRenderArea(this); ra = qobject_cast(renderArea); setMouseTracking(true); connect(ctx->getSequenceGObject(), SIGNAL(si_sequenceChanged()), this, SLOT(sl_sequenceChanged())); connect(ctx->getSequenceGObject(), SIGNAL(si_nameChanged(const QString&)), this, SLOT(sl_onSequenceObjectRenamed(const QString&))); pack(); //mark sequence as circular ctx->getSequenceObject()->setCircular(true); } void CircularView::pack() { updateMinHeight(); layout = new QVBoxLayout(); layout->setContentsMargins(0,0,0,0); layout->addWidget(renderArea); setLayout(layout); setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Maximum); } void CircularView::updateMinHeight() { int minH = (ra->regionY.count() - 1)*ra->ellipseDelta + MIN_OUTER_SIZE; setMinimumHeight(minH); } void CircularView::sl_sequenceWidgetRemoved(ADVSequenceWidget* w) { foreach (ADVSequenceObjectContext *wctx, w->getSequenceContexts()) { if (ctx == wctx) { close(); } } } void CircularView::mousePressEvent(QMouseEvent * e) { GSequenceLineViewAnnotated::mousePressEvent(e); QPoint p = toRenderAreaPoint(e->pos()); int offset = ra->getCenterY(); QPoint point(p.x() - width()/2 , p.y() - offset); qreal arcsin = coordToAngle(point); lastPressPos = 180 * graduation * arcsin / PI; lastPressPos-=ra->rotationDegree*graduation; if(lastPressPos<0) { lastPressPos+=360*graduation; } lastMovePos = lastPressPos; lastMouseY = point.y(); currectSelectionLen = 0; holdSelection = false; QWidget::mousePressEvent(e); } CircularView::Direction CircularView::getDirection(float a, float b) const { if (a == b) { return UNKNOWN; } a/=graduation; b/=graduation; bool cl = ( (a-b>=180) || ((b-a <=180) && (b-a >=0)) ); if (cl) { return CW; } else { return CCW; } } void CircularView::mouseMoveEvent( QMouseEvent * e ) { QWidget::mouseMoveEvent(e); QPoint areaPoint = toRenderAreaPoint(e->pos()); QPoint point(areaPoint.x() - width()/2 , areaPoint.y() - ra->getCenterY()); qreal arcsin = coordToAngle(point); ra->mouseAngle = arcsin; if (e->buttons() & Qt::LeftButton) { float a = 180 * graduation * arcsin / PI; a-=ra->rotationDegree*graduation; if(a<0) { a+=360*graduation; } Direction pressMove = getDirection(lastPressPos, lastMovePos); Direction moveA = getDirection(lastMovePos, a); float totalLen = qAbs(lastPressPos-lastMovePos) + qAbs(lastMovePos-a); totalLen/=graduation; if ((totalLen<10) && !holdSelection) { if ((pressMove!=CW) && (moveA!=CW)) { clockwise = false; } else if ((pressMove != CCW) && (moveA != CCW)) { clockwise = true; } if (totalLen < 1) { clockwise = lastPressPos < a; } holdSelection = true; } if (!clockwise) { float tmp = a; a = lastPressPos; lastPressPos = tmp; } // compute selection int seqLen = ctx->getSequenceLen(); int selStart = lastPressPos / (360.0*graduation) * seqLen + 0.5f; int selEnd = a / (360.0*graduation) * seqLen + 0.5f; int selLen = selEnd-selStart; bool twoParts = false; if (selLen < 0) { // 'a' and 'lastPressPos' are swapped so it should be positive selLen = selEnd + seqLen - selStart; Q_ASSERT(selLen>=0); if (selEnd) { // [0, selEnd] twoParts = true; } } if (selLen > seqLen-selStart) { selLen = seqLen-selStart; } if (!clockwise) { float tmp = lastPressPos; lastPressPos = a; a = tmp; } lastMovePos = a; lastMouseY = point.y(); if (twoParts) { setSelection(U2Region(selStart, seqLen-selStart)); addSelection(U2Region(0, selEnd)); } else { setSelection(U2Region(selStart, selLen)); } } renderArea->update(); } void CircularView::mouseReleaseEvent(QMouseEvent* e) { GSequenceLineViewAnnotated::mouseReleaseEvent(e); } void CircularView::setAngle(int angle) { assert(angle>=0 && angle<=360); ra->rotationDegree=angle; addUpdateFlags(GSLV_UF_NeedCompleteRedraw); renderArea->update(); } void CircularView::sl_onAnnotationSelectionChanged(AnnotationSelection* selection, const QList& added, const QList& removed) { foreach (Annotation* a, added) { bool splitted = U2AnnotationUtils::isSplitted(a->getLocation(), ctx->getSequenceObject()->getSequenceRange()); int locationIdx = selection->getAnnotationData(a)->locationIdx; if (splitted && locationIdx != -1) { // set locationIdx = -1 to make sure whole annotation region is selected selection->addToSelection(a); return; } } GSequenceLineViewAnnotated::sl_onAnnotationSelectionChanged(selection, added, removed); renderArea->update(); } void CircularView::sl_onDNASelectionChanged( LRegionsSelection* thiz, const QVector& added, const QVector& removed ) { GSequenceLineViewAnnotated::sl_onDNASelectionChanged(thiz, added, removed); renderArea->update(); } QList CircularView::selectAnnotationByCoord( const QPoint& coord ) const { QList res; CircularViewRenderArea* renderArea = qobject_cast(this->renderArea); QPoint cp(coord - QPoint(width()/2, renderArea->getCenterY())); foreach(CircularAnnotationItem* item, renderArea->circItems) { int region = item->containsRegion(cp); if(region != -1) { res.append(AnnotationSelectionData(item->getAnnotation(), region)); return res; } } foreach(CircularAnnotationItem* item, renderArea->circItems) { foreach(CircurlarAnnotationRegionItem* r, item->getRegions()) { CircularAnnotationLabel* lbl = r->getLabel(); if(lbl->isVisible() && lbl->contains(cp)) { res.append(AnnotationSelectionData(item->getAnnotation(), item->getRegions().indexOf(r))); return res; } } } return res; } QSize CircularView::sizeHint() const { return ra->size(); } const QMap& CircularView::getCircularItems() const { return ra->circItems; } const QList& CircularView::getLabelList() const { return ra->labelList; } void CircularView::wheelEvent(QWheelEvent* we) { if (we->modifiers()&Qt::ControlModifier) { if (we->delta()>0) { sl_zoomIn(); } else { sl_zoomOut(); } } else { emit si_wheelMoved(we->delta()); } QWidget::wheelEvent(we); } void CircularView::resizeEvent( QResizeEvent* e ) { if (ra->fitsInView) { sl_fitInView(); } QWidget::resizeEvent(e); } #define VIEW_MARGIN 10 void CircularView::sl_fitInView() { int yLvl = ra->regionY.count() - 1; ra->outerEllipseSize = qMin(height(), width()) - ra->ellipseDelta*yLvl - VIEW_MARGIN; adaptSizes(); updateZoomActions(); } #define ZOOM_SCALE 1.5 void CircularView::sl_zoomIn() { if (ra->outerEllipseSize / width() > 10) { return; } ra->outerEllipseSize*=ZOOM_SCALE; adaptSizes(); updateZoomActions(); } void CircularView::sl_zoomOut() { if (ra->fitsInView) { return; } ra->outerEllipseSize/=ZOOM_SCALE; adaptSizes(); updateZoomActions(); } void CircularView::sl_onSequenceObjectRenamed(const QString&) { update(); } void CircularView::updateZoomActions() { if (ra->outerEllipseSize*ZOOM_SCALE / width() > 10) { emit si_zoomInDisabled(true); } else { emit si_zoomInDisabled(false); } int viewSize = qMin(height(), width()) - VIEW_MARGIN; int size = ra->outerEllipseSize + (ra->regionY.count()-1)*ra->ellipseDelta; if (size <= viewSize) { emit si_fitInViewDisabled(true); emit si_zoomOutDisabled(true); } else { emit si_fitInViewDisabled(false); emit si_zoomOutDisabled(false); } } void CircularView::adaptSizes() { ra->innerEllipseSize=ra->outerEllipseSize-CV_REGION_ITEM_WIDTH; ra->rulerEllipseSize=ra->outerEllipseSize-CV_REGION_ITEM_WIDTH; ra->middleEllipseSize = (ra->outerEllipseSize + ra->innerEllipseSize)/2; updateMinHeight(); addUpdateFlags(GSLV_UF_NeedCompleteRedraw); ra->update(); } qreal CircularView::coordToAngle(const QPoint point) { float norm = sqrt((double)point.x()*point.x() + point.y()*point.y()); float arcsin = 0.0; if (abs(norm) > 1.0) { arcsin = asin(abs((double)point.y())/norm); } if(point.x() < 0) { arcsin = PI - arcsin; } if(point.y() < 0) { arcsin = 2*PI - arcsin; } return arcsin; } void CircularView::paint( QPainter& p ) { ra->paintContent(p); } /************************************************************************/ /* CircularViewRenderArea */ /************************************************************************/ const int CircularViewRenderArea::OUTER_ELLIPSE_SIZE = 512; const int CircularViewRenderArea::ELLIPSE_DELTA = 22; const int CircularViewRenderArea::INNER_ELLIPSE_SIZE = OUTER_ELLIPSE_SIZE - CircularView::CV_REGION_ITEM_WIDTH; const int CircularViewRenderArea::RULER_ELLIPSE_SIZE = INNER_ELLIPSE_SIZE - CircularView::CV_REGION_ITEM_WIDTH; const int CircularViewRenderArea::MIDDLE_ELLIPSE_SIZE = (INNER_ELLIPSE_SIZE + OUTER_ELLIPSE_SIZE) / 2; const int CircularViewRenderArea::ARROW_LENGTH = 32; const int CircularViewRenderArea::ARROW_HEIGHT_DELTA = 4; const int CircularViewRenderArea::MAX_DISPLAYING_LABELS = 20; const int CircularViewRenderArea::MARKER_LEN = 30; const int CircularViewRenderArea::ARR_LEN = 4; const int CircularViewRenderArea::ARR_WIDTH = 10; const int CircularViewRenderArea::NOTCH_SIZE = 5; CircularViewRenderArea::CircularViewRenderArea(CircularView* d) : GSequenceLineViewAnnotatedRenderArea(d, true), outerEllipseSize(OUTER_ELLIPSE_SIZE), ellipseDelta(ELLIPSE_DELTA), innerEllipseSize(INNER_ELLIPSE_SIZE), rulerEllipseSize(RULER_ELLIPSE_SIZE), middleEllipseSize(MIDDLE_ELLIPSE_SIZE), arrowLength(ARROW_LENGTH), arrowHeightDelta(ARROW_HEIGHT_DELTA), maxDisplayingLabels(MAX_DISPLAYING_LABELS), fitsInView(true), circularView(d), rotationDegree(0), mouseAngle(0), oldYlevel(0) { setMouseTracking(true); ADVSequenceObjectContext* ctx = view->getSequenceContext(); //build annotation items to get number of region levels for proper resize AnnotationSettingsRegistry* asr = AppContext::getAnnotationsSettingsRegistry(); QSet anns = ctx->getAnnotationObjects(true); foreach(AnnotationTableObject* ao, anns) { foreach(Annotation* a, ao->getAnnotations()) { AnnotationSettings* as = asr->getAnnotationSettings(a->getAnnotationName()); buildAnnotationItem(DrawAnnotationPass_DrawFill, a, false, as); } } } void CircularViewRenderArea::adaptNumberOfLabels(int h) { QFont font; QFontMetrics fm(font); int lblHeight = fm.height(); maxDisplayingLabels = int(h/lblHeight); } void CircularViewRenderArea::paintContent( QPainter& p ) { int viewSize = qMin(circularView->height(), circularView->width()); uiLog.details(tr("circular view size %1 %2").arg(circularView->width()).arg(circularView->height())); verticalOffset = parentWidget()->height()/2; if (outerEllipseSize + (regionY.count()-1)*ellipseDelta + VIEW_MARGIN > viewSize) { verticalOffset += rulerEllipseSize/2; } p.fillRect(0, 0, width(), height(), Qt::white); p.save(); p.translate(parentWidget()->width()/2, verticalOffset); drawRuler(p); drawAnnotations(p); drawSequenceName(p); drawAnnotationsSelection(p); drawSequenceSelection(p); drawMarker(p); p.restore(); } void CircularViewRenderArea::drawAll(QPaintDevice* pd) { QPainter p(pd); p.setRenderHint(QPainter::Antialiasing); GSLV_UpdateFlags uf = view->getUpdateFlags(); bool completeRedraw = uf.testFlag(GSLV_UF_NeedCompleteRedraw) || uf.testFlag(GSLV_UF_ViewResized) || uf.testFlag(GSLV_UF_AnnotationsChanged); int viewSize = qMin(circularView->height(), circularView->width()); verticalOffset = parentWidget()->height()/2; if (outerEllipseSize + (regionY.count()-1)*ellipseDelta + VIEW_MARGIN > viewSize) { verticalOffset += rulerEllipseSize/2; fitsInView = false; } else { fitsInView = true; } if (completeRedraw) { QPainter pCached(cachedView); pCached.setRenderHint(QPainter::Antialiasing); pCached.fillRect(0, 0, pd->width(), pd->height(), Qt::white); pCached.translate(parentWidget()->width()/2, verticalOffset); pCached.setPen(Qt::black); drawRuler(pCached); drawAnnotations(pCached); pCached.end(); } p.drawPixmap(0, 0, *cachedView); p.translate(parentWidget()->width()/2, verticalOffset); drawSequenceName(p); drawAnnotationsSelection(p); drawSequenceSelection(p); drawMarker(p); if (oldYlevel!=regionY.count()) { oldYlevel = regionY.count(); if (verticalOffset<=parentWidget()->height()/2) { circularView->sl_fitInView(); paintEvent(new QPaintEvent(rect())); } } } void CircularViewRenderArea::drawAnnotationsSelection(QPainter& p) { ADVSequenceObjectContext* ctx = view->getSequenceContext(); if(ctx->getAnnotationsSelection()->getSelection().isEmpty()) { return; } foreach(CircularAnnotationItem* item, circItems.values()) { item->setSelected(false); } foreach(const AnnotationSelectionData& asd, ctx->getAnnotationsSelection()->getSelection()) { AnnotationTableObject* o = asd.annotation->getGObject(); if (ctx->getAnnotationObjects(true).contains(o)) { if(circItems.contains(asd.annotation)) { CircularAnnotationItem* item = circItems[asd.annotation]; item->setSelected(true); item->paint(&p, NULL, this); foreach(const CircurlarAnnotationRegionItem* r, item->getRegions()) { CircularAnnotationLabel* lbl = r->getLabel(); if(lbl->isVisible()) { lbl->paint(&p, NULL, this); } } } } } } #define RULER_PAD 40 void CircularViewRenderArea::drawSequenceName(QPainter& p) { QPen boldPen(Qt::black); boldPen.setWidth(3); ADVSequenceObjectContext* ctx = view->getSequenceContext(); assert( ctx->getSequenceGObject() != NULL ); //QString docName = ctx->getSequenceGObject()->getDocument()->getName(); QString docName = ctx->getSequenceGObject()->getGObjectName(); QString seqLen = QString::number(ctx->getSequenceLen()) + " bp"; int docNameFullLength = docName.length(); QFont font = p.font(); QFontMetrics fm(font); int cw = fm.width('O'); int symbolsAlowed = (rulerEllipseSize - RULER_PAD)/cw; if(symbolsAlowedheight(); namePt = QPointF(0, -delta-nameBound.height()-lenBound.height()); lenPt = namePt + QPointF(0, lenBound.height()); } else { namePt = QPointF(0,0); lenPt = QPointF(0, nameBound.height()); } nameBound.moveCenter(namePt); p.drawText(nameBound, docName); lenBound.moveCenter(lenPt); p.drawText(lenBound, seqLen); } void CircularViewRenderArea::drawSequenceSelection( QPainter& p ) { ADVSequenceObjectContext* ctx = view->getSequenceContext(); int seqLen = ctx->getSequenceLen(); const QVector& selection = view->getSequenceContext()->getSequenceSelection()->getSelectedRegions(); QList paths; foreach(const U2Region& r, selection) { QPainterPath* path = new QPainterPath(); int yLevel = regionY.count() - 1; QRect outerRect(-outerEllipseSize/2 - yLevel * ellipseDelta/2 - ARROW_HEIGHT_DELTA, -outerEllipseSize/2 - yLevel * ellipseDelta/2 - ARROW_HEIGHT_DELTA, outerEllipseSize + yLevel * ellipseDelta + ARROW_HEIGHT_DELTA*2, outerEllipseSize + yLevel * ellipseDelta + ARROW_HEIGHT_DELTA*2); QRectF innerRect(-rulerEllipseSize/2 + NOTCH_SIZE, -rulerEllipseSize/2 + NOTCH_SIZE, rulerEllipseSize - 2*NOTCH_SIZE, rulerEllipseSize-2*NOTCH_SIZE); float startAngle = r.startPos / (float)seqLen * 360 + rotationDegree; float spanAngle = r.length / (float)seqLen * 360; path->moveTo(outerRect.width()/2 * cos(-startAngle / 180.0 * PI), -outerRect.width()/2 * sin(-startAngle / 180.0 * PI)); path->arcTo(outerRect, -startAngle, -spanAngle); path->arcTo(innerRect, -startAngle-spanAngle, spanAngle); path->closeSubpath(); paths.append(path); } p.save(); QPen selectionPen(QColor("#007DE3")); selectionPen.setStyle(Qt::DashLine); selectionPen.setWidth(1); p.setPen(selectionPen); foreach(QPainterPath* path, paths) { p.drawPath(*path); } p.restore(); } void normalizeAngle(qreal& a) { while(a>360) { a-=360; } while(a<0) { a+=360; } } void normalizeAngleRad(qreal& a) { while(a>2*PI) { a-=2*PI; } while(a<0) { a+=2*PI; } } void CircularViewRenderArea::drawRulerNotches(QPainter& p, int start, int span, int seqLen) { int notchSize = 5; QFont f; QFontMetrics fm(f); int cw = fm.width('0'); int N = QString::number(start+span).length()*cw*3/2.0 + 0.5f; int rulerLen = span / (float)seqLen * PI * rulerEllipseSize; int chunk = GraphUtils::findChunk(rulerLen, span, N); start-=start%chunk; float halfChar = 180 / (float)seqLen; for (int currentNotch=start+chunk; currentNotch < start + span + chunk; currentNotch+=chunk) { if (currentNotch > seqLen) { currentNotch = seqLen; } qreal d = currentNotch / (float)seqLen * 360 + rotationDegree - halfChar; d*=PI/180.0; d = 2*PI - d; QPoint point1 ( rulerEllipseSize * cos(d) / 2.0 + 0.5f, - rulerEllipseSize * sin(d) / 2.0 - 0.5f); point1-=QPoint(0,0); QPoint point2 = point1 - QPoint(notchSize*cos(d), -notchSize*sin(d)); QPoint point3 = point2 - QPoint(3*cos(d), 0); if (currentNotch == 0) { } QString label = FormatUtils::formatNumber(currentNotch); QRect bounding = p.boundingRect(0,0,1000,1000, Qt::AlignLeft, label); normalizeAngleRad(d); if(d>PI/4 && d<=PI/2 + PI/4) { QPoint dP((float)bounding.width() / 2 * (1-cos(d)), 0); bounding.moveTopRight(point3 + dP); } else if(d>PI/2 + PI/4 && d<=PI + PI/4) { QPoint dP(0, (float)bounding.height() / 2 * (1-sin(d))); bounding.moveTopLeft(point3 - dP); } else if(d>PI + PI/4 && d<=3*PI/2 + PI/4) { QPoint dP((float)bounding.width() / 2 * (1-cos(d)), 0); bounding.moveBottomRight(point3 + dP); } else { QPoint dP(0, (float)bounding.height() / 2 * (1-sin(d))); bounding.moveTopRight(point3 - dP); } p.drawLine(point1,point2); p.drawText(bounding, label); } } qreal CircularViewRenderArea::getVisibleAngle() const { int w = parentWidget()->width(); int h = parentWidget()->height(); int y = verticalOffset - h; float x = rulerEllipseSize/2.0; assert(y>0); assert(x>y); int rulerChord = 2*sqrt(double(x*x - y*y)); rulerChord = qMin(rulerChord, w); assert(qAbs(rulerChord) CircularViewRenderArea::getVisibleRange() const { ADVSequenceObjectContext* ctx = view->getSequenceContext(); int seqLen = ctx->getSequenceObject()->getSequenceLen(); if (verticalOffset <= parentWidget()->height()) { return qMakePair(0, seqLen); } qreal spanAngle = getVisibleAngle(); qreal startAngle = 3*PI/2.0 - spanAngle; qreal temp = startAngle - rotationDegree*PI/180.0; normalizeAngleRad(temp); int start = seqLen*temp/(2.0*PI) + 0.5f; int span = seqLen*spanAngle/(double(PI)) + 0.5f; return qMakePair(start, span); } void CircularViewRenderArea::drawRuler( QPainter& p ) { p.save(); ADVSequenceObjectContext* ctx = view->getSequenceContext(); const U2Region& range = ctx->getSequenceObject()->getSequenceRange(); int seqLen = range.length; normalizeAngle(rotationDegree); if (fitsInView) { drawRulerNotches(p, range.startPos, seqLen, seqLen); } else { const QPair& loc = getVisibleRange(); int start = loc.first; int span = loc.second; if (start==seqLen) { drawRulerNotches(p, 0, span, seqLen); } else if (start + span > seqLen) { int span1 = seqLen - start; int span2 = start + span - seqLen; assert(span1); assert(span2); drawRulerNotches(p, start, span1, seqLen); drawRulerNotches(p, 0, span2, seqLen); } else { drawRulerNotches(p, start, span, seqLen); } } QPen boldPen(Qt::black); boldPen.setWidth(3); p.setPen(boldPen); QRectF rulerRect(-rulerEllipseSize/2, -rulerEllipseSize/2, rulerEllipseSize, rulerEllipseSize); rulerRect.moveCenter(QPointF(0,0)); p.drawEllipse(rulerRect); p.restore(); } void CircularViewRenderArea::drawAnnotations(QPainter& p) { ADVSequenceObjectContext* ctx = view->getSequenceContext(); foreach(CircularAnnotationItem* item, circItems) { delete item; } circItems.clear(); labelList.clear(); annotationYLevel.clear(); regionY.clear(); circItems.clear(); AnnotationSettingsRegistry* asr = AppContext::getAnnotationsSettingsRegistry(); //for(QSet::const_iterator i = ctx->getAnnotationObjects().begin(); i != ctx->getAnnotationGObjects().constEnd(); i++) { //TODO: there need const order of annotation tables QSet anns = ctx->getAnnotationObjects(true); foreach(AnnotationTableObject* ao, anns) { foreach(Annotation* a, ao->getAnnotations()) { AnnotationSettings* as = asr->getAnnotationSettings(a->getAnnotationName()); buildAnnotationItem(DrawAnnotationPass_DrawFill, a, false, as); buildAnnotationLabel(p.font(), a, as); } } CircularAnnotationLabel::prepareLabels(labelList); evaluateLabelPositions(); foreach(CircularAnnotationItem* item, circItems) { item->paint(&p, NULL, this); } foreach(CircularAnnotationLabel* label, labelList) { label->setLabelPosition(); label->paint(&p, NULL, this); } } #define REGION_MIN_LEN 3 void CircularViewRenderArea::buildAnnotationItem(DrawAnnotationPass pass, Annotation* a, bool selected /* = false */, const AnnotationSettings* as /* = NULL */) { if (!as->visible && (pass == DrawAnnotationPass_DrawFill || !selected)) { return; } ADVSequenceObjectContext* ctx = view->getSequenceContext(); int seqLen = ctx->getSequenceLen(); const QVector& location = a->getRegions(); U2Region generalLocation(location.first().startPos, location.last().startPos - location.first().startPos + location.last().length); int yLevel = 0; bool yFind = false; for(;yLevel& rY = regionY[yLevel]; rY.append(generalLocation); yFind = true; break; } } if(!yFind) { QVector newLevel; newLevel.append(generalLocation); regionY.append(newLevel); } annotationYLevel[a] = yLevel; QList regions; bool splitted = U2AnnotationUtils::isSplitted(a->getLocation(), ctx->getSequenceObject()->getSequenceRange()); bool splittedItemIsReady = false; foreach(const U2Region& r, location) { int totalLen = 0; if (splitted) { if (!splittedItemIsReady) { totalLen = r.length + location[1].length; splittedItemIsReady = true; } else { break; } } else { totalLen = r.length; } float startAngle = (float)r.startPos / (float)seqLen * 360; float spanAngle = (float)totalLen / (float)seqLen * 360; //cut annotation border if dna is linear if(!circularView->isCircularTopology()) { spanAngle = qMin(spanAngle, (float)(360-startAngle)); } startAngle+=rotationDegree; QPainterPath path; QRect outerRect(-outerEllipseSize/2 - yLevel * ellipseDelta/2, -outerEllipseSize/2 - yLevel * ellipseDelta/2, outerEllipseSize + yLevel * ellipseDelta, outerEllipseSize + yLevel * ellipseDelta); QRect innerRect(-innerEllipseSize/2 - yLevel * ellipseDelta/2, -innerEllipseSize/2 - yLevel * ellipseDelta/2, innerEllipseSize + yLevel * ellipseDelta, innerEllipseSize + yLevel * ellipseDelta); QRect middleRect(-middleEllipseSize/2 - yLevel * ellipseDelta/2, -middleEllipseSize/2 - yLevel * ellipseDelta/2, middleEllipseSize + yLevel * ellipseDelta, middleEllipseSize + yLevel * ellipseDelta); arrowLength = qMin(arrowLength, ARROW_LENGTH); float dAlpha = 360 * arrowLength / (float)PI / (outerEllipseSize + innerEllipseSize + yLevel*ellipseDelta); bool isShort = totalLen / (float)seqLen * 360 < dAlpha; float regionLen = spanAngle*PI/180 * outerRect.height()/2; if(regionLen < REGION_MIN_LEN) { spanAngle = (float)REGION_MIN_LEN / (PI*outerRect.height()) * 360; } if(isShort) { path.moveTo(outerRect.width()/2 * cos(-startAngle / 180.0 * PI),-outerRect.height()/2 * sin(-startAngle / 180.0 * PI)); path.arcTo(outerRect, -startAngle, -spanAngle); path.arcTo(innerRect, -startAngle-spanAngle, spanAngle); path.closeSubpath(); } else { if(a->getStrand().isCompementary()) { path.moveTo(outerRect.width()/2 * cos((startAngle + dAlpha) / 180.0 * PI), outerRect.height()/2 * sin((startAngle + dAlpha) / 180.0 * PI)); path.lineTo((outerRect.width()/2 + arrowHeightDelta) * cos((startAngle + dAlpha) / 180.0 * PI), (outerRect.width()/2 + arrowHeightDelta) * sin((startAngle + dAlpha) / 180.0 * PI)); path.lineTo(middleRect.width()/2 * cos(startAngle / 180.0 * PI), middleRect.height()/2 * sin(startAngle/ 180.0 * PI)); path.lineTo((innerRect.width()/2 - arrowHeightDelta) * cos((startAngle + dAlpha) / 180.0 * PI), (innerRect.width()/2 - arrowHeightDelta) * sin((startAngle + dAlpha) / 180.0 * PI)); path.arcTo(innerRect, -(startAngle + dAlpha), -(spanAngle - dAlpha)); path.arcTo(outerRect, -startAngle - spanAngle, spanAngle - dAlpha); path.closeSubpath(); } else { path.moveTo(outerRect.width()/2 * cos(startAngle / 180.0 * PI), outerRect.height()/2 * sin(startAngle / 180.0 * PI)); path.arcTo(outerRect, -startAngle, -(spanAngle - dAlpha)); path.lineTo((outerRect.width()/2 + arrowHeightDelta) * cos((startAngle + spanAngle - dAlpha) / 180.0 * PI),(outerRect.height()/2 + arrowHeightDelta) * sin((startAngle + spanAngle - dAlpha) / 180.0 * PI)); path.lineTo(middleRect.width()/2 * cos((startAngle + spanAngle) / 180.0 * PI),middleRect.height()/2 * sin((startAngle + spanAngle)/ 180.0 * PI)); path.lineTo((innerRect.width()/2 - arrowHeightDelta) * cos((-startAngle - (spanAngle - dAlpha)) / 180.0 * PI),(innerRect.height()/2 - arrowHeightDelta) * sin((startAngle + spanAngle - dAlpha) / 180.0 * PI)); path.arcTo(innerRect, -startAngle - (spanAngle - dAlpha), spanAngle - dAlpha); path.closeSubpath(); } } regions.append(new CircurlarAnnotationRegionItem(path, isShort, location.indexOf(r))); } CircularAnnotationItem* item = new CircularAnnotationItem(a, regions, this); circItems[a] = item; } void CircularViewRenderArea::buildAnnotationLabel(const QFont& font, Annotation* a, const AnnotationSettings* as) { if (!as->visible) { return; } if(!circItems.contains(a)) { return; } ADVSequenceObjectContext* ctx = view->getSequenceContext(); bool splitted = U2AnnotationUtils::isSplitted(a->getLocation(), ctx->getSequenceObject()->getSequenceRange()); int seqLen = ctx->getSequenceLen(); const QVector& location = a->getRegions(); for(int r = 0; r < location.count(); r++) { if (splitted && r != 0) { break; } CircularAnnotationLabel* label = new CircularAnnotationLabel(a, r, seqLen, font, this); labelList.append(label); CircurlarAnnotationRegionItem* ri = circItems[a]->getRegions()[r]; ri->setLabel(label); } } U2Region CircularViewRenderArea::getAnnotationYRange(Annotation*, int, const AnnotationSettings*) const{ return U2Region(0,0); } void CircularViewRenderArea::resizeEvent( QResizeEvent *e ) { view->addUpdateFlags(GSLV_UF_ViewResized); QWidget::resizeEvent(e); } void CircularViewRenderArea::drawMarker(QPainter& p) { int yLevel = regionY.count() - 1; QPen markerPen; markerPen.setWidth(1); markerPen.setColor(Qt::gray); p.setPen(markerPen); QPainterPath arr1, arr2; arr1.moveTo((rulerEllipseSize/2.0 - MARKER_LEN)*cos(mouseAngle), (rulerEllipseSize/2.0 - MARKER_LEN)*sin(mouseAngle)); QPointF point11((rulerEllipseSize/2.0 - NOTCH_SIZE)*cos(mouseAngle), (rulerEllipseSize/2.0 - NOTCH_SIZE)*sin(mouseAngle)); arr1.lineTo(point11); arr1.lineTo(point11 - QPointF(ARR_LEN*sin(mouseAngle) + ARR_WIDTH/2*cos(mouseAngle), -ARR_LEN*cos(mouseAngle) + ARR_WIDTH/2*sin(mouseAngle))); arr1.moveTo(point11); arr1.lineTo(point11 + QPointF(ARR_LEN*sin(mouseAngle) - ARR_WIDTH/2*cos(mouseAngle), -ARR_LEN*cos(mouseAngle) - ARR_WIDTH/2*sin(mouseAngle))); arr2.moveTo((outerEllipseSize/2 + yLevel * ellipseDelta/2 + MARKER_LEN)*cos(mouseAngle), (outerEllipseSize/2 + yLevel * ellipseDelta/2 + MARKER_LEN)*sin(mouseAngle)); QPointF point21((outerEllipseSize/2 + yLevel * ellipseDelta/2 + ARROW_HEIGHT_DELTA)*cos(mouseAngle), (outerEllipseSize/2 + yLevel * ellipseDelta/2 + ARROW_HEIGHT_DELTA)*sin(mouseAngle)); arr2.lineTo(point21); arr2.lineTo(point21 + QPointF(ARR_LEN*sin(mouseAngle) + ARR_WIDTH/2*cos(mouseAngle), -ARR_LEN*cos(mouseAngle) + ARR_WIDTH/2*sin(mouseAngle))); arr2.moveTo(point21); arr2.lineTo(point21 + QPointF(-ARR_LEN*sin(mouseAngle) + ARR_WIDTH/2*cos(mouseAngle), ARR_LEN*cos(mouseAngle) + ARR_WIDTH/2*sin(mouseAngle))); p.drawPath(arr1); p.drawPath(arr2); } #define LABEL_PAD 30 void CircularViewRenderArea::evaluateLabelPositions() { labelEmptyPositions.clear(); labelEmptyInnerPositions.clear(); QFont f; QFontMetrics fm(f); int labelHeight = fm.height(); int lvlsNum = regionY.count(); int outerRadius = outerEllipseSize/2 + (lvlsNum-1)*ellipseDelta/2; int cw = fm.width('O'); int areaHeight = height(); /*int minAreaHeight = outerEllipseSize + ellipseDelta*lvlsNum; areaHeight = qMax(areaHeight, minAreaHeight);*/ int z0 = -areaHeight/2 + labelHeight; int z1 = areaHeight/2 - labelHeight; if (!fitsInView) { int wH = parentWidget()->height(); if (verticalOffset>wH) { z0 = -outerRadius; z1 = -outerRadius*cos(getVisibleAngle()); } } for(int zPos=z0; zPos0) { QRect l_rect(-x - LABEL_PAD, zPos, width()/2-(x+LABEL_PAD), labelHeight); QRect r_rect(x + LABEL_PAD, zPos, width()/2-(x+LABEL_PAD), labelHeight); labelEmptyPositions << l_rect << r_rect; } } //inner points int innerRadius = rulerEllipseSize/2 - LABEL_PAD; for (int zPos=-innerRadius+labelHeight; zPos<-2*labelHeight; zPos+=labelHeight) { int x = sqrt(float(innerRadius*innerRadius - zPos*zPos)); if(2*x>=cw) { QRect r_rect(x,zPos,2*x,labelHeight); QRect l_rect(-x,zPos,2*x,labelHeight); labelEmptyInnerPositions << r_rect << l_rect; } } for (int zPos=innerRadius; zPos>2*labelHeight; zPos-=labelHeight) { int x = sqrt(float(innerRadius*innerRadius - zPos*zPos)); if(2*x>=cw) { QRect r_rect(x,zPos,2*x,labelHeight); QRect l_rect(-x,zPos,2*x,labelHeight); labelEmptyInnerPositions << r_rect << l_rect; } } } CircularViewRenderArea::~CircularViewRenderArea() { qDeleteAll(circItems.values()); } }//namespace ugene-1.9.8/src/plugins/circular_view/transl/0000755000175000017500000000000011651544321017725 5ustar ilyailyaugene-1.9.8/src/plugins/circular_view/transl/russian.ts0000644000175000017500000000714711651544321021772 0ustar ilyailya U2::CircularViewAction Show circular view Показать круговой вид U2::CircularViewContext Save circular view as image Сохранить круговой вид как изображение Remove circular view Удалить круговой вид Show circular view Показать круговой вид U2::CircularViewHeaderWidget Zoom in Zoom out Fit in view Save circular view as image Сохранить круговой вид как изображение Raster image (*.png *.bmp *.jpg *.jpeg *.ppm *.xbm *.xpm) Vector image (*.svg) Portable document (*.pdf *.ps) Export circular view to image Сохранить круговой вид как изображение Unexpected error while exporting image! U2::CircularViewPlugin CircularView Круговой вид Enables drawing of DNA sequences using circular representation Круговой вид ДНК последовательности ugene-1.9.8/src/plugins/circular_view/transl/czech.ts0000644000175000017500000000463611651544321021402 0ustar ilyailya U2::CircularViewAction Show circular view U2::CircularViewContext Save circular view as image Remove circular view Show circular view U2::CircularViewHeaderWidget Save circular view as image Raster image (*.png *.bmp *.jpg *.jpeg *.ppm *.xbm *.xpm) Vector image (*.svg) Portable document (*.pdf *.ps) Export circular view to image U2::CircularViewPlugin CircularView Enables drawing of DNA sequences using circular representation ugene-1.9.8/src/plugins/circular_view/transl/english.ts0000644000175000017500000000627411651544321021737 0ustar ilyailya U2::CircularViewAction Show circular view U2::CircularViewContext Save circular view as image Remove circular view Show circular view U2::CircularViewHeaderWidget Zoom in Zoom out Fit in view Save circular view as image Raster image (*.png *.bmp *.jpg *.jpeg *.ppm *.xbm *.xpm) Vector image (*.svg) Portable document (*.pdf *.ps) Export circular view to image Unexpected error while exporting image! U2::CircularViewPlugin CircularView Enables drawing of DNA sequences using circular representation ugene-1.9.8/src/plugins/dbi_file/0000755000175000017500000000000011651544321015321 5ustar ilyailyaugene-1.9.8/src/plugins/dbi_file/dbi_file.pri0000644000175000017500000000051011651544321017566 0ustar ilyailya# include (dbi_file.pri) PLUGIN_ID=dbi_file PLUGIN_NAME=DBI implementation based on local files PLUGIN_VENDOR=Unipro LIBS += -lugenedb !debug_and_release|build_pass { CONFIG(debug, debug|release) { LIBS -= -lugenedb LIBS += -lugenedbd } } include( ../../ugene_plugin_common.pri ) ugene-1.9.8/src/plugins/dbi_file/dbi_file.pro0000644000175000017500000000024111651544321017575 0ustar ilyailyainclude (dbi_file.pri) # Input HEADERS += src/FileDbiPlugin.h \ src/FileDbi.h SOURCES += src/FileDbiPlugin.cpp \ src/FileDbi.cpp ugene-1.9.8/src/plugins/dbi_file/src/0000755000175000017500000000000011651544322016111 5ustar ilyailyaugene-1.9.8/src/plugins/dbi_file/src/FileDbi.cpp0000644000175000017500000000666611651544321020130 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "FileDbi.h" #include #include #include #include #include namespace U2 { // FileDbi FileDbi::FileDbi(FileDbiFactory * f) : U2AbstractDbi(f->getId()), fid(f->getDocumentFormatId()), seqDbi(NULL){ assert(!fid.isEmpty()); } void FileDbi::init(const QHash& props, const QVariantMap&, U2OpStatus& os) { bool create = props.value(U2_DBI_OPTION_CREATE, "0").toInt() > 0; Q_UNUSED(create); assert(!create); QString url = props.value(U2_DBI_OPTION_URL); if(url.isEmpty()) { os.setError(FileDbiL10N::tr("File url is empty")); state = U2DbiState_Void; return; } Project * prj = AppContext::getProject(); Document * doc = NULL; if(prj == NULL || (doc = prj->findDocumentByURL(url)) == NULL || !doc->isLoaded()) { os.setError(FileDbiL10N::tr("File '%1' needed to be added to project and loaded").arg(url)); state = U2DbiState_Void; return; } if(doc->getDocumentFormat()->getSupportedObjectTypes().contains(GObjectTypes::SEQUENCE)) { QList objs = doc->findGObjectByType(GObjectTypes::SEQUENCE); QList seqObjs; foreach(GObject * obj, objs) { DNASequenceObject * o = qobject_cast(obj); if(o != NULL) { seqObjs << o; } else { assert(false); } } if(seqObjs.isEmpty()) { os.setError(FileDbiL10N::tr("No sequence objects found in '%1'").arg(url)); state = U2DbiState_Void; return; } seqDbi = new DNASequenceObjectSequenceDbiWrapper(seqObjs, this); } initProperties = props; state = U2DbiState_Ready; } QVariantMap FileDbi::shutdown(U2OpStatus&) { return QVariantMap(); } U2SequenceDbi * FileDbi::getSequenceDbi() { return seqDbi; } // FileDbiFactory const U2DbiFactoryId FileDbiFactory::ID_PREFIX("FileDbi_"); FileDbiFactory::FileDbiFactory(const DocumentFormatId & f) : U2DbiFactory(), fid(f) { assert(!fid.isEmpty()); } U2Dbi * FileDbiFactory::createDbi() { DocumentFormatRegistry * dfReg = AppContext::getDocumentFormatRegistry(); if(dfReg != NULL && dfReg->getFormatById(fid) != NULL) { return new FileDbi(this); } return NULL; } U2DbiFactoryId FileDbiFactory::getId() const { return ID_PREFIX + fid; } bool FileDbiFactory::isValidDbi(const QHash&, const QByteArray&, U2OpStatus&) const { return false; } } // U2 ugene-1.9.8/src/plugins/dbi_file/src/FileDbiPlugin.h0000644000175000017500000000213511651544322020740 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_FILE_DBI_PLUGIN_H__ #define _U2_FILE_DBI_PLUGIN_H__ #include namespace U2 { class FileDbiPlugin : public Plugin { Q_OBJECT public: FileDbiPlugin(); }; // FileDbiPlugin } // U2 #endif // _U2_FILE_DBI_PLUGIN_H__ ugene-1.9.8/src/plugins/dbi_file/src/FileDbi.h0000644000175000017500000000421011651544322017555 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_FILE_DBI_H__ #define _U2_FILE_DBI_H__ #include #include namespace U2 { class FileDbiFactory; class FileDbi : public U2AbstractDbi { public: FileDbi(FileDbiFactory * f); virtual void init(const QHash& properties, const QVariantMap& persistentData, U2OpStatus& os); virtual QVariantMap shutdown(U2OpStatus & op); virtual U2SequenceDbi * getSequenceDbi(); private: DocumentFormatId fid; // seqDbi is deleted by dna seq obj that holds it U2SequenceDbi * seqDbi; }; // FileDbi class FileDbiFactory : public U2DbiFactory { static const U2DbiFactoryId ID_PREFIX; public: FileDbiFactory(const DocumentFormatId & fid); /** Creates new DBI instance */ virtual U2Dbi *createDbi(); /** Returns DBI type ID */ virtual U2DbiFactoryId getId() const; /** Checks that data pointed by properties is a valid DBI resource */ virtual bool isValidDbi(const QHash& properties, const QByteArray& rawData, U2OpStatus& os) const; DocumentFormatId getDocumentFormatId() const {return fid;} private: DocumentFormatId fid; }; // FileDbiFactory class FileDbiL10N : public QObject { Q_OBJECT }; // FileDbiL10N } // U2 #endif // _U2_FILE_DBI_H__ ugene-1.9.8/src/plugins/dbi_file/src/FileDbiPlugin.cpp0000644000175000017500000000306411651544322021275 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "FileDbiPlugin.h" #include "FileDbi.h" #include #include #include namespace U2 { extern "C" Q_DECL_EXPORT Plugin* U2_PLUGIN_INIT_FUNC() { FileDbiPlugin* plug = new FileDbiPlugin(); return plug; } FileDbiPlugin::FileDbiPlugin() : Plugin(tr("Plain files support in database"), tr("Adds support for using plain files in database")) { DocumentFormatConstraints constr; constr.supportedObjectTypes.insert(GObjectTypes::SEQUENCE); foreach(const DocumentFormatId & fid, AppContext::getDocumentFormatRegistry()->selectFormats(constr)) { AppContext::getDbiRegistry()->registerDbiFactory(new FileDbiFactory(fid)); } } } // U2 ugene-1.9.8/src/plugins/genome_aligner/0000755000175000017500000000000011651544323016541 5ustar ilyailyaugene-1.9.8/src/plugins/genome_aligner/genome_aligner.pri0000644000175000017500000000225511651544323022234 0ustar ilyailya# include (genome_aligner.pri) PLUGIN_ID=genome_aligner PLUGIN_NAME=Genome aligner PLUGIN_VENDOR=Unipro include( ../../ugene_plugin_common.pri ) #adding CUDA specific parameters use_cuda() { #manually convert INCLUDEPATH: GA_CUDA_INCLUDEPATH = for(path, INCLUDEPATH) { GA_CUDA_INCLUDEPATH += -I$${path} } for(path, QMAKE_INCDIR) { GA_CUDA_INCLUDEPATH += -I$${path} } LIBS += -L$$UGENE_CUDA_LIB_DIR -lcudart INCLUDEPATH += $$UGENE_CUDA_INC_DIR GA_NVCC_FLAGS = #TODO: win 64? !win32 { GA_NVCC_FLAGS += -Xcompiler -fPIC } GA_CUDA_LIBS += -lcudart GA_CUDA_FILES += src/suffix_search.cu nvzz.output = $$OBJECTS_DIR/${QMAKE_FILE_BASE}$$QMAKE_EXT_OBJ nvzz.commands = $$UGENE_NVCC $$GA_NVCC_FLAGS -c -I\"$$UGENE_CUDA_INC_DIR\" $$GA_CUDA_INCLUDEPATH -I$$QMAKE_INCDIR_QT \ -L\"$$UGENE_CUDA_LIB_DIR\" $$GA_CUDA_LIBS \ -o ${QMAKE_FILE_OUT} \ ${QMAKE_FILE_NAME} nvzz.depend_command = nvzz.input = GA_CUDA_FILES QMAKE_EXTRA_COMPILERS += nvzz DEFINES += GA_BUILD_WITH_CUDA } ugene-1.9.8/src/plugins/genome_aligner/genome_aligner.pro0000644000175000017500000000252511651544323022242 0ustar ilyailyainclude (genome_aligner.pri) # Input HEADERS += src/BuildSArraySettingsWidget.h \ src/GenomeAlignerCMDLineTask.h \ src/GenomeAlignerFindTask.h \ src/GenomeAlignerIndex.h \ src/GenomeAlignerIndexPart.h \ src/GenomeAlignerIndexTask.h \ src/GenomeAlignerIO.h \ src/GenomeAlignerPlugin.h \ src/GenomeAlignerSearchQuery.h \ src/GenomeAlignerSettingsWidget.h \ src/GenomeAlignerTask.h \ src/GenomeAlignerWorker.h \ src/GenomeAlignerWriteTask.h \ src/SuffixSearchCUDA.h FORMS += src/ui/BuildSuffixArraySettings.ui src/ui/GenomeAlignerSettings.ui SOURCES += src/BuildSArraySettingsWidget.cpp \ src/GenomeAlignerCMDLineTask.cpp \ src/GenomeAlignerFindTask.cpp \ src/GenomeAlignerIndex.cpp \ src/GenomeAlignerIndexPart.cpp \ src/GenomeAlignerIndexTask.cpp \ src/GenomeAlignerIO.cpp \ src/GenomeAlignerPlugin.cpp \ src/GenomeAlignerSearchQuery.cpp \ src/GenomeAlignerSettingsWidget.cpp \ src/GenomeAlignerTask.cpp \ src/GenomeAlignerWorker.cpp \ src/GenomeAlignerWriteTask.cpp \ src/SuffixSearchCUDA.cpp TRANSLATIONS += transl/english.ts transl/russian.ts ugene-1.9.8/src/plugins/genome_aligner/src/0000755000175000017500000000000011651544323017330 5ustar ilyailyaugene-1.9.8/src/plugins/genome_aligner/src/GenomeAlignerIndexPart.cpp0000644000175000017500000001214311651544323024370 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include #include #include #include #include "GenomeAlignerIndexPart.h" namespace U2 { IndexPart::IndexPart() { sArray = NULL; bitMask = NULL; seq = NULL; partCount = 0; currentPart = -1; seqStarts = NULL; seqLengths = NULL; saLengths = NULL; refFile = NULL; partFiles = NULL; } IndexPart::~IndexPart() { delete[] sArray; delete[] bitMask; delete[] seq; delete[] seqStarts; delete[] seqLengths; delete[] saLengths; if (NULL != refFile) { refFile->close(); } delete refFile; for (int i=0; iclose(); } delete partFiles[i]; } delete[] partFiles; } SAType IndexPart::getLoadedPartSize() { assert(currentPart>=0); return saLengths[currentPart]; } bool isLittleEndian() { char little[] = {1, 0, 0, 0}; int *n = (int*)little; if (1 == *n) { return true; } return false; } bool IndexPart::load(int part) { assert(part < partCount); if (part == currentPart) { return true; } currentPart = part; //int elemSize = sizeof(SAType) + sizeof(BMType); qint64 size = 0; saLengths[part] = (partFiles[part]->size() - 1 - seqLengths[currentPart]/4)/sizeof(SAType); if (!partFiles[part]->isOpen()) { partFiles[part]->open(QIODevice::ReadOnly); } partFiles[part]->seek(0); char *buff = (char*)sArray; size = partFiles[part]->read(buff, saLengths[currentPart]*sizeof(SAType)); assert(size == saLengths[currentPart]*sizeof(SAType)); if (size != qint64(saLengths[currentPart]) * sizeof(SAType)) { return false; } uchar *bitSeq = new uchar[1 + seqLengths[currentPart]/4]; size = partFiles[part]->read((char*)bitSeq, 1 + seqLengths[currentPart]/4); assert(size == 1 + seqLengths[currentPart]/4); if (size != 1 + seqLengths[currentPart]/4) { return false; } refFile->seek(seqStarts[currentPart]); size = refFile->read(seq, seqLengths[currentPart]); assert(size == seqLengths[currentPart]); if (size != seqLengths[currentPart]) { return false; } for (quint32 i=0; i((uchar*)(sArray + i)); } bitMask[i] = getBitValue(bitSeq, sArray[i]); } delete[] bitSeq; return true; } SAType IndexPart::getMaxLength() { SAType maxLength = 0; for (int i=0; i=0); return seqStarts[currentPart]; } void IndexPart::build(int) { } void IndexPart::writePart(int part, quint32 arrLen) { partFiles[part]->open(QIODevice::ReadWrite); currentPart = part; if (!isLittleEndian()) { for (quint32 i=0; iwrite((char*)sArray, arrLen * sizeof(SAType)); uchar *values = new uchar[1 + seqLengths[currentPart]/4]; int i = 0; int bitNum = 0; BitsTable bt; const quint32 *bitTable = bt.getBitMaskCharBits(DNAAlphabet_NUCL); for (quint32 j=0; j= 8) { bitNum = 0; i++; } } if (bitNum > 0) { values[i] <<= 8-bitNum; } partFiles[part]->write((char*)values, 1 + seqLengths[currentPart]/4); delete[] values; } BMType IndexPart::getBitValue(uchar *seq, SAType idx) { int charNum = idx/4; BMType res = qFromBigEndian(seq+charNum); if (0 == (idx - charNum*4)) { res >>= 2; return res; } res <<= 2*(idx - charNum*4); uchar qwe = *(seq+charNum+8); qwe >>= 2*((charNum+1)*4 - idx); res |= (BMType)qwe; res >>= 2; return res; } } //U2 ugene-1.9.8/src/plugins/genome_aligner/src/GenomeAlignerSearchQuery.h0000644000175000017500000000562311651544323024377 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_GENOME_ALIGNER_SEARCH_QUERY_H_ #define _U2_GENOME_ALIGNER_SEARCH_QUERY_H_ #include #include #include "GenomeAlignerIndexPart.h" #define BinarySearchResult qint64 namespace U2 { class GenomeAlignerIndex; class FindInPartSubTask; class PrepareVectorsSubTask; class CacheResult { public: int posAtShortRead; int numberOfPart; quint64 bitValue; }; class SearchQuery { public: SearchQuery(const DNASequence *shortRead, SearchQuery *revCompl = NULL); SearchQuery(const U2AssemblyRead &shortRead, SearchQuery *revCompl = NULL); ~SearchQuery(); QString getName() const; int length() const; int getNameLength() const; char *data(); const char *constData() const; const QByteArray constSequence() const; bool hasQuality() const; const DNAQuality &getQuality() const; bool haveResult() const; bool haveMCount() const; void addResult(SAType result, quint32 mCount); void addOveplapResult(SAType result); void onPartChanged(); void clear(); SAType firstResult() const; quint32 firstMCount() const; bool contains(SAType result) const; QVector &getResults(); bool isWroteResult() const {return wroteResult;} void writeResult() {wroteResult = true;} SearchQuery *getRevCompl() {return revCompl;} void setRevCompl(SearchQuery *rc) {revCompl = rc;} private: //U2AssemblyRead assRead; DNAQuality *quality; char *seq; char *name; quint32 seqLength; quint32 nameLength; bool dna; bool wroteResult; SearchQuery *revCompl; QVector results; QVector overlapResults; QVector mismatchCounts; }; class SearchQueryContainer { public: SearchQueryContainer(); ~SearchQueryContainer(); void append(SearchQuery *qu); void clear(); quint64 size(); SearchQuery *at(quint64 pos); private: SearchQuery **queries; quint64 length; quint64 allocated; static const quint64 reallocSize; }; } //U2 #endif //_U2_GENOME_ALIGNER_SEARCH_QUERY_H_ ugene-1.9.8/src/plugins/genome_aligner/src/GenomeAlignerSettingsWidget.h0000644000175000017500000000323711651544323025107 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _DIST_MATRIX_MODEL_WIDGET_H_ #define _DIST_MATRIX_MODEL_WIDGET_H_ #include "ui/ui_GenomeAlignerSettings.h" #include "U2View/DnaAssemblyGUIExtension.h" namespace U2{ class GenomeAlignerSettingsWidget : public DnaAssemblyAlgorithmMainWidget, Ui_GenomeAlignerSettings { Q_OBJECT public: GenomeAlignerSettingsWidget(QWidget* parent); virtual QMap getDnaAssemblyCustomSettings(); virtual bool isParametersOk(QString &error); virtual bool buildIndexUrl(const GUrl& url, bool prebuiltIndex, QString &error); virtual void prebuiltIndex(bool value); virtual bool isIndexOk(QString &error, GUrl refName); private slots: void sl_onSetIndexDirButtonClicked(); void sl_onPartSliderChanged(int value); void sl_onReadSliderChanged(int value); private: int systemSize; }; } #endif ugene-1.9.8/src/plugins/genome_aligner/src/GenomeAlignerIndex.cpp0000644000175000017500000004555511651544323023556 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include #include #include #include #include #include "GenomeAlignerFindTask.h" #include "GenomeAlignerTask.h" #include "GenomeAlignerIndex.h" #include "SuffixSearchCUDA.h" namespace U2 { const QString GenomeAlignerIndex::HEADER_EXTENSION("idx"); const QString GenomeAlignerIndex::SARRAY_EXTENSION("sarr"); const QString GenomeAlignerIndex::REF_INDEX_EXTENSION("ref"); const QString GenomeAlignerIndex::HEADER("#UGENE suffix array index\n"); const QString GenomeAlignerIndex::PARAMETERS("#file \"%1\", sequence's length = %2, w = %3\n"); const int GenomeAlignerIndex::charsInMask = MAX_BIT_MASK_LENGTH; const int GenomeAlignerIndex::overlapSize = 10000; const QString COMMENT1("#sequence length, window size, bitChar's length, seqPartSize, count of sequences\n"); const QString COMMENT2("#reference name\n"); const QString COMMENT3("#offsets of sequences in the reference\n"); const QString COMMENT4("#seqStart, seqLength, saStart, saLength\n"); GenomeAlignerIndex::GenomeAlignerIndex() : memIdx(NULL), memBM(NULL), objLens(NULL) { bitTable = bt.getBitMaskCharBits(DNAAlphabet_NUCL); bitCharLen = bt.getBitMaskCharBitsNum(DNAAlphabet_NUCL); seqLength = 0; w = 0; partsInMemCache = 0; objCount = 0; currentPart = -1; build = true; seqPartSize = -1; } GenomeAlignerIndex::~GenomeAlignerIndex() { delete[] memIdx; delete[] memBM; delete[] objLens; } void GenomeAlignerIndex::serialize(const QString &refFileName) { QString indexFileName = baseFileName + QString(".") + HEADER_EXTENSION; QFile file(indexFileName); if (!file.open(QIODevice::WriteOnly)) { return; } QByteArray data; data = HEADER.toAscii(); data += PARAMETERS.arg(refFileName).arg(seqLength).arg(w).toAscii(); data += COMMENT1 + COMMENT2 + COMMENT3 + COMMENT4; data += QByteArray::number(seqLength, 10) + ", "; data += QByteArray::number(w, 10) + ", "; data += QByteArray::number(bitCharLen, 10) + ", "; data += QByteArray::number(seqPartSize, 10) + ", "; data += QByteArray::number(objCount, 10) + "\n"; data += seqObjName + "\n"; for (int i=0; i'9') { intErr = true; return -1; } } return result.toUInt(); } bool GenomeAlignerIndex::deserialize(QByteArray &error) { QString indexFileName = baseFileName + QString(".") + HEADER_EXTENSION; QFile file(indexFileName); if (!file.open(QIODevice::ReadOnly)) { error = "Can't open file-index."; return false; } QByteArray data; bool eol = false; bool intErr = false; do { data = file.readLine().trimmed(); } while (data.length() > 0 && '#' == data[0]); if (0 == data.length()) { error = "Empty parameters' line in the file-index."; file.close(); return false; } seqLength = getNextInt(data, eol, intErr); w = getNextInt(data, eol, intErr); int bitCharLen = getNextInt(data, eol, intErr); seqPartSize = getNextInt(data, eol, intErr); if (eol) { error = "Too little amount of parameters in the file-index."; file.close(); return false; } objCount = getNextInt(data, eol, intErr); if (intErr) { error = "Bad integer for some parameter in the file-index."; file.close(); return false; } if (objCount <= 0) { error = "Count of sequences must be >0."; file.close(); return false; } seqObjName = file.readLine().trimmed(); data = file.readLine().trimmed(); objLens = new quint32[objCount]; eol = false; intErr = false; for (int i=0; ibitCharLen != bitCharLen) { error = "This index was built for a sequence with another sequence type."; file.close(); return false; } else { this->bitCharLen = bitCharLen; } file.close(); return true; } bool GenomeAlignerIndex::openIndexFiles() { indexPart.refFile = new QFile(baseFileName+QString(".")+GenomeAlignerIndex::REF_INDEX_EXTENSION); return indexPart.refFile->open(QIODevice::ReadOnly); } BMType GenomeAlignerIndex::getBitValue(const char *seq, int length) const { BMType bitValue = 0; for (int i = 0; i < length; i++) { bitValue = (bitValue << bitCharLen) | bitTable[uchar(*(seq+i))]; } bitValue <<= 2*charsInMask - bitCharLen*length; return bitValue; } bool GenomeAlignerIndex::loadPart(int part) { currentPart = part; if (build) { GTIMER(c, v, "GenomeAlignerIndex::build"); SAType arrLen = 0; sArray = indexPart.sArray; bitMask = indexPart.bitMask; buildPart(indexPart.seqStarts[part], indexPart.seqLengths[part], arrLen); indexPart.saLengths[part] = arrLen; indexPart.currentPart = part; sort(bitMask, 0, arrLen); GTIMER(c2, v2, "GenomeAlignerIndex::writePart"); indexPart.writePart(part, arrLen); v2.stop(); sArray = NULL; bitMask = NULL; if (part == indexPart.partCount - 1) { build = false; serialize(baseFileName + "." + REF_INDEX_EXTENSION); } return true; } else { GTIMER(c, v, "GenomeAlignerIndex::load"); return indexPart.load(part); } } BinarySearchResult GenomeAlignerIndex::bitMaskBinarySearch(BMType bitValue, BMType bitFilter) { int low = 0; int high = indexPart.getLoadedPartSize() - 1; BMType *a = indexPart.bitMask; qint64 rc = 0; while (low <= high) { int mid = (low + high) / 2; rc = (a[mid]&bitFilter) - (bitValue&bitFilter); if (rc < 0) { low = mid + 1; } else if (rc > 0) { high = mid - 1; } else { for(high=mid-1;high >= 0 && (a[high]&bitFilter)==(bitValue&bitFilter); high--){}; high++; break; } } if (0==rc) { return high; } return -1; } BinarySearchResult *GenomeAlignerIndex::bitMaskBinarySearchOpenCL(const BMType *bitValues, int size, BMType bitFilter) { taskLog.details(QString("Binary search on GPU of %1 Mb search-values in %2 Mb base values") .arg((8*size)/(1024*1024)).arg((8*indexPart.getLoadedPartSize())/(1024*1024))); BinaryFindOpenCL bf((NumberType*)indexPart.bitMask, indexPart.getLoadedPartSize(), (NumberType*)bitValues, size, bitFilter); NumberType *ans = bf.launch(); return (BinarySearchResult*)ans; } BinarySearchResult * GenomeAlignerIndex::findBitValuesUsingCUDA( BMType *bitValues, int size, BMType bitFilter ) { Q_UNUSED(bitValues);Q_UNUSED(size);Q_UNUSED(bitFilter); BinarySearchResult* result = NULL; #ifdef GA_BUILD_WITH_CUDA taskLog.details(QString("Binary search using CUDA on GPU of %1 Mb search-values in %2 Mb base values") .arg((8*size)/(1024*1024)).arg((8*indexPart.getLoadedPartSize())/(1024*1024))); // estimate memory size? SuffixSearchCUDA ss; result = (BinarySearchResult*)ss.runSearch( indexPart.bitMask, indexPart.getLoadedPartSize(), bitValues, size, bitFilter); #endif // GA_BUILD_WITH_CUDA return result; } bool GenomeAlignerIndex::isValidPos(SAType offset, int startPos, int length, SAType &fisrtSymbol, SearchQuery *qu, SAType &loadedSeqStart) { assert(offsetcontains(fisrtSymbol)) { return false; } //binary search in reference objects int low = 0; int high = objCount; int mid = 0; qint64 rc = 0; SAType minBorder = 0; while (low <= high) { mid = (low + high) / 2; rc = objLens[mid] - (qint64)offset; minBorder = mid>0?objLens[mid-1]:0; if (((qint64)offset >= minBorder) && (rc > 0)) { break; } else if (rc <= 0) { low = mid; } else { high = mid; } } if (fisrtSymbol < minBorder) { return false; } if (offset + (length - startPos - 1) >= objLens[mid]) { return false; } return true; } bool GenomeAlignerIndex::compare(const char *sourceSeq, const char *querySeq, int startPos, int w, int &c, int CMAX, int length) { // forward collect for (int i=startPos+w; iCMAX) { return false; } // backward collect for (int i=startPos-1; i>=0 && c <= CMAX; i--) { c += (querySeq[i] == sourceSeq[i])?0:1; } if (c <= CMAX) { return true; } return false; } //this method contains big copy-paste but it works very fast because of it. void GenomeAlignerIndex::alignShortRead(SearchQuery *qu, BMType bitValue, int startPos, BinarySearchResult firstResult, AlignContext *settings, BMType bitFilter, int w) { if (firstResult < 0) { return; } SAType fisrtSymbol = 0; //SAType offset = 0; const QByteArray &querySeq = qu->constSequence(); char *refBuff = NULL; int CMAX = settings->nMismatches; if (!settings->absMismatches) { CMAX = (querySeq.length() * settings->ptMismatches) / MAX_PERCENTAGE; } int bestC = CMAX + 1; SAType bestResult = 0; bool found = false; if (settings->bestMode) { if (qu->haveResult()) { bestC = qu->firstMCount(); } if (NULL != qu->getRevCompl() && qu->getRevCompl()->haveResult()) { int cRev = qu->getRevCompl()->firstMCount(); if (cRev < bestC) { bestC = cRev; } } } CMAX = bestC - 1; SAType loadedPartSize = indexPart.getLoadedPartSize(); SAType loadedSeqStart = indexPart.getLoadedSeqStart(); quint64 rightOverlapStart = (quint64)loadedSeqStart + (quint64)indexPart.seqLengths[indexPart.currentPart]; if (indexPart.currentPart != indexPart.partCount - 1) { rightOverlapStart -= 2*overlapSize; } for (SAType k=firstResult; (kbestMode) { found = true; bestC = c; bestResult = fisrtSymbol; CMAX = bestC - 1; if (0 == c) { break; } else { continue; } } if (fisrtSymbol >= rightOverlapStart) { qu->addOveplapResult(fisrtSymbol); } else { qu->addResult(fisrtSymbol, c); } } } if (settings->bestMode && found) { qu->clear(); qu->addResult(bestResult, bestC); } } /*build index*/ void GenomeAlignerIndex::buildPart(SAType start, SAType length, SAType &arrLen) { initSArray(start, length, arrLen); const char *seq = indexPart.seq; SAType *arunner = sArray; BMType *mrunner = bitMask; BMType bitValue = 0; SAType expectedNext = 0; quint32 wCharsInMask1 = w - 1; for (BMType *end = mrunner + arrLen; mrunner < end; arunner++, mrunner++) { const char* s = seq + *arunner; if (*arunner == expectedNext && expectedNext != 0) { //pop first bit, push wCharsInMask1 char to the mask bitValue = ((bitValue << bitCharLen) | bitTable[uchar(*(s + wCharsInMask1))]) & bitFilter; #ifdef _DEBUG // double check that optimization doesn't break anything BMType bitValue2 = getBitValue(s, w); assert(bitValue == bitValue2); #endif } else { //recompute the mask if we have some symbols skipped bitValue = getBitValue(s, w); } expectedNext = (s + 1) - seq; *mrunner = bitValue; } } void GenomeAlignerIndex::initSArray(SAType start, SAType length, SAType &arrLen) { indexPart.refFile->seek(start); qint64 l = indexPart.refFile->read(indexPart.seq, length); if (length != l) { //setError("Index .ref file is corrupted."); return; } const char *seq = indexPart.seq; SAType *arunner = sArray; SAType idx = start; SAType seqIdx = 0; SAType tmpIdx = 0; int curObj = 0; for (; curObj (objLens[curObj]-w) && idx < objLens[curObj]) { seqIdx += objLens[curObj] - idx; idx = objLens[curObj]; curObj++; goodSuff = false; } if (idx >= seqLength || seqIdx >= length) { break; } if (goodSuff) { if (seq[seqIdx + w-1]==unknownChar) { goodSuff = false; seqIdx += w; idx += w; i--; continue; } } if (!goodSuff) { int goodChars = 0; tmpIdx = idx; SAType j = seqIdx; for (; j off && compare(x+j-1,x+j)>0; j--) { swap(x+j, x+j-1); } } return; } // Choose a partition element, v quint32 m = off + len / 2; // Small arrays, middle element if (len > 7) { quint32 l = off; quint32 n = off + len - 1; if (len > 40) { // Big arrays, pseudo median of 9 quint32 s = len / 8; l = med3(x, l, l+s, l+2*s); m = med3(x, m-s, m, m+s); n = med3(x, n-2*s, n-s, n); } m = med3(x, l, m, n); // Mid-size, med of 3 } BMType *v = x + m; // Establish Invariant: v* (v)* v* int a = off, b = a, c = off + len - 1, d = c; while(true) { qint64 cr; while (b <= c && (cr = compare(v, x+b)) >=0 ) { if (cr == 0) { (x+b==v) && (v=x+a);//save middle pos value swap(x+a++,x+b); } b++; } while (c >= b && (cr = compare(x+c, v)) >=0 ) { if (cr == 0) { (x+c==v) && (v=x+d);//save middle pos value swap(x+c, x+d--); } c--; } if (b > c) { break; } swap(x+b++, x+c--); } // Swap partition elements back to middle int s, n = off + len; s = qMin(a-off, b-a ); vecswap(x+off, x+b-s, s); s = qMin(d-c, n-d-1); vecswap(x+b, x+n-s, s); // Recursively sort non-partition-elements if ((s = b-a) > 1) { sort(x, off, s); } if ((s = d-c) > 1) { sort(x, n-s, s); } } qint64 GenomeAlignerIndex::compare(const BMType *x1, const BMType *x2) const { return *x1-*x2; } void GenomeAlignerIndex::swap(BMType *x1, BMType *x2) const { assert(x1 - bitMask >= 0 && x1 - bitMask < (qint64)indexPart.saLengths[indexPart.currentPart]); assert(x2 - bitMask >= 0 && x2 - bitMask < (qint64)indexPart.saLengths[indexPart.currentPart]); SAType *a1 = sArray+(x1-bitMask); SAType *a2 = sArray+(x2-bitMask); qSwap(*x1, *x2); qSwap(*a1, *a2); } quint32 GenomeAlignerIndex::med3(BMType *x, quint32 a, quint32 b, quint32 c) { qint64 bc = compare(x+b, x+c); qint64 ac = compare(x+a, x+c); return compare(x+a, x+b) < 0 ? (bc < 0 ? b : ac < 0 ? c : a) : (bc > 0 ? b : ac > 0 ? c : a); } void GenomeAlignerIndex::vecswap(BMType *x1, BMType *x2, quint32 n) { for (quint32 i=0; i * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _GENOME_ALIGNER_IO_H_ #define _GENOME_ALIGNER_IO_H_ #include "GenomeAlignerSearchQuery.h" #include "GenomeAlignerIndexPart.h" #include #include #include #include #include #include #include #include #include #include #include namespace U2 { /************************************************************************/ /* Abstract short reads reader and writer */ /************************************************************************/ class GenomeAlignerReader { public: virtual ~GenomeAlignerReader() {} virtual SearchQuery *read() = 0; virtual bool isEnd() = 0; virtual int getProgress() = 0; }; class GenomeAlignerWriter { public: virtual void write(SearchQuery *seq, SAType offset) = 0; virtual void close() = 0; virtual void setReferenceName(const QString &refName) = 0; quint64 getWrittenReadsCount() const {return writtenReadsCount;} protected: quint64 writtenReadsCount; QString refName; }; /************************************************************************/ /* Abstract container for storing in QVariant */ /************************************************************************/ class GenomeAlignerReaderContainer { public: GenomeAlignerReaderContainer() : reader(NULL) { } GenomeAlignerReaderContainer(GenomeAlignerReader* reader) { this->reader = reader; } GenomeAlignerReader* reader; }; class GenomeAlignerWriterContainer { public: GenomeAlignerWriterContainer() : writer(NULL) {} GenomeAlignerWriterContainer(GenomeAlignerWriter* writer) { this->writer = writer; } GenomeAlignerWriter* writer; }; /************************************************************************/ /* URL short reads reader and writer */ /************************************************************************/ class GenomeAlignerUrlReader : public GenomeAlignerReader { public: GenomeAlignerUrlReader(const QList &dnaList); inline SearchQuery *read(); inline bool isEnd(); int getProgress(); private: bool initOk; StreamSequenceReader reader; }; class GenomeAlignerUrlWriter : public GenomeAlignerWriter { public: GenomeAlignerUrlWriter(const GUrl &resultFile, const QString &refName, int refLength); inline void write(SearchQuery *seq, SAType offset); void close(); void setReferenceName(const QString &refName); private: StreamShortReadsWriter seqWriter; }; /************************************************************************/ /* Workflow short reads reader and writer */ /************************************************************************/ namespace LocalWorkflow { class GenomeAlignerCommunicationChanelReader : public GenomeAlignerReader { public: GenomeAlignerCommunicationChanelReader(CommunicationChannel* reads); ~GenomeAlignerCommunicationChanelReader(); inline SearchQuery *read(); inline bool isEnd(); int getProgress(); private: CommunicationChannel* reads; DNASequenceObject *obj; }; class GenomeAlignerMAlignmentWriter : public GenomeAlignerWriter { public: GenomeAlignerMAlignmentWriter(); inline void write(SearchQuery *seq, SAType offset); void close(); void setReferenceName(const QString &refName); MAlignment &getResult(); private: MAlignment result; }; } //LocalWorkflow /************************************************************************/ /* DBI short reads reader and writer */ /************************************************************************/ class GenomeAlignerDbiReader : public GenomeAlignerReader { public: GenomeAlignerDbiReader(U2AssemblyDbi *rDbi, U2Assembly assembly); inline SearchQuery *read(); inline bool isEnd(); int getProgress(); private: bool end; DNASequenceObject *obj; U2AssemblyDbi *rDbi; U2Assembly assembly; QList reads; U2Region wholeAssembly; U2OpStatusImpl status; QList::Iterator currentRead; qint64 readNumber; qint64 maxRow; qint64 readsInAssembly; std::auto_ptr< U2DbiIterator > dbiIterator; static const qint64 readBunchSize; }; class GenomeAlignerDbiWriter : public GenomeAlignerWriter { public: GenomeAlignerDbiWriter(QString dbiFilePath, QString refName, int refLength); inline void write(SearchQuery *seq, SAType offset); void close(); void setReferenceName(const QString &) {}; private: U2OpStatusImpl status; QSharedPointer dbiHandle; U2Dbi* sqliteDbi; U2AssemblyDbi *wDbi; U2Assembly assembly; QList reads; static const qint64 readBunchSize; }; bool checkAndLogError(const U2OpStatusImpl & status); } //U2 Q_DECLARE_METATYPE(U2::GenomeAlignerReaderContainer); Q_DECLARE_METATYPE(U2::GenomeAlignerWriterContainer); #endif //_GENOME_ALIGNER_IO_H_ ugene-1.9.8/src/plugins/genome_aligner/src/GenomeAlignerTask.h0000644000175000017500000001144411651544323023044 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_GENOME_ALIGNER_TASK_H_ #define _U2_GENOME_ALIGNER_TASK_H_ #include #include #include #include #include "GenomeAlignerFindTask.h" #include "GenomeAlignerIO.h" #include "GenomeAlignerIndexPart.h" #include "GenomeAlignerWriteTask.h" namespace U2 { class DNASequenceObject; class DNATranslation; class LoadDocumentTask; class GenomeAlignerIndexTask; class GenomeAlignerIndex; class ReadShortReadsSubTask; class WriteAlignedReadsSubTask; class DbiHandle; class GenomeAlignerTask : public DnaAssemblyToReferenceTask { Q_OBJECT friend class ReadShortReadsSubTask; public: GenomeAlignerTask(const DnaAssemblyToRefTaskSettings& settings, bool justBuildIndex = false); ~GenomeAlignerTask(); virtual void prepare(); virtual ReportResult report(); virtual QList onSubTaskFinished(Task* subTask); QString getIndexPath(); static const QString OPTION_READS_READER; static const QString OPTION_READS_WRITER; static const QString OPTION_ALIGN_REVERSED; static const QString OPTION_OPENCL; static const QString OPTION_USE_CUDA; static const QString OPTION_IF_ABS_MISMATCHES; static const QString OPTION_MISMATCHES; static const QString OPTION_PERCENTAGE_MISMATCHES; static const QString OPTION_INDEX_DIR; static const QString OPTION_QUAL_THRESHOLD; static const QString OPTION_BEST; static const QString OPTION_DBI_IO; static const QString OPTION_READS_MEMORY_SIZE; static const QString OPTION_SEQ_PART_SIZE; static const int MIN_SHORT_READ_LENGTH = 30; static int calculateWindowSize(bool absMismatches, int nMismatches, int ptMismatches, int minReadLength, int maxReadLength); DNA_ASSEMBLEY_TO_REF_TASK_FACTORY(GenomeAlignerTask) private: LoadDocumentTask *loadDbiTask; GenomeAlignerIndexTask *createIndexTask; ReadShortReadsSubTask *readTask; GenomeAlignerFindTask *findTask; WriteAlignedReadsSubTask *writeTask; GenomeAlignerWriteTask *pWriteTask; GenomeAlignerReader *seqReader; GenomeAlignerWriter *seqWriter; AlignContext alignContext; bool justBuildIndex; uint bunchSize; bool alignReversed; bool dbiIO; QString indexFileName; bool prebuiltIndex; GenomeAlignerIndex *index; int qualityThreshold; int readMemSize; int seqPartSize; SearchQuery *lastQuery; bool noDataToAlign; //statistics quint64 readsCount; quint64 readsAligned; qint64 shortreadLoadTime; qint64 resultWriteTime; qint64 searchTime; qint64 indexLoadTime; qint64 shortreadIOTime; float currentProgress; void setupCreateIndexTask(); }; class ReadShortReadsSubTask : public Task { Q_OBJECT public: ReadShortReadsSubTask(SearchQuery **lastQuery, GenomeAlignerReader *seqReader, const DnaAssemblyToRefTaskSettings& settings, AlignContext &alignContext, quint64 freeMemorySize); virtual void run(); uint bunchSize; int minReadLength; int maxReadLength; private: SearchQuery **lastQuery; GenomeAlignerReader *seqReader; const DnaAssemblyToRefTaskSettings &settings; AlignContext &alignContext; quint64 freeMemorySize; inline bool add(int &CMAX, int &W, int &q, int &readNum, SearchQuery *query, GenomeAlignerTask *parent); static const int ONE_SEARCH_QUERY_SIZE = 38; //~38 bytes for one search query? }; class WriteAlignedReadsSubTask : public Task { Q_OBJECT public: WriteAlignedReadsSubTask(GenomeAlignerWriter *seqWriter, QVector &queries, quint64 &readsAligned); virtual void run(); private: GenomeAlignerWriter *seqWriter; QVector &queries; quint64 &readsAligned; inline void setReadWritten(SearchQuery *read, SearchQuery *revCompl); }; } //namespace #endif // _U2_GENOME_ALIGNER_TASK_H_ ugene-1.9.8/src/plugins/genome_aligner/src/GenomeAlignerIndex.h0000644000175000017500000001034011651544323023203 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_GENOME_ALIGNER_INDEX_H_ #define _U2_GENOME_ALIGNER_INDEX_H_ #include #include #include #include "GenomeAlignerIndexPart.h" #include "GenomeAlignerSettingsWidget.h" #include "GenomeAlignerFindTask.h" namespace U2 { #define BinarySearchResult qint64 class AlignContext; class SearchQuery; class GenomeAlignerIndex { friend class GenomeAlignerIndexTask; friend class GenomeAlignerSettingsWidget; friend class GenomeAlignerFindTask; public: GenomeAlignerIndex(); ~GenomeAlignerIndex(); BMType getBitValue(const char *seq, int length) const; bool loadPart(int part); void alignShortRead(SearchQuery *qu, BMType bitValue, int startPos, BinarySearchResult firstResult, AlignContext *settings, BMType bitFilter, int w); BinarySearchResult bitMaskBinarySearch(BMType bitValue, BMType bitFilter); BinarySearchResult *bitMaskBinarySearchOpenCL(const BMType *bitValues, int size, quint64 BMType); BinarySearchResult *findBitValuesUsingCUDA(BMType *bitValues, int size, BMType filter); QString getSeqName() const {return seqObjName;} int getPartCount() const {return indexPart.partCount;} SAType getSArraySize() const {return indexPart.saLengths[currentPart];} SAType getSeqLength() const {return seqLength;} IndexPart& getLoadedPart() { return indexPart; } private: quint32 seqLength; //reference sequence's length int seqPartSize; //in Mb int w; //window size QString baseFileName; //base of the file name quint32 *memIdx; quint64 *memBM; BitsTable bt; const quint32* bitTable; int bitCharLen; BMType bitFilter; int partsInMemCache; quint32 *objLens; int objCount; QString seqObjName; int currentPart; IndexPart indexPart; bool build; char unknownChar; void serialize(const QString &refFileName); bool deserialize(QByteArray &error); bool openIndexFiles(); inline bool isValidPos(SAType offset, int startPos, int length, SAType &fisrtSymbol, SearchQuery *qu, SAType &loadedSeqStart); inline bool compare(const char *sourceSeq, const char *querySeq, int startPos, int w, int &c, int CMAX, int length); inline void fullBitMaskOptimization(int CMAX, BMType bitValue, BMType bitMaskValue, int restBits, int w, int &bits, int &c); inline bool find(SAType &offset, SAType &firstSymbol, int &startPos, SearchQuery *qu, bool &bestMode, int &CMAX, bool valid); static const QString HEADER; static const QString PARAMETERS; /*build*/ SAType *sArray; BMType *bitMask; void buildPart(SAType start, SAType length, SAType &arrLen); void initSArray(SAType start, SAType length, SAType &arrLen); void sort(BMType *x, int off, int len); inline qint64 compare(const BMType *x1, const BMType *x2) const; inline void swap(BMType *x1, BMType *x2) const; inline quint32 med3(BMType *x, quint32 a, quint32 b, quint32 c); inline void vecswap(BMType *x1, BMType *x2, quint32 n); public: static const QString HEADER_EXTENSION; static const QString SARRAY_EXTENSION; static const QString REF_INDEX_EXTENSION; static const int charsInMask; static const int overlapSize; }; } //U2 #endif ugene-1.9.8/src/plugins/genome_aligner/src/GenomeAlignerFindTask.cpp0000644000175000017500000002652511651544323024206 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include #include #include #include #include #include "GenomeAlignerIndex.h" #include "GenomeAlignerTask.h" #include "SuffixSearchCUDA.h" #include #include "GenomeAlignerFindTask.h" namespace U2 { const int GenomeAlignerFindTask::ALIGN_DATA_SIZE = 100000; GenomeAlignerFindTask::GenomeAlignerFindTask(U2::GenomeAlignerIndex *i, AlignContext *s, GenomeAlignerWriteTask *w) : Task("GenomeAlignerFindTask", TaskFlag_None), index(i), writeTask(w), alignContext(s), bitMaskResults(NULL) { partLoaded = false; openCLFinished = false; nextElementToGive = 0; indexLoadTime = 0; waiterCount = 0; alignerTaskCount = 0; } void GenomeAlignerFindTask::prepare() { alignContext->w = GenomeAlignerTask::calculateWindowSize(alignContext->absMismatches, alignContext->nMismatches, alignContext->ptMismatches, alignContext->minReadLength, alignContext->maxReadLength); alignContext->bitFilter = ((quint64)0 - 1)<<(62 - alignContext->w*2); if (alignContext->useCUDA) { //proceed to run function return; } alignerTaskCount = AppContext::getAppSettings()->getAppResourcePool()->getIdealThreadCount(); setMaxParallelSubtasks(alignerTaskCount); for (int i=0; isetSubtaskProgressWeight(1.0f/alignerTaskCount); addSubTask(subTask); } } void GenomeAlignerFindTask::run() { if (alignContext->useCUDA) { GenomeAlignerCUDAHelper cudaHelper; cudaHelper.loadShortReads(alignContext->queries, stateInfo); if (hasError()) { return; } for (int part = 0; part < index->getPartCount(); ++part) { if (!index->loadPart(part)) { setError("Incorrect index file. Please, try to create a new index file."); } cudaHelper.alignReads(index->getLoadedPart(),alignContext, stateInfo); if (hasError()) { return; } } } } void GenomeAlignerFindTask::loadPartForAligning(int part) { waitMutex.lock(); waiterCount++; if (waiterCount != alignerTaskCount) { waiter.wait(&waitMutex); waiter.wakeOne(); } else { waiterCount = 0; partLoaded = false; waiter.wakeOne(); } waitMutex.unlock(); QMutexLocker lock(&loadPartMutex); if (!partLoaded) { taskLog.details(QString("loading part %1").arg(part)); if (!index->loadPart(part)) { setError("Incorrect index file. Please, try to create a new index file."); } partLoaded = true; openCLFinished = false; nextElementToGive = 0; taskLog.details(QString("finish to load part %1").arg(part)); } } void GenomeAlignerFindTask::unsafeGetData(int &first, int &length) { int bitValuesCount = alignContext->bitValuesV.size(); first = nextElementToGive; if (first >= bitValuesCount) { length = 0; } else if (first + ALIGN_DATA_SIZE > bitValuesCount) { length = bitValuesCount - first; } else { length = ALIGN_DATA_SIZE; } QVector &rn = alignContext->readNumbersV; int it = first + length; for (int last=it-1; itqueries.at(rn[last]); SearchQuery *qu = alignContext->queries.at(rn[it]); if (lastQu->getRevCompl() == qu) { last = it; length++; } else { break; } } } nextElementToGive += length; } void GenomeAlignerFindTask::getDataForAligning(int &first, int &length) { QMutexLocker lock(&shortReadsMutex); unsafeGetData(first, length); } void GenomeAlignerFindTask::waitDataForAligning(int &first, int &length) { QMutexLocker lock(&shortReadsMutex); while ((!alignContext->isReadingFinished && alignContext->bitValuesV.size() - nextElementToGive < ALIGN_DATA_SIZE) || !alignContext->isReadingStarted) { //while (not enough read) wait alignContext->alignerWait.wait(&shortReadsMutex); } unsafeGetData(first, length); if (alignContext->isReadingFinished) { alignContext->alignerWait.wakeAll(); } } bool GenomeAlignerFindTask::runOpenCLBinarySearch() { QMutexLocker lock(&openCLMutex); if (!openCLFinished) { openCLFinished = true; delete[] bitMaskResults; bitMaskResults = index->bitMaskBinarySearchOpenCL(alignContext->bitValuesV.constData(), alignContext->bitValuesV.size(), alignContext->bitFilter); if (NULL == bitMaskResults) { setError("OpenCL binary find error"); return false; } } if (NULL == bitMaskResults) { return false; } return true; } GenomeAlignerFindTask::~GenomeAlignerFindTask() { delete[] bitMaskResults; } ShortReadAligner::ShortReadAligner(GenomeAlignerIndex *i, AlignContext *s, GenomeAlignerWriteTask *w) : Task("ShortReadAligner", TaskFlag_None), index(i), alignContext(s), writeTask(w) { } void ShortReadAligner::run() { GenomeAlignerFindTask *parent = static_cast(getParentTask()); SearchQuery *shortRead = NULL; SearchQuery *revCompl = NULL; int first = 0; int last = 0; int length = 0; BinarySearchResult bmr = 0; BinarySearchResult *bitMaskResults = NULL; //for thread safe: SearchQuery **q = const_cast(alignContext->queries.constData()); BMType bv = 0; int rn = 0; int rn1 = 0; int pos = 0; int w = GenomeAlignerTask::calculateWindowSize(alignContext->absMismatches, alignContext->nMismatches, alignContext->ptMismatches, alignContext->minReadLength, alignContext->maxReadLength); int currentW = w; BMType bitFilter = ((quint64)0 - 1)<<(62 - w*2); BMType currentBitFilter = bitFilter; for (int part=0; part < index->getPartCount(); part++) { q = const_cast(alignContext->queries.constData()); const BMType *bitValues = alignContext->bitValuesV.constData(); const int *readNumbers = alignContext->readNumbersV.constData(); const int *par = alignContext->positionsAtReadV.constData(); stateInfo.setProgress(100*part/index->getPartCount()); parent->loadPartForAligning(part); if (parent->hasError()) { return; } stateInfo.setProgress(stateInfo.getProgress() + 25/index->getPartCount()); if (alignContext->openCL) { if (!parent->runOpenCLBinarySearch()) { return; } bitMaskResults = parent->bitMaskResults; stateInfo.setProgress(stateInfo.getProgress() + 50/index->getPartCount()); } if (part > 0 || alignContext->openCL) { parent->getDataForAligning(first, length); } else { //if (0 == part) then wait for reading shortreads parent->waitDataForAligning(first, length); } while (length > 0) { if (!(part > 0 || alignContext->openCL)) { w = GenomeAlignerTask::calculateWindowSize(alignContext->absMismatches, alignContext->nMismatches, alignContext->ptMismatches, alignContext->minReadLength, alignContext->maxReadLength); bitFilter = ((quint64)0 - 1)<<(62 - w*2); } last = first + length; for (int i=first; i 0 || alignContext->openCL) { //for avoiding a QVector deep copy bv = bitValues[i]; rn = readNumbers[i]; pos = par[i]; if (i < last - 1) { rn1 = readNumbers[i+1]; } shortRead = q[rn]; } else { QMutexLocker lock(&alignContext->listM); bv = alignContext->bitValuesV[i]; rn = alignContext->readNumbersV[i]; pos = alignContext->positionsAtReadV[i]; if (i < last - 1) { rn1 = alignContext->readNumbersV[i+1]; } shortRead = alignContext->queries[rn]; } revCompl = shortRead->getRevCompl(); if (alignContext->bestMode) { if (0 == shortRead->firstMCount()) { continue; } if (NULL != revCompl && 0 == revCompl->firstMCount()) { continue; } } currentBitFilter = bitFilter; currentW = w; if (alignContext->openCL) { bmr = bitMaskResults[i]; } else { if (shortRead->length() < GenomeAlignerTask::MIN_SHORT_READ_LENGTH) { currentW = GenomeAlignerTask::calculateWindowSize(alignContext->absMismatches, alignContext->nMismatches, alignContext->ptMismatches, shortRead->length(), shortRead->length()); currentBitFilter = ((quint64)0 - 1)<<(62 - currentW*2); if (0 == currentW) { continue; } } bmr = index->bitMaskBinarySearch(bv, currentBitFilter); } index->alignShortRead(shortRead, bv, pos, bmr, alignContext, currentBitFilter, currentW); if (!alignContext->bestMode) { if ((i == last - 1) || (rn1 != rn)) { if (shortRead->haveResult()) { writeTask->addResult(shortRead); } shortRead->onPartChanged(); } } } if (part > 0 || alignContext->openCL) { parent->getDataForAligning(first, length); } else { parent->waitDataForAligning(first, length); } w = GenomeAlignerTask::calculateWindowSize(alignContext->absMismatches, alignContext->nMismatches, alignContext->ptMismatches, alignContext->minReadLength, alignContext->maxReadLength); bitFilter = ((quint64)0 - 1)<<(62 - w*2); } } } } // U2 ugene-1.9.8/src/plugins/genome_aligner/src/SuffixSearchCUDA.cpp0000644000175000017500000002171711651544323023073 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifdef GA_BUILD_WITH_CUDA #include #endif #include #include #include #include "GenomeAlignerIndexPart.h" #include "GenomeAlignerFindTask.h" #include "SuffixSearchCUDA.h" #define SAFE_CALL(call) { \ cudaError_t err = call; \ if ( cudaSuccess != err) { \ stateInfo.setError(QString("CUDA driver error: %1 at %2:%3").arg(cudaGetErrorString(err)).arg(__FILE__).arg(__LINE__)); \ return; \ } }\ namespace U2 { #ifdef GA_BUILD_WITH_CUDA extern "C" void cudaBinarySearch(quint64* pList1Dev, int nList1Length, quint64* pList2Dev, int nList2Length); extern "C" void cudaAlignReads(char* readsData, int* readSizes, int* readOffsets, int readsNumber, char* refSeq, int refSeqSize, SAType* sArrayData, int sArraySize, BMType* bmArrayData, int bmArraySize, BMType bitFilter, int refStartPos, int loadedPartSize, int CMAX, int w, quint32* results); quint64* U2::SuffixSearchCUDA::runSearch( const quint64* numbers, const int numbersSize, const quint64* query, const int querySize, quint64 filter ) { cudaMalloc((void **)&numbersListDev, numbersSize * sizeof(quint64)); cudaMalloc((void **)&queryListDev,querySize * sizeof(quint64)); cudaMemcpy(numbersListDev, numbers, numbersSize * sizeof(quint64), cudaMemcpyHostToDevice); cudaMemcpy(queryListDev, query, querySize * sizeof(quint64), cudaMemcpyHostToDevice); cudaBinarySearch(numbersListDev, numbersSize, queryListDev, querySize); quint64* results = new quint64[querySize]; cudaMemcpy(results, queryListDev, querySize * sizeof(quint64), cudaMemcpyDeviceToHost); cudaFree(numbersListDev); cudaFree(queryListDev); return results; } #endif //GA_BUILD_WITH_CUDA GenomeAlignerCUDAHelper::GenomeAlignerCUDAHelper( ) : readsNumber(0), suffixSize(0), seqSize(0) { bufSizeMB = 1; } void GenomeAlignerCUDAHelper::loadShortReads(QVector& queries, TaskStateInfo& stateInfo) { #ifdef GA_BUILD_WITH_CUDA // TODO: // perform memory checks readsNumber = queries.size(); QVector sizes; QVector offsets; int totalReadsSize = 0; foreach (SearchQuery* q, queries) { int len = q->length(); sizes.append(len); offsets.append(totalReadsSize); totalReadsSize += len; } // TODO: // set counters taskLog.details(QString("Allocation data for short reads on CUDA device")); SAFE_CALL( cudaMalloc((void **)&readsDev, totalReadsSize * sizeof(char)) ); SAFE_CALL( cudaMalloc((void **)&readSizesDev, readsNumber * sizeof(quint32)) ); SAFE_CALL( cudaMalloc((void **)&readOffsetsDev, readsNumber * sizeof(quint32)) ); taskLog.details(QString("Copying %1 bytes of short reads data to device").arg(totalReadsSize*sizeof(char))); // TODO: change the way reads are loaded into memory: use big data chunks when loading! char* buf = NULL; // buffer to speed-up reads transfer to GPU int bufSizeBytes = bufSizeMB*1024*1024; int curSize = 0, lastOffset = 0; cudaError_t err = cudaSuccess; // It's f**king dangerous! try { buf = new char[bufSizeBytes]; } catch(std::bad_alloc e) { stateInfo.setError("Can't allocate memory for CUDA buffer.\ Try to close some of your programs or to decrease \"maxMemorySize\"-option"); return; } for (int i = 0; i < readsNumber; ++i) { int readSize = sizes.at(i); int offset = offsets.at(i); if (curSize + readSize > bufSizeBytes) { err = cudaMemcpy(readsDev + lastOffset, buf, curSize * sizeof(char), cudaMemcpyHostToDevice) ; lastOffset = offset; curSize = 0; if (err != cudaSuccess) { break; } } qMemCopy(buf + curSize, queries.at(i)->constData(), readSize ); curSize += readSize; } if (curSize > 0) { cudaMemcpy(readsDev + lastOffset, buf, curSize * sizeof(char), cudaMemcpyHostToDevice) ; } delete[] buf; if (err != cudaSuccess) { stateInfo.setError(QString("Error while coping short reads to CUDA device: %1") .arg(cudaGetErrorString(err) )); return; } taskLog.details(QString("Copying %1 bytes of read sizes data to device").arg(readsNumber*sizeof(quint32))); SAFE_CALL( cudaMemcpy(readSizesDev, sizes.data(), readsNumber*sizeof(quint32), cudaMemcpyHostToDevice ) ); taskLog.details(QString("Copying %1 bytes of read offsets data to device").arg(readsNumber*sizeof(quint32))); SAFE_CALL( cudaMemcpy(readOffsetsDev, offsets.data(), readsNumber*sizeof(quint32), cudaMemcpyHostToDevice ) ); #else Q_UNUSED(queries); stateInfo.setError(GenomeAlignerFindTask::tr("The CUDA optimization is not included into this bundle.\ Please make sure to set UGENE_CUDA_DECTECTED=1 when building UGENE") ); #endif } void GenomeAlignerCUDAHelper::alignReads(IndexPart& indexPart, AlignContext* ctx, TaskStateInfo& stateInfo) { #ifdef GA_BUILD_WITH_CUDA suffixSize = indexPart.getLoadedPartSize(); seqSize = suffixSize + ctx->w - 1; assert(readsNumber == ctx->queries.size()); SAFE_CALL( cudaMalloc((void **)&bmArrayDev, suffixSize * sizeof(quint64))); SAFE_CALL( cudaMalloc((void **)&sArrayDev, suffixSize * sizeof(quint32))); SAFE_CALL( cudaMalloc((void **)&seqDev, seqSize*sizeof(char))); SAFE_CALL( cudaMalloc((void **)&resultsDev, 2*readsNumber*sizeof(int))); taskLog.details(QString("Copying %1 bytes of bit mask array data to device").arg(suffixSize*sizeof(quint64))); SAFE_CALL( cudaMemcpy(bmArrayDev, indexPart.bitMask, suffixSize*sizeof(quint64), cudaMemcpyHostToDevice ) ); taskLog.details(QString("Copying %1 bytes of suffix array data to device").arg(suffixSize*sizeof(quint32))); SAFE_CALL( cudaMemcpy(sArrayDev, indexPart.sArray, suffixSize*sizeof(quint32), cudaMemcpyHostToDevice ) ); taskLog.details(QString("Copying %1 bytes of reference sequence to device").arg(seqSize*sizeof(char))); SAFE_CALL( cudaMemcpy(seqDev, indexPart.seq , seqSize*sizeof(char), cudaMemcpyHostToDevice ) ); cudaAlignReads(readsDev,readSizesDev,readOffsetsDev,readsNumber,seqDev,seqSize, sArrayDev,suffixSize,bmArrayDev,suffixSize,ctx->bitFilter,indexPart.getLoadedSeqStart(), indexPart.getLoadedPartSize(), ctx->nMismatches, ctx->w, resultsDev ); QVector results; results.resize(2*readsNumber); taskLog.details( QString("Copying %1 bytes of results data to host").arg(2*readsNumber*sizeof(int)) ); SAFE_CALL( cudaMemcpy(results.data(), resultsDev, 2*readsNumber*sizeof(int), cudaMemcpyDeviceToHost ) ); for (int i = 0; i < readsNumber; ++i) { int rPos = results[2*i]; if (rPos != -1) { int mCount = results[2*i+1]; ctx->queries[i]->addResult(rPos, mCount); } } SAFE_CALL( cudaFree(resultsDev) ); SAFE_CALL( cudaFree(seqDev) ); SAFE_CALL( cudaFree(bmArrayDev) ); SAFE_CALL( cudaFree(sArrayDev) ); #else Q_UNUSED(indexPart);Q_UNUSED(ctx); stateInfo.setError(GenomeAlignerFindTask::tr("The CUDA optimization is not included into this bundle.\ Please make sure to set UGENE_CUDA_DECTECTED=1 when building UGENE") ); #endif } qint64 GenomeAlignerCUDAHelper::estimateMemoryUsage() { return 0; } GenomeAlignerCUDAHelper::~GenomeAlignerCUDAHelper() { #ifdef GA_BUILD_WITH_CUDA // is it safe to do it in destructor? if (readsNumber != 0) { cudaFree(readsDev); cudaFree(readSizesDev); cudaFree(readOffsetsDev); } #endif } } //namespace ugene-1.9.8/src/plugins/genome_aligner/src/GenomeAlignerWriteTask.h0000644000175000017500000000354611651544323024063 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_GENOME_ALIGNER_WRITE_TASK_H_ #define _U2_GENOME_ALIGNER_WRITE_TASK_H_ #include "GenomeAlignerIO.h" #include "GenomeAlignerSearchQuery.h" #include #include #include namespace U2 { class WriteData { public: SearchQuery *qu; SAType offset; }; class GenomeAlignerWriteTask : public Task { Q_OBJECT public: GenomeAlignerWriteTask(GenomeAlignerWriter *seqWriter); virtual void run(); void addResult(SearchQuery *qu); void flush(); void setFinished(); quint64 getWrittenReadsCount() const {return readsWritten;} void setSeqWriter(GenomeAlignerWriter *seqWriter); private: GenomeAlignerWriter *seqWriter; QVector results; bool end; bool writing; quint64 readsWritten; QMutex listMutex; QMutex writeMutex; QMutex waitMutex; QWaitCondition waiter; static const int MAX_LIST_SIZE = 1000; inline void setReadWritten(SearchQuery *read, SearchQuery *revCompl); }; } //namespace #endif // _U2_GENOME_ALIGNER_WRITE_TASK_H_ ugene-1.9.8/src/plugins/genome_aligner/src/GenomeAlignerWorker.h0000644000175000017500000001152711651544323023415 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_GENOME_ALIGNER_WORKER_H_ #define _U2_GENOME_ALIGNER_WORKER_H_ #include #include #include "GenomeAlignerTask.h" #include "GenomeAlignerIO.h" namespace U2 { namespace LocalWorkflow { /************************************************************************/ /* Genome aligner */ /************************************************************************/ class GenomeAlignerPrompter : public PrompterBase { Q_OBJECT public: GenomeAlignerPrompter(Actor* p = 0) : PrompterBase(p) {} protected: QString composeRichDoc(); }; class GenomeAlignerWorker : public BaseWorker { Q_OBJECT public: GenomeAlignerWorker(Actor* a); virtual void init(); virtual bool isReady(); virtual Task* tick(); virtual bool isDone() {return done;} virtual void cleanup(); private slots: void sl_taskFinished(); protected: CommunicationChannel *reads, *index, *output; GenomeAlignerReader *reader; GenomeAlignerWriter *writer; QString resultName,transId; DnaAssemblyToRefTaskSettings settings; bool done; }; class GenomeAlignerWorkerFactory : public DomainFactory { public: static const QString ACTOR_ID; static void init(); GenomeAlignerWorkerFactory() : DomainFactory(ACTOR_ID) {} virtual Worker* createWorker(Actor* a) {return new GenomeAlignerWorker(a);} }; /************************************************************************/ /* Genome aligner index build */ /************************************************************************/ class GenomeAlignerBuildPrompter : public PrompterBase { Q_OBJECT public: GenomeAlignerBuildPrompter(Actor* p = 0) : PrompterBase(p) {} protected: QString composeRichDoc(); }; class GenomeAlignerBuildWorker : public BaseWorker { Q_OBJECT public: GenomeAlignerBuildWorker(Actor* a) : BaseWorker(a), output(NULL), done(false) {} virtual void init(); virtual bool isReady(); virtual Task* tick(); virtual bool isDone(); virtual void cleanup() {} private slots: void sl_taskFinished(); protected: CommunicationChannel *output; QString resultName, transId; GUrl refSeqUrl; GUrl indexUrl; bool done; DnaAssemblyToRefTaskSettings settings; }; class GenomeAlignerBuildWorkerFactory : public DomainFactory { public: static const QString ACTOR_ID; static void init(); GenomeAlignerBuildWorkerFactory() : DomainFactory(ACTOR_ID) {} virtual Worker* createWorker(Actor* a) {return new GenomeAlignerBuildWorker(a);} }; /************************************************************************/ /* Genome aligner index read */ /************************************************************************/ class GenomeAlignerIndexReaderPrompter : public PrompterBase { Q_OBJECT public: GenomeAlignerIndexReaderPrompter(Actor* p = 0) : PrompterBase(p) {} protected: QString composeRichDoc(); }; class GenomeAlignerIndexReaderWorker : public BaseWorker { Q_OBJECT public: GenomeAlignerIndexReaderWorker(Actor* a) : BaseWorker(a), output(NULL), done(false) {} virtual void init(); virtual bool isReady(); virtual Task* tick(); virtual bool isDone(); virtual void cleanup() {} private slots: void sl_taskFinished(); protected: CommunicationChannel *output; QString resultName,transId; GUrl indexUrl; bool done; }; class GenomeAlignerIndexReaderWorkerFactory : public DomainFactory { public: static const QString ACTOR_ID; static void init(); GenomeAlignerIndexReaderWorkerFactory() : DomainFactory(ACTOR_ID) {} virtual Worker* createWorker(Actor* a) {return new GenomeAlignerIndexReaderWorker(a);} }; } // Workflow namespace } // U2 namespace #endif // GENOME_ALIGNER_WORKER ugene-1.9.8/src/plugins/genome_aligner/src/GenomeAlignerIndexTask.cpp0000644000175000017500000001717711651544323024400 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include #include #include #include #include #include #include #include "U2Formats/StreamSequenceReader.h" #include #include #include "GenomeAlignerIndex.h" #include "GenomeAlignerIndexTask.h" namespace U2 { GenomeAlignerIndexTask::GenomeAlignerIndexTask(const GenomeAlignerIndexSettings &settings) : Task("Building genome aligner's index", TaskFlag_None), objLens(NULL), unknownChar('N') { GUrl i = settings.indexFileName; baseFileName = i.dirPath() + "/" + i.baseFileName(); w = MAX_BIT_MASK_LENGTH; bitTable = bt.getBitMaskCharBits(DNAAlphabet_NUCL); bitCharLen = bt.getBitMaskCharBitsNum(DNAAlphabet_NUCL); index = new GenomeAlignerIndex(); index->baseFileName = baseFileName; index->unknownChar = unknownChar; index->bitFilter = ((BMType)1<<(bitCharLen * w))-1; this->settings = settings; } GenomeAlignerIndexTask::~GenomeAlignerIndexTask() { } SAType getPartStartPos(SAType seqLength, int parts, int curPart) { SAType start = (seqLength/parts)*curPart; if (curPart > 0) { start -= GenomeAlignerIndex::overlapSize; } return start; } SAType getPartLength(SAType seqLength, int parts, int curPart) { SAType length = 0; if (curPart < parts - 1) { length = (seqLength/parts) + GenomeAlignerIndex::overlapSize; } else { length = seqLength - (seqLength/parts)*curPart; } if (curPart > 0) { length += GenomeAlignerIndex::overlapSize; } return length; } void GenomeAlignerIndexTask::run() { QByteArray error; bool res = index->deserialize(error); if (settings.prebuiltIndex) { index->build = false; if (!res) { setError("Index file is corrupted. Try to create index another time."); return; } QString refName = baseFileName + QString(".") + GenomeAlignerIndex::REF_INDEX_EXTENSION; if (!QFile::exists(refName)) { setError(tr("File %1 is not found. Try to create index another time.").arg(refName)); return; } seqLength = index->seqLength; settings.seqPartSize = index->seqPartSize; } else { if (!res) { algoLog.details(error + " Index file is not defined. I will try to create a new index file."); } index->build = !(res && (index->seqPartSize == settings.seqPartSize)); if (!index->build) { index->build = !QFile::exists(baseFileName + QString(".") + GenomeAlignerIndex::REF_INDEX_EXTENSION); seqLength = index->seqLength; } if (index->build) { reformatSequence(); if (isCanceled() || hasError()) { return; } seqLength = objLens[objCount-1]; index->seqLength = seqLength; index->w = w; index->seqPartSize = settings.seqPartSize; } } MAX_ELEM_COUNT_IN_MEMORY = settings.seqPartSize*1024*1024; int parts = seqLength/(MAX_ELEM_COUNT_IN_MEMORY - 2*GenomeAlignerIndex::overlapSize) + 1; index->indexPart.partCount = parts; index->indexPart.seqStarts = new SAType[parts]; index->indexPart.seqLengths = new SAType[parts]; index->indexPart.saLengths = new SAType[parts]; index->indexPart.partFiles = new QFile*[parts]; SAType start = 0; SAType length = 0; for (int i=0; iindexPart.seqStarts[i] = start; index->indexPart.seqLengths[i] = length; index->indexPart.partFiles[i] = new QFile(baseFileName + "." + QByteArray::number(i) + "." + GenomeAlignerIndex::SARRAY_EXTENSION); if (!index->build) { if (!index->build && !index->indexPart.partFiles[i]->exists()) { if (settings.prebuiltIndex) { setError(tr("File %1 is not found. Try to create index another time.").arg(index->indexPart.partFiles[i]->fileName())); return; } index->build = true; } else { index->build = false; } } else { index->indexPart.partFiles[i]->remove(); } } if (!index->openIndexFiles()) { setError("Can't open some of index files"); return; } memFreeSize = MEM_FOR_READS*1024*1024; gpuFreeSize = memFreeSize; SAType maxLength = index->indexPart.getMaxLength(); try { index->indexPart.bitMask = new BMType[maxLength]; index->indexPart.sArray = new SAType[maxLength]; index->indexPart.seq = new char[maxLength]; } catch(std::bad_alloc e) { setError("Can't allocate this amount of memory. Try to close some of your programs or to decrease \"maxMemorySize\"-option"); return; } if (settings.justBuildIndex) { for (int i=0; ibuild = true; index->loadPart(i); index->indexPart.partFiles[i]->close(); stateInfo.progress += 100/parts; } } } void GenomeAlignerIndexTask::reformatSequence() { StreamSequenceReader seqReader; QList urls; urls.append(GUrl(settings.refFileName)); bool init = seqReader.init(urls); if (!init) { setError(tr("Can not init short reads loader. %1").arg(seqReader.getErrorMessage())); return; } objCount = 0; QList seqLens; QFile newRefFile(baseFileName + QString(".") + GenomeAlignerIndex::REF_INDEX_EXTENSION); newRefFile.open(QIODevice::WriteOnly); bool firstSeq = true; while (seqReader.hasNext()) { objCount++; const DNASequence *seq = seqReader.getNextSequenceObject(); if (NULL == seq) { setError("Reference object type must be a sequence, but not a multiple alignment"); return; } if (DNAAlphabet_NUCL != seq->alphabet->getType()) { setError("Unsupported file format: alphabet type is not NUCL"); return; } seqLens.append(seq->length()); newRefFile.write(seq->constData()); if (firstSeq) { index->seqObjName = seq->getName() + QString("_and_others"); firstSeq = false; } } newRefFile.close(); if (0 == objCount) { setError(QString("Unsupported file format or empty reference in %1").arg(settings.refFileName)); return; } index->objLens = new quint32[objCount]; index->objCount = objCount; objLens = index->objLens; int i = 0; quint32 prev = 0; foreach (quint32 len, seqLens) { objLens[i] = prev + len; prev = objLens[i]; i++; } } } //U2 ugene-1.9.8/src/plugins/genome_aligner/src/BuildSArraySettingsWidget.h0000644000175000017500000000270111651544323024547 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _DIST_BUILD_SARRAY_WIDGET_H_ #define _DIST_BUILD_SARRAY_WIDGET_H_ #include "ui/ui_BuildSuffixArraySettings.h" #include "U2View/DnaAssemblyGUIExtension.h" namespace U2{ class BuildSArraySettingsWidget : public DnaAssemblyAlgorithmBuildIndexWidget, Ui_BuildSuffixArraySettings { Q_OBJECT public: BuildSArraySettingsWidget(QWidget* parent); virtual QMap getBuildIndexCustomSettings(); virtual QString getIndexFileExtension(); virtual void buildIndexUrl(const GUrl& url); private slots: void sl_onPartSliderChanged(int value); private: int systemSize; }; } #endif ugene-1.9.8/src/plugins/genome_aligner/src/GenomeAlignerFindTask.h0000644000175000017500000000672311651544323023651 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_GENOME_ALIGNER_FIND_TASK_H_ #define _U2_GENOME_ALIGNER_FIND_TASK_H_ #include "GenomeAlignerSearchQuery.h" #include "GenomeAlignerWriteTask.h" #include #include #include #include #include #include #include #include #include #define BinarySearchResult qint64 namespace U2 { class GenomeAlignerIndex; class FindInPartSubTask; class PrepareVectorsSubTask; class AlignContext { public: AlignContext(): w(-1), ptMismatches(0), nMismatches(0), absMismatches(0), bestMode(false), openCL(false), useCUDA(0), minReadLength(-1), maxReadLength(-1), bitFilter(0), isReadingFinished(false) {} int w; int ptMismatches; int nMismatches; bool absMismatches; bool bestMode; bool openCL; bool useCUDA; int minReadLength; int maxReadLength; BMType bitFilter; QVector queries; QVector bitValuesV; QVector readNumbersV; QVector positionsAtReadV; bool isReadingFinished; bool isReadingStarted; QMutex listM; QWaitCondition alignerWait; }; #define MAX_PERCENTAGE 100 class GenomeAlignerFindTask : public Task { Q_OBJECT friend class ShortReadAligner; public: GenomeAlignerFindTask(GenomeAlignerIndex *i, AlignContext *s, GenomeAlignerWriteTask *writeTask); ~GenomeAlignerFindTask(); virtual void run(); virtual void prepare(); void loadPartForAligning(int part); void getDataForAligning(int &first, int &length); void waitDataForAligning(int &first, int &length); bool runOpenCLBinarySearch(); qint64 getIndexLoadTime() const {return indexLoadTime;} private: GenomeAlignerIndex *index; GenomeAlignerWriteTask *writeTask; AlignContext *alignContext; BinarySearchResult *bitMaskResults; int alignerTaskCount; int waiterCount; int nextElementToGive; qint64 indexLoadTime; bool partLoaded; bool openCLFinished; QMutex loadPartMutex; QMutex shortReadsMutex; QMutex waitMutex; QWaitCondition waiter; QMutex openCLMutex; void unsafeGetData(int &first, int &length); static const int ALIGN_DATA_SIZE; }; typedef QVector::iterator QueryIter; class ShortReadAligner : public Task { Q_OBJECT public: ShortReadAligner(GenomeAlignerIndex *index, AlignContext *alignContext, GenomeAlignerWriteTask *writeTask); virtual void run(); private: GenomeAlignerIndex *index; AlignContext *alignContext; GenomeAlignerWriteTask *writeTask; }; } //U2 #endif // _U2_GENOME_ALIGNER_FIND_TASK_H_ ugene-1.9.8/src/plugins/genome_aligner/src/ui/0000755000175000017500000000000011651544323017745 5ustar ilyailyaugene-1.9.8/src/plugins/genome_aligner/src/ui/BuildSuffixArraySettings.ui0000644000175000017500000001113711651544323025253 0ustar ilyailya BuildSuffixArraySettings 0 0 194 127 Reference fragmentation <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> <html><head><meta name="qrichtext" content="1" /><style type="text/css"> p, li { white-space: pre-wrap; } </style></head><body style=" font-family:'MS Shell Dlg 2'; font-size:8.25pt; font-weight:400; font-style:normal;"> <p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-size:8pt;">This parameter influences on the amount of parts the reference will be divided. It is better to make it bigger, but it influences on the amount of memory used during the aligning.</span></p></body></html> Qt::Horizontal 50 0 50 16777215 Qt::Horizontal 40 20 Total memory usage: 61 0 61 16777215 Qt::Horizontal 40 20 System memory size: 61 0 61 16777215 ugene-1.9.8/src/plugins/genome_aligner/src/ui/GenomeAlignerSettings.ui0000644000175000017500000005543211651544323024552 0ustar ilyailya GenomeAlignerSettings 0 0 317 285 Form 0 Common parameters Chech this box if mismatches between the reference sequence and the reads are allowed. Mismatches allowed true false Select the number of mismatched nucleotides allowed. Mismatches number true Qt::Horizontal 40 20 Select the number of mismatched nucleotides allowed. 1 3 Select the percentage of mismatches allowed. Note, that absolute number of mismatches can vary for different reads. Percentage of mismatches Qt::Horizontal 40 20 false Select the percentage of mismatches allowed. Note, that absolute number of mismatches can vary for different reads. 1 10 0 129 Set short reads aligning options. Align options true Use both the read and its reverse complement during aligning. Align reverse complement reads false <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> <html><head><meta name="qrichtext" content="1" /><style type="text/css"> p, li { white-space: pre-wrap; } </style></head><body style=" font-family:'MS Shell Dlg 2'; font-size:8.25pt; font-weight:400; font-style:normal;"> <p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-size:8pt;">Report only about best alignments (in terms of mismatches).</span></p></body></html> Use "best"-mode during the aligning true Omit reads with qualities lower than the specified value. Reads that have no qualities are not omited. Omit reads with qualities lower than Qt::Horizontal 40 20 false Omit reads with qualities lower than the specified value. Reads that have no qualities are not omited. 1 70 20 Use an openCL-enabled GPU during the aligning. Use GPU-optimization Qt::Vertical 20 0 Advanced parameters Maximum memory for short reads: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> <html><head><meta name="qrichtext" content="1" /><style type="text/css"> p, li { white-space: pre-wrap; } </style></head><body style=" font-family:'MS Shell Dlg 2'; font-size:8.25pt; font-weight:400; font-style:normal;"> <p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-size:8pt;">You can change the amount of memory that will be used for keeping short-reads during the aligning. It is better to make it bigger.</span></p></body></html> Qt::Horizontal 50 0 50 16777215 Qt::Horizontal 40 20 Total memory usage: 61 0 61 16777215 Qt::Horizontal 40 20 System memory size: 61 0 61 16777215 Qt::Vertical 20 0 Index parameters Reference fragmentation <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> <html><head><meta name="qrichtext" content="1" /><style type="text/css"> p, li { white-space: pre-wrap; } </style></head><body style=" font-family:'MS Shell Dlg 2'; font-size:8.25pt; font-weight:400; font-style:normal;"> <p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-size:8pt;">This parameter influences on the amount of parts the reference will be divided. It is better to make it bigger, but it influences on the amount of memory used during the aligning.</span></p></body></html> Qt::Horizontal 50 0 50 16777215 Qt::Horizontal 40 20 Index memory usage size: 50 0 50 16777215 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> <html><head><meta name="qrichtext" content="1" /><style type="text/css"> p, li { white-space: pre-wrap; } </style></head><body style=" font-family:'MS Shell Dlg 2'; font-size:8.25pt; font-weight:400; font-style:normal;"> <p align="justify" style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-size:8pt;">You can choose a temporary directory for saving index files for the reference that will be built during the aligning. If you need to run this algorithm another time with the </span><span style=" font-size:8pt; font-weight:600;">equal reference</span><span style=" font-size:8pt;"> and with the </span><span style=" font-size:8pt; font-weight:600;">equal reference fragmentation parameter </span><span style=" font-size:8pt;">you can use this prebuilt index that will be located at this temporary directory.</span></p></body></html> Qt::AutoText false true ... Specify an index to build during execution of the selected short reads aligning algorithm. If this option is selected, the value is <b>required</b>. true Directory for index files: Qt::Vertical 20 0 omitQualitiesBox toggled(bool) qualThresholdBox setEnabled(bool) 226 243 376 244 absRadioButton toggled(bool) mismatchesAllowedSpinBox setEnabled(bool) 174 70 338 76 percentRadioButton toggled(bool) percentMismatchesAllowedSpinBox setEnabled(bool) 164 104 335 103 ugene-1.9.8/src/plugins/genome_aligner/src/SuffixSearchCUDA.h0000644000175000017500000000367011651544323022536 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_SUFFIX_SEARCH_CUDA_H_ #define _U2_SUFFIX_SEARCH_CUDA_H_ #include #include namespace U2 { #ifdef GA_BUILD_WITH_CUDA class SuffixSearchCUDA { public: SuffixSearchCUDA() {} quint64* runSearch(const quint64* _numbers, const int _numbersSize, const quint64* _findNumbers, const int _findNumbersSize, quint64 filter); private: quint64 *numbersListDev, *queryListDev; }; #endif class AlignContext; class IndexPart; class SearchQuery; class TaskStateInfo; class GenomeAlignerCUDAHelper { public: GenomeAlignerCUDAHelper( ); ~GenomeAlignerCUDAHelper(); void loadShortReads(QVector& queries,TaskStateInfo& stateInfo); void alignReads(IndexPart& indexPart, AlignContext* context, TaskStateInfo& stateInfo); qint64 estimateMemoryUsage(); private: int bufSizeMB; int readsNumber, suffixSize, seqSize; // device data char* seqDev, *readsDev; int *readSizesDev,*readOffsetsDev; quint32 *results, *resultsDev, *sArrayDev; quint64 *bmArrayDev; }; } //namespace #endif //_U2_SUFFIX_SEARCH_CUDA_H_ ugene-1.9.8/src/plugins/genome_aligner/src/GenomeAlignerWriteTask.cpp0000644000175000017500000000607311651544323024414 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "GenomeAlignerWriteTask.h" namespace U2 { GenomeAlignerWriteTask::GenomeAlignerWriteTask(GenomeAlignerWriter *s) : Task("WriteAlignedReadsSubTask", TaskFlag_None), seqWriter(s), end(false), writing(false), readsWritten(0) { } void GenomeAlignerWriteTask::setSeqWriter(GenomeAlignerWriter *seqWriter) { this->seqWriter = seqWriter; } void GenomeAlignerWriteTask::addResult(SearchQuery *qu) { listMutex.lock(); WriteData data; foreach (SAType offset, qu->getResults()) { data.qu = qu; data.offset = offset; results.append(data); } if (!writing && results.size() > 1000) { writing = true; waiter.wakeAll(); } listMutex.unlock(); } void GenomeAlignerWriteTask::setFinished() { end = true; waiter.wakeAll(); } void GenomeAlignerWriteTask::flush() { try { writeMutex.lock(); foreach (WriteData data, results) { seqWriter->write(data.qu, data.offset); setReadWritten(data.qu, data.qu->getRevCompl()); } results.clear(); writeMutex.unlock(); } catch (QString exeptionMessage) { setError(exeptionMessage); } } void GenomeAlignerWriteTask::run() { stateInfo.setProgress(0); try { do { waitMutex.lock(); writing = false; waiter.wait(&waitMutex); if (end) { writing = false; break; } QVector newResults; listMutex.lock(); newResults += (results); results.clear(); listMutex.unlock(); waitMutex.unlock(); writeMutex.lock(); foreach (WriteData data, newResults) { seqWriter->write(data.qu, data.offset); setReadWritten(data.qu, data.qu->getRevCompl()); } writeMutex.unlock(); } while (!end); } catch (QString exeptionMessage) { setError(exeptionMessage); } } void GenomeAlignerWriteTask::setReadWritten(SearchQuery *read, SearchQuery *revCompl) { if (!read->isWroteResult()) { readsWritten++; read->writeResult(); if (NULL != revCompl) { revCompl->writeResult(); } } } } // U2 ugene-1.9.8/src/plugins/genome_aligner/src/GenomeAlignerTask.cpp0000644000175000017500000004701111651544323023376 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "GenomeAlignerFindTask.h" #include "GenomeAlignerIndexTask.h" #include "GenomeAlignerIndex.h" #include "SuffixSearchCUDA.h" #include "GenomeAlignerTask.h" namespace U2 { const QString GenomeAlignerTask::taskName(tr("UGENE genome aligner")); const QString GenomeAlignerTask::OPTION_READS_READER("rreader"); const QString GenomeAlignerTask::OPTION_READS_WRITER("rwriter"); const QString GenomeAlignerTask::OPTION_ALIGN_REVERSED("align_reversed"); const QString GenomeAlignerTask::OPTION_OPENCL("use_gpu_optimization"); const QString GenomeAlignerTask::OPTION_USE_CUDA("use_cuda"); const QString GenomeAlignerTask::OPTION_IF_ABS_MISMATCHES("if_absolute_mismatches_value"); const QString GenomeAlignerTask::OPTION_MISMATCHES("mismatches_allowed"); const QString GenomeAlignerTask::OPTION_PERCENTAGE_MISMATCHES("mismatches_percentage_allowed"); const QString GenomeAlignerTask::OPTION_INDEX_DIR("dir_of_the_index_file"); const QString GenomeAlignerTask::OPTION_BEST("best_mode"); const QString GenomeAlignerTask::OPTION_DBI_IO("dbi_io"); const QString GenomeAlignerTask::OPTION_QUAL_THRESHOLD("quality_threshold"); const QString GenomeAlignerTask::OPTION_READS_MEMORY_SIZE("reads_mem_size"); const QString GenomeAlignerTask::OPTION_SEQ_PART_SIZE("seq_part_size"); GenomeAlignerTask::GenomeAlignerTask( const DnaAssemblyToRefTaskSettings& settings, bool _justBuildIndex ) : DnaAssemblyToReferenceTask(settings, TaskFlags_NR_FOSCOE | TaskFlag_ReportingIsSupported | TaskFlag_ReportingIsEnabled, _justBuildIndex), loadDbiTask(NULL), createIndexTask(NULL), readTask(NULL), findTask(NULL), writeTask(NULL), pWriteTask(NULL), seqReader(NULL), seqWriter(NULL), justBuildIndex(_justBuildIndex), bunchSize(0), index(NULL), lastQuery(NULL) { GCOUNTER(cvar,tvar, "GenomeAlignerTask"); setMaxParallelSubtasks(3); haveResults = true; readsCount = 0; readsAligned = 0; shortreadLoadTime = 0; resultWriteTime = 0; searchTime = 0; indexLoadTime = 0; shortreadIOTime = 0; currentProgress = 0.0f; noDataToAlign = false; alignReversed = settings.getCustomValue(OPTION_ALIGN_REVERSED, true).toBool(); alignContext.openCL = settings.getCustomValue(OPTION_OPENCL, false).toBool(); alignContext.useCUDA = settings.getCustomValue(OPTION_USE_CUDA, false).toBool(); alignContext.absMismatches = settings.getCustomValue(OPTION_IF_ABS_MISMATCHES, true).toBool(); alignContext.nMismatches = settings.getCustomValue(OPTION_MISMATCHES, 0).toInt(); alignContext.ptMismatches = settings.getCustomValue(OPTION_PERCENTAGE_MISMATCHES, 0).toInt(); qualityThreshold = settings.getCustomValue(OPTION_QUAL_THRESHOLD, 0).toInt(); alignContext.bestMode = settings.getCustomValue(OPTION_BEST, false).toBool(); seqPartSize = settings.getCustomValue(OPTION_SEQ_PART_SIZE, 10).toInt(); readMemSize = settings.getCustomValue(OPTION_READS_MEMORY_SIZE, 10).toInt(); prebuiltIndex = settings.prebuiltIndex; if (settings.indexFileName.isEmpty()) { if (prebuiltIndex) { indexFileName = settings.refSeqUrl.dirPath() + "/" + settings.refSeqUrl.baseFileName(); } else { QString tempDir = AppContext::getAppSettings()->getUserAppsSettings()->getTemporaryDirPath(); QString indexDir = settings.getCustomValue(OPTION_INDEX_DIR, tempDir).toString(); indexFileName = indexDir + "/" + settings.refSeqUrl.baseFileName() + "." + GenomeAlignerIndex::HEADER_EXTENSION; } } else { indexFileName = settings.indexFileName; } taskLog.details(tr("Genome Aligner settings")); taskLog.details(tr("Index file name: %1").arg(indexFileName)); taskLog.details(tr("Use prebuilt index: %2").arg(prebuiltIndex)); qint64 memUseMB = seqPartSize*13; if (!justBuildIndex) { memUseMB += readMemSize; } addTaskResource(TaskResourceUsage(RESOURCE_MEMORY, memUseMB, true)); if (alignContext.openCL) { addTaskResource(TaskResourceUsage(RESOURCE_OPENCL_GPU, 1, true)); } else if (alignContext.useCUDA) { addTaskResource(TaskResourceUsage(RESOURCE_CUDA_GPU, 1 ,true)); } } GenomeAlignerTask::~GenomeAlignerTask() { qDeleteAll(alignContext.queries); delete index; } void GenomeAlignerTask::prepare() { setupCreateIndexTask(); addSubTask(createIndexTask); if (!justBuildIndex && !alignContext.bestMode) { pWriteTask = new GenomeAlignerWriteTask(seqWriter); pWriteTask->setSubtaskProgressWeight(0.0f); addSubTask(pWriteTask); } } QList GenomeAlignerTask::onSubTaskFinished( Task* subTask ) { QList subTasks; if (hasError() || isCanceled()) { if (!justBuildIndex && !alignContext.bestMode) { pWriteTask->setFinished(); } return subTasks; } assert(createIndexTask != NULL); if (justBuildIndex) { return subTasks; } qint64 time=(subTask->getTimeInfo().finishTime - subTask->getTimeInfo().startTime); if (subTask == createIndexTask) { index = createIndexTask->index; seqReader = settings.getCustomValue(OPTION_READS_READER, qVariantFromValue(GenomeAlignerReaderContainer())) .value().reader; if (NULL == seqReader) { seqReader = new GenomeAlignerUrlReader(settings.shortReadUrls); } if (seqReader->isEnd()) { setError(tr("Can not init short reads loader.")); return subTasks; } seqWriter = settings.getCustomValue(OPTION_READS_WRITER, qVariantFromValue(GenomeAlignerWriterContainer())) .value().writer; if (NULL == seqWriter) { if (settings.samOutput) { seqWriter = new GenomeAlignerUrlWriter(settings.resultFileName, index->getSeqName(), index->getSeqLength()); } else { try { seqWriter = new GenomeAlignerDbiWriter(settings.resultFileName.getURLString(), index->getSeqName(), index->getSeqLength()); } catch (QString exeptionMessage) { setError(exeptionMessage); return subTasks; } } } seqWriter->setReferenceName(index->getSeqName()); if (!alignContext.bestMode) { pWriteTask->setSeqWriter(seqWriter); } taskLog.details(QString("Genome aligner index creation time: %1").arg((double)time/(1000*1000))); } if (subTask == findTask) { taskLog.details(QString("Bunch of reads aligning time: %1").arg((double)time/(1000*1000))); indexLoadTime += findTask->getIndexLoadTime(); if (alignContext.bestMode) { writeTask = new WriteAlignedReadsSubTask(seqWriter, alignContext.queries, readsAligned); writeTask->setSubtaskProgressWeight(0.0f); subTasks.append(writeTask); return subTasks; } } if (subTask == readTask) { shortreadLoadTime += time; shortreadIOTime += time; if (alignContext.queries.count() == 0) { // no more reads to align if (!alignContext.bestMode) { pWriteTask->setFinished(); } seqWriter->close(); noDataToAlign = true; return subTasks; } readsCount += readTask->bunchSize; taskLog.details(QString("Reading (and complementing) of %1 short-reads time: %2") .arg(readTask->bunchSize).arg((double)time/(1000*1000))); /*findTask = new GenomeAlignerFindTask(index, &alignContext, pWriteTask); findTask->setSubtaskProgressWeight(0.0f); subTasks.append(findTask); findTask->setSubtaskProgressWeight(seqReader->getProgress()/100.0f - currentProgress); currentProgress = seqReader->getProgress()/100.0f;*/ } if (subTask == createIndexTask || subTask == findTask || subTask == writeTask) { if (subTask == writeTask) { resultWriteTime += time; shortreadIOTime += time; } if (!noDataToAlign) { alignContext.isReadingStarted = false; alignContext.isReadingFinished = false; alignContext.minReadLength = INT_MAX; alignContext.maxReadLength = 0; readTask = new ReadShortReadsSubTask(&lastQuery, seqReader, settings, alignContext, readMemSize*1024*1024); readTask->setSubtaskProgressWeight(0.0f); subTasks.append(readTask); findTask = new GenomeAlignerFindTask(index, &alignContext, pWriteTask); findTask->setSubtaskProgressWeight(0.0f); subTasks.append(findTask); } return subTasks; } return subTasks; } static bool isDnaQualityAboveThreshold(const DNAQuality &dna, int threshold) { assert(!dna.isEmpty()); for (int i = 0; i < dna.qualCodes.length(); ++i) { int qValue = dna.getValue(i); if (qValue < threshold) { return false; } } return true; } void GenomeAlignerTask::setupCreateIndexTask() { GenomeAlignerIndexSettings s; s.refFileName = settings.refSeqUrl.getURLString(); s.indexFileName = indexFileName; s.justBuildIndex = justBuildIndex; s.seqPartSize = seqPartSize; s.prebuiltIndex = prebuiltIndex; createIndexTask = new GenomeAlignerIndexTask(s); if (justBuildIndex) { createIndexTask->setSubtaskProgressWeight(1.0f); } else { createIndexTask->setSubtaskProgressWeight(0.0f); } } Task::ReportResult GenomeAlignerTask::report() { TaskTimeInfo inf=getTimeInfo(); if (hasError()) { return ReportResult_Finished; } if (justBuildIndex) { return ReportResult_Finished; } if (seqWriter->getWrittenReadsCount() == 0) { haveResults = false; return ReportResult_Finished; } if (readsCount > 0) { taskLog.info(tr("The aligning is finished.")); taskLog.info(tr("Whole working time = %1.").arg((GTimer::currentTimeMicros() - inf.startTime)/(1000*1000))); if (alignContext.bestMode) { taskLog.info(tr("%1% reads aligned.").arg(100*(double)readsAligned/readsCount)); taskLog.info(tr("Short-reads loading time = %1").arg(shortreadLoadTime/(1000*1000))); taskLog.info(tr("Results writing time = %1").arg(resultWriteTime/(1000*1000))); } else { taskLog.info(tr("%1% reads aligned.").arg(100*(double)pWriteTask->getWrittenReadsCount()/readsCount)); } taskLog.info(tr("Index loading time = %1").arg(indexLoadTime)); taskLog.info(tr("Short-reads IO time = %1").arg(shortreadIOTime/(1000*1000))); } return ReportResult_Finished; } int GenomeAlignerTask::calculateWindowSize(bool absMismatches, int nMismatches, int ptMismatches, int minReadLength, int maxReadLength) { int CMAX = nMismatches; int windowSize = MAX_BIT_MASK_LENGTH; int q = 0; for (int len = minReadLength; len <= maxReadLength; len++) { if (!absMismatches) { CMAX = len*ptMismatches/MAX_PERCENTAGE; } q = len/(CMAX + 1); if (windowSize > q) { windowSize = q; } } return windowSize; } QString GenomeAlignerTask::getIndexPath() { return indexFileName; } #define ALIGN_DATA_SIZE 1000 ReadShortReadsSubTask::ReadShortReadsSubTask(SearchQuery **_lastQuery, GenomeAlignerReader *_seqReader, const DnaAssemblyToRefTaskSettings &_settings, AlignContext &_alignContext, quint64 m) : Task("ReadShortReadsSubTask", TaskFlag_None), lastQuery(_lastQuery), seqReader(_seqReader), settings(_settings), alignContext(_alignContext), freeMemorySize(m) { minReadLength = INT_MAX; maxReadLength = 0; } void ReadShortReadsSubTask::run() { stateInfo.setProgress(0); GTIMER(cvar, tvar, "ReadSubTask"); GenomeAlignerTask *parent = static_cast(getParentTask()); if (!alignContext.bestMode) { parent->pWriteTask->flush(); } foreach (SearchQuery *qu, alignContext.queries) { delete qu; } if (isCanceled()) { return; } alignContext.queries.clear(); alignContext.bitValuesV.clear(); alignContext.readNumbersV.clear(); alignContext.positionsAtReadV.clear(); bunchSize = 0; qint64 m = freeMemorySize; taskLog.details(QString("Memory size is %1").arg(m)); bool alignReversed = settings.getCustomValue(GenomeAlignerTask::OPTION_ALIGN_REVERSED, true).toBool(); int qualityThreshold = settings.getCustomValue(GenomeAlignerTask::OPTION_QUAL_THRESHOLD, 0).toInt(); //int s = sizeof(SearchQuery); int n = 0; int CMAX = alignContext.nMismatches; int W = 0; int q = 0; int readNum = 0; int alignBunchSize = 0; DNATranslation* transl = AppContext::getDNATranslationRegistry()-> lookupTranslation(BaseDNATranslationIds::NUCL_DNA_DEFAULT_COMPLEMENT); alignContext.isReadingStarted = true; while(!seqReader->isEnd()) { SearchQuery *query = NULL; if (NULL == *lastQuery) { query = seqReader->read(); } else { query = *lastQuery; } if (NULL == query) { if (!seqReader->isEnd()) { setError("Short-reads object type must be a sequence, but not a multiple alignment"); return; } break; } if ( qualityThreshold > 0 && query->hasQuality() ) { // simple quality filtering bool ok = isDnaQualityAboveThreshold(query->getQuality(), qualityThreshold); if (!ok) { continue; } } if (GenomeAlignerTask::MIN_SHORT_READ_LENGTH <= query->length()) { if (alignContext.minReadLength > query->length()) { alignContext.minReadLength = query->length(); } if (alignContext.maxReadLength < query->length()) { alignContext.maxReadLength = query->length(); } } n = alignContext.absMismatches ? alignContext.nMismatches+1 : (query->length()*alignContext.ptMismatches/100)+1; if (alignReversed) { m -= 2*(n*24 + sizeof(SearchQuery) + ONE_SEARCH_QUERY_SIZE + query->length() + query->getNameLength()); // 2*(long long + int) == 24 alignBunchSize += 2; } else { m -= n*24 + sizeof(SearchQuery) + ONE_SEARCH_QUERY_SIZE + query->length() + query->getNameLength(); alignBunchSize++; } if (m<=0) { delete *lastQuery; *lastQuery = query; break; } if (!add(CMAX, W, q, readNum, query, parent)) { delete query; continue; } ++bunchSize; *lastQuery = NULL; if (alignReversed) { QByteArray reversed(query->constSequence()); TextUtils::reverse(reversed.data(), reversed.count()); SearchQuery *rQu = new SearchQuery(new DNASequence(QString("%1_rev").arg(query->getName()), reversed, NULL), query); transl->translate(const_cast(rQu->constData()), rQu->length()); if (rQu->constSequence() != query->constSequence()) { query->setRevCompl(rQu); add(CMAX, W, q, readNum, rQu, parent); } else { delete rQu; } } if (alignBunchSize > ALIGN_DATA_SIZE) { alignContext.alignerWait.wakeAll(); } } alignContext.isReadingFinished = true; alignContext.alignerWait.wakeAll(); } inline bool ReadShortReadsSubTask::add(int &CMAX, int &W, int &q, int &readNum, SearchQuery *query, GenomeAlignerTask *parent) { QMutexLocker lock(&alignContext.listM); W = query->length(); if (!alignContext.absMismatches) { CMAX = (W * alignContext.ptMismatches) / MAX_PERCENTAGE; } q = W / (CMAX + 1); if (0 == q) { return false; } const char* querySeq = query->constData(); for (int i = 0; i < W - q + 1; i+=q) { const char *seq = querySeq + i; BMType bv = parent->index->getBitValue(seq, qMin(GenomeAlignerIndex::charsInMask, W - i)); alignContext.bitValuesV.push_back(bv); alignContext.readNumbersV.push_back(readNum); alignContext.positionsAtReadV.push_back(i); } readNum++; alignContext.queries.append(query); return true; } WriteAlignedReadsSubTask::WriteAlignedReadsSubTask(GenomeAlignerWriter *_seqWriter, QVector &_queries, quint64 &r) : Task("WriteAlignedReadsSubTask", TaskFlag_None), seqWriter(_seqWriter), queries(_queries), readsAligned(r) { } void WriteAlignedReadsSubTask::setReadWritten(SearchQuery *read, SearchQuery *revCompl) { if (!read->isWroteResult()) { readsAligned++; read->writeResult(); if (NULL != revCompl) { revCompl->writeResult(); } } } void WriteAlignedReadsSubTask::run() { stateInfo.setProgress(0); SearchQuery *read = NULL; SearchQuery *revCompl = NULL; SearchQuery **q = queries.data(); int size = queries.size(); try { for (int i=0; igetRevCompl(); if (ihaveResult()) { seqWriter->write(read, read->firstResult()); readsAligned++; } else if (NULL != revCompl) { int c = read->firstMCount(); int cRev = revCompl->firstMCount(); if (c <= cRev && c < INT_MAX) { seqWriter->write(read, read->firstResult()); readsAligned++; } else if (cRev < INT_MAX) { seqWriter->write(revCompl, revCompl->firstResult()); readsAligned++; } } } } catch (QString exeptionMessage) { setError(exeptionMessage); return; } } } // U2 ugene-1.9.8/src/plugins/genome_aligner/src/GenomeAlignerCMDLineTask.cpp0000644000175000017500000002051711651544323024534 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include #include #include #include "GenomeAlignerTask.h" #include "GenomeAlignerCMDLineTask.h" namespace U2 { #define OPTION_INDEX_PATH "index" #define OPTION_SHORTREADS "short-reads" #define OPTION_RESULT "result" #define OPTION_BUILD_INDEX "build-index" #define OPTION_REFERENCE "reference" #define OPTION_MEMSIZE "memsize" #define OPTION_CUDA "use-cuda" #define OPTION_USE_OPENCL "use-opencl" #define OPTION_REF_FRAG "ref-size" #define OPTION_N_MISMATHES "n-mis" #define OPTION_PT_MISMATHES "pt-mis" #define OPTION_REVERSE "rev-comp" #define OPTION_BEST_MODE "best" #define OPTION_OMIT "omit-size" #define OPTION_SAM "sam" GenomeAlignerCMDLineTask::GenomeAlignerCMDLineTask() :Task( tr( "Run genome aligner from command line" ), TaskFlags_NR_FOSCOE), onlyBuildIndex(false) { mismatchCount = 0; ptMismatchCount = 0; memSize = 1000; refSize = 10; qualityThreshold = 0; useCuda = false; useOpenCL = false; alignRevCompl = false; bestMode = false; onlyBuildIndex = false; samOutput = false; // parse options QList options = AppContext::getCMDLineRegistry()->getParameters(); foreach (const StringPair& opt, options ) { if (opt.first == OPTION_INDEX_PATH ) { indexPath = opt.second; }else if (opt.first == OPTION_BUILD_INDEX ) { onlyBuildIndex = true; } else if (opt.first == OPTION_REFERENCE) { refPath = opt.second; } else if (opt.first == OPTION_RESULT) { resultPath = opt.second; } else if (opt.first == OPTION_SHORTREADS) { QStringList urls = opt.second.split(";"); foreach(const QString& url, urls) { shortReadUrls.append(url); } } else if (opt.first == OPTION_CUDA) { useCuda = true; useOpenCL = false; } else if (opt.first == OPTION_USE_OPENCL) { useOpenCL = true; useCuda = false; } else if (opt.first == OPTION_REF_FRAG) { refSize = opt.second.toInt(); assert(refSize != 0); if (refSize == 0) { refSize = 10; } } else if (opt.first == OPTION_N_MISMATHES) { mismatchCount = opt.second.toInt(); ptMismatchCount = 0; if (mismatchCount<0) { mismatchCount = 0; } } else if (opt.first == OPTION_PT_MISMATHES) { ptMismatchCount = opt.second.toInt(); mismatchCount = 0; if (ptMismatchCount<0) { ptMismatchCount = 0; } } else if (opt.first == OPTION_REVERSE) { alignRevCompl = true; } else if (opt.first == OPTION_MEMSIZE) { memSize = opt.second.toInt(); } else if (opt.first == OPTION_BEST_MODE) { bestMode = true; } else if (opt.first == OPTION_OMIT) { qualityThreshold = opt.second.toInt(); if (qualityThreshold<0) { qualityThreshold = 0; } } else if (opt.first == OPTION_SAM) { samOutput = true; } } coreLog.info( tr( "Finished parsing genome aligner options." ) ); } GenomeAlignerCMDLineTask::~GenomeAlignerCMDLineTask() { // clean up resources } void GenomeAlignerCMDLineTask::prepare() { if (onlyBuildIndex && refPath.isEmpty()) { setError(tr("Path to reference sequence is not set.")); return; } if (!onlyBuildIndex) { if ( shortReadUrls.isEmpty() ) { setError(tr("Short reads list is empty.")); return; } else { if (refPath.isEmpty() && indexPath.isEmpty()) { setError(tr("Reference (index or sequence) is not set.")); return; } } } if (resultPath.isEmpty()) { resultPath = QDir::current().path() + "/output.sam"; } settings.resultFileName = resultPath; settings.shortReadUrls = shortReadUrls; settings.refSeqUrl = refPath; settings.indexFileName = indexPath; settings.openView = false; settings.samOutput = samOutput; if (onlyBuildIndex) { settings.prebuiltIndex = false; } else { settings.prebuiltIndex = !indexPath.isEmpty(); } settings.setCustomValue(GenomeAlignerTask::OPTION_READS_MEMORY_SIZE, memSize); settings.setCustomValue(GenomeAlignerTask::OPTION_ALIGN_REVERSED, alignRevCompl); settings.setCustomValue(GenomeAlignerTask::OPTION_USE_CUDA, useCuda); settings.setCustomValue(GenomeAlignerTask::OPTION_OPENCL, useOpenCL); settings.setCustomValue(GenomeAlignerTask::OPTION_SEQ_PART_SIZE, refSize); settings.setCustomValue(GenomeAlignerTask::OPTION_IF_ABS_MISMATCHES, ptMismatchCount == 0); settings.setCustomValue(GenomeAlignerTask::OPTION_MISMATCHES, mismatchCount); settings.setCustomValue(GenomeAlignerTask::OPTION_PERCENTAGE_MISMATCHES, ptMismatchCount); settings.setCustomValue(GenomeAlignerTask::OPTION_BEST, bestMode); settings.setCustomValue(GenomeAlignerTask::OPTION_QUAL_THRESHOLD, qualityThreshold); GenomeAlignerTask* task = new GenomeAlignerTask(settings, onlyBuildIndex); addSubTask(task); } QString GenomeAlignerCMDLineTask::getArgumentsDescritption() { QString desc; int fieldSize = -11; desc += tr(" --%1 Use this flag to only build index for reference sequence.\n\n").arg(OPTION_BUILD_INDEX, fieldSize); desc += tr(" --%1 Path to reference genome sequence\n\n").arg(OPTION_REFERENCE, fieldSize); desc += tr(" --%1 Path to short-reads data in FASTA or FASTQ format\n\n").arg(OPTION_SHORTREADS, fieldSize); desc += tr(" --%1 Path to prebuilt index (base file name or with .idx extension). If not set, index is searched in system temporary directory. If --build-index option is applied, index will be saved to specified path.\n\n").arg(OPTION_INDEX_PATH, fieldSize); desc += tr(" --%1 Path to output alignment in UGENEDB or SAM format (see --%2)\n\n").arg(OPTION_RESULT, fieldSize).arg(OPTION_SAM); desc += tr(" --%1 Memory size (in Mbs) reserved for short-reads. The bigger value the faster algorithm works. Default value depends on available system memory.\n\n").arg(OPTION_MEMSIZE, fieldSize); desc += tr(" --%1 Index fragmentation size (in Mbs). Small fragments better fit into RAM, allowing to load more short reads. Default value is 10.\n\n").arg(OPTION_REF_FRAG, fieldSize); desc += tr(" --%1 Absolute amount of allowed mismatches per every short-read (mutually exclusive with --%2). Default value is 0.\n\n").arg(OPTION_N_MISMATHES, fieldSize).arg(OPTION_PT_MISMATHES); desc += tr(" --%1 Percentage amount of allowed mismatches per every short-read (mutually exclusive with --%2). Default value is 0.\n\n").arg(OPTION_PT_MISMATHES, fieldSize).arg(OPTION_N_MISMATHES); desc += tr(" --%1 Use both the read and its reverse complement during the aligning.\n\n").arg(OPTION_REVERSE, fieldSize); desc += tr(" --%1 Report only about best alignments (in terms of mismatches).\n\n").arg(OPTION_BEST_MODE, fieldSize); desc += tr(" --%1 Omit reads with qualities lower than the specified value. Reads which have no qualities are not omitted. Default value is 0.\n\n").arg(OPTION_OMIT, fieldSize); desc += tr(" --%1 Output aligned reads in SAM format. Default value is false.\n\n").arg(OPTION_SAM, fieldSize); return desc; } }//namespace ugene-1.9.8/src/plugins/genome_aligner/src/suffix_search.cu0000644000175000017500000002021011651544323022505 0ustar ilyailya#include //#include "cuPrintf.cu" typedef unsigned long long BMType; typedef unsigned int SAType; __global__ void binarySearch(BMType array[], int arraySize, BMType query[], int querySize) { unsigned int threadId = blockIdx.x * blockDim.x + threadIdx.x; int left = 0; int right = arraySize - 1; const BMType target = query[threadId]; while (left <= right) { int mid = (left + right) >> 1; BMType midValue = array[mid]; if(midValue > target) { right = mid - 1; } else if(midValue < target) { left = mid + 1; } else { for (mid = mid - 1; mid >= 0; --mid ) { if (array[mid] != target) { break; } } query[threadId] = mid + 1; return; } } query[threadId] = -1; } extern "C" void cudaBinarySearch(BMType* array, int arraySize, BMType* query, int querySize ) { printf("Starting binary search...\n"); binarySearch <<>> (array, arraySize, query, querySize); cudaThreadSynchronize(); printf("Binary search is finished...\n"); } struct ShortReads { char* data; int* offsets; int* sizes; int count; }; struct BMArray { BMType* data; int size; }; struct SArray { SAType* data; int size; }; struct AlgSettings { BMType bitFilter; int refStartPos; int loadedPartSize; int CMAX; int w; }; __device__ int lowerBound(BMType* bmArray, int bmArraySize, BMType target, BMType bitFilter) { int left = 0; int right = bmArraySize - 1; int result = -1; while (left <= right) { int mid = (left + right) >> 1; long long rc = (bmArray[mid]&bitFilter) - (target&bitFilter); if(rc > 0) { right = mid - 1; } else if(rc < 0) { left = mid + 1; } else { for (mid = mid - 1; mid >= 0; --mid ) { if ((bmArray[mid]&bitFilter) != (target&bitFilter)) { break; } } result = mid + 1; break; } } return result; } __device__ BMType calcBitValue(char* readsData, int readOffset, int length, int charsInMask, SAType* bitTable) { const int bitCharLen = 2; BMType bitValue = 0; //cuPrintf("L = %d, charsInMask = %d\n",length,charsInMask); //cuPrintf("bw=%ullx\n", bitValue); for (int i = 0; i < length; i++) { char c = readsData[readOffset+i]; //cuPrintf("C=%c\n",c); //cuPrintf("bw=%llx\n", bitValue); bitValue = (bitValue << bitCharLen) | bitTable[c - 65]; } bitValue <<= 2*charsInMask - bitCharLen*length; return bitValue; } __device__ void initBitTable(SAType* bitTable) { bitTable['A' - 65] = 0x0; //00 bitTable['C' - 65] = 0x1; //01 bitTable['T' - 65] = 0x2; //10 bitTable['G' - 65] = 0x3; //11 } __device__ bool compare(const char *sourceSeq, const char *querySeq, int startPos, int w, int& c, int CMAX, int length) { // forward collect for (int i=startPos+w; iCMAX) { return false; } // backward collect for (int i=startPos-1; i>=0 && c <= CMAX; i--) { char c1 = querySeq[i]; char c2 = sourceSeq[i]; c += (c1 == c2) ? 0 : 1; //cuPrintf("B: %c %c pos=%d\n",c1,c2,i); } if (c <= CMAX) { return true; } return false; } __global__ void alignReadsKernel(ShortReads reads, char* refSeq, int refSeqSize, SArray sArray, BMArray bmArray, AlgSettings s, SAType* results) { const int CHARS_IN_MASK = 31; unsigned int threadId = blockIdx.x * blockDim.x + threadIdx.x; if (threadId >= reads.count) { return; } int readOffset = reads.offsets[threadId]; int readSize = reads.sizes[threadId]; unsigned int bitTable[32]; initBitTable(bitTable); /* if (threadId == 0) { cuPrintf("Offset is %d\n", readOffset); cuPrintf("Read size is: %d\n", readSize); cuPrintf("Read first symbol is %c\n", reads.data[0]); cuPrintf("First symbol of ref seq is %c\n", refSeq[0]); cuPrintf("Read last symbol is %c\n", reads.data[readOffset + readSize - 1]); }*/ int CMAX = s.CMAX; int q = readSize / (CMAX + 1); SAType result = -1; int bestC = 0; for (int startPosInRead = 0; startPosInRead < readSize - s.w + 1; startPosInRead += q) { int len = readSize - startPosInRead > CHARS_IN_MASK ? CHARS_IN_MASK : readSize - startPosInRead; BMType bitValue = calcBitValue(reads.data, readOffset + startPosInRead, len, CHARS_IN_MASK, bitTable); SAType bmResult = lowerBound(bmArray.data, bmArray.size, bitValue, s.bitFilter); //cuPrintf("BW result is %u\n", bmResult); if (bmResult == -1) { continue; } for (SAType k = bmResult; (k < s.loadedPartSize) && (bitValue & s.bitFilter)==(bmArray.data[k] & s.bitFilter); k++) { SAType pos = sArray.data[k]; SAType firstSymbolPos = pos - startPosInRead; /*cuPrintf("pos is %d\n", pos); cuPrintf("startPosInRead=%d\n", startPosInRead); cuPrintf("firstSymbolPos=%d\n", firstSymbolPos);*/ if (firstSymbolPos == result) { continue; } //TODO: check if valid pos in sense of sequence ends... /* if (!isValidPos( pos + loadedSeqStart, readStartPos, readSize, fisrtSymbol, q)) { continue; } */ char* refBuff = refSeq + firstSymbolPos; char* readBuff = reads.data + readOffset; int c = 0; if (compare(refBuff, readBuff, startPosInRead, s.w, c, CMAX, readSize)) { //cuPrintf("c=%d,CMAX=%d\n",c, CMAX); result = firstSymbolPos; if (0 == c) { break; } bestC = c; CMAX = bestC - 1; } } } //cuPrintf("Result is %d, mismatch rate is %d\n", result,bestC); results[2*threadId] = result + s.refStartPos; results[2*threadId + 1] = bestC; } extern "C" void cudaAlignReads(char* readsData, int* readSizes, int* readOffsets, int readsNumber, char* refSeq, int refSeqSize, SAType* sArrayData, int sArraySize, BMType* bmArrayData, int bmArraySize, BMType bitFilter, int refStartPos, int loadedPartSize, int CMAX, int w, SAType* results) { printf("Starting aligning reads with CUDA...\n"); ShortReads reads; reads.data = readsData; reads.sizes = readSizes; reads.offsets = readOffsets; reads.count = readsNumber; BMArray bmArray; bmArray.data = bmArrayData; bmArray.size = bmArraySize; SArray sArray; sArray.data = sArrayData; sArray.size = sArraySize; AlgSettings settings; settings.bitFilter = bitFilter; settings.refStartPos = refStartPos; settings.loadedPartSize = loadedPartSize; settings.CMAX = CMAX; settings.w = w; //cudaPrintfInit(10*1024*1024); alignReadsKernel <<>> (reads, refSeq, refSeqSize, sArray, bmArray, settings, results); //cudaPrintfDisplay(stdout, true); cudaThreadSynchronize(); //cudaPrintfEnd(); printf("Finished aligning reads with CUDA\n"); } ugene-1.9.8/src/plugins/genome_aligner/src/GenomeAlignerSearchQuery.cpp0000644000175000017500000001114511651544323024726 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "GenomeAlignerSearchQuery.h" #include #include namespace U2 { SearchQuery::SearchQuery(const DNASequence *shortRead, SearchQuery *revCompl) { dna = true; wroteResult = false; this->revCompl = revCompl; seqLength = shortRead->length(); nameLength = shortRead->getName().length(); seq = new char[seqLength+1]; name = new char[nameLength+1]; qstrcpy(seq, shortRead->constData()); qstrcpy(name, shortRead->getName().toAscii().constData()); if (shortRead->hasQualityScores()) { quality = new DNAQuality(shortRead->quality); } else { quality = NULL; } //assRead = NULL; } SearchQuery::SearchQuery(const U2AssemblyRead &, SearchQuery *revCompl) { dna = false; wroteResult = false; this->revCompl = revCompl; seq = NULL; name = NULL; quality = NULL; //assRead = shortRead; } SearchQuery::~SearchQuery() { delete seq; delete name; delete quality; revCompl = NULL; } QString SearchQuery::getName() const { if (dna) { return QString(name); } else { return NULL; } } int SearchQuery::length() const { if (dna) { return seqLength; } else { return 0;//assRead->readSequence.length(); } } int SearchQuery::getNameLength() const { if (dna) { return nameLength; } else { return 0;//assRead->readSequence.length(); } } char *SearchQuery::data() { if (dna) { return seq; } else { return NULL;//assRead->readSequence.data(); } } const char *SearchQuery::constData() const { if (dna) { return seq; } else { return NULL;//assRead->readSequence.constData(); } } const QByteArray SearchQuery::constSequence() const { if (dna) { return QByteArray(seq); } else { return NULL;//assRead->readSequence; } } bool SearchQuery::hasQuality() const { if (dna) { return NULL != quality; } else { return false; } } const DNAQuality &SearchQuery::getQuality() const { assert(dna); return *quality; } bool SearchQuery::haveResult() const { return !results.isEmpty(); } bool SearchQuery::haveMCount() const { return !mismatchCounts.isEmpty(); } void SearchQuery::addResult(SAType result, quint32 mCount) { results.append(result); mismatchCounts.append(mCount); } void SearchQuery::addOveplapResult(SAType result) { overlapResults.append(result); } void SearchQuery::onPartChanged() { clear(); results += overlapResults; overlapResults.clear(); } void SearchQuery::clear() { results.clear(); mismatchCounts.clear(); } SAType SearchQuery::firstResult() const { return results.first(); } quint32 SearchQuery::firstMCount() const { if (mismatchCounts.isEmpty()) { return INT_MAX; } return mismatchCounts.first(); } bool SearchQuery::contains(SAType result) const { return (results.contains(result) || overlapResults.contains(result)); } QVector &SearchQuery::getResults() { return results; } const quint64 SearchQueryContainer::reallocSize = 100; SearchQueryContainer::SearchQueryContainer() { queries = NULL; allocated = 0; length = 0; } SearchQueryContainer::~SearchQueryContainer() { delete[] queries; allocated = 0; length = 0; } void SearchQueryContainer::append(SearchQuery *qu) { if (length == allocated) { queries = (SearchQuery**)qRealloc(queries, (allocated + reallocSize)*sizeof(SearchQuery*)); allocated += reallocSize; } queries[length] = qu; length++; } void SearchQueryContainer::clear() { } quint64 SearchQueryContainer::size() { return length; } SearchQuery *SearchQueryContainer::at(quint64 pos) { assert(pos <= size()); return queries[pos]; } } //U2 ugene-1.9.8/src/plugins/genome_aligner/src/GenomeAlignerIO.cpp0000644000175000017500000002122011651544323022775 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "GenomeAlignerIO.h" #include #include #include #include #include #include #include #include namespace U2 { /************************************************************************/ /* GenomeAlignerUrlReader */ /************************************************************************/ GenomeAlignerUrlReader::GenomeAlignerUrlReader(const QList &dnaList) { initOk = reader.init(dnaList); } bool GenomeAlignerUrlReader::isEnd() { if (!initOk) { return true; } return !reader.hasNext(); } int GenomeAlignerUrlReader::getProgress() { return reader.getProgress(); } SearchQuery *GenomeAlignerUrlReader::read() { return new SearchQuery(reader.getNextSequenceObject()); } /************************************************************************/ /* GenomeAlignerUrlWriter */ /************************************************************************/ GenomeAlignerUrlWriter::GenomeAlignerUrlWriter(const GUrl &resultFile, const QString &refName, int refLength) :seqWriter(resultFile, refName, refLength) { writtenReadsCount = 0; } void GenomeAlignerUrlWriter::write(SearchQuery *seq, SAType offset) { seqWriter.writeNextAlignedRead(offset, DNASequence(seq->getName(), seq->constSequence())); writtenReadsCount++; } void GenomeAlignerUrlWriter::close() { seqWriter.close(); } void GenomeAlignerUrlWriter::setReferenceName(const QString &refName) { this->refName = refName; seqWriter.setRefSeqName(refName); } namespace LocalWorkflow { /************************************************************************/ /* GenomeAlignerCommunicationChanelReader */ /************************************************************************/ GenomeAlignerCommunicationChanelReader::GenomeAlignerCommunicationChanelReader(CommunicationChannel* reads) { assert(reads != NULL); this->reads = reads; obj = new DNASequenceObject("obj", DNASequence(QByteArray("aaa"), DocumentFormatUtils::findAlphabet("aaa"))); } bool GenomeAlignerCommunicationChanelReader::isEnd() { return !reads->hasMessage() || reads->isEnded(); } int GenomeAlignerCommunicationChanelReader::getProgress() { return 100; } SearchQuery *GenomeAlignerCommunicationChanelReader::read() { DNASequence seq = reads->get().getData().toMap().value(BaseSlots::DNA_SEQUENCE_SLOT().getId()).value(); return new SearchQuery(&seq); } GenomeAlignerCommunicationChanelReader::~GenomeAlignerCommunicationChanelReader() { delete obj; } /************************************************************************/ /* GenomeAlignerMAlignmentWriter */ /************************************************************************/ GenomeAlignerMAlignmentWriter::GenomeAlignerMAlignmentWriter() { writtenReadsCount = 0; } void GenomeAlignerMAlignmentWriter::close() { //TODO: add some heuristic alphabet selection. result.setAlphabet(AppContext::getDNAAlphabetRegistry()->findById(BaseDNAAlphabetIds::NUCL_DNA_DEFAULT())); } MAlignment& GenomeAlignerMAlignmentWriter::getResult() { return result; } void GenomeAlignerMAlignmentWriter::write(SearchQuery *seq, SAType offset) { MAlignmentRow row; row.setName(seq->getName()); row.setSequence(seq->constSequence(), offset); if (seq->hasQuality() && seq->getQuality().qualCodes.length() > 0) { row.setQuality(seq->getQuality()); } result.addRow(row); writtenReadsCount++; } void GenomeAlignerMAlignmentWriter::setReferenceName(const QString &refName) { this->refName = refName; result.setName(refName); } } //LocalWorkflow /************************************************************************/ /* GenomeAlignerDbiReader */ /************************************************************************/ const qint64 GenomeAlignerDbiReader::readBunchSize = 1000; GenomeAlignerDbiReader::GenomeAlignerDbiReader(U2AssemblyDbi *_rDbi, U2Assembly _assembly) : rDbi(_rDbi), assembly(_assembly) { obj = new DNASequenceObject("obj", DNASequence(QByteArray("aaa"), DocumentFormatUtils::findAlphabet("aaa"))); wholeAssembly.startPos = 0; wholeAssembly.length = rDbi->getMaxEndPos(assembly.id, status); currentRead = reads.end(); readNumber = 0; maxRow = rDbi->getMaxPackedRow(assembly.id, wholeAssembly, status); readsInAssembly = rDbi->countReads(assembly.id, wholeAssembly, status); if (readsInAssembly <= 0 || status.hasError()) { uiLog.error(QString("Genome Aligner -> Database Error: " + status.getError()).toAscii().data()); end = true; return; } end = false; } SearchQuery *GenomeAlignerDbiReader::read() { if (end) { return NULL; } reads.clear(); if (dbiIterator.get() == NULL) { dbiIterator.reset(rDbi->getReads(assembly.id, wholeAssembly, status)); } if (dbiIterator->hasNext()) { U2AssemblyRead read = dbiIterator->next(); readNumber++; return new SearchQuery(read); } else { end = true; return NULL; } } bool GenomeAlignerDbiReader::isEnd() { return end; } int GenomeAlignerDbiReader::getProgress() { return (int)(100*(double)readNumber/readsInAssembly); } /************************************************************************/ /* GenomeAlignerDbiWriter */ /************************************************************************/ const qint64 GenomeAlignerDbiWriter::readBunchSize = 10000; inline void checkOperationStatus(const U2OpStatus &status) { if (status.hasError()) { throw status.getError(); } } GenomeAlignerDbiWriter::GenomeAlignerDbiWriter(QString dbiFilePath, QString refName, int refLength) { //TODO: support several assemblies. dbiHandle = QSharedPointer(new DbiHandle("SQLiteDbi", dbiFilePath, true, status)); checkOperationStatus(status); sqliteDbi = dbiHandle->dbi; wDbi = sqliteDbi->getAssemblyDbi(); sqliteDbi->getObjectDbi()->createFolder("/", status); checkOperationStatus(status); assembly.visualName = refName; U2AssemblyReadsImportInfo importInfo; wDbi->createAssemblyObject(assembly, "/", NULL, importInfo, status); checkOperationStatus(status); U2IntegerAttribute lenAttr; lenAttr.objectId = assembly.id; lenAttr.name = "reference_length_attribute"; lenAttr.version = 1; lenAttr.value = refLength; dbiHandle->dbi->getAttributeDbi()->createIntegerAttribute(lenAttr, status); } void GenomeAlignerDbiWriter::write(SearchQuery *seq, SAType offset) { U2AssemblyRead read(new U2AssemblyReadData()); read->name = seq->getName().toAscii(); read->leftmostPos = offset; read->effectiveLen = seq->length(); read->readSequence = seq->constSequence(); read->quality = seq->hasQuality() ? seq->getQuality().qualCodes : ""; read->flags = None; read->cigar.append(U2CigarToken(U2CigarOp_M, seq->length())); reads.append(read); if (reads.size() >= readBunchSize) { BufferedDbiIterator readsIterator(reads); wDbi->addReads(assembly.id, &readsIterator, status); checkOperationStatus(status); reads.clear(); } } void GenomeAlignerDbiWriter::close() { if (reads.size() > 0) { BufferedDbiIterator readsIterator(reads); wDbi->addReads(assembly.id, &readsIterator, status); checkOperationStatus(status); reads.clear(); } U2AssemblyPackStat packStatus; wDbi->pack(assembly.id, packStatus, status); checkOperationStatus(status); } } //U2 ugene-1.9.8/src/plugins/genome_aligner/src/GenomeAlignerWorker.cpp0000644000175000017500000004542711651544323023756 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "GenomeAlignerWorker.h" #include #include #include #include #include #include #include #include #include #include #include #include #include "GenomeAlignerPlugin.h" namespace U2 { namespace LocalWorkflow { static const QString INDEX_PORT_ID("in-gen-al-index"); static const QString INDEX_OUT_PORT_ID("out-gen-al-index"); const QString GenomeAlignerWorkerFactory::ACTOR_ID("genome-aligner"); const QString GenomeAlignerBuildWorkerFactory::ACTOR_ID("gen-al-build-index"); const QString GenomeAlignerIndexReaderWorkerFactory::ACTOR_ID("gen-al-read-index"); const QString ABS_OR_PERC_MISMATCHES_ATTR("if-absolute-mismatches-value"); const QString MISMATCHES_ATTR("absolute-mismatches"); const QString PERCENT_MISMATCHES_ATTR("percentage-mismatches"); const QString REVERSE_ATTR("reverse"); const QString BEST_ATTR("best"); const QString GPU_ATTR("gpu"); const QString QUAL_ATTR("quality-threshold"); const QString REFSEQ_URL_ATTR("url-reference"); const QString INDEX_URL_ATTR("url-index"); const QString REF_SIZE_ATTR("ref-size"); /************************************************************************/ /* Genome aligner */ /************************************************************************/ GenomeAlignerWorker::GenomeAlignerWorker(Actor* a) : BaseWorker(a, false), reads(NULL), index(NULL), output(NULL), reader(NULL), writer(NULL) { done = false; } static const Descriptor INDEX_SLOT("gen-al-index-slot", QString("Genome aligner index"), QString("Index for genome aligner")); void GenomeAlignerWorkerFactory::init() { QList p; QList a; Descriptor readsd(BasePorts::IN_SEQ_PORT_ID(), GenomeAlignerWorker::tr("Short read sequences"), GenomeAlignerWorker::tr("Short reads to be aligned.")); Descriptor indexd(INDEX_PORT_ID, QString("Genome aligner index"), QString("Genome aligner index of reference sequence.")); Descriptor oud(BasePorts::OUT_MSA_PORT_ID(), GenomeAlignerWorker::tr("Short reads alignment"), GenomeAlignerWorker::tr("Result of alignment.")); QMap inSeqM; inSeqM[BaseSlots::DNA_SEQUENCE_SLOT()] = BaseTypes::DNA_SEQUENCE_TYPE(); p << new PortDescriptor(readsd, DataTypePtr(new MapDataType("genome.aligner.in.reads", inSeqM)), true /*input*/); QMap inIndexM; inIndexM[INDEX_SLOT] = GenomeAlignerPlugin::GENOME_ALIGNER_INDEX_TYPE(); p << new PortDescriptor(indexd, DataTypePtr(new MapDataType("genome.aligner.in.index", inIndexM)), true /*input*/, false /*multi*/, IntegralBusPort::BLIND_INPUT); QMap outM; outM[BaseSlots::MULTIPLE_ALIGNMENT_SLOT()] = BaseTypes::MULTIPLE_ALIGNMENT_TYPE(); p << new PortDescriptor(oud, DataTypePtr(new MapDataType("genome.aligner.out.ma", outM)), false /*input*/, false /*multi*/); Descriptor absMismatches(ABS_OR_PERC_MISMATCHES_ATTR, GenomeAlignerWorker::tr("Is absolute mismatches values?"), GenomeAlignerWorker::tr("

true - absolute mismatches mode is used

false - percentage mismatches mode is used

\ You can choose absolute or percentage mismatches values mode.")); Descriptor mismatches(MISMATCHES_ATTR, GenomeAlignerWorker::tr("Absolute mismatches"), GenomeAlignerWorker::tr("Number of mismatches allowed while aligning reads.")); Descriptor ptMismatches(PERCENT_MISMATCHES_ATTR, GenomeAlignerWorker::tr("Percentage mismatches"), GenomeAlignerWorker::tr("Percentage of mismatches allowed while aligning reads.")); Descriptor reverse(REVERSE_ATTR, GenomeAlignerWorker::tr("Align reverse complement reads"), GenomeAlignerWorker::tr("Set this option to align both direct and reverse complement reads.")); Descriptor best(BEST_ATTR, GenomeAlignerWorker::tr("Use \"best\"-mode"), GenomeAlignerWorker::tr("Report only the best alignment for each read (in terms of mismatches).")); Descriptor qual(QUAL_ATTR, GenomeAlignerWorker::tr("Omit reads with qualities lower than"), GenomeAlignerWorker::tr("Omit reads with qualities lower than the specified value. Reads that have no qualities are not omited.\

Set \"0\" to switch off this option.

")); Descriptor gpu(GPU_ATTR, GenomeAlignerWorker::tr("Use GPU-optimization"), GenomeAlignerWorker::tr("Use GPU-calculatings while aligning reads. This option requires OpenCL-enable GPU-device.")); a << new Attribute(absMismatches, BaseTypes::BOOL_TYPE(), true/*required*/, false); a << new Attribute(mismatches, BaseTypes::NUM_TYPE(), false, 0); a << new Attribute(ptMismatches, BaseTypes::NUM_TYPE(), false, 0); a << new Attribute(reverse, BaseTypes::BOOL_TYPE(), false/*required*/, true); a << new Attribute(best, BaseTypes::BOOL_TYPE(), false/*required*/, false); a << new Attribute(qual, BaseTypes::NUM_TYPE(), false/*required*/, 0); a << new Attribute(gpu, BaseTypes::BOOL_TYPE(), false/*required*/, false); Descriptor desc(ACTOR_ID, GenomeAlignerWorker::tr("UGENE genome aligner"), GenomeAlignerWorker::tr("Unique UGENE algorithm for aligning short reads to reference genome")); ActorPrototype* proto = new IntegralBusActorPrototype(desc, p, a); QMap delegates; { QVariantMap m; m["minimum"] = 0; m["maximum"] = 3; delegates[MISMATCHES_ATTR] = new SpinBoxDelegate(m); QVariantMap ptM; ptM["minimum"] = 0; ptM["maximum"] = 10; delegates[PERCENT_MISMATCHES_ATTR] = new SpinBoxDelegate(ptM); QVariantMap q; q["minimum"] = 0; q["maximum"] = 70; delegates[QUAL_ATTR] = new SpinBoxDelegate(q); } proto->setEditor(new DelegateEditor(delegates)); proto->setPrompter(new GenomeAlignerPrompter()); proto->setIconPath(":core/images/align.png"); WorkflowEnv::getProtoRegistry()->registerProto(BaseActorCategories::CATEGORY_ASSEMBLY(), proto); DomainFactory* localDomain = WorkflowEnv::getDomainRegistry()->getById(LocalDomainFactory::ID); localDomain->registerEntry(new GenomeAlignerWorkerFactory()); } void GenomeAlignerWorker::init() { reader = NULL; writer = NULL; reads = ports.value(BasePorts::IN_SEQ_PORT_ID()); index = ports.value(INDEX_PORT_ID); output = ports.value(BasePorts::OUT_MSA_PORT_ID()); //TODO: PREBUILT INDEX //settings.setCustomValue(GenomeAlignerTask::OPTION_PREBUILT_INDEX, true); settings.prebuiltIndex = true; bool absMismatches = actor->getParameter(ABS_OR_PERC_MISMATCHES_ATTR)->getAttributeValue(); settings.setCustomValue(GenomeAlignerTask::OPTION_IF_ABS_MISMATCHES, absMismatches); int nMismatches = actor->getParameter(MISMATCHES_ATTR)->getAttributeValue(); settings.setCustomValue(GenomeAlignerTask::OPTION_MISMATCHES, nMismatches); int ptMismatches = actor->getParameter(PERCENT_MISMATCHES_ATTR)->getAttributeValue(); settings.setCustomValue(GenomeAlignerTask::OPTION_PERCENTAGE_MISMATCHES, ptMismatches); bool alignReverse = actor->getParameter(REVERSE_ATTR)->getAttributeValue(); settings.setCustomValue(GenomeAlignerTask::OPTION_ALIGN_REVERSED, alignReverse); bool best = actor->getParameter(BEST_ATTR)->getAttributeValue(); settings.setCustomValue(GenomeAlignerTask::OPTION_BEST, best); int qual = actor->getParameter(QUAL_ATTR)->getAttributeValue(); settings.setCustomValue(GenomeAlignerTask::OPTION_QUAL_THRESHOLD, qual); bool gpu = actor->getParameter(GPU_ATTR)->getAttributeValue(); settings.setCustomValue(GenomeAlignerTask::OPTION_OPENCL, gpu); } bool GenomeAlignerWorker::isReady() { return (reads && reads->hasMessage() && index && index->hasMessage()); } Task* GenomeAlignerWorker::tick() { if (reads->hasMessage()) { if(reads->isEnded()) { algoLog.error(GenomeAlignerWorker::tr("Short reads list is empty.")); return NULL; } reader = new GenomeAlignerCommunicationChanelReader(reads); writer = new GenomeAlignerMAlignmentWriter(); QString indexFile = index->get().getData().toMap().value(INDEX_SLOT.getId()).value(); settings.refSeqUrl = indexFile; settings.setCustomValue(GenomeAlignerTask::OPTION_READS_READER, QVariant::fromValue(GenomeAlignerReaderContainer(reader))); settings.setCustomValue(GenomeAlignerTask::OPTION_READS_WRITER, QVariant::fromValue(GenomeAlignerWriterContainer(writer))); Task* t = new GenomeAlignerTask(settings); connect(t, SIGNAL(si_stateChanged()), SLOT(sl_taskFinished())); return t; } return NULL; } void GenomeAlignerWorker::cleanup() { delete reader; delete writer; writer = NULL; reader = NULL; } void GenomeAlignerWorker::sl_taskFinished() { GenomeAlignerTask* t = qobject_cast(sender()); if (t->getState() != Task::State_Finished) { return; } QVariant v = qVariantFromValue(dynamic_cast(writer)->getResult()); output->put(Message(BaseTypes::MULTIPLE_ALIGNMENT_TYPE(), v)); if (reads->isEnded()) { output->setEnded(); } done = true; } QString GenomeAlignerPrompter::composeRichDoc() { Actor* readsProducer = qobject_cast(target->getPort(BasePorts::IN_SEQ_PORT_ID()))->getProducer(BasePorts::IN_SEQ_PORT_ID()); Actor* indexProducer = qobject_cast(target->getPort(INDEX_PORT_ID))->getProducer(INDEX_PORT_ID); QString readsName = readsProducer ? tr(" from %1").arg(readsProducer->getLabel()) : ""; QString indexName = indexProducer ? tr(" from %1").arg(indexProducer->getLabel()) : ""; QString doc = tr("Align short reads %1 to the reference genome %2 and send it to output.") .arg(readsName).arg(indexName); return doc; } /************************************************************************/ /* Genome aligner index build */ /************************************************************************/ void GenomeAlignerBuildWorkerFactory::init() { QList p; QList a; Descriptor oud(INDEX_OUT_PORT_ID, QString("Genome aligner index"), QString("Result genome aligner index of reference sequence.")); QMap outM; outM[INDEX_SLOT] = GenomeAlignerPlugin::GENOME_ALIGNER_INDEX_TYPE(); p << new PortDescriptor(oud, DataTypePtr(new MapDataType("gen.al.build.index.out", outM)), false /*input*/, true /*multi*/); Descriptor refseq(REFSEQ_URL_ATTR, GenomeAlignerBuildWorker::tr("Reference"), GenomeAlignerBuildWorker::tr("Reference sequence url. The short reads will be aligned to this reference genome.")); Descriptor desc(ACTOR_ID, GenomeAlignerBuildWorker::tr("Genome aligner index builder"), GenomeAlignerBuildWorker::tr("GenomeAlignerBuild builds an index from a set of DNA sequences. GenomeAlignerBuild outputs a set of 3 files with suffixes .idx, .ref, .sarr. These files together constitute the index: they are all that is needed to align reads to that reference.")); Descriptor index(INDEX_URL_ATTR, GenomeAlignerBuildWorker::tr("Index"), GenomeAlignerBuildWorker::tr("Output index url.")); Descriptor refSize(REF_SIZE_ATTR, GenomeAlignerBuildWorker::tr("Reference fragmentation"), GenomeAlignerBuildWorker::tr("Reference fragmentation size")); a << new Attribute(refseq, BaseTypes::STRING_TYPE(), true /*required*/, QString()); a << new Attribute(index, BaseTypes::STRING_TYPE(), true /*required*/, QString()); a << new Attribute(refSize, BaseTypes::NUM_TYPE(), true /*required*/, 10); ActorPrototype* proto = new IntegralBusActorPrototype(desc, p, a); QMap delegates; delegates[REFSEQ_URL_ATTR] = new URLDelegate(DialogUtils::prepareDocumentsFileFilter(true), QString(), true); delegates[INDEX_URL_ATTR] = new URLDelegate(DialogUtils::prepareDocumentsFileFilter(true), QString(), false); proto->setEditor(new DelegateEditor(delegates)); proto->setPrompter(new GenomeAlignerBuildPrompter()); proto->setIconPath(":core/images/align.png"); WorkflowEnv::getProtoRegistry()->registerProto(BaseActorCategories::CATEGORY_ASSEMBLY(), proto); DomainFactory* localDomain = WorkflowEnv::getDomainRegistry()->getById(LocalDomainFactory::ID); localDomain->registerEntry(new GenomeAlignerBuildWorkerFactory()); } void GenomeAlignerBuildWorker::init() { output = ports.value(INDEX_OUT_PORT_ID); refSeqUrl = actor->getParameter(REFSEQ_URL_ATTR)->getAttributeValue(); indexUrl = actor->getParameter(INDEX_URL_ATTR)->getAttributeValue(); settings.prebuiltIndex = false; } bool GenomeAlignerBuildWorker::isReady() { return !isDone(); } Task* GenomeAlignerBuildWorker::tick() { if( refSeqUrl.isEmpty()) { algoLog.trace(GenomeAlignerBuildWorker::tr("Reference sequence URL is empty")); return NULL; } if( indexUrl.isEmpty()) { algoLog.trace(GenomeAlignerBuildWorker::tr("Result index URL is empty")); return NULL; } settings.refSeqUrl = refSeqUrl; settings.indexFileName = indexUrl.getURLString(); Task* t = new GenomeAlignerTask(settings, true); connect(t, SIGNAL(si_stateChanged()), SLOT(sl_taskFinished())); return t; } void GenomeAlignerBuildWorker::sl_taskFinished() { GenomeAlignerTask* t = qobject_cast(sender()); if (t->getState() != Task::State_Finished) { return; } done = true; QVariant v = qVariantFromValue(t->getIndexPath()); output->put(Message(GenomeAlignerPlugin::GENOME_ALIGNER_INDEX_TYPE(), v)); output->setEnded(); algoLog.trace(tr("Genome aligner index building finished. Result name is %1").arg(t->getIndexPath())); } bool GenomeAlignerBuildWorker::isDone() { return done; } QString GenomeAlignerBuildPrompter::composeRichDoc() { QString refSeqUrl = getParameter(REFSEQ_URL_ATTR).toString(); QString refSeq = (refSeqUrl.isEmpty() ? "" : QString("%1").arg(GUrl(refSeqUrl).fileName()) ); QString doc = tr("Build genome aligner index from %1 and send it url to output.").arg(refSeq); return doc; } /************************************************************************/ /* Genome aligner index read */ /************************************************************************/ void GenomeAlignerIndexReaderWorkerFactory::init() { QList p; QList a; Descriptor oud(INDEX_OUT_PORT_ID, GenomeAlignerIndexReaderWorker::tr("Genome aligner index"), GenomeAlignerIndexReaderWorker::tr("Result of genome aligner index builder.")); QMap outM; outM[INDEX_SLOT] = GenomeAlignerPlugin::GENOME_ALIGNER_INDEX_TYPE(); p << new PortDescriptor(oud, DataTypePtr(new MapDataType("gen.al.index.reader.out", outM)), false /*input*/, true /*multi*/); Descriptor desc(ACTOR_ID, GenomeAlignerIndexReaderWorker::tr("Genome aligner index reader"), GenomeAlignerIndexReaderWorker::tr("Read a set of several files with extensions .idx, .ref, .X.sarr. These files together constitute the index: they are all that is needed to align reads to that reference.")); Descriptor index(INDEX_URL_ATTR, GenomeAlignerIndexReaderWorker::tr("Index"), GenomeAlignerIndexReaderWorker::tr("Select an index file with the .idx extension")); a << new Attribute(index, BaseTypes::STRING_TYPE(), true /*required*/, QString()); ActorPrototype* proto = new IntegralBusActorPrototype(desc, p, a); QMap delegates; delegates[INDEX_URL_ATTR] = new URLDelegate(DialogUtils::prepareDocumentsFileFilter(true), QString(), false, false, false); proto->setEditor(new DelegateEditor(delegates)); proto->setPrompter(new GenomeAlignerIndexReaderPrompter()); proto->setIconPath(":core/images/align.png"); WorkflowEnv::getProtoRegistry()->registerProto(BaseActorCategories::CATEGORY_ASSEMBLY(), proto); DomainFactory* localDomain = WorkflowEnv::getDomainRegistry()->getById(LocalDomainFactory::ID); localDomain->registerEntry(new GenomeAlignerIndexReaderWorkerFactory()); } void GenomeAlignerIndexReaderWorker::init() { output = ports.value(INDEX_OUT_PORT_ID); indexUrl = actor->getParameter(INDEX_URL_ATTR)->getAttributeValue(); } bool GenomeAlignerIndexReaderWorker::isReady() { return !isDone(); } Task *GenomeAlignerIndexReaderWorker::tick() { if(indexUrl.isEmpty()) { algoLog.trace(GenomeAlignerIndexReaderWorker::tr("Index URL is empty")); return NULL; } Task* t = new Task("Genome aligner index reader", TaskFlags_NR_FOSCOE); connect(t, SIGNAL(si_stateChanged()), SLOT(sl_taskFinished())); return t; } void GenomeAlignerIndexReaderWorker::sl_taskFinished() { QVariant v = qVariantFromValue(indexUrl.getURLString()); output->put(Message(GenomeAlignerPlugin::GENOME_ALIGNER_INDEX_TYPE(), v)); output->setEnded(); done = true; algoLog.trace(tr("Reading genome aligner index finished. Result name is %1").arg(indexUrl.getURLString())); } bool GenomeAlignerIndexReaderWorker::isDone() { return done; } QString GenomeAlignerIndexReaderPrompter::composeRichDoc() { QString indexUrl = getParameter(INDEX_URL_ATTR).toString(); QString index = (indexUrl.isEmpty() ? "" : QString("%1").arg(GUrl(indexUrl).fileName())); QString doc = tr("Read genome aligner index from %1 and send it url to output.").arg(index); return doc; } } //namespace LocalWorkflow } //namespace U2 ugene-1.9.8/src/plugins/genome_aligner/src/GenomeAlignerSettingsWidget.cpp0000644000175000017500000001745511651544323025451 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "GenomeAlignerTask.h" #include "GenomeAlignerIndex.h" #include #include #include #include #include #include #include #include #include "GenomeAlignerSettingsWidget.h" namespace U2 { static const int MIN_READ_SIZE = 10; static const int MIN_PART_SIZE = 1; static const int DEFAULT_PART_SIZE = 10; GenomeAlignerSettingsWidget::GenomeAlignerSettingsWidget(QWidget* parent) : DnaAssemblyAlgorithmMainWidget(parent) { setupUi(this); layout()->setContentsMargins(0,0,0,0); connect(buildIndexFileButton, SIGNAL(clicked()), SLOT(sl_onSetIndexDirButtonClicked())); connect(partSlider, SIGNAL(valueChanged(int)), SLOT(sl_onPartSliderChanged(int))); connect(readSlider, SIGNAL(valueChanged(int)), SLOT(sl_onReadSliderChanged(int))); buildIndexFileButton->toggle(); if (AppContext::getOpenCLGpuRegistry()->empty()) { gpuBox->setEnabled(false); } systemSize = AppContext::getAppSettings()->getAppResourcePool()->getMaxMemorySizeInMB(); partSlider->setEnabled(false); readSlider->setMinimum(MIN_READ_SIZE); readSlider->setMaximum(systemSize); readSlider->setValue(systemSize*2/3); indexDirEdit->setText(AppContext::getAppSettings()->getUserAppsSettings()->getTemporaryDirPath()); partSizeLabel->setText(QByteArray::number(partSlider->value()) + " Mb"); indexSizeLabel->setText(QByteArray::number(partSlider->value()*13) + " Mb"); totalSizeLabel->setText(QByteArray::number(partSlider->value()*13 + readSlider->value()) + " Mb"); systemSizeLabel->setText(QByteArray::number(systemSize) + " Mb"); } QMap GenomeAlignerSettingsWidget::getDnaAssemblyCustomSettings() { QMap settings; settings.insert(GenomeAlignerTask::OPTION_ALIGN_REVERSED, reverseBox->isChecked()); settings.insert(GenomeAlignerTask::OPTION_OPENCL, gpuBox->isChecked()); settings.insert(GenomeAlignerTask::OPTION_BEST, firstMatchBox->isChecked()); settings.insert(GenomeAlignerTask::OPTION_READS_MEMORY_SIZE, readSlider->value()); settings.insert(GenomeAlignerTask::OPTION_SEQ_PART_SIZE, partSlider->value()); settings.insert(GenomeAlignerTask::OPTION_INDEX_DIR, indexDirEdit->text()); if (omitQualitiesBox->isChecked()) { settings.insert(GenomeAlignerTask::OPTION_QUAL_THRESHOLD, qualThresholdBox->value() ); } if (groupBox_mismatches->isChecked()) { settings.insert(GenomeAlignerTask::OPTION_MISMATCHES, mismatchesAllowedSpinBox->value()); settings.insert(GenomeAlignerTask::OPTION_IF_ABS_MISMATCHES, absRadioButton->isChecked()); settings.insert(GenomeAlignerTask::OPTION_PERCENTAGE_MISMATCHES, percentMismatchesAllowedSpinBox->value()); } else { settings.insert(GenomeAlignerTask::OPTION_MISMATCHES, 0); settings.insert(GenomeAlignerTask::OPTION_IF_ABS_MISMATCHES, true); settings.insert(GenomeAlignerTask::OPTION_PERCENTAGE_MISMATCHES, 0); } return settings; } bool GenomeAlignerSettingsWidget::buildIndexUrl(const GUrl& url, bool prebuiltIndex, QString &error) { if (prebuiltIndex) { GenomeAlignerIndex index; index.baseFileName = url.dirPath() + "/" + url.baseFileName(); QByteArray e; bool res = index.deserialize(e); if (!res || url.lastFileSuffix() != GenomeAlignerIndex::HEADER_EXTENSION) { error = tr("This index file is corrupted. Please, load a valid index file."); return false; } partSlider->setMinimum(MIN_PART_SIZE); partSlider->setMaximum(index.seqPartSize); partSlider->setEnabled(true); partSlider->setValue(index.seqPartSize); } else { QString refUrl = url.getURLString(); QFile file(refUrl); if (file.exists()) { int fileSize = 1 + (int)(file.size()/(1024*1024)); int maxPartSize = qMin(fileSize*13, systemSize - MIN_READ_SIZE)/13; partSlider->setMinimum(MIN_PART_SIZE); partSlider->setMaximum(maxPartSize); partSlider->setEnabled(true); partSlider->setValue(qMin(maxPartSize, DEFAULT_PART_SIZE)); } } return true; } void GenomeAlignerSettingsWidget::prebuiltIndex(bool value) { indexTab->setEnabled(!value); } bool GenomeAlignerSettingsWidget::isParametersOk(QString &error) { if (systemSize < readSlider->value() + 13*partSlider->value()) { error = "There is no enough memory for the aligning on your computer. Try to reduce a memory size for short reads or for the reference fragment."; return false; } return true; } bool GenomeAlignerSettingsWidget::isIndexOk(QString &error, GUrl refName) { GenomeAlignerIndex index; if (indexTab->isEnabled()) { //prebuiltIndex is not checked index.baseFileName = indexDirEdit->text() + "/" + refName.baseFileName(); } else { index.baseFileName = refName.dirPath() + "/" + refName.baseFileName(); } QByteArray e; bool res = index.deserialize(e); if (indexTab->isEnabled()) { //prebuiltIndex is not checked if (!res) { return true; } if (index.seqPartSize == partSlider->value()) { return true; } error = tr("The index directory has already contain the prebuilt index. But its reference fragmentation parameter is %1 and it doesn't equal to \ the parameter you have chosen (%2).\n\nPress \"Ok\" to delete this index file and create a new during the aligning.\nPress \"Cancel\" to change this parameter \ or the index directory.").arg(index.seqPartSize).arg(partSlider->value()); return false; } else { if (!res || refName.lastFileSuffix() != GenomeAlignerIndex::HEADER_EXTENSION) { error = tr("This index file is corrupted. Please, load a valid index file."); return false; } return true; } } void GenomeAlignerSettingsWidget::sl_onSetIndexDirButtonClicked() { LastOpenDirHelper lod; lod.url = QFileDialog::getExistingDirectory(this, tr("Set index files directory"), indexDirEdit->text()); if (!lod.url.isEmpty()) { GUrl result = lod.url; indexDirEdit->setText(result.getURLString()); } } void GenomeAlignerSettingsWidget::sl_onPartSliderChanged(int value) { partSizeLabel->setText(QByteArray::number(value) + " Mb"); indexSizeLabel->setText(QByteArray::number(value*13) + " Mb"); if (systemSize - 13*value >= MIN_READ_SIZE) { readSlider->setMaximum(systemSize - 13*value); } else { readSlider->setMaximum(MIN_READ_SIZE); } totalSizeLabel->setText(QByteArray::number(value*13 + readSlider->value()) + " Mb"); } void GenomeAlignerSettingsWidget::sl_onReadSliderChanged(int value) { readSizeLabel->setText(QByteArray::number(value) + " Mb"); totalSizeLabel->setText(QByteArray::number(partSlider->value()*13 + value) + " Mb"); } } //namespace ugene-1.9.8/src/plugins/genome_aligner/src/GenomeAlignerIndexTask.h0000644000175000017500000000463011651544323024033 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_GENOME_ALIGNER_INDEX_TASK_H_ #define _U2_GENOME_ALIGNER_INDEX_TASK_H_ #include #include #include #include #include "GenomeAlignerIndex.h" namespace U2 { class GenomeAlignerIndex; class DNASequenceObject; class GenomeAlignerIndexSettings { public: QString indexFileName; QString refFileName; bool justBuildIndex; int seqPartSize; //in Mb bool prebuiltIndex; }; class GenomeAlignerIndexTask: public Task { Q_OBJECT public: GenomeAlignerIndexTask(const GenomeAlignerIndexSettings &settings); ~GenomeAlignerIndexTask(); void run(); qint64 getFreeMemSize() {return memFreeSize;} qint64 getFreeGPUSize() {return gpuFreeSize;} GenomeAlignerIndex *index; private: SAType seqLength; //reference sequence's length int w; //window size QString baseFileName; //base of the index's file name BitsTable bt; const quint32* bitTable; int bitCharLen; BMType bitFilter; SAType *objLens; int objCount; char unknownChar; qint64 memFreeSize; qint64 gpuFreeSize; GenomeAlignerIndexSettings settings; quint32 MAX_ELEM_COUNT_IN_MEMORY; static const int BUFF_SIZE = 6291456; //6Mb. Must be divided by 8 static const int MEM_FOR_READS = 400; //Mb for aligning reads private: void reformatSequence(); }; } //U2 #endif // _U2_GENOME_ALIGNER_INDEX_TASK_H_ ugene-1.9.8/src/plugins/genome_aligner/src/BuildSArraySettingsWidget.cpp0000644000175000017500000000546111651544323025110 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include #include #include #include #include #include #include #include "BuildSArraySettingsWidget.h" #include "GenomeAlignerTask.h" static const int MIN_PART_SIZE = 1; static const int DEFAULT_PART_SIZE = 10; namespace U2 { BuildSArraySettingsWidget::BuildSArraySettingsWidget(QWidget* parent) : DnaAssemblyAlgorithmBuildIndexWidget(parent) { setupUi(this); layout()->setContentsMargins(0,0,0,0); connect(partSlider, SIGNAL(valueChanged(int)), SLOT(sl_onPartSliderChanged(int))); systemSize = AppContext::getAppSettings()->getAppResourcePool()->getMaxMemorySizeInMB(); partSlider->setEnabled(false); partSizeLabel->setText(QByteArray::number(partSlider->value()) + " Mb"); totalSizeLabel->setText(QByteArray::number(partSlider->value()*13) + " Mb"); systemSizeLabel->setText(QByteArray::number(systemSize) + " Mb"); } QMap BuildSArraySettingsWidget::getBuildIndexCustomSettings() { QMap settings; settings.insert(GenomeAlignerTask::OPTION_SEQ_PART_SIZE, partSlider->value()); return settings; } QString BuildSArraySettingsWidget::getIndexFileExtension() { return ""; } void BuildSArraySettingsWidget::sl_onPartSliderChanged(int value) { partSizeLabel->setText(QByteArray::number(value) + " Mb"); totalSizeLabel->setText(QByteArray::number(value*13) + " Mb"); } void BuildSArraySettingsWidget::buildIndexUrl(const GUrl& url) { QString refUrl = url.getURLString(); QFile file(refUrl); if (file.exists()) { int fileSize = 1 + (int)(file.size()/(1024*1024)); int maxPartSize = qMin(fileSize*13, systemSize)/13; partSlider->setMinimum(MIN_PART_SIZE); partSlider->setMaximum(maxPartSize); partSlider->setEnabled(true); partSlider->setValue(qMin(maxPartSize, DEFAULT_PART_SIZE)); } } } //namespace ugene-1.9.8/src/plugins/genome_aligner/src/GenomeAlignerPlugin.cpp0000644000175000017500000001167711651544323023743 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "GenomeAlignerPlugin.h" #include "GenomeAlignerTask.h" #include "GenomeAlignerSettingsWidget.h" #include "GenomeAlignerCMDLineTask.h" #include "BuildSArraySettingsWidget.h" #include #include #include #include #include #include #include #include "GenomeAlignerTask.h" #include "GenomeAlignerWorker.h" namespace U2 { extern "C" Q_DECL_EXPORT Plugin * U2_PLUGIN_INIT_FUNC() { GenomeAlignerPlugin * plug = new GenomeAlignerPlugin(); return plug; } const QString GenomeAlignerPlugin::GENOME_ALIGNER_INDEX_TYPE_ID("gai"); const QString GenomeAlignerPlugin::RUN_GENOME_ALIGNER("genome-aligner"); DataTypePtr GenomeAlignerPlugin::GENOME_ALIGNER_INDEX_TYPE() { DataTypeRegistry* dtr = WorkflowEnv::getDataTypeRegistry(); assert(dtr); static bool startup = true; if (startup) { dtr->registerEntry(DataTypePtr(new DataType(GENOME_ALIGNER_INDEX_TYPE_ID, QString("Genome aligner index"), QString("Index for genome aligner")))); startup = false; } return dtr->getById(GENOME_ALIGNER_INDEX_TYPE_ID); } class GenomeAlignerGuiExtFactory : public DnaAssemblyGUIExtensionsFactory { public: GenomeAlignerGuiExtFactory(){}; DnaAssemblyAlgorithmMainWidget* createMainWidget(QWidget* parent) {return new GenomeAlignerSettingsWidget(parent);} DnaAssemblyAlgorithmBuildIndexWidget* createBuildIndexWidget(QWidget* parent) {return new BuildSArraySettingsWidget(parent);} bool hasMainWidget() {return true;} bool hasBuildIndexWidget() {return true;} }; GenomeAlignerPlugin::GenomeAlignerPlugin() : Plugin( tr("UGENE genome aligner"), tr("Assembly DNA to reference sequence") ) { // Register GenomeAligner algorithm DnaAssemblyAlgRegistry* registry = AppContext::getDnaAssemblyAlgRegistry(); bool guiMode = AppContext::getMainWindow(); DnaAssemblyGUIExtensionsFactory* guiFactory = guiMode ? new GenomeAlignerGuiExtFactory(): NULL; DnaAssemblyAlgorithmEnv* algo = new DnaAssemblyAlgorithmEnv("UGENE genome aligner", new GenomeAlignerTask::Factory, guiFactory, true, true); bool res = registry->registerAlgorithm(algo); Q_UNUSED(res); assert(res); LocalWorkflow::GenomeAlignerWorkerFactory::init(); LocalWorkflow::GenomeAlignerBuildWorkerFactory::init(); LocalWorkflow::GenomeAlignerIndexReaderWorkerFactory::init(); registerCMDLineHelp(); processCMDLineOptions(); } GenomeAlignerPlugin::~GenomeAlignerPlugin() { } void GenomeAlignerPlugin::processCMDLineOptions() { CMDLineRegistry * cmdlineReg = AppContext::getCMDLineRegistry(); assert(cmdlineReg != NULL); if (cmdlineReg->hasParameter( RUN_GENOME_ALIGNER ) ) { Task * t = new GenomeAlignerCMDLineTask(); connect(AppContext::getPluginSupport(), SIGNAL(si_allStartUpPluginsLoaded()), new TaskStarter(t), SLOT(registerTask())); } } void GenomeAlignerPlugin::registerCMDLineHelp() { CMDLineRegistry * cmdLineRegistry = AppContext::getCMDLineRegistry(); assert( NULL != cmdLineRegistry ); CMDLineHelpProvider * taskSection = new CMDLineHelpProvider( RUN_GENOME_ALIGNER, tr("UGENE Short Reads Aligner"), tr("UGENE Genome Aligner is an efficient and fast tool for short read alignment." "It has 2 work modes: build index and align short reads (default mode).\nIf there is no " "index available for reference sequence it will be built on the fly.\n" "\nUsage: ugene --genome-aligner { --option[=argument] }\n" "\nOptions\n--------\n\n%1" "\nExamples\n--------\n\n" "Build index for reference sequence:\n" "ugene --genome-aligner --build-index --reference=/path/to/ref\n" "\nAlign short reads using existing index:\n" "ugene --genome-aligner --reference=/path/to/ref" " --short-reads=/path/to/reads --result=/path/to/result\n") .arg( GenomeAlignerCMDLineTask::getArgumentsDescritption() ) ); cmdLineRegistry->registerCMDLineHelpProvider( taskSection ); } } //namespace ugene-1.9.8/src/plugins/genome_aligner/src/GenomeAlignerPlugin.h0000644000175000017500000000260611651544323023400 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_GENOME_ALIGNER_PLUGIN_H_ #define _U2_GENOME_ALIGNER_PLUGIN_H_ #include #include namespace U2 { class GenomeAlignerPlugin : public Plugin { Q_OBJECT private: void registerCMDLineHelp(); void processCMDLineOptions(); public: GenomeAlignerPlugin(); ~GenomeAlignerPlugin(); static const QString GENOME_ALIGNER_INDEX_TYPE_ID; static const QString RUN_GENOME_ALIGNER; static DataTypePtr GENOME_ALIGNER_INDEX_TYPE(); }; } //namespace #endif // _U2_GENOME_ALIGNER_PLUGIN_H_ ugene-1.9.8/src/plugins/genome_aligner/src/GenomeAlignerCMDLineTask.h0000644000175000017500000000317411651544323024201 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_GENOME_ALIGNER_CMDLINE_TASK_H_ #define _U2_GENOME_ALIGNER_CMDLINE_TASK_H_ #include #include #include namespace U2 { class GenomeAlignerCMDLineTask : public Task { Q_OBJECT public: GenomeAlignerCMDLineTask(); virtual ~GenomeAlignerCMDLineTask(); virtual void prepare(); static QString getArgumentsDescritption(); private: int mismatchCount, ptMismatchCount, memSize, refSize, qualityThreshold; bool useCuda, useOpenCL; bool alignRevCompl, bestMode, samOutput; DnaAssemblyToRefTaskSettings settings; QString indexPath, resultPath, refPath; bool onlyBuildIndex; QList shortReadUrls; }; // GenomeAlignerCMDLineTask } //namespace #endif // _U2_GENOME_ALIGNER_CMDLINE_TASK_H_ ugene-1.9.8/src/plugins/genome_aligner/src/GenomeAlignerIndexPart.h0000644000175000017500000000361111651544323024035 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_GENOME_ALIGNER_INDEX_PART_H_ #define _U2_GENOME_ALIGNER_INDEX_PART_H_ #include #include typedef quint64 BMType; typedef quint32 SAType; #define MAX_BIT_MASK_LENGTH 31 namespace U2 { class GenomeAlignerIndexTask; class IndexPart { friend class GenomeAlignerIndexTask; friend class GenomeAlignerIndex; public: IndexPart(); ~IndexPart(); SAType *sArray; BMType *bitMask; char *seq; SAType getLoadedPartSize(); SAType getMaxLength(); SAType getLoadedSeqStart(); int getCurrentPart() {return currentPart;} bool load(int part); void build(int part); void writePart(int part, quint32 arrLen); private: int partCount; int currentPart; SAType *seqStarts; SAType *seqLengths; SAType *saLengths; QFile *refFile; QFile **partFiles; BMType getBitValue(uchar *seq, SAType idx); }; bool isLittleEndian(); } //U2 #endif //_U2_GENOME_ALIGNER_INDEX_PART_H_ ugene-1.9.8/src/plugins/genome_aligner/transl/0000755000175000017500000000000011651544323020044 5ustar ilyailyaugene-1.9.8/src/plugins/genome_aligner/transl/russian.ts0000644000175000017500000004511311651544323022104 0ustar ilyailya BuildSuffixArraySettings Parameters Параметры Set the paramaters of the selected align short reads algorithm. Optimize the index created for reads with length (greater than or) equal to the specified value. Note, that <b>during short reads aligning a read must be greater than or equal to this value</b>. Optimize for read length Chech this box if mismatches between the reference sequence and the reads are allowed. Mismatches allowed Допустимо несоответствий Select the number of mismatched nucleotides allowed. Mismatches number Select the percentage of mismatches allowed. Note, that absolute number of mismatches can vary for different reads. Percentage of mismatches U2::GenomeAlignerPlugin UGENE genome aligner Модуль сборки контигов UGENE Assembly DNA to reference sequence Сборка контигов по последовательности U2::GenomeAlignerSettingsWidget Set index file name Open index file U2::GenomeAlignerTask Short reads list is empry! Считываемые последовательности пусты! UGENE genome aligner Модуль сборки контигов UGENE Can not init short reads loader. %1 U2::LocalWorkflow::GenomeAlignerPrompter from <u>%1</u> из <u>%1</u> Align short reads %1 to the reference genome %2 and send it to output. Собрать контигы из считываемых последовательностей %1 по референсному геному%2 и направить их на вывод. U2::LocalWorkflow::GenomeAlignerWorker Short read sequences Считываемые последовательности Short reads to be aligned. Считываемые последовательности для сборки. Short reads alignment Выравнивание считываемых последовательностей Result of alignment. Результат выравнивания. Reference Референсная последовательность Reference sequence url. The short reads will be aligned to this genome. Указатель на референсную последовательность. Считываемые последовательности будут собраны по этому геному. Absolute of percentage mismatches' values Choose absolute of percentage mismatches' values Mismatches Несоответствий Number of mismatches allowed while aligning reads. Число несоответствий, допустимое при собрке контигов из считываемых последовательностей. Mismatches percentage Percentage of mismatches allowed while aligning reads. Align reversed Сборка обращённых последовательностей Set this option to align both direct and reverse reads. Установите эту опцию для сборки как прямых, так и обращённых считываемых последовательностей. Add ref to result Добавить реф. послед. Set TRUE if you wish to append reference sequence to result alignment Выберите значение ИСТИНА, если референсная последовательность должна быть включена в результирующее выравнивание Prebuilt index Set TRUE if you wish to use prebuilt index for this reference Index file Path to the index file UGENE genome aligner Модуль сборки контигов UGENE Unique UGENE algorithm for aligning short reads to reference genome Уникальный алгоритм UGENE для сборки контигов из считываемых последовательностей по референсному геному Short reads list is empty. Список считываемых последовательностей пуст. Genome aligner finished. Result name is %1 Сборка контигов завершена. Имя результата: "%1" GenomeAlignerSettings Form Set the paramaters of the selected align short reads algorithm. Parameters Параметры Chech this box if mismatches between the reference sequence and the reads are allowed. Mismatches allowed Допустимо несоответствий Select the number of mismatched nucleotides allowed. Select the percentage of mismatches allowed. Note, that absolute number of mismatches can vary for different reads. Mismatches number Percentage of mismatches Set short reads aligning options. Use both the read and its reverse complement during aligning. Align reverse complement reads Search only for the first occurence of each read in the reference sequence. Omit reads with qualities lower than the specified value. Reads that have no qualities are not omited. Use an appropriate index to optimize a short reads aligning algorithm. Index Specify an index to build during execution of the selected short reads aligning algorithm. If this option is selected, the value is <b>required</b>. Save index to ... Use an appropriate prebuilt index to optimize the selected short reads aligning algorithm. If this option is selected, the value is <b>required</b>. Use prebuit index from Align options Align reverse reads Сборка по обращённым последовательностям Stop searching on the first successful match Omit reads with qualities lower than Add reference sequence to alignment Добавить референсную последовательность в выравнивание ugene-1.9.8/src/plugins/genome_aligner/transl/english.ts0000644000175000017500000003751511651544323022060 0ustar ilyailya BuildSuffixArraySettings Parameters Set the paramaters of the selected align short reads algorithm. Optimize the index created for reads with length (greater than or) equal to the specified value. Note, that <b>during short reads aligning a read must be greater than or equal to this value</b>. Optimize for read length Chech this box if mismatches between the reference sequence and the reads are allowed. Mismatches allowed Select the number of mismatched nucleotides allowed. Mismatches number Select the percentage of mismatches allowed. Note, that absolute number of mismatches can vary for different reads. Percentage of mismatches U2::GenomeAlignerPlugin UGENE genome aligner Assembly DNA to reference sequence U2::GenomeAlignerSettingsWidget Set index file name Open index file U2::GenomeAlignerTask UGENE genome aligner Can not init short reads loader. %1 U2::LocalWorkflow::GenomeAlignerPrompter from <u>%1</u> Align short reads %1 to the reference genome %2 and send it to output. U2::LocalWorkflow::GenomeAlignerWorker Short read sequences Short reads to be aligned. Short reads alignment Result of alignment. Reference Reference sequence url. The short reads will be aligned to this genome. Absolute of percentage mismatches' values Choose absolute of percentage mismatches' values Mismatches Number of mismatches allowed while aligning reads. Mismatches percentage Percentage of mismatches allowed while aligning reads. Align reversed Set this option to align both direct and reverse reads. Add ref to result Set TRUE if you wish to append reference sequence to result alignment Prebuilt index Set TRUE if you wish to use prebuilt index for this reference Index file Path to the index file UGENE genome aligner Unique UGENE algorithm for aligning short reads to reference genome Short reads list is empty. Genome aligner finished. Result name is %1 GenomeAlignerSettings Form Set the paramaters of the selected align short reads algorithm. Parameters Chech this box if mismatches between the reference sequence and the reads are allowed. Mismatches allowed Select the number of mismatched nucleotides allowed. Select the percentage of mismatches allowed. Note, that absolute number of mismatches can vary for different reads. Mismatches number Percentage of mismatches Set short reads aligning options. Use both the read and its reverse complement during aligning. Align reverse complement reads Search only for the first occurence of each read in the reference sequence. Omit reads with qualities lower than the specified value. Reads that have no qualities are not omited. Use an appropriate index to optimize a short reads aligning algorithm. Index Specify an index to build during execution of the selected short reads aligning algorithm. If this option is selected, the value is <b>required</b>. Save index to ... Use an appropriate prebuilt index to optimize the selected short reads aligning algorithm. If this option is selected, the value is <b>required</b>. Use prebuit index from Align options Stop searching on the first successful match Omit reads with qualities lower than ugene-1.9.8/src/plugins/query_designer/0000755000175000017500000000000011651544324016614 5ustar ilyailyaugene-1.9.8/src/plugins/query_designer/query_designer.qrc0000644000175000017500000000066411651544323022355 0ustar ilyailya images/delete.png images/green_circle.png images/query_designer.png images/filenew.png images/fileopen.png images/filesave.png images/run.png images/strands.png images/eye.png ugene-1.9.8/src/plugins/query_designer/images/0000755000175000017500000000000011651544323020060 5ustar ilyailyaugene-1.9.8/src/plugins/query_designer/images/delete.png0000644000175000017500000000072611651544323022035 0ustar ilyailyaPNG  IHDRatEXtSoftwareAdobe ImageReadyqe<xIDATxڤSn@(!7P HD:u cʀ(hhh@goX68 7D {y >%wa%fph@۰8S=$\q{tA k5[4/1x{Q\ܱUH1M aĞ5n*K 5nYi4j2akQðn8E\c+φu|=XG5_AJbY̑rW(!K%`djܔLD> 4f^q:gw"L8S=jpnd7pĭK^ IENDB`ugene-1.9.8/src/plugins/query_designer/images/filenew.png0000644000175000017500000000124211651544323022216 0ustar ilyailyaPNG  IHDRatEXtSoftwareAdobe ImageReadyqe<DIDATx|SMhAvm#HA"EQPH"6њSmV4J`5` E,"-?Mdg3a#voތ9( lcEԛq}+P3xFy&{w ē܆!" նmnY/JRX,r0ZD(RVJpGeYQ$fl!-0DYr"Zd2I^5[4G,ոCrV+=܄[1a&D5-x*ncwa=uDb} AqY dy8=FkwD##'E 0JKf?`&o&\y,}oܖ$~ntnم{R/۪0:27 B8P pxڙj9HǙpE2X5^yՋ+zy&b]8-O#j xWGˏЦh[zM AѸzx߹mB]P</N0}ϣ@/IENDB`ugene-1.9.8/src/plugins/query_designer/images/run.png0000644000175000017500000000061611651544323021375 0ustar ilyailyaPNG  IHDRatEXtSoftwareAdobe ImageReadyqe<0IDATxb?%Ba<1l kk'ˀ?~1pih1 V\)#݀o&&.$\x6#~I_ >}dgK<綄h~~O?0|KYKZ&z#l Ϗ }c``ff203\$ʀ?߿0?f6vק1|xqow?Ĺ??0019|v .삷W2{uώq$o exB5c5/?;sK &%2xn0s&URIENDB`ugene-1.9.8/src/plugins/query_designer/images/filesave.png0000644000175000017500000000132411651544323022364 0ustar ilyailyaPNG  IHDRatEXtSoftwareAdobe ImageReadyqe<vIDATx|Ska}٤!B* *U^JA/ĢA Ă9YAj*xAJQAf6oK7~3oޛ 31B";c3< 2}aL2d1' j4T4M*JX,R6!Q2Ij6qJ%/h&(}Jmۊ8+^[kǕ[EcI04Ih]}Tq{ TUT*$i(>myȽ*c@xG_o/iZ[V18S{pz4~a?m 0P7Μ<vş^Y*u *f62klICy]_`.9 !>#!`n AHEqdW`.xL$(kyw{5}!=,3I v66[.šT?TWbQ#; X5J Z0;v$b;9AG)ʃn)AT F#7q#CJ>[<"ù2{w+8t㽻Yp ߯VxAL<IENDB`ugene-1.9.8/src/plugins/query_designer/images/eye.png0000644000175000017500000000076711651544323021362 0ustar ilyailyaPNG  IHDRasRGB pHYs  tIME 0/fIDAT8풱jUK``Z*-"A!Y݋(^2 E Q!SD (:48mo9;y{u?8 çT5t]f۶u[(0^J r,'TUP 5eYiJA ""WWrrٹt:XbYiE@'J...#vkiT8~^?Zl6 }{A vwrx<^%I}$}(qX,Y,p,yj4ͯvjz5NhZh`08E_(>@D ۳TOIENDB`ugene-1.9.8/src/plugins/query_designer/images/query_designer.png0000644000175000017500000000145611651544323023621 0ustar ilyailyaPNG  IHDRhtEXtSoftwareAdobe ImageReadyqe<IDATxb?#0ͷ#LܐRr 'gI]kaj,0F٪`yv|¿֫R o?eea*z [ow@ascb^\ W0ܾr }f"ŰZ >a`?<6Meε"^?~ۼd^Xg < e瀾|BFڹz⿶<)us cGA)t0Dl[jh z=ӡ؀}Nߘ9$>y& 0/_ C%/o2g`dx \< b`Ǫ f: o~s @iA\˒ ayw3sc1#fkŵG׮{3 +oL0+< 4qs=bbf%u? ~xxxߊ+Qa }TIENDB`ugene-1.9.8/src/plugins/query_designer/images/strands.png0000644000175000017500000000072511651544323022250 0ustar ilyailyaPNG  IHDRasRGB pHYs  tIME %3iTXtCommentCreated with GIMPd.e>IDAT8c`020000, \<_xn4Ҷ9]z5FeO r?1gHgÇXZ0|}r?|b//Nx`VXWr>cv 4{Fb x5)EJ2_&?0````?× ,ʎM1$Ï:Ȉ ?0.Na`d|Đ g6O PZgOu, Ξx5hÐa]w;Z(!xGُUIENDB`ugene-1.9.8/src/plugins/query_designer/images/fileopen.png0000644000175000017500000000100611651544323022364 0ustar ilyailyaPNG  IHDRatEXtSoftwareAdobe ImageReadyqe<IDATxڌKPƿ[t N.Nڎ Z|,p .;( N(uA"EDS{Ii6&9sΗðB@HػCfbl&|Fdb~HI `] IENDB`ugene-1.9.8/src/plugins/query_designer/images/green_circle.png0000644000175000017500000000032011651544323023202 0ustar ilyailyaPNG  IHDRKlgAMA aIDAT8OݔA EޜiDEc&:<+;Qѱ:j@A˳֎ U Bk\|Ef#2At$qBrbJYOxi * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "QueryEditor.h" #include "QueryProcCfgModel.h" #include "QueryProcCfgDelegate.h" #include "QDDocument.h" #include "QueryViewController.h" #include "QueryViewItems.h" #include #include #include namespace U2 { QueryEditor::QueryEditor(QWidget* parent/* =0 */) : QWidget(parent), current(NULL) { setupUi(this); caption->setMinimumHeight(nameEdit->sizeHint().height()); //QueryViewController* controller = qobject_cast(parent); nameEdit->setValidator(new QRegExpValidator(QRegExp(QDDocument::ID_PATTERN), nameEdit)); directionCombo->insertItem(0, tr("Forward")); directionCombo->insertItem(1, tr("Backward")); directionCombo->insertItem(2, tr("Any")); cfgModel = new QueryProcCfgModel(this); table->setModel(cfgModel); table->horizontalHeader()->setResizeMode(QHeaderView::Interactive); table->horizontalHeader()->setStretchLastSection(true); table->verticalHeader()->hide(); table->verticalHeader()->setDefaultSectionSize(QFontMetrics(QFont()).height() + 6); table->setItemDelegate(new QueryProcCfgDelegate(this)); table->setMinimumHeight(height()/2); reset(); connect(table->selectionModel(), SIGNAL(currentChanged(QModelIndex, QModelIndex)), SLOT(sl_showPropDoc())); connect(nameEdit, SIGNAL(editingFinished()), SLOT(sl_setLabel())); connect(keyEdit, SIGNAL(editingFinished()), SLOT(sl_setKey())); connect(directionCombo, SIGNAL(currentIndexChanged(int)), SLOT(sl_setDirection(int))); connect(cfgModel, SIGNAL(dataChanged(QModelIndex, QModelIndex)), SIGNAL(modified())); } void QueryEditor::setCurrentAttribute(const QString& id) { QModelIndex modelIndex = cfgModel->modelIndexById(id); QModelIndex prev = table->selectionModel()->currentIndex(); if (modelIndex==prev) { table->selectionModel()->reset(); } table->setCurrentIndex(modelIndex); //table->selectionModel()->setCurrentIndex(modelIndex, QItemSelectionModel::ClearAndSelect); } void QueryEditor::sl_setLabel() { if (current->getParameters()->getLabel()!=nameEdit->text()) { current->getParameters()->setLabel(nameEdit->text()); emit modified(); } } void QueryEditor::sl_setKey() { if (current->getParameters()->getAnnotationKey()!=keyEdit->text()) { current->getParameters()->setAnnotationKey(keyEdit->text()); emit modified(); } } void QueryEditor::sl_setDirection(int index) { QDStrandOption dir = QDStrandOption(index); if (current->getStrand()!=dir) { current->setStrand(dir); emit modified(); } } void QueryEditor::sl_showPropDoc() { QModelIndex current = table->selectionModel()->currentIndex(); if (current.isValid()) { propDoc->setText(WorkflowUtils::getRichDoc(current.data(DescriptorRole).value())); } else { propDoc->setText(""); } } void QueryEditor::setDescriptor(const Descriptor* d, const QString& hint) { QString text = d ? WorkflowUtils::getRichDoc(*d) + "

" + hint : hint; if (text.isEmpty()) { text = tr("Select an element to inspect."); } doc->setText(text); } void QueryEditor::showProto(QDActorPrototype* proto) { if (proto) { caption->setText(tr("Element Name")); caption->show(); annotationLbl->setText(tr("Annotate As")); annotationLbl->show(); directionLbl->setText(tr("Direction")); directionLbl->show(); //nameEdit->setText(a->getParameters()->getLabel()); nameEdit->show(); nameEdit->setDisabled(true); //keyEdit->setText(a->getParameters()->getAnnotationKey()); keyEdit->show(); keyEdit->setDisabled(true); directionCombo->show(); directionCombo->setDisabled(true); setDescriptor(&proto->getDescriptor(), tr("To configure the algorithm element parameters go to the \"Parameters\" area below.")); cfgModel->setConfiguration(proto->getEditor(), proto->getParameters()); tableSplitter->show(); tableSplitter->setDisabled(true); } else { reset(); } } void QueryEditor::edit(QDConstraint* constraint) { if(constraint) { caption->setText(""); caption->hide(); annotationLbl->setText(""); annotationLbl->hide(); directionLbl->setText(tr("")); directionLbl->hide(); nameEdit->setText(""); nameEdit->hide(); keyEdit->setText(""); keyEdit->hide(); directionCombo->hide(); doc->setText(tr("To configure the constraint element parameters go to the \"Parameters\" area below.")); cfgModel->setConfiguration(constraint->getParameters()); tableSplitter->show(); tableSplitter->setDisabled(false); } else { reset(); } } void QueryEditor::edit(QDActor* a) { current = a; if(a) { caption->setText(tr("Element Name")); caption->show(); annotationLbl->setText(tr("Annotate As")); annotationLbl->show(); directionLbl->setText(tr("Direction")); directionLbl->show(); nameEdit->setText(a->getParameters()->getLabel()); nameEdit->show(); nameEdit->setDisabled(false); keyEdit->setText(a->getParameters()->getAnnotationKey()); keyEdit->show(); keyEdit->setDisabled(false); directionCombo->setCurrentIndex(a->getStrand()); directionCombo->show(); if (a->hasStrand()) { directionCombo->setDisabled(false); } else { directionCombo->setDisabled(true); } setDescriptor(&a->getProto()->getDescriptor(), tr("To configure the algorithm element parameters go to the \"Parameters\" area below.")); cfgModel->setConfiguration(a->getParameters()); a->updateEditor(); tableSplitter->show(); tableSplitter->setDisabled(false); } else { reset(); } } void QueryEditor::reset() { caption->setText(""); caption->hide(); annotationLbl->setText(""); annotationLbl->hide(); directionLbl->setText(tr("")); directionLbl->hide(); nameEdit->setText(""); nameEdit->hide(); keyEdit->setText(""); keyEdit->hide(); directionCombo->hide(); setDescriptor(NULL); cfgModel->setConfiguration(NULL); tableSplitter->hide(); propDoc->setText(""); } }//namespace ugene-1.9.8/src/plugins/query_designer/src/QueryViewAdapter.cpp0000644000175000017500000001322611651544324023354 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "QueryViewAdapter.h" #include "QueryViewItems.h" namespace U2 { #define FN_MIN_LEN 30 QueryViewAdapter::QueryViewAdapter(QDScheme* scheme, const QPointF& topLeftCorner) : scheme(scheme) { QMap unitMap; QList constraints = scheme->getConstraints(); foreach(QDActor const* a, scheme->getActors()) { foreach(QDSchemeUnit* su, a->getSchemeUnits()) { QDElement* uv = new QDElement(su); uv->moveBy(topLeftCorner.x(), topLeftCorner.y()); createdElements.append(uv); unitMap.insertMulti(su, uv); } constraints << a->getParamConstraints(); } foreach(QDConstraint* c, constraints) { QDDistanceConstraint* dc = static_cast(c); if (dc) { QDElement* src = unitMap.value(dc->getSource()); QDElement* dst = unitMap.value(dc->getDestination()); createdFootnotes << new Footnote(src, dst, dc->distanceType(), dc); } } } void QueryViewAdapter::placeElement(QDElement* uv) { //rearrange other adjacent units positions if necessary foreach(Footnote* fn, uv->getFootnotes()) { const QPointF& srcPt = fn->getSrcPoint(); const QPointF& dstPt = fn->getDstPoint(); qreal fnLen = dstPt.x() - srcPt.x(); qreal dx = fnLen - FN_MIN_LEN; if (dx<0) { if (fn->getSrc()==uv) { moveElement(fn->getDst(), -dx); } else { assert(fn->getDst()==uv); moveElement(uv, -dx); } } } } void QueryViewAdapter::moveElement(QDElement* uv, int dx) { assert(currentPath.isEmpty()); QList affectedUnits; if (needToMove(uv, dx, affectedUnits)) { foreach(QDElement* u, affectedUnits) { u->moveBy(dx, 0); } } } bool QueryViewAdapter::needToMove(QDElement* current, int dx, QList& res) { //check recursion if (currentPath.contains(current)) { currentPath.clear(); return false; } currentPath.append(current); if (!res.contains(current)) { res.append(current); } if (dx>0) { foreach(Footnote* fn, current->getFootnotes()) { if (fn->getSrc()==current) { if (!needToMove(fn->getDst(), dx, res)) { return false; } } } } else { foreach(Footnote* fn, current->getFootnotes()) { if (fn->getDst()==current) { if (!needToMove(fn->getSrc(), dx, res)) { return false; } } } } currentPath.removeAll(current); return true; } QRectF getUnitLocation(QDElement* uv) { QRectF res = uv->boundingRect(); res.moveTopLeft(uv->scenePos()); return res; } bool intersects(QDElement* uv, const QList& others) { foreach(QDElement* other, others) { if (uv!=other) { const QRectF& uvRect = getUnitLocation(uv); const QRectF& otherRect = getUnitLocation(other); if (uvRect.intersects(otherRect)) { return true; } } } return false; } void QueryViewAdapter::sortVertically() { foreach(QDElement* uv, createdElements) { while (intersects(uv, createdElements)) { uv->moveBy(0, GRID_STEP); } } } QList QueryViewAdapter::getSharedFootnotes(QDElement* uv1, QDElement* uv2) const { QList uv1Fns = uv1->getFootnotes(); const QList& uv2Fns = uv2->getFootnotes(); foreach(Footnote* uv2fn, uv2Fns) { if (!uv1Fns.contains(uv2fn)) { uv1Fns.removeAll(uv2fn); } } return uv1Fns; } //enum Border{Left,Right}; // //class QDEdge; //class QDVertex { //public: // QDVertex(QDElement* _parent, Border _border, int _xPos=0) // : parent(_parent), border(_border), xPos(_xPos) {} // void setXPos(int x) { xPos=x; } // int getXPos() const { return xPos; } //private: // QDElement* parent; // Border border; // QList in, out; // int xPos; // friend class QDEdge; //}; // //class QDEdge { //public: // QDEdge(QDVertex* _src, QDVertex* _dst) : src(_src), dst(_dst) { // src->out.append(this); // dst->in.append(this); // } // QDVertex* getSrc() const { return src; } // QDVertex* getDst() const { return dst; } //private: // QDVertex* src; // QDVertex* dst; //}; // //void QueryViewAdapter::scheme2graph() { // QList graph; // foreach(QDElement* el, createdElements) { // graph << QDVertex(el, Left) << QDVertex(el, Right); // } // foreach(Footnote* fn, createdFootnotes) { // QDElement* srcEl = fn->getSrc(); // QDElement* dstEl = fn->getDst(); // } //} }//namespace ugene-1.9.8/src/plugins/query_designer/src/QDDocument.cpp0000644000175000017500000003342311651544323022116 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "QDDocument.h" #include "QDSceneIOTasks.h" #include #include namespace U2 { #define STRING_MAX_LEN 80 #define TEXT_OFFSET " " #define DOUBLE_TEXT_OFFSET " " static const QString GRAPH_KEYWORD = "query"; static const QString IMPORT_KEYWORD = "import"; static const QString BLOCK_START = "{"; static const QString BLOCK_END = "}"; static const QString META_KEYWORD = ".meta"; static const QString VISUAL_KEYWORD = "visual"; QString QDDocStatement::getAttribute(const QString& name) const { foreach(const StringAttribute& attr, attributes) { if (attr.first==name) { return attr.second; } } return QString(); } void QDDocStatement::setAttribute(const QString& name, const QString& value) { assert(!name.contains(' ')); for (int i=0; i newAttr = qMakePair(name, value); attributes.append(newAttr); } QString QDDocStatement::toString() const { int strLen = evalStringLen(); QString res; foreach(const StringAttribute& attr, attributes) { if (strLen>STRING_MAX_LEN) { res+="\n"; res+=DOUBLE_TEXT_OFFSET; } res += " " + attr.first + ": "; QString val; if (attr.second.contains(';') || attr.second.contains('#')) { val = "\""+attr.second+"\""; } else { val = attr.second; } res+=val + ';'; } return res; } int QDDocStatement::evalStringLen() const { int res=0; foreach(const StringAttribute& attr, attributes) { res+=attr.first.length() + attr.second.length() + 2; } return res; } const QString QDElementStatement::GEOMETRY_ATTR_NAME("geometry"); const QString QDElementStatement::ALGO_ATTR_NAME("type"); QString QDElementStatement::toString() const { QString res = QDDocStatement::toString(); if (evalStringLen()>STRING_MAX_LEN) { res = BLOCK_START + res + "\n" + TEXT_OFFSET + BLOCK_END; } else { res = BLOCK_START + res + " " + BLOCK_END +" "; } res = TEXT_OFFSET + id + " " + res; return res; } QString QDElementStatement::definedIn() const { return QDDocument::definedIn(id); } const QString QDLinkStatement::TYPE_ATTR_NAME("type"); QString QDLinkStatement::toString() const { QString res = " " + BLOCK_START + QDDocStatement::toString() + " " + BLOCK_END; QString prefix = elementIds.at(0); for (int i=1; igetId()==id) { return stmt; } } return NULL; } QList QDDocument::getElements(QDStatementType type) const { QList res; foreach(QDElementStatement* stmt, elements) { if (stmt->getType()==type) { res.append(stmt); } } return res; } QByteArray QDDocument::toByteArray() const { QString content; foreach(QDElementStatement* el, getElements(Group)) { if (el->getId()==GROUPS_SECTION) { continue; } content += el->toString() + "\n"; } content+="\n"; foreach(QDLinkStatement* lnk, getLinks()) { content += lnk->toString() + "\n"; } content+="\n"; QString txtOffset = QString(TEXT_OFFSET); content+=txtOffset + META_KEYWORD + BLOCK_START + "\n"; content+=txtOffset + txtOffset + VISUAL_KEYWORD + BLOCK_START + "\n"; foreach(QDElementStatement* el, getElements(Element)) { content+=txtOffset+txtOffset+txtOffset; content += el->toString() + "\n"; } content+=txtOffset + txtOffset + BLOCK_END + "\n"; if (!order.isEmpty()) { content+=txtOffset + txtOffset + ORDER_KEYWORD + " " + BLOCK_START + " "; foreach(QString s, order) { content+=s+';'; } content+= " " + BLOCK_END + "\n"; } if (schemaStrand!=QDStrand_Both) { content+=txtOffset + txtOffset + SCHEMA_STRAND_ATTR + " : "; content+= QDSchemeSerializer::STRAND_MAP.value(schemaStrand) + ';'; content+= " \n"; } QDElementStatement* grEl = getElement(GROUPS_SECTION); if (grEl) { content+=txtOffset + grEl->toString() + "\n"; } content+=txtOffset + BLOCK_END + "\n"; QString desc = docDesc; desc = "#" + desc.replace("\n", "\n#") + "\n\n"; content = HEADER_LINE + "\n" + desc + GRAPH_KEYWORD + " " + docName + " {\n\n\n" + content + "}"; return content.toUtf8(); } bool QDDocument::setContent(const QString& content) { QRegExp reg(DOC_NAME_PATTERN); reg.indexIn(content); docName = reg.cap(1); findImportedUrls(content); findComments(content); parseSchemaStrand(content); if(!findElementStatements(content)) { return false; } if (!findLinkStatements(content)) { return false; } return true; } void QDDocument::parseSchemaStrand(const QString& str) { QRegExp reg(SCHEMA_STRAND_PATTERN); int pos = reg.indexIn(str); if (pos>=0) { QString strandStr = reg.cap(1); if (QDSchemeSerializer::STRAND_MAP.values().contains(strandStr)) { schemaStrand = QDSchemeSerializer::STRAND_MAP.key(strandStr); } } } void QDDocument::findComments(const QString& str) { QRegExp reg("((?:#[^\n]*\n{1,1})+)\\s*"+GRAPH_KEYWORD); int pos = reg.indexIn(str); if (pos>=0) { QString coms = reg.cap(1); coms.remove(HEADER_LINE); docDesc = coms.replace("#",""); int lastIdx = docDesc.length()-1; assert(QString(docDesc.at(lastIdx))=="\n"); docDesc.remove(lastIdx,1); } } void QDDocument::parseOrder(const QString& str) { order.clear(); order = str.trimmed().split(QRegExp("\\s*;\\s*")); } bool QDDocument::addElement(QDElementStatement* el) { QDStatementType elType = el->getType(); const QString& elId = el->getId(); foreach(QDElementStatement* stmt, elements) { if (stmt->getId()==elId && stmt->getType()==elType) { return false; } } elements.append(el); assert(el->document==NULL); el->document = this; return true; } void QDDocument::findImportedUrls(const QString& str) { QRegExp reg(IMPORT_PATTERN); int pos=0; while(pos>=0) { pos = reg.indexIn(str, pos); if (pos>=0) { pos+=reg.matchedLength(); QString toImport = reg.cap(1); importedUrls.append(toImport); } } } bool QDDocument::findElementStatements(const QString& str) { QRegExp reg; reg.setPattern(ELEMENT_STATEMENT_PATTERN); int pos=0; while(pos>=0) { pos = reg.indexIn(str, pos); if (pos>=0) { /*QString ch1 = QString(str.at(pos)); QString ch2 = QString(str.at(pos-1)); QString ch3 = QString(str.at(pos+1));*/ pos+=reg.matchedLength(); const QString& id = reg.cap(1); const QString& attrs = reg.cap(2); if (id==ORDER_KEYWORD) { parseOrder(attrs); continue; } const QMap& attrsMap = string2attributesMap(attrs); QDStatementType type; if (id.contains('.')) { type = Element; } else { type = Group; } QDElementStatement* element = new QDElementStatement(id, type); foreach(const QString& attrName, attrsMap.keys()) { const QString& val = attrsMap.value(attrName); element->setAttribute(attrName, val); } addElement(element); } } return true; } bool QDDocument::findLinkStatements(const QString& str) { QRegExp reg(LINK_STATEMENT_PATTERN); int pos=0; while (pos>=0) { pos = reg.indexIn(str, pos); if (pos>=0) { pos+=reg.matchedLength(); const QString& elemS = reg.cap(1); const QList& elIds = idsFromString(elemS); QDLinkStatement* link = new QDLinkStatement(elIds); int capCount = reg.numCaptures(); const QString& attrs = reg.cap(capCount); const QMap& attrsMap = string2attributesMap(attrs); foreach(const QString& attrName, attrsMap.keys()) { const QString& val = attrsMap.value(attrName); link->setAttribute(attrName, val); } addLink(link); } } return true; } QMap QDDocument::string2attributesMap(const QString& str) { QMap res; QRegExp reg(ID_PATTERN + "\\s*:\\s*" + VAL_PATTERN); int pos = 0; while (pos>=0) { pos = reg.indexIn(str, pos); if (pos >= 0) { const QString& attrName = reg.cap(1); QString attrVal = reg.cap(2); attrVal.remove('"'); res[attrName] = attrVal; pos+=reg.matchedLength(); } } return res; } QList QDDocument::idsFromString(const QString& str) { QStringList l = str.split(QRegExp("\\s*--\\s*")); return l; } QString QDDocument::definedIn(const QString &id) { const QStringList& chunks = id.split('.'); if (chunks.size()<3) { return QString(); } else { assert(chunks.size()==3); QString defIn = chunks.at(0); return defIn; } } QString QDDocument::getLocalName(const QString& id) { if (id.contains('.')) { int dotPos = id.indexOf('.'); return id.mid(dotPos+1); } return id; } QDElementStatement* QDDocument::findElementByUnitName(QDElementStatement* parent, const QString& unitName) const { return getElement(parent->getId()+"."+unitName); } void QDDocument::saveOrder(const QList& actors) { foreach(QDActor* a, actors) { order.append(a->getParameters()->getLabel()); } } //Mapper ////////////////////////////////////////////////////////////////////////// QString QDIdMapper::distance2string(QDDistanceType type) { switch (type) { case E2S: return "end-to-start"; case E2E: return "end-to-end"; case S2S: return "start-to-start"; case S2E: return "start-to-end"; default: return QString(); } } int QDIdMapper::string2distance(const QString& str) { if (str=="end-to-start") { return 0; } if (str=="end-to-end") { return 1; } if (str=="start-to-start") { return 2; } if (str=="start-to-end") { return 3; } return -1; } QDConstraintType QDIdMapper::string2constraintType(const QString& str) { if (str=="distance") { return QDConstraintTypes::DISTANCE; } return QString(); } QString QDIdMapper::constraintType2string(const QDConstraintType& type) { if (type==QDConstraintTypes::DISTANCE) { return "distance"; } return QString(); } }//namespace ugene-1.9.8/src/plugins/query_designer/src/QueryDesignerPlugin.h0000644000175000017500000000371311651544324023525 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_QUERY_DESIGNER_PLUGIN_H_ #define _U2_QUERY_DESIGNER_PLUGIN_H_ #include #include #include namespace U2 { #define QUERY_SAMPLES_PATH "/query_samples" class Task; class QueryDesignerPlugin : public Plugin { Q_OBJECT public: QueryDesignerPlugin(); private: void registerLibFactories(); private: GObjectViewWindowContext* viewCtx; }; class QueryDesignerViewContext : public GObjectViewWindowContext { Q_OBJECT public: QueryDesignerViewContext(QObject* p); protected: virtual void initViewContext(GObjectView* view); private slots: void sl_showDialog(); }; class QueryDesignerService : public Service { Q_OBJECT public: QueryDesignerService() : Service(124, tr("Query Designer"), "") {} bool closeViews(); protected: virtual Task* createServiceEnablingTask(); virtual Task* createServiceDisablingTask(); virtual void serviceStateChangedCallback(ServiceState oldState, bool enabledStateChanged); private slots: void sl_startQDPlugin(); void sl_showDesignerWindow(); }; } //namespace #endif ugene-1.9.8/src/plugins/query_designer/src/QueryEditor.h0000644000175000017500000000340411651544324022031 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_QUERY_EDITOR_H_ #define _U2_QUERY_EDITOR_H_ #include "ui_QueryEditorWidget.h" namespace U2 { class Descriptor; class QueryProcCfgModel; class QDParameters; class QDActor; class QDConstraint; class QueryViewController; class ProcessNameValidator; class QDActorPrototype; class QueryEditor : public QWidget, public Ui_QueryEditorWidget { Q_OBJECT friend class ProcessNameValidator; public: QueryEditor(QWidget* parent=0); void showProto(QDActorPrototype* proto); void edit(QDConstraint* constraint); void edit(QDActor* a); void reset(); void setCurrentAttribute(const QString& id); private slots: void sl_showPropDoc(); void sl_setLabel(); void sl_setKey(); void sl_setDirection(int); signals: void modified(); private: void setDescriptor(const Descriptor* d, const QString& hint = QString()); QueryProcCfgModel* cfgModel; QDActor* current; }; }//namespace #endif ugene-1.9.8/src/plugins/query_designer/src/QDTests.cpp0000644000175000017500000001356311651544323021445 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "QDTests.h" #include "QDSceneIOTasks.h" #include #include #include #include #include namespace U2 { #define SCHEMA "schema" #define SEQUENCE_NAME "seq" #define EXPECTED_RESULT "expected_result" static const QString GROUP_NAME = "Query results"; void GTest_QDSchedulerTest::init(XMLTestFormat *, const QDomElement& el) { sched = NULL; expectedResult = NULL; seqObj = NULL; result = new AnnotationTableObject(GObjectTypes::getTypeInfo(GObjectTypes::ANNOTATION_TABLE).name); schema = new QDScheme; seqName = el.attribute(SEQUENCE_NAME); if (seqName.isEmpty()) { failMissingValue(SEQUENCE_NAME); return; } expectedResName = el.attribute(EXPECTED_RESULT); if (expectedResName.isEmpty()) { failMissingValue(EXPECTED_RESULT); return; } schemaUri = el.attribute(SCHEMA); if (schemaUri.isEmpty()) { failMissingValue(SCHEMA); return; } schemaUri = env->getVar("COMMON_DATA_DIR") + "/" + schemaUri; } void GTest_QDSchedulerTest::prepare() { if (hasError() || isCanceled()) { return; } Document* seqDoc = getContext(this, seqName); if (seqDoc == NULL){ stateInfo.setError("can't find sequence"); return; } seqObj = qobject_cast(seqDoc->findGObjectByType(GObjectTypes::SEQUENCE).first()); if (seqObj == NULL){ stateInfo.setError("can't find sequence"); return; } Document* expDoc = getContext(this, expectedResName); if (expDoc == NULL){ stateInfo.setError("can't find result"); return; } expectedResult = qobject_cast(expDoc->findGObjectByType(GObjectTypes::ANNOTATION_TABLE).first()); if (expectedResult == NULL){ stateInfo.setError("can't find result"); return; } QDDocument* doc = new QDDocument; QFile f(schemaUri); if (!f.open(QIODevice::ReadOnly)) { stateInfo.setError("can't read result"); return; } QByteArray data = f.readAll(); const QString& content = QString::fromUtf8(data); f.close(); bool res = doc->setContent(content); if (!res) { stateInfo.setError( tr("Invalid content: %1").arg(expectedResName) ); return; } bool ok = QDSceneSerializer::doc2scheme( (QList() << doc), schema ); delete doc; if (!ok) { stateInfo.setError(tr("can't read %1").arg(expectedResName)); return; } QDRunSettings s; schema->setDNA(seqObj); s.region = seqObj->getSequenceRange(); s.scheme = schema; s.annotationsObj = result; s.groupName = GROUP_NAME; sched = new QDScheduler(s); addSubTask(sched); } QList GTest_QDSchedulerTest::onSubTaskFinished(Task* subTask) { QList subs; if (subTask==sched) { AnnotationGroup* resG = result->getRootGroup()->getSubgroup(GROUP_NAME, false); AnnotationGroup* expResG = expectedResult->getRootGroup()->getSubgroup(GROUP_NAME, false); CHECK_EXT(resG!=NULL, setError("Group not found!" + GROUP_NAME), subs); CHECK_EXT(expResG!=NULL, setError("Exp group not found!" + GROUP_NAME), subs); const QList& res = resG->getSubgroups(); const QList& expRes = expResG->getSubgroups();; subs.append(new CompareAnnotationGroupsTask(res, expRes)); } else { CompareAnnotationGroupsTask* compareTask = qobject_cast(subTask); assert(compareTask); if (!compareTask->areEqual()) { setError(tr("Results do not match.")); } } return subs; } GTest_QDSchedulerTest::~GTest_QDSchedulerTest() { delete schema; delete result; } QList QDTests::createTestFactories() { QList res; res.append(GTest_QDSchedulerTest::createFactory()); return res; } static bool containsRegion(AnnotationGroup* g, const U2Region& subj) { foreach(Annotation* a, g->getAnnotations()) { foreach(const U2Region& r, a->getRegions()) { if (r==subj) { return true; } } } return false; } static bool compareGroups(AnnotationGroup* g1, AnnotationGroup* g2) { foreach(Annotation* a1, g1->getAnnotations()) { foreach(const U2Region& r1, a1->getRegions()) { if (!containsRegion(g2, r1)) { return false; } } } return true; } static bool containsGroup(const QList& grps, AnnotationGroup* subj) { foreach(AnnotationGroup* grp, grps) { if (compareGroups(grp, subj)) { return true; } } return false; } void CompareAnnotationGroupsTask::run() { foreach(AnnotationGroup* g1, grps1) { if(!containsGroup(grps2, g1)) { equal = false; return; } } equal = true; } }//namespace ugene-1.9.8/src/plugins/query_designer/src/QueryViewController.cpp0000644000175000017500000011450311651544324024117 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "QueryViewController.h" #include "QueryViewItems.h" #include "QueryPalette.h" #include "QDSamples.h" #include "QueryEditor.h" #include "QDSceneIOTasks.h" #include "QDRunDialog.h" #include "QDGroupsEditor.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include namespace U2 { /************************************************************************/ /* Scene */ /************************************************************************/ const QSizeF QueryScene::MAX_SCENE_SIZE(10*1000, 10*1000); const QSizeF QueryScene::DEFAULT_SCENE_SIZE(1000, 1000); #define MAX_ITEM_SIZE 10000 // max point size for any visual item and whole scene #define MIN_ROWS_NUMBER 3 #define DESCRIPTION_TOP_PAD 40 #define DESCRIPTION_BOTTOM_PAD 20 #define FOOTNOTES_AREA_TOP_MARGIN 20 #define FOOTNOTE_BOTTOM_MARGIN 20 QueryScene::QueryScene(QueryViewController* parent/* =0 */) : QGraphicsScene(parent), dropCandidateLeft(NULL), dropCandidateRight(NULL), view(parent), rowsNum(3), showSchemeLbl(false), showDesc(true), showOrder(true), modified(false) { setSceneRect(0, 0, DEFAULT_SCENE_SIZE.width(), DEFAULT_SCENE_SIZE.height()); setItemIndexMethod(NoIndex); scheme = new QDScheme; initTitle(); initRuler(); initDescription(); } QueryScene::~QueryScene() { clearScene(); delete scheme; delete labelTxtItem; delete descTxtItem; delete ruler; } #define LABEL_HEIGHT 40 #define LABEL_PIXEL_SIZE 15 #define LABEL_LEFT_PAD 200 void QueryScene::initTitle() { labelTxtItem = new QDLabelItem("NewSchema"); QFont lblFont; lblFont.setItalic(true); lblFont.setPixelSize(LABEL_PIXEL_SIZE); labelTxtItem->setFont(lblFont); labelTxtItem->setPos(LABEL_LEFT_PAD,0); if (view) { connect(labelTxtItem, SIGNAL(si_editingFinished()), view, SLOT(sl_updateTitle())); } } void QueryScene::initRuler() { ruler = new QDRulerItem; connect(this, SIGNAL(si_schemeChanged()), ruler, SLOT(sl_updateText())); ruler->setPos(0,0); addItem(ruler); } void QueryScene::initDescription() { descTxtItem = new QDDescriptionItem(""); descTxtItem->setTextWidth(200); qreal viewWidth(0); if (views().isEmpty()) { viewWidth = sceneRect().width(); } else { assert(views().size() == 1); QGraphicsView* v = views().first(); viewWidth = v->viewport()->width(); } qreal xPos = (viewWidth - descTxtItem->boundingRect().width()) / 2.0; qreal yPos = footnotesArea().bottom() + DESCRIPTION_TOP_PAD; descTxtItem->setPos(xPos, yPos); addItem(descTxtItem); descTxtItem->setVisible(false); } int QueryScene::getRow(QDElement* const uv) const { const QPointF& pos = uv->scenePos(); qreal top=annotationsArea().top(); int row = (pos.y()-top)/GRID_STEP; return row; } bool yPosLessThan(QGraphicsItem* uv1, QGraphicsItem* uv2) { const QPointF& pos1 = uv1->scenePos(); const QPointF& pos2 = uv2->scenePos(); if (pos1.y()=0); if (idx>=rowsNum) { rowsNum = idx+1; return; } qreal rowTop = idx*GRID_STEP + annotationsArea().top(); //sort items by y-pos QList units; foreach(QGraphicsItem* it, items()) { if (it->type()==QDElementType) { if(it->scenePos().y() >= rowTop) { units.append(it); } } } qSort(units.begin(), units.end(), yPosLessThan); foreach(QGraphicsItem* it, units) { QPointF itPos = it->scenePos(); itPos.ry()+=GRID_STEP; it->setPos(itPos); } } void QueryScene::sl_adaptRowsNumber() { int adaptedNum = rowsNum; for (int i=rowsNum-1;i>=MIN_ROWS_NUMBER; i--) { if (unitsIntersectedByRow(i).isEmpty()) { --adaptedNum; } else { break; } } setRowsNumber(adaptedNum); } void QueryScene::sl_updateRulerText() { ruler->sl_updateText(); } QString QueryScene::getLabel() const { return labelTxtItem->toPlainText(); } QString QueryScene::getDescription() const { return descTxtItem->toPlainText(); } void QueryScene::setLabel(const QString& lbl) { labelTxtItem->setPlainText(lbl); } void QueryScene::setDescription(const QString& dsc) { descTxtItem->setPlainText(dsc); } void QueryScene::sl_showLabel(bool show) { if (showSchemeLbl==show) { return; } showSchemeLbl = show; int dy(0); if (showSchemeLbl) { addItem(labelTxtItem); dy = LABEL_HEIGHT; ruler->setPos(0, LABEL_HEIGHT); } else { removeItem(labelTxtItem); dy = -LABEL_HEIGHT; ruler->setPos(0,0); } foreach(QGraphicsItem* it, items()) { if (it->type()==QDElementType) { it->moveBy(0.0, dy); } } descTxtItem->moveBy(0.0, dy); update(); } void QueryScene::sl_showSchemeDesc(bool show) { descTxtItem->setVisible(show); } void QueryScene::sl_showItemDesc(bool show) { showDesc = show; foreach(QGraphicsItem* it, items()) { if (it->type()==QDElementType) { QDElement* uv = qgraphicsitem_cast(it); uv->sl_refresh(); uv->rememberSize(); uv->adaptSize(); sl_adaptRowsNumber(); } } } void QueryScene::sl_showOrder(bool show) { showOrder = show; foreach(QGraphicsItem* it, items()) { if (it->type()==QDElementType) { QDElement* uv = qgraphicsitem_cast(it); uv->sl_refresh(); } } } QRectF QueryScene::rulerArea() const { QRectF area = ruler->boundingRect(); area.moveTopLeft(ruler->scenePos()); assert(area.width() < MAX_ITEM_SIZE && area.height() < MAX_ITEM_SIZE); return area; } QRectF QueryScene::annotationsArea() const { const QRectF& rect = sceneRect(); assert(rect.width() < MAX_ITEM_SIZE && rect.height() < MAX_ITEM_SIZE); //qreal top = round(rect.top() + dy, GRID_STEP); qreal top = rect.top() + ruler->boundingRect().height(); if (showSchemeLbl) { top += LABEL_HEIGHT; } qreal areaHeight = rowsNum*GRID_STEP; return QRectF(rect.left(), top, rect.width(), areaHeight); } QRectF QueryScene::footnotesArea() const { qreal tlX = sceneRect().left(); qreal tlY = annotationsArea().bottom() + FOOTNOTES_AREA_TOP_MARGIN; qreal brX = sceneRect().right(); qreal brY=tlY; foreach(QGraphicsItem* it, items()) { if (it->type()==FootnoteItemType) { qreal itBottomEdge = it->scenePos().y() + it->boundingRect().height(); if (itBottomEdge>brY) { brY = itBottomEdge; } } } brY += FOOTNOTE_BOTTOM_MARGIN; QRectF rect(QPointF(tlX,tlY), QPointF(brX,brY)); assert(rect.width() < MAX_ITEM_SIZE && rect.height() < MAX_ITEM_SIZE); return rect; } QList QueryScene::getElements() const { QList res; foreach(QGraphicsItem* item, items()) { if (item->type()==QDElementType) { QDElement* el = qgraphicsitem_cast(item); res.append(el); } } return res; } QList QueryScene::getFootnotes() const { QList res; foreach(QGraphicsItem* item, items()) { if (item->type()==FootnoteItemType) { res.append(item); } } return res; } QDElement* QueryScene::getUnitView(QDSchemeUnit* su) const { foreach(QDElement* el, getElements()) { if (el->getSchemeUnit()==su) { return el; } } return NULL; } #define MAX_ROWS_NUMBER 200 void QueryScene::setRowsNumber(int count) { if (count <= MAX_ROWS_NUMBER) { qreal dY = (count - rowsNum)*GRID_STEP; rowsNum = count; foreach(QGraphicsItem* item, items()) { if(item->type()==FootnoteItemType) { Footnote* fn = qgraphicsitem_cast(item); fn->moveBy(0.0, dY); } } descTxtItem->moveBy(0.0, dY); qreal bottom = descTxtItem->mapRectToScene(descTxtItem->boundingRect()).bottom(); bottom = footnotesArea().bottom() + DESCRIPTION_TOP_PAD; descTxtItem->setY(bottom); qreal newH = qMax(QueryScene::DEFAULT_SCENE_SIZE.height(), descTxtItem->mapRectToScene(descTxtItem->boundingRect()).bottom() + DESCRIPTION_BOTTOM_PAD); QRectF r = sceneRect(); if (newH > r.height()) { r.setHeight(newH); setSceneRect(r); } update(); } } void QueryScene::drawBackground(QPainter *painter, const QRectF &rect) { Q_UNUSED(rect); int step = GRID_STEP; painter->setPen(QPen(QColor(200, 200, 255, 125))); // draw horizontal grid const QRectF& area = annotationsArea(); qreal start = area.top(); for (qreal y = start; y < start + (rowsNum+1)*step; y += step) { painter->drawLine(area.left(), y, area.right(), y); } } QList QueryScene::getElements(const QRectF& area) { QList items = QGraphicsScene::items(area, Qt::IntersectsItemShape); foreach(QGraphicsItem* item, items) { if(item->type()!=QDElementType) { items.removeAll(item); } } return items; } #define BINDING_AREA 50 void QueryScene::dragEnterEvent(QGraphicsSceneDragDropEvent *) {} void QueryScene::dragMoveEvent(QGraphicsSceneDragDropEvent *event) { const QString& mimeStr = event->mimeData()->text(); if (mimeStr==QDDistanceIds::E2S || mimeStr==QDDistanceIds::S2E || mimeStr==QDDistanceIds::S2S || mimeStr==QDDistanceIds::E2E) { const QList& sceneUnitViews = getElements(sceneRect()); if (sceneUnitViews.size()<2) { event->setDropAction(Qt::IgnoreAction); return; } if(dropCandidateLeft && dropCandidateRight) { dropCandidateLeft->highlighted = false; dropCandidateRight->highlighted = false; } QPointF mousePos = event->scenePos(); QRectF leftArea = sceneRect(); leftArea.setRight(mousePos.x()); const QList& annItemsToLeft = getElements(leftArea); QRectF rightArea = sceneRect(); rightArea.setLeft(mousePos.x()); const QList& annItemsToRight = getElements(rightArea); qreal delta = sceneRect().width()*sceneRect().width() + sceneRect().height()*sceneRect().height(); QDElement *src = NULL, *dst = NULL; foreach(QGraphicsItem* itLeft, annItemsToLeft) { QDElement* leftAnn = qgraphicsitem_cast(itLeft); assert(leftAnn); foreach(QGraphicsItem* itRight, annItemsToRight) { QDElement* rightAnn = qgraphicsitem_cast(itRight); assert(rightAnn); QLineF srcToPos(leftAnn->getRightConnector(), mousePos); QLineF dstToPos(rightAnn->getLeftConnector(), mousePos); QLineF srcToDst(leftAnn->getRightConnector(), rightAnn->getLeftConnector()); qreal curDelta = srcToPos.length() + dstToPos.length() - srcToDst.length(); if(curDelta < delta) { delta = curDelta; src=leftAnn; dst=rightAnn; } } } if(delta < BINDING_AREA) { dropCandidateLeft = src; dropCandidateRight = dst; dropCandidateLeft->highlighted = true; dropCandidateRight->highlighted = true; update(); } event->acceptProposedAction(); } else if(AppContext::getQDActorProtoRegistry()->getAllIds().contains(mimeStr)) { event->acceptProposedAction(); } else { event->acceptProposedAction(); } } void QueryScene::dropEvent(QGraphicsSceneDragDropEvent *event) { if(!event->mimeData()->hasText()) { return; } const QString& mimeStr = event->mimeData()->text(); if (AppContext::getQDActorProtoRegistry()->getAllIds().contains(mimeStr)) { QDActorPrototype* proto = AppContext::getQDActorProtoRegistry()->getProto(mimeStr); QDActor* actor = proto->createInstance(); addActor(actor, event->scenePos()); return; } else if (mimeStr==QDDistanceIds::E2E) { setupDistanceDialog(E2E); } else if (mimeStr==QDDistanceIds::S2S) { setupDistanceDialog(S2S); } else if (mimeStr==QDDistanceIds::E2S) { setupDistanceDialog(E2S); } else if (mimeStr==QDDistanceIds::S2E) { setupDistanceDialog(S2E); } if (dropCandidateLeft) { dropCandidateLeft->highlighted = false; } if (dropCandidateRight) { dropCandidateRight->highlighted = false; } dropCandidateLeft = NULL; dropCandidateRight = NULL; } void QueryScene::setupDistanceDialog(QDDistanceType kind) { if(dropCandidateLeft && dropCandidateRight) { AddConstraintDialog dlg(this, kind, dropCandidateLeft, dropCandidateRight); dlg.exec(); } } #define UNIT_PADDING 30 void QueryScene::addActor(QDActor* actor, const QPointF& pos) { int count = 0; foreach(QDActor* a, scheme->getActors()) { if (a->getActorType() == actor->getActorType()) { ++count; } } QDActorParameters* actorCfg = actor->getParameters(); QString defaultName = actor->getProto()->getDisplayName(); if (count>0) { actorCfg->setLabel(QString("%1%2").arg(defaultName).arg(count)); } else { actorCfg->setLabel(defaultName); } qreal top = annotationsArea().top(); int rowNum = (pos.y() - top)/GRID_STEP; assert(rowNum>=0); qreal y = rowNum*GRID_STEP + top; scheme->addActor(actor); int dx = 0; QMap unit2view; foreach(QDSchemeUnit* su, actor->getSchemeUnits()) { QDElement* uv = new QDElement(su); unit2view[su] = uv; addItem(uv); uv->setPos(pos.x() + dx, y); dx += UNIT_PADDING + uv->boundingRect().width(); } foreach(QDConstraint* c, actor->getParamConstraints()) { QDDistanceConstraint* dc = static_cast(c); if (dc) { QueryViewController::setupConstraintEditor(dc); Footnote* fn = new Footnote(unit2view.value(dc->getSource()), unit2view.value(dc->getDestination()), dc->distanceType(), c ); addItem(fn); fn->updatePos(); } } connect(actor->getParameters(), SIGNAL(si_modified()), ruler, SLOT(sl_updateText())); emit_schemeChanged(); setModified(true); } void QueryScene::addDistanceConstraint(QDElement* src, QDElement* dst, QDDistanceType distType, int min, int max) { if(src!=dst) { QList units; units << src->getSchemeUnit() << dst->getSchemeUnit(); QDConstraint* c = new QDDistanceConstraint(units, distType, min, max); QueryViewController::setupConstraintEditor(c); scheme->addConstraint(c); connect(c->getParameters(), SIGNAL(si_modified()), ruler, SLOT(sl_updateText())); Footnote* fn = new Footnote(src, dst, distType, c); addItem(fn); fn->updatePos(); updateDescription(); emit_schemeChanged(); } setModified(true); } void QueryScene::removeActor(QDActor* actor) { foreach(QGraphicsItem* it, getElements()) { QDElement* uv = qgraphicsitem_cast(it); assert(uv); if (uv->getActor()==actor) { removeItem(uv); delete uv; } } const QList& actors = scheme->getActors(); int removedIdx = actors.indexOf(actor); scheme->removeActor(actor); int actorsNumber = actors.size(); for (int idx=removedIdx; idxsetOrder(a, idx); foreach(QDElement* el, getElements()) { if (el->getActor()==a) { el->sl_refresh(); break; } } } emit_schemeChanged(); setModified(true); } void QueryScene::removeActors(const QList& actors) { foreach(QDActor* a, actors) { removeActor(a); } } void QueryScene::removeConstraint(QDConstraint* constraint) { QDSchemeUnit* su = constraint->getSchemeUnits().at(0); Q_UNUSED(su); assert(su->getConstraints().contains(constraint)); foreach(QGraphicsItem* it, getFootnotes()) { Footnote* fn = qgraphicsitem_cast(it); assert(fn); if (fn->getConstraint()==constraint) { removeItem(fn); delete fn; } } scheme->removeConstraint(constraint); updateDescription(); emit_schemeChanged(); setModified(true); } void QueryScene::clearScene() { removeActors(scheme->getActors()); scheme->clear(); } QList QueryScene::unitsIntersectedByRow(int idx) const { const QRectF& area = annotationsArea(); QRectF currRow(area.left(), idx*GRID_STEP, area.width(), GRID_STEP); currRow.moveTop(currRow.top()+annotationsArea().top()); QList rowItems = items(currRow, Qt::IntersectsItemShape); foreach(QGraphicsItem* it, rowItems) { if (it->type()!=QDElementType) { rowItems.removeAll(it); } } return rowItems; } void QueryScene::setModified( bool b ) { modified=b; if (view) { view->enableSaveAction(b); } } void QueryScene::updateDescription() { qreal y = footnotesArea().bottom() + DESCRIPTION_TOP_PAD; descTxtItem->setY(y); QRectF rect = sceneRect(); y = descTxtItem->mapRectToScene(descTxtItem->boundingRect()).bottom(); qreal newH = qMax(y + DESCRIPTION_BOTTOM_PAD, QueryScene::DEFAULT_SCENE_SIZE.height()); rect.setHeight(newH); setSceneRect(rect); } /************************************************************************/ /* View Controller */ /************************************************************************/ enum {ElementsTab,GroupsTab,SamplesTab}; #define PALETTE_STATE "query_palette_settings" QueryViewController::QueryViewController() : MWMDIWindow(tr("Query Designer")) { GCOUNTER(cvar, tvar, "OpenQDWindow"); scene = new QueryScene(this); sceneView = new GlassView(scene); sceneView->setDragMode(QGraphicsView::RubberBandDrag); palette = new QueryPalette(this); groupsEditor = new QDGroupsEditor(this); QDSamplesWidget* samples = new QDSamplesWidget(scene, this); tabs = new QTabWidget(this); tabs->insertTab(ElementsTab, palette, tr("Elements")); tabs->insertTab(GroupsTab, groupsEditor, tr("Groups")); tabs->insertTab(SamplesTab, samples, tr("Samples")); editor = new QueryEditor(this); connect(scene, SIGNAL(selectionChanged()), SLOT(sl_editItem())); connect(palette, SIGNAL(processSelected(QDActorPrototype*)), SLOT(sl_elementSelected(QDActorPrototype*))); connect(samples, SIGNAL(setupGlass(GlassPane*)), sceneView, SLOT(setGlass(GlassPane*))); connect(samples, SIGNAL(itemActivated(QDDocument*)), SLOT(sl_pasteSample(QDDocument*))); connect(tabs, SIGNAL(currentChanged(int)), samples, SLOT(sl_cancel())); connect(editor, SIGNAL(modified()), scene, SLOT(sl_setModified())); QSplitter* splitter = new QSplitter(Qt::Horizontal, this); splitter->addWidget(tabs); splitter->addWidget(sceneView); splitter->addWidget(editor); Settings* settings = AppContext::getSettings(); if (settings->contains(PALETTE_STATE)) { palette->restoreState(settings->getValue(PALETTE_STATE)); } QHBoxLayout* layout = new QHBoxLayout(this); layout->addWidget(splitter); layout->setSpacing(0); layout->setMargin(0); layout->setContentsMargins(0, 0, 0, 0); setLayout(layout); createActions(); sl_updateTitle(); sl_scrollUp(); } void QueryViewController::loadScene(const QString& content) { QDDocument doc; doc.setContent(content); QList docs; docs << &doc; QDSceneSerializer::doc2scene(scene, docs); scene->setModified(false); sl_updateTitle(); } void QueryViewController::createActions() { runAction = new QAction(tr("Run Schema..."), this); runAction->setIcon(QIcon(":query_designer/images/run.png")); connect(runAction, SIGNAL(triggered()), SLOT(sl_run())); newAction = new QAction(tr("New Schema"), this); newAction->setShortcuts(QKeySequence::New); newAction->setIcon(QIcon(":query_designer/images/filenew.png")); connect(newAction, SIGNAL(triggered()), SLOT(sl_newScene())); loadAction = new QAction(tr("Load Schema..."), this); loadAction->setShortcut(QKeySequence("Ctrl+L")); loadAction->setIcon(QIcon(":query_designer/images/fileopen.png")); connect(loadAction, SIGNAL(triggered()), SLOT(sl_loadScene())); saveAction = new QAction(tr("Save Schema"), this); saveAction->setShortcut(QKeySequence::Save); saveAction->setIcon(QIcon(":query_designer/images/filesave.png")); saveAction->setDisabled(true); connect(saveAction, SIGNAL(triggered()), SLOT(sl_saveScene())); saveAsAction = new QAction(tr("Save Schema As..."), this); saveAsAction->setShortcut(QKeySequence::SaveAs); saveAsAction->setIcon(QIcon(":query_designer/images/filesave.png")); connect(saveAsAction, SIGNAL(triggered()), SLOT(sl_saveSceneAs())); deleteAction = new QAction(tr("Delete"), this); deleteAction->setShortcut(QKeySequence::Delete); deleteAction->setIcon(QIcon(":query_designer/images/delete.png")); connect(deleteAction, SIGNAL(triggered()), SLOT(sl_deleteItem())); showLabelAction = new QAction(tr("Show title"), this); showLabelAction->setCheckable(true); showLabelAction->setChecked(false); connect(showLabelAction, SIGNAL(toggled(bool)), scene, SLOT(sl_showLabel(bool))); showDescAction = new QAction(tr("Show description"), this); showDescAction->setCheckable(true); showDescAction->setChecked(false); connect(showDescAction, SIGNAL(toggled(bool)), scene, SLOT(sl_showSchemeDesc(bool))); showItemDescAction = new QAction(tr("Show element info"), this); showItemDescAction->setCheckable(true); showItemDescAction->setChecked(true); connect(showItemDescAction, SIGNAL(toggled(bool)), scene, SLOT(sl_showItemDesc(bool))); showOrderAction = new QAction(tr("Show order"), this); showOrderAction->setCheckable(true); showOrderAction->setChecked(true); connect(showOrderAction, SIGNAL(toggled(bool)), scene, SLOT(sl_showOrder(bool))); strandActions = new QActionGroup(this); directStrandAction = new QAction(tr("Direct strand"), strandActions); directStrandAction->setCheckable(true); complementStrandAction = new QAction(tr("Reverse complementary strand"), strandActions); complementStrandAction->setCheckable(true); bothStrandsAction = new QAction(tr("Both strands"), strandActions); bothStrandsAction->setCheckable(true); QDStrandOption strand = scene->getScheme()->getStrand(); switch (strand) { case QDStrand_Both: bothStrandsAction->setChecked(true); break; case QDStrand_DirectOnly: directStrandAction->setChecked(true); break; case QDStrand_ComplementOnly: complementStrandAction->setChecked(true); break; default: assert(0); break; } connect(strandActions, SIGNAL(triggered(QAction*)), SLOT(sl_setGlobalStrand(QAction*))); } void QueryViewController::setupViewModeMenu(QMenu* m) { m->addAction(showLabelAction); m->addAction(showDescAction); m->addAction(showItemDescAction); m->addAction(showOrderAction); } void QueryViewController::setupQuerySequenceModeMenu(QMenu* m) { m->addAction(directStrandAction); m->addAction(complementStrandAction); m->addAction(bothStrandsAction); } void QueryViewController::setupStrandMenu(QMenu* m) { m->addActions(strandActions->actions()); } void QueryViewController::setupMDIToolbar(QToolBar* tb) { tb->addAction(newAction); tb->addAction(loadAction); tb->addAction(saveAction); tb->addAction(saveAsAction); tb->addSeparator(); tb->addAction(runAction); tb->addSeparator(); QToolButton* tt = new QToolButton(tb); QMenu* viewModeMenu = new QMenu(tr("View Mode"), this); setupViewModeMenu(viewModeMenu); QAction* a = viewModeMenu->menuAction(); tt->setDefaultAction(a); tt->setPopupMode(QToolButton::InstantPopup); tt->setIcon(QIcon(":query_designer/images/eye.png")); tb->addWidget(tt); QToolButton* st = new QToolButton(tb); QMenu* strandMenu = new QMenu(tr("Query Sequence Mode"), this); setupStrandMenu(strandMenu); QAction* sa = strandMenu->menuAction(); st->setDefaultAction(sa); st->setPopupMode(QToolButton::InstantPopup); st->setIcon(QIcon(":query_designer/images/strands.png")); tb->addWidget(st); tb->addSeparator(); tb->addAction(deleteAction); } void QueryViewController::setupViewMenu(QMenu* m) { m->addAction(newAction); m->addAction(loadAction); m->addAction(saveAction); m->addAction(saveAsAction); m->addSeparator(); m->addAction(runAction); m->addSeparator(); QMenu* viewModeMenu = new QMenu(tr("View Mode"), this); viewModeMenu->setIcon(QIcon(":query_designer/images/eye.png")); setupViewModeMenu(viewModeMenu); m->addMenu(viewModeMenu); QMenu* querySequenceModeMenu = new QMenu(tr("Query Sequence Mode"), this); querySequenceModeMenu->setIcon((QIcon(":query_designer/images/strands.png"))); setupQuerySequenceModeMenu(querySequenceModeMenu); m->addMenu(querySequenceModeMenu); m->addSeparator(); m->addAction(deleteAction); m->addSeparator(); } void QueryViewController::switchToGroupsTab() { tabs->setCurrentIndex(GroupsTab); } bool QueryViewController::onCloseEvent() { saveState(); return confirmModified(); } void QueryViewController::saveState() { AppContext::getSettings()->setValue(PALETTE_STATE, palette->saveState()); } void QueryViewController::sl_run() { QDScheme* scheme = scene->getScheme(); if (scheme->isEmpty()) { QMessageBox::critical(this, L10N::errorTitle(), tr("The schema is empty!")); } else if (!scheme->isValid()) { QMessageBox::critical(this, L10N::errorTitle(), tr("The schema is invalid! Please see the log for details.")); } else { QDRunDialog runDlg(scene->getScheme(), this, inFile_, outFile_); runDlg.exec(); } } void QueryViewController::sl_newScene() { if(!scene->getScheme()->getActors().isEmpty()) { if (!confirmModified()) { return; } } schemeUri.clear(); scene->setLabel("NewSchema"); scene->setDescription(""); scene->clearScene(); sl_updateTitle(); } void QueryViewController::sl_loadScene() { if(!scene->getScheme()->getActors().isEmpty()) { if (!confirmModified()) { return; } } LastOpenDirHelper dir(QUERY_DESIGNER_ID); dir.url = QFileDialog::getOpenFileName(this, tr("Load Schema"), dir, QString("*.%1").arg(QUERY_SCHEME_EXTENSION)); if (!dir.url.isEmpty()) { QDLoadSceneTask* t = new QDLoadSceneTask(scene, dir.url); connect(new TaskSignalMapper(t), SIGNAL(si_taskFinished(Task*)), SLOT(sl_updateTitle())); AppContext::getTaskScheduler()->registerTopLevelTask(t); scene->setModified(false); schemeUri = dir.url; } } void QueryViewController::sl_saveScene() { if (schemeUri.isEmpty()) { sl_saveSceneAs(); } else { QDSceneInfo info; info.path = schemeUri; info.schemeName = scene->getLabel(); info.description = scene->getDescription(); QDSaveSceneTask* t = new QDSaveSceneTask(scene, info); AppContext::getTaskScheduler()->registerTopLevelTask(t); scene->setModified(false); } } void QueryViewController::sl_saveSceneAs() { LastOpenDirHelper dir(QUERY_DESIGNER_ID); dir.url = QFileDialog::getSaveFileName(this, tr("Save Schema"), dir, QString("*.%1").arg(QUERY_SCHEME_EXTENSION)); if (!dir.url.isEmpty()) { schemeUri = dir.url; sl_saveScene(); } } void QueryViewController::sl_deleteItem() { QList actors2remove; QList constraints2remove; QList selectedItems = scene->selectedItems(); foreach(QGraphicsItem* item, selectedItems) { switch (item->type()) { case QDElementType: { QDElement* uv = qgraphicsitem_cast(item); assert(uv); QDActor* a = uv->getActor(); if(!actors2remove.contains(a)) { actors2remove.append(a); } } break; case FootnoteItemType: { Footnote* fn = qgraphicsitem_cast(item); assert(fn); QDConstraint* c = fn->getConstraint(); if (!constraints2remove.contains(c)) { constraints2remove.append(c); } } break; default: break; } } QList removedConstraints; foreach (QDConstraint* c, constraints2remove) { if (removedConstraints.contains(c)) { continue; } QDSchemeUnit* su = c->getSchemeUnits().at(0); QDActor* actor = su->getActor(); if (!su->getConstraints().contains(c)) { //param constraint actors2remove.removeAll(actor); removedConstraints << actor->getConstraints(); scene->removeActor(actor); continue; } scene->removeConstraint(c); } scene->removeActors(actors2remove); scene->setModified(true); } void QueryViewController::sl_editItem() { const QList& selectedItems = scene->selectedItems(); if(1==selectedItems.size()) { QGraphicsItem* selectedItem = selectedItems.at(0); if(selectedItem->type()==QDElementType) { QDElement* unitView = qgraphicsitem_cast(selectedItem); QDActor* a = unitView->getSchemeUnit()->getActor(); editor->edit(a); } if(selectedItem->type()==FootnoteItemType) { Footnote* fn = qgraphicsitem_cast(selectedItem); QDConstraint* con = fn->getConstraint(); editor->edit(con); } } else { editor->reset(); } } void QueryViewController::sl_elementSelected(QDActorPrototype* proto) { scene->clearSelection(); editor->showProto(proto); } void QueryViewController::sl_pasteSample(QDDocument* content) { if(!scene->getScheme()->getActors().isEmpty()) { if (!confirmModified()) { return; } } tabs->setCurrentIndex(ElementsTab); scene->clearScene(); QList docList = ( QList() << content ); QDSceneSerializer::doc2scene(scene, docList); sl_updateTitle(); scene->setModified(false); schemeUri.clear(); } void QueryViewController::sl_selectEditorCell(const QString& link) { editor->setCurrentAttribute(link); } void QueryViewController::sl_updateTitle() { setWindowTitle(tr("Query Designer - %1").arg(scene->getLabel())); } void QueryViewController::sl_setGlobalStrand(QAction* a) { QDScheme* scheme = scene->getScheme(); QDStrandOption old = scheme->getStrand(); if (a==bothStrandsAction) { scheme->setStrand(QDStrand_Both); } else if (a==directStrandAction) { scheme->setStrand(QDStrand_DirectOnly); } else { assert(a==complementStrandAction); scheme->setStrand(QDStrand_ComplementOnly); } if (scheme->getStrand()!=old) { scene->setModified(true); } } void QueryViewController::sl_scrollUp() { QPointF topLeft = scene->sceneRect().topLeft(); QSize s = sceneView->viewport()->rect().size(); QRectF topRect(topLeft, s); sceneView->ensureVisible(topRect); } void QueryViewController::setupConstraintEditor(QDConstraint* c) { if (c->constraintType()==QDConstraintTypes::DISTANCE) { QMap delegates; { QVariantMap lenMap; lenMap["minimum"] = QVariant(0); lenMap["maximum"] = QVariant(INT_MAX); lenMap["suffix"] = L10N::suffixBp(); delegates[QDConstraintController::MIN_LEN_ATTR] = new SpinBoxDelegate(lenMap); delegates[QDConstraintController::MAX_LEN_ATTR] = new SpinBoxDelegate(lenMap); } c->setUIEditor(new DelegateEditor(delegates)); } } bool QueryViewController::confirmModified() { if (scene->isModified()) { AppContext::getMainWindow()->getMDIManager()->activateWindow(this); int ret = QMessageBox::question(this, tr("Query Designer"), tr("The schema has been modified.\n" "Do you want to save changes?"), QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel, QMessageBox::Save); if (QMessageBox::Cancel == ret) { return false; } else if (QMessageBox::Save == ret){ sl_saveScene(); } } return true; } void QueryViewController::enableSaveAction( bool enable ) { if (saveAction) { saveAction->setEnabled(enable); } } /************************************************************************/ /* AddConstraintDialog */ /************************************************************************/ AddConstraintDialog::AddConstraintDialog(QueryScene* _scene, QDDistanceType _kind, QDElement* defSrc, QDElement* defDst) : scene(_scene), kind(_kind) { setupUi(this); QString title = "Add %1 Constraint"; switch (kind) { case E2S: setWindowTitle(title.arg("'" + tr("End-Start") + "'")); break; case E2E: setWindowTitle(title.arg("'" + tr("End-End") + "'")); break; case S2E: setWindowTitle(title.arg("'" + tr("Start-End") + "'")); break; case S2S: setWindowTitle(title.arg("'" + tr("Start-Start") + "'")); break; default: break; } maxSpin->setMaximum(INT_MAX); minSpin->setMaximum(INT_MAX); const QList& elements = scene->getElements(); int index = 0; foreach(QDElement* el, elements) { const QVariant& data = qVariantFromValue(el); QDActor* a = el->getActor(); QString name = a->getParameters()->getLabel(); if (a->getSchemeUnits().size()>1) { name += QString(".%1").arg(a->getUnitId(el->getSchemeUnit())); } fromCBox->insertItem(index, name); fromCBox->setItemData(index, data); toCBox->insertItem(index, name); toCBox->setItemData(index, data); ++index; } assert(elements.contains(defSrc)); assert(elements.contains(defDst)); fromCBox->setCurrentIndex(elements.indexOf(defSrc)); toCBox->setCurrentIndex(elements.indexOf(defDst)); } void AddConstraintDialog::accept() { int min = minSpin->text().toInt(); int max = maxSpin->text().toInt(); QDElement* src = qVariantValue(fromCBox->itemData(fromCBox->currentIndex())); QDElement* dst = qVariantValue(toCBox->itemData(toCBox->currentIndex())); scene->addDistanceConstraint(src, dst, kind, min, max); QDialog::accept(); } /************************************************************************/ /* GUIUtils */ /************************************************************************/ QPixmap QDUtils::generateSnapShot(QDDocument* doc, const QRect& rect) { QueryScene scene; QList docs = (QList() << doc); QDSceneSerializer::doc2scene(&scene, docs); return generateSnapShot(&scene, rect); } QPixmap QDUtils::generateSnapShot( QueryScene* scene, const QRect& rect) { //assert(!rect.isNull()); QRectF bounds; foreach(QGraphicsItem* item, scene->items()) { if (item->type()==QDElementType || item->type()==FootnoteItemType) { QRectF itemBound = item->boundingRect(); QPointF pos = item->scenePos(); itemBound.moveTopLeft(pos); bounds |= itemBound; if (bounds.width() > MAX_ITEM_SIZE || bounds.height() > MAX_ITEM_SIZE) { uiLog.trace(QString("Illegal QD item size, stop rendering preview!")); break; } } } QPixmap pixmap(bounds.size().toSize()); if (pixmap.isNull()) { // failed to allocate uiLog.trace(QString("Failed to allocate pixmap for the QD scene, bounds: x:%1 y:%2 w:%3 h:%4") .arg(bounds.x()).arg(bounds.y()).arg(bounds.width()).arg(bounds.height())); QPixmap naPixmap = QPixmap(rect.size()); naPixmap.fill(); QPainter p(&naPixmap); p.drawText(naPixmap.rect(), Qt::AlignHCenter | Qt::AlignTop, QueryScene::tr("Preview is not available.")); return naPixmap; } pixmap.fill(); QPainter painter(&pixmap); painter.setRenderHint(QPainter::Antialiasing); scene->render(&painter, rect, bounds); return pixmap; } }//namespace ugene-1.9.8/src/plugins/query_designer/src/QDRunDialog.h0000644000175000017500000000527711651544323021677 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_QD_RUN_DIALOG_H_ #define _U2_QD_RUN_DIALOG_H_ #include #include #include #include namespace U2 { class QDScheme; class Document; class QDScheduler; class SaveDocumentTask; class AnnotationTableObject; class QDRunDialogTask : public Task { Q_OBJECT public: QDRunDialogTask(QDScheme* scheme, const QString& inUri, const QString& outUri, bool addToProject); protected: virtual QList onSubTaskFinished(Task* subTask); private slots: void sl_updateProgress(); private: QList init(); void setupQuery(Document* doc); private: QDScheme* scheme; QString inUri; QString output; bool addToProject; Task* openProjTask; Task* loadTask; QDScheduler* scheduler; Document* docWithSequence; AnnotationTableObject* ato; }; class QueryViewController; class QDRunDialog : public QDialog, public Ui_RunQueryDlg { Q_OBJECT public: QDRunDialog(QDScheme* _scheme, QWidget* parent, const QString& defaultIn = QString(), const QString& defaultOut = QString()); private slots: void sl_run(); void sl_selectFile(); private: QDScheme* scheme; }; class ADVSequenceObjectContext; class CreateAnnotationWidgetController; class QDDialog : public QDialog, public Ui_QDDialog { Q_OBJECT public: QDDialog(ADVSequenceObjectContext* ctx); private: void addAnnotationsWidget(); void connectGUI(); void setParameters(); QVector getLocation() const; private slots: void sl_selectScheme(); void sl_radioCustomRangeToggled(bool checked); void sl_rangeStartChanged(int i); void sl_rangeEndChanged(int i); void sl_okBtnClicked(); private: ADVSequenceObjectContext* ctx; CreateAnnotationWidgetController* cawc; QDScheme* scheme; QTextDocument* txtDoc; }; }//namespace #endif ugene-1.9.8/src/plugins/query_designer/src/library/0000755000175000017500000000000011651544324021047 5ustar ilyailyaugene-1.9.8/src/plugins/query_designer/src/library/QDFindActor.h0000644000175000017500000000327611651544324023326 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_FIND_QUERY_H_ #define _U2_FIND_QUERY_H_ #include #include namespace U2 { class QDFindActor : public QDActor { Q_OBJECT public: QDFindActor(QDActorPrototype const* proto); int getMinResultLen() const; int getMaxResultLen() const; QString getText() const; Task* getAlgorithmTask(const QVector& location); QColor defaultColor() const { return QColor(0xff,0xf8,0); } private slots: void sl_onFindTaskFinished(Task* t); private: FindAlgorithmTaskSettings settings; }; class QDFindActorPrototype : public QDActorPrototype { public: QDFindActorPrototype(); virtual QDActor* createInstance() const { return new QDFindActor(this); } virtual QIcon getIcon() const { return QIcon(":core/images/find_dialog.png"); } }; }//namespace #endif ugene-1.9.8/src/plugins/query_designer/src/library/QDFindPolyRegionsActor.cpp0000644000175000017500000002223011651544324026043 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "QDFindPolyRegionsActor.h" #include #include #include #include #include #include #include #include #include #include namespace U2 { void FindPolyRegionsTask::find(const char* seq, qint64 seqLen, char ch, int percent, qint64 len, QVector& result) { assert(len <= seqLen); qreal reqChNumReal = len*percent/100.0; qint64 reqChNum = reqChNumReal; if ( reqChNumReal > reqChNum ) { ++reqChNum; } U2Region lastFound; qint64 chNum = 0; for (qint64 i=0; i=reqChNum) { lastFound.startPos = 0; lastFound.length = len; } for (qint64 i=len; i 0) { --chNum; } if (seq[i]==ch) { ++chNum; } if (chNum>=reqChNum) { if (lastFound.endPos()>=startPos) { lastFound.length = i + 1 - lastFound.startPos; } else { result.append(lastFound); lastFound.startPos = startPos; lastFound.length = len; } } } result.append(lastFound); //remove (0,0) region located in the beginning of the array if (!result.isEmpty() && result.first().isEmpty()) { result.remove(0); } } void FindPolyRegionsTask::run() { if (settings_.strand == QDStrand_DirectOnly || settings_.strand == QDStrand_Both) { find(sequence_.seq.constData(), sequence_.seq.length(), settings_.ch, settings_.percent, settings_.minLen, directResults); } if(settings_.strand == QDStrand_ComplementOnly || settings_.strand == QDStrand_Both) { assert(settings_.complTT); char ch = settings_.ch; TextUtils::translate(settings_.complTT->getOne2OneMapper(), &ch, 1); find(sequence_.seq.constData(), sequence_.seq.length(), ch, settings_.percent, settings_.minLen, compResults); } } QList FindPolyRegionsTask::getResultAsAnnotations() const { QList res; res += createAnnotations(directResults, settings_.offset, U2Strand::Direct); res += createAnnotations(compResults, settings_.offset, U2Strand::Complementary); return res; } QList FindPolyRegionsTask::createAnnotations(const QVector& regions, qint64 offset, U2Strand::Direction strand) { QList res; foreach(U2Region r, regions) { SharedAnnotationData d(new AnnotationData()); r.startPos += offset; d->location->regions.append(r); d->location->strand = strand; res.append(d); } return res; } static const QString UNIT_ID("find-poly"); static const QString BASE_ATTR("base"); static const QString PERCENT_ATTR("percent"); static const QString MIN_LEN_ATTR("min-len"); static const QString MAX_LEN_ATTR("max-len"); QDFindPolyActor::QDFindPolyActor( QDActorPrototype const* proto ) : QDActor(proto) { units[UNIT_ID] = new QDSchemeUnit(this); } int QDFindPolyActor::getMinResultLen() const { return cfg->getParameter(MIN_LEN_ATTR)->getAttributeValue(); } int QDFindPolyActor::getMaxResultLen() const { return cfg->getParameter(MAX_LEN_ATTR)->getAttributeValue(); } QString QDFindPolyActor::getText() const { return tr("Searches regions in a sequence that contain a specified percentage of a certain base."); } Task* QDFindPolyActor::getAlgorithmTask( const QVector& location ) { DNASequence sequence = scheme->getDNA()->getDNASequence(); FindPolyRegionsSettings settings; settings.strand = getStrandToRun(); if (settings.strand != QDStrand_DirectOnly) { QList compTTs = AppContext::getDNATranslationRegistry()->lookupTranslation(scheme->getDNA()->getAlphabet(), DNATranslationType_NUCL_2_COMPLNUCL); if (!compTTs.isEmpty()) { settings.complTT = compTTs.first(); } else { QString err = tr("Could not find complement translation"); return new FailTask(err); } } QString baseStr = cfg->getParameter(BASE_ATTR)->getAttributeValue(); if (baseStr.size()!=1) { QString err = tr("'%1' error. Incorrect value of 'Base' parameter.").arg(cfg->getLabel()); return new FailTask(err); } settings.ch = baseStr.at(0).toAscii(); int percent = cfg->getParameter(PERCENT_ATTR)->getAttributeValue(); if (percent < 50 || percent > 100) { algoLog.error(tr("'%1' error. Percent parameter should be not less than 50% not higher than 100%. Setting up default value: 90%.")); settings.percent = 90; } else { settings.percent = percent; } int minLen = cfg->getParameter(MIN_LEN_ATTR)->getAttributeValue(); if (minLen<5 || minLen>sequence.length()) { QString err = tr("'%1' error. Min length should be not less than 5 and not higher than sequence length.").arg(cfg->getLabel()); return new FailTask(err); } settings.minLen = minLen; Task* t = new Task(tr("Search poly regions QD task"), TaskFlag_NoRun); foreach(U2Region r, location) { FindPolyRegionsSettings stngs(settings); stngs.offset = r.startPos; FindPolyRegionsTask* sub = new FindPolyRegionsTask(stngs, sequence); t->addSubTask(sub); connect(new TaskSignalMapper(sub), SIGNAL(si_taskFinished(Task*)), SLOT(sl_onTaskFinished(Task*))); } return t; } void QDFindPolyActor::sl_onTaskFinished(Task* t) { FindPolyRegionsTask* fprt = qobject_cast(t); QList annotations = fprt->getResultAsAnnotations(); foreach(SharedAnnotationData d, annotations) { if (d->location->regions.first().length > getMaxResultLen()) { continue; } QDResultUnit ru(new QDResultUnitData); ru->region = d->location->regions.first(); ru->strand = d->location->strand; ru->owner = units.value(UNIT_ID); QDResultGroup* g = new QDResultGroup(QDStrand_DirectOnly); g->add(ru); results.append(g); } } QDFindPolyActorPrototype::QDFindPolyActorPrototype() { descriptor.setId("base-content"); descriptor.setDisplayName(QDFindPolyActor::tr("BaseContent")); descriptor.setDocumentation(QDFindPolyActor::tr( "Searches regions in a sequence that contain a specified percentage" " of a certain base.")); Descriptor bd(BASE_ATTR, QDFindPolyActor::tr("Base"), QDFindPolyActor::tr("Specifies the base.")); Descriptor pd(PERCENT_ATTR, QDFindPolyActor::tr("Percentage"), QDFindPolyActor::tr("Percentage of the base in a region.")); Descriptor mind(MIN_LEN_ATTR, QDFindPolyActor::tr("Min Length"), QDFindPolyActor::tr("Minimum length of a region.")); Descriptor maxd(MAX_LEN_ATTR, QDFindPolyActor::tr("Max Length"), QDFindPolyActor::tr("Maximum length of a region.")); attributes << new Attribute(bd, BaseTypes::STRING_TYPE(), true); attributes << new Attribute(pd, BaseTypes::NUM_TYPE(), true, QVariant(90)); attributes << new Attribute(mind, BaseTypes::NUM_TYPE(), false, QVariant(50)); attributes << new Attribute(maxd, BaseTypes::NUM_TYPE(), false, QVariant(1000)); QMap delegates; { QVariantMap bm; bm.insert("A","A"); bm.insert("G","G"); bm.insert("C","C"); bm.insert("T","T"); delegates[BASE_ATTR] = new ComboBoxDelegate(bm); QVariantMap m; m["minimum"] = 50; m["maximum"] = 100; m["suffix"] = "%"; delegates[PERCENT_ATTR] = new SpinBoxDelegate(m); QVariantMap lenMap; lenMap["minimum"] = 5; lenMap["maximum"]=INT_MAX; lenMap["suffix"] = " bp"; delegates[MIN_LEN_ATTR] = new SpinBoxDelegate(lenMap); delegates[MAX_LEN_ATTR] = new SpinBoxDelegate(lenMap); } editor = new DelegateEditor(delegates); } } //namespace ugene-1.9.8/src/plugins/query_designer/src/library/QDFindPolyRegionsActor.h0000644000175000017500000000524411651544324025516 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_QD_FIND_POLY_ACTOR_H_ #define _U2_QD_FIND_POLY_ACTOR_H_ #include #include #include namespace U2 { class DNATranslation; class FindPolyRegionsSettings { public: char ch; int percent; qint64 minLen; qint64 offset; DNATranslation* complTT; QDStrandOption strand; FindPolyRegionsSettings() : ch('A'), percent(0.9f), minLen(0), offset(0), complTT(NULL) {} }; class FindPolyRegionsTask : public Task { Q_OBJECT public: FindPolyRegionsTask(const FindPolyRegionsSettings& settings, const DNASequence& sequence) : Task(tr("Find base content task"), TaskFlag_None), settings_(settings), sequence_(sequence) {} void run(); QList getResultAsAnnotations() const; private: void find(const char* seq, qint64 seqLen, char ch, int percent, qint64 len, QVector& result ); static QList createAnnotations(const QVector& regions, qint64 offset, U2Strand::Direction strand); private: FindPolyRegionsSettings settings_; DNASequence sequence_; QVector directResults; QVector compResults; }; class QDFindPolyActor : public QDActor { Q_OBJECT public: QDFindPolyActor(QDActorPrototype const* proto); int getMinResultLen() const; int getMaxResultLen() const; QString getText() const; Task* getAlgorithmTask(const QVector& location); QColor defaultColor() const { return QColor(0xff, 0xc6, 0); } private slots: void sl_onTaskFinished(Task*); }; class QDFindPolyActorPrototype : public QDActorPrototype { public: QDFindPolyActorPrototype(); virtual QDActor* createInstance() const { return new QDFindPolyActor(this); } }; } //namespace #endif ugene-1.9.8/src/plugins/query_designer/src/library/QDFindActor.cpp0000644000175000017500000001122111651544324023646 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "QDFindActor.h" #include #include #include #include #include #include #include namespace U2 { static const QString PATTERN_ATTR("pattern"); QDFindActor::QDFindActor(QDActorPrototype const* proto) : QDActor(proto) { units["find"] = new QDSchemeUnit(this); } int QDFindActor::getMinResultLen() const { return cfg->getParameter(PATTERN_ATTR)->getAttributeValue().length(); } int QDFindActor::getMaxResultLen() const { return getMinResultLen(); } QString QDFindActor::getText() const { QString hypPtrn = cfg->getParameter(PATTERN_ATTR)->getAttributeValue().toUpper(); if (hypPtrn.isEmpty()) { hypPtrn = QString("<
pattern>").arg(PATTERN_ATTR); } else { hypPtrn = QString("%2") .arg(PATTERN_ATTR) .arg(hypPtrn); } return hypPtrn; } Task* QDFindActor::getAlgorithmTask(const QVector& location) { Task* t = new Task(tr("Find"), TaskFlag_NoRun); settings.sequence = scheme->getDNA()->getSequence(); settings.pattern = cfg->getParameter(PATTERN_ATTR)->getAttributeValue().toAscii().toUpper(); switch(getStrandToRun()) { case QDStrand_Both: settings.strand = FindAlgorithmStrand_Both; break; case QDStrand_DirectOnly: settings.strand = FindAlgorithmStrand_Direct; break; case QDStrand_ComplementOnly: settings.strand = FindAlgorithmStrand_Complement; break; } if (settings.strand != FindAlgorithmStrand_Direct) { QList compTTs = AppContext::getDNATranslationRegistry()->lookupTranslation(scheme->getDNA()->getAlphabet(), DNATranslationType_NUCL_2_COMPLNUCL); if (!compTTs.isEmpty()) { settings.complementTT = compTTs.first(); } else { QString err = tr("%1: can not find complement translation.").arg(getParameters()->getLabel()); return new FailTask(err); } } if (settings.pattern.isEmpty()) { QString err = tr("%1: pattern is empty.").arg(getParameters()->getLabel()); return new FailTask(err); } DNAAlphabet* ptrnAl = AppContext::getDNAAlphabetRegistry()->findAlphabet(settings.pattern); if (ptrnAl->getType()!=DNAAlphabet_NUCL) { QString err = tr("%1: pattern has to be nucleic").arg(getParameters()->getLabel()); return new FailTask(err); } foreach(const U2Region& r, location) { FindAlgorithmTaskSettings s(settings); s.searchRegion = r; FindAlgorithmTask* findTask = new FindAlgorithmTask(s); connect(new TaskSignalMapper(findTask), SIGNAL(si_taskFinished(Task*)), SLOT(sl_onFindTaskFinished(Task*))); t->addSubTask(findTask); } return t; } void QDFindActor::sl_onFindTaskFinished(Task* t) { FindAlgorithmTask* findTask = qobject_cast(t); QList res = findTask->popResults(); foreach(const FindAlgorithmResult& r, res) { QDResultUnit ru(new QDResultUnitData); ru->strand = r.strand; ru->region = r.region; ru->owner = units.value("find"); QDResultGroup* g = new QDResultGroup(QDStrand_DirectOnly); g->add(ru); results.append(g); } } QDFindActorPrototype::QDFindActorPrototype() { descriptor.setId("search"); descriptor.setDisplayName(QDFindActor::tr("Pattern")); descriptor.setDocumentation(QDFindActor::tr("Finds pattern.")); Descriptor pd(PATTERN_ATTR, QDFindActor::tr("Pattern"), QDFindActor::tr("A subsequence pattern to look for.")); attributes << new Attribute(pd, BaseTypes::STRING_TYPE(), true); } }//namespace ugene-1.9.8/src/plugins/query_designer/src/QDDocumentFormat.h0000644000175000017500000000567011651544323022737 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_QD_DOC_FORMAT_H_ #define _U2_QD_DOC_FORMAT_H_ #include #include #include #include #include "QueryDesignerPlugin.h" namespace U2 { class QDDocFormat : public DocumentFormat { Q_OBJECT public: QDDocFormat(QObject* p); static const DocumentFormatId FORMAT_ID; virtual DocumentFormatId getFormatId() const {return FORMAT_ID;} virtual const QString& getFormatName() const {return formatName;} virtual Document* createNewDocument(IOAdapterFactory* io, const QString& url, const QVariantMap& fs = QVariantMap()); virtual Document* loadDocument(IOAdapter* io, TaskStateInfo& ti, const QVariantMap& fs, DocumentLoadMode mode = DocumentLoadMode_Whole); virtual void storeDocument( Document* d, TaskStateInfo& ts, IOAdapter* io); virtual RawDataCheckResult checkRawData(const QByteArray& rawData, const GUrl& = GUrl()) const; private: QString formatName; }; class QueryScene; class QDGObject : public GObject { Q_OBJECT public: static const GObjectType TYPE; QDGObject(const QString& objectName, const QString& data, const QVariantMap& map = QVariantMap()) : GObject(TYPE, objectName), serializedScene(data), scene(NULL) { Q_UNUSED(map); } virtual GObject* clone() const; QueryScene* getScene() const { return scene; } void setSceneRawData(const QString& d) { serializedScene=d; } QString getSceneRawData() const { return serializedScene; } private: QString serializedScene; QueryScene* scene; }; class QDViewFactory : public GObjectViewFactory { Q_OBJECT public: static const GObjectViewFactoryId ID; QDViewFactory(QObject* p = NULL) : GObjectViewFactory(ID, U2::QueryDesignerPlugin::tr("Query Designer"), p) {} virtual bool canCreateView(const MultiGSelection& multiSelection); virtual Task* createViewTask(const MultiGSelection& multiSelection, bool single = false); }; class OpenQDViewTask : public ObjectViewTask { Q_OBJECT public: OpenQDViewTask(Document* doc); virtual void open(); }; }//namespace #endif ugene-1.9.8/src/plugins/query_designer/src/QDSamples.h0000644000175000017500000000500411651544323021403 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_QD_SAMPLES_H_ #define _U2_QD_SAMPLES_H_ #include #include #include #include namespace U2 { class QDDocument; class QueryScene; class QDSample { public: Descriptor d; QDDocument* content; }; class QDLoadSamplesTask : public Task { Q_OBJECT public: QDLoadSamplesTask(const QStringList& _dirs); virtual QList onSubTaskFinished(Task* subTask); ReportResult report(); private: QMap idMap; QList result; }; class QDSamplesRegistry { public: static const QList& getSamples() { return data; } private: static QList data; friend class QDLoadSamplesTask; }; class QDSamplePane : public GlassPane { Q_OBJECT public: QDSamplePane(QueryScene* _scene); virtual void paint(QPainter* painter); virtual bool eventFilter(QObject*, QEvent* e) { this->event(e); return current != NULL; } void setItem(QListWidgetItem* item) { current=item; } signals: void itemActivated(QListWidgetItem* item); protected: void mouseDoubleClickEvent(QMouseEvent* e); private: QueryScene* scene; QListWidgetItem* current; }; class QDSamplesWidget : public QListWidget { Q_OBJECT public: QDSamplesWidget(QueryScene* scene, QWidget* parent=NULL); signals: void itemActivated(QDDocument*); void setupGlass(GlassPane* glass); private: void addSample(const QDSample& sample); private slots: void sl_onItemChanged(QListWidgetItem* item); void sl_onItemSelected(QListWidgetItem* item); void sl_cancel(); private: QDSamplePane* glass; }; }//namespace #endif ugene-1.9.8/src/plugins/query_designer/src/ui/0000755000175000017500000000000011651544324020020 5ustar ilyailyaugene-1.9.8/src/plugins/query_designer/src/ui/QueryEditorWidget.ui0000644000175000017500000002010011651544324023770 0ustar ilyailya QueryEditorWidget 0 0 312 438 Form 1 1 1 3 1 Property Editor 0 0 TextLabel Qt::AlignHCenter|Qt::AlignTop true Qt::LinksAccessibleByMouse|Qt::TextSelectableByMouse 0 0 true TextLabel TextLabel 0 0 0 0 Qt::Vertical false true 0 1 0 70 false true Qt::TextBrowserInteraction 0 5 Parameters true 0 0 1 0 0 Qt::Vertical 2 false 0 2 0 100 QAbstractItemView::CurrentChanged|QAbstractItemView::DoubleClicked|QAbstractItemView::EditKeyPressed|QAbstractItemView::SelectedClicked true QAbstractItemView::SingleSelection QAbstractItemView::SelectRows Qt::ElideMiddle false false false true 0 1 false true Qt::TextBrowserInteraction ugene-1.9.8/src/plugins/query_designer/src/ui/QDDialog.ui0000644000175000017500000001640311651544324022007 0ustar ilyailya QDDialog 0 0 569 217 Analyze with Query Schema File with query true ... true 0 0 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> <html><head><meta name="qrichtext" content="1" /><style type="text/css"> p, li { white-space: pre-wrap; } </style></head><body style=" font-family:'MS Shell Dlg 2'; font-size:8.25pt; font-weight:400; font-style:normal;"> <p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-size:8pt;">Hint: </span></p> <p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-size:8pt;">Queries can be created using the Query Designer tool. </span></p> <p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-size:8pt;">To launch the Query Designer select the</span><span style=" font-size:8pt; font-style:italic;">&quot;Tools &gt; Query Designer&quot; </span><span style=" font-size:8pt;">item.</span></p></body></html> Qt::TextSelectableByKeyboard|Qt::TextSelectableByMouse 0 0 Range Whole sequence true Selected range Custom range false 100 0 Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter true 1 1 - false 100 0 Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter true 1 1 Qt::Horizontal 93 20 0 0 Qt::Horizontal 40 20 Search Cancel cancelBtn clicked() QDDialog reject() 518 202 283 112 ugene-1.9.8/src/plugins/query_designer/src/ui/RunQueryDialog.ui0000644000175000017500000001143511651544324023275 0ustar ilyailya RunQueryDlg 0 0 502 137 0 0 485 137 Run Schema 0 0 Load sequence 0 0 Save results to true ... ... Qt::Horizontal 40 20 0 0 Add to project true Qt::Vertical 20 0 Qt::Horizontal 40 20 Run Cancel cancelBtn clicked() RunQueryDlg reject() 436 78 242 50 ugene-1.9.8/src/plugins/query_designer/src/ui/AddConstraintDialog.ui0000644000175000017500000001170611651544324024241 0ustar ilyailya AddConstraintDialog 0 0 290 107 Add Constraint 0 0 From 0 0 To 0 0 0 0 0 0 Min 0 0 Max Qt::Vertical 20 13 Qt::Horizontal 40 20 Qt::Horizontal QDialogButtonBox::Cancel|QDialogButtonBox::Ok buttonBox accepted() AddConstraintDialog accept() 248 254 157 274 buttonBox rejected() AddConstraintDialog reject() 316 260 286 274 ugene-1.9.8/src/plugins/query_designer/src/QDGroupsEditor.cpp0000644000175000017500000001357511651544323022774 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "QDGroupsEditor.h" #include "QueryViewController.h" #include #include #include #include #include #include namespace U2 { QDGroupsEditor::QDGroupsEditor( QueryViewController* p ) : view(p) { header()->hide(); setColumnCount(2); initActions(); rebuild(); connect(view->getScheme(), SIGNAL(si_schemeChanged()), SLOT(rebuild())); } void QDGroupsEditor::initActions() { addGroupAction = new QAction(tr("Add Group"), this); connect(addGroupAction, SIGNAL(triggered(bool)), SLOT(sl_addGroup())); removeGroupAction = new QAction(tr("Remove Group"), this); connect(removeGroupAction, SIGNAL(triggered(bool)), SLOT(sl_removeGroup())); addActorAction = new QAction(tr("Add Element"), this); connect(addActorAction, SIGNAL(triggered(bool)), SLOT(sl_addActor())); removeActorAction = new QAction(tr("Remove Element"), this); connect(removeActorAction, SIGNAL(triggered(bool)), SLOT(sl_removeActor())); setGroupReqNumAction = new QAction(tr("Set Required Number"), this); connect(setGroupReqNumAction, SIGNAL(triggered(bool)), SLOT(sl_setReqNum())); } void QDGroupsEditor::rebuild() { clear(); QDScheme* scheme = view->getScheme(); foreach(const QString& group, scheme->getActorGroups()) { QStringList grpItemTexts; int grpSize = scheme->getActors(group).size(); int reqNum = grpSize ? scheme->getRequiredNumber(group) : 0; QString countLbl = QString("%1/%2") .arg(reqNum) .arg(grpSize); grpItemTexts << group << countLbl; QTreeWidgetItem* groupItem = new QTreeWidgetItem(this, grpItemTexts); addTopLevelItem(groupItem); foreach(QDActor const* actor, scheme->getActors(group)) { const QString& actorLabel = actor->getParameters()->getLabel(); /*QTreeWidgetItem* actorItem = */new QTreeWidgetItem(groupItem, QStringList(actorLabel)); } } } void QDGroupsEditor::mousePressEvent( QMouseEvent *event ) { if (event->buttons()&Qt::RightButton) { QTreeWidgetItem* item = currentItem();// = itemAt(event->pos()); QMenu m; if (!item) { m.addAction(addGroupAction); } else if (item->parent()){ m.addAction(addActorAction); m.addAction(removeActorAction); } else { m.addAction(addActorAction); m.addAction(addGroupAction); m.addAction(removeGroupAction); m.addAction(setGroupReqNumAction); } m.exec(event->globalPos()); } QTreeWidget::mousePressEvent(event); } static const QString MSGBOX_TITLE = QDGroupsEditor::tr("Query Designer"); void QDGroupsEditor::sl_addGroup() { QDScheme* scheme = view->getScheme(); bool ok; QString text = QInputDialog::getText(this, tr("Create element group"), tr("Group name"), QLineEdit::Normal, QString(), &ok); if (!ok) { return; } if (scheme->getActorGroups().contains(text)) { QMessageBox::critical(NULL, MSGBOX_TITLE, tr("Group '%1' already exists!").arg(text)); return; } if (!scheme->validateGroupName(text)) { QMessageBox::critical(NULL, MSGBOX_TITLE, tr("Invalid group name!")); return; } scheme->createActorGroup(text); } void QDGroupsEditor::sl_removeGroup() { assert(!currentItem()->parent()); view->getScheme()->removeActorGroup(currentItem()->text(0)); } void QDGroupsEditor::sl_addActor() { QDScheme* scheme = view->getScheme(); QTreeWidgetItem* item = currentItem(); assert(item); if (item->parent()) { item = item->parent(); } QString group = item->text(0); QStringList list; foreach(QDActor* a, scheme->getActors()) { list << a->getParameters()->getLabel(); } if (list.isEmpty()) { return; } bool ok; QString label = QInputDialog::getItem(this, tr("Add Element To Group '%1'").arg(group), tr("Element:"), list, 0, false, &ok); if (!ok) { return; } QDActor* sel = scheme->getActorByLabel(label); assert(sel); if (!scheme->getActorGroup(sel).isEmpty()) { QMessageBox::critical(this, MSGBOX_TITLE, tr("Actor is already in group!")); return; } scheme->addActorToGroup(sel, group); //item->setExpanded(true); } void QDGroupsEditor::sl_removeActor() { QDScheme* scheme = view->getScheme(); assert(currentItem()); assert(currentItem()->parent()); QDActor* sel = scheme->getActorByLabel(currentItem()->text(0)); scheme->removeActorFromGroup(sel); } void QDGroupsEditor::sl_setReqNum() { QDScheme* scheme = view->getScheme(); assert(currentItem()); assert(!currentItem()->parent()); QString group = currentItem()->text(0); bool ok; int num = QInputDialog::getInt(this, tr("Set required number for '%1'").arg(group), tr("Number:"), 1, 1, scheme->getActors(group).size(), 1, &ok); if (ok) { scheme->setRequiredNum(group, num); } } }//namespace ugene-1.9.8/src/plugins/query_designer/src/QueryPalette.h0000644000175000017500000000416111651544324022202 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_QUERY_PALETTE_H_ #define _U2_QUERY_PALETTE_H_ #include #include namespace U2 { class QDDistanceIds { public: static const QString E2S; static const QString S2E; static const QString E2E; static const QString S2S; }; class QDActorPrototype; class QueryPalette : public QTreeWidget { Q_OBJECT public: static const QString MIME_TYPE; QueryPalette(QWidget* parent=NULL); QVariant saveState() const; void restoreState(const QVariant&); signals: void processSelected(QDActorPrototype*); protected: void mousePressEvent(QMouseEvent *event); void mouseMoveEvent(QMouseEvent *event); void leaveEvent(QEvent *); private slots: void sl_selectProcess(bool checked=false); private: void setContent(); QAction* createItemAction(QDActorPrototype* item); QAction* createItemAction(const QString& constraintId); private: QTreeWidgetItem* overItem; QAction* currentAction; QPoint dragStartPosition; // < category id, item ids > ids r used as display names QMap< QString, QList > categoryMap; QMap actionMap; friend class PaletteDelegate; }; }//namespace Q_DECLARE_METATYPE(QAction *) Q_DECLARE_METATYPE(U2::QDActorPrototype *) #endif ugene-1.9.8/src/plugins/query_designer/src/QDSamples.cpp0000644000175000017500000001223511651544323021742 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "QDSamples.h" #include "QDDocument.h" #include "QDSceneIOTasks.h" #include "QueryViewController.h" #include #include #include #include Q_DECLARE_METATYPE(QTextDocument*); namespace U2 { QList QDSamplesRegistry::data; QDLoadSamplesTask::QDLoadSamplesTask(const QStringList& _dirs) : Task(tr("Load query samples"), TaskFlag_NoRun) { foreach(const QString& s, _dirs) { QDir dir(s); QStringList names(QString("*.%1").arg(QUERY_SCHEME_EXTENSION)); foreach(const QFileInfo& fi, dir.entryInfoList(names, QDir::Files|QDir::NoSymLinks)) { const QString& file = fi.absoluteFilePath(); QDLoadDocumentTask* t = new QDLoadDocumentTask(file); addSubTask(t); idMap[t] = file; } } } QList QDLoadSamplesTask::onSubTaskFinished(Task* subTask) { QList st; if (isCanceled()) { return st; } QDLoadDocumentTask* loadTask = qobject_cast(subTask); assert(loadTask); QDSample sample; sample.content = loadTask->getDocument(); sample.d.setId(idMap.value(loadTask)); sample.d.setDisplayName(sample.content->getName()); sample.d.setDocumentation(sample.content->getDocDesc()); result.append(sample); return st; } Task::ReportResult QDLoadSamplesTask::report() { QDSamplesRegistry::data = result; return ReportResult_Finished; } #define DATA_ROLE Qt::UserRole #define DOC_ROLE Qt::UserRole + 1 QDSamplesWidget::QDSamplesWidget(QueryScene* scene, QWidget* parent/* =NULL */) : QListWidget(parent) { setWordWrap(true); foreach(const QDSample& sample, QDSamplesRegistry::getSamples()) { addSample(sample); } glass = new QDSamplePane(scene); connect(this, SIGNAL(currentItemChanged(QListWidgetItem*,QListWidgetItem*)),SLOT(sl_onItemChanged(QListWidgetItem*))); connect(this, SIGNAL(itemDoubleClicked(QListWidgetItem*)),SLOT(sl_onItemSelected(QListWidgetItem*))); connect(glass, SIGNAL(itemActivated(QListWidgetItem*)), SLOT(sl_onItemSelected(QListWidgetItem*))); } void QDSamplesWidget::addSample(const QDSample& sample) { QListWidgetItem* item = new QListWidgetItem(sample.d.getDisplayName(), this); item->setData(DATA_ROLE, qVariantFromValue(sample.content)); QTextDocument* txtDoc = new QTextDocument(this); QIcon ico; ico.addPixmap(QDUtils::generateSnapShot(sample.content, QRect())); DesignerGUIUtils::setupSamplesDocument(sample.d, ico, txtDoc); item->setData(DOC_ROLE, qVariantFromValue(txtDoc)); } void QDSamplesWidget::sl_onItemChanged(QListWidgetItem* item) { if (item && !item->data(DATA_ROLE).isValid()) { item = NULL; } assert(glass); glass->setItem(item); emit setupGlass(glass); } void QDSamplesWidget::sl_onItemSelected(QListWidgetItem* item) { QDDocument* doc = qVariantValue(item->data(DATA_ROLE)); assert(doc); emit itemActivated(doc); } void QDSamplesWidget::sl_cancel() { selectionModel()->clear(); if (isHidden()) { emit setupGlass(NULL); glass->setItem(NULL); } else { emit setupGlass(glass); } } QDSamplePane::QDSamplePane(QueryScene* _scene) : scene(_scene), current(NULL) {} void QDSamplePane::paint(QPainter* painter) { if (!current && scene->getScheme()->getActors().isEmpty()) { DesignerGUIUtils::paintSamplesArrow(painter); return; } if (current) { QTextDocument* doc = current->data(DOC_ROLE).value(); DesignerGUIUtils::paintSamplesDocument(painter, doc, width(), height(), palette()); } } void QDSamplePane::mouseDoubleClickEvent(QMouseEvent* e) { if (current == NULL) { return; } QTextDocument* doc = current->data(DOC_ROLE).value(); int pageWidth = qMax(width() - 100, 100); int pageHeight = qMax(height() - 100, 100); if (pageWidth != doc->pageSize().width()) { doc->setPageSize(QSize(pageWidth, pageHeight)); } QSize ts = doc->size().toSize(); QRect textRect; textRect.setSize(ts); QPoint position = e->pos(); if(textRect.contains(position)) { emit itemActivated(current); } else { current = NULL; scene->update(); } } }//namespace ugene-1.9.8/src/plugins/query_designer/src/QueryProcCfgDelegate.h0000644000175000017500000000620011651544324023556 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ /************************************************************************/ /* Copy of "workflow_designer/ProxyDelegate.h" */ /************************************************************************/ #ifndef _U2_QUERY_PROC_CFG_DELEGATE_H_ #define _U2_QUERY_PROC_CFG_DELEGATE_H_ #include "QueryEditor.h" #include #include Q_DECLARE_METATYPE(U2::PropertyDelegate*) namespace U2 { enum { DelegateRole = Qt::UserRole + 100, DescriptorRole }; class QueryProcCfgDelegate : public QItemDelegate { public: QueryProcCfgDelegate(QueryEditor* parent) : QItemDelegate(parent) {} QWidget* createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const { QItemDelegate* d = index.model()->data(index, DelegateRole).value(); if (d) { connect(d, SIGNAL(commitData(QWidget*)), SIGNAL(commitData(QWidget*))); return d->createEditor(parent, option, index); } return QItemDelegate::createEditor(parent, option, index); } void setEditorData(QWidget *editor, const QModelIndex &index) const { QItemDelegate* d = index.model()->data(index, DelegateRole).value(); if (d) { d->setEditorData(editor, index); return; } QItemDelegate::setEditorData(editor, index); } void setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const { QVariant old; PropertyDelegate* d = model->data(index, DelegateRole).value(); if (d) { old = model->data(index, ConfigurationEditor::ItemValueRole); d->setModelData(editor, model, index); } else { old = model->data(index, Qt::EditRole); QItemDelegate::setModelData(editor, model, index); } QVariant val = model->data(index, (d == NULL) ? (int)Qt::EditRole : (int)ConfigurationEditor::ItemValueRole); if (val != old) { if (d) { model->setData(index, d->getDisplayValue(val), Qt::DisplayRole); } model->setData(index, model->data(index, Qt::DisplayRole).toString(), Qt::ToolTipRole); } } }; }//namespace #endif ugene-1.9.8/src/plugins/query_designer/src/QDGroupsEditor.h0000644000175000017500000000306211651544323022427 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_QD_GROUPS_EDITOR_H_ #define _U2_QD_GROUPS_EDITOR_H_ #include namespace U2 { class QueryViewController; class QDGroupsEditor : public QTreeWidget { Q_OBJECT public: QDGroupsEditor(QueryViewController* p); protected: virtual void mousePressEvent(QMouseEvent *event); private slots: void sl_addGroup(); void sl_removeGroup(); void sl_addActor(); void sl_removeActor(); void sl_setReqNum(); void rebuild(); private: void initActions(); private: QueryViewController* view; QAction* addGroupAction; QAction* removeGroupAction; QAction* addActorAction; QAction* removeActorAction; QAction* setGroupReqNumAction; }; }//namespace #endif ugene-1.9.8/src/plugins/query_designer/src/QDDocument.h0000644000175000017500000001217511651544323021564 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_GRAPH_DOCUMENT_H_ #define _U2_GRAPH_DOCUMENT_H_ #include #include #include namespace U2 { class QDDocument; class QDDocStatement { public: const QList< QPair >& getAttributes() const { return attributes; } QString getAttribute(const QString& name) const; void setAttribute(const QString& name, const QString& value); void setComment(const QString& com) { comment = com; } const QString& getComment() const { return comment; } virtual QString toString() const; protected: int evalStringLen() const; protected: QString comment; QList< QPair > attributes; }; enum QDStatementType { Element, Group }; class QDElementStatement : public QDDocStatement { friend class QDDocument; public: QDElementStatement(const QString& _id, QDStatementType _type) : id(_id), type(_type), document(NULL) {} const QString& getId() const { return id; } QDStatementType getType() const { return type; } QString toString() const; QString definedIn() const; QDDocument* getDocument() const { return document; } public: static const QString GEOMETRY_ATTR_NAME; static const QString ALGO_ATTR_NAME; private: QString id; QDStatementType type; QDDocument* document; }; class QDLinkStatement : public QDDocStatement { friend class QDDocument; public: QDLinkStatement(const QList& ids) : elementIds(ids), document(NULL) {} const QList& getElementIds() const { return elementIds; } QString toString() const; QDDocument* getDocument() const { return document; } public: static const QString TYPE_ATTR_NAME; private: QList elementIds; QDDocument* document; }; class QDDocument : QObject { Q_OBJECT public: QDDocument() : schemaStrand(QDStrand_Both) {} ~QDDocument(); bool setContent(const QString& content); QByteArray toByteArray() const; void setName(const QString& name) { docName = name; } const QString& getName() const { return docName; } bool addElement(QDElementStatement* el); void addLink(QDLinkStatement* lnk) { assert(lnk->document==NULL); links.append(lnk); lnk->document = this; } const QList& getElements() const { return elements; } QList getElements(QDStatementType type) const; QDElementStatement* getElement(const QString& id) const; const QList& getLinks() const { return links; } const QList& getImportedUrls() const { return importedUrls; } static QString definedIn(const QString& id); static QString getLocalName(const QString& id); QDElementStatement* findElementByUnitName(QDElementStatement* parent, const QString& unitName) const; const QString& getDocDesc() const { return docDesc; } void setDocDesc(const QString& newDesc) { docDesc = newDesc; } const QStringList& getOrder() const { return order; } void saveOrder(const QList& actors); void parseSchemaStrand(const QString& str); QDStrandOption getSchemaStrand() const { return schemaStrand; } void setSchemaStrand(QDStrandOption stOp) { schemaStrand = stOp; } public: static const QString HEADER_LINE; static const QString GROUPS_SECTION; static const QString ID_PATTERN; private: void findImportedUrls(const QString& str); bool findElementStatements(const QString& str); bool findLinkStatements(const QString& str); void findComments(const QString& str); void parseOrder(const QString& str); static QMap string2attributesMap(const QString& str); static QList idsFromString(const QString& str); private: QString docName; QList elements; QList links; QList importedUrls; QString docDesc; //ID, comment QMap comments; QStringList order; QDStrandOption schemaStrand; }; class QDIdMapper { public: static QString distance2string(QDDistanceType type); static int string2distance(const QString& str); static QDConstraintType string2constraintType(const QString& str); static QString constraintType2string(const QDConstraintType& type); }; }//namespace Q_DECLARE_METATYPE(U2::QDDocument*) #endif ugene-1.9.8/src/plugins/query_designer/src/QDRunDialog.cpp0000644000175000017500000003763211651544323022232 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "QDRunDialog.h" #include "QDSceneIOTasks.h" #include "QueryViewController.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include namespace U2 { /************************************************************************/ /* Dialog for run from designer window */ /************************************************************************/ QDRunDialog::QDRunDialog(QDScheme* _scheme, QWidget* parent, const QString& defaultIn, const QString& defaultOut) : QDialog(parent), scheme(_scheme) { setupUi(this); inFileEdit->setText(defaultIn); outFileEdit->setText(defaultOut); connect(tbInFile, SIGNAL(clicked()), SLOT(sl_selectFile())); connect(tbOutFile, SIGNAL(clicked()), SLOT(sl_selectFile())); connect(runBtn, SIGNAL(clicked()), SLOT(sl_run())); } void QDRunDialog::sl_selectFile() { QToolButton* tb = qobject_cast(sender()); assert(tb); QLineEdit* edit = NULL; if (tb==tbInFile) { edit = inFileEdit; } else { assert(tb==tbOutFile); edit = outFileEdit; } QString title; QString fileFilter; if (edit==inFileEdit) { title = tr("Select input file"); fileFilter = DialogUtils::prepareDocumentsFileFilterByObjType(GObjectTypes::SEQUENCE, true); } else { title = tr("Select output file"); fileFilter = DialogUtils::prepareDocumentsFileFilter(BaseDocumentFormats::PLAIN_GENBANK, true, QStringList()); } LastOpenDirHelper dir; if (!edit->text().isEmpty()) { QFileInfo fi(edit->text()); dir.url = fi.absoluteFilePath(); dir.dir = fi.absolutePath(); } if (edit==inFileEdit) { dir.url = QFileDialog::getOpenFileName(this, title, dir, fileFilter); } else { dir.url = QFileDialog::getSaveFileName(this, title, dir, fileFilter); } if (!dir.url.isEmpty()) { edit->setText(dir.url); QueryViewController* view = qobject_cast(parentWidget()); assert(view); if (edit==inFileEdit) { view->setDefaultInFile(dir.url); } else { view->setDefaultOutFile(dir.url); } } } void QDRunDialog::sl_run() { const QString& inUri = inFileEdit->text(); const QString& outUri = outFileEdit->text(); if (inUri.isEmpty()) { QMessageBox::critical(this, L10N::errorTitle(), tr("The sequence is not specified!")); return; } if (outUri.isEmpty()) { QMessageBox::critical(this, L10N::errorTitle(), tr("The output file is not selected!")); return; } QDRunDialogTask* t = new QDRunDialogTask(scheme, inUri, outUri, cbAddToProj->isChecked()); AppContext::getTaskScheduler()->registerTopLevelTask(t); QDialog::accept(); } /************************************************************************/ /* Task */ /************************************************************************/ QDRunDialogTask::QDRunDialogTask(QDScheme* _scheme, const QString& _inUri, const QString& outUri, bool addToProject) : Task(tr("Query Designer"), TaskFlags_NR_FOSCOE), scheme(_scheme), inUri(_inUri), output(outUri), addToProject(addToProject), openProjTask(NULL), loadTask(NULL), scheduler(NULL), docWithSequence(NULL), ato(NULL) { tpm = Progress_Manual; stateInfo.progress = 0; if (addToProject && !AppContext::getProject()) { openProjTask = AppContext::getProjectLoader()->createNewProjectTask(); addSubTask(openProjTask); } else { const QList& tasks = init(); foreach(Task* t, tasks) { addSubTask(t); } } } void QDRunDialogTask::sl_updateProgress() { assert(scheduler); stateInfo.progress = scheduler->getProgress(); } QList QDRunDialogTask::init() { QList res; if (AppContext::getProject()) { foreach(Document* doc, AppContext::getProject()->getDocuments()) { if (doc->getURLString()==inUri) { docWithSequence = doc; break; } } } if (docWithSequence) { if (!docWithSequence->isLoaded()) { loadTask = new LoadUnloadedDocumentTask(docWithSequence); res.append(loadTask); } else { setupQuery(docWithSequence); res.append(scheduler); } } else { IOAdapterFactory* iof = AppContext::getIOAdapterRegistry()->getIOAdapterFactoryById(BaseIOAdapters::url2io(inUri)); assert(iof); QList dfs = DocumentUtils::detectFormat(inUri); if (dfs.isEmpty()) { setError(tr("")); } else { foreach(const FormatDetectionResult& i, dfs){ if (i.format->getSupportedObjectTypes().contains(GObjectTypes::SEQUENCE)) { loadTask = new LoadDocumentTask(i.format->getFormatId(), inUri, iof); res.append(loadTask); break; } } if (!loadTask) { setError(tr("Sequence not found!")); } } } return res; } void QDRunDialogTask::setupQuery(Document* doc) { const QList& objs = doc->findGObjectByType(GObjectTypes::SEQUENCE); if (!objs.isEmpty()) { DNASequenceObject* seqObj = qobject_cast(objs.first()); assert(seqObj); scheme->setDNA(seqObj); QDRunSettings settings; settings.region = seqObj->getSequenceRange(); settings.scheme = scheme; settings.sequenceObj = seqObj; settings.annotationsObj = new AnnotationTableObject(GObjectTypes::getTypeInfo(GObjectTypes::ANNOTATION_TABLE).name); settings.annotationsObj->addObjectRelation(seqObj, GObjectRelationRole::SEQUENCE); scheduler = new QDScheduler(settings); connect(scheduler, SIGNAL(si_progressChanged()), SLOT(sl_updateProgress())); } } QList QDRunDialogTask::onSubTaskFinished(Task* subTask) { QList st; if (hasError() || isCanceled()) { return st; } if (subTask == openProjTask) { st << init(); } else if (subTask == loadTask) { if (!docWithSequence) { LoadDocumentTask* t = qobject_cast(subTask); assert(t); docWithSequence = t->getDocument(); } setupQuery(docWithSequence); st.append(scheduler); } else if (subTask == scheduler) { DocumentFormatRegistry* dfr = AppContext::getDocumentFormatRegistry(); DocumentFormat* df = dfr->getFormatById(BaseDocumentFormats::PLAIN_GENBANK); IOAdapterRegistry* ior = AppContext::getIOAdapterRegistry(); IOAdapterFactory* io = ior->getIOAdapterFactoryById(BaseIOAdapters::LOCAL_FILE); GUrl url(output, GUrl_File); QList gobjects; gobjects.append(scheduler->getSettings().annotationsObj); Document* docWithAnnotations = new Document(df, io, url, gobjects); Project* proj = AppContext::getProject(); if (!addToProject) { scheme->setDNA(NULL); SaveDocumentTask* saveTask = new SaveDocumentTask(docWithAnnotations, SaveDoc_DestroyAfter, QSet()); st.append(saveTask); } else { Document* sameUrlDoc = proj->findDocumentByURL(url); if (sameUrlDoc) { proj->removeDocument(sameUrlDoc); } st.append(new SaveDocumentTask(docWithAnnotations)); st.append(new AddDocumentTask(docWithAnnotations)); assert(docWithSequence && docWithSequence->isLoaded()); if (proj && proj->getDocuments().contains(docWithSequence)) { st.append(new OpenViewTask(docWithSequence)); } else { const GUrl& fullPath = docWithSequence->getURL(); DocumentFormat* format = docWithSequence->getDocumentFormat(); IOAdapterFactory * iof = docWithSequence->getIOAdapterFactory(); Document* clonedDoc = new Document(format, iof, fullPath); clonedDoc->loadFrom(docWithSequence); assert(!clonedDoc->isTreeItemModified()); assert(clonedDoc->isLoaded()); st.append(new AddDocumentTask(clonedDoc)); st.append(new OpenViewTask(clonedDoc)); } } } return st; } /************************************************************************/ /* Dialog for dna view context menu */ /************************************************************************/ QDDialog::QDDialog(ADVSequenceObjectContext* _ctx) : QDialog(_ctx->getAnnotatedDNAView()->getWidget()), ctx(_ctx), scheme(NULL), txtDoc(NULL) { setupUi(this); addAnnotationsWidget(); setParameters(); connectGUI(); } void QDDialog::addAnnotationsWidget() { DNASequenceObject *dnaso = qobject_cast(ctx->getSequenceGObject()); CreateAnnotationModel acm; acm.sequenceObjectRef = GObjectReference(dnaso); acm.hideAnnotationName = true; acm.hideLocation = true; acm.data->name = "Query_results"; acm.useUnloadedObjects = true; acm.sequenceLen = dnaso->getSequenceLen(); cawc = new CreateAnnotationWidgetController(acm, this); QWidget* caw = cawc->getWidget(); QVBoxLayout* l = new QVBoxLayout(); l->setMargin(0); l->addWidget(caw); annotationsWidget->setLayout(l); annotationsWidget->setMinimumSize(caw->layout()->minimumSize()); } void QDDialog::connectGUI() { connect(tbSelectQuery, SIGNAL(clicked()), SLOT(sl_selectScheme())); connect(spinRangeStart, SIGNAL(valueChanged(int)), SLOT(sl_rangeStartChanged(int))); connect(spinRangeEnd, SIGNAL(valueChanged(int)), SLOT(sl_rangeEndChanged(int))); connect(radioCustomRange, SIGNAL(toggled(bool)), SLOT(sl_radioCustomRangeToggled(bool))); connect(okBtn, SIGNAL(clicked()), SLOT(sl_okBtnClicked())); } void QDDialog::setParameters() { const U2Region& range = ctx->getSequenceObject()->getSequenceRange(); spinRangeStart->setMinimum(range.startPos); spinRangeStart->setMaximum(range.endPos()); spinRangeStart->setValue(range.startPos); spinRangeEnd->setMinimum(range.startPos); spinRangeEnd->setMaximum(range.endPos()); spinRangeEnd->setValue(range.endPos()); const QVector& selectedRegions = ctx->getSequenceSelection()->getSelectedRegions(); if (!selectedRegions.isEmpty()) { radioSelectedRange->setChecked(true); } else { radioSelectedRange->setDisabled(true); } } QVector QDDialog::getLocation() const { QVector res; if (radioWholeSequence->isChecked()) { res << ctx->getSequenceObject()->getSequenceRange(); } else if (radioSelectedRange->isChecked()) { res << ctx->getSequenceSelection()->getSelectedRegions(); } else if (radioCustomRange->isChecked()) { res << U2Region(spinRangeStart->value(), spinRangeEnd->value()-spinRangeStart->value()); } return res; } void QDDialog::sl_selectScheme() { delete scheme; scheme = NULL; LastOpenDirHelper dir(QUERY_DESIGNER_ID); dir.url = QFileDialog::getOpenFileName(this, tr("Select query"), dir, QString("*.%1").arg(QUERY_SCHEME_EXTENSION)); if (dir.url.isEmpty()) { return; } queryFileEdit->setText(dir.url); QDDocument doc; QFile f(dir.url); if (!f.open(QIODevice::ReadOnly)) { return; } QByteArray data = f.readAll(); const QString& content = QString::fromUtf8(data); f.close(); bool res = doc.setContent(content); if (!res) { QMessageBox::critical(this, L10N::errorTitle(), tr("Can not load %1").arg(dir.url)); return; } QueryScene scene; QList docs = (QList() << &doc); if(!QDSceneSerializer::doc2scene(&scene, docs)) { QMessageBox::critical(this, L10N::errorTitle(), tr("Can not load %1").arg(dir.url)); return; } scheme = new QDScheme; QDSceneSerializer::doc2scheme(docs, scheme); QPixmap pixmap = QDUtils::generateSnapShot(&doc, QRect()); QIcon icon(pixmap); hintEdit->clear(); txtDoc = new QTextDocument(hintEdit); QString html = "" "
" "" "
" ""; QString img("img://img"); html = html.arg(img); qreal h = pixmap.height()*hintEdit->width()/pixmap.width(); qreal w = hintEdit->width(); txtDoc->addResource(QTextDocument::ImageResource, QUrl(img), icon.pixmap(w, h)); txtDoc->setHtml(html); hintEdit->setDocument(txtDoc); } void QDDialog::sl_radioCustomRangeToggled(bool checked) { spinRangeStart->setEnabled(checked); spinRangeEnd->setEnabled(checked); } void QDDialog::sl_rangeStartChanged(int i) { if (i > spinRangeEnd->value()) { spinRangeEnd->setValue(i); } } void QDDialog::sl_rangeEndChanged(int i) { if (i < spinRangeStart->value()) { spinRangeStart->setValue(i); } } void QDDialog::sl_okBtnClicked() { if (!scheme) { QMessageBox::critical(this, L10N::errorTitle(), tr("File with query is not selected!")); return; } if (!scheme->isValid()) { QMessageBox::critical(this, L10N::errorTitle(), tr("Error in schema!")); return; } QString err = cawc->validate(); if (!err.isEmpty()) { QMessageBox::critical(this, tr("Error"), err); return; } cawc->prepareAnnotationObject(); const CreateAnnotationModel& m = cawc->getModel(); scheme->setDNA(ctx->getSequenceObject()); QDRunSettings settings; GObject* ao = GObjectUtils::selectObjectByReference(m.annotationObjectRef, UOF_LoadedOnly); settings.annotationsObj = qobject_cast(ao); settings.annotationsObjRef = m.annotationObjectRef; settings.groupName = m.groupName; settings.scheme = scheme; settings.sequenceObj = ctx->getSequenceObject(); settings.viewName = ctx->getAnnotatedDNAView()->getName(); const QVector& location = getLocation(); settings.region = location.first(); QDScheduler* t = new QDScheduler(settings); AppContext::getTaskScheduler()->registerTopLevelTask(t); QDDialog::accept(); } }//namespace ugene-1.9.8/src/plugins/query_designer/src/QDSceneIOTasks.cpp0000644000175000017500000004546011651544323022637 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "QDSceneIOTasks.h" #include "QueryViewController.h" #include "QueryViewItems.h" #include "QueryViewAdapter.h" #include #include #include #include #include #include namespace U2 { //QDSaveSceneTask ////////////////////////////////////////////////////////////////////////// QDSaveSceneTask::QDSaveSceneTask(QueryScene* scene, const QDSceneInfo& info) : Task(tr("Save query scheme"), TaskFlag_None), path(info.path), scene(scene) { // int st = path.lastIndexOf("/")+1; // int end = path.indexOf(".", st); QString id = info.schemeName;//path.mid(st, end-st); QDDocument* doc = QDSceneSerializer::scene2doc(scene); doc->setName(id); doc->setDocDesc(info.description); rawData = doc->toByteArray(); } void QDSaveSceneTask::run() { ioLog.details(tr("Saving scheme to file: %1").arg(path)); QFile f(path); if (f.open(QIODevice::WriteOnly | QIODevice::Truncate)) { qint64 s = f.write(rawData); f.close(); if (s != rawData.size()) { stateInfo.setError(L10N::errorWritingFile(path)); } } else { stateInfo.setError(L10N::errorOpeningFileWrite(path)); } } //QDLoadSceneTask ////////////////////////////////////////////////////////////////////////// QDLoadSceneTask::QDLoadSceneTask(QueryScene* scene, const QString& url) : Task(tr("Load query scheme"), TaskFlag_NoRun), scene(scene), url(url) { scene->clearScene(); } void QDLoadSceneTask::prepare() { QDLoadDocumentTask* t = new QDLoadDocumentTask(url); addSubTask(t); } QList QDLoadSceneTask::onSubTaskFinished(Task* subTask) { QList subTasks; QDLoadDocumentTask* t = qobject_cast(subTask); assert(t); QDDocument* loadedDoc = t->getDocument(); assert(loadedDoc); docs << loadedDoc; foreach(const QString& importUrl, loadedDoc->getImportedUrls()) { QDLoadDocumentTask* sub = new QDLoadDocumentTask(importUrl); subTasks << sub; } return subTasks; } Task::ReportResult QDLoadSceneTask::report() { if (!stateInfo.hasError()) { QDSceneSerializer::doc2scene(scene, docs); } return Task::ReportResult_Finished; } //QDLoadSchemetask ////////////////////////////////////////////////////////////////////////// QDLoadSchemeTask::QDLoadSchemeTask(const QString& uri) : Task(tr("Load query task"), TaskFlag_NoRun) { scheme = new QDScheme; QDLoadDocumentTask* t = new QDLoadDocumentTask(uri); addSubTask(t); } QList QDLoadSchemeTask::onSubTaskFinished(Task* subTask) { QList subTasks; QDLoadDocumentTask* t = qobject_cast(subTask); assert(t); QDDocument* loadedDoc = t->getDocument(); assert(loadedDoc); docs << loadedDoc; foreach(const QString& importUrl, loadedDoc->getImportedUrls()) { QDLoadDocumentTask* sub = new QDLoadDocumentTask(importUrl); subTasks << sub; } return subTasks; } Task::ReportResult QDLoadSchemeTask::report() { if (!stateInfo.hasError()) { QDSceneSerializer::doc2scheme(docs, scheme); } return Task::ReportResult_Finished; } //QDLoadDocumentTask ////////////////////////////////////////////////////////////////////////// QDLoadDocumentTask::QDLoadDocumentTask(const QString& url) : Task(tr("Loading document from %1").arg(url), TaskFlag_None), doc(NULL), url(url) {} void QDLoadDocumentTask::run() { ioLog.details(tr("Loading scheme from file: %1").arg(url)); doc = new QDDocument; //url = "E:/!sandbox/Schema.txt"; QFile f(url); if (!f.open(QIODevice::ReadOnly)) { stateInfo.setError( L10N::errorOpeningFileRead(url) ); return; } QByteArray data = f.readAll(); const QString& content = QString::fromUtf8(data); f.close(); bool res = doc->setContent(content); if (!res) { stateInfo.setError( tr("Invalid content: %1").arg(url) ); } } //QDSceneSerializer ////////////////////////////////////////////////////////////////////////// bool QDSceneSerializer::doc2scene(QueryScene* scene, const QList& docs) { QMap stmt2actor; QDScheme* scheme = scene->getScheme(); bool res = doc2scheme(docs, stmt2actor, scheme); if (!res) { return false; } foreach(QDActor* actor, scheme->getActors()) { QObject::connect(actor->getParameters(), SIGNAL(si_modified()), scene, SLOT(sl_updateRulerText())); } const QPointF& topLeftCorner = scene->annotationsArea().topLeft(); QueryViewAdapter qva(scheme, topLeftCorner); foreach(QDElement* uv, qva.getElements()) { QDActor* actor = uv->getActor(); QDElementStatement* actorStmt = stmt2actor.key(actor, NULL); assert(actorStmt); QString unitId; if (actor->getSchemeUnits().size()==1) { unitId = "unit"; } else { unitId = actor->getUnitId(uv->getSchemeUnit()); } QDElementStatement* el = docs.at(0)->getElement(actorStmt->getId() + "." + unitId); if (el) { uv->loadState(el); } else { qva.placeElement(uv); } } qva.sortVertically(); foreach(QDElement* uv, qva.getElements()) { scene->addItem(uv); } QList haveEditor; foreach(Footnote* fn, qva.getFootnotes()) { scene->addItem(fn); fn->updatePos(); QDConstraint* owner = fn->getConstraint(); if (!haveEditor.contains(owner)) { QueryViewController::setupConstraintEditor(owner); haveEditor.append(owner); } } QString docName = docs.first()->getName(); QString docDesc = docs.first()->getDocDesc(); scene->setLabel(docName); scene->setDescription(docDesc); scene->sl_updateRulerText(); return true; } bool QDSceneSerializer::doc2scheme(const QList& docs, QDScheme* scheme) { QMap stmt2actor; return doc2scheme(docs, stmt2actor, scheme); } bool QDSceneSerializer::doc2scheme(const QList& docs, QMap& stmt2actor, QDScheme* scheme) { QList groups; foreach(QDDocument* doc, docs) { groups.append(doc->getElements(Group)); } QDActor* actor = NULL; //map QDElementStatement to QDActor created from it foreach(QDElementStatement* grpStmt, groups) { //if grpStmt references to stmt defined in other query //find it and instantiate with that query attributes if (grpStmt->getId()==QDDocument::GROUPS_SECTION) { continue; } QDElementStatement* actualStmt = NULL; const QString& definedIn = grpStmt->definedIn(); QString group; if (!definedIn.isEmpty()) { foreach(QDDocument* importedDoc, docs) { if (importedDoc->getName()==definedIn) { actualStmt = importedDoc->getElement(grpStmt->getId()); } } if (actualStmt==NULL) { algoLog.error(QObject::tr("{%1} is not found in imported files.").arg(actualStmt->getId())); return false; } actor = QDSchemeSerializer::loadActor(actualStmt, group); } else { actor = QDSchemeSerializer::loadActor(grpStmt, group); } if (!actor) { return false; } stmt2actor[grpStmt] = actor; scheme->addActor(actor); if (!group.isEmpty()) { if(!scheme->getActorGroups().contains(group)) { scheme->createActorGroup(group); } scheme->addActorToGroup(actor, group); } } //load constraints QList lnks; foreach(QDDocument* doc, docs) { lnks << doc->getLinks(); } foreach(QDLinkStatement* lnk, lnks) { QDConstraint* c = QDSchemeSerializer::loadConstraint(lnk, stmt2actor, docs); if (c) { scheme->addConstraint(c); } else { return false; } } //specify order QStringList ids = docs.first()->getOrder(); if (!ids.isEmpty()) { for (int idx=0, n = ids.size(); idx < n; idx++) { QString id = ids.at(idx); foreach(QDActor* a, scheme->getActors()) { if (a->getParameters()->getLabel()==id) { scheme->setOrder(a, idx); } } } } QDStrandOption strOpt = docs.first()->getSchemaStrand(); scheme->setStrand(strOpt); //load groups bool ok = QDSchemeSerializer::loadGroups(scheme, docs.first()); if (!ok) { return false; } return true; } QDDocument* QDSceneSerializer::scene2doc(QueryScene* scene) { QDDocument* doc = new QDDocument; QMap unit2stmt; QDScheme* scheme = scene->getScheme(); const QList& sceneActors = scheme->getActors(); foreach(QDActor* actor, sceneActors) { QDElementStatement* actorElement = QDSchemeSerializer::saveActor(actor, doc); foreach(QDSchemeUnit* su, actor->getSchemeUnits()) { QString name = actorElement->getId()+"."; if (actor->getSchemeUnits().size()==1) { name+="unit"; } else { name+=su->getId(); } QDElementStatement* unitElement = new QDElementStatement(name, Element); unit2stmt[su] = unitElement; bool res = doc->addElement(unitElement); Q_UNUSED(res); assert(res); QDElement const* uv = scene->getUnitView(su); assert(uv); uv->saveState(unitElement); } } foreach(QDConstraint* c, scheme->getConstraints()) { QDSchemeSerializer::saveConstraint(c, doc, unit2stmt); } doc->saveOrder(scheme->getActors()); doc->setSchemaStrand(scheme->getStrand()); QDSchemeSerializer::saveGroups(scheme, doc); return doc; } //QDSchemeSerializer ////////////////////////////////////////////////////////////////////////// static const QString GROUP_ATTR = "group"; static const QString STRAND_ATTR = "strand"; static const QString STRAND_DIRECT = "direct"; static const QString STRAND_COMPLEMENT = "complement"; static const QString STRAND_BOTH = "both"; static QMap initDirectionMap() { QMap res; res.insertMulti(QDStrand_DirectOnly, STRAND_DIRECT); res.insertMulti(QDStrand_ComplementOnly, STRAND_COMPLEMENT); res.insertMulti(QDStrand_Both, STRAND_BOTH); return res; } const QMap QDSchemeSerializer::STRAND_MAP(initDirectionMap()); QDElementStatement* QDSchemeSerializer::saveActor( QDActor* actor, QDDocument* doc ) { /*const QString& suffix = QString::number(doc->getElements(Group).size() + 1); QDElementStatement* actorElement = new QDElementStatement("A"+suffix, Group);*/ QString elementName = actor->getParameters()->getLabel(); QDElementStatement* actorElement = new QDElementStatement(elementName, Group); bool res = doc->addElement(actorElement); Q_UNUSED(res); assert(res); actorElement->setAttribute(QDElementStatement::ALGO_ATTR_NAME, actor->getActorType()); QList< QPair > attrsMap = actor->saveConfiguration(); QString group = actor->getScheme()->getActorGroup(actor); if (!group.isEmpty()) { attrsMap.append(qMakePair(GROUP_ATTR, group)); } foreach(const StringAttribute& attr, attrsMap) { actorElement->setAttribute(attr.first, attr.second); } if (actor->getStrand()!=QDStrand_Both) { actorElement->setAttribute(STRAND_ATTR, STRAND_MAP.value(actor->getStrand())); } return actorElement; } QDActor* QDSchemeSerializer::loadActor(QDElementStatement* actorElement, QString& group) { assert(actorElement->getType()==Group); const QString& algo = actorElement->getAttribute(QDElementStatement::ALGO_ATTR_NAME); if (algo.isEmpty()) { return NULL; } QDActorPrototypeRegistry* afr = AppContext::getQDActorProtoRegistry(); if (!afr->getAllIds().contains(algo)) { ioLog.error(QObject::tr("Can not find %1.").arg(algo)); return NULL; } QDActor* actor = afr->getProto(algo)->createInstance(); if (actor==NULL) { return NULL; } QString actorName = actorElement->getId(); actor->getParameters()->setLabel(actorName); actor->loadConfiguration(actorElement->getAttributes()); QString dirAttrVal = actorElement->getAttribute(STRAND_ATTR); if (!dirAttrVal.isEmpty()) { if (!STRAND_MAP.values().contains(dirAttrVal)) { coreLog.error(QObject::tr("Error loading file.")); return NULL; } actor->setStrand(STRAND_MAP.key(dirAttrVal)); } group = actorElement->getAttribute(GROUP_ATTR); return actor; } static const QString DISTANCE_ATTR_NAME = "distance_type"; static const QString MIN_ATTR_NAME = "min"; static const QString MAX_ATTR_NAME = "max"; QDLinkStatement* QDSchemeSerializer::saveConstraint(QDConstraint* constraint, QDDocument* doc, const QMap& unit2stmt) { if (QDConstraintTypes::DISTANCE==constraint->constraintType()) { QDDistanceConstraint* dc = static_cast(constraint); QDSchemeUnit* src = dc->getSource(); QDSchemeUnit* dst = dc->getDestination(); QList elIds; QString srcElId = unit2stmt.value(src)->getId(); QString dstElId = unit2stmt.value(dst)->getId(); elIds << srcElId << dstElId; QDLinkStatement* link = new QDLinkStatement(elIds); doc->addLink(link); link->setAttribute(QDLinkStatement::TYPE_ATTR_NAME, QDIdMapper::constraintType2string(QDConstraintTypes::DISTANCE)); link->setAttribute(DISTANCE_ATTR_NAME, QDIdMapper::distance2string(dc->distanceType())); link->setAttribute(MIN_ATTR_NAME, QString::number(dc->getMin())); link->setAttribute(MAX_ATTR_NAME, QString::number(dc->getMax())); return link; } return NULL; } QDConstraint* QDSchemeSerializer::loadConstraint(QDLinkStatement* lnk, const QMap& stmt2unit, const QList& docs) { const QDConstraintType& typeStr = QDIdMapper::string2constraintType(lnk->getAttribute(QDLinkStatement::TYPE_ATTR_NAME)); if (typeStr.isEmpty()) { return NULL; } if (QDConstraintTypes::DISTANCE==typeStr) { const QString& distanceStr = lnk->getAttribute(DISTANCE_ATTR_NAME); const QString& minS = lnk->getAttribute(MIN_ATTR_NAME); const QString& maxS = lnk->getAttribute(MAX_ATTR_NAME); const QList& elIds = lnk->getElementIds(); if (distanceStr.isEmpty() || minS.isEmpty() || maxS.isEmpty() || elIds.size()!=2) { return NULL; } const QString& srcId = elIds.at(0); const QString& dstId = elIds.at(1); QDSchemeUnit* src = findSchemeUnit(srcId, lnk->getDocument(), stmt2unit, docs); if(!src) { return NULL; } QDSchemeUnit* dst = findSchemeUnit(dstId, lnk->getDocument(), stmt2unit, docs); if(!dst) { return NULL; } QList units; units << src << dst; int min = minS.toInt(); int max = maxS.toInt(); int distTypeInt = QDIdMapper::string2distance(distanceStr); if (distTypeInt<0) { return NULL; } QDDistanceType distType = QDDistanceType(distTypeInt); QDDistanceConstraint* dc = new QDDistanceConstraint(units, distType, min, max); return dc; } return NULL; } QDSchemeUnit* QDSchemeSerializer::findSchemeUnit(const QString& id, QDDocument* doc, const QMap stmt2actor, const QList& docs) { const QString& docName = QDDocument::definedIn(id); if (docName.isEmpty()) { int lastPointIdx = id.lastIndexOf('.'); const QString& actorId = id.mid(0, lastPointIdx); const QString& unitId = id.mid(lastPointIdx+1); QDActor* actor = stmt2actor.value(doc->getElement(actorId)); if (actor->getSchemeUnits().size()==1) { return actor->getSchemeUnits().first(); } return actor->getSchemeUnit(unitId); } foreach(QDDocument* doc, docs) { if (doc->getName()==docName) { const QString& elStr = QDDocument::getLocalName(id); int lastPointIdx = elStr.lastIndexOf('.'); const QString& actorId = elStr.mid(0, lastPointIdx); const QString& unitId = elStr.mid(lastPointIdx+1); QDActor* actor = stmt2actor.value(doc->getElement(actorId)); if (actor->getSchemeUnits().size()==1) { return actor->getSchemeUnit(unitId); } return actor->getSchemeUnit(unitId); } } return NULL; } void QDSchemeSerializer::saveGroups(QDScheme* scheme, QDDocument* doc) { QDElementStatement* elStmt = new QDElementStatement(QDDocument::GROUPS_SECTION, Group); foreach(QString group, scheme->getActorGroups()) { elStmt->setAttribute(group, QString::number(scheme->getRequiredNumber(group))); doc->addElement(elStmt); } } bool QDSchemeSerializer::loadGroups(QDScheme* scheme, QDDocument* doc) { QDElementStatement* el = doc->getElement(QDDocument::GROUPS_SECTION); if (!el) { return true; } for(int idx=0, n=el->getAttributes().size(); idx attr = el->getAttributes().at(idx); QString group = attr.first; if (!scheme->getActorGroups().contains(group)) { coreLog.error(QObject::tr("Error loading schema. Schema does not contain group %1.").arg(group)); return false; } bool ok; int reqNum = attr.second.toInt(&ok); if (!ok) { return false; } scheme->setRequiredNum(group, reqNum); } return true; } }//namespace ugene-1.9.8/src/plugins/query_designer/src/QueryProcCfgModel.h0000644000175000017500000001162011651544324023106 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_QUERY_PROC_CFG_MODEL_H_ #define _U2_QUERY_PROC_CFG_MODEL_H_ #include "QueryProcCfgDelegate.h" #include #include #include #include namespace U2 { class QueryProcCfgModel : public QAbstractTableModel { Q_OBJECT private: QList attrs; ConfigurationEditor* editor; Configuration* cfg; public: QueryProcCfgModel(QObject* parent) : QAbstractTableModel(parent), editor(NULL), cfg(NULL) {} QModelIndex modelIndexById(const QString& id) { foreach(Attribute* a, attrs) { if (a->getId()==id) { int row = attrs.indexOf(a); QModelIndex modelIndex = index(row, 1); return modelIndex; } } return QModelIndex(); } void setConfiguration(Configuration* cfg) { this->cfg = cfg; if (cfg) { editor = cfg->getEditor(); //attrs = cfg->getParameters().values(); attrs = cfg->getAttributes(); } else { editor = NULL; attrs.clear(); } reset(); } void setConfiguration(ConfigurationEditor* ed, const QList& al) { editor = ed; attrs = al; reset(); } int columnCount(const QModelIndex&) const { return 2; } int rowCount(const QModelIndex&) const { return attrs.size(); } Qt::ItemFlags flags (const QModelIndex& index) const { if (index.column() == 0) { return Qt::ItemIsEnabled; } return Qt::ItemIsEditable | Qt::ItemIsEnabled | Qt::ItemIsSelectable; } QVariant headerData (int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const { if (orientation == Qt::Horizontal && role == Qt::DisplayRole) { switch(section) { case 0: return tr("Name"); case 1: return tr("Value"); } } return QVariant(); } QVariant data(const QModelIndex &index, int role /* = Qt::DisplayRole */) const { const Attribute* item = attrs.at(index.row()); if (role == DescriptorRole) { return qVariantFromValue(*item); } if (index.column() == 0) { switch (role) { case Qt::DisplayRole: return item->getDisplayName(); case Qt::ToolTipRole: return item->getDocumentation(); case Qt::FontRole: if (item->isRequiredAttribute()) { QFont fnt; fnt.setBold(true); return QVariant(fnt); } default: return QVariant(); } } QVariant val = item->getAttributePureValue(); PropertyDelegate* pd = editor ? editor->getDelegate(item->getId()) : NULL; switch (role) { case Qt::DisplayRole: case Qt::ToolTipRole: { if(pd) { return pd->getDisplayValue(val); } else { QString valueStr = WorkflowUtils::getStringForParameterDisplayRole(val); return !valueStr.isEmpty() ? valueStr : val; } } case DelegateRole: return qVariantFromValue(pd); case Qt::EditRole: case ConfigurationEditor::ItemValueRole: return val; } return QVariant(); } bool setData(const QModelIndex& index, const QVariant& value, int role = Qt::EditRole ) { if (index.column() != 1) { return false; } Attribute* item = attrs[index.row()]; switch (role) { case Qt::EditRole: case ConfigurationEditor::ItemValueRole: const QString& key = item->getId(); if (item->getAttributePureValue() != value) { cfg->setParameter(key, value); emit dataChanged(index, index); } return true; } return false; } }; }//namespace #endif ugene-1.9.8/src/plugins/query_designer/src/QueryViewController.h0000644000175000017500000001514211651544324023563 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_QUERY_VIEW_CONTROLLER_H_ #define _U2_QUERY_VIEW_CONTROLLER_H_ #include "ui_AddConstraintDialog.h" #include #include #include namespace U2 { class QueryViewController; class QDElement; class QueryEditor; class QDLabelItem; class QDDescriptionItem; class QDRulerItem; class QueryScene : public QGraphicsScene { friend class LoadSequenceTask; friend class QueryViewController; friend class QDViewAdapter; Q_OBJECT public: QueryScene(QueryViewController* parent=0); ~QueryScene(); void initTitle(); void initRuler(); void initDescription(); QDScheme* getScheme() const { return scheme; } QRectF rulerArea() const; QRectF annotationsArea() const; QRectF footnotesArea() const; QList getElements() const; QList getFootnotes() const; QDElement* getUnitView(QDSchemeUnit* su) const; void updateSceneRect(); void setRowsNumber(int count); int getRowsNumber() { return rowsNum; } void insertRow(int idx); int getRow(QDElement* const uv) const; QDLabelItem* getLabelItem() const { return labelTxtItem; } QString getLabel() const; void setLabel(const QString& lbl); QString getDescription() const; void setDescription(const QString& dsc); QueryViewController* getViewController() const { return view; } bool showActorDesc() const { return showDesc; } bool showActorOrder() const { return showOrder; } void updateDescription(); void addActor(QDActor* actor, const QPointF& pos); void addDistanceConstraint(QDElement* src, QDElement* dst, QDDistanceType distType, int min, int max); void removeActor(QDActor* actor); void removeActors(const QList& actors); void removeConstraint(QDConstraint* c); void clearScene(); bool isModified() const { return modified; } void setModified(bool b); signals: void si_schemeChanged(); public slots: void sl_showLabel(bool show); void sl_showSchemeDesc(bool show); void sl_showItemDesc(bool show); void sl_showOrder(bool show); void sl_adaptRowsNumber(); void sl_updateRulerText(); void sl_setModified() { setModified(true); } public: static const QSizeF MAX_SCENE_SIZE; static const QSizeF DEFAULT_SCENE_SIZE; protected: void dragEnterEvent(QGraphicsSceneDragDropEvent *event); void dragMoveEvent(QGraphicsSceneDragDropEvent *event); void dropEvent(QGraphicsSceneDragDropEvent *event); void drawBackground(QPainter *painter, const QRectF &rect); void emit_schemeChanged() { emit si_schemeChanged(); } private: QList unitsIntersectedByRow(int idx) const; QList getElements(const QRectF& area); void setupDistanceDialog(QDDistanceType kind); private: QDElement* dropCandidateLeft; QDElement* dropCandidateRight; QueryViewController* view; int rowsNum; QDScheme* scheme; QDLabelItem* labelTxtItem; QDDescriptionItem* descTxtItem; QDRulerItem* ruler; bool showSchemeLbl; bool showDesc; bool showOrder; bool modified; }; class GlassView; class QueryPalette; class QDGroupsEditor; class QDDocument; class QueryViewController : public MWMDIWindow { Q_OBJECT public: QueryViewController(); virtual void setupMDIToolbar(QToolBar* tb); virtual void setupViewMenu(QMenu* m); void loadScene(const QString& content); void switchToGroupsTab(); void setDefaultInFile(const QString& inFile) { inFile_=inFile; } void setDefaultOutFile(const QString& outFile) { outFile_=outFile; } QDScheme* getScheme() const { return scene->getScheme(); } static void setupConstraintEditor(QDConstraint* c); void enableSaveAction(bool enable); protected: bool onCloseEvent(); private slots: void sl_newScene(); void sl_loadScene(); void sl_saveScene(); void sl_saveSceneAs(); void sl_run(); void sl_deleteItem(); void sl_pasteSample(QDDocument* content); void sl_editItem(); void sl_elementSelected(QDActorPrototype* proto); void sl_selectEditorCell(const QString& link); void sl_updateTitle(); void sl_setGlobalStrand(QAction* a); void sl_scrollUp(); private: void createActions(); void saveState(); void setupViewModeMenu(QMenu* m); void setupQuerySequenceModeMenu(QMenu* m); void setupStrandMenu(QMenu* m); bool confirmModified(); private: QueryScene* scene; GlassView* sceneView; QTabWidget* tabs; QueryEditor* editor; QueryPalette* palette; QDGroupsEditor* groupsEditor; QAction* runAction; QAction* newAction; QAction* loadAction; QAction* saveAsAction; QAction* saveAction; QAction* deleteAction; QAction* showLabelAction; QAction* showDescAction; QAction* showItemDescAction; QAction* showOrderAction; QActionGroup* strandActions; QAction* directStrandAction; QAction* complementStrandAction; QAction* bothStrandsAction; QString inFile_, outFile_; QString schemeUri; }; class AddConstraintDialog : public QDialog, public Ui_AddConstraintDialog { Q_OBJECT public: AddConstraintDialog(QueryScene* scene, QDDistanceType kind, QDElement* defSrc, QDElement* defDst); void accept(); private: QueryScene* scene; QDDistanceType kind; }; class QDUtils { public: static QPixmap generateSnapShot(QDDocument* doc, const QRect& rect); static QPixmap generateSnapShot(QueryScene* scene, const QRect& rect); }; } //namespace #endif ugene-1.9.8/src/plugins/query_designer/src/QueryDesignerPlugin.cpp0000644000175000017500000001456611651544323024067 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "QueryDesignerPlugin.h" #include "QueryViewController.h" #include "QDSamples.h" #include "QDRunDialog.h" #include "QDDocumentFormat.h" #include "QDSceneIOTasks.h" #include "QDTests.h" #include "QDWorker.h" #include #include #include #include #include #include #include #include #include #include namespace U2 { extern "C" Q_DECL_EXPORT Plugin* U2_PLUGIN_INIT_FUNC() { QueryDesignerPlugin * plug = new QueryDesignerPlugin(); return plug; } QueryDesignerPlugin::QueryDesignerPlugin() : Plugin(tr("Query Designer"), tr("Analyzes a nucleotide sequence using different algorithms (Repeat finder," " ORF finder, etc.) imposing constraints on the positional relationship" " of the results.")) { if (AppContext::getMainWindow()) { services << new QueryDesignerService(); viewCtx = new QueryDesignerViewContext(this); viewCtx->init(); AppContext::getObjectViewFactoryRegistry() ->registerGObjectViewFactory(new QDViewFactory(this)); } registerLibFactories(); AppContext::getDocumentFormatRegistry()->registerFormat(new QDDocFormat(this)); QString defaultDir = QDir::searchPaths( PATH_PREFIX_DATA ).first() + "/query_samples"; if (DialogUtils::getLastOpenFileDir(QUERY_DESIGNER_ID).isEmpty()) { DialogUtils::setLastOpenFileDir(defaultDir, QUERY_DESIGNER_ID); } //tests GTestFormatRegistry* tfr = AppContext::getTestFramework()->getTestFormatRegistry(); XMLTestFormat *xmlTestFormat = qobject_cast(tfr->findFormat("XML")); assert(xmlTestFormat!=NULL); GAutoDeleteList* l = new GAutoDeleteList(this); l->qlist = QDTests::createTestFactories(); foreach(XMLTestFactory* f, l->qlist) { bool res = xmlTestFormat->registerTestFactory(f); assert(res); Q_UNUSED(res); } LocalWorkflow::QDWorkerFactory::init(); } void QueryDesignerPlugin::registerLibFactories() { AppContext::getQDActorProtoRegistry()->registerProto(new QDFindActorPrototype()); AppContext::getQDActorProtoRegistry()->registerProto(new QDFindPolyActorPrototype()); } QueryDesignerViewContext::QueryDesignerViewContext(QObject *p) : GObjectViewWindowContext(p, ANNOTATED_DNA_VIEW_FACTORY_ID) {} void QueryDesignerViewContext::initViewContext(GObjectView* view) { AnnotatedDNAView* av = qobject_cast(view); ADVGlobalAction* a = new ADVGlobalAction(av, QIcon(":query_designer/images/query_designer.png"), tr("Analyze with query schema..."), 50, ADVGlobalActionFlag_AddToAnalyseMenu); connect(a, SIGNAL(triggered()), SLOT(sl_showDialog())); } void QueryDesignerViewContext::sl_showDialog() { GObjectViewAction* viewAction = qobject_cast(sender()); AnnotatedDNAView* av = qobject_cast(viewAction->getObjectView()); assert(av); ADVSequenceObjectContext* seqCtx = av->getSequenceInFocus(); QDDialog d(seqCtx); d.exec(); } class CloseDesignerTask : public Task { public: CloseDesignerTask(QueryDesignerService* s) : Task(U2::QueryDesignerPlugin::tr("Close Designer"), TaskFlag_NoRun), service(s) {} virtual void prepare(); private: QueryDesignerService* service; }; void CloseDesignerTask::prepare() { if (!service->closeViews()) { stateInfo.setError( U2::QueryDesignerPlugin::tr("Close Designer canceled") ); } } bool QueryDesignerService::closeViews() { MWMDIManager* wm = AppContext::getMainWindow()->getMDIManager(); assert(wm); foreach(MWMDIWindow* w, wm->getWindows()) { QueryViewController* view = qobject_cast(w); if (view) { if (!AppContext::getMainWindow()->getMDIManager()->closeMDIWindow(view)) { return false; } } } return true; } void QueryDesignerService::sl_startQDPlugin() { QAction* action = new QAction(QIcon(":query_designer/images/query_designer.png"), tr("Query Designer..."), this); connect(action, SIGNAL(triggered()), SLOT(sl_showDesignerWindow())); QMenu* toolsMenu = AppContext::getMainWindow()->getTopLevelMenu(MWMENU_TOOLS); toolsMenu->addAction(action); } void QueryDesignerService::sl_showDesignerWindow() { assert(isEnabled()); QueryViewController* view = new QueryViewController; view->setWindowIcon(QIcon(":query_designer/images/query_designer.png")); AppContext::getMainWindow()->getMDIManager()->addMDIWindow(view); AppContext::getMainWindow()->getMDIManager()->activateWindow(view); } Task* QueryDesignerService::createServiceEnablingTask() { QString defaultDir = QDir::searchPaths( PATH_PREFIX_DATA ).first() + QUERY_SAMPLES_PATH; return new QDLoadSamplesTask(QStringList(defaultDir)); } Task* QueryDesignerService::createServiceDisablingTask() { return new CloseDesignerTask(this); } void QueryDesignerService::serviceStateChangedCallback(ServiceState , bool enabledStateChanged) { if (!enabledStateChanged) { return; } if (isEnabled()) { if(!AppContext::getPluginSupport()->isAllPluginsLoaded()) { connect(AppContext::getPluginSupport(),SIGNAL(si_allStartUpPluginsLoaded()),SLOT(sl_startQDPlugin())); } else { sl_startQDPlugin(); } } } }//namespace ugene-1.9.8/src/plugins/query_designer/src/QueryPalette.cpp0000644000175000017500000002654511651544324022547 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "QueryPalette.h" #include #include #include #include #include #include #include namespace U2 { const QString QDDistanceIds::E2S(QObject::tr("End-Start")); const QString QDDistanceIds::S2E(QObject::tr("Start-End")); const QString QDDistanceIds::E2E(QObject::tr("End-End")); const QString QDDistanceIds::S2S(QObject::tr("Start-Start")); class PaletteDelegate: public QItemDelegate { public: PaletteDelegate(QueryPalette *view) : QItemDelegate(view), m_view(view) {} virtual void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const { const QAbstractItemModel *model = index.model(); Q_ASSERT(model); if (!model->parent(index).isValid()) { // this is a top-level item. QStyleOptionButton buttonOption; buttonOption.state = option.state; #ifdef Q_WS_MAC buttonOption.state |= QStyle::State_Raised; #endif buttonOption.state &= ~QStyle::State_HasFocus; buttonOption.rect = option.rect; buttonOption.palette = option.palette; buttonOption.features = QStyleOptionButton::None; m_view->style()->drawControl(QStyle::CE_PushButton, &buttonOption, painter, m_view); QStyleOption branchOption; static const int i = 9; // ### hardcoded in qcommonstyle.cpp QRect r = option.rect; branchOption.rect = QRect(r.left() + i/2, r.top() + (r.height() - i)/2, i, i); branchOption.palette = option.palette; branchOption.state = QStyle::State_Children; if (m_view->isExpanded(index)) branchOption.state |= QStyle::State_Open; m_view->style()->drawPrimitive(QStyle::PE_IndicatorBranch, &branchOption, painter, m_view); // draw text QRect textrect = QRect(r.left() + i*2, r.top(), r.width() - ((5*i)/2), r.height()); QString text = elidedText(option.fontMetrics, textrect.width(), Qt::ElideMiddle, model->data(index, Qt::DisplayRole).toString()); m_view->style()->drawItemText(painter, textrect, Qt::AlignCenter, option.palette, m_view->isEnabled(), text); } else { QStyleOptionToolButton buttonOption; buttonOption.state = option.state; buttonOption.state &= ~QStyle::State_HasFocus; buttonOption.direction = option.direction; buttonOption.rect = option.rect; buttonOption.font = option.font; buttonOption.fontMetrics = option.fontMetrics; buttonOption.palette = option.palette; buttonOption.subControls = QStyle::SC_ToolButton; buttonOption.features = QStyleOptionToolButton::None; QAction* action = qVariantValue(index.data(Qt::UserRole)); buttonOption.text = action->text(); buttonOption.icon = action->icon(); if (!buttonOption.icon.isNull()) { buttonOption.iconSize = QSize(22, 22); } if (action->isChecked()) { buttonOption.state |= QStyle::State_On; buttonOption.state |= QStyle::State_Sunken; buttonOption.activeSubControls = QStyle::SC_ToolButton; } else { buttonOption.state |= QStyle::State_Raised; buttonOption.activeSubControls = QStyle::SC_None; } if (m_view->overItem == m_view->itemFromIndex(index)) { buttonOption.state |= QStyle::State_MouseOver; } buttonOption.state |= QStyle::State_AutoRaise; buttonOption.toolButtonStyle = Qt::ToolButtonTextBesideIcon; m_view->style()->drawComplexControl(QStyle::CC_ToolButton, &buttonOption, painter, m_view); //QItemDelegate::paint(painter, option, index); } } virtual QSize sizeHint(const QStyleOptionViewItem &opt, const QModelIndex &index) const { const QAbstractItemModel *model = index.model(); Q_ASSERT(model); QStyleOptionViewItem option = opt; bool top = !model->parent(index).isValid(); QSize sz = QItemDelegate::sizeHint(opt, index) + QSize(top?2:20, top?2:20); return sz; } private: QueryPalette *m_view; }; const QString QueryPalette::MIME_TYPE("application/x-ugene-query-id"); QueryPalette::QueryPalette(QWidget* parent/* =NULL */) : QTreeWidget(parent), overItem(NULL), currentAction(NULL) { setFocusPolicy(Qt::NoFocus); setSelectionMode(QAbstractItemView::NoSelection); setItemDelegate(new PaletteDelegate(this)); setRootIsDecorated(false); setColumnCount(1); header()->hide(); header()->setResizeMode(QHeaderView::Stretch); setMouseTracking(true); setContent(); setSizePolicy(QSizePolicy(QSizePolicy::Preferred, QSizePolicy::Ignored)); } void QueryPalette::setContent() { QTreeWidgetItem* algorithmCategory = new QTreeWidgetItem; algorithmCategory->setText(0, tr("Algorithms")); addTopLevelItem(algorithmCategory); algorithmCategory->setExpanded(true); QDActorPrototypeRegistry* qpr = AppContext::getQDActorProtoRegistry(); foreach(QDActorPrototype* pf, qpr->getAllEntries()) { QAction* action = createItemAction(pf); QTreeWidgetItem* algMenuItem = new QTreeWidgetItem(/*algorithmCategory*/); actionMap[action] = algMenuItem; algMenuItem->setText(0, action->text()); algMenuItem->setData(0, Qt::UserRole, qVariantFromValue(action)); algorithmCategory->addChild(algMenuItem); } QTreeWidgetItem* constraintCategory = new QTreeWidgetItem; constraintCategory->setText(0, tr("Constraints")); addTopLevelItem(constraintCategory); constraintCategory->setExpanded(true); QList constraintItemActions; constraintItemActions << createItemAction(QDDistanceIds::E2S) << createItemAction(QDDistanceIds::S2E) << createItemAction(QDDistanceIds::E2E) << createItemAction(QDDistanceIds::S2S); foreach(QAction* a, constraintItemActions) { QTreeWidgetItem* linkMenuItem = new QTreeWidgetItem(constraintCategory); actionMap[a] = linkMenuItem; linkMenuItem->setText(0, a->text()); linkMenuItem->setData(0, Qt::UserRole, qVariantFromValue(a)); constraintCategory->addChild(linkMenuItem); } } QAction* QueryPalette::createItemAction(QDActorPrototype* item) { QAction* a = new QAction(item->getDisplayName(), this); a->setCheckable(true); if (!item->getIcon().isNull()) { a->setIcon(item->getIcon()); } else { QIcon icon(":query_designer/images/green_circle.png"); a->setIcon(icon); } a->setData(qVariantFromValue(item)); connect(a, SIGNAL(triggered(bool)), SLOT(sl_selectProcess(bool))); connect(a, SIGNAL(toggled(bool)), SLOT(sl_selectProcess(bool))); return a; } QAction* QueryPalette::createItemAction(const QString& constraintId) { QAction* a = new QAction(constraintId, this); a->setCheckable(true); QIcon icon(":query_designer/images/green_circle.png"); a->setIcon(icon); a->setData(qVariantFromValue(constraintId)); connect(a, SIGNAL(triggered(bool)), SLOT(sl_selectProcess(bool))); connect(a, SIGNAL(toggled(bool)), SLOT(sl_selectProcess(bool))); return a; } void QueryPalette::sl_selectProcess(bool checked) { if (currentAction && currentAction!=sender()) { currentAction->setChecked(false); } if (!checked) { update(indexFromItem(actionMap.value(currentAction))); currentAction = NULL; } else { currentAction = qobject_cast(sender()); assert(currentAction); } if (currentAction && currentAction->data().type() != QVariant::String) { emit processSelected(qVariantValue(currentAction->data())); } else { emit processSelected(NULL); } } void QueryPalette::mousePressEvent(QMouseEvent *event) { if (event->buttons() & Qt::LeftButton) { QTreeWidgetItem* item = itemAt(event->pos()); if (!item) return; event->accept(); if (item->parent() == 0) { setItemExpanded(item, !isItemExpanded(item)); return; } QAction* action = qVariantValue(item->data(0, Qt::UserRole)); if (action) { action->toggle(); dragStartPosition = event->pos(); update(indexFromItem(actionMap.value(action))); } return; } //QTreeWidget::mousePressEvent(event); } void QueryPalette::mouseMoveEvent(QMouseEvent *event) { if (event->buttons() & Qt::LeftButton) { if ((event->pos()-dragStartPosition).manhattanLength()pos(); QTreeWidgetItem* item = itemAt(pos.toPoint()); if(!item) { return; } QAction* action = qVariantValue(item->data(0,Qt::UserRole)); if (!action) { return; } QDrag *drag = new QDrag(this); QMimeData *mimeData = new QMimeData; if (action->data().type() == QVariant::String) { QString str = action->data().toString(); mimeData->setText(str); } else { QDActorPrototype* proto = qVariantValue(action->data()); mimeData->setText(proto->getId()); } drag->setMimeData(mimeData); /*Qt::DropAction dropAction = */drag->exec(Qt::CopyAction | Qt::CopyAction); return; } QTreeWidgetItem* prev = overItem; overItem = itemAt(event->pos()); if (prev) { update(indexFromItem(prev)); } if (overItem) { update(indexFromItem(overItem)); } QTreeWidget::mouseMoveEvent(event); } void QueryPalette::leaveEvent(QEvent *) { QTreeWidgetItem* prev = overItem; overItem = NULL; if (prev) { QModelIndex index = indexFromItem(prev); update(index); }; } QVariant QueryPalette::saveState() const { QVariantList l; for (int i = 0, count = topLevelItemCount(); i < count; i++) { QTreeWidgetItem* it = topLevelItem(i); l.append(it->isExpanded()); } return l; } void QueryPalette::restoreState(const QVariant& v) { const QVariantList& l = v.toList(); for(int i=0, n=l.size(); isetExpanded(l.at(i).toBool()); } } }//namespaceugene-1.9.8/src/plugins/query_designer/src/QDSceneIOTasks.h0000644000175000017500000000710411651544323022275 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_QD_SCENE_IO_TASKS_H_ #define _U2_QD_SCENE_IO_TASKS_H_ #include #include "QDDocument.h" namespace U2 { static const QString QUERY_DESIGNER_ID = "query_designer"; static const QString QUERY_SCHEME_EXTENSION = "uql"; class QDSceneInfo { public: QString path; QString schemeName; QString description; }; class QueryScene; class QDSaveSceneTask : public Task { Q_OBJECT public: QDSaveSceneTask(QueryScene* scene, const QDSceneInfo& info); void run(); private: QString path; QueryScene* scene; QByteArray rawData; }; class QDLoadSceneTask : public Task { Q_OBJECT public: QDLoadSceneTask(QueryScene* scene, const QString& url); void prepare(); QList onSubTaskFinished(Task* subTask); Task::ReportResult report(); private: QueryScene* scene; QString url; QList docs; }; class QDLoadSchemeTask : public Task { Q_OBJECT public: QDLoadSchemeTask(const QString& uri); QDScheme* getScheme() const { return scheme; } QList onSubTaskFinished(Task* subTask); Task::ReportResult report(); private: QString uri; QDScheme* scheme; QList docs; }; class QDLoadDocumentTask : public Task { Q_OBJECT public: QDLoadDocumentTask(const QString& url); void run(); QDDocument* getDocument() const { return doc; } private: QDDocument* doc; QString url; }; class QDSceneSerializer { public: static bool doc2scene(QueryScene* scene, const QList& docs); static QDDocument* scene2doc(QueryScene* scene); static bool doc2scheme(const QList& docs, QMap& stmt2actor, QDScheme* scheme); static bool doc2scheme(const QList& docs, QDScheme* scheme); }; class QDActor; class QDActorParameters; class QDSchemeUnit; class QDConstraint; class QDSchemeSerializer { public: static QDElementStatement* saveActor(QDActor* actor, QDDocument* doc); static QDActor* loadActor(QDElementStatement* actorElement, QString& group); static QDLinkStatement* saveConstraint(QDConstraint* constraint, QDDocument* doc, const QMap& unit2stmt); static QDConstraint* loadConstraint(QDLinkStatement* lnk, const QMap& stmt2unit, const QList& docs); static QDSchemeUnit* findSchemeUnit(const QString& id, QDDocument* doc, const QMap stmt2actor, const QList& docs); static void saveGroups(QDScheme* scheme, QDDocument* doc); static bool loadGroups(QDScheme* scheme, QDDocument* doc); static const QMap STRAND_MAP; }; }//namespace #endif ugene-1.9.8/src/plugins/query_designer/src/QueryViewItems.cpp0000644000175000017500000012743311651544324023063 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "QueryViewItems.h" #include "QueryViewController.h" #include "QueryPalette.h" #include #include #include #include #include #include #include #include #include #include #include namespace U2 { /************************************************************************/ /* Annotation Item */ /************************************************************************/ #define ANNOTATION_MIN_SIZE GRID_STEP #define ANNOTATION_MAX_SIZE 4*GRID_STEP #define MARGIN 4 #define ARR_W 15 QDElement::QDElement(QDSchemeUnit* _unit) : highlighted(false), unit(_unit), font(QFont()), bound(0,0,3*ANNOTATION_MIN_SIZE,ANNOTATION_MIN_SIZE), dragging(false), extendedHeight(ANNOTATION_MIN_SIZE), itemResizeFlags(0) { setFlag(QGraphicsItem::ItemIsSelectable, true); #if (QT_VERSION >= QT_VERSION_CHECK(4, 6, 0)) setFlag(QGraphicsItem::ItemSendsGeometryChanges, true); #endif setAcceptHoverEvents(true); setZValue(1); doc = new QTextDocument(this); QDParameters* params = unit->getActor()->getParameters(); connect(params, SIGNAL(si_modified()), SLOT(sl_refresh())); connect(unit->getActor(), SIGNAL(si_strandChanged(QDStrandOption)), SLOT(sl_refresh())); itemDescription = new QDElementDescription(this); itemDescription->setDocument(doc); const QString& s = getHeaderString(); const QFont& f = itemDescription->font(); QFontMetrics fm(f); if (getActor()->hasAnyDirection()) { bound.setWidth(fm.width(s) + 2*ARR_W); } else { bound.setWidth(fm.width(s) + ARR_W); } } void QDElement::updateDescription() { if (getActor()->hasAnyDirection()) { itemDescription->setTextWidth(bound.width()-2*ARR_W); } else { itemDescription->setTextWidth(bound.width()-ARR_W); } itemDescription->setHeight(bound.height()-MARGIN); itemDescription->document()->setPageSize(itemDescription->boundingRect().size()); } void QDElement::rememberSize() { QueryScene* qs = qobject_cast(scene()); assert(qs); if (!qs->showActorDesc()) { extendedHeight = bound.height(); } } void QDElement::adaptSize() { QueryScene* qs = qobject_cast(scene()); assert(qs); prepareGeometryChange(); if (qs->showActorDesc()) { qreal raY = scenePos().y()+bound.height(); QRectF requiredArea(QPointF(scenePos().x(), raY), QSizeF(bound.width(), extendedHeight-bound.height())); int requiredRowsNum = requiredArea.height() / GRID_STEP; for (int i=0; i< requiredRowsNum; i++) { QRectF reqRowFragment(requiredArea.left(), requiredArea.top() + i*GRID_STEP, requiredArea.width(), GRID_STEP); QPainterPath rowPath; rowPath.addRect(reqRowFragment); QList containedItems = qs->items(rowPath, Qt::IntersectsItemShape); QList containedUnits; foreach(QGraphicsItem* it, containedItems) { if (it->type()==QDElementType) { containedUnits.append(it); } } if (containedUnits.size()>0) { int insertAt = qs->getRow(this) + i +1; qs->insertRow(insertAt); } } bound.setHeight(extendedHeight); } else { bound.setHeight(ANNOTATION_MIN_SIZE); } doc->setPageSize(bound.size() - QSizeF(MARGIN*2,MARGIN*2)); updateDescription(); if (bound.bottom() + scenePos().y()annotationsArea().bottom()) { qs->sl_adaptRowsNumber(); } else if(bound.bottom() + scenePos().y()>qs->annotationsArea().bottom()) { int prevRowsNum = qs->getRowsNumber(); qreal bottomEdge = scenePos().y() + boundingRect().height(); int reqRowNum = (bottomEdge - qs->annotationsArea().top())/GRID_STEP; int rowNum = qMax(prevRowsNum, reqRowNum); qs->setRowsNumber(rowNum); } } void QDElement::loadState(QDElementStatement* el) { assert(el->getType()==Element); const QString& geometryStr = el->getAttribute(QDElementStatement::GEOMETRY_ATTR_NAME); QStringList attrs = geometryStr.split(','); const QString& xPosStr = attrs.at(0); const QString& yPosStr = attrs.at(1); QPointF pos(xPosStr.toInt(), yPosStr.toInt()); assert(!pos.isNull()); const QString& wS = attrs.at(2); const QString& hS = attrs.at(3); QSizeF size(wS.toInt(), hS.toInt()); bound.setSize(size); setPos(pos); doc->setPageSize(bound.size() - QSizeF(MARGIN*2,MARGIN*2)); const QString& eHS = attrs.at(4); extendedHeight = eHS.toInt(); } void QDElement::saveState(QDElementStatement* el) const { assert(el->getType()==Element); QGraphicsScene* s = scene(); QueryScene* qs = qobject_cast(s); assert(qs); qreal extHeight = extendedHeight; if (qs->showActorDesc()) { extHeight = bound.height(); } QString geomStr = QString("%1,%2,%3,%4,%5") .arg(scenePos().x()) .arg(scenePos().y()) .arg(boundingRect().width()) .arg(boundingRect().height()) .arg(extHeight); el->setAttribute(QDElementStatement::GEOMETRY_ATTR_NAME, geomStr); } void QDElement::sl_refresh() { QString baseHtml = "
" + getHeaderString(); QueryScene* qs = qobject_cast(scene()); if (qs && !qs->showActorDesc()) { doc->setHtml(baseHtml); } else { QString infoStr = unit->getActor()->getText(); doc->setHtml(QString("%1
%2") .arg(baseHtml) .arg(infoStr)); } update(); if ( getActor()->hasAnyDirection() || getActor()->hasBackwardDirection() ) { itemDescription->setPos(ARR_W,0); } else { itemDescription->setPos(0,0); } updateDescription(); } QString QDElement::getHeaderString() const { QString res; QString annotateAsStr = unit->getActor()->annotateAs(); annotateAsStr.replace('<', "<"); annotateAsStr.replace('>', ">"); QueryScene* qs = qobject_cast(scene()); QDActorParameters* params = unit->getActor()->getParameters(); if (getActor()->getSchemeUnits().size()==1) { res = QString("%1 (\"%3\")") .arg(params->getLabel()) .arg(annotateAsStr); } else { res = QString("%1.%2 (\"%3\")") .arg(params->getLabel()) .arg(unit->getId()) .arg(annotateAsStr); } if (qs && qs->showActorOrder()) { int serialNumber = qs->getScheme()->getActors().indexOf(getActor()) + 1; res+=QString(" Order: %1").arg(serialNumber); } return res; } bool QDElement::isLinkedWith(QDElement* /*other*/, QDDistanceType /*kind*/) { /*foreach(Footnote* linkIt, links) { if(other->links.contains(linkIt) && linkIt->kind()==kind) { return true; } }*/ return false; } QList QDElement::getOutcomeFootnotes() const { QList res; foreach(Footnote* fn, links) { if (fn->getSrc()==this) { res.append(fn); } } return res; } QList QDElement::getIncomeFootnotes() const { QList res; foreach(Footnote* fn, links) { if (fn->getDst()==this) { res.append(fn); } } return res; } #define CORNER_DIAM 6 void QDElement::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) { Q_UNUSED(option); Q_UNUSED(widget); QPen pen; if(isSelected()) { pen.setStyle(Qt::DashLine); painter->setPen(pen); } if(highlighted) { pen.setWidth(2); painter->setPen(pen); } painter->setRenderHint(QPainter::Antialiasing); painter->setBrush(getActor()->defaultColor()); qreal w = boundingRect().width(); qreal h = boundingRect().height(); QPainterPath path; if (!getActor()->hasAnyDirection()) { path.moveTo(QPointF(CORNER_DIAM/2.0, 0)); path.lineTo(w - ARR_W, 0); path.lineTo(w, h/2); path.lineTo(w - ARR_W, h); path.lineTo(CORNER_DIAM/2.0, h); path.arcTo(0, h-CORNER_DIAM, CORNER_DIAM, CORNER_DIAM, -90, -90); path.lineTo(0, CORNER_DIAM/2); path.arcTo(0, 0, CORNER_DIAM, CORNER_DIAM, 180, -90); if (getActor()->hasBackwardDirection()) { painter->rotate(180); painter->translate(-w,-h); } } else { path.moveTo(0, h/2); path.lineTo(ARR_W, 0); path.lineTo(w-ARR_W, 0); path.lineTo(w, h/2); path.lineTo(w-ARR_W, h); path.lineTo(ARR_W, h); path.lineTo(0, h/2); path.lineTo(ARR_W, 0); } painter->fillPath(path, painter->brush()); painter->drawPath(path); } QPointF QDElement::getRightConnector() { return mapToScene(QPointF(boundingRect().right(), (boundingRect().top() + boundingRect().bottom())/2)); } QPointF QDElement::getLeftConnector() { return mapToScene(QPointF(boundingRect().left(), (boundingRect().top() + boundingRect().bottom())/2)); } void QDElement::mouseMoveEvent(QGraphicsSceneMouseEvent *event) { if(event->buttons() & Qt::LeftButton) { foreach(Footnote* link, links) { link->draging = true; } if (!dragging) { dragPoint = event->pos(); dragging = true; } QPointF newPos = scenePos(); const QPointF& mousePos = event->pos(); const QPointF& p = mousePos - dragPoint; newPos.rx()+=p.x(); if (qAbs(p.y())>=GRID_STEP/2) { newPos.ry()+=p.y(); } setPos(newPos); } else { QGraphicsItem::mouseMoveEvent(event); } } void QDElement::mouseReleaseEvent(QGraphicsSceneMouseEvent *event) { foreach(Footnote* link, links) { link->draging = false; link->update(); } dragging = false; QGraphicsItem::mouseReleaseEvent(event); } void QDElement::contextMenuEvent(QGraphicsSceneContextMenuEvent *event) { QueryScene* qs = qobject_cast(scene()); assert(qs); QDScheme* scheme = qs->getScheme(); const QList& actors = scheme->getActors(); int serialNum = actors.indexOf(getActor()); QMenu menu; QMenu* orderMenu = new QMenu(tr("Set order"), &menu); for (int i=0; iaddAction(QString("%1 %2") .arg(i+1) .arg(actor->getParameters()->getLabel()) ); a->setCheckable(true); a->setChecked(false); if (i==serialNum) { a->setChecked(true); } a->setData(qVariantFromValue(i)); } QAction* removeFromGroupAction = NULL; QAction* addToGroupAction = NULL; if (!scheme->getActorGroups().isEmpty()) { if (!scheme->getActorGroup(getActor()).isEmpty()) { removeFromGroupAction = menu.addAction(tr("Remove from group")); } else { addToGroupAction = menu.addAction(tr("Add to group")); } } menu.addSeparator(); menu.addMenu(orderMenu); menu.addSeparator(); QAction* upAction = menu.addAction(tr("Up")); QAction* downAction = menu.addAction(tr("Down")); QAction* action = menu.exec(event->screenPos()); if (!action) { return; } if (action==addToGroupAction) { bool ok; QString sel = QInputDialog::getItem(NULL, tr("Add '%1' to group").arg(getActor()->getParameters()->getLabel()), tr("Group:"), scheme->getActorGroups(), 0, false, &ok); if(!ok) { return; } scheme->addActorToGroup(getActor(), sel); qs->getViewController()->switchToGroupsTab(); return; } if (action==removeFromGroupAction) { scheme->removeActorFromGroup(getActor()); qs->getViewController()->switchToGroupsTab(); return; } int newSerialNum = serialNum; if (action==upAction) { newSerialNum = serialNum + 1; } else if (action==downAction) { newSerialNum = serialNum-1; } else { newSerialNum = action->data().toInt(); } int from = 0; int to = 0; if (serialNum < newSerialNum) { from = qMax(serialNum,0); to = qMin(newSerialNum, actors.size()-1); } else { from = qMax(newSerialNum,0); to = qMin(serialNum, actors.size()-1); } scheme->setOrder(getActor(), newSerialNum); for(int i=from; i<=to; i++) { QDActor* a = actors.at(i); const QList& suList = a->getSchemeUnits(); foreach(QDSchemeUnit* su, suList) { foreach(QGraphicsItem* it, qs->getElements()) { QDElement* uv = qgraphicsitem_cast(it); assert(uv); if (uv->getSchemeUnit()==su) { uv->sl_refresh(); } } } } } //resize processing #define EDGE_WIDTH 4 bool QDElement::sceneEvent(QEvent *event) { switch(event->type()) { case QEvent::GraphicsSceneHoverEnter: case QEvent::GraphicsSceneHoverMove: { itemResizeFlags = 0; QGraphicsSceneHoverEvent* he = static_cast(event); QPointF p = he->pos(); int dxRight = qAbs(boundingRect().right() - p.x()); int dxLeft = qAbs(boundingRect().left() - p.x()); int dyBottom = qAbs(boundingRect().bottom() - p.y()); int dyTop = qAbs(boundingRect().top() - p.y()); if (dxRight < EDGE_WIDTH) { itemResizeFlags |= ResizeRight; setCursor(Qt::SizeHorCursor); } else if(dxLeft < EDGE_WIDTH) { itemResizeFlags |= ResizeLeft; setCursor(Qt::SizeHorCursor); } if (dyBottom < EDGE_WIDTH) { itemResizeFlags |= ResizeBottom; setCursor(Qt::SizeVerCursor); } else if(dyTop < EDGE_WIDTH) { itemResizeFlags |= ResizeTop; setCursor(Qt::SizeVerCursor); } if((itemResizeFlags&ResizeBottom&&itemResizeFlags&ResizeRight)|| (itemResizeFlags&ResizeTop&&itemResizeFlags&ResizeLeft)) { setCursor(Qt::SizeFDiagCursor); } else if((itemResizeFlags&ResizeTop&&itemResizeFlags&ResizeRight)|| (itemResizeFlags&ResizeBottom&&itemResizeFlags&ResizeLeft)) { setCursor(Qt::SizeBDiagCursor); } if(!itemResizeFlags && cursor().shape()!=Qt::PointingHandCursor) { unsetCursor(); } break; } case QEvent::GraphicsSceneHoverLeave: case QEvent::GraphicsSceneMouseRelease: itemResizeFlags = 0; break; case QEvent::GraphicsSceneMouseMove: { if(itemResizeFlags) { QueryScene* qs = qobject_cast(scene()); QGraphicsSceneMouseEvent* me = static_cast(event); if(me->buttons()&Qt::LeftButton) { QPointF p = me->pos(); p.setY(round(p.y(), GRID_STEP)); QRectF newBound(bound); if(itemResizeFlags&ResizeRight) { newBound.setRight(p.x()); } else if (itemResizeFlags&ResizeLeft && me->scenePos().x()>0) { newBound.setWidth(newBound.width() - p.x()); } if(itemResizeFlags&ResizeTop) { newBound.setHeight(newBound.height() - p.y() + newBound.top()); } else if(itemResizeFlags&ResizeBottom) { newBound.setBottom(p.y()); } //keep minimum size if(newBound.width()annotationsArea().bottom()) { qs->sl_adaptRowsNumber(); } //expand rows area if necessary if(newBound.bottom() + scenePos().y() > qs->annotationsArea().bottom()) { int prevRowsNum = qs->getRowsNumber(); qreal bottomEdge = scenePos().y() + boundingRect().height(); int reqRowNum = (bottomEdge - qs->annotationsArea().top())/GRID_STEP; int rowNum = qMax(prevRowsNum, reqRowNum); qs->setRowsNumber(rowNum); } //find new position for left|top resize QPointF newPos = scenePos(); if (itemResizeFlags&ResizeTop) { qreal deltaY = newBound.height() - bound.height(); newPos.setY(newPos.y() - deltaY); } if (itemResizeFlags&ResizeLeft) { newPos.setX(newPos.x() + p.x()); } //check for collisions QRectF rect = newBound; rect.moveTopLeft(newPos); QPainterPath path; path.addRect(rect); QList items = scene()->items(path, Qt::IntersectsItemShape); items.removeAll(this); foreach(QGraphicsItem* item, items) { if(item->type()!=QDElementType) { items.removeAll(item); } } if(!items.isEmpty()) { break; } //check if affected footnotes have positive length if ( itemResizeFlags & ResizeRight ) { foreach(Footnote* fn, links) { if (fn->getDst()==this) { if (fn->getDistType()==S2E || fn->getDistType()==E2E) { if (newPos.x()+newBound.width()-fn->getSrcPoint().x()<=0) { return true; } } } else { if (fn->getDistType()==E2S || fn->getDistType()==E2E) { if (fn->getDstPoint().x()-newPos.x()-newBound.width()<=0) { return true; } } } } } if ( itemResizeFlags & ResizeLeft ) { foreach(Footnote* fn, links) { if (fn->getDst()==this) { if (fn->getDistType()==S2S || fn->getDistType()==E2S) { if (newPos.x() - fn->getSrcPoint().x()<=0) { return true; } } } else { if (fn->getDistType()==S2S || fn->getDistType()==S2E) { if (fn->getDstPoint().x()-newPos.x()<=0) { return true; } } } } } bound.setRect(newBound.x(),newBound.y(),newBound.width(),newBound.height()); if (itemResizeFlags & (ResizeTop|ResizeLeft)) { if (newPos!=scenePos()) { setPos(newPos); } } //update updateDescription(); updateFootnotes(); qs->setModified(true); qs->update(); } } } break; default:; } if(itemResizeFlags) { return true; } else { return QGraphicsItem::sceneEvent(event); } } QVariant QDElement::itemChange( GraphicsItemChange change, const QVariant & value ) { switch(change) { case ItemPositionChange: { //value is the new position QPointF newPos = value.toPointF(); QueryScene* qs = qobject_cast(scene()); if (qs==NULL) { return newPos; } // Adjust position for item to fit in row qreal start = qs->annotationsArea().top(); newPos.setY(round(newPos.y() - start, GRID_STEP) + start); QRectF rect = qs->annotationsArea(); rect.setHeight(rect.height()-boundingRect().height()); rect.setWidth(rect.width()-boundingRect().width()); if (!rect.contains(newPos)) { if (newPos.y()>rect.bottom()) { int prevRowsNum = qs->getRowsNumber(); qreal bottomEdge = newPos.y() + boundingRect().height(); int reqRowNum = (bottomEdge - qs->annotationsArea().top())/GRID_STEP; int rowNum = qMax(prevRowsNum, reqRowNum); qs->setRowsNumber(rowNum); } // Keep the item inside the annotation area newPos.setX(qBound(rect.left(), newPos.x(), rect.left() + QueryScene::MAX_SCENE_SIZE.width())); newPos.setY(qMax(newPos.y(), rect.top())); } //prevent collision QRectF itemRect = boundingRect(); const QPointF& topLeft = mapToScene(itemRect.topLeft()); itemRect.moveTopLeft(topLeft); itemRect.translate(newPos - scenePos()); QPainterPath path; path.addRect(itemRect); QList items = scene()->items(path, Qt::IntersectsItemShape); items.removeAll(this); foreach(QGraphicsItem* item, items) { if(item->type()!=QDElementType) { items.removeAll(item); } } const QPointF& oldPos = scenePos(); if(!items.isEmpty()) { return oldPos; } //check if links have positive length foreach(Footnote* fn, links) { if(fn->from==this) { //future connector position QPointF left = fn->getSrcPoint(); left+=newPos-scenePos(); QPointF right = fn->getDstPoint(); if(right.x()-left.x()<=0) { return oldPos; } } else { QPointF right = fn->getDstPoint(); right+=newPos-scenePos(); QPointF left = fn->getSrcPoint(); if(right.x()-left.x()<=0) { return oldPos; } } } return newPos; } break; case ItemPositionHasChanged: { QueryScene* qs = qobject_cast(scene()); if (qs==NULL) { return QGraphicsItem::itemChange(change, value); } qs->sl_adaptRowsNumber(); QRectF rect = qs->sceneRect(); qreal rightEdge = mapRectToScene(boundingRect()).right(); qreal min = rect.left() + QueryScene::DEFAULT_SCENE_SIZE.width(); qreal max = rect.left() + QueryScene::MAX_SCENE_SIZE.width(); rightEdge = qBound(min, rightEdge, max); if (rightEdge > rect.right()) { rect.setRight(rightEdge); qs->setSceneRect(rect); } updateFootnotes(); qs->setModified(true); } break; case ItemSceneChange: if(qVariantValue(value)==NULL) { foreach(Footnote* fn, links) { scene()->removeItem(fn); delete fn; } } break; case ItemSceneHasChanged: if(qVariantValue(value)!=NULL) { sl_refresh(); adaptSize(); QueryScene* qs = qobject_cast(scene()); QueryViewController* view = qs->getViewController(); if (view) { connect(itemDescription, SIGNAL(linkActivated(const QString&)), view, SLOT(sl_selectEditorCell(const QString&))); connect(itemDescription, SIGNAL(linkHovered(const QString&)), SLOT(sl_onHoverLink(const QString&))); } } break; default: break; } return QGraphicsItem::itemChange(change, value); } void QDElement::updateFootnotes() { QueryScene* qs = qobject_cast(scene()); QGraphicsView* view = qs->views().at(0); assert(view); QGraphicsView::ViewportUpdateMode mode = view->viewportUpdateMode(); view->setViewportUpdateMode(QGraphicsView::NoViewportUpdate); foreach(Footnote* fn, links) { fn->updatePos(); } view->setViewportUpdateMode(mode); } void QDElement::sl_onHoverLink(const QString &link) { if (link.isEmpty()) { unsetCursor(); } else { setCursor(Qt::PointingHandCursor); } } /************************************************************************/ /* QDElementDescription */ /************************************************************************/ QDElementDescription::QDElementDescription(QGraphicsItem* parent/* =NULL */) : QGraphicsTextItem(parent) { setAcceptHoverEvents(true); setTextInteractionFlags(Qt::LinksAccessibleByMouse|Qt::LinksAccessibleByKeyboard); } QRectF QDElementDescription::boundingRect() const { QRectF bound = QGraphicsTextItem::boundingRect(); bound.setHeight(height); return bound; } void QDElementDescription::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) { QStyleOptionGraphicsItem deselectedOption = *option; deselectedOption.state &= ~(QStyle::State_Selected | QStyle::State_HasFocus); QGraphicsTextItem::paint(painter, &deselectedOption, widget); } // subscribe to mouse release event (link activation in QGraphicsTextItem) by accepting mouse press void QDElementDescription::mousePressEvent(QGraphicsSceneMouseEvent *event) { QGraphicsTextItem::mousePressEvent(event); event->accept(); } bool QDElementDescription::sceneEvent(QEvent *event) { bool res = QGraphicsTextItem::sceneEvent(event); switch (event->type()) { case QEvent::GraphicsSceneHoverEnter: case QEvent::GraphicsSceneHoverMove: case QEvent::GraphicsSceneMouseRelease: case QEvent::GraphicsSceneMouseMove: case QEvent::GraphicsSceneMousePress: { QGraphicsSceneMouseEvent* me = static_cast(event); QDElement* parent = qgraphicsitem_cast(parentItem()); assert(parent); me->setPos(mapToParent(me->pos())); res = parent->sceneEvent(me); } break; default: break; } return res; } /************************************************************************/ /* Footnote Item */ /************************************************************************/ Footnote::Footnote(QDElement* _from, QDElement* _to, QDDistanceType _distType, QDConstraint* parent, const QFont& _font) : from(_from), to(_to), distType(_distType), constraint(parent), font(_font), draging(false) { #if (QT_VERSION >= QT_VERSION_CHECK(4, 6, 0)) setFlag(QGraphicsItem::ItemSendsGeometryChanges, true); #endif connect(constraint->getParameters(), SIGNAL(si_modified()), SLOT(sl_update())); init(); } void Footnote::init() { setFlag(QGraphicsItem::ItemIsSelectable, true); from->links << this; to->links << this; QPen refPen(Qt::black); refPen.setStyle(Qt::DotLine); leftRef = new QGraphicsLineItem; rightRef = new QGraphicsLineItem; leftRef->setPen(refPen); leftRef->setZValue(-1); rightRef->setPen(refPen); rightRef->setZValue(-1); sl_update(); } Footnote::~Footnote() {} void Footnote::sl_update() { update(); } #define FOOTNOTE_MARGIN 6 void Footnote::updatePos() { qreal xPos = getSrcPoint().x(); int step = boundingRect().height() + FOOTNOTE_MARGIN; QueryScene* qs = qobject_cast(scene()); assert(qs); const QRectF& area = qs->footnotesArea(); //look for vacant position int y; for(y=area.top() + FOOTNOTE_MARGIN; y overlapingItems = qs->items(bound, Qt::IntersectsItemBoundingRect); overlapingItems.removeAll(this); foreach(QGraphicsItem* item, overlapingItems) { if (item->type()!=FootnoteItemType) { overlapingItems.removeAll(item); } } if(overlapingItems.isEmpty()) { setPos(xPos, y); updateLines(QPointF(xPos, y)); return; } } y+=step; //assert(qs->footnotesArea().contains(QPointF(xPos,y))); setPos(xPos, y); updateLines(QPointF(xPos, y)); } void Footnote::updateLines(const QPointF& p) { QPointF p3 = getSrcPoint(); QLineF rightLine(p3,p); QPointF p1 = getDstPoint(); QPointF p2 = p + QPointF(p1.x()-p3.x(),0); QLineF leftLine(p1, p2); leftRef->setLine(leftLine); rightRef->setLine(rightLine); } QString Footnote::getText() const { return constraint->getText(from->getSchemeUnit(), to->getSchemeUnit()); } QVariant Footnote::itemChange(GraphicsItemChange change, const QVariant &value) { if(change==ItemSceneHasChanged) { if(scene()) { scene()->addItem(leftRef); scene()->addItem(rightRef); } } else if(change==ItemSceneChange) { if(qVariantValue(value)==NULL) { scene()->removeItem(leftRef); scene()->removeItem(rightRef); delete leftRef; delete rightRef; from->links.removeAll(this); to->links.removeAll(this); } } else if (change==ItemPositionHasChanged) { updateLines(scenePos()); leftRef->update(); rightRef->update(); } return QGraphicsItem::itemChange(change, value); } #define ARROW_DELTA 2 #define ARROW_WIDTH 4 QRectF Footnote::boundingRect() const { const QString& text = getText(); QFontMetricsF fm(font); //fm.boundingRect().width() and fm.width() provide different values QRectF textBound(0,0,fm.width(text),fm.height()); textBound.moveTop(ARROW_DELTA); qreal arrW = getDstPoint().x() - getSrcPoint().x(); QRectF arrowBound(0,-ARROW_DELTA, arrW, 2*ARROW_DELTA); return textBound | arrowBound; } void Footnote::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) { Q_UNUSED(option); Q_UNUSED(widget); painter->fillRect(boundingRect(),Qt::white); qreal arrW = getDstPoint().x() - getSrcPoint().x(); QPen pen(Qt::black); if(isSelected()) { pen.setStyle(Qt::DashLine); } if(draging) { pen.setColor(Qt::green); } QDDistanceConstraint* dc = static_cast(constraint); if (dc && dc->getMin()>dc->getMax()) { pen.setColor(Qt::red); } painter->setPen(pen); painter->drawLine(0, 0, arrW, 0); //draw arrow endings painter->drawLine(0,0,ARROW_WIDTH,ARROW_DELTA); painter->drawLine(0,0,ARROW_WIDTH,-ARROW_DELTA); painter->drawLine(arrW,0,arrW-ARROW_WIDTH,ARROW_DELTA); painter->drawLine(arrW,0,arrW-ARROW_WIDTH,-ARROW_DELTA); //draw text const QString& text = getText(); QFontMetrics fm(font); QRectF textBound(0,0,fm.width(text),fm.height()); textBound.moveTop(ARROW_DELTA); QPointF c(boundingRect().center().x(), textBound.center().y()); textBound.moveCenter(c); painter->drawText(textBound, text); } QPointF Footnote::getSrcPoint() const { switch (distType) { case E2S: case E2E: return from->getRightConnector(); case S2E: case S2S: return from->getLeftConnector(); } assert(false); return QPointF(0,0); } QPointF Footnote::getDstPoint() const { switch (distType) { case E2S: case S2S: return to->getLeftConnector(); case S2E: case E2E: return to->getRightConnector(); } assert(false); return QPointF(0,0); } QDElement* Footnote::adjacent(QDElement* uv) const { if (uv==from) { return to; } if (uv==to) { return from; } return NULL; } /************************************************************************/ /* QDLabelItem */ /************************************************************************/ QDLabelItem::QDLabelItem(const QString& text) : QGraphicsTextItem(text) { setTextInteractionFlags(Qt::TextEditorInteraction); } void QDLabelItem::keyPressEvent(QKeyEvent *event) { if (event->key()==Qt::Key_Return || event->key()==Qt::Key_Enter || event->key()==Qt::Key_Space) { setSelected(false); return; } QGraphicsTextItem::keyPressEvent(event); } void QDLabelItem::focusOutEvent(QFocusEvent *event) { setTextInteractionFlags(Qt::NoTextInteraction); QGraphicsTextItem::focusOutEvent(event); emit si_editingFinished(); } void QDLabelItem::mousePressEvent(QGraphicsSceneMouseEvent *event) { setTextInteractionFlags(Qt::TextEditorInteraction); QGraphicsTextItem::mousePressEvent(event); } /************************************************************************/ /* QDDescriptionItem */ /************************************************************************/ #define TEXT_MARGINS 5 QDDescriptionItem::QDDescriptionItem(const QString& text) : QGraphicsTextItem(text), resize(0) { setTextInteractionFlags(Qt::TextEditorInteraction); setAcceptHoverEvents(true); setFlag(QGraphicsItem::ItemIsSelectable, true); } QRectF QDDescriptionItem::boundingRect() const { QRectF bound = QGraphicsTextItem::boundingRect(); const QPointF& cp = bound.center(); bound.setWidth(bound.width()+TEXT_MARGINS*2); bound.setHeight(bound.height()+TEXT_MARGINS*2); bound.moveCenter(cp); return bound; } QPainterPath QDDescriptionItem::shape() const { QRectF bound = boundingRect(); QPainterPath path; path.addRect(bound); return path; } void QDDescriptionItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) { Q_UNUSED(option); Q_UNUSED(widget); QRectF bound = boundingRect(); bound.setHeight(bound.height()-1); //bound.setLeft(bound.left()+1); bound.setWidth(bound.width()-1); if (!hasFocus()) { painter->drawRect(bound); } QGraphicsTextItem::paint(painter, option, widget); } bool QDDescriptionItem::sceneEvent(QEvent *event) { switch(event->type()) { case QEvent::GraphicsSceneHoverEnter: case QEvent::GraphicsSceneHoverMove: { QGraphicsSceneHoverEvent* he = static_cast(event); QPointF p = he->pos(); qreal dxRight = qAbs(boundingRect().right() - p.x()); qreal dxLeft = qAbs(boundingRect().left() - p.x()); if (p.y()>=boundingRect().top() && p.y()<=boundingRect().bottom()) { if (dxRight < EDGE_WIDTH) { setCursor(Qt::SizeHorCursor); resize = QDElement::ResizeRight; } else if(dxLeft < EDGE_WIDTH) { setCursor(Qt::SizeHorCursor); resize = QDElement::ResizeLeft; } else { unsetCursor(); resize = 0; } } break; } case QEvent::GraphicsSceneHoverLeave: case QEvent::GraphicsSceneMouseRelease: unsetCursor(); resize=0; break; case QEvent::GraphicsSceneMouseMove: { if(resize) { //QueryScene* qs = qobject_cast(scene()); QGraphicsSceneMouseEvent* me = static_cast(event); if(me->buttons()&Qt::LeftButton) { QPointF p = me->pos(); QPointF oldPos = me->lastPos(); if (resize==QDElement::ResizeRight) { setTextWidth(textWidth()+p.x()-oldPos.x()); } else if (resize==QDElement::ResizeLeft) { QPointF newPos = scenePos(); newPos.setX(me->scenePos().x()); setTextWidth(textWidth()-newPos.x()+scenePos().x()); setPos(newPos); } } } } break; default:; } return QGraphicsTextItem::sceneEvent(event); } void QDDescriptionItem::mousePressEvent(QGraphicsSceneMouseEvent *event) { setTextInteractionFlags(Qt::TextEditorInteraction); QGraphicsTextItem::mousePressEvent(event); } void QDDescriptionItem::focusOutEvent(QFocusEvent *event) { setTextInteractionFlags(Qt::NoTextInteraction); QGraphicsTextItem::focusOutEvent(event); } /************************************************************************/ /* Ruler */ /************************************************************************/ #define NOTCH_SIZE 6 #define QD_RULER_MARGINS 5 #define MIN_LEN_TO_DRAW 20 QRectF QDRulerItem::boundingRect() const { QRectF bound(leftPos, 0, rightPos, QD_RULER_MARGINS*2 + NOTCH_SIZE); QRectF resBound = bound.united(txtBound()); resBound.setHeight(resBound.height()+QD_RULER_MARGINS); return resBound; } QRectF QDRulerItem::txtBound() const { QFontMetricsF fm(font); QRectF txtBound(0,0,fm.width(text),fm.height()); qreal txtX = leftPos + (rightPos - leftPos) / 2; qreal txtY = QD_RULER_MARGINS + NOTCH_SIZE + txtBound.height()/2; txtBound.moveCenter(QPointF(txtX, txtY)); return txtBound; } void QDRulerItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *, QWidget * ) { if (rightPos - leftPos < MIN_LEN_TO_DRAW) { return; } painter->drawLine(leftPos, NOTCH_SIZE/2 + QD_RULER_MARGINS, rightPos, NOTCH_SIZE/2+QD_RULER_MARGINS); painter->drawLine(leftPos, QD_RULER_MARGINS, leftPos, NOTCH_SIZE + QD_RULER_MARGINS); painter->drawLine(rightPos, QD_RULER_MARGINS, rightPos, NOTCH_SIZE + QD_RULER_MARGINS); painter->setFont(font); painter->drawText(txtBound(), text); } QVariant QDRulerItem::itemChange(GraphicsItemChange change, const QVariant &value) { if(change==ItemSceneHasChanged) { if(scene()) { connect(scene(), SIGNAL(changed(const QList&)), SLOT(sl_updateGeometry())); } } return QGraphicsItem::itemChange(change, value); } void QDRulerItem::sl_updateGeometry() { QueryScene* qs = qobject_cast(scene()); assert(qs); QList items; foreach(QGraphicsItem* it, qs->getElements()) { QDElement* uv = qgraphicsitem_cast(it); assert(uv); items.append(uv); } if (items.isEmpty()) { leftPos = 0; rightPos = 0; } else { leftPos = items.first()->scenePos().x(); rightPos = items.first()->scenePos().x() + items.first()->boundingRect().width(); foreach(QDElement* item, items) { qreal curLeft = item->scenePos().x(); qreal curRight = curLeft + item->boundingRect().right(); if (curLeft < leftPos) { leftPos = curLeft; } if (curRight > rightPos) { rightPos = curRight; } } } } void QDRulerItem::sl_updateText() { int minDist = 0; int maxDist = 0; QueryScene* qs = qobject_cast(scene()); assert(qs); QDScheme* scheme = qs->getScheme(); QList units; foreach(QDActor* a, scheme->getActors()) { units << a->getSchemeUnits(); } for (int i=0, n=units.size(); i paths = scheme->findPaths(src, dst); int curMinDist=0; int curMaxDist=0; foreach(QDPath* path, paths) { QDDistanceConstraint* dc = path->toConstraint(); if(!dc) { text = tr("N/A"); update(); return; } curMinDist = dc->getMin(); curMaxDist = dc->getMax(); QDSchemeUnit* dcSrc = dc->getSource(); QDSchemeUnit* dcDst = dc->getDestination(); if (dc->distanceType()==S2S) { curMinDist+=dcDst->getActor()->getMinResultLen(); curMaxDist+=dcDst->getActor()->getMaxResultLen(); } if (dc->distanceType()==E2E) { curMinDist+=dcSrc->getActor()->getMinResultLen(); curMaxDist+=dcSrc->getActor()->getMaxResultLen(); } if (dc->distanceType()==E2S) { curMinDist+=dcSrc->getActor()->getMinResultLen(); curMaxDist+=dcSrc->getActor()->getMaxResultLen(); curMinDist+=dcDst->getActor()->getMinResultLen(); curMaxDist+=dcDst->getActor()->getMaxResultLen(); } minDist = qMax(minDist, curMinDist); maxDist = qMax(maxDist, curMaxDist); } } } foreach(QDSchemeUnit* su, units) { minDist = qMax(su->getActor()->getMinResultLen(), minDist); maxDist = qMax(su->getActor()->getMaxResultLen(), maxDist); } if (minDist==maxDist) { text= QString("%1 bp").arg(minDist); } else { text = QString("%1..%2 bp").arg(minDist).arg(maxDist); } update(); } }//namespace ugene-1.9.8/src/plugins/query_designer/src/QDWorker.h0000644000175000017500000000360111651544323021251 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_QD_WORKER_H_ #define _U2_QD_WORKER_H_ #include #include namespace U2 { class QDScheme; class AnnotationTableObject; namespace LocalWorkflow { class QDPrompter; typedef PrompterBase QDPrompterBase; class QDPrompter : public QDPrompterBase { Q_OBJECT public: QDPrompter(Actor* p = 0) : QDPrompterBase(p) {} protected: QString composeRichDoc(); }; class QDWorker : public BaseWorker { Q_OBJECT public: QDWorker(Actor* a); virtual void init(); virtual bool isReady(); virtual Task* tick(); virtual bool isDone(); virtual void cleanup(); private slots: void sl_taskFinished(Task*); protected: CommunicationChannel *input, *output; QDScheme* scheme; }; class QDWorkerFactory : public DomainFactory { public: static const QString ACTOR_ID; static void init(); QDWorkerFactory() : DomainFactory(ACTOR_ID) {} virtual Worker* createWorker(Actor* a) { return new QDWorker(a); } }; }//Workflow namespace }//U2 namespace #endif ugene-1.9.8/src/plugins/query_designer/src/QDWorker.cpp0000644000175000017500000002210211651544323021601 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "QDWorker.h" #include "QDSceneIOTasks.h" #include "QueryDesignerPlugin.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include namespace U2 { namespace LocalWorkflow { /************************************************************************* * QDWorkerFactory *************************************************************************/ static const QString SCHEMA_ATTR(BaseAttributes::URL_IN_ATTRIBUTE().getId()); static const QString OUTPUT_ATTR("merge"); static const QString OFFSET_ATTR("offset"); const QString QDWorkerFactory::ACTOR_ID("query"); void QDWorkerFactory::init() { QList p; QList a; { Descriptor id(BasePorts::IN_SEQ_PORT_ID(), QDWorker::tr("Input sequences"), QDWorker::tr("A nucleotide sequence to analyze.")); Descriptor od(BasePorts::OUT_ANNOTATIONS_PORT_ID(), QDWorker::tr("Result annotations"), QDWorker::tr("A set of annotations marking found results.")); QMap inM; inM[BaseSlots::DNA_SEQUENCE_SLOT()] = BaseTypes::DNA_SEQUENCE_TYPE(); p << new PortDescriptor(id, DataTypePtr(new MapDataType("query.seq", inM)), true /*input*/); QMap outM; outM[BaseSlots::ANNOTATION_TABLE_SLOT()] = BaseTypes::ANNOTATION_TABLE_TYPE(); p << new PortDescriptor(od, DataTypePtr(new MapDataType("query.annotations", outM)), false /*input*/, true /*multi*/); } { Descriptor sd(SCHEMA_ATTR, QDWorker::tr("Schema"), QDWorker::tr("Schema file")); Descriptor od(OFFSET_ATTR, QDWorker::tr("Offset"), QDWorker::tr("Specifies left and right offsets for merged annotation (if 'Merge' parameter is set to true).")); Descriptor sad(OUTPUT_ATTR, QDWorker::tr("Merge"), QDWorker::tr("Merges regions of each result into single annotation if true.")); a << new Attribute(sd, BaseTypes::STRING_TYPE(), true); a << new Attribute(od, BaseTypes::NUM_TYPE(), false, 0); a << new Attribute(sad, BaseTypes::BOOL_TYPE(), false, false); } Descriptor desc(ACTOR_ID, QDWorker::tr("Annotate with UQL"), QDWorker::tr("Analyzes a nucleotide sequence using different algorithms" "(Repeat finder, ORF finder, etc.) imposing constraints" " on the positional relationship of the results.")); ActorPrototype* proto = new IntegralBusActorPrototype(desc, p, a); QMap delegates; { delegates[SCHEMA_ATTR] = new URLDelegate( DialogUtils::prepareFileFilter(QDWorker::tr("Query schemes"), QStringList(QUERY_SCHEME_EXTENSION), true), QUERY_DESIGNER_ID, false); QVariantMap m; m["minimum"] = 0; m["maximum"] = INT_MAX; delegates[OFFSET_ATTR] = new SpinBoxDelegate(m); } proto->setPrompter(new QDPrompter()); proto->setEditor(new DelegateEditor(delegates)); proto->setIconPath(":query_designer/images/query_designer.png"); WorkflowEnv::getProtoRegistry()->registerProto(BaseActorCategories::CATEGORY_BASIC(), proto); DomainFactory* localDomain = WorkflowEnv::getDomainRegistry()->getById(LocalDomainFactory::ID); localDomain->registerEntry(new QDWorkerFactory()); } /****************************** * QDPrompter ******************************/ QString QDPrompter::composeRichDoc() { IntegralBusPort* input = qobject_cast(target->getPort(BasePorts::IN_SEQ_PORT_ID())); Actor* producer = input->getProducer(BaseSlots::DNA_SEQUENCE_SLOT().getId()); QString unsetStr = ""+tr("unset")+""; QString producerName = tr("from %1").arg(producer ? producer->getLabel() : unsetStr); QString schemaFile = getRequiredParam(SCHEMA_ATTR); QString doc = tr("Analyze each nucleotide sequence %1 with %2.") .arg(producerName) .arg(getHyperlink(SCHEMA_ATTR, schemaFile)); return doc; } /****************************** * QDWorker ******************************/ QDWorker::QDWorker(Actor* a) : BaseWorker(a), input(NULL), output(NULL), scheme(NULL) { } void QDWorker::init() { input = ports.value(BasePorts::IN_SEQ_PORT_ID()); output = ports.value(BasePorts::OUT_ANNOTATIONS_PORT_ID()); } bool QDWorker::isReady() { return (input && input->hasMessage()); } Task* QDWorker::tick() { QString schemaUri = actor->getParameter(SCHEMA_ATTR)->getAttributePureValue().toString(); QDDocument doc; QFileInfo fi(schemaUri); if (!fi.exists()) { QString defaultDir = QDir::searchPaths( PATH_PREFIX_DATA ).first() + QUERY_SAMPLES_PATH; QDir dir(defaultDir); QStringList names(QString("*.%1").arg(QUERY_SCHEME_EXTENSION)); foreach(const QFileInfo& fi, dir.entryInfoList(names, QDir::Files|QDir::NoSymLinks)) { if (fi.fileName()==schemaUri || fi.baseName()==schemaUri) { schemaUri = fi.absoluteFilePath(); break; } } } QFile f(schemaUri); if (!f.open(QIODevice::ReadOnly)) { return new FailTask(L10N::errorOpeningFileRead(schemaUri)); } QByteArray data = f.readAll(); QString content = QString::fromUtf8(data); f.close(); bool res = doc.setContent(content); if (!res) { return NULL; } scheme = new QDScheme; QList docs; docs << &doc; bool ok = QDSceneSerializer::doc2scheme(docs, scheme); if (!ok) { return NULL; } Message inputMessage = getMessageAndSetupScriptValues(input); QVariantMap map = inputMessage.getData().toMap(); DNASequence seq = map.value(BaseSlots::DNA_SEQUENCE_SLOT().getId()).value(); QDRunSettings settings; settings.annotationsObj = new AnnotationTableObject(GObjectTypes::getTypeInfo(GObjectTypes::ANNOTATION_TABLE).name); settings.scheme = scheme; settings.sequenceObj = new DNASequenceObject(GObjectTypes::getTypeInfo(GObjectTypes::SEQUENCE).name, seq); settings.region = settings.sequenceObj->getSequenceRange(); scheme->setDNA(settings.sequenceObj); bool outputType = actor->getParameter(OUTPUT_ATTR)->getAttributeValue(); if (outputType) { settings.outputType = QDRunSettings::Single; settings.offset = actor->getParameter(OFFSET_ATTR)->getAttributeValue(); } else { settings.outputType = QDRunSettings::Group; } QDScheduler* scheduler = new QDScheduler(settings); connect(new TaskSignalMapper(scheduler), SIGNAL(si_taskFinished(Task*)), SLOT(sl_taskFinished(Task*))); return scheduler; } bool QDWorker::isDone() { return !input || input->isEnded(); } void QDWorker::cleanup() { } void annObjToAnnDataList(AnnotationTableObject* annObj, QList& result) { foreach(Annotation* a, annObj->getAnnotations()) { foreach(AnnotationGroup* grp, a->getGroups()) { a->addQualifier(GBFeatureUtils::QUALIFIER_GROUP, grp->getGroupName()); } result.append(a->data()); } } void QDWorker::sl_taskFinished(Task* t) { delete scheme; if (output) { QDScheduler* sched = qobject_cast(t); QList res; AnnotationTableObject* ao = sched->getSettings().annotationsObj; annObjToAnnDataList(ao, res); QVariant v = qVariantFromValue< QList >(res); output->put(Message(BaseTypes::ANNOTATION_TABLE_TYPE(), v)); if (input->isEnded()) { output->setEnded(); } } } }//Workflow namespace }//U2 namespace ugene-1.9.8/src/plugins/query_designer/src/QDTests.h0000644000175000017500000000427311651544323021110 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _GB2_QD_TESTS_H_ #define _GB2_QD_TESTS_H_ #include #include namespace U2 { class AnnotationTableObject; class DNASequenceObject; class QDScheduler; class QDScheme; //cppcheck-suppress noConstructor class GTest_QDSchedulerTest : public GTest { Q_OBJECT public: SIMPLE_XML_TEST_BODY_WITH_FACTORY_EXT(GTest_QDSchedulerTest, "qd_search", TaskFlags_NR_FOSCOE); ~GTest_QDSchedulerTest(); virtual void prepare(); virtual QList onSubTaskFinished(Task* subTask); private: QString seqName; QString schemaUri; QString expectedResName; DNASequenceObject* seqObj; AnnotationTableObject* expectedResult; AnnotationTableObject* result; QDScheme* schema; QDScheduler* sched; }; class QDTests { public: static QList createTestFactories(); }; class AnnotationGroup; class CompareAnnotationGroupsTask : public Task { Q_OBJECT public: CompareAnnotationGroupsTask(const QList& _grp1, const QList& _grp2) : Task(tr("Compare annotation tables task"), TaskFlag_None), grps1(_grp1), grps2(_grp2), equal(false) {} virtual void run(); bool areEqual() const { assert(isFinished()); return equal; } private: QList grps1, grps2; bool equal; }; }//namespace #endif ugene-1.9.8/src/plugins/query_designer/src/QueryViewItems.h0000644000175000017500000001536011651544324022523 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_QUERY_VIEW_ITEMS_H_ #define _U2_QUERY_VIEW_ITEMS_H_ #include #include #include "QueryPalette.h" #include "QDDocument.h" #include #include #include #include #include #include class QTextDocument; namespace U2 { class QueryViewController; class QueryScene; #define GRID_STEP 40 inline qreal round(qreal val, int step) { int tmp = int(val) + step /2; tmp -= tmp % step; return qreal(tmp); } enum { QDElementType = QGraphicsItem::UserType + 1, FootnoteItemType }; class QDElementDescription : public QGraphicsTextItem { Q_OBJECT public: QDElementDescription(QGraphicsItem* parent=NULL); QRectF boundingRect() const; void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget); void setHeight(qreal h) { height=h; } signals: void linkClicked(const QString& link); protected: bool sceneEvent(QEvent *event); void mousePressEvent(QGraphicsSceneMouseEvent *event); void contextMenuEvent(QGraphicsSceneContextMenuEvent *event) { event->ignore(); } private: qreal height; }; class Footnote; class QDElement : public QGraphicsObject { friend class QDElementDescription; friend class Footnote; friend class QueryViewController; Q_OBJECT public: QDElement(QDSchemeUnit* _unit); ~QDElement() { assert(links.isEmpty()); } void setBoundingRect(const QRectF& r) { bound=r; } QRectF boundingRect() const { return bound; } void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget /* = 0 */); void saveState(QDElementStatement* el) const; void loadState(QDElementStatement* el); //returns constraint's connection point in scene coords QPointF getRightConnector(); QPointF getLeftConnector(); bool isLinkedWith(QDElement* other, QDDistanceType kind); QDActor* getActor() const { return unit->getActor(); } QDSchemeUnit* getSchemeUnit() const { return unit; } const QList& getFootnotes() const { return links; } QList getOutcomeFootnotes() const; QList getIncomeFootnotes() const; void adaptSize(); void rememberSize(); bool highlighted; enum {Type = QDElementType}; int type() const {return Type;} enum ResizeFlag { ResizeRight = 1<<1, ResizeBottom = 1<<2, ResizeLeft = 1<<3, ResizeTop = 1<<4, }; public slots: void sl_refresh(); private slots: void sl_onHoverLink(const QString& link); protected: void mouseMoveEvent(QGraphicsSceneMouseEvent *event); void mouseReleaseEvent(QGraphicsSceneMouseEvent *event); QVariant itemChange( GraphicsItemChange change, const QVariant & value ); bool sceneEvent(QEvent *event); void contextMenuEvent(QGraphicsSceneContextMenuEvent *event); private: void updateDescription(); void updateFootnotes(); QString getHeaderString() const; private: QDSchemeUnit* unit; QFont font; QRectF bound; QPointF dragPoint; bool dragging; QList links; QTextDocument* doc; qreal extendedHeight; typedef QFlags ResizeFlags; ResizeFlags itemResizeFlags; QDElementDescription* itemDescription; }; class Footnote : public QGraphicsObject { friend class QDElement; Q_OBJECT public: Footnote(QDElement* _from, QDElement* _to, QDDistanceType _distType, QDConstraint* parent, const QFont& _font = QFont()); ~Footnote(); void init(); QRectF boundingRect() const; void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget /* = 0 */); void updatePos(); enum {Type = FootnoteItemType}; int type() const {return Type;} QPointF getSrcPoint() const; QPointF getDstPoint() const; QDElement* getSrc() const { return from; } QDElement* getDst() const { return to; } QDElement* adjacent(QDElement* uv) const; QDConstraint* getConstraint() const { return constraint; } QDDistanceType getDistType() const { return distType; } public slots: void sl_update(); protected: QVariant itemChange(GraphicsItemChange change, const QVariant &value); private: void updateLines(const QPointF& p); QString getText() const; QDElement* from; QDElement* to; QDDistanceType distType; QDConstraint* constraint; QFont font; bool draging; QGraphicsLineItem* leftRef; QGraphicsLineItem* rightRef; }; class QDLabelItem : public QGraphicsTextItem { Q_OBJECT public: QDLabelItem(const QString& text=""); void keyPressEvent(QKeyEvent *event); void focusOutEvent(QFocusEvent *event); void mousePressEvent(QGraphicsSceneMouseEvent *event); signals: void si_editingFinished(); }; class QDDescriptionItem : public QGraphicsTextItem { Q_OBJECT public: QDDescriptionItem(const QString& text=""); QRectF boundingRect() const; void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget); bool sceneEvent(QEvent *event); void focusOutEvent(QFocusEvent *event); void mousePressEvent(QGraphicsSceneMouseEvent *event); QPainterPath shape() const; private: int resize; }; class QDRulerItem : public QGraphicsObject { Q_OBJECT public: QDRulerItem() : leftPos(0), rightPos(0) {} void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget /* = 0 */); QRectF boundingRect() const; public slots: void sl_updateGeometry(); void sl_updateText(); protected: QVariant itemChange(GraphicsItemChange change, const QVariant &value); private: QRectF txtBound() const; private: qreal leftPos; qreal rightPos; QString text; QFont font; }; }//namespace Q_DECLARE_METATYPE(U2::QDElement*); #endif ugene-1.9.8/src/plugins/query_designer/src/QueryViewAdapter.h0000644000175000017500000000345411651544324023023 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_QUERY_VIEW_ADAPTER_H_ #define _U2_QUERY_VIEW_ADAPTER_H_ #include #include namespace U2 { class QDScheme; class QDSchemeUnit; class QDElement; class Footnote; class QueryViewAdapter { public: QueryViewAdapter(QDScheme* scheme, const QPointF& topLeftCorner = QPointF(0,0)); const QList& getElements() const { return createdElements; } const QList& getFootnotes() const { return createdFootnotes; } void placeElement(QDElement* uv); void sortVertically(); //void scheme2graph(); private: void moveElement(QDElement* uv, int dx); //returns false if recursive bool needToMove(QDElement* current, int dx, QList& res); QList getSharedFootnotes(QDElement* uv1, QDElement* uv2) const; private: QDScheme* scheme; QList createdElements; QList createdFootnotes; QList currentPath; }; }//namespace #endif ugene-1.9.8/src/plugins/query_designer/src/QDDocumentFormat.cpp0000644000175000017500000001355411651544323023272 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "QDDocumentFormat.h" #include "QDSceneIOTasks.h" #include "QDDocument.h" #include "QueryViewController.h" #include #include #include namespace U2 { //QDGobject ////////////////////////////////////////////////////////////////////////// const GObjectType QDGObject::TYPE("query-obj"); GObject* QDGObject::clone() const { QDGObject* copy = new QDGObject(getGObjectName(), serializedScene, getGHintsMap()); return copy; } const DocumentFormatId QDDocFormat::FORMAT_ID = "QueryDocFormat"; //Format ////////////////////////////////////////////////////////////////////////// QDDocFormat::QDDocFormat(QObject* p) : DocumentFormat(p, DocumentFormatFlags_W1, QStringList(QUERY_SCHEME_EXTENSION)), formatName(tr("Query Schema")) { supportedObjectTypes += QDGObject::TYPE; } Document* QDDocFormat::createNewDocument(IOAdapterFactory* io, const QString& url, const QVariantMap& fs /* = QVariantMap()*/ ) { Document* d = DocumentFormat::createNewDocument(io, url, fs); GObject* o = new QDGObject(tr("Query Schema"), ""); d->addObject(o); return d; } #define BUFF_SIZE 1024 Document* QDDocFormat::loadDocument( IOAdapter* io, TaskStateInfo& ti, const QVariantMap& fs, DocumentLoadMode mode /* = DocumentLoadMode_Whole*/ ) { Q_UNUSED(mode); QByteArray rawData; QByteArray block(BUFF_SIZE, '\0'); int blockLen = 0; while ((blockLen = io->readBlock(block.data(), BUFF_SIZE)) > 0) { rawData.append(block.data(), blockLen); ti.progress = io->getProgress(); } if (checkRawData(rawData).score != FormatDetection_Matched) { ti.setError(tr("Invalid header. %1 expected").arg(QDDocument::HEADER_LINE)); rawData.clear(); return NULL; } QList objects; QString data = QString::fromUtf8(rawData.data(), rawData.size()); objects.append(new QDGObject(tr("Query Schema"), data)); return new Document(this, io->getFactory(), io->getURL(), objects, fs); } void QDDocFormat::storeDocument(Document* d, TaskStateInfo& ts, IOAdapter* io) { Q_UNUSED(ts) assert(d->getDocumentFormat() == this); assert(d->getObjects().size() ==1); QDGObject* wo = qobject_cast(d->getObjects().first()); assert(wo && wo->getScene()); QByteArray rawData = QDSceneSerializer::scene2doc(wo->getScene())->toByteArray(); int nWritten = 0; int nTotal = rawData.size(); while(nWritten < nTotal) { int d = io->writeBlock(rawData.data() + nWritten, nTotal - nWritten); assert(d > 0); nWritten+= d; } wo->setSceneRawData(rawData); } RawDataCheckResult QDDocFormat::checkRawData( const QByteArray& rawData, const GUrl&) const { const QString& data = rawData; if(data.trimmed().startsWith(QDDocument::HEADER_LINE)) { return FormatDetection_Matched; } return FormatDetection_NotMatched; } //Factory ////////////////////////////////////////////////////////////////////////// const GObjectViewFactoryId QDViewFactory::ID("query-view-factory"); bool QDViewFactory::canCreateView( const MultiGSelection& multiSelection ) { foreach(GObject* go, SelectionUtils::findObjects(QDGObject::TYPE, &multiSelection, UOF_LoadedOnly)) { if (!qobject_cast(go)->getScene()) { return true; } } return false; } Task* QDViewFactory::createViewTask( const MultiGSelection& multiSelection, bool single /* = false*/ ) { QSet documents = SelectionUtils::findDocumentsWithObjects(QDGObject::TYPE, &multiSelection, UOF_LoadedAndUnloaded, true); if (documents.size() == 0) { return NULL; } Task* result = (single || documents.size() == 1) ? NULL : new Task(tr("Open multiple views"), TaskFlag_NoRun); foreach(Document* d, documents) { Task* t = new OpenQDViewTask(d); if (result == NULL) { return t; } result->addSubTask(t); } return result; } //OpenViewTask ////////////////////////////////////////////////////////////////////////// OpenQDViewTask::OpenQDViewTask( Document* doc ) : ObjectViewTask(QDViewFactory::ID) { if (!doc->isLoaded()) { documentsToLoad.append(doc); } else { foreach(GObject* go, doc->findGObjectByType(QDGObject::TYPE)) { selectedObjects.append(go) ; } assert(!selectedObjects.isEmpty()); } } void OpenQDViewTask::open() { if (stateInfo.hasError()) { return; } if (!documentsToLoad.isEmpty()) { foreach(GObject* go, documentsToLoad.first()->findGObjectByType(QDGObject::TYPE)) { selectedObjects.append(go); } } foreach(QPointer po, selectedObjects) { QDGObject* o = qobject_cast(po); assert(o && !o->getScene()); QueryViewController* view = new QueryViewController; view->loadScene(o->getSceneRawData()); AppContext::getMainWindow()->getMDIManager()->addMDIWindow(view); AppContext::getMainWindow()->getMDIManager()->activateWindow(view); } } }//namespace ugene-1.9.8/src/plugins/query_designer/query_designer.pri0000644000175000017500000000022311651544323022351 0ustar ilyailya# include (query_designer.pri) PLUGIN_ID=query_designer PLUGIN_NAME=Query designer PLUGIN_VENDOR=Unipro include( ../../ugene_plugin_common.pri ) ugene-1.9.8/src/plugins/query_designer/transl/0000755000175000017500000000000011651544324020117 5ustar ilyailyaugene-1.9.8/src/plugins/query_designer/transl/russian.ts0000644000175000017500000012334511651544324022163 0ustar ilyailya AddConstraintDialog Add Constraint Добавить расстояние From От To До Min Минимальное Max Максимальное QDDialog Analyze with Query Schema Поиск сигналов с помощью дизайнера запросов File with query Файл схемы запроса ... <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> <html><head><meta name="qrichtext" content="1" /><style type="text/css"> p, li { white-space: pre-wrap; } </style></head><body style=" font-family:'MS Shell Dlg 2'; font-size:8.25pt; font-weight:400; font-style:normal;"> <p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-size:8pt;">Hint: </span></p> <p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-size:8pt;">Queries can be created using the Query Designer tool. </span></p> <p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-size:8pt;">To launch the Query Designer select the</span><span style=" font-size:8pt; font-style:italic;">&quot;Tools &gt; Query Designer&quot; </span><span style=" font-size:8pt;">item.</span></p></body></html> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> <html><head><meta name="qrichtext" content="1" /><style type="text/css"> p, li { white-space: pre-wrap; } </style></head><body style=" font-family:'MS Shell Dlg 2'; font-size:8.25pt; font-weight:400; font-style:normal;"> <p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-size:8pt;">Подсказка: </span></p> <p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-size:8pt;">Запросы можно создавать с помощью Дизайнера Запросов. </span></p> <p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-size:8pt;">Чтобы запустить Дизайнер Запросов выберите пункт меню</span><span style=" font-size:8pt; font-style:italic;">&quot;Инструменты &gt; Дизайнер Запросов&quot; </span><span style=" font-size:8pt;">.</span></p></body></html> Range Искать в диапазоне Whole sequence Вся последовательность Selected range Выделенный регион Custom range Указанный регион - Search Искать Cancel Отмена QObject End-Start Конец-Начало Start-End Начало-Конец End-End Конец-Конец Start-Start Начало-Начало {%1} is not found in imported files. {%1} не найден в импортируемых файлах. Can not find %1. Error loading file. Error loading schema. Schema does not contain group %1. QueryEditorWidget Form Property Editor Редактор настроек TextLabel Parameters Параметры RunQueryDlg Run Schema Запуск схемы Load sequence Последовательность Save results to Сохранить результаты в ... Add to project Добавить к проекту Run Выполнить Cancel Отмена U2::AddConstraintDialog End-Start Конец-Начало End-End Конец-Конец Start-End Начало-Конец Start-Start Начало-Начало U2::CompareATObjectsTask Compare annotation tables task U2::FindPolyRegionsTask Find base content task U2::GTest_QDSchedulerTest Invalid content: %1 can't read %1 Results do not match. U2::LocalWorkflow::QDPrompter unset from %1 Analyze each nucleotide sequence <u>%1</u> with <u>%2</u>. U2::LocalWorkflow::QDWorker Input sequences A nucleotide sequence to analyze. Result annotations A set of annotations marking found results. Schema Schema file Offset Specifies left and right offsets for merged annotation (if 'Merge' parameter is set to true). Merge Merges regions of each result into single annotation if true. Annotate with UQL Analyzes a nucleotide sequence using different algorithms(Repeat finder, ORF finder, etc.) imposing constraints on the positional relationship of the results. Query schemes U2::QDDialog Select query Выбор схемы запроса Can not load %1 Не удаётся загрузить схему %1 File with query is not selected! Не выбран файл схемы! Error in schema! Ошибка в схеме! Error Ошибка U2::QDDocFormat Query Schema Invalid header. %1 expected Неправильный заголовок! Должен быть: %1 U2::QDElement Set order Задать порядок Remove from group Удалить из группы Add to group Добавить к группе Up Повысить Down Понизить Add '%1' to group Добавить '%1' к группе Group: Группа U2::QDFindActor Find %1: pattern is empty. %1: pattern has to be nucleic Pattern Finds pattern. Ищет паттерн. A subsequence pattern to look for. Паттерн для поиска интересующих подпоследовательностей. U2::QDFindPolyActor '%1' error. Incorrect value of 'Base' parameter. '%1' error. Percent parameter should be not less than 50% not higher than 100%. Setting up default value: 90%. '%1' error. Min length should be not less than 5 and not higher than sequence length. Search poly regions QD task BaseContent Searches regions in a sequence that contain a specified percentage of a certain base. Поиск регионов последовательности с заданным содержанием азотистого основания. Base Основание Specifies the base. Указывает азотистое основание. Percentage Процент Percentage of the base in a region. Указывает процент содержания азотистого основания в регионе. Min Length Минимальная длина Minimum length of a region. Минимальная длина региона. Max Length Максимальная длина Maximum length of a region. Максимальная длина региона. U2::QDGroupsEditor Add Group Добавить группу Remove Group Удалить группу Add Element Добавить элемент Remove Element Удалить элемент Set Required Number Задать число элементов Query Designer Дизайнер запросов Create element group Создать группу элементов Group name Имя группы Group '%1' already exists! Группа '%1' уже существует! Invalid group name! Недопустимое имя группы! Add Element To Group '%1' Добавить элемент к группе '%1' Element: Элемент Actor is already in group! Элемент уже присутствует в группе! Set required number for '%1' Задать минимальное число элементов группы '%1' Number: Число U2::QDLoadDocumentTask Loading document from %1 Loading scheme from file: %1 Invalid content: %1 U2::QDLoadSamplesTask Load query samples U2::QDLoadSceneTask Load query scheme U2::QDLoadSchemeTask Load query task U2::QDRulerItem N/A U2::QDRunDialog Select output file Выбрать выходной файл Select input file Выбрать входной файл The sequence is not specified! Не задана последовательность! The output file is not selected! Не задан выходной файл! U2::QDRunDialogTask Query Designer Дизайнер запросов Sequence is not supplied. Annotation table is empty U2::QDSaveSceneTask Save query scheme Saving scheme to file: %1 U2::QDViewFactory Open multiple views U2::QueryDesignerPlugin Query Designer Дизайнер запросов Analyzes a nucleotide sequence using different algorithms (Repeat finder, ORF finder, etc.) imposing constraints on the positional relationship of the results. Close Designer Close Designer canceled U2::QueryDesignerService Query Designer... Дизайнер запросов... Query Designer Дизайнер запросов U2::QueryDesignerViewContext Analyze with query schema... Использовать схему дизайнера запросов U2::QueryEditor Forward Прямое Backward Обратное Any Любое Select an element to inspect. Выберите элемент для просмотра или редактирования. Element Name Имя элемента Annotate As Аннотации Direction Направление To configure the constraint element parameters go to the "Parameters" area below. Параметры элемента можно отредактировать в таблице, расположенной ниже. To configure the algorithm element parameters go to the "Parameters" area below. Параметры элемента можно отредактировать в таблице, расположенной ниже. U2::QueryPalette Algorithms Алгоритмы Constraints Условия U2::QueryProcCfgModel Name Имя Value Значение U2::QueryScene Preview is not available. Предварительный просмотр недоступен. U2::QueryViewController Query Designer Дизайнер запросов Elements Элементы Groups Группы Samples Примеры Run Schema... Выполнить схему... New Schema Создать схему Load Schema... Загрузить схему... Save Schema Сохранить схему Save Schema As... Сохранить схему как... Delete Удалить Show title Показывать заголовок Show description Показывать описание схемы Show element info Показывать описание элемента Show order Показывать порядок выполнения Direct strand Считывать прямую цепь Reverse complementary strand Считывать обратно-комлементарную цепь Both strands Считывать обе цепи Query Sequence Mode Режим считывания последовательности View Mode Режим отображения The schema is empty! Схема пуста! The schema is invalid! Please see the log for details. Схема содержит ошибки. Для получения подробностей обратитесь к логу. Load Schema Загрузить схему Query Designer - %1 Дизайнер заросов - %1 The schema has been modified. Do you want to save changes? Схема была изменена. Сохранить изменения? ugene-1.9.8/src/plugins/query_designer/transl/english.ts0000644000175000017500000011077711651544324022135 0ustar ilyailya AddConstraintDialog Add Constraint From To Min Max QDDialog Analyze with Query Schema File with query ... <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> <html><head><meta name="qrichtext" content="1" /><style type="text/css"> p, li { white-space: pre-wrap; } </style></head><body style=" font-family:'MS Shell Dlg 2'; font-size:8.25pt; font-weight:400; font-style:normal;"> <p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-size:8pt;">Hint: </span></p> <p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-size:8pt;">Queries can be created using the Query Designer tool. </span></p> <p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-size:8pt;">To launch the Query Designer select the</span><span style=" font-size:8pt; font-style:italic;">&quot;Tools &gt; Query Designer&quot; </span><span style=" font-size:8pt;">item.</span></p></body></html> Range Whole sequence Selected range Custom range - Search Cancel QObject {%1} is not found in imported files. Can not find %1. Error loading schema. Schema does not contain group %1. Error loading file. End-Start Start-End End-End Start-Start QueryEditorWidget Form Property Editor TextLabel Parameters RunQueryDlg Run Schema Load sequence Save results to ... Add to project Run Cancel U2::AddConstraintDialog End-Start End-End Start-End Start-Start U2::CompareATObjectsTask Compare annotation tables task U2::FindPolyRegionsTask Find base content task U2::GTest_QDSchedulerTest Invalid content: %1 can't read %1 Results do not match. U2::LocalWorkflow::QDPrompter unset from %1 Analyze each nucleotide sequence <u>%1</u> with <u>%2</u>. U2::LocalWorkflow::QDWorker Input sequences A nucleotide sequence to analyze. Result annotations A set of annotations marking found results. Schema Schema file Offset Specifies left and right offsets for merged annotation (if 'Merge' parameter is set to true). Merge Merges regions of each result into single annotation if true. Annotate with UQL Analyzes a nucleotide sequence using different algorithms(Repeat finder, ORF finder, etc.) imposing constraints on the positional relationship of the results. Query schemes U2::QDDialog Select query Can not load %1 File with query is not selected! Error in schema! Error U2::QDDocFormat Query Schema Invalid header. %1 expected U2::QDElement Set order Remove from group Add to group Up Down Add '%1' to group Group: U2::QDFindActor Find %1: pattern is empty. %1: pattern has to be nucleic Pattern Finds pattern. A subsequence pattern to look for. U2::QDFindPolyActor Searches regions in a sequence that contain a specified percentage of a certain base. '%1' error. Incorrect value of 'Base' parameter. '%1' error. Percent parameter should be not less than 50% not higher than 100%. Setting up default value: 90%. '%1' error. Min length should be not less than 5 and not higher than sequence length. Search poly regions QD task BaseContent Base Specifies the base. Percentage Percentage of the base in a region. Min Length Minimum length of a region. Max Length Maximum length of a region. U2::QDGroupsEditor Add Group Remove Group Add Element Remove Element Set Required Number Query Designer Create element group Group name Group '%1' already exists! Invalid group name! Add Element To Group '%1' Element: Actor is already in group! Set required number for '%1' Number: U2::QDLoadDocumentTask Loading document from %1 Loading scheme from file: %1 Invalid content: %1 U2::QDLoadSamplesTask Load query samples U2::QDLoadSceneTask Load query scheme U2::QDLoadSchemeTask Load query task U2::QDRulerItem N/A U2::QDRunDialog Select input file Select output file The sequence is not specified! The output file is not selected! U2::QDRunDialogTask Query Designer Sequence is not supplied. Annotation table is empty U2::QDSaveSceneTask Save query scheme Saving scheme to file: %1 U2::QDViewFactory Open multiple views U2::QueryDesignerPlugin Query Designer Analyzes a nucleotide sequence using different algorithms (Repeat finder, ORF finder, etc.) imposing constraints on the positional relationship of the results. Close Designer Close Designer canceled U2::QueryDesignerService Query Designer... Query Designer U2::QueryDesignerViewContext Analyze with query schema... U2::QueryEditor Forward Backward Any Select an element to inspect. Element Name Annotate As Direction To configure the algorithm element parameters go to the "Parameters" area below. To configure the constraint element parameters go to the "Parameters" area below. U2::QueryPalette Algorithms Constraints U2::QueryProcCfgModel Name Value U2::QueryScene Preview is not available. U2::QueryViewController Query Designer Elements Groups Samples Delete Show title Show description Show element info Show order Direct strand Reverse complementary strand Both strands Query Sequence Mode View Mode Run Schema... New Schema Load Schema... Save Schema Save Schema As... The schema is empty! The schema is invalid! Please see the log for details. Load Schema Query Designer - %1 The schema has been modified. Do you want to save changes? ugene-1.9.8/src/plugins/weight_matrix/0000755000175000017500000000000011651544324016442 5ustar ilyailyaugene-1.9.8/src/plugins/weight_matrix/images/0000755000175000017500000000000011651544324017707 5ustar ilyailyaugene-1.9.8/src/plugins/weight_matrix/images/weight_matrix.png0000644000175000017500000000167611651544324023302 0ustar ilyailyaPNG  IHDRhtEXtSoftwareAdobe ImageReadyqe<`IDATxb`H>Wc8n+cŽ3 x"4O-|{~wK!1qLLL ] | [|_QY?[L^ /=agb|w7Vu Rf `;'?@m?w #~aecefd0%%ASA l? k!`<;3#F!@_l gD* Av,!"J&xA@D* ةZ|0e@ M$q4bf8qΚn=%$'c(p2jC[!upjK(s-TjװnE 8fko^5_]_]ƧH01#pqz /kJ݄F?ЪEX;]$M)GysB bw<1@a/_c}9x2"SUmWƩea(P .JTGuQ(hv /\.]uYPb!Il$Bu0垙g._y7ya.XNוML{xGc bu!&J:KrLKE nRmLa4SbYvHj{^PP80H;8:9ŗFvegp(bfK Hu^HVUs;TE@"*frCGmkF6yn O/ӷ|eoV*+Ji9D7I=RG|IENDB`ugene-1.9.8/src/plugins/weight_matrix/weight_matrix.pri0000644000175000017500000000022011651544324022023 0ustar ilyailya# include (weight_matrix.pri) PLUGIN_ID=weight_matrix PLUGIN_NAME=Weight matrix PLUGIN_VENDOR=Unipro include( ../../ugene_plugin_common.pri ) ugene-1.9.8/src/plugins/weight_matrix/weight_matrix.qrc0000644000175000017500000000016411651544324022025 0ustar ilyailya images/weight_matrix.png ugene-1.9.8/src/plugins/weight_matrix/src/0000755000175000017500000000000011651544324017231 5ustar ilyailyaugene-1.9.8/src/plugins/weight_matrix/src/SetParametersDialogController.h0000644000175000017500000000253111651544324025346 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_WEIGHT_MATRIX_SET_PARAMETERS_DIALOG_CONTROLLER_H_ #define _U2_WEIGHT_MATRIX_SET_PARAMETERS_DIALOG_CONTROLLER_H_ #include #include #include "WeightMatrixPlugin.h" namespace U2 { class SetParametersDialogController : public QDialog, public Ui_SetDefaultParametersDialog { Q_OBJECT public: SetParametersDialogController(QWidget* w = NULL); private slots: void sl_onOkButton(); void sl_onSliderMoved(int); }; } //namespace #endifugene-1.9.8/src/plugins/weight_matrix/src/PWMJASPARDialogController.h0000644000175000017500000000366211651544324024141 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_WEIGHT_MATRIX_JASPAR_DIALOG_CONTROLLER_H_ #define _U2_WEIGHT_MATRIX_JASPAR_DIALOG_CONTROLLER_H_ #include #include #include #include #include #include "WeightMatrixPlugin.h" namespace U2 { class PWMJASPARDialogController : public QDialog, public Ui_SearchJASPARDatabase { Q_OBJECT public: PWMJASPARDialogController(QWidget* w = NULL); QString fileName; private slots: void sl_onOK(); void sl_onCancel(); void sl_onSelectionChanged(); void sl_onDoubleClicked(QTreeWidgetItem* item, int col); void sl_onTableItemClicked(QTableWidgetItem* item); }; class JasparTreeItem; class JasparGroupTreeItem : public QTreeWidgetItem { public: JasparGroupTreeItem(const QString& s); QString s; bool operator<(const QTreeWidgetItem & other) const; }; class JasparTreeItem : public QTreeWidgetItem { public: JasparTreeItem(const JasparInfo& ed); JasparInfo matrix; bool operator<(const QTreeWidgetItem & other) const; }; } //namespace #endifugene-1.9.8/src/plugins/weight_matrix/src/PWMJASPARDialogController.cpp0000644000175000017500000001270511651544324024472 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "PWMJASPARDialogController.h" #include #include #include namespace U2 { PWMJASPARDialogController::PWMJASPARDialogController(QWidget *w) : QDialog(w) { setupUi(this); QString jasparDir = QDir::searchPaths( PATH_PREFIX_DATA ).first() + "/position_weight_matrix/JASPAR"; QDir dir(jasparDir); QStringList list = dir.entryList(QDir::Dirs | QDir::NoDotAndDotDot); for (int i = 0, n = list.size(); i < n; i++) { QString filename = jasparDir; filename.append("/").append(list[i]).append("/matrix_list.txt"); if (QFile::exists(filename)) { JasparGroupTreeItem* gti = new JasparGroupTreeItem(list[i]); gti->setFlags(gti->flags() & ~Qt::ItemIsSelectable); jasparTree->addTopLevelItem(gti); QFile base(filename); base.open(QIODevice::ReadOnly); while (!base.atEnd()) { QString curr = base.readLine(); JasparInfo info=(curr); JasparTreeItem* ti = new JasparTreeItem(info); gti->addChild(ti); } base.close(); } } fileName = ""; connect(okButton, SIGNAL(clicked()), SLOT(sl_onOK())); connect(cancelButton, SIGNAL(clicked()), SLOT(sl_onCancel())); connect(jasparTree, SIGNAL(itemSelectionChanged()), SLOT(sl_onSelectionChanged())); connect(jasparTree, SIGNAL(itemDoubleClicked(QTreeWidgetItem*, int)), SLOT(sl_onDoubleClicked(QTreeWidgetItem*, int))); connect(propertiesTable, SIGNAL(itemClicked(QTableWidgetItem*)), SLOT(sl_onTableItemClicked(QTableWidgetItem*))); } void PWMJASPARDialogController::sl_onOK() { QDialog::accept(); } void PWMJASPARDialogController::sl_onCancel() { QDialog::reject(); } void PWMJASPARDialogController::sl_onSelectionChanged() { QTreeWidgetItem* item = jasparTree->currentItem(); if (item == 0) { fileName = ""; return; } if (!item->isSelected()) { fileName = ""; return; } JasparTreeItem* it = static_cast(item); QMap props = it->matrix.getProperties(); fileName = QDir::searchPaths( PATH_PREFIX_DATA ).first() + "/position_weight_matrix/JASPAR/"; fileName.append(it->matrix.getProperty("tax_group")).append("/"); fileName.append(it->matrix.getProperty("id")).append(".pfm"); propertiesTable->clear(); propertiesTable->setRowCount(props.size()); propertiesTable->setColumnCount(2); propertiesTable->verticalHeader()->setVisible(false); propertiesTable->horizontalHeader()->setVisible(false); QMapIterator iter(props); int pos = 0; while (iter.hasNext()) { iter.next(); propertiesTable->setItem(pos, 0, new QTableWidgetItem(iter.key())); propertiesTable->setItem(pos, 1, new QTableWidgetItem(iter.value())); pos++; } } void PWMJASPARDialogController::sl_onTableItemClicked(QTableWidgetItem* item) { if (item->column() != 1) return; int row = item->row(); QString text = propertiesTable->item(row, 0)->text(); QString link = ""; if (text == "acc") { link = "http://www.uniprot.org/uniprot/" + item->text(); } if (text == "medline") { link = "http://www.ncbi.nlm.nih.gov/pubmed/" + item->text(); } if (text == "species") { link = "http://www.ncbi.nlm.nih.gov/Taxonomy/Browser/wwwtax.cgi?id=" + item->text(); } if (!link.isEmpty()) { GUIUtils::runWebBrowser(link); } } void PWMJASPARDialogController::sl_onDoubleClicked(QTreeWidgetItem* item, int col) { Q_UNUSED(col); if (item == 0) return; if (!item->isSelected()) return; QDialog::accept(); } ////////////////////////////////////////////////////////////////////////// // Tree item JasparTreeItem::JasparTreeItem(const JasparInfo& ed) : matrix(ed) { this->setText(0, matrix.getProperty(QString("name"))); this->setText(1, matrix.getProperty(QString("id"))); this->setText(2, matrix.getProperty(QString("class"))); this->setText(3, matrix.getProperty(QString("family"))); } bool JasparTreeItem::operator<(const QTreeWidgetItem & other) const { int col = treeWidget()->sortColumn(); const JasparTreeItem& ei = static_cast(other); return text(col) < ei.text(col); } JasparGroupTreeItem::JasparGroupTreeItem(const QString& _s) : s(_s){ this->setText(0, s); } bool JasparGroupTreeItem::operator<(const QTreeWidgetItem & other) const { if (other.parent() != NULL) { return true; } int col = treeWidget()->sortColumn(); return text(col) < other.text(col); } }ugene-1.9.8/src/plugins/weight_matrix/src/WeightMatrixIO.cpp0000644000175000017500000002373011651544324022606 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "WeightMatrixIO.h" #include "WeightMatrixPlugin.h" #include #include #include #include #include #include #include #include #include #include #include /* TRANSLATOR U2::IOAdapter */ namespace U2 { const QString WeightMatrixIO::WEIGHT_MATRIX_ID("weight_matrix"); const QString WeightMatrixIO::FREQUENCY_MATRIX_ID("frequency_matrix"); const QString WeightMatrixIO::WEIGHT_MATRIX_EXT("pwm"); const QString WeightMatrixIO::FREQUENCY_MATRIX_EXT("pfm"); QString WeightMatrixIO::getAllMatrixFileFilter(bool includeAll) { return DialogUtils::prepareFileFilter(tr("Frequency and weight matrices"), QStringList() << FREQUENCY_MATRIX_EXT << WEIGHT_MATRIX_EXT, includeAll); } QString WeightMatrixIO::getPFMFileFilter(bool includeAll) { return DialogUtils::prepareFileFilter(tr("Frequency matrices"), QStringList(FREQUENCY_MATRIX_EXT), includeAll); } QString WeightMatrixIO::getPWMFileFilter(bool includeAll) { return DialogUtils::prepareFileFilter(tr("Weight matrices"), QStringList(WEIGHT_MATRIX_EXT), includeAll); } #define BUFF_SIZE 4096 #define MATRIX_VAL_SEPARATOR ';' PFMatrix WeightMatrixIO::readPFMatrix(IOAdapterFactory* iof, const QString& url, TaskStateInfo& si) { PFMatrix matrix; QVarLengthArray res; int len = -1, msize = 0; std::auto_ptr io(iof->createIOAdapter()); if (!io->open(url, IOAdapterMode_Read)) { si.setError( L10N::errorOpeningFileRead(url) ); return matrix; } QByteArray text; int size = io->left(); if (size > 0) { text.reserve(size); } QByteArray block(BUFF_SIZE, '\0'); qint64 blockLen = 0; while ((blockLen = io->readBlock(block.data(), BUFF_SIZE)) > 0) { text.append(QByteArray::fromRawData(block.data(), blockLen)); if (text.size() > 1000*1000) { si.setError(L10N::errorFileTooLarge(url)); break; } } io->close(); if (si.hasError()) { return matrix; } QTextStream reader(text); QString line; while (!reader.atEnd() && !si.hasError()) { line = reader.readLine(); if (line.isEmpty()) { continue; } QStringList curr = line.split(" ", QString::SkipEmptyParts); if (len == -1) { len = curr.length(); } if (len != curr.length()) { si.setError(tr("Error parsing settings line %1").arg(line) ); break; } for (int i = 0; i < len; i++) { bool ok; int val = curr[i].toInt(&ok); if (!ok) { si.setError(tr("Error parsing value %1").arg(curr[i]) ); break; } if (val < 0) { si.setError(tr("Unexpected negative frequency value %1").arg(val) ); break; } res.append(val); } msize++; } if (si.hasError()) { return matrix; } if (msize != 4 && msize != 16) { si.setError(tr("Incorrect size of weight matrix: %1").arg(msize)); return matrix; } matrix = PFMatrix(res, (msize == 4) ? PFM_MONONUCLEOTIDE : PFM_DINUCLEOTIDE); QStringList splitUrl = url.split("/"); QString name = splitUrl.last(); splitUrl.removeLast(); splitUrl.append(QString("matrix_list.txt")); QString jasparBasePath = splitUrl.join("/"); if (!QFile::exists(jasparBasePath)) { return matrix; } int pos = name.lastIndexOf("."); name.remove(pos, name.length() - pos); QFile jasparBase(jasparBasePath); jasparBase.open(QIODevice::ReadOnly); bool found = false; while (!found && !jasparBase.atEnd()) { QString curr = QString(jasparBase.readLine()); if (!curr.startsWith(name)) continue; found = true; JasparInfo info(curr); matrix.setInfo(info); } jasparBase.close(); return matrix; } PWMatrix WeightMatrixIO::readPWMatrix(IOAdapterFactory* iof, const QString& url, TaskStateInfo& si) { PWMatrix matrix; QVarLengthArray res; int len = -1, msize = 0; std::auto_ptr io(iof->createIOAdapter()); if (!io->open(url, IOAdapterMode_Read)) { si.setError( L10N::errorOpeningFileRead(url) ); return matrix; } QByteArray text; int size = io->left(); if (size > 0) { text.reserve(size); } QByteArray block(BUFF_SIZE, '\0'); qint64 blockLen = 0; while ((blockLen = io->readBlock(block.data(), BUFF_SIZE)) > 0) { text.append(QByteArray::fromRawData(block.data(), blockLen)); if (text.size() > 1000*1000) { si.setError(L10N::errorFileTooLarge(url)); break; } } io->close(); if (si.hasError()) { return matrix; } QTextStream reader(text); QString line; while (!reader.atEnd() && !si.hasError()) { line = reader.readLine(); if (line.isEmpty()) { continue; } if (line.indexOf(":") > 2 || line.indexOf(":") < 0) { UniprobeInfo info(line); matrix.setInfo(info); continue; } QStringList curr = line.split(QRegExp("\\s+"), QString::SkipEmptyParts); if (len == -1) { len = curr.length() - 1; } if (len != curr.length() - 1) { si.setError(tr("Error parsing settings line %1").arg(line) ); break; } for (int i = 1; i <= len; i++) { bool ok; QString tmp = curr[i]; float val = tmp.toFloat(&ok); if (!ok) { si.setError(tr("Error parsing value %1").arg(tmp)); break; } res.append(val); } msize++; } if (si.hasError()) { return matrix; } if (msize != 4 && msize != 16) { si.setError(tr("Incorrect size of weight matrix: %1").arg(msize)); return matrix; } matrix = PWMatrix(res, (msize == 4) ? PWM_MONONUCLEOTIDE : PWM_DINUCLEOTIDE); return matrix; } void WeightMatrixIO::writePFMatrix(IOAdapterFactory* iof, const QString& url, TaskStateInfo& si, const PFMatrix& model) { assert (model.getLength() >= 0); QByteArray res; int size = (model.getType() == PFM_MONONUCLEOTIDE) ? 4 : 16; for (int i = 0; i < size; i++) { for (int j = 0, n = model.getLength(); j < n; j++) { res.append(QString("%1").arg(model.getValue(i, j), 4)); } res.append("\n"); } std::auto_ptr io(iof->createIOAdapter()); if (!io->open(url, IOAdapterMode_Write)) { si.setError( L10N::errorOpeningFileWrite(url) ); return; } int len = io->writeBlock(res); if (len != res.size()) { si.setError( L10N::errorWritingFile(url) ); return; } io->close(); } void WeightMatrixIO::writePWMatrix(IOAdapterFactory* iof, const QString& url, TaskStateInfo& si, const PWMatrix& model) { assert (model.getLength() >= 0); QByteArray res; int size = (model.getType() == PWM_MONONUCLEOTIDE) ? 4 : 16; for (int i = 0; i < size; i++) { if (model.getType() == PWM_MONONUCLEOTIDE) { res.append(DiProperty::fromIndex(i)); res.append(": "); } else { res.append(DiProperty::fromIndexHi(i)); res.append(DiProperty::fromIndexLo(i)); res.append(": "); } for (int j = 0, n = model.getLength(); j < n; j++) { res.append(QString("%1").arg(model.getValue(i, j), -20, 'f', 15)); } res.append("\n"); } std::auto_ptr io(iof->createIOAdapter()); if (!io->open(url, IOAdapterMode_Write)) { si.setError( L10N::errorOpeningFileWrite(url) ); return; } int len = io->writeBlock(res); if (len != res.size()) { si.setError( L10N::errorWritingFile(url) ); return; } io->close(); } void PFMatrixReadTask::run() { IOAdapterFactory* iof = AppContext::getIOAdapterRegistry()->getIOAdapterFactoryById(BaseIOAdapters::url2io(url)); model = WeightMatrixIO::readPFMatrix(iof, url, stateInfo); } void PFMatrixWriteTask::run() { IOAdapterFactory* iof = AppContext::getIOAdapterRegistry()->getIOAdapterFactoryById(BaseIOAdapters::url2io(url)); if (fileMode & SaveDoc_Roll && !GUrlUtils::renameFileWithNameRoll(url, stateInfo)) { return; } WeightMatrixIO::writePFMatrix(iof, url, stateInfo, model); } void PWMatrixReadTask::run() { IOAdapterFactory* iof = AppContext::getIOAdapterRegistry()->getIOAdapterFactoryById(BaseIOAdapters::url2io(url)); model = WeightMatrixIO::readPWMatrix(iof, url, stateInfo); } void PWMatrixWriteTask::run() { IOAdapterFactory* iof = AppContext::getIOAdapterRegistry()->getIOAdapterFactoryById(BaseIOAdapters::url2io(url)); if (fileMode & SaveDoc_Roll && !GUrlUtils::renameFileWithNameRoll(url, stateInfo)) { return; } WeightMatrixIO::writePWMatrix(iof, url, stateInfo, model); } }//namespace ugene-1.9.8/src/plugins/weight_matrix/src/WMQuery.h0000644000175000017500000000434211651544324020756 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_WM_QUERY_H_ #define _U2_WM_QUERY_H_ #include "WeightMatrixSearchTask.h" #include #include #include namespace U2 { class PWMatrixReadTask; class WMQDTask : public Task { Q_OBJECT public: WMQDTask(const QString& url, const WeightMatrixSearchCfg& cfg, DNASequenceObject* sqnc, const QString& resName, const QVector& location); QList onSubTaskFinished(Task* subTask); QList takeResults(); private: WeightMatrixSearchCfg settings; DNASequenceObject* seqObj; QString resultName; PWMatrixReadTask* readTask; QList res; QVector location; }; class QDWMActor : public QDActor { Q_OBJECT public: QDWMActor(QDActorPrototype const* proto); int getMinResultLen() const; int getMaxResultLen() const; QString getText() const; Task* getAlgorithmTask(const QVector& location); QColor defaultColor() const { return QColor(0xff,0xf8,0); } private slots: void sl_onAlgorithmTaskFinished(Task* t); }; class QDWMActorPrototype : public QDActorPrototype { public: QDWMActorPrototype(); QIcon getIcon() const { return QIcon(":weight_matrix/images/weight_matrix.png"); } virtual QDActor* createInstance() const { return new QDWMActor(this); } }; }//namespace #endif ugene-1.9.8/src/plugins/weight_matrix/src/WeightMatrixAlgorithm.cpp0000644000175000017500000000366211651544324024227 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "WeightMatrixAlgorithm.h" #include namespace U2 { float WeightMatrixAlgorithm::getScore(const char* seq, int len, const PWMatrix& m, DNATranslation* complMap) { int l = m.getLength(); float lower = m.getMinSum(), upper = m.getMaxSum(); QByteArray complMapper = (complMap != NULL) ? complMap->getOne2OneMapper() : QByteArray(); assert ((upper - lower) > 1e-9); float curr = 0; if (m.getType() == PWM_MONONUCLEOTIDE) { for (int i = 0; i < len && i < l; i++) { char c = (complMap != NULL) ? complMapper[uchar(seq[i])] : seq[i]; curr += m.getValue(DiProperty::index(c), i); } } else { for (int i = 0; i < len && i < l; i++) { char c1 = (complMap != NULL) ? complMapper[uchar(seq[i])] : seq[i]; char c2 = (complMap != NULL) ? complMapper[uchar(seq[i+1])] : seq[i+1]; curr += m.getValue(DiProperty::index(c1, c2), i); } } assert (curr >= lower); assert (curr <= upper); return (curr - lower) / (upper - lower); } } //namespaceugene-1.9.8/src/plugins/weight_matrix/src/ViewMatrixDialogController.cpp0000644000175000017500000001552311651544324025226 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "ViewMatrixDialogController.h" #include #include #include #include #include namespace U2 { ViewMatrixDialogController::ViewMatrixDialogController(QWidget *w) : QDialog(w), logoArea(NULL) { setupUi(this); connect(closeButton, SIGNAL(clicked()), SLOT(sl_onCloseButton())); } ViewMatrixDialogController::ViewMatrixDialogController(PFMatrix matrix, QWidget *w) : QDialog(w), logoArea(NULL) { setupUi(this); if (matrix.getType() == PFM_MONONUCLEOTIDE) { tableWidget->setRowCount(4); tableWidget->setColumnCount(matrix.getLength()); for (int i = 0, n = matrix.getLength(); i < n; i++) { tableWidget->setHorizontalHeaderItem(i, new QTableWidgetItem(QString("%1").arg(i + 1))); } for (int i = 0; i < 4; i++) { tableWidget->setVerticalHeaderItem(i, new QTableWidgetItem(QString(DiProperty::fromIndex(i)))); for (int j = 0, n = matrix.getLength(); j < n; j++) { tableWidget->setItem(i, j, new QTableWidgetItem(QString("%1").arg(matrix.getValue(i, j)))); tableWidget->item(i, j)->setTextAlignment(Qt::AlignRight); } } } else { tableWidget->setRowCount(16); tableWidget->setColumnCount(matrix.getLength()); for (int i = 0, n = matrix.getLength(); i < n; i++) { tableWidget->setHorizontalHeaderItem(i, new QTableWidgetItem(QString("%1").arg(i + 1))); } for (int i = 0; i < 16; i++) { tableWidget->setVerticalHeaderItem(i, new QTableWidgetItem(QString(DiProperty::fromIndexHi(i))+QString(DiProperty::fromIndexLo(i)))); for (int j = 0, n = matrix.getLength(); j < n; j++) { tableWidget->setItem(i, j, new QTableWidgetItem(QString("%1").arg(matrix.getValue(i, j)))); tableWidget->item(i, j)->setTextAlignment(Qt::AlignRight); } } } tableWidget->resizeRowsToContents(); tableWidget->resizeColumnsToContents(); tableWidget->setMinimumWidth(tableWidget->width()); tableWidget->setFixedHeight(tableWidget->verticalHeader()->length() + tableWidget->horizontalHeader()->height() + 20); int len = matrix.getLength(); int size = 0; int n = matrix.getType() == PFM_MONONUCLEOTIDE ? 4 : 16; int logoheight = 150; int logowidth = 8 * len; for (int i = 0; i < n; i++) { size += matrix.getValue(i, 0); } QList rows; for (int i = 0; i < size; i++) { QByteArray arr; for (int j = 0; j < len; j++) { int row = 0; int sum = i; while (row < n && sum >= matrix.getValue(row, j)) { sum -= matrix.getValue(row, j); row++; } if (row == n) row--; if (matrix.getType() == PFM_MONONUCLEOTIDE) { arr.append(DiProperty::fromIndex(row)); } else { arr.append(DiProperty::fromIndexHi(row)); if (j == len - 1) { arr.append(DiProperty::fromIndexLo(row)); } } } rows.append(MAlignmentRow("", arr)); } DNAAlphabet* al = AppContext::getDNAAlphabetRegistry()->findById(BaseDNAAlphabetIds::NUCL_DNA_DEFAULT()); MAlignment ma(QString("Temporary alignment"), al, rows); AlignmentLogoSettings logoSettings(ma); logoWidget->resize(logowidth, logoheight); scrollArea->resize(logowidth, logoheight + 10); if (logoArea != NULL) { logoArea->replaceSettings(logoSettings); } else { logoArea = new AlignmentLogoRenderArea(logoSettings, logoWidget); } logoArea->repaint(); connect(closeButton, SIGNAL(clicked()), SLOT(sl_onCloseButton())); } ViewMatrixDialogController::ViewMatrixDialogController(PWMatrix matrix, QWidget *w) : QDialog(w), logoArea(NULL) { setupUi(this); if (matrix.getType() == PWM_MONONUCLEOTIDE) { tableWidget->setRowCount(4); tableWidget->setColumnCount(matrix.getLength()); for (int i = 0, n = matrix.getLength(); i < n; i++) { tableWidget->setHorizontalHeaderItem(i, new QTableWidgetItem(QString("%1").arg(i + 1))); } for (int i = 0; i < 4; i++) { tableWidget->setVerticalHeaderItem(i, new QTableWidgetItem(QString(DiProperty::fromIndex(i)))); for (int j = 0, n = matrix.getLength(); j < n; j++) { tableWidget->setItem(i, j, new QTableWidgetItem(QString("%1").arg(matrix.getValue(i, j)))); tableWidget->item(i, j)->setTextAlignment(Qt::AlignRight); } } } else { tableWidget->setRowCount(16); tableWidget->setColumnCount(matrix.getLength()); for (int i = 0, n = matrix.getLength(); i < n; i++) { tableWidget->setHorizontalHeaderItem(i, new QTableWidgetItem(QString("%1").arg(i + 1))); } for (int i = 0; i < 16; i++) { tableWidget->setVerticalHeaderItem(i, new QTableWidgetItem(QString(DiProperty::fromIndexHi(i))+QString(DiProperty::fromIndexLo(i)))); for (int j = 0, n = matrix.getLength(); j < n; j++) { tableWidget->setItem(i, j, new QTableWidgetItem(QString("%1").arg(matrix.getValue(i, j)))); tableWidget->item(i, j)->setTextAlignment(Qt::AlignRight); } } } tableWidget->resizeRowsToContents(); tableWidget->resizeColumnsToContents(); tableWidget->setMinimumWidth(tableWidget->width()); tableWidget->setMinimumHeight(tableWidget->verticalHeader()->length() + tableWidget->horizontalHeader()->height() + 20); scrollArea->setHidden(true); verticalLayout_2->setStretch(0, 1); verticalLayout_2->setStretch(1, 0); verticalLayout_2->setStretch(2, 0); resize(width(), minimumHeight()); connect(closeButton, SIGNAL(clicked()), SLOT(sl_onCloseButton())); } void ViewMatrixDialogController::sl_onCloseButton() { QDialog::reject(); } } //namespaceugene-1.9.8/src/plugins/weight_matrix/src/PWMBuildDialogController.cpp0000644000175000017500000005200711651544324024550 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "PWMBuildDialogController.h" #include "WeightMatrixPlugin.h" #include "WeightMatrixIO.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #define SETTINGS_ROOT QString("plugin_weight_matrix/") namespace U2 { PWMBuildDialogController::PWMBuildDialogController(QWidget* w) : QDialog(w), logoArea(NULL) { task = NULL; setupUi(this); QStringList algo = AppContext::getPWMConversionAlgorithmRegistry()->getAlgorithmIds(); algorithmCombo->addItems(algo); this->resize(this->width(), this->minimumHeight()); connect(inputButton, SIGNAL(clicked()), SLOT(sl_inFileButtonClicked())); connect(outputButton, SIGNAL(clicked()), SLOT(sl_outFileButtonClicked())); connect(okButton, SIGNAL(clicked()), SLOT(sl_okButtonClicked())); connect(weightButton, SIGNAL(toggled(bool)), SLOT(sl_matrixTypeChanged(bool))); } void PWMBuildDialogController::sl_inFileButtonClicked() { LastOpenDirHelper lod; lod.url = QFileDialog::getOpenFileName(this, tr("Select file with alignment"), lod, DialogUtils::prepareDocumentsFileFilterByObjType(GObjectTypes::MULTIPLE_ALIGNMENT, true).append("\n").append( DialogUtils::prepareDocumentsFileFilterByObjType(GObjectTypes::SEQUENCE, false))); if (lod.url.isEmpty()) { return; } QString inFile = QFileInfo(lod.url).absoluteFilePath(); inputEdit->setText(inFile); QList formats = DocumentUtils::detectFormat(inFile); if (formats.isEmpty()) { return; } DocumentFormat* format = NULL; foreach(const FormatDetectionResult& i, formats) { if (i.format->getSupportedObjectTypes().contains(GObjectTypes::MULTIPLE_ALIGNMENT)) { format = i.format; break; } } if (format == NULL) { foreach(const FormatDetectionResult& i, formats) { if (i.format->getSupportedObjectTypes().contains(GObjectTypes::SEQUENCE)) { format = i.format; break; } } } //DocumentFormat* format = formats.first(); IOAdapterFactory* iof = AppContext::getIOAdapterRegistry()->getIOAdapterFactoryById(BaseIOAdapters::url2io(inFile)); TaskStateInfo ti; QVariantMap hints; Document *doc = format->loadDocument(iof, inFile, ti, hints); if (ti.hasError()) { return; } assert (doc != NULL); QList mobjs = doc->findGObjectByType(GObjectTypes::MULTIPLE_ALIGNMENT); if (!mobjs.isEmpty()) { MAlignmentObject* mobj = qobject_cast(mobjs.first()); MAlignment ma = mobj->getMAlignment(); replaceLogo(ma); } else { mobjs = doc->findGObjectByType(GObjectTypes::SEQUENCE); if (!mobjs.isEmpty()) { QList rows; foreach (GObject* obj, mobjs) { DNASequenceObject* dnaObj = qobject_cast(obj); if (dnaObj->getAlphabet()->getType() != DNAAlphabet_NUCL) { ti.setError( tr("Wrong sequence alphabet") ); } rows.append(MAlignmentRow(dnaObj->getDNASequence().getName(), dnaObj->getSequence())); } DNASequenceObject* dnaObj = qobject_cast(mobjs.first()); MAlignment ma(dnaObj->getDNASequence().getName(), dnaObj->getAlphabet(), rows); replaceLogo(ma); } else { PFMatrix pfm = WeightMatrixIO::readPFMatrix(iof, lod.url, ti); if (ti.hasError()) { logoArea->hide(); return; } int len = pfm.getLength(); if (len == 0) { logoArea->hide(); ti.setError(tr("Zero length matrix is not allowed")); return; } int size = 0; for (int i = 0, n = pfm.getType() == PFM_MONONUCLEOTIDE ? 4 : 16; i < n; i++) { size += pfm.getValue(i, 0); } QList rows; for (int i = 0; i < size; i++) { QByteArray arr; for (int j = 0; j < len; j++) { int row = 0; int sum = i; while (sum >= pfm.getValue(row, j)) { sum -= pfm.getValue(row, j); row++; } if (pfm.getType() == PFM_MONONUCLEOTIDE) { arr.append(DiProperty::fromIndex(row)); } else { arr.append(DiProperty::fromIndexHi(row)); if (j == len - 1) { arr.append(DiProperty::fromIndexLo(row)); } } } rows.append(MAlignmentRow("", arr)); } DNAAlphabet* al = AppContext::getDNAAlphabetRegistry()->findById(BaseDNAAlphabetIds::NUCL_DNA_DEFAULT()); MAlignment ma(QString("Temporary alignment"), al, rows); replaceLogo(ma); } } } void PWMBuildDialogController::replaceLogo(const MAlignment& ma) { int logoheight = 150; if (ma.getLength() < 50) { AlignmentLogoSettings logoSettings(ma); logoWidget->resize(logoWidget->width(), logoheight); logoWidget->setMinimumHeight(logoheight); logoWidget->show(); if (logoArea != NULL) { logoArea->replaceSettings(logoSettings); } else { logoArea = new AlignmentLogoRenderArea(logoSettings, logoWidget); } logoArea->repaint(); } } void PWMBuildDialogController::sl_outFileButtonClicked() { LastOpenDirHelper lod(WeightMatrixIO::WEIGHT_MATRIX_ID); if (frequencyButton->isChecked()) { lod.url = QFileDialog::getSaveFileName(this, tr("Select file to save frequency matrix to..."), lod, WeightMatrixIO::getPFMFileFilter(false)); } else { lod.url = QFileDialog::getSaveFileName(this, tr("Select file to save weight matrix to..."), lod, WeightMatrixIO::getPWMFileFilter(false)); } if (lod.url.isEmpty()) { return; } outputEdit->setText(QFileInfo(lod.url).absoluteFilePath()); } void PWMBuildDialogController::sl_matrixTypeChanged(bool matrixType) { QStringList nameParts = outputEdit->text().split("."); if (matrixType) { for (int i = nameParts.length() - 1; i >= 0; --i) { if (nameParts[i] == WeightMatrixIO::FREQUENCY_MATRIX_EXT) { nameParts[i] = WeightMatrixIO::WEIGHT_MATRIX_EXT; break; } } } else { for (int i = nameParts.length() - 1; i >= 0; --i) { if (nameParts[i] == WeightMatrixIO::WEIGHT_MATRIX_EXT) { nameParts[i] = WeightMatrixIO::FREQUENCY_MATRIX_EXT; break; } } } QString name = nameParts.join("."); if (QFile::exists(name)) { if (QMessageBox::No == QMessageBox::question(this, tr("Overwrite existing file"), tr("File with this name already exists.\nDo you want to write over this file?"), QMessageBox::Yes | QMessageBox::No)) { emit sl_outFileButtonClicked(); return; } } outputEdit->setText(name); } void PWMBuildDialogController::sl_okButtonClicked() { if (task != NULL) { accept(); //go to background return; } // try prepare model PMBuildSettings s; QString errMsg; QString inFile = inputEdit->text(); if (inFile.isEmpty() || !QFile::exists(inFile)) { statusLabel->setText(tr("Illegal input file name")); inputEdit->setFocus(); return; } QString outFile = outputEdit->text(); if (outFile.isEmpty()) { statusLabel->setText(tr("Illegal output file name")); outputEdit->setFocus(); return; } if (frequencyButton->isChecked()) { s.target = FREQUENCY_MATRIX; } else { s.target = WEIGHT_MATRIX; } //save settings //AppContext::getSettings()->setValue(SETTINGS_ROOT + WEIGHT_ALG, weightAlgCombo->currentIndex()); if (mononucleicButton->isChecked()) { s.type = PM_MONONUCLEOTIDE; } else { s.type = PM_DINUCLEOTIDE; } // run task if (frequencyButton->isChecked()) { task = new PFMatrixBuildToFileTask(inFile, outFile, s); } else { s.algo = algorithmCombo->currentText(); task = new PWMatrixBuildToFileTask(inFile, outFile, s); } connect(task, SIGNAL(si_stateChanged()), SLOT(sl_onStateChanged())); connect(task, SIGNAL(si_progressChanged()), SLOT(sl_onProgressChanged())); AppContext::getTaskScheduler()->registerTopLevelTask(task); statusLabel->setText(tr("Counting frequency statistics")); //update buttons okButton->setText(tr("Hide")); cancelButton->setText(tr("Cancel")); } void PWMBuildDialogController::sl_onStateChanged() { Task* t = qobject_cast(sender()); assert(task!=NULL); if (task != t || t->getState() != Task::State_Finished) { return; } task->disconnect(this); const TaskStateInfo& si = task->getStateInfo(); if (si.hasError()) { statusLabel->setText(tr("Build finished with errors: %1").arg(si.getError())); lastURL = ""; } else if (task->isCanceled()) { statusLabel->setText(tr("Build canceled")); lastURL = ""; } else { statusLabel->setText(tr("Build finished successfuly")); lastURL = outputEdit->text(); } okButton->setText(tr("Start")); cancelButton->setText(tr("Close")); task = NULL; } void PWMBuildDialogController::sl_onProgressChanged() { assert(task==sender()); statusLabel->setText(tr("Running state %1 progress %2%").arg(task->getStateInfo().getDescription()).arg(task->getProgress())); } void PWMBuildDialogController::reject() { if (task!=NULL) { task->cancel(); } if (lastURL != "") { QDialog::accept(); } else { QDialog::reject(); } } ////////////////////////////////////////////////////////////////////////// // tasks PFMatrixBuildTask::PFMatrixBuildTask(const PMBuildSettings& s, const MAlignment& ma) : Task (tr("Build frequency matrix"), TaskFlag_None), settings(s), ma(ma) { GCOUNTER( cvar, tvar, "PFMatrixBuildTask" ); tpm = Task::Progress_Manual; } void PFMatrixBuildTask::run() { if (ma.hasGaps()) { stateInfo.setError( tr("Alignment has gaps") ); return; } if (ma.isEmpty()) { stateInfo.setError( tr("Alignment is empty") ); return; } if (!ma.getAlphabet()->isNucleic()) { stateInfo.setError( tr("Alignment is not nucleic") ); return; } stateInfo.setDescription( tr("Calculating frequencies of nucleotids") ); if (settings.type == PM_MONONUCLEOTIDE) { m = PFMatrix(ma, PFM_MONONUCLEOTIDE); } else { m = PFMatrix(ma, PFM_DINUCLEOTIDE); } stateInfo.progress+=50; if (stateInfo.hasError() || isCanceled()) { return; } return; } PFMatrixBuildToFileTask::PFMatrixBuildToFileTask(const QString& inFile, const QString& _outFile, const PMBuildSettings& s) : Task (tr("Build weight matrix"), TaskFlag_NoRun), loadTask(NULL), buildTask(NULL), outFile(_outFile), settings(s) { tpm = Task::Progress_SubTasksBased; DocumentFormatConstraints c; c.checkRawData = true; c.supportedObjectTypes += GObjectTypes::MULTIPLE_ALIGNMENT; c.supportedObjectTypes += GObjectTypes::SEQUENCE; c.rawData = BaseIOAdapters::readFileHeader(inFile); QList formats = DocumentUtils::detectFormat(inFile); if (formats.isEmpty()) { stateInfo.setError( tr("Input format error") ); return; } DocumentFormatId format = ""; foreach(const FormatDetectionResult& i, formats) { if (i.format->getSupportedObjectTypes().contains(GObjectTypes::MULTIPLE_ALIGNMENT)) { format = i.format->getFormatId(); break; } } if(format.isEmpty()) { foreach(const FormatDetectionResult& i, formats) { if (i.format->getSupportedObjectTypes().contains(GObjectTypes::SEQUENCE)) { format = i.format->getFormatId(); break; } } } //DocumentFormatId format = formats.first()->getFormatId(); IOAdapterFactory* iof = AppContext::getIOAdapterRegistry()->getIOAdapterFactoryById(BaseIOAdapters::url2io(inFile)); loadTask = new LoadDocumentTask(format, inFile, iof); loadTask->setSubtaskProgressWeight(0.03F); stateInfo.progress = 0; stateInfo.setDescription(tr("Loading alignment")); addSubTask(loadTask); } QList PFMatrixBuildToFileTask::onSubTaskFinished(Task* subTask) { QList res; if (isCanceled()) { return res; } if (subTask->getStateInfo().hasError()) { stateInfo.setError( subTask->getStateInfo().getError() ); return res; } if (subTask == loadTask) { setUseDescriptionFromSubtask(true); Document* d = loadTask->getDocument(); assert(d != NULL); QList mobjs = d->findGObjectByType(GObjectTypes::MULTIPLE_ALIGNMENT); if (!mobjs.isEmpty()) { MAlignmentObject* mobj = qobject_cast(mobjs.first()); MAlignment ma = mobj->getMAlignment(); buildTask = new PFMatrixBuildTask(settings, ma); res.append(buildTask); } else { mobjs = d->findGObjectByType(GObjectTypes::SEQUENCE); if (!mobjs.isEmpty()) { QList rows; foreach (GObject* obj, mobjs) { DNASequenceObject* dnaObj = qobject_cast(obj); if (dnaObj->getAlphabet()->getType() != DNAAlphabet_NUCL) { stateInfo.setError( tr("Wrong sequence alphabet") ); } rows.append(MAlignmentRow(dnaObj->getDNASequence().getName(), dnaObj->getSequence())); } DNASequenceObject* dnaObj = qobject_cast(mobjs.first()); QString baseName = d->getURL().baseFileName(); MAlignment ma(baseName, dnaObj->getAlphabet(), rows); buildTask = new PFMatrixBuildTask(settings, ma); res.append(buildTask); } else { stateInfo.setError( tr("No alignments or sequences found") ); } } } else if (subTask == buildTask) { Task* t = new PFMatrixWriteTask(outFile, buildTask->getResult()); t->setSubtaskProgressWeight(0); res.append(t); } return res; } PWMatrixBuildTask::PWMatrixBuildTask(const PMBuildSettings& s, const MAlignment& ma) : Task (tr("Build weight matrix"), TaskFlag_None), settings(s), ma(ma) { GCOUNTER( cvar, tvar, "PWMatrixBuildTask" ); tpm = Task::Progress_Manual; } PWMatrixBuildTask::PWMatrixBuildTask(const PMBuildSettings& s, const PFMatrix& ma) : Task (tr("Build weight matrix"), TaskFlag_None), settings(s), tempMatrix(ma) { GCOUNTER( cvar, tvar, "PWMatrixBuildTask" ); tpm = Task::Progress_Manual; } void PWMatrixBuildTask::run() { if (tempMatrix.getLength() > 0) { if (settings.type == PM_DINUCLEOTIDE && tempMatrix.getType() == PFM_MONONUCLEOTIDE) { stateInfo.setError( tr("Can't convert mononucleotide matrix to dinucleotide one")); return; } if (settings.type == PM_MONONUCLEOTIDE && tempMatrix.getType() == PFM_DINUCLEOTIDE) { tempMatrix = PFMatrix::convertDi2Mono(tempMatrix); } stateInfo.progress+=40; if (stateInfo.hasError() || isCanceled()) { return; } } else { if (ma.hasGaps()) { stateInfo.setError( tr("Alignment has gaps") ); return; } if (ma.isEmpty()) { stateInfo.setError( tr("Alignment is empty") ); return; } if (!ma.getAlphabet()->isNucleic()) { stateInfo.setError( tr("Alignment is not nucleic") ); return; } if (settings.type == PM_MONONUCLEOTIDE) { tempMatrix = PFMatrix(ma, PFM_MONONUCLEOTIDE); } else { tempMatrix = PFMatrix(ma, PFM_DINUCLEOTIDE); } stateInfo.progress+=40; if (stateInfo.hasError() || isCanceled()) { return; } } PWMConversionAlgorithmFactory* factory = AppContext::getPWMConversionAlgorithmRegistry()->getAlgorithmFactory(settings.algo); PWMConversionAlgorithm* algo = factory->createAlgorithm(); m = algo->convert(tempMatrix); stateInfo.progress+=40; return; } PWMatrixBuildToFileTask::PWMatrixBuildToFileTask(const QString& inFile, const QString& _outFile, const PMBuildSettings& s) : Task (tr("Build weight matrix"), TaskFlag_NoRun), loadTask(NULL), buildTask(NULL), outFile(_outFile), settings(s) { tpm = Task::Progress_SubTasksBased; DocumentFormatConstraints c; c.checkRawData = true; c.supportedObjectTypes += GObjectTypes::MULTIPLE_ALIGNMENT; c.supportedObjectTypes += GObjectTypes::SEQUENCE; c.rawData = BaseIOAdapters::readFileHeader(inFile); QList formats = DocumentUtils::detectFormat(inFile); if (formats.isEmpty()) { stateInfo.setError( tr("Input format error") ); return; } DocumentFormatId format = formats.first().format->getFormatId(); IOAdapterFactory* iof = AppContext::getIOAdapterRegistry()->getIOAdapterFactoryById(BaseIOAdapters::url2io(inFile)); loadTask = new LoadDocumentTask(format, inFile, iof); loadTask->setSubtaskProgressWeight(0.03F); stateInfo.progress = 0; stateInfo.setDescription(tr("Loading alignment")); addSubTask(loadTask); } QList PWMatrixBuildToFileTask::onSubTaskFinished(Task* subTask) { QList res; if (isCanceled()) { return res; } if (subTask->getStateInfo().hasError()) { stateInfo.setError( subTask->getStateInfo().getError() ); return res; } if (subTask == loadTask) { setUseDescriptionFromSubtask(true); Document* d = loadTask->getDocument(); assert(d != NULL); QList mobjs = d->findGObjectByType(GObjectTypes::MULTIPLE_ALIGNMENT); if (!mobjs.isEmpty()) { MAlignmentObject* mobj = qobject_cast(mobjs.first()); MAlignment ma = mobj->getMAlignment(); buildTask = new PWMatrixBuildTask(settings, ma); res.append(buildTask); } else { mobjs = d->findGObjectByType(GObjectTypes::SEQUENCE); if (!mobjs.isEmpty()) { QList rows; foreach (GObject* obj, mobjs) { DNASequenceObject* dnaObj = qobject_cast(obj); if (dnaObj->getAlphabet()->getType() != DNAAlphabet_NUCL) { stateInfo.setError( tr("Wrong sequence alphabet") ); } rows.append(MAlignmentRow(dnaObj->getDNASequence().getName(), dnaObj->getSequence())); } DNASequenceObject* dnaObj = qobject_cast(mobjs.first()); QString baseName = d->getURL().baseFileName(); MAlignment ma(baseName, dnaObj->getAlphabet(), rows); buildTask = new PWMatrixBuildTask(settings, ma); res.append(buildTask); } else { stateInfo.setError( tr("No alignments or sequences found") ); } } } else if (subTask == buildTask) { Task* t = new PWMatrixWriteTask(outFile, buildTask->getResult()); t->setSubtaskProgressWeight(0); res.append(t); } return res; } }//namespace ugene-1.9.8/src/plugins/weight_matrix/src/WeightMatrixSearchTask.h0000644000175000017500000000760311651544324023775 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_WEIGHT_MATRIX_SEARCH_TASK_H_ #define _U2_WEIGHT_MATRIX_SEARCH_TASK_H_ #include "WeightMatrixAlgorithm.h" #include #include #include #include #include namespace U2 { class WeightMatrixSearchResult { public: WeightMatrixSearchResult() : strand(U2Strand::Direct), score(-1) { qual = QMap(); } SharedAnnotationData toAnnotation(const QString& name) const { SharedAnnotationData data; data = new AnnotationData; data->name = name; data->location->regions << region; data->setStrand(strand); if (!modelInfo.isEmpty()) { data->qualifiers.append(U2Qualifier("Weight matrix model", modelInfo)); } data->qualifiers.append(U2Qualifier("Score", QString::number(score))); QMapIterator iter(qual); while (iter.hasNext()) { iter.next(); data->qualifiers.append(U2Qualifier(iter.key(), iter.value())); } return data; } static QList toTable(const QList& res, const QString& name) { QList list; foreach (const WeightMatrixSearchResult& f, res) { list.append(f.toAnnotation(name)); } return list; } U2Region region; U2Strand strand; float score; QString modelInfo; QMap qual; }; class WeightMatrixSearchCfg { public: WeightMatrixSearchCfg() : minPSUM(0), modelName(""), complTT(NULL), complOnly(false), algo("") {} int minPSUM; QString modelName; DNATranslation* complTT; bool complOnly; //FIXME use strand instead QString algo; }; class WeightMatrixSearchTask : public Task { Q_OBJECT public: WeightMatrixSearchTask(const QList< QPair< PWMatrix, WeightMatrixSearchCfg > >& models, const char* seq, int len, int resultsOffset); QList takeResults(); private: void addResult(const WeightMatrixSearchResult& r); QMutex lock; QList< QPair > models; QList results; int resultsOffset; }; class WeightMatrixSingleSearchTask : public Task, public SequenceWalkerCallback { Q_OBJECT public: WeightMatrixSingleSearchTask(const PWMatrix& model, const char* seq, int len, const WeightMatrixSearchCfg& cfg, int resultsOffset); virtual void onRegion(SequenceWalkerSubtask* t, TaskStateInfo& ti); QList takeResults(); private: void addResult(const WeightMatrixSearchResult& r); QMutex lock; PWMatrix model; WeightMatrixSearchCfg cfg; QList results; int resultsOffset; }; }//namespace #endif ugene-1.9.8/src/plugins/weight_matrix/src/PWMSearchDialogController.cpp0000644000175000017500000004647111651544324024726 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "PWMSearchDialogController.h" #include "PWMBuildDialogController.h" #include "PWMJASPARDialogController.h" #include "ViewMatrixDialogController.h" #include "SetParametersDialogController.h" #include "WeightMatrixSearchTask.h" #include "WeightMatrixAlgorithm.h" #include "WeightMatrixIO.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include namespace U2 { class WeightMatrixResultItem : public QTreeWidgetItem { public: WeightMatrixResultItem(const WeightMatrixSearchResult& r); WeightMatrixSearchResult res; virtual bool operator< ( const QTreeWidgetItem & other ) const { const WeightMatrixResultItem* o = (const WeightMatrixResultItem*)&other; int n = treeWidget()->sortColumn(); switch (n) { case 0 : return res.region.startPos < o->res.region.startPos; case 1: return res.modelInfo < o->res.modelInfo; case 2: return res.strand != o->res.strand ? res.strand.isCompementary() : (res.region.startPos < o->res.region.startPos); case 3: return res.score < o->res.score; } return false; } }; class WeightMatrixQueueItem : public QTreeWidgetItem { public: WeightMatrixQueueItem(const WeightMatrixSearchCfg& r); WeightMatrixSearchCfg res; virtual bool operator< ( const QTreeWidgetItem & other ) const { const WeightMatrixQueueItem* o = (const WeightMatrixQueueItem*)&other; int n = treeWidget()->sortColumn(); switch (n) { case 0 : return res.modelName.split("/").last() < o->res.modelName.split("/").last(); case 1 : return res.minPSUM < o->res.minPSUM; case 2 : return res.algo < o->res.algo; } return false; } }; /* TRANSLATOR U2::PWMSearchDialogController */ PWMSearchDialogController::PWMSearchDialogController(ADVSequenceObjectContext* _ctx, QWidget *p):QDialog(p) { setupUi(this); model = PWMatrix(); intermediate = PFMatrix(); ctx = _ctx; task = NULL; initialSelection = ctx->getSequenceSelection()->isEmpty() ? U2Region() : ctx->getSequenceSelection()->getSelectedRegions().first(); int seqLen = ctx->getSequenceLen(); sbRangeStart->setMinimum(1); sbRangeStart->setMaximum(seqLen); sbRangeEnd->setMinimum(1); sbRangeEnd->setMaximum(seqLen); sbRangeStart->setValue(1); sbRangeEnd->setValue(seqLen); connectGUI(); updateState(); scoreValueLabel->setText(QString("%1%").arg(scoreSlider->value())); QStringList algo = AppContext::getPWMConversionAlgorithmRegistry()->getAlgorithmIds(); algorithmCombo->addItems(algo); pbSelectModelFile->setFocus(); timer = new QTimer(this); connect(timer, SIGNAL(timeout()), SLOT(sl_onTimer())); } void PWMSearchDialogController::connectGUI() { //buttons connect(pbSelectModelFile, SIGNAL(clicked()), SLOT(sl_selectModelFile())); connect(pbSaveAnnotations, SIGNAL(clicked()), SLOT(sl_onSaveAnnotations())); connect(pbClear, SIGNAL(clicked()), SLOT(sl_onClearList())); connect(pbSearch, SIGNAL(clicked()), SLOT(sl_onSearch())); connect(pbClose, SIGNAL(clicked()), SLOT(sl_onClose())); connect(scoreSlider, SIGNAL(valueChanged(int)), SLOT(sl_onSliderMoved(int))); connect(buildButton, SIGNAL(clicked()), SLOT(sl_onBuildMatrix())); connect(jasparButton, SIGNAL(clicked()), SLOT(sl_onSearchJaspar())); connect(viewMatrixButton, SIGNAL(clicked()), SLOT(sl_onViewMatrix())); connect(queueButton, SIGNAL(clicked()), SLOT(sl_onAddToQueue())); connect(algorithmCombo, SIGNAL(currentIndexChanged(QString)), SLOT (sl_onAlgoChanged(QString))); connect(loadListButton, SIGNAL(clicked()), SLOT(sl_onLoadList())); connect(saveListButton, SIGNAL(clicked()), SLOT(sl_onSaveList())); connect(loadFolderButton, SIGNAL(clicked()), SLOT(sl_onLoadFolder())); connect(clearListButton, SIGNAL(clicked()), SLOT(sl_onClearQueue())); //results list connect(resultsTree, SIGNAL(itemActivated(QTreeWidgetItem*, int)), SLOT(sl_onResultActivated(QTreeWidgetItem*, int))); resultsTree->installEventFilter(this); } void PWMSearchDialogController::updateState() { bool hasInitialSelection = initialSelection.length > 0; rbSelectionRange->setEnabled(hasInitialSelection); bool hasActiveTask = task!=NULL; bool hasCompl = ctx->getComplementTT()!=NULL; bool hasResults = resultsTree->topLevelItemCount() > 0; pbSearch->setEnabled(!hasActiveTask); pbSaveAnnotations->setEnabled(!hasActiveTask && hasResults); pbClear->setEnabled(!hasActiveTask && hasResults); pbClose->setText(hasActiveTask ? tr("Cancel") : tr("Close")); rbBoth->setEnabled(!hasActiveTask && hasCompl); rbDirect->setEnabled(!hasActiveTask); rbComplement->setEnabled(!hasActiveTask && hasCompl); updateStatus(); } void PWMSearchDialogController::updateStatus() { QString message; if (task != NULL) { message = tr("Progress %1% ").arg(qMax(0, task->getProgress())); } message += tr("Results found: %1.").arg(resultsTree->topLevelItemCount()); statusLabel->setText(message); } bool PWMSearchDialogController::eventFilter(QObject *obj, QEvent *ev) { if (obj == resultsTree && ev->type() == QEvent::KeyPress) { QKeyEvent* ke = (QKeyEvent*)ev; if (ke->key() == Qt::Key_Space) { WeightMatrixResultItem* item = static_cast(resultsTree->currentItem()); if (item != NULL) { sl_onResultActivated(item, 0); } } } return false; } void PWMSearchDialogController::sl_selectModelFile() { LastOpenDirHelper lod(WeightMatrixIO::WEIGHT_MATRIX_ID); lod.url = QFileDialog::getOpenFileName(this, tr("Select file with frequency or weight matrix"), lod, WeightMatrixIO::getAllMatrixFileFilter(false) + ";;" + WeightMatrixIO::getPFMFileFilter(false) + ";;" + WeightMatrixIO::getPWMFileFilter(true)); if (lod.url.isEmpty()) { return; } loadFile(lod.url); } void PWMSearchDialogController::updateModel(const PWMatrix& m) { model = m; } void PWMSearchDialogController::sl_onSaveAnnotations() { if (resultsTree->topLevelItemCount() == 0) { return; } CreateAnnotationModel m; m.sequenceObjectRef = ctx->getSequenceObject(); m.hideLocation = true; m.sequenceLen = ctx->getSequenceObject()->getSequenceLen(); CreateAnnotationDialog d(this, m); int rc = d.exec(); if (rc != QDialog::Accepted) { return; } const QString& name = m.data->name; QList list; for (int i=0, n = resultsTree->topLevelItemCount(); i(resultsTree->topLevelItem(i)); list.append(item->res.toAnnotation(name)); } CreateAnnotationsTask* t = new CreateAnnotationsTask(m.getAnnotationObject(), m.groupName, list); AppContext::getTaskScheduler()->registerTopLevelTask(t); } void PWMSearchDialogController::sl_onClearList() { resultsTree->clear(); updateState(); } void PWMSearchDialogController::sl_onSearch() { runTask(); } void PWMSearchDialogController::sl_onAddToQueue() { addToQueue(); } void PWMSearchDialogController::addToQueue() { if (model.getLength() == 0) { QMessageBox::critical(this, L10N::errorTitle(), tr("Zero length or corrupted model")); modelFileEdit->setFocus(); return; } WeightMatrixSearchCfg cfg; cfg.modelName = modelFileEdit->text(); cfg.minPSUM = scoreSlider->value(); if (intermediate.getLength() != 0) { cfg.algo = algorithmCombo->currentText(); } QPair queueElement; queueElement.first = model; queueElement.second = cfg; WeightMatrixQueueItem* item = new WeightMatrixQueueItem(cfg); tasksTree->addTopLevelItem(item); queue.append(queueElement); model = PWMatrix(); intermediate = PFMatrix(); modelFileEdit->setText(""); } void PWMSearchDialogController::reject() { if (task!=NULL) { task->cancel(); return; } QDialog::reject(); } void PWMSearchDialogController::sl_onClose() { reject(); } void PWMSearchDialogController::sl_onSliderMoved(int value) { scoreValueLabel->setText(QString("%1%").arg(value)); updateState(); } void PWMSearchDialogController::sl_onBuildMatrix() { PWMBuildDialogController bd(this); if (bd.exec() == QDialog::Accepted) { loadFile(bd.outputEdit->text()); } } void PWMSearchDialogController::sl_onAlgoChanged(QString newAlgo){ if (intermediate.getLength() == 0) return; PWMConversionAlgorithmFactory* factory = AppContext::getPWMConversionAlgorithmRegistry()->getAlgorithmFactory(newAlgo); PWMConversionAlgorithm* algo = factory->createAlgorithm(); PWMatrix m = algo->convert(intermediate); if (m.getLength() == 0) { QMessageBox::critical(this, L10N::errorTitle(), tr("Zero length or corrupted model\nMaybe model data is not enough for selected algorithm")); return; } updateModel(m); } void PWMSearchDialogController::sl_onSearchJaspar() { PWMJASPARDialogController jd(this); if (jd.exec() == QDialog::Accepted) { if (QFile::exists(jd.fileName)) { loadFile(jd.fileName); } } } void PWMSearchDialogController::sl_onViewMatrix() { if (intermediate.getLength() != 0) { ViewMatrixDialogController vd(intermediate, this); vd.exec(); } else if (model.getLength() != 0) { ViewMatrixDialogController vd(model, this); vd.exec(); } else { QMessageBox::information(this, L10N::warningTitle(), tr("Model not selected")); } } void PWMSearchDialogController::sl_onLoadList() { LastOpenDirHelper lod(WeightMatrixIO::WEIGHT_MATRIX_ID); lod.url = QFileDialog::getOpenFileName(this, tr("Load file with list of matrices"), lod, tr("CSV files (*.csv)")); if (lod.url.isEmpty()) { return; } queue.clear(); tasksTree->clear(); QFile list(lod.url); QDir dir(lod.url); dir.cdUp(); QString path = dir.canonicalPath(); list.open(QIODevice::ReadOnly); while (!list.atEnd()) { QStringList curr = QString(list.readLine()).split(","); if (QDir::isAbsolutePath(curr[0])) { loadFile(curr[0]); } else if (QDir::isAbsolutePath(path + "/" + curr[0])) { loadFile(path + "/" + curr[0]); } else { continue; } bool ok = true; if (curr.length() > 1) { int score = curr[1].toInt(&ok); if (ok) scoreSlider->setSliderPosition(score); } if (curr.length() > 2) { int index = algorithmCombo->findText(curr[2]); if (index == -1) index = 0; algorithmCombo->setCurrentIndex(index); } addToQueue(); } list.close(); } void PWMSearchDialogController::sl_onSaveList() { if (queue.isEmpty()) { return; } LastOpenDirHelper lod(WeightMatrixIO::WEIGHT_MATRIX_ID); lod.url = QFileDialog::getSaveFileName(this, tr("Save file with list of matrices"), lod, tr("CSV files (*.csv)")); if (lod.url.isEmpty()) { return; } QFile list(lod.url); list.open(QIODevice::WriteOnly); for (int i = 0, n = queue.size(); i < n; i++) { WeightMatrixSearchCfg cfg = queue[i].second; list.write(cfg.modelName.toLatin1()); list.write(","); list.write(QString("%1").arg(cfg.minPSUM).toLatin1()); if (!cfg.algo.isEmpty()) { list.write(","); list.write(cfg.algo.toLatin1()); } list.write("\n"); } list.close(); } void PWMSearchDialogController::sl_onClearQueue() { queue.clear(); tasksTree->clear(); } void PWMSearchDialogController::sl_onLoadFolder() { LastOpenDirHelper lod(WeightMatrixIO::WEIGHT_MATRIX_ID); lod.dir = QFileDialog::getExistingDirectory(this, tr("Select directory with frequency or weight matrices"), lod); if (lod.dir.isEmpty()) { return; } queue.clear(); tasksTree->clear(); QDir dir(lod.dir); QStringList filter; filter << "*." + WeightMatrixIO::WEIGHT_MATRIX_EXT; filter << "*." + WeightMatrixIO::WEIGHT_MATRIX_EXT + ".gz"; filter << "*." + WeightMatrixIO::FREQUENCY_MATRIX_EXT; filter << "*." + WeightMatrixIO::FREQUENCY_MATRIX_EXT + ".gz"; QStringList filelist = dir.entryList(filter, QDir::Files); if (filelist.size() > 0) { SetParametersDialogController spc; if (spc.exec() == QDialog::Accepted) { scoreSlider->setSliderPosition(spc.scoreSlider->sliderPosition()); int index = algorithmCombo->findText(spc.algorithmComboBox->currentText()); if (index == -1) index = 0; algorithmCombo->setCurrentIndex(index); } for (int i = 0, n = filelist.size(); i < n; i++) { loadFile(lod.dir + "/" + filelist[i]); addToQueue(); } } } void PWMSearchDialogController::runTask() { assert(task == NULL); if (model.getLength() != 0) { addToQueue(); } if (queue.size() == 0) { QMessageBox::information(this, L10N::warningTitle(), tr("Model not selected")); return; } U2Region reg; if (rbSequenceRange->isChecked()) { reg = ctx->getSequenceObject()->getSequenceRange(); } else if (rbSelectionRange->isChecked()) { reg = initialSelection; } else { reg.startPos = sbRangeStart->value(); reg.length = sbRangeEnd->value() - sbRangeStart->value() + 1; if (reg.length <= model.getLength()) { QMessageBox::critical(this, L10N::errorTitle(), tr("Range is too small")); sbRangeEnd->setFocus(); return; } } const char* seq = ctx->getSequenceData().constData() + reg.startPos; DNATranslation* complTT = rbBoth->isChecked() || rbComplement->isChecked() ? ctx->getComplementTT() : NULL; bool complOnly = rbComplement->isChecked(); for (int i = 0, n = queue.size(); i < n; i++) { queue[i].second.complTT = complTT; queue[i].second.complOnly = complOnly; } int len = reg.length; sl_onClearList(); task = new WeightMatrixSearchTask(queue, seq, len, reg.startPos); connect(task, SIGNAL(si_stateChanged()), SLOT(sl_onTaskFinished())); AppContext::getTaskScheduler()->registerTopLevelTask(task); updateState(); timer->start(400); } void PWMSearchDialogController::sl_onTaskFinished() { task = qobject_cast(sender()); if (!task->isFinished()) { return; } timer->stop(); importResults(); task = NULL; updateState(); } void PWMSearchDialogController::sl_onTimer() { importResults(); } void PWMSearchDialogController::importResults() { resultsTree->setSortingEnabled(false); QList newResults = task->takeResults(); foreach(const WeightMatrixSearchResult& r, newResults) { WeightMatrixResultItem* item = new WeightMatrixResultItem(r); resultsTree->addTopLevelItem(item); } updateStatus(); resultsTree->setSortingEnabled(true); } void PWMSearchDialogController::sl_onResultActivated(QTreeWidgetItem* i, int col) { Q_UNUSED(col); assert(i); WeightMatrixResultItem* item = static_cast(i); DNASequenceSelection* sel = ctx->getSequenceSelection(); sel->clear(); sel->addRegion(item->res.region); } void PWMSearchDialogController::loadFile(QString filename) { IOAdapterFactory* iof = AppContext::getIOAdapterRegistry()->getIOAdapterFactoryById(BaseIOAdapters::url2io(filename)); TaskStateInfo siPFM; PWMatrix m; intermediate = WeightMatrixIO::readPFMatrix(iof, filename, siPFM); if (siPFM.hasError()) { TaskStateInfo siPWM; m = WeightMatrixIO::readPWMatrix(iof, filename, siPWM); if (siPWM.hasError()) { QMessageBox::critical(this, L10N::errorTitle(), siPWM.getError()); return; } algorithmLabel->setEnabled(false); algorithmCombo->setEnabled(false); } else { algorithmLabel->setEnabled(true); algorithmCombo->setEnabled(true); PWMConversionAlgorithmFactory* factory = AppContext::getPWMConversionAlgorithmRegistry()->getAlgorithmFactory(algorithmCombo->currentText()); PWMConversionAlgorithm* algo = factory->createAlgorithm(); m = algo->convert(intermediate); if (m.getLength() == 0) { QMessageBox::critical(this, L10N::errorTitle(), tr("Zero length or corrupted model\nMaybe model data is not enough for selected algorithm")); } } updateModel(m); QFileInfo fi(filename); modelFileEdit->setText(fi.canonicalFilePath()); } ////////////////////////////////////////////////////////////////////////// /// tree WeightMatrixResultItem::WeightMatrixResultItem(const WeightMatrixSearchResult& r) : res(r) { setTextAlignment(0, Qt::AlignRight); setTextAlignment(1, Qt::AlignLeft); setTextAlignment(2, Qt::AlignRight); setTextAlignment(3, Qt::AlignRight); QString range = QString("%1..%2").arg(r.region.startPos + 1).arg(r.region.endPos()); setText(0, range); setText(1, r.modelInfo); QString strand = res.strand.isCompementary()? PWMSearchDialogController::tr("Complementary strand") : PWMSearchDialogController::tr("Direct strand") ; setText(2, strand); setText(3, QString::number(res.score, 'f', 2)+"%"); } WeightMatrixQueueItem::WeightMatrixQueueItem(const WeightMatrixSearchCfg& r) : res(r) { setTextAlignment(0, Qt::AlignLeft); setTextAlignment(1, Qt::AlignRight); setTextAlignment(2, Qt::AlignLeft); setText(0, r.modelName.split("/").last()); setText(1, QString::number(res.minPSUM)+"%"); setText(2, r.algo); } }//namespace ugene-1.9.8/src/plugins/weight_matrix/src/WeightMatrixIO.h0000644000175000017500000000646411651544324022260 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_WEIGHT_MATRIX_IO_H_ #define _U2_WEIGHT_MATRIX_IO_H_ #include #include #include #include #include namespace U2 { class IOAdapterFactory; class WeightMatrixIO : public QObject { Q_OBJECT public: //IDs for LastOpenDirHelper static const QString WEIGHT_MATRIX_ID; static const QString FREQUENCY_MATRIX_ID; //extensions for PFMatrix and PWMatrix files static const QString WEIGHT_MATRIX_EXT; static const QString FREQUENCY_MATRIX_EXT; static QString getAllMatrixFileFilter(bool includeAll = true); static QString getPFMFileFilter(bool includeAll = true); static QString getPWMFileFilter(bool includeAll = true); static PFMatrix readPFMatrix(IOAdapterFactory* iof, const QString& url, TaskStateInfo& si); static PWMatrix readPWMatrix(IOAdapterFactory* iof, const QString& url, TaskStateInfo& si); static void writePFMatrix(IOAdapterFactory* iof, const QString& url, TaskStateInfo& si, const PFMatrix& model); static void writePWMatrix(IOAdapterFactory* iof, const QString& url, TaskStateInfo& si, const PWMatrix& model); }; class PFMatrixReadTask: public Task { Q_OBJECT public: PFMatrixReadTask(const QString& url) : Task(tr("Read frequency matrix"), TaskFlag_None), url(url) {} void run(); PFMatrix getResult() const {return model;} QString getURL() const {return url;} private: QString url; PFMatrix model; }; class PWMatrixReadTask: public Task { Q_OBJECT public: PWMatrixReadTask(const QString& url) : Task(tr("Read weight matrix"), TaskFlag_None), url(url) {} void run(); PWMatrix getResult() const {return model;} QString getURL() const {return url;} private: QString url; PWMatrix model; }; class PFMatrixWriteTask : public Task { Q_OBJECT public: PFMatrixWriteTask(const QString& url, const PFMatrix& model, uint f = 0) : Task(tr("Save position frequency matrix"), TaskFlag_None), url(url), model(model), fileMode(f) {} virtual void run(); private: QString url; PFMatrix model; uint fileMode; }; class PWMatrixWriteTask : public Task { Q_OBJECT public: PWMatrixWriteTask(const QString& url, const PWMatrix& model, uint f = 0) : Task(tr("Save weight matrix"), TaskFlag_None), url(url), model(model), fileMode(f) {} virtual void run(); private: QString url; PWMatrix model; uint fileMode; }; }//namespace #endif ugene-1.9.8/src/plugins/weight_matrix/src/ui/0000755000175000017500000000000011651544324017646 5ustar ilyailyaugene-1.9.8/src/plugins/weight_matrix/src/ui/PWMSearchDialog.ui0000644000175000017500000003442511651544324023126 0ustar ilyailya PWMSearchDialog 0 0 546 556 Weight matrix search Matrix: true ... Minimal score Score: 100 85 Qt::Horizontal QSlider::TicksBelow 5 30 0 85% Search JASPAR database Build new matrix Qt::Horizontal 40 20 View matrix false Weight algorithm false 0 0 Strands Both strands true strand_direct_wit Direct strand false strand_complement_wit Complement strand Range Whole sequence true Qt::Horizontal 40 20 Selection range Qt::Horizontal 40 20 Custom range false 100 0 Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter true - false 100 0 Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter true 99 false true true Matrix Minimal score Algorithm Load list... Save list... Load folder... Clear list false true 4 Range Matrix Strand Score Clear results Save as annotations Qt::Horizontal 40 20 Status Qt::Horizontal 40 20 Add to queue Search Cancel rbCustomRange toggled(bool) sbRangeEnd setEnabled(bool) 240 156 464 156 rbCustomRange toggled(bool) sbRangeStart setEnabled(bool) 240 156 348 156 ugene-1.9.8/src/plugins/weight_matrix/src/ui/PWMBuildDialog.ui0000644000175000017500000001456511651544324022763 0ustar ilyailya PWMBuildDialog 0 0 489 359 Build weight or frequency matrix Input file ... Output file ... Statistic options Statistic type: Mononucleic true Dinucleic Matrix options Matrix type: Frequency matrix true Weight matrix false Weight algorithm false 0 0 0 0 Qt::Horizontal 40 20 Start Cancel cancelButton clicked() PWMBuildDialog reject() 395 142 222 82 weightButton toggled(bool) algorithmLabel setEnabled(bool) 395 96 94 149 weightButton toggled(bool) algorithmCombo setEnabled(bool) 395 96 320 149 ugene-1.9.8/src/plugins/weight_matrix/src/ui/ViewMatrixDialog.ui0000644000175000017500000000516011651544324023426 0ustar ilyailya ViewMatrixDialog 0 0 402 321 0 0 View matrix 0 0 Qt::LeftToRight 4 true true true 0 0 380 68 Qt::Horizontal 40 20 Close Qt::Horizontal 40 20 ugene-1.9.8/src/plugins/weight_matrix/src/ui/SetDefaultParametersDialog.ui0000644000175000017500000000576211651544324025423 0ustar ilyailya SetDefaultParametersDialog 0 0 466 102 Set default parameters QFormLayout::AllNonFixedFieldsGrow Weight algorithm Score: 0 100 85 Qt::Horizontal QSlider::TicksBelow 5 85% Qt::Horizontal 40 20 OK Qt::Horizontal 40 20 ugene-1.9.8/src/plugins/weight_matrix/src/ui/SearchJASPARDatabase.ui0000644000175000017500000000472311651544324023746 0ustar ilyailya SearchJASPARDatabase 0 0 488 415 Search JASPAR database true Name ID Class Family false 200 false false false 200 Qt::Horizontal 40 20 Select Cancel ugene-1.9.8/src/plugins/weight_matrix/src/SetParametersDialogController.cpp0000644000175000017500000000311011651544324025673 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "SetParametersDialogController.h" #include #include namespace U2 { SetParametersDialogController::SetParametersDialogController(QWidget *w) : QDialog(w) { setupUi(this); QStringList algo = AppContext::getPWMConversionAlgorithmRegistry()->getAlgorithmIds(); algorithmComboBox->addItems(algo); connect(okButton, SIGNAL(clicked()), SLOT(sl_onOkButton())); connect(scoreSlider, SIGNAL(valueChanged(int)), SLOT(sl_onSliderMoved(int))); } void SetParametersDialogController::sl_onSliderMoved(int value) { scoreValueLabel->setText(QString("%1%").arg(value)); } void SetParametersDialogController::sl_onOkButton() { QDialog::accept(); } }ugene-1.9.8/src/plugins/weight_matrix/src/WeightMatrixBuildWorker.cpp0000644000175000017500000003610211651544324024525 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "WeightMatrixWorkers.h" #include "WeightMatrixIOWorkers.h" #include "WeightMatrixPlugin.h" #include "PWMBuildDialogController.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include /* TRANSLATOR U2::WeightMatrixIO */ /* TRANSLATOR U2::LocalWorkflow::PWMatrixBuildWorker */ namespace U2 { namespace LocalWorkflow { static const QString ALG_ATTR("weight-algorithm"); static const QString TYPE_ATTR("matrix-type"); static const QString FMATRIX_OUT_PORT_ID("out-fmatrix"); static const QString FMATRIX_IN_PORT_ID("in-fmatrix"); static const QString WMATRIX_OUT_PORT_ID("out-wmatrix"); const QString PWMatrixBuildWorker::ACTOR_ID("wmatrix-build"); const QString PFMatrixBuildWorker::ACTOR_ID("fmatrix-build"); const QString PFMatrixConvertWorker::ACTOR_ID("fmatrix-to-wmatrix"); ////////////////////////////////////////////////////////////////////////// // PWMatrix build worker ////////////////////////////////////////////////////////////////////////// void PWMatrixBuildWorker::registerProto() { QList p; QList a; QMap m; Descriptor id(BasePorts::IN_MSA_PORT_ID(), PWMatrixBuildWorker::tr("Input alignment"), PWMatrixBuildWorker::tr("Input multiple sequence alignment for building statistical model.")); m[BaseSlots::MULTIPLE_ALIGNMENT_SLOT()] = BaseTypes::MULTIPLE_ALIGNMENT_TYPE(); DataTypePtr t(new MapDataType(Descriptor("build.pwmatrix.content"), m)); Descriptor od(WMATRIX_OUT_PORT_ID, PWMatrixBuildWorker::tr("Weight matrix"), PWMatrixBuildWorker::tr("Produced statistical model of specified TFBS data.")); p << new PortDescriptor(id, t, true /*input*/); QMap outM; outM[PWMatrixWorkerFactory::WMATRIX_SLOT] = PWMatrixWorkerFactory::WEIGHT_MATRIX_MODEL_TYPE(); p << new PortDescriptor(od, DataTypePtr(new MapDataType("wmatrix.build.out", outM)), false /*input*/, true /*multi*/); { Descriptor ad(ALG_ATTR, PWMatrixBuildWorker::tr("Weight algorithm"), QApplication::translate("PWMBuildDialog", "algo_tip", 0, QApplication::UnicodeUTF8)); a << new Attribute(ad, BaseTypes::STRING_TYPE(), true, BuiltInPWMConversionAlgorithms::BVH_ALGO); } { Descriptor td(TYPE_ATTR, PWMatrixBuildWorker::tr("Matrix type"), QApplication::translate("PWMBuildDialog", "type_tip", 0, QApplication::UnicodeUTF8)); a << new Attribute(td, BaseTypes::BOOL_TYPE(), true, false /* false = mononucleic, true = dinucleic */); } Descriptor desc(ACTOR_ID, tr("Build weight matrix"), tr("Builds weight matrix. Weight matrices are used for probabilistic recognition of transcription factor binding sites.")); ActorPrototype* proto = new IntegralBusActorPrototype(desc, p, a); QMap delegates; { QVariantMap modeMap; QStringList algo = AppContext::getPWMConversionAlgorithmRegistry()->getAlgorithmIds(); foreach (QString curr, algo) { modeMap[curr] = QVariant(curr); } delegates[ALG_ATTR] = new ComboBoxDelegate(modeMap); } { QVariantMap modeMap; modeMap[tr("Mononucleic")] = QVariant(false); modeMap[tr("Dinucleic")] = QVariant(true); delegates[TYPE_ATTR] = new ComboBoxDelegate(modeMap); } proto->setPrompter(new PWMatrixBuildPrompter()); proto->setEditor(new DelegateEditor(delegates)); proto->setIconPath(":weight_matrix/images/weight_matrix.png"); WorkflowEnv::getProtoRegistry()->registerProto(BaseActorCategories::CATEGORY_TRANSCRIPTION(), proto); } QString PWMatrixBuildPrompter::composeRichDoc() { IntegralBusPort* input = qobject_cast(target->getPort(BasePorts::IN_MSA_PORT_ID())); Actor* msaProducer = input->getProducer(BasePorts::IN_MSA_PORT_ID()); QString msaName = msaProducer ? tr("For each MSA from %1,").arg(msaProducer->getLabel()) : ""; QString doc = tr("%1 build weight matrix.") .arg(msaName); return doc; } void PWMatrixBuildWorker::init() { input = ports.value(BasePorts::IN_MSA_PORT_ID()); output = ports.value(WMATRIX_OUT_PORT_ID); } bool PWMatrixBuildWorker::isReady() { return (input && input->hasMessage()); } Task* PWMatrixBuildWorker::tick() { Message inputMessage = getMessageAndSetupScriptValues(input); mtype = PWMatrixWorkerFactory::WEIGHT_MATRIX_MODEL_TYPE(); QVariantMap data = inputMessage.getData().toMap(); cfg.algo = actor->getParameter(ALG_ATTR)->getAttributeValue(); cfg.type = actor->getParameter(TYPE_ATTR)->getAttributeValue() ? PM_DINUCLEOTIDE : PM_MONONUCLEOTIDE; const MAlignment& ma = data.value(BaseSlots::MULTIPLE_ALIGNMENT_SLOT().getId()).value(); Task* t = new PWMatrixBuildTask(cfg, ma); connect(t, SIGNAL(si_stateChanged()), SLOT(sl_taskFinished())); return t; } void PWMatrixBuildWorker::sl_taskFinished() { PWMatrixBuildTask* t = qobject_cast(sender()); if (t->getState() != Task::State_Finished) return; PWMatrix model = t->getResult(); QVariant v = qVariantFromValue(model); output->put(Message(mtype, v)); if (input->isEnded()) { output->setEnded(); } } bool PWMatrixBuildWorker::isDone() { return !input || input->isEnded(); } ////////////////////////////////////////////////////////////////////////// // PFMatrix build worker ////////////////////////////////////////////////////////////////////////// void PFMatrixBuildWorker::registerProto() { QList p; QList a; QMap m; Descriptor id(BasePorts::IN_MSA_PORT_ID(), PFMatrixBuildWorker::tr("Input alignment"), PFMatrixBuildWorker::tr("Input multiple sequence alignment for building statistical model.")); m[BaseSlots::MULTIPLE_ALIGNMENT_SLOT()] = BaseTypes::MULTIPLE_ALIGNMENT_TYPE(); DataTypePtr t(new MapDataType(Descriptor("build.pfmatrix.content"), m)); Descriptor od(FMATRIX_OUT_PORT_ID, PFMatrixBuildWorker::tr("Frequency matrix"), PFMatrixBuildWorker::tr("Produced statistical model of specified TFBS data.")); p << new PortDescriptor(id, t, true /*input*/); QMap outM; outM[PFMatrixWorkerFactory::FMATRIX_SLOT] = PFMatrixWorkerFactory::FREQUENCY_MATRIX_MODEL_TYPE(); p << new PortDescriptor(od, DataTypePtr(new MapDataType("fmatrix.build.out", outM)), false /*input*/, true /*multi*/); { Descriptor td(TYPE_ATTR, PWMatrixBuildWorker::tr("Matrix type"), QApplication::translate("PWMBuildDialog", "type_tip", 0, QApplication::UnicodeUTF8)); a << new Attribute(td, BaseTypes::BOOL_TYPE(), true, false /* false = mononucleic, true = dinucleic */); } Descriptor desc(ACTOR_ID, tr("Build frequency matrix"), tr("Builds frequency matrix. Frequency matrices are used for probabilistic recognition of transcription factor binding sites.")); ActorPrototype* proto = new IntegralBusActorPrototype(desc, p, a); QMap delegates; { QVariantMap modeMap; modeMap[tr("Mononucleic")] = QVariant(false); modeMap[tr("Dinucleic")] = QVariant(true); delegates[TYPE_ATTR] = new ComboBoxDelegate(modeMap); } proto->setPrompter(new PFMatrixBuildPrompter()); proto->setEditor(new DelegateEditor(delegates)); proto->setIconPath(":weight_matrix/images/weight_matrix.png"); WorkflowEnv::getProtoRegistry()->registerProto(BaseActorCategories::CATEGORY_TRANSCRIPTION(), proto); } QString PFMatrixBuildPrompter::composeRichDoc() { IntegralBusPort* input = qobject_cast(target->getPort(BasePorts::IN_MSA_PORT_ID())); Actor* msaProducer = input->getProducer(BasePorts::IN_MSA_PORT_ID()); QString msaName = msaProducer ? tr("For each MSA from %1,").arg(msaProducer->getLabel()) : ""; QString doc = tr("%1 build frequency matrix.") .arg(msaName); return doc; } void PFMatrixBuildWorker::init() { input = ports.value(BasePorts::IN_MSA_PORT_ID()); output = ports.value(FMATRIX_OUT_PORT_ID); } bool PFMatrixBuildWorker::isReady() { return (input && input->hasMessage()); } Task* PFMatrixBuildWorker::tick() { Message inputMessage = getMessageAndSetupScriptValues(input); mtype = PFMatrixWorkerFactory::FREQUENCY_MATRIX_MODEL_TYPE(); QVariantMap data = inputMessage.getData().toMap(); cfg.type = actor->getParameter(TYPE_ATTR)->getAttributeValue() ? PM_DINUCLEOTIDE : PM_MONONUCLEOTIDE; const MAlignment& ma = data.value(BaseSlots::MULTIPLE_ALIGNMENT_SLOT().getId()).value(); Task* t = new PFMatrixBuildTask(cfg, ma); connect(t, SIGNAL(si_stateChanged()), SLOT(sl_taskFinished())); return t; } void PFMatrixBuildWorker::sl_taskFinished() { PFMatrixBuildTask* t = qobject_cast(sender()); if (t->getState() != Task::State_Finished) return; PFMatrix model = t->getResult(); QVariant v = qVariantFromValue(model); output->put(Message(mtype, v)); if (input->isEnded()) { output->setEnded(); } } bool PFMatrixBuildWorker::isDone() { return !input || input->isEnded(); } ////////////////////////////////////////////////////////////////////////// // PFMatrix convert worker ////////////////////////////////////////////////////////////////////////// void PFMatrixConvertWorker::registerProto() { QList p; QList a; QMap m; Descriptor id(FMATRIX_IN_PORT_ID, PFMatrixConvertWorker::tr("Frequency matrix"), PFMatrixConvertWorker::tr("Frequency matrix to convert.")); m[PFMatrixWorkerFactory::FMATRIX_SLOT] = PFMatrixWorkerFactory::FREQUENCY_MATRIX_MODEL_TYPE(); DataTypePtr t(new MapDataType(Descriptor("convert.pfmatrix.content"), m)); Descriptor od(WMATRIX_OUT_PORT_ID, PFMatrixConvertWorker::tr("Weight matrix"), PFMatrixConvertWorker::tr("Produced statistical model of specified TFBS data.")); p << new PortDescriptor(id, t, true /*input*/); QMap outM; outM[PWMatrixWorkerFactory::WMATRIX_SLOT] = PWMatrixWorkerFactory::WEIGHT_MATRIX_MODEL_TYPE(); p << new PortDescriptor(od, DataTypePtr(new MapDataType("fmatrix.convert.out", outM)), false /*input*/, true /*multi*/); { Descriptor ad(ALG_ATTR, PWMatrixBuildWorker::tr("Weight algorithm"), QApplication::translate("PWMBuildDialog", "algo_tip", 0, QApplication::UnicodeUTF8)); a << new Attribute(ad, BaseTypes::STRING_TYPE(), true, BuiltInPWMConversionAlgorithms::BVH_ALGO); } { Descriptor td(TYPE_ATTR, PWMatrixBuildWorker::tr("Matrix type"), QApplication::translate("PWMBuildDialog", "type_tip", 0, QApplication::UnicodeUTF8)); a << new Attribute(td, BaseTypes::BOOL_TYPE(), true, false /* false = mononucleic, true = dinucleic */); } Descriptor desc(ACTOR_ID, tr("Convert frequency matrix"), tr("Converts frequency matrix to weight matrix. Weight matrices are used for probabilistic recognition of transcription factor binding sites.")); ActorPrototype* proto = new IntegralBusActorPrototype(desc, p, a); QMap delegates; { QVariantMap modeMap; QStringList algo = AppContext::getPWMConversionAlgorithmRegistry()->getAlgorithmIds(); foreach (QString curr, algo) { modeMap[curr] = QVariant(curr); } delegates[ALG_ATTR] = new ComboBoxDelegate(modeMap); } { QVariantMap modeMap; modeMap[tr("Mononucleic")] = QVariant(false); modeMap[tr("Dinucleic")] = QVariant(true); delegates[TYPE_ATTR] = new ComboBoxDelegate(modeMap); } proto->setPrompter(new PFMatrixConvertPrompter()); proto->setEditor(new DelegateEditor(delegates)); proto->setIconPath(":weight_matrix/images/weight_matrix.png"); WorkflowEnv::getProtoRegistry()->registerProto(BaseActorCategories::CATEGORY_TRANSCRIPTION(), proto); } QString PFMatrixConvertPrompter::composeRichDoc() { IntegralBusPort* input = qobject_cast(target->getPort(FMATRIX_IN_PORT_ID)); Actor* msaProducer = input->getProducer(FMATRIX_IN_PORT_ID); QString msaName = msaProducer ? tr("For each frequency matrix from %1,").arg(msaProducer->getLabel()) : ""; QString doc = tr("%1 build weight matrix.") .arg(msaName); return doc; } void PFMatrixConvertWorker::init() { input = ports.value(FMATRIX_IN_PORT_ID); output = ports.value(WMATRIX_OUT_PORT_ID); } bool PFMatrixConvertWorker::isReady() { return (input && input->hasMessage()); } Task* PFMatrixConvertWorker::tick() { Message inputMessage = getMessageAndSetupScriptValues(input); mtype = PFMatrixWorkerFactory::FREQUENCY_MATRIX_MODEL_TYPE(); QVariantMap data = inputMessage.getData().toMap(); PWMatrix model = data.value(PWMatrixWorkerFactory::WEIGHT_MATRIX_MODEL_TYPE_ID).value(); QString url = data.value(BaseSlots::URL_SLOT().getId()).toString(); cfg.algo = actor->getParameter(ALG_ATTR)->getAttributeValue(); cfg.type = actor->getParameter(TYPE_ATTR)->getAttributeValue() ? PM_DINUCLEOTIDE : PM_MONONUCLEOTIDE; const PFMatrix& ma = data.value(PFMatrixWorkerFactory::FMATRIX_SLOT.getId()).value(); Task* t = new PWMatrixBuildTask(cfg, ma); connect(t, SIGNAL(si_stateChanged()), SLOT(sl_taskFinished())); return t; } void PFMatrixConvertWorker::sl_taskFinished() { PWMatrixBuildTask* t = qobject_cast(sender()); if (t->getState() != Task::State_Finished) return; PWMatrix model = t->getResult(); QVariant v = qVariantFromValue(model); output->put(Message(mtype, v)); if (input->isEnded()) { output->setEnded(); } } bool PFMatrixConvertWorker::isDone() { return !input || input->isEnded(); } } //namespace LocalWorkflow } //namespace U2 ugene-1.9.8/src/plugins/weight_matrix/src/WeightMatrixSearchTask.cpp0000644000175000017500000001055311651544324024326 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include #include "WeightMatrixSearchTask.h" namespace U2 { //Weight matrix multiple search WeightMatrixSearchTask::WeightMatrixSearchTask(const QList > &m, const char *s, int l, int ro) : Task(tr("Weight matrix multiple search"), TaskFlags_NR_FOSCOE), models(m), resultsOffset(ro) { for (int i = 0, n = m.size(); i < n; i++) { addSubTask(new WeightMatrixSingleSearchTask(m[i].first, s, l, m[i].second, ro)); } } void WeightMatrixSearchTask::addResult(const WeightMatrixSearchResult& r) { lock.lock(); results.append(r); lock.unlock(); } QList WeightMatrixSearchTask::takeResults() { lock.lock(); QList res; QList sub = getSubtasks(); foreach (Task* task, sub) { WeightMatrixSingleSearchTask* curr = static_cast(task); res.append(curr->takeResults()); } lock.unlock(); return res; } //Weight matrix single search WeightMatrixSingleSearchTask::WeightMatrixSingleSearchTask(const PWMatrix& m, const char* s, int l, const WeightMatrixSearchCfg& cfg, int ro) : Task(tr("Weight matrix search"), TaskFlags_NR_FOSCOE), model(m), cfg(cfg), resultsOffset(ro) { GCOUNTER( cvar, tvar, "WeightMatrixSingleSearchTask" ); SequenceWalkerConfig c; c.seq = s; c.seqSize = l; c.complTrans = cfg.complTT; c.strandToWalk = cfg.complTT == NULL ? StrandOption_DirectOnly : StrandOption_Both; c.aminoTrans = NULL; c.chunkSize = l; c.overlapSize = 0; SequenceWalkerTask* t = new SequenceWalkerTask(c, this, tr("Weight matrix search parallel")); addSubTask(t); } void WeightMatrixSingleSearchTask::onRegion(SequenceWalkerSubtask* t, TaskStateInfo& ti) { //TODO: process border case as if there are 'N' chars before 0 and after seqlen if (cfg.complOnly && !t->isDNAComplemented()) { return; } U2Region globalRegion = t->getGlobalRegion(); int seqLen = globalRegion.length; const char* seq = t->getGlobalConfig().seq + globalRegion.startPos;; int modelSize = model.getLength(); ti.progress =0; int lenPerPercent = seqLen / 100; int pLeft = lenPerPercent; DNATranslation* complTT = t->isDNAComplemented() ? t->getGlobalConfig().complTrans : NULL; for (int i = 0, n = seqLen - modelSize; i <= n && !ti.cancelFlag; i++, --pLeft) { float psum = WeightMatrixAlgorithm::getScore(seq + i, modelSize, model, complTT); if (psum < -1e-6 || psum > 1 + 1e-6) { ti.setError( tr("Internal error invalid psum: %1").arg(psum) ); return; } WeightMatrixSearchResult r; r.score = 100*psum; if (r.score >= cfg.minPSUM) {//report result r.strand = t->isDNAComplemented() ? U2Strand::Complementary : U2Strand::Direct; r.region.startPos = globalRegion.startPos + i + resultsOffset; r.region.length = modelSize; r.qual = model.getProperties(); r.modelInfo = cfg.modelName.split("/").last(); addResult(r); } if (pLeft == 0) { ti.progress++; pLeft = lenPerPercent; } } } void WeightMatrixSingleSearchTask::addResult(const WeightMatrixSearchResult& r) { lock.lock(); results.append(r); lock.unlock(); } QList WeightMatrixSingleSearchTask::takeResults() { lock.lock(); QList res = results; results.clear(); lock.unlock(); return res; } }//namespace ugene-1.9.8/src/plugins/weight_matrix/src/WeightMatrixWorkers.h0000644000175000017500000001176211651544324023402 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_WEIGHT_MATRIX_WORKER_H_ #define _U2_WEIGHT_MATRIX_WORKER_H_ #include #include #include "WeightMatrixAlgorithm.h" #include "WeightMatrixSearchTask.h" namespace U2 { namespace LocalWorkflow { class PWMatrixBuildPrompter : public PrompterBase { Q_OBJECT public: PWMatrixBuildPrompter(Actor* p = 0) : PrompterBase(p) {} protected: QString composeRichDoc(); }; class PFMatrixBuildPrompter : public PrompterBase { Q_OBJECT public: PFMatrixBuildPrompter(Actor* p = 0) : PrompterBase(p) {} protected: QString composeRichDoc(); }; class PWMatrixSearchPrompter : public PrompterBase { Q_OBJECT public: PWMatrixSearchPrompter(Actor* p = 0) : PrompterBase(p) {} protected: QString composeRichDoc(); }; class PWMatrixBuildWorker : public BaseWorker { Q_OBJECT public: static const QString ACTOR_ID; static void registerProto(); PWMatrixBuildWorker(Actor* a) : BaseWorker(a), input(NULL), output(NULL) {} virtual void init() ; virtual bool isReady(); virtual Task* tick() ; virtual bool isDone() ; virtual void cleanup() {} private slots: void sl_taskFinished(); protected: CommunicationChannel *input, *output; PMBuildSettings cfg; DataTypePtr mtype; }; class PFMatrixBuildWorker : public BaseWorker { Q_OBJECT public: static const QString ACTOR_ID; static void registerProto(); PFMatrixBuildWorker(Actor* a) : BaseWorker(a), input(NULL), output(NULL) {} virtual void init() ; virtual bool isReady(); virtual Task* tick() ; virtual bool isDone() ; virtual void cleanup() {} private slots: void sl_taskFinished(); protected: CommunicationChannel *input, *output; PMBuildSettings cfg; DataTypePtr mtype; }; class PFMatrixConvertPrompter : public PrompterBase { Q_OBJECT public: PFMatrixConvertPrompter(Actor* p = 0) : PrompterBase(p) {} protected: QString composeRichDoc(); }; class PFMatrixConvertWorker : public BaseWorker { Q_OBJECT public: static const QString ACTOR_ID; static void registerProto(); PFMatrixConvertWorker(Actor* a) : BaseWorker(a), input(NULL), output(NULL) {} virtual void init() ; virtual bool isReady(); virtual Task* tick() ; virtual bool isDone() ; virtual void cleanup() {} private slots: void sl_taskFinished(); protected: CommunicationChannel *input, *output; PMBuildSettings cfg; DataTypePtr mtype; }; class PWMatrixSearchWorker : public BaseWorker { Q_OBJECT public: static const QString ACTOR_ID; static void registerProto(); PWMatrixSearchWorker(Actor* a) : BaseWorker(a, false), modelPort(NULL), dataPort(NULL), output(NULL), strand(0) {} virtual void init() ; virtual bool isReady(); virtual Task* tick() ; virtual bool isDone() ; virtual void cleanup() {} private slots: void sl_taskFinished(Task*); protected: IntegralBus *modelPort, *dataPort, *output; QString resultName; QList models; int strand; WeightMatrixSearchCfg cfg; }; class PWMatrixWorkerFactory : public DomainFactory { public: static const Descriptor WEIGHT_MATRIX_CATEGORY(); static const QString WEIGHT_MATRIX_MODEL_TYPE_ID; static DataTypePtr const WEIGHT_MATRIX_MODEL_TYPE(); static const Descriptor WMATRIX_SLOT; static void init(); PWMatrixWorkerFactory(const Descriptor& d) : DomainFactory(d) {} virtual Worker* createWorker(Actor* a); }; class PFMatrixWorkerFactory : public DomainFactory { public: static const Descriptor FREQUENCY_MATRIX_CATEGORY(); static const QString FREQUENCY_MATRIX_MODEL_TYPE_ID; static DataTypePtr const FREQUENCY_MATRIX_MODEL_TYPE(); static const Descriptor FMATRIX_SLOT; static void init(); PFMatrixWorkerFactory(const Descriptor& d) : DomainFactory(d) {} virtual Worker* createWorker(Actor* a); }; } // Workflow namespace } // U2 namespace #endif ugene-1.9.8/src/plugins/weight_matrix/src/PWMBuildDialogController.h0000644000175000017500000000662111651544324024216 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_WEIGHT_MATRIX_BUILD_DIALOG_CONTROLLER_H_ #define _U2_WEIGHT_MATRIX_BUILD_DIALOG_CONTROLLER_H_ #include #include "WeightMatrixPlugin.h" #include "WeightMatrixAlgorithm.h" #include #include #include #include #include #include #include #include namespace U2 { class LoadDocumentTask; class PWMBuildSettings; class PWMModel; class PWMBuildDialogController : public QDialog, public Ui_PWMBuildDialog { Q_OBJECT public: PWMBuildDialogController(QWidget* w = NULL); QString lastURL; public slots: virtual void reject(); private slots: void sl_inFileButtonClicked(); void sl_outFileButtonClicked(); void sl_okButtonClicked(); void sl_matrixTypeChanged(bool); void sl_onStateChanged(); void sl_onProgressChanged(); private: Task* task; AlignmentLogoRenderArea* logoArea; void replaceLogo(const MAlignment& ma); }; class PFMatrixBuildTask : public Task { Q_OBJECT public: PFMatrixBuildTask(const PMBuildSettings& s, const MAlignment& ma); void run(); PFMatrix getResult() const {return m;} private: PMBuildSettings settings; MAlignment ma; PFMatrix m; }; class PFMatrixBuildToFileTask : public Task { Q_OBJECT public: PFMatrixBuildToFileTask(const QString& inFile, const QString& outFile, const PMBuildSettings& s); virtual QList onSubTaskFinished(Task* subTask); private: LoadDocumentTask* loadTask; PFMatrixBuildTask* buildTask; QString outFile; PMBuildSettings settings; }; class PWMatrixBuildTask : public Task { Q_OBJECT public: PWMatrixBuildTask(const PMBuildSettings& s, const MAlignment& ma); PWMatrixBuildTask(const PMBuildSettings& s, const PFMatrix& m); void run(); PWMatrix getResult() const {return m;} private: PMBuildSettings settings; MAlignment ma; PFMatrix tempMatrix; PWMatrix m; }; class PWMatrixBuildToFileTask : public Task { Q_OBJECT public: PWMatrixBuildToFileTask(const QString& inFile, const QString& outFile, const PMBuildSettings& s); virtual QList onSubTaskFinished(Task* subTask); private: LoadDocumentTask* loadTask; PWMatrixBuildTask* buildTask; QString outFile; PMBuildSettings settings; }; } //namespace #endif ugene-1.9.8/src/plugins/weight_matrix/src/WeightMatrixPlugin.h0000644000175000017500000000320411651544324023174 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_WEIGHTMATRIX_PLUGIN_H_ #define _U2_WEIGHTMATRIX_PLUGIN_H_ #include #include #include namespace U2 { class WeightMatrixADVContext; class XMLTestFactory; class WeightMatrixPlugin : public Plugin { Q_OBJECT public: WeightMatrixPlugin(); ~WeightMatrixPlugin(); protected slots: void sl_build(); private: WeightMatrixADVContext* ctxADV; }; class WeightMatrixADVContext: public GObjectViewWindowContext { Q_OBJECT public: WeightMatrixADVContext(QObject* p); protected slots: void sl_search(); protected: virtual void initViewContext(GObjectView* view); }; class WeightMatrixAlgorithmTests { public: static QList createTestFactories(); }; } //namespace #endif ugene-1.9.8/src/plugins/weight_matrix/src/WeightMatrixPlugin.cpp0000644000175000017500000000766211651544324023543 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "WeightMatrixPlugin.h" #include "WeightMatrixIO.h" #include "WeightMatrixWorkers.h" #include "PWMBuildDialogController.h" #include "PWMSearchDialogController.h" #include "WMQuery.h" #include #include #include #include #include #include #include #include #include #include namespace U2 { extern "C" Q_DECL_EXPORT Plugin* U2_PLUGIN_INIT_FUNC() { WeightMatrixPlugin* plug = new WeightMatrixPlugin(); return plug; } WeightMatrixPlugin::WeightMatrixPlugin() : Plugin(tr("Weight matrix"), tr("Search for TFBS with weight matrices")) { if (AppContext::getMainWindow()) { ctxADV = new WeightMatrixADVContext(this); ctxADV->init(); QAction* buildAction = new QAction(tr("Build weight matrix"), this); connect(buildAction, SIGNAL(triggered()), SLOT(sl_build())); QMenu* tools = AppContext::getMainWindow()->getTopLevelMenu(MWMENU_TOOLS); QMenu* toolsSubmenu = tools->addMenu(QIcon(":/weight_matrix/images/weight_matrix.png"), tr("Weight matrix")); toolsSubmenu->addAction(buildAction); } LocalWorkflow::PWMatrixWorkerFactory::init(); LocalWorkflow::PFMatrixWorkerFactory::init(); QString defaultDir = QDir::searchPaths( PATH_PREFIX_DATA ).first() + "/position_weight_matrix"; if (DialogUtils::getLastOpenFileDir(WeightMatrixIO::WEIGHT_MATRIX_ID).isEmpty()) { DialogUtils::setLastOpenFileDir(defaultDir, WeightMatrixIO::WEIGHT_MATRIX_ID); } if (DialogUtils::getLastOpenFileDir(WeightMatrixIO::FREQUENCY_MATRIX_ID).isEmpty()) { DialogUtils::setLastOpenFileDir(defaultDir, WeightMatrixIO::FREQUENCY_MATRIX_ID); } QDActorPrototypeRegistry* qdpr = AppContext::getQDActorProtoRegistry(); qdpr->registerProto(new QDWMActorPrototype); } WeightMatrixPlugin::~WeightMatrixPlugin() { } void WeightMatrixPlugin::sl_build() { QWidget *p = (QWidget*)(AppContext::getMainWindow()->getQMainWindow()); PWMBuildDialogController d(p); d.exec(); } WeightMatrixADVContext::WeightMatrixADVContext(QObject* p) : GObjectViewWindowContext(p, ANNOTATED_DNA_VIEW_FACTORY_ID) { } void WeightMatrixADVContext::initViewContext(GObjectView* view) { AnnotatedDNAView* av = qobject_cast(view); ADVGlobalAction* a = new ADVGlobalAction(av, QIcon(":weight_matrix/images/weight_matrix.png"), tr("Search TFBS with matrices..."), 80); a->addAlphabetFilter(DNAAlphabet_NUCL); connect(a, SIGNAL(triggered()), SLOT(sl_search())); } void WeightMatrixADVContext::sl_search() { GObjectViewAction* action = qobject_cast(sender()); AnnotatedDNAView* av = qobject_cast(action->getObjectView()); ADVSequenceObjectContext* seqCtx = av->getSequenceInFocus(); assert(seqCtx->getAlphabet()->isNucleic()); PWMSearchDialogController d(seqCtx, av->getWidget()); d.exec(); } }//namespace ugene-1.9.8/src/plugins/weight_matrix/src/WeightMatrixIOWorkers.cpp0000644000175000017500000005362711651544324024173 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "WeightMatrixIOWorkers.h" #include "WeightMatrixWorkers.h" #include "WeightMatrixIO.h" #include "PWMSearchDialogController.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include /* TRANSLATOR U2::WeightMatrixIO */ namespace U2 { namespace LocalWorkflow { const QString PWMatrixReader::ACTOR_ID("wmatrix-read"); const QString PWMatrixWriter::ACTOR_ID("wmatrix-write"); const QString PFMatrixReader::ACTOR_ID("fmatrix-read"); const QString PFMatrixWriter::ACTOR_ID("fmatrix-write"); static const QString FMATRIX_OUT_PORT_ID("out-fmatrix"); // FIXME: redifinition static const QString FMATRIX_IN_PORT_ID("in-fmatrix"); // FIXME: redifinition static const QString WMATRIX_OUT_PORT_ID("out-wmatrix"); // FIXME: redifinition static const QString WMATRIX_IN_PORT_ID("in-wmatrix"); // FIXME: redifinition const QString PWMatrixWorkerFactory::WEIGHT_MATRIX_MODEL_TYPE_ID("pwmatrix.model"); const QString PFMatrixWorkerFactory::FREQUENCY_MATRIX_MODEL_TYPE_ID("pfmatrix.model"); DataTypePtr const PWMatrixWorkerFactory::WEIGHT_MATRIX_MODEL_TYPE() { DataTypeRegistry* dtr = WorkflowEnv::getDataTypeRegistry(); assert(dtr); static bool startup = true; if (startup) { dtr->registerEntry(DataTypePtr(new DataType(WEIGHT_MATRIX_MODEL_TYPE_ID, WeightMatrixIO::tr("Weight matrix"), ""))); startup = false; } return dtr->getById(WEIGHT_MATRIX_MODEL_TYPE_ID); } const Descriptor PWMatrixWorkerFactory::WMATRIX_SLOT("wmatrix", WeightMatrixIO::tr("Weight matrix"), ""); const Descriptor PWMatrixWorkerFactory::WEIGHT_MATRIX_CATEGORY() {return Descriptor("hweightmatrix", WeightMatrixIO::tr("Weight matrix"), "");} PWMatrixIOProto::PWMatrixIOProto(const Descriptor& _desc, const QList& _ports, const QList& _attrs ) : IntegralBusActorPrototype(_desc, _ports, _attrs) { } bool PWMatrixIOProto::isAcceptableDrop(const QMimeData * md, QVariantMap * params, const QString & urlAttrId ) const { if (md->hasUrls()) { QList urls = md->urls(); if (urls.size() == 1) { QString url = urls.at(0).toLocalFile(); QString ext = GUrlUtils::getUncompressedExtension(GUrl(url, GUrl_File)); if (WeightMatrixIO::WEIGHT_MATRIX_EXT == ext) { if (params) { params->insert(urlAttrId, url); } return true; } } } return false; } ReadPWMatrixProto::ReadPWMatrixProto(const Descriptor& _desc, const QList& _ports, const QList& _attrs ) : PWMatrixIOProto( _desc, _ports, _attrs ) { attrs << new Attribute(BaseAttributes::URL_IN_ATTRIBUTE(), BaseTypes::STRING_TYPE(), true); QMap delegateMap; delegateMap[BaseAttributes::URL_IN_ATTRIBUTE().getId()] = new URLDelegate(WeightMatrixIO::getPWMFileFilter(), WeightMatrixIO::WEIGHT_MATRIX_ID, true); setEditor(new DelegateEditor(delegateMap)); setIconPath(":weight_matrix/images/weight_matrix.png"); } bool ReadPWMatrixProto::isAcceptableDrop(const QMimeData * md, QVariantMap * params ) const { return PWMatrixIOProto::isAcceptableDrop( md, params, BaseAttributes::URL_IN_ATTRIBUTE().getId() ); } WritePWMatrixProto::WritePWMatrixProto(const Descriptor& _desc, const QList& _ports, const QList& _attrs ) : PWMatrixIOProto( _desc, _ports, _attrs ) { attrs << new Attribute(BaseAttributes::URL_OUT_ATTRIBUTE(), BaseTypes::STRING_TYPE(), true ); attrs << new Attribute(BaseAttributes::FILE_MODE_ATTRIBUTE(), BaseTypes::NUM_TYPE(), false, SaveDoc_Roll); QMap delegateMap; delegateMap[BaseAttributes::URL_OUT_ATTRIBUTE().getId()] = new URLDelegate(WeightMatrixIO::getPWMFileFilter(), WeightMatrixIO::WEIGHT_MATRIX_ID, false ); delegateMap[BaseAttributes::FILE_MODE_ATTRIBUTE().getId()] = new FileModeDelegate(false); setEditor(new DelegateEditor(delegateMap)); setIconPath(":weight_matrix/images/weight_matrix.png"); setValidator(new ScreenedParamValidator(BaseAttributes::URL_OUT_ATTRIBUTE().getId(), ports.first()->getId(), BaseSlots::URL_SLOT().getId())); setPortValidator(WMATRIX_IN_PORT_ID, new ScreenedSlotValidator(BaseSlots::URL_SLOT().getId())); } bool WritePWMatrixProto::isAcceptableDrop(const QMimeData * md, QVariantMap * params ) const { return PWMatrixIOProto::isAcceptableDrop( md, params, BaseAttributes::URL_OUT_ATTRIBUTE().getId() ); } void PWMatrixWorkerFactory::init() { ActorPrototypeRegistry* r = WorkflowEnv::getProtoRegistry(); assert(r); { QMap m; Descriptor sd(BaseSlots::URL_SLOT().getId(), WeightMatrixIO::tr("Location"), WeightMatrixIO::tr("Location hint for the target file.")); m[BaseSlots::URL_SLOT()] = BaseTypes::STRING_TYPE(); m[WMATRIX_SLOT] = WEIGHT_MATRIX_MODEL_TYPE(); DataTypePtr t(new MapDataType(Descriptor("write.pwmatrix.content"), m)); QList p; QList a; Descriptor pd(WMATRIX_IN_PORT_ID, WeightMatrixIO::tr("Weight matrix"), WeightMatrixIO::tr("Input weight matrix")); p << new PortDescriptor(pd, t, true /*input*/); Descriptor desc(PWMatrixWriter::ACTOR_ID, WeightMatrixIO::tr("Write weight matrix"), WeightMatrixIO::tr("Saves all input weight matrices to specified location.")); IntegralBusActorPrototype* proto = new WritePWMatrixProto(desc, p, a); proto->setPrompter(new PWMatrixWritePrompter()); r->registerProto(BaseActorCategories::CATEGORY_TRANSCRIPTION(), proto); } { QList p; QList a; Descriptor pd(WMATRIX_OUT_PORT_ID, WeightMatrixIO::tr("Weight matrix"), WeightMatrixIO::tr("Loaded weight matrices data.")); QMap outM; outM[WMATRIX_SLOT] = WEIGHT_MATRIX_MODEL_TYPE(); p << new PortDescriptor(pd, DataTypePtr(new MapDataType("wmatrix.read.out", outM)), false /*input*/, true /*multi*/); Descriptor desc(PWMatrixReader::ACTOR_ID, WeightMatrixIO::tr("Read weight matrix"), WeightMatrixIO::tr("Reads weight matrices from file(s). The files can be local or Internet URLs.")); IntegralBusActorPrototype* proto = new ReadPWMatrixProto(desc, p, a); proto->setPrompter(new PWMatrixReadPrompter()); r->registerProto(BaseActorCategories::CATEGORY_TRANSCRIPTION(), proto); } PWMatrixBuildWorker::registerProto(); PWMatrixSearchWorker::registerProto(); DomainFactory* localDomain = WorkflowEnv::getDomainRegistry()->getById(LocalDomainFactory::ID); localDomain->registerEntry(new PWMatrixWorkerFactory(PWMatrixReader::ACTOR_ID)); localDomain->registerEntry(new PWMatrixWorkerFactory(PWMatrixWriter::ACTOR_ID)); localDomain->registerEntry(new PWMatrixWorkerFactory(PWMatrixSearchWorker::ACTOR_ID)); localDomain->registerEntry(new PWMatrixWorkerFactory(PWMatrixBuildWorker::ACTOR_ID)); } Worker* PWMatrixWorkerFactory::createWorker(Actor* a) { BaseWorker* w = NULL; if (PWMatrixReader::ACTOR_ID == a->getProto()->getId()) { w = new PWMatrixReader(a); } else if (PWMatrixWriter::ACTOR_ID == a->getProto()->getId()) { w = new PWMatrixWriter(a); } else if (PWMatrixBuildWorker::ACTOR_ID == a->getProto()->getId()) { w = new PWMatrixBuildWorker(a); } else if (PWMatrixSearchWorker::ACTOR_ID == a->getProto()->getId()) { w = new PWMatrixSearchWorker(a); } return w; } QString PWMatrixReadPrompter::composeRichDoc() { return tr("Read model(s) from %1").arg(getHyperlink(BaseAttributes::URL_IN_ATTRIBUTE().getId(), getURL(BaseAttributes::URL_IN_ATTRIBUTE().getId()))); } QString PWMatrixWritePrompter::composeRichDoc() { IntegralBusPort* input = qobject_cast(target->getPort(WMATRIX_IN_PORT_ID)); Actor* producer = input->getProducer(PWMatrixWorkerFactory::WEIGHT_MATRIX_MODEL_TYPE_ID); QString from = producer ? producer->getLabel() : ""+tr("unset")+""; QString url = getScreenedURL(input, BaseAttributes::URL_OUT_ATTRIBUTE().getId(), BaseSlots::URL_SLOT().getId()); url = getHyperlink(BaseAttributes::URL_OUT_ATTRIBUTE().getId(), url); QString doc = tr("Save the profile(s) from %1 to %2.") .arg(from) .arg(url); return doc; } void PWMatrixReader::init() { output = ports.value(WMATRIX_OUT_PORT_ID); urls = WorkflowUtils::expandToUrls(actor->getParameter(BaseAttributes::URL_IN_ATTRIBUTE().getId())->getAttributeValue()); mtype = PWMatrixWorkerFactory::WEIGHT_MATRIX_MODEL_TYPE(); } Task* PWMatrixReader::tick() { Task* t = new PWMatrixReadTask(urls.takeFirst()); connect(t, SIGNAL(si_stateChanged()), SLOT(sl_taskFinished())); tasks.append(t); return t; } void PWMatrixReader::sl_taskFinished() { PWMatrixReadTask* t = qobject_cast(sender()); if (t->getState() != Task::State_Finished) return; tasks.removeAll(t); if (output) { if (!t->hasError()) { QVariant v = qVariantFromValue(t->getResult()); output->put(Message(mtype, v)); } if (urls.isEmpty() && tasks.isEmpty()) { output->setEnded(); } ioLog.info(tr("Loaded weight matrix from %1").arg(t->getURL())); } } void PWMatrixWriter::init() { input = ports.value(WMATRIX_IN_PORT_ID); } Task* PWMatrixWriter::tick() { Message inputMessage = getMessageAndSetupScriptValues(input); url = actor->getParameter(BaseAttributes::URL_OUT_ATTRIBUTE().getId())->getAttributeValue(); fileMode = actor->getParameter(BaseAttributes::FILE_MODE_ATTRIBUTE().getId())->getAttributeValue(); QVariantMap data = inputMessage.getData().toMap(); PWMatrix model = data.value(PWMatrixWorkerFactory::WMATRIX_SLOT.getId()).value(); QString anUrl = url; if (anUrl.isEmpty()) { anUrl = data.value(BaseSlots::URL_SLOT().getId()).toString(); } if (anUrl.isEmpty()) { QString err = tr("Unspecified URL for writing weight matrix"); //if (failFast) { return new FailTask(err); /*} else { ioLog.error(err); return NULL; }*/ } assert(!anUrl.isEmpty()); int count = ++counter[anUrl]; if (count != 1) { anUrl = GUrlUtils::prepareFileName(anUrl, count, QStringList(WeightMatrixIO::WEIGHT_MATRIX_EXT)); } else { anUrl = GUrlUtils::ensureFileExt( anUrl, QStringList(WeightMatrixIO::WEIGHT_MATRIX_EXT)).getURLString(); } ioLog.info(tr("Writing weight matrix to %1").arg(anUrl)); return new PWMatrixWriteTask(anUrl, model, fileMode); } ////////////////////////////////////////////////////////////////////////// // PFMatrix workers ////////////////////////////////////////////////////////////////////////// DataTypePtr const PFMatrixWorkerFactory::FREQUENCY_MATRIX_MODEL_TYPE() { DataTypeRegistry* dtr = WorkflowEnv::getDataTypeRegistry(); assert(dtr); static bool startup = true; if (startup) { dtr->registerEntry(DataTypePtr(new DataType(FREQUENCY_MATRIX_MODEL_TYPE_ID, WeightMatrixIO::tr("Frequency matrix"), ""))); startup = false; } return dtr->getById(FREQUENCY_MATRIX_MODEL_TYPE_ID); } const Descriptor PFMatrixWorkerFactory::FMATRIX_SLOT("fmatrix", WeightMatrixIO::tr("Frequency matrix"), ""); const Descriptor PFMatrixWorkerFactory::FREQUENCY_MATRIX_CATEGORY() {return Descriptor("hweightmatrix", WeightMatrixIO::tr("Weight matrix"), "");} PFMatrixIOProto::PFMatrixIOProto(const Descriptor& _desc, const QList& _ports, const QList& _attrs ) : IntegralBusActorPrototype(_desc, _ports, _attrs) { } bool PFMatrixIOProto::isAcceptableDrop(const QMimeData * md, QVariantMap * params, const QString & urlAttrId ) const { if (md->hasUrls()) { QList urls = md->urls(); if (urls.size() == 1) { QString url = urls.at(0).toLocalFile(); QString ext = GUrlUtils::getUncompressedExtension(GUrl(url, GUrl_File)); if (WeightMatrixIO::FREQUENCY_MATRIX_EXT == ext) { if (params) { params->insert(urlAttrId, url); } return true; } } } return false; } ReadPFMatrixProto::ReadPFMatrixProto(const Descriptor& _desc, const QList& _ports, const QList& _attrs ) : PFMatrixIOProto( _desc, _ports, _attrs ) { attrs << new Attribute(BaseAttributes::URL_IN_ATTRIBUTE(), BaseTypes::STRING_TYPE(), true); QMap delegateMap; delegateMap[BaseAttributes::URL_IN_ATTRIBUTE().getId()] = new URLDelegate(WeightMatrixIO::getPFMFileFilter(), WeightMatrixIO::FREQUENCY_MATRIX_ID, true); setEditor(new DelegateEditor(delegateMap)); setIconPath(":weight_matrix/images/weight_matrix.png"); } bool ReadPFMatrixProto::isAcceptableDrop(const QMimeData * md, QVariantMap * params ) const { return PFMatrixIOProto::isAcceptableDrop( md, params, BaseAttributes::URL_IN_ATTRIBUTE().getId()); } WritePFMatrixProto::WritePFMatrixProto(const Descriptor& _desc, const QList& _ports, const QList& _attrs ) : PFMatrixIOProto( _desc, _ports, _attrs ) { attrs << new Attribute(BaseAttributes::URL_OUT_ATTRIBUTE(), BaseTypes::STRING_TYPE(), true ); attrs << new Attribute(BaseAttributes::FILE_MODE_ATTRIBUTE(), BaseTypes::NUM_TYPE(), false, SaveDoc_Roll); QMap delegateMap; delegateMap[BaseAttributes::URL_OUT_ATTRIBUTE().getId()] = new URLDelegate(WeightMatrixIO::getPFMFileFilter(), WeightMatrixIO::FREQUENCY_MATRIX_ID, false ); delegateMap[BaseAttributes::FILE_MODE_ATTRIBUTE().getId()] = new FileModeDelegate(false); setEditor(new DelegateEditor(delegateMap)); setIconPath(":weight_matrix/images/weight_matrix.png"); setValidator(new ScreenedParamValidator(BaseAttributes::URL_OUT_ATTRIBUTE().getId(), ports.first()->getId(), BaseSlots::URL_SLOT().getId())); setPortValidator(FMATRIX_IN_PORT_ID, new ScreenedSlotValidator(BaseSlots::URL_SLOT().getId())); } bool WritePFMatrixProto::isAcceptableDrop(const QMimeData * md, QVariantMap * params ) const { return PFMatrixIOProto::isAcceptableDrop( md, params, BaseAttributes::URL_OUT_ATTRIBUTE().getId() ); } void PFMatrixWorkerFactory::init() { ActorPrototypeRegistry* r = WorkflowEnv::getProtoRegistry(); assert(r); { QMap m; Descriptor sd(BaseSlots::URL_SLOT().getId(), WeightMatrixIO::tr("Location"), WeightMatrixIO::tr("Location hint for the target file.")); m[BaseSlots::URL_SLOT()] = BaseTypes::STRING_TYPE(); m[PFMatrixWorkerFactory::FMATRIX_SLOT] = PFMatrixWorkerFactory::FREQUENCY_MATRIX_MODEL_TYPE(); DataTypePtr t(new MapDataType(Descriptor("write.pfmatrix.content"), m)); QList p; QList a; Descriptor pd(FMATRIX_IN_PORT_ID, WeightMatrixIO::tr("Frequency matrix"), WeightMatrixIO::tr("Input frequency matrix")); p << new PortDescriptor(pd, t, true /*input*/); Descriptor desc(PFMatrixWriter::ACTOR_ID, WeightMatrixIO::tr("Write frequency matrix"), WeightMatrixIO::tr("Saves all input frequency matrices to specified location.")); IntegralBusActorPrototype* proto = new WritePFMatrixProto(desc, p, a); proto->setPrompter(new PFMatrixWritePrompter()); r->registerProto(BaseActorCategories::CATEGORY_TRANSCRIPTION(), proto); } { QList p; QList a; Descriptor pd(FMATRIX_OUT_PORT_ID, WeightMatrixIO::tr("Frequency matrix"), WeightMatrixIO::tr("Loaded weight matrices data.")); QMap outM; outM[PFMatrixWorkerFactory::FMATRIX_SLOT] = PFMatrixWorkerFactory::FREQUENCY_MATRIX_MODEL_TYPE(); p << new PortDescriptor(pd, DataTypePtr(new MapDataType("fmatrix.read.out", outM)), false /*input*/, true /*multi*/); Descriptor desc(PFMatrixReader::ACTOR_ID, WeightMatrixIO::tr("Read frequency matrix"), WeightMatrixIO::tr("Reads frequency matrices from file(s). The files can be local or Internet URLs.")); IntegralBusActorPrototype* proto = new ReadPFMatrixProto(desc, p, a); proto->setPrompter(new PFMatrixReadPrompter()); r->registerProto(BaseActorCategories::CATEGORY_TRANSCRIPTION(), proto); } PFMatrixBuildWorker::registerProto(); PFMatrixConvertWorker::registerProto(); DomainFactory* localDomain = WorkflowEnv::getDomainRegistry()->getById(LocalDomainFactory::ID); localDomain->registerEntry(new PFMatrixWorkerFactory(PFMatrixReader::ACTOR_ID)); localDomain->registerEntry(new PFMatrixWorkerFactory(PFMatrixWriter::ACTOR_ID)); localDomain->registerEntry(new PFMatrixWorkerFactory(PFMatrixBuildWorker::ACTOR_ID)); localDomain->registerEntry(new PFMatrixWorkerFactory(PFMatrixConvertWorker::ACTOR_ID)); } Worker* PFMatrixWorkerFactory::createWorker(Actor* a) { BaseWorker* w = NULL; if (PFMatrixReader::ACTOR_ID == a->getProto()->getId()) { w = new PFMatrixReader(a); } else if (PFMatrixWriter::ACTOR_ID == a->getProto()->getId()) { w = new PFMatrixWriter(a); } else if (PFMatrixBuildWorker::ACTOR_ID == a->getProto()->getId()) { w = new PFMatrixBuildWorker(a); } else if (PFMatrixConvertWorker::ACTOR_ID == a->getProto()->getId()) { w = new PFMatrixConvertWorker(a); } return w; } QString PFMatrixReadPrompter::composeRichDoc() { return tr("Read model(s) from %1").arg(getHyperlink(BaseAttributes::URL_IN_ATTRIBUTE().getId(), getURL(BaseAttributes::URL_IN_ATTRIBUTE().getId()))); } QString PFMatrixWritePrompter::composeRichDoc() { IntegralBusPort* input = qobject_cast(target->getPort(FMATRIX_IN_PORT_ID)); Actor* producer = input->getProducer(PFMatrixWorkerFactory::FREQUENCY_MATRIX_MODEL_TYPE_ID); QString from = producer ? producer->getLabel() : ""+tr("unset")+""; QString url = getScreenedURL(input, BaseAttributes::URL_OUT_ATTRIBUTE().getId(), BaseSlots::URL_SLOT().getId()); url = getHyperlink(BaseAttributes::URL_OUT_ATTRIBUTE().getId(), url); QString doc = tr("Save the profile(s) from %1 to %2.") .arg(from) .arg(url); return doc; } void PFMatrixReader::init() { output = ports.value(FMATRIX_OUT_PORT_ID); urls = WorkflowUtils::expandToUrls(actor->getParameter(BaseAttributes::URL_IN_ATTRIBUTE().getId())->getAttributeValue()); mtype = PFMatrixWorkerFactory::FREQUENCY_MATRIX_MODEL_TYPE(); } Task* PFMatrixReader::tick() { Task* t = new PFMatrixReadTask(urls.takeFirst()); connect(t, SIGNAL(si_stateChanged()), SLOT(sl_taskFinished())); tasks.append(t); return t; } void PFMatrixReader::sl_taskFinished() { PFMatrixReadTask* t = qobject_cast(sender()); if (t->getState() != Task::State_Finished) return; tasks.removeAll(t); if (output) { if (!t->hasError()) { QVariant v = qVariantFromValue(t->getResult()); output->put(Message(mtype, v)); } if (urls.isEmpty() && tasks.isEmpty()) { output->setEnded(); } ioLog.info(tr("Loaded frequency matrix from %1").arg(t->getURL())); } } void PFMatrixWriter::init() { input = ports.value(FMATRIX_IN_PORT_ID); } Task* PFMatrixWriter::tick() { Message inputMessage = getMessageAndSetupScriptValues(input); url = actor->getParameter(BaseAttributes::URL_OUT_ATTRIBUTE().getId())->getAttributeValue(); fileMode = actor->getParameter(BaseAttributes::FILE_MODE_ATTRIBUTE().getId())->getAttributeValue(); QVariantMap data = inputMessage.getData().toMap(); PFMatrix model = data.value(PFMatrixWorkerFactory::FMATRIX_SLOT.getId()).value(); QString anUrl = url; if (anUrl.isEmpty()) { anUrl = data.value(BaseSlots::URL_SLOT().getId()).toString(); } if (anUrl.isEmpty()) { QString err = tr("Unspecified URL for writing frequency matrix"); //if (failFast) { return new FailTask(err); /*} else { ioLog.error(err); return NULL; }*/ } assert(!anUrl.isEmpty()); int count = ++counter[anUrl]; if (count != 1) { anUrl = GUrlUtils::prepareFileName(anUrl, count, QStringList(WeightMatrixIO::FREQUENCY_MATRIX_EXT)); } else { anUrl = GUrlUtils::ensureFileExt( anUrl, QStringList(WeightMatrixIO::FREQUENCY_MATRIX_EXT)).getURLString(); } ioLog.info(tr("Writing frequency matrix to %1").arg(anUrl)); return new PFMatrixWriteTask(anUrl, model, fileMode); } } //namespace LocalWorkflow } //namespace U2 ugene-1.9.8/src/plugins/weight_matrix/src/WMQuery.cpp0000644000175000017500000001652511651544324021317 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "WMQuery.h" #include "WeightMatrixIO.h" #include #include #include #include #include #include #include #include #include #include #include namespace U2 { /************************************************************************/ /* WMQDTask */ /************************************************************************/ WMQDTask::WMQDTask(const QString& url, const WeightMatrixSearchCfg& cfg, DNASequenceObject* sqnc, const QString& resName, const QVector& location) : Task(tr("Weight matrix query"), TaskFlag_NoRun), settings(cfg), seqObj(sqnc), resultName(resName), location(location) { readTask = new PWMatrixReadTask(url); addSubTask(readTask); } QList WMQDTask::onSubTaskFinished(Task* subTask) { QList subtasks; if (subTask==readTask) { PWMatrix model = readTask->getResult(); foreach(const U2Region& r, location) { subtasks << new WeightMatrixSingleSearchTask(model, seqObj->getSequence().constData() + r.startPos, r.length, settings, r.startPos); } } else { WeightMatrixSingleSearchTask* t = qobject_cast(subTask); assert(t); res << t->takeResults(); } return subtasks; } QList WMQDTask::takeResults() { QList results = res; res.clear(); return results; } /************************************************************************/ /* QDWMActor */ /************************************************************************/ static const QString SCORE_ATTR = "min-score"; static const QString PROFILE_URL_ATTR = "matrix"; QDWMActor::QDWMActor(QDActorPrototype const* proto) : QDActor(proto) { units["wm"] = new QDSchemeUnit(this); } int QDWMActor::getMinResultLen() const { return 1; } int QDWMActor::getMaxResultLen() const { if (scheme->getDNA()) { return scheme->getDNA()->getSequenceLen(); } return 30;//FIX ME: supply reasonable value } QString QDWMActor::getText() const { QMap params = cfg->getParameters(); QString strandName; switch (strand) { case QDStrand_Both: strandName = tr("both strands"); break; case QDStrand_DirectOnly: strandName = tr("direct strand"); break; case QDStrand_ComplementOnly: strandName = tr("complement strand"); break; } QString profileUrl = params.value(PROFILE_URL_ATTR)->getAttributeValue(); if (profileUrl.isEmpty()) { profileUrl = "unset"; } profileUrl = QString("%2").arg(PROFILE_URL_ATTR).arg(profileUrl); int score = params.value(SCORE_ATTR)->getAttributeValue(); QString scoreStr = QString("%2%").arg(SCORE_ATTR).arg(score); QString doc = tr("Searches TFBS with all profiles from %1 " "
Recognizes sites with similarity %2, processes %3.") .arg(profileUrl) .arg(scoreStr) .arg(strandName); return doc; } Task* QDWMActor::getAlgorithmTask(const QVector& location) { Task* t = NULL; DNASequenceObject* dna = scheme->getDNA(); assert(dna); QMap params = cfg->getParameters(); WeightMatrixSearchCfg config; config.minPSUM = params.value(SCORE_ATTR)->getAttributeValue(); const QString& modelUrl = params.value(PROFILE_URL_ATTR)->getAttributeValue(); if (dna->getAlphabet()->getType() == DNAAlphabet_NUCL) { config.complOnly = strand == QDStrand_ComplementOnly; if (strand == QDStrand_Both || strand == QDStrand_ComplementOnly) { QList compTTs = AppContext::getDNATranslationRegistry()-> lookupTranslation(dna->getAlphabet(), DNATranslationType_NUCL_2_COMPLNUCL); if (!compTTs.isEmpty()) { config.complTT = compTTs.first(); } } t = new WMQDTask(modelUrl, config, dna, "", location); connect(new TaskSignalMapper(t), SIGNAL(si_taskFinished(Task*)), SLOT(sl_onAlgorithmTaskFinished(Task*))); } else { QString err = tr("%1: sequence should be nucleic.").arg(getParameters()->getLabel()); return new FailTask(err); } return t; } void QDWMActor::sl_onAlgorithmTaskFinished(Task* t) { WMQDTask* wmqdt = qobject_cast(t); assert(wmqdt); QList res = wmqdt->takeResults(); foreach(const WeightMatrixSearchResult& r, res) { QDResultUnit ru(new QDResultUnitData); ru->strand = r.strand; QMapIterator it(r.qual); while (it.hasNext()) { it.next(); ru->quals.append(U2Qualifier(it.key(), it.value())); } ru->region = r.region; ru->owner = units.value("wm"); QDResultGroup::buildGroupFromSingleResult(ru, results); } } /************************************************************************/ /* Factory */ /************************************************************************/ QDWMActorPrototype::QDWMActorPrototype() { descriptor.setId("wsearch"); descriptor.setDisplayName(QObject::tr("WeightMatrix")); descriptor.setDocumentation(QObject::tr("Searches the sequence for transcription factor binding sites significantly similar to the specified weight matrix.")); Descriptor scd(SCORE_ATTR, QObject::tr("Min score"), QApplication::translate("PWMSearchDialog", "min_err_tip", 0, QApplication::UnicodeUTF8)); Descriptor mx(PROFILE_URL_ATTR, QObject::tr("Matrix"), QObject::tr("Path to profile")); attributes << new Attribute(scd, BaseTypes::NUM_TYPE(), false, 85); attributes << new Attribute(mx, BaseTypes::STRING_TYPE(), true); QMap delegates; { QVariantMap m; m["minimum"] = 1; m["maximum"] = 100; m["suffix"] = "%"; delegates[SCORE_ATTR] = new SpinBoxDelegate(m); } delegates[PROFILE_URL_ATTR] = new URLDelegate(WeightMatrixIO::getPWMFileFilter(), WeightMatrixIO::WEIGHT_MATRIX_ID, true); editor = new DelegateEditor(delegates); } }//namespace ugene-1.9.8/src/plugins/weight_matrix/src/WeightMatrixAlgorithm.h0000644000175000017500000000310511651544324023664 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_WEIGHT_MATRIX_ALGORITHM_H_ #define _U2_WEIGHT_MATRIX_ALGORITHM_H_ #include #include namespace U2 { enum MatrixBuldTarget { FREQUENCY_MATRIX, WEIGHT_MATRIX }; enum MatrixBuildType { PM_MONONUCLEOTIDE, PM_DINUCLEOTIDE }; class PMBuildSettings { public: PMBuildSettings(): type(PM_MONONUCLEOTIDE), target(FREQUENCY_MATRIX) { } QString algo; MatrixBuildType type; MatrixBuldTarget target; }; class WeightMatrixAlgorithm : public QObject { Q_OBJECT public: static float getScore(const char* seq, int len, const PWMatrix& m, DNATranslation* complMap); }; } //namespace #endifugene-1.9.8/src/plugins/weight_matrix/src/ViewMatrixDialogController.h0000644000175000017500000000307211651544324024667 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_WEIGHT_MATRIX_VIEW_MATRIX_DIALOG_CONTROLLER_H_ #define _U2_WEIGHT_MATRIX_VIEW_MATRIX_DIALOG_CONTROLLER_H_ #include #include #include #include #include #include "WeightMatrixPlugin.h" namespace U2 { class ViewMatrixDialogController : public QDialog, public Ui_ViewMatrixDialog { Q_OBJECT public: ViewMatrixDialogController(QWidget* w = NULL); ViewMatrixDialogController(PFMatrix matrix, QWidget* w = NULL); ViewMatrixDialogController(PWMatrix matrix, QWidget* w = NULL); private: AlignmentLogoRenderArea* logoArea; private slots: void sl_onCloseButton(); }; } //namespace #endifugene-1.9.8/src/plugins/weight_matrix/src/PWMSearchDialogController.h0000644000175000017500000000605111651544324024361 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_WEIGHT_MATRIX_SEARCH_DIALOG_H_ #define _U2_WEIGHT_MATRIX_SEARCH_DIALOG_H_ #include #include #include #include #include #include #include #include #include #include "WeightMatrixSearchTask.h" namespace U2 { class ADVSequenceObjectContext; class DNASequenceObject; class WeightMatrixSearchTask; class Task; class WeightMatrixResultItem; class WeightMatrixQueueItem; class PWMSearchDialogController : public QDialog, public Ui_PWMSearchDialog { Q_OBJECT public: PWMSearchDialogController(ADVSequenceObjectContext* ctx, QWidget *p = NULL); public slots: virtual void reject(); protected: bool eventFilter(QObject *obj, QEvent *ev); private slots: //buttons: void sl_selectModelFile(); void sl_onSaveAnnotations(); void sl_onClearList(); void sl_onSearch(); void sl_onClose(); void sl_onBuildMatrix(); void sl_onSearchJaspar(); void sl_onSliderMoved(int value); void sl_onAlgoChanged(QString newAlgo); void sl_onViewMatrix(); void sl_onAddToQueue(); void sl_onLoadList(); void sl_onSaveList(); void sl_onLoadFolder(); void sl_onClearQueue(); // groups void sl_onTaskFinished(); void sl_onTimer(); void sl_onResultActivated(QTreeWidgetItem* i, int col); private: void connectGUI(); void updateState(); void updateStatus(); void updateModel(const PWMatrix& m); void loadFile(QString filename); void addToQueue(); bool checkPrevSettings(); void savePrevSettings(); void runTask(); void importResults(); private: ADVSequenceObjectContext* ctx; U2Region initialSelection; PFMatrix intermediate; PWMatrix model; QList< QPair > queue; WeightMatrixSearchTask* task; QTimer* timer; }; }//namespace #endif ugene-1.9.8/src/plugins/weight_matrix/src/WeightMatrixSearchWorker.cpp0000644000175000017500000002401011651544324024666 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "WeightMatrixWorkers.h" #include "WeightMatrixIOWorkers.h" #include "WeightMatrixSearchTask.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include /* TRANSLATOR U2::LocalWorkflow::PWMatrixSearchWorker */ namespace U2 { namespace LocalWorkflow { static const QString MODEL_PORT("in-wmatrix"); static const QString NAME_ATTR("result-name"); static const QString SCORE_ATTR("min-score"); const QString PWMatrixSearchWorker::ACTOR_ID("wmatrix-search"); void PWMatrixSearchWorker::registerProto() { QList p; QList a; { Descriptor md(MODEL_PORT, PWMatrixSearchWorker::tr("Weight matrix"), PWMatrixSearchWorker::tr("Profile data to search with.")); Descriptor sd(BasePorts::IN_SEQ_PORT_ID(), PWMatrixSearchWorker::tr("Sequence"), PWMatrixSearchWorker::tr("Input nucleotide sequence to search in.")); Descriptor od(BasePorts::OUT_ANNOTATIONS_PORT_ID(), PWMatrixSearchWorker::tr("Weight matrix annotations"), PWMatrixSearchWorker::tr("Annotations marking found TFBS sites.")); QMap modelM; modelM[PWMatrixWorkerFactory::WMATRIX_SLOT] = PWMatrixWorkerFactory::WEIGHT_MATRIX_MODEL_TYPE(); p << new PortDescriptor(md, DataTypePtr(new MapDataType("wmatrix.search.model", modelM)), true /*input*/, false, IntegralBusPort::BLIND_INPUT); QMap seqM; seqM[BaseSlots::DNA_SEQUENCE_SLOT()] = BaseTypes::DNA_SEQUENCE_TYPE(); p << new PortDescriptor(sd, DataTypePtr(new MapDataType("wmatrix.search.sequence", seqM)), true /*input*/); QMap outM; outM[BaseSlots::ANNOTATION_TABLE_SLOT()] = BaseTypes::ANNOTATION_TABLE_TYPE(); p << new PortDescriptor(od, DataTypePtr(new MapDataType("wmatrix.search.out", outM)), false /*input*/, true /*multi*/); } { Descriptor nd(NAME_ATTR, PWMatrixSearchWorker::tr("Result annotation"), PWMatrixSearchWorker::tr("Annotation name for marking found regions")); Descriptor scd(SCORE_ATTR, PWMatrixSearchWorker::tr("Min score"), QApplication::translate("PWMSearchDialog", "min_err_tip", 0, QApplication::UnicodeUTF8)); a << new Attribute(nd, BaseTypes::STRING_TYPE(), true, "misc_feature"); a << new Attribute(BaseAttributes::STRAND_ATTRIBUTE(), BaseTypes::STRING_TYPE(), false, BaseAttributes::STRAND_BOTH()); a << new Attribute(scd, BaseTypes::NUM_TYPE(), false, 85); } Descriptor desc(ACTOR_ID, tr("Search for TFBS with weight matrix"), tr("Searches each input sequence for transcription factor binding sites significantly similar to specified weight matrices." " In case several profiles were supplied, searches with all profiles one by one and outputs merged set of annotations for each sequence.") ); ActorPrototype* proto = new IntegralBusActorPrototype(desc, p, a); QMap delegates; { QVariantMap m; m["minimum"] = 1; m["maximum"] = 100; m["suffix"] = "%"; delegates[SCORE_ATTR] = new SpinBoxDelegate(m); } delegates[BaseAttributes::STRAND_ATTRIBUTE().getId()] = new ComboBoxDelegate(BaseAttributes::STRAND_ATTRIBUTE_VALUES_MAP()); proto->setPrompter(new PWMatrixSearchPrompter()); proto->setEditor(new DelegateEditor(delegates)); proto->setIconPath(":weight_matrix/images/weight_matrix.png"); WorkflowEnv::getProtoRegistry()->registerProto(BaseActorCategories::CATEGORY_TRANSCRIPTION(), proto); } static int getStrand(const QString & s) { QString str = s.toLower(); if(BaseAttributes::STRAND_BOTH().startsWith(str)) { return 0; } else if(BaseAttributes::STRAND_DIRECT().startsWith(str)) { return 1; } else if(BaseAttributes::STRAND_COMPLEMENTARY().startsWith(str)) { return -1; } else { bool ok = false; int num = str.toInt(&ok); if(ok) { return num; } else { return 0; } } } QString PWMatrixSearchPrompter::composeRichDoc() { Actor* modelProducer = qobject_cast(target->getPort(MODEL_PORT))->getProducer(PWMatrixWorkerFactory::WMATRIX_SLOT.getId()); Actor* seqProducer = qobject_cast(target->getPort(BasePorts::IN_SEQ_PORT_ID()))->getProducer(BaseSlots::DNA_SEQUENCE_SLOT().getId()); QString unsetStr = ""+tr("unset")+""; QString seqName = tr("For each sequence from %1,").arg(seqProducer ? seqProducer->getLabel() : unsetStr); QString modelName = tr("with all profiles provided by %1,").arg(modelProducer ? modelProducer->getLabel() : unsetStr); QString resultName = getRequiredParam(NAME_ATTR); resultName = getHyperlink(NAME_ATTR, resultName); QString strandName; switch (getStrand(getParameter(BaseAttributes::STRAND_ATTRIBUTE().getId()).value())) { case 0: strandName = PWMatrixSearchWorker::tr("both strands"); break; case 1: strandName = PWMatrixSearchWorker::tr("direct strand"); break; case -1: strandName = PWMatrixSearchWorker::tr("complement strand"); break; } strandName = getHyperlink(BaseAttributes::STRAND_ATTRIBUTE().getId(), strandName); QString doc = tr("%1 search transcription factor binding sites (TFBS) %2." "
Recognize sites with similarity %3%, process %4." "
Output the list of found regions annotated as %5.") .arg(seqName) .arg(modelName) .arg(getHyperlink(SCORE_ATTR, getParameter(SCORE_ATTR).toInt())) .arg(strandName) .arg(resultName); return doc; } void PWMatrixSearchWorker::init() { modelPort = ports.value(MODEL_PORT); dataPort = ports.value(BasePorts::IN_SEQ_PORT_ID()); output = ports.value(BasePorts::OUT_ANNOTATIONS_PORT_ID()); dataPort->addComplement(output); output->addComplement(dataPort); strand = getStrand(actor->getParameter(BaseAttributes::STRAND_ATTRIBUTE().getId())->getAttributeValue()); cfg.minPSUM = actor->getParameter(SCORE_ATTR)->getAttributeValue(); resultName = actor->getParameter(NAME_ATTR)->getAttributeValue(); } bool PWMatrixSearchWorker::isReady() { return ((!models.isEmpty() && modelPort->isEnded()) && dataPort->hasMessage()) || modelPort->hasMessage(); } Task* PWMatrixSearchWorker::tick() { while (modelPort->hasMessage()) { models << modelPort->get().getData().toMap().value(PWMatrixWorkerFactory::WMATRIX_SLOT.getId()).value(); } if (models.isEmpty() || !modelPort->isEnded() || !dataPort->hasMessage()) { return NULL; } DNASequence seq = dataPort->get().getData().toMap().value(BaseSlots::DNA_SEQUENCE_SLOT().getId()).value(); if (!seq.isNull() && seq.alphabet->getType() == DNAAlphabet_NUCL) { WeightMatrixSearchCfg config(cfg); config.complOnly = (strand < 0); if (strand <= 0) { QList compTTs = AppContext::getDNATranslationRegistry()-> lookupTranslation(seq.alphabet, DNATranslationType_NUCL_2_COMPLNUCL); if (!compTTs.isEmpty()) { config.complTT = compTTs.first(); } } QList subtasks; foreach(PWMatrix model, models) { subtasks << new WeightMatrixSingleSearchTask(model, seq.constData(), seq.length(), config, 0); } Task* t = new MultiTask(tr("Search TFBS in %1").arg(seq.getName()), subtasks); connect(new TaskSignalMapper(t), SIGNAL(si_taskFinished(Task*)), SLOT(sl_taskFinished(Task*))); return t; } QString err = tr("Bad sequence supplied to Weight Matrix Search: %1").arg(seq.getName()); //if (failFast) { return new FailTask(err); /*} else { algoLog.error(err); output->put(Message(BioDataTypes::ANNOTATION_TABLE_TYPE(), QVariant())); if (dataPort->isEnded()) { output->setEnded(); } return NULL; }*/ } void PWMatrixSearchWorker::sl_taskFinished(Task* t) { QList res; foreach(Task* sub, t->getSubtasks()) { WeightMatrixSingleSearchTask* sst = qobject_cast(sub); res += WeightMatrixSearchResult::toTable(sst->takeResults(), resultName); } QVariant v = qVariantFromValue >(res); output->put(Message(BaseTypes::ANNOTATION_TABLE_TYPE(), v)); if (dataPort->isEnded()) { output->setEnded(); } algoLog.info(tr("Found %1 TFBS").arg(res.size())); //TODO set task description for report } bool PWMatrixSearchWorker::isDone() { return dataPort->isEnded(); } } //namespace LocalWorkflow } //namespace U2 ugene-1.9.8/src/plugins/weight_matrix/src/WeightMatrixIOWorkers.h0000644000175000017500000001427411651544324023633 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_WEIGHT_MATRIX_IO_WORKER_H_ #define _U2_WEIGHT_MATRIX_IO_WORKER_H_ #include #include #include #include "WeightMatrixAlgorithm.h" Q_DECLARE_METATYPE(U2::PWMatrix) Q_DECLARE_METATYPE(U2::PFMatrix) namespace U2 { namespace LocalWorkflow { class PWMatrixIOProto : public IntegralBusActorPrototype { public: PWMatrixIOProto(const Descriptor& desc, const QList& ports, const QList& attrs = QList()); virtual bool isAcceptableDrop(const QMimeData*, QVariantMap*) const = 0; bool isAcceptableDrop(const QMimeData*, QVariantMap*, const QString & urlAttrId ) const; }; class ReadPWMatrixProto : public PWMatrixIOProto { public: ReadPWMatrixProto(const Descriptor& desc, const QList& ports, const QList& attrs = QList()); virtual bool isAcceptableDrop(const QMimeData*, QVariantMap*) const; }; class WritePWMatrixProto : public PWMatrixIOProto { public: WritePWMatrixProto(const Descriptor& desc, const QList& ports, const QList& attrs = QList()); virtual bool isAcceptableDrop(const QMimeData*, QVariantMap*) const; }; class PWMatrixReadPrompter : public PrompterBase { Q_OBJECT public: PWMatrixReadPrompter(Actor* p = 0) : PrompterBase(p) {} protected: QString composeRichDoc(); }; class PWMatrixWritePrompter : public PrompterBase { Q_OBJECT public: PWMatrixWritePrompter(Actor* p = 0) : PrompterBase(p) {} protected: QString composeRichDoc(); }; class PWMatrixReader : public BaseWorker { Q_OBJECT public: static const QString ACTOR_ID; PWMatrixReader(Actor* a) : BaseWorker(a), output(NULL) {} virtual void init() ; virtual bool isReady() {return !urls.isEmpty();} virtual Task* tick() ; virtual bool isDone() {return urls.isEmpty();} virtual void cleanup() {} private slots: void sl_taskFinished(); protected: CommunicationChannel *output; QStringList urls; QList tasks; DataTypePtr mtype; }; class PWMatrixWriter : public BaseWorker { Q_OBJECT public: static const QString ACTOR_ID; PWMatrixWriter(Actor* a) : BaseWorker(a), input(NULL), done(false), fileMode(SaveDoc_Overwrite) {} virtual void init() ; virtual bool isReady() {return input && input->hasMessage();} virtual Task* tick() ; virtual bool isDone() {return !input || input->isEnded();} virtual void cleanup() {} protected: CommunicationChannel *input; QString url; QMap counter; bool done; uint fileMode; }; ////////////////////////////////////////////////////////////////////////// // PFMatrix ////////////////////////////////////////////////////////////////////////// class PFMatrixIOProto : public IntegralBusActorPrototype { public: PFMatrixIOProto(const Descriptor& desc, const QList& ports, const QList& attrs = QList()); virtual bool isAcceptableDrop(const QMimeData*, QVariantMap*) const = 0; bool isAcceptableDrop(const QMimeData*, QVariantMap*, const QString & urlAttrId ) const; }; class ReadPFMatrixProto : public PFMatrixIOProto { public: ReadPFMatrixProto(const Descriptor& desc, const QList& ports, const QList& attrs = QList()); virtual bool isAcceptableDrop(const QMimeData*, QVariantMap*) const; }; class WritePFMatrixProto : public PFMatrixIOProto { public: WritePFMatrixProto(const Descriptor& desc, const QList& ports, const QList& attrs = QList()); virtual bool isAcceptableDrop(const QMimeData*, QVariantMap*) const; }; class PFMatrixReadPrompter : public PrompterBase { Q_OBJECT public: PFMatrixReadPrompter(Actor* p = 0) : PrompterBase(p) {} protected: QString composeRichDoc(); }; class PFMatrixWritePrompter : public PrompterBase { Q_OBJECT public: PFMatrixWritePrompter(Actor* p = 0) : PrompterBase(p) {} protected: QString composeRichDoc(); }; class PFMatrixReader : public BaseWorker { Q_OBJECT public: static const QString ACTOR_ID; PFMatrixReader(Actor* a) : BaseWorker(a), output(NULL) {} virtual void init() ; virtual bool isReady() {return !urls.isEmpty();} virtual Task* tick() ; virtual bool isDone() {return urls.isEmpty();} virtual void cleanup() {} private slots: void sl_taskFinished(); protected: CommunicationChannel *output; QStringList urls; QList tasks; DataTypePtr mtype; }; class PFMatrixWriter : public BaseWorker { Q_OBJECT public: static const QString ACTOR_ID; PFMatrixWriter(Actor* a) : BaseWorker(a), input(NULL), done(false), fileMode(SaveDoc_Overwrite) {} virtual void init() ; virtual bool isReady() {return input && input->hasMessage();} virtual Task* tick() ; virtual bool isDone() {return !input || input->isEnded();} virtual void cleanup() {} protected: CommunicationChannel *input; QString url; QMap counter; bool done; uint fileMode; }; } // Workflow namespace } // U2 namespace #endif ugene-1.9.8/src/plugins/weight_matrix/transl/0000755000175000017500000000000011651544324017745 5ustar ilyailyaugene-1.9.8/src/plugins/weight_matrix/transl/russian.ts0000644000175000017500000017400711651544324022012 0ustar ilyailya PWMBuildDialog Build weight or frequency matrix Построить весовую или частотную матрицу Input file Входной файл ... Output file Выходной файл Statistic options Настройки статистики Statistic type: Тип статистики: Mononucleic Мононуклеотидная Dinucleic Динуклеотидная Matrix options Настройки матрицы Matrix type: Тип матрицы: Frequency matrix Частотная матрица Weight matrix Весовая матрица Weight algorithm Весовой алгоритм Start Старт Cancel Отмена algo_tip Различные весовые алгоритмы применяют разные функции для построения весовых матриц. Это позволяет добиться большей точности на разных наборах входных данных. Алгоритмы Log-odds, NLG и Match чувствительны к матрица с нулевыми ячейками, поэтому некоторые из них могут не работать на таких матрицах type_tip Динуклеотидные матрицы более подробно сохраняют свойства входных выравниваний, но для малых наборов входных данных мононуклеотиндые матрицы лучше вследствие меньшей разреженности PWMSearchDialog Weight matrix search Поиск с весовыми матрицами Matrix: Матрица: ... Minimal score Минимальный скор Score: Скор: 85% 85% Search JASPAR database Поиск по базе JASPAR Build new matrix Построить новую матрицу View matrix Просмотр матрицы Weight algorithm Весовой алгоритм Strands Направление Both strands Все strand_direct_wit Только прямые Direct strand Только прямые strand_complement_wit Только комплементарные Complement strand Только комплементарные Range Регион Whole sequence Вся последовательность Selection range Селектированный регион Custom range Указанный регион - Matrix Матрица Algorithm Алгоритм Load list... Загрузить список... Save list... Сохранить список... Load folder... Загрузить папку... Clear list Очистить очередь Strand Стренд Score Скор Clear results Сбросить результаты Save as annotations Сохранить результаты Status Статус Add to queue Добавить в очередь Search Искать Cancel Отмена min_err_tip Минимальный скор распознавания сайта связывания транскрипционного фактора QObject Weight matrix Searches the sequence for transcription factor binding sites significantly similar to the specified weight matrix. Annotation name for marking found regions Имя аннотации для обозначения найденных регионов Min score Мин. скор Matrix Матрица Path to profile both strands все direct strand только прямые complement strand только комплементарные SearchJASPARDatabase Search JASPAR database Просмотр базы JASPAR Name Имя ID ID Class Класс Family Семейство Select Выбрать Cancel Отмена SetDefaultParametersDialog Set default parameters Установить параметры по умолчанию Weight algorithm Весовой алгоритм Score: Скор: 85% OK U2::LocalWorkflow::PFMatrixBuildPrompter For each MSA from <u>%1</u>, Для каждого выравнивания из <u>%1</u>, %1 build frequency matrix. U2::LocalWorkflow::PFMatrixBuildWorker Input alignment Входное выравнивание Input multiple sequence alignment for building statistical model. Введите выравнивание для построения статистической модели. Frequency matrix Частотная матрица Produced statistical model of specified TFBS data. Итоговая матрица для заданного ССТФ. Build frequency matrix Построить частотную матрицу Builds frequency matrix. Frequency matrices are used for probabilistic recognition of transcription factor binding sites. Построение частотной матрицы. Частотные матрицы используются для вероятностного распознавания сайтов связывания транскрипционных факторов. Mononucleic Мононуклеотидная Dinucleic Динуклеотидная Built frequency matrix Построена частотная матрица U2::LocalWorkflow::PFMatrixConvertPrompter For each frequency matrix from <u>%1</u>, Для каждой частотной матрицы из <u>%1</u>, %1 build weight matrix. %1 строит весовую матрицу. U2::LocalWorkflow::PFMatrixConvertWorker Weight matrix Весовая матрица Frequency matrix to convert. Частотная матрица для конвертации. Frequency matrix Частотная матрица Produced statistical model of specified TFBS data. Итоговая матрица для заданного ССТФ. Convert frequency matrix Конвертировать частотную матрицу Converts frequency matrix to weight matrix. Weight matrices are used for probabilistic recognition of transcription factor binding sites. Конвертация частотной матрицы в весовую. Весовые матрицы используются для вероятностного распознавания сайтов связывания транскрипционных факторов. Mononucleic Мононуклеотидная Dinucleic Динуклеотидная Built weight matrix Построена весовая матрица U2::LocalWorkflow::PFMatrixReadPrompter Read model(s) from <u>%1</u> Чтение матриц из <u>%1</u> U2::LocalWorkflow::PFMatrixReader Loaded frequency matrix from %1 Загружена частотная матрица из %1 U2::LocalWorkflow::PFMatrixWritePrompter Save the profile(s) from <u>%1</u> to %2. Сохранить матрицы из <u>%1</u> в %2. U2::LocalWorkflow::PFMatrixWriter Unspecified URL for writing frequency matrix Не указан адрес для записи частотной матрицы Writing frequency matrix to %1 Запись частотной матрицы в %1 U2::LocalWorkflow::PWMatrixBuildPrompter For each MSA from <u>%1</u>, Для каждого выравнивания из <u>%1</u>, %1 build weight matrix. %1 строит весовую матрицу. U2::LocalWorkflow::PWMatrixBuildWorker Input alignment Входное выравнивание Input multiple sequence alignment for building statistical model. Введите выравнивание для построения статистической модели. Weight matrix Весовая матрица Produced statistical model of specified TFBS data. Итоговая матрица для заданного ССТФ. Weight algorithm Весовой алгоритм Matrix type Тип матрицы Build weight matrix Построить весовую матрицу Builds weight matrix. Weight matrices are used for probabilistic recognition of transcription factor binding sites. Построение весовой матрицы. Весовые матрицы используются для вероятностного распознавания сайтов связывания транскрипционных факторов. Mononucleic Мононуклеотидная Dinucleic Динуклеотидная Built weight matrix Построена весовая матрица U2::LocalWorkflow::PWMatrixReadPrompter Read model(s) from <u>%1</u> Чтение матриц из <u>%1</u> U2::LocalWorkflow::PWMatrixReader Loaded weight matrix from %1 Загружена весовая матрица из %1 U2::LocalWorkflow::PWMatrixSearchPrompter For each sequence from <u>%1</u>, Для каждой последовательности из <u>%1</u>, with all profiles provided by <u>%1</u>, со всеми матрицами, предоставленными <u>%1</u>, %1 search transcription factor binding sites (TFBS) %2.<br>Recognize sites with <u>similarity %3%</u>, process <u>%4</u>.<br>Output the list of found regions annotated as <u>%5</u>. %1 ищет сайты свазывания транскрипционных факторов (ССТФ) %2. <br>Распознаёт сайты со <u>сходством %3%</u>, производит <u>%4</u>. <br>Выводит список найденных регионов в виде аннотаций <u>%5</u>. U2::LocalWorkflow::PWMatrixSearchWorker Weight matrix Весовая матрица Profile data to search with. Матрицы для поиска. Sequence Последовательность Input nucleotide sequence to search in. Входная нуклеотидная последовательность для поиска. Weight matrix annotations Аннотации весовых матриц Annotations marking found TFBS sites. Аннотации, отмечающие найденные ССТФ. Result annotation Итоговая аннотация Annotation name for marking found regions Имя аннотации для обозначения найденных регионов Search in Искать в Which strands should be searched: direct, complement or both. В каком стренде искать: прямом, комплементарном или обоих. Min score Мин. скор Search for TFBS with weight matrix Search TFBS Поиск ССТФ Searches each input sequence for transcription factor binding sites significantly similar to specified weight matrices. In case several profiles were supplied, searches with all profiles one by one and outputs merged set of annotations for each sequence. Производит в каждой входной последовательности поиск сайтов связывания транскрипционных факторов, заданных весовыми матрицами. В случае, если предоставлено несколько матриц, проводится поиск по каждой матрице, результаты объединяются в набор аннотаций для каждой последовательности. both strands все direct strand только прямые complement strand только комплементарные Search TFBS in %1 Поиск ССТФ в %1 Bad sequence supplied to Weight Matrix Search: %1 Поиску по весовым матрицам предоставлена неверная последовательность: %1 Found %1 TFBS Найдено %1 ССТФ U2::LocalWorkflow::PWMatrixWritePrompter Save the profile(s) from <u>%1</u> to %2. Сохранить матрицы из <u>%1</u> в %2. U2::LocalWorkflow::PWMatrixWriter Unspecified URL for writing weight matrix Не указан адрес для записи весовой матрицы Writing weight matrix to %1 Запись весовой матрицы в %1 U2::PFMatrixBuildTask Build frequency matrix Построить частотную матрицу Alignment has gaps В выравнивании есть пробелы Alignment is empty Выравнивание пусто Alignment is not nucleic Неправильный алфавит выравнивания Calculating frequencies of nucleotids Подсчёт частотной статистики U2::PFMatrixBuildToFileTask Build weight matrix Построить весовую матрицу Input format error Неверный входной формат Loading alignment Загрузка выравнивания Wrong sequence alphabet Неверный алфавит последовательности No alignments or sequences found Не выбрано ни одного выравнивания или последовательности U2::PFMatrixReadTask Read frequency matrix Чтение частотной матрицы U2::PFMatrixWriteTask Save position frequency matrix Сохранение частотной матрицы U2::PWMBuildDialogController Select file with alignment Выберите файл с выравниванием Wrong sequence alphabet Неверный алфавит последовательности Zero length matrix is not allowed Матрицы нулевой длины не разрешены Select file to save frequency matrix to... Выберите файл для сохранения частотной матрицы... Select file to save weight matrix to... Выберите файл для сохранения весовой матрицы... Overwrite existing file Переписать существующий файл File with this name already exists. Do you want to write over this file? Файл с таким именем уже существует. Вы хотите переписать его? Illegal input file name Неправильное имя входного файла Illegal output file name Неправильное имя выходного файла Counting frequency statistics Подсчёт частотной статистики Hide Скрыть Cancel Отмена Build finished with errors: %1 Построение завершено с ошибками: %1 Build canceled Построение отменено Build finished successfuly Построение завершено успешно Start Старт Close Закрыть Running state %1 progress %2% Состояние выполнения %1 прогресс %2% U2::PWMSearchDialogController Cancel Отмена Close Закрыть Progress %1% Прогресс %1% Results found: %1. Результатов найдено: %1. Select file with frequency or weight matrix Выберите файл с весовой или частотной матрицей Zero length or corrupted model Maybe model data is not enough for selected algorithm Model not selected Не выбрана матрица Load file with list of matrices Загрузить файл со списком матриц CSV files (*.csv) Файлы CSV (*.csv) Save file with list of matrices Сохранить файл со списком матриц Select directory with frequency or weight matrices Выберите папку с частотными или весовыми матрицами Complement strand Только комплементарные Direct strand Только прямые Zero length or corrupted model Повреждённая матрица либо матрица нулевой длины Range is too small Регион слишком мал U2::PWMatrixBuildTask Build weight matrix Построить весовую матрицу Can't convert mononucleotide matrix to dinucleotide one Невозможно преобразовать мононуклеотидную матрицу в динуклеотидную Alignment has gaps В выравнивании есть пробелы Alignment is empty Выравнивание пусто Alignment is not nucleic Неправильный алфавит выравнивания U2::PWMatrixBuildToFileTask Build weight matrix Построить весовую матрицу Input format error Неверный входной формат Loading alignment Загрузка выравнивания Wrong sequence alphabet Неверный алфавит последовательности No alignments or sequences found Не выбрано ни одного выравнивания или последовательности U2::PWMatrixReadTask Read weight matrix Чтение весовой матрицы U2::PWMatrixWriteTask Save weight matrix Сохранение весовой матрицы U2::QDWMActor both strands direct strand complement strand Searches TFBS with all profiles from <u>%1</u> <br> Recognizes sites with <u>similarity %2</u>, processes <u>%3</u>. Bad sequence supplied to weight matrix search Which strands should be searched: direct, complement or both. В каком стренде искать: прямом, комплементарном или обоих. U2::WMQDActor both strands оба стренда direct strand только прямой стренд complement strand только комплементарный стренд Searches TFBS with all profiles from <u>%1</u> <br> Recognizes sites with <u>similarity %2</u>, processes <u>%3</u>.<br> Annotates the results as <u>%4</u> Ищет сайты связывания транскрипционных факторов (ССТФ) со всеми профайлами %1 <br> Распознаёт сайты со схожестью %2, рассматривает %3. Аннотирует результаты как %4 U2::WMQDTask Weight matrix query U2::WeightMatrixADVContext Search TFBS with matrices... Весовые матрицы: Искать сайты связывания ТФ... U2::WeightMatrixIO Frequency and weight matrices Частотные и весовые матрицы Frequency matrices Частотные матрицы Weight matrices Весовые матрицы Error parsing settings line %1 Ошибка при чтении строки %1 Error parsing value %1 Ошибка при чтении значения %1 Unexpected negative frequency value %1 Отрицательное значение частоты: %1 Incorrect size of weight matrix: %1 Неправильный размер весовой матрицы: %1 Weight matrix Весовые матрицы Location Путь Location hint for the target file. Место для сохранения целевого файла. Input weight matrix Входная весовая матрица Write weight matrix Сохранение весовой матрицы Saves all input weight matrices to specified location. Сохраняет все входные весовые матрицы в указанное место. Loaded weight matrices data. Загруженные весовые матрицы. Read weight matrix Чтение весовой матрицы Reads weight matrices from file(s). The files can be local or Internet URLs. Читает весовые матрицы из файла(ов). Файлы могут быть как локальными, так и в Интернете. Frequency matrix Частотная матрица Input frequency matrix Входные частотные матрицы Write frequency matrix Сохранение частотной матрицы Saves all input frequency matrices to specified location. Сохраняет все входные частотные матрицы в указанное место. Read frequency matrix Чтение частотной матрицы Reads frequency matrices from file(s). The files can be local or Internet URLs. Читает частотные матрицы из файла(ов). Файлы могут быть как локальными, так и в Интернете. U2::WeightMatrixPlugin Weight matrix Весовые матрицы Search for TFBS with weight matrices Весовые матрицы: искать сайты связывания ТФ Build weight matrix Построить весовую матрицу U2::WeightMatrixSearchTask Weight matrix multiple search Поиск с несколькими весовыми матрицами U2::WeightMatrixSingleSearchTask Weight matrix search Поиск с весовыми матрицами Weight matrix search parallel Параллельный поиск с весовыми матрицами Internal error invalid psum: %1 Внутренняя ошибка - неверная сумма: %1 ViewMatrixDialog View matrix Просмотр матрицы Close Закрыть ugene-1.9.8/src/plugins/weight_matrix/transl/czech.ts0000644000175000017500000013352711651544324021424 0ustar ilyailya U2::LocalWorkflow::PFMatrixBuildPrompter For each MSA from <u>%1</u>, %1 build frequency matrix. %1 построить частотную матрицу. U2::LocalWorkflow::PFMatrixBuildWorker Input alignment Input multiple sequence alignment for building statistical model. Frequency matrix Produced statistical model of specified TFBS data. Build frequency matrix Builds frequency matrix. Frequency matrices are used for probabilistic recognition of transcription factor binding sites. Mononucleic Dinucleic Built frequency matrix U2::LocalWorkflow::PFMatrixConvertPrompter For each frequency matrix from <u>%1</u>, %1 build weight matrix. U2::LocalWorkflow::PFMatrixConvertWorker Weight matrix Frequency matrix to convert. Produced statistical model of specified TFBS data. Convert frequency matrix Converts frequency matrix to weight matrix. Weight matrices are used for probabilistic recognition of transcription factor binding sites. Mononucleic Dinucleic Built weight matrix U2::LocalWorkflow::PFMatrixReadPrompter Read model(s) from <u>%1</u> U2::LocalWorkflow::PFMatrixReader Loaded frequency matrix from %1 U2::LocalWorkflow::PFMatrixWritePrompter Save the profile(s) from <u>%1</u> to %2. U2::LocalWorkflow::PFMatrixWriter Unspecified URL for writing frequency matrix Writing frequency matrix to %1 U2::LocalWorkflow::PWMatrixBuildPrompter For each MSA from <u>%1</u>, %1 build weight matrix. U2::LocalWorkflow::PWMatrixBuildWorker Input alignment Input multiple sequence alignment for building statistical model. Weight matrix Produced statistical model of specified TFBS data. Weight algorithm Matrix type Build weight matrix Builds weight matrix. Weight matrices are used for probabilistic recognition of transcription factor binding sites. Mononucleic Dinucleic Built weight matrix U2::LocalWorkflow::PWMatrixReadPrompter Read model(s) from <u>%1</u> U2::LocalWorkflow::PWMatrixReader Loaded weight matrix from %1 U2::LocalWorkflow::PWMatrixSearchPrompter For each sequence from <u>%1</u>, with all profiles provided by <u>%1</u>, %1 search transcription factor binding sites (TFBS) %2.<br>Recognize sites with <u>similarity %3%</u>, process <u>%4</u>.<br>Output the list of found regions annotated as <u>%5</u>. U2::LocalWorkflow::PWMatrixSearchWorker Weight matrix Profile data to search with. Sequence Input nucleotide sequence to search in. Weight matrix annotations Annotations marking found TFBS sites. Result annotation Annotation name for marking found regions Which strands should be searched: direct, complement or both. Min score Search TFBS Searches each input sequence for transcription factor binding sites significantly similar to specified weight matrices. In case several profiles were supplied, searches with all profiles one by one and outputs merged set of annotations for each sequence. both strands direct strand complement strand Search TFBS in %1 Bad sequence supplied to Weight Matrix Search: %1 Found %1 TFBS U2::LocalWorkflow::PWMatrixWritePrompter Save the profile(s) from <u>%1</u> to %2. U2::LocalWorkflow::PWMatrixWriter Unspecified URL for writing weight matrix Writing weight matrix to %1 U2::PFMatrixBuildTask Build frequency matrix Alignment has gaps Alignment is empty Alignment is not nucleic Calculating frequencies of nucleotids U2::PFMatrixBuildToFileTask Build weight matrix Input format error Loading alignment Wrong sequence alphabet No alignments or sequences found U2::PFMatrixReadTask Read frequency matrix U2::PFMatrixWriteTask Save position frequency matrix U2::PWMBuildDialogController Select file with alignment Wrong sequence alphabet Zero length matrix is not allowed Select file to save frequency matrix to... Select file to save weight matrix to... Overwrite existing file File with this name already exists. Do you want to write over this file? Illegal input file name Illegal output file name Counting frequency statistics Hide Cancel Build finished with errors: %1 Build canceled Build finished successfuly Start Close Running state %1 progress %2% U2::PWMSearchDialogController Cancel Close Progress %1% Results found: %1. Select file with frequency or weight matrix Model not selected Load file with list of matrices CSV files (*.csv) Save file with list of matrices Select directory with frequency or weight matrices Complement strand Direct strand Zero length or corrupted model Range is too small U2::PWMatrixBuildTask Build weight matrix Can't convert mononucleotide matrix to dinucleotide one Alignment has gaps Alignment is empty Alignment is not nucleic U2::PWMatrixBuildToFileTask Build weight matrix Input format error Loading alignment Wrong sequence alphabet No alignments or sequences found U2::PWMatrixReadTask Read weight matrix U2::PWMatrixWriteTask Save weight matrix U2::WeightMatrixADVContext Search TFBS with matrices U2::WeightMatrixIO Frequency and weight matrices Frequency matrices Weight matrices Error parsing settings line %1 Error parsing value %1 Unexpected negative frequency value %1 Incorrect size of weight matrix: %1 Weight matrix Location Location hint for the target file. Input weight matrix Write weight matrix Saves all input weight matrices to specified location. Loaded weight matrices data. Read weight matrix Reads weight matrices from file(s). The files can be local or Internet URLs. Frequency matrix Input frequency matrix Write frequency matrix Saves all input frequency matrices to specified location. Read frequency matrix Reads frequency matrices from file(s). The files can be local or Internet URLs. U2::WeightMatrixPlugin Weight matrix Search for TFBS with weight matrices Build weight matrix U2::WeightMatrixSearchTask Weight matrix multiple search U2::WeightMatrixSingleSearchTask Weight matrix search Weight matrix search parallel Internal error invalid psum: %1 PWMBuildDialog Build weight or frequency matrix Input file ... Output file Statistic options Statistic type: Mononucleic Dinucleic Matrix options Matrix type: Frequency matrix Weight matrix Weight algorithm Start Cancel algo_tip Different weight algorithms uses different functions to build weight matrices. It allows us to get better precision on different data sets. Log-odds, NLG and Match algorithms are sensitive to input matrices with zero values, so some of them may not work on those matrices type_tip Dinucleic matrices are more detailed, while mononucleic one are more useful for small input data sets PWMSearchDialog Weight matrix search Matrix: ... Minimal score Score: 85% Search JASPAR database Build new matrix View matrix Weight algorithm Strands Both strands strand_direct_wit Direct strand strand_complement_wit Complement strand Range Whole sequence Selection range Custom range - Matrix Algorithm Load list... Save list... Load folder... Clear list Strand Score Clear results Save as annotations Status Add to queue Search Cancel min_err_tip Minimum score to detect transcription factor binding site SearchJASPARDatabase Search JASPAR database Name ID Class Family Select Cancel SetDefaultParametersDialog Set default parameters Weight algorithm Score: 85% OK ViewMatrixDialog View matrix Close ugene-1.9.8/src/plugins/weight_matrix/transl/english.ts0000644000175000017500000013653411651544324021762 0ustar ilyailya PWMBuildDialog Build weight or frequency matrix Input file ... Output file Statistic options Statistic type: Mononucleic Dinucleic Matrix options Matrix type: Frequency matrix Weight matrix Weight algorithm Start Cancel algo_tip Different weight algorithms uses different functions to build weight matrices. It allows us to get better precision on different data sets. Log-odds, NLG and Match algorithms are sensitive to input matrices with zero values, so some of them may not work on those matrices type_tip Dinucleic matrices are more detailed, while mononucleic one are more useful for small input data sets PWMSearchDialog Weight matrix search Matrix: ... Minimal score Score: 85% Search JASPAR database Build new matrix View matrix Weight algorithm Strands Both strands strand_direct_wit Direct strand strand_complement_wit Complement strand Range Whole sequence Selection range Custom range - Matrix Algorithm Load list... Save list... Load folder... Clear list Strand Score Clear results Save as annotations Status Add to queue Search Cancel min_err_tip Minimum score to detect transcription factor binding site QObject Weight matrix Searches the sequence for transcription factor binding sites significantly similar to the specified weight matrix. Min score Matrix Path to profile SearchJASPARDatabase Search JASPAR database Name ID Class Family Select Cancel SetDefaultParametersDialog Set default parameters Weight algorithm Score: 85% OK U2::LocalWorkflow::PFMatrixBuildPrompter For each MSA from <u>%1</u>, %1 build frequency matrix. %1 построить частотную матрицу. U2::LocalWorkflow::PFMatrixBuildWorker Input alignment Input multiple sequence alignment for building statistical model. Frequency matrix Produced statistical model of specified TFBS data. Build frequency matrix Builds frequency matrix. Frequency matrices are used for probabilistic recognition of transcription factor binding sites. U2::LocalWorkflow::PFMatrixConvertPrompter For each frequency matrix from <u>%1</u>, %1 build weight matrix. U2::LocalWorkflow::PFMatrixConvertWorker Weight matrix Frequency matrix to convert. Frequency matrix Produced statistical model of specified TFBS data. Convert frequency matrix Converts frequency matrix to weight matrix. Weight matrices are used for probabilistic recognition of transcription factor binding sites. U2::LocalWorkflow::PFMatrixReadPrompter Read model(s) from <u>%1</u> U2::LocalWorkflow::PFMatrixReader Loaded frequency matrix from %1 U2::LocalWorkflow::PFMatrixWritePrompter Save the profile(s) from <u>%1</u> to %2. U2::LocalWorkflow::PFMatrixWriter Unspecified URL for writing frequency matrix Writing frequency matrix to %1 U2::LocalWorkflow::PWMatrixBuildPrompter For each MSA from <u>%1</u>, %1 build weight matrix. U2::LocalWorkflow::PWMatrixBuildWorker Input alignment Input multiple sequence alignment for building statistical model. Weight matrix Produced statistical model of specified TFBS data. Weight algorithm Matrix type Build weight matrix Builds weight matrix. Weight matrices are used for probabilistic recognition of transcription factor binding sites. U2::LocalWorkflow::PWMatrixReadPrompter Read model(s) from <u>%1</u> U2::LocalWorkflow::PWMatrixReader Loaded weight matrix from %1 U2::LocalWorkflow::PWMatrixSearchPrompter For each sequence from <u>%1</u>, with all profiles provided by <u>%1</u>, %1 search transcription factor binding sites (TFBS) %2.<br>Recognize sites with <u>similarity %3%</u>, process <u>%4</u>.<br>Output the list of found regions annotated as <u>%5</u>. U2::LocalWorkflow::PWMatrixSearchWorker Weight matrix Profile data to search with. Sequence Input nucleotide sequence to search in. Weight matrix annotations Annotations marking found TFBS sites. Result annotation Annotation name for marking found regions Which strands should be searched: direct, complement or both. Min score Search for TFBS with weight matrix Searches each input sequence for transcription factor binding sites significantly similar to specified weight matrices. In case several profiles were supplied, searches with all profiles one by one and outputs merged set of annotations for each sequence. both strands direct strand complement strand Search TFBS in %1 Bad sequence supplied to Weight Matrix Search: %1 Found %1 TFBS U2::LocalWorkflow::PWMatrixWritePrompter Save the profile(s) from <u>%1</u> to %2. U2::LocalWorkflow::PWMatrixWriter Unspecified URL for writing weight matrix Writing weight matrix to %1 U2::PFMatrixBuildTask Build frequency matrix Alignment has gaps Alignment is empty Alignment is not nucleic Calculating frequencies of nucleotids U2::PFMatrixBuildToFileTask Build weight matrix Input format error Loading alignment Wrong sequence alphabet No alignments or sequences found U2::PFMatrixReadTask Read frequency matrix U2::PFMatrixWriteTask Save position frequency matrix U2::PWMBuildDialogController Select file with alignment Wrong sequence alphabet Zero length matrix is not allowed Select file to save frequency matrix to... Select file to save weight matrix to... Overwrite existing file File with this name already exists. Do you want to write over this file? Illegal input file name Illegal output file name Counting frequency statistics Hide Cancel Build finished with errors: %1 Build canceled Build finished successfuly Start Close Running state %1 progress %2% U2::PWMSearchDialogController Cancel Close Progress %1% Results found: %1. Select file with frequency or weight matrix Zero length or corrupted model Maybe model data is not enough for selected algorithm Model not selected Load file with list of matrices CSV files (*.csv) Save file with list of matrices Select directory with frequency or weight matrices Complement strand Direct strand Zero length or corrupted model Range is too small U2::PWMatrixBuildTask Build weight matrix Can't convert mononucleotide matrix to dinucleotide one Alignment has gaps Alignment is empty Alignment is not nucleic U2::PWMatrixBuildToFileTask Build weight matrix Input format error Loading alignment Wrong sequence alphabet No alignments or sequences found U2::PWMatrixReadTask Read weight matrix U2::PWMatrixWriteTask Save weight matrix U2::QDWMActor both strands direct strand complement strand Searches TFBS with all profiles from <u>%1</u> <br> Recognizes sites with <u>similarity %2</u>, processes <u>%3</u>. Bad sequence supplied to weight matrix search Which strands should be searched: direct, complement or both. U2::WMQDTask Weight matrix query U2::WeightMatrixADVContext Search TFBS with matrices... U2::WeightMatrixIO Frequency and weight matrices Frequency matrices Weight matrices Error parsing settings line %1 Error parsing value %1 Unexpected negative frequency value %1 Incorrect size of weight matrix: %1 Weight matrix Location Location hint for the target file. Input weight matrix Write weight matrix Saves all input weight matrices to specified location. Loaded weight matrices data. Read weight matrix Reads weight matrices from file(s). The files can be local or Internet URLs. Frequency matrix Input frequency matrix Write frequency matrix Saves all input frequency matrices to specified location. Read frequency matrix Reads frequency matrices from file(s). The files can be local or Internet URLs. U2::WeightMatrixPlugin Weight matrix Search for TFBS with weight matrices Build weight matrix U2::WeightMatrixSearchTask Weight matrix multiple search U2::WeightMatrixSingleSearchTask Weight matrix search Weight matrix search parallel Internal error invalid psum: %1 ViewMatrixDialog View matrix Close ugene-1.9.8/src/plugins/weight_matrix/weight_matrix.pro0000644000175000017500000000253611651544324022045 0ustar ilyailyainclude (weight_matrix.pri) # Input HEADERS += src/WeightMatrixPlugin.h \ src/PWMBuildDialogController.h \ src/PWMJASPARDialogController.h \ src/PWMSearchDialogController.h \ src/ViewMatrixDialogController.h \ src/SetParametersDialogController.h \ src/WeightMatrixAlgorithm.h \ src/WeightMatrixSearchTask.h \ src/WeightMatrixIO.h \ src/WeightMatrixIOWorkers.h \ src/WeightMatrixWorkers.h \ src/WMQuery.h FORMS += src/ui/PWMBuildDialog.ui \ src/ui/PWMSearchDialog.ui \ src/ui/SearchJASPARDatabase.ui \ src/ui/ViewMatrixDialog.ui \ src/ui/SetDefaultParametersDialog.ui SOURCES += src/WeightMatrixPlugin.cpp \ src/PWMBuildDialogController.cpp \ src/PWMJASPARDialogController.cpp \ src/PWMSearchDialogController.cpp \ src/ViewMatrixDialogController.cpp \ src/SetParametersDialogController.cpp \ src/WeightMatrixAlgorithm.cpp \ src/WeightMatrixSearchTask.cpp \ src/WeightMatrixIO.cpp \ src/WeightMatrixIOWorkers.cpp \ src/WeightMatrixBuildWorker.cpp \ src/WeightMatrixSearchWorker.cpp \ src/WMQuery.cpp RESOURCES += weight_matrix.qrc TRANSLATIONS += transl/english.ts transl/russian.ts ugene-1.9.8/src/plugins/external_tool_support/0000755000175000017500000000000011651544323020241 5ustar ilyailyaugene-1.9.8/src/plugins/external_tool_support/images/0000755000175000017500000000000011651544323021506 5ustar ilyailyaugene-1.9.8/src/plugins/external_tool_support/images/tcoffee_warn.png0000644000175000017500000000112511651544323024655 0ustar ilyailyaPNG  IHDRasRGB pHYs  tIME  2IDAT8ݒ=hSQGϽyI IĚU#R-URURE]꒮ ..Dh:ꢂ t-T#Z`SҤyɽ?E]8T! Em` O'y6Oaφ5޻ r^++Xu1!MUTml%_,8hqft3i=@-$BA1|l1lA9;fƮwO$sH$bi ~ bIHS/O6}=#9\m1֚R?:  BAxiUyrUA1C@U lM'U? Gwd'j"]`,+훶#\>7 ҇@r!A&(+V;YU9GIENDB`ugene-1.9.8/src/plugins/external_tool_support/images/clustalx_gray.png0000644000175000017500000001376111651544323025105 0ustar ilyailyaPNG  IHDRU>sRGB pHYs  tIME#/ JIDATx{{UՕ}@E|d" I4hIj۝23Lz;IZ@$ڼLǀ+QA /Dy)`@J={}ǹֽŭϏ-Sk}[k _$V]<"/Q_TB6Re-0}G=jYcA NPϗ+G>mRԚj); dfD}Y;}/w5P6\P`(+\u_GBŬqD ʎ@Uϧ k΅I]K׮t+z:$dAv !c)tm.uck :o΅}/l[[w:GfapӶlV/A &bG2%ŽOs$gw#$˒|SLJ@K&j,Ɔ㛛KI$IHL+e_]8Pjtb8~ZX婫ϒ_XS2GRصM5 AUp܁ix!z ZoO_ބb xu]P-k1>j(;(/Ml0H_8ݶ I~cHryTE7H7]Mص0b7l.xH!H ( c1B~]aEE Q/ixԼE$R1O$I$$_夔 $'7® OK]] yUeDPvk4X!9AO9eN%e?g*ل]k )Aq"Mܔ#tRPS@+rN(zrW% 6,w-EdI=!tm,)׹`OOn❈Ph [RXׯ߉5R sl:$q{e|Y{ɐ\LU8V[Ύ1W갬o WJ #-TԯFQejDE;yuBf8i_wh$\  ^_qE)l#rC sTV0Z (*ᖀ]i o‡}d@CZlFJ[a{$.{JuDQ:`{܀J/t8#^rEht5f2\k"$^sb\U5HDHTɍ= AU1 ȶo 8aR PgF(xeu9/YU ^P1!}F+>[m% ALsZZ[EL{>7`tF)  ӝYئi)6(Cb ؝HłK&Ô& 4U»,"}E  J7^]IJ.6a.TnBv=[ K 0,9&1õd(Qm3חCmV2ѐ9N?I _%s0!l;hX_$fmL/:6r.2OVFYW1x!^>!n!b Tn*mDNSdG [;3#guc2UफsU4YLM!lpWCp) }s ħP1lW_$hC5D\F&$m<$C@_|Q\>=*a0Ʒw5̷_LofEQ! 8R 0wLM@pO7_p}_Mϕ}/2psg d+*oPzq <~Ud7h髟Dp_1%fS7߭e]o-OPA6}㋣^cq f b1ְ,\wޟ([}1 ?.;LG$ߚȐ:aZK֔?@,;nd \Kr^ Ѥ[_x8'oǯa|)~0s;@:siTpxEgZ ofϗɟ-姎W{ׯmFHkew3?rà zeb8&A2-={.(9  obrm{_JU?3롁̼W.7> zRGKqD񵉃Gz w+{iJ~4CeHǔVH^e%GMwݣ揝w1 }l׀2lydt{놕%^QԬQՀ"[^;6;ſ089ŷG17Sk}H@-OEWYG0 4/B!հ,xyWwc,~{# hv*$S!TG]$` 3rJb^ĠY2W;{%PI|eDs_q_ T,vtGצc/X¸)kіаUlU3<&"g޸} Δ]nNxT/%#ME;WHo SY@GF% n#aT5*Aq<*lfɸ/mR ͓r'?ž\..%l+uE2W.l / 9z[1+;gp&_~+sb5U&g3}w/Ҕ% ;v?3@Z|T,Á#+}JFiצd 3.qύ p@Kmt<8 3f&DĦ: $C-K}k (bBk?*"}zŲv?TD^ eεJ;< LV|5-.Vx3w}lɰbKS7dDZ/:\{%{}0 -ay;,]ظt/'_bC2O`Yo|u8sљALo!ڎZhvxdRǚ;w\0 # L~<‰Z8Hrgr=fa4wڒnO%5? d|H) |Z*q|u2*d]w﬛ናd/%wɊgycbyMC;`vzѦ(̓xq%ӗ2póO+?^ oŬ o)כdMwaI>$K}×>pYaQ#o'0۠q!s09 &nՖŒR($W}`&U>f6iM"L ~I %Ug״DDn,ˆ<`)VO } !ÔLCXk(:Ȫ, Jt}ԠH[HW"k71? ZTiQMeR.tˢVOKT}& ׵`/(K={ZKک`!@@¡@8`e@M̃ܰQ-C,@2Fc ̝`%闻sZ8?Py?ډLN 玺]u\:8g%Ifqgm 5I/ oE!ܗp&T=l29U iiײwBU]rR -Dyaf!ɭin3;#9xAGX-L>%QE]-J01\5! }ZuH#X2Oȑf4#My_z@ӏXLc\v%&7Avd\>B&}EQ0Nl6ٙqgqmUwR,)I֚+Y$A/AE$؃0|Hd AE[%P^SWֽ82}뼜}}REFQO&OH]SQ1J;IW "Je oIe#9٤#O-*oJM°7i2$kɏK$πo6tΘ*"4c!-!x|1wiuXKޓ"nSD/_FFk7*y/}cj9Β SA6F#!yVeDW#dݬYt l=\Y7,zdy%%چD1X5`/mqĽ9d&w(S S $b{U+aQēŽK+SL'ԏժ5k:n|\el""^-a"#*y=9{{q+EV9Ҥ> 쿾<@{hڙ܌F9XZE1d:?7:"(@ZXVY8,bz% **VoKVОf:p$@ D"A׿/KIENDB`ugene-1.9.8/src/plugins/external_tool_support/images/ncbi_warn.png0000644000175000017500000001247611651544323024170 0ustar ilyailyaPNG  IHDR &# OiCCPPhotoshop ICC profilexڝSgTS=BKKoR RB&*! J!QEEȠQ, !{kּ> H3Q5 B.@ $pd!s#~<<+"x M0B\t8K@zB@F&S`cbP-`'{[! eDh;VEX0fK9-0IWfH  0Q){`##xFW<+*x<$9E[-qWW.(I+6aa@.y24x6_-"bbϫp@t~,/;m%h^ uf@Wp~<5j>{-]cK'Xto(hw?G%fIq^D$.Tʳ?D*A, `6B$BB dr`)B(Ͱ*`/@4Qhp.U=pa( Aa!ڈbX#!H$ ɈQ"K5H1RT UH=r9\F;2G1Q= C7F dt1r=6Ыhڏ>C03l0.B8, c˱" VcϱwE 6wB aAHXLXNH $4 7 Q'"K&b21XH,#/{C7$C2'ITFnR#,4H#dk9, +ȅ3![ b@qS(RjJ4e2AURݨT5ZBRQ4u9̓IKhhitݕNWGw Ljg(gwLӋT071oUX**| J&*/Tު UUT^S}FU3S ԖUPSSg;goT?~YYLOCQ_ cx,!k u5&|v*=9C3J3WRf?qtN (~))4L1e\kXHQG6EYAJ'\'GgSSݧ M=:.kDwn^Loy}/TmG X $ <5qo</QC]@Caaᄑ.ȽJtq]zۯ6iܟ4)Y3sCQ? 0k߬~OCOg#/c/Wװwa>>r><72Y_7ȷOo_C#dz%gA[z|!?:eAAA!h쐭!ΑiP~aa~ 'W?pX15wCsDDDޛg1O9-J5*>.j<74?.fYXXIlK9.*6nl {/]py.,:@LN8A*%w% yg"/6шC\*NH*Mz쑼5y$3,幄'L Lݛ:v m2=:1qB!Mggfvˬen/kY- BTZ(*geWf͉9+̳ې7ᒶKW-X潬j9(xoʿܔĹdff-[n ڴ VE/(ۻCɾUUMfeI?m]Nmq#׹=TR+Gw- 6 U#pDy  :v{vg/jBFS[b[O>zG499?rCd&ˮ/~јѡ򗓿m|x31^VwwO| (hSЧc3-bKGD pHYsgRtIME  -8U@ pIDATXõXiUNw7ofa, !J!dl&(D*IaibJK`eXZbD ePYf̛mwLDx[uN}} v$&vÝƬNf?V`ZxŷLz;v/ZY|9 $||  {ޯye?o}gJ:0?[8%:*|e# $ƪv=@JĈxiO_sGG @0UHKf_zC~EP Ɍ C$b`cUdǴЫ[%v$_b|yP!42}$6lȻ\UȊwϫ-yɱ>aEeѐ7h]hO83n]w:@J|yMg.)؞#=_zrǓy.Ow k[ y%nJ'W_L-5GV={} Ro|+׾|Fg~k|~sO2?ޗ8';>qtgbo[|eeO98gOr}cmoZYmHfDH?eOno폽y7?8yBx3T0U SumlN.{ׁˏcMKO8x*>5n{HHԗܞPP2$,R+M|ҤZi8nXҍ:JP9.ߞK8$rYc8 */$kw .ܺ;w;˦ <kK۷I˳_{,]ơʂ׎潩^+̘*ڟxAc *:>z8W_{⣒>Fk \}N`: SVÜ8>cRzc,z\CbK|qeA'Uv&/zǗ;NO x&8 Z.T ,VT͇-z M (`h?܋躊LvzIf%6غ$ DY4 )%s+_YuV]a.U+\54 Cu6tt R\,KJLE&* T\8}ņꛗVvkN`r."=Zw=>@޶uնʑ_\fF#fwR$Ge äM'hV_: /F~eG MkVFDYnj4v}!!I`)2RzY)8ip?E"Q^Z*.Wɞ[hGk'|MMڰe|mu?ͥYz`[WcB5ˏVYFUxgS8C^w}xYgTEBUa$ѨH hqIE ',H"u\ђUnpH'.@$$$V0a'  *  `tӆ P$@$Aq󥔜`$Nu@$bl, `BB_:a27!IENDB`ugene-1.9.8/src/plugins/external_tool_support/images/clustalx.jpg0000644000175000017500000004035211651544323024053 0ustar ilyailyaJFIFCC" }!1AQa"q2#BR$3br %&'()*456789:CDEFGHIJSTUVWXYZcdefghijstuvwxyz w!1AQaq"2B #3Rbr $4%&'()*56789:CDEFGHIJSTUVWXYZcdefghijstuvwxyz ??( +o{> |`~;~.|ZCӼM-_BE=&.>Q&s*Aft=J-6/soCǏ)F<+Ͱ? `;q]i*UU:\EV)*z3I |0Y%b,̲V !˱ok:VJ*Zaz t*N ':= C_s~(k4]=].ռ)i~"Khvh :M+_Wŵih(v~~ K͟ψ>8hMcww+5IPmndմOEp5ޥaicosuGod/⬿+`3LM|KpXfK,5F:҆^NshWьRxAOxf^`L]<&i`j,C|M\,L#^41qnJ\].e<=D.$V1/7 |43OxvVZ4ˮ>EMm'd4 Q7/z¶Ko5/g!}Lm.x*L< xЕ%9FuR{[I*t}Y>X3,?K Qu9()B7%7y=ػwvKV_xkTߌu X4\9r@ckkYK}sO^1_ h#xg EY jҡyY"K[PY%t3/+j=̓1b=C&b8GG(rYF5T&F!N- OvJ5)WZugFQzQy++-N&_>6L񖶺Q2 Լ+=Kqi֖w7Wk;'kSI_]M:5]=q-CRKwY^ /m(gwӍ~~. f\IC4q6;&.P`(N4>L;U)Q#ZPU^\7bX&ev][0 :U1x59BxL5J=JܿYK Wx #xC׊M7vwַ^vvIw{y;\I!TWT=4>C~! _K.ɡ3GsZv F[{;yKt \2?gUdn?*¶%iשRJ&PRSRtENx~7O9Q!86C7a䵲:?bjՒ:ukJ(ңiYUh{^b(B(_&wq +/j:Kɑ6|jo~ ±x,|qM6fvi{GƲO<|o f9v3_ Bx9sάHp5a*K/^8l>e[OQڜ`N"Tάr>WZޒaJ\8t18̿ B}~#k|1T|?Z/5H/<J:d%/jC$-l4.h^!|bZc_ Os)&ufo xhb-z[KH-|CFڍ66_? iɨ`(òx?^)c;rReZEٸ!żSer)FqR tc<^_ka/MJ*II( 4s8pgn&ijsV(ź[Zx%˳ 3qX,4Ш+B?kJasƙ6o̹~8 }BO$,Qx[ZsxO*WKexl.J51UiPmEVcsU<>xGl88sFXVc RK¦[*OC)TPk<*<̿OG+Jٞxƅn!α 014:uQpX|.'K ((4}_IM6MWKt:-cHPMWHSM{[:k+hL\Z\’ S_7Oc ׂ3w5;^wh^iyW6V,RƬ1_$F^3a| Mï |+?+~vV=g<)x\ɯ{"ڎ-zT/!_]|Hr|z_Fu;MF_x+T}o/Ə X]Vmд_ \K?-spN_Ę3311yN#1<)j|6"yJl<9sZmx:ᬤM^9 HO㗷U>W7 <>OnokM-|l%՜#WZN??_ ?1O'f?7,:Γ*_ͬhQX\4B?"+;~~>-,u&h/ [4Zwtv[÷gl4նS'1] |q&F=O?xNa)g ^_K.Xn~(;Icd.$T?๺ŭoO2h_|0_ğ =fɕG-|2xn|ka}SW-E@F׾|<V&~3χ I6=s}as6q7ß {Ȟk&I?GYTf Ncf3 w Q,N[4q ω1 ^KBZP<%7 '<m'U)qGå?ٸZr1I FL B&xfcJUuDMD.t}aKTa b]B&k-m'4Tٟ&1o?P7Ckik:şif/ GSh> a ^:>,|Ιww^^5䶓k汷2 8x?fx̛r晆&数S(`؜V jUb*E'ΚI018ZRjW Tn0MRQKM_1_?+-a?ix;P]Ku7f /$pڃ_AKOԔyw懦>"*yhoZũӦlmTMp8 Fx^k 5l^ifdA^%z#4~X5἖ LrX>˧O}nPskysqi<HW9}8*CyNa|?$0U(u0Us~P'N5*B2ygW8Uhc4jCj)Im-l>5?O)')앥]x{h,NV/>|Ll+4g>!]gxJ6H⯣$W7.Tk_ F/sֳOpef=T?wˡzMm3Io8O 92~>+o#WO k.?o5k:r}itZϊN)㝧vݵ̷m oc}p3=I?sLҎ#W!xmyk>9~?O^+࿄ kYً:*ּCIiZ~O]+OAKF:RyeUC<#嘎603 6336W[x %~6Q߳w3;,aXnx{^Zu:e<]k+K[YZȲ ژĬ,xvS<:t:iK *. ب`iqXa%Sìʽ\|>>IŜcW-,AT8{c:K/'{Ì,'bs,Jy:+7z9榝W >V~ |bt+7&q<ť|,aYXo/t]_I`R]|@^?h_s෇>h2y|SC!>>F 7znoj@ZH/ r_Ժ; /?઺5(O[ :C-g2ٖ1* aic V~q ܟR8W{KlRT3YZ],n J96Vt8Ƽ)Zq棛xxj*lyZ 2)N? :Ң[r|$TbqTE=u7$ri[[ _?WI~~0'WcBi?NZh6Rgh~l4o Nxՙ F7cknڮv̖~t>W[{[_<̱lUH/#Xiw/u3T?lE}uM$ǢK4Q/i(o6<Ӕ?hg|3eY_1eX %(egFUa7*<3N*"|kiZR}j:vO}j2,VvVVsuuq+,P[#*F~?ho |Pi2>!4i??emVV.o~4xE?c햞ums$/ŵ?z=~xWNJ=VZuX|n//IaX|EMb{X_~$hu~yuhfgquNr!c09 ʕIETC FN? r5%W18c,NgeXVψeZKF(Ji Td)S6I'i߲;gg.؋c|HmEm7zt~0|Ȼ`,jb@_=Ҵ/B~:GI|f;;>ܷb_#tvg?«{^!.N~"mwuKP~2tNǪC{M#0_֬u:5#?m4z xCEx.Ɨ;@ǃCK-|3I#/^O?m/g3ɩZhsko>sBo?x?F xSJxB|=t++^>/C{c åC6Ŀ7۵Kړ[v<%+| ~ξ]GV^ݮoN΃WzݢGeioxc,ak'xGo-fqş?gK}7ñ?x9aߣ=g-ʘS|nGX~1|+|2,Tq|N>sksa{Cs#30F`Եψoo+ePOiajY+*ZG#Ee*aue-^ᯄ2ծoX|8"kV_s5ѬxcZtݤwPyӾ2? |) ԯ<'cxS8T dwp v_qT׊xl7*9g_WvfCury? M_o_gߋwA:g|hTkhz>e#޿^57M36:Cݖ1Kc-| ŋ%[o}HBo#o?uM|D1NJ+ {P'!íj/49_Q7.|4>1P7 zj2 nnn5fXU4x/{V msߏN.Uc`(WNup^I_Qu:פXхzѡ 9~,.Kc~/BX/ͱeP_qu1*y%GvsMؿ(?nq%9Tx-/|SnW|:׏[mui6>\XmeF'  oi/ڼ~#Y2E-ߊ'~џ|WhR*OT!ice|W^ep>厕HpnQBkX$j:މOLJy]->>?``xKïF bp 1|9Zcb+6r"H/w8x1a\gB/uKP9j;|'o;&G5PGax.=?_ԓQ^[A ]Om d?u: WmK _Iw >+>o|F,.MAc|Cla?# 隞VƏyjU嶣jzuw}qi{ewnkuk0]BˤwiᏈjze&+l^2\O|Sty|EzMZK[xB1ʍHVZܒ n]W:%e BVT%R r-4[Q_AEP_Sß|4/Mo _ƙ\X3]wKe**s-kGw ~ʺII ៃZ^² i:w-nTV\v$Im4mcVfL[i /LӴM3NѴ{]3I,m4/M;k-?N%Xm- x"U(HB'_Yt0x~r9:hvC1JaR,f+< a+R8~_HGͫ<¿fyv& VKتm)0Z .|tUHNE/eRTN~~[k~ 3N'E5+'@|-hkm%S^k[~:s]K܆<ۗ|ŗl8&Iumne u%s|!*!|H./xFsx#o|CVjO/)OOu`O9|wx V5q4BJ.P85QizyUZ)ApN^lN?!tmय़&hz? 7sؾfuRҿ[$Ѽq[Fӗb:3iFB]~;ErzUc(Uqf|~g?oh#89\|o?|iW>9%.%45ɳXD'2?JnpП: ppg d30˸0qJukW)1c u'֓^g3⥈L6/8U')(.tk;^M%uhiVZ7hYyI׬tsR4mGQ#$(J(>lſ߰5#FGwuV6V#K̷zߋ/h_igx~x ⿋'Zx7w xuSmGVе[po-767B["k4&W(n6R}ot}* ]ú.X<%[_ >M h6izMÕj~_m?Vmⷀ#<zvG&>૩]!kD 4kcsoeukscsqe{o=Z]C%ͭͼJ,*(>#ua|+θK s.a,%<.P1n Xl&Waa`hSTpԥ?coh"q8uѧ[SWca Y SV (`(O _fÿ> ڕz[Tpm֯tUZEiYEiY[Aae-rW7Ez/E~Sx6{㳜灲\4̱51xv.8N"Rսb pQN1cysCs|?89ͱuqٖe2+.jjԖ*hQN:q8+O_UDħbޗ&xo–0\'u {[X.ΩvͨJaanpƿ5E~dyG X,!˰VQRtpY~ӔVj]jURIu*u*JSQȸG%srITeC/J JU'Zj5zjkU'*kTVRr(Oh(+cc >~xEk0a;6ȴzt:/#M4&ݯ]E|p7 ˳. XJX.*3Jp*CjEOve*t~'8_0X<_*|]7G3}W:R:*BtV ~Χ,HJTi~1~t|fl?φ0X,e#a9r謃ʧΗ_9LuhZ:ms  DY1!j m`Pm~7;HHە* *jq)&4qf~j~B/zg@4ER`UT@&I&TUnsd` t:mf0N P y h#lZg)I |q9Np8 K)M^؍AP"DȜ H26T*&!{ RADLIR&i(=Y~G]5JC_(F`eIENDB`ugene-1.9.8/src/plugins/external_tool_support/images/cmdline_warn.png0000644000175000017500000000127611651544323024664 0ustar ilyailyaPNG  IHDRasRGB pHYs  tIME  :PIDAT8˥kq?w䮹%/C`n%nE* t NHA)TJqSH[ݏ9*->}EJf>gm`t:=.,},qMaڶ !B|<x;v_Y]]54]4IRr 溮200@\fff^BTBs]Wm6d2VVV,,,uuv:SSS "\J/UZVJ),h4 eYxu_MX[{aA;  !mzN氵"<}0:!柜cp0e H)m]AA!H&I&ӌ0/<~[14-ґ M3h7ε*}vu.'$3:v"L&fFcj B*PXA1y% ЭWAҫCHDP#":9ׂ7>:#_$}D |tu)EnZ=N!}PQJ%χy~[E4tIENDB`ugene-1.9.8/src/plugins/external_tool_support/images/ncbi.png0000644000175000017500000001342011651544323023127 0ustar ilyailyaPNG  IHDR &# pHYsgR OiCCPPhotoshop ICC profilexڝSgTS=BKKoR RB&*! J!QEEȠQ, !{kּ> H3Q5 B.@ $pd!s#~<<+"x M0B\t8K@zB@F&S`cbP-`'{[! eDh;VEX0fK9-0IWfH  0Q){`##xFW<+*x<$9E[-qWW.(I+6aa@.y24x6_-"bbϫp@t~,/;m%h^ uf@Wp~<5j>{-]cK'Xto(hw?G%fIq^D$.Tʳ?D*A, `6B$BB dr`)B(Ͱ*`/@4Qhp.U=pa( Aa!ڈbX#!H$ ɈQ"K5H1RT UH=r9\F;2G1Q= C7F dt1r=6Ыhڏ>C03l0.B8, c˱" VcϱwE 6wB aAHXLXNH $4 7 Q'"K&b21XH,#/{C7$C2'ITFnR#,4H#dk9, +ȅ3![ b@qS(RjJ4e2AURݨT5ZBRQ4u9̓IKhhitݕNWGw Ljg(gwLӋT071oUX**| J&*/Tު UUT^S}FU3S ԖUPSSg;goT?~YYLOCQ_ cx,!k u5&|v*=9C3J3WRf?qtN (~))4L1e\kXHQG6EYAJ'\'GgSSݧ M=:.kDwn^Loy}/TmG X $ <5qo</QC]@Caaᄑ.ȽJtq]zۯ6iܟ4)Y3sCQ? 0k߬~OCOg#/c/Wװwa>>r><72Y_7ȷOo_C#dz%gA[z|!?:eAAA!h쐭!ΑiP~aa~ 'W?pX15wCsDDDޛg1O9-J5*>.j<74?.fYXXIlK9.*6nl {/]py.,:@LN8A*%w% yg"/6шC\*NH*Mz쑼5y$3,幄'L Lݛ:v m2=:1qB!Mggfvˬen/kY- BTZ(*geWf͉9+̳ې7ᒶKW-X潬j9(xoʿܔĹdff-[n ڴ VE/(ۻCɾUUMfeI?m]Nmq#׹=TR+Gw- 6 U#pDy  :v{vg/jBFS[b[O>zG499?rCd&ˮ/~јѡ򗓿m|x31^VwwO| (hSЧc3- cHRMz%u0`:o_F ;IDATxڌXi\u^^f׌f48ȅ1 66SƅTHB( $eL1.ȕ8]`9v $Hfh֞-wɏ3B؀Ώ{{\b4) zFLjH-q MP%;6̲++wˊ_F 3%,us2;[HG p ZM>zq둾\Ȕgrn  gG2IRCj(DQ|PX0 02'JgF&P%#.4Ƅ/PP`Ik(\0Iwη?+?U3S pRջAgmZ({ @CTWj8xzbgJf4ayL1tI,jOmicܚ*Ù?U=7yT%?~7esN<%f\EOI@kcUC& }2 ]߳/$S6x;:j&8%1Zj60PZ)]1?ݎࠔ=[=zi(83HD9A[ʆ(ǜt 60@ \W.Ux  PJ>q߆|w|kќ?"F@10>yfbۮY^|Eb)4X֖D1EɒbEBPysRV d^ xrD-0o LmZ'/?7C[o욛>OKZ1~pc7۶?]D(!U0.aSDTPJS񼏣E:A`EWc4<5;}aΞ[p׷*~-{G@uFh閍o>=_sƱP_cA>吆 [0sHm< L8\aqcc, 86TBxj3[FNjQZܴ\b[CWCj` (Ew >Jn2 G-:-& z"욦=ې kXxpF` -P <}`/6lMb@͛:Nq% Q@)me gj-+'IA#CD08G4"T,P*Azt<0V՛#38R98 u5 S% bP@ꐨT~r`/Jt>w:WMmO 229(y OJbyGUXW]:N +)u1h 獷J__s_1T. `< (@F@pE, Iw,??=} aFC`p hS]b-{̊MKE7'52%3WJ(.mKZ5/}dtpO{t:Hq[jp%jphQdT "،Ψмqu.SZi'/nʎ/%߼g rbg NW\M ʭ:5;e2 *Zzt#wb_%#έM/ww[^p{d=}\hЍkgPU80N;̆4YBhiyKgbI {._уaix0˲@`@nw2].][޹ gjߪV4˕gĆ8_x$nRxׯYs9 eh[mygՏw2Gf X/؋1#GC^~> B mw5k- 6yZsAE":#㷋7Qn@Zʈ+#Nňbx"U,w))ZrGŠ F21 E?e fIENDB`ugene-1.9.8/src/plugins/external_tool_support/images/ncbi_gray.png0000644000175000017500000001036311651544323024154 0ustar ilyailyaPNG  IHDR &*Qb OiCCPPhotoshop ICC profilexڝSgTS=BKKoR RB&*! J!QEEȠQ, !{kּ> H3Q5 B.@ $pd!s#~<<+"x M0B\t8K@zB@F&S`cbP-`'{[! eDh;VEX0fK9-0IWfH  0Q){`##xFW<+*x<$9E[-qWW.(I+6aa@.y24x6_-"bbϫp@t~,/;m%h^ uf@Wp~<5j>{-]cK'Xto(hw?G%fIq^D$.Tʳ?D*A, `6B$BB dr`)B(Ͱ*`/@4Qhp.U=pa( Aa!ڈbX#!H$ ɈQ"K5H1RT UH=r9\F;2G1Q= C7F dt1r=6Ыhڏ>C03l0.B8, c˱" VcϱwE 6wB aAHXLXNH $4 7 Q'"K&b21XH,#/{C7$C2'ITFnR#,4H#dk9, +ȅ3![ b@qS(RjJ4e2AURݨT5ZBRQ4u9̓IKhhitݕNWGw Ljg(gwLӋT071oUX**| J&*/Tު UUT^S}FU3S ԖUPSSg;goT?~YYLOCQ_ cx,!k u5&|v*=9C3J3WRf?qtN (~))4L1e\kXHQG6EYAJ'\'GgSSݧ M=:.kDwn^Loy}/TmG X $ <5qo</QC]@Caaᄑ.ȽJtq]zۯ6iܟ4)Y3sCQ? 0k߬~OCOg#/c/Wװwa>>r><72Y_7ȷOo_C#dz%gA[z|!?:eAAA!h쐭!ΑiP~aa~ 'W?pX15wCsDDDޛg1O9-J5*>.j<74?.fYXXIlK9.*6nl {/]py.,:@LN8A*%w% yg"/6шC\*NH*Mz쑼5y$3,幄'L Lݛ:v m2=:1qB!Mggfvˬen/kY- BTZ(*geWf͉9+̳ې7ᒶKW-X潬j9(xoʿܔĹdff-[n ڴ VE/(ۻCɾUUMfeI?m]Nmq#׹=TR+Gw- 6 U#pDy  :v{vg/jBFS[b[O>zG499?rCd&ˮ/~јѡ򗓿m|x31^VwwO| (hSЧc3-bKGD̿ pHYsgRtIME  ),Q)IDATHuYlTsxf6Ĥa"EHDJԖjFA}(NJUKHIH(V'LR266=^ƞ}rNAw>Fs QG"Kگw?r7-`0I!$hL$,/N {h*ࢨ"{!A#1拧zL8(Z0X  ɰFKd5[mxE4S3G2DYƺ%#!\;X-8dE<=o]tcs_2{ƦS.oШ{H @'ޘS%U_}`rE5.6H@1@4| o_z+WB每ls6*ei\28WqqF!A@# 'DG5984N \$69"E47p)$CXcv2-FWQ",a1IcGb#X랬-K My{s4bQ DRAfÙ}&6Xw{\̖㕉ЖhbRE\sk=/-|Rc>=%4[^X؄#A櫒z7ks9i"ɱr?H4.(f|[,'s 3ٺ\cL,<\6p\ԘX̵\2鈏B && q$@⮏w wC T0BqV>֩ |"ٌ>x=_ yW;ַ'/)%e,|km k3K .ni67>c!5^jԸ$M٬Zy%BK3*:'84w94V`[hΎPA h[#P<F@U: LZjjFhsNǍN5j v do00f^qnٿ"$p48& 8@Qrķ ;&W(L3Gi.W1 s8($Ȑgp\pCs뙩+f"Uj3>%A'0 (ܦ2vC!<;dXqQ00dI%,D͡G_w.s?`?W]>|!f:#&X\zdxS&8n/5GhLJfX6'$n!G jmexPv*Q<ԿPO"H\`>X&[/ȻZ`a``cn8]omwvluIͽO%u fՙʂ11md |gkQZp1Yշ #=(&`CaRj?zy,,7 ]IEǶm2*~sonnpkkj hgh fhggefbOtRNS@f pHYs  tIME   ?pIDATc0bf@fFL40d@RӖbd`ea`71PVTbbe`Va``cTt`fb(Nu [.`"@w8ˊU L͂`dK0 Ձ2kK e^{u- [?X4*C1'S u#FIphEߍ;bLkU0['JW8hu@7,k7+f!,Z!/qU5xIENDB`ugene-1.9.8/src/plugins/external_tool_support/external_tool_support.pri0000644000175000017500000000024111651544323025425 0ustar ilyailya# include (external_tool_support.pri) PLUGIN_ID=external_tool_support PLUGIN_NAME=External tools PLUGIN_VENDOR=Unipro include( ../../ugene_plugin_common.pri ) ugene-1.9.8/src/plugins/external_tool_support/external_tool_support.qrc0000644000175000017500000000116711651544323025430 0ustar ilyailya images/clustalx.png images/clustalx_gray.png images/cmdline.png images/cmdline_gray.png images/ncbi.png images/tcoffee_gray.png images/tcoffee.png images/clustalx_warn.png images/cmdline_warn.png images/tcoffee_warn.png images/cancel.png images/ncbi_gray.png images/ncbi_warn.png ugene-1.9.8/src/plugins/external_tool_support/src/0000755000175000017500000000000011651544323021030 5ustar ilyailyaugene-1.9.8/src/plugins/external_tool_support/src/TaskLocalStorage.cpp0000644000175000017500000000356211651544323024744 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "TaskLocalStorage.h" #include class ETSContext *getETSContext() { return U2::TaskLocalData::current(); } int getETSWorkerID() { return U2::TaskLocalData::currentWorkerID(); } namespace U2 { QThreadStorage TaskLocalData::tls; class ETSContext* TaskLocalData::current(){ ETSContextTLSRef* ref = tls.localData(); if (ref!=NULL) { assert(ref->ctx!=NULL); return ref->ctx; } assert(0); return NULL; } unsigned TaskLocalData::currentWorkerID() { ETSContextTLSRef* ref = tls.localData(); if (ref!=NULL) { return ref->workerID; } assert(0); return -1; } void TaskLocalData::bindToETSTLSContext(ETSContext *ctx, int workerID) { assert(ctx!=NULL); assert(!tls.hasLocalData()); tls.setLocalData(new ETSContextTLSRef(ctx, workerID)); } void TaskLocalData::detachETSTLSContext() { ETSContextTLSRef* ref = tls.localData(); assert(ref!=NULL && ref->ctx!=NULL); ref->ctx = NULL; tls.setLocalData(NULL); } }//namespace ugene-1.9.8/src/plugins/external_tool_support/src/ExternalToolSupportSettings.h0000644000175000017500000000307711651544323026746 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_EXTERNAL_TOOL_SUPPORT_SETTINGS_H_ #define _U2_EXTERNAL_TOOL_SUPPORT_SETTINGS_H_ #include #include #include #include namespace U2 { class Watcher : public QObject { Q_OBJECT signals: void changed(); friend class ExternalToolSupportSettings; }; #define SETTINGS QString("ExternalToolSupport/") class ExternalToolSupportSettings { public: static int getNumberExternalTools(); static void setNumberExternalTools(int value); static bool getExternalTools(); static void setExternalTools(); static void checkTemporaryDir(); static Watcher * const watcher; private: static int prevNumberExternalTools; }; }//namespace #endif ugene-1.9.8/src/plugins/external_tool_support/src/utils/0000755000175000017500000000000011651544323022170 5ustar ilyailyaugene-1.9.8/src/plugins/external_tool_support/src/utils/ExternalToolSupportAction.cpp0000644000175000017500000001277211651544323030060 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "ExternalToolSupportAction.h" #include #include #include namespace U2 { ExternalToolSupprotAction::ExternalToolSupprotAction(QObject* p, GObjectView* v, const QString& _text, int order, const QStringList& _toolNames) : GObjectViewAction(p,v,_text,order), toolNames(_toolNames) { QFont isConfiguredToolFont; bool isOneOfToolConfigured=false; foreach(QString toolName, toolNames){ if(!AppContext::getExternalToolRegistry()->getByName(toolName)->getPath().isEmpty()){ isOneOfToolConfigured=true; } ExternalTool* exTool=AppContext::getExternalToolRegistry()->getByName(toolName); connect(exTool, SIGNAL(si_pathChanged()), SLOT(sl_pathChanged())); } connect(AppContext::getAppSettings()->getUserAppsSettings(), SIGNAL(si_temporaryPathChanged()), SLOT(sl_pathChanged())); if(!isOneOfToolConfigured || (AppContext::getAppSettings()->getUserAppsSettings()->getTemporaryDirPath().isEmpty())){ isConfiguredToolFont.setItalic(true); setFont(isConfiguredToolFont); // setText(text()+"..."); setIcon(AppContext::getExternalToolRegistry()->getByName(toolNames.at(0))->getGrayIcon()); }else{ isConfiguredToolFont.setItalic(false); setFont(isConfiguredToolFont); // if(text().endsWith("...")){ // setText(text().remove(text().length()-3,3)); // }else{ // setText(text()); // } if(AppContext::getExternalToolRegistry()->getByName(toolNames.at(0))->isValid()){ setIcon(AppContext::getExternalToolRegistry()->getByName(toolNames.at(0))->getIcon()); }else{ setIcon(AppContext::getExternalToolRegistry()->getByName(toolNames.at(0))->getWarnIcon()); } } } ExternalToolSupprotAction::ExternalToolSupprotAction(const QString& _text, QObject* p, const QStringList& _toolNames) : GObjectViewAction(p, NULL, _text), toolNames(_toolNames) { QFont isConfiguredToolFont; bool isOneOfToolConfigured=false; foreach(QString toolName, toolNames){ if(!AppContext::getExternalToolRegistry()->getByName(toolName)->getPath().isEmpty()){ isOneOfToolConfigured=true; } ExternalTool* exTool=AppContext::getExternalToolRegistry()->getByName(toolName); connect(exTool, SIGNAL(si_pathChanged()), SLOT(sl_pathChanged())); } connect(AppContext::getAppSettings()->getUserAppsSettings(), SIGNAL(si_temporaryPathChanged()), SLOT(sl_pathChanged())); if(!isOneOfToolConfigured || (AppContext::getAppSettings()->getUserAppsSettings()->getTemporaryDirPath().isEmpty())){ isConfiguredToolFont.setItalic(true); setFont(isConfiguredToolFont); // setText(text()+"..."); setIcon(AppContext::getExternalToolRegistry()->getByName(toolNames.at(0))->getGrayIcon()); }else{ isConfiguredToolFont.setItalic(false); setFont(isConfiguredToolFont); // if(text().endsWith("...")){ // setText(text().remove(text().length()-3,3)); // }else{ // setText(text()); // } if(AppContext::getExternalToolRegistry()->getByName(toolNames.at(0))->isValid()){ setIcon(AppContext::getExternalToolRegistry()->getByName(toolNames.at(0))->getIcon()); }else{ setIcon(AppContext::getExternalToolRegistry()->getByName(toolNames.at(0))->getWarnIcon()); } } } void ExternalToolSupprotAction::sl_pathChanged() { QFont isConfiguredToolFont; bool isOneOfToolConfigured=false; foreach(QString toolName, toolNames){ if(!AppContext::getExternalToolRegistry()->getByName(toolName)->getPath().isEmpty()){ isOneOfToolConfigured=true; } } if(!isOneOfToolConfigured || (AppContext::getAppSettings()->getUserAppsSettings()->getTemporaryDirPath().isEmpty())){ isConfiguredToolFont.setItalic(true); setFont(isConfiguredToolFont); // if(!text().endsWith("...")){ // setText(text()+"..."); // } setIcon(AppContext::getExternalToolRegistry()->getByName(toolNames.at(0))->getGrayIcon()); }else{ isConfiguredToolFont.setItalic(false); setFont(isConfiguredToolFont); // if(text().endsWith("...")){ // setText(text().remove(text().length()-3,3)); // } if(AppContext::getExternalToolRegistry()->getByName(toolNames.at(0))->isValid()){ setIcon(AppContext::getExternalToolRegistry()->getByName(toolNames.at(0))->getIcon()); }else{ setIcon(AppContext::getExternalToolRegistry()->getByName(toolNames.at(0))->getWarnIcon()); } } } }//namespace ugene-1.9.8/src/plugins/external_tool_support/src/utils/BlastTaskSettings.h0000644000175000017500000001526411651544323025762 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_BLAST_TASK_SETTINGS_H #define _U2_BLAST_TASK_SETTINGS_H #include #include namespace U2 { /*Options for BlastAll blastall 2.2.21 not included arguments: -I Show GI's in deflines [T/F] default = F -v Number of database sequences to show one-line descriptions for (V) [Integer] default = 500 -b Number of database sequence to show alignments for (B) [Integer] default = 250 -Q Query Genetic code to use [Integer] default = 1 -D DB Genetic code (for tblast[nx] only) [Integer] default = 1 -O SeqAlign file [File Out] Optional -J Believe the query defline [T/F] default = F -z Effective length of the database (use zero for the real size) [Real] default = 0 -P 0 for multiple hit, 1 for single hit (does not apply to blastn) [Integer] default = 0 -Y Effective length of the search space (use zero for the real size) [Real] default = 0 -S Query strands to search against database (for blast[nx], and tblastx) 3 is both, 1 is top, 2 is bottom [Integer] default = 3 -T Produce HTML output [T/F] default = F -l Restrict search of database to list of GI's [String] Optional -U Use lower case filtering of FASTA sequence [T/F] Optional -R PSI-TBLASTN checkpoint file [File In] Optional -L Location on query sequence [String] Optional -w Frame shift penalty (OOF algorithm for blastx) [Integer] default = 0 -t Length of the largest intron allowed in a translated nucleotide sequence when linking multiple distinct alignments. (0 invokes default behavior; a negative value disables linking.) [Integer] default = 0 -B Number of concatenated queries, for blastn and tblastn [Integer] Optional default = 0 -V Force use of the legacy BLAST engine [T/F] Optional default = F -C Use composition-based score adjustments for blastp or tblastn: As first character: D or d: default (equivalent to T) 0 or F or f: no composition-based statistics 2 or T or t: Composition-based score adjustments as in Bioinformatics 21:902-911, 1: Composition-based statistics as in NAR 29:2994-3005, 2001 2005, conditioned on sequence properties 3: Composition-based score adjustment as in Bioinformatics 21:902-911, 2005, unconditionally For programs other than tblastn, must either be absent or be D, F or 0. As second character, if first character is equivalent to 1, 2, or 3: U or u: unified p-value combining alignment p-value and compositional p-value in round 1 only [String] default = D -s Compute locally optimal Smith-Waterman alignments (This option is only available for gapped tblastn.) [T/F] default = F */ class BlastTaskSettings { public: BlastTaskSettings(); void reset(); QString programName; //-p Program Name [String] QString databaseNameAndPath; //-d database [String] QString filter; //-F Filter query sequence (DUST with blastn, SEG with others) [String] : default = T float expectValue; //-e Expectation value [Real] : default = 10.0 bool megablast; //-n MegaBlast search [T/F] int wordSize; //-W Word size, default if zero (blastn 11, megablast 28, all others 3) [Integer] up to 99 int gapOpenCost; //-G Cost to open a gap (-1 invokes default behavior) [Integer] int gapExtendCost; //-E Cost to extend a gap (-1 invokes default behavior) [Integer] bool isDefaultCosts; bool isGappedAlignment; //-g Perform gapped alignment (not available with tblastx) //only for nucleotide sequence int mismatchPenalty; //-q Penalty for a nucleotide mismatch (blastn only) [Integer] int matchReward; //-r Reward for a nucleotide match (blastn only) [Integer] bool isDefautScores; //only for protein sequence QString matrix; //-M Matrix [String] : default = BLOSUM62 bool isDefaultMatrix; //X dropoff int xDropoffGA; //-X X dropoff value for gapped alignment (in bits) blastn 30, megablast 20, tblastx 0, all others 15 [Integer] float xDropoffUnGA; //-y X dropoff value for ungapped extensions in bits blastn 20, megablast 10, all others 7 [Real] int xDropoffFGA; //-Z X dropoff value for final gapped alignment in bits blastn/megablast 100, tblastx 0, all others 25 [Integer] int windowSize; //-A Multiple Hits window size, default if zero (blastn/megablast 0, all others 40 [Integer] bool isDefaultThreshold; float threshold; //-f Threshold for extending hits, default if zero blastp 11, blastn 0, blastx 12, tblastn 13 tblastx 13, megablast 0 [Real] QString queryFile; //-i Query File [File In] QByteArray querySequence; QString outputResFile; //Output file with annotations QString outputOriginalFile; //-o BLAST report Output File [File Out] Optional int outputType; //-m Type of BLAST report Output File [File Out] Optional int numberOfProcessors; //-a Number of processors to use [Integer] int numberOfHits; //-K Number of best hits from a region to keep. Off by default. If used a value of 100 is recommended. bool isNucleotideSeq; DNAAlphabet* alphabet; //settings for annotations bool needCreateAnnotations; AnnotationTableObject* aobj; QString groupName; int offsInGlobalSeq; }; } #endif // _U2_BLAST_TASK_SETTINGS_H ugene-1.9.8/src/plugins/external_tool_support/src/utils/ExportTasks.cpp0000644000175000017500000000677111651544323025176 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "ExportTasks.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include namespace U2 { ////////////////////////////////////////////////////////////////////////// // DNAExportAlignmentTask SaveAlignmentTask::SaveAlignmentTask(const MAlignment& _ma, const QString& _fileName, DocumentFormatId _f) : Task("", TaskFlag_None), ma(_ma), fileName(_fileName), format(_f) { GCOUNTER( cvar, tvar, "ExportAlignmentTask" ); setTaskName(tr("Export alignment to '%1'").arg(QFileInfo(fileName).fileName())); setVerboseLogMode(true); assert(!ma.isEmpty()); } void SaveAlignmentTask::run() { DocumentFormatRegistry* r = AppContext::getDocumentFormatRegistry(); DocumentFormat* f = r->getFormatById(format); IOAdapterFactory* iof = AppContext::getIOAdapterRegistry()->getIOAdapterFactoryById(BaseIOAdapters::url2io(fileName)); doc.reset(f->createNewDocument(iof, fileName)); doc->addObject(new MAlignmentObject(ma)); f->storeDocument(doc.get(), stateInfo); } ////////////////////////////////////////////////////////////////////////// // export alignment 2 sequence format SaveMSA2SequencesTask::SaveMSA2SequencesTask(const MAlignment& _ma, const QString& _url, bool _trimAli, DocumentFormatId _format) : Task(tr("Export alignment to sequence: %1").arg(_url), TaskFlag_None), ma(_ma), url(_url), trimAli(_trimAli), format(_format) { GCOUNTER( cvar, tvar, "ExportMSA2SequencesTask" ); setVerboseLogMode(true); } void SaveMSA2SequencesTask::run() { DocumentFormatRegistry* r = AppContext::getDocumentFormatRegistry(); DocumentFormat* f = r->getFormatById(format); IOAdapterFactory* iof = AppContext::getIOAdapterRegistry()->getIOAdapterFactoryById(BaseIOAdapters::url2io(url)); doc.reset(f->createNewDocument(iof, url)); QList lst = MSAUtils::ma2seq(ma, trimAli); QSet usedNames; foreach(const DNASequence& s, lst) { QString name = s.getName(); if (usedNames.contains(name)) { name = TextUtils::variate(name, " ", usedNames, false, 1); } doc->addObject(new DNASequenceObject(name, s)); usedNames.insert(name); } f->storeDocument(doc.get(), stateInfo); } }//namespace ugene-1.9.8/src/plugins/external_tool_support/src/utils/BlastTaskSettings.cpp0000644000175000017500000000326111651544323026307 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "BlastTaskSettings.h" namespace U2 { BlastTaskSettings::BlastTaskSettings() { offsInGlobalSeq=0; aobj=NULL; alphabet=NULL; isNucleotideSeq=false; numberOfHits=0; isDefaultMatrix=true; isDefautScores=true; isDefaultCosts=true; isGappedAlignment=true; isDefaultThreshold=true; reset(); } void BlastTaskSettings::reset() { programName=""; databaseNameAndPath=""; expectValue=10.0; megablast=false; wordSize=11; gapOpenCost=0; gapExtendCost=0; mismatchPenalty=0; matchReward=0; matrix=""; queryFile=""; outputResFile=""; numberOfProcessors=1; needCreateAnnotations=true; filter=""; isGappedAlignment=true; xDropoffGA=0; xDropoffUnGA=0; xDropoffFGA=0; windowSize=0; threshold=0; isDefaultThreshold=true; } }//namespace ugene-1.9.8/src/plugins/external_tool_support/src/utils/ExportTasks.h0000644000175000017500000000374611651544323024642 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_EXPORT_PLUGIN_TASKS_H_ #define _U2_EXPORT_PLUGIN_TASKS_H_ #include #include #include #include #include namespace U2 { /** A task to save alignment to CLUSTAL */ class SaveAlignmentTask : public Task { Q_OBJECT public: SaveAlignmentTask(const MAlignment& ma, const QString& fileName, DocumentFormatId f); void run(); virtual Document* getDocument() const {return doc.get();} private: MAlignment ma; QString fileName; DocumentFormatId format; std::auto_ptr doc; }; /** A task to export alignment to FASTA */ class SaveMSA2SequencesTask : public Task { Q_OBJECT public: SaveMSA2SequencesTask(const MAlignment& ma, const QString& url, bool trimAli, DocumentFormatId format); void run(); virtual Document* getDocument() const {return doc.get();} private: MAlignment ma; QString url; bool trimAli; QString format; std::auto_ptr doc; }; }//namespace #endif ugene-1.9.8/src/plugins/external_tool_support/src/utils/ExternalToolSupportAction.h0000644000175000017500000000277411651544323027526 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_EXTERNAL_TOOL_SUPPORT_ACTION_H #define _U2_EXTERNAL_TOOL_SUPPORT_ACTION_H #include #include namespace U2 { class ExternalToolSupprotAction : public GObjectViewAction { Q_OBJECT public: ExternalToolSupprotAction(QObject* p, GObjectView* v, const QString& _text, int order, const QStringList& _toolNames); ExternalToolSupprotAction(const QString& text, QObject* p, const QStringList& _toolNames); const QStringList getToolNames(){return toolNames;} private slots: void sl_pathChanged(); private: QStringList toolNames; }; }//namespace #endif // _U2_EXTERNAL_TOOL_SUPPORT_ACTION_H ugene-1.9.8/src/plugins/external_tool_support/src/utils/ExternalToolValidateTask.h0000644000175000017500000000370511651544323027263 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_EXTERNAL_TOOL_VALIDATE_TASK_H #define _U2_EXTERNAL_TOOL_VALIDATE_TASK_H #include #include namespace U2 { class ExternalToolLogParser; class ExternalToolValidateTask: public Task { Q_OBJECT public: ExternalToolValidateTask(const QString& toolName); ExternalToolValidateTask(const QString& toolName, const QString& path); ~ExternalToolValidateTask(); void prepare(); void run(); Task::ReportResult report(); void cancelProcess(); bool isValidTool() { return isValid; } QString getToolName() { return toolName; } QString getToolPath() { return program; } QString getToolVersion() { return version; } private: void parseLog(); void checkVersion(const QString& partOfLog); QStringList arguments; QString program; QProcess* externalToolProcess; QString toolName; QString expectedMessage; QRegExp checkVersionRegExp; QString version; bool isValid; QString lastErrLine; QString lastOutLine; }; }//namespace #endif // _U2_EXTERNAL_TOOL_VALIDATE_TASK_H ugene-1.9.8/src/plugins/external_tool_support/src/utils/BlastRunCommonDialog.h0000644000175000017500000000362011651544323026365 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_BLAST_RUN_COMMON_DIALOG_H #define _U2_BLAST_RUN_COMMON_DIALOG_H #include #include #include #include #include #include "BlastTaskSettings.h" namespace U2 { class BlastRunCommonDialog : public QDialog, public Ui_BlastAllSupportDialog { Q_OBJECT public: BlastRunCommonDialog(BlastTaskSettings& settings, QWidget* parent); protected slots: virtual void sl_runQuery() = 0; virtual void sl_lineEditChanged() = 0; void sl_onBrowseDatabasePath();//= void sl_onProgNameChange(int i);//= void sl_onMatchScoresChanged(int i);//= void sl_onMatrixChanged(int i);//= void sl_megablastChecked();//= void sl_restoreDefault();//= protected: void getSettings(BlastTaskSettings& settings); BlastTaskSettings& settings; bool needRestoreDefault; CreateAnnotationWidgetController* ca_c; }; }//namespace #endif // _U2_BLAST_RUN_COMMON_DIALOG_H ugene-1.9.8/src/plugins/external_tool_support/src/utils/BlastRunCommonDialog.cpp0000644000175000017500000004252211651544323026724 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "BlastRunCommonDialog.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include namespace U2 { //////////////////////////////////////// //BlastAllSupportRunCommonDialog BlastRunCommonDialog::BlastRunCommonDialog(BlastTaskSettings& _settings, QWidget* _parent) : QDialog(_parent), settings(_settings) { setupUi(this); //I don`t know what this in local BLAST phiPatternEdit->hide(); phiPatternLabel->hide(); //set avaliable number of threads numberOfCPUSpinBox->setMaximum(AppContext::getAppSettings()->getAppResourcePool()->getIdealThreadCount()); numberOfCPUSpinBox->setValue(AppContext::getAppSettings()->getAppResourcePool()->getIdealThreadCount()); //Connecting people connect(programName,SIGNAL(currentIndexChanged(int)),SLOT(sl_onProgNameChange(int))); connect(databaseToolButton,SIGNAL(clicked()),SLOT(sl_onBrowseDatabasePath())); connect(databasePathLineEdit,SIGNAL(textChanged(QString)),SLOT(sl_lineEditChanged())); connect(baseNameLineEdit,SIGNAL(textChanged(QString)),SLOT(sl_lineEditChanged())); connect(matrixComboBox,SIGNAL(currentIndexChanged(int)),SLOT(sl_onMatrixChanged(int))); sl_onMatrixChanged(0); connect(scoresComboBox,SIGNAL(currentIndexChanged(int)),SLOT(sl_onMatchScoresChanged(int))); sl_onMatchScoresChanged(0); connect(megablastCheckBox,SIGNAL(toggled(bool)),SLOT(sl_megablastChecked())); connect(okButton,SIGNAL(clicked()),SLOT(sl_runQuery())); connect(restoreButton,SIGNAL(clicked()),SLOT(sl_restoreDefault())); sl_onProgNameChange(0); okButton->setEnabled(false); } void BlastRunCommonDialog::sl_onMatchScoresChanged(int index){ Q_UNUSED(index); if(!scoresComboBox->isVisible()){ return; } settings.matchReward=scoresComboBox->currentText().split(" ").at(0).toInt(); settings.mismatchPenalty=scoresComboBox->currentText().split(" ").at(1).toInt(); //For help see http://www.ncbi.nlm.nih.gov/staff/tao/URLAPI/blastall/blastall_node76.html //Last values is default if((scoresComboBox->currentText() == "1 -4") || (scoresComboBox->currentText() == "1 -3")){//-G 1 -E 2; -G 0 -E 2;-G 2 -E 1; -G 1 -E 1; -G 2 -E 2 costsComboBox->clear(); costsComboBox->addItem("2 2"); costsComboBox->addItem("1 2"); costsComboBox->addItem("0 2"); costsComboBox->addItem("2 1"); costsComboBox->addItem("1 1"); }else if(scoresComboBox->currentText() == "1 -2"){//-G 1 -E 2; -G 0 -E 2; -G 3 -E 1; -G 2 -E 1; -G 1 -E 1; -G 2 -E 2 costsComboBox->clear(); costsComboBox->addItem("2 2"); costsComboBox->addItem("1 2"); costsComboBox->addItem("0 2"); costsComboBox->addItem("3 1"); costsComboBox->addItem("2 1"); costsComboBox->addItem("1 1"); }else if(scoresComboBox->currentText() == "1 -1"){//-G 3 -E 2; -G 2 -E 2; -G 1 -E 2; -G 0 -E 2; -G 4 -E 1; -G 3 -E 1; -G 2 -E 1; -G 4 -E 2 :Not supported megablast costsComboBox->clear(); costsComboBox->addItem("4 2"); costsComboBox->addItem("3 2"); costsComboBox->addItem("2 2"); costsComboBox->addItem("1 2"); costsComboBox->addItem("0 2"); costsComboBox->addItem("4 1"); costsComboBox->addItem("3 1"); costsComboBox->addItem("2 1"); }else if((scoresComboBox->currentText() == "2 -7") || (scoresComboBox->currentText() == "2 -5")){//-G 2 -E 4; -G 0 -E 4; -G 4 -E 2; -G 2 -E 2; -G 4 -E 4 costsComboBox->clear(); costsComboBox->addItem("4 4"); costsComboBox->addItem("2 4"); costsComboBox->addItem("0 4"); costsComboBox->addItem("4 2"); costsComboBox->addItem("2 2"); }else if(scoresComboBox->currentText() == "2 -3"){//-G 4 -E 4; -G 2 -E 4; -G 0 -E 4; -G 3 -E 3; -G 6 -E 2; -G 5 -E 2; -G 4 -E 2; -G 2 -E 2, -G 6 -E 4 costsComboBox->clear(); costsComboBox->addItem("6 4"); costsComboBox->addItem("4 4"); costsComboBox->addItem("2 4"); costsComboBox->addItem("0 4"); costsComboBox->addItem("3 3"); costsComboBox->addItem("6 2"); costsComboBox->addItem("5 2"); costsComboBox->addItem("4 2"); costsComboBox->addItem("2 2"); }else if((scoresComboBox->currentText() == "4 -5") || (scoresComboBox->currentText() == "5 -4")){//-G 6 -E 5; -G 5 -E 5; -G 4 -E 5; -G 3 -E 5; -G 12 -E 8 costsComboBox->clear(); costsComboBox->addItem("12 8"); costsComboBox->addItem("6 5"); costsComboBox->addItem("5 5"); costsComboBox->addItem("4 5"); costsComboBox->addItem("3 5"); }else{ assert(0); } } void BlastRunCommonDialog::sl_onMatrixChanged(int index){ Q_UNUSED(index); if(!matrixComboBox->isVisible()){ return; } settings.matrix=matrixComboBox->currentText(); //For help see http://www.ncbi.nlm.nih.gov/staff/tao/URLAPI/blastall/blastall_node77.html //Last values is default if(matrixComboBox->currentText() == "PAM30"){//-G 5 -E 2; -G 6 -E 2; -G 7 -E 2; -G 8 -E 1; -G 10 -E 1; -G 9 -E 1 costsComboBox->clear(); costsComboBox->addItem("9 1"); costsComboBox->addItem("5 2"); costsComboBox->addItem("6 2"); costsComboBox->addItem("7 2"); costsComboBox->addItem("8 1"); costsComboBox->addItem("10 1"); }else if(matrixComboBox->currentText() == "PAM70"){//-G 6 -E 2; -G 7 -E 2; -G 8 -E 2; -G 9 -E 2; -G 11 -E 1; -G 10 -E 1 costsComboBox->clear(); costsComboBox->addItem("10 1"); costsComboBox->addItem("6 2"); costsComboBox->addItem("7 2"); costsComboBox->addItem("8 2"); costsComboBox->addItem("9 2"); costsComboBox->addItem("11 1"); }else if(matrixComboBox->currentText() == "BLOSUM45"){//-G 10 -E 3; -G 11 -E 3; -G 12 -E 3; -G 12 -E 2; -G 13 -E 2, -G 14 -E 2; //-G 16 -E 2; -G 15 -E 1; -G 16 -E 1; -G 17 -E 1; -G 18 -E 1; -G 19 -E 1; -G 15 -E 2 costsComboBox->clear(); costsComboBox->addItem("15 2"); costsComboBox->addItem("10 3"); costsComboBox->addItem("11 3"); costsComboBox->addItem("12 3"); costsComboBox->addItem("12 2"); costsComboBox->addItem("13 2"); costsComboBox->addItem("14 2"); costsComboBox->addItem("16 2"); costsComboBox->addItem("15 1"); costsComboBox->addItem("16 1"); costsComboBox->addItem("17 1"); costsComboBox->addItem("18 1"); costsComboBox->addItem("19 1"); }else if(matrixComboBox->currentText() == "BLOSUM62"){//-G 7 -E 2; -G 8 -E 2; -G 9 -E 2; -G 10 -E 1; -G 12 -E 1; -G 11 -E 1 costsComboBox->clear(); costsComboBox->addItem("11 1"); costsComboBox->addItem("7 2"); costsComboBox->addItem("8 2"); costsComboBox->addItem("9 2"); costsComboBox->addItem("10 1"); costsComboBox->addItem("12 1"); }else if(matrixComboBox->currentText() == "BLOSUM80"){//-G 6 -E 2; -G 7 -E 2; -G 8 -E 2; -G 9 -E 1; -G 11 -E 1; -G 10 -E 1 costsComboBox->clear(); costsComboBox->addItem("10 1"); costsComboBox->addItem("6 2"); costsComboBox->addItem("7 2"); costsComboBox->addItem("8 2"); costsComboBox->addItem("9 1"); costsComboBox->addItem("11 1"); }else{ assert(0); } } void BlastRunCommonDialog::sl_restoreDefault(){ needRestoreDefault=true; // sl_onProgNameChange(0); megablastCheckBox->setChecked(false); sl_megablastChecked(); sl_onMatchScoresChanged(0); sl_onMatrixChanged(0); evalueSpinBox->setValue(10); needRestoreDefault=false; } void BlastRunCommonDialog::sl_megablastChecked(){ if(megablastCheckBox->isChecked()){ if(wordSizeSpinBox->value()<12 || needRestoreDefault){ wordSizeSpinBox->setValue(28); } wordSizeSpinBox->setMaximum(100); wordSizeSpinBox->setMinimum(12); xDropoffGASpinBox->setValue(20); xDropoffUnGASpinBox->setValue(20); }else{ if(wordSizeSpinBox->value()<7 || needRestoreDefault){ wordSizeSpinBox->setValue(11); } wordSizeSpinBox->setMaximum(100); wordSizeSpinBox->setMinimum(7); xDropoffGASpinBox->setValue(30); xDropoffUnGASpinBox->setValue(10); } } void BlastRunCommonDialog::sl_onBrowseDatabasePath(){ LastOpenDirHelper lod("Database Directory"); QString name; lod.url = name = QFileDialog::getExistingDirectory(NULL, tr("Select a directory with database files"), lod.dir); if (!name.isEmpty()) { databasePathLineEdit->setText(name); } databasePathLineEdit->setFocus(); } void BlastRunCommonDialog::sl_onProgNameChange(int index){ Q_UNUSED(index); settings.programName=programName->currentText(); if(programName->currentText() == "blastn"){//nucl programName->setToolTip(tr("Direct nucleotide alignment")); gappedAlignmentCheckBox->setEnabled(true); thresholdSpinBox->setValue(0); }else if(programName->currentText() == "blastp"){//amino programName->setToolTip(tr("Direct protein alignment")); gappedAlignmentCheckBox->setEnabled(true); thresholdSpinBox->setValue(11); }else if(programName->currentText() == "blastx"){//nucl programName->setToolTip(tr("Protein alignment, input nucleotide is translated input protein before the search")); gappedAlignmentCheckBox->setEnabled(true); thresholdSpinBox->setValue(12); }else if(programName->currentText() == "tblastn"){//amino programName->setToolTip(tr("Protein alignment, nucleotide database is translated input protein before the search")); gappedAlignmentCheckBox->setEnabled(true); thresholdSpinBox->setValue(13); }else if(programName->currentText() == "tblastx"){//nucl programName->setToolTip(tr("Protein alignment, both input query and database are translated before the search")); gappedAlignmentCheckBox->setEnabled(false); thresholdSpinBox->setValue(13); }else{ assert(0); } if(programName->currentText() == "blastn"){ megablastCheckBox->setEnabled(true); if(megablastCheckBox->isChecked()){ wordSizeSpinBox->setValue(28); wordSizeSpinBox->setMaximum(100); wordSizeSpinBox->setMinimum(12); }else{ wordSizeSpinBox->setValue(11); wordSizeSpinBox->setMaximum(100); wordSizeSpinBox->setMinimum(7); } windowSizeSpinBox->setValue(0); matchScoreLabel->show(); scoresComboBox->show(); matrixLabel->hide(); matrixComboBox->hide(); serviceLabel->hide(); serviceComboBox->hide(); thresholdSpinBox->hide(); thresholdLabel->hide(); sl_onMatchScoresChanged(0); }else{ megablastCheckBox->setEnabled(false); wordSizeSpinBox->setValue(3); wordSizeSpinBox->setMaximum(3); wordSizeSpinBox->setMinimum(2); windowSizeSpinBox->setValue(40); matchScoreLabel->hide(); scoresComboBox->hide(); matrixLabel->show(); matrixComboBox->show(); serviceLabel->show(); serviceComboBox->show(); thresholdSpinBox->show(); thresholdLabel->show(); sl_onMatrixChanged(0); } //set X dropoff values if(programName->currentText() == "blastn"){ megablastCheckBox->setEnabled(true); if(megablastCheckBox->isChecked()){ xDropoffGASpinBox->setValue(20); xDropoffUnGASpinBox->setValue(10); }else{ xDropoffGASpinBox->setValue(30); xDropoffUnGASpinBox->setValue(20); } xDropoffFGASpinBox->setValue(100); xDropoffGASpinBox->setEnabled(true); xDropoffFGASpinBox->setEnabled(true); }else if (programName->currentText() == "tblastx"){ xDropoffGASpinBox->setValue(0); xDropoffGASpinBox->setEnabled(false); xDropoffUnGASpinBox->setValue(7); xDropoffFGASpinBox->setValue(0); xDropoffFGASpinBox->setEnabled(false); }else{ xDropoffGASpinBox->setValue(15); xDropoffUnGASpinBox->setValue(7); xDropoffFGASpinBox->setValue(25); xDropoffGASpinBox->setEnabled(true); xDropoffFGASpinBox->setEnabled(true); } } void BlastRunCommonDialog::getSettings(BlastTaskSettings &localSettings){ localSettings.programName=programName->currentText(); localSettings.databaseNameAndPath=databasePathLineEdit->text()+"/"+baseNameLineEdit->text(); localSettings.expectValue=evalueSpinBox->value(); localSettings.wordSize=wordSizeSpinBox->value(); localSettings.megablast=megablastCheckBox->isChecked(); localSettings.numberOfHits=numberOfHitsSpinBox->value(); localSettings.numberOfProcessors=numberOfCPUSpinBox->value(); localSettings.gapOpenCost=costsComboBox->currentText().split(" ").at(0).toInt(); localSettings.gapExtendCost=costsComboBox->currentText().split(" ").at(1).toInt(); //setup filters if(lowComplexityFilterCheckBox->isChecked()){ localSettings.filter="L"; } if(repeatsCheckBox->isChecked()){ localSettings.filter=localSettings.filter.isEmpty() ? "R" : localSettings.filter+"; R"; } // if(lowerCaseCheckBox->isChecked()){ // settings.filter=settings.filter.isEmpty() ? "???" : settings.filter+"; ???"; // } if(lookupMaskCheckBox->isChecked()){ localSettings.filter=localSettings.filter.isEmpty() ? "m" : "m "+localSettings.filter; } if(localSettings.isNucleotideSeq){ if((((scoresComboBox->currentText() == "1 -4") || (scoresComboBox->currentText() == "1 -3")) && costsComboBox->currentText()=="2 2") || //-G 2 -E 2 ((scoresComboBox->currentText() == "1 -2") && costsComboBox->currentText()=="2 2") || //-G 2 -E 2 ((scoresComboBox->currentText() == "1 -1") && costsComboBox->currentText()=="4 2") || //-G 4 -E 2 (((scoresComboBox->currentText() == "2 -7") || (scoresComboBox->currentText() == "2 -5"))&& costsComboBox->currentText()=="4 4") || //-G 4 -E 4 ((scoresComboBox->currentText() == "2 -3") && costsComboBox->currentText()=="6 4") || //-G 6 -E 4 (((scoresComboBox->currentText() == "4 -5") || (scoresComboBox->currentText() == "5 -4")) && costsComboBox->currentText()=="12 8"))//-G 12 -E 8 { localSettings.isDefaultCosts=true; }else{ localSettings.isDefaultCosts=false; } localSettings.isDefautScores=(scoresComboBox->currentText() == "1 -3"); }else{ if(((matrixComboBox->currentText() == "PAM30") && costsComboBox->currentText()=="9 1") || //-G 9 -E 1 ((matrixComboBox->currentText() == "PAM70") && costsComboBox->currentText()=="10 1") || //-G 10 -E 1 ((matrixComboBox->currentText() == "BLOSUM45") && costsComboBox->currentText()=="15 2") || ((matrixComboBox->currentText() == "BLOSUM62") && costsComboBox->currentText()=="11 1") || ((matrixComboBox->currentText() == "BLOSUM80") && costsComboBox->currentText()=="10 1")) { localSettings.isDefaultCosts=true; }else{ localSettings.isDefaultCosts=false; } localSettings.isDefaultMatrix=(matrixComboBox->currentText() == "BLOSUM62"); } localSettings.isGappedAlignment=gappedAlignmentCheckBox->isChecked(); localSettings.windowSize=windowSizeSpinBox->value(); localSettings.threshold=thresholdSpinBox->value(); localSettings.xDropoffGA=xDropoffGASpinBox->value(); localSettings.xDropoffUnGA=xDropoffUnGASpinBox->value(); localSettings.xDropoffFGA=xDropoffFGASpinBox->value(); if((localSettings.programName == "blastn" && localSettings.threshold != 0) || (localSettings.programName == "blastp" && localSettings.threshold != 11) || (localSettings.programName == "blastx" && localSettings.threshold != 12) || (localSettings.programName == "tblastn" && localSettings.threshold != 13) || (localSettings.programName == "tblastx" && localSettings.threshold != 13)){ localSettings.isDefaultThreshold=false; } } }//namespace ugene-1.9.8/src/plugins/external_tool_support/src/utils/ExternalToolValidateTask.cpp0000644000175000017500000001076411651544323027621 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "ExternalToolValidateTask.h" #include #include #include #include namespace U2 { ExternalToolValidateTask::ExternalToolValidateTask(const QString& _toolName) : Task(_toolName + " validate task", TaskFlag_None), toolName(_toolName) { program=AppContext::getExternalToolRegistry()->getByName(toolName)->getPath(); assert(program!=""); arguments=AppContext::getExternalToolRegistry()->getByName(toolName)->getValidationArguments(); expectedMessage=AppContext::getExternalToolRegistry()->getByName(toolName)->getValidMessage(); if(expectedMessage==""){ assert(NULL); } coreLog.trace("Creating validation task for: " + toolName); externalToolProcess=NULL; isValid=false; checkVersionRegExp=AppContext::getExternalToolRegistry()->getByName(toolName)->getVersionRegExp(); version="unknown"; } ExternalToolValidateTask::ExternalToolValidateTask(const QString& _toolName, const QString& path) : Task(_toolName + " validate task", TaskFlag_None), toolName(_toolName) { program=path; assert(program!=""); arguments=AppContext::getExternalToolRegistry()->getByName(toolName)->getValidationArguments(); expectedMessage=AppContext::getExternalToolRegistry()->getByName(toolName)->getValidMessage(); if(expectedMessage==""){ assert(NULL); } coreLog.trace("Creating validation task for: " + toolName); externalToolProcess=NULL; isValid=false; checkVersionRegExp=AppContext::getExternalToolRegistry()->getByName(toolName)->getVersionRegExp(); version="unknown"; } ExternalToolValidateTask::~ExternalToolValidateTask(){ delete externalToolProcess; externalToolProcess=NULL; } void ExternalToolValidateTask::prepare(){ algoLog.trace("Program executable: "+program); algoLog.trace("Program arguments: "+arguments.join(" ")); } void ExternalToolValidateTask::run(){ externalToolProcess=new QProcess(); externalToolProcess->start(program, arguments); if(!externalToolProcess->waitForStarted(3000)){ stateInfo.setError(tr("It is possible that the specified executable file for %1 tool is invalid. Tool does not start.").arg(toolName)); isValid=false; return; } while(!externalToolProcess->waitForFinished(1000)){ if (isCanceled()) { cancelProcess(); } } parseLog(); } Task::ReportResult ExternalToolValidateTask::report(){ if(!isValid && !stateInfo.hasError()){ stateInfo.setError(tr("It is possible that the specified executable file for %1 tool is invalid. Can not find expected message.").arg(toolName)); } return ReportResult_Finished; } void ExternalToolValidateTask::cancelProcess(){ externalToolProcess->kill(); } void ExternalToolValidateTask::parseLog(){ QString log=QString(externalToolProcess->readAllStandardOutput()); if(!log.isEmpty()){ if(log.contains(expectedMessage)){ isValid=true; checkVersion(log); } } QString errLog=QString(externalToolProcess->readAllStandardError()); if(!errLog.isEmpty()){ if(errLog.contains(expectedMessage)){ isValid=true; checkVersion(errLog); } } } void ExternalToolValidateTask::checkVersion(const QString &partOfLog){ QStringList lastPartOfLog=partOfLog.split(QRegExp("(\n|\r)")); foreach(QString buf, lastPartOfLog){ if(buf.contains(checkVersionRegExp)){ assert(checkVersionRegExp.indexIn(buf)>-1); checkVersionRegExp.indexIn(buf); version=checkVersionRegExp.cap(1); return; } } } }//namespace ugene-1.9.8/src/plugins/external_tool_support/src/blast_plus/0000755000175000017500000000000011651544323023200 5ustar ilyailyaugene-1.9.8/src/plugins/external_tool_support/src/blast_plus/BlastXPlusSupportTask.h0000644000175000017500000000323411651544323027634 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_BLASTXPLUS_SUPPORT_TASK_H #define _U2_BLASTXPLUS_SUPPORT_TASK_H #include #include #include #include #include #include #include "utils/ExportTasks.h" #include #include #include "ExternalToolRunTask.h" #include "BlastPlusSupportCommonTask.h" #include #include namespace U2 { class BlastXPlusSupportTask : public BlastPlusSupportCommonTask { Q_OBJECT public: BlastXPlusSupportTask(const BlastTaskSettings& settings):BlastPlusSupportCommonTask(settings){} virtual ExternalToolRunTask* createBlastPlusTask(); }; }//namespace #endif // _U2_BLASTXPLUS_SUPPORT_TASK_H ugene-1.9.8/src/plugins/external_tool_support/src/blast_plus/RPSBlastSupportTask.h0000644000175000017500000000336311651544323027230 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_RPS_BLAST_SUPPORT_TASK_H_ #define _U2_RPS_BLAST_SUPPORT_TASK_H_ #include "BlastPlusSupportCommonTask.h" #include namespace U2 { class RPSBlastSupportTask : public BlastPlusSupportCommonTask { Q_OBJECT public: RPSBlastSupportTask(const BlastTaskSettings& settings) : BlastPlusSupportCommonTask(settings) {} virtual ExternalToolRunTask* createBlastPlusTask(); }; class LocalCDSearch : public CDSearchResultListener { public: LocalCDSearch(const CDSearchSettings& settings); virtual Task* getTask() const { return task; } virtual QList getCDSResults() const; private: RPSBlastSupportTask* task; }; class CDSearchLocalTaskFactory : public CDSearchFactory { public: virtual CDSearchResultListener* createCDSearch(const CDSearchSettings& settings) const { return new LocalCDSearch(settings); } }; } //namespace #endif ugene-1.9.8/src/plugins/external_tool_support/src/blast_plus/RPSBlastSupportTask.cpp0000644000175000017500000000372711651544323027567 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "RPSBlastSupportTask.h" #include "BlastPlusSupport.h" namespace U2 { ExternalToolRunTask* RPSBlastSupportTask::createBlastPlusTask() { QStringList arguments; arguments << "-db" << settings.databaseNameAndPath; arguments << "-evalue" << QString::number(settings.expectValue); arguments << "-query" << url; arguments << "-outfmt" << "5"; //Set output file format to xml arguments << "-out" << url+".xml"; //settings.outputRepFile; algoLog.trace("RPSBlast arguments: "+arguments.join(" ")); logParser=new ExternalToolLogParser; return new ExternalToolRunTask(RPSBLAST_TOOL_NAME, arguments, logParser); } LocalCDSearch::LocalCDSearch(const CDSearchSettings& settings) { BlastTaskSettings stngs; stngs.databaseNameAndPath = settings.localDbFolder + "/" + settings.dbName; stngs.querySequence = settings.query; stngs.expectValue = settings.ev; stngs.alphabet = settings.alp; stngs.needCreateAnnotations = false; task = new RPSBlastSupportTask(stngs); } QList LocalCDSearch::getCDSResults() const { return task->getResultedAnnotations(); } } //namespace ugene-1.9.8/src/plugins/external_tool_support/src/blast_plus/BlastNPlusSupportTask.h0000644000175000017500000000323411651544323027622 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_BLASTNPLUS_SUPPORT_TASK_H #define _U2_BLASTNPLUS_SUPPORT_TASK_H #include #include #include #include #include #include #include "utils/ExportTasks.h" #include #include #include "ExternalToolRunTask.h" #include "BlastPlusSupportCommonTask.h" #include #include namespace U2 { class BlastNPlusSupportTask : public BlastPlusSupportCommonTask { Q_OBJECT public: BlastNPlusSupportTask(const BlastTaskSettings& settings):BlastPlusSupportCommonTask(settings){} virtual ExternalToolRunTask* createBlastPlusTask(); }; }//namespace #endif // _U2_BLASTNPLUS_SUPPORT_TASK_H ugene-1.9.8/src/plugins/external_tool_support/src/blast_plus/BlastPlusSupport.h0000644000175000017500000000355411651544323026666 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_BLASTPLUS_SUPPORT_H #define _U2_BLASTPLUS_SUPPORT_H #include #include #define BLASTN_TOOL_NAME "BlastN" #define BLASTP_TOOL_NAME "BlastP" #define BLASTX_TOOL_NAME "BlastX" #define TBLASTN_TOOL_NAME "TBlastN" #define TBLASTX_TOOL_NAME "TBlastX" #define RPSBLAST_TOOL_NAME "RPSBlast" namespace U2 { class BlastPlusSupport : public ExternalTool { Q_OBJECT public: BlastPlusSupport(const QString& name, const QString& path = ""); public slots: void sl_runWithExtFileSpecify(); private: QString lastDBPath; QString lastDBName; }; class BlastPlusSupportContext: public GObjectViewWindowContext { Q_OBJECT public: BlastPlusSupportContext(QObject* p); protected slots: void sl_showDialog(); protected: virtual void initViewContext(GObjectView* view); virtual void buildMenu(GObjectView* view, QMenu* m); private: QStringList toolList; QString lastDBPath; QString lastDBName; }; }//namespace #endif // _U2_BLASTPLUS_SUPPORT_H ugene-1.9.8/src/plugins/external_tool_support/src/blast_plus/BlastXPlusSupportTask.cpp0000644000175000017500000001003611651544323030165 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "BlastXPlusSupportTask.h" #include "BlastPlusSupport.h" #include #include #include #include #include #include #include #include #include #include //#include namespace U2 { ExternalToolRunTask* BlastXPlusSupportTask::createBlastPlusTask(){ QStringList arguments; //arguments <<"-p"<< settings.programName; //taskname // if(!settings.filter.isEmpty()){ // arguments <<"-F"< * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_BLASTPLUS_SUPPORT_TASK_H #define _U2_BLASTPLUS_SUPPORT_TASK_H #include #include #include #include #include #include #include "utils/ExportTasks.h" #include #include #include "ExternalToolRunTask.h" #include "utils/BlastTaskSettings.h" #include #include namespace U2 { class BlastPlusSupportCommonTask : public Task { Q_OBJECT public: BlastPlusSupportCommonTask(const BlastTaskSettings& settings); void prepare(); QList onSubTaskFinished(Task* subTask); Task::ReportResult report(); QList getResultedAnnotations() const; BlastTaskSettings getSettings() const; virtual ExternalToolRunTask* createBlastPlusTask() = 0; protected: BlastTaskSettings settings; ExternalToolLogParser* logParser; QString url; private: SaveDocumentTask* saveTemporaryDocumentTask; ExternalToolRunTask* blastPlusTask; DNASequenceObject* sequenceObject; Document* tmpDoc; QList result; void parseResult(); void parseHit(const QDomNode &xml); void parseHsp(const QDomNode &xml,const QString &id, const QString &def, const QString &accession); }; class BlastPlusSupportMultiTask : public Task { Q_OBJECT public: BlastPlusSupportMultiTask(QList& settingsList, QString& url); void prepare(); QList onSubTaskFinished(Task* subTask); Task::ReportResult report(); QString generateReport() const; private: QList settingsList; Document* doc; QString url; }; }//namespace #endif // _U2_BLASTPLUS_SUPPORT_TASK_H ugene-1.9.8/src/plugins/external_tool_support/src/blast_plus/TBlastNPlusSupportTask.cpp0000644000175000017500000001004211651544323030274 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "TBlastNPlusSupportTask.h" #include "BlastPlusSupport.h" #include #include #include #include #include #include #include #include #include #include //#include namespace U2 { ExternalToolRunTask* TBlastNPlusSupportTask::createBlastPlusTask(){ QStringList arguments; //arguments <<"-p"<< settings.programName; //taskname // if(!settings.filter.isEmpty()){ // arguments <<"-F"< * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "BlastNPlusSupportTask.h" #include "BlastPlusSupport.h" #include #include #include #include #include #include #include #include #include #include //#include namespace U2 { ExternalToolRunTask* BlastNPlusSupportTask::createBlastPlusTask(){ QStringList arguments; //arguments <<"-p"<< settings.programName; //taskname // if(!settings.filter.isEmpty()){ // arguments <<"-F"< * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_TBLASTXPLUS_SUPPORT_TASK_H #define _U2_TBLASTXPLUS_SUPPORT_TASK_H #include #include #include #include #include #include #include "utils/ExportTasks.h" #include #include #include "ExternalToolRunTask.h" #include "BlastPlusSupportCommonTask.h" #include #include namespace U2 { class TBlastXPlusSupportTask : public BlastPlusSupportCommonTask { Q_OBJECT public: TBlastXPlusSupportTask(const BlastTaskSettings& settings):BlastPlusSupportCommonTask(settings){} virtual ExternalToolRunTask* createBlastPlusTask(); }; }//namespace #endif // _U2_TBLASTXPLUS_SUPPORT_TASK_H ugene-1.9.8/src/plugins/external_tool_support/src/blast_plus/TBlastXPlusSupportTask.cpp0000644000175000017500000000733211651544323030316 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "TBlastXPlusSupportTask.h" #include "BlastPlusSupport.h" #include #include #include #include #include #include #include #include #include #include //#include namespace U2 { ExternalToolRunTask* TBlastXPlusSupportTask::createBlastPlusTask(){ QStringList arguments; //arguments <<"-p"<< settings.programName; //taskname // if(!settings.filter.isEmpty()){ // arguments <<"-F"< * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_BLASTPPLUS_SUPPORT_TASK_H #define _U2_BLASTPPLUS_SUPPORT_TASK_H #include #include #include #include #include #include #include "utils/ExportTasks.h" #include #include #include "ExternalToolRunTask.h" #include "BlastPlusSupportCommonTask.h" #include #include namespace U2 { class BlastPPlusSupportTask : public BlastPlusSupportCommonTask { Q_OBJECT public: BlastPPlusSupportTask(const BlastTaskSettings& settings):BlastPlusSupportCommonTask(settings){} virtual ExternalToolRunTask* createBlastPlusTask(); }; }//namespace #endif // _U2_BLASTPPLUS_SUPPORT_TASK_H ugene-1.9.8/src/plugins/external_tool_support/src/blast_plus/BlastPlusSupportRunDialog.h0000644000175000017500000000462311651544323030471 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_BLAST_PLUS_SUPPORT_RUN_DIALOG_H #define _U2_BLAST_PLUS_SUPPORT_RUN_DIALOG_H #include #include #include #include #include #include "BlastPlusSupportCommonTask.h" #include "utils/BlastRunCommonDialog.h" namespace U2 { class BlastPlusSupportRunDialog : public BlastRunCommonDialog { Q_OBJECT public: BlastPlusSupportRunDialog(DNASequenceObject* dnaso, BlastTaskSettings& settings, QString &_lastDBPath, QString &_lastDBName, QWidget* parent); protected slots: virtual void sl_runQuery(); virtual void sl_lineEditChanged(); private: DNASequenceObject* dnaso; bool checkToolPath(); QString &lastDBPath; QString &lastDBName; }; class BlastPlusWithExtFileSpecifySupportRunDialog : public BlastRunCommonDialog { Q_OBJECT public: BlastPlusWithExtFileSpecifySupportRunDialog(QList& settingsList, QString &_lastDBPath, QString &_lastDBName, QWidget* parent); protected slots: void sl_runQuery(); void sl_lineEditChanged(); private slots: void sl_cancel(); void sl_inputFileLineEditChanged(const QString& str); void sl_inputFileLoadTaskStateChanged(); private: bool checkToolPath(); FileLineEdit* inputFileLineEdit; bool wasNoOpenProject; QList& settingsList; QList sequencesRefList; QString &lastDBPath; QString &lastDBName; }; }//namespace #endif // _U2_BLAST_PLUS_SUPPORT_RUN_DIALOG_H ugene-1.9.8/src/plugins/external_tool_support/src/blast_plus/BlastPlusWorker.h0000644000175000017500000000364411651544323026463 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_BLASTPLUS_WORKER_H_ #define _U2_BLASTPLUS_WORKER_H_ #include #include #include "BlastPlusSupportCommonTask.h" namespace U2 { namespace LocalWorkflow { class BlastPlusPrompter : public PrompterBase { Q_OBJECT public: BlastPlusPrompter(Actor* p = 0); protected: QString composeRichDoc(); }; class BlastPlusWorker : public BaseWorker { Q_OBJECT public: BlastPlusWorker(Actor* a); virtual void init(); virtual bool isReady(); virtual Task* tick(); virtual bool isDone(); virtual void cleanup(); private slots: void sl_taskFinished(); protected: CommunicationChannel *input, *output; QString resultName,transId; BlastTaskSettings cfg; }; class BlastPlusWorkerFactory : public DomainFactory { public: static const QString ACTOR_ID; static void init(); BlastPlusWorkerFactory() : DomainFactory(ACTOR_ID) {} virtual Worker* createWorker(Actor* a) {return new BlastPlusWorker(a);} }; } // Workflow namespace } // U2 namespace #endif ugene-1.9.8/src/plugins/external_tool_support/src/blast_plus/BlastPPlusSupportTask.cpp0000644000175000017500000001003711651544323030156 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "BlastPPlusSupportTask.h" #include "BlastPlusSupport.h" #include #include #include #include #include #include #include #include #include #include //#include namespace U2 { ExternalToolRunTask* BlastPPlusSupportTask::createBlastPlusTask(){ QStringList arguments; //arguments <<"-p"<< settings.programName; //taskname // if(!settings.filter.isEmpty()){ // arguments <<"-F"< * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "BlastPlusWorker.h" #include "TaskLocalStorage.h" #include "BlastPlusSupport.h" #include "BlastNPlusSupportTask.h" #include "BlastPPlusSupportTask.h" #include "BlastXPlusSupportTask.h" #include "TBlastNPlusSupportTask.h" #include "TBlastXPlusSupportTask.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include namespace U2 { namespace LocalWorkflow { /**************************** * BlastAllWorkerFactory ****************************/ const QString BlastPlusWorkerFactory::ACTOR_ID("blast-plus"); //const QString PROGRAM_NAME("programName"); //const QString DATABASE_PATH("databasePath"); //const QString DATABASE_NAME("databaseName"); //const QString EXPECT_VALUE("expectValue"); //const QString GROUP_NAME("groupName"); //const QString ORIGINAL_OUT("Blast_output"); //const QString EXT_TOOL_PATH("extToolPath"); //const QString TMP_DIR_PATH("tmpDirPath"); const QString PROGRAM_NAME("blast-type"); const QString DATABASE_PATH("db-path"); const QString DATABASE_NAME("db-name"); const QString EXPECT_VALUE("e-val"); const QString GROUP_NAME("result-name"); const QString EXT_TOOL_PATH("tool-path"); const QString TMP_DIR_PATH("temp-dir"); //Additional options const QString ORIGINAL_OUT("blast-output");//path for output file const QString OUT_TYPE("type-output");//original option -m 0-11 const QString GAPPED_ALN("gapped-aln");//Perform gapped alignment (not available with tblastx) void BlastPlusWorkerFactory::init() { QList p; QList a; Descriptor ind(BasePorts::IN_SEQ_PORT_ID(), BlastPlusWorker::tr("Input sequence"), BlastPlusWorker::tr("Sequence for which annotations is searched.")); Descriptor oud(BasePorts::OUT_ANNOTATIONS_PORT_ID(), BlastPlusWorker::tr("Annotations"), BlastPlusWorker::tr("Found annotations.")); QMap inM; inM[BaseSlots::DNA_SEQUENCE_SLOT()] = BaseTypes::DNA_SEQUENCE_TYPE(); p << new PortDescriptor(ind, DataTypePtr(new MapDataType("blast.plus.seq", inM)), true /*input*/); QMap outM; outM[BaseSlots::ANNOTATION_TABLE_SLOT()] = BaseTypes::ANNOTATION_TABLE_TYPE(); p << new PortDescriptor(oud, DataTypePtr(new MapDataType("blast.plus.annotations", outM)), false /*input*/, true /*multi*/); Descriptor pn(PROGRAM_NAME, BlastPlusWorker::tr("Search type"), BlastPlusWorker::tr("Select type of BLAST+ searches")); Descriptor dp(DATABASE_PATH, BlastPlusWorker::tr("Database Path"), BlastPlusWorker::tr("Path with database files")); Descriptor dn(DATABASE_NAME, BlastPlusWorker::tr("Database Name"), BlastPlusWorker::tr("Base name for BLAST+ DB files")); Descriptor ev(EXPECT_VALUE, BlastPlusWorker::tr("Expected value"), BlastPlusWorker::tr("This setting specifies the statistical significance threshold for reporting matches against database sequences.")); Descriptor gn(GROUP_NAME, BlastPlusWorker::tr("Annotate as"), BlastPlusWorker::tr("Name for annotations")); Descriptor etp(EXT_TOOL_PATH, BlastPlusWorker::tr("Tool Path"), BlastPlusWorker::tr("External tool path")); Descriptor tdp(TMP_DIR_PATH, BlastPlusWorker::tr("Temporary directory"), BlastPlusWorker::tr("Directory for temporary files")); Descriptor output(ORIGINAL_OUT, BlastPlusWorker::tr("BLAST output"), BlastPlusWorker::tr("Location of BLAST output file.")); Descriptor outtype(OUT_TYPE, BlastPlusWorker::tr("BLAST output type"), BlastPlusWorker::tr("Type of BLAST output file.")); Descriptor ga(GAPPED_ALN, BlastPlusWorker::tr("Gapped alignment"), BlastPlusWorker::tr("Perform gapped alignment")); a << new Attribute(pn, BaseTypes::STRING_TYPE(), true, QVariant("blastn")); a << new Attribute(dp, BaseTypes::STRING_TYPE(), true, QVariant("")); a << new Attribute(dn, BaseTypes::STRING_TYPE(), true, QVariant("")); a << new Attribute(etp, BaseTypes::STRING_TYPE(), true, QVariant("default")); a << new Attribute(tdp, BaseTypes::STRING_TYPE(), true, QVariant("default")); a << new Attribute(ev, BaseTypes::NUM_TYPE(), false, QVariant(10.00)); a << new Attribute(gn, BaseTypes::STRING_TYPE(), false, QVariant("")); Attribute* gaAttr= new Attribute(ga, BaseTypes::BOOL_TYPE(), false, QVariant(true)); gaAttr->addRelation(PROGRAM_NAME,"blastn"); gaAttr->addRelation(PROGRAM_NAME,"blastp"); gaAttr->addRelation(PROGRAM_NAME,"blastx"); gaAttr->addRelation(PROGRAM_NAME,"tblastn"); a << gaAttr; a << new Attribute(output, BaseTypes::STRING_TYPE(), false, QVariant("")); a << new Attribute(outtype, BaseTypes::STRING_TYPE(), false, QVariant("5")); Descriptor desc(ACTOR_ID, BlastPlusWorker::tr("Local BLAST+ search"), BlastPlusWorker::tr("Finds annotations for DNA sequence in local database")); ActorPrototype* proto = new IntegralBusActorPrototype(desc, p, a); QMap delegates; { QVariantMap m; m["blastn"] = "blastn"; m["blastp"] = "blastp"; m["blastx"] = "blastx"; m["tblastn"] = "tblastn"; m["tblastx"] = "tblastx"; delegates[PROGRAM_NAME] = new ComboBoxDelegate(m); } { QVariantMap m; m["minimum"] = 0.000001; m["maximum"] = 100000; m["singleStep"] = 1.0; m["decimals"] = 6; delegates[EXPECT_VALUE] = new DoubleSpinBoxDelegate(m); } { QVariantMap m; m["use"] = true; m["not use"] = false; delegates[GAPPED_ALN] = new ComboBoxDelegate(m); } { QVariantMap m; m["traditional pairwise (-outfmt 0)"] = 0; // m["query-anchored showing identities"] = 1; // m["query-anchored no identities"] = 2; // m["flat query-anchored, show identities"] = 3; // m["flat query-anchored, no identities"] = 4; m["XML (-outfmt 5)"] = 5; m["tabular (-outfmt 6)"] = 6; // m["tabular with comment lines"] = 7; // m["Text ASN.1"] = 8; // m["Binary ASN.1"] = 9; // m["Comma-separated values"] = 10; // m["BLAST archive format (ASN.1)"] = 11; delegates[OUT_TYPE] = new ComboBoxDelegate(m); } delegates[ORIGINAL_OUT] = new URLDelegate("", "out file", false); delegates[DATABASE_PATH] = new URLDelegate("", "Database Directory", false, true); delegates[EXT_TOOL_PATH] = new URLDelegate("", "executable", false); delegates[TMP_DIR_PATH] = new URLDelegate("", "TmpDir", false, true); proto->setEditor(new DelegateEditor(delegates)); proto->setPrompter(new BlastPlusPrompter()); proto->setIconPath(":external_tool_support/images/ncbi.png"); WorkflowEnv::getProtoRegistry()->registerProto(BaseActorCategories::CATEGORY_BASIC(), proto); DomainFactory* localDomain = WorkflowEnv::getDomainRegistry()->getById(LocalDomainFactory::ID); localDomain->registerEntry(new BlastPlusWorkerFactory()); } /**************************** * BlastPlusPrompter ****************************/ BlastPlusPrompter::BlastPlusPrompter(Actor* p) : PrompterBase(p) { } QString BlastPlusPrompter::composeRichDoc() { IntegralBusPort* input = qobject_cast(target->getPort(BasePorts::IN_SEQ_PORT_ID())); Actor* producer = input->getProducer(BaseSlots::DNA_SEQUENCE_SLOT().getId()); QString unsetStr = ""+tr("unset")+""; QString producerName = tr(" from %1").arg(producer ? producer->getLabel() : unsetStr); QString doc = tr("For sequence %1 find annotations in database %2") .arg(producerName).arg(getHyperlink(DATABASE_NAME, getRequiredParam(DATABASE_NAME))); return doc; } /**************************** * BlastPlusWorker ****************************/ BlastPlusWorker::BlastPlusWorker(Actor* a) : BaseWorker(a), input(NULL), output(NULL) { } void BlastPlusWorker::init() { input = ports.value(BasePorts::IN_SEQ_PORT_ID()); output = ports.value(BasePorts::OUT_ANNOTATIONS_PORT_ID()); } bool BlastPlusWorker::isReady() { return (input && input->hasMessage()); } Task* BlastPlusWorker::tick() { Message inputMessage = getMessageAndSetupScriptValues(input); cfg.programName=actor->getParameter(PROGRAM_NAME)->getAttributeValue(); cfg.databaseNameAndPath=actor->getParameter(DATABASE_PATH)->getAttributeValue() +"/"+ actor->getParameter(DATABASE_NAME)->getAttributeValue(); cfg.isDefaultCosts=true; cfg.isDefaultMatrix=true; cfg.isDefautScores=true; cfg.expectValue=actor->getParameter(EXPECT_VALUE)->getAttributeValue(); cfg.groupName=actor->getParameter(GROUP_NAME)->getAttributeValue(); if(cfg.groupName.isEmpty()){ cfg.groupName="blast result"; } cfg.wordSize=0; cfg.isGappedAlignment=actor->getParameter(GAPPED_ALN)->getAttributeValue(); QString path=actor->getParameter(EXT_TOOL_PATH)->getAttributeValue(); if(QString::compare(path, "default", Qt::CaseInsensitive) != 0){ if(cfg.programName == "blastn"){ AppContext::getExternalToolRegistry()->getByName(BLASTN_TOOL_NAME)->setPath(path); }else if(cfg.programName == "blastp"){ AppContext::getExternalToolRegistry()->getByName(BLASTP_TOOL_NAME)->setPath(path); }else if(cfg.programName == "blastx"){ AppContext::getExternalToolRegistry()->getByName(BLASTX_TOOL_NAME)->setPath(path); }else if(cfg.programName == "tblastn"){ AppContext::getExternalToolRegistry()->getByName(TBLASTN_TOOL_NAME)->setPath(path); }else if(cfg.programName == "tblastx"){ AppContext::getExternalToolRegistry()->getByName(TBLASTX_TOOL_NAME)->setPath(path); } } path=actor->getParameter(TMP_DIR_PATH)->getAttributeValue(); if(QString::compare(path, "default", Qt::CaseInsensitive) != 0){ AppContext::getAppSettings()->getUserAppsSettings()->setTemporaryDirPath(path); } DNASequence seq = inputMessage.getData().toMap().value(BaseSlots::DNA_SEQUENCE_SLOT().getId()).value(); if( seq.length() < 1) { return new FailTask(tr("Empty sequence supplied to BLAST")); } cfg.querySequence=seq.seq; DNAAlphabet *alp = AppContext::getDNAAlphabetRegistry()->findAlphabet(seq.seq); cfg.alphabet=alp; //TO DO: Check alphabet if(seq.alphabet->isAmino()) { if(cfg.programName == "blastn" || cfg.programName == "blastx" || cfg.programName == "tblastx") { return new FailTask(tr("Selected BLAST search with nucleotide input sequence")); } } else { if(cfg.programName == "blastp" || cfg.programName == "tblastn") { return new FailTask(tr("Selected BLAST search with amino acid input sequence")); } } cfg.needCreateAnnotations=false; cfg.outputType=actor->getParameter(OUT_TYPE)->getAttributeValue(); cfg.outputOriginalFile=actor->getParameter(ORIGINAL_OUT)->getAttributeValue(); if(cfg.outputType != 5 && cfg.outputOriginalFile.isEmpty()){ return new FailTask(tr("Not selected BLAST output file")); } Task * t=NULL; if(cfg.programName == "blastn"){ t = new BlastNPlusSupportTask(cfg); }else if(cfg.programName == "blastp"){ t = new BlastPPlusSupportTask(cfg); }else if(cfg.programName == "blastx"){ t = new BlastXPlusSupportTask(cfg); }else if(cfg.programName == "tblastn"){ t = new TBlastNPlusSupportTask(cfg); }else if(cfg.programName == "tblastx"){ t = new TBlastXPlusSupportTask(cfg); } connect(t, SIGNAL(si_stateChanged()), SLOT(sl_taskFinished())); return t; } void BlastPlusWorker::sl_taskFinished() { BlastPlusSupportCommonTask* t = qobject_cast(sender()); if (t->getState() != Task::State_Finished) return; if(output) { QList res = t->getResultedAnnotations(); QString annName = actor->getParameter(GROUP_NAME)->getAttributeValue(); if(!annName.isEmpty()) { for(int i = 0; iname = annName; } } QVariant v = qVariantFromValue >(res); output->put(Message(BaseTypes::ANNOTATION_TABLE_TYPE(), v)); if (input->isEnded()) { output->setEnded(); } } } bool BlastPlusWorker::isDone() { return !input || input->isEnded(); } void BlastPlusWorker::cleanup() { } } //namespace LocalWorkflow } //namespace U2 ugene-1.9.8/src/plugins/external_tool_support/src/blast_plus/BlastPlusSupportRunDialog.cpp0000644000175000017500000004013111651544323031016 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "BlastPlusSupportRunDialog.h" #include "BlastPlusSupport.h" #include "ExternalToolSupportSettingsController.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include namespace U2 { //////////////////////////////////////// //BlastAllSupportRunDialog BlastPlusSupportRunDialog::BlastPlusSupportRunDialog(DNASequenceObject* _dnaso, BlastTaskSettings& _settings, QString &_lastDBPath, QString &_lastDBName, QWidget* _parent) : BlastRunCommonDialog(_settings, _parent), dnaso(_dnaso), lastDBPath(_lastDBPath), lastDBName(_lastDBName) { CreateAnnotationModel ca_m; ca_m.data->name = "misc_feature"; ca_m.hideAnnotationName = true; ca_m.hideLocation = true; ca_m.sequenceObjectRef = GObjectReference(dnaso); ca_m.sequenceLen = dnaso->getSequenceLen(); ca_c = new CreateAnnotationWidgetController(ca_m, this); //lowerCaseCheckBox->hide(); QWidget *wdgt = ca_c->getWidget(); wdgt->setMinimumHeight(150); verticalLayout_4->addWidget(wdgt); if(dnaso->getAlphabet()->getType() == DNAAlphabet_AMINO){ programName->removeItem(0);//blastn programName->removeItem(1);//blastx programName->removeItem(2);//tblastx settings.isNucleotideSeq=false; }else{ programName->removeItem(1);//blastp programName->removeItem(2);//tblastn settings.isNucleotideSeq=true; } databasePathLineEdit->setText(lastDBPath); baseNameLineEdit->setText(lastDBName); connect(cancelButton,SIGNAL(clicked()),SLOT(reject())); } void BlastPlusSupportRunDialog::sl_lineEditChanged(){ bool isFilledDatabasePathLineEdit = !databasePathLineEdit->text().isEmpty(); bool isFilledBaseNameLineEdit = !baseNameLineEdit->text().isEmpty(); okButton->setEnabled(isFilledBaseNameLineEdit && isFilledDatabasePathLineEdit); } bool BlastPlusSupportRunDialog::checkToolPath(){ bool needSetToolPath=false; QString toolName; QMessageBox msgBox; msgBox.setWindowTitle("BLAST+ Search"); msgBox.setInformativeText(tr("Do you want to select it now?")); msgBox.setStandardButtons(QMessageBox::Yes | QMessageBox::No); msgBox.setDefaultButton(QMessageBox::Yes); if((programName->currentText() == "blastn") && (AppContext::getExternalToolRegistry()->getByName(BLASTN_TOOL_NAME)->getPath().isEmpty())){ needSetToolPath=true; toolName=BLASTN_TOOL_NAME; }else if((programName->currentText() == "blastp") && (AppContext::getExternalToolRegistry()->getByName(BLASTP_TOOL_NAME)->getPath().isEmpty())){ needSetToolPath=true; toolName=BLASTP_TOOL_NAME; }else if((programName->currentText() == "blastx") && (AppContext::getExternalToolRegistry()->getByName(BLASTX_TOOL_NAME)->getPath().isEmpty())){ needSetToolPath=true; toolName=BLASTX_TOOL_NAME; }else if((programName->currentText() == "tblastn") && (AppContext::getExternalToolRegistry()->getByName(TBLASTN_TOOL_NAME)->getPath().isEmpty())){ needSetToolPath=true; toolName=TBLASTN_TOOL_NAME; }else if((programName->currentText() == "tblastx") && (AppContext::getExternalToolRegistry()->getByName(TBLASTX_TOOL_NAME)->getPath().isEmpty())){ needSetToolPath=true; toolName=TBLASTX_TOOL_NAME; } if(needSetToolPath){ msgBox.setText(tr("Path for BLAST+ %1 tool not selected.").arg(toolName)); int ret = msgBox.exec(); switch (ret) { case QMessageBox::Yes: AppContext::getAppSettingsGUI()->showSettingsDialog(ExternalToolSupportSettingsPageId); break; case QMessageBox::No: return false; break; default: assert(NULL); break; } if(!AppContext::getExternalToolRegistry()->getByName(toolName)->getPath().isEmpty()){ return true; }else{ return false; } }else{ return true; } } void BlastPlusSupportRunDialog::sl_runQuery(){ if(!checkToolPath()){ return; } QString error = ca_c->validate(); if (!error.isEmpty()) { QMessageBox::critical(NULL, tr("Wrong parameters for creating annotations"), error); return; } settings.outputResFile=ca_c->getModel().newDocUrl; if(ca_c->isNewObject()) { settings.aobj = new AnnotationTableObject("Annotations"); settings.aobj->addObjectRelation(GObjectRelation(ca_c->getModel().sequenceObjectRef, GObjectRelationRole::SEQUENCE)); } else { ca_c->prepareAnnotationObject(); settings.aobj = ca_c->getModel().getAnnotationObject(); } settings.groupName=ca_c->getModel().groupName; getSettings(settings); settings.alphabet=dnaso->getAlphabet(); lastDBPath=databasePathLineEdit->text(); lastDBName=baseNameLineEdit->text(); settings.outputType=5;//By default set output file format to xml accept(); } //////////////////////////////////////// //BlastPlusWithExtFileSpecifySupportRunDialog BlastPlusWithExtFileSpecifySupportRunDialog::BlastPlusWithExtFileSpecifySupportRunDialog(QList& _settingsList, QString &_lastDBPath, QString &_lastDBName, QWidget *_parent) : BlastRunCommonDialog(_settingsList[0], _parent), settingsList(_settingsList), lastDBPath(_lastDBPath), lastDBName(_lastDBName) { ca_c=NULL; wasNoOpenProject=false; //create input file widget QWidget * widget = new QWidget(_parent); inputFileLineEdit= new FileLineEdit("","", false, widget); inputFileLineEdit->setReadOnly(true); inputFileLineEdit->setText(""); QToolButton * selectToolPathButton = new QToolButton(widget); selectToolPathButton->setVisible(true); selectToolPathButton->setText("..."); connect(selectToolPathButton, SIGNAL(clicked()), inputFileLineEdit, SLOT(sl_onBrowse())); connect(inputFileLineEdit,SIGNAL(textChanged(QString)),this, SLOT(sl_inputFileLineEditChanged(QString))); QHBoxLayout* layout = new QHBoxLayout(widget); layout->addWidget(inputFileLineEdit); layout->addWidget(selectToolPathButton); QGroupBox* inputFileGroupBox=new QGroupBox(tr("Select input file"),widget); inputFileGroupBox->setLayout(layout); QBoxLayout* parentLayout = qobject_cast(this->layout()); assert(parentLayout); parentLayout->insertWidget(0, inputFileGroupBox); databasePathLineEdit->setText(lastDBPath); baseNameLineEdit->setText(lastDBName); connect(cancelButton,SIGNAL(clicked()),SLOT(sl_cancel())); connect(this,SIGNAL(rejected()),SLOT(sl_cancel())); } void BlastPlusWithExtFileSpecifySupportRunDialog::sl_lineEditChanged(){ bool isFilledDatabasePathLineEdit = !databasePathLineEdit->text().isEmpty(); bool isFilledBaseNameLineEdit = !baseNameLineEdit->text().isEmpty(); bool isInputFileLineEdit = !inputFileLineEdit->text().isEmpty(); okButton->setEnabled(isFilledBaseNameLineEdit && isFilledDatabasePathLineEdit && isInputFileLineEdit); } void BlastPlusWithExtFileSpecifySupportRunDialog::sl_inputFileLineEditChanged(const QString& str){ if(!str.isEmpty()){ QFileInfo fi(str); if (fi.exists()){ QList tasks; Project* proj = AppContext::getProject(); if (proj == NULL) { wasNoOpenProject=true; tasks.append( AppContext::getProjectLoader()->createNewProjectTask()); } DocumentFormatConstraints c; c.checkRawData = true; c.supportedObjectTypes += GObjectTypes::SEQUENCE; c.rawData = BaseIOAdapters::readFileHeader(str); QList formats = AppContext::getDocumentFormatRegistry()->selectFormats(c); if (formats.isEmpty()) { //stateInfo.setError(tr("input_format_error")); //show error message return; } DocumentFormatId df = formats.first(); LoadDocumentTask* loadDocumentTask= new LoadDocumentTask(df, str, AppContext::getIOAdapterRegistry()->getIOAdapterFactoryById(BaseIOAdapters::url2io(str))); connect(loadDocumentTask,SIGNAL(si_stateChanged()),SLOT(sl_inputFileLoadTaskStateChanged())); tasks.append(loadDocumentTask); AppContext::getTaskScheduler()->registerTopLevelTask(new MultiTask("Load documents and open project",tasks)); }else{ return; } } } void BlastPlusWithExtFileSpecifySupportRunDialog::sl_inputFileLoadTaskStateChanged(){ LoadDocumentTask* s=qobject_cast(sender()); if((s->isFinished())&&(!s->hasError())){ int numOfSequences=0; foreach(GObject* gobj, s->getDocument()->getObjects()){ if(gobj->getGObjectType()==GObjectTypes::SEQUENCE){ numOfSequences++; } } settingsList.clear(); sequencesRefList.clear(); if(numOfSequences ==0){ QMessageBox::critical(this, tr("Wrong input file"), tr("This file not contain any sequence.")); inputFileLineEdit->setText(""); return; } foreach(GObject* gobj, s->getDocument()->getObjects()){ if(gobj->getGObjectType()==GObjectTypes::SEQUENCE){ DNASequenceObject* seq=(DNASequenceObject*)gobj; BlastTaskSettings localSettings; localSettings.querySequence=seq->getDNASequence().seq; localSettings.alphabet=seq->getDNASequence().alphabet; if(localSettings.alphabet->getType() != DNAAlphabet_AMINO){ localSettings.isNucleotideSeq=true; } localSettings.queryFile=s->getURL().getURLString(); settingsList.append(localSettings); sequencesRefList.append(GObjectReference(gobj)); } } //DNASequenceObject* seq=(DNASequenceObject*)sequencesRefList[0]; CreateAnnotationModel ca_m; ca_m.data->name = "misc_feature"; ca_m.hideAnnotationName = true; ca_m.hideLocation = true; ca_m.sequenceObjectRef = sequencesRefList[0];//GObjectReference(seq);//not needed, it unused ca_m.sequenceLen = 10;//dnaso->getSequenceLen(); if(ca_c != NULL){ verticalLayout_4->removeWidget(ca_c->getWidget()); delete ca_c; } ca_c = new CreateAnnotationWidgetController(ca_m, this); QWidget *wdgt = ca_c->getWidget(); wdgt->setMinimumHeight(150); verticalLayout_4->addWidget(wdgt); } sl_lineEditChanged(); } bool BlastPlusWithExtFileSpecifySupportRunDialog::checkToolPath(){ bool needSetToolPath=false; QString toolName; QMessageBox msgBox; msgBox.setWindowTitle("BLAST+ Search"); msgBox.setInformativeText(tr("Do you want to select it now?")); msgBox.setStandardButtons(QMessageBox::Yes | QMessageBox::No); msgBox.setDefaultButton(QMessageBox::Yes); if((programName->currentText() == "blastn") && (AppContext::getExternalToolRegistry()->getByName(BLASTN_TOOL_NAME)->getPath().isEmpty())){ needSetToolPath=true; toolName=BLASTN_TOOL_NAME; }else if((programName->currentText() == "blastp") && (AppContext::getExternalToolRegistry()->getByName(BLASTP_TOOL_NAME)->getPath().isEmpty())){ needSetToolPath=true; toolName=BLASTP_TOOL_NAME; }else if((programName->currentText() == "blastx") && (AppContext::getExternalToolRegistry()->getByName(BLASTX_TOOL_NAME)->getPath().isEmpty())){ needSetToolPath=true; toolName=BLASTX_TOOL_NAME; }else if((programName->currentText() == "tblastn") && (AppContext::getExternalToolRegistry()->getByName(TBLASTN_TOOL_NAME)->getPath().isEmpty())){ needSetToolPath=true; toolName=TBLASTN_TOOL_NAME; }else if((programName->currentText() == "tblastx") && (AppContext::getExternalToolRegistry()->getByName(TBLASTX_TOOL_NAME)->getPath().isEmpty())){ needSetToolPath=true; toolName=TBLASTX_TOOL_NAME; } if(needSetToolPath){ msgBox.setText(tr("Path for BLAST+ %1 tool not selected.").arg(toolName)); int ret = msgBox.exec(); switch (ret) { case QMessageBox::Yes: AppContext::getAppSettingsGUI()->showSettingsDialog(ExternalToolSupportSettingsPageId); break; case QMessageBox::No: return false; break; default: assert(NULL); break; } if(!AppContext::getExternalToolRegistry()->getByName(toolName)->getPath().isEmpty()){ return true; }else{ return false; } }else{ return true; } } void BlastPlusWithExtFileSpecifySupportRunDialog::sl_runQuery(){ if(!checkToolPath()){ return; } QString error = ca_c->validate(); if (!error.isEmpty()) { QMessageBox::critical(NULL, tr("Wrong parameters for creating annotations"), error); return; } for(int i=0; igetModel().newDocUrl; if(ca_c->isNewObject()) { settingsList[i].aobj = new AnnotationTableObject(sequencesRefList[i].objName+" annotations"); settingsList[i].aobj->addObjectRelation(GObjectRelation(sequencesRefList[i], GObjectRelationRole::SEQUENCE)); } else { assert(NULL);//always created new document for annotations // ca_c->prepareAnnotationObject(); // settings.aobj = caControllers.at(i)->getModel().getAnnotationObject(); } settingsList[i].groupName=ca_c->getModel().groupName; getSettings(settingsList[i]); settingsList[i].outputType = 5;//By default set output file format to xml } bool docAlreadyInProject=false; Project* proj=AppContext::getProject(); foreach(Document* doc, proj->getDocuments()){ if(doc->getURL() == inputFileLineEdit->text()){ docAlreadyInProject=true; } } if(!docAlreadyInProject){ QString url = inputFileLineEdit->text(); AppContext::getTaskScheduler()->registerTopLevelTask(AppContext::getProjectLoader()->openWithProjectTask(url)); } lastDBPath=databasePathLineEdit->text(); lastDBName=baseNameLineEdit->text(); accept(); } void BlastPlusWithExtFileSpecifySupportRunDialog::sl_cancel(){ if(qobject_cast(sender()) == NULL){ reject(); return; } if(wasNoOpenProject){ AppContext::getTaskScheduler()->registerTopLevelTask(AppContext::getProjectService()->closeProjectTask()); } } }//namespace ugene-1.9.8/src/plugins/external_tool_support/src/blast_plus/BlastPlusSupportCommonTask.cpp0000644000175000017500000003765311651544323031224 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "BlastPlusSupportCommonTask.h" #include "BlastPlusSupport.h" #include "BlastNPlusSupportTask.h" #include "BlastPPlusSupportTask.h" #include "BlastXPlusSupportTask.h" #include "TBlastNPlusSupportTask.h" #include "TBlastXPlusSupportTask.h" #include "RPSBlastSupportTask.h" #include #include #include #include #include #include #include #include #include #include #include //#include namespace U2 { BlastPlusSupportCommonTask::BlastPlusSupportCommonTask(const BlastTaskSettings& _settings) : Task("Run NCBI Blast+ task", TaskFlags_NR_FOSCOE), settings(_settings) { GCOUNTER( cvar, tvar, "BlastPlusSupportCommonTask" ); blastPlusTask=NULL; logParser=NULL; tmpDoc=NULL; saveTemporaryDocumentTask=NULL; sequenceObject=NULL; addTaskResource(TaskResourceUsage(RESOURCE_THREAD, settings.numberOfProcessors)); } void BlastPlusSupportCommonTask::prepare(){ if(settings.databaseNameAndPath.contains(" ")){ stateInfo.setError("Database path have space(s). Try select any other directory without spaces."); return; } //Add new subdir for temporary files //Directory name is ExternalToolName + CurrentDate + CurrentTime QString tmpDirName = "BlastPlus_"+QString::number(this->getTaskId())+"_"+ QDate::currentDate().toString("dd.MM.yyyy")+"_"+ QTime::currentTime().toString("hh.mm.ss.zzz")+"_"+ QString::number(QCoreApplication::applicationPid())+"/"; //Check and remove subdir for temporary files QDir tmpDir(AppContext::getAppSettings()->getUserAppsSettings()->getTemporaryDirPath()+"/"+tmpDirName); if(tmpDir.exists()){ foreach(const QString& file, tmpDir.entryList()){ tmpDir.remove(file); } if(!tmpDir.rmdir(tmpDir.absolutePath())){ stateInfo.setError(tr("Subdirectory for temporary files exists. Can not remove this directory.")); return; } } if(!tmpDir.mkpath(AppContext::getAppSettings()->getUserAppsSettings()->getTemporaryDirPath()+"/"+tmpDirName)){ stateInfo.setError(tr("Can not create directory for temporary files.")); return; } QList objects; sequenceObject= new DNASequenceObject("input sequence", DNASequence(settings.querySequence, settings.alphabet)); objects.append(sequenceObject); url=AppContext::getAppSettings()->getUserAppsSettings()->getTemporaryDirPath() + "/" + tmpDirName + "tmp.fa"; if(url.contains(" ")){ stateInfo.setError("Temporary directory path have space(s). Try select any other directory without spaces."); return; } tmpDoc = new Document(AppContext::getDocumentFormatRegistry()->getFormatById(BaseDocumentFormats::PLAIN_FASTA), AppContext::getIOAdapterRegistry()->getIOAdapterFactoryById(BaseIOAdapters::LOCAL_FILE), GUrl(url), objects); saveTemporaryDocumentTask = new SaveDocumentTask(tmpDoc, AppContext::getIOAdapterRegistry()->getIOAdapterFactoryById(BaseIOAdapters::LOCAL_FILE), url); saveTemporaryDocumentTask->setSubtaskProgressWeight(5); addSubTask(saveTemporaryDocumentTask); } QList BlastPlusSupportCommonTask::onSubTaskFinished(Task* subTask) { QList res; if(subTask->hasError()) { stateInfo.setError(subTask->getError()); return res; } if(hasError() || isCanceled()) { return res; } if(subTask==saveTemporaryDocumentTask){ delete tmpDoc;//sequenceObject also deleted at this place blastPlusTask=createBlastPlusTask();//new ExternalToolRunTask(BLASTN_TOOL_NAME,arguments, logParser); blastPlusTask->setSubtaskProgressWeight(95); res.append(blastPlusTask); } else if(subTask==blastPlusTask){ assert(logParser); delete logParser; if(settings.outputType == 5){ if(!QFileInfo(settings.outputOriginalFile).exists()){ QString curToolName; if(settings.programName == "blastn"){ curToolName=BLASTN_TOOL_NAME; }else if(settings.programName == "blastp"){ curToolName=BLASTP_TOOL_NAME; }else if(settings.programName == "blastx"){ curToolName=BLASTX_TOOL_NAME; }else if(settings.programName == "tblastn"){ curToolName=TBLASTN_TOOL_NAME; }else if(settings.programName == "tblastx"){ curToolName=TBLASTX_TOOL_NAME; } else if(settings.programName == "rpsblast") { curToolName = RPSBLAST_TOOL_NAME; } if(AppContext::getExternalToolRegistry()->getByName(curToolName)->isValid()){ stateInfo.setError(tr("Output file not found")); }else{ stateInfo.setError(tr("Output file not found. May be %1 tool path '%2' not valid?") .arg(AppContext::getExternalToolRegistry()->getByName(curToolName)->getName()) .arg(AppContext::getExternalToolRegistry()->getByName(curToolName)->getPath())); } return res; } parseResult(); if((!result.isEmpty())&&(settings.needCreateAnnotations)) { // Document* d = AppContext::getProject()->findDocumentByURL(url); //assert(d==NULL); if(!settings.outputResFile.isEmpty()) { IOAdapterFactory* iof = AppContext::getIOAdapterRegistry()->getIOAdapterFactoryById(BaseIOAdapters::LOCAL_FILE); DocumentFormat* df = AppContext::getDocumentFormatRegistry()->getFormatById(BaseDocumentFormats::PLAIN_GENBANK); Document *d = df->createNewDocument(iof, settings.outputResFile); d->addObject(settings.aobj); AppContext::getProject()->addDocument(d); } for(QMutableListIterator it_ad(result); it_ad.hasNext(); ) { AnnotationData * ad = it_ad.next().data(); U2Region::shift(settings.offsInGlobalSeq, ad->location->regions); } res.append(new CreateAnnotationsTask(settings.aobj, settings.groupName, result)); } } } return res; } Task::ReportResult BlastPlusSupportCommonTask::report(){ if( url.isEmpty() ) { return ReportResult_Finished; } //Remove subdir for temporary files, that created in prepare QDir tmpDir(QFileInfo(url).absoluteDir()); foreach(QString file, tmpDir.entryList()){ tmpDir.remove(file); } if(!tmpDir.rmdir(tmpDir.absolutePath())){ stateInfo.setError(tr("Can not remove directory for temporary files.")); emit si_stateChanged(); } return ReportResult_Finished; } QList BlastPlusSupportCommonTask::getResultedAnnotations() const { return result; } BlastTaskSettings BlastPlusSupportCommonTask::getSettings() const { return settings; } void BlastPlusSupportCommonTask::parseResult() { QDomDocument xmlDoc; QFile file(settings.outputOriginalFile); if (!file.open(QIODevice::ReadOnly)){ stateInfo.setError("Can't open output file"); return; } if (!xmlDoc.setContent(&file)) { stateInfo.setError("Can't read output file"); file.close(); return; } file.close(); QDomNodeList hits = xmlDoc.elementsByTagName("Hit"); for(int i = 0; iqualifiers.push_back(U2Qualifier("bit-score", elem.text())); } elem = xml.lastChildElement("Hsp_score"); if(!elem.isNull()) { ad->qualifiers.push_back(U2Qualifier("score", elem.text())); } elem = xml.lastChildElement("Hsp_evalue"); if(!elem.isNull()) { ad->qualifiers.push_back(U2Qualifier("E-value", elem.text())); } elem = xml.lastChildElement("Hsp_query-from"); QString fr = elem.text(); from = elem.text().toInt(&isOk); if(!isOk) { stateInfo.setError("Can't get location"); return; } elem = xml.lastChildElement("Hsp_query-to"); to = elem.text().toInt(&isOk); if(!isOk) { stateInfo.setError("Can't get location"); return; } elem = xml.lastChildElement("Hsp_hit-from"); if(!elem.isNull()) { ad->qualifiers.push_back(U2Qualifier("hit-from", elem.text())); } elem = xml.lastChildElement("Hsp_hit-to"); if(!elem.isNull()) { ad->qualifiers.push_back(U2Qualifier("hit-to", elem.text())); } elem = xml.lastChildElement("Hsp_hit-frame"); int frame = elem.text().toInt(&isOk); if(!isOk) { stateInfo.setError("Can't get location"); return; } QString frame_txt = (frame < 0) ? "complement" : "direct"; ad->qualifiers.push_back(U2Qualifier( "source_frame", frame_txt )); ad->setStrand(frame < 0 ? U2Strand::Complementary: U2Strand::Direct); elem = xml.lastChildElement("Hsp_identity"); identities = elem.text().toInt(&isOk); if(!isOk) { stateInfo.setError("Can't get identity"); return; } elem = xml.lastChildElement("Hsp_gaps"); if(!elem.isNull()) { gaps = elem.text().toInt(&isOk); if(!isOk) { stateInfo.setError("Can't get gaps"); return; } } elem = xml.lastChildElement("Hsp_align-len"); align_len = elem.text().toInt(&isOk); if(!isOk) { stateInfo.setError("Can't get align length"); return; } //at new blast+ not need check strand ad->location->regions << U2Region( from-1, to - from + 1); if( align_len != -1 ) { if( gaps != -1 ) { float percent = (float)gaps / (float)align_len * 100.; QString str = QString::number(gaps) + "/" + QString::number(align_len) + " (" + QString::number(percent,'g',4) + "%)"; ad->qualifiers.push_back(U2Qualifier( "gaps", str )); } if( identities != -1 ) { float percent = (float)identities / (float)align_len * 100.; QString str = QString::number(identities) + '/' + QString::number(align_len) + " (" + QString::number(percent,'g',4) + "%)"; ad->qualifiers.push_back(U2Qualifier( "identities", str )); } } ad->qualifiers.push_back(U2Qualifier("id",id)); ad->qualifiers.push_back(U2Qualifier("def",def)); ad->qualifiers.push_back(U2Qualifier("accession",accession)); ad->name = "blast result"; result.append(ad); } /////////////////////////////////////// //BlastPlusSupportMultiTask BlastPlusSupportMultiTask::BlastPlusSupportMultiTask(QList& _settingsList, QString& _url): Task("Run NCBI BlastAll multitask", TaskFlags_NR_FOSCOE | TaskFlag_ReportingIsSupported), settingsList(_settingsList), doc(NULL), url(_url) { } void BlastPlusSupportMultiTask::prepare(){ //create document IOAdapterFactory* iof = AppContext::getIOAdapterRegistry()->getIOAdapterFactoryById(BaseIOAdapters::LOCAL_FILE); DocumentFormat* df = AppContext::getDocumentFormatRegistry()->getFormatById(BaseDocumentFormats::PLAIN_GENBANK); //url=settingsList[0].outputResFile; doc = df->createNewDocument(iof, url); foreach(BlastTaskSettings settings, settingsList){ settings.needCreateAnnotations=false; Task * t=NULL; if(settings.programName == "blastn"){ t = new BlastNPlusSupportTask(settings); }else if(settings.programName == "blastp"){ t = new BlastPPlusSupportTask(settings); }else if(settings.programName == "blastx"){ t = new BlastXPlusSupportTask(settings); }else if(settings.programName == "tblastn"){ t = new TBlastNPlusSupportTask(settings); }else if(settings.programName == "tblastx"){ t = new TBlastXPlusSupportTask(settings); }else if(settings.programName == "rpsblast"){ t = new RPSBlastSupportTask(settings); } addSubTask(t); } } QList BlastPlusSupportMultiTask::onSubTaskFinished(Task *subTask){ QList res; if(subTask->hasError()) { stateInfo.setError(subTask->getError()); return res; } if(hasError() || isCanceled()) { return res; } BlastPlusSupportCommonTask* s=qobject_cast(subTask); if(s != NULL){ BlastTaskSettings settings=s->getSettings(); assert(settings.aobj!=NULL); QList result=s->getResultedAnnotations(); if(result.length()>0){ doc->addObject(settings.aobj); for(QMutableListIterator it_ad(result); it_ad.hasNext(); ) { AnnotationData * ad = it_ad.next().data(); U2Region::shift(settings.offsInGlobalSeq, ad->location->regions); } res.append(new CreateAnnotationsTask(settings.aobj, settings.groupName, result)); } } return res; } Task::ReportResult BlastPlusSupportMultiTask::report(){ if(!hasError()){ if(doc->getObjects().length() > 0){ AppContext::getProject()->addDocument(doc); }else{ setReportingEnabled(true); } } return ReportResult_Finished; } QString BlastPlusSupportMultiTask::generateReport() const { QString res; res+=""; res+=""; res+=""; res+=""; res+=""; res+="
" + tr("Source file") + "" + settingsList.at(0).queryFile + "
" + tr("Used databse") + "" + settingsList.at(0).databaseNameAndPath + "
" + tr("No any results found") + "
"; return res; } }//namespace ugene-1.9.8/src/plugins/external_tool_support/src/blast_plus/BlastPlusSupport.cpp0000644000175000017500000002754111651544323027223 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "BlastPlusSupport.h" #include "BlastPlusSupportRunDialog.h" #include "BlastPlusSupportCommonTask.h" #include "BlastNPlusSupportTask.h" #include "BlastPPlusSupportTask.h" #include "BlastXPlusSupportTask.h" #include "TBlastNPlusSupportTask.h" #include "TBlastXPlusSupportTask.h" #include "RPSBlastSupportTask.h" #include "utils/ExternalToolSupportAction.h" #include "ExternalToolSupportSettingsController.h" #include "ExternalToolSupportSettings.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include namespace U2 { BlastPlusSupport::BlastPlusSupport(const QString& name, const QString& path) : ExternalTool(name, path) { if (AppContext::getMainWindow()) { icon = QIcon(":external_tool_support/images/ncbi.png"); grayIcon = QIcon(":external_tool_support/images/ncbi_gray.png"); warnIcon = QIcon(":external_tool_support/images/ncbi_warn.png"); } validationArguments<<"-h"; if(name == BLASTN_TOOL_NAME){ #ifdef Q_OS_WIN executableFileName="blastn.exe"; #else #ifdef Q_OS_LINUX executableFileName="blastn"; #endif #endif validMessage="Nucleotide-Nucleotide BLAST"; description="The blastn tool searches a nucleotide database \ using a nucleotide query."; versionRegExp=QRegExp("Nucleotide-Nucleotide BLAST (\\d+\\.\\d+\\.\\d+\\+?)"); }else if(name == BLASTP_TOOL_NAME){ #ifdef Q_OS_WIN executableFileName="blastp.exe"; #else #ifdef Q_OS_LINUX executableFileName="blastp"; #endif #endif validMessage="Protein-Protein BLAST"; description="The blastp tool searches a protein database \ using a protein query."; versionRegExp=QRegExp("Protein-Protein BLAST (\\d+\\.\\d+\\.\\d+\\+?)"); }else if(name == BLASTX_TOOL_NAME){ #ifdef Q_OS_WIN executableFileName="blastx.exe"; #else #ifdef Q_OS_LINUX executableFileName="blastx"; #endif #endif validMessage="Translated Query-Protein Subject"; description="The blastx tool searches a protein database \ using a translated nucleotide query."; versionRegExp=QRegExp("Translated Query-Protein Subject BLAST (\\d+\\.\\d+\\.\\d+\\+?)"); }else if(name == TBLASTN_TOOL_NAME){ #ifdef Q_OS_WIN executableFileName="tblastn.exe"; #else #ifdef Q_OS_LINUX executableFileName="tblastn"; #endif #endif validMessage="Protein Query-Translated Subject"; description="The tblastn compares a protein query against \ a translated nucleotide database"; versionRegExp=QRegExp("Protein Query-Translated Subject BLAST (\\d+\\.\\d+\\.\\d+\\+?)"); }else if(name == TBLASTX_TOOL_NAME){ #ifdef Q_OS_WIN executableFileName="tblastx.exe"; #else #ifdef Q_OS_LINUX executableFileName="tblastx"; #endif #endif validMessage="Translated Query-Translated Subject"; description="The tblastx translates the query nucleotide \ sequence in all six possible frames and compares it \ against the six-frame translations of a nucleotide \ sequence database."; versionRegExp=QRegExp("Translated Query-Translated Subject BLAST (\\d+\\.\\d+\\.\\d+\\+?)"); }else if(name == RPSBLAST_TOOL_NAME) { #ifdef Q_OS_WIN executableFileName="rpsblast.exe"; #else #ifdef Q_OS_LINUX executableFileName="rpsblast"; #endif #endif validMessage="Reverse Position Specific BLAST"; description=""; versionRegExp=QRegExp("Reverse Position Specific BLAST (\\d+\\.\\d+\\.\\d+\\+?)"); } toolKitName="BLAST+"; lastDBName=""; lastDBPath=""; } void BlastPlusSupport::sl_runWithExtFileSpecify(){ //Check that blastal and tempory directory path defined QStringList toolList; toolList << BLASTN_TOOL_NAME << BLASTP_TOOL_NAME << BLASTX_TOOL_NAME << TBLASTN_TOOL_NAME << TBLASTX_TOOL_NAME << RPSBLAST_TOOL_NAME; bool isOneOfToolConfigured=false; foreach(QString toolName, toolList){ if(!AppContext::getExternalToolRegistry()->getByName(toolName)->getPath().isEmpty()){ isOneOfToolConfigured=true; } } if (!isOneOfToolConfigured){ QMessageBox msgBox; msgBox.setWindowTitle("BLAST+ Search"); msgBox.setText(tr("Path for BLAST+ tools not selected.")); msgBox.setInformativeText(tr("Do you want to select it now?")); msgBox.setStandardButtons(QMessageBox::Yes | QMessageBox::No); msgBox.setDefaultButton(QMessageBox::Yes); int ret = msgBox.exec(); switch (ret) { case QMessageBox::Yes: AppContext::getAppSettingsGUI()->showSettingsDialog(ExternalToolSupportSettingsPageId); break; case QMessageBox::No: return; break; default: assert(NULL); break; } bool isOneOfToolConfigured=false; foreach(QString toolName, toolList){ if(!AppContext::getExternalToolRegistry()->getByName(toolName)->getPath().isEmpty()){ isOneOfToolConfigured=true; } } if (!isOneOfToolConfigured){ return; } } ExternalToolSupportSettings::checkTemporaryDir(); if (AppContext::getAppSettings()->getUserAppsSettings()->getTemporaryDirPath().isEmpty()){ return; } //Call select input file and setup settings dialog QList settingsList; BlastTaskSettings settings; settingsList.append(settings); BlastPlusWithExtFileSpecifySupportRunDialog blastPlusRunDialog(settingsList, lastDBPath, lastDBName, AppContext::getMainWindow()->getQMainWindow()); if(blastPlusRunDialog.exec() != QDialog::Accepted){ return; } BlastPlusSupportMultiTask* blastPlusSupportMultiTask = new BlastPlusSupportMultiTask(settingsList,settingsList[0].outputResFile); AppContext::getTaskScheduler()->registerTopLevelTask(blastPlusSupportMultiTask); } //////////////////////////////////////// //BlastPlusSupportContext BlastPlusSupportContext::BlastPlusSupportContext(QObject* p) : GObjectViewWindowContext(p, ANNOTATED_DNA_VIEW_FACTORY_ID) { toolList << BLASTN_TOOL_NAME << BLASTP_TOOL_NAME << BLASTX_TOOL_NAME << TBLASTN_TOOL_NAME << TBLASTX_TOOL_NAME << RPSBLAST_TOOL_NAME; lastDBName=""; lastDBPath=""; } void BlastPlusSupportContext::initViewContext(GObjectView* view) { AnnotatedDNAView* av = qobject_cast(view); assert(av!=NULL); Q_UNUSED(av); ExternalToolSupprotAction* queryAction = new ExternalToolSupprotAction(this, view, tr("Query with BLAST+..."), 2000, toolList); addViewAction(queryAction); connect(queryAction, SIGNAL(triggered()), SLOT(sl_showDialog())); } void BlastPlusSupportContext::buildMenu(GObjectView* view, QMenu* m) { QList actions = getViewActions(view); QMenu* analyseMenu = GUIUtils::findSubMenu(m, ADV_MENU_ANALYSE); assert(analyseMenu!=NULL); foreach(GObjectViewAction* a, actions) { a->addToMenuWithOrder(analyseMenu); } } void BlastPlusSupportContext::sl_showDialog() { //Check that any of BLAST+ tools and tempory directory path defined bool isOneOfToolConfigured=false; foreach(QString toolName, toolList){ if(!AppContext::getExternalToolRegistry()->getByName(toolName)->getPath().isEmpty()){ isOneOfToolConfigured=true; } } if (!isOneOfToolConfigured){ QMessageBox msgBox; msgBox.setWindowTitle("BLAST+ Search"); msgBox.setText(tr("Path for BLAST+ tools not selected.")); msgBox.setInformativeText(tr("Do you want to select it now?")); msgBox.setStandardButtons(QMessageBox::Yes | QMessageBox::No); msgBox.setDefaultButton(QMessageBox::Yes); int ret = msgBox.exec(); switch (ret) { case QMessageBox::Yes: AppContext::getAppSettingsGUI()->showSettingsDialog(ExternalToolSupportSettingsPageId); break; case QMessageBox::No: return; break; default: assert(NULL); break; } bool isOneOfToolConfigured=false; foreach(QString toolName, toolList){ if(!AppContext::getExternalToolRegistry()->getByName(toolName)->getPath().isEmpty()){ isOneOfToolConfigured=true; } } if (!isOneOfToolConfigured){ return; } } ExternalToolSupportSettings::checkTemporaryDir(); if (AppContext::getAppSettings()->getUserAppsSettings()->getTemporaryDirPath().isEmpty()){ return; } QAction* a = (QAction*)sender(); GObjectViewAction* viewAction = qobject_cast(a); AnnotatedDNAView* av = qobject_cast(viewAction->getObjectView()); assert(av); BlastTaskSettings settings; ADVSequenceObjectContext* seqCtx = av->getSequenceInFocus(); BlastPlusSupportRunDialog dlg(seqCtx->getSequenceObject(), settings, lastDBPath, lastDBName, av->getWidget()); //Call run blastall dialog if(dlg.exec() == QDialog::Accepted) { //prepare query const QByteArray& sequence = seqCtx->getSequenceData(); DNASequenceSelection* s = seqCtx->getSequenceSelection(); QVector regions; if(s->isEmpty()) { int seqLen = seqCtx->getSequenceLen(); regions.append(U2Region(0, seqLen)); } else { regions = s->getSelectedRegions(); } foreach(const U2Region& r, regions) { QByteArray query( sequence.constData() + r.startPos, r.length ); settings.querySequence = query; // DNATranslation * aminoT = (dlg.translateToAmino ? seqCtx->getAminoTT() : 0); // DNATranslation * complT = (dlg.translateToAmino ? seqCtx->getComplementTT() : 0); settings.offsInGlobalSeq=r.startPos; Task * t=NULL; if(settings.programName == "blastn"){ t = new BlastNPlusSupportTask(settings); }else if(settings.programName == "blastp"){ t = new BlastPPlusSupportTask(settings); }else if(settings.programName == "blastx"){ t = new BlastXPlusSupportTask(settings); }else if(settings.programName == "tblastn"){ t = new TBlastNPlusSupportTask(settings); }else if(settings.programName == "tblastx"){ t = new TBlastXPlusSupportTask(settings); }else if(settings.programName == "rpsblast"){ t = new RPSBlastSupportTask(settings); } assert(t); AppContext::getTaskScheduler()->registerTopLevelTask( t ); } } } }//namespace ugene-1.9.8/src/plugins/external_tool_support/src/blast_plus/TBlastNPlusSupportTask.h0000644000175000017500000000324111651544323027744 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_TBLASTNPLUS_SUPPORT_TASK_H #define _U2_TBLASTNPLUS_SUPPORT_TASK_H #include #include #include #include #include #include #include "utils/ExportTasks.h" #include #include #include "ExternalToolRunTask.h" #include "BlastPlusSupportCommonTask.h" #include #include namespace U2 { class TBlastNPlusSupportTask : public BlastPlusSupportCommonTask { Q_OBJECT public: TBlastNPlusSupportTask(const BlastTaskSettings& settings):BlastPlusSupportCommonTask(settings){} virtual ExternalToolRunTask* createBlastPlusTask(); }; }//namespace #endif // _U2_TBLASTNPLUS_SUPPORT_TASK_H ugene-1.9.8/src/plugins/external_tool_support/src/ExternalToolSupportSettings.cpp0000644000175000017500000001327411651544323027301 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "ExternalToolSupportSettings.h" #include #include #include #include #include #include #include #include #include #include #include namespace U2 { #define NUMBER_EXTERNAL_TOOL SETTINGS + "numberExternalTools" #define PREFIX_EXTERNAL_TOOL_NAME SETTINGS + "exToolName" #define PREFIX_EXTERNAL_TOOL_PATH SETTINGS + "exToolPath" #define PREFIX_EXTERNAL_TOOL_IS_VALID SETTINGS + "exToolIsValid" #define PREFIX_EXTERNAL_TOOL_VERSION SETTINGS + "exToolVersion" #define TEMPORY_DIRECTORY SETTINGS + "temporyDirectory" Watcher* const ExternalToolSupportSettings::watcher = new Watcher; int ExternalToolSupportSettings::prevNumberExternalTools = 0; int ExternalToolSupportSettings::getNumberExternalTools() { return AppContext::getSettings()->getValue(NUMBER_EXTERNAL_TOOL, 0).toInt(); } void ExternalToolSupportSettings::setNumberExternalTools( int v ) { AppContext::getSettings()->setValue(NUMBER_EXTERNAL_TOOL, v); emit watcher->changed(); } bool ExternalToolSupportSettings::getExternalTools() { int numberExternalTools=getNumberExternalTools(); QString name; QString path; bool isValid; QString version; for(int i=0; igetValue(PREFIX_EXTERNAL_TOOL_NAME + QString::number(i), QVariant("")).toString(); path=AppContext::getSettings()->getValue(PREFIX_EXTERNAL_TOOL_PATH + QString::number(i), QVariant("")).toString(); isValid=AppContext::getSettings()->getValue(PREFIX_EXTERNAL_TOOL_IS_VALID + QString::number(i), QVariant(false)).toBool(); version=AppContext::getSettings()->getValue(PREFIX_EXTERNAL_TOOL_VERSION + QString::number(i), QVariant("unknown")).toString(); if(AppContext::getExternalToolRegistry()->getByName(name) != NULL){ AppContext::getExternalToolRegistry()->getByName(name)->setValid(isValid); AppContext::getExternalToolRegistry()->getByName(name)->setPath(path); AppContext::getExternalToolRegistry()->getByName(name)->setVersion(version); } } prevNumberExternalTools = numberExternalTools; return true;//bad code } void ExternalToolSupportSettings::setExternalTools() { QList ExternalToolList = AppContext::getExternalToolRegistry()->getAllEntries(); int numberExternalTools = ExternalToolList.length(); setNumberExternalTools(numberExternalTools); QString name; QString path; bool isValid; QString version; int numberIterations=numberExternalTools >= prevNumberExternalTools ? numberExternalTools : prevNumberExternalTools; for(int i=0; igetName(); path = ExternalToolList.at(i)->getPath(); isValid = ExternalToolList.at(i)->isValid(); version = ExternalToolList.at(i)->getVersion(); AppContext::getSettings()->setValue(PREFIX_EXTERNAL_TOOL_NAME + QString::number(i), name); AppContext::getSettings()->setValue(PREFIX_EXTERNAL_TOOL_PATH + QString::number(i), path); AppContext::getSettings()->setValue(PREFIX_EXTERNAL_TOOL_IS_VALID + QString::number(i), isValid); AppContext::getSettings()->setValue(PREFIX_EXTERNAL_TOOL_VERSION + QString::number(i), version); }else{ AppContext::getSettings()->remove(PREFIX_EXTERNAL_TOOL_NAME + QString::number(i)); AppContext::getSettings()->remove(PREFIX_EXTERNAL_TOOL_PATH + QString::number(i)); AppContext::getSettings()->remove(PREFIX_EXTERNAL_TOOL_IS_VALID + QString::number(i)); AppContext::getSettings()->remove(PREFIX_EXTERNAL_TOOL_VERSION + QString::number(i)); } } prevNumberExternalTools = numberExternalTools; } void ExternalToolSupportSettings::checkTemporaryDir(){ if(AppContext::getAppSettings()->getUserAppsSettings()->getTemporaryDirPath().isEmpty()){ QMessageBox msgBox; msgBox.setWindowTitle(QObject::tr("Path for temporary files")); msgBox.setText(QObject::tr("Path for temporary files not selected.")); msgBox.setInformativeText(QObject::tr("Do you want to select it now?")); msgBox.setStandardButtons(QMessageBox::Yes | QMessageBox::No); msgBox.setDefaultButton(QMessageBox::Yes); int ret = msgBox.exec(); switch (ret) { case QMessageBox::Yes: AppContext::getAppSettingsGUI()->showSettingsDialog(APP_SETTINGS_USER_APPS); break; case QMessageBox::No: return; break; default: assert(NULL); break; } } } }//namespace ugene-1.9.8/src/plugins/external_tool_support/src/ExternalToolSupportPlugin.cpp0000644000175000017500000003157411651544323026742 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "ExternalToolSupportPlugin.h" #include "ExternalToolSupportSettings.h" #include "ExternalToolSupportSettingsController.h" #include "utils/ExternalToolSupportAction.h" #include "utils/ExternalToolValidateTask.h" #include "ETSProjectViewItemsContoller.h" #include "clustalw/ClustalWSupport.h" #include "clustalw/ClustalWWorker.h" #include "mafft/MAFFTSupport.h" #include "mafft/MAFFTWorker.h" #include "tcoffee/TCoffeeSupport.h" #include "tcoffee/TCoffeeWorker.h" #include "blast/FormatDBSupport.h" #include "blast/BlastAllSupport.h" #include "blast/BlastAllWorker.h" #include "blast_plus/BlastPlusSupport.h" #include "blast_plus/BlastPlusWorker.h" #include "cap3/CAP3Support.h" #include #include #define EXTERNAL_TOOL_SUPPORT_FACTORY_ID "ExternalToolSupport" namespace U2 { extern "C" Q_DECL_EXPORT Plugin * U2_PLUGIN_INIT_FUNC() { ExternalToolSupportPlugin * plug = new ExternalToolSupportPlugin(); return plug; } ExternalToolSupportPlugin::ExternalToolSupportPlugin():Plugin(tr("External tool support"),tr("Runs other external tools")) { //Fill ExternalToolRegistry with supported tools //ClustalW ClustalWSupport* clustalWTool=new ClustalWSupport(CLUSTAL_TOOL_NAME); AppContext::getExternalToolRegistry()->registerEntry(clustalWTool); //MAFFT MAFFTSupport* mAFFTTool=new MAFFTSupport(MAFFT_TOOL_NAME); AppContext::getExternalToolRegistry()->registerEntry(mAFFTTool); //T-Coffee TCoffeeSupport* tCoffeeTool=new TCoffeeSupport(TCOFFEE_TOOL_NAME); AppContext::getExternalToolRegistry()->registerEntry(tCoffeeTool); if (AppContext::getMainWindow()) { clustalWTool->getViewContext()->setParent(this); clustalWTool->getViewContext()->init(); ExternalToolSupprotAction* clustalWAction = new ExternalToolSupprotAction(tr("ClustalW..."), this, QStringList(CLUSTAL_TOOL_NAME)); connect(clustalWAction, SIGNAL(triggered()), clustalWTool, SLOT(sl_runWithExtFileSpecify())); mAFFTTool->getViewContext()->setParent(this); mAFFTTool->getViewContext()->init(); ExternalToolSupprotAction* mAFFTAction= new ExternalToolSupprotAction(tr("MAFFT..."), this, QStringList(MAFFT_TOOL_NAME)); connect(mAFFTAction, SIGNAL(triggered()), mAFFTTool, SLOT(sl_runWithExtFileSpecify())); tCoffeeTool->getViewContext()->setParent(this); tCoffeeTool->getViewContext()->init(); ExternalToolSupprotAction* tCoffeeAction= new ExternalToolSupprotAction(tr("T-Coffee..."), this, QStringList(TCOFFEE_TOOL_NAME)); connect(tCoffeeAction, SIGNAL(triggered()), tCoffeeTool, SLOT(sl_runWithExtFileSpecify())); //Add to menu MA QMenu* tools = AppContext::getMainWindow()->getTopLevelMenu(MWMENU_TOOLS); QMenu* toolsSubmenu = tools->findChild(MWMENU_TOOLS_MALIGN); if(toolsSubmenu == NULL){ toolsSubmenu = tools->addMenu(tr("Multiple alignment")); toolsSubmenu->setObjectName(MWMENU_TOOLS_MALIGN); } toolsSubmenu->setIcon(QIcon(":core/images/msa.png"));//bad code toolsSubmenu->addAction(clustalWAction); toolsSubmenu->addAction(mAFFTAction); toolsSubmenu->addAction(tCoffeeAction); } //FormatDB FormatDBSupport* formatDBTool = new FormatDBSupport(FORMATDB_TOOL_NAME); AppContext::getExternalToolRegistry()->registerEntry(formatDBTool); //MakeBLASTDB from BLAST+ FormatDBSupport* makeBLASTDBTool = new FormatDBSupport(MAKEBLASTDB_TOOL_NAME); AppContext::getExternalToolRegistry()->registerEntry(makeBLASTDBTool); //BlastAll BlastAllSupport* blastallTool = new BlastAllSupport(BLASTALL_TOOL_NAME); AppContext::getExternalToolRegistry()->registerEntry(blastallTool); BlastPlusSupport* blastNPlusTool = new BlastPlusSupport(BLASTN_TOOL_NAME); AppContext::getExternalToolRegistry()->registerEntry(blastNPlusTool); BlastPlusSupport* blastPPlusTool = new BlastPlusSupport(BLASTP_TOOL_NAME); AppContext::getExternalToolRegistry()->registerEntry(blastPPlusTool); BlastPlusSupport* blastXPlusTool = new BlastPlusSupport(BLASTX_TOOL_NAME); AppContext::getExternalToolRegistry()->registerEntry(blastXPlusTool); BlastPlusSupport* tBlastNPlusTool = new BlastPlusSupport(TBLASTN_TOOL_NAME); AppContext::getExternalToolRegistry()->registerEntry(tBlastNPlusTool); BlastPlusSupport* tBlastXPlusTool = new BlastPlusSupport(TBLASTX_TOOL_NAME); AppContext::getExternalToolRegistry()->registerEntry(tBlastXPlusTool); BlastPlusSupport* rpsblastTool = new BlastPlusSupport(RPSBLAST_TOOL_NAME); AppContext::getExternalToolRegistry()->registerEntry(rpsblastTool); CAP3Support* cap3Tool = new CAP3Support(CAP3_TOOL_NAME); AppContext::getExternalToolRegistry()->registerEntry(cap3Tool); if (AppContext::getMainWindow()) { ExternalToolSupprotAction* formatDBAction= new ExternalToolSupprotAction(tr("FormatDB..."), this, QStringList(FORMATDB_TOOL_NAME)); connect(formatDBAction, SIGNAL(triggered()), formatDBTool, SLOT(sl_runWithExtFileSpecify())); ExternalToolSupprotAction* makeBLASTDBAction= new ExternalToolSupprotAction(tr("BLAST+ make DB..."), this, QStringList(MAKEBLASTDB_TOOL_NAME)); connect(makeBLASTDBAction, SIGNAL(triggered()), makeBLASTDBTool, SLOT(sl_runWithExtFileSpecify())); blastallTool->getViewContext()->setParent(this); blastallTool->getViewContext()->init(); ExternalToolSupprotAction* blastallAction= new ExternalToolSupprotAction(tr("BLAST Search..."), this, QStringList(BLASTALL_TOOL_NAME)); connect(blastallAction, SIGNAL(triggered()), blastallTool, SLOT(sl_runWithExtFileSpecify())); BlastPlusSupportContext* blastPlusViewCtx = new BlastPlusSupportContext(this); blastPlusViewCtx->setParent(this);//may be problems??? blastPlusViewCtx->init(); QStringList toolList; toolList << BLASTN_TOOL_NAME << BLASTP_TOOL_NAME << BLASTX_TOOL_NAME << TBLASTN_TOOL_NAME << TBLASTX_TOOL_NAME << RPSBLAST_TOOL_NAME; ExternalToolSupprotAction* blastPlusAction= new ExternalToolSupprotAction(tr("BLAST+ Search..."), this, toolList); connect(blastPlusAction, SIGNAL(triggered()), blastNPlusTool, SLOT(sl_runWithExtFileSpecify())); //Add to menu NCBI Toolkit QMenu* tools = AppContext::getMainWindow()->getTopLevelMenu(MWMENU_TOOLS); QMenu* blastSubmenu = tools->addMenu(tr("BLAST")); blastSubmenu->setIcon(QIcon(":external_tool_support/images/ncbi.png")); blastSubmenu->addAction(formatDBAction); blastSubmenu->addAction(blastallAction); blastSubmenu->addAction(makeBLASTDBAction); blastSubmenu->addAction(blastPlusAction); ExternalToolSupprotAction* cap3Action = new ExternalToolSupprotAction(QString("Contig assembly with %1").arg(cap3Tool->getName()), this, QStringList(cap3Tool->getName())); connect(cap3Action, SIGNAL(triggered()), cap3Tool, SLOT(sl_runWithExtFileSpecify())); QMenu* assemblySumbenu = tools->findChild(MWMENU_TOOLS_ASSEMBLY); assemblySumbenu->addAction(cap3Action); } AppContext::getCDSFactoryRegistry()->registerFactory(new CDSearchLocalTaskFactory(), CDSearchFactoryRegistry::LocalSearch); //Read settings ExternalToolSupportSettings::getExternalTools(); //Search in tools path #ifdef Q_OS_WIN QString clustalWPath = QDir::toNativeSeparators(QCoreApplication::applicationDirPath()+"\\tools\\clustalw2.exe"); if(AppContext::getExternalToolRegistry()->getByName(CLUSTAL_TOOL_NAME)->getPath().isEmpty()){ QFileInfo clustalExe(clustalWPath); if(clustalExe.exists()){ AppContext::getExternalToolRegistry()->getByName(CLUSTAL_TOOL_NAME)->setPath(clustalWPath); } } QString cap3Path = QDir::toNativeSeparators(QCoreApplication::applicationDirPath()+"\\tools\\cap3.exe"); if(AppContext::getExternalToolRegistry()->getByName(CAP3_TOOL_NAME)->getPath().isEmpty()){ QFileInfo cap3Exe(cap3Path); if(cap3Exe.exists()){ AppContext::getExternalToolRegistry()->getByName(CAP3_TOOL_NAME)->setPath(cap3Path); } } #endif QStringList envList = QProcess::systemEnvironment(); if(envList.indexOf(QRegExp("PATH=.*"))>=0){ QString pathEnv = envList.at(envList.indexOf(QRegExp("PATH=.*"))); #ifdef Q_OS_LINUX QStringList paths = pathEnv.split("=").at(1).split(":"); #else #ifdef Q_OS_WIN QStringList paths = pathEnv.split("=").at(1).split(";"); #else QStringList paths; #endif #endif foreach(ExternalTool* curTool, AppContext::getExternalToolRegistry()->getAllEntries()){ foreach(QString curPath, paths){ if(curTool->getPath().isEmpty()){ QString exePath = curPath+"/"+curTool->getExecutableFileName(); QFileInfo fileExe(exePath); if(fileExe.exists() && (curTool->getPath()=="")){ //curTool->setPath(exePath); ExternalToolValidateTask* validateTask=new ExternalToolValidateTask(curTool->getName(), exePath); connect(validateTask,SIGNAL(si_stateChanged()),SLOT(sl_validateTaskStateChanged())); AppContext::getTaskScheduler()->registerTopLevelTask(validateTask); } } } } } if (AppContext::getMainWindow()) { //Add viewer for settings AppContext::getAppSettingsGUI()->registerPage(new ExternalToolSupportSettingsPageController()); } //Add new workers to WD LocalWorkflow::ClustalWWorkerFactory::init(); LocalWorkflow::MAFFTWorkerFactory::init(); LocalWorkflow::BlastAllWorkerFactory::init(); LocalWorkflow::BlastPlusWorkerFactory::init(); LocalWorkflow::TCoffeeWorkerFactory::init(); if (AppContext::getMainWindow()) { //Add project view service services.push_back(new ExternalToolSupportService()); } } ExternalToolSupportPlugin::~ExternalToolSupportPlugin(){ ExternalToolSupportSettings::setExternalTools(); } void ExternalToolSupportPlugin::sl_validateTaskStateChanged(){ ExternalToolValidateTask* s=qobject_cast(sender()); assert(s); if(s->isFinished()){ AppContext::getExternalToolRegistry()->getByName(s->getToolName())->setValid(s->isValidTool()); AppContext::getExternalToolRegistry()->getByName(s->getToolName())->setVersion(s->getToolVersion()); AppContext::getExternalToolRegistry()->getByName(s->getToolName())->setPath(s->getToolPath()); } } ////////////////////////////////////////////////////////////////////////// // Service ExternalToolSupportService::ExternalToolSupportService() : Service(Service_ExternalToolSupport, tr("External tools support"), tr("Provides support to run external tools from UGENE"), QList() << Service_ProjectView) { projectViewController = NULL; } void ExternalToolSupportService::serviceStateChangedCallback(ServiceState oldState, bool enabledStateChanged) { Q_UNUSED(oldState); if (!enabledStateChanged) { return; } if (isEnabled()) { projectViewController = new ETSProjectViewItemsContoller(this); } else { delete projectViewController; projectViewController = NULL; } } } ugene-1.9.8/src/plugins/external_tool_support/src/mafft/0000755000175000017500000000000011651544323022125 5ustar ilyailyaugene-1.9.8/src/plugins/external_tool_support/src/mafft/MAFFTSupportTask.cpp0000644000175000017500000003401411651544323025710 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "MAFFTSupportTask.h" #include "MAFFTSupport.h" #include #include #include #include #include #include #include #include #include #include #include #include #include namespace U2 { void MAFFTSupportTaskSettings::reset() { gapExtenstionPenalty = -1; gapOpenPenalty = -1; maxNumberIterRefinement=0; inputFilePath=""; } MAFFTSupportTask::MAFFTSupportTask(MAlignmentObject* _mAObject, const MAFFTSupportTaskSettings& _settings) : Task("Run MAFFT alignment task", TaskFlags_NR_FOSCOE), mAObject(_mAObject), settings(_settings) { GCOUNTER( cvar, tvar, "MAFFTSupportTask" ); currentDocument = mAObject->getDocument(); saveTemporaryDocumentTask=NULL; loadTmpDocumentTask=NULL; mAFFTTask=NULL; newDocument=NULL; logParser=NULL; } void MAFFTSupportTask::prepare(){ algoLog.info(tr("MAFFT alignment started")); //Add new subdir for temporary files //Directory name is ExternalToolName + CurrentDate + CurrentTime QString tmpDirName = "MAFFT_"+QString::number(this->getTaskId())+"_"+ QDate::currentDate().toString("dd.MM.yyyy")+"_"+ QTime::currentTime().toString("hh.mm.ss.zzz")+"_"+ QString::number(QCoreApplication::applicationPid())+"/"; url=AppContext::getAppSettings()->getUserAppsSettings()->getTemporaryDirPath() + "/" + tmpDirName + "tmp.fa"; ioLog.details(tr("Saving data to temporary file '%1'").arg(url)); //Check and remove subdir for temporary files QDir tmpDir(AppContext::getAppSettings()->getUserAppsSettings()->getTemporaryDirPath()+"/"+tmpDirName); if(tmpDir.exists()){ foreach(QString file, tmpDir.entryList()){ tmpDir.remove(file); } if(!tmpDir.rmdir(tmpDir.absolutePath())){ stateInfo.setError(tr("Subdir for temporary files exists. Can not remove this directory.")); return; } } if(!tmpDir.mkpath(AppContext::getAppSettings()->getUserAppsSettings()->getTemporaryDirPath()+"/"+tmpDirName)){ stateInfo.setError(tr("Can not create directory for temporary files.")); return; } saveTemporaryDocumentTask=new SaveMSA2SequencesTask(mAObject->getMAlignment(), url, false, BaseDocumentFormats::PLAIN_FASTA); saveTemporaryDocumentTask->setSubtaskProgressWeight(5); addSubTask(saveTemporaryDocumentTask); } QList MAFFTSupportTask::onSubTaskFinished(Task* subTask) { QList res; if(subTask->hasError()) { if(subTask==loadTmpDocumentTask){ if(AppContext::getExternalToolRegistry()->getByName(MAFFT_TOOL_NAME)->isValid()){ stateInfo.setError(tr("Can not open output file: ")+subTask->getError()); }else{ stateInfo.setError(tr("Can not open output file: ")+subTask->getError() +tr(" May be %1 tool path '%2' not valid?") .arg(AppContext::getExternalToolRegistry()->getByName(MAFFT_TOOL_NAME)->getName()) .arg(AppContext::getExternalToolRegistry()->getByName(MAFFT_TOOL_NAME)->getPath())); } }else{ stateInfo.setError(subTask->getError()); } return res; } if(hasError() || isCanceled()) { return res; } QString outputUrl = url+".out.fa"; if (subTask == saveTemporaryDocumentTask){ QStringList arguments; if(settings.gapOpenPenalty != -1) { arguments <<"--op" << QString::number(settings.gapOpenPenalty); } if(settings.gapExtenstionPenalty != -1) { arguments <<"--ep"<getMAlignment().getNumRows(), settings.maxNumberIterRefinement, outputUrl); mAFFTTask = new ExternalToolRunTask(MAFFT_TOOL_NAME, arguments, logParser); mAFFTTask->setSubtaskProgressWeight(95); res.append(mAFFTTask); } else if (subTask == mAFFTTask) { assert(logParser); delete logParser; if (!QFileInfo(outputUrl).exists()) { if (AppContext::getExternalToolRegistry()->getByName(MAFFT_TOOL_NAME)->isValid()){ stateInfo.setError(tr("Output file '%1' not found").arg(outputUrl)); } else { stateInfo.setError(tr("Output file '%3' not found. May be %1 tool path '%2' not valid?") .arg(AppContext::getExternalToolRegistry()->getByName(MAFFT_TOOL_NAME)->getName()) .arg(AppContext::getExternalToolRegistry()->getByName(MAFFT_TOOL_NAME)->getPath()) .arg(outputUrl)); } emit si_stateChanged(); return res; } ioLog.details(tr("Loading output file '%1'").arg(outputUrl)); IOAdapterFactory* iof = AppContext::getIOAdapterRegistry()->getIOAdapterFactoryById(BaseIOAdapters::LOCAL_FILE); loadTmpDocumentTask= new LoadDocumentTask(BaseDocumentFormats::PLAIN_FASTA, outputUrl, iof); loadTmpDocumentTask->setSubtaskProgressWeight(5); res.append(loadTmpDocumentTask); } else if (subTask == loadTmpDocumentTask) { newDocument=loadTmpDocumentTask->takeDocument(); SAFE_POINT(newDocument!=NULL, QString("output document '%1' not loaded").arg(newDocument->getURLString()), res); SAFE_POINT(newDocument->getObjects().length()!=0, QString("no objects in output document '%1'").arg(newDocument->getURLString()), res); //move MAlignment from new alignment to old document resultMA = MSAUtils::seq2ma(newDocument->getObjects(), stateInfo); if (hasError()) { emit si_stateChanged(); //TODO: task can't emit this signal! return res; } mAObject->setMAlignment(resultMA); if(currentDocument != NULL){ currentDocument->setModified(true); } algoLog.info(tr("MAFFT alignment successfully finished")); //new document deleted in destructor of LoadDocumentTask } return res; } Task::ReportResult MAFFTSupportTask::report(){ //Remove subdir for temporary files, that created in prepare if(!url.isEmpty()){ QDir tmpDir(QFileInfo(url).absoluteDir()); foreach(QString file, tmpDir.entryList()){ tmpDir.remove(file); } if(!tmpDir.rmdir(tmpDir.absolutePath())){ stateInfo.setError(tr("Can not remove directory for temporary files.")); emit si_stateChanged(); } } return ReportResult_Finished; } //////////////////////////////////////// //MAFFTWithExtFileSpecifySupportTask MAFFTWithExtFileSpecifySupportTask::MAFFTWithExtFileSpecifySupportTask(const MAFFTSupportTaskSettings& _settings) : Task("Run MAFFT alignment task", TaskFlags_NR_FOSCOE), settings(_settings) { GCOUNTER( cvar, tvar, "MAFFTSupportTask" ); mAObject = NULL; currentDocument = NULL; saveDocumentTask = NULL; loadDocumentTask = NULL; mAFFTSupportTask = NULL; cleanDoc = true; } MAFFTWithExtFileSpecifySupportTask::~MAFFTWithExtFileSpecifySupportTask(){ if (cleanDoc){ delete currentDocument; } } void MAFFTWithExtFileSpecifySupportTask::prepare(){ DocumentFormatConstraints c; c.checkRawData = true; c.supportedObjectTypes += GObjectTypes::MULTIPLE_ALIGNMENT; c.rawData = BaseIOAdapters::readFileHeader(settings.inputFilePath); QList formats = AppContext::getDocumentFormatRegistry()->selectFormats(c); if (formats.isEmpty()) { stateInfo.setError( tr("input_format_error") ); return; } DocumentFormatId alnFormat = formats.first(); IOAdapterFactory* iof = AppContext::getIOAdapterRegistry()->getIOAdapterFactoryById(BaseIOAdapters::url2io(settings.inputFilePath)); QVariantMap hints; hints[DocumentReadingMode_SequenceAsAlignmentHint] = true; loadDocumentTask = new LoadDocumentTask(alnFormat, settings.inputFilePath, iof, hints); addSubTask(loadDocumentTask); } QList MAFFTWithExtFileSpecifySupportTask::onSubTaskFinished(Task* subTask) { QList res; if(subTask->hasError()) { stateInfo.setError(subTask->getError()); return res; } if(hasError() || isCanceled()) { return res; } if (subTask==loadDocumentTask){ currentDocument=loadDocumentTask->getDocument()->clone(); assert(currentDocument!=NULL); assert(currentDocument->getObjects().length()==1); mAObject=qobject_cast(currentDocument->getObjects().first()); assert(mAObject!=NULL); mAFFTSupportTask=new MAFFTSupportTask(mAObject,settings); res.append(mAFFTSupportTask); } else if (subTask == mAFFTSupportTask){ saveDocumentTask = new SaveDocumentTask(currentDocument,AppContext::getIOAdapterRegistry()->getIOAdapterFactoryById(BaseIOAdapters::url2io(settings.inputFilePath)),settings.inputFilePath); res.append(saveDocumentTask); } else if (subTask==saveDocumentTask){ Project* proj = AppContext::getProject(); if (proj == NULL) { res.append(AppContext::getProjectLoader()->openWithProjectTask(currentDocument->getURL(), currentDocument->getGHintsMap())); } else { Document* projDoc = proj->findDocumentByURL(currentDocument->getURL()); if (projDoc != NULL) { projDoc->setLastUpdateTime(); res.append(new LoadUnloadedDocumentAndOpenViewTask(projDoc)); } else { // Add document to project res.append(new AddDocumentAndOpenViewTask(currentDocument)); cleanDoc = false; } } } return res; } Task::ReportResult MAFFTWithExtFileSpecifySupportTask::report(){ return ReportResult_Finished; } //////////////////////////////////////// //ClustalWLogParser MAFFTLogParser::MAFFTLogParser(int _countSequencesInMSA, int _countRefinementIter, const QString& _outputFileName) : countSequencesInMSA(_countSequencesInMSA), countRefinementIter(_countRefinementIter), outputFileName(_outputFileName) { isOutputFileCreated=false; firstDistanceMatrix=false; firstUPGMATree=false; firstProAlign=false; outFile.setFileName(outputFileName); if(outFile.open(QIODevice::WriteOnly)){ isOutputFileCreated=true; } } void MAFFTLogParser::parseOutput(const QString& partOfLog){ outFile.write(partOfLog.toAscii()); } void MAFFTLogParser::parseErrOutput(const QString& partOfLog){ lastPartOfLog=partOfLog.split(QRegExp("(\n|\r)")); lastPartOfLog.first()=lastErrLine+lastPartOfLog.first(); lastErrLine=lastPartOfLog.takeLast(); foreach(QString buf, lastPartOfLog){ if(buf.contains("WARNING") ||buf.contains("rejected.") ||buf.contains("identical.") ||buf.contains("accepted.")){ algoLog.info("MAFFT: " + buf); }else if(!buf.isEmpty()){ algoLog.trace("MAFFT: " + buf); } } } int MAFFTLogParser::getProgress(){ /* Making a distance matrix - 5% Constructing a UPGMA tree - 10% Progressive alignment - 15% Making a distance matrix - 20% Constructing a UPGMA tree - 25% Progressive alignment - 30-80% STEP 001-002-3 - 80-100% */ if(!lastPartOfLog.isEmpty()){ foreach(QString buf, lastPartOfLog){ if(buf.contains("Making")){ if(firstDistanceMatrix){ progress=20; }else{ firstDistanceMatrix=true; progress=5; } } if(buf.contains("Constructing")){ if(firstUPGMATree){ progress=25; }else{ firstUPGMATree=true; progress=10; } } if(buf.contains("Progressive")){ if(!firstProAlign){ firstProAlign=true; progress=15; } } } if(firstProAlign&&firstUPGMATree&&firstDistanceMatrix){ QString lastMessage=lastPartOfLog.last(); if(lastMessage.contains(QRegExp("STEP +\\d+ /"))){ QRegExp rx("STEP +(\\d+) /"); assert(rx.indexIn(lastMessage)>-1); rx.indexIn(lastMessage); progress=rx.cap(1).toInt()*50/countSequencesInMSA+30; }else if(lastMessage.contains(QRegExp("STEP +\\d+-"))){ QRegExp rx("STEP +(\\d+)-"); assert(rx.indexIn(lastMessage)>-1); rx.indexIn(lastMessage); progress=rx.cap(1).toInt()*20/countRefinementIter+80; } } } return progress; } }//namespace ugene-1.9.8/src/plugins/external_tool_support/src/mafft/MAFFTSupport.h0000644000175000017500000000401411651544323024527 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_MAFFT_SUPPORT_H #define _U2_MAFFT_SUPPORT_H #include #include #include "utils/ExternalToolSupportAction.h" #define MAFFT_TOOL_NAME "MAFFT" namespace U2 { class MAFFTSupport : public ExternalTool { Q_OBJECT public: MAFFTSupport(const QString& name, const QString& path = ""); GObjectViewWindowContext* getViewContext(){ return viewCtx; } public slots: void sl_runWithExtFileSpecify(); private: GObjectViewWindowContext* viewCtx; }; class MAFFTSupportContext: public GObjectViewWindowContext { Q_OBJECT public: MAFFTSupportContext(QObject* p); protected slots: void sl_align_with_MAFFT(); protected: virtual void initViewContext(GObjectView* view); virtual void buildMenu(GObjectView* view, QMenu* m); }; class MAFFTSupportAction : public ExternalToolSupprotAction { Q_OBJECT public: MAFFTSupportAction(QObject* p, GObjectView* v, const QString& text, int order) : ExternalToolSupprotAction(p,v,text,order, QStringList(MAFFT_TOOL_NAME)) {} MSAEditor* getMSAEditor() const; private slots: void sl_lockedStateChanged(); }; }//namespace #endif // _U2_MAFFT_SUPPORT_H ugene-1.9.8/src/plugins/external_tool_support/src/mafft/MAFFTSupportTask.h0000644000175000017500000000774111651544323025364 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_MAFFT_SUPPORT_TASK_H #define _U2_MAFFT_SUPPORT_TASK_H #include #include #include #include #include "utils/ExportTasks.h" #include #include "ExternalToolRunTask.h" namespace U2 { /*Options for MAFFT + --op # : Gap opening penalty, default: 1.53 + --ep # : Offset (works like gap extension penalty), default: 0.0 + --maxiterate # : Maximum number of iterative refinement, default: 0 ? --clustalout : Output: clustal format, default: fasta // With this option bad output clustal file is generated.(dkandrov) ? --reorder : Outorder: aligned, default: input order ? --quiet : Do not report progress ? --thread # : Number of threads. (# must be <= number of physical cores - 1) */ class MAFFTLogParser; class MAFFTSupportTaskSettings { public: MAFFTSupportTaskSettings() {reset();} void reset(); float gapOpenPenalty; float gapExtenstionPenalty; int maxNumberIterRefinement; QString inputFilePath; }; class MAFFTSupportTask : public Task { Q_OBJECT public: MAFFTSupportTask(MAlignmentObject* _mAObject, const MAFFTSupportTaskSettings& settings); void prepare(); Task::ReportResult report(); QList onSubTaskFinished(Task* subTask); MAlignment resultMA; private: MAlignmentObject* mAObject; Document* currentDocument; Document* newDocument; QString url; MAFFTLogParser* logParser; SaveMSA2SequencesTask* saveTemporaryDocumentTask; ExternalToolRunTask* mAFFTTask; LoadDocumentTask* loadTmpDocumentTask; MAFFTSupportTaskSettings settings; }; class MAFFTWithExtFileSpecifySupportTask : public Task { Q_OBJECT public: MAFFTWithExtFileSpecifySupportTask(const MAFFTSupportTaskSettings& settings); ~MAFFTWithExtFileSpecifySupportTask(); void prepare(); Task::ReportResult report(); QList onSubTaskFinished(Task* subTask); private: MAlignmentObject* mAObject; Document* currentDocument; bool cleanDoc; SaveDocumentTask* saveDocumentTask; LoadDocumentTask* loadDocumentTask; MAFFTSupportTask* mAFFTSupportTask; MAFFTSupportTaskSettings settings; }; class MAFFTLogParser : public ExternalToolLogParser { public: MAFFTLogParser(int countSequencesInMSA, int countRefinementIter, const QString& outputFileName); ~MAFFTLogParser(){ outFile.close(); } int getProgress(); void parseOutput(const QString& partOfLog); void parseErrOutput(const QString& partOfLog); bool isOutFileCreated(){ return isOutputFileCreated; } private: int countSequencesInMSA; int countRefinementIter; QString outputFileName; QFile outFile; bool isOutputFileCreated; QString lastErrLine; bool firstDistanceMatrix; bool firstUPGMATree; bool firstProAlign; int progress; }; }//namespace #endif // _U2_MAFFT_SUPPORT_TASK_H ugene-1.9.8/src/plugins/external_tool_support/src/mafft/MAFFTWorker.cpp0000644000175000017500000002003411651544323024657 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "MAFFTWorker.h" #include "TaskLocalStorage.h" #include "MAFFTSupport.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include namespace U2 { namespace LocalWorkflow { /**************************** * MAFFTWorkerFactory ****************************/ const QString MAFFTWorkerFactory::ACTOR_ID("mafft"); const QString GAP_OPEN_PENALTY("gap-open-penalty"); const QString GAP_EXT_PENALTY("gap-ext-penalty"); const QString NUM_ITER("iterations-max-num"); const QString EXT_TOOL_PATH("path"); const QString TMP_DIR_PATH("temp-dir"); void MAFFTWorkerFactory::init() { QList p; QList a; Descriptor ind(BasePorts::IN_MSA_PORT_ID(), MAFFTWorker::tr("Input MSA"), MAFFTWorker::tr("Multiple sequence alignment to be processed.")); Descriptor oud(BasePorts::OUT_MSA_PORT_ID(), MAFFTWorker::tr("Multiple sequence alignment"), MAFFTWorker::tr("Result of alignment.")); QMap inM; inM[BaseSlots::MULTIPLE_ALIGNMENT_SLOT()] = BaseTypes::MULTIPLE_ALIGNMENT_TYPE(); p << new PortDescriptor(ind, DataTypePtr(new MapDataType("mafft.in.msa", inM)), true /*input*/); QMap outM; outM[BaseSlots::MULTIPLE_ALIGNMENT_SLOT()] = BaseTypes::MULTIPLE_ALIGNMENT_TYPE(); p << new PortDescriptor(oud, DataTypePtr(new MapDataType("mafft.out.msa", outM)), false /*input*/, true /*multi*/); Descriptor gop(GAP_OPEN_PENALTY, MAFFTWorker::tr("Gap Open Penalty"), MAFFTWorker::tr("Gap Open Penalty")); Descriptor gep(GAP_EXT_PENALTY, MAFFTWorker::tr("Offset"), MAFFTWorker::tr("Works like gap extension penalty")); Descriptor tgp(NUM_ITER, MAFFTWorker::tr("Max Iteration"), MAFFTWorker::tr("Maximum number of iterative refinement")); Descriptor etp(EXT_TOOL_PATH, MAFFTWorker::tr("Tool Path"), MAFFTWorker::tr("External tool path")); Descriptor tdp(TMP_DIR_PATH, MAFFTWorker::tr("Temporary directory"), MAFFTWorker::tr("Directory for temporary files")); a << new Attribute(gop, BaseTypes::NUM_TYPE(), false, QVariant(1.53)); a << new Attribute(gep, BaseTypes::NUM_TYPE(), false, QVariant(0.00)); a << new Attribute(tgp, BaseTypes::NUM_TYPE(), false, QVariant(0)); a << new Attribute(etp, BaseTypes::STRING_TYPE(), true, QVariant("default")); a << new Attribute(tdp, BaseTypes::STRING_TYPE(), true, QVariant("default")); Descriptor desc(ACTOR_ID, MAFFTWorker::tr("Align with MAFFT"), MAFFTWorker::tr("MAFFT is a multiple sequence alignment program for unix-like operating systems. " "

It offers a range of multiple alignment methods, " "L-INS-i (accurate; for alignment of <~200 sequences), " "FFT-NS-2 (fast; for alignment of <~10,000 sequences), etc.

")); ActorPrototype* proto = new IntegralBusActorPrototype(desc, p, a); QMap delegates; { QVariantMap m; m["minimum"] = double(.00); m["maximum"] = double(100.00); m["decimals"] = 2; delegates[GAP_OPEN_PENALTY] = new DoubleSpinBoxDelegate(m); } { QVariantMap m; m["minimum"] = double(.00); m["maximum"] = double(10.00); m["decimals"] = 2; delegates[GAP_EXT_PENALTY] = new DoubleSpinBoxDelegate(m); } { QVariantMap m; m["minimum"] = int(0); m["maximum"] = int(1000); delegates[NUM_ITER] = new SpinBoxDelegate(m); } delegates[EXT_TOOL_PATH] = new URLDelegate("", "executable", false); delegates[TMP_DIR_PATH] = new URLDelegate("", "TmpDir", false, true); proto->setEditor(new DelegateEditor(delegates)); proto->setPrompter(new MAFFTPrompter()); proto->setIconPath(":external_tool_support/images/cmdline.png"); WorkflowEnv::getProtoRegistry()->registerProto(BaseActorCategories::CATEGORY_ALIGNMENT(), proto); DomainFactory* localDomain = WorkflowEnv::getDomainRegistry()->getById(LocalDomainFactory::ID); localDomain->registerEntry(new MAFFTWorkerFactory()); } /**************************** * MAFFTPrompter ****************************/ MAFFTPrompter::MAFFTPrompter(Actor* p) : PrompterBase(p) { } QString MAFFTPrompter::composeRichDoc() { IntegralBusPort* input = qobject_cast(target->getPort(BasePorts::IN_MSA_PORT_ID())); Actor* producer = input->getProducer(BasePorts::IN_MSA_PORT_ID()); QString producerName = producer ? tr(" from %1").arg(producer->getLabel()) : ""; QString doc = tr("Aligns each MSA supplied %1 with \"MAFFT\".") .arg(producerName); return doc; } /**************************** * MAFFTWorker ****************************/ MAFFTWorker::MAFFTWorker(Actor* a) : BaseWorker(a), input(NULL), output(NULL) { } void MAFFTWorker::init() { input = ports.value(BasePorts::IN_MSA_PORT_ID()); output = ports.value(BasePorts::OUT_MSA_PORT_ID()); } bool MAFFTWorker::isReady() { return (input && input->hasMessage()); } Task* MAFFTWorker::tick() { Message inputMessage = getMessageAndSetupScriptValues(input); cfg.gapOpenPenalty=actor->getParameter(GAP_OPEN_PENALTY)->getAttributeValue(); cfg.gapExtenstionPenalty=actor->getParameter(GAP_EXT_PENALTY)->getAttributeValue(); cfg.maxNumberIterRefinement=actor->getParameter(NUM_ITER)->getAttributeValue(); QString path=actor->getParameter(EXT_TOOL_PATH)->getAttributeValue(); if(QString::compare(path, "default", Qt::CaseInsensitive) != 0){ AppContext::getExternalToolRegistry()->getByName(MAFFT_TOOL_NAME)->setPath(path); } path=actor->getParameter(TMP_DIR_PATH)->getAttributeValue(); if(QString::compare(path, "default", Qt::CaseInsensitive) != 0){ AppContext::getAppSettings()->getUserAppsSettings()->setTemporaryDirPath(path); } MAlignment msa = inputMessage.getData().toMap().value(BaseSlots::MULTIPLE_ALIGNMENT_SLOT().getId()).value(); if( msa.isEmpty() ) { return new FailTask(tr("An empty MSA has been supplied to MAFFT.")); } Task* t = new MAFFTSupportTask(new MAlignmentObject(msa), cfg); connect(t, SIGNAL(si_stateChanged()), SLOT(sl_taskFinished())); return t; } void MAFFTWorker::sl_taskFinished() { MAFFTSupportTask* t = qobject_cast(sender()); if (t->getState() != Task::State_Finished) return; QVariant v = qVariantFromValue(t->resultMA); output->put(Message(BaseTypes::MULTIPLE_ALIGNMENT_TYPE(), v)); if (input->isEnded()) { output->setEnded(); } algoLog.info(tr("Aligned %1 with MAFFT").arg(t->resultMA.getName())); } bool MAFFTWorker::isDone() { return !input || input->isEnded(); } void MAFFTWorker::cleanup() { } } //namespace LocalWorkflow } //namespace U2 ugene-1.9.8/src/plugins/external_tool_support/src/mafft/MAFFTWorker.h0000644000175000017500000000356711651544323024340 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_MAFFT_WORKER_H_ #define _U2_MAFFT_WORKER_H_ #include #include #include "MAFFTSupportTask.h" namespace U2 { namespace LocalWorkflow { class MAFFTPrompter : public PrompterBase { Q_OBJECT public: MAFFTPrompter(Actor* p = 0); protected: QString composeRichDoc(); }; class MAFFTWorker : public BaseWorker { Q_OBJECT public: MAFFTWorker(Actor* a); virtual void init(); virtual bool isReady(); virtual Task* tick(); virtual bool isDone(); virtual void cleanup(); private slots: void sl_taskFinished(); protected: CommunicationChannel *input, *output; QString resultName,transId; MAFFTSupportTaskSettings cfg; }; class MAFFTWorkerFactory : public DomainFactory { public: static const QString ACTOR_ID; static void init(); MAFFTWorkerFactory() : DomainFactory(ACTOR_ID) {} virtual Worker* createWorker(Actor* a) {return new MAFFTWorker(a);} }; } // Workflow namespace } // U2 namespace #endif ugene-1.9.8/src/plugins/external_tool_support/src/mafft/MAFFTSupportRunDialog.h0000644000175000017500000000345011651544323026337 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_MAFFT_SUPPORT_RUN_DIALOG_H #define _U2_MAFFT_SUPPORT_RUN_DIALOG_H #include #include #include #include "MAFFTSupportTask.h" namespace U2 { class MAFFTSupportRunDialog : public QDialog, public Ui_MAFFTSupportRunDialog { Q_OBJECT public: MAFFTSupportRunDialog(MAFFTSupportTaskSettings& settings, QWidget* parent); private slots: void sl_align(); private: MAFFTSupportTaskSettings& settings; }; class MAFFTWithExtFileSpecifySupportRunDialog : public QDialog, public Ui_MAFFTSupportRunDialog { Q_OBJECT public: MAFFTWithExtFileSpecifySupportRunDialog(MAFFTSupportTaskSettings& settings, QWidget* parent); private slots: void sl_align(); void sl_inputFileLineEditChanged(const QString& str); private: MAFFTSupportTaskSettings& settings; FileLineEdit* inputFileLineEdit; }; }//namespace #endif // _U2_MAFFT_SUPPORT_RUN_DIALOG_H ugene-1.9.8/src/plugins/external_tool_support/src/mafft/MAFFTSupport.cpp0000644000175000017500000001630511651544323025070 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "MAFFTSupport.h" #include "MAFFTSupportRunDialog.h" #include "MAFFTSupportTask.h" #include "ExternalToolSupportSettingsController.h" #include "ExternalToolSupportSettings.h" #include #include #include #include #include #include #include #include #include #include #include #include namespace U2 { MAFFTSupport::MAFFTSupport(const QString& name, const QString& path) : ExternalTool(name, path) { if (AppContext::getMainWindow()) { viewCtx = new MAFFTSupportContext(this); icon = QIcon(":external_tool_support/images/cmdline.png"); grayIcon = QIcon(":external_tool_support/images/cmdline_gray.png"); warnIcon = QIcon(":external_tool_support/images/cmdline_warn.png"); } #ifdef Q_OS_WIN executableFileName="mafft.bat"; #else #ifdef Q_OS_LINUX executableFileName="mafft"; #endif #endif validationArguments<<"-help"; validMessage="MAFFT"; description=tr("MAFFT is a multiple sequence alignment program for unix-like operating systems. "); versionRegExp=QRegExp("MAFFT v(\\d+\\.\\d+\\w)"); toolKitName="MAFFT"; } void MAFFTSupport::sl_runWithExtFileSpecify(){ //Check that Clustal and tempory directory path defined if (path.isEmpty()){ QMessageBox msgBox; msgBox.setWindowTitle(name); msgBox.setText(tr("Path for %1 tool not selected.").arg(name)); msgBox.setInformativeText(tr("Do you want to select it now?")); msgBox.setStandardButtons(QMessageBox::Yes | QMessageBox::No); msgBox.setDefaultButton(QMessageBox::Yes); int ret = msgBox.exec(); switch (ret) { case QMessageBox::Yes: AppContext::getAppSettingsGUI()->showSettingsDialog(ExternalToolSupportSettingsPageId); break; case QMessageBox::No: return; break; default: assert(NULL); break; } } if (path.isEmpty()){ return; } ExternalToolSupportSettings::checkTemporaryDir(); if (AppContext::getAppSettings()->getUserAppsSettings()->getTemporaryDirPath().isEmpty()){ return; } //Call select input file and setup settings dialog MAFFTSupportTaskSettings settings; MAFFTWithExtFileSpecifySupportRunDialog mAFFTRunDialog(settings, AppContext::getMainWindow()->getQMainWindow()); if(mAFFTRunDialog.exec() != QDialog::Accepted){ return; } assert(!settings.inputFilePath.isEmpty()); // MAFFTWithExtFileSpecifySupportTask* mAFFTSupportTask=new MAFFTWithExtFileSpecifySupportTask(settings); AppContext::getTaskScheduler()->registerTopLevelTask(mAFFTSupportTask); } //////////////////////////////////////// //ClustalWSupportAction ??? MSAEditor* MAFFTSupportAction::getMSAEditor() const { MSAEditor* e = qobject_cast(getObjectView()); assert(e!=NULL); return e; } void MAFFTSupportAction::sl_lockedStateChanged() { StateLockableItem* item = qobject_cast(sender()); assert(item!=NULL); setEnabled(!item->isStateLocked()); } //////////////////////////////////////// //ExternalToolSupportMSAContext MAFFTSupportContext::MAFFTSupportContext(QObject* p) : GObjectViewWindowContext(p, MSAEditorFactory::ID) { } void MAFFTSupportContext::initViewContext(GObjectView* view) { MSAEditor* msaed = qobject_cast(view); assert(msaed!=NULL); if (msaed->getMSAObject() == NULL) { return; } bool objLocked = msaed->getMSAObject()->isStateLocked(); MAFFTSupportAction* alignAction = new MAFFTSupportAction(this, view, tr("Align with MAFFT..."), 2000); addViewAction(alignAction); alignAction->setEnabled(!objLocked); connect(msaed->getMSAObject(), SIGNAL(si_lockedStateChanged()), alignAction, SLOT(sl_lockedStateChanged())); connect(alignAction, SIGNAL(triggered()), SLOT(sl_align_with_MAFFT())); } void MAFFTSupportContext::buildMenu(GObjectView* view, QMenu* m) { QList actions = getViewActions(view); QMenu* alignMenu = GUIUtils::findSubMenu(m, MSAE_MENU_ALIGN); assert(alignMenu!=NULL); foreach(GObjectViewAction* a, actions) { a->addToMenuWithOrder(alignMenu); } } void MAFFTSupportContext::sl_align_with_MAFFT() { //Check that MAFFT and tempory directory path defined if (AppContext::getExternalToolRegistry()->getByName(MAFFT_TOOL_NAME)->getPath().isEmpty()){ QMessageBox msgBox; msgBox.setWindowTitle(MAFFT_TOOL_NAME); msgBox.setText(tr("Path for %1 tool not selected.").arg(MAFFT_TOOL_NAME)); msgBox.setInformativeText(tr("Do you want to select it now?")); msgBox.setStandardButtons(QMessageBox::Yes | QMessageBox::No); msgBox.setDefaultButton(QMessageBox::Yes); int ret = msgBox.exec(); switch (ret) { case QMessageBox::Yes: AppContext::getAppSettingsGUI()->showSettingsDialog(ExternalToolSupportSettingsPageId); break; case QMessageBox::No: return; break; default: assert(NULL); break; } } if (AppContext::getExternalToolRegistry()->getByName(MAFFT_TOOL_NAME)->getPath().isEmpty()){ return; } ExternalToolSupportSettings::checkTemporaryDir(); if (AppContext::getAppSettings()->getUserAppsSettings()->getTemporaryDirPath().isEmpty()){ return; } //Call run MAFFT align dialog MAFFTSupportAction* action = qobject_cast(sender()); assert(action!=NULL); MSAEditor* ed = action->getMSAEditor(); MAlignmentObject* obj = ed->getMSAObject(); if (obj == NULL) return; assert(!obj->isStateLocked()); MAFFTSupportTaskSettings settings; MAFFTSupportRunDialog mAFFTRunDialog(settings, AppContext::getMainWindow()->getQMainWindow()); if(mAFFTRunDialog.exec() != QDialog::Accepted){ return; } MAFFTSupportTask* mAFFTSupportTask=new MAFFTSupportTask(obj, settings); AppContext::getTaskScheduler()->registerTopLevelTask(mAFFTSupportTask); } }//namespace ugene-1.9.8/src/plugins/external_tool_support/src/mafft/MAFFTSupportRunDialog.cpp0000644000175000017500000000767011651544323026702 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "MAFFTSupportRunDialog.h" #include #include #include namespace U2 { //////////////////////////////////////// //MAFFTSupportRunDialog MAFFTSupportRunDialog::MAFFTSupportRunDialog(MAFFTSupportTaskSettings& _settings, QWidget* _parent) : QDialog(_parent), settings(_settings) { setupUi(this); connect(this->cancelButton,SIGNAL(clicked()),this,SLOT(reject())); connect(this->alignButton,SIGNAL(clicked()),this,SLOT(sl_align())); } void MAFFTSupportRunDialog::sl_align(){ if(gapOpenCheckBox->isChecked()) { settings.gapOpenPenalty = gapOpenSpinBox->value(); } if(gapExtCheckBox->isChecked()) { settings.gapExtenstionPenalty = gapExtSpinBox->value(); } if(maxNumberIterRefinementCheckBox->isChecked()){ settings.maxNumberIterRefinement = maxNumberIterRefinementSpinBox->value(); } accept(); } //////////////////////////////////////// //MAFFTWithExtFileSpecifySupportRunDialog MAFFTWithExtFileSpecifySupportRunDialog::MAFFTWithExtFileSpecifySupportRunDialog(MAFFTSupportTaskSettings& _settings, QWidget* _parent) : QDialog(_parent), settings(_settings) { setupUi(this); QWidget * widget = new QWidget(_parent); inputFileLineEdit= new FileLineEdit(DialogUtils::prepareDocumentsFileFilterByObjType(GObjectTypes::MULTIPLE_ALIGNMENT, true), "", false, widget); inputFileLineEdit->setText(""); QToolButton * selectToolPathButton = new QToolButton(widget); selectToolPathButton->setVisible(true); selectToolPathButton->setText("..."); connect(selectToolPathButton, SIGNAL(clicked()), inputFileLineEdit, SLOT(sl_onBrowse())); connect(inputFileLineEdit,SIGNAL(textChanged(QString)),this, SLOT(sl_inputFileLineEditChanged(QString))); QHBoxLayout* layout = new QHBoxLayout(widget); layout->addWidget(inputFileLineEdit); layout->addWidget(selectToolPathButton); QGroupBox* inputFileGroupBox=new QGroupBox(tr("Select input file"),widget); inputFileGroupBox->setLayout(layout); QBoxLayout* parentLayout = qobject_cast(this->layout()); assert(parentLayout); parentLayout->insertWidget(0, inputFileGroupBox); alignButton->setEnabled(false); connect(this->cancelButton, SIGNAL(clicked()), this, SLOT(reject())); connect(this->alignButton, SIGNAL(clicked()), this, SLOT(sl_align())); } void MAFFTWithExtFileSpecifySupportRunDialog::sl_inputFileLineEditChanged(const QString& str){ alignButton->setEnabled(!str.isEmpty()); } void MAFFTWithExtFileSpecifySupportRunDialog::sl_align(){ if(gapOpenCheckBox->isChecked()) { settings.gapOpenPenalty = gapOpenSpinBox->value(); } if(gapExtCheckBox->isChecked()) { settings.gapExtenstionPenalty = gapExtSpinBox->value(); } if(maxNumberIterRefinementCheckBox->isChecked()){ settings.maxNumberIterRefinement = maxNumberIterRefinementSpinBox->value(); } if(!inputFileLineEdit->text().isEmpty()){ settings.inputFilePath=inputFileLineEdit->text(); }else{ assert(NULL); reject(); } accept(); } }//namespace ugene-1.9.8/src/plugins/external_tool_support/src/ui/0000755000175000017500000000000011651544323021445 5ustar ilyailyaugene-1.9.8/src/plugins/external_tool_support/src/ui/MAFFTSupportRunDialog.ui0000644000175000017500000001114411651544323026044 0ustar ilyailya MAFFTSupportRunDialog 0 0 428 178 Align with MAFFT Advanced options Gap opening penalty false 10.000000000000000 0.100000000000000 1.530000000000000 Offset (works like gap extension penalty) false 10.000000000000000 0.000000000000000 Maximum number of iterative refinement false 1000 Qt::Horizontal 40 20 Align Cancel gapOpenCheckBox toggled(bool) gapOpenSpinBox setEnabled(bool) 160 48 356 48 gapExtCheckBox toggled(bool) gapExtSpinBox setEnabled(bool) 160 79 356 79 maxNumberIterRefinementCheckBox toggled(bool) maxNumberIterRefinementSpinBox setEnabled(bool) 160 110 356 110 ugene-1.9.8/src/plugins/external_tool_support/src/ui/ETSSettingsWidget.ui0000644000175000017500000001616111651544323025331 0ustar ilyailya ETSSettingsWidget 0 0 444 582 0 0 0 0 Resource settings You can select path for Check lastest version of external tools package <a href="http://ugene.unipro.ru/external.html">external tools package</a> Qt::Horizontal 40 20 Browse... 0 0 Supported tools QLayout::SetMinimumSize 200 0 Name Path 0 0 0 0 16777215 16777215 0 140 Additional information Qt::AlignLeading|Qt::AlignLeft|Qt::AlignTop QLayout::SetDefaultConstraint 0 0 0 75 16777215 16777215 true <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> <html><head><meta name="qrichtext" content="1" /><style type="text/css"> p, li { white-space: pre-wrap; } </style></head><body style=" font-family:'Sans Serif'; font-size:9pt; font-weight:400; font-style:normal;"> <table border="0" style="-qt-table-type: root; margin-top:4px; margin-bottom:4px; margin-left:4px; margin-right:4px;"> <tr> <td style="border: none;"> <p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Select an external tool to view more information about it.</p></td></tr></table></body></html> 0 0 QFrame::NoFrame Binary path: true Version info ugene-1.9.8/src/plugins/external_tool_support/src/ui/BlastAllSupportDialog.ui0000644000175000017500000005220411651544323026222 0ustar ilyailya BlastAllSupportDialog 0 0 564 322 16777215 522 Request to local BLAST database false false false 0 General options Select search: blastn blastp blastx tblastn tblastx Search for short, nearly exact matches Expectation value Megablast Max hits Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter Off 200 10 20 6 0.000001000000000 100000.000000000000000 10.000000000000000 Select database path: ... Base name for BLAST DB files: Qt::Horizontal 40 20 Number of CPUs being used 0 0 Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter 1 6000 1 2 Advanced options 0 0 Word size Gap costs 2 0 -1 0 0 Matrix BLOSUM62 BLOSUM45 BLOSUM80 PAM30 PAM70 Service plain psi phi PHI pattern Qt::Horizontal 40 20 Qt::Horizontal 40 20 3 0 1 -3 1 -4 1 -2 1 -1 2 -7 2 -5 2 -3 4 -5 5 -4 0 0 Match scores Threshold for extending hits Threshold Qt::Horizontal 40 20 Filters Low complexity filter Human repeats filter Masks Mask for lookup table only false Mask lower case letters Qt::Vertical 20 40 Extension options X dropoff value (in bits) For gapped alignment 999 For ungapped extensions For final gapped alignment 999 Multiple Hits window size Perform gapped alignment true Qt::Vertical 20 40 Qt::Vertical 20 40 Qt::Horizontal 138 20 Restore to Default false Search false true Cancel false ugene-1.9.8/src/plugins/external_tool_support/src/ui/CAP3SupportDialog.ui0000644000175000017500000003351511651544323025216 0ustar ilyailya CAP3SupportDialog 0 0 494 430 400 300 Contig Assembly With CAP3 0 Base Input files (long DNA reads to assembly): Long DNA reads in FASTA or FASTQ formats Add Remove Remove All Qt::Vertical 20 40 Result contig: Result contig alignment in ACE format. true ... Advanced 10 8 Band expansion size: 10 20 Overlap length cutoff: 20 100 40 Base quality cutoff for differences: 15 20 Overlap percent identity cutoff 65 100 80 Base quality cutoff for clipping: 5 12 6 Max gap length in any overlap: 1 100 20 Max qscore sum at differences: 20 1000 200 Overlap similarity score cutoff: Mismatch score factor: 400 1000 900 -100 -1 -5 Gap penalty factor: 1 2 Match score factor: Max number of word matches: 30 1000 300 Clipping range 6 1000 250 Assembly reverse reads true Qt::Vertical 20 143 Qt::Horizontal QDialogButtonBox::Cancel|QDialogButtonBox::Ok buttonBox accepted() CAP3SupportDialog accept() 248 254 157 274 buttonBox rejected() CAP3SupportDialog reject() 316 260 286 274 ugene-1.9.8/src/plugins/external_tool_support/src/ui/TCoffeeSupportRunDialog.ui0000644000175000017500000001125411651544323026524 0ustar ilyailya TCoffeeSupportRunDialog 0 0 428 178 Align with T-Coffee Advanced options Gap opening penalty Gap extension penalty Number of iterations false 1000 false -10000 0 50 -50 false -5000 5000 10 Qt::Horizontal 40 20 Align Cancel maxNumberIterRefinementCheckBox toggled(bool) maxNumberIterRefinementSpinBox setEnabled(bool) 160 110 356 110 gapOpenCheckBox toggled(bool) gapOpenSpinBox setEnabled(bool) 160 48 356 48 gapExtCheckBox toggled(bool) gapExtSpinBox setEnabled(bool) 160 79 356 79 ugene-1.9.8/src/plugins/external_tool_support/src/ui/FormatDBSupportRunDialog.ui0000644000175000017500000002321111651544323026643 0ustar ilyailya FormatDBSupportRunDialog 0 0 400 455 16777215 523 Format database QLayout::SetDefaultConstraint Input data Select input file(s) for formatting database: true ... Or select directory with input files: false false ... false File filter Include files filter true *.fa;*.fasta Exclude files filter false *.pal Type of file(s) protein true nucleotide Output settings Select the path to save the database into: ... Base name for BLAST files: Title for database file: Qt::Horizontal 40 20 Format Cancel inputDirRadioButton toggled(bool) inputDirLineEdit setEnabled(bool) 199 79 183 109 inputDirRadioButton toggled(bool) inputDirToolButton setEnabled(bool) 199 79 376 109 inputFilesRadioButton toggled(bool) inputFilesLineEdit setEnabled(bool) 199 19 183 49 inputFilesRadioButton toggled(bool) inputFilesToolButton setEnabled(bool) 199 19 376 49 inputDirRadioButton toggled(bool) filterGroupBox setEnabled(bool) 199 105 199 202 includeFilterRadioButton toggled(bool) includeFFLineEdit setEnabled(bool) 97 194 268 194 excludeFilterRadioButton toggled(bool) excludeFFLineEdit setEnabled(bool) 97 225 268 225 ugene-1.9.8/src/plugins/external_tool_support/src/ui/SelectPathDialog.ui0000644000175000017500000000653211651544323025166 0ustar ilyailya SelectPathDialog Qt::WindowModal 0 0 400 154 0 0 16777215 154 Path settings 0 0 Select executable file of QLayout::SetMinimumSize ... 0 0 Select directory for tempory files: QLayout::SetMinimumSize ... QLayout::SetMinimumSize Qt::Horizontal 40 20 OK Cancel ugene-1.9.8/src/plugins/external_tool_support/src/ui/ClustalWSupportRunDialog.ui0000644000175000017500000002552611651544323026756 0ustar ilyailya ClustalWSupportRunDialog 0 0 400 428 16777215 3660 Align with ClustalW Advanced options Gap opening penalty false 100.000000000000000 15.000000000000000 Gap extension penalty false 10.000000000000000 6.660000000000000 Weight matrix false IUB CLUSTALW false ArrowCursor Max iterations false 1 999 3 false NONE TREE ALIGNMENT Iteration type Out sequences order false Input Aligned false Protein gap parameters Gap separation distance false 1 10 4 Hydrophilic gaps off No end gap separation penalty Residue-specific gaps off Qt::Horizontal 40 20 Align Cancel gapOpenCheckBox toggled(bool) gapOpenSpinBox setEnabled(bool) 108 48 290 48 gapExtCheckBox toggled(bool) gapExtSpinBox setEnabled(bool) 108 81 290 81 gapDistancesCheckBox toggled(bool) gapDistancesSpinBox setEnabled(bool) 108 156 290 156 maxIterationsCheckBox toggled(bool) maxIterationsSpinBox setEnabled(bool) 108 147 290 147 weightMatrixCheckBox toggled(bool) weightMatrixComboBox setEnabled(bool) 108 114 290 114 iterationTypeCheckBox toggled(bool) iterationTypeComboBox setEnabled(bool) 108 147 290 147 iterationTypeCheckBox toggled(bool) maxIterationsCheckBox setEnabled(bool) 108 147 108 178 outOrderCheckBox toggled(bool) outOrderComboBox setEnabled(bool) 108 209 290 209 ugene-1.9.8/src/plugins/external_tool_support/src/ExternalToolSupportSettingsController.h0000644000175000017500000000611011651544323031001 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_EXTERNAL_TOOL_SUPPORT_SETTINGS_CONTROLLER_H #define _U2_EXTERNAL_TOOL_SUPPORT_SETTINGS_CONTROLLER_H #include #include #include #include namespace U2 { #define ExternalToolSupportSettingsPageId QString("ets") struct ExternalToolInfo{ QString name; QString path; QString description; QString version; bool valid; }; class ExternalToolSupportSettingsPageController : public AppSettingsGUIPageController { Q_OBJECT public: ExternalToolSupportSettingsPageController(QObject* p = NULL); AppSettingsGUIPageState* getSavedState(); void saveState(AppSettingsGUIPageState* s); AppSettingsGUIPageWidget* createWidget(AppSettingsGUIPageState* state); }; class ExternalToolSupportSettingsPageState : public AppSettingsGUIPageState { Q_OBJECT public: QList externalTools; }; class ExternalToolSupportSettingsPageWidget: public AppSettingsGUIPageWidget, public Ui_ETSSettingsWidget { Q_OBJECT public: ExternalToolSupportSettingsPageWidget(ExternalToolSupportSettingsPageController* ctrl); virtual void setState(AppSettingsGUIPageState* state); virtual AppSettingsGUIPageState* getState(QString& err) const; private: QWidget* createPathEditor(QWidget *parent, const QString& path) const; void insertChild(QTreeWidgetItem* rootItem, QString name, int pos); private slots: void sl_toolPathCanged();//QString path); void sl_validateTaskStateChanged(); void sl_itemSelectionChanged(); void sl_onPathEditWidgetClick(); void sl_onBrowseToolKitPath(); void sl_onBrowseToolPackPath(); void sl_linkActivated(QString); private: QMap externalToolsInfo; mutable int buttonsWidth; }; class PathLineEdit : public QLineEdit { Q_OBJECT public: PathLineEdit(const QString& filter, const QString& type, bool multi, QWidget *parent) : QLineEdit(parent), FileFilter(filter), type(type), multi(multi) {} private slots: void sl_onBrowse(); void sl_clear(); private: QString FileFilter; QString type; bool multi; QString path; }; }//namespace #endif // _U2_EXTERNAL_TOOL_SUPPORT_SETTINGS_CONTROLLER_H ugene-1.9.8/src/plugins/external_tool_support/src/ExternalToolRunTask.cpp0000644000175000017500000002025111651544323025464 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "ExternalToolRunTask.h" #include #include #include #include #include #include #include #include #include namespace U2 { ExternalToolRunTask::ExternalToolRunTask(const QString& _toolName, const QStringList& _arguments, ExternalToolLogParser* _logParser) : Task(_toolName + " run task", TaskFlag_None), arguments(_arguments), logParser(_logParser), toolName(_toolName), externalToolProcess(NULL) { ExternalTool * tool = AppContext::getExternalToolRegistry()->getByName(toolName); if (tool == NULL) { setError(tr("Undefined tool: '%1'").arg(toolName)); return; } if (tool->getPath().isEmpty()) { setError(tr("Path for '%1' tool not set").arg(toolName)); return; } if (!tool->isValid()) { // setError(tr("'%1' tool located in '%2' not exists or not valid").arg(toolName).arg(tool->getPath())); // return; } program=tool->getPath(); coreLog.trace("Creating run task for: " + toolName); } ExternalToolRunTask::~ExternalToolRunTask(){ delete externalToolProcess; } void ExternalToolRunTask::prepare(){ if (hasError() || isCanceled()) { return; } } void ExternalToolRunTask::run(){ if (hasError() || isCanceled()) { return; } externalToolProcess = new QProcess();//??? ExternalToolRunTaskHelper* h = new ExternalToolRunTaskHelper(this); connect(externalToolProcess,SIGNAL(readyReadStandardOutput()), h, SLOT(sl_onReadyToReadLog())); connect(externalToolProcess,SIGNAL(readyReadStandardError()), h, SLOT(sl_onReadyToReadErrLog())); algoLog.details(tr("Launching %1 tool: %2 %3").arg(toolName).arg(program).arg(arguments.join(" "))); externalToolProcess->start(program, arguments); //externalToolProcess->state() if (!externalToolProcess->waitForStarted(3000)){ ExternalTool* tool = AppContext::getExternalToolRegistry()->getByName(toolName); if (tool->isValid()){ stateInfo.setError(tr("Can not run %1 tool.").arg(toolName)); } else { stateInfo.setError(tr("Can not run %1 tool. May be tool path '%2' not valid?") .arg(toolName) .arg(AppContext::getExternalToolRegistry()->getByName(toolName)->getPath())); } return; } while(!externalToolProcess->waitForFinished(1000)){ if (isCanceled()) { cancelProcess(); } } { int exitCode = externalToolProcess->exitCode(); if(exitCode != EXIT_SUCCESS && !hasError()) { setError(tr("%1 tool exited with code %2").arg(toolName).arg(exitCode)); } else { algoLog.details(tr("Tool %1 finished successfully").arg(toolName)); } } } Task::ReportResult ExternalToolRunTask::report(){ return ReportResult_Finished; } void ExternalToolRunTask::cancelProcess(){ externalToolProcess->kill(); } ExternalToolRunTaskHelper::ExternalToolRunTaskHelper(ExternalToolRunTask* t) : QObject(t), p(t) { logData.resize(1000); } void ExternalToolRunTaskHelper::sl_onReadyToReadLog(){ assert(p->isRunning()); if (p->externalToolProcess->readChannel() == QProcess::StandardError) { p->externalToolProcess->setReadChannel(QProcess::StandardOutput); } int numberReadChars = p->externalToolProcess->read(logData.data(), logData.size()); while(numberReadChars > 0){ //call log parser QString line = QString::fromLocal8Bit(logData.constData(), numberReadChars); p->logParser->parseOutput(line); numberReadChars = p->externalToolProcess->read(logData.data(), logData.size()); } p->stateInfo.progress = p->logParser->getProgress(); } void ExternalToolRunTaskHelper::sl_onReadyToReadErrLog(){ assert(p->isRunning()); if (p->externalToolProcess->readChannel() == QProcess::StandardOutput) { p->externalToolProcess->setReadChannel(QProcess::StandardError); } int numberReadChars = p->externalToolProcess->read(logData.data(), logData.size()); while(numberReadChars > 0){ //call log parser QString line = QString::fromLocal8Bit(logData.constData(), numberReadChars); p->logParser->parseErrOutput(line); numberReadChars = p->externalToolProcess->read(logData.data(), logData.size()); } QString lastErr = p->logParser->getLastError(); if (!lastErr.isEmpty()) { p->stateInfo.setError(lastErr); } p->stateInfo.progress = p->logParser->getProgress(); } //////////////////////////////////////// //ExternalToolLogParser ExternalToolLogParser::ExternalToolLogParser() { progress=-1; lastLine=""; lastErrLine=""; } void ExternalToolLogParser::parseOutput(const QString& partOfLog){ lastPartOfLog=partOfLog.split(QChar('\n')); lastPartOfLog.first()=lastLine+lastPartOfLog.first(); lastLine=lastPartOfLog.takeLast(); foreach(QString buf, lastPartOfLog){ if(buf.contains("error",Qt::CaseInsensitive)){ ioLog.error(buf); lastErrLine = buf; }else{ ioLog.trace(buf); } } } void ExternalToolLogParser::parseErrOutput(const QString& partOfLog){ lastPartOfLog=partOfLog.split(QChar('\n')); lastPartOfLog.first()=lastErrLine+lastPartOfLog.first(); lastErrLine=lastPartOfLog.takeLast(); foreach(const QString& buf, lastPartOfLog){ if(buf.contains("error",Qt::CaseInsensitive)){ ioLog.error(buf); lastErrLine = buf; }else{ ioLog.trace(buf); } } } bool ExternalToolSupportUtils::removeTmpDir( const QString& tmpDirUrl, QString& errMsg ) { if(!tmpDirUrl.isEmpty()){ QDir tmpDir(tmpDirUrl); foreach(const QString& file, tmpDir.entryList(QDir::NoDotAndDotDot | QDir::AllEntries)){ if (!tmpDir.remove(file)) { errMsg = tr("Can not remove files from temporary directory."); return false; } } if(!tmpDir.rmdir(tmpDir.absolutePath())){ errMsg = tr("Can not remove directory for temporary files."); return false; } } else { errMsg = tr("Can not remove temporary directory: path is empty."); return false; } return true; } QString ExternalToolSupportUtils::createTmpDir( const QString& dirName, int id, QString& errMsg ) { //Directory name is ExternalToolName + unique ID + CurrentDate + CurrentTime QString tmpDirName = dirName+"_"+QString::number(id)+ "_" + QDate::currentDate().toString("dd.MM.yyyy")+"_"+ QTime::currentTime().toString("hh.mm.ss.zzz")+"_"+ QString::number(QCoreApplication::applicationPid())+"/"; QDir tmpDir(AppContext::getAppSettings()->getUserAppsSettings()->getTemporaryDirPath() + "/" + tmpDirName); //Remove dir for temporary files if it exists already if(tmpDir.exists()){ if (!removeTmpDir(tmpDir.absolutePath(), errMsg)) { return QString(); } } if(!tmpDir.mkpath(AppContext::getAppSettings()->getUserAppsSettings()->getTemporaryDirPath() + "/" + tmpDirName)){ errMsg = tr("Can not create directory for temporary files."); return QString(); } return tmpDir.absolutePath(); } }//namespace ugene-1.9.8/src/plugins/external_tool_support/src/blast/0000755000175000017500000000000011651544323022135 5ustar ilyailyaugene-1.9.8/src/plugins/external_tool_support/src/blast/BlastAllWorker.cpp0000644000175000017500000006444711651544323025550 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "BlastAllWorker.h" #include "TaskLocalStorage.h" #include "BlastAllSupport.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include namespace U2 { namespace LocalWorkflow { /**************************** * BlastAllWorkerFactory ****************************/ const QString BlastAllWorkerFactory::ACTOR_ID("blast"); const QString PROGRAM_NAME("blast-type"); const QString DATABASE_PATH("db-path"); const QString DATABASE_NAME("db-name"); const QString EXPECT_VALUE("e-val"); const QString GROUP_NAME("result-name"); const QString EXT_TOOL_PATH("tool-path"); const QString TMP_DIR_PATH("temp-dir"); //Additional options const QString ORIGINAL_OUT("blast-output");//path for output file const QString OUT_TYPE("type-output");//original option -m 0-11 const QString GAPPED_ALN("gapped-aln");//Perform gapped alignment (not available with tblastx) //const QString USE_MEGABLAST("mega-blast");// //const QString WORD_SIZE("word-size");// //const QString GAP_COSTS("gap-cost");//gap-open and gap-ext costs //const QString MATCH_SCORES("match-scores");//mismatchPenalty and matchReward scores //const QString MATRIX("matrix");// void BlastAllWorkerFactory::init() { QList p; QList a; Descriptor ind(BasePorts::IN_SEQ_PORT_ID(), BlastAllWorker::tr("Input sequence"), BlastAllWorker::tr("Sequence for which annotations is searched.")); Descriptor oud(BasePorts::OUT_ANNOTATIONS_PORT_ID(), BlastAllWorker::tr("Annotations"), BlastAllWorker::tr("Found annotations.")); QMap inM; inM[BaseSlots::DNA_SEQUENCE_SLOT()] = BaseTypes::DNA_SEQUENCE_TYPE(); p << new PortDescriptor(ind, DataTypePtr(new MapDataType("blast.seq", inM)), true /*input*/); QMap outM; outM[BaseSlots::ANNOTATION_TABLE_SLOT()] = BaseTypes::ANNOTATION_TABLE_TYPE(); p << new PortDescriptor(oud, DataTypePtr(new MapDataType("blast.seq", outM)), false /*input*/, true /*multi*/); Descriptor pn(PROGRAM_NAME, BlastAllWorker::tr("Search type"), BlastAllWorker::tr("Select type of BLAST searches")); Descriptor dp(DATABASE_PATH, BlastAllWorker::tr("Database Path"), BlastAllWorker::tr("Path with database files")); Descriptor dn(DATABASE_NAME, BlastAllWorker::tr("Database Name"), BlastAllWorker::tr("Base name for BLAST DB files")); Descriptor ev(EXPECT_VALUE, BlastAllWorker::tr("Expected value"), BlastAllWorker::tr("This setting specifies the statistical significance threshold for reporting matches against database sequences.")); Descriptor gn(GROUP_NAME, BlastAllWorker::tr("Annotate as"), BlastAllWorker::tr("Name for annotations")); Descriptor etp(EXT_TOOL_PATH, BlastAllWorker::tr("Tool Path"), BlastAllWorker::tr("External tool path")); Descriptor tdp(TMP_DIR_PATH, BlastAllWorker::tr("Temporary directory"), BlastAllWorker::tr("Directory for temporary files")); Descriptor output(ORIGINAL_OUT, BlastAllWorker::tr("BLAST output"), BlastAllWorker::tr("Location of BLAST output file.")); Descriptor outtype(OUT_TYPE, BlastAllWorker::tr("BLAST output type"), BlastAllWorker::tr("Type of BLAST output file.")); Descriptor ga(GAPPED_ALN, BlastAllWorker::tr("Gapped alignment"), BlastAllWorker::tr("Perform gapped alignment")); // Descriptor umb(USE_MEGABLAST, BlastAllWorker::tr("Use MEGABLAST"), // BlastAllWorker::tr("Activates MEGABLAST algorithm for blastn search")); // Descriptor ws(WORD_SIZE, BlastAllWorker::tr("Word size"), // BlastAllWorker::tr("Specifies the word size" // "
Note:" // "Zero invokes default, 11 for blastn, 28 for megablast, 3 for all others. Only 2 and 3 are available for protein alignment. Word size range for blastn is 7 and up, for megablast 12 and up. ")); // Descriptor gc(GAP_COSTS, BlastAllWorker::tr("Gap costs"), // BlastAllWorker::tr("Specifies the gap opening and extension cost")); // Descriptor ms(MATCH_SCORES, BlastAllWorker::tr("Match scores"), // BlastAllWorker::tr("Specifies penalty for a nucleotide mismatch and reward for a nucleotide match")); // Descriptor matrix(MATRIX, BlastAllWorker::tr("Matrix"), // BlastAllWorker::tr("Specifies which protein scoring matrix to use")); a << new Attribute(pn, BaseTypes::STRING_TYPE(), true, QVariant("blastn")); a << new Attribute(dp, BaseTypes::STRING_TYPE(), true, QVariant("")); a << new Attribute(dn, BaseTypes::STRING_TYPE(), true, QVariant("")); a << new Attribute(etp, BaseTypes::STRING_TYPE(), true, QVariant("default")); a << new Attribute(tdp, BaseTypes::STRING_TYPE(), true, QVariant("default")); a << new Attribute(ev, BaseTypes::NUM_TYPE(), false, QVariant(10.00)); a << new Attribute(gn, BaseTypes::STRING_TYPE(), false, QVariant("")); Attribute* gaAttr= new Attribute(ga, BaseTypes::BOOL_TYPE(), false, QVariant(true)); gaAttr->addRelation(PROGRAM_NAME,"blastn"); gaAttr->addRelation(PROGRAM_NAME,"blastp"); gaAttr->addRelation(PROGRAM_NAME,"blastx"); gaAttr->addRelation(PROGRAM_NAME,"tblastn"); a << gaAttr; // Attribute* umbAttr= new Attribute(umb, BaseTypes::BOOL_TYPE(), false, QVariant(false)); // umbAttr->addRelation(PROGRAM_NAME,"blastn"); // a << umbAttr; // a << new Attribute(ws, BaseTypes::NUM_TYPE(), false, QVariant(0)); // Attribute* msAttr = new Attribute(ms, BaseTypes::STRING_TYPE(), false, QVariant("default")); // msAttr->addRelation(PROGRAM_NAME,"blastn"); // a << msAttr; // Attribute* matrixAttr= new Attribute(matrix, BaseTypes::STRING_TYPE(), false, QVariant("BLOSUM62")); // matrixAttr->addRelation(PROGRAM_NAME,"blastp"); // matrixAttr->addRelation(PROGRAM_NAME,"blastx"); // matrixAttr->addRelation(PROGRAM_NAME,"tblastn"); // matrixAttr->addRelation(PROGRAM_NAME,"tblastx"); // a << matrixAttr; // a << new Attribute(gc, BaseTypes::STRING_TYPE(), false, QVariant("default")); a << new Attribute(output, BaseTypes::STRING_TYPE(), false, QVariant("")); a << new Attribute(outtype, BaseTypes::STRING_TYPE(), false, QVariant("7")); Descriptor desc(ACTOR_ID, BlastAllWorker::tr("Local BLAST search"), BlastAllWorker::tr("Finds annotations for DNA sequence in local database")); ActorPrototype* proto = new IntegralBusActorPrototype(desc, p, a); QMap delegates; { QVariantMap m; m["blastn"] = "blastn"; m["blastp"] = "blastp"; m["blastx"] = "blastx"; m["tblastn"] = "tblastn"; m["tblastx"] = "tblastx"; delegates[PROGRAM_NAME] = new ComboBoxDelegate(m); } { QVariantMap m; m["minimum"] = 0.000001; m["maximum"] = 100000; m["singleStep"] = 1.0; m["decimals"] = 6; delegates[EXPECT_VALUE] = new DoubleSpinBoxDelegate(m); } { QVariantMap m; m["use"] = true; m["not use"] = false; delegates[GAPPED_ALN] = new ComboBoxDelegate(m); } delegates[DATABASE_PATH] = new URLDelegate("", "Database Directory", false, true); delegates[ORIGINAL_OUT] = new URLDelegate("", "out file", false); delegates[EXT_TOOL_PATH] = new URLDelegate("", "executable", false); delegates[TMP_DIR_PATH] = new URLDelegate("", "TmpDir", false, true); // { // QVariantMap m; // m["default"] = "default"; // m["1 -4"] = "1 -4"; // m["1 -3"] = "1 -3"; // m["1 -2"] = "1 -2"; // m["1 -1"] = "1 -1"; // m["2 -7"] = "2 -7"; // m["2 -5"] = "2 -5"; // m["2 -3"] = "2 -3"; // m["4 -5"] = "4 -5"; // m["5 -4"] = "5 -4"; // delegates[MATCH_SCORES] = new ComboBoxDelegate(m); // } // { // QVariantMap m; // m["default"] = "default"; // //if selected blastn // m["0 2 - with scores (1 -4), (1 -3), (1 -2), (1 -1)"] = "0 2"; // m["0 4 - with scores (2 -7), (2 -5), (2 -3)"] = "0 4"; // m["1 1 - with scores (1 -4), (1 -3), (1 -2)"] = "1 1"; // m["1 2 - with scores (1 -4), (1 -3), (1 -2), (1 -1)"] = "1 2"; // m["2 1 - with scores (1 -4), (1 -3), (1 -2), (1 -1)"] = "2 1"; // m["2 2 - with scores (1 -4), (1 -3), (1 -2), (1 -1), (2 -7), (2 -5), (2 -3)"] = "2 2"; // m["2 4 - with scores (2 -7), (2 -5), (2 -3)"] = "2 4"; // m["3 1 - with scores (1 -2), (1 -1)"] = "3 1"; // m["3 2 - with scores (1 -1)"] = "3 2"; // m["3 3 - with scores (2 -3)"] = "3 3"; // m["3 5 - with scores (4 -5), (5 -4)"] = "3 5"; // m["4 1 - with scores (1 -1)"] = "4 1"; // m["4 2 - with scores (1 -1), (2 -7), (2 -5), (2 -3)"] = "4 2"; // m["4 4 - with scores (2 -7), (2 -5), (2 -3)"] = "4 4"; // m["4 5 - with scores (4 -5), (5 -4)"] = "4 5"; // m["5 2 - with scores (2 -3)"] = "5 2"; // m["5 5 - with scores (4 -5), (5 -4)"] = "5 5"; // m["6 2 - with scores (2 -3)"] = "6 2"; // m["6 4 - with scores (2 -3)"] = "6 4"; // m["6 5 - with scores (4 -5), (5 -4)"] = "6 5"; // m["12 8 - with scores (4 -5), (5 -4)"] = "12 8"; // //else // m["9 1 (PAM30, BLOSUM80)"] = "9 1"; // m["5 2 (PAM30)"] = "5 2"; // m["6 2 (PAM30, PAM70, BLOSUM80)"] = "6 2"; // m["7 2 (PAM30, PAM70, BLOSUM62, BLOSUM80)"] = "7 2"; // m["8 1 (PAM30)"] = "8 1"; // m["10 1 (PAM30, PAM70, BLOSUM62, BLOSUM80)"] = "10 1"; // m["8 2 (PAM70, BLOSUM62, BLOSUM80)"] = "8 2"; // m["9 2 (PAM70, BLOSUM62)"] = "9 2"; // m["11 1 (PAM70, BLOSUM62, BLOSUM80)"] = "11 1"; // m["15 2 (BLOSUM45)"] = "15 2"; // m["10 3 (BLOSUM45)"] = "10 3"; // m["11 3 (BLOSUM45)"] = "11 3"; // m["12 3 (BLOSUM45)"] = "12 3"; // m["12 2 (BLOSUM45)"] = "12 2"; // m["13 2 (BLOSUM45)"] = "13 2"; // m["14 2 (BLOSUM45)"] = "14 2"; // m["16 2 (BLOSUM45)"] = "16 2"; // m["15 1 (BLOSUM45)"] = "15 1"; // m["16 1 (BLOSUM45)"] = "16 1"; // m["17 1 (BLOSUM45)"] = "17 1"; // m["18 1 (BLOSUM45)"] = "18 1"; // m["19 1 (BLOSUM45)"] = "19 1"; // m["12 1 (BLOSUM62)"] = "12 1"; // delegates[GAP_COSTS] = new ComboBoxDelegate(m); // } // { // QVariantMap m; // m["BLOSUM62"] = "BLOSUM62"; // m["BLOSUM45"] = "BLOSUM45"; // m["BLOSUM80"] = "BLOSUM80"; // m["PAM30"] = "PAM30"; // m["PAM70"] = "PAM70"; // delegates[MATRIX] = new ComboBoxDelegate(m); // } { QVariantMap m; m["traditional pairwise (-m 0)"] = 0; // m["query-anchored showing identities"] = 1; // m["query-anchored no identities"] = 2; // m["flat query-anchored, show identities"] = 3; // m["flat query-anchored, no identities"] = 4; // m["query-anchored no identities and blunt ends"] = 5; // m["flat query-anchored, no identities and blunt ends"] = 6; m["XML (-m 7)"] = 7; m["tabular without post search sorting (-m 8)"] = 8; // m["tabular with comment lines and post search sorting"] = 9; // m["ascii ASN"] = 10; // m["binary ASN"] = 11; delegates[OUT_TYPE] = new ComboBoxDelegate(m); } proto->setEditor(new DelegateEditor(delegates)); proto->setPrompter(new BlastAllPrompter()); proto->setIconPath(":external_tool_support/images/ncbi.png"); WorkflowEnv::getProtoRegistry()->registerProto(BaseActorCategories::CATEGORY_BASIC(), proto); DomainFactory* localDomain = WorkflowEnv::getDomainRegistry()->getById(LocalDomainFactory::ID); localDomain->registerEntry(new BlastAllWorkerFactory()); } /**************************** * BlastAllPrompter ****************************/ BlastAllPrompter::BlastAllPrompter(Actor* p) : PrompterBase(p) { } QString BlastAllPrompter::composeRichDoc() { IntegralBusPort* input = qobject_cast(target->getPort(BasePorts::IN_SEQ_PORT_ID())); Actor* producer = input->getProducer(BaseSlots::DNA_SEQUENCE_SLOT().getId()); QString unsetStr = ""+tr("unset")+""; QString producerName = tr(" from %1").arg(producer ? producer->getLabel() : unsetStr); QString doc = tr("For sequence %1 find annotations in database %2") .arg(producerName).arg(getHyperlink(DATABASE_NAME, getRequiredParam(DATABASE_NAME))); return doc; } /**************************** * BlastAllWorker ****************************/ BlastAllWorker::BlastAllWorker(Actor* a) : BaseWorker(a), input(NULL), output(NULL) { } void BlastAllWorker::init() { input = ports.value(BasePorts::IN_SEQ_PORT_ID()); output = ports.value(BasePorts::OUT_ANNOTATIONS_PORT_ID()); } bool BlastAllWorker::isReady() { return (input && input->hasMessage()); } Task* BlastAllWorker::tick() { Message inputMessage = getMessageAndSetupScriptValues(input); cfg.programName=actor->getParameter(PROGRAM_NAME)->getAttributeValue(); cfg.databaseNameAndPath=actor->getParameter(DATABASE_PATH)->getAttributeValue() +"/"+ actor->getParameter(DATABASE_NAME)->getAttributeValue(); // if(actor->getParameter(GAP_COSTS)->getAttributeValue() == "default"){ cfg.isDefaultCosts=true; // }else{ // cfg.gapOpenCost=actor->getParameter(GAP_COSTS)->getAttributeValue().split(" ")[0].toInt(); // cfg.gapExtendCost=actor->getParameter(GAP_COSTS)->getAttributeValue().split(" ")[1].toInt(); // } // if(actor->getParameter(MATRIX)->getAttributeValue() == "BLOSUM62"){ cfg.isDefaultMatrix=true; // cfg.matrix=actor->getParameter(MATRIX)->getAttributeValue(); // }else{ // cfg.matrix=actor->getParameter(MATRIX)->getAttributeValue(); // } // if(actor->getParameter(MATCH_SCORES)->getAttributeValue() == "default"){ cfg.isDefautScores=true; // }else{ // cfg.mismatchPenalty=actor->getParameter(MATCH_SCORES)->getAttributeValue().split(" ")[0].toInt(); // cfg.matchReward=actor->getParameter(MATCH_SCORES)->getAttributeValue().split(" ")[1].toInt(); // } cfg.wordSize=0;//actor->getParameter(WORD_SIZE)->getAttributeValue(); // cfg.megablast=actor->getParameter(USE_MEGABLAST)->getAttributeValue(); cfg.isGappedAlignment=actor->getParameter(GAPPED_ALN)->getAttributeValue(); cfg.expectValue=actor->getParameter(EXPECT_VALUE)->getAttributeValue(); cfg.groupName=actor->getParameter(GROUP_NAME)->getAttributeValue(); if(cfg.groupName.isEmpty()){ cfg.groupName="blast result"; } QString path=actor->getParameter(EXT_TOOL_PATH)->getAttributeValue(); if(QString::compare(path, "default", Qt::CaseInsensitive) != 0){ AppContext::getExternalToolRegistry()->getByName(BLASTALL_TOOL_NAME)->setPath(path); } path=actor->getParameter(TMP_DIR_PATH)->getAttributeValue(); if(QString::compare(path, "default", Qt::CaseInsensitive) != 0){ AppContext::getAppSettings()->getUserAppsSettings()->setTemporaryDirPath(path); } DNASequence seq = inputMessage.getData().toMap().value(BaseSlots::DNA_SEQUENCE_SLOT().getId()).value(); if( seq.length() < 1) { return new FailTask(tr("Empty sequence supplied to BLAST")); } cfg.querySequence=seq.seq; DNAAlphabet *alp = AppContext::getDNAAlphabetRegistry()->findAlphabet(seq.seq); cfg.alphabet=alp; //TO DO: Check alphabet if(seq.alphabet->isAmino()) { if(cfg.programName == "blastn" || cfg.programName == "blastx" || cfg.programName == "tblastx") { return new FailTask(tr("Selected BLAST search with nucleotide input sequence")); } } else { if(cfg.programName == "blastp" || cfg.programName == "tblastn") { return new FailTask(tr("Selected BLAST search with amino acid input sequence")); } } cfg.needCreateAnnotations=false; cfg.outputType=actor->getParameter(OUT_TYPE)->getAttributeValue(); cfg.outputOriginalFile=actor->getParameter(ORIGINAL_OUT)->getAttributeValue(); if(cfg.outputType != 7 && cfg.outputOriginalFile.isEmpty()){ return new FailTask(tr("Not selected BLAST output file")); } // //check on wrong input parameters // //word size // if(cfg.programName == "blastn" && cfg.megablast && cfg.wordSize !=0 && cfg.wordSize < 12){ // return new FailTask(tr("Wrong word size selected. Word size must be more or equal 12.")); // }else if (cfg.programName == "blastn" && !cfg.megablast && cfg.wordSize !=0 && cfg.wordSize < 7){ // return new FailTask(tr("Wrong word size selected. Word size must be more or equal 7.")); // }else if (cfg.programName != "blastn" && cfg.wordSize !=0 && (cfg.wordSize !=2 || cfg.wordSize != 3)){ // return new FailTask(tr("Wrong word size selected. Word size must be equal 2 or 3.")); // } // //costs // //For help see http://www.ncbi.nlm.nih.gov/staff/tao/URLAPI/blastall/blastall_node77.html // //Last values is default // QString costs=actor->getParameter(GAP_COSTS)->getAttributeValue(); // QString scores=actor->getParameter(MATCH_SCORES)->getAttributeValue(); // if(cfg.programName != "blastn"){ // if(cfg.matrix == "PAM30" && // (costs != "9 1" || costs != "5 2" || costs != "6 2" || costs != "7 2" || costs != "8 1" || costs != "10 1")){ // //-G 5 -E 2; -G 6 -E 2; -G 7 -E 2; -G 8 -E 1; -G 10 -E 1; -G 9 -E 1 // return new FailTask(tr("Wrong gap costs selected. With matrix PAM30 gap costs must be equal \"9 1\" or \"5 2\" or \"6 2\" or \"7 2\" or \"8 1\" or \"10 1\". " // "\nFor help see http://www.ncbi.nlm.nih.gov/staff/tao/URLAPI/blastall/blastall_node77.html")); // }else if(cfg.matrix == "PAM70" && // (costs != "10 1" || costs != "6 2" || costs != "7 2" || costs != "8 2" || costs != "9 2" || costs != "11 1")){ // //-G 6 -E 2; -G 7 -E 2; -G 8 -E 2; -G 9 -E 2; -G 11 -E 1; -G 10 -E 1 // return new FailTask(tr("Wrong gap costs selected. With matrix PAM70 gap costs must be equal \"10 1\" or \"6 2\" or \"7 2\" or \"8 2\" or \"9 2\" or \"11 1\". " // "\nFor help see http://www.ncbi.nlm.nih.gov/staff/tao/URLAPI/blastall/blastall_node77.html")); // }else if(cfg.matrix == "BLOSUM45" && // (costs != "15 2" || costs != "10 3" || costs != "11 3" || costs != "12 3" || costs != "12 2" || costs != "13 2" || costs != "14 2" || // costs != "16 2" || costs != "15 1" || costs != "16 1" || costs != "17 1" || costs != "18 1" || costs != "19 1")){ // //-G 10 -E 3; -G 11 -E 3; -G 12 -E 3; -G 12 -E 2; -G 13 -E 2, -G 14 -E 2; // //-G 16 -E 2; -G 15 -E 1; -G 16 -E 1; -G 17 -E 1; -G 18 -E 1; -G 19 -E 1; -G 15 -E 2 // return new FailTask(tr("Wrong gap costs selected. With matrix BLOSUM45 gap costs must be equal \"15 2\" or \"10 3\" or \"11 3\" or \"12 3\" or \"12 2\" or \"13 2\" or \"14 2\"" // "or \"16 2\" or \"15 1\" or \"16 1\" or \"17 1\" or \"18 1\" or \"19 1\". " // "\nFor help see http://www.ncbi.nlm.nih.gov/staff/tao/URLAPI/blastall/blastall_node77.html")); // }else if(cfg.matrix == "BLOSUM62" && // (costs != "11 1" || costs != "7 2" || costs != "8 2" || costs != "9 2" || costs != "10 1" || costs != "12 1")){ // //-G 7 -E 2; -G 8 -E 2; -G 9 -E 2; -G 10 -E 1; -G 12 -E 1; -G 11 -E 1 // return new FailTask(tr("Wrong gap costs selected. With matrix BLOSUM62 gap costs must be equal \"11 1\" or \"7 2\" or \"8 2\" or \"8 2\" or \"10 1\" or \"12 1\". " // "\nFor help see http://www.ncbi.nlm.nih.gov/staff/tao/URLAPI/blastall/blastall_node77.html")); // }else if(cfg.matrix == "BLOSUM80" && // (costs != "10 1" || costs != "6 2" || costs != "7 2" || costs != "8 2" || costs != "9 1" || costs != "11 1")){ // //-G 6 -E 2; -G 7 -E 2; -G 8 -E 2; -G 9 -E 1; -G 11 -E 1; -G 10 -E 1 // return new FailTask(tr("Wrong gap costs selected. With matrix BLOSUM80 gap costs must be equal \"10 1\" or \"6 2\" or \"7 2\" or \"8 2\" or \"9 1\" or \"11 1\". " // "\nFor help see http://www.ncbi.nlm.nih.gov/staff/tao/URLAPI/blastall/blastall_node77.html")); // } // }else{ // //For help see http://www.ncbi.nlm.nih.gov/staff/tao/URLAPI/blastall/blastall_node76.html // //Last values is default // if(((scores == "1 -4") || (scores == "1 -3")) && // (costs != "2 2" || costs != "1 2" || costs != "0 2" || costs != "2 1" || costs != "1 1")){ // //-G 1 -E 2; -G 0 -E 2;-G 2 -E 1; -G 1 -E 1; -G 2 -E 2 // return new FailTask(tr("Wrong gap costs selected. With scores \"%1\" gap costs must be equal \"2 2\" or \"1 2\" or \"0 2\" or \"2 1\" or \"1 1\". " // "\nFor help see http://www.ncbi.nlm.nih.gov/staff/tao/URLAPI/blastall/blastall_node76.html").arg(scores)); // }else if(scores == "1 -2" && // (costs != "2 2" || costs != "1 2" || costs != "0 2" || costs != "3 1" || costs != "2 1" || costs != "1 1")){ // //-G 1 -E 2; -G 0 -E 2; -G 3 -E 1; -G 2 -E 1; -G 1 -E 1; -G 2 -E 2 // return new FailTask(tr("Wrong gap costs selected. With scores \"1 -2\" gap costs must be equal \"2 2\" or \"1 2\" or \"0 2\" or \"3 1\" or \"2 1\" or \"1 1\". " // "\nFor help see http://www.ncbi.nlm.nih.gov/staff/tao/URLAPI/blastall/blastall_node76.html")); // }else if(scores == "1 -1" && // (costs != "4 2" || costs != "3 2" || costs != "2 2" || costs != "1 2" || costs != "0 2" || costs != "4 1" || costs != "3 1" || costs != "2 1")){ // //-G 3 -E 2; -G 2 -E 2; -G 1 -E 2; -G 0 -E 2; -G 4 -E 1; -G 3 -E 1; -G 2 -E 1; -G 4 -E 2 :Not supported megablast // return new FailTask(tr("Wrong gap costs selected. With scores \"1 -1\" gap costs must be equal \"4 2\" or \"3 2\" or \"2 2\" or \"1 2\" or \"0 2\" or \"4 1\" or \"3 1\" or \"2 1\". " // "\nFor help see http://www.ncbi.nlm.nih.gov/staff/tao/URLAPI/blastall/blastall_node76.html")); // }else if(((scores == "2 -7") || (scores == "2 -5")) && // (costs != "4 4" || costs != "2 4" || costs != "0 4" || costs != "4 2" || costs != "2 2")){ // //-G 2 -E 4; -G 0 -E 4; -G 4 -E 2; -G 2 -E 2; -G 4 -E 4 // return new FailTask(tr("Wrong gap costs selected. With scores \"%1\" gap costs must be equal \"4 4\" or \"2 4\" or \"0 4\" or \"4 2\" or \"2 2\". " // "\nFor help see http://www.ncbi.nlm.nih.gov/staff/tao/URLAPI/blastall/blastall_node76.html").arg(scores)); // }else if(scores == "2 -3" && // (costs != "6 4" || costs != "4 4" || costs != "2 4" || costs != "0 4" || costs != "3 3" || costs != "6 2" || costs != "5 2" || costs != "4 2" || costs != "2 2")){ // //-G 4 -E 4; -G 2 -E 4; -G 0 -E 4; -G 3 -E 3; -G 6 -E 2; -G 5 -E 2; -G 4 -E 2; -G 2 -E 2, -G 6 -E 4 // return new FailTask(tr("Wrong gap costs selected. With scores \"2 -3\" gap costs must be equal \"6 4\" or \"4 4\" or \"2 4\" or \"0 4\" or \"3 3\" or \"6 2\" or \"5 2\" or \"4 2\" or \"2 2\". " // "\nFor help see http://www.ncbi.nlm.nih.gov/staff/tao/URLAPI/blastall/blastall_node76.html")); // }else if((scores == "4 -5") || (scores == "5 -4") && // (costs != "12 8" || costs != "6 5" || costs != "5 5" || costs != "4 5" || costs != "3 5")){ // //-G 6 -E 5; -G 5 -E 5; -G 4 -E 5; -G 3 -E 5; -G 12 -E 8 // return new FailTask(tr("Wrong gap costs selected. With scores \"%1\" gap costs must be equal \"12 8\" or \"6 5\" or \"5 5\" or \"4 5\" or \"3 5\". " // "\nFor help see http://www.ncbi.nlm.nih.gov/staff/tao/URLAPI/blastall/blastall_node76.html").arg(scores)); // } // } Task* t = new BlastAllSupportTask(cfg); connect(t, SIGNAL(si_stateChanged()), SLOT(sl_taskFinished())); return t; } void BlastAllWorker::sl_taskFinished() { BlastAllSupportTask* t = qobject_cast(sender()); if (t->getState() != Task::State_Finished) return; if(output) { QList res = t->getResultedAnnotations(); QString annName = actor->getParameter(GROUP_NAME)->getAttributeValue(); if(!annName.isEmpty()) { for(int i = 0; iname = annName; } } QVariant v = qVariantFromValue >(res); output->put(Message(BaseTypes::ANNOTATION_TABLE_TYPE(), v)); if (input->isEnded()) { output->setEnded(); } } } bool BlastAllWorker::isDone() { return !input || input->isEnded(); } void BlastAllWorker::cleanup() { } } //namespace LocalWorkflow } //namespace U2 ugene-1.9.8/src/plugins/external_tool_support/src/blast/BlastAllSupportTask.h0000644000175000017500000000527311651544323026233 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_BLASTALL_SUPPORT_TASK_H #define _U2_BLASTALL_SUPPORT_TASK_H #include #include #include #include #include #include #include "utils/ExportTasks.h" #include #include #include "ExternalToolRunTask.h" #include "utils/BlastTaskSettings.h" #include #include namespace U2 { class BlastAllSupportTask : public Task { Q_OBJECT public: BlastAllSupportTask(const BlastTaskSettings& settings); void prepare(); QList onSubTaskFinished(Task* subTask); Task::ReportResult report(); QList getResultedAnnotations() const; BlastTaskSettings getSettings() const; private: ExternalToolLogParser* logParser; QString url; SaveDocumentTask* saveTemporaryDocumentTask; ExternalToolRunTask* blastAllTask; BlastTaskSettings settings; DNASequenceObject* sequenceObject; Document* tmpDoc; QList result; void parseResult(); void parseHit(const QDomNode &xml); void parseHsp(const QDomNode &xml,const QString &id, const QString &def, const QString &accession); }; class BlastAllSupportMultiTask : public Task { Q_OBJECT public: BlastAllSupportMultiTask(QList& settingsList, QString& url); void prepare(); QList onSubTaskFinished(Task* subTask); Task::ReportResult report(); QString generateReport() const; private: QList settingsList; Document* doc; QString url; }; }//namespace #endif // _U2_FORMATDB_SUPPORT_TASK_H ugene-1.9.8/src/plugins/external_tool_support/src/blast/BlastAllSupportTask.cpp0000644000175000017500000004263311651544323026567 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "BlastAllSupportTask.h" #include "BlastAllSupport.h" #include #include #include #include #include #include #include #include #include #include #include //#include namespace U2 { BlastAllSupportTask::BlastAllSupportTask(const BlastTaskSettings& _settings) : Task("Run NCBI BlastAll task", TaskFlags_NR_FOSCOE), settings(_settings) { GCOUNTER( cvar, tvar, "BlastAllSupportTask" ); blastAllTask=NULL; logParser=NULL; tmpDoc=NULL; saveTemporaryDocumentTask=NULL; sequenceObject=NULL; addTaskResource(TaskResourceUsage(RESOURCE_THREAD, settings.numberOfProcessors)); } void BlastAllSupportTask::prepare(){ //Add new subdir for temporary files //Directory name is ExternalToolName + CurrentDate + CurrentTime QString tmpDirName = "BlastAll_"+QString::number(this->getTaskId())+"_"+ QDate::currentDate().toString("dd.MM.yyyy")+"_"+ QTime::currentTime().toString("hh.mm.ss.zzz")+"_"+ QString::number(QCoreApplication::applicationPid())+"/"; //Check and remove subdir for temporary files QDir tmpDir(AppContext::getAppSettings()->getUserAppsSettings()->getTemporaryDirPath()+"/"+tmpDirName); if(tmpDir.exists()){ foreach(const QString& file, tmpDir.entryList()){ tmpDir.remove(file); } if(!tmpDir.rmdir(tmpDir.absolutePath())){ stateInfo.setError(tr("Subdirectory for temporary files exists. Can not remove this directory.")); return; } } if(!tmpDir.mkpath(AppContext::getAppSettings()->getUserAppsSettings()->getTemporaryDirPath()+"/"+tmpDirName)){ stateInfo.setError(tr("Can not create directory for temporary files.")); return; } QList objects; sequenceObject= new DNASequenceObject("input sequence", DNASequence(settings.querySequence, settings.alphabet)); objects.append(sequenceObject); url=AppContext::getAppSettings()->getUserAppsSettings()->getTemporaryDirPath() + "/" + tmpDirName + "tmp.fa"; tmpDoc = new Document(AppContext::getDocumentFormatRegistry()->getFormatById(BaseDocumentFormats::PLAIN_FASTA), AppContext::getIOAdapterRegistry()->getIOAdapterFactoryById(BaseIOAdapters::LOCAL_FILE), GUrl(url), objects); saveTemporaryDocumentTask = new SaveDocumentTask(tmpDoc, AppContext::getIOAdapterRegistry()->getIOAdapterFactoryById(BaseIOAdapters::LOCAL_FILE), url); saveTemporaryDocumentTask->setSubtaskProgressWeight(5); addSubTask(saveTemporaryDocumentTask); } QList BlastAllSupportTask::onSubTaskFinished(Task* subTask) { QList res; if(subTask->hasError()) { stateInfo.setError(subTask->getError()); return res; } if(hasError() || isCanceled()) { return res; } if(subTask==saveTemporaryDocumentTask){ delete tmpDoc;//sequenceObject also deleted at this place QStringList arguments; arguments <<"-p"<< settings.programName; if(!settings.filter.isEmpty()){ arguments <<"-F"<setSubtaskProgressWeight(95); res.append(blastAllTask); } else if(subTask==blastAllTask){ assert(logParser); delete logParser; if(settings.outputType == 7){ if(!QFileInfo(settings.outputOriginalFile).exists()){ if(AppContext::getExternalToolRegistry()->getByName(BLASTALL_TOOL_NAME)->isValid()){ stateInfo.setError(tr("Output file not found")); }else{ stateInfo.setError(tr("Output file not found. May be %1 tool path '%2' not valid?") .arg(AppContext::getExternalToolRegistry()->getByName(BLASTALL_TOOL_NAME)->getName()) .arg(AppContext::getExternalToolRegistry()->getByName(BLASTALL_TOOL_NAME)->getPath())); } emit si_stateChanged(); return res; } parseResult(); if((!result.isEmpty())&&(settings.needCreateAnnotations)) { // Document* d = AppContext::getProject()->findDocumentByURL(url); //assert(d==NULL); if(!settings.outputResFile.isEmpty()) { IOAdapterFactory* iof = AppContext::getIOAdapterRegistry()->getIOAdapterFactoryById(BaseIOAdapters::LOCAL_FILE); DocumentFormat* df = AppContext::getDocumentFormatRegistry()->getFormatById(BaseDocumentFormats::PLAIN_GENBANK); Document *d = df->createNewDocument(iof, settings.outputResFile); d->addObject(settings.aobj); AppContext::getProject()->addDocument(d); } for(QMutableListIterator it_ad(result); it_ad.hasNext(); ) { AnnotationData * ad = it_ad.next().data(); U2Region::shift(settings.offsInGlobalSeq, ad->location->regions); } res.append(new CreateAnnotationsTask(settings.aobj, settings.groupName, result)); } } } return res; } Task::ReportResult BlastAllSupportTask::report(){ if( url.isEmpty() ) { return ReportResult_Finished; } //Remove subdir for temporary files, that created in prepare QDir tmpDir(QFileInfo(url).absoluteDir()); foreach(QString file, tmpDir.entryList()){ tmpDir.remove(file); } if(!tmpDir.rmdir(tmpDir.absolutePath())){ stateInfo.setError(tr("Can not remove directory for temporary files.")); emit si_stateChanged(); } return ReportResult_Finished; } BlastTaskSettings BlastAllSupportTask::getSettings() const { return settings; } QList BlastAllSupportTask::getResultedAnnotations() const { return result; } void BlastAllSupportTask::parseResult() { QDomDocument xmlDoc; QFile file(settings.outputOriginalFile); if (!file.open(QIODevice::ReadOnly)){ stateInfo.setError("Can't open output file"); return; } if (!xmlDoc.setContent(&file)) { //stateInfo.setError("Can't read output file"); file.close(); return; } file.close(); QDomNodeList hits = xmlDoc.elementsByTagName("Hit"); for(int i = 0; iqualifiers.push_back(U2Qualifier("bit-score", elem.text())); } elem = xml.lastChildElement("Hsp_score"); if(!elem.isNull()) { ad->qualifiers.push_back(U2Qualifier("score", elem.text())); } elem = xml.lastChildElement("Hsp_evalue"); if(!elem.isNull()) { ad->qualifiers.push_back(U2Qualifier("E-value", elem.text())); } elem = xml.lastChildElement("Hsp_query-from"); QString fr = elem.text(); from = elem.text().toInt(&isOk); if(!isOk) { stateInfo.setError("Can't get location"); return; } elem = xml.lastChildElement("Hsp_query-to"); to = elem.text().toInt(&isOk); if(!isOk) { stateInfo.setError("Can't get location"); return; } elem = xml.lastChildElement("Hsp_hit-from"); if(!elem.isNull()) { ad->qualifiers.push_back(U2Qualifier("hit-from", elem.text())); } elem = xml.lastChildElement("Hsp_hit-to"); if(!elem.isNull()) { ad->qualifiers.push_back(U2Qualifier("hit-to", elem.text())); } elem = xml.lastChildElement("Hsp_hit-frame"); int frame = elem.text().toInt(&isOk); if(!isOk) { stateInfo.setError("Can't get location"); return; } QString frame_txt = (frame < 0) ? "complement" : "direct"; ad->qualifiers.push_back(U2Qualifier( "source_frame", frame_txt )); ad->setStrand(frame < 0 ? U2Strand::Complementary : U2Strand::Direct); elem = xml.lastChildElement("Hsp_identity"); identities = elem.text().toInt(&isOk); if(!isOk) { stateInfo.setError("Can't get identity"); return; } elem = xml.lastChildElement("Hsp_gaps"); if(!elem.isNull()) { gaps = elem.text().toInt(&isOk); if(!isOk) { stateInfo.setError("Can't get gaps"); return; } } elem = xml.lastChildElement("Hsp_align-len"); align_len = elem.text().toInt(&isOk); if(!isOk) { stateInfo.setError("Can't get align length"); return; } if( from != -1 && to != -1 ) { if(from <= to){ ad->location->regions << U2Region( from-1, to - from + 1); }else{ ad->location->regions << U2Region( to-1, from - to + 1); } } else { stateInfo.setError("Can't evaluate location"); return; } if( align_len != -1 ) { if( gaps != -1 ) { float percent = (float)gaps / (float)align_len * 100; QString str = QString::number(gaps) + "/" + QString::number(align_len) + " (" + QString::number(percent,'g',4) + "%)"; ad->qualifiers.push_back(U2Qualifier( "gaps", str )); } if( identities != -1 ) { float percent = (float)identities / (float)align_len * 100; QString str = QString::number(identities) + '/' + QString::number(align_len) + " (" + QString::number(percent,'g',4) + "%)"; ad->qualifiers.push_back(U2Qualifier( "identities", str )); } } ad->qualifiers.push_back(U2Qualifier("id",id)); ad->qualifiers.push_back(U2Qualifier("def",def)); ad->qualifiers.push_back(U2Qualifier("accession",accession)); ad->name = "blast result"; result.append(ad); } /////////////////////////////////////// //BlastAllSupportMultiTask BlastAllSupportMultiTask::BlastAllSupportMultiTask(QList& _settingsList, QString& _url): Task("Run NCBI BlastAll multitask", TaskFlags_NR_FOSCOE | TaskFlag_ReportingIsSupported), settingsList(_settingsList), doc(NULL), url(_url) { } void BlastAllSupportMultiTask::prepare(){ //create document IOAdapterFactory* iof = AppContext::getIOAdapterRegistry()->getIOAdapterFactoryById(BaseIOAdapters::LOCAL_FILE); DocumentFormat* df = AppContext::getDocumentFormatRegistry()->getFormatById(BaseDocumentFormats::PLAIN_GENBANK); doc = df->createNewDocument(iof, url); foreach(BlastTaskSettings settings, settingsList){ settings.needCreateAnnotations=false; addSubTask(new BlastAllSupportTask(settings)); } } QList BlastAllSupportMultiTask::onSubTaskFinished(Task *subTask){ QList res; if(subTask->hasError()) { stateInfo.setError(subTask->getError()); return res; } if(hasError() || isCanceled()) { return res; } BlastAllSupportTask* s=qobject_cast(subTask); if(s != NULL){ BlastTaskSettings settings=s->getSettings(); assert(settings.aobj!=NULL); QList result=s->getResultedAnnotations(); if(result.length()>0){ doc->addObject(settings.aobj); for(QMutableListIterator it_ad(result); it_ad.hasNext(); ) { AnnotationData * ad = it_ad.next().data(); U2Region::shift(settings.offsInGlobalSeq, ad->location->regions); } res.append(new CreateAnnotationsTask(settings.aobj, settings.groupName, result)); } } return res; } Task::ReportResult BlastAllSupportMultiTask::report(){ if(!hasError()){ if(doc->getObjects().length() > 0){ AppContext::getProject()->addDocument(doc); }else{ setReportingEnabled(true); } } return ReportResult_Finished; } QString BlastAllSupportMultiTask::generateReport() const { QString res; res+=""; res+=""; res+=""; res+=""; res+=""; res+="
" + tr("Source file") + "" + settingsList.at(0).queryFile + "
" + tr("Used databse") + "" + settingsList.at(0).databaseNameAndPath + "
" + tr("No any results found") + "
"; return res; } }//namespace ugene-1.9.8/src/plugins/external_tool_support/src/blast/BlastAllSupport.h0000644000175000017500000000340711651544323025405 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_BLASTALL_SUPPORT_H #define _U2_BLASTALL_SUPPORT_H #include #include #define BLASTALL_TOOL_NAME "BlastAll" namespace U2 { class BlastAllSupport : public ExternalTool { Q_OBJECT public: BlastAllSupport(const QString& name, const QString& path = ""); GObjectViewWindowContext* getViewContext(){ return viewCtx; } public slots: void sl_runWithExtFileSpecify(); private: GObjectViewWindowContext* viewCtx; QString lastDBPath; QString lastDBName; }; class BlastAllSupportContext: public GObjectViewWindowContext { Q_OBJECT public: BlastAllSupportContext(QObject* p); protected slots: void sl_showDialog(); protected: virtual void initViewContext(GObjectView* view); virtual void buildMenu(GObjectView* view, QMenu* m); private: QString lastDBPath; QString lastDBName; }; }//namespace #endif // _U2_BLASTALL_SUPPORT_H ugene-1.9.8/src/plugins/external_tool_support/src/blast/FormatDBSupport.h0000644000175000017500000000247311651544323025347 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_FORMATDB_SUPPORT_H #define _U2_FORMATDB_SUPPORT_H #include #include "utils/ExternalToolSupportAction.h" #define FORMATDB_TOOL_NAME "FormatDB" #define MAKEBLASTDB_TOOL_NAME "MakeBLASTDB" namespace U2 { class FormatDBSupport : public ExternalTool { Q_OBJECT public: FormatDBSupport(const QString& name, const QString& path = ""); public slots: void sl_runWithExtFileSpecify(); }; }//namespace #endif // _U2_FORMATDB_SUPPORT_H ugene-1.9.8/src/plugins/external_tool_support/src/blast/FormatDBSupportRunDialog.cpp0000644000175000017500000001556111651544323027511 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "FormatDBSupportRunDialog.h" #include #include #include #include namespace U2 { //////////////////////////////////////// //FormatDBWithExtFileSpecifySupportRunDialog FormatDBSupportRunDialog::FormatDBSupportRunDialog(FormatDBSupportTaskSettings& _settings, QWidget* _parent) : QDialog(_parent), settings(_settings) { setupUi(this); connect(inputFilesToolButton,SIGNAL(clicked()),SLOT(sl_onBrowseInputFiles())); connect(inputDirToolButton,SIGNAL(clicked()),SLOT(sl_onBrowseInputDir())); connect(databasePathToolButton,SIGNAL(clicked()),SLOT(sl_onBrowseDatabasePath())); connect(inputFilesLineEdit,SIGNAL(textChanged(QString)), SLOT(sl_lineEditChanged())); connect(databasePathLineEdit,SIGNAL(textChanged(QString)), SLOT(sl_lineEditChanged())); connect(databaseTitleLineEdit,SIGNAL(textChanged(QString)), SLOT(sl_lineEditChanged())); connect(baseNamelineEdit,SIGNAL(textChanged(QString)), SLOT(sl_lineEditChanged())); if(!settings.inputFilesPath.isEmpty()){ QString names=settings.inputFilesPath.join(";"); inputFilesLineEdit->setText(names); inputFilesLineEdit->setReadOnly(true); inputFilesToolButton->setDisabled(true); inputDirLineEdit->setDisabled(true); inputDirRadioButton->setDisabled(true); inputDirToolButton->setDisabled(true); } formatButton->setEnabled(false); connect(this->cancelButton,SIGNAL(clicked()),this,SLOT(reject())); connect(this->formatButton,SIGNAL(clicked()),this,SLOT(sl_formatDB())); } void FormatDBSupportRunDialog::sl_onBrowseInputFiles(){ LastOpenDirHelper lod(""); QString name; QStringList lst = QFileDialog::getOpenFileNames(NULL, tr("Select file(s)"), lod.dir, ""); name = lst.join(";"); if (!lst.isEmpty()) { lod.url = lst.first(); } if (!name.isEmpty()) { inputFilesLineEdit->setText(name); } inputFilesLineEdit->setFocus(); if(lst.length()==1){ QFileInfo fi(lst.first()); if(databaseTitleLineEdit->text().isEmpty()){ databaseTitleLineEdit->setText(fi.baseName()); } if(baseNamelineEdit->text().isEmpty()){ baseNamelineEdit->setText(fi.baseName()); } } } void FormatDBSupportRunDialog::sl_onBrowseInputDir(){ LastOpenDirHelper lod(""); QString name; lod.url = name = QFileDialog::getExistingDirectory(NULL, tr("Select a directory with input files"), lod.dir); if (!name.isEmpty()) { inputDirLineEdit->setText(name); } inputDirLineEdit->setFocus(); } void FormatDBSupportRunDialog::sl_onBrowseDatabasePath(){ LastOpenDirHelper lod("Database Directory"); QString name; lod.url = name = QFileDialog::getExistingDirectory(NULL, tr("Select a directory to save database files"), lod.dir); if (!name.isEmpty()) { databasePathLineEdit->setText(name); } databasePathLineEdit->setFocus(); } void FormatDBSupportRunDialog::sl_lineEditChanged(){ bool isFilledInputFilesOrDirLineEdit = (!inputFilesLineEdit->text().isEmpty() && inputFilesRadioButton->isChecked()) || (!inputDirLineEdit->text().isEmpty() && inputDirRadioButton->isChecked()); bool isFilledDatabasePathLineEdit = !databasePathLineEdit->text().isEmpty(); bool isFilledDatabaseTitleLineEdit = !databaseTitleLineEdit->text().isEmpty(); bool isFilledBaseNamelineEdit = !baseNamelineEdit->text().isEmpty(); formatButton->setEnabled(isFilledBaseNamelineEdit && isFilledDatabasePathLineEdit && isFilledDatabaseTitleLineEdit && isFilledInputFilesOrDirLineEdit); } QStringList getAllFiles(QDir inputDir, QString filter, bool isIncludeFilter=true); void FormatDBSupportRunDialog::sl_formatDB(){ if(inputFilesRadioButton->isChecked()){ settings.inputFilesPath=inputFilesLineEdit->text().split(';'); }else{ if(includeFilterRadioButton->isChecked()){ settings.inputFilesPath=getAllFiles(QDir(inputDirLineEdit->text()), includeFFLineEdit->text()); }else{ settings.inputFilesPath=getAllFiles(QDir(inputDirLineEdit->text()), excludeFFLineEdit->text(), false); } } settings.databaseTitle=databaseTitleLineEdit->text(); if ((!databasePathLineEdit->text().endsWith('/'))&&(!databasePathLineEdit->text().endsWith('\\'))){ settings.outputPath=databasePathLineEdit->text()+'/'+baseNamelineEdit->text(); }else{ settings.outputPath=databasePathLineEdit->text()+baseNamelineEdit->text(); } settings.typeOfFile=proteinTypeRadioButton->isChecked(); accept(); } QStringList getAllFiles(QDir inputDir, QString filter, bool isIncludeFilter){ QStringList includeFileList; QStringList excludeFilesList; QStringList filters=filter.split(';'); //IsIncludeFilter == true //get files from input dir foreach(QString inputFileName, inputDir.entryList(filters, QDir::NoDotAndDotDot | QDir::NoSymLinks | QDir::Dirs | QDir::Files)){ inputFileName = inputDir.absolutePath()+"/"+inputFileName; QFileInfo inputFileInfo(inputFileName); if(inputFileInfo.isFile()){ includeFileList.append(inputFileName); } } //get files from subdirs foreach(QString inputFileName, inputDir.entryList(QDir::NoDotAndDotDot | QDir::NoSymLinks | QDir::Dirs | QDir::Files)){ inputFileName = inputDir.absolutePath()+"/"+inputFileName; QFileInfo inputFileInfo(inputFileName); if(inputFileInfo.isDir()){ includeFileList.append(getAllFiles(QDir(inputFileName), filter, true)); excludeFilesList.append(getAllFiles(QDir(inputFileName), filter, false)); }else{ if(!includeFileList.contains(inputFileName)){ //IsIncludeFilter == false excludeFilesList.append(inputFileName); } } } if(isIncludeFilter){ return includeFileList; }else{ return excludeFilesList; } } }//namespace ugene-1.9.8/src/plugins/external_tool_support/src/blast/BlastAllWorker.h0000644000175000017500000000366611651544323025211 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_BLASTALL_WORKER_H_ #define _U2_BLASTALL_WORKER_H_ #include #include #include "BlastAllSupportTask.h" #include "utils/BlastTaskSettings.h" namespace U2 { namespace LocalWorkflow { class BlastAllPrompter : public PrompterBase { Q_OBJECT public: BlastAllPrompter(Actor* p = 0); protected: QString composeRichDoc(); }; class BlastAllWorker : public BaseWorker { Q_OBJECT public: BlastAllWorker(Actor* a); virtual void init(); virtual bool isReady(); virtual Task* tick(); virtual bool isDone(); virtual void cleanup(); private slots: void sl_taskFinished(); protected: CommunicationChannel *input, *output; QString resultName,transId; BlastTaskSettings cfg; }; class BlastAllWorkerFactory : public DomainFactory { public: static const QString ACTOR_ID; static void init(); BlastAllWorkerFactory() : DomainFactory(ACTOR_ID) {} virtual Worker* createWorker(Actor* a) {return new BlastAllWorker(a);} }; } // Workflow namespace } // U2 namespace #endif ugene-1.9.8/src/plugins/external_tool_support/src/blast/FormatDBSupport.cpp0000644000175000017500000001123211651544323025673 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "FormatDBSupport.h" #include "FormatDBSupportRunDialog.h" #include "FormatDBSupportTask.h" #include "ExternalToolSupportSettingsController.h" #include "ExternalToolSupportSettings.h" #include #include #include #include #include #include #include #include #include #include #include namespace U2 { FormatDBSupport::FormatDBSupport(const QString& name, const QString& path) : ExternalTool(name, path) { if (AppContext::getMainWindow() != NULL) { icon = QIcon(":external_tool_support/images/ncbi.png"); grayIcon = QIcon(":external_tool_support/images/ncbi_gray.png"); warnIcon = QIcon(":external_tool_support/images/ncbi_warn.png"); } assert((name == FORMATDB_TOOL_NAME)||(name == MAKEBLASTDB_TOOL_NAME)); if(name == FORMATDB_TOOL_NAME){ #ifdef Q_OS_WIN executableFileName="formatdb.exe"; #else #ifdef Q_OS_LINUX executableFileName="formatdb"; #endif #endif validationArguments<<"--help"; validMessage="formatdb"; description=tr("The formatdb formats protein or" " nucleotide source databases before these databases" " can be searched by blastall."); versionRegExp=QRegExp("formatdb (\\d+\\.\\d+\\.\\d+)"); toolKitName="BLAST"; }else if(name == MAKEBLASTDB_TOOL_NAME){ #ifdef Q_OS_WIN executableFileName="makeblastdb.exe"; #else #ifdef Q_OS_LINUX executableFileName="makeblastdb"; #endif #endif validationArguments<<"-help"; validMessage="makeblastdb"; description=tr("The makeblastdb formats protein or" " nucleotide source databases before these databases" " can be searched by other BLAST+ tools."); versionRegExp=QRegExp("Application to create BLAST databases, version (\\d+\\.\\d+\\.\\d+\\+?)"); toolKitName="BLAST+"; } } void FormatDBSupport::sl_runWithExtFileSpecify(){ //Check that formatDB or makeblastdb and tempory directory path defined if (path.isEmpty()){ QMessageBox msgBox; if(name == FORMATDB_TOOL_NAME){ msgBox.setWindowTitle("BLAST "+name); msgBox.setText(tr("Path for BLAST %1 tool not selected.").arg(name)); }else{ msgBox.setWindowTitle("BLAST+ "+name); msgBox.setText(tr("Path for BLAST+ %1 tool not selected.").arg(name)); } msgBox.setInformativeText(tr("Do you want to select it now?")); msgBox.setStandardButtons(QMessageBox::Yes | QMessageBox::No); msgBox.setDefaultButton(QMessageBox::Yes); int ret = msgBox.exec(); switch (ret) { case QMessageBox::Yes: AppContext::getAppSettingsGUI()->showSettingsDialog(ExternalToolSupportSettingsPageId); break; case QMessageBox::No: return; break; default: assert(NULL); break; } } if (path.isEmpty()){ return; } ExternalToolSupportSettings::checkTemporaryDir(); if (AppContext::getAppSettings()->getUserAppsSettings()->getTemporaryDirPath().isEmpty()){ return; } //Call select input file and setup settings dialog FormatDBSupportTaskSettings settings; FormatDBSupportRunDialog formatDBRunDialog(settings, AppContext::getMainWindow()->getQMainWindow()); if(formatDBRunDialog.exec() != QDialog::Accepted){ return; } //assert(!settings.inputFilePath.isEmpty()); // FormatDBSupportTask* formatDBSupportTask=new FormatDBSupportTask(name, settings); AppContext::getTaskScheduler()->registerTopLevelTask(formatDBSupportTask); } }//namespace ugene-1.9.8/src/plugins/external_tool_support/src/blast/BlastAllSupportRunDialog.cpp0000644000175000017500000002701211651544323027543 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "BlastAllSupportRunDialog.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include namespace U2 { //////////////////////////////////////// //BlastAllSupportRunDialog BlastAllSupportRunDialog::BlastAllSupportRunDialog(DNASequenceObject* _dnaso, BlastTaskSettings& _settings, QString &_lastDBPath, QString &_lastDBName, QWidget* _parent) : BlastRunCommonDialog(_settings, _parent), dnaso(_dnaso), lastDBPath(_lastDBPath), lastDBName(_lastDBName) { CreateAnnotationModel ca_m; ca_m.data->name = "misc_feature"; ca_m.hideAnnotationName = true; ca_m.hideLocation = true; ca_m.sequenceObjectRef = GObjectReference(dnaso); ca_m.sequenceLen = dnaso->getSequenceLen(); ca_c = new CreateAnnotationWidgetController(ca_m, this); //lowerCaseCheckBox->hide(); QWidget *wdgt = ca_c->getWidget(); wdgt->setMinimumHeight(150); verticalLayout_4->addWidget(wdgt); if(dnaso->getAlphabet()->getType() == DNAAlphabet_AMINO){ programName->removeItem(0);//blastn programName->removeItem(1);//blastx programName->removeItem(2);//tblastx settings.isNucleotideSeq=false; }else{ programName->removeItem(1);//blastp programName->removeItem(2);//tblastn settings.isNucleotideSeq=true; } databasePathLineEdit->setText(lastDBPath); baseNameLineEdit->setText(lastDBName); connect(cancelButton,SIGNAL(clicked()),SLOT(reject())); } void BlastAllSupportRunDialog::sl_lineEditChanged(){ bool isFilledDatabasePathLineEdit = !databasePathLineEdit->text().isEmpty(); bool isFilledBaseNameLineEdit = !baseNameLineEdit->text().isEmpty(); okButton->setEnabled(isFilledBaseNameLineEdit && isFilledDatabasePathLineEdit); } void BlastAllSupportRunDialog::sl_runQuery(){ QString error = ca_c->validate(); if (!error.isEmpty()) { QMessageBox::critical(NULL, tr("Wrong parameters for creating annotations"), error); return; } settings.outputResFile=ca_c->getModel().newDocUrl; if(ca_c->isNewObject()) { settings.aobj = new AnnotationTableObject("Annotations"); settings.aobj->addObjectRelation(GObjectRelation(ca_c->getModel().sequenceObjectRef, GObjectRelationRole::SEQUENCE)); } else { ca_c->prepareAnnotationObject(); settings.aobj = ca_c->getModel().getAnnotationObject(); } settings.groupName=ca_c->getModel().groupName; settings.alphabet=dnaso->getAlphabet(); getSettings(settings); lastDBPath=databasePathLineEdit->text(); lastDBName=baseNameLineEdit->text(); settings.outputType=7;//By default set output file format to xml accept(); } //////////////////////////////////////// //BlastAllWithExtFileSpecifySupportRunDialog BlastAllWithExtFileSpecifySupportRunDialog::BlastAllWithExtFileSpecifySupportRunDialog(QList& _settingsList, QString &_lastDBPath, QString &_lastDBName,QWidget* _parent) : BlastRunCommonDialog(_settingsList[0], _parent), settingsList(_settingsList), lastDBPath(_lastDBPath), lastDBName(_lastDBName) { ca_c=NULL; wasNoOpenProject=false; //create input file widget QWidget * widget = new QWidget(_parent); inputFileLineEdit= new FileLineEdit("","", false, widget); inputFileLineEdit->setReadOnly(true); inputFileLineEdit->setText(""); QToolButton * selectToolPathButton = new QToolButton(widget); selectToolPathButton->setVisible(true); selectToolPathButton->setText("..."); connect(selectToolPathButton, SIGNAL(clicked()), inputFileLineEdit, SLOT(sl_onBrowse())); connect(inputFileLineEdit,SIGNAL(textChanged(QString)),this, SLOT(sl_inputFileLineEditChanged(QString))); QHBoxLayout* layout = new QHBoxLayout(widget); layout->addWidget(inputFileLineEdit); layout->addWidget(selectToolPathButton); QGroupBox* inputFileGroupBox=new QGroupBox(tr("Select input file"),widget); inputFileGroupBox->setLayout(layout); QBoxLayout* parentLayout = qobject_cast(this->layout()); assert(parentLayout); parentLayout->insertWidget(0, inputFileGroupBox); databasePathLineEdit->setText(lastDBPath); baseNameLineEdit->setText(lastDBName); connect(cancelButton,SIGNAL(clicked()),SLOT(sl_cancel())); connect(this,SIGNAL(rejected()),SLOT(sl_cancel())); } void BlastAllWithExtFileSpecifySupportRunDialog::sl_lineEditChanged(){ bool isFilledDatabasePathLineEdit = !databasePathLineEdit->text().isEmpty(); bool isFilledBaseNameLineEdit = !baseNameLineEdit->text().isEmpty(); bool isInputFileLineEdit = !inputFileLineEdit->text().isEmpty(); okButton->setEnabled(isFilledBaseNameLineEdit && isFilledDatabasePathLineEdit && isInputFileLineEdit); } void BlastAllWithExtFileSpecifySupportRunDialog::sl_inputFileLineEditChanged(const QString& str){ if(!str.isEmpty()){ QFileInfo fi(str); if (fi.exists()){ QList tasks; Project* proj = AppContext::getProject(); if (proj == NULL) { wasNoOpenProject=true; tasks.append( AppContext::getProjectLoader()->createNewProjectTask() ); } DocumentFormatConstraints c; c.checkRawData = true; c.supportedObjectTypes += GObjectTypes::SEQUENCE; c.rawData = BaseIOAdapters::readFileHeader(str); QList formats = AppContext::getDocumentFormatRegistry()->selectFormats(c); if (formats.isEmpty()) { //stateInfo.setError(tr("input_format_error")); //show error message return; } DocumentFormatId df = formats.first(); LoadDocumentTask* loadDocumentTask= new LoadDocumentTask(df, str, AppContext::getIOAdapterRegistry()->getIOAdapterFactoryById(BaseIOAdapters::url2io(str))); connect(loadDocumentTask,SIGNAL(si_stateChanged()),SLOT(sl_inputFileLoadTaskStateChanged())); tasks.append(loadDocumentTask); AppContext::getTaskScheduler()->registerTopLevelTask(new MultiTask("Load documents and open project",tasks)); }else{ return; } } } void BlastAllWithExtFileSpecifySupportRunDialog::sl_inputFileLoadTaskStateChanged(){ LoadDocumentTask* s=qobject_cast(sender()); if((s->isFinished())&&(!s->hasError())){ int numOfSequences=0; foreach(GObject* gobj, s->getDocument()->getObjects()){ if(gobj->getGObjectType()==GObjectTypes::SEQUENCE){ numOfSequences++; } } settingsList.clear(); sequencesRefList.clear(); if(numOfSequences ==0){ QMessageBox::critical(this, tr("Wrong input file"), tr("This file not contain any sequence.")); inputFileLineEdit->setText(""); return; } foreach(GObject* gobj, s->getDocument()->getObjects()){ if(gobj->getGObjectType()==GObjectTypes::SEQUENCE){ DNASequenceObject* seq=(DNASequenceObject*)gobj; BlastTaskSettings localSettings; localSettings.querySequence=seq->getDNASequence().seq; localSettings.alphabet=seq->getDNASequence().alphabet; if(localSettings.alphabet->getType() != DNAAlphabet_AMINO){ localSettings.isNucleotideSeq=true; } localSettings.queryFile=s->getURL().getURLString(); settingsList.append(localSettings); sequencesRefList.append(GObjectReference(gobj)); } } //DNASequenceObject* seq=(DNASequenceObject*)sequencesRefList[0]; CreateAnnotationModel ca_m; ca_m.data->name = "misc_feature"; ca_m.hideAnnotationName = true; ca_m.hideLocation = true; ca_m.sequenceObjectRef = sequencesRefList[0];//GObjectReference(seq);//not needed, it unused ca_m.sequenceLen = 10;//dnaso->getSequenceLen(); if(ca_c != NULL){ verticalLayout_4->removeWidget(ca_c->getWidget()); delete ca_c; } ca_c = new CreateAnnotationWidgetController(ca_m, this); QWidget *wdgt = ca_c->getWidget(); wdgt->setMinimumHeight(150); verticalLayout_4->addWidget(wdgt); } sl_lineEditChanged(); } void BlastAllWithExtFileSpecifySupportRunDialog::sl_runQuery(){ QString error = ca_c->validate(); if (!error.isEmpty()) { QMessageBox::critical(this, tr("Wrong parameters for creating annotations"), error); return; } for(int i=0; igetModel().newDocUrl; if(ca_c->isNewObject()) { settingsList[i].aobj = new AnnotationTableObject(sequencesRefList[i].objName+" annotations"); settingsList[i].aobj->addObjectRelation(GObjectRelation(sequencesRefList[i], GObjectRelationRole::SEQUENCE)); } else { assert(NULL);//allways created new document for annotations // ca_c->prepareAnnotationObject(); // settings.aobj = caControllers.at(i)->getModel().getAnnotationObject(); } settingsList[i].groupName=ca_c->getModel().groupName; getSettings(settingsList[i]); //setup filters settingsList[i].outputType=7;//By default set output file format to xml } bool docAlreadyInProject=false; Project* proj=AppContext::getProject(); foreach(Document* doc, proj->getDocuments()){ if(doc->getURL() == inputFileLineEdit->text()){ docAlreadyInProject=true; } } if(!docAlreadyInProject){ QString url = inputFileLineEdit->text(); AppContext::getTaskScheduler()->registerTopLevelTask(AppContext::getProjectLoader()->openWithProjectTask(url)); } lastDBPath=databasePathLineEdit->text(); lastDBName=baseNameLineEdit->text(); accept(); } void BlastAllWithExtFileSpecifySupportRunDialog::sl_cancel(){ if(qobject_cast(sender()) == NULL){ reject(); return; } if(wasNoOpenProject){ AppContext::getTaskScheduler()->registerTopLevelTask(AppContext::getProjectService()->closeProjectTask()); } } }//namespace ugene-1.9.8/src/plugins/external_tool_support/src/blast/FormatDBSupportTask.cpp0000644000175000017500000000630011651544323026516 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "FormatDBSupportTask.h" #include "FormatDBSupport.h" #include #include #include #include #include #include #include #include namespace U2 { void FormatDBSupportTaskSettings::reset() { inputFilesPath=QList(); outputPath=""; databaseTitle=""; typeOfFile=true; } FormatDBSupportTask::FormatDBSupportTask(const QString& name, const FormatDBSupportTaskSettings& _settings) : Task("Run NCBI FormatDB task", TaskFlags_NR_FOSCOE), toolName(name), settings(_settings) { GCOUNTER( cvar, tvar, "FormatDBSupportTask" ); formatDBTask=NULL; logParser=NULL; } void FormatDBSupportTask::prepare(){ QStringList arguments; assert((toolName == FORMATDB_TOOL_NAME)||(toolName == MAKEBLASTDB_TOOL_NAME)); if(toolName == FORMATDB_TOOL_NAME){ for(int i=0; i< settings.inputFilesPath.length(); i++){ if(settings.inputFilesPath[i].contains(" ")){ stateInfo.setError(tr("Input files paths contain space characters.")); return; } } arguments <<"-i"<< settings.inputFilesPath.join(" "); arguments <<"-l"<< settings.outputPath+"formatDB.log"; arguments <<"-n"<< settings.outputPath; arguments <<"-p"<< (settings.typeOfFile ? "T" : "F"); }else if (toolName == MAKEBLASTDB_TOOL_NAME){ for(int i=0; i< settings.inputFilesPath.length(); i++){ settings.inputFilesPath[i]="\""+settings.inputFilesPath[i]+"\""; } arguments <<"-in"<< settings.inputFilesPath.join(" "); arguments <<"-logfile"<< settings.outputPath+"MakeBLASTDB.log"; if(settings.outputPath.contains(" ")){ stateInfo.setError(tr("Output database path contain space characters.")); return; } arguments <<"-out"<< settings.outputPath; arguments <<"-dbtype"<< (settings.typeOfFile ? "prot" : "nucl"); } logParser=new ExternalToolLogParser(); formatDBTask=new ExternalToolRunTask(toolName, arguments, logParser); formatDBTask->setSubtaskProgressWeight(95); addSubTask(formatDBTask); } Task::ReportResult FormatDBSupportTask::report(){ return ReportResult_Finished; } }//namespace ugene-1.9.8/src/plugins/external_tool_support/src/blast/BlastAllSupport.cpp0000644000175000017500000001760711651544323025747 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "BlastAllSupport.h" #include "BlastAllSupportRunDialog.h" #include "BlastAllSupportTask.h" #include "utils/BlastTaskSettings.h" #include "ExternalToolSupportSettingsController.h" #include "ExternalToolSupportSettings.h" #include "utils/ExternalToolSupportAction.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include namespace U2 { BlastAllSupport::BlastAllSupport(const QString& name, const QString& path) : ExternalTool(name, path) { if (AppContext::getMainWindow()) { viewCtx = new BlastAllSupportContext(this); icon = QIcon(":external_tool_support/images/ncbi.png"); grayIcon = QIcon(":external_tool_support/images/ncbi_gray.png"); warnIcon = QIcon(":external_tool_support/images/ncbi_warn.png"); } #ifdef Q_OS_WIN executableFileName="blastall.exe"; #else #ifdef Q_OS_LINUX executableFileName="blastall"; #endif #endif validationArguments<<"--help"; validMessage="blastall"; description=tr("The blastall is the old program developed and distributed \ by the NCBI for running BLAST searches. The NCBI recommends \ that people start using the programs of the BLAST+ package instead."); versionRegExp=QRegExp("blastall (\\d+\\.\\d+\\.\\d+)"); toolKitName="BLAST"; lastDBName=""; lastDBPath=""; } void BlastAllSupport::sl_runWithExtFileSpecify(){ //Check that blastall and tempory directory path defined if (path.isEmpty()){ QMessageBox msgBox; msgBox.setWindowTitle("BLAST "+name); msgBox.setText(tr("Path for BLAST %1 tool not selected.").arg(name)); msgBox.setInformativeText(tr("Do you want to select it now?")); msgBox.setStandardButtons(QMessageBox::Yes | QMessageBox::No); msgBox.setDefaultButton(QMessageBox::Yes); int ret = msgBox.exec(); switch (ret) { case QMessageBox::Yes: AppContext::getAppSettingsGUI()->showSettingsDialog(ExternalToolSupportSettingsPageId); break; case QMessageBox::No: return; break; default: assert(NULL); break; } } if (path.isEmpty()){ return; } ExternalToolSupportSettings::checkTemporaryDir(); if (AppContext::getAppSettings()->getUserAppsSettings()->getTemporaryDirPath().isEmpty()){ return; } //Call select input file and setup settings dialog QList settingsList; BlastTaskSettings settings; settingsList.append(settings); BlastAllWithExtFileSpecifySupportRunDialog blastallRunDialog(settingsList, lastDBPath, lastDBName, AppContext::getMainWindow()->getQMainWindow()); if(blastallRunDialog.exec() != QDialog::Accepted){ return; } BlastAllSupportMultiTask* blastallSupportMultiTask = new BlastAllSupportMultiTask(settingsList,settingsList[0].outputResFile); AppContext::getTaskScheduler()->registerTopLevelTask(blastallSupportMultiTask); } //////////////////////////////////////// //BlastAllSupportContext BlastAllSupportContext::BlastAllSupportContext(QObject* p) : GObjectViewWindowContext(p, ANNOTATED_DNA_VIEW_FACTORY_ID) { lastDBName=""; lastDBPath=""; } void BlastAllSupportContext::initViewContext(GObjectView* view) { AnnotatedDNAView* av = qobject_cast(view); assert(av!=NULL); Q_UNUSED(av); ExternalToolSupprotAction* queryAction = new ExternalToolSupprotAction(this, view, tr("Query with BLAST..."), 2000, QStringList(BLASTALL_TOOL_NAME)); addViewAction(queryAction); connect(queryAction, SIGNAL(triggered()), SLOT(sl_showDialog())); } void BlastAllSupportContext::buildMenu(GObjectView* view, QMenu* m) { QList actions = getViewActions(view); QMenu* analyseMenu = GUIUtils::findSubMenu(m, ADV_MENU_ANALYSE); assert(analyseMenu!=NULL); foreach(GObjectViewAction* a, actions) { a->addToMenuWithOrder(analyseMenu); } } void BlastAllSupportContext::sl_showDialog() { //Checking the BlastAll path and temporary directory path are defined if (AppContext::getExternalToolRegistry()->getByName(BLASTALL_TOOL_NAME)->getPath().isEmpty()){ QMessageBox msgBox; msgBox.setWindowTitle("BLAST "+QString(BLASTALL_TOOL_NAME)); msgBox.setText(tr("Path for BLAST %1 tool not selected.").arg(BLASTALL_TOOL_NAME)); msgBox.setInformativeText(tr("Do you want to select it now?")); msgBox.setStandardButtons(QMessageBox::Yes | QMessageBox::No); msgBox.setDefaultButton(QMessageBox::Yes); int ret = msgBox.exec(); switch (ret) { case QMessageBox::Yes: AppContext::getAppSettingsGUI()->showSettingsDialog(ExternalToolSupportSettingsPageId); break; case QMessageBox::No: return; break; default: assert(NULL); break; } } if (AppContext::getExternalToolRegistry()->getByName(BLASTALL_TOOL_NAME)->getPath().isEmpty()){ return; } ExternalToolSupportSettings::checkTemporaryDir(); if (AppContext::getAppSettings()->getUserAppsSettings()->getTemporaryDirPath().isEmpty()){ return; } QAction* a = (QAction*)sender(); GObjectViewAction* viewAction = qobject_cast(a); AnnotatedDNAView* av = qobject_cast(viewAction->getObjectView()); assert(av); BlastTaskSettings settings; ADVSequenceObjectContext* seqCtx = av->getSequenceInFocus(); BlastAllSupportRunDialog dlg(seqCtx->getSequenceObject(), settings, lastDBPath, lastDBName, av->getWidget()); //Call run blastall dialog if(dlg.exec() == QDialog::Accepted) { //prepare query const QByteArray& sequence = seqCtx->getSequenceData(); DNASequenceSelection* s = seqCtx->getSequenceSelection(); QVector regions; if(s->isEmpty()) { int seqLen = seqCtx->getSequenceLen(); regions.append(U2Region(0, seqLen)); } else { regions = s->getSelectedRegions(); } foreach(const U2Region& r, regions) { QByteArray query( sequence.constData() + r.startPos, r.length ); settings.querySequence = query; // DNATranslation * aminoT = (dlg.translateToAmino ? seqCtx->getAminoTT() : 0); // DNATranslation * complT = (dlg.translateToAmino ? seqCtx->getComplementTT() : 0); settings.offsInGlobalSeq=r.startPos; Task * t = new BlastAllSupportTask(settings); AppContext::getTaskScheduler()->registerTopLevelTask( t ); } } } }//namespace ugene-1.9.8/src/plugins/external_tool_support/src/blast/FormatDBSupportRunDialog.h0000644000175000017500000000303611651544323027150 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_FORMATDB_SUPPORT_RUN_DIALOG_H #define _U2_FORMATDB_SUPPORT_RUN_DIALOG_H #include #include #include #include "FormatDBSupportTask.h" namespace U2 { class FormatDBSupportRunDialog : public QDialog, public Ui_FormatDBSupportRunDialog { Q_OBJECT public: FormatDBSupportRunDialog(FormatDBSupportTaskSettings& settings, QWidget* parent); private slots: void sl_formatDB(); void sl_lineEditChanged(); void sl_onBrowseInputFiles(); void sl_onBrowseInputDir(); void sl_onBrowseDatabasePath(); private: FormatDBSupportTaskSettings& settings; }; }//namespace #endif // _U2_FORMATDB_SUPPORT_RUN_DIALOG_H ugene-1.9.8/src/plugins/external_tool_support/src/blast/FormatDBSupportTask.h0000644000175000017500000000712611651544323026172 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_FORMATDB_SUPPORT_TASK_H #define _U2_FORMATDB_SUPPORT_TASK_H #include #include #include #include #include "utils/ExportTasks.h" #include #include "ExternalToolRunTask.h" namespace U2 { /*Options for FormatDB -t Title for database file [String] Optional -i Input file(s) for formatting [File In] Optional -l Logfile name: [File Out] Optional default = formatdb.log -p Type of file T - protein F - nucleotide [T/F] Optional default = T -o Parse options T - True: Parse SeqId and create indexes. F - False: Do not parse SeqId. Do not create indexes. [T/F] Optional default = F -a Input file is database in ASN.1 format (otherwise FASTA is expected) T - True, F - False. [T/F] Optional default = F -b ASN.1 database in binary mode T - binary, F - text mode. [T/F] Optional default = F -e Input is a Seq-entry [T/F] Optional default = F -n Base name for BLAST files [String] Optional -v Database volume size in millions of letters [Integer] Optional default = 4000 -s Create indexes limited only to accessions - sparse [T/F] Optional default = F -V Verbose: check for non-unique string ids in the database [T/F] Optional default = F -L Create an alias file with this name use the gifile arg (below) if set to calculate db size use the BLAST db specified with -i (above) [File Out] Optional -F Gifile (file containing list of gi's) [File In] Optional -B Binary Gifile produced from the Gifile specified above [File Out] Optional -T Taxid file to set the taxonomy ids in ASN.1 deflines [File In] Optional */ //class FormatDBLogParser; class FormatDBSupportTaskSettings { public: FormatDBSupportTaskSettings() {reset();} void reset(); QStringList inputFilesPath; QString outputPath; QString databaseTitle; /*-p Type of file T - protein F - nucleotide*/ bool typeOfFile; }; class FormatDBSupportTask : public Task { Q_OBJECT public: FormatDBSupportTask(const QString& name, const FormatDBSupportTaskSettings& settings); void prepare(); Task::ReportResult report(); private: ExternalToolLogParser* logParser; ExternalToolRunTask* formatDBTask; QString toolName; FormatDBSupportTaskSettings settings; }; //class FormatDBLogParser : public ExternalToolLogParser { //public: // FormatDBLogParser(int countSequencesInMSA); // int getProgress(); //private: // int countSequencesInMSA; //}; }//namespace #endif // _U2_FORMATDB_SUPPORT_TASK_H ugene-1.9.8/src/plugins/external_tool_support/src/blast/BlastAllSupportRunDialog.h0000644000175000017500000000451111651544323027207 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_BLASTALL_SUPPORT_RUN_DIALOG_H #define _U2_BLASTALL_SUPPORT_RUN_DIALOG_H #include #include #include #include #include #include "BlastAllSupportTask.h" #include "utils/BlastRunCommonDialog.h" namespace U2 { class BlastAllSupportRunDialog : public BlastRunCommonDialog { Q_OBJECT public: BlastAllSupportRunDialog(DNASequenceObject* dnaso, BlastTaskSettings& settings, QString &_lastDBPath, QString &_lastDBName, QWidget* parent); protected slots: virtual void sl_runQuery(); virtual void sl_lineEditChanged(); private: DNASequenceObject* dnaso; QString &lastDBPath; QString &lastDBName; }; class BlastAllWithExtFileSpecifySupportRunDialog : public BlastRunCommonDialog { Q_OBJECT public: BlastAllWithExtFileSpecifySupportRunDialog(QList& settings, QString &_lastDBPath, QString &_lastDBName, QWidget* parent); protected slots: void sl_runQuery(); void sl_lineEditChanged(); private slots: void sl_cancel(); void sl_inputFileLineEditChanged(const QString& str); void sl_inputFileLoadTaskStateChanged(); private: FileLineEdit* inputFileLineEdit; bool wasNoOpenProject; QList& settingsList; QList sequencesRefList; QString &lastDBPath; QString &lastDBName; }; }//namespace #endif // _U2_BLASTALL_SUPPORT_RUN_DIALOG_H ugene-1.9.8/src/plugins/external_tool_support/src/ExternalToolSupportPlugin.h0000644000175000017500000000301511651544323026374 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_EXTERNAL_TOOL_SUPPORT_PLUGIN_H_ #define _U2_EXTERNAL_TOOL_SUPPORT_PLUGIN_H_ #include #include namespace U2 { class ETSProjectViewItemsContoller; class ExternalToolSupportPlugin : public Plugin { Q_OBJECT public: ExternalToolSupportPlugin(); ~ExternalToolSupportPlugin(); private slots: void sl_validateTaskStateChanged(); }; class ExternalToolSupportService: public Service { Q_OBJECT public: ExternalToolSupportService(); protected: virtual void serviceStateChangedCallback(ServiceState oldState, bool enabledStateChanged); ETSProjectViewItemsContoller* projectViewController; }; } #endif ugene-1.9.8/src/plugins/external_tool_support/src/ETSProjectViewItemsContoller.h0000644000175000017500000000273211651544323026706 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_ETS_PROJECT_VIEW_ITEMS_CONTOLLER_H #define _U2_ETS_PROJECT_VIEW_ITEMS_CONTOLLER_H #include #include #include #include "utils/ExternalToolSupportAction.h" namespace U2 { class ETSProjectViewItemsContoller : public QObject { Q_OBJECT public: ETSProjectViewItemsContoller(QObject* p); private slots: void sl_addToProjectViewMenu(QMenu&); void sl_runFormatDBOnSelection(); private: ExternalToolSupprotAction* formatDBOnSelectionAction; ExternalToolSupprotAction* makeBLASTDBOnSelectionAction; }; }//namespace #endif // _U2_ETS_PROJECT_VIEW_ITEMS_CONTOLLER_H ugene-1.9.8/src/plugins/external_tool_support/src/cap3/0000755000175000017500000000000011651544323021656 5ustar ilyailyaugene-1.9.8/src/plugins/external_tool_support/src/cap3/CAP3SupportTask.h0000644000175000017500000000751011651544323024740 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_CAP3_SUPPORT_TASK_H_ #define _U2_CAP3_SUPPORT_TASK_H_ #include #include #include #include #include #include #include #include "utils/ExportTasks.h" #include #include "ExternalToolRunTask.h" namespace U2 { class CAP3LogParser; class CopyDataTask; class CAP3SupportTaskSettings { public: CAP3SupportTaskSettings() { openView = true; bandExpansionSize = 20; baseQualityDiffCutoff = 20; baseQualityClipCutoff = 12; maxQScoreSum = 200; maxGapLength = 20; gapPenaltyFactor = 6; maxOverhangPercent = 20; matchScoreFactor = 2; mismatchScoreFactor = -5; overlapSimilarityScoreCutoff = 900; overlapLengthCutoff = 40; overlapPercentIdentetyCutoff = 80; clippingRange = 250; reverseReads = 1; } QStringList getArgumentsList(); QStringList inputFiles; QString outputFilePath; bool openView; int bandExpansionSize; int baseQualityDiffCutoff; int baseQualityClipCutoff; int maxQScoreSum; int maxGapLength; int gapPenaltyFactor; int maxOverhangPercent; int matchScoreFactor; int mismatchScoreFactor; int overlapLengthCutoff; int overlapPercentIdentetyCutoff; int overlapSimilarityScoreCutoff; int maxNumberOfWordMatches; int clippingRange; int reverseReads; }; class PrepareInputForCAP3Task : public Task { Q_OBJECT public: PrepareInputForCAP3Task(const QStringList& inputFiles, const QString& outputDirPath); void prepare(); void run(); bool onlyCopyInputFiles() { return onlyCopyFiles; } const QString& getPreparedPath() { return preparedPath; } private: QList copyTasks; QStringList inputUrls; QStringList filesToCopy; StreamSequenceReader seqReader; StreamShortReadWriter seqWriter; QString outputDir, preparedPath; bool onlyCopyFiles; }; class CAP3SupportTask : public Task { Q_OBJECT public: CAP3SupportTask(const CAP3SupportTaskSettings& settings); void prepare(); MAlignmentObject* getResultAlignment() { return maObject; } Task::ReportResult report(); QList onSubTaskFinished(Task* subTask); private: MAlignmentObject* maObject; QString tmpDirUrl, tmpOutputUrl; Document* newDoc; LoadDocumentTask* loadTmpDocumentTask; PrepareInputForCAP3Task* prepareDataForCAP3Task; ExternalToolRunTask* cap3Task; CopyDataTask* copyResultTask; CAP3LogParser* logParser; CAP3SupportTaskSettings settings; }; class CAP3LogParser : public ExternalToolLogParser { public: CAP3LogParser(); int getProgress(); private: int countSequencesInMSA; }; }//namespace #endif // _U2_CAP3_SUPPORT_TASK_H_ ugene-1.9.8/src/plugins/external_tool_support/src/cap3/CAP3SupportDialog.cpp0000644000175000017500000001042111651544323025563 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "CAP3SupportDialog.h" #include "CAP3SupportTask.h" #include #include namespace U2 { //////////////////////////////////////// //CAP3SupportDialog CAP3SupportDialog::CAP3SupportDialog(CAP3SupportTaskSettings& s, QWidget* parent) : QDialog(parent), settings(s) { setupUi(this); QString outputUrl; outputPathLineEdit->setText(outputUrl); connect(addButton, SIGNAL(clicked()), SLOT(sl_onAddButtonClicked())); connect(removeButton, SIGNAL(clicked()), SLOT(sl_onRemoveButtonClicked())); connect(removeAllButton, SIGNAL(clicked()), SLOT(sl_onRemoveAllButtonClicked())); connect(specifyOutputPathButton, SIGNAL(clicked()), SLOT(sl_onSpecifyOutputPathButtonClicked())); } void CAP3SupportDialog::accept() { if (seqList->count() == 0) { QMessageBox::information(this, windowTitle(), tr("List of input files is empty!") ); return; } int itemCount = seqList->count(); for (int i = 0; i < itemCount; ++i) { settings.inputFiles.append( seqList->item(i)->text() ); } if (outputPathLineEdit->text().isEmpty() ) { QMessageBox::information(this, windowTitle(), tr("Result contig file name is not set!") ); return; } settings.outputFilePath = outputPathLineEdit->text(); settings.bandExpansionSize = bandExpansionBox->value(); settings.baseQualityClipCutoff = baseQualityClipCutoffBox->value(); settings.baseQualityDiffCutoff = baseQualityDiffCutoffBox->value(); settings.maxQScoreSum = maxQScoreDiffBox->value(); settings.gapPenaltyFactor = gapPenaltyFactorBox->value(); settings.maxGapLength = maxGapLengthBox->value(); settings.matchScoreFactor = matchScoreFactorBox->value(); settings.mismatchScoreFactor = mismatchScoreFactorBox->value(); settings.overlapPercentIdentetyCutoff = overlapPercentIdentityBox->value(); settings.overlapLengthCutoff = overlapLengthCutoffBox->value(); settings.overlapSimilarityScoreCutoff = overlapSimilarityScoreCutoffBox->value(); settings.maxNumberOfWordMatches = maxNumWordMatchesBox->value(); settings.reverseReads = reverseReadsBox->isChecked(); settings.clippingRange = clippingRangeBox->value(); QDialog::accept(); } void CAP3SupportDialog::sl_onAddButtonClicked() { LastOpenDirHelper lod; QStringList fileNames = QFileDialog::getOpenFileNames(this, tr("Add sequences to assembly"), lod.dir); if (fileNames.isEmpty()) { return; } lod.url = fileNames.at(fileNames.count() - 1); foreach(const QString& f, fileNames) { seqList->addItem(f); } GUrl url( seqList->item(0)->text()); outputPathLineEdit->setText(url.dirPath() + "/" + url.baseFileName() + ".cap.ace" ); } void CAP3SupportDialog::sl_onRemoveButtonClicked() { int currentRow = seqList->currentRow(); seqList->takeItem(currentRow); } void CAP3SupportDialog::sl_onRemoveAllButtonClicked() { seqList->clear(); } void CAP3SupportDialog::sl_onSpecifyOutputPathButtonClicked() { LastOpenDirHelper lod; lod.url = QFileDialog::getSaveFileName(this, tr("Set result contig file name"), lod.dir, tr("ACE format (*.ace)")); if (!lod.url.isEmpty()) { GUrl result = lod.url; if (result.lastFileSuffix().isEmpty()) { result = QString( "%1.ace" ).arg( result.getURLString() ); } outputPathLineEdit->setText(result.getURLString()); } } }//namespace ugene-1.9.8/src/plugins/external_tool_support/src/cap3/CAP3Worker.h0000644000175000017500000000360211651544323023710 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_CAP3_WORKER_H_ #define _U2_CAP3_WORKER_H_ #include #include #include "CAP3SupportTask.h" namespace U2 { namespace LocalWorkflow { class CAP3Prompter : public PrompterBase { Q_OBJECT public: CAP3Prompter(Actor* p = 0); protected: QString composeRichDoc(); }; class CAP3Worker : public BaseWorker { Q_OBJECT public: CAP3Worker(Actor* a); virtual void init(); virtual bool isReady(); virtual Task* tick(); virtual bool isDone(); virtual void cleanup(); private slots: void sl_taskFinished(); protected: CommunicationChannel *input, *output; QString resultName,transId; CAP3SupportTaskSettings cfg; }; class CAP3WorkerFactory : public DomainFactory { public: static const QString ACTOR_ID; static void init(); CAP3WorkerFactory() : DomainFactory(ACTOR_ID) {} virtual Worker* createWorker(Actor* a) {return new CAP3Worker(a);} }; } // Workflow namespace } // U2 namespace #endif // _U2_CAP3_WORKER_H_ ugene-1.9.8/src/plugins/external_tool_support/src/cap3/CAP3Support.cpp0000644000175000017500000001015111651544323024443 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "CAP3Support.h" #include "CAP3SupportDialog.h" #include "CAP3SupportTask.h" #include "ExternalToolSupportSettingsController.h" #include "ExternalToolSupportSettings.h" #include #include #include #include #include #include #include #include #include #include #include #include #include namespace U2 { CAP3Support::CAP3Support(const QString& name, const QString& path) : ExternalTool(name, path) { if (AppContext::getMainWindow()) { viewCtx = NULL; //new CAP3SupportContext(this); icon = QIcon(":external_tool_support/images/cmdline.png"); grayIcon = QIcon(":external_tool_support/images/cmdline_gray.png"); warnIcon = QIcon(":external_tool_support/images/cmdline_warn.png"); } #ifdef Q_OS_WIN executableFileName="cap3.exe"; #else #ifdef Q_OS_LINUX executableFileName="cap3"; #endif #endif validMessage="cap3 File_of_reads [options]"; description=tr("CAP3 is a contig assembly program. \
It allows to assembly long DNA reads (up to 1000 bp). \
Binaries can be downloaded from http://seq.cs.iastate.edu/cap3.html"); description+=tr("

Huang, X. and Madan, A. (1999)"); description+=tr("
CAP3: A DNA Sequence Assembly Program,"); description+=tr("
Genome Research, 9: 868-877."); versionRegExp=QRegExp("VersionDate: (\\d+\\/\\d+\\/\\d+)"); toolKitName="CAP3"; } void CAP3Support::sl_runWithExtFileSpecify(){ //Check that CAP3 and temporary directory path defined if (path.isEmpty()){ QMessageBox msgBox; msgBox.setWindowTitle(name); msgBox.setText(tr("Path for %1 tool not selected.").arg(name)); msgBox.setInformativeText(tr("Do you want to select it now?")); msgBox.setStandardButtons(QMessageBox::Yes | QMessageBox::No); msgBox.setDefaultButton(QMessageBox::Yes); int ret = msgBox.exec(); switch (ret) { case QMessageBox::Yes: AppContext::getAppSettingsGUI()->showSettingsDialog(ExternalToolSupportSettingsPageId); break; case QMessageBox::No: return; break; default: assert(NULL); break; } } if (path.isEmpty()){ return; } ExternalToolSupportSettings::checkTemporaryDir(); if (AppContext::getAppSettings()->getUserAppsSettings()->getTemporaryDirPath().isEmpty()){ return; } //Call select input file and setup settings dialog CAP3SupportTaskSettings settings; CAP3SupportDialog cap3Dialog(settings, QApplication::activeWindow()); if(cap3Dialog.exec() != QDialog::Accepted){ return; } assert(!settings.inputFiles.isEmpty()); CAP3SupportTask* task = new CAP3SupportTask(settings); AppContext::getTaskScheduler()->registerTopLevelTask(task); } }//namespace ugene-1.9.8/src/plugins/external_tool_support/src/cap3/CAP3Support.h0000644000175000017500000000260711651544323024117 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_CAP3_SUPPORT_H_ #define _U2_CAP3_SUPPORT_H_ #include #include #include "utils/ExternalToolSupportAction.h" #define CAP3_TOOL_NAME "CAP3" namespace U2 { class CAP3Support : public ExternalTool { Q_OBJECT public: CAP3Support(const QString& name, const QString& path = ""); GObjectViewWindowContext* getViewContext(){ return viewCtx; } public slots: void sl_runWithExtFileSpecify(); private: GObjectViewWindowContext* viewCtx; }; }//namespace #endif // _U2_CAP3_SUPPORT_H_ ugene-1.9.8/src/plugins/external_tool_support/src/cap3/CAP3SupportDialog.h0000644000175000017500000000276611651544323025245 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_CAP3_SUPPORT_DIALOG_H_ #define _U2_CAP3_SUPPORT_DIALOG_H_ #include #include #include namespace U2 { class CAP3SupportTaskSettings; class CAP3SupportDialog : public QDialog, public Ui_CAP3SupportDialog { Q_OBJECT public: CAP3SupportDialog(CAP3SupportTaskSettings& settings, QWidget* parent); void accept(); private slots: void sl_onAddButtonClicked(); void sl_onRemoveButtonClicked(); void sl_onRemoveAllButtonClicked(); void sl_onSpecifyOutputPathButtonClicked(); private: CAP3SupportTaskSettings& settings; }; }//namespace #endif // _U2_CAP3_SUPPORT_DIALOG_H_ ugene-1.9.8/src/plugins/external_tool_support/src/cap3/CAP3SupportTask.cpp0000644000175000017500000002410611651544323025273 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "CAP3SupportTask.h" #include "CAP3Support.h" #include #include #include #include #include #include #include #include #include #include #include namespace U2 { ////////////////////////////////////////////////////////////////////////// ////CAP3SupportTask CAP3SupportTask::CAP3SupportTask(const CAP3SupportTaskSettings& _settings) : Task("CAP3SupportTask", TaskFlags_NR_FOSCOE), settings(_settings) { GCOUNTER( cvar, tvar, "CAP3SupportTask" ); setMaxParallelSubtasks(1); newDoc = NULL; logParser = NULL; loadTmpDocumentTask = NULL; copyResultTask = NULL; cap3Task = NULL; prepareDataForCAP3Task = NULL; maObject = NULL; } void CAP3SupportTask::prepare(){ //Add new subdir for temporary files QString errMsg; tmpDirUrl = ExternalToolSupportUtils::createTmpDir("CAP3", getTaskId(), errMsg); if (tmpDirUrl.isEmpty()) { setError(errMsg); return; } prepareDataForCAP3Task = new PrepareInputForCAP3Task(settings.inputFiles, tmpDirUrl); addSubTask(prepareDataForCAP3Task); } #define CAP3_EXT ".cap.ace" QList CAP3SupportTask::onSubTaskFinished(Task* subTask) { QList res; propagateSubtaskError(); if(hasError() || isCanceled()) { return res; } if (subTask == prepareDataForCAP3Task) { assert(!prepareDataForCAP3Task->getPreparedPath().isEmpty()); GUrl inputUrl = prepareDataForCAP3Task->getPreparedPath(); if (prepareDataForCAP3Task->onlyCopyInputFiles()) { tmpOutputUrl = inputUrl.getURLString()+ CAP3_EXT; } else { tmpOutputUrl = inputUrl.dirPath() + "/" + inputUrl.baseFileName() + CAP3_EXT; } QStringList arguments = settings.getArgumentsList(); arguments.prepend( inputUrl.getURLString() ); logParser = new CAP3LogParser(); cap3Task = new ExternalToolRunTask(CAP3_TOOL_NAME, arguments, logParser); cap3Task->setSubtaskProgressWeight(95); res.append(cap3Task); } else if (subTask == cap3Task){ if(!QFile::exists(tmpOutputUrl)){ if(AppContext::getExternalToolRegistry()->getByName(CAP3_TOOL_NAME)->isValid()){ stateInfo.setError(tr("Output file not found")); }else{ stateInfo.setError(tr("Output file not found. May be %1 tool path '%2' not valid?") .arg(AppContext::getExternalToolRegistry()->getByName(CAP3_TOOL_NAME)->getName()) .arg(AppContext::getExternalToolRegistry()->getByName(CAP3_TOOL_NAME)->getPath())); } return res; } IOAdapterFactory* iof = AppContext::getIOAdapterRegistry()->getIOAdapterFactoryById(BaseIOAdapters::LOCAL_FILE); copyResultTask = new CopyDataTask(iof, tmpOutputUrl, iof, settings.outputFilePath ); res.append(copyResultTask); } else if (subTask == copyResultTask) { if( !QFile::exists(settings.outputFilePath)) { stateInfo.setError(tr("Output file not found: copy from tmp dir failed.")); return res; } loadTmpDocumentTask= new LoadDocumentTask(BaseDocumentFormats::ACE, settings.outputFilePath, AppContext::getIOAdapterRegistry()->getIOAdapterFactoryById(BaseIOAdapters::LOCAL_FILE)); loadTmpDocumentTask->setSubtaskProgressWeight(5); res.append(loadTmpDocumentTask); } else if( subTask == loadTmpDocumentTask ) { Document* doc = loadTmpDocumentTask->getDocument(); SAFE_POINT(doc != NULL, "Failed loading result document", res); if (doc->getObjects().size() == 0) { // TODO: delete new file? setError(tr("No assembly is found for provided reads")); return res; } maObject = qobject_cast( doc->getObjects().first() ); if (settings.openView) { if (AppContext::getProject() == NULL) { res.append( AppContext::getProjectLoader()->createNewProjectTask() ); } // clone doc because it was created in another thread Document* clonedDoc = doc->clone(); res.append(new AddDocumentAndOpenViewTask(clonedDoc)); } } return res; } Task::ReportResult CAP3SupportTask::report(){ QString errMsg; if (!ExternalToolSupportUtils::removeTmpDir(tmpDirUrl,errMsg)) { stateInfo.setError(errMsg); } return ReportResult_Finished; } ////////////////////////////////////////// ////CAP3LogParser CAP3LogParser::CAP3LogParser() { } int CAP3LogParser::getProgress() { return 0; } ////////////////////////////////////////// ////PrepareInput PrepareInputForCAP3Task::PrepareInputForCAP3Task( const QStringList& inputFiles, const QString& outputDirPath) :Task("PrepareInputForCAP3Task", TaskFlags_FOSCOE), inputUrls(inputFiles), outputDir(outputDirPath), onlyCopyFiles(false) { } void PrepareInputForCAP3Task::prepare() { if (inputUrls.size() == 1) { const QString& inputFileUrl = inputUrls.first(); QList results = DocumentUtils::detectFormat(inputFileUrl); if (!results.isEmpty()) { DocumentFormat* format = results.first().format; if (format->getFormatId() == BaseDocumentFormats::PLAIN_FASTA) { onlyCopyFiles = true; } } } if (onlyCopyFiles) { // short path: copy single FASTA file along with quality and constraints to target dir QString inputFileUrl = inputUrls.first(); filesToCopy.append(inputFileUrl); QString inputFileUrlBase = GUrl(inputFileUrl).baseFileName(); QString inputFileDir = GUrl(inputFileUrl).dirPath(); QString qualFileUrl = inputFileDir + "/" + inputFileUrlBase + ".qual"; if (QFile::exists(qualFileUrl)) { filesToCopy.append(qualFileUrl); } QString constraintsFileUrl = inputFileDir+ "/" + inputFileUrlBase + ".con"; if (QFile::exists(constraintsFileUrl)) { filesToCopy.append(qualFileUrl); } foreach (const QString& fileName, filesToCopy) { IOAdapterFactory* iof = AppContext::getIOAdapterRegistry()->getIOAdapterFactoryById(BaseIOAdapters::LOCAL_FILE); CopyDataTask* copyTask = new CopyDataTask(iof, fileName, iof, outputDir + "/" + GUrl(fileName).fileName()); addSubTask(copyTask); } preparedPath = outputDir + "/" + GUrl(inputFileUrl).fileName(); } else { // long path: load each file, save sequences and qualities to output dir QList inputGUrls; foreach( const QString& url, inputUrls) { inputGUrls.append(url); } if (!seqReader.init(inputGUrls)) { setError(seqReader.getErrorMessage()); return; } QString outPath = outputDir + "/" + QString("%1_misc").arg(inputGUrls.first().baseFileName()); if (!seqWriter.init(outPath)) { setError(tr("Failed to initialize sequence writer.")); return; } } } void PrepareInputForCAP3Task::run() { if (hasError() || onlyCopyFiles) { return; } while (seqReader.hasNext()) { if (isCanceled()) { return; } DNASequence* seq = seqReader.getNextSequenceObject(); if (seq == NULL) { setError(seqReader.getErrorMessage()); return; } // avoid names dublicating QByteArray seqName = seq->getName().toAscii(); seqName.replace(' ','_'); seq->setName(seqName); bool ok = seqWriter.writeNextSequence(*seq); if (!ok) { setError(tr("Failed to write sequence %1").arg(seq->getName())); return; } } preparedPath = seqWriter.getOutputPath().getURLString(); seqWriter.close(); } QStringList CAP3SupportTaskSettings::getArgumentsList() { QStringList res; res += "-a"; res += QString("%1").arg(bandExpansionSize); res += "-b"; res += QString("%1").arg(baseQualityDiffCutoff); res += "-c"; res += QString("%1").arg(baseQualityClipCutoff); res += "-d"; res += QString("%1").arg(maxQScoreSum); res += "-f"; res += QString("%1").arg(maxGapLength); res += "-g"; res += QString("%1").arg(gapPenaltyFactor); res += "-m"; res += QString("%1").arg(matchScoreFactor); res += "-n"; res += QString("%1").arg(mismatchScoreFactor); res += "-o"; res += QString("%1").arg(overlapLengthCutoff); res += "-p"; res += QString("%1").arg(overlapPercentIdentetyCutoff); res += "-s"; res += QString("%1").arg(overlapSimilarityScoreCutoff); res += "-t"; res += QString("%1").arg(maxNumberOfWordMatches); res += "-y"; res += QString("%1").arg(clippingRange); return res; } }//namespace ugene-1.9.8/src/plugins/external_tool_support/src/cap3/CAP3Worker.cpp0000644000175000017500000001217411651544323024247 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "CAP3Worker.h" #include "TaskLocalStorage.h" #include "CAP3Support.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include namespace U2 { namespace LocalWorkflow { ////////////////////////////////////////////////////////////////////////// //CAP3WorkerFactory ////////////////////////////////////////////////////////////////////////// const QString CAP3WorkerFactory::ACTOR_ID("CAP3"); const QString INPUT_FILE_PATH("input-path"); void CAP3WorkerFactory::init() { QList p; QList a; Descriptor oud(BasePorts::OUT_MSA_PORT_ID(), CAP3Worker::tr("CAP3 result multiple sequence alignment"), CAP3Worker::tr("The result of the CAP3 contig assembly.")); QMap outM; outM[BaseSlots::MULTIPLE_ALIGNMENT_SLOT()] = BaseTypes::MULTIPLE_ALIGNMENT_TYPE(); p << new PortDescriptor(oud, DataTypePtr(new MapDataType("ace.out.msa", outM)), false /*input*/, true /*multi*/); Descriptor input(INPUT_FILE_PATH, CAP3Worker::tr("Input"), CAP3Worker::tr("Path to input long DNA reads.")); a << new Attribute(input, BaseTypes::STRING_TYPE(), true, QVariant("Default")); QString cap3Description = AppContext::getExternalToolRegistry()->getByName(CAP3_TOOL_NAME)->getDescription(); Descriptor desc(ACTOR_ID, CAP3Worker::tr("Align with CAP3"), cap3Description); ActorPrototype* proto = new IntegralBusActorPrototype(desc, p, a); QMap delegates; delegates[INPUT_FILE_PATH] = new URLDelegate("", "inputPath", false); proto->setEditor(new DelegateEditor(delegates)); proto->setPrompter(new CAP3Prompter()); proto->setIconPath(":external_tool_support/images/clustalx.png"); WorkflowEnv::getProtoRegistry()->registerProto(BaseActorCategories::CATEGORY_ASSEMBLY(), proto); DomainFactory* localDomain = WorkflowEnv::getDomainRegistry()->getById(LocalDomainFactory::ID); localDomain->registerEntry(new CAP3WorkerFactory()); } ////////////////////////////////////////////////////////////////////////// // CAP3Prompter ////////////////////////////////////////////////////////////////////////// CAP3Prompter::CAP3Prompter(Actor* p) : PrompterBase(p) { } QString CAP3Prompter::composeRichDoc() { QString inputPath = target->getParameter(INPUT_FILE_PATH)->getAttributeValue(); QString doc = tr("Aligns long DNA reads from %1 with \"CAP3\".") .arg(inputPath); return doc; } ////////////////////////////////////////////////////////////////////////// // CAP3Worker ////////////////////////////////////////////////////////////////////////// CAP3Worker::CAP3Worker(Actor* a) : BaseWorker(a), input(NULL), output(NULL) { } void CAP3Worker::init() { input = ports.value(BasePorts::IN_MSA_PORT_ID()); output = ports.value(BasePorts::OUT_MSA_PORT_ID()); } bool CAP3Worker::isReady() { return (input && input->hasMessage()); } Task* CAP3Worker::tick() { Message inputMessage = getMessageAndSetupScriptValues(input); cfg.inputFiles.append( actor->getParameter(INPUT_FILE_PATH)->getAttributeValue() ); Task* t = new CAP3SupportTask(cfg); connect(t, SIGNAL(si_stateChanged()), SLOT(sl_taskFinished())); return t; } void CAP3Worker::sl_taskFinished() { CAP3SupportTask* t = qobject_cast(sender()); if (t->getState() != Task::State_Finished) return; QVariant v = qVariantFromValue(t->getResultAlignment()->getMAlignment()); output->put(Message(BaseTypes::MULTIPLE_ALIGNMENT_TYPE(), v)); if (input->isEnded()) { output->setEnded(); } algoLog.info(tr("Aligned %1 with CAP3").arg(t->getResultAlignment()->getMAlignment().getName())); } bool CAP3Worker::isDone() { return !input || input->isEnded(); } void CAP3Worker::cleanup() { } } //namespace LocalWorkflow } //namespace U2 ugene-1.9.8/src/plugins/external_tool_support/src/ETSProjectViewItemsContoller.cpp0000644000175000017500000001306011651544323027235 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "ETSProjectViewItemsContoller.h" #include "ExternalToolSupportSettingsController.h" #include "ExternalToolSupportSettings.h" #include #include #include #include #include #include #include #include #include #include #include #include #include "blast/FormatDBSupport.h" #include "blast/FormatDBSupportRunDialog.h" #include "blast/FormatDBSupportTask.h" namespace U2 { ETSProjectViewItemsContoller::ETSProjectViewItemsContoller(QObject* p) : QObject(p) { formatDBOnSelectionAction=new ExternalToolSupprotAction(tr("FormatDB..."), this, QStringList(FORMATDB_TOOL_NAME)); makeBLASTDBOnSelectionAction=new ExternalToolSupprotAction(tr("BLAST+ make DB..."), this, QStringList(MAKEBLASTDB_TOOL_NAME)); connect(formatDBOnSelectionAction,SIGNAL(triggered()), SLOT(sl_runFormatDBOnSelection())); connect(makeBLASTDBOnSelectionAction,SIGNAL(triggered()), SLOT(sl_runFormatDBOnSelection())); ProjectView* pv = AppContext::getProjectView(); assert(pv!=NULL); connect(pv, SIGNAL(si_onDocTreePopupMenuRequested(QMenu&)), SLOT(sl_addToProjectViewMenu(QMenu&))); } void ETSProjectViewItemsContoller::sl_addToProjectViewMenu(QMenu& m) { ProjectView* pv = AppContext::getProjectView(); assert(pv!=NULL); MultiGSelection ms; //ms.addSelection(pv->getGObjectSelection()); ms.addSelection(pv->getDocumentSelection()); QList set = SelectionUtils::getSelectedDocs(ms); bool hasFastaDocs=false; foreach(Document* doc,set){ if(doc->getDocumentFormatId() == BaseDocumentFormats::PLAIN_FASTA){ hasFastaDocs=true; break; } } if (hasFastaDocs) { QMenu* subMenu = m.addMenu(tr("BLAST")); subMenu->setIcon(QIcon(":external_tool_support/images/ncbi.png")); subMenu->addAction(formatDBOnSelectionAction); subMenu->addAction(makeBLASTDBOnSelectionAction); } } void ETSProjectViewItemsContoller::sl_runFormatDBOnSelection(){ ExternalToolSupprotAction* s = qobject_cast(sender()); assert(s != NULL); assert((s->getToolNames().contains(FORMATDB_TOOL_NAME))||(s->getToolNames().contains(MAKEBLASTDB_TOOL_NAME))); //Check that formatDB and tempory directory path defined if (AppContext::getExternalToolRegistry()->getByName(s->getToolNames().at(0))->getPath().isEmpty()){ QMessageBox msgBox; if(s->getToolNames().at(0) == FORMATDB_TOOL_NAME){ msgBox.setWindowTitle("BLAST "+s->getToolNames().at(0)); msgBox.setText(tr("Path for BLAST %1 tool not selected.").arg(s->getToolNames().at(0))); }else{ msgBox.setWindowTitle("BLAST+ "+s->getToolNames().at(0)); msgBox.setText(tr("Path for BLAST+ %1 tool not selected.").arg(s->getToolNames().at(0))); } msgBox.setInformativeText(tr("Do you want to select it now?")); msgBox.setStandardButtons(QMessageBox::Yes | QMessageBox::No); msgBox.setDefaultButton(QMessageBox::Yes); int ret = msgBox.exec(); switch (ret) { case QMessageBox::Yes: AppContext::getAppSettingsGUI()->showSettingsDialog(ExternalToolSupportSettingsPageId); break; case QMessageBox::No: return; break; default: assert(NULL); break; } } if (AppContext::getExternalToolRegistry()->getByName(s->getToolNames().at(0))->getPath().isEmpty()){ return; } ExternalToolSupportSettings::checkTemporaryDir(); if (AppContext::getAppSettings()->getUserAppsSettings()->getTemporaryDirPath().isEmpty()){ return; } ProjectView* pv = AppContext::getProjectView(); assert(pv!=NULL); MultiGSelection ms; ms.addSelection(pv->getGObjectSelection()); ms.addSelection(pv->getDocumentSelection());//??? FormatDBSupportTaskSettings settings; foreach(Document* doc,pv->getDocumentSelection()->getSelectedDocuments()){ if(doc->getDocumentFormatId() == BaseDocumentFormats::PLAIN_FASTA){ settings.inputFilesPath.append(doc->getURLString()); } } FormatDBSupportRunDialog formatDBRunDialog(settings, AppContext::getMainWindow()->getQMainWindow()); if(formatDBRunDialog.exec() != QDialog::Accepted){ return; } FormatDBSupportTask* formatDBSupportTask=new FormatDBSupportTask(s->getToolNames().at(0), settings); AppContext::getTaskScheduler()->registerTopLevelTask(formatDBSupportTask); } }//namespace ugene-1.9.8/src/plugins/external_tool_support/src/TaskLocalStorage.h0000644000175000017500000000266311651544323024412 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _ETS_TASK_LOCAL_STORAGE_ #define _ETS_TASK_LOCAL_STORAGE_ #include class ETSContext; namespace U2 { class ETSContextTLSRef { public: ETSContextTLSRef(ETSContext* _ctx, int _workerID) : ctx(_ctx), workerID(_workerID){} ETSContext* ctx; int workerID; }; class TaskLocalData { public: static ETSContext* current(); static unsigned currentWorkerID(); static void bindToETSTLSContext(ETSContext *ctx, int workerID = 0); static void detachETSTLSContext(); private: static QThreadStorage tls; }; } //namespace #endif ugene-1.9.8/src/plugins/external_tool_support/src/tcoffee/0000755000175000017500000000000011651544323022443 5ustar ilyailyaugene-1.9.8/src/plugins/external_tool_support/src/tcoffee/TCoffeeSupportRunDialog.cpp0000644000175000017500000000767411651544323027702 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "TCoffeeSupportRunDialog.h" #include #include #include namespace U2 { //////////////////////////////////////// //TCoffeeSupportRunDialog TCoffeeSupportRunDialog::TCoffeeSupportRunDialog(TCoffeeSupportTaskSettings& _settings, QWidget* _parent) : QDialog(_parent), settings(_settings) { setupUi(this); connect(this->cancelButton,SIGNAL(clicked()),this,SLOT(reject())); connect(this->alignButton,SIGNAL(clicked()),this,SLOT(sl_align())); } void TCoffeeSupportRunDialog::sl_align(){ if(gapOpenCheckBox->isChecked()) { settings.gapOpenPenalty = gapOpenSpinBox->value(); } if(gapExtCheckBox->isChecked()) { settings.gapExtenstionPenalty = gapExtSpinBox->value(); } if(maxNumberIterRefinementCheckBox->isChecked()){ settings.numIterations = maxNumberIterRefinementSpinBox->value(); } accept(); } //////////////////////////////////////// //TCoffeeWithExtFileSpecifySupportRunDialog TCoffeeWithExtFileSpecifySupportRunDialog::TCoffeeWithExtFileSpecifySupportRunDialog(TCoffeeSupportTaskSettings& _settings, QWidget* _parent) : QDialog(_parent), settings(_settings) { setupUi(this); QWidget * widget = new QWidget(_parent); inputFileLineEdit= new FileLineEdit(DialogUtils::prepareDocumentsFileFilterByObjType(GObjectTypes::MULTIPLE_ALIGNMENT, true), "", false, widget); inputFileLineEdit->setText(""); QToolButton * selectToolPathButton = new QToolButton(widget); selectToolPathButton->setVisible(true); selectToolPathButton->setText("..."); connect(selectToolPathButton, SIGNAL(clicked()), inputFileLineEdit, SLOT(sl_onBrowse())); connect(inputFileLineEdit,SIGNAL(textChanged(QString)),this, SLOT(sl_inputFileLineEditChanged(QString))); QHBoxLayout* layout = new QHBoxLayout(widget); layout->addWidget(inputFileLineEdit); layout->addWidget(selectToolPathButton); QGroupBox* inputFileGroupBox=new QGroupBox(tr("Select input file"),widget); inputFileGroupBox->setLayout(layout); QBoxLayout* parentLayout = qobject_cast(this->layout()); assert(parentLayout); parentLayout->insertWidget(0, inputFileGroupBox); alignButton->setEnabled(false); connect(this->cancelButton, SIGNAL(clicked()), this, SLOT(reject())); connect(this->alignButton, SIGNAL(clicked()), this, SLOT(sl_align())); } void TCoffeeWithExtFileSpecifySupportRunDialog::sl_inputFileLineEditChanged(const QString& str){ alignButton->setEnabled(!str.isEmpty()); } void TCoffeeWithExtFileSpecifySupportRunDialog::sl_align(){ if(gapOpenCheckBox->isChecked()) { settings.gapOpenPenalty = gapOpenSpinBox->value(); } if(gapExtCheckBox->isChecked()) { settings.gapExtenstionPenalty = gapExtSpinBox->value(); } if(maxNumberIterRefinementCheckBox->isChecked()){ settings.numIterations = maxNumberIterRefinementSpinBox->value(); } if(!inputFileLineEdit->text().isEmpty()){ settings.inputFilePath=inputFileLineEdit->text(); }else{ assert(NULL); reject(); } accept(); } }//namespace ugene-1.9.8/src/plugins/external_tool_support/src/tcoffee/TCoffeeWorker.cpp0000644000175000017500000002005311651544323025654 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "TCoffeeWorker.h" #include "TaskLocalStorage.h" #include "TCoffeeSupport.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include namespace U2 { namespace LocalWorkflow { /**************************** * TCoffeeWorkerFactory ****************************/ const QString TCoffeeWorkerFactory::ACTOR_ID("tcoffee"); const QString GAP_OPEN_PENALTY("gap-open-penalty"); const QString GAP_EXT_PENALTY("gap-ext-penalty"); const QString NUM_ITER("iterations-max-num"); const QString EXT_TOOL_PATH("path"); const QString TMP_DIR_PATH("temp-dir"); void TCoffeeWorkerFactory::init() { QList p; QList a; Descriptor ind(BasePorts::IN_MSA_PORT_ID(), TCoffeeWorker::tr("Input MSA"), TCoffeeWorker::tr("Multiple sequence alignment to be processed.")); Descriptor oud(BasePorts::OUT_MSA_PORT_ID(), TCoffeeWorker::tr("Multiple sequence alignment"), TCoffeeWorker::tr("Result of alignment.")); QMap inM; inM[BaseSlots::MULTIPLE_ALIGNMENT_SLOT()] = BaseTypes::MULTIPLE_ALIGNMENT_TYPE(); p << new PortDescriptor(ind, DataTypePtr(new MapDataType("tcoffee.in.msa", inM)), true /*input*/); QMap outM; outM[BaseSlots::MULTIPLE_ALIGNMENT_SLOT()] = BaseTypes::MULTIPLE_ALIGNMENT_TYPE(); p << new PortDescriptor(oud, DataTypePtr(new MapDataType("tcoffee.out.msa", outM)), false /*input*/, true /*multi*/); Descriptor gop(GAP_OPEN_PENALTY, TCoffeeWorker::tr("Gap Open Penalty"), TCoffeeWorker::tr("Gap Open Penalty. Must be negative, best matches get a score of 1000.")); Descriptor gep(GAP_EXT_PENALTY, TCoffeeWorker::tr("Gap Extension Penalty"), TCoffeeWorker::tr("Gap Extension Penalty. Positive values give rewards to gaps and prevent the alignment of unrelated segments.")); Descriptor tgp(NUM_ITER, TCoffeeWorker::tr("Max Iteration"), TCoffeeWorker::tr("Number of iteration on the progressive alignment
" "0 - no iteration, -1 - Nseq iterations")); Descriptor etp(EXT_TOOL_PATH, TCoffeeWorker::tr("Tool Path"), TCoffeeWorker::tr("External tool path")); Descriptor tdp(TMP_DIR_PATH, TCoffeeWorker::tr("Temporary directory"), TCoffeeWorker::tr("Directory for temporary files")); a << new Attribute(gop, BaseTypes::NUM_TYPE(), false, QVariant(-50)); a << new Attribute(gep, BaseTypes::NUM_TYPE(), false, QVariant(0)); a << new Attribute(tgp, BaseTypes::NUM_TYPE(), false, QVariant(0)); a << new Attribute(etp, BaseTypes::STRING_TYPE(), true, QVariant("default")); a << new Attribute(tdp, BaseTypes::STRING_TYPE(), true, QVariant("default")); Descriptor desc(ACTOR_ID, TCoffeeWorker::tr("Align with T-Coffee"), TCoffeeWorker::tr("T-Coffee is a multiple sequence alignment package. ")); ActorPrototype* proto = new IntegralBusActorPrototype(desc, p, a); QMap delegates; { QVariantMap m; m["minimum"] = int(-10000); m["maximum"] = int(0); m["singleStep"] = int(50); delegates[GAP_OPEN_PENALTY] = new SpinBoxDelegate(m); } { QVariantMap m; m["minimum"] = int(-5000); m["maximum"] = int(5000); m["singleStep"] = int(10); delegates[GAP_EXT_PENALTY] = new SpinBoxDelegate(m); } { QVariantMap m; m["minimum"] = int(-1); m["maximum"] = int(100); delegates[NUM_ITER] = new SpinBoxDelegate(m); } delegates[EXT_TOOL_PATH] = new URLDelegate("", "executable", false); delegates[TMP_DIR_PATH] = new URLDelegate("", "TmpDir", false, true); proto->setEditor(new DelegateEditor(delegates)); proto->setPrompter(new TCoffeePrompter()); proto->setIconPath(":external_tool_support/images/tcoffee.png"); WorkflowEnv::getProtoRegistry()->registerProto(BaseActorCategories::CATEGORY_ALIGNMENT(), proto); DomainFactory* localDomain = WorkflowEnv::getDomainRegistry()->getById(LocalDomainFactory::ID); localDomain->registerEntry(new TCoffeeWorkerFactory()); } /**************************** * TCoffeePrompter ****************************/ TCoffeePrompter::TCoffeePrompter(Actor* p) : PrompterBase(p) { } QString TCoffeePrompter::composeRichDoc() { IntegralBusPort* input = qobject_cast(target->getPort(BasePorts::IN_MSA_PORT_ID())); Actor* producer = input->getProducer(BasePorts::IN_MSA_PORT_ID()); QString producerName = producer ? tr(" from %1").arg(producer->getLabel()) : ""; QString doc = tr("For each MSA%1, build the alignment using \"T-Coffee\" and send it to output.") .arg(producerName); return doc; } /**************************** * TCoffeeWorker ****************************/ TCoffeeWorker::TCoffeeWorker(Actor* a) : BaseWorker(a), input(NULL), output(NULL) { } void TCoffeeWorker::init() { input = ports.value(BasePorts::IN_MSA_PORT_ID()); output = ports.value(BasePorts::OUT_MSA_PORT_ID()); } bool TCoffeeWorker::isReady() { return (input && input->hasMessage()); } Task* TCoffeeWorker::tick() { Message inputMessage = getMessageAndSetupScriptValues(input); cfg.gapOpenPenalty=actor->getParameter(GAP_OPEN_PENALTY)->getAttributeValue(); cfg.gapExtenstionPenalty=actor->getParameter(GAP_EXT_PENALTY)->getAttributeValue(); cfg.numIterations=actor->getParameter(NUM_ITER)->getAttributeValue(); QString path=actor->getParameter(EXT_TOOL_PATH)->getAttributeValue(); if(QString::compare(path, "default", Qt::CaseInsensitive) != 0){ AppContext::getExternalToolRegistry()->getByName(TCOFFEE_TOOL_NAME)->setPath(path); } path=actor->getParameter(TMP_DIR_PATH)->getAttributeValue(); if(QString::compare(path, "default", Qt::CaseInsensitive) != 0){ AppContext::getAppSettings()->getUserAppsSettings()->setTemporaryDirPath(path); } MAlignment msa = inputMessage.getData().toMap().value(BaseSlots::MULTIPLE_ALIGNMENT_SLOT().getId()).value(); if( msa.isEmpty() ) { return new FailTask(tr("Empty msa supplied to tcoffee")); } Task* t = new TCoffeeSupportTask(new MAlignmentObject(msa), cfg); connect(t, SIGNAL(si_stateChanged()), SLOT(sl_taskFinished())); return t; } void TCoffeeWorker::sl_taskFinished() { TCoffeeSupportTask* t = qobject_cast(sender()); if (t->getState() != Task::State_Finished) return; QVariant v = qVariantFromValue(t->resultMA); output->put(Message(BaseTypes::MULTIPLE_ALIGNMENT_TYPE(), v)); if (input->isEnded()) { output->setEnded(); } algoLog.info(tr("Aligned %1 with T-Coffee").arg(t->resultMA.getName())); } bool TCoffeeWorker::isDone() { return !input || input->isEnded(); } void TCoffeeWorker::cleanup() { } } //namespace LocalWorkflow } //namespace U2 ugene-1.9.8/src/plugins/external_tool_support/src/tcoffee/TCoffeeSupport.cpp0000644000175000017500000001646511651544323026073 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "TCoffeeSupport.h" #include "TCoffeeSupportRunDialog.h" #include "TCoffeeSupportTask.h" #include "ExternalToolSupportSettingsController.h" #include "ExternalToolSupportSettings.h" #include #include #include #include #include #include #include #include #include #include #include #include namespace U2 { TCoffeeSupport::TCoffeeSupport(const QString& name, const QString& path) : ExternalTool(name, path) { if (AppContext::getMainWindow()) { viewCtx = new TCoffeeSupportContext(this); icon = QIcon(":external_tool_support/images/tcoffee.png"); grayIcon = QIcon(":external_tool_support/images/tcoffee_gray.png"); warnIcon = QIcon(":external_tool_support/images/tcoffee_warn.png"); } #ifdef Q_OS_WIN executableFileName="t_coffee.exe";//need check on windows #else #ifdef Q_OS_LINUX executableFileName="t_coffee"; #endif #endif validationArguments<<"-h"; validMessage="PROGRAM: T-COFFEE"; description=tr("T-Coffee is a multiple sequence alignment package."); versionRegExp=QRegExp("PROGRAM: T-COFFEE \\(Version_(\\d+\\.\\d+_\\d+)"); toolKitName="T-Coffee"; } void TCoffeeSupport::sl_runWithExtFileSpecify(){ //Check that T-Coffee and tempory directory path defined if (path.isEmpty()){ QMessageBox msgBox; msgBox.setWindowTitle(name); msgBox.setText(tr("Path for %1 tool not selected.").arg(name)); msgBox.setInformativeText(tr("Do you want to select it now?")); msgBox.setStandardButtons(QMessageBox::Yes | QMessageBox::No); msgBox.setDefaultButton(QMessageBox::Yes); int ret = msgBox.exec(); switch (ret) { case QMessageBox::Yes: AppContext::getAppSettingsGUI()->showSettingsDialog(ExternalToolSupportSettingsPageId); break; case QMessageBox::No: return; break; default: assert(NULL); break; } } if (path.isEmpty()){ return; } ExternalToolSupportSettings::checkTemporaryDir(); if (AppContext::getAppSettings()->getUserAppsSettings()->getTemporaryDirPath().isEmpty()){ return; } //Call select input file and setup settings dialog TCoffeeSupportTaskSettings settings; TCoffeeWithExtFileSpecifySupportRunDialog tCoffeeRunDialog(settings, AppContext::getMainWindow()->getQMainWindow()); if(tCoffeeRunDialog.exec() != QDialog::Accepted){ return; } assert(!settings.inputFilePath.isEmpty()); // TCoffeeWithExtFileSpecifySupportTask* tCoffeeSupportTask=new TCoffeeWithExtFileSpecifySupportTask(settings); AppContext::getTaskScheduler()->registerTopLevelTask(tCoffeeSupportTask); } //////////////////////////////////////// //TCoffeeSupportAction ??? MSAEditor* TCoffeeSupportAction::getMSAEditor() const { MSAEditor* e = qobject_cast(getObjectView()); assert(e!=NULL); return e; } void TCoffeeSupportAction::sl_lockedStateChanged() { StateLockableItem* item = qobject_cast(sender()); assert(item!=NULL); setEnabled(!item->isStateLocked()); } //////////////////////////////////////// //TCoffeeSupportContext TCoffeeSupportContext::TCoffeeSupportContext(QObject* p) : GObjectViewWindowContext(p, MSAEditorFactory::ID) { } void TCoffeeSupportContext::initViewContext(GObjectView* view) { MSAEditor* msaed = qobject_cast(view); assert(msaed!=NULL); if (msaed->getMSAObject() == NULL) { return; } bool objLocked = msaed->getMSAObject()->isStateLocked(); TCoffeeSupportAction* alignAction = new TCoffeeSupportAction(this, view, tr("Align with T-Coffee..."), 2000); addViewAction(alignAction); alignAction->setEnabled(!objLocked); connect(msaed->getMSAObject(), SIGNAL(si_lockedStateChanged()), alignAction, SLOT(sl_lockedStateChanged())); connect(alignAction, SIGNAL(triggered()), SLOT(sl_align_with_TCoffee())); } void TCoffeeSupportContext::buildMenu(GObjectView* view, QMenu* m) { QList actions = getViewActions(view); QMenu* alignMenu = GUIUtils::findSubMenu(m, MSAE_MENU_ALIGN); assert(alignMenu!=NULL); foreach(GObjectViewAction* a, actions) { a->addToMenuWithOrder(alignMenu); } } void TCoffeeSupportContext::sl_align_with_TCoffee() { //Check that T-Coffee and tempory directory path defined if (AppContext::getExternalToolRegistry()->getByName(TCOFFEE_TOOL_NAME)->getPath().isEmpty()){ QMessageBox msgBox; msgBox.setWindowTitle(TCOFFEE_TOOL_NAME); msgBox.setText(tr("Path for %1 tool not selected.").arg(TCOFFEE_TOOL_NAME)); msgBox.setInformativeText(tr("Do you want to select it now?")); msgBox.setStandardButtons(QMessageBox::Yes | QMessageBox::No); msgBox.setDefaultButton(QMessageBox::Yes); int ret = msgBox.exec(); switch (ret) { case QMessageBox::Yes: AppContext::getAppSettingsGUI()->showSettingsDialog(ExternalToolSupportSettingsPageId); break; case QMessageBox::No: return; break; default: assert(NULL); break; } } if (AppContext::getExternalToolRegistry()->getByName(TCOFFEE_TOOL_NAME)->getPath().isEmpty()){ return; } ExternalToolSupportSettings::checkTemporaryDir(); if (AppContext::getAppSettings()->getUserAppsSettings()->getTemporaryDirPath().isEmpty()){ return; } //Call run T-Coffee align dialog TCoffeeSupportAction* action = qobject_cast(sender()); assert(action!=NULL); MSAEditor* ed = action->getMSAEditor(); MAlignmentObject* obj = ed->getMSAObject(); if (obj == NULL) return; assert(!obj->isStateLocked()); TCoffeeSupportTaskSettings settings; TCoffeeSupportRunDialog tCoffeeRunDialog(settings, AppContext::getMainWindow()->getQMainWindow()); if(tCoffeeRunDialog.exec() != QDialog::Accepted){ return; } TCoffeeSupportTask* tCoffeeSupportTask=new TCoffeeSupportTask(obj, settings); AppContext::getTaskScheduler()->registerTopLevelTask(tCoffeeSupportTask); } }//namespace ugene-1.9.8/src/plugins/external_tool_support/src/tcoffee/TCoffeeSupportRunDialog.h0000644000175000017500000000350511651544323027334 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_TCOFFEE_SUPPORT_RUN_DIALOG_H #define _U2_TCOFFEE_SUPPORT_RUN_DIALOG_H #include #include #include #include "TCoffeeSupportTask.h" namespace U2 { class TCoffeeSupportRunDialog : public QDialog, public Ui_TCoffeeSupportRunDialog { Q_OBJECT public: TCoffeeSupportRunDialog(TCoffeeSupportTaskSettings& settings, QWidget* parent); private slots: void sl_align(); private: TCoffeeSupportTaskSettings& settings; }; class TCoffeeWithExtFileSpecifySupportRunDialog : public QDialog, public Ui_TCoffeeSupportRunDialog{ Q_OBJECT public: TCoffeeWithExtFileSpecifySupportRunDialog(TCoffeeSupportTaskSettings& settings, QWidget* parent); private slots: void sl_align(); void sl_inputFileLineEditChanged(const QString& str); private: TCoffeeSupportTaskSettings& settings; FileLineEdit* inputFileLineEdit; }; }//namespace #endif // _U2_TCOFFEE_SUPPORT_RUN_DIALOG_H ugene-1.9.8/src/plugins/external_tool_support/src/tcoffee/TCoffeeSupportTask.h0000644000175000017500000000715111651544323026353 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_TCOFFEE_SUPPORT_TASK_H #define _U2_TCOFFEE_SUPPORT_TASK_H #include #include #include #include #include "utils/ExportTasks.h" #include #include "ExternalToolRunTask.h" namespace U2 { /*Options for MAFFT + --op # : Gap opening penalty, default: 1.53 + --ep # : Offset (works like gap extension penalty), default: 0.0 + --maxiterate # : Maximum number of iterative refinement, default: 0 ? --clustalout : Output: clustal format, default: fasta // With this option bad output clustal file is generated.(dkandrov) ? --reorder : Outorder: aligned, default: input order ? --quiet : Do not report progress ? --thread # : Number of threads. (# must be <= number of physical cores - 1) */ class TCoffeeLogParser; class TCoffeeSupportTaskSettings { public: TCoffeeSupportTaskSettings() {reset();} void reset(); float gapOpenPenalty; float gapExtenstionPenalty; int numIterations; QString inputFilePath; }; class TCoffeeSupportTask : public Task { Q_OBJECT public: TCoffeeSupportTask(MAlignmentObject* _mAObject, const TCoffeeSupportTaskSettings& settings); void prepare(); Task::ReportResult report(); QList onSubTaskFinished(Task* subTask); MAlignment resultMA; private: MAlignmentObject* mAObject; Document* currentDocument; Document* newDocument; QString url; TCoffeeLogParser* logParser; SaveMSA2SequencesTask* saveTemporaryDocumentTask; ExternalToolRunTask* tCoffeeTask; LoadDocumentTask* loadTmpDocumentTask; TCoffeeSupportTaskSettings settings; }; class TCoffeeWithExtFileSpecifySupportTask : public Task { Q_OBJECT public: TCoffeeWithExtFileSpecifySupportTask(const TCoffeeSupportTaskSettings& settings); ~TCoffeeWithExtFileSpecifySupportTask(); void prepare(); Task::ReportResult report(); QList onSubTaskFinished(Task* subTask); private: MAlignmentObject* mAObject; Document* currentDocument; bool cleanDoc; SaveDocumentTask* saveDocumentTask; LoadDocumentTask* loadDocumentTask; TCoffeeSupportTask* tCoffeeSupportTask; TCoffeeSupportTaskSettings settings; }; class TCoffeeLogParser : public ExternalToolLogParser { public: TCoffeeLogParser(); int getProgress(); void parseOutput(const QString& partOfLog); void parseErrOutput(const QString& partOfLog); private: QString lastErrLine; int progress; }; }//namespace #endif // _U2_TCOFFEE_SUPPORT_TASK_H ugene-1.9.8/src/plugins/external_tool_support/src/tcoffee/TCoffeeSupportTask.cpp0000644000175000017500000002752411651544323026714 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "TCoffeeSupportTask.h" #include "TCoffeeSupport.h" #include #include #include #include #include #include #include #include #include #include #include #include #include namespace U2 { void TCoffeeSupportTaskSettings::reset() { gapExtenstionPenalty = -1; gapOpenPenalty = -1; numIterations=0; inputFilePath=""; } TCoffeeSupportTask::TCoffeeSupportTask(MAlignmentObject* _mAObject, const TCoffeeSupportTaskSettings& _settings) : Task("Run T-Coffee alignment task", TaskFlags_NR_FOSCOE), mAObject(_mAObject), settings(_settings) { GCOUNTER( cvar, tvar, "TCoffeeSupportTask" ); currentDocument = mAObject->getDocument(); saveTemporaryDocumentTask=NULL; loadTmpDocumentTask=NULL; tCoffeeTask=NULL; newDocument=NULL; logParser=NULL; } void TCoffeeSupportTask::prepare(){ algoLog.info(tr("T-Coffee alignment started")); //Add new subdir for temporary files //Directory name is ExternalToolName + CurrentDate + CurrentTime QString tmpDirName = "TCoffee_"+QString::number(this->getTaskId())+"_"+ QDate::currentDate().toString("dd.MM.yyyy")+"_"+ QTime::currentTime().toString("hh.mm.ss.zzz")+"_"+ QString::number(QCoreApplication::applicationPid())+"/"; url=AppContext::getAppSettings()->getUserAppsSettings()->getTemporaryDirPath() + "/" + tmpDirName + "tmp.fa"; ioLog.details(tr("Saving data to temporary file '%1'").arg(url)); //Check and remove subdir for temporary files QDir tmpDir(AppContext::getAppSettings()->getUserAppsSettings()->getTemporaryDirPath()+"/"+tmpDirName); if(tmpDir.exists()){ foreach(QString file, tmpDir.entryList()){ tmpDir.remove(file); } if(!tmpDir.rmdir(tmpDir.absolutePath())){ stateInfo.setError(tr("Subdir for temporary files exists. Can not remove this directory.")); return; } } if(!tmpDir.mkpath(AppContext::getAppSettings()->getUserAppsSettings()->getTemporaryDirPath()+"/"+tmpDirName)){ stateInfo.setError(tr("Can not create directory for temporary files.")); return; } saveTemporaryDocumentTask=new SaveMSA2SequencesTask(mAObject->getMAlignment(), url, false, BaseDocumentFormats::PLAIN_FASTA); saveTemporaryDocumentTask->setSubtaskProgressWeight(5); addSubTask(saveTemporaryDocumentTask); } QList TCoffeeSupportTask::onSubTaskFinished(Task* subTask) { QList res; if(subTask->hasError()) { stateInfo.setError(subTask->getError()); return res; } if(hasError() || isCanceled()) { return res; } QString outputUrl = url+".msf"; if(subTask==saveTemporaryDocumentTask){ QStringList arguments; if(url.contains(" ")){ stateInfo.setError("Temporary directory path have space(s). Try select any other directory without spaces."); return res; } arguments <setSubtaskProgressWeight(95); res.append(tCoffeeTask); }else if(subTask==tCoffeeTask){ assert(logParser); delete logParser; if(!QFileInfo(outputUrl).exists()){ if(AppContext::getExternalToolRegistry()->getByName(TCOFFEE_TOOL_NAME)->isValid()){ stateInfo.setError(tr("Output file %1 not found").arg(outputUrl)); }else{ stateInfo.setError(tr("Output file %3 not found. May be %1 tool path '%2' not valid?") .arg(AppContext::getExternalToolRegistry()->getByName(TCOFFEE_TOOL_NAME)->getName()) .arg(AppContext::getExternalToolRegistry()->getByName(TCOFFEE_TOOL_NAME)->getPath()) .arg(outputUrl)); } emit si_stateChanged(); return res; } ioLog.details(tr("Loading output file '%1'").arg(outputUrl)); IOAdapterFactory* iof = AppContext::getIOAdapterRegistry()->getIOAdapterFactoryById(BaseIOAdapters::LOCAL_FILE); QVariantMap hints; hints[DocumentReadingMode_SequenceAsAlignmentHint] = true; loadTmpDocumentTask = new LoadDocumentTask(BaseDocumentFormats::MSF, outputUrl, iof, hints); loadTmpDocumentTask->setSubtaskProgressWeight(5); res.append(loadTmpDocumentTask); } else if (subTask==loadTmpDocumentTask) { newDocument=loadTmpDocumentTask->takeDocument(); SAFE_POINT(newDocument!=NULL, QString("output document '%1' not loaded").arg(newDocument->getURLString()), res); SAFE_POINT(newDocument->getObjects().length()!=0, QString("no objects in output document '%1'").arg(newDocument->getURLString()), res); //move MAlignment from new alignment to old document MAlignmentObject* newMAligmentObject=qobject_cast(newDocument->getObjects().first()); assert(newMAligmentObject!=NULL); resultMA=newMAligmentObject->getMAlignment(); mAObject->setMAlignment(resultMA); if (currentDocument != NULL){ currentDocument->setModified(true); } algoLog.info(tr("T-Coffee alignment successfully finished")); //new document deleted in destructor of LoadDocumentTask } return res; } Task::ReportResult TCoffeeSupportTask::report(){ //Remove subdir for temporary files, that created in prepare if(!url.isEmpty()){ QDir tmpDir(QFileInfo(url).absoluteDir()); foreach(QString file, tmpDir.entryList()){ tmpDir.remove(file); } if(!tmpDir.rmdir(tmpDir.absolutePath())){ stateInfo.setError(tr("Can not remove directory for temporary files.")); emit si_stateChanged(); } } return ReportResult_Finished; } //////////////////////////////////////// //TCoffeeWithExtFileSpecifySupportTask TCoffeeWithExtFileSpecifySupportTask::TCoffeeWithExtFileSpecifySupportTask(const TCoffeeSupportTaskSettings& _settings) : Task("Run MAFFT alignment task", TaskFlags_NR_FOSCOE), settings(_settings) { GCOUNTER( cvar, tvar, "TCoffeeSupportTask" ); mAObject = NULL; currentDocument = NULL; saveDocumentTask = NULL; loadDocumentTask = NULL; tCoffeeSupportTask = NULL; cleanDoc = true; } TCoffeeWithExtFileSpecifySupportTask::~TCoffeeWithExtFileSpecifySupportTask(){ if (cleanDoc){ delete currentDocument; } } void TCoffeeWithExtFileSpecifySupportTask::prepare(){ DocumentFormatConstraints c; c.checkRawData = true; c.supportedObjectTypes += GObjectTypes::MULTIPLE_ALIGNMENT; c.rawData = BaseIOAdapters::readFileHeader(settings.inputFilePath); QList formats = AppContext::getDocumentFormatRegistry()->selectFormats(c); if (formats.isEmpty()) { stateInfo.setError( tr("input_format_error") ); return; } DocumentFormatId alnFormat = formats.first(); IOAdapterFactory* iof = AppContext::getIOAdapterRegistry()->getIOAdapterFactoryById(BaseIOAdapters::url2io(settings.inputFilePath)); QVariantMap hints; hints[DocumentReadingMode_SequenceAsAlignmentHint] = true; loadDocumentTask = new LoadDocumentTask(alnFormat, settings.inputFilePath, iof, hints); addSubTask(loadDocumentTask); } QList TCoffeeWithExtFileSpecifySupportTask::onSubTaskFinished(Task* subTask) { QList res; if (subTask->hasError()) { stateInfo.setError(subTask->getError()); return res; } if (hasError() || isCanceled()) { return res; } if (subTask==loadDocumentTask){ currentDocument=loadDocumentTask->getDocument()->clone(); assert(currentDocument!=NULL); assert(currentDocument->getObjects().length()==1); mAObject=qobject_cast(currentDocument->getObjects().first()); assert(mAObject!=NULL); tCoffeeSupportTask=new TCoffeeSupportTask(mAObject,settings); res.append(tCoffeeSupportTask); } else if (subTask == tCoffeeSupportTask){ saveDocumentTask = new SaveDocumentTask(currentDocument,AppContext::getIOAdapterRegistry()->getIOAdapterFactoryById(BaseIOAdapters::url2io(settings.inputFilePath)),settings.inputFilePath); res.append(saveDocumentTask); } else if (subTask==saveDocumentTask){ Project* proj = AppContext::getProject(); if (proj == NULL) { res.append(AppContext::getProjectLoader()->openWithProjectTask(currentDocument->getURL(), currentDocument->getGHintsMap())); } else { Document* projDoc = proj->findDocumentByURL(currentDocument->getURL()); if (projDoc != NULL) { projDoc->setLastUpdateTime(); res.append(new LoadUnloadedDocumentAndOpenViewTask(projDoc)); } else { // Add document to project res.append(new AddDocumentAndOpenViewTask(currentDocument)); cleanDoc = false; } } } return res; } Task::ReportResult TCoffeeWithExtFileSpecifySupportTask::report(){ return ReportResult_Finished; } //////////////////////////////////////// //TCoffeeLogParser TCoffeeLogParser::TCoffeeLogParser() { progress=0; } void TCoffeeLogParser::parseOutput(const QString& partOfLog){ Q_UNUSED(partOfLog) } void TCoffeeLogParser::parseErrOutput(const QString& partOfLog){ lastPartOfLog=partOfLog.split(QRegExp("(\n|\r)")); lastPartOfLog.first()=lastErrLine+lastPartOfLog.first(); lastErrLine=lastPartOfLog.takeLast(); foreach(QString buf, lastPartOfLog){ if(buf.contains("WARNING")){ algoLog.info("MAFFT: " + buf); }else{ algoLog.trace(buf); } } } int TCoffeeLogParser::getProgress(){ /* parse progress string: [Submit Job][TOT= 18][ 22 %][ELAPSED TIME: 0 sec.] */ if(!lastPartOfLog.isEmpty()){ QString lastMessage=lastPartOfLog.last(); if(lastMessage.contains(QRegExp("\\[Submit +Job\\]\\[TOT="))){ QRegExp rx("(.*)\\[ +(\\d+) %\\](.*)"); assert(rx.indexIn(lastMessage)>-1); rx.indexIn(lastMessage); return rx.cap(2).toInt(); } } return progress; } }//namespace ugene-1.9.8/src/plugins/external_tool_support/src/tcoffee/TCoffeeWorker.h0000644000175000017500000000361711651544323025330 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_TCOFFEE_WORKER_H_ #define _U2_TCOFFEE_WORKER_H_ #include #include #include "TCoffeeSupportTask.h" namespace U2 { namespace LocalWorkflow { class TCoffeePrompter : public PrompterBase { Q_OBJECT public: TCoffeePrompter(Actor* p = 0); protected: QString composeRichDoc(); }; class TCoffeeWorker : public BaseWorker { Q_OBJECT public: TCoffeeWorker(Actor* a); virtual void init(); virtual bool isReady(); virtual Task* tick(); virtual bool isDone(); virtual void cleanup(); private slots: void sl_taskFinished(); protected: CommunicationChannel *input, *output; QString resultName,transId; TCoffeeSupportTaskSettings cfg; }; class TCoffeeWorkerFactory : public DomainFactory { public: static const QString ACTOR_ID; static void init(); TCoffeeWorkerFactory() : DomainFactory(ACTOR_ID) {} virtual Worker* createWorker(Actor* a) {return new TCoffeeWorker(a);} }; } // Workflow namespace } // U2 namespace #endif ugene-1.9.8/src/plugins/external_tool_support/src/tcoffee/TCoffeeSupport.h0000644000175000017500000000404711651544323025531 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_TCOFFEE_SUPPORT_H #define _U2_TCOFFEE_SUPPORT_H #include #include #include "utils/ExternalToolSupportAction.h" #define TCOFFEE_TOOL_NAME "T-Coffee" namespace U2 { class TCoffeeSupport : public ExternalTool { Q_OBJECT public: TCoffeeSupport(const QString& name, const QString& path = ""); GObjectViewWindowContext* getViewContext(){ return viewCtx; } public slots: void sl_runWithExtFileSpecify(); private: GObjectViewWindowContext* viewCtx; }; class TCoffeeSupportContext: public GObjectViewWindowContext { Q_OBJECT public: TCoffeeSupportContext(QObject* p); protected slots: void sl_align_with_TCoffee(); protected: virtual void initViewContext(GObjectView* view); virtual void buildMenu(GObjectView* view, QMenu* m); }; class TCoffeeSupportAction : public ExternalToolSupprotAction { Q_OBJECT public: TCoffeeSupportAction(QObject* p, GObjectView* v, const QString& text, int order) : ExternalToolSupprotAction(p,v,text,order, QStringList(TCOFFEE_TOOL_NAME)) {} MSAEditor* getMSAEditor() const; private slots: void sl_lockedStateChanged(); }; }//namespace #endif // _U2_TCOFFEE_SUPPORT_H ugene-1.9.8/src/plugins/external_tool_support/src/ExternalToolRunTask.h0000644000175000017500000000537311651544323025141 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_EXTERNAL_TOOL_RUN_TASK_H #define _U2_EXTERNAL_TOOL_RUN_TASK_H #include #include namespace U2 { class ExternalToolLogParser; class ExternalToolRunTaskHelper; class ExternalToolRunTask: public Task { Q_OBJECT friend class ExternalToolRunTaskHelper; public: ExternalToolRunTask(const QString& toolName, const QStringList& arguments, ExternalToolLogParser* logParser); ~ExternalToolRunTask(); void prepare(); void run(); Task::ReportResult report(); void cancelProcess(); private: QStringList arguments; QString program; ExternalToolLogParser* logParser; QString toolName; QProcess* externalToolProcess; }; /** Part of ExternalToolRunTask that belongs to task run thread -> get signals from that thread directly */ class ExternalToolRunTaskHelper : public QObject { Q_OBJECT public: ExternalToolRunTaskHelper(ExternalToolRunTask* t); public slots: void sl_onReadyToReadLog(); void sl_onReadyToReadErrLog(); private: ExternalToolRunTask* p; QByteArray logData; }; class ExternalToolSupportUtils : public QObject { public: static bool removeTmpDir(const QString& absoulutePath, QString& errMsg); static QString createTmpDir(const QString& dirName, int uniqueId, QString& errMsg); }; class ExternalToolLogParser { public: ExternalToolLogParser(); virtual int getProgress(){ return progress; } virtual void parseOutput(const QString& partOfLog); virtual void parseErrOutput(const QString& partOfLog); QString getLastError() const {return lastErrLine;} private: /* Percent values in range 0..100, negative if unknown. */ QString lastErrLine; int progress; QString lastLine; protected: QStringList lastPartOfLog; }; }//namespace #endif // _U2_EXTERNAL_TOOL_RUN_TASK_H ugene-1.9.8/src/plugins/external_tool_support/src/ExternalToolSupportSettingsController.cpp0000644000175000017500000005222311651544323031342 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "ExternalToolSupportSettingsController.h" #include "ExternalToolSupportSettings.h" #include "utils/ExternalToolValidateTask.h" #include #include #include #include #include #include #include #include namespace U2 { ExternalToolSupportSettingsPageController::ExternalToolSupportSettingsPageController(QObject* p) : AppSettingsGUIPageController(tr("External Tools"), ExternalToolSupportSettingsPageId, p) {} AppSettingsGUIPageState* ExternalToolSupportSettingsPageController::getSavedState() { ExternalToolSupportSettingsPageState* state = new ExternalToolSupportSettingsPageState(); state->externalTools=AppContext::getExternalToolRegistry()->getAllEntries(); return state; } void ExternalToolSupportSettingsPageController::saveState(AppSettingsGUIPageState* s) { ExternalToolSupportSettingsPageState* state = qobject_cast(s); //Add new external tools to registry foreach(ExternalTool* externalTool, state->externalTools){ AppContext::getExternalToolRegistry()->getByName(externalTool->getName())->setValid(externalTool->isValid()); AppContext::getExternalToolRegistry()->getByName(externalTool->getName())->setPath(externalTool->getPath()); AppContext::getExternalToolRegistry()->getByName(externalTool->getName())->setVersion(externalTool->getVersion()); } ExternalToolSupportSettings::setExternalTools(); } AppSettingsGUIPageWidget* ExternalToolSupportSettingsPageController::createWidget(AppSettingsGUIPageState* state) { ExternalToolSupportSettingsPageWidget* r = new ExternalToolSupportSettingsPageWidget(this); r->setState(state); return r; } ExternalToolSupportSettingsPageWidget::ExternalToolSupportSettingsPageWidget(ExternalToolSupportSettingsPageController* ) { setupUi(this); versionLabel->hide(); binaryPathLabel->hide(); } QWidget* ExternalToolSupportSettingsPageWidget::createPathEditor(QWidget *parent, const QString& path) const { QWidget * widget = new QWidget(parent); PathLineEdit* toolPathEdit= new PathLineEdit("","executable", false, widget); toolPathEdit->setObjectName("PathLineEdit"); toolPathEdit->setFrame(false); toolPathEdit->setSizePolicy(QSizePolicy(QSizePolicy::Preferred,QSizePolicy::Preferred)); toolPathEdit->setText(QDir::toNativeSeparators(path)); widget->setFocusProxy(toolPathEdit); connect(toolPathEdit, SIGNAL(cursorPositionChanged(int,int)), this, SLOT(sl_onPathEditWidgetClick())); connect(toolPathEdit, SIGNAL(selectionChanged()), this, SLOT(sl_onPathEditWidgetClick())); connect(toolPathEdit, SIGNAL(editingFinished()), this, SLOT(sl_toolPathCanged())); QToolButton * selectToolPathButton = new QToolButton(widget); selectToolPathButton->setVisible(true); selectToolPathButton->setText("..."); selectToolPathButton->setSizePolicy(QSizePolicy(QSizePolicy::Fixed,QSizePolicy::Preferred)); connect(selectToolPathButton, SIGNAL(clicked()), this, SLOT(sl_onPathEditWidgetClick())); connect(selectToolPathButton, SIGNAL(clicked()), toolPathEdit, SLOT(sl_onBrowse())); QToolButton * clearToolPathButton = new QToolButton(widget); clearToolPathButton->setObjectName("ClearToolPathButton"); clearToolPathButton->setVisible(true); clearToolPathButton->setIcon(QIcon(":external_tool_support/images/cancel.png")); clearToolPathButton->setSizePolicy(QSizePolicy(QSizePolicy::Fixed,QSizePolicy::Preferred)); clearToolPathButton->setEnabled(!path.isEmpty()); connect(clearToolPathButton, SIGNAL(clicked()), this, SLOT(sl_onPathEditWidgetClick())); connect(clearToolPathButton,SIGNAL(clicked()),toolPathEdit,SLOT(sl_clear())); QHBoxLayout* layout = new QHBoxLayout(widget); layout->setSpacing(0); layout->setMargin(0); layout->addWidget(toolPathEdit); QHBoxLayout* layout2 = new QHBoxLayout(widget); layout2->addWidget(selectToolPathButton); layout2->addWidget(clearToolPathButton); layout->addLayout(layout2); buttonsWidth=layout2->minimumSize().width(); return widget; } void ExternalToolSupportSettingsPageWidget::sl_linkActivated(QString url){ GUIUtils::runWebBrowser(url); } void ExternalToolSupportSettingsPageWidget::setState(AppSettingsGUIPageState* s) { ExternalToolSupportSettingsPageState* state = qobject_cast(s); connect(selectToolPackButton, SIGNAL(clicked()), this, SLOT(sl_onBrowseToolPackPath())); connect(linkLabel,SIGNAL(linkActivated(QString)),this,SLOT(sl_linkActivated(QString))); foreach(ExternalTool* tool, state->externalTools){ ExternalToolInfo info; info.name=tool->getName(); info.path=tool->getPath(); info.description=tool->getDescription(); info.valid=tool->isValid(); info.version=tool->getVersion(); externalToolsInfo.insert(info.name,info); } treeWidget->setColumnWidth(0,this->geometry().width()/3); QList > listToolKits=AppContext::getExternalToolRegistry()->getAllEntriesSortedByToolKits(); foreach(QList toolsList, listToolKits){ if(toolsList.length()>1){ QTreeWidgetItem* rootItem=new QTreeWidgetItem((QStringList) toolsList.first()->getToolKitName()); rootItem->setIcon(0, toolsList.first()->getIcon()); treeWidget->insertTopLevelItem(0, rootItem); foreach(ExternalTool* tool, toolsList){ insertChild(rootItem, tool->getName(), 0); } rootItem->setExpanded(true); //draw widget for path select button QWidget * widget = new QWidget(treeWidget); QToolButton * selectToolKitPathButton = new QToolButton(widget); selectToolKitPathButton->setVisible(true); selectToolKitPathButton->setText("..."); selectToolKitPathButton->setMinimumWidth(buttonsWidth); selectToolKitPathButton->setSizePolicy(QSizePolicy(QSizePolicy::Fixed,QSizePolicy::Preferred)); connect(selectToolKitPathButton, SIGNAL(clicked()), this, SLOT(sl_onPathEditWidgetClick())); connect(selectToolKitPathButton, SIGNAL(clicked()), this, SLOT(sl_onBrowseToolKitPath())); QHBoxLayout* layout = new QHBoxLayout(widget); layout->setSpacing(0); layout->setMargin(0); layout->addStretch(); layout->addWidget(selectToolKitPathButton); treeWidget->setItemWidget(rootItem,1,widget); }else{ QTreeWidgetItem* item=new QTreeWidgetItem((QStringList) toolsList.first()->getName()); treeWidget->addTopLevelItem(item); treeWidget->setItemWidget(item,1,createPathEditor(treeWidget, toolsList.first()->getPath())); if(toolsList.first()->getPath().isEmpty()){ item->setIcon(0, toolsList.first()->getGrayIcon()); }else if(toolsList.first()->isValid()){ item->setIcon(0, toolsList.first()->getIcon()); }else{ item->setIcon(0, toolsList.first()->getWarnIcon()); } } } connect(treeWidget,SIGNAL(itemSelectionChanged()),SLOT(sl_itemSelectionChanged())); } void ExternalToolSupportSettingsPageWidget::insertChild(QTreeWidgetItem* rootItem, QString name, int pos){ QTreeWidgetItem* item=new QTreeWidgetItem((QStringList)name); rootItem->insertChild(pos,item); treeWidget->setItemWidget(item,1,createPathEditor(treeWidget, externalToolsInfo[name].path)); if(externalToolsInfo.value(name).path.isEmpty()){ item->setIcon(0, AppContext::getExternalToolRegistry()->getByName(name)->getGrayIcon()); }else if(externalToolsInfo.value(name).valid){ item->setIcon(0, AppContext::getExternalToolRegistry()->getByName(name)->getIcon()); }else{ item->setIcon(0, AppContext::getExternalToolRegistry()->getByName(name)->getWarnIcon()); } } AppSettingsGUIPageState* ExternalToolSupportSettingsPageWidget::getState(QString& ) const { ExternalToolSupportSettingsPageState* state = new ExternalToolSupportSettingsPageState(); ExternalTool* externalTool; foreach(ExternalToolInfo info, externalToolsInfo){ externalTool=new ExternalTool(info.name,info.path); externalTool->setValid(info.valid); externalTool->setVersion(info.version); state->externalTools.append(externalTool); } return state; } void ExternalToolSupportSettingsPageWidget::sl_toolPathCanged(){ PathLineEdit* s=qobject_cast(sender()); assert(s!=NULL); if(!s->isModified()){ return; } QWidget* par=s->parentWidget(); QString path=s->text(); s->setModified(false); QList listOfItems=treeWidget->findItems("",Qt::MatchContains|Qt::MatchRecursive); assert(listOfItems.length()!=0); treeWidget->clearSelection(); foreach(QTreeWidgetItem* item, listOfItems){ QWidget* itemWid=treeWidget->itemWidget(item,1); if(par == itemWid){//may be no good method for check QTreeWidgetItem if(s->text().isEmpty()){ item->setIcon(0, AppContext::getExternalToolRegistry()->getByName(item->text(0))->getGrayIcon()); externalToolsInfo[item->text(0)].path=""; externalToolsInfo[item->text(0)].valid=false; externalToolsInfo[item->text(0)].version=""; }else{ ExternalToolValidateTask* validateTask=new ExternalToolValidateTask(item->text(0), path); connect(validateTask,SIGNAL(si_stateChanged()),SLOT(sl_validateTaskStateChanged())); AppContext::getTaskScheduler()->registerTopLevelTask(validateTask); externalToolsInfo[item->text(0)].path=path; } } } } void ExternalToolSupportSettingsPageWidget::sl_validateTaskStateChanged(){ ExternalToolValidateTask* s=qobject_cast(sender()); assert(s); if(s->isFinished()){ QList listOfItems=treeWidget->findItems(s->getToolName(),Qt::MatchExactly|Qt::MatchRecursive); assert(listOfItems.length()==1); if(s->isValidTool()){ listOfItems.at(0)->setIcon(0, AppContext::getExternalToolRegistry()->getByName(s->getToolName())->getIcon()); externalToolsInfo[s->getToolName()].valid=true; }else{ listOfItems.at(0)->setIcon(0, AppContext::getExternalToolRegistry()->getByName(s->getToolName())->getWarnIcon()); externalToolsInfo[s->getToolName()].valid=false; } externalToolsInfo[s->getToolName()].version=s->getToolVersion(); descriptionTextEdit->setText(AppContext::getExternalToolRegistry()->getByName(s->getToolName())->getDescription()); descriptionTextEdit->setText(descriptionTextEdit->toHtml()+tr("
Version: ")+externalToolsInfo[s->getToolName()].version); descriptionTextEdit->setText(descriptionTextEdit->toHtml()+tr("
Binary path: ")+externalToolsInfo[s->getToolName()].path); } } void ExternalToolSupportSettingsPageWidget::sl_itemSelectionChanged(){ QList selectedItems=treeWidget->selectedItems(); if(selectedItems.length()==0){ descriptionTextEdit->setText(tr("Select an external tool to view more information about it.")); return; } assert(selectedItems.length()==1); QString name=selectedItems.at(0)->text(0); if((selectedItems.at(0)->text(0) != "BLAST") && (selectedItems.at(0)->text(0) != "BLAST+")){ descriptionTextEdit->setText(AppContext::getExternalToolRegistry()->getByName(selectedItems.at(0)->text(0))->getDescription()); if(!externalToolsInfo[selectedItems.at(0)->text(0)].version.isEmpty()){ descriptionTextEdit->setText(descriptionTextEdit->toHtml()+tr("
Version: ")+externalToolsInfo[selectedItems.at(0)->text(0)].version); descriptionTextEdit->setText(descriptionTextEdit->toHtml()+tr("
Binary path: ")+externalToolsInfo[selectedItems.at(0)->text(0)].path); } } if(selectedItems.at(0)->text(0) == "BLAST"){ descriptionTextEdit->setText(tr("The Basic Local Alignment Search Tool (BLAST) finds regions of local similarity between sequences. " "The program compares nucleotide or protein sequences to sequence databases and calculates the statistical significance of matches. " "BLAST can be used to infer functional and evolutionary relationships between sequences as well as help identify members of gene families.")); } if(selectedItems.at(0)->text(0) == "BLAST+"){ descriptionTextEdit->setText(tr("BLAST+ is a new version of the BLAST package from the NCBI.")); } } void ExternalToolSupportSettingsPageWidget::sl_onPathEditWidgetClick(){ QWidget* s=qobject_cast(sender()); assert(s); QList listOfItems=treeWidget->findItems("",Qt::MatchContains|Qt::MatchRecursive); assert(listOfItems.length()!=0); treeWidget->clearSelection(); foreach(QTreeWidgetItem* item, listOfItems){ QWidget* par=s->parentWidget(); QWidget* itemWid=treeWidget->itemWidget(item,1); if(par == itemWid){ item->setSelected(true); } } } void ExternalToolSupportSettingsPageWidget::sl_onBrowseToolKitPath(){ LastOpenDirHelper lod("toolkit path"); QString dir; lod.url = dir = QFileDialog::getExistingDirectory(this, tr("Choose Directory With Executables"), lod.dir, QFileDialog::ShowDirsOnly | QFileDialog::DontResolveSymlinks); if (!dir.isEmpty()) { assert(treeWidget->selectedItems().isEmpty()==0); QString toolKitName=treeWidget->selectedItems().first()->text(0); QList listOfItems=treeWidget->findItems("",Qt::MatchContains|Qt::MatchRecursive); assert(listOfItems.length()!=0); foreach(QTreeWidgetItem* item, listOfItems){ if(AppContext::getExternalToolRegistry()->getByName(item->text(0)) != NULL){ if(AppContext::getExternalToolRegistry()->getByName(item->text(0))->getToolKitName() == toolKitName){ QWidget* itemWid=treeWidget->itemWidget(item,1); PathLineEdit* lineEdit=itemWid->findChild("PathLineEdit"); if(lineEdit->text().isEmpty()){ QDirIterator it(dir,QDirIterator::Subdirectories); bool fileNotFound=true; QString executableFileName=AppContext::getExternalToolRegistry()->getByName(item->text(0))->getExecutableFileName(); while (it.hasNext()&&fileNotFound) { QFileInfo info(it.filePath()+"/"+executableFileName); if(info.exists() && info.isFile() && info.isExecutable()){ QString path=QDir::toNativeSeparators(it.filePath()+"/"+executableFileName); lineEdit->setText(path); lineEdit->setModified(false); externalToolsInfo[item->text(0)].path=path; QToolButton* clearToolPathButton = itemWid->findChild("ClearToolPathButton"); assert(clearToolPathButton); clearToolPathButton->setEnabled(true); ExternalToolValidateTask* validateTask=new ExternalToolValidateTask(item->text(0), path); connect(validateTask,SIGNAL(si_stateChanged()),SLOT(sl_validateTaskStateChanged())); AppContext::getTaskScheduler()->registerTopLevelTask(validateTask); fileNotFound=false; } it.next(); } } } } } } } void ExternalToolSupportSettingsPageWidget::sl_onBrowseToolPackPath(){ LastOpenDirHelper lod("toolpack path"); QString dirPath; bool isPathValid=false; lod.url = dirPath = QFileDialog::getExistingDirectory(this, tr("Choose Directory With External Tools Pack"), lod.dir, QFileDialog::ShowDirsOnly | QFileDialog::DontResolveSymlinks); if (!dirPath.isEmpty()) { QDir dir=QDir(dirPath); QList listOfItems=treeWidget->findItems("",Qt::MatchContains|Qt::MatchRecursive); assert(listOfItems.length()!=0); foreach(QString dirName, dir.entryList(QDir::Dirs)){ foreach(QTreeWidgetItem* item, listOfItems){ if(AppContext::getExternalToolRegistry()->getByName(item->text(0)) != NULL){ QString toolKitName=AppContext::getExternalToolRegistry()->getByName(item->text(0))->getToolKitName(); if(toolKitName=="BLAST" && dirName.contains(toolKitName,Qt::CaseInsensitive) && dirName.contains("BLAST+",Qt::CaseInsensitive)){ }else{ if(dirName.contains(toolKitName,Qt::CaseInsensitive)){ isPathValid=true; QWidget* itemWid=treeWidget->itemWidget(item,1); PathLineEdit* lineEdit=itemWid->findChild("PathLineEdit"); if(lineEdit->text().isEmpty()){ QDirIterator it(dirPath+"/"+dirName,QDirIterator::Subdirectories); bool fileNotFound=true; QString executableFileName=AppContext::getExternalToolRegistry()->getByName(item->text(0))->getExecutableFileName(); while (it.hasNext()&&fileNotFound) { QFileInfo info(it.filePath()+"/"+executableFileName); if(info.exists() && info.isFile() && info.isExecutable()){ QString path=QDir::toNativeSeparators(it.filePath()+"/"+executableFileName); lineEdit->setText(path); lineEdit->setModified(false); externalToolsInfo[item->text(0)].path=path; QToolButton* clearToolPathButton = itemWid->findChild("ClearToolPathButton"); assert(clearToolPathButton); clearToolPathButton->setEnabled(true); ExternalToolValidateTask* validateTask=new ExternalToolValidateTask(item->text(0), path); connect(validateTask,SIGNAL(si_stateChanged()),SLOT(sl_validateTaskStateChanged())); AppContext::getTaskScheduler()->registerTopLevelTask(validateTask); fileNotFound=false; } it.next(); } } } } } } } if(!isPathValid){ QMessageBox::warning(this, L10N::warningTitle(), tr("Not a valid external tools directory"), QMessageBox::Ok); } } } //////////////////////////////////////// //PathLineEdit void PathLineEdit::sl_onBrowse() { LastOpenDirHelper lod(type); QString name; if(text().isEmpty()){ lod.url = name = QFileDialog::getOpenFileName(NULL, tr("Select a file"), lod.dir, FileFilter, 0, QFileDialog::DontConfirmOverwrite); }else{ lod.url = name = QFileDialog::getOpenFileName(NULL, tr("Select a file"), text(), FileFilter, 0, QFileDialog::DontConfirmOverwrite); } if (!name.isEmpty()) { setText(QDir::toNativeSeparators(name)); setModified(true); emit editingFinished(); } QToolButton* clearToolPathButton = this->parentWidget()->findChild("ClearToolPathButton"); assert(clearToolPathButton); clearToolPathButton->setEnabled(!text().isEmpty()); setFocus(); } void PathLineEdit::sl_clear(){ QToolButton* s=qobject_cast(sender()); assert(s); setText(""); s->setEnabled(false); setModified(true); emit editingFinished(); } } //namespace ugene-1.9.8/src/plugins/external_tool_support/src/clustalw/0000755000175000017500000000000011651544323022666 5ustar ilyailyaugene-1.9.8/src/plugins/external_tool_support/src/clustalw/ClustalWSupportTask.h0000644000175000017500000001005211651544323027013 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_CLUSTALW_SUPPORT_TASK_H #define _U2_CLUSTALW_SUPPORT_TASK_H #include #include #include #include #include "utils/ExportTasks.h" #include #include "ExternalToolRunTask.h" namespace U2 { /*Options for clustalW ***Multiple Alignments:*** ? -NEWTREE= :file for new guide tree ? -USETREE= :file for old guide tree + -MATRIX= :Protein weight matrix=BLOSUM, PAM, GONNET, ID or filename + -DNAMATRIX= :DNA weight matrix=IUB, CLUSTALW or filename + -GAPOPEN=f :gap opening penalty -- 100.0? + -GAPEXT=f :gap extension penalty -- 10.0? + -ENDGAPS :no end gap separation pen. + -GAPDIST=n :gap separation pen. range + -NOPGAP :residue-specific gaps off + -NOHGAP :hydrophilic gaps off ? -HGAPRESIDUES= :list hydrophilic res. ? -MAXDIV=n :% ident. for delay ? -TYPE= :PROTEIN or DNA - -TRANSWEIGHT=f :transitions weighting + -ITERATION= :NONE or TREE or ALIGNMENT + -NUMITER=n :maximum number of iterations to perform - -NOWEIGHTS :disable sequence weighting + -OUTORDER= :INPUT or ALIGNED */ class ClustalWLogParser; class ClustalWSupportTaskSettings { public: ClustalWSupportTaskSettings() {reset();} void reset(); float gapOpenPenalty; float gapExtenstionPenalty; bool endGaps; bool noPGaps; bool noHGaps; int gapDist; QString iterationType; int numIterations; QString inputFilePath; QString matrix; bool outOrderInput; // false - aligned, true - input }; class ClustalWSupportTask : public Task { Q_OBJECT public: ClustalWSupportTask(MAlignmentObject* _mAObject, const ClustalWSupportTaskSettings& settings); void prepare(); Task::ReportResult report(); QList onSubTaskFinished(Task* subTask); MAlignment resultMA; private: MAlignmentObject* mAObject; Document* currentDocument; Document* newDocument; QString url; ClustalWLogParser* logParser; SaveAlignmentTask* saveTemporaryDocumentTask; ExternalToolRunTask* clustalWTask; LoadDocumentTask* loadTemporyDocumentTask; ClustalWSupportTaskSettings settings; }; class ClustalWWithExtFileSpecifySupportTask : public Task { Q_OBJECT public: ClustalWWithExtFileSpecifySupportTask(const ClustalWSupportTaskSettings& settings); ~ClustalWWithExtFileSpecifySupportTask(); void prepare(); Task::ReportResult report(); QList onSubTaskFinished(Task* subTask); private: MAlignmentObject* mAObject; Document* currentDocument; bool cleanDoc; SaveDocumentTask* saveDocumentTask; LoadDocumentTask* loadDocumentTask; ClustalWSupportTask* clustalWSupportTask; ClustalWSupportTaskSettings settings; }; class ClustalWLogParser : public ExternalToolLogParser { public: ClustalWLogParser(int countSequencesInMSA); int getProgress(); private: int countSequencesInMSA; }; }//namespace #endif // _U2_CLUSTALW_SUPPORT_TASK_H ugene-1.9.8/src/plugins/external_tool_support/src/clustalw/ClustalWWorker.h0000644000175000017500000000363311651544323025774 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_CLUSTALW_WORKER_H_ #define _U2_CLUSTALW_WORKER_H_ #include #include #include "ClustalWSupportTask.h" namespace U2 { namespace LocalWorkflow { class ClustalWPrompter : public PrompterBase { Q_OBJECT public: ClustalWPrompter(Actor* p = 0); protected: QString composeRichDoc(); }; class ClustalWWorker : public BaseWorker { Q_OBJECT public: ClustalWWorker(Actor* a); virtual void init(); virtual bool isReady(); virtual Task* tick(); virtual bool isDone(); virtual void cleanup(); private slots: void sl_taskFinished(); protected: CommunicationChannel *input, *output; QString resultName,transId; ClustalWSupportTaskSettings cfg; }; class ClustalWWorkerFactory : public DomainFactory { public: static const QString ACTOR_ID; static void init(); ClustalWWorkerFactory() : DomainFactory(ACTOR_ID) {} virtual Worker* createWorker(Actor* a) {return new ClustalWWorker(a);} }; } // Workflow namespace } // U2 namespace #endif ugene-1.9.8/src/plugins/external_tool_support/src/clustalw/ClustalWSupportRunDialog.cpp0000644000175000017500000001532111651544323030334 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "ClustalWSupportRunDialog.h" #include #include #include #include namespace U2 { //////////////////////////////////////// //ClustalWSupportRunDialog ClustalWSupportRunDialog::ClustalWSupportRunDialog(const MAlignment& _ma, ClustalWSupportTaskSettings& _settings, QWidget* _parent) : QDialog(_parent), ma(_ma), settings(_settings) { setupUi(this); connect(this->iterationTypeCheckBox,SIGNAL(toggled(bool)),this,SLOT(sl_iterationTypeEnabled(bool))); connect(this->cancelButton,SIGNAL(clicked()),this,SLOT(reject())); connect(this->alignButton,SIGNAL(clicked()),this,SLOT(sl_align())); if(ma.getAlphabet()->isAmino()){ gapOpenSpinBox->setValue(10.0); gapExtSpinBox->setValue(0.2); proteinGapParamGroupBox->setEnabled(true); weightMatrixComboBox->clear(); weightMatrixComboBox->addItem("BLOSUM"); weightMatrixComboBox->addItem("PAM"); weightMatrixComboBox->addItem("GONNET"); weightMatrixComboBox->addItem("ID"); } } void ClustalWSupportRunDialog::sl_iterationTypeEnabled(bool checked){ if(checked){ iterationTypeComboBox->removeItem(0); }else{ iterationTypeComboBox->insertItem(0,"NONE"); iterationTypeComboBox->setCurrentIndex(0); } } void ClustalWSupportRunDialog::sl_align(){ if(gapOpenCheckBox->isChecked()) { settings.gapOpenPenalty = gapOpenSpinBox->value(); } if(gapExtCheckBox->isChecked()) { settings.gapExtenstionPenalty = gapExtSpinBox->value(); } if(gapDistancesCheckBox->isChecked()){ settings.gapDist = gapDistancesSpinBox->value(); } if(residueSpecificGapsOffCheckBox->isChecked()){ settings.noPGaps=true; } if(hydrophilicGapsOffCheckBox->isChecked()){ settings.noHGaps=true; } if(endGapsCheckBox->isChecked()){ settings.endGaps=true; } if(weightMatrixCheckBox->isChecked()){ settings.matrix=weightMatrixComboBox->currentText(); } if(outOrderCheckBox->isChecked()){ if(outOrderComboBox->currentText() == "Input"){ settings.outOrderInput=true; }else{ settings.outOrderInput=false; } } if(iterationTypeCheckBox->isChecked()){ settings.iterationType=iterationTypeComboBox->currentText(); if(maxIterationsCheckBox->isChecked()){ settings.numIterations=maxIterationsSpinBox->value(); } } accept(); } //////////////////////////////////////// //ClustalWWithExtFileSpecifySupportRunDialog ClustalWWithExtFileSpecifySupportRunDialog::ClustalWWithExtFileSpecifySupportRunDialog(ClustalWSupportTaskSettings& _settings, QWidget* _parent) : QDialog(_parent), settings(_settings) { setupUi(this); QWidget * widget = new QWidget(_parent); inputFileLineEdit= new FileLineEdit(DialogUtils::prepareDocumentsFileFilterByObjType(GObjectTypes::MULTIPLE_ALIGNMENT, true), "", false, widget); inputFileLineEdit->setText(""); QToolButton * selectToolPathButton = new QToolButton(widget); selectToolPathButton->setVisible(true); selectToolPathButton->setText("..."); connect(selectToolPathButton, SIGNAL(clicked()), inputFileLineEdit, SLOT(sl_onBrowse())); connect(inputFileLineEdit,SIGNAL(textChanged(QString)),this, SLOT(sl_inputFileLineEditChanged(QString))); QHBoxLayout* layout = new QHBoxLayout(widget); layout->addWidget(inputFileLineEdit); layout->addWidget(selectToolPathButton); QGroupBox* inputFileGroupBox=new QGroupBox(tr("Select input file"),widget); inputFileGroupBox->setLayout(layout); QBoxLayout* parentLayout = qobject_cast(this->layout()); assert(parentLayout); parentLayout->insertWidget(0, inputFileGroupBox); alignButton->setEnabled(false); connect(this->iterationTypeCheckBox,SIGNAL(toggled(bool)),this,SLOT(sl_iterationTypeEnabled(bool))); connect(this->cancelButton,SIGNAL(clicked()),this,SLOT(reject())); connect(this->alignButton,SIGNAL(clicked()),this,SLOT(sl_align())); proteinGapParamGroupBox->setEnabled(true); weightMatrixComboBox->insertSeparator(2); weightMatrixComboBox->addItem("BLOSUM"); weightMatrixComboBox->addItem("PAM"); weightMatrixComboBox->addItem("GONNET"); weightMatrixComboBox->addItem("ID"); } void ClustalWWithExtFileSpecifySupportRunDialog::sl_inputFileLineEditChanged(const QString& str){ alignButton->setEnabled(!str.isEmpty()); } void ClustalWWithExtFileSpecifySupportRunDialog::sl_iterationTypeEnabled(bool checked){ if(checked){ iterationTypeComboBox->removeItem(0); }else{ iterationTypeComboBox->insertItem(0,"NONE"); iterationTypeComboBox->setCurrentIndex(0); } } void ClustalWWithExtFileSpecifySupportRunDialog::sl_align(){ if(gapOpenCheckBox->isChecked()) { settings.gapOpenPenalty = gapOpenSpinBox->value(); } if(gapExtCheckBox->isChecked()) { settings.gapExtenstionPenalty = gapExtSpinBox->value(); } if(gapDistancesCheckBox->isChecked()){ settings.gapDist = gapDistancesSpinBox->value(); } if(residueSpecificGapsOffCheckBox->isChecked()){ settings.noPGaps=true; } if(hydrophilicGapsOffCheckBox->isChecked()){ settings.noHGaps=true; } if(endGapsCheckBox->isChecked()){ settings.endGaps=true; } if(weightMatrixCheckBox->isChecked()){ settings.matrix=weightMatrixComboBox->currentText(); } if(iterationTypeCheckBox->isChecked()){ settings.iterationType=iterationTypeComboBox->currentText(); if(maxIterationsCheckBox->isChecked()){ settings.numIterations=maxIterationsSpinBox->value(); } } if(!inputFileLineEdit->text().isEmpty()){ settings.inputFilePath=inputFileLineEdit->text(); }else{ assert(NULL); reject(); } accept(); } }//namespace ugene-1.9.8/src/plugins/external_tool_support/src/clustalw/ClustalWSupport.cpp0000644000175000017500000001662511651544323026537 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "ClustalWSupport.h" #include "ClustalWSupportRunDialog.h" #include "ClustalWSupportTask.h" #include "ExternalToolSupportSettingsController.h" #include "ExternalToolSupportSettings.h" #include #include #include #include #include #include #include #include #include #include #include #include #include namespace U2 { ClustalWSupport::ClustalWSupport(const QString& name, const QString& path) : ExternalTool(name, path) { if (AppContext::getMainWindow()) { viewCtx = new ClustalWSupportContext(this); icon = QIcon(":external_tool_support/images/clustalx.png"); grayIcon = QIcon(":external_tool_support/images/clustalx_gray.png"); warnIcon = QIcon(":external_tool_support/images/clustalx_warn.png"); } #ifdef Q_OS_WIN executableFileName="clustalw2.exe"; #else #ifdef Q_OS_LINUX executableFileName="clustalw2"; #endif #endif validationArguments<<"-help"; validMessage="CLUSTAL"; description=tr("ClustalW is a free sequence alignment software for DNA or proteins."); versionRegExp=QRegExp("CLUSTAL (\\d+\\.\\d+\\.\\d+) Multiple Sequence Alignments"); toolKitName="ClustalW"; } void ClustalWSupport::sl_runWithExtFileSpecify(){ //Check that Clustal and tempory directory path defined if (path.isEmpty()){ QMessageBox msgBox; msgBox.setWindowTitle(name); msgBox.setText(tr("Path for %1 tool not selected.").arg(name)); msgBox.setInformativeText(tr("Do you want to select it now?")); msgBox.setStandardButtons(QMessageBox::Yes | QMessageBox::No); msgBox.setDefaultButton(QMessageBox::Yes); int ret = msgBox.exec(); switch (ret) { case QMessageBox::Yes: AppContext::getAppSettingsGUI()->showSettingsDialog(ExternalToolSupportSettingsPageId); break; case QMessageBox::No: return; break; default: assert(NULL); break; } } if (path.isEmpty()){ return; } ExternalToolSupportSettings::checkTemporaryDir(); if (AppContext::getAppSettings()->getUserAppsSettings()->getTemporaryDirPath().isEmpty()){ return; } //Call select input file and setup settings dialog ClustalWSupportTaskSettings settings; ClustalWWithExtFileSpecifySupportRunDialog clustalWRunDialog(settings, AppContext::getMainWindow()->getQMainWindow()); if(clustalWRunDialog.exec() != QDialog::Accepted){ return; } assert(!settings.inputFilePath.isEmpty()); ClustalWWithExtFileSpecifySupportTask* clustalWSupportTask=new ClustalWWithExtFileSpecifySupportTask(settings); AppContext::getTaskScheduler()->registerTopLevelTask(clustalWSupportTask); } //////////////////////////////////////// //ClustalWSupportAction MSAEditor* ClustalWSupportAction::getMSAEditor() const { MSAEditor* e = qobject_cast(getObjectView()); assert(e!=NULL); return e; } void ClustalWSupportAction::sl_lockedStateChanged() { StateLockableItem* item = qobject_cast(sender()); assert(item!=NULL); setEnabled(!item->isStateLocked()); } //////////////////////////////////////// //ExternalToolSupportMSAContext ClustalWSupportContext::ClustalWSupportContext(QObject* p) : GObjectViewWindowContext(p, MSAEditorFactory::ID) { } void ClustalWSupportContext::initViewContext(GObjectView* view) { MSAEditor* msaed = qobject_cast(view); assert(msaed!=NULL); if (msaed->getMSAObject() == NULL) { return; } bool objLocked = msaed->getMSAObject()->isStateLocked(); ClustalWSupportAction* alignAction = new ClustalWSupportAction(this, view, tr("Align with ClustalW..."), 2000); addViewAction(alignAction); alignAction->setEnabled(!objLocked); connect(msaed->getMSAObject(), SIGNAL(si_lockedStateChanged()), alignAction, SLOT(sl_lockedStateChanged())); connect(alignAction, SIGNAL(triggered()), SLOT(sl_align_with_ClustalW())); } void ClustalWSupportContext::buildMenu(GObjectView* view, QMenu* m) { QList actions = getViewActions(view); QMenu* alignMenu = GUIUtils::findSubMenu(m, MSAE_MENU_ALIGN); assert(alignMenu!=NULL); foreach(GObjectViewAction* a, actions) { a->addToMenuWithOrder(alignMenu); } } void ClustalWSupportContext::sl_align_with_ClustalW() { //Check that Clustal and tempory directory path defined if (AppContext::getExternalToolRegistry()->getByName(CLUSTAL_TOOL_NAME)->getPath().isEmpty()){ QMessageBox msgBox; msgBox.setWindowTitle(CLUSTAL_TOOL_NAME); msgBox.setText(tr("Path for %1 tool not selected.").arg(CLUSTAL_TOOL_NAME)); msgBox.setInformativeText(tr("Do you want to select it now?")); msgBox.setStandardButtons(QMessageBox::Yes | QMessageBox::No); msgBox.setDefaultButton(QMessageBox::Yes); int ret = msgBox.exec(); switch (ret) { case QMessageBox::Yes: AppContext::getAppSettingsGUI()->showSettingsDialog(ExternalToolSupportSettingsPageId); break; case QMessageBox::No: return; break; default: assert(NULL); break; } } if (AppContext::getExternalToolRegistry()->getByName(CLUSTAL_TOOL_NAME)->getPath().isEmpty()){ return; } ExternalToolSupportSettings::checkTemporaryDir(); if (AppContext::getAppSettings()->getUserAppsSettings()->getTemporaryDirPath().isEmpty()){ return; } //Call run ClustalW align dialog ClustalWSupportAction* action = qobject_cast(sender()); assert(action!=NULL); MSAEditor* ed = action->getMSAEditor(); MAlignmentObject* obj = ed->getMSAObject(); if (obj == NULL) { return; } assert(!obj->isStateLocked()); ClustalWSupportTaskSettings settings; ClustalWSupportRunDialog clustalWRunDialog(obj->getMAlignment(), settings, AppContext::getMainWindow()->getQMainWindow()); if(clustalWRunDialog.exec() != QDialog::Accepted){ return; } ClustalWSupportTask* clustalWSupportTask=new ClustalWSupportTask(obj, settings); AppContext::getTaskScheduler()->registerTopLevelTask(clustalWSupportTask); } }//namespace ugene-1.9.8/src/plugins/external_tool_support/src/clustalw/ClustalWSupportTask.cpp0000644000175000017500000003165611651544323027363 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "ClustalWSupportTask.h" #include "ClustalWSupport.h" #include #include #include #include #include #include #include #include #include #include #include namespace U2 { void ClustalWSupportTaskSettings::reset() { gapExtenstionPenalty = -1; gapOpenPenalty = -1; endGaps=false; noPGaps=false; noHGaps=false; gapDist=-1; iterationType=""; numIterations=-1; matrix=""; inputFilePath=""; outOrderInput=true; } ClustalWSupportTask::ClustalWSupportTask(MAlignmentObject* _mAObject, const ClustalWSupportTaskSettings& _settings) : Task("Run ClustalW alignment task", TaskFlags_NR_FOSCOE), mAObject(_mAObject), settings(_settings) { GCOUNTER( cvar, tvar, "ClustalWSupportTask" ); currentDocument = mAObject->getDocument(); saveTemporaryDocumentTask=NULL; loadTemporyDocumentTask=NULL; clustalWTask=NULL; newDocument=NULL; logParser=NULL; } void ClustalWSupportTask::prepare(){ algoLog.info(tr("ClustalW alignment started")); //Add new subdir for temporary files //Directory name is ExternalToolName + CurrentDate + CurrentTime QString tmpDirName = "ClustalW_"+QString::number(this->getTaskId())+"_"+ QDate::currentDate().toString("dd.MM.yyyy")+"_"+ QTime::currentTime().toString("hh.mm.ss.zzz")+"_"+ QString::number(QCoreApplication::applicationPid())+"/"; url=AppContext::getAppSettings()->getUserAppsSettings()->getTemporaryDirPath() + "/" + tmpDirName + "tmp.aln"; ioLog.details(tr("Saving data to temporary file '%1'").arg(url)); //Check and remove subdir for temporary files QDir tmpDir(AppContext::getAppSettings()->getUserAppsSettings()->getTemporaryDirPath()+"/"+tmpDirName); if(tmpDir.exists()){ foreach(const QString& file, tmpDir.entryList()){ tmpDir.remove(file); } if(!tmpDir.rmdir(tmpDir.absolutePath())){ stateInfo.setError(tr("Subdirectory for temporary files exists. Can not remove this directory.")); return; } } if(!tmpDir.mkpath(AppContext::getAppSettings()->getUserAppsSettings()->getTemporaryDirPath()+"/"+tmpDirName)){ stateInfo.setError(tr("Can not create directory for temporary files.")); return; } saveTemporaryDocumentTask = new SaveAlignmentTask(mAObject->getMAlignment(), url, BaseDocumentFormats::CLUSTAL_ALN); saveTemporaryDocumentTask->setSubtaskProgressWeight(5); addSubTask(saveTemporaryDocumentTask); } QList ClustalWSupportTask::onSubTaskFinished(Task* subTask) { QList res; if(subTask->hasError()) { stateInfo.setError(subTask->getError()); return res; } if(hasError() || isCanceled()) { return res; } QString outputUrl = url+".out.aln"; if(subTask==saveTemporaryDocumentTask){ QStringList arguments; arguments <<"-ALIGN"<< "-INFILE="+url; if(settings.gapOpenPenalty != -1) { arguments <<"-GAPOPEN="+QString::number(settings.gapOpenPenalty); } if(settings.gapExtenstionPenalty != -1) { arguments <<"-GAPEXT="+QString::number(settings.gapExtenstionPenalty); } if(settings.gapDist != -1) { arguments <<"-GAPDIST="+QString::number(settings.gapDist); } if(!settings.iterationType.isEmpty()){ arguments<<"-ITERATION="+settings.iterationType; if(settings.numIterations != -1){ arguments <<"-NUMITER="+QString::number(settings.numIterations); } } if(settings.outOrderInput){ arguments << "-OUTORDER=INPUT"; }else{ arguments << "-OUTORDER=ALIGNED"; //this is default value in ClustalW, may be not needed set this option } if(!settings.matrix.isEmpty()){ if((settings.matrix == "IUB")||(settings.matrix == "CLUSTALW")){ arguments <<"-DNAMATRIX="+settings.matrix; }else{ arguments <<"-MATRIX="+settings.matrix; } } if(settings.endGaps) arguments<<"-ENDGAPS"; if(settings.noPGaps) arguments<<"-NOPGAP"; if(settings.noHGaps) arguments<<"-NOHGAP"; arguments << "-OUTFILE="+outputUrl; logParser=new ClustalWLogParser(mAObject->getMAlignment().getNumRows()); clustalWTask=new ExternalToolRunTask(CLUSTAL_TOOL_NAME,arguments, logParser); clustalWTask->setSubtaskProgressWeight(95); res.append(clustalWTask); }else if(subTask==clustalWTask){ assert(logParser); delete logParser; if(!QFileInfo(outputUrl).exists()){ if(AppContext::getExternalToolRegistry()->getByName(CLUSTAL_TOOL_NAME)->isValid()){ stateInfo.setError(tr("Output file %1 not found").arg(outputUrl)); }else{ stateInfo.setError(tr("Output file %3 not found. May be %1 tool path '%2' not valid?") .arg(AppContext::getExternalToolRegistry()->getByName(CLUSTAL_TOOL_NAME)->getName()) .arg(AppContext::getExternalToolRegistry()->getByName(CLUSTAL_TOOL_NAME)->getPath()) .arg(outputUrl)); } emit si_stateChanged(); return res; } ioLog.details(tr("Loading output file '%1'").arg(outputUrl)); loadTemporyDocumentTask= new LoadDocumentTask(BaseDocumentFormats::CLUSTAL_ALN, outputUrl, AppContext::getIOAdapterRegistry()->getIOAdapterFactoryById(BaseIOAdapters::LOCAL_FILE)); loadTemporyDocumentTask->setSubtaskProgressWeight(5); res.append(loadTemporyDocumentTask); }else if(subTask==loadTemporyDocumentTask){ newDocument=loadTemporyDocumentTask->takeDocument(); SAFE_POINT(newDocument!=NULL, QString("output document '%1' not loaded").arg(newDocument->getURLString()), res); SAFE_POINT(newDocument->getObjects().length()==1, QString("no objects in output document '%1'").arg(newDocument->getURLString()), res); //move MAlignment from new alignment to old document MAlignmentObject* newMAligmentObject=qobject_cast(newDocument->getObjects().first()); SAFE_POINT(newMAligmentObject!=NULL, "newDocument->getObjects().first() is not a MAlignmentObject", res); resultMA=newMAligmentObject->getMAlignment(); mAObject->setMAlignment(resultMA); if(currentDocument != NULL){ currentDocument->setModified(true); } algoLog.info(tr("ClustalW alignment successfully finished")); //new document deleted in destructor of LoadDocumentTask } return res; } Task::ReportResult ClustalWSupportTask::report(){ //Remove subdir for temporary files, that created in prepare if(!url.isEmpty()){ QDir tmpDir(QFileInfo(url).absoluteDir()); foreach(QString file, tmpDir.entryList()){ tmpDir.remove(file); } if(!tmpDir.rmdir(tmpDir.absolutePath())){ stateInfo.setError(tr("Can not remove directory for temporary files.")); emit si_stateChanged(); } } return ReportResult_Finished; } //////////////////////////////////////// //ClustalWWithExtFileSpecifySupportTask ClustalWWithExtFileSpecifySupportTask::ClustalWWithExtFileSpecifySupportTask(const ClustalWSupportTaskSettings& _settings) : Task("Run ClustalW alignment task", TaskFlags_NR_FOSCOE), settings(_settings) { GCOUNTER( cvar, tvar, "ClustalWSupportTask" ); mAObject = NULL; currentDocument = NULL; saveDocumentTask = NULL; loadDocumentTask = NULL; clustalWSupportTask = NULL; cleanDoc = true; } ClustalWWithExtFileSpecifySupportTask::~ClustalWWithExtFileSpecifySupportTask(){ if (cleanDoc) { delete currentDocument; } } void ClustalWWithExtFileSpecifySupportTask::prepare(){ DocumentFormatConstraints c; c.checkRawData = true; c.supportedObjectTypes += GObjectTypes::MULTIPLE_ALIGNMENT; c.rawData = BaseIOAdapters::readFileHeader(settings.inputFilePath); QList formats = AppContext::getDocumentFormatRegistry()->selectFormats(c); if (formats.isEmpty()) { stateInfo.setError(tr("input_format_error")); return; } DocumentFormatId alnFormat = formats.first(); QVariantMap hints; hints[DocumentReadingMode_SequenceAsAlignmentHint] = true; IOAdapterFactory* iof = AppContext::getIOAdapterRegistry()->getIOAdapterFactoryById(BaseIOAdapters::url2io(settings.inputFilePath)); loadDocumentTask = new LoadDocumentTask(alnFormat, settings.inputFilePath,iof, hints); addSubTask(loadDocumentTask); } QList ClustalWWithExtFileSpecifySupportTask::onSubTaskFinished(Task* subTask) { QList res; if(subTask->hasError()) { stateInfo.setError(subTask->getError()); return res; } if (hasError() || isCanceled()) { return res; } if (subTask == loadDocumentTask){ currentDocument=loadDocumentTask->getDocument()->clone(); // clone doc because it was created in another thread assert(currentDocument!=NULL); assert(currentDocument->getObjects().length()==1); mAObject=qobject_cast(currentDocument->getObjects().first()); assert(mAObject!=NULL); clustalWSupportTask=new ClustalWSupportTask(mAObject,settings); res.append(clustalWSupportTask); } else if (subTask == clustalWSupportTask) { saveDocumentTask = new SaveDocumentTask(currentDocument, AppContext::getIOAdapterRegistry()->getIOAdapterFactoryById(BaseIOAdapters::url2io(settings.inputFilePath)),settings.inputFilePath); res.append(saveDocumentTask); } else if (subTask == saveDocumentTask) { Project* proj = AppContext::getProject(); if (proj == NULL) { res.append(AppContext::getProjectLoader()->openWithProjectTask(currentDocument->getURLString(), currentDocument->getGHintsMap())); } else { Document* projDoc = proj->findDocumentByURL(currentDocument->getURL()); if (projDoc != NULL) { projDoc->setLastUpdateTime(); res.append(new LoadUnloadedDocumentAndOpenViewTask(projDoc)); } else { // Add document to project res.append(new AddDocumentAndOpenViewTask(currentDocument)); cleanDoc = false; } } } return res; } Task::ReportResult ClustalWWithExtFileSpecifySupportTask::report(){ return ReportResult_Finished; } //////////////////////////////////////// //ClustalWLogParser ClustalWLogParser::ClustalWLogParser(int _countSequencesInMSA) : ExternalToolLogParser(), countSequencesInMSA(_countSequencesInMSA){ } int ClustalWLogParser::getProgress(){ if(countSequencesInMSA <= 0){ return -1; } if(!lastPartOfLog.isEmpty()){ QString lastMessage=lastPartOfLog.last(); //0..10% progresss if(lastMessage.contains(QRegExp("Sequence \\d+:"))){ QRegExp rx("Sequence (\\d+):"); assert(rx.indexIn(lastMessage)>-1); rx.indexIn(lastMessage); return rx.cap(1).toInt()*10/countSequencesInMSA; } //10..90% progresss if(lastMessage.contains(QRegExp("Sequences \\(\\d+:\\d+\\)"))){ QRegExp rx("Sequences \\((\\d+):\\d+\\)"); assert(rx.indexIn(lastMessage)>-1); rx.indexIn(lastMessage); return rx.cap(1).toInt()*80/countSequencesInMSA+10; } //90..100% progresss if(lastMessage.contains(QRegExp("Group \\d+:"))){ QRegExp rx("Group (\\d+):"); assert(rx.indexIn(lastMessage)>-1); rx.indexIn(lastMessage); return rx.cap(1).toInt()*10/countSequencesInMSA+90; } } return 0; } }//namespace ugene-1.9.8/src/plugins/external_tool_support/src/clustalw/ClustalWSupportRunDialog.h0000644000175000017500000000375111651544323030005 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_CLUSTALW_SUPPORT_RUN_DIALOG_H #define _U2_CLUSTALW_SUPPORT_RUN_DIALOG_H #include #include #include #include "ClustalWSupportTask.h" namespace U2 { class ClustalWSupportRunDialog : public QDialog, public Ui_ClustalWSupportRunDialog { Q_OBJECT public: ClustalWSupportRunDialog(const MAlignment& ma, ClustalWSupportTaskSettings& settings, QWidget* parent); private slots: void sl_align(); void sl_iterationTypeEnabled(bool checked); private: MAlignment ma; ClustalWSupportTaskSettings& settings; }; class ClustalWWithExtFileSpecifySupportRunDialog : public QDialog, public Ui_ClustalWSupportRunDialog { Q_OBJECT public: ClustalWWithExtFileSpecifySupportRunDialog(ClustalWSupportTaskSettings& settings, QWidget* parent); private slots: void sl_align(); void sl_iterationTypeEnabled(bool checked); void sl_inputFileLineEditChanged(const QString& str); private: ClustalWSupportTaskSettings& settings; FileLineEdit* inputFileLineEdit; }; }//namespace #endif // _U2_CLUSTALW_SUPPORT_RUN_DIALOG_H ugene-1.9.8/src/plugins/external_tool_support/src/clustalw/ClustalWWorker.cpp0000644000175000017500000003266111651544323026332 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "ClustalWWorker.h" #include "TaskLocalStorage.h" #include "ClustalWSupport.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include namespace U2 { namespace LocalWorkflow { /**************************** * ClustalWWorkerFactory ****************************/ const QString ClustalWWorkerFactory::ACTOR_ID("clustalw"); const QString GAP_OPEN_PENALTY("gap-open-penalty"); const QString GAP_EXT_PENALTY("gap-ext-penalty"); const QString GAP_DIST("gap-distance"); const QString END_GAPS("close-gap-penalty"); const QString NO_PGAPS("no-residue-specific-gaps"); const QString NO_HGAPS("no-hydrophilic-gaps"); const QString ITERATION("iteration-type"); const QString NUM_ITERATIONS("iterations-max-num"); const QString MATRIX("matrix"); const QString EXT_TOOL_PATH("path"); const QString TMP_DIR_PATH("temp-dir"); void ClustalWWorkerFactory::init() { QList p; QList a; Descriptor ind(BasePorts::IN_MSA_PORT_ID(), ClustalWWorker::tr("Input MSA"), ClustalWWorker::tr("Input MSA to process.")); Descriptor oud(BasePorts::OUT_MSA_PORT_ID(), ClustalWWorker::tr("ClustalW result MSA"), ClustalWWorker::tr("The result of the ClustalW alignment.")); QMap inM; inM[BaseSlots::MULTIPLE_ALIGNMENT_SLOT()] = BaseTypes::MULTIPLE_ALIGNMENT_TYPE(); p << new PortDescriptor(ind, DataTypePtr(new MapDataType("clustal.in.msa", inM)), true /*input*/); QMap outM; outM[BaseSlots::MULTIPLE_ALIGNMENT_SLOT()] = BaseTypes::MULTIPLE_ALIGNMENT_TYPE(); p << new PortDescriptor(oud, DataTypePtr(new MapDataType("clustal.out.msa", outM)), false /*input*/, true /*multi*/); Descriptor gop(GAP_OPEN_PENALTY, ClustalWWorker::tr("Gap open penalty"), ClustalWWorker::tr("The penalty for opening a gap.")); Descriptor gep(GAP_EXT_PENALTY, ClustalWWorker::tr("Gap extension penalty"), ClustalWWorker::tr("The penalty for extending a gap.")); Descriptor gd(GAP_DIST, ClustalWWorker::tr("Gap distance"), ClustalWWorker::tr("The gap separation penalty. Tries to decrease the chances of gaps being too close to each other.")); Descriptor eg(END_GAPS, ClustalWWorker::tr("End gaps"), ClustalWWorker::tr("The penalty for closing a gap.")); Descriptor npg(NO_PGAPS, ClustalWWorker::tr("Residue-specific gaps off"), ClustalWWorker::tr("Residue-specific penalties are amino specific gap penalties that reduce or increase the gap opening penalties at each position in the alignment.")); Descriptor nhg(NO_HGAPS, ClustalWWorker::tr("Hydrophilic gaps off"), ClustalWWorker::tr("Hydrophilic gap penalties are used to increase the chances of a gap within a run (5 or more residues) of hydrophilic amino acids.")); Descriptor iter(ITERATION, ClustalWWorker::tr("Iteration type"), ClustalWWorker::tr("Alignment improvement iteration type. Can take values:

\

    \
  • None - No iteration;
  • \
  • Tree - Iteration at each step of alignment process;
  • \
  • Alignment - Iteation only on final alignment.
  • \
")); Descriptor ni(NUM_ITERATIONS, ClustalWWorker::tr("Number of iterations"), ClustalWWorker::tr("The maximum number of iterations to perform.")); Descriptor matrix(MATRIX, ClustalWWorker::tr("Weight matrix"), ClustalWWorker::tr("For proteins it is a scoring table which describes the similarity of each amino acid to each other and can take values:

\

    \
  • BLOSUM - Appear to be the best available for carrying out database similarity (homology searches). \
  • PAM - Have been extremely widely used since the late '70s. \
  • Gonnet - Derived using almost the same procedure as the PAM bit are much more up to date. \
  • ID - Identitical matrix gives a score of 1.0 to two identical amino acids and a score of zero otherwise. \
\

\ For DNA it is the scores assigned to matches and mismatches. The values available are: \

    \
  • IUB - The default scoring matrix used by BESTFIT for the comparison of nucleic acid sequences. All matches score 1.9; all mismatches for IUB symbols score 0.\
  • ClustalW - The previous system used by Clustal W, in which matches score 1.0 and mismatches score 0. All matches for IUB symbols also score 0. \
")); Descriptor etp(EXT_TOOL_PATH, ClustalWWorker::tr("Tool path"), ClustalWWorker::tr("Path to the ClustalW tool." "

The default path can be set in the UGENE application settings.")); Descriptor tdp(TMP_DIR_PATH, ClustalWWorker::tr("Temporary directory"), ClustalWWorker::tr("Directory to store temporary files.")); a << new Attribute(gop, BaseTypes::NUM_TYPE(), false, QVariant(53.90)); a << new Attribute(gep, BaseTypes::NUM_TYPE(), false, QVariant(8.52)); a << new Attribute(gd, BaseTypes::NUM_TYPE(), false, QVariant(4.42)); a << new Attribute(eg, BaseTypes::BOOL_TYPE(), false, QVariant(false)); a << new Attribute(npg, BaseTypes::BOOL_TYPE(), false, QVariant(false)); a << new Attribute(nhg, BaseTypes::BOOL_TYPE(), false, QVariant(false)); a << new Attribute(iter, BaseTypes::NUM_TYPE(), false, 0); a << new Attribute(ni, BaseTypes::NUM_TYPE(), false, QVariant(3)); a << new Attribute(matrix, BaseTypes::NUM_TYPE(), false, -1); a << new Attribute(etp, BaseTypes::STRING_TYPE(), true, QVariant("Default")); a << new Attribute(tdp, BaseTypes::STRING_TYPE(), true, QVariant("Default")); Descriptor desc(ACTOR_ID, ClustalWWorker::tr("Align with ClustalW"), ClustalWWorker::tr("Aligns multiple sequence alignments (MSAs) supplied with ClustalW." "

ClustalW is a general purpose multiple sequence alignment program for DNA or proteins." "Visit http://www.clustal.org/ to learn more about it.")); ActorPrototype* proto = new IntegralBusActorPrototype(desc, p, a); QMap delegates; { QVariantMap m; m["minimum"] = double(.00); m["maximum"] = double(100.00); m["decimals"] = 2; delegates[GAP_OPEN_PENALTY] = new DoubleSpinBoxDelegate(m); } { QVariantMap m; m["minimum"] = double(.00); m["maximum"] = double(10.00); m["decimals"] = 2; delegates[GAP_EXT_PENALTY] = new DoubleSpinBoxDelegate(m); } { QVariantMap m; m["minimum"] = double(.00); m["maximum"] = double(10.00); m["decimals"] = 2; delegates[GAP_DIST] = new DoubleSpinBoxDelegate(m); } { QVariantMap vm; vm["None"] = 0; vm["Tree"] = 1; vm["Alignment"] = 2; delegates[ITERATION] = new ComboBoxDelegate(vm); } { QVariantMap vm; vm["default"] = -1; vm["IUB"] = 0; vm["ClustalW"] = 1; vm["BLOSUM"] = 2; vm["PAM"] = 3; vm["GONNET"] = 4; vm["ID"] = 5; delegates[MATRIX] = new ComboBoxDelegate(vm); } delegates[EXT_TOOL_PATH] = new URLDelegate("", "executable", false); delegates[TMP_DIR_PATH] = new URLDelegate("", "TmpDir", false, true); proto->setEditor(new DelegateEditor(delegates)); proto->setPrompter(new ClustalWPrompter()); proto->setIconPath(":external_tool_support/images/clustalx.png"); WorkflowEnv::getProtoRegistry()->registerProto(BaseActorCategories::CATEGORY_ALIGNMENT(), proto); DomainFactory* localDomain = WorkflowEnv::getDomainRegistry()->getById(LocalDomainFactory::ID); localDomain->registerEntry(new ClustalWWorkerFactory()); } /**************************** * ClustalWPrompter ****************************/ ClustalWPrompter::ClustalWPrompter(Actor* p) : PrompterBase(p) { } QString ClustalWPrompter::composeRichDoc() { IntegralBusPort* input = qobject_cast(target->getPort(BasePorts::IN_MSA_PORT_ID())); Actor* producer = input->getProducer(BasePorts::IN_MSA_PORT_ID()); QString producerName = producer ? tr(" from %1").arg(producer->getLabel()) : ""; QString doc = tr("Aligns each MSA supplied %1 with \"ClustalW\".") .arg(producerName); return doc; } /**************************** * ClustalWWorker ****************************/ ClustalWWorker::ClustalWWorker(Actor* a) : BaseWorker(a), input(NULL), output(NULL) { } void ClustalWWorker::init() { input = ports.value(BasePorts::IN_MSA_PORT_ID()); output = ports.value(BasePorts::OUT_MSA_PORT_ID()); } bool ClustalWWorker::isReady() { return (input && input->hasMessage()); } Task* ClustalWWorker::tick() { Message inputMessage = getMessageAndSetupScriptValues(input); cfg.gapOpenPenalty=actor->getParameter(GAP_OPEN_PENALTY)->getAttributeValue(); cfg.gapExtenstionPenalty=actor->getParameter(GAP_EXT_PENALTY)->getAttributeValue(); cfg.gapDist=actor->getParameter(GAP_DIST)->getAttributeValue(); cfg.endGaps=actor->getParameter(END_GAPS)->getAttributeValue(); cfg.noHGaps=actor->getParameter(NO_HGAPS)->getAttributeValue(); cfg.noPGaps=actor->getParameter(NO_PGAPS)->getAttributeValue(); if(actor->getParameter(ITERATION)->getAttributeValue() != 0){ if(actor->getParameter(ITERATION)->getAttributeValue() == 1){ cfg.iterationType="TREE"; }else if(actor->getParameter(ITERATION)->getAttributeValue() == 2){ cfg.iterationType="ALIGNMENT"; } if(actor->getParameter(NUM_ITERATIONS)->getAttributeValue() != 3){ cfg.numIterations=actor->getParameter(NUM_ITERATIONS)->getAttributeValue(); } } if(actor->getParameter(MATRIX)->getAttributeValue() == -1){ if(actor->getParameter(MATRIX)->getAttributeValue() == 0){ cfg.matrix="IUB"; }else if(actor->getParameter(MATRIX)->getAttributeValue() == 1){ cfg.matrix="CLUSTALW"; }else if(actor->getParameter(MATRIX)->getAttributeValue() == 2){ cfg.matrix="BLOSUM"; }else if(actor->getParameter(MATRIX)->getAttributeValue() == 3){ cfg.matrix="PAM"; }else if(actor->getParameter(MATRIX)->getAttributeValue() == 4){ cfg.matrix="GONNET"; }else if(actor->getParameter(MATRIX)->getAttributeValue() == 5){ cfg.matrix="ID"; } } QString path=actor->getParameter(EXT_TOOL_PATH)->getAttributeValue(); if(QString::compare(path, "default", Qt::CaseInsensitive) != 0){ AppContext::getExternalToolRegistry()->getByName(CLUSTAL_TOOL_NAME)->setPath(path); } path=actor->getParameter(TMP_DIR_PATH)->getAttributeValue(); if(QString::compare(path, "default", Qt::CaseInsensitive) != 0){ AppContext::getAppSettings()->getUserAppsSettings()->setTemporaryDirPath(path); } MAlignment msa = inputMessage.getData().toMap().value(BaseSlots::MULTIPLE_ALIGNMENT_SLOT().getId()).value(); if( msa.isEmpty() ) { return new FailTask(tr("An empty MSA has been supplied to ClustalW.")); } Task* t = new ClustalWSupportTask(new MAlignmentObject(msa), cfg); connect(t, SIGNAL(si_stateChanged()), SLOT(sl_taskFinished())); return t; } void ClustalWWorker::sl_taskFinished() { ClustalWSupportTask* t = qobject_cast(sender()); if (t->getState() != Task::State_Finished) return; QVariant v = qVariantFromValue(t->resultMA); output->put(Message(BaseTypes::MULTIPLE_ALIGNMENT_TYPE(), v)); if (input->isEnded()) { output->setEnded(); } algoLog.info(tr("Aligned %1 with ClustalW").arg(t->resultMA.getName())); } bool ClustalWWorker::isDone() { return !input || input->isEnded(); } void ClustalWWorker::cleanup() { } } //namespace LocalWorkflow } //namespace U2 ugene-1.9.8/src/plugins/external_tool_support/src/clustalw/ClustalWSupport.h0000644000175000017500000000406211651544323026174 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_CLUSTALW_SUPPORT_H #define _U2_CLUSTALW_SUPPORT_H #include #include #include "utils/ExternalToolSupportAction.h" #define CLUSTAL_TOOL_NAME "ClustalW" namespace U2 { class ClustalWSupport : public ExternalTool { Q_OBJECT public: ClustalWSupport(const QString& name, const QString& path = ""); GObjectViewWindowContext* getViewContext(){ return viewCtx; } public slots: void sl_runWithExtFileSpecify(); private: GObjectViewWindowContext* viewCtx; }; class ClustalWSupportContext: public GObjectViewWindowContext { Q_OBJECT public: ClustalWSupportContext(QObject* p); protected slots: void sl_align_with_ClustalW (); protected: virtual void initViewContext(GObjectView* view); virtual void buildMenu(GObjectView* view, QMenu* m); }; class ClustalWSupportAction : public ExternalToolSupprotAction { Q_OBJECT public: ClustalWSupportAction(QObject* p, GObjectView* v, const QString& text, int order) : ExternalToolSupprotAction(p,v,text,order, QStringList(CLUSTAL_TOOL_NAME)) {} MSAEditor* getMSAEditor() const; private slots: void sl_lockedStateChanged(); }; }//namespace #endif // _U2_CLUSTALW_SUPPORT_H ugene-1.9.8/src/plugins/external_tool_support/transl/0000755000175000017500000000000011651544323021544 5ustar ilyailyaugene-1.9.8/src/plugins/external_tool_support/transl/russian.ts0000644000175000017500000025467211651544323023620 0ustar ilyailya BlastAllSupportDialog Request to local BLAST database Запрос к локальной БД BLAST General options Основные параметры Select search: Тип поиска blastn blastp blastx tblastn tblastx Search for short, nearly exact matches Поиск коротких последовательностей Expectation value Математическое ожидание Megablast Max hits Макс. число совпадений: Off Select database path: Путь к БД ... Base name for BLAST DB files: Базовое имя для файлов БД Number of CPUs being used Использовать процессоров Advanced options Дополнительные опции Word size Размер слова Gap costs Вес пропуска Match scores Веса совпадений 1 -3 1 -4 1 -2 1 -1 2 -7 2 -5 2 -3 4 -5 5 -4 Matrix Матрица BLOSUM62 BLOSUM45 BLOSUM80 PAM30 PAM70 Service Сервис plain psi phi PHI pattern Шаблон PHI Filters Фильтры Low complexity filter Фильтр низкой сложности Human repeats filter Фильтр человеческих повторов Masks Маски Mask for lookup table only Только маска таблицы поиска Mask lower case letters Маска символов нижн. регистра Restore to Default Значения по умолчанию Search Искать Cancel Отмена ClustalWSupportRunDialog Align with ClustalW Выравнивание ClustalW Advanced options Дополнительные опции Gap opening penalty Штраф за открывающий пропуск Gap extension penalty Штраф за промежуточный пропуск Weight matrix Весовая матрица IUB CLUSTALW Max iterations Количество итераций TREE Дерево ALIGNMENT Выравнивание Iteration type Тип итераций Protein gap parameters Параметры для белковых последовательностей Gap separation distance Расстояние между пропусками Residue-specific gaps off Откл. специфические для остатков пропуски Hydrophilic gaps off Отключить гидрофильные пропуски No end gap separation penalty Не вводить штраф за разделение пропусков Align Выровнять Cancel Отмена ETSSettingsWidget Resource settings Настройки ресурсов Supported tools Поддерживаемые программы Name Имя Path Путь Additional information Дополнительная информация <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> <html><head><meta name="qrichtext" content="1" /><style type="text/css"> p, li { white-space: pre-wrap; } </style></head><body style=" font-family:'Sans Serif'; font-size:9pt; font-weight:400; font-style:normal;"> <table border="0" style="-qt-table-type: root; margin-top:4px; margin-bottom:4px; margin-left:4px; margin-right:4px;"> <tr> <td style="border: none;"> <p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Select an external tool to view more information about it.</p></td></tr></table></body></html> Binary path: Version info FormatDBSupportRunDialog Format database Input data Select input file(s) for formatting database: ... Or select directory with input files: File filter Include files filter *.fa;*.fasta Exclude files filter *.pal Type of file(s) protein nucleotide Output settings Select the path to save the database into: Base name for BLAST files: Title for database file: Format Cancel Отмена MAFFTSupportRunDialog Align with MAFFT Выровнять с MAFFT Advanced options Дополнительные опции Gap opening penalty Штраф за открывающий пропуск Offset (works like gap extension penalty) Смещение (работает как штраф за промежуточный пропуск) Maximum number of iterative refinement Максимальное число итераций Align Выровнять Cancel Отмена QObject Path for temporary files Путь к папке с временными файлами Path for temporary files not selected. Do you want to select it now? SelectPathDialog Path settings Установки пути Select executable file of Укажите исполнимый файл ... Select directory for tempory files: Выберите директорию для временных файлов: OK Готово Cancel Отмена TCoffeeSupportRunDialog Align with T-Coffee Выровнять с T-Coffee Advanced options Дополнительные опции Gap opening penalty Штраф за открывающий пропуск Gap extension penalty Штраф за промежуточный пропуск Number of iterations Количество итераций Align Выровнять Cancel Отмена U2::BlastAllSupport The <i>blastall</i> is the old program developed and distributed by the NCBI for running BLAST searches. The NCBI recommends that people start using the programs of the BLAST+ package instead. Path for BLAST %1 tool not selected. Do you want to select it now? U2::BlastAllSupportContext Query with BLAST... Path for BLAST %1 tool not selected. Do you want to select it now? U2::BlastAllSupportMultiTask Source file Used databse No any results found U2::BlastAllSupportRunDialog Wrong parameters for creating annotations U2::BlastAllSupportTask Subdirectory for temporary files exists. Can not remove this directory. Can not create directory for temporary files. Не удаётся создать директорию для временных файлов. Can not remove directory for temporary files. U2::BlastAllWithExtFileSpecifySupportRunDialog Select input file Выберите входной файл Wrong input file This file not contain any sequence. Wrong parameters for creating annotations U2::BlastPlusSupport Path for BLAST+ tools not selected. Do you want to select it now? U2::BlastPlusSupportCommonTask Subdirectory for temporary files exists. Can not remove this directory. Can not create directory for temporary files. Не удаётся создать директорию для временных файлов. Can not remove directory for temporary files. U2::BlastPlusSupportContext Query with BLAST+... Path for BLAST+ tools not selected. Do you want to select it now? U2::BlastPlusSupportMultiTask Source file Used databse No any results found U2::BlastPlusSupportRunDialog Wrong parameters for creating annotations U2::BlastPlusWithExtFileSpecifySupportRunDialog Select input file Выберите входной файл Wrong input file This file not contain any sequence. Wrong parameters for creating annotations U2::BlastRunCommonDialog Select a directory with database files Direct nucleotide alignment Direct protein alignment Protein alignment, input nucleotide is translated input protein before the search Protein alignment, nucleotide database is translated input protein before the search Protein alignment, both input query and database are translated before the search U2::ClustalWSupport <i>ClustalW</i> is a free sequence alignment software for DNA or proteins. Path for %1 tool not selected. Do you want to select it now? U2::ClustalWSupportContext Align with ClustalW Выровнять с ClustalW Path for %1 tool not selected. Do you want to select it now? U2::ClustalWSupportTask Subdirectory for temporary files exists. Can not remove this directory. Can not create directory for temporary files. Не удаётся создать директорию для временных файлов. Can not remove directory for temporary files. U2::ClustalWWithExtFileSpecifySupportRunDialog Select input file Выберите входной файл U2::ClustalWWithExtFileSpecifySupportTask input_format_error Ошибка входного формата U2::ETSProjectViewItemsContoller FormatDB BLAST+ make DB BLAST Path for BLAST %1 tool not selected. Path for BLAST+ %1 tool not selected. Do you want to select it now? U2::ExternalToolRunTask Can not run %1 tool. U2::ExternalToolSupportPlugin External tool support Поддержка внешних инструментов Runs other external tools Модуль позволяет использовать внешние программы ClustalW MAFFT T-Coffee Multiple alignment Множественное выравнивание FormatDB... Создать БД BLAST... BLAST+ make DB... Создать БД BLAST+... BLAST Search... Искать с помощью BLAST... BLAST+ Search... Искать с помощью BLAST+... BLAST U2::ExternalToolSupportService External tools support Поддержка внешних инструментов Provides support to run external tools from UGENE Позволяет запускать внешние инструменты из UGENE U2::ExternalToolSupportSettingsPageController External tools Внешние инструменты U2::ExternalToolSupportSettingsPageWidget BLAST BLAST+ <br>Version: <br>Binary path: Select an external tool to view more information about it. The <i>Basic Local Alignment Search Tool</i> (BLAST) finds regions of local similarity between sequences. The program compares nucleotide or protein sequences to sequence databases and calculates the statistical significance of matches. BLAST can be used to infer functional and evolutionary relationships between sequences as well as help identify members of gene families. <i>BLAST+</i> is a new version of the BLAST package from the NCBI. U2::ExternalToolValidateTask It is possible that the specified executable file for %1 tool is invalid. Tool does not start. It is possible that the specified executable file for %1 tool is invalid. Can not find expected message. U2::FormatDBSupport The <i>formatdb</i> formats protein or nucleotide source databases before these databases can be searched by <i>blastall</i>. The <i>makeblastdb</i> formats protein or nucleotide source databases before these databases can be searched by other BLAST+ tools. Path for BLAST %1 tool not selected. Path for BLAST+ %1 tool not selected. Do you want to select it now? U2::FormatDBSupportRunDialog Select file(s) Select a directory with input files Select a directory to save database files U2::FormatDBSupportTask Input files paths contain space characters. Output database path contain space characters. U2::LocalWorkflow::BlastAllPrompter from %1 For sequence <u>%1</u> find annotations in database <u>%2</u> U2::LocalWorkflow::BlastAllWorker Input sequence Sequence for which annotations is searched. Annotations Found annotations. Search type Select type of BLAST searches Database Path Path with database files Database Name Base name for BLAST DB files Expected value This setting specifies the statistical significance threshold for reporting matches against database sequences. Annotate as Name for annotations Tool Path External tool path Temporary directory Directory for temporary files Local BLAST search Finds annotations for DNA sequence in local database Empty sequence supplied to BLAST Selected BLAST search with nucleotide input sequence Selected BLAST search with amino acid input sequence U2::LocalWorkflow::BlastPlusPrompter from %1 For sequence <u>%1</u> find annotations in database <u>%2</u> U2::LocalWorkflow::BlastPlusWorker Input sequence Sequence for which annotations is searched. Annotations Found annotations. Search type Select type of BLAST+ searches Database Path Path with database files Database Name Base name for BLAST+ DB files Expected value This setting specifies the statistical significance threshold for reporting matches against database sequences. Annotate as Name for annotations Tool Path External tool path Temporary directory Directory for temporary files Local BLAST+ search Finds annotations for DNA sequence in local database Empty sequence supplied to BLAST Selected BLAST search with nucleotide input sequence Selected BLAST search with amino acid input sequence U2::LocalWorkflow::ClustalWPrompter from %1 Aligns each MSA supplied <u>%1</u> with "<u>ClustalW</u>". U2::LocalWorkflow::ClustalWWorker Input MSA Input MSA to process. ClustalW result MSA The result of the ClustalW alignment. Gap open penalty The penalty for opening a gap. Gap extension penalty Штраф за промежуточный пропуск The penalty for extending a gap. Gap distance The gap separation penalty. Tries to decrease the chances of gaps being too close to each other. End gaps The penalty for closing a gap. Residue-specific gaps off Откл. спецефические для остатков пропуски Residue-specific penalties are amino specific gap penalties that reduce or increase the gap opening penalties at each position in the alignment. Hydrophilic gaps off Отключить гидрофильные пропуски Hydrophilic gap penalties are used to increase the chances of a gap within a run (5 or more residues) of hydrophilic amino acids. Iteration type Number of iterations Количество итераций The maximum number of iterations to perform. Weight matrix Tool path Path to the ClustalW tool.<p>The default path can be set in the UGENE application settings. Directory to store temporary files. Aligns multiple sequence alignments (MSAs) supplied with ClustalW.<p>ClustalW is a general purpose multiple sequence alignment program for DNA or proteins.Visit <a href="http://www.clustal.org/">http://www.clustal.org/</a> to learn more about it. Temporary directory Alignment improvement iteration type. Can take values: <p> <ul> <li>None - No iteration;</li> <li>Tree - Iteration at each step of alignment process;</li> <li>Alignment - Iteation only on final alignment.</li> </ul> For proteins it is a scoring table which describes the similarity of each amino acid to each other and can take values: <p> <ul> <li>BLOSUM - Appear to be the best available for carrying out database similarity (homology searches). <li>PAM - Have been extremely widely used since the late '70s. <li>Gonnet - Derived using almost the same procedure as the PAM bit are much more up to date. <li>ID - Identitical matrix gives a score of 1.0 to two identical amino acids and a score of zero otherwise. </ul> <p> For DNA it is the scores assigned to matches and mismatches. The values available are: <ul> <li>IUB - The default scoring matrix used by BESTFIT for the comparison of nucleic acid sequences. All matches score 1.9; all mismatches for IUB symbols score 0. <li>ClustalW - The previous system used by Clustal W, in which matches score 1.0 and mismatches score 0. All matches for IUB symbols also score 0. </ul> Align with ClustalW An empty MSA has been supplied to ClustalW. Aligned %1 with ClustalW U2::LocalWorkflow::MAFFTPrompter from %1 Aligns each MSA supplied <u>%1</u> with <u>"MAFFT"</u>. U2::LocalWorkflow::MAFFTWorker Input MSA Multiple sequence alignment to be processed. Multiple sequence alignment Result of alignment. Gap Open Penalty Offset Works like gap extension penalty Max Iteration Maximum number of iterative refinement Максимальное число итераций Tool Path External tool path Temporary directory Directory for temporary files Align with MAFFT Выровнять с MAFFT An empty MSA has been supplied to MAFFT. Aligned %1 with MAFFT MAFFT is a multiple sequence alignment program for unix-like operating systems. <p><dfn>It offers a range of multiple alignment methods, L-INS-i (accurate; for alignment of &lt;&#126;200 sequences), FFT-NS-2 (fast; for alignment of &lt;&#126;10,000 sequences), etc. </dfn></p> U2::LocalWorkflow::TCoffeePrompter from %1 For each MSA<u>%1</u>, build the alignment using <u>"T-Coffee"</u> and send it to output. U2::LocalWorkflow::TCoffeeWorker Input MSA Multiple sequence alignment to be processed. Multiple sequence alignment Result of alignment. Gap Open Penalty Gap Open Penalty. Must be negative, best matches get a score of 1000. Gap Extension Penalty Gap Extension Penalty. Positive values give rewards to gaps and prevent the alignment of unrelated segments. Max Iteration Number of iteration on the progressive alignment<br>0 - no iteration, -1 - Nseq iterations Tool Path External tool path Temporary directory Directory for temporary files Align with T-Coffee Выровнять с T-Coffee T-Coffee is a multiple sequence alignment package. Empty msa supplied to tcoffee Aligned %1 with T-Coffee U2::MAFFTSupport <i>MAFFT</i> is a multiple sequence alignment program for unix-like operating systems. Path for %1 tool not selected. Do you want to select it now? U2::MAFFTSupportContext Align with MAFFT Выровнять с MAFFT Path for %1 tool not selected. Do you want to select it now? U2::MAFFTSupportTask Subdir for temporary files exists. Can not remove this directory. Can not create directory for temporary files. Не удаётся создать директорию для временных файлов. Can not get multiple alignment from temporary file. Can not remove directory for temporary files. U2::MAFFTWithExtFileSpecifySupportRunDialog Select input file Выберите входной файл U2::MAFFTWithExtFileSpecifySupportTask input_format_error Ошибка входного формата U2::PathLineEdit Select a file Выберите файл U2::SaveAlignmentTask Export alignment to '%1' U2::SaveMSA2SequencesTask Export alignment to sequence: %1 U2::SelectPathDialog Select a file Выберите файл Select a directory for tempory files Выберите директорию для временных файлов The directory %1 does not exist. Директория %1 не существует. Do you want to create this directory? Хотите ли вы содать эту директорию? Can not create directory for temporary files. Не удаётся создать директорию для временных файлов. Try choose another directory. Попробуйте выбрать другую директорию. U2::TCoffeeSupport <i>T-Coffee</i> is a multiple sequence alignment package. Path for %1 tool not selected. Do you want to select it now? U2::TCoffeeSupportContext Align with T-Coffee Выровнять с T-Coffee Path for %1 tool not selected. Do you want to select it now? U2::TCoffeeSupportTask Subdir for temporary files exists. Can not remove this directory. Can not create directory for temporary files. Не удаётся создать директорию для временных файлов. Can not remove directory for temporary files. U2::TCoffeeWithExtFileSpecifySupportRunDialog Select input file Выберите входной файл U2::TCoffeeWithExtFileSpecifySupportTask input_format_error Ошибка входного формата ugene-1.9.8/src/plugins/external_tool_support/transl/english.ts0000644000175000017500000024671211651544323023561 0ustar ilyailya BlastAllSupportDialog Request to local BLAST database General options Select search: blastn qwe blastp blastx tblastn tblastx Search for short, nearly exact matches Expectation value Megablast Max hits Off Select database path: ... Base name for BLAST DB files: Number of CPUs being used Advanced options Word size Gap costs Match scores 1 -3 1 -4 1 -2 1 -1 2 -7 2 -5 2 -3 4 -5 5 -4 Matrix BLOSUM62 BLOSUM45 BLOSUM80 PAM30 PAM70 Service plain psi phi PHI pattern Filters Low complexity filter Human repeats filter Masks Mask for lookup table only Mask lower case letters Restore to Default Search Cancel ClustalWSupportRunDialog Align with ClustalW Advanced options Gap opening penalty Gap extension penalty Weight matrix IUB CLUSTALW Max iterations TREE ALIGNMENT Iteration type Protein gap parameters Gap separation distance Residue-specific gaps off Hydrophilic gaps off No end gap separation penalty Align Cancel ETSSettingsWidget Resource settings Supported tools Name Path Additional information <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> <html><head><meta name="qrichtext" content="1" /><style type="text/css"> p, li { white-space: pre-wrap; } </style></head><body style=" font-family:'Sans Serif'; font-size:9pt; font-weight:400; font-style:normal;"> <table border="0" style="-qt-table-type: root; margin-top:4px; margin-bottom:4px; margin-left:4px; margin-right:4px;"> <tr> <td style="border: none;"> <p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Select an external tool to view more information about it.</p></td></tr></table></body></html> Binary path: Version info FormatDBSupportRunDialog Format database Input data Select input file(s) for formatting database: ... Or select directory with input files: File filter Include files filter *.fa;*.fasta Exclude files filter *.pal Type of file(s) protein nucleotide Output settings Select the path to save the database into: Base name for BLAST files: Title for database file: Format Cancel MAFFTSupportRunDialog Align with MAFFT Advanced options Gap opening penalty Offset (works like gap extension penalty) Maximum number of iterative refinement Align Cancel QObject Path for temporary files Path for temporary files not selected. Do you want to select it now? SelectPathDialog Path settings Select executable file of ... Select directory for tempory files: OK Cancel TCoffeeSupportRunDialog Align with T-Coffee Advanced options Gap opening penalty Gap extension penalty Number of iterations Align Cancel U2::BlastAllSupport The <i>blastall</i> is the old program developed and distributed by the NCBI for running BLAST searches. The NCBI recommends that people start using the programs of the BLAST+ package instead. Path for BLAST %1 tool not selected. Do you want to select it now? U2::BlastAllSupportContext Query with BLAST... Path for BLAST %1 tool not selected. Do you want to select it now? U2::BlastAllSupportMultiTask Source file Used databse No any results found U2::BlastAllSupportRunDialog Wrong parameters for creating annotations U2::BlastAllSupportTask Subdirectory for temporary files exists. Can not remove this directory. Can not create directory for temporary files. Can not remove directory for temporary files. U2::BlastAllWithExtFileSpecifySupportRunDialog Select input file Wrong input file This file not contain any sequence. Wrong parameters for creating annotations U2::BlastPlusSupport Path for BLAST+ tools not selected. Do you want to select it now? U2::BlastPlusSupportCommonTask Subdirectory for temporary files exists. Can not remove this directory. Can not create directory for temporary files. Can not remove directory for temporary files. U2::BlastPlusSupportContext Query with BLAST+... Path for BLAST+ tools not selected. Do you want to select it now? U2::BlastPlusSupportMultiTask Source file Used databse No any results found U2::BlastPlusSupportRunDialog Wrong parameters for creating annotations U2::BlastPlusWithExtFileSpecifySupportRunDialog Select input file Wrong input file This file not contain any sequence. Wrong parameters for creating annotations U2::BlastRunCommonDialog Select a directory with database files Direct nucleotide alignment Direct protein alignment Protein alignment, input nucleotide is translated input protein before the search Protein alignment, nucleotide database is translated input protein before the search Protein alignment, both input query and database are translated before the search U2::ClustalWSupport <i>ClustalW</i> is a free sequence alignment software for DNA or proteins. Path for %1 tool not selected. Do you want to select it now? U2::ClustalWSupportContext Align with ClustalW Path for %1 tool not selected. Do you want to select it now? U2::ClustalWSupportTask Subdirectory for temporary files exists. Can not remove this directory. Can not create directory for temporary files. Can not remove directory for temporary files. U2::ClustalWWithExtFileSpecifySupportRunDialog Select input file U2::ClustalWWithExtFileSpecifySupportTask input_format_error U2::ETSProjectViewItemsContoller FormatDB BLAST+ make DB BLAST Path for BLAST %1 tool not selected. Path for BLAST+ %1 tool not selected. Do you want to select it now? U2::ExternalToolRunTask Can not run %1 tool. U2::ExternalToolSupportPlugin External tool support Runs other external tools ClustalW MAFFT T-Coffee Multiple alignment FormatDB... BLAST+ make DB... BLAST Search... BLAST+ Search... BLAST U2::ExternalToolSupportService External tools support Provides support to run external tools from UGENE U2::ExternalToolSupportSettingsPageController External tools U2::ExternalToolSupportSettingsPageWidget BLAST BLAST+ <br>Version: <br>Binary path: Select an external tool to view more information about it. The <i>Basic Local Alignment Search Tool</i> (BLAST) finds regions of local similarity between sequences. The program compares nucleotide or protein sequences to sequence databases and calculates the statistical significance of matches. BLAST can be used to infer functional and evolutionary relationships between sequences as well as help identify members of gene families. <i>BLAST+</i> is a new version of the BLAST package from the NCBI. U2::ExternalToolValidateTask It is possible that the specified executable file for %1 tool is invalid. Tool does not start. It is possible that the specified executable file for %1 tool is invalid. Can not find expected message. U2::FormatDBSupport The <i>formatdb</i> formats protein or nucleotide source databases before these databases can be searched by <i>blastall</i>. The <i>makeblastdb</i> formats protein or nucleotide source databases before these databases can be searched by other BLAST+ tools. Path for BLAST %1 tool not selected. Path for BLAST+ %1 tool not selected. Do you want to select it now? U2::FormatDBSupportRunDialog Select file(s) Select a directory with input files Select a directory to save database files U2::FormatDBSupportTask Input files paths contain space characters. Output database path contain space characters. U2::LocalWorkflow::BlastAllPrompter from %1 For sequence <u>%1</u> find annotations in database <u>%2</u> U2::LocalWorkflow::BlastAllWorker Input sequence Sequence for which annotations is searched. Annotations Found annotations. Search type Select type of BLAST searches Database Path Path with database files Database Name Base name for BLAST DB files Expected value This setting specifies the statistical significance threshold for reporting matches against database sequences. Annotate as Name for annotations Tool Path External tool path Temporary directory Directory for temporary files Local BLAST search Finds annotations for DNA sequence in local database Empty sequence supplied to BLAST Selected BLAST search with nucleotide input sequence Selected BLAST search with amino acid input sequence U2::LocalWorkflow::BlastPlusPrompter from %1 For sequence <u>%1</u> find annotations in database <u>%2</u> U2::LocalWorkflow::BlastPlusWorker Input sequence Sequence for which annotations is searched. Annotations Found annotations. Search type Select type of BLAST+ searches Database Path Path with database files Database Name Base name for BLAST+ DB files Expected value This setting specifies the statistical significance threshold for reporting matches against database sequences. Annotate as Name for annotations Tool Path External tool path Temporary directory Directory for temporary files Local BLAST+ search Finds annotations for DNA sequence in local database Empty sequence supplied to BLAST Selected BLAST search with nucleotide input sequence Selected BLAST search with amino acid input sequence U2::LocalWorkflow::ClustalWPrompter from %1 Aligns each MSA supplied <u>%1</u> with "<u>ClustalW</u>". U2::LocalWorkflow::ClustalWWorker Input MSA Input MSA to process. ClustalW result MSA The result of the ClustalW alignment. Gap open penalty The penalty for opening a gap. Gap extension penalty The penalty for extending a gap. Gap distance The gap separation penalty. Tries to decrease the chances of gaps being too close to each other. End gaps The penalty for closing a gap. Residue-specific gaps off Residue-specific penalties are amino specific gap penalties that reduce or increase the gap opening penalties at each position in the alignment. Hydrophilic gaps off Hydrophilic gap penalties are used to increase the chances of a gap within a run (5 or more residues) of hydrophilic amino acids. Iteration type Number of iterations The maximum number of iterations to perform. Weight matrix Tool path Path to the ClustalW tool.<p>The default path can be set in the UGENE application settings. Directory to store temporary files. Aligns multiple sequence alignments (MSAs) supplied with ClustalW.<p>ClustalW is a general purpose multiple sequence alignment program for DNA or proteins.Visit <a href="http://www.clustal.org/">http://www.clustal.org/</a> to learn more about it. Temporary directory Alignment improvement iteration type. Can take values: <p> <ul> <li>None - No iteration;</li> <li>Tree - Iteration at each step of alignment process;</li> <li>Alignment - Iteation only on final alignment.</li> </ul> For proteins it is a scoring table which describes the similarity of each amino acid to each other and can take values: <p> <ul> <li>BLOSUM - Appear to be the best available for carrying out database similarity (homology searches). <li>PAM - Have been extremely widely used since the late '70s. <li>Gonnet - Derived using almost the same procedure as the PAM bit are much more up to date. <li>ID - Identitical matrix gives a score of 1.0 to two identical amino acids and a score of zero otherwise. </ul> <p> For DNA it is the scores assigned to matches and mismatches. The values available are: <ul> <li>IUB - The default scoring matrix used by BESTFIT for the comparison of nucleic acid sequences. All matches score 1.9; all mismatches for IUB symbols score 0. <li>ClustalW - The previous system used by Clustal W, in which matches score 1.0 and mismatches score 0. All matches for IUB symbols also score 0. </ul> Align with ClustalW An empty MSA has been supplied to ClustalW. Aligned %1 with ClustalW U2::LocalWorkflow::MAFFTPrompter from %1 Aligns each MSA supplied <u>%1</u> with <u>"MAFFT"</u>. U2::LocalWorkflow::MAFFTWorker Input MSA Multiple sequence alignment to be processed. Multiple sequence alignment Result of alignment. Gap Open Penalty Offset Works like gap extension penalty Max Iteration Maximum number of iterative refinement Tool Path External tool path Temporary directory Directory for temporary files Align with MAFFT An empty MSA has been supplied to MAFFT. Aligned %1 with MAFFT MAFFT is a multiple sequence alignment program for unix-like operating systems. <p><dfn>It offers a range of multiple alignment methods, L-INS-i (accurate; for alignment of &lt;&#126;200 sequences), FFT-NS-2 (fast; for alignment of &lt;&#126;10,000 sequences), etc. </dfn></p> U2::LocalWorkflow::TCoffeePrompter from %1 For each MSA<u>%1</u>, build the alignment using <u>"T-Coffee"</u> and send it to output. U2::LocalWorkflow::TCoffeeWorker Input MSA Multiple sequence alignment to be processed. Multiple sequence alignment Result of alignment. Gap Open Penalty Gap Open Penalty. Must be negative, best matches get a score of 1000. Gap Extension Penalty Gap Extension Penalty. Positive values give rewards to gaps and prevent the alignment of unrelated segments. Max Iteration Number of iteration on the progressive alignment<br>0 - no iteration, -1 - Nseq iterations Tool Path External tool path Temporary directory Directory for temporary files Align with T-Coffee T-Coffee is a multiple sequence alignment package. Empty msa supplied to tcoffee Aligned %1 with T-Coffee U2::MAFFTSupport <i>MAFFT</i> is a multiple sequence alignment program for unix-like operating systems. Path for %1 tool not selected. Do you want to select it now? U2::MAFFTSupportContext Align with MAFFT Path for %1 tool not selected. Do you want to select it now? U2::MAFFTSupportTask Subdir for temporary files exists. Can not remove this directory. Can not create directory for temporary files. Can not get multiple alignment from temporary file. Can not remove directory for temporary files. U2::MAFFTWithExtFileSpecifySupportRunDialog Select input file U2::MAFFTWithExtFileSpecifySupportTask input_format_error U2::PathLineEdit Select a file U2::SaveAlignmentTask Export alignment to '%1' U2::SaveMSA2SequencesTask Export alignment to sequence: %1 U2::SelectPathDialog Select a file Select a directory for tempory files The directory %1 does not exist. Do you want to create this directory? Can not create directory for temporary files. Try choose another directory. U2::TCoffeeSupport <i>T-Coffee</i> is a multiple sequence alignment package. Path for %1 tool not selected. Do you want to select it now? U2::TCoffeeSupportContext Align with T-Coffee Path for %1 tool not selected. Do you want to select it now? U2::TCoffeeSupportTask Subdir for temporary files exists. Can not remove this directory. Can not create directory for temporary files. Can not remove directory for temporary files. U2::TCoffeeWithExtFileSpecifySupportRunDialog Select input file U2::TCoffeeWithExtFileSpecifySupportTask input_format_error ugene-1.9.8/src/plugins/external_tool_support/external_tool_support.pro0000644000175000017500000001111611651544323025436 0ustar ilyailyainclude (external_tool_support.pri) # Input HEADERS += src/ETSProjectViewItemsContoller.h \ src/ExternalToolRunTask.h \ src/ExternalToolSupportPlugin.h \ src/ExternalToolSupportSettings.h \ src/ExternalToolSupportSettingsController.h \ src/TaskLocalStorage.h \ src/blast/BlastAllSupport.h \ src/blast/BlastAllSupportRunDialog.h \ src/blast/BlastAllSupportTask.h \ src/blast/BlastAllWorker.h \ src/blast/FormatDBSupport.h \ src/blast/FormatDBSupportRunDialog.h \ src/blast/FormatDBSupportTask.h \ src/blast_plus/BlastNPlusSupportTask.h \ src/blast_plus/BlastPlusSupport.h \ src/blast_plus/BlastPlusSupportCommonTask.h \ src/blast_plus/BlastPlusSupportRunDialog.h \ src/blast_plus/BlastPlusWorker.h \ src/blast_plus/BlastPPlusSupportTask.h \ src/blast_plus/BlastXPlusSupportTask.h \ src/blast_plus/RPSBlastSupportTask.h \ src/blast_plus/TBlastNPlusSupportTask.h \ src/blast_plus/TBlastXPlusSupportTask.h \ src/cap3/CAP3Support.h \ src/cap3/CAP3SupportDialog.h \ src/cap3/CAP3SupportTask.h \ src/cap3/CAP3Worker.h \ src/clustalw/ClustalWSupport.h \ src/clustalw/ClustalWSupportRunDialog.h \ src/clustalw/ClustalWSupportTask.h \ src/clustalw/ClustalWWorker.h \ src/mafft/MAFFTSupport.h \ src/mafft/MAFFTSupportRunDialog.h \ src/mafft/MAFFTSupportTask.h \ src/mafft/MAFFTWorker.h \ src/tcoffee/TCoffeeSupport.h \ src/tcoffee/TCoffeeSupportRunDialog.h \ src/tcoffee/TCoffeeSupportTask.h \ src/tcoffee/TCoffeeWorker.h \ src/utils/BlastRunCommonDialog.h \ src/utils/BlastTaskSettings.h \ src/utils/ExportTasks.h \ src/utils/ExternalToolSupportAction.h \ src/utils/ExternalToolValidateTask.h FORMS += src/ui/BlastAllSupportDialog.ui \ src/ui/CAP3SupportDialog.ui \ src/ui/ClustalWSupportRunDialog.ui \ src/ui/ETSSettingsWidget.ui \ src/ui/FormatDBSupportRunDialog.ui \ src/ui/MAFFTSupportRunDialog.ui \ src/ui/SelectPathDialog.ui \ src/ui/TCoffeeSupportRunDialog.ui SOURCES += src/ETSProjectViewItemsContoller.cpp \ src/ExternalToolRunTask.cpp \ src/ExternalToolSupportPlugin.cpp \ src/ExternalToolSupportSettings.cpp \ src/ExternalToolSupportSettingsController.cpp \ src/TaskLocalStorage.cpp \ src/blast/BlastAllSupport.cpp \ src/blast/BlastAllSupportRunDialog.cpp \ src/blast/BlastAllSupportTask.cpp \ src/blast/BlastAllWorker.cpp \ src/blast/FormatDBSupport.cpp \ src/blast/FormatDBSupportRunDialog.cpp \ src/blast/FormatDBSupportTask.cpp \ src/blast_plus/BlastNPlusSupportTask.cpp \ src/blast_plus/BlastPlusSupport.cpp \ src/blast_plus/BlastPlusSupportCommonTask.cpp \ src/blast_plus/BlastPlusSupportRunDialog.cpp \ src/blast_plus/BlastPlusWorker.cpp \ src/blast_plus/BlastPPlusSupportTask.cpp \ src/blast_plus/BlastXPlusSupportTask.cpp \ src/blast_plus/RPSBlastSupportTask.cpp \ src/blast_plus/TBlastNPlusSupportTask.cpp \ src/blast_plus/TBlastXPlusSupportTask.cpp \ src/cap3/CAP3Support.cpp \ src/cap3/CAP3SupportDialog.cpp \ src/cap3/CAP3SupportTask.cpp \ src/cap3/CAP3Worker.cpp \ src/clustalw/ClustalWSupport.cpp \ src/clustalw/ClustalWSupportRunDialog.cpp \ src/clustalw/ClustalWSupportTask.cpp \ src/clustalw/ClustalWWorker.cpp \ src/mafft/MAFFTSupport.cpp \ src/mafft/MAFFTSupportRunDialog.cpp \ src/mafft/MAFFTSupportTask.cpp \ src/mafft/MAFFTWorker.cpp \ src/tcoffee/TCoffeeSupport.cpp \ src/tcoffee/TCoffeeSupportRunDialog.cpp \ src/tcoffee/TCoffeeSupportTask.cpp \ src/tcoffee/TCoffeeWorker.cpp \ src/utils/BlastRunCommonDialog.cpp \ src/utils/BlastTaskSettings.cpp \ src/utils/ExportTasks.cpp \ src/utils/ExternalToolSupportAction.cpp \ src/utils/ExternalToolValidateTask.cpp RESOURCES += external_tool_support.qrc TRANSLATIONS += transl/english.ts transl/russian.ts ugene-1.9.8/src/plugins/assembly_browser/0000755000175000017500000000000011651544321017146 5ustar ilyailyaugene-1.9.8/src/plugins/assembly_browser/assembly_browser.pro0000644000175000017500000000272411651544321023257 0ustar ilyailyainclude (assembly_browser.pri) # Input HEADERS += src/AssemblyBrowser.h \ src/AssemblyBrowserPlugin.h \ src/AssemblyDensityGraph.h \ src/AssemblyReadsArea.h \ src/AssemblyReadsAreaHint.h \ src/AssemblyReferenceArea.h \ src/AssemblyCellRenderer.h \ src/AssemblyRuler.h \ src/ShortReadIterator.h \ src/AssemblyBrowserFactory.h \ src/AssemblyBrowserSettings.h \ src/BackgroundTaskRunner.h \ src/AssemblyModel.h \ src/ZoomableAssemblyOverview.h \ src/CoverageInfo.h \ src/CoveredRegionsManager.h \ src/ExportReadsDialog.h SOURCES += src/AssemblyBrowser.cpp \ src/AssemblyBrowserPlugin.cpp \ src/AssemblyDensityGraph.cpp \ src/AssemblyReadsArea.cpp \ src/AssemblyReadsAreaHint.cpp \ src/AssemblyReferenceArea.cpp \ src/AssemblyCellRenderer.cpp \ src/AssemblyRuler.cpp \ src/ShortReadIterator.cpp \ src/AssemblyBrowserFactory.cpp \ src/AssemblyBrowserSettings.cpp \ src/BackgroundTaskRunner.cpp \ src/AssemblyModel.cpp \ src/ZoomableAssemblyOverview.cpp \ src/CoverageInfo.cpp \ src/CoveredRegionsManager.cpp \ src/ExportReadsDialog.cpp FORMS += src/ui/ExportReadsDialog.ui TRANSLATIONS += transl/czech.ts transl/english.ts transl/russian.tsugene-1.9.8/src/plugins/assembly_browser/src/0000755000175000017500000000000011651544321017735 5ustar ilyailyaugene-1.9.8/src/plugins/assembly_browser/src/CoverageInfo.cpp0000644000175000017500000000725111651544321023015 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "CoverageInfo.h" #include #include "AssemblyModel.h" #include #include namespace U2 { CalcCoverageInfoTask::CalcCoverageInfoTask(const CalcCoverageInfoTaskSettings & settings_) : BackgroundTask("Calculate assembly coverage", TaskFlag_None), settings(settings_) { tpm = Progress_Manual; }; void CalcCoverageInfoTask::run() { U2AssemblyCoverageStat cachedCoverageStat; { cachedCoverageStat = settings.model->getCoverageStat(stateInfo); if(stateInfo.isCoR()) { return; } } qint64 modelLength = 0; { U2OpStatusImpl status; modelLength = settings.model->getModelLength(status); if(status.hasError()) { stateInfo.setError(status.getError()); return; } } double basesPerRegion = (double)settings.visibleRange.length/settings.regions; double coverageStatBasesPerRegion = (double)modelLength/cachedCoverageStat.coverage.size(); result.coverageInfo.resize(settings.regions); if(cachedCoverageStat.coverage.isEmpty() || (coverageStatBasesPerRegion > basesPerRegion)) { U2AssemblyCoverageStat coverageStat; coverageStat.coverage.resize(settings.regions); { settings.model->calculateCoverageStat(settings.visibleRange, coverageStat, stateInfo); if(stateInfo.isCoR()) { return; } } assert(coverageStat.coverage.size() == settings.regions); for(int regionIndex = 0;regionIndex < settings.regions;regionIndex++) { result.coverageInfo[regionIndex] = coverageStat.coverage[regionIndex].maxValue; } } else { for(int regionIndex = 0;regionIndex < settings.regions;regionIndex++) { int startPosition = qRound((settings.visibleRange.startPos + basesPerRegion*regionIndex)/coverageStatBasesPerRegion); int endPosition = qRound((settings.visibleRange.startPos + basesPerRegion*(regionIndex + 1))/coverageStatBasesPerRegion); result.coverageInfo[regionIndex] = 0; for(int i = startPosition;i < endPosition;i++) { result.coverageInfo[regionIndex] = std::max(result.coverageInfo[regionIndex], (qint64)cachedCoverageStat.coverage[i].maxValue); } } } { result.maxCoverage = 0; result.minCoverage = std::numeric_limits::max(); qint64 sum = 0; for(int regionIndex = 0;regionIndex < settings.regions;regionIndex++) { result.maxCoverage = std::max(result.maxCoverage, result.coverageInfo[regionIndex]); result.minCoverage = std::min(result.maxCoverage, result.coverageInfo[regionIndex]); sum += result.coverageInfo[regionIndex]; } result.averageCoverage = (double)sum/settings.regions; } } } ugene-1.9.8/src/plugins/assembly_browser/src/AssemblyReadsArea.h0000644000175000017500000001226111651544321023437 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef __ASSEMBLY_READS_AREA_H__ #define __ASSEMBLY_READS_AREA_H__ #include #include #include #include #include #include #include "AssemblyCellRenderer.h" #include "AssemblyReadsAreaHint.h" #include "AssemblyModel.h" namespace U2 { class AssemblyBrowser; class AssemblyBrowserUi; class AssemblyReadsArea; class AssemblyReadsArea: public QWidget { Q_OBJECT // (hotkey, description) pairs struct HotkeyDescription { QString key; QString desc; HotkeyDescription(const QString& k, const QString & d) : key(k), desc(d) {} }; static const QList HOTKEY_DESCRIPTIONS; static QList initHotkeyDescriptions(); public: AssemblyReadsArea(AssemblyBrowserUi * ui, QScrollBar * hBar, QScrollBar * vBar); protected: void paintEvent(QPaintEvent * e); void resizeEvent(QResizeEvent * e); void wheelEvent(QWheelEvent * e); void mousePressEvent(QMouseEvent * e); void mouseReleaseEvent(QMouseEvent * e); void mouseMoveEvent(QMouseEvent * e); void leaveEvent(QEvent * e); void hideEvent(QHideEvent * e); bool event(QEvent * e); void keyPressEvent(QKeyEvent * e); void mouseDoubleClickEvent(QMouseEvent * e); bool eventFilter(QObject *obj, QEvent *ev); private: void initRedraw(); void connectSlots(); void setupHScrollBar(); void setupVScrollBar(); void drawAll(); void drawWelcomeScreen(QPainter & p); void drawReads(QPainter & p); void drawHint(QPainter & p); int calcFontPointSize() const; bool findReadUnderMouse(U2AssemblyRead & read); void updateMenuActions(); void exportReads(const QList & reads); signals: void si_heightChanged(); void si_mouseMovedToPos(const QPoint &); public slots: void sl_hideHint(); void sl_redraw(); private slots: void sl_coveredRegionClicked(const QString & link); void sl_onHScrollMoved(int pos); void sl_onVScrollMoved(int pos); void sl_zoomOperationPerformed(); void sl_onCopyReadData(); void sl_onExportRead(); void sl_onExportReadsOnScreen(); private: AssemblyBrowserUi * ui; AssemblyBrowser * browser; QSharedPointer model; bool redraw; QPixmap cachedView; AssemblyCellRenderer cellRenderer; QLabel coveredRegionsLabel; QScrollBar * hBar; QScrollBar * vBar; // caches reads that are visible on a screen class ReadsCache { public: bool isEmpty() const { return data.isEmpty(); } void clear() { data.clear(); visibleBases = U2Region(); visibleRows = U2Region(); letterWidth = 0; xOffsetInAssembly = 0; yOffsetInAssembly = 0; } QList data; U2Region visibleBases; U2Region visibleRows; int letterWidth; qint64 xOffsetInAssembly; qint64 yOffsetInAssembly; }; ReadsCache cachedReads; QPoint curPos; struct HintData { HintData(QWidget * p) : redrawHint(false), hint(p) {} bool redrawHint; AssemblyReadsAreaHint hint; U2DataId curReadId; } hintData; // needed to move by-letter when scribbling class ReadsMover { public: ReadsMover() : cellWidth(0) {}; ReadsMover(int cellWidth_, QPoint initPos) : lastPos(initPos), cellWidth(cellWidth_ ? cellWidth_ : 1){} void handleEvent(QPoint newPos) { assert(cellWidth); QPoint diff_ = newPos - lastPos; lastPos = newPos; diff += diff_; } int getXunits() { assert(cellWidth); int result = diff.x() / cellWidth; diff.setX(diff.x() % cellWidth); return result; } int getYunits() { assert(cellWidth); int result = diff.y() / cellWidth; diff.setY(diff.y() % cellWidth); return result; } private: QPoint lastPos; QPoint diff; int cellWidth; } mover; bool scribbling; QMenu * readMenu; QAction * copyDataAction; QAction * exportReadAction; int currentHotkeyIndex; }; } //ns #endif ugene-1.9.8/src/plugins/assembly_browser/src/AssemblyBrowserPlugin.h0000644000175000017500000000213511651544321024411 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef __ASSEMBLY_BROWSER_PLUGIN__ #define __ASSEMBLY_BROWSER_PLUGIN__ #include namespace U2 { class AssemblyBrowserPlugin : public Plugin { Q_OBJECT public: AssemblyBrowserPlugin(); }; } #endif // __ASSEMBLY_BROWSER_PLUGIN__ ugene-1.9.8/src/plugins/assembly_browser/src/ExportReadsDialog.cpp0000644000175000017500000000506511651544321024027 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "ExportReadsDialog.h" #include #include #include #include #include namespace U2 { ExportReadsDialog::ExportReadsDialog(QWidget * p, const QList & formats) : QDialog(p) { setupUi(this); foreach(const DocumentFormatId & fid, formats) { documentFormatComboBox->addItem(fid, fid); DocumentFormat * df = AppContext::getDocumentFormatRegistry()->getFormatById(fid); assert(df != NULL); filter += QString("%1 - (*.%2);;").arg(fid).arg(df->getSupportedDocumentFileExtensions().first()); } connect(okPushButton, SIGNAL(clicked()), SLOT(accept())); connect(cancelPushButton, SIGNAL(clicked()), SLOT(reject())); connect(filepathToolButton, SIGNAL(clicked()), SLOT(sl_selectFile())); setMaximumHeight(layout()->minimumSize().height()); } void ExportReadsDialog::accept() { if(filepathLineEdit->text().isEmpty()) { QMessageBox::critical(this, tr("Error!"), tr("Select destination file")); filepathLineEdit->setFocus(Qt::OtherFocusReason); return; } QDialog::accept(); } void ExportReadsDialog::sl_selectFile() { LastOpenDirHelper lod("ExportReadsDialog"); lod.url = QFileDialog::getSaveFileName(this, tr("Select file to save"), lod, filter); if (lod.url.isEmpty()) { return; } filepathLineEdit->setText(lod.url); } ExportReadsDialogModel ExportReadsDialog::getModel() const { ExportReadsDialogModel ret; ret.filepath = filepathLineEdit->text(); ret.format = documentFormatComboBox->currentText(); ret.addToProject = addToProjectCheckBox->isChecked(); return ret; } } // U2 ugene-1.9.8/src/plugins/assembly_browser/src/BackgroundTaskRunner.h0000644000175000017500000000646111651544321024211 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef __BACKGROUND_TASK_RUNNER_H__ #define __BACKGROUND_TASK_RUNNER_H__ #include #include namespace U2 { /** * Simple template task which allows to grab its result. * Intended to be used as a base class for tasks for BackgroundTaskRunner. */ template class BackgroundTask : public Task { public: inline Result getResult() const {return result;}; protected: BackgroundTask(const QString& _name, TaskFlags f) : Task(_name, f){}; Result result; }; /** * Stub containing Q_OBJECT macro, signals&slots. Classes with signal/slot related * stuff can't be templates, so everything needed for BackgroundTaskRunner is moved here */ class BackgroundTaskRunner_base: public QObject { Q_OBJECT public: virtual ~BackgroundTaskRunner_base(); virtual void emitFinished(); signals: void si_finished(); private slots: virtual void sl_finished() = 0; }; /** * Simple manager for background tasks. * Allows running only one background task at a time, canceling previous task * when the new one is queued with run(). Emits si_finished() (defined in the base) * when the queued task is finished. Cancels current task in destructor. */ template class BackgroundTaskRunner : public BackgroundTaskRunner_base { public: BackgroundTaskRunner() : task(0) {} virtual ~BackgroundTaskRunner() { if(task) { task->cancel(); } } void run(BackgroundTask * newTask) { if(task) { task->cancel(); } task = newTask; connect(task, SIGNAL(si_stateChanged()), SLOT(sl_finished())); AppContext::getTaskScheduler()->registerTopLevelTask(task); } inline Result getResult() const { if(task) { return Result(); } return result; } inline bool isFinished() { return !task; } private: virtual void sl_finished() { BackgroundTask * senderr = dynamic_cast*>(sender()); assert(senderr); if(task != senderr) { return; } if(Task::State_Finished != senderr->getState()) { return; } result = task->getResult(); task = NULL; emitFinished(); } private: BackgroundTask * task; Result result; private: BackgroundTaskRunner(const BackgroundTaskRunner &); BackgroundTaskRunner operator=(const BackgroundTaskRunner &); }; } #endif ugene-1.9.8/src/plugins/assembly_browser/src/AssemblyModel.cpp0000644000175000017500000004203211651544321023202 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "AssemblyModel.h" #include "AssemblyBrowser.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include namespace U2 { //============================================================================== // AssemblyModel //============================================================================== AssemblyModel::AssemblyModel(const DbiHandle & dbiHandle_) : cachedModelLength(NO_VAL), cachedModelHeight(NO_VAL), referenceDbi(0), assemblyDbi(0), dbiHandle(dbiHandle_), refSeqDbiHandle(0), loadingReference(false), refDoc(0), md5Retrieved(false), cachedReadsNumber(NO_VAL), speciesRetrieved(false), uriRetrieved(false){ Project * prj = AppContext::getProject(); if(prj != NULL) { connect(prj, SIGNAL(si_documentRemoved(Document*)), SLOT(sl_referenceDocRemoved(Document*))); connect(prj, SIGNAL(si_documentAdded(Document*)), SLOT(sl_referenceDocAdded(Document*))); } } AssemblyModel::~AssemblyModel() { cleanup(); } void AssemblyModel::cleanup() { if(refSeqDbiHandle != NULL) { delete refSeqDbiHandle; refSeqDbiHandle = NULL; } referenceDbi = NULL; reference.length = 0; refDoc = NULL; } bool AssemblyModel::isEmpty() const { return assemblyDbi == NULL; } QList AssemblyModel::getReadsFromAssembly(const U2Region & r, qint64 minRow, qint64 maxRow, U2OpStatus & os) { std::auto_ptr< U2DbiIterator > it(assemblyDbi->getReadsByRow(assembly.id, r, minRow, maxRow, os)); return U2DbiUtils::toList(it.get()); } qint64 AssemblyModel::countReadsInAssembly(const U2Region & r, U2OpStatus & os) { return assemblyDbi->countReads(assembly.id, r, os); } void AssemblyModel::calculateCoverageStat(const U2Region & r, U2AssemblyCoverageStat & stat, U2OpStatus & os) { return assemblyDbi->calculateCoverage(assembly.id, r, stat, os); } const U2AssemblyCoverageStat &AssemblyModel::getCoverageStat(U2OpStatus & os) { QMutexLocker mutexLocker(&mutex); Q_UNUSED(mutexLocker); if(cachedCoverageStat.coverage.isEmpty()) { U2AttributeDbi * attributeDbi = dbiHandle.dbi->getAttributeDbi(); if(NULL != attributeDbi) { static const QByteArray COVERAGE_STAT_ATTRIBUTE_NAME("coverageStat"); QByteArray data = U2AttributeUtils::findByteArrayAttribute(attributeDbi, assembly.id, COVERAGE_STAT_ATTRIBUTE_NAME, QByteArray(), os); if(!os.isCoR()) { if(!data.isEmpty()) { if(0 == (data.size() % 4)) { for(int index = 0;index < data.size()/4;index++) { int value = 0; for(int i = 0;i < 4;i++) { value |= ((int)data[index*4 + i] & 0xff) << (i*8); } cachedCoverageStat.coverage.append(U2Range(value, value)); } } else { os.setError("Invalid attribute size"); } } else { qint64 length = getModelLength(os); if(!os.isCoR()) { static const qint64 MAX_COVERAGE_CACHE_SIZE = 1000*1000; int coverageCacheSize = (int)qMin(MAX_COVERAGE_CACHE_SIZE, length); cachedCoverageStat.coverage.resize(coverageCacheSize); calculateCoverageStat(U2Region(0, length), cachedCoverageStat, os); if(!os.isCoR()) { QByteArray data; for(int index = 0;index < cachedCoverageStat.coverage.size();index++) { for(int i = 0;i < 4;i++) { data.append((char)(cachedCoverageStat.coverage[index].maxValue >> (i*8))); } } U2ByteArrayAttribute attribute; attribute.objectId = assembly.id; attribute.name = COVERAGE_STAT_ATTRIBUTE_NAME; attribute.value = data; attribute.version = assembly.version; U2OpStatusImpl opStatus; attributeDbi->createByteArrayAttribute(attribute, opStatus); LOG_OP(opStatus); } } } } } else { os.setError("Attribute DBI is not supported"); } } return cachedCoverageStat; } U2Region AssemblyModel::getGlobalRegion() { U2OpStatusImpl os; return U2Region(0, getModelLength(os)); } qint64 AssemblyModel::getModelLength(U2OpStatus & os) { if(NO_VAL == cachedModelLength) { // try to set length from attributes U2AttributeDbi * attributeDbi = dbiHandle.dbi->getAttributeDbi(); U2OpStatusImpl status; static const QByteArray REFERENCE_ATTRIBUTE_NAME("reference_length_attribute"); if(attributeDbi != NULL) { cachedModelLength = U2AttributeUtils::findIntegerAttribute(attributeDbi, assembly.id, REFERENCE_ATTRIBUTE_NAME, NO_VAL, os); } // ignore incorrect attribute value if(cachedModelLength <= 0) { cachedModelLength = NO_VAL; coreLog.details(QString("ignored incorrect value of attribute %1: should be > 0, got %2").arg(QString(REFERENCE_ATTRIBUTE_NAME)).arg(cachedModelLength)); } // if cannot from attributes -> set from reference or max end pos if(cachedModelLength == NO_VAL) { qint64 refLen = hasReference() ? reference.length : 0; qint64 assLen = assemblyDbi->getMaxEndPos(assembly.id, status); LOG_OP(status); cachedModelLength = qMax(refLen, assLen); } } return cachedModelLength; } QByteArray AssemblyModel::getReferenceMd5(U2OpStatus& os) { if(!md5Retrieved) { md5Retrieved = true; U2AttributeDbi * attributeDbi = dbiHandle.dbi->getAttributeDbi(); static const QByteArray MD5_ATTRIBUTE_NAME("reference_md5_attribute"); if (attributeDbi != NULL) { referenceMd5 = U2AttributeUtils::findByteArrayAttribute(attributeDbi, assembly.id, MD5_ATTRIBUTE_NAME, QByteArray(), os); } } return referenceMd5; } qint64 AssemblyModel::getModelHeight(U2OpStatus & os) { if(NO_VAL == cachedModelHeight) { U2AttributeDbi * attributeDbi = dbiHandle.dbi->getAttributeDbi(); //U2OpStatusImpl os; static const QByteArray MAX_PROW_ATTRIBUTE_NAME("max_prow_attribute"); if(attributeDbi != NULL) { cachedModelHeight = U2AttributeUtils::findIntegerAttribute(attributeDbi, assembly.id, MAX_PROW_ATTRIBUTE_NAME, NO_VAL, os); } if(cachedModelHeight == NO_VAL) { LOG_OP(os); cachedModelHeight = assemblyDbi->getMaxPackedRow(assembly.id, U2Region(0, getModelLength(os)), os); } } return cachedModelHeight; } void AssemblyModel::setAssembly(U2AssemblyDbi * dbi, const U2Assembly & assm) { assert(dbi != NULL); assert(assemblyDbi == NULL); assemblyDbi = dbi; assembly = assm; // check if have reference if(!assembly.referenceId.isEmpty()) { // 1. get cross reference by ref id U2CrossDatabaseReferenceDbi * crossDbi = dbiHandle.dbi->getCrossDatabaseReferenceDbi(); U2OpStatusImpl status; U2CrossDatabaseReference crossRef = crossDbi->getCrossReference(assembly.referenceId, status); SAFE_POINT_OP(status,); // 2. find project and load reference doc to project Project * prj = AppContext::getProject(); SAFE_POINT(prj!=NULL, tr("No active project found!"), ); refDoc = prj->findDocumentByURL(crossRef.dataRef.dbiId); Task * t = NULL; if( refDoc != NULL ) { // document already in project, load if it is not loaded if(refDoc->isLoaded()) { sl_referenceLoaded(); } else { t = new LoadUnloadedDocumentTask(refDoc); } } else { // no document at project -> create doc, add it to project and load it t = createLoadReferenceAndAddtoProjectTask(crossRef); SAFE_POINT(t, "Failed to load reference sequence!",); } // 3. watch load-unload doc connect(refDoc, SIGNAL(si_loadedStateChanged()), SLOT(sl_referenceDocLoadedStateChanged())); // 4. run task and wait for finished in referenceLoaded() if(t != NULL) { startLoadReferenceTask(t); } } } Task * AssemblyModel::createLoadReferenceAndAddtoProjectTask(const U2CrossDatabaseReference& ref) { // hack: factoryId in FileDbi looks like FileDbi_formatId DocumentFormatId fid = ref.dataRef.factoryId.mid(ref.dataRef.factoryId.indexOf("_") + 1); DocumentFormat * df = AppContext::getDocumentFormatRegistry()->getFormatById(fid); SAFE_POINT(df, QString("Document format is not supported? %1").arg(fid), NULL); QString url = ref.dataRef.dbiId; IOAdapterId iofId = BaseIOAdapters::url2io(url); IOAdapterFactory * iof = AppContext::getIOAdapterRegistry()->getIOAdapterFactoryById(iofId); SAFE_POINT(iof, QString("IO-factory is unknown? %1, url: %2").arg(iofId).arg(url), NULL); refDoc = new Document(df, iof, url); Task * t = new LoadUnloadedDocumentTask(refDoc); t->addSubTask(new AddDocumentTask(refDoc)); t->setMaxParallelSubtasks(1); return t; } void AssemblyModel::startLoadReferenceTask(Task * t) { assert(t != NULL); TaskSignalMapper * tsm = new TaskSignalMapper(t); connect(tsm, SIGNAL(si_taskSucceeded(Task*)), SLOT(sl_referenceLoaded())); connect(tsm, SIGNAL(si_taskFailed(Task*)), SLOT(sl_referenceLoadingFailed())); loadingReference = true; emit si_referenceChanged(); AppContext::getTaskScheduler()->registerTopLevelTask(t); } void AssemblyModel::sl_referenceLoadingFailed() { loadingReference = false; emit si_referenceChanged(); // to update reference area } // when reference doc removed from project void AssemblyModel::sl_referenceDocRemoved(Document* d) { if(d != NULL && d == refDoc) { QMessageBox::StandardButtons fl = QMessageBox::Yes | QMessageBox::No; QMessageBox::StandardButton btn = QMessageBox::question(QApplication::activeWindow(), tr("Errors"), tr("Remove association with '%1' assembly").arg(assembly.visualName), fl, QMessageBox::Yes); if(btn == QMessageBox::Yes) { sl_unassociateReference(); } else { refDoc->disconnect(SIGNAL(si_loadedStateChanged())); cleanup(); emit si_referenceChanged(); } } } // when reference doc added to project void AssemblyModel::sl_referenceDocAdded(Document * d) { SAFE_POINT(d, "Reference document is NULL!", ); if(refDoc.isNull() && !assembly.referenceId.isEmpty()) { U2OpStatusImpl status; U2CrossDatabaseReference ref = dbiHandle.dbi->getCrossDatabaseReferenceDbi()->getCrossReference(assembly.referenceId, status); SAFE_POINT_OP(status,); if(ref.dataRef.dbiId == d->getURLString()) { if(!d->isLoaded()) { startLoadReferenceTask(new LoadUnloadedDocumentTask(refDoc = d)); } else { assert(false); } } } } // when load-unload document void AssemblyModel::sl_referenceDocLoadedStateChanged() { Document * doc = qobject_cast(sender()); SAFE_POINT(doc, "Reference document is NULL!", ); if(doc->isLoaded()) { if(!loadingReference) { refDoc = doc; sl_referenceLoaded(); } } else { // refDoc unloaded cleanup(); emit si_referenceChanged(); } } // document is loaded and in the project -> create dbi handle and set reference void AssemblyModel::sl_referenceLoaded() { U2OpStatusImpl status; U2CrossDatabaseReference ref = dbiHandle.dbi->getCrossDatabaseReferenceDbi()->getCrossReference(assembly.referenceId, status); cleanup(); refSeqDbiHandle = new DbiHandle(ref.dataRef.factoryId, ref.dataRef.dbiId, false, status); if(status.hasError()) { LOG_OP(status); sl_unassociateReference(); loadingReference = false; return; } U2SequenceDbi * seqDbi = refSeqDbiHandle->dbi->getSequenceDbi(); if(seqDbi != NULL) { U2Sequence refSeq = seqDbi->getSequenceObject(ref.dataRef.entityId, status); SAFE_POINT_OP(status,); setReference(seqDbi, refSeq); } else { assert(false); } loadingReference = false; } bool AssemblyModel::hasReference() const { return (bool)referenceDbi; } bool AssemblyModel::referenceAssociated() const { return !assembly.referenceId.isEmpty(); } void AssemblyModel::setReference(U2SequenceDbi * dbi, const U2Sequence & seq) { if(refDoc.isNull()) { Project * p = AppContext::getProject(); if(p != NULL) { refDoc = p->findDocumentByURL(seq.dbiId); } } reference = seq; referenceDbi = dbi; emit si_referenceChanged(); } QByteArray AssemblyModel::getReferenceRegion(const U2Region& region, U2OpStatus& os) { SAFE_POINT(!refDoc.isNull() && refDoc->isLoaded(), "Reference document is not ready!", QByteArray()); return referenceDbi->getSequenceData(reference.id, region, os); } void AssemblyModel::associateWithReference(const U2CrossDatabaseReference & ref) { assert(hasReference()); assert(assemblyDbi != NULL); // save cross reference id to assembly assembly.referenceId = ref.id; U2OpStatusImpl status; assemblyDbi->updateAssemblyObject(assembly, status); LOG_OP(status); } qint64 AssemblyModel::getReadsNumber(U2OpStatus & os) { if(cachedReadsNumber == NO_VAL) { U2AttributeDbi * attributeDbi = dbiHandle.dbi->getAttributeDbi(); //U2OpStatusImpl os; static const QByteArray READS_COUNT_ATTRIBUTE_NAME("count_reads_attribute"); if(attributeDbi != NULL) { cachedReadsNumber = U2AttributeUtils::findIntegerAttribute(attributeDbi, assembly.id, READS_COUNT_ATTRIBUTE_NAME, NO_VAL, os); } if(cachedReadsNumber == NO_VAL) { LOG_OP(os); cachedReadsNumber = assemblyDbi->countReads(assembly.id, U2_ASSEMBLY_REGION_MAX, os); } } return cachedReadsNumber; } bool AssemblyModel::hasReads(U2OpStatus & os) { return getReadsNumber(os) != 0; } QByteArray AssemblyModel::getReferenceSpecies(U2OpStatus & os) { if(!speciesRetrieved) { speciesRetrieved = true; U2AttributeDbi * attributeDbi = dbiHandle.dbi->getAttributeDbi(); static const QByteArray SPECIES_ATTRIBUTE_NAME("reference_species_attribute"); if (attributeDbi != NULL) { referenceSpecies = U2AttributeUtils::findByteArrayAttribute(attributeDbi, assembly.id, SPECIES_ATTRIBUTE_NAME, QByteArray(), os); } } return referenceSpecies; } QString AssemblyModel::getReferenceUri(U2OpStatus & os) { if(!uriRetrieved) { uriRetrieved = true; U2AttributeDbi * attributeDbi = dbiHandle.dbi->getAttributeDbi(); static const QByteArray URI_ATTRIBUTE_NAME("reference_uri_attribute"); if(attributeDbi != NULL) { referenceUri = U2AttributeUtils::findStringAttribute(attributeDbi, assembly.id, URI_ATTRIBUTE_NAME, QString(), os); } } return referenceUri; } void AssemblyModel::sl_unassociateReference() { if(!assembly.referenceId.isEmpty()) { assembly.referenceId.clear(); U2OpStatusImpl status; assemblyDbi->updateAssemblyObject(assembly, status); LOG_OP(status); cleanup(); emit si_referenceChanged(); } } } // U2 ugene-1.9.8/src/plugins/assembly_browser/src/AssemblyBrowserSettings.h0000644000175000017500000000253011651544321024752 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef __ASSEMBLY_BROWSER_SETTINGS_H__ #define __ASSEMBLY_BROWSER_SETTINGS_H__ namespace U2 { class AssemblyBrowserSettings { public: enum OverviewScaleType { Scale_Linear, Scale_Logarithmic }; static OverviewScaleType getOverviewScaleType(); static void setOverviewScaleType(OverviewScaleType t); static bool getShowCoordsOnRuler(); static void setShowCoordsOnRuler(bool what); }; // AssemblyBrowserSettings } // U2 #endif // __ASSEMBLY_BROWSER_SETTINGS_H__ ugene-1.9.8/src/plugins/assembly_browser/src/ExportReadsDialog.h0000644000175000017500000000300611651544321023465 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_EXPORT_READS_DIALOG_H__ #define _U2_EXPORT_READS_DIALOG_H__ #include #include #include namespace U2 { struct ExportReadsDialogModel { QString filepath; DocumentFormatId format; bool addToProject; }; class ExportReadsDialog : public QDialog, Ui_ExportReadsDialog { Q_OBJECT public: ExportReadsDialog(QWidget * p, const QList & formats); virtual void accept(); ExportReadsDialogModel getModel() const; private slots: void sl_selectFile(); private: QString filter; }; // ExportReadsDialog } // U2 #endif // _U2_EXPORT_READS_DIALOG_H__ ugene-1.9.8/src/plugins/assembly_browser/src/CoveredRegionsManager.h0000644000175000017500000000407711651544321024327 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef __COVERED_REGIONS_MANAGER_H__ #define __COVERED_REGIONS_MANAGER_H__ #include #include "CoverageInfo.h" namespace U2 { /** * Wrapper for region and its coverage. Here coverage is number of reads * intersecting the region. */ struct CoveredRegion { CoveredRegion(const U2Region & region_, qint64 coverage_) : region(region_), coverage(coverage_) {} U2Region region; qint64 coverage; }; /** * Simple holder of coverage information, provides methods to select well-covered regions. */ class CoveredRegionsManager { public: CoveredRegionsManager() {} CoveredRegionsManager(const U2Region & visibleRegion_, const QVector & coverageInfo_); inline bool isEmpty() const {return allRegions.empty();} inline int getSize() const { return allRegions.size(); } /** * Returns list of regions with coverage >= coverageLevel. */ QList getCoveredRegions(qint64 coverageLevel) const; /** * Returns topSize most covered regions with topSize >= coverageLevel. */ QList getTopCoveredRegions(int topSize, qint64 coverageLevel=0) const; private: U2Region visibleRegion; QList allRegions; }; } #endif ugene-1.9.8/src/plugins/assembly_browser/src/AssemblyBrowserPlugin.cpp0000644000175000017500000000261011651544321024742 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "AssemblyBrowserPlugin.h" #include #include "AssemblyBrowserFactory.h" namespace U2 { extern "C" Q_DECL_EXPORT Plugin* U2_PLUGIN_INIT_FUNC() { AssemblyBrowserPlugin * plug = new AssemblyBrowserPlugin(); return plug; } AssemblyBrowserPlugin::AssemblyBrowserPlugin() : Plugin(tr("Assembly Browser"), tr("Visualization of enormous genome assemblies.")) { if(AppContext::isGUIMode()) { AppContext::getObjectViewFactoryRegistry()->registerGObjectViewFactory(new AssemblyBrowserFactory(this)); } } } //ns ugene-1.9.8/src/plugins/assembly_browser/src/AssemblyReadsAreaHint.h0000644000175000017500000000317411651544321024265 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef __U2_ASSEMBLY_READS_AREA_HINT_H__ #define __U2_ASSEMBLY_READS_AREA_HINT_H__ #include #include #include namespace U2 { // hint that is shown under cursor for current read class AssemblyReadsAreaHint : public QFrame { Q_OBJECT public: static const QPoint OFFSET_FROM_CURSOR; static const int LETTER_MAX_COUNT = 60; static QString getReadDataAsString(const U2AssemblyRead & r); public: AssemblyReadsAreaHint(QWidget * p); void setData(const U2AssemblyRead& r); protected: bool eventFilter(QObject *, QEvent *); void leaveEvent(QEvent * e); void mouseMoveEvent(QMouseEvent * e); private: QLabel * label; }; // AssemblyReadsAreaHint } // U2 #endif // __U2_ASSEMBLY_READS_AREA_HINT_H__ ugene-1.9.8/src/plugins/assembly_browser/src/CoverageInfo.h0000644000175000017500000000327711651544321022466 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef __COVERAGE_INFO_H__ #define __COVERAGE_INFO_H__ #include #include #include #include "BackgroundTaskRunner.h" #include "AssemblyModel.h" namespace U2 { struct CoverageInfo { CoverageInfo() : averageCoverage(0.), maxCoverage(0), minCoverage(0) {} inline bool isEmpty() { return coverageInfo.empty(); } QVector coverageInfo; double averageCoverage; qint64 maxCoverage; qint64 minCoverage; }; struct CalcCoverageInfoTaskSettings { QSharedPointer model; U2Region visibleRange; int regions; }; class CalcCoverageInfoTask : public BackgroundTask { public: CalcCoverageInfoTask(const CalcCoverageInfoTaskSettings & settings); virtual void run(); private: CalcCoverageInfoTaskSettings settings; }; } #endif ugene-1.9.8/src/plugins/assembly_browser/src/ui/0000755000175000017500000000000011651544321020352 5ustar ilyailyaugene-1.9.8/src/plugins/assembly_browser/src/ui/ExportReadsDialog.ui0000644000175000017500000000470111651544321024273 0ustar ilyailya ExportReadsDialog 0 0 400 123 Export Reads Export to file ... File format Add to project true Qt::Horizontal 40 20 Export Cancel ugene-1.9.8/src/plugins/assembly_browser/src/AssemblyReadsAreaHint.cpp0000644000175000017500000001474711651544321024630 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "AssemblyReadsAreaHint.h" #include "AssemblyReadsArea.h" #include "ShortReadIterator.h" #include #include #include #include namespace U2 { const QPoint AssemblyReadsAreaHint::OFFSET_FROM_CURSOR(13, 13); static const int HINT_MAX_WIDTH = 200; AssemblyReadsAreaHint::AssemblyReadsAreaHint(QWidget * p): QFrame(p), label(new QLabel(this)) { QBoxLayout * top = new QVBoxLayout(this); top->setMargin(2); setLayout(top); top->addWidget(label); top->setSpacing(0); top->setSizeConstraint(QLayout::SetMinimumSize); setMaximumHeight(layout()->minimumSize().height()); setMaximumWidth(HINT_MAX_WIDTH); installEventFilter(this); label->installEventFilter(this); label->setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Minimum); { QPalette p(palette()); p.setColor(QPalette::Background, QColor(245, 245, 206)); setPalette(p); } // hack: tooltip do not works on linux, popup do not work on windows #ifdef Q_OS_WIN setWindowFlags(Qt::ToolTip); #else setWindowFlags(Qt::Popup); #endif setWindowOpacity(0.8); setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Minimum); setMouseTracking(true); setLineWidth(1); setFrameShape(QFrame::Box); } static QString getCigarString(const QString & ci) { if(ci.isEmpty()) { return AssemblyReadsAreaHint::tr("no information"); } QString cigar; for(int i = 0; i < ci.size(); ++i) { QChar ch = ci.at(i); if(ch.isNumber()) { cigar.append(ch); } else { cigar.append(QString("%1 ").arg(ch)); } } return cigar; } static const QString DIRECT_STR(AssemblyReadsAreaHint::tr("direct")); static const QString COMPL_STR(AssemblyReadsAreaHint::tr("complement")); QString getReadSequence(const QByteArray & bytes) { QString ret(bytes); if(ret.size() < AssemblyReadsAreaHint::LETTER_MAX_COUNT) { return ret; } return ret.mid(0, AssemblyReadsAreaHint::LETTER_MAX_COUNT) + "..."; } QString AssemblyReadsAreaHint::getReadDataAsString(const U2AssemblyRead & r) { QString ret; ret += QString("> %1\n").arg(QString(r->name)); ret += QString("%1\n\n").arg(QString(r->readSequence)); { qint64 len = U2AssemblyUtils::getEffectiveReadLength(r); ret += QString("From %1 to %2\n").arg(r->leftmostPos + 1).arg(r->leftmostPos + len); ret += QString("Length: %1\n").arg(len); ret += QString("Row: %1\n").arg(r->packedViewRow + 1); } ret += QString("Cigar: %1\n").arg(QString(U2AssemblyUtils::cigar2String(r->cigar))); { bool onCompl = ReadFlagsUtils::isComplementaryRead(r->flags); ret += QString("Strand: %1\n").arg(onCompl ? COMPL_STR : DIRECT_STR); } if(ReadFlagsUtils::isUnmappedRead(r->flags)) { ret += "Unmapped\n"; } return ret; } QString getReadNameWrapped(QString n) { QString ret; while(!n.isEmpty()) { n = n.trimmed(); if(n.size() > AssemblyReadsAreaHint::LETTER_MAX_COUNT) { QString sub = n.mid(0, AssemblyReadsAreaHint::LETTER_MAX_COUNT); int pos = sub.lastIndexOf(QRegExp("\\s+")); if(pos == -1) { pos = sub.size(); } ret += sub.mid(0, pos) + "
"; n = n.mid(pos); } else { ret += n; n.clear(); } } return ret; } void AssemblyReadsAreaHint::setData(const U2AssemblyRead& r) { QString text; text += ""; text += QString("").arg(getReadNameWrapped(r->name)); { qint64 len = U2AssemblyUtils::getEffectiveReadLength(r); text += QString(""). arg(r->leftmostPos + 1). arg(r->leftmostPos + len). arg(r->packedViewRow + 1); text += QString("").arg(len); } text += QString("").arg(getCigarString(U2AssemblyUtils::cigar2String(r->cigar))); { bool onCompl = ReadFlagsUtils::isComplementaryRead(r->flags); text += QString("").arg(onCompl ? COMPL_STR : DIRECT_STR); } text += QString("").arg(getReadSequence(r->readSequence)); if(ReadFlagsUtils::isUnmappedRead(r->flags)) { text += QString("").arg(tr("Unmapped")); } text += "
%1
From %1 to %2 Row: %3
Length: %1
Cigar: %1
Strand: %1
Read sequence: %1
%1
"; label->setText(text); setMaximumHeight(layout()->minimumSize().height()); } bool AssemblyReadsAreaHint::eventFilter(QObject *, QEvent * event) { QMouseEvent * e = dynamic_cast(event); if(e != NULL) { QWidget * p = qobject_cast(parent()); QMouseEvent eventToParent(e->type(), p->mapFromGlobal(QCursor::pos()), e->button(), e->buttons(), e->modifiers()); QApplication::sendEvent(p, &eventToParent); return true; } else { return false; } } void AssemblyReadsAreaHint::leaveEvent(QEvent *) { AssemblyReadsArea * p = qobject_cast(parent()); QPoint curInParentCoords = p->mapFromGlobal(QCursor::pos()); if(!p->rect().contains(curInParentCoords)) { p->sl_hideHint(); } } void AssemblyReadsAreaHint::mouseMoveEvent(QMouseEvent * e) { AssemblyReadsArea * p = qobject_cast(parent()); p->sl_hideHint(); QFrame::mouseMoveEvent(e); } } // U2 ugene-1.9.8/src/plugins/assembly_browser/src/BackgroundTaskRunner.cpp0000644000175000017500000000030411651544321024532 0ustar ilyailya#include "BackgroundTaskRunner.h" namespace U2 { BackgroundTaskRunner_base::~BackgroundTaskRunner_base() { } void BackgroundTaskRunner_base::emitFinished() { emit(si_finished()); } } //ns ugene-1.9.8/src/plugins/assembly_browser/src/AssemblyBrowserFactory.cpp0000644000175000017500000001433011651544321025115 0ustar ilyailya#include "AssemblyBrowserFactory.h" #include #include #include #include #include #include #include #include "AssemblyBrowser.h" namespace U2 { //============================================================================== // AssemblyBrowserFactory //============================================================================== const GObjectViewFactoryId AssemblyBrowserFactory::ID = "assembly-browser-factory"; AssemblyBrowserFactory::AssemblyBrowserFactory(QObject * parent /* = 0 */) : GObjectViewFactory(ID, tr("Assembly Browser"), parent) { } bool AssemblyBrowserFactory::canCreateView(const MultiGSelection & multiSelection) { bool hasAssembly = !SelectionUtils::findDocumentsWithObjects(GObjectTypes::ASSEMBLY, &multiSelection, UOF_LoadedAndUnloaded, true).isEmpty(); return hasAssembly; } #define MAX_VIEWS 5 void addAsmObjs(QList & asmObjs, const QList & docObjs) { foreach(GObject * go, docObjs) { if(!asmObjs.contains(go)) { asmObjs.append(go); } } } Task * AssemblyBrowserFactory::createViewTask(const MultiGSelection & multiSelection, bool single /* = false */) { QList asmObjects = SelectionUtils::findObjects(GObjectTypes::ASSEMBLY, &multiSelection, UOF_LoadedAndUnloaded); QSet docsWithAsm = SelectionUtils::findDocumentsWithObjects(GObjectTypes::ASSEMBLY, &multiSelection, UOF_LoadedAndUnloaded, false); QList resTasks; foreach(Document* doc, docsWithAsm) { QList docObjs = doc->findGObjectByType(GObjectTypes::ASSEMBLY, UOF_LoadedAndUnloaded); if (!docObjs.isEmpty()) { addAsmObjs(asmObjects, docObjs); } else { resTasks.append(new OpenAssemblyBrowserTask(doc)); if (resTasks.size() == MAX_VIEWS) { break; } } } if (!asmObjects.isEmpty()) { foreach(GObject* o, asmObjects) { if (resTasks.size() == MAX_VIEWS) { break; } if (o->getGObjectType() == GObjectTypes::UNLOADED) { resTasks.append(new OpenAssemblyBrowserTask(qobject_cast(o))); } else { SAFE_POINT(o->getGObjectType() == GObjectTypes::ASSEMBLY, "Invalid assembly object!", NULL); resTasks.append(new OpenAssemblyBrowserTask(qobject_cast(o))); } } } if (resTasks.isEmpty()) { return NULL; } if (resTasks.size() == 1 || single) { return resTasks.first(); } Task* result = new Task(tr("Open multiple views"), TaskFlag_NoRun); foreach(Task* t, resTasks) { result->addSubTask(t); } return result; } //============================================================================== // OpenAssemblyBrowserTask //============================================================================== OpenAssemblyBrowserTask::OpenAssemblyBrowserTask(AssemblyObject * obj) : ObjectViewTask(AssemblyBrowserFactory::ID) { selectedObjects.append(obj); } OpenAssemblyBrowserTask::OpenAssemblyBrowserTask(UnloadedObject * unloadedObj) : ObjectViewTask(AssemblyBrowserFactory::ID), unloadedObjRef(unloadedObj) { documentsToLoad.append(unloadedObj->getDocument()); } OpenAssemblyBrowserTask::OpenAssemblyBrowserTask(Document * doc) : ObjectViewTask(AssemblyBrowserFactory::ID) { assert(!doc->isLoaded()); documentsToLoad.append(doc); } void OpenAssemblyBrowserTask::open() { if (stateInfo.hasError() || (documentsToLoad.isEmpty() && selectedObjects.isEmpty())) { return; } if (selectedObjects.isEmpty()) { assert(1 == documentsToLoad.size()); Document* doc = documentsToLoad.first(); QList objects; if (unloadedObjRef.isValid()) { GObject* obj = doc->findGObjectByName(unloadedObjRef.objName); if (obj!=NULL && obj->getGObjectType() == GObjectTypes::ASSEMBLY) { selectedObjects.append(qobject_cast(obj)); } } else { QList objects = doc->findGObjectByType(GObjectTypes::ASSEMBLY, UOF_LoadedAndUnloaded); if(!objects.isEmpty()) { selectedObjects.append(qobject_cast(objects.first())); } } if (selectedObjects.isEmpty()) { stateInfo.setError(tr("Assembly object not found")); return; } } foreach(QPointer po, selectedObjects) { AssemblyObject* o = qobject_cast(po); SAFE_POINT(o, "Invalid assembly object!", ); viewName = GObjectViewUtils::genUniqueViewName(o->getDocument(), o); AssemblyBrowser * v = new AssemblyBrowser(o); // before opening view, check for incorrect reference length attribute U2OpStatusImpl status; qint64 modelLen = v->getModel()->getModelLength(status); if(status.hasError()) { LOG_OP(status); AppContext::getMainWindow()->getNotificationStack()->addError(status.getError()); delete v; continue; } if(modelLen <= 0) { QString message = tr("Cannot open assembly browser for %1: model length should be > 0").arg(o->getDocument()->getURLString()); coreLog.error(message); AppContext::getMainWindow()->getNotificationStack()->addError(message); delete v; continue; } GObjectViewWindow* w = new GObjectViewWindow(v, viewName, false); AppContext::getMainWindow()->getMDIManager()->addMDIWindow(w); } } void OpenAssemblyBrowserTask::updateTitle(AssemblyBrowser* ab) { const QString& oldViewName = ab->getName(); GObjectViewWindow* w = GObjectViewUtils::findViewByName(oldViewName); if (w != NULL) { AssemblyObject* aObj = ab->getAssemblyObject(); QString newViewName = GObjectViewUtils::genUniqueViewName(aObj->getDocument(), aObj); ab->setName(newViewName); w->setWindowTitle(newViewName); } } } //ns ugene-1.9.8/src/plugins/assembly_browser/src/AssemblyCellRenderer.cpp0000644000175000017500000000624711651544321024520 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "AssemblyCellRenderer.h" #include #include #include namespace U2 { namespace { QMap initDefaultColorSheme() { QMap colors; //TODO other chars ?? //TODO = symbol colors['a'] = QColor("#FCFF92"); colors['c'] = QColor("#70F970"); colors['g'] = QColor("#4EADE1"); colors['t'] = QColor("#FF99B1"); colors['A'] = QColor("#FCFF92"); colors['C'] = QColor("#70F970"); colors['G'] = QColor("#4EADE1"); colors['T'] = QColor("#FF99B1"); colors['-'] = QColor("#FBFBFB"); colors['N'] = QColor("#FBFBFB"); return colors; } } const QMap defaultColorScheme = initDefaultColorSheme(); AssemblyCellRenderer::AssemblyCellRenderer(const QMap & colorScheme_) : colorScheme(colorScheme_), cachedTextFlag(false) { } QVector AssemblyCellRenderer::render(const QSize & size, bool text /*= false*/, const QFont & font /*= QFont()*/) { GTIMER(c1, t1, "AssemblyCellRenderer::render"); if(images.empty() || (cachedSize != size || cachedTextFlag != text)) { drawCells(size, font, text); } return images; } void AssemblyCellRenderer::drawCells(const QSize & size, const QFont & font, bool text) { images = QVector(256, QImage(size, QImage::Format_RGB32)); foreach(char c, colorScheme.keys()) { drawCell(c, colorScheme.value(c)); if(text) { drawText(c, font); } } } void AssemblyCellRenderer::drawText(char c, const QFont & f) { QImage & result = images[c]; QPainter p(&result); p.setFont(f); if('-' == c || 'N' == c) { //TODO : get rid of hardcoded values! p.setPen(Qt::red); } p.drawText(result.rect(), Qt::AlignCenter, QString(c)); } void AssemblyCellRenderer::drawCell(char c, const QColor & color) { QImage & result = images[c]; QPainter p(&result); //TODO invent something greater QLinearGradient linearGrad(QPointF(0, 0), QPointF(result.width(), result.height())); linearGrad.setColorAt(0, QColor::fromRgb(color.red()-70,color.green()-70,color.blue()-70)); linearGrad.setColorAt(1, color); QBrush br(linearGrad); QRect imgRect(0, 0, result.width(), result.height()); p.fillRect(imgRect, br); } } //ns ugene-1.9.8/src/plugins/assembly_browser/src/AssemblyBrowserSettings.cpp0000644000175000017500000000344011651544321025306 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "AssemblyBrowserSettings.h" #include #include #include namespace U2 { static const QString SETTINGS_PREFIX("assembly_browser/"); static const QString SCALE_TYPE(SETTINGS_PREFIX + "scale_type"); static const QString SHOW_RULER_COORDS(SETTINGS_PREFIX + "show_coords_on_ruler"); AssemblyBrowserSettings::OverviewScaleType AssemblyBrowserSettings::getOverviewScaleType() { return OverviewScaleType(AppContext::getSettings()->getValue(SCALE_TYPE, Scale_Linear).value()); } void AssemblyBrowserSettings::setOverviewScaleType(OverviewScaleType t) { AppContext::getSettings()->setValue(SCALE_TYPE, t); } bool AssemblyBrowserSettings::getShowCoordsOnRuler() { return AppContext::getSettings()->getValue(SHOW_RULER_COORDS, true).value(); } void AssemblyBrowserSettings::setShowCoordsOnRuler(bool what) { AppContext::getSettings()->setValue(SHOW_RULER_COORDS, what); } } // U2 ugene-1.9.8/src/plugins/assembly_browser/src/ZoomableAssemblyOverview.h0000644000175000017500000001021611651544321025105 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef __ZOOMABLE_ASSEMBLY_OVERVIEW_H__ #define __ZOOMABLE_ASSEMBLY_OVERVIEW_H__ #include #include #include #include "AssemblyBrowserSettings.h" #include "CoverageInfo.h" #include "BackgroundTaskRunner.h" class QMenu; namespace U2 { class AssemblyModel; class AssemblyBrowserUi; class AssemblyBrowser; class ZoomableAssemblyOverview: public QWidget { Q_OBJECT public: ZoomableAssemblyOverview(AssemblyBrowserUi * ui, bool zoomable = false); void setScaleType(AssemblyBrowserSettings::OverviewScaleType t); AssemblyBrowserSettings::OverviewScaleType getScaleType()const; void checkedSetVisibleRange(qint64 newStartPos, qint64 newLen); void checkedSetVisibleRange(const U2Region & newRegion); inline U2Region getVisibleRange() const {return visibleRange;} signals: void si_visibleRangeChanged(const U2Region &); void si_coverageReady(); protected: void paintEvent(QPaintEvent * e); void resizeEvent(QResizeEvent * e); void mousePressEvent(QMouseEvent * me); void mouseMoveEvent(QMouseEvent * me); void mouseReleaseEvent(QMouseEvent * me); void wheelEvent(QWheelEvent * e); void contextMenuEvent(QContextMenuEvent * e); private slots: void sl_visibleAreaChanged(); void sl_redraw(); void sl_zoomIn(const QPoint & pos); void sl_zoomOut(const QPoint & pos); void sl_zoomInContextMenu(); void sl_zoomOutContextMenu(); void sl_zoom100xContextMenu(); void sl_restoreGlobalOverview(); private: qint64 calcXAssemblyCoord(int x) const; qint64 calcYAssemblyCoord(int y) const; QRect calcCurrentSelection() const; U2Region calcVisibleAssemblyRange() const; void moveSelectionToPos(QPoint pos, bool moveModel = true); void zoomToPixRange(int x_pix_start, int x_pix_end); void checkedMoveVisibleRange(qint64 newStartPos); qint64 minimalOverviewedLen() const; bool canZoomToRange(const U2Region & range) const; void setupActions(); void updateActions(); void connectSlots(); void initSelectionRedraw(); void drawAll(); void drawBackground(QPainter & p); void drawSelection(QPainter & p); void drawCoordLabels(QPainter & p); void drawZoomToRegion(QPainter & p); void launchCoverageCalculation(); private: AssemblyBrowserUi * ui; AssemblyBrowser * browser; QSharedPointer model; QMenu * contextMenu; QPoint contextMenuPos; //context menu actions QAction * zoomInAction; QAction * zoomOutAction; QAction * zoomIn100xActon; QAction * restoreGlobalOverviewAction; bool zoomable; U2Region visibleRange; double zoomFactor; QRect cachedSelection; QPixmap cachedView; bool redrawSelection; QPixmap cachedBackground; bool redrawBackground; BackgroundTaskRunner coverageTaskRunner; bool selectionScribbling; QPoint selectionDiff; bool visibleRangeScribbling; QPoint visibleRangeLastPos; AssemblyBrowserSettings::OverviewScaleType scaleType; struct ZoomToRegionSelector { ZoomToRegionSelector() : scribbling(false) {} bool scribbling; QPoint startPos; } zoomToRegionSelector; const static int FIXED_HEIGHT = 70; const static double ZOOM_MULT; }; } //ns #endif ugene-1.9.8/src/plugins/assembly_browser/src/AssemblyBrowser.h0000644000175000017500000001405511651544321023236 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef __ASSEMBLY_BROWSER_H__ #define __ASSEMBLY_BROWSER_H__ #include #include #include #include #include #include #include #include #include #include #include "AssemblyModel.h" #include "CoveredRegionsManager.h" namespace U2 { class AssemblyBrowserUi; class PositionSelector; class AssemblyBrowser : public GObjectView { Q_OBJECT public: AssemblyBrowser(AssemblyObject * o); // from GObjectView virtual void buildStaticToolbar(QToolBar* tb); virtual void buildStaticMenu(QMenu* m); void setGlobalCoverageInfo(const CoverageInfo & info); QList getCoveredRegions() const; inline bool areCoveredRegionsReady() const {return coverageReady;} // asm coords <-> pix coords functions qint64 calcPixelCoord(qint64 asmCoord) const; qint64 calcAsmCoordX(qint64 pixCoord) const; qint64 calcAsmCoordY(qint64 pixCoord) const; qint64 calcAsmPosX(qint64 pixPosX) const; qint64 calcAsmPosY(qint64 pixPosY) const; qint64 calcPainterOffset(qint64 xAsmCoord) const; // cells utility functions int getCellWidth() const; qint64 basesCanBeVisible() const; qint64 rowsCanBeVisible() const; qint64 basesVisible() const; qint64 rowsVisible() const; bool areReadsVisible() const; bool areCellsVisible() const; bool areLettersVisible() const; // offsets in assembly inline qint64 getXOffsetInAssembly() const {return xOffsetInAssembly; } inline qint64 getYOffsetInAssembly() const {return yOffsetInAssembly; } void setXOffsetInAssembly(qint64 x); void setYOffsetInAssembly(qint64 y); void setOffsetsInAssembly(qint64 x, qint64 y); qint64 normalizeXoffset(qint64 x)const; qint64 normalizeYoffset(qint64 y)const; void adjustOffsets(qint64 dx, qint64 dy); void navigateToRegion(const U2Region & region); // other inline QSharedPointer getModel() const {return model;} inline QFont getFont() const {return font;} void setFocusToPosSelector(); AssemblyObject* getAssemblyObject() const {return gobject;} public slots: void sl_zoomIn(const QPoint & pos = QPoint()); void sl_zoomOut(const QPoint & pos = QPoint()); void sl_zoomToReads(); signals: void si_offsetsChanged(); void si_zoomOperationPerformed(); protected: virtual QWidget * createWidget(); virtual bool eventFilter(QObject*, QEvent*); virtual void onObjectRenamed(GObject* obj, const QString& oldName); private slots: void sl_assemblyLoaded(); void sl_onPosChangeRequest(int); void sl_changeOverviewType(); void sl_onShowCoordsOnRulerChanged(); void sl_saveScreenshot(); void sl_showContigInfo(); void sl_exportToSam(); private: void initFont(); void setupActions(); void updateOverviewTypeActions(); void clear(); // returns error string QString tryAddObject(GObject * obj); // utility functions for zooming bool canPerformZoomIn() const {return zoomInAction->isEnabled();} bool canPerformZoomOut() const {return zoomOutAction->isEnabled();} int zoomInFromSize(int oldCellSize); int zoomOutFromSize(int oldCellSize); void updateZoomingActions(); private: AssemblyBrowserUi * ui; AssemblyObject * gobject; U2OpStatusImpl dbiOpStatus; QSharedPointer model; double zoomFactor; QFont font; qint64 xOffsetInAssembly; qint64 yOffsetInAssembly; CoverageInfo coverageInfo; CoveredRegionsManager coveredRegionsManager; bool coverageReady; QAction * zoomInAction; QAction * zoomOutAction; QAction * posSelectorAction; PositionSelector * posSelector; QList overviewScaleTypeActions; QAction * showCoordsOnRulerAction; QAction * saveScreenShotAction; QAction * showInfoAction; QAction * exportToSamAction; const static int MAX_CELL_WIDTH = 300; const static double INITIAL_ZOOM_FACTOR; const static double ZOOM_MULT; const static int LETTER_VISIBLE_WIDTH = 7; const static int CELL_VISIBLE_WIDTH = 1; }; class AssemblyOverview; class ZoomableAssemblyOverview; class AssemblyReferenceArea; class AssemblyDensityGraph; class AssemblyRuler; class AssemblyReadsArea; class AssemblyBrowserUi : public QWidget { Q_OBJECT public: AssemblyBrowserUi(AssemblyBrowser * browser); inline QSharedPointer getModel() const {return browser->getModel();} inline AssemblyBrowser * getWindow() const {return browser;} inline AssemblyReadsArea * getReadsArea() const {return readsArea;} inline ZoomableAssemblyOverview * getOverview() const {return zoomableOverview;} inline AssemblyRuler * getRuler() const {return ruler;} inline AssemblyReferenceArea * getReferenceArea() const {return referenceArea;} private: AssemblyBrowser * browser; ZoomableAssemblyOverview * zoomableOverview; AssemblyReferenceArea * referenceArea; AssemblyDensityGraph * densityGraph; AssemblyRuler * ruler; AssemblyReadsArea * readsArea; }; } //ns #endif ugene-1.9.8/src/plugins/assembly_browser/src/AssemblyReferenceArea.h0000644000175000017500000000363211651544321024301 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef __ASSEMBLY_REFERENCE_AREA_H__ #define __ASSEMBLY_REFERENCE_AREA_H__ #include #include #include #include "AssemblyCellRenderer.h" #include "AssemblyModel.h" namespace U2 { class AssemblyBrowserUi; class AssemblyBrowser; class AssemblyReferenceArea: public QWidget { Q_OBJECT public: AssemblyReferenceArea(AssemblyBrowserUi * ui); protected: void paintEvent(QPaintEvent * e); void resizeEvent(QResizeEvent * e); void mouseMoveEvent(QMouseEvent * e); void mousePressEvent(QMouseEvent* e); signals: void si_mouseMovedToPos(const QPoint &); void si_unassociateReference(); private slots: void sl_redraw(); private: void connectSlots(); void drawAll(); void drawReference(QPainter & p); private: AssemblyBrowserUi * ui; AssemblyBrowser * browser; QSharedPointer model; QPixmap cachedView; bool redraw; AssemblyCellRenderer cellRenderer; const static int FIXED_HEIGHT = 25; QMenu * referenceAreaMenu; }; } //ns #endif ugene-1.9.8/src/plugins/assembly_browser/src/AssemblyRuler.h0000644000175000017500000000420211651544321022675 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef __ASSEMBLY_RULER__ #define __ASSEMBLY_RULER__ #include #include #include "AssemblyModel.h" namespace U2 { class AssemblyBrowserUi; class AssemblyBrowser; /** * Ruler widget provides auto-adjustable scale, labeled notches and a * mouse-tracking cursor showing the current coordinate in assembly. */ class AssemblyRuler : public QWidget { Q_OBJECT public: AssemblyRuler(AssemblyBrowserUi * ui); void setShowCoordsOnRuler(bool showCoords); bool getShowCoordsOnRuler()const; protected: void paintEvent(QPaintEvent * e); void resizeEvent(QResizeEvent * e); void mouseMoveEvent(QMouseEvent * e); public slots: void sl_handleMoveToPos(const QPoint &); private slots: void sl_redraw(); private: void connectSlots(); void drawAll(); void drawRuler(QPainter & p); void drawCursor(QPainter & p); private: AssemblyBrowserUi * ui; AssemblyBrowser * browser; QSharedPointer model; bool redraw; QPixmap cachedView; int cursorPos; //x-coord of the cursor on the widget //cached ruler labels. Rendered once in paintEvent, //used on each cursor redraw QList cachedLabelsRects; QList cachedLabels; bool showCoords; }; } //ns #endif ugene-1.9.8/src/plugins/assembly_browser/src/AssemblyModel.h0000644000175000017500000000721611651544321022654 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef __U2_ASSEMBLY_BROWSER_MODEL_H__ #define __U2_ASSEMBLY_BROWSER_MODEL_H__ #include #include #include #include namespace U2 { class Document; class AssemblyModel : public QObject { Q_OBJECT public: //TODO refactor AssemblyModel(const DbiHandle & dbiHandle); ~AssemblyModel(); bool isEmpty() const; QList getReadsFromAssembly(const U2Region & r, qint64 minRow, qint64 maxRow, U2OpStatus & os); qint64 countReadsInAssembly(const U2Region & r, U2OpStatus & os); void calculateCoverageStat(const U2Region & r, U2AssemblyCoverageStat & stat, U2OpStatus & os); const U2AssemblyCoverageStat &getCoverageStat(U2OpStatus & os); U2Region getGlobalRegion(); qint64 getModelLength(U2OpStatus & os); QByteArray getReferenceMd5(U2OpStatus & os); QByteArray getReferenceSpecies(U2OpStatus & os); QString getReferenceUri(U2OpStatus & os); qint64 getModelHeight(U2OpStatus & os); void setAssembly(U2AssemblyDbi * dbi, const U2Assembly & assm); bool hasReference() const; bool referenceAssociated()const; void setReference(U2SequenceDbi * dbi, const U2Sequence & seq); QByteArray getReferenceRegion(const U2Region& region, U2OpStatus& os); const DbiHandle & getDbiHandle() const {return dbiHandle;} void associateWithReference(const U2CrossDatabaseReference & ref); bool isLoadingReference()const { return loadingReference; } qint64 getReadsNumber(U2OpStatus & os); bool hasReads(U2OpStatus & os); private: void cleanup(); void startLoadReferenceTask(Task * t); Task * createLoadReferenceAndAddtoProjectTask(const U2CrossDatabaseReference& ref); signals: void si_referenceChanged(); private slots: void sl_referenceLoaded(); void sl_referenceLoadingFailed(); void sl_referenceDocLoadedStateChanged(); void sl_referenceDocRemoved(Document*); void sl_referenceDocAdded(Document *); void sl_unassociateReference(); private: const static qint64 NO_VAL = -1; //TODO: track model changes and invalidate caches accordingly qint64 cachedModelLength; qint64 cachedModelHeight; U2Sequence reference; U2SequenceDbi * referenceDbi; U2Assembly assembly; U2AssemblyDbi * assemblyDbi; DbiHandle dbiHandle; DbiHandle * refSeqDbiHandle; bool loadingReference; QPointer refDoc; QByteArray referenceMd5; bool md5Retrieved; qint64 cachedReadsNumber; QByteArray referenceSpecies; bool speciesRetrieved; QString referenceUri; bool uriRetrieved; U2AssemblyCoverageStat cachedCoverageStat; QMutex mutex; }; // AssemblyModel } // U2 #endif // __U2_ASSEMBLY_BROWSER_MODEL_H__ ugene-1.9.8/src/plugins/assembly_browser/src/AssemblyRuler.cpp0000644000175000017500000002020711651544321023233 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "AssemblyRuler.h" #include #include #include #include #include #include "AssemblyBrowser.h" #include "AssemblyReadsArea.h" //TODO get rid of cross-widget dependencies ? #include "AssemblyBrowserSettings.h" namespace U2 { static const int FIXED_HEIGHT = 36; static const int AXIS_LINE_Y = 6; //see drawRuler() for details about short/long/border notches //these are Y coords of all of the notches static const int BORDER_NOTCH_START = 2; static const int BORDER_NOTCH_END = 20; static const int SHORT_NOTCH_START = 5; static const int SHORT_NOTCH_END = 10; static const int LONG_NOTCH_START = 3; static const int LONG_NOTCH_END = 18; static const int LABELS_END = LONG_NOTCH_END + 2; AssemblyRuler::AssemblyRuler(AssemblyBrowserUi * ui_) : QWidget(ui_), ui(ui_), browser(ui->getWindow()), model(ui->getModel()), cursorPos(0), showCoords(AssemblyBrowserSettings::getShowCoordsOnRuler()) { setFixedHeight(FIXED_HEIGHT); connectSlots(); sl_redraw(); setMouseTracking(true); } void AssemblyRuler::connectSlots() { connect(browser, SIGNAL(si_zoomOperationPerformed()), SLOT(sl_redraw())); connect(browser, SIGNAL(si_offsetsChanged()), SLOT(sl_redraw())); } void AssemblyRuler::drawAll() { if(!model->isEmpty()) { if (redraw) { cachedView.fill(Qt::transparent); QPainter p(&cachedView); redraw = false; drawRuler(p); } QPixmap cachedViewCopy(cachedView); { QPainter p(&cachedViewCopy); drawCursor(p); } QPainter p(this); p.drawPixmap(0, 0, cachedViewCopy); } } namespace { int numOfDigits(qint64 n) { assert(n >= 0); return QString::number(n).length(); } } void AssemblyRuler::drawCursor(QPainter & p) { //1. draw the cursor itself p.setPen(Qt::darkRed); p.drawLine(cursorPos, BORDER_NOTCH_START, cursorPos, BORDER_NOTCH_END); p.drawLine(cursorPos+1, BORDER_NOTCH_START, cursorPos+1, BORDER_NOTCH_END); //2. extract coverage info on current position qint64 posXInAsm = browser->calcAsmPosX(cursorPos); U2OpStatusImpl status; //quint64 readsPerXPixel = model->countReadsInAssembly(U2Region(posXInAsm, 1), status); U2AssemblyCoverageStat coverageStat; coverageStat.coverage.resize(1); model->calculateCoverageStat(U2Region(posXInAsm, 1), coverageStat, status); LOG_OP(status); //3. format the string // pos + 1 because of 1-based coords QString cursorLabel = FormatUtils::formatNumberWithSeparators(posXInAsm + 1) + QString(" C%1").arg(coverageStat.coverage.at(0).maxValue); int textWidth = p.fontMetrics().width(cursorLabel); int textHeight = p.fontMetrics().height(); QRect offsetRect(cursorPos - textWidth/2, LABELS_END, textWidth, textHeight); if(offsetRect.left() < 0) { offsetRect.moveLeft(0); } if(offsetRect.right() > width() - 1) { offsetRect.moveRight(width() - 1); } //4. draw cursor label p.drawText(offsetRect, Qt::AlignCenter, cursorLabel); if(!showCoords) { return; } //5. draw cached labels. Skip labels intersecting the cursor label assert(cachedLabelsRects.size() == cachedLabels.size()); for(int i = 0; i < cachedLabels.size(); i++) { const QRect & labelRect = cachedLabelsRects.at(i); if(!labelRect.intersects(offsetRect) && rect().contains(labelRect)) { p.drawImage(cachedLabelsRects.at(i), cachedLabels.at(i)); } } } void AssemblyRuler::drawRuler(QPainter & p) { cachedLabelsRects.clear(); cachedLabels.clear(); p.setPen(Qt::black); // draw the axis + left and right border notches { // axis p.drawLine(0, AXIS_LINE_Y, width(), AXIS_LINE_Y); // borders p.drawLine(0, BORDER_NOTCH_START, 0, BORDER_NOTCH_END); p.drawLine(width()-1, BORDER_NOTCH_START, width()-1, BORDER_NOTCH_END); } int lettersPerZ = browser->calcAsmCoordX(50); int interval = pow((double)10, numOfDigits(lettersPerZ)-1); //interval between notches //int pixInterval = browser->calcPixelCoord(interval); int globalOffset = browser->getXOffsetInAssembly(); qint64 firstLetterWithNotch = globalOffset - 1; while((firstLetterWithNotch + 1) % interval != 0) { ++firstLetterWithNotch; } int start = firstLetterWithNotch - globalOffset; int end = browser->basesCanBeVisible(); int bigInterval = interval * 10; //interval between long notches int halfCell = browser->getCellWidth() / 2; int lastLabelRight = 0; //used to skip intersecting labels //iterate over notches to draw for(int i = start; i < end; i+=interval) { int x_pix = browser->calcPainterOffset(i) + halfCell; //draw long notches + labels for "big interval" int oneBasedOffset = globalOffset + i + 1; if(oneBasedOffset == 1 || oneBasedOffset % bigInterval == 0) { //draw long notch p.drawLine(x_pix, LONG_NOTCH_START, x_pix, LONG_NOTCH_END); //draw labels QString offsetStr = FormatUtils::formatNumberWithSeparators(oneBasedOffset); int textWidth = p.fontMetrics().width(offsetStr); int textHeight = p.fontMetrics().height(); QRect offsetRect(x_pix - textWidth/2, LABELS_END, textWidth, textHeight); if(offsetRect.left() > lastLabelRight) { //render image with label and cache it. all images will be drawn on mouseMove event QImage img(textWidth, textHeight, QImage::Format_ARGB32); QPainter labelPainter(&img); img.fill(Qt::transparent); labelPainter.drawText(QRect(0, 0, textWidth, textHeight), Qt::AlignCenter, offsetStr); lastLabelRight = offsetRect.right() + 15; //prevent intersecting or too close labels cachedLabelsRects.append(offsetRect); cachedLabels.append(img); } } else { //draw short notches p.drawLine(x_pix, SHORT_NOTCH_START, x_pix, SHORT_NOTCH_END); } } } void AssemblyRuler::sl_handleMoveToPos(const QPoint & pos) { int cellWidth = browser->getCellWidth(); if(cellWidth == 0) { cursorPos = pos.x(); redraw = true; update(); } else { //redraw cursor only if it points to the new cell int cellNumOld = cursorPos / cellWidth; int cellNumNew = pos.x() / cellWidth; if(cellNumOld != cellNumNew) { cursorPos = cellNumNew * cellWidth + cellWidth / 2; redraw = true; update(); } } } void AssemblyRuler::paintEvent(QPaintEvent * e) { drawAll(); QWidget::paintEvent(e); } void AssemblyRuler::resizeEvent(QResizeEvent * e) { sl_redraw(); QWidget::resizeEvent(e); } void AssemblyRuler::mouseMoveEvent(QMouseEvent * e) { sl_handleMoveToPos(e->pos()); QWidget::mouseMoveEvent(e); } void AssemblyRuler::sl_redraw() { cachedView = QPixmap (size()); redraw = true; update(); } void AssemblyRuler::setShowCoordsOnRuler(bool sh) { AssemblyBrowserSettings::setShowCoordsOnRuler(sh); showCoords = sh; redraw = true; update(); } bool AssemblyRuler::getShowCoordsOnRuler() const { return showCoords; } } ugene-1.9.8/src/plugins/assembly_browser/src/CoveredRegionsManager.cpp0000644000175000017500000000526111651544321024656 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "CoveredRegionsManager.h" #include #include namespace U2 { CoveredRegionsManager::CoveredRegionsManager(const U2Region & visibleRegion_, const QVector & coverageInfo) : visibleRegion(visibleRegion_) { assert(!coverageInfo.empty()); assert(!visibleRegion.isEmpty()); //convert coverage info to covered regions //splitting visible region to coverageInfo.size() "covered" regions double step = double(visibleRegion.length)/coverageInfo.size(); //precise length of the region for(int i = 0; i < coverageInfo.size(); ++i) { U2Region region(step*i, qint64(step)); CoveredRegion coveredRegion(region, coverageInfo[i]); allRegions.push_back(coveredRegion); } }; QList CoveredRegionsManager::getCoveredRegions(qint64 coverageLevel) const { QList coveredRegions; foreach(CoveredRegion cr, allRegions) { if(cr.coverage >= coverageLevel) { coveredRegions.push_back(cr); } } return coveredRegions; } QList CoveredRegionsManager::getTopCoveredRegions(int topMax, qint64 coverageLevel/*=0*/) const { assert(topMax > 0); QMultiMap topCovered; for(int i = 0; i < allRegions.size(); ++i) { const CoveredRegion & cr = allRegions.at(i); if(cr.coverage >= coverageLevel) { topCovered.insert(cr.coverage, cr); } if(topCovered.size() > topMax) { topCovered.erase(topCovered.begin()); } } assert(topCovered.size() <= topMax); QList topCoveredList = topCovered.values(); QList result; //reverse copy, since topCoveredList is sorted in the ascending order std::copy(topCoveredList.begin(), topCoveredList.end(), std::front_inserter(result)); return result; } } ugene-1.9.8/src/plugins/assembly_browser/src/AssemblyBrowser.cpp0000644000175000017500000006641011651544321023573 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "AssemblyBrowser.h" #include "AssemblyBrowserFactory.h" #include "ZoomableAssemblyOverview.h" #include "AssemblyReferenceArea.h" #include "AssemblyDensityGraph.h" #include "AssemblyRuler.h" #include "AssemblyReadsArea.h" #include "AssemblyBrowserSettings.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include namespace U2 { //============================================================================== // AssemblyBrowser //============================================================================== const double AssemblyBrowser::ZOOM_MULT = 1.25; const double AssemblyBrowser::INITIAL_ZOOM_FACTOR= 1.; AssemblyBrowser::AssemblyBrowser(AssemblyObject * o) : GObjectView(AssemblyBrowserFactory::ID, GObjectViewUtils::genUniqueViewName(o->getDocument(), o)), ui(0), gobject(o), model(0), zoomFactor(INITIAL_ZOOM_FACTOR), xOffsetInAssembly(0), yOffsetInAssembly(0), coverageReady(false), zoomInAction(0), zoomOutAction(0), posSelectorAction(0), posSelector(0), showCoordsOnRulerAction(0), saveScreenShotAction(0), showInfoAction(0), exportToSamAction(0) { GCOUNTER( cvar, tvar, "AssemblyBrowser:open" ); initFont(); setupActions(); if(gobject) { objects.append(o); requiredObjects.append(o); const U2DataRef& ref= gobject->getDbiRef(); model = QSharedPointer(new AssemblyModel(DbiHandle(ref.factoryId, ref.dbiId, dbiOpStatus))); sl_assemblyLoaded(); } onObjectAdded(gobject); } QWidget * AssemblyBrowser::createWidget() { ui = new AssemblyBrowserUi(this); U2OpStatusImpl os; if(model->hasReads(os)) { updateOverviewTypeActions(); showCoordsOnRulerAction->setChecked(ui->getRuler()->getShowCoordsOnRuler()); ui->installEventFilter(this); ui->setAcceptDrops(true); } return ui; } bool AssemblyBrowser::eventFilter(QObject* o, QEvent* e) { if(o == ui) { if (e->type() == QEvent::DragEnter || e->type() == QEvent::Drop) { QDropEvent* de = (QDropEvent*)e; const QMimeData* md = de->mimeData(); const GObjectMimeData* gomd = qobject_cast(md); if (gomd != NULL) { if (e->type() == QEvent::DragEnter) { de->acceptProposedAction(); } else { QString err = tryAddObject(gomd->objPtr.data()); if(!err.isEmpty()) { QMessageBox::critical(ui, tr("Error!"), err); } } } } } return false; } QString AssemblyBrowser::tryAddObject(GObject * obj) { DNASequenceObject * seqObj = qobject_cast(obj); if(seqObj == NULL) { return tr("Only sequence object can be added to assembly browser"); } Document * seqDoc = seqObj->getDocument(); if(seqDoc == NULL) { assert(false); return tr("Internal error: only sequence with document can be added to browser"); } assert(seqDoc->getDocumentFormat() != NULL); U2SequenceDbi * seqDbi = seqObj->asDbi(); assert(seqDbi != NULL); U2OpStatusImpl status; QString seqObjName = seqObj->getGObjectName(); U2Sequence u2SeqObj = seqDbi->getSequenceObject(seqObjName.toAscii(), status); if(status.hasError()) { return status.getError(); } QStringList errs; qint64 modelLen = model->getModelLength(status); if(u2SeqObj.length != modelLen) { errs << tr("- Reference sequence is %1 than assembly").arg(u2SeqObj.length < modelLen ? tr("lesser") : tr("bigger")); } if(seqObjName != gobject->getGObjectName()) { errs << tr("- Reference and assembly names not match"); } // commented: waiting for fix //QByteArray refMd5 = model->getReferenceMd5(); //if(!refMd5.isEmpty()) { // //QByteArray data = QString(seqObj->getSequence()).remove("-").toUpper().toUtf8(); // QByteArray data = QString(seqObj->getSequence()).toUpper().toUtf8(); // QByteArray seqObjMd5 = QCryptographicHash::hash(data, QCryptographicHash::Md5).toHex(); // if(seqObjMd5 != refMd5) { // errs << tr("- Reference MD5 not match with MD5 written in assembly"); // } //} bool setRef = true; if(!errs.isEmpty()) { errs << tr("\n Continue?"); QMessageBox::StandardButtons fl = QMessageBox::Ok | QMessageBox::Cancel; QMessageBox::StandardButton btn = QMessageBox::question(ui, tr("Errors"), errs.join("\n"), fl, QMessageBox::Ok); setRef = btn == QMessageBox::Ok; } if(setRef) { model->setReference(seqDbi, u2SeqObj); U2CrossDatabaseReferenceDbi * crossDbi = model->getDbiHandle().dbi->getCrossDatabaseReferenceDbi(); U2CrossDatabaseReference crossDbRef; crossDbRef.dataRef.dbiId = u2SeqObj.dbiId; crossDbRef.dataRef.entityId = u2SeqObj.id; crossDbRef.dataRef.version = 1; crossDbRef.dataRef.factoryId = "FileDbi_" + seqDoc->getDocumentFormatId(); crossDbi->createCrossReference(crossDbRef, status); LOG_OP(status); model->associateWithReference(crossDbRef); } GCOUNTER( cvar, tvar, "AssemblyBrowser:associate_with_reference" ); return ""; } void AssemblyBrowser::buildStaticToolbar(QToolBar* tb) { U2OpStatusImpl os; if(model->hasReads(os)) { tb->addAction(zoomInAction); tb->addAction(zoomOutAction); U2OpStatusImpl st; posSelector = new PositionSelector(tb, 1, model->getModelLength(st)); if(!st.hasError()) { connect(posSelector, SIGNAL(si_positionChanged(int)), SLOT(sl_onPosChangeRequest(int))); tb->addSeparator(); tb->addWidget(posSelector); } tb->addSeparator(); updateZoomingActions(); // commented because do not know if log scale is needed /*QToolButton * overviewScaleTypeToolButton = new QToolButton(tb); QMenu * scaleTypeMenu = new QMenu(tr("Scale type"), ui); foreach(QAction * a, overviewScaleTypeActions) { scaleTypeMenu->addAction(a); } overviewScaleTypeToolButton->setDefaultAction(scaleTypeMenu->menuAction()); overviewScaleTypeToolButton->setPopupMode(QToolButton::InstantPopup); tb->addWidget(overviewScaleTypeToolButton);*/ tb->addAction(showCoordsOnRulerAction); tb->addAction(saveScreenShotAction); tb->addAction(showInfoAction); // tb->addAction(exportToSamAction); } GObjectView::buildStaticToolbar(tb); } void AssemblyBrowser::sl_onPosChangeRequest(int pos) { setXOffsetInAssembly(normalizeXoffset(pos - 1)); ui->getReadsArea()->setFocus(); } void AssemblyBrowser::buildStaticMenu(QMenu* m) { U2OpStatusImpl os; if(model->hasReads(os)) { m->addAction(zoomInAction); m->addAction(zoomOutAction); m->addAction(saveScreenShotAction); m->addAction(showInfoAction); m->addAction(exportToSamAction); } GObjectView::buildStaticMenu(m); GUIUtils::disableEmptySubmenus(m); } void AssemblyBrowser::setGlobalCoverageInfo(const CoverageInfo & newInfo) { coverageReady = true; if(newInfo.coverageInfo.size() <= coveredRegionsManager.getSize()) { return; } U2OpStatusImpl os; U2Region globalRegion(0, model->getModelLength(os)); coveredRegionsManager = CoveredRegionsManager(globalRegion, newInfo.coverageInfo); coverageInfo = newInfo; } QList AssemblyBrowser::getCoveredRegions() const { if(!coveredRegionsManager.isEmpty()) { return coveredRegionsManager.getTopCoveredRegions(10, 1); } return QList(); } int AssemblyBrowser::getCellWidth() const { return calcPixelCoord(1); } qint64 AssemblyBrowser::calcAsmCoordX(qint64 xPixCoord) const { U2OpStatusImpl status; qint64 modelLen = model->getModelLength(status); qint64 width = ui->getReadsArea()->width(); qint64 xAsmCoord = (double(modelLen) / width * zoomFactor * double(xPixCoord)) + 0.5; return xAsmCoord; } qint64 AssemblyBrowser::calcAsmCoordY(qint64 pixCoord)const { U2OpStatusImpl status; qint64 modelHeight = model->getModelHeight(status); LOG_OP(status); qint64 h = ui->getReadsArea()->height(); return (double(modelHeight) / h * zoomFactor * double(pixCoord)) + 0.5; } qint64 AssemblyBrowser::calcAsmPosX(qint64 pixPosX) const { int cellWidth = getCellWidth(); if(cellWidth == 0) { return xOffsetInAssembly + calcAsmCoordX(pixPosX); } return xOffsetInAssembly + (double)pixPosX / cellWidth; } qint64 AssemblyBrowser::calcAsmPosY(qint64 pixPosY) const { int cellWidth = getCellWidth(); if(cellWidth == 0) { return yOffsetInAssembly + calcAsmCoordY(pixPosY); } return yOffsetInAssembly + (double)pixPosY / cellWidth; } qint64 AssemblyBrowser::calcPixelCoord(qint64 xAsmCoord) const { U2OpStatusImpl status; qint64 modelLen = model->getModelLength(status); qint64 width = ui->getReadsArea()->width(); SAFE_POINT(modelLen != 0, "modelLen == 0, cannot divide to find pixel coordinate", 0); qint64 xPixelCoord = (double(width) / modelLen * double(xAsmCoord)) / zoomFactor + 0.5; return xPixelCoord; } qint64 AssemblyBrowser::calcPainterOffset(qint64 xAsmCoord) const { qint64 letterWidth = getCellWidth(); if(!(letterWidth > 0)) { return calcPixelCoord(xAsmCoord); } qint64 result = letterWidth * xAsmCoord; return result; } qint64 AssemblyBrowser::basesCanBeVisible() const { int width = ui->getReadsArea()->width(); qint64 letterWidth = getCellWidth(); if(0 == letterWidth) { return calcAsmCoordX(width); } qint64 result = width / letterWidth + !!(width % letterWidth); return result; } qint64 AssemblyBrowser::basesVisible() const { U2OpStatusImpl status; qint64 modelLength = model->getModelLength(status); return qMin(modelLength, basesCanBeVisible()); } qint64 AssemblyBrowser::rowsCanBeVisible() const { int height = ui->getReadsArea()->height(); qint64 letterWidth = getCellWidth(); if(0 == letterWidth) { return calcAsmCoordX(height); } qint64 result = height / letterWidth + !!(height % letterWidth); return result; } qint64 AssemblyBrowser::rowsVisible() const { U2OpStatusImpl status; qint64 modelHeight = model->getModelHeight(status); return qMin(rowsCanBeVisible(), modelHeight); } bool AssemblyBrowser::areReadsVisible() const { int readWidthPix = calcPixelCoord(1); // TODO: average read length ? return readWidthPix >= 1; } bool AssemblyBrowser::areCellsVisible() const { return getCellWidth() >= CELL_VISIBLE_WIDTH; } bool AssemblyBrowser::areLettersVisible() const { return getCellWidth() >= LETTER_VISIBLE_WIDTH; } qint64 AssemblyBrowser::normalizeXoffset(qint64 x) const { if(x < 0) { return 0; } U2OpStatusImpl st; // hack: first case is needed to show last column qint64 maxWindowSize = areCellsVisible() ? basesCanBeVisible() - 1 : basesCanBeVisible(); qint64 xMax = model->getModelLength(st) - qMax((qint64)1, maxWindowSize); LOG_OP(st); if(xMax < 0) { return 0; } if(x > xMax && xMax >= 0) { return xMax; } return x; } qint64 AssemblyBrowser::normalizeYoffset(qint64 y) const { if(y < 0) { return 0; } U2OpStatusImpl st; qint64 yMax = model->getModelHeight(st) - qMax((qint64)1, rowsCanBeVisible() - 2); LOG_OP(st); if(yMax < 0) { return 0; } if(y > yMax && yMax >= 0) { return yMax; } return y; } void AssemblyBrowser::setXOffsetInAssembly(qint64 x) { U2OpStatusImpl st; qint64 len = model->getModelLength(st); Q_UNUSED(len); assert(x >= 0 && (x < len || len == 0)); // len == 0 in case of empty model xOffsetInAssembly = x; emit si_offsetsChanged(); } void AssemblyBrowser::setYOffsetInAssembly(qint64 y) { U2OpStatusImpl st; qint64 height = model->getModelHeight(st); Q_UNUSED(height); assert(y >= 0 && (y < height || height == 0)); yOffsetInAssembly = y; emit si_offsetsChanged(); } void AssemblyBrowser::setOffsetsInAssembly(qint64 x, qint64 y) { U2OpStatusImpl st; Q_UNUSED(st); qint64 len = model->getModelLength(st); Q_UNUSED(len); qint64 height = model->getModelHeight(st); Q_UNUSED(height); assert(x >= 0 && (x < len || len == 0)); assert(y >= 0 && (y < height || height == 0)); xOffsetInAssembly = x; yOffsetInAssembly = y; emit si_offsetsChanged(); } void AssemblyBrowser::adjustOffsets(qint64 dx, qint64 dy) { //U2OpStatusImpl status; //qint64 modelLen = model->getModelLength(status); //qint64 modelHeight = model->getModelHeight(status); xOffsetInAssembly = normalizeXoffset(xOffsetInAssembly + dx); yOffsetInAssembly = normalizeYoffset(yOffsetInAssembly + dy); emit si_offsetsChanged(); } void AssemblyBrowser::setFocusToPosSelector() { posSelector->getPosEdit()->setFocus(); } void AssemblyBrowser::sl_assemblyLoaded() { assert(model); GTIMER(c1, t1, "AssemblyBrowser::sl_assemblyLoaded"); LOG_OP(dbiOpStatus); U2Dbi * dbi = model->getDbiHandle().dbi; assert(U2DbiState_Ready == dbi->getState()); U2AssemblyDbi * assmDbi = dbi->getAssemblyDbi(); U2DataId objectId = gobject->getDbiRef().entityId; U2Assembly assm = dbi->getAssemblyDbi()->getAssemblyObject(objectId, dbiOpStatus); LOG_OP(dbiOpStatus); model->setAssembly(assmDbi, assm); } void AssemblyBrowser::navigateToRegion(const U2Region & region) { //if cells are not visible -> make them visible if(!areCellsVisible()) { while(!areCellsVisible()) { sl_zoomIn(); } } //if visible area does not contain reads area -> shift reads area if(xOffsetInAssembly < region.startPos) { setXOffsetInAssembly(region.startPos); } else if(xOffsetInAssembly > region.endPos()-region.length) { setXOffsetInAssembly(region.endPos()-region.length); } } void AssemblyBrowser::initFont() { font.setStyleHint(QFont::SansSerif, QFont::PreferAntialias); } void AssemblyBrowser::setupActions() { zoomInAction = new QAction(QIcon(":core/images/zoom_in.png"), tr("Zoom in"), this); connect(zoomInAction, SIGNAL(triggered()), SLOT(sl_zoomIn())); zoomOutAction = new QAction(QIcon(":core/images/zoom_out.png"), tr("Zoom out"), this); connect(zoomOutAction, SIGNAL(triggered()), SLOT(sl_zoomOut())); QAction * linearScaleAction = new QAction(tr("Linear"), this); linearScaleAction->setCheckable(true); QAction * logScaleAction = new QAction(tr("Logarithmic"), this); logScaleAction->setCheckable(true); connect(linearScaleAction, SIGNAL(triggered()), SLOT(sl_changeOverviewType())); connect(logScaleAction, SIGNAL(triggered()), SLOT(sl_changeOverviewType())); overviewScaleTypeActions << linearScaleAction << logScaleAction; showCoordsOnRulerAction = new QAction(QIcon(":core/images/notch.png"), tr("Show coordinates on ruler"), this); showCoordsOnRulerAction->setCheckable(true); connect(showCoordsOnRulerAction, SIGNAL(triggered()), SLOT(sl_onShowCoordsOnRulerChanged())); saveScreenShotAction = new QAction(QIcon(":/core/images/cam2.png"), tr("Export as image"), this); connect(saveScreenShotAction, SIGNAL(triggered()), SLOT(sl_saveScreenshot())); showInfoAction = new QAction(QIcon(":ugene/images/task_report.png"), tr("Show assembly information"), this); connect(showInfoAction, SIGNAL(triggered()), SLOT(sl_showContigInfo())); exportToSamAction = new QAction(QIcon(":/core/images/sam.png"), tr("Export assembly to SAM format"), this); connect(exportToSamAction, SIGNAL(triggered()), SLOT(sl_exportToSam())); } void AssemblyBrowser::sl_showContigInfo() { QDialog dlg(ui, Qt::WindowTitleHint | Qt::WindowSystemMenuHint); dlg.setWindowTitle(tr("'%1' Contig Information").arg(gobject->getGObjectName())); dlg.setLayout(new QVBoxLayout()); QLabel * infoLabel = new QLabel(); { U2OpStatusImpl st; QString text = ""; text += QString("").arg(gobject->getGObjectName()); text += QString("").arg(FormatUtils::insertSeparators(model->getModelLength(st))); text += QString("").arg(FormatUtils::insertSeparators(model->getReadsNumber(st))); QByteArray md5 = model->getReferenceMd5(st); if(!md5.isEmpty()) { text += QString("").arg(QString(md5)); } QByteArray species = model->getReferenceSpecies(st); if(!species.isEmpty()) { text += QString("").arg(QString(species)); } QString uri = model->getReferenceUri(st); if(!uri.isEmpty()) { text += QString("").arg(uri); } text += "
Name: %1
Length: %1
Number of reads: %1
MD5: %1
Species: %1
URI: %1
"; infoLabel->setText(text); infoLabel->setTextInteractionFlags(Qt::TextSelectableByMouse); } dlg.layout()->addWidget(infoLabel); dlg.resize(300, dlg.sizeHint().height()); dlg.setMaximumHeight(dlg.layout()->minimumSize().height()); dlg.exec(); } void AssemblyBrowser::sl_saveScreenshot() { ExportImageDialog dialog(ui); dialog.exec(); } void AssemblyBrowser::sl_exportToSam() { U2OpStatusImpl os; QHash metaInfo = model->getDbiHandle().dbi->getDbiMetaInfo(os); ConvertAssemblyToSamDialog dialog(ui, metaInfo["url"]); if (dialog.exec()) { ConvertAssemblyToSamTask *convertTask = new ConvertAssemblyToSamTask(&(model->getDbiHandle()), dialog.getSamFileUrl()); AppContext::getTaskScheduler()->registerTopLevelTask(convertTask); } } void AssemblyBrowser::sl_onShowCoordsOnRulerChanged() { bool showRulerCoords = showCoordsOnRulerAction->isChecked(); ui->getRuler()->setShowCoordsOnRuler(showRulerCoords); } void AssemblyBrowser::sl_changeOverviewType() { QAction * a = qobject_cast(sender()); if(a == NULL) { assert(false); return; } AssemblyBrowserSettings::OverviewScaleType t(AssemblyBrowserSettings::Scale_Linear); if(a == overviewScaleTypeActions[1]) { t = AssemblyBrowserSettings::Scale_Logarithmic; } else if(a != overviewScaleTypeActions[0]) { assert(false); } ui->getOverview()->setScaleType(t); updateOverviewTypeActions(); } void AssemblyBrowser::updateZoomingActions() { bool enableZoomOut = INITIAL_ZOOM_FACTOR != zoomFactor; zoomOutAction->setEnabled(enableZoomOut); if(posSelector != NULL) { posSelector->setEnabled(enableZoomOut); } // decide if on next zoom cellWidth will increase max width { bool enableZoomIn = false; double curZoomFactor = zoomFactor; enableZoomIn = !(zoomInFromSize(getCellWidth()) > MAX_CELL_WIDTH); zoomFactor = curZoomFactor; zoomInAction->setEnabled(enableZoomIn); } } void AssemblyBrowser::updateOverviewTypeActions() { AssemblyBrowserSettings::OverviewScaleType t(ui->getOverview()->getScaleType()); overviewScaleTypeActions[0]->setChecked(t == AssemblyBrowserSettings::Scale_Linear); overviewScaleTypeActions[1]->setChecked(t == AssemblyBrowserSettings::Scale_Logarithmic); } void AssemblyBrowser::sl_zoomIn(const QPoint & pos) { if(!canPerformZoomIn()) { return; } qint64 oldWidth = basesCanBeVisible(); qint64 posXAsmCoord = calcAsmPosX(pos.x()); //qint64 posYAsmCoord = calcAsmPosY(pos.y()); // zoom in { int oldCellSize = getCellWidth(); if(!oldCellSize) { zoomFactor /= ZOOM_MULT; } else { int cellWidth = zoomInFromSize(oldCellSize); Q_UNUSED(cellWidth); assert(cellWidth <= MAX_CELL_WIDTH); } } // calculate new offsets qint64 newXOff = 0; int cellWidth = getCellWidth(); if(!pos.isNull() && cellWidth != 0) { newXOff = posXAsmCoord - pos.x() / cellWidth; } else { //zooming to the center of the screen newXOff = xOffsetInAssembly + (oldWidth - basesCanBeVisible()) / 2; } setXOffsetInAssembly(normalizeXoffset(newXOff)); updateZoomingActions(); emit si_zoomOperationPerformed(); } void AssemblyBrowser::sl_zoomOut(const QPoint & pos) { if(!canPerformZoomOut()) { return; } qint64 oldWidth = basesVisible(); qint64 posXAsmCoord = calcAsmPosX(pos.x()); //qint64 posYAsmCoord = calcAsmPosY(pos.y()); // zoom out { int oldCellSize = getCellWidth(); if(zoomFactor * ZOOM_MULT > INITIAL_ZOOM_FACTOR) { // next zoom to far zoomFactor = INITIAL_ZOOM_FACTOR; } else if(!oldCellSize) { zoomFactor *= ZOOM_MULT; } else { zoomOutFromSize(oldCellSize); } } // calculate new offsets qint64 newXOff = 0; int cellWidth = getCellWidth(); if(!pos.isNull() && cellWidth != 0) { newXOff = posXAsmCoord - pos.x() / cellWidth; } else { //zooming out of the center newXOff = xOffsetInAssembly + (oldWidth - basesCanBeVisible()) / 2; } setXOffsetInAssembly(normalizeXoffset(newXOff)); updateZoomingActions(); emit si_zoomOperationPerformed(); } void AssemblyBrowser::sl_zoomToReads() { if(!areReadsVisible()) { zoomInFromSize(0); emit si_zoomOperationPerformed(); } } int AssemblyBrowser::zoomInFromSize(int oldCellSize) { SAFE_POINT(oldCellSize >= 0, "oldCellSize < 0, zooming will not work correctly!", oldCellSize); //single decreasing of the zoomFactor not always changes the cell size //so we have to do it in the cycle, until cells grow int cellWidth = 0; do { zoomFactor /= ZOOM_MULT; cellWidth = getCellWidth(); } while(oldCellSize == cellWidth); return cellWidth; } int AssemblyBrowser::zoomOutFromSize(int oldCellSize) { SAFE_POINT(oldCellSize >= 0, "oldCellSize < 0, zooming will not work correctly!", oldCellSize); //single increasing of the zoomFactor not always changes the cell size //so we have to do it in the cycle int cellWidth = 0; do { zoomFactor *= ZOOM_MULT; cellWidth = getCellWidth(); } while(cellWidth == oldCellSize); return cellWidth; } void AssemblyBrowser::onObjectRenamed(GObject*, const QString&) { OpenAssemblyBrowserTask::updateTitle(this); } //============================================================================== // AssemblyBrowserUi //============================================================================== AssemblyBrowserUi::AssemblyBrowserUi(AssemblyBrowser * browser_) : browser(browser_), zoomableOverview(0), referenceArea(0), densityGraph(0), ruler(0), readsArea(0){ U2OpStatusImpl os; if(browser->getModel()->hasReads(os)) { // has mapped reads -> show rich visualization setMinimumSize(300, 200); QScrollBar * readsHBar = new QScrollBar(Qt::Horizontal); QScrollBar * readsVBar = new QScrollBar(Qt::Vertical); zoomableOverview = new ZoomableAssemblyOverview(this, true); //zooming temporarily disabled -iefremov referenceArea = new AssemblyReferenceArea(this); //densityGraph = new AssemblyDensityGraph(this); densityGraph = NULL; ruler = new AssemblyRuler(this); readsArea = new AssemblyReadsArea(this, readsHBar, readsVBar); QVBoxLayout *mainLayout = new QVBoxLayout(); mainLayout->setMargin(0); mainLayout->setSpacing(2); mainLayout->addWidget(zoomableOverview); QGridLayout * readsLayout = new QGridLayout(); readsLayout->setMargin(0); readsLayout->setSpacing(0); //readsLayout->addWidget(densityGraph); readsLayout->addWidget(referenceArea, 0, 0); readsLayout->addWidget(ruler, 1, 0); readsLayout->addWidget(readsArea, 2, 0); readsLayout->addWidget(readsVBar, 2, 1, 1, 1); //readsLayout->addWidget(readsHBar, 3, 0); QWidget * readsLayoutWidget = new QWidget; readsLayoutWidget->setLayout(readsLayout); mainLayout->addWidget(readsLayoutWidget); mainLayout->addWidget(readsHBar); setLayout(mainLayout); connect(readsArea, SIGNAL(si_heightChanged()), zoomableOverview, SLOT(sl_visibleAreaChanged())); connect(readsArea, SIGNAL(si_mouseMovedToPos(const QPoint&)), ruler, SLOT(sl_handleMoveToPos(const QPoint&))); connect(referenceArea, SIGNAL(si_mouseMovedToPos(const QPoint&)), ruler, SLOT(sl_handleMoveToPos(const QPoint&))); connect(browser, SIGNAL(si_offsetsChanged()), readsArea, SLOT(sl_hideHint())); connect(browser->getModel().data(), SIGNAL(si_referenceChanged()), referenceArea, SLOT(sl_redraw())); connect(zoomableOverview, SIGNAL(si_coverageReady()), readsArea, SLOT(sl_redraw())); connect(referenceArea, SIGNAL(si_unassociateReference()), browser->getModel().data(), SLOT(sl_unassociateReference())); } // do not how to show them else { QVBoxLayout * mainLayout = new QVBoxLayout(); QString msg = tr("Assembly has no mapped reads. Nothing to visualize."); QLabel * infoLabel = new QLabel(QString("
%1
").arg(msg)); infoLabel->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); mainLayout->addWidget(infoLabel); setLayout(mainLayout); } } } //ns ugene-1.9.8/src/plugins/assembly_browser/src/AssemblyCellRenderer.h0000644000175000017500000000325011651544321024154 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef __ASSEMBLY_CELL_RENDERER__ #define __ASSEMBLY_CELL_RENDERER__ #include #include #include #include #include namespace U2 { //TODO: implement real color schemes as for MSA extern const QMap defaultColorScheme; class AssemblyCellRenderer { public: AssemblyCellRenderer(const QMap & colorScheme_ = defaultColorScheme); QVector render(const QSize & size, bool text = false, const QFont & font = QFont()); private: void drawCells(const QSize & size, const QFont & font, bool text); void drawText(char c, const QFont & f); void drawCell(char c, const QColor & color); private: QMap colorScheme; QVector images; QSize cachedSize; bool cachedTextFlag; }; } //ns #endif ugene-1.9.8/src/plugins/assembly_browser/src/ZoomableAssemblyOverview.cpp0000644000175000017500000005643511651544321025455 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "ZoomableAssemblyOverview.h" #include #include #include #include #include #include #include #include #include #include "AssemblyBrowser.h" #include "AssemblyReadsArea.h" #include "AssemblyBrowserSettings.h" namespace U2 { //============================================================================== // ZoomableAssemblyOverview //============================================================================== const double ZoomableAssemblyOverview::ZOOM_MULT = 2.; ZoomableAssemblyOverview::ZoomableAssemblyOverview(AssemblyBrowserUi * ui_, bool zoomable_): QWidget(ui_), ui(ui_), browser(ui->getWindow()), model(ui_->getModel()), zoomable(zoomable_), zoomFactor(1.), redrawSelection(true), redrawBackground(true), selectionScribbling(false), visibleRangeScribbling(false), scaleType(AssemblyBrowserSettings::getOverviewScaleType()) { U2OpStatusImpl os; visibleRange.startPos = 0; visibleRange.length = model->getModelLength(os); setFixedHeight(FIXED_HEIGHT); setMouseTracking(true); connectSlots(); setupActions(); setContextMenuPolicy(Qt::DefaultContextMenu); initSelectionRedraw(); } void ZoomableAssemblyOverview::setupActions() { zoomInAction = new QAction(tr("Zoom in"), this); zoomOutAction = new QAction(tr("Zoom out"), this); zoomIn100xActon = new QAction(tr("Zoom in 100x"), this); restoreGlobalOverviewAction = new QAction(tr("Restore global overview"), this); connect(zoomInAction, SIGNAL(triggered()), SLOT(sl_zoomInContextMenu())); connect(zoomOutAction, SIGNAL(triggered()), SLOT(sl_zoomOutContextMenu())); connect(zoomIn100xActon, SIGNAL(triggered()), SLOT(sl_zoom100xContextMenu())); connect(restoreGlobalOverviewAction, SIGNAL(triggered()), SLOT(sl_restoreGlobalOverview())); contextMenu = new QMenu(this); contextMenu->addAction(zoomInAction); contextMenu->addAction(zoomOutAction); contextMenu->addAction(zoomIn100xActon); contextMenu->addAction(restoreGlobalOverviewAction); updateActions(); } void ZoomableAssemblyOverview::updateActions() { bool showingGlobalRegion = model->getGlobalRegion() == visibleRange; zoomOutAction->setDisabled(showingGlobalRegion); restoreGlobalOverviewAction->setDisabled(showingGlobalRegion); bool cantZoomIn = visibleRange.length == minimalOverviewedLen(); zoomIn100xActon->setDisabled(cantZoomIn); zoomInAction->setDisabled(cantZoomIn); } void ZoomableAssemblyOverview::connectSlots() { connect(&coverageTaskRunner, SIGNAL(si_finished()), SLOT(sl_redraw())); connect(&coverageTaskRunner, SIGNAL(si_finished()), SIGNAL(si_coverageReady())); connect(browser, SIGNAL(si_zoomOperationPerformed()), SLOT(sl_visibleAreaChanged())); connect(browser, SIGNAL(si_offsetsChanged()), SLOT(sl_redraw())); } void ZoomableAssemblyOverview::initSelectionRedraw() { redrawSelection = true; cachedView = QPixmap(size()); } void ZoomableAssemblyOverview::drawAll() { if(!model->isEmpty()) { //no coverage -> draw nothing if(!coverageTaskRunner.isFinished()) { cachedBackground = QPixmap(size()); QPainter p(&cachedBackground); p.fillRect(cachedBackground.rect(), Qt::gray); p.drawText(cachedBackground.rect(), Qt::AlignCenter, tr("Background is rendering...")); } //coverage is ready -> redraw background if needed else if(redrawBackground) { cachedBackground = QPixmap(size()); QPainter p(&cachedBackground); drawBackground(p); } //draw selection and labels if (redrawSelection) { cachedView = cachedBackground; QPainter p(&cachedView); drawSelection(p); drawCoordLabels(p); redrawSelection = false; } QPixmap cachedViewCopy(cachedView); if(zoomToRegionSelector.scribbling) { QPainter p(&cachedViewCopy); drawZoomToRegion(p); } QPainter p(this); p.drawPixmap(0, 0, cachedViewCopy); } } void ZoomableAssemblyOverview::drawZoomToRegion(QPainter & p) { if(!zoomToRegionSelector.scribbling) { assert(false); return; } QPoint topLeft; QPoint bottomRight; int curX = mapFromGlobal(QCursor::pos()).x(); if(zoomToRegionSelector.startPos.x() <= curX) { topLeft = QPoint(zoomToRegionSelector.startPos.x(), 0); bottomRight = QPoint(curX, height()); } else { topLeft = QPoint(curX, 0); bottomRight = QPoint(zoomToRegionSelector.startPos.x(), height()); } p.fillRect(QRect(topLeft, bottomRight), QColor(128, 0, 0, 100)); } void ZoomableAssemblyOverview::drawBackground(QPainter & p) { CoverageInfo ci = coverageTaskRunner.getResult(); if(visibleRange == model->getGlobalRegion()) { browser->setGlobalCoverageInfo(ci); } const int widgetHeight = height(); const int widgetWidth = width(); //1. calc reads per pixel static double logMax = .0; double readsPerYPixel = .0; switch(scaleType) { case AssemblyBrowserSettings::Scale_Linear: readsPerYPixel = double(ci.maxCoverage) / widgetHeight; break; case AssemblyBrowserSettings::Scale_Logarithmic: logMax = log((double)ci.maxCoverage); readsPerYPixel = double(logMax) / widgetHeight; break; default: assert(false); } p.fillRect(rect(), Qt::white); //2. draw the graph line-by-line for(int i = 0 ; i < widgetWidth; ++i) { quint64 columnPixels = 0; double grayCoeffD = 0.; switch(scaleType) { case AssemblyBrowserSettings::Scale_Linear: grayCoeffD = double(ci.coverageInfo[i]) / ci.maxCoverage; columnPixels = qint64(double(ci.coverageInfo[i]) / readsPerYPixel + 0.5); //grayCoeff = 255 - int(double(255) / ci.maxCoverage * ci.coverageInfo[i] + 0.5); break; case AssemblyBrowserSettings::Scale_Logarithmic: grayCoeffD = log((double)ci.coverageInfo[i]) / logMax; columnPixels = qint64(double(log((double)ci.coverageInfo[i])) / readsPerYPixel + 0.5); //grayCoeff = 255 - int(double(255) / logMax * log((double)ci.coverageInfo[i]) + 0.5); break; } //UGENE-style colors p.setPen(QColor(80-60*grayCoeffD, 160-100*grayCoeffD, 200-130*grayCoeffD)); p.drawLine(i, 0, i, columnPixels); } //3. draw gray border p.setPen(Qt::gray); p.drawRect(rect().adjusted(0,0,-1,-1)); } static inline bool isRectVerySmall(const QRect & r) { return r.width() <=2 && r.height() <= 15; } static const int CROSS_HALF_SIZE = 3; static const QPoint CROSS_LEFT_CORNER(CROSS_HALF_SIZE, 0); static const QPoint CROSS_RIGHT_CORNER(0, CROSS_HALF_SIZE); void ZoomableAssemblyOverview::drawSelection(QPainter & p) { cachedSelection = calcCurrentSelection(); //if selection is TOO small - enlarge it a bit if(0 == cachedSelection.width()) { cachedSelection.setWidth(1); } if(0 == cachedSelection.height()) { cachedSelection.setHeight(1); } //cached selection can be outside the visible range, so intersect it with it QRect selectionToDraw = rect().intersect(cachedSelection); if(selectionToDraw.isNull()) { return; } if(isRectVerySmall(selectionToDraw)) { //draw red cross QPoint c = selectionToDraw.center(); QPen oldPen = p.pen(); p.setPen(Qt::red); p.drawLine(c - CROSS_LEFT_CORNER, c + CROSS_LEFT_CORNER); p.drawLine(c - CROSS_RIGHT_CORNER, c + CROSS_RIGHT_CORNER); p.setPen(oldPen); } else { //draw transparent rectangle if(selectionToDraw.width() < 5 || selectionToDraw.height() < 5) { //red borders if rect is thin p.setPen(Qt::red); } p.fillRect(selectionToDraw, QColor(230, 230, 230, 180)); p.drawRect(selectionToDraw.adjusted(0, 0, -1, -1)); } } static void insertSpaceSeparators(QString & str) { for(int i = str.length()-3; i > 0; i-=3) { str.insert(i, " "); } } void ZoomableAssemblyOverview::drawCoordLabels(QPainter & p) { const static int xoffset = 4; const static int yoffset = 3; U2OpStatusImpl status; //Prepare text QString visibleStartText = QString::number(visibleRange.startPos); QString visibleEndText = QString::number(visibleRange.endPos()); QString visibleDiffText = QString::number(visibleRange.length); insertSpaceSeparators(visibleStartText); insertSpaceSeparators(visibleEndText); insertSpaceSeparators(visibleDiffText); //Prepare font QFont font; font.setStyleHint(QFont::SansSerif, QFont::PreferAntialias); QFontMetrics fontMetrics(font); //draw Visible Region QString visibleRegionText = tr("%1 to %2 (%3 bp)").arg(visibleStartText).arg(visibleEndText).arg(visibleDiffText); QRect grtRect = QRect(0, 0, fontMetrics.width(visibleRegionText), fontMetrics.height()); grtRect.translate(xoffset, rect().height() - yoffset - grtRect.height()); if(rect().contains(grtRect)) { p.fillRect(grtRect, QColor(255, 255, 255, 180)); p.setPen(Qt::darkRed); p.drawText(grtRect, Qt::AlignCenter, visibleRegionText); } //draw Selected Region qint64 from = browser->getXOffsetInAssembly(); qint64 to = qMin(browser->getXOffsetInAssembly() + browser->basesCanBeVisible(), model->getModelLength(status)); //prepare text QString fromText = QString::number(from + 1); // because of 1-based coords QString toText = QString::number(to); QString diff = QString::number(to - from); insertSpaceSeparators(fromText); insertSpaceSeparators(toText); insertSpaceSeparators(diff); //draw text QString selectedRegionText = tr("%1 to %2 (%3 bp)").arg(fromText, toText, diff); QRect srtRect = QRect(0, 0, fontMetrics.width(selectedRegionText), fontMetrics.height()); srtRect.translate(rect().width() - srtRect.width() - xoffset, rect().height() - yoffset - grtRect.height()); if(rect().contains(srtRect) && !srtRect.intersects(grtRect)) { p.fillRect(srtRect, QColor(255, 255, 255, 180)); p.setPen(Qt::darkRed); p.drawText(srtRect, /*Qt::AlignCenter, */selectedRegionText); } } qint64 ZoomableAssemblyOverview::calcXAssemblyCoord(int x) const { U2OpStatusImpl status; qint64 result = double(visibleRange.length) / width() * x + 0.5 + visibleRange.startPos; return result; } qint64 ZoomableAssemblyOverview::calcYAssemblyCoord(int y) const { U2OpStatusImpl status; qint64 result = double(model->getModelHeight(status)) / height() * y + 0.5; return result; } QRect ZoomableAssemblyOverview::calcCurrentSelection() const { U2OpStatusImpl status; int w = rect().width(); int h = rect().height(); // qint64 x_ass_start = qMax(0, browser->getXOffsetInAssembly()-visibleRange.startPos); int x_pix_start = (double(w) / visibleRange.length * (browser->getXOffsetInAssembly()-visibleRange.startPos)) + 0.5; int y_pix_start = double(h) / model->getModelHeight(status) * browser->getYOffsetInAssembly() + 0.5; int pix_width = (double(w) / visibleRange.length * browser->basesVisible()) + 0.5; int pix_height = double(h) / model->getModelHeight(status) * browser->rowsVisible() + 0.5; return QRect(x_pix_start, y_pix_start, pix_width, pix_height); } //prevents selection from crossing widget borders. //Tries to move selection center to pos. void ZoomableAssemblyOverview::moveSelectionToPos( QPoint pos, bool moveModel ) { const QRect & thisRect = rect(); QRect newSelection(cachedSelection); newSelection.moveCenter(pos); int dy = 0; int dx = 0; if(!thisRect.contains(newSelection)) { QRect uneeon = thisRect.united(newSelection); if(uneeon.bottom() > thisRect.height()) { dy = uneeon.bottom() - thisRect.height(); } else if(uneeon.top() < 0) { dy = uneeon.top(); } // if(uneeon.right() > thisRect.right()) { // dx = uneeon.right() - thisRect.right(); // } else if(uneeon.left() < 0) { // dx = uneeon.left(); // } newSelection.translate(-dx, -dy); } U2OpStatusImpl status; qint64 newXoffset = 0; qint64 newYoffset = 0; if(dx) { newXoffset = (dx < 0) ? 0 : model->getModelLength(status) - browser->basesVisible(); moveModel = true; } else { newXoffset = calcXAssemblyCoord(newSelection.x()); } if(dy) { newYoffset = (dy < 0) ? 0 : model->getModelHeight(status) - browser->rowsVisible(); moveModel = true; } else { newYoffset = calcYAssemblyCoord(newSelection.y()); } if(moveModel) { browser->setOffsetsInAssembly(browser->normalizeXoffset(newXoffset), browser->normalizeYoffset(newYoffset)); } } void ZoomableAssemblyOverview::zoomToPixRange(int x_pix_start, int x_pix_end) { assert(x_pix_start <= x_pix_end); qint64 left_asm = calcXAssemblyCoord(x_pix_start); qint64 right_asm = calcXAssemblyCoord(x_pix_end); checkedSetVisibleRange(left_asm, right_asm-left_asm); sl_redraw(); } void ZoomableAssemblyOverview::checkedMoveVisibleRange(qint64 newStartPos) { if(!zoomable) return; U2OpStatusImpl os; qint64 realNewStartPos = qBound((qint64)0, newStartPos, model->getModelLength(os)-visibleRange.length); visibleRange.startPos = realNewStartPos; launchCoverageCalculation(); } qint64 ZoomableAssemblyOverview::minimalOverviewedLen() const { U2OpStatusImpl os; qint64 modelLen = model->getModelLength(os); LOG_OP(os); // 1 letter == 1 pixel. We are not going to draw more than one pixel per letter // Allow more pixels per letter only if model is shorter than screen return qMin(modelLen, (qint64)width()); } bool ZoomableAssemblyOverview::canZoomToRange(const U2Region & range)const { return minimalOverviewedLen() != range.length; } void ZoomableAssemblyOverview::checkedSetVisibleRange(qint64 newStartPos, qint64 newLen) { if(!zoomable) return; U2OpStatusImpl os; qint64 modelLen = model->getModelLength(os); Q_UNUSED(modelLen); assert(newLen <= modelLen); if(newLen != visibleRange.length || newStartPos != visibleRange.startPos) { qint64 minLen = minimalOverviewedLen(); qint64 minLenDiff = 0; if(newLen < minLen) { minLenDiff = minLen - newLen; } //shift start pos to keep needed region in the center, if //requested length is smaller than minimal allowed length newStartPos -= minLenDiff / 2; newStartPos = qMax((qint64)0, newStartPos); visibleRange.length = qMax(newLen, minLen); checkedMoveVisibleRange(newStartPos); emit si_visibleRangeChanged(visibleRange); } } void ZoomableAssemblyOverview::checkedSetVisibleRange(const U2Region & newRegion) { checkedSetVisibleRange(newRegion.startPos, newRegion.length); } void ZoomableAssemblyOverview::paintEvent(QPaintEvent * e) { drawAll(); QWidget::paintEvent(e); } void ZoomableAssemblyOverview::resizeEvent(QResizeEvent * e) { cachedSelection = calcCurrentSelection(); moveSelectionToPos(cachedSelection.center(), false); launchCoverageCalculation(); sl_redraw(); QWidget::resizeEvent(e); } void ZoomableAssemblyOverview::mousePressEvent(QMouseEvent * me) { //background scribbling if(me->button() == Qt::MidButton) { visibleRangeScribbling = true; visibleRangeLastPos = me->pos(); setCursor(Qt::ClosedHandCursor); } if (me->button() == Qt::LeftButton) { //zoom in if(me->modifiers() & Qt::AltModifier) { QPoint pos = me->pos(); int left_pix = qMax(0, pos.x() - 2); int right_pix = qMin(width(), pos.x() + 2); zoomToPixRange(left_pix, right_pix); } // select region else if(me->modifiers() & Qt::ShiftModifier) { zoomToRegionSelector.scribbling = true; zoomToRegionSelector.startPos = me->pos(); } //selection scribbling else { selectionScribbling = true; if(!cachedSelection.contains(me->pos())) { selectionDiff = QPoint(); moveSelectionToPos(me->pos()); } else { selectionDiff = me->pos() - cachedSelection.center(); } } } QWidget::mousePressEvent(me); } void ZoomableAssemblyOverview::mouseMoveEvent(QMouseEvent * me) { //selection scribbling if((me->buttons() & Qt::LeftButton) && selectionScribbling) { moveSelectionToPos(me->pos() - selectionDiff); } //background scribbling (Ctrl-Click) else if((me->buttons() & Qt::MidButton) && visibleRangeScribbling){ int pixelDiff = visibleRangeLastPos.x() - me->pos().x(); qint64 asmDiff = calcXAssemblyCoord(pixelDiff); checkedMoveVisibleRange(asmDiff); visibleRangeLastPos = me->pos(); } if(zoomToRegionSelector.scribbling) { sl_redraw(); } QWidget::mouseMoveEvent(me); } void ZoomableAssemblyOverview::mouseReleaseEvent(QMouseEvent * me) { if(me->button() == Qt::LeftButton) { if(selectionScribbling) { selectionScribbling = false; } if(zoomToRegionSelector.scribbling) { zoomToRegionSelector.scribbling = false; QPoint curPoint = me->pos(); int regionStartPix = qMin(zoomToRegionSelector.startPos.x(), curPoint.x()); int regionEndPix = qMax(zoomToRegionSelector.startPos.x(), curPoint.x()); if(regionEndPix != regionStartPix) { zoomToPixRange(qMax(0, regionStartPix), qMin(width(), regionEndPix)); update(); } } return; } if((me->button() == Qt::MidButton) && visibleRangeScribbling){ visibleRangeScribbling = false; setCursor(Qt::ArrowCursor); } QWidget::mouseReleaseEvent(me); } void ZoomableAssemblyOverview::wheelEvent(QWheelEvent * e) { bool positive = e->delta() > 0; int numDegrees = abs(e->delta()) / 8; int numSteps = numDegrees / 15; // zoom if(Qt::NoButton == e->buttons()) { if(e->modifiers() & Qt::ControlModifier) { // with Ctrl: zoom overview for(int i = 0; i < numSteps; ++i) { if(positive) { sl_zoomIn(e->pos()); } else { sl_zoomOut(e->pos()); } } } else { // without Ctrl: zoom reads area QApplication::sendEvent(ui->getReadsArea(), e); } } QWidget::wheelEvent(e); } void ZoomableAssemblyOverview::contextMenuEvent(QContextMenuEvent * e) { updateActions(); contextMenu->move(e->globalPos()); contextMenu->show(); contextMenuPos = e->pos(); QWidget::contextMenuEvent(e); } void ZoomableAssemblyOverview::sl_visibleAreaChanged() { cachedSelection = calcCurrentSelection(); moveSelectionToPos(cachedSelection.center(), false); sl_redraw(); } void ZoomableAssemblyOverview::sl_redraw() { initSelectionRedraw(); update(); } void ZoomableAssemblyOverview::sl_zoomIn(const QPoint & pos) { if(!zoomable) return; //1. count new length of the visible region qint64 newLen = visibleRange.length / ZOOM_MULT + 0.5; // if(newLen < browser->basesCanBeVisible()) { // newLen = browser->basesCanBeVisible(); // } qint64 oldLen = visibleRange.length; qint64 minLen = minimalOverviewedLen(); if(newLen < minLen) { newLen = minLen; } if(oldLen == newLen) { return; } //2. count new start position of the visible region qint64 newStart = 0; if(!pos.isNull()) { //Black magic. Zooms overview so that region under mouse pointer remains //under pointer after zoom newStart = calcXAssemblyCoord(pos.x()) - double(newLen)/width()*pos.x(); } else { //simply zoom to center newStart = visibleRange.startPos + (visibleRange.length-newLen)/2; } //3. if nothing changed -> do nothing if(newLen == visibleRange.length && newStart == visibleRange.startPos) { return; } //4. set new values and update widget checkedSetVisibleRange(newStart,newLen); sl_redraw(); } void ZoomableAssemblyOverview::sl_zoomInContextMenu() { sl_zoomIn(contextMenuPos); } void ZoomableAssemblyOverview::sl_zoomOutContextMenu() { sl_zoomOut(contextMenuPos); } void ZoomableAssemblyOverview::sl_zoom100xContextMenu() { QPoint pos = contextMenuPos; int left_pix = qMax(0, pos.x() - 2); int right_pix = qMin(width(), pos.x() + 2); zoomToPixRange(left_pix, right_pix); } void ZoomableAssemblyOverview::sl_restoreGlobalOverview() { checkedSetVisibleRange(model->getGlobalRegion()); sl_redraw(); } void ZoomableAssemblyOverview::sl_zoomOut(const QPoint & pos) { if(!zoomable) return; // 1. count new length of the visible region qint64 newLen = visibleRange.length * ZOOM_MULT + 0.5; U2OpStatusImpl os; if(newLen > model->getModelLength(os)) { newLen = model->getModelLength(os); } // 2. count new start of the visible region qint64 newStart = 0; if(!pos.isNull()) { //Black magic. Zooms overview so that region under mouse pointer remains //under pointer after zoom newStart = calcXAssemblyCoord(pos.x()) - double(newLen)/width()*pos.x(); } else { //simply zoom to center newStart = visibleRange.startPos + (visibleRange.length-newLen)/2; } //3. if nothing changed -> do nothing if(newLen == visibleRange.length && newStart == visibleRange.startPos) { return; } //4. set new values and update widget checkedSetVisibleRange(newStart, newLen); sl_redraw(); } void ZoomableAssemblyOverview::setScaleType(AssemblyBrowserSettings::OverviewScaleType t) { AssemblyBrowserSettings::setOverviewScaleType(t); if(scaleType != t) { scaleType = t; launchCoverageCalculation(); } } AssemblyBrowserSettings::OverviewScaleType ZoomableAssemblyOverview::getScaleType() const { return scaleType; } void ZoomableAssemblyOverview::launchCoverageCalculation() { CalcCoverageInfoTaskSettings settings; settings.model = model; settings.visibleRange = visibleRange; settings.regions = width(); coverageTaskRunner.run(new CalcCoverageInfoTask(settings)); redrawBackground = true; sl_redraw(); } } //ns ugene-1.9.8/src/plugins/assembly_browser/src/AssemblyReferenceArea.cpp0000644000175000017500000001024611651544321024633 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "AssemblyReferenceArea.h" #include #include #include #include #include "AssemblyBrowser.h" namespace U2 { AssemblyReferenceArea::AssemblyReferenceArea(AssemblyBrowserUi * ui_) : QWidget(ui_), ui(ui_), browser(ui_->getWindow()), model(ui_->getModel()), referenceAreaMenu(new QMenu(this)) { setFixedHeight(FIXED_HEIGHT); connectSlots(); sl_redraw(); setMouseTracking(true); // setup menu QAction * unassociateReferenceAction = referenceAreaMenu->addAction(tr("Unassociate")); connect(unassociateReferenceAction, SIGNAL(triggered()), SIGNAL(si_unassociateReference())); } void AssemblyReferenceArea::connectSlots() { connect(browser, SIGNAL(si_zoomOperationPerformed()), SLOT(sl_redraw())); connect(browser, SIGNAL(si_offsetsChanged()), SLOT(sl_redraw())); } void AssemblyReferenceArea::drawAll() { if(!model->isEmpty() && (model->hasReference() || model->isLoadingReference())) { if (redraw) { cachedView.fill(Qt::transparent); QPainter p(&cachedView); redraw = false; drawReference(p); } QPainter p(this); p.drawPixmap(0, 0, cachedView); } } void AssemblyReferenceArea::drawReference(QPainter & p) { GTIMER(c1, t1, "AssemblyReferenceArea::drawReference"); if(model->isLoadingReference()) { p.drawText(rect(), Qt::AlignCenter, tr("Reference is loading...")); return; } if(browser->areCellsVisible()) { p.fillRect(rect(), Qt::transparent); qint64 xOffsetInAss = browser->getXOffsetInAssembly(); U2Region visibleRegion(xOffsetInAss, browser->basesCanBeVisible()); U2OpStatusImpl status; QByteArray visibleSequence = model->getReferenceRegion(visibleRegion, status); SAFE_POINT_OP(status,); int letterWidth = browser->getCellWidth(); int letterHeight = FIXED_HEIGHT; int x_pix_start = 0; const int y_pix_start = 0; bool text = browser->areLettersVisible(); QFont f = browser->getFont(); if(text) { int pointSize = qMin(letterWidth, letterHeight) / 2; if(pointSize) { f.setPointSize(pointSize); } else { text = false; } } QVector cells = cellRenderer.render(QSize(letterWidth, letterHeight), text, f); for(int i = 0; i < visibleSequence.length(); ++i, x_pix_start+=letterWidth) { QRect r(x_pix_start, y_pix_start, letterWidth, letterHeight); char c = visibleSequence.at(i); p.drawImage(r, cells[c]); } } } void AssemblyReferenceArea::paintEvent(QPaintEvent * e) { drawAll(); QWidget::paintEvent(e); } void AssemblyReferenceArea::resizeEvent(QResizeEvent * e) { sl_redraw(); QWidget::resizeEvent(e); } void AssemblyReferenceArea::mouseMoveEvent(QMouseEvent * e) { emit si_mouseMovedToPos(e->pos()); QWidget::mouseMoveEvent(e); } void AssemblyReferenceArea::sl_redraw() { cachedView = QPixmap(size()); redraw = true; update(); } void AssemblyReferenceArea::mousePressEvent(QMouseEvent* e) { if(e->button() == Qt::RightButton && model->referenceAssociated()) { referenceAreaMenu->exec(QCursor::pos()); } } } //ns ugene-1.9.8/src/plugins/assembly_browser/src/AssemblyDensityGraph.h0000644000175000017500000000326111651544321024211 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef __ASSEMBLY_DENSITY_GRAPH_H__ #define __ASSEMBLY_DENSITY_GRAPH_H__ #include #include #include "AssemblyModel.h" namespace U2 { class AssemblyBrowserUi; class AssemblyBrowser; class AssemblyDensityGraph: public QWidget { Q_OBJECT public: AssemblyDensityGraph(AssemblyBrowserUi * ui); protected: void paintEvent(QPaintEvent * e); void resizeEvent(QResizeEvent * e); void mouseMoveEvent(QMouseEvent * e); signals: void si_mouseMovedToPos(const QPoint &); private slots: void sl_redraw(); private: void connectSlots(); void drawAll(); void drawGraph(QPainter & p); AssemblyBrowserUi * ui; AssemblyBrowser * browser; QSharedPointer model; QPixmap cachedView; bool redraw; const static int FIXED_HEIGHT = 25; }; } //ns #endif ugene-1.9.8/src/plugins/assembly_browser/src/AssemblyDensityGraph.cpp0000644000175000017500000000677711651544321024563 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "AssemblyDensityGraph.h" #include #include #include "AssemblyBrowser.h" namespace U2 { AssemblyDensityGraph::AssemblyDensityGraph(AssemblyBrowserUi * ui_) : QWidget(ui_), ui(ui_), browser(ui_->getWindow()), model(ui_->getModel()) { setFixedHeight(FIXED_HEIGHT); connectSlots(); sl_redraw(); setMouseTracking(true); } void AssemblyDensityGraph::connectSlots() { connect(browser, SIGNAL(si_zoomOperationPerformed()), SLOT(sl_redraw())); connect(browser, SIGNAL(si_offsetsChanged()), SLOT(sl_redraw())); } void AssemblyDensityGraph::drawAll() { if(!model->isEmpty()) { if (redraw) { cachedView.fill(Qt::transparent); QPainter p(&cachedView); redraw = false; drawGraph(p); } QPainter p(this); p.drawPixmap(0, 0, cachedView); } } void AssemblyDensityGraph::drawGraph(QPainter & p) { if(browser->areCellsVisible()) { int cellWidth = browser->getCellWidth(); int visibleBases = browser->basesVisible(); qint64 xStart = browser->getXOffsetInAssembly(); QVector densities(visibleBases); qint64 maxDensity = -1; //calculate density for each visible column for(int ibase = 0; ibase < visibleBases; ++ibase) { U2OpStatusImpl os; qint64 base = xStart + ibase; qint64 density = model->countReadsInAssembly(U2Region(base, 1), os); if (os.hasError()) { LOG_OP(os); break; } if(maxDensity < density) { maxDensity = density; } densities[ibase] = density; } if(0 == maxDensity) { return; } //draw density for each visible column double readsPerYPixel = double(maxDensity)/height(); for(int ibase = 0; ibase < visibleBases; ++ibase) { int columnPixels = qint64(double(densities[ibase]) / readsPerYPixel + 0.5); int grayCoeff = 255 - int(double(255) / maxDensity * densities[ibase] + 0.5); p.fillRect(ibase*cellWidth, 0, cellWidth, columnPixels, QColor(grayCoeff, grayCoeff, grayCoeff)); } } } void AssemblyDensityGraph::paintEvent(QPaintEvent * e) { drawAll(); QWidget::paintEvent(e); } void AssemblyDensityGraph::resizeEvent(QResizeEvent * e) { sl_redraw(); QWidget::resizeEvent(e); } void AssemblyDensityGraph::mouseMoveEvent(QMouseEvent * e) { emit si_mouseMovedToPos(e->pos()); QWidget::mouseMoveEvent(e); } void AssemblyDensityGraph::sl_redraw() { cachedView = QPixmap(size()); redraw = true; update(); } } //ns ugene-1.9.8/src/plugins/assembly_browser/src/AssemblyBrowserFactory.h0000644000175000017500000000346611651544321024572 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef __ASSEMBLY_BROWSER_FACTORY_H__ #define __ASSEMBLY_BROWSER_FACTORY_H__ #include #include #include namespace U2 { class AssemblyBrowserFactory : public GObjectViewFactory { Q_OBJECT public: AssemblyBrowserFactory(QObject * parent = 0); virtual bool canCreateView(const MultiGSelection & multiSelection); virtual Task * createViewTask(const MultiGSelection & multiSelection, bool single = false); static const GObjectViewFactoryId ID; }; class AssemblyObject; class UnloadedObject; class Document; class AssemblyBrowser; class OpenAssemblyBrowserTask : public ObjectViewTask { Q_OBJECT public: OpenAssemblyBrowserTask(AssemblyObject * obj); OpenAssemblyBrowserTask(UnloadedObject * obj); OpenAssemblyBrowserTask(Document * doc); virtual void open(); static void updateTitle(AssemblyBrowser* ab); private: GObjectReference unloadedObjRef; }; } #endif ugene-1.9.8/src/plugins/assembly_browser/src/ShortReadIterator.cpp0000644000175000017500000001474411651544321024060 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "ShortReadIterator.h" namespace U2 { ShortReadIterator::ShortReadIterator(const QByteArray & read_, QList cigar_, int startPos /*= 0*/) : offsetInRead(0), read(read_), offsetInToken(0), offsetInCigar(0), cigar(cigar_) { for(int i = 0; i < startPos && hasNext();) { skip(); U2CigarToken t = cigar.at(offsetInCigar); if(i + t.count <= startPos) { //we are going to skip the current token if(isMatch()) { offsetInRead += t.count; } i += t.count; offsetInToken += t.count; if(!hasNext()) break; advanceToNextToken(); } else { //landing in the current token offsetInToken = startPos - i; if(isMatch()) { offsetInRead += offsetInToken; } break; } } } bool ShortReadIterator::hasNext() const { assert(offsetInCigar <= cigar.size()); if(offsetInCigar == cigar.size()) { return false; } //check if staying on the last pos of current token if(offsetInToken == cigar.at(offsetInCigar).count) { //if staying on the last pos of current token of the last token -> hasn't next if(offsetInCigar == cigar.size()-1) { return false; } //check if everything after current pos is insertion/padding/hard clip int i = offsetInCigar+1; for(; i < cigar.size(); ++i) { U2CigarOp op = cigar.at(i).op; if(U2CigarOp_I != op && U2CigarOp_S != op && U2CigarOp_P != op && U2CigarOp_H != op) { break; } } if(i == cigar.size()) { return false; //no matches/deletions found } } return true; } char ShortReadIterator::nextLetter() { assert(hasNext()); skip(); if(offsetInToken != cigar.at(offsetInCigar).count) { //staying in the current token offsetInToken++; } else { //current token is finished advanceToNextToken(); offsetInToken = 1; } bool del = isDeletion(); char c = del ? '-' : read.at(offsetInRead); //TODO: hardcoded '-' offsetInRead += !del; //adjust offsetInRead only when going through match token return c; } void ShortReadIterator::advanceToNextToken() { offsetInToken = 0; offsetInCigar++; skip(); } bool ShortReadIterator::isMatch() const { U2CigarOp op = cigar.at(offsetInCigar).op; return U2CigarOp_M == op || U2CigarOp_X == op || U2CigarOp_EQ == op; } bool ShortReadIterator::isInsertion() const { U2CigarOp op = cigar.at(offsetInCigar).op; return U2CigarOp_I == op || U2CigarOp_S == op; } bool ShortReadIterator::isDeletion() const { U2CigarOp op = cigar.at(offsetInCigar).op; return U2CigarOp_D == op || U2CigarOp_N == op; } bool ShortReadIterator::isPaddingOrHardClip() const { U2CigarOp op = cigar.at(offsetInCigar).op; return U2CigarOp_P == op || U2CigarOp_H == op; } void ShortReadIterator::skip() { while(hasNext() && !isMatch() && !isDeletion()) { skipInsertion(); skipPaddingAndHardClip(); } } //skip tokens and corresponding letters void ShortReadIterator::skipInsertion() { while(hasNext() && isInsertion()) { offsetInRead += cigar.at(offsetInCigar).count; offsetInCigar++; } } //silently skip this tokens. void ShortReadIterator::skipPaddingAndHardClip() { while(hasNext() && isPaddingOrHardClip()) { offsetInCigar++; } } namespace { void check(const QByteArray & expectedSeq, ShortReadIterator & it) { int i = 0; while(it.hasNext()) { assert(i < expectedSeq.size()); char expected = expectedSeq[i++]; char actual = it.nextLetter(); Q_UNUSED(actual);Q_UNUSED(expected); assert(expected == actual); } assert(i == expectedSeq.size()); } void t01() { QByteArray read("SIIISSAIIIAAASSIS"); QList cigar; //1H 1S 2I 1I 2S 1M 3I 1D 1M 2D 100H 200P 2M 2S 1I 1S 5H cigar << U2CigarToken(U2CigarOp_H, 1) << U2CigarToken(U2CigarOp_S, 1) << U2CigarToken(U2CigarOp_I, 2) << U2CigarToken(U2CigarOp_I, 1) << U2CigarToken(U2CigarOp_S, 2) << U2CigarToken(U2CigarOp_M, 1) << U2CigarToken(U2CigarOp_I, 3) << U2CigarToken(U2CigarOp_D, 1) << U2CigarToken(U2CigarOp_M, 1) << U2CigarToken(U2CigarOp_D, 2) << U2CigarToken(U2CigarOp_H, 100) << U2CigarToken(U2CigarOp_P, 200) << U2CigarToken(U2CigarOp_M, 2) << U2CigarToken(U2CigarOp_S, 2) << U2CigarToken(U2CigarOp_I, 1) << U2CigarToken(U2CigarOp_S, 1) << U2CigarToken(U2CigarOp_H, 5); QByteArray expectedRead("A-A--AA"); ShortReadIterator it(read, cigar); check(expectedRead, it); } void t02() { QByteArray read("SIIIA"); QList cigar; //1S 3I 1M cigar << U2CigarToken(U2CigarOp_S, 1) << U2CigarToken(U2CigarOp_I, 3) << U2CigarToken(U2CigarOp_EQ, 1); QByteArray expectedRead("A"); ShortReadIterator it(read, cigar); check(expectedRead, it); } void t03() { QByteArray read("ACTS"); QList cigar; //2H 1P 1M 1= 1X 1S 5H cigar << U2CigarToken(U2CigarOp_H, 2) << U2CigarToken(U2CigarOp_P, 1) << U2CigarToken(U2CigarOp_M, 1) << U2CigarToken(U2CigarOp_EQ, 1) << U2CigarToken(U2CigarOp_X, 1) << U2CigarToken(U2CigarOp_S, 1) << U2CigarToken(U2CigarOp_H, 5); QByteArray expectedRead("ACT"); ShortReadIterator it(read, cigar); check(expectedRead, it); } } //ns void shortReadIteratorSmokeTest() { t01(); t02(); t03(); } } //ns ugene-1.9.8/src/plugins/assembly_browser/src/AssemblyReadsArea.cpp0000644000175000017500000006244711651544321024005 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "AssemblyReadsArea.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "AssemblyBrowser.h" #include "ShortReadIterator.h" #include "ZoomableAssemblyOverview.h" #include "ExportReadsDialog.h" namespace U2 { AssemblyReadsArea::AssemblyReadsArea(AssemblyBrowserUi * ui_, QScrollBar * hBar_, QScrollBar * vBar_) : QWidget(ui_), ui(ui_), browser(ui_->getWindow()), model(ui_->getModel()), redraw(true), coveredRegionsLabel(this), hBar(hBar_), vBar(vBar_), hintData(this), scribbling(false), readMenu(new QMenu(this)), copyDataAction(NULL), exportReadAction(NULL), currentHotkeyIndex(-1) { QVBoxLayout * coveredRegionsLayout = new QVBoxLayout(); coveredRegionsLayout->addWidget(&coveredRegionsLabel); setLayout(coveredRegionsLayout); initRedraw(); connectSlots(); setMouseTracking(true); setFocusPolicy(Qt::StrongFocus); coveredRegionsLabel.installEventFilter(this); //setup menu copyDataAction = readMenu->addAction(tr("Copy read information to clipboard")); connect(copyDataAction, SIGNAL(triggered()), SLOT(sl_onCopyReadData())); QMenu * exportMenu = readMenu->addMenu(tr("Export")); exportReadAction = exportMenu->addAction("Current read"); connect(exportReadAction, SIGNAL(triggered()), SLOT(sl_onExportRead())); QAction * exportVisibleReads = exportMenu->addAction("Visible reads"); connect(exportVisibleReads, SIGNAL(triggered()), SLOT(sl_onExportReadsOnScreen())); } void AssemblyReadsArea::initRedraw() { redraw = true; cachedView = QPixmap(size()); } void AssemblyReadsArea::connectSlots() { connect(browser, SIGNAL(si_zoomOperationPerformed()), SLOT(sl_zoomOperationPerformed())); connect(browser, SIGNAL(si_offsetsChanged()), SLOT(sl_redraw())); connect(&coveredRegionsLabel, SIGNAL(linkActivated(const QString&)), SLOT(sl_coveredRegionClicked(const QString&))); } void AssemblyReadsArea::setupHScrollBar() { U2OpStatusImpl status; hBar->disconnect(this); qint64 assemblyLen = model->getModelLength(status); qint64 numVisibleBases = browser->basesVisible(); hBar->setMinimum(0); hBar->setMaximum(assemblyLen - numVisibleBases + 1); //TODO: remove +1 hBar->setSliderPosition(browser->getXOffsetInAssembly()); hBar->setSingleStep(1); hBar->setPageStep(numVisibleBases); hBar->setDisabled(numVisibleBases == assemblyLen); connect(hBar, SIGNAL(valueChanged(int)), SLOT(sl_onHScrollMoved(int))); } void AssemblyReadsArea::setupVScrollBar() { U2OpStatusImpl status; vBar->disconnect(this); qint64 assemblyHeight = model->getModelHeight(status); qint64 numVisibleRows = browser->rowsVisible(); vBar->setMinimum(0); vBar->setMaximum(assemblyHeight - numVisibleRows + 2); //TODO: remove +2 vBar->setSliderPosition(browser->getYOffsetInAssembly()); vBar->setSingleStep(1); vBar->setPageStep(numVisibleRows); if(numVisibleRows == assemblyHeight) { vBar->setDisabled(true); //vBar->hide(); TODO: do hide(), but prevent infinite resizing (hide->show->hide->show) caused by width change } else { vBar->setDisabled(false); //vBar->show(); } connect(vBar, SIGNAL(valueChanged(int)), SLOT(sl_onVScrollMoved(int))); } void AssemblyReadsArea::drawAll() { GTIMER(c1, t1, "AssemblyReadsArea::drawAll"); if(!model->isEmpty()) { if (redraw) { cachedView.fill(Qt::transparent); QPainter p(&cachedView); redraw = false; if(!browser->areReadsVisible()) { drawWelcomeScreen(p); } else { drawReads(p); } setupHScrollBar(); setupVScrollBar(); } QPixmap cachedViewCopy(cachedView); if(hintData.redrawHint) { QPainter p(&cachedViewCopy); hintData.redrawHint = false; drawHint(p); } QPainter p(this); p.drawPixmap(0, 0, cachedViewCopy); } } const static QString ZOOM_LINK("zoom"); const QList AssemblyReadsArea::HOTKEY_DESCRIPTIONS = AssemblyReadsArea::initHotkeyDescriptions(); QList AssemblyReadsArea::initHotkeyDescriptions() { QList res; res << HotkeyDescription(tr("Shift+move mouse"), tr("Zoom the Assembly Overview to selection")); res << HotkeyDescription(tr("Ctrl+wheel"), tr("Zoom the Assembly Overview")); res << HotkeyDescription(tr("Alt+click"), tr("Zoom the Assembly Overview in 100x")); res << HotkeyDescription(tr("Wheel+move mouse"), tr("Move the Assembly Overview")); res << HotkeyDescription(tr("Wheel"), tr("Zoom the Reads Area")); res << HotkeyDescription(tr("Double-click"), tr("Zoom in the Reads Area")); res << HotkeyDescription(tr("+/-"), tr("Zoom in/Zoom out the Reads Area")); res << HotkeyDescription(tr("Click+move mouse"), tr("Move the Reads Area")); res << HotkeyDescription(tr("Arrow"), tr("Move one base in the corresponding direction in the Reads Area")); res << HotkeyDescription(tr("Ctrl+arrow"), tr("Move one page in the corresponding direction in the Reads Area")); res << HotkeyDescription(tr("Page up/Page down"), tr("Move one page up/down in the Reads Area")); res << HotkeyDescription(tr("Home/End"), tr("Move to the beginning/end of the assembly in the Reads Area")); res << HotkeyDescription(tr("Ctrl+G"), tr("Focus to the Go to position field on the toolbar")); return res; } void AssemblyReadsArea::drawWelcomeScreen(QPainter &) { GTIMER(c1, t1, "AssemblyReadsArea::drawDensityGraph"); cachedReads.clear(); QString text = tr("Zoom in to see the reads").arg(ZOOM_LINK); QList coveredRegions = browser->getCoveredRegions(); if(!browser->areCoveredRegionsReady()) { text = tr("Please wait until overview rendering is finished, or zoom in to see the reads").arg(ZOOM_LINK); } else if(!coveredRegions.empty()) { text += tr(" or choose one of the well-covered regions:

"); QString coveredRegionsText = ""; /* * | | Region | Coverage | * | 1 | [x,y] | z | */ coveredRegionsText += tr(""); for(int i = 0; i < coveredRegions.size(); ++i) { const CoveredRegion & cr = coveredRegions.at(i); QString crStart = FormatUtils::splitThousands(cr.region.startPos); QString crEnd = FormatUtils::splitThousands(cr.region.endPos()); QString crCoverage = FormatUtils::splitThousands(cr.coverage); coveredRegionsText += ""; coveredRegionsText += QString("").arg(i+1); coveredRegionsText += QString("").arg(i).arg(crStart).arg(crEnd); coveredRegionsText += tr("").arg(crCoverage); coveredRegionsText += ""; } coveredRegionsText += "
RegionApprox. coverage
%1  [%2 - %3]%4
"; text += coveredRegionsText; } assert(!HOTKEY_DESCRIPTIONS.isEmpty()); if(currentHotkeyIndex == -1 || !coveredRegionsLabel.isVisible()) { currentHotkeyIndex = qrand() % HOTKEY_DESCRIPTIONS.size(); } text += "


TIP:   "; HotkeyDescription hotkey = HOTKEY_DESCRIPTIONS.at(currentHotkeyIndex); text += QString("%1 — %2").arg(hotkey.key).arg(hotkey.desc); coveredRegionsLabel.setText(text); coveredRegionsLabel.setAlignment(Qt::AlignHCenter | Qt::AlignVCenter); coveredRegionsLabel.show(); //p.drawText(rect(), Qt::AlignCenter, ); } void AssemblyReadsArea::drawReads(QPainter & p) { GTIMER(c1, t1, "AssemblyReadsArea::drawReads"); coveredRegionsLabel.hide(); p.setFont(browser->getFont()); p.fillRect(rect(), Qt::white); cachedReads.xOffsetInAssembly = browser->getXOffsetInAssembly(); cachedReads.yOffsetInAssembly = browser->getYOffsetInAssembly(); cachedReads.visibleBases = U2Region(cachedReads.xOffsetInAssembly, browser->basesCanBeVisible()); cachedReads.visibleRows = U2Region(cachedReads.yOffsetInAssembly, browser->rowsCanBeVisible()); // 0. Get reads from the database U2OpStatusImpl status; qint64 t = GTimer::currentTimeMicros(); cachedReads.data = model->getReadsFromAssembly(cachedReads.visibleBases, cachedReads.visibleRows.startPos, cachedReads.visibleRows.endPos(), status); t = GTimer::currentTimeMicros() - t; perfLog.trace(QString("Assembly: reads 2D load time: %1").arg(double(t) / 1000 / 1000)); if (status.hasError()) { LOG_OP(status); return; } // 1. Render cells using AssemblyCellRenderer cachedReads.letterWidth = browser->getCellWidth(); QVector cells; bool text = browser->areLettersVisible(); if(browser->areCellsVisible()) { GTIMER(c3, t3, "AssemblyReadsArea::drawReads -> cells rendering"); QFont f = browser->getFont(); if(text) { f.setPointSize(calcFontPointSize()); } cells = cellRenderer.render(QSize(cachedReads.letterWidth, cachedReads.letterWidth), text, f); } // 2. Iterate over all visible reads and draw them QListIterator it(cachedReads.data); while(it.hasNext()) { GTIMER(c3, t3, "AssemblyReadsArea::drawReads -> cycle through all reads"); const U2AssemblyRead & read = it.next(); QByteArray readSequence = read->readSequence; U2Region readBases(read->leftmostPos, U2AssemblyUtils::getEffectiveReadLength(read)); U2Region readVisibleBases = readBases.intersect(cachedReads.visibleBases); U2Region xToDrawRegion(readVisibleBases.startPos - cachedReads.xOffsetInAssembly, readVisibleBases.length); if(readVisibleBases.isEmpty()) { continue; } U2Region readVisibleRows = U2Region(read->packedViewRow, 1).intersect(cachedReads.visibleRows); // WTF? U2Region yToDrawRegion(readVisibleRows.startPos - cachedReads.yOffsetInAssembly, readVisibleRows.length); if(readVisibleRows.isEmpty()) { continue; } if(browser->areCellsVisible()) { //->draw color rects int firstVisibleBase = readVisibleBases.startPos - readBases.startPos; int x_pix_start = browser->calcPainterOffset(xToDrawRegion.startPos); int y_pix_start = browser->calcPainterOffset(yToDrawRegion.startPos); //iterate over letters of the read QList cigar(read->cigar); // hack: to show reads without cigar but with mapped position if(cigar.isEmpty()) { cigar << U2CigarToken(U2CigarOp_M, readSequence.size()); } ShortReadIterator cigarIt(readSequence, cigar, firstVisibleBase); int basesPainted = 0; for(int x_pix_offset = 0; cigarIt.hasNext() && basesPainted++ < readVisibleBases.length; x_pix_offset += cachedReads.letterWidth) { GTIMER(c2, t2, "AssemblyReadsArea::drawReads -> cycle through one read"); char c = cigarIt.nextLetter(); if(!defaultColorScheme.contains(c)) { //TODO: smarter analysis. Don't forget about '=' symbol and IUPAC codes c = 'N'; } QPoint cellStart(x_pix_start + x_pix_offset, y_pix_start); p.drawImage(cellStart, cells[c]); } } else { int xstart = browser->calcPixelCoord(xToDrawRegion.startPos); int xend = browser->calcPixelCoord(xToDrawRegion.endPos()); int ystart = browser->calcPixelCoord(yToDrawRegion.startPos); int yend = browser->calcPixelCoord(yToDrawRegion.endPos()); p.fillRect(xstart, ystart, xend - xstart, yend - ystart, Qt::black); } } } bool AssemblyReadsArea::findReadUnderMouse(U2AssemblyRead & read) { qint64 asmX = cachedReads.xOffsetInAssembly + (double)curPos.x() / cachedReads.letterWidth; qint64 asmY = cachedReads.yOffsetInAssembly + (double)curPos.y() / cachedReads.letterWidth; bool found = false; QListIterator it(cachedReads.data); while(it.hasNext()) { const U2AssemblyRead & r = it.next(); if(r->packedViewRow == asmY && asmX >= r->leftmostPos && asmX < r->leftmostPos + U2AssemblyUtils::getEffectiveReadLength(r)) { read = r; found = true; break; } } return found; } void AssemblyReadsArea::drawHint(QPainter & p) { if(cachedReads.isEmpty() || cachedReads.letterWidth == 0 || scribbling) { sl_hideHint(); return; } // 1. find assembly read we stay on U2AssemblyRead read; bool found = findReadUnderMouse(read); if(!found) { sl_hideHint(); return; } // 2. set hint info if(read->id != hintData.curReadId) { hintData.curReadId = read->id; hintData.hint.setData(read); } // 3. move hint if needed QRect readsAreaRect(mapToGlobal(rect().topLeft()), mapToGlobal(rect().bottomRight())); QRect hintRect = hintData.hint.rect(); hintRect.moveTo(QCursor::pos() + AssemblyReadsAreaHint::OFFSET_FROM_CURSOR); QPoint offset(0, 0); if(hintRect.right() > readsAreaRect.right()) { offset -= QPoint(hintRect.right() - readsAreaRect.right(), 0); } if(hintRect.bottom() > readsAreaRect.bottom()) { offset -= QPoint(0, hintRect.bottom() - readsAreaRect.bottom()); // move hint bottom to reads area offset -= QPoint(0, readsAreaRect.bottom() - QCursor::pos().y() + AssemblyReadsAreaHint::OFFSET_FROM_CURSOR.y()); } QPoint newPos = QCursor::pos() + AssemblyReadsAreaHint::OFFSET_FROM_CURSOR + offset; if(hintData.hint.pos() != newPos) { hintData.hint.move(newPos); } if(!hintData.hint.isVisible()) { hintData.hint.show(); } // 4. paint frame around read U2Region readBases(read->leftmostPos, U2AssemblyUtils::getEffectiveReadLength(read)); U2Region readVisibleBases = readBases.intersect(cachedReads.visibleBases); assert(!readVisibleBases.isEmpty()); U2Region xToDrawRegion(readVisibleBases.startPos - cachedReads.xOffsetInAssembly, readVisibleBases.length); U2Region readVisibleRows = U2Region(read->packedViewRow, 1).intersect(cachedReads.visibleRows); U2Region yToDrawRegion(readVisibleRows.startPos - cachedReads.yOffsetInAssembly, readVisibleRows.length); assert(!readVisibleRows.isEmpty()); assert(browser->areCellsVisible()); int x_pix_start = browser->calcPainterOffset(xToDrawRegion.startPos); int y_pix_start = browser->calcPainterOffset(yToDrawRegion.startPos); p.setPen(Qt::darkRed); QPoint l(x_pix_start, y_pix_start); QPoint r(x_pix_start + readVisibleBases.length * cachedReads.letterWidth, y_pix_start); const QPoint off(0, cachedReads.letterWidth); p.drawLine(l, r); p.drawLine(l + off, r + off); if(readBases.startPos == readVisibleBases.startPos) { // draw left border p.drawLine(l, l + off); } if(readBases.endPos() == readVisibleBases.endPos()) { // draw right border p.drawLine(r, r + off); } } int AssemblyReadsArea::calcFontPointSize() const { return browser->getCellWidth() / 2; } void AssemblyReadsArea::paintEvent(QPaintEvent * e) { assert(model); drawAll(); QWidget::paintEvent(e); } void AssemblyReadsArea::resizeEvent(QResizeEvent * e) { if(e->oldSize().height() - e->size().height()) { emit si_heightChanged(); } initRedraw(); QWidget::resizeEvent(e); } void AssemblyReadsArea::wheelEvent(QWheelEvent * e) { bool positive = e->delta() > 0; int numDegrees = abs(e->delta()) / 8; int numSteps = numDegrees / 15; // zoom if(Qt::NoButton == e->buttons()) { for(int i = 0; i < numSteps; ++i) { if(positive) { browser->sl_zoomIn(curPos); } else { browser->sl_zoomOut(curPos); } } } QWidget::wheelEvent(e); } void AssemblyReadsArea::mousePressEvent(QMouseEvent * e) { curPos = e->pos(); if(browser->getCellWidth() != 0 && e->button() == Qt::LeftButton) { scribbling = true; setCursor(Qt::ClosedHandCursor); mover = ReadsMover(browser->getCellWidth(), curPos); } if(e->button() == Qt::RightButton && browser->areCellsVisible()) { updateMenuActions(); readMenu->exec(QCursor::pos()); } QWidget::mousePressEvent(e); } void AssemblyReadsArea::mouseReleaseEvent(QMouseEvent * e) { if(e->button() == Qt::LeftButton && scribbling) { scribbling = false; setCursor(Qt::ArrowCursor); } QWidget::mousePressEvent(e); } void AssemblyReadsArea::mouseMoveEvent(QMouseEvent * e) { emit si_mouseMovedToPos(e->pos()); if((e->buttons() & Qt::LeftButton) && scribbling) { mover.handleEvent(e->pos()); int x_units = mover.getXunits(); int y_units = mover.getYunits(); browser->adjustOffsets(-x_units, -y_units); } curPos = e->pos(); hintData.redrawHint = true; update(); } void AssemblyReadsArea::leaveEvent(QEvent *) { QPoint curInHintCoords = hintData.hint.mapFromGlobal(QCursor::pos()); if(!hintData.hint.rect().contains(curInHintCoords)) { sl_hideHint(); } } void AssemblyReadsArea::hideEvent(QHideEvent *) { sl_hideHint(); } bool AssemblyReadsArea::event(QEvent * e) { QEvent::Type t = e->type(); if(t == QEvent::WindowDeactivate) { sl_hideHint(); hintData.redrawHint = false; } return QWidget::event(e); } void AssemblyReadsArea::keyPressEvent(QKeyEvent * e) { int k = e->key(); if(browser->getCellWidth() != 0 && (k == Qt::Key_Left || k == Qt::Key_Right)) { if(hBar->isEnabled()) { int step = e->modifiers() & Qt::ControlModifier ? hBar->pageStep() : hBar->singleStep(); step = k == Qt::Key_Left ? -step : step; hBar->setValue(hBar->value() + step); e->accept(); } } else if(k == Qt::Key_Up || k == Qt::Key_Down) { if(vBar->isEnabled()) { int step = e->modifiers() & Qt::ControlModifier ? vBar->pageStep() : vBar->singleStep(); step = k == Qt::Key_Up ? -step : step; vBar->setValue(vBar->value() + step); e->accept(); } } else if(k == Qt::Key_Home) { if(hBar->isEnabled()) { hBar->setValue(0); e->accept(); } } else if(k == Qt::Key_End) { if(hBar->isEnabled()) { U2OpStatusImpl status; hBar->setValue(model->getModelLength(status)); LOG_OP(status); e->accept(); } } else if(k == Qt::Key_Plus) { browser->sl_zoomIn(); e->accept(); } else if(k == Qt::Key_Minus) { browser->sl_zoomOut(); e->accept(); } else if(k == Qt::Key_G && (e->modifiers() & Qt::ControlModifier)) { browser->setFocusToPosSelector(); e->accept(); } else if(k == Qt::Key_PageUp || k == Qt::Key_PageDown) { if(vBar->isEnabled()) { int step = k == Qt::Key_PageUp ? -vBar->pageStep() : vBar->pageStep(); vBar->setValue(vBar->value() + step); e->accept(); } } if(!e->isAccepted()) { QWidget::keyPressEvent(e); } } bool AssemblyReadsArea::eventFilter(QObject *obj, QEvent *ev) { if(obj == &coveredRegionsLabel) { if(ev->type() == QEvent::MouseMove) { QWidget::event(ev); } return false; } else { return QWidget::eventFilter(obj, ev); } } void AssemblyReadsArea::mouseDoubleClickEvent(QMouseEvent * e) { qint64 cursorXoffset = browser->calcAsmPosX(e->pos().x()); qint64 cursorYoffset = browser->calcAsmPosY(e->pos().y()); //1. zoom in static const int howManyZoom = 1; for(int i = 0; i < howManyZoom; ++i) { browser->sl_zoomIn(); } //2. move cursor offset to center // move x if(hBar->isEnabled()) { qint64 xOffset = browser->getXOffsetInAssembly(); qint64 windowHalfX = xOffset + qRound64((double)browser->basesCanBeVisible() / 2); browser->setXOffsetInAssembly(browser->normalizeXoffset(xOffset + cursorXoffset - windowHalfX + 1)); } // move y if(vBar->isEnabled()) { qint64 yOffset = browser->getYOffsetInAssembly(); qint64 windowHalfY = yOffset + qRound64((double)browser->rowsCanBeVisible() / 2); browser->setYOffsetInAssembly(browser->normalizeYoffset(yOffset + cursorYoffset - windowHalfY + 1)); } } void AssemblyReadsArea::sl_coveredRegionClicked(const QString & link) { if(ZOOM_LINK == link) { browser->sl_zoomToReads(); } else { bool ok; int i = link.toInt(&ok); assert(ok); CoveredRegion cr = browser->getCoveredRegions().at(i); ui->getOverview()->checkedSetVisibleRange(cr.region); browser->navigateToRegion(ui->getOverview()->getVisibleRange()); } } void AssemblyReadsArea::sl_onHScrollMoved(int pos) { browser->setXOffsetInAssembly(pos); } void AssemblyReadsArea::sl_onVScrollMoved(int pos) { browser->setYOffsetInAssembly(pos); } void AssemblyReadsArea::sl_zoomOperationPerformed() { sl_redraw(); } void AssemblyReadsArea::sl_redraw() { initRedraw(); update(); } void AssemblyReadsArea::sl_hideHint() { hintData.hint.hide(); update(); } void AssemblyReadsArea::sl_onCopyReadData() { U2AssemblyRead read; bool found = findReadUnderMouse(read); if(!found) { return; } QApplication::clipboard()->setText(AssemblyReadsAreaHint::getReadDataAsString(read)); } void AssemblyReadsArea::updateMenuActions() { U2AssemblyRead read; bool found = findReadUnderMouse(read); copyDataAction->setEnabled(found); exportReadAction->setEnabled(found); } void AssemblyReadsArea::exportReads(const QList & reads) { GCOUNTER( cvar, tvar, "AssemblyReadsArea:exportReads" ); assert(!reads.isEmpty()); ExportReadsDialog dlg(this, QList() << BaseDocumentFormats::PLAIN_FASTA << BaseDocumentFormats::FASTQ); int ret = dlg.exec(); if(ret == QDialog::Accepted) { ExportReadsDialogModel model = dlg.getModel(); assert(!model.filepath.isEmpty()); DocumentFormat * df = AppContext::getDocumentFormatRegistry()->getFormatById(model.format); if(df == NULL) { assert(false); return; } QList objs; foreach(const U2AssemblyRead & r, reads) { DNAAlphabet * al = AppContext::getDNAAlphabetRegistry()->findAlphabet(r->readSequence); DNASequence seq = DNASequence(r->readSequence, al); seq.quality = DNAQuality(r->quality, DNAQualityType_Sanger); objs << new DNASequenceObject(r->name, seq); } IOAdapterFactory * iof = AppContext::getIOAdapterRegistry()->getIOAdapterFactoryById(BaseIOAdapters::url2io(model.filepath)); Document * doc = new Document(df, iof, model.filepath, objs); SaveDocFlags fl; fl |= SaveDoc_Overwrite; fl |= SaveDoc_DestroyAfter; SaveDocumentTask * saveDocTask = new SaveDocumentTask(doc, fl); Task * t = NULL; if(!model.addToProject) { // only saving t = saveDocTask; } else { // save, add doc t = new AddDocumentTask(new Document(df, iof, model.filepath)); // new doc because doc will be deleted t->addSubTask(saveDocTask); t->setMaxParallelSubtasks(1); } AppContext::getTaskScheduler()->registerTopLevelTask(t); } } void AssemblyReadsArea::sl_onExportRead() { U2AssemblyRead read; bool found = findReadUnderMouse(read); if(!found) { return; } exportReads(QList() << read); } void AssemblyReadsArea::sl_onExportReadsOnScreen() { if(!cachedReads.data.isEmpty()) { exportReads(cachedReads.data); } } } //ns ugene-1.9.8/src/plugins/assembly_browser/src/ShortReadIterator.h0000644000175000017500000000543611651544321023523 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef __SHORT_READ_ITERATOR_H__ #define __SHORT_READ_ITERATOR_H__ #include namespace U2 { //TODO: remove hard-coded '-' gap symbol. Allow custom gap symbols ? /** * Iterator for Next-Gen Sequencing short reads based on CIGAR model * (see enum U2CigarOp for details about CIGAR operations). Provides transparent * iterations through read sequence, skipping clipping/padding/insertions and * returning special symbols when going through deletions or skipped regions. * * Handling of CIGAR operations: * 1. Hard clips (H) and padding (P) operations are silently skipped. * 2. Soft clips (S) and insertions (I) do present in read sequence. So this operations * are skipped together with the corresponding letters of the sequence. * 3. Deletions (D) and skipped regions (N) are 'virtual letters'. Iterator returns gap * symbol when iterating through them. * 4. Matches/mismatches (M/=/X) are treated normally. */ class ShortReadIterator { public: /** * Constructs iterator from raw data and CIGAR model. Iterations can be started * form any position using startPos argument. */ ShortReadIterator(const QByteArray & read_, QList cigar_, int startPos = 0); /** * Returns true if the next letter is a match (mismatch) or deletion/skip. * If the read ends with clipping/insertion/etc hasNext() returns false. */ bool hasNext() const; /** * Returns next letter for match/mismatch or gap symbol for deletion/skip. */ char nextLetter(); private: void advanceToNextToken(); void skip(); void skipInsertion(); void skipPaddingAndHardClip(); bool isMatch() const; bool isInsertion() const; bool isDeletion() const; bool isPaddingOrHardClip() const; int offsetInRead; const QByteArray & read; int offsetInToken; int offsetInCigar; QList cigar; }; extern void shortReadIteratorSmokeTest(); } //ns #endif ugene-1.9.8/src/plugins/assembly_browser/assembly_browser.pri0000644000175000017500000000024011651544321023240 0ustar ilyailya# include (assembly_browser.pri) PLUGIN_ID=assembly_browser PLUGIN_NAME=Genome Assembly Browser PLUGIN_VENDOR=Unipro include( ../../ugene_plugin_common.pri ) ugene-1.9.8/src/plugins/dna_export/0000755000175000017500000000000011651544322015730 5ustar ilyailyaugene-1.9.8/src/plugins/dna_export/dna_export.pro0000644000175000017500000000533511651544322020623 0ustar ilyailyainclude (dna_export.pri) # Input HEADERS += src/CSVColumnConfiguration.h \ src/CSVColumnConfigurationDialog.h \ src/DNAExportPlugin.h \ src/DNAExportPluginTests.h \ src/ExportAlignmentViewItems.h \ src/ExportAnnotationsDialog.h \ src/ExportAnnotations2CSVTask.h \ src/ExportChromatogramDialog.h \ src/ExportMSA2MSADialog.h \ src/ExportMSA2SequencesDialog.h \ src/ExportProjectViewItems.h \ src/ExportSequences2MSADialog.h \ src/ExportSequencesDialog.h \ src/ExportSequenceTask.h \ src/ExportSequenceViewItems.h \ src/ExportTasks.h \ src/ExportUtils.h \ src/GetSequenceByIdDialog.h \ src/ImportAnnotationsFromCSVDialog.h \ src/ImportAnnotationsFromCSVTask.h \ src/ImportQualityScoresTask.h \ src/ImportQualityScoresWorker.h \ src/WriteAnnotationsWorker.h \ src/DNASequenceGenerator.h \ src/DNASequenceGeneratorDialog.h \ src/GenerateDNAWorker.h FORMS += src/ui/CSVColumnConfigurationDialog.ui \ src/ui/ExportAnnotationsDialog.ui \ src/ui/ExportChromatogramDialog.ui \ src/ui/ExportMSA2MSADialog.ui \ src/ui/ExportMSA2SequencesDialog.ui \ src/ui/ExportSequences2MSADialog.ui \ src/ui/ExportSequencesDialog.ui \ src/ui/GetSequenceByIdDialog.ui \ src/ui/ImportAnnotationsFromCSVDialog.ui \ src/ui/DNASequenceGeneratorDialog.ui \ src/ui/BaseContentDialog.ui SOURCES += src/CSVColumnConfigurationDialog.cpp \ src/DNAExportPlugin.cpp \ src/DNAExportPluginTests.cpp \ src/ExportAlignmentViewItems.cpp \ src/ExportAnnotationsDialog.cpp \ src/ExportAnnotations2CSVTask.cpp \ src/ExportChromatogramDialog.cpp \ src/ExportMSA2MSADialog.cpp \ src/ExportMSA2SequencesDialog.cpp \ src/ExportProjectViewItems.cpp \ src/ExportSequences2MSADialog.cpp \ src/ExportSequencesDialog.cpp \ src/ExportSequenceTask.cpp \ src/ExportSequenceViewItems.cpp \ src/ExportTasks.cpp \ src/ExportUtils.cpp \ src/GetSequenceByIdDialog.cpp \ src/ImportAnnotationsFromCSVDialog.cpp \ src/ImportAnnotationsFromCSVTask.cpp \ src/ImportQualityScoresTask.cpp \ src/ImportQualityScoresWorker.cpp \ src/WriteAnnotationsWorker.cpp \ src/DNASequenceGenerator.cpp \ src/DNASequenceGeneratorDialog.cpp \ src/GenerateDNAWorker.cpp TRANSLATIONS += transl/czech.ts transl/english.ts transl/russian.ts ugene-1.9.8/src/plugins/dna_export/dna_export.pri0000644000175000017500000000030411651544322020604 0ustar ilyailya# include (dna_export.pri) PLUGIN_ID=dna_export PLUGIN_NAME=DNA sequence export utilities PLUGIN_VENDOR=Unipro include( ../../ugene_plugin_common.pri ) INCLUDEPATH += ../../corelibs/U2Misc/_tmpugene-1.9.8/src/plugins/dna_export/src/0000755000175000017500000000000011651544322016517 5ustar ilyailyaugene-1.9.8/src/plugins/dna_export/src/ExportSequenceViewItems.cpp0000644000175000017500000007172111651544322024042 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "ExportSequenceViewItems.h" #include "ExportUtils.h" #include "ExportSequenceTask.h" #include "ExportSequencesDialog.h" #include "ExportAnnotationsDialog.h" #include "ExportAnnotations2CSVTask.h" #include "ExportSequences2MSADialog.h" #include "GetSequenceByIdDialog.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include namespace U2 { ////////////////////////////////////////////////////////////////////////// // ExportSequenceViewItemsController ExportSequenceViewItemsController::ExportSequenceViewItemsController(QObject* p) : GObjectViewWindowContext(p, ANNOTATED_DNA_VIEW_FACTORY_ID) { } void ExportSequenceViewItemsController::initViewContext(GObjectView* v) { AnnotatedDNAView* av = qobject_cast(v); ADVExportContext* vc= new ADVExportContext(av); addViewResource(av, vc); } void ExportSequenceViewItemsController::buildMenu(GObjectView* v, QMenu* m) { QList resources = viewResources.value(v); assert(resources.size() == 1); QObject* r = resources.first(); ADVExportContext* vc = qobject_cast(r); assert(vc!=NULL); vc->buildMenu(m); } ////////////////////////////////////////////////////////////////////////// // ADV view context ADVExportContext::ADVExportContext(AnnotatedDNAView* v) : view(v) { sequence2SequenceAction = new QAction(tr("Export selected sequence region..."), this); connect(sequence2SequenceAction, SIGNAL(triggered()), SLOT(sl_saveSelectedSequences())); annotations2SequenceAction = new QAction(tr("Export sequence of selected annotations..."), this); connect(annotations2SequenceAction, SIGNAL(triggered()), SLOT(sl_saveSelectedAnnotationsSequence())); annotations2CSVAction = new QAction(tr("Export annotations..."), this); connect(annotations2CSVAction, SIGNAL(triggered()), SLOT(sl_saveSelectedAnnotations())); annotationsToAlignmentAction = new QAction(QIcon(":core/images/msa.png"), tr("Align selected annotations..."), this); connect(annotationsToAlignmentAction, SIGNAL(triggered()), SLOT(sl_saveSelectedAnnotationsToAlignment())); annotationsToAlignmentWithTranslatedAction = new QAction(QIcon(":core/images/msa.png"), tr("Align selected annotations (amino acids)..."), this); connect(annotationsToAlignmentWithTranslatedAction, SIGNAL(triggered()), SLOT(sl_saveSelectedAnnotationsToAlignmentWithTranslation())); sequenceToAlignmentAction = new QAction(QIcon(":core/images/msa.png"), tr("Align selected sequence regions..."), this); connect(sequenceToAlignmentAction, SIGNAL(triggered()), SLOT(sl_saveSelectedSequenceToAlignment())); sequenceToAlignmentWithTranslationAction = new QAction(QIcon(":core/images/msa.png"), tr("Align selected sequence regions (amino acids)..."), this); connect(sequenceToAlignmentWithTranslationAction, SIGNAL(triggered()), SLOT(sl_saveSelectedSequenceToAlignmentWithTranslation())); sequenceById = new QAction(tr("Export sequences by 'id'"), this); connect(sequenceById, SIGNAL(triggered()), SLOT(sl_getSequenceById())); sequenceByAccession = new QAction(tr("Export sequences by 'accession'"), this); connect(sequenceByAccession, SIGNAL(triggered()), SLOT(sl_getSequenceByAccession())); sequenceByDBXref = new QAction(tr("Export sequences by 'db_xref'"), this); connect(sequenceByDBXref, SIGNAL(triggered()), SLOT(sl_getSequenceByDBXref())); connect(view->getAnnotationsSelection(), SIGNAL(si_selectionChanged(AnnotationSelection*, const QList&, const QList& )), SLOT(sl_onAnnotationSelectionChanged(AnnotationSelection*, const QList&, const QList&))); connect(view, SIGNAL(si_sequenceAdded(ADVSequenceObjectContext*)), SLOT(sl_onSequenceContextAdded(ADVSequenceObjectContext*))); connect(view, SIGNAL(si_sequenceRemoved(ADVSequenceObjectContext*)), SLOT(sl_onSequenceContextRemoved(ADVSequenceObjectContext*))); foreach(ADVSequenceObjectContext* sCtx, view->getSequenceContexts()) { sl_onSequenceContextAdded(sCtx); } } void ADVExportContext::sl_onSequenceContextAdded(ADVSequenceObjectContext* c) { connect(c->getSequenceSelection(), SIGNAL(si_selectionChanged(LRegionsSelection*, const QVector&, const QVector&)), SLOT(sl_onSequenceSelectionChanged(LRegionsSelection*, const QVector&, const QVector&))); updateActions(); } void ADVExportContext::sl_onSequenceContextRemoved(ADVSequenceObjectContext* c) { c->disconnect(this); updateActions(); } void ADVExportContext::sl_onAnnotationSelectionChanged(AnnotationSelection* , const QList& , const QList&) { updateActions(); } void ADVExportContext::sl_onSequenceSelectionChanged(LRegionsSelection* , const QVector& , const QVector& ) { updateActions(); } static bool allNucleic(const QList& seqs) { foreach(const ADVSequenceObjectContext* s, seqs) { if (!s->getAlphabet()->isNucleic()) { return false; } } return true; } void ADVExportContext::updateActions() { bool hasSelectedAnnotations = !view->getAnnotationsSelection()->isEmpty(); bool hasSelectedGroups = view->getAnnotationsGroupSelection(); int nSequenceSelections = 0; foreach(ADVSequenceObjectContext* c, view->getSequenceContexts()) { nSequenceSelections += c->getSequenceSelection()->getSelectedRegions().count(); } sequence2SequenceAction->setEnabled(nSequenceSelections>=1); annotations2SequenceAction->setEnabled(hasSelectedAnnotations); annotations2CSVAction->setEnabled(hasSelectedAnnotations || hasSelectedGroups); bool _allNucleic = allNucleic(view->getSequenceContexts()); bool hasMultipleAnnotationsSelected = view->getAnnotationsSelection()->getSelection().size() > 1; annotationsToAlignmentAction->setEnabled(hasMultipleAnnotationsSelected); annotationsToAlignmentWithTranslatedAction->setEnabled(hasMultipleAnnotationsSelected && _allNucleic); bool hasMultiSequenceSelection = nSequenceSelections > 1; sequenceToAlignmentAction->setEnabled(hasMultiSequenceSelection); sequenceToAlignmentWithTranslationAction->setEnabled(hasMultiSequenceSelection && _allNucleic); } void ADVExportContext::buildMenu(QMenu* m) { QMenu* alignMenu = GUIUtils::findSubMenu(m, ADV_MENU_ALIGN); alignMenu->addAction(sequenceToAlignmentAction); alignMenu->addAction(sequenceToAlignmentWithTranslationAction); alignMenu->addAction(annotationsToAlignmentAction); alignMenu->addAction(annotationsToAlignmentWithTranslatedAction); QMenu* exportMenu = GUIUtils::findSubMenu(m, ADV_MENU_EXPORT); exportMenu->addAction(sequence2SequenceAction); exportMenu->addAction(annotations2SequenceAction); exportMenu->addAction(annotations2CSVAction); bool isShowId = false; bool isShowAccession = false; bool isShowDBXref = false; QString name; if(!view->getAnnotationsSelection()->getSelection().isEmpty()) { name = view->getAnnotationsSelection()->getSelection().first().annotation->getAnnotationName(); } foreach(const AnnotationSelectionData &sel, view->getAnnotationsSelection()->getSelection()) { if(name != sel.annotation->getAnnotationName()) { name = ""; } if(!isShowId && !sel.annotation->findFirstQualifierValue("id").isEmpty()) { isShowId = true; } else if(!isShowAccession && !sel.annotation->findFirstQualifierValue("accession").isEmpty()) { isShowAccession = true; } else if(!isShowDBXref && !sel.annotation->findFirstQualifierValue("db_xref").isEmpty()) { isShowDBXref = true; } } if(isShowId || isShowAccession || isShowDBXref) { name = name.isEmpty() ? "" : "from '" + name + "'"; QMenu *fetchMenu = new QMenu(tr("Fetch sequences from remote database")); m->insertMenu(exportMenu->menuAction(),fetchMenu); if(isShowId) { sequenceById->setText(tr("Fetch sequences by 'id' %1").arg(name)); fetchMenu->addAction(sequenceById); } if(isShowAccession) { sequenceByAccession->setText(tr("Fetch sequences by 'accession' %1").arg(name)); fetchMenu->addAction(sequenceByAccession); } if(isShowDBXref) { sequenceByDBXref->setText(tr("Fetch sequences by 'db_xref' %1").arg(name)); fetchMenu->addAction(sequenceByDBXref); } } } void ADVExportContext::sl_saveSelectedAnnotationsSequence() { AnnotationSelection* as = view->getAnnotationsSelection(); AnnotationGroupSelection* ags = view->getAnnotationsGroupSelection(); QSet annotations; const QList& aData = as->getSelection(); foreach(const AnnotationSelectionData& ad, aData) { annotations.insert(ad.annotation); } const QList& groups = ags->getSelection(); foreach(AnnotationGroup* g, groups) { g->findAllAnnotationsInGroupSubTree(annotations); } if (annotations.isEmpty()) { QMessageBox::warning(view->getWidget(), L10N::warningTitle(), tr("No annotations selected!")); return; } bool allowComplement = true; bool allowTranslation = true; bool allowBackTranslation = true; QMap > annotationsPerSeq; foreach(Annotation* a, annotations) { ADVSequenceObjectContext* seqCtx = view->getSequenceContext(a->getGObject()); if (seqCtx == NULL) { continue; } QList& annsPerSeq = annotationsPerSeq[seqCtx]; annsPerSeq.append(a->data()); if (annsPerSeq.size() > 1) { continue; } DNASequenceObject* seqObj = seqCtx->getSequenceObject(); if (GObjectUtils::findComplementTT(seqObj) == NULL) { allowComplement = false; } if (GObjectUtils::findAminoTT(seqObj, false) == NULL) { allowTranslation = false; } if (GObjectUtils::findBackTranslationTT(seqObj) == NULL) { allowBackTranslation = false; } } QString fileExt = AppContext::getDocumentFormatRegistry()->getFormatById(BaseDocumentFormats::PLAIN_FASTA)->getSupportedDocumentFileExtensions().first(); GUrl seqUrl = view->getSequenceInFocus()->getSequenceGObject()->getDocument()->getURL(); GUrl defaultUrl = GUrlUtils::rollFileName(seqUrl.dirPath() + "/" + seqUrl.baseFileName() + "_annotation." + fileExt, DocumentUtils::getNewDocFileNameExcludesHint()); ExportSequencesDialog d(true, allowComplement, allowTranslation, allowBackTranslation, defaultUrl.getURLString(), BaseDocumentFormats::PLAIN_FASTA, AppContext::getMainWindow()->getQMainWindow()); d.setWindowTitle(annotations2SequenceAction->text()); d.disableAllFramesOption(true); // only 1 frame is suitable d.disableStrandOption(true); // strand is already recorded in annotation d.disableAnnotationsOption(true); // here we do not export annotations for sequence under another annotations int rc = d.exec(); if (rc == QDialog::Rejected) { return; } assert(d.file.length() > 0); ExportAnnotationSequenceTaskSettings s; ExportUtils::loadDNAExportSettingsFromDlg(s.exportSequenceSettings,d); foreach(const ADVSequenceObjectContext* seqCtx, annotationsPerSeq.keys()) { ExportSequenceAItem ei; DNASequenceObject* seqObj = seqCtx->getSequenceObject(); ei.sequence = seqObj->getDNASequence(); ei.complTT = seqCtx->getComplementTT(); ei.aminoTT = d.translate ? seqCtx->getAminoTT() : NULL; if (d.useSpecificTable && ei.sequence.alphabet->isNucleic()) { DNATranslationRegistry* tr = AppContext::getDNATranslationRegistry(); ei.aminoTT = tr->lookupTranslation(seqObj->getAlphabet(), DNATranslationType_NUCL_2_AMINO, d.translationTable); } ei.annotations = annotationsPerSeq.value(seqCtx); s.items.append(ei); } Task* t = ExportUtils::wrapExportTask(new ExportAnnotationSequenceTask(s), d.addToProject); AppContext::getTaskScheduler()->registerTopLevelTask(t); } static QList findAnnotationsInRegion(const U2Region& region, const QList& aobjects) { QList result; foreach (const AnnotationTableObject* aobj, aobjects) { foreach(Annotation* a, aobj->getAnnotations()) { U2Region areg = U2Region::containingRegion(a->getRegions()); if (region.contains(areg)) { result.append(a->data()); } } } return result; } // removes all annotation regions that does not intersect the given region // adjusts startpos to make in relative to the given region static void adjustAnnotationLocations(const U2Region& r, QList& anns) { for (int i = anns.size(); --i >= 0;) { SharedAnnotationData& d = anns[i]; for (int j = d->location->regions.size(); --j >= 0; ) { U2Region& ar = d->location->regions[j]; U2Region resr = ar.intersect(r); if (resr.isEmpty()) { d->location->regions.remove(j); continue; } resr.startPos -= r.startPos; d->location->regions[j] = resr; } if( d->location->regions.isEmpty()) { anns.removeAt(i); } } } void ADVExportContext::sl_saveSelectedSequences() { ADVSequenceObjectContext* seqCtx = view->getSequenceInFocus(); DNASequenceSelection* sel = NULL; if (seqCtx!=NULL) { //TODO: support multi-export.. sel = seqCtx->getSequenceSelection(); } if (sel == NULL || sel->isEmpty()) { QMessageBox::warning(view->getWidget(), L10N::warningTitle(), tr("No sequence regions selected!")); return; } const QVector& regions = sel->getSelectedRegions(); bool merge = regions.size() > 1; bool complement = seqCtx->getComplementTT()!=NULL; bool amino = seqCtx->getAminoTT()!=NULL; bool nucleic = GObjectUtils::findBackTranslationTT(seqCtx->getSequenceObject())!=NULL; QString fileExt = AppContext::getDocumentFormatRegistry()->getFormatById(BaseDocumentFormats::PLAIN_FASTA)->getSupportedDocumentFileExtensions().first(); GUrl seqUrl = seqCtx->getSequenceGObject()->getDocument()->getURL(); GUrl defaultUrl = GUrlUtils::rollFileName(seqUrl.dirPath() + "/" + seqUrl.baseFileName() + "_region." + fileExt, DocumentUtils::getNewDocFileNameExcludesHint()); ExportSequencesDialog d(merge, complement, amino, nucleic, defaultUrl.getURLString(), BaseDocumentFormats::PLAIN_FASTA, AppContext::getMainWindow()->getQMainWindow()); d.setWindowTitle(sequence2SequenceAction->text()); int rc = d.exec(); if (rc == QDialog::Rejected) { return; } assert(d.file.length() > 0); const QByteArray& sequence = seqCtx->getSequenceData(); DNAAlphabet* al = seqCtx->getAlphabet(); ExportSequenceTaskSettings s; ExportUtils::loadDNAExportSettingsFromDlg(s,d); QSet usedNames; foreach(const U2Region& r, regions) { QString prefix = QString("region [%1 %2]").arg(QString::number(r.startPos+1)).arg(QString::number(r.endPos())); QString name = prefix; for (int i = 0; i < s.items.size(); ++i) { if (usedNames.contains(name)) { name = prefix + "|" + QString::number(i); } } usedNames.insert(name); ExportSequenceItem ei; QByteArray seq(sequence.constData() + r.startPos, r.length); ei.sequence = DNASequence(name, seq, al); ei.complTT = seqCtx->getComplementTT(); ei.aminoTT = d.translate ? (d.useSpecificTable ? GObjectUtils::findAminoTT(seqCtx->getSequenceObject(), false, d.translationTable) : seqCtx->getAminoTT()) : NULL; ei.backTT = d.backTranslate ? GObjectUtils::findBackTranslationTT(seqCtx->getSequenceObject(), d.translationTable) : NULL; if (s.saveAnnotations) { ei.annotations = findAnnotationsInRegion(r, seqCtx->getAnnotationObjects(true).toList()); adjustAnnotationLocations(r, ei.annotations); } s.items.append(ei); } Task* t = ExportUtils::wrapExportTask(new ExportSequenceTask(s), d.addToProject); AppContext::getTaskScheduler()->registerTopLevelTask(t); } void ADVExportContext::sl_saveSelectedAnnotations() { // find annotations: selected annotations, selected groups QSet annotationSet; AnnotationSelection* as = view->getAnnotationsSelection(); foreach(const AnnotationSelectionData &data, as->getSelection()) { annotationSet.insert(data.annotation); } foreach(AnnotationGroup *group, view->getAnnotationsGroupSelection()->getSelection()) { group->findAllAnnotationsInGroupSubTree(annotationSet); } if (annotationSet.isEmpty()) { QMessageBox::warning(view->getWidget(), L10N::warningTitle(), tr("No annotations selected!")); return; } Annotation* first = *annotationSet.begin(); Document* doc = first->getGObject()->getDocument(); ADVSequenceObjectContext *sequenceContext = view->getSequenceInFocus(); GUrl url; if (doc != NULL) { url = doc->getURL(); } else if (sequenceContext != NULL) { url = sequenceContext->getSequenceGObject()->getDocument()->getURL(); } else { url = GUrl("newfile"); } QString fileName = GUrlUtils::rollFileName(url.dirPath() + "/" + url.baseFileName() + "_annotations.csv", DocumentUtils::getNewDocFileNameExcludesHint()); ExportAnnotationsDialog d(fileName, AppContext::getMainWindow()->getQMainWindow()); d.setWindowTitle(annotations2CSVAction->text()); if (QDialog::Accepted != d.exec()) { return; } //TODO: lock documents or use shared-data objects QList annotationList = annotationSet.toList(); qStableSort(annotationList.begin(), annotationList.end(), Annotation::annotationLessThan); // run task Task * t = NULL; if(d.fileFormat() == ExportAnnotationsDialog::CSV_FORMAT_ID) { t = new ExportAnnotations2CSVTask(annotationList, sequenceContext->getSequenceData(), sequenceContext->getComplementTT(), d.exportSequence(), d.filePath()); } else { t = ExportUtils::saveAnnotationsTask(d.filePath(), d.fileFormat(), annotationList); } AppContext::getTaskScheduler()->registerTopLevelTask(t); } ////////////////////////////////////////////////////////////////////////// // alignment part #define MAX_ALI_MODEL (10*1000*1000) QString ADVExportContext::prepareMAFromAnnotations(MAlignment& ma, bool translate) { assert(ma.isEmpty()); const QList& selection = view->getAnnotationsSelection()->getSelection(); if (selection.size() < 2) { return tr("At least 2 annotations are required"); } // check that all sequences are present and have the same alphabets DNAAlphabet* al = NULL; DNATranslation* complTT = NULL; foreach(const AnnotationSelectionData& a, selection) { AnnotationTableObject* ao = a.annotation->getGObject(); ADVSequenceObjectContext* seqCtx = view->getSequenceContext(ao); if (seqCtx == NULL) { return tr("No sequence object found"); } if (al == NULL ) { al = seqCtx->getAlphabet(); complTT = seqCtx->getComplementTT(); } else { DNAAlphabet* al2 = seqCtx->getAlphabet(); //BUG524: support alphabet reduction if (al->getType() != al2->getType()) { return tr("Different sequence alphabets"); } else if (al != al2) { al = al->getMap().count(true) >= al2->getMap().count(true) ? al : al2; } } } int maxLen = 0; ma.setAlphabet(al); QSet names; foreach(const AnnotationSelectionData& a, selection) { QString rowName = ExportUtils::genUniqueName(names, a.annotation->getAnnotationName()); AnnotationTableObject* ao = a.annotation->getGObject(); ADVSequenceObjectContext* seqCtx = view->getSequenceContext(ao); const QByteArray& sequence = seqCtx->getSequenceData(); maxLen = qMax(maxLen, a.getSelectedRegionsLen()); if (maxLen * ma.getNumRows() > MAX_ALI_MODEL) { return tr("Alignment is too large"); } bool doComplement = a.annotation->getStrand().isCompementary(); DNATranslation* aminoTT = translate ? seqCtx->getAminoTT() : NULL; QByteArray rowSequence; AnnotationSelection::getAnnotationSequence(rowSequence, a, MAlignment_GapChar, sequence, doComplement? complTT : NULL, aminoTT); ma.addRow(MAlignmentRow(rowName, rowSequence)); names.insert(rowName); } return ""; } QString ADVExportContext::prepareMAFromSequences(MAlignment& ma, bool translate) { assert(ma.isEmpty()); DNAAlphabet* al = translate ? AppContext::getDNAAlphabetRegistry()->findById(BaseDNAAlphabetIds::AMINO_DEFAULT()) : NULL; //derive alphabet int nItems = 0; bool forceTranslation = false; foreach(ADVSequenceObjectContext* c, view->getSequenceContexts()) { if (c->getSequenceSelection()->isEmpty()) { continue; } nItems += c->getSequenceSelection()->getSelectedRegions().count(); DNAAlphabet* seqAl = c->getAlphabet(); if (al == NULL) { al = seqAl; } else if (al != seqAl) { if (al->isNucleic() && seqAl->isAmino()) { forceTranslation = true; al = seqAl; } else if (al->isAmino() && seqAl->isNucleic()) { forceTranslation = true; } else { return tr("Can't derive alignment alphabet"); } } } if (nItems < 2) { return tr("At least 2 sequences required"); } //cache sequences QSet names; QList rows; qint64 maxLen = 0; foreach(ADVSequenceObjectContext* c, view->getSequenceContexts()) { if (c->getSequenceSelection()->isEmpty()) { continue; } DNAAlphabet* seqAl = c->getAlphabet(); DNATranslation* aminoTT = ((translate || forceTranslation) && seqAl->isNucleic()) ? c->getAminoTT() : NULL; foreach(const U2Region& r, c->getSequenceSelection()->getSelectedRegions()) { const QByteArray& seq = c->getSequenceData(); maxLen = qMax(maxLen, r.length); if (maxLen * rows.size() > MAX_ALI_MODEL) { return tr("Alignment is too large"); } QByteArray mid = seq.mid(r.startPos, r.length); if (aminoTT!=NULL) { int len = aminoTT->translate(mid.data(), mid.size()); mid.resize(len); } MAlignmentRow row(ExportUtils::genUniqueName(names, c->getSequenceGObject()->getGObjectName()), mid); names.insert(row.getName()); rows.append(row); } } ma.setAlphabet(al); foreach(const MAlignmentRow& row, rows) { ma.addRow(row); } return ""; } void ADVExportContext::selectionToAlignment(const QString& title, bool annotations, bool translate) { MAlignment ma(MA_OBJECT_NAME); QString err = annotations ? prepareMAFromAnnotations(ma, translate) : prepareMAFromSequences(ma, translate); if (!err.isEmpty()) { QMessageBox::critical(NULL, L10N::errorTitle(), err); return; } DocumentFormatConstraints c; c.addFlagToSupport(DocumentFormatFlag_SupportWriting); c.supportedObjectTypes += GObjectTypes::MULTIPLE_ALIGNMENT; ExportSequences2MSADialog d(view->getWidget()); d.setWindowTitle(title); d.setOkButtonText(tr("Create alignment")); d.setFileLabelText(tr("Save alignment to file")); int rc = d.exec(); if (rc != QDialog::Accepted) { return; } Task* t = ExportUtils::wrapExportTask(new ExportAlignmentTask(ma, d.url, d.format), d.addToProjectFlag); AppContext::getTaskScheduler()->registerTopLevelTask(t); } void ADVExportContext::sl_saveSelectedAnnotationsToAlignment() { selectionToAlignment(annotationsToAlignmentAction->text(), true, false); } void ADVExportContext::sl_saveSelectedAnnotationsToAlignmentWithTranslation() { selectionToAlignment(annotationsToAlignmentAction->text(), true, true); } void ADVExportContext::sl_saveSelectedSequenceToAlignment() { selectionToAlignment(sequenceToAlignmentAction->text(), false, false); } void ADVExportContext::sl_saveSelectedSequenceToAlignmentWithTranslation() { selectionToAlignment(sequenceToAlignmentWithTranslationAction->text(), false, true); } void ADVExportContext::sl_getSequenceByDBXref() { const QList& selection = view->getAnnotationsSelection()->getSelection(); QStringList genbankID ; foreach(const AnnotationSelectionData &sel, selection) { Annotation* ann = sel.annotation; QString tmp = ann->findFirstQualifierValue("db_xref"); if(!tmp.isEmpty()) { genbankID << tmp.split(":").last(); } } QString listId = genbankID.join(","); fetchSequencesFromRemoteDB(listId); } void ADVExportContext::sl_getSequenceByAccession() { const QList& selection = view->getAnnotationsSelection()->getSelection(); QStringList genbankID ; foreach(const AnnotationSelectionData &sel, selection) { Annotation* ann = sel.annotation; QString tmp = ann->findFirstQualifierValue("accession"); if(!tmp.isEmpty()) { genbankID << tmp; } } QString listId = genbankID.join(","); fetchSequencesFromRemoteDB(listId); } void ADVExportContext::sl_getSequenceById() { const QList& selection = view->getAnnotationsSelection()->getSelection(); QStringList genbankID ; foreach(const AnnotationSelectionData &sel, selection) { Annotation* ann = sel.annotation; QString tmp = ann->findFirstQualifierValue("id"); if(!tmp.isEmpty()) { int off = tmp.indexOf("|"); int off1 = tmp.indexOf("|", off + 1); genbankID << tmp.mid(off + 1, off1 - off - 1); } } QString listId = genbankID.join(","); fetchSequencesFromRemoteDB(listId); } void ADVExportContext::fetchSequencesFromRemoteDB(const QString & listId) { // const QList& selection = view->getAnnotationsSelection()->getSelection(); // AnnotationTableObject *ao = selection.first().annotation->getGObject(); DNAAlphabet* seqAl = view->getSequenceObjectsWithContexts().first()->getAlphabet(); QString db; if(seqAl->getId() == BaseDNAAlphabetIds::NUCL_DNA_DEFAULT()) { db = "NCBI GenBank (DNA sequence)"; } else if(seqAl->getId() == BaseDNAAlphabetIds::AMINO_DEFAULT()) { db = "NCBI protein sequence database"; } else { return; } GetSequenceByIdDialog dlg(view->getWidget()); if(dlg.exec() == QDialog::Accepted) { QString dir = dlg.getDirectory(); Task *t; if(dlg.isAddToProject()) { t = new LoadRemoteDocumentAndOpenViewTask(listId, db, dir); } else { t = new LoadRemoteDocumentTask(listId, db, dir); } AppContext::getTaskScheduler()->registerTopLevelTask(t); } } } //namespace ugene-1.9.8/src/plugins/dna_export/src/ExportMSA2MSADialog.cpp0000644000175000017500000000636211651544322022617 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "ExportMSA2MSADialog.h" #include #include #include #include #include #include #include #include #include #include #include namespace U2 { ExportMSA2MSADialog::ExportMSA2MSADialog(const QString& defaultFileName, const DocumentFormatId& f, bool wholeAlignmentOnly, QWidget* p): QDialog(p) { setupUi(this); addToProjectFlag = true; SaveDocumentGroupControllerConfig conf; conf.dfc.addFlagToSupport(DocumentFormatFlag_SupportWriting); conf.dfc.supportedObjectTypes+=GObjectTypes::MULTIPLE_ALIGNMENT; conf.fileDialogButton = fileButton; conf.formatCombo = formatCombo; conf.fileNameEdit = fileNameEdit; conf.parentWidget = this; conf.defaultFileName = defaultFileName; conf.defaultFormatId = f; conf.saveTitle = tr("Export alignment"); saveContoller = new SaveDocumentGroupController(conf, this); DNAAlphabet* al = AppContext::getDNAAlphabetRegistry()->findById(BaseDNAAlphabetIds::NUCL_DNA_DEFAULT()); DNATranslationRegistry* tr = AppContext::getDNATranslationRegistry(); QList aminoTs = tr->lookupTranslation(al, DNATranslationType_NUCL_2_AMINO); assert(!aminoTs.empty()); foreach(DNATranslation* t, aminoTs) { translationCombo->addItem(t->getTranslationName()); tableID.append(t->getTranslationId()); } translationTable = tableID[translationCombo->currentIndex()]; connect(exportButton, SIGNAL(clicked()), SLOT(sl_exportClicked())); rangeGroupBox->setDisabled(wholeAlignmentOnly); int height = layout()->minimumSize().height(); setMaximumHeight(height); } void ExportMSA2MSADialog::updateModel(){ formatId = saveContoller->getFormatIdToSave(); file = saveContoller->getSaveFileName(); translationTable = tableID[translationCombo->currentIndex()]; addToProjectFlag = addDocumentButton->isChecked(); exportWholeAlignment = wholeRangeButton->isChecked(); } void ExportMSA2MSADialog::sl_exportClicked() { if (fileNameEdit->text().isEmpty()) { QMessageBox::warning(this, L10N::warningTitle(), tr("File is empty")); fileNameEdit->setFocus(); return; } updateModel(); accept(); } }//namespace ugene-1.9.8/src/plugins/dna_export/src/ExportMSA2SequencesDialog.cpp0000644000175000017500000000442211651544322024125 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "ExportMSA2SequencesDialog.h" #include #include #include #include #include #include #include #include #define SETTINGS_ROOT QString("dna_export/") namespace U2 { ExportMSA2SequencesDialog::ExportMSA2SequencesDialog(QWidget* p): QDialog(p) { setupUi(this); trimGapsFlag = false; addToProjectFlag = true; SaveDocumentGroupControllerConfig conf; conf.dfc.addFlagToExclude(DocumentFormatFlag_SingleObjectFormat); conf.dfc.addFlagToSupport(DocumentFormatFlag_SupportWriting); conf.dfc.supportedObjectTypes+=GObjectTypes::SEQUENCE; conf.fileDialogButton = fileButton; conf.formatCombo = formatCombo; conf.fileNameEdit = fileNameEdit; conf.parentWidget = this; conf.defaultFormatId = BaseDocumentFormats::PLAIN_FASTA; saveContoller = new SaveDocumentGroupController(conf, this); } void ExportMSA2SequencesDialog::accept() { if (fileNameEdit->text().isEmpty()) { QMessageBox::critical(this, L10N::errorTitle(), tr("File name is empty!")); return; } url = saveContoller->getSaveFileName(); format = saveContoller->getFormatIdToSave(); trimGapsFlag = trimGapsRB->isChecked(); addToProjectFlag = addToProjectBox->isChecked(); QDialog::accept(); } }//namespace ugene-1.9.8/src/plugins/dna_export/src/ImportQualityScoresWorker.h0000644000175000017500000000421611651544322024067 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _IMPORT_PHRED_QUALITY_WORKER_H_ #define _IMPORT_PHRED_QUALITY_WORKER_H_ #include #include #include "ImportQualityScoresTask.h" namespace U2 { class DNASequenceObject; namespace LocalWorkflow { class ImportPhredQualityPrompter : public PrompterBase { Q_OBJECT public: ImportPhredQualityPrompter(Actor* p = 0) : PrompterBase(p) {} protected: QString composeRichDoc(); }; class ImportPhredQualityWorker : public BaseWorker { Q_OBJECT public: ImportPhredQualityWorker(Actor* a); virtual void init(); virtual bool isReady(); virtual Task* tick(); virtual bool isDone(); virtual void cleanup(); private slots: void sl_taskFinished(); protected: CommunicationChannel *input, *output; QString resultName,transId; ImportQualityScoresConfig cfg; QList seqObjs; }; class ImportPhredQualityWorkerFactory : public DomainFactory { public: static const QString ACTOR_ID; static void init(); ImportPhredQualityWorkerFactory() : DomainFactory(ACTOR_ID) {} virtual Worker* createWorker(Actor* a) {return new ImportPhredQualityWorker(a);} }; } // Workflow namespace } // U2 namespace #endif // _IMPORT_PHRED_QUALITY_WORKER_H_ ugene-1.9.8/src/plugins/dna_export/src/ImportQualityScoresWorker.cpp0000644000175000017500000001634011651544322024423 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "ImportQualityScoresWorker.h" /* TRANSLATOR U2::LocalWorkflow::ImportPhredQualityWorker */ namespace U2 { namespace LocalWorkflow { /************************************* * ImportPhredQualityWorkerFactory *************************************/ const QString ImportPhredQualityWorkerFactory::ACTOR_ID("import-phred-qualities"); const QString QUALITY_TYPE_ATTR("quality-format"); void ImportPhredQualityWorkerFactory::init() { QList p; QList a; Descriptor ind(BasePorts::IN_SEQ_PORT_ID(), ImportPhredQualityWorker::tr("DNA sequences"), ImportPhredQualityWorker::tr("The PHRED scores will be imported to these sequences")); Descriptor oud(BasePorts::OUT_SEQ_PORT_ID(), ImportPhredQualityWorker::tr("DNA sequences with imported qualities"), ImportPhredQualityWorker::tr("These sequences have quality scores.")); QMap inM; inM[BaseSlots::DNA_SEQUENCE_SLOT()] = BaseTypes::DNA_SEQUENCE_TYPE(); p << new PortDescriptor(ind, DataTypePtr(new MapDataType("import.qual.in", inM)), true /*input*/); QMap outM; outM[BaseSlots::DNA_SEQUENCE_SLOT()] = BaseTypes::DNA_SEQUENCE_TYPE(); p << new PortDescriptor(oud, DataTypePtr(new MapDataType("import.qual.out", outM)), false /*input*/, true /*multi*/); Descriptor qualUrl(BaseAttributes::URL_IN_ATTRIBUTE().getId(), ImportPhredQualityWorker::tr("PHRED input"), ImportPhredQualityWorker::tr("Path to file with PHRED quality scores.")); Descriptor qualType(QUALITY_TYPE_ATTR, ImportPhredQualityWorker::tr("Quality format"), ImportPhredQualityWorker::tr("Choose format to encode quality scores.")); a << new Attribute(qualUrl, BaseTypes::STRING_TYPE(), true /*required*/, QString()); a << new Attribute(qualType, BaseTypes::STRING_TYPE(), false/*required*/, DNAQuality::getDNAQualityNameByType(DNAQualityType_Sanger) ); Descriptor desc(ACTOR_ID, ImportPhredQualityWorker::tr("Import PHRED qualities"), ImportPhredQualityWorker::tr("Add corresponding PHRED quality scores to the sequences.\nYou can use this worker to convert .fasta and .qual pair to fastq format")); ActorPrototype* proto = new IntegralBusActorPrototype(desc, p, a); QMap delegates; delegates[BaseAttributes::URL_IN_ATTRIBUTE().getId()] = new URLDelegate(DialogUtils::prepareDocumentsFileFilter(true), QString(), true); QVariantMap m; QStringList qualFormats = DNAQuality::getDNAQualityTypeNames(); foreach( const QString& name, qualFormats ) { m[name] = name; } delegates[QUALITY_TYPE_ATTR] = new ComboBoxDelegate(m); proto->setEditor(new DelegateEditor(delegates)); proto->setPrompter(new ImportPhredQualityPrompter()); WorkflowEnv::getProtoRegistry()->registerProto(BaseActorCategories::CATEGORY_BASIC(), proto); DomainFactory* localDomain = WorkflowEnv::getDomainRegistry()->getById(LocalDomainFactory::ID); localDomain->registerEntry(new ImportPhredQualityWorkerFactory()); } /************************************* * ImportPhredQualityPrompter *************************************/ QString ImportPhredQualityPrompter::composeRichDoc() { IntegralBusPort* input = qobject_cast(target->getPort(BasePorts::IN_SEQ_PORT_ID())); Actor* producer = input->getProducer(BasePorts::IN_SEQ_PORT_ID()); QString producerName = producer ? tr(" from %1").arg(producer->getLabel()) : ""; QString qualUrl = getParameter(BaseAttributes::URL_IN_ATTRIBUTE().getId()).toString(); QString qualSeq = (qualUrl.isEmpty() ? ""+tr("unset")+"" : QString("%1").arg(GUrl(qualUrl).fileName()) ); qualSeq = getHyperlink(BaseAttributes::URL_IN_ATTRIBUTE().getId(), qualSeq); QString doc = tr("Import PHRED quality scores in file %1 to the sequences %2 and send the sequences to the output.") .arg(qualSeq).arg(producerName); return doc; } /************************************* * ImportPhredQualityWorker *************************************/ ImportPhredQualityWorker::ImportPhredQualityWorker(Actor* a) : BaseWorker(a), input(NULL), output(NULL) { } void ImportPhredQualityWorker::init() { input = ports.value(BasePorts::IN_SEQ_PORT_ID()); output = ports.value(BasePorts::OUT_SEQ_PORT_ID()); cfg.fileName = actor->getParameter(BaseAttributes::URL_IN_ATTRIBUTE().getId())->getAttributeValue(); cfg.type = DNAQuality::getDNAQualityTypeByName( actor->getParameter(QUALITY_TYPE_ATTR)->getAttributeValue() ); } bool ImportPhredQualityWorker::isReady() { return (input && input->hasMessage()); } Task* ImportPhredQualityWorker::tick() { while (!input->isEnded()) { DNASequence dna = input->get().getData().toMap().value(BaseSlots::DNA_SEQUENCE_SLOT().getId()).value(); seqObjs.append(new DNASequenceObject(dna.getName(), dna)); } if( seqObjs.isEmpty() ) { algoLog.error( tr("Sequence list is empty.") ); return NULL; } Task* t = new ImportPhredQualityScoresTask(seqObjs, cfg); connect(t, SIGNAL(si_stateChanged()), SLOT(sl_taskFinished())); return t; } void ImportPhredQualityWorker::sl_taskFinished() { ImportPhredQualityScoresTask* t = qobject_cast(sender()); if (t->getState() != Task::State_Finished) { return; } foreach (DNASequenceObject* obj, seqObjs) { DNASequence dna = obj->getDNASequence(); QVariant v = qVariantFromValue(dna); output->put(Message(BaseTypes::DNA_SEQUENCE_TYPE(), v)); } if (input->isEnded()) { output->setEnded(); } algoLog.trace(tr("Import of qualities is finished.") ); } bool ImportPhredQualityWorker::isDone() { return !input || input->isEnded(); } void ImportPhredQualityWorker::cleanup() { qDeleteAll(seqObjs); } } //namespace LocalWorkflow } //namespace U2 ugene-1.9.8/src/plugins/dna_export/src/ExportSequenceTask.h0000644000175000017500000001137011651544322022467 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_EXPORT_SEQUENCE_PLUGIN_TASKS_H_ #define _U2_EXPORT_SEQUENCE_PLUGIN_TASKS_H_ #include "ExportTasks.h" namespace U2 { class DNAAlphabet; class DNATranslation; /** An item to export sequence. Contains unprocessed sequence + annotations + info about required transformations */ class ExportSequenceItem { public: ExportSequenceItem() : complTT(NULL), aminoTT(NULL), backTT(NULL){} DNASequence sequence; // the sequences to copy QList annotations;//annotations to copy DNATranslation* complTT; // complement translations for a sequence. Used only if 'strand' is 'compl' or 'both' DNATranslation* aminoTT; // amino translation for a sequence. If not NULL -> sequence is translated DNATranslation* backTT; // nucleic translation for a sequence. If not NULL -> sequence is back translated }; class ExportSequenceTaskSettings { public: ExportSequenceTaskSettings() { merge = false; mergeGap = 0; strand = TriState_Yes; allAminoFrames = false; formatId = BaseDocumentFormats::PLAIN_FASTA; mostProbable = true; saveAnnotations = false; } QList items; // sequences to export QString fileName; // result file name bool merge; // if true -> multiple sequences are merged int mergeGap; // the gap between sequences if merged TriState strand; // Yes -> direct, No -> complement, Unknown -> Both bool allAminoFrames; // for every sequence and (every complement if needed) generates 3-frame amino translations bool mostProbable; // True - use most probable codon, False - use distribution according to frequency bool saveAnnotations; // Store available annotations for sequences into result file too DocumentFormatId formatId; }; /** Exports sequences a file */ class ExportSequenceTask: public AbstractExportTask { Q_OBJECT public: ExportSequenceTask(const ExportSequenceTaskSettings& s); void run(); virtual Document* getDocument() const {return doc.get();} private: std::auto_ptr doc; ExportSequenceTaskSettings config; }; ////////////////////////////////////////////////////////////////////////// // Task to export sequences under annotations class ExportSequenceAItem { public: ExportSequenceAItem() : aminoTT(NULL), complTT(NULL) {} DNASequence sequence; // sequence QList annotations; // annotated regions to be exported DNATranslation* aminoTT; // if not null -> sequence regions will be translated (0-frame only) DNATranslation* complTT; // if not null & annotation location is on complement strand - it will be rev-complemented }; class ExportAnnotationSequenceTaskSettings { public: QList items; // data to export ExportSequenceTaskSettings exportSequenceSettings; // extra configuration for ExportSequenceTask }; class ExportAnnotationSequenceSubTask : public Task{ Q_OBJECT public: ExportAnnotationSequenceSubTask(ExportAnnotationSequenceTaskSettings& s); void run(); private: ExportAnnotationSequenceTaskSettings& config; }; class ExportAnnotationSequenceTask : public AbstractExportTask { Q_OBJECT public: ExportAnnotationSequenceTask(const ExportAnnotationSequenceTaskSettings& s); virtual Document* getDocument() const {return exportSubTask->getDocument();} virtual QList onSubTaskFinished(Task* subTask); private: ExportAnnotationSequenceTaskSettings config; ExportAnnotationSequenceSubTask* extractSubTask; ExportSequenceTask* exportSubTask; }; }//namespace #endif ugene-1.9.8/src/plugins/dna_export/src/DNAExportPluginTests.cpp0000644000175000017500000002212511651544322023233 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include #include #include #include #include #include #include #include #include #include "ImportQualityScoresTask.h" #include "DNAExportPluginTests.h" namespace U2 { #define URL_ATTR "url" #define SEQLIST_ATTR "seq-list" #define NUCL_ALIGN_URL_ATTR "nucleic-url" #define EXP_ALIGN_URL_ATTR "exp-url" #define EXTRACT_ROWS_ATTR "rows" #define TRANS_TABLE_ATTR "trans-table" void GTest_ImportPhredQualityScoresTask::init(XMLTestFormat *tf, const QDomElement& el) { Q_UNUSED(tf); QString buf = el.attribute(SEQLIST_ATTR); if (buf.isEmpty()) { failMissingValue(SEQLIST_ATTR); return; } seqNameList = buf.split(","); if (seqNameList.count() == 0) { stateInfo.setError("No sequences are found."); return; } fileName = el.attribute(URL_ATTR); if (fileName.isEmpty()) { failMissingValue(URL_ATTR); } fileName = env->getVar("COMMON_DATA_DIR") + "/" + fileName; } void GTest_ImportPhredQualityScoresTask::prepare() { foreach(const QString& seqName, seqNameList) { GObject *obj = getContext(this, seqName); if(obj==NULL){ stateInfo.setError(QString("wrong sequence name: %1").arg(seqName)); return; } DNASequenceObject * mySequence = qobject_cast(obj); if(mySequence == NULL){ stateInfo.setError(QString("Can't cast to sequence from: %1").arg(obj->getGObjectName())); return; } seqList.append(mySequence); } ImportQualityScoresConfig cfg; cfg.createNewDocument = false; cfg.fileName = fileName; cfg.type = DNAQualityType_Sanger; Task* importTask = new ImportPhredQualityScoresTask(seqList, cfg); addSubTask(importTask); } void GTest_ExportNucleicToAminoAlignmentTask::init(XMLTestFormat *tf, const QDomElement& el) { Q_UNUSED(tf); QString buf; buf = el.attribute(NUCL_ALIGN_URL_ATTR); if (buf.isEmpty()) { failMissingValue(NUCL_ALIGN_URL_ATTR); return; } inputFile = buf; QTemporaryFile qtf(env->getVar("TEMP_DATA_DIR") + "/XXXXXX.aln"); if (qtf.open()) { outputFileName = qtf.fileName(); } else { stateInfo.setError(GTest::tr("Unable to create temporary file")); } buf = el.attribute(EXP_ALIGN_URL_ATTR); if (buf.isEmpty()) { failMissingValue(EXP_ALIGN_URL_ATTR); return; } expectedOutputFile = buf; buf = el.attribute(TRANS_TABLE_ATTR); if (buf.isEmpty()) { failMissingValue(TRANS_TABLE_ATTR); return; } bool ok; ok = false; transTable = buf.toInt(&ok); if (!ok || transTable < 0) { stateInfo.setError(GTest::tr("Invalid translation table num: %1").arg(buf)); return; } selectedRows = U2Region(); buf = el.attribute(EXTRACT_ROWS_ATTR); if (!buf.isEmpty()) { QStringList sl = buf.split(","); if (sl.size() != 2) { assert(0); return; } ok = false; int base = sl[0].toInt(&ok); if (!ok || base < 0) { stateInfo.setError(GTest::tr("Invalid base : %1").arg(sl[0])); return; } ok = false; int len = sl[1].toInt(&ok); if (!ok || len < 0) { stateInfo.setError(GTest::tr("Invalid base : %1").arg(sl[1])); return; } selectedRows = U2Region(base, len); } } void GTest_ExportNucleicToAminoAlignmentTask::prepare() { if (hasError()) { return; } Document* doc = getContext(this, inputFile); if (doc == NULL) { stateInfo.setError(GTest::tr("context not found %1").arg(inputFile)); return; } QList list = doc->findGObjectByType(GObjectTypes::MULTIPLE_ALIGNMENT); if (list.size() == 0) { stateInfo.setError(GTest::tr("container of object with type \"%1\" is empty").arg(GObjectTypes::MULTIPLE_ALIGNMENT)); return; } MAlignmentObject* alObj = qobject_cast(list.first()); srcAl = MAlignment(alObj->getMAlignment()); QList trans; QString trid = DNATranslationID(0); trid.replace("0", QString("%1").arg(transTable)); trans << AppContext::getDNATranslationRegistry()->lookupTranslation(trid); exportTask = new ExportMSA2MSATask(srcAl, selectedRows.length ? selectedRows.startPos : 0, selectedRows.length ? selectedRows.length : srcAl.getNumRows(), outputFileName, trans, BaseDocumentFormats::CLUSTAL_ALN); addSubTask(exportTask); } QList GTest_ExportNucleicToAminoAlignmentTask::onSubTaskFinished(Task* subTask) { Q_UNUSED(subTask); QList res; if (hasError() || subTask->hasError() || isCanceled()) { return res; } if (subTask == exportTask) { IOAdapterFactory* iof = AppContext::getIOAdapterRegistry()->getIOAdapterFactoryById(BaseIOAdapters::url2io(outputFileName)); resultLoadTask = new LoadDocumentTask(BaseDocumentFormats::CLUSTAL_ALN, outputFileName, iof); res << resultLoadTask; } else if (subTask == resultLoadTask) { Document* resdoc = resultLoadTask->getDocument(); if (resdoc == NULL) { stateInfo.setError(GTest::tr("context not found %1").arg(outputFileName)); return res; } QList reslist = resdoc->findGObjectByType(GObjectTypes::MULTIPLE_ALIGNMENT); if (reslist.size() == 0) { stateInfo.setError(GTest::tr("container of object with type \"%1\" is empty").arg(GObjectTypes::MULTIPLE_ALIGNMENT)); return res; } MAlignmentObject * resAlign = qobject_cast(reslist.first()); resAl = resAlign->getMAlignment(); } return res; } Task::ReportResult GTest_ExportNucleicToAminoAlignmentTask::report() { propagateSubtaskError(); if (hasError()) { return ReportResult_Finished; } Document* expdoc = getContext(this, expectedOutputFile); if (expdoc == NULL) { stateInfo.setError(GTest::tr("context not found %1").arg(expectedOutputFile)); return ReportResult_Finished; } QList explist = expdoc->findGObjectByType(GObjectTypes::MULTIPLE_ALIGNMENT); if (explist.size() == 0) { stateInfo.setError(GTest::tr("container of object with type \"%1\" is empty").arg(GObjectTypes::MULTIPLE_ALIGNMENT)); return ReportResult_Finished; } MAlignmentObject * expAlign = qobject_cast(explist.first()); MAlignment expAl = expAlign->getMAlignment(); if (resAl.getLength() != expAl.getLength()) { stateInfo.setError(GTest::tr("Unexpected alignment length %1, expected %2").arg(resAl.getLength()).arg(expAl.getLength())); return ReportResult_Finished; } if (resAl.getNumRows() != expAl.getNumRows()) { stateInfo.setError(GTest::tr("Unexpected alignment size %1, expected %2").arg(resAl.getNumRows()).arg(expAl.getNumRows())); return ReportResult_Finished; } QStringList resNames = resAl.getRowNames(); QStringList expNames = expAl.getRowNames(); for (int i = 0; i < resAl.getNumRows(); i++) { if (resNames[i] != expNames[i]) { stateInfo.setError(GTest::tr("Invalid name for row %1: %2, expected %3").arg(i+1).arg(resNames[i]).arg(expNames[i])); return ReportResult_Finished; } for (int j = 0; j < resAl.getLength(); j++) { if (resAl.charAt(i, j) != expAl.charAt(i, j)) { stateInfo.setError(GTest::tr("Invalid char at row %1 column %2: %3, expected %4").arg(i+1).arg(j+1).arg(resAl.charAt(i, j)).arg(expAl.charAt(i, j))); return ReportResult_Finished; } } } return ReportResult_Finished; } QList DNAExportPluginTests::createTestFactories() { QList factories; factories.append(GTest_ImportPhredQualityScoresTask::createFactory()); factories.append(GTest_ExportNucleicToAminoAlignmentTask::createFactory()); return factories; } } //namespace ugene-1.9.8/src/plugins/dna_export/src/CSVColumnConfiguration.h0000644000175000017500000000372011651544322023233 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_CSV_COLUMN_CONFIGURATION_H_ #define _U2_CSV_COLUMN_CONFIGURATION_H_ #include namespace U2 { enum ColumnRole { ColumnRole_Ignore, // ignore this column ColumnRole_Qualifier, // column will be mapped to a qualifier ColumnRole_Name, // name (or key) of the annotation ColumnRole_StartPos, // column will be mapped as start position ColumnRole_EndPos, // column will be mapped as end position ColumnRole_Length, // column will be mapped as length ColumnRole_ComplMark // column is a complement strand indicator }; class ColumnConfig { public: ColumnConfig() : role (ColumnRole_Ignore), startPositionOffset(0), endPositionIsInclusive(false) {} ColumnRole role; QString qualifierName; QString complementMark; int startPositionOffset; bool endPositionIsInclusive; void reset() { role = ColumnRole_Ignore; qualifierName.clear(); complementMark.clear(); startPositionOffset = 0; endPositionIsInclusive = false; } //TODO: support groups? }; }//namespace #endif ugene-1.9.8/src/plugins/dna_export/src/DNAExportPlugin.cpp0000644000175000017500000000750711651544322022217 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "DNAExportPlugin.h" #include "DNAExportPluginTests.h" #include "ExportProjectViewItems.h" #include "ExportSequenceViewItems.h" #include "ExportAlignmentViewItems.h" #include "ImportQualityScoresWorker.h" #include "WriteAnnotationsWorker.h" #include "DNASequenceGeneratorDialog.h" #include "GenerateDNAWorker.h" #include #include #include #include namespace U2 { extern "C" Q_DECL_EXPORT Plugin* U2_PLUGIN_INIT_FUNC() { DNAExportPlugin* plug = new DNAExportPlugin(); return plug; } DNAExportPlugin::DNAExportPlugin() : Plugin(tr("DNA export"), tr("Export and import support for DNA & protein sequences")) { if (AppContext::getMainWindow()) { services.push_back(new DNAExportService()); QAction* a = new QAction(tr("Generate Sequence..."), this); connect(a, SIGNAL(triggered()), SLOT(sl_generateSequence())); QMenu* toolsMenu = AppContext::getMainWindow()->getTopLevelMenu(MWMENU_TOOLS); toolsMenu->addAction(a); } //tests GTestFormatRegistry* tfr = AppContext::getTestFramework()->getTestFormatRegistry(); XMLTestFormat *xmlTestFormat = qobject_cast(tfr->findFormat("XML")); assert(xmlTestFormat!=NULL); GAutoDeleteList* l = new GAutoDeleteList(this); l->qlist = DNAExportPluginTests::createTestFactories(); foreach(XMLTestFactory* f, l->qlist) { bool res = xmlTestFormat->registerTestFactory(f); assert(res); Q_UNUSED(res); } LocalWorkflow::ImportPhredQualityWorkerFactory::init(); LocalWorkflow::WriteAnnotationsWorkerFactory::init(); LocalWorkflow::GenerateDNAWorkerFactory::init(); } void DNAExportPlugin::sl_generateSequence() { DNASequenceGeneratorDialog dlg; dlg.exec(); } ////////////////////////////////////////////////////////////////////////// // Service DNAExportService::DNAExportService() : Service(Service_DNAExport, tr("DNA export service"), tr("Export and import support for DNA & protein sequences"), QList() << Service_ProjectView) { projectViewController = NULL; sequenceViewController = NULL; alignmentViewController = NULL; } void DNAExportService::serviceStateChangedCallback(ServiceState oldState, bool enabledStateChanged) { Q_UNUSED(oldState); if (!enabledStateChanged) { return; } if (isEnabled()) { projectViewController = new ExportProjectViewItemsContoller(this); sequenceViewController = new ExportSequenceViewItemsController(this); sequenceViewController->init(); alignmentViewController = new ExportAlignmentViewItemsController(this); alignmentViewController->init(); } else { delete projectViewController; projectViewController = NULL; delete sequenceViewController; sequenceViewController = NULL; delete alignmentViewController; alignmentViewController = NULL; } } }//namespace ugene-1.9.8/src/plugins/dna_export/src/ExportProjectViewItems.h0000644000175000017500000000360211651544322023336 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_EXPORT_PROJECT_VIEW_ITEMS_H_ #define _U2_EXPORT_PROJECT_VIEW_ITEMS_H_ #include #include #include namespace U2 { class ExportProjectViewItemsContoller : public QObject { Q_OBJECT public: ExportProjectViewItemsContoller(QObject* p); private slots: void sl_addToProjectViewMenu(QMenu&); void sl_saveSequencesToSequenceFormat(); void sl_saveSequencesAsAlignment(); void sl_saveAlignmentAsSequences(); void sl_exportNucleicAlignmentToAmino(); void sl_importAnnotationsFromCSV(); void sl_exportChromatogramToSCF(); void sl_exportAnnotations(); private: void addExportMenu(QMenu& m); void addImportMenu(QMenu& m); QAction* exportSequencesToSequenceFormatAction; QAction* exportSequencesAsAlignmentAction; QAction* exportAlignmentAsSequencesAction; QAction* exportNucleicAlignmentToAminoAction; QAction* importAnnotationsFromCSVAction; QAction* exportDNAChromatogramAction; QAction* exportAnnotations2CSV; }; }//namespace #endif ugene-1.9.8/src/plugins/dna_export/src/WriteAnnotationsWorker.h0000644000175000017500000000430411651544322023373 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef __WRITE_ANNOTATIONS_WORKER_H_ #define __WRITE_ANNOTATIONS_WORKER_H_ #include #include #include namespace U2 { namespace LocalWorkflow { class WriteAnnotationsPrompter : public PrompterBase { Q_OBJECT public: WriteAnnotationsPrompter(Actor * p = NULL) : PrompterBase(p) {} protected: QString composeRichDoc(); }; // WriteAnnotationsPrompter class WriteAnnotationsWorker : public BaseWorker { Q_OBJECT public: WriteAnnotationsWorker(Actor * p) : BaseWorker(p), annotationsPort(NULL), done(false) {} ~WriteAnnotationsWorker(); virtual void init(); virtual bool isReady(); virtual Task * tick(); virtual bool isDone(); virtual void cleanup(); private: IntegralBus * annotationsPort; QList createdAnnotationObjects; QMap annotationsByUrl; bool done; }; // WriteAnnotationsWorker class WriteAnnotationsWorkerFactory : public DomainFactory { public: static const QString ACTOR_ID; WriteAnnotationsWorkerFactory() : DomainFactory(ACTOR_ID) {} static void init(); virtual Worker * createWorker(Actor* a); }; // WriteAnnotationsWorkerFactory } } // U2 #endif // __WRITE_ANNOTATIONS_WORKER_H_ ugene-1.9.8/src/plugins/dna_export/src/GenerateDNAWorker.cpp0000644000175000017500000003121211651544322022471 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "GenerateDNAWorker.h" #include "DNASequenceGenerator.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include namespace U2 { namespace LocalWorkflow { /************************** * GenerateDNAWorkerFactory **************************/ static const QString LENGHT_ATTR("length"); static const QString SEQ_NUM_ATTR("count"); static const QString CONTENT_ATTR("content"); static const QString REFERENCE_ATTR("reference-url"); static const QString A_PERCENT_ATTR("percent-a"); static const QString C_PERCENT_ATTR("percent-c"); static const QString G_PERCENT_ATTR("percent-g"); static const QString T_PERCENT_ATTR("percent-t"); static const QString ALGORITHM("algorithm"); static const QString WINDOW_SIZE("window-size"); static const QString GC_SKEW("gc-skew"); static const QString SEED("seed"); const QString GenerateDNAWorkerFactory::ACTOR_ID("generate-dna"); class ContentIds { public: static const QString REFERENCE; static const QString MANUAL; }; const QString ContentIds::REFERENCE("reference"); const QString ContentIds::MANUAL("manual"); void GenerateDNAWorkerFactory::init() { QList p; { Descriptor d(BasePorts::OUT_SEQ_PORT_ID(), GenerateDNAWorker::tr("Sequences"), GenerateDNAWorker::tr("Generated sequences")); QMap outM; outM[BaseSlots::DNA_SEQUENCE_SLOT()] = BaseTypes::DNA_SEQUENCE_TYPE(); p << new PortDescriptor(d, DataTypePtr(new MapDataType("random.sequence", outM)), false, true); } QList a; { Descriptor ld(LENGHT_ATTR, GenerateDNAWorker::tr("Length"), GenerateDNAWorker::tr("Length of the resulted sequence(s).")); Descriptor nd(SEQ_NUM_ATTR, GenerateDNAWorker::tr("Count"), GenerateDNAWorker::tr("Number of sequences to generate.")); Descriptor cd(CONTENT_ATTR, GenerateDNAWorker::tr("Content"), GenerateDNAWorker::tr("Specifies if the nucleotide content of generated sequence(s) will be taken from reference or specified manually (A, G, C, T parameters).")); Descriptor rd(REFERENCE_ATTR, GenerateDNAWorker::tr("Reference"), GenerateDNAWorker::tr("Path to the reference file (could be a sequence or an alignment).")); Descriptor apd(A_PERCENT_ATTR, GenerateDNAWorker::tr("A"), GenerateDNAWorker::tr("Adenine content.")); Descriptor cpd(C_PERCENT_ATTR, GenerateDNAWorker::tr("C"), GenerateDNAWorker::tr("Cytosine content.")); Descriptor gpd(G_PERCENT_ATTR, GenerateDNAWorker::tr("G"), GenerateDNAWorker::tr("Guanine content.")); Descriptor tpd(T_PERCENT_ATTR, GenerateDNAWorker::tr("T"), GenerateDNAWorker::tr("Thymine content.")); Descriptor alg(ALGORITHM, GenerateDNAWorker::tr("Algorithm"),GenerateDNAWorker::tr("Algorithm for generating.")); Descriptor wnd(WINDOW_SIZE, GenerateDNAWorker::tr("Window size"), GenerateDNAWorker::tr("Size of window where set content.")); Descriptor gcSkew(GC_SKEW, GenerateDNAWorker::tr("GC Skew"), GenerateDNAWorker::tr("GC Skew.")); Descriptor seed(SEED, GenerateDNAWorker::tr("Seed"), GenerateDNAWorker::tr("Value to initialize the random generator. " "By default (seed = -1) the generator is initialized with the system time.")); a << new Attribute(ld, BaseTypes::NUM_TYPE(), false, 1000); a << new Attribute(nd, BaseTypes::NUM_TYPE(), false, 1); a << new Attribute(seed, BaseTypes::NUM_TYPE(), false, -1); a << new Attribute(cd, BaseTypes::STRING_TYPE(), false, ContentIds::MANUAL); a << new Attribute(alg, BaseTypes::STRING_TYPE(), false, "GC Content"); a << new Attribute(wnd, BaseTypes::NUM_TYPE(), true, 1000); a << new Attribute(rd, BaseTypes::STRING_TYPE(), false); Attribute *aAttr = new Attribute(apd, BaseTypes::NUM_TYPE(), false, 25); Attribute *cAttr = new Attribute(cpd, BaseTypes::NUM_TYPE(), false, 25); Attribute *gAttr = new Attribute(gpd, BaseTypes::NUM_TYPE(), false, 25); Attribute *tAttr = new Attribute(tpd, BaseTypes::NUM_TYPE(), false, 25); aAttr->addRelation(ALGORITHM, "GC Content"); cAttr->addRelation(ALGORITHM, "GC Content"); gAttr->addRelation(ALGORITHM, "GC Content"); tAttr->addRelation(ALGORITHM, "GC Content"); a << aAttr; a << cAttr; a << gAttr; a << tAttr; Attribute *attr = new Attribute(gcSkew, BaseTypes::NUM_TYPE(), false, 0.25); attr->addRelation(ALGORITHM, "GC Skew"); a << attr; } QMap delegates; { QVariantMap lenMap; lenMap["minimum"] = 1; lenMap["maximum"] = INT_MAX; lenMap["suffix"] = L10N::suffixBp(); delegates[LENGHT_ATTR] = new SpinBoxDelegate(lenMap); QVariantMap countMap; countMap["minimum"] = 1; countMap["maximum"] = 99; delegates[SEQ_NUM_ATTR] = new SpinBoxDelegate(countMap); QVariantMap contentMap; contentMap[ContentIds::REFERENCE] = ContentIds::REFERENCE; contentMap[ContentIds::MANUAL] = ContentIds::MANUAL; delegates[CONTENT_ATTR] = new ComboBoxDelegate(contentMap); delegates[REFERENCE_ATTR] = new URLDelegate(DNASequenceGenerator::prepareReferenceFileFilter(), DNASequenceGenerator::ID); QVariantMap percentMap; percentMap["minimum"] = 0; percentMap["maximum"] = 100; percentMap["suffix"] = " %"; delegates[A_PERCENT_ATTR] = new SpinBoxDelegate(percentMap); delegates[C_PERCENT_ATTR] = new SpinBoxDelegate(percentMap); delegates[G_PERCENT_ATTR] = new SpinBoxDelegate(percentMap); delegates[T_PERCENT_ATTR] = new SpinBoxDelegate(percentMap); QVariantMap algMap; algMap["GC Content"] = "GC Content"; algMap["GC Skew"] = "GC Skew"; delegates[ALGORITHM] = new ComboBoxDelegate(algMap); QVariantMap gcMap; gcMap["minimum"] = -1; gcMap["maximum"] = 1; gcMap["singleStep"] = 0.01; delegates[GC_SKEW] = new DoubleSpinBoxDelegate(gcMap); QVariantMap seedMap; seedMap["minimum"] = -1; seedMap["maximum"] = 1000; seedMap["singleStep"] = 1; delegates[SEED] = new SpinBoxDelegate(seedMap); } Descriptor desc(ACTOR_ID, GenerateDNAWorker::tr("Generate DNA"), GenerateDNAWorker::tr("Generates random DNA sequences with given nucleotide content" " that can be specified manually or evaluated from the reference file.")); ActorPrototype* proto = new IntegralBusActorPrototype(desc, p, a); proto->setPrompter(new GenerateDNAPrompter()); proto->setEditor(new DelegateEditor(delegates)); WorkflowEnv::getProtoRegistry()->registerProto(BaseActorCategories::CATEGORY_STATISTIC(), proto); DomainFactory* localDomain = WorkflowEnv::getDomainRegistry()->getById(LocalDomainFactory::ID); localDomain->registerEntry(new GenerateDNAWorkerFactory()); } /************************** * GenerateDNAPrompter **************************/ QString GenerateDNAPrompter::composeRichDoc() { return tr("Generates random DNA sequence(s)"); } /************************** * GenerateDNAWorker **************************/ void GenerateDNAWorker::init() { done = false; ch = ports.value(BasePorts::OUT_SEQ_PORT_ID()); } bool GenerateDNAWorker::isReady() { return !isDone(); } Task* GenerateDNAWorker::tick() { done = true; DNASequenceGeneratorConfig cfg; cfg.sequenceName = "Sequence "; QString cs = actor->getParameter(CONTENT_ATTR)->getAttributeValue(); if (cs == ContentIds::REFERENCE) { cfg.useRef = true; } else if (cs == ContentIds::MANUAL) { cfg.useRef = false; } else { QString err = tr("Unexpected value of 'content' parameter"); return new FailTask(err); } cfg.seed = actor->getParameter(SEED)->getAttributeValue(); if (cfg.useRef) { cfg.refUrl = actor->getParameter(REFERENCE_ATTR)->getAttributeValue(); if (cfg.refUrl.isEmpty()) { QString err = tr("Reference url is not set."); return new FailTask(err); } } else { if(actor->getParameter(ALGORITHM)->getAttributeValue() == "GC Skew") { int percentA = qrand(); int percentC = qrand(); int percentT = qrand(); int percentG = qrand(); int sum = percentA + percentC + percentG + percentT; percentA = (float)percentA / sum * 100; percentG = (float)percentG / sum * 100; percentC = (float)percentC / sum * 100; percentT = (float)percentT / sum * 100; int CG = percentG + percentG; float gcSkew = actor->getParameter(GC_SKEW)->getAttributeValue(); percentC = (1 - gcSkew)* CG / 2; percentG = percentC + gcSkew * CG; if(percentC < 0 || percentC > 100 || percentG < 0 || percentG > 100) { return new FailTask("Wrong GC Skew value"); } cfg.content['A'] = percentA / 100.0; cfg.content['C'] = percentC / 100.0; cfg.content['G'] = percentG / 100.0; cfg.content['T'] = percentT / 100.0; } else { int percentA = actor->getParameter(A_PERCENT_ATTR)->getAttributeValue(); int percentC = actor->getParameter(C_PERCENT_ATTR)->getAttributeValue(); int percentG = actor->getParameter(G_PERCENT_ATTR)->getAttributeValue(); int percentT = actor->getParameter(T_PERCENT_ATTR)->getAttributeValue(); if (percentA<0 || percentC<0 || percentG<0 || percentT<0) { QString err = tr("Base content must be between 0 and 100"); return new FailTask(err); } int total = percentA + percentC + percentG + percentT; if (total > 100) { QString err = tr("Total content percentage is more than 100"); return new FailTask(err); } cfg.content['A'] = percentA / 100.0; cfg.content['C'] = percentC / 100.0; cfg.content['G'] = percentG / 100.0; cfg.content['T'] = percentT / 100.0; } cfg.alphabet = AppContext::getDNAAlphabetRegistry()->findById(BaseDNAAlphabetIds::NUCL_DNA_DEFAULT()); } cfg.length = actor->getParameter(LENGHT_ATTR)->getAttributeValue(); cfg.window = actor->getParameter(WINDOW_SIZE)->getAttributeValue(); if (cfg.length < 10) { QString err = "'length' parameter value must be not less than 10"; return new FailTask(err); } cfg.numSeqs = actor->getParameter(SEQ_NUM_ATTR)->getAttributeValue(); if (cfg.numSeqs < 1) { QString err = "Number of sequences to generate is less than 1"; return new FailTask(err); } // true is used when executed from the dialog window cfg.saveDoc = false; Task* t = new DNASequenceGeneratorTask(cfg); connect(new TaskSignalMapper(t), SIGNAL(si_taskFinished(Task*)), SLOT(sl_taskFinished(Task*))); return t; } bool GenerateDNAWorker::isDone() { return done; } void GenerateDNAWorker::sl_taskFinished(Task* t) { DNASequenceGeneratorTask* task = qobject_cast(t); if (ch) { foreach(DNASequence seq, task->getSequences()) { ch->put(Message(BaseTypes::DNA_SEQUENCE_TYPE(), qVariantFromValue(seq))); } ch->setEnded(); } } } //namespace LocalWorkflow } // U2 namespace ugene-1.9.8/src/plugins/dna_export/src/ExportSequencesDialog.cpp0000644000175000017500000002242011651544322023500 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "ExportSequencesDialog.h" #include #include #include #include #include #include #include #include #include #include #include #include #define SETTINGS_ROOT QString("dna_export/") namespace U2 { ExportSequencesDialog::ExportSequencesDialog(bool m, bool allowComplement, bool allowTranslation, bool allowBackTranslation, const QString& defaultFileName, const DocumentFormatId& id, QWidget* p) : QDialog(p) { setupUi(this); SaveDocumentGroupControllerConfig conf; conf.dfc.addFlagToExclude(DocumentFormatFlag_SingleObjectFormat); conf.dfc.addFlagToSupport(DocumentFormatFlag_SupportWriting); conf.dfc.supportedObjectTypes += GObjectTypes::SEQUENCE; conf.parentWidget = this; conf.fileNameEdit = fileNameEdit; conf.formatCombo = formatCombo; conf.fileDialogButton = fileButton; conf.defaultFormatId = id; conf.defaultFileName = defaultFileName; conf.saveTitle = tr("Export sequences"); saveGroupContoller = new SaveDocumentGroupController(conf, this); multiMode = m; strand = TriState_Yes; translate = false; translateAllFrames = false; addToProject = false; withAnnotationsBox->setEnabled(false); if (!allowComplement) { directStrandButton->setEnabled(false); complementStrandButton->setEnabled(false); bothStrandsButton->setEnabled(false); directStrandButton->setHidden(true); complementStrandButton->setHidden(true); bothStrandsButton->setHidden(true); } if (!allowTranslation) { translateButton->setEnabled(false); translateButton->setHidden(true); allTFramesButton->setHidden(true); } if (!allowTranslation && !allowComplement) { translationBox->setHidden(true); } if (!multiMode) { saveModeBox->setEnabled(false); //saveModeBox->setHidden(true); } if (!allowBackTranslation) { backTranslationBox->setHidden(true); } if (allowTranslation) { DNAAlphabet* al = AppContext::getDNAAlphabetRegistry()->findById(BaseDNAAlphabetIds::NUCL_DNA_DEFAULT()); DNATranslationRegistry* tr = AppContext::getDNATranslationRegistry(); QList aminoTs = tr->lookupTranslation(al, DNATranslationType_NUCL_2_AMINO); if (!aminoTs.empty()) { foreach(DNATranslation* t, aminoTs) { translationTableCombo->addItem(t->getTranslationName()); tableID.append(t->getTranslationId()); } } translationTable = tableID[translationTableCombo->currentIndex()]; } if (allowBackTranslation) { DNAAlphabet* al = AppContext::getDNAAlphabetRegistry()->findById(BaseDNAAlphabetIds::AMINO_DEFAULT()); DNATranslationRegistry* treg = AppContext::getDNATranslationRegistry(); QList nucleicTs = treg->lookupTranslation(al, DNATranslationType_AMINO_2_NUCL); QTreeWidget *tree = new QTreeWidget(); tree->setHeaderHidden(true); organismCombo->setModel(tree->model()); organismCombo->setView (tree); if (!nucleicTs.empty()) { tree->setSortingEnabled(false); foreach(DNATranslation* t, nucleicTs) { QStringList current = t->getTranslationId().split("/"); QString type = current[1]; QString text = t->getTranslationName(); int i, n = tree->topLevelItemCount(); for (i = 0; i < n; i++) { QTreeWidgetItem* gi = tree->topLevelItem(i); if (gi->text(0) == type) { QTreeWidgetItem* curr = new QTreeWidgetItem(gi); curr->setText(0, text); curr->setText(1, t->getTranslationId()); gi->addChild(curr); break; } } if (i == n) { QTreeWidgetItem* gi = new QTreeWidgetItem(tree); gi->setFlags(gi->flags() & ~Qt::ItemIsSelectable); gi->setText(0, type); tree->addTopLevelItem(gi); QTreeWidgetItem* curr = new QTreeWidgetItem(gi); curr->setText(0, text); curr->setText(1, t->getTranslationId()); gi->addChild(curr); gi->setExpanded(true); } } tree->sortItems(0, Qt::AscendingOrder); QTreeWidgetItem* def = new QTreeWidgetItem(tree); def->setText(0, tr("Select organism")); def->setFlags(def->flags() & ~Qt::ItemIsSelectable); tree->insertTopLevelItem(0, def); tree->setCurrentItem(def); organismCombo->setCurrentIndex(organismCombo->count()-1); } } formatId = id; connect(exportButton, SIGNAL(clicked()), SLOT(sl_exportClicked())); connect(translateButton, SIGNAL(clicked()), SLOT(sl_translationTableEnabler())); connect(translationTableButton, SIGNAL(clicked()), SLOT(sl_translationTableEnabler())); connect(formatCombo, SIGNAL(currentIndexChanged(int)), SLOT(sl_formatChanged(int))); int height = layout()->minimumSize().height(); setMaximumHeight(height); } void ExportSequencesDialog::sl_formatChanged(int) { //Q_UNUSED(index); QString text = saveGroupContoller->getFormatIdToSave(); DocumentFormatRegistry *dfr = AppContext::getDocumentFormatRegistry(); assert(dfr); if(dfr->getFormatById(text)->getSupportedObjectTypes().contains(GObjectTypes::ANNOTATION_TABLE)) { //if(text == BaseDocumentFormats::PLAIN_GENBANK) { withAnnotationsBox->setEnabled(true); } else { withAnnotationsBox->setEnabled(false); } } void ExportSequencesDialog::updateModel() { strand = directStrandButton->isChecked() ? TriState_Yes : complementStrandButton->isChecked() ? TriState_No : TriState_Unknown; translate = translateButton->isChecked(); translateAllFrames = allTFramesButton->isVisible() && allTFramesButton->isChecked(); addToProject = addToProjectBox->isChecked(); merge = mergeButton->isChecked(); mergeGap = merge ? mergeSpinBox->value() : 0; file = fileNameEdit->text(); QFileInfo fi(file); if( fi.isRelative() ) { // save it in root sequence directory file = QFileInfo(saveGroupContoller->getDefaultFileName()).absoluteDir().absolutePath() + "/" + file; } formatId = saveGroupContoller->getFormatIdToSave(); useSpecificTable = translationTableButton->isChecked(); if (translate) { translationTable = tableID[translationTableCombo->currentIndex()]; } backTranslate = backTranslateButton->isChecked(); if (backTranslate) { QTreeWidget *tree = (QTreeWidget *)organismCombo->view(); QTreeWidgetItem *current = tree->currentItem(); translationTable = current->text(1); } mostProbable = mostFrequentlyButton->isChecked(); withAnnotations = withAnnotationsBox->isChecked() && withAnnotationsBox->isEnabled(); } void ExportSequencesDialog::sl_exportClicked() { if (fileNameEdit->text().isEmpty()) { QMessageBox::warning(this, L10N::warningTitle(), tr("File is empty")); fileNameEdit->setFocus(); return; } if (backTranslateButton->isChecked() && organismCombo->currentText().isEmpty()){ QMessageBox::warning(this, L10N::warningTitle(), tr("Organism for back translation not specified")); organismCombo->setFocus(); return; } updateModel(); accept(); } void ExportSequencesDialog::sl_translationTableEnabler() { if (translateButton->isChecked() && translationTableButton->isChecked()) { emit translationTableCombo->setEnabled(true); } else { emit translationTableCombo->setEnabled(false); } } void ExportSequencesDialog::disableAllFramesOption(bool v) { allTFramesButton->setHidden(v); } void ExportSequencesDialog::disableStrandOption(bool v) { directStrandButton->setDisabled(v); complementStrandButton->setDisabled(v); bothStrandsButton->setDisabled(v); } void ExportSequencesDialog::disableAnnotationsOption(bool v) { withAnnotationsBox->setDisabled(v); } }//namespace ugene-1.9.8/src/plugins/dna_export/src/ExportAnnotationsDialog.h0000644000175000017500000000325111651544322023510 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_EXPORT_ANNOTATIONS_2_CSV_DIALOG_H_ #define _U2_EXPORT_ANNOTATIONS_2_CSV_DIALOG_H_ #include #include namespace U2 { class ExportAnnotationsDialog : public QDialog, public Ui::ExportAnnotationsDialog { Q_OBJECT Q_DISABLE_COPY(ExportAnnotationsDialog) public: static const QString CSV_FORMAT_ID; public: explicit ExportAnnotationsDialog(const QString & filename, QWidget *parent); QString filePath()const; bool exportSequence()const; void setExportSequenceVisible(bool value); QString fileFormat()const; protected: virtual void changeEvent(QEvent *e); private slots: void sl_onChooseFileButtonClicked(); void sl_onFormatChanged(const QString &); private: QList supportedFormatsExts; }; } // namespace U2 #endif ugene-1.9.8/src/plugins/dna_export/src/CSVColumnConfigurationDialog.cpp0000644000175000017500000000771611651544322024717 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "CSVColumnConfigurationDialog.h" #include #include #include "QtGui/QMessageBox" namespace U2 { CSVColumnConfigurationDialog::CSVColumnConfigurationDialog(QWidget* w, const ColumnConfig& _config) : QDialog(w), config(_config) { setupUi(this); connect(complMarkRB, SIGNAL(toggled(bool)), SLOT(sl_complMarkToggle(bool))); connect(startRB, SIGNAL(toggled(bool)), SLOT(sl_startToggle(bool))); switch(config.role) { case ColumnRole_Ignore: ignoreRB->setChecked(true); break; case ColumnRole_Name: nameRB->setChecked(true); break; case ColumnRole_Qualifier: qualifierRB->setChecked(true); qualifierNameEdit->setText(config.qualifierName); break; case ColumnRole_StartPos: startRB->setChecked(true); startOffsetCheck->setChecked(config.startPositionOffset!=0); startOffsetValue->setValue(config.startPositionOffset); break; case ColumnRole_EndPos: endRB->setChecked(true); endInclusiveCheck->setChecked(config.endPositionIsInclusive); break; case ColumnRole_Length: lengthRB->setChecked(true); break; case ColumnRole_ComplMark: complMarkRB->setChecked(true); complValueEdit->setText(config.complementMark); complValueCheck->setChecked(!config.complementMark.isEmpty()); break; default: assert(0); } } void CSVColumnConfigurationDialog::accept() { config.reset(); if (startRB->isChecked()) { config.role = ColumnRole_StartPos; config.startPositionOffset = startOffsetCheck->isChecked() ? startOffsetValue->value() : 0; } else if (endRB->isChecked()) { config.role = ColumnRole_EndPos; config.endPositionIsInclusive = endInclusiveCheck->isChecked(); } else if (lengthRB->isChecked()) { config.role = ColumnRole_Length; } else if (qualifierRB->isChecked()) { config.role = ColumnRole_Qualifier; config.qualifierName = qualifierNameEdit->text(); if (!Annotation::isValidQualifierName(config.qualifierName)) { QMessageBox::critical(this, L10N::errorTitle(), tr("Invalid qualifier name!")); qualifierNameEdit->setFocus(); return; } } else if (nameRB->isChecked()) { config.role = ColumnRole_Name; } else if (complMarkRB->isChecked()) { config.role = ColumnRole_ComplMark; config.complementMark = complValueCheck->isChecked() ? complValueEdit->text() : QString(); } else { assert(ignoreRB->isChecked()); } QDialog::accept(); } void CSVColumnConfigurationDialog::sl_complMarkToggle(bool checked) { complValueCheck->setEnabled(checked); complValueEdit->setEnabled(checked && complValueCheck->isChecked()); } void CSVColumnConfigurationDialog::sl_startToggle(bool checked) { startOffsetCheck->setEnabled(checked); startOffsetValue->setEnabled(checked && startOffsetCheck->isChecked()); } } //namespace ugene-1.9.8/src/plugins/dna_export/src/DNASequenceGenerator.h0000644000175000017500000001016111651544322022631 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_DNA_SEQUENCE_GENERATOR_H_ #define _U2_DNA_SEQUENCE_GENERATOR_H_ #include #include namespace U2 { class GObject; class Document; class MAlignment; class DNAAlphabet; class DocumentFormat; class LoadDocumentTask; class SaveDocumentTask; class DNASequenceGeneratorConfig { public: DNASequenceGeneratorConfig() : addToProj(false), saveDoc(true), format(NULL), alphabet(NULL), length(0), numSeqs(1), useRef(true) {} DNAAlphabet* getAlphabet() const { assert(alphabet); return alphabet; } bool useReference() const { return useRef; } const QString& getReferenceUrl() const { return refUrl; } const QMap& getContent() const { return content; } int getLength() const { return length; } int getNumberOfSequences() const { return numSeqs; } QString getSequenceName() const { return sequenceName; } QString getOutUrlString() const { return outUrl; } DocumentFormat* getDocumentFormat() const { return format; } bool addToProj; bool saveDoc; // output url QString outUrl; // output sequence base name QString sequenceName; // output document format DocumentFormat* format; // output sequence alphabet DNAAlphabet* alphabet; // output sequence length int length; // number of sequences to generate int numSeqs; // use content from reference or specified manually bool useRef; // reference file url QString refUrl; // char frequencies QMap content; //window size int window; //seed to initialize qrand int seed; }; class DNASequenceGenerator { public: static const QString ID; static QString prepareReferenceFileFilter(); static void generateSequence(const QMap& charFreqs, int length, QByteArray& result); static void evaluateBaseContent(const DNASequence& sequence, QMap& result); static void evaluateBaseContent(const MAlignment& ma, QMap& result); }; class EvaluateBaseContentTask : public Task { Q_OBJECT public: EvaluateBaseContentTask(GObject* obj); void run(); QMap getResult() const { return result; } DNAAlphabet* getAlphabet() const { return alp; } private: GObject* _obj; DNAAlphabet* alp; QMap result; }; class GenerateDNASequenceTask : public Task { Q_OBJECT public: GenerateDNASequenceTask(const QMap& baseContent_, int length_, int window_, int count_, int seed_); void run(); QList< QByteArray > getResult() const { return result; } private: QMap baseContent; int length; int window; int count; int seed; QList< QByteArray > result; }; class DNASequenceGeneratorTask : public Task { Q_OBJECT public: DNASequenceGeneratorTask(const DNASequenceGeneratorConfig& cfg_); QList onSubTaskFinished(Task* subTask); QList getSequences() const { return results; } private: static EvaluateBaseContentTask* createEvaluationTask(Document* doc, QString& err); private: DNASequenceGeneratorConfig cfg; LoadDocumentTask* loadRefTask; EvaluateBaseContentTask* evalTask; GenerateDNASequenceTask* generateTask; SaveDocumentTask* saveTask; QList results; }; } //namespace #endif ugene-1.9.8/src/plugins/dna_export/src/ExportUtils.cpp0000644000175000017500000000651411651544322021533 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include #include #include #include #include #include "ExportSequencesDialog.h" #include "ExportSequenceTask.h" #include "ExportUtils.h" namespace U2 { void ExportUtils::loadDNAExportSettingsFromDlg(ExportSequenceTaskSettings& s, const ExportSequencesDialog& d) { s.fileName = d.file; s.merge = d.merge; s.mergeGap = d.mergeGap; s.allAminoFrames = d.translateAllFrames; s.strand = d.strand; s.formatId = d.formatId; s.mostProbable = d.mostProbable; s.saveAnnotations = d.withAnnotations; } Task* ExportUtils::wrapExportTask(AbstractExportTask* t, bool addToProject) { if (!addToProject) { return t; } return new AddExportedDocumentAndOpenViewTask(t); } QString ExportUtils::genUniqueName(const QSet& names, QString prefix) { if (!names.contains(prefix)) { return prefix; } QString name = prefix; int i=0; do { if (!names.contains(name)) { break; } name = prefix + "_" + QString::number(++i); } while(true); return name; } Task * ExportUtils::saveAnnotationsTask(const QString & filepath, const DocumentFormatId & format, const QList & annList) { SaveDocFlags fl(SaveDoc_Roll); fl |= SaveDoc_DestroyAfter; IOAdapterFactory* iof = AppContext::getIOAdapterRegistry()->getIOAdapterFactoryById(BaseIOAdapters::url2io(filepath)); assert(iof != NULL); DocumentFormat * df = AppContext::getDocumentFormatRegistry()->getFormatById(format); assert(df != NULL); Document * doc = new Document(df, iof, filepath); doc->setLoaded(true); // object and annotations will be deleted when savedoc task will delete doc AnnotationTableObject * att = new AnnotationTableObject("exported_annotations"); bool setAttName = false; foreach(Annotation * a, annList) { if(!setAttName && a->getGObject() != NULL) { QString newName = a->getGObject()->getGObjectName(); assert(!newName.isEmpty()); att->setGObjectName(newName); setAttName = true; } QString groupName = a->getGroups().isEmpty() ? "" : a->getGroups().first()->getGroupName(); att->addAnnotation(new Annotation(a->data()), groupName); } att->setModified(false); doc->addObject(att); return new SaveDocumentTask(doc, fl, DocumentUtils::getNewDocFileNameExcludesHint()); } }//namespace ugene-1.9.8/src/plugins/dna_export/src/ExportAnnotationsDialog.cpp0000644000175000017500000001154211651544322024045 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include #include #include #include #include #include #include "ExportAnnotationsDialog.h" namespace U2 { const QString ExportAnnotationsDialog::CSV_FORMAT_ID("csv"); ExportAnnotationsDialog::ExportAnnotationsDialog(const QString & filename, QWidget *parent) : QDialog(parent) { setupUi(this); fileNameEdit->setText(filename); connect(chooseFileButton, SIGNAL(clicked()), SLOT(sl_onChooseFileButtonClicked())); DocumentFormatConstraints constr; QList supportedFormats; constr.supportedObjectTypes.insert(GObjectTypes::ANNOTATION_TABLE); constr.addFlagToSupport(DocumentFormatFlag_SupportWriting); supportedFormats = AppContext::getDocumentFormatRegistry()->selectFormats(constr); supportedFormats.append(CSV_FORMAT_ID); supportedFormatsExts.append(CSV_FORMAT_ID); foreach(const DocumentFormatId & fid, supportedFormats) { formatsBox->addItem(fid); if(fid != CSV_FORMAT_ID) { DocumentFormat * df = AppContext::getDocumentFormatRegistry()->getFormatById(fid); assert(df != NULL); supportedFormatsExts.append(df->getSupportedDocumentFileExtensions().first()); } } formatsBox->setCurrentIndex(formatsBox->findText(supportedFormats.first())); connect(formatsBox, SIGNAL(currentIndexChanged(const QString &)), SLOT(sl_onFormatChanged(const QString &))); sl_onFormatChanged(formatsBox->currentText()); } void ExportAnnotationsDialog::sl_onFormatChanged(const QString & newFormat) { exportSequenceCheck->setEnabled(newFormat == CSV_FORMAT_ID); QString ext("."); if(newFormat == CSV_FORMAT_ID) { ext.append(CSV_FORMAT_ID); } else { DocumentFormat * df = AppContext::getDocumentFormatRegistry()->getFormatById(newFormat); assert(df != NULL); ext.append(df->getSupportedDocumentFileExtensions().first()); } assert(!ext.isEmpty()); QFileInfo fi(fileNameEdit->text()); fileNameEdit->setText(QDir::cleanPath(fi.absoluteDir().absolutePath() + "/" + fi.completeBaseName() + ext)); } QString ExportAnnotationsDialog::filePath() const { return fileNameEdit->text(); } bool ExportAnnotationsDialog::exportSequence()const { return exportSequenceCheck->isChecked(); } void ExportAnnotationsDialog::changeEvent(QEvent *e) { QDialog::changeEvent(e); switch (e->type()) { case QEvent::LanguageChange: retranslateUi(this); break; default: break; } } void ExportAnnotationsDialog::sl_onChooseFileButtonClicked() { QString curFormatExt; { QString curFormat = formatsBox->currentText(); if(curFormat == CSV_FORMAT_ID) { curFormatExt = CSV_FORMAT_ID; } else { DocumentFormat * df = AppContext::getDocumentFormatRegistry()->getFormatById(curFormat); assert(df != NULL); curFormatExt = df->getSupportedDocumentFileExtensions().first(); } } QList formats(supportedFormatsExts); formats.removeAll(curFormatExt); formats.prepend(curFormatExt); QString fileFormats; for(int i = 0; i < formats.size(); ++i) { QString formatName = formats.at(i); fileFormats += formatName.toUpper() + " format (*." + formatName + ");;"; } fileFormats.append("All files (*)"); LastOpenDirHelper helper("ExportAnnotationsDialogHelperDomain"); helper.url = QFileDialog::getSaveFileName(this, tr("Select file to save annotations"), helper.dir, fileFormats, NULL, QFileDialog::DontConfirmOverwrite); if(!helper.url.isEmpty()) { fileNameEdit->setText(helper.url); sl_onFormatChanged(formatsBox->currentText()); } } void ExportAnnotationsDialog::setExportSequenceVisible( bool value ) { exportSequenceCheck->setVisible(value); } QString ExportAnnotationsDialog::fileFormat() const { return formatsBox->currentText(); } } // namespace U2 ugene-1.9.8/src/plugins/dna_export/src/GetSequenceByIdDialog.cpp0000644000175000017500000000446611651544322023335 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include #include #include #include "GetSequenceByIdDialog.h" #include #include #include namespace U2 { GetSequenceByIdDialog::GetSequenceByIdDialog(QWidget *w): QDialog(w) { setupUi(this); connect(toolButton, SIGNAL(clicked()), SLOT(sl_saveFilenameButtonClicked())); QString defaultPath = AppContext::getAppSettings()->getUserAppsSettings()->getDownloadDirPath(); directoryEdit->setText(defaultPath); dir = defaultPath; } const QString DOWNLOAD_REMOTE_FILE_DOMAIN = "DownloadRemoteFileDialog"; void GetSequenceByIdDialog::sl_saveFilenameButtonClicked() { LastOpenDirHelper lod(DOWNLOAD_REMOTE_FILE_DOMAIN); QString dirName = QFileDialog::getExistingDirectory(this, tr("Select directory to save"), lod.dir); if(!dirName.isEmpty()) { directoryEdit->setText(dirName); dir = dirName; } } void GetSequenceByIdDialog::accept() { if(dir.isEmpty()) { return; } QDir downloadDir(dir); if (!downloadDir.exists()) { if (QMessageBox::Yes == QMessageBox::question(this, windowTitle(), tr("Directory doesn't exist. Do you want to create it?"), QMessageBox::Yes, QMessageBox::No)) { downloadDir.mkpath(dir); } else { return; } } addToProject = addBox->isChecked(); QDialog::accept(); } }ugene-1.9.8/src/plugins/dna_export/src/ExportUtils.h0000644000175000017500000000311611651544322021173 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_EXPORT_UTILS_H_ #define _U2_EXPORT_UTILS_H_ #include namespace U2 { class Task; class ExportSequencesDialog; class ExportSequenceTaskSettings; class AbstractExportTask; class Annotation; class ExportUtils: public QObject { Q_OBJECT public: static void loadDNAExportSettingsFromDlg(ExportSequenceTaskSettings& s, const ExportSequencesDialog& d); static Task* wrapExportTask(AbstractExportTask* t, bool addToProject); // generates unique name using prefix + numbers static QString genUniqueName(const QSet& names, QString prefix); static Task * saveAnnotationsTask(const QString & filepath, const DocumentFormatId & format, const QList & annList); }; }//namespace #endif ugene-1.9.8/src/plugins/dna_export/src/ExportTasks.cpp0000644000175000017500000002507711651544322021525 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "ExportTasks.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include namespace U2 { ////////////////////////////////////////////////////////////////////////// // AddDocumentAndOpenViewTask AddExportedDocumentAndOpenViewTask::AddExportedDocumentAndOpenViewTask(AbstractExportTask* t) : Task("Export sequence to document", TaskFlags_NR_FOSCOE) { exportTask = t; addSubTask(exportTask); } QList AddExportedDocumentAndOpenViewTask::onSubTaskFinished( Task* subTask ) { QList subTasks; if (subTask == exportTask && !subTask->hasError()) { Document* doc = exportTask->getDocument(); const GUrl& fullPath = doc->getURL(); Project* prj = AppContext::getProject(); if (prj) { Document* sameURLdoc = prj->findDocumentByURL(fullPath); if (sameURLdoc) { taskLog.trace(tr("Document is already added to the project %1").arg(doc->getURL().getURLString())); subTasks << new LoadUnloadedDocumentAndOpenViewTask(sameURLdoc); return subTasks; } } DocumentFormat* format = doc->getDocumentFormat(); IOAdapterFactory * iof = doc->getIOAdapterFactory(); Document* clonedDoc = new Document(format, iof, fullPath); clonedDoc->loadFrom(doc); // doc was loaded in a separate thread -> clone all GObjects assert(!clonedDoc->isTreeItemModified()); assert(clonedDoc->isLoaded()); if (!clonedDoc->isStateLocked()) { clonedDoc->setModified(doc->isModified()); } subTasks << new AddDocumentTask(clonedDoc); subTasks << new LoadUnloadedDocumentAndOpenViewTask(clonedDoc); } //TODO: provide a report if subtask fails return subTasks; } ////////////////////////////////////////////////////////////////////////// // DNAExportAlignmentTask ExportAlignmentTask::ExportAlignmentTask(const MAlignment& _ma, const QString& _fileName, DocumentFormatId _f) : AbstractExportTask("", TaskFlag_None), ma(_ma), fileName(_fileName), format(_f) { GCOUNTER( cvar, tvar, "ExportAlignmentTask" ); setTaskName(tr("Export alignment to '%1'").arg(QFileInfo(fileName).fileName())); setVerboseLogMode(true); assert(!ma.isEmpty()); } void ExportAlignmentTask::run() { DocumentFormatRegistry* r = AppContext::getDocumentFormatRegistry(); DocumentFormat* f = r->getFormatById(format); IOAdapterFactory* iof = AppContext::getIOAdapterRegistry()->getIOAdapterFactoryById(BaseIOAdapters::url2io(fileName)); doc.reset(f->createNewDocument(iof, fileName)); doc->addObject(new MAlignmentObject(ma)); f->storeDocument(doc.get(), stateInfo); } ////////////////////////////////////////////////////////////////////////// // export alignment 2 sequence format ExportMSA2SequencesTask::ExportMSA2SequencesTask(const MAlignment& _ma, const QString& _url, bool _trimAli, DocumentFormatId _format) : AbstractExportTask(tr("Export alignment to sequence: %1").arg(_url), TaskFlag_None), ma(_ma), url(_url), trimAli(_trimAli), format(_format) { GCOUNTER( cvar, tvar, "ExportMSA2SequencesTask" ); setVerboseLogMode(true); } void ExportMSA2SequencesTask::run() { DocumentFormatRegistry* r = AppContext::getDocumentFormatRegistry(); DocumentFormat* f = r->getFormatById(format); IOAdapterFactory* iof = AppContext::getIOAdapterRegistry()->getIOAdapterFactoryById(BaseIOAdapters::url2io(url)); doc.reset(f->createNewDocument(iof, url)); QList lst = MSAUtils::ma2seq(ma, trimAli); QSet usedNames; foreach(const DNASequence& s, lst) { QString name = s.getName(); if (usedNames.contains(name)) { name = TextUtils::variate(name, " ", usedNames, false, 1); } doc->addObject(new DNASequenceObject(name, s)); usedNames.insert(name); } f->storeDocument(doc.get(), stateInfo); } ////////////////////////////////////////////////////////////////////////// // export nucleic alignment 2 amino alignment ExportMSA2MSATask::ExportMSA2MSATask(const MAlignment& _ma, int _offset, int _len, const QString& _url, const QList& _aminoTranslations, DocumentFormatId _format) : AbstractExportTask(tr("Export alignment to alignment: %1").arg(_url), TaskFlag_None), ma(_ma), offset(_offset), len(_len), url(_url), format(_format), aminoTranslations(_aminoTranslations) { GCOUNTER( cvar, tvar, "ExportMSA2MSATask" ); setVerboseLogMode(true); } void ExportMSA2MSATask::run() { DocumentFormatRegistry* r = AppContext::getDocumentFormatRegistry(); DocumentFormat* f = r->getFormatById(format); IOAdapterFactory* iof = AppContext::getIOAdapterRegistry()->getIOAdapterFactoryById(BaseIOAdapters::url2io(url)); doc.reset(f->createNewDocument(iof, url)); QList lst = MSAUtils::ma2seq(ma, true); QList res; for (int i = offset; i < offset + len; i++) { DNASequence& s = lst[i]; QString name = s.getName(); if (!aminoTranslations.isEmpty()) { DNATranslation* aminoTT = aminoTranslations.first(); name += "(translated)"; QByteArray seq = s.seq; int len = seq.length() / 3; QByteArray resseq(len, '\0'); if (resseq.isNull() && len != 0) { stateInfo.setError( tr("Out of memory") ); return; } assert(aminoTT->isThree2One()); aminoTT->translate(seq.constData(), seq.length(), resseq.data(), resseq.length()); resseq.replace("*","X"); DNASequence rs(name, resseq, aminoTT->getDstAlphabet()); res << new DNASequenceObject(name, rs); } else { res << new DNASequenceObject(name, s); } } MAlignment ma = MSAUtils::seq2ma(res, stateInfo); if (hasError()) { return; } doc->addObject(new MAlignmentObject(ma)); f->storeDocument(doc.get(), stateInfo); } ////////////////////////////////////////////////////////////////////////// // export chromatogram to SCF ExportDNAChromatogramTask::ExportDNAChromatogramTask( DNAChromatogramObject* _obj, const ExportChromatogramTaskSettings& _settings) : AbstractExportTask(tr("Export chromatogram to SCF"), TaskFlags_NR_FOSCOE), cObj(_obj), settings(_settings), loadTask(NULL) { GCOUNTER( cvar, tvar, "ExportDNAChromatogramTask" ); setVerboseLogMode(true); } void ExportDNAChromatogramTask::prepare() { Document* d = cObj->getDocument(); assert(d != NULL); if (d == NULL ) { stateInfo.setError("Chromatogram object document is not found!"); return; } QList relatedObjs = cObj->findRelatedObjectsByRole(GObjectRelationRole::SEQUENCE); assert(relatedObjs.count() == 1); if (relatedObjs.count() != 1) { stateInfo.setError("Sequence related to chromatogram is not found!"); } QString seqObjName = relatedObjs.first().ref.objName; GObject* resObj = d->findGObjectByName(seqObjName); DNASequenceObject * sObj = qobject_cast(resObj); assert(sObj != NULL); DNAChromatogram cd = cObj->getChromatogram(); DNASequence dna = sObj->getSequence(); if (settings.reverse) { TextUtils::reverse(dna.seq.data(), dna.seq.length()); reverseVector(cd.A); reverseVector(cd.C); reverseVector(cd.G); reverseVector(cd.T); int offset = 0; if (cObj->getDocument()->getDocumentFormatId() == BaseDocumentFormats::ABIF) { int baseNum = cd.baseCalls.count(); int seqLen = cd.seqLength; // this is required for base <-> peak correspondence if (baseNum > seqLen) { cd.baseCalls.remove(baseNum - 1); cd.prob_A.remove(baseNum - 1); cd.prob_C.remove(baseNum - 1); cd.prob_G.remove(baseNum - 1); cd.prob_T.remove(baseNum - 1); } } else if (cObj->getDocument()->getDocumentFormatId() == BaseDocumentFormats::SCF) { // SCF format particularities offset = -1; } for (int i = 0; i < cd.seqLength; ++i) { cd.baseCalls[i] = cd.traceLength - cd.baseCalls[i] + offset; } reverseVector(cd.baseCalls); reverseVector(cd.prob_A); reverseVector(cd.prob_C); reverseVector(cd.prob_G); reverseVector(cd.prob_T); } if (settings.complement) { DNATranslation* tr = AppContext::getDNATranslationRegistry()->lookupTranslation(BaseDNATranslationIds::NUCL_DNA_DEFAULT_COMPLEMENT); tr->translate(dna.seq.data(), dna.length()); qSwap(cd.A,cd.T); qSwap(cd.C, cd.G); qSwap(cd.prob_A, cd.prob_T); qSwap(cd.prob_C, cd.prob_G); } SCFFormat::exportDocumentToSCF(settings.url, cd, dna, stateInfo); if (stateInfo.hasError()) { return; } if (settings.loadDocument) { IOAdapterFactory* iof = AppContext::getIOAdapterRegistry()->getIOAdapterFactoryById(BaseIOAdapters::LOCAL_FILE); loadTask = new LoadDocumentTask(BaseDocumentFormats::SCF, settings.url, iof ); addSubTask( loadTask ); } } Document* ExportDNAChromatogramTask::getDocument() const { Document* doc = loadTask->getDocument(); return doc; } }//namespace ugene-1.9.8/src/plugins/dna_export/src/ui/0000755000175000017500000000000011651544322017134 5ustar ilyailyaugene-1.9.8/src/plugins/dna_export/src/ui/DNASequenceGeneratorDialog.ui0000644000175000017500000002662611651544322024571 0ustar ilyailya DNASequenceGeneratorDialog 0 0 576 350 Generate Sequence 0 0 Parameters 2 4 4 Length Qt::Horizontal 40 20 0 0 bp 1 2147483647 1000 Window size Qt::Horizontal 40 20 bp 1 2147483647 1000 Number of sequences Qt::Horizontal 40 20 0 0 1 Initialize random generator manually Qt::Horizontal 40 20 1000 0 0 Content Reference true 2 ... Manual 0 0 Configure... Qt::Horizontal 40 20 0 0 Output Output File 2 ... Format 0 0 0 0 Qt::LeftToRight Add to project true Qt::Vertical 20 0 Qt::Horizontal 40 20 Generate Cancel ugene-1.9.8/src/plugins/dna_export/src/ui/ImportAnnotationsFromCSVDialog.ui0000644000175000017500000003155311651544322025512 0ustar ilyailya ImportAnnotationsFromCSVDialog 0 0 685 677 Import annotations from CSV true File to read ... Results Result file ... File format Add result file to project true 0 0 Column separator File parsing Column separator true Qt::Horizontal 40 20 0 0 , Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter Guess Script Qt::Horizontal 78 20 Edit First lines to skip Qt::Horizontal 40 20 Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter Do not skip line(s) 1000 Skip all lines starts with the text Qt::Horizontal 68 20 0 0 # 30 Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter Interpret multiple separators like a single separator (try when separator is a whitespace character) Remove quotes true Default annotation name 0 0 misc_feature 30 Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter Results preview Qt::Horizontal 40 20 Preview 0 2 false false Raw file preview: Qt::Horizontal 40 20 0 1 true Qt::Horizontal 40 20 Run Cancel cancelButton clicked() ImportAnnotationsFromCSVDialog reject() 485 459 266 240 runButton clicked(bool) ImportAnnotationsFromCSVDialog accept() 541 579 334 300 ugene-1.9.8/src/plugins/dna_export/src/ui/ExportAnnotationsDialog.ui0000644000175000017500000000703111651544322024313 0ustar ilyailya U2::ExportAnnotationsDialog 0 0 465 131 Export annotations true Export to file: ... File format: Save sequences under annotations Qt::Vertical 20 40 Qt::Horizontal 40 20 Qt::Horizontal QDialogButtonBox::Cancel|QDialogButtonBox::Ok exportSequenceCheck buttonBox formatsBox horizontalSpacer buttonBox buttonBox accepted() U2::ExportAnnotationsDialog accept() 248 254 157 274 buttonBox rejected() U2::ExportAnnotationsDialog reject() 316 260 286 274 ugene-1.9.8/src/plugins/dna_export/src/ui/ExportSequencesDialog.ui0000644000175000017500000002662011651544322023756 0ustar ilyailya U2::ExportSequencesDialog 0 0 539 452 0 0 Export selected sequences true Export to file ... File format to use Export with annotations Add document to the project true Convertion options Save direct strand true Save complement strand Save both strands Translate to amino alphabet false Save all amino frames true false false Use custom translation table Back translation options Translate back to nucleic alphabet false Most frequently used codons true false Frequency distribution false Organism: false true Merge options Add gap symbols between sequences false Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter 100000 Merge sequences Save as separate sequences true Qt::Vertical 20 4 Qt::Horizontal 40 20 Export Cancel cancelButton clicked() U2::ExportSequencesDialog reject() 454 142 251 82 mergeButton toggled(bool) mergeSpinBox setEnabled(bool) 369 69 428 95 translateButton clicked(bool) allTFramesButton setEnabled(bool) 99 93 266 93 backTranslateButton clicked(bool) mostFrequentlyButton setEnabled(bool) 112 204 112 228 backTranslateButton clicked(bool) frequencyDistributionButton setEnabled(bool) 112 204 365 228 backTranslateButton clicked(bool) organismLabel setEnabled(bool) 112 204 112 252 backTranslateButton clicked(bool) organismCombo setEnabled(bool) 112 204 365 252 translateButton clicked(bool) translationTableButton setEnabled(bool) 100 139 100 160 ugene-1.9.8/src/plugins/dna_export/src/ui/BaseContentDialog.ui0000644000175000017500000002064011651544322023022 0ustar ilyailya BaseContentDialog 0 0 331 197 0 0 Set Base Content Base conetnt true 20 0 0 20 0 A 0 0 % 100 0 0 20 0 C 0 0 % 100 0 0 20 0 G 0 0 % 100 0 0 20 0 T 0 0 % 100 GC Skew -1.000000000000000 1.000000000000000 0.010000000000000 0.250000000000000 Qt::Horizontal 40 20 Qt::Vertical 0 0 4 Qt::Horizontal 40 20 Save Cancel canelButton clicked() BaseContentDialog reject() 177 261 162 156 ugene-1.9.8/src/plugins/dna_export/src/ui/ExportMSA2SequencesDialog.ui0000644000175000017500000001024311651544322024373 0ustar ilyailya U2::ExportMSA2SequencesDialog 0 0 416 195 Convert alignment to separate sequences true Export to file ... File format to use Add document to the project true Gap characters ('-') Keep true Trim Qt::Vertical 20 0 Qt::Horizontal 40 20 Export true Cancel cancelButton clicked() U2::ExportMSA2SequencesDialog reject() 198 233 199 149 okButton clicked() U2::ExportMSA2SequencesDialog accept() 115 233 199 149 ugene-1.9.8/src/plugins/dna_export/src/ui/ExportChromatogramDialog.ui0000644000175000017500000000773611651544322024455 0ustar ilyailya ExportChromatogramDialog 0 0 506 177 Export chromatogram file true Export to file ... File format to use Reversed false Complemented Add document to the project true Qt::Vertical 20 0 Qt::Horizontal 40 20 Export true Cancel cancelButton clicked() ExportChromatogramDialog reject() 198 233 199 149 okButton clicked() ExportChromatogramDialog accept() 115 233 199 149 ugene-1.9.8/src/plugins/dna_export/src/ui/ExportSequences2MSADialog.ui0000644000175000017500000000674711651544322024411 0ustar ilyailya U2::ExportSequences2MSADialog 0 0 483 126 Export sequences as alignment true Export to file ... File format to use Add document to the project true Qt::Vertical 20 0 Qt::Horizontal 40 20 Export true Cancel cancelButton clicked() U2::ExportSequences2MSADialog reject() 198 233 199 149 okButton clicked() U2::ExportSequences2MSADialog accept() 115 233 199 149 ugene-1.9.8/src/plugins/dna_export/src/ui/ExportMSA2MSADialog.ui0000644000175000017500000001040011651544322023053 0ustar ilyailya U2::ExportMSA2MSADialog 0 0 457 278 0 0 Dialog Export to file ... File format to use Amino translation Add document to the project true Export range Whole alignment true Selected rows Qt::Vertical QSizePolicy::Expanding 20 40 Qt::Horizontal 40 20 Export Cancel cancelButton clicked() U2::ExportMSA2MSADialog reject() 413 339 230 180 ugene-1.9.8/src/plugins/dna_export/src/ui/CSVColumnConfigurationDialog.ui0000644000175000017500000002015411651544322025156 0ustar ilyailya CSVColumnConfigurationDialog 0 0 425 296 Select the role of the column true Column role Annotation start position false Add offset false Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter bp -1000000000 1000000000 Annotation end position false Inclusive true Annotation length Complement strand mark false Mark value QFrame::Sunken Qt::Horizontal Annotation name Qualifier false Qt::Horizontal Ignore this column false Qt::Horizontal 250 5 Qt::Vertical 20 134 Qt::Horizontal 40 20 Ok Cancel cancelButton clicked() CSVColumnConfigurationDialog reject() 352 183 199 102 qualifierRB toggled(bool) qualifierNameEdit setEnabled(bool) 89 110 273 110 endRB toggled(bool) endInclusiveCheck setEnabled(bool) 89 63 273 63 startOffsetCheck toggled(bool) startOffsetValue setEnabled(bool) 218 41 328 41 okButton clicked() CSVColumnConfigurationDialog accept() 271 183 199 102 complValueCheck toggled(bool) complValueEdit setEnabled(bool) 256 113 355 113 ugene-1.9.8/src/plugins/dna_export/src/ui/GetSequenceByIdDialog.ui0000644000175000017500000000655011651544322023601 0ustar ilyailya getSequenceByIdDialog 0 0 350 150 Get sequences by ID The sequences from selected BLAST results will be downloaded from NCBI Genbank by their GI identifier Save to directctory: ... Add to project true Qt::Vertical 20 40 Qt::Horizontal 40 20 Qt::Horizontal QDialogButtonBox::Cancel|QDialogButtonBox::Ok buttonBox accepted() getSequenceByIdDialog accept() 248 254 157 274 buttonBox rejected() getSequenceByIdDialog reject() 316 260 286 274 ugene-1.9.8/src/plugins/dna_export/src/ImportAnnotationsFromCSVTask.h0000644000175000017500000000720011651544322024402 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_IMPORT_ANNOTATIONS_FROM_CSV_TASK_H_ #define _U2_IMPORT_ANNOTATIONS_FROM_CSV_TASK_H_ #include #include #include "CSVColumnConfiguration.h" #include namespace U2 { class DocumentFormat; // FIXME: implement splitToken as a default value for parsing script (i.e line.split()) class CSVParsingConfig { public: CSVParsingConfig() : defaultAnnotationName("misc_feature"), linesToSkip(0), keepEmptyParts(true), removeQuotes(true){} QString defaultAnnotationName; QString splitToken; int linesToSkip; QString prefixToSkip; bool keepEmptyParts; QList columns; QString parsingScript; bool removeQuotes; static QBitArray QUOTES; }; class ImportAnnotationsFromCSVTaskConfig { public: ImportAnnotationsFromCSVTaskConfig() : addToProject(true), df(NULL) {} QString csvFile; QString dstFile; bool addToProject; DocumentFormat* df; CSVParsingConfig parsingOptions; }; class ReadCSVAsAnnotationsTask; class SaveDocumentTask; class AddDocumentTask; class Annotation; class Document; class ImportAnnotationsFromCSVTask: public Task { Q_OBJECT public: ImportAnnotationsFromCSVTask(ImportAnnotationsFromCSVTaskConfig& config); QList onSubTaskFinished(Task* subTask); private: QList prepareAnnotations() const; Document* prepareNewDocument(const QList& annotations) const; ImportAnnotationsFromCSVTaskConfig config; ReadCSVAsAnnotationsTask* readTask; SaveDocumentTask* writeTask; AddDocumentTask* addTask; QPointer doc; }; class ReadCSVAsAnnotationsTask : public Task { Q_OBJECT public: ReadCSVAsAnnotationsTask(const QString& file, const CSVParsingConfig& config); void run(); QList getResult() const {return result;} static QList parseLinesIntoTokens(const QString& text, const CSVParsingConfig& config, int& maxColumns, TaskStateInfo& ti); static QStringList parseLineIntoTokens(const QString& line, const CSVParsingConfig& config, TaskStateInfo& ti, int lineNum = 1); static QString guessSeparatorString(const QString& text, const CSVParsingConfig& config); // script variable that holds line value static QString LINE_VAR; // script variable that holds parsed line numbers. Lines that skipped to not increment this value static QString LINE_NUM_VAR; private: QString file; CSVParsingConfig config; QList result; }; } // namespace U2 #endif ugene-1.9.8/src/plugins/dna_export/src/ExportMSA2MSADialog.h0000644000175000017500000000311111651544322022251 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_EXPORT_MSA_TO_MSA_DIALOG_H_ #define _U2_EXPORT_MSA_TO_MSA_DIALOG_H_ #include #include #include namespace U2 { class SaveDocumentGroupController; class ExportMSA2MSADialog : public QDialog, Ui_ExportMSA2MSADialog { Q_OBJECT public: ExportMSA2MSADialog(const QString& defaultFileName, const DocumentFormatId& f, bool wholeAlignmentOnly, QWidget* p); void updateModel(); DocumentFormatId formatId; QString file; bool addToProjectFlag; QString translationTable; bool exportWholeAlignment; private slots: void sl_exportClicked(); private: SaveDocumentGroupController* saveContoller; QList tableID; }; }//namespace #endif ugene-1.9.8/src/plugins/dna_export/src/DNASequenceGeneratorDialog.cpp0000644000175000017500000002252311651544322024311 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "DNASequenceGeneratorDialog.h" #include "DNASequenceGenerator.h" #include #include #include #include #include #include #include #include #include namespace U2 { #define ROOT_SETTING QString("dna_export/") #define GCSKEW_SETTING QString("gc_skew") static QMap initContent() { QMap res; res['A'] = 0.25; res['C'] = 0.25; res['G'] = 0.25; res['T'] = 0.25; return res; } QMap DNASequenceGeneratorDialog::content = initContent(); DNASequenceGeneratorDialog::DNASequenceGeneratorDialog(QWidget* p) : QDialog(p) { setupUi(this); seedSpinBox->setEnabled(false); referenceButton->setChecked(true); sl_refButtonToggled(true); SaveDocumentGroupControllerConfig conf; conf.dfc.addFlagToExclude(DocumentFormatFlag_SingleObjectFormat); conf.dfc.addFlagToSupport(DocumentFormatFlag_SupportWriting); conf.dfc.supportedObjectTypes += GObjectTypes::SEQUENCE; conf.parentWidget = this; conf.fileNameEdit = outputEdit; conf.formatCombo = formatCombo; conf.fileDialogButton = outputButton; conf.defaultFormatId = BaseDocumentFormats::PLAIN_FASTA; //conf.defaultFileName = defaultFileName; conf.saveTitle = tr("Save sequences"); saveGroupContoller = new SaveDocumentGroupController(conf, this); connect(inputButton, SIGNAL(clicked()), SLOT(sl_browseReference())); connect(configureButton, SIGNAL(clicked()), SLOT(sl_configureContent())); connect(generateButton, SIGNAL(clicked()), SLOT(sl_generate())); connect(cancelButton, SIGNAL(clicked()), SLOT(reject())); connect(referenceButton, SIGNAL(toggled(bool)), SLOT(sl_refButtonToggled(bool))); connect(seedCheckBox, SIGNAL(stateChanged (int)), SLOT(sl_stateChanged(int))); } void DNASequenceGeneratorDialog::sl_stateChanged(int state) { if(state == Qt::Checked) { seedSpinBox->setEnabled(true); } else { seedSpinBox->setEnabled(false); } } void DNASequenceGeneratorDialog::sl_browseReference() { LastOpenDirHelper lod; QString filter = DNASequenceGenerator::prepareReferenceFileFilter(); lod.url = QFileDialog::getOpenFileName(this, tr("Open file"), lod.dir, filter); inputEdit->setText(lod.url); } void DNASequenceGeneratorDialog::sl_configureContent() { BaseContentDialog bcDlg(content, this); bcDlg.exec(); } void DNASequenceGeneratorDialog::sl_generate() { DNASequenceGeneratorConfig cfg; cfg.addToProj = addToProjCBox->isChecked(); cfg.length = lengthSpin->value(); cfg.numSeqs = seqNumSpin->value(); cfg.useRef = referenceButton->isChecked(); cfg.refUrl = inputEdit->text(); cfg.outUrl = outputEdit->text(); cfg.sequenceName = "Sequence "; cfg.format = saveGroupContoller->getFormatToSave(); cfg.content = content; cfg.window = windowSpinBox->value(); if(seedCheckBox->isChecked()) { cfg.seed = seedSpinBox->value(); } else { cfg.seed = -1; } if(cfg.window > cfg.length) { QMessageBox::critical(this, tr("DNA Sequence Generator"), tr("Windows size bigger than sequence length")); return; } if (!cfg.useRef) { cfg.alphabet = AppContext::getDNAAlphabetRegistry()->findById(BaseDNAAlphabetIds::NUCL_DNA_DEFAULT()); } if (cfg.refUrl.isEmpty() && cfg.useRef) { QMessageBox::critical(this, tr("DNA Sequence Generator"), tr("Reference url is not specified.")); return; } if (cfg.outUrl.isEmpty()) { QMessageBox::critical(this, tr("DNA Sequence Generator"), tr("Output file is no specified.")); return; } AppContext::getTaskScheduler()->registerTopLevelTask(new DNASequenceGeneratorTask(cfg)); accept(); } void DNASequenceGeneratorDialog::sl_refButtonToggled(bool checked) { assert(manualButton->isChecked() == !checked); inputEdit->setDisabled(!checked); inputButton->setDisabled(!checked); configureButton->setDisabled(checked); } BaseContentDialog::BaseContentDialog(QMap& percentMap_, QWidget* p) : QDialog(p), percentMap(percentMap_) { setupUi(this); percentASpin->setValue(percentMap.value('A')*100.0); percentCSpin->setValue(percentMap.value('C')*100.0); percentGSpin->setValue(percentMap.value('G')*100.0); percentTSpin->setValue(percentMap.value('T')*100.0); gcSkew = ((float)((int)(percentMap.value('G')*100) - (int)(percentMap.value('C')*100))) /((int)(percentMap.value('G')*100) + (int)(percentMap.value('C')*100)); int iGCSkew = (int)(gcSkew * 100); gcSkew = (float(iGCSkew))/100.0; percentGCSpin->setValue(gcSkew); gcSkewPrev = gcSkew; connect(saveButton, SIGNAL(clicked()), SLOT(sl_save())); connect(baseContentRadioButton, SIGNAL(clicked()), SLOT(sl_baseClicked())); connect(gcSkewRadioButton, SIGNAL(clicked()), SLOT(sl_gcSkewClicked())); //baseContentRadioButton->setChecked(true); Settings *s = AppContext::getSettings(); bool gc = s->getValue(ROOT_SETTING + GCSKEW_SETTING,false).toBool(); if(gc) { percentASpin->setEnabled(false); percentCSpin->setEnabled(false); percentTSpin->setEnabled(false); percentGSpin->setEnabled(false); percentGCSpin->setEnabled(true); } else { percentASpin->setEnabled(true); percentCSpin->setEnabled(true); percentTSpin->setEnabled(true); percentGSpin->setEnabled(true); percentGCSpin->setEnabled(false); } baseContentRadioButton->setChecked(!gc); gcSkewRadioButton->setChecked(gc); } void BaseContentDialog::sl_baseClicked() { percentASpin->setEnabled(true); percentCSpin->setEnabled(true); percentTSpin->setEnabled(true); percentGSpin->setEnabled(true); percentGCSpin->setEnabled(false); } void BaseContentDialog::sl_gcSkewClicked() { percentASpin->setEnabled(false); percentCSpin->setEnabled(false); percentTSpin->setEnabled(false); percentGSpin->setEnabled(false); percentGCSpin->setEnabled(true); } void BaseContentDialog::sl_save() { float percentA; float percentC; float percentG; float percentT; if(baseContentRadioButton->isChecked()) { percentA = percentASpin->value(); percentC = percentCSpin->value(); percentG = percentGSpin->value(); percentT = percentTSpin->value(); } else { gcSkew = percentGCSpin->value(); if(gcSkew != gcSkewPrev) { int percentAi = qrand(); int percentCi = qrand(); int percentTi = qrand(); int percentGi = qrand(); int sum = percentAi + percentCi + percentGi + percentTi; percentAi = (float)percentAi / sum * 100; percentGi = (float)percentGi / sum * 100; percentCi = (float)percentCi / sum * 100; percentTi = (float)percentTi / sum * 100; int CG = percentGi + percentCi; percentCi = (1 - gcSkew)* CG / 2; percentGi = percentCi + gcSkew * CG; if(percentCi < 0 || percentCi > 100 || percentGi < 0 || percentGi > 100) { QMessageBox::critical(this, tr("Base content"), tr("Incorrect GC Skew value")); return; } sum = percentAi + percentCi + percentGi + percentTi; percentAi += 100 - sum; percentA = percentAi; percentC = percentCi; percentG = percentGi; percentT = percentTi; percentASpin->setValue(percentAi); percentCSpin->setValue(percentCi); percentGSpin->setValue(percentGi); percentTSpin->setValue(percentTi); } else { percentA = percentASpin->value(); percentC = percentCSpin->value(); percentG = percentGSpin->value(); percentT = percentTSpin->value(); } } float total = percentA + percentC + percentG + percentT; if (total != 100) { QMessageBox::critical(this, tr("Base content"), tr("Total percentage has to be 100 %")); return; } percentMap['A'] = percentA / 100.0; percentMap['C'] = percentC / 100.0; percentMap['G'] = percentG / 100.0; percentMap['T'] = percentT / 100.0; Settings *s = AppContext::getSettings(); //bool gc = s->getValue("dna_export/gc_skew",false).toBool(); s->setValue(ROOT_SETTING + GCSKEW_SETTING, gcSkewRadioButton->isChecked()); accept(); } } //namespace ugene-1.9.8/src/plugins/dna_export/src/ExportTasks.h0000644000175000017500000000772311651544322021170 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_EXPORT_PLUGIN_TASKS_H_ #define _U2_EXPORT_PLUGIN_TASKS_H_ #include #include #include #include #include #include namespace U2 { /** Base class for all export tasks */ class AbstractExportTask : public Task { public: AbstractExportTask(const QString& _name, TaskFlags f) : Task(_name, f){} virtual Document* getDocument() const = 0; }; /** A task to adds exported document to project and open view*/ //TODO: make this task a general purpose routine class AddExportedDocumentAndOpenViewTask: public Task { Q_OBJECT public: AddExportedDocumentAndOpenViewTask(AbstractExportTask* t); QList onSubTaskFinished( Task* subTask ); private: AbstractExportTask* exportTask; }; /** A task to save alignment to CLUSTAL */ class ExportAlignmentTask : public AbstractExportTask { Q_OBJECT public: ExportAlignmentTask(const MAlignment& ma, const QString& fileName, DocumentFormatId f); void run(); virtual Document* getDocument() const {return doc.get();} private: MAlignment ma; QString fileName; DocumentFormatId format; std::auto_ptr doc; }; /** A task to export alignment to FASTA */ class ExportMSA2SequencesTask : public AbstractExportTask { Q_OBJECT public: ExportMSA2SequencesTask(const MAlignment& ma, const QString& url, bool trimAli, DocumentFormatId format); void run(); virtual Document* getDocument() const {return doc.get();} private: MAlignment ma; QString url; bool trimAli; QString format; std::auto_ptr doc; }; class ExportMSA2MSATask : public AbstractExportTask { Q_OBJECT public: ExportMSA2MSATask(const MAlignment& ma, int offset, int len, const QString& url, const QList& aminoTranslations, DocumentFormatId format); void run(); virtual Document* getDocument() const {return doc.get();} private: MAlignment ma; int offset; int len; QString url; QString format; QList aminoTranslations; // amino translation for a sequences in alignment. If not NULL -> sequence is translated std::auto_ptr doc; }; class DNAChromatogramObject; class LoadDocumentTask; /** A task to export chromatogram to SCF */ struct ExportChromatogramTaskSettings { ExportChromatogramTaskSettings() : reverse(false), complement(false), loadDocument(false) {} QString url; bool reverse; bool complement; bool loadDocument; }; class ExportDNAChromatogramTask : public AbstractExportTask { Q_OBJECT public: ExportDNAChromatogramTask(DNAChromatogramObject* chromaObj, const ExportChromatogramTaskSettings& url); void prepare(); virtual Document* getDocument() const; private: DNAChromatogramObject* cObj; ExportChromatogramTaskSettings settings; LoadDocumentTask* loadTask; }; }//namespace #endif ugene-1.9.8/src/plugins/dna_export/src/ImportQualityScoresTask.cpp0000644000175000017500000001160211651544322024050 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include #include #include #include #include #include #include #include "ImportQualityScoresTask.h" #include #include #define ULOG_IMPORT_QUALITY_SCORES "Dna_export: import quality scores" namespace U2 { ReadQualityScoresTask::ReadQualityScoresTask( const QString& file, DNAQualityType t) : Task("ReadPhredQuality", TaskFlag_None), fileName(file), type(t) { } #define READ_BUF_SIZE 4096 void ReadQualityScoresTask::run() { IOAdapterFactory* f = AppContext::getIOAdapterRegistry()->getIOAdapterFactoryById(BaseIOAdapters::LOCAL_FILE); std::auto_ptr io( f->createIOAdapter() ); if (!io->open(fileName, IOAdapterMode_Read) ) { stateInfo.setError("Can not open quality file"); return; } int headerCounter = -1; QByteArray readBuf(READ_BUF_SIZE+1, 0); char* buf = readBuf.data(); while (!stateInfo.cancelFlag) { int len = io->readUntil(buf, READ_BUF_SIZE, TextUtils::LINE_BREAKS, IOAdapter::Term_Include); stateInfo.progress = io->getProgress(); if (len == 0) { recordQuality(headerCounter); break; } if (buf[0] == '>') { recordQuality(headerCounter); QByteArray header = readBuf.mid(1, len - 1).trimmed(); headers.append(header); values.clear(); ++headerCounter; continue; } QByteArray valsBuf = readBuf.mid(0, len).trimmed(); QList valList = valsBuf.split(' '); foreach(const QByteArray& valStr, valList) { bool ok = false; values.append( valStr.toInt(&ok) ); if (!ok) { setError(QString("Failed parse quality value: file %1, seq name %2").arg(fileName).arg(headers[headerCounter])); } } } io->close(); } void ReadQualityScoresTask::recordQuality( int headerCounter ) { if (headerCounter > -1) { QByteArray qualCodes; foreach (int v, values) { char code = DNAQuality::encode(v, type); qualCodes.append(code); } result.insert(headers[headerCounter], DNAQuality(qualCodes,type)); //log.trace( QString("Phred quality parsed: %1 %2").arg(headers[headerCounter]).arg(qualCodes.constData()) ); } } ////////////////////////////////////////////////////////////////////////// ImportPhredQualityScoresTask::ImportPhredQualityScoresTask(const QList& sequences, ImportQualityScoresConfig& cfg ) : Task("ImportPhredQualityScores", TaskFlags_NR_FOSCOE), readQualitiesTask(NULL), config(cfg), seqList(sequences) { } void ImportPhredQualityScoresTask::prepare() { readQualitiesTask = new ReadQualityScoresTask(config.fileName, config.type); addSubTask(readQualitiesTask); } QList ImportPhredQualityScoresTask::onSubTaskFinished( Task* subTask ) { QList subTasks; if ( subTask->hasError() || subTask->isCanceled() ) { return subTasks; } if (subTask == readQualitiesTask) { QMap qualities = readQualitiesTask->getResult(); if (config.createNewDocument) { assert(0); //TODO: consider creating this option } else { foreach (DNASequenceObject* obj, seqList) { if (obj->isStateLocked()) { setError(QString("Unable to modify sequence %1: object is locked.").arg(obj->getGObjectName())); continue; } QString dnaName = obj->getDNASequence().getName().split(' ').first(); if (qualities.contains(dnaName)) { obj->setQuality(qualities.value(dnaName)); } else { setError(QString("Quality scores for %1 are not found.").arg(dnaName)); break; } } } } return subTasks; } } // namespace U2 ugene-1.9.8/src/plugins/dna_export/src/ImportAnnotationsFromCSVDialog.h0000644000175000017500000000600011651544322024674 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_IMPORT_ANNOTATIONS_FROM_CSV_DIALOG_H_ #define _U2_IMPORT_ANNOTATIONS_FROM_CSV_DIALOG_H_ #include #include "CSVColumnConfiguration.h" class QTreeWidgetItem; namespace U2 { class SaveDocumentGroupController; class ImportAnnotationsFromCSVTaskConfig; class CSVParsingConfig; class ImportAnnotationsFromCSVDialog : public QDialog, Ui_ImportAnnotationsFromCSVDialog { Q_OBJECT public: ImportAnnotationsFromCSVDialog(QWidget* w); void toTaskConfig(ImportAnnotationsFromCSVTaskConfig& config) const; void toParsingConfig(CSVParsingConfig& config) const; public slots: virtual void accept(); private slots: void sl_readFileClicked(); void sl_previewClicked(); void sl_guessSeparatorClicked(); void sl_scriptSeparatorClicked(); void sl_separatorChanged(const QString&); void sl_prefixToSkipChanged(const QString&); void sl_tableItemClicked(QTableWidgetItem*); void sl_tableHeaderClicked(int); void sl_separatorRadioToggled(bool); void sl_scriptRadioToggled(bool); void sl_removeQuotesToggled(bool); void sl_separatorsModeToggled(bool); void sl_linesToSkipChanged(int); private: // returns input file name if no errors found or empty string QString checkInputGroup(bool silentFail); // returns output file name if no errors found or empty string QString checkOutputGroup(); bool checkSeparators(bool silentFail); void prepareColumnsConfig(int numColumnsHint); QTableWidgetItem* createHeaderItem(int column) const; QString getHeaderItemText(int column) const; void configureColumn(int column); QString readFileHeader(const QString& fileName, bool silentFail); void guessSeparator(bool silentFail); void preview(bool silentFail); SaveDocumentGroupController* saveGroupController; QList columnsConfig; // script text used to parse separator QString parsingScript; // header of the script QString scriptHeader; // last separator value before switch to script mode QString lastUsedSeparator; static const int SEPARATOR_EDIT_MAX_LENGTH = 20; }; } // namespace U2 #endif ugene-1.9.8/src/plugins/dna_export/src/ExportSequences2MSADialog.cpp0000644000175000017500000000465211651544322024132 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "ExportSequences2MSADialog.h" #include #include #include #include #include #include #include #include #define SETTINGS_ROOT QString("dna_export/") namespace U2 { ExportSequences2MSADialog::ExportSequences2MSADialog(QWidget* p, const QString& defaultUrl): QDialog(p) { setupUi(this); addToProjectFlag = true; SaveDocumentGroupControllerConfig conf; conf.dfc.addFlagToSupport(DocumentFormatFlag_SupportWriting); conf.dfc.supportedObjectTypes+=GObjectTypes::MULTIPLE_ALIGNMENT; conf.fileDialogButton = fileButton; conf.formatCombo = formatCombo; conf.fileNameEdit = fileNameEdit; conf.parentWidget = this; conf.defaultFileName = defaultUrl; conf.defaultFormatId = BaseDocumentFormats::CLUSTAL_ALN; saveContoller = new SaveDocumentGroupController(conf, this); } void ExportSequences2MSADialog::accept() { if (fileNameEdit->text().isEmpty()) { QMessageBox::critical(this, L10N::errorTitle(), tr("File name is empty!")); return; } url = saveContoller->getSaveFileName(); format = saveContoller->getFormatIdToSave(); addToProjectFlag = addToProjectBox->isChecked(); QDialog::accept(); } void ExportSequences2MSADialog::setOkButtonText(const QString& text) const { okButton->setText(text); } void ExportSequences2MSADialog::setFileLabelText(const QString& text) const { fileLabel->setText(text); } }//namespace ugene-1.9.8/src/plugins/dna_export/src/ExportChromatogramDialog.h0000644000175000017500000000305211651544322023635 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_EXPORT_CHROMATOGRAM_DIALOG_H_ #define _U2_EXPORT_CHROMATOGRAM_DIALOG_H_ #include #include #include #include namespace U2 { class SaveDocumentGroupController; class ExportChromatogramDialog : public QDialog, Ui_ExportChromatogramDialog { Q_OBJECT public: ExportChromatogramDialog(QWidget* p, const GUrl& fileName); virtual void accept(); public: QString url; DocumentFormatId format; bool addToProjectFlag; bool reversed; bool complemented; private slots: void sl_onBrowseClicked(); private: SaveDocumentGroupController* saveController; }; }//namespace #endif ugene-1.9.8/src/plugins/dna_export/src/ExportMSA2SequencesDialog.h0000644000175000017500000000265311651544322023576 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_EXPORT_MSA2SEQ_DIALOG_H_ #define _U2_EXPORT_MSA2SEQ_DIALOG_H_ #include #include #include namespace U2 { class SaveDocumentGroupController; class ExportMSA2SequencesDialog : public QDialog, Ui_ExportMSA2SequencesDialog { Q_OBJECT public: ExportMSA2SequencesDialog(QWidget* p); virtual void accept(); public: QString url; DocumentFormatId format; bool trimGapsFlag; bool addToProjectFlag; private: SaveDocumentGroupController* saveContoller; }; }//namespace #endif ugene-1.9.8/src/plugins/dna_export/src/GenerateDNAWorker.h0000644000175000017500000000362511651544322022145 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_GENERATE_DNA_WORKER_H_ #define _U2_GENERATE_DNA_WORKER_H_ #include #include namespace U2 { namespace LocalWorkflow { class GenerateDNAPrompter : public PrompterBase { Q_OBJECT public: GenerateDNAPrompter(Actor* p = 0) : PrompterBase(p) {} protected: QString composeRichDoc(); }; class GenerateDNAWorker : public BaseWorker { Q_OBJECT public: GenerateDNAWorker(Actor* a) : BaseWorker(a), ch(NULL), done(false) {} virtual void init(); virtual bool isReady(); virtual Task* tick(); virtual bool isDone(); virtual void cleanup() {} private slots: void sl_taskFinished(Task*); private: CommunicationChannel* ch; bool done; }; class GenerateDNAWorkerFactory : public DomainFactory { public: static const QString ACTOR_ID; static void init(); GenerateDNAWorkerFactory() : DomainFactory(ACTOR_ID) {} virtual Worker* createWorker(Actor* a) { return new GenerateDNAWorker(a); } }; } // LocalWorkflow namespace } // U2 namespace #endif ugene-1.9.8/src/plugins/dna_export/src/ExportAnnotations2CSVTask.cpp0000644000175000017500000001113511651544322024204 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "ExportAnnotations2CSVTask.h" #include #include #include #include #include #include #include #include namespace U2 { ExportAnnotations2CSVTask::ExportAnnotations2CSVTask(const QList& annotations, const QByteArray& sequence, DNATranslation *complementTranslation, bool exportSequence, const QString& url, bool apnd) : Task(tr("Export2CSV"), TaskFlag_None), annotations(annotations), sequence(sequence), complementTranslation(complementTranslation), exportSequence(exportSequence), url(url), append(apnd) { GCOUNTER( cvar, tvar, "ExportAnnotattions2CSVTask" ); } static void writeCSVLine(const QStringList& container, IOAdapter *ioAdapter, U2OpStatus& os) { bool first = true; foreach(QString value, container) { if (!first) { if (0 == ioAdapter->writeBlock(",")) { os.setError(L10N::errorWritingFile(ioAdapter->getURL())); return; } } QString preparedStr = "\"" + value.replace("\"","\"\"") + "\""; if (0 == ioAdapter->writeBlock(preparedStr.toLocal8Bit())) { os.setError(L10N::errorWritingFile(ioAdapter->getURL())); return; } first = false; } if (0 == ioAdapter->writeBlock("\n")) { os.setError(L10N::errorWritingFile(ioAdapter->getURL())); return; } } void ExportAnnotations2CSVTask::run() { std::auto_ptr ioAdapter; { IOAdapterId ioAdapterId = BaseIOAdapters::url2io(url); IOAdapterFactory *ioAdapterFactory = AppContext::getIOAdapterRegistry()->getIOAdapterFactoryById(ioAdapterId); CHECK_EXT (ioAdapterFactory != NULL, stateInfo.setError(tr("No IO adapter found for URL: %1").arg(url)), ); ioAdapter.reset(ioAdapterFactory->createIOAdapter()); } if(!ioAdapter->open(url, append ? IOAdapterMode_Append : IOAdapterMode_Write)) { stateInfo.setError(L10N::errorOpeningFileWrite(url)); return; } QHash columnIndices; QStringList columnNames; columnNames << tr("Group") << tr("Name") << tr("Start") << tr("End") << tr("Length") << tr("Complementary"); if (exportSequence) { columnNames << tr("Sequence"); } foreach(const Annotation* annotation, annotations) { foreach(const U2Qualifier& qualifier, annotation->getQualifiers()) { const QString& qName = qualifier.name; if (!columnIndices.contains(qName)) { columnIndices.insert(qName, columnNames.size()); columnNames.append(qName); } } } writeCSVLine(columnNames, ioAdapter.get(), stateInfo); CHECK_OP(stateInfo, ); foreach(const Annotation* annotation, annotations) { foreach(const U2Region& region, annotation->getRegions()) { QStringList values; values << annotation->getGroups().last()->getGroupPath(); values << annotation->getAnnotationName(); values << QString::number(region.startPos + 1); values << QString::number(region.startPos + region.length); values << QString::number(region.length); if (annotation->getStrand().isCompementary()) { values << tr("yes"); } else { values << tr("no"); } if (exportSequence) { QByteArray sequencePart = sequence.mid(region.startPos, region.length); if (annotation->getStrand().isCompementary()) { complementTranslation->translate(sequencePart.data(), sequencePart.size()); TextUtils::reverse(sequencePart.data(), sequencePart.size()); } values << sequencePart; } //add empty strings as default qualifier values while (values.size() < columnNames.size()) { values << QString(); } foreach(const U2Qualifier& qualifier, annotation->getQualifiers()) { int qualifiedIndex = columnIndices[qualifier.name]; values[qualifiedIndex] = qualifier.value; } writeCSVLine(values, ioAdapter.get(), stateInfo); } } } } // namespace U2 ugene-1.9.8/src/plugins/dna_export/src/DNAExportPluginTests.h0000644000175000017500000000426311651544322022703 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_DNA_EXPORT_PLUGIN_TESTS_H_ #define _U2_DNA_EXPORT_PLUGIN_TESTS_H_ #include #include #include #include "ExportTasks.h" namespace U2 { class DNASequenceObject; class MAlignmentObject; class GTest_ImportPhredQualityScoresTask : public GTest { Q_OBJECT public: SIMPLE_XML_TEST_BODY_WITH_FACTORY_EXT(GTest_ImportPhredQualityScoresTask, "import-phred-qualities", TaskFlags_NR_FOSCOE); void prepare(); QList seqList; QStringList seqNameList; QString fileName; }; class GTest_ExportNucleicToAminoAlignmentTask : public GTest { Q_OBJECT public: SIMPLE_XML_TEST_BODY_WITH_FACTORY_EXT(GTest_ExportNucleicToAminoAlignmentTask, "export-nucleic-alignment", TaskFlags_NR_FOSCOE); void prepare(); ReportResult report(); QList onSubTaskFinished(Task* subTask); int transTable; QString inputFile; QString outputFileName; QString expectedOutputFile; U2Region selectedRows; ExportMSA2MSATask* exportTask; LoadDocumentTask* resultLoadTask; MAlignment srcAl; MAlignment resAl; }; class DNAExportPluginTests { public: static QList createTestFactories(); }; } // namespace U2 #endif ugene-1.9.8/src/plugins/dna_export/src/WriteAnnotationsWorker.cpp0000644000175000017500000002541411651544322023733 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "ExportAnnotations2CSVTask.h" #include "WriteAnnotationsWorker.h" namespace U2 { namespace LocalWorkflow { const QString WriteAnnotationsWorkerFactory::ACTOR_ID("write-annotations"); static const QString WRITE_ANNOTATIONS_IN_TYPE_ID("write-annotations-in-type"); static const QString CSV_FORMAT_ID("csv"); static const QString ANNOTATIONS_NAME("annotations-name"); static const QString ANNOTATIONS_NAME_DEF_VAL("unknown features"); /******************************* * WriteAnnotationsWorker *******************************/ WriteAnnotationsWorker::~WriteAnnotationsWorker() { qDeleteAll(createdAnnotationObjects); } void WriteAnnotationsWorker::init() { annotationsPort = ports.value(BasePorts::IN_ANNOTATIONS_PORT_ID()); } bool WriteAnnotationsWorker::isReady() { return annotationsPort->hasMessage(); } Task * WriteAnnotationsWorker::tick() { QString formatId = actor->getParameter(BaseAttributes::DOCUMENT_FORMAT_ATTRIBUTE().getId())->getAttributeValue(); DocumentFormat * format = AppContext::getDocumentFormatRegistry()->getFormatById(formatId); SaveDocFlags fl(actor->getParameter(BaseAttributes::FILE_MODE_ATTRIBUTE().getId())->getAttributeValue()); if( formatId != CSV_FORMAT_ID && format == NULL ) { return new FailTask(tr("Unrecognized formatId: '%1'").arg(formatId)); } while(annotationsPort->hasMessage()) { Message inputMessage = getMessageAndSetupScriptValues(annotationsPort); QString filepath = actor->getParameter(BaseAttributes::URL_OUT_ATTRIBUTE().getId())->getAttributeValue(); filepath = filepath.isEmpty() ? inputMessage.getData().toMap().value(BaseSlots::URL_SLOT().getId()).value() : filepath; if (filepath.isEmpty()) { return new FailTask(tr("Unspecified URL to write %1").arg(formatId)); } QStringList exts = formatId == CSV_FORMAT_ID ? QStringList("csv") : format->getSupportedDocumentFileExtensions(); filepath = GUrlUtils::ensureFileExt(filepath, exts).getURLString(); QString objName = actor->getParameter(ANNOTATIONS_NAME)->getAttributeValue(); if(objName.isEmpty()) { objName = ANNOTATIONS_NAME_DEF_VAL; coreLog.details(tr("Annotations name not specified. Default value used: '%1'").arg(objName)); } AnnotationTableObject * att = NULL; if (annotationsByUrl.contains(filepath)) { att = annotationsByUrl.value(filepath); } else { att = new AnnotationTableObject(objName); annotationsByUrl.insert(filepath, att); } QList atl = QVariantUtils::var2ftl(inputMessage.getData().toMap(). value(BaseSlots::ANNOTATION_TABLE_SLOT().getId()).toList()); foreach(const SharedAnnotationData & ad, atl) { att->addAnnotation(new Annotation(ad)); } } // while done = annotationsPort->isEnded(); if (!done) { return NULL; } QList taskList; QSet excludeFileNames = DocumentUtils::getNewDocFileNameExcludesHint(); foreach (QString filepath, annotationsByUrl.keys()) { AnnotationTableObject *att = annotationsByUrl.value(filepath); if(formatId == CSV_FORMAT_ID) { createdAnnotationObjects << att; // will delete in destructor TaskStateInfo ti; if(fl.testFlag(SaveDoc_Roll) && !GUrlUtils::renameFileWithNameRoll(filepath, ti, excludeFileNames, &coreLog)) { return new FailTask(ti.getError()); } taskList << new ExportAnnotations2CSVTask(att->getAnnotations(), QByteArray(), NULL, false, filepath, fl.testFlag(SaveDoc_Append)); } else { fl |= SaveDoc_DestroyAfter; IOAdapterFactory* iof = AppContext::getIOAdapterRegistry()->getIOAdapterFactoryById(BaseIOAdapters::url2io(filepath)); Document * doc = new Document(AppContext::getDocumentFormatRegistry()->getFormatById(formatId), iof, filepath); doc->setLoaded(true); att->setModified(false); doc->addObject(att); // savedoc task will delete doc -> doc will delete att taskList << new SaveDocumentTask(doc, fl, excludeFileNames); } } return taskList.size() == 1 ? taskList.first() : new MultiTask(tr("Save annotations"), taskList); } bool WriteAnnotationsWorker::isDone() { return done; } void WriteAnnotationsWorker::cleanup() { } /******************************* * WriteAnnotationsWorkerFactory *******************************/ void WriteAnnotationsWorkerFactory::init() { // ports description QList portDescs; { QMap inM; inM[BaseSlots::ANNOTATION_TABLE_SLOT()] = BaseTypes::ANNOTATION_TABLE_LIST_TYPE(); inM[BaseSlots::URL_SLOT()] = BaseTypes::STRING_TYPE(); DataTypePtr inSet(new MapDataType(WRITE_ANNOTATIONS_IN_TYPE_ID, inM)); Descriptor inPortDesc(BasePorts::IN_ANNOTATIONS_PORT_ID(), WriteAnnotationsWorker::tr("Input annotations"), WriteAnnotationsWorker::tr("Input annotations which will be written to output file")); portDescs << new PortDescriptor(inPortDesc, inSet, true); } QList supportedFormats; // attributes description QList attrs; { DocumentFormatConstraints constr; constr.supportedObjectTypes.insert( GObjectTypes::ANNOTATION_TABLE ); constr.addFlagToSupport(DocumentFormatFlag_SupportWriting); supportedFormats = AppContext::getDocumentFormatRegistry()->selectFormats( constr ); supportedFormats.append(CSV_FORMAT_ID); attrs << new Attribute(BaseAttributes::DOCUMENT_FORMAT_ATTRIBUTE(), BaseTypes::STRING_TYPE(), false, supportedFormats.contains(BaseDocumentFormats::PLAIN_GENBANK) ? BaseDocumentFormats::PLAIN_GENBANK : supportedFormats.first()); attrs << new Attribute(BaseAttributes::URL_OUT_ATTRIBUTE(), BaseTypes::STRING_TYPE(), false ); attrs << new Attribute(BaseAttributes::FILE_MODE_ATTRIBUTE(), BaseTypes::NUM_TYPE(), false, SaveDoc_Roll); Descriptor annotationsNameDesc(ANNOTATIONS_NAME, WriteAnnotationsWorker::tr("Annotations name"), WriteAnnotationsWorker::tr("Object name of saving annotations")); attrs << new Attribute(annotationsNameDesc, BaseTypes::STRING_TYPE(), false, QVariant(ANNOTATIONS_NAME_DEF_VAL)); } Descriptor protoDesc(WriteAnnotationsWorkerFactory::ACTOR_ID, WriteAnnotationsWorker::tr("Write annotations"), WriteAnnotationsWorker::tr("Writes all supplied annotations to file(s) in selected formatId.")); ActorPrototype * proto = new IntegralBusActorPrototype(protoDesc, portDescs, attrs); // proto delegates QMap delegates; { QVariantMap m; foreach( const DocumentFormatId & fid, supportedFormats ) { m[fid] = fid; } ComboBoxDelegate *comboDelegate = new ComboBoxDelegate(m); URLDelegate *urlDelegate = new URLDelegate( DialogUtils::prepareDocumentsFileFilterByObjType(GObjectTypes::ANNOTATION_TABLE, true), QString(), false ); QObject::connect(comboDelegate, SIGNAL(si_valueChanged(const QString &)), urlDelegate, SLOT(sl_formatChanged(const QString &))); delegates[BaseAttributes::DOCUMENT_FORMAT_ATTRIBUTE().getId()] = comboDelegate; delegates[BaseAttributes::URL_OUT_ATTRIBUTE().getId()] = urlDelegate; delegates[BaseAttributes::FILE_MODE_ATTRIBUTE().getId()] = new FileModeDelegate(attrs.size() > 2); } proto->setEditor(new DelegateEditor(delegates)); proto->setPrompter(new WriteAnnotationsPrompter()); proto->setValidator(new ScreenedParamValidator(BaseAttributes::URL_OUT_ATTRIBUTE().getId(), BasePorts::IN_ANNOTATIONS_PORT_ID(), BaseSlots::URL_SLOT().getId())); proto->setPortValidator(BasePorts::IN_ANNOTATIONS_PORT_ID(), new ScreenedSlotValidator(BaseSlots::URL_SLOT().getId())); WorkflowEnv::getProtoRegistry()->registerProto(BaseActorCategories::CATEGORY_DATASINK(), proto); WorkflowEnv::getDomainRegistry()->getById(LocalDomainFactory::ID)->registerEntry(new WriteAnnotationsWorkerFactory()); } Worker * WriteAnnotationsWorkerFactory::createWorker(Actor* a) { return new WriteAnnotationsWorker(a); } /*************************** * WriteAnnotationsPrompter ***************************/ QString WriteAnnotationsPrompter::composeRichDoc() { QString unsetStr = ""+tr("unset")+""; IntegralBusPort * input = qobject_cast(target->getPort(BasePorts::IN_ANNOTATIONS_PORT_ID())); QString annName = getProducers(BasePorts::IN_ANNOTATIONS_PORT_ID(), BaseSlots::ANNOTATION_TABLE_SLOT().getId()); annName = annName.isEmpty() ? unsetStr : annName; QString url = getScreenedURL(input, BaseAttributes::URL_OUT_ATTRIBUTE().getId(), BaseSlots::URL_SLOT().getId()); QString format = getParameter(BaseAttributes::DOCUMENT_FORMAT_ATTRIBUTE().getId()).value(); return tr("Save all annotations from %1 to %2 in %3 format") .arg(annName) .arg(getHyperlink(BaseAttributes::URL_OUT_ATTRIBUTE().getId(), url)) .arg(getHyperlink(BaseAttributes::DOCUMENT_FORMAT_ATTRIBUTE().getId(), format)); } } // LocalWorkflow } // U2 ugene-1.9.8/src/plugins/dna_export/src/ExportSequences2MSADialog.h0000644000175000017500000000305711651544322023575 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_EXPORT_SEQ2MSA_DIALOG_H_ #define _U2_EXPORT_SEQ2MSA_DIALOG_H_ #include #include #include namespace U2 { class SaveDocumentGroupController; class ExportSequences2MSADialog : public QDialog, Ui_ExportSequences2MSADialog { Q_OBJECT public: ExportSequences2MSADialog(QWidget* p, const QString& defaultUrl = QString() ); void setOkButtonText(const QString& text) const; void setFileLabelText(const QString& text) const; virtual void accept(); public: QString url; DocumentFormatId format; bool addToProjectFlag; private: SaveDocumentGroupController* saveContoller; }; }//namespace #endif ugene-1.9.8/src/plugins/dna_export/src/ExportAlignmentViewItems.h0000644000175000017500000000342211651544322023646 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_EXPORT_ALIGNMENT_VIEW_ITEMS_H_ #define _U2_EXPORT_ALIGNMENT_VIEW_ITEMS_H_ #include #include #include namespace U2 { class ADVSequenceObjectContext; class AnnotatedDNAView; class AnnotationSelection; class Annotation; class LRegionsSelection; class MAlignment; class MSAEditor; class ExportAlignmentViewItemsController : public GObjectViewWindowContext { Q_OBJECT public: ExportAlignmentViewItemsController(QObject* p); protected: virtual void initViewContext(GObjectView* view); virtual void buildMenu(GObjectView* v, QMenu* m); }; class MSAExportContext : public QObject { Q_OBJECT; public: MSAExportContext(MSAEditor* e); void buildMenu(QMenu* m); protected slots: void sl_exportNucleicMsaToAmino(); void updateActions(); private: MSAEditor* editor; QAction* translateMSAAction; }; }//namespace #endif ugene-1.9.8/src/plugins/dna_export/src/GetSequenceByIdDialog.h0000644000175000017500000000251711651544322022775 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef GET_SEQUENCE_BY_ID_ #define GET_SEQUENCE_BY_ID_ #include "ui/ui_GetSequenceByIdDialog.h" namespace U2 { class GetSequenceByIdDialog: public QDialog, public Ui_getSequenceByIdDialog{ Q_OBJECT public: GetSequenceByIdDialog(QWidget *w = NULL); void accept(); bool isAddToProject() const {return addToProject;} QString getDirectory() const {return dir;} private slots: void sl_saveFilenameButtonClicked(); private: QString dir; bool addToProject; }; } #endifugene-1.9.8/src/plugins/dna_export/src/ExportChromatogramDialog.cpp0000644000175000017500000000474511651544322024202 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "ExportChromatogramDialog.h" #include #include #include #include #include #include #include #include #include #include #define SETTINGS_ROOT QString("dna_export/") namespace U2 { ExportChromatogramDialog::ExportChromatogramDialog(QWidget* p, const GUrl& fileUrl): QDialog(p) { setupUi(this); addToProjectFlag = true; //SaveDocumentGroupControllerConfig conf; GUrl newUrl = GUrlUtils::rollFileName(fileUrl.dirPath() + "/" + fileUrl.baseFileName() + "_copy.scf", DocumentUtils::getNewDocFileNameExcludesHint()); fileNameEdit->setText( newUrl.getURLString() ); formatCombo->addItem( BaseDocumentFormats::SCF.toUpper() ); connect(fileButton, SIGNAL(clicked()),SLOT(sl_onBrowseClicked()) ); } void ExportChromatogramDialog::sl_onBrowseClicked() { LastOpenDirHelper lod; QString filter; lod.url = QFileDialog::getSaveFileName(this, tr("Select a file"), lod.dir, "*.scf"); if (lod.url.isEmpty()) { return; } fileNameEdit->setText( lod.url ); } void ExportChromatogramDialog::accept() { if (fileNameEdit->text().isEmpty()) { QMessageBox::critical(this, L10N::errorTitle(), tr("File name is empty!")); return; } url = fileNameEdit->text(); addToProjectFlag = addToProjectBox->isChecked(); reversed = reverseBox->isChecked(); complemented = complementBox->isChecked(); QDialog::accept(); } }//namespace ugene-1.9.8/src/plugins/dna_export/src/DNAExportPlugin.h0000644000175000017500000000321311651544322021652 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_DNA_EXPORT_PLUGIN_H_ #define _U2_DNA_EXPORT_PLUGIN_H_ #include #include namespace U2 { class ExportProjectViewItemsContoller; class ExportSequenceViewItemsController; class ExportAlignmentViewItemsController; class DNAExportPlugin : public Plugin { Q_OBJECT public: DNAExportPlugin(); private slots: void sl_generateSequence(); }; class DNAExportService: public Service { Q_OBJECT public: DNAExportService(); protected: virtual void serviceStateChangedCallback(ServiceState oldState, bool enabledStateChanged); ExportProjectViewItemsContoller* projectViewController; ExportSequenceViewItemsController* sequenceViewController; ExportAlignmentViewItemsController* alignmentViewController; }; } //namespace #endif ugene-1.9.8/src/plugins/dna_export/src/ExportSequenceViewItems.h0000644000175000017500000000630111651544322023477 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_EXPORT_SEQUENCE_VIEW_ITEMS_H_ #define _U2_EXPORT_SEQUENCE_VIEW_ITEMS_H_ #include #include #include namespace U2 { class ADVSequenceObjectContext; class AnnotatedDNAView; class AnnotationSelection; class Annotation; class LRegionsSelection; class MAlignment; class ExportSequenceViewItemsController : public GObjectViewWindowContext { Q_OBJECT public: ExportSequenceViewItemsController(QObject* p); protected: virtual void initViewContext(GObjectView* view); virtual void buildMenu(GObjectView* v, QMenu* m); }; class ADVExportContext : public QObject { Q_OBJECT; public: ADVExportContext(AnnotatedDNAView* v); void buildMenu(QMenu* m); protected slots: void sl_saveSelectedSequences(); void sl_saveSelectedAnnotationsSequence(); void sl_saveSelectedAnnotations(); void sl_saveSelectedAnnotationsToAlignment(); void sl_saveSelectedAnnotationsToAlignmentWithTranslation(); void sl_saveSelectedSequenceToAlignment(); void sl_saveSelectedSequenceToAlignmentWithTranslation(); void sl_getSequenceByDBXref(); void sl_getSequenceByAccession(); void sl_getSequenceById(); void sl_onSequenceContextAdded(ADVSequenceObjectContext* c); void sl_onSequenceContextRemoved(ADVSequenceObjectContext* c); void sl_onAnnotationSelectionChanged(AnnotationSelection*, const QList& added, const QList& removed); void sl_onSequenceSelectionChanged(LRegionsSelection* thiz, const QVector& added, const QVector& removed); void updateActions(); private: QString prepareMAFromAnnotations(MAlignment& ma, bool translate); QString prepareMAFromSequences(MAlignment& ma, bool translate); void fetchSequencesFromRemoteDB(const QString & listId); void selectionToAlignment(const QString& title, bool annotations, bool translate); AnnotatedDNAView* view; QAction* sequence2SequenceAction; QAction* annotations2SequenceAction; QAction* annotations2CSVAction; QAction* annotationsToAlignmentAction; QAction* annotationsToAlignmentWithTranslatedAction; QAction* sequenceToAlignmentAction; QAction* sequenceToAlignmentWithTranslationAction; QAction* sequenceById; QAction* sequenceByAccession; QAction* sequenceByDBXref; }; }//namespace #endif ugene-1.9.8/src/plugins/dna_export/src/ImportAnnotationsFromCSVDialog.cpp0000644000175000017500000004561311651544322025244 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "ImportAnnotationsFromCSVDialog.h" #include "ImportAnnotationsFromCSVTask.h" #include "CSVColumnConfigurationDialog.h" #include #include #include #include #include #include #include #include #include #include #include #include #include //TODO: add complement token configuration //TODO: autodetect numeric columns, propose using them as start/end/length positions //TODO: option for negative len -> complement namespace U2 { // TODO: unify with plugin settings #define SETTINGS_ROOT QString("dna_export/import_annotations_from_csv/") #define A_NAME QString("annotation_name") #define T_SEPARATOR QString("token_separator") #define SKIP_LINES_COUNT QString("skip_lines_count") #define SKIP_LINES_PREFIX QString("skip_lines_prefix") ImportAnnotationsFromCSVDialog::ImportAnnotationsFromCSVDialog(QWidget* w) : QDialog (w) { setupUi(this); connect(readFileButton, SIGNAL(clicked()), SLOT(sl_readFileClicked())); connect(previewButton, SIGNAL(clicked()), SLOT(sl_previewClicked())); connect(guessButton, SIGNAL(clicked()), SLOT(sl_guessSeparatorClicked())); connect(scriptButton, SIGNAL(clicked()), SLOT(sl_scriptSeparatorClicked())); connect(separatorEdit, SIGNAL(textChanged(const QString&)), SLOT(sl_separatorChanged(const QString&))); connect(prefixToSkipEdit, SIGNAL(textChanged(const QString&)), SLOT(sl_prefixToSkipChanged(const QString&))); connect(previewTable, SIGNAL(itemClicked(QTableWidgetItem*)), SLOT(sl_tableItemClicked(QTableWidgetItem*))); connect(previewTable->horizontalHeader(), SIGNAL(sectionClicked(int)), SLOT(sl_tableHeaderClicked(int))); connect(columnSeparatorRadioButton, SIGNAL(toggled(bool)), SLOT(sl_separatorRadioToggled(bool))); connect(scriptRadioButton, SIGNAL(toggled(bool)), SLOT(sl_scriptRadioToggled(bool))); SaveDocumentGroupControllerConfig conf; conf.dfc.addFlagToSupport(DocumentFormatFlag_SupportWriting); conf.dfc.supportedObjectTypes += GObjectTypes::ANNOTATION_TABLE; conf.fileDialogButton = saveFileButton; conf.fileNameEdit = saveFileName; conf.saveTitle = tr("Save imported annotations to"); conf.parentWidget = this; conf.formatCombo = saveFormatCombo; saveGroupController = new SaveDocumentGroupController(conf, this); sl_separatorChanged(separatorEdit->text()); sl_prefixToSkipChanged(prefixToSkipEdit->text()); //restore last settings QString lastName = AppContext::getSettings()->getValue(SETTINGS_ROOT + A_NAME).toString(); if (!lastName.isEmpty()) { defaultNameEdit->setText(lastName); } QString separator = AppContext::getSettings()->getValue(SETTINGS_ROOT + T_SEPARATOR).toString(); if (!separator.isEmpty()) { separatorEdit->setText(separator); } int skipLinesCount = AppContext::getSettings()->getValue(SETTINGS_ROOT + SKIP_LINES_COUNT).toInt(); linesToSkipBox->setValue(skipLinesCount); QString skipPrefix = AppContext::getSettings()->getValue(SETTINGS_ROOT + SKIP_LINES_PREFIX).toString(); if (!skipPrefix.isEmpty()) { prefixToSkipEdit->setText(skipPrefix); } scriptHeader = tr("//The script parses input line\n // and returns an array of parsed elements as the result\nvar %1; //input line\nvar %2; //parsed line number") .arg(ReadCSVAsAnnotationsTask::LINE_VAR).arg(ReadCSVAsAnnotationsTask::LINE_NUM_VAR); columnSeparatorRadioButton->setChecked(true); sl_scriptRadioToggled(false); separatorEdit->setMaxLength(SEPARATOR_EDIT_MAX_LENGTH); // connect this slot after initial dialog model is set up connect(removeQuotesCheck, SIGNAL(toggled(bool)),SLOT(sl_removeQuotesToggled(bool))); connect(separatorsModeCheck, SIGNAL(toggled(bool)), SLOT(sl_separatorsModeToggled(bool))); connect(linesToSkipBox, SIGNAL(valueChanged(int)), SLOT(sl_linesToSkipChanged(int))); } void ImportAnnotationsFromCSVDialog::accept() { QString inFile = checkInputGroup(false); if (inFile.isEmpty()) { return; } bool qOk = checkSeparators(false); if (!qOk) { return; } QString outFile = checkOutputGroup(); if (outFile.isEmpty()) { return; } //check that position is OK int endPos = 0; int startPos = 0; int length = 0; int names = 0; foreach (const ColumnConfig& conf, columnsConfig) { switch(conf.role) { case ColumnRole_EndPos: endPos++; break; case ColumnRole_StartPos: startPos++; break; case ColumnRole_Length: length++; break; case ColumnRole_Name: names++; break; case ColumnRole_Ignore: break; case ColumnRole_Qualifier: break; default:; } } if (endPos + startPos + length != 2 || endPos > 1 || startPos > 1 || length > 1) { QMessageBox::critical(this, L10N::errorTitle(), tr("Invalid start position/end position/length configuration!")); return; } if (names > 1 ) { QMessageBox::critical(this, L10N::errorTitle(), tr("Multiple columns are used as a name!")); return; } if (!Annotation::isValidAnnotationName(defaultNameEdit->text())) { QMessageBox::critical(this, L10N::errorTitle(), tr("Invalid default annotation name!")); defaultNameEdit->setFocus(); return; } //store last settings AppContext::getSettings()->setValue(SETTINGS_ROOT + A_NAME, defaultNameEdit->text()); AppContext::getSettings()->setValue(SETTINGS_ROOT + T_SEPARATOR, separatorEdit->text()); AppContext::getSettings()->setValue(SETTINGS_ROOT + SKIP_LINES_COUNT, linesToSkipBox->value()); AppContext::getSettings()->setValue(SETTINGS_ROOT + SKIP_LINES_PREFIX, prefixToSkipEdit->text()); return QDialog::accept(); } void ImportAnnotationsFromCSVDialog::toParsingConfig(CSVParsingConfig& config) const { config.columns = columnsConfig; config.linesToSkip = linesToSkipBox->value(); config.prefixToSkip = prefixToSkipEdit->text(); config.keepEmptyParts = !separatorsModeCheck->isChecked(); config.defaultAnnotationName = defaultNameEdit->text(); config.removeQuotes = removeQuotesCheck->isChecked(); config.parsingScript.clear(); config.splitToken.clear(); if( columnSeparatorRadioButton->isChecked() ) { config.splitToken = separatorEdit->text(); } else if( scriptRadioButton->isChecked() ) { config.parsingScript = parsingScript; } else { assert(false); } } void ImportAnnotationsFromCSVDialog::toTaskConfig(ImportAnnotationsFromCSVTaskConfig& config) const { assert(result() == QDialog::Accepted); toParsingConfig(config.parsingOptions); config.csvFile = readFileName->text(); config.df = saveGroupController->getFormatToSave(); config.dstFile = saveGroupController->getSaveFileName(); config.addToProject = addToProjectCheck->isChecked(); } #define PREVIEW_BUFF_SIZE 8196 QString ImportAnnotationsFromCSVDialog::readFileHeader(const QString& fileName, bool silentFail) { IOAdapterId ioId = BaseIOAdapters::url2io(fileName); IOAdapterFactory* iof = AppContext::getIOAdapterRegistry()->getIOAdapterFactoryById(ioId); std::auto_ptr io(iof->createIOAdapter()); bool ok = io->open(fileName, IOAdapterMode_Read); if (!ok) { if (!silentFail) { QMessageBox::critical(this, L10N::errorTitle(), L10N::errorOpeningFileRead(fileName)); readFileName->setFocus(); } return QString(); } QByteArray previewBuff; previewBuff.resize(PREVIEW_BUFF_SIZE); qint64 bytesRead = io->readBlock(previewBuff.data(), PREVIEW_BUFF_SIZE); if (bytesRead == -1) { if (!silentFail) { QMessageBox::critical(this, L10N::errorTitle(), L10N::errorReadingFile(GUrl(fileName))); readFileName->setFocus(); } return QString(); } assert(bytesRead >= 0); previewBuff.resize(bytesRead); return QString::fromLocal8Bit(previewBuff); } void ImportAnnotationsFromCSVDialog::sl_removeQuotesToggled(bool) { guessSeparator(true); } void ImportAnnotationsFromCSVDialog::sl_separatorsModeToggled(bool) { guessSeparator(true); } void ImportAnnotationsFromCSVDialog::sl_linesToSkipChanged(int) { guessSeparator(true); } void ImportAnnotationsFromCSVDialog::sl_guessSeparatorClicked() { guessSeparator(false); } void ImportAnnotationsFromCSVDialog::sl_scriptSeparatorClicked() { if (parsingScript.isEmpty()) { lastUsedSeparator = separatorEdit->text(); } ScriptEditorDialog d(this, scriptHeader); if (!parsingScript.isEmpty()) { d.setScriptText(parsingScript); } else { //set sample script QString l1 = "var firstColumn = ["+ReadCSVAsAnnotationsTask::LINE_NUM_VAR+"];\n"; QString l2 = "var otherColumns = "+ReadCSVAsAnnotationsTask::LINE_VAR+".split(\" \");\n"; QString l3 = "result =firstColumn.concat(otherColumns);"; d.setScriptText(l1 + l2 + l3); } int rc = d.exec(); if (rc != QDialog::Accepted) { return; } parsingScript = d.getScriptText(); separatorEdit->setText(lastUsedSeparator); } void ImportAnnotationsFromCSVDialog::guessSeparator(bool silent) { QString url = checkInputGroup(silent); if (url.isEmpty()) { return; } QString text = readFileHeader(url, silent); CSVParsingConfig config; toParsingConfig(config); QString sep = ReadCSVAsAnnotationsTask::guessSeparatorString(text, config); if (sep.isEmpty()) { if (!silent) { QMessageBox::critical(this, L10N::errorTitle(), tr("Failed to guess separator sequence!")); readFileName->setFocus(); } return; } separatorEdit->setText(sep); preview(silent); } static QString toHex(const QString& text) { QString rawHex = text.toLocal8Bit().toHex(); QString res; for (int i=0; i 0 ? " ": "") + hexPart; } return res; } void ImportAnnotationsFromCSVDialog::sl_separatorChanged(const QString& v) { if (v.isEmpty()) { separatorLabel->setText(tr("Column separator")); } else { separatorLabel->setText(tr("Column separator value: [%1], hex: [%2], length: %3") .arg(v).arg(toHex(v)).arg(v.length())); if (v.trimmed().length() == 0) { separatorsModeCheck->setChecked(true); } } if (!v.isEmpty() && TextUtils::contains(CSVParsingConfig::QUOTES, v.toLocal8Bit().constData(), v.length())) { removeQuotesCheck->setChecked(false); } } void ImportAnnotationsFromCSVDialog::sl_prefixToSkipChanged(const QString& v) { skipPrefixLabel->setEnabled(!v.isEmpty()); } void ImportAnnotationsFromCSVDialog::sl_readFileClicked() { // show the dialog LastOpenDirHelper lod("CSV"); QString filter = DialogUtils::prepareFileFilter(tr("CSV Files"), QStringList() << "csv", true, QStringList()); lod.url = QFileDialog::getOpenFileName(this, tr("Select CSV file to read"), lod, filter); if (lod.url.isEmpty()) { return; } readFileName->setText(lod.url); // guess separator & show preview guessSeparator(true); } QString ImportAnnotationsFromCSVDialog::checkInputGroup(bool silent) { QString inputFile = readFileName->text(); if (inputFile.isEmpty()) { if (!silent) { QMessageBox::critical(this, L10N::errorTitle(), tr("Enter input CSV file name")); readFileName->setFocus(); } return QString(); } QFileInfo csvFile(inputFile); if (!csvFile.exists() || !csvFile.isFile()) { if (!silent) { QMessageBox::critical(this, L10N::errorTitle(), L10N::errorFileNotFound(inputFile)); readFileName->setFocus(); } return QString(); } if (!csvFile.isReadable()) { if (!silent) { QMessageBox::critical(this, L10N::errorTitle(), L10N::errorOpeningFileRead(inputFile)); readFileName->setFocus(); } return QString(); } return csvFile.canonicalFilePath(); } bool ImportAnnotationsFromCSVDialog::checkSeparators(bool silent) { if (columnSeparatorRadioButton->isChecked() && separatorEdit->text().isEmpty() ) { if (!silent) { QMessageBox::critical(this, L10N::errorTitle(), tr("Separator value is not set")); separatorEdit->setFocus(); } return false; } else if( scriptRadioButton->isChecked() && parsingScript.isEmpty() ){ if (!silent) { QMessageBox::critical(this, L10N::errorTitle(), tr("Script is empty")); } return false; } return true; } QString ImportAnnotationsFromCSVDialog::checkOutputGroup() { QString outFile = saveGroupController->getSaveFileName(); if (outFile.isEmpty()) { QMessageBox::critical(this, L10N::errorTitle(), tr("Output file name is not set!")); saveFileName->setFocus(); return QString(); } if (saveGroupController->getFormatToSave() == NULL) { QMessageBox::critical(this, L10N::errorTitle(), tr("Output file format is not set!")); saveFormatCombo->setFocus(); return QString(); } return outFile; } void ImportAnnotationsFromCSVDialog::sl_previewClicked() { preview(false); } void ImportAnnotationsFromCSVDialog::preview(bool silent) { QString fileName = checkInputGroup(silent); if (fileName.isEmpty()) { return; } QString text = readFileHeader(fileName, silent); previewTable->clear(); rawPreview->clear(); rawPreview->setPlainText(text); if (!checkSeparators(true)) { return; } CSVParsingConfig parseOptions; toParsingConfig(parseOptions); if (parseOptions.splitToken.isEmpty() && parseOptions.parsingScript.isEmpty()) { return; } int columnCount = 0; TaskStateInfo ti; QList lines = ReadCSVAsAnnotationsTask::parseLinesIntoTokens(text, parseOptions, columnCount, ti); if (ti.hasError()) { QMessageBox::critical(this, L10N::errorTitle(), ti.getError()); return; } prepareColumnsConfig(columnCount); columnCount = qMax(columnCount, columnsConfig.size()); previewTable->setRowCount(lines.size()); previewTable->setColumnCount(columnCount); for (int column = 0; column < columnCount; column++) { QTableWidgetItem* headerItem = createHeaderItem(column); previewTable->setHorizontalHeaderItem(column, headerItem); } for (int row = 0; row < lines.size(); row++) { const QStringList& rowData = lines.at(row); for (int column = 0; column < rowData.size(); column ++) { QString token = rowData.at(column); QTableWidgetItem* item = new QTableWidgetItem(token); item->setFlags(Qt::ItemIsEnabled); previewTable->setItem(row, column, item); } } } void ImportAnnotationsFromCSVDialog::prepareColumnsConfig(int numColumns) { while (columnsConfig.size() < numColumns) { columnsConfig.append(ColumnConfig()); } while (columnsConfig.size() > numColumns) { const ColumnConfig& config = columnsConfig.last(); if (config.role == ColumnRole_Ignore) { columnsConfig.removeLast(); } } } QTableWidgetItem* ImportAnnotationsFromCSVDialog::createHeaderItem(int column) const { assert(column >=0 && column < columnsConfig.size()); QString text = getHeaderItemText(column); return new QTableWidgetItem(text); } QString ImportAnnotationsFromCSVDialog::getHeaderItemText(int column) const { const ColumnConfig& config = columnsConfig.at(column); QString text = tr("[ignored]"); switch (config.role) { case ColumnRole_Qualifier: text = tr("[qualifier %1]").arg(config.qualifierName); break; case ColumnRole_Name: text = tr("[name]"); break; case ColumnRole_StartPos: if (config.startPositionOffset!=0) { text = tr("[start position with offset %1]").arg(config.startPositionOffset); } else { text = tr("[start position]"); } break; case ColumnRole_EndPos: if (config.endPositionIsInclusive) { text = tr("[end position (inclusive)]"); } else { text = tr("[end position]"); } break; case ColumnRole_Length: text = tr("[length]"); break; case ColumnRole_ComplMark: if (config.complementMark.isEmpty()) { text = tr("[complement]"); } else { text = tr("[complement if '%1']").arg(config.complementMark); } break; default: assert(config.role == ColumnRole_Ignore); } return text; } void ImportAnnotationsFromCSVDialog::sl_tableItemClicked(QTableWidgetItem* item) { int column = previewTable->column(item); configureColumn(column); } void ImportAnnotationsFromCSVDialog::sl_tableHeaderClicked(int column) { configureColumn(column); } void ImportAnnotationsFromCSVDialog::sl_separatorRadioToggled(bool checked) { separatorEdit->setEnabled(checked); guessButton->setEnabled(checked); } void ImportAnnotationsFromCSVDialog::sl_scriptRadioToggled(bool checked) { scriptButton->setEnabled(checked); if(checked && parsingScript.isEmpty()) { sl_scriptSeparatorClicked(); } } void ImportAnnotationsFromCSVDialog::configureColumn(int column) { assert(column >= 0 && column < columnsConfig.size()); const ColumnConfig& config = columnsConfig.at(column); CSVColumnConfigurationDialog d(this, config); int rc = d.exec(); // TODO: set dialog position close to the header item if (rc == QDialog::Accepted) { columnsConfig[column] = d.config; } previewTable->horizontalHeaderItem(column)->setText(getHeaderItemText(column)); } } //namespace ugene-1.9.8/src/plugins/dna_export/src/ExportAlignmentViewItems.cpp0000644000175000017500000001046011651544322024201 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "ExportAlignmentViewItems.h" #include "ExportUtils.h" #include "ExportTasks.h" #include "ExportMSA2MSADialog.h" #include #include #include #include #include #include #include #include #include #include #include #include #include namespace U2 { ////////////////////////////////////////////////////////////////////////// // ExportAlignmentViewItemsController ExportAlignmentViewItemsController::ExportAlignmentViewItemsController(QObject* p) : GObjectViewWindowContext(p, MSAEditorFactory::ID) { } void ExportAlignmentViewItemsController::initViewContext(GObjectView* v) { MSAEditor* msaed = qobject_cast(v); assert(msaed!=NULL); MSAExportContext* mc= new MSAExportContext(msaed); addViewResource(msaed, mc); } void ExportAlignmentViewItemsController::buildMenu(GObjectView* v, QMenu* m) { QList resources = viewResources.value(v); assert(resources.size() == 1); QObject* r = resources.first(); MSAExportContext* mc = qobject_cast(r); assert(mc!=NULL); mc->buildMenu(m); } ////////////////////////////////////////////////////////////////////////// // MSA view context MSAExportContext::MSAExportContext(MSAEditor* e) : editor(e) { translateMSAAction = new QAction(tr("Amino translation of alignment rows..."), this); connect(translateMSAAction, SIGNAL(triggered()), SLOT(sl_exportNucleicMsaToAmino())); } void MSAExportContext::updateActions() { translateMSAAction->setEnabled(editor->getMSAObject()->getAlphabet()->isNucleic()); } void MSAExportContext::buildMenu(QMenu* m) { QMenu* exportMenu = GUIUtils::findSubMenu(m, MSAE_MENU_EXPORT); MAlignmentObject* mObject = editor->getMSAObject(); if (mObject->getAlphabet()->isNucleic()) { exportMenu->addAction(translateMSAAction); } } void MSAExportContext::sl_exportNucleicMsaToAmino() { const MAlignment& ma = editor->getMSAObject()->getMAlignment(); assert(ma.getAlphabet()->isNucleic()); QString fileExt = AppContext::getDocumentFormatRegistry()->getFormatById(BaseDocumentFormats::CLUSTAL_ALN)->getSupportedDocumentFileExtensions().first(); GUrl msaUrl = editor->getMSAObject()->getDocument()->getURL(); GUrl defaultUrl = GUrlUtils::rollFileName(msaUrl.dirPath() + "/" + msaUrl.baseFileName() + "_transl." + fileExt, DocumentUtils::getNewDocFileNameExcludesHint()); ExportMSA2MSADialog d(defaultUrl.getURLString(), BaseDocumentFormats::CLUSTAL_ALN, editor->getCurrentSelection().height() < 1, AppContext::getMainWindow()->getQMainWindow()); d.setWindowTitle(translateMSAAction->text()); int rc = d.exec(); if (rc == QDialog::Rejected) { return; } QList trans; trans << AppContext::getDNATranslationRegistry()->lookupTranslation(d.translationTable); int offset = d.exportWholeAlignment ? 0 : editor->getCurrentSelection().top(); int len = d.exportWholeAlignment ? ma.getNumRows() : editor->getCurrentSelection().height(); Task* t = ExportUtils::wrapExportTask(new ExportMSA2MSATask(ma, offset, len, d.file, trans, d.formatId), d.addToProjectFlag); AppContext::getTaskScheduler()->registerTopLevelTask(t); } } //namespace ugene-1.9.8/src/plugins/dna_export/src/ExportProjectViewItems.cpp0000644000175000017500000004357211651544322023703 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "ExportProjectViewItems.h" #include "ExportSequenceTask.h" #include "ExportSequencesDialog.h" #include "ExportSequences2MSADialog.h" #include "ExportMSA2SequencesDialog.h" #include "ExportMSA2MSADialog.h" #include "ExportChromatogramDialog.h" #include "ExportAnnotationsDialog.h" #include "ExportAnnotations2CSVTask.h" #include "ExportUtils.h" #include "ImportAnnotationsFromCSVDialog.h" #include "ImportAnnotationsFromCSVTask.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include namespace U2 { ExportProjectViewItemsContoller::ExportProjectViewItemsContoller(QObject* p) : QObject(p) { exportSequencesToSequenceFormatAction = new QAction(tr("Export sequences"), this); connect(exportSequencesToSequenceFormatAction, SIGNAL(triggered()), SLOT(sl_saveSequencesToSequenceFormat())); exportSequencesAsAlignmentAction = new QAction(tr("Export sequences as alignment"), this); connect(exportSequencesAsAlignmentAction, SIGNAL(triggered()), SLOT(sl_saveSequencesAsAlignment())); exportAlignmentAsSequencesAction = new QAction(tr("Export alignment to sequence format"), this); connect(exportAlignmentAsSequencesAction, SIGNAL(triggered()), SLOT(sl_saveAlignmentAsSequences())); exportNucleicAlignmentToAminoAction = new QAction(tr("Export nucleic alignment to amino translation"), this); connect(exportNucleicAlignmentToAminoAction, SIGNAL(triggered()), SLOT(sl_exportNucleicAlignmentToAmino())); importAnnotationsFromCSVAction = new QAction(tr("Import annotations from CSV file"), this); connect(importAnnotationsFromCSVAction, SIGNAL(triggered()), SLOT(sl_importAnnotationsFromCSV())); exportDNAChromatogramAction = new QAction(tr("Export chromatogram to SCF"), this); connect(exportDNAChromatogramAction, SIGNAL(triggered()), SLOT(sl_exportChromatogramToSCF())); exportAnnotations2CSV = new QAction(tr("Export annotations"), this); connect(exportAnnotations2CSV, SIGNAL(triggered()), SLOT(sl_exportAnnotations())); ProjectView* pv = AppContext::getProjectView(); assert(pv!=NULL); connect(pv, SIGNAL(si_onDocTreePopupMenuRequested(QMenu&)), SLOT(sl_addToProjectViewMenu(QMenu&))); } void ExportProjectViewItemsContoller::sl_addToProjectViewMenu(QMenu& m) { addExportMenu(m); addImportMenu(m); } #define ACTION_PROJECT__EXPORT_MENU "action_project__export_menu" #define ACTION_PROJECT__IMPORT_MENU "action_project__import_menu" void ExportProjectViewItemsContoller::addExportMenu(QMenu& m) { ProjectView* pv = AppContext::getProjectView(); assert(pv!=NULL); QMenu* sub = NULL; MultiGSelection ms; ms.addSelection(pv->getGObjectSelection()); ms.addSelection(pv->getDocumentSelection()); QList set = SelectionUtils::findObjects(GObjectTypes::SEQUENCE, &ms, UOF_LoadedOnly); if (!set.isEmpty()) { sub = new QMenu(tr("Export")); sub->addAction(exportSequencesToSequenceFormatAction); sub->addAction(exportSequencesAsAlignmentAction); } else { set = SelectionUtils::findObjects(GObjectTypes::MULTIPLE_ALIGNMENT, &ms, UOF_LoadedOnly); if (set.size() == 1) { sub = new QMenu(tr("Export")); sub->addAction(exportAlignmentAsSequencesAction); GObject* obj = set.first(); MAlignment ma = qobject_cast(obj)->getMAlignment(); if (ma.getAlphabet()->isNucleic()) { sub->addAction(exportNucleicAlignmentToAminoAction); } } } set = SelectionUtils::findObjects(GObjectTypes::ANNOTATION_TABLE, &ms, UOF_LoadedOnly); if (set.size() == 1) { if (sub == NULL) { sub = new QMenu(tr("Export")); } sub->addAction(exportAnnotations2CSV); } set = SelectionUtils::findObjects(GObjectTypes::CHROMATOGRAM, &ms, UOF_LoadedOnly); if (set.size() == 1) { if (sub == NULL) { sub = new QMenu(tr("Export")); } sub->addAction(exportDNAChromatogramAction); } if (sub != NULL) { sub->setObjectName(ACTION_PROJECT__EXPORT_MENU); QAction* beforeAction = GUIUtils::findActionAfter(m.actions(), ACTION_PROJECT__ADD_MENU); m.insertMenu(beforeAction, sub); } } void ExportProjectViewItemsContoller::addImportMenu(QMenu& m) { QMenu* importMenu = new QMenu(tr("Import")); importMenu->setObjectName(ACTION_PROJECT__IMPORT_MENU); importMenu->addAction(importAnnotationsFromCSVAction); QAction* beforeAction = GUIUtils::findActionAfter(m.actions(), ACTION_PROJECT__ADD_MENU); m.insertMenu(beforeAction, importMenu); } static bool hasComplementForAll(const QList& set) { foreach(GObject* o, set) { DNASequenceObject* so = qobject_cast(o); if (o == NULL || GObjectUtils::findComplementTT(so) == NULL) { return false; } } return true; } static bool hasAminoForAll(const QList& set) { foreach(GObject* o, set) { DNASequenceObject* so = qobject_cast(o); if (o == NULL || GObjectUtils::findAminoTT(so, false, NULL) == NULL) { return false; } } return true; } static bool hasNucleicForAll(const QList& set) { foreach(GObject* o, set) { DNASequenceObject* so = qobject_cast(o); if (o == NULL || GObjectUtils::findBackTranslationTT(so) == NULL) { return false; } } return true; } void ExportProjectViewItemsContoller::sl_saveSequencesToSequenceFormat() { ProjectView* pv = AppContext::getProjectView(); assert(pv!=NULL); MultiGSelection ms; ms.addSelection(pv->getGObjectSelection()); ms.addSelection(pv->getDocumentSelection()); QList set = SelectionUtils::findObjects(GObjectTypes::SEQUENCE, &ms, UOF_LoadedOnly); if (set.isEmpty()) { QMessageBox::critical(NULL, L10N::errorTitle(), tr("No sequence objects selected!")); return; } bool allowMerge = set.size() > 1; bool allowComplement = hasComplementForAll(set); bool allowTranslate = hasAminoForAll(set); bool allowBackTranslate = hasNucleicForAll(set); QFileInfo fi((*set.constBegin())->getDocument()->getURLString()); QString defaultFileNameDir = fi.absoluteDir().absolutePath(); QString defaultFileName = defaultFileNameDir + "/" + fi.baseName() + "_new.fa"; ExportSequencesDialog d(allowMerge, allowComplement, allowTranslate, allowBackTranslate, defaultFileName, BaseDocumentFormats::PLAIN_FASTA, AppContext::getMainWindow()->getQMainWindow()); d.setWindowTitle(exportSequencesToSequenceFormatAction->text()); int rc = d.exec(); if (rc == QDialog::Rejected) { return; } assert(d.file.length() > 0); ExportSequenceTaskSettings s; ExportUtils::loadDNAExportSettingsFromDlg(s,d); QList allAnnotationTables = s.saveAnnotations ? GObjectUtils::findAllObjects(UOF_LoadedOnly, GObjectTypes::ANNOTATION_TABLE) : QList(); QStringList objectNames; foreach(GObject* o, set) { DNASequenceObject* so = qobject_cast(o); QString docUrl = so->getDocument()->getURLString(); QList anns; if (s.saveAnnotations) { foreach(GObject* aObj, allAnnotationTables) { if (aObj->hasObjectRelation(so, GObjectRelationRole::SEQUENCE)) { AnnotationTableObject* annObj = qobject_cast(aObj); foreach(const Annotation* ann, annObj->getAnnotations()) { anns.append(ann->data()); } } } } ExportSequenceItem ei; ei.sequence = so->getDNASequence(); ei.annotations = anns; ei.complTT = GObjectUtils::findComplementTT(so); ei.aminoTT = d.translate ? GObjectUtils::findAminoTT(so, false, d.useSpecificTable ? d.translationTable : NULL) : NULL; ei.backTT = d.backTranslate ? GObjectUtils::findBackTranslationTT(so, d.translationTable) : NULL; s.items.append(ei); } Task* t = ExportUtils::wrapExportTask(new ExportSequenceTask(s), d.addToProject); AppContext::getTaskScheduler()->registerTopLevelTask(t); } void ExportProjectViewItemsContoller::sl_saveSequencesAsAlignment() { ProjectView* pv = AppContext::getProjectView(); assert(pv!=NULL); MultiGSelection ms; ms.addSelection(pv->getGObjectSelection()); ms.addSelection(pv->getDocumentSelection()); QList sequenceObjects = SelectionUtils::findObjectsKeepOrder(GObjectTypes::SEQUENCE, &ms, UOF_LoadedOnly); if (sequenceObjects.isEmpty()) { QMessageBox::critical(NULL, L10N::errorTitle(), tr("No sequence objects selected!")); return; } U2OpStatusImpl os; MAlignment ma = MSAUtils::seq2ma(sequenceObjects, os); if (os.hasError()) { QMessageBox::critical(NULL, L10N::errorTitle(), os.getError()); return; } QString fileExt = AppContext::getDocumentFormatRegistry()->getFormatById(BaseDocumentFormats::CLUSTAL_ALN)->getSupportedDocumentFileExtensions().first(); GUrl seqUrl = sequenceObjects.first()->getDocument()->getURL(); GUrl defaultUrl = GUrlUtils::rollFileName(seqUrl.dirPath() + "/" + seqUrl.baseFileName() + "." + fileExt, DocumentUtils::getNewDocFileNameExcludesHint()); ExportSequences2MSADialog d(AppContext::getMainWindow()->getQMainWindow(), defaultUrl.getURLString()); d.setWindowTitle(exportSequencesAsAlignmentAction->text()); int rc = d.exec(); if (rc != QDialog::Accepted) { return; } QString objName = GUrl(d.url).baseFileName(); ma.setName(objName); Task* t = ExportUtils::wrapExportTask(new ExportAlignmentTask(ma, d.url, d.format), d.addToProjectFlag); AppContext::getTaskScheduler()->registerTopLevelTask(t); } void ExportProjectViewItemsContoller::sl_saveAlignmentAsSequences() { ProjectView* pv = AppContext::getProjectView(); assert(pv!=NULL); MultiGSelection ms; ms.addSelection(pv->getGObjectSelection()); ms.addSelection(pv->getDocumentSelection()); QList set = SelectionUtils::findObjects(GObjectTypes::MULTIPLE_ALIGNMENT, &ms, UOF_LoadedOnly); if (set.size()!=1) { QMessageBox::critical(NULL, L10N::errorTitle(), tr("Select one alignment object to export")); return; } GObject* obj = set.first(); MAlignmentObject* maObject = qobject_cast(obj); const MAlignment& ma = maObject->getMAlignment(); ExportMSA2SequencesDialog d(AppContext::getMainWindow()->getQMainWindow()); d.setWindowTitle(exportAlignmentAsSequencesAction->text()); int rc = d.exec(); if (rc == QDialog::Rejected) { return; } Task* t = ExportUtils::wrapExportTask(new ExportMSA2SequencesTask(ma, d.url, d.trimGapsFlag, d.format), d.addToProjectFlag); AppContext::getTaskScheduler()->registerTopLevelTask(t); } void ExportProjectViewItemsContoller::sl_exportNucleicAlignmentToAmino() { ProjectView* pv = AppContext::getProjectView(); assert(pv!=NULL); MultiGSelection ms; ms.addSelection(pv->getGObjectSelection()); ms.addSelection(pv->getDocumentSelection()); QList set = SelectionUtils::findObjects(GObjectTypes::MULTIPLE_ALIGNMENT, &ms, UOF_LoadedOnly); if (set.size()!=1) { QMessageBox::critical(NULL, L10N::errorTitle(), tr("Select one alignment object to export")); return; } GObject* obj = set.first(); MAlignment ma = qobject_cast(obj)->getMAlignment(); GObject* firstObject = set.first(); Document* doc = firstObject->getDocument(); QString fileExt = AppContext::getDocumentFormatRegistry()->getFormatById(BaseDocumentFormats::CLUSTAL_ALN)->getSupportedDocumentFileExtensions().first(); GUrl msaUrl = doc->getURLString(); GUrl defaultUrl = GUrlUtils::rollFileName(msaUrl.dirPath() + "/" + msaUrl.baseFileName() + "_transl." + fileExt, DocumentUtils::getNewDocFileNameExcludesHint()); ExportMSA2MSADialog d(defaultUrl.getURLString(), BaseDocumentFormats::CLUSTAL_ALN, true, AppContext::getMainWindow()->getQMainWindow()); d.setWindowTitle(exportAlignmentAsSequencesAction->text()); int rc = d.exec(); if (rc == QDialog::Rejected) { return; } QList trans; trans << AppContext::getDNATranslationRegistry()->lookupTranslation(d.translationTable); Task* t = ExportUtils::wrapExportTask(new ExportMSA2MSATask(ma, 0, ma.getNumRows(), d.file, trans, d.formatId), d.addToProjectFlag); AppContext::getTaskScheduler()->registerTopLevelTask(t); } void ExportProjectViewItemsContoller::sl_importAnnotationsFromCSV() { ImportAnnotationsFromCSVDialog d(AppContext::getMainWindow()->getQMainWindow()); int rc = d.exec(); if (rc != QDialog::Accepted) { return; } ImportAnnotationsFromCSVTaskConfig taskConfig; d.toTaskConfig(taskConfig); ImportAnnotationsFromCSVTask* task = new ImportAnnotationsFromCSVTask(taskConfig); AppContext::getTaskScheduler()->registerTopLevelTask(task); } void ExportProjectViewItemsContoller::sl_exportChromatogramToSCF() { ProjectView* pv = AppContext::getProjectView(); assert(pv!=NULL); MultiGSelection ms; ms.addSelection(pv->getGObjectSelection()); ms.addSelection(pv->getDocumentSelection()); QList set = SelectionUtils::findObjects(GObjectTypes::CHROMATOGRAM, &ms, UOF_LoadedOnly); if (set.size() != 1 ) { QMessageBox::warning(NULL, L10N::errorTitle(), tr("Select one chromatogram object to export")); return; } GObject* obj = set.first(); DNAChromatogramObject* chromaObj = qobject_cast(obj); assert(chromaObj != NULL); ExportChromatogramDialog d(QApplication::activeWindow(), chromaObj->getDocument()->getURL()); int rc = d.exec(); if (rc == QDialog::Rejected) { return; } ExportChromatogramTaskSettings settings; settings.url = d.url; settings.complement = d.complemented; settings.reverse = d.reversed; settings.loadDocument = d.addToProjectFlag; Task* task = ExportUtils::wrapExportTask(new ExportDNAChromatogramTask(chromaObj, settings), d.addToProjectFlag); AppContext::getTaskScheduler()->registerTopLevelTask(task); } void ExportProjectViewItemsContoller::sl_exportAnnotations() { // find annotations: whole annotation file ProjectView* pv = AppContext::getProjectView(); assert(pv!=NULL); MultiGSelection ms; ms.addSelection(pv->getGObjectSelection()); ms.addSelection(pv->getDocumentSelection()); QList set = SelectionUtils::findObjects(GObjectTypes::ANNOTATION_TABLE, &ms, UOF_LoadedOnly); if (set.size() != 1 ) { QMessageBox::warning(QApplication::activeWindow(), exportAnnotations2CSV->text(), tr("Select one annotation object to export")); return; } GObject* obj = set.first(); AnnotationTableObject* aObj = qobject_cast(obj); assert(aObj != NULL); QList annotations = aObj->getAnnotations(); if (annotations.size() == 0 ) { QMessageBox::warning(QApplication::activeWindow(), exportAnnotations2CSV->text(), tr("Selected object doesn't have annotations")); return; } Annotation* first = annotations.first(); const GUrl& url = first->getGObject()->getDocument()->getURL(); QString fileName = GUrlUtils::rollFileName(url.dirPath() + "/" + url.baseFileName() + "_annotations.csv", DocumentUtils::getNewDocFileNameExcludesHint()); ExportAnnotationsDialog d(fileName, QApplication::activeWindow()); d.setWindowTitle(exportAnnotations2CSV->text()); d.setExportSequenceVisible(false); if (QDialog::Accepted != d.exec()) { return; } // TODO: lock documents or use shared-data objects // same as in ADVExportContext::sl_saveSelectedAnnotations() qStableSort(annotations.begin(), annotations.end(), Annotation::annotationLessThan); // run task Task * t = NULL; if(d.fileFormat() == ExportAnnotationsDialog::CSV_FORMAT_ID) { t = new ExportAnnotations2CSVTask(annotations, QByteArray(),NULL, false, d.filePath()); } else { t = ExportUtils::saveAnnotationsTask(d.filePath(), d.fileFormat(), annotations); } AppContext::getTaskScheduler()->registerTopLevelTask(t); } } //namespace ugene-1.9.8/src/plugins/dna_export/src/ExportAnnotations2CSVTask.h0000644000175000017500000000303211651544322023646 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_EXPORT_ANNOTATIONS_2_CSV_TASK_H_ #define _U2_EXPORT_ANNOTATIONS_2_CSV_TASK_H_ #include #include namespace U2 { class Annotation; class ExportAnnotations2CSVTask : public Task { Q_OBJECT public: ExportAnnotations2CSVTask( const QList& annotations, const QByteArray& sequence, DNATranslation *complementTranslation, bool exportSequence, const QString& url, bool append = false); void run(); private: QList annotations; QByteArray sequence; DNATranslation *complementTranslation; bool exportSequence; QString url; bool append; }; } // namespace U2 #endif ugene-1.9.8/src/plugins/dna_export/src/ExportSequencesDialog.h0000644000175000017500000000410611651544322023146 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_EXPORT_SEQUENCES_DIALOG_H_ #define _U2_EXPORT_SEQUENCES_DIALOG_H_ #include #include #include namespace U2 { class SaveDocumentGroupController; class ExportSequencesDialog : public QDialog, Ui_ExportSequencesDialog { Q_OBJECT public: ExportSequencesDialog(bool multiMode, bool allowComplement, bool allowTranslation, bool allowBackTranslation, const QString& defaultFileName, const DocumentFormatId& f, QWidget* p); void updateModel(); bool multiMode; DocumentFormatId formatId; QString file; TriState strand;//Yes-> direct, No->complement, Unkn -> both bool translate; bool translateAllFrames; bool useSpecificTable; QString translationTable; bool backTranslate; bool mostProbable; bool merge; bool addToProject; int mergeGap; bool withAnnotations; void disableAllFramesOption(bool v); void disableStrandOption(bool v); void disableAnnotationsOption(bool v); private slots: void sl_exportClicked(); void sl_translationTableEnabler(); void sl_formatChanged(int); private: SaveDocumentGroupController* saveGroupContoller; QList tableID; }; }//namespace #endif ugene-1.9.8/src/plugins/dna_export/src/DNASequenceGeneratorDialog.h0000644000175000017500000000351611651544322023757 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_DNA_SEQUENCE_GENERATOR_DIALOG_H_ #define _U2_DNA_SEQUENCE_GENERATOR_DIALOG_H_ #include "ui_DNASequenceGeneratorDialog.h" #include "ui_BaseContentDialog.h" namespace U2 { class SaveDocumentGroupController; class DNASequenceGeneratorDialog : public QDialog, public Ui_DNASequenceGeneratorDialog { Q_OBJECT public: DNASequenceGeneratorDialog(QWidget* p=NULL); private slots: void sl_browseReference(); void sl_configureContent(); void sl_generate(); void sl_refButtonToggled(bool checked); void sl_stateChanged(int state); private: SaveDocumentGroupController* saveGroupContoller; static QMap content; }; class BaseContentDialog : public QDialog, public Ui_BaseContentDialog { Q_OBJECT public: BaseContentDialog(QMap& percentMap_, QWidget* p=NULL); private slots: void sl_save(); void sl_baseClicked(); void sl_gcSkewClicked(); private: QMap& percentMap; float gcSkew; float gcSkewPrev; }; } //namespace #endif ugene-1.9.8/src/plugins/dna_export/src/CSVColumnConfigurationDialog.h0000644000175000017500000000262611651544322024357 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_CSV_COLUMN_CONFIGURATION_DIALOG_H_ #define _U2_CSV_COLUMN_CONFIGURATION_DIALOG_H_ #include #include "CSVColumnConfiguration.h" namespace U2 { class CSVColumnConfigurationDialog : public QDialog, Ui_CSVColumnConfigurationDialog { Q_OBJECT public: CSVColumnConfigurationDialog(QWidget* w, const ColumnConfig& config); ColumnConfig config; public slots: virtual void accept(); private slots: virtual void sl_complMarkToggle(bool); virtual void sl_startToggle(bool); }; } // namespace U2 #endif ugene-1.9.8/src/plugins/dna_export/src/DNASequenceGenerator.cpp0000644000175000017500000002571711651544322023201 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "DNASequenceGenerator.h" #include #include #include #include #include #include #include #include #include #include #include namespace U2 { int getRandomInt(int max) { return qrand() % (max + 1); } const QString DNASequenceGenerator::ID("dna_generator"); QString DNASequenceGenerator::prepareReferenceFileFilter() { QString filter = DialogUtils::prepareDocumentsFileFilterByObjType(GObjectTypes::SEQUENCE, true) + ";;" + DialogUtils::prepareDocumentsFileFilterByObjType(GObjectTypes::MULTIPLE_ALIGNMENT, false); return filter; } void DNASequenceGenerator::generateSequence(const QMap& charFreqs, int length, QByteArray& result) { QMap content; QMapIterator iter(charFreqs); assert(iter.hasNext()); iter.next(); char ch = iter.key(); int total = 0; while (iter.hasNext()) { iter.next(); char ch = iter.key(); qreal percent = iter.value(); assert(percent>=0 && percent<=1); int num = length * percent; total += num; content.insertMulti(ch, num); } assert(total>=0 && total<=length); content[ch] = length - total; result.resize(length); for (int idx = 0; idx < length; idx++) { int rnd = getRandomInt(length - idx - 1); assert(rnd < length - idx); int charRange = 0; foreach(char ch, content.keys()) { charRange += content.value(ch); if (rnd < charRange) { --content[ch]; result[idx] = ch; break; } } } } void evaluate(const QByteArray& seq, QMap& result) { QMap occurrencesMap; foreach(char ch, seq) { if (!occurrencesMap.keys().contains(ch)) { occurrencesMap.insertMulti(ch, 1); } else { ++occurrencesMap[ch]; } } qreal len = seq.length(); QMapIterator i(occurrencesMap); while (i.hasNext()) { i.next(); int count = i.value(); qreal freq = count / len; result.insertMulti(i.key(), freq); } } void DNASequenceGenerator::evaluateBaseContent(const DNASequence& sequence, QMap& result) { evaluate(sequence.seq, result); } void DNASequenceGenerator::evaluateBaseContent(const MAlignment& ma, QMap& result) { QList< QMap > rowsContents; foreach(const MAlignmentRow& row, ma.getRows()) { QMap rowContent; evaluate(row.getCore(), rowContent); rowsContents.append(rowContent); } QListIterator< QMap > listIter(rowsContents); while (listIter.hasNext()) { const QMap& cm = listIter.next(); QMapIterator mapIter(cm); while (mapIter.hasNext()) { mapIter.next(); char ch = mapIter.key(); qreal freq = mapIter.value(); if (!result.keys().contains(ch)) { result.insertMulti(ch, freq); } else { result[ch] += freq; } } } int rowsNum = ma.getNumRows(); QMutableMapIterator i(result); while (i.hasNext()) { i.next(); i.value() /= rowsNum; } } // DNASequenceGeneratorTask ////////////////////////////////////////////////////////////////////////// EvaluateBaseContentTask* DNASequenceGeneratorTask::createEvaluationTask(Document* doc, QString& err) { assert(doc->isLoaded()); QList gobjects = doc->findGObjectByType(GObjectTypes::SEQUENCE); gobjects << doc->findGObjectByType(GObjectTypes::MULTIPLE_ALIGNMENT); if (!gobjects.isEmpty()) { return new EvaluateBaseContentTask(gobjects.first()); } err = tr("Reference for sequence generator has to be a sequence or an alignment"); return NULL; } DNASequenceGeneratorTask::DNASequenceGeneratorTask(const DNASequenceGeneratorConfig& cfg_) : Task(tr("Generate sequence task"), TaskFlag_NoRun), cfg(cfg_), loadRefTask(NULL), evalTask(NULL), generateTask(NULL), saveTask(NULL) { if (cfg.useReference()) { // do not load reference file if it is already in project and has loaded state const QString& docUrl = cfg.getReferenceUrl(); Project* prj = AppContext::getProject(); if (prj) { Document* doc = prj->findDocumentByURL(docUrl); if (doc && doc->isLoaded()) { QString err; evalTask = createEvaluationTask(doc, err); if (evalTask) { addSubTask(evalTask); } else { stateInfo.setError(err); } return; } } loadRefTask = LoadDocumentTask::getDefaultLoadDocTask(GUrl(docUrl)); if (loadRefTask) { addSubTask(loadRefTask); } else { stateInfo.setError(tr("Incorrect reference file")); return; } } else { generateTask = new GenerateDNASequenceTask(cfg.getContent(), cfg.getLength(), cfg.window, cfg.getNumberOfSequences(), cfg.seed); addSubTask(generateTask); } } QList DNASequenceGeneratorTask::onSubTaskFinished(Task* subTask) { QList tasks; if (hasError() || isCanceled()) { return tasks; } if (subTask == loadRefTask) { QString err; Document* doc = loadRefTask->getDocument(); evalTask = createEvaluationTask(doc, err); if (evalTask) { tasks.append(evalTask); } else { stateInfo.setError(err); } } else if (subTask == evalTask) { cfg.alphabet = evalTask->getAlphabet(); QMap content = evalTask->getResult(); generateTask = new GenerateDNASequenceTask(content, cfg.getLength(), cfg.window, cfg.getNumberOfSequences(), cfg.seed); tasks.append(generateTask); } else if (subTask == generateTask) { QList< QByteArray > seqs = generateTask->getResult(); const QString& name = cfg.getSequenceName(); DNAAlphabet* alp = cfg.getAlphabet(); assert(alp); IOAdapterFactory * io = AppContext::getIOAdapterRegistry()->getIOAdapterFactoryById(BaseIOAdapters::url2io(cfg.getOutUrlString())); if (seqs.size() == 1) { const QByteArray& seq = seqs.first(); DNASequence dna(name, seq, alp); results.append(dna); } else { for (int i = 0, n = seqs.size(); i sequences; foreach(DNASequence s, results) { DNASequenceObject* dnaObj = new DNASequenceObject(s.getName(), s); sequences.append(dnaObj); } Document* doc = new Document(cfg.getDocumentFormat(), io, GUrl(cfg.getOutUrlString()), sequences); saveTask = new SaveDocumentTask(doc, SaveDoc_Overwrite); tasks.append(saveTask); } } else if (saveTask == subTask) { Document* doc = saveTask->getDocument(); if (!cfg.addToProj) { doc->unload(); delete doc; } else { Project* prj = AppContext::getProject(); if (prj) { Document* d = prj->findDocumentByURL(doc->getURL()); if (d==NULL) { prj->addDocument(doc); tasks << new OpenViewTask(doc); } else { // if document with same url is already exists in project // it will be reloaded by DocumentUpdater => delete this instance doc->unload(); delete doc; } } else { tasks << AppContext::getProjectLoader()->openWithProjectTask(QList() << doc->getURL()); // open project task will load supplied url doc->unload(); delete doc; } } } return tasks; } // EvaluateBaseContentTask EvaluateBaseContentTask::EvaluateBaseContentTask(GObject* obj) : Task(tr("Evaluate base content task"), TaskFlag_None), _obj(obj), alp(NULL) { } void EvaluateBaseContentTask::run() { if (_obj->getGObjectType() == GObjectTypes::SEQUENCE) { DNASequenceObject* dnaObj = qobject_cast(_obj); alp = dnaObj->getAlphabet(); DNASequenceGenerator::evaluateBaseContent(dnaObj->getDNASequence(), result); } else if (_obj->getGObjectType() == GObjectTypes::MULTIPLE_ALIGNMENT) { MAlignmentObject* maObj = qobject_cast(_obj); alp = maObj->getAlphabet(); DNASequenceGenerator::evaluateBaseContent(maObj->getMAlignment(), result); } else { stateInfo.setError(tr("Base content can be evaluated for sequence or sequence alignment")); } } // GenerateTask GenerateDNASequenceTask::GenerateDNASequenceTask(const QMap& baseContent_, int length_, int window_, int count_, int seed_) : Task(tr("Generate DNA sequence task"), TaskFlag_None), baseContent(baseContent_), length(length_), window(window_), count(count_), seed(seed_) { } void GenerateDNASequenceTask::run() { if(seed < 0) { qsrand(QDateTime::currentDateTime().toTime_t()); } else { qsrand(seed); } for (int i=0; i length) { window = length; } for(int i = 0; i< length/window; i++) { DNASequenceGenerator::generateSequence(baseContent, window, tmp); seq.append(tmp); } DNASequenceGenerator::generateSequence(baseContent, length % window, tmp); seq.append(tmp); result.append(seq); } } } //namespace ugene-1.9.8/src/plugins/dna_export/src/ImportAnnotationsFromCSVTask.cpp0000644000175000017500000004125311651544322024743 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "ImportAnnotationsFromCSVTask.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include namespace U2 { QBitArray CSVParsingConfig::QUOTES = TextUtils::createBitMap("\'\""); ImportAnnotationsFromCSVTask::ImportAnnotationsFromCSVTask(ImportAnnotationsFromCSVTaskConfig& _config) : Task(tr("Import annotations from CSV"), TaskFlags_NR_FOSCOE), config(_config), readTask(NULL), writeTask(NULL), addTask(NULL) { assert(config.df != NULL); GCOUNTER(cvar,tvar,"ImportAnnotationsFromCSVTask"); readTask = new ReadCSVAsAnnotationsTask(config.csvFile, config.parsingOptions); addSubTask(readTask); } static void adjustRelations(AnnotationTableObject* ao) { if (!ao->findRelatedObjectsByType(GObjectRelationRole::SEQUENCE).isEmpty()) { return; //nothing to adjust -> already has relation } // try automatically associate annotations doc with active sequence view GObjectViewWindow* activeViewWindow = GObjectViewUtils::getActiveObjectViewWindow(); if (activeViewWindow == NULL) { return; } AnnotatedDNAView* seqView = qobject_cast(activeViewWindow->getObjectView()); if (seqView == NULL) { return; } foreach(DNASequenceObject *seqObj, seqView->getSequenceObjectsWithContexts()){ bool outOfRange = false; foreach(const Annotation* ann, ao->getAnnotations()) { const QVector& locations = ann->getRegions(); if(locations.last().endPos() > seqObj->getSequenceLen()) { outOfRange = true; break; } } if (!outOfRange) { ao->addObjectRelation(seqObj, GObjectRelationRole::SEQUENCE); seqView->addObject(ao); break; } else { algoLog.trace(QString("Annotation is out of the sequence range %1").arg(seqObj->getGObjectName())); } } } QList ImportAnnotationsFromCSVTask::onSubTaskFinished(Task* subTask) { QList result; if (hasError() || subTask == addTask) { return result; } GUrl docUrl(config.dstFile); Document* projDoc = AppContext::getProject()->findDocumentByURL(docUrl); bool inProject = projDoc!=NULL; if (doc.isNull() && projDoc != NULL) { doc = projDoc;; } if (doc.isNull()) { //document is null -> save it and add to the project assert(subTask == readTask); QList annotations = prepareAnnotations(); doc = prepareNewDocument(annotations); writeTask = new SaveDocumentTask(doc); result.append(writeTask); } else if (writeTask != NULL && !inProject) { // document was saved -> add to the project addTask = new AddDocumentTask(doc); result.append(addTask); } else { //document already in the project -> check loaded state and add annotations to it assert(inProject); if (!doc->isLoaded()) { result.append(new LoadUnloadedDocumentTask(doc)); } else { DocumentFormatConstraints dfc; dfc.flagsToSupport = DocumentFormatFlag_SupportWriting; dfc.supportedObjectTypes += GObjectTypes::ANNOTATION_TABLE; if (!doc->getDocumentFormat()->checkConstraints(dfc)) { setError(tr("Annotations can't be added to the document %1").arg(doc->getURLString())); return result; } if (doc->isStateLocked()) { setError(tr("Document is locked and can't be modified %1").arg(doc->getURLString())); return result; } QList objs = doc->findGObjectByType(GObjectTypes::ANNOTATION_TABLE); AnnotationTableObject* ao = objs.isEmpty() ? NULL : qobject_cast(objs.first()); if (ao == NULL) { ao = new AnnotationTableObject("Annotations"); adjustRelations(ao); } assert(ao != NULL); QList annotations = prepareAnnotations(); ao->addAnnotations(annotations); } } return result; } QList ImportAnnotationsFromCSVTask::prepareAnnotations() const { assert(readTask != NULL && readTask->isFinished()); QList datas = readTask->getResult(); QList result; foreach (const SharedAnnotationData& d, datas) { Annotation* a = new Annotation(d); result.append(a); } return result; } Document* ImportAnnotationsFromCSVTask::prepareNewDocument(const QList& annotations) const { IOAdapterId ioId = BaseIOAdapters::url2io(config.dstFile); IOAdapterFactory* iof = AppContext::getIOAdapterRegistry()->getIOAdapterFactoryById(ioId); Document* result = config.df->createNewDocument(iof, config.dstFile); AnnotationTableObject* ao = new AnnotationTableObject("Annotations"); ao->addAnnotations(annotations); ao->setModified(false); result->addObject(ao); adjustRelations(ao); return result; } ////////////////////////////////////////////////////////////////////////// // ReadCSVAsAnnotationsTask ReadCSVAsAnnotationsTask::ReadCSVAsAnnotationsTask(const QString& _file, const CSVParsingConfig& _config) : Task(tr("Parse CSV file %1").arg(_file), TaskFlag_None), file(_file), config(_config) { } #define BUFF_SIZE 8192 void ReadCSVAsAnnotationsTask::run() { GUrl url(file); IOAdapterId ioId = BaseIOAdapters::url2io(url); IOAdapterFactory* iof = AppContext::getIOAdapterRegistry()->getIOAdapterFactoryById(ioId); std::auto_ptr io(iof->createIOAdapter()); if (!io->open(url, IOAdapterMode_Read)) { setError(L10N::errorOpeningFileRead(url)); return; } QByteArray block(BUFF_SIZE, '\0'); int blockLen = 0; QString text; while ((blockLen = io->readBlock(block.data(), BUFF_SIZE)) > 0) { int sizeBefore = text.length(); QString line = QString::fromLocal8Bit(block.data(), blockLen).trimmed(); text.append(line); if (text.length() != sizeBefore + line.length()) { setError(L10N::errorReadingFile(url)); } stateInfo.progress = io->getProgress(); } int maxColumns = 0; QList parsedLines = parseLinesIntoTokens(text, config, maxColumns, stateInfo); foreach(QStringList lineTokens, parsedLines) { SharedAnnotationData a(new AnnotationData()); bool ok = true; QString error; int startPos = -1; int startPosOffset = 0; int len = -1; int endPos = -1; for (int column = 0; column < lineTokens.size() && ok; column++) { if (column > config.columns.size()) { break; } const ColumnConfig& columnConf = config.columns.at(column); const QString& token = lineTokens.at(column); switch(columnConf.role) { case ColumnRole_Qualifier: assert(!columnConf.qualifierName.isEmpty()); a->qualifiers.append(U2Qualifier(columnConf.qualifierName, token)); break; case ColumnRole_Name: a->name = token.isEmpty() ? config.defaultAnnotationName : token; ok = Annotation::isValidAnnotationName(a->name); if (!ok) { error = tr("Invalid annotation name: '%1'").arg(a->name); } break; case ColumnRole_StartPos: assert(startPos == -1); startPos = token.toInt(&ok) - 1; startPosOffset = columnConf.startPositionOffset; if (!ok) { error = tr("Start offset is not numeric: '%1'").arg(token); } break; case ColumnRole_EndPos: assert(endPos == -1); endPos = token.toInt(&ok) + (columnConf.endPositionIsInclusive ? 1 : 0) - 1; if (!ok) { error = tr("End offset is not numeric: '%1'").arg(token); } break; case ColumnRole_Length: assert(len == -1); len = token.toInt(&ok); if (!ok) { error = tr("Length is not numeric: '%1'").arg(token); } break; case ColumnRole_ComplMark: a->location->strand = (columnConf.complementMark.isEmpty() || token == columnConf.complementMark) ? U2Strand::Complementary : U2Strand::Direct; break; default: assert(columnConf.role == ColumnRole_Ignore); } } //add annotation if (ok) { //set up default name if (a->name.isEmpty()) { a->name = config.defaultAnnotationName; } //set up location U2Region location; if (startPos != -1) { location.startPos = startPos + startPosOffset; if (endPos != -1) { location.length = endPos - startPos; } else { location.length = len; } } else { location.length = len; location.startPos = endPos - len; } if (location.length < 0) { location.startPos = location.startPos + location.length; location.length = - location.length; } if (location.startPos < 0 || location.startPos > location.endPos()) { algoLog.details(tr("Invalid location: start: %1 len: %2, in line :%3, ignoring") .arg(QString::number(location.startPos)).arg(QString::number(location.length)).arg(lineTokens.join(config.splitToken))); } else { a->location->regions.append(location); result.append(a); } } else { //TODO: make configurable to allow stop parsing on any error! algoLog.details(tr("Can't parse line: '%1', error = %2, ignoring").arg(lineTokens.join(config.splitToken)).arg(error)); } } } static QStringList removeQuotes(const QStringList& tokens) { QStringList result; foreach(const QString& token, tokens) { if (token.length() < 2) { result.append(token); continue; } char c1 = token.at(0).toAscii(); char c2 = token.at(token.length()-1).toAscii(); if (c1!=c2 || !CSVParsingConfig::QUOTES.testBit(quint8(c1))) { result.append(token); continue; } QString unquoted = token.mid(1, token.length()-2); result.append(unquoted); } return result; } QList ReadCSVAsAnnotationsTask::parseLinesIntoTokens(const QString& text, const CSVParsingConfig& config, int& maxColumns, TaskStateInfo& ti) { QList result; assert(!config.splitToken.isEmpty() || !config.parsingScript.isEmpty()); maxColumns = 0; QStringList lines = text.split('\n', QString::SkipEmptyParts); int lineNum = 1; for (int l = 0; l < lines.size(); l++) { if (l < config.linesToSkip) { continue; } QString line = lines.at(l).trimmed(); if (!config.prefixToSkip.isEmpty() && line.startsWith(config.prefixToSkip)) { continue; } QStringList tokens = parseLineIntoTokens(line, config, ti, lineNum); if (config.removeQuotes) { tokens = removeQuotes(tokens); } lineNum++; maxColumns = qMax(maxColumns, tokens.size()); result.append(tokens); } return result; } QString ReadCSVAsAnnotationsTask::LINE_VAR("line"); QString ReadCSVAsAnnotationsTask::LINE_NUM_VAR("lineNum"); QStringList ReadCSVAsAnnotationsTask::parseLineIntoTokens(const QString& line, const CSVParsingConfig& config, TaskStateInfo& ti, int lineNum) { QStringList result; if (config.parsingScript.isEmpty()) { result = line.split(config.splitToken, config.keepEmptyParts ? QString::KeepEmptyParts: QString::SkipEmptyParts); return result; } //run script QMap vars; QScriptEngine engine; vars[LINE_VAR] = QScriptValue(&engine, line); vars[LINE_NUM_VAR] = QScriptValue(&engine, lineNum); QScriptValue scriptResult = ScriptTask::runScript(&engine, vars, config.parsingScript, ti); if (ti.cancelFlag || ti.hasError()) { return result; } if (scriptResult.isString()) { result.append(scriptResult.toString()); } else if (scriptResult.isArray()) { QScriptValueIterator it(scriptResult); while (it.hasNext()) { it.next(); if (it.flags() & QScriptValue::SkipInEnumeration) continue; QScriptValue val = it.value(); QString strVal = val.toString(); result.append(strVal); } } else { ti.setError(tr("Script result is not an array of strings!")); } return result; } class CharStat { public: CharStat() : ch(0), count(0) {} char ch; int count; }; static QVector countFreqs(const QString& line) { QVector result(256); QByteArray ba = line.toLocal8Bit(); const char* data = ba.constData(); char prevChar = 0; for (int i = 0, n = ba.length(); i < n; i++) { char c = data[i]; if (c == prevChar && (c == ' ' || c == '\t')) { //do not count repeating ws continue; } result[uchar(c)].ch = c; result[uchar(c)].count++; prevChar = c; } return result; } static void mergeFreqs(QVector& globalFreqs, const QVector& localFreqs) { assert(globalFreqs.size() == localFreqs.size()); for(int i = 0, n = globalFreqs.size(); i < n; i++) { if (globalFreqs.at(i).count != localFreqs.at(i).count) { globalFreqs[i].count = 0; } } } QString ReadCSVAsAnnotationsTask::guessSeparatorString(const QString& text, const CSVParsingConfig& config) { QVector globalFreqs; QStringList lines = text.split('\n', QString::SkipEmptyParts); for (int l = 0; l < lines.size(); l++) { if (l < config.linesToSkip) { continue; } QString line = lines.at(l).trimmed(); QVector lineFreqs = countFreqs(line); if (globalFreqs.isEmpty()) { globalFreqs = lineFreqs; continue; } if (!config.prefixToSkip.isEmpty() && line.startsWith(config.prefixToSkip)) { continue; } mergeFreqs(globalFreqs, lineFreqs); } CharStat max; float maxWeight = 0; static QString doubleWeightChars = ",;: \t"; // chars that are often used as separators static QString lowWeightChars= "\'\""; // quotes and other frequent chars that rare used as separators for (int i = 0; i < globalFreqs.size(); i++) { const CharStat& cs = globalFreqs.at(i); float csWeight = cs.count; if (doubleWeightChars.contains(cs.ch)) { csWeight = csWeight * 2; } else if (lowWeightChars.contains(cs.ch)) { csWeight = csWeight / 2; } if (csWeight > maxWeight) { max = cs; maxWeight = csWeight; } } if (max.count == 0) { return QString(); } return QString(QChar(max.ch)); } } //namespace ugene-1.9.8/src/plugins/dna_export/src/ExportSequenceTask.cpp0000644000175000017500000002644611651544322023034 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "ExportSequenceTask.h" #include "ExportUtils.h" #include #include #include #include #include #include #include #include #include #include #include namespace U2 { ////////////////////////////////////////////////////////////////////////// //ExportSequenceTask ExportSequenceTask::ExportSequenceTask(const ExportSequenceTaskSettings& s) : AbstractExportTask("", TaskFlag_None), config(s) { setTaskName(tr("Export sequence to '%1'").arg(QFileInfo(s.fileName).fileName())); setVerboseLogMode(true); } static bool checkFrame(const QVector& regions, int frame) { foreach(const U2Region& r, regions) { if (r.startPos % 3 != frame) { return false; } } return true; } static ExportSequenceItem toRevComplement(const ExportSequenceItem& ei, TaskStateInfo& si) { ExportSequenceItem complEi = ei; if (ei.complTT == NULL) { si.setError( ExportSequenceTask::tr("Complement translation not found") ); return complEi; } complEi.sequence.setName(ei.sequence.getName() +"|rev-compl" ); // translate char* data = complEi.sequence.seq.data(); //creates a copy if (data == NULL) { si.setError(L10N::outOfMemory()); return complEi; } int len = complEi.sequence.length(); ei.complTT->translate(data, len); TextUtils::reverse(data, len); // fix annotation locations for (int a = 0; a < complEi.annotations.size(); a++) { SharedAnnotationData& ad = complEi.annotations[a]; ad->setStrand(ad->getStrand() == U2Strand::Direct ? U2Strand::Complementary : U2Strand::Direct); U2Region::mirror(len, ad->location->regions); U2Region::reverse(ad->location->regions); } return complEi; } static QList toAmino(const ExportSequenceItem& ei, bool allFrames, TaskStateInfo& si) { QList res; if (ei.aminoTT == NULL) { si.setError( ExportSequenceTask::tr("Amino translation not found") ); return res; } for (int i = 0, nFrames = allFrames ? 3 : 1; i < nFrames; i++) { ExportSequenceItem transEi = ei; transEi.sequence.setName(ei.sequence.getName() + "|transl" + (nFrames == 1 ? QString("") : " " + QString::number(i))); transEi.sequence.alphabet = ei.aminoTT->getDstAlphabet(); //translate sequence transEi.sequence.seq = QByteArray(ei.sequence.length() / 3, '\0'); if (transEi.sequence.length() == 0 && ei.sequence.length() != 0) { si.setError(L10N::outOfMemory()); return res; } assert(ei.aminoTT->isThree2One()); ei.aminoTT->translate(ei.sequence.constData() + i, ei.sequence.length() - i, transEi.sequence.seq.data(), transEi.sequence.length()); // fix annotation locations transEi.annotations.clear(); foreach(const SharedAnnotationData& ad, ei.annotations) { if (checkFrame(ad->getRegions(), i)) { SharedAnnotationData r = ad; U2Region::divide(3, r->location->regions); transEi.annotations.append(r); } } res.append(transEi); } return res; } static ExportSequenceItem backToNucleic(const ExportSequenceItem& ei, bool mostProbable, TaskStateInfo& si) { ExportSequenceItem backEi = ei; if (ei.backTT == NULL) { si.setError( ExportSequenceTask::tr("Back-translation not found") ); return backEi; } backEi.sequence.setName(ei.sequence.getName() + "|revtransl"); backEi.sequence.seq = QByteArray(ei.sequence.length() * 3, '\0'); backEi.sequence.alphabet = ei.backTT->getDstAlphabet(); if (backEi.sequence.length() == 0 && ei.sequence.length() != 0) { si.setError(L10N::outOfMemory()); return backEi; } assert(ei.backTT->isOne2Three()); DNATranslation1to3Impl* trans = static_cast(ei.backTT); trans->translate(ei.sequence.constData(), ei.sequence.length(), backEi.sequence.seq.data(), backEi.sequence.length(), mostProbable ? USE_MOST_PROBABLE_CODONS : USE_FREQUENCE_DISTRIBUTION); // fix annotation locations for (int a = 0; a < backEi.annotations.size(); a++) { SharedAnnotationData& ad = backEi.annotations[a]; U2Region::multiply(3, ad->location->regions); } return backEi; } void ExportSequenceTask::run() { DocumentFormatRegistry* r = AppContext::getDocumentFormatRegistry(); DocumentFormat* f = r->getFormatById(config.formatId); IOAdapterFactory* iof = AppContext::getIOAdapterRegistry()->getIOAdapterFactoryById(BaseIOAdapters::url2io(config.fileName)); doc.reset(f->createNewDocument(iof, config.fileName)); QList notMergedItems; foreach(const ExportSequenceItem& ei0, config.items) { QList r1Items; if (config.strand == TriState_Yes || config.strand == TriState_Unknown) { r1Items.append(ei0); } if (config.strand == TriState_No || config.strand == TriState_Unknown) { r1Items.append(toRevComplement(ei0, stateInfo)); } if (hasError()) { return; } // translate to amino or back-translate if needed QList r2Items; foreach(const ExportSequenceItem& ei1, r1Items) { if (ei1.aminoTT != NULL) { r2Items.append(toAmino(ei1, config.allAminoFrames, stateInfo)); } else if (ei1.backTT != NULL) { r2Items.append(backToNucleic(ei1, config.mostProbable, stateInfo)); } else { r2Items.append(ei1); } if (hasError()) { return; } } notMergedItems.append(r2Items); //TODO: if we do not need to merge items, here we can use streaming & save the doc! } QList resultItems; if (config.merge && notMergedItems.size() > 1) { ExportSequenceItem mergedEi = notMergedItems[0]; QByteArray gapSequence(config.mergeGap, mergedEi.sequence.alphabet->getDefaultSymbol()); for (int x = 1; x < notMergedItems.length(); x++) { const ExportSequenceItem& ei2 = notMergedItems.at(x); mergedEi.sequence.seq.append(gapSequence); // fix annotation locations foreach(const SharedAnnotationData& ad, ei2.annotations) { SharedAnnotationData ma = ad; int offset = mergedEi.sequence.length(); U2Region::shift(offset, ma->location->regions); mergedEi.annotations.append(ma); } mergedEi.sequence.seq.append(ei2.sequence.seq); } resultItems.append(mergedEi); } else { resultItems = notMergedItems; } QSet usedNames; foreach(const ExportSequenceItem& ri, resultItems) { QString name = ri.sequence.getName(); if (name.isEmpty()) { name = "sequence"; } name = ExportUtils::genUniqueName(usedNames, name); usedNames.insert(name); DNASequenceObject* seqObj = new DNASequenceObject(name, ri.sequence); doc->addObject(seqObj); Document::Constraints c; c.objectTypeToAdd.append(GObjectTypes::ANNOTATION_TABLE); bool annotationsSupported = doc->checkConstraints(c); if (annotationsSupported && !ri.annotations.isEmpty()) { QString aName = ExportUtils::genUniqueName(usedNames, name + " annotations"); AnnotationTableObject *annObj = new AnnotationTableObject(aName); usedNames.insert(aName); QList annotations; foreach(const SharedAnnotationData& ad, ri.annotations) { annotations.append(new Annotation(ad)); } annObj->addAnnotations(annotations); annObj->addObjectRelation(seqObj, GObjectRelationRole::SEQUENCE); annObj->setModified(false); doc->addObject(annObj); } } //store the document f->storeDocument(doc.get(), stateInfo); } ////////////////////////////////////////////////////////////////////////// // Export sequence under annotations ExportAnnotationSequenceTask::ExportAnnotationSequenceTask(const ExportAnnotationSequenceTaskSettings& s) : AbstractExportTask(tr("Export annotations"), TaskFlags_NR_FOSCOE), config(s) { extractSubTask = new ExportAnnotationSequenceSubTask(config); addSubTask(extractSubTask); } QList ExportAnnotationSequenceTask::onSubTaskFinished(Task* subTask) { QList res; if (subTask == extractSubTask && !extractSubTask->hasError() && !isCanceled()) { exportSubTask = new ExportSequenceTask(config.exportSequenceSettings); res.append(exportSubTask); } return res; } ExportAnnotationSequenceSubTask::ExportAnnotationSequenceSubTask(ExportAnnotationSequenceTaskSettings& s) : Task(tr("Extract annotation regions"), TaskFlag_None), config(s) { } void ExportAnnotationSequenceSubTask::run() { // extract sequences for every annotation & form ExportSequenceTaskSettings foreach(const ExportSequenceAItem& ei, config.items) { foreach(const SharedAnnotationData& ad, ei.annotations) { QList annSequence = SequenceUtils::extractRegions(ei.sequence.seq, ad->location->regions, ad->getStrand().isCompementary() ? ei.complTT : NULL); DNAAlphabet* al = ei.sequence.alphabet; if (ei.aminoTT != NULL) { QList aminoRegions = SequenceUtils::translateRegions(annSequence, ei.aminoTT, ad->isJoin()); annSequence = aminoRegions; al = ei.aminoTT->getDstAlphabet(); } SharedAnnotationData newAnn = ad; newAnn->location->strand = U2Strand::Direct; newAnn->location->regions = SequenceUtils::toJoinedRegions(annSequence); ExportSequenceItem esi; // both complement & amino ops were already done, so => NULL esi.sequence = DNASequence(ad->name, SequenceUtils::joinRegions(annSequence), al); esi.annotations.append(newAnn); config.exportSequenceSettings.items.append(esi); } } } }//namespace ugene-1.9.8/src/plugins/dna_export/src/ImportQualityScoresTask.h0000644000175000017500000000426711651544322023526 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_IMPORT_QUALITY_SCORES_TASK_H_ #define _U2_IMPORT_QUALITY_SOCRES_TASK_H_ #include #include #include namespace U2 { class DNASequenceObject; class ImportQualityScoresConfig { public: ImportQualityScoresConfig() : createNewDocument(false) {} QString fileName; DNAQualityType type; bool createNewDocument; QString dstFileName; }; class ReadQualityScoresTask : public Task { Q_OBJECT public: ReadQualityScoresTask(const QString& fileName, DNAQualityType t); void run(); QMap getResult() const { return result; } private: void recordQuality( int headerCounter ); QString fileName; DNAQualityType type; QStringList headers; QList values; QMap result; }; class ImportPhredQualityScoresTask : public Task { Q_OBJECT public: ImportPhredQualityScoresTask(const QList& sequences, ImportQualityScoresConfig& config); void prepare(); QList onSubTaskFinished(Task* subTask); private: ReadQualityScoresTask* readQualitiesTask; ImportQualityScoresConfig config; QList seqList; }; } // namespace U2 #endif ugene-1.9.8/src/plugins/dna_export/transl/0000755000175000017500000000000011651544322017233 5ustar ilyailyaugene-1.9.8/src/plugins/dna_export/transl/russian.ts0000644000175000017500000020605111651544322021273 0ustar ilyailya CSVColumnConfigurationDialog Select the role of the column Выберите роль данных в столбце Column role Роль Annotation start position Начальная позиция Add offset Смещение bp сим Annotation end position Конечная позиция Inclusive Включительно Annotation length Длина аннотации Complement strand mark Комплементарное направление Mark value Метка Annotation name Имя аннотации Qualifier Квалификатор Ignore this column Не использовать этот столбец Ok Принять Cancel Отменить ExportChromatogramDialog Export chromatogram file Экспортировать хроматограмму Export to file Записать в файл ... ... File format to use Используемый формат файла Reversed Обратный Complemented Комплементарный Add document to the project Добавить документ к проекту Export Экспорт Cancel Отменить ImportAnnotationsFromCSVDialog Import annotations from CSV Импортировать аннотации из CSV File to read Входной файл ... Results Результаты Result file Выходной файл File format Формат файла Add result file to project Добавить результат к проекту Column separator Разделитель столбцов File parsing , Guess Определить Script Edit First lines to skip Пропускать сначала Do not skip Не пропускать line(s) строка(и) Skip all lines starts with the text Пропускать строки, начинающиеся с текста # Remove quotes Default annotation name Имя аннотации по умолчанию misc_feature Interpret multiple separators like a single separator (try when separator is a whitespace character) Интерпретировать повторяющийся разделитель как одиночный (используйте, когда разделителем служит пробел) Results preview Просмотр результата Preview Просмотр Raw file preview: Просмотр "сырого" файла: Run Запустить Cancel Отменить U2::ADVExportContext Export selected sequence region... Экспорт выбранных регионов последовательности... Export sequence of selected annotations... Экспорт последовательностей выбранных аннотаций... Export annotations to CSV format... Экспорт аннотаций в CSV... Export annotations... Экспортировать аннотации... Align selected annotations... Выровнять выбранные аннотации... Align selected annotations (amino acids)... Вырвнять выбранные аннотации (аминокислоты)... Align selected sequence regions... Выровнять выбранные последовательности... Align selected sequence regions (amino acids)... Выравнять выбранные регионы (аминокислоты)... Export sequences by 'id' Экспортировать последовательности по 'id' Export sequences by 'accession' Экспортировать последовательности по 'accession' Export sequences by 'db_xref' Экспортировать последовательности по 'db_xref' Fetch sequences from remote database Загрузить последовательности Fetch sequences by 'id' %1 Загрузить по 'id' %1 Fetch sequences by 'accession' %1 Загрузить по 'accsession' %1 Fetch sequences by 'db_xref' %1 Загрузить по 'db_xref' %1 Create alignment Создать выравнивание Save alignment to file Сохранить выравнивание в файл Make an alignment of translated sequence Выровнять транслированные последовательности No annotations selected! Сначала выберите аннотации! No sequence regions selected! Нет выбранных участков! At least 2 annotations are required Нужно выбрать хотя бы 2 аннотации Different sequence alphabets Несопоставимые алфавиты At least 2 sequences required Необходимо как минимум 2 последовательности No sequence object found Последовательность недоступна Different alphabets Алфавиты последовательностей не совпадают Alignment is too large Слишком большой размер выравнивания Can't derive alignment alphabet Невозможно определить алфавит выравнивания U2::CSVColumnConfigurationDialog Invalid qualifier name! Неправильное имя квалификатора! U2::DNAExportPlugin dna_export_name Экспорт dna_export_desc Поддержка экспорта последовательностей и выравниваний DNA export Export and import support for DNA & protein sequences U2::DNAExportService dna_export_service_name Экспорт dna_export_service_desc Экспорт последовательностей DNA export service Export and import support for DNA & protein sequences U2::ExportAlignmentTask Export alignment to '%1' Экспорт выравнивания в '%1' U2::ExportAnnotationSequenceSubTask Extract annotation regions U2::ExportAnnotationSequenceTask Export annotations U2::ExportAnnotations2CSVDialog Export annotations to CSV Экспорт аннотаций в CSV Export to file: Записать в файл: Save sequences under annotations Сохранить последовательности под аннотациями CSV files (*.csv);;All files (*) Файлы CSV (*.csv);;Все файлы (*) U2::ExportAnnotations2CSVTask Export2CSV Экспорт в CSV No IO adapter found for URL: %1 Не найден IO-адаптер для URL: %1 Group Группа Name Имя Start Начало End Конец Length Длина Complementary Комплементарная Complement Комплементарная Sequence Последовательность yes да no нет U2::ExportAnnotationsDialog Export annotations Экспортировать аннотации Export to file: Записать в файл: ... ... File format: Формат файла: Save sequences under annotations Сохранить последовательности под аннотациями Select file to save annotations Выберите файл для сохранения аннотаций U2::ExportChromatogramDialog Select a file Выберите файл File name is empty! Не указано имя файла! U2::ExportDNAChromatogramTask Export chromatogram to SCF Экспорт хроматограммы в SCF U2::ExportMSA2MSADialog Dialog Export to file Записать в файл ... File format to use Используемый формат файла Amino translation Таблица трансляции Add document to the project Добавить документ к проекту Export range Рамки экспорта Whole alignment Всё выравнивание Selected rows Выбранные строки Export Экспорт Cancel Отменить Export alignment Экспорт выравнивания File is empty Не указано имя файла U2::ExportMSA2MSATask Export alignment to alignment: %1 Экспортировать выравнивание в выравнивание: %1 Out of memory Ошибка выделения памяти U2::ExportMSA2SequencesDialog Convert alignment to separate sequences Конвертировать выравнивание в разные последовательности Export to file Записать в файл ... File format to use Используемый формат файла Add document to the project Добавить документ к проекту Gap characters ('-') Символы пропуска ("-") Keep Сохранять Trim Удалять Export Cancel Отменить File name is empty! Не указано имя файла! U2::ExportMSA2SequencesTask Export alignment to sequence: %1 Экспорт выравнивания в последовательность: %1 U2::ExportProjectViewItemsContoller Export sequences Экспорт последовательностей Export sequences as alignment Экспорт последовательностей как выравнивания Export alignment to sequence format Экспорт выравнивания в последовательность Export nucleic alignment to amino translation Экспортировать и транслировать выравнивание Import annotations from CSV file Импортировать аннотации из CSV Export chromatogram to SCF Экспорт хроматограммы в SCF Export annotations Экспортировать аннотации Export Экспорт Import Импорт No sequence objects selected! Выделите один или более объектов! Select one alignment object to export Выберите один объект выравнивания Select one chromatogram object to export Выберите один объект для экспорта Select one annotation object to export Selected object doesn't have annotations U2::ExportSequenceTask Export sequence to '%1' Экспорт последовательностей в '%1' Complement translation not found Amino translation not found Back-translation not found U2::ExportSequences2MSADialog Export sequences as alignment Экспорт последовательностей как выравнивания Export to file Записать в файл ... File format to use Используемый формат файла Add document to the project Добавить документ к проекту Export Сохранить Cancel Отменить File name is empty! Не указано имя файла! U2::ExportSequencesDialog Export selected sequences Экспорт выбранных последовательностей Export to file Записать в файл ... File format to use Используемый формат файла Export with annotations Экспортировать с аннотациями Add document to the project Добавить документ к проекту Convertion options Настройки трансляции Save direct strand Сохранять прямую Save complement strand Сохранять комплементарную Save both strands Сохранять обе Translate to amino alphabet Транслировать Save all amino frames Сохранять все рамки трансляции Use this translation table Использовать таблицу трансляции Back translation options Настройки обратной трансляции Translate back to nucleic alphabet Транслировать обратно в алфавит нуклеотидов Most frequently used codons Наиболее часто используемые кодоны Organism: Организм: Save as separate sequences Сохр. послед. раздельно Frequency distribution Частотное распределение Use custom translation table Merge options Настройки группировки последовательностей Add gap symbols between sequences Добавлять пробелы между последовательностями Merge sequences Объединять последовательности Save as separate sequencs Сохранять отдельными Export Сохранить Cancel Отменить Export sequences Экспорт последовательностей Select organism Выберите организм File is empty Не указано имя файла Organism for back translation not specified Не выбран организм для обратной трансляции U2::ExportSequencesTask Export sequence to '%1' Экспорт последовательностей в '%1' Complement translator not found Не найдена таблица комплементарной трансляции Out of memory Ошибка выделения памяти U2::GTest Unable to create temporary file Invalid translation table num: %1 Invalid base : %1 context not found %1 container of object with type "%1" is empty Unexpected alignment length %1, expected %2 Unexpected alignment size %1, expected %2 Invalid name for row %1: %2, expected %3 Invalid char at row %1 column %2: %3, expected %4 U2::GetSequenceByIdDialog Select directory to save Папка для сохранения U2::ImportAnnotationsFromCSVDialog Save imported annotations to Выберите файл для сохранения аннотаций //The script parses input line // and returns an array of parsed elements as the result var %1; //input line var %2; //parsed line number Invalid start position/end position/length configuration! Неправильная конфигурация координат аннотации! Multiple columns are used as a name! В качестве имени аннотации можно выбрать только один столбец! Column separator value: [%1], hex: [%2], length: %3 Script is empty Output file format is not set! Не задан формат файла с аннотациями! Output file name is not set! Не задано имя файла с аннотациями! Column separator is not set! Не задан символ разделитель столбцов! Invalid default annotation name! Неправильное имя аннотации по умолчанию! Failed to guess separator sequence! Не удалось определить разделителный символ ! Column separator Разделитель столбцов Column separator value: [%1], length: %2 Значение разделителя: [%1], длина: [%2] Select CSV file to read Выберите файл со столбцами Enter input CSV file name Укажите исходный файл с данными Separator value is not set Не задан символ разделитель столбцов Enter output file name Введите имя файла для сохранения аннотаций [ignored] [не используется] [qualifier %1] [квалификатор: %1] [name] [имя] [start position with offset %1] [начальная позиция, смещение %1] [start position] [начальная позиция] [end position (inclusive)] [конечная позиция (включительно)] [end position] [конечная позиция] [length] [длина] [complement] [complement if '%1'] U2::ImportAnnotationsFromCSVTask Import annotations from CSV Импортировать аннотации из CSV Annotations can't be added to the document %1 Аннотации не могут быть добавлены к документу %1 Document is locked and can't be modified %1 Документ заблокирован и не может быть изменён %1 U2::LocalWorkflow::ImportPhredQualityPrompter from <u>%1</u> unset Import PHRED quality scores in file %1 to the sequences %2 and send the sequences to the output. U2::LocalWorkflow::ImportPhredQualityWorker DNA sequences The PHRED scores will be imported to these sequences DNA sequences with imported qualities These sequences have quality scores. PHRED input Path to file with PHRED quality scores. Quality format Choose format to encode quality scores. Import PHRED qualities Add corresponding PHRED quality scores to the sequences. You can use this worker to convert .fasta and .qual pair to fastq format Sequence list is empty. Import of qualities is finished. U2::LocalWorkflow::WriteAnnotationsPrompter unset Save all annotations from <u>%1</u> to %2 in <u>%3</u> format U2::LocalWorkflow::WriteAnnotationsWorker Unrecognized formatId: '%1' Unspecified URL to write %1 Annotations name not specified. Default value used: '%1' Input annotations Input annotations which will be written to output file Annotations name Object name of saving annotations Write annotations Writes all supplied annotations to file(s) in selected formatId. U2::MSAExportContext Export amino translation of alignment rows... Экспортировать трансляцию строк выравнивания... U2::ReadCSVAsAnnotationsTask Parse CSV file %1 Разобрать CSV %1 Invalid annotation name: '%1' Неправильное имя аннотации: '%1' Start offset is not numeric: '%1' Смещение начала не является числом: '%1' End offset is not numeric: '%1' Смещение конца не является числом: '%1' Length is not numeric: '%1' Длина не является числом: '%1' Invalid location: start: %1 len: %2, in line :%3, ignoring Неверная позиция: начало: %1 длина: %2, в строке :%3, пропуск Can't parse line: '%1', error = %2, ignoring Невозможно разобрать строку: '%1', ошибка = %2, пропуск Script result is not an array of strings! getSequenceByIdDialog Get sequences by ID Загрузить последовательности по ШВ The sequences from selected BLAST results will be downloaded from NCBI Genbank by their GI identifier Последовательности из выбранных аннотаций буду загружены из NCBI Genbank по идентификатору Save to directctory: Папка для сохранения: ... ... Add to project Добавить в проект ugene-1.9.8/src/plugins/dna_export/transl/czech.ts0000644000175000017500000015704311651544322020711 0ustar ilyailya CSVColumnConfigurationDialog Select the role of the column Column role Annotation start position Add offset bp Annotation end position Inclusive Annotation length Complement strand mark Mark value Annotation name Qualifier Ignore this column Ok Cancel ExportChromatogramDialog Export chromatogram file Export to file ... File format to use Reversed Complemented Add document to the project Export Cancel ImportAnnotationsFromCSVDialog Import annotations from CSV File to read ... Results Result file File format Add result file to project Column separator File parsing , Guess Script Edit First lines to skip Do not skip line(s) Skip all lines starts with the text # Remove quotes Default annotation name misc_feature Interpret multiple separators like a single separator (try when separator is a whitespace character) Results preview Preview Raw file preview: Run Cancel U2::ADVExportContext Export selected sequence region... Export sequence of selected annotations... Export annotations... Align selected annotations... Align selected annotations (amino acids)... Align selected sequence regions... Align selected sequence regions (amino acids)... Export sequences by 'id' Export sequences by 'accession' Export sequences by 'db_xref' Fetch sequences from remote database Fetch sequences by 'id' %1 Fetch sequences by 'accession' %1 Fetch sequences by 'db_xref' %1 No annotations selected! No sequence regions selected! At least 2 annotations are required Different sequence alphabets At least 2 sequences required Create alignment Save alignment to file No sequence object found Alignment is too large Can't derive alignment alphabet U2::CSVColumnConfigurationDialog Invalid qualifier name! U2::DNAExportPlugin dna_export_name DNA Export dna_export_desc Routines to export or align multiple DNA sequences DNA export Export and import support for DNA & protein sequences U2::DNAExportService dna_export_service_name DNA Export dna_export_service_desc This service provides routines to export DNA sequence to FASTA format DNA export service Export and import support for DNA & protein sequences U2::ExportAlignmentTask Export alignment to '%1' U2::ExportAnnotationSequenceSubTask Extract annotation regions U2::ExportAnnotationSequenceTask Export annotations U2::ExportAnnotations2CSVTask Export2CSV No IO adapter found for URL: %1 Group Name Start End Length Complement Sequence yes no U2::ExportAnnotationsDialog Export annotations Export to file: ... File format: Save sequences under annotations Select file to save annotations U2::ExportChromatogramDialog Select a file File name is empty! U2::ExportDNAChromatogramTask Export chromatogram to SCF U2::ExportMSA2MSADialog Dialog Export to file ... File format to use Amino translation Add document to the project Export range Whole alignment Selected rows Export Cancel Export alignment File is empty U2::ExportMSA2MSATask Export alignment to alignment: %1 Out of memory U2::ExportMSA2SequencesDialog Convert alignment to separate sequences Export to file ... File format to use Add document to the project Gap characters ('-') Keep Trim Export Cancel File name is empty! U2::ExportMSA2SequencesTask Export alignment to sequence: %1 U2::ExportProjectViewItemsContoller Export sequences Export sequences as alignment Export alignment to sequence format Export nucleic alignment to amino translation Import annotations from CSV file Export chromatogram to SCF Export annotations Export Import No sequence objects selected! Select one alignment object to export Select one chromatogram object to export Select one annotation object to export Selected object doesn't have annotations U2::ExportSequenceTask Export sequence to '%1' Complement translation not found Amino translation not found Back-translation not found U2::ExportSequences2MSADialog Export sequences as alignment Export to file ... File format to use Add document to the project Export Cancel File name is empty! U2::ExportSequencesDialog Export selected sequences Export to file ... File format to use Export with annotations Add document to the project Convertion options Save direct strand Save complement strand Save both strands Translate to amino alphabet Save all amino frames Save as separate sequences Back translation options Translate back to nucleic alphabet Most frequently used codons Organism: Frequency distribution Use custom translation table Merge options Add gap symbols between sequences Merge sequences Export Cancel Export sequences Select organism File is empty Organism for back translation not specified U2::GTest Unable to create temporary file Invalid translation table num: %1 Invalid base : %1 context not found %1 container of object with type "%1" is empty Unexpected alignment length %1, expected %2 Unexpected alignment size %1, expected %2 Invalid name for row %1: %2, expected %3 Invalid char at row %1 column %2: %3, expected %4 U2::GetSequenceByIdDialog Select directory to save U2::ImportAnnotationsFromCSVDialog Save imported annotations to //The script parses input line // and returns an array of parsed elements as the result var %1; //input line var %2; //parsed line number Invalid start position/end position/length configuration! Multiple columns are used as a name! Column separator value: [%1], hex: [%2], length: %3 Script is empty Output file format is not set! Output file name is not set! Invalid default annotation name! Failed to guess separator sequence! Column separator Select CSV file to read Enter input CSV file name Separator value is not set [ignored] [qualifier %1] [name] [start position with offset %1] [start position] [end position (inclusive)] [end position] [length] [complement] [complement if '%1'] U2::ImportAnnotationsFromCSVTask Import annotations from CSV Annotations can't be added to the document %1 Document is locked and can't be modified %1 U2::LocalWorkflow::ImportPhredQualityPrompter from <u>%1</u> unset Import PHRED quality scores in file %1 to the sequences %2 and send the sequences to the output. U2::LocalWorkflow::ImportPhredQualityWorker DNA sequences The PHRED scores will be imported to these sequences DNA sequences with imported qualities These sequences have quality scores. PHRED input Path to file with PHRED quality scores. Quality format Choose format to encode quality scores. Import PHRED qualities Add corresponding PHRED quality scores to the sequences. You can use this worker to convert .fasta and .qual pair to fastq format Sequence list is empty. Import of qualities is finished. U2::LocalWorkflow::WriteAnnotationsPrompter unset Save all annotations from <u>%1</u> to %2 in <u>%3</u> format U2::LocalWorkflow::WriteAnnotationsWorker Unrecognized formatId: '%1' Unspecified URL to write %1 Annotations name not specified. Default value used: '%1' Input annotations Input annotations which will be written to output file Annotations name Object name of saving annotations Write annotations Writes all supplied annotations to file(s) in selected formatId. U2::MSAExportContext Export amino translation of alignment rows... U2::ReadCSVAsAnnotationsTask Parse CSV file %1 Invalid annotation name: '%1' Start offset is not numeric: '%1' End offset is not numeric: '%1' Length is not numeric: '%1' Invalid location: start: %1 len: %2, in line :%3, ignoring Can't parse line: '%1', error = %2, ignoring Script result is not an array of strings! getSequenceByIdDialog Get sequences by ID The sequences from selected BLAST results will be downloaded from NCBI Genbank by their GI identifier Save to directctory: ... Add to project ugene-1.9.8/src/plugins/dna_export/transl/english.ts0000644000175000017500000015607511651544322021252 0ustar ilyailya CSVColumnConfigurationDialog Select the role of the column Column role Annotation start position Add offset bp Annotation end position Inclusive Annotation length Complement strand mark Mark value Annotation name Qualifier Ignore this column Ok Cancel ExportChromatogramDialog Export chromatogram file Export to file ... File format to use Reversed Complemented Add document to the project Export Cancel ImportAnnotationsFromCSVDialog Import annotations from CSV File to read ... Results Result file File format Add result file to project Column separator File parsing , Guess Script Edit First lines to skip Do not skip line(s) Skip all lines starts with the text # Remove quotes Default annotation name misc_feature Interpret multiple separators like a single separator (try when separator is a whitespace character) Results preview Preview Raw file preview: Run Cancel U2::ADVExportContext Export selected sequence region... Export sequence of selected annotations... Align selected annotations... Align selected annotations (amino acids)... Align selected sequence regions... Align selected sequence regions (amino acids)... Export sequences by 'id' Export sequences by 'accession' Export sequences by 'db_xref' Fetch sequences from remote database Fetch sequences by 'id' %1 Fetch sequences by 'accession' %1 Fetch sequences by 'db_xref' %1 Create alignment Save alignment to file No annotations selected! Export annotations... No sequence regions selected! At least 2 annotations are required Different sequence alphabets At least 2 sequences required No sequence object found Alignment is too large Can't derive alignment alphabet U2::CSVColumnConfigurationDialog Invalid qualifier name! U2::DNAExportPlugin dna_export_name DNA Export dna_export_desc Routines to export or align multiple DNA sequences DNA export Export and import support for DNA & protein sequences U2::DNAExportService dna_export_service_name DNA Export dna_export_service_desc This service provides routines to export DNA sequence to FASTA format DNA export service Export and import support for DNA & protein sequences U2::ExportAlignmentTask Export alignment to '%1' U2::ExportAnnotationSequenceSubTask Extract annotation regions U2::ExportAnnotationSequenceTask Export annotations U2::ExportAnnotations2CSVTask Export2CSV No IO adapter found for URL: %1 Group Name Start End Length Complement Sequence yes no U2::ExportAnnotationsDialog Export annotations Export to file: ... File format: Save sequences under annotations Select file to save annotations U2::ExportChromatogramDialog Select a file File name is empty! U2::ExportDNAChromatogramTask Export chromatogram to SCF U2::ExportMSA2MSADialog Dialog Export to file ... File format to use Amino translation Add document to the project Export range Whole alignment Selected rows Export Cancel Export alignment File is empty U2::ExportMSA2MSATask Export alignment to alignment: %1 Out of memory U2::ExportMSA2SequencesDialog Convert alignment to separate sequences Export to file ... File format to use Add document to the project Gap characters ('-') Keep Trim Export Cancel File name is empty! U2::ExportMSA2SequencesTask Export alignment to sequence: %1 U2::ExportProjectViewItemsContoller Export sequences Export sequences as alignment Export alignment to sequence format Export nucleic alignment to amino translation Import annotations from CSV file Export chromatogram to SCF Export annotations Export Import No sequence objects selected! Select one alignment object to export Select one chromatogram object to export Select one annotation object to export Selected object doesn't have annotations U2::ExportSequenceTask Export sequence to '%1' Complement translation not found Amino translation not found Back-translation not found U2::ExportSequences2MSADialog Export sequences as alignment Export to file ... File format to use Add document to the project Export Cancel File name is empty! U2::ExportSequencesDialog Export selected sequences Export to file ... File format to use Export with annotations Add document to the project Convertion options Save direct strand Save complement strand Save both strands Translate to amino alphabet Save all amino frames Back translation options Translate back to nucleic alphabet Most frequently used codons Organism: Save as separate sequences Frequency distribution Use custom translation table Merge options Add gap symbols between sequences Merge sequences Export Cancel Export sequences Select organism File is empty Organism for back translation not specified U2::GTest Unable to create temporary file Invalid translation table num: %1 Invalid base : %1 context not found %1 container of object with type "%1" is empty Unexpected alignment length %1, expected %2 Unexpected alignment size %1, expected %2 Invalid name for row %1: %2, expected %3 Invalid char at row %1 column %2: %3, expected %4 U2::GetSequenceByIdDialog Select directory to save U2::ImportAnnotationsFromCSVDialog Save imported annotations to //The script parses input line // and returns an array of parsed elements as the result var %1; //input line var %2; //parsed line number Invalid start position/end position/length configuration! Multiple columns are used as a name! Column separator value: [%1], hex: [%2], length: %3 Script is empty Output file format is not set! Output file name is not set! Invalid default annotation name! Failed to guess separator sequence! Column separator Select CSV file to read Enter input CSV file name Separator value is not set [ignored] [qualifier %1] [name] [start position with offset %1] [start position] [end position (inclusive)] [end position] [length] [complement] [complement if '%1'] U2::ImportAnnotationsFromCSVTask Import annotations from CSV Annotations can't be added to the document %1 Document is locked and can't be modified %1 U2::LocalWorkflow::ImportPhredQualityPrompter from <u>%1</u> unset Import PHRED quality scores in file %1 to the sequences %2 and send the sequences to the output. U2::LocalWorkflow::ImportPhredQualityWorker DNA sequences The PHRED scores will be imported to these sequences DNA sequences with imported qualities These sequences have quality scores. PHRED input Path to file with PHRED quality scores. Quality format Choose format to encode quality scores. Import PHRED qualities Add corresponding PHRED quality scores to the sequences. You can use this worker to convert .fasta and .qual pair to fastq format Sequence list is empty. Import of qualities is finished. U2::LocalWorkflow::WriteAnnotationsPrompter unset Save all annotations from <u>%1</u> to %2 in <u>%3</u> format U2::LocalWorkflow::WriteAnnotationsWorker Unrecognized formatId: '%1' Unspecified URL to write %1 Annotations name not specified. Default value used: '%1' Input annotations Input annotations which will be written to output file Annotations name Object name of saving annotations Write annotations Writes all supplied annotations to file(s) in selected formatId. U2::MSAExportContext Export amino translation of alignment rows... U2::ReadCSVAsAnnotationsTask Parse CSV file %1 Invalid annotation name: '%1' Start offset is not numeric: '%1' End offset is not numeric: '%1' Length is not numeric: '%1' Invalid location: start: %1 len: %2, in line :%3, ignoring Can't parse line: '%1', error = %2, ignoring Script result is not an array of strings! getSequenceByIdDialog Get sequences by ID The sequences from selected BLAST results will be downloaded from NCBI Genbank by their GI identifier Save to directctory: ... Add to project ugene-1.9.8/src/plugins/dbi_sqlite/0000755000175000017500000000000011651544322015704 5ustar ilyailyaugene-1.9.8/src/plugins/dbi_sqlite/dbi_sqlite.pri0000644000175000017500000000056411651544322020544 0ustar ilyailya# include (dbi_sqlite.pri) PLUGIN_ID=dbi_sqlite PLUGIN_NAME=SQLite based DBI implementation PLUGIN_VENDOR=Unipro LIBS += -lugenedb !debug_and_release|build_pass { CONFIG(debug, debug|release) { LIBS -= -lugenedb LIBS += -lugenedbd } } include( ../../ugene_plugin_common.pri ) INCLUDEPATH += ../../libs_3rdparty/sqlite3/srcugene-1.9.8/src/plugins/dbi_sqlite/dbi_sqlite.pro0000644000175000017500000000172311651544322020550 0ustar ilyailyainclude (dbi_sqlite.pri) # Input HEADERS += src/SQLiteAssemblyDbi.h \ src/SQLiteAttributeDbi.h \ src/SQLiteDbi.h \ src/SQLiteDbiPlugin.h \ src/SQLiteMsaDbi.h \ src/SQLiteObjectDbi.h \ src/SQLiteSequenceDbi.h \ src/assembly/AssemblyPackAlgorithm.h \ src/assembly/MultiTableAssemblyAdapter.h \ src/assembly/RTreeAssemblyAdapter.h \ src/assembly/SingleTableAssemblyAdapter.h SOURCES += src/SQLiteAssemblyDbi.cpp \ src/SQLiteAttributeDbi.cpp \ src/SQLiteDbi.cpp \ src/SQLiteDbiPlugin.cpp \ src/SQLiteMsaDbi.cpp \ src/SQLiteObjectDbi.cpp \ src/SQLiteSequenceDbi.cpp \ src/assembly/AssemblyPackAlgorithm.cpp \ src/assembly/MultiTableAssemblyAdapter.cpp \ src/assembly/RTreeAssemblyAdapter.cpp \ src/assembly/SingleTableAssemblyAdapter.cpp ugene-1.9.8/src/plugins/dbi_sqlite/src/0000755000175000017500000000000011651544322016473 5ustar ilyailyaugene-1.9.8/src/plugins/dbi_sqlite/src/SQLiteAttributeDbi.cpp0000644000175000017500000002706511651544322022655 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "SQLiteAttributeDbi.h" #include #include namespace U2 { SQLiteAttributeDbi::SQLiteAttributeDbi(SQLiteDbi* dbi) : U2AttributeDbi(dbi), SQLiteChildDBICommon(dbi) { } void SQLiteAttributeDbi::initSqlSchema(U2OpStatus& os) { if (os.hasError()) { return; } // object attribute main table // object -> object id this attribute is for // child -> optional object id in case if this attribute shows relation between 2 objects // otype, ctype -> object and child types // oextra, cextra -> object and child db extra // version -> object version is attribute is valid for // name -> name of the attribute SQLiteQuery("CREATE TABLE Attribute (id INTEGER PRIMARY KEY AUTOINCREMENT, type INTEGER NOT NULL, " " object INTEGER, child INTEGER, otype INTEGER NOT NULL, ctype INTEGER, oextra BLOB NOT NULL, cextra BLOB, " " version INTEGER NOT NULL, name TEXT NOT NULL, " " FOREIGN KEY(object) REFERENCES Object(id), FOREIGN KEY(child) REFERENCES Object(id) )" , db, os).execute(); //TODO: check if index is efficient for gettting attribute for specific object SQLiteQuery("CREATE INDEX Attribute_name on Attribute(name)" , db, os).execute(); SQLiteQuery("CREATE TABLE IntegerAttribute (attribute INTEGER, value INTEGER NOT NULL, " " FOREIGN KEY(attribute) REFERENCES Attribute(id) )" , db, os).execute(); SQLiteQuery("CREATE TABLE RealAttribute (attribute INTEGER, value REAL NOT NULL, " " FOREIGN KEY(attribute) REFERENCES Attribute(id) )" , db, os).execute(); SQLiteQuery("CREATE TABLE StringAttribute (attribute INTEGER, value TEXT NOT NULL, " " FOREIGN KEY(attribute) REFERENCES Attribute(id) )" , db, os).execute(); SQLiteQuery("CREATE TABLE ByteArrayAttribute (attribute INTEGER, value BLOB NOT NULL, " " FOREIGN KEY(attribute) REFERENCES Attribute(id) )" , db, os).execute(); } /** Returns all attribute names available in the database */ QStringList SQLiteAttributeDbi::getAvailableAttributeNames(U2OpStatus& os) { return SQLiteQuery("SELECT DISTINCT name FROM Attribute", db, os).selectStrings(); } /** Returns all attribute ids for the given object */ QList SQLiteAttributeDbi::getObjectAttributes(const U2DataId& objectId, const QString& name, U2OpStatus& os) { if (name.isEmpty()) { SQLiteQuery q("SELECT id, type, '' FROM Attribute WHERE object = ?1 ORDER BY id", db, os); q.bindDataId(1, objectId); return q.selectDataIdsExt(); } SQLiteQuery q("SELECT id, type, '' FROM Attribute WHERE object = ?1 AND name = ?2 ORDER BY id", db, os); q.bindDataId(1, objectId); q.bindString(2, name); return q.selectDataIdsExt(); } /** Returns all attribute ids for the given object */ QList SQLiteAttributeDbi::getObjectPairAttributes(const U2DataId& objectId, const U2DataId& childId, const QString& name, U2OpStatus& os) { if (name.isEmpty()) { SQLiteQuery q("SELECT id, type, '' FROM Attribute WHERE object = ?1 AND child = ?2 ORDER BY id", db, os); q.bindDataId(1, objectId); q.bindDataId(2, childId); return q.selectDataIdsExt(); } SQLiteQuery q("SELECT id, type, '' FROM Attribute WHERE object = ?1 AND child = ?2 AND name = ?3 ORDER BY id", db, os); q.bindDataId(1, objectId); q.bindDataId(2, childId); q.bindString(3, name); return q.selectDataIdsExt(); } /** Loads int64 attribute by id */ U2IntegerAttribute SQLiteAttributeDbi::getIntegerAttribute(const U2DataId& attributeId, U2OpStatus& os) { SQLiteQuery q(buildSelectAttributeQuery("IntegerAttribute"), db, os); q.bindDataId(1, attributeId); U2IntegerAttribute res; readAttribute(q, res); res.value = q.getInt64(0); q.ensureDone(); return res; } /** Loads real64 attribute by id */ U2RealAttribute SQLiteAttributeDbi::getRealAttribute(const U2DataId& attributeId, U2OpStatus& os) { SQLiteQuery q(buildSelectAttributeQuery("RealAttribute"), db, os); q.bindDataId(1, attributeId); U2RealAttribute res; readAttribute(q, res); res.value = q.getDouble(0); q.ensureDone(); return res; } /** Loads String attribute by id */ U2StringAttribute SQLiteAttributeDbi::getStringAttribute(const U2DataId& attributeId, U2OpStatus& os) { SQLiteQuery q(buildSelectAttributeQuery("StringAttribute"), db, os); q.bindDataId(1, attributeId); U2StringAttribute res; readAttribute(q, res); res.value = q.getString(0); q.ensureDone(); return res; } /** Loads byte attribute by id */ U2ByteArrayAttribute SQLiteAttributeDbi::getByteArrayAttribute(const U2DataId& attributeId, U2OpStatus& os) { SQLiteQuery q(buildSelectAttributeQuery("ByteArrayAttribute"), db, os); q.bindDataId(1, attributeId); U2ByteArrayAttribute res; readAttribute(q, res); res.value = q.getBlob(0); q.ensureDone(); return res; } QString SQLiteAttributeDbi::buildSelectAttributeQuery(const QString& attributeTable) { return "SELECT t.value, a.id, a.type, '', a.object, a.otype, a.oextra, a.child, a.ctype, a.cextra, a.version, a.name " " FROM Attribute AS a, " + attributeTable + " AS t WHERE a.id = ?1 AND t.attribute = a.id"; } void SQLiteAttributeDbi::readAttribute(SQLiteQuery& q, U2Attribute& attr) { if (q.hasError()) { return; } if (!q.step()) { if (!q.hasError()) { q.setError(SQLiteL10n::tr("Attribute not found!")); } return; } attr.id = q.getDataIdExt(1); attr.objectId = q.getDataIdExt(4); attr.childId = q.getDataIdExt(7); attr.version = q.getInt64(10); attr.name = q.getString(11); } /** Sorts all objects in database according to U2DbiSortConfig provided */ QList SQLiteAttributeDbi::sort(const U2DbiSortConfig& , qint64 , qint64 , U2OpStatus& os) { QList res; os.setError("not implemented"); return res; } static void removeAttribute(SQLiteQuery& q, const U2DataId& id) { q.reset(); q.bindDataId(1, id); q.execute(); } /** Removes attribute from database Requires U2DbiFeature_WriteAttribute feature support */ void SQLiteAttributeDbi::removeAttributes(const QList& attributeIds, U2OpStatus& os) { SQLiteTransaction t(db, os); SQLiteQuery q("DELETE FROM Attribute WHERE id = ?1", db, os); SQLiteQuery qi("DELETE FROM IntegerAttribute WHERE attribute = ?1", db, os); SQLiteQuery qr("DELETE FROM RealAttribute WHERE attribute = ?1", db, os); SQLiteQuery qs("DELETE FROM StringAttribute WHERE attribute = ?1", db, os); SQLiteQuery qb("DELETE FROM ByteArrayAttribute WHERE attribute = ?1", db, os); foreach(const U2DataId& id, attributeIds) { q.reset(); q.bindDataId(1, id); q.execute(); U2DataType type = SQLiteUtils::toType(id); switch (type) { case U2Type::AttributeInteger: removeAttribute(qi, id); break; case U2Type::AttributeReal: removeAttribute(qr, id); break; case U2Type::AttributeString: removeAttribute(qs, id); break; case U2Type::AttributeByteArray: removeAttribute(qb, id); break; default: os.setError(SQLiteL10n::tr("Unsupported attribute type: %1").arg(type)); break; } if (os.hasError()) { break; } } } void SQLiteAttributeDbi::removeObjectAttributes(const U2DataId& objectId, U2OpStatus& os) { QList attributes = getObjectAttributes(objectId, "", os); if (!attributes.isEmpty()) { removeAttributes(attributes, os); } } qint64 SQLiteAttributeDbi::createAttribute(U2Attribute& attr, U2DataType type, U2OpStatus& os) { SQLiteQuery q("INSERT INTO Attribute(type, object, child, otype, ctype, oextra, cextra, version, name) " " VALUES(?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9)", db, os); q.bindType(1, type); q.bindDataId(2, attr.objectId); q.bindDataId(3, attr.childId); q.bindType(4, SQLiteUtils::toType(attr.objectId)); q.bindType(5, SQLiteUtils::toType(attr.childId)); q.bindBlob(6, SQLiteUtils::toDbExtra(attr.objectId)); q.bindBlob(7, SQLiteUtils::toDbExtra(attr.childId)); q.bindInt64(8, attr.version); q.bindString(9, attr.name); return q.insert(); } /** Creates int64 attribute in database. ObjectId must be already set in attribute and present in the same database Requires U2DbiFeature_WriteAttribute feature support */ void SQLiteAttributeDbi::createIntegerAttribute(U2IntegerAttribute& a, U2OpStatus& os) { qint64 id = createAttribute(a, U2Type::AttributeInteger, os); if (os.hasError()) { return; } a.id = SQLiteUtils::toU2DataId(id, U2Type::AttributeInteger); SQLiteQuery q("INSERT INTO IntegerAttribute(attribute, value) VALUES(?1, ?2)", db, os); q.bindInt64(1, id); q.bindInt64(2, a.value); q.execute(); } /** Creates real64 attribute in database. ObjectId must be already set in attribute and present in the same database Requires U2DbiFeature_WriteAttribute feature support */ void SQLiteAttributeDbi::createRealAttribute(U2RealAttribute& a, U2OpStatus& os) { qint64 id = createAttribute(a, U2Type::AttributeReal, os); if (os.hasError()) { return; } a.id = SQLiteUtils::toU2DataId(id, U2Type::AttributeReal); SQLiteQuery q("INSERT INTO RealAttribute(attribute, value) VALUES(?1, ?2)", db, os); q.bindInt64(1, id); q.bindDouble(2, a.value); q.execute(); } /** Creates String attribute in database. ObjectId must be already set in attribute and present in the same database Requires U2DbiFeature_WriteAttribute feature support */ void SQLiteAttributeDbi::createStringAttribute(U2StringAttribute& a, U2OpStatus& os) { qint64 id = createAttribute(a, U2Type::AttributeString, os); if (os.hasError()) { return; } a.id = SQLiteUtils::toU2DataId(id, U2Type::AttributeString); SQLiteQuery q("INSERT INTO StringAttribute(attribute, value) VALUES(?1, ?2)", db, os); q.bindInt64(1, id); q.bindString(2, a.value); q.execute(); } /** Creates Byte attribute in database. ObjectId must be already set in attribute and present in the same database Requires U2DbiFeature_WriteAttribute feature support */ void SQLiteAttributeDbi::createByteArrayAttribute(U2ByteArrayAttribute& a, U2OpStatus& os) { qint64 id = createAttribute(a, U2Type::AttributeByteArray, os); if (os.hasError()) { return; } a.id = SQLiteUtils::toU2DataId(id, U2Type::AttributeByteArray); SQLiteQuery q("INSERT INTO ByteArrayAttribute(attribute, value) VALUES(?1, ?2)", db, os); q.bindInt64(1, id); q.bindBlob(2, a.value, false); q.execute(); } } //namespace ugene-1.9.8/src/plugins/dbi_sqlite/src/SQLiteDbiPlugin.h0000644000175000017500000000207311651544322021605 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_SQLITE_DBI_PLUGIN_H_ #define _U2_SQLITE_DBI_PLUGIN_H_ #include namespace U2 { class SQLiteDbiPlugin : public Plugin { Q_OBJECT public: SQLiteDbiPlugin(); }; } //namespace #endif ugene-1.9.8/src/plugins/dbi_sqlite/src/SQLiteMsaDbi.cpp0000644000175000017500000001457411651544322021433 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "SQLiteMsaDbi.h" #include namespace U2 { SQLiteMsaRDbi::SQLiteMsaRDbi(SQLiteDbi* dbi) : U2SimpleMsaDbi(dbi), SQLiteChildDBICommon(dbi) { } void SQLiteMsaRDbi::initSqlSchema(U2OpStatus& os) { if (os.hasError()) { return; } // msa object SQLiteQuery(" CREATE TABLE Msa (object INTEGER, length INTEGER NOT NULL, alphabet TEXT NOT NULL, sequenceCount INTEGER NOT NULL, " " FOREIGN KEY(object) REFERENCES Object(id) )", db, os).execute(); // msa object row // msa - msa object id // sequence - sequence object id // pos - positional number of row in msa // gstart - offset of the first non-gap sequence element. Same as gstart of the first MsaRowGap // gend - offset of the last non-gap sequence element. Same as gend of the last MsaRowGap SQLiteQuery("CREATE TABLE MsaRow (msa INTEGER, sequence INTEGER, pos INTEGER NOT NULL, gstart INTEGER NOT NULL, gend INTEGER NOT NULL, " " FOREIGN KEY(msa) REFERENCES Msa(object), " " FOREIGN KEY(sequence) REFERENCES Msa(object) )", db, os).execute(); // gap info for msa row: // gstart - global (in msa) start of non-gap region // gend - global (in msa) end of non-gap region // sstart - local (in sequence) start of non-gap region // send - local (in sequence) end of non-gap region // Note! there is invariant: gend - gstart == send - sstart SQLiteQuery("CREATE TABLE MsaRowGap (msa INTEGER, sequence INTEGER, gstart INTEGER NOT NULL, gend INTEGER NOT NULL, " " sstart INTEGER NOT NULL, send INTEGER NOT NULL, " " FOREIGN KEY(msa) REFERENCES MsaRow(msa), " " FOREIGN KEY(sequence) REFERENCES MsaRow(sequence) )", db, os).execute(); } U2Msa SQLiteMsaRDbi::getMsaObject(const U2DataId& msaId, U2OpStatus& os) { U2Msa res(msaId, dbi->getDbiId(), 0); SQLiteQuery q("SELECT Msa.alphabet, Object.version FROM Msa, Object WHERE Object.id = ?1 AND Msa.object = Object.id", db, os); q.bindDataId(1, msaId); if (q.step()) { res.alphabet = q.getString(1); res.version = q.getInt64(2); q.ensureDone(); } return res; } qint64 SQLiteMsaRDbi::getSequencesCount(const U2DataId& msaId, U2OpStatus& os) { SQLiteQuery q("SELECT COUNT(*) FROM MsaRow WHERE msa = ?1", db, os); q.bindDataId(1, msaId); return q.selectInt64(); } QList SQLiteMsaRDbi::getRows(const U2DataId& msaId, qint32 firstRow, qint32 numRows, U2OpStatus& os) { QList res; SQLiteQuery q("SELECT sequence FROM MsaRow WHERE msa = ?1 AND pos >= ?2 AND pos < ?3", db, os); q.bindDataId(1, msaId); q.bindInt64(2, firstRow); q.bindInt64(3, firstRow + numRows); SQLiteQuery gapQ("SELECT sstart, send, FROM MsaRowGap WHERE msa = ?1 AND sequence = ?2 ORDER BY sstart", db, os); while (q.step()) { U2MsaRow row; row.sequenceId = q.getDataId(0, U2Type::Sequence); gapQ.reset(); gapQ.bindDataId(1, msaId); gapQ.bindDataId(2, row.sequenceId); U2MsaGap prev; while (gapQ.step()) { U2MsaGap gap; gap.offset = gapQ.getInt64(0); gap.gap = gapQ.getInt64(1) - gap.offset; row.gaps.append(gap); assert(prev.offset + prev.gap < gap.offset); //gaps are ordered correctly and do not overlap prev = gap; } if (os.hasError()) { break; } res.append(row); } return res; } qint32 SQLiteMsaRDbi::countSequencesAt(const U2DataId& msaId, qint64 coord, U2OpStatus& os) { SQLiteQuery q("SELECT COUNT(*) FROM MsaRow WHERE msa = ?1 AND gstart <= ?2 AND gend > ?2", db, os); q.bindDataId(1, msaId); q.bindInt64(2, coord); return (qint32)q.selectInt64(); } QList SQLiteMsaRDbi::getSequencesAt(const U2DataId& msaId, qint64 coord, qint32 offset, qint32 count, U2OpStatus& os) { SQLiteQuery q("SELECT sequenceId FROM MsaRow WHERE msa = ?1 AND gstart <= ?2 AND gend > ?2", offset, count, db, os); q.bindDataId(1, msaId); q.bindInt64(2, coord); return q.selectDataIds(U2Type::Sequence); } qint32 SQLiteMsaRDbi::countSequencesAt(const U2DataId& msaId, const U2Region& r, U2OpStatus& os) { SQLiteQuery q("SELECT COUNT(*) FROM MsaRow WHERE msa = ?1 AND ((gstart <= ?2 AND gend > ?2) OR (gstart <= ?3 AND gend > ?3)", db, os); q.bindDataId(1, msaId); q.bindInt64(2, r.startPos); q.bindInt64(3, r.endPos()); return (qint32)q.selectInt64(); } QList SQLiteMsaRDbi::getSequencesAt(const U2DataId& msaId, const U2Region& r, qint32 offset, qint32 count, U2OpStatus& os) { SQLiteQuery q("SELECT sequenceId FROM MsaRow WHERE msa = ?1 AND ((gstart <= ?2 AND gend > ?2) OR (gstart <= ?3 AND gend > ?3)", offset, count, db, os); q.bindDataId(1, msaId); q.bindInt64(2, r.startPos); q.bindInt64(3, r.endPos()); return q.selectDataIds(U2Type::Sequence); } qint32 SQLiteMsaRDbi::countSequencesWithoutGapAt(const U2DataId& msaId, qint64 coord, U2OpStatus& os) { SQLiteQuery q("SELECT COUNT(*) FROM MsaRowGap WHERE msa = ?1 AND gstart <= ?2 AND gend > ?2", db, os); q.bindDataId(1, msaId); q.bindInt64(2, coord); return (qint32)q.selectInt64(); } QList SQLiteMsaRDbi::getSequencesWithoutGapAt(const U2DataId& msaId, qint64 coord, qint32 offset, qint32 count, U2OpStatus& os) { SQLiteQuery q("SELECT sequenceId FROM MsaRowGap WHERE msa = ?1 AND gstart <= ?2 AND gend > ?2", offset, count, db, os); q.bindDataId(1, msaId); q.bindInt64(2, coord); return q.selectDataIds(U2Type::Sequence); } } //namespace ugene-1.9.8/src/plugins/dbi_sqlite/src/SQLiteDbi.h0000644000175000017500000001464611651544322020437 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_SQLITE_DBI_H_ #define _U2_SQLITE_DBI_H_ #include #include struct sqlite3; namespace U2 { class SQLiteObjectDbi; class SQLiteSequenceDbi; class SQLiteMsaRDbi; class SQLiteAssemblyDbi; class SQLiteCrossDatabaseReferenceDbi; class SQLiteAttributeDbi; class DbRef; // Names of SQLiteDbi flags #define SQLITE_DBI_OPTION_UGENE_VERSION "ugene-version" /** Name of the init property used to indicate assembly reads storage method for all new assemblies */ #define SQLITE_DBI_ASSEMBLY_READ_ELEN_METHOD_KEY "sqlite-assembly-reads-elen-method" /** Stores all reads in a single table. Not optimal if read effective length varies */ #define SQLITE_DBI_ASSEMBLY_READ_ELEN_METHOD_SINGLE_TABLE "single-table" /** Store all reads in N tables sorted by effective read length */ #define SQLITE_DBI_ASSEMBLY_READ_ELEN_METHOD_MULTITABLE_V1 "multi-table-v1" /** Uses RTree index to store reads. This method is simple but not very efficient in terms of space/insert time */ #define SQLITE_DBI_ASSEMBLY_READ_ELEN_METHOD_RTREE "rtree2d" /** Name of the property used to indicate compression algorithm for reads data */ #define SQLITE_DBI_ASSEMBLY_READ_COMPRESSION_METHOD_KEY "sqlite-assembly-reads-compression-method" /** No compression is applied. Best for manual DB browsing (default)*/ #define SQLITE_DBI_ASSEMBLY_READ_COMPRESSION_METHOD_NO_COMPRESSION "no-compression" /** CIGAR and sequence are packed using bits compression and stored as a single BLOB */ #define SQLITE_DBI_ASSEMBLY_READ_COMPRESSION_METHOD_BITS_1 "compress-bits-1" /** Indicates object life-cycle and storage location */ enum SQLiteDbiObjectRank { /** Object is stored in this database and is top-level (included into some folder) */ SQLiteDbiObjectRank_TopLevel = 1, /** Object is stored in this database and is not top-level, it is a child of another object */ SQLiteDbiObjectRank_Child = 2, /** Object is stored in another database, see CrossDbiReference table for details */ SQLiteDbiObjectRank_Remote = 3 }; // Values of SQLiteDbi flags #define SQLITE_DBI_VALUE_MEMORY_DB_URL ":memory:" class SQLiteDbi : public U2AbstractDbi { public: SQLiteDbi(); ~SQLiteDbi(); /** Boots the database up to functional state. Can be called again after successful shutdown, to re-load the database. special flags "assembly-reads-compression=1" - enables reads compression for assembly. Affects new DB only */ virtual void init(const QHash& properties, const QVariantMap& persistentData, U2OpStatus& os); /** Stops the database and frees up used resources. */ virtual QVariantMap shutdown(U2OpStatus& os); /** Ensures that dbi state is synchronized with storage Return 'true' of operation is successful */ virtual bool flush(U2OpStatus& os); /** Unique database id. Used for cross-database references. */ virtual QString getDbiId() const; /** Returns database meta-info. Any set of properties to be shown to user */ virtual QHash getDbiMetaInfo(U2OpStatus& os) ; /** Returns type of the entity referenced by the given ID */ virtual U2DataType getEntityTypeById(const U2DataId& id) const; virtual U2ObjectDbi* getObjectDbi(); virtual U2SequenceDbi* getSequenceDbi(); virtual U2AssemblyDbi* getAssemblyDbi(); virtual U2CrossDatabaseReferenceDbi* getCrossDatabaseReferenceDbi(); virtual U2AttributeDbi* getAttributeDbi(); DbRef* getDbRef() const {return db;} SQLiteObjectDbi* getSQLiteObjectDbi() const; /** Returns properties used to initialized the database */ virtual QHash getInitProperties() const {return initProperties;} private: QString getLastErrorMessage(int rc); void setState(U2DbiState state); QString getProperty(const QString& name, const QString& defaultValue, U2OpStatus& os) const; void setProperty(const QString& name, const QString& value, U2OpStatus& os); void populateDefaultSchema(U2OpStatus& os); void internalInit(const QHash& props, U2OpStatus& os); QString url; DbRef* db; SQLiteObjectDbi* objectDbi; SQLiteSequenceDbi* sequenceDbi; SQLiteMsaRDbi* msaDbi; SQLiteAssemblyDbi* assemblyDbi; SQLiteCrossDatabaseReferenceDbi* crossDbi; SQLiteAttributeDbi* attributeDbi; friend class SQLiteObjectDbi; friend class SQLiteCrossDatabaseReferenceDbi; friend class SQLiteSequenceDbi; friend class SQLiteAssemblyDbi; friend class SQLiteMsaRDbi; friend class SQLiteAttributeDbi; }; class SQLiteDbiFactory : public U2DbiFactory { public: SQLiteDbiFactory(); /** Creates new DBI instance */ virtual U2Dbi *createDbi(); /** Returns DBI type ID */ virtual U2DbiFactoryId getId() const; /** Checks that data pointed by properties is a valid DBI resource */ virtual bool isValidDbi(const QHash& properties, const QByteArray& rawData, U2OpStatus& os) const; public: static const U2DbiFactoryId ID; }; /** helper class, used as a base for all SQLiteDbis */ class SQLiteChildDBICommon { public: SQLiteChildDBICommon(SQLiteDbi* dbi) : dbi(dbi), db (dbi->getDbRef()){} virtual ~SQLiteChildDBICommon(){} virtual void initSqlSchema(U2OpStatus& os) = 0; virtual void shutdown(U2OpStatus&) {}; protected: SQLiteDbi* dbi; DbRef* db; }; class SQLiteL10N : public QObject { Q_OBJECT }; } //namespace #endif ugene-1.9.8/src/plugins/dbi_sqlite/src/SQLiteSequenceDbi.cpp0000644000175000017500000002125411651544322022454 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "SQLiteSequenceDbi.h" #include "SQLiteObjectDbi.h" #include #include namespace U2 { SQLiteSequenceDbi::SQLiteSequenceDbi(SQLiteDbi* dbi) : U2SequenceDbi(dbi), SQLiteChildDBICommon(dbi) { } void SQLiteSequenceDbi::initSqlSchema(U2OpStatus& os) { if (os.hasError()) { return; } // sequence object SQLiteQuery("CREATE TABLE Sequence (object INTEGER, length INTEGER NOT NULL DEFAULT 0, alphabet TEXT NOT NULL, " "circular INTEGER NOT NULL DEFAULT 0, " "FOREIGN KEY(object) REFERENCES Object(id) )", db, os).execute(); // part of the sequence, starting with 'sstart'(inclusive) and ending at 'send'(not inclusive) SQLiteQuery("CREATE TABLE SequenceData (sequence INTEGER, sstart INTEGER NOT NULL, send INTEGER NOT NULL, data BLOB NOT NULL, " "FOREIGN KEY(sequence) REFERENCES Sequence(object) )", db, os).execute(); } U2Sequence SQLiteSequenceDbi::getSequenceObject(const U2DataId& sequenceId, U2OpStatus& os) { U2Sequence res; SQLiteQuery q("SELECT Sequence.length, Sequence.alphabet, Sequence.circular, Object.version FROM Sequence, Object " " WHERE Object.id = ?1 AND Sequence.object = Object.id", db, os); q.bindDataId(1, sequenceId); if (q.step()) { res.id = sequenceId; res.dbiId = dbi->getDbiId(); res.version = 0; res.length = q.getInt64(0); res.alphabet = q.getString(1); res.circular = q.getBool(2); res.version = q.getInt64(3); q.ensureDone(); } else if (!os.hasError()) { os.setError(SQLiteL10N::tr("Sequence object not found.")); } return res; } QByteArray SQLiteSequenceDbi::getSequenceData(const U2DataId& sequenceId, const U2Region& region, U2OpStatus& os) { GTIMER(c1, t1, "SQLiteSequenceDbi::getSequenceData"); QByteArray res; res.reserve(region.length); SQLiteQuery q("SELECT sstart, send, data FROM SequenceData WHERE sequence = ?1 " "AND ((sstart >= ?2 AND sstart <= ?3) OR (?2 >= sstart AND send > ?2)) ORDER BY sstart", db, os); q.bindDataId(1, sequenceId); q.bindInt64(2, region.startPos); q.bindInt64(3, region.endPos()); qint64 pos = region.startPos; while (q.step()) { qint64 sstart = q.getInt64(0); qint64 send = q.getInt64(1); qint64 length = send - sstart; QByteArray data = q.getBlob(2); int copyStart = pos - sstart; int copyLength = qMin(region.length, length - copyStart); res.append(data.constData() + copyStart, copyLength); pos+=copyLength; } return res; } void SQLiteSequenceDbi::createSequenceObject(U2Sequence& sequence, const QString& folder, U2OpStatus& os) { sequence.id = SQLiteObjectDbi::createObject(U2Type::Sequence, folder, sequence.visualName, SQLiteDbiObjectRank_TopLevel, db, os); if (os.hasError()) { return; } SQLiteQuery q("INSERT INTO Sequence(object, alphabet, circular) VALUES(?1, ?2, ?3)", db, os); q.bindDataId(1, sequence.id); q.bindString(2, sequence.alphabet.id); q.bindBool(3, sequence.circular); q.execute(); } #define SEQUENCE_CHUNK_SIZE (1024*1024) static QList quantify(const QList input) { QList res; QByteArray currentChunk; foreach (const QByteArray& i, input) { int d = SEQUENCE_CHUNK_SIZE - currentChunk.length(); if (i.length() <= d) { //if 'i' fits into chunk - just add it currentChunk.append(i); } else { // 'i' does not fit into chunk -> split it into separate chunks for (int j = 0; j < i.length(); j += d) { if (j > 0) { d = qMin(SEQUENCE_CHUNK_SIZE, i.length() - j); } currentChunk.append(i.constData() + j, + d); assert(currentChunk.length() == SEQUENCE_CHUNK_SIZE); res.append(currentChunk); currentChunk.clear(); } } if (currentChunk.length() == SEQUENCE_CHUNK_SIZE) { res.append(currentChunk); currentChunk.clear(); } } if (!currentChunk.isEmpty()) { res.append(currentChunk); } return res; } void SQLiteSequenceDbi::updateSequenceData(const U2DataId& sequenceId, const U2Region& regionToReplace, const QByteArray& dataToInsert, U2OpStatus& os) { SQLiteTransaction t(db, os); //algorithm: // find all regions affected -> remove them // construct new regions from cuts from old regions and new dataToInsert // remove affected annotations or adjust their locations if possible // find cropped parts QByteArray leftCrop; SQLiteQuery leftQ("SELECT sstart FROM SequenceData WHERE sequence = ?1 AND sstart <= ?2 AND send >= ?2", db, os); leftQ.bindDataId(1, sequenceId); leftQ.bindInt64(2, regionToReplace.startPos); qint64 cropLeftPos = leftQ.selectInt64(-1); if (os.hasError()) { return; } if (cropLeftPos >= 0) { leftCrop = getSequenceData(sequenceId, U2Region(cropLeftPos, regionToReplace.startPos - cropLeftPos), os); } else { cropLeftPos = 0; } QByteArray rightCrop; SQLiteQuery rightQ("SELECT send FROM SequenceData WHERE sequence = ?1 AND sstart <= ?2 AND send >= ?2", db, os); rightQ.bindDataId(1, sequenceId); rightQ.bindInt64(2, regionToReplace.endPos()); qint64 cropRightPos = rightQ.selectInt64(-1); if (os.hasError()) { return; } if (cropRightPos > 0) { rightCrop = getSequenceData(sequenceId, U2Region(regionToReplace.endPos(), cropRightPos - regionToReplace.endPos()), os); } // remove all affected regions SQLiteQuery removeQ("DELETE FROM SequenceData WHERE sequence = ?1 " " AND ((sstart >= ?2 AND sstart <= ?3) OR (?2 >= sstart AND send >= ?2))", db, os); removeQ.bindDataId(1, sequenceId); removeQ.bindInt64(2, regionToReplace.startPos); removeQ.bindInt64(3, regionToReplace.endPos()); removeQ.execute(); if (os.hasError()) { return; } // now adjust 'sstart' & 'send' for all sequence regions on the right side of the insert if (dataToInsert.length() != regionToReplace.length) { qint64 d = dataToInsert.length() - regionToReplace.length; SQLiteQuery updateQ("UPDATE SequenceData SET sstart = sstart + ?1, send = send + ?1 WHERE sequence = ?2 AND sstart >= ?3", db, os); updateQ.bindInt64(1, d); updateQ.bindDataId(2, sequenceId); updateQ.bindInt64(3, regionToReplace.endPos()); updateQ.execute(); if (os.hasError()) { return; } } // insert new regions QList newDataToInsert = quantify(QList() << leftCrop << dataToInsert << rightCrop); SQLiteQuery insertQ("INSERT INTO SequenceData(sequence, sstart, send, data) VALUES(?1, ?2, ?3, ?4)", db, os); qint64 startPos = cropLeftPos; foreach(const QByteArray& d, newDataToInsert) { insertQ.reset(); insertQ.bindDataId(1, sequenceId); insertQ.bindInt64(2, startPos); insertQ.bindInt64(3, startPos + d.length()); insertQ.bindBlob(4, d); insertQ.execute(); if (os.hasError()) { return; } startPos += d.length(); } // Update sequence object length; SQLiteQuery lengthQ("SELECT MAX(send) FROM SequenceData WHERE sequence = ?1", db, os); lengthQ.bindDataId(1, sequenceId); qint64 newLength = lengthQ.selectInt64(); if (os.hasError()) { return; } SQLiteQuery updateLengthQuery("UPDATE Sequence SET length = ?1 WHERE object = ?2", db, os); updateLengthQuery.bindInt64(1, newLength); updateLengthQuery.bindDataId(2, sequenceId); updateLengthQuery.update(1); if (os.hasError()) { return; } SQLiteObjectDbi::incrementVersion(sequenceId, db, os); } } //namespace ugene-1.9.8/src/plugins/dbi_sqlite/src/SQLiteSequenceDbi.h0000644000175000017500000000452011651544322022116 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_SQLITE_SEQUENCE_DBI_H_ #define _U2_SQLITE_SEQUENCE_DBI_H_ #include "SQLiteDbi.h" namespace U2 { class SQLiteSequenceDbi : public U2SequenceDbi, public SQLiteChildDBICommon { public: SQLiteSequenceDbi(SQLiteDbi* dbi); /** Reads sequence object from database */ virtual U2Sequence getSequenceObject(const U2DataId& sequenceId, U2OpStatus& os); /** Reads specified sequence data region from database */ virtual QByteArray getSequenceData(const U2DataId& sequenceId, const U2Region& region, U2OpStatus& os); /** Adds new (empty) sequence instance into database, sets the assigned id on the passed U2Sequence instance. The folder must exist in the database. Use 'updateSequenceData' method to supply data to the created sequence. //TODO do we need to allow empty folder?? */ virtual void createSequenceObject(U2Sequence& sequence, const QString& folder, U2OpStatus& os); /** Updates sequence region. The region must be valid region within sequence bounds. Note: regionToReplace length can differ from dataToInsert length, so the method can be used to add/remove sequence regions //TODO think about annotations: should we fix locations automatically?? If yes, emit notifications?? */ virtual void updateSequenceData(const U2DataId& sequenceId, const U2Region& regionToReplace, const QByteArray& dataToInsert, U2OpStatus& os); virtual void initSqlSchema(U2OpStatus& os); }; } //namespace #endif ugene-1.9.8/src/plugins/dbi_sqlite/src/SQLiteDbiPlugin.cpp0000644000175000017500000001113611651544322022140 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "SQLiteDbiPlugin.h" #include "SQLiteDbi.h" #include #include #include #include #include #include #include #include #include namespace U2 { extern "C" Q_DECL_EXPORT Plugin* U2_PLUGIN_INIT_FUNC() { SQLiteDbiPlugin* plug = new SQLiteDbiPlugin(); return plug; } //#define TEST_SQLITE_DBI #ifdef TEST_SQLITE_DBI static QList generateReads(int nReads, const U2Region& elenRange, int refSeqLen) { static const char* acgt = "ACGT"; QList res; qint64 readSeqLen = qMin(qint64(30), elenRange.startPos); for (int i = 0; i < nReads ; i++) { U2AssemblyRead r(new U2AssemblyReadData()); int elen = elenRange.startPos + (qrand() % elenRange.length); int delta = elen - readSeqLen; r->cigar << U2CigarToken(U2CigarOp_M, readSeqLen-2) << U2CigarToken(U2CigarOp_D, delta) << U2CigarToken(U2CigarOp_M, 2); r->leftmostPos = qrand() % (refSeqLen - elen); r->readSequence.resize(readSeqLen); for (int j = 0; j < readSeqLen; j++) { char c = acgt[qrand() % 4]; //char c = 'A'; r->readSequence[j] = c; } r->name = r->readSequence.mid(0, 15); res.append(r); } return res; } #endif SQLiteDbiPlugin::SQLiteDbiPlugin() : Plugin(tr("SQLite format support"), tr("Adds support for SQLite format to UGENE")) { AppContext::getDbiRegistry()->registerDbiFactory(new SQLiteDbiFactory()); DbiDocumentFormat* f = new DbiDocumentFormat(SQLiteDbiFactory::ID, "usqlite", tr("UGENE Database"), QStringList()<<"ugenedb" ); AppContext::getDocumentFormatRegistry()->registerFormat(f); #ifdef TEST_SQLITE_DBI SQLiteDbi dbi; U2OpStatusImpl os; QHash props; QString url = "c:/test.sqlite"; QFile::remove(url); props[U2_DBI_OPTION_URL] = url; //props[U2_DBI_OPTION_URL] = SQLITE_DBI_VALUE_MEMORY_DB_URL; //props[SQLITE_DBI_OPTION_ASSEMBLY_READ_COMPRESSION1_FLAG] = U2_DBI_VALUE_ON; props[U2_DBI_OPTION_CREATE] = U2_DBI_VALUE_ON; //props[SQLITE_DBI_ASSEMBLY_READ_ELEN_METHOD_KEY] = SQLITE_DBI_ASSEMBLY_READ_ELEN_METHOD_RTREE; //props[SQLITE_DBI_ASSEMBLY_READ_ELEN_METHOD_KEY] = SQLITE_DBI_ASSEMBLY_READ_ELEN_METHOD_SINGLE_TABLE; props[SQLITE_DBI_ASSEMBLY_READ_ELEN_METHOD_KEY] = SQLITE_DBI_ASSEMBLY_READ_ELEN_METHOD_MULTITABLE_V1; dbi.init(props, QVariantMap(), os); dbi.getDbRef()->useTransaction = true; int nReads = 100*1000; int seqLen = 100*1000; U2Region lenRange(30, 500); QList rows = generateReads(nReads, lenRange, seqLen); dbi.getObjectDbi()->createFolder("/", os); qint64 t0 = GTimer::currentTimeMicros(); U2Assembly as; { // dbi.getAssemblyRWDbi()->createAssemblyObject(as, "/", NULL, os); // dbi.getAssemblyRWDbi()->addReads(as.id, rows, os); BufferedDbiIterator it(rows); dbi.getAssemblyDbi()->createAssemblyObject(as, "/", &it, os); } qint64 t1 = GTimer::currentTimeMicros(); float nSeconds = float((t1-t0)/(1000*1000.0)); perfLog.info(QString("Insert rate: %1/second").arg(int(nReads/nSeconds))); if (os.hasError()) { coreLog.error(os.getError()); } bool pack = true; if (pack) { U2AssemblyPackStat stat; qint64 t0 = GTimer::currentTimeMicros(); dbi.getAssemblyDbi()->pack(as.id, stat, os); qint64 t1 = GTimer::currentTimeMicros(); float nSeconds = float((t1-t0)/(1000*1000.0)); perfLog.info(QString("Pack rate: %1/second").arg(int(nReads/nSeconds))); } dbi.shutdown(os); #endif } }//namespace ugene-1.9.8/src/plugins/dbi_sqlite/src/SQLiteDbi.cpp0000644000175000017500000002474711651544322020775 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "SQLiteDbi.h" #include "SQLiteObjectDbi.h" #include "SQLiteSequenceDbi.h" #include "SQLiteMsaDbi.h" #include "SQLiteAssemblyDbi.h" #include "SQLiteAttributeDbi.h" #include #include #include #include #include namespace U2 { SQLiteDbi::SQLiteDbi() : U2AbstractDbi (SQLiteDbiFactory::ID){ db = new DbRef(); objectDbi = new SQLiteObjectDbi(this); sequenceDbi = new SQLiteSequenceDbi(this); msaDbi = new SQLiteMsaRDbi(this); assemblyDbi = new SQLiteAssemblyDbi(this); crossDbi = new SQLiteCrossDatabaseReferenceDbi(this); attributeDbi = new SQLiteAttributeDbi(this); } SQLiteDbi::~SQLiteDbi() { assert(db->handle == NULL); delete objectDbi; delete sequenceDbi; delete msaDbi; delete assemblyDbi; delete crossDbi; delete attributeDbi; delete db; } U2ObjectDbi* SQLiteDbi::getObjectDbi() { return objectDbi; } U2SequenceDbi* SQLiteDbi::getSequenceDbi() { return sequenceDbi; } U2AssemblyDbi* SQLiteDbi::getAssemblyDbi() { return assemblyDbi; } U2CrossDatabaseReferenceDbi* SQLiteDbi::getCrossDatabaseReferenceDbi() { return crossDbi; } U2AttributeDbi* SQLiteDbi::getAttributeDbi() { return attributeDbi; } QString SQLiteDbi::getProperty(const QString& name, const QString& defaultValue, U2OpStatus& os) const { SQLiteQuery q("SELECT value FROM Meta WHERE name = ?1", db, os); q.bindString(1, name); bool found = q.step(); if (os.hasError()) { return QString(); } if (found) { return q.getString(0); } return defaultValue; } void SQLiteDbi::setProperty(const QString& name, const QString& value, U2OpStatus& os) { if (os.hasError()) { return; } SQLiteQuery q1("DELETE FROM Meta WHERE name = ?1", db, os); q1.bindString(1, name); q1.execute(); SQLiteQuery q2("INSERT INTO Meta(name, value) VALUES (?1, ?2)", db, os); q2.bindString(1, name); q2.bindString(2, value); q2.execute(); } static int isEmptyCallback(void *o, int argc, char ** /*argv*/, char ** /*column*/) { int* res = (int*)o; *res = argc; return 0; } static bool isEmpty(DbRef* db, U2OpStatus& os) { QByteArray showTablesQuery = "SELECT * FROM sqlite_master WHERE type='table';"; int nTables = 0; char* err; int rc = sqlite3_exec(db->handle, showTablesQuery.constData(), isEmptyCallback, &nTables, &err); if (rc != SQLITE_OK) { os.setError(SQLiteL10N::tr("Error checking SQLite database: %1!").arg(err)); sqlite3_free(err); return false; } return nTables == 0; } #define CT(table, fields) \ { \ char* err = NULL; \ QByteArray query = QByteArray("CREATE TABLE ") + table + " (" + fields + ");";\ int rc = sqlite3_exec(db->handle, query, NULL, NULL, &err); \ if (rc != SQLITE_OK) { \ os.setError(SQLiteL10N::tr("Error creating table: %1, error: %2").arg(table).arg(err)); \ sqlite3_free(err); \ return; \ } \ } void SQLiteDbi::populateDefaultSchema(U2OpStatus& os) { // meta table, stores general db info SQLiteQuery("CREATE TABLE Meta(name TEXT NOT NULL, value TEXT NOT NULL)", db, os).execute(); objectDbi->initSqlSchema(os); sequenceDbi->initSqlSchema(os); msaDbi->initSqlSchema(os); assemblyDbi->initSqlSchema(os); crossDbi->initSqlSchema(os); attributeDbi->initSqlSchema(os); setProperty(SQLITE_DBI_OPTION_UGENE_VERSION, Version::ugeneVersion().text, os); } void SQLiteDbi::internalInit(const QHash& props, U2OpStatus& os){ QString dbUgeneVersionText = getProperty(SQLITE_DBI_OPTION_UGENE_VERSION, "", os); if (os.hasError()) { return; } if (dbUgeneVersionText.isEmpty()) { os.setError(SQLiteL10n::tr("Not a UGENE SQLite database: %1").arg(url)); return; } Version dbUgeneVersion = Version::parseVersion(dbUgeneVersionText); Version currentVersion = Version::ugeneVersion(); if (dbUgeneVersion > currentVersion) { coreLog.info(SQLiteL10n::tr("Warning! Database of version %1 was created with a newer UGENE version: %2. Not all database features are supported!").arg(currentVersion.text).arg(dbUgeneVersion.text)); } foreach(const QString& key, props.keys()) { if (key.startsWith("sqlite-")) { setProperty(key, props.value(key), os); } } // set up features list features.insert(U2DbiFeature_ReadSequence); features.insert(U2DbiFeature_ReadMsa); features.insert(U2DbiFeature_ReadAssembly); features.insert(U2DbiFeature_WriteSequence); //features.insert(U2DbiFeature_WriteMsa); features.insert(U2DbiFeature_WriteAssembly); features.insert(U2DbiFeature_AssemblyReadsPacking); features.insert(U2DbiFeature_AssemblyCoverageStat); features.insert(U2DbiFeature_RemoveObjects); features.insert(U2DbiFeature_ChangeFolders); features.insert(U2DbiFeature_ReadCrossDatabaseReferences); features.insert(U2DbiFeature_WriteCrossDatabaseReferences); features.insert(U2DbiFeature_ReadAttributes); features.insert(U2DbiFeature_WriteAttributes); } void SQLiteDbi::setState(U2DbiState s) { state = s; } QString SQLiteDbi::getLastErrorMessage(int rc) { QString err = db->handle == NULL ? QString(" error-code: %1").arg(rc) : QString(sqlite3_errmsg(db->handle)); return err; } void SQLiteDbi::init(const QHash& props, const QVariantMap&, U2OpStatus& os) { if (db->handle != NULL) { os.setError(SQLiteL10N::tr("Database is already opened!")); return; } if (state != U2DbiState_Void) { os.setError(SQLiteL10N::tr("Illegal database state: %1").arg(state)); return; } setState(U2DbiState_Starting); url = props.value(U2_DBI_OPTION_URL); if (url.isEmpty()) { os.setError(SQLiteL10N::tr("URL is not specified")); setState(U2DbiState_Void); return; } do { int flags = SQLITE_OPEN_READWRITE; bool create = props.value(U2_DBI_OPTION_CREATE, "0").toInt() > 0; if (create) { flags |= SQLITE_OPEN_CREATE; } QByteArray file = url.toUtf8(); int rc = sqlite3_open_v2(file.constData(), &db->handle, flags, NULL); if (rc != SQLITE_OK) { QString err = getLastErrorMessage(rc); os.setError(SQLiteL10N::tr("Error opening SQLite database: %1!").arg(err)); break; } SQLiteQuery("PRAGMA synchronous = OFF", db, os).execute(); SQLiteQuery("PRAGMA main.locking_mode = EXCLUSIVE", db, os).execute(); SQLiteQuery("PRAGMA temp_store = MEMORY", db, os).execute(); SQLiteQuery("PRAGMA journal_mode = MEMORY", db, os).execute(); SQLiteQuery("PRAGMA cache_size = 200000", db, os).execute(); //SQLiteQuery("PRAGMA page_size = 4096", db, os).execute(); //TODO: int sqlite3_enable_shared_cache(int); //TODO: read_uncommitted //TODO: incremental_vacuum //TODO: temp_store_directory // check if the opened database is valid UGENE sqlite dbi initProperties = props; if (isEmpty(db, os)) { if (create) { populateDefaultSchema(os); if (os.hasError()) { break; } } } dbiId = url; internalInit(props, os); // OK, initialization complete if (!os.hasError()) { ioLog.trace(QString("SQLite: initialized: %1\n").arg(url)); } } while (0); if (os.hasError()) { sqlite3_close(db->handle); db->handle = NULL; setState(U2DbiState_Void); return; } setState(U2DbiState_Ready); } QVariantMap SQLiteDbi::shutdown(U2OpStatus& os) { if (db == NULL) { os.setError(SQLiteL10N::tr("Database is already closed!")); return QVariantMap(); } if (state != U2DbiState_Ready) { os.setError(SQLiteL10N::tr("Illegal database state %1!").arg(state)); return QVariantMap(); } objectDbi->shutdown(os); sequenceDbi->shutdown(os); msaDbi->shutdown(os); assemblyDbi->shutdown(os); crossDbi->shutdown(os); attributeDbi->shutdown(os); setState(U2DbiState_Stopping); int rc = sqlite3_close(db->handle); if (rc != SQLITE_OK) { ioLog.error(SQLiteL10N::tr("Failed to close database: %1, err: %2").arg(url).arg(getLastErrorMessage(rc))); } ioLog.trace(QString("SQLite: shutting down: %1\n").arg(url)); db->handle = NULL; url.clear(); initProperties.clear(); setState(U2DbiState_Void); return QVariantMap(); } bool SQLiteDbi::flush(U2OpStatus& ) { //todo: return true; } QString SQLiteDbi::getDbiId() const { return url; } QHash SQLiteDbi::getDbiMetaInfo(U2OpStatus& ) { QHash res; res["url"] = url; return res; } U2DataType SQLiteDbi::getEntityTypeById(const U2DataId& id) const { return SQLiteUtils::toType(id); } SQLiteObjectDbi* SQLiteDbi::getSQLiteObjectDbi() const { return static_cast(objectDbi); } // SQLiteDbiFactory SQLiteDbiFactory::SQLiteDbiFactory() : U2DbiFactory() { } U2Dbi *SQLiteDbiFactory::createDbi() { return new SQLiteDbi(); } U2DbiFactoryId SQLiteDbiFactory::getId()const { return ID; } bool SQLiteDbiFactory::isValidDbi(const QHash& properties, const QByteArray& rawData, U2OpStatus& ) const { QString surl = properties.value(U2_DBI_OPTION_URL); GUrl url(surl); if (!url.isLocalFile()) { return false; } return rawData.startsWith("SQLite format 3"); } const U2DbiFactoryId SQLiteDbiFactory::ID = "SQLiteDbi"; }//namespace ugene-1.9.8/src/plugins/dbi_sqlite/src/SQLiteAssemblyDbi.cpp0000644000175000017500000004617011651544322022467 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "SQLiteAssemblyDbi.h" #include "SQLiteObjectDbi.h" #include "assembly/SingleTableAssemblyAdapter.h" #include "assembly/RTreeAssemblyAdapter.h" #include "assembly/MultiTableAssemblyAdapter.h" #include #include #include #include #include #include #include #include namespace U2 { SQLiteAssemblyDbi::SQLiteAssemblyDbi(SQLiteDbi* dbi) : U2AssemblyDbi(dbi), SQLiteChildDBICommon(dbi) { } SQLiteAssemblyDbi::~SQLiteAssemblyDbi() { assert(adaptersById.isEmpty()); } void SQLiteAssemblyDbi::initSqlSchema(U2OpStatus& os) { if (os.hasError()) { return; } // assembly object // reference - reference sequence id // imethod - indexing method - method used to handle read location // cmethod - method used to handle compression of reads data // idata - additional indexing method data // cdata - additional compression method data SQLiteQuery("CREATE TABLE Assembly (object INTEGER, reference INTEGER, imethod TEXT NOT NULL, cmethod TEXT NOT NULL, " "idata BLOB, cdata BLOB, " " FOREIGN KEY(object) REFERENCES Object(id), " " FOREIGN KEY(reference) REFERENCES Sequence(object) )", db, os).execute(); } void SQLiteAssemblyDbi::shutdown(U2OpStatus& os) { foreach(AssemblyAdapter* a, adaptersById.values()) { a->shutdown(os); delete a; } adaptersById.clear(); } AssemblyAdapter* SQLiteAssemblyDbi::getAdapter(const U2DataId& assemblyId, U2OpStatus& os) { qint64 sqliteId = SQLiteUtils::toDbiId(assemblyId); AssemblyAdapter* res = adaptersById.value(sqliteId); if (res != NULL) { return res; } SQLiteQuery q("SELECT imethod, cmethod FROM Assembly WHERE object = ?1", db, os); q.bindDataId(1, assemblyId); if (!q.step()) { os.setError(SQLiteL10N::tr("There is no assembly object with the specified id.")); return NULL; } QString indexMethod = q.getString(0); QByteArray idata = q.getBlob(2); assert(!indexMethod.isEmpty()); //TODO QString comp = q.getString(1); if (indexMethod == SQLITE_DBI_ASSEMBLY_READ_ELEN_METHOD_SINGLE_TABLE) { res = new SingleTableAssemblyAdapter(dbi, assemblyId, 'S', "", NULL, db, os); } else if (indexMethod == SQLITE_DBI_ASSEMBLY_READ_ELEN_METHOD_MULTITABLE_V1) { res = new MultiTableAssemblyAdapter(dbi, assemblyId, NULL, db, os); } else if (indexMethod == SQLITE_DBI_ASSEMBLY_READ_ELEN_METHOD_RTREE) { res = new RTreeAssemblyAdapter(dbi, assemblyId, NULL, db, os); } else { os.setError(SQLiteL10N::tr("Unsupported reads storage type: %1").arg(indexMethod)); return NULL; } adaptersById[sqliteId] = res; return res; } U2Assembly SQLiteAssemblyDbi::getAssemblyObject(const U2DataId& assemblyId, U2OpStatus& os) { U2Assembly res; SQLiteQuery q("SELECT Assembly.reference, Object.name, Object.version FROM Assembly, Object " " WHERE Object.id = ?1 AND Assembly.object = Object.id", db, os); q.bindDataId(1, assemblyId); if (q.step()) { res.id = assemblyId; res.dbiId = dbi->getDbiId(); res.version = 0; res.referenceId = q.getDataId(0, U2Type::Assembly); res.visualName = q.getString(1); res.version = q.getInt64(2); q.ensureDone(); } else if (!os.hasError()) { os.setError(SQLiteL10N::tr("Assembly object not found.")); } return res; } qint64 SQLiteAssemblyDbi::countReads(const U2DataId& assemblyId, const U2Region& r, U2OpStatus& os) { GTIMER(c2, t2, "SQLiteAssemblyDbi::countReadsAt"); AssemblyAdapter* a = getAdapter(assemblyId, os); if ( a == NULL ) { return -1; } return a->countReads(r, os); } U2DbiIterator* SQLiteAssemblyDbi::getReads(const U2DataId& assemblyId, const U2Region& r, U2OpStatus& os) { GTIMER(c2, t2, "SQLiteAssemblyDbi::getReadsAt"); AssemblyAdapter* a = getAdapter(assemblyId, os); if ( a != NULL ) { return a->getReads(r, os); } return NULL; } U2DbiIterator* SQLiteAssemblyDbi::getReadsByRow(const U2DataId& assemblyId, const U2Region& r, qint64 minRow, qint64 maxRow, U2OpStatus& os) { GTIMER(c2, t2, "SQLiteAssemblyDbi::getReadsAt"); quint64 t0 = GTimer::currentTimeMicros(); AssemblyAdapter* a = getAdapter(assemblyId, os); if ( a == NULL ) { return NULL; } U2DbiIterator* res = a->getReadsByRow(r, minRow, maxRow, os); t2.stop(); perfLog.trace(QString("Assembly: reads 2D select time: %1 seconds").arg((GTimer::currentTimeMicros() - t0) / float(1000*1000))); return res; } U2DbiIterator* SQLiteAssemblyDbi::getReadsByName(const U2DataId& assemblyId, const QByteArray& name, U2OpStatus& os) { GTIMER(c2, t2, "SQLiteAssemblyDbi::getReadsByName"); AssemblyAdapter* a = getAdapter(assemblyId, os); if ( a != NULL ) { return a->getReadsByName(name, os); } return NULL; } qint64 SQLiteAssemblyDbi::getMaxPackedRow(const U2DataId& assemblyId, const U2Region& r, U2OpStatus& os) { quint64 t0 = GTimer::currentTimeMicros(); AssemblyAdapter* a = getAdapter(assemblyId, os); if ( a == NULL ) { return -1; } qint64 res = a->getMaxPackedRow(r, os); perfLog.trace(QString("Assembly: get max packed row: %1 seconds").arg((GTimer::currentTimeMicros() - t0) / (1000*1000))); return res; } qint64 SQLiteAssemblyDbi::getMaxEndPos(const U2DataId& assemblyId, U2OpStatus& os) { quint64 t0 = GTimer::currentTimeMicros(); AssemblyAdapter* a = getAdapter(assemblyId, os); if ( a == NULL ) { return -1; } quint64 res = a->getMaxEndPos(os); perfLog.trace(QString("Assembly: get max end pos: %1 seconds").arg((GTimer::currentTimeMicros() - t0) / (1000*1000))); return res; } void SQLiteAssemblyDbi::createAssemblyObject(U2Assembly& assembly, const QString& folder, U2DbiIterator* it, U2AssemblyReadsImportInfo& importInfo, U2OpStatus& os) { assembly.id = SQLiteObjectDbi::createObject(U2Type::Assembly, folder, assembly.visualName, SQLiteDbiObjectRank_TopLevel, db, os); SAFE_POINT_OP(os,); //QString elenMethod = dbi->getProperty(SQLITE_DBI_ASSEMBLY_READ_ELEN_METHOD_KEY, SQLITE_DBI_ASSEMBLY_READ_ELEN_METHOD_RTREE, os); QString elenMethod = dbi->getProperty(SQLITE_DBI_ASSEMBLY_READ_ELEN_METHOD_KEY, SQLITE_DBI_ASSEMBLY_READ_ELEN_METHOD_MULTITABLE_V1, os); //QString elenMethod = dbi->getProperty(SQLITE_DBI_ASSEMBLY_READ_ELEN_METHOD_KEY, SQLITE_DBI_ASSEMBLY_READ_ELEN_METHOD_SINGLE_TABLE, os); SQLiteQuery q("INSERT INTO Assembly(object, reference, imethod, cmethod) VALUES(?1, ?2, ?3, ?4)", db, os); q.bindDataId(1, assembly.id); q.bindDataId(2, assembly.referenceId); q.bindString(3, elenMethod); q.bindString(4, SQLITE_DBI_ASSEMBLY_READ_COMPRESSION_METHOD_NO_COMPRESSION); q.execute(); SAFE_POINT_OP(os,); AssemblyAdapter* a = getAdapter(assembly.id, os); SAFE_POINT_OP(os,); a->createReadsTables(os); SAFE_POINT_OP(os,); if (it != NULL) { addReads(a, it, importInfo, os); SAFE_POINT_OP(os,); } a->createReadsIndexes(os); SAFE_POINT_OP(os,); } void SQLiteAssemblyDbi::updateAssemblyObject(const U2Assembly& assembly, U2OpStatus& os) { SQLiteTransaction(db, os); SQLiteQuery q1("UPDATE Assembly SET reference = ?1 WHERE object = ?2", db, os); q1.bindDataId(1, assembly.referenceId); q1.bindDataId(2, assembly.id); q1.execute(); SQLiteQuery q2("UPDATE Object SET version = version + 1 WHERE id = ?2", db, os); q2.bindDataId(1, assembly.id); q2.execute(); } void SQLiteAssemblyDbi::removeReads(const U2DataId& assemblyId, const QList& rowIds, U2OpStatus& os){ AssemblyAdapter* a = getAdapter(assemblyId, os); if ( a != NULL ) { a->removeReads(rowIds, os); } } void SQLiteAssemblyDbi::addReads(AssemblyAdapter* a, U2DbiIterator* it, U2AssemblyReadsImportInfo& ii, U2OpStatus& os) { GTIMER(c2, t2, "SQLiteAssemblyDbi::addReads"); quint64 t0 = GTimer::currentTimeMicros(); a->addReads(it, ii, os); t2.stop(); perfLog.trace(QString("Assembly: %1 reads added in %2 seconds. Auto-packing: %3") .arg(ii.nReads).arg((GTimer::currentTimeMicros() - t0) / float(1000*1000)).arg(ii.packStat.readsCount > 0 ? "yes" : "no")); } void SQLiteAssemblyDbi::addReads(const U2DataId& assemblyId, U2DbiIterator* it, U2OpStatus& os) { AssemblyAdapter* a = getAdapter(assemblyId, os); if ( a != NULL ) { U2AssemblyReadsImportInfo ii; addReads(a, it, ii, os); } } /** Packs assembly rows: assigns packedViewRow value for every read in assembly */ void SQLiteAssemblyDbi::pack(const U2DataId& assemblyId, U2AssemblyPackStat& stat, U2OpStatus& os) { GTIMER(c2, t2, "SQLiteAssemblyDbi::pack"); quint64 t0 = GTimer::currentTimeMicros(); AssemblyAdapter* a = getAdapter(assemblyId, os); if ( a == NULL ) { return; } stat.readsCount = a->countReads(U2_ASSEMBLY_REGION_MAX, os); a->pack(stat, os); perfLog.trace(QString("Assembly: full pack time: %1 seconds").arg((GTimer::currentTimeMicros() - t0) / float(1000*1000))); } void SQLiteAssemblyDbi::calculateCoverage(const U2DataId& assemblyId, const U2Region& region, U2AssemblyCoverageStat& c, U2OpStatus& os) { GCOUNTER(c1, t1, "SQLiteAssemblyDbi::calculateCoverage"); GTIMER(c2, t2, "SQLiteAssemblyDbi::calculateCoverage"); quint64 t0 = GTimer::currentTimeMicros(); AssemblyAdapter* a = getAdapter(assemblyId, os); if ( a == NULL ) { return; } a->calculateCoverage(region, c, os); perfLog.trace(QString("Assembly: full coverage calculation time: %1 seconds").arg((GTimer::currentTimeMicros() - t0) / float(1000*1000))); } ////////////////////////////////////////////////////////////////////////// // AssemblyAdapter AssemblyAdapter::AssemblyAdapter(const U2DataId& _assemblyId, const AssemblyCompressor* _compressor, DbRef* _db) :assemblyId(_assemblyId), compressor(_compressor), db(_db) { } ////////////////////////////////////////////////////////////////////////// // SQLiteAssemblyUtils QByteArray SQLiteAssemblyUtils::packData(SQLiteAssemblyDataMethod method, const QByteArray& name, const QByteArray& seq, const QByteArray& cigarText, const QByteArray& qualityString, U2OpStatus& os) { assert(method == SQLiteAssemblyDataMethod_NSCQ); if (method != SQLiteAssemblyDataMethod_NSCQ) { os.setError(SQLiteL10N::tr("Packing method is not supported: %1").arg(method)); return QByteArray(); } int nBytes = 1 + name.length() + 1 + seq.length() + 1 + cigarText.length() + 1 + qualityString.length(); #if QT_VERSION >= QT_VERSION_CHECK(4, 7, 0) QByteArray res(nBytes, Qt::Uninitialized); #else QByteArray res(nBytes, char(0)); #endif char* data = res.data(); int pos = 0; // packing type data[pos] = '0'; pos++; // name qMemCopy(data + pos, name.constData(), name.length()); pos+=name.length(); data[pos] = '\n'; pos++; // sequence qMemCopy(data + pos, seq.constData(), seq.length()); pos+=seq.length(); data[pos] = '\n'; pos++; // cigar qMemCopy(data + pos, cigarText.constData(), cigarText.length()); pos+=cigarText.length(); data[pos] = '\n'; pos++; // quality qMemCopy(data + pos, qualityString.constData(), qualityString.length()); //#define _SQLITE_CHECK_ASSEMBLY_DATA_PACKING_ #ifdef _SQLITE_CHECK_ASSEMBLY_DATA_PACKING_ QByteArray n, s, c, q; unpackData(res, n, s, c, q, os); assert(n == name); assert(s == seq); assert(c == cigarText); assert(q == qualityString); #endif return res; } void SQLiteAssemblyUtils::unpackData(const QByteArray& packedData, QByteArray& name, QByteArray& sequence, QByteArray& cigarText, QByteArray& qualityString, U2OpStatus& os) { if (packedData.isEmpty()) { os.setError(SQLiteL10N::tr("Packed data is empty!")); return; } const char* data = packedData.constData(); if (data[0] != '0') { os.setError(SQLiteL10N::tr("Packing method prefix is not supported: %1").arg(data)); return; } int nameStart = 1; int nameEnd = packedData.indexOf('\n', nameStart); if (nameEnd == -1) { os.setError(SQLiteL10N::tr("Data is corrupted, no name end marker found: %1").arg(data)); return; } name.append(QByteArray(data + nameStart, nameEnd - nameStart)); int sequenceStart = nameEnd + 1; int sequenceEnd = packedData.indexOf('\n', sequenceStart); if (sequenceEnd == -1) { os.setError(SQLiteL10N::tr("Data is corrupted, no sequence end marker found: %1").arg(data)); return; } sequence.append(data + sequenceStart, sequenceEnd - sequenceStart); int cigarStart = sequenceEnd + 1; int cigarEnd = packedData.indexOf('\n', cigarStart); if (sequenceEnd == -1) { os.setError(SQLiteL10N::tr("Data is corrupted, no CIGAR end marker found: %1").arg(data)); return; } cigarText.append(data + cigarStart, cigarEnd - cigarStart); int qualityStart = cigarEnd + 1; if (qualityStart < packedData.length()) { qualityString.append(data + qualityStart, packedData.length() - qualityStart); } } void SQLiteAssemblyUtils::calculateCoverage(SQLiteQuery& q, const U2Region& r, U2AssemblyCoverageStat& c, U2OpStatus& os) { int csize = c.coverage.size(); SAFE_POINT(csize > 0, "illegal coverage vector size!", ); U2Range* cdata = c.coverage.data(); double basesPerRange = double(r.length) / csize; while (q.step() && !os.isCoR()) { qint64 startPos = q.getInt64(0); qint64 len = q.getInt64(1); U2Region readRegion(startPos, len); U2Region readCroppedRegion = readRegion.intersect(r); if (readCroppedRegion.isEmpty()) { continue; } int firstCoverageIdx = (int)((readCroppedRegion.startPos - r.startPos)/ basesPerRange); int lastCoverageIdx = (int)((readCroppedRegion.startPos + readCroppedRegion.length - 1 - r.startPos ) / basesPerRange); for (int i = firstCoverageIdx; i <= lastCoverageIdx && i < csize; i++) { cdata[i].minValue++; cdata[i].maxValue++; } } } #define MAX_COVERAGE_VECTOR_SIZE (1000*1000) static void remapCoverage(U2AssemblyReadsImportInfo& ii, int newSize, int newBasesPerPoint) { int oldSize = ii.coverage.coverage.size(); SAFE_POINT(oldSize < newSize, "Invalid new coverage vector size!",); SAFE_POINT(ii.coverageBasesPerPoint <= newBasesPerPoint, "Invalid new coverage bases per point value!",); SAFE_POINT(newSize < MAX_COVERAGE_VECTOR_SIZE, "New coverage vector size is too large", ); ii.coverage.coverage.resize(newSize); if (ii.coverageBasesPerPoint == newBasesPerPoint || oldSize == 0) { return; } //remap int nPointsToMerge = newBasesPerPoint / ii.coverageBasesPerPoint; U2Range* data = ii.coverage.coverage.data(); int oldSizeInNewVector = oldSize / nPointsToMerge; int oldI = 0; for (int i = 0; i < oldSizeInNewVector; i++) { U2Range res = data[oldI]; for (int oldEnd = oldI + nPointsToMerge; ++oldI < oldEnd;) { U2Range oldVal = data[oldI]; res = res + oldVal; } data[i] = res; } qFill(data + oldSizeInNewVector, data + oldSize, U2Range()); } void SQLiteAssemblyUtils::addToCoverage(U2AssemblyReadsImportInfo& ii, const U2AssemblyRead& read) { if (!ii.computeCoverage) { return; } int csize = ii.coverage.coverage.size(); int basesPerPoint = qMax(1, ii.coverageBasesPerPoint); int endPos = (read->leftmostPos + read->effectiveLen) / basesPerPoint; if (endPos >= csize) { // resize and remap coverage info int newCSize = ii.maxEndPosHint > 0 ? ii.maxEndPosHint : endPos * 2; while (newCSize > MAX_COVERAGE_VECTOR_SIZE) { basesPerPoint*=2; if (newCSize/2 == MAX_COVERAGE_VECTOR_SIZE) { newCSize = MAX_COVERAGE_VECTOR_SIZE; break; } newCSize/=2; } remapCoverage(ii, newCSize, basesPerPoint); endPos = (read->leftmostPos + read->effectiveLen) / basesPerPoint; ii.coverageBasesPerPoint = basesPerPoint; } int startPos = read->leftmostPos / basesPerPoint; U2Range* coverageData = ii.coverage.coverage.data(); for (int i = startPos; i <= endPos; i++) { coverageData[i].minValue++; coverageData[i].maxValue++; } } ////////////////////////////////////////////////////////////////////////// // read loader U2AssemblyRead SimpleAssemblyReadLoader::load(SQLiteQuery* q) { U2AssemblyRead read(new U2AssemblyReadData()); read->id = q->getDataId(0, U2Type::AssemblyRead); read->packedViewRow = q->getInt64(1); if (q->hasError()) { return U2AssemblyRead(); } read->leftmostPos= q->getInt64(2); read->effectiveLen = q->getInt64(3); read->flags = q->getInt64(4); read->mappingQuality = (quint8)q->getInt32(5); QByteArray data = q->getBlob(6); if (q->hasError()) { return U2AssemblyRead(); } QByteArray cigarText; SQLiteAssemblyUtils::unpackData(data, read->name, read->readSequence, cigarText, read->quality, q->getOpStatus()); if (q->hasError()) { return U2AssemblyRead(); } QString err; read->cigar = U2AssemblyUtils::parseCigar(cigarText, err); if (!err.isEmpty()) { q->setError(err); return U2AssemblyRead(); } #ifdef _DEBUG //additional check to ensure that db stores correct info qint64 effectiveLengthFromCigar = read->readSequence.length() + U2AssemblyUtils::getCigarExtraLength(read->cigar); assert(effectiveLengthFromCigar == read->effectiveLen); #endif return read; } PackAlgorithmData SimpleAssemblyReadPackedDataLoader::load(SQLiteQuery* q) { PackAlgorithmData data; data.readId = q->getDataId(0, U2Type::AssemblyRead); data.leftmostPos = q->getInt64(1); data.effectiveLen = q->getInt64(2); return data; } } //namespace ugene-1.9.8/src/plugins/dbi_sqlite/src/SQLiteAssemblyDbi.h0000644000175000017500000001707411651544322022135 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_SQLITE_ASSEMBLY_DBI_H_ #define _U2_SQLITE_ASSEMBLY_DBI_H_ #include "SQLiteDbi.h" #include #include "assembly/AssemblyPackAlgorithm.h" namespace U2 { class SQLiteQuery; class AssemblyAdapter; class SQLiteAssemblyDbi : public U2AssemblyDbi, public SQLiteChildDBICommon { public: SQLiteAssemblyDbi(SQLiteDbi* dbi); ~SQLiteAssemblyDbi(); /** Reads assembly objects by id */ virtual U2Assembly getAssemblyObject(const U2DataId& assemblyId, U2OpStatus& os); /** Return number of reads in assembly that intersect given region 'Intersect' here means that region(leftmost pos, rightmost pos) intersects with 'r' */ virtual qint64 countReads(const U2DataId& assemblyId, const U2Region& r, U2OpStatus& os); /** Return reads that intersect given region Note: iterator instance must be deallocated by caller method */ virtual U2DbiIterator* getReads(const U2DataId& assemblyId, const U2Region& r, U2OpStatus& os); /** Return reads with packed row value >= min, <= max that intersect given region Note: iterator instance must be deallocated by caller method */ virtual U2DbiIterator* getReadsByRow(const U2DataId& assemblyId, const U2Region& r, qint64 minRow, qint64 maxRow, U2OpStatus& os); /** Return reads with a specified name. Used to find paired reads that must have equal names Note: iterator instance must be deallocated by caller method */ virtual U2DbiIterator* getReadsByName(const U2DataId& assemblyId, const QByteArray& name, U2OpStatus& os); /** Return max packed row at the given coordinate 'Intersect' here means that region(leftmost pos, rightmost pos) intersects with 'r' */ virtual qint64 getMaxPackedRow(const U2DataId& assemblyId, const U2Region& r, U2OpStatus& os); /** Count 'length of assembly' - position of the rightmost base of all reads */ virtual qint64 getMaxEndPos(const U2DataId& assemblyId, U2OpStatus& os); /** Creates new empty assembly object. Reads iterator can be NULL Requires: U2DbiFeature_WriteAssembly feature support */ virtual void createAssemblyObject(U2Assembly& assembly, const QString& folder, U2DbiIterator* it, U2AssemblyReadsImportInfo& ii, U2OpStatus& os); /** Updates assembly object fields Requires: U2DbiFeature_WriteAssembly feature support */ virtual void updateAssemblyObject(const U2Assembly&, U2OpStatus& os); /** Removes sequences from assembly Automatically removes affected sequences that are not anymore accessible from folders */ virtual void removeReads(const U2DataId& assemblyId, const QList& rowIds, U2OpStatus& os); /** Adds sequences to assembly Reads got their ids assigned. */ virtual void addReads(const U2DataId& assemblyId, U2DbiIterator* it, U2OpStatus& os); /** Packs assembly rows: assigns packedViewRow value for every read in assembly */ virtual void pack(const U2DataId& assemblyId, U2AssemblyPackStat& stat, U2OpStatus& os); /** Calculates coverage information for the given region. Saves result to 'c.coverage' vector. Note: Coverage window size depends on 'c.coverage' vector size passed to the method call. */ virtual void calculateCoverage(const U2DataId& assemblyId, const U2Region& region, U2AssemblyCoverageStat& c, U2OpStatus& os); virtual void initSqlSchema(U2OpStatus& os); virtual void shutdown(U2OpStatus& os); private: virtual void addReads(AssemblyAdapter* a, U2DbiIterator* it, U2AssemblyReadsImportInfo& ii, U2OpStatus& os); /** Return assembly storage adapter for the given assembly */ AssemblyAdapter* getAdapter(const U2DataId& assemblyId, U2OpStatus& os); /** Adapters by database assembly id */ QHash adaptersById; }; // reserved for future use; class AssemblyCompressor { }; class AssemblyAdapter { public: AssemblyAdapter(const U2DataId& assemblyId, const AssemblyCompressor* compressor, DbRef* ref); virtual void createReadsTables(U2OpStatus& ) {}; virtual void createReadsIndexes(U2OpStatus& ) {}; virtual void shutdown(U2OpStatus& ) {}; virtual qint64 countReads(const U2Region& r, U2OpStatus& os) = 0; virtual qint64 getMaxPackedRow(const U2Region& r, U2OpStatus& os) = 0; virtual qint64 getMaxEndPos(U2OpStatus& os) = 0; virtual U2DbiIterator* getReads(const U2Region& r, U2OpStatus& os) = 0; virtual U2DbiIterator* getReadsByRow(const U2Region& r, qint64 minRow, qint64 maxRow, U2OpStatus& os) = 0; virtual U2DbiIterator* getReadsByName(const QByteArray& name, U2OpStatus& os) = 0; virtual void addReads(U2DbiIterator* it, U2AssemblyReadsImportInfo& ii, U2OpStatus& os) = 0; virtual void removeReads(const QList& rowIds, U2OpStatus& os) = 0; virtual void pack(U2AssemblyPackStat& stat, U2OpStatus& os) = 0; virtual void calculateCoverage(const U2Region& region, U2AssemblyCoverageStat& c, U2OpStatus& os) = 0; protected: U2DataId assemblyId; const AssemblyCompressor* compressor; DbRef* db; }; /** Compression method for assembly data */ enum SQLiteAssemblyDataMethod { /** Merges Name, Sequence, Cigar and Quality values into single byte array separated by '\n' character. Merge prefix is '0'*/ SQLiteAssemblyDataMethod_NSCQ = 1 }; class SQLiteAssemblyUtils { public: static QByteArray packData(SQLiteAssemblyDataMethod method, const QByteArray& name, const QByteArray& seq, const QByteArray& cigarText, const QByteArray& qualityString, U2OpStatus& os); static void unpackData(const QByteArray& packed, QByteArray& name, QByteArray& sequence, QByteArray& cigarText, QByteArray& qualityString, U2OpStatus& os); static void calculateCoverage(SQLiteQuery& q, const U2Region& r, U2AssemblyCoverageStat& c, U2OpStatus& os); static void addToCoverage(U2AssemblyReadsImportInfo& ii, const U2AssemblyRead& read); }; class SQLiteAssemblyNameFilter : public SqlRSFilter { public: SQLiteAssemblyNameFilter(const QByteArray& expectedName) : name (expectedName) {} virtual bool filter(const U2AssemblyRead& r) {return name == r->name;} protected: QByteArray name; }; class SimpleAssemblyReadLoader: public SqlRSLoader { public: U2AssemblyRead load(SQLiteQuery* q); }; class SimpleAssemblyReadPackedDataLoader : public SqlRSLoader { public: virtual PackAlgorithmData load(SQLiteQuery* q); }; } //namespace #endif ugene-1.9.8/src/plugins/dbi_sqlite/src/SQLiteMsaDbi.h0000644000175000017500000000603211651544322021066 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_SQLITE_MSA_DBI_H_ #define _U2_SQLITE_MSA_DBI_H_ #include "SQLiteDbi.h" #include namespace U2 { class SQLiteMsaRDbi : public U2SimpleMsaDbi, public SQLiteChildDBICommon { public: SQLiteMsaRDbi(SQLiteDbi* dbi); /** Reads Msa objects by id */ virtual U2Msa getMsaObject(const U2DataId& id, U2OpStatus& os); /** Returns region of Msa rows. Total number of MSA rows is equal to number of sequences in MSA */ virtual QList getRows(const U2DataId& msaId, qint32 firstRow, qint32 numRows, U2OpStatus& os); /** Returns number of sequences in MSA*/ virtual qint64 getSequencesCount(const U2DataId& msaId, U2OpStatus& os); /** Return number of sequences in alignment that intersect given coord 'Intersect' here means that first non gap character is <= coord <= last non gap character */ virtual qint32 countSequencesAt(const U2DataId& msaId, qint64 coord, U2OpStatus& os); /** Return 'count' sequences starting with 'offset' that intersect given coordinate */ virtual QList getSequencesAt(const U2DataId& msaId, qint64 coord, qint32 offset, qint32 count, U2OpStatus& os); /** Return number of sequences in alignment that intersect given region 'Intersect' here means that first non gap character is <= coord <= last non gap character */ virtual qint32 countSequencesAt(const U2DataId& msaId, const U2Region& r, U2OpStatus& os); /** Return 'count' sequences starting with 'offset' that intersect given region */ virtual QList getSequencesAt(const U2DataId& msaId, const U2Region& r, qint32 offset, qint32 count, U2OpStatus& os); /** Return number of sequences in alignment that that have non-gap character at the given coord */ virtual qint32 countSequencesWithoutGapAt(const U2DataId& msaId, qint64 coord, U2OpStatus& os); /** Return 'count' sequences starting with 'offset' alignment that that have non-gap character at the given coord */ virtual QList getSequencesWithoutGapAt(const U2DataId& msaId, qint64 coord, qint32 offset, qint32 count, U2OpStatus& os); virtual void initSqlSchema(U2OpStatus& os); }; } //namespace #endif ugene-1.9.8/src/plugins/dbi_sqlite/src/SQLiteAttributeDbi.h0000644000175000017500000001020211651544322022303 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_SQLITE_ATTRIBUTE_DBI_H_ #define _U2_SQLITE_ATTRIBUTE_DBI_H_ #include "SQLiteDbi.h" namespace U2 { class SQLiteQuery; class SQLiteAttributeDbi : public U2AttributeDbi, public SQLiteChildDBICommon { public: SQLiteAttributeDbi(SQLiteDbi* dbi); /** Returns all attribute names available in the database */ virtual QStringList getAvailableAttributeNames(U2OpStatus& os); /** Returns all attribute ids for the given object */ virtual QList getObjectAttributes(const U2DataId& objectId, const QString& name, U2OpStatus& os); /** Returns all attribute ids for the given object */ virtual QList getObjectPairAttributes(const U2DataId& objectId, const U2DataId& childId, const QString& name, U2OpStatus& os); /** Loads int64 attribute by id */ virtual U2IntegerAttribute getIntegerAttribute(const U2DataId& attributeId, U2OpStatus& os); /** Loads real64 attribute by id */ virtual U2RealAttribute getRealAttribute(const U2DataId& attributeId, U2OpStatus& os); /** Loads String attribute by id */ virtual U2StringAttribute getStringAttribute(const U2DataId& attributeId, U2OpStatus& os); /** Loads byte attribute by id */ virtual U2ByteArrayAttribute getByteArrayAttribute(const U2DataId& attributeId, U2OpStatus& os); /** Sorts all objects in database according to U2DbiSortConfig provided */ virtual QList sort(const U2DbiSortConfig& sc, qint64 offset, qint64 count, U2OpStatus& os); /** Removes attributes from database Requires U2DbiFeature_WriteAttribute feature support */ virtual void removeAttributes(const QList& attributeIds, U2OpStatus& os); /** Removes all attributes associated with the object Requires U2DbiFeature_WriteAttribute feature support */ virtual void removeObjectAttributes(const U2DataId& objectId, U2OpStatus& os); /** Creates int64 attribute in database. ObjectId must be already set in attribute and present in the same database Requires U2DbiFeature_WriteAttribute feature support */ virtual void createIntegerAttribute(U2IntegerAttribute& a, U2OpStatus& os); /** Creates real64 attribute in database. ObjectId must be already set in attribute and present in the same database Requires U2DbiFeature_WriteAttribute feature support */ virtual void createRealAttribute(U2RealAttribute& a, U2OpStatus& os); /** Creates String attribute in database. ObjectId must be already set in attribute and present in the same database Requires U2DbiFeature_WriteAttribute feature support */ virtual void createStringAttribute(U2StringAttribute& a, U2OpStatus& os); /** Creates Byte attribute in database. ObjectId must be already set in attribute and present in the same database Requires U2DbiFeature_WriteAttribute feature support */ virtual void createByteArrayAttribute(U2ByteArrayAttribute& a, U2OpStatus& os); virtual void initSqlSchema(U2OpStatus& os); private: qint64 createAttribute(U2Attribute& attr, U2DataType type, U2OpStatus& os); QString buildSelectAttributeQuery(const QString& attributeTable); void readAttribute(SQLiteQuery& q, U2Attribute& attr); }; } //namespace #endif ugene-1.9.8/src/plugins/dbi_sqlite/src/SQLiteObjectDbi.h0000644000175000017500000002012211651544322021550 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_SQLITE_OBJECT_DBI_H_ #define _U2_SQLITE_OBJECT_DBI_H_ #include "SQLiteDbi.h" namespace U2 { class SQLiteObjectDbi : public U2ObjectDbi, public SQLiteChildDBICommon { public: SQLiteObjectDbi(SQLiteDbi* dbi); // Read methods for objects /** Returns number of top-level U2Objects in database */ virtual qint64 countObjects(U2OpStatus& os); /** Returns number of top-level U2Objects with the specified type in database */ virtual qint64 countObjects(U2DataType type, U2OpStatus& os); /** Lists database top-level objects, starts with 'offset' and limits by 'count' */ virtual QList getObjects(qint64 offset, qint64 count, U2OpStatus& os); /** Lists database top-level objects of the specified type, starts with 'offset' and limits by 'count' */ virtual QList getObjects(U2DataType type, qint64 offset, qint64 count, U2OpStatus& os); /** Returns parents for entity. If entity is object, returns other object this object is a part of If object is not a part of any other object and does not belongs to any folder - it's automatically removed. */ virtual QList getParents(const U2DataId& entityId, U2OpStatus& os); // Read methods for folders /** Returns list of folders stored in database. Folders are separated by '/' character. At least one root folder is required. */ virtual QStringList getFolders(U2OpStatus& os); /** Returns number of top-level U2Objects in folder */ virtual qint64 countObjects(const QString& folder, U2OpStatus& os); /** Lists database top-level objects of the specified type, starts with 'offset' and limits by 'count' */ virtual QList getObjects(const QString& folder, qint64 offset, qint64 count, U2OpStatus& os); /** Returns all folders this object must be shown in */ virtual QStringList getObjectFolders(const U2DataId& objectId, U2OpStatus& os); // Write methods for objects /** Removes object from the specified folder. If folder is empty - removes object from all folders. Note: the object & all related data is automatically removed from database when object is not placed in any folder or is not a part of any other more complex object (ex: sequence in msa) */ virtual void removeObject(const U2DataId& dataId, const QString& folder, U2OpStatus& os); /** Removes collection of objects from the specified folder. If folder is empty - removes object from all folders. Note: the object & all related data is automatically removed from database when object is not placed in any folder or is not a part of any other more complex object (ex: sequence in msa) */ virtual void removeObjects(const QList& dataIds, const QString& folder, U2OpStatus& os); // Write methods for folders /** Creates folder in the database. The specified path must be a valid unique path, not existing in the database. It is not required that parent folders must exist, they are created automatically. */ virtual void createFolder(const QString& path, U2OpStatus& os); /** Removes folder. The folder must be existing path. Runs GC check for all objects in the folder */ virtual void removeFolder(const QString& folder, U2OpStatus& os); /** Returns version of the folder. The folder version increases if new object(s)/subfolder(s) are added into this folder Note that if object(s)/folder(s) are added into one of the subfolders the folder version is not changed */ virtual qint64 getFolderLocalVersion(const QString& folder, U2OpStatus& os); /** Returns version of the folder that changes every time object(s)/folder(s) added to the specified folder or any of its child folders */ virtual qint64 getFolderGlobalVersion(const QString& folder, U2OpStatus& os); /** Adds objects to the specified folder. All objects must exist and have a top-level type.*/ virtual void addObjectsToFolder(const QList& objectIds, const QString& toFolder, U2OpStatus& os); /** Moves objects between folders. 'fromFolder' must be existing path containing all specified objects. 'toFolder' must be existing path or empty string. If 'toFolder' is empty, removes the objects from 'fromFolder' and deletes non-top-level objects without parents, if any appear in the specified list. Otherwise, moves the specified objects between the specified folders, omitting duplicates. */ virtual void moveObjects(const QList& objectIds, const QString& fromFolder, const QString& toFolder, U2OpStatus& os); ////////////////////////////////////////////////////////////////////////// // Helper methods /** Creates new object of the specified type. Puts it into the 'folder' Returns result object data id */ static U2DataId createObject(U2DataType type, const QString& folder, const QString& objectName, SQLiteDbiObjectRank rank, DbRef* db, U2OpStatus& os); /** Returns internal database folder id Fails if folder not found and 'mustExist' == true */ static qint64 getFolderId(const QString& path, bool mustExist, DbRef* db, U2OpStatus& os); /** Increment object version count */ static void incrementVersion(const U2DataId& id, DbRef* db, U2OpStatus& os); /** Returns version of the given object */ virtual qint64 getObjectVersion(const U2DataId& objectId, U2OpStatus& os); /** Removes objects parent relation. If child object has no parents and is not top level it will be automatically removed if 'removeDeadChild' is true */ void removeParent(const U2DataId& parentId, const U2DataId& childId, bool removeDeadChild, U2OpStatus& os); /** Ensures that corresponding parent record exists in db. Adds record if not exists */ void ensureParent(const U2DataId& parentId, const U2DataId& childId, U2OpStatus& os); virtual void initSqlSchema(U2OpStatus& os); private: /** Removes object from database, returns 'true' if object is completely erased */ bool removeObjectImpl(const U2DataId& id, const QString& folder, U2OpStatus& os); void removeObjectAttributes(const U2DataId& id, U2OpStatus& os); /** Updates versions */ void onFolderUpdated(const QString& folder); }; class SQLiteCrossDatabaseReferenceDbi : public U2CrossDatabaseReferenceDbi, public SQLiteChildDBICommon { public: SQLiteCrossDatabaseReferenceDbi(SQLiteDbi* dbi); /** Adds new remote object to database. Sets local object id assigned to the new value Requires: U2DbiFeature_WriteCrossDatabaseReferences */ virtual void createCrossReference(U2CrossDatabaseReference& reference, U2OpStatus& os); /** Loads remote object information from DB Requires: U2DbiFeature_ReadCrossDatabaseReferences */ virtual U2CrossDatabaseReference getCrossReference(const U2DataId& objectId, U2OpStatus& os); /** Updates all fields of cross database reference object Requires: U2DbiFeature_WriteCrossDatabaseReferences */ virtual void updateCrossReference(const U2CrossDatabaseReference& reference, U2OpStatus& os); virtual void initSqlSchema(U2OpStatus& os); }; } //namespace #endif ugene-1.9.8/src/plugins/dbi_sqlite/src/SQLiteObjectDbi.cpp0000644000175000017500000004341311651544322022113 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "SQLiteObjectDbi.h" #include #include namespace U2 { SQLiteObjectDbi::SQLiteObjectDbi(SQLiteDbi* dbi) : U2ObjectDbi(dbi), SQLiteChildDBICommon(dbi) { } void SQLiteObjectDbi::initSqlSchema(U2OpStatus& os) { if (os.hasError()) { return; } // objects table - stores IDs and types for all objects. It also stores 'top_level' flag to simplify queries // rank: see SQLiteDbiObjectRank // name is a visual name of the object shown to user. SQLiteQuery("CREATE TABLE Object (id INTEGER PRIMARY KEY AUTOINCREMENT, type INTEGER NOT NULL, " "version INTEGER NOT NULL DEFAULT 1, rank INTEGER NOT NULL, name TEXT NOT NULL)", db, os).execute(); // parent-child object relation SQLiteQuery("CREATE TABLE Parent (parent INTEGER, child INTEGER, " "FOREIGN KEY(parent) REFERENCES Object(id), " "FOREIGN KEY(child) REFERENCES Object(id) )", db, os).execute(); // folders SQLiteQuery("CREATE TABLE Folder (id INTEGER PRIMARY KEY AUTOINCREMENT, path TEXT UNIQUE NOT NULL, " "vlocal INTEGER NOT NULL DEFAULT 1, vglobal INTEGER NOT NULL DEFAULT 1 )", db, os).execute(); // folder-object relation SQLiteQuery("CREATE TABLE FolderContent (folder INTEGER, object INTEGER, " "FOREIGN KEY(folder) REFERENCES Folder(id)," "FOREIGN KEY(object) REFERENCES Object(id) )", db, os).execute(); } ////////////////////////////////////////////////////////////////////////// // Read methods for objects #define TOP_LEVEL_FILTER ("rank = " + QString::number(SQLiteDbiObjectRank_TopLevel)) qint64 SQLiteObjectDbi::countObjects(U2OpStatus& os) { return SQLiteQuery("COUNT (*) FROM Object WHERE " + TOP_LEVEL_FILTER, db, os).selectInt64(); } qint64 SQLiteObjectDbi::countObjects(U2DataType type, U2OpStatus& os) { SQLiteQuery q("COUNT (*) FROM Object WHERE " + TOP_LEVEL_FILTER + " AND type = ?1", db, os); q.bindType(1, type); return q.selectInt64(); } QList SQLiteObjectDbi::getObjects(qint64 offset, qint64 count, U2OpStatus& os) { return SQLiteQuery("SELECT id, type FROM Object WHERE " + TOP_LEVEL_FILTER, offset, count, db, os).selectDataIdsExt(); } QList SQLiteObjectDbi::getObjects(U2DataType type, qint64 offset, qint64 count, U2OpStatus& os) { SQLiteQuery q("SELECT id, type FROM Object WHERE " + TOP_LEVEL_FILTER + " AND type = ?1", offset, count, db, os ); q.bindType(1, type); return q.selectDataIdsExt(); } QList SQLiteObjectDbi::getParents(const U2DataId& entityId, U2OpStatus& os) { SQLiteQuery q("SELECT o.id AS id, o.type AS type FROM Parent AS p, Object AS o WHERE p.child = ?1 and p.parent = o.id", db, os); q.bindDataId(1, entityId); return q.selectDataIdsExt(); } ////////////////////////////////////////////////////////////////////////// // Write methods for objects void SQLiteObjectDbi::removeObject(const U2DataId& dataId, const QString& folder, U2OpStatus& os) { removeObjectImpl(dataId, folder, os); if (os.hasError()) { return; } onFolderUpdated(folder); } void SQLiteObjectDbi::removeObjects(const QList& dataIds, const QString& folder, U2OpStatus& os) { foreach (U2DataId id, dataIds) { removeObjectImpl(id, folder, os); if (os.hasError()) { break; } } onFolderUpdated(folder); } bool SQLiteObjectDbi::removeObjectImpl(const U2DataId& objectId, const QString& folder, U2OpStatus& os) { SQLiteTransaction trans(db, os); U2DataType type = getRootDbi()->getEntityTypeById(objectId); if (!U2Type::isObjectType(type)) { os.setError(SQLiteL10N::tr("Not an object! Id: %1, type: %2").arg(SQLiteUtils::text(objectId)).arg(type)); return false; } qint64 folderId = SQLiteQuery("SELECT id FROM Folder WHERE path = '"+folder+"'", db, os).selectInt64(); if (os.hasError()) { return false; } SQLiteQuery deleteQ("DELETE FROM FolderContent WHERE folder = ?1 AND object = ?2", db, os); deleteQ.bindInt64(1, folderId); deleteQ.bindDataId(2, objectId); int nRecords = deleteQ.update(); if (os.hasError()) { return false; } if (nRecords == 0) { os.setError(SQLiteL10N::tr("Object: %1 not found in folder: %2").arg(SQLiteUtils::text(objectId)).arg(folder)); return false; } QStringList folders = getObjectFolders(objectId, os); if (os.hasError()) { return false; } if (!folders.isEmpty()) { // object is a part of another folder -> do not erase return false; } QList parents = getParents(objectId, os); if (os.hasError()) { return false; } if (parents.isEmpty()) { // object is a part of another object -> do not erase //update top_level flag! SQLiteQuery toplevelQ("UPDATE Object SET rank = " + QString::number(SQLiteDbiObjectRank_Child) + " WHERE id = ?1", db, os); toplevelQ.bindDataId(1, objectId); toplevelQ.execute(); return false; } // now erase object // remove all attributes first removeObjectAttributes(objectId, os); if (os.hasError()) { return false; } switch (type) { case U2Type::Sequence: SQLiteUtils::remove("Sequence", "object", objectId, 1, db, os); SQLiteUtils::remove("SequenceData", "sequence", objectId, -1, db, os); break; case U2Type::Msa: //TODO: removeMsaObject(objectId); break; case U2Type::PhyTree: //TODO: removePhyTreeObject(objectId); break; case U2Type::Assembly: //TODO: removeAssemblyObject(objectId); break; case U2Type::CrossDatabaseReference: //TODO: removeCrossDatabaseReferenceObject(objectId.id); break; default: os.setError(SQLiteL10N::tr("Unknown object type! Id: %1, type: %2").arg(SQLiteUtils::text(objectId)).arg(type)); } if (os.hasError()) { return false; } SQLiteUtils::remove("Object", "id", objectId, 1, db, os); return !os.hasError(); } void SQLiteObjectDbi::removeObjectAttributes(const U2DataId& id, U2OpStatus& os) { U2AttributeDbi* attributeDbi = dbi->getAttributeDbi(); attributeDbi->removeObjectAttributes(id, os); } ////////////////////////////////////////////////////////////////////////// // Read methods for folders QStringList SQLiteObjectDbi::getFolders(U2OpStatus& os) { return SQLiteQuery("SELECT path FROM Folder ORDER BY path", db, os).selectStrings(); } qint64 SQLiteObjectDbi::countObjects(const QString& folder, U2OpStatus& os) { SQLiteQuery q("SELECT COUNT(fc.*) FROM FolderContent AS fc, Folder AS f WHERE f.path = ?1 AND fc.folder = f.id", db, os); q.bindString(1, folder); return q.selectInt64(); } QList SQLiteObjectDbi::getObjects(const QString& folder, qint64 , qint64 , U2OpStatus& os) { SQLiteQuery q("SELECT o.id, o.type FROM Object AS o, FolderContent AS fc, Folder AS f WHERE f.path = ?1 AND fc.folder = f.id AND fc.object=o.id", db, os); q.bindString(1, folder); return q.selectDataIdsExt(); } QStringList SQLiteObjectDbi::getObjectFolders(const U2DataId& objectId, U2OpStatus& os) { SQLiteQuery q("SELECT f.path FROM FolderContent AS fc, Folder AS f WHERE fc.object = ?1 AND fc.folder = f.id", db, os); q.bindDataId(1, objectId); return q.selectStrings(); } ////////////////////////////////////////////////////////////////////////// // Write methods for folders void SQLiteObjectDbi::createFolder(const QString& path, U2OpStatus& os) { //TODO: validate folder name SQLiteQuery q("INSERT INTO Folder(path) VALUES(?1)", db, os); q.bindString(1, path); q.execute(); if (!os.hasError()) { onFolderUpdated(path); } } void SQLiteObjectDbi::removeFolder(const QString& folder, U2OpStatus& os) { // remove subfolders first SQLiteQuery q("SELECT path FROM Folder WHERE path LIKE ?1", db, os); q.bindString(1, folder + "/%"); QStringList subfolders = q.selectStrings(); if (os.hasError()) { return; } subfolders.sort(); //remove innermost folders first for (int i = subfolders.length(); --i >= 0 && !os.hasError();) { const QString& subfolder = subfolders.at(i); removeFolder(subfolder, os); } if (os.hasError()) { return; } // remove all objects from folder qint64 nObjects = countObjects(folder, os); if (os.hasError()) { return; } int nObjectsPerIteration = 1000; for (int i = 0; i < nObjects; i += nObjectsPerIteration) { QList objects = getObjects(folder, i, nObjectsPerIteration, os); if (os.hasError()) { return; } // Remove all objects in the folder if (!objects.isEmpty()) { removeObjects(objects, folder, os); if (os.hasError()) { return; } } } // remove folder record SQLiteQuery dq("DELETE FROM Folder WHERE path = ?1", db, os); dq.bindString(1, folder); dq.execute(); if (os.hasError()) { return; } onFolderUpdated(folder); } void SQLiteObjectDbi::addObjectsToFolder(const QList& objectIds, const QString& folder, U2OpStatus& os) { qint64 folderId = getFolderId(folder, true, db, os); if (os.hasError()) { return; } QList addedObjects; SQLiteQuery countQ("SELECT count(object) FROM FolderContent WHERE folder = ?1", db, os); SQLiteQuery insertQ("INSERT INTO FolderContent(folder, object) VALUES(?1, ?2)", db, os); SQLiteQuery toplevelQ("UPDATE Object SET rank = " + QString::number(SQLiteDbiObjectRank_TopLevel) + " WHERE id = ?1", db, os); foreach(const U2DataId& objectId, objectIds) { countQ.reset(); countQ.bindInt64(1, folderId); int c = countQ.selectInt64(); if (c != 0) { continue; // object is already in folder, skip it } insertQ.reset(); insertQ.bindInt64(1, folderId); insertQ.bindDataId(2, objectId); insertQ.execute(); toplevelQ.reset(); toplevelQ.bindDataId(1, objectId); toplevelQ.execute(); if (os.hasError()) { break; } addedObjects.append(objectId); } onFolderUpdated(folder); } void SQLiteObjectDbi::moveObjects(const QList& objectIds, const QString& fromFolder, const QString& toFolder, U2OpStatus& os) { if (fromFolder == toFolder) { return; } if (!toFolder.isEmpty()) { addObjectsToFolder(objectIds, toFolder, os); if (os.hasError()) { return; } } removeObjects(objectIds, fromFolder, os); } void SQLiteObjectDbi::removeParent(const U2DataId& parentId, const U2DataId& childId, bool removeDeadChild, U2OpStatus& os) { SQLiteQuery q("DELETE FROM Parent WHERE parent = ?1 AND child = ?2", db, os); q.bindDataId(1, parentId); q.bindDataId(2, childId); /*qint64 res = */q.update(1); if (os.hasError()) { return; } if (!removeDeadChild) { return; } QList parents = getParents(childId, os); if (!parents.isEmpty() || os.hasError()) { return; } QList folders = getObjectFolders(childId, os); if (!folders.isEmpty() || os.hasError()) { return; } removeObjects(QList() << childId, "", os); } void SQLiteObjectDbi::ensureParent(const U2DataId& parentId, const U2DataId& childId, U2OpStatus& os) { SQLiteQuery checkQ("SELECT COUNT(*) FROM Parent WHERE parent = ?1 AND child = ?2", db, os); checkQ.bindDataId(1, parentId); checkQ.bindDataId(2, childId); if (checkQ.selectInt64() == 1) { return; } SQLiteQuery insertQ("INSERT INTO Parent (parent, child) VALUES (?1, ?2)", db, os); insertQ.bindDataId(1, parentId); insertQ.bindDataId(2, childId); insertQ.execute(); } ////////////////////////////////////////////////////////////////////////// // Helper methods void SQLiteObjectDbi::incrementVersion(const U2DataId& objectId, DbRef* db, U2OpStatus& os) { SQLiteQuery q("UPDATE Object SET version = version + 1 WHERE id = ?1", db, os); q.bindDataId(1, objectId); q.update(1); } qint64 SQLiteObjectDbi::getObjectVersion(const U2DataId& objectId, U2OpStatus& os) { SQLiteQuery q("SELECT version FROM Object WHERE id = ?1", db, os); q.bindDataId(1, objectId); return q.selectInt64(); } U2DataId SQLiteObjectDbi::createObject(U2DataType type, const QString& folder, const QString& vname, SQLiteDbiObjectRank rank, DbRef* db, U2OpStatus& os) { SQLiteQuery i1("INSERT INTO Object(type, rank, name) VALUES(?1, ?2, ?3)", db, os); i1.bindType(1, type); i1.bindInt32(2, rank); i1.bindString(3, vname); U2DataId res = i1.insert(type); if (os.hasError()) { return res; } if (folder.isEmpty()) { return res; } assert(rank == SQLiteDbiObjectRank_TopLevel); qint64 folderId = getFolderId(folder, true, db, os); if (os.hasError()) { return res; } SQLiteQuery i2("INSERT INTO FolderContent(folder, object) VALUES(?1, ?2)", db, os); i2.bindInt64(1, folderId); i2.bindDataId(2, res); i2.execute(); return res; } qint64 SQLiteObjectDbi::getFolderId(const QString& path, bool mustExist, DbRef* db, U2OpStatus& os) { SQLiteQuery q("SELECT id FROM Folder WHERE path = ?1", db, os); q.bindString(1, path); qint64 res = q.selectInt64(); if (os.hasError()) { return -1; } if (mustExist && res == -1) { os.setError(SQLiteL10N::tr("Folder not found :%1").arg(path)); } return res; } qint64 SQLiteObjectDbi::getFolderLocalVersion(const QString& folder, U2OpStatus& os) { SQLiteQuery q("SELECT vlocal FROM Folder WHERE path = ?1", db, os); q.bindString(1, folder); return q.selectInt64(); } qint64 SQLiteObjectDbi::getFolderGlobalVersion(const QString& folder, U2OpStatus& os) { SQLiteQuery q("SELECT vglobal FROM Folder WHERE path = ?1", db, os); q.bindString(1, folder); return q.selectInt64(); } void SQLiteObjectDbi::onFolderUpdated(const QString& ) { //TODO: update local version of the given folder & global for all parents } ////////////////////////////////////////////////////////////////////////// // cross references dbi SQLiteCrossDatabaseReferenceDbi::SQLiteCrossDatabaseReferenceDbi(SQLiteDbi* dbi) : U2CrossDatabaseReferenceDbi(dbi), SQLiteChildDBICommon(dbi) { } void SQLiteCrossDatabaseReferenceDbi::initSqlSchema(U2OpStatus& os) { if (os.hasError()) { return; } // cross database reference object // factory - remote dbi factory // dbi - remote dbi id (url) // rid - remote object id // version - remove object version SQLiteQuery("CREATE TABLE CrossDatabaseReference (object INTEGER, factory TEXT NOT NULL, dbi TEXT NOT NULL, " "rid BLOB NOT NULL, version INTEGER NOT NULL, " " FOREIGN KEY(object) REFERENCES Object(id) )", db, os).execute(); } void SQLiteCrossDatabaseReferenceDbi::createCrossReference(U2CrossDatabaseReference& reference, U2OpStatus& os) { reference.id = SQLiteObjectDbi::createObject(U2Type::Assembly, QString(), reference.visualName, SQLiteDbiObjectRank_TopLevel, db, os); if (os.hasError()) { return; } SQLiteQuery q("INSERT INTO CrossDatabaseReference(object, factory, dbi, rid, version) VALUES(?1, ?2, ?3, ?4, ?5)", db, os); q.bindDataId(1, reference.id); q.bindString(2, reference.dataRef.factoryId); q.bindString(3, reference.dataRef.dbiId); q.bindBlob(4, reference.dataRef.entityId); q.bindInt64(5, reference.dataRef.version); q.execute(); } U2CrossDatabaseReference SQLiteCrossDatabaseReferenceDbi::getCrossReference(const U2DataId& objectId, U2OpStatus& os) { U2CrossDatabaseReference res(objectId, dbi->getDbiId(), 0); SQLiteQuery q("SELECT r.factory, r.dbi, r.rid, r.version, o.name, o.version FROM CrossDatabaseReference AS r, Object AS o " " WHERE o.id = ?1 AND r.object = o.id", db, os); q.bindDataId(1, objectId); if (q.step()) { res.dataRef.factoryId = q.getString(0); res.dataRef.dbiId = q.getString(1); res.dataRef.entityId = q.getBlob(2); res.dataRef.version = q.getInt64(3); res.visualName = q.getString(4); res.version = q.getInt64(5); q.ensureDone(); } return res; } void SQLiteCrossDatabaseReferenceDbi::updateCrossReference(const U2CrossDatabaseReference& reference, U2OpStatus& os) { SQLiteQuery q("UPDATE CrossDatabaseReference SET factory = ?1, dbi = ?2, rid = ?3, version = ?4 WHERE object = ?5", db, os); q.bindString(1, reference.dataRef.factoryId); q.bindString(2, reference.dataRef.dbiId); q.bindBlob(3, reference.dataRef.entityId); q.bindInt64(4, reference.dataRef.version); q.bindDataId(5, reference.id); q.execute(); } } //namespace ugene-1.9.8/src/plugins/dbi_sqlite/src/assembly/0000755000175000017500000000000011651544322020312 5ustar ilyailyaugene-1.9.8/src/plugins/dbi_sqlite/src/assembly/RTreeAssemblyAdapter.cpp0000644000175000017500000002310511651544322025041 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "RTreeAssemblyAdapter.h" #include "../SQLiteDbi.h" #include "../SQLiteAssemblyDbi.h" #include "../SQLiteObjectDbi.h" #include #include namespace U2 { #define RANGE_CONDITION_CHECK QString(" (i.gstart < ?1 AND i.gend > ?2) ") #define ALL_READ_FIELDS QString(" r.id, i.prow1, i.gstart, i.gend - i.gstart, r.flags, r.mq, r.data") #define SAME_IDX QString(" (i.id == r.id) ") #define FROM_2TABLES QString(" FROM %1 AS r, %2 AS i ") RTreeAssemblyAdapter::RTreeAssemblyAdapter(SQLiteDbi* _dbi, const U2DataId& assemblyId, const AssemblyCompressor* compressor, DbRef* db, U2OpStatus& ) : AssemblyAdapter(assemblyId, compressor, db) { dbi = _dbi; readsTable = QString("AssemblyRead_R%1").arg(SQLiteUtils::toDbiId(assemblyId)); indexTable = readsTable + "_RTree"; } void RTreeAssemblyAdapter::createReadsTables(U2OpStatus& os) { // name - name hash // flags - flags // mq - mapping quality // data - compressed name/sequence/cigar/mapping static QString q1 = "CREATE TABLE %1 (id INTEGER PRIMARY KEY AUTOINCREMENT, name INTEGER NOT NULL, " "flags INTEGER NOT NULL, mq INTEGER NOT NULL, data BLOB NOT NULL)"; // gstart, gend - start and end read position // prow1, prow2 - packed view row. prow1 always the same as prow2 static QString q2 = "CREATE VIRTUAL TABLE %1 USING rtree_i32(id, gstart, gend, prow1, prow2)"; SQLiteQuery(q1.arg(readsTable), db, os).execute(); if (os.hasError()) { return; } SQLiteQuery(q2.arg(indexTable), db, os).execute(); if (os.hasError()) { coreLog.error(SQLiteL10N::tr("Error during RTree index creation: %1! Check if SQLite library has RTree index support!").arg(os.getError())); } } void RTreeAssemblyAdapter::createReadsIndexes(U2OpStatus& os) { static QString q = "CREATE INDEX %1_name ON %1(name)"; SQLiteQuery(q.arg(readsTable), db, os).execute(); } qint64 RTreeAssemblyAdapter::countReads(const U2Region& r, U2OpStatus& os) { if (r == U2_ASSEMBLY_REGION_MAX) { return SQLiteQuery(QString("SELECT COUNT(*) FROM %1").arg(readsTable), db, os).selectInt64(); } QString qStr = QString("SELECT COUNT(*) FROM %1 AS i WHERE " + RANGE_CONDITION_CHECK).arg(indexTable); SQLiteQuery q(qStr, db, os); q.bindInt64(1, r.endPos()); q.bindInt64(2, r.startPos); return q.selectInt64(); } qint64 RTreeAssemblyAdapter::getMaxPackedRow(const U2Region& r, U2OpStatus& os) { SQLiteQuery q(QString("SELECT MAX(prow1) FROM %1 AS i WHERE (" + RANGE_CONDITION_CHECK + ")").arg(indexTable), db, os); q.bindInt64(1, r.endPos()); q.bindInt64(2, r.startPos); return q.selectInt64(); } qint64 RTreeAssemblyAdapter::getMaxEndPos(U2OpStatus& os) { return SQLiteQuery(QString("SELECT MAX(gend) FROM %1").arg(indexTable), db, os).selectInt64(); } U2DbiIterator* RTreeAssemblyAdapter::getReads(const U2Region& r, U2OpStatus& os) { QString qStr = QString("SELECT " + ALL_READ_FIELDS + FROM_2TABLES + " WHERE " + SAME_IDX + " AND "+ RANGE_CONDITION_CHECK ) .arg(readsTable).arg(indexTable); SQLiteQuery* q = new SQLiteQuery(qStr, db, os); q->bindInt64(1, r.endPos()); q->bindInt64(2, r.startPos); return new SqlRSIterator(q, new SimpleAssemblyReadLoader(), NULL, U2AssemblyRead(), os); } U2DbiIterator* RTreeAssemblyAdapter::getReadsByRow(const U2Region& r, qint64 minRow, qint64 maxRow, U2OpStatus& os) { QString qStr = QString("SELECT " + ALL_READ_FIELDS + FROM_2TABLES + " WHERE " + SAME_IDX + " AND "+ RANGE_CONDITION_CHECK + " AND (i.prow1 >= ?3 AND i.prow2 < ?4)").arg(readsTable).arg(indexTable); SQLiteQuery* q = new SQLiteQuery(qStr, db, os); q->bindInt64(1, r.endPos()); q->bindInt64(2, r.startPos); q->bindInt64(3, minRow); q->bindInt64(4, maxRow); return new SqlRSIterator(q, new SimpleAssemblyReadLoader(), NULL, U2AssemblyRead(), os); } U2DbiIterator* RTreeAssemblyAdapter::getReadsByName(const QByteArray& name, U2OpStatus& os) { QString qStr = QString("SELECT " + ALL_READ_FIELDS + " FROM %1 WHERE name = ?1").arg(readsTable); SQLiteQuery* q = new SQLiteQuery(qStr, db, os); int hash = qHash(name); q->bindInt64(1, hash); return new SqlRSIterator(q, new SimpleAssemblyReadLoader(), new SQLiteAssemblyNameFilter(name), U2AssemblyRead(), os); } void RTreeAssemblyAdapter::addReads(U2DbiIterator* it, U2AssemblyReadsImportInfo& ii, U2OpStatus& os) { static QString q1 = "INSERT INTO %1(name, flags, mq, data) VALUES (?1, ?2, ?3, ?4)"; static QString q2 = "INSERT INTO %1(id, gstart, gend, prow1, prow2) VALUES (?1, ?2, ?3, ?4, ?5)"; SQLiteTransaction t(db, os); SQLiteQuery insertRQ(q1.arg(readsTable), db, os); SQLiteQuery insertIQ(q2.arg(indexTable), db, os); while (it->hasNext()) { U2AssemblyRead read = it->next(); bool dnaExt = false; //TODO QByteArray cigarText = U2AssemblyUtils::cigar2String(read->cigar); qint64 flags = read->flags; flags = flags | (dnaExt ? DnaExtAlphabet : 0); int readLen = read->readSequence.length(); int effectiveReadLength = readLen + U2AssemblyUtils::getCigarExtraLength(read->cigar); read->effectiveLen = effectiveReadLength; int hash = qHash(read->name); insertRQ.reset(); insertRQ.bindInt64(1, hash); insertRQ.bindInt64(2, flags); insertRQ.bindInt32(3, read->mappingQuality); QByteArray packedData = SQLiteAssemblyUtils::packData(SQLiteAssemblyDataMethod_NSCQ, read->name, read->readSequence, cigarText, read->quality, os); insertRQ.bindBlob(4, packedData, false); insertRQ.insert(); if (os.hasError()) { break; } insertIQ.reset(); insertIQ.bindDataId(1, read->id); insertIQ.bindInt64(2, read->leftmostPos); insertIQ.bindInt64(3, read->leftmostPos + read->effectiveLen); insertIQ.bindInt64(4, read->packedViewRow); insertIQ.bindInt64(5, read->packedViewRow); insertIQ.execute(); SQLiteAssemblyUtils::addToCoverage(ii, read); ii.nReads++; //#define U2_SQLITE_CHECK_RTREE_ #ifdef U2_SQLITE_CHECK_RTREE_ // Consistency check. To be removed after all known rtree issues are resolved qint64 dbId = SQLiteUtils::toDbiId(read->id); SQLiteQuery cq("SELECT gstart, gend FROM " + indexTable + " WHERE id = " + QString::number(dbId), db, os); cq.step(); qint64 cstart = cq.getInt64(0); qint64 cend = cq.getInt64(1); assert(cstart == read->leftmostPos); assert(cend == read->leftmostPos + read->effectiveLen); #endif } } void RTreeAssemblyAdapter::removeReads(const QList& readIds, U2OpStatus& os) { foreach(const U2DataId& readId, readIds) { SQLiteUtils::remove(readsTable, "id", readId, 1, db, os); SQLiteUtils::remove(indexTable, "id", readId, 1, db, os); } SQLiteObjectDbi::incrementVersion(assemblyId, db, os); } void RTreeAssemblyAdapter::pack(U2AssemblyPackStat& stat, U2OpStatus& os) { RTreePackAlgorithmAdapter packAdapter(db, readsTable, indexTable); AssemblyPackAlgorithm::pack(packAdapter, stat, os); } void RTreeAssemblyAdapter::calculateCoverage(const U2Region& r, U2AssemblyCoverageStat& c, U2OpStatus& os) { QString queryString = "SELECT gstart, gend - gstart FROM " + indexTable; bool rangeArgs = false; if (r != U2_ASSEMBLY_REGION_MAX) { queryString+="AS i WHERE " + RANGE_CONDITION_CHECK; rangeArgs = true; } SQLiteQuery q(queryString, db, os); if (rangeArgs) { q.bindInt64(1, r.endPos()); q.bindInt64(2, r.startPos); } SQLiteAssemblyUtils::calculateCoverage(q, r, c, os); } U2DbiIterator* RTreePackAlgorithmAdapter::selectAllReads(U2OpStatus& os) { SQLiteQuery* q = new SQLiteQuery("SELECT id, gstart, gend - gstart FROM " + indexTable + " ORDER BY gstart", db, os); return new SqlRSIterator(q, new SimpleAssemblyReadPackedDataLoader(), NULL, PackAlgorithmData(), os); } RTreePackAlgorithmAdapter::~RTreePackAlgorithmAdapter() { delete updateQuery; } void RTreePackAlgorithmAdapter::assignProw(const U2DataId& readId, qint64 prow, U2OpStatus& os) { if (updateQuery == NULL) { updateQuery = new SQLiteQuery("UPDATE " + indexTable + " SET prow1 = ?1, prow2=?1 WHERE id = ?2", db, os); } updateQuery->setOpStatus(os); updateQuery->reset(); updateQuery->bindInt64(1, prow); updateQuery->bindDataId(2, readId); updateQuery->execute(); } } //namespace ugene-1.9.8/src/plugins/dbi_sqlite/src/assembly/SingleTableAssemblyAdapter.h0000644000175000017500000000724411651544322025664 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_SQLITE_ASSEMBLY_SINGLE_TABLE_DBI_H_ #define _U2_SQLITE_ASSEMBLY_SINGLE_TABLE_DBI_H_ #include "SQLiteAssemblyDbi.h" #include "AssemblyPackAlgorithm.h" #include namespace U2 { class SingleTableAssemblyAdapter : public AssemblyAdapter { public: SingleTableAssemblyAdapter(SQLiteDbi* dbi, const U2DataId& assemblyId, char tablePrefix, const QString& tableSuffix, const AssemblyCompressor* compressor, DbRef* ref, U2OpStatus& os); virtual void createReadsTables(U2OpStatus& os); virtual void createReadsIndexes(U2OpStatus& os); virtual qint64 countReads(const U2Region& r, U2OpStatus& os); virtual qint64 countReadsPrecise(const U2Region& r, U2OpStatus& os); virtual qint64 getMaxPackedRow(const U2Region& r, U2OpStatus& os); virtual qint64 getMaxEndPos(U2OpStatus& os); virtual U2DbiIterator* getReads(const U2Region& r, U2OpStatus& os); virtual U2DbiIterator* getReadsByRow(const U2Region& r, qint64 minRow, qint64 maxRow, U2OpStatus& os); virtual U2DbiIterator* getReadsByName(const QByteArray& name, U2OpStatus& os); virtual void addReads(U2DbiIterator* it, U2AssemblyReadsImportInfo& ii, U2OpStatus& os); virtual void removeReads(const QList& readIds, U2OpStatus& os); virtual void pack(U2AssemblyPackStat& stat, U2OpStatus& os); virtual void calculateCoverage(const U2Region& region, U2AssemblyCoverageStat& c, U2OpStatus& os); const QString& getReadsTableName() const {return readsTable;} void enableRangeTableMode(int minLength, int maxLength); static QString getReadsTableName(const U2DataId& assemblyId, char prefix, const QString& suffix); void dropReadsIndexes(U2OpStatus& os); qint64 getMinReadLength() const {return minReadLength;} qint64 getMaxReadLength() const {return maxReadLength;} protected: void bindRegion(SQLiteQuery& q, const U2Region& r, bool forCount = false); SQLiteDbi* dbi; QString readsTable; QString rangeConditionCheck; QString rangeConditionCheckForCount; int minReadLength; // used in range mode int maxReadLength; // used in range mode bool rangeMode; // flag to show that range mode is in use }; class SingleTablePackAlgorithmAdapter : public PackAlgorithmAdapter { public: SingleTablePackAlgorithmAdapter(DbRef* _db, const QString& _readsTable) : db(_db), readsTable(_readsTable), updateQuery(NULL){} ~SingleTablePackAlgorithmAdapter(); virtual U2DbiIterator* selectAllReads(U2OpStatus& os); virtual void assignProw(const U2DataId& readId, qint64 prow, U2OpStatus& os); void releaseDbResources(); private: DbRef* db; QString readsTable; SQLiteQuery* updateQuery; }; } //namespace #endif ugene-1.9.8/src/plugins/dbi_sqlite/src/assembly/AssemblyPackAlgorithm.h0000644000175000017500000000364411651544322024717 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_SQLITE_ASSEMBLY_PACK_ALGORITHM_DBI_H_ #define _U2_SQLITE_ASSEMBLY_PACK_ALGORITHM_DBI_H_ #include "SQLiteDbi.h" #include namespace U2 { class PackAlgorithmData { public: PackAlgorithmData() : leftmostPos(0), effectiveLen(0){} U2DataId readId; qint64 leftmostPos; qint64 effectiveLen; }; class PackAlgorithmAdapter { public: virtual U2DbiIterator* selectAllReads(U2OpStatus& os) = 0; virtual void assignProw(const U2DataId& readId, qint64 prow, U2OpStatus& os) = 0; }; #define PACK_TAIL_SIZE 50000 class PackAlgorithmContext { public: PackAlgorithmContext(); int maxProw; qint64 nReads; // used to assign prow for reads when TAIL_SIZE is not enough qint64 peakEnd; qint64 peakRow; QVector tails; }; class AssemblyPackAlgorithm { public: static void pack(PackAlgorithmAdapter& adapter, U2AssemblyPackStat& stat, U2OpStatus& os); static int packRead(const U2Region& reg, PackAlgorithmContext& ctx, U2OpStatus& os); }; } //namespace #endif ugene-1.9.8/src/plugins/dbi_sqlite/src/assembly/MultiTableAssemblyAdapter.h0000644000175000017500000001716111651544322025534 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_SQLITE_ASSEMBLY_MULTI_TABLE_DBI_H_ #define _U2_SQLITE_ASSEMBLY_MULTI_TABLE_DBI_H_ #include "SingleTableAssemblyAdapter.h" #include "AssemblyPackAlgorithm.h" #include #include namespace U2 { class MTASingleTableAdapter { public: /** Wrapper over 1 table in database. If singleTableAdapter == NULL the table was not created yet */ MTASingleTableAdapter(SingleTableAssemblyAdapter* a, int _rowPos, int _elenPos, const QByteArray& extra) : singleTableAdapter(a), rowPos(_rowPos), elenPos(_elenPos), idExtra(extra) {} SingleTableAssemblyAdapter* singleTableAdapter; int rowPos; int elenPos; QByteArray idExtra; }; class MultiTableAssemblyAdapter : public AssemblyAdapter { public: MultiTableAssemblyAdapter(SQLiteDbi* dbi, const U2DataId& assemblyId, const AssemblyCompressor* compressor, DbRef* ref, U2OpStatus& os); ~MultiTableAssemblyAdapter(); virtual qint64 countReads(const U2Region& r, U2OpStatus& os); virtual qint64 getMaxPackedRow(const U2Region& r, U2OpStatus& os); virtual qint64 getMaxEndPos(U2OpStatus& os); virtual U2DbiIterator* getReads(const U2Region& r, U2OpStatus& os); virtual U2DbiIterator* getReadsByRow(const U2Region& r, qint64 minRow, qint64 maxRow, U2OpStatus& os); virtual U2DbiIterator* getReadsByName(const QByteArray& name, U2OpStatus& os); virtual void addReads(U2DbiIterator* it, U2AssemblyReadsImportInfo& ii, U2OpStatus& os); virtual void removeReads(const QList& readIds, U2OpStatus& os); virtual void pack(U2AssemblyPackStat& stat, U2OpStatus& os); virtual void calculateCoverage(const U2Region& region, U2AssemblyCoverageStat& c, U2OpStatus& os); virtual void createReadsIndexes(U2OpStatus& os); int getElenRangePosByLength(qint64 readLength) const; int getElenRangePosById(const U2DataId& id) const; int getNumberOfElenRanges() const {return elenRanges.size();} int getRowRangePosByRow(quint64 row) const; int getRowRangePosById(const U2DataId& id) const; int getRowsPerRange() const {return rowsPerRange;} const QVector& getAdapters() const {return adapters;} const QVector& getIdExtrasPerRange() const {return idExtras;} DbRef* getDbRef() const {return dbi->getDbRef();} MTASingleTableAdapter* getAdapterByRowAndElenRange(int rowRange, int elenRange, bool createIfNotExits, U2OpStatus& os); protected: QString getTableSuffix(int rowRange, int elenRange); static QByteArray getIdExtra(int rowRange, int elenRange); void addTableAdapter(int minLen, int maxLen, const U2DataId& assemblyId, const AssemblyCompressor* compressor, bool last, U2OpStatus& os); /** Checks if table info must be re-read from DB and calls re-read if needed */ void syncTables(U2OpStatus& os); /** For a new and empty assembly analyzes reads data and calculate ranges */ void initTables(const QList& reads, U2OpStatus& os); /** Re-reads table info from DB */ void rereadTables(const QByteArray& idata, U2OpStatus& os); /** Flushes tables info into database */ void flushTables(U2OpStatus& os); void clearTableAdaptersInfo(); MTASingleTableAdapter* createAdapter(int rowRange, int elenRange, U2OpStatus& os); void initAdaptersGrid(int nRows, int nRanges); SQLiteDbi* dbi; /** All non-NUL adapters */ QVector adapters; /** outer dim -> prow, inner dim -> elen */ QVector< QVector > adaptersGrid; /** id extras for every table, same hierarchy with tableAdapters */ QVector idExtras; /** assembly object version adapters are used for */ qint32 version; /** effective length ranges */ QVector elenRanges; /** prow range per table */ qint32 rowsPerRange; //TODO: add read-locks into all methods QReadWriteLock tablesSyncLock; }; class ReadTableMigrationData { public: ReadTableMigrationData() : readId (-1), oldTable(NULL), newProw(-1){} ReadTableMigrationData(qint64 oldId, MTASingleTableAdapter* oldT, int newP) : readId(oldId), oldTable(oldT), newProw(newP) {} qint64 readId; MTASingleTableAdapter* oldTable; int newProw; }; class MultiTablePackAlgorithmAdapter : public PackAlgorithmAdapter { public: MultiTablePackAlgorithmAdapter(MultiTableAssemblyAdapter* a); ~MultiTablePackAlgorithmAdapter(); virtual U2DbiIterator* selectAllReads(U2OpStatus& os); virtual void assignProw(const U2DataId& readId, qint64 prow, U2OpStatus& os); void releaseDbResources(); void migrateAll(U2OpStatus& os); private: void ensureGridSize(int nRows); void migrate(MTASingleTableAdapter* newA, const QVector& data, qint64 migratedBefore, qint64 totalMigrationCount, U2OpStatus& os); MultiTableAssemblyAdapter* multiTableAdapter; QVector packAdapters; QVector< QVector > packAdaptersGrid; QHash > migrations; }; // Class that multiplexes multiple read iterators into 1 class MTAReadsIterator : public U2DbiIterator { public: MTAReadsIterator(QVector< U2DbiIterator* >& iterators, const QVector& idExtras); virtual ~MTAReadsIterator(); virtual bool hasNext(); virtual U2AssemblyRead next(); virtual U2AssemblyRead peek(); private: QVector*> iterators; int currentRange; QVector idExtras; }; // Class that multiplexes multiple read packed data iterators into 1 and supports ordering class MTAPackAlgorithmDataIterator : public U2DbiIterator { public: MTAPackAlgorithmDataIterator(QVector< U2DbiIterator* >& iterators, const QVector& idExtras); virtual ~MTAPackAlgorithmDataIterator(); virtual bool hasNext(); virtual PackAlgorithmData next(); virtual PackAlgorithmData peek(); private: void fetchNextData(); QVector*> iterators; PackAlgorithmData nextData; QVector idExtras; }; } //namespace #endif ugene-1.9.8/src/plugins/dbi_sqlite/src/assembly/RTreeAssemblyAdapter.h0000644000175000017500000000555011651544322024512 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_SQLITE_ASSEMBLY_RTREE_DBI_H_ #define _U2_SQLITE_ASSEMBLY_RTREE_DBI_H_ #include "SQLiteAssemblyDbi.h" #include "AssemblyPackAlgorithm.h" #include namespace U2 { class RTreeAssemblyAdapter : public AssemblyAdapter { public: RTreeAssemblyAdapter(SQLiteDbi* dbi, const U2DataId& assemblyId, const AssemblyCompressor* compressor, DbRef* ref, U2OpStatus& os); virtual void createReadsTables(U2OpStatus& os); virtual void createReadsIndexes(U2OpStatus& os); virtual qint64 countReads(const U2Region& r, U2OpStatus& os); virtual qint64 getMaxPackedRow(const U2Region& r, U2OpStatus& os); virtual qint64 getMaxEndPos(U2OpStatus& os); virtual U2DbiIterator* getReads(const U2Region& r, U2OpStatus& os); virtual U2DbiIterator* getReadsByRow(const U2Region& r, qint64 minRow, qint64 maxRow, U2OpStatus& os); virtual U2DbiIterator* getReadsByName(const QByteArray& name, U2OpStatus& os); virtual void addReads(U2DbiIterator* it, U2AssemblyReadsImportInfo& ii, U2OpStatus& os); virtual void removeReads(const QList& readIds, U2OpStatus& os); virtual void pack(U2AssemblyPackStat& stat, U2OpStatus& os); virtual void calculateCoverage(const U2Region& region, U2AssemblyCoverageStat& c, U2OpStatus& os); protected: SQLiteDbi* dbi; QString readsTable; QString indexTable; }; class RTreePackAlgorithmAdapter : public PackAlgorithmAdapter { public: RTreePackAlgorithmAdapter(DbRef* _db, const QString& _readsTable, const QString& _indexTable) : db(_db), readsTable(_readsTable), indexTable(_indexTable), updateQuery(NULL){} ~RTreePackAlgorithmAdapter(); virtual U2DbiIterator* selectAllReads(U2OpStatus& os); virtual void assignProw(const U2DataId& readId, qint64 prow, U2OpStatus& os); private: DbRef* db; QString readsTable; QString indexTable; SQLiteQuery* updateQuery; }; } //namespace #endif ugene-1.9.8/src/plugins/dbi_sqlite/src/assembly/SingleTableAssemblyAdapter.cpp0000644000175000017500000002612611651544322026217 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "SingleTableAssemblyAdapter.h" #include "../SQLiteDbi.h" #include "../SQLiteAssemblyDbi.h" #include "../SQLiteObjectDbi.h" #include #include namespace U2 { // ?1 -> end of the region // ?2 -> start of the region (- max read size) // ?3 -> real start of the region #define DEFAULT_RANGE_CONDITION_CHECK QString(" (gstart < ?1 AND gstart + elen > ?2) ") #define RTM_RANGE_CONDITION_CHECK QString(" ((gstart < ?1 AND gstart > ?2) AND gstart + elen > ?3) ") #define RTM_RANGE_CONDITION_CHECK_COUNT QString(" (gstart < ?1 AND gstart > ?2) ") #define ALL_READ_FIELDS QString(" id, prow, gstart, elen, flags, mq, data") SingleTableAssemblyAdapter::SingleTableAssemblyAdapter(SQLiteDbi* _dbi, const U2DataId& assemblyId, char tablePrefix, const QString& tableSuffix, const AssemblyCompressor* compressor, DbRef* db, U2OpStatus& ) : AssemblyAdapter(assemblyId, compressor, db) { dbi = _dbi; rangeConditionCheck = DEFAULT_RANGE_CONDITION_CHECK; rangeConditionCheckForCount = DEFAULT_RANGE_CONDITION_CHECK; readsTable = getReadsTableName(assemblyId, tablePrefix, tableSuffix); rangeMode = false; minReadLength = 0; maxReadLength = 0; } QString SingleTableAssemblyAdapter::getReadsTableName(const U2DataId& assemblyId, char prefix, const QString& suffix) { return QString("AssemblyRead_%1%2_%3").arg(prefix).arg(SQLiteUtils::toDbiId(assemblyId)).arg(suffix);; } void SingleTableAssemblyAdapter::enableRangeTableMode(int minLen, int maxLen) { rangeMode = true; minReadLength = minLen; maxReadLength = maxLen; rangeConditionCheck = RTM_RANGE_CONDITION_CHECK; rangeConditionCheckForCount = RTM_RANGE_CONDITION_CHECK_COUNT; } void SingleTableAssemblyAdapter::createReadsTables(U2OpStatus& os) { // id - id of the read // name - read name hash // prow - packed view row // gstart - start of the read // elen - effective length of the read // flags - read flags // mq - mapping quality // data - packed data: CIGAR, read sequence, quality string static QString q = "CREATE TABLE IF NOT EXISTS %1 (id INTEGER PRIMARY KEY AUTOINCREMENT, name INTEGER NOT NULL, prow INTEGER NOT NULL, " "gstart INTEGER NOT NULL, elen INTEGER NOT NULL, flags INTEGER NOT NULL, mq INTEGER NOT NULL, data BLOB NOT NULL)"; SQLiteQuery(q.arg(readsTable), db, os).execute(); } void SingleTableAssemblyAdapter::createReadsIndexes(U2OpStatus& os) { static QString q1 = "CREATE INDEX IF NOT EXISTS %1_gstart ON %1(gstart)"; SQLiteQuery(q1.arg(readsTable), db, os).execute(); static QString q2 = "CREATE INDEX IF NOT EXISTS %1_name ON %1(name)"; SQLiteQuery(q2.arg(readsTable), db, os).execute(); } void SingleTableAssemblyAdapter::dropReadsIndexes(U2OpStatus& os) { static QString q1 = "DROP INDEX IF EXISTS %1_gstart"; SQLiteQuery(q1.arg(readsTable), db, os).execute(); static QString q2 = "DROP INDEX IF EXISTS %1_name"; SQLiteQuery(q2.arg(readsTable), db, os).execute(); } void SingleTableAssemblyAdapter::bindRegion(SQLiteQuery& q, const U2Region& r, bool forCount) { if (rangeMode) { q.bindInt64(1, r.endPos()); q.bindInt64(2, r.startPos - maxReadLength); if (!forCount) { q.bindInt64(3, r.startPos); } } else { q.bindInt64(1, r.endPos()); q.bindInt64(2, r.startPos); } } qint64 SingleTableAssemblyAdapter::countReads(const U2Region& r, U2OpStatus& os) { if (r == U2_ASSEMBLY_REGION_MAX) { return SQLiteQuery(QString("SELECT COUNT(*) FROM %1").arg(readsTable), db, os).selectInt64(); } QString qStr = QString("SELECT COUNT(*) FROM %1 WHERE " + rangeConditionCheckForCount).arg(readsTable); SQLiteQuery q(qStr, db, os); bindRegion(q, r, true); return q.selectInt64(); } qint64 SingleTableAssemblyAdapter::countReadsPrecise(const U2Region& r, U2OpStatus& os) { if (!rangeMode) { return countReads(r, os); } //here we use not-optimized rangeConditionCheck but not rangeConditionCheckForCount QString qStr = QString("SELECT COUNT(*) FROM %1 WHERE " + rangeConditionCheck).arg(readsTable); SQLiteQuery q(qStr, db, os); bindRegion(q, r, false); return q.selectInt64(); } qint64 SingleTableAssemblyAdapter::getMaxPackedRow(const U2Region& r, U2OpStatus& os) { SQLiteQuery q(QString("SELECT MAX(prow) FROM %1 WHERE " + rangeConditionCheck).arg(readsTable), db, os); bindRegion(q, r); return q.selectInt64(); } qint64 SingleTableAssemblyAdapter::getMaxEndPos(U2OpStatus& os) { return SQLiteQuery(QString("SELECT MAX(gstart + elen) FROM %1").arg(readsTable), db, os).selectInt64(); } U2DbiIterator* SingleTableAssemblyAdapter::getReads(const U2Region& r, U2OpStatus& os) { QString qStr = QString("SELECT " + ALL_READ_FIELDS + " FROM %1 WHERE " + rangeConditionCheck).arg(readsTable); SQLiteQuery* q = new SQLiteQuery(qStr, db, os); bindRegion(*q, r); return new SqlRSIterator(q, new SimpleAssemblyReadLoader(), NULL, U2AssemblyRead(), os); } U2DbiIterator* SingleTableAssemblyAdapter::getReadsByRow(const U2Region& r, qint64 minRow, qint64 maxRow, U2OpStatus& os) { int rowFieldPos = rangeMode ? 4 : 3; QString qStr = QString("SELECT " + ALL_READ_FIELDS + " FROM %1 WHERE " + rangeConditionCheck + " AND (prow >= ?%2 AND prow < ?%3)").arg(readsTable).arg(rowFieldPos).arg(rowFieldPos + 1); SQLiteQuery* q = new SQLiteQuery(qStr, db, os); bindRegion(*q, r); q->bindInt64(rowFieldPos, minRow); q->bindInt64(rowFieldPos + 1, maxRow); return new SqlRSIterator(q, new SimpleAssemblyReadLoader(), NULL, U2AssemblyRead(), os); } U2DbiIterator* SingleTableAssemblyAdapter::getReadsByName(const QByteArray& name, U2OpStatus& os) { QString qStr = QString("SELECT " + ALL_READ_FIELDS + " FROM %1 WHERE name = ?1").arg(readsTable); SQLiteQuery* q = new SQLiteQuery(qStr, db, os); int hash = qHash(name); q->bindInt64(1, hash); return new SqlRSIterator(q, new SimpleAssemblyReadLoader(), new SQLiteAssemblyNameFilter(name), U2AssemblyRead(), os); } void SingleTableAssemblyAdapter::addReads(U2DbiIterator* it, U2AssemblyReadsImportInfo& ii, U2OpStatus& os) { SQLiteTransaction t(db, os); QString q = "INSERT INTO %1(name, prow, flags, gstart, elen, mq, data) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)"; SQLiteQuery insertQ(q.arg(readsTable), db, os); while (it->hasNext()) { U2AssemblyRead read = it->next(); bool dnaExt = false; //TODO: QByteArray cigarText = U2AssemblyUtils::cigar2String(read->cigar); qint64 flags = read->flags; flags = flags | (dnaExt ? DnaExtAlphabet : 0); if (rangeMode) { //effective read length must be precomputed in this mode assert(read->effectiveLen >= minReadLength && read->effectiveLen < maxReadLength); } else { int readLen = read->readSequence.length(); int effectiveReadLength = readLen + U2AssemblyUtils::getCigarExtraLength(read->cigar); read->effectiveLen = effectiveReadLength; } int hash = qHash(read->name); insertQ.reset(); insertQ.bindInt64(1, hash); insertQ.bindInt64(2, read->packedViewRow); insertQ.bindInt64(3, flags); insertQ.bindInt64(4, read->leftmostPos); insertQ.bindInt64(5, read->effectiveLen); insertQ.bindInt32(6, read->mappingQuality); QByteArray packedData = SQLiteAssemblyUtils::packData(SQLiteAssemblyDataMethod_NSCQ, read->name, read->readSequence, cigarText, read->quality, os); insertQ.bindBlob(7, packedData, false); insertQ.insert(); SQLiteAssemblyUtils::addToCoverage(ii, read); ii.nReads++; } } void SingleTableAssemblyAdapter::removeReads(const QList& readIds, U2OpStatus& os) { //TODO: add transaction per pack or reads //TODO: remove multiple reads in 1 SQL at once //SQLiteObjectDbi* objDbi = dbi->getSQLiteObjectDbi(); foreach(U2DataId readId, readIds) { SQLiteUtils::remove(readsTable, "id", readId, 1, db, os); if (os.hasError()) { break; } } SQLiteObjectDbi::incrementVersion(assemblyId, db, os); } void SingleTableAssemblyAdapter::pack(U2AssemblyPackStat& stat, U2OpStatus& os) { SingleTablePackAlgorithmAdapter packAdapter(db, readsTable); AssemblyPackAlgorithm::pack(packAdapter, stat, os); createReadsIndexes(os); } void SingleTableAssemblyAdapter::calculateCoverage(const U2Region& r, U2AssemblyCoverageStat& c, U2OpStatus& os) { QString queryString = "SELECT gstart, elen FROM " + readsTable; bool rangeArgs = !rangeMode || (r== U2_ASSEMBLY_REGION_MAX) || r.length < 50; if (rangeArgs) { queryString+=" WHERE " + rangeConditionCheck; } SQLiteQuery q(queryString, db, os); if (rangeArgs) { bindRegion(q, r, false); } SQLiteAssemblyUtils::calculateCoverage(q, r, c, os); } ////////////////////////////////////////////////////////////////////////// // pack adapter U2DbiIterator* SingleTablePackAlgorithmAdapter::selectAllReads(U2OpStatus& os) { SQLiteQuery* q = new SQLiteQuery("SELECT id, gstart, elen FROM " + readsTable + " ORDER BY gstart", db, os); return new SqlRSIterator(q, new SimpleAssemblyReadPackedDataLoader(), NULL, PackAlgorithmData(), os); } SingleTablePackAlgorithmAdapter::~SingleTablePackAlgorithmAdapter() { releaseDbResources(); } void SingleTablePackAlgorithmAdapter::assignProw(const U2DataId& readId, qint64 prow, U2OpStatus& os) { if (updateQuery == NULL) { updateQuery = new SQLiteQuery("UPDATE " + readsTable + " SET prow = ?1 WHERE id = ?2", db, os); } updateQuery->setOpStatus(os); updateQuery->reset(); updateQuery->bindInt64(1, prow); updateQuery->bindDataId(2, readId); updateQuery->execute(); } void SingleTablePackAlgorithmAdapter::releaseDbResources() { delete updateQuery; updateQuery = NULL; } } //namespace ugene-1.9.8/src/plugins/dbi_sqlite/src/assembly/MultiTableAssemblyAdapter.cpp0000644000175000017500000007602511651544322026073 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "MultiTableAssemblyAdapter.h" #include "../SQLiteDbi.h" #include "../SQLiteAssemblyDbi.h" #include "../SQLiteObjectDbi.h" #include #include #include #include #include namespace U2 { #define DEFAULT_ROWS_PER_TABLE 5000 MultiTableAssemblyAdapter::MultiTableAssemblyAdapter(SQLiteDbi* _dbi, const U2DataId& assemblyId, const AssemblyCompressor* compressor, DbRef* db, U2OpStatus& os) : AssemblyAdapter(assemblyId, compressor, db) { dbi = _dbi; version = -1; syncTables(os); rowsPerRange = DEFAULT_ROWS_PER_TABLE; } MultiTableAssemblyAdapter::~MultiTableAssemblyAdapter() { clearTableAdaptersInfo(); } void MultiTableAssemblyAdapter::clearTableAdaptersInfo() { qDeleteAll(adapters); adaptersGrid.clear(); idExtras.clear(); elenRanges.clear(); } void MultiTableAssemblyAdapter::syncTables(U2OpStatus& os) { qint64 versionInDb = dbi->getObjectDbi()->getObjectVersion(assemblyId, os); if (versionInDb <= version) { return; } SQLiteQuery q("SELECT idata FROM Assembly WHERE object = ?1", db, os); q.bindDataId(1, assemblyId); if (q.step()) { QByteArray data = q.getBlob(0); rereadTables(data, os); if (!os.hasError()) { version = versionInDb; } } } static QVector toRange(const QVector& startPos) { QVector res; int prev = 0; foreach(int pos, startPos){ res << U2Region(prev, pos - prev); prev = pos; } return res; } void MultiTableAssemblyAdapter::initTables(const QList& reads, U2OpStatus& os) { if (os.hasError()) { return; } SAFE_POINT(elenRanges.isEmpty(), "Effective ranges are already initialized!", ); int nReads = reads.size(); if (false && nReads > 1000) { /* // get reads distribution first QVector distribution(nReads / 10, 0); int* data = distribution.data(); foreach(const U2AssemblyRead& read, reads) { int elen = read->readSequence.size() + U2AssemblyUtils::getCigarExtraLength(read->cigar); int idx = elen / 10; data[idx]++; } // derive regions // TODO:*/ } else { QVector starts; starts << 50 << 100 << 200 << 400 << 800 << 4*1000 << 25*1000 << 100*1000 << 500*1000 << 2*1000*1000; elenRanges << toRange( starts); } initAdaptersGrid(1, elenRanges.size()); flushTables(os); } void MultiTableAssemblyAdapter::rereadTables(const QByteArray& idata, U2OpStatus& os) { QWriteLocker wl(&tablesSyncLock); clearTableAdaptersInfo(); // format: N, N, N, N | N, N |..... // elements are separated by | sign. First element encodes ranges, second prow step and max prow, others are for future extension if (idata.isEmpty()) { //assembly is empty - no index data was created return; } QList elements = idata.split('|'); if (elements.size() < 2) { os.setError(SQLiteL10n::tr("Failed to detect assembly storage format: %1").arg(idata.constData())); return; } QByteArray elenData = elements.at(0); QByteArray prowData = elements.at(1); QList elenTokens = elenData.split(','); U2Region prev(-1, 1); bool parseOk = true; foreach(const QByteArray& elenTok, elenTokens) { int start = elenTok.toInt(&parseOk); if (!parseOk || start < prev.endPos()) { os.setError(QString("Failed to parse range: %1, full: %2").arg(elenTok.constData()).arg(elenData.constData())); return; } U2Region region(prev.endPos(), start - prev.endPos()); elenRanges << region; prev = region; } elenRanges << U2Region(prev.endPos(), INT_MAX); QList prowTokens = prowData.split(','); int prange = prowTokens.at(0).toInt(&parseOk); if (prange < 1 || !parseOk) { os.setError(SQLiteL10n::tr("Failed to parse packed row range info %1").arg(idata.constData())); return; } if (prowTokens.size() != 2) { os.setError(SQLiteL10n::tr("Failed to parse packed row range info %1").arg(idata.constData())); return; } int nRows = prowTokens.at(1).toInt(&parseOk); if (nRows < 0 || !parseOk) { os.setError(SQLiteL10n::tr("Failed to parse packed row range info %1").arg(idata.constData())); return; } // ok, all regions parsed, now create adapters int nElens = elenRanges.size(); initAdaptersGrid(nRows, nElens); for (int rowPos = 0; rowPos < nRows; rowPos++) { for (int elenPos = 0; elenPos < nElens; elenPos++) { QString suffix = getTableSuffix(rowPos, elenPos); QString tableName = SingleTableAssemblyAdapter::getReadsTableName(assemblyId, 'M', suffix); if (SQLiteUtils::isTableExists(tableName, db, os)) { createAdapter(rowPos, elenPos, os); } } } } void MultiTableAssemblyAdapter::flushTables(U2OpStatus& os) { QByteArray idata; for(int i = 0; i < elenRanges.size(); i++) { int rangeStart = elenRanges[i].startPos; if (!idata.isEmpty()) { idata.append(','); } idata.append(QByteArray::number(rangeStart)); } idata.append('|').append(QByteArray::number(rowsPerRange)).append(',').append(QByteArray::number(adaptersGrid.size())); SQLiteQuery q("UPDATE Assembly SET idata = ?1 WHERE object = ?2", db, os); q.bindBlob(1, idata); q.bindDataId(2, assemblyId); q.execute(); } QString MultiTableAssemblyAdapter::getTableSuffix(int rowPos, int elenPos) { U2Region eRegion = elenRanges[elenPos]; bool last = (elenPos + 1== elenRanges.size()); return QString("%1_%2_%3").arg(eRegion.startPos).arg(last ? QString("U") : QString::number(eRegion.endPos())).arg(rowPos); } void MultiTableAssemblyAdapter::initAdaptersGrid(int nRows, int nElens) { assert(adaptersGrid.isEmpty()); adaptersGrid.resize(nRows); for (int i = 0; i < nRows; i++) { adaptersGrid[i] = QVector(nElens, NULL); } } MTASingleTableAdapter* MultiTableAssemblyAdapter::createAdapter(int rowPos, int elenPos, U2OpStatus& os) { assert(adaptersGrid.at(rowPos).at(elenPos) == NULL); QString suffix = getTableSuffix(rowPos, elenPos); SingleTableAssemblyAdapter* sa = new SingleTableAssemblyAdapter(dbi, assemblyId, 'M', suffix, compressor, db, os); const U2Region& elenRange = elenRanges.at(elenPos); sa->enableRangeTableMode(elenRange.startPos, elenRange.endPos()); QByteArray idExtra = getIdExtra(rowPos, elenPos); MTASingleTableAdapter * ma = new MTASingleTableAdapter(sa, rowPos, elenPos, idExtra); ma->singleTableAdapter->createReadsTables(os); adapters << ma; idExtras << idExtra; adaptersGrid[rowPos][elenPos] = ma; return ma; } void MultiTableAssemblyAdapter::createReadsIndexes(U2OpStatus& os) { foreach(MTASingleTableAdapter* a, adapters) { a->singleTableAdapter->createReadsIndexes(os); if (os.hasError()) { break; } } } QByteArray MultiTableAssemblyAdapter::getIdExtra(int rowPos, int elenPos) { QByteArray res(4, 0); qint16* data = (qint16*)res.data(); data[0] = (qint16)rowPos; data[1] = (qint16)elenPos; return res; } qint64 MultiTableAssemblyAdapter::countReads(const U2Region& r, U2OpStatus& os) { bool all = r == U2_ASSEMBLY_REGION_MAX; qint64 sum = 0; // use more sensitive algorithm for smaller regions with low amount of reads // and not-very sensitive for huge regions with a lot of reads int nReadsToUseNotPreciseAlgorithms = 1000 / (r.length + 1); foreach(MTASingleTableAdapter* a, adapters) { int n = a->singleTableAdapter->countReads(r, os); if (n != 0 && !all && n < nReadsToUseNotPreciseAlgorithms) { n = a->singleTableAdapter->countReadsPrecise(r, os); } if (os.hasError()) { break; } sum+=n; } return sum; } qint64 MultiTableAssemblyAdapter::getMaxPackedRow(const U2Region& r, U2OpStatus& os) { qint64 max = 0; // process only hi row adapters int nRows = adaptersGrid.size(); for (int rowPos = nRows; --rowPos>=0 && max == 0;) { QVector elenAdapters = adaptersGrid.at(rowPos); for (int elenPos = 0, nElens = elenAdapters.size(); elenPos < nElens; elenPos++) { MTASingleTableAdapter* a = elenAdapters.at(elenPos); if (a == NULL) { continue; } assert(a->rowPos == rowPos); qint64 n = a->singleTableAdapter->getMaxPackedRow(r, os); assert(U2Region(rowsPerRange * rowPos, rowsPerRange).contains(n)); max = qMax(max, n); } } return max; } qint64 MultiTableAssemblyAdapter::getMaxEndPos(U2OpStatus& os) { //TODO: optimize by using gstart + maxReadLen for first n-1 tables qint64 max = 0; foreach(MTASingleTableAdapter* a, adapters) { qint64 n = a->singleTableAdapter->getMaxEndPos(os); if (os.hasError()) { break; } max = qMax(max, n); } return max; } U2DbiIterator* MultiTableAssemblyAdapter::getReads(const U2Region& r, U2OpStatus& os) { QVector< U2DbiIterator* > iterators; foreach(MTASingleTableAdapter* a, adapters) { iterators << a->singleTableAdapter->getReads(r, os); if (os.hasError()) { break; } } if (os.hasError()) { qDeleteAll(iterators); return NULL; } return new MTAReadsIterator(iterators, idExtras); } U2DbiIterator* MultiTableAssemblyAdapter::getReadsByRow(const U2Region& r, qint64 minRow, qint64 maxRow, U2OpStatus& os) { QVector< U2DbiIterator* > iterators; U2Region targetRowRange(minRow, maxRow - minRow); foreach(MTASingleTableAdapter* a, adapters) { const U2Region rowRegion(a->rowPos * rowsPerRange, rowsPerRange); if (!rowRegion.intersects(targetRowRange)) { continue; } iterators << a->singleTableAdapter->getReadsByRow(r, minRow, maxRow, os); if (os.hasError()) { break; } } if (os.hasError()) { qDeleteAll(iterators); return NULL; } return new MTAReadsIterator(iterators, idExtras); } U2DbiIterator* MultiTableAssemblyAdapter::getReadsByName(const QByteArray& name, U2OpStatus& os) { QVector< U2DbiIterator* > iterators; foreach(MTASingleTableAdapter* a, adapters) { iterators << a->singleTableAdapter->getReadsByName(name, os); if (os.hasError()) { break; } } if (os.hasError()) { qDeleteAll(iterators); return NULL; } return new MTAReadsIterator(iterators, idExtras); } int MultiTableAssemblyAdapter::getElenRangePosById(const U2DataId& id) const { QByteArray extra = SQLiteUtils::toDbExtra(id); SAFE_POINT(extra.size() == 4, QString("Illegal assembly read ID extra part! HEX: %1").arg(extra.toHex().constData()), -1); const qint16* data = (const qint16*)extra.constData(); return int(data[1]); } int MultiTableAssemblyAdapter::getElenRangePosByLength(qint64 readLength) const { int nElenRanges = elenRanges.size(); for (int i = 0; i < nElenRanges; i++) { const U2Region& r = elenRanges[i]; if (r.contains(readLength)) { return i; } } FAIL(QString("Read length does not fit any range: %1, number of ranges: %2").arg(readLength).arg(nElenRanges), nElenRanges - 1); } int MultiTableAssemblyAdapter::getRowRangePosByRow(quint64 row) const { return row / rowsPerRange; } int MultiTableAssemblyAdapter::getRowRangePosById(const U2DataId& id) const { QByteArray extra = SQLiteUtils::toDbExtra(id); SAFE_POINT(extra.size() == 4, QString("Extra part size of assembly read ID is not correct! HEX(Extra): %1").arg(extra.toHex().constData()), -1); const qint16* data = (const qint16*)extra.constData(); return int(data[0]); } static U2DataId addTable2Id(const U2DataId& id, const QByteArray& idExtra) { assert(SQLiteUtils::toDbExtra(id).isEmpty()); U2DataId res = SQLiteUtils::toU2DataId(SQLiteUtils::toDbiId(id), U2Type::AssemblyRead, idExtra); return res; } static void ensureGridSize(QVector > > & grid, int rowPos, int nElens) { int oldRows = grid.size(); if (oldRows > rowPos) { return; } int newRows = rowPos + 1; grid.resize(newRows); for (int r = oldRows; r < newRows; r++) { grid[r].resize(nElens); } } #define N_READS_TO_FLUSH_TOTAL 100000 #define N_READS_TO_FLUSH_PER_RANGE 10000 void MultiTableAssemblyAdapter::addReads(U2DbiIterator* it, U2AssemblyReadsImportInfo& ii, U2OpStatus& os) { bool empty = adaptersGrid.isEmpty(); if (empty) { // TODO: fetch some reads for analysis. By now not needed, since regions are hard-coded anyway initTables(QList(), os); if (os.hasError()) { return; } } bool packIsOn = empty; qint64 prevLeftmostPos = -1; PackAlgorithmContext packContext; QVector > > readsGrid; //reads sorted by range bool lastIteration = false; qint64 readsInGrid = 0; while(!os.isCoR()) { int nElens = elenRanges.size(); if(it->hasNext()) { U2AssemblyRead read = it->next(); if (os.isCoR()) { break; } int readLen = read->readSequence.length(); read->effectiveLen = readLen + U2AssemblyUtils::getCigarExtraLength(read->cigar); int elenPos = getElenRangePosByLength(read->effectiveLen); packIsOn = packIsOn && read->leftmostPos >= prevLeftmostPos; read->packedViewRow = packIsOn ? AssemblyPackAlgorithm::packRead(U2Region(read->leftmostPos, read->effectiveLen), packContext, os): 0; int rowPos = getRowRangePosByRow(read->packedViewRow); ensureGridSize(readsGrid, rowPos, nElens); readsGrid[rowPos][elenPos] << read; ++ii.nReads; ++readsInGrid; } else { lastIteration = true; } int nRows = readsGrid.size(); if(lastIteration || readsInGrid > N_READS_TO_FLUSH_TOTAL) { for (int rowPos = 0; rowPos < nRows && !os.isCoR(); rowPos++) { for (int elenPos = 0; elenPos < nElens && !os.isCoR(); elenPos++) { QList& rangeReads = readsGrid[rowPos][elenPos]; int nRangeReads = rangeReads.size(); if (nRangeReads == 0 || (!lastIteration && nRangeReads < N_READS_TO_FLUSH_PER_RANGE)) { continue; } MTASingleTableAdapter* adapter = getAdapterByRowAndElenRange(rowPos, elenPos, true, os); U2AssemblyReadsImportInfo rangeReadsImportInfo; BufferedDbiIterator rangeReadsIterator(rangeReads); adapter->singleTableAdapter->addReads(&rangeReadsIterator, rangeReadsImportInfo, os); readsInGrid -= rangeReads.size(); rangeReads.clear(); } } } if (lastIteration) { break; } } createReadsIndexes(os); if (packIsOn && !os.hasError()) { ii.packStat.readsCount = ii.nReads; ii.packStat.maxProw = packContext.maxProw; ii.packed = true; flushTables(os); } } MTASingleTableAdapter* MultiTableAssemblyAdapter::getAdapterByRowAndElenRange(int rowPos, int elenPos, bool createIfNotExits, U2OpStatus& os) { int nElens = elenRanges.size(); assert(elenPos < nElens); if (rowPos >= adaptersGrid.size()) { assert(createIfNotExits); if (!createIfNotExits) { return NULL; } int oldRowSize = adaptersGrid.size(); int newRowSize = rowPos + 1; adaptersGrid.resize(newRowSize); for (int i = oldRowSize; i < newRowSize; i++) { adaptersGrid[i].resize(nElens); } } QVector elenAdapters = adaptersGrid.at(rowPos); assert(elenAdapters.size() == nElens); MTASingleTableAdapter* adapter = elenAdapters.at(elenPos); if (adapter == NULL && createIfNotExits) { adapter = createAdapter(rowPos, elenPos, os); } return adapter; } void MultiTableAssemblyAdapter::removeReads(const QList& readIds, U2OpStatus& os) { int nReads = readIds.size(); QHash > readsByAdapter; for (int i = 0; i < nReads; i++) { const U2DataId& readId = readIds[i]; int rowPos = getRowRangePosById(readId); int elenPos = getElenRangePosById(readId); MTASingleTableAdapter* a = getAdapterByRowAndElenRange(rowPos, elenPos, false, os); SAFE_POINT(a != NULL, QString("No table adapter was found! row: %1, elen: %2").arg(rowPos).arg(elenPos),); if (!readsByAdapter.contains(a)) { readsByAdapter[a] = QList(); } readsByAdapter[a].append(readId); } foreach(MTASingleTableAdapter* a, readsByAdapter.keys()) { QList& rangeReadIds = readsByAdapter[a]; a->singleTableAdapter->removeReads(rangeReadIds, os); //TODO: remove adapters for empty tables. And tables as well } } void MultiTableAssemblyAdapter::pack(U2AssemblyPackStat& stat, U2OpStatus& os) { MultiTablePackAlgorithmAdapter packAdapter(this); AssemblyPackAlgorithm::pack(packAdapter, stat, os); packAdapter.releaseDbResources(); quint64 t0 = GTimer::currentTimeMicros(); packAdapter.migrateAll(os); perfLog.trace(QString("Assembly: table migration pack time: %1 seconds").arg((GTimer::currentTimeMicros() - t0) / float(1000*1000))); t0 = GTimer::currentTimeMicros(); // if new tables created during the pack algorithm -> create indexes createReadsIndexes(os); perfLog.trace(QString("Assembly: re-indexing pack time: %1 seconds").arg((GTimer::currentTimeMicros() - t0) / float(1000*1000))); flushTables(os); } void MultiTableAssemblyAdapter::calculateCoverage(const U2Region& region, U2AssemblyCoverageStat& c, U2OpStatus& os) { for(int i = 0; i < adapters.size(); ++i) { MTASingleTableAdapter * a = adapters.at(i); a->singleTableAdapter->calculateCoverage(region, c, os); if (os.isCoR()) { break; } os.setProgress((double(i + 1) / adapters.size()) * 100); } } ////////////////////////////////////////////////////////////////////////// // pack adapter MultiTablePackAlgorithmAdapter::MultiTablePackAlgorithmAdapter(MultiTableAssemblyAdapter* ma) { multiTableAdapter = ma; DbRef* db = multiTableAdapter->getDbRef(); int nElens = multiTableAdapter->getNumberOfElenRanges(); ensureGridSize(nElens); foreach(MTASingleTableAdapter* a , multiTableAdapter->getAdapters()) { SingleTablePackAlgorithmAdapter* sa = new SingleTablePackAlgorithmAdapter(db, a->singleTableAdapter->getReadsTableName()); packAdapters << sa; if (packAdaptersGrid.size() <= a->rowPos) { packAdaptersGrid.resize(a->rowPos + 1); } if(packAdaptersGrid[a->rowPos].size() <= a->elenPos) { packAdaptersGrid[a->rowPos].resize(a->elenPos + 1); } packAdaptersGrid[a->rowPos][a->elenPos] = sa; } } U2DbiIterator* MultiTablePackAlgorithmAdapter::selectAllReads(U2OpStatus& os) { QVector< U2DbiIterator* > iterators; foreach(SingleTablePackAlgorithmAdapter* a, packAdapters) { iterators << a->selectAllReads(os); } return new MTAPackAlgorithmDataIterator(iterators, multiTableAdapter->getIdExtrasPerRange()); } MultiTablePackAlgorithmAdapter::~MultiTablePackAlgorithmAdapter() { qDeleteAll(packAdapters); } void MultiTablePackAlgorithmAdapter::assignProw(const U2DataId& readId, qint64 prow, U2OpStatus& os) { int elenPos = multiTableAdapter->getElenRangePosById(readId); int oldRowPos = multiTableAdapter->getRowRangePosById(readId); int newRowPos = multiTableAdapter->getRowRangePosByRow(prow); SingleTablePackAlgorithmAdapter* sa = NULL; if (newRowPos == oldRowPos) { sa = packAdaptersGrid[oldRowPos][elenPos]; sa->assignProw(readId, prow, os); return; } ensureGridSize(newRowPos + 1); sa = packAdaptersGrid[newRowPos][elenPos]; MTASingleTableAdapter* oldA = multiTableAdapter->getAdapterByRowAndElenRange(oldRowPos, elenPos, false, os); MTASingleTableAdapter* newA = multiTableAdapter->getAdapterByRowAndElenRange(newRowPos, elenPos, true, os); SAFE_POINT(oldA!=NULL, QString("Can't find reads table adapter: row: %1, elen: %2").arg(oldRowPos).arg(elenPos) ,); SAFE_POINT(newA!=NULL, QString("Can't find reads table adapter: row: %1, elen: %2").arg(newRowPos).arg(elenPos) ,); SAFE_POINT_OP(os,); if (sa == NULL) { sa = new SingleTablePackAlgorithmAdapter(multiTableAdapter->getDbRef(), newA->singleTableAdapter->getReadsTableName()); packAdapters << sa; packAdaptersGrid[newRowPos][elenPos] = sa; } QVector& newTableData = migrations[newA]; newTableData.append(ReadTableMigrationData(SQLiteUtils::toDbiId(readId), oldA, prow)); //TODO: add mem check here! } void MultiTablePackAlgorithmAdapter::releaseDbResources() { foreach(SingleTablePackAlgorithmAdapter* a, packAdapters) { a->releaseDbResources(); } } void MultiTablePackAlgorithmAdapter::migrate(MTASingleTableAdapter* newA, const QVector& data, qint64 migratedBefore, qint64 totalMigrationCount, U2OpStatus& os) { SAFE_POINT_OP(os,); //delete reads from old tables, and insert into new one QHash > readsByOldTable; foreach(const ReadTableMigrationData& d, data) { readsByOldTable[d.oldTable].append(d); } DbRef* db = multiTableAdapter->getDbRef(); foreach(MTASingleTableAdapter* oldA, readsByOldTable.keys()) { const QVector& migData = readsByOldTable[oldA]; if (migData.isEmpty()) { continue; } QString oldTable = oldA->singleTableAdapter->getReadsTableName(); QString newTable = newA->singleTableAdapter->getReadsTableName(); QString idsTable = "tmp_mig_" + oldTable; //TODO #ifdef _DEBUG qint64 nOldReads1 = SQLiteQuery("SELECT COUNT(*) FROM " + oldTable, db, os).selectInt64(); qint64 nNewReads1 = SQLiteQuery("SELECT COUNT(*) FROM " + newTable, db, os).selectInt64(); int readsMoved = migData.size(); int rowsPerRange = multiTableAdapter->getRowsPerRange(); U2Region newProwRegion(newA->rowPos * rowsPerRange, rowsPerRange); #endif perfLog.trace(QString("Assembly: running reads migration from %1 to %2 number of reads: %3").arg(oldTable).arg(newTable).arg(migData.size())); quint64 t0 = GTimer::currentTimeMicros(); { //nested block is needed to ensure all queries are finalized SQLiteQuery(QString("CREATE TEMPORARY TABLE %1(id INTEGER PRIMARY KEY, prow INTEGER NOT NULL)").arg(idsTable), db, os).execute(); SQLiteQuery insertIds(QString("INSERT INTO %1(id, prow) VALUES(?1, ?2)").arg(idsTable), db, os); foreach(const ReadTableMigrationData& d, migData) { insertIds.reset(false); insertIds.bindInt64(1, d.readId); insertIds.bindInt32(2, d.newProw); assert(newProwRegion.contains(d.newProw)); insertIds.execute(); if (os.hasError()) { break; } } SQLiteQuery(QString("INSERT INTO %1(prow, name, gstart, elen, flags, mq, data) " "SELECT %3.prow, name, gstart, elen, flags, mq, data FROM %2, %3 WHERE %2.id = %3.id") .arg(newTable).arg(oldTable).arg(idsTable), db, os).execute(); SQLiteQuery(QString("DELETE FROM %1 WHERE id IN (SELECT id FROM %2)").arg(oldTable).arg(idsTable), db, os).execute(); } U2OpStatusImpl osStub; // using stub here -> this operation must be performed even if any of internal queries failed SQLiteQuery(QString("DROP TABLE IF EXISTS %1").arg(idsTable), db, osStub).execute(); qint64 nMigrated = migratedBefore + migData.size(); perfLog.trace(QString("Assembly: reads migration from %1 to %2 finished, time %3 seconds, progress: %4/%5 (%6%)") .arg(oldTable).arg(newTable).arg((GTimer::currentTimeMicros() - t0)/float(1000*1000)) .arg(nMigrated).arg(totalMigrationCount).arg(100*nMigrated/totalMigrationCount)); #ifdef _DEBUG qint64 nOldReads2 = SQLiteQuery("SELECT COUNT(*) FROM " + oldTable, db, os).selectInt64(); qint64 nNewReads2 = SQLiteQuery("SELECT COUNT(*) FROM " + newTable, db, os).selectInt64(); assert(nOldReads1 + nNewReads1 == nOldReads2 + nNewReads2); assert(nNewReads1 + readsMoved == nNewReads2); #endif } } void MultiTablePackAlgorithmAdapter::migrateAll(U2OpStatus& os) { SAFE_POINT_OP(os,); qint64 nReadsToMigrate = 0; foreach(MTASingleTableAdapter* newTable, migrations.keys()) { const QVector& data = migrations[newTable]; nReadsToMigrate+=data.size(); } if (nReadsToMigrate == 0) { return; } qint64 nReadsTotal = multiTableAdapter->countReads(U2_ASSEMBLY_REGION_MAX, os); qint64 migrationPercent = nReadsToMigrate * 100 / nReadsTotal; perfLog.trace(QString("Assembly: starting reads migration process. Reads to migrate: %1, total: %2 (%3%)").arg(nReadsToMigrate).arg(nReadsTotal).arg(migrationPercent)); #define MAX_PERCENT_TO_REINDEX 20 if (migrationPercent > MAX_PERCENT_TO_REINDEX) { perfLog.trace("Assembly: dropping old indexes first"); foreach(MTASingleTableAdapter* adapter, multiTableAdapter->getAdapters()) { adapter->singleTableAdapter->dropReadsIndexes(os); } perfLog.trace("Assembly: indexes are dropped"); } SAFE_POINT_OP(os, ); int nMigrated = 0; foreach(MTASingleTableAdapter* newTable, migrations.keys()) { const QVector& data = migrations[newTable]; migrate(newTable, data, nMigrated, nReadsToMigrate, os); nMigrated+=data.size(); } migrations.clear(); } void MultiTablePackAlgorithmAdapter::ensureGridSize(int nRows) { int oldNRows = packAdaptersGrid.size(); if (oldNRows < nRows) { int nElens = multiTableAdapter->getNumberOfElenRanges(); packAdaptersGrid.resize(nRows); for (int i = oldNRows; i < nRows; i++) { packAdaptersGrid[i].resize(nElens); } } } ////////////////////////////////////////////////////////////////////////// // MTAReadsIterator MTAReadsIterator::MTAReadsIterator(QVector< U2DbiIterator* >& i, const QVector& ie) : iterators (i), currentRange(0), idExtras(ie) { } MTAReadsIterator::~MTAReadsIterator() { qDeleteAll(iterators); } bool MTAReadsIterator::hasNext() { bool res = currentRange < iterators.size(); if (res) { do { U2DbiIterator* it = iterators[currentRange]; res = it->hasNext(); if (res) { break; } currentRange++; } while (currentRange < iterators.size()); } return res; } U2AssemblyRead MTAReadsIterator::next() { U2AssemblyRead res; if (currentRange < iterators.size()) { do { U2DbiIterator* it = iterators[currentRange]; if (it->hasNext()) { res = it->next(); const QByteArray& idExtra = idExtras.at(currentRange);; res->id = addTable2Id(res->id, idExtra); break; } currentRange++; } while (currentRange < iterators.size()); } return res; } U2AssemblyRead MTAReadsIterator::peek() { U2AssemblyRead res; if (currentRange < iterators.size()) { do { U2DbiIterator* it = iterators[currentRange]; if (it->hasNext()) { res = it->peek(); const QByteArray& idExtra = idExtras.at(currentRange);; res->id = addTable2Id(res->id, idExtra); break; } currentRange++; } while (currentRange < iterators.size()); } return res; } ////////////////////////////////////////////////////////////////////////// // MTAPackAlgorithmDataIterator MTAPackAlgorithmDataIterator::MTAPackAlgorithmDataIterator(QVector< U2DbiIterator* >& i, const QVector& ie) : iterators (i), idExtras(ie) { fetchNextData(); } MTAPackAlgorithmDataIterator::~MTAPackAlgorithmDataIterator() { qDeleteAll(iterators); } bool MTAPackAlgorithmDataIterator::hasNext() { return !nextData.readId.isEmpty(); } PackAlgorithmData MTAPackAlgorithmDataIterator::next() { PackAlgorithmData res = nextData; fetchNextData(); return res; } PackAlgorithmData MTAPackAlgorithmDataIterator::peek() { return nextData; } void MTAPackAlgorithmDataIterator::fetchNextData() { PackAlgorithmData bestCandidate; int bestRange = 0; for (int i = 0; i < iterators.size(); i++) { U2DbiIterator* it = iterators[i]; if (!it->hasNext()) { continue; } PackAlgorithmData d = it->peek(); if (bestCandidate.readId.isEmpty() || bestCandidate.leftmostPos > d.leftmostPos) { bestCandidate = d; bestRange = i; } } nextData = bestCandidate; if (!nextData.readId.isEmpty()) { iterators[bestRange]->next(); const QByteArray& idExtra = idExtras.at(bestRange); nextData.readId = addTable2Id(nextData.readId, idExtra); } } } //namespace ugene-1.9.8/src/plugins/dbi_sqlite/src/assembly/AssemblyPackAlgorithm.cpp0000644000175000017500000000640511651544322025250 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "AssemblyPackAlgorithm.h" #include #include #include namespace U2 { static qint64 selectProw(qint64* tails, qint64 start, qint64 end ){ for (int i = 0; i < PACK_TAIL_SIZE; i++) { if (tails[i] <= start) { tails[i] = end; return i; } } return -1; } PackAlgorithmContext::PackAlgorithmContext() { maxProw = 0; nReads = 0; peakEnd = -1; peakRow = PACK_TAIL_SIZE; tails.resize(PACK_TAIL_SIZE); } #define PACK_TRACE_CHECKPOINT 100000 void AssemblyPackAlgorithm::pack(PackAlgorithmAdapter& adapter, U2AssemblyPackStat& stat, U2OpStatus& os) { //Algorithm idea: // select * reads ordered by start position // keep tack (tail) of used rows to assign packed row for reads (N elements) // if all elements are used -> assign -1 to read and postprocess it later GTIMER(c1, t1, "AssemblyPackAlgorithm::pack"); quint64 t0 = GTimer::currentTimeMicros(); int nPacked = 0; stat.maxProw = 0; gauto_array tails(new qint64[PACK_TAIL_SIZE]); qFill(tails.get(), tails.get() + PACK_TAIL_SIZE, -1); std::auto_ptr< U2DbiIterator > allReadsIterator(adapter.selectAllReads(os)); PackAlgorithmContext ctx; while (allReadsIterator->hasNext() && !os.isCoR()) { PackAlgorithmData read = allReadsIterator->next(); int prow = packRead(U2Region(read.leftmostPos, read.effectiveLen), ctx, os); adapter.assignProw(read.readId, prow, os); stat.maxProw = ctx.maxProw; if ((++nPacked % PACK_TRACE_CHECKPOINT) == 0) { perfLog.trace(QString("Assembly: number packed reads so far: %1 of %2 (%3%)").arg(nPacked).arg(stat.readsCount).arg((nPacked/stat.readsCount)*100)); } } assert(stat.readsCount == nPacked); t1.stop(); perfLog.trace(QString("Assembly: algorithm pack time: %1 seconds").arg((GTimer::currentTimeMicros() - t0) / float(1000*1000))); } int AssemblyPackAlgorithm::packRead(const U2Region& reg, PackAlgorithmContext& ctx, U2OpStatus& ) { int prow = selectProw(ctx.tails.data(), reg.startPos, reg.endPos()); if (prow == -1) { if (reg.startPos > ctx.peakEnd) { ctx.peakRow = PACK_TAIL_SIZE; } prow = ctx.peakRow; ctx.peakRow++; ctx.peakEnd = reg.endPos(); } ctx.maxProw = qMax(prow, ctx.maxProw); return prow; } } //namespace ugene-1.9.8/src/plugins/opencl_support/0000755000175000017500000000000011651544323016642 5ustar ilyailyaugene-1.9.8/src/plugins/opencl_support/opencl_support.pro0000644000175000017500000000043311651544323022440 0ustar ilyailyainclude (opencl_support.pri) # Input HEADERS += src/OpenCLSupportPlugin.h \ src/OpenCLSupportSettingsController.h \ SOURCES += src/OpenCLSupportPlugin.cpp \ src/OpenCLSupportSettingsController.cpp \ TRANSLATIONS += transl/english.ts transl/russian.tsugene-1.9.8/src/plugins/opencl_support/opencl_support.pri0000644000175000017500000000037711651544323022441 0ustar ilyailya# include (opencl_support.pri) include( ../../ugene_globals.pri ) use_opencl() { INCLUDEPATH += $$UGENE_OPENCL_INC_DIR PLUGIN_ID=opencl_support PLUGIN_NAME=OpenCL support PLUGIN_VENDOR=Unipro include( ../../ugene_plugin_common.pri ) } #use_opencl ugene-1.9.8/src/plugins/opencl_support/src/0000755000175000017500000000000011651544323017431 5ustar ilyailyaugene-1.9.8/src/plugins/opencl_support/src/OpenCLSupportSettingsController.cpp0000644000175000017500000001321511651544323026441 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include #include #include #include #include #include #include "OpenCLSupportSettingsController.h" namespace U2 { OpenCLSupportSettingsPageController::OpenCLSupportSettingsPageController( const QString & _displayMsg, QObject * p /* = 0 */ ) : AppSettingsGUIPageController( tr("OpenCL"), OpenCLSupportSettingsPageId, p ), displayMsg(_displayMsg) {} AppSettingsGUIPageState * OpenCLSupportSettingsPageController::getSavedState() { QList registeredGpus = AppContext::getOpenCLGpuRegistry()->getRegisteredGpus(); OpenCLSupportSettingsPageState * s = new OpenCLSupportSettingsPageState( registeredGpus.size() ); for( int i = 0, end = s->enabledGpus.size(); i < end; ++i ) { s->enabledGpus[i] = registeredGpus.at(i)->isEnabled(); } return s; } void OpenCLSupportSettingsPageController::saveState( AppSettingsGUIPageState * _s ) { QList registeredGpus = AppContext::getOpenCLGpuRegistry()->getRegisteredGpus(); OpenCLSupportSettingsPageState * s = qobject_cast(_s); //saving state of enabled/disabled GPUs into registry for( int i = 0, end = s->enabledGpus.size(); i < end; ++i ) { registeredGpus[i]->setEnabled( s->enabledGpus[i] ); } //increasing/decreasing maxuse of according resource int totalEnabled = s->enabledGpus.count(true); AppResource * gpuResource = AppResourcePool::instance()->getResource( RESOURCE_OPENCL_GPU ); if( gpuResource ) { gpuResource->maxUse = totalEnabled; } //else - resource was not registered, nothing to do. } AppSettingsGUIPageWidget * OpenCLSupportSettingsPageController::createWidget( AppSettingsGUIPageState* state ) { OpenCLSupportSettingsPageWidget * w = new OpenCLSupportSettingsPageWidget(displayMsg, this); w->setState(state); return w; } OpenCLSupportSettingsPageState::OpenCLSupportSettingsPageState( int num_gpus ) { assert( num_gpus >= 0 ); enabledGpus.resize( num_gpus ); } const static char * gpusDiscoveredText = "The following OpenCL-enabled GPUs are detected.
\ Check the GPUs to use for accelerating algorithms computations."; const static char * noGpusDiscoveredText = "No OpenCL-enabled GPU detected."; OpenCLSupportSettingsPageWidget::OpenCLSupportSettingsPageWidget( const QString & _msg, OpenCLSupportSettingsPageController * /*ctrl*/ ) : onlyMsg(_msg){ if( !onlyMsg.isEmpty() ) { //just display the centered warning message QHBoxLayout* hLayout = new QHBoxLayout(this); QLabel * msgLabel = new QLabel( onlyMsg, this ); msgLabel->setAlignment( Qt::AlignLeft ); hLayout->setAlignment( Qt::AlignTop | Qt::AlignLeft); hLayout->addWidget(msgLabel); hLayout->addStretch(); setLayout(hLayout); } else { //everything is OK - adding info about all available GPUs QVBoxLayout* vLayout = new QVBoxLayout(this); QList gpus = AppContext::getOpenCLGpuRegistry()->getRegisteredGpus(); const QString & actualText = gpus.empty() ? tr(noGpusDiscoveredText) : tr(gpusDiscoveredText); QLabel * gpusDiscoveredLabel = new QLabel( actualText, this ); gpusDiscoveredLabel->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred); vLayout->addWidget( gpusDiscoveredLabel ); foreach( OpenCLGpuModel * m, gpus ) { vLayout->setAlignment( Qt::AlignLeft | Qt::AlignTop ); QHBoxLayout * hLayout = new QHBoxLayout(this); QString gpuText = m->getName() + " " + QString::number(m->getGlobalMemorySizeBytes() / (1024*1024)) + " Mb"; QCheckBox * check = new QCheckBox( gpuText, this ); check->setChecked(true); gpuEnableChecks.push_back(check); hLayout->addWidget(check); vLayout->addLayout( hLayout ); } setLayout(vLayout); } } void OpenCLSupportSettingsPageWidget::setState( AppSettingsGUIPageState * _state ) { OpenCLSupportSettingsPageState * state = qobject_cast(_state); assert( state->enabledGpus.size() == gpuEnableChecks.size() ); for( int i = 0, end = state->enabledGpus.size(); i < end; ++i ) { gpuEnableChecks.at(i)->setChecked( state->enabledGpus.at(i) ); } } AppSettingsGUIPageState* OpenCLSupportSettingsPageWidget::getState( QString & /*err*/ ) const { OpenCLSupportSettingsPageState * state = new OpenCLSupportSettingsPageState( gpuEnableChecks.size() ); assert( state->enabledGpus.size() == gpuEnableChecks.size() ); for( int i = 0, end = state->enabledGpus.size(); i < end; ++i ) { state->enabledGpus[i] = gpuEnableChecks.at(i)->isChecked(); } return state; } } //namespace ugene-1.9.8/src/plugins/opencl_support/src/OpenCLSupportPlugin.cpp0000644000175000017500000002454511651544323024043 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #define _CRT_SECURE_NO_WARNINGS #include #include #include #include #include #include #include "OpenCLSupportPlugin.h" #include "OpenCLSupportSettingsController.h" namespace U2 { extern "C" Q_DECL_EXPORT Plugin * U2_PLUGIN_INIT_FUNC() { OpenCLSupportPlugin * plug = new OpenCLSupportPlugin(); return plug; } const static char * RESOURCE_OPENCL_GPU_NAME = "OpenCLGpu"; OpenCLSupportPlugin::OpenCLSupportPlugin() : Plugin(tr("OpenCL Support"), tr("Plugin provides support for OpenCL-enabled GPUs.") ) { QString err_str; OpenCLSupportError err = obtainGpusInfo( err_str ); if( err_str.isEmpty() && gpus.empty() ) { err_str = "No OpenCL-enabled GPUs found."; } if( Error_NoError == err ) { loadGpusSettings(); registerAvailableGpus(); } else { coreLog.details( err_str ); } //adding settings page if (AppContext::getMainWindow()) { QString settingsPageMsg = getSettingsErrorString(err); AppContext::getAppSettingsGUI()->registerPage( new OpenCLSupportSettingsPageController(settingsPageMsg) ); } //registering gpu resource if( !gpus.empty() ) { AppResource * gpuResource = new AppResource( RESOURCE_OPENCL_GPU, gpus.size(), RESOURCE_OPENCL_GPU_NAME); AppResourcePool::instance()->registerResource( gpuResource ); } } QString OpenCLSupportPlugin::getSettingsErrorString( OpenCLSupportError err ) { switch(err) { case Error_NoError: return QString(""); case Error_BadDriverLib: return tr("Cannot load OpenCL driver dynamic library.

\ Install the latest video GPU driver." ); case Error_OpenCLError: return tr("An error has occurred while obtaining information \ about installed OpenCL GPUs.
\ See OpenCL Support plugin log for details." ); default: assert(false); return QString(); } } OpenCLSupportPlugin::OpenCLSupportError OpenCLSupportPlugin::obtainGpusInfo( QString & errStr ) { //load driver library const OpenCLHelper& openCLHelper = AppContext::getOpenCLGpuRegistry()->getOpenCLHelper(); if (!openCLHelper.isLoaded()) { errStr = openCLHelper.getErrorString(); return Error_BadDriverLib; } cl_int errCode = 0; coreLog.details( tr("Initializing OpenCL") ); //numEntries is the number of cl_platform_id entries that can be added to platforms cl_uint numPlatformEntries = 15; gauto_array platformIDs (new cl_platform_id[numPlatformEntries]); cl_uint numPlatforms = 0; errCode = openCLHelper.clGetPlatformIDs_p(numPlatformEntries, platformIDs.get(), &numPlatforms); if (hasOPENCLError(errCode, errStr)) { return Error_OpenCLError; } coreLog.details(tr("Number of OpenCL platforms: %1").arg(numPlatforms)); //Get each platform info for (unsigned int i = 0; i < numPlatforms; i++) { //numEntries is the number of cl_platform_id entries that can be added to platforms cl_uint numDeviceEntries = 15; gauto_array deviceIDs (new cl_device_id[numDeviceEntries]); cl_uint numDevices = 0; errCode = openCLHelper.clGetDeviceIDs_p(platformIDs.get()[i], CL_DEVICE_TYPE_GPU, numDeviceEntries, deviceIDs.get(), &numDevices); if (hasOPENCLError(errCode, errStr)) { return Error_OpenCLError; } coreLog.details(tr("Number of OpenCL devices: %1").arg(numDevices)); for (unsigned int k = 0; k < numDevices; k++) { cl_device_id deviceId = deviceIDs.get()[k]; int maximumParamLength = 200; gauto_array paramValue (new char[maximumParamLength]); size_t actualParamSize; int actualParamLength = 0; //****************************** errCode = openCLHelper.clGetDeviceInfo_p(deviceId, CL_DEVICE_VENDOR, sizeof(char)*maximumParamLength, paramValue.get(), &actualParamSize); if (hasOPENCLError(errCode, errStr)) { return Error_OpenCLError; } actualParamLength = (actualParamSize) / sizeof(char); gauto_array vendorNameValue(new char[actualParamLength + 1]); strncpy(vendorNameValue.get(), paramValue.get(), actualParamLength); QString vendorName = vendorNameValue.get(); //****************************** errCode = openCLHelper.clGetDeviceInfo_p(deviceId, CL_DEVICE_NAME , sizeof(char)*maximumParamLength, paramValue.get(), &actualParamSize); if (hasOPENCLError(errCode, errStr)) { return Error_OpenCLError; } actualParamLength = (actualParamSize) / sizeof(char); gauto_array deviceNameValue(new char[actualParamLength + 1]); strncpy(deviceNameValue.get(), paramValue.get(), actualParamLength); QString deviceName = deviceNameValue.get(); //****************************** cl_ulong globalMemSize = 0; errCode = openCLHelper.clGetDeviceInfo_p(deviceId, CL_DEVICE_GLOBAL_MEM_SIZE, sizeof(cl_ulong), &globalMemSize, &actualParamSize); if (hasOPENCLError(errCode, errStr)) { return Error_OpenCLError; } //****************************** cl_ulong localMemSize = 0; errCode = openCLHelper.clGetDeviceInfo_p(deviceId, CL_DEVICE_LOCAL_MEM_SIZE , sizeof(cl_ulong), &localMemSize, &actualParamSize); if (hasOPENCLError(errCode, errStr)) { return Error_OpenCLError; } //****************************** cl_uint maxClockFrequency = 0; errCode = openCLHelper.clGetDeviceInfo_p(deviceId, CL_DEVICE_MAX_CLOCK_FREQUENCY , sizeof(cl_uint), &maxClockFrequency, &actualParamSize); if (hasOPENCLError(errCode, errStr)) { return Error_OpenCLError; } //****************************** cl_uint maxComputeUnits = 10; errCode = openCLHelper.clGetDeviceInfo_p(deviceId, CL_DEVICE_MAX_COMPUTE_UNITS, sizeof(cl_uint), &maxComputeUnits, &actualParamSize); if (hasOPENCLError(errCode, errStr)) { return Error_OpenCLError; } //****************************** cl_uint maxWorkItemDimensions = 0; errCode = openCLHelper.clGetDeviceInfo_p(deviceId, CL_DEVICE_MAX_WORK_ITEM_DIMENSIONS, sizeof(cl_uint), &maxWorkItemDimensions, &actualParamSize); if (hasOPENCLError(errCode, errStr)) { return Error_OpenCLError; } //****************************** size_t maxWorkGroupSize = 0; errCode = openCLHelper.clGetDeviceInfo_p(deviceId, CL_DEVICE_MAX_WORK_GROUP_SIZE , sizeof(size_t), &maxWorkGroupSize, &actualParamSize); if (hasOPENCLError(errCode, errStr)) { return Error_OpenCLError; } //create OpenCL model OpenCLGpuModel * openCLGpuModel = new OpenCLGpuModel( vendorName + " " + deviceName, OpenCLGpuId((long)deviceId), (qint64)platformIDs.get()[i], globalMemSize, localMemSize, maxComputeUnits, maxWorkGroupSize, maxClockFrequency); gpus.push_back(openCLGpuModel); coreLog.info( tr("Registering OpenCL-enabled GPU: %1, global mem: %2 Mb, \ local mem: %3 Kb, max compute units: %4, \ max work group size: %5, max frequency: %6 Hz") .arg(openCLGpuModel->getName()) .arg(openCLGpuModel->getGlobalMemorySizeBytes() / (1024 * 1024)) .arg(openCLGpuModel->getLocalMemorySizeBytes() / 1024) .arg(openCLGpuModel->getMaxComputeUnits()) .arg(openCLGpuModel->getMaxWorkGroupSize()) .arg(openCLGpuModel->getMaxClockFrequency())); } } return Error_NoError; } bool OpenCLSupportPlugin::hasOPENCLError(cl_int errCode, QString& errMessage) { //TODO: print details error message if(errCode != CL_SUCCESS) { errMessage = tr("OpenCL error code (%1)").arg(errCode); return true; } else { return false; } } void OpenCLSupportPlugin::registerAvailableGpus() { foreach( OpenCLGpuModel * m, gpus ) { AppContext::getOpenCLGpuRegistry()->registerOpenCLGpu(m); } } void OpenCLSupportPlugin::loadGpusSettings() { Settings * s = AppContext::getSettings(); foreach( OpenCLGpuModel * m, gpus ) { QString key = OPENCL_GPU_REGISTRY_SETTINGS_GPU_SPECIFIC + QString::number(m->getId()) + OPENCL_GPU_SETTINGS_ENABLED; QVariant enabled_v = s->getValue( key ); if( !enabled_v.isNull() ) { m->setEnabled( enabled_v.toBool() ); } else { m->setEnabled( true ); } } } } //namespace ugene-1.9.8/src/plugins/opencl_support/src/OpenCLSupportPlugin.h0000644000175000017500000000327111651544323023501 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef __OPENCL_SUPPORT_PLUGIN_H__ #define __OPENCL_SUPPORT_PLUGIN_H__ #include #include #include namespace U2 { #define ULOG_CAT_PLUGIN_OPENCL_SUPPORT "Plugin: OpenCLSupport" class OpenCLSupportPlugin : public Plugin { Q_OBJECT public: enum OpenCLSupportError { Error_NoError, Error_BadDriverLib, Error_OpenCLError }; OpenCLSupportPlugin(); private: OpenCLSupportError obtainGpusInfo( QString & err ); void loadGpusSettings(); void registerAvailableGpus(); bool hasOPENCLError(cl_int err, QString& errMessage); // static QString getCudaErrorString( CUresult code ); static QString getSettingsErrorString( OpenCLSupportError err ); QList gpus; }; } #endif //__OPENCL_SUPPORT_PLUGIN_H__ ugene-1.9.8/src/plugins/opencl_support/src/OpenCLSupportSettingsController.h0000644000175000017500000000424211651544323026106 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef __OPENCL_SUPPORT_SETTINGS_CONTROLLER__ #define __OPENCL_SUPPORT_SETTINGS_CONTROLLER__ #include #include #include #include namespace U2 { #define OpenCLSupportSettingsPageId QString("oclss") class OpenCLSupportSettingsPageController : public AppSettingsGUIPageController { Q_OBJECT public: OpenCLSupportSettingsPageController( const QString & _displayMsg, QObject * p = 0 ); virtual AppSettingsGUIPageState * getSavedState(); virtual void saveState( AppSettingsGUIPageState * s ); virtual AppSettingsGUIPageWidget * createWidget( AppSettingsGUIPageState* state ); private: QString displayMsg; }; class OpenCLSupportSettingsPageState : public AppSettingsGUIPageState { Q_OBJECT public: OpenCLSupportSettingsPageState( int num_gpus ); QVector enabledGpus; }; class OpenCLSupportSettingsPageWidget : public AppSettingsGUIPageWidget { Q_OBJECT public: OpenCLSupportSettingsPageWidget( const QString & _msg, OpenCLSupportSettingsPageController * ctrl ); virtual void setState( AppSettingsGUIPageState * state ); virtual AppSettingsGUIPageState* getState( QString & err ) const; QString onlyMsg; QList gpuEnableChecks; }; } //namespace #endif //__OPENCL_SUPPORT_SETTINGS_CONTROLLER__ ugene-1.9.8/src/plugins/opencl_support/transl/0000755000175000017500000000000011651544323020145 5ustar ilyailyaugene-1.9.8/src/plugins/opencl_support/transl/russian.ts0000644000175000017500000000523611651544323022207 0ustar ilyailya U2::OpenCLSupportPlugin OpenCL Support Plugin provides support for OpenCL-enabled GPUs. Cannot load OpenCL driver dynamic library.<p> Install the latest video GPU driver. An error has occurred while obtaining information about installed OpenCL GPUs.<br> See OpenCL Support plugin log for details. Initializing OpenCL Number of OpenCL platforms: %1 Number of OpenCL devices: %1 Registering OpenCL-enabled GPU: %1, global mem: %2 Mb, local mem: %3 Kb, max compute units: %4, max work group size: %5, max frequency: %6 Hz OpenCL error code (%1) U2::OpenCLSupportSettingsPageController OpenCL Настройки OpenCL ugene-1.9.8/src/plugins/opencl_support/transl/czech.ts0000644000175000017500000001606711651544323021623 0ustar ilyailya Loading CUDA driver library Loading CUDA driver library Cannot load driver library. Error while loading %1: Cannot load driver library. Error while loading %1: Initializing CUDA Initializing CUDA Cannot resolve symbol Cannot resolve symbol Obtaining number of CUDA-enabled devices Obtaining number of CUDA-enabled devices Cannot resolve symbol Cannot resolve symbol Registering CUDA-enabled GPU: %1, id: %2 Registering CUDA-enabled GPU: %1, id: %2 U2::CudaSupportPlugin CUDA Support CUDA Support Utility plugin for CUDA-enabled GPUs support Utility plugin for CUDA-enabled GPUs support Invalid device Invalid device No cuda-enabled devices found No cuda-enabled devices found Unknown error Unknown error Cannot load CUDA driver dynamic library. It is necessary to install latest Nvidia GPU driver for running GPU-accelerated algorithms on Nvidia hardware. Cannot load CUDA driver dynamic library.It is necessary to install latest Nvidia GPU driver for running GPU-accelerated algorithms on Nvidia hardware. Cannot obtain needed info about Nvidia GPU. Consider reinstallation of GPU driver. See CUDA Support plugin log for details. Cannot obtain needed info about Nvidia GPU.Consider reinstallation of GPU driver. See CUDA Support plugin log for details. An error occured while obtaining information about installed Nvidia GPUs. See CUDA Support plugin log for details An error occured while obtaining information about installed Nvidia GPUs.See CUDA Support plugin log for details Loading CUDA driver library Loading CUDA driver library Cannot load driver library. Error while loading %1: Cannot load driver library. Error while loading %1: Initializing CUDA Initializing CUDA Cannot resolve symbol Cannot resolve symbol Obtaining number of CUDA-enabled devices Obtaining number of CUDA-enabled devices Cannot resolve symbol Cannot resolve symbol Registering CUDA-enabled GPU: %1, id: %2 Registering CUDA-enabled GPU: %1, id: %2 U2::CudaSupportSettingsPageController CUDA Support CUDA Support U2::OpenCLSupportPlugin OpenCL Support Utility plugin for OpenCL-enabled GPUs support Cannot load OpenCL driver dynamic library.<p>It is necessary to install latest video GPU driver for running<br>GPU-accelerated algorithms on OpenCL hardware. An error occurred while obtaining information about installed OpenCL GPUs.<br> See OpenCL Support plugin log for details Initializing OpenCL Number of OpenCL platforms: %1 Number of OpenCL devices: %1 Registering OPENCL-enabled GPU: %1, global mem: %2 Mb, local mem: %3 Kb, max compute units: %4, max work group size: %5, max frequency: %6 Hz OPENCL error code (%1) U2::OpenCLSupportSettingsPageController OpenCL Support ugene-1.9.8/src/plugins/opencl_support/transl/english.ts0000644000175000017500000000522711651544323022154 0ustar ilyailya U2::OpenCLSupportPlugin OpenCL Support Plugin provides support for OpenCL-enabled GPUs. Cannot load OpenCL driver dynamic library.<p> Install the latest video GPU driver. An error has occurred while obtaining information about installed OpenCL GPUs.<br> See OpenCL Support plugin log for details. Initializing OpenCL Number of OpenCL platforms: %1 Number of OpenCL devices: %1 Registering OpenCL-enabled GPU: %1, global mem: %2 Mb, local mem: %3 Kb, max compute units: %4, max work group size: %5, max frequency: %6 Hz OpenCL error code (%1) U2::OpenCLSupportSettingsPageController OpenCL ugene-1.9.8/src/plugins/dotplot/0000755000175000017500000000000011651544322015252 5ustar ilyailyaugene-1.9.8/src/plugins/dotplot/dotplot.pri0000644000175000017500000000023611651544322017454 0ustar ilyailya#include (dotplot.pri) PLUGIN_ID=dotplot PLUGIN_NAME=Dotplot viewer PLUGIN_VENDOR=Unipro PLUGIN_MODE=ui include( ../../ugene_plugin_common.pri ) ugene-1.9.8/src/plugins/dotplot/images/0000755000175000017500000000000011651544322016517 5ustar ilyailyaugene-1.9.8/src/plugins/dotplot/images/hand_icon.png0000644000175000017500000000142411651544322021150 0ustar ilyailyaPNG  IHDRatEXtSoftwareAdobe ImageReadyqe<IDATxtSMK[A=/iЀ$ӍBԂF4]X ֕"EܴE% 76R7nX+nLݥIjPb6n$$ DΝ^f;g9u1y#JcppPBwysrrbymmN Y<`XYY96667>>@N!r } eշEEE~zz BA3ܲooPa(3 hjj2%y ( BKjccZało& /n x$Izt r(@ ѡBĞh4f!+2xɢrGGGbJ^fJƾ>;:r8Uuy}-7NO|J5:88mQҹ+mW]sKtHDW Fy{-~Y|D H PdIDATxL9Ha= H2!@ rr* "l B%hj+i(2BB"<*~Ï}8H|}} \.J%迯RW(2GGG9ԤRڗr\*EzNNNdnGGÃJdsOOO0(tv`0p5\. X^^&&hoo†C)>00?99 h4"bl ZL&TUU]]]555B!2̅Bzà ~~~ 8___ _&a< J|hALFh=ao{{{xxv6NÖq?_-,, Zֳա!h] Hkkksssq||<55ŀ@whL&ĝEJzJs8K&&&X.t~~,ސ&14]]], #ޟlEpqni򽽽LE"6\`vww=&>(+//͢1J%@MBAEPiMZGIENDB`ugene-1.9.8/src/plugins/dotplot/images/exit.png0000644000175000017500000000072611651544322020203 0ustar ilyailyaPNG  IHDRatEXtSoftwareAdobe ImageReadyqe<xIDATxڤSn@(!7P HD:u cʀ(hhh@goX68 7D {y >%wa%fph@۰8S=$\q{tA k5[4/1x{Q\ܱUH1M aĞ5n*K 5nYi4j2akQðn8E\c+φu|=XG5_AJbY̑rW(!K%`djܔLD> 4f^q:gw"L8S=jpnd7pĭK^ IENDB`ugene-1.9.8/src/plugins/dotplot/images/cursor.png0000644000175000017500000000070411651544322020543 0ustar ilyailyaPNG  IHDRatEXtSoftwareAdobe ImageReadyqe<fIDATxb?2~i0>Ā?~2 0 Cݻ, ''Ǐ7o.' %%4$իY$rʲ3… $?0/yyyV!}N #ـ߿3W=zh`A@YY;YGVς0Ȱyf^^^/_sennnMX 9N<```R Ds<==]xqׯm۶-k47ܹv_>}z[^ Y&Oo߾}n3:O9YC5 tw`iii.`i>t(IENDB`ugene-1.9.8/src/plugins/dotplot/images/lock.png0000644000175000017500000000060711651544322020160 0ustar ilyailyaPNG  IHDR7gAMA7tEXtSoftwareAdobe ImageReadyqe<IDAT(cπbZ*=S6MX,VrG [a(X$=č3X$CS0_dƽͭkA( Oгe~uP!w> Oy۽iVEjP؎)7D fNz5azy\gʭ\%ᾘ8Anj2䛑<^az嵌k'3od^Q'X{Mg1.ۚ%F5=',qpkEDR%HOIENDB`ugene-1.9.8/src/plugins/dotplot/src/0000755000175000017500000000000011651544322016041 5ustar ilyailyaugene-1.9.8/src/plugins/dotplot/src/DotPlotPlugin.h0000644000175000017500000000426311651544322020763 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_DOTPLOT_PLUGIN_H_ #define _U2_DOTPLOT_PLUGIN_H_ #include #include namespace U2 { class DotPlotSplitter; class DotPlotWidget; class DotPlotPlugin : public Plugin { Q_OBJECT public: DotPlotPlugin(); private: GObjectViewWindowContext* viewCtx; private slots: void sl_initDotPlotView(); }; class DotPlotViewContext: public GObjectViewWindowContext { Q_OBJECT public: DotPlotViewContext(QObject* p); protected: virtual void initViewContext(GObjectView* view); void createSplitter(); void buildMenu(GObjectView *v, QMenu *m); DotPlotSplitter* getView(GObjectView* view, bool create); void removeDotPlotView(GObjectView* view); private slots: void sl_buildDotPlot(); void sl_removeDotPlot(); void sl_showDotPlotDialog(); void sl_loadTaskStateChanged(Task* task); private: GObjectViewAction* removeDotPlotAction, *addDotPlotAction; bool createdByWizard; QString firstFile; QString secondFile; }; #define DOTPLOT_ACTION_NAME "DOTPLOT_ACTION" class DotPlotViewAction : public ADVSequenceWidgetAction { Q_OBJECT public: DotPlotViewAction() : ADVSequenceWidgetAction(DOTPLOT_ACTION_NAME, tr("Show dot plot")), view(NULL) {} ~DotPlotViewAction(){} DotPlotWidget* view; }; } //namespace #endif ugene-1.9.8/src/plugins/dotplot/src/DotPlotFilesDialog.h0000644000175000017500000000314211651544322021702 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_DOT_PLOT_FILES_DIALOG_H_ #define _U2_DOT_PLOT_FILES_DIALOG_H_ #include namespace U2 { class ADVSequenceObjectContext; class DotPlotFilesDialog : public QDialog, public Ui_DotPlotFilesDialog{ Q_OBJECT public: DotPlotFilesDialog(QWidget *parent); virtual void accept(); QString getFirstFileName() const {return firstFileName;} QString getSecondFileName() const {return secondFileName;} int getFirstGap() const; int getSecondGap() const; protected slots: void sl_openFirstFile(); void sl_openSecondFile(); void sl_oneSequence(); void sl_mergeFirst(); void sl_mergeSecond(); private: QString firstFileName; QString secondFileName; QString filter; }; } //namespace #endif ugene-1.9.8/src/plugins/dotplot/src/DotPlotPlugin.cpp0000644000175000017500000002351011651544322021312 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "DotPlotPlugin.h" #include "DotPlotSplitter.h" #include "DotPlotWidget.h" #include "DotPlotFilesDialog.h" #include "DotPlotTasks.h" #include #include #include #include #include #include #include #include #include #include #include namespace U2 { extern "C" Q_DECL_EXPORT Plugin* U2_PLUGIN_INIT_FUNC() { /*RepeatFinderTaskFactoryRegistry *fr = AppContext::getRepeatFinderTaskFactoryRegistry(); Q_ASSERT(fr); RepeatFinderTaskFactory *factory = fr->getFactory(""); if (!factory) { // can't work without repeat finder algorithm return NULL; }*/ DotPlotPlugin* plug = new DotPlotPlugin(); return plug; } DotPlotPlugin::DotPlotPlugin() : Plugin(tr("Dotplot"), tr("Build dotplot for sequences")), viewCtx(NULL) { connect( AppContext::getPluginSupport(), SIGNAL( si_allStartUpPluginsLoaded() ), SLOT(sl_initDotPlotView())); } void DotPlotPlugin::sl_initDotPlotView() { if (AppContext::getMainWindow()) { RepeatFinderTaskFactoryRegistry *fr = AppContext::getRepeatFinderTaskFactoryRegistry(); RepeatFinderTaskFactory *factory = fr->getFactory(""); if (factory) { viewCtx = new DotPlotViewContext(this); viewCtx->init(); } } } DotPlotViewContext::DotPlotViewContext(QObject* p) : GObjectViewWindowContext(p, AnnotatedDNAViewFactory::ID), createdByWizard(false) { // add dotplot item to the tools menu QAction* showDlgAction = new QAction( QIcon(":dotplot/images/dotplot.png"), tr("Build dotplot..."), this ); connect( showDlgAction, SIGNAL( triggered() ), SLOT( sl_showDotPlotDialog() ) ); AppContext::getMainWindow()->getTopLevelMenu( MWMENU_TOOLS )->addAction( showDlgAction ); // need to know it build dotplot wizard finished work connect( AppContext::getTaskScheduler(), SIGNAL( si_stateChanged(Task*) ), SLOT( sl_loadTaskStateChanged(Task*) ) ); } // wizard finished loading needed files for dotplot void DotPlotViewContext::sl_loadTaskStateChanged(Task* task) { DotPlotLoadDocumentsTask *loadTask = qobject_cast(task); if (!loadTask || !loadTask->isFinished()) { return; } if (loadTask->getStateInfo().hasError()) { DotPlotDialogs::filesOpenError(); return; } if(loadTask->isNoView()){ return; } // prepare document objects to open view with GObjectSelection os; QList docs = loadTask->getDocuments(); foreach (Document* doc, docs) { os.addToSelection(doc->getObjects()); } MultiGSelection ms; ms.addSelection(&os); GObjectViewFactoryRegistry* reg = AppContext::getObjectViewFactoryRegistry(); GObjectViewFactory* f = reg->getFactoryById(AnnotatedDNAViewFactory::ID); bool canCreate = f->canCreateView(ms); if (canCreate) { AppContext::getTaskScheduler()->registerTopLevelTask(f->createViewTask(ms, false)); createdByWizard = true; // set flag that we need to show a dotplot settings dialog firstFile = loadTask->getFirstFile(); secondFile = loadTask->getSecondFile(); } } // DotPlot wizard dialog void DotPlotViewContext::sl_showDotPlotDialog() { Task *tasks = new Task("Creating dotplot", TaskFlag_NoRun); DotPlotFilesDialog d(QApplication::activeWindow()); if (d.exec()) { if (!AppContext::getProject()) { tasks->addSubTask( AppContext::getProjectLoader()->createNewProjectTask() ); } DotPlotLoadDocumentsTask *t = new DotPlotLoadDocumentsTask(d.getFirstFileName(), d.getFirstGap(), d.getSecondFileName(), d.getSecondGap()); tasks->addSubTask(t); } AppContext::getTaskScheduler()->registerTopLevelTask(tasks); } static DNASequenceObject * getSequenceByFile(QString file) { Project *project = AppContext::getProject(); SAFE_POINT(project != NULL, "No project loaded", NULL); Document *doc = project->findDocumentByURL(GUrl(file)); CHECK(doc != NULL, NULL); QList sequences = GObjectUtils::select(doc->getObjects(), GObjectTypes::SEQUENCE, UOF_LoadedOnly); if(! sequences.isEmpty()) { return qobject_cast(sequences.first()); } return NULL; } // called from the context menu void DotPlotViewContext::sl_buildDotPlot() { GObjectViewAction *action = qobject_cast(sender()); if (!action) { return; } // tell in which dnaView we should build dotplot AnnotatedDNAView *dnaView = qobject_cast(action->getObjectView()); if (!dnaView) { return; } DotPlotWidget *dotPlot = new DotPlotWidget(dnaView); dotPlot->setSequences(getSequenceByFile(firstFile), getSequenceByFile(secondFile)); // show settings dialog if (dotPlot && (dotPlot->sl_showSettingsDialog(createdByWizard))) { DotPlotSplitter* splitter = getView(dnaView, true); // create new splitter Q_ASSERT(splitter); splitter->addView(dotPlot); connect (dotPlot, SIGNAL(si_removeDotPlot()), SLOT(sl_removeDotPlot())); } else { delete dotPlot; // user clicked cancel button dotPlot = NULL; } createdByWizard = false; } // DotPlotWidget said we should remove it from the splitter void DotPlotViewContext::sl_removeDotPlot() { DotPlotWidget *dotPlot = qobject_cast(sender()); if (!dotPlot) { return; } // get dnaView that contains that DotPlotWidget AnnotatedDNAView *dnaView = dotPlot->getDnaView(); Q_ASSERT(dnaView); // get DotPlotSplitter that contained in dnaView DotPlotSplitter* splitter = getView(dnaView, false); if (splitter) { splitter->removeView(dotPlot); delete dotPlot; dotPlot = NULL; // remove empty splitter from dnaView if (splitter->isEmpty()) { removeDotPlotView(dnaView); } } } // new view context is opened void DotPlotViewContext::initViewContext(GObjectView* v) { AnnotatedDNAView* av = qobject_cast(v); Q_ASSERT(av); // add the dotplot menu item to an analyze menu QString dotPlotBuildString = tr("Build dotplot..."); ADVGlobalAction* act = new ADVGlobalAction(av, QIcon(":dotplot/images/dotplot.png"), dotPlotBuildString, 40, ADVGlobalActionFlags(ADVGlobalActionFlag_AddToAnalyseMenu)); connect(act, SIGNAL(triggered()), SLOT(sl_buildDotPlot())); ADVGlobalAction* tb = new ADVGlobalAction(av, QIcon(":dotplot/images/dotplot.png"), dotPlotBuildString, 40, ADVGlobalActionFlags(ADVGlobalActionFlag_AddToToolbar)); connect(tb, SIGNAL(triggered()), SLOT(sl_buildDotPlot())); // this view context is created by dotplot wizard if (createdByWizard) { // createdByWizard = false; QWidget* widget = av->getWidget()->parentWidget(); Q_ASSERT(widget != NULL); widget->showMaximized(); // show dotplot settings dialog act->trigger(); } } // create if needed and return DotPlotSplitter in the dnaView DotPlotSplitter* DotPlotViewContext::getView(GObjectView* view, bool create) { DotPlotSplitter* dotPlotView = NULL; // search for DotPlotSpliter in the view QList resources = viewResources.value(view); foreach(QObject* r, resources) { dotPlotView = qobject_cast(r); if (dotPlotView!=NULL) { return dotPlotView; } } // create new DotPlotSplitter if (create) { AnnotatedDNAView* av = qobject_cast(view); Q_ASSERT(av); dotPlotView = new DotPlotSplitter(av); av->insertWidgetIntoSplitter(dotPlotView); resources.append(dotPlotView); viewResources.insert(view, resources); } return dotPlotView; } // context menu opened void DotPlotViewContext::buildMenu(U2::GObjectView *v, QMenu *m) { QList resources = viewResources.value(v); foreach(QObject* r, resources) { DotPlotSplitter* dotPlotView = qobject_cast(r); if (dotPlotView && !dotPlotView->isEmpty()) { dotPlotView->buildPopupMenu(m); return; } } } // remove a splitter from the view void DotPlotViewContext::removeDotPlotView(GObjectView* view) { QList resources = viewResources.value(view); foreach(QObject* r, resources) { DotPlotSplitter* dotPlotView = qobject_cast(r); if (dotPlotView) { assert(dotPlotView->isEmpty()); AnnotatedDNAView* av = qobject_cast(view); Q_ASSERT(av); av->unregisterSplitWidget(dotPlotView); resources.removeOne(dotPlotView); viewResources.insert(view, resources); delete dotPlotView; } } } }//namespace ugene-1.9.8/src/plugins/dotplot/src/DotPlotSplitter.cpp0000644000175000017500000002472411651544322021672 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "DotPlotSplitter.h" #include "DotPlotWidget.h" #include #include #include #include #include #include #include //#include //#include #include #include namespace U2 { DotPlotSplitter::DotPlotSplitter(AnnotatedDNAView* a) : ADVSplitWidget(a), locked(false) { QLayout *layout = new QHBoxLayout; if (!layout) { return; } layout->setSpacing(0); layout->setContentsMargins(0,0,3,0); syncLockButton = createToolButton(":core/images/sync_lock.png", tr("Multiple view synchronization lock"), SLOT(sl_toggleSyncLock(bool))); aspectRatioButton = createToolButton(":dotplot/images/aspectRatio.png", tr("Keep aspect ratio"), SLOT(sl_toggleAspectRatio(bool))); zoomInButton = createToolButton(":core/images/zoom_in.png", tr("Zoom in ( + )"), SLOT(sl_toggleZoomIn()), false); zoomOutButton = createToolButton(":core/images/zoom_out.png", tr("Zoom out ( - )"), SLOT(sl_toggleZoomOut()), false); resetZoomingButton = createToolButton(":core/images/zoom_whole.png", tr("Reset zooming (0)"), SLOT(sl_toggleZoomReset()), false); selButton = createToolButton(":dotplot/images/cursor.png", tr("Select tool (S)"), SLOT(sl_toggleSel())); handButton = createToolButton(":dotplot/images/hand_icon.png", tr("Hand tool (H)"), SLOT(sl_toggleHand())); syncLockButton->setAutoRaise(true); syncLockButton->setAutoFillBackground(true); aspectRatioButton->setAutoRaise(true); zoomInButton->setAutoRaise(true); zoomOutButton->setAutoRaise(true); resetZoomingButton->setAutoRaise(true); selButton->setAutoRaise(true); selButton->setChecked(true); handButton->setAutoRaise(true); buttonToolBar = new HBar(this); if (!buttonToolBar) { return; } buttonToolBar->setOrientation(Qt::Vertical); buttonToolBar->setFloatable(false); buttonToolBar->setMovable(false); buttonToolBar->setStyleSheet("background: "); buttonToolBar->addWidget(syncLockButton); // buttonToolBar->addWidget(aspectRatioButton); // todo: not implemented yet buttonToolBar->addWidget(zoomInButton); buttonToolBar->addWidget(zoomOutButton); buttonToolBar->addWidget(resetZoomingButton); buttonToolBar->addWidget(selButton); buttonToolBar->addWidget(handButton); splitter = new QSplitter(Qt::Horizontal); if (!splitter) { return; } layout->addWidget(buttonToolBar); layout->setAlignment(buttonToolBar, Qt::AlignTop); layout->addWidget(splitter); setAcceptDrops(false); setLayout(layout); setFocus(); } QToolButton *DotPlotSplitter::createToolButton(const QIcon& ic, const QString& toolTip, const char *slot, bool checkable) { QToolButton *toolButton = new QToolButton(this); if (toolButton) { toolButton->setIcon(ic); toolButton->setToolTip(toolTip); toolButton->setFixedWidth(20); toolButton->setFixedHeight(20); toolButton->setCheckable(checkable); if (checkable) { connect(toolButton, SIGNAL(toggled(bool)), this, slot); } else { connect(toolButton, SIGNAL(clicked()), this, slot); } } return toolButton; } QToolButton *DotPlotSplitter::createToolButton(const QString& iconPath, const QString& toolTip, const char *slot, bool checkable) { return createToolButton(QIcon(iconPath), toolTip, slot, checkable); } DotPlotSplitter::~DotPlotSplitter() { delete syncLockButton; delete aspectRatioButton; delete zoomInButton; delete zoomOutButton; delete resetZoomingButton; delete handButton; delete selButton; delete buttonToolBar; delete splitter; } void DotPlotSplitter::addView(DotPlotWidget* view) { dotPlotList.append(view); Q_ASSERT(splitter); splitter->addWidget(view); connect(view, SIGNAL(si_dotPlotChanged(ADVSequenceObjectContext*, ADVSequenceObjectContext*, float, float, QPointF)), SLOT(sl_dotPlotChanged(ADVSequenceObjectContext*, ADVSequenceObjectContext*, float, float, QPointF))); connect(view, SIGNAL(si_dotPlotSelecting()), SLOT(sl_dotPlotSelecting())); checkLockButtonState(); view->setFocus(); updateButtonState(); } void DotPlotSplitter::removeView(DotPlotWidget* view) { dotPlotList.removeAll(view); checkLockButtonState(); } typedef QPair QStringPair; void DotPlotSplitter::checkLockButtonState() { QSet dotPlots; bool enableLockButton = false; int dotPlotCount = dotPlotList.count(); foreach (DotPlotWidget *dpWidget, dotPlotList) { QString nameX = dpWidget->getXSequenceName(); QString nameY = dpWidget->getYSequenceName(); if (!nameX.isEmpty() && !nameY.isEmpty()) { QStringPair p; p.first = nameX; p.second = nameY; if (dotPlots.contains(p)) { enableLockButton = true; } else { dotPlots.insert(p); } dpWidget->setIgnorePanView(dotPlotCount > 1); } } if (syncLockButton) { syncLockButton->setEnabled(enableLockButton); if (!enableLockButton) { // disabled button should not be checked syncLockButton->setChecked(false); } } } bool DotPlotSplitter::isEmpty() const{ return dotPlotList.isEmpty(); } // build popup menu for all DotPlotWidgets // each DotPlotWidget defines if it should add menu void DotPlotSplitter::buildPopupMenu(QMenu *m) { foreach (DotPlotWidget *w, dotPlotList) { Q_ASSERT(w); w->buildPopupMenu(m); } } void DotPlotSplitter::sl_toggleSyncLock(bool l) { locked = l; } void DotPlotSplitter::sl_toggleAspectRatio(bool aspectRatio) { bool noFocus = true; foreach (DotPlotWidget *dpWidget, dotPlotList) { if(dpWidget->hasFocus()){ dpWidget->setKeepAspectRatio(aspectRatio); noFocus = false; break; } } if(noFocus){ foreach (DotPlotWidget *dpWidget, dotPlotList) { dpWidget->setKeepAspectRatio(aspectRatio); } } } void DotPlotSplitter::sl_toggleZoomIn() { bool noFocus = true; foreach (DotPlotWidget *dpWidget, dotPlotList) { if(dpWidget->hasFocus()){ dpWidget->zoomIn(); noFocus = false; break; } } if(noFocus){ foreach (DotPlotWidget *dpWidget, dotPlotList) { dpWidget->zoomIn(); } } updateButtonState(); } void DotPlotSplitter::sl_toggleZoomOut() { bool noFocus = true; foreach (DotPlotWidget *dpWidget, dotPlotList) { if(dpWidget->hasFocus()){ dpWidget->zoomOut(); noFocus = false; break; } } if(noFocus){ foreach (DotPlotWidget *dpWidget, dotPlotList) { dpWidget->zoomOut(); } } updateButtonState(); } void DotPlotSplitter::sl_toggleZoomReset() { bool noFocus = true; foreach (DotPlotWidget *dpWidget, dotPlotList) { if(dpWidget->hasFocus()){ dpWidget->zoomReset(); noFocus = false; break; } } if(noFocus){ foreach (DotPlotWidget *dpWidget, dotPlotList) { dpWidget->zoomReset(); } } updateButtonState(); } void DotPlotSplitter::sl_toggleSel(){ handButton->setChecked(!selButton->isChecked()); foreach (DotPlotWidget *dpWidget, dotPlotList) { dpWidget->setSelActive(selButton->isChecked()); } } void DotPlotSplitter::sl_toggleHand(){ selButton->setChecked(!handButton->isChecked()); foreach (DotPlotWidget *dpWidget, dotPlotList) { dpWidget->setSelActive(selButton->isChecked()); } } void DotPlotSplitter::sl_dotPlotChanged(ADVSequenceObjectContext* sequenceX, ADVSequenceObjectContext* sequenceY, float shiftX, float shiftY, QPointF zoom) { checkLockButtonState(); if (locked) { foreach (DotPlotWidget* w, dotPlotList) { w->setShiftZoom(sequenceX, sequenceY, shiftX, shiftY, zoom); } update(); } updateButtonState(); } void DotPlotSplitter::sl_dotPlotSelecting() { bool selecting = false; foreach (DotPlotWidget* w, dotPlotList) { selecting = w->hasSelection(); if (selecting) { break; } } } void DotPlotSplitter::updateButtonState(){ bool noFocus = true; foreach (DotPlotWidget *dpWidget, dotPlotList) { if (dpWidget->hasFocus()){ zoomInButton->setEnabled(dpWidget->canZoomIn()); zoomOutButton->setEnabled(dpWidget->canZoomOut()); resetZoomingButton->setEnabled(dpWidget->canZoomOut()); noFocus = false; break; } } if (noFocus && !dotPlotList.isEmpty()){ DotPlotWidget *dpWidget = dotPlotList.first(); zoomInButton->setEnabled(dpWidget->canZoomIn()); zoomOutButton->setEnabled(dpWidget->canZoomOut()); resetZoomingButton->setEnabled(dpWidget->canZoomOut()); handButton->setShortcut(QKeySequence()); selButton->setShortcut(QKeySequence()); zoomInButton->setShortcut(QKeySequence()); zoomOutButton->setShortcut(QKeySequence()); resetZoomingButton->setShortcut(QKeySequence()); } else { handButton->setShortcut('H'); selButton->setShortcut('S'); zoomInButton->setShortcut('+'); zoomOutButton->setShortcut('-'); resetZoomingButton->setShortcut('0'); } } } // namespace ugene-1.9.8/src/plugins/dotplot/src/DotPlotClasses.h0000644000175000017500000000547111651544322021124 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_DOT_PLOT_CLASSES_H_ #define _U2_DOT_PLOT_CLASSES_H_ #include #include #include #include namespace U2 { // mini map on the DotPlotWidget class DotPlotMiniMap { public: DotPlotMiniMap (int bigMapW, int bigMapH, float ratio); void draw(QPainter &p, int shiftX, int shiftY, const QPointF &zoom) const; QRectF getBoundary() const; QPointF fromMiniMap(const QPointF &p, const QPointF &zoom) const; private: int x, y, w, h; float ratio; }; // error messages and dialogs class DotPlotDialogs: QObject { Q_OBJECT public: enum Errors {ErrorOpen, ErrorNames, NoErrors}; static void taskRunning(); static int saveDotPlot(); static void fileOpenError(const QString &filename); static void filesOpenError(); static int loadDifferent(); static void loadWrongFormat(); static void wrongAlphabetTypes(); static void tooManyResults(); }; struct DotPlotResults { DotPlotResults(): x(0), y(0), len(0){}; DotPlotResults(int _x, int _y, int _len):x(_x), y(_y), len(_len){}; int x, y, len; }; // Listener which collect results from an algorithm class DotPlotResultsListener : public RFResultsListener { friend class DotPlotWidget; public: DotPlotResultsListener(); ~DotPlotResultsListener(); void setTask(Task *); virtual void onResult(const RFResult& r); virtual void onResults(const QVector& v); private: QList *dotPlotList; QMutex mutex; bool stateOk; static const int maxResults = 8*1024*1024; Task *rfTask; }; // apply rev-compl transformation for X sequence results class DotPlotRevComplResultsListener : public DotPlotResultsListener { public: DotPlotRevComplResultsListener() : xLen(0) {} virtual void onResult(const RFResult& r); virtual void onResults(const QVector& v); int xLen; }; } // namespace #endif // _U2_DOT_PLOT_CLASSES_H_ ugene-1.9.8/src/plugins/dotplot/src/ui/0000755000175000017500000000000011651544322016456 5ustar ilyailyaugene-1.9.8/src/plugins/dotplot/src/ui/DotPlotFilesDialog.ui0000644000175000017500000001700411651544322022507 0ustar ilyailya DotPlotFilesDialog Qt::ApplicationModal 0 0 476 234 0 0 Build dotplot from sequences :/repeat_finder/repeats_image:/repeat_finder/repeats_image true File with first sequence ... Join all sequences found in the file Qt::Horizontal 40 20 Gap size: Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter false 10000000 Qt::Vertical 20 18 Compare sequence against itself Qt::Vertical 20 18 File with second sequence true ... Join all sequences found in the file Qt::Horizontal 40 20 Gap size: Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter false 10000000 Qt::Vertical 20 5 Qt::Horizontal 40 20 Next true Cancel firstFileEdit openFirstButton mergeFirstCheckBox gapFirst oneSequenceCheckBox secondFileEdit openSecondButton mergeSecondCheckBox gapSecond startButton cancelButton startButton clicked() DotPlotFilesDialog accept() 382 223 273 270 cancelButton clicked() DotPlotFilesDialog reject() 465 223 273 270 ugene-1.9.8/src/plugins/dotplot/src/ui/DotPlotDialog.ui0000644000175000017500000003311211651544322021522 0ustar ilyailya DotPlotDialog Qt::ApplicationModal 0 0 547 328 Dotplot :/repeat_finder/repeats_image:/repeat_finder/repeats_image true Dotplot parameters 0 0 QFrame::Sunken Qt::Horizontal Custom algorithm false Qt::Horizontal Qt::Horizontal 40 20 Qt::Horizontal 40 20 X axis sequence 0 0 Minimum repeat length Y axis sequence Repeats identity 0 0 0 0 Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter bp 2 1000000 1 100 0 0 Heuristic based selection of repeat length so the number of repeats in the sequence will not exceed 1000 1k 0 0 0 0 Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter % 50 100 100 0 0 Resets repeats identity to 100% 100 Qt::Horizontal 87 20 Qt::Horizontal 87 20 Qt::Horizontal 87 20 Qt::Horizontal Search inverted repeats Search direct repeats true false false false Qt::Horizontal 40 20 default default false false false Click to load a sequence from the file system. The sequence will be added to the combo boxes when it is loaded to the project Load Sequence Qt::Horizontal 40 20 OK true Cancel xAxisCombo yAxisCombo loadSequenceButton directCheckBox invertedCheckBox directColorButton directDefaultColorButton invertedColorButton invertedDefaultColorButton algoCheck algoCombo minLenBox minLenHeuristicsButton identityBox hundredPercentButton startButton cancelButton startButton clicked() DotPlotDialog accept() 453 317 273 270 cancelButton clicked() DotPlotDialog reject() 536 317 273 270 algoCheck toggled(bool) algoCombo setEnabled(bool) 127 212 526 213 ugene-1.9.8/src/plugins/dotplot/src/DotPlotTasks.cpp0000644000175000017500000001734111651544322021146 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "DotPlotTasks.h" #include #include #include #include #include #include #include #include #include namespace U2 { void SaveDotPlotTask::run() { QFile file(filename); if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) { return; } QTextStream stream(&file); saveDotPlot(stream); file.close(); } void LoadDotPlotTask::run() { QFile file(filename); if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) { return; } QTextStream stream(&file); if (!loadDotPlot(stream, file.size())) { stateInfo.setError(tr("Wrong dotplot format")); } file.close(); } // check if the file opens DotPlotDialogs::Errors SaveDotPlotTask::checkFile(const QString &filename) { QFile file(filename); if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) { return DotPlotDialogs::ErrorOpen; } file.close(); return DotPlotDialogs::NoErrors; } void SaveDotPlotTask::saveDotPlot(QTextStream &stream){ Q_ASSERT (sequenceX); Q_ASSERT (sequenceY); stream << sequenceX->getGObjectName() << endl; stream << sequenceY->getGObjectName() << endl; stream << minLen << " " << identity << endl; Q_ASSERT(directList); int listSizes = directList->size() + inverseList->size(); Q_ASSERT (listSizes); int i=0; foreach(const DotPlotResults &r, *directList) { if (stateInfo.cancelFlag) { return; } stream << r.x << " " << r.y << " " << r.len << endl; stateInfo.progress = (100*i)/listSizes; i++; } stream << endl << "0 0 0" << endl; Q_ASSERT(inverseList); foreach(const DotPlotResults &r, *inverseList) { if (stateInfo.cancelFlag) { return; } stream << r.x << " " << r.y << " " << r.len << endl; stateInfo.progress = (100*i)/listSizes; i++; } } // check if the file opens and sequence names are the same DotPlotDialogs::Errors LoadDotPlotTask::checkFile(const QString &filename, const QString &seqXName, const QString &seqYName) { QFile file(filename); if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) { return DotPlotDialogs::ErrorOpen; } QTextStream stream(&file); QString readedXName; QString readedYName; readedXName = stream.readLine(); readedYName = stream.readLine(); DotPlotDialogs::Errors err = DotPlotDialogs::NoErrors; if (seqXName != readedXName || seqYName != readedYName) { err = DotPlotDialogs::ErrorNames; } file.close(); return err; } bool LoadDotPlotTask::loadDotPlot(QTextStream &stream, int fileSize) { QString readedXName; QString readedYName; readedXName = stream.readLine(); readedYName = stream.readLine(); // not checking names, just loading dotplot int newMinLen, newIdentity; QList newDotPlotDirectList; QList newDotPlotInverseList; stream >> newMinLen >> newIdentity; if (newMinLen<2 || newIdentity<50) { // wrong format return false; } *inverted = *direct = false; bool readingDirect = true; long count = 0; while (!stream.atEnd() && !stateInfo.cancelFlag) { DotPlotResults r; stream >> r.x >> r.y >> r.len; if (readingDirect && (r.x == 0) && (r.y == 0) && (r.len == 0)) { if (count>0) { *direct = true; count = 0; } readingDirect = false; continue; } if (readingDirect) { newDotPlotDirectList.push_back(r); } else { newDotPlotInverseList.push_back(r); } Q_ASSERT (stream.device()); Q_ASSERT (fileSize); int streamPos = stream.device()->pos(); stateInfo.progress = (100*streamPos)/fileSize; count++; } if (!readingDirect && (count>0)) { *inverted = true; } Q_ASSERT(directList); directList->clear(); *directList = newDotPlotDirectList; Q_ASSERT(inverseList); inverseList->clear(); *inverseList = newDotPlotInverseList; Q_ASSERT(minLen); Q_ASSERT(identity); *minLen = newMinLen; *identity = newIdentity; return true; } DotPlotLoadDocumentsTask::DotPlotLoadDocumentsTask(QString firstF, int firstG, QString secondF, int secondG, bool view) : Task(tr("DotPlot loading"), TaskFlags(TaskFlag_NoRun | TaskFlag_FailOnSubtaskCancel)), noView(!view) { firstFile = firstF; firstGap = firstG; secondFile = secondF; secondGap= secondG; } void DotPlotLoadDocumentsTask::prepare() { // load sequences Document *doc = loadFile(firstFile, firstGap); if (doc) { docs << doc; } if (hasError()) { return; } doc = loadFile(secondFile, secondGap); if (doc) { docs << doc; } } Document *DotPlotLoadDocumentsTask::loadFile(QString inFile, int gapSize) { if(inFile == ""){ return NULL; } GUrl URL(inFile); Project *project = AppContext::getProject(); Q_ASSERT(project); Document *doc = project->findDocumentByURL(URL); // document already present in the project if (doc) { return doc; } QList formats = DocumentUtils::detectFormat(inFile); if (formats.isEmpty()) { stateInfo.setError(tr("Detecting format error for file %1").arg(inFile)); return NULL; } DocumentFormat* format = formats.first().format; Q_ASSERT(format); IOAdapterFactory* iof = AppContext::getIOAdapterRegistry()->getIOAdapterFactoryById(BaseIOAdapters::url2io(URL)); QVariantMap formatSettings; if (gapSize >= 0) { QString mergeToken = DocumentReadingMode_SequenceMergeGapSize; formatSettings[mergeToken] = gapSize; } doc = new Document(format, iof, URL, QList(), formatSettings); doc->setUserModLock(false); addSubTask(new AddDocumentTask(doc)); // add document to the project addSubTask(new LoadUnloadedDocumentTask(doc)); // load document return doc; } DotPlotLoadDocumentsTask::~DotPlotLoadDocumentsTask() { // error while loading documents if (hasError()) { Project *project = AppContext::getProject(); // skip added to the project documents if (project) { QList projectDocs = project->getDocuments(); foreach (Document *doc, projectDocs) { docs.removeAll(doc); } } // delete loaded but not added to the project documents // qDeleteAll(docs); foreach (Document *doc, docs) { // docs.removeAll(doc); delete doc; } } } } // namespace ugene-1.9.8/src/plugins/dotplot/src/DotPlotDialog.h0000644000175000017500000000516311651544322020724 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_DOT_PLOT_DIALOG_H_ #define _U2_DOT_PLOT_DIALOG_H_ #include #include #include namespace U2 { class ADVSequenceObjectContext; class GObject; class AnnotatedDNAView; class DNASequenceObject; class DotPlotDialog : public QDialog, public Ui_DotPlotDialog{ Q_OBJECT public: DotPlotDialog(QWidget *parent, AnnotatedDNAView* currentADV, int minLen, int identity, ADVSequenceObjectContext *seqX, ADVSequenceObjectContext *seqY, bool dir, bool inv, const QColor &dColor = QColor(), const QColor &iColor = QColor(), bool hideLoadSequences = false); virtual void accept(); ADVSequenceObjectContext *getXSeq() const {return xSeq;} ADVSequenceObjectContext *getYSeq() const {return ySeq;} int getMinLen() const; int getMismatches() const; RFAlgorithm getAlgo() const; bool isDirect() const; bool isInverted() const; const QColor& getDirectColor() const {return directColor;} const QColor& getInvertedColor() const {return invertedColor;} protected slots: void sl_minLenHeuristics(); void sl_hundredPercent(); void sl_directInvertedCheckBox(); void sl_directColorButton(); void sl_invertedColorButton(); void sl_directDefaultColorButton(); void sl_invertedDefaultColorButton(); void sl_loadSequenceButton(); void sl_loadTaskStateChanged(Task* t); private: QList sequences; ADVSequenceObjectContext *xSeq, *ySeq; AnnotatedDNAView* adv; QColor directColor, invertedColor; void updateColors(); bool isObjectInADV(GObject* obj); GObject* getGObjectByName(const QString& gObjectName); Task* openSequenceTask; QString curURL; }; } //namespace #endif ugene-1.9.8/src/plugins/dotplot/src/DotPlotTasks.h0000644000175000017500000000710011651544322020603 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_DOT_PLOT_TASKS_H_ #define _U2_DOT_PLOT_TASKS_H_ #include "DotPlotClasses.h" #include #include namespace U2 { class Document; class DNASequenceObject; // save dotplot to the file class SaveDotPlotTask : public Task { Q_OBJECT public: SaveDotPlotTask(const QString &file, QList *dotPlotDirectList, QList *dotPlotInverseList, DNASequenceObject *seqX, DNASequenceObject *seqY, int mLen, int ident) : Task(tr("DotPlot saving"), TaskFlags_FOSCOE), filename(file), directList(dotPlotDirectList), inverseList(dotPlotInverseList), sequenceX(seqX), sequenceY(seqY), minLen(mLen), identity(ident) { tpm = Task::Progress_Manual; }; void run(); static DotPlotDialogs::Errors checkFile(const QString &filename); private: QString filename; QList *directList, *inverseList; DNASequenceObject *sequenceX, *sequenceY; int minLen, identity; void saveDotPlot(QTextStream &stream); }; // load dotplot from file class LoadDotPlotTask : public Task { Q_OBJECT public: LoadDotPlotTask(const QString &file, QList *dotPlotDirectList, QList *dotPlotInverseList, DNASequenceObject *seqX, DNASequenceObject *seqY, int *mLen, int *ident, bool *dir, bool *inv) : Task(tr("DotPlot loading"), TaskFlags_FOSCOE), filename(file), directList(dotPlotDirectList), inverseList(dotPlotInverseList), sequenceX(seqX), sequenceY(seqY), minLen(mLen), identity(ident), direct(dir), inverted(inv) { tpm = Task::Progress_Manual; }; void run(); static DotPlotDialogs::Errors checkFile(const QString &filename, const QString &seqXName, const QString &seqYName); private: QString filename; QList *directList, *inverseList; DNASequenceObject *sequenceX, *sequenceY; int *minLen, *identity; bool *direct, *inverted; bool loadDotPlot(QTextStream &stream, int fileSize); }; // dotplot wizard: load needed files, open sequence view and build dotplot class DotPlotLoadDocumentsTask : public Task { Q_OBJECT public: DotPlotLoadDocumentsTask(QString firstF, int firstG, QString secondF, int secondG, bool view = true); ~DotPlotLoadDocumentsTask(); void run(){}; void prepare(); QList getDocuments() const {return docs;} bool isNoView(){return noView;} QString getFirstFile() { return firstFile; } QString getSecondFile() { return secondFile; } private: QString firstFile, secondFile; int firstGap, secondGap; QList docs; bool noView; Document* loadFile(QString inFile, int gapSize); signals: void si_stateChanged(Task* task); }; } // namespace #endif // _U2_DOT_PLOT_TASKS_H_ ugene-1.9.8/src/plugins/dotplot/src/DotPlotWidget.h0000644000175000017500000001432411651544322020747 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_DOT_PLOT_WIDGET_H_ #define _U2_DOT_PLOT_WIDGET_H_ #include #include #include #include #include #include namespace U2 { class Task; class ADVSequenceObjectContext; class ADVSequenceWidget; class GObjectView; class LRegionsSelection; class DotPlotResultsListener; class DotPlotRevComplResultsListener; class DotPlotMiniMap; struct DotPlotResults; class GSequenceLineView; class DotPlotWidget : public ADVSplitWidget { Q_OBJECT public: DotPlotWidget(AnnotatedDNAView* dnaView); ~DotPlotWidget(); virtual bool acceptsGObject(GObject*) {return false;} virtual void updateState(const QVariantMap&) {} virtual void saveState(QVariantMap&) {} void buildPopupMenu(QMenu *) const; AnnotatedDNAView* getDnaView() const {return dnaView;} void setShiftZoom(ADVSequenceObjectContext*, ADVSequenceObjectContext*, float, float, const QPointF&); bool hasSelection(); void setIgnorePanView(bool); void setKeepAspectRatio(bool); void zoomIn(); void zoomOut(); void zoomReset(); bool canZoomOut(); bool canZoomIn(); void setSelActive(bool state); QString getXSequenceName(); QString getYSequenceName(); void setSequences(DNASequenceObject* seqX, DNASequenceObject* seqY); signals: void si_removeDotPlot(); void si_dotPlotChanged(ADVSequenceObjectContext*, ADVSequenceObjectContext*, float, float, QPointF); void si_dotPlotSelecting(); public slots: bool sl_showSettingsDialog(bool disableLoad = false); private slots: void sl_taskFinished(Task*); void sl_showSaveImageDialog(); bool sl_showSaveFileDialog(); bool sl_showLoadFileDialog(); void sl_showDeleteDialog(); void sl_onSequenceSelectionChanged(LRegionsSelection*, const QVector& , const QVector&); void sl_sequenceWidgetRemoved(ADVSequenceWidget*); void sl_panViewChanged(); void sl_timer(); protected: void paintEvent(QPaintEvent *); void resizeEvent(QResizeEvent *); void wheelEvent(QWheelEvent *); void mousePressEvent(QMouseEvent *); void mouseMoveEvent(QMouseEvent *); void mouseReleaseEvent(QMouseEvent *); void focusInEvent(QFocusEvent* fe); void focusOutEvent(QFocusEvent* fe); bool event(QEvent *event); private: AnnotatedDNAView* dnaView; QCursor cursor; bool selecting, shifting, miniMapLooking, selActive, nearestSelecting; LRegionsSelection *selectionX, *selectionY; ADVSequenceObjectContext *sequenceX, *sequenceY; bool direct, inverted, nearestInverted, ignorePanView, keepAspectRatio; QPointF zoom; float shiftX, shiftY; int minLen, identity; bool pixMapUpdateNeeded, deleteDotPlotFlag; Task *dotPlotTask; QPixmap *pixMap; DotPlotMiniMap *miniMap; const DotPlotResults *nearestRepeat; QTimer *timer; QToolButton *exitButton; QPointF clickedFirst, clickedSecond; DotPlotResultsListener* dpDirectResultListener; DotPlotRevComplResultsListener* dpRevComplResultsListener; QAction *showSettingsDialogAction; QAction *saveImageAction; QAction *saveDotPlotAction; QAction *loadDotPlotAction; QAction *deleteDotPlotAction; int textSpace; static const int defaultTextSpace = 30; static const int rulerNotchSize = 2; int w; int h; QColor dotPlotBGColor; QColor dotPlotDirectColor; QColor dotPlotInvertedColor; QColor dotPlotNearestRepeatColor; QByteArray sharedSeqX, sharedSeqY; bool clearedByRepitSel; void pixMapUpdate(); void initActionsAndSignals(); void connectSequenceSelectionSignals(); void drawAll(QPainter&); void drawNames(QPainter&) const; void drawAxises(QPainter&) const; void drawDots(QPainter&); void drawSelection(QPainter&) const; void drawRulers(QPainter&) const; void drawMiniMap(QPainter&) const; void drawNearestRepeat(QPainter&) const; void drawFocus(QPainter& p) const; void sequencesMouseSelection(const QPointF &, const QPointF &); void sequencesCoordsSelection(const QPointF &, const QPointF &); void sequenceClearSelection(); void clearRepeatSelection(); void selectNearestRepeat(const QPointF &); const DotPlotResults* findNearestRepeat(const QPoint &); // sets nearestInverted void calcZooming(const QPointF &oldzoom, const QPointF &newzoom, const QPoint &p, bool emitSignal = true); void multZooming(float multzoom); void resetZooming(); void checkShift(bool emitSignal = true); void updateCursor(); QString makeToolTipText() const; QPointF zoomTo(Qt::Axis axis, const U2Region &lr, bool emitSignal = true); U2Region getVisibleRange(Qt::Axis axis); int getLrDifference(const U2Region &a, const U2Region &b); void miniMapShift(); void drawRectCorrect(QPainter &p, QRectF rect) const; QPoint toInnerCoords(int x, int y) const; QPoint toInnerCoords(const QPoint &p) const; QPointF unshiftedUnzoomed(const QPointF &p) const; QPoint sequenceCoords(const QPointF &c) const; QString getRoundedText(QPainter& p, int num, int size) const; bool getLineToDraw(const DotPlotResults &r, QLine *line, float ratioX, float ratioY, bool invert = false) const; void addCloseDotPlotTask(); void cancelRepeatFinderTask(); }; } // namespace #endif // _U2_DOT_PLOT_WIDGET_H_ ugene-1.9.8/src/plugins/dotplot/src/DotPlotWidget.cpp0000644000175000017500000014311511651544322021303 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "DotPlotWidget.h" #include "DotPlotDialog.h" #include "DotPlotTasks.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include namespace U2 { DotPlotWidget::DotPlotWidget(AnnotatedDNAView* dnaView) :ADVSplitWidget(dnaView), selecting(false),shifting(false),miniMapLooking(false), selActive(true), nearestSelecting(false), selectionX(NULL),selectionY(NULL),sequenceX(NULL),sequenceY(NULL), direct(true), inverted(false), nearestInverted(false), ignorePanView(false), keepAspectRatio(false), zoom(1.0f, 1.0f), shiftX(0), shiftY(0), minLen(100), identity(100), pixMapUpdateNeeded(true), deleteDotPlotFlag(false), dotPlotTask(NULL), pixMap(NULL), miniMap(NULL), nearestRepeat(NULL), sharedSeqX(NULL), sharedSeqY(NULL), clearedByRepitSel(false) { dpDirectResultListener = new DotPlotResultsListener(); dpRevComplResultsListener = new DotPlotRevComplResultsListener(); QFontMetrics fm = QPainter(this).fontMetrics(); int minTextSpace = fm.width(" 00000 "); if (defaultTextSpace < minTextSpace) { textSpace = minTextSpace; } else { textSpace = defaultTextSpace; } // border around view w = width() - 2*textSpace; h = height() - 2*textSpace; Q_ASSERT(dnaView); this->dnaView = dnaView; initActionsAndSignals(); dotPlotBGColor = QColor(240, 240, 255); dotPlotNearestRepeatColor = QColor(240, 0, 0); setFocusPolicy(Qt::WheelFocus); timer = new QTimer(this); timer->setInterval(2000); connect(timer, SIGNAL(timeout()), this, SLOT(sl_timer())); exitButton = new QToolButton(this); connect(exitButton, SIGNAL(clicked()), SLOT(sl_showDeleteDialog())); exitButton->setToolTip("Close"); QIcon exitIcon = QIcon(QString(":dotplot/images/exit.png")); exitButton->setIcon(exitIcon); exitButton->setAutoFillBackground(true); exitButton->setAutoRaise(true); } // init menu items, actions and connect signals void DotPlotWidget::initActionsAndSignals() { showSettingsDialogAction = new QAction(tr("Parameters"), this); connect(showSettingsDialogAction, SIGNAL(triggered()), SLOT(sl_showSettingsDialog())); saveImageAction = new QAction(tr("Save as image"), this); connect(saveImageAction, SIGNAL(triggered()), SLOT(sl_showSaveImageDialog())); saveDotPlotAction = new QAction(tr("Save"), this); connect(saveDotPlotAction, SIGNAL(triggered()), SLOT(sl_showSaveFileDialog())); loadDotPlotAction = new QAction(tr("Load"), this); connect(loadDotPlotAction, SIGNAL(triggered()), SLOT(sl_showLoadFileDialog())); deleteDotPlotAction = new QAction(tr("Remove"), this); connect(deleteDotPlotAction, SIGNAL(triggered()), SLOT(sl_showDeleteDialog())); connect(AppContext::getTaskScheduler(), SIGNAL(si_stateChanged(Task*)), SLOT(sl_taskFinished(Task*))); foreach (ADVSequenceWidget *advSeqWidget, dnaView->getSequenceWidgets()) { ADVSingleSequenceWidget *ssw = qobject_cast(advSeqWidget); if (ssw != NULL) { connect (ssw->getPanView(), SIGNAL(si_visibleRangeChanged()), SLOT(sl_panViewChanged())); } } setMouseTracking(true); } // connect signals to know if user clicks on dotplot sequences void DotPlotWidget::connectSequenceSelectionSignals() { if (!(sequenceX && sequenceY)) { return; } Q_ASSERT(dnaView); connect (dnaView, SIGNAL(si_sequenceWidgetRemoved(ADVSequenceWidget*)), SLOT(sl_sequenceWidgetRemoved(ADVSequenceWidget*))); foreach (ADVSequenceObjectContext* ctx, dnaView->getSequenceContexts()) { Q_ASSERT(ctx); connect(ctx->getSequenceSelection(), SIGNAL(si_selectionChanged(LRegionsSelection*, const QVector&, const QVector&)), SLOT(sl_onSequenceSelectionChanged(LRegionsSelection*, const QVector& , const QVector&))); } } DotPlotWidget::~DotPlotWidget() { delete timer; delete showSettingsDialogAction; delete saveImageAction; delete saveDotPlotAction; delete loadDotPlotAction; delete deleteDotPlotAction; delete pixMap; if (dotPlotTask) { cancelRepeatFinderTask(); } delete dpDirectResultListener; delete dpRevComplResultsListener; } // called by DotPlotSplitter void DotPlotWidget::buildPopupMenu(QMenu *m) const { QPoint mapped(mapFromGlobal(QCursor::pos())); // build menu only if the mouse cursor is over this dotplot if (sequenceX && sequenceY && QRect(0, 0, width(), height()).contains(mapped)) { assert(!m->actions().isEmpty()); QMenu* dotPlotMenu = new QMenu(tr("Dotplot"), m); QMenu* saveMenu = new QMenu(tr("Save/Load"), dotPlotMenu); saveMenu->addAction(saveImageAction); saveMenu->addAction(saveDotPlotAction); saveMenu->addAction(loadDotPlotAction); dotPlotMenu->setIcon(QIcon(":dotplot/images/dotplot.png")); dotPlotMenu->addAction(showSettingsDialogAction); dotPlotMenu->addMenu(saveMenu); dotPlotMenu->addAction(deleteDotPlotAction); QAction *b = *(m->actions().begin()); m->insertMenu(b, dotPlotMenu); } } QPointF DotPlotWidget::zoomTo(Qt::Axis axis, const U2Region &lr, bool emitSignal) { if(lr.length == 0){ return zoom; } int seqLen = 0; switch (axis) { case Qt::XAxis : seqLen = sequenceX->getSequenceLen(); zoom.setX(seqLen/(float)lr.length); shiftX = -lr.startPos*w/(float)seqLen; shiftX*=zoom.x(); break; case Qt::YAxis : seqLen = sequenceY->getSequenceLen(); zoom.setY(seqLen/(float)lr.length); shiftY = -lr.startPos*h/(float)seqLen; shiftY*=zoom.y(); break; default: return zoom; } checkShift(emitSignal); pixMapUpdateNeeded = true; update(); return zoom; } U2Region DotPlotWidget::getVisibleRange(Qt::Axis axis) { QPointF zeroPoint(0, 0); QPointF rightPoint(w, 0); QPointF topPoint(0, h); int startPos = 0; int len = 0; switch (axis) { case Qt::XAxis: startPos = sequenceCoords(unshiftedUnzoomed(zeroPoint)).x(); len = sequenceCoords(unshiftedUnzoomed(rightPoint)).x(); break; case Qt::YAxis: startPos = sequenceCoords(unshiftedUnzoomed(zeroPoint)).y(); len = sequenceCoords(unshiftedUnzoomed(topPoint)).y(); break; default: return U2Region(); } len-=startPos; return U2Region(startPos, len); } int DotPlotWidget::getLrDifference(const U2Region &a, const U2Region &b) { return qAbs(a.startPos - b.startPos) + qAbs(a.length - b.length); } void DotPlotWidget::sl_panViewChanged() { GSequenceLineView *lw = qobject_cast(sender()); PanView *panView = qobject_cast(sender()); if (selecting || shifting || !(lw && panView) || nearestSelecting) { return; } U2Region lr = panView->getVisibleRange(); ADVSequenceObjectContext* ctx = lw->getSequenceContext(); if (!ctx || ignorePanView) { return; } U2Region xAxisVisibleRange = getVisibleRange(Qt::XAxis); if ((ctx == sequenceX) && (lr != xAxisVisibleRange)) { zoomTo(Qt::XAxis, lr); } if (!shifting) { U2Region yAxisVisibleRange = getVisibleRange(Qt::YAxis); if ((ctx == sequenceY) && (lr != yAxisVisibleRange)) { if(sequenceX == sequenceY){ zoomTo(Qt::XAxis, lr, sequenceX != sequenceY); }else{ zoomTo(Qt::YAxis, lr, sequenceX != sequenceY); } } } } void DotPlotWidget::sl_timer(){ if (hasFocus() && selActive) { QPoint pos = clickedSecond.toPoint(); pos = sequenceCoords(unshiftedUnzoomed(pos)); const DotPlotResults *res = findNearestRepeat(pos); if(res == nearestRepeat){ QString text = makeToolTipText(); QFont dFont, f("Monospace"); f.setPointSize(dFont.pointSize()); f.setStyleHint(QFont::Courier); QToolTip::setFont(f); QToolTip::showText(QCursor::pos(), text); } } timer->stop(); } void DotPlotWidget::sl_taskFinished(Task *task) { Q_ASSERT(task); if ( task != dotPlotTask || task->getState() != Task::State_Finished) { return; } if (!dpDirectResultListener->stateOk || !dpRevComplResultsListener->stateOk) { DotPlotDialogs::tooManyResults(); } dotPlotTask = NULL; dpDirectResultListener->setTask(NULL); dpRevComplResultsListener->setTask(NULL); if (deleteDotPlotFlag) { deleteDotPlotFlag = false; emit si_removeDotPlot(); return; } // build dotplot task finished pixMapUpdateNeeded = true; update(); } // tell repeat finder that dotPlotResultsListener will be deleted // if dotPlotTask is not RF task, nothing happened void DotPlotWidget::cancelRepeatFinderTask() { RepeatFinderTaskFactoryRegistry *tfr = AppContext::getRepeatFinderTaskFactoryRegistry(); RepeatFinderTaskFactory *factory = tfr->getFactory(""); SAFE_POINT(factory != NULL, "Repeats factory is NULL!", ); factory->setRFResultsListener(dotPlotTask, NULL); MultiTask *mTask = qobject_cast(dotPlotTask); if (mTask) { foreach(Task *t, mTask->getSubtasks()) { if (!t->isFinished()) { t->cancel(); } } } } bool DotPlotWidget::event(QEvent *event){ if (event->type() == QEvent::ToolTip && hasFocus() && selActive) { QHelpEvent *helpEvent = static_cast(event); QPoint pos = toInnerCoords(helpEvent->pos().x(), helpEvent->pos().y()); pos = sequenceCoords(unshiftedUnzoomed(pos)); const DotPlotResults *res = findNearestRepeat(pos); if(res == nearestRepeat){ QString text = makeToolTipText(); QFont dFont, f("Monospace"); f.setPointSize(dFont.pointSize()); f.setStyleHint(QFont::Courier); QToolTip::setFont(f); QToolTip::showText(helpEvent->globalPos(), text); } } return QWidget::event(event); } void DotPlotWidget::sl_sequenceWidgetRemoved(ADVSequenceWidget* w) { bool needed = false; foreach (ADVSequenceObjectContext *deleted, w->getSequenceContexts()) { if (deleted == sequenceX) { sequenceX = NULL; needed = true; } if (deleted == sequenceY) { sequenceY = NULL; needed = true; } } if (needed) { deleteDotPlotFlag = true; if (dotPlotTask) { cancelRepeatFinderTask(); } else { addCloseDotPlotTask(); } } } // click on the sequence view void DotPlotWidget::sl_onSequenceSelectionChanged(LRegionsSelection* s, const QVector&, const QVector&) { QObject *sen = sender(); DNASequenceSelection *dnaSelection = qobject_cast(sen); if (dnaSelection) { const DNASequenceObject *selectedSequence = dnaSelection->getSequenceObject(); if (selectedSequence == sequenceX->getSequenceGObject()) { if(!nearestSelecting) clearedByRepitSel = false; selectionX = s; } if (selectedSequence == sequenceY->getSequenceObject()) { if(!nearestSelecting) clearedByRepitSel = false; selectionY = s; } update(); } emit si_dotPlotSelecting(); } // save dotplot as image void DotPlotWidget::sl_showSaveImageDialog() { exitButton->hide(); ExportImageDialog dialog(this, this->rect()); dialog.exec(); exitButton->show(); } // save dotplot into a dotplot file, return true if successful bool DotPlotWidget::sl_showSaveFileDialog() { LastOpenDirHelper lod("Dotplot"); lod.url = QFileDialog::getSaveFileName(NULL, tr("Save Dotplot"), lod.dir, tr("Dotplot files (*.dpt)")); if (lod.url.length() <= 0) { return false; // Cancel button pressed } // check if file opens DotPlotDialogs::Errors err = SaveDotPlotTask::checkFile(lod.url); switch (err) { case DotPlotDialogs::ErrorOpen: DotPlotDialogs::fileOpenError(lod.url); return false; default: break; } TaskScheduler* ts = AppContext::getTaskScheduler(); if (dotPlotTask) { // Check if there is already some dotPlotTask DotPlotDialogs::taskRunning(); return false; } Q_ASSERT(dpDirectResultListener); Q_ASSERT(sequenceX); Q_ASSERT(sequenceY); dotPlotTask = new SaveDotPlotTask( lod.url, dpDirectResultListener->dotPlotList, dpRevComplResultsListener->dotPlotList, sequenceX->getSequenceObject(), sequenceY->getSequenceObject(), minLen, identity ); ts->registerTopLevelTask(dotPlotTask); return true; } // load dotplot from the dotplot file, return true if successful bool DotPlotWidget::sl_showLoadFileDialog() { LastOpenDirHelper lod("Dotplot"); lod.url = QFileDialog::getOpenFileName(NULL, tr("Load Dotplot"), lod.dir, tr("Dotplot files (*.dpt)")); if (lod.url.length() <= 0) { return false; // Cancel button pressed } if (dotPlotTask) { // Check if there is already some dotPlotTask DotPlotDialogs::taskRunning(); return false; } Q_ASSERT(sequenceX); Q_ASSERT(sequenceY); Q_ASSERT(sequenceX->getSequenceObject()); Q_ASSERT(sequenceY->getSequenceObject()); // check if the file opens and names of the loading sequences same as names of current sequences DotPlotDialogs::Errors err = LoadDotPlotTask::checkFile( lod.url, sequenceX->getSequenceObject()->getGObjectName(), sequenceY->getSequenceObject()->getGObjectName() ); switch (err) { case DotPlotDialogs::ErrorOpen: DotPlotDialogs::fileOpenError(lod.url); return false; case DotPlotDialogs::ErrorNames: if (DotPlotDialogs::loadDifferent() == QMessageBox::Yes) { break; // load dotplot anyway } else { return false; } default: break; } Q_ASSERT(dpDirectResultListener); Q_ASSERT(dpDirectResultListener->dotPlotList); Q_ASSERT(dpRevComplResultsListener); Q_ASSERT(dpRevComplResultsListener->dotPlotList); dotPlotTask = new LoadDotPlotTask( lod.url, dpDirectResultListener->dotPlotList, dpRevComplResultsListener->dotPlotList, sequenceX->getSequenceObject(), sequenceY->getSequenceObject(), &minLen, &identity, &direct, &inverted ); TaskScheduler* ts = AppContext::getTaskScheduler(); ts->registerTopLevelTask(dotPlotTask); pixMapUpdateNeeded = true; update(); return true; } // creating new dotplot or changing settings bool DotPlotWidget::sl_showSettingsDialog(bool disableLoad) { if (dotPlotTask) { // Check if there is already some dotPlotTask DotPlotDialogs::taskRunning(); return false; } Q_ASSERT(dnaView); DotPlotDialog d(this, dnaView, minLen, identity, sequenceX, sequenceY, direct, inverted, dotPlotDirectColor, dotPlotInvertedColor, disableLoad); if (d.exec()) { setMinimumHeight(200); nearestRepeat = NULL; nearestInverted = false; bool res = false; if ((sequenceX != d.getXSeq()) || (sequenceY != d.getYSeq())) { res = true; } sequenceX = d.getXSeq(); sequenceY = d.getYSeq(); if(res){ resetZooming(); } direct = d.isDirect(); inverted = d.isInverted(); Q_ASSERT(direct || inverted); dotPlotDirectColor = d.getDirectColor(); dotPlotInvertedColor = d.getInvertedColor(); Q_ASSERT(d.minLenBox); Q_ASSERT(d.identityBox); minLen = d.minLenBox->value(); identity = d.identityBox->value(); connectSequenceSelectionSignals(); Q_ASSERT(dpDirectResultListener); Q_ASSERT(dpDirectResultListener->dotPlotList); dpDirectResultListener->dotPlotList->clear(); Q_ASSERT(dpRevComplResultsListener); Q_ASSERT(dpRevComplResultsListener->dotPlotList); dpRevComplResultsListener->dotPlotList->clear(); Q_ASSERT(sequenceX); Q_ASSERT(sequenceY); if ((sequenceX->getAlphabet()->getType() != sequenceY->getAlphabet()->getType()) || (sequenceX->getAlphabet()->getType() != DNAAlphabet_NUCL)){ sequenceX = NULL; sequenceY = NULL; DotPlotDialogs::wrongAlphabetTypes(); return false; } Q_ASSERT(sequenceX->getSequenceObject()); Q_ASSERT(sequenceY->getSequenceObject()); DNAAlphabet *al = sequenceX->getAlphabet(); if ((al->getId() == BaseDNAAlphabetIds::NUCL_DNA_DEFAULT()) || (al->getId() == BaseDNAAlphabetIds::NUCL_RNA_DEFAULT())) { al = sequenceY->getAlphabet(); } sharedSeqX = sequenceX->getSequenceObject()->getSequence(); sharedSeqY = sequenceY->getSequenceObject()->getSequence(); RepeatFinderTaskFactoryRegistry *tfr = AppContext::getRepeatFinderTaskFactoryRegistry(); RepeatFinderTaskFactory *factory = tfr->getFactory(""); SAFE_POINT(factory != NULL, "Repeats factory is NULL!", false); QList tasks; if (d.isDirect()) { RepeatFinderSettings cDirect( dpDirectResultListener, sequenceX->getSequenceObject()->getSequence().data(), sequenceX->getSequenceLen(), false, // direct sequenceY->getSequenceObject()->getSequence().data(), sequenceY->getSequenceLen(), al, d.getMinLen(), d.getMismatches(), d.getAlgo() ); Task *dotPlotDirectTask = factory->getTaskInstance(cDirect); dpDirectResultListener->setTask(dotPlotDirectTask); tasks << dotPlotDirectTask; } if (d.isInverted()) { RepeatFinderSettings cInverse( dpRevComplResultsListener, sequenceX->getSequenceObject()->getSequence().constData(), sequenceX->getSequenceLen(), true, // inverted sequenceY->getSequenceObject()->getSequence().constData(), sequenceY->getSequenceLen(), al, d.getMinLen(), d.getMismatches(), d.getAlgo() ); Task *dotPlotInversedTask = factory->getTaskInstance(cInverse); dpRevComplResultsListener->setTask(dotPlotInversedTask); dpRevComplResultsListener->xLen = sequenceX->getSequenceLen(); tasks << dotPlotInversedTask; } dotPlotTask = new MultiTask("Searching repeats", tasks); TaskScheduler* ts = AppContext::getTaskScheduler(); ts->registerTopLevelTask(dotPlotTask); } else { return false; } return true; } // ask user if he wants to save dotplot first void DotPlotWidget::sl_showDeleteDialog() { int answer = DotPlotDialogs::saveDotPlot(); bool saveDotPlot; switch (answer) { case QMessageBox::Cancel: return; case QMessageBox::Yes: saveDotPlot = sl_showSaveFileDialog(); if (!saveDotPlot) { // cancel button pressed return; } break; default: break; } if (!deleteDotPlotFlag) { addCloseDotPlotTask(); } } void DotPlotWidget::addCloseDotPlotTask() { deleteDotPlotFlag = true; Task *t = new Task("Closing dotplot", TaskFlags_NR_FOSCOE); if (!dotPlotTask) { dotPlotTask = t; } AppContext::getTaskScheduler()->registerTopLevelTask(t); } // dotplot results updated, need to update picture void DotPlotWidget::pixMapUpdate() { if (!pixMapUpdateNeeded || !sequenceX || !sequenceY || dotPlotTask) { return; } if ((sequenceX->getSequenceLen() <= 0) || (sequenceY->getSequenceLen() <= 0)) { return; } float ratioX = w/(float)sequenceX->getSequenceLen(); float ratioY = h/(float)sequenceY->getSequenceLen(); //float ratioY = ratioX; delete pixMap; pixMap = new QPixmap(w, h); QPainter pixp(pixMap); pixp.setPen( Qt::NoPen ); // do not draw outline pixp.setBrush(dotPlotBGColor); pixp.drawRect(0, 0, w, h); QLine line; Q_ASSERT(dpDirectResultListener); Q_ASSERT(dpDirectResultListener->dotPlotList); // draw to the dotplot direct results if (direct) { pixp.setPen(dotPlotDirectColor); foreach(const DotPlotResults &r, *dpDirectResultListener->dotPlotList) { if (!getLineToDraw(r, &line, ratioX, ratioY)) { continue; } pixp.drawLine(line); } } // draw to the dotplot inverted results if (inverted) { pixp.setPen(dotPlotInvertedColor); foreach(const DotPlotResults &r, *dpRevComplResultsListener->dotPlotList) { if (!getLineToDraw(r, &line, ratioX, ratioY, true)) { continue; } pixp.drawLine(line); } } pixMapUpdateNeeded = false; } // return true if the line intersects with the area to draw bool DotPlotWidget::getLineToDraw(const DotPlotResults &r, QLine *line, float ratioX, float ratioY, bool invert) const { float x1 = r.x*ratioX * zoom.x() + shiftX; float y1 = r.y*ratioY * zoom.y() + shiftY; float x2 = x1 + r.len*ratioX * zoom.x(); float y2 = y1 + r.len*ratioY * zoom.y(); if ((x2 < 0) || (y2 < 0) || (x1 > w) || (y1 > h)) { return false; } if (x1<0) { float y_0 = y1 - x1*(y2-y1)/(x2-x1); if ((y_0 >= 0) && (y_0 <= h)) { x1 = 0; y1 = y_0; } } if (x2>w) { float y_w = y1 + (w-x1)*(y2-y1)/(x2-x1); if ((y_w >= 0) && (y_w <= h)) { x2 = w; y2 = y_w; } } if (y1<0) { float x_0 = x1 - y1*(x2-x1)/(y2-y1); if ((x_0 >= 0) && (x_0 <= w)) { y1 = 0; x1 = x_0; } } if (y2>h) { float x_h = x1 + (h-y1)*(x2-x1)/(y2-y1); if ((x_h >= 0) && (x_h <= w)) { y2 = h; x2 = x_h; } } if ((x1 < 0) || (x2 < 0) || (y1 < 0) || (y2 < 0) || (x1 > w) || (y1 > h) || (x2 > w) || (y2 > h)) { return false; } Q_ASSERT(line); if (invert) { float tmpX = x1; x1 = x2; x2 = tmpX; } line->setLine(x1, y1, x2, y2); return true; } // draw everything void DotPlotWidget::drawAll(QPainter& p) { if (sequenceX == NULL || sequenceY == NULL || w <= 0 || h <= 0) { return; } p.save(); p.setRenderHint(QPainter::Antialiasing); p.setBrush(QBrush(palette().window().color())); drawNames(p); p.translate(textSpace, textSpace); drawAxises(p); drawDots(p); drawSelection(p); drawMiniMap(p); drawNearestRepeat(p); p.translate(-textSpace, -textSpace); drawRulers(p); p.restore(); if(hasFocus()){ drawFocus(p); } #define DP_MARGIN 2 #define DP_EXIT_BUTTON_SIZE 20 exitButton->setGeometry(width()- DP_MARGIN - DP_EXIT_BUTTON_SIZE, DP_MARGIN, DP_EXIT_BUTTON_SIZE, DP_EXIT_BUTTON_SIZE); } void DotPlotWidget::drawFocus(QPainter& p) const{ p.setPen(QPen(Qt::black, 1, Qt::DotLine)); p.drawRect(0, 0, width()-1, height()-1); } void DotPlotWidget::drawNames(QPainter &p) const { Q_ASSERT(sequenceX->getSequenceObject()); Q_ASSERT(sequenceY->getSequenceObject()); QString nameX = sequenceX->getSequenceObject()->getGObjectName(); QString nameY = sequenceY->getSequenceObject()->getGObjectName(); const QFontMetrics &fm = this->fontMetrics(); nameX += tr(" (min length %1, identity %2%)").arg(minLen).arg(identity); int nameXWidth = fm.width(nameX); // If nameX doesn't fit, it should be aligned left instead of center int flags = (nameXWidth < w) ? Qt::AlignCenter : Qt::AlignVCenter | Qt::AlignLeft; p.drawText(textSpace, h + textSpace, w, textSpace, Qt::AlignCenter, nameX); p.save(); p.rotate(90); p.translate(DP_MARGIN + textSpace, -(w +textSpace*2)); int nameYWidth = fm.width(nameY); // If nameY doesn't fit, it should be aligned left instead of center flags = (nameYWidth < h) ? Qt::AlignCenter : Qt::AlignVCenter | Qt::AlignLeft; p.drawText(0, 0, h, textSpace, flags, nameY); p.restore(); } void DotPlotWidget::drawNearestRepeat(QPainter& p) const { if (!nearestRepeat) { return; } p.save(); p.setPen(dotPlotNearestRepeatColor); float ratioX = w/(float)sequenceX->getSequenceLen(); float ratioY = h/(float)sequenceY->getSequenceLen(); QLine line; if (getLineToDraw(*nearestRepeat, &line, ratioX, ratioY, nearestInverted)) { p.drawLine(line); } p.restore(); } void DotPlotWidget::drawMiniMap(QPainter& p) const { if (miniMap && ((zoom.x() > 1.0f) || (zoom.y() > 1.0f))) { miniMap->draw(p, shiftX, shiftY, zoom); } } // update dotplot picture if needed and draw it void DotPlotWidget::drawDots(QPainter& p) { pixMapUpdate(); if (pixMap) { p.drawPixmap(0, 0, w, h, *pixMap); } } void DotPlotWidget::drawAxises(QPainter& p) const { QPoint zeroPoint(0, 0); QPoint lowLeftPoint(0, h); QPoint topRightPoint(w, 0); p.drawLine(zeroPoint, lowLeftPoint); p.drawLine(zeroPoint, topRightPoint); } // get cutted text to draw rulers QString DotPlotWidget::getRoundedText(QPainter &p, int num, int size) const { QRectF rect; QString curStr = QString::number(num); rect = p.boundingRect(0, 0, size, 100, Qt::AlignLeft | Qt::AlignTop, curStr); if (rect.width() < size) return curStr; curStr = QString::number(num/(float)1000, 'f', 1) + QString("K"); rect = p.boundingRect(0, 0, size, 100, Qt::AlignLeft | Qt::AlignTop, curStr); if (rect.width() < size) return curStr; curStr = QString::number(num/(float)1000000, 'f', 1) + QString("M"); rect = p.boundingRect(0, 0, size, 100, Qt::AlignLeft | Qt::AlignTop, curStr); if (rect.width() < size) return curStr; return ""; } void DotPlotWidget::drawRulers(QPainter &p) const{ GraphUtils::RulerConfig rConf; rConf.notchSize = rulerNotchSize; rConf.textPosition = GraphUtils::LEFT; QFont rulerFont; rulerFont.setFamily("Arial"); rulerFont.setPointSize(8); int startX = sequenceCoords(unshiftedUnzoomed(QPointF(0,0))).x(), endX = sequenceCoords(unshiftedUnzoomed(QPointF(w,0))).x(), startY = sequenceCoords(unshiftedUnzoomed(QPointF(0,0))).y(), endY = sequenceCoords(unshiftedUnzoomed(QPointF(0,h))).y(); QPoint extraLen(0, 0); int xSeqLen = sequenceX->getSequenceLen(); int ySeqLen = sequenceY->getSequenceLen(); if (xSeqLen && ySeqLen) { float ratioX = w/(float)xSeqLen; float ratioY = h/(float)ySeqLen; extraLen = QPoint(0.5*ratioX, 0.5*ratioY); } GraphUtils::drawRuler(p, QPoint(textSpace + extraLen.x(), textSpace), w - 2*extraLen.x(), startX+1, endX, rulerFont, rConf); rConf.direction = GraphUtils::TTB; rConf.textBorderEnd = 10; GraphUtils::drawRuler(p, QPoint(textSpace, textSpace + extraLen.y()), h - 2*extraLen.y(), startY+1, endY, rulerFont, rConf); } // need to draw inside area not containing borders void DotPlotWidget::drawRectCorrect(QPainter &p, QRectF r) const { if ((r.right() < 0) || (r.left() > w) || (r.bottom() < 0) || (r.top() > h)) { return; } if (r.left() < 0) { r.setLeft(0); } if (r.top() < 0) { r.setTop(0); } if (r.right() > w) { r.setRight(w); } if (r.bottom() > h) { r.setBottom(h); } p.drawRect(r); } // part of the sequence is selected, show it void DotPlotWidget::drawSelection(QPainter &p) const{ if (!sequenceX || !sequenceY) { return; } if (!(selectionX || selectionY)) { return; } if(clearedByRepitSel){ return; } p.save(); QPen pen; pen.setStyle(Qt::DotLine); pen.setColor(QColor(0, 125, 227, 200)); p.setPen(pen); p.setBrush(QBrush(QColor(200, 200, 200, 100))); float xLeft, xLen, yBottom, yLen; int xSeqLen = sequenceX->getSequenceLen(); int ySeqLen = sequenceY->getSequenceLen(); Q_ASSERT(xSeqLen); Q_ASSERT(ySeqLen); // for each selected part on the sequence X, highlight selected part on the sequence Y if((selectionX && selectionX->getSelectedRegions().size() > 1)){ const QVector& sel = selectionX->getSelectedRegions(); const U2Region &rx = sel[0]; xLeft = rx.startPos/(float)xSeqLen * w*zoom.x(); xLen = rx.length/(float)xSeqLen * w*zoom.x(); const U2Region &ry = sel[1]; yBottom = ry.startPos/(float)ySeqLen * h*zoom.y(); yLen = ry.length/(float)ySeqLen * h*zoom.y(); drawRectCorrect(p, QRectF(xLeft + shiftX, yBottom + shiftY, xLen, yLen)); }else{ if (selectionX) { foreach(const U2Region &rx, selectionX->getSelectedRegions()) { xLeft = rx.startPos/(float)xSeqLen * w*zoom.x(); xLen = rx.length/(float)xSeqLen * w*zoom.x(); if (!selectionY || selectionY->getSelectedRegions().size() == 0) { yBottom = 0; yLen = 1.0f * h*zoom.y(); drawRectCorrect(p, QRectF(xLeft + shiftX, yBottom + shiftY, xLen, yLen)); } else { foreach(const U2Region &ry, selectionY->getSelectedRegions()) { yBottom = ry.startPos/(float)ySeqLen * h*zoom.y(); yLen = ry.length/(float)ySeqLen * h*zoom.y(); drawRectCorrect(p, QRectF(xLeft + shiftX, yBottom + shiftY, xLen, yLen)); } } } } // user selected only part of the Y sequence if ((!selectionX || selectionX->getSelectedRegions().size() == 0) && (selectionY && selectionY->getSelectedRegions().size() != 0)) { xLeft = 0; xLen = 1.0f * w*zoom.x(); foreach(const U2Region &ry, selectionY->getSelectedRegions()) { yBottom = ry.startPos/(float)ySeqLen * h*zoom.y(); yLen = ry.length/(float)ySeqLen * h*zoom.y(); drawRectCorrect(p, QRectF(xLeft + shiftX, yBottom + shiftY, xLen, yLen)); } } } p.restore(); } // shifted camera or changed zoom void DotPlotWidget::checkShift(bool emitSignal) { if (shiftX > 0) { shiftX = 0; } if (shiftY > 0) { shiftY = 0; } if (shiftX < w*(1-zoom.x())) { shiftX = w*(1-zoom.x()); } if (shiftY < h*(1-zoom.y())) { shiftY = h*(1-zoom.y()); } if (emitSignal) { emit si_dotPlotChanged(sequenceX, sequenceY, shiftX/w, shiftY/h, zoom); } U2Region visRangeX; U2Region visRangeY; foreach (ADVSequenceWidget *advSeqWidget, dnaView->getSequenceWidgets()) { ADVSingleSequenceWidget *advSingleSeqWidget = qobject_cast(advSeqWidget); visRangeX = getVisibleRange(Qt::XAxis); visRangeY = getVisibleRange(Qt::YAxis); if (advSingleSeqWidget->getSequenceContext() == sequenceX) { if (advSingleSeqWidget->getVisibleRange() != getVisibleRange(Qt::XAxis)) { advSingleSeqWidget->setVisibleRange(getVisibleRange(Qt::XAxis)); } } if ((sequenceX != sequenceY) && (advSingleSeqWidget->getSequenceContext() == sequenceY)) { if (advSingleSeqWidget->getVisibleRange() != getVisibleRange(Qt::YAxis)) { advSingleSeqWidget->setVisibleRange(getVisibleRange(Qt::YAxis)); } } } } void DotPlotWidget::calcZooming(const QPointF &oldzoom, const QPointF &nZoom, const QPoint &inner, bool emitSignal) { if (dotPlotTask || (w<=0) || (h<=0)) { return; } if (!(sequenceX && sequenceY)) { return; } float seqLenX = sequenceX->getSequenceLen(); float seqLenY = sequenceY->getSequenceLen(); QPointF newzoom(nZoom); // limit maximum zoom if (newzoom.x() > seqLenX) { newzoom.setX(seqLenX); } if (newzoom.y() > seqLenY) { newzoom.setY(seqLenY); } // dotplot has no zooming and the user tries zoom out if (newzoom.x() < 1.0f) { newzoom.setX(1.0f); } if (newzoom.y() < 1.0f) { newzoom.setY(1.0f); } float xi = (inner.x() - shiftX)/oldzoom.x(); float yi = (inner.y() - shiftY)/oldzoom.y(); shiftX = inner.x() - xi*newzoom.x(); shiftY = inner.y() - yi*newzoom.y(); if (zoom != newzoom) { pixMapUpdateNeeded = true; update(); } zoom = newzoom; checkShift(emitSignal); } void DotPlotWidget::multZooming(float multzoom) { if (multzoom <=0 ) { return; } calcZooming(zoom, zoom*multzoom, QPoint(w/2, h/2)); } void DotPlotWidget::setShiftZoom(ADVSequenceObjectContext* seqX, ADVSequenceObjectContext* seqY, float shX, float shY, const QPointF &z) { shX*=w; shY*=h; if ((sequenceX == seqX) && (sequenceY == seqY)) { if (shiftX!=(int)shX || shiftY!=(int)shY || zoom!=z) { pixMapUpdateNeeded = true; } shiftX = shX; shiftY = shY; zoom = z; update(); } } void DotPlotWidget::setIgnorePanView(bool ignore) { ignorePanView = ignore; } void DotPlotWidget::setKeepAspectRatio(bool keepAr) { keepAspectRatio = keepAr; } void DotPlotWidget::zoomIn() { if (hasSelection()) { if (selectionX && !selectionX->getSelectedRegions().isEmpty()) { zoomTo(Qt::XAxis, selectionX->getSelectedRegions().first()); } if (selectionY && !selectionY->getSelectedRegions().isEmpty()) { if(sequenceX != sequenceY || selectionY->getSelectedRegions().count() == 1){ zoomTo(Qt::YAxis, selectionY->getSelectedRegions().first()); }else{ zoomTo(Qt::YAxis, selectionY->getSelectedRegions().at(1)); } } }else{ multZooming(2.0f); } } void DotPlotWidget::zoomOut() { multZooming(0.5f); } void DotPlotWidget::zoomReset() { resetZooming(); } // translate visible coords to the sequence coords (starts from 0) QPoint DotPlotWidget::sequenceCoords(const QPointF &c) const { Q_ASSERT(sequenceX); Q_ASSERT(sequenceY); int xLen = sequenceX->getSequenceLen(); int yLen = sequenceY->getSequenceLen(); Q_ASSERT(w>0); Q_ASSERT(h>0); int innerX = (c.x() * xLen)/w; int innerY = (c.y() * yLen)/h; return QPoint(innerX, innerY); } // select sequences using sequence coords void DotPlotWidget::sequencesCoordsSelection(const QPointF &start, const QPointF &end) { float startX = start.x(); float startY = start.y(); float endX = end.x(); float endY = end.y(); if (endX < startX) { float tmp = endX; endX = startX; startX = tmp; } if (endY < startY) { float tmp = endY; endY = startY; startY = tmp; } Q_ASSERT(dnaView); foreach (ADVSequenceWidget *w, dnaView->getSequenceWidgets()) { Q_ASSERT(w); foreach (ADVSequenceObjectContext *s, w->getSequenceContexts()) { Q_ASSERT(s); if ( ((int)(endX-startX) > 0) && (s == sequenceX)) { s->getSequenceSelection()->clear(); s->getSequenceSelection()->addRegion(U2Region(startX, endX-startX)); w->centerPosition(startX); } if ( ((int)(endY-startY) > 0) && (s == sequenceY)) { if(sequenceX != sequenceY){ s->getSequenceSelection()->clear(); } s->getSequenceSelection()->addRegion(U2Region(startY, endY-startY)); w->centerPosition(startY); } } } update(); } // select sequences with mouse void DotPlotWidget::sequencesMouseSelection(const QPointF &zoomedA, const QPointF &zoomedB) { if (!(sequenceX || sequenceY)) { return; } if (zoomedA == zoomedB) { selectionX = NULL; selectionY = NULL; return; } QPointF a(unshiftedUnzoomed(zoomedA)); QPointF b(unshiftedUnzoomed(zoomedB)); QPointF start = sequenceCoords(a); QPointF end = sequenceCoords(b); sequencesCoordsSelection(start, end); } // get mouse coords, select the nearest found repeat void DotPlotWidget::selectNearestRepeat(const QPointF &p) { QPoint seqCoords = sequenceCoords(unshiftedUnzoomed(p)); nearestRepeat = findNearestRepeat(seqCoords); if (!nearestRepeat) { return; } nearestSelecting = true; sequencesCoordsSelection( QPoint(nearestRepeat->x, nearestRepeat->y), QPoint(nearestRepeat->x + nearestRepeat->len, nearestRepeat->y + nearestRepeat->len) ); foreach (ADVSequenceWidget *w, dnaView->getSequenceWidgets()) { foreach (ADVSequenceObjectContext *s, w->getSequenceContexts()) { if (s == sequenceX) { w->centerPosition(nearestRepeat->x); } } } nearestSelecting = false; } // get sequence coords, return sequence coords of the nearest repeat const DotPlotResults* DotPlotWidget::findNearestRepeat(const QPoint &p) { const DotPlotResults* need = NULL; float minD = 0; float x = p.x(); float y = p.y(); Q_ASSERT(sequenceX); Q_ASSERT(sequenceY); if ((sequenceX->getSequenceLen() <= 0) || (sequenceY->getSequenceLen() <= 0)) { return NULL; } float ratioX = w/(float)sequenceX->getSequenceLen(); float ratioY = h/(float)sequenceY->getSequenceLen(); ratioX*=ratioX; ratioY*=ratioY; bool first = true; Q_ASSERT (dpDirectResultListener); foreach (const DotPlotResults &r, *dpDirectResultListener->dotPlotList) { float halfLen = r.len/(float)2; float midX = r.x + halfLen; float midY = r.y + halfLen; // square of the distance between two points. ratioX and ratioY are squared float d = (x-midX)*(x-midX)*ratioX + (y-midY)*(y-midY)*ratioY; if (d < minD || first) { minD = d; need = &r; nearestInverted = false; } first = false; } Q_ASSERT (dpRevComplResultsListener); foreach (const DotPlotResults &r, *dpRevComplResultsListener->dotPlotList) { float halfLen = r.len/(float)2; float midX = r.x + halfLen; float midY = r.y + halfLen; // square of the distance between two points. ratioX and ratioY are squared float d = (x-midX)*(x-midX)*ratioX + (y-midY)*(y-midY)*ratioY; if (d < minD || first) { minD = d; need = &r; nearestInverted = true; } first = false; } return need; } // get mouse coords, return coords in the area without border QPoint DotPlotWidget::toInnerCoords(int x, int y) const { x = x - textSpace; y = y - textSpace; if (x > w) { x = w; } if (y > h) { y = h; } if (x < 0) { x = 0; } if (y < 0) { y = 0; } return QPoint(x, y); } QPoint DotPlotWidget::toInnerCoords(const QPoint &p) const { return toInnerCoords(p.x(), p.y()); } void DotPlotWidget::paintEvent(QPaintEvent *e) { QWidget::paintEvent(e); QPainter p(this); drawAll(p); } void DotPlotWidget::resizeEvent(QResizeEvent *e) { Q_ASSERT(e); if (e->oldSize() == e->size()) { return; } int oldw = w; int oldh = h; w = e->size().width() - 2*textSpace; h = e->size().height() - 2*textSpace; // update shift when resizing if (pixMap && (oldw > 0) && (oldh > 0)) { shiftX *= w/(float)(oldw); shiftY *= h/(float)(oldh); } delete miniMap; miniMap = new DotPlotMiniMap(w, h, 10); pixMapUpdateNeeded = true; } // zoom in/zoom out void DotPlotWidget::wheelEvent(QWheelEvent *e) { Q_ASSERT(e); setFocus(); if (dotPlotTask) { return; } QPointF oldzoom = zoom; QPointF newzoom = zoom*(1 + e->delta()/(float)1000); // cursor coords excluding dotplot border calcZooming(oldzoom, newzoom, toInnerCoords(e->pos())); update(); } QString DotPlotWidget::makeToolTipText() const{ if (!nearestRepeat){ return ""; } if (!sequenceX || !sequenceY){ return ""; } int maxRepeatSequenceShowLen = 32; QString text ="HIT: len: %1, match: %2, %: %3\n"; QString coord = "Coordinates(beg.): x: %1 y: %2\n"; QString upLineSeq =""; QString middleLineSeq = ""; QString downLineSeq = ""; QByteArray repX = sequenceX->getSequenceObject()->getSequence().mid(nearestRepeat->x, nearestRepeat->len); QByteArray repY = sequenceY->getSequenceObject()->getSequence().mid(nearestRepeat->y, nearestRepeat->len); if (nearestInverted) { DNATranslation* complT = AppContext::getDNATranslationRegistry()->lookupComplementTranslation(sequenceX->getAlphabet()); assert(complT != NULL); TextUtils::reverse(repX.data(), repX.length()); complT->translate(repX.data(), repX.length()); } int match = 0; for (int i = 0; i < nearestRepeat->len; i++){ if (repX[i] == repY[i]) { match++; } } text = text.arg(nearestRepeat->len).arg(match).arg((float)(match/(float)nearestRepeat->len)*100); coord = coord.arg(nearestRepeat->x + 1).arg(nearestRepeat->y + 1); text.append(coord); for(int i = 0; i < nearestRepeat->len && i < maxRepeatSequenceShowLen; i++) { char rx = repX[i]; char ry = repY[i]; if (rx == ry) { middleLineSeq.append(rx); } else { middleLineSeq.append("*"); } upLineSeq.append(rx); downLineSeq.append(ry); } QString ttt = nearestRepeat->len <= maxRepeatSequenceShowLen ? "\n" : "...\n"; text.append("X: "); text.append(upLineSeq); text.append(ttt); text.append(">: "); text.append(middleLineSeq); text.append(ttt); text.append("Y: "); text.append(downLineSeq); ttt.chop(1); text.append(ttt); return text; } void DotPlotWidget::resetZooming() { calcZooming(zoom, QPointF(1.0f, 1.0f), QPoint(w/2, h/2)); } // user clicked on the minimap void DotPlotWidget::miniMapShift() { Q_ASSERT(miniMap); QPointF fromMiniMap = miniMap->fromMiniMap(clickedSecond, zoom); shiftX = -fromMiniMap.x(); shiftY = -fromMiniMap.y(); checkShift(); pixMapUpdateNeeded = true; update(); } void DotPlotWidget::mousePressEvent(QMouseEvent *e) { setFocus(); Q_ASSERT(e); QWidget::mousePressEvent(e); if (dotPlotTask) { return; } clickedFirst = toInnerCoords(e->pos().x(), e->pos().y()); clickedSecond = clickedFirst; // selecting sequences or using minimap if (e->button() == Qt::LeftButton) { if (miniMap && miniMap->getBoundary().contains(clickedFirst)) { // click on the miniMap miniMapLooking = true; miniMapShift(); return; } if(e->modifiers() & Qt::ControlModifier){ clearRepeatSelection(); }else if(e->modifiers() & Qt::ShiftModifier){ shifting = true; cursor.setShape(Qt::OpenHandCursor); setCursor(cursor); }else if(selActive){ selecting = true; }else{ shifting = true; } } // shifting dotplot view if (e->button() == Qt::MidButton) { shifting = true; } if(timer->isActive()){ timer->stop(); } } // return real coords on the dotplot QPointF DotPlotWidget::unshiftedUnzoomed(const QPointF &p) const { //Q_ASSERT(zoom.manhattanLength()>0); return QPointF((p.x() - shiftX)/zoom.x(), (p.y() - shiftY)/zoom.y()); } void DotPlotWidget::mouseMoveEvent(QMouseEvent *e) { Q_ASSERT(e); QWidget::mouseMoveEvent(e); if (dotPlotTask) { return; } clickedSecond = toInnerCoords(e->pos().x(), e->pos().y()); if (miniMapLooking) { miniMapShift(); return; } QToolTip::showText(e->globalPos(), ""); if (selecting) { if ((clickedFirst.x() != clickedSecond.x()) && (clickedFirst.y() != clickedSecond.y())) { clearedByRepitSel = false; sequencesMouseSelection(clickedFirst, clickedSecond); } } if (shifting) { shiftX += (clickedSecond.x() - clickedFirst.x()); shiftY += (clickedSecond.y() - clickedFirst.y()); clickedFirst = toInnerCoords(e->pos().x(), e->pos().y()); checkShift(); pixMapUpdateNeeded = true; update(); } if(timer->isActive()){ timer->stop(); } } void DotPlotWidget::sequenceClearSelection(){ Q_ASSERT(dnaView); foreach (ADVSequenceWidget *w, dnaView->getSequenceWidgets()) { Q_ASSERT(w); foreach (ADVSequenceObjectContext *s, w->getSequenceContexts()) { Q_ASSERT(s); s->getSequenceSelection()->clear(); } } } QString DotPlotWidget::getXSequenceName() { if (!sequenceX) { return ""; } return sequenceX->getSequenceObject()->getGObjectName(); } QString DotPlotWidget::getYSequenceName() { if (!sequenceY) { return ""; } return sequenceY->getSequenceObject()->getGObjectName(); } void DotPlotWidget::setSequences(DNASequenceObject* seqX, DNASequenceObject* seqY) { CHECK(dnaView != NULL,); if(seqX != NULL) { sequenceX = dnaView->getSequenceContext(seqX); } if(seqY != NULL) { sequenceY = dnaView->getSequenceContext(seqY); } } void DotPlotWidget::mouseReleaseEvent(QMouseEvent *e) { setFocus(); Q_ASSERT(e); if (dotPlotTask) { return; } QWidget::mouseReleaseEvent(e); if (e->button() == Qt::LeftButton) { if(!shifting){ selecting = false; miniMapLooking = false; if (clickedFirst == clickedSecond && !(e->modifiers() & Qt::ControlModifier)) { if(!timer->isActive()){ timer->start(); } sequenceClearSelection(); clearedByRepitSel = true; selectNearestRepeat(clickedFirst); } } shifting = false; updateCursor(); } if (e->button() == Qt::MidButton) { shifting = false; } update(); } bool DotPlotWidget::hasSelection() { if (selectionX) { foreach (const U2Region &lr, selectionX->getSelectedRegions()) { if (lr.length>0) { return true; } } } if (selectionY) { foreach (const U2Region &lr, selectionY->getSelectedRegions()) { if (lr.length>0) { return true; } } } return false; } bool DotPlotWidget::canZoomIn(){ float seqLenX = sequenceX->getSequenceLen(); float seqLenY = sequenceY->getSequenceLen(); return ((zoom.x() < seqLenX) && (zoom.y() < seqLenY)); } bool DotPlotWidget::canZoomOut(){ return ((zoom.x() > 1.0f) || (zoom.y() > 1.0f)); } void DotPlotWidget::setSelActive(bool state){ selActive = state; updateCursor(); } void DotPlotWidget::focusInEvent(QFocusEvent* fe) { QWidget::focusInEvent(fe); emit si_dotPlotChanged(sequenceX, sequenceY, shiftX/w, shiftY/h, zoom); } void DotPlotWidget::focusOutEvent(QFocusEvent* fe){ QWidget::focusOutEvent(fe); emit si_dotPlotChanged(sequenceX, sequenceY, shiftX/w, shiftY/h, zoom); } void DotPlotWidget::updateCursor(){ if(selActive){ cursor.setShape(Qt::ArrowCursor); }else{ cursor.setShape(Qt::OpenHandCursor); } setCursor(cursor); } void DotPlotWidget::clearRepeatSelection(){ nearestRepeat = NULL; clearedByRepitSel = true; update(); } } // namespace ugene-1.9.8/src/plugins/dotplot/src/DotPlotDialog.cpp0000644000175000017500000002607211651544322021261 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "DotPlotDialog.h" #include "DotPlotTasks.h" #include #include #include #include #include #include #include #include #include #include #include namespace U2 { DotPlotDialog::DotPlotDialog(QWidget *parent, AnnotatedDNAView* currentADV, int minLen, int identity, ADVSequenceObjectContext *sequenceX, ADVSequenceObjectContext *sequenceY, bool dir, bool inv, const QColor &dColor, const QColor &iColor, bool hideLoadSequences) : QDialog(parent), xSeq(sequenceX), ySeq(sequenceY), adv(currentADV), directColor(dColor), invertedColor(iColor) ,openSequenceTask(NULL), curURL("") { setupUi(this); SAFE_POINT(adv != NULL, "DotPlotDialog called without view context!", ); directCheckBox->setChecked(dir); invertedCheckBox->setChecked(inv); updateColors(); // set algorithms algoCombo->addItem(tr("Auto"), RFAlgorithm_Auto); algoCombo->addItem(tr("Suffix index"), RFAlgorithm_Suffix); algoCombo->addItem(tr("Diagonals"), RFAlgorithm_Diagonal); int xSeqIndex = -1, ySeqIndex = -1, curIndex = 0; //sequences in the project QList allSequences = GObjectUtils::findAllObjects(UOF_LoadedOnly, GObjectTypes::SEQUENCE); foreach (GObject* obj, allSequences) { DNASequenceObject* seqObj = qobject_cast(obj); QString name = seqObj->getGObjectName(); xAxisCombo->addItem(name); yAxisCombo->addItem(name); if (sequenceX && (sequenceX->getSequenceGObject() == seqObj)) { xSeqIndex = curIndex; } if (sequenceY && (sequenceY->getSequenceGObject() == seqObj)) { ySeqIndex = curIndex; } curIndex++; sequences << seqObj; } if (xSeqIndex >= 0) { xAxisCombo->setCurrentIndex(xSeqIndex); } if (ySeqIndex >= 0) { yAxisCombo->setCurrentIndex(ySeqIndex); } else if (sequences.size() > 1) { // choose the second sequence for Y axis by default yAxisCombo->setCurrentIndex(1); } minLenBox->setValue(minLen); identityBox->setValue(identity); connect(minLenHeuristicsButton, SIGNAL(clicked()), SLOT(sl_minLenHeuristics())); connect(hundredPercentButton, SIGNAL(clicked()), SLOT(sl_hundredPercent())); connect(directCheckBox, SIGNAL(clicked()), SLOT(sl_directInvertedCheckBox())); connect(invertedCheckBox, SIGNAL(clicked()), SLOT(sl_directInvertedCheckBox())); connect(directColorButton, SIGNAL(clicked()), SLOT(sl_directColorButton())); connect(invertedColorButton, SIGNAL(clicked()), SLOT(sl_invertedColorButton())); connect(directDefaultColorButton, SIGNAL(clicked()), SLOT(sl_directDefaultColorButton())); connect(invertedDefaultColorButton, SIGNAL(clicked()), SLOT(sl_invertedDefaultColorButton())); connect(loadSequenceButton, SIGNAL(clicked()), SLOT(sl_loadSequenceButton())); if(hideLoadSequences){ loadSequenceButton->hide(); } } void DotPlotDialog::accept() { int xIdx = xAxisCombo->currentIndex(); int yIdx = yAxisCombo->currentIndex(); SAFE_POINT(xIdx >= 0 && xIdx < sequences.length(), QString("DotPlotDialog: index is out of range: %1").arg(xIdx),); SAFE_POINT(yIdx >= 0 && yIdx < sequences.length(), QString("DotPlotDialog: index is out of range: %1").arg(yIdx),); DNASequenceObject* objX = sequences[xIdx]; DNASequenceObject* objY = sequences[yIdx]; if (!isObjectInADV(objX)) { adv->addObject(objX); } if (!isObjectInADV(objY)) { adv->addObject(objY); } xSeq = adv->getSequenceContext(objX); ySeq = adv->getSequenceContext(objY); QDialog::accept(); } void DotPlotDialog::sl_minLenHeuristics() { identityBox->setValue(100); // formula used here: nVariations / lenVariations = wantedResCount (==1000) // where nVariations == area size // lenVariations = 4^len where len is result // so we have len = ln(nVariations/wantedResCount)/ln(4) int xIdx = xAxisCombo->currentIndex(); int yIdx = yAxisCombo->currentIndex(); DNASequenceObject *objX = sequences.at(xIdx); DNASequenceObject *objY = sequences.at(yIdx); qint64 xSeqLen = objX->getSequenceLen(); qint64 ySeqLen = objY->getSequenceLen(); double nVariations = xSeqLen*ySeqLen; double resCount = 1000; double len = log(nVariations / resCount) / log(double(4)); minLenBox->setValue((int)len); } void DotPlotDialog::sl_hundredPercent() { identityBox->setValue(100); } int DotPlotDialog::getMismatches() const { return (100-identityBox->value()) * minLenBox->value()/ 100; } // which algorithm RFAlgorithm DotPlotDialog::getAlgo() const { if (algoCheck->isChecked()) { int index = algoCombo->currentIndex(); return RFAlgorithm(algoCombo->itemData(index).toInt()); } return RFAlgorithm_Auto; } int DotPlotDialog::getMinLen() const { return minLenBox->value(); } bool DotPlotDialog::isDirect() const { return directCheckBox->isChecked(); } bool DotPlotDialog::isInverted() const { return invertedCheckBox->isChecked(); } void DotPlotDialog::sl_directInvertedCheckBox() { startButton->setEnabled(directCheckBox->isChecked() || invertedCheckBox->isChecked()); } static const QString COLOR_STYLE("QPushButton { background-color: %1 }"); void DotPlotDialog::sl_directColorButton() { QColorDialog d(directColor, this); if (d.exec()) { directColor = d.selectedColor(); directCheckBox->setChecked(true); } updateColors(); } void DotPlotDialog::sl_invertedColorButton() { QColorDialog d(invertedColor, this); if (d.exec()) { invertedColor = d.selectedColor(); invertedCheckBox->setChecked(true); } updateColors(); } void DotPlotDialog::sl_directDefaultColorButton() { directColor = QColor(); directCheckBox->setChecked(true); updateColors(); } void DotPlotDialog::sl_invertedDefaultColorButton() { invertedColor = QColor(); invertedCheckBox->setChecked(true); updateColors(); } void DotPlotDialog::sl_loadSequenceButton(){ QString filter = DialogUtils::prepareDocumentsFileFilterByObjType(GObjectTypes::SEQUENCE, true); LastOpenDirHelper lod("DotPlot file"); lod.url = QFileDialog::getOpenFileName(NULL, tr("Open file"), lod.dir, filter); if(!lod.url.isEmpty()){ Task *tasks = new Task("Adding document to the project", TaskFlag_NoRun); if (!AppContext::getProject()) { tasks->addSubTask( AppContext::getProjectLoader()->createNewProjectTask() ); } //DotPlotLoadDocumentsTask *t = new DotPlotLoadDocumentsTask(lod.url, -1, NULL, -1, false); //tasks->addSubTask(t); QVariantMap hints; hints[ProjectLoaderHint_LoadWithoutView] = true; hints[ProjectLoaderHint_LoadUnloadedDocument] = true; openSequenceTask = AppContext::getProjectLoader()->openWithProjectTask(lod.url, hints); if(openSequenceTask == NULL){ return; } curURL = lod.url; tasks->addSubTask(openSequenceTask); connect( AppContext::getTaskScheduler(), SIGNAL( si_stateChanged(Task*) ), SLOT( sl_loadTaskStateChanged(Task*) ) ); AppContext::getTaskScheduler()->registerTopLevelTask(tasks); } } void DotPlotDialog::sl_loadTaskStateChanged(Task* t){ DotPlotLoadDocumentsTask *loadTask = qobject_cast(t); if (!loadTask || !loadTask->isFinished()) { if(t->isFinished()){ if(curURL == ""){ return; } GUrl URL(curURL); Project *project = AppContext::getProject(); Q_ASSERT(project); Document *doc = project->findDocumentByURL(URL); if (!doc || !doc->isLoaded()) { return; } QList docObjects = doc->getObjects(); foreach (GObject* obj, docObjects) { DNASequenceObject* seqObj = qobject_cast(obj); if (seqObj != NULL){ QString name = seqObj->getGObjectName(); xAxisCombo->addItem(name); yAxisCombo->addItem(name); sequences << seqObj; } } curURL = ""; } return; } if (loadTask->getStateInfo().hasError()) { DotPlotDialogs::filesOpenError(); return; } QList docs = loadTask->getDocuments(); foreach (Document* doc, docs) { QList docObjects = doc->getObjects(); foreach (GObject* obj, docObjects) { DNASequenceObject* seqObj = qobject_cast(obj); if (seqObj != NULL){ QString name = seqObj->getGObjectName(); xAxisCombo->addItem(name); yAxisCombo->addItem(name); sequences << seqObj; } } } } void DotPlotDialog::updateColors() { directColorButton->setStyleSheet(COLOR_STYLE.arg(directColor.name())); invertedColorButton->setStyleSheet(COLOR_STYLE.arg(invertedColor.name())); } bool DotPlotDialog::isObjectInADV(GObject* obj){ SAFE_POINT(obj != NULL, "Object is NULL in DotPlotDialog::isObjectInADV(GObject* obj)", false); QList currentContexts = adv->getSequenceContexts(); bool result = false; foreach(ADVSequenceObjectContext* objContext, currentContexts){ if (objContext->getSequenceGObject()->getGObjectName() == obj->getGObjectName()){ result = true; } } return result; } GObject* DotPlotDialog::getGObjectByName(const QString& gObjectName){ QList allSequences = GObjectUtils::findAllObjects(UOF_LoadedOnly, GObjectTypes::SEQUENCE); GObject* obj = NULL; foreach (GObject* s, allSequences) { if (gObjectName == s->getGObjectName()) { obj = s; } } return obj; } }//namespace ugene-1.9.8/src/plugins/dotplot/src/DotPlotSplitter.h0000644000175000017500000000476711651544322021344 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_DOT_PLOT_SPLITTER_H_ #define _U2_DOT_PLOT_SPLITTER_H_ #include #include class QMenu; class QToolButton; namespace U2 { class GObjectView; class DotPlotWidget; class ADVSequenceObjectContext; class HBar; class DotPlotSplitter : public ADVSplitWidget { Q_OBJECT public: DotPlotSplitter(AnnotatedDNAView*); ~DotPlotSplitter(); virtual bool acceptsGObject(GObject* objects) {Q_UNUSED(objects);return false;} virtual void updateState(const QVariantMap&){}; virtual void saveState(QVariantMap&){}; void addView(DotPlotWidget*); void removeView(DotPlotWidget*); bool isEmpty() const; void buildPopupMenu(QMenu *); private: QToolButton *createToolButton(const QString& iconPath, const QString& toolTip, const char *slot, bool checkable = true); QToolButton *createToolButton(const QIcon& ic, const QString& toolTip, const char *slot, bool checkable = true); QSplitter *splitter; HBar *buttonToolBar; QList dotPlotList; bool locked; QToolButton *syncLockButton, *aspectRatioButton, *zoomInButton, *zoomOutButton, *resetZoomingButton, *zoomToButton, *handButton, *selButton; void updateButtonState(); void checkLockButtonState(); private slots: void sl_toggleSyncLock(bool); void sl_toggleAspectRatio(bool); void sl_toggleSel(); void sl_toggleHand(); void sl_toggleZoomIn(); void sl_toggleZoomOut(); void sl_toggleZoomReset(); void sl_dotPlotChanged(ADVSequenceObjectContext*, ADVSequenceObjectContext*, float, float, QPointF); void sl_dotPlotSelecting(); }; } // namespace #endif // _U2_DOT_PLOT_SPLITTER_H_ ugene-1.9.8/src/plugins/dotplot/src/DotPlotClasses.cpp0000644000175000017500000001233011651544322021447 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "DotPlotClasses.h" namespace U2 { DotPlotMiniMap::DotPlotMiniMap(int bigMapW, int bigMapH, float ratio) { this->ratio = ratio; Q_ASSERT(ratio>0); w = bigMapW/ratio; h = bigMapH/ratio; // coords of the mini map on widget x = bigMapW - w; y = bigMapH - h; } QRectF DotPlotMiniMap::getBoundary() const { return QRectF(x, y, w, h); } // get coordinates on the dotplot picture matching point on the minimap QPointF DotPlotMiniMap::fromMiniMap(const QPointF &p, const QPointF &zoom) const { float lx = p.x() - x; float ly = p.y() - y; return QPointF((lx*zoom.x() - w/2)*ratio, (ly*zoom.y() - h/2)*ratio); } // draw minimap void DotPlotMiniMap::draw(QPainter &p, int shiftX, int shiftY, const QPointF &zoom) const { p.save(); p.setBrush(QBrush(QColor(200, 200, 200, 100))); p.translate(x, y); p.drawRect(0, 0, w, h); QRect r((-shiftX/ratio)/zoom.x(), (-shiftY/ratio)/zoom.y(), w/zoom.x(), h/zoom.y()); if (!r.width()) { r.setWidth(1); } if (!r.height()) { r.setHeight(1); } p.drawRect(r); p.restore(); } DotPlotResultsListener::DotPlotResultsListener() { dotPlotList = new QList(); stateOk = true; rfTask = NULL; } DotPlotResultsListener::~DotPlotResultsListener() { delete dotPlotList; } void DotPlotResultsListener::setTask(Task *t) { rfTask = t; stateOk = true; } // add new found results to the list void DotPlotResultsListener::onResult(const RFResult& r) { QMutexLocker locker(&mutex); if (!dotPlotList) { return; } if (dotPlotList->size() > maxResults) { Q_ASSERT(rfTask); rfTask->cancel(); stateOk = false; return; } DotPlotResults vec(r.x, r.y, r.l); dotPlotList->push_back(vec); } void DotPlotResultsListener::onResults(const QVector& v) { QMutexLocker locker(&mutex); foreach (const RFResult &r, v) { if (!dotPlotList) { return; } if (dotPlotList->size() > maxResults) { Q_ASSERT(rfTask); rfTask->cancel(); stateOk = false; return; } DotPlotResults vec(r.x, r.y, r.l); dotPlotList->push_back(vec); } } // add new found results to the list void DotPlotRevComplResultsListener::onResult(const RFResult& r) { RFResult res(xLen - r.x - r.l, r.y , r.l); assert(res.x >= 0 && res.x < xLen); DotPlotResultsListener::onResult(res); } void DotPlotRevComplResultsListener::onResults(const QVector& v) { QVector results; results.reserve(v.size()); foreach(const RFResult& r, v) { RFResult res(xLen - r.x - r.l, r.y, r.l); assert(res.x >= 0 && res.x < xLen); results << res; } DotPlotResultsListener::onResults(results); } // dialogs and error messages void DotPlotDialogs::taskRunning() { QMessageBox mb(QMessageBox::Critical, tr("Task is already running"), tr("Build or Load DotPlot task is already running")); mb.exec(); } int DotPlotDialogs::saveDotPlot() { QMessageBox mb(QMessageBox::Information, tr("Save dot-plot"), tr("Save dot-plot data before closing?"), QMessageBox::Yes | QMessageBox::No | QMessageBox::Cancel); return mb.exec(); } void DotPlotDialogs::fileOpenError(const QString &filename) { QMessageBox mb(QMessageBox::Critical, tr("File opening error"), tr("Error opening file %1").arg(filename)); mb.exec(); } void DotPlotDialogs::filesOpenError() { QMessageBox mb(QMessageBox::Critical, tr("Error"), tr("Error opening files")); mb.exec(); } int DotPlotDialogs::loadDifferent() { QMessageBox mb(QMessageBox::Critical, tr("Sequences are different"), tr("Current and loading sequences are different. Continue loading dot-plot anyway?"), QMessageBox::Yes | QMessageBox::No); return mb.exec(); } void DotPlotDialogs::loadWrongFormat() { QMessageBox mb(QMessageBox::Critical, tr("Wrong format"), tr("Wrong dot-plot file format, loading aborted")); mb.exec(); } void DotPlotDialogs::wrongAlphabetTypes() { QMessageBox mb(QMessageBox::Critical, tr("Wrong alphabet types"), tr("Both sequence alphabets must be 4-symbols DNA alphabets")); mb.exec(); } void DotPlotDialogs::tooManyResults() { QMessageBox mb(QMessageBox::Critical, tr("Too many results"), tr("Too many results. Try to increase minimum repeat length")); mb.exec(); } } ugene-1.9.8/src/plugins/dotplot/src/DotPlotFilesDialog.cpp0000644000175000017500000000762511651544322022247 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "DotPlotFilesDialog.h" #include #include #include #include namespace U2 { DotPlotFilesDialog::DotPlotFilesDialog(QWidget *parent) : QDialog(parent) { setupUi(this); connect(openFirstButton, SIGNAL(clicked()), SLOT(sl_openFirstFile())); connect(openSecondButton, SIGNAL(clicked()), SLOT(sl_openSecondFile())); connect(oneSequenceCheckBox, SIGNAL(clicked()), SLOT(sl_oneSequence())); connect(mergeFirstCheckBox, SIGNAL(clicked()), SLOT(sl_mergeFirst())); connect(mergeSecondCheckBox, SIGNAL(clicked()), SLOT(sl_mergeSecond())); filter = DialogUtils::prepareDocumentsFileFilterByObjType(GObjectTypes::MULTIPLE_ALIGNMENT, true).append("\n").append( DialogUtils::prepareDocumentsFileFilterByObjType(GObjectTypes::SEQUENCE, false)); } void DotPlotFilesDialog::sl_oneSequence() { secondFileEdit->setDisabled(oneSequenceCheckBox->isChecked()); openSecondButton->setDisabled(oneSequenceCheckBox->isChecked()); mergeSecondCheckBox->setDisabled(oneSequenceCheckBox->isChecked()); gapSecond->setDisabled(oneSequenceCheckBox->isChecked() || !mergeSecondCheckBox->isChecked()); } void DotPlotFilesDialog::sl_mergeFirst() { gapFirst->setDisabled(!mergeFirstCheckBox->isChecked()); } void DotPlotFilesDialog::sl_mergeSecond() { gapSecond->setDisabled(!mergeSecondCheckBox->isChecked()); } // open first file button clicked void DotPlotFilesDialog::sl_openFirstFile() { LastOpenDirHelper lod("DotPlot first file"); lod.url = QFileDialog::getOpenFileName(NULL, tr("Open first file"), lod.dir, filter); Q_ASSERT(firstFileEdit); if (!lod.url.isEmpty()) { firstFileEdit->setText(lod.url); } } // open second file button clicked void DotPlotFilesDialog::sl_openSecondFile() { LastOpenDirHelper lod("DotPlot second file"); if (lod.dir.isEmpty()) { LastOpenDirHelper lodFirst("DotPlot first file"); lod.dir = lodFirst.dir; } lod.url = QFileDialog::getOpenFileName(NULL, tr("Open second file"), lod.dir, filter); Q_ASSERT(secondFileEdit); if (!lod.url.isEmpty()) { secondFileEdit->setText(lod.url); } } // ok button clicked void DotPlotFilesDialog::accept() { Q_ASSERT(firstFileEdit); Q_ASSERT(secondFileEdit); firstFileName = firstFileEdit->text(); secondFileName = secondFileEdit->text(); if (oneSequenceCheckBox->isChecked()) { secondFileName = firstFileName; } if (!firstFileName.isEmpty() && !secondFileName.isEmpty()) { QDialog::accept(); } else { QMessageBox mb(QMessageBox::Critical, tr("Select files"), tr("Select files first to build dotplot")); mb.exec(); } } int DotPlotFilesDialog::getFirstGap() const { if (mergeFirstCheckBox->isChecked()) { return gapFirst->value(); } else { return -1; } } int DotPlotFilesDialog::getSecondGap() const { if (mergeSecondCheckBox->isChecked()) { return gapSecond->value(); } else { return -1; } } }//namespace ugene-1.9.8/src/plugins/dotplot/dotplot.pro0000644000175000017500000000124211651544322017460 0ustar ilyailyainclude (dotplot.pri) # Input HEADERS += src/DotPlotSplitter.h \ src/DotPlotDialog.h \ src/DotPlotFilesDialog.h \ src/DotPlotTasks.h \ src/DotPlotClasses.h \ src/DotPlotWidget.h \ src/DotPlotPlugin.h FORMS += src/ui/DotPlotDialog.ui \ src/ui/DotPlotFilesDialog.ui SOURCES += src/DotPlotSplitter.cpp \ src/DotPlotDialog.cpp \ src/DotPlotFilesDialog.cpp \ src/DotPlotTasks.cpp \ src/DotPlotClasses.cpp \ src/DotPlotWidget.cpp \ src/DotPlotPlugin.cpp RESOURCES += dotplot.qrc TRANSLATIONS += transl/english.ts transl/russian.ts ugene-1.9.8/src/plugins/dotplot/dotplot.qrc0000644000175000017500000000040411651544322017444 0ustar ilyailya images/dotplot.png images/lock.png images/cursor.png images/exit.png images/hand_icon.png ugene-1.9.8/src/plugins/dotplot/transl/0000755000175000017500000000000011651544322016555 5ustar ilyailyaugene-1.9.8/src/plugins/dotplot/transl/russian.ts0000644000175000017500000005104011651544322020611 0ustar ilyailya DotPlotDialog Dotplot Dotplot parameters Dotplot параметры Custom algorithm Выбранный алгоритм X axis sequence Последовательность оси X Minimum repeat length Мин длина повторов Y axis sequence Последовательность оси Y Repeats identity Идентичность повторов bp нк Heuristic based selection of repeat length so the number of repeats in the sequence will not exceed 1000 Эвристический подбор длины повторов, с тем чтобы кол-во повторов в последовательности не превысило 1000 1k % Resets repeats identity to 100% Сбросить к 100% 100 Search inverted repeats Search direct repeats default Click to load a sequence from the file system. The sequence will be added to the combo boxes when it is loaded to the project Load Sequence OK Cancel Отмена DotPlotFilesDialog Open sequences to build dotplot Выберите последовательности для построения dotplot File name: Имя файла: ... Merge sequences Объединить последовательности Build dotplot from sequences File with first sequence Join all sequences found in the file Gap size: Длина пропуска: Compare sequence against itself File with second sequence Next Далее Cancel Отмена One sequence Одна последовательность U2::DotPlotDialog Auto Автовыбор Suffix index Суффиксный индекс Diagonals Диагональный Open file U2::DotPlotDialogs Task is already running Задача уже запущена Build or Load DotPlot task is already running Задача построения или загрузки dotplot уже запущена Save DotPlot Сохранить dotplot Save DotPlot before deletion? Сохранить dotplot перед удалением? Save dot-plot Save dot-plot data before closing? File opening error Ошибка открытия файла Error opening file %1 Ошибка открытия файла %1 Error Ошибка Error opening files Ошибка открытия файлов Sequences are different Последовательности отличаются Current and loading sequences are different. Continue loading dot-plot anyway? Wrong dot-plot file format, loading aborted Both sequence alphabets must be 4-symbols DNA alphabets Too many results. Try to increase minimum repeat length Current and loading sequences are different. Continue loading DotPlot anyway? Текущие и загружаемые последовательности отличаются. Продолжать загрузку dotplot? Wrong format Неправильный формат Wrong DotPlot file format, loading aborted Неправильный формат файла dotplot, загрузка прервана Wrong alphabet types Неправильные типы алфавитов Both alphabets must be default DNA nucleotide Оба алфавита должны быть стандартными алфавитами ДНК нуклеотидов No project Нет проекта Create or load project first Создайте или загрузите проект для начала Too many results Слишком много результатов Too many results. Try to increase min length Слишком много результатов. Попробуйте уменьшить минимальную длину повтора U2::DotPlotFilesDialog Open first file Открыть первый файл Open second file Открыть второй файл Select files Выберите файлы Select files first to build dotplot Выберите файлы, чтобы посмотрить dotplot U2::DotPlotLoadDocumentsTask DotPlot loading Dotplot загружается Detecting format error for file %1 Ошибка определения формата файла %1 U2::DotPlotPlugin Dotplot Build dotplot for sequences Построение dotplot для последовательностей U2::DotPlotSplitter Multiple view synchronization lock Keep aspect ratio Zoom in (<b> + </b>) Zoom out (<b> - </b>) Reset zooming (<b>0</b>) Select tool (<b>S</b>) Hand tool (<b>H</b>) U2::DotPlotViewAction Show dot plot Показать dotplot U2::DotPlotViewContext Build dotplot... Построить dotplot... U2::DotPlotWidget Settings Настройки Parameters Параметры Save as image Сохранить как изображение Save Сохранить Load Загрузить Remove Удалить Save/Load Сохранить/Загрузить (min length %1, identity %2%) (мин. длинна %1, идентичность %2%) Dotplot Save Dotplot image Сохранение изображения dotplot Image Files (*.png *.jpg *.bmp) Файлы изображений (*.png *.jpg *.bmp) Save Dotplot Сохранить dotplot Dotplot files (*.dpt) Файлы dotplot (*.dpt) Load Dotplot Загрузить dotplot U2::LoadDotPlotTask Wrong dotplot format Неправильный формат файла dotplot DotPlot loading Dotplot загружается U2::SaveDotPlotTask DotPlot saving Dotplot сохраняется ugene-1.9.8/src/plugins/dotplot/transl/czech.ts0000644000175000017500000004001611651544322020222 0ustar ilyailya DotPlotDialog Dotplot Dotplot parameters Custom algorithm X axis sequence Minimum repeat length Y axis sequence Repeats identity bp Heuristic based selection of repeat length so the number of repeats in the sequence will not exceed 1000 1k % Resets repeats identity to 100% 100 Search inverted repeats Search direct repeats default Click to load a sequence from the file system. The sequence will be added to the combo boxes when it is loaded to the project Load Sequence OK Cancel DotPlotFilesDialog ... Build dotplot from sequences File with first sequence Join all sequences found in the file Gap size: Compare sequence against itself File with second sequence Next Cancel U2::DotPlotDialog Auto Suffix index Diagonals Open file U2::DotPlotDialogs Task is already running Build or Load DotPlot task is already running Save dot-plot Save dot-plot data before closing? File opening error Error opening file %1 Error Error opening files Sequences are different Current and loading sequences are different. Continue loading dot-plot anyway? Wrong dot-plot file format, loading aborted Both sequence alphabets must be 4-symbols DNA alphabets Too many results. Try to increase minimum repeat length Wrong format Wrong alphabet types Too many results U2::DotPlotFilesDialog Open first file Open second file Select files Select files first to build dotplot U2::DotPlotLoadDocumentsTask DotPlot loading Detecting format error for file %1 U2::DotPlotPlugin Dotplot Build dotplot for sequences U2::DotPlotSplitter Multiple view synchronization lock Keep aspect ratio Zoom in (<b> + </b>) Zoom out (<b> - </b>) Reset zooming (<b>0</b>) Select tool (<b>S</b>) Hand tool (<b>H</b>) U2::DotPlotViewAction Show dot plot Show dotplot U2::DotPlotViewContext Build dotplot... Build dotplot... U2::DotPlotWidget Parameters Save as image Save Load Remove Save/Load (min length %1, identity %2%) Dotplot Save Dotplot Dotplot files (*.dpt) DotPlot Files (*.dpt) Dotplot files (*.dpt) Load Dotplot U2::LoadDotPlotTask Wrong dotplot format DotPlot loading Dotplot loading U2::SaveDotPlotTask DotPlot saving Dotplot saving ugene-1.9.8/src/plugins/dotplot/transl/english.ts0000644000175000017500000003742211651544322020566 0ustar ilyailya DotPlotDialog Dotplot Dotplot parameters Custom algorithm X axis sequence Minimum repeat length Y axis sequence Repeats identity bp Heuristic based selection of repeat length so the number of repeats in the sequence will not exceed 1000 1k % Resets repeats identity to 100% 100 Search inverted repeats Search for inverted repeats Search direct repeats Search for direct repeats default Click to load a sequence from the file system. The sequence will be added to the combo boxes when it is loaded to the project Load Sequence OK Cancel DotPlotFilesDialog ... Build dotplot from sequences File with first sequence Join all sequences found in the file Gap size: Compare sequence against itself File with second sequence Next Cancel U2::DotPlotDialog Auto Suffix index Diagonals Open file U2::DotPlotDialogs Task is already running Build or Load DotPlot task is already running Save dot-plot Save dot-plot data before closing? File opening error Error opening file %1 Error Error opening files Sequences are different Current and loading sequences are different. Continue loading dot-plot anyway? Wrong dot-plot file format, loading aborted Both sequence alphabets must be 4-symbols DNA alphabets Too many results. Try to increase minimum repeat length Wrong format Wrong alphabet types Too many results U2::DotPlotFilesDialog Open first file Open second file Select files Select files first to build dotplot U2::DotPlotLoadDocumentsTask DotPlot loading Detecting format error for file %1 U2::DotPlotPlugin Dotplot Build dotplot for sequences U2::DotPlotSplitter Multiple view synchronization lock Keep aspect ratio Zoom in (<b> + </b>) Zoom out (<b> - </b>) Reset zooming (<b>0</b>) Select tool (<b>S</b>) Hand tool (<b>H</b>) U2::DotPlotViewAction Show dot plot Show dotplot U2::DotPlotViewContext Build dotplot... U2::DotPlotWidget Parameters Save as image Save Load Remove Save/Load (min length %1, identity %2%) Dotplot Save Dotplot Dotplot files (*.dpt) DotPlot Files (*.dpt) Dotplot files (*.dpt) Load Dotplot U2::LoadDotPlotTask Wrong dotplot format DotPlot loading Dotplot loading U2::SaveDotPlotTask DotPlot saving Dotplot saving ugene-1.9.8/src/plugins/smith_waterman/0000755000175000017500000000000011651544324016611 5ustar ilyailyaugene-1.9.8/src/plugins/smith_waterman/smith_waterman.pro0000644000175000017500000000206311651544324022356 0ustar ilyailyainclude (smith_waterman.pri) # Input HEADERS += src/PairAlignSequences.h \ src/SmithWatermanAlgorithm.h \ src/SmithWatermanAlgorithmSSE2.h \ src/SWAlgorithmPlugin.h \ src/SWAlgorithmTask.h \ src/SmithWatermanAlgorithmCUDA.h \ src/SmithWatermanAlgorithmOPENCL.h \ src/sw_cuda_cpp.h \ src/SWTaskFactory.h \ src/SmithWatermanTests.h \ src/SWWorker.h \ src/SWQuery.h SOURCES += src/PairAlignSequences.cpp \ src/SmithWatermanAlgorithm.cpp \ src/SmithWatermanAlgorithmSSE2.cpp \ src/SWAlgorithmPlugin.cpp \ src/SWAlgorithmTask.cpp \ src/SmithWatermanAlgorithmCUDA.cpp \ src/SmithWatermanAlgorithmOPENCL.cpp \ src/sw_cuda_cpp.cpp \ src/SWTaskFactory.cpp \ src/SmithWatermanTests.cpp \ src/SWWorker.cpp \ src/SWQuery.cpp RESOURCES += smith_waterman.qrc TRANSLATIONS += transl/english.ts transl/russian.ts ugene-1.9.8/src/plugins/smith_waterman/smith_waterman.pri0000644000175000017500000000340711651544324022353 0ustar ilyailyainclude (../../ugene_globals.pri) PLUGIN_ID=smith_waterman PLUGIN_NAME=Smith-Waterman PLUGIN_VENDOR=Unipro include( ../../ugene_plugin_common.pri ) INCLUDEPATH += ../../corelibs/U2View/_tmp #adding SSE2 gcc compiler flag if building on SSE2 capable CPU use_sse2() { !win32 { QMAKE_CXXFLAGS += -msse2 QMAKE_CFLAGS_DEBUG += -msse2 QMAKE_CFLAGS_RELEASE += -msse2 } DEFINES += SW2_BUILD_WITH_SSE2 } #adding CUDA specific parameters use_cuda() { LIBS += -L$$UGENE_CUDA_LIB_DIR -lcudart INCLUDEPATH += $$UGENE_CUDA_INC_DIR SW2_NVCC_FLAGS = #TODO: win 64? !win32 { SW2_NVCC_FLAGS += -Xcompiler -fPIC } SW2_CUDA_LIBS += -lcudart SW2_CUDA_FILES += src/sw_cuda.cu #workaround for nmake bug: nvcc failes with an internal error when launched from Makefile by nvcc win32 { SW2_CUDA_NULL_REDIRECT = > nul } else { SW2_CUDA_NULL_REDIRECT = } #manually convert INCLUDEPATH: SW2_CUDA_INCLUDEPATH = for(path, INCLUDEPATH) { SW2_CUDA_INCLUDEPATH += -I$${path} } for(path, QMAKE_INCDIR) { SW2_CUDA_INCLUDEPATH += -I$${path} } # message( $$SW2_CUDA_INCLUDEPATH ) nvzz.output = $$OBJECTS_DIR/${QMAKE_FILE_BASE}$$QMAKE_EXT_OBJ nvzz.commands = $$UGENE_NVCC $$SW2_NVCC_FLAGS -c -I$$UGENE_CUDA_INC_DIR $$SW2_CUDA_INCLUDEPATH -I$$QMAKE_INCDIR_QT \ -L$$UGENE_CUDA_LIB_DIR $$SW2_CUDA_LIBS \ -o ${QMAKE_FILE_OUT} \ ${QMAKE_FILE_NAME} \ $$SW2_CUDA_NULL_REDIRECT nvzz.depend_command = nvzz.input = SW2_CUDA_FILES QMAKE_EXTRA_COMPILERS += nvzz DEFINES += SW2_BUILD_WITH_CUDA } #adding OPENCL specific parameters use_opencl() { DEFINES += SW2_BUILD_WITH_OPENCL } ugene-1.9.8/src/plugins/smith_waterman/src/0000755000175000017500000000000011651544324017400 5ustar ilyailyaugene-1.9.8/src/plugins/smith_waterman/src/SWAlgorithmPlugin.h0000644000175000017500000000330211651544324023126 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_SW_ALGORITHM_PLUGIN_H_ #define _U2_SW_ALGORITHM_PLUGIN_H_ #include #include #include namespace U2 { class XMLTestFactory; class SWAlgorithmADVContext; class SWAlgorithmPlugin : public Plugin { Q_OBJECT public: SWAlgorithmPlugin(); public slots: void regDependedIMPLFromOtherPlugins(); private: QList fs; SWAlgorithmADVContext * ctxADV; }; class SWAlgorithmTests { public: static QList createTestFactories(); }; class SWAlgorithmADVContext: public GObjectViewWindowContext { Q_OBJECT public: SWAlgorithmADVContext(QObject* p); protected slots: void sl_search(); protected: virtual void initViewContext(GObjectView* view); private: SWDialogConfig dialogConfig; }; } //namespace #endif ugene-1.9.8/src/plugins/smith_waterman/src/sw_opencl.cl0000644000175000017500000001354511651544324021721 0ustar ilyailya//#ifdef SW2_BUILD_WITH_CUDA typedef int ScoreType; //global function __kernel void calculateMatrix(global const char * seqLib, global ScoreType* queryProfile, global ScoreType* g_HdataUp, global ScoreType* g_HdataRec, global ScoreType* g_HdataMax, global ScoreType* g_FdataUp, global ScoreType* g_directionsUp, global ScoreType* g_directionsRec, global ScoreType* g_directionsMax, __const int queryStartPos, __const int partSeqSize, __const int partsNumber, __const int overlapLength, __const int seqLibLength, __const int queryLength, __const int gapOpen, __const int gapExtension, __const int queryPartLength, __local ScoreType* shared_H, __local ScoreType* shared_E, __local ScoreType* shared_direction) { //registers int patternPos = get_local_id(0); // threadIdx.x; int globalPatternPos = queryStartPos + patternPos; //int seqStartPos = blockIdx.x * (partSeqSize - overlapLength); int seqStartPos = get_group_id(0) * (partSeqSize - overlapLength); // int globalStartPos = blockIdx.x * (partSeqSize + 1); int globalStartPos = get_group_id(0) * (partSeqSize + 1); int seqPos = 0, globalPos = 0, diagNum = 0; ScoreType substScore = 0; ScoreType E = 0, E_left = 0, F = 0, F_up = 0, H = 0, H_left = 0, H_up = 0, H_upleft = 0, E_left_init = 0, H_left_init = 0, directionLeft = 0, directionUp = 0, directionUpLeft = 0, direction = 0, directionInit = 0, maxScore = 0; shared_H[patternPos] = 0; shared_E[patternPos] = 0; shared_direction[patternPos] = 0; barrier(CLK_LOCAL_MEM_FENCE); seqPos = seqStartPos - patternPos; globalPos = globalStartPos - patternPos; diagNum = (partSeqSize + queryPartLength - 1); for (int iteration = 0; iteration < diagNum; iteration++) { //check boundaries bool isActual = seqPos < seqLibLength && seqPos >= seqStartPos && seqPos < seqStartPos + partSeqSize && globalPatternPos < queryLength; if (isActual) { substScore = queryProfile[seqLib[seqPos] * queryLength + globalPatternPos]; H_left = shared_H[patternPos]; E_left = shared_E[patternPos]; directionLeft = shared_direction[patternPos]; if (patternPos == 0) { H_left = g_HdataUp[globalPos]; E_left = g_FdataUp[globalPos]; directionLeft = g_directionsUp[globalPos]; if (globalPos > 0) { H_upleft = g_HdataUp[globalPos - 1]; directionUpLeft = g_directionsUp[globalPos - 1]; } if (queryStartPos == 0 || iteration == 0) { directionUpLeft = seqPos; } } } barrier(CLK_LOCAL_MEM_FENCE); if (isActual) { E = max(E_left - gapExtension, H_left - gapOpen); F = max(F_up - gapExtension, H_up - gapOpen); // Compute H H = max(0, E); H = max(H, F); H = max(H, H_upleft + substScore); //chose direction if (H == 0) { direction = seqPos + 1; } else if (H == E) { direction = directionLeft; } else if (H == F) { direction = directionUp; } //(H == H_upleft + substScore) else { direction = directionUpLeft; } shared_E[patternPos + 1] = E; shared_H[patternPos + 1] = H; shared_direction[patternPos + 1] = direction; H_upleft = H_left; H_up = H; F_up = F; directionUp = direction; directionUpLeft = directionLeft; //collect best result maxScore = max(H, g_HdataMax[globalPos]); if (maxScore == H) { g_HdataMax[globalPos] = maxScore; g_directionsMax[globalPos] = direction; } //if this last iteration then start prepare next if (patternPos == (queryPartLength - 1)) { g_HdataRec[globalPos] = H; g_FdataUp[globalPos] = E; g_directionsRec[globalPos] = direction; } } barrier(CLK_LOCAL_MEM_FENCE); seqPos++;// = seqStartPos + iteration - patternPos; globalPos++;// = globalStartPos + iteration - patternPos; } } ugene-1.9.8/src/plugins/smith_waterman/src/SWAlgorithmPlugin.cpp0000644000175000017500000001263711651544324023474 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "SWAlgorithmPlugin.h" #include "SWAlgorithmTask.h" #include "SWTaskFactory.h" #include "SmithWatermanTests.h" #include "SWQuery.h" #include "SWWorker.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include namespace U2 { extern "C" Q_DECL_EXPORT Plugin* U2_PLUGIN_INIT_FUNC() { #ifdef SW2_BUILD_WITH_SSE2 bool runningOnSSEProc = AppResourcePool::isSSE2Enabled(); if( !runningOnSSEProc ) { return 0; } #endif SWAlgorithmPlugin * plug = new SWAlgorithmPlugin(); return plug; } SWAlgorithmPlugin::SWAlgorithmPlugin() : Plugin(tr("Optimized Smith-Waterman "), tr("Various implementations of Smith-Waterman algorithm")) { //initializing ADV context if (AppContext::getMainWindow()) { ctxADV = new SWAlgorithmADVContext(this); ctxADV->init(); } LocalWorkflow::SWWorkerFactory::init(); QDActorPrototypeRegistry* qdpr = AppContext::getQDActorProtoRegistry(); qdpr->registerProto(new SWQDActorFactory()); //Smith-Waterman algorithm tests GTestFormatRegistry * tfr = AppContext::getTestFramework()->getTestFormatRegistry(); XMLTestFormat *xmlTestFormat = qobject_cast(tfr->findFormat("XML")); assert(xmlTestFormat!=NULL); U2::GAutoDeleteList* l = new U2::GAutoDeleteList(this); l->qlist = SWAlgorithmTests::createTestFactories(); foreach(XMLTestFactory* f, l->qlist) { bool res = xmlTestFormat->registerTestFactory(f); Q_UNUSED(res); assert(res); } SmithWatermanTaskFactoryRegistry* swar = AppContext::getSmithWatermanTaskFactoryRegistry(); coreLog.trace("Registering classic SW implementation"); swar->registerFactory(new SWTaskFactory(SW_classic), QString("Classic 2")); regDependedIMPLFromOtherPlugins(); #ifdef SW2_BUILD_WITH_SSE2 coreLog.trace("Registering SSE2 SW implementation"); swar->registerFactory(new SWTaskFactory(SW_sse2), QString("SSE2")); #endif this->connect(AppContext::getPluginSupport(), SIGNAL(si_allStartUpPluginsLoaded()), SLOT(regDependedIMPLFromOtherPlugins())); } QList SWAlgorithmTests::createTestFactories() { QList res; res.append(GTest_SmithWatermnan::createFactory()); res.append(GTest_SmithWatermnanPerf::createFactory()); return res; } //SLOT void SWAlgorithmPlugin::regDependedIMPLFromOtherPlugins() { SmithWatermanTaskFactoryRegistry* swar = AppContext::getSmithWatermanTaskFactoryRegistry(); Q_UNUSED( swar ); #ifdef SW2_BUILD_WITH_CUDA if ( !AppContext::getCudaGpuRegistry()->empty() ) { coreLog.trace("Registering CUDA SW implementation"); swar->registerFactory(new SWTaskFactory(SW_cuda), QString("CUDA")); } #endif #ifdef SW2_BUILD_WITH_OPENCL if ( !AppContext::getOpenCLGpuRegistry()->empty() ) { coreLog.trace("Registering OpenCL SW implementation"); swar->registerFactory(new SWTaskFactory(SW_opencl), QString("OPENCL")); } #endif } SWAlgorithmADVContext::SWAlgorithmADVContext(QObject* p) : GObjectViewWindowContext(p, ANNOTATED_DNA_VIEW_FACTORY_ID) { } void SWAlgorithmADVContext::initViewContext(GObjectView* view) { AnnotatedDNAView* av = qobject_cast(view); assert(av != NULL); ADVGlobalAction* a = new ADVGlobalAction(av, QIcon(":core/images/sw.png"), tr("Find pattern [Smith-Waterman]..."), 15); a->setShortcut(QKeySequence(Qt::CTRL | Qt::SHIFT | Qt::Key_F)); a->setShortcutContext(Qt::WindowShortcut); av->getWidget()->addAction(a); connect(a, SIGNAL(triggered()), SLOT(sl_search())); } void SWAlgorithmADVContext::sl_search() { GObjectViewAction* action = qobject_cast(sender()); assert(0 != action); AnnotatedDNAView* av = qobject_cast(action->getObjectView()); assert(av != NULL); ADVSequenceObjectContext* seqCtx = av->getSequenceInFocus(); SmithWatermanDialogController::run(av->getWidget(), seqCtx, &dialogConfig); } } //namespace ugene-1.9.8/src/plugins/smith_waterman/src/SWAlgorithmTask.cpp0000644000175000017500000003057511651544324023141 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifdef SW2_BUILD_WITH_CUDA #include #endif #include "SWAlgorithmTask.h" #include "SmithWatermanAlgorithmCUDA.h" #include "SmithWatermanAlgorithmSSE2.h" #include "SmithWatermanAlgorithmOPENCL.h" #include "sw_cuda_cpp.h" #include #include #include #include #include #include #include #include #include using namespace std; namespace U2 { SWAlgorithmTask::SWAlgorithmTask(const SmithWatermanSettings& s, const QString& taskName, SW_AlgType _algType):Task (taskName, TaskFlag_NoRun), sWatermanConfig(s) { GCOUNTER( cvar, tvar, "SWAlgorithmTask" ); algType = _algType; if (algType == SW_sse2) { if (sWatermanConfig.ptrn.length() < 8) { algType = SW_classic; } } //acquiring resourses for GPU computations if( SW_cuda == algType ) { addTaskResource(TaskResourceUsage( RESOURCE_CUDA_GPU, 1, true /*prepareStage*/)); } else if( SW_opencl == algType ) { addTaskResource(TaskResourceUsage( RESOURCE_OPENCL_GPU, 1, true /*prepareStage*/)); } int maxScore = calculateMaxScore(s.ptrn, s.pSm); minScore = (maxScore * s.percentOfScore) / 100; if ( (maxScore * (int)s.percentOfScore) % 100 != 0) minScore += 1; setupTask(maxScore); } SWAlgorithmTask::~SWAlgorithmTask() { delete sWatermanConfig.resultListener; delete sWatermanConfig.resultCallback; // we do not delete resultFilter here, because filters are stored in special registry } void SWAlgorithmTask::setupTask(int maxScore) { SequenceWalkerConfig c; c.seq = sWatermanConfig.sqnc.constData(); c.seqSize = sWatermanConfig.sqnc.size(); c.range = sWatermanConfig.globalRegion; c.complTrans = sWatermanConfig.complTT; c.aminoTrans = sWatermanConfig.aminoTT; c.strandToWalk = sWatermanConfig.strand; algoLog.details(QString("Strand: %1 ").arg(c.strandToWalk)); int overlapSize = calculateMatrixLength(sWatermanConfig.sqnc, sWatermanConfig.ptrn, sWatermanConfig.gapModel.scoreGapOpen, sWatermanConfig.gapModel.scoreGapExtd, maxScore, minScore); // divide sequence by PARTS_NUMBER parts int idealThreadCount = AppContext::getAppSettings()->getAppResourcePool()->getIdealThreadCount(); int PARTS_NUMBER = 0; if (algType == SW_sse2) { PARTS_NUMBER = idealThreadCount * 2.5; } else if (algType == SW_classic){ PARTS_NUMBER = idealThreadCount; } else if (algType == SW_cuda || algType == SW_opencl) { PARTS_NUMBER = 1; } if ((PARTS_NUMBER != 1) && (PARTS_NUMBER - 1) * overlapSize < sWatermanConfig.globalRegion.length) { c.chunkSize = (c.seqSize + overlapSize * (PARTS_NUMBER - 1)) / PARTS_NUMBER; if (c.chunkSize == overlapSize) c.chunkSize++; c.overlapSize = overlapSize; } else { c.overlapSize = 0; c.chunkSize = c.seqSize; PARTS_NUMBER = 1; } c.lastChunkExtraLen = PARTS_NUMBER - 1; c.nThreads = PARTS_NUMBER; t = new SequenceWalkerTask(c, this, tr("Smith Waterman2 SequenceWalker")); addSubTask(t); } void SWAlgorithmTask::prepare() { if( SW_cuda == algType ) { CudaGpuModel *& gpu = gpuModel.cudaGpu; gpu = AppContext::getCudaGpuRegistry()->acquireAnyReadyGpu(); assert( gpu ); #ifdef SW2_BUILD_WITH_CUDA quint64 needMemBytes = SmithWatermanAlgorithmCUDA::estimateNeededGpuMemory( sWatermanConfig.pSm, sWatermanConfig.ptrn, sWatermanConfig.sqnc ); quint64 gpuMemBytes = gpu->getGlobalMemorySizeBytes(); if( gpuMemBytes < needMemBytes ) { stateInfo.setError( tr("Not enough memory on CUDA-enabled device. " "The space required is %1 bytes, but only %2 bytes are available. Device id: %3, device name: %4"). arg(QString::number(needMemBytes), QString::number(gpuMemBytes), QString::number(gpu->getId()), QString(gpu->getName())) ); return; } else { algoLog.details( tr("The Smith-Waterman search allocates ~%1 bytes (%2 Mb) on CUDA device"). arg(QString::number(needMemBytes), QString::number(needMemBytes/1024/1024+1)) ); } coreLog.details(QString("GPU model: %1").arg(gpuModel.cudaGpu->getId())); cudaSetDevice( gpuModel.cudaGpu->getId() ); #else assert(false); #endif } } QList & SWAlgorithmTask::getResult() { removeResultFromOverlap(pairAlignSequences); SmithWatermanAlgorithm::sortByScore(pairAlignSequences); return pairAlignSequences; } void SWAlgorithmTask::onRegion(SequenceWalkerSubtask* t, TaskStateInfo& ti) { Q_UNUSED(ti); int regionLen = t->getRegionSequenceLen(); QByteArray localSeq(t->getRegionSequence(), regionLen); SmithWatermanAlgorithm * sw = NULL; if (algType == SW_sse2) { #ifdef SW2_BUILD_WITH_SSE2 sw = new SmithWatermanAlgorithmSSE2; #else coreLog.error( "SSE2 was not enabled in this build" ); return; #endif //SW2_BUILD_WITH_SSE2 } else if (algType == SW_cuda) { #ifdef SW2_BUILD_WITH_CUDA sw = new SmithWatermanAlgorithmCUDA; #else coreLog.error( "CUDA was not enabled in this build" ); return; #endif //SW2_BUILD_WITH_CUDA } else if (algType == SW_opencl) { #ifdef SW2_BUILD_WITH_OPENCL sw = new SmithWatermanAlgorithmOPENCL; #else coreLog.error( "OPENCL was not enabled in this build" ); return; #endif //SW2_BUILD_WITH_OPENCL } else { assert(algType == SW_classic); sw = new SmithWatermanAlgorithm; } quint64 t1 = GTimer::currentTimeMicros(); sw->launch(sWatermanConfig.pSm, sWatermanConfig.ptrn, localSeq, sWatermanConfig.gapModel.scoreGapOpen + sWatermanConfig.gapModel.scoreGapExtd, sWatermanConfig.gapModel.scoreGapExtd, minScore); QString algName; if (algType == SW_cuda) { algName = "CUDA"; } else { algName = "Classic"; } QString testName; if (getParentTask() != NULL) { testName = getParentTask()->getTaskName(); } else { testName = "SW alg"; } perfLog.details(QString("\n%1 %2 run time is %3\n").arg(testName).arg(algName).arg(GTimer::secsBetween(t1, GTimer::currentTimeMicros()))); QList res = sw->getResults(); for (int i = 0; i < res.size(); i++) { res[i].isDNAComplemented = t->isDNAComplemented(); res[i].isAminoTranslated = t->isAminoTranslated(); if (t->isAminoTranslated()) { res[i].intervalSeq1.startPos *= 3; res[i].intervalSeq1.length *= 3; } if (t->isDNAComplemented()) { const U2Region& wr = t->getGlobalRegion(); res[i].intervalSeq1.startPos = wr.endPos() - res[i].intervalSeq1.endPos() - sWatermanConfig.globalRegion.startPos; } else { res[i].intervalSeq1.startPos += (t->getGlobalRegion().startPos - sWatermanConfig.globalRegion.startPos); } } addResult(res); ///////////////////// delete sw; } void SWAlgorithmTask::removeResultFromOverlap(QList & res) { for (int i = 0; i < res.size() - 1; i++) { for (int j = i + 1; j < res.size(); j++) { if (res.at(i).intervalSeq1 == res.at(j).intervalSeq1 && res.at(i).isDNAComplemented == res.at(j).isDNAComplemented) { if (res.at(i).score > res.at(j).score) { res.removeAt(j); j--; } else { res.removeAt(i); i--; j=res.size(); } } } } } void SWAlgorithmTask::addResult(QList & res) { QMutexLocker ml(&lock); pairAlignSequences += res; pairAlignSequences += res; } int SWAlgorithmTask::calculateMatrixLength(const QByteArray & searchSeq, const QByteArray & patternSeq, int gapOpen, int gapExtension, int maxScore, int minScore) { int matrixLength = 0; int gap = gapOpen; if (gapOpen < gapExtension) gap = gapExtension; matrixLength = patternSeq.length() + (maxScore - minScore)/gap * (-1) + 1; if (searchSeq.length() + 1 < matrixLength) matrixLength = searchSeq.length() + 1; matrixLength += 1; return matrixLength; } int SWAlgorithmTask::calculateMaxScore(const QByteArray & seq, const SMatrix& substitutionMatrix) { int maxScore = 0; int max; int substValue = 0; QByteArray alphaChars = substitutionMatrix.getAlphabet()->getAlphabetChars(); for (int i = 0; i < seq.length(); i++) { max = 0; for (int j = 0; j < alphaChars.size(); j++) { //TODO: use raw pointers! char c1 = seq.at(i); char c2 = alphaChars.at(j); substValue = substitutionMatrix.getScore(c1, c2); if (max < substValue) max = substValue; } maxScore += max; } return maxScore; } Task::ReportResult SWAlgorithmTask::report() { if( SW_cuda == algType ) { gpuModel.cudaGpu->setAcquired(false); } SmithWatermanResultListener* rl = sWatermanConfig.resultListener; QList resultList = rl->getResults(); int resultsNum = resultList.size(); algoLog.details(tr("%1 results found").arg(resultsNum)); if (0 != sWatermanConfig.resultCallback) { SmithWatermanReportCallback* rcb = sWatermanConfig.resultCallback; QString res = rcb->report(resultList); if (!res.isEmpty()) { stateInfo.setError(res); } } return ReportResult_Finished; } QList SWAlgorithmTask::onSubTaskFinished( Task* subTask ){ QList res; if (hasError() || isCanceled()) { return res; } if (subTask == t){ res.append(new SWResultsPostprocessingTask(sWatermanConfig, resultList, getResult())); } return res; } SWResultsPostprocessingTask::SWResultsPostprocessingTask( SmithWatermanSettings &_sWatermanConfig, QList &_resultList, QList &_resPAS ) :Task ("SWResultsPostprocessing", TaskFlag_None), sWatermanConfig(_sWatermanConfig), resultList(_resultList), resPAS(_resPAS){ } void SWResultsPostprocessingTask::prepare(){ } void SWResultsPostprocessingTask::run(){ SmithWatermanResult r; for (int i = 0; i < resPAS.size(); i++) { r.strand = resPAS.at(i).isDNAComplemented ? U2Strand::Complementary : U2Strand::Direct; r.trans = resPAS.at(i).isAminoTranslated; r.region = resPAS.at(i).intervalSeq1; r.region.startPos += sWatermanConfig.globalRegion.startPos; r.score = resPAS.at(i).score; resultList.append(r); } if (0 != sWatermanConfig.resultFilter) { SmithWatermanResultFilter* rf = sWatermanConfig.resultFilter; rf->applyFilter(&resultList); } foreach( const SmithWatermanResult & r, resultList ) { /* push results after filters */ sWatermanConfig.resultListener->pushResult( r ); } } } //namespace ugene-1.9.8/src/plugins/smith_waterman/src/sw_cuda.cu0000644000175000017500000001236011651544324021360 0ustar ilyailya//#ifdef SW2_BUILD_WITH_CUDA typedef int ScoreType; // CUDA global constants __constant__ int partSeqSize, partsNumber, overlapLength, seqLibLength, queryLength; __constant__ int gapOpen, gapExtension, maxScore, queryPartLength; //global function __global__ void calculateMatrix(const char * seqLib, ScoreType* queryProfile, ScoreType* g_HdataUp, ScoreType* g_HdataRec, ScoreType* g_HdataMax, ScoreType* g_FdataUp, ScoreType* g_directionsUp, ScoreType* g_directionsRec, ScoreType* g_directionsMax, int queryStartPos) { //registers int patternPos = threadIdx.x; int globalPatternPos = queryStartPos + patternPos; int seqStartPos = blockIdx.x * (partSeqSize - overlapLength); int globalStartPos = blockIdx.x * (partSeqSize + 1); int seqPos = 0, globalPos = 0, diagNum = 0; ScoreType substScore = 0; ScoreType E = 0, E_left = 0, F = 0, F_up = 0, H = 0, H_left = 0, H_up = 0, H_upleft = 0, E_left_init = 0, H_left_init = 0, directionLeft = 0, directionUp = 0, directionUpLeft = 0, direction = 0, directionInit = 0, maxScore = 0; //dynamic allocation shared memory extern __shared__ ScoreType shared_H[]; ScoreType* shared_E = (ScoreType*)&shared_H[queryPartLength + 1]; ScoreType* shared_direction = (ScoreType*)&shared_E[queryPartLength + 1]; shared_H[patternPos] = 0; shared_E[patternPos] = 0; shared_direction[patternPos] = 0; __syncthreads(); seqPos = seqStartPos - patternPos; globalPos = globalStartPos - patternPos; diagNum = (partSeqSize + queryPartLength - 1); for (int iteration = 0; iteration < diagNum; iteration++) { //check boundaries bool isActual = seqPos < seqLibLength && seqPos >= seqStartPos && seqPos < seqStartPos + partSeqSize && globalPatternPos < queryLength; if (isActual) { substScore = queryProfile[seqLib[seqPos] * queryLength + globalPatternPos]; H_left = shared_H[patternPos]; E_left = shared_E[patternPos]; directionLeft = shared_direction[patternPos]; if (patternPos == 0) { H_left = g_HdataUp[globalPos]; E_left = g_FdataUp[globalPos]; directionLeft = g_directionsUp[globalPos]; if (globalPos > 0) { H_upleft = g_HdataUp[globalPos - 1]; directionUpLeft = g_directionsUp[globalPos - 1]; } if (queryStartPos == 0 || iteration == 0) { directionUpLeft = seqPos; } } } __syncthreads(); if (isActual) { E = max(E_left - gapExtension, H_left - gapOpen); F = max(F_up - gapExtension, H_up - gapOpen); // Compute H H = max(0, E); H = max(H, F); H = max(H, H_upleft + substScore); //chose direction if (H == 0) { direction = seqPos + 1; } else if (H == E) { direction = directionLeft; } else if (H == F) { direction = directionUp; } //(H == H_upleft + substScore) else { direction = directionUpLeft; } shared_E[patternPos + 1] = E; shared_H[patternPos + 1] = H; shared_direction[patternPos + 1] = direction; H_upleft = H_left; H_up = H; F_up = F; directionUp = direction; directionUpLeft = directionLeft; //collect best result maxScore = max(H, g_HdataMax[globalPos]); if (maxScore == H) { g_HdataMax[globalPos] = maxScore; g_directionsMax[globalPos] = direction; } //if this last iteration then start prepare next if (patternPos == (queryPartLength - 1)) { g_HdataRec[globalPos] = H; g_FdataUp[globalPos] = E; g_directionsRec[globalPos] = direction; } } __syncthreads(); seqPos++;// = seqStartPos + iteration - patternPos; globalPos++;// = globalStartPos + iteration - patternPos; } } void calculateMatrix_wrap(int blockSize, int threadNum, const char * seqLib, ScoreType* queryProfile, ScoreType* g_HdataUp, ScoreType* g_HdataRec, ScoreType* g_HdataMax, ScoreType* g_FdataUp, ScoreType* g_directionsUp, ScoreType* g_directionsRec, ScoreType* g_directionsMax, int iteration) { size_t sh_mem_size = sizeof(ScoreType) * (threadNum + 1) * 3; calculateMatrix<<>>(seqLib, queryProfile, g_HdataUp, g_HdataRec, g_HdataMax, g_FdataUp, g_directionsUp, g_directionsRec, g_directionsMax, iteration); } void setConstants(int partSeqSize, int partsNumber, int overlapLength, int seqLibLength, int queryLength, int gapOpen, int gapExtension, int maxScore, int queryPartLength) { cudaMemcpyToSymbol("partSeqSize", &partSeqSize, sizeof(partSeqSize)); cudaMemcpyToSymbol("partsNumber", &partsNumber, sizeof(partsNumber)); cudaMemcpyToSymbol("overlapLength", &overlapLength, sizeof(overlapLength)); cudaMemcpyToSymbol("seqLibLength", &seqLibLength, sizeof(seqLibLength)); cudaMemcpyToSymbol("queryLength", &queryLength, sizeof(queryLength)); cudaMemcpyToSymbol("gapOpen", &gapOpen, sizeof(gapOpen)); cudaMemcpyToSymbol("gapExtension", &gapExtension, sizeof(gapExtension)); cudaMemcpyToSymbol("maxScore", &maxScore, sizeof(maxScore)); cudaMemcpyToSymbol("queryPartLength", &queryPartLength, sizeof(queryPartLength)); } //#endif //SW2_BUILD_WITH_CUDA ugene-1.9.8/src/plugins/smith_waterman/src/sw_cuda_cpp.h0000644000175000017500000000273111651544324022043 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifdef SW2_BUILD_WITH_CUDA #ifndef _SW_CUDA_CPP_H #define _SW_CUDA_CPP_H #include struct resType { U2::U2Region reg; int score; }; class sw_cuda_cpp { public: typedef int ScoreType; QList launch(const char * seqLib, int seqLibLength, ScoreType* queryProfile, ScoreType qProfLen, int queryLength, ScoreType gapOpen, ScoreType gapExtension, ScoreType maxScore); static quint64 estimateNeededGpuMemory( int seqLibLength, ScoreType qProfLen, int queryLength ); static const int MAX_BLOCKS_NUMBER; static const int MAX_SHARED_VECTOR_LENGTH; }; #endif #endif //SW2_BUILD_WITH_CUDA ugene-1.9.8/src/plugins/smith_waterman/src/SmithWatermanAlgorithmOPENCL.cpp0000644000175000017500000004777611651544324025464 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifdef SW2_BUILD_WITH_OPENCL #include "SmithWatermanAlgorithmOPENCL.h" #include "PairAlignSequences.h" #include #include #include #include #include #include #include namespace U2 { SmithWatermanAlgorithmOPENCL::SmithWatermanAlgorithmOPENCL() : MAX_BLOCKS_NUMBER(AppContext::getOpenCLGpuRegistry()->getAnyEnabledGpu()->getMaxComputeUnits()), MAX_SHARED_VECTOR_LENGTH(32), clEvent(NULL), clKernel(NULL), clProgram(NULL), clCommandQueue(NULL), clContext(NULL), queryProfBuf(NULL), seqLibProfBuf(NULL), hDataMaxBuf(NULL), hDataUpBufTmp(NULL), hDataRecBufTmp(NULL), fDataUpBuf(NULL), directionsUpBufTmp(NULL), directionsRecBufTmp(NULL), directionsMaxBuf(NULL) {} quint64 SmithWatermanAlgorithmOPENCL::estimateNeededGpuMemory( const SMatrix& sm, QByteArray const & _patternSeq, QByteArray const & _searchSeq ) { Q_UNUSED(sm); Q_UNUSED(_patternSeq); Q_UNUSED(_searchSeq); //TODO //const QByteArray & alphChars = sm.getAlphabet()->getAlphabetChars(); //int subLen = alphChars.size(); //int qLen = _patternSeq.size(); //int profLen = subLen * (qLen + 1) * (alphChars[ alphChars.size()-1 ] + 1); return 0;//sw_cuda_cpp::estimateNeededGpuMemory( _searchSeq.size(), profLen, qLen ); } //TODO: calculate maximum alignment length int SmithWatermanAlgorithmOPENCL::calcOverlap(int queryLength) { return queryLength * 2; } //number of parts of the sequence which we divide int SmithWatermanAlgorithmOPENCL::calcPartsNumber(int seqLibLength, int overlapLength) { int partsNumber = (seqLibLength + overlapLength - 1) / overlapLength; if (partsNumber > MAX_BLOCKS_NUMBER) { partsNumber = MAX_BLOCKS_NUMBER; } return partsNumber; } //size of sequence's part int SmithWatermanAlgorithmOPENCL::calcPartSeqSize(int seqLibLength, int overlapLength, int partsNumber) { return (seqLibLength + (partsNumber - 1) * (overlapLength + 1)) / partsNumber; } //size of vector that contain all results int SmithWatermanAlgorithmOPENCL::calcSizeRow(int partsNumber, int partSeqSize) { return (partSeqSize + 1) * partsNumber; } bool hasOPENCLError(int err, QString errorMessage) { if(err != 0) { algoLog.error(QString("OPENCL: %1; Error code (%2)").arg(errorMessage).arg(err)); return true; } else { return false; } } void SmithWatermanAlgorithmOPENCL::launch(const SMatrix& sm, QByteArray const & _patternSeq, QByteArray const & _searchSeq, int _gapOpen, int _gapExtension, int _minScore) { setValues(sm, _patternSeq, _searchSeq, _gapOpen, _gapExtension, _minScore); algoLog.details(QObject::tr("START SmithWatermanAlgorithmOPENCL::launch")); int queryLength = patternSeq.size(); int searchLen = searchSeq.size(); int subLen = sm.getAlphabet()->getNumAlphabetChars(); //alphChars is sorted const QByteArray & alphChars = sm.getAlphabet()->getAlphabetChars(); int profLen = subLen * (queryLength + 1) * (alphChars[ alphChars.size()-1 ] + 1); ScoreType * queryProfile = new ScoreType[profLen]; gauto_array qpm(queryProfile); // to ensure the data is deallocated correctly for (int i = 0; i < profLen; i++) { queryProfile[i] = 0; } //calculate query profile for (int i = 0; i < subLen; i++) { for (int j = 0; j < queryLength; j++) { char ch = alphChars[i]; queryProfile[ch * queryLength + j] = sm.getScore(ch, _patternSeq.at(j)); } } cl_int err = CL_SUCCESS; cl_uint clNumDevices = 1; cl_device_id deviceId = (cl_device_id) AppContext::getOpenCLGpuRegistry()->getAnyEnabledGpu()->getId(); const OpenCLHelper& openCLHelper = AppContext::getOpenCLGpuRegistry()->getOpenCLHelper(); if (!openCLHelper.isLoaded()) { coreLog.error(openCLHelper.getErrorString()); return; } algoLog.trace("Creating a context"); clContext = openCLHelper.clCreateContext_p(0, clNumDevices, &deviceId, NULL, NULL, &err); if (hasOPENCLError(err, "cl::Context() failed")) return; //******************************* //calculate lengths const int overlapLength = queryLength * 3; int seqLibLength = _searchSeq.size(); int partsNumber = calcPartsNumber(seqLibLength, overlapLength); int queryDevider = 1; if (queryLength > MAX_SHARED_VECTOR_LENGTH) { queryDevider = (queryLength + MAX_SHARED_VECTOR_LENGTH - 1) / MAX_SHARED_VECTOR_LENGTH; } int partQuerySize = (queryLength + queryDevider - 1) / queryDevider; int partSeqSize = calcPartSeqSize(seqLibLength, overlapLength, partsNumber); int sizeRow = calcSizeRow(partsNumber, partSeqSize); ScoreType* g_HdataTmp = new ScoreType[sizeRow]; gauto_array g_HdataTmpPtr(g_HdataTmp); ScoreType* g_directionsRec = new ScoreType[sizeRow]; gauto_array g_directionsRecPtr(g_directionsRec); for (int i = 0; i < sizeRow; i++) { g_HdataTmp[i] = 0; g_directionsRec[i] = 0; } queryProfBuf = openCLHelper.clCreateBuffer_p(clContext, CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR, sizeof(cl_int) * profLen, queryProfile, &err); if (hasOPENCLError(err, "Can't allocate memory in buffer")) return; seqLibProfBuf = openCLHelper.clCreateBuffer_p(clContext, CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR, sizeof(char) * (_searchSeq.length() + 1), searchSeq.data(), &err); if (hasOPENCLError(err, "Can't allocate memory in buffer")) return; hDataMaxBuf = openCLHelper.clCreateBuffer_p(clContext, CL_MEM_READ_WRITE | CL_MEM_COPY_HOST_PTR, sizeof(ScoreType) * (sizeRow), g_HdataTmp, &err); if (hasOPENCLError(err, "Can't allocate memory in buffer")) return; hDataUpBufTmp = openCLHelper.clCreateBuffer_p(clContext, CL_MEM_READ_WRITE | CL_MEM_COPY_HOST_PTR, sizeof(ScoreType) * (sizeRow), g_HdataTmp, &err); if (hasOPENCLError(err, "Can't allocate memory in buffer")) return; cl_mem* hDataUpBuf = &hDataUpBufTmp; hDataRecBufTmp = openCLHelper.clCreateBuffer_p(clContext, CL_MEM_READ_WRITE | CL_MEM_COPY_HOST_PTR, sizeof(ScoreType) * (sizeRow), g_HdataTmp, &err); if (hasOPENCLError(err, "Can't allocate memory in buffer")) return; cl_mem* hDataRecBuf = &hDataRecBufTmp; cl_mem* hDataTmpBuf = NULL; fDataUpBuf = openCLHelper.clCreateBuffer_p(clContext, CL_MEM_READ_WRITE | CL_MEM_COPY_HOST_PTR, sizeof(ScoreType) * (sizeRow), g_HdataTmp, &err); if (hasOPENCLError(err, "Can't allocate memory in buffer")) return; directionsUpBufTmp = openCLHelper.clCreateBuffer_p(clContext, CL_MEM_READ_WRITE | CL_MEM_COPY_HOST_PTR, sizeof(ScoreType) * (sizeRow), g_directionsRec, &err); if (hasOPENCLError(err, "Can't allocate memory in buffer")) return; cl_mem* directionsUpBuf = &directionsUpBufTmp; directionsRecBufTmp = openCLHelper.clCreateBuffer_p(clContext, CL_MEM_READ_WRITE | CL_MEM_COPY_HOST_PTR, sizeof(ScoreType) * (sizeRow), g_directionsRec, &err); if (hasOPENCLError(err, "Can't allocate memory in buffer")) return; cl_mem* directionsRecBuf = &directionsRecBufTmp; directionsMaxBuf = openCLHelper.clCreateBuffer_p(clContext, CL_MEM_READ_WRITE | CL_MEM_COPY_HOST_PTR, sizeof(ScoreType) * (sizeRow), g_directionsRec, &err); if (hasOPENCLError(err, "Can't allocate memory in buffer")) return; algoLog.trace(QString("partsNumber: %1 queryDevider: %2").arg(partsNumber).arg(queryDevider)); algoLog.trace(QString("seqLen: %1 partSeqSize: %2 overlapSize: %3").arg(seqLibLength).arg(partSeqSize).arg(overlapLength)); algoLog.trace(QString("queryLen %1 partQuerySize: %2 sizeRow: %3").arg(queryLength).arg(partQuerySize).arg(sizeRow)); //open and read file contains OPENCL code clProgram = OpenCLUtils::createProgramByResource(clContext, deviceId, ":src/sw_opencl.cl", openCLHelper, err); if (hasOPENCLError(err, "createProgramByResource() failed")) return; clKernel = openCLHelper.clCreateKernel_p(clProgram, "calculateMatrix", &err); if (hasOPENCLError(err, "Kernel::Kernel() failed")) return; //************begin: set arguments**************** int n = 0; //0: seqLib err = openCLHelper.clSetKernelArg_p(clKernel, n++, sizeof(cl_mem), (void*)&seqLibProfBuf); if (hasOPENCLError(err, QObject::tr("Kernel::setArg(%1) failed").arg(n))) return; //1: queryProfile err = openCLHelper.clSetKernelArg_p(clKernel, n++, sizeof(cl_mem), (void*)&queryProfBuf); if (hasOPENCLError(err, QObject::tr("Kernel::setArg(%1) failed").arg(n))) return; //2: g_HdataUp err = openCLHelper.clSetKernelArg_p(clKernel, n++, sizeof(cl_mem), (void*)hDataUpBuf); if (hasOPENCLError(err, QObject::tr("Kernel::setArg(%1) failed").arg(n))) return; //3: g_HdataRec err = openCLHelper.clSetKernelArg_p(clKernel, n++, sizeof(cl_mem), (void*)hDataRecBuf); if (hasOPENCLError(err, QObject::tr("Kernel::setArg(%1) failed").arg(n))) return; //4: g_HdataMax err = openCLHelper.clSetKernelArg_p(clKernel, n++, sizeof(cl_mem), (void*)&hDataMaxBuf); if (hasOPENCLError(err, QObject::tr("Kernel::setArg(%1) failed").arg(n))) return; //5: g_FdataUp err = openCLHelper.clSetKernelArg_p(clKernel, n++, sizeof(cl_mem), (void*)&fDataUpBuf); if (hasOPENCLError(err, QObject::tr("Kernel::setArg(%1) failed").arg(n))) return; //6: g_directionsUp err = openCLHelper.clSetKernelArg_p(clKernel, n++, sizeof(cl_mem), (void*)directionsUpBuf); if (hasOPENCLError(err, QObject::tr("Kernel::setArg(%1) failed").arg(n))) return; //7: g_directionsRec err = openCLHelper.clSetKernelArg_p(clKernel, n++, sizeof(cl_mem), (void*)directionsRecBuf); if (hasOPENCLError(err, QObject::tr("Kernel::setArg(%1) failed").arg(n))) return; //8: g_directionsMax err = openCLHelper.clSetKernelArg_p(clKernel, n++, sizeof(cl_mem), (void*)&directionsMaxBuf); if (hasOPENCLError(err, QObject::tr("Kernel::setArg(%1) failed").arg(n))) return; //9: queryStartPos cl_int queryStartPos = 0; err = openCLHelper.clSetKernelArg_p(clKernel, n++, sizeof(cl_int), (void*)&queryStartPos); if (hasOPENCLError(err, QObject::tr("Kernel::setArg(%1) failed").arg(n))) return; //10: partSeqSize err = openCLHelper.clSetKernelArg_p(clKernel, n++, sizeof(cl_int), (void*)&partSeqSize); if (hasOPENCLError(err, QObject::tr("Kernel::setArg(%1) failed").arg(n))) return; //11: partsNumber err = openCLHelper.clSetKernelArg_p(clKernel, n++, sizeof(cl_int), (void*)&partsNumber); if (hasOPENCLError(err, QObject::tr("Kernel::setArg(%1) failed").arg(n))) return; //12: overlapLength err = openCLHelper.clSetKernelArg_p(clKernel, n++, sizeof(cl_int), (void*)&overlapLength); if (hasOPENCLError(err, QObject::tr("Kernel::setArg(%1) failed").arg(n))) return; //13: seqLibLength err = openCLHelper.clSetKernelArg_p(clKernel, n++, sizeof(cl_int), (void*)&searchLen); if (hasOPENCLError(err, QObject::tr("Kernel::setArg(%1) failed").arg(n))) return; //14: queryLength err = openCLHelper.clSetKernelArg_p(clKernel, n++, sizeof(cl_int), (void*)&queryLength); if (hasOPENCLError(err, QObject::tr("Kernel::setArg(%1) failed").arg(n))) return; //15: gapOpen cl_int clGapOpen = -1 * gapOpen; err = openCLHelper.clSetKernelArg_p(clKernel, n++, sizeof(cl_int), (void*)&clGapOpen); if (hasOPENCLError(err, QObject::tr("Kernel::setArg(%1) failed").arg(n))) return; //16: gapExtension cl_int clGapExtension = -1 * gapExtension; err = openCLHelper.clSetKernelArg_p(clKernel, n++, sizeof(cl_int), (void*)&clGapExtension); if (hasOPENCLError(err, QObject::tr("Kernel::setArg(%1) failed").arg(n))) return; //17: queryPartLength err = openCLHelper.clSetKernelArg_p(clKernel, n++, sizeof(cl_int), (void*)&partQuerySize); if (hasOPENCLError(err, QObject::tr("Kernel::setArg(%1) failed").arg(n))) return; //18: shared_E err = openCLHelper.clSetKernelArg_p(clKernel, n++, sizeof(cl_int) * partQuerySize, NULL); if (hasOPENCLError(err, QObject::tr("Kernel::setArg(%1) failed").arg(n))) return; //19: shared_direction err = openCLHelper.clSetKernelArg_p(clKernel, n++, sizeof(cl_int) * partQuerySize, NULL); if (hasOPENCLError(err, QObject::tr("Kernel::setArg(%1) failed").arg(n))) return; //20: shared_direction err = openCLHelper.clSetKernelArg_p(clKernel, n++, sizeof(cl_int) * partQuerySize, NULL); if (hasOPENCLError(err, QObject::tr("Kernel::setArg(%1) failed").arg(n))) return; //************end: set arguments**************** clCommandQueue = openCLHelper.clCreateCommandQueue_p(clContext, deviceId, CL_QUEUE_OUT_OF_ORDER_EXEC_MODE_ENABLE, &err); if (hasOPENCLError(err, "cl::CommandQueue() failed ")) return; coreLog.details(QObject::tr("OPENCL: Running CL program")); //run kernel const size_t szGlobalWorkSize = partsNumber * partQuerySize; const size_t szLocalWorkSize = partQuerySize; for (int i = 0; i < queryDevider; i++) { err = openCLHelper.clEnqueueNDRangeKernel_p( clCommandQueue, clKernel, 1, NULL, &szGlobalWorkSize, &szLocalWorkSize, 0, NULL, &clEvent); if (hasOPENCLError(err, "CommandQueue::enqueueNDRangeKernel() failed")) return; err = openCLHelper.clWaitForEvents_p(1, &clEvent); if (hasOPENCLError(err, "clWaitForEvents failed")) return; if (clEvent) { err = openCLHelper.clReleaseEvent_p (clEvent); if (hasOPENCLError(err, "clReleaseEvent 1 failed")) return; } //revert arrays hDataTmpBuf = hDataRecBuf; hDataRecBuf = hDataUpBuf; hDataUpBuf = hDataTmpBuf; hDataTmpBuf = directionsRecBuf; directionsRecBuf = directionsUpBuf; directionsUpBuf = hDataTmpBuf; //g_HdataUp err = openCLHelper.clSetKernelArg_p(clKernel, 2, sizeof(cl_mem), (void*)hDataUpBuf); if (hasOPENCLError(err, "Kernel::setArg(2) failed")) return; //g_HdataRec err = openCLHelper.clSetKernelArg_p(clKernel, 3, sizeof(cl_mem), (void*)hDataRecBuf); if (hasOPENCLError(err, "Kernel::setArg(3) failed")) return; //g_directionsUp err = openCLHelper.clSetKernelArg_p(clKernel, 6, sizeof(cl_mem), (void*)directionsUpBuf); if (hasOPENCLError(err, "Kernel::setArg(6) failed")) return; //g_directionsRec err = openCLHelper.clSetKernelArg_p(clKernel, 7, sizeof(cl_mem), (void*)directionsRecBuf); if (hasOPENCLError(err, "Kernel::setArg(7) failed")) return; //queryStartPos queryStartPos = (i+1) * partQuerySize; err = openCLHelper.clSetKernelArg_p(clKernel, 9, sizeof(cl_int), (void*)&queryStartPos); if (hasOPENCLError(err, "Kernel::setArg(9) failed")) return; } //copy from platform to host err = openCLHelper.clEnqueueReadBuffer_p(clCommandQueue, hDataMaxBuf, CL_FALSE, 0, sizeof(cl_int) * (sizeRow), g_HdataTmp, 0, NULL, &clEvent); if (hasOPENCLError(err, "clEnqueueReadBuffer failed")) return; err = openCLHelper.clWaitForEvents_p(1, &clEvent); if (hasOPENCLError(err, "clWaitForEvents failed")) return; if (clEvent) { err = openCLHelper.clReleaseEvent_p (clEvent); if (hasOPENCLError(err, "clReleaseEvent 2 failed")) return; } err = openCLHelper.clEnqueueReadBuffer_p(clCommandQueue, directionsMaxBuf, CL_FALSE, 0, sizeof(ScoreType) * (sizeRow), g_directionsRec, 0, NULL, &clEvent); if (hasOPENCLError(err, "clEnqueueReadBuffer failed")) return; err = openCLHelper.clWaitForEvents_p(1, &clEvent); if (hasOPENCLError(err, "clWaitForEvents failed")) return; if (clEvent) { err = openCLHelper.clReleaseEvent_p (clEvent); if (hasOPENCLError(err, "clReleaseEvent 3 failed")) return; } err = openCLHelper.clFinish_p(clCommandQueue); if (hasOPENCLError(err, "clFinish failed")) return; // cout <<"after: " <= minScore) { tmp.intervalSeq1.startPos = g_directionsRec[j]; tmp.intervalSeq1.length = j - tmp.intervalSeq1.startPos + 1 - (j) / (partSeqSize + 1) * overlapLength - (j) / (partSeqSize + 1); tmp.score = g_HdataTmp[j]; // cout <<"score: " <getOpenCLHelper(); cl_int err = CL_SUCCESS; if (clKernel) { err = openCLHelper.clReleaseKernel_p (clKernel); hasOPENCLError(err, "clReleaseEvent failed"); } if (clProgram) { err = openCLHelper.clReleaseProgram_p(clProgram); hasOPENCLError(err, "clReleaseEvent failed"); } if (clCommandQueue) { err = openCLHelper.clReleaseCommandQueue_p (clCommandQueue); hasOPENCLError(err, "clReleaseEvent failed"); } if (clContext) { err = openCLHelper.clReleaseContext_p(clContext); hasOPENCLError(err, "clReleaseEvent failed"); } if (queryProfBuf) { err = openCLHelper.clReleaseMemObject_p (queryProfBuf); hasOPENCLError(err, "clReleaseEvent failed"); } if (seqLibProfBuf) { err = openCLHelper.clReleaseMemObject_p (seqLibProfBuf); hasOPENCLError(err, "clReleaseEvent failed"); } if (hDataMaxBuf) { err = openCLHelper.clReleaseMemObject_p (hDataMaxBuf); hasOPENCLError(err, "clReleaseEvent failed"); } if (hDataUpBufTmp) { err = openCLHelper.clReleaseMemObject_p (hDataUpBufTmp); hasOPENCLError(err, "clReleaseEvent failed"); } if (hDataRecBufTmp) { err = openCLHelper.clReleaseMemObject_p (hDataRecBufTmp); hasOPENCLError(err, "clReleaseEvent failed"); } if (fDataUpBuf) { err = openCLHelper.clReleaseMemObject_p (fDataUpBuf); hasOPENCLError(err, "clReleaseEvent failed"); } if (directionsUpBufTmp) { err = openCLHelper.clReleaseMemObject_p (directionsUpBufTmp); hasOPENCLError(err, "clReleaseEvent failed"); } if (directionsRecBufTmp) { err = openCLHelper.clReleaseMemObject_p (directionsRecBufTmp); hasOPENCLError(err, "clReleaseEvent failed"); } if (directionsMaxBuf) { err = openCLHelper.clReleaseMemObject_p (directionsMaxBuf); hasOPENCLError(err, "clReleaseEvent failed"); } algoLog.details(QObject::tr("Finish cleanup OpenCL resources")); } } //namespace #endif //SW2_BUILD_WITH_OPENCL ugene-1.9.8/src/plugins/smith_waterman/src/SWTaskFactory.cpp0000644000175000017500000000227311651544324022614 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "SWTaskFactory.h" namespace U2 { SWTaskFactory::SWTaskFactory(SW_AlgType _algType) { algType = _algType; } SWTaskFactory::~SWTaskFactory() { } Task* SWTaskFactory::getTaskInstance( const SmithWatermanSettings& config, const QString& taskName) const { return new SWAlgorithmTask(config, taskName, algType); } } // namespace ugene-1.9.8/src/plugins/smith_waterman/src/SWAlgorithmTask.h0000644000175000017500000000570511651544324022603 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_SW_ALGORITHM_TASK_H_ #define _U2_SW_ALGORITHM_TASK_H_ #include #include #include #include #include #include "SmithWatermanAlgorithm.h" #include "PairAlignSequences.h" #include #include namespace U2 { enum SW_AlgType {SW_classic, SW_sse2, SW_cuda, SW_opencl}; class CudaGpuModel; class OpenCLGpuModel; class SWAlgorithmTask : public Task, public SequenceWalkerCallback { Q_OBJECT public: SWAlgorithmTask(const SmithWatermanSettings& s, const QString& taskName, SW_AlgType algType); ~SWAlgorithmTask(); void prepare(); virtual void onRegion(SequenceWalkerSubtask* t, TaskStateInfo& ti); QList & getResult(); ReportResult report(); QList onSubTaskFinished(Task* subTask); private: void addResult(QList & res); int calculateMatrixLength(const QByteArray & searchSeq, const QByteArray & patternSeq, int gapOpent, int gapExtension, int maxScore, int minScore); void removeResultFromOverlap(QList & res); int calculateMaxScore(const QByteArray & seq, const SMatrix& substitutionMatrix); void setupTask(int maxScore); QList pairAlignSequences; int minScore; QMutex lock; SW_AlgType algType; QList resultList; SmithWatermanSettings sWatermanConfig; SequenceWalkerTask* t; union { CudaGpuModel * cudaGpu; } gpuModel; }; class SWResultsPostprocessingTask : public Task{ Q_OBJECT public: SWResultsPostprocessingTask(SmithWatermanSettings &_sWatermanConfig, QList &_resultList, QList &_resPAS); ~SWResultsPostprocessingTask(){}; void prepare(); void run(); ReportResult report(){return ReportResult_Finished;}; private: SmithWatermanSettings sWatermanConfig; QList resultList; QList resPAS; }; } #endif ugene-1.9.8/src/plugins/smith_waterman/src/SmithWatermanTests.cpp0000644000175000017500000003243411651544324023720 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "SmithWatermanTests.h" #include #include #include #include #include #include #include #define FILE_SUBSTITUTION_MATRIX_ATTR "subst_f" #define FILE_FASTA_CONTAIN_SEQUENCE_ATTR "seq_f" #define FILE_FASTA_CONTAIN_PATTERN_ATTR "pattern_f" #define GAP_OPEN_ATTR "g_o" #define GAP_EXT_ATTR "g_e" #define PERCENT_OF_SCORE_ATTR "percent_of_score" #define EXPECTED_RESULT_ATTR "expected_res" #define ENV_IMPL_ATTR "IMPL" #define REMOTE_MACHINE "MACHINE" #define IMPL_ATTR "impl" using namespace std; namespace U2 { void GTest_SmithWatermnan::sortByScore(QList & resultsForSort) { for (int i = 0; i < resultsForSort.size(); i++) { for (int j = i + 1; j < resultsForSort.size(); j++) { if (resultsForSort.at(i).score < resultsForSort.at(j).score) { SmithWatermanResult buf = resultsForSort.at(i); resultsForSort[i] = resultsForSort.at(j); resultsForSort[j] = buf; } if (resultsForSort.at(i).score == resultsForSort.at(j).score && resultsForSort.at(i).region.startPos > resultsForSort.at(j).region.startPos) { SmithWatermanResult buf = resultsForSort.at(i); resultsForSort[i] = resultsForSort.at(j); resultsForSort[j] = buf; } if (resultsForSort.at(i).score == resultsForSort.at(j).score && resultsForSort.at(i).region.startPos == resultsForSort.at(j).region.startPos && resultsForSort.at(i).region.length > resultsForSort.at(j).region.length) { SmithWatermanResult buf = resultsForSort.at(i); resultsForSort[i] = resultsForSort.at(j); resultsForSort[j] = buf; } } } } void GTest_SmithWatermnan::init(XMLTestFormat *, const QDomElement& el) { searchSeqDocName = el.attribute(FILE_FASTA_CONTAIN_SEQUENCE_ATTR); if (searchSeqDocName.isEmpty()) { failMissingValue(FILE_FASTA_CONTAIN_SEQUENCE_ATTR); return; } patternSeqDocName = el.attribute(FILE_FASTA_CONTAIN_PATTERN_ATTR); if (patternSeqDocName.isEmpty()) { failMissingValue(FILE_FASTA_CONTAIN_PATTERN_ATTR); return; } pathToSubst = el.attribute(FILE_SUBSTITUTION_MATRIX_ATTR); if (pathToSubst.isEmpty()) { failMissingValue(FILE_SUBSTITUTION_MATRIX_ATTR); return; } QString buffer = el.attribute(GAP_OPEN_ATTR); bool ok = false; if (!buffer.isEmpty()) { ok=false; gapOpen = buffer.toInt(&ok); if(!ok) { failMissingValue(GAP_OPEN_ATTR); return; } } buffer = el.attribute(GAP_EXT_ATTR); if (!buffer.isEmpty()) { ok=false; gapExtension = buffer.toInt(&ok); if(!ok) { failMissingValue(GAP_EXT_ATTR); return; } } buffer = el.attribute(PERCENT_OF_SCORE_ATTR); if (!buffer.isEmpty()) { ok=false; percentOfScore = buffer.toFloat(&ok); if(!ok) { failMissingValue(PERCENT_OF_SCORE_ATTR); return; } } expected_res = el.attribute(EXPECTED_RESULT_ATTR); if (expected_res.isEmpty()) { failMissingValue(EXPECTED_RESULT_ATTR); return; } if (!parseExpected_res()) { stateInfo.setError(QString("value not correct %1").arg(EXPECTED_RESULT_ATTR)); return; } impl = env->getVar(ENV_IMPL_ATTR); if (impl.isEmpty()) { failMissingValue(ENV_IMPL_ATTR); return; } machinePath = env->getVar( REMOTE_MACHINE ); if( !machinePath.isEmpty() ) { machinePath = env->getVar( "COMMON_DATA_DIR" ) + "/" + machinePath; } } void GTest_SmithWatermnan::prepare() { //get search sequence DNASequenceObject * searchSeqObj = getContext(this, searchSeqDocName); if(searchSeqObj==NULL){ stateInfo.setError(QString("error can't cast to sequence from GObject")); return; } searchSeq = searchSeqObj->getDNASequence().seq; //get pattern sequence DNASequenceObject * patternSeqObj = getContext(this, patternSeqDocName); if(patternSeqObj==NULL){ stateInfo.setError(QString("error can't cast to sequence from GObject")); return; } patternSeq = patternSeqObj->getDNASequence().seq; //set subst matrix QString pathToCommonData = getEnv()->getVar("COMMON_DATA_DIR"); if(patternSeqObj==NULL){ stateInfo.setError(QString("error can't get path to common_data dir")); return; } QString fullPathToSubst = pathToCommonData + "/" + pathToSubst; QString error; SMatrix mtx = SubstMatrixRegistry::readMatrixFromFile(fullPathToSubst, error); if (mtx.isEmpty()) { stateInfo.setError(QString("value not set %1").arg(FILE_SUBSTITUTION_MATRIX_ATTR)); return; } s.pSm = mtx; s.sqnc = searchSeq; s.ptrn = patternSeq; s.globalRegion.startPos = 0; s.globalRegion.length = searchSeq.length(); s.gapModel.scoreGapOpen = gapOpen; s.gapModel.scoreGapExtd = gapExtension; s.percentOfScore = percentOfScore; s.aminoTT = NULL; s.complTT = NULL; s.strand = StrandOption_DirectOnly; s.resultCallback = NULL; s.resultListener = NULL; s.resultFilter = 0; if( !machinePath.isEmpty() ) { /* run smith-waterman on remote machine */ //TODO: BUG-001870 assert(0); // SmithWatermanLocalTaskSettings localTaskSettings( s ); // RemoteMachine * machine = NULL; // if( !SerializeUtils::deserializeRemoteMachineSettingsFromFile( machinePath, &machine ) ) { // setError( QString( "Cannot create remote machine from '%1'" ).arg( machinePath ) ); // return; // } // assert( NULL != machine ); // swAlgorithmTask = new RemoteTask( SmithWatermanLocalTaskFactory::ID, localTaskSettings, machine ); } else { /* run on local machine */ s.resultListener = new SmithWatermanResultListener(); if (0 != AppContext::getSmithWatermanTaskFactoryRegistry()->getFactory(impl)) { swAlgorithmTask = (Task *) AppContext::getSmithWatermanTaskFactoryRegistry()->getFactory(impl)->getTaskInstance(s, "tests SmithWaterman"); } else { stateInfo.setError(QString("Not known impl of Smith-Waterman: %1").arg(impl)); return; } } addSubTask(swAlgorithmTask); } bool GTest_SmithWatermnan::parseExpected_res() { SWresult swRes; QStringList expectedList = expected_res.split(tr("**")); foreach(QString res, expectedList) { QStringList resValues = res.split(tr(",")); if (resValues.size() != 2) { stateInfo.setError(QString("wrong count values in expected result: %1").arg(resValues.size())); return false; } //////// first enterval QStringList bounds = resValues.at(1).split(tr("..")); if (bounds.size() != 2) { stateInfo.setError( QString("wrong region in expected result %1").arg(resValues.at(1)) ); return false; } bool startOk, finishOk; int start = bounds.first().toInt(&startOk); int finish = bounds.last().toInt(&finishOk); if (startOk && finishOk != true) { stateInfo.setError( QString("wrong region in expected result %1").arg(resValues.at(1)) ); return false; } swRes.sInterval.startPos = start; swRes.sInterval.length = finish - start; start = resValues.at(0).toInt(&startOk); if (startOk != true) { stateInfo.setError( QString("wrong scorein expected result %1").arg(resValues.at(0)) ); return false; } swRes.score= start; expectedRes.append(swRes); } return true; } bool GTest_SmithWatermnan::toInt(QString & str, int & num) { bool ok = false; if (!str.isEmpty()) { num = str.toInt(&ok); } return ok; } Task::ReportResult GTest_SmithWatermnan::report() { propagateSubtaskError(); if( hasError() ) { return ReportResult_Finished; } QList resultList; if( !machinePath.isEmpty() ) { /* remote task used */ //TODO: BUG-0001870 // RemoteTask * remoteSW = qobject_cast( swAlgorithmTask ); // assert( NULL != remoteSW ); // SmithWatermanLocalTaskResult * result = dynamic_cast( remoteSW->getResult() ); // assert( NULL != result ); // resultList = result->getResult(); } else { /* task on local machine */ resultList = s.resultListener->popResults(); } sortByScore(resultList); if (expectedRes.size() != resultList.size()) { stateInfo.setError(QString("Not expected result: count result not coincide")); return ReportResult_Finished; } for (int i = 0; i < resultList.size(); i++) { if (expectedRes.at(i).score != resultList.at(i).score || expectedRes.at(i).sInterval != resultList.at(i).region) { stateInfo.setError(QString("Not expected result")); return ReportResult_Finished; } } return ReportResult_Finished; } void GTest_SmithWatermnanPerf::init(XMLTestFormat *tf, const QDomElement& el) { Q_UNUSED(tf); searchSeqDocName = el.attribute(FILE_FASTA_CONTAIN_SEQUENCE_ATTR); if (searchSeqDocName.isEmpty()) { failMissingValue(FILE_FASTA_CONTAIN_SEQUENCE_ATTR); return; } patternSeqDocName = el.attribute(FILE_FASTA_CONTAIN_PATTERN_ATTR); if (patternSeqDocName.isEmpty()) { failMissingValue(FILE_FASTA_CONTAIN_PATTERN_ATTR); return; } impl = el.attribute(IMPL_ATTR); if (patternSeqDocName.isEmpty()) { failMissingValue(IMPL_ATTR); return; } pathToSubst = "smith_waterman2/blosum62.txt"; gapOpen = -1; gapExtension = -1; percentOfScore = 100; } void GTest_SmithWatermnanPerf::prepare() { //get search sequence DNASequenceObject * searchSeqObj = getContext(this, searchSeqDocName); if(searchSeqObj==NULL){ stateInfo.setError(QString("error can't cast to sequence from GObject")); return; } searchSeq = searchSeqObj->getDNASequence().seq; //get pattern sequence DNASequenceObject * patternSeqObj = getContext(this, patternSeqDocName); if(patternSeqObj==NULL){ stateInfo.setError(QString("error can't cast to sequence from GObject")); return; } patternSeq = patternSeqObj->getDNASequence().seq; setTaskName(QString("Test seq size %1").arg(patternSeq.size())); //set subst matrix QString pathToCommonData = getEnv()->getVar("COMMON_DATA_DIR"); if(patternSeqObj==NULL){ stateInfo.setError(QString("error can't get path to common_data dir")); return; } QString fullPathToSubst = pathToCommonData + "/" + pathToSubst; QString error; SMatrix mtx = SubstMatrixRegistry::readMatrixFromFile(fullPathToSubst, error); if (mtx.isEmpty()) { stateInfo.setError(QString("value not set %1").arg(FILE_SUBSTITUTION_MATRIX_ATTR)); return; } s.pSm = mtx; s.sqnc = searchSeq; s.ptrn = patternSeq; s.globalRegion.startPos = 0; s.globalRegion.length = searchSeq.length(); s.gapModel.scoreGapOpen = gapOpen; s.gapModel.scoreGapExtd = gapExtension; s.percentOfScore = percentOfScore; s.aminoTT = NULL; s.complTT = NULL; s.strand = StrandOption_DirectOnly; s.resultCallback = NULL; s.resultListener = NULL; s.resultFilter = 0; s.resultListener = new SmithWatermanResultListener(); if (0 != AppContext::getSmithWatermanTaskFactoryRegistry()->getFactory(impl)) { swAlgorithmTask = (Task *) AppContext::getSmithWatermanTaskFactoryRegistry()->getFactory(impl)->getTaskInstance(s, "test SW performance"); } else { stateInfo.setError(QString("Not known impl of Smith-Waterman: %1").arg(impl)); return; } addSubTask(swAlgorithmTask); } Task::ReportResult GTest_SmithWatermnanPerf::report() { propagateSubtaskError(); if( hasError() ) { return ReportResult_Finished; } return ReportResult_Finished; } } ugene-1.9.8/src/plugins/smith_waterman/src/SmithWatermanTests.h0000644000175000017500000000511011651544324023354 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_SW_ALHORITHM_TESTS_H_ #define _U2_SW_ALHORITHM_TESTS_H_ #include #include #include #include #include #include #include namespace U2 { struct SWresult{ U2Region sInterval; int score; }; class GTest_SmithWatermnan : public GTest { Q_OBJECT public: SIMPLE_XML_TEST_BODY_WITH_FACTORY(GTest_SmithWatermnan, "plugin_sw-algorithm"); void prepare(); Task::ReportResult report(); static void sortByScore(QList & resultsForSort); private: SmithWatermanSettings s; bool parseExpected_res(); bool toInt(QString & str, int & num); QByteArray patternSeq; QByteArray searchSeq; QString patternSeqDocName; QString searchSeqDocName; QString expected_res; QString pathToSubst; QString impl; int gapOpen; int gapExtension; float percentOfScore; QString resultDocContextName; QList expectedRes; Task * swAlgorithmTask; QString machinePath; }; class GTest_SmithWatermnanPerf : public GTest { Q_OBJECT public: SIMPLE_XML_TEST_BODY_WITH_FACTORY(GTest_SmithWatermnanPerf, "test-sw-performance"); void prepare(); Task::ReportResult report(); private: SmithWatermanSettings s; QByteArray patternSeq; QByteArray searchSeq; QString patternSeqDocName; QString searchSeqDocName; QString pathToSubst; QString impl; int gapOpen; int gapExtension; float percentOfScore; QString resultDocContextName; QList expectedRes; Task * swAlgorithmTask; }; } //namespace #endif ugene-1.9.8/src/plugins/smith_waterman/src/SmithWatermanAlgorithmCUDA.cpp0000644000175000017500000000645411651544324025204 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifdef SW2_BUILD_WITH_CUDA #include "SmithWatermanAlgorithmCUDA.h" #include "sw_cuda_cpp.h" #include "PairAlignSequences.h" #include #include using namespace std; namespace U2 { quint64 SmithWatermanAlgorithmCUDA::estimateNeededGpuMemory( const SMatrix& sm, QByteArray const & _patternSeq, QByteArray const & _searchSeq ) { const QByteArray & alphChars = sm.getAlphabet()->getAlphabetChars(); int subLen = alphChars.size(); int qLen = _patternSeq.size(); int profLen = subLen * (qLen + 1) * (alphChars[ alphChars.size()-1 ] + 1); return sw_cuda_cpp::estimateNeededGpuMemory( _searchSeq.size(), profLen, qLen ); } void SmithWatermanAlgorithmCUDA::launch(const SMatrix& sm, QByteArray const & _patternSeq, QByteArray const & _searchSeq, int _gapOpen, int _gapExtension, int _minScore) { algoLog.details("START SmithWatermanAlgorithmCUDA::launch"); int qLen = _patternSeq.size(); int subLen = sm.getAlphabet()->getNumAlphabetChars(); //alphChars is sorted const QByteArray & alphChars = sm.getAlphabet()->getAlphabetChars(); int profLen = subLen * (qLen + 1) * (alphChars[ alphChars.size()-1 ] + 1); ScoreType * queryProfile = new ScoreType[profLen]; for (int i = 0; i < profLen; i++) { queryProfile[i] = 0; } //calculate query profile for (int i = 0; i < subLen; i++) { for (int j = 0; j < qLen; j++) { char ch = alphChars[i]; queryProfile[ch * qLen + j] = sm.getScore(ch, _patternSeq.at(j)); } } sw_cuda_cpp sw; QList pResults = sw.launch(_searchSeq.constData(), _searchSeq.size(), queryProfile, profLen, qLen, (-1)*_gapOpen, (-1)*_gapExtension, _minScore); // Collect results PairAlignSequences tmp; resType res; QMutableListIterator iter(pResults); while( iter.hasNext() ) { res = iter.next(); tmp.score = res.score; tmp.intervalSeq1.startPos = res.reg.startPos; tmp.intervalSeq1.length = res.reg.length; pairAlignmentStrings.append(tmp); } //free memory delete[] queryProfile; algoLog.details("FINISH SmithWatermanAlgorithmCUDA::launch"); } } //namespase #endif //SW2_BUILD_WITH_CUDA ugene-1.9.8/src/plugins/smith_waterman/src/PairAlignSequences.h0000644000175000017500000000252511651544324023277 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef PAIRALIGNMENTSTRINGS_H #define PAIRALIGNMENTSTRINGS_H #include namespace U2 { class PairAlignSequences { public: PairAlignSequences(); void setValues(int _score, U2Region const & _intervalSeq1); U2Region intervalSeq1; int score; bool isAminoTranslated; bool isDNAComplemented; static const char UP = 'u'; static const char LEFT = 'l'; static const char DIAG = 'd'; static const char GAP_CHARACTER = '_'; }; }//namespace #endif ugene-1.9.8/src/plugins/smith_waterman/src/SmithWatermanAlgorithmCUDA.h0000644000175000017500000000267211651544324024647 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifdef SW2_BUILD_WITH_CUDA #ifndef _SMITHWATERMANALGORITHM_CUDA_H #define _SMITHWATERMANALGORITHM_CUDA_H #include "SmithWatermanAlgorithm.h" namespace U2 { class SmithWatermanAlgorithmCUDA : public SmithWatermanAlgorithm { public: typedef int ScoreType; virtual void launch(const SMatrix& m, QByteArray const & _patternSeq, QByteArray const & _searchSeq, int _gapOpen, int _gapExtension, int _minScore); static quint64 estimateNeededGpuMemory( const SMatrix& sm, QByteArray const & _patternSeq, QByteArray const & _searchSeq ); private: }; } // namespace #endif #endif //SW2_BUILD_WITH_CUDA ugene-1.9.8/src/plugins/smith_waterman/src/SWTaskFactory.h0000644000175000017500000000301311651544324022252 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_SMITH_WATERMAN_ALG_IMPL_H_ #define _U2_SMITH_WATERMAN_ALG_IMPL_H_ #include #include #include #include #include "SWAlgorithmTask.h" namespace U2 { class SWTaskFactory: public SmithWatermanTaskFactory { public: SWTaskFactory(SW_AlgType _algType); virtual ~SWTaskFactory(); virtual Task* getTaskInstance(const SmithWatermanSettings& config, const QString& taskName) const; private: bool isValidParameters(const SmithWatermanSettings& sWatermanConfig, SequenceWalkerSubtask* t) const; SW_AlgType algType; }; } // namespace #endif ugene-1.9.8/src/plugins/smith_waterman/src/SWQuery.cpp0000644000175000017500000003133411651544324021467 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "SWQuery.h" #include #include #include #include #include #include #include #include #include #include #include #include #include namespace U2 { static const QString PATTERN_ATTR("pattern"); static const QString SCORE_ATTR("min-score"); static const QString MATRIX_ATTR("matrix"); static const QString AMINO_ATTR("translate"); static const QString ALGO_ATTR("algorithm"); static const QString FILTER_ATTR("filter"); static const QString GAPOPEN_ATTR("gap-open-score"); static const QString GAPEXT_ATTR("gap-ext-score"); void SWAlgoEditor::populate() { QStringList algoLst = AppContext::getSmithWatermanTaskFactoryRegistry()->getListFactoryNames(); if (algoLst.isEmpty()) { return; } foreach(const QString& n, algoLst) { items.insert(n,n); } algAttr->setAttributeValue(algoLst.first()); } /************************************************************************/ /* QDSWActor */ /************************************************************************/ QDSWActor::QDSWActor(QDActorPrototype const* proto) : QDActor(proto), algo(0) { units["sw"] = new QDSchemeUnit(this); algo = NULL; } int QDSWActor::getMinResultLen() const { return cfg->getParameter(PATTERN_ATTR)->getAttributeValue().toAscii().size()/2; } int QDSWActor::getMaxResultLen() const { return 4*getMinResultLen(); } QString QDSWActor::getText() const { QMap params = cfg->getParameters(); QString pattern = params.value(PATTERN_ATTR)->getAttributeValue().toAscii().toUpper(); if (pattern.isEmpty()) { pattern = "unset"; } pattern = QString("%2").arg(PATTERN_ATTR).arg(pattern); int percentOfScore = params.value(SCORE_ATTR)->getAttributeValue(); QString percentOfScoreStr = QString("%2%").arg(SCORE_ATTR).arg(percentOfScore); QString match = percentOfScore < 100 ? QDSWActor::tr("matches with at least %1 score").arg(percentOfScoreStr) : QDSWActor::tr("exact matches"); QString strandName; switch (strand) { case QDStrand_Both: strandName = QDSWActor::tr("both strands"); break; case QDStrand_DirectOnly: strandName = QDSWActor::tr("direct strand"); break; case QDStrand_ComplementOnly: strandName = QDSWActor::tr("complement strand"); break; default: break; } QString doc = QDSWActor::tr("Finds pattern %1." "
Looks for %2 in %3.") .arg(pattern) .arg(match) .arg(strandName); return doc; } Task* QDSWActor::getAlgorithmTask(const QVector& searchLocation) { Task* task = NULL; assert(scheme); QMap params = cfg->getParameters(); settings.aminoTT = NULL; settings.complTT = NULL; switch(getStrandToRun()) { case QDStrand_Both: settings.strand = StrandOption_Both; break; case QDStrand_DirectOnly: settings.strand = StrandOption_DirectOnly; break; case QDStrand_ComplementOnly: settings.strand = StrandOption_ComplementOnly; break; } settings.percentOfScore = params.value(SCORE_ATTR)->getAttributeValue(); if(settings.percentOfScore<0&&settings.percentOfScore>100) { QString err = tr("%1: percent of score out of bounds.").arg(getParameters()->getLabel()); return new FailTask(err); } settings.gapModel.scoreGapExtd = params.value(GAPEXT_ATTR)->getAttributeValue(); settings.gapModel.scoreGapOpen = params.value(GAPOPEN_ATTR)->getAttributeValue(); mtrx = params.value(MATRIX_ATTR)->getAttributeValue(); settings.pSm = AppContext::getSubstMatrixRegistry()->getMatrix(mtrx); QString filter = params.value(FILTER_ATTR)->getAttributeValue(); settings.resultFilter = AppContext::getSWResultFilterRegistry()->getFilter(filter); if(!settings.resultFilter) { QString err = tr("%1: incorrect result filter.").arg(getParameters()->getLabel()); return new FailTask(err); } settings.ptrn = params.value(PATTERN_ATTR)->getAttributeValue().toAscii().toUpper(); if(settings.ptrn.isEmpty()) { QString err = tr("%1: pattern is empty.").arg(getParameters()->getLabel()); return new FailTask(err); } QString algName = params.value(ALGO_ATTR)->getAttributeValue(); algo = AppContext::getSmithWatermanTaskFactoryRegistry()->getFactory(algName); if(!algo) { QString err = tr("%1: can not find %2.") .arg(getParameters()->getLabel()) .arg(algName); return new FailTask(err); } DNASequenceObject* dna = scheme->getDNA(); settings.sqnc = QByteArray(dna->getSequence().constData(), dna->getSequenceLen()); if (settings.strand != StrandOption_DirectOnly) { QList compTTs = AppContext::getDNATranslationRegistry()-> lookupTranslation(dna->getAlphabet(), DNATranslationType_NUCL_2_COMPLNUCL); if (!compTTs.isEmpty()) { settings.complTT = compTTs.first(); } else { //Could not find complement translation, searching only direct strand settings.strand = StrandOption_DirectOnly; } } if (params.value(AMINO_ATTR)->getAttributeValue()) { DNATranslationType tt = (dna->getAlphabet()->getType() == DNAAlphabet_NUCL) ? DNATranslationType_NUCL_2_AMINO : DNATranslationType_RAW_2_AMINO; QList TTs = AppContext::getDNATranslationRegistry()->lookupTranslation(dna->getAlphabet(), tt); if (!TTs.isEmpty()) { settings.aminoTT = TTs.first(); //FIXME let user choose or use hints ? } } assert(dna->getAlphabet()->containsAll(settings.ptrn.constData(),settings.ptrn.length())); assert(settings.pSm.getName().isEmpty() && mtrx.toLower() != "auto"); if (settings.pSm.isEmpty()) { QString matrixName; QStringList lst = AppContext::getSubstMatrixRegistry()->selectMatrixNamesByAlphabet(dna->getAlphabet()); if (!lst.isEmpty()) { matrixName = lst.first(); settings.pSm = AppContext::getSubstMatrixRegistry()->getMatrix(matrixName); } assert(!settings.pSm.isEmpty()); } settings.globalRegion = dna->getSequenceRange(); //SmithWatermanReportCallbackImpl* rcb = new SmithWatermanReportCallbackImpl(NULL, resultName, QString()); //FIXME!!! where to delete? //settings.resultCallback = rcb; //settings.resultListener = new SmithWatermanResultListener(); //FIXME: where to delete?? //task = algo->getTaskInstance(settings, QDSWActor::tr("smith_waterman_task")); task = new Task(tr("SSearch"), TaskFlag_NoRun); foreach(const U2Region& r, searchLocation) { SmithWatermanSettings stngs(settings); SmithWatermanReportCallbackImpl* rcb = new SmithWatermanReportCallbackImpl(NULL,"",QString()); stngs.resultCallback = rcb; stngs.resultListener = new SmithWatermanResultListener(); stngs.globalRegion = r; Task* sub = algo->getTaskInstance(stngs, tr("smith_waterman_task")); rcb->setParent(sub); task->addSubTask(sub); callbacks.insert(sub, rcb); } //callbacks.insert(task, rcb); connect(new TaskSignalMapper(task), SIGNAL(si_taskFinished(Task*)), SLOT(sl_onAlgorithmTaskFinished(Task*))); return task; } void QDSWActor::sl_onAlgorithmTaskFinished(Task*) { /*SmithWatermanReportCallbackImpl* rcb = callbacks.take(t); assert(rcb);*/ //const QList& res = rcb->getAnotations(); QList res; QMapIterator iter(callbacks); while (iter.hasNext()) { iter.next(); res << iter.value()->getAnotations(); } //QDStrandOption schemaStrand = scheme->getStrand(); foreach(const SharedAnnotationData& ad, res) { QDResultUnit ru(new QDResultUnitData); ru->strand = ad->getStrand(); ru->quals = ad->qualifiers; ru->region = ad->location->regions.first(); ru->owner = units.value("sw"); QDResultGroup::buildGroupFromSingleResult(ru, results); } callbacks.clear(); } SWQDActorFactory::SWQDActorFactory() { descriptor.setId("ssearch"); descriptor.setDisplayName(QDSWActor::tr("Smith-Waterman")); descriptor.setDocumentation(QDSWActor::tr("Finds regions of similarity to the specified pattern in each input sequence (nucleotide or protein one). " "

Under the hood is the well-known Smith-Waterman algorithm for performing local sequence alignment.")); QStringList filterLst = AppContext::getSWResultFilterRegistry()->getFiltersIds(); QString defFilter = SWRF_EmptyFilter().getId(); if(!filterLst.contains(defFilter)) { defFilter = AppContext::getSWResultFilterRegistry()->getDefaultFilterId(); } Descriptor pd(PATTERN_ATTR, QDSWActor::tr("Pattern"), QDSWActor::tr("A subsequence pattern to look for.")); Descriptor scd(SCORE_ATTR, QDSWActor::tr("Min score"), QDSWActor::tr("The search stringency.")); Descriptor ald(ALGO_ATTR, QDSWActor::tr("Algorithm"), QDSWActor::tr("Algorithm version.")); Descriptor amd(AMINO_ATTR, QDSWActor::tr("Search in translation"), QDSWActor::tr("Translate a supplied nucleotide sequence to protein then search in the translated sequence.")); Descriptor mxd(MATRIX_ATTR, QDSWActor::tr("Scoring matrix"), QDSWActor::tr("The scoring matrix.")); Descriptor frd(FILTER_ATTR, QDSWActor::tr("Filter results"), QDSWActor::tr("Result filtering strategy.")); Descriptor god(GAPOPEN_ATTR, QDSWActor::tr("Gap open score"), QDSWActor::tr("Gap open score.")); Descriptor ged(GAPEXT_ATTR, QDSWActor::tr("Gap ext score"), QDSWActor::tr("Gap extension score.")); attributes << new Attribute(pd, BaseTypes::STRING_TYPE(), true); attributes << new Attribute(mxd, BaseTypes::STRING_TYPE(), true, QString("---")); Attribute* algAttr = new Attribute(ald, BaseTypes::STRING_TYPE(), true); attributes << algAttr; attributes << new Attribute(frd, BaseTypes::STRING_TYPE(), false, defFilter); attributes << new Attribute(scd, BaseTypes::NUM_TYPE(), false, 90); attributes << new Attribute(amd, BaseTypes::BOOL_TYPE(), false, false); attributes << new Attribute(god, BaseTypes::NUM_TYPE(), false, -10.); attributes << new Attribute(ged, BaseTypes::NUM_TYPE(), false, -1.); QMap delegates; { QVariantMap m; m["minimum"] = 1; m["maximum"] = 100; m["suffix"] = "%"; delegates[SCORE_ATTR] = new SpinBoxDelegate(m); } { QVariantMap m; m["maximum"] = -0.; m["minimum"]=-10000000.; delegates[GAPOPEN_ATTR] = new DoubleSpinBoxDelegate(m); m["maximum"] = -1.; delegates[GAPEXT_ATTR] = new DoubleSpinBoxDelegate(m); } { QVariantMap m; foreach(const QString& n, filterLst) { m.insert(n,n); } delegates[FILTER_ATTR] = new ComboBoxDelegate(m); } { QVariantMap m; m.insert(QDSWActor::tr("Auto"), QString("---")); QStringList lst = AppContext::getSubstMatrixRegistry()->getMatrixNames(); foreach(const QString& n, lst) { m.insert(n,n); } delegates[MATRIX_ATTR] = new ComboBoxDelegate(m); } SWAlgoEditor* aled = new SWAlgoEditor(algAttr); aled->connect(AppContext::getPluginSupport(), SIGNAL(si_allStartUpPluginsLoaded()), SLOT(populate())); aled->populate(); delegates[ALGO_ATTR] = aled; editor = new DelegateEditor(delegates); } }//namespace ugene-1.9.8/src/plugins/smith_waterman/src/SmithWatermanAlgorithmOPENCL.h0000644000175000017500000000446111651544324025111 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifdef SW2_BUILD_WITH_OPENCL #ifndef _SMITHWATERMANALGORITHM_OPENCL_H #define _SMITHWATERMANALGORITHM_OPENCL_H #include #include #include #include "SmithWatermanAlgorithm.h" namespace U2 { class SmithWatermanAlgorithmOPENCL : public SmithWatermanAlgorithm { public: typedef int ScoreType; SmithWatermanAlgorithmOPENCL(); ~SmithWatermanAlgorithmOPENCL(); virtual void launch(const SMatrix& m, QByteArray const & _patternSeq, QByteArray const & _searchSeq, int _gapOpen, int _gapExtension, int _minScore); static quint64 estimateNeededGpuMemory( const SMatrix& sm, QByteArray const & _patternSeq, QByteArray const & _searchSeq ); private: int calcOverlap(int queryLength); int calcPartsNumber(int seqLibLength, int overlapLength); int calcPartSeqSize(int seqLibLength, int overlapLength, int partsNumber); int calcSizeRow(int partsNumber, int partSeqSize); const int MAX_BLOCKS_NUMBER; const int MAX_SHARED_VECTOR_LENGTH; cl_event clEvent; cl_kernel clKernel; cl_program clProgram; cl_command_queue clCommandQueue; cl_context clContext; cl_mem queryProfBuf; cl_mem seqLibProfBuf; cl_mem hDataMaxBuf; cl_mem hDataUpBufTmp; cl_mem hDataRecBufTmp; cl_mem fDataUpBuf; cl_mem directionsUpBufTmp; cl_mem directionsRecBufTmp; cl_mem directionsMaxBuf; }; } // namespace #endif #endif //SW2_BUILD_WITH_OPENCL ugene-1.9.8/src/plugins/smith_waterman/src/SWWorker.h0000644000175000017500000000463711651544324021306 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_SW_WORKER_H_ #define _U2_SW_WORKER_H_ #include #include #include #include #include #include namespace U2 { namespace LocalWorkflow { class SWPrompter : public PrompterBase { Q_OBJECT public: SWPrompter(Actor* p = 0) : PrompterBase(p) {} protected: QString composeRichDoc(); }; class SWAlgoEditor : public ComboBoxDelegate { Q_OBJECT public: SWAlgoEditor(ActorPrototype* proto) : ComboBoxDelegate(QVariantMap()), proto(proto) {} public slots: void populate(); private: ActorPrototype* proto; }; class SWWorker : public BaseWorker { Q_OBJECT public: SWWorker(Actor* a); virtual void init(); virtual bool isReady(); virtual Task* tick(); virtual bool isDone(); virtual void cleanup(); private slots: void sl_taskFinished(Task*); private: QString readPatternsFromFile(const QString url); private: CommunicationChannel *input, *output; QMap callbacks; QMap patterns; QMap patternNames; QMap fastaHeaders; }; class SWWorkerFactory : public DomainFactory { public: static const QString ACTOR_ID; static void init(); SWWorkerFactory() : DomainFactory(ACTOR_ID) {} virtual Worker* createWorker(Actor* a) {return new SWWorker(a);} }; } //namespace LocalWorkflow } // U2 namespace #endif ugene-1.9.8/src/plugins/smith_waterman/src/SmithWatermanAlgorithmSSE2.h0000644000175000017500000000326411651544324024645 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifdef SW2_BUILD_WITH_SSE2 #ifndef _SMITHWATERMANALGORITHM_SSE2_H #define _SMITHWATERMANALGORITHM_SSE2_H #include "SmithWatermanAlgorithm.h" #include namespace U2 { class SmithWatermanAlgorithmSSE2 : public SmithWatermanAlgorithm { public: typedef qint16 ScoreType; virtual void launch(const SMatrix& substitutionMatrix, QByteArray const & _patternSeq, QByteArray const & _searchSeq, int _gapOpen, int _gapExtension, int _minScore); private: static const int nElementsInVec = 8; void printVector(__m128i &toprint, int add); void calculateMatrix(); int calculateMatrixSSE2(unsigned queryLength, unsigned char *dbSeq, unsigned dbLength, unsigned short gapOpenOrig, unsigned short gapExtend); ScoreType ** matrix; ScoreType maximumScore; }; } // namespace #endif #endif //SW2_BUILD_WITH_SSE2 ugene-1.9.8/src/plugins/smith_waterman/src/SWQuery.h0000644000175000017500000000421511651544324021132 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_SW_QUERY_H_ #define _U2_SW_QUERY_H_ #include #include #include #include #include namespace U2 { class Attribute; class SWAlgoEditor : public ComboBoxDelegate { Q_OBJECT public: SWAlgoEditor(Attribute* algAttr) : ComboBoxDelegate(QVariantMap()), algAttr(algAttr) {} public slots: void populate(); private: Attribute* algAttr; }; class QDSWActor : public QDActor { Q_OBJECT public: QDSWActor(QDActorPrototype const* proto); int getMinResultLen() const; int getMaxResultLen() const; QString getText() const; Task* getAlgorithmTask(const QVector& location); QColor defaultColor() const { return QColor(0xff,0xf8,0); } private slots: void sl_onAlgorithmTaskFinished(Task*); private: SmithWatermanSettings settings; QString transId, mtrx; SmithWatermanTaskFactory* algo; QMap callbacks; }; class SWQDActorFactory : public QDActorPrototype { public: SWQDActorFactory(); QIcon getIcon() const { return QIcon(":core/images/sw.png"); } virtual QDActor* createInstance() const { return new QDSWActor(this); } }; }//namespace #endif ugene-1.9.8/src/plugins/smith_waterman/src/SWWorker.cpp0000644000175000017500000005317111651544324021636 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "SWWorker.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include namespace U2 { namespace LocalWorkflow { /************************** * SWWorkerFactory **************************/ static const QString NAME_ATTR("result-name"); static const QString PATTERN_ATTR("pattern"); static const QString SCORE_ATTR("min-score"); static const QString MATRIX_ATTR("matrix"); static const QString AMINO_ATTR("amino"); static const QString ALGO_ATTR("algorithm"); static const QString FILTER_ATTR("filter-strategy"); static const QString GAPOPEN_ATTR("gap-open-score"); static const QString GAPEXT_ATTR("gap-ext-score"); const QString SWWorkerFactory::ACTOR_ID("ssearch"); static const QString PATTERN_DELIMITER(";"); void SWAlgoEditor::populate() { QStringList algoLst = AppContext::getSmithWatermanTaskFactoryRegistry()->getListFactoryNames(); if (algoLst.isEmpty()) { return; } foreach(const QString& n, algoLst) { items.insert(n,n); } QList lst = proto->getAttributes(); foreach(Attribute* a, lst) { if (a->getId() == ALGO_ATTR) { a->setAttributeValue(algoLst.first()); break; } } } void SWWorkerFactory::init() { QList p; { Descriptor ind(BasePorts::IN_SEQ_PORT_ID(), SWWorker::tr("Input Data"), SWWorker::tr("An input sequence to search in.")); Descriptor oud(BasePorts::OUT_ANNOTATIONS_PORT_ID(), SWWorker::tr("Pattern Annotations"), SWWorker::tr("The regions found.")); QMap inM; inM[BaseSlots::DNA_SEQUENCE_SLOT()] = BaseTypes::DNA_SEQUENCE_TYPE(); p << new PortDescriptor(ind, DataTypePtr(new MapDataType("sw.sequence", inM)), true); QMap outM; outM[BaseSlots::ANNOTATION_TABLE_SLOT()] = BaseTypes::ANNOTATION_TABLE_TYPE(); p << new PortDescriptor(oud, DataTypePtr(new MapDataType("sw.annotations", outM)), false, true); } QStringList filterLst = AppContext::getSWResultFilterRegistry()->getFiltersIds(); QList a; { Descriptor nd(NAME_ATTR, SWWorker::tr("Annotate as"), SWWorker::tr("Name of the result annotations.")); Descriptor pd(PATTERN_ATTR, SWWorker::tr("Pattern(s)"), SWWorker::tr("Semicolon-separated list of patterns to search for. You can choose file with sequences for patterns or enter them manually")); Descriptor scd(SCORE_ATTR, SWWorker::tr("Min Score"), SWWorker::tr("Minimal percent similarity between a sequence and a pattern.")); Descriptor ald(ALGO_ATTR, SWWorker::tr("Algorithm"), SWWorker::tr("Version of the Smith-Waterman algorithm. You can use the optimized" " versions of the algorithm (SSE, CUDA and OpenCL) if your hardware supports" " these capabilities.")); Descriptor amd(AMINO_ATTR, SWWorker::tr("Search in Translation"), SWWorker::tr("Translates a supplied nucleotide sequence to protein" " and searches in the translated sequence.")); Descriptor mxd(MATRIX_ATTR, SWWorker::tr("Substitution Matrix"), SWWorker::tr("Describes the rate at which one character in a sequence changes" " to other character states over time.")); Descriptor frd(FILTER_ATTR, SWWorker::tr("Filter Results"), SWWorker::tr("Specifies either to filter the intersected results or to return all" " the results.")); Descriptor god(GAPOPEN_ATTR, SWWorker::tr("Gap Open Score"), SWWorker::tr("Penalty for opening a gap.")); Descriptor ged(GAPEXT_ATTR, SWWorker::tr("Gap Extension Score"), SWWorker::tr("Penalty for extending a gap.")); a << new Attribute(nd, BaseTypes::STRING_TYPE(), true, "misc_feature"); a << new Attribute(pd, BaseTypes::STRING_TYPE(), true); a << new Attribute(mxd, BaseTypes::STRING_TYPE(), true, QString("Auto")); a << new Attribute(ald, BaseTypes::STRING_TYPE(), true); a << new Attribute(frd, BaseTypes::STRING_TYPE(), false, filterLst.isEmpty() ? QString() : filterLst.first()); a << new Attribute(scd, BaseTypes::NUM_TYPE(), false, 90); a << new Attribute(BaseAttributes::STRAND_ATTRIBUTE(), BaseTypes::STRING_TYPE(), false, BaseAttributes::STRAND_BOTH()); a << new Attribute(amd, BaseTypes::BOOL_TYPE(), false, false); a << new Attribute(god, BaseTypes::NUM_TYPE(), false, -10.); a << new Attribute(ged, BaseTypes::NUM_TYPE(), false, -1.); } Descriptor desc(ACTOR_ID, SWWorker::tr("Smith-Waterman Search"), SWWorker::tr("Searches regions in a sequence similar to a pattern" " sequence. Outputs a set of annotations.

Under the hood is" " the well-known Smith-Waterman algorithm for performing local" " sequence alignment.")); ActorPrototype* proto = new IntegralBusActorPrototype(desc, p, a); // delegates QMap delegates; { QVariantMap m; m["minimum"] = 1; m["maximum"] = 100; m["suffix"] = "%"; delegates[SCORE_ATTR] = new SpinBoxDelegate(m); } { QVariantMap m; m["maximum"] = -0.; m["minimum"]=-10000000.; delegates[GAPOPEN_ATTR] = new DoubleSpinBoxDelegate(m); m["maximum"] = -1.; delegates[GAPEXT_ATTR] = new DoubleSpinBoxDelegate(m); } delegates[BaseAttributes::STRAND_ATTRIBUTE().getId()] = new ComboBoxDelegate(BaseAttributes::STRAND_ATTRIBUTE_VALUES_MAP()); { QVariantMap m; foreach(const QString& n, filterLst) { m.insert(n,n); } delegates[FILTER_ATTR] = new ComboBoxDelegate(m); } { QVariantMap m; m.insert(SWWorker::tr("Auto"), QString("Auto")); QStringList lst = AppContext::getSubstMatrixRegistry()->getMatrixNames(); foreach(const QString& n, lst) { m.insert(n,n); } delegates[MATRIX_ATTR] = new ComboBoxDelegate(m); } delegates[PATTERN_ATTR] = new URLDelegate(DialogUtils::prepareDocumentsFileFilter(true), QString()); SWAlgoEditor* aled = new SWAlgoEditor(proto); aled->connect(AppContext::getPluginSupport(), SIGNAL(si_allStartUpPluginsLoaded()), SLOT(populate())); delegates[ALGO_ATTR] = aled; proto->setEditor(new DelegateEditor(delegates)); proto->setIconPath(":core/images/sw.png"); proto->setPrompter(new SWPrompter()); WorkflowEnv::getProtoRegistry()->registerProto(BaseActorCategories::CATEGORY_BASIC(), proto); DomainFactory* localDomain = WorkflowEnv::getDomainRegistry()->getById(LocalDomainFactory::ID); localDomain->registerEntry(new SWWorkerFactory()); } static StrandOption getStrand(const QString & s) { QString str = s.toLower(); if(BaseAttributes::STRAND_BOTH().startsWith(str)) { return StrandOption_Both; } else if(BaseAttributes::STRAND_DIRECT().startsWith(str)) { return StrandOption_DirectOnly; } else if(BaseAttributes::STRAND_COMPLEMENTARY().startsWith(str)) { return StrandOption_ComplementOnly; } else { bool ok = false; int num = str.toInt(&ok); if(ok && num >= 0) { return StrandOption(num); } else { return StrandOption_Both; } } } /************************** * SWPrompter **************************/ QString SWPrompter::composeRichDoc() { IntegralBusPort* input = qobject_cast(target->getPort(BasePorts::IN_SEQ_PORT_ID())); Actor* seqProducer = input->getProducer(BaseSlots::DNA_SEQUENCE_SLOT().getId()); QString unsetStr = "" + tr("unset") + ""; QString seqName; seqProducer ? (seqName = seqProducer->getLabel()) : (seqName = unsetStr); SmithWatermanSettings cfg; cfg.strand = getStrand(getParameter(BaseAttributes::STRAND_ATTRIBUTE().getId()).value()); cfg.percentOfScore = getParameter(SCORE_ATTR).toInt(); QString pattern = getRequiredParam(PATTERN_ATTR); QString strandName; switch (cfg.strand) { case StrandOption_Both: strandName = SWWorker::tr("both strands"); break; case StrandOption_DirectOnly: strandName = SWWorker::tr("direct strand"); break; case StrandOption_ComplementOnly: strandName = SWWorker::tr("complementary strand"); break; default: assert(false); } QString searchInTranslationSelected = ""; if (getParameter(AMINO_ATTR).toBool()) { searchInTranslationSelected = "" + tr("translated") + "" + " "; } QString resultName = getRequiredParam(NAME_ATTR); QString doc = tr("Searches regions in each sequence from %1" " similar to %2 pattern(s).
Percent similarity between" " a sequence and a pattern is %3.
Seaches in %4" " of a %5 sequence.
Outputs the regions found annotated as %6.") .arg(seqName) .arg(getHyperlink(PATTERN_ATTR, pattern)) .arg(getHyperlink(SCORE_ATTR, QString::number(cfg.percentOfScore) + "%")) .arg(getHyperlink(BaseAttributes::STRAND_ATTRIBUTE().getId(), strandName)) .arg(getHyperlink(AMINO_ATTR, searchInTranslationSelected)) .arg(getHyperlink(NAME_ATTR, resultName)); return doc; } /************************** * SWWorker **************************/ SWWorker::SWWorker(Actor* a) : BaseWorker(a), input(NULL), output(NULL) { } void SWWorker::init() { input = ports.value(BasePorts::IN_SEQ_PORT_ID()); output = ports.value(BasePorts::OUT_ANNOTATIONS_PORT_ID()); } bool SWWorker::isReady() { return (input && input->hasMessage()); } QString SWWorker::readPatternsFromFile(const QString url) { QFileInfo fi(url); QString pattern; if (!fi.exists()) { return ""; } QList fs = DocumentUtils::detectFormat(url); DocumentFormat* format = NULL; foreach( const FormatDetectionResult& i, fs ) { const QSet& types = i.format->getSupportedObjectTypes(); if (types.contains(GObjectTypes::SEQUENCE) || types.contains(GObjectTypes::MULTIPLE_ALIGNMENT)) { format = i.format; break; } } if (format == NULL) { return ""; } ioLog.info(tr("Reading sequences from %1 [%2]").arg(url).arg(format->getFormatName())); IOAdapterFactory* iof = AppContext::getIOAdapterRegistry()->getIOAdapterFactoryById(BaseIOAdapters::url2io(url)); IOAdapter *io = iof->createIOAdapter(); if (!io->open(url, IOAdapterMode_Read)) { return ""; } QVariantMap hints; TaskStateInfo stateInfo; Document *doc = format->loadDocument(io, stateInfo, hints); // assert(isCanceled() || doc!=NULL || hasError()); assert(doc == NULL || doc->isLoaded()); if (doc!=NULL && doc->isLoaded()) { const QSet& types = format->getSupportedObjectTypes(); if (types.contains(GObjectTypes::SEQUENCE)) { QList seqObjs = doc->findGObjectByType(GObjectTypes::SEQUENCE); QList annObjs = doc->findGObjectByType(GObjectTypes::ANNOTATION_TABLE); foreach(GObject* go, seqObjs) { assert(go != NULL); const DNASequence& dna = ((DNASequenceObject*)go)->getDNASequence(); pattern += QString(dna.constData()) + ";"; patternNames[dna.constData()] = dna.getName(); if(!dna.info[DNAInfo::FASTA_HDR].toString().isEmpty()) { fastaHeaders[dna.constData()] = dna.info[DNAInfo::FASTA_HDR].toString(); } } } else { foreach(GObject* go, doc->findGObjectByType(GObjectTypes::MULTIPLE_ALIGNMENT)) { foreach(const DNASequence& s, MSAUtils::ma2seq(((MAlignmentObject*)go)->getMAlignment(), false)) { pattern += QString(s.constData()) + ";"; } } } } if (doc!=NULL && doc->isLoaded()) { doc->unload(); } return pattern; } Task* SWWorker::tick() { Message inputMessage = getMessageAndSetupScriptValues(input); SmithWatermanSettings cfg; // sequence DNASequence seq = inputMessage.getData().toMap().value(BaseSlots::DNA_SEQUENCE_SLOT().getId()).value(); if(seq.isNull()) { return new FailTask(tr("Null sequence supplied to Smith-Waterman: %1").arg(seq.getName())); } // scoring matrix QString mtrx = actor->getParameter(MATRIX_ATTR)->getAttributeValue(); if(mtrx.isEmpty()){ mtrx = "Auto"; } cfg.pSm = AppContext::getSubstMatrixRegistry()->getMatrix(mtrx); if(cfg.pSm.getName().isEmpty() && mtrx.toLower() != "auto") { algoLog.details(tr("Invalid value: weight matrix with given name not exists")); return new FailTask(tr("Invalid value: weight matrix with given name not exists")); } if (cfg.pSm.isEmpty()) { QString matrixName; QStringList lst = AppContext::getSubstMatrixRegistry()->selectMatrixNamesByAlphabet(seq.alphabet); if (!lst.isEmpty()) { matrixName = lst.first(); cfg.pSm = AppContext::getSubstMatrixRegistry()->getMatrix(matrixName); } if(cfg.pSm.isEmpty()) { return new FailTask(tr("Can't find weight matrix name: '%1'!").arg(matrixName.isEmpty() ? tr("") : matrixName)); } } if(mtrx.toLower() != "auto") { QByteArray alphChars = seq.alphabet->getAlphabetChars(); if(cfg.pSm.getAlphabet()->containsAll(alphChars.constData(), alphChars.length()) ) { return new FailTask(tr("Wrong matrix selected. Alphabets do not match")); } } // pattern QString ptrnStr = actor->getParameter(PATTERN_ATTR)->getAttributeValue(); if(QFile::exists(ptrnStr)) { ptrnStr = readPatternsFromFile(ptrnStr); } ptrnStr.remove(" "); ptrnStr = ptrnStr.toUpper(); QByteArray ptrnBytes = QString(ptrnStr).remove(PATTERN_DELIMITER).toAscii(); if(!cfg.pSm.getAlphabet()->containsAll(ptrnBytes.constData(), ptrnBytes.length())) { algoLog.error(tr("Incorrect value: pattern alphabet doesn't match sequence alphabet ")); return new FailTask(tr("Pattern symbols not matching to alphabet")); } cfg.sqnc = QByteArray(seq.constData(), seq.length()); cfg.globalRegion.length = seq.length(); // score and gap model cfg.percentOfScore = actor->getParameter(SCORE_ATTR)->getAttributeValue(); if(cfg.percentOfScore < 0 || cfg.percentOfScore > 100){ algoLog.error(tr("Incorrect value: score value must lay between 0 and 100")); return new FailTask(tr("Incorrect value: score value must lay between 0 and 100")); } cfg.gapModel.scoreGapExtd = actor->getParameter(GAPEXT_ATTR)->getAttributeValue(); cfg.gapModel.scoreGapOpen = actor->getParameter(GAPOPEN_ATTR)->getAttributeValue(); // filter QString filter = actor->getParameter(FILTER_ATTR)->getAttributeValue(); cfg.resultFilter = AppContext::getSWResultFilterRegistry()->getFilter(filter); if(cfg.resultFilter == NULL){ algoLog.error(tr("Incorrect value: filter name incorrect, default value used")); //details level won't work cfg.resultFilter = AppContext::getSWResultFilterRegistry()->getFilter("none"); } // annotation name QString resultName = actor->getParameter(NAME_ATTR)->getAttributeValue(); if(resultName.isEmpty()){ algoLog.error(tr("Incorrect value: result name is empty, default value used")); //details level won't work resultName = "misc_feature"; } // translations cfg.strand = getStrand(actor->getParameter(BaseAttributes::STRAND_ATTRIBUTE().getId())->getAttributeValue()); if (cfg.strand != StrandOption_DirectOnly/* && seq.alphabet->getType() == DNAAlphabet_NUCL*/) { QList compTTs = AppContext::getDNATranslationRegistry()-> lookupTranslation(seq.alphabet, DNATranslationType_NUCL_2_COMPLNUCL); if (!compTTs.isEmpty()) { cfg.complTT = compTTs.first(); } else { algoLog.error(tr("Could not find complement translation for %1, searching only direct strand").arg(seq.getName())); cfg.strand = StrandOption_DirectOnly; } } if (actor->getParameter(AMINO_ATTR)->getAttributeValue()) { DNATranslationType tt = seq.alphabet->getType() == DNAAlphabet_NUCL ? DNATranslationType_NUCL_2_AMINO : DNATranslationType_RAW_2_AMINO; QList TTs = AppContext::getDNATranslationRegistry()->lookupTranslation(seq.alphabet, tt); if (!TTs.isEmpty()) { cfg.aminoTT = TTs.first(); //FIXME let user choose or use hints ? } } // algorithm QString algName = actor->getParameter(ALGO_ATTR)->getAttributeValue(); SmithWatermanTaskFactory* algo = AppContext::getSmithWatermanTaskFactoryRegistry()->getFactory(algName); if (!algo) { return new FailTask(tr("SmithWaterman algorithm not found: %1").arg(algName)); } // for each pattern run smith-waterman QStringList ptrnStrList = ptrnStr.split(PATTERN_DELIMITER, QString::SkipEmptyParts); if(ptrnStrList.isEmpty()) { algoLog.error(tr("Incorrect value: search pattern, pattern is empty")); return new FailTask(tr("Incorrect value: search pattern, pattern is empty")); } QList subs; foreach(const QString & p, ptrnStrList) { assert(!p.isEmpty()); SmithWatermanSettings config(cfg); config.ptrn = p.toAscii(); SmithWatermanReportCallbackImpl* rcb = new SmithWatermanReportCallbackImpl( NULL, resultName, QString()); config.resultCallback = rcb; config.resultListener = new SmithWatermanResultListener(); //FIXME: where to delete? Task * swTask = algo->getTaskInstance(config, tr("smith_waterman_task")); rcb->setParent(swTask); // swTask will delete rcb callbacks.insert(swTask, rcb); patterns.insert(swTask, config.ptrn); subs << swTask; } assert(!subs.isEmpty()); MultiTask * multiSw = new MultiTask(tr("Smith waterman subtasks"), subs); connect(new TaskSignalMapper(multiSw), SIGNAL(si_taskFinished(Task*)), SLOT(sl_taskFinished(Task*))); return multiSw; } void SWWorker::sl_taskFinished(Task* t) { QList annData; MultiTask * multiSw = qobject_cast(t); assert(multiSw != NULL); QList subs = multiSw->getTasks(); assert(!subs.isEmpty()); QStringList ptrns; foreach(Task * sub, subs) { SmithWatermanReportCallbackImpl* rcb = callbacks.take(sub); assert(rcb != NULL); if(rcb) { foreach(SharedAnnotationData a, rcb->getAnotations()) { QString pattern = patterns.value(sub); if(!patternNames[pattern].isEmpty()) { a->qualifiers.push_back(U2Qualifier("pattern_name", patternNames[pattern])); } if(!fastaHeaders[pattern].isEmpty()) { a->qualifiers.push_back(U2Qualifier("fasta_header", fastaHeaders[pattern])); } annData << a; } //annData << rcb->getAnotations(); } ptrns << patterns.value(sub); } assert(output != NULL); if(output) { QVariant v = qVariantFromValue >(annData); output->put(Message(BaseTypes::ANNOTATION_TABLE_TYPE(), v)); if (input->isEnded()) { output->setEnded(); } algoLog.info(tr("Found %1 matches of pattern '%2'").arg(annData.size()).arg(ptrns.join(PATTERN_DELIMITER))); } } bool SWWorker::isDone() { return !input || input->isEnded(); } void SWWorker::cleanup() { } } //namespace LocalWorkflow } //namespace U2 ugene-1.9.8/src/plugins/smith_waterman/src/SmithWatermanAlgorithmSSE2.cpp0000644000175000017500000004167211651544324025205 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifdef SW2_BUILD_WITH_SSE2 #include "SmithWatermanAlgorithmSSE2.h" #include #include using namespace std; namespace U2 { // static bool PRINT_DIRECTIONS = false; // static bool PRINT_SCORE = false; // static bool PRINT_JUST_SCORE = false; // static bool PRINT_E = false; // static bool PRINT_F = true; // static bool PRINT_F_SHIFT = false; // static bool PRINT_H = false; void SmithWatermanAlgorithmSSE2::launch(const SMatrix& _substitutionMatrix, QByteArray const & _patternSeq, QByteArray const & _searchSeq, int _gapOpen, int _gapExtension, int _minScore) { setValues(_substitutionMatrix, _patternSeq, _searchSeq, _gapOpen, _gapExtension, _minScore); int maxScor = 0; if (isValidParams() && calculateMatrixLength()) { maxScor = calculateMatrixSSE2(patternSeq.length(),(unsigned char *)searchSeq.data(), searchSeq.length(), (-1)*(gapOpen + gapExtension), (-1)*(gapExtension)); if (minScore <= maxScor) { calculateMatrix(); } } else { //No result // See validationParams(); //Perhaps reason: minScore > maxScore // or gap_open >= 0 or gap_extension >= 0 } } //Calculating dynamic matrix //and save results void SmithWatermanAlgorithmSSE2::calculateMatrix() { char ch; //ScoreType substValue = 0; //warning: unused variable substValue ScoreType max = 0; int matrixLengthDivisibleByN = matrixLength; int patternLengthDivisibleByN = patternSeq.length() + 1; while (matrixLengthDivisibleByN % nElementsInVec != 0) matrixLengthDivisibleByN++; while (patternLengthDivisibleByN % nElementsInVec != 0) patternLengthDivisibleByN++; ScoreType * temp = (ScoreType*)_mm_malloc(nElementsInVec*sizeof(ScoreType),16); for (int pp = 0; pp < nElementsInVec; pp++) temp[pp] = 0; __m128i zero = _mm_set1_epi32(0); __m128i tmp = _mm_set1_epi32(0); //Load 0 all elements of vector zero zero = _mm_insert_epi16 (zero, 0, 0); zero = _mm_shufflelo_epi16 (zero, 0); zero = _mm_shuffle_epi32 (zero, 0); __m128i substValVec = zero; // int f1, f2, e1, e2; __m128i f1 = zero, f2 = zero, f3 = zero;//, e1 = zero, e2 = zero, e3 = zero; //warning: unused variables e1, e2, e3 __m128i gapOpenVec = _mm_set1_epi32(0); __m128i gapExtensionVec = _mm_set1_epi32(0); __m128i maxVec = _mm_set1_epi32(0); // Load gap opening penalty to all elements of a vector gapOpenVec = _mm_insert_epi16 (gapOpenVec, gapOpen, 0); gapOpenVec = _mm_shufflelo_epi16 (gapOpenVec, 0); gapOpenVec = _mm_shuffle_epi32 (gapOpenVec, 0); // Load gap extension penalty to all elements of a vector gapExtensionVec = _mm_insert_epi16 (gapExtensionVec, gapExtension, 0); gapExtensionVec = _mm_shufflelo_epi16 (gapExtensionVec, 0); gapExtensionVec = _mm_shuffle_epi32 (gapExtensionVec, 0); ScoreType * EArray = (ScoreType*)_mm_malloc((nElementsInVec + patternLengthDivisibleByN)*sizeof(ScoreType),16); ScoreType * FArray = (ScoreType*)_mm_malloc((nElementsInVec + patternLengthDivisibleByN)*sizeof(ScoreType),16); ScoreType * maxArray = (ScoreType*)_mm_malloc((nElementsInVec + patternLengthDivisibleByN)*sizeof(ScoreType),16); for (int tt = 0; tt < patternLengthDivisibleByN; tt++) { FArray[tt] = 0; EArray[tt] = 0; } ScoreType ** matrix = new ScoreType*[matrixLengthDivisibleByN]; matrix[0] = (ScoreType*)_mm_malloc(matrixLengthDivisibleByN*patternLengthDivisibleByN*sizeof(ScoreType), 16); for (int i = 1; i < matrixLengthDivisibleByN; i++) { matrix[i] = matrix[i-1] + patternLengthDivisibleByN; } __m128i * pvScore; int segSize = (patternSeq.length() + nElementsInVec - 1) / nElementsInVec; //count iter int ALPHA_SIZE = substitutionMatrix.getAlphabet()->getNumAlphabetChars(); __m128i* pvQueryProf = (__m128i*)_mm_malloc ('Z'*ALPHA_SIZE*segSize*sizeof(__m128i), 16); ScoreType * queryProfile = (ScoreType *) pvQueryProf; QByteArray alphaChars = substitutionMatrix.getAlphabet()->getAlphabetChars(); for (int i = 0; i = patternSeq.length()) queryProfile[posI + k] = 0; else { queryProfile[posI + k] = (ScoreType)substitutionMatrix.getScore(patternSeq.at(k), ch); } } } } ////////////////////////////////////////////////////////////////////////// for (int tt = 0; tt < matrixLengthDivisibleByN; tt++) for (int ww = 0; ww < patternLengthDivisibleByN; ww++) matrix[tt][ww] = 0; //initialization dynamic matrices QVector rowChars; QVector rowInts; for (int tt = 0; tt < patternLengthDivisibleByN + 1; tt++) { rowChars.append(STOP); rowInts.append(0); } for (int tt = 0; tt < matrixLengthDivisibleByN; tt++) { directionMatrix.append(rowChars); } ScoreType ee1 = 0, ee2 = 0; PairAlignSequences p; QByteArray pairAlign; U2Region sReg; U2Region pReg; QVector > directionSearchSeq; directionSearchSeq.push_back(rowInts); directionSearchSeq.push_back(rowInts); int even = 0; int odd = 0; //Sart dynamic programming for (int i = 1; i < searchSeq.length() + 1; i++) { ch = searchSeq.at(i - 1); pvScore = pvQueryProf + ch * segSize; even = i % 2; odd = (i + 1) % 2; directionSearchSeq[odd][0] = i - 1; p.score = 0; for (int j = 0; j < patternSeq.length(); j += nElementsInVec) { //TODO: use __m128i*, not array f1 = _mm_load_si128((__m128i*) ((ScoreType *) &FArray[j])); f1 = _mm_add_epi16(f1, gapExtensionVec); tmp = _mm_load_si128((__m128i*) ((ScoreType *) &matrix[getRow(i-1)][j])); f2 = _mm_add_epi16(tmp, gapOpenVec); f3 = _mm_max_epi16(f1, f2); _mm_store_si128((__m128i*) &FArray[j], f3); substValVec = _mm_load_si128( pvScore++ ); tmp = _mm_slli_si128(tmp, 2); tmp = _mm_insert_epi16 (tmp, matrix[getRow(i-1)][j-1], 0); tmp = _mm_add_epi16(tmp, substValVec); _mm_store_si128((__m128i*) &temp[0], tmp); maxVec = _mm_max_epi16(tmp, f3); _mm_store_si128((__m128i*) &maxArray[0], maxVec); //Use non vector operations for calculate maxScore and backtrace for (int pp = j; pp < j + nElementsInVec && pp < patternSeq.length(); pp++) { int eIndex = pp + 1; ee1 = EArray[eIndex - 1] + gapExtension; ee2 = matrix[getRow(i)][pp - 1] + gapOpen; if (ee1 > ee2) EArray[eIndex] = ee1; else EArray[eIndex] = ee2; if (maxArray[pp - j] > EArray[eIndex]) max = maxArray[pp - j]; else max = EArray[eIndex]; if (max < 0) max = 0; matrix[getRow(i)][pp] = max; int col = pp + 1; if (max == 0) { directionSearchSeq[even][col] = i; } else if (max == EArray[eIndex]) { directionSearchSeq[even][col] = directionSearchSeq[even][col - 1]; } else if (max == FArray[pp]) { directionSearchSeq[even][col] = directionSearchSeq[odd][col]; } else if (max == temp[pp - j]) { directionSearchSeq[even][col] = directionSearchSeq[odd][col - 1]; } if (max >= p.score) { p.score = max; p.intervalSeq1.startPos = directionSearchSeq[even][col]; p.intervalSeq1.length = i - p.intervalSeq1.startPos; } } } if (p.score >= minScore) { pairAlignmentStrings.append(p); } //Print matrix // for(int k = 0; k < patternSeq.length() + 1 ; k++) cout <getNumAlphabetChars(); __m128i* pvQueryProf = (__m128i*)_mm_malloc ('Z'*ALPHA_SIZE*iter*sizeof(__m128i), 16); int weight = 0; unsigned short * queryProfile = (unsigned short *) pvQueryProf; int segSize = (queryLength + 7) / 8; //iter int nCount = segSize * 8; char curChar = ' '; QByteArray alphaChars = substitutionMatrix.getAlphabet()->getAlphabetChars(); for (int i = 0; i < ALPHA_SIZE; i++) { curChar = alphaChars.at(i); int h = 0; for (int j = 0; j < segSize; j++) { unsigned int k = j; for (unsigned int kk = 0; kk < 8; kk++) { if (k >= queryLength) { weight = 0; } else { weight = substitutionMatrix.getScore(curChar, patternSeq.at(k)); } queryProfile[curChar * nCount + h] = (unsigned short) weight; k += segSize; h++; } } } __m128i *pvHLoad = (__m128i*)_mm_malloc(iter*sizeof(__m128i), 16); __m128i *pvHStore = (__m128i*)_mm_malloc(iter*sizeof(__m128i), 16); __m128i *pvE = (__m128i*)_mm_malloc(iter*sizeof(__m128i), 16); unsigned i = 0, j = 0; int score = 0; int cmp = 0; unsigned short gapOpenFarrar = gapOpenOrig - gapExtend; __m128i *pv = 0; __m128i vE = _mm_set1_epi32(0), vF = _mm_set1_epi32(0), vH = _mm_set1_epi32(0); __m128i vMaxScore = _mm_set1_epi32(0); __m128i vGapOpen = _mm_set1_epi32(0); __m128i vGapExtend = _mm_set1_epi32(0); __m128i vMin = _mm_set1_epi32(0); __m128i vMinimums = _mm_set1_epi32(0); __m128i vTemp = _mm_set1_epi32(0); __m128i *pvScore = 0; /* Load gap opening penalty to all elements of a constant */ vGapOpen = _mm_insert_epi16 (vGapOpen, gapOpenFarrar, 0); vGapOpen = _mm_shufflelo_epi16 (vGapOpen, 0); vGapOpen = _mm_shuffle_epi32 (vGapOpen, 0); /* Load gap extension penalty to all elements of a constant */ vGapExtend = _mm_insert_epi16 (vGapExtend, gapExtend, 0); vGapExtend = _mm_shufflelo_epi16 (vGapExtend, 0); vGapExtend = _mm_shuffle_epi32 (vGapExtend, 0); /* load vMaxScore with the zeros. since we are using signed */ /* math, we will bias the maxscore to -32768 so we have the */ /* full range of the short. */ vMaxScore = _mm_cmpeq_epi16 (vMaxScore, vMaxScore); vMaxScore = _mm_slli_epi16 (vMaxScore, 15); vMinimums = _mm_shuffle_epi32 (vMaxScore, 0); Q_UNUSED(vMinimums); vMin = _mm_shuffle_epi32 (vMaxScore, 0); vMin = _mm_srli_si128 (vMin, 14); /* Zero out the storage vector */ for (i = 0; i < iter; ++i) { _mm_store_si128 (pvE + i, vMaxScore); _mm_store_si128 (pvHStore + i, vMaxScore); } PairAlignSequences p; U2Region sReg; for (i = 0; i < dbLength; ++i) { /* fetch first data asap. */ pvScore = pvQueryProf + dbSeq[i] * iter; /* zero out F. */ vF = _mm_cmpeq_epi16 (vF, vF); vF = _mm_slli_epi16 (vF, 15); /* load the next h value */ vH = _mm_load_si128 (pvHStore + iter - 1); vH = _mm_slli_si128 (vH, 2); vH = _mm_or_si128 (vH, vMin); pv = pvHLoad; pvHLoad = pvHStore; pvHStore = pv; for (j = 0; j < iter; ++j) { /* load values of vF and vH from previous row (one unit up) */ vE = _mm_load_si128 (pvE + j); /* add score to vH */ vH = _mm_adds_epi16 (vH, *pvScore++); /* Update highest score encountered this far */ vMaxScore = _mm_max_epi16 (vMaxScore, vH); /* get max from vH, vE and vF */ vH = _mm_max_epi16 (vH, vE); vH = _mm_max_epi16 (vH, vF); /* save vH values */ _mm_store_si128 (pvHStore + j, vH); /* update vE value */ vH = _mm_subs_epi16 (vH, vGapOpen); vE = _mm_subs_epi16 (vE, vGapExtend); vE = _mm_max_epi16 (vE, vH); /* update vF value */ vF = _mm_subs_epi16 (vF, vGapExtend); vF = _mm_max_epi16 (vF, vH); /* save vE values */ _mm_store_si128 (pvE + j, vE); /* load the next h value */ vH = _mm_load_si128 (pvHLoad + j); } /* reset pointers to the start of the saved data */ j = 0; vH = _mm_load_si128 (pvHStore + j); /* the computed vF value is for the given column. since */ /* we are at the end, we need to shift the vF value over */ /* to the next column. */ vF = _mm_slli_si128 (vF, 2); vF = _mm_or_si128 (vF, vMin); vTemp = _mm_subs_epi16 (vH, vGapOpen); vTemp = _mm_cmpgt_epi16 (vF, vTemp); cmp = _mm_movemask_epi8 (vTemp); while (cmp != 0x0000) //for (unsigned cnt=0; cnt= iter) { j = 0; vF = _mm_slli_si128 (vF, 2); vF = _mm_or_si128 (vF, vMin); } vH = _mm_load_si128 (pvHStore + j); vTemp = _mm_subs_epi16 (vH, vGapOpen); vTemp = _mm_cmpgt_epi16 (vF, vTemp); cmp = _mm_movemask_epi8 (vTemp); } } /* find largest score in the vMaxScore vector */ vTemp = _mm_srli_si128 (vMaxScore, 8); vMaxScore = _mm_max_epi16 (vMaxScore, vTemp); vTemp = _mm_srli_si128 (vMaxScore, 4); vMaxScore = _mm_max_epi16 (vMaxScore, vTemp); vTemp = _mm_srli_si128 (vMaxScore, 2); vMaxScore = _mm_max_epi16 (vMaxScore, vTemp); /* store in temporary variable */ score = (short) _mm_extract_epi16 (vMaxScore, 0); _mm_free(pvHLoad); _mm_free(pvHStore); _mm_free(pvE); _mm_free(pvQueryProf); /* return largest score */ return score + 32768; } inline void SmithWatermanAlgorithmSSE2::printVector(__m128i &toprint, int add) { ScoreType * tmpArray = (ScoreType*)_mm_malloc(nElementsInVec*sizeof(ScoreType),16); _mm_store_si128((__m128i*) &tmpArray[0], toprint); cout <<"printVector" < * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifdef SW2_BUILD_WITH_CUDA #include #include #include #include "sw_cuda_cpp.h" #include typedef int ScoreType; extern QList calculateOnGPU(const char * seqLib, int seqLibLength, ScoreType* queryProfile, ScoreType qProfLen, int queryLength, ScoreType gapOpen, ScoreType gapExtension, ScoreType maxScore); static U2::Logger log("Smith Waterman CUDA"); QList sw_cuda_cpp::launch(const char * seqLib, int seqLibLength, ScoreType* queryProfile, ScoreType qProfLen, int queryLength, ScoreType gapOpen, ScoreType gapExtension, ScoreType maxScore) { return calculateOnGPU(seqLib, seqLibLength, queryProfile, qProfLen, queryLength, gapOpen, gapExtension, maxScore); } //TODO: calculate maximum alignment length int calcOverlap(int queryLength) { return queryLength * 3; } //number of parts of the sequence which we divide int calcPartsNumber(int seqLibLength, int overlapLength) { int partsNumber = (seqLibLength + overlapLength - 1) / overlapLength; if (partsNumber > sw_cuda_cpp::MAX_BLOCKS_NUMBER) { partsNumber = sw_cuda_cpp::MAX_BLOCKS_NUMBER; } return partsNumber; } //size of sequence's part int calcPartSeqSize(int seqLibLength, int overlapLength, int partsNumber) { return (seqLibLength + (partsNumber - 1) * (overlapLength + 1)) / partsNumber; } //size of vector that contain all results int calcSizeRow(int seqLibLength, int overlapLength, int partsNumber, int partSeqSize) { return (partSeqSize + 1) * partsNumber; } quint64 sw_cuda_cpp::estimateNeededGpuMemory( int seqLibLength, ScoreType qProfLen, int queryLength ) { int sizeP = qProfLen * sizeof(ScoreType); int sizeL = (seqLibLength) * sizeof(char); const int overlapLength = calcOverlap(queryLength); int partsNumber = calcPartsNumber(seqLibLength, overlapLength); int partSeqSize = calcPartSeqSize(seqLibLength, overlapLength, partsNumber); int sizeRow = calcSizeRow(seqLibLength, overlapLength, partsNumber, partSeqSize); int sizeN = 7 * sizeRow * sizeof(ScoreType); quint64 memToAlloc = sizeL + sizeP + sizeN; //see cudaMallocs in sw_cuda.cu for details return memToAlloc * 1.2; //just for safety } //IMPORTANT: these settings depend on the video card //TODO: develop logic for calculation this settings const int sw_cuda_cpp::MAX_BLOCKS_NUMBER = 14; //we have 3 shared vector, this mean all shared memory = MAX_SHARED_VECTOR_LENGTH * 3 const int sw_cuda_cpp::MAX_SHARED_VECTOR_LENGTH = 128; //__global__ extern void calculateMatrix_wrap(int blockSize, int threadNum, const char * seqLib, ScoreType* queryProfile, ScoreType* g_HdataUp, ScoreType* g_HdataRec, ScoreType* g_HdataMax, ScoreType* g_FdataUp, ScoreType* g_directionsUp, ScoreType* g_directionsRec, ScoreType* g_directionsMax, int iteration); extern void setConstants(int partSeqSize, int partsNumber, int overlapLength, int seqLibLength, int queryLength, int gapOpen, int gapExtension, int maxScore, int queryPartLength); QList calculateOnGPU(const char * seqLib, int seqLibLength, ScoreType* queryProfile, ScoreType qProfLen, int queryLength, ScoreType gapOpen, ScoreType gapExtension, ScoreType maxScore) { //TODO: calculate maximum alignment length const int overlapLength = calcOverlap(queryLength); int partsNumber = calcPartsNumber(seqLibLength, overlapLength); int queryDevider = 1; if (queryLength > sw_cuda_cpp::MAX_SHARED_VECTOR_LENGTH) { queryDevider = (queryLength + sw_cuda_cpp::MAX_SHARED_VECTOR_LENGTH - 1) / sw_cuda_cpp::MAX_SHARED_VECTOR_LENGTH; } int partQuerySize = (queryLength + queryDevider - 1) / queryDevider; int partSeqSize = calcPartSeqSize(seqLibLength, overlapLength, partsNumber); int sizeRow = calcSizeRow(seqLibLength, overlapLength, partsNumber, partSeqSize); log.details(QString("partsNumber: %1 queryDevider: %2").arg(partsNumber).arg(queryDevider)); log.details(QString("seqLen: %1 partSeqSize: %2 overlapSize: %3").arg(seqLibLength).arg(partSeqSize).arg(overlapLength)); log.details(QString("queryLen %1 partQuerySize: %2").arg(queryLength).arg(partQuerySize)); //************************** declare some temp variables on host ScoreType* tempRow = new ScoreType[sizeRow]; ScoreType* zerroArr = new ScoreType[sizeRow]; for (int i = 0; i < sizeRow; i++) { zerroArr[i] = 0; } ScoreType* directionRow = new ScoreType[sizeRow]; //************************** sizes of arrays size_t sizeQ = sizeRow * sizeof(ScoreType); size_t sizeQQ = (sizeRow) * sizeof(ScoreType); size_t sizeP = qProfLen * sizeof(ScoreType); size_t sizeL = (seqLibLength) * sizeof(char); //************************** declare arrays on device char * g_seqLib; ScoreType* g_queryProfile; ScoreType* g_HdataMax; ScoreType* g_HdataUp; ScoreType* g_HdataRec; ScoreType* g_HdataTmp; ScoreType* g_FdataUp; ScoreType* g_directionsUp; ScoreType* g_directionsMax; ScoreType* g_directionsRec; //************************** allocate global memory on device cudaMalloc((void **)& g_seqLib, sizeL); cudaMalloc((void **)& g_queryProfile, sizeP); cudaMalloc((void **)& g_HdataMax, sizeQ); cudaMalloc((void **)& g_HdataUp, sizeQ); cudaMalloc((void **)& g_FdataUp, sizeQ); cudaMalloc((void **)& g_directionsUp, sizeQ); cudaMalloc((void **)& g_directionsMax, sizeQ); cudaMalloc((void **)& g_HdataRec, sizeQ); cudaMalloc((void **)& g_directionsRec, sizeQ); log.details(QString("GLOBAL MEMORY USED %1 KB").arg((sizeL + sizeP + sizeQ * 7) / 1024)); //************************** copy from host to device cudaMemcpy(g_seqLib, seqLib, sizeL, cudaMemcpyHostToDevice); cudaMemcpy(g_queryProfile, queryProfile, sizeP, cudaMemcpyHostToDevice); cudaMemcpy(g_HdataMax, zerroArr, sizeQ, cudaMemcpyHostToDevice); cudaMemcpy(g_HdataUp, zerroArr, sizeQ, cudaMemcpyHostToDevice); cudaMemcpy(g_FdataUp, zerroArr, sizeQ, cudaMemcpyHostToDevice); cudaMemcpy(g_directionsUp, zerroArr, sizeQ, cudaMemcpyHostToDevice); cudaMemcpy(g_directionsMax, zerroArr, sizeQ, cudaMemcpyHostToDevice); cudaMemcpy(g_directionsRec, zerroArr, sizeQ, cudaMemcpyHostToDevice); cudaMemcpy(g_HdataRec, zerroArr, sizeQ, cudaMemcpyHostToDevice); //************************** start calculation int BLOCK_SIZE = partsNumber; dim3 dimBlock(BLOCK_SIZE); dim3 dimGrid(partQuerySize); //move constants variables to constant cuda memory setConstants(partSeqSize, partsNumber, overlapLength, seqLibLength, queryLength, gapOpen, gapExtension, maxScore, partQuerySize); size_t sh_mem_size = sizeof(ScoreType) * (dimGrid.x + 1) * 3; log.details(QString("SHARED MEM SIZE USED: %1 B").arg(sh_mem_size)); // start main loop for (int i = 0; i < queryDevider; i++) { calculateMatrix_wrap( dimBlock.x, dimGrid.x, g_seqLib, g_queryProfile, g_HdataUp, g_HdataRec, g_HdataMax, g_FdataUp, g_directionsUp, g_directionsRec, g_directionsMax, i * partQuerySize); cudaError hasErrors = cudaThreadSynchronize(); if (hasErrors != 0) { log.trace(QString("CUDA ERROR HAPPEN, errorId: ") + QString::number(hasErrors)); } // cudaMemcpy(tempRow, g_HdataMax, sizeQQ, cudaMemcpyDeviceToHost); // QString str1 = ""; // int maximumScore = 0; // if (i == 0) { // for (int j = 0; j < 26; j++) { // if (j % (partSeqSize + 1) == 0 && j != 0) { // str1 += "|| "; // } // str1 += QString().sprintf("%2d", j) + " "; // } // log.details(str1); // log.details("**************"); // } //revert arrays g_HdataTmp = g_HdataRec; g_HdataRec = g_HdataUp; g_HdataUp = g_HdataTmp; g_HdataTmp = g_directionsRec; g_directionsRec = g_directionsUp; g_directionsUp = g_HdataTmp; } //Copy vectors on host and find actual results cudaMemcpy(tempRow, g_HdataMax, sizeQQ, cudaMemcpyDeviceToHost); cudaMemcpy(directionRow, g_directionsMax, sizeQQ, cudaMemcpyDeviceToHost); QList pas; resType res; for (int j = 0; j < (sizeRow); j++) { if (tempRow[j] >= maxScore) { res.reg.startPos = directionRow[j]; res.reg.length = j - res.reg.startPos + 1 - (j) / (partSeqSize + 1) * overlapLength - (j) / (partSeqSize + 1); res.score = tempRow[j]; // log.info(QString("score: %1, reg: %2..%3").arg(res.score).arg(res.reg.startPos).arg(res.reg.endPos())); pas.append(res); } } //deallocation memory cudaFree(g_seqLib); cudaFree(g_queryProfile); cudaFree(g_HdataMax); cudaFree(g_HdataUp); cudaFree(g_HdataRec); cudaFree(g_FdataUp); cudaFree(g_directionsUp); cudaFree(g_directionsMax); cudaFree(g_directionsRec); delete[] tempRow; delete[] directionRow; delete[] zerroArr; return pas; } #endif //SW2_BUILD_WITH_CUDA ugene-1.9.8/src/plugins/smith_waterman/src/SmithWatermanAlgorithm.cpp0000644000175000017500000003213311651544324024540 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "SmithWatermanAlgorithm.h" #include #include #include namespace U2 { const char SmithWatermanAlgorithm::STOP = 's'; const char SmithWatermanAlgorithm::UP = 'u'; const char SmithWatermanAlgorithm::LEFT = 'l'; const char SmithWatermanAlgorithm::DIAG = 'd'; SmithWatermanAlgorithm::SmithWatermanAlgorithm() { //default values gapOpen = 0; gapExtension = 0; minScore = 0; matrixLength = 0; storedResults = 0; } //notes: Gap < 0 bool SmithWatermanAlgorithm::calculateMatrixLength() { int maxScore = 0; int max; int substValue = 0; QByteArray alphaChars = substitutionMatrix.getAlphabet()->getAlphabetChars(); for (int i = 0; i < patternSeq.length(); i++) { max = 0; int nCharsInAlphabet = alphaChars.size(); for (int j = 0; j < nCharsInAlphabet; j++) { //TODO: cache pattern seq raw pointer and alphaChars row pointer out of the loop char c1 = patternSeq.at(i); char c2 = alphaChars.at(j); substValue = (int) substitutionMatrix.getScore(c1, c2); max = qMax(max, substValue); } maxScore += max; } if (minScore > maxScore) { //Error: perhaps minScore > maxScore algoLog.trace(QString("SW Error min score > max score. Min score: %1, max score: %2").arg(minScore).arg(maxScore)); return false; } int gap = gapOpen; if (gapOpen < gapExtension) gap = gapExtension; if (gap < 0) matrixLength = patternSeq.length() + (maxScore - minScore)/gap * (-1) + 1; if (searchSeq.length() + 1 < matrixLength) matrixLength = searchSeq.length() + 1; return true; } void SmithWatermanAlgorithm::setValues(const SMatrix& _substitutionMatrix, QByteArray const & _patternSeq, QByteArray const & _searchSeq, int _gapOpen, int _gapExtension, int _minScore) { substitutionMatrix = _substitutionMatrix; patternSeq = _patternSeq; searchSeq = _searchSeq; gapOpen = _gapOpen; gapExtension = _gapExtension; minScore = _minScore; } void SmithWatermanAlgorithm::launch(const SMatrix& _substitutionMatrix, QByteArray const & _patternSeq, QByteArray const & _searchSeq, int _gapOpen, int _gapExtension, int _minScore) { //set values setValues(_substitutionMatrix, _patternSeq, _searchSeq, _gapOpen, _gapExtension, _minScore); //launch algorithm if (isValidParams() && calculateMatrixLength()) { calculateMatrix(); } else { //No result // See validationParams(); //Perhaps reason: minScore > maxScore // or gap_open >= 0 or gap_extension >= 0 } // clock_t eTime = clock(); } bool SmithWatermanAlgorithm::isValidParams() { if (searchSeq.length() <= 0) return false; if (patternSeq.length() <= 0) return false; if (searchSeq.length() < patternSeq.length()) return false; if (gapOpen >= 0 || gapExtension >= 0) return false; // if (substitutionMatrix.alphabet.isEmpty() || substitutionMatrix.alphabet.isNull()) return false; return true; } //Get results //countResults - count of results will be return QList SmithWatermanAlgorithm::getResults() { return pairAlignmentStrings; } void SmithWatermanAlgorithm::sortByScore( QList & res) { algoLog.trace("RUN sortByScore"); QList buf; QVector pos; QVector sortedScores; // for (int i = 0; i < res.size(); i++) { // pos.append(i); // sortedScores.append( // KeyOfPairAlignSeq(res.at(i).score, // res.at(i).intervalSeq1)); // } for (int i = 0; i < res.size(); i++) for (int j = i + 1; j < res.size(); j++) { // if (sortedScores.at(i).score < sortedScores.at(j).score) // KeyOfPairAlignSeq::exchange(sortedScores[i], pos[i], sortedScores[j] , pos[j]); // // else if (sortedScores.at(i).score == sortedScores.at(j).score // && sortedScores.at(i).intervalSeq1.startPos > sortedScores.at(j).intervalSeq1.startPos) KeyOfPairAlignSeq::exchange(sortedScores[i], pos[i], sortedScores[j] , pos[j]); // // else if (sortedScores.at(i).score == sortedScores.at(j).score // && sortedScores.at(i).intervalSeq1.startPos == sortedScores.at(j).intervalSeq1.startPos // && sortedScores.at(i).intervalSeq1.len > sortedScores.at(j).intervalSeq1.len) // KeyOfPairAlignSeq::exchange(sortedScores[i], pos[i], sortedScores[j] , pos[j]); // // else if (sortedScores.at(i).score == sortedScores.at(j).score // && sortedScores.at(i).intervalSeq1.startPos == sortedScores.at(j).intervalSeq1.startPos // && sortedScores.at(i).intervalSeq1.len == sortedScores.at(j).intervalSeq1.len // && sortedScores.at(i).intervalSeq2.startPos > sortedScores.at(j).intervalSeq2.startPos) // KeyOfPairAlignSeq::exchange(sortedScores[i], pos[i], sortedScores[j] , pos[j]); if (res.at(i).score < res.at(j).score) { KeyOfPairAlignSeq::exchange(res[i],res[j]); } else if (res.at(i).score == res.at(j).score && res.at(i).intervalSeq1.startPos > res.at(j).intervalSeq1.startPos) { KeyOfPairAlignSeq::exchange(res[i], res[j]); } else if (res.at(i).score == res.at(j).score && res.at(i).intervalSeq1.startPos == res.at(j).intervalSeq1.startPos && res.at(i).intervalSeq1.length > res.at(j).intervalSeq1.length) { KeyOfPairAlignSeq::exchange(res[i], res[j]); } } // for (int i = 0; i < res.size(); i++) { // buf.append(res.at(pos.at(i))); // } // res = buf; algoLog.trace("FINISH sortByScore"); } //Calculating dynamic matrix //and save results void SmithWatermanAlgorithm::calculateMatrix() { QString str; char ch; int substValue = 0, max = 0; int f1, f2, e1, e2; //initialization dynamic matrices QVector rowInts; QVector rowChars; for (int tt = 0; tt < patternSeq.length() + 2; tt++) { rowInts.append(0); rowChars.append(STOP); EMatrix.append(0); FMatrix.append(0); } for (int tt = 0; tt < matrixLength; tt++) { matrix.append(rowInts); directionMatrix.append(rowChars); } PairAlignSequences p; QByteArray pairAlign; U2Region sReg; U2Region pReg; QVector > directionSearchSeq; directionSearchSeq.push_back(rowInts); directionSearchSeq.push_back(rowInts); int even = 0; int odd = 0; for (int i = 1; i < searchSeq.length() + 1; i++) { ch = searchSeq.at(i - 1); even = i % 2; odd = (i + 1) % 2; directionSearchSeq[odd][0] = i - 1; p.score = 0; for (int j = 1; j < patternSeq.length()+1; j++) { f1 = FMatrix[j] + gapExtension; f2 = matrix[getRow(i-1)][j] + gapOpen; if (f1 > f2) FMatrix[j] = f1; else FMatrix[j] = f2; e1 = EMatrix[j - 1] + gapExtension; e2 = matrix[getRow(i)][j-1] + gapOpen; if (e1 > e2) EMatrix[j] = e1; else EMatrix[j] = e2; substValue = matrix[getRow(i-1)][j-1] + substitutionMatrix.getScore(ch, patternSeq.at(j-1)); //Get max value and store them max = maximum(EMatrix[j], FMatrix[j], substValue); matrix[getRow(i)][j] = max; //Save direction from we come here for back trace // if (max == 0) directionMatrix[getRow(i)][j] = STOP; // else if (max == EMatrix[j]) directionMatrix[getRow(i)][j] = LEFT; // else if (max == FMatrix[j]) directionMatrix[getRow(i)][j] = UP; // else if (max == substValue) directionMatrix[getRow(i)][j] = DIAG; /* //If value meet the conditions then start backtrace() if ( max >= minScore ) backtrace(i, j, max); */ if (max == 0) { directionSearchSeq[even][j] = i; } else if (max == EMatrix[j]) { directionSearchSeq[even][j] = directionSearchSeq[even][j - 1]; } else if (max == FMatrix[j]) { directionSearchSeq[even][j] = directionSearchSeq[odd][j]; } else if (max == substValue) { directionSearchSeq[even][j] = directionSearchSeq[odd][j - 1]; } if (max >= p.score) { p.intervalSeq1.startPos = directionSearchSeq[even][j]; p.intervalSeq1.length = i - directionSearchSeq[even][j]; p.score = max; } } if (p.score >= minScore) { pairAlignmentStrings.append(p); } // for (int qq = 0; qq < directionSearchSeq[0].size(); qq++) { // cout < maxValue) maxValue = var2; if (var3 > maxValue) maxValue = var3; if (var4 > maxValue) maxValue = var4; return maxValue; } }//namespace ugene-1.9.8/src/plugins/smith_waterman/src/SmithWatermanAlgorithm.h0000644000175000017500000001015411651544324024204 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _SMITHWATERMANALGORITHM_H #define _SMITHWATERMANALGORITHM_H #include "PairAlignSequences.h" #include #include #include namespace U2 { class SmithWatermanAlgorithm { public: SmithWatermanAlgorithm(); virtual ~SmithWatermanAlgorithm() {}; virtual void launch(const SMatrix& m, QByteArray const & _patternSeq, QByteArray const & _searchSeq, int _gapOpen, int _gapExtension, int _minScore); QList getResults(); static void sortByScore(QList & pairAlignmentStrings); protected: bool calculateMatrixLength(); void printMatrix() const; int getRow(int row) const; bool isValidParams(); int maximum(int var1, int var2, int var3, int var4 = 0); void setValues(const SMatrix& _substitutionMatrix, QByteArray const & _patternSeq, QByteArray const & _searchSeq, int _gapOpen, int _gapExtension, int _minScore); QList pairAlignmentStrings; SMatrix substitutionMatrix; QByteArray patternSeq; QByteArray searchSeq; int gapOpen; int gapExtension; int minScore; int matrixLength; int storedResults; QVector > directionMatrix; void backtrace(int row, int col, int score); static const char STOP; static const char UP; static const char LEFT; static const char DIAG; struct KeyOfPairAlignSeq { KeyOfPairAlignSeq(int _score, U2Region const & _intervalSeq1) { setValues(_score, _intervalSeq1); } // KeyOfPairAlignSeq(int _score, U2Region const & _intervalSeq1, U2Region const & _intervalSeq2) { // setValues(_score, _intervalSeq1, _intervalSeq2); // } // KeyOfPairAlignSeq() { // score = 0; // // intervalSeq1.startPos = 0; // intervalSeq1.len = 0; // // intervalSeq2.startPos = 0;; // intervalSeq2.len = 0; // }; KeyOfPairAlignSeq() { score = 0; intervalSeq1.startPos = 0; intervalSeq1.length = 0; }; // static void exchange(KeyOfPairAlignSeq & a, int & pos1, KeyOfPairAlignSeq & b, int & pos2) { // KeyOfPairAlignSeq bufKey; // int buf; // // buf = pos1; // pos1 = pos2; // pos2 = buf; // // bufKey = a; // a = b; // b = bufKey; // } static void exchange(PairAlignSequences & a, PairAlignSequences & b) { PairAlignSequences bufKey; bufKey = a; a = b; b = bufKey; } // void setValues(int _score, U2Region const & _intervalSeq1, U2Region const & _intervalSeq2) { // score = _score; // intervalSeq1 = _intervalSeq1; // intervalSeq2 = _intervalSeq2; // } void setValues(int _score, U2Region const & _intervalSeq1) { score = _score; intervalSeq1 = _intervalSeq1; } int score; U2Region intervalSeq1; }; private: QVector > matrix; QVector EMatrix; QVector FMatrix; void calculateMatrix(); }; }//namespace #endif ugene-1.9.8/src/plugins/smith_waterman/src/PairAlignSequences.cpp0000644000175000017500000000223211651544324023625 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "PairAlignSequences.h" namespace U2 { void PairAlignSequences::setValues(int _score, U2Region const & _intervalSeq1) { score = _score; intervalSeq1 = _intervalSeq1; } PairAlignSequences::PairAlignSequences() { score = 0; isDNAComplemented = false; isAminoTranslated = false; } }//namespace ugene-1.9.8/src/plugins/smith_waterman/smith_waterman.qrc0000644000175000017500000000015711651544324022345 0ustar ilyailya src/sw_opencl.cl ugene-1.9.8/src/plugins/smith_waterman/transl/0000755000175000017500000000000011651544324020114 5ustar ilyailyaugene-1.9.8/src/plugins/smith_waterman/transl/russian.ts0000644000175000017500000006362311651544324022162 0ustar ilyailya QObject START SmithWatermanAlgorithmOPENCL::launch Kernel::setArg(%1) failed OPENCL: Running CL program FINISH SmithWatermanAlgorithmOPENCL::launch Starting cleanup OpenCL resources Finish cleanup OpenCL resources U2::GTest_SmithWatermnan ** , .. U2::LocalWorkflow::SWPrompter unset не указан translated транслированной Searches regions in each sequence from <u>%1</u> similar to <u>%2</u> pattern(s). <br/>Percent similarity between a sequence and a pattern is <u>%3%</u>. <br/>Seaches in <u>%4</u> of a %5sequence. <br/>Outputs the regions found annotated as <u>%6</u>. В каждой последовательности, полученной от <u>%1</u> ищет регионы, похожие на паттерн(ы) <u>%2</u>. <br/>Совпадение между регионом последовательности и паттерном должно быть как минимум <u>%3%</u>. Поиск ведется в <u>%4</u> %5последовательности.<br/>Возвращает найденные регионы как <u>%6</u> аннотации. U2::LocalWorkflow::SWWorker Annotate as Аннотации Pattern(s) Паттерн(ы) Semicolon-separated list of patterns to search for. Список паттернов для поиска. Algorithm Алгоритм Input Data Входная последовательность An input sequence to search in. Последовательность, для которой применяется алгоритм. Pattern Annotations Найденные аннотации The regions found. Аннотации, найденные для последовательности. Name of the result annotations. Имя аннотаций для найденных регионов. Min Score Минимальный процент совпадения Minimal percent similarity between a sequence and a pattern. Минимальный процент совпадения между регионом последовательности и паттерном. Version of the Smith-Waterman algorithm. You can use the optimized versions of the algorithm (SSE, CUDA and OpenCL) if your hardware supports these capabilities. Версия реализации алгоритма Смита-Ватермана. Если имеется соответствующее аппаратное обеспечения для ускорения вычислений могут быть использованы оптимизированные версии алгоритма (SSE, CUDA и OpenCL). Search in Translation Искать в трансляции Translates a supplied nucleotide sequence to protein and searches in the translated sequence. Указывает транслировать входную нуклеотидную последовательность в протеиновую и искать указанный паттерн в полученной протеиновой последовательности. Substitution Matrix Матрица Describes the rate at which one character in a sequence changes to other character states over time. Матрица весов для алгоритма. Filter Results Фильтрация результатов Specifies either to filter the intersected results or to return all the results. Указывает, требуется ли отфильтровывать пересекающиеся результаты. Gap Open Score Вес открытия пропуска Penalty for opening a gap. Штраф, накладываемый за открытие пропуска. Gap Extension Score Вес продления пропуска Penalty for extending a gap. Штраф, накладываемый за продление пропуска. Smith-Waterman Search Поиск Смита-Ватермана Searches regions in a sequence similar to a pattern sequence. Outputs a set of annotations. <p>Under the hood is the well-known Smith-Waterman algorithm for performing local sequence alignment. Поиск подпоследовательностей, похожих на указанный паттерн, в каждой входной последовательности (нуклеотидной или протеиновой), с учётом выбранной матрицы весов. <p>Используется реализация широко известного алгоритма Смита-Ватермана для локального выравнивания пар последовательностей. Auto Авто both strands в обеих цепях direct strand прямой цепи complementary strand комплементарной цепи Null sequence supplied to Smith-Waterman: %1 Incorrect value: pattern alphabet doesn't match sequence alphabet Pattern symbols not matching to alphabet Incorrect value: score value must lay between 0 and 100 Incorrect value: filter name incorrect, default value used Incorrect value: result name is empty, default value used Could not find complement translation for %1, searching only direct strand Invalid value: weight matrix with given name not exists Can't find weight matrix name: '%1'! <empty> Wrong matrix selected. Alphabets do not match SmithWaterman algorithm not found: %1 Incorrect value: search pattern, pattern is empty smith_waterman_task Smith waterman subtasks Found %1 matches of pattern '%2' U2::QDSWActor matches with <u>at least %1 score</u> с оценкой не менее %1 exact matches точным совпадением both strands все direct strand только прямые complement strand только комплементарные Finds pattern <u>%1</u>.<br>Looks for <u>%2</u> in <u>%3</u>. Искать паттерн <u>%1</u>.<br>Искать совпадения <u>%2</u> в <u>%3</u>. %1: percent of score out of bounds. %1: incorrect result filter. %1: pattern is empty. %1: can not find %2. SSearch smith_waterman_task Smith-Waterman Finds regions of similarity to the specified pattern in each input sequence (nucleotide or protein one). <p>Under the hood is the well-known Smith-Waterman algorithm for performing local sequence alignment. Поиск подпоследовательностей, похожих на указанный паттерн, в каждой входной последовательности (нуклеотидной или протеиновой), с учётом выбранной матрицы весов. Используется реализация широко известного алгоритма Смита-Ватермана для локального выравнивания пар последовательностей. Pattern Паттерн A subsequence pattern to look for. Паттерн для поиска интересующих подпоследовательностей. Min score Мин оценка The search stringency. Строгость поиска. Algorithm Алгоритм Algorithm version. Выбор версии алгоритма. Search in translation Искать в трансляции Translate a supplied nucleotide sequence to protein then search in the translated sequence. Транслировать входную нуклеотидную последовательность в протеиновую, искать указанный паттерн в последней. Search in Направление Which strands should be searched: direct, complement or both. В каких стрендах последовательности следует искать паттерн: прямых, комплементарных или всех. Scoring matrix Матрица The scoring matrix. Матрица весов для алгоритма. Filter results Фильтр результатов Result filtering strategy. Дополнительная фильтрация результатов. Gap open score Вес открытия пропуска Gap open score. Вес открытия пропуска. Gap ext score Вес продления пропуска Gap extension score. Вес продления пропуска. Auto Авто U2::SWAlgorithmADVContext Find pattern [Smith-Waterman]... Смит-Ватерман: Поиск по шаблону... U2::SWAlgorithmPlugin Optimized Smith-Waterman Оптимизированный алгроитм Смита-Ватермана Various implementations of Smith-Waterman algorithm Различные реализации алгоритма Смита-Ватермана U2::SWAlgorithmTask Smith Waterman2 SequenceWalker Not enough memory on CUDA-enabled device. The space required is %1 bytes, but only %2 bytes are available. Device id: %3, device name: %4 The Smith-Waterman search allocates ~%1 bytes (%2 Mb) on CUDA device %1 results found ugene-1.9.8/src/plugins/smith_waterman/transl/english.ts0000644000175000017500000005110511651544324022117 0ustar ilyailya QObject START SmithWatermanAlgorithmOPENCL::launch Kernel::setArg(%1) failed OPENCL: Running CL program FINISH SmithWatermanAlgorithmOPENCL::launch Starting cleanup OpenCL resources Finish cleanup OpenCL resources U2::GTest_SmithWatermnan ** , .. U2::LocalWorkflow::SWPrompter unset translated Searches regions in each sequence from <u>%1</u> similar to <u>%2</u> pattern(s). <br/>Percent similarity between a sequence and a pattern is <u>%3%</u>. <br/>Seaches in <u>%4</u> of a %5sequence. <br/>Outputs the regions found annotated as <u>%6</u>. U2::LocalWorkflow::SWWorker Annotate as Pattern(s) Semicolon-separated list of patterns to search for. Algorithm Input Data An input sequence to search in. Pattern Annotations The regions found. Name of the result annotations. Min Score Minimal percent similarity between a sequence and a pattern. Version of the Smith-Waterman algorithm. You can use the optimized versions of the algorithm (SSE, CUDA and OpenCL) if your hardware supports these capabilities. Search in Translation Translates a supplied nucleotide sequence to protein and searches in the translated sequence. Substitution Matrix Describes the rate at which one character in a sequence changes to other character states over time. Filter Results Specifies either to filter the intersected results or to return all the results. Gap Open Score Penalty for opening a gap. Gap Extension Score Penalty for extending a gap. Smith-Waterman Search Searches regions in a sequence similar to a pattern sequence. Outputs a set of annotations. <p>Under the hood is the well-known Smith-Waterman algorithm for performing local sequence alignment. Auto both strands direct strand complementary strand Null sequence supplied to Smith-Waterman: %1 Incorrect value: pattern alphabet doesn't match sequence alphabet Pattern symbols not matching to alphabet Incorrect value: score value must lay between 0 and 100 Incorrect value: filter name incorrect, default value used Incorrect value: result name is empty, default value used Could not find complement translation for %1, searching only direct strand Invalid value: weight matrix with given name not exists Can't find weight matrix name: '%1'! <empty> Wrong matrix selected. Alphabets do not match SmithWaterman algorithm not found: %1 Incorrect value: search pattern, pattern is empty smith_waterman_task Smith waterman subtasks Found %1 matches of pattern '%2' U2::QDSWActor matches with <u>at least %1 score</u> exact matches both strands direct strand complement strand Finds pattern <u>%1</u>.<br>Looks for <u>%2</u> in <u>%3</u>. %1: percent of score out of bounds. %1: incorrect result filter. %1: pattern is empty. %1: can not find %2. SSearch smith_waterman_task Smith-Waterman Finds regions of similarity to the specified pattern in each input sequence (nucleotide or protein one). <p>Under the hood is the well-known Smith-Waterman algorithm for performing local sequence alignment. Pattern A subsequence pattern to look for. Min score The search stringency. Algorithm Algorithm version. Search in translation Translate a supplied nucleotide sequence to protein then search in the translated sequence. Scoring matrix The scoring matrix. Filter results Result filtering strategy. Gap open score Gap open score. Gap ext score Gap extension score. Auto U2::SWAlgorithmADVContext Find pattern [Smith-Waterman]... U2::SWAlgorithmPlugin Optimized Smith-Waterman Various implementations of Smith-Waterman algorithm U2::SWAlgorithmTask Smith Waterman2 SequenceWalker Not enough memory on CUDA-enabled device. The space required is %1 bytes, but only %2 bytes are available. Device id: %3, device name: %4 The Smith-Waterman search allocates ~%1 bytes (%2 Mb) on CUDA device %1 results found ugene-1.9.8/src/plugins/dna_stat/0000755000175000017500000000000011651544322015362 5ustar ilyailyaugene-1.9.8/src/plugins/dna_stat/dna_stat.pri0000644000175000017500000000026111651544322017672 0ustar ilyailya# include (dna_stat.pri) PLUGIN_ID=dna_stat PLUGIN_NAME=Sequence and alignment related statistics PLUGIN_VENDOR=Unipro PLUGIN_MODE=ui include( ../../ugene_plugin_common.pri ) ugene-1.9.8/src/plugins/dna_stat/dna_stat.pro0000644000175000017500000000076211651544322017706 0ustar ilyailyainclude (dna_stat.pri) # Input HEADERS += src/DNAStatPlugin.h \ src/DNAStatMSAProfileDialog.h \ src/DistanceMatrixMSAProfileDialog.h FORMS += src/ui/DNAStatMSAProfileDialog.ui \ src/ui/DistanceMatrixMSAProfileDialog.ui SOURCES += src/DNAStatPlugin.cpp \ src/DNAStatMSAProfileDialog.cpp \ src/DistanceMatrixMSAProfileDialog.cpp TRANSLATIONS += transl/english.ts \ transl/russian.ts ugene-1.9.8/src/plugins/dna_stat/src/0000755000175000017500000000000011651544322016151 5ustar ilyailyaugene-1.9.8/src/plugins/dna_stat/src/DNAStatMSAProfileDialog.cpp0000644000175000017500000002563111651544322023124 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "DNAStatMSAProfileDialog.h" #include #include #include #include #include #include #include #include #include namespace U2 { DNAStatMSAProfileDialog::DNAStatMSAProfileDialog(QWidget* p, MSAEditor* _c) : QDialog(p), ctx(_c) { setupUi(this); connect(fileButton, SIGNAL(clicked()), SLOT(sl_selectFile())); connect(htmlRB, SIGNAL(toggled(bool)), SLOT(sl_formatChanged(bool))); connect(csvRB, SIGNAL(toggled(bool)), SLOT(sl_formatChanged(bool))); } void DNAStatMSAProfileDialog::sl_selectFile() { LastOpenDirHelper h("plugin_dna_stat"); QString filter; if (csvRB->isChecked()) { filter = tr("CSV files") + " (*.csv)"; } else { filter = tr("HTML files") + " (*.html)"; } h.url = QFileDialog::getSaveFileName(this, tr("Select file to save report to.."), h.dir, filter); if (h.url.isEmpty()) { return; } fileEdit->setText(h.url); } void DNAStatMSAProfileDialog::sl_formatChanged(bool) { QString t = fileEdit->text(); if (t.isEmpty()) { return; } QString ext = ".html"; if (csvRB->isChecked()) { ext = ".csv"; } if (t.endsWith(ext)) { return; } QFileInfo fi(t); QString dir = fi.absoluteDir().absolutePath(); if (!(dir.endsWith('/') || dir.endsWith('\\'))) { dir.append('/'); } fileEdit->setText(dir + fi.baseName() + ext); } void DNAStatMSAProfileDialog::accept() { DNAStatMSAProfileTaskSettings s; MAlignmentObject* msaObj = ctx->getMSAObject(); if (msaObj == NULL) { return; } s.profileName = msaObj->getGObjectName(); s.profileURL = msaObj->getDocument()->getURLString(); s.usePercents = percentsRB->isChecked(); s.ma = msaObj->getMAlignment(); s.reportGaps = gapCB->isChecked(); s.stripUnused = !unusedCB->isChecked(); s.countGapsInConsensusNumbering = !skipGapPositionsCB->isChecked(); if (saveBox->isChecked()) { s.outURL = fileEdit->text(); if (s.outURL.isEmpty()) { QMessageBox::critical(this, tr("Error"), tr("File URL is empty")); return; } s.outFormat = csvRB->isChecked() ? DNAStatMSAProfileOutputFormat_CSV : DNAStatMSAProfileOutputFormat_HTML; } AppContext::getTaskScheduler()->registerTopLevelTask(new DNAStatMSAProfileTask(s)); QDialog::accept(); } ////////////////////////////////////////////////////////////////////////// // task DNAStatMSAProfileTask::DNAStatMSAProfileTask(const DNAStatMSAProfileTaskSettings& _s) : Task(tr("Generate alignment profile"), TaskFlag_None), s(_s) { setVerboseLogMode(true); } void DNAStatMSAProfileTask::run() { computeStats(); if (hasError()) { return; } if (s.outFormat != DNAStatMSAProfileOutputFormat_Show && s.outURL.isEmpty()) { setError(tr("No output file name specified")); return; } if (s.outFormat == DNAStatMSAProfileOutputFormat_Show || s.outFormat == DNAStatMSAProfileOutputFormat_HTML) { int maxVal = s.usePercents ? 100 : s.ma.getNumRows(); QString colors[] = {"#ff5555", "#ff9c00", "#60ff00", "#a1d1e5", "#dddddd"}; //setup style resultText= "\n"; //header resultText+= "

" + tr("Multiple Sequence Alignment Grid Profile") + "


\n"; resultText+="\n"; resultText+= "\n"; resultText+= "\n"; resultText+= "
"+tr("Alignment file:") + "" + s.profileURL + "@" + s.profileName+ "
"+tr("Table content:") + "" +(s.usePercents ? tr("symbol percents") : tr("symbol counts")) + "
\n"; resultText+="

\n"; resultText+=""; //consensus numbers line resultText+=""; int pos = 1; for (int i=0; i< columns.size(); i++) { ColumnStat& cs = columns[i]; QString posStr; bool nums = s.countGapsInConsensusNumbering || cs.consChar!=MAlignment_GapChar; posStr = nums? QString::number(pos++) : QString(" "); // while(posStr.length() < maxLenLen) {posStr = (nums ? "0" : " ") + posStr;} resultText+=""; } resultText+="\n"; //consensus chars line resultText+=""; for (int i=0; i< columns.size(); i++) { ColumnStat& cs = columns[i]; resultText+=""; } resultText+="\n"; //out char freqs QByteArray aChars = s.ma.getAlphabet()->getAlphabetChars(); for (int i=0; i < aChars.size(); i++) { char c = aChars[i]; if (c == MAlignment_GapChar && !s.reportGaps) { continue; } if (s.stripUnused && unusedChars.contains(c)) { continue; } int idx = char2index[c]; resultText+=""; resultText+=""; for (int j=0; j < columns.size(); j++) { ColumnStat& cs = columns[j]; int val = cs.charFreqs[idx]; QString colorStr; int hotness = qRound(100 * double(val) / maxVal); if (hotness >= 90) { colorStr = " bgcolor=" + colors[0]; } else if (hotness >= 70) { colorStr = " bgcolor=" + colors[1]; } else if (hotness > 50) { colorStr = " bgcolor=" + colors[2]; } else if (hotness > 25) { colorStr = " bgcolor=" + colors[3]; } else if (hotness > 10) { colorStr = " bgcolor=" + colors[4]; } resultText+="" + QString::number(cs.charFreqs[idx]) + ""; } resultText+="\n"; } resultText+="
" + posStr + "
Consensus " + QString(cs.consChar) + "
" + QString(c) + "
\n"; //legend: resultText+="

\n"; resultText+= "\n"; resultText+="\n"; resultText+="\n"; resultText+="\n"; resultText+="\n"; resultText+="
" + tr("Legend:")+"  \n"; resultText+="10%25%50%70%90%

\n"; } else { //out char freqs QByteArray aChars = s.ma.getAlphabet()->getAlphabetChars(); for (int i=0; i < aChars.size(); i++) { char c = aChars[i]; if (c == MAlignment_GapChar && !s.reportGaps) { continue; } if (s.stripUnused && unusedChars.contains(c)) { continue; } int idx = char2index[c]; resultText+=QString(c); for (int j=0; j < columns.size(); j++) { ColumnStat& cs = columns[j]; resultText+="," + QString::number(cs.charFreqs[idx]); } resultText+="\n"; } } if (s.outFormat != DNAStatMSAProfileOutputFormat_Show) { QFile f(s.outURL); bool ok = f.open(QIODevice::Truncate | QIODevice::WriteOnly); if (!ok) { setError(tr("Can't open file for write: %1").arg(s.outURL)); return; } f.write(resultText.toLocal8Bit()); } } Task::ReportResult DNAStatMSAProfileTask::report() { if (s.outFormat != DNAStatMSAProfileOutputFormat_Show || hasError() || isCanceled()) { return Task::ReportResult_Finished; } assert(!resultText.isEmpty()); QString title = s.profileName.isEmpty() ? tr("Alignment profile") : tr("Alignment profile for %1").arg(s.profileName); WebWindow* w = new WebWindow(title, resultText); w->setWindowIcon(QIcon(":core/images/chart_bar.png")); AppContext::getMainWindow()->getMDIManager()->addMDIWindow(w); return Task::ReportResult_Finished; } void DNAStatMSAProfileTask::computeStats() { //fill names QByteArray aChars = s.ma.getAlphabet()->getAlphabetChars(); for (int i = 0; i < aChars.size(); i++) { char c = aChars[i]; verticalColumnNames.append(QChar(c)); char2index[uchar(c)] = i; unusedChars.insert(c); } //fill values columns.resize(s.ma.getLength()); consenusChars.resize(s.ma.getLength()); for (int pos = 0; pos < s.ma.getLength(); pos++) { int topCharCount = 0; ColumnStat& cs = columns[pos]; cs.charFreqs.resize(aChars.size()); cs.consChar = MAlignment_GapChar; for (int i = 0; i< s.ma.getNumRows(); i++) { const MAlignmentRow& row = s.ma.getRow(i); char c = row.chatAt(pos); unusedChars.remove(c); int idx = char2index.value(c); int v = ++cs.charFreqs[idx]; if (v > topCharCount) { topCharCount = v; cs.consChar = c; } else if (v == topCharCount) { cs.consChar = MAlignment_GapChar; } } } if (s.usePercents) { int charsInColumn = s.ma.getNumRows(); for (int pos = 0; pos < s.ma.getLength(); pos++) { ColumnStat& cs = columns[pos]; for (int i=0; i < aChars.size(); i++) { char c = aChars[i]; int idx = char2index.value(c); cs.charFreqs[idx] = qRound(100.0 * cs.charFreqs[idx] / charsInColumn); } } } } }//namespace ugene-1.9.8/src/plugins/dna_stat/src/DistanceMatrixMSAProfileDialog.cpp0000644000175000017500000002333511651544322024604 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "DistanceMatrixMSAProfileDialog.h" #include #include #include #include #include #include #include #include #include #include #include #include namespace U2 { DistanceMatrixMSAProfileDialog::DistanceMatrixMSAProfileDialog(QWidget* p, MSAEditor* _c) : QDialog(p), ctx(_c) { setupUi(this); QStringList algo = AppContext::getMSADistanceAlgorithmRegistry()->getAlgorithmIds(); algoCombo->addItems(algo); connect(fileButton, SIGNAL(clicked()), SLOT(sl_selectFile())); connect(htmlRB, SIGNAL(toggled(bool)), SLOT(sl_formatChanged(bool))); connect(csvRB, SIGNAL(toggled(bool)), SLOT(sl_formatChanged(bool))); } void DistanceMatrixMSAProfileDialog::sl_selectFile() { LastOpenDirHelper h("plugin_dna_stat"); QString filter; if (csvRB->isChecked()) { filter = tr("CSV files") + " (*.csv)"; } else { filter = tr("HTML files") + " (*.html)"; } h.url = QFileDialog::getSaveFileName(this, tr("Select file to save report to.."), h.dir, filter); if (h.url.isEmpty()) { return; } fileEdit->setText(h.url); } void DistanceMatrixMSAProfileDialog::sl_formatChanged(bool) { QString t = fileEdit->text(); if (t.isEmpty()) { return; } QString ext = ".html"; if (csvRB->isChecked()) { ext = ".csv"; } if (t.endsWith(ext)) { return; } QFileInfo fi(t); QString dir = fi.absoluteDir().absolutePath(); if (!(dir.endsWith('/') || dir.endsWith('\\'))) { dir.append('/'); } fileEdit->setText(dir + fi.baseName() + ext); } void DistanceMatrixMSAProfileDialog::accept() { DistanceMatrixMSAProfileTaskSettings s; MAlignmentObject* msaObj = ctx->getMSAObject(); if (msaObj == NULL) { return; } s.profileName = msaObj->getGObjectName(); s.profileURL = msaObj->getDocument()->getURLString(); s.usePercents = percentsRB->isChecked(); s.algoName = algoCombo->currentText(); s.ma = msaObj->getMAlignment(); if (saveBox->isChecked()) { s.outURL = fileEdit->text(); if (s.outURL.isEmpty()) { QMessageBox::critical(this, tr("Error"), tr("File URL is empty")); return; } s.outFormat = csvRB->isChecked() ? DistanceMatrixMSAProfileOutputFormat_CSV : DistanceMatrixMSAProfileOutputFormat_HTML; } AppContext::getTaskScheduler()->registerTopLevelTask(new DistanceMatrixMSAProfileTask(s)); QDialog::accept(); } ////////////////////////////////////////////////////////////////////////// // task DistanceMatrixMSAProfileTask::DistanceMatrixMSAProfileTask(const DistanceMatrixMSAProfileTaskSettings& _s) : Task(tr("Generate distance matrix"), TaskFlag_NoRun), s(_s) { setVerboseLogMode(true); } void DistanceMatrixMSAProfileTask::prepare() { MSADistanceAlgorithm* algo = AppContext::getMSADistanceAlgorithmRegistry()->getAlgorithmFactory(s.algoName)->createAlgorithm(s.ma); if (algo == NULL) { return; } addSubTask(algo); } QList DistanceMatrixMSAProfileTask::onSubTaskFinished(Task* subTask){ MSADistanceAlgorithm* algo = qobject_cast(subTask); QList res; if (algo != NULL) { if (s.outFormat != DistanceMatrixMSAProfileOutputFormat_Show && s.outURL.isEmpty()) { setError(tr("No output file name specified")); return res; } if (s.outFormat == DistanceMatrixMSAProfileOutputFormat_Show || s.outFormat == DistanceMatrixMSAProfileOutputFormat_HTML) { int maxVal = s.usePercents ? 100 : s.ma.getLength(); QString colors[] = {"#ff5555", "#ff9c00", "#60ff00", "#a1d1e5", "#dddddd"}; //setup style resultText= "\n"; //header resultText+= "

" + tr("Multiple Sequence Alignment Distance Matrix") + "


\n"; resultText+="\n"; resultText+= "\n"; resultText+= "\n"; resultText+= "
"+tr("Alignment file:") + "" + s.profileURL + "@" + s.profileName+ "
"+tr("Table content:") + "" +(s.usePercents ? tr("similarity percents") : tr("similarity distance")) + "
\n"; resultText+="

\n"; resultText+="\n"; resultText+=""; for (int i=0; i < s.ma.getNumRows(); i++) { QString name = s.ma.getRow(i).getName(); resultText+=""; } resultText+="\n"; //out char freqs for (int i=0; i < s.ma.getNumRows(); i++) { QString name = s.ma.getRow(i).getName(); resultText+=""; resultText+=""; for (int j=0; j < s.ma.getNumRows(); j++) { int val = qRound(algo->getSimilarity(i, j) * (s.usePercents ? (100.0 / s.ma.getLength()) : 1.0)); QString colorStr = ""; if (i != j) { int hotness = qRound(100 * double(val) / maxVal); if (hotness >= 90) { colorStr = " bgcolor=" + colors[0]; } else if (hotness >= 70) { colorStr = " bgcolor=" + colors[1]; } else if (hotness > 50) { colorStr = " bgcolor=" + colors[2]; } else if (hotness > 25) { colorStr = " bgcolor=" + colors[3]; } else if (hotness > 10) { colorStr = " bgcolor=" + colors[4]; } } resultText+="" + QString::number(val) + (s.usePercents ? "%" : "") + ""; } resultText+="\n"; } resultText+="
" + name + "
" + name + "
\n"; //legend: resultText+="

\n"; resultText+= "\n"; resultText+="\n"; resultText+="\n"; resultText+="\n"; resultText+="\n"; resultText+="
" + tr("Legend:")+"  \n"; resultText+="10%25%50%70%90%

\n"; } else { resultText+= " "; for (int i=0; i < s.ma.getNumRows(); i++) { QString name = s.ma.getRow(i).getName(); TextUtils::wrapForCSV(name); resultText+= "," + name; } resultText+="\n"; for (int i=0; i < s.ma.getNumRows(); i++) { QString name = s.ma.getRow(i).getName(); TextUtils::wrapForCSV(name); resultText+=name; for (int j=0; j < s.ma.getNumRows(); j++) { int val = qRound(algo->getSimilarity(i, j) * (s.usePercents ? (100.0 / s.ma.getLength()) : 1.0)); resultText+= "," + QString::number(val) + (s.usePercents ? "%" : ""); } resultText+="\n"; } } if (s.outFormat != DistanceMatrixMSAProfileOutputFormat_Show) { QFile f(s.outURL); bool ok = f.open(QIODevice::Truncate | QIODevice::WriteOnly); if (!ok) { setError(tr("Can't open file for write: %1").arg(s.outURL)); return res; } f.write(resultText.toLocal8Bit()); } } return res; } Task::ReportResult DistanceMatrixMSAProfileTask::report() { if (s.outFormat != DistanceMatrixMSAProfileOutputFormat_Show || hasError() || isCanceled()) { return Task::ReportResult_Finished; } assert(!resultText.isEmpty()); QString title = s.profileName.isEmpty() ? tr("Distance matrix") : tr("Distance matrix for %1").arg(s.profileName); WebWindow* w = new WebWindow(title, resultText); w->setWindowIcon(QIcon(":core/images/chart_bar.png")); AppContext::getMainWindow()->getMDIManager()->addMDIWindow(w); return Task::ReportResult_Finished; } }//namespace ugene-1.9.8/src/plugins/dna_stat/src/ui/0000755000175000017500000000000011651544322016566 5ustar ilyailyaugene-1.9.8/src/plugins/dna_stat/src/ui/DNAStatMSAProfileDialog.ui0000644000175000017500000001267211651544322023375 0ustar ilyailya DNAStatMSAProfileDialog 0 0 547 347 Generate Alignment Profile Profile mode Counts true Percents Custom options Show scores for gaps Show scores for symbols not used in alignment Skip gaps in consensus position increments Save profile to file true false File ... Hypertext (.HTML) true Comma separated ( .CSV) false label fileEdit fileButton htmlRB csvRB Qt::Vertical 20 17 Qt::Horizontal 38 18 Generate true Cancel cancelButton clicked() DNAStatMSAProfileDialog reject() 498 238 273 130 okButton clicked() DNAStatMSAProfileDialog accept() 415 238 273 130 ugene-1.9.8/src/plugins/dna_stat/src/ui/DistanceMatrixMSAProfileDialog.ui0000644000175000017500000001146311651544322025053 0ustar ilyailya DistanceMatrixMSAProfileDialog 0 0 547 271 Generate Distance matrix Distance algorithm Profile mode Counts true Percents Save profile to file true false File ... Hypertext (.HTML) true Comma separated ( .CSV) false Qt::Vertical 20 17 Qt::Horizontal 38 18 Generate true Cancel cancelButton clicked() DistanceMatrixMSAProfileDialog reject() 498 238 273 130 okButton clicked() DistanceMatrixMSAProfileDialog accept() 415 238 273 130 ugene-1.9.8/src/plugins/dna_stat/src/DistanceMatrixMSAProfileDialog.h0000644000175000017500000000527711651544322024256 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_DISTANCE_MATRIX_MSA_PROFILE_DIALOG_H_ #define _U2_DISTANCE_MATRIX_MSA_PROFILE_DIALOG_H_ #include "ui/ui_DistanceMatrixMSAProfileDialog.h" #include #include #include #include #include namespace U2 { class MSAEditor; class DistanceMatrixMSAProfileDialog : public QDialog, public Ui_DistanceMatrixMSAProfileDialog { Q_OBJECT public: DistanceMatrixMSAProfileDialog(QWidget* p, MSAEditor* ctx); virtual void accept(); private slots: void sl_selectFile(); void sl_formatChanged(bool); private: MSAEditor* ctx; }; enum DistanceMatrixMSAProfileOutputFormat { DistanceMatrixMSAProfileOutputFormat_Show, DistanceMatrixMSAProfileOutputFormat_CSV, DistanceMatrixMSAProfileOutputFormat_HTML }; class DistanceMatrixMSAProfileTaskSettings { public: DistanceMatrixMSAProfileTaskSettings(){ outFormat = DistanceMatrixMSAProfileOutputFormat_Show; usePercents = false; } QString algoName; // selected algorithm QString profileName; // usually object name QString profileURL; // document url MAlignment ma; bool usePercents; //report percents but not counts DistanceMatrixMSAProfileOutputFormat outFormat; QString outURL; }; class DistanceMatrixMSAProfileTask : public Task { Q_OBJECT public: DistanceMatrixMSAProfileTask(const DistanceMatrixMSAProfileTaskSettings& s); virtual void prepare(); QList onSubTaskFinished(Task* subTask); //void run(); ReportResult report(); private: DistanceMatrixMSAProfileTaskSettings s; QString resultText; }; }//namespace #endif ugene-1.9.8/src/plugins/dna_stat/src/DNAStatPlugin.cpp0000644000175000017500000001021211651544322021266 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "DNAStatPlugin.h" #include "DNAStatMSAProfileDialog.h" #include "DistanceMatrixMSAProfileDialog.h" #include #include #include #include #include #include #include namespace U2 { extern "C" Q_DECL_EXPORT Plugin* U2_PLUGIN_INIT_FUNC() { if (AppContext::getMainWindow()) { DNAStatPlugin* plug = new DNAStatPlugin(); return plug; } return NULL; } DNAStatPlugin::DNAStatPlugin() : Plugin(tr("DNA Statistics"), tr("Provides statistical reports for sequences and alignments")) { statViewCtx = new DNAStatMSAEditorContext(this); statViewCtx->init(); distanceViewCtx = new DistanceMatrixMSAEditorContext(this); distanceViewCtx->init(); } DNAStatMSAEditorContext::DNAStatMSAEditorContext(QObject* p) : GObjectViewWindowContext(p, MSAEditorFactory::ID) {} void DNAStatMSAEditorContext::initViewContext(GObjectView* v) { MSAEditor* msaed = qobject_cast(v); if (msaed != NULL && !msaed->getMSAObject()) return; GObjectViewAction* profileAction = new GObjectViewAction(this, v, tr("Generate grid profile")); connect(profileAction, SIGNAL(triggered()), SLOT(sl_showMSAProfileDialog())); addViewAction(profileAction); } void DNAStatMSAEditorContext::buildMenu(GObjectView* v, QMenu* m) { MSAEditor* msaed = qobject_cast(v); if (msaed != NULL && !msaed->getMSAObject()) return; QList actions = getViewActions(v); QMenu* statMenu = GUIUtils::findSubMenu(m, MSAE_MENU_STATISTICS); assert(statMenu!=NULL); foreach(GObjectViewAction* a, actions) { statMenu->addAction(a); } } void DNAStatMSAEditorContext::sl_showMSAProfileDialog() { GObjectViewAction* viewAction = qobject_cast(sender()); MSAEditor* msaEd = qobject_cast(viewAction->getObjectView()); DNAStatMSAProfileDialog d(msaEd->getWidget(), msaEd); d.exec(); } DistanceMatrixMSAEditorContext::DistanceMatrixMSAEditorContext(QObject* p) : GObjectViewWindowContext(p, MSAEditorFactory::ID) {} void DistanceMatrixMSAEditorContext::initViewContext(GObjectView* v) { MSAEditor* msaed = qobject_cast(v); if (msaed != NULL && !msaed->getMSAObject()) return; GObjectViewAction* profileAction = new GObjectViewAction(this, v, tr("Generate distance matrix")); connect(profileAction, SIGNAL(triggered()), SLOT(sl_showDistanceMatrixDialog())); addViewAction(profileAction); } void DistanceMatrixMSAEditorContext::buildMenu(GObjectView* v, QMenu* m) { MSAEditor* msaed = qobject_cast(v); if (msaed != NULL && !msaed->getMSAObject()) return; QList actions = getViewActions(v); QMenu* statMenu = GUIUtils::findSubMenu(m, MSAE_MENU_STATISTICS); assert(statMenu!=NULL); foreach(GObjectViewAction* a, actions) { statMenu->addAction(a); } } void DistanceMatrixMSAEditorContext::sl_showDistanceMatrixDialog() { GObjectViewAction* viewAction = qobject_cast(sender()); MSAEditor* msaEd = qobject_cast(viewAction->getObjectView()); DistanceMatrixMSAProfileDialog d(msaEd->getWidget(), msaEd); d.exec(); } }//namespace ugene-1.9.8/src/plugins/dna_stat/src/DNAStatPlugin.h0000644000175000017500000000343111651544322020740 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_DNA_STAT_PLUGIN_H_ #define _U2_DNA_STAT_PLUGIN_H_ #include #include namespace U2 { class DNAStatPlugin : public Plugin { Q_OBJECT public: DNAStatPlugin(); private: GObjectViewWindowContext* statViewCtx; GObjectViewWindowContext* distanceViewCtx; }; class DNAStatMSAEditorContext: public GObjectViewWindowContext { Q_OBJECT public: DNAStatMSAEditorContext(QObject* p); protected slots: void sl_showMSAProfileDialog(); void buildMenu(GObjectView* v, QMenu* m); protected: virtual void initViewContext(GObjectView* view); }; class DistanceMatrixMSAEditorContext: public GObjectViewWindowContext { Q_OBJECT public: DistanceMatrixMSAEditorContext(QObject* p); protected slots: void sl_showDistanceMatrixDialog(); void buildMenu(GObjectView* v, QMenu* m); protected: virtual void initViewContext(GObjectView* view); }; } //namespace #endif ugene-1.9.8/src/plugins/dna_stat/src/DNAStatMSAProfileDialog.h0000644000175000017500000000633311651544322022567 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_DNASTAT_MSA_PROFILE_DIALOG_H_ #define _U2_DNASTAT_MSA_PROFILE_DIALOG_H_ #include "ui/ui_DNAStatMSAProfileDialog.h" #include #include #include #include #include namespace U2 { class MSAEditor; class DNAStatMSAProfileDialog : public QDialog, public Ui_DNAStatMSAProfileDialog { Q_OBJECT public: DNAStatMSAProfileDialog(QWidget* p, MSAEditor* ctx); virtual void accept(); private slots: void sl_selectFile(); void sl_formatChanged(bool); private: MSAEditor* ctx; }; enum DNAStatMSAProfileOutputFormat { DNAStatMSAProfileOutputFormat_Show, DNAStatMSAProfileOutputFormat_CSV, DNAStatMSAProfileOutputFormat_HTML }; class DNAStatMSAProfileTaskSettings { public: DNAStatMSAProfileTaskSettings(){ outFormat = DNAStatMSAProfileOutputFormat_Show; usePercents = false; reportGaps = false; stripUnused = false; countGapsInConsensusNumbering = true; } QString profileName; // usually object name QString profileURL; // document url MAlignment ma; bool usePercents; //report percents but not counts DNAStatMSAProfileOutputFormat outFormat; QString outURL; bool reportGaps; // report GAPS statistics bool stripUnused; // do not include into report chars unused in alignment bool countGapsInConsensusNumbering; //affects html output only }; class DNAStatMSAProfileTask : public Task { Q_OBJECT public: DNAStatMSAProfileTask(const DNAStatMSAProfileTaskSettings& s); void run(); ReportResult report(); private: void computeStats(); DNAStatMSAProfileTaskSettings s; // fields to keep statistics struct ColumnStat { char consChar; QVector charFreqs; }; QStringList verticalColumnNames; QVector columns; QVector consenusChars; QHash char2index; //char 2 index in 'ColumnStat' QSet unusedChars; QString resultText; }; }//namespace #endif ugene-1.9.8/src/plugins/dna_stat/transl/0000755000175000017500000000000011651544322016665 5ustar ilyailyaugene-1.9.8/src/plugins/dna_stat/transl/russian.ts0000644000175000017500000003530511651544322020727 0ustar ilyailya DNAStatMSAProfileDialog Generate Alignment Profile Генерация сеточного отчета для выравнивания Profile mode Использовать Counts Числа Percents Проценты Custom options Дополнительные опции Show scores for gaps Включить в отчет статистику для пропусков Show scores for symbols not used in alignment Включить в отчет неиспользуемые символы Skip gaps in consensus position increments Не учитывать пропуске в шкале позиций Save profile to file Сохранить отчет в файл File Файл ... Hypertext (.HTML) Гипертекст (.HTML) Comma separated ( .CSV) Значения через запятую (.CSV) Generate Создать отчет Cancel Отмена DistanceMatrixMSAProfileDialog Generate Distance matrix Distance algorithm Profile mode Использовать Counts Числа Percents Проценты Save profile to file Сохранить отчет в файл File Файл ... Hypertext (.HTML) Гипертекст (.HTML) Comma separated ( .CSV) Значения через запятую (.CSV) Generate Создать отчет Cancel Отмена U2::DNAStatMSAEditorContext Generate grid profile Показать сеточный отчет U2::DNAStatMSAProfileDialog CSV files CSV файлы HTML files HTML файлы Select file to save report to.. Выберете файл для сохранения отчета Error Ошибка File URL is empty Не указан файл для сохранения отчета U2::DNAStatMSAProfileTask Generate alignment profile Генерация сеточного отчета No output file name specified Не указано имя файла для сохранения отчета Alignment file: Файл: Table content: Результаты: symbol percents процент символа symbol counts количество символов Can't open file for write: %1 Не могу открыть файл для записи: %1 Alignment profile Отчет для множественного выравнивания Alignment profile for %1 Отчет для множественного выравнивания %1 Multiple Sequence Alignment Grid Profile Сеточный отчет для множественного выравнивания Legend: Легенда: U2::DNAStatPlugin DNA Statistics Provides statistical reports for sequences and alignments Набор статистических отчетов U2::DistanceMatrixMSAEditorContext Generate distance matrix U2::DistanceMatrixMSAProfileDialog CSV files CSV файлы HTML files HTML файлы Select file to save report to.. Выберете файл для сохранения отчета Error Ошибка File URL is empty Не указан файл для сохранения отчета U2::DistanceMatrixMSAProfileTask Generate distance matrix No output file name specified Не указано имя файла для сохранения отчета Multiple Sequence Alignment Distance Matrix Alignment file: Файл: Table content: Результаты: similarity percents similarity distance Legend: Легенда: Can't open file for write: %1 Не могу открыть файл для записи: %1 Distance matrix Distance matrix for %1 ugene-1.9.8/src/plugins/dna_stat/transl/czech.ts0000644000175000017500000001514311651544322020335 0ustar ilyailya DNAStatMSAProfileDialog Generate Alignment Profile Profile mode Counts Percents Custom options Show scores for gaps Show scores for symbols not used in alignment Skip gaps in consensus position increments Save profile to file File ... Hypertext (.HTML) Comma separated ( .CSV) Generate Cancel U2::DNAStatMSAEditorContext Generate grid profile U2::DNAStatMSAProfileDialog CSV files HTML files Select file to save report to.. Error File URL is empty U2::DNAStatMSAProfileTask Generate alignment profile No output file name specified Alignment file: Table content: symbol percents symbol counts Can't open file for write: %1 Alignment profile Alignment profile for %1 Multiple Sequence Alignment Grid Profile Legend: U2::DNAStatPlugin DNA Statistics Provides statistical reports for sequences and alignments ugene-1.9.8/src/plugins/dna_stat/transl/english.ts0000644000175000017500000003147311651544322020676 0ustar ilyailya DNAStatMSAProfileDialog Generate Alignment Profile Profile mode Counts Percents Custom options Show scores for gaps Show scores for symbols not used in alignment Skip gaps in consensus position increments Save profile to file File ... Hypertext (.HTML) Comma separated ( .CSV) Generate Cancel DistanceMatrixMSAProfileDialog Generate Distance matrix Distance algorithm Profile mode Counts Percents Save profile to file File ... Hypertext (.HTML) Comma separated ( .CSV) Generate Cancel U2::DNAStatMSAEditorContext Generate grid profile U2::DNAStatMSAProfileDialog CSV files HTML files Select file to save report to.. Error File URL is empty U2::DNAStatMSAProfileTask Generate alignment profile No output file name specified Alignment file: Table content: symbol percents symbol counts Can't open file for write: %1 Alignment profile Alignment profile for %1 Multiple Sequence Alignment Grid Profile Legend: U2::DNAStatPlugin DNA Statistics Provides statistical reports for sequences and alignments U2::DistanceMatrixMSAEditorContext Generate distance matrix U2::DistanceMatrixMSAProfileDialog CSV files HTML files Select file to save report to.. Error File URL is empty U2::DistanceMatrixMSAProfileTask Generate distance matrix No output file name specified Multiple Sequence Alignment Distance Matrix Alignment file: Table content: similarity percents similarity distance Legend: Can't open file for write: %1 Distance matrix Distance matrix for %1 ugene-1.9.8/src/plugins/remote_blast/0000755000175000017500000000000011651544324016247 5ustar ilyailyaugene-1.9.8/src/plugins/remote_blast/remote_blast.pro0000644000175000017500000000133611651544324021454 0ustar ilyailyainclude (remote_blast.pri) # Input HEADERS += src/RemoteBLASTPlugin.h \ src/RemoteBLASTPluginTests.h \ src/RemoteBLASTTask.h \ src/HttpRequest.h \ src/SendSelectionDialog.h \ src/RemoteBLASTConsts.h \ src/RemoteBLASTWorker.h \ src/DBRequestFactory.h \ src/BlastQuery.h FORMS += src/ui/RemoteBLASTDialog.ui SOURCES += src/RemoteBLASTPlugin.cpp \ src/RemoteBLASTPluginTests.cpp \ src/RemoteBLASTTask.cpp \ src/HttpRequestBLAST.cpp \ src/HttpRequestCDD.cpp \ src/SendSelectionDialog.cpp \ src/RemoteBLASTConsts.cpp \ src/RemoteBLASTWorker.cpp \ src/BlastQuery.cpp RESOURCES += remote_blast.qrc TRANSLATIONS += transl/english.ts transl/russian.ts ugene-1.9.8/src/plugins/remote_blast/remote_blast.qrc0000644000175000017500000000030111651544324021430 0ustar ilyailya images/remote_db_request.png images/down_arrow.png images/up_arrow.png ugene-1.9.8/src/plugins/remote_blast/images/0000755000175000017500000000000011651544324017514 5ustar ilyailyaugene-1.9.8/src/plugins/remote_blast/images/down_arrow.png0000644000175000017500000000076311651544324022411 0ustar ilyailyaPNG  IHDR;tEXtSoftwareAdobe ImageReadyqe<IDATxڴN@[*'T}7I( "Θoͺ1M e៙yMN<40P||^VE))_lj`Ѳ4Po }c]W sDzxؠJ[$`Q'Um 0M 6D qL(#V^Bh:9sVбtSXAQ, |gVgnd_^^<"^Op\S 2FN?8[]os(QjO0xmx4JG(hY$?z\UDJq@pFo2^S1ɏ$'-whDf2%ECHh$&gBw*`XxmrIENDB`ugene-1.9.8/src/plugins/remote_blast/images/remote_db_request.png0000644000175000017500000000137511651544324023740 0ustar ilyailyaPNG  IHDRatEXtSoftwareAdobe ImageReadyqe<IDATxڤSMHTQ޼K͟l ,jDB!2A\ -[ -leDBLAKc"p!kjhrLƹ̇EѢ s~|9jJ)r0{( و|;meCCCB^0B aqqlmffI:ʩ-ƘUX#x}_ 5`|Ast:t.iKK 'X'Xf0ssf2UDQ&J!#|U`/x\pn8Jbyar9=,0V*ʯOYr i%^X^)4 pHTjVӃкoR}3kZ-2A/|ut+!d۹>xl:^g͝.#ˡ\.[$eb|||Yw!@%60hG`IENDB`ugene-1.9.8/src/plugins/remote_blast/images/up_arrow.png0000644000175000017500000000102411651544324022055 0ustar ilyailyaPNG  IHDR;sRGBbKGD pHYs  tIME/>IDAT8˵]OQv)D FTP4Fz B#*i[y4+VlvΙgg*<ӿQOu gW|A+oķ']oKwgb XmXיե3X;-g"E^QW {M 6]) Hvdp3H% fG{TyJ5]Rtk8tPv< pE*?H,Tcr?B${l~0HxCWtu%< 63LačX,NgRX3RS8 yDmt4{Ul: )Rl'8#\p7 =2y8ҋ#,/^UKZ8MIENDB`ugene-1.9.8/src/plugins/remote_blast/src/0000755000175000017500000000000011651544324017036 5ustar ilyailyaugene-1.9.8/src/plugins/remote_blast/src/HttpRequestCDD.cpp0000644000175000017500000001501711651544324022351 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "HttpRequest.h" namespace U2 { const QString HttpRequestCDD::host = "http://www.ncbi.nlm.nih.gov/Structure/cdd/wrpsb.cgi?"; void HttpRequestCDD::sendRequest(const QString ¶ms,const QString &query) { QString request = host; request.append(params); request.append("&seqinput="); request.append(query); IOAdapterFactory * iof = AppContext::getIOAdapterRegistry()->getIOAdapterFactoryById( BaseIOAdapters::HTTP_FILE ); IOAdapter * io = iof->createIOAdapter(); if(!io->open( request, IOAdapterMode_Read )) { connectionError = true; error = QObject::tr("Cannot open the IO adapter"); return; } int offs = 0; int read = 0; int CHUNK_SIZE = 1024; QByteArray response( CHUNK_SIZE, 0 ); do { if(task->isCanceled()) { io->close(); return; } read = io->readBlock( response.data() + offs, CHUNK_SIZE ); offs += read; response.resize( offs + read ); } while( read == CHUNK_SIZE ); response.resize(offs); io->close(); if(read<0){ connectionError = true; error = QObject::tr("Cannot load page"); return; } int ind = response.indexOf("RID = ") + 6; int ind2 = response.indexOf("<",ind); QString rid = response.mid(ind, ind2 - ind); while(response.indexOf("Loading...")!=-1) { Waiter::await(5000); io = iof->createIOAdapter(); if(!io->open( host + "RID=" + rid, IOAdapterMode_Read )) { connectionError = true; error = QObject::tr("Cannot open the IO adapter"); return; } int offs = 0; int read = 0; int CHUNK_SIZE = 1024; response.resize(CHUNK_SIZE); response.fill(0); do { if(task->isCanceled()) { io->close(); return; } read = io->readBlock( response.data() + offs, CHUNK_SIZE ); offs += read; response.resize( offs + read ); } while( read == CHUNK_SIZE ); response.resize(offs); io->close(); if(read<0){ connectionError = true; error = QObject::tr("Cannot load page"); return; } } if((response.indexOf("Loading...")!=-1) || (response.isEmpty())) { connectionError = true; error = QObject::tr("The database did not respond"); return; } if(response.indexOf("Query Exception:")!=-1) { connectionError = true; error = QObject::tr("Incorrect query"); return; } ResponseBuffer buf; buf.setBuffer(&response); buf.open(QIODevice::ReadOnly); parseResult(buf); } void HttpRequestCDD::parseResult(ResponseBuffer &buf) { QByteArray b = buf.readLine(); int fl = 0; while(b!= QString("\n").toAscii()&&fl<2) { if(task->isCanceled()) { return; } b = buf.readLine(); if(b.indexOf("Description\n")!=-1) fl++; if(b.indexOf("
")!=-1) { parseHit(b,buf); } } connectionError = false; } void HttpRequestCDD::parseHit(QByteArray &b,ResponseBuffer &buf) { SharedAnnotationData ad(new AnnotationData()); QString str(b); str = str.split("
").last(); str = str.split("
")[0]; ad->qualifiers.push_back(U2Qualifier("Description",str.split(",").last())); b = buf.readLine(); ad->qualifiers.push_back(U2Qualifier("PssmId",extractText(b))); b = buf.readLine(); ad->qualifiers.push_back(U2Qualifier("MultiDom",extractText(b))); b = buf.readLine(); ad->qualifiers.push_back(U2Qualifier("E-Value",extractText(b))); buf.readLine(); buf.readLine(); b = buf.readLine(); int ind = b.indexOf("Cd Length: ") + 23; QByteArray t; for(int i = ind;b[i]!='&';i++) t[i-ind] = b[i]; ad->qualifiers.push_back(U2Qualifier("cd_length",QString(t))); ind = b.indexOf("Bit Score: ") + 15; for(int i = ind;b[i]!='&';i++) t[i-ind] = b[i]; ad->qualifiers.push_back(U2Qualifier("bit_score",QString(t))); int begLoc = 1000000; int endLoc = 0; QString id; while(!b.contains("")) { while(!b.contains("lcl|") && !b.contains("")) { b = buf.readLine(); } if(b.contains("")) { break; } int from,to; if(!getLocations(b,from,to)) { connectionError = true; error = QObject::tr("Cannot evaluate the location"); return; } if(from < begLoc) { begLoc = from; } endLoc = to; b = buf.readLine(); //b = buf.readLine(); ind = b.indexOf("Cdd:") + 4; for(int i = ind;b[i]!='<' && i < b.length();i++) { t[i-ind] = b[i]; } id = QString(t); } ad->location->regions << U2Region( begLoc-1, endLoc - begLoc + 1); ad->qualifiers.push_back(U2Qualifier("id",QString(t))); ad->name = "CDD result"; result.append(ad); } QString HttpRequestCDD::extractText(const QByteArray &b) { QString str(b); str = str.split("").last(); return str; } bool HttpRequestCDD::getLocations(QByteArray &b,int &from, int &to) { QString str(b); QStringList L = str.split(""); bool isOk; from = L[0].split(">").last().toInt(&isOk); if(!isOk) { return false; } to = L[L.count()-2].split(">").last().toInt(&isOk); if(!isOk) { return false; } if(from < 0 && to < 0) { from *= -1; to *= -1; } return true; } } ugene-1.9.8/src/plugins/remote_blast/src/SendSelectionDialog.cpp0000644000175000017500000003515011651544324023425 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include #include #include #include #include "SendSelectionDialog.h" namespace U2 { #define SETTINGS_ROOT QString("remote_blast_plugin/") #define SHORT_SETTINGS QString("short") #define EXPECT_SETTINGS QString("espect_value") #define HITS_SETTINGS QString("max_hits") #define LOW_COMPLEX_SETTINGS QString("low_complexity_filter") #define REPEATS_SETTINGS QString("human_repeats_filter") #define LOOKUP_SETTINGS QString("lookup_mask") #define LOWCASE_SETTINGS QString("lowcase_mask") #define RETRY_SETTINGS QString("retry") #define FILTER_SETTINGS QString("filter") void SendSelectionDialog::setUpSettings() { Settings *s = AppContext::getSettings(); shortSequenceCheckBox->setChecked(s->getValue(SETTINGS_ROOT + SHORT_SETTINGS, false).toBool()); evalueSpinBox->setValue(s->getValue(SETTINGS_ROOT + EXPECT_SETTINGS, 10).toDouble()); quantitySpinBox->setValue(s->getValue(SETTINGS_ROOT + HITS_SETTINGS, 20).toInt()); lowComplexityFilterCheckBox->setChecked(s->getValue(SETTINGS_ROOT + LOW_COMPLEX_SETTINGS, true).toBool()); repeatsCheckBox->setChecked(s->getValue(SETTINGS_ROOT + REPEATS_SETTINGS, false).toBool()); lookupMaskCheckBox->setChecked(s->getValue(SETTINGS_ROOT + LOOKUP_SETTINGS, false).toBool()); lowerCaseCheckBox->setChecked(s->getValue(SETTINGS_ROOT + LOWCASE_SETTINGS, false).toBool()); retrySpinBox->setValue(s->getValue(SETTINGS_ROOT + RETRY_SETTINGS, 2).toInt()); evalueRadioButton->setChecked(s->getValue(SETTINGS_ROOT + FILTER_SETTINGS, true).toBool()); scoreRadioButton->setChecked(!s->getValue(SETTINGS_ROOT + FILTER_SETTINGS, true).toBool()); } void SendSelectionDialog::saveSettings() { Settings *s = AppContext::getSettings(); s->setValue(SETTINGS_ROOT + SHORT_SETTINGS, shortSequenceCheckBox->isChecked()); s->setValue(SETTINGS_ROOT + EXPECT_SETTINGS, evalueSpinBox->value()); s->setValue(SETTINGS_ROOT + HITS_SETTINGS, quantitySpinBox->value()); s->setValue(SETTINGS_ROOT + LOW_COMPLEX_SETTINGS, lowComplexityFilterCheckBox->isChecked()); s->setValue(SETTINGS_ROOT + REPEATS_SETTINGS, repeatsCheckBox->isChecked()); s->setValue(SETTINGS_ROOT + LOOKUP_SETTINGS, lookupMaskCheckBox->isChecked()); s->setValue(SETTINGS_ROOT + LOWCASE_SETTINGS, lowerCaseCheckBox->isChecked()); s->setValue(SETTINGS_ROOT + RETRY_SETTINGS, retrySpinBox->value()); s->setValue(SETTINGS_ROOT + FILTER_SETTINGS, evalueRadioButton->isChecked()); } void SendSelectionDialog::alignComboBoxes() { int count = dataBase->count(); dataBase->setEditable(true); dataBase->lineEdit()->setReadOnly(true); dataBase->lineEdit()->setAlignment(Qt::AlignRight); for(int i = 0; i < count; i++) { dataBase->setItemData(i,Qt::AlignRight, Qt::TextAlignmentRole); } count = wordSizeComboBox->count(); wordSizeComboBox->setEditable(true); wordSizeComboBox->lineEdit()->setReadOnly(true); wordSizeComboBox->lineEdit()->setAlignment(Qt::AlignRight); for(int i = 0; i < count; i++) { wordSizeComboBox->setItemData(i,Qt::AlignRight, Qt::TextAlignmentRole); } count = scoresComboBox->count(); scoresComboBox->setEditable(true); scoresComboBox->lineEdit()->setReadOnly(true); scoresComboBox->lineEdit()->setAlignment(Qt::AlignRight); for(int i = 0; i < count; i++) { scoresComboBox->setItemData(i,Qt::AlignRight, Qt::TextAlignmentRole); } count = costsComboBox->count(); costsComboBox->setEditable(true); costsComboBox->lineEdit()->setReadOnly(true); costsComboBox->lineEdit()->setAlignment(Qt::AlignRight); for(int i = 0; i < count; i++) { costsComboBox->setItemData(i,Qt::AlignRight, Qt::TextAlignmentRole); } count = matrixComboBox->count(); matrixComboBox->setEditable(true); matrixComboBox->lineEdit()->setReadOnly(true); matrixComboBox->lineEdit()->setAlignment(Qt::AlignRight); for(int i = 0; i < count; i++) { matrixComboBox->setItemData(i,Qt::AlignRight, Qt::TextAlignmentRole); } count = serviceComboBox->count(); serviceComboBox->setEditable(true); serviceComboBox->lineEdit()->setReadOnly(true); serviceComboBox->lineEdit()->setAlignment(Qt::AlignRight); for(int i = 0; i < count; i++) { serviceComboBox->setItemData(i,Qt::AlignRight, Qt::TextAlignmentRole); } } SendSelectionDialog::SendSelectionDialog(const DNASequenceObject* dnaso, bool _isAminoSeq, QWidget *p):QDialog(p), translateToAmino(false), isAminoSeq(_isAminoSeq), extImported(false) { CreateAnnotationModel ca_m; ca_m.data->name = "misc_feature"; ca_m.hideAnnotationName = true; ca_m.hideLocation = true; ca_m.sequenceObjectRef = GObjectReference(dnaso); ca_m.sequenceLen = dnaso->getSequenceLen(); ca_c = new CreateAnnotationWidgetController(ca_m, this); setupUi(this); int idx = 2; QWidget *wdgt; wdgt = ca_c->getWidget(); wdgt->setMinimumHeight(150); verticalLayout_4->insertWidget(idx, wdgt); matrixComboBox->addItems(ParametersLists::blastp_matrix); matrixComboBox->hide(); label_10->hide(); label_12->hide(); phiPatternEdit->hide(); label_7->hide(); textEdit->setMaximumHeight(100); setupDataBaseList(); setUpSettings(); megablastCheckBox->setEnabled(false); alignComboBoxes(); connect( dataBase, SIGNAL(currentIndexChanged(int)), SLOT(sl_scriptSelected(int)) ); connect( okButton, SIGNAL(clicked()), SLOT(sl_OK()) ); connect( cancelButton, SIGNAL(clicked()), SLOT(sl_Cancel()) ); connect( megablastCheckBox, SIGNAL(stateChanged(int)),SLOT(sl_megablastChecked(int)) ); connect( serviceComboBox,SIGNAL(currentIndexChanged(int)),SLOT(sl_serviceChanged(int)) ); sl_scriptSelected( 0 ); } void SendSelectionDialog::sl_serviceChanged(int) { if(serviceComboBox->currentText()=="phi") { label_12->show(); phiPatternEdit->show(); } else { label_12->hide(); phiPatternEdit->hide(); } } void SendSelectionDialog::sl_megablastChecked(int state) { if(state==Qt::Checked) { wordSizeComboBox->clear(); wordSizeComboBox->addItems(ParametersLists::megablast_wordSize); wordSizeComboBox->setCurrentIndex(3); } else { wordSizeComboBox->clear(); wordSizeComboBox->addItems(ParametersLists::blastn_wordSize); } } QString SendSelectionDialog::getGroupName() const { return ca_c->getModel().groupName; } const CreateAnnotationModel *SendSelectionDialog::getModel() const { return &(ca_c->getModel()); } AnnotationTableObject* SendSelectionDialog::getAnnotationObject() const { if(ca_c->isNewObject()) { AnnotationTableObject* aobj = new AnnotationTableObject("Annotations"); aobj->addObjectRelation(GObjectRelation(ca_c->getModel().sequenceObjectRef, GObjectRelationRole::SEQUENCE)); return aobj; } else { ca_c->prepareAnnotationObject(); return ca_c->getModel().getAnnotationObject(); } } QString SendSelectionDialog::getUrl() const{ return ca_c->getModel().newDocUrl; } void SendSelectionDialog::setupDataBaseList() { //cannot analyze amino sequences using nucleotide databases if( isAminoSeq ) { dataBase->removeItem(0); } } void SendSelectionDialog::sl_scriptSelected( int index ) { Q_UNUSED(index); //this->adjustSize(); QString descr = ""; if(dataBase->currentText()=="cdd") { optionsTab->setTabEnabled(1,0); descr.append(CDD_DESCRIPTION); shortSequenceCheckBox->setEnabled(false); megablastCheckBox->setEnabled(false); matrixComboBox->hide(); label_10->hide(); dbComboBox->clear(); dbComboBox->addItems(ParametersLists::cdd_dataBase); } else { optionsTab->setTabEnabled(1,1); descr.append(BLAST_DESCRIPTION); shortSequenceCheckBox->setEnabled(true); megablastCheckBox->setEnabled(true); if(dataBase->currentText()=="blastn") { phiPatternEdit->hide(); label_12->hide(); megablastCheckBox->setEnabled(true); wordSizeComboBox->clear(); wordSizeComboBox->addItems(ParametersLists::blastn_wordSize); wordSizeComboBox->setCurrentIndex(1); costsComboBox->clear(); costsComboBox->addItems(ParametersLists::blastn_gapCost); costsComboBox->setCurrentIndex(4); scoresComboBox->clear(); scoresComboBox->addItems(ParametersLists::blastn_scores); scoresComboBox->setCurrentIndex(3); scoresComboBox->show(); label_5->show(); dbComboBox->clear(); dbComboBox->addItems(ParametersLists::blastn_dataBase); dbComboBox->setCurrentIndex(2); matrixComboBox->hide(); label_10->hide(); serviceComboBox->hide(); label_7->hide(); } else { megablastCheckBox->setEnabled(false); wordSizeComboBox->clear(); wordSizeComboBox->addItems(ParametersLists::blastp_wordSize); wordSizeComboBox->setCurrentIndex(1); costsComboBox->clear(); costsComboBox->addItems(ParametersLists::blastp_gapCost); costsComboBox->setCurrentIndex(4); dbComboBox->clear(); dbComboBox->addItems(ParametersLists::blastp_dataBase); matrixComboBox->show(); matrixComboBox->setCurrentIndex(3); label_10->show(); scoresComboBox->hide(); label_5->hide(); serviceComboBox->show(); label_7->show(); } } textEdit->setPlainText(descr); alignComboBoxes(); } void SendSelectionDialog::sl_OK() { QString error = ca_c->validate(); if (!error.isEmpty()) { QMessageBox::critical(NULL, tr("Error"), error); return; } retries = retrySpinBox->value(); db = dataBase->currentText(); if(db!="cdd") { requestParameters = "CMD=Put"; addParametr(requestParameters,ReqParams::program,db); double eValue = evalueSpinBox->value(); if(shortSequenceCheckBox->isChecked()) eValue = 1000; addParametr(requestParameters,ReqParams::expect,eValue); int maxHit = quantitySpinBox->value(); addParametr(requestParameters,ReqParams::hits,maxHit); if(megablastCheckBox->isChecked()) { addParametr(requestParameters,ReqParams::megablast,"yes"); } addParametr(requestParameters,ReqParams::database,dbComboBox->currentText().split(" ").last()); QString filter=""; if(lowComplexityFilterCheckBox->isChecked()&&!shortSequenceCheckBox->isChecked()) { filter.append("L"); } if(repeatsCheckBox->isChecked()) { filter.append("R"); } if(lookupMaskCheckBox->isChecked()) { filter.append("m"); } if(!filter.isEmpty()) { addParametr(requestParameters,ReqParams::filter,filter); } addParametr(requestParameters,ReqParams::gapCost,costsComboBox->currentText()); addParametr(requestParameters,ReqParams::matchScore,scoresComboBox->currentText().split(" ").first()); addParametr(requestParameters,ReqParams::mismatchScore,scoresComboBox->currentText().split(" ").last()); if(shortSequenceCheckBox->isChecked()) { QString wordSize = wordSizeComboBox->currentText().toInt()>7 ? "7" : wordSizeComboBox->currentText(); addParametr(requestParameters,ReqParams::wordSize, wordSize); } else { addParametr(requestParameters,ReqParams::wordSize,wordSizeComboBox->currentText()); } if(lowerCaseCheckBox->isChecked()) { addParametr(requestParameters,ReqParams::lowCaseMask,"yes"); } if(db=="blastp") { if(!isAminoSeq) { translateToAmino = true; } addParametr(requestParameters,ReqParams::matrix,matrixComboBox->currentText()); addParametr(requestParameters,ReqParams::service,serviceComboBox->currentText()); if(serviceComboBox->currentText()=="phi") { addParametr(requestParameters,ReqParams::phiPattern,phiPatternEdit->text()); } } } else { //CDD if(!isAminoSeq) { translateToAmino = true; } requestParameters = "filter=true"; addParametr(requestParameters,ReqParams::cdd_db,dbComboBox->currentText()); addParametr(requestParameters,ReqParams::cdd_hits,quantitySpinBox->value()); addParametr(requestParameters,ReqParams::cdd_eValue,evalueSpinBox->value()); } if(translateToAmino) { QMessageBox msg(this); msg.setText(tr("You chose to search nucleotide sequence in protein database. This sequence will be converted into 6 sequences(3 translations for both strands)." "Therefore this search may take some time. Continue?")); msg.setWindowTitle(windowTitle()); msg.setStandardButtons(QMessageBox::Yes | QMessageBox::Cancel); msg.setDefaultButton(QMessageBox::Yes); if(msg.exec() == QMessageBox::Cancel) { return; } } int filterResults = 0; filterResults |= (int)accessionCheckBox->isChecked(); filterResults |= (int)defCheckBox->isChecked() << 1; filterResults |= (int)idCheckBox->isChecked() << 2; cfg.filterResult = filterResults; cfg.useEval = evalueRadioButton->isChecked(); cfg.retries = retrySpinBox->value(); cfg.params = requestParameters; cfg.dbChoosen = db; saveSettings(); accept(); } void SendSelectionDialog::sl_Cancel() { reject(); } } ugene-1.9.8/src/plugins/remote_blast/src/RemoteBLASTTask.cpp0000644000175000017500000002663411651544324022421 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "RemoteBLASTTask.h" #include #include #include #include #include #include namespace U2 { class BaseIOAdapters; class BaseDocumentFormats; RemoteBLASTToAnnotationsTask::RemoteBLASTToAnnotationsTask( const RemoteBLASTTaskSettings & _cfg, int _qoffs, AnnotationTableObject* _ao, const QString &_url,const QString & _group): Task( tr("RemoteBLASTTask"), TaskFlags_NR_FOSCOE ), offsInGlobalSeq(_qoffs), aobj(_ao), group(_group), url(_url) { GCOUNTER( cvar, tvar, "RemoteBLASTToAnnotationsTask" ); queryTask = new RemoteBLASTTask(_cfg); addSubTask(queryTask); } QList RemoteBLASTToAnnotationsTask::onSubTaskFinished(Task* subTask) { QList res; if(subTask->hasError() && subTask == queryTask) { stateInfo.setError(subTask->getError()); return res; } if (hasError() || isCanceled()) { return res; } if (aobj.isNull()) { stateInfo.setError( tr("The object was removed\n") ); return res; } if (subTask == queryTask) { //shift annotations according to offset first RemoteBLASTTask * rrTask = qobject_cast(queryTask); assert( rrTask ); QList anns = rrTask->getResultedAnnotations(); if(!anns.isEmpty()) { // Document* d = AppContext::getProject()->findDocumentByURL(url); //assert(d==NULL); if(!url.isEmpty()) { Document *d = AppContext::getProject()->findDocumentByURL(url); if(d==NULL) { IOAdapterFactory* iof = AppContext::getIOAdapterRegistry()->getIOAdapterFactoryById(BaseIOAdapters::LOCAL_FILE); DocumentFormat* df = AppContext::getDocumentFormatRegistry()->getFormatById(BaseDocumentFormats::PLAIN_GENBANK); d = df->createNewDocument(iof, url); d->addObject(aobj); AppContext::getProject()->addDocument(d); } else { setError(tr("File %1 already exists").arg(url)); return res; } } for(QMutableListIterator it_ad(anns); it_ad.hasNext(); ) { AnnotationData * ad = it_ad.next().data(); U2Region::shift(offsInGlobalSeq, ad->location->regions); } res.append(new CreateAnnotationsTask(aobj, group, anns)); } } return res; } RemoteBLASTTask::RemoteBLASTTask( const RemoteBLASTTaskSettings & cfg_) : Task( tr("RemoteBLASTTask"), TaskFlag_None ), timeout(true), cfg(cfg_) { } void RemoteBLASTTask::prepareQueries() { Query q; if(cfg.aminoT) { q.amino = true; QByteArray complQuery( cfg.query.size(), 0 ); cfg.complT->translate( cfg.query.data(), cfg.query.size(), complQuery.data(), complQuery.size() ); TextUtils::reverse( complQuery.data(), complQuery.size() ); for( int i = 0; i < 3; ++i ) { QByteArray aminoQuery( cfg.query.size() / 3, 0 ); cfg.aminoT->translate( cfg.query.data()+i, cfg.query.size()-i, aminoQuery.data(), aminoQuery.size() ); q.seq = aminoQuery; q.offs = i; q.complement = false; queries.push_back(q); QByteArray aminoQueryCompl( cfg.query.size() / 3, 0 ); cfg.aminoT->translate(complQuery.data()+i, complQuery.size()-i, aminoQueryCompl.data(), aminoQueryCompl.size()); q.seq = aminoQueryCompl; q.offs = i; q.complement = true; queries.push_back(q); } } else { q.seq = cfg.query; queries.push_back(q); } } void RemoteBLASTTask::prepare() { prepareQueries(); algoLog.trace("Sequences prepared"); for (QList::iterator it = queries.begin(),end = queries.end();it!=end;it++) { DataBaseFactory *dbf = AppContext::getDataBaseRegistry()->getFactoryById(cfg.dbChoosen); if(dbf == NULL) { stateInfo.setError(tr("Incorrect database")); return; } HttpRequest *tmp = dbf->getRequest(this); httpRequest.append(tmp); } algoLog.trace("Requests formed"); connect(&timer,SIGNAL(timeout()),SLOT(sl_timeout())); timeout = true; timer.setSingleShot(true); int mult = cfg.aminoT ? 6 : 1; //if 6 requests - 6 times more wait timer.start(cfg.retries*1000*60*mult); } void RemoteBLASTTask::run() { for( int i = 0;i < queries.count();i++ ) { bool error = true; if( isCanceled() ) { return; } httpRequest[i]->sendRequest(cfg.params,QString(queries[i].seq.data())); error = httpRequest[i]->connectionError; if(error) { stateInfo.setError(httpRequest[i]->getError()); return; } createAnnotations(queries[i],httpRequest[i]); } } QList RemoteBLASTTask::getResultedAnnotations() const { return resultAnnotations; } void RemoteBLASTTask::createAnnotations(const Query &q, HttpRequest *t) { QList annotations = t->getAnnotations(); if(annotations.isEmpty()) return; if(cfg.filterResult) { annotations = filterAnnotations(annotations); } for (int i = 0; i < annotations.size(); i++) { SharedAnnotationData & d = annotations[i]; for( QVector::iterator jt = d->location->regions.begin(), eend = d->location->regions.end(); eend != jt; ++jt ) { qint64& s = jt->startPos; qint64& l = jt->length; if( q.complement ) { s = q.seq.size() - s - l; d->setStrand(d->getStrand().isCompementary() ? U2Strand::Direct : U2Strand::Complementary); } if( q.amino ) { s = s * 3 + (q.complement ? 2 - q.offs : q.offs); l = l * 3; } } } resultAnnotations << annotations; } QList RemoteBLASTTask::filterAnnotations(QList annotations) { QString selectiveQual = cfg.useEval ? "e-value" : "score"; QList resultList; if(cfg.filterResult & FilterResultByAccession) { QStringList accessions; foreach(const SharedAnnotationData &ann, annotations) { QString acc = ann->findFirstQualifierValue("accession"); if(accessions.contains(acc)) { QString eval = ann->findFirstQualifierValue(selectiveQual); foreach(const SharedAnnotationData &a, resultList) { if(a->findFirstQualifierValue("accession") == acc) { if(cfg.useEval ? a->findFirstQualifierValue(selectiveQual).toDouble() < eval.toDouble() : a->findFirstQualifierValue(selectiveQual).toDouble() > eval.toDouble()) { resultList.removeOne(a); resultList << ann; } break; } } } else { resultList << ann; accessions << acc; } } annotations = resultList; } if(cfg.filterResult & FilterResultByDef) { resultList.clear(); QStringList defs; foreach(const SharedAnnotationData &ann, annotations) { QString def = ann->findFirstQualifierValue("def"); if(defs.contains(def)) { QString eval = ann->findFirstQualifierValue(selectiveQual); foreach(const SharedAnnotationData &a, resultList) { if(a->findFirstQualifierValue("def") == def) { if(cfg.useEval ? a->findFirstQualifierValue(selectiveQual).toDouble() < eval.toDouble() : a->findFirstQualifierValue(selectiveQual).toDouble() > eval.toDouble()) { resultList.removeOne(a); resultList << ann; } break; } } } else { resultList << ann; defs << def; } } annotations = resultList; } if(cfg.filterResult & FilterResultById) { resultList.clear(); QStringList ids; foreach(const SharedAnnotationData &ann, annotations) { QString id = ann->findFirstQualifierValue("id"); if(ids.contains(id)) { QString eval = ann->findFirstQualifierValue(selectiveQual); foreach(const SharedAnnotationData &a, resultList) { if(a->findFirstQualifierValue("id") == id) { if(cfg.useEval ? a->findFirstQualifierValue(selectiveQual).toDouble() < eval.toDouble() : a->findFirstQualifierValue(selectiveQual).toDouble() > eval.toDouble()) { resultList.removeOne(a); resultList << ann; } break; } } } else { resultList << ann; ids << id; } } } return resultList; } RemoteCDSearch::RemoteCDSearch(const CDSearchSettings& settings) { RemoteBLASTTaskSettings cfg; cfg.dbChoosen = "cdd"; addParametr(cfg.params, ReqParams::cdd_hits, 500); addParametr(cfg.params, ReqParams::cdd_eValue, settings.ev); if (settings.dbName == CDDNames::CDD_DB()) { addParametr(cfg.params, ReqParams::cdd_db, "CDD"); } else if (settings.dbName == CDDNames::PFAM_DB()) { addParametr(cfg.params, ReqParams::cdd_db, "oasis_pfam"); } else if (settings.dbName == CDDNames::SMART_DB()) { addParametr(cfg.params, ReqParams::cdd_db, "oasis_smart"); } else if (settings.dbName == CDDNames::COG_DB()) { addParametr(cfg.params, ReqParams::cdd_db, "oasis_cog"); } else if (settings.dbName == CDDNames::KOG_DB()) { addParametr(cfg.params, ReqParams::cdd_db, "oasis_kog"); } else if (settings.dbName == CDDNames::PRK_DB()) { addParametr(cfg.params, ReqParams::cdd_db, "oasis_prk"); } else if (settings.dbName == CDDNames::TIGR_DB()) { addParametr(cfg.params, ReqParams::cdd_db, "oasis_tigr"); } else { assert(0); } cfg.query = settings.query; cfg.retries = 60; cfg.filterResult = 0; task = new RemoteBLASTTask(cfg); } } ugene-1.9.8/src/plugins/remote_blast/src/RemoteBLASTPlugin.h0000644000175000017500000000331211651544324022406 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_REMOTE_QUERY_PLUGIN_H_ #define _U2_REMOTE_QUERY_PLUGIN_H_ #include #include #include #include "RemoteBLASTPluginTests.h" #include "SendSelectionDialog.h" #include "RemoteBLASTTask.h" #include "RemoteBLASTWorker.h" #include "DBRequestFactory.h" namespace U2 { class XMLTestFactory; class RemoteBLASTViewContext; class RemoteBLASTPlugin : public Plugin { Q_OBJECT public: RemoteBLASTPlugin(); private: RemoteBLASTViewContext * ctx; }; class RemoteBLASTViewContext : public GObjectViewWindowContext { Q_OBJECT public: RemoteBLASTViewContext(QObject * p); protected: virtual void initViewContext( GObjectView* view ); private slots: void sl_showDialog(); }; class RemoteBLASTPluginTests { public: static QList createTestFactories(); }; } #endif ugene-1.9.8/src/plugins/remote_blast/src/ui/0000755000175000017500000000000011651544324017453 5ustar ilyailyaugene-1.9.8/src/plugins/remote_blast/src/ui/RemoteBLASTDialog.ui0000644000175000017500000005473711651544324023173 0ustar ilyailya Dialog 0 0 555 492 Search through a remote database false false false 0 General options Select the search type: blastn blastp cdd Search for short, nearly exact matches Expectation value Megablast Max hits Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter 1000 10 20 Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter 6 0.000001000000000 100000.000000000000000 10.000000000000000 The database: 2 Human genomic plus transcript - est_human Mouse genomic plus transcript - est_mouse Nucleotide collection - nr Reference nRNA sequences - refseq_rna Reference genomic seqence - refseq_genomic NCBI genomes - chromosome Express sequence tags - est Non-human, non-mouse ESTs - est_other Genomic survey sequences - gss High throughput genomic sequences - HTGS Patent sequences - pat Protein data bank - pdb Human ALU repeat elements - alu_repeats Sequence tagged sites - dbsts Whole-genome shotgun reads - wgs Environmental samples - env_nt The database description: true <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> <html><head><meta name="qrichtext" content="1" /><style type="text/css"> p, li { white-space: pre-wrap; } </style></head><body style=" font-family:'Sans Serif'; font-size:9pt; font-weight:400; font-style:normal;"> <p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'MS Shell Dlg 2'; font-size:8pt;"></p></body></html> Qt::Horizontal 40 20 Search timeout 0 0 Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter min 1 6000 1 2 Advanced options 0 0 Word size 2 0 0 3 7 11 15 Gap costs 2 0 0 11 1 5 2 4 2 1 2 0 2 3 1 2 1 1 1 0 0 Match scores 0 1 -2 1 -3 1 -4 2 -3 4 -5 1 -1 0 0 Matrix Service plain psi phi PHI pattern Qt::Horizontal 40 20 Qt::Horizontal 40 20 Filters Low complexity filter Human repeats filter Masks Mask for lookup table only Mask lower case letters Filter results Filter by accession def (filter by definition of annotations) id Select result by EValue true Score Qt::Vertical 20 40 Qt::Vertical 39 13 Qt::Vertical 20 40 Qt::Horizontal 138 20 Search Cancel ugene-1.9.8/src/plugins/remote_blast/src/RemoteBLASTPluginTests.h0000644000175000017500000000275711651544324023445 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_REMOTE_QUERY_PLUGIN_TEST_H_ #define _U2_REMOTE_QUERY_PLUGIN_TEST_H_ #include #include "RemoteBLASTTask.h" namespace U2 { //cppcheck-suppress noConstructor class GTest_RemoteBLAST : public GTest { Q_OBJECT public: SIMPLE_XML_TEST_BODY_WITH_FACTORY(GTest_RemoteBLAST, "plugin_remote-query"); void prepare(); void cleanup(); Task::ReportResult report(); private: AnnotationTableObject *ao; RemoteBLASTToAnnotationsTask *task; int minLength; int maxLength; QString index; QString sequence; QString request; QString algoritm; QStringList expectedResults; }; }//ns #endif ugene-1.9.8/src/plugins/remote_blast/src/BlastQuery.h0000644000175000017500000000352411651544324021306 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_BLAST_QUERY_H_ #define _U2_BLAST_QUERY_H_ #include "RemoteBLASTTask.h" #include "RemoteBLASTConsts.h" #include #include namespace U2 { class QDCDDActor : public QDActor { Q_OBJECT public: QDCDDActor(QDActorPrototype const* a); int getMinResultLen() const; int getMaxResultLen() const; QString getText() const; Task* getAlgorithmTask(const QVector& location); QColor defaultColor() const { return QColor(0x6A, 0x94, 0xd4); } virtual bool hasStrand() const { return false; } private slots: void sl_onAlgorithmTaskFinished(); private: RemoteBLASTTaskSettings settings; QMap offsetMap; }; class QDCDDActorPrototype : public QDActorPrototype { public: QDCDDActorPrototype(); virtual QDActor* createInstance() const { return new QDCDDActor(this); } virtual QIcon getIcon() const { return QIcon(":remote_blast/images/remote_db_request.png"); } }; }//namespace #endif ugene-1.9.8/src/plugins/remote_blast/src/SendSelectionDialog.h0000644000175000017500000000417511651544324023075 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _SEND_SELECTION_DIALOG_H_ #define _SEND_SELECTION_DIALOG_H_ #include "ui/ui_RemoteBLASTDialog.h" #include #include #include #include "RemoteBLASTTask.h" #include "RemoteBLASTConsts.h" namespace U2 { class CreateAnnotationWidgetController; class AnnotationTableObject; class SendSelectionDialog: public QDialog, Ui_Dialog { Q_OBJECT public: SendSelectionDialog( const DNASequenceObject* dnaso, bool _isAminoSeq, QWidget *p = NULL ); QString getGroupName() const; AnnotationTableObject* getAnnotationObject() const; const CreateAnnotationModel *getModel() const; QString getUrl() const; private slots: void sl_scriptSelected( int index ); void sl_megablastChecked(int state); void sl_serviceChanged(int); void sl_OK(); void sl_Cancel(); private: void setupDataBaseList(); void setupAlphabet(); void setUpSettings(); void saveSettings(); void alignComboBoxes(); public: int retries; QString db; QString requestParameters; bool translateToAmino; int filterResults; bool useEval; RemoteBLASTTaskSettings cfg; private: bool isAminoSeq; CreateAnnotationWidgetController * ca_c; bool extImported; }; } #endif ugene-1.9.8/src/plugins/remote_blast/src/RemoteBLASTPlugin.cpp0000644000175000017500000001224411651544324022745 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "RemoteBLASTPlugin.h" #include "BlastQuery.h" #include "RemoteBLASTTask.h" #include namespace U2 { extern "C" Q_DECL_EXPORT Plugin * U2_PLUGIN_INIT_FUNC() { RemoteBLASTPlugin * plug = new RemoteBLASTPlugin(); return plug; } RemoteBLASTPlugin::RemoteBLASTPlugin():Plugin(tr("Remote BLAST"),tr("Performs remote database queries: BLAST, CDD, etc...")), ctx(NULL) { if(AppContext::getMainWindow()) { ctx = new RemoteBLASTViewContext(this); ctx->init(); } DataBaseRegistry *reg = AppContext::getDataBaseRegistry(); reg->registerDataBase(new BLASTFactory(),"blastn"); reg->registerDataBase(new BLASTFactory(),"blastp"); reg->registerDataBase(new CDDFactory(),"cdd"); LocalWorkflow::RemoteBLASTWorkerFactory::init(); QDActorPrototypeRegistry* qdpr = AppContext::getQDActorProtoRegistry(); qdpr->registerProto(new QDCDDActorPrototype()); AppContext::getCDSFactoryRegistry()->registerFactory(new RemoteCDSearchFactory(), CDSearchFactoryRegistry::RemoteSearch); GTestFormatRegistry *tfr = AppContext::getTestFramework()->getTestFormatRegistry(); XMLTestFormat *xmlTestFormat = qobject_cast(tfr->findFormat("XML")); assert(xmlTestFormat!=NULL); GAutoDeleteList *l = new GAutoDeleteList(this); l->qlist = RemoteBLASTPluginTests::createTestFactories(); foreach(XMLTestFactory *f,l->qlist) { bool res = xmlTestFormat->registerTestFactory(f); Q_UNUSED(res); assert(res); } } RemoteBLASTViewContext::RemoteBLASTViewContext(QObject *p):GObjectViewWindowContext(p,ANNOTATED_DNA_VIEW_FACTORY_ID) { } void RemoteBLASTViewContext::initViewContext(GObjectView * view) { AnnotatedDNAView* av = qobject_cast(view); ADVGlobalAction * a = new ADVGlobalAction(av, QIcon(":/remote_blast/images/remote_db_request.png"), tr("Query NCBI BLAST database..."), 60); connect( a, SIGNAL(triggered()), SLOT(sl_showDialog()) ); } void RemoteBLASTViewContext::sl_showDialog() { QAction* a = (QAction*)sender(); GObjectViewAction* viewAction = qobject_cast(a); AnnotatedDNAView* av = qobject_cast(viewAction->getObjectView()); assert(av); ADVSequenceObjectContext* seqCtx = av->getSequenceInFocus(); bool isAminoSeq = seqCtx->getAlphabet()->isAmino(); SendSelectionDialog dlg( seqCtx->getSequenceObject(), isAminoSeq, av->getWidget() ); if( QDialog::Accepted == dlg.exec() ) { //prepare query const QByteArray& sequence = seqCtx->getSequenceData(); DNASequenceSelection* s = seqCtx->getSequenceSelection(); QVector regions; if(s->isEmpty()) { int seqLen = seqCtx->getSequenceLen(); regions.append(U2Region(0, seqLen)); } else { regions = s->getSelectedRegions(); } foreach(const U2Region& r, regions) { QByteArray query( sequence.constData() + r.startPos, r.length ); DNATranslation * aminoT = (dlg.translateToAmino ? seqCtx->getAminoTT() : 0); DNATranslation * complT = (dlg.translateToAmino ? seqCtx->getComplementTT() : 0); RemoteBLASTTaskSettings cfg = dlg.cfg; cfg.query = query; cfg.aminoT = aminoT; cfg.complT = complT; Task * t = new RemoteBLASTToAnnotationsTask(cfg, r.startPos, dlg.getAnnotationObject(), dlg.getUrl(),dlg.getGroupName()); AppContext::getTaskScheduler()->registerTopLevelTask( t ); } } } QList RemoteBLASTPluginTests::createTestFactories() { QList res; res.append(GTest_RemoteBLAST::createFactory()); return res; } } ugene-1.9.8/src/plugins/remote_blast/src/RemoteBLASTConsts.cpp0000644000175000017500000001422711651544324022763 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "RemoteBLASTConsts.h" namespace U2 { const QStringList ParametersLists::blastn_wordSize = QStringList() << "7" << "11" << "15"; const QStringList ParametersLists::blastp_wordSize = QStringList() << "2" << "3"; const QStringList ParametersLists::megablast_wordSize = QStringList() << "16" << "20" << "24" << "28" << "32" << "48" << "64"; const QStringList ParametersLists::blastn_gapCost = QStringList() << "4 4" << "2 4" << "0 4" << "3 3" << "5 2" << "4 2" << "2 2"; const QStringList ParametersLists::blastp_gapCost = QStringList() << "9 2" << "8 2" << "7 2" << "12 1" << "11 1" << "10 1"; const QStringList ParametersLists::blastn_scores = QStringList() << "1 -2" << "1 -3" << "1 -4" << "2 -3" << "4 -5" << "1 -1"; const QStringList ParametersLists::blastp_matrix = QStringList() << "PAM30" << "PAM70" << "BLOSUM80" << "BLOSUM62" << "BLOSUM45"; const QStringList ParametersLists::blastn_dataBase = QStringList() << "Human genomic plus transcript - est_human" << "Mouse genomic plus transcript - est_mouse" << "Nucleotide collection - nr" << "Reference nRNA sequences - refseq_rna" << "Reference genomic seqence - refseq_genomic" << "NCBI genomes - chromosome" << "Express sequence tagsest - est" << "Non-human, non-mouse ESTs - est_other" << "Genomic survey sequences - gss" << "High throughput genomic sequences - HTGS" << "Patent sequences - pat" << "Protein Data Bank - pdb" << "Human ALU repeat elements - alu" << "Sequence tagged sites - dbsts" << "Whole-genome shotgun reads - wgs" << "Environmental samples - env_nt"; const QStringList ParametersLists::blastp_dataBase = QStringList() << "Non-redundant protein sequences - nr" << "Reference proteins - refseq_protein" << "Swissprot protein sequences - swissprot" << "Patented protein sequences - pat" << "Protein Data Bank proteins - pdb" << "Environmental samples - env_nr"; const QStringList ParametersLists::cdd_dataBase = QStringList() << "CDD" << "oasis_pfam" << "oasis_smart" << "oasis_cog" << "oasis_kog" << "oasis_prk" << "oasis_tigr"; const QString ReqParams::program = "PROGRAM"; const QString ReqParams::expect = "EXPECT"; const QString ReqParams::wordSize = "WORD_SIZE"; const QString ReqParams::hits = "HITLIST_SIZE"; const QString ReqParams::database = "DATABASE"; const QString ReqParams::gapCost = "GAPCOSTS"; const QString ReqParams::matchScore = "NUCL_REWARD"; const QString ReqParams::mismatchScore = "NUCL_PENALTY"; const QString ReqParams::matrix = "MATRIX"; const QString ReqParams::filter = "FILTER"; const QString ReqParams::megablast = "MEGABLAST"; const QString ReqParams::lowCaseMask = "LCASE_MASK"; const QString ReqParams::sequence = "QUERY"; const QString ReqParams::service = "SERVICE"; const QString ReqParams::phiPattern = "PHI_PATTERN"; const QString ReqParams::cdd_eValue = "evalue"; const QString ReqParams::cdd_hits = "maxhits"; const QString ReqParams::cdd_sequence = "seqinput"; const QString ReqParams::cdd_db = "db"; void addParametr(QString &requestParameters,const QString ¶mName, const QString ¶m) { requestParameters.append("&"); requestParameters.append(paramName); requestParameters.append("="); requestParameters.append(param); } void addParametr(QString &requestParameters,const QString ¶mName, const double param) { requestParameters.append("&"); requestParameters.append(paramName); requestParameters.append("="); requestParameters.append(QString::number(param)); } void addParametr(QString &requestParameters,const QString ¶mName, const int param) { requestParameters.append("&"); requestParameters.append(paramName); requestParameters.append("="); requestParameters.append(QString::number(param)); } } ugene-1.9.8/src/plugins/remote_blast/src/BlastQuery.cpp0000644000175000017500000001540511651544324021642 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "BlastQuery.h" #include #include #include #include #include #include #include namespace U2 { static const QString UNIT_ID = "CDD"; const QString EXPECT("evalue"); const QString MAX_HITS("max-hits"); const QString MIN_RES_LEN("min-length"); const QString MAX_RES_LEN("max-length"); static const QString QUAL_ATTR = "pattern"; QDCDDActor::QDCDDActor(QDActorPrototype const* proto) : QDActor(proto) { cfg->setAnnotationKey("CDD result"); units[UNIT_ID] = new QDSchemeUnit(this); } int QDCDDActor::getMaxResultLen() const { return cfg->getParameter(MAX_RES_LEN)->getAttributeValue(); } int QDCDDActor::getMinResultLen() const { return cfg->getParameter(MIN_RES_LEN)->getAttributeValue(); } QString QDCDDActor::getText() const { return tr("Searches through the NCBI CDD database for annotations.");; } Task* QDCDDActor::getAlgorithmTask(const QVector& location) { DNASequenceObject* dna = scheme->getDNA(); settings.dbChoosen = "cdd"; settings.params = "db=cdd"; //to do: supply db choice int evalue = cfg->getParameter(EXPECT)->getAttributeValue(); int maxHits = 500;//cfg->getParameter(MAX_HITS)->getAttributeValue(); addParametr(settings.params, ReqParams::cdd_hits, maxHits); addParametr(settings.params, ReqParams::cdd_eValue, evalue); settings.retries = 60; DNAAlphabet* alph = dna->getAlphabet(); settings.complT = GObjectUtils::findComplementTT(dna); settings.aminoT = NULL; if (!alph->isAmino()) { DNATranslationType tt; if (alph->getType() == DNAAlphabet_NUCL) { tt = DNATranslationType_NUCL_2_AMINO; } else { tt = DNATranslationType_RAW_2_AMINO; } QList TTs = AppContext::getDNATranslationRegistry()->lookupTranslation(alph, tt); if (!TTs.isEmpty()) { settings.aminoT = TTs.first(); } else { return new FailTask(tr("Bad sequence.")); } } Task* t = new Task(tr("CDD Search"), TaskFlag_NoRun); foreach(const U2Region& r, location) { RemoteBLASTTaskSettings s(settings); QByteArray query(dna->getSequence().constData() + r.startPos, r.length); s.query = query; RemoteBLASTTask* sub = new RemoteBLASTTask(s); t->addSubTask(sub); offsetMap[sub] = r.startPos; } connect(new TaskSignalMapper(t),SIGNAL(si_taskFinished(Task*)),SLOT(sl_onAlgorithmTaskFinished())); return t; } void QDCDDActor::sl_onAlgorithmTaskFinished() { QList res; QMapIterator iter(offsetMap); while (iter.hasNext()) { iter.next(); RemoteBLASTTask* rqt = iter.key(); QList annotations = rqt->getResultedAnnotations(); //shift by offset int offset = offsetMap.value(rqt); QMutableListIterator annIter(annotations); while (annIter.hasNext()) { QVector& location = annIter.next()->location->regions; U2Region::shift(offset, location); } res << annotations; } offsetMap.clear(); int minLen = cfg->getParameter(MIN_RES_LEN)->getAttributeValue(); int maxLen = cfg->getParameter(MAX_RES_LEN)->getAttributeValue(); const QString& qualVal = cfg->getParameter(QUAL_ATTR)->getAttributeValue(); foreach(const SharedAnnotationData& ad, res) { const U2Region& reg = ad->location->regions.first(); if (reg.length < minLen || reg.length > maxLen) { continue; } foreach(const U2Qualifier& qual, ad->qualifiers) { if (qual.value.contains(qualVal)) { QDResultUnit ru(new QDResultUnitData); ru->strand = ad->getStrand(); ru->quals = ad->qualifiers; ru->region = reg; ru->owner = units.values().first(); QDResultGroup* g = new QDResultGroup(QDStrand_Both); g->add(ru); results.append(g); break; } } } } QDCDDActorPrototype::QDCDDActorPrototype() { descriptor.setId("CDD"); descriptor.setDisplayName(QDCDDActor::tr("CDD")); descriptor.setDocumentation(QDCDDActor::tr("Finds annotations for DNA sequences in a remote database")); Descriptor evalue(EXPECT,QDCDDActor::tr("Expected value"), QDCDDActor::tr("This parameter specifies the statistical significance threshold of reporting matches against the database sequences.")); Descriptor qual(QUAL_ATTR, QDCDDActor::tr("Pattern"), QDCDDActor::tr("Include results containing specified value")); Descriptor minResLen(MIN_RES_LEN, QDCDDActor::tr("Min length"), QDCDDActor::tr("Minimum result length")); Descriptor maxResLen(MAX_RES_LEN, QDCDDActor::tr("Max length"), QDCDDActor::tr("Maximum result length")); attributes << new Attribute(evalue, BaseTypes::STRING_TYPE(), false, 10); attributes << new Attribute(minResLen, BaseTypes::NUM_TYPE(), false, 50); attributes << new Attribute(maxResLen, BaseTypes::NUM_TYPE(), false, 5000); attributes << new Attribute(qual, BaseTypes::STRING_TYPE(), true); QMap delegates; { QVariantMap m; m["1e-100"] = 1e-100; m["1e-10"] = 1e-10; m["1"] = 1; m["10"] = 10; m["100"] = 100; m["1000"] = 1000; delegates[EXPECT] = new ComboBoxDelegate(m); } { QVariantMap lenMap; lenMap["minimum"] = QVariant(0); lenMap["maximum"] = QVariant(INT_MAX); lenMap["suffix"] = L10N::suffixBp(); delegates[MIN_RES_LEN] = new SpinBoxDelegate(lenMap); delegates[MAX_RES_LEN] = new SpinBoxDelegate(lenMap); } editor = new DelegateEditor(delegates); } }//namespace ugene-1.9.8/src/plugins/remote_blast/src/RemoteBLASTPluginTests.cpp0000644000175000017500000001767511651544324024005 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "RemoteBLASTPluginTests.h" #include #include namespace U2 { void GTest_RemoteBLAST::init(XMLTestFormat *tf, const QDomElement& el) { Q_UNUSED(tf); ao = NULL; task = NULL; sequence = el.attribute(SEQUENCE_ATTR); if (sequence.isEmpty()) { failMissingValue(SEQUENCE_ATTR); return; } algoritm = el.attribute(ALG_ATTR); if(algoritm.isEmpty()) { failMissingValue(ALG_ATTR); return; } if(algoritm == "cdd") { QString db = el.attribute(DATABASE_ATTR); if(db.isEmpty()) { failMissingValue(DATABASE_ATTR); return; } request = "db="; request.append(db); QString eValue = el.attribute(EVALUE_ATTR); if(eValue.isEmpty()) { failMissingValue(EVALUE_ATTR); return; } addParametr(request,ReqParams::cdd_eValue,eValue); QString hits = el.attribute(HITS_ATTR); if(hits.isEmpty()) { failMissingValue(HITS_ATTR); return; } addParametr(request,ReqParams::cdd_hits,hits); } else { request = "CMD=Put"; addParametr(request,ReqParams::program,algoritm); QString database = el.attribute(DATABASE_ATTR); if(database.isEmpty()) { failMissingValue(DATABASE_ATTR); return; } addParametr(request,ReqParams::database,database); QString megablast = el.attribute(MEGABLAST_ATTR); if(megablast.isEmpty()) { megablast = "no"; } addParametr(request,ReqParams::megablast,megablast); QString hits = el.attribute(HITS_ATTR); if(hits.isEmpty()) { failMissingValue(HITS_ATTR); return; } addParametr(request,ReqParams::hits,hits); QString eValue = el.attribute(EVALUE_ATTR); if(eValue.isEmpty()) { failMissingValue(EVALUE_ATTR); return; } QString wordSize = el.attribute(WORD_SIZE_ATTR); if(wordSize.isEmpty()) { failMissingValue(WORD_SIZE_ATTR); return; } QString filter = el.attribute(FILTERS_ATTR); bool isOk; int shortSeq = el.attribute(SHORTSEQ_ATTR).toInt(&isOk); if(!isOk) { failMissingValue(SHORTSEQ_ATTR); return; } if(shortSeq == 1) { eValue = "1000"; filter = ""; wordSize = "7"; } addParametr(request,ReqParams::expect,eValue); addParametr(request,ReqParams::wordSize,wordSize); addParametr(request,ReqParams::filter,filter); QString gapCost = el.attribute(GAP_ATTR); if(gapCost.isEmpty()) { failMissingValue(GAP_ATTR); return; } addParametr(request,ReqParams::gapCost,gapCost); QString alph = el.attribute(ALPH_ATTR); if(alph.isEmpty()) { failMissingValue(ALPH_ATTR); return; } if(alph == "nucleo") { QString scores = el.attribute(MATCHSCORE_ATTR); if(scores.isEmpty()) { failMissingValue(MATCHSCORE_ATTR); return; } QString match = scores.split(" ").first(); QString mismatch = scores.split(" ").last(); addParametr(request,ReqParams::matchScore,match); addParametr(request,ReqParams::mismatchScore,mismatch); } else { QString matrix = el.attribute(MATRIX_ATTR); if(matrix.isEmpty()) { failMissingValue(MATRIX_ATTR); return; } addParametr(request,ReqParams::matrix,matrix); QString service = el.attribute(SERVICE_ATTR); if(service.isEmpty()) { service = "plain"; } addParametr(request,ReqParams::service,service); if(service=="phi") { QString phiPattern = el.attribute(PATTERN_ATTR); addParametr(request,ReqParams::phiPattern,phiPattern); } } } bool isOk; maxLength = el.attribute(MAX_LEN_ATTR).toInt(&isOk); if (!isOk) { stateInfo.setError( QString("value not set %1, or unable to convert to integer ").arg(MAX_LEN_ATTR) ); return; } minLength = el.attribute(MIN_LEN_ATTR).toInt(&isOk); if (!isOk) { stateInfo.setError( QString("value not set %1, or unable to convert to integer ").arg(MIN_LEN_ATTR) ); return; } QString expected = el.attribute(EXPECTED_ATTR); if (!expected.isEmpty()) { QStringList expectedList = expected.split(QRegExp("\\,")); foreach(QString id, expectedList) { expectedResults.append(id); } } } void GTest_RemoteBLAST::prepare() { DNAAlphabet *alp = AppContext::getDNAAlphabetRegistry()->findAlphabet(sequence.toAscii()); DNASequenceObject mySequence("seq", DNASequence(sequence.toAscii(), alp)); QByteArray query(sequence.toAscii()); ao = new AnnotationTableObject("aaa"); RemoteBLASTTaskSettings cfg; cfg.dbChoosen = algoritm; cfg.aminoT = NULL; cfg.complT = NULL; cfg.query = query; cfg.retries = 600; cfg.filterResult = 0; cfg.useEval = 0; cfg.params = request; task = new RemoteBLASTToAnnotationsTask(cfg, 0, ao, "",QString("result")); addSubTask(task); } Task::ReportResult GTest_RemoteBLAST::report() { QStringList result; if(task->hasError()) { stateInfo.setError(""); return ReportResult_Finished; } if (ao != NULL){ QList alist(ao->getAnnotations()); foreach(Annotation *an, alist) { foreach(U2Qualifier q, an->getQualifiers()){ QString qual; if(algoritm=="cdd") { qual = "id"; } else { qual = "accession"; } if (q.name == qual) { if(!result.contains(q.value)) //Don't count different hsp result.append(q.value); } } } } if(result.size() != expectedResults.size()){ stateInfo.setError( QString("Expected and Actual sizes of lists of regions are different: %1 %2").arg(expectedResults.size()).arg(result.size()) ); return ReportResult_Finished; } result.sort(); expectedResults.sort(); QStringListIterator e(expectedResults), a(result); for(; e.hasNext();){ QString exp = e.next(), act = a.next(); } if(result != expectedResults) { //stateInfo.setError( QString("Expected and actual id's not equal") ); QString res = ""; foreach(const QString &str, result) { res.append(str); res.append(" "); } stateInfo.setError( QString("Expected and actual id's not equal: %1").arg(res) ); return ReportResult_Finished; } return ReportResult_Finished; } void GTest_RemoteBLAST::cleanup() { if(ao != NULL){ delete ao; ao = NULL; } } } ugene-1.9.8/src/plugins/remote_blast/src/RemoteBLASTConsts.h0000644000175000017500000000717211651544324022431 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _REMOTE_QUERY_CONSTS_ #define _REMOTE_QUERY_CONSTS_ #include namespace U2 { #define MAX_BLAST_SEQ_LEN 3000 #define CDD_DESCRIPTION "CDD (Conserved Domain Database) is a protein annotation resource that consists of a collection of well-annotated multiple sequence alignment models for ancient domains and full-length proteins." #define BLAST_DESCRIPTION "Basic Local Alignment Search Tool, or BLAST, is an algorithm for comparing primary biological sequence information, such as the amino-acid sequences of different proteins or the nucleotides of DNA sequences. A BLAST search enables a researcher to compare a query sequence with a library or database of sequences, and identify library sequences that resemble the query sequence above a certain threshold." #define EXPECTED_ATTR "expected_results" #define MIN_LEN_ATTR "min_length" #define MAX_LEN_ATTR "max_length" #define TRANSL_ATTR "transl" #define DATABASE_ATTR "db" #define EVALUE_ATTR "e-value" #define INDEX_ATTR "index" #define SEQUENCE_ATTR "seq" #define SHORTSEQ_ATTR "short_seq" #define HITS_ATTR "hits" #define ALG_ATTR "alg" #define FILTERS_ATTR "filters" #define GAP_ATTR "gap_costs" #define MATCHSCORE_ATTR "match_scores" #define MATRIX_ATTR "matrix" #define MEGABLAST_ATTR "megablast" #define WORD_SIZE_ATTR "word_size" #define ALPH_ATTR "alph" #define SERVICE_ATTR "service" #define PATTERN_ATTR "phi-pattern" class ParametersLists { public: static const QStringList blastn_wordSize; static const QStringList blastp_wordSize; static const QStringList megablast_wordSize; static const QStringList blastn_gapCost; static const QStringList blastp_gapCost; static const QStringList blastn_scores; static const QStringList blastn_dataBase; static const QStringList blastp_dataBase; static const QStringList cdd_dataBase; static const QStringList blastp_matrix; }; class ReqParams { public: static const QString program; static const QString expect; static const QString wordSize; static const QString hits; static const QString database; static const QString gapCost; static const QString matchScore; static const QString mismatchScore; static const QString matrix; static const QString filter; static const QString megablast; static const QString lowCaseMask; static const QString sequence; static const QString service; static const QString phiPattern; static const QString cdd_eValue; static const QString cdd_hits; static const QString cdd_sequence; static const QString cdd_db; }; void addParametr(QString &str,const QString ¶mName, const QString ¶m); void addParametr(QString &str,const QString ¶mName, const double param); void addParametr(QString &str,const QString ¶mName, const int param); } #endif ugene-1.9.8/src/plugins/remote_blast/src/RemoteBLASTTask.h0000644000175000017500000000756711651544324022072 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_REMOTE_QUERY_TASK_H_ #define _U2_REMOTE_QUERY_TASK_H_ #include #include #include #include #include "HttpRequest.h" namespace U2 { class DNATranslation; class AnnotationTableObject; enum SendSelectionAlphabet { SendSelectionAlphabet_Any, SendSelectionAlphabet_Nucleo, SendSelectionAlphabet_Amino }; enum FilterResult { FilterResultByAccession = 1, FilterResultByDef = 2, FilterResultById = 4 }; struct RemoteBLASTTaskSettings { QString dbChoosen; QString params; int retries; DNATranslation * aminoT; DNATranslation * complT; QByteArray query; int filterResult; bool useEval; RemoteBLASTTaskSettings() : retries(0), aminoT(NULL), complT(NULL), filterResult(0), useEval(false) {} }; class RemoteBLASTToAnnotationsTask : public Task { Q_OBJECT public: RemoteBLASTToAnnotationsTask( const RemoteBLASTTaskSettings &cfg, int qoffs, AnnotationTableObject* ao, const QString &url, const QString & group ); QList onSubTaskFinished(Task* subTask); private: int offsInGlobalSeq; QPointer aobj; QString group; Task* queryTask; QString url; }; class RemoteBLASTTask : public Task { Q_OBJECT public: RemoteBLASTTask( const RemoteBLASTTaskSettings & cfg ); void run(); void prepare(); bool isTranslated() const {return ( cfg.aminoT != NULL); } void increaseProgress() { stateInfo.progress++; emit si_progressChanged();} void resetProgress() {stateInfo.progress = 0; emit si_progressChanged();} QByteArray getOutputFile() const {return httpRequest.first()->getOutputFile();} QList getResultedAnnotations() const; bool timeout; private slots: void sl_timeout() {timeout = false;} private: struct Query { Query() : amino(false), complement(false), offs(0){} QByteArray seq; bool amino; bool complement; int offs; //translation frame offset }; void prepareQueries(); void createAnnotations(const Query & q,HttpRequest *t); QList filterAnnotations(QList annotations); RemoteBLASTTaskSettings cfg; QList queries; QList resultAnnotations; QList httpRequest; QTimer timer; }; //used by CDSearchWorker class RemoteCDSearch : public CDSearchResultListener { public: RemoteCDSearch(const CDSearchSettings& settings); virtual Task* getTask() const { return task; } virtual QList getCDSResults() const { return task->getResultedAnnotations(); } private: RemoteBLASTTask* task; }; class RemoteCDSearchFactory : public CDSearchFactory { virtual CDSearchResultListener* createCDSearch(const CDSearchSettings& settings) const { return new RemoteCDSearch(settings); } }; } #endif ugene-1.9.8/src/plugins/remote_blast/src/RemoteBLASTWorker.h0000644000175000017500000000403211651544324022421 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _REMOTE_QUERY_WORKER_ #define _REMOTE_QUERY_WORKER_ #include #include #include "RemoteBLASTTask.h" namespace U2 { namespace LocalWorkflow { class RemoteBLASTPrompter; typedef PrompterBase RemoteBLASTPrompterBase; class RemoteBLASTPrompter : public RemoteBLASTPrompterBase { Q_OBJECT public: RemoteBLASTPrompter(Actor* p = 0) : RemoteBLASTPrompterBase(p) {} protected: QString composeRichDoc(); }; class RemoteBLASTWorker: public BaseWorker { Q_OBJECT public: RemoteBLASTWorker(Actor *a) : BaseWorker(a), input(NULL), output(NULL) {} virtual void init(); virtual bool isReady(); virtual bool isDone(); virtual Task* tick(); virtual void cleanup() {}; private slots: void sl_taskFinished(); protected: CommunicationChannel *input, *output; //QString resultName,transId; RemoteBLASTTaskSettings cfg; }; class RemoteBLASTWorkerFactory:public DomainFactory { static const QString ACTOR_ID; public: static void init(); RemoteBLASTWorkerFactory() : DomainFactory(ACTOR_ID) {} virtual Worker* createWorker(Actor* a) {return new RemoteBLASTWorker(a);} }; } } #endif ugene-1.9.8/src/plugins/remote_blast/src/HttpRequest.h0000644000175000017500000000526511651544324021507 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _HTTP_REQUEST_H_ #define _HTTP_REQUEST_H_ #include #include #include #include #include #include #include #include #include "RemoteBLASTConsts.h" namespace U2 { class RemoteBLASTTask; struct ResponseBuffer { ResponseBuffer(){} ~ResponseBuffer() { buf.close(); } void setBuffer(QByteArray *arr) { buf.setBuffer(arr); } bool open(QIODevice::OpenMode openMode) { return buf.open(openMode); } void close() { buf.close(); } QByteArray readLine() { return buf.readLine(); } QBuffer buf; }; class HttpRequestBLAST:public HttpRequest { public: HttpRequestBLAST(Task *_task):HttpRequest(_task){}; virtual void sendRequest(const QString &program,const QString &query); virtual void parseResult(const QByteArray &buf); virtual QByteArray getOutputFile(); private: class Waiter: public QThread { public: static void await(int mseconds) { msleep(mseconds); } }; static const QString host; QByteArray output; void parseHit(const QDomNode &xml); void parseHsp(const QDomNode &xml,const QString &id, const QString &def, const QString &accession); }; class HttpRequestCDD:public HttpRequest { public: HttpRequestCDD(Task *_task):HttpRequest(_task){}; virtual void sendRequest(const QString &program,const QString &query); virtual void parseResult(ResponseBuffer &buf); private: class Waiter: public QThread { public: static void await(int mseconds) { msleep(mseconds); } }; static const QString host; void parseHit(QByteArray &b,ResponseBuffer &buf); QString extractText(const QByteArray &b); bool getLocations(QByteArray &b,int &from, int &to); }; } #endif ugene-1.9.8/src/plugins/remote_blast/src/HttpRequestBLAST.cpp0000644000175000017500000002523711651544324022631 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "HttpRequest.h" #include "RemoteBLASTTask.h" namespace U2 { const QString HttpRequestBLAST::host = "http://www.ncbi.nlm.nih.gov/blast/Blast.cgi?"; void HttpRequestBLAST::sendRequest(const QString ¶ms,const QString &query) { QString request = host; request.append(params); addParametr(request,ReqParams::sequence,query); // algoLog.trace("Request 1:"+request); IOAdapterFactory * iof = AppContext::getIOAdapterRegistry()->getIOAdapterFactoryById( BaseIOAdapters::HTTP_FILE ); IOAdapter * io = iof->createIOAdapter(); if(!io->open( request, IOAdapterMode_Read )) { connectionError = true; error = QObject::tr("Cannot open the IO adapter"); return; } int offs = 0; int read = 0; int CHUNK_SIZE = 1024; QByteArray response( CHUNK_SIZE, 0 ); do { if(task->isCanceled()) { io->close(); return; } read = io->readBlock( response.data() + offs, CHUNK_SIZE ); offs += read; response.resize( offs + read ); } while( read == CHUNK_SIZE ); io->close(); if(read<0) { connectionError = true; error = QObject::tr("Cannot load a page"); return; } if(response.isEmpty() || response.indexOf("TIGRFAM site.
  • COG - a mirror of the current COG database of orthologous protein families focusing on prokaryotes. Seed alignments have been generated by an automated process. An alternative search engine, \"Cognitor\", which runs protein-BLAST against a database of COG-assigned sequences, is offered on the COG site.
  • KOG - a eukaryotic counterpart to the COG database. KOGs are not included in the CDD superset, but are searchable as a separate data set.

  • More information about each database is provided in the section on Where does CDD content come from?") ); Descriptor nd(ANNOTATION_ATTR, CDSearchWorker::tr("Annotate as"), CDSearchWorker::tr("Name of the result annotations marking found conserved domains.") ); Descriptor ld(LOCAL_ATTR, CDSearchWorker::tr("Local search"), CDSearchWorker::tr("Perform the search on local machine or submit the search to NCBI for remote execution.") ); Descriptor ed(EVALUE_ATTR, CDSearchWorker::tr("Expect value"), CDSearchWorker::tr("Modifies the E-value threshold used for filtering results. False positive results should be very rare with the default setting of 0.01 (use a more conservative, i.e. lower setting for more reliable results), results with E-values in the range of 1 and above should be considered putative false positives.") ); Descriptor pd(DB_PATH_ATTR, CDSearchWorker::tr("Database directory"), CDSearchWorker::tr("Specifies database directory for local search.") ); a << new Attribute(nd, BaseTypes::STRING_TYPE(), true, "CDD result"); a << new Attribute(dd, BaseTypes::STRING_TYPE(), false, CDDNames::CDD_DB()); a << new Attribute(pd, BaseTypes::STRING_TYPE(), false); a << new Attribute(ld, BaseTypes::BOOL_TYPE(), false, true); a << new Attribute(ed, BaseTypes::NUM_TYPE(), false, 0.01); } Descriptor desc( ACTOR_ID, CDSearchWorker::tr("CD-Search"), CDSearchWorker::tr("Finds conserved domains in protein sequences. In case conserved domains database is downloaded the search can be executed on local machine. The search also can be submitted to the NCBI for remote execution.") ); ActorPrototype* proto = new IntegralBusActorPrototype(desc, p, a); QMap delegates; { QVariantMap m; m[CDDNames::CDD_DB()] = CDDNames::CDD_DB(); m[CDDNames::PFAM_DB()] = CDDNames::PFAM_DB(); m[CDDNames::SMART_DB()] = CDDNames::SMART_DB(); m[CDDNames::COG_DB()] = CDDNames::COG_DB(); m[CDDNames::KOG_DB()] = CDDNames::KOG_DB(); m[CDDNames::PRK_DB()] = CDDNames::PRK_DB(); m[CDDNames::TIGR_DB()] = CDDNames::TIGR_DB(); delegates[DATABASE_ATTR] = new ComboBoxDelegate(m); } { QVariantMap m; m["1e-100"] = 1e-100; m["1e-10"] = 1e-10; m["1"] = 1; m["10"] = 10; m["100"] = 100; m["1000"] = 1000; delegates[EVALUE_ATTR] = new ComboBoxDelegate(m); } { delegates[DB_PATH_ATTR] = new URLDelegate("", "Database Directory", false, true); } proto->setPrompter(new CDSearchPrompter()); proto->setEditor(new DelegateEditor(delegates)); WorkflowEnv::getProtoRegistry()->registerProto(BaseActorCategories::CATEGORY_BASIC(), proto); DomainFactory* localDomain = WorkflowEnv::getDomainRegistry()->getById(LocalDomainFactory::ID); localDomain->registerEntry(new CDSearchWorkerFactory()); } QString CDSearchPrompter::composeRichDoc() { IntegralBusPort* input = qobject_cast(target->getPort(BasePorts::IN_SEQ_PORT_ID())); Actor* producer = input->getProducer(BaseSlots::DNA_SEQUENCE_SLOT().getId()); QString unsetStr = ""+tr("unset")+""; QString producerName = tr(" from %1").arg(producer ? producer->getLabel() : unsetStr); QString dbStr = target->getParameter(DATABASE_ATTR)->getAttributeValue(); QString doc = tr("For sequence %1 find conserved domains in database %2") .arg(producerName) .arg(getHyperlink(DATABASE_ATTR, dbStr)); return doc; } void CDSearchWorker::init() { input = ports.value(BasePorts::IN_SEQ_PORT_ID()); output = ports.value(BasePorts::OUT_ANNOTATIONS_PORT_ID()); } bool CDSearchWorker::isReady() { return (input && input->hasMessage()); } bool CDSearchWorker::isDone() { return !input || input->isEnded(); } Task* CDSearchWorker::tick() { Message inputMessage = getMessageAndSetupScriptValues(input); DNASequence seq = inputMessage.getData().toMap().value(BaseSlots::DNA_SEQUENCE_SLOT().getId()).value(); settings.query = seq.seq; settings.alp = seq.alphabet; if (!settings.alp->isAmino()) { QString err = "Required amino acid input sequence"; return new FailTask(err); } settings.ev = actor->getParameter(EVALUE_ATTR)->getAttributeValue(); settings.dbName = actor->getParameter(DATABASE_ATTR)->getAttributeValue(); bool local = actor->getParameter(LOCAL_ATTR)->getAttributePureValue().toBool(); CDSearchFactory* factory = NULL; if (local) { factory = AppContext::getCDSFactoryRegistry()->getFactory(CDSearchFactoryRegistry::LocalSearch); if (!factory) { QString err = tr("'External tools' plugin has to be loaded."); return new FailTask(err); } settings.localDbFolder = actor->getParameter(DB_PATH_ATTR)->getAttributeValue(); } else { // remote factory = AppContext::getCDSFactoryRegistry()->getFactory(CDSearchFactoryRegistry::RemoteSearch); if (!factory) { QString err = tr("'Remote blast' plugin has to be loaded."); return new FailTask(err); } } cds = factory->createCDSearch(settings); Task* t = cds->getTask(); connect(new TaskSignalMapper(t), SIGNAL(si_taskFinished(Task*)), SLOT(sl_taskFinished(Task*))); return t; } void CDSearchWorker::sl_taskFinished(Task*) { if(output) { QList res = cds->getCDSResults(); QString annName = actor->getParameter(ANNOTATION_ATTR)->getAttributeValue(); if(!annName.isEmpty()) { for(int i = 0; iname = annName; } } QVariant v = qVariantFromValue >(res); output->put(Message(BaseTypes::ANNOTATION_TABLE_TYPE(), v)); if (input->isEnded()) { output->setEnded(); } } delete cds; cds = NULL; } } // Workflow } // U2 ugene-1.9.8/src/plugins/workflow_designer/src/library/DocWorkers.h0000644000175000017500000000705011651544325024012 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_WORKFLOW_DOC_WORKERS_H_ #define _U2_WORKFLOW_DOC_WORKERS_H_ #include "BaseDocWorker.h" #include "CoreLib.h" #include #include namespace U2 { namespace LocalWorkflow { class TextReader : public BaseDocReader { Q_OBJECT public: TextReader(Actor* a) : BaseDocReader(a, CoreLibConstants::TEXT_TYPESET_ID, BaseDocumentFormats::PLAIN_TEXT), io(NULL), done(false){} void init(); bool isDone(); bool isReady(); Task *tick(); protected: virtual void doc2data(Document* doc); private: IOAdapter *io; QStringList urls; QString url; bool done; }; class TextWriter : public BaseDocWriter { Q_OBJECT public: TextWriter(Actor* a) : BaseDocWriter(a, BaseDocumentFormats::PLAIN_TEXT){} protected: virtual void data2doc(Document*, const QVariantMap&); }; class FastaWriter : public BaseDocWriter { Q_OBJECT public: FastaWriter(Actor* a) : BaseDocWriter(a, BaseDocumentFormats::PLAIN_FASTA){} protected: virtual void data2doc(Document*, const QVariantMap&); public: static void data2document(Document*, const QVariantMap&); }; class GenbankWriter : public BaseDocWriter { Q_OBJECT public: GenbankWriter(Actor* a) : BaseDocWriter(a, BaseDocumentFormats::PLAIN_GENBANK){} protected: virtual void data2doc(Document*, const QVariantMap&); public: static void data2document(Document*, const QVariantMap&); }; class FastQWriter : public BaseDocWriter { Q_OBJECT public: FastQWriter(Actor* a) : BaseDocWriter(a, BaseDocumentFormats::FASTQ){} protected: virtual void data2doc(Document*, const QVariantMap&); public: static void data2document(Document*, const QVariantMap&); }; class RawSeqWriter : public BaseDocWriter { Q_OBJECT public: RawSeqWriter(Actor* a) : BaseDocWriter(a, BaseDocumentFormats::RAW_DNA_SEQUENCE){} protected: virtual void data2doc(Document*, const QVariantMap&); public: static void data2document(Document*, const QVariantMap&); }; // generic sequence writer class SeqWriter : public BaseDocWriter { Q_OBJECT public: SeqWriter( Actor * a ) : BaseDocWriter(a) {} protected: virtual void data2doc(Document*, const QVariantMap&); }; class MSAWriter : public BaseDocWriter { Q_OBJECT public: MSAWriter(Actor* a, const DocumentFormatId& fid) : BaseDocWriter(a, fid){} MSAWriter(Actor * a) : BaseDocWriter(a){} protected: virtual void data2doc(Document*, const QVariantMap&); }; class DataWorkerFactory : public DomainFactory { public: DataWorkerFactory(const Descriptor& d) : DomainFactory(d) {} virtual ~DataWorkerFactory() {} virtual Worker* createWorker(Actor*); static void init(); }; } // Workflow namespace } // U2 namespace #endif ugene-1.9.8/src/plugins/workflow_designer/src/library/BaseDocWorker.h0000644000175000017500000000442711651544325024427 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_WORKFLOW_BASEDOC_WORKERS_H_ #define _U2_WORKFLOW_BASEDOC_WORKERS_H_ #include #include namespace U2 { class Document; class DocumentFormat; namespace LocalWorkflow { class BaseDocReader : public BaseWorker { Q_OBJECT public: BaseDocReader(Actor* a, const QString& tid, const DocumentFormatId& fid); virtual ~BaseDocReader() {} virtual void init() ; virtual bool isReady(); virtual Task* tick() ; virtual bool isDone() ; virtual void cleanup() ; protected: virtual void doc2data(Document* ) = 0; protected: CommunicationChannel* ch; DocumentFormatId fid; QMap docs; bool done, attachDoc2Proj; QList cache; DataTypePtr mtype; }; class BaseDocWriter : public BaseWorker { Q_OBJECT public: BaseDocWriter(Actor* a, const DocumentFormatId& fid); BaseDocWriter( Actor * a ); virtual ~BaseDocWriter(){} virtual void init() ; virtual bool isReady(); virtual Task* tick() ; virtual bool isDone() ; virtual void cleanup() ; protected: virtual void data2doc(Document*, const QVariantMap&) = 0; Task* processDocs(); protected: CommunicationChannel* ch; DocumentFormat* format; QMap docs; bool done, append; QString url; QMap counter; uint fileMode; }; }// Workflow namespace }// U2 namespace #endif ugene-1.9.8/src/plugins/workflow_designer/src/library/ScriptWorker.cpp0000644000175000017500000002217211651544325024723 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "ScriptWorker.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include namespace U2 { namespace LocalWorkflow { const QString ScriptWorkerFactory::ACTOR_ID("Script-"); const static QString INPUT_PORT_TYPE("input-for-"); const static QString OUTPUT_PORT_TYPE("output-for-"); static const QString IN_PORT_ID("in"); static const QString OUT_PORT_ID("out"); void ScriptWorkerTask::run() { //QScriptEngine engine; QMap scriptVars; foreach( const Descriptor & key, script->getScriptVars().uniqueKeys() ) { assert(!key.getId().isEmpty()); if(!(script->getScriptVars().value(key)).isNull()) { scriptVars[key.getId()] = engine->newVariant(script->getScriptVars().value(key)); } else { scriptVars[key.getId()] = engine->newVariant(engine->globalObject().property(key.getId().toAscii().data()).toVariant()); } } WorkflowScriptLibrary::initEngine(engine); QScriptValue scriptResultValue = ScriptTask::runScript(engine, scriptVars, script->getScriptText(), stateInfo); result = scriptResultValue.toVariant(); if(engine->hasUncaughtException()) { result = engine->uncaughtException().toVariant(); stateInfo.setError(tr("Error in line ") + QString::number(engine->uncaughtExceptionLineNumber()) + ":" + result.toString().split(":").last()); } if(engine->globalObject().property("list").toBool()) { isList = true; } if( stateInfo.cancelFlag ) { if( !stateInfo.hasError() ) { stateInfo.setError("Script task canceled"); } } } QString ScriptPromter::composeRichDoc() { return target->getProto()->getDocumentation(); } bool ScriptWorkerFactory::init(QList input, QList output, QList attrs, const QString& name, const QString &description) { QList portDescs; QList attribs = attrs; QMap map; foreach(const DataTypePtr & tptr, input) { if(tptr == DataTypePtr()) { coreLog.error(ScriptWorker::tr("For input port was set empty data type")); return false; } map[WorkflowUtils::getSlotDescOfDatatype(tptr)] = tptr; } DataTypePtr inSet( new MapDataType(Descriptor(INPUT_PORT_TYPE + name), map) ); DataTypeRegistry * dr = WorkflowEnv::getDataTypeRegistry(); assert(dr); dr->registerEntry( inSet ); map.clear(); foreach(const DataTypePtr & tptr, output) { if(tptr == DataTypePtr()) { coreLog.error(ScriptWorker::tr("For output port was set empty data type")); return false; } map[WorkflowUtils::getSlotDescOfDatatype(tptr)] = tptr; } DataTypePtr outSet( new MapDataType(Descriptor(OUTPUT_PORT_TYPE + name), map) ); dr->registerEntry( outSet ); Descriptor inDesc( IN_PORT_ID, ScriptWorker::tr("input data"), ScriptWorker::tr("input data") ); Descriptor outDesc( OUT_PORT_ID, ScriptWorker::tr("output data"), ScriptWorker::tr("output data") ); portDescs << new PortDescriptor( inDesc, inSet, /*input*/ true ); portDescs << new PortDescriptor( outDesc, outSet, /*input*/false, /*multi*/true ); Descriptor desc( ScriptWorkerFactory::ACTOR_ID + name, name, description ); ActorPrototype * proto = new IntegralBusActorPrototype( desc, portDescs, attribs ); proto->setEditor( new DelegateEditor(QMap()) ); proto->setIconPath(":workflow_designer/images/script.png"); proto->setPrompter( new ScriptPromter() ); proto->setScriptFlag(); WorkflowEnv::getProtoRegistry()->registerProto(BaseActorCategories::CATEGORY_SCRIPT(), proto); DomainFactory* localDomain = WorkflowEnv::getDomainRegistry()->getById( LocalDomainFactory::ID ); localDomain->registerEntry( new ScriptWorkerFactory(ACTOR_ID + name) ); return true; } void ScriptWorker::init() { input = ports.value(IN_PORT_ID); output = ports.value(OUT_PORT_ID); } bool ScriptWorker::isReady() { return (input && input->hasMessage()); } bool ScriptWorker::isDone() { return input->isEnded(); } void ScriptWorker::bindPortVariables() { foreach( IntegralBus * bus, ports.values() ) { assert(bus != NULL); if(actor->getPort(bus->getPortId())->isOutput()) { // means that it is bus for output port continue; } QVariantMap busData = bus->look().getData().toMap(); foreach(const QString & slotDesc, busData.keys()) { ActorId actorId = IntegralBusType::parseSlotDesc(slotDesc); QString attrId = IntegralBusType::parseAttributeIdFromSlotDesc(slotDesc); QString portId = bus->getPortId(); IntegralBusPort * busPort = qobject_cast(actor->getPort(portId)); Q_UNUSED(busPort); assert(busPort != NULL); //Actor * bindedAttrOwner = busPort->getLinkedActorById(actorId); attrId.prepend("in_"); if( script->hasVarWithId(attrId)) { script->setVarValueWithId(attrId, busData.value(slotDesc)); } } } } void ScriptWorker::bindAttributeVariables() { QMap attrs = actor->getParameters(); QMap::iterator it; for(it = attrs.begin(); it!=attrs.end();it++) { Attribute* attr = it.value(); if(script->hasVarWithId(attr->getId())) { script->setVarValueWithId(attr->getId(),attr->getAttributePureValue()); } } } Task *ScriptWorker::tick() { //AttributeScript *script = actor->getScript(); if( script->isEmpty() ) { coreLog.error(tr("no script text")); return new FailTask(tr("no script text")); } bindPortVariables(); bindAttributeVariables(); getMessageAndSetupScriptValues(input); Task *t = new ScriptWorkerTask(&engine, script); connect(t, SIGNAL(si_stateChanged()), SLOT(sl_taskFinished())); return t; } void ScriptWorker::sl_taskFinished() { ScriptWorkerTask *t = qobject_cast(sender()); if (t->getState() != Task::State_Finished || t->hasError()) { return; } QString name = actor->getProto()->getDisplayName(); DataTypeRegistry *dtr = WorkflowEnv::getDataTypeRegistry(); assert(dtr); DataTypePtr ptr = dtr->getById(OUTPUT_PORT_TYPE + name); if(ptr->getAllDescriptors().size() == 1 && ptr->getAllDescriptors().first().getId() == BaseTypes::MULTIPLE_ALIGNMENT_TYPE()->getId()) { if (!input->isEnded()) { return; } } QVariantMap map; foreach(const Descriptor &desc, ptr->getAllDescriptors()) { QString varName = "out_" + desc.getId(); //MAlignment ma = t->getEngine()->globalObject().property(varName.toAscii().data()).toVariant().value(); map[desc.getId()] = t->getEngine()->globalObject().property(varName.toAscii().data()).toVariant(); } if(output) { if(t->isList) { QString varName = "out_" + BaseTypes::DNA_SEQUENCE_TYPE()->getId(); QList seqs = t->getEngine()->globalObject().property(varName.toAscii().data()).toVariant().value >(); //QList seqs = t->getResult().value >(); foreach(DNASequence seq, seqs) { QVariantMap message; //message[ptr->getAllDescriptors().first().getId()] = QVariant::fromValue(seq); map[BaseTypes::DNA_SEQUENCE_TYPE()->getId()] = QVariant::fromValue(seq); output->put(Message(ptr,map)); } } else { QVariant scriptResult = t->getResult(); output->put(Message(ptr,map)); } } if (input->isEnded()) { output->setEnded(); } } } //namespace LocalWorkflow } //namespace U2 ugene-1.9.8/src/plugins/workflow_designer/src/library/ImportAnnotationsWorker.h0000644000175000017500000000356611651544325026622 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef __IMPORT_ANNOTATIONS_WORKER_H_ #define __IMPORT_ANNOTATIONS_WORKER_H_ #include #include namespace U2 { namespace LocalWorkflow { class ImportAnnotationsWorker : public BaseWorker { Q_OBJECT public: ImportAnnotationsWorker(Actor * p) : BaseWorker(p), inPort(NULL), outPort(NULL) {} virtual void init(); virtual bool isReady(); virtual Task * tick(); virtual bool isDone(); virtual void cleanup(); private slots: void sl_docsLoaded(Task *); private: IntegralBus * inPort; IntegralBus * outPort; QMap > annsMap; }; // ImportAnnotationsWorker class ImportAnnotationsWorkerFactory : public DomainFactory { public: static const QString ACTOR_ID; ImportAnnotationsWorkerFactory() : DomainFactory(ACTOR_ID) {} static void init(); virtual Worker * createWorker(Actor* a); }; // ImportAnnotationsWorkerFactory } // LocalWorkflow } // U2 #endif // __IMPORT_ANNOTATIONS_WORKER_H_ ugene-1.9.8/src/plugins/workflow_designer/src/library/DocActors.cpp0000644000175000017500000002153111651544325024144 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "DocActors.h" #include "CoreLib.h" #include #include #include #include #include #include #include #include namespace U2 { namespace Workflow { /**************************** * DocActorProto *****************************/ DocActorProto::DocActorProto(const DocumentFormatId& _fid, const Descriptor& _desc, const QList& _ports, const QList& _attrs ) : IntegralBusActorPrototype(_desc, _ports, _attrs), fid(_fid) { } DocActorProto::DocActorProto(const Descriptor& _desc, const GObjectType& t, const QList& _ports, const QList& _attrs ) : IntegralBusActorPrototype(_desc, _ports, _attrs), type(t) { } bool DocActorProto::isAcceptableDrop(const QMimeData * md, QVariantMap * params, const QString & urlAttrId ) const { QList fs; QString url = WorkflowUtils::getDropUrl(fs, md); foreach(DocumentFormat* df, fs) { if (fid == df->getFormatId()) { if (params) { params->insert( urlAttrId, url ); } return true; } } return false; } QString DocActorProto::prepareDocumentFilter() { if( !fid.isEmpty() ) { return DialogUtils::prepareDocumentsFileFilter( fid, true ); } else { assert( !type.isEmpty() ); return DialogUtils::prepareDocumentsFileFilterByObjType( type, true ); } } /**************************** * ReadDocActorProto *****************************/ ReadDocActorProto::ReadDocActorProto(const DocumentFormatId& _fid, const Descriptor& _desc, const QList& _ports, const QList& _attrs ) : DocActorProto( _fid, _desc, _ports, _attrs ) { attrs << new Attribute( BaseAttributes::URL_IN_ATTRIBUTE(), BaseTypes::STRING_TYPE(), true ); QMap< QString, PropertyDelegate* > delegateMap; delegateMap[BaseAttributes::URL_IN_ATTRIBUTE().getId()] = new URLDelegate( prepareDocumentFilter(), QString(), true ); setEditor( new DelegateEditor( delegateMap ) ); } bool ReadDocActorProto::isAcceptableDrop(const QMimeData * md, QVariantMap * params ) const { return DocActorProto::isAcceptableDrop( md, params, BaseAttributes::URL_IN_ATTRIBUTE().getId() ); } /**************************** * WriteDocActorProto *****************************/ WriteDocActorProto::WriteDocActorProto(const DocumentFormatId& _fid, const Descriptor& _desc, const QList& _ports, const QString & portId, const QList& _attrs) : DocActorProto( _fid, _desc, _ports, _attrs ), outPortId(portId), urlDelegate(NULL) { construct(); } WriteDocActorProto::WriteDocActorProto(const Descriptor& _desc, const GObjectType & t, const QList& _ports, const QString & portId, const QList& _attrs) : DocActorProto(_desc, t, _ports, _attrs), outPortId(portId), urlDelegate(NULL) { construct(); } bool WriteDocActorProto::isAcceptableDrop(const QMimeData * md, QVariantMap * params ) const { return DocActorProto::isAcceptableDrop( md, params, BaseAttributes::URL_OUT_ATTRIBUTE().getId() ); } void WriteDocActorProto::construct() { attrs << new Attribute(BaseAttributes::URL_OUT_ATTRIBUTE(), BaseTypes::STRING_TYPE(), false ); attrs << new Attribute(BaseAttributes::FILE_MODE_ATTRIBUTE(), BaseTypes::NUM_TYPE(), false, SaveDoc_Roll); QMap< QString, PropertyDelegate* > delegateMap; urlDelegate = new URLDelegate(prepareDocumentFilter(), QString(), false, false, true, 0, fid); delegateMap[BaseAttributes::URL_OUT_ATTRIBUTE().getId()] = urlDelegate; delegateMap[BaseAttributes::FILE_MODE_ATTRIBUTE().getId()] = new FileModeDelegate(attrs.size() > 2); setEditor(new DelegateEditor(delegateMap)); setValidator(new ScreenedParamValidator(BaseAttributes::URL_OUT_ATTRIBUTE().getId(), ports.first()->getId(), BaseSlots::URL_SLOT().getId())); setPortValidator(outPortId, new ScreenedSlotValidator(BaseSlots::URL_SLOT().getId())); } URLDelegate *WriteDocActorProto::getUrlDelegate() { return urlDelegate; } /**************************** * WriteGenbankPrompter *****************************/ QString WriteGenbankPrompter::composeRichDoc() { QString outPortId = target->getInputPorts().first()->getId(); IntegralBusPort* input = qobject_cast(target->getPort(outPortId)); Actor* seqProducer = input->getProducer(BaseSlots::DNA_SEQUENCE_SLOT().getId()); QString seqName = seqProducer ? tr(" sequence from %1").arg(seqProducer->getLabel()) : ""; QString annName = getProducers(outPortId, BaseSlots::ANNOTATION_TABLE_SLOT().getId()); if (!annName.isEmpty()) { annName = tr(" set of annotations from %1").arg(annName); } QString url = getScreenedURL( qobject_cast(target->getPort(outPortId)), BaseAttributes::URL_OUT_ATTRIBUTE().getId(), BaseSlots::URL_SLOT().getId() ); url = getHyperlink(BaseAttributes::URL_OUT_ATTRIBUTE().getId(), url); QString data; if (seqName.isEmpty() && annName.isEmpty()) { QString doc = tr("Write sequence(s) in Genbank format to %1.").arg(url); return doc; } else if (!seqName.isEmpty() && !annName.isEmpty()) { data = tr("each %1 and %2").arg(seqName).arg(annName); } else { data = tr("each ") + seqName + annName; } return tr("Write %1 in Genbank format, to %2.") .arg(data) .arg(url); } /**************************** * WriteFastaPrompter *****************************/ QString WriteFastaPrompter::composeRichDoc() { QString outPortId = target->getInputPorts().first()->getId(); IntegralBusPort* input = qobject_cast(target->getPort(outPortId)); QString url = getScreenedURL( qobject_cast(target->getPort(outPortId)), BaseAttributes::URL_OUT_ATTRIBUTE().getId(), BaseSlots::URL_SLOT().getId() ); url = getHyperlink(BaseAttributes::URL_OUT_ATTRIBUTE().getId(), url); Actor* seqProducer = input->getProducer(BaseSlots::DNA_SEQUENCE_SLOT().getId()); if (!seqProducer) { QString doc = tr("Writes sequence(s) in %1 format to %2.").arg(format).arg(url); return doc; } QString doc = tr("Writes sequence(s) from %1 in %2 format to %3.") .arg(seqProducer->getLabel()) .arg(format) .arg(url); return doc; } ActorDocument* WriteFastaPrompter::createDescription(Actor* a) { WriteFastaPrompter* doc = new WriteFastaPrompter(format, a); doc->connect(a, SIGNAL(si_labelChanged()), SLOT(sl_actorModified())); doc->connect(a, SIGNAL(si_modified()), SLOT(sl_actorModified())); foreach(Workflow::Port* input, a->getInputPorts()) { doc->connect(input, SIGNAL(bindingChanged()), SLOT(sl_actorModified())); } return doc; } /**************************** * WriteDocPrompter *****************************/ QString WriteDocPrompter::composeRichDoc() { QString outPortId = target->getInputPorts().first()->getId(); QString url = getScreenedURL( qobject_cast(target->getPort(outPortId)), BaseAttributes::URL_OUT_ATTRIBUTE().getId(), BaseSlots::URL_SLOT().getId() ); url = getHyperlink(BaseAttributes::URL_OUT_ATTRIBUTE().getId(), url); QString producers = getProducers(outPortId, slot); if (producers.isEmpty()) { QString unsetStr = ""+tr("unset")+""; return spec.arg(unsetStr).arg(url); } return spec.arg(producers).arg(url); } /**************************** * ReadDocPrompter *****************************/ QString ReadDocPrompter::composeRichDoc() { const QString& id = BaseAttributes::URL_IN_ATTRIBUTE().getId(); return spec.arg(getHyperlink(id, getURL(id))); } }//namespace Workflow }//namespace U2 ugene-1.9.8/src/plugins/workflow_designer/src/library/MSA2SequenceWorker.h0000644000175000017500000000405011651544325025312 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _MSA_2_SEQUENCE_WORKER_H_ #define _MSA_2_SEQUENCE_WORKER_H_ #include #include namespace U2 { namespace LocalWorkflow { class Alignment2SequencePrompter : public PrompterBase { Q_OBJECT public: Alignment2SequencePrompter(Actor * p = NULL) : PrompterBase(p) {} protected: QString composeRichDoc(); }; // Text2SequencePrompter class Alignment2SequenceWorker : public BaseWorker { Q_OBJECT public: static QMap cuteAlIdNames; public: Alignment2SequenceWorker(Actor * p) : BaseWorker(p), input(NULL), output(NULL) {} virtual void init(); virtual bool isReady(); virtual Task * tick(); virtual bool isDone(); virtual void cleanup(); private: IntegralBus * input; IntegralBus * output; }; // Text2SequenceWorker class Alignment2SequenceWorkerFactory : public DomainFactory { public: static const QString ACTOR_ID; Alignment2SequenceWorkerFactory() : DomainFactory(ACTOR_ID) {} static void init(); virtual Worker * createWorker(Actor* a); }; // Text2SequenceWorkerFactory } // LocalWorkflow } // U2 #endif ugene-1.9.8/src/plugins/workflow_designer/src/library/ScriptWorker.h0000644000175000017500000000513511651544325024370 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_SCRIPT_WORKER_H_ #define _U2_SCRIPT_WORKER_H_ #include #include namespace U2 { namespace LocalWorkflow { class ScriptWorkerTask: public Task { Q_OBJECT public: ScriptWorkerTask(QScriptEngine *_engine, AttributeScript* _script ):Task(tr("Script worker task"),TaskFlag_None), isList(false),engine(_engine),script(_script) {} void run(); QVariant getResult() const {return result;} QScriptEngine *getEngine() {return engine;} bool isList; private: QVariant result; QScriptEngine *engine; AttributeScript *script; }; class ScriptPromter : public PrompterBase { Q_OBJECT public: ScriptPromter( Actor * p = 0 ) : PrompterBase(p) {}; protected: QString composeRichDoc(); }; class ScriptWorker: public BaseWorker { Q_OBJECT public: ScriptWorker(Actor *a): BaseWorker(a), input(NULL), output(NULL) {script = a->getScript();} virtual void init(); virtual bool isReady(); virtual bool isDone(); virtual Task* tick(); virtual void cleanup() {}; private slots: void sl_taskFinished(); private: void bindAttributeVariables(); void bindPortVariables(); //QVariant scriptResult; CommunicationChannel *input, *output; QScriptEngine engine; AttributeScript *script; }; class ScriptWorkerFactory: public DomainFactory { public: ScriptWorkerFactory(QString name) : DomainFactory(name) {} static bool init(QList input, QList output, QList attrs, const QString& name,const QString &description); virtual Worker* createWorker(Actor* a) {return new ScriptWorker(a);} static const QString ACTOR_ID; }; } // Workflow namespace } // U2 namespace #endif ugene-1.9.8/src/plugins/workflow_designer/src/library/CoreLib.cpp0000644000175000017500000004665111651544325023614 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include #include "CoreLib.h" #include "BaseDocWorker.h" #include "DocWorkers.h" #include "DocActors.h" #include "GenericReadActor.h" #include "FindWorker.h" #include "SequenceSplitWorker.h" #include "ScriptWorker.h" #include "Text2SequenceWorker.h" #include "ImportAnnotationsWorker.h" #include "SequencesToMSAWorker.h" #include "FilterAnnotationsWorker.h" #include "CDSearchWorker.h" #include "StatisticWorkers.h" #include "ReverseComplementWorker.h" #include "MSA2SequenceWorker.h" #include "ExternalProcessWorker.h" #include "RemoteDBFetcherWorker.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include /* TRANSLATOR U2::Workflow::CoreLib */ namespace U2 { using namespace LocalWorkflow; namespace Workflow { static const QString FASTQ_TYPESET_ID("fastq.content"); static const QString FASTA_TYPESET_ID("fasta.content"); static const QString SEQ_TYPESET_ID("seq.content"); static const QString GENBANK_TYPESET_ID("genbank.content"); static const QString MA_TYPESET_ID("ma.content"); #define WORKFLOW_DOC "GB2WORKFLOW" #define ACTOR_ELEMENT "Actor" #define INPUT_PORT_ELEMENT "Input-port" #define OUTPUT_PORT_ELEMENT "Output-port" #define ATTRIBUTE_ELEMENT "Attributes" #define IN_SLOT_ELEMENT "In-Slots" #define OUT_SLOT_ELEMENT "Out-Slots" #define SLOT_ID "Slot" #define ATTR_ELEMENT "Attribute" #define NAME_ID "Name" #define TYPE_ID "Type" #define NAME_ELEMENT "Element-name" #define DESCR_ELEMENT "Element-description" #define DESCR_ID "Description" void CoreLib::init() { Descriptor writeUrlD(BaseSlots::URL_SLOT().getId(), tr("Location"), tr("Location for writing data")); DataTypeRegistry* dr = WorkflowEnv::getDataTypeRegistry(); assert(dr); DataTypePtr writeMAType; { QMap m; m[writeUrlD] = BaseTypes::STRING_TYPE(); m[BaseSlots::MULTIPLE_ALIGNMENT_SLOT()] = BaseTypes::MULTIPLE_ALIGNMENT_TYPE(); writeMAType = new MapDataType(Descriptor(MA_TYPESET_ID), m); //dr->registerEntry(writeMAType); } ActorPrototypeRegistry* r = WorkflowEnv::getProtoRegistry(); assert(r); r->registerProto(BaseActorCategories::CATEGORY_DATASRC(), new GenericMAActorProto()); r->registerProto(BaseActorCategories::CATEGORY_DATASRC(), new GenericSeqActorProto()); // WRITE FASTA actor proto { QMap m; m[writeUrlD] = BaseTypes::STRING_TYPE(); m[BaseSlots::DNA_SEQUENCE_SLOT()] = BaseTypes::DNA_SEQUENCE_TYPE(); m[BaseSlots::FASTA_HEADER_SLOT()] = BaseTypes::STRING_TYPE(); DataTypePtr fastaTypeSet(new MapDataType(Descriptor(FASTA_TYPESET_ID), m)); QList p; QList a; Descriptor acd(CoreLibConstants::WRITE_FASTA_PROTO_ID, tr("Write FASTA"), tr("Writes all supplied sequences to file(s) in FASTA format.")); Descriptor pd(BasePorts::IN_SEQ_PORT_ID(), tr("Sequence"), tr("A sequence along with FASTA header line.")); p << new PortDescriptor(pd, fastaTypeSet, true); a << new Attribute(BaseAttributes::ACCUMULATE_OBJS_ATTRIBUTE(), BaseTypes::BOOL_TYPE(), false, true); IntegralBusActorPrototype* proto = new WriteDocActorProto(BaseDocumentFormats::PLAIN_FASTA, acd, p, pd.getId(), a); proto->setPrompter(new WriteFastaPrompter("FASTA")); r->registerProto(BaseActorCategories::CATEGORY_DATASINK(), proto); } // WRITE FASTQ actor proto { QMap m; m[writeUrlD] = BaseTypes::STRING_TYPE(); m[BaseSlots::DNA_SEQUENCE_SLOT()] = BaseTypes::DNA_SEQUENCE_TYPE(); DataTypePtr fastqTypeSet(new MapDataType(Descriptor(FASTQ_TYPESET_ID), m)); QList p; QList a; Descriptor acd(CoreLibConstants::WRITE_FASTQ_PROTO_ID, tr("Write FASTQ"), tr("Writes all supplied sequences to file(s) in FASTQ format.")); Descriptor pd(BasePorts::IN_SEQ_PORT_ID(), tr("Sequence"), tr("A sequence in FASTQ format along with PHRED quality scores.")); p << new PortDescriptor(pd, fastqTypeSet, true); a << new Attribute(BaseAttributes::ACCUMULATE_OBJS_ATTRIBUTE(), BaseTypes::BOOL_TYPE(), false, true); IntegralBusActorPrototype* proto = new WriteDocActorProto(BaseDocumentFormats::FASTQ, acd, p, pd.getId(), a); proto->setPrompter(new WriteFastaPrompter("FASTQ")); r->registerProto(BaseActorCategories::CATEGORY_DATASINK(), proto); } // WRITE GENBANK actor proto { QMap m; m[writeUrlD] = BaseTypes::STRING_TYPE(); m[BaseSlots::DNA_SEQUENCE_SLOT()] = BaseTypes::DNA_SEQUENCE_TYPE(); m[BaseSlots::ANNOTATION_TABLE_SLOT()] = BaseTypes::ANNOTATION_TABLE_LIST_TYPE(); //m[gbAccd] = BaseTypes::STRING_TYPE(); DataTypePtr genbankTypeSet(new MapDataType(Descriptor(GENBANK_TYPESET_ID), m)); QList p; QList a; Descriptor acd(CoreLibConstants::WRITE_GENBANK_PROTO_ID, tr("Write Genbank"), tr("Writes all supplied sequences and related annotations to file(s) in Genbank format.")); Descriptor pd(BasePorts::IN_SEQ_PORT_ID(), tr("Sequence"), tr("Sequence and set of annotations")); p << new PortDescriptor(pd, genbankTypeSet, true); a << new Attribute(BaseAttributes::ACCUMULATE_OBJS_ATTRIBUTE(), BaseTypes::BOOL_TYPE(), false, true); IntegralBusActorPrototype* proto = new WriteDocActorProto(BaseDocumentFormats::PLAIN_GENBANK, acd, p, pd.getId(), a); proto->setPrompter(new WriteGenbankPrompter()); r->registerProto(BaseActorCategories::CATEGORY_DATASINK(), proto); } // READ PLAIN TEXT actor proto { QMap m; m[BaseSlots::URL_SLOT()] = BaseTypes::STRING_TYPE(); m[BaseSlots::TEXT_SLOT()] = BaseTypes::STRING_TYPE(); DataTypePtr dtl(new MapDataType(Descriptor(CoreLibConstants::TEXT_TYPESET_ID), m)); dr->registerEntry(dtl); QList p; QList a; a << new Attribute(BaseAttributes::READ_BY_LINES_ATTRIBUTE(), BaseTypes::BOOL_TYPE(), false, false); Descriptor acd(CoreLibConstants::READ_TEXT_PROTO_ID, tr("Read plain text"), tr("Reads text from local or remote files.")); p << new PortDescriptor(Descriptor(BasePorts::OUT_TEXT_PORT_ID(), tr("Plain text"), ""), dtl, false, true); IntegralBusActorPrototype* proto = new ReadDocActorProto(BaseDocumentFormats::PLAIN_TEXT, acd, p, a); proto->setPrompter(new ReadDocPrompter(tr("Reads text from %1."))); if(AppContext::isGUIMode()) { proto->setIcon( GUIUtils::createRoundIcon(QColor(85,85,255), 22)); } r->registerProto(BaseActorCategories::CATEGORY_DATASRC(), proto); } // WRITE PLAIN TEXT actor proto { QMap m; m[writeUrlD] = BaseTypes::STRING_TYPE(); m[BaseSlots::TEXT_SLOT()] = new ListDataType("string-list", BaseTypes::STRING_TYPE()); DataTypePtr dtl(new MapDataType(Descriptor("in.text"), m)); QList p; QList a; Descriptor acd(CoreLibConstants::WRITE_TEXT_PROTO_ID, tr("Write plain text"), tr("Write strings to a file")); Descriptor pd(BasePorts::IN_TEXT_PORT_ID(), tr("Plain text"), tr("Plain text")); p << new PortDescriptor(pd, dtl, true); a << new Attribute(BaseAttributes::ACCUMULATE_OBJS_ATTRIBUTE(), BaseTypes::BOOL_TYPE(), false, true); IntegralBusActorPrototype* proto = new WriteDocActorProto(BaseDocumentFormats::PLAIN_TEXT, acd, p, pd.getId(), a); proto->setPrompter(new WriteDocPrompter(tr("Save text from %1 to %2."), BaseSlots::TEXT_SLOT().getId())); r->registerProto(BaseActorCategories::CATEGORY_DATASINK(), proto); } // WRITE CLUSTAL actor proto { QList p; QList a; Descriptor acd(CoreLibConstants::WRITE_CLUSTAL_PROTO_ID, tr("Write ClustalW"), tr("Writes all supplied alignments to file(s) in CLUSTALW format.")); Descriptor pd(BasePorts::IN_MSA_PORT_ID(), tr("Multiple sequence alignment"), tr("Multiple sequence alignment")); p << new PortDescriptor(pd, writeMAType, true); IntegralBusActorPrototype* proto = new WriteDocActorProto(BaseDocumentFormats::CLUSTAL_ALN, acd, p, pd.getId(), a); proto->setPrompter(new WriteDocPrompter(tr("Save all MSAs from %1 to %2."), BaseSlots::MULTIPLE_ALIGNMENT_SLOT().getId())); r->registerProto(BaseActorCategories::CATEGORY_DATASINK(), proto); } // WRITE STOCKHOLM actor proto { QList p; QList a; Descriptor acd(CoreLibConstants::WRITE_STOCKHOLM_PROTO_ID, tr("Write Stockholm"), tr("Writes all supplied alignments to file(s) in Stockholm format.")); Descriptor pd(BasePorts::IN_MSA_PORT_ID(), tr("Multiple sequence alignment"), tr("Multiple sequence alignment")); p << new PortDescriptor(pd, writeMAType, true); a << new Attribute(BaseAttributes::ACCUMULATE_OBJS_ATTRIBUTE(), BaseTypes::BOOL_TYPE(), false, true); IntegralBusActorPrototype* proto = new WriteDocActorProto(BaseDocumentFormats::STOCKHOLM, acd, p, pd.getId(), a); proto->setPrompter(new WriteDocPrompter(tr("Save all MSAs from %1 to %2."), BaseSlots::MULTIPLE_ALIGNMENT_SLOT().getId())); r->registerProto(BaseActorCategories::CATEGORY_DATASINK(), proto); } // GENERIC WRITE MSA actor proto { DocumentFormatConstraints constr; constr.supportedObjectTypes.insert( GObjectTypes::MULTIPLE_ALIGNMENT ); constr.addFlagToSupport(DocumentFormatFlag_SupportWriting); QList supportedFormats = AppContext::getDocumentFormatRegistry()->selectFormats( constr ); if( !supportedFormats.isEmpty() ) { QList p; QList a; Descriptor acd(CoreLibConstants::WRITE_MSA_PROTO_ID, tr("Write alignment"), tr("Writes all supplied alignments to file(s) in selected format")); Descriptor pd(BasePorts::IN_MSA_PORT_ID(), tr("Multiple sequence alignment"), tr("Multiple sequence alignment")); p << new PortDescriptor(pd, writeMAType, true); a << new Attribute(BaseAttributes::DOCUMENT_FORMAT_ATTRIBUTE(), BaseTypes::STRING_TYPE(), false, supportedFormats.contains( BaseDocumentFormats::CLUSTAL_ALN ) ? BaseDocumentFormats::CLUSTAL_ALN : supportedFormats.first() ); WriteDocActorProto *childProto = new WriteDocActorProto( acd, GObjectTypes::MULTIPLE_ALIGNMENT, p, pd.getId(), a ); IntegralBusActorPrototype * proto = childProto; QVariantMap m; foreach( const DocumentFormatId & fid, supportedFormats ) { m[fid] = fid; } ComboBoxDelegate *comboDelegate = new ComboBoxDelegate(m); connect(comboDelegate, SIGNAL(si_valueChanged(const QString &)), childProto->getUrlDelegate(), SLOT(sl_formatChanged(const QString &))); proto->getEditor()->addDelegate(comboDelegate, BaseAttributes::DOCUMENT_FORMAT_ATTRIBUTE().getId()); proto->setPrompter(new WriteDocPrompter(tr("Save all MSAs from %1 to %2."), BaseSlots::MULTIPLE_ALIGNMENT_SLOT().getId())); r->registerProto(BaseActorCategories::CATEGORY_DATASINK(), proto); } } // GENERIC WRITE SEQ actor proto { DocumentFormatConstraints constr; constr.supportedObjectTypes.insert( GObjectTypes::SEQUENCE ); constr.addFlagToSupport(DocumentFormatFlag_SupportWriting); QList supportedFormats = AppContext::getDocumentFormatRegistry()->selectFormats( constr ); if( !supportedFormats.isEmpty() ) { QMap typeMap; typeMap[writeUrlD] = BaseTypes::STRING_TYPE(); typeMap[BaseSlots::DNA_SEQUENCE_SLOT()] = BaseTypes::DNA_SEQUENCE_TYPE(); typeMap[BaseSlots::ANNOTATION_TABLE_SLOT()] = BaseTypes::ANNOTATION_TABLE_LIST_TYPE(); DataTypePtr typeSet( new MapDataType(Descriptor(SEQ_TYPESET_ID), typeMap)); QList p; QList a; Descriptor acd(CoreLibConstants::WRITE_SEQ_PROTO_ID, tr("Write sequence"), tr("Writes all supplied sequences to file(s) in selected format.")); Descriptor pd(BasePorts::IN_SEQ_PORT_ID(), tr("Sequence"), tr("Sequence")); p << new PortDescriptor(pd, typeSet, true); a << new Attribute(BaseAttributes::ACCUMULATE_OBJS_ATTRIBUTE(), BaseTypes::BOOL_TYPE(), false, true); a << new Attribute(BaseAttributes::DOCUMENT_FORMAT_ATTRIBUTE(), BaseTypes::STRING_TYPE(), false, supportedFormats.contains( BaseDocumentFormats::PLAIN_FASTA ) ? BaseDocumentFormats::PLAIN_FASTA : supportedFormats.first() ); WriteDocActorProto *childProto = new WriteDocActorProto( acd, GObjectTypes::SEQUENCE, p, pd.getId(), a ); IntegralBusActorPrototype * proto = childProto; QVariantMap m; foreach( const DocumentFormatId & fid, supportedFormats ) { m[fid] = fid; } ComboBoxDelegate *comboDelegate = new ComboBoxDelegate(m); connect(comboDelegate, SIGNAL(si_valueChanged(const QString &)), childProto->getUrlDelegate(), SLOT(sl_formatChanged(const QString &))); proto->getEditor()->addDelegate(comboDelegate, BaseAttributes::DOCUMENT_FORMAT_ATTRIBUTE().getId()); proto->setPrompter(new WriteDocPrompter(tr("Save all sequences from %1 to %2."), BaseSlots::DNA_SEQUENCE_SLOT().getId())); r->registerProto(BaseActorCategories::CATEGORY_DATASINK(), proto); } } DataWorkerFactory::init(); FindWorkerFactory::init(); RemoteDBFetcherFactory::init(); SequenceSplitWorkerFactory::init(); Text2SequenceWorkerFactory::init(); Alignment2SequenceWorkerFactory::init(); ImportAnnotationsWorkerFactory::init(); FilterAnnotationsWorkerFactory::init(); SequencesToMSAWorkerFactory::init(); CDSearchWorkerFactory::init(); DNAStatWorkerFactory::init(); RCWorkerFactory::init(); initUsersWorkers(); initExternalToolsWorkers(); } void CoreLib::initUsersWorkers() { QString path = WorkflowSettings::getUserDirectory(); QDir dir(path); if(!dir.exists()) { //log.info(tr("There isn't directory with users workflow elements")); return; } dir.setNameFilters(QStringList() << "*.usa"); //think about file extension QFileInfoList fileList = dir.entryInfoList(); foreach(const QFileInfo& fileInfo, fileList) { QString url = fileInfo.filePath(); QFile file(url); //fileInfo.setFile(file); QDomDocument xml; file.open(QIODevice::ReadOnly); QByteArray content = file.readAll(); file.close(); QString error; xml.setContent(content,false,&error); if(!error.isEmpty()) { coreLog.message(LogLevel_ERROR, tr("Can't load actor %1").arg(url), ULOG_CAT_IO); continue; } QDomElement doc = xml.documentElement(); DataTypeRegistry *dtr = WorkflowEnv::getDataTypeRegistry(); assert(dtr); //QDomElement actor = doc.elementsByTagName(ACTOR_ELEMENT).item(0).toElement(); //QDomElement input = actor.elementsByTagName(INPUT_PORT_ELEMENT).item(0).toElement(); QDomNodeList inputs = doc.elementsByTagName(IN_SLOT_ELEMENT); QList inputTypes; for(int i = 0; i < inputs.size(); i++) { QDomElement slot = inputs.item(i).toElement(); QString id = slot.attribute(SLOT_ID); inputTypes << dtr->getById(id); } //QDomElement output = doc.elementsByTagName(OUTPUT_PORT_ELEMENT).item(0).toElement(); QDomNodeList outputs = doc.elementsByTagName(OUT_SLOT_ELEMENT); QList outputTypes; for(int i = 0; i < outputs.size(); i++) { QDomElement slot = outputs.item(i).toElement(); QString id = slot.attribute(SLOT_ID); outputTypes << dtr->getById(id); } //QDomElement attribute = doc.elementsByTagName(ATTRIBUTE_ELEMENT).item(0).toElement(); QDomNodeList attributes = doc.elementsByTagName(ATTR_ELEMENT); QListattrs; for(int i = 0;i < attributes.size(); i++) { QDomElement attr = attributes.item(i).toElement(); QString typeId = attr.attribute(TYPE_ID); QString name = attr.attribute(NAME_ID); DataTypePtr ptr = dtr->getById(typeId); Descriptor desc(name, name, ptr->getDisplayName()); if(ptr == BaseTypes::BOOL_TYPE()) { attrs << new Attribute(desc, ptr, false, QVariant(false)); } else { attrs << new Attribute(desc, ptr); } } QDomElement name = doc.elementsByTagName(NAME_ELEMENT).item(0).toElement(); QString actorName = name.attribute(NAME_ID); QDomElement descr = doc.elementsByTagName(DESCR_ELEMENT).item(0).toElement(); QString actorDesc = descr.attribute(DESCR_ID); ScriptWorkerFactory::init(inputTypes, outputTypes, attrs, actorName, actorDesc); } } void CoreLib::initExternalToolsWorkers() { QString path = WorkflowSettings::getExternalToolDirectory(); QDir dir(path); if(!dir.exists()) { return; } dir.setNameFilters(QStringList() << "*.etc"); QFileInfoList fileList = dir.entryInfoList(); foreach(const QFileInfo& fileInfo, fileList) { QString url = fileInfo.filePath(); QFile file(url); file.open(QIODevice::ReadOnly); QString data = file.readAll().data(); ExternalProcessConfig *cfg = NULL; cfg = HRSchemaSerializer::string2Actor(data); if(cfg) { ExternalProcessWorkerFactory::init(cfg); } file.close(); } } } // Workflow namespace } // U2 namespace ugene-1.9.8/src/plugins/workflow_designer/src/library/GenericReadWorker.h0000644000175000017500000000542311651544325025274 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_WORKFLOW_READ_SEQ_WORKER_H_ #define _U2_WORKFLOW_READ_SEQ_WORKER_H_ #include #include #include namespace U2 { namespace LocalWorkflow { class DNASelector { public: //DNASelector(const QString& acc):acc(acc){} bool matches(const DNASequence&); QString acc; }; class LoadSeqTask : public Task { Q_OBJECT public: LoadSeqTask(QString url, const QVariantMap& cfg, DNASelector* sel) : Task(tr("Read sequences from %1").arg(url), TaskFlag_None), url(url), selector(sel), cfg(cfg) {} virtual void prepare(); virtual void run(); QString url; DNASelector *selector; QVariantMap cfg; QList results; }; class LoadMSATask : public Task { Q_OBJECT public: LoadMSATask(QString url) : Task(tr("Read MSA from %1").arg(url), TaskFlag_None), url(url) {} virtual void prepare(); virtual void run(); QString url; QList results; }; class GenericMSAReader : public BaseWorker { Q_OBJECT public: GenericMSAReader(Actor* a) : BaseWorker(a), ch(NULL), done(false) {} virtual void init() ; virtual bool isReady(); virtual Task* tick() ; virtual bool isDone() ; virtual void cleanup() {} protected slots: virtual void sl_taskFinished(); protected: virtual Task* createReadTask(const QString& url) {return new LoadMSATask(url);} CommunicationChannel* ch; QList urls; bool done; QList cache; DataTypePtr mtype; }; class GenericSeqReader : public GenericMSAReader { Q_OBJECT public: GenericSeqReader(Actor* a) : GenericMSAReader(a){} virtual void init() ; protected slots: virtual void sl_taskFinished(); protected: virtual Task* createReadTask(const QString& url) {return new LoadSeqTask(url, cfg, &selector);} QVariantMap cfg; DNASelector selector; }; } // Workflow namespace } // U2 namespace #endif ugene-1.9.8/src/plugins/workflow_designer/src/library/ExternalProcessWorker.cpp0000644000175000017500000005167511651544325026612 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "ExternalProcessWorker.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include namespace U2 { namespace LocalWorkflow { const static QString INPUT_PORT_TYPE("input-for-"); const static QString OUTPUT_PORT_TYPE("output-for-"); static const QString OUT_PORT_ID("out"); bool ExternalProcessWorkerFactory::init(ExternalProcessConfig *cfg) { DataTypeRegistry *dtr = WorkflowEnv::getDataTypeRegistry(); QList portDescs; foreach(const DataConfig& dcfg, cfg->inputs) { QMap map; if(dcfg.type == SEQ_WITH_ANNS) { map[BaseSlots::DNA_SEQUENCE_SLOT()] = BaseTypes::DNA_SEQUENCE_TYPE(); map[BaseSlots::ANNOTATION_TABLE_SLOT()] = BaseTypes::ANNOTATION_TABLE_TYPE(); } else { map[WorkflowUtils::getSlotDescOfDatatype(dtr->getById(dcfg.type))] = dtr->getById(dcfg.type); } DataTypePtr input( new MapDataType(Descriptor(INPUT_PORT_TYPE + dcfg.attrName), map) ); DataTypeRegistry * dr = WorkflowEnv::getDataTypeRegistry(); assert(dr); dr->registerEntry( input ); portDescs << new PortDescriptor(Descriptor(dcfg.attrName, dcfg.attrName, dcfg.description), input, true); } QMap map; foreach(const DataConfig& dcfg, cfg->outputs) { if(dcfg.type == SEQ_WITH_ANNS) { map[BaseSlots::ANNOTATION_TABLE_SLOT()] = BaseTypes::ANNOTATION_TABLE_TYPE(); map[BaseSlots::DNA_SEQUENCE_SLOT()] = BaseTypes::DNA_SEQUENCE_TYPE(); } else { map[WorkflowUtils::getSlotDescOfDatatype(dtr->getById(dcfg.type))] = dtr->getById(dcfg.type); } } if(!map.isEmpty()) { DataTypePtr outSet( new MapDataType(Descriptor(OUTPUT_PORT_TYPE + cfg->name), map) ); DataTypeRegistry * dr = WorkflowEnv::getDataTypeRegistry(); assert(dr); dr->registerEntry( outSet ); Descriptor outDesc( OUT_PORT_ID, ExternalProcessWorker::tr("output data"), ExternalProcessWorker::tr("output data") ); portDescs << new PortDescriptor( outDesc, outSet, false, true ); } Descriptor desc( cfg->name, cfg->name, cfg->description.isEmpty() ? cfg->name : cfg->description ); QList attribs; QMap delegates; foreach(const AttributeConfig& acfg, cfg->attrs) { //PropertyDelegate *delegate = NULL; DataTypePtr type; QString descr = acfg.description.isEmpty() ? acfg.type : acfg.description; if(acfg.type == "URL") { type = BaseTypes::STRING_TYPE(); delegates[acfg.attrName] = new URLDelegate("All Files(*.*)",""); attribs << new Attribute(Descriptor(acfg.attrName, acfg.attrName, descr), type); } else if(acfg.type == "String") { type = BaseTypes::STRING_TYPE(); attribs << new Attribute(Descriptor(acfg.attrName, acfg.attrName, descr), type); } else if(acfg.type == "Number") { type = BaseTypes::NUM_TYPE(); attribs << new Attribute(Descriptor(acfg.attrName, acfg.attrName, descr), type); } else if(acfg.type == "Boolean") { type = BaseTypes::BOOL_TYPE(); attribs << new Attribute(Descriptor(acfg.attrName, acfg.attrName, descr), type, false, QVariant(false)); } //attribs << new Attribute(Descriptor(acfg.attrName, acfg.attrName, acfg.type), type); /*if(delegate) { delegates[acfg.attrName] = acfg.delegate; }*/ } ActorPrototype * proto = new IntegralBusActorPrototype( desc, portDescs, attribs ); proto->setEditor(new DelegateEditor(delegates)); proto->setIconPath(":workflow_designer/images/external_cmd_tool.png"); proto->setPrompter( new ExternalProcessWorkerPrompter() ); WorkflowEnv::getProtoRegistry()->registerProto(BaseActorCategories::CATEGORY_EXTERNAL(), proto); DomainFactory* localDomain = WorkflowEnv::getDomainRegistry()->getById( LocalDomainFactory::ID ); WorkflowEnv::getExternalCfgRegistry()->registerExternalTool(cfg); localDomain->registerEntry( new ExternalProcessWorkerFactory(cfg->name) ); return true; } const QString ExternalProcessWorker::generateURL(const QString &extention, const QString &name) { QString url; QString path = AppContext::getAppSettings()->getUserAppsSettings()->getTemporaryDirPath(); url = path + "/tmp" + name + QString::number(QDateTime::currentDateTime().toTime_t()) + "." + extention; return url; } Task* ExternalProcessWorker::tick() { if(busy) { return NULL; } busy = true; QString execString = commandLine; foreach(Attribute *a, actor->getAttributes()) { int i = execString.indexOf(QRegExp("\\$" + a->getDisplayName() + "(\\W|$)")); if(i != -1) { //commandLine.replace("$" + a->getDisplayName(), a->getAttributeValue()); //set parameters in command line with attributes values execString.replace(i, a->getDisplayName().size() + 1 , a->getAttributeValue()); //set parameters in command line with attributes values } } int i = 0; foreach(const DataConfig& dataCfg, cfg->inputs) { //write all input data to files DocumentFormat *f = AppContext::getDocumentFormatRegistry()->getFormatById(dataCfg.format); IOAdapterFactory *io = AppContext::getIOAdapterRegistry()->getIOAdapterFactoryById(BaseIOAdapters::LOCAL_FILE); QString url = generateURL(f->getSupportedDocumentFileExtensions().first(), dataCfg.attrName); inputUrls << url; /*Document *d = new Document(f, io, url); d->setLoaded(true);*/ Document *d = NULL; Message inputMessage = getMessageAndSetupScriptValues(inputs[i]); QList l; QVariantMap qm = inputMessage.getData().toMap(); if(dataCfg.type == BaseTypes::DNA_SEQUENCE_TYPE()->getId()) { DNASequence seq = qm.value(BaseSlots::DNA_SEQUENCE_SLOT().getId()).value(); //d->addObject(new DNASequenceObject(seq.getName(), seq)); l << new DNASequenceObject(seq.getName(), seq); d = new Document(f, io, url, l); } else if(dataCfg.type == BaseTypes::ANNOTATION_TABLE_TYPE()->getId()) { QList anns = qm.value(BaseSlots::ANNOTATION_TABLE_SLOT().getId()).value >(); AnnotationTableObject * aobj = new AnnotationTableObject("anns"); foreach(SharedAnnotationData ann, anns) { QStringList list; aobj->addAnnotation(new Annotation(ann)); } l << aobj; //d->addObject(aobj); d = new Document(f, io, url, l); } else if(dataCfg.type == BaseTypes::MULTIPLE_ALIGNMENT_TYPE()->getId()) { MAlignment ma = qm.value(BaseSlots::MULTIPLE_ALIGNMENT_SLOT().getId()).value(); l << new MAlignmentObject(ma); //d->addObject(new MAlignmentObject(ma)); d = new Document(f, io, url, l); } else if(dataCfg.type == SEQ_WITH_ANNS) { DNASequence seq = qm.value(BaseSlots::DNA_SEQUENCE_SLOT().getId()).value(); DNASequenceObject*dnaObj = new DNASequenceObject(seq.getName(), seq); //d->addObject(dnaObj); l << dnaObj; QList anns = qm.value(BaseSlots::ANNOTATION_TABLE_SLOT().getId()).value >(); AnnotationTableObject * aobj = new AnnotationTableObject("anns"); foreach(SharedAnnotationData ann, anns) { QStringList list; aobj->addAnnotation(new Annotation(ann)); } l << aobj; d = new Document(f, io, url, l); QList rel; rel << GObjectRelation(GObjectReference(dnaObj), GObjectRelationRole::SEQUENCE); aobj->setObjectRelations(rel); } else if(dataCfg.type == BaseTypes::STRING_TYPE()->getId()) { QString str = qm.value(BaseSlots::TEXT_SLOT().getId()).value(); TextObject *obj = new TextObject(str, "tmp_text_object"); l << obj; d = new Document(f, io, url, l); } //TODO: document can be NULL here!!! //IOAdapterFactory *io = AppContext::getIOAdapterRegistry()->getIOAdapterFactoryById(BaseIOAdapters::LOCAL_FILE); //QString url = generateURL(f->getSupportedDocumentFileExtensions().first(), dataCfg.attrName); //inputUrls << url; //Document *d = new Document(f, io, url, l); TaskStateInfo ts; f->storeDocument(d, ts, io); int ind = execString.indexOf(QRegExp("\\$" + dataCfg.attrName + "(\\W|$)")); if(ind != -1) { execString.replace(ind, dataCfg.attrName.size() + 1 , url); } //commandLine.replace("$" + dataCfg.attrName, url); delete d; i++; } foreach(const DataConfig &dataCfg, cfg->outputs) { QString url1 = generateURL(AppContext::getDocumentFormatRegistry()->getFormatById(dataCfg.format)->getSupportedDocumentFileExtensions().first(), dataCfg.attrName); outputUrls.insert(url1, dataCfg); int ind = execString.indexOf(QRegExp("\\$" + dataCfg.attrName + "(\\W|$)")); if(ind != -1) { execString.replace(ind, dataCfg.attrName.size() + 1 , "\"" + url1 + "\""); } //commandLine.replace("$" + dataCfg.attrName, url1); } LaunchExternalToolTask *task = new LaunchExternalToolTask(execString); connect(task, SIGNAL(si_stateChanged()), SLOT(sl_onTaskFinishied())); return task; } void ExternalProcessWorker::sl_onTaskFinishied() { Task *t = static_cast(sender()); if(output && t->isFinished() && !t->hasError()) { QMap::iterator i; QVariantMap v; for(i = outputUrls.begin(); i != outputUrls.end(); i++) { DataConfig cfg = i.value(); QString url = i.key(); DocumentFormat *f = AppContext::getDocumentFormatRegistry()->getFormatById(cfg.format); IOAdapterFactory *io = AppContext::getIOAdapterRegistry()->getIOAdapterFactoryById(BaseIOAdapters::LOCAL_FILE); TaskStateInfo ts; Document * d = f->loadDocument(io, url,ts, QVariantMap()); if(d == NULL) { //coreLog.error(tr("Can't open document")); bool isEnded = true; foreach(CommunicationChannel *ch, inputs) { isEnded = isEnded && ch->isEnded(); } if(isEnded) { output->setEnded(); done = true; } busy = false; QFile::remove(url); outputUrls.clear(); return; } if(cfg.type == BaseTypes::DNA_SEQUENCE_TYPE()->getId()){ DNASequenceObject *obj = static_cast(d->findGObjectByType(GObjectTypes::SEQUENCE, UOF_LoadedAndUnloaded).first()); DataTypePtr dataType = WorkflowEnv::getDataTypeRegistry()->getById(cfg.type); v[WorkflowUtils::getSlotDescOfDatatype(dataType).getId()] = qVariantFromValue(obj->getDNASequence()); } else if(cfg.type == BaseTypes::MULTIPLE_ALIGNMENT_TYPE()->getId()) { MAlignmentObject *obj = static_cast (d->findGObjectByType(GObjectTypes::MULTIPLE_ALIGNMENT, UOF_LoadedAndUnloaded).first()); DataTypePtr dataType = WorkflowEnv::getDataTypeRegistry()->getById(cfg.type); v[WorkflowUtils::getSlotDescOfDatatype(dataType).getId()] = qVariantFromValue(obj->getMAlignment()); } else if(cfg.type == BaseTypes::ANNOTATION_TABLE_TYPE()->getId()) { AnnotationTableObject *obj = static_cast(d->findGObjectByType(GObjectTypes::ANNOTATION_TABLE, UOF_LoadedAndUnloaded).first()); QList list; foreach(Annotation* a, obj->getAnnotations()) { list << a->data(); } DataTypePtr dataType = WorkflowEnv::getDataTypeRegistry()->getById(cfg.type); v[WorkflowUtils::getSlotDescOfDatatype(dataType).getId()] = qVariantFromValue(list); } else if(cfg.type == SEQ_WITH_ANNS) { if(!d->findGObjectByType(GObjectTypes::SEQUENCE, UOF_LoadedAndUnloaded).isEmpty()) { DNASequenceObject *seqObj = static_cast(d->findGObjectByType(GObjectTypes::SEQUENCE, UOF_LoadedAndUnloaded).first()); DNASequence seq = seqObj->getSequence(); seq.alphabet = AppContext::getDNAAlphabetRegistry()->findById(BaseDNAAlphabetIds::RAW()); v[BaseSlots::DNA_SEQUENCE_SLOT().getId()] = qVariantFromValue(seq); } if(!d->findGObjectByType(GObjectTypes::ANNOTATION_TABLE, UOF_LoadedAndUnloaded).isEmpty()) { AnnotationTableObject *obj = static_cast(d->findGObjectByType(GObjectTypes::ANNOTATION_TABLE, UOF_LoadedAndUnloaded).first()); QList list; foreach(Annotation* a, obj->getAnnotations()) { list << a->data(); } v[BaseSlots::ANNOTATION_TABLE_SLOT().getId()] = qVariantFromValue(list); } } else if(cfg.type == BaseTypes::STRING_TYPE()->getId()) { if(!d->findGObjectByType(GObjectTypes::TEXT, UOF_LoadedAndUnloaded).isEmpty()) { TextObject *obj = static_cast(d->findGObjectByType(GObjectTypes::TEXT, UOF_LoadedAndUnloaded).first()); DataTypePtr dataType = WorkflowEnv::getDataTypeRegistry()->getById(cfg.type); v[WorkflowUtils::getSlotDescOfDatatype(dataType).getId()] = qVariantFromValue(obj->getText()); } } QFile::remove(url); } outputUrls.clear(); DataTypePtr dataType = WorkflowEnv::getDataTypeRegistry()->getById(OUTPUT_PORT_TYPE + cfg->name); output->put(Message(dataType, v)); bool isEnded = true; foreach(CommunicationChannel *ch, inputs) { isEnded = isEnded && ch->isEnded(); } if(isEnded) { output->setEnded(); done = true; } } else { bool res = true; foreach(const CommunicationChannel *ch, inputs) { if(ch) { res = res && ch->hasMessage(); } } done = !res; } busy = false; } void ExternalProcessWorker::init() { foreach(const DataConfig& input, cfg->inputs) { inputs << ports.value(input.attrName); } output = ports.value(OUT_PORT_ID); } bool ExternalProcessWorker::isReady() { if(inputs.isEmpty()) { return !done; } else { bool res = true; foreach(const CommunicationChannel *ch, inputs) { if(ch) { res = res && ch->hasMessage(); } } return res; } } bool ExternalProcessWorker::isDone() { /*bool res = true; foreach(CommunicationChannel *ch, inputs) { res = res && ch->isEnded(); }*/ return done; } void ExternalProcessWorker::cleanup() { foreach(const QString& url, inputUrls) { if(QFile::exists(url)) { QFile::remove(url); } } foreach(const QString& url, outputUrls.keys()) { if(QFile::exists(url)) { QFile::remove(url); } } } LaunchExternalToolTask::LaunchExternalToolTask(const QString &_execString): Task("Launch external process task", TaskFlag_None), execString(_execString) { } void LaunchExternalToolTask::run() { QProcess *externalProcess = new QProcess(); if(execString.contains(">")) { QString output = execString.split(">").last(); output = output.trimmed(); if(output.at(0) == '\"') { output = output.mid(1, output.length() - 2); } execString = execString.split(">").first(); externalProcess->setStandardOutputFile(output); } externalProcess->start(execString); if(!externalProcess->waitForStarted(3000)) { stateInfo.setError(tr("Can't launch %1").arg(execString)); return; } while(!externalProcess->waitForFinished(1000)) { if(isCanceled()) { externalProcess->kill(); } } } QString ExternalProcessWorkerPrompter::composeRichDoc() { ExternalProcessConfig *cfg = WorkflowEnv::getExternalCfgRegistry()->getConfigByName(target->getProto()->getId()); assert(cfg); QString doc = cfg->templateDescription; foreach(const DataConfig& dataCfg, cfg->inputs) { QRegExp param("\\$" + dataCfg.attrName + /*"[,:;\s\.\-]"*/"\\W|$"); if(doc.contains(param)) { IntegralBusPort* input = qobject_cast(target->getPort(dataCfg.attrName)); DataTypePtr dataType = WorkflowEnv::getDataTypeRegistry()->getById(dataCfg.type); if(dataCfg.type == SEQ_WITH_ANNS) { dataType = BaseTypes::DNA_SEQUENCE_TYPE(); } Actor* producer = input->getProducer(WorkflowUtils::getSlotDescOfDatatype(dataType).getId()); QString unsetStr = ""+tr("unset")+""; QString producerName = tr("%1").arg(producer ? producer->getLabel() : unsetStr); doc.replace("$" + dataCfg.attrName, producerName); } } foreach(const DataConfig& dataCfg, cfg->outputs) { QRegExp param("\\$" + dataCfg.attrName + /*"[,:;\s\.\-]"*/"\\W|$"); if(doc.contains(param)) { IntegralBusPort* output = qobject_cast(target->getPort(OUT_PORT_ID)); DataTypePtr dataType = WorkflowEnv::getDataTypeRegistry()->getById(dataCfg.type); if(dataCfg.type == SEQ_WITH_ANNS) { dataType = BaseTypes::DNA_SEQUENCE_TYPE(); } QString destinations; QString unsetStr = ""+tr("unset")+""; if(!output->getLinks().isEmpty()) { foreach(Port *p, output->getLinks().keys()) { IntegralBusPort* ibp = qobject_cast(p); Actor *dest = ibp->owner(); destinations += tr("%1").arg(dest ? dest->getLabel() : unsetStr) + ","; } } if(destinations.isEmpty()) { destinations = tr("%1").arg(unsetStr); } else { destinations.resize(destinations.size() - 1); //remove last semicolon } doc.replace("$" + dataCfg.attrName, destinations); } } foreach(const AttributeConfig &attrCfg, cfg->attrs) { QRegExp param("\\$" + attrCfg.attrName + /*"[,:;\s\.\-]"*/"\\W|$"); if(doc.contains(param)) { QString prm = getRequiredParam(attrCfg.attrName); doc.replace("$" + attrCfg.attrName, getHyperlink(attrCfg.attrName, prm)); } } return doc; } } } ugene-1.9.8/src/plugins/workflow_designer/src/library/FilterAnnotationsWorker.h0000644000175000017500000000477611651544325026601 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_FILTER_ANNOTATIONS_WORKER_H_ #define _U2_FILTER_ANNOTATIONS_WORKER_H_ #include #include #include namespace U2 { namespace LocalWorkflow { class FilterAnnotationsPrompter : public PrompterBase { Q_OBJECT public: FilterAnnotationsPrompter(Actor* p = 0) : PrompterBase(p) {} protected: QString composeRichDoc(); }; class FilterAnnotationsWorker : public BaseWorker { Q_OBJECT public: FilterAnnotationsWorker(Actor* a) : BaseWorker(a), input(NULL), output(NULL) {}; virtual void init(); virtual bool isReady(); virtual Task* tick(); virtual bool isDone(); virtual void cleanup(); private slots: void sl_taskFinished(); private: CommunicationChannel *input, *output; QList inputAnns; }; class FilterAnnotationsWorkerFactory : public DomainFactory { public: static const QString ACTOR_ID; static void init(); FilterAnnotationsWorkerFactory() : DomainFactory(ACTOR_ID) {} virtual Worker* createWorker(Actor* a) { return new FilterAnnotationsWorker(a); } }; class FilterAnnotationsTask : public Task { Q_OBJECT public: FilterAnnotationsTask(QList& annotations, const QString& names, bool accept) : Task(tr("Filter annotations task"), TaskFlag_None), annotations_(annotations), names_(names), accept_(accept) {} void run(); private: QStringList readAnnotationNames(); private: QList& annotations_; QString names_; bool accept_; }; } // LocalWorkflow namespace } // U2 namespace #endif ugene-1.9.8/src/plugins/workflow_designer/src/library/StatisticWorkers.h0000644000175000017500000000226711651544325025261 0ustar ilyailya#ifndef _STATISTIC_WORKERS_H_ #define _STATISTIC_WORKERS_H_ #include #include namespace U2 { namespace LocalWorkflow { class DNAStatWorker:public BaseWorker { Q_OBJECT public: DNAStatWorker(Actor* a) : BaseWorker(a), input(NULL), output(NULL) {} virtual void init(); virtual bool isReady(); virtual Task* tick(); virtual bool isDone(); virtual void cleanup() {}; private: float calcGCContent(const QByteArray &seq); float calcGC1Content(const QByteArray &seq); float calcGC2Content(const QByteArray &seq); float calcGC3Content(const QByteArray &seq); CommunicationChannel *input, *output; }; class DNAStatWorkerFactory: public DomainFactory { public: static const QString ACTOR_ID; static void init(); DNAStatWorkerFactory() : DomainFactory(ACTOR_ID) {} virtual Worker* createWorker(Actor* a) { return new DNAStatWorker(a); } }; class DNAStatWorkerPrompter: public PrompterBase { Q_OBJECT public: DNAStatWorkerPrompter(Actor* p = 0) : PrompterBase(p) {} protected: QString composeRichDoc(); }; }//LocalWorkflow }//U2 #endifugene-1.9.8/src/plugins/workflow_designer/src/library/SequencesToMSAWorker.cpp0000644000175000017500000001114311651544325026252 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "SequencesToMSAWorker.h" #include #include #include #include #include #include #include #include #include namespace U2 { namespace LocalWorkflow { QString SequencesToMSAPromter::composeRichDoc() { return tr("Creates multiple sequence alignment from supplied sequences."); } void SequencesToMSAWorker::init() { inPort = ports.value(BasePorts::IN_SEQ_PORT_ID()); outPort = ports.value(BasePorts::OUT_MSA_PORT_ID()); } bool SequencesToMSAWorker::isReady() { return inPort->hasMessage(); } bool SequencesToMSAWorker::isDone() { return outPort->isEnded();; } void SequencesToMSAWorker::cleanup() {} Task* SequencesToMSAWorker::tick() { Message inputMessage = getMessageAndSetupScriptValues(inPort); QVariantMap qm = inputMessage.getData().toMap(); DNASequence seq = qVariantValue< DNASequence >( qm.value(BaseSlots::DNA_SEQUENCE_SLOT().getId()) ); data.append(seq); if (inPort->isEnded()) { Task* t = new MSAFromSequencesTask(data); connect(new TaskSignalMapper(t), SIGNAL(si_taskFinished(Task*)), SLOT(sl_onTaskFinished(Task*))); return t; } return NULL; } void MSAFromSequencesTask::run() { DNASequence seq = sequences_.first(); ma.setAlphabet(seq.alphabet); ma.addRow( MAlignmentRow(seq.getName(),seq.seq) ); for (int i=1; i(t); MAlignment ma = maTask->getResult(); outPort->put( Message(BaseTypes::MULTIPLE_ALIGNMENT_TYPE(), qVariantFromValue(ma)) ); if (inPort->isEnded()) { outPort->setEnded(); } } const QString SequencesToMSAWorkerFactory::ACTOR_ID("sequences-to-msa"); void SequencesToMSAWorkerFactory::init() { QList p; QList a; { Descriptor id(BasePorts::IN_SEQ_PORT_ID(), SequencesToMSAWorker::tr("Input sequences"), SequencesToMSAWorker::tr("Sequences to be joined into alignment.")); Descriptor od(BasePorts::OUT_MSA_PORT_ID(), SequencesToMSAWorker::tr("Result alignment"), SequencesToMSAWorker::tr("Alignment created from the given sequences.")); QMap inM; inM[BaseSlots::DNA_SEQUENCE_SLOT()] = BaseTypes::DNA_SEQUENCE_TYPE(); p << new PortDescriptor(id, DataTypePtr(new MapDataType("seq2msa.seq", inM)), true /*input*/); QMap outM; outM[BaseSlots::MULTIPLE_ALIGNMENT_SLOT()] = BaseTypes::MULTIPLE_ALIGNMENT_TYPE(); p << new PortDescriptor(od, DataTypePtr(new MapDataType("seq2msa.msa", outM)), false /*input*/, true /*multi*/); } Descriptor desc( SequencesToMSAWorkerFactory::ACTOR_ID, SequencesToMSAWorker::tr("Join sequences into alignment"), SequencesToMSAWorker::tr("Creates multiple sequence alignment from sequences.") ); ActorPrototype * proto = new IntegralBusActorPrototype( desc, p, QList() ); proto->setEditor(new DelegateEditor(QMap())); proto->setPrompter( new SequencesToMSAPromter() ); WorkflowEnv::getProtoRegistry()->registerProto( BaseActorCategories::CATEGORY_ALIGNMENT(), proto ); DomainFactory* localDomain = WorkflowEnv::getDomainRegistry()->getById( LocalDomainFactory::ID ); localDomain->registerEntry( new SequencesToMSAWorkerFactory() ); } } //LocalWorkflow namespace } //U2 namespace ugene-1.9.8/src/plugins/workflow_designer/src/library/SequenceSplitWorker.cpp0000644000175000017500000002671311651544325026250 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "SequenceSplitWorker.h" #include "GenericReadActor.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include namespace U2 { namespace LocalWorkflow { const QString SequenceSplitWorkerFactory::ACTOR("extract-annotated-sequence"); const static QString REGIONED_SEQ_TYPE("regioned.sequence"); const static QString TRANSLATE_ATTR( "translate" ); const static QString COMPLEMENT_ATTR( "complement" ); const static QString EXTEND_LEFT_ATTR( "extend-left" ); const static QString EXTEND_RIGHT_ATTR( "extend-right" ); const static QString GAP_LENGTH_ATTR( "merge-gap-length" ); QString SequenceSplitPromter::composeRichDoc() { IntegralBusPort * input = qobject_cast ( target->getPort(BasePorts::IN_SEQ_PORT_ID()) ); Actor * seqProducer = input->getProducer( BaseSlots::DNA_SEQUENCE_SLOT().getId() ); QString unsetStr = ""+tr("unset")+""; QString seqProducerText = tr("from %1").arg(seqProducer ? seqProducer->getLabel() : unsetStr); //translate or not? bool translate = getParameter( TRANSLATE_ATTR ).toBool(); QString translateText; if (translate) { translateText = tr("%1 it if annotation marks translated subsequence, ") .arg(getHyperlink(TRANSLATE_ATTR, tr("translate"))); } //complement or not? bool complement = getParameter( COMPLEMENT_ATTR ).toBool(); QString complementText; if (complement) { complementText = tr("make it %1 if annotation is located on complement strand, ") .arg(getHyperlink(COMPLEMENT_ATTR, "reverse-complement")); } //expand QString expandText; int expandLeft = getParameter( EXTEND_LEFT_ATTR ).toInt(); int expandRight = getParameter( EXTEND_RIGHT_ATTR ).toInt(); if( expandLeft ) { expandText += tr("expand it to left with %1, ").arg(getHyperlink(EXTEND_LEFT_ATTR, expandLeft)); } if( expandRight ) { expandText += tr("expand it to right with %1").arg(getHyperlink(EXTEND_RIGHT_ATTR, expandRight)); } if( !expandRight && expandLeft ){ expandText.remove( expandText.size()-1, 2); } //merge result QString doc = tr("Extract each annotated sequence region %5 %2 %3%4") //.arg(filterText) .arg(complementText) .arg(translateText) .arg(expandText) .arg(seqProducerText); doc.remove( QRegExp("[\\,\\s]*$") ); //remove all commas and spaces from the end; doc.append("."); return doc; } void SequenceSplitWorker::init() { seqPort = ports.value(BasePorts::IN_SEQ_PORT_ID()); outPort = ports.value(BasePorts::OUT_SEQ_PORT_ID()); } bool SequenceSplitWorker::isReady() { return seqPort->hasMessage(); } Task * SequenceSplitWorker::tick() { Message inputMessage = getMessageAndSetupScriptValues(seqPort); cfg.translate = actor->getParameter( TRANSLATE_ATTR )->getAttributeValue(); cfg.complement = actor->getParameter( COMPLEMENT_ATTR )->getAttributeValue(); cfg.extLeft = actor->getParameter( EXTEND_LEFT_ATTR )->getAttributeValue(); cfg.extRight = actor->getParameter( EXTEND_RIGHT_ATTR )->getAttributeValue(); cfg.gapLength = actor->getParameter( GAP_LENGTH_ATTR )->getAttributeValue(); cfg.gapSym = '-'; //FIXME QVariantMap qm = inputMessage.getData().toMap(); DNASequence inputSeq = qm.value( BaseSlots::DNA_SEQUENCE_SLOT().getId() ).value(); inputAnns = qVariantValue >( qm.value(BaseSlots::ANNOTATION_TABLE_SLOT().getId()) ); bool noSeq = inputSeq.isNull(); bool noAnns = inputAnns.isEmpty(); if( noSeq || noAnns ) { //if( failFast ) { if( noSeq ) { return new FailTask( tr("No sequence provided to split worker") ); } else if( noAnns ) { return new FailTask( tr("Nothing to extract. No annotations provided to split worker") ); } else { assert(false); } // } outPort->put( Message(BaseTypes::ANNOTATION_TABLE_TYPE(), QVariant()) ); if( seqPort->isEnded() ) { outPort->setEnded(); } return 0; } ssTasks.clear(); foreach( SharedAnnotationData ann, inputAnns ) { Task * t = new ExtractAnnotatedRegionTask( inputSeq, ann, cfg ); ssTasks.push_back(t); } if( ssTasks.isEmpty() ) { return new FailTask(tr("Nothing to extract: no sequence region match the constraints")); } Task * t = new MultiTask( "Sequence split tasks", ssTasks ); connect( new TaskSignalMapper(t), SIGNAL(si_taskFinished(Task*)), SLOT(sl_onTaskFinished(Task*)) ); return t; } void SequenceSplitWorker::cleanup() { } bool SequenceSplitWorker::isDone() { return seqPort->isEnded(); } void SequenceSplitWorker::sl_onTaskFinished( Task * ) { int count = 0; foreach( Task * t, ssTasks ) { ExtractAnnotatedRegionTask * ssT = qobject_cast(t); assert( ssT ); DNASequence resSeq = ssT->getResultedSequence(); SharedAnnotationData resAnn = ssT->getResultedAnnotation(); QString name = resSeq.getName() + "|" + resAnn->name + "|" + QString::number(++count); resSeq.info[DNAInfo::ID] = name; QVariant vSeq = qVariantFromValue(resSeq); QList annToPut; annToPut.push_back( resAnn ); QVariant vAnns = qVariantFromValue >(annToPut); QVariantMap messageData; messageData[ BaseSlots::DNA_SEQUENCE_SLOT().getId() ] = vSeq; messageData[ BaseSlots::ANNOTATION_TABLE_SLOT().getId() ] = vAnns; DataTypePtr messageType = WorkflowEnv::getDataTypeRegistry()->getById( REGIONED_SEQ_TYPE ); if( outPort ) { outPort->put( Message(messageType, messageData) ); } } if( seqPort->isEnded() ) { outPort->setEnded(); } } void SequenceSplitWorkerFactory::init() { QList portDescs; QList attribs; //accept sequence and annotated regions as input QMap inputMap; inputMap[ BaseSlots::DNA_SEQUENCE_SLOT() ] = BaseTypes::DNA_SEQUENCE_TYPE(); inputMap[ BaseSlots::ANNOTATION_TABLE_SLOT() ] = BaseTypes::ANNOTATION_TABLE_TYPE(); DataTypePtr inSet( new MapDataType(Descriptor(REGIONED_SEQ_TYPE), inputMap) ); DataTypeRegistry * dr = WorkflowEnv::getDataTypeRegistry(); assert(dr); dr->registerEntry( inSet ); { //Create input port descriptors Descriptor seqDesc( BasePorts::IN_SEQ_PORT_ID(), SequenceSplitWorker::tr("Input sequence"), SequenceSplitWorker::tr("A sequence which will be split into annotated regions.") ); Descriptor outDesc( BasePorts::OUT_SEQ_PORT_ID(), SequenceSplitWorker::tr("Annotated regions"), SequenceSplitWorker::tr("Resulted subsequences, translated and complemented according to corresponding annotations.") ); portDescs << new PortDescriptor( seqDesc, inSet, /*input*/ true ); portDescs << new PortDescriptor( outDesc, inSet, /*input*/false, /*multi*/true ); } { //Create attributes descriptors Descriptor translateDesc( TRANSLATE_ATTR, SequenceSplitWorker::tr("Translate"), SequenceSplitWorker::tr("Translate the annotated regions.") ); Descriptor complementDesc( COMPLEMENT_ATTR, SequenceSplitWorker::tr("Complement"), SequenceSplitWorker::tr("Complement the annotated regions if the corresponding annotation is located on complement strand.") ); Descriptor extendLeftDesc( EXTEND_LEFT_ATTR, SequenceSplitWorker::tr("Extend left"), SequenceSplitWorker::tr("Extend the resulted regions to left") ); Descriptor extendRightDesc( EXTEND_RIGHT_ATTR, SequenceSplitWorker::tr("Extend right"), SequenceSplitWorker::tr("Extend the resulted regions to right") ); Descriptor gapLengthDesc( GAP_LENGTH_ATTR, SequenceSplitWorker::tr("Gap length"), SequenceSplitWorker::tr("Insert gap of specified length between merged locations of annotation.") ); attribs << new Attribute( translateDesc, BaseTypes::BOOL_TYPE(), /*required*/ false, QVariant(false) ); attribs << new Attribute( complementDesc, BaseTypes::BOOL_TYPE(), /*required*/ false, QVariant(true) ); attribs << new Attribute( extendLeftDesc, BaseTypes::NUM_TYPE(), /*required*/ false, QVariant(0) ); attribs << new Attribute( extendRightDesc, BaseTypes::NUM_TYPE(), /*required*/ false, QVariant(0) ); attribs << new Attribute( gapLengthDesc, BaseTypes::NUM_TYPE(), false, QVariant(1) ); } Descriptor desc( SequenceSplitWorkerFactory::ACTOR, SequenceSplitWorker::tr("Get sequences by annotations"), SequenceSplitWorker::tr("Creates sequences from annotated regions of input sequence") ); ActorPrototype * proto = new IntegralBusActorPrototype( desc, portDescs, attribs ); //create delegates for attribute editing QMap delegates; { QVariantMap eMap; eMap["minimum"] = (0); eMap["maximum"] = (INT_MAX); delegates[EXTEND_LEFT_ATTR] = new SpinBoxDelegate( eMap ); delegates[EXTEND_RIGHT_ATTR] = new SpinBoxDelegate( eMap ); delegates[GAP_LENGTH_ATTR] = new SpinBoxDelegate( eMap ); } proto->setEditor( new DelegateEditor(delegates) ); // proto->setIconPath( "" ); proto->setPrompter( new SequenceSplitPromter() ); WorkflowEnv::getProtoRegistry()->registerProto( BaseActorCategories::CATEGORY_BASIC(), proto ); DomainFactory* localDomain = WorkflowEnv::getDomainRegistry()->getById( LocalDomainFactory::ID ); localDomain->registerEntry( new SequenceSplitWorkerFactory() ); } Worker * SequenceSplitWorkerFactory::createWorker( Actor * a ) { return new SequenceSplitWorker(a); } } //ns LocalWorkflow } //ns U2 ugene-1.9.8/src/plugins/workflow_designer/src/library/GenericReadWorker.cpp0000644000175000017500000003010511651544325025622 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "GenericReadWorker.h" #include "GenericReadActor.h" #include "CoreLib.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include namespace U2 { using namespace Workflow; namespace LocalWorkflow { /************************** * GenericMSAReader **************************/ void GenericMSAReader::init() { mtype = WorkflowEnv::getDataTypeRegistry()->getById(GenericMAActorProto::TYPE); urls = WorkflowUtils::expandToUrls(actor->getParameter(BaseAttributes::URL_IN_ATTRIBUTE().getId())->getAttributeValue()); assert(ports.size() == 1); ch = ports.values().first(); } bool GenericMSAReader::isReady() { return !isDone(); } Task* GenericMSAReader::tick() { if (cache.isEmpty() && !urls.isEmpty()) { Task* t = createReadTask(urls.takeFirst()); connect(t, SIGNAL(si_stateChanged()), SLOT(sl_taskFinished())); return t; } while (!cache.isEmpty()) { ch->put(cache.takeFirst()); } if (urls.isEmpty()) { done = true; ch->setEnded(); } return NULL; } bool GenericMSAReader::isDone() { return done && cache.isEmpty(); } void GenericMSAReader::sl_taskFinished() { LoadMSATask* t = qobject_cast(sender()); if (!t->isFinished() || t->hasError()) { return; } foreach(MAlignment ma, t->results) { QVariantMap m; m.insert(BaseSlots::URL_SLOT().getId(), t->url); m.insert(BaseSlots::MULTIPLE_ALIGNMENT_SLOT().getId(), qVariantFromValue(ma)); cache.append(Message(mtype, m)); } } /************************** * LoadMSATask **************************/ void LoadMSATask::prepare() { int memUseMB = 0; QFileInfo file(url); memUseMB = file.size() / (1024*1024); IOAdapterFactory* iof = AppContext::getIOAdapterRegistry()->getIOAdapterFactoryById(BaseIOAdapters::url2io(url)); if (iof->getAdapterId() == BaseIOAdapters::GZIPPED_LOCAL_FILE || iof->getAdapterId() == BaseIOAdapters::GZIPPED_HTTP_FILE) { memUseMB *= 2.5; //Need to calculate compress level } coreLog.trace(QString("load document:Memory resource %1").arg(memUseMB)); if (memUseMB > 0) { addTaskResource(TaskResourceUsage(RESOURCE_MEMORY, memUseMB, false)); } } void LoadMSATask::run() { QFileInfo fi(url); if(!fi.exists()){ stateInfo.setError( tr("File '%1' not exists").arg(url) ); return; } DocumentFormat* format = NULL; QList fs = DocumentUtils::toFormats(DocumentUtils::detectFormat(url)); foreach(DocumentFormat* f, fs) { if (f->getSupportedObjectTypes().contains(GObjectTypes::MULTIPLE_ALIGNMENT)) { format = f; break; } } if (format == NULL) { foreach(DocumentFormat* f, fs) { if (f->getSupportedObjectTypes().contains(GObjectTypes::SEQUENCE)) { format = f; break; } } } if (format == NULL) { stateInfo.setError( tr("Unsupported document format") ); return; } ioLog.info(tr("Reading MSA from %1 [%2]").arg(url).arg(format->getFormatName())); IOAdapterFactory* iof = AppContext::getIOAdapterRegistry()->getIOAdapterFactoryById(BaseIOAdapters::url2io(url)); Document *doc = format->loadDocument(iof, url, stateInfo, QVariantMap()); assert(isCanceled() || doc!=NULL || hasError()); assert(doc == NULL || doc->isLoaded()); if (!isCanceled() && doc!=NULL && doc->isLoaded()) { if (!doc->findGObjectByType(GObjectTypes::MULTIPLE_ALIGNMENT).isEmpty()) { foreach(GObject* go, doc->findGObjectByType(GObjectTypes::MULTIPLE_ALIGNMENT)) { results.append(((MAlignmentObject*)go)->getMAlignment()); } } else { MAlignment ma = MSAUtils::seq2ma(doc->findGObjectByType(GObjectTypes::SEQUENCE), stateInfo); if (!hasError()) { results.append(ma); } } } if (doc != NULL && doc->isLoaded()) { doc->unload(); } } /************************** * GenericSeqReader **************************/ void GenericSeqReader::init() { GenericMSAReader::init(); mtype = WorkflowEnv::getDataTypeRegistry()->getById(GenericSeqActorProto::TYPE); GenericSeqActorProto::Mode mode = GenericSeqActorProto::Mode(actor->getParameter( GenericSeqActorProto::MODE_ATTR)->getAttributeValue()); if (GenericSeqActorProto::MERGE == mode) { QString mergeToken = DocumentReadingMode_SequenceMergeGapSize; cfg[mergeToken] = actor->getParameter(GenericSeqActorProto::GAP_ATTR)->getAttributeValue(); } selector.acc = actor->getParameter(GenericSeqActorProto::ACC_ATTR)->getAttributeValue(); } void GenericSeqReader::sl_taskFinished() { LoadSeqTask* t = qobject_cast(sender()); if (!t->isFinished() || t->hasError()) { return; } foreach(const QVariantMap& m, t->results) { cache.append(Message(mtype, m)); } } /************************** * LoadSeqTask **************************/ void LoadSeqTask::prepare() { int memUseMB = 0; QFileInfo file(url); memUseMB = file.size() / (1024*1024); IOAdapterFactory* iof = AppContext::getIOAdapterRegistry()->getIOAdapterFactoryById(BaseIOAdapters::url2io(url)); if (iof->getAdapterId() == BaseIOAdapters::GZIPPED_LOCAL_FILE || iof->getAdapterId() == BaseIOAdapters::GZIPPED_HTTP_FILE) { memUseMB *= 2.5; //Need to calculate compress level } coreLog.trace(QString("load document:Memory resource %1").arg(memUseMB)); if (memUseMB > 0) { addTaskResource(TaskResourceUsage(RESOURCE_MEMORY, memUseMB, false)); } } void LoadSeqTask::run() { QFileInfo fi(url); if(!fi.exists()){ stateInfo.setError( tr("File '%1' not exists").arg(url) ); return; } QList fs = DocumentUtils::toFormats(DocumentUtils::detectFormat(url)); DocumentFormat* format = NULL; foreach( DocumentFormat * f, fs ) { const QSet& types = f->getSupportedObjectTypes(); if (types.contains(GObjectTypes::SEQUENCE) || types.contains(GObjectTypes::MULTIPLE_ALIGNMENT)) { format = f; break; } } if (format == NULL) { stateInfo.setError( tr("Unsupported document format") ); return; } ioLog.info(tr("Reading sequences from %1 [%2]").arg(url).arg(format->getFormatName())); IOAdapterFactory* iof = AppContext::getIOAdapterRegistry()->getIOAdapterFactoryById(BaseIOAdapters::url2io(url)); Document *doc = format->loadDocument(iof, url, stateInfo, cfg); assert(isCanceled() || doc!=NULL || hasError()); assert(doc == NULL || doc->isLoaded()); if (!isCanceled() && doc!=NULL && doc->isLoaded()) { const QSet& types = format->getSupportedObjectTypes(); if (types.contains(GObjectTypes::SEQUENCE)) { QList seqObjs = doc->findGObjectByType(GObjectTypes::SEQUENCE); QList annObjs = doc->findGObjectByType(GObjectTypes::ANNOTATION_TABLE); foreach(GObject* go, seqObjs) { assert(go != NULL); const DNASequence& dna = ((DNASequenceObject*)go)->getDNASequence(); if (!selector->matches(dna)) { continue; } QVariantMap m; m.insert(BaseSlots::URL_SLOT().getId(), url); m.insert(BaseSlots::DNA_SEQUENCE_SLOT().getId(), qVariantFromValue(dna)); QList allLoadedAnnotations = doc->findGObjectByType(GObjectTypes::ANNOTATION_TABLE); QList annotations = GObjectUtils::findObjectsRelatedToObjectByRole(go, GObjectTypes::ANNOTATION_TABLE, GObjectRelationRole::SEQUENCE, allLoadedAnnotations, UOF_LoadedOnly); if (!annotations.isEmpty()) { QList l; foreach(GObject * annGObj, annotations) { AnnotationTableObject* att = qobject_cast(annGObj); foreach(Annotation* a, att->getAnnotations()) { l << a->data(); } annObjs.removeAll(annGObj); } m.insert(BaseSlots::ANNOTATION_TABLE_SLOT().getId(), qVariantFromValue >(l)); } results.append(m); } // if there are annotations that are not connected to a sequence -> put them independently foreach(GObject * annObj, annObjs) { AnnotationTableObject* att = qobject_cast(annObj); if(att->findRelatedObjectsByRole(GObjectRelationRole::SEQUENCE).isEmpty()) { assert(att != NULL); QVariantMap m; m.insert(BaseSlots::URL_SLOT().getId(), url); QList l; foreach(Annotation* a, att->getAnnotations()) { l << a->data(); } m.insert(BaseSlots::ANNOTATION_TABLE_SLOT().getId(), qVariantFromValue >(l)); results.append(m); } } } else { //TODO merge seqs from alignment // QString mergeToken = MERGE_MULTI_DOC_GAP_SIZE_SETTINGS; // bool merge = cfg.contains(mergeToken); // int gaps = cfg.value(mergeToken).toInt(); foreach(GObject* go, doc->findGObjectByType(GObjectTypes::MULTIPLE_ALIGNMENT)) { foreach(const DNASequence& s, MSAUtils::ma2seq(((MAlignmentObject*)go)->getMAlignment(), false)) { if (!selector->matches(s)) { continue; } QVariantMap m; m.insert(BaseSlots::URL_SLOT().getId(), url); m.insert(BaseSlots::DNA_SEQUENCE_SLOT().getId(), qVariantFromValue(s)); results.append(m); } } } } if (doc!=NULL && doc->isLoaded()) { doc->unload(); } } /************************** * DNASelector **************************/ bool DNASelector::matches( const DNASequence& dna) { if (acc.isEmpty()) { return true; } if (dna.info.contains(DNAInfo::ACCESSION)) { return dna.info.value(DNAInfo::ACCESSION).toStringList().contains(acc); } return acc == dna.getName(); } } // Workflow namespace } // U2 namespace ugene-1.9.8/src/plugins/workflow_designer/src/library/ReverseComplementWorker.cpp0000644000175000017500000001270211651544325027114 0ustar ilyailya#include "ReverseComplementWorker.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "CoreLib.h" namespace U2 { namespace LocalWorkflow { const QString RCWorkerFactory::ACTOR_ID = QString("reverse-complement"); const QString OP_TYPE("op-type"); enum OpType { Reverse, Complement, ReverseComplement }; void RCWorkerFactory::init() { QList p; QList attrs; Descriptor ind(BasePorts::IN_SEQ_PORT_ID(), RCWorker::tr("Input sequence"), RCWorker::tr("The sequence to be complemented")); Descriptor outd(BasePorts::OUT_SEQ_PORT_ID(), RCWorker::tr("Output sequence"), RCWorker::tr("Reverse-complement sequence")); QMap inM; inM[BaseSlots::DNA_SEQUENCE_SLOT()] = BaseTypes::DNA_SEQUENCE_TYPE(); p << new PortDescriptor(ind, DataTypePtr(new MapDataType("rc.input.sequence", inM)), true); QMap outM; //outM[BaseSlots::DNA_SEQUENCE_SLOT()] = BaseTypes::DNA_SEQUENCE_TYPE(); p << new PortDescriptor(outd, DataTypePtr(new MapDataType("rc.outpur.sequence", inM)), false, true); Descriptor opType(OP_TYPE,RCWorker::tr("Operation type"), RCWorker::tr("Select what to do with sequence")); attrs << new Attribute(opType, BaseTypes::STRING_TYPE(),true,"reverse-complement"); Descriptor desc(ACTOR_ID, RCWorker::tr("Reverse Complement"), RCWorker::tr("Converts input sequence into its reverse, complement or reverse-complement counterpart") ); ActorPrototype* proto = new IntegralBusActorPrototype(desc, p, attrs); QMap delegates; QVariantMap m; m["Reverse Complement"] = "reverse-complement"; m["Reverse"] = "nocompl"; m["Complement"] = "norev"; delegates[OP_TYPE] = new ComboBoxDelegate(m); proto->setPrompter(new RCWorkerPrompter()); proto->setEditor(new DelegateEditor(delegates)); WorkflowEnv::getProtoRegistry()->registerProto(BaseActorCategories::CATEGORY_CONVERTERS(), proto); DomainFactory* localDomain = WorkflowEnv::getDomainRegistry()->getById(LocalDomainFactory::ID); localDomain->registerEntry(new RCWorkerFactory()); } QString RCWorkerPrompter::composeRichDoc() { IntegralBusPort* input = qobject_cast(target->getPort(BasePorts::IN_SEQ_PORT_ID())); Actor* producer = input->getProducer(BaseSlots::DNA_SEQUENCE_SLOT().getId()); QString unsetStr = ""+tr("unset")+""; QString producerName = tr(" from %1").arg(producer ? producer->getLabel() : unsetStr); QString type = getRequiredParam(OP_TYPE); QString op = type == "norev" ? "complement" : type == "nocompl" ? "reverse" : "reverse-complement"; op = getHyperlink(OP_TYPE, op); QString res = tr("Converts each input sequence from %1 into its %2 counterpart").arg(producerName).arg(op); return res; } void RCWorker::init() { input = ports.value(BasePorts::IN_SEQ_PORT_ID()); output = ports.value(BasePorts::OUT_SEQ_PORT_ID()); } bool RCWorker::isDone() { return !input || input->isEnded(); } bool RCWorker::isReady() { return (input && input->hasMessage()); } Task* RCWorker::tick() { Message inputMessage = getMessageAndSetupScriptValues(input); QVariantMap qm = inputMessage.getData().toMap(); DNASequence seq = qm.value(BaseSlots::DNA_SEQUENCE_SLOT().getId()).value(); if(seq.isNull()) { return new FailTask(tr("Null sequence supplied to FindWorker: %1").arg(seq.getName())); } QString type = actor->getParameter(OP_TYPE)->getAttributeValue(); DNATranslation *complTT; if(!seq.alphabet->isNucleic()) { coreLog.info(tr("Can't complement amino sequence")); if (input->isEnded()) { output->setEnded(); } return NULL; } if(type == "reverse-complement") { complTT = AppContext::getDNATranslationRegistry()->lookupComplementTranslation(seq.alphabet); if(complTT == NULL) { coreLog.info(tr("Can't find complement translation")); if (input->isEnded()) { output->setEnded(); } return NULL; } complTT->translate(seq.seq.data(),seq.seq.size(), seq.seq.data(), seq.seq.size()); TextUtils::reverse(seq.seq.data(), seq.seq.size()); } else if(type == "norev") { complTT = AppContext::getDNATranslationRegistry()->lookupComplementTranslation(seq.alphabet); if(complTT == NULL) { coreLog.info(tr("Can't find complement translation")); if (input->isEnded()) { output->setEnded(); } return NULL; } complTT->translate(seq.seq.data(),seq.seq.size(), seq.seq.data(), seq.seq.size()); } else { TextUtils::reverse(seq.seq.data(), seq.seq.size()); } if(output) { QVariant v = qVariantFromValue(seq); output->put(Message(BaseTypes::DNA_SEQUENCE_TYPE(), v)); if (input->isEnded()) { output->setEnded(); } } return NULL; } } }ugene-1.9.8/src/plugins/workflow_designer/src/library/DocActors.h0000644000175000017500000001101611651544325023606 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_WORKFLOW_DOC_ACTORS_H_ #define _U2_WORKFLOW_DOC_ACTORS_H_ #include #include #include #include #include #include namespace U2 { namespace Workflow { class DocActorProto : public IntegralBusActorPrototype { public: DocActorProto(const DocumentFormatId& _fid, const Descriptor& desc, const QList& ports, const QList& attrs = QList()); DocActorProto(const Descriptor& desc, const GObjectType& t, const QList& ports, const QList& attrs = QList()); virtual bool isAcceptableDrop(const QMimeData*, QVariantMap*) const = 0; bool isAcceptableDrop(const QMimeData*, QVariantMap*, const QString & urlAttrId ) const; protected: QString prepareDocumentFilter(); protected: DocumentFormatId fid; GObjectType type; }; class ReadDocActorProto : public DocActorProto { public: ReadDocActorProto( const DocumentFormatId& fid, const Descriptor& desc, const QList& ports, const QList& attrs = QList() ); virtual bool isAcceptableDrop(const QMimeData*, QVariantMap*) const; }; class WriteDocActorProto : public DocActorProto { public: WriteDocActorProto( const DocumentFormatId& fid, const Descriptor& desc, const QList& ports, const QString & portId, const QList& attrs = QList() ); WriteDocActorProto(const Descriptor& desc, const GObjectType & t, const QList& ports, const QString & portId, const QList& attrs = QList() ); URLDelegate *getUrlDelegate(); private: void construct(); virtual bool isAcceptableDrop(const QMimeData*, QVariantMap*) const; private: QString outPortId; URLDelegate *urlDelegate; }; class ReadDocPrompter; typedef PrompterBase ReadDocPrompterBase; class ReadDocPrompter : public ReadDocPrompterBase { Q_OBJECT public: ReadDocPrompter(const QString& s) : spec(s) {} ReadDocPrompter(Actor* p = 0) : ReadDocPrompterBase(p) {} virtual ActorDocument* createDescription(Actor* a) { ReadDocPrompter* doc = static_cast(ReadDocPrompterBase::createDescription(a)); doc->spec = this->spec; return doc; } protected: QString composeRichDoc(); QString spec; }; class WriteDocPrompter; typedef PrompterBase WriteDocPrompterBase; class WriteDocPrompter : public WriteDocPrompterBase { Q_OBJECT public: WriteDocPrompter(const QString& spec, const QString& slot) : spec(spec), slot(slot){} WriteDocPrompter(Actor* p = 0) : WriteDocPrompterBase(p) {} virtual ActorDocument* createDescription(Actor* a) { WriteDocPrompter* doc = static_cast(WriteDocPrompterBase::createDescription(a)); doc->spec = this->spec; doc->slot = this->slot; return doc; } protected: QString composeRichDoc(); QString spec,slot; }; class WriteGenbankPrompter : public PrompterBase { Q_OBJECT public: WriteGenbankPrompter(Actor* p = 0) : PrompterBase(p){} protected: QString composeRichDoc(); }; class WriteFastaPrompter : public PrompterBaseImpl { Q_OBJECT public: WriteFastaPrompter(const QString & formatId, Actor* p = 0) : PrompterBaseImpl(p), format(formatId){} virtual QString composeRichDoc(); virtual ActorDocument * createDescription(Actor*); private: QString format; }; } // Workflow namespace } // U2 namespace #endif ugene-1.9.8/src/plugins/workflow_designer/src/library/CreateExternalProcessDialog.cpp0000644000175000017500000011267211651544325027657 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "CreateExternalProcessDialog.h" #include #include #include #include #include #include #include #include "WorkflowEditorDelegates.h" #include #include #include #include #include namespace U2 { class CreateExternalProcessDialog; class CfgExternalToolItem { public: CfgExternalToolItem() { dfr = AppContext::getDocumentFormatRegistry(); dtr = Workflow::WorkflowEnv::getDataTypeRegistry(); delegateForTypes = NULL; delegateForFormats = NULL; itemData.type = BaseTypes::DNA_SEQUENCE_TYPE()->getId(); itemData.format = BaseDocumentFormats::PLAIN_FASTA; } ~CfgExternalToolItem() { delete delegateForTypes; delete delegateForFormats; } QString getDataType() const {return itemData.type;} void setDataType(const QString& id) { itemData.type = id; } QString getName() const {return itemData.attrName;} void setName(const QString &_name) {itemData.attrName = _name;} QString getFormat() const {return itemData.format;} void setFormat(const QString & f) {itemData.format = f;} QString getDescription() const {return itemData.description;} void setDescription(const QString & _descr) {itemData.description = _descr;} PropertyDelegate *delegateForTypes; PropertyDelegate *delegateForFormats; DataConfig itemData; private: DocumentFormatRegistry *dfr; DataTypeRegistry *dtr; }; class CfgExternalToolModel: public QAbstractTableModel { public: CfgExternalToolModel(QObject *obj = NULL): QAbstractTableModel(obj) { init(); /*CfgListItem *newItem = new CfgListItem(); newItem->delegateForTypes = new ComboBoxDelegate(types); items.append(newItem);*/ } int rowCount(const QModelIndex & /* = QModelIndex */) const{ return items.size(); } int columnCount(const QModelIndex & /* = QModelIndex */) const { return 4; } Qt::ItemFlags flags(const QModelIndex &) const{ return Qt::ItemIsEditable | Qt::ItemIsEnabled | Qt::ItemIsSelectable; } CfgExternalToolItem* getItem(const QModelIndex &index) const { return items.at(index.row()); } QList getItems() const { return items; } QVariant data(const QModelIndex &index, int role /* = Qt::DisplayRole */) const { CfgExternalToolItem *item = getItem(index); int col = index.column(); switch(role) { case Qt::DisplayRole: case Qt::ToolTipRole: if(col == 0) return item->getName(); else if(col == 1) return item->delegateForTypes->getDisplayValue(item->getDataType()); else if(col == 2) return item->delegateForFormats->getDisplayValue(item->getFormat()); else if(col == 3) return item->getDescription(); else return QVariant(); case DelegateRole: if(col == 1) return qVariantFromValue(item->delegateForTypes); else if(col == 2) return qVariantFromValue(item->delegateForFormats); else return QVariant(); case Qt::EditRole: case ConfigurationEditor::ItemValueRole: if(col == 1) return item->getDataType(); else if(col == 2) return item->getFormat(); else return QVariant(); default: return QVariant(); } } void createFormatDelegate(const QString &newType, CfgExternalToolItem *item) { PropertyDelegate *delegate; QString format; if(newType == BaseTypes::DNA_SEQUENCE_TYPE()->getId()) { delegate = new ComboBoxDelegate(seqFormatsW); format = seqFormatsW.values().first().toString(); } else if(newType == BaseTypes::MULTIPLE_ALIGNMENT_TYPE()->getId()) { delegate = new ComboBoxDelegate(msaFormatsW); format = msaFormatsW.values().first().toString(); } else if(newType == BaseTypes::ANNOTATION_TABLE_TYPE()->getId()) { delegate = new ComboBoxDelegate(annFormatsW); format = annFormatsW.values().first().toString(); } else if(newType == SEQ_WITH_ANNS){ delegate = new ComboBoxDelegate(annFormatsW); format = annFormatsW.values().first().toString(); } else if(newType == BaseTypes::STRING_TYPE()->getId()) { delegate = new ComboBoxDelegate(textFormat); format = textFormat.values().first().toString(); } else{ return; } item->setFormat(format); item->delegateForFormats = delegate; } bool setData(const QModelIndex &index, const QVariant &value, int role) { int col = index.column(); CfgExternalToolItem * item = getItem(index); switch (role) { case Qt::EditRole: case ConfigurationEditor::ItemValueRole: if(col == 0) { if(item->getName() != value.toString()) { item->setName(value.toString()); } }else if(col == 1) { QString newType = value.toString(); if(item->getDataType() != newType) { if(!newType.isEmpty()) { item->setDataType(newType); createFormatDelegate(newType, item); } } } else if(col == 2) { if(item->getFormat() != value.toString() && !value.toString().isEmpty()) { item->setFormat(value.toString()); } } else if(col == 3) { if(item->getDescription() != value.toString()) { item->setDescription(value.toString()); } } emit dataChanged(index, index); } return true; } QVariant headerData ( int section, Qt::Orientation orientation, int role = Qt::DisplayRole ) const { if (orientation == Qt::Horizontal && role == Qt::DisplayRole) { switch(section) { case 0: return CreateExternalProcessDialog::tr("Name for command line parameter"); case 1: return CreateExternalProcessDialog::tr("Type"); case 2: return CreateExternalProcessDialog::tr("Format"); case 3: return CreateExternalProcessDialog::tr("Description"); default: return QVariant(); } } return QVariant(); } bool insertRows ( int row, int count = 0, const QModelIndex & parent = QModelIndex() ) { Q_UNUSED(row); Q_UNUSED(count); beginInsertRows(parent, items.size(), items.size()); CfgExternalToolItem *newItem = new CfgExternalToolItem(); newItem->delegateForTypes = new ComboBoxDelegate(types); newItem->delegateForFormats = new ComboBoxDelegate(seqFormatsW); items.append(newItem); endInsertRows(); return true; } bool removeRows(int row, int count = 0, const QModelIndex & parent = QModelIndex()) { Q_UNUSED(count); if(row >= 0 && row < items.size()) { beginRemoveRows(parent, row, row); items.removeAt(row); endRemoveRows(); return true; } else { return false; } } void init() { initTypes(); initFormats(); } void initFormats() { QList ids = AppContext::getDocumentFormatRegistry()->getRegisteredFormats(); DocumentFormatConstraints seqWrite; seqWrite.supportedObjectTypes+=GObjectTypes::SEQUENCE; seqWrite.addFlagToSupport(DocumentFormatFlag_SupportWriting); seqWrite.addFlagToExclude(DocumentFormatFlag_SingleObjectFormat); DocumentFormatConstraints seqRead; seqRead.supportedObjectTypes+=GObjectTypes::SEQUENCE; seqRead.addFlagToSupport(DocumentFormatFlag_SupportStreaming); seqRead.addFlagToExclude(DocumentFormatFlag_SingleObjectFormat); DocumentFormatConstraints msaWrite; msaWrite.supportedObjectTypes+=GObjectTypes::MULTIPLE_ALIGNMENT; msaWrite.addFlagToSupport(DocumentFormatFlag_SupportWriting); msaWrite.addFlagToExclude(DocumentFormatFlag_SingleObjectFormat); DocumentFormatConstraints msaRead; msaRead.supportedObjectTypes+=GObjectTypes::MULTIPLE_ALIGNMENT; msaRead.addFlagToSupport(DocumentFormatFlag_SupportStreaming); msaRead.addFlagToExclude(DocumentFormatFlag_SingleObjectFormat); DocumentFormatConstraints annWrite; annWrite.supportedObjectTypes+=GObjectTypes::ANNOTATION_TABLE; annWrite.addFlagToSupport(DocumentFormatFlag_SupportWriting); annWrite.addFlagToExclude(DocumentFormatFlag_SingleObjectFormat); DocumentFormatConstraints annRead; annRead.supportedObjectTypes+=GObjectTypes::ANNOTATION_TABLE; annRead.addFlagToSupport(DocumentFormatFlag_SupportStreaming); annRead.addFlagToExclude(DocumentFormatFlag_SingleObjectFormat); foreach(const DocumentFormatId& id, ids) { DocumentFormat* df = AppContext::getDocumentFormatRegistry()->getFormatById(id); if (df->checkConstraints(seqWrite)) { seqFormatsW[df->getFormatName()] = df->getFormatId(); } if (df->checkConstraints(seqRead)) { seqFormatsR[df->getFormatName()] = df->getFormatId(); } if (df->checkConstraints(msaWrite)) { msaFormatsW[df->getFormatName()] = df->getFormatId(); } if (df->checkConstraints(msaRead)) { msaFormatsR[df->getFormatName()] = df->getFormatId(); } if (df->checkConstraints(annWrite)) { annFormatsW[df->getFormatName()] = df->getFormatId(); } if (df->checkConstraints(annRead)) { annFormatsR[df->getFormatName()] = df->getFormatId(); } } DocumentFormat *df = AppContext::getDocumentFormatRegistry()->getFormatById(BaseDocumentFormats::PLAIN_TEXT); textFormat[df->getFormatName()] = df->getFormatId(); } void initTypes() { DataTypePtr ptr = BaseTypes::DNA_SEQUENCE_TYPE(); types[ptr->getDisplayName()] = ptr->getId(); ptr = BaseTypes::ANNOTATION_TABLE_TYPE(); types[ptr->getDisplayName()] = ptr->getId(); ptr = BaseTypes::MULTIPLE_ALIGNMENT_TYPE(); types[ptr->getDisplayName()] = ptr->getId(); ptr = BaseTypes::STRING_TYPE(); types[ptr->getDisplayName()] = ptr->getId(); types["Sequence with annotations"] = SEQ_WITH_ANNS; } private: QList items; QVariantMap types; QVariantMap seqFormatsW; QVariantMap msaFormatsW; QVariantMap annFormatsW; QVariantMap seqFormatsR; QVariantMap msaFormatsR; QVariantMap annFormatsR; QVariantMap textFormat; }; class AttributeItem { public: QString getName() const {return name;} void setName(const QString& _name) {name = _name;} QString getDataType() const {return type;} void setDataType(const QString &_type) {type = _type;} QString getDescription() const {return description;} void setDescription(const QString &_description) {description = _description;} private: QString name; QString type; QString description; }; class CfgExternalToolModelAttributes: public QAbstractTableModel { public: CfgExternalToolModelAttributes() { types["URL"] = "URL"; types["String"] = "String"; types["Number"] = "Number"; types["Boolean"] = "Boolean"; delegate = new ComboBoxDelegate(types); } ~CfgExternalToolModelAttributes() { foreach(AttributeItem* item, items) { delete item; } } int rowCount(const QModelIndex & /* = QModelIndex */) const{ return items.size(); } int columnCount(const QModelIndex & /* = QModelIndex */) const { return 3; } Qt::ItemFlags flags(const QModelIndex &) const{ return Qt::ItemIsEditable | Qt::ItemIsEnabled | Qt::ItemIsSelectable; } AttributeItem* getItem(const QModelIndex &index) const { return items.at(index.row()); } QList getItems() const { return items; } QVariant data(const QModelIndex &index, int role /* = Qt::DisplayRole */) const { AttributeItem *item = getItem(index); int col = index.column(); switch(role) { case Qt::DisplayRole: case Qt::ToolTipRole: if(col == 0) return item->getName(); else if(col == 1) return delegate->getDisplayValue(item->getDataType()); else if(col == 2) return item->getDescription(); else return QVariant(); case DelegateRole: if(col == 1) return qVariantFromValue(delegate); else return QVariant(); case Qt::EditRole: case ConfigurationEditor::ItemValueRole: if(col == 1) return item->getDataType(); else return QVariant(); default: return QVariant(); } } bool setData(const QModelIndex &index, const QVariant &value, int role) { int col = index.column(); AttributeItem * item = getItem(index); switch (role) { case Qt::EditRole: case ConfigurationEditor::ItemValueRole: if(col == 0) { if(item->getName() != value.toString()) { item->setName(value.toString()); } }else if(col == 1) { QString newType = value.toString(); if(item->getDataType() != newType) { if(!newType.isEmpty()) { item->setDataType(newType); } } } else if(col == 2) { if(item->getDescription() != value.toString()) { item->setDescription(value.toString()); } } emit dataChanged(index, index); } return true; } QVariant headerData ( int section, Qt::Orientation orientation, int role = Qt::DisplayRole ) const { if (orientation == Qt::Horizontal && role == Qt::DisplayRole) { switch(section) { case 0: return CreateExternalProcessDialog::tr("Name"); case 1: return CreateExternalProcessDialog::tr("Type"); case 2: return CreateExternalProcessDialog::tr("Description"); default: return QVariant(); } } return QVariant(); } bool insertRows ( int row, int count = 0, const QModelIndex & parent = QModelIndex() ) { Q_UNUSED(row); Q_UNUSED(count); beginInsertRows(parent, items.size(), items.size()); AttributeItem *newItem = new AttributeItem(); newItem->setDataType("String"); items.append(newItem); endInsertRows(); return true; } bool removeRows(int row, int count = 0, const QModelIndex & parent = QModelIndex()) { Q_UNUSED(count); if(row >= 0 && row < items.size()) { beginRemoveRows(parent, row, row); items.removeAt(row); endRemoveRows(); return true; } else { return false; } } private: QList items; PropertyDelegate *delegate; QVariantMap types; }; CreateExternalProcessDialog::CreateExternalProcessDialog(QWidget *p, ExternalProcessConfig *cfg):QWizard(p) { ui.setupUi(this); connect(ui.addInputButton, SIGNAL(clicked()), SLOT(sl_addInput())); connect(ui.addOutputButton, SIGNAL(clicked()), SLOT(sl_addOutput())); connect(ui.deleteInputButton, SIGNAL(clicked()), SLOT(sl_deleteInput())); connect(ui.deleteOutputButton, SIGNAL(clicked()), SLOT(sl_deleteOutput())); connect(ui.addAttributeButton, SIGNAL(clicked()), SLOT(sl_addAttribute())); connect(ui.deleteAttributeButton, SIGNAL(clicked()), SLOT(sl_deleteAttribute())); //connect(button(QWizard::NextButton), SIGNAL(clicked()), SLOT(validateNextPage())); connect(this, SIGNAL(currentIdChanged(int)), SLOT(sl_validatePage(int))); //connect(button(QWizard::FinishButton), SIGNAL(clicked()), SLOT(sl_OK())); //connect(button(QWizard::NextButton), SIGNAL(clicked()), SLOT(sl_generateTemplateString())); QFontMetrics info(ui.descr1TextEdit->font()); ui.descr1TextEdit->setFixedHeight(info.height() * INFO_STRINGS_NUM); ui.descr2TextEdit->setFixedHeight(info.height() * INFO_STRINGS_NUM); ui.descr3TextEdit->setFixedHeight(info.height() * INFO_STRINGS_NUM); ui.descr4TextEdit->setFixedHeight(info.height() * INFO_STRINGS_NUM); ui.inputTableView->setModel(new CfgExternalToolModel()); ui.outputTableView->setModel(new CfgExternalToolModel()); ui.attributesTableView->setModel(new CfgExternalToolModelAttributes()); ui.inputTableView->setItemDelegate(new ProxyDelegate()); ui.outputTableView->setItemDelegate(new ProxyDelegate()); ui.attributesTableView->setItemDelegate(new ProxyDelegate()); ui.inputTableView->horizontalHeader()->setStretchLastSection(true); ui.outputTableView->horizontalHeader()->setStretchLastSection(true); ui.attributesTableView->horizontalHeader()->setStretchLastSection(true); ui.inputTableView->horizontalHeader()->setDefaultAlignment(Qt::AlignLeft); ui.outputTableView->horizontalHeader()->setDefaultAlignment(Qt::AlignLeft); ui.attributesTableView->horizontalHeader()->setDefaultAlignment(Qt::AlignLeft); QFontMetrics fm(ui.inputTableView->font()); ui.inputTableView->setColumnWidth(1, fm.width(SEQ_WITH_ANNS)*1.5); ui.outputTableView->setColumnWidth(1, fm.width(SEQ_WITH_ANNS)*1.5); int ind = 0; foreach(const DataConfig &dataCfg, cfg->inputs) { ui.inputTableView->model()->insertRow(0, QModelIndex()); QModelIndex index = ui.inputTableView->model()->index(ind,0); ui.inputTableView->model()->setData(index, dataCfg.attrName); index = ui.inputTableView->model()->index(ind,1); ui.inputTableView->model()->setData(index, dataCfg.type); index = ui.inputTableView->model()->index(ind,2); ui.inputTableView->model()->setData(index, dataCfg.format); index = ui.inputTableView->model()->index(ind,3); ui.inputTableView->model()->setData(index, dataCfg.description); ind++; } ind = 0; foreach(const DataConfig &dataCfg, cfg->outputs) { ui.outputTableView->model()->insertRow(0, QModelIndex()); QModelIndex index = ui.outputTableView->model()->index(ind,0); ui.outputTableView->model()->setData(index, dataCfg.attrName); index = ui.outputTableView->model()->index(ind,1); ui.outputTableView->model()->setData(index, dataCfg.type); index = ui.outputTableView->model()->index(ind,2); ui.outputTableView->model()->setData(index, dataCfg.format); index = ui.outputTableView->model()->index(ind,3); ui.outputTableView->model()->setData(index, dataCfg.description); ind++; } ind = 0; foreach(const AttributeConfig &attrCfg, cfg->attrs) { ui.attributesTableView->model()->insertRow(0, QModelIndex()); QModelIndex index = ui.attributesTableView->model()->index(ind,0); ui.attributesTableView->model()->setData(index, attrCfg.attrName); index = ui.attributesTableView->model()->index(ind,1); ui.attributesTableView->model()->setData(index, attrCfg.type); index = ui.attributesTableView->model()->index(ind,2); ui.attributesTableView->model()->setData(index, attrCfg.description); ind++; } ui.nameLineEdit->setText(cfg->name); ui.descriptionTextEdit->setText(cfg->description); ui.templateLineEdit->setText(cfg->cmdLine); ui.prompterTextEdit->setText(cfg->templateDescription); editing = true; connect(ui.nameLineEdit, SIGNAL(textChanged(const QString &)), this, SLOT(sl_validateName(const QString &))); connect(ui.templateLineEdit, SIGNAL(textChanged(const QString &)), this, SLOT(sl_validateCmdLine(const QString &))); connect(ui.inputTableView->model(), SIGNAL(dataChanged ( const QModelIndex &, const QModelIndex &)), SLOT(validateDataModel(const QModelIndex &, const QModelIndex &))); connect(ui.outputTableView->model(), SIGNAL(dataChanged ( const QModelIndex &, const QModelIndex &)), SLOT(validateDataModel(const QModelIndex &, const QModelIndex &))); connect(ui.attributesTableView->model(), SIGNAL(dataChanged ( const QModelIndex &, const QModelIndex &)), SLOT(validateAttributeModel(const QModelIndex &, const QModelIndex &))); //validateNextPage(); } void CreateExternalProcessDialog::sl_addInput() { ui.inputTableView->model()->insertRow(0, QModelIndex()); validateDataModel(); } void CreateExternalProcessDialog::sl_addOutput() { ui.outputTableView->model()->insertRow(0, QModelIndex()); validateDataModel(); } void CreateExternalProcessDialog::sl_deleteInput() { QModelIndex index = ui.inputTableView->currentIndex(); ui.inputTableView->model()->removeRow(index.row()); validateDataModel(); } void CreateExternalProcessDialog::sl_deleteOutput() { QModelIndex index = ui.outputTableView->currentIndex(); ui.outputTableView->model()->removeRow(index.row()); validateDataModel(); } void CreateExternalProcessDialog::sl_addAttribute() { ui.attributesTableView->model()->insertRow(0, QModelIndex()); validateAttributeModel(); } void CreateExternalProcessDialog::sl_deleteAttribute() { QModelIndex index = ui.attributesTableView->currentIndex(); ui.attributesTableView->model()->removeRow(index.row()); validateAttributeModel(); } CreateExternalProcessDialog::CreateExternalProcessDialog( QWidget *p /* = NULL*/ ): QWizard(p) { ui.setupUi(this); connect(ui.addInputButton, SIGNAL(clicked()), SLOT(sl_addInput())); connect(ui.addOutputButton, SIGNAL(clicked()), SLOT(sl_addOutput())); connect(ui.deleteInputButton, SIGNAL(clicked()), SLOT(sl_deleteInput())); connect(ui.deleteOutputButton, SIGNAL(clicked()), SLOT(sl_deleteOutput())); connect(ui.addAttributeButton, SIGNAL(clicked()), SLOT(sl_addAttribute())); connect(ui.deleteAttributeButton, SIGNAL(clicked()), SLOT(sl_deleteAttribute())); //connect(button(QWizard::FinishButton), SIGNAL(clicked()), SLOT(sl_OK())); connect(button(QWizard::NextButton), SIGNAL(clicked()), SLOT(sl_generateTemplateString())); //connect(button(QWizard::NextButton), SIGNAL(clicked()), SLOT(validateNextPage())); connect(this, SIGNAL(currentIdChanged(int)), SLOT(sl_validatePage(int))); connect(ui.nameLineEdit, SIGNAL(textChanged(const QString &)), this, SLOT(sl_validateName(const QString &))); connect(ui.templateLineEdit, SIGNAL(textChanged(const QString &)), this, SLOT(sl_validateCmdLine(const QString &))); ui.inputTableView->setModel(new CfgExternalToolModel()); ui.outputTableView->setModel(new CfgExternalToolModel()); ui.attributesTableView->setModel(new CfgExternalToolModelAttributes()); connect(ui.inputTableView->model(), SIGNAL(dataChanged ( const QModelIndex &, const QModelIndex &)), SLOT(validateDataModel(const QModelIndex &, const QModelIndex &))); connect(ui.outputTableView->model(), SIGNAL(dataChanged ( const QModelIndex &, const QModelIndex &)), SLOT(validateDataModel(const QModelIndex &, const QModelIndex &))); connect(ui.attributesTableView->model(), SIGNAL(dataChanged ( const QModelIndex &, const QModelIndex &)), SLOT(validateAttributeModel(const QModelIndex &, const QModelIndex &))); ui.inputTableView->setItemDelegate(new ProxyDelegate()); ui.outputTableView->setItemDelegate(new ProxyDelegate()); ui.attributesTableView->setItemDelegate(new ProxyDelegate()); ui.inputTableView->horizontalHeader()->setStretchLastSection(true); ui.outputTableView->horizontalHeader()->setStretchLastSection(true); ui.attributesTableView->horizontalHeader()->setStretchLastSection(true); ui.inputTableView->horizontalHeader()->setDefaultAlignment(Qt::AlignLeft); ui.outputTableView->horizontalHeader()->setDefaultAlignment(Qt::AlignLeft); ui.attributesTableView->horizontalHeader()->setDefaultAlignment(Qt::AlignLeft); QFontMetrics fm(ui.inputTableView->font()); ui.inputTableView->setColumnWidth(1, fm.width(SEQ_WITH_ANNS)*1.5); ui.outputTableView->setColumnWidth(1, fm.width(SEQ_WITH_ANNS)*1.5); QFontMetrics info(ui.descr1TextEdit->font()); ui.descr1TextEdit->setFixedHeight(info.height() * INFO_STRINGS_NUM); ui.descr2TextEdit->setFixedHeight(info.height() * INFO_STRINGS_NUM); ui.descr3TextEdit->setFixedHeight(info.height() * INFO_STRINGS_NUM); ui.descr4TextEdit->setFixedHeight(info.height() * INFO_STRINGS_NUM); editing = false; } void CreateExternalProcessDialog::accept() { CfgExternalToolModel *model; cfg = new ExternalProcessConfig(); cfg->name = ui.nameLineEdit->text(); cfg->description = ui.descriptionTextEdit->toPlainText(); cfg->templateDescription = ui.prompterTextEdit->toPlainText(); model = static_cast(ui.inputTableView->model()); foreach(CfgExternalToolItem *item, model->getItems()) { cfg->inputs << item->itemData; } model = static_cast(ui.outputTableView->model()); foreach(CfgExternalToolItem *item, model->getItems()) { cfg->outputs << item->itemData; } CfgExternalToolModelAttributes *aModel = static_cast(ui.attributesTableView->model()); foreach(AttributeItem *item, aModel->getItems()) { AttributeConfig attributeData; attributeData.attrName = item->getName(); attributeData.type = item->getDataType(); attributeData.description = item->getDescription(); cfg->attrs << attributeData; } cfg->cmdLine = ui.templateLineEdit->text(); if(!validate()) { return; } QString str = HRSchemaSerializer::actor2String(cfg); QString dir = WorkflowSettings::getExternalToolDirectory(); QDir d(dir); if(!d.exists()) { d.mkdir(dir); } QFile file(dir + cfg->name + ".etc"); file.open(QIODevice::WriteOnly); file.write(str.toAscii()); file.close(); done(QDialog::Accepted); } bool CreateExternalProcessDialog::validate() { QString title = tr("Create Element"); if(cfg->inputs.isEmpty() && cfg->outputs.isEmpty()) { QMessageBox::critical(this, title, tr("Please set the input/output data.")); return false; } if(cfg->cmdLine.isEmpty()) { QMessageBox::critical(this, title, tr("Please set the command line to run external tool.")); return false; } if(cfg->name.isEmpty()) { QMessageBox::critical(this, title, tr("Please set the name for the new element.")); return false; } QRegExp invalidSymbols("[\\.,:;\\?]"); if(cfg->name.contains(invalidSymbols)) { QMessageBox::critical(this, title, tr("Invalid symbols in the element name.")); return false; } if(WorkflowEnv::getProtoRegistry()->getProto(cfg->name) && !editing) { QMessageBox::critical(this, title, tr("Element with this name already exists.")); return false; } invalidSymbols = QRegExp("\\W"); QStringList nameList; foreach(const DataConfig & dc, cfg->inputs) { if(dc.attrName.isEmpty()) { QMessageBox::critical(this, title, tr("For one or more parameter name was not set.")); return false; } if(dc.attrName.contains(invalidSymbols)) { QMessageBox::critical(this, title, tr("Invalid symbols in a name.").arg(dc.attrName)); return false; } nameList << dc.attrName; } foreach(const DataConfig & dc, cfg->outputs) { if(dc.attrName.isEmpty()) { QMessageBox::critical(this, title, tr("For one or more parameter name was not set.")); return false; } if(dc.attrName.contains(invalidSymbols)) { QMessageBox::critical(this, title, tr("Invalid symbols in a name.").arg(dc.attrName)); return false; } nameList << dc.attrName; } foreach(const AttributeConfig & ac, cfg->attrs) { if(ac.attrName.isEmpty()) { QMessageBox::critical(this, title, tr("For one or more parameter name was not set.")); return false; } if(ac.attrName.contains(invalidSymbols)) { QMessageBox::critical(this, title, tr("Invalid symbols in a name.").arg(ac.attrName)); return false; } nameList << ac.attrName; } if(nameList.removeDuplicates() > 0) { QMessageBox::critical(this, title, tr("The same name of element parameters was found")); return false; } foreach(const QString &str, nameList) { if(!cfg->cmdLine.contains("$" + str)) { QMessageBox msgBox(this); msgBox.setWindowTitle(title); msgBox.setText(tr("You don't use parameter %1 in template string. Continue?").arg(str)); msgBox.addButton(tr("Continue"), QMessageBox::ActionRole); QPushButton *cancel = msgBox.addButton(tr("Abort"), QMessageBox::ActionRole); msgBox.exec(); if(msgBox.clickedButton() == cancel) { return false; } } } return true; } void CreateExternalProcessDialog::sl_generateTemplateString() { QString cmd = ""; CfgExternalToolModel *model = static_cast(ui.inputTableView->model()); foreach(CfgExternalToolItem *item, model->getItems()) { cmd += " $" + item->itemData.attrName; } model = static_cast(ui.outputTableView->model()); foreach(CfgExternalToolItem *item, model->getItems()) { cmd += " $" + item->itemData.attrName; } CfgExternalToolModelAttributes *aModel = static_cast(ui.attributesTableView->model()); int i = 0; foreach(AttributeItem *item, aModel->getItems()) { i++; cmd += " -p" + QString::number(i) + " $" + item->getName(); } ui.templateLineEdit->setText(cmd); } void CreateExternalProcessDialog::sl_validateName( const QString &text) { bool res = true; if(text.isEmpty()) { //QMessageBox::critical(this, title, tr("Please set the name for the new element.")); res = false; } QRegExp invalidSymbols("\\W"); if(text.contains(invalidSymbols)) { //QMessageBox::critical(this, title, tr("Invalid symbols in the element name.")); res = false; } if(WorkflowEnv::getProtoRegistry()->getProto(text) && !editing) { //QMessageBox::critical(this, title, tr("Element with this name already exists.")); res = false; } button(QWizard::NextButton)->setEnabled(res); } void CreateExternalProcessDialog::sl_validateCmdLine( const QString & text) { if(text.isEmpty()) { button(QWizard::FinishButton)->setEnabled(false); } else { button(QWizard::FinishButton)->setEnabled(true); } } void CreateExternalProcessDialog::validateDataModel(const QModelIndex &, const QModelIndex & ) { bool res = true; CfgExternalToolModel *model; QRegExp invalidSymbols("\\W"); QStringList nameList; model = static_cast(ui.inputTableView->model()); foreach(CfgExternalToolItem *item, model->getItems()) { if(item->itemData.attrName.isEmpty()) { //QMessageBox::critical(this, title, tr("For one or more parameter name was not set.")); res = false; } if(item->itemData.attrName.contains(invalidSymbols)) { //QMessageBox::critical(this, title, tr("Invalid symbols in a name.").arg(dc.attrName)); res = false; } nameList << item->itemData.attrName; } model = static_cast(ui.outputTableView->model()); foreach(CfgExternalToolItem *item, model->getItems()) { if(item->itemData.attrName.isEmpty()) { //QMessageBox::critical(this, title, tr("For one or more parameter name was not set.")); res = false; } if(item->itemData.attrName.contains(invalidSymbols)) { //QMessageBox::critical(this, title, tr("Invalid symbols in a name.").arg(dc.attrName)); res = false; } nameList << item->itemData.attrName; } if(nameList.removeDuplicates() > 0) { //QMessageBox::critical(this, title, tr("The same name of element parameters was found")); res = false; } if(nameList.isEmpty()) { res = false; } button(QWizard::NextButton)->setEnabled(res); } void CreateExternalProcessDialog::validateAttributeModel(const QModelIndex &, const QModelIndex & ) { bool res = true; CfgExternalToolModel *model; QRegExp invalidSymbols("\\W"); QStringList nameList; model = static_cast(ui.inputTableView->model()); foreach(CfgExternalToolItem *item, model->getItems()) { if(item->itemData.attrName.isEmpty()) { //QMessageBox::critical(this, title, tr("For one or more parameter name was not set.")); res = false; } if(item->itemData.attrName.contains(invalidSymbols)) { //QMessageBox::critical(this, title, tr("Invalid symbols in a name.").arg(dc.attrName)); res = false; } nameList << item->itemData.attrName; } model = static_cast(ui.outputTableView->model()); foreach(CfgExternalToolItem *item, model->getItems()) { if(item->itemData.attrName.isEmpty()) { //QMessageBox::critical(this, title, tr("For one or more parameter name was not set.")); res = false; } if(item->itemData.attrName.contains(invalidSymbols)) { //QMessageBox::critical(this, title, tr("Invalid symbols in a name.").arg(dc.attrName)); res = false; } nameList << item->itemData.attrName; } CfgExternalToolModelAttributes *aModel = static_cast(ui.attributesTableView->model()); foreach(AttributeItem *item, aModel->getItems()) { if(item->getName().isEmpty()) { //QMessageBox::critical(this, title, tr("For one or more parameter name was not set.")); res = false; } if(item->getName().contains(invalidSymbols)) { //QMessageBox::critical(this, title, tr("Invalid symbols in a name.").arg(ac.attrName)); res = false; } nameList << item->getName(); } if(nameList.removeDuplicates() > 0) { //QMessageBox::critical(this, title, tr("The same name of element parameters was found")); res = false; } button(QWizard::NextButton)->setEnabled(res); } void CreateExternalProcessDialog::validateNextPage() { int id = currentId(); switch(id) { case 0: sl_validateName(ui.nameLineEdit->text()); break; case 1: validateDataModel(); break; case 2: validateAttributeModel(); case 3: sl_validateCmdLine(ui.templateLineEdit->text()); } } void CreateExternalProcessDialog::sl_validatePage(int id) { switch(id) { case 0: sl_validateName(ui.nameLineEdit->text()); break; case 1: validateDataModel(); break; case 2: validateAttributeModel(); case 3: sl_validateCmdLine(ui.templateLineEdit->text()); } } } ugene-1.9.8/src/plugins/workflow_designer/src/library/CreateExternalProcessDialog.h0000644000175000017500000000451411651544325027317 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef CreateExternalProcessDialog_h__ #define CreateExternalProcessDialog_h__ #include "ui/ui_ExternalProcessWorkerDialog.h" #include #include #include namespace U2 { class ExternalProcessConfig; class CreateExternalProcessDialog: public QWizard { Q_OBJECT public: CreateExternalProcessDialog(QWidget *p = NULL); CreateExternalProcessDialog(QWidget *p, ExternalProcessConfig *cfg); ExternalProcessConfig* config() const {return cfg;} bool validate(); //bool isComplete() const; public slots: void accept(); private slots: void sl_addInput(); void sl_addOutput(); void sl_deleteInput(); void sl_deleteOutput(); void sl_addAttribute(); void sl_deleteAttribute(); void sl_generateTemplateString(); // void sl_updateButtons(); void sl_validateName(const QString &); void sl_validateCmdLine(const QString &); void validateDataModel(const QModelIndex & i1 = QModelIndex(), const QModelIndex & i2 = QModelIndex()); void validateAttributeModel(const QModelIndex & i1 = QModelIndex(), const QModelIndex & i2 = QModelIndex()); void validateNextPage(); void sl_validatePage(int); //void sl_OK(); private: Ui::CreateExternalProcessWorkerDialog ui; ExternalProcessConfig *cfg; bool editing; static const int INFO_STRINGS_NUM = 5; }; } #endif // CreateExternalProcessDialog_h__ ugene-1.9.8/src/plugins/workflow_designer/src/library/ReverseComplementWorker.h0000644000175000017500000000200011651544325026547 0ustar ilyailya#ifndef _REVERSE_COMPLEMENT_WORKER_H_ #define _REVERSE_COMPLEMENT_WORKER_H_ #include #include namespace U2 { namespace LocalWorkflow { class RCWorkerPrompter: public PrompterBase { Q_OBJECT public: RCWorkerPrompter(Actor* p = 0) : PrompterBase(p) {} protected: QString composeRichDoc(); }; class RCWorker: public BaseWorker { Q_OBJECT public: RCWorker(Actor* a): BaseWorker(a), input(NULL), output(NULL) {} virtual void init(); virtual bool isReady(); virtual Task* tick(); virtual bool isDone(); virtual void cleanup() {} /*private slots: void sl_taskFinished(Task*);*/ protected: CommunicationChannel *input, *output; }; class RCWorkerFactory: public DomainFactory { public: static const QString ACTOR_ID; static void init(); RCWorkerFactory() : DomainFactory(ACTOR_ID) {} virtual Worker* createWorker(Actor* a) {return new RCWorker(a);} }; } } #endifugene-1.9.8/src/plugins/workflow_designer/src/library/RemoteDBFetcherWorker.cpp0000644000175000017500000002436211651544325026424 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "RemoteDBFetcherWorker.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include namespace U2 { namespace LocalWorkflow { #define ICOLOR QColor(85,85,255) // FIXME const QString RemoteDBFetcherFactory::ACTOR_ID("fetch-sequence"); static const QString TYPE("remote.seq"); static const QString DBID_ID("database"); static const QString SEQID_ID("resource-id"); static const QString PATH_ID("save-dir"); static const QString DEFAULT_PATH("default"); /* class RemoteDBFetcherPrompter : public PrompterBase */ QString RemoteDBFetcherPrompter::composeRichDoc() { QString unsetStr = ""+tr("unset")+""; QStringList seqids = getParameter(SEQID_ID).value().split(";", QString::SkipEmptyParts); QString seq = seqids.size() > 1 ? RemoteDBFetcherWorker::tr("sequences") : RemoteDBFetcherWorker::tr("sequence"); QString seqidsStr = seqids.isEmpty() ? unsetStr : QString("%1").arg(seqids.join(", ")); QString dbid = getParameter(DBID_ID).value(); dbid = RemoteDBFetcherFactory::cuteDbNames.key(dbid, dbid); QString saveDir = getParameter(PATH_ID).value(); saveDir = getHyperlink(PATH_ID, saveDir); QString saveDirStr = RemoteDBFetcherWorker::tr("Save result to %1 directory").arg(saveDir); return RemoteDBFetcherWorker::tr("Reads %1 identified with %2 from %3 remote database. %4"). arg(seq). arg(getHyperlink(SEQID_ID, seqidsStr)). arg(getHyperlink(DBID_ID, dbid)). arg(saveDirStr); } /* class RemoteDBFetcherWorker : public BaseWorker */ RemoteDBFetcherWorker::RemoteDBFetcherWorker(Actor *a) : BaseWorker(a), output(0) { } void RemoteDBFetcherWorker::init() { output = ports.value(BasePorts::OUT_SEQ_PORT_ID()); assert(dbid.isEmpty()); dbid = actor->getParameter(DBID_ID)->getAttributeValue(); if(RemoteDBFetcherFactory::cuteDbNames.values().contains(dbid.toLower())) { dbid = RemoteDBFetcherFactory::cuteDbNames.key(dbid.toLower()); assert(!dbid.isEmpty()); } seqids = actor->getParameter(SEQID_ID)->getAttributeValue().split(";", QString::SkipEmptyParts); fullPathDir = actor->getParameter(PATH_ID)->getAttributeValue(); if (fullPathDir == DEFAULT_PATH) { fullPathDir = LoadRemoteDocumentTask::getDefaultDownloadDirectory(); } } bool RemoteDBFetcherWorker::isReady() { return !isDone(); } Task* RemoteDBFetcherWorker::tick() { if(!QDir(fullPathDir).exists()) { if(!QDir().mkpath(fullPathDir)) { return new FailTask(tr("Cannot create directory '%1'").arg(fullPathDir)); } } Task *ret = 0; // fetch and load next file QString seqId = ""; while (seqId.isEmpty()) { if (seqids.isEmpty()) { return ret; } seqId = seqids.takeFirst().trimmed(); } ret = new LoadRemoteDocumentTask(seqId, dbid, fullPathDir); connect(ret, SIGNAL(si_stateChanged()), SLOT(sl_taskFinished())); return ret; } bool RemoteDBFetcherWorker::isDone() { return (!dbid.isEmpty() && seqids.isEmpty()); } void RemoteDBFetcherWorker::cleanup() { } void RemoteDBFetcherWorker::sl_taskFinished() { LoadRemoteDocumentTask *loadTask = qobject_cast(sender()); assert(loadTask); if (loadTask->getState() != Task::State_Finished) { return; } if (loadTask->hasError()) { loadTask->setError(tr("failed to load item '%1' from '%2' DB : %3").arg(loadTask->getAccNumber(), loadTask->getDBName(), loadTask->getError())); return; } Document *doc = loadTask->getDocument(); assert(doc); foreach(GObject *gobj, doc->findGObjectByType(GObjectTypes::SEQUENCE)) { DNASequenceObject *dnao = qobject_cast(gobj); assert(dnao); QList allLoadedAnnotations = doc->findGObjectByType(GObjectTypes::ANNOTATION_TABLE); QList annotations = GObjectUtils::findObjectsRelatedToObjectByRole(gobj, GObjectTypes::ANNOTATION_TABLE, GObjectRelationRole::SEQUENCE, allLoadedAnnotations, UOF_LoadedOnly); QList sads; if (!annotations.isEmpty()) { AnnotationTableObject *ato = qobject_cast(annotations.first()); foreach(Annotation *a, ato->getAnnotations()) { sads << a->data(); } } QVariantMap messageData; messageData[ BaseSlots::DNA_SEQUENCE_SLOT().getId() ] = qVariantFromValue(dnao->getDNASequence()); messageData[ BaseSlots::ANNOTATION_TABLE_SLOT().getId() ] = qVariantFromValue(sads); DataTypePtr messageType = WorkflowEnv::getDataTypeRegistry()->getById(TYPE); output->put(Message(messageType, messageData)); } if (seqids.isEmpty()) { output->setEnded(); } } /* class RemoteDBFetcherFactory : public DomainFactory */ const QMap RemoteDBFetcherFactory::cuteDbNames = RemoteDBFetcherFactory::initCuteDbNames(); QMap RemoteDBFetcherFactory::initCuteDbNames() { QMap ret; // FIXME: use constants. see LoadRemoteDocumentTask.cpp ret["NCBI GenBank (DNA sequence)"] ="ncbi dna"; ret["NCBI protein sequence database"] ="ncbi protein"; ret["PDB"] = "pdb"; ret["SWISS-PROT"] = "swiss-prot"; ret["UniProtKB/Swiss-Prot"] = "uniprot-swiss-prot"; ret["UniProtKB/TrEMBL"] = "uniprot-trembl"; return ret; } void RemoteDBFetcherFactory::init() { QMap outMap; outMap[ BaseSlots::DNA_SEQUENCE_SLOT() ] = BaseTypes::DNA_SEQUENCE_TYPE(); outMap[ BaseSlots::ANNOTATION_TABLE_SLOT() ] = BaseTypes::ANNOTATION_TABLE_TYPE(); DataTypePtr outType( new MapDataType(Descriptor(TYPE), outMap) ); DataTypeRegistry *dr = WorkflowEnv::getDataTypeRegistry(); assert(dr); dr->registerEntry(outType); Descriptor desc(ACTOR_ID, RemoteDBFetcherWorker::tr("Read from remote database"), RemoteDBFetcherWorker::tr("Reads sequences and annotations if any from a remote database.")); QList pds; { Descriptor outd(BasePorts::OUT_SEQ_PORT_ID(), RemoteDBFetcherWorker::tr("Sequence"), RemoteDBFetcherWorker::tr("Sequence")); pds << new PortDescriptor(outd, outType, /*input*/ false, /*output*/ true); } RemoteDBRegistry ®istry = RemoteDBRegistry::getRemoteDBRegistry(); QStringList dataBases = registry.getDBs(); QString defaultDB = dataBases.first(); QList attrs; { Descriptor dbidd(DBID_ID, RemoteDBFetcherWorker::tr("Database"), RemoteDBFetcherWorker::tr("The database to read from.")); attrs << new Attribute(dbidd, BaseTypes::STRING_TYPE(), true, cuteDbNames.value(defaultDB, defaultDB)); Descriptor seqidd(SEQID_ID, RemoteDBFetcherWorker::tr("Resource IDs"), RemoteDBFetcherWorker::tr("Semicolon-separated list of resource IDs in the database.")); attrs << new Attribute(seqidd, BaseTypes::STRING_TYPE(), true, ""); Descriptor fullpathd(PATH_ID, RemoteDBFetcherWorker::tr("Save file to directory"), RemoteDBFetcherWorker::tr("Directory to store sequence files loaded from a database.")); attrs << new Attribute(fullpathd, BaseTypes::STRING_TYPE(), true, DEFAULT_PATH); } ActorPrototype *proto = new IntegralBusActorPrototype(desc, pds, attrs); QMap delegates; { QVariantMap values; foreach(const QString &dbName, dataBases) { values[dbName] = cuteDbNames.value(dbName, dbName); } delegates[DBID_ID] = new ComboBoxDelegate(values); delegates[SEQID_ID] = new StringListDelegate(); delegates[PATH_ID] = new URLDelegate(QString(), QString(), false, true); } proto->setEditor(new DelegateEditor(delegates)); proto->setPrompter(new RemoteDBFetcherPrompter()); if(AppContext::isGUIMode()) { proto->setIcon(GUIUtils::createRoundIcon(ICOLOR, 22)); } WorkflowEnv::getProtoRegistry()->registerProto(BaseActorCategories::CATEGORY_DATASRC(), proto); DomainFactory *localDomain = WorkflowEnv::getDomainRegistry()->getById(LocalDomainFactory::ID); localDomain->registerEntry(new RemoteDBFetcherFactory()); } } // namespace U2::LocalWorkflow } ugene-1.9.8/src/plugins/workflow_designer/src/library/ExternalProcessWorker.h0000644000175000017500000000537211651544325026250 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef ExtrenalProcessWorker_h__ #define ExtrenalProcessWorker_h__ #include #include #include #include #include namespace U2 { namespace LocalWorkflow { class ExternalProcessWorker: public BaseWorker { Q_OBJECT public: ExternalProcessWorker(Actor *a): BaseWorker(a, false), output(NULL) { ExternalToolCfgRegistry * reg = WorkflowEnv::getExternalCfgRegistry(); cfg = reg->getConfigByName(actor->getProto()->getId()); commandLine = cfg->cmdLine; done = false; busy = false; } bool isReady(); bool isDone(); Task* tick(); void init(); void cleanup(); private slots: void sl_onTaskFinishied(); private: const QString generateURL(const QString &extention, const QString &name); CommunicationChannel *output; QList inputs; QString commandLine; ExternalProcessConfig *cfg; QStringList inputUrls; QMap outputUrls; bool done; bool busy; }; class ExternalProcessWorkerFactory: public DomainFactory { public: ExternalProcessWorkerFactory(QString name) : DomainFactory(name) {} static bool init(ExternalProcessConfig * cfg); virtual Worker* createWorker(Actor* a) {return new ExternalProcessWorker(a);} }; class ExternalProcessWorkerPrompter: public PrompterBase { Q_OBJECT public: ExternalProcessWorkerPrompter(Actor *p = NULL): PrompterBase(p) {} QString composeRichDoc(); }; class LaunchExternalToolTask: public Task { Q_OBJECT public: LaunchExternalToolTask(const QString &execString); void run(); private: QString execString; }; } } #endif // ExtrenalProcessWorker_h__ ugene-1.9.8/src/plugins/workflow_designer/src/library/GenericReadActor.h0000644000175000017500000000363211651544325025073 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_WORKFLOW_SEQ_ACTOR_H_ #define _U2_WORKFLOW_SEQ_ACTOR_H_ #include #include #include namespace U2 { namespace Workflow { class GenericMAActorProto : public IntegralBusActorPrototype { public: static const QString TYPE; GenericMAActorProto(); virtual bool isAcceptableDrop(const QMimeData*, QVariantMap*) const; }; class GenericSeqActorProto : public IntegralBusActorPrototype { public: enum Mode{ SPLIT, MERGE, }; static const QString MODE_ATTR; static const QString GAP_ATTR; static const QString ACC_ATTR; static const QString TYPE; GenericSeqActorProto(); virtual bool isAcceptableDrop(const QMimeData*, QVariantMap*) const; }; class SeqReadPrompter; typedef PrompterBase SeqReadPrompterBase; class SeqReadPrompter : public SeqReadPrompterBase { Q_OBJECT public: SeqReadPrompter(Actor* p = 0) : SeqReadPrompterBase(p) {} protected: QString composeRichDoc(); }; }//namespace Workflow }//namespace U2 #endif ugene-1.9.8/src/plugins/workflow_designer/src/library/Text2SequenceWorker.cpp0000644000175000017500000002506311651544325026160 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include #include #include #include #include #include #include #include #include #include #include #include #include "Text2SequenceWorker.h" namespace U2 { namespace LocalWorkflow { const QString Text2SequenceWorkerFactory::ACTOR_ID("convert-text-to-sequence"); static const Descriptor TEXT_2_SEQUENCE_IN_TYPE_ID("text-2-sequence-in-type"); static const Descriptor TEXT_2_SEQUENCE_OUT_TYPE_ID("text-2-sequence-out-type"); static const QString SEQ_NAME_ATTR_ID("sequence-name"); static const QString ALPHABET_ATTR_ID("alphabet"); static const QString SKIP_SYM_ATTR_ID("skip-unknown"); static const QString REPLACE_SYM_ATTR_ID("replace-unknown-with"); static const QString SEQ_NAME_ATTR_DEF_VAL("Sequence"); static const QString ALPHABET_ATTR_ID_DEF_VAL("Auto"); /******************************* * Text2SequenceWorker *******************************/ QMap Text2SequenceWorker::cuteAlIdNames = Text2SequenceWorker::initCuteAlNames(); QMap Text2SequenceWorker::initCuteAlNames() { QMap res; res[BaseDNAAlphabetIds::RAW()] = "All symbols"; res[BaseDNAAlphabetIds::NUCL_DNA_DEFAULT()] = "Standard DNA"; res[BaseDNAAlphabetIds::NUCL_RNA_DEFAULT()] = "Standard RNA"; res[BaseDNAAlphabetIds::NUCL_DNA_EXTENDED()] = "Extended DNA"; res[BaseDNAAlphabetIds::NUCL_RNA_EXTENDED()] = "Extended RNA"; res[BaseDNAAlphabetIds::AMINO_DEFAULT()] = "Standard amino"; return res; } void Text2SequenceWorker::init() { txtPort = ports.value(BasePorts::IN_TEXT_PORT_ID()); outSeqPort = ports.value(BasePorts::OUT_SEQ_PORT_ID()); } bool Text2SequenceWorker::isReady() { return txtPort->hasMessage(); } Task * Text2SequenceWorker::tick() { Message inputMessage = getMessageAndSetupScriptValues(txtPort); QString seqName = actor->getParameter(SEQ_NAME_ATTR_ID)->getAttributeValue(); if(seqName.isEmpty()) { return new FailTask(tr("Sequence name not set")); } if(tickedNum++ > 0) { seqName += QString::number(tickedNum); } QString alId = actor->getParameter(ALPHABET_ATTR_ID)->getAttributeValue(); if(alId.isEmpty()) { alId = ALPHABET_ATTR_ID_DEF_VAL; } else { alId = cuteAlIdNames.key(alId, alId); } bool skipUnknown = actor->getParameter(SKIP_SYM_ATTR_ID)->getAttributeValue(); QChar replaceChar; if(!skipUnknown) { QString replaceStr = actor->getParameter(REPLACE_SYM_ATTR_ID)->getAttributeValue(); assert(replaceStr.size() <= 1); if(replaceStr.isEmpty()) { return new FailTask(tr("skip flag should be set or replace character defined")); } replaceChar = replaceStr.at(0); } QByteArray txt = inputMessage.getData().toMap().value(BaseSlots::TEXT_SLOT().getId()).value().toUtf8(); DNAAlphabetRegistry * alphabetRegistry = AppContext::getDNAAlphabetRegistry(); DNAAlphabet * alphabet = NULL; if(alId == ALPHABET_ATTR_ID_DEF_VAL) { alphabet = alphabetRegistry->findAlphabet(txt); } else { alphabet = alphabetRegistry->findById(alId); } if(alphabet == NULL) { QString msg; if(alId == ALPHABET_ATTR_ID_DEF_VAL) { msg = tr("Alphabet cannot be automatically detected"); } else { msg = tr("Alphabet '%1' cannot be found"); } return new FailTask(msg); } QByteArray normSequence = SeqPasterWidgetController::getNormSequence(alphabet, txt, !skipUnknown, replaceChar); DNASequence result(seqName, normSequence, alphabet); QVariantMap msgData; { msgData[BaseSlots::DNA_SEQUENCE_SLOT().getId()] = qVariantFromValue(result); } if(outSeqPort) { outSeqPort->put(Message(BaseTypes::DNA_SEQUENCE_TYPE(), msgData)); } if(txtPort->isEnded()) { outSeqPort->setEnded(); } return NULL; } bool Text2SequenceWorker::isDone() { return txtPort->isEnded(); } void Text2SequenceWorker::cleanup() { } /******************************* * Text2SequenceWorkerFactory *******************************/ void Text2SequenceWorkerFactory::init() { // ports description QList portDescs; { QMap inM; inM[BaseSlots::TEXT_SLOT()] = BaseTypes::STRING_TYPE(); DataTypePtr inSet(new MapDataType(TEXT_2_SEQUENCE_IN_TYPE_ID, inM)); Descriptor inPortDesc(BasePorts::IN_TEXT_PORT_ID(), Text2SequenceWorker::tr("Input text"), Text2SequenceWorker::tr("A text which will be converted to sequence")); portDescs << new PortDescriptor(inPortDesc, inSet, true); QMap outM; outM[BaseSlots::DNA_SEQUENCE_SLOT()] = BaseTypes::DNA_SEQUENCE_TYPE(); DataTypePtr outSet(new MapDataType(TEXT_2_SEQUENCE_OUT_TYPE_ID, outM)); Descriptor outPortDesc(BasePorts::OUT_SEQ_PORT_ID(), Text2SequenceWorker::tr("Output sequence"), Text2SequenceWorker::tr("Converted sequence")); portDescs << new PortDescriptor(outPortDesc, outSet, false); } // attributes description QList attrs; { Descriptor seqNameDesc(SEQ_NAME_ATTR_ID, Text2SequenceWorker::tr("Sequence name"), Text2SequenceWorker::tr("Result sequence name")); Descriptor alphabetDesc(ALPHABET_ATTR_ID, Text2SequenceWorker::tr("Sequence alphabet"), Text2SequenceWorker::tr("Select one of the listed alphabets or choose auto to auto-detect")); Descriptor skipSymbolsDesc(SKIP_SYM_ATTR_ID, Text2SequenceWorker::tr("Skip unknown symbols"), Text2SequenceWorker::tr("Do not include symbols that are not contained in alphabet")); Descriptor replaceSymbolsDesc(REPLACE_SYM_ATTR_ID, Text2SequenceWorker::tr("Replace unknown symbols with"), Text2SequenceWorker::tr("Replace unknown symbols with given character")); attrs << new Attribute(seqNameDesc, BaseTypes::STRING_TYPE(), /* required */ true, QVariant(SEQ_NAME_ATTR_DEF_VAL)); attrs << new Attribute(alphabetDesc, BaseTypes::STRING_TYPE(), false, QVariant(ALPHABET_ATTR_ID_DEF_VAL)); attrs << new Attribute(skipSymbolsDesc, BaseTypes::BOOL_TYPE(), false, QVariant(true)); attrs << new Attribute(replaceSymbolsDesc, BaseTypes::STRING_TYPE(), false); } Descriptor protoDesc(Text2SequenceWorkerFactory::ACTOR_ID, Text2SequenceWorker::tr("Convert text to sequence"), Text2SequenceWorker::tr("Converts input text to sequence")); ActorPrototype * proto = new IntegralBusActorPrototype(protoDesc, portDescs, attrs); // proto delegates QMap delegates; { QVariantMap alMap; QList alps = AppContext::getDNAAlphabetRegistry()->getRegisteredAlphabets(); foreach(DNAAlphabet *a, alps){ alMap[a->getName()] = Text2SequenceWorker::cuteAlIdNames[a->getId()]; } alMap[ALPHABET_ATTR_ID_DEF_VAL] = ALPHABET_ATTR_ID_DEF_VAL; delegates[ALPHABET_ATTR_ID] = new ComboBoxDelegate(alMap); delegates[REPLACE_SYM_ATTR_ID] = new CharacterDelegate(); } proto->setEditor(new DelegateEditor(delegates)); proto->setPrompter(new Text2SequencePrompter()); WorkflowEnv::getProtoRegistry()->registerProto(BaseActorCategories::CATEGORY_CONVERTERS(), proto); WorkflowEnv::getDomainRegistry()->getById( LocalDomainFactory::ID )->registerEntry( new Text2SequenceWorkerFactory() ); } Worker * Text2SequenceWorkerFactory::createWorker(Actor* a) { return new Text2SequenceWorker(a); } /******************************* * Text2SequencePrompter *******************************/ QString Text2SequencePrompter::composeRichDoc() { QString unsetStr = ""+tr("unset")+""; IntegralBusPort * input = qobject_cast(target->getPort(BasePorts::IN_TEXT_PORT_ID())); Actor * txtProducer = input->getProducer(BaseSlots::TEXT_SLOT().getId()); QString txtProducetStr = tr(" from %1").arg(txtProducer ? txtProducer->getLabel() : unsetStr); QString seqName = getRequiredParam(SEQ_NAME_ATTR_ID); QString seqNameStr = tr("sequence with name %1").arg(getHyperlink(SEQ_NAME_ATTR_ID, seqName)); QString alId = getParameter(ALPHABET_ATTR_ID).value(); QString seqAlStr; if(alId == ALPHABET_ATTR_ID_DEF_VAL) { seqAlStr = getHyperlink(ALPHABET_ATTR_ID, tr("Automatically detect sequence alphabet")); } else { alId = Text2SequenceWorker::cuteAlIdNames.key(alId, ""); DNAAlphabet * alphabet = AppContext::getDNAAlphabetRegistry()->findById(alId); QString alphStr = getHyperlink(ALPHABET_ATTR_ID, alphabet ? alphabet->getName() : unsetStr); seqAlStr = tr("Set sequence alphabet to %1").arg(alphStr); } bool skipUnknown = getParameter(SKIP_SYM_ATTR_ID).value(); QString replaceStr = getRequiredParam(REPLACE_SYM_ATTR_ID); QString unknownSymbolsStr; if (skipUnknown) { unknownSymbolsStr = getHyperlink(SKIP_SYM_ATTR_ID, tr("skipped")); } else { unknownSymbolsStr = QString("%1 %2") .arg(getHyperlink(SKIP_SYM_ATTR_ID, tr("replaced with symbol"))) .arg(getHyperlink(REPLACE_SYM_ATTR_ID, replaceStr)); } QString doc = tr("Convert input text%1 to %2. %3. Unknown symbols are %4.") .arg(txtProducetStr) .arg(seqNameStr) .arg(seqAlStr) .arg(unknownSymbolsStr); return doc; } } // LocalWorkflow } // U2 ugene-1.9.8/src/plugins/workflow_designer/src/library/BaseDocWorker.cpp0000644000175000017500000002166411651544325024764 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "BaseDocWorker.h" #include "CoreLib.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include namespace U2 { namespace LocalWorkflow { /********************************** * BaseDocReader **********************************/ BaseDocReader::BaseDocReader(Actor* a, const QString& tid, const DocumentFormatId& fid) : BaseWorker(a), ch(NULL), fid(fid), done(false), attachDoc2Proj(false) { mtype = WorkflowEnv::getDataTypeRegistry()->getById(tid); } void BaseDocReader::init() { QStringList urls = WorkflowUtils::expandToUrls(actor->getParameter(BaseAttributes::URL_IN_ATTRIBUTE().getId())->getAttributeValue()); Project* p = AppContext::getProject(); foreach(QString url, urls) { Document* doc = NULL; bool newDoc = true; if (p) { doc = p->findDocumentByURL(url); if (doc && doc->getDocumentFormatId() == fid) { newDoc = false; } else { doc = NULL; } } if (!doc) { DocumentFormat* format = AppContext::getDocumentFormatRegistry()->getFormatById(fid); assert(format); IOAdapterFactory* iof = AppContext::getIOAdapterRegistry()->getIOAdapterFactoryById(BaseIOAdapters::url2io(url)); doc = new Document(format, iof, url); } //TODO lock document??? docs.insert(doc, newDoc); } assert(ports.size() == 1); ch = ports.values().first(); } bool BaseDocReader::isReady() { return !isDone(); } Task* BaseDocReader::tick() { if (!docs.isEmpty()) { Document* doc = docs.begin().key(); if (!doc->isLoaded()) { return new LoadUnloadedDocumentTask(doc); } else { doc2data(doc); while (!cache.isEmpty()) { ch->put(cache.takeFirst()); } if (docs.take(doc)) { doc->unload(); delete doc; } } } if (docs.isEmpty()) { done = true; ch->setEnded(); } return NULL; } bool BaseDocReader::isDone() { return done && cache.isEmpty(); } void BaseDocReader::cleanup() { QMapIterator it(docs); while (it.hasNext()) { it.next(); if (it.value()) { if (it.key()->isLoaded()) { it.key()->unload(); } delete it.key(); } } } /********************************** * BaseDocWriter **********************************/ BaseDocWriter::BaseDocWriter(Actor* a, const DocumentFormatId& fid) : BaseWorker(a), ch(NULL), format(NULL), done(false), append(false), fileMode(SaveDoc_Roll) { format = AppContext::getDocumentFormatRegistry()->getFormatById(fid); } BaseDocWriter::BaseDocWriter( Actor * a ) : BaseWorker(a), ch(NULL), format(NULL), done(false), append(false), fileMode(SaveDoc_Roll) { } bool BaseDocWriter::isDone() { return done; } void BaseDocWriter::cleanup() { } void BaseDocWriter::init() { assert(ports.size() == 1); ch = ports.values().first(); } bool BaseDocWriter::isReady() { int hasMsg = ch->hasMessage(); bool ended = ch->isEnded(); return hasMsg || (ended && !done); } #define GZIP_SUFFIX ".gz" Task* BaseDocWriter::tick() { while(ch->hasMessage()) { Message inputMessage = getMessageAndSetupScriptValues(ch); Attribute * formatAttr = actor->getParameter(BaseAttributes::DOCUMENT_FORMAT_ATTRIBUTE().getId()); if( formatAttr != NULL ) { // user sets format QString formatId = formatAttr->getAttributeValue(); format = AppContext::getDocumentFormatRegistry()->getFormatById( formatId ); } Attribute * urlAttribute = actor->getParameter(BaseAttributes::URL_OUT_ATTRIBUTE().getId()); url = urlAttribute->getAttributeValue(); fileMode = actor->getParameter(BaseAttributes::FILE_MODE_ATTRIBUTE().getId())->getAttributeValue(); fileMode |= SaveDoc_DestroyAfter; Attribute* a = actor->getParameter(BaseAttributes::ACCUMULATE_OBJS_ATTRIBUTE().getId()); if(a != NULL) { append = a->getAttributeValue(); } QVariantMap data = inputMessage.getData().toMap(); if(format == NULL) { return new FailTask(tr("Document format not set")); } Document* doc = NULL; QString anUrl = url; if (anUrl.isEmpty()) { anUrl = data.value(BaseSlots::URL_SLOT().getId()).toString(); } if (anUrl.isEmpty()) { QString err = tr("Unspecified URL to write %1").arg(format->getFormatName()); return new FailTask(err); } // to avoid "c:/..." and "C:/..." on windows anUrl = QFileInfo(anUrl).absoluteFilePath(); // set correct file extension // commented because of UGENE-537 //GUrl path(anUrl); //QStringList suffixList = format->getSupportedDocumentFileExtensions(); //QString suffix = /*path.completeFileSuffix();*/ path.lastFileSuffix(); //QString newSuffix = suffixList.first(); //if (suffix.contains("gz")) { // newSuffix.append(GZIP_SUFFIX); // suffix = path.completeFileSuffix(); // suffix.remove(GZIP_SUFFIX); //} //if (!suffixList.contains(suffix)) { // path = path.dirPath() + "/" + path.baseFileName() + "." + newSuffix; // anUrl = path.getURLString(); // //urlAttribute->setAttributeValue(anUrl); //} doc = docs.value(anUrl); if (!doc) { IOAdapterFactory* iof = AppContext::getIOAdapterRegistry()->getIOAdapterFactoryById(BaseIOAdapters::url2io(url)); // commented because of UGENE-537 /*int count = ++counter[anUrl]; if(!append && count > 1) { anUrl = GUrlUtils::prepareFileName(anUrl, count, format->getSupportedDocumentFileExtensions()); } else { assert(count == 1); anUrl = GUrlUtils::ensureFileExt(anUrl, format->getSupportedDocumentFileExtensions()).getURLString(); } urlAttribute->setAttributeValue(anUrl);*/ doc = new Document(format, iof, anUrl); doc->setLoaded(true); docs.insert(anUrl, doc); } data2doc(doc, data); if (!append) { break; } } done = ch->isEnded(); if (append && !done) { return NULL; } return processDocs(); } Task* BaseDocWriter::processDocs() { if(docs.isEmpty()) { //coreLog.error( "nothing to write: no documents" ); return new FailTask("nothing to write: no documents"); } QList tlist; QMapIterator it(docs); while (it.hasNext()) { it.next(); Document* doc = it.value(); QString anUrl = it.key(); //int count = ++counter[anUrl]; /*if (!append && count != 1) { anUrl = GUrlUtils::prepareFileName(anUrl, count, format->getSupportedDocumentFileExtensions()); } else { assert(count == 1); anUrl = GUrlUtils::ensureFileExt(anUrl, format->getSupportedDocumentFileExtensions()).getURLString(); }*/ //doc->setURL(anUrl); ioLog.details(tr("Writing to %1 [%2]").arg(anUrl).arg(format->getFormatName())); tlist << new SaveDocumentTask(doc, SaveDocFlags(fileMode), DocumentUtils::getNewDocFileNameExcludesHint()); } docs.clear(); return tlist.size() == 1 ? tlist.first() : new MultiTask(tr("Save documents"), tlist); } } // Workflow namespace } // U2 namespace ugene-1.9.8/src/plugins/workflow_designer/src/library/ImportAnnotationsWorker.cpp0000644000175000017500000001600211651544325027142 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "DocActors.h" #include "ImportAnnotationsWorker.h" namespace U2 { namespace LocalWorkflow { const QString ImportAnnotationsWorkerFactory::ACTOR_ID("import-annotations"); static const QString IMPORT_ANNOTATIONS_IN_TYPE_ID("import.annotations.in.port"); static const QString IMPORT_ANNOTATIONS_OUT_TYPE_ID("import.annotations.out.port"); /************************** * ImportAnnotationsWorker **************************/ void ImportAnnotationsWorker::init() { inPort = ports.value(BasePorts::IN_ANNOTATIONS_PORT_ID()); outPort = ports.value(BasePorts::OUT_ANNOTATIONS_PORT_ID()); assert(inPort && outPort); } bool ImportAnnotationsWorker::isReady() { return inPort->hasMessage(); } Task * ImportAnnotationsWorker::tick() { Message inputMessage = getMessageAndSetupScriptValues(inPort); QList urls = WorkflowUtils::expandToUrls( actor->getParameter(BaseAttributes::URL_IN_ATTRIBUTE().getId())->getAttributeValue()); QList loadTasks; foreach(const QString & url, urls) { LoadDocumentTask * loadDocTask = LoadDocumentTask::getDefaultLoadDocTask(url); if(loadDocTask == NULL) { qDeleteAll(loadTasks); return new FailTask(L10N::errorOpeningFileRead(url)); } loadTasks << loadDocTask; } Task * ret = new MultiTask(tr("Load documents with annotations"), loadTasks); connect(new TaskSignalMapper(ret), SIGNAL(si_taskFinished(Task*)), SLOT(sl_docsLoaded(Task*))); annsMap[ret] = QVariantUtils::var2ftl(inputMessage.getData().toMap().value(BaseSlots::ANNOTATION_TABLE_SLOT().getId()).toList()); return ret; } static QList getAnnsFromDoc(Document* doc) { QList ret; if(doc == NULL) { return ret; } QList objs = doc->findGObjectByType(GObjectTypes::ANNOTATION_TABLE); foreach(GObject* obj, objs) { AnnotationTableObject * annObj = qobject_cast(obj); if(NULL == annObj) { continue; } foreach(Annotation * a, annObj->getAnnotations()) { if(a != NULL) { ret << a->data(); } } } return ret; } void ImportAnnotationsWorker::sl_docsLoaded(Task* ta) { MultiTask * t = qobject_cast(ta); if(t == NULL || t->hasError()) { return; } QList anns = annsMap.value(t); QList loadSubs = t->getTasks(); foreach(Task * s, loadSubs) { LoadDocumentTask * sub = qobject_cast(s); if(sub == NULL || sub->hasError()) { continue; } anns.append(getAnnsFromDoc(sub->getDocument())); } QVariant v = qVariantFromValue >(anns); outPort->put(Message(BaseTypes::ANNOTATION_TABLE_TYPE(), v)); if(inPort->isEnded()) { outPort->setEnded(); } } bool ImportAnnotationsWorker::isDone() { return inPort->isEnded(); } void ImportAnnotationsWorker::cleanup() { } /********************************* * ImportAnnotationsWorkerFactory *********************************/ void ImportAnnotationsWorkerFactory::init() { // ports description QList portDescs; { QMap inM; inM[BaseSlots::ANNOTATION_TABLE_SLOT()] = BaseTypes::ANNOTATION_TABLE_LIST_TYPE(); DataTypePtr inSet(new MapDataType(IMPORT_ANNOTATIONS_IN_TYPE_ID, inM)); Descriptor inPortDesc(BasePorts::IN_ANNOTATIONS_PORT_ID(), ImportAnnotationsWorker::tr("Input annotations"), ImportAnnotationsWorker::tr("Input annotation table. Read annotations will be added to it")); portDescs << new PortDescriptor(inPortDesc, inSet, true); QMap outM; outM[BaseSlots::ANNOTATION_TABLE_SLOT()] = BaseTypes::ANNOTATION_TABLE_TYPE(); DataTypePtr outSet(new MapDataType(IMPORT_ANNOTATIONS_OUT_TYPE_ID, outM)); Descriptor outPortDesc(BasePorts::OUT_ANNOTATIONS_PORT_ID(), ImportAnnotationsWorker::tr("Output annotations"), ImportAnnotationsWorker::tr("Output annotation table")); portDescs << new PortDescriptor(outPortDesc, outSet, false); } // attributes description QList attrs; { attrs << new Attribute(BaseAttributes::URL_IN_ATTRIBUTE(), BaseTypes::STRING_TYPE(), true); } Descriptor protoDesc(ImportAnnotationsWorkerFactory::ACTOR_ID, ImportAnnotationsWorker::tr("Merge annotations"), ImportAnnotationsWorker::tr("Read input annotation table and merge it with supplied annotation tables")); ActorPrototype * proto = new IntegralBusActorPrototype(protoDesc, portDescs, attrs); //proto delegates QMap delegates; { delegates[BaseAttributes::URL_IN_ATTRIBUTE().getId()] = new URLDelegate( DialogUtils::prepareDocumentsFileFilterByObjType(GObjectTypes::ANNOTATION_TABLE, true), QString(), true ); } proto->setEditor(new DelegateEditor(delegates)); proto->setPrompter(new ReadDocPrompter(ImportAnnotationsWorker::tr("Merge input annotations with annotations from %1."))); WorkflowEnv::getProtoRegistry()->registerProto(BaseActorCategories::CATEGORY_BASIC(), proto); WorkflowEnv::getDomainRegistry()->getById(LocalDomainFactory::ID)->registerEntry(new ImportAnnotationsWorkerFactory()); } Worker * ImportAnnotationsWorkerFactory::createWorker(Actor* a) { return new ImportAnnotationsWorker(a); } } // LocalWorkflow } // U2 ugene-1.9.8/src/plugins/workflow_designer/src/library/FindWorker.h0000644000175000017500000000452211651544325024003 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_FIND_WORKER_H_ #define _U2_FIND_WORKER_H_ #include #include #include #include namespace U2 { namespace LocalWorkflow { class FindPrompter : public PrompterBase { Q_OBJECT public: FindPrompter(Actor* p = 0) : PrompterBase(p) {} protected: QString composeRichDoc(); }; class FindWorker : public BaseWorker { Q_OBJECT public: FindWorker(Actor* a); virtual void init(); virtual bool isReady(); virtual Task* tick(); virtual bool isDone(); virtual void cleanup(); private slots: void sl_taskFinished(Task*); protected: CommunicationChannel *input, *output; QString resultName; QMap patterns; }; class FindWorkerFactory : public DomainFactory { public: static const QString ACTOR_ID; static void init(); FindWorkerFactory() : DomainFactory(ACTOR_ID) {} virtual Worker* createWorker(Actor* a) {return new FindWorker(a);} }; class FindAllRegionsTask : public Task { //FIXME this is temporary solution until FindAlgorithmTask moved to SequenceWalker Q_OBJECT public: FindAllRegionsTask(const FindAlgorithmTaskSettings& s, const QList&); virtual void prepare(); QList getResult(); private: FindAlgorithmTaskSettings cfg; QList regions; }; } // Workflow namespace } // U2 namespace #endif ugene-1.9.8/src/plugins/workflow_designer/src/library/CDSearchWorker.h0000644000175000017500000000404611651544325024540 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_CDSEARCH_WORKER_H_ #define _U2_CDSEARCH_WORKER_H_ #include #include #include namespace U2 { namespace LocalWorkflow { class CDSearchPrompter; typedef PrompterBase CDSearchPrompterBase; class CDSearchPrompter : public CDSearchPrompterBase { Q_OBJECT public: CDSearchPrompter(Actor* p = 0) : CDSearchPrompterBase(p) {} protected: QString composeRichDoc(); }; class CDSearchWorker: public BaseWorker { Q_OBJECT public: CDSearchWorker(Actor *a) : BaseWorker(a), input(NULL), output(NULL), cds(NULL) {} virtual void init(); virtual bool isReady(); virtual bool isDone(); virtual Task* tick(); virtual void cleanup() {}; private slots: void sl_taskFinished(Task*); protected: CommunicationChannel *input, *output; CDSearchSettings settings; CDSearchResultListener* cds; }; class CDSearchWorkerFactory : public DomainFactory { static const QString ACTOR_ID; public: static void init(); CDSearchWorkerFactory() : DomainFactory(ACTOR_ID) {} virtual Worker* createWorker(Actor* a) {return new CDSearchWorker(a);} }; } // Workflow } // U2 #endif ugene-1.9.8/src/plugins/workflow_designer/src/library/RemoteDBFetcherWorker.h0000644000175000017500000000420111651544325026057 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_REMOTE_DB_FETCHER_H_ #define _U2_REMOTE_DB_FETCHER_H_ #include #include namespace U2 { namespace LocalWorkflow { class RemoteDBFetcherPrompter : public PrompterBase { Q_OBJECT public: RemoteDBFetcherPrompter(Actor *p = 0) : PrompterBase(p) {} protected: virtual QString composeRichDoc(); }; class RemoteDBFetcherWorker : public BaseWorker { Q_OBJECT public: RemoteDBFetcherWorker (Actor *a); virtual void init(); virtual bool isReady(); virtual Task* tick(); virtual bool isDone(); virtual void cleanup(); private slots: void sl_taskFinished(); protected: CommunicationChannel *output; QString dbid; QString fullPathDir; QStringList seqids; }; class RemoteDBFetcherFactory : public DomainFactory { public: static const QString ACTOR_ID; static const QMap cuteDbNames; private: static QMap initCuteDbNames(); public: RemoteDBFetcherFactory() : DomainFactory(ACTOR_ID) {} static void init(); virtual Worker* createWorker(Actor *a) { return new RemoteDBFetcherWorker(a); } }; } // namespace U2 } // namespace LocalWorkflow #endif // #ifndef _U2_REMOTE_DB_FETCHER_H_ ugene-1.9.8/src/plugins/workflow_designer/src/library/StatisticWorkers.cpp0000644000175000017500000001471111651544325025611 0ustar ilyailya#include "StatisticWorkers.h" #include #include #include #include #include #include #include #include #include #include #include #include #include namespace U2 { namespace LocalWorkflow { const QString DNAStatWorkerFactory::ACTOR_ID("dna-stats"); const QString GCCONTENT("gc-content"); const QString GC1CONTENT("gc1-content"); const QString GC2CONTENT("gc2-content"); const QString GC3CONTENT("gc3-content"); void DNAStatWorkerFactory::init() { QList portDescs; QList attribs; //accept sequence and annotated regions as input QMap inputMap; QMap outputMap; inputMap[ BaseSlots::DNA_SEQUENCE_SLOT() ] = BaseTypes::DNA_SEQUENCE_TYPE(); outputMap[ BaseSlots::ANNOTATION_TABLE_SLOT() ] = BaseTypes::ANNOTATION_TABLE_TYPE(); { //Create input port descriptors Descriptor inDesc( BasePorts::IN_SEQ_PORT_ID(), DNAStatWorker::tr("Input sequence"), DNAStatWorker::tr("Sequence for which GC-content and GC3-content will be evaluated.") ); Descriptor outDesc( BasePorts::OUT_ANNOTATIONS_PORT_ID(), DNAStatWorker::tr("Result annotation"), DNAStatWorker::tr("Resulted annotations, with GC-content and GC3-content.") ); portDescs << new PortDescriptor( inDesc, DataTypePtr(new MapDataType("filter.anns", inputMap)), /*input*/ true ); portDescs << new PortDescriptor( outDesc, DataTypePtr(new MapDataType("filter.anns", outputMap)), /*input*/false, /*multi*/true ); } attribs << new Attribute(Descriptor(GCCONTENT, DNAStatWorker::tr("GC-content"), DNAStatWorker::tr("Evaluate GC-content")), BaseTypes::BOOL_TYPE(),false, true); attribs << new Attribute(Descriptor(GC1CONTENT, DNAStatWorker::tr("GC1-content"), DNAStatWorker::tr("Evaluate GC1-content")), BaseTypes::BOOL_TYPE(),false, true); attribs << new Attribute(Descriptor(GC2CONTENT, DNAStatWorker::tr("GC2-content"), DNAStatWorker::tr("Evaluate GC2-content")), BaseTypes::BOOL_TYPE(),false, true); attribs << new Attribute(Descriptor(GC3CONTENT, DNAStatWorker::tr("GC3-content"), DNAStatWorker::tr("Evaluate GC3-content")), BaseTypes::BOOL_TYPE(),false, true); Descriptor desc( ACTOR_ID, DNAStatWorker::tr("DNA statistics"), DNAStatWorker::tr("Evaluates statistics for DNA sequences") ); ActorPrototype * proto = new IntegralBusActorPrototype( desc, portDescs, attribs ); proto->setPrompter( new DNAStatWorkerPrompter() ); proto->setEditor(new DelegateEditor(QMap())); WorkflowEnv::getProtoRegistry()->registerProto( BaseActorCategories::CATEGORY_STATISTIC(), proto ); DomainFactory* localDomain = WorkflowEnv::getDomainRegistry()->getById( LocalDomainFactory::ID ); localDomain->registerEntry( new DNAStatWorkerFactory() ); } QString DNAStatWorkerPrompter::composeRichDoc() { return tr("Evaluates GC-Content and GC3-Content"); } void DNAStatWorker::init() { input = ports.value(BasePorts::IN_SEQ_PORT_ID()); output = ports.value(BasePorts::OUT_ANNOTATIONS_PORT_ID()); } bool DNAStatWorker::isReady() { return input->hasMessage(); } Task* DNAStatWorker::tick() { Message inputMessage = getMessageAndSetupScriptValues(input); QVariantMap qm = inputMessage.getData().toMap(); DNASequence dna = qVariantValue( qm.value(BaseSlots::DNA_SEQUENCE_SLOT().getId()) ); if(!dna.alphabet->isNucleic()) { return new FailTask(tr("Sequence must be nucleotide")); } QList res; SharedAnnotationData gcAnn(new AnnotationData()); gcAnn->name = "statistics"; gcAnn->location->regions << U2Region( 0, dna.seq.size()); if(actor->getParameter(GCCONTENT)->getAttributeValue()) { float gcContent = calcGCContent(dna.seq); gcAnn->qualifiers.push_back(U2Qualifier("gc-content", QString::number(gcContent*100) + "%")); } if(actor->getParameter(GC1CONTENT)->getAttributeValue()) { float gc1Content = calcGC1Content(dna.seq); gcAnn->qualifiers.push_back(U2Qualifier("gc1-content", QString::number(gc1Content*100) + "%")); } if(actor->getParameter(GC2CONTENT)->getAttributeValue()) { float gc2Content = calcGC2Content(dna.seq); gcAnn->qualifiers.push_back(U2Qualifier("gc2-content", QString::number(gc2Content*100) + "%")); } if(actor->getParameter(GC3CONTENT)->getAttributeValue()) { float gc3Content = calcGC3Content(dna.seq); gcAnn->qualifiers.push_back(U2Qualifier("gc3-content", QString::number(gc3Content*100) + "%")); } if(gcAnn->qualifiers.isEmpty()) { return new FailTask(tr("No statistics was selected")); } res << gcAnn; QVariant v = qVariantFromValue >(res); output->put( Message(BaseTypes::ANNOTATION_TABLE_TYPE(), v) ); if (input->isEnded()) { output->setEnded(); } return NULL; } bool DNAStatWorker::isDone() { return input->isEnded(); } float DNAStatWorker::calcGCContent(const QByteArray &seq) { int gc = 0; for(int i = 0; i < seq.size(); i++) { if(QRegExp("[cCgG]").exactMatch(QString(seq.at(i)))){ gc++; } } float gcContent = (float)gc/seq.size(); return gcContent; } float DNAStatWorker::calcGC1Content(const QByteArray &seq) { int gc1 = 0; for(int i = 0; i < seq.size(); i+=3) { if(QRegExp("[cCgG]").exactMatch(QString(seq.at(i)))){ gc1++; } } float gc1Content = (float)gc1/seq.size()*3; return gc1Content; } float DNAStatWorker::calcGC2Content(const QByteArray &seq) { int gc2 = 0; for(int i = 1; i < seq.size(); i+=3) { if(QRegExp("[cCgG]").exactMatch(QString(seq.at(i)))){ gc2++; } } float gc2Content = (float)gc2/seq.size()*3; return gc2Content; } float DNAStatWorker::calcGC3Content(const QByteArray &seq) { int gc3 = 0; for(int i = 2; i < seq.size(); i+=3) { if(QRegExp("[cCgG]").exactMatch(QString(seq.at(i)))){ gc3++; } } float gc3Content = (float)gc3/seq.size()*3; return gc3Content; } } //LocalWorkflow } //U2ugene-1.9.8/src/plugins/workflow_designer/src/library/FindWorker.cpp0000644000175000017500000003336211651544325024342 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "CoreLib.h" #include "FindWorker.h" /* TRANSLATOR U2::LocalWorkflow::FindWorker */ namespace U2 { namespace LocalWorkflow { /*************************** * FindWorkerFactory ***************************/ static const QString NAME_ATTR("result-name"); static const QString PATTERN_ATTR("pattern"); static const QString ERR_ATTR("max-mismatches-num"); static const QString ALGO_ATTR("allow-ins-del"); static const QString AMINO_ATTR("amino"); static const QString AMBIGUOUS_ATTR("ambiguous"); const QString FindWorkerFactory::ACTOR_ID("search"); const QString PATTERN_DELIMITER(";"); void FindWorkerFactory::init() { QMap m; m[BaseSlots::DNA_SEQUENCE_SLOT()] = BaseTypes::DNA_SEQUENCE_TYPE(); DataTypePtr inSet(new MapDataType(Descriptor("regioned.sequence"), m)); DataTypeRegistry* dr = WorkflowEnv::getDataTypeRegistry(); assert(dr); dr->registerEntry(inSet); QList p; { Descriptor ind(BasePorts::IN_SEQ_PORT_ID(), FindWorker::tr("Input Data"), FindWorker::tr("An input sequence to search in.")); Descriptor oud(BasePorts::OUT_ANNOTATIONS_PORT_ID(), FindWorker::tr("Pattern Annotations"), FindWorker::tr("The regions found.")); p << new PortDescriptor(ind, inSet, true); QMap outM; outM[BaseSlots::ANNOTATION_TABLE_SLOT()] = BaseTypes::ANNOTATION_TABLE_TYPE(); p << new PortDescriptor(oud, DataTypePtr(new MapDataType("find.annotations", outM)), false, true); } QList a; { Descriptor nd(NAME_ATTR, FindWorker::tr("Annotate as"), FindWorker::tr("Name of the result annotations.")); Descriptor pd(PATTERN_ATTR, FindWorker::tr("Pattern(s)"), FindWorker::tr("Semicolon-separated list of patterns to search for.")); Descriptor ed(ERR_ATTR, FindWorker::tr("Max Mismatches"), FindWorker::tr("Maximum number of mismatches between a substring" " and a pattern.")); Descriptor ald(ALGO_ATTR, FindWorker::tr("Allow Insertions/Deletions"), FindWorker::tr("Takes into account possibility of insertions/deletions" " when searching. By default substitutions are only considered.")); Descriptor ambigd(AMBIGUOUS_ATTR, FindWorker::tr("Support ambiguous bases"), FindWorker::tr("Performs correct handling of ambiguous bases. When this option" " is activated insertions and deletions are not considered. ")); Descriptor amd(AMINO_ATTR, FindWorker::tr("Search in Translation"), FindWorker::tr("Translates a supplied nucleotide sequence to protein" " and searches in the translated sequence.")); a << new Attribute(nd, BaseTypes::STRING_TYPE(), true, "misc_feature"); a << new Attribute(pd, BaseTypes::STRING_TYPE(), true); a << new Attribute(ed, BaseTypes::NUM_TYPE(), false, 0); a << new Attribute(BaseAttributes::STRAND_ATTRIBUTE(), BaseTypes::STRING_TYPE(), false, BaseAttributes::STRAND_BOTH()); a << new Attribute(ald, BaseTypes::BOOL_TYPE(), false, false); a << new Attribute(ambigd, BaseTypes::BOOL_TYPE(), false, false); a << new Attribute(amd, BaseTypes::BOOL_TYPE(), false, false); } Descriptor desc(ACTOR_ID, FindWorker::tr("Find Substrings"), FindWorker::tr("Searches regions in a sequence similar to a pattern" " sequence. Outputs a set of annotations.")); ActorPrototype* proto = new IntegralBusActorPrototype(desc, p, a); QMap delegates; { QVariantMap lenMap; lenMap["minimum"] = QVariant(0); lenMap["maximum"] = QVariant(INT_MAX); delegates[ERR_ATTR] = new SpinBoxDelegate(lenMap); } { delegates[BaseAttributes::STRAND_ATTRIBUTE().getId()] = new ComboBoxDelegate(BaseAttributes::STRAND_ATTRIBUTE_VALUES_MAP()); } proto->setEditor(new DelegateEditor(delegates)); proto->setIconPath( ":core/images/find_dialog.png" ); proto->setPrompter(new FindPrompter()); WorkflowEnv::getProtoRegistry()->registerProto(BaseActorCategories::CATEGORY_BASIC(), proto); DomainFactory* localDomain = WorkflowEnv::getDomainRegistry()->getById(LocalDomainFactory::ID); localDomain->registerEntry(new FindWorkerFactory()); } static FindAlgorithmStrand getStrand(const QString & s) { QString str = s.toLower(); if(BaseAttributes::STRAND_BOTH().startsWith(str)) { return FindAlgorithmStrand_Both; } else if(BaseAttributes::STRAND_DIRECT().startsWith(str)) { return FindAlgorithmStrand_Direct; } else if(BaseAttributes::STRAND_COMPLEMENTARY().startsWith(str)) { return FindAlgorithmStrand_Complement; } else { bool ok = false; int num = str.toInt(&ok); if(ok && num >= 0) { return FindAlgorithmStrand(num); } else { return FindAlgorithmStrand_Both; } } } /*************************** * FindPrompter ***************************/ QString FindPrompter::composeRichDoc() { IntegralBusPort* input = qobject_cast(target->getPort(BasePorts::IN_SEQ_PORT_ID())); Actor* seqProducer = input->getProducer(BaseSlots::DNA_SEQUENCE_SLOT().getId()); QString unsetStr = "" + tr("unset") + ""; QString seqName; seqProducer ? (seqName = seqProducer->getLabel()) : (seqName = unsetStr); FindAlgorithmSettings cfg; cfg.strand = getStrand(getParameter(BaseAttributes::STRAND_ATTRIBUTE().getId()).value()); cfg.maxErr = getParameter(ERR_ATTR).toInt(); cfg.insDelAlg = getParameter(ALGO_ATTR).toBool(); QString pattern = getHyperlink(PATTERN_ATTR, getRequiredParam(PATTERN_ATTR)); QString strandName; switch (cfg.strand) { case FindAlgorithmStrand_Both: strandName = FindWorker::tr("both strands"); break; case FindAlgorithmStrand_Direct: strandName = FindWorker::tr("direct strand"); break; case FindAlgorithmStrand_Complement: strandName = FindWorker::tr("complement strand"); break; default: assert(false); } strandName = getHyperlink(BaseAttributes::STRAND_ATTRIBUTE().getId(), strandName); QString searchInTranslationSelected = ""; if (getParameter(AMINO_ATTR).toBool()) { searchInTranslationSelected = "" + tr("translated") + "" + " "; } searchInTranslationSelected = getHyperlink(AMINO_ATTR, searchInTranslationSelected); QString resultName = getHyperlink(NAME_ATTR, getRequiredParam(NAME_ATTR)); QString matches; if (0 == cfg.maxErr) { matches = tr("A substring must %1.") .arg(getHyperlink(ERR_ATTR, tr("match a pattern exactly"))); } else { matches = tr("Maximum number of mismatches is %1.") .arg(getHyperlink(ERR_ATTR, cfg.maxErr)); } QString doc = tr("Searches regions in each sequence from %1" " similar to %2 pattern(s).
    %3
    Searches in" " %4 of a %5sequence. Outputs the regions found" " annotated as %6.") .arg(seqName) .arg(pattern) .arg(matches) .arg(strandName) .arg(searchInTranslationSelected) .arg(resultName); return doc; } /*************************** * FindWorker ***************************/ FindWorker::FindWorker(Actor* a) : BaseWorker(a), input(NULL), output(NULL) { } void FindWorker::init() { input = ports.value(BasePorts::IN_SEQ_PORT_ID()); output = ports.value(BasePorts::OUT_ANNOTATIONS_PORT_ID()); } bool FindWorker::isReady() { return (input && input->hasMessage()); } Task* FindWorker::tick() { Message inputMessage = getMessageAndSetupScriptValues(input); FindAlgorithmTaskSettings cfg; // sequence QVariantMap qm = inputMessage.getData().toMap(); DNASequence seq = qm.value(BaseSlots::DNA_SEQUENCE_SLOT().getId()).value(); if(seq.isNull()) { return new FailTask(tr("Null sequence supplied to FindWorker: %1").arg(seq.getName())); } cfg.sequence = QByteArray(seq.constData(), seq.length()); cfg.searchRegion.length = seq.length(); // other parameters cfg.maxErr = actor->getParameter(ERR_ATTR)->getAttributeValue(); cfg.insDelAlg = actor->getParameter(ALGO_ATTR)->getAttributeValue(); cfg.useAmbiguousBases = actor->getParameter(AMBIGUOUS_ATTR)->getAttributeValue(); resultName = actor->getParameter(NAME_ATTR)->getAttributeValue(); // translations cfg.strand = getStrand(actor->getParameter(BaseAttributes::STRAND_ATTRIBUTE().getId())->getAttributeValue()); if(cfg.strand != FindAlgorithmStrand_Direct /*&& seq.alphabet->getType() == DNAAlphabet_NUCL*/) { QList compTTs = AppContext::getDNATranslationRegistry()-> lookupTranslation(seq.alphabet, DNATranslationType_NUCL_2_COMPLNUCL); if (!compTTs.isEmpty()) { cfg.complementTT = compTTs.first(); } else { cfg.strand = FindAlgorithmStrand_Direct; } } if(actor->getParameter(AMINO_ATTR)->getAttributeValue()) { DNATranslationType tt = seq.alphabet->getType() == DNAAlphabet_NUCL ? DNATranslationType_NUCL_2_AMINO : DNATranslationType_RAW_2_AMINO; QList TTs = AppContext::getDNATranslationRegistry()->lookupTranslation(seq.alphabet, tt); if (!TTs.isEmpty()) { cfg.proteinTT = TTs.first(); //FIXME let user choose or use hints ? } } // for each pattern run find task QStringList ptrnStrs = actor->getParameter(PATTERN_ATTR)->getAttributeValue().split(PATTERN_DELIMITER, QString::SkipEmptyParts); if(ptrnStrs.isEmpty()) { return new FailTask(tr("Empty pattern given")); } QList subs; foreach(const QString & p, ptrnStrs) { assert(!p.isEmpty()); FindAlgorithmTaskSettings config(cfg); config.pattern = p.toUpper().toAscii(); Task * findTask = new FindAlgorithmTask(config); patterns.insert(findTask, config.pattern); subs << findTask; } assert(!subs.isEmpty()); MultiTask * multiFind = new MultiTask(tr("Find algorithm subtasks"), subs); connect(new TaskSignalMapper(multiFind), SIGNAL(si_taskFinished(Task*)), SLOT(sl_taskFinished(Task*))); return multiFind; } void FindWorker::sl_taskFinished(Task* t) { MultiTask * multiFind = qobject_cast(t); assert(multiFind != NULL); QList subs = multiFind->getTasks(); assert(!subs.isEmpty()); QStringList ptrns; QList annData; foreach(Task * sub, subs) { FindAlgorithmTask * findTask = qobject_cast(sub); assert(findTask != NULL); annData << findTask->popResults(); ptrns << patterns.value(findTask); } if(output) { QVariant v = qVariantFromValue >(FindAlgorithmResult::toTable(annData, resultName)); output->put(Message(BaseTypes::ANNOTATION_TABLE_TYPE(), v)); if (input->isEnded()) { output->setEnded(); } algoLog.info(tr("Found %1 matches of pattern '%2'").arg(annData.size()).arg(ptrns.join(PATTERN_DELIMITER))); } } bool FindWorker::isDone() { return !input || input->isEnded(); } void FindWorker::cleanup() { } /*************************** * FindAllRegionsTask ***************************/ FindAllRegionsTask::FindAllRegionsTask(const FindAlgorithmTaskSettings& s, const QList& l) : Task(tr("FindAllRegionsTask"), TaskFlag_NoRun), cfg(s), regions(l) {} void FindAllRegionsTask::prepare() { foreach(SharedAnnotationData sd, regions) { foreach(U2Region lr, sd->getRegions()) { cfg.searchRegion = lr; addSubTask(new FindAlgorithmTask(cfg)); } } } QList FindAllRegionsTask::getResult() { QList lst; foreach(Task* t, getSubtasks()) { FindAlgorithmTask* ft = qobject_cast(t); lst += ft->popResults(); } return lst; } } //namespace LocalWorkflow } //namespace U2 ugene-1.9.8/src/plugins/workflow_designer/src/library/FilterAnnotationsWorker.cpp0000644000175000017500000001532511651544325027124 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "FilterAnnotationsWorker.h" #include #include #include #include #include #include #include #include #include #include #include namespace U2 { namespace LocalWorkflow { const QString FilterAnnotationsWorkerFactory::ACTOR_ID("filter-annotations"); const static QString FILTER_NAMES_ATTR( "annotation-names" ); const static QString WHICH_FILTER_ATTR( "accept-or-filter" ); QString FilterAnnotationsPrompter::composeRichDoc() { QString unsetStr = ""+tr("unset")+""; QString annName = getProducers(BasePorts::IN_ANNOTATIONS_PORT_ID(), BaseSlots::ANNOTATION_TABLE_SLOT().getId()); annName = annName.isEmpty() ? unsetStr : annName; return tr("Filter annotations from %1 by supplied names.").arg(annName); } void FilterAnnotationsWorker::init() { input = ports.value(BasePorts::IN_ANNOTATIONS_PORT_ID()); output = ports.value(BasePorts::OUT_ANNOTATIONS_PORT_ID()); } bool FilterAnnotationsWorker::isReady() { return input->hasMessage(); } Task* FilterAnnotationsWorker::tick() { Message inputMessage = getMessageAndSetupScriptValues(input); QVariantMap qm = inputMessage.getData().toMap(); inputAnns = qVariantValue >( qm.value(BaseSlots::ANNOTATION_TABLE_SLOT().getId()) ); bool accept = actor->getParameter( WHICH_FILTER_ATTR )->getAttributeValue(); QString namesStr = actor->getParameter( FILTER_NAMES_ATTR )->getAttributeValue(); Task* t = new FilterAnnotationsTask(inputAnns, namesStr, accept); connect(new TaskSignalMapper(t), SIGNAL(si_taskFinished(Task*)), SLOT(sl_taskFinished())); return t; } void FilterAnnotationsWorker::sl_taskFinished() { output->put( Message(BaseTypes::ANNOTATION_TABLE_TYPE(), qVariantFromValue(inputAnns)) ); if (input->isEnded()) { output->setEnded(); } } bool FilterAnnotationsWorker::isDone() { return input->isEnded(); } void FilterAnnotationsWorker::cleanup() { } void FilterAnnotationsWorkerFactory::init() { QList portDescs; QList attribs; //accept sequence and annotated regions as input QMap inputMap; inputMap[ BaseSlots::ANNOTATION_TABLE_SLOT() ] = BaseTypes::ANNOTATION_TABLE_TYPE(); { //Create input port descriptors Descriptor inDesc( BasePorts::IN_ANNOTATIONS_PORT_ID(), FilterAnnotationsWorker::tr("Input annotations"), FilterAnnotationsWorker::tr("Annotations to be filtered by name.") ); Descriptor outDesc( BasePorts::OUT_ANNOTATIONS_PORT_ID(), FilterAnnotationsWorker::tr("Result annotations"), FilterAnnotationsWorker::tr("Resulted annotations, filtered by name.") ); portDescs << new PortDescriptor( inDesc, DataTypePtr(new MapDataType("filter.anns", inputMap)), /*input*/ true ); portDescs << new PortDescriptor( outDesc, DataTypePtr(new MapDataType("filter.anns", inputMap)), /*input*/false, /*multi*/true ); } { //Create attributes descriptors Descriptor filterNamesDesc( FILTER_NAMES_ATTR, FilterAnnotationsWorker::tr("Annotation names"), FilterAnnotationsWorker::tr("File with annotation names, separated with whitespaces or list of annotation names " "which will be accepted or filtered. Use space as the separator.") ); Descriptor whichFilterDesc( WHICH_FILTER_ATTR, FilterAnnotationsWorker::tr("Accept or filter"), FilterAnnotationsWorker::tr("Selects the name filter: accept specified names or accept all except specified") ); attribs << new Attribute( filterNamesDesc, BaseTypes::STRING_TYPE(), /*required*/true ); attribs << new Attribute( whichFilterDesc, BaseTypes::BOOL_TYPE(), /*required*/ false, QVariant(true) ); } Descriptor desc( FilterAnnotationsWorkerFactory::ACTOR_ID, FilterAnnotationsWorker::tr("Filter annotations by name"), FilterAnnotationsWorker::tr("Filters annotations by name") ); ActorPrototype * proto = new IntegralBusActorPrototype( desc, portDescs, attribs ); proto->setPrompter( new FilterAnnotationsPrompter() ); { QMap delegateMap; delegateMap[FILTER_NAMES_ATTR] = new URLDelegate(DialogUtils::prepareDocumentsFileFilter(true), QString(), true); proto->setEditor(new DelegateEditor(delegateMap)); } WorkflowEnv::getProtoRegistry()->registerProto( BaseActorCategories::CATEGORY_BASIC(), proto ); DomainFactory* localDomain = WorkflowEnv::getDomainRegistry()->getById( LocalDomainFactory::ID ); localDomain->registerEntry( new FilterAnnotationsWorkerFactory() ); } void FilterAnnotationsTask::run() { QStringList names; if(QFileInfo(names_).exists()) { // annotation names are listed in file names = readAnnotationNames(); } else { // annotation names are listed in a string names = names_.split( QRegExp("\\s+"), QString::SkipEmptyParts ); //split by whitespace } QMutableListIterator i(annotations_); while (i.hasNext()) { SharedAnnotationData ad = i.next(); if (accept_) { if (!names.contains(ad->name)) { i.remove(); } } else { if (names.contains(ad->name)) { i.remove(); } } } } QStringList FilterAnnotationsTask::readAnnotationNames() { QStringList res; QFile f(names_); if(!f.open(QFile::ReadOnly)) { return res; } QString data = f.readAll(); return data.split(QRegExp("\\s+"), QString::SkipEmptyParts); } } // U2 namespace } // LocalWorkflow namespace ugene-1.9.8/src/plugins/workflow_designer/src/library/SequencesToMSAWorker.h0000644000175000017500000000464111651544325025724 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_SEQUENCES_TO_MSA_WORKER_H_ #define _U2_SEQUENCES_TO_MSA_WORKER_H_ #include #include #include #include namespace U2 { namespace LocalWorkflow { class SequencesToMSAPromter : public PrompterBase { Q_OBJECT public: SequencesToMSAPromter( Actor * p = 0 ) : PrompterBase(p) {}; protected: QString composeRichDoc(); }; class SequencesToMSAWorker : public BaseWorker { Q_OBJECT public: SequencesToMSAWorker( Actor * p ) : BaseWorker(p), inPort(NULL), outPort(NULL) {}; virtual void init(); virtual bool isReady(); virtual Task* tick(); virtual bool isDone(); virtual void cleanup(); private: IntegralBus* inPort; IntegralBus* outPort; private slots: void sl_onTaskFinished(Task* t); private: QList data; }; class SequencesToMSAWorkerFactory : public DomainFactory { public: const static QString ACTOR_ID; SequencesToMSAWorkerFactory() : DomainFactory(ACTOR_ID) {}; static void init(); virtual Worker* createWorker( Actor * a ) { return new SequencesToMSAWorker(a); } }; class MSAFromSequencesTask : public Task { Q_OBJECT public: MSAFromSequencesTask(const QList& sequences) : Task(tr("MSAFromSequencesTask"), TaskFlag_None), sequences_(sequences), ma(NULL) {} void run(); MAlignment getResult() const { return ma; } private: QList sequences_; MAlignment ma; }; } //LocalWorkflow namespace } //U2 namespace #endif ugene-1.9.8/src/plugins/workflow_designer/src/library/SequenceSplitWorker.h0000644000175000017500000000452011651544325025705 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef __SEQUENCE_SPLIT_WORKER_H__ #define __SEQUENCE_SPLIT_WORKER_H__ #include #include #include #include #include #include namespace U2 { namespace LocalWorkflow { class SequenceSplitPromter : public PrompterBase { Q_OBJECT public: SequenceSplitPromter( Actor * p = 0 ) : PrompterBase(p) {}; protected: QString composeRichDoc(); }; class SequenceSplitWorker : public BaseWorker { Q_OBJECT public: SequenceSplitWorker( Actor * p ) : BaseWorker(p, /*auto transit*/false), seqPort(NULL), outPort(NULL), useAcceptedOrFiltered(false) {}; virtual void init(); virtual bool isReady(); virtual Task * tick(); virtual bool isDone(); virtual void cleanup(); protected: IntegralBus * seqPort; IntegralBus * outPort; private: QList ssTasks; QList inputAnns; QStringList acceptedNames; QStringList filteredNames; bool useAcceptedOrFiltered; ExtractAnnotatedRegionTaskSettings cfg; private slots: void sl_onTaskFinished( Task * t ); }; class SequenceSplitWorkerFactory : public DomainFactory { public: const static QString ACTOR; SequenceSplitWorkerFactory() : DomainFactory( ACTOR ) {}; static void init(); virtual Worker * createWorker( Actor * a ); }; } //ns LocalWorkflow } //ns U2 #endif ugene-1.9.8/src/plugins/workflow_designer/src/library/MSA2SequenceWorker.cpp0000644000175000017500000001222211651544325025645 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "MSA2SequenceWorker.h" #include #include #include #include #include #include #include #include #include #include #include #include namespace U2 { namespace LocalWorkflow { const QString Alignment2SequenceWorkerFactory::ACTOR_ID("convert-alignment-to-sequence"); static const Descriptor ALN_2_SEQUENCE_IN_TYPE_ID("alignment-2-sequence-in-type"); static const Descriptor ALN_2_SEQUENCE_OUT_TYPE_ID("alignment-2-sequence-out-type"); /******************************* * Alignment2SequenceWorker *******************************/ void Alignment2SequenceWorker::init() { input = ports.value(BasePorts::IN_MSA_PORT_ID()); output = ports.value(BasePorts::OUT_SEQ_PORT_ID()); } bool Alignment2SequenceWorker::isReady() { return input->hasMessage(); } Task * Alignment2SequenceWorker::tick() { Message inputMessage = getMessageAndSetupScriptValues(input); MAlignment ma = inputMessage.getData().toMap().value(BaseSlots::MULTIPLE_ALIGNMENT_SLOT().getId()).value(); if(ma.isEmpty()) { return new FailTask(tr("empty input alignment")); } QList seqs = MSAUtils::ma2seq(ma,true); foreach(const DNASequence &seq, seqs) { QVariantMap msgData; msgData[BaseSlots::DNA_SEQUENCE_SLOT().getId()] = qVariantFromValue(seq); output->put(Message(BaseTypes::DNA_SEQUENCE_TYPE(), msgData)); } if(!input->hasMessage()) { output->setEnded(); } return NULL; } bool Alignment2SequenceWorker::isDone() { return input->isEnded(); } void Alignment2SequenceWorker::cleanup() { } /******************************* * Alignment2SequenceWorkerFactory *******************************/ void Alignment2SequenceWorkerFactory::init() { // ports description QList portDescs; { QMap inM; inM[BaseSlots::MULTIPLE_ALIGNMENT_SLOT()] = BaseTypes::MULTIPLE_ALIGNMENT_TYPE(); DataTypePtr inSet(new MapDataType(ALN_2_SEQUENCE_IN_TYPE_ID, inM)); Descriptor inPortDesc(BasePorts::IN_MSA_PORT_ID(), Alignment2SequenceWorker::tr("Input alignment"), Alignment2SequenceWorker::tr("A alignment which will be split into sequences")); portDescs << new PortDescriptor(inPortDesc, inSet, true); QMap outM; outM[BaseSlots::DNA_SEQUENCE_SLOT()] = BaseTypes::DNA_SEQUENCE_TYPE(); DataTypePtr outSet(new MapDataType(ALN_2_SEQUENCE_OUT_TYPE_ID, outM)); Descriptor outPortDesc(BasePorts::OUT_SEQ_PORT_ID(), Alignment2SequenceWorker::tr("Output sequences"), Alignment2SequenceWorker::tr("Converted sequences")); portDescs << new PortDescriptor(outPortDesc, outSet, false); } QList attrs; Descriptor protoDesc(Alignment2SequenceWorkerFactory::ACTOR_ID, Alignment2SequenceWorker::tr("Split alignment into sequences"), Alignment2SequenceWorker::tr("Splits input alignment into sequences")); ActorPrototype * proto = new IntegralBusActorPrototype(protoDesc, portDescs, attrs); proto->setPrompter(new Alignment2SequencePrompter()); WorkflowEnv::getProtoRegistry()->registerProto(BaseActorCategories::CATEGORY_ALIGNMENT(), proto); WorkflowEnv::getDomainRegistry()->getById( LocalDomainFactory::ID )->registerEntry( new Alignment2SequenceWorkerFactory() ); } Worker * Alignment2SequenceWorkerFactory::createWorker(Actor* a) { return new Alignment2SequenceWorker(a); } /******************************* * Alignment2SequencePrompter *******************************/ QString Alignment2SequencePrompter::composeRichDoc() { QString unsetStr = ""+tr("unset")+""; IntegralBusPort* input = qobject_cast(target->getPort(BasePorts::IN_MSA_PORT_ID())); Actor* producer = input->getProducer(BaseSlots::MULTIPLE_ALIGNMENT_SLOT().getId()); QString source = tr(" from %1").arg(producer ? producer->getLabel() : unsetStr); return tr("Split alignment%1 into sequences").arg(source); } } // LocalWorkflow } // U2 ugene-1.9.8/src/plugins/workflow_designer/src/library/CoreLib.h0000644000175000017500000000227111651544325023247 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_WORKFLOW_CORE_LIB_LIB_H_ #define _U2_WORKFLOW_CORE_LIB_LIB_H_ #include namespace U2 { namespace Workflow { class CoreLib : public QObject { Q_OBJECT public: static void init(); static void initUsersWorkers(); static void initExternalToolsWorkers(); }; } // Workflow namespace } // U2 namespace #endif ugene-1.9.8/src/plugins/workflow_designer/src/library/Text2SequenceWorker.h0000644000175000017500000000421711651544325025623 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef __TEXT_2_SEQUENCE_WORKER_H_ #define __TEXT_2_SEQUENCE_WORKER_H_ #include #include namespace U2 { namespace LocalWorkflow { class Text2SequencePrompter : public PrompterBase { Q_OBJECT public: Text2SequencePrompter(Actor * p = NULL) : PrompterBase(p) {} protected: QString composeRichDoc(); }; // Text2SequencePrompter class Text2SequenceWorker : public BaseWorker { Q_OBJECT public: static QMap cuteAlIdNames; public: Text2SequenceWorker(Actor * p) : BaseWorker(p), txtPort(NULL), outSeqPort(NULL), tickedNum(0) {} virtual void init(); virtual bool isReady(); virtual Task * tick(); virtual bool isDone(); virtual void cleanup(); private: static QMap initCuteAlNames(); private: IntegralBus * txtPort; IntegralBus * outSeqPort; int tickedNum; }; // Text2SequenceWorker class Text2SequenceWorkerFactory : public DomainFactory { public: static const QString ACTOR_ID; Text2SequenceWorkerFactory() : DomainFactory(ACTOR_ID) {} static void init(); virtual Worker * createWorker(Actor* a); }; // Text2SequenceWorkerFactory } // LocalWorkflow } // U2 #endif // __TEXT_2_SEQUENCE_WORKER_H_ ugene-1.9.8/src/plugins/workflow_designer/src/library/DocWorkers.cpp0000644000175000017500000003673111651544325024355 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "DocWorkers.h" #include "CoreLib.h" #include "GenericReadWorker.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include namespace U2 { namespace LocalWorkflow { static int ct = 0; /************************************* * TextReader *************************************/ void TextReader::init() { urls = WorkflowUtils::expandToUrls(actor->getParameter(BaseAttributes::URL_IN_ATTRIBUTE().getId())->getAttributeValue()); assert(ports.size() == 1); ch = ports.values().first(); } bool TextReader::isDone() { return done; } bool TextReader::isReady() { return !isDone(); } Task *TextReader::tick() { if(io && io->isOpen()) { QByteArray buf; buf.resize(1024); buf.fill(0); int read = io->readLine(buf.data(), 1024); buf.resize(read); QVariantMap m; m[BaseSlots::TEXT_SLOT().getId()] = QString(buf); m[BaseSlots::URL_SLOT().getId()] = url; ch->put( Message(mtype, m)); if(io->isEof()) { io->close(); } } else { url = urls.takeFirst(); IOAdapterFactory *iof = AppContext::getIOAdapterRegistry()->getIOAdapterFactoryById(BaseIOAdapters::url2io(url)); io = iof->createIOAdapter(); if(!io->open(url,IOAdapterMode_Read)) { return new FailTask(tr("Can't load file %1").arg(url)); } if(actor->getParameter(BaseAttributes::READ_BY_LINES_ATTRIBUTE().getId())->getAttributeValue() == false) { QByteArray buf; int read = 0; int offs = 0; static const int READ_BLOCK_SZ = 1024; buf.resize(READ_BLOCK_SZ); buf.fill(0); do { read = io->readBlock( buf.data() + offs, READ_BLOCK_SZ ); if( read != READ_BLOCK_SZ ) { assert(read < READ_BLOCK_SZ); buf.resize(buf.size() - READ_BLOCK_SZ + read); break; } offs += read; buf.resize( offs + READ_BLOCK_SZ ); } while(read == READ_BLOCK_SZ); QVariantMap m; m[BaseSlots::TEXT_SLOT().getId()] = QString(buf); m[BaseSlots::URL_SLOT().getId()] = url; ch->put( Message(mtype, m)); io->close(); } else { QByteArray buf; buf.resize(1024); buf.fill(0); int read = io->readLine(buf.data(), 1024); buf.resize(read); QVariantMap m; QString str(buf); m[BaseSlots::TEXT_SLOT().getId()] = QString(buf); m[BaseSlots::URL_SLOT().getId()] = url; ch->put( Message(mtype, m)); if(io->isEof()) { io->close(); } } } if(urls.isEmpty() && (!io || !io->isOpen())) { ch->setEnded(); done = true; } return NULL; } void TextReader::doc2data(Document* doc) { algoLog.info(tr("Reading text from %1").arg(doc->getURLString())); foreach(GObject* go, GObjectUtils::select(doc->getObjects(), GObjectTypes::TEXT, UOF_LoadedOnly)) { TextObject* txtObject = qobject_cast(go); assert(txtObject); QVariantMap m; m[BaseSlots::TEXT_SLOT().getId()] = txtObject->getText(); m[BaseSlots::URL_SLOT().getId()] = doc->getURLString(); cache << Message(mtype, m); } } /************************************* * TextWriter *************************************/ void TextWriter::data2doc(Document* doc, const QVariantMap& data) { QStringList list = data.value(BaseSlots::TEXT_SLOT().getId()).toStringList(); QString text = list.join("\n"); TextObject* to = qobject_cast(GObjectUtils::selectOne(doc->getObjects(), GObjectTypes::TEXT, UOF_LoadedOnly)); if (!to) { to = new TextObject(text, QString("Text %1").arg(++ct)); doc->addObject(to); } else { to->setText(to->getText() + "\n" + text); } } /************************************* * FastaWriter *************************************/ void FastaWriter::data2doc(Document* doc, const QVariantMap& data) { data2document(doc, data); } void FastaWriter::data2document(Document* doc, const QVariantMap& data) { DNASequence seq = qVariantValue(data.value(BaseSlots::DNA_SEQUENCE_SLOT().getId())); QString sequenceName = data.value(BaseSlots::FASTA_HEADER_SLOT().getId()).toString(); if (sequenceName.isEmpty()) { sequenceName = seq.getName(); } else { seq.info.insert(DNAInfo::FASTA_HDR, sequenceName); } if (sequenceName.isEmpty()) { sequenceName = QString("unknown sequence %1").arg(doc->getObjects().size()); } if (seq.alphabet && seq.length() != 0 && !doc->findGObjectByName(sequenceName)) { algoLog.trace(QString("Adding seq [%1] to FASTA doc %2").arg(sequenceName).arg(doc->getURLString())); doc->addObject(new DNASequenceObject(sequenceName, seq)); } } /************************************* * FastQWriter *************************************/ void FastQWriter::data2doc(Document* doc, const QVariantMap& data) { data2document(doc, data); } void FastQWriter::data2document(Document* doc, const QVariantMap& data) { DNASequence seq = qVariantValue(data.value(BaseSlots::DNA_SEQUENCE_SLOT().getId())); QString sequenceName = seq.getName(); if (sequenceName.isEmpty()) { sequenceName = QString("unknown sequence %1").arg(doc->getObjects().size()); } if (seq.alphabet && seq.length() != 0 && !doc->findGObjectByName(sequenceName)) { algoLog.trace(QString("Adding seq [%1] to FASTQ doc %2").arg(sequenceName).arg(doc->getURLString())); doc->addObject(new DNASequenceObject(sequenceName, seq)); algoLog.info( QString("Sequence %1 added to document").arg(sequenceName) ); } } /************************************* * RawSeqWriter *************************************/ void RawSeqWriter::data2doc(Document* doc, const QVariantMap& data) { data2document(doc, data); } // same as FastQWriter::data2document void RawSeqWriter::data2document(Document* doc, const QVariantMap& data) { DNASequence seq = qVariantValue(data.value(BaseSlots::DNA_SEQUENCE_SLOT().getId())); QString sequenceName = seq.getName(); if (sequenceName.isEmpty()) { sequenceName = QString("unknown sequence %1").arg(doc->getObjects().size()); } if (seq.alphabet && seq.length() != 0 && !doc->findGObjectByName(sequenceName)) { algoLog.trace(QString("Adding seq [%1] to Raw sequence document %2").arg(sequenceName).arg(doc->getURLString())); if(doc->getDocumentFormat()->isObjectOpSupported(doc, DocumentFormat::DocObjectOp_Add, GObjectTypes::SEQUENCE)) { doc->addObject(new DNASequenceObject(sequenceName, seq)); algoLog.info( QString("Sequence %1 added to document").arg(sequenceName) ); } else { algoLog.error( QString("Cannot add sequence %1 to document" ).arg(sequenceName) ); } } } /************************************* * GenbankWriter *************************************/ void GenbankWriter::data2doc(Document* doc, const QVariantMap& data) { data2document(doc, data); } void GenbankWriter::data2document(Document* doc, const QVariantMap& data) { DNASequence seq = qVariantValue(data.value(BaseSlots::DNA_SEQUENCE_SLOT().getId())); /*QStringList order; order << DNAInfo::DEFINITION << DNAInfo::ACCESSION << DNAInfo::VERSION; order << DNAInfo::PROJECT << DNAInfo::KEYWORDS << DNAInfo::SEGMENT; foreach(const QString& key, order) { if (seq.info.contains(key)) { QVariant v = seq.info.take(key); if (!(v.canConvert(QVariant::String)||v.canConvert(QVariant::StringList))) { seq.info.remove(key); } } }*/ QMapIterator it(seq.info); while (it.hasNext()) { it.next(); if ( !(it.value().type() == QVariant::String || it.value().type() == QVariant::StringList) ) { seq.info.remove(it.key()); } } QString sequenceName = seq.getName(); //data.value(CoreLib::GENBANK_ACN_SLOT_ID).toString(); QString annotationName; if (sequenceName.isEmpty()) { int num = doc->findGObjectByType(GObjectTypes::SEQUENCE).size(); sequenceName = QString("unknown sequence %1").arg(num); int featuresNum = doc->findGObjectByType(GObjectTypes::ANNOTATION_TABLE).size(); annotationName = QString("unknown features %1").arg(featuresNum); } else { annotationName = sequenceName + " features"; } QList atl = QVariantUtils::var2ftl(data.value(BaseSlots::ANNOTATION_TABLE_SLOT().getId()).toList()); DNASequenceObject* dna = qobject_cast(doc->findGObjectByName(sequenceName)); if (!dna && !seq.isNull()) { doc->addObject(dna = new DNASequenceObject(sequenceName, seq)); algoLog.trace(QString("Adding seq [%1] to GB doc %2").arg(sequenceName).arg(doc->getURLString())); } if (!atl.isEmpty()) { AnnotationTableObject* att = NULL; if (dna) { QList relAnns = GObjectUtils::findObjectsRelatedToObjectByRole(dna, GObjectTypes::ANNOTATION_TABLE, GObjectRelationRole::SEQUENCE, doc->getObjects(), UOF_LoadedOnly); att = relAnns.isEmpty() ? NULL : qobject_cast(relAnns.first()); } if (!att) { doc->addObject(att = new AnnotationTableObject(annotationName)); if (dna) { att->addObjectRelation(dna, GObjectRelationRole::SEQUENCE); } algoLog.trace(QString("Adding features [%1] to GB doc %2").arg(annotationName).arg(doc->getURLString())); } foreach(SharedAnnotationData sad, atl) { att->addAnnotation(new Annotation(sad), QString()); } } } /************************************* * SeqWriter *************************************/ void SeqWriter::data2doc(Document* doc, const QVariantMap& data){ if( format == NULL ) { return; } DocumentFormatId fid = format->getFormatId(); if( fid == BaseDocumentFormats::PLAIN_FASTA ) { FastaWriter::data2document( doc, data ); } else if( fid == BaseDocumentFormats::PLAIN_GENBANK ) { GenbankWriter::data2document( doc, data ); } else if ( fid == BaseDocumentFormats::FASTQ) { FastQWriter::data2document( doc, data ); } else if( fid == BaseDocumentFormats::RAW_DNA_SEQUENCE ) { RawSeqWriter::data2document( doc, data ); } else { assert(0); ioLog.error(QString("Unknown data format for writing: %1").arg(fid)); } } /************************************* * MSAWriter *************************************/ void MSAWriter::data2doc(Document* doc, const QVariantMap& data) { MAlignment ma = data.value(BaseSlots::MULTIPLE_ALIGNMENT_SLOT().getId()).value(); if (ma.isEmpty()) { algoLog.error(tr("Empty alignment passed for writing to %1").arg(doc->getURLString())); return; //FIXME } if (ma.getName().isEmpty()) { ma.setName( QString(MA_OBJECT_NAME + "_%1").arg(ct++) ); } doc->addObject(new MAlignmentObject(ma)); } /************************************* * DataWorkerFactory *************************************/ Worker* DataWorkerFactory::createWorker(Actor* a) { // TODO: wtf is this?? // each actor must have own factory BaseWorker* w = NULL; QString protoId = a->getProto()->getId(); if (CoreLibConstants::READ_TEXT_PROTO_ID == protoId ) { TextReader* t = new TextReader(a); w = t; } else if (CoreLibConstants::WRITE_TEXT_PROTO_ID == protoId) { w = new TextWriter(a); } else if (CoreLibConstants::WRITE_FASTA_PROTO_ID == protoId) { w = new FastaWriter(a); } else if (CoreLibConstants::WRITE_GENBANK_PROTO_ID == protoId) { w = new GenbankWriter(a); } else if (CoreLibConstants::WRITE_CLUSTAL_PROTO_ID == protoId) { w = new MSAWriter(a, BaseDocumentFormats::CLUSTAL_ALN); } else if (CoreLibConstants::WRITE_STOCKHOLM_PROTO_ID == protoId) { w = new MSAWriter(a, BaseDocumentFormats::STOCKHOLM); } else if (CoreLibConstants::GENERIC_READ_MA_PROTO_ID == protoId) { w = new GenericMSAReader(a); } else if (CoreLibConstants::GENERIC_READ_SEQ_PROTO_ID == protoId) { w = new GenericSeqReader(a); } else if(CoreLibConstants::WRITE_MSA_PROTO_ID == protoId ) { w = new MSAWriter(a); } else if(CoreLibConstants::WRITE_SEQ_PROTO_ID == protoId ) { w = new SeqWriter(a); } else if (CoreLibConstants::WRITE_FASTQ_PROTO_ID == protoId ) { w = new FastQWriter(a); } else { assert(0); } return w; } void DataWorkerFactory::init() { DomainFactory* localDomain = WorkflowEnv::getDomainRegistry()->getById(LocalDomainFactory::ID); localDomain->registerEntry(new DataWorkerFactory(CoreLibConstants::WRITE_FASTA_PROTO_ID)); localDomain->registerEntry(new DataWorkerFactory(CoreLibConstants::WRITE_GENBANK_PROTO_ID)); localDomain->registerEntry(new DataWorkerFactory(CoreLibConstants::READ_TEXT_PROTO_ID)); localDomain->registerEntry(new DataWorkerFactory(CoreLibConstants::WRITE_TEXT_PROTO_ID)); localDomain->registerEntry(new DataWorkerFactory(CoreLibConstants::GENERIC_READ_SEQ_PROTO_ID)); localDomain->registerEntry(new DataWorkerFactory(CoreLibConstants::GENERIC_READ_MA_PROTO_ID)); localDomain->registerEntry(new DataWorkerFactory(CoreLibConstants::WRITE_CLUSTAL_PROTO_ID)); localDomain->registerEntry(new DataWorkerFactory(CoreLibConstants::WRITE_STOCKHOLM_PROTO_ID)); localDomain->registerEntry(new DataWorkerFactory(CoreLibConstants::WRITE_MSA_PROTO_ID)); localDomain->registerEntry(new DataWorkerFactory(CoreLibConstants::WRITE_SEQ_PROTO_ID)); localDomain->registerEntry(new DataWorkerFactory(CoreLibConstants::WRITE_FASTQ_PROTO_ID)); } } // Workflow namespace } // U2 namespace ugene-1.9.8/src/plugins/workflow_designer/src/cmdline/0000755000175000017500000000000011651544325021524 5ustar ilyailyaugene-1.9.8/src/plugins/workflow_designer/src/cmdline/WorkflowCMDLineTasks.cpp0000644000175000017500000001770511651544325026216 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include #include #include #include #include #include #include #include #include #include #include #include #include #include "WorkflowDesignerPlugin.h" #include "WorkflowCMDLineTasks.h" #define WORKFLOW_CMDLINE_TASK_LOG_CAT "Workflow cmdline tasks" namespace U2 { /******************************************* * WorkflowRunFromCMDLineBase *******************************************/ WorkflowRunFromCMDLineBase::WorkflowRunFromCMDLineBase() : Task( tr( "Workflow run from cmdline" ), TaskFlag_NoRun ), schema(NULL), optionsStartAt(-1), loadTask(NULL) { GCOUNTER(cvar,tvar,"workflow_run_from_cmdline"); CMDLineRegistry * cmdLineRegistry = AppContext::getCMDLineRegistry(); // try to process schema without 'task' option (it can only be the first one) QStringList pureValues = CMDLineRegistryUtils::getPureValues(); if( !pureValues.isEmpty() ) { QString schemaName = pureValues.first(); processLoadSchemaTask( schemaName, 1 ); // because after program name } if( loadTask != NULL ) { addSubTask( loadTask ); return; } // process schema with 'task' option int taskOptionIdx = CMDLineRegistryUtils::getParameterIndex( WorkflowDesignerPlugin::RUN_WORKFLOW ); if(taskOptionIdx != -1) { processLoadSchemaTask( cmdLineRegistry->getParameterValue( WorkflowDesignerPlugin::RUN_WORKFLOW, taskOptionIdx ), taskOptionIdx ); } if( loadTask == NULL ) { setError( tr( "no task to run" ) ); return; } addSubTask( loadTask ); } void WorkflowRunFromCMDLineBase::processLoadSchemaTask( const QString & schemaNameCandidate, int optionIdx ) { loadTask = prepareLoadSchemaTask( schemaNameCandidate ); if( loadTask != NULL ) { schemaName = schemaNameCandidate; optionsStartAt = optionIdx + 1; } } LoadWorkflowTask * WorkflowRunFromCMDLineBase::prepareLoadSchemaTask( const QString & schemaName ) { QString pathToSchema = WorkflowUtils::findPathToSchemaFile( schemaName ); if( pathToSchema.isEmpty() ) { coreLog.error( tr( "Cannot find schema: %1" ).arg( schemaName ) ); return NULL; } schema = new Schema(); schema->setDeepCopyFlag(true); return new LoadWorkflowTask( schema, NULL, pathToSchema ); } WorkflowRunFromCMDLineBase::~WorkflowRunFromCMDLineBase() { delete schema; } static void setSchemaCMDLineOptions( Schema * schema, int optionsStartAtIdx ) { assert( schema != NULL && optionsStartAtIdx > 0 ); QList parameters = AppContext::getCMDLineRegistry()->getParameters(); int sz = parameters.size(); for( int i = optionsStartAtIdx; i < sz; ++i ) { const StringPair & param = parameters.at(i); if( param.first.isEmpty() ) { // TODO: unnamed parameters not supported yet continue; } QString paramAlias = param.first; QString paramName; Actor * actor = WorkflowUtils::findActorByParamAlias( schema->getProcesses(), paramAlias, paramName ); if( actor == NULL ) { assert( paramName.isEmpty() ); coreLog.info( WorkflowRunFromCMDLineBase::tr( "alias '%1' not set in schema" ).arg( paramAlias ) ); continue; } Attribute * attr = actor->getParameter( paramName ); if( attr == NULL ) { coreLog.error( WorkflowRunFromCMDLineBase::tr( "actor parameter '%1' not found" ).arg( paramName ) ); continue; } DataTypeValueFactory * valueFactory = WorkflowEnv::getDataTypeValueFactoryRegistry()-> getById( attr->getAttributeType()->getId() ); if( valueFactory == NULL ) { coreLog.error( WorkflowRunFromCMDLineBase::tr( "cannot parse value from '%1'" ).arg( param.second ) ); continue; } ActorId id = actor->getId(); bool isOk; QVariant value = valueFactory->getValueFromString( param.second, &isOk ); if(!isOk){ coreLog.error( WorkflowRunFromCMDLineBase::tr( "Incorrect value for '%1', null or default value passed to schema" ). arg( param.first )); continue; } QList & iterations = schema->getIterations(); QList::iterator it = iterations.begin(); while( it != iterations.end() ) { // TODO: make different values for different iterations it->cfg[id].insert( paramName, value ); ++it; } } } QList WorkflowRunFromCMDLineBase::onSubTaskFinished( Task* subTask ) { assert( subTask != NULL ); QList res; propagateSubtaskError(); if( hasError() || isCanceled() ) { return res; } assert( !hasError() ); // if error, we won't be here if( loadTask == subTask ) { Schema * schema = loadTask->getSchema(); assert( schema != NULL ); remapping = loadTask->getRemapping(); setSchemaCMDLineOptions( schema, optionsStartAt ); if( schema->getDomain().isEmpty() ) { QList domainsId = WorkflowEnv::getDomainRegistry()->getAllIds(); assert(!domainsId.isEmpty()); if(!domainsId.isEmpty()) { schema->setDomain(domainsId.first()); } } QStringList l; bool good = WorkflowUtils::validate(*schema, l); if(!good) { QString schemaHelpStr = QString("\n\nsee 'ugene --help=%1' for details").arg(schemaName); setError("\n\n" + l.join("\n\n") + schemaHelpStr); return res; } res << getWorkflowRunTask(); } return res; } /******************************************* * WorkflowRunFromCMDLineTask *******************************************/ Task * WorkflowRunFromCMDLineTask::getWorkflowRunTask() const { return new WorkflowRunTask(*schema, schema->getIterations(), remapping); } /******************************************* * WorkflowRemoteRunFromCMDLineTask *******************************************/ WorkflowRemoteRunFromCMDLineTask::WorkflowRemoteRunFromCMDLineTask() { } Task * WorkflowRemoteRunFromCMDLineTask::getWorkflowRunTask() const { assert(settings != NULL); return new RemoteWorkflowRunTask( settings, *schema, schema->getIterations()); } void WorkflowRemoteRunFromCMDLineTask::prepare() { CMDLineRegistry * cmdlineReg = AppContext::getCMDLineRegistry(); assert(cmdlineReg != NULL); QString filePath = cmdlineReg->getParameterValue(WorkflowDesignerPlugin::REMOTE_MACHINE); if( filePath.isEmpty() ) { stateInfo.setError(tr("%1 parameter expected, but not set").arg(WorkflowDesignerPlugin::REMOTE_MACHINE)); return; } if( !SerializeUtils::deserializeRemoteMachineSettingsFromFile(filePath, &settings) ) { //assert(settings == NULL); stateInfo.setError(tr("Cannot read remote machine settings from %2").arg(filePath)); return; } assert(settings != NULL); } } // U2 ugene-1.9.8/src/plugins/workflow_designer/src/cmdline/WorkflowCMDLineTasks.h0000644000175000017500000000430611651544325025654 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_WORKFLOW_CMDLINE_TASKS_H_ #define _U2_WORKFLOW_CMDLINE_TASKS_H_ #include #include #include namespace U2 { class WorkflowRunFromCMDLineBase : public Task { Q_OBJECT public: WorkflowRunFromCMDLineBase(); virtual ~WorkflowRunFromCMDLineBase(); QList onSubTaskFinished( Task* subTask ); protected: virtual Task * getWorkflowRunTask() const = 0; private: LoadWorkflowTask * prepareLoadSchemaTask( const QString & schemaName ); void processLoadSchemaTask( const QString & schemaName, int optionIdx ); protected: Schema* schema; int optionsStartAt; LoadWorkflowTask * loadTask; QString schemaName; QMap remapping; }; // WorkflowRunFromCMDLineBase class WorkflowRunFromCMDLineTask : public WorkflowRunFromCMDLineBase { Q_OBJECT public: virtual Task * getWorkflowRunTask() const; }; // WorkflowRunFromCMDLineTask class WorkflowRemoteRunFromCMDLineTask : public WorkflowRunFromCMDLineBase { Q_OBJECT public: WorkflowRemoteRunFromCMDLineTask(); virtual void prepare(); virtual Task * getWorkflowRunTask() const; private: RemoteMachineSettings * settings; }; // WorkflowRemoteRunFromCMDLineTask } // U2 #endif // _U2_WORKFLOW_CMDLINE_TASKS_H_ ugene-1.9.8/src/plugins/workflow_designer/src/WorkflowMetaDialog.cpp0000644000175000017500000000565711651544324024372 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "WorkflowMetaDialog.h" #include #include #include #include #include namespace U2 { WorkflowMetaDialog::WorkflowMetaDialog(QWidget * p, const Metadata& meta): QDialog(p), meta(meta) { setupUi(this); connect(browseButton, SIGNAL(clicked()), SLOT(sl_onBrowse())); connect(cancelButton, SIGNAL(clicked()), SLOT(reject())); connect(okButton, SIGNAL(clicked()), SLOT(sl_onSave())); connect(urlEdit, SIGNAL(textChanged(const QString & )), SLOT(sl_onURLChanged(const QString& ))); connect(urlEdit, SIGNAL(textEdited (const QString & )), SLOT(sl_onURLChanged(const QString& ))); urlEdit->setText(meta.url); okButton->setDisabled(meta.url.isEmpty()); nameEdit->setText(meta.name); commentEdit->setText(meta.comment); } void WorkflowMetaDialog::sl_onSave() { assert(!WorkflowUtils::WD_FILE_EXTENSIONS.isEmpty()); QString url = urlEdit->text(); bool endsWithWDExt = false; foreach( const QString & ext, WorkflowUtils::WD_FILE_EXTENSIONS ) { assert(!ext.isEmpty()); if(url.endsWith(ext)) { endsWithWDExt = true; } } if(!endsWithWDExt) { url.append("." + WorkflowUtils::WD_FILE_EXTENSIONS.first()); } meta.url = url; meta.comment = commentEdit->toPlainText(); meta.name = nameEdit->text(); accept(); } void WorkflowMetaDialog::sl_onURLChanged(const QString & text) { okButton->setDisabled(text.isEmpty()); } #define LAST_DIR QString("workflowview/lastdir") void WorkflowMetaDialog::sl_onBrowse() { QString url = urlEdit->text(); if (url.isEmpty()) { url = AppContext::getSettings()->getValue(LAST_DIR, QString("")).toString(); } QString filter = DesignerUtils::getSchemaFileFilter(false); url = QFileDialog::getSaveFileName(0, tr("Save workflow schema to file"), url, filter); if (!url.isEmpty()) { AppContext::getSettings()->setValue(LAST_DIR, QFileInfo(url).absoluteDir().absolutePath()); urlEdit->setText(url); } } }//namespace ugene-1.9.8/src/plugins/workflow_designer/src/ui/0000755000175000017500000000000011651544325020526 5ustar ilyailyaugene-1.9.8/src/plugins/workflow_designer/src/ui/WorkflowMetaDialog.ui0000644000175000017500000000372711651544325024637 0ustar ilyailya WorkflowMetaDialog 0 0 444 227 Workflow properties Location ... Name Comment true OK true Cancel false ugene-1.9.8/src/plugins/workflow_designer/src/ui/ExternalProcessWorkerDialog.ui0000644000175000017500000002740711651544325026532 0ustar ilyailya CreateExternalProcessWorkerDialog 0 0 587 415 Create Element with Command Line Tool QWizard::ClassicStyle QWizard::HelpButtonOnRight QFrame::StyledPanel true <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> <html><head><meta name="qrichtext" content="1" /><style type="text/css"> p, li { white-space: pre-wrap; } </style></head><body style=" font-family:'MS Shell Dlg 2'; font-size:8.25pt; font-weight:400; font-style:normal;"> <p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-size:8pt;">Name and description for new workflow element.</span></p></body></html> Element description Qt::Horizontal Name Description true <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> <html><head><meta name="qrichtext" content="1" /><style type="text/css"> p, li { white-space: pre-wrap; } </style></head><body style=" font-family:'MS Shell Dlg 2'; font-size:8.25pt; font-weight:400; font-style:normal;"> <p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-size:8pt;">Input and output data for external tool. Name is a command line parameter for input/output data in external tool. Set data type and format in which external tool reads/writes input/output data. You also can set description for workflow designer. Each input data will be represented as port in workflow designer. Each output data will be represented as slot of single slot.</span></p></body></html> Input data Qt::Horizontal Qt::Horizontal 188 20 Add input Delete Output data Qt::Horizontal Qt::Horizontal 188 20 Add output Delete true <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> <html><head><meta name="qrichtext" content="1" /><style type="text/css"> p, li { white-space: pre-wrap; } </style></head><body style=" font-family:'MS Shell Dlg 2'; font-size:8.25pt; font-weight:400; font-style:normal;"> <p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-size:8pt;">Another parameters for external tool. You must set name for parameter and its type. You also can set description for workflow designer. Each parameter will be represented as parameter of workflow element.</span></p></body></html> Parameters Qt::Horizontal Qt::Horizontal 188 20 Add attribute Delete Qt::Vertical 20 76 true <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> <html><head><meta name="qrichtext" content="1" /><style type="text/css"> p, li { white-space: pre-wrap; } </style></head><body style=" font-family:'MS Shell Dlg 2'; font-size:8.25pt; font-weight:400; font-style:normal;"> <p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-size:8pt;">Execution string and element's description. To substitute input, output data or parameter, use it's name with prefix $ in execution string. You can set parameterized description for new element(description that appears not in property editor but on element itself). In parameterized description you also can use parameters substitution with prefix $.</span></p></body></html> Command line template Qt::Horizontal Execution string Parameterized description ugene-1.9.8/src/plugins/workflow_designer/src/ui/WorkflowEditorWidget.ui0000644000175000017500000002753411651544325025225 0ustar ilyailya WorkflowEditorWidget 0 0 312 560 Form QGroupBox::indicator:unchecked { image: url(:workflow_designer/images/toggle_expand.png); } QGroupBox::indicator:unchecked:hover { image: url(:workflow_designer/images/toggle_expand.png); } QGroupBox::indicator:unchecked:pressed { image: url(:workflow_designer/images/toggle_expand.png); } QGroupBox::indicator:checked { image: url(:workflow_designer/images/toggle.png); } QGroupBox::indicator:checked:hover { image: url(:workflow_designer/images/toggle.png); } QGroupBox::indicator:checked:pressed { image: url(:workflow_designer/images/toggle.png); } QGroupBox::indicator:disabled { image: url(:/images/checkbox_indeterminate_hover.png); } 1 1 1 3 1 Property Editor 3 3 QLayout::SetFixedSize 0 0 TextLabel Qt::AlignHCenter|Qt::AlignTop true Qt::LinksAccessibleByMouse|Qt::TextSelectableByMouse 0 0 true 0 0 0 0 Qt::Vertical false true 0 1 0 70 false true Qt::TextBrowserInteraction 0 1 Iterations true true true 0 0 1 0 0 0 4 Parameters true true 0 0 1 0 0 Qt::Vertical 2 false 0 4 0 100 QAbstractItemView::CurrentChanged|QAbstractItemView::DoubleClicked|QAbstractItemView::EditKeyPressed|QAbstractItemView::SelectedClicked true QAbstractItemView::SingleSelection QAbstractItemView::SelectRows Qt::ElideMiddle false false false 0 2 Input data true true true 0 0 0 2 0 2 Output data true true true 0 0 0 0 0 1 true Qt::TextBrowserInteraction ugene-1.9.8/src/plugins/workflow_designer/src/ui/CreateScriptBlockDialog.ui0000644000175000017500000001464211651544325025557 0ustar ilyailya CreateScriptBlockDialog 0 0 501 481 Create Element with Script Name ScriptBlock Description <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> <html><head><meta name="qrichtext" content="1" /><style type="text/css"> p, li { white-space: pre-wrap; } </style></head><body style=" font-family:'MS Shell Dlg 2'; font-size:8.25pt; font-weight:400; font-style:normal;"> <p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-size:8pt;">Evaluates user's script</span></p></body></html> Input Port Add input slot Delete input slot Output Port Add output slot Delete output slot Attributes Add Attribute Delete Attribute Qt::Horizontal 40 20 Error false false 1 Error occured while saving new actor. Can't write to current directory. Choose another directory for store user's elements false true ... Qt::Horizontal 40 20 OK Cancel ugene-1.9.8/src/plugins/workflow_designer/src/ui/ChooseItemDialog.ui0000644000175000017500000000415211651544325024246 0ustar ilyailya ChooseItemDialog 0 0 290 352 Choose task type Add a task of the following type: Qt::Horizontal 40 20 OK Cancel okButotn clicked() ChooseItemDialog accept() 157 329 144 175 cancelButton clicked() ChooseItemDialog reject() 240 329 144 175 ugene-1.9.8/src/plugins/workflow_designer/src/ui/WorkflowSettingsWidget.ui0000644000175000017500000001146411651544325025572 0ustar ilyailya WorkflowSettingsWidget 0 0 487 465 Resource settings Scene appearance Show grid Snap to grid Element style Element font Element background color 0 0 Runtime settings Track running progress Directories Directory for custom elements with scripts ... Directory for custom elements with command line tools ... Run tasks in separate process Qt::Vertical 20 178 ugene-1.9.8/src/plugins/workflow_designer/src/ui/SchemaAliasesConfigurationDialog.ui0000644000175000017500000000627411651544325027450 0ustar ilyailya SchemaAliasesConfigurationDialog Qt::NonModal 0 0 618 265 Configure command line aliases true 0 0 Workflow elements 0 0 Qt::Horizontal Qt::Horizontal 0 0 Schema parameter Command line alias Help message Qt::Horizontal 40 20 Ok Cancel ugene-1.9.8/src/plugins/workflow_designer/src/ui/SchemaConfigurationDialog.ui0000644000175000017500000001552611651544325026146 0ustar ilyailya SchemaConfigurationDialog 0 0 594 475 Configure Schema Qt::Vertical false Iterations true 0 0 Parameters true 0 0 Qt::Horizontal 1 false 0 0 Qt::ScrollBarAlwaysOff Qt::ScrollBarAsNeeded QAbstractItemView::CurrentChanged|QAbstractItemView::DoubleClicked|QAbstractItemView::EditKeyPressed|QAbstractItemView::SelectedClicked true true QAbstractItemView::SelectItems Qt::ElideMiddle true true 10 0 QAbstractItemView::CurrentChanged|QAbstractItemView::DoubleClicked|QAbstractItemView::EditKeyPressed|QAbstractItemView::SelectedClicked true true QAbstractItemView::SelectItems Qt::ElideMiddle QAbstractItemView::ScrollPerItem true Qt::Horizontal QDialogButtonBox::Close|QDialogButtonBox::Ok buttonBox accepted() SchemaConfigurationDialog accept() 248 254 157 274 buttonBox rejected() SchemaConfigurationDialog reject() 316 260 286 274 treeView collapsed(QModelIndex) dataView collapse(QModelIndex) 107 228 302 228 treeView expanded(QModelIndex) dataView expand(QModelIndex) 107 228 302 228 dataView collapsed(QModelIndex) treeView collapse(QModelIndex) 425 239 137 239 dataView expanded(QModelIndex) treeView expand(QModelIndex) 425 239 137 239 ugene-1.9.8/src/plugins/workflow_designer/src/WorkflowPalette.h0000644000175000017500000000464411651544324023422 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_WORKFLOW_PALETTE_H_ #define _U2_WORKFLOW_PALETTE_H_ #include #include #include #include namespace U2 { using namespace Workflow; class WorkflowView; class WorkflowScene; class WorkflowPalette : public QTreeWidget { Q_OBJECT public: static const QString MIME_TYPE; WorkflowPalette(ActorPrototypeRegistry* reg, QWidget *parent = 0); QMenu* createMenu(const QString& name); QVariant saveState() const; void restoreState(const QVariant&); public slots: void resetSelection(); signals: void processSelected(Workflow::ActorPrototype*); void si_protoDeleted(const QString &); protected: void contextMenuEvent(QContextMenuEvent *e); void mouseMoveEvent ( QMouseEvent * event ); void mousePressEvent ( QMouseEvent * event ); void leaveEvent ( QEvent * event ); private slots: void handleItemAction(); void sl_selectProcess(bool checked = false); void rebuild(); void editElement(); void removeElement(); private: QTreeWidgetItem* createItemWidget(QAction* a); QAction* createItemAction(Workflow::ActorPrototype* item); void setContent(ActorPrototypeRegistry*); void sortTree(); private: QMap > categoryMap; QMap actionMap; QTreeWidgetItem *overItem; QAction* currentAction; QPoint dragStartPosition; friend class PaletteDelegate; }; }//namespace Q_DECLARE_METATYPE(QAction *) Q_DECLARE_METATYPE(U2::Workflow::ActorPrototype *) #endif ugene-1.9.8/src/plugins/workflow_designer/src/WorkflowViewItems.cpp0000644000175000017500000011546711651544325024302 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "WorkflowViewItems.h" #include "ItemViewStyle.h" #include "WorkflowViewController.h" #include "HRSceneSerializer.h" #include "WorkflowEditor.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include namespace U2 { WorkflowProcessItem::WorkflowProcessItem(Actor* prc) : process(prc) { setToolTip(process->getProto()->getDocumentation()); setFlag(QGraphicsItem::ItemIsSelectable, true); setFlag(QGraphicsItem::ItemIsMovable, true); #if (QT_VERSION >= QT_VERSION_CHECK(4, 6, 0)) setFlag(QGraphicsItem::ItemSendsGeometryChanges, true); #endif setAcceptHoverEvents(true); styles[ItemStyles::SIMPLE] = new SimpleProcStyle(this); styles[ItemStyles::EXTENDED] = new ExtendedProcStyle(this); currentStyle = getStyleByIdSafe(WorkflowSettings::defaultStyle()); currentStyle->setVisible(true); createPorts(); } WorkflowProcessItem::~WorkflowProcessItem() { qDeleteAll(styles.values()); delete process; qDeleteAll(ports); } ItemViewStyle* WorkflowProcessItem::getStyleByIdSafe(StyleId id) const { if (!styles.contains(id)) { uiLog.trace(QString("Unknown workflow item style: %1").arg(id)); id = ItemStyles::EXTENDED; } ItemViewStyle* result = styles.value(id); assert(result!=NULL); return result; } ItemViewStyle* WorkflowProcessItem::getStyleById(const StyleId & id) const { return styles.value(id); } bool WorkflowProcessItem::containsStyle(const StyleId & id) const { return styles.contains(id); } WorkflowPortItem* WorkflowProcessItem::getPort(const QString& id) const { foreach(WorkflowPortItem* pit, ports) { if (pit->getPort()->getId() == id) { return pit; } } return NULL; } void WorkflowProcessItem::createPorts() { assert(ports.isEmpty()); int num = process->getInputPorts().size() + 1; qreal pie = 180/num; int i = 1; QGraphicsScene* sc = scene(); foreach(Port* port, process->getInputPorts()) { WorkflowPortItem* pit = new WorkflowPortItem(this, port); ports << pit; pit->setOrientation(90 + pie*i++); if (sc) { sc->addItem(pit); } } num = process->getOutputPorts().size() + 1; pie = 180/num; i = 1; foreach(Port* port, process->getOutputPorts()) { WorkflowPortItem* pit = new WorkflowPortItem(this, port); ports << pit; pit->setOrientation(270 + pie*i++); if (sc) { sc->addItem(pit); } } } void WorkflowProcessItem::sl_update() { prepareGeometryChange(); currentStyle->refresh(); foreach(WorkflowPortItem* pit, ports) { pit->adaptOwnerShape(); } update(); } void WorkflowProcessItem::setStyle(StyleId s) { prepareGeometryChange(); currentStyle->setVisible(false); currentStyle = getStyleByIdSafe(s); currentStyle->setVisible(true); currentStyle->refresh(); foreach(WorkflowPortItem* pit, ports) { pit->setStyle(s); } assert(currentStyle); update(); } QRectF WorkflowProcessItem::boundingRect(void) const { QRectF brect = currentStyle->boundingRect(); if (/*getWorkflowScene()->getRunner()*/ true) { brect.setTop(brect.top() - QFontMetrics(QFont()).height()*2 - 2); } return brect; } QRectF WorkflowProcessItem::portsBoundingRect() const { QRectF rect; // null rect foreach(WorkflowPortItem* p, getPortItems()) { QRectF pBound = p->boundingRect(); QPointF pCenter = pBound.center(); pCenter = p->mapToItem(this, pCenter); pBound.moveCenter(pCenter); rect |= pBound; } return rect; } QPainterPath WorkflowProcessItem::shape () const { return currentStyle->shape(); } void WorkflowProcessItem::paint(QPainter *painter, const QStyleOptionGraphicsItem */*option*/, QWidget */*widget*/) { WorkflowAbstractRunner* rt = getWorkflowScene()->getRunner(); if (rt) { //{WorkerWaiting, WorkerReady, WorkerRunning, WorkerDone}; static QColor rsColors[4] = {QColor(234,143,7),"#04AA04", "#AA0404", "#0404AA"}; //{QColor(234,143,7),QColor(Qt::red),QColor(Qt::green),QColor(0,0,255)}; static QString rsNames[4] = {("Waiting"),("Ready"),("Running"),("Done")}; const QList rsList = rt->getState(this->process); WorkerState state = WorkerDone; if (rsList.contains(WorkerRunning)) { state = WorkerRunning; } else if (rsList.contains(WorkerReady)) { state = WorkerReady; } else if (rsList.contains(WorkerWaiting)) { state = WorkerWaiting; } QString stateName = rsNames[state]; QColor scolor = rsColors[state]; painter->setPen(scolor); QRectF brect = boundingRect(); qreal fh = QFontMetrics(QFont()).height(); if (rsList.size() == 1) { brect.setTop(brect.top()+2+fh); } painter->drawRoundedRect(brect, 5, 5); painter->drawText(brect, Qt::AlignHCenter, stateName); if (rsList.size() == 1) { } else { uint vals[4] = {0,0,0,0}; for (int i = rsList.size();i>0;) { vals[rsList.at(--i)]++; } // draw progress bar if (state != WorkerDone) { QRectF textRect(brect.topLeft()+QPointF(0,fh-1),QSizeF(brect.width(), 3)); textRect.setLeft(brect.left()+1); textRect.setRight(brect.right()-1); QColor fc = /*rsColors[WorkerDone];//*/QColor(0,80,222); fc.setAlpha(90); painter->setPen(fc); painter->drawRect(textRect); qreal done = (qreal)vals[WorkerDone]/rsList.size(); QBrush brush(fc); // QLinearGradient lg(textRect.topLeft(),textRect.topRight()); // lg.setColorAt(0, fc); // lg.setColorAt(done, fc.lighter(128)); // lg.setColorAt(done + 1./rsList.size(), QColor(Qt::white)); //lg.setColorAt(1, QColor(Qt::white)); //brush = QBrush(lg); textRect.setRight(textRect.left() + textRect.width()*done); painter->fillRect(textRect, brush); } // draw extended text painter->save(); QTextDocument d; d.setHtml("
    " + QString("%2/" " " " %6/" " %8/" " %9") .arg(rsColors[WorkerWaiting].name()).arg(vals[WorkerWaiting]) .arg(rsColors[WorkerReady].name()).arg(vals[WorkerReady]) .arg(rsColors[WorkerRunning].name()).arg(vals[WorkerRunning]) .arg(rsColors[WorkerDone].name()).arg(vals[WorkerDone]) .arg(rsList.size()) + "
    "); //d.setTextWidth(brect.width()); painter->translate(brect.center().x() - d.idealWidth()/2, brect.top() + fh); d.drawContents(painter/*, brect*/); painter->restore(); // qreal unit = brect.width()/rsList.size(); // qreal step = 3; // qreal w = 10; // QPointF base(brect.topLeft()); // base.ry() += 5; // for (int i = 3; i>=0; i--) { // // base.ry() -= step; // // painter->setPen(rsColors[i]); painter->drawLine(base, base + QPointF(unit*vals[i],0)); // QRectF rt(base, base + QPointF(unit*vals[i],w)); base = rt.topRight(); // painter->setPen(rsColors[i]); // QColor fc = rsColors[i]; fc.setAlpha(128); // painter->fillRect(rt, QBrush(fc)); // painter->drawText(rt, Qt::AlignJustify|Qt::AlignVCenter, rsNames[i]); // } } } } QVariant WorkflowProcessItem::itemChange ( GraphicsItemChange change, const QVariant & value ) { switch(change) { case ItemSelectedHasChanged: { currentStyle->update(); } break; case ItemZValueHasChanged: { qreal z = qVariantValue(value); foreach(WorkflowPortItem* pit, ports) { pit->setZValue(z); } } break; case ItemPositionChange: { // value is the new position. QPointF newPos = value.toPointF(); if (scene() && pos() != QPointF(0,0)) { QRectF bound = boundingRect() | childrenBoundingRect() | portsBoundingRect(); QRectF sceneRect = scene()->sceneRect(); qreal x0 = sceneRect.left() - bound.left(); qreal x1 = sceneRect.left() + sceneRect.width() - bound.right() - 10; //extra space for scroll bars qreal y0 = sceneRect.top() - bound.top(); qreal y1 = sceneRect.top() + sceneRect.height() - bound.bottom() - 10; newPos.setX( qBound(x0, newPos.x(), x1) ); newPos.setY( qBound(y0, newPos.y(), y1) ); } if (WorkflowSettings::snap2Grid()) { newPos.setX(round(newPos.x(), GRID_STEP)); newPos.setY(round(newPos.y(), GRID_STEP)); } return newPos; /*foreach(WorkflowPortItem* pit, ports) { foreach(WorkflowBusItem*bit, pit->getDataFlows()) { bit->prepareGeometryChange(); } }*/ } break; case ItemPositionHasChanged: { foreach(WorkflowPortItem* pit, ports) { pit->setPos(pos()); foreach(WorkflowBusItem*bit, pit->getDataFlows()) { bit->updatePos(); } } WorkflowScene * sc = qobject_cast(scene()); if(sc != NULL) { if (!sc->views().isEmpty()) { foreach(QGraphicsView* view, sc->views()) { QRectF itemRect = boundingRect() | childrenBoundingRect(); // ports are not the child items atm // unite with their bounds itemRect |= portsBoundingRect(); QPointF itemCenter = itemRect.center(); itemCenter = mapToScene(itemCenter); itemRect.moveCenter(itemCenter); view->ensureVisible(itemRect, 0, 0); } } sc->setModified(true); } if (scene()) { scene()->update(); } } break; case ItemSceneHasChanged: { WorkflowScene* ws = getWorkflowScene(); if (ws) { ItemViewStyle* viewStyle = styles.value(ItemStyles::EXTENDED); ExtendedProcStyle* extStyle = qgraphicsitem_cast(viewStyle); assert(extStyle); WorkflowView* view = ws->getController(); if (view) { connect(extStyle, SIGNAL(linkActivated(const QString&)), view->getPropertyEditor(), SLOT(sl_linkActivated(const QString&))); } foreach(WorkflowPortItem* pit, ports) { ws->addItem(pit); } } } break; case ItemSceneChange: if (qVariantValue(value) == NULL) { foreach(WorkflowPortItem* pit, ports) { scene()->removeItem(pit); } } break; default: break; } return QGraphicsItem::itemChange(change, value); } bool WorkflowProcessItem::sceneEvent( QEvent * event ) { if (currentStyle->sceneEventFilter(this, event)) { return true; } return QGraphicsItem::sceneEvent(event); } QList WorkflowProcessItem::getContextMenuActions() const { return currentStyle->getContextMenuActions(); } void WorkflowProcessItem::saveState(QDomElement& el) const { el.setAttribute("pos", QVariantUtils::var2String(pos())); el.setAttribute("style", styles.key(currentStyle)); foreach(ItemViewStyle* style, styles) { QDomElement stel = el.ownerDocument().createElement(style->getId()); style->saveState(stel); if (stel.hasAttributes() || stel.hasChildNodes()) { el.appendChild(stel); } } } void WorkflowProcessItem::loadState(QDomElement& el) { const QString posS = el.attribute("pos"); const QPointF pos = QVariantUtils::String2Var(posS).toPointF(); assert(!pos.isNull()); setPos(pos); foreach(ItemViewStyle* style, styles) { QDomElement stel = el.elementsByTagName(style->getId()).item(0).toElement(); if (stel.isNull()) continue; style->loadState(stel); } QString key = el.attribute("style"); if (styles.contains(key)) { setStyle(key); } } void WorkflowProcessItem::mouseMoveEvent( QGraphicsSceneMouseEvent *event ) { if (event->buttons() & Qt::LeftButton) { if (initialPositions.isEmpty()) { if (isSelected()) { QList selectedItems = scene()->selectedItems(); foreach(QGraphicsItem* item, selectedItems) { if (item->type()==WorkflowProcessItemType) { initialPositions[item] = item->scenePos(); } } } else { initialPositions[this] = scenePos(); } } // Find the active view. QGraphicsView *view = 0; if (event->widget()) { view = qobject_cast(event->widget()->parentWidget()); } for (int i=0, n=initialPositions.keys().size(); imapToScene(view->mapFromGlobal(event->screenPos())); QPointF buttonDownParentPos = view->mapToScene(view->mapFromGlobal(event->buttonDownScreenPos(Qt::LeftButton))); item->setPos(initialPositions.value(item) + currentParentPos - buttonDownParentPos); } } else { event->ignore(); } } void WorkflowProcessItem::mouseReleaseEvent( QGraphicsSceneMouseEvent *event ) { initialPositions.clear(); QGraphicsItem::mouseReleaseEvent(event); } ///////////// PIO ///////////// WorkflowPortItem* WorkflowPortItem::findNearbyBindingCandidate(const QPointF& pos) const { QPainterPath neighbourhood; neighbourhood.addEllipse(pos, R/2, R/2); //QRectF neighbourhood(pos.x() - R/2, pos.y() + R/2, R, R); WorkflowPortItem* candidate = NULL; qreal distance = R*2; foreach(QGraphicsItem* it, scene()->items(neighbourhood, Qt::IntersectsItemBoundingRect)) { WorkflowPortItem* next = qgraphicsitem_cast(it); if (next) { if (bindCandidates.contains(next)) { QLineF l(pos, next->headToScene()); qreal len = l.length(); if (distance > len) { distance = len; candidate = next; } } } } return candidate; } //static const QCursor portRotationCursor = QCursor(QBitmap(":workflow_designer/images/rot_cur.png")); //FIXME static const int portRotationModifier = Qt::AltModifier; static const int bl = (int) A/4; WorkflowPortItem::WorkflowPortItem(WorkflowProcessItem* owner, Port* p) : /*StyledItem(owner), */ currentStyle(owner->getStyle()),port(p),owner(owner),orientation(0), dragging(false), rotating(false), sticky(false), highlight(false) { setFlag(QGraphicsItem::ItemIsSelectable, true); setAcceptHoverEvents(true); QString tt = p->isInput() ? "Input port (" : "Output port ("; tt += p->getDocumentation(); tt += ").\nDrag it to connect to other process/port." "\nHold Alt key while dragging to change port orientation"; setToolTip(tt); setPos(owner->pos()); setZValue(owner->zValue()); } WorkflowPortItem::~WorkflowPortItem() { assert(flows.isEmpty()); } void WorkflowPortItem::setStyle(StyleId s) { Q_UNUSED(s); currentStyle = owner->getStyle(); adaptOwnerShape(); } void WorkflowPortItem::adaptOwnerShape() { setOrientation(orientation); } void WorkflowPortItem::setOrientation(qreal angle) { qreal oldOrientation = orientation; orientation = angle; bool snap2grid = WorkflowSettings::snap2Grid(); if (ItemStyles::SIMPLE == currentStyle) { // common algorithm works fine as well, // but gives visible distortions when snapping to grid if (snap2grid) { angle = round(angle, ANGLE_STEP); } angle = -angle; qreal x = R*qCos(angle*2*PI/360); qreal y = R*qSin(angle*2*PI/360); resetTransform(); translate(x, y); rotate(angle); } else { // EXTENDED STYLE resetTransform(); QRectF rec = owner->boundingRect(); QPolygonF pol(owner->shape().toFillPolygon()); qreal radius = qMax(rec.width(), rec.height()) * 2; //log.debug(QString("radius=%1 pol=%2").arg(radius).arg(pol.count())); QLineF centerLine(0,0,radius, 0); assert(pol.containsPoint(centerLine.p1(), Qt::WindingFill)); assert(!pol.containsPoint(centerLine.p2(), Qt::WindingFill)); centerLine.setAngle(angle); QPointF p1 = pol.first(); QPointF p2; QLineF polyLine; QPointF intersectPoint; for (int i = 1; i < pol.count(); ++i) { p2 = pol.at(i); polyLine = QLineF(p1, p2); if (QLineF::BoundedIntersection == polyLine.intersect(centerLine, &intersectPoint)) { break; } p1 = p2; } if (snap2grid && polyLine.p1().x() == polyLine.p2().x()) { //vertical line, snap intersectPoint to grid qreal v = round(intersectPoint.y(), GRID_STEP); qreal min = qMin(polyLine.p1().y(), polyLine.p2().y()); qreal max = qMax(polyLine.p1().y(), polyLine.p2().y()); intersectPoint.setY(qBound(min, v, max)); } if (snap2grid && polyLine.p1().y() == polyLine.p2().y()) { //horizontal line, do the same qreal v = round(intersectPoint.x(), GRID_STEP); qreal min = qMin(polyLine.p1().x(), polyLine.p2().x()); qreal max = qMax(polyLine.p1().x(), polyLine.p2().x()); intersectPoint.setX(qBound(min, v, max)); } translate(intersectPoint.x(), intersectPoint.y()); //qreal polyAngle = polyLine.angle(); qreal norm = polyLine.normalVector().angle(); qreal df = qAbs(norm - angle); if (df > 90 && df < 270) { norm += 180; } //log.info(QString("centerLine=[%1,%2]->[%3,%4]").arg(centerLine.p1().x()).arg(centerLine.p1().y()).arg(centerLine.p2().x()).arg(centerLine.p2().y())); //log.info(QString("polyLine=[%1,%2]->[%3,%4]").arg(polyLine.p1().x()).arg(polyLine.p1().y()).arg(polyLine.p2().x()).arg(polyLine.p2().y())); //log.info(QString("a=%1 pa=%2 pn=%3 n=%4 df=%5").arg(angle).arg(polyAngle).arg(polyLine.normalVector().angle()).arg(norm).arg(df)); rotate(-norm); } if(oldOrientation != orientation) { WorkflowScene * sc = qobject_cast(owner->scene()); if(sc != NULL) { sc->setModified(true); sc->update(); } } } WorkflowBusItem* WorkflowPortItem::getDataFlow(const WorkflowPortItem* otherPit) const { foreach(WorkflowBusItem* dit, flows) { if ((port->isInput() ? dit->getOutPort() : dit->getInPort()) == otherPit) { return dit; } } return NULL; } static bool checkTypes(Port* p1, Port* p2) { Port* ip = p1->isInput() ? p1 : p2; Port* op = p1->isInput() ? p2 : p1; DataTypePtr idt = ip->getType(); DataTypePtr odt = op->getType(); if (idt->isSingle() && odt->isMap()) { foreach(Descriptor d, odt->getAllDescriptors()) { if (idt == odt->getDatatypeByDescriptor(d)) return true; } } if (idt->isMap() && odt->isMap()) { foreach(Descriptor d1, idt->getAllDescriptors()) { foreach(Descriptor d2, odt->getAllDescriptors()) { if (idt->getDatatypeByDescriptor(d1) == odt->getDatatypeByDescriptor(d2)) return true; } } } return odt == idt; } WorkflowPortItem* WorkflowPortItem::checkBindCandidate(const QGraphicsItem* it) const { switch (it->type()) { case WorkflowProcessItemType: { const WorkflowProcessItem* receiver = static_cast(it); // try best matches first foreach(WorkflowPortItem* otherPit, receiver->getPortItems()) { if (port->canBind(otherPit->getPort()) && checkTypes(port, otherPit->getPort())) { return otherPit; } } // take first free port foreach(WorkflowPortItem* otherPit, receiver->getPortItems()) { if (port->canBind(otherPit->getPort())) { return otherPit; } } } break; case WorkflowPortItemType: { WorkflowPortItem* otherPit = (WorkflowPortItem*)(it); if (port->canBind(otherPit->getPort())) { return otherPit; } } break; } return NULL; } WorkflowBusItem* WorkflowPortItem::tryBind(WorkflowPortItem* otherPit) { WorkflowBusItem* dit = NULL; QList linkedActors; if (port->canBind(otherPit->getPort())) { WorkflowUtils::getLinkedActorsId(port->owner(), linkedActors); if(linkedActors.contains(otherPit->getPort()->owner()->getId())) { return NULL; } dit = new WorkflowBusItem(this, otherPit); flows << dit; otherPit->flows << dit; WorkflowScene * sc = qobject_cast(scene()); assert(sc != NULL); sc->addItem(dit); sc->setModified(true); dit->updatePos(); } return dit; } void WorkflowPortItem::removeDataFlow(WorkflowBusItem* flow) { assert(flows.contains(flow)); flows.removeOne(flow); port->removeLink(flow->getBus()); assert(!flows.contains(flow)); } QPointF WorkflowPortItem::head(const QGraphicsItem* item) const { return mapToItem(item, A/2 + bl, 0); } QPointF WorkflowPortItem::headToScene() const { return mapToScene(A, 0); } QLineF WorkflowPortItem::arrow(const QGraphicsItem* item) const { return QLineF(mapToItem(item, 0,0),mapToItem(item, A,0)); } QRectF WorkflowPortItem::boundingRect(void) const { QRectF rect(0, -A, A+A/2, 2*A); if (dragging) { rect |= QRectF(QPointF(A, 0), dragPoint); //FIXME arrow tip inclusion } return rect; } static void drawArrow(QPainter *painter, const QPen& pen, const QPointF& p1, const QPointF& p2) { painter->setPen(pen); QLineF l(p1, p2); painter->drawLine(l); //draw arrow tip painter->save(); painter->translate(p2); painter->rotate(-l.angle()); QRectF rf(-3*A, -A/2, A*1.5, A); QPainterPath tip(QPointF(0,0)); tip.arcTo(rf, -50, 100); tip.closeSubpath(); painter->fillPath(tip, QBrush(pen.color())); painter->restore(); } static QList getCandidates(WorkflowPortItem* port) { QList l; foreach(QGraphicsItem* it, port->scene()->items()) { if (it->type() == WorkflowPortItemType) { WorkflowPortItem* next = qgraphicsitem_cast(it); if (port->getPort()->canBind(next->getPort()) && checkTypes(next->getPort(), port->getPort())) { l.append(next); } } } return l; } void WorkflowPortItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) { Q_UNUSED(widget); QPointF p1(A/2 + bl, 0); QColor greenLight(0,0x99,0x33, 128); QColor stickyLight(0,0x77,0x33); if (highlight) { QPen pen; pen.setColor(greenLight); painter->setPen(pen); } //painter->fillRect(boundingRect(), QBrush(Qt::magenta, Qt::Dense4Pattern)); painter->setRenderHint(QPainter::Antialiasing); painter->drawLine(0, 0, bl, 0); if (port->isInput()) { if (highlight) { QPainterPath path; path.addEllipse(bl, -A/2, A, A); painter->fillPath(path, QBrush(greenLight)); } else { painter->drawArc(QRectF(bl, -A/2, A, A), 90*16, 180*16); } } else { if (highlight) { QPainterPath path; path.addEllipse(p1, A/2, A/2); painter->fillPath(path, QBrush(greenLight)); } else { painter->drawEllipse(p1, A/2, A/2); } } if (0 && port->getWidth() == 0) { // draw a hint painter->save(); QPen pen; //pen.setWidthF(2); pen.setStyle(Qt::DashLine); painter->setPen(pen); QPointF hc(R, 0); drawArrow(painter, pen, hc, p1); painter->translate(R, 0); painter->rotate(orientation); QRectF approx(-10, -10, 200, 100); QRectF htb = painter->boundingRect(approx, Qt::AlignCenter, port->getDisplayName()); //painter->drawRoundedRect(htb, 30, 30, Qt::RelativeSize); painter->drawRoundedRect(htb, 30, 30, Qt::RelativeSize); painter->drawText(approx, Qt::AlignCenter, port->getDisplayName()); painter->setPen(Qt::red);painter->drawPoint(0,0); painter->restore(); } if (dragging) { QPen pen; //pen.setWidthF(3); pen.setStyle(Qt::DotLine); if (sticky) { pen.setColor(stickyLight); } //put drag point inside of the scene rect QPointF pp = dragPoint; QRectF scRect = scene()->sceneRect(); QList sceneEdges; sceneEdges << QLineF(scRect.topLeft(), scRect.topRight()) << QLineF(scRect.topRight(), scRect.bottomRight()) << QLineF(scRect.bottomLeft(), scRect.bottomRight()) << QLineF(scRect.topLeft(), scRect.bottomLeft()); QLineF arr(mapToScene(dragPoint), mapToScene(p1)); QPointF crossPt; foreach(QLineF scEdge, sceneEdges) { if (scEdge.intersect(arr, &crossPt) == QLineF::BoundedIntersection) { pp = mapFromScene(crossPt); break; } } ////////////////////////////////////////////////////////////////////////// if (port->isInput()) drawArrow(painter, pen, pp, p1); else drawArrow(painter, pen, p1, pp); } else if (option->state & QStyle::State_Selected) { QPen pen; //pen.setWidthF(2); pen.setStyle(Qt::DotLine); painter->setPen(pen); painter->drawRoundedRect(boundingRect(), 30, 30, Qt::RelativeSize); } } void WorkflowPortItem::mouseMoveEvent( QGraphicsSceneMouseEvent * event ) { if (!dragging && !rotating && (event->buttons() & Qt::LeftButton) && !dragPoint.isNull()) { //log.debug("port grabbed mouse"); if ((event->pos().toPoint() - dragPoint.toPoint()).manhattanLength() < 10) return; event->accept(); //grabMouse(); if (event->modifiers() & portRotationModifier) { rotating = true; //setCursor(portRotationCursor); setCursor(QCursor(QPixmap(":workflow_designer/images/rot_cur.png"))); } //else { dragging = true; setCursor(Qt::ClosedHandCursor); bindCandidates = getCandidates(this); foreach(WorkflowPortItem* it, bindCandidates) { it->setHighlight(true);it->update(it->boundingRect()); } } } sticky = false; if (dragging) { rotating = (event->modifiers() & portRotationModifier); } if (!dragging && !rotating) { return; } event->accept(); prepareGeometryChange(); if (rotating) { qreal angle = QLineF(owner->pos(), event->scenePos()).angle(); setOrientation(angle); } if (dragging) { foreach(QGraphicsView* v, scene()->views()) { QRectF r(0,0,5,5); r.moveCenter(mapToScene(dragPoint)); v->ensureVisible(r,0,0); } /*dragPoint = rotating ? mapFromScene(event->scenePos()) : event->pos();*/ if (rotating) { dragPoint += event->scenePos() - event->lastScenePos(); } else { dragPoint += event->pos() - event->lastPos(); } WorkflowPortItem* preferable = findNearbyBindingCandidate(event->scenePos()); if (preferable) { dragPoint = preferable->head(this); sticky = true; } } } void WorkflowPortItem::mousePressEvent ( QGraphicsSceneMouseEvent * event ) { dragPoint = QPointF(); if ((event->buttons() & Qt::LeftButton) && !getWorkflowScene()->isLocked()) { dragPoint = event->pos(); if (event->modifiers() & portRotationModifier) { rotating = true; //setCursor(portRotationCursor); setCursor(QCursor(QPixmap(":workflow_designer/images/rot_cur.png"))); } else { setCursor(Qt::ClosedHandCursor); } } else { QGraphicsItem::mousePressEvent(event); } } void WorkflowPortItem::mouseReleaseEvent ( QGraphicsSceneMouseEvent * event ) { ungrabMouse(); unsetCursor(); QGraphicsItem::mouseReleaseEvent(event); rotating = false; if (dragging && (event->button() == Qt::LeftButton)) { event->accept(); QList li = scene()->items(/*event->scenePos()*/ mapToScene(dragPoint)); //bool done = false; WorkflowPortItem* otherPit = NULL; foreach(QGraphicsItem * it, li) { otherPit = checkBindCandidate(it); WorkflowBusItem* dit; if (otherPit && (dit = tryBind(otherPit))) { scene()->clearSelection(); IntegralBusPort* bp = qobject_cast(dit->getInPort()->getPort()); if (bp) { bp->setupBusMap(); } dit->getInPort()->setSelected(true); break; } } prepareGeometryChange(); dragging = false;dragPoint = QPointF(); foreach(WorkflowPortItem* it, bindCandidates) { it->setHighlight(false); } scene()->update(); bindCandidates.clear(); } } void WorkflowPortItem::hoverEnterEvent ( QGraphicsSceneHoverEvent * event ) { if (getWorkflowScene()->isLocked()) { return; } setCursor((event->modifiers() & portRotationModifier) ? QCursor(QPixmap(":workflow_designer/images/rot_cur.png")) : QCursor(Qt::OpenHandCursor)); } void WorkflowPortItem::hoverLeaveEvent(QGraphicsSceneHoverEvent *) { unsetCursor(); } QVariant WorkflowPortItem::itemChange ( GraphicsItemChange change, const QVariant & value ) { if (change == ItemPositionChange || change == ItemTransformChange) { foreach(WorkflowBusItem* dit, flows) { dit->prepareGeometryChange(); } } else if (change == ItemPositionHasChanged || change == ItemTransformHasChanged) { foreach(WorkflowBusItem* dit, flows) { //TODO correct update //dit->update(dit->boundingRect()); dit->updatePos(); } } else if (change == ItemSceneChange && qVariantValue(value) == NULL) { foreach(WorkflowBusItem* dit, flows) { scene()->removeItem(dit); delete dit; } } return QGraphicsItem::itemChange(change, value); } ////////////////// Flow ////////////// WorkflowBusItem::WorkflowBusItem(WorkflowPortItem* p1, WorkflowPortItem* p2) { if (p1->getPort()->isInput()) { assert(!p2->getPort()->isInput()); dst = p1; src = p2; } else { assert(p2->getPort()->isInput()); dst = p2; src = p1; } bus = new Link(p1->getPort(), p2->getPort()); setAcceptHoverEvents(true); setFlag(QGraphicsItem::ItemIsSelectable, true); setZValue(-1000); this->text = new HintItem(src->getPort()->getDisplayName(), this); connect(dst->getPort(), SIGNAL(bindingChanged()), this, SLOT(sl_update())); } WorkflowBusItem::~WorkflowBusItem() { assert(bus == NULL); //delete text; } void WorkflowBusItem::updatePos() { // QPointF p1 = dst->pos(); // QPointF p2 = src->pos(); QPointF p1 = dst->headToScene(); QPointF p2 = src->headToScene(); setPos((p1.x() + p2.x())/2, (p1.y() + p2.y())/2); } QVariant WorkflowBusItem::itemChange ( GraphicsItemChange change, const QVariant & value ) { if (change == ItemSceneChange && qVariantValue(value) == NULL) { dst->removeDataFlow(this); src->removeDataFlow(this); disconnect(dst->getPort(), SIGNAL(bindingChanged()), this, SLOT(sl_update())); //dst = src = NULL; delete bus; bus = NULL; } return QGraphicsItem::itemChange(change, value); } void WorkflowBusItem::hoverEnterEvent ( QGraphicsSceneHoverEvent * event ) { Q_UNUSED(event); setCursor(QCursor(Qt::PointingHandCursor)); } void WorkflowBusItem::hoverLeaveEvent ( QGraphicsSceneHoverEvent * event ) { Q_UNUSED(event); unsetCursor(); } QRectF WorkflowBusItem::boundingRect(void) const { QRectF brect(mapFromItem(dst, dst->boundingRect()).boundingRect() | mapFromItem(src, src->boundingRect()).boundingRect()); QRectF trect(text->boundingRect().translated(text->pos())); if (/*getWorkflowScene()->getRunner()*/ true) { trect.setTop(trect.top() - trect.height()); } return brect | trect; } QPainterPath WorkflowBusItem::shape () const { QPainterPath p; QPointF p1 = dst->head(this); QPointF p2 = src->head(this); QLineF direct(p2,p1); QLineF n = direct.normalVector(); n.setLength(A/2); p.moveTo(n.p2()); p.lineTo(n.translated(p1-p2).p2()); QLineF rn(n.p2(), n.p1()); rn.translate(n.p1()-n.p2()); p.lineTo(rn.translated(p1-p2).p2()); p.lineTo(rn.p2()); p.closeSubpath(); p.addRect(text->boundingRect().translated(text->pos())); return p; } void WorkflowBusItem::paint ( QPainter * painter, const QStyleOptionGraphicsItem * option, QWidget * widget) { Q_UNUSED(widget); painter->setRenderHint(QPainter::Antialiasing); QColor baseColor(0x66, 0x66, 0x66); painter->setPen(baseColor); //painter->fillRect(boundingRect(), QBrush(Qt::blue)); QPointF p1 = dst->head(this); QPointF p2 = src->head(this); QPainterPath path; path.addEllipse(p2, A/2 - 2, A/2 - 2); path.addEllipse(p1, A/2 - 2, A/2 - 2); painter->fillPath(path, QBrush(baseColor)); QPen pen = painter->pen(); if (option->state & QStyle::State_Selected) { pen.setWidthF(1.5); pen.setStyle(Qt::DashLine); } if (!validate()) { pen.setColor(Qt::red); } drawArrow(painter, pen, p2, p1); //update(); painter->setRenderHint(QPainter::NonCosmeticDefaultPen); QColor yc = QColor(Qt::yellow).lighter();yc.setAlpha(127); QRectF textRec = text->boundingRect().translated(text->pos()); painter->fillRect(textRec, QBrush(yc)); painter->drawRect(textRec); WorkflowAbstractRunner* rt = getWorkflowScene()->getRunner(); if (rt) { int msgsInQueue = rt->getMsgNum(this->bus); int passed = rt->getMsgPassed(this->bus); QString rts = QString("%1 in queue, %2 passed").arg(msgsInQueue).arg(passed); QRectF rtb = textRec.translated(0, -QFontMetricsF(QFont()).height()); qreal shift = (QFontMetricsF(QFont()).width(rts) - rtb.width()) / 2; rtb.setLeft(rtb.left() - shift); rtb.setRight(rtb.right() + shift); painter->drawText(rtb, Qt::AlignHCenter, rts); if (msgsInQueue == 0) { return; } qreal dx = (p2.x() - p1.x())/msgsInQueue; qreal dy = (p2.y() - p1.y())/msgsInQueue; QPointF dp(dx,dy); QColor c1("#AA0404"); painter->setPen(c1); c1.setAlphaF(0.8); QColor c2(Qt::white); c2.setAlphaF(0.8); while (msgsInQueue-- > 0) { QPainterPath p; p.addEllipse(p1, 3,3); QRadialGradient rg(p1+QPointF(1.,-1.), 3); rg.setColorAt(1, c1); rg.setColorAt(0, c2); QBrush br(rg); painter->fillPath(p,br); //painter->drawEllipse(p1, 3,3); p1 += dp; } } } void WorkflowBusItem::sl_update() { update(); } bool WorkflowBusItem::validate() { QStringList lst; return dst->getPort()->validate(lst); } void WorkflowBusItem::saveState(QDomElement& el) const { el.setAttribute("hint-pos", QVariantUtils::var2String(text->pos())); } void WorkflowBusItem::loadState(QDomElement& el) { if (el.hasAttribute("hint-pos")) { QPointF pos = QVariantUtils::String2Var(el.attribute("hint-pos")).toPointF(); if (!pos.isNull()) { text->setPos(pos); } } } WorkflowScene* StyledItem::getWorkflowScene() const { return qobject_cast(scene()); } }//namespace ugene-1.9.8/src/plugins/workflow_designer/src/WorkflowEditor.cpp0000644000175000017500000004264611651544324023611 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "WorkflowEditor.h" #include "WorkflowViewController.h" #include "IterationListWidget.h" #include "WorkflowEditorDelegates.h" #include "ActorCfgModel.h" #include #include #include #include #include #include #define MAIN_SPLITTER "main.splitter" #define TAB_SPLITTER "tab.splitter" namespace U2 { WorkflowEditor::WorkflowEditor(WorkflowView *p) : QWidget(p), owner(p), custom(NULL), customWidget(NULL), subject(NULL), actor(NULL) { setupUi(this); inputPortWidget << table2; outputPortWidget << table3; inputPortBox->setEnabled(false); outputPortBox->setEnabled(false); inputPortBox->setVisible(true); outputPortBox->setVisible(true); caption->setMinimumHeight(nameEdit->sizeHint().height()); //doc->setMaximumHeight(height()/4); iterationList = new IterationListWidget(this); iterationBox->layout()->addWidget(iterationList); connect(iterationBox, SIGNAL(toggled(bool)), iterationList, SLOT(setVisible(bool))); connect(iterationBox, SIGNAL(toggled(bool)), SLOT(sl_resizeSplitter(bool))); iterationBox->setChecked(false); //iterationBox->setMaximumHeight(height()/4); actorModel = new ActorCfgModel(this, iterationList->list()); table->setModel(actorModel); table->horizontalHeader()->setResizeMode(QHeaderView::Interactive); table->horizontalHeader()->setStretchLastSection(true); //table->horizontalHeader()->setStretchLastSection(false); //table->horizontalHeader()->setResizeMode(0, QHeaderView::ResizeToContents); //table->horizontalHeader()->setResizeMode(1, QHeaderView::Interactive); //table->horizontalHeader()->setResizeMode(2, QHeaderView::Stretch); table->horizontalHeader()->setClickable(false); table->verticalHeader()->hide(); table->verticalHeader()->setDefaultSectionSize(QFontMetrics(QFont()).height() + 6); table->setItemDelegate(new SuperDelegate(this)); //table->setMinimumHeight(height()/2); reset(); doc->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); propDoc->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); doc->installEventFilter(this); connect(iterationList, SIGNAL(iterationListAboutToChange()), SLOT(finishPropertyEditing())); connect(iterationList, SIGNAL(selectionChanged()), SLOT(updateIterationData())); connect(iterationList, SIGNAL(listChanged()), SLOT(commitIterations())); connect(iterationList, SIGNAL(selectionChanged()), SIGNAL(iterationSelected())); connect(nameEdit, SIGNAL(editingFinished()), SLOT(editingLabelFinished())); connect(table->selectionModel(), SIGNAL(currentChanged(QModelIndex, QModelIndex)), SLOT(sl_showPropDoc())); connect(table->model(), SIGNAL(dataChanged(QModelIndex, QModelIndex)), SLOT(handleDataChanged(QModelIndex, QModelIndex))); // FIXME //connect(doc, SIGNAL(customContextMenuRequested(const QPoint &)), SLOT(sl_contextMenuForDoc(const QPoint &))); } void WorkflowEditor::setEditable(bool editable) { table->setDisabled(!editable); iterationList->setDisabled(!editable); foreach(QWidget* w, inputPortWidget) { w->setDisabled(!editable); } foreach(QWidget* w, outputPortWidget) { w->setDisabled(!editable); } } void WorkflowEditor::sl_resizeSplitter(bool b) { QWidget *w = qobject_cast(sender()); int ind = splitter->indexOf(w); if(ind != -1) { if(!b) { splitter->setStretchFactor(ind, 0); QList sizes = splitter->sizes(); sizes[ind] = 0; splitter->setSizes(sizes); } else { if(paramBox == w) { changeSizes(paramBox, paramHeight); } else { int h = w->minimumHeight(); QList sizes = splitter->sizes(); sizes[ind] = h; sizes[splitter->indexOf(propDoc)] -= h; splitter->setSizes(sizes); } } } } void WorkflowEditor::changeSizes(QWidget *w, int h) { int ind = splitter->indexOf(w); if(ind == -1) { return; } else { QList sizes = splitter->sizes(); sizes[ind] = h; sizes[splitter->indexOf(propDoc)] -= h/2; sizes[splitter->indexOf(doc)] -= h/2; splitter->setSizes(sizes); } } void WorkflowEditor::handleDataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight) { if (topLeft == bottomRight) { commitIterations(); } } void WorkflowEditor::changeScriptMode(bool _mode) { if(table->currentIndex().column() == 2) { table->clearSelection(); table->setCurrentIndex(QModelIndex()); } actorModel->changeScriptMode(_mode); //table->horizontalHeader()->resizeSections(QHeaderView::ResizeToContents); table->horizontalHeader()->setResizeMode(QHeaderView::Interactive); table->horizontalHeader()->setStretchLastSection(true); if(_mode) { int tWidth = table->width(); table->setColumnWidth(0, tWidth/3 - 2); table->setColumnWidth(1, tWidth/3 - 2); table->setColumnWidth(2, tWidth/3 - 2); } } void WorkflowEditor::selectIteration(int id) { iterationList->selectIteration(id); } Iteration WorkflowEditor::getCurrentIteration() const { return iterationList->list().at(iterationList->current()); } void WorkflowEditor::updateIterationData() { if (sender()) { finishPropertyEditing(); } actorModel->setIterations(iterationList->list()); actorModel->selectIteration(iterationList->current()); } void WorkflowEditor::sl_showDoc(const QString& str) { propDoc->setText(str); } void WorkflowEditor::sl_showPropDoc() { QModelIndex current = table->selectionModel()->currentIndex(); if (current.isValid()) { propDoc->setText(WorkflowUtils::getRichDoc(current.data(DescriptorRole).value())); } else { propDoc->setText(""); } } void WorkflowEditor::editingLabelFinished() { QString newLabel = nameEdit->text(); if( !newLabel.isEmpty() && newLabel != actor->getLabel() ) { actor->setLabel(newLabel); owner->getScene()->setModified(true); owner->refreshView(); } } void WorkflowEditor::reset() { caption->setText(""); nameEdit->hide(); paramBox->setTitle(tr("Parameters")); setDescriptor(NULL); edit(NULL); actor = NULL; actorModel->setActor(NULL); propDoc->setText(""); inputPortBox->setEnabled(false); outputPortBox->setEnabled(false); inputPortBox->setVisible(true); outputPortBox->setVisible(true); paramBox->setEnabled(false); QList sizes = splitter->sizes(); int splitterHeight = splitter->height(); int indDoc = splitter->indexOf(doc); int indPropDoc = splitter->indexOf(propDoc); int ind = splitter->indexOf(inputPortBox); splitter->setStretchFactor(ind, 0); sizes[ind] = 0; ind = splitter->indexOf(outputPortBox); splitter->setStretchFactor(ind, 0); sizes[ind] = 0; ind = splitter->indexOf(paramBox); splitter->setStretchFactor(ind, 0); sizes[ind] = 0; ind = splitter->indexOf(iterationBox); splitter->setStretchFactor(ind, 0); sizes[ind] = 0; sizes[indDoc] = splitterHeight/2; splitter->setStretchFactor(indDoc, 1); sizes[indPropDoc] = splitterHeight/2; splitter->setStretchFactor(indPropDoc, 1); splitter->setSizes(sizes); paramHeight = 0; inputHeight = 0; outputHeight = 0; } void WorkflowEditor::resetIterations() { //disconnect(iterationList, SIGNAL(listChanged()), this, SLOT(commitIterations())); iterationList->setList(owner->getScene()->getIterations()); //connect(iterationList, SIGNAL(listChanged()), SLOT(commitIterations())); } void WorkflowEditor::commitIterations() { uiLog.trace("committing iterations data"); owner->getScene()->setIterations(iterationList->list()); } void WorkflowEditor::finishPropertyEditing() { //table->setCurrentCell(0,0, QItemSelectionModel::NoUpdate); table->setCurrentIndex(QModelIndex()/*table->model()->index(0, 0, QModelIndex())*/); } void WorkflowEditor::commit() { finishPropertyEditing(); //commitIterations(); } void WorkflowEditor::editActor(Actor* a) { reset(); actor = a; if (a) { caption->setText(tr("Element name:")); nameEdit->setText(a->getLabel()); nameEdit->show(); setDescriptor(a->getProto(), tr("To configure the parameters of the element go to \"Parameters\" area below.")); edit(a); paramHeight = table->rowHeight(0) * (table->model()->rowCount() + 3); paramBox->setTitle(tr("Parameters")); if(paramBox->isChecked()) { changeSizes(paramBox, paramHeight); } if(!a->getInputPorts().isEmpty()) { inputPortBox->setVisible(true); inputHeight = 0; foreach(Port *p, a->getInputPorts()) { BusPortEditor* ed = new BusPortEditor(qobject_cast(p)); ed->setParent(p); p->setEditor(ed); QWidget *w = ed->getWidget(); inputHeight += ed->getOptimalHeight(); inputLayout->addWidget(w); w->setVisible(inputPortBox->isChecked()); inputPortBox->setEnabled(true); inputPortBox->setVisible(true); connect(ed, SIGNAL(si_showDoc(const QString&)), SLOT(sl_showDoc(const QString&))); inputPortWidget << w; } connect(inputPortBox, SIGNAL(toggled(bool)), SLOT(sl_changeVisibleInput(bool))); if(inputPortBox->isChecked()) { changeSizes(inputPortBox, inputHeight); } } else { inputPortBox->setEnabled(false); inputPortBox->setVisible(false); inputPortBox->resize(0,0); } if(!a->getOutputPorts().isEmpty()) { outputPortBox->setVisible(true); outputHeight = 0; foreach(Port *p, a->getOutputPorts()) { BusPortEditor* ed = new BusPortEditor(qobject_cast(p)); ed->setParent(p); p->setEditor(ed); QWidget *w = ed->getWidget(); outputHeight += ed->getOptimalHeight(); outputLayout->addWidget(w); w->setVisible(outputPortBox->isChecked()); outputPortBox->setEnabled(true); outputPortBox->setVisible(true); connect(ed, SIGNAL(si_showDoc(const QString&)), SLOT(sl_showDoc(const QString&))); outputPortWidget << w; } connect(outputPortBox, SIGNAL(toggled(bool)), SLOT(sl_changeVisibleOutput(bool))); if(outputPortBox->isChecked()) { changeSizes(outputPortBox, outputHeight); } } else { outputPortBox->setEnabled(false); outputPortBox->setVisible(false); outputPortBox->resize(0,0); } } } void WorkflowEditor::sl_changeVisibleInput(bool isChecked) { if(inputPortWidget.isEmpty()) { return; } foreach(QWidget *w, inputPortWidget) { w->setVisible(isChecked); } if(!isChecked) { int ind = splitter->indexOf(inputPortBox); QList sizes = splitter->sizes(); splitter->setStretchFactor(ind, 0); //splitterSizes[0] += splitterSizes[ind]; sizes[ind] = 0; splitter->setSizes(sizes); } else { changeSizes(inputPortBox, inputHeight); } } void WorkflowEditor::sl_changeVisibleOutput(bool isChecked) { if(outputPortWidget.isEmpty()) { return; } foreach(QWidget *w, outputPortWidget) { w->setVisible(isChecked); } if(!isChecked) { int ind = splitter->indexOf(outputPortBox); QList sizes = splitter->sizes(); splitter->setStretchFactor(ind, 0); //splitterSizes[0] += splitterSizes[ind]; sizes[ind] = 0; splitter->setSizes(sizes); } else { changeSizes(outputPortBox, outputHeight); } } void WorkflowEditor::editPort(Port* p) { reset(); if (p) { //caption->setText(formatPortCaption(p)); QString portDoc = tr("%1 \"%2\" of task \"%3\":
    %4

    %5") .arg(p->isOutput() ? tr("Output port") : tr("Input port")) .arg(p->getDisplayName()) .arg(p->owner()->getLabel()) .arg(p->getDocumentation()) .arg(tr("You can observe data slots of the port and configure connections if any in the \"Parameters\" widget suited below.")); doc->setText(portDoc); inputPortBox->setEnabled(false); outputPortBox->setEnabled(false); inputPortBox->setVisible(false); outputPortBox->setVisible(false); BusPortEditor* ed = new BusPortEditor(qobject_cast(p)); ed->setParent(p); p->setEditor(ed); paramHeight = ed->getOptimalHeight(); edit(p); if(paramBox->isChecked()) { changeSizes(paramBox, paramHeight); } if(p->isInput()) { paramBox->setTitle(tr("Input data")); } else { paramBox->setTitle(tr("Output data")); } } } void WorkflowEditor::setDescriptor(Descriptor* d, const QString& hint) { QString text = d ? WorkflowUtils::getRichDoc(*d) + "

    " + hint : hint; if (text.isEmpty()) { text = tr("Select an element to inspect."); } doc->setText(text); } void WorkflowEditor::edit(Configuration* cfg) { paramBox->setEnabled(true); disconnect(paramBox, SIGNAL(toggled(bool)), tableSplitter, SLOT(setVisible(bool))); if (customWidget) { custom->commit(); customWidget->hide(); paramBox->layout()->removeWidget(customWidget); customWidget->disconnect(); delete customWidget; } foreach(QWidget *w, inputPortWidget) { w->hide(); inputLayout->removeWidget(w); //w = NULL; w->disconnect(); } inputPortWidget.clear(); foreach(QWidget *w, outputPortWidget) { w->hide(); inputLayout->removeWidget(w); //w = NULL; w->disconnect(); } outputPortWidget.clear(); subject = cfg; custom = cfg ? cfg->getEditor() : NULL; customWidget = custom ? custom->getWidget() : NULL; if(customWidget) { connect(paramBox, SIGNAL(toggled(bool)), customWidget, SLOT(setVisible(bool))); connect(paramBox, SIGNAL(toggled(bool)), SLOT(sl_resizeSplitter(bool))); } //int h = 0; if (subject && !customWidget) { assert(actor); actorModel->setActor(actor); updateIterationData(); tableSplitter->setVisible(paramBox->isChecked()); /*if(paramBox->isChecked()) { h = table->sizeHint().height(); }*/ connect(paramBox, SIGNAL(toggled(bool)), tableSplitter, SLOT(setVisible(bool))); connect(paramBox, SIGNAL(toggled(bool)), SLOT(sl_resizeSplitter(bool))); } else { tableSplitter->hide(); if (customWidget) { if (actor) assert(0 && "No support for iterations yet"); paramBox->layout()->addWidget(customWidget); customWidget->setVisible(paramBox->isChecked()); /*if(paramBox->isChecked()) { h = customWidget->minimumSizeHint().height(); }*/ } } } QVariant WorkflowEditor::saveState() const { QVariantMap m; m.insert(MAIN_SPLITTER, splitter->saveState()); m.insert(TAB_SPLITTER, tableSplitter->saveState()); return m; } void WorkflowEditor::restoreState(const QVariant& v) { QVariantMap m = v.toMap(); splitter->restoreState(m.value(MAIN_SPLITTER).toByteArray()); tableSplitter->restoreState(m.value(TAB_SPLITTER).toByteArray()); } bool WorkflowEditor::eventFilter(QObject* object, QEvent* event) { if (event->type() == QEvent::Shortcut || event->type() == QEvent::ShortcutOverride) { if (object == doc) { event->accept(); return true; } } return false; } static const QString& PARAM_ARG("param:"); void WorkflowEditor::sl_linkActivated(const QString& url) { QStringList args = url.split('&'); QString id; foreach(QString arg, args) { if (arg.startsWith(PARAM_ARG)) { id = arg.mid(PARAM_ARG.length()); } } QModelIndex modelIndex = actorModel->modelIndexById(id); QModelIndex prev = table->selectionModel()->currentIndex(); if (modelIndex==prev) { table->selectionModel()->reset(); } table->setCurrentIndex(modelIndex); } }//namespace ugene-1.9.8/src/plugins/workflow_designer/src/SceneSerializer.h0000644000175000017500000000275111651544324023355 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_WORKFLOW_SCENE_SERIALIZER_H_ #define _U2_WORKFLOW_SCENE_SERIALIZER_H_ #include class QGraphicsItem; namespace U2 { class WorkflowScene; class WorkflowProcessItem; class WorkflowBusItem; class SceneSerializer { public: static void saveItems(const QList& items, QDomElement& proj); static void scene2xml(const WorkflowScene* scene, QDomDocument& xml); static QString xml2scene(const QDomElement& projectElement, WorkflowScene* scene, QMap& remapping, bool ignoreErrors = false, bool select = false); }; } // U2 #endif // _U2_WORKFLOW_SCENE_SERIALIZER_H_ ugene-1.9.8/src/plugins/workflow_designer/src/WorkflowEditorDelegates.cpp0000644000175000017500000000725211651544324025421 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "WorkflowEditor.h" #include "IterationListWidget.h" #include "WorkflowEditorDelegates.h" namespace U2 { /******************************** * ProxyDelegate ********************************/ QWidget *ProxyDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const { //if (owner->custom) { QItemDelegate* itemDelegate = index.model()->data(index, DelegateRole).value(); if (itemDelegate) { connect(itemDelegate, SIGNAL(commitData(QWidget*)), SIGNAL(commitData(QWidget*))); return itemDelegate->createEditor(parent, option, index); } } return QItemDelegate::createEditor(parent, option, index); } void ProxyDelegate::setEditorData(QWidget *editor, const QModelIndex &index) const { //if (owner->custom) { QItemDelegate* itemDelegate = index.model()->data(index, DelegateRole).value(); if (itemDelegate) { itemDelegate->setEditorData(editor, index); return; } } QItemDelegate::setEditorData(editor, index); } void ProxyDelegate::setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const { QVariant old; QVariant expanded; PropertyDelegate* propertyDelegate = model->data(index, DelegateRole).value(); if (/*owner->custom &&*/ propertyDelegate ) { old = model->data(index, ConfigurationEditor::ItemValueRole); propertyDelegate->setModelData(editor, model, index); expanded = model->data(index, ConfigurationEditor::ItemListValueRole); } else { old = model->data(index, Qt::EditRole); QItemDelegate::setModelData(editor, model, index); } /* QString name = model->data(index, DescriptorRole).value().getId(); if (handlePropertyValueList(name, expanded)) { return; }*/ QVariant val = model->data(index, (propertyDelegate == NULL) ? (int)Qt::EditRole : (int)ConfigurationEditor::ItemValueRole); if (val != old) { QString name = model->data(index, DescriptorRole).value().getId(); if (handlePropertyValueList(name, expanded)) { return; } setPropertyValue(name, val); if (propertyDelegate) { model->setData(index, propertyDelegate->getDisplayValue(val), Qt::DisplayRole); } model->setData(index, model->data(index, Qt::DisplayRole).toString(), Qt::ToolTipRole); } } /******************************** * SuperDelegate ********************************/ SuperDelegate::SuperDelegate(WorkflowEditor *parent) : ProxyDelegate(parent), owner(parent) { } bool SuperDelegate::handlePropertyValueList(const QString& name, QVariant list) const { return owner->iterationList->expandList(owner->actor->getId(), name, list); } } // U2 ugene-1.9.8/src/plugins/workflow_designer/src/WorkflowDocument.cpp0000644000175000017500000001512611651544324024132 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include #include #include #include #include #include #include #include #include #include #include #include "WorkflowViewController.h" #include "HRSceneSerializer.h" #include "WorkflowDocument.h" /* TRANSLATOR U2::IOAdapter */ namespace U2 { const GObjectType WorkflowGObject::TYPE("workflow-obj"); const GObjectViewFactoryId WorkflowViewFactory::ID("workflow-view-factory"); const DocumentFormatId WorkflowDocFormat::FORMAT_ID = "WorkflowDocFormat"; bool WorkflowGObject::isTreeItemModified () const { if (view) { return view->getScene()->isModified(); } return GObject::isItemModified(); } void WorkflowGObject::setView(WorkflowView* _view) { view = _view; } void WorkflowGObject::setSceneRawData(const QString & data) { assert(view != NULL); assert(!view->getScene()->isModified()); serializedScene = data; } GObject* WorkflowGObject::clone() const { WorkflowGObject* copy = new WorkflowGObject(getGObjectName(), serializedScene, getGHintsMap()); assert(!view); return copy; } ////////////////////////////////////////////////////////////////////////// /// Workflow document format WorkflowDocFormat::WorkflowDocFormat(QObject* p) : DocumentFormat(p, DocumentFormatFlags_W1, QStringList(WorkflowUtils::WD_FILE_EXTENSIONS) << WorkflowUtils::WD_XML_FORMAT_EXTENSION), formatName(tr("Workflow Schema")) { supportedObjectTypes += WorkflowGObject::TYPE; } Document* WorkflowDocFormat::createNewDocument(IOAdapterFactory* io, const QString& url, const QVariantMap& fs) { Document* d = DocumentFormat::createNewDocument(io, url, fs); GObject* o = new WorkflowGObject(tr("Workflow Schema"), ""); d->addObject(o); return d; } #define BUFF_SIZE 1024 Document* WorkflowDocFormat::loadDocument(IOAdapter* io, TaskStateInfo& ti, const QVariantMap& fs, DocumentLoadMode mode) { Q_UNUSED(mode); QByteArray rawData; QByteArray block(BUFF_SIZE, '\0'); int blockLen = 0; while ((blockLen = io->readBlock(block.data(), BUFF_SIZE)) > 0) { rawData.append(block.data(), blockLen); ti.progress = io->getProgress(); } if (checkRawData(rawData).score != FormatDetection_Matched) { ti.setError(tr("Invalid header. %1 expected").arg(HRSchemaSerializer::HEADER_LINE)); rawData.clear(); return NULL; } //todo: check file-readonly status? QList objects; QString data = QString::fromUtf8(rawData.data(), rawData.size()); objects.append(new WorkflowGObject(tr("Workflow Schema"), data)); return new Document(this, io->getFactory(), io->getURL(), objects, fs); } void WorkflowDocFormat::storeDocument( Document* d, TaskStateInfo& ts, IOAdapter* io) { Q_UNUSED(ts) assert(d->getDocumentFormat() == this); assert(d->getObjects().size() ==1); WorkflowGObject* wo = qobject_cast(d->getObjects().first()); assert(wo && wo->getView()); QByteArray rawData = HRSceneSerializer::scene2String(wo->getView()->getScene(), wo->getView()->getMeta()).toUtf8(); int nWritten = 0; int nTotal = rawData.size(); while(nWritten < nTotal) { int d = io->writeBlock(rawData.data() + nWritten, nTotal - nWritten); assert(d > 0); nWritten+= d; } wo->getView()->getScene()->setModified(false); wo->setSceneRawData(rawData); } RawDataCheckResult WorkflowDocFormat::checkRawData(const QByteArray& data, const GUrl&) const { LoadWorkflowTask::FileFormat format = LoadWorkflowTask::detectFormat(data); bool ok = format == LoadWorkflowTask::HR || format == LoadWorkflowTask::XML; return ok ? FormatDetection_Matched : FormatDetection_NotMatched; } bool WorkflowViewFactory::canCreateView(const MultiGSelection& multiSelection) { foreach(GObject* go, SelectionUtils::findObjects(WorkflowGObject::TYPE, &multiSelection, UOF_LoadedOnly)) { if (!qobject_cast(go)->getView()) { return true; } } return false; } Task* WorkflowViewFactory::createViewTask(const MultiGSelection& multiSelection, bool single) { QSet documents = SelectionUtils::findDocumentsWithObjects(WorkflowGObject::TYPE, &multiSelection, UOF_LoadedAndUnloaded, true); if (documents.size() == 0) { return NULL; } Task* result = (single || documents.size() == 1) ? NULL : new Task(tr("Open multiple views"), TaskFlag_NoRun); foreach(Document* d, documents) { Task* t = new OpenWorkflowViewTask(d); if (result == NULL) { return t; } result->addSubTask(t); } return result; } OpenWorkflowViewTask::OpenWorkflowViewTask(Document* doc) : ObjectViewTask(WorkflowViewFactory::ID) { if (!doc->isLoaded()) { documentsToLoad.append(doc); } else { foreach(GObject* go, doc->findGObjectByType(WorkflowGObject::TYPE)) { selectedObjects.append(go) ; } assert(!selectedObjects.isEmpty()); } } void OpenWorkflowViewTask::open() { if (stateInfo.hasError()) { return; } if (!documentsToLoad.isEmpty()) { foreach(GObject* go, documentsToLoad.first()->findGObjectByType(WorkflowGObject::TYPE)) { selectedObjects.append(go) ; } } foreach(QPointer po, selectedObjects) { WorkflowGObject* o = qobject_cast(po); assert(o && !o->getView()); WorkflowView* view = new WorkflowView(o); AppContext::getMainWindow()->getMDIManager()->addMDIWindow(view); AppContext::getMainWindow()->getMDIManager()->activateWindow(view); } } }//namespace ugene-1.9.8/src/plugins/workflow_designer/src/WorkflowSceneIOTasks.cpp0000644000175000017500000001072311651544324024645 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include #include #include #include #include #include #include #include "WorkflowViewController.h" #include "HRSceneSerializer.h" #include "SceneSerializer.h" #include "WorkflowDocument.h" #include "WorkflowSceneIOTasks.h" namespace U2 { using namespace Workflow; /********************************** * SaveWorkflowSceneTask **********************************/ const QString SaveWorkflowSceneTask::SCHEMA_PATHS_SETTINGS_TAG = "workflow_settings/schema_paths"; SaveWorkflowSceneTask::SaveWorkflowSceneTask(WorkflowScene* s, const Metadata& m) : Task(tr("Save workflow scene task"), TaskFlag_None), scene(s), meta(m) { GCOUNTER(cvar,tvar,"SaveWorkflowSceneTask"); assert(scene != NULL); rawData = HRSceneSerializer::scene2String(scene, meta); // add ( name, path ) pair to settings. need for running schemas in cmdline by name Settings * settings = AppContext::getSettings(); assert( settings != NULL ); QVariantMap pathsMap = settings->getValue( SCHEMA_PATHS_SETTINGS_TAG ).toMap(); pathsMap.insert(meta.name, meta.url); settings->setValue( SCHEMA_PATHS_SETTINGS_TAG, pathsMap ); } void SaveWorkflowSceneTask::run() { if(hasError()) { return; } QFile file(meta.url); if(!file.open(QIODevice::WriteOnly)) { setError(L10N::errorOpeningFileWrite(meta.url)); return; } QTextStream out(&file); out.setCodec("UTF-8"); out << rawData; } Task::ReportResult SaveWorkflowSceneTask::report() { if (!stateInfo.hasError() && !scene.isNull()) { scene->setModified(false); } return ReportResult_Finished; } /********************************** * LoadWorkflowSceneTask **********************************/ LoadWorkflowSceneTask::LoadWorkflowSceneTask(WorkflowScene* s, Workflow::Metadata* m, const QString& u): Task(tr("Load workflow scene"),TaskFlag_None), scene(s), meta(m), url(u) { GCOUNTER(cvar,tvar, "LoadWorkflowSceneTask"); assert(scene != NULL); assert(meta != NULL); } void LoadWorkflowSceneTask::run() { QFile file(url); if(!file.open(QIODevice::ReadOnly)) { setError(L10N::errorOpeningFileRead(url)); return; } QTextStream in(&file); in.setCodec("UTF-8"); rawData = in.readAll(); format = LoadWorkflowTask::detectFormat(rawData); if(format == LoadWorkflowTask::UNKNOWN) { setError(tr("Undefined format: plain text or xml expected")); return; } } Task::ReportResult LoadWorkflowSceneTask::report() { if(hasError()) { return ReportResult_Finished; } QString err; if (!scene->items().isEmpty()) { scene->clearScene(); } if(format == LoadWorkflowTask::HR) { err = HRSceneSerializer::string2Scene(rawData, scene, meta); } else if(format == LoadWorkflowTask::XML) { QDomDocument xml; QMap remapping; xml.setContent(rawData); err = SceneSerializer::xml2scene(xml.documentElement(), scene, remapping); SchemaSerializer::readMeta(meta, xml.documentElement()); scene->setIterations(QList()); scene->setModified(false); meta->url = url; } else { // cause check for errors in the begin assert(false); } if(!err.isEmpty()) { setError(tr("Error while parsing file: %1").arg(err)); scene->sl_reset(); meta->reset(); return ReportResult_Finished; } scene->setModified(false); meta->url = url; return ReportResult_Finished; } }//namespace ugene-1.9.8/src/plugins/workflow_designer/src/ChooseItemDialog.h0000644000175000017500000000264011651544324023442 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_CHOOSE_DIALOG_CONTROLLER_H_ #define _U2_CHOOSE_DIALOG_CONTROLLER_H_ #include #include #include namespace U2 { class ChooseItemDialog : public QDialog, public Ui_ChooseItemDialog { Q_OBJECT public: ChooseItemDialog(QWidget* p = NULL); //virtual int select(const QList& items); virtual QString select(const QMap& items); Workflow::ActorPrototype* select(const QList& items); }; } //namespace #endif ugene-1.9.8/src/plugins/workflow_designer/src/CreateScriptWorker.h0000644000175000017500000000444511651544324024052 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_CREATE_SCRIPT_WORKER_DIALOG_H_ #define _U2_CREATE_SCRIPT_WORKER_DIALOG_H_ #include "ui/ui_CreateScriptBlockDialog.h" #include #include #include #include #include #include #include #include namespace U2 { using namespace Workflow; class CreateScriptElementDialog : public QDialog, public Ui_CreateScriptBlockDialog { Q_OBJECT public: //CreateScriptElementDialog(QWidget* p = NULL); CreateScriptElementDialog(QWidget* p = NULL, ActorPrototype* proto = NULL); QList getInput() const; QList getOutput() const; QList getAttributes() const; const QString getName() const; const QString getDescription() const; private slots: void sl_addInputClicked(); void sl_addOutputClicked(); void sl_okClicked(); void sl_cancelClicked(); void sl_addAttribute(); void sl_deleteInputClicked(); void sl_deleteOutputClicked(); void sl_deleteAttributeClicked(); void sl_getDirectory(); private: QDomDocument saveXml(); bool saveParams(); void fillFields(ActorPrototype *proto); void changeDirectoryForActors(); QList input; QList output; QList attrs; QString name; QString description; bool editing; }; } //namespace #endif ugene-1.9.8/src/plugins/workflow_designer/src/WorkflowViewController.cpp0000644000175000017500000016676311651544325025351 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "WorkflowDesignerPlugin.h" #include "WorkflowViewItems.h" #include "WorkflowDocument.h" #include "WorkflowSceneIOTasks.h" #include "WorkflowPalette.h" #include "WorkflowEditor.h" #include "WorkflowMetaDialog.h" #include "ChooseItemDialog.h" #include "SchemaConfigurationDialog.h" #include "SchemaAliasesConfigurationDialogImpl.h" #include "WorkflowSamples.h" #include "CreateScriptWorker.h" #include "library/ScriptWorker.h" #include "HRSceneSerializer.h" #include "SceneSerializer.h" #include "WorkflowViewItems.h" #include "WorkflowViewController.h" #include "library/CreateExternalProcessDialog.h" #include "library/ExternalProcessWorker.h" /* TRANSLATOR U2::LocalWorkflow::WorkflowView*/ namespace U2 { #define LAST_DIR SETTINGS + "lastdir" #define SPLITTER_STATE SETTINGS + "splitter" #define EDITOR_STATE SETTINGS + "editor" #define PALETTE_STATE SETTINGS + "palette" #define TABS_STATE SETTINGS + "tabs" enum {ElementsTab,SamplesTab}; #define WS 1000 #define MAX_FILE_SIZE 1000000 static QString percentStr = WorkflowView::tr("%"); /******************************** * PercentValidator ********************************/ class PercentValidator : public QRegExpValidator { public: PercentValidator(QObject* parent) : QRegExpValidator(QRegExp("[1-9][0-9]*"+percentStr), parent) {} void fixup(QString& input) const { if (!input.endsWith(percentStr)) { input.append(percentStr); } } }; // PercentValidator static const QString XML_SCHEMA_WARNING = WorkflowView::tr("You opened obsolete schema in XML format. It is strongly recommended" " to clear working space and create schema from scratch."); static const QString XML_SCHEMA_APOLOGIZE = WorkflowView::tr("Sorry! This schema is obsolete and cannot be opened."); /******************************** * WorkflowView ********************************/ WorkflowView::WorkflowView(WorkflowGObject* go) : MWMDIWindow(tr("Workflow Designer")), go(go), currentProc(NULL), currentActor(NULL), pasteCount(0), scriptingMode(false) { scene = new WorkflowScene(this); scene->setSceneRect(QRectF(-WS, -WS, WS, WS)); scene->setItemIndexMethod(QGraphicsScene::NoIndex); connect(scene, SIGNAL(processItemAdded()), SLOT(sl_procItemAdded())); connect(scene, SIGNAL(processDblClicked()), SLOT(sl_toggleStyle())); runMode = (RunMode)WorkflowSettings::getRunMode(); scriptingMode = WorkflowSettings::getScriptingMode(); palette = new WorkflowPalette(WorkflowEnv::getProtoRegistry()/*, this*/); palette->setSizePolicy(QSizePolicy(QSizePolicy::Preferred, QSizePolicy::Ignored)); connect(palette, SIGNAL(processSelected(Workflow::ActorPrototype*)), SLOT(sl_selectProcess(Workflow::ActorPrototype*))); connect(palette, SIGNAL(si_protoDeleted(const QString&)), SLOT(sl_protoDeleted(const QString&))); infoList = new QListWidget(this); connect(infoList, SIGNAL(itemDoubleClicked(QListWidgetItem*)), SLOT(sl_pickInfo(QListWidgetItem*))); splitter = new QSplitter(this); tabs = new QTabWidget(this); tabs->insertTab(ElementsTab, palette, tr("Elements")); SamplesWidget* samples = new SamplesWidget(scene); tabs->insertTab(SamplesTab, samples, tr("Samples")); splitter->addWidget(tabs); sceneView = new GlassView(scene); connect(samples, SIGNAL(setupGlass(GlassPane*)), sceneView, SLOT(setGlass(GlassPane*))); connect(samples, SIGNAL(sampleSelected(QString)), this, SLOT(sl_pasteSample(QString))); connect(tabs, SIGNAL(currentChanged(int)), samples, SLOT(cancelItem())); connect(tabs, SIGNAL(currentChanged(int)), palette, SLOT(resetSelection())); connect(tabs, SIGNAL(currentChanged(int)), scene, SLOT(setHint(int))); //sceneView->setResizeAnchor(QGraphicsView::AnchorViewCenter); sceneView->setAlignment(Qt::AlignCenter); infoSplitter = new QSplitter(Qt::Vertical, splitter); infoSplitter->addWidget(sceneView); { QGroupBox* w = new QGroupBox(infoSplitter); w->setFlat(true); w->setTitle(tr("Error list")); QVBoxLayout* vl = new QVBoxLayout(w); vl->setSpacing(0); vl->setMargin(0); vl->setContentsMargins(0,0,0,0); vl->addWidget(infoList); w->hide(); infoSplitter->addWidget(w); } splitter->addWidget(infoSplitter); propertyEditor = new WorkflowEditor(this); //connect(scene, SIGNAL(selectionChanged()), propertyEditor, SLOT(clearContents())); //connect(scene, SIGNAL(selectionChanged()), propertyEditor, SLOT(hide())); connect(scene, SIGNAL(selectionChanged()), SLOT(sl_editItem())); connect(scene, SIGNAL(selectionChanged()), SLOT(sl_onSelectionChanged())); splitter->addWidget(propertyEditor); Settings* settings = AppContext::getSettings(); if (settings->contains(SPLITTER_STATE)) { splitter->restoreState(settings->getValue(SPLITTER_STATE).toByteArray()); } /*if (settings->contains(EDITOR_STATE)) { propertyEditor->restoreState(settings->getValue(EDITOR_STATE)); }*/ if (settings->contains(PALETTE_STATE)) { palette->restoreState(settings->getValue(PALETTE_STATE)); } tabs->setCurrentIndex(settings->getValue(TABS_STATE, SamplesTab).toInt()); scene->views().at(0)->setDragMode(QGraphicsView::RubberBandDrag); //scene->views().at(0)->setRubberBandSelectionMode(Qt::ContainsItemShape); QHBoxLayout *layout = new QHBoxLayout; layout->addWidget(splitter); layout->setSpacing(0); layout->setMargin(0); layout->setContentsMargins(0, 0, 0, 0); setLayout(layout); createActions(); sl_changeScriptMode(); if(go) { LoadWorkflowTask::FileFormat format = LoadWorkflowTask::detectFormat(go->getSceneRawData()); go->setView(this); QString err; if(format == LoadWorkflowTask::HR) { err = HRSceneSerializer::string2Scene(go->getSceneRawData(), scene, &meta); } else if(format == LoadWorkflowTask::XML) { QDomDocument xml; QMap remapping; xml.setContent(go->getSceneRawData().toUtf8()); err = SceneSerializer::xml2scene(xml.documentElement(), scene, remapping); SchemaSerializer::readMeta(&meta, xml.documentElement()); scene->setModified(false); if(err.isEmpty()) { QMessageBox::warning(this, tr("Warning!"), XML_SCHEMA_WARNING); } else { QMessageBox::warning(this, tr("Warning!"), XML_SCHEMA_APOLOGIZE); } } else { coreLog.error(tr("Undefined workflow format for %1").arg(go->getDocument() ? go->getDocument()->getURLString() : tr("file"))); sl_newScene(); } if (!err.isEmpty()) { sl_newScene(); coreLog.error(err); } else { if (go->getDocument()) { meta.url = go->getDocument()->getURLString(); } sl_updateTitle(); propertyEditor->resetIterations(); scene->setModified(false); sl_refreshActorDocs(); } } else { sl_newScene(); } connect(scene, SIGNAL(configurationChanged()), SLOT(sl_refreshActorDocs())); connect(propertyEditor, SIGNAL(iterationSelected()), SLOT(sl_refreshActorDocs())); connect(WorkflowSettings::watcher, SIGNAL(changed()), scene, SLOT(update())); propertyEditor->reset(); } WorkflowView::~WorkflowView() { uiLog.trace("~WorkflowView"); if(AppContext::getProjectService()) { AppContext::getProjectService()->enableSaveAction(true); } WorkflowSettings::setRunMode((int)runMode); WorkflowSettings::setScriptingMode(scriptingMode); } void WorkflowView::sl_rescaleScene(const QString &scale) { int percentPos = scale.indexOf(percentStr); double newScale = scale.left(percentPos).toDouble() / 100.0; QMatrix oldMatrix = scene->views().at(0)->matrix(); scene->views().at(0)->resetMatrix(); scene->views().at(0)->translate(oldMatrix.dx(), oldMatrix.dy()); scene->views().at(0)->scale(newScale, newScale); QRectF rect = scene->sceneRect(); qreal w = rect.width()/newScale; qreal h = rect.height()/newScale; rect.setWidth(w); rect.setHeight(h); scene->setSceneRect(rect); } void WorkflowView::createActions() { runAction = new QAction(tr("&Run schema"), this); runAction->setIcon(QIcon(":workflow_designer/images/run.png")); runAction->setShortcut(QKeySequence("Ctrl+R")); connect(runAction, SIGNAL(triggered()), SLOT(sl_launch())); stopAction = new QAction(tr("S&top schema"), this); stopAction->setIcon(QIcon(":workflow_designer/images/stopTask.png")); connect(stopAction, SIGNAL(triggered()), SLOT(sl_stop())); validateAction = new QAction(tr("&Validate schema"), this); validateAction->setIcon(QIcon(":workflow_designer/images/ok.png")); validateAction->setShortcut(QKeySequence("Ctrl+E")); connect(validateAction, SIGNAL(triggered()), SLOT(sl_validate())); newAction = new QAction(tr("&New schema"), this); newAction->setIcon(QIcon(":workflow_designer/images/filenew.png")); newAction->setShortcuts(QKeySequence::New); connect(newAction, SIGNAL(triggered()), SLOT(sl_newScene())); saveAction = new QAction(tr("&Save schema"), this); saveAction->setIcon(QIcon(":workflow_designer/images/filesave.png")); saveAction->setShortcut(QKeySequence::Save); saveAction->setShortcutContext(Qt::WindowShortcut); if(AppContext::getProjectService()) { AppContext::getProjectService()->enableSaveAction(false); } connect(saveAction, SIGNAL(triggered()), SLOT(sl_saveScene())); saveAsAction = new QAction(tr("&Save schema as..."), this); saveAsAction->setIcon(QIcon(":workflow_designer/images/filesaveas.png")); connect(saveAsAction, SIGNAL(triggered()), SLOT(sl_saveSceneAs())); loadAction = new QAction(tr("&Load schema"), this); loadAction->setIcon(QIcon(":workflow_designer/images/fileopen.png")); loadAction->setShortcut(QKeySequence("Ctrl+L"));//("Ctrl+L")); connect(loadAction, SIGNAL(triggered()), SLOT(sl_loadScene())); exportAction = new QAction(tr("&Export schema"), this); exportAction->setIcon(QIcon(":workflow_designer/images/export.png")); exportAction->setShortcut(QKeySequence("Ctrl+Shift+S")); connect(exportAction, SIGNAL(triggered()), SLOT(sl_exportScene())); deleteAction = new QAction(tr("Delete"), this); deleteAction->setIcon(QIcon(":workflow_designer/images/delete.png")); deleteAction->setShortcuts(QKeySequence::Delete); connect(deleteAction, SIGNAL(triggered()), scene, SLOT(sl_deleteItem())); configureAliasesAction = new QAction(tr("Configure command line aliases..."), this); configureAliasesAction->setIcon(QIcon(":workflow_designer/images/table_relationship.png")); connect(configureAliasesAction, SIGNAL(triggered()), SLOT(sl_configureAliases())); configureIterationsAction = new QAction(tr("Configure iterations..."), this); configureIterationsAction->setIcon(QIcon(":workflow_designer/images/tag.png")); //configureIterationsAction ->setShortcut(QKeySequence::Delete); connect(configureIterationsAction , SIGNAL(triggered()), SLOT(sl_configureIterations())); selectAction = new QAction(tr("Select all elements"), this); selectAction->setShortcuts(QKeySequence::SelectAll); connect(selectAction, SIGNAL(triggered()), scene, SLOT(sl_selectAll())); copyAction = new QAction(tr("&Copy"), this); copyAction->setIcon(QIcon(":workflow_designer/images/editcopy.png")); copyAction->setShortcut(QKeySequence("Ctrl+C")); connect(copyAction, SIGNAL(triggered()), SLOT(sl_copyItems())); cutAction = new QAction(tr("Cu&t"), this); cutAction->setIcon(QIcon(":workflow_designer/images/editcut.png")); cutAction->setShortcuts(QKeySequence::Cut); connect(cutAction, SIGNAL(triggered()), SLOT(sl_cutItems())); pasteAction = new QAction(tr("&Paste"), this); pasteAction->setIcon(QIcon(":workflow_designer/images/editpaste.png")); pasteAction->setShortcuts(QKeySequence::Paste); connect(pasteAction, SIGNAL(triggered()), SLOT(sl_pasteItems())); sceneScaleCombo = new QComboBox(this); sceneScaleCombo->setEditable(true); sceneScaleCombo->setValidator(new PercentValidator(this)); QStringList scales; scales << "25%" << "50%" << "75%" << "100%" << "125%" << "150%" << "200%"; sceneScaleCombo->addItems(scales); sceneScaleCombo->setCurrentIndex(3); connect(sceneScaleCombo, SIGNAL(currentIndexChanged(const QString &)), SLOT(sl_rescaleScene(const QString &))); QAction* simpleStyle = new QAction(tr("Minimal"), this); simpleStyle->setData(QVariant(ItemStyles::SIMPLE)); connect(simpleStyle, SIGNAL(triggered()), SLOT(sl_setStyle())); QAction* extStyle = new QAction(tr("Extended"), this); extStyle->setData(QVariant(ItemStyles::EXTENDED)); connect(extStyle, SIGNAL(triggered()), SLOT(sl_setStyle())); styleActions << simpleStyle << extStyle; QAction * localHostRunMode = new QAction( tr( "Local host" ), this ); localHostRunMode->setCheckable( true ); localHostRunMode->setChecked( LOCAL_HOST == runMode ); connect( localHostRunMode, SIGNAL( triggered() ), SLOT( sl_setRunMode() ) ); QAction * remoteMachineRunMode = new QAction( tr( "Remote machine" ), this ); remoteMachineRunMode->setCheckable( true ); remoteMachineRunMode->setChecked( REMOTE_MACHINE == runMode ); connect( remoteMachineRunMode, SIGNAL( triggered() ), SLOT( sl_setRunMode() ) ); runModeActions << localHostRunMode << remoteMachineRunMode; QAction * notShowScriptAction = new QAction( tr( "Hide scripting options" ), this ); notShowScriptAction->setCheckable( true ); connect( notShowScriptAction, SIGNAL( triggered() ), SLOT( sl_changeScriptMode() ) ); notShowScriptAction->setChecked(!scriptingMode); QAction * showScriptAction = new QAction( tr( "Show scripting options" ), this ); showScriptAction->setCheckable( true ); connect( showScriptAction, SIGNAL( triggered() ), SLOT( sl_changeScriptMode() ) ); showScriptAction->setChecked(scriptingMode); scriptingActions << notShowScriptAction << showScriptAction; unlockAction = new QAction(tr("Unlock Scene"), this); unlockAction->setCheckable(true); unlockAction->setChecked(true); connect(unlockAction, SIGNAL(toggled(bool)), SLOT(sl_toggleLock(bool))); createScriptAcction = new QAction(tr("Create element with script..."), this); createScriptAcction->setIcon(QIcon(":workflow_designer/images/script.png")); connect(createScriptAcction, SIGNAL(triggered()), SLOT(sl_createScript())); editScriptAction = new QAction(tr("Edit script of the element..."),this); editScriptAction->setIcon(QIcon(":workflow_designer/images/script_edit.png")); editScriptAction->setEnabled(false); // because user need to select actor with script to enable it connect(editScriptAction, SIGNAL(triggered()), SLOT(sl_editScript())); externalToolAction = new QAction(tr("Create element with command line tool..."), this); externalToolAction->setIcon(QIcon(":workflow_designer/images/external_cmd_tool.png")); connect(externalToolAction, SIGNAL(triggered()), SLOT(sl_externalAction())); appendExternalTool = new QAction(tr("Add element with command line tool..."), this); appendExternalTool->setIcon(QIcon(":workflow_designer/images/external_cmd_tool_add.png")); connect(appendExternalTool, SIGNAL(triggered()), SLOT(sl_appendExternalToolWorker())); } void WorkflowView::sl_createScript() { CreateScriptElementDialog dlg(this); if(dlg.exec() == QDialog::Accepted) { QList input = dlg.getInput(); QList output = dlg.getOutput(); QList attrs = dlg.getAttributes(); QString name = dlg.getName(); QString desc = dlg.getDescription(); if(LocalWorkflow::ScriptWorkerFactory::init(input, output, attrs, name,desc)) { ActorPrototype *proto = WorkflowEnv::getProtoRegistry()->getProto(LocalWorkflow::ScriptWorkerFactory::ACTOR_ID + name); QRectF rect = scene->sceneRect(); scene->addProcess( scene->createActor( proto, QVariantMap()), rect.center()); } } } void WorkflowView::sl_externalAction() { CreateExternalProcessDialog dlg(this); if(dlg.exec() == QDialog::Accepted) { ExternalProcessConfig *cfg = dlg.config(); if(LocalWorkflow::ExternalProcessWorkerFactory::init(cfg)) { ActorPrototype *proto = WorkflowEnv::getProtoRegistry()->getProto(cfg->name); QRectF rect = scene->sceneRect(); scene->addProcess( scene->createActor( proto, QVariantMap()), rect.center()); } } } void WorkflowView::sl_appendExternalToolWorker() { QString filter = DialogUtils::prepareFileFilter(WorkflowUtils::tr("UGENE workflow element"), QStringList() << "etc", true); QString url = QFileDialog::getOpenFileName(this, tr("Add element"), QString(), filter); if (!url.isEmpty()) { IOAdapter *io = AppContext::getIOAdapterRegistry()->getIOAdapterFactoryById(BaseIOAdapters::url2io(GUrl(url)))->createIOAdapter(); if(!io->open(url, IOAdapterMode_Read)) { coreLog.error(tr("Can't load element.")); return; } QByteArray data; data.resize(MAX_FILE_SIZE); data.fill(0); io->readBlock(data.data(), MAX_FILE_SIZE); //file.open(QIODevice::ReadOnly); //QString data = file.readAll().data(); ExternalProcessConfig *cfg = NULL; cfg = HRSchemaSerializer::string2Actor(data.data()); if(cfg) { if(WorkflowEnv::getProtoRegistry()->getProto(cfg->name)) { coreLog.error("Element with this name already exists"); } else { LocalWorkflow::ExternalProcessWorkerFactory::init(cfg); ActorPrototype *proto = WorkflowEnv::getProtoRegistry()->getProto(cfg->name); QRectF rect = scene->sceneRect(); scene->addProcess( scene->createActor( proto, QVariantMap()), rect.center()); } } else { coreLog.error(tr("Can't load element.")); } io->close(); } } void WorkflowView::sl_editScript() { QList selectedActors = scene->getSelectedProcItems(); if(selectedActors.size() == 1) { Actor *scriptActor = selectedActors.first(); AttributeScript *script = scriptActor->getScript(); if(script!= NULL) { ScriptEditorDialog scriptDlg(this,AttributeScriptDelegate::createScriptHeader(*script), script->getScriptText()); if(scriptDlg.exec() == QDialog::Accepted) { script->setScriptText(scriptDlg.getScriptText()); scriptActor->setScript(script); } } } } void WorkflowView::sl_protoDeleted(const QString &id) { QList deleteList; foreach(QGraphicsItem *i, scene->items()) { if(i->type() == WorkflowProcessItemType) { WorkflowProcessItem *wItem = static_cast(i); if(wItem->getProcess()->getProto()->getId() == id) { deleteList << wItem; } } } foreach(WorkflowProcessItem *item, deleteList) { scene->removeItem(item); delete item; scene->update(); } } void WorkflowView::sl_toggleLock(bool b) { if (sender() != unlockAction) { unlockAction->setChecked(b); return; } if (b) { scene->setRunner(NULL); } deleteAction->setEnabled(b); selectAction->setEnabled(b); copyAction->setEnabled(b); pasteAction->setEnabled(b); cutAction->setEnabled(b); loadAction->setEnabled(b); //newAction->setEnabled(b); configureIterationsAction->setEnabled(b); runAction->setEnabled(b); validateAction->setEnabled(b); configureAliasesAction->setEnabled(b); propertyEditor->setEnabled(b); palette->setEnabled(b); scene->setLocked(!b); scene->update(); } void WorkflowView::sl_setStyle() { StyleId s = qobject_cast(sender())->data().value(); QList lst = scene->selectedItems(); if (lst.isEmpty()) { lst = scene->items(); } foreach(QGraphicsItem* it, lst) { switch (it->type()) { case WorkflowProcessItemType: case WorkflowPortItemType: case WorkflowBusItemType: (static_cast(it))->setStyle(s); } } scene->update(); //update(); } // FIXME: move to utils classes static void removeUrlLocationParameter( Actor * actor ) { assert( NULL != actor ); Attribute * attr = actor->getParameter( BaseAttributes::URL_LOCATION_ATTRIBUTE().getId() ); if( NULL != attr ) { Attribute * removed = actor->removeParameter( BaseAttributes::URL_LOCATION_ATTRIBUTE().getId() ); assert( attr == removed ); Q_UNUSED(removed); delete attr; delete actor->getEditor()->removeDelegate( BaseAttributes::URL_LOCATION_ATTRIBUTE().getId() ); } URLDelegate * urlDelegate = qobject_cast( actor->getEditor()->getDelegate( BaseAttributes::URL_IN_ATTRIBUTE().getId() ) ); if( NULL != urlDelegate ) { urlDelegate->sl_showEditorButton( true ); } } // FIXME: move to utils classes static void addUrlLocationParameter( Actor * actor ) { assert( NULL != actor ); Attribute * urlAttr = actor->getParameter( BaseAttributes::URL_IN_ATTRIBUTE().getId() ); Attribute * urlLocationAttr = actor->getParameter( BaseAttributes::URL_LOCATION_ATTRIBUTE().getId() ); if( NULL != urlAttr && NULL == urlLocationAttr ) { actor->addParameter( BaseAttributes::URL_LOCATION_ATTRIBUTE().getId(), new Attribute( BaseAttributes::URL_LOCATION_ATTRIBUTE(), BaseTypes::BOOL_TYPE(), false, true ) ); SchemaRunModeDelegate * runModeDelegate = new SchemaRunModeDelegate(); URLDelegate * urlDelegate = qobject_cast ( actor->getEditor()->getDelegate( BaseAttributes::URL_IN_ATTRIBUTE().getId() ) ); QObject::connect( runModeDelegate, SIGNAL( si_showOpenFileButton( bool ) ), urlDelegate, SLOT( sl_showEditorButton( bool ) ) ); actor->getEditor()->addDelegate( runModeDelegate, BaseAttributes::URL_LOCATION_ATTRIBUTE().getId() ); } } void WorkflowView::sl_setRunMode() { QAction * a = qobject_cast( sender() ); if( runModeActions[0] == a ) { // local host run mode runMode = LOCAL_HOST; } else if( runModeActions[1] == a ) { // remote machine run mode runMode = REMOTE_MACHINE; } else { // no sender. smbdy called it like a function } runModeActions[0]->setChecked( LOCAL_HOST == runMode ); runModeActions[1]->setChecked( REMOTE_MACHINE == runMode ); // change actors that are on pallete now QList actorsOnBoard = scene->getAllProcs(); foreach( Actor * actor, actorsOnBoard ) { switch( runMode ) { case LOCAL_HOST: removeUrlLocationParameter(actor); break; case REMOTE_MACHINE: addUrlLocationParameter(actor); break; default: assert(false); } } scene->sl_deselectAll(); } void WorkflowView::sl_changeScriptMode() { QAction *a = qobject_cast(sender()); if(a != NULL) { if(a == scriptingActions[0]){ scriptingMode = false; } else if(a == scriptingActions[1]) { scriptingMode = true; } } // else invoked from constructor scriptingActions[0]->setChecked(!scriptingMode); scriptingActions[1]->setChecked(scriptingMode); propertyEditor->changeScriptMode(scriptingMode); } void WorkflowView::sl_toggleStyle() { foreach(QGraphicsItem* it, scene->selectedItems()) { StyleId s = (static_cast(it))->getStyle(); if (s == ItemStyles::SIMPLE) { s = ItemStyles::EXTENDED; } else { s = ItemStyles::SIMPLE; } (static_cast(it))->setStyle(s); } scene->update(); } void WorkflowView::sl_refreshActorDocs() { foreach(QGraphicsItem* it, scene->items()) { if (it->type() == WorkflowProcessItemType) { Actor* a = qgraphicsitem_cast(it)->getProcess(); a->getDescription()->update(propertyEditor->getCurrentIteration().getParameters(a->getId())); } } } void WorkflowView::setupMDIToolbar(QToolBar* tb) { tb->addAction(newAction); tb->addAction(loadAction); tb->addAction(saveAction); tb->addAction(saveAsAction); tb->addSeparator(); tb->addAction(validateAction); tb->addAction(runAction); tb->addAction(stopAction); tb->addAction(configureAliasesAction); tb->addAction(configureIterationsAction); tb->addSeparator(); tb->addAction(createScriptAcction); tb->addAction(editScriptAction); tb->addSeparator(); tb->addAction(externalToolAction); tb->addAction(appendExternalTool); tb->addSeparator(); tb->addAction(copyAction); tb->addAction(pasteAction); pasteAction->setEnabled(!lastPaste.isEmpty()); tb->addAction(cutAction); tb->addAction(deleteAction); tb->addSeparator(); tb->addWidget(sceneScaleCombo); tb->addSeparator(); QToolButton* tt = new QToolButton(tb); QMenu* ttMenu = new QMenu(tr("Element style"), this); foreach(QAction* a, styleActions) { ttMenu->addAction(a); } tt->setDefaultAction(ttMenu->menuAction()); tt->setPopupMode(QToolButton::InstantPopup); tb->addWidget(tt); QToolButton * runModeToolButton = new QToolButton(tb); QMenu * runModeMenu = new QMenu( tr( "Run mode" ), this ); foreach( QAction * a, runModeActions ) { runModeMenu->addAction( a ); } runModeToolButton->setDefaultAction( runModeMenu->menuAction() ); runModeToolButton->setPopupMode( QToolButton::InstantPopup ); tb->addWidget( runModeToolButton ); QToolButton * scriptingMode = new QToolButton(tb); QMenu * scriptingModeMenu = new QMenu( tr( "Scripting mode" ), this ); foreach( QAction * a, scriptingActions ) { scriptingModeMenu->addAction( a ); } scriptingMode->setDefaultAction( scriptingModeMenu->menuAction() ); scriptingMode->setPopupMode( QToolButton::InstantPopup ); tb->addWidget( scriptingMode ); } void WorkflowView::setupViewMenu(QMenu* m) { m->addMenu(palette->createMenu(tr("Add element"))); m->addAction(copyAction); m->addAction(pasteAction); pasteAction->setEnabled(!lastPaste.isEmpty()); m->addAction(cutAction); m->addAction(deleteAction); m->addAction(selectAction); m->addSeparator(); m->addSeparator(); m->addAction(newAction); m->addAction(loadAction); m->addAction(saveAction); m->addAction(saveAsAction); m->addAction(exportAction); m->addSeparator(); m->addAction(validateAction); m->addAction(runAction); m->addAction(stopAction); m->addAction(configureAliasesAction); m->addAction(configureIterationsAction); m->addSeparator(); m->addAction(createScriptAcction); m->addAction(editScriptAction); m->addSeparator(); m->addAction(externalToolAction); m->addAction(appendExternalTool); m->addSeparator(); QMenu* ttMenu = new QMenu(tr("Element style")); foreach(QAction* a, styleActions) { ttMenu->addAction(a); } m->addMenu(ttMenu); QMenu * runModeMenu = new QMenu( tr( "Run mode" ) ); foreach( QAction * a, runModeActions ) { runModeMenu->addAction( a ); } m->addMenu( runModeMenu ); QMenu* scriptMenu = new QMenu(tr("Scripting mode")); foreach(QAction* a, scriptingActions) { scriptMenu->addAction(a); } m->addMenu(scriptMenu); if (!unlockAction->isChecked()) { m->addSeparator(); m->addAction(unlockAction); } m->addSeparator(); } void WorkflowView::setupContextMenu(QMenu* m) { if (!unlockAction->isChecked()) { m->addAction(unlockAction); return; } //if(!QApplication::clipboard()->text().isEmpty()) { if(!lastPaste.isEmpty()) { m->addAction(pasteAction); } QList sel = scene->selectedItems(); if (!sel.isEmpty()) { if(!((sel.size() == 1 && sel.first()->type() == WorkflowBusItemType) || sel.first()->type() == WorkflowPortItemType)) { m->addAction(copyAction); m->addAction(cutAction); } if(!(sel.size() == 1 && sel.first()->type() == WorkflowPortItemType)) { m->addAction(deleteAction); } m->addSeparator(); if (sel.size() == 1 && sel.first()->type() == WorkflowProcessItemType) { WorkflowProcessItem* wit = qgraphicsitem_cast(sel.first()); Actor *scriptActor = wit->getProcess(); AttributeScript *script = scriptActor->getScript(); if(script) { m->addAction(editScriptAction); } m->addSeparator(); QMenu* itMenu = new QMenu(tr("Element properties")); foreach(QAction* a, wit->getContextMenuActions()) { itMenu->addAction(a); } m->addMenu(itMenu); } if(!(sel.size() == 1 && (sel.first()->type() == WorkflowBusItemType || sel.first()->type() == WorkflowPortItemType))) { QMenu* ttMenu = new QMenu(tr("Element style")); foreach(QAction* a, styleActions) { ttMenu->addAction(a); } m->addMenu(ttMenu); } } m->addSeparator(); QMenu * runModeMenu = new QMenu( tr( "Run mode" ) ); foreach( QAction * a, runModeActions ) { runModeMenu->addAction( a ); } m->addMenu( runModeMenu ); m->addSeparator(); m->addAction(selectAction); m->addMenu(palette->createMenu(tr("Add element"))); } void WorkflowView::sl_pickInfo(QListWidgetItem* info) { ActorId id = info->data(ACTOR_REF).value(); foreach(QGraphicsItem* it, scene->items()) { if (it->type() == WorkflowProcessItemType) { WorkflowProcessItem* proc = static_cast(it); if (proc->getProcess()->getId() != id) { continue; } scene->clearSelection(); QString pid = info->data(PORT_REF).toString(); WorkflowPortItem* port = proc->getPort(pid); if (port) { port->setSelected(true); } else { proc->setSelected(true); int itid = info->data(ITERATION_REF).toInt(); propertyEditor->selectIteration(itid); } return; } } } bool WorkflowView::sl_validate(bool notify) { if( scene->getSchema().getProcesses().isEmpty() ) { QMessageBox::warning(this, tr("Empty schema!"), tr("Nothing to run: empty workflow schema")); return false; } propertyEditor->commit(); infoList->clear(); QList lst; bool good = WorkflowUtils::validate(scene->getSchema(), &lst); if (lst.count() != 0) { foreach(QListWidgetItem* wi, lst) { infoList->addItem(wi); } infoList->parentWidget()->show(); QList s = infoSplitter->sizes(); if (s.last() == 0) { s.last() = qMin(infoList->sizeHint().height(), 300); infoSplitter->setSizes(s); } } else { infoList->parentWidget()->hide(); } if (!good) { QMessageBox::warning(this, tr("Schema cannot be executed"), tr("Please fix issues listed in the error list (located under schema).")); } else { if (notify) { QMessageBox::information(this, tr("Schema is valid"), tr("Schema is valid.\nWell done!")); } } return good; } void WorkflowView::localHostLaunch() { if (!sl_validate(false)) { return; } Schema sh = scene->getSchema(); if (sh.getDomain().isEmpty()) { //|TODO user choice sh.setDomain(WorkflowEnv::getDomainRegistry()->getAllIds().value(0)); } WorkflowAbstractRunner * t = NULL; #ifndef RUN_WORKFLOW_IN_THREADS if(WorkflowSettings::runInSeparateProcess() && !WorkflowSettings::getCmdlineUgenePath().isEmpty()) { t = new WorkflowRunInProcessTask(sh, scene->getIterations()); } else { t = new WorkflowRunTask(sh, scene->getIterations()); } #else t = new WorkflowRunTask(sh, scene->getIterations()); #endif // RUN_WORKFLOW_IN_THREADS t->setReportingEnabled(true); if (WorkflowSettings::monitorRun()) { unlockAction->setChecked(false); scene->setRunner(t); connect(t, SIGNAL(si_ticked()), scene, SLOT(update())); connect(new TaskSignalMapper(t), SIGNAL(si_taskFinished(Task*)), SLOT(sl_toggleLock())); } AppContext::getTaskScheduler()->registerTopLevelTask(t); } void WorkflowView::remoteLaunch() { if( !sl_validate(false) ) { return; } Schema sh = scene->getSchema(); if( sh.getDomain().isEmpty() ) { sh.setDomain(WorkflowEnv::getDomainRegistry()->getAllIds().value( 0 )); } RemoteMachineMonitor * rmm = AppContext::getRemoteMachineMonitor(); assert( NULL != rmm ); RemoteMachineSettings *settings = RemoteMachineMonitorDialogController::selectRemoteMachine(rmm, true); if (!settings) { return; } assert(settings->getMachineType() == RemoteMachineType_RemoteService); AppContext::getTaskScheduler()->registerTopLevelTask( new RemoteWorkflowRunTask( settings, sh, scene->getIterations() ) ); } void WorkflowView::sl_launch() { switch( runMode ) { case LOCAL_HOST: localHostLaunch(); break; case REMOTE_MACHINE: remoteLaunch(); break; default: assert( false ); } } void WorkflowView::sl_stop() { Task *runningWorkflow = scene->getRunner(); if(runningWorkflow) { runningWorkflow->cancel(); } } void WorkflowView::sl_configureIterations() { propertyEditor->commit(); SchemaConfigurationDialog d(scene->getSchema(), scene->getIterations(), this); int ret = d.exec(); if (d.hasModifications()) { scene->setIterations(d.getIterations()); propertyEditor->resetIterations(); } if (QDialog::Accepted == ret) { sl_launch(); } } static Actor* findActorById( const Schema & sc, const ActorId & id ) { Actor * ret = NULL; foreach( Actor * a, sc.getProcesses() ) { assert( a != NULL ); if( id == a->getId() ) { return a; } } return ret; } void WorkflowView::sl_configureAliases() { SchemaAliasesConfigurationDialogImpl dlg( scene->getSchema(), this ); int ret = QDialog::Accepted; do { ret = dlg.exec(); if( ret == QDialog::Accepted ) { if( !dlg.validateModel() ) { QMessageBox::critical( this, tr("Bad input!"), tr("Aliases for schema parameters should be different!") ); continue; } // clear aliases before inserting new foreach(Actor * actor, scene->getSchema().getProcesses()) { actor->getParamAliases().clear(); } SchemaAliasesCfgDlgModel model = dlg.getModel(); foreach(const ActorId & id, model.aliases.keys()) { foreach(const Descriptor & d, model.aliases.value(id).keys()) { Actor * actor = findActorById(scene->getSchema(), id); assert(actor != NULL); QString alias = model.aliases.value(id).value(d); assert(!alias.isEmpty()); actor->getParamAliases().insert(d.getId(), alias); QString help = model.help.value(id).value(d); if( !help.isEmpty() ) { actor->getAliasHelp().insert(alias, help); } } } break; } else if( ret == QDialog::Rejected ) { break; } else { assert(false); } } while( ret == QDialog::Accepted ); } void WorkflowView::sl_selectProcess(Workflow::ActorPrototype* p) { propertyEditor->setEditable(!p); scene->clearSelection(); currentProc = p; propertyEditor->reset(); if (!p) { scene->views().at(0)->unsetCursor(); propertyEditor->changeScriptMode(scriptingMode); } else { delete currentActor; currentActor = NULL; currentActor = scene->createActor(p); propertyEditor->editActor(currentActor); propertyEditor->setDescriptor(p, tr("Drag the palette element to the scene or just click on the scene to add the element.")); scene->views().at(0)->setCursor(Qt::CrossCursor); } } void WorkflowView::sl_copyItems() { QList items = scene->selectedItems(); if (items.isEmpty()) { return; } QList lst; foreach(const Iteration& it, scene->getIterations()) { Iteration copy(it); foreach(QGraphicsItem* item, items) { WorkflowProcessItem* proc = qgraphicsitem_cast(item); if (proc && it.cfg.contains(proc->getProcess()->getId())) { copy.cfg.insert(proc->getProcess()->getId(), it.cfg.value(proc->getProcess()->getId())); } } if (!copy.cfg.isEmpty()) { lst.append(copy); } } lastPaste = HRSceneSerializer::items2String(items, lst); pasteAction->setEnabled(true); QApplication::clipboard()->setText(lastPaste); pasteCount = 0; } void WorkflowView::sl_cutItems() { sl_copyItems(); scene->sl_deleteItem(); } void WorkflowView::sl_pasteSample(const QString& s) { tabs->setCurrentIndex(ElementsTab); if (scene->items().isEmpty()) { // fixing bug with pasting same schema 2 times lastPaste.clear(); sl_pasteItems(s); HRSceneSerializer::string2Scene(s, NULL, &meta); sl_setRunMode(); sl_updateTitle(); } else { scene->clearScene(); propertyEditor->resetIterations(); sl_pasteSample(s); } } void WorkflowView::sl_pasteItems(const QString& s) { QString tmp = s.isNull() ? QApplication::clipboard()->text() : s; if (tmp == lastPaste) { ++pasteCount; } else { pasteCount = 0; lastPaste = tmp; } QByteArray lpt = lastPaste.toAscii(); DocumentFormat* wf = AppContext::getDocumentFormatRegistry()->getFormatById(WorkflowDocFormat::FORMAT_ID); if (wf->checkRawData(lpt).score != FormatDetection_Matched) { return; } scene->clearSelection(); QList oldIterations = scene->getIterations(); scene->setIterations(QList()); QString msg = HRSceneSerializer::string2Scene(lastPaste, scene, NULL, true, true); if (!msg.isEmpty()) { uiLog.error("Paste issues: " + msg); } // merge iteration data QList iterations = scene->getIterations(); scene->setIterations(oldIterations); if (!iterations.isEmpty()) { QList current = scene->getIterations(); if(current.isEmpty()) { current = iterations; } if (iterations.size() == 1 || current.size() == 1) { // one-to-many mapping Iteration& it = iterations.size() == 1 ? iterations[0] : current[0]; QList& target = iterations.size() == 1 ? current : iterations; for (int i = 0; i < target.size(); i++) { target[i].cfg.unite(it.cfg); //unite is safe as no actor ids can coincide } scene->setIterations(target); } else { // many-to-many foreach(const Iteration& pasted, iterations) { bool gotIt = false; for (int i = 0; i < current.size(); i++) { Iteration& it = current[i]; if (it.name == pasted.name && it.id == pasted.id) { it.cfg.unite(pasted.cfg); gotIt = true; break; } } if (!gotIt) { current.append(pasted); } } scene->setIterations(current); } propertyEditor->resetIterations(); } int shift = GRID_STEP*(pasteCount); foreach(QGraphicsItem * it, scene->selectedItems()) { it->moveBy(shift, shift); } } void WorkflowView::sl_procItemAdded() { currentActor = NULL; propertyEditor->setEditable(true); if (!currentProc) { return; } uiLog.trace(currentProc->getDisplayName() + " added"); palette->resetSelection(); currentProc = NULL; assert(scene->views().size() == 1); scene->views().at(0)->unsetCursor(); } void WorkflowView::sl_showEditor() { propertyEditor->show(); QList s = splitter->sizes(); if (s.last() == 0) { s.last() = propertyEditor->sizeHint().width(); splitter->setSizes(s); } } void WorkflowView::sl_editItem() { QList list = scene->selectedItems(); if (list.size() == 1) { QGraphicsItem* it = list.at(0); if (it->type() == WorkflowProcessItemType) { propertyEditor->editActor(qgraphicsitem_cast(it)->getProcess()); return; } Port* p = NULL; if (it->type() == WorkflowBusItemType) { p = qgraphicsitem_cast(it)->getInPort()->getPort(); } else if (it->type() == WorkflowPortItemType) { p = qgraphicsitem_cast(it)->getPort(); } if (p) { if (qobject_cast(p)) { BusPortEditor* ed = new BusPortEditor(qobject_cast(p)); ed->setParent(p); p->setEditor(ed); } } propertyEditor->editPort(p); } else { propertyEditor->reset(); } } void WorkflowView::sl_onSelectionChanged() { QList actorsSelected = scene->getSelectedProcItems(); editScriptAction->setEnabled(actorsSelected.size() == 1 && actorsSelected.first()->getScript() != NULL); } void WorkflowView::sl_exportScene() { propertyEditor->commit(); ExportImageDialog dialog(sceneView->viewport(),sceneView->viewport()->rect(),true,true); dialog.exec(); } void WorkflowView::sl_saveScene() { if (meta.url.isEmpty()) { WorkflowMetaDialog md(this, meta); int rc = md.exec(); if (rc != QDialog::Accepted) { return; } meta = md.meta; sl_updateTitle(); } propertyEditor->commit(); Task* t = new SaveWorkflowSceneTask(scene, meta); AppContext::getTaskScheduler()->registerTopLevelTask(t); } void WorkflowView::sl_saveSceneAs() { WorkflowMetaDialog md(this, meta); int rc = md.exec(); if (rc != QDialog::Accepted) { return; } propertyEditor->commit(); meta = md.meta; Task* t = new SaveWorkflowSceneTask(scene, meta); AppContext::getTaskScheduler()->registerTopLevelTask(t); sl_updateTitle(); } void WorkflowView::sl_loadScene() { if (!confirmModified()) { return; } QString dir = AppContext::getSettings()->getValue(LAST_DIR, QString("")).toString(); QString filter = DesignerUtils::getSchemaFileFilter(true, true); QString url = QFileDialog::getOpenFileName(0, tr("Open workflow schema file"), dir, filter); if (!url.isEmpty()) { AppContext::getSettings()->setValue(LAST_DIR, QFileInfo(url).absoluteDir().absolutePath()); Task* t = new LoadWorkflowSceneTask(scene, &meta, url); //FIXME unsynchronized meta usage TaskSignalMapper* m = new TaskSignalMapper(t); connect(m, SIGNAL(si_taskFinished(Task*)), SLOT(sl_updateTitle())); connect(m, SIGNAL(si_taskFinished(Task*)), scene, SLOT(centerView())); connect(m, SIGNAL(si_taskFinished(Task*)), propertyEditor, SLOT(resetIterations())); if(LoadWorkflowTask::detectFormat(BaseIOAdapters::readFileHeader(url)) == LoadWorkflowTask::XML) { connect(m, SIGNAL(si_taskFinished(Task*)), SLOT(sl_xmlSchemaLoaded(Task*))); } AppContext::getTaskScheduler()->registerTopLevelTask(t); } } void WorkflowView::sl_xmlSchemaLoaded(Task* t) { assert(t != NULL); if(!t->hasError()) { QMessageBox::warning(this, tr("Warning!"), XML_SCHEMA_WARNING); } else { QMessageBox::warning(this, tr("Warning!"), XML_SCHEMA_APOLOGIZE); } } void WorkflowView::sl_newScene() { if (!confirmModified()) { return; } infoList->parentWidget()->hide(); scene->sl_reset(); meta.reset(); meta.name = tr("New schema"); sl_updateTitle(); propertyEditor->resetIterations(); scene->setModified(false); scene->update(); } void WorkflowView::sl_updateTitle() { setWindowTitle(tr("Workflow Designer - %1").arg(meta.name)); } void WorkflowView::saveState() { AppContext::getSettings()->setValue(SPLITTER_STATE, splitter->saveState()); AppContext::getSettings()->setValue(EDITOR_STATE, propertyEditor->saveState()); AppContext::getSettings()->setValue(PALETTE_STATE, palette->saveState()); AppContext::getSettings()->setValue(TABS_STATE, tabs->currentIndex()); } bool WorkflowView::onCloseEvent() { saveState(); if (!confirmModified()) { return false; } if (go) { go->setView(NULL); } return true; } bool WorkflowView::confirmModified() { propertyEditor->commit(); if (scene->isModified() && !scene->items().isEmpty()) { AppContext::getMainWindow()->getMDIManager()->activateWindow(this); int ret = QMessageBox::question(this, tr("Workflow Designer"), tr("The schema has been modified.\n" "Do you want to save changes?"), QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel, QMessageBox::Save); if (QMessageBox::Cancel == ret) { return false; } else if (QMessageBox::Discard == ret) { //scene->setModified(false); } else { sl_saveScene(); } } return true; } /******************************** * WorkflowScene ********************************/ static bool canDrop(const QMimeData* m, QList& lst) { if (m->hasFormat(WorkflowPalette::MIME_TYPE)) { QString id(m->data(WorkflowPalette::MIME_TYPE)); ActorPrototype* proto = WorkflowEnv::getProtoRegistry()->getProto(id); if (proto) { lst << proto; } } else { foreach(QList l, WorkflowEnv::getProtoRegistry()->getProtos().values()) { foreach(ActorPrototype* proto, l) { if (proto->isAcceptableDrop(m)) { lst << proto; } } } } //foreach(ActorPrototype* a, lst) {log.debug("drop acceptable: " + a->getId());} return !lst.isEmpty(); } WorkflowScene::WorkflowScene(WorkflowView *parent) : QGraphicsScene(parent), controller(parent), modified(false), locked(false), runner(NULL), hint(0){ } WorkflowScene::~WorkflowScene() { sl_reset(); } Schema WorkflowScene::getSchema() const { Schema schema; foreach(QGraphicsItem* it, items()) { if (it->type() == WorkflowProcessItemType) { schema.addProcess((static_cast(it))->getProcess()); } else if (it->type() == WorkflowBusItemType) { schema.addFlow((static_cast(it))->getBus()); } } schema.getIterations() = iterations; return schema; } void WorkflowScene::sl_deleteItem() { assert(!locked); QList ids; QList items; foreach(QGraphicsItem* it, selectedItems()) { switch (it->type()) { case WorkflowProcessItemType: ids << qgraphicsitem_cast(it)->getProcess()->getId(); items << it; } } modified |= !items.isEmpty(); foreach(QGraphicsItem* it, items) { removeItem(it); delete it; } foreach(QGraphicsItem* it, selectedItems()) { switch (it->type()) { case WorkflowBusItemType: removeItem(it); delete it; modified = true; break; } } bool cfgModified = false; for (int i = 0; ipropertyEditor->resetIterations(); emit configurationChanged(); } update(); } QList WorkflowScene::getSelectedProcItems() const { QList list; foreach (QGraphicsItem *item, selectedItems()) { if (item->type() == WorkflowProcessItemType) { list << static_cast(item)->getProcess(); } } return list; } QList WorkflowScene::getAllProcs() const { QList res; foreach( QGraphicsItem * item, items() ) { assert( NULL != item ); if (item->type() == WorkflowProcessItemType) { res << static_cast(item)->getProcess(); } } return res; } void WorkflowScene::contextMenuEvent(QGraphicsSceneContextMenuEvent * e) { QMenu menu; controller->setupContextMenu(&menu); e->accept(); menu.exec(e->screenPos()); } void WorkflowScene::mouseDoubleClickEvent(QGraphicsSceneMouseEvent * mouseEvent) { if (!mouseEvent->isAccepted() && (mouseEvent->button() == Qt::LeftButton) && !selectedItems().isEmpty()) { emit processDblClicked(); } QGraphicsScene::mousePressEvent(mouseEvent); } void WorkflowScene::dragEnterEvent(QGraphicsSceneDragDropEvent * event) { QList lst; if (!locked && canDrop(event->mimeData(), lst)) { event->acceptProposedAction(); } else { QGraphicsScene::dragEnterEvent(event); } } void WorkflowScene::dragMoveEvent(QGraphicsSceneDragDropEvent * event) { QList lst; if (!locked && canDrop(event->mimeData(), lst)) { event->acceptProposedAction(); } else { QGraphicsScene::dragMoveEvent(event); } } void WorkflowScene::dropEvent(QGraphicsSceneDragDropEvent * event) { QList lst; if (!locked && canDrop(event->mimeData(), lst)) { QList targets = items(event->scenePos()); bool done = false; foreach(QGraphicsItem* it, targets) { WorkflowProcessItem* target = qgraphicsitem_cast(it); if (target && lst.contains(target->getProcess()->getProto())) { clearSelection(); QVariantMap params; Actor* a = target->getProcess(); a->getProto()->isAcceptableDrop(event->mimeData(), ¶ms); QMapIterator cfg(params); while (cfg.hasNext()) { cfg.next(); a->setParameter(cfg.key(),cfg.value()); } target->setSelected(true); done = true; break; } } if (!done) { ActorPrototype* proto = lst.size() > 1 ? ChooseItemDialog(controller).select(lst) : lst.first(); if (proto) { QVariantMap params; //proto->isAcceptableDrop(event->mimeData(), ¶ms); Actor* a = controller->getActor(); if (a) { addProcess( a, event->scenePos()); } event->setDropAction(Qt::CopyAction); } } } QGraphicsScene::dropEvent(event); } void WorkflowScene::addProcess(Actor* proc, const QPointF& pos) { WorkflowProcessItem* it = new WorkflowProcessItem(proc); it->setPos(pos); addItem(it); modified = true; emit processItemAdded(); update(); } void WorkflowScene::clearScene() { QList deleteList; foreach(QGraphicsItem *i, items()) { if(i->type() == WorkflowProcessItemType) { WorkflowProcessItem *wItem = static_cast(i); deleteList << wItem; } } foreach(WorkflowProcessItem *item, deleteList) { removeItem(item); } iterations.clear(); } static QString newActorName(ActorPrototype * proto, const QList & procs) { assert(proto != NULL); QString name = proto->getDisplayName(); QList thisProcs; foreach(Actor * actor, procs) { if(actor->getProto()->getId() == proto->getId()) { thisProcs << actor; } } if(thisProcs.isEmpty()) { return name; } int number = thisProcs.size() + 1; foreach(Actor * actor, thisProcs) { QStringList list = actor->getLabel().split(QRegExp("\\s")); if(!list.isEmpty()) { bool ok = false; int num = list.last().toInt(&ok); if(ok) { number = qMax(number, num + 1); } } } return name + QString(" %1").arg(number); } Actor * WorkflowScene::createActor( ActorPrototype * proto, const QVariantMap & params ) { assert( NULL != proto ); Actor * actor = proto->createInstance( NULL, params ); assert( NULL != actor ); actor->setLabel(newActorName(proto, getAllProcs())); if( WorkflowView::REMOTE_MACHINE == controller->runMode ) { addUrlLocationParameter( actor ); } return actor; } void WorkflowScene::mousePressEvent(QGraphicsSceneMouseEvent *mouseEvent) { if (!locked && !mouseEvent->isAccepted() && controller->selectedProto() && (mouseEvent->button() == Qt::LeftButton)) { addProcess( controller->getActor(), mouseEvent->scenePos()); } QGraphicsScene::mousePressEvent(mouseEvent); } void WorkflowScene::mouseMoveEvent(QGraphicsSceneMouseEvent *mouseEvent) { QGraphicsScene::mouseMoveEvent(mouseEvent); } void WorkflowScene::mouseReleaseEvent(QGraphicsSceneMouseEvent *mouseEvent) { QGraphicsScene::mouseReleaseEvent(mouseEvent); } void WorkflowScene::sl_selectAll() { foreach(QGraphicsItem* it, items()) { //if (it->type() == WorkflowProcessItemType) { it->setSelected(true); } } } void WorkflowScene::sl_deselectAll() { foreach(QGraphicsItem* it, items()) { it->setSelected( false ); } } void WorkflowScene::sl_reset() { QList list; foreach(QGraphicsItem* it, items()) { if (it->type() == WorkflowProcessItemType) { list << it; } } modified = false; foreach(QGraphicsItem* it, list) { removeItem(it); delete it; } iterations.clear(); } void WorkflowScene::setModified(bool b) { modified = b; } void WorkflowScene::drawBackground(QPainter * painter, const QRectF & rect) { if (WorkflowSettings::showGrid()) { int step = GRID_STEP; painter->setPen(QPen(QColor(200, 200, 255, 125))); // draw horizontal grid qreal start = round(rect.top(), step); if (start > rect.top()) { start -= step; } for (qreal y = start - step; y < rect.bottom(); ) { y += step; painter->drawLine(rect.left(), y, rect.right(), y); } // now draw vertical grid start = round(rect.left(), step); if (start > rect.left()) { start -= step; } for (qreal x = start - step; x < rect.right(); ) { x += step; painter->drawLine(x, rect.top(), x, rect.bottom()); } } if (items().size() == 0) { // draw a hint on empty scene painter->setPen(Qt::darkGray); QFont f = painter->font(); if (hint == SamplesTab) { } else { QTransform trans = painter->combinedTransform(); f.setFamily("Courier New"); f.setPointSizeF(f.pointSizeF()* 2./trans.m11()); painter->setFont(f); QRectF res; painter->drawText(sceneRect(), Qt::AlignCenter, tr("Drop an element from the palette here"), &res); QPixmap pix(":workflow_designer/images/leftarrow.png"); QPointF pos(res.left(), res.center().y()); pos.rx() -= pix.width() + GRID_STEP; pos.ry() -= pix.height()/2; painter->drawPixmap(pos, pix); } } } void WorkflowScene::setIterations( const QList& lst ) { assert(!locked); iterations = lst; modified = true; emit configurationChanged(); } void WorkflowScene::centerView() { QRectF childRect; foreach (QGraphicsItem *child, items()) { QPointF childPos = child->pos(); QTransform matrix = child->transform() * QTransform().translate(childPos.x(), childPos.y()); childRect |= matrix.mapRect(child->boundingRect() | child->childrenBoundingRect()); } // QPointF zero = childRect.center(); //log.info(QString("center [%1 %2]").arg(zero.x()).arg(zero.y())); //FIXME does not work //views().first()->centerOn(zero); update(); } }//namespace ugene-1.9.8/src/plugins/workflow_designer/src/ItemViewStyle.cpp0000644000175000017500000005105211651544324023371 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "WorkflowViewItems.h" #include "WorkflowViewController.h" #include "ItemViewStyle.h" namespace U2 { const StyleId ItemStyles::SIMPLE = "simple"; const StyleId ItemStyles::EXTENDED = "ext"; #define BGC QString("-bgc") #define FONT QString("-font") ItemViewStyle::ItemViewStyle(WorkflowProcessItem* p, const QString& id) : QGraphicsObject(p), defFont(WorkflowSettings::defaultFont()), id(id) { setVisible(false); bgColorAction = new QAction(tr("Background color"), this); connect(bgColorAction, SIGNAL(triggered()), SLOT(selectBGColor())); fontAction = new QAction(tr("Font"), this); connect(fontAction, SIGNAL(triggered()), SLOT(selectFont())); } void ItemViewStyle::selectBGColor() { QColor res = QColorDialog::getColor(bgColor, owner->scene()->views().first()); if (res.isValid()) { bgColor = res; WorkflowScene* sc = qobject_cast(owner->scene()); if(sc != NULL) { sc->setModified(true); } } } void ItemViewStyle::selectFont() { bool ok; QFont res = QFontDialog::getFont(&ok, defFont, owner->scene()->views().first()); if (ok) { defFont = res; WorkflowScene* sc = qobject_cast(owner->scene()); if(sc != NULL) { sc->setModified(true); } } } void ItemViewStyle::saveState(QDomElement& el) const { if (bgColor != defaultColor()) el.setAttribute(id+BGC, QVariantUtils::var2String(bgColor)); if (defFont != QFont()) el.setAttribute(id+FONT, defFont.toString()); } void ItemViewStyle::loadState(QDomElement& el) { if (el.hasAttribute(id+BGC)) { QColor bgc = QVariantUtils::String2Var(el.attribute(id+BGC)).value(); if (bgc.isValid()) { bgColor = bgc; } } if (el.hasAttribute(id+FONT)) { defFont.fromString(el.attribute(id+FONT)); } } SimpleProcStyle::SimpleProcStyle(WorkflowProcessItem* pit) : ItemViewStyle(pit, ItemStyles::SIMPLE) { owner = (pit); owner->connect(owner->getProcess(), SIGNAL(si_labelChanged()), SLOT(sl_update())); bgColor = defaultColor(); } QColor SimpleProcStyle::defaultColor() const { /*QColor ret(Qt::darkCyan); ret.setAlpha(200);*/ QColor ret = WorkflowSettings::getBGColor(); return ret; } QRectF SimpleProcStyle::boundingRect(void) const { // extra space added for clean antialiased painting return QRectF(-R-2, -R-2, R*2+4, R*2+4); } QPainterPath SimpleProcStyle::shape () const { QPainterPath contour; contour.addEllipse(QPointF(0,0), R, R); return contour; } void SimpleProcStyle::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) { Q_UNUSED(option); Q_UNUSED(widget); //painter->fillRect(boundingRect(), QBrush(Qt::magenta, Qt::Dense6Pattern)); painter->setRenderHint(QPainter::Antialiasing); QPainterPath contour; contour.addEllipse(QPointF(0,0), R, R); if (owner->isSelected()) { QPen pen; pen.setWidthF(2); pen.setStyle(Qt::DashLine); painter->setPen(pen); } QRadialGradient rg(R/2, -R/2, R*2); rg.setColorAt(1, bgColor); rg.setColorAt(0, QColor(Qt::white)); QBrush procBrush(rg); painter->drawPath(contour); painter->fillPath(contour, procBrush); painter->save(); QTextDocument d; d.setDefaultFont(defFont); d.setHtml("
    " + Qt::escape(owner->getProcess()->getLabel()) + "
    "); d.setTextWidth(R*2); //d.setDefaultTextOption(QTextOption(Qt::AlignHCenter)); painter->translate(-d.size().width()/2, -d.size().height()/2); //painter->translate(-R, -R); d.drawContents(painter, QRectF(0,0,2*R,2*R)); painter->restore(); } //QPainterPath shape () const; #define MARGIN 5 ExtendedProcStyle::ExtendedProcStyle(WorkflowProcessItem* pit) : ItemViewStyle(pit, ItemStyles::EXTENDED), autoResize(true), resizing(NoResize) { owner = (pit); Actor* process = pit->getProcess(); doc = process->getDescription(); if (doc) { owner->connect(doc, SIGNAL(contentsChanged()), SLOT(sl_update())); } else { doc = new QTextDocument(pit); doc->setHtml(QString("
    %1

    %2
    aLSKDJALSK LASDJ LASKD LASJD ALSKDJ XCKLJSLC Jas dlkjsdf sdlkjsdlfj sdlkfjlsdkfjs dlkfjsdlkfjsld flsdkjflsd kfjlsdkfj lsdkfjlsd flskfjsldkfjsldf jsdlkfjsdlkfjsdlfkjsdlfj") .arg(process->getLabel()).arg(process->getProto()->getDocumentation())); } owner->connect(fontAction, SIGNAL(triggered()), SLOT(sl_update())); desc = new DescriptionItem(this); refresh(); resizeModeAction = new QAction(tr("Auto-resize to text"), this); resizeModeAction->setCheckable(true); resizeModeAction->setChecked(autoResize); connect(resizeModeAction, SIGNAL(toggled(bool)), SLOT(setAutoResizeEnabled(bool))); bgColor = defaultColor(); } QColor ExtendedProcStyle::defaultColor() const { return WorkflowSettings::getBGColor(); } #define MINW 2*R #define MAXW 6*R void ExtendedProcStyle::refresh() { doc->setDefaultFont(defFont); if (autoResize) { bool snap2grid = WorkflowSettings::snap2Grid(); qreal w,h; int cycle = 0; do { QSizeF docFrame = doc->size(); w = docFrame.width() + MARGIN*2; if (snap2grid) { w = roundUp(w, GRID_STEP); doc->setTextWidth(w - MARGIN*2); docFrame = doc->size(); } h = qMax(2*R, docFrame.height()) + MARGIN*2; if (snap2grid) { h = roundUp(h, GRID_STEP); } //printf("ideal=%f, actual=%f\n",doc->idealWidth(),w); // try to improve docFrame proportions if (++cycle > 2) { break; } if ((h/w < 0.6 && w > (MINW+MAXW)/2) //doc is disproportionately wide || (h/w > 1.6 && w < MAXW) //doc is disproportionately long and can be widen || (w < MINW || w > MAXW)) { //width is out of bounds doc->setTextWidth(qBound(MINW, (qreal)(h/1.6), MAXW-MARGIN*2)); } } while (true); bounds = QRectF(-R, -R, w, h); } else { //bounds.setSize(bounds.size().expandedTo(doc->size() + QSizeF(MARGIN*2,MARGIN*2))); } desc->setDocument(doc); } QPainterPath ExtendedProcStyle::shape () const { QPainterPath contour; contour.addRoundedRect(bounds, MARGIN, MARGIN); return contour; } void ExtendedProcStyle::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *) { if (owner->isSelected()) { ((QStyleOptionGraphicsItem*)option)->state |= QStyle::State_Selected; } bgColor.setAlpha(64); QRectF tb = boundingRect(); painter->fillRect(tb, QBrush(bgColor)); painter->setRenderHint(QPainter::Antialiasing); if (doc->pageCount() > 1) { QPointF tp = bounds.bottomRight(); // draw a page corner //QPen pen; //pen.setWidthF(1.2); //painter->setPen(pen); //qreal len = 6; //painter->drawLine(tp.x() - len, tp.y() - len, tp.x(), tp.y() - len); //painter->drawLine(tp.x() - len, tp.y() - len, tp.x() - len, tp.y()); // draw 3 dots at corner QPointF dt(tp.x() - 7, tp.y() - 5); QPainterPath dot; dot.addEllipse(dt, 1.2,1.2); dot.addEllipse(dt - QPointF(4,0), 1.2,1.2); dot.addEllipse(dt - QPointF(8,0), 1.2,1.2); painter->fillPath(dot, QBrush(QColor(0x33, 0x33, 0x33))); } QPen pen; pen.setWidthF(1.3); if (owner->isSelected()) { pen.setStyle(Qt::DashLine); } painter->setPen(pen); painter->drawRoundedRect(tb, MARGIN, MARGIN); } #define RESIZE_AREA 4 bool ExtendedProcStyle::sceneEventFilter( QGraphicsItem * watched, QEvent * event ) { assert(watched == owner); Q_UNUSED(watched); bool ret = false; switch (event->type()) { case QEvent::GraphicsSceneHoverEnter: case QEvent::GraphicsSceneHoverMove: { QGraphicsSceneHoverEvent* he = static_cast(event); ret = updateCursor(he->pos()); } break; case QEvent::GraphicsSceneMouseRelease: desc->mouseReleaseEvent(event); case QEvent::GraphicsSceneHoverLeave: if (resizing) { owner->unsetCursor(); } resizing = NoResize; break; case QEvent::GraphicsSceneMouseMove: if (resizing && event->spontaneous()) { QGraphicsSceneMouseEvent* me = (static_cast(event)); WorkflowSettings::setSnap2Grid(false); QPointF newPos; if ((me->buttons() & Qt::LeftButton)) { ret = true; QRectF b2 = bounds; QPointF p = me->pos(); QPointF p2 = p - me->lastPos(); if (resizing & RightResize && // border is either "pulled" or "pushed" by mouse pointer // in the latter case pointer should be close to the border ((p2.x() < 0 && b2.right() > p.x()) || (p2.x() > 0 && b2.right() < p.x()) || (qAbs(b2.right() - p.x()) < RESIZE_AREA))) { qreal rb = b2.right() + p2.x(); b2.setRight(rb); if (b2.width() < MARGIN*2 + R) { return true; } } if (resizing & LeftResize && ((p2.x() < 0 && b2.left() > p.x()) || (p2.x() > 0 && b2.left() < p.x()) || (qAbs(b2.left() - p.x()) < RESIZE_AREA))) { b2.setWidth(b2.width() - p2.x()); newPos = owner->scenePos(); newPos.setX(newPos.x() - (b2.width() - bounds.width())); if (b2.width() < MARGIN*2 + R) { return true; } setFixedBounds(b2); owner->setPos(newPos); } if(resizing & TopResize && ((p2.y() < 0 && b2.top() > p.y()) || (p2.y() > 0 && b2.top() < p.y()) || (qAbs(b2.top() - p.y()) < RESIZE_AREA))) { b2.setHeight(b2.height() - p2.y()); newPos = owner->scenePos(); newPos.setY(newPos.y() - (b2.height() - bounds.height())); qreal minHeight = R + MARGIN*2; WorkflowScene * sc = qobject_cast(owner->scene()); if (b2.height() < minHeight || newPos.y() < sc->sceneRect().top()) { return true; } setFixedBounds(b2); owner->setPos(newPos); } if (resizing & BottomResize && ((p2.y() < 0 && b2.bottom() > p.y()) || (p2.y() > 0 && b2.bottom() < p.y()) || (qAbs(b2.bottom() - p.y()) < RESIZE_AREA))) { b2.setBottom(b2.bottom() + p2.y()); } //qreal minHeight = qMax(doc->size().height(), R) + MARGIN*2; qreal minHeight = R + MARGIN*2; if (b2.height() < minHeight) { b2.setHeight(minHeight); } setFixedBounds(b2); WorkflowScene * sc = qobject_cast(owner->scene()); if(sc != NULL) { sc->setModified(true); } } } break; /*case QEvent::GraphicsSceneMousePress: mousePressEvent(static_cast(event)); break; case QEvent::GraphicsSceneMouseDoubleClick: mouseDoubleClickEvent(static_cast(event)); break; case QEvent::GraphicsSceneWheel: wheelEvent(static_cast(event)); break; case QEvent::KeyPress: keyPressEvent(static_cast(event)); break; case QEvent::KeyRelease: keyReleaseEvent(static_cast(event)); break; case QEvent::InputMethod: inputMethodEvent(static_cast(event)); break;*/ default: return false; } return ret; } bool ExtendedProcStyle::updateCursor(const QPointF& p) { bool ret = false; resizing = NoResize; qreal dx = qAbs(bounds.right() - p.x()); qreal dy = qAbs(bounds.bottom() - p.y()); if (dx < RESIZE_AREA) { resizing |= RightResize; } if(dx > (bounds.width() - RESIZE_AREA)) { resizing |= LeftResize; } if (dy < RESIZE_AREA) { resizing |= BottomResize; } if(dy > (bounds.height() - RESIZE_AREA)) { resizing |= TopResize; } switch (resizing) { case NoResize: owner->unsetCursor(); break; case RightResize: case LeftResize: owner->setCursor(Qt::SizeHorCursor); break; case BottomResize: case TopResize: owner->setCursor(Qt::SizeVerCursor); break; case RBResize: case LTResize: owner->setCursor(Qt::SizeFDiagCursor); break; case LBResize: case RTResize: owner->setCursor(Qt::SizeBDiagCursor); break; } ret = (resizing != NoResize); return ret; } void ExtendedProcStyle::setFixedBounds( const QRectF& b) { doc->setPageSize(b.size() - QSizeF(MARGIN*2,MARGIN*2)); if (bounds != b) { bounds = b; owner->prepareUpdate(); foreach(WorkflowPortItem* pit, owner->getPortItems()) { pit->adaptOwnerShape(); } } owner->update(); resizeModeAction->setChecked(false); } void ExtendedProcStyle::setAutoResizeEnabled(bool b) { autoResize = b; if (autoResize) { doc->setPageSize(QSizeF(-1,-1)); owner->sl_update(); } } QList ExtendedProcStyle::getContextMenuActions() const { QList ret; ret << resizeModeAction << bgColorAction << fontAction; return ret; } #define ARM QString("arm") #define BOUNDS QString("bounds") void ExtendedProcStyle::saveState(QDomElement& el) const { //el.setAttribute(ARM, autoResize); if (!autoResize) { el.setAttribute(BOUNDS, QVariantUtils::var2String(bounds)); } ItemViewStyle::saveState(el); } void ExtendedProcStyle::loadState(QDomElement& el) { if (el.hasAttribute(BOUNDS)) { QRectF b = QVariantUtils::String2Var(el.attribute(BOUNDS)).toRectF(); if (!b.isNull()) { setFixedBounds(b); } } ItemViewStyle::loadState(el); } void ExtendedProcStyle::linkHovered(const QString& url) { if (url.isEmpty()) { owner->unsetCursor(); } else { owner->setCursor(Qt::PointingHandCursor); } } HintItem::HintItem( const QString & text, QGraphicsItem * parent) : QGraphicsTextItem(text, parent), dragging(false) { setFlag(QGraphicsItem::ItemIsSelectable); #if (QT_VERSION >= QT_VERSION_CHECK(4, 6, 0)) setFlag(QGraphicsItem::ItemSendsGeometryChanges, true); #endif document()->setDefaultTextOption(QTextOption(Qt::AlignCenter)); setTextWidth(qMin(3*R, document()->idealWidth())); QRectF tb = boundingRect(); setPos(-tb.width()/2, -tb.height()- 3); setDefaultTextColor(QColor(Qt::gray).darker()); QFont f = font(); f.setWeight(QFont::Light); setFont(f); } QVariant HintItem::itemChange( GraphicsItemChange change, const QVariant & value ) { if (change == ItemSelectedChange && value.toBool()) { parentItem()->setSelected(true); return false; } if (change == ItemPositionChange) { QPointF newPos = value.toPointF(); if (scene()) { QRectF bound = boundingRect(); QRectF sceneRect = scene()->sceneRect(); // scene topLeft in parent coords QPointF tl = mapToParent(mapFromScene(sceneRect.topLeft())); sceneRect.moveTopLeft(tl); qreal x0 = sceneRect.left() - bound.left(); qreal x1 = sceneRect.left() + sceneRect.width() - bound.right(); qreal y0 = sceneRect.top() - bound.top(); qreal y1 = sceneRect.top() + sceneRect.height() - bound.bottom(); newPos.setX( qBound(x0, newPos.x(), x1) ); newPos.setY( qBound(y0, newPos.y(), y1) ); } return newPos; } if (change == ItemPositionHasChanged) { parentItem()->update(); if (scene()) { foreach(QGraphicsView* v, scene()->views()) { v->ensureVisible(this, 0, 0); } } } return QGraphicsItem::itemChange(change, value); } void HintItem::mouseMoveEvent(QGraphicsSceneMouseEvent *event) { if (event->buttons() & Qt::LeftButton) { if (!dragging) { initPos = pos(); dragging = true; } QPointF delta = event->screenPos() - event->buttonDownScreenPos(Qt::LeftButton); setPos(initPos + delta); } else { event->ignore(); } } void HintItem::mouseReleaseEvent( QGraphicsSceneMouseEvent *event ) { dragging = false; QGraphicsTextItem::mouseReleaseEvent(event); } DescriptionItem::DescriptionItem(ExtendedProcStyle* p) : QGraphicsTextItem(p) { setPos(-R + MARGIN, -R + MARGIN); setTextInteractionFlags(Qt::LinksAccessibleByMouse|Qt::LinksAccessibleByKeyboard); p->connect(this, SIGNAL(linkActivated(const QString&)), SIGNAL(linkActivated(const QString&))); p->connect(this, SIGNAL(linkHovered(const QString&)), SLOT(linkHovered(const QString&))); } QRectF DescriptionItem::boundingRect() const { QRectF bounds = parentItem()->boundingRect(); bounds.translate(R - MARGIN, R - MARGIN); return bounds; } void DescriptionItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) { QStyleOptionGraphicsItem deselectedOption = *option; deselectedOption.state &= ~(QStyle::State_Selected | QStyle::State_HasFocus); QGraphicsTextItem::paint(painter, &deselectedOption, widget); } void DescriptionItem::mouseReleaseEvent(QEvent *event) { QGraphicsSceneMouseEvent* e = static_cast(event); e->setPos(mapFromParent(e->pos())); QGraphicsTextItem::mouseReleaseEvent(e); } bool DescriptionItem::sceneEvent(QEvent *event) { switch (event->type()) { case QEvent::GraphicsSceneHoverMove: case QEvent::GraphicsSceneHoverEnter: { ExtendedProcStyle* owner = qgraphicsitem_cast(parentItem()); if (owner->resizing) { QGraphicsSceneHoverEvent* he = static_cast(event); const QPointF& p = mapToParent(he->pos()); owner->updateCursor(p); } } break; default: break; } return QGraphicsTextItem::sceneEvent(event); } }//namespace ugene-1.9.8/src/plugins/workflow_designer/src/IterationListWidget.cpp0000644000175000017500000003152211651544324024555 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "IterationListWidget.h" #include #include #include #include #include #include #include #include #include #include /* TRANSLATOR U2::LocalWorkflow::IterationListWidget */ namespace U2 { static QString findIterationName(const QString & candidate, const QList & its) { bool unique = true; foreach(const Iteration & it, its) { if(candidate == it.name) { unique = false; break; } } if(unique) { return candidate; } QList similar; foreach(const Iteration & it, its) { if(it.name.startsWith(candidate)) { similar << it.name; } } int num = similar.size() + 1; foreach(const QString & name, similar) { QStringList lst = name.split(QRegExp("\\s+")); if(lst.size() > 1) { bool ok = false; int n = lst.last().toInt(&ok); if(ok) { num = qMax(num, n + 1); } } } return candidate + QString(" %1").arg(num); } class IterationListModel : public QAbstractListModel { public: IterationListModel(QObject *parent = 0) : QAbstractListModel(parent) {} Qt::ItemFlags flags ( const QModelIndex & index ) const { Q_UNUSED(index); return Qt::ItemIsEditable | Qt::ItemIsEnabled | Qt::ItemIsSelectable; } int rowCount ( const QModelIndex & parent = QModelIndex() ) const { if (parent.isValid()) return 0; return dataList.size(); } /*Used to supply item data to views and delegates. Generally, models only need to supply data for Qt::DisplayRole and any application-specific user roles, but it is also good practice to provide data for Qt::ToolTipRole, Qt::AccessibleTextRole, and Qt::AccessibleDescriptionRole.*/ QVariant data ( const QModelIndex & index, int role = Qt::DisplayRole ) const { if (index.row() < 0 || index.row() >= dataList.size()) return QVariant(); if (role == Qt::DisplayRole || role == Qt::EditRole) return dataList.at(index.row()).name; if (role == Qt::ToolTipRole) { return QString("%1 [id=%2]").arg(dataList.at(index.row()).name).arg(dataList.at(index.row()).id); } return QVariant(); } /*Used to modify the item of data associated with a specified model index. To be able to accept user input, provided by user interface elements, this function must handle data associated with Qt::EditRole. The implementation may also accept data associated with many different kinds of roles specified by Qt::ItemDataRole. After changing the item of data, models must emit the dataChanged() signal to inform other components of the change.*/ bool setData ( const QModelIndex & index, const QVariant & value, int role = Qt::EditRole ) { if (index.row() >= 0 && index.row() < dataList.size() && (role == Qt::EditRole || role == Qt::DisplayRole)) { QString name = value.toString(); if (dataList.at(index.row()).name != name) { dataList[index.row()].name = name; emit dataChanged(index, index); } return true; } return false; } bool copySelected(const QItemSelection& sel) { QList lst; foreach (QModelIndex i, sel.indexes()) { lst.append(QPersistentModelIndex(i)); } foreach(QPersistentModelIndex i, lst) { assert(i.isValid()); int row = i.row(); beginInsertRows(QModelIndex(), row, row); Iteration copy = dataList.at(row); copy.name = findIterationName(U2::IterationListWidget::tr("Copy of %1").arg(copy.name), dataList); dataList.insert(row, copy); endInsertRows(); } return true; } bool removeSelected(const QItemSelection& sel) { QList lst; foreach (QModelIndex i, sel.indexes()) { lst.append(QPersistentModelIndex(i)); } foreach(QPersistentModelIndex i, lst) { assert(i.isValid()); int row = i.row(); beginRemoveRows(QModelIndex(), row, row); dataList.removeAt(row); endRemoveRows(); } return true; } bool insertRows ( int row, int count, const QModelIndex & parent = QModelIndex() ) { if (count < 1 || row < 0 || row > rowCount(parent)) { return false; } beginInsertRows(QModelIndex(), row, row + count - 1); for (int r = 0; r < count; ++r) { dataList.insert(row, findIterationName(U2::IterationListWidget::tr("New Iteration"), dataList)); } endInsertRows(); return true; } bool removeRows(int row, int count, const QModelIndex &parent) { if (count <= 0 || row < 0 || (row + count) > rowCount(parent)) return false; beginRemoveRows(QModelIndex(), row, row + count - 1); for (int r = 0; r < count; ++r) dataList.removeAt(row); endRemoveRows(); return true; } void replaceData(const QList& lst) { dataList = lst; reset(); } QList dataList; }; // IterationListModel IterationListWidget::IterationListWidget(QWidget *parent) : QWidget(parent), cloneAction(NULL), removeAction(NULL) { QVBoxLayout* vert = new QVBoxLayout(this); vert->setSpacing(0); vert->setContentsMargins(0, 1, 0, 0); iterationList = new QListView(this); iterationList->setAlternatingRowColors(false); iterationList->setSelectionMode(QAbstractItemView::SingleSelection); iterationList->setSelectionBehavior(QAbstractItemView::SelectRows); vert->addWidget(iterationList); setupIterationUI(this); sl_updateActions(); } QList& IterationListWidget::list() const { IterationListModel* mdl = static_cast(iterationList->model()); return mdl->dataList; } void IterationListWidget::setList(const QList& lst) { IterationListModel* mdl = static_cast(iterationList->model()); mdl->replaceData(lst); updateIterationState(); } int IterationListWidget::current() const { int row = iterationList->selectionModel()->currentIndex().row(); if (row == -1 && !iterationList->selectionModel()->selectedRows().isEmpty()) { row = iterationList->selectionModel()->selectedRows().first().row(); } if (row == -1) { //TODO: assert(0); row = 0; } return row; } QItemSelection IterationListWidget::selection() const { return iterationList->selectionModel()->selection(); } void IterationListWidget::setupIterationUI(QWidget* w) { QToolBar* tb = new QToolBar(w); cloneAction = new QAction(QIcon(), tr("Clone"), this); connect(cloneAction, SIGNAL(triggered()), SLOT(sl_cloneIteration())); tb->addAction(cloneAction); QAction* addAction = new QAction(QIcon(), tr("Add"), this); connect(addAction, SIGNAL(triggered()), SLOT(sl_addIteration())); tb->addAction(addAction); removeAction = new QAction(QIcon(), tr("Remove"), this); connect(removeAction, SIGNAL(triggered()), SLOT(sl_removeIteration())); tb->addAction(removeAction); QAction* selectAction = new QAction(QIcon(), tr("All"), this); connect(selectAction, SIGNAL(triggered()), SLOT(sl_selectIterations())); //tb->addAction(selectAction); iterationList->setModel(new IterationListModel(this)); connect(iterationList->selectionModel(), SIGNAL(selectionChanged(QItemSelection,QItemSelection)), SLOT(sl_iterationSelected())); connect(iterationList->model(), SIGNAL(dataChanged(QModelIndex,QModelIndex)), SIGNAL(listChanged())); connect(iterationList->model(), SIGNAL(rowsAboutToBeRemoved(QModelIndex,int,int)), SIGNAL(iterationListAboutToChange())); connect(iterationList->model(), SIGNAL(rowsAboutToBeInserted(QModelIndex,int,int)), SIGNAL(iterationListAboutToChange())); connect(this, SIGNAL(selectionChanged()), SLOT(sl_updateActions())); qobject_cast(w->layout())->insertWidget(0, tb); } void IterationListWidget::updateIterationState() { if (iterationList->model()->rowCount() == 0) { sl_addIteration(); iterationList->model()->setData(iterationList->model()->index(0,0), tr("Default iteration")); sl_selectIterations(); } else if (iterationList->selectionModel()->selection().isEmpty()) { iterationList->selectionModel()->setCurrentIndex(iterationList->model()->index(0,0), QItemSelectionModel::Select); } } void IterationListWidget::sl_addIteration() { int row = iterationList->currentIndex().row(); if (row < 0) row = 0; iterationList->model()->insertRow(row); emit listChanged(); } void IterationListWidget::sl_removeIteration(){ IterationListModel* mdl = static_cast(iterationList->model()); mdl->removeSelected(iterationList->selectionModel()->selection()); updateIterationState(); emit listChanged(); } void IterationListWidget::sl_cloneIteration() { IterationListModel* mdl = static_cast(iterationList->model()); QItemSelection sel = iterationList->selectionModel()->selection(); if (!sel.isEmpty()) { mdl->copySelected(sel); emit listChanged(); } } void IterationListWidget::sl_selectIterations(){ iterationList->selectAll(); } void IterationListWidget::sl_iterationSelected() { emit selectionChanged(); } void IterationListWidget::sl_updateActions() { bool noSelection = iterationList->selectionModel()->selection().isEmpty(); cloneAction->setEnabled(!noSelection); removeAction->setEnabled(!noSelection); } void IterationListWidget::selectIteration(int id) { IterationListModel* mdl = static_cast(iterationList->model()); for (int i = 0; i < mdl->dataList.size(); ++i) { if (mdl->dataList.at(i).id == id) { disconnect(iterationList->selectionModel(), SIGNAL(selectionChanged(QItemSelection,QItemSelection)), this, SLOT(sl_iterationSelected())); iterationList->selectionModel()->clear(); iterationList->selectionModel()->setCurrentIndex( iterationList->model()->index(i,0), QItemSelectionModel::Select); connect(iterationList->selectionModel(), SIGNAL(selectionChanged(QItemSelection,QItemSelection)), SLOT(sl_iterationSelected())); break; } } } bool IterationListWidget::expandList(const ActorId& id, const QString& key, const QVariant& val) { QVariantList vList = val.toList(); if (vList.size() > 1) { QMessageBox askBox(QMessageBox::Question, tr("Workflow Designer"), tr("Do you want to divide the list into separate iterations?"), QMessageBox::Yes | QMessageBox::No, this); askBox.setDefaultButton(QMessageBox::No); askBox.setTextFormat(Qt::RichText); askBox.setInformativeText(tr("If you need to process each item in the list with different schema parameters,\n" "the Designer can create separate iterations for each item now.\n" "Otherwise, if all items should be processed uniformly,\nit is better to leave the list intact.")); if (QMessageBox::Yes == askBox.exec()) { QList& dataList = list(); Iteration& base = dataList[current()]; QVariant v = vList.takeFirst(); base.cfg[id].insert(key,v); base.name = v.toString(); foreach (QVariant v, vList) { Iteration it(v.toString()); it.cfg = base.cfg; it.cfg[id].insert(key,v); dataList.append(it); } setList(dataList); emit listChanged(); return true; } } return false; } }//namespace ugene-1.9.8/src/plugins/workflow_designer/src/SceneSerializer.cpp0000644000175000017500000001266211651544324023712 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include #include #include #include #include #include #include #include #include "WorkflowViewController.h" #include "WorkflowViewItems.h" #include "SceneSerializer.h" /* TRANSLATOR U2::LocalWorkflow::WorkflowView */ namespace U2 { using namespace Workflow; static const QString WORKFLOW_EL = "workflow"; static const QString PROCESS_EL = "process"; static const QString PORT_EL = "port"; static const QString PARAMS_EL = "params"; static const QString DATAFLOW_EL = "dataflow"; static const QString POSITION_ATTR = "pos"; static const QString ID_ATTR = "id"; static const QString NAME_ATTR = "name"; static const QString NUM_IN_SCHEMA = "numberInSchema"; static const QString TYPE_ATTR = "type"; static const QString SRC_PORT_ATTR = "sprt"; static const QString SRC_PROC_ATTR = "sprc"; static const QString DST_PORT_ATTR = "dprt"; static const QString DST_PROC_ATTR = "dprc"; static const QString SCRIPT_TEXT = "scriptText"; static void saveProcess(const WorkflowProcessItem* pit, QDomElement& proj) { QDomElement docElement = SchemaSerializer::saveActor(pit->getProcess(), proj); pit->saveState(docElement); foreach(WorkflowPortItem* iot, pit->getPortItems()) { Port* port = iot->getPort(); QDomElement portElement = SchemaSerializer::savePort(port, docElement); portElement.setAttribute(POSITION_ATTR, iot->getOrientarion()); } } static void saveFlow(const WorkflowBusItem* dit, QDomElement& proj) { QDomElement el = SchemaSerializer::saveLink(dit->getBus(), proj); dit->saveState(el); } void SceneSerializer::scene2xml(const WorkflowScene* scene, QDomDocument& xmlDoc){ QDomElement projectElement = xmlDoc.createElement(WORKFLOW_EL); // TODO save scale and view rect?? xmlDoc.appendChild(projectElement); saveItems(scene->items(), projectElement); } void SceneSerializer::saveItems(const QList& items, QDomElement& proj) { foreach(QGraphicsItem* item, items) { switch (item->type()) { case WorkflowProcessItemType: saveProcess(qgraphicsitem_cast(item), proj); break; case WorkflowBusItemType: saveFlow(static_cast(item), proj); break; } } } static void initProcMap(QMap & procMap, WorkflowScene* scene) { foreach(QGraphicsItem* item, scene->items()) { if (item->type() == WorkflowProcessItemType) { WorkflowProcessItem* wit = qgraphicsitem_cast(item); procMap[wit->getProcess()->getId()] = wit; } } } QString SceneSerializer::xml2scene(const QDomElement& projectElement, WorkflowScene* scene, QMap& /*remapping*/, bool ignoreErrors, bool select) { QMap procMap; QMap actorMap; initProcMap(procMap, scene); ActorPrototypeRegistry* registry = WorkflowEnv::getProtoRegistry(); QDomNodeList procNodes = projectElement.elementsByTagName(PROCESS_EL); for(int i=0; igetProto(name); if (!proto) { return WorkflowView::tr("Invalid content: unknown process type %1").arg(name); } Actor* proc = proto->createInstance(NULL); actorMap[id] = proc; proc->setLabel(procElement.attribute(NAME_ATTR)); WorkflowProcessItem* it = new WorkflowProcessItem(proc); it->loadState(procElement); scene->addItem(it); if (select) { it->setSelected(true); } procMap[id] = it; // foreach(PortDescriptor * pd, proto->getPortDesciptors()) { // if(pd == NULL) { // continue; // } // WorkflowPortItem * p = it->getPort(pd->getId()); // } } return QString(); } }//namespace ugene-1.9.8/src/plugins/workflow_designer/src/util/0000755000175000017500000000000011651544325021066 5ustar ilyailyaugene-1.9.8/src/plugins/workflow_designer/src/util/SaveSchemaImageUtils.h0000644000175000017500000000515711651544325025252 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_WORKFLOW_SAVE_SCHEMA_IMAGE_UTILS_H_ #define _U2_WORKFLOW_SAVE_SCHEMA_IMAGE_UTILS_H_ #include #include #include #include namespace U2 { using namespace Workflow; class SaveSchemaImageUtils : public QObject { Q_OBJECT public: static QPixmap generateSchemaSnapshot(const QString & data); static QString saveSchemaImageToFile(const QString & schemaName, const QString & imagePath); }; class GoogleChartImage { public: static const QString CHART_TYPE_OPTION; static const QString GRAPH_OPTION; static const QString CHART_SIZE_OPTION; static const QString GRAPH_VIZ_CHART_TYPE; static const QSize CHART_SIZE_DEFAULT; static const QString GOOGLE_CHART_BASE_URL; public: GoogleChartImage(Schema * sc, const Metadata& meta); QString getImageUrl() const; private: QString getUrlArguments() const; private: QSize chartSize; Schema * schema; Metadata meta; }; /** * Produces link to googlechart api of produced image */ class ProduceSchemaImageLinkTask : public Task { Q_OBJECT public: ProduceSchemaImageLinkTask(const QString & schemaName); ~ProduceSchemaImageLinkTask(); virtual void prepare(); virtual ReportResult report(); virtual QList onSubTaskFinished(Task* subTask); QString getImageLink() const; private: ProduceSchemaImageLinkTask(); ProduceSchemaImageLinkTask(const ProduceSchemaImageLinkTask &); ProduceSchemaImageLinkTask & operator=(const ProduceSchemaImageLinkTask &); private: QString schemaPath; Schema * schema; Metadata meta; QString imageLink; }; // ProduceSchemaImageLinkTask } // U2 #endif // _U2_WORKFLOW_SAVE_SCHEMA_IMAGE_UTILS_H_ ugene-1.9.8/src/plugins/workflow_designer/src/util/SaveSchemaImageUtils.cpp0000644000175000017500000001524411651544325025603 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include #include #include #include #include #include "WorkflowViewController.h" #include "SaveSchemaImageUtils.h" #include "HRSceneSerializer.h" #include namespace U2 { Logger log("Save schema image task"); /******************************** * ProduceSchemaImageLinkTask ********************************/ ProduceSchemaImageLinkTask::ProduceSchemaImageLinkTask(const QString & schemaName) : Task(tr("Save workflow schema image"), TaskFlags_NR_FOSCOE), schema(NULL) { schemaPath = WorkflowUtils::findPathToSchemaFile( schemaName ); if( schemaPath.isEmpty() ) { setError( tr( "Cannot find schema: %1" ).arg( schemaName ) ); return; } } ProduceSchemaImageLinkTask::~ProduceSchemaImageLinkTask() { delete schema; } void ProduceSchemaImageLinkTask::prepare() { if(hasError() || isCanceled()) { return; } schema = new Schema(); schema->setDeepCopyFlag(true); addSubTask(new LoadWorkflowTask( schema, &meta, schemaPath )); } QList ProduceSchemaImageLinkTask::onSubTaskFinished(Task* subTask) { LoadWorkflowTask * loadTask = qobject_cast(subTask); assert(loadTask != NULL); QList res; if( loadTask->hasError() || loadTask->isCanceled() ) { return res; } GoogleChartImage googleImg(schema, meta); imageLink = googleImg.getImageUrl(); return res; } QString ProduceSchemaImageLinkTask::getImageLink() const { return imageLink; } Task::ReportResult ProduceSchemaImageLinkTask::report() { return ReportResult_Finished; } /******************************** * GoogleChartImage ********************************/ const QString GoogleChartImage::CHART_TYPE_OPTION = "cht"; const QString GoogleChartImage::GRAPH_OPTION = "chl"; const QString GoogleChartImage::CHART_SIZE_OPTION = "chs"; const QString GoogleChartImage::GRAPH_VIZ_CHART_TYPE = "gv:dot"; const QSize GoogleChartImage::CHART_SIZE_DEFAULT(500, 500); const QString GoogleChartImage::GOOGLE_CHART_BASE_URL = "http://chart.apis.google.com/chart?"; GoogleChartImage::GoogleChartImage(Schema * sc, const Metadata& m) : chartSize(CHART_SIZE_DEFAULT), schema(sc), meta(m) { assert(schema != NULL); } QString GoogleChartImage::getImageUrl() const { return GOOGLE_CHART_BASE_URL + getUrlArguments(); } static QString makeArgumentPair( const QString & argName, const QString & value ) { return argName + "=" + value + "&"; } //static QString getSchemaGraphInSimpleDotNotation(Schema * schema, const Metadata & meta) { // assert(schema != NULL); // QString graph = "digraph{"; // graph += QString("label=\"Schema %1\"").arg(meta.name); // foreach(Link * link, schema->getFlows()) { // assert(link != NULL); // Actor * source = link->source()->owner(); // Actor * destination = link->destination()->owner(); // assert(source != NULL && destination != NULL); // graph += QString("%1->%2;").arg("\"" + source->getLabel() + "\"").arg("\"" + destination->getLabel() + "\""); // } // graph = graph.mid(0, graph.size() - 1); // return graph + "}"; //} static QString getSchemaGraphInExtendedDotNotation(Schema * schema, const Metadata & meta) { assert(schema != NULL); QString graph = "digraph{"; graph += QString("label=\"Schema %1\";").arg(meta.name); graph += QString("compound=true;"); graph += QString("rankdir=LR;"); graph += QString("bgcolor=white;"); graph += QString("edge [arrowsize=1, color=black];"); graph += QString("node [shape=box,style=\"filled, rounded\",fillcolor=lightblue];"); // Nodes definition foreach(Actor * actor, schema->getProcesses()) { graph += QString("%1 [label=\"%2\"];").arg(QString("node_%1").arg(actor->getId())).arg(actor->getLabel()); } // relationships definition foreach(Link * link, schema->getFlows()) { Actor * source = link->source()->owner(); Actor * destination = link->destination()->owner(); graph += QString("node_%1->node_%2;").arg(source->getId()).arg(destination->getId()); } graph = graph.mid(0, graph.size() - 1); return graph + "}"; } //static QString getSizeStr(const QSize & sz) { // return QString("%1x%2").arg(sz.width()).arg(sz.height()); //} QString GoogleChartImage::getUrlArguments() const { QString res; res += makeArgumentPair(CHART_TYPE_OPTION, GRAPH_VIZ_CHART_TYPE); res += makeArgumentPair(GRAPH_OPTION, getSchemaGraphInExtendedDotNotation(schema, meta)); //res += makeArgumentPair(CHART_SIZE_OPTION, getSizeStr(chartSize)); return res.mid(0, res.size() - 1); } /******************************** * SaveSchemaImageUtils ********************************/ QPixmap SaveSchemaImageUtils::generateSchemaSnapshot(const QString & data) { WorkflowScene* scene = new WorkflowScene(); QString msg = HRSceneSerializer::string2Scene(data, scene, NULL, true); if (!msg.isEmpty()) { log.trace(QString("Snapshot issues: cannot read scene: '%1'").arg(msg)); return QPixmap(); } QRectF bounds = scene->itemsBoundingRect(); QPixmap pixmap(bounds.size().toSize()); pixmap.fill(); QPainter painter(&pixmap); painter.setRenderHint(QPainter::Antialiasing); scene->render(&painter, QRectF(), bounds); delete scene; return pixmap; } QString SaveSchemaImageUtils::saveSchemaImageToFile(const QString & schemaPath, const QString & imagePath) { log.info(QString("Saving %1 snapshot to %2").arg(schemaPath).arg(imagePath)); QFile file(schemaPath); if(!file.open(QIODevice::ReadOnly)) { return L10N::errorOpeningFileRead(schemaPath); } QByteArray rawData = file.readAll(); QPixmap image = generateSchemaSnapshot(rawData); image.save(imagePath, "png"); return QString(); } } // U2 ugene-1.9.8/src/plugins/workflow_designer/src/WorkflowDocument.h0000644000175000017500000000621011651544324023571 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_WORKFLOW_FORMAT_H_ #define _U2_WORKFLOW_FORMAT_H_ #include "WorkflowDesignerPlugin.h" #include #include #include #include #include #include class QDomDocument; namespace U2 { class WorkflowView; class WorkflowDocFormat : public DocumentFormat { Q_OBJECT public: WorkflowDocFormat(QObject* p); static const DocumentFormatId FORMAT_ID; virtual DocumentFormatId getFormatId() const {return FORMAT_ID;} virtual const QString& getFormatName() const {return formatName;} virtual Document* createNewDocument(IOAdapterFactory* io, const QString& url, const QVariantMap& fs = QVariantMap()); virtual Document* loadDocument(IOAdapter* io, TaskStateInfo& ti, const QVariantMap& fs, DocumentLoadMode mode = DocumentLoadMode_Whole); virtual void storeDocument( Document* d, TaskStateInfo& ts, IOAdapter* io); virtual RawDataCheckResult checkRawData(const QByteArray& rawData, const GUrl& url = GUrl()) const; private: QString formatName; }; class WorkflowGObject : public GObject { Q_OBJECT public: static const GObjectType TYPE; WorkflowGObject(const QString& objectName, const QString& s, const QVariantMap& map = QVariantMap()) : GObject(TYPE, objectName), serializedScene(s), view(NULL) { Q_UNUSED(map); } QString getSceneRawData() const {return serializedScene;} void setSceneRawData(const QString & data); virtual GObject* clone() const; virtual bool isTreeItemModified () const; void setView(WorkflowView* view); WorkflowView* getView() const {return view;} protected: QString serializedScene; WorkflowView* view; }; class WorkflowViewFactory : public GObjectViewFactory { Q_OBJECT public: static const GObjectViewFactoryId ID; WorkflowViewFactory(QObject* p = NULL) : GObjectViewFactory(ID, U2::WorkflowDesignerPlugin::tr("Workflow Designer"), p) {} virtual bool canCreateView(const MultiGSelection& multiSelection); virtual Task* createViewTask(const MultiGSelection& multiSelection, bool single = false); }; class OpenWorkflowViewTask : public ObjectViewTask { Q_OBJECT public: OpenWorkflowViewTask(Document* doc); virtual void open(); }; }//namespace #endif ugene-1.9.8/src/plugins/workflow_designer/src/ChooseItemDialog.cpp0000644000175000017500000000411311651544324023772 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "ChooseItemDialog.h" #include namespace U2 { ChooseItemDialog::ChooseItemDialog(QWidget* p) : QDialog(p) { setupUi(this); connect(listWidget, SIGNAL(itemDoubleClicked(QListWidgetItem*)), SLOT(accept())); } QString ChooseItemDialog::select(const QMap& items) { listWidget->clear(); QMapIterator it(items); while (it.hasNext()) { it.next(); listWidget->addItem(new QListWidgetItem(it.value(), it.key())); } listWidget->setItemSelected(listWidget->item(0), true); if (exec() == QDialog::Accepted) { return listWidget->currentItem()->text(); } else { return QString(); } } Workflow::ActorPrototype* ChooseItemDialog::select(const QList& items) { listWidget->clear(); foreach(Workflow::ActorPrototype* a, items) { QListWidgetItem* it = new QListWidgetItem(a->getIcon(), a->getDisplayName()); it->setToolTip(a->getDocumentation()); listWidget->addItem(it); } listWidget->setItemSelected(listWidget->item(0), true); if (exec() == QDialog::Accepted) { return items.at(listWidget->currentRow()); } else { return NULL; } } }//namespace ugene-1.9.8/src/plugins/workflow_designer/src/WorkflowPalette.cpp0000644000175000017500000004526711651544324023763 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "WorkflowPalette.h" #include "CreateScriptWorker.h" #include "library/ScriptWorker.h" #include "library/ExternalProcessWorker.h" #include "library/CreateExternalProcessDialog.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include namespace U2 { const QString WorkflowPalette::MIME_TYPE("application/x-ugene-workflow-id"); class PaletteDelegate: public QItemDelegate { public: PaletteDelegate(WorkflowPalette *view) : QItemDelegate(view), m_view(view){} virtual void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const; virtual QSize sizeHint(const QStyleOptionViewItem &opt, const QModelIndex &index) const; private: WorkflowPalette *m_view; }; QTreeWidgetItem* WorkflowPalette::createItemWidget(QAction *a) { QTreeWidgetItem* item = new QTreeWidgetItem(); item->setToolTip(0, a->toolTip()); item->setData(0, Qt::UserRole, qVariantFromValue(a)); actionMap[a] = item; connect(a, SIGNAL(triggered()), SLOT(handleItemAction())); connect(a, SIGNAL(toggled(bool)), SLOT(handleItemAction())); return item; } void WorkflowPalette::handleItemAction() { QAction* a = qobject_cast(sender()); assert(a); assert(actionMap[a]); if (a) { update(indexFromItem(actionMap[a])); } } QAction* WorkflowPalette::createItemAction(ActorPrototype* item) { QAction* a = new QAction(item->getDisplayName(), this); a->setToolTip(item->getDocumentation()); a->setCheckable(true); if (item->getIcon().isNull()) { item->setIconPath(":workflow_designer/images/green_circle.png"); } a->setIcon(item->getIcon()); a->setData(qVariantFromValue(item)); connect(a, SIGNAL(triggered(bool)), SLOT(sl_selectProcess(bool))); connect(a, SIGNAL(toggled(bool)), SLOT(sl_selectProcess(bool))); return a; } void WorkflowPalette::sl_selectProcess(bool checked) { if (currentAction && currentAction != sender()) { currentAction->setChecked(false); } if (!checked) { currentAction = NULL; } else { currentAction = qobject_cast(sender()); assert(currentAction); } emit processSelected(currentAction ? qVariantValue(currentAction->data()) : NULL ); } void WorkflowPalette::resetSelection() { if (currentAction) { currentAction->setChecked(false); currentAction = NULL; } } void WorkflowPalette::rebuild() { setMouseTracking(false); resetSelection(); ActorPrototypeRegistry* reg = qobject_cast(sender()); if (reg) { QVariant v = saveState(); clear(); setContent(reg); restoreState(v); } setMouseTracking(true); } WorkflowPalette::WorkflowPalette(ActorPrototypeRegistry* reg, QWidget *parent) : QTreeWidget(parent), overItem(NULL), currentAction(NULL) { setFocusPolicy(Qt::NoFocus); setSelectionMode(QAbstractItemView::NoSelection); setItemDelegate(new PaletteDelegate(this)); setRootIsDecorated(false); //setAnimated(true); setMouseTracking(true); setColumnCount(1); header()->hide(); header()->setResizeMode(QHeaderView::Stretch); //setTextElideMode (Qt::ElideMiddle); setContent(reg); connect(reg, SIGNAL(si_registryModified()), SLOT(rebuild())); } void WorkflowPalette::setContent(ActorPrototypeRegistry* reg) { QMapIterator > it(reg->getProtos()); while (it.hasNext()) { it.next(); QTreeWidgetItem* category = new QTreeWidgetItem(this); category->setText(0, it.key().getDisplayName()); category->setData(0, Qt::UserRole, it.key().getId()); addTopLevelItem(category); foreach(ActorPrototype* proto, it.value()) { QAction* action = createItemAction(proto); int i = 0; while(category->child(i)) { QString s1 = category->child(i)->data(0,Qt::UserRole).value()->text(); QString s2 = action->text(); if(QString::compare(s1,s2, Qt::CaseInsensitive) > 0) { categoryMap[it.key().getDisplayName()] << action; category->insertChild(i,createItemWidget(action)); break; } i++; } if(!category->child(i)) { categoryMap[it.key().getDisplayName()] << action; category->addChild(createItemWidget(action)); } } } sortTree(); } void WorkflowPalette::sortTree() { sortItems(0,Qt::AscendingOrder); QString text = BaseActorCategories::CATEGORY_DATASRC().getDisplayName(); QTreeWidgetItem *item; if(!findItems(text,Qt::MatchExactly).isEmpty()) { item = findItems(text,Qt::MatchExactly).first(); takeTopLevelItem(indexFromItem(item).row()); insertTopLevelItem(0,item); } text = BaseActorCategories::CATEGORY_DATASINK().getDisplayName(); if(!findItems(text,Qt::MatchExactly).isEmpty()) { item = findItems(text,Qt::MatchExactly).first(); takeTopLevelItem(indexFromItem(item).row()); insertTopLevelItem(1,item); } text = BaseActorCategories::CATEGORY_SCRIPT().getDisplayName(); if(!findItems(text,Qt::MatchExactly).isEmpty()) { item = findItems(text,Qt::MatchExactly).first(); if(item) { takeTopLevelItem(indexFromItem(item).row()); addTopLevelItem(item); } } text = BaseActorCategories::CATEGORY_EXTERNAL().getDisplayName(); if (!findItems(text, Qt::MatchExactly).isEmpty()) { item = findItems(text, Qt::MatchExactly).first(); if (item) { takeTopLevelItem(indexFromItem(item).row()); addTopLevelItem(item); } } } QMenu* WorkflowPalette::createMenu(const QString& name) { QMenu* itemsMenu = new QMenu(name, this); QMenu *dataSink = NULL, *dataSource = NULL, *userScript = NULL, *externalTools = NULL; QAction *firstAction = NULL; QMapIterator > it(categoryMap); while (it.hasNext()) { it.next(); QMenu* grpMenu = new QMenu(it.key(), itemsMenu); QMap map; foreach(QAction* a, it.value()) { map[a->text()] = a; } QMapIterator jt(map); while(jt.hasNext()) { jt.next(); grpMenu->addAction(jt.value()); } if(it.key() == BaseActorCategories::CATEGORY_DATASRC().getDisplayName()) { dataSource = grpMenu; }else if (it.key() == BaseActorCategories::CATEGORY_DATASINK().getDisplayName()) { dataSink = grpMenu; } else if (it.key() == BaseActorCategories::CATEGORY_SCRIPT().getDisplayName()) { userScript = grpMenu; } else if (it.key() == BaseActorCategories::CATEGORY_EXTERNAL().getDisplayName()) { externalTools = grpMenu; } else { QAction * a = itemsMenu->addMenu(grpMenu); firstAction = firstAction ? firstAction : a; } } itemsMenu->insertMenu(firstAction, dataSource); itemsMenu->insertMenu(firstAction, dataSink); if (userScript) { itemsMenu->addMenu(userScript); } if (externalTools) { itemsMenu->addMenu(externalTools); } return itemsMenu; } void WorkflowPalette::mouseMoveEvent(QMouseEvent * event) { if (!hasMouseTracking()) return; if ((event->buttons() & Qt::LeftButton) && !dragStartPosition.isNull()) { if ((event->pos() - dragStartPosition).manhattanLength() <= QApplication::startDragDistance()) return; QTreeWidgetItem* item = itemAt(event->pos()); if (!item) return; QAction* action = qVariantValue(item->data(0, Qt::UserRole)); if (!action) return; ActorPrototype* proto = action->data().value(); assert(proto); QMimeData* mime = new QMimeData(); mime->setData(MIME_TYPE, proto->getId().toAscii()); mime->setText(proto->getId()); QDrag *drag = new QDrag(this); drag->setMimeData(mime); drag->setPixmap(action->icon().pixmap(QSize(44, 44))); resetSelection(); dragStartPosition = QPoint(); Qt::DropAction dropAction = drag->exec(Qt::CopyAction, Qt::CopyAction); Q_UNUSED(dropAction); return; } QTreeWidgetItem* prev = overItem; overItem = itemAt(event->pos()); if (prev) { update(indexFromItem(prev)); } if (overItem) { update(indexFromItem(overItem)); } QTreeWidget::mouseMoveEvent(event); } void WorkflowPalette::leaveEvent(QEvent *) { if (!hasMouseTracking()) { return; } QTreeWidgetItem* prev = overItem; overItem = NULL; if (prev) { QModelIndex index = indexFromItem(prev); update(index); }; } void WorkflowPalette::mousePressEvent(QMouseEvent * event) { if (!hasMouseTracking()) return; dragStartPosition = QPoint(); if ((event->buttons() & Qt::LeftButton)) { QTreeWidgetItem* item = itemAt(event->pos()); if (!item) return; event->accept(); if (item->parent() == 0) { setItemExpanded(item, !isItemExpanded(item)); return; } QAction* action = qVariantValue(item->data(0, Qt::UserRole)); if (action) { action->toggle(); dragStartPosition = event->pos(); } } } void WorkflowPalette::contextMenuEvent(QContextMenuEvent *e) { QMenu menu; menu.addAction(tr("Expand all"), this, SLOT(expandAll())); menu.addAction(tr("Collapse all"), this, SLOT(collapseAll())); if(itemAt(e->pos()) && itemAt(e->pos())->parent() && (itemAt(e->pos())->parent()->text(0) == BaseActorCategories::CATEGORY_SCRIPT().getDisplayName() || itemAt(e->pos())->parent()->text(0) == BaseActorCategories::CATEGORY_EXTERNAL().getDisplayName())) { menu.addAction(tr("Edit"), this, SLOT(editElement())); menu.addAction(tr("Remove"), this, SLOT(removeElement())); currentAction = actionMap.key(itemAt(e->pos())); } e->accept(); menu.exec(mapToGlobal(e->pos())); } void WorkflowPalette::removeElement() { QMessageBox msg(this); msg.setWindowTitle("Remove element"); msg.setText("Remove this element?"); msg.addButton(QMessageBox::Ok); msg.addButton(QMessageBox::Cancel); if(msg.exec() == QMessageBox::Cancel) { return; } ActorPrototype *proto = currentAction->data().value(); QString path = WorkflowSettings::getUserDirectory(); QString fileName = path + proto->getDisplayName() + ".usa"; //use constant if(!QFile::exists(fileName)) { fileName = WorkflowSettings::getExternalToolDirectory() + proto->getDisplayName() + ".etc"; } QFile::setPermissions(fileName, QFile::ReadOwner | QFile::WriteOwner); if(!QFile::remove(fileName)) { uiLog.error(tr("Can't remove element %1").arg(proto->getDisplayName())); return; } QString id = proto->getId(); emit si_protoDeleted(id); ActorPrototypeRegistry *reg = WorkflowEnv::getProtoRegistry(); assert(reg); reg->unregisterProto(id); } void WorkflowPalette::editElement() { ActorPrototype *proto = currentAction->data().value(); QString oldName = proto->getDisplayName(); ActorPrototypeRegistry *reg = WorkflowEnv::getProtoRegistry(); QMap > categories = reg->getProtos(); if(categories.value(BaseActorCategories::CATEGORY_SCRIPT()).contains(proto)) { CreateScriptElementDialog dlg(this, proto); if(dlg.exec() == QDialog::Accepted) { ActorPrototypeRegistry *reg = WorkflowEnv::getProtoRegistry(); assert(reg); QList input = dlg.getInput(); QList output = dlg.getOutput(); QList attrs = dlg.getAttributes(); QString name = dlg.getName(); QString desc = dlg.getDescription(); if(oldName != name) { removeElement(); } else { QString id = proto->getId(); emit si_protoDeleted(id); reg->unregisterProto(proto->getId()); } LocalWorkflow::ScriptWorkerFactory::init(input, output, attrs, name,desc); } } else { //External process category ExternalProcessConfig *cfg = WorkflowEnv::getExternalCfgRegistry()->getConfigByName(proto->getId()); CreateExternalProcessDialog dlg(this, cfg); if(dlg.exec() == QDialog::Accepted) { cfg = dlg.config(); WorkflowEnv::getExternalCfgRegistry()->unregisterConfig(oldName); WorkflowEnv::getExternalCfgRegistry()->registerExternalTool(cfg); if(oldName != cfg->name) { removeElement(); } else { QString id = proto->getId(); emit si_protoDeleted(id); reg->unregisterProto(proto->getId()); } LocalWorkflow::ExternalProcessWorkerFactory::init(cfg); } } } void PaletteDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const { const QAbstractItemModel *model = index.model(); Q_ASSERT(model); if (!model->parent(index).isValid()) { // this is a top-level item. QStyleOptionButton buttonOption; buttonOption.state = option.state; #ifdef Q_WS_MAC buttonOption.state |= QStyle::State_Raised; #endif buttonOption.state &= ~QStyle::State_HasFocus; buttonOption.rect = option.rect; buttonOption.palette = option.palette; buttonOption.features = QStyleOptionButton::None; m_view->style()->drawControl(QStyle::CE_PushButton, &buttonOption, painter, m_view); QStyleOption branchOption; static const int i = 9; // ### hardcoded in qcommonstyle.cpp QRect r = option.rect; branchOption.rect = QRect(r.left() + i/2, r.top() + (r.height() - i)/2, i, i); branchOption.palette = option.palette; branchOption.state = QStyle::State_Children; if (m_view->isExpanded(index)) branchOption.state |= QStyle::State_Open; m_view->style()->drawPrimitive(QStyle::PE_IndicatorBranch, &branchOption, painter, m_view); // draw text QRect textrect = QRect(r.left() + i*2, r.top(), r.width() - ((5*i)/2), r.height()); QString text = elidedText(option.fontMetrics, textrect.width(), Qt::ElideMiddle, model->data(index, Qt::DisplayRole).toString()); m_view->style()->drawItemText(painter, textrect, Qt::AlignCenter, option.palette, m_view->isEnabled(), text); } else { QStyleOptionToolButton buttonOption; buttonOption.state = option.state; buttonOption.state &= ~QStyle::State_HasFocus; buttonOption.direction = option.direction; buttonOption.rect = option.rect; buttonOption.font = option.font; buttonOption.fontMetrics = option.fontMetrics; buttonOption.palette = option.palette; buttonOption.subControls = QStyle::SC_ToolButton; buttonOption.features = QStyleOptionToolButton::None; QAction* action = qVariantValue(index.data(Qt::UserRole)); buttonOption.text = action->text(); buttonOption.icon = action->icon(); if (!buttonOption.icon.isNull()) { buttonOption.iconSize = QSize(22, 22); } if (action->isChecked()) { buttonOption.state |= QStyle::State_On; buttonOption.state |= QStyle::State_Sunken; buttonOption.activeSubControls = QStyle::SC_ToolButton; } else { buttonOption.state |= QStyle::State_Raised; buttonOption.activeSubControls = QStyle::SC_None; } if (m_view->overItem == m_view->itemFromIndex(index)) { buttonOption.state |= QStyle::State_MouseOver; } buttonOption.state |= QStyle::State_AutoRaise; buttonOption.toolButtonStyle = Qt::ToolButtonTextBesideIcon; m_view->style()->drawComplexControl(QStyle::CC_ToolButton, &buttonOption, painter, m_view); //QItemDelegate::paint(painter, option, index); } } QSize PaletteDelegate::sizeHint(const QStyleOptionViewItem &opt, const QModelIndex &index) const { const QAbstractItemModel *model = index.model(); Q_ASSERT(model); QStyleOptionViewItem option = opt; bool top = !model->parent(index).isValid(); QSize sz = QItemDelegate::sizeHint(opt, index) + QSize(top?2:20, top?2:20); return sz; } QVariant WorkflowPalette::saveState() const { QVariantMap m; for (int i = 0, count = topLevelItemCount(); i < count; ++i) { QTreeWidgetItem* it = topLevelItem(i); m.insert(it->data(0, Qt::UserRole).toString(), it->isExpanded()); } return m; } void WorkflowPalette::restoreState(const QVariant& v) { QMapIterator it(v.toMap()); while (it.hasNext()) { it.next(); for (int i = 0; i < topLevelItemCount(); i++) { if (topLevelItem(i)->data(0, Qt::UserRole) == it.key()) { topLevelItem(i)->setExpanded(it.value().toBool()); break; } } } } }//namespace ugene-1.9.8/src/plugins/workflow_designer/src/WorkflowSamples.cpp0000644000175000017500000002676411651544324023772 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "WorkflowSamples.h" #include "WorkflowViewController.h" #include "HRSceneSerializer.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include Q_DECLARE_METATYPE(QTextDocument*); namespace U2 { const QString SamplesWidget::MIME_TYPE("application/x-ugene-sample-id"); QList SampleRegistry::data; #define DATA_ROLE Qt::UserRole #define INFO_ROLE Qt::UserRole + 1 #define ICON_ROLE Qt::UserRole + 2 #define DOC_ROLE Qt::UserRole + 3 class SampleDelegate : public QStyledItemDelegate { public: SampleDelegate(QObject* parent = 0) : QStyledItemDelegate(parent){} QSize sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const { QVariant value = index.data(Qt::SizeHintRole); if (value.isValid()) return qvariant_cast(value); QStyleOptionViewItemV4 opt = option; initStyleOption(&opt, index); const QWidget *widget = qobject_cast(parent());//QStyledItemDelegatePrivate::widget(option); QStyle *style = widget ? widget->style() : QApplication::style(); opt.rect.setSize(widget->size()); return style->sizeFromContents(QStyle::CT_ItemViewItem, &opt, QSize(), widget); } // void QStyledItemDelegate::paint(QPainter *painter, // const QStyleOptionViewItem &option, const QModelIndex &index) const // { // Q_ASSERT(index.isValid()); // // QStyleOptionViewItemV4 opt = option; // initStyleOption(&opt, index); // // const QWidget *widget = qobject_cast(parent());//QStyledItemDelegatePrivate::widget(option); // QStyle *style = widget ? widget->style() : QApplication::style(); // style->drawControl(QStyle::CE_ItemViewItem, &opt, painter, widget); // } /*void initStyleOption(QStyleOptionViewItem *option, const QModelIndex &index) const { QStyledItemDelegate::initStyleOption(option, index); QWidget* owner; if ((owner = qobject_cast(parent()))) { option->rect.setWidth(owner->width()); option->rect.setHeight(0); } // QVariant value = index.data(Qt::FontRole); // if (value.isValid() && !value.isNull()) { // option->font = qvariant_cast(value).resolve(option->font); // option->fontMetrics = QFontMetrics(option->font); // } // // value = index.data(Qt::TextAlignmentRole); // if (value.isValid() && !value.isNull()) // option->displayAlignment = (Qt::Alignment)value.toInt(); // // value = index.data(Qt::ForegroundRole); // if (qVariantCanConvert(value)) // option->palette.setBrush(QPalette::Text, qvariant_cast(value)); if (QStyleOptionViewItemV2 *v2 = qstyleoption_cast(option)) { v2->features |= QStyleOptionViewItemV2::WrapText; } }*/ }; SamplesWidget::SamplesWidget(WorkflowScene *scene, QWidget *parent) : QTreeWidget(parent) { setColumnCount(1); //header()->hide(); setHeaderHidden(true); setItemDelegate(new SampleDelegate(this)); setWordWrap(true); foreach(const SampleCategory& cat, SampleRegistry::getCategories()) { addCategory(cat); } expandAll(); glass = new SamplePane(scene); //connect(this, SIGNAL(itemActivated(QTreeWidgetItem*,int)), SLOT(handleItem(QTreeWidgetItem*))); connect(this, SIGNAL(currentItemChanged(QTreeWidgetItem*,QTreeWidgetItem*)), SLOT(handleTreeItem(QTreeWidgetItem*))); //connect(this, SIGNAL(itemSelectionChanged()), glass, SLOT(test())); connect(this, SIGNAL(itemDoubleClicked(QTreeWidgetItem*, int)), SLOT(activateItem(QTreeWidgetItem*))); connect(glass, SIGNAL(itemActivated(QTreeWidgetItem*)), SLOT(activateItem(QTreeWidgetItem*))); connect(glass, SIGNAL(cancel()), SLOT(cancelItem())); } void SamplesWidget::activateItem(QTreeWidgetItem * item) { if (item && item->data(0, DATA_ROLE).isValid()) { emit sampleSelected(item->data(0, DATA_ROLE).toString()); } } void SamplesWidget::handleTreeItem(QTreeWidgetItem * item) { // bool show = false; if (item && !item->data(0, DATA_ROLE).isValid()) { item = NULL; // glass->setItem(item); // show = true; } // emit setupGlass(show ? glass : NULL); glass->setItem(item); emit setupGlass(glass); } void SamplesWidget::cancelItem() { selectionModel()->clear(); if (isHidden()) { emit setupGlass(NULL); glass->setItem(NULL); } else { emit setupGlass(glass); } } void SamplesWidget::addCategory( const SampleCategory& cat ) { QTreeWidgetItem* ci = new QTreeWidgetItem(this, QStringList(cat.d.getDisplayName())); ci->setFlags(Qt::ItemIsEnabled); QFont cf; cf.setBold(true); ci->setData(0, Qt::FontRole, cf); ci->setData(0, Qt::BackgroundRole, QColor(255,255,160, 127)); //QFont sf; //sf.setBold(true); //sf.setItalic(true); foreach(const Sample& item, cat.items) { QTreeWidgetItem* ib = new QTreeWidgetItem(ci, QStringList(item.d.getDisplayName())); ib->setData(0, DATA_ROLE, item.content); //ib->setData(0, ICON_ROLE, item.ico.pixmap(200)); //ib->setData(0, INFO_ROLE, qVariantFromValue(item.d)); QTextDocument* doc = new QTextDocument(this); ib->setData(0, DOC_ROLE, qVariantFromValue(doc)); //ib->setData(0, Qt::FontRole, sf); Descriptor d = item.d; QIcon ico = item.ico; if (ico.isNull()) { ico.addPixmap(SaveSchemaImageUtils::generateSchemaSnapshot(item.content.toUtf8())); } DesignerGUIUtils::setupSamplesDocument(d, ico, doc); } } void SamplePane::setItem(QTreeWidgetItem* it) { item = it; // if (!item) { // m_document->clear(); // return; // } // Descriptor d = it->data(0, INFO_ROLE).value(); // QString text = // "" // "" // "" // "" // "" // "

    %1

    %3
    %4
    " // ""; // QString img("img://img"); // m_document->addResource(QTextDocument::ImageResource, QUrl(img), it->data(0, ICON_ROLE)); // // //QString img = QString("
    "); // QString body = Qt::escape(d.getDocumentation()).replace("\n", "
    "); // text = text.arg(d.getDisplayName()).arg(img).arg(body).arg(tr("Double click to load the sample")); // m_document->setHtml(text); } void SamplePane::test() { uiLog.error("Acha!!!"); } void SamplePane::mouseDoubleClickEvent( QMouseEvent *e) { if (!item) { return; } QTextDocument* doc = item->data(0, DOC_ROLE).value(); int pageWidth = qMax(width() - 100, 100); int pageHeight = qMax(height() - 100, 100); if (pageWidth != doc->pageSize().width()) { doc->setPageSize(QSize(pageWidth, pageHeight)); } QSize ts = doc->size().toSize(); QRect textRect; textRect.setSize(ts); QPoint position = e->pos(); if(textRect.contains(position)) { emit itemActivated(item); } else { item = NULL; scene->update(); } } void SamplePane::keyPressEvent(QKeyEvent * event ){ if (event->key() == Qt::Key_Escape) { emit cancel(); } else if (event->key() == Qt::Key_Enter) { emit itemActivated(item); } } SamplePane::SamplePane(WorkflowScene *_scene) : item(NULL), scene(_scene) { m_document = new QTextDocument(this); } void SamplePane::paint(QPainter* painter) { if (!item && !scene->items().size()) { DesignerGUIUtils::paintSamplesArrow(painter); return; } if(item) { QTextDocument* doc = item->data(0, DOC_ROLE).value(); DesignerGUIUtils::paintSamplesDocument(painter, doc, width(), height(), palette()); } } LoadSamplesTask::LoadSamplesTask( const QStringList& lst) : Task(tr("Load workflow samples"), TaskFlag_None), dirs(lst) {} void LoadSamplesTask::run() { foreach(const QString& s, dirs) { scanDir(s); } } void LoadSamplesTask::scanDir( const QString& s) { QDir dir(s); if (!dir.exists()) { ioLog.error(tr("Sample dir does not exist: %1").arg(s)); return; } SampleCategory category(s,dir.dirName()); QStringList names; foreach(const QString & ext, WorkflowUtils::WD_FILE_EXTENSIONS) { names << "*." + ext; } foreach(const QFileInfo& fi, dir.entryInfoList(names, QDir::Files|QDir::NoSymLinks)) { QFile f(fi.absoluteFilePath()); if(!f.open(QIODevice::ReadOnly)) { ioLog.error(tr("Failed to load sample: %1").arg(L10N::errorOpeningFileRead(fi.absoluteFilePath()))); continue; } QTextStream in(&f); in.setCodec("UTF-8"); Sample sample; sample.content = in.readAll(); Metadata meta; QString err = HRSceneSerializer::string2Scene(sample.content, NULL, &meta); if(!err.isEmpty()) { coreLog.error(tr("Failed to load sample: %1").arg(err)); continue; } sample.d = Descriptor(fi.absoluteFilePath(), meta.name.isEmpty()? fi.baseName() : meta.name, meta.comment); QString icoName = dir.absoluteFilePath(fi.baseName() + ".png"); if (QFile::exists(icoName)) { sample.ico.addFile(icoName); } category.items << sample; } if (!category.items.isEmpty()) { result << category; } foreach(const QFileInfo& fi, dir.entryInfoList(QStringList(), QDir::AllDirs|QDir::NoSymLinks|QDir::NoDotAndDotDot)) { scanDir(fi.absoluteFilePath()); } } Task::ReportResult LoadSamplesTask::report() { SampleRegistry::data = result; return ReportResult_Finished; } Task* SampleRegistry::init( const QStringList& lst) { return new LoadSamplesTask(lst); } } //namespace ugene-1.9.8/src/plugins/workflow_designer/src/HRSceneSerializer.cpp0000644000175000017500000006220711651544324024144 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include #include #include #include "ItemViewStyle.h" #include "HRSceneSerializer.h" #include namespace U2 { static const QString DESCRIPTION_ATTR = "description"; static const QString TOOLTIP_ATTR = "tooltip"; static const QString POSITION_ATTR = "pos"; static const QString STYLE_ATTR = "style"; static const QString BG_COLOR = "bg-color-"; static const QString FONT = "font-"; static const QString BOUNDS = "bounds"; static const QString PORT_ANGLE = "angle"; static const QString TEXT_POS_ATTR = "text-pos"; const QString UNEXPECTED_END_OF_FILE = HRSceneSerializer::tr("Unexpected end of file"); /*************************************** * Writing support ***************************************/ using namespace U2; static const int VISUAL_BLOCK_TABS_NUM = 4; static QString point2String(const QPointF & point) { return QString("%1 %2").arg(point.x()).arg(point.y()); } static QString rect2String(const QRectF & rect) { return QString("%1 %2").arg(point2String(rect.topLeft())).arg(point2String(rect.bottomRight())); } static QString extendedStyleData(ExtendedProcStyle * style) { QString res; if(style == NULL) { return res; } if( !style->isAutoResized() ) { res += HRSchemaSerializer::makeEqualsPair(BOUNDS, rect2String(style->boundingRect()), VISUAL_BLOCK_TABS_NUM); } return res; } static QString color2String(const QColor & color) { return QString("%1 %2 %3 %4").arg(color.red()).arg(color.green()).arg(color.blue()).arg(color.alpha()); } static QString styleData(ItemViewStyle * style) { QString res; if( style == NULL ) { return res; } if( style->getBgColor() != style->defaultColor() ) { res += HRSchemaSerializer::makeEqualsPair(BG_COLOR + style->getId(), color2String(style->getBgColor()), VISUAL_BLOCK_TABS_NUM); } if( style->defaultFont() != QFont() ) { res += HRSchemaSerializer::makeEqualsPair(FONT + style->getId(), style->defaultFont().toString(), VISUAL_BLOCK_TABS_NUM); } return res; } static QString actorVisualData(WorkflowProcessItem * procItem) { assert(procItem != NULL); QString res; QString descStr = procItem->getProcess()->getDescription()->toHtml().replace(HRSchemaSerializer::NEW_LINE, " "); res += HRSchemaSerializer::makeEqualsPair(DESCRIPTION_ATTR, descStr, VISUAL_BLOCK_TABS_NUM); res += HRSchemaSerializer::makeEqualsPair(TOOLTIP_ATTR, procItem->toolTip().replace(HRSchemaSerializer::NEW_LINE, " "), VISUAL_BLOCK_TABS_NUM); res += HRSchemaSerializer::makeEqualsPair(POSITION_ATTR, point2String(procItem->pos()), VISUAL_BLOCK_TABS_NUM); res += HRSchemaSerializer::makeEqualsPair(STYLE_ATTR, procItem->getStyle(), VISUAL_BLOCK_TABS_NUM); res += styleData(procItem->getStyleById(ItemStyles::SIMPLE)); res += styleData(procItem->getStyleById(ItemStyles::EXTENDED)); res += extendedStyleData(qobject_cast(procItem->getStyleByIdSafe(ItemStyles::EXTENDED))); foreach(WorkflowPortItem * pit, procItem->getPortItems()) { res += HRSchemaSerializer::makeEqualsPair(pit->getPort()->getId() + HRSchemaSerializer::DOT + PORT_ANGLE, QString::number(pit->getOrientarion()), VISUAL_BLOCK_TABS_NUM ); } return res; } static QString linkVisualData(WorkflowBusItem * link) { return HRSchemaSerializer::makeEqualsPair(TEXT_POS_ATTR, point2String(link->getText()->pos()), 4); } static QString visualData(const QList & items, const HRSchemaSerializer::NamesMap& nmap) { assert(!items.isEmpty()); QString res; foreach( QGraphicsItem * item, items ) { switch(item->type()) { case WorkflowProcessItemType: { WorkflowProcessItem * procItem = qgraphicsitem_cast(item); res += HRSchemaSerializer::makeBlock(nmap[procItem->getProcess()->getId()], HRSchemaSerializer::NO_NAME, actorVisualData(procItem), 3); break; } case WorkflowBusItemType: { WorkflowBusItem * busItem = static_cast(item); Port * src = busItem->getBus()->source(); Port * dst = busItem->getBus()->destination(); res += HRSchemaSerializer::makeBlock(HRSchemaSerializer::makeArrowPair(nmap[src->owner()->getId()] + HRSchemaSerializer::DOT + src->getId(), nmap[dst->owner()->getId()] + HRSchemaSerializer::DOT + dst->getId(), 0), HRSchemaSerializer::NO_NAME, linkVisualData(busItem), 3); break; } } } return res; } static QString metaData(WorkflowScene * scene, const HRSchemaSerializer::NamesMap& nmap) { assert(scene != NULL); QString res; Schema schema = scene->getSchema(); if(schema.hasParamAliases()) { res += HRSchemaSerializer::makeBlock(HRSchemaSerializer::ALIASES_START, HRSchemaSerializer::NO_NAME, HRSchemaSerializer::schemaAliases(schema.getProcesses(), nmap), 2); } if(schema.hasAliasHelp()) { res += HRSchemaSerializer::makeBlock(HRSchemaSerializer::ALIASES_HELP_START, HRSchemaSerializer::NO_NAME, HRSchemaSerializer::aliasesHelp(schema.getProcesses()), 2); } res += HRSchemaSerializer::makeBlock(HRSchemaSerializer::VISUAL_START, HRSchemaSerializer::NO_NAME, visualData(scene->items(), nmap), 2); return res; } static QString bodyItself(WorkflowScene * scene) { assert(scene); QString res; Schema schema = scene->getSchema(); HRSchemaSerializer::NamesMap nmap = HRSchemaSerializer::generateElementNames(schema.getProcesses()); res += HRSchemaSerializer::elementsDefinition(schema.getProcesses(), nmap); res += HRSchemaSerializer::dataflowDefinition(schema.getProcesses(), nmap); res += HRSchemaSerializer::iterationsDefinition(schema.getIterations(), nmap); res += HRSchemaSerializer::makeBlock(HRSchemaSerializer::META_START, HRSchemaSerializer::NO_NAME, metaData(scene, nmap)); return res; } QString HRSceneSerializer::scene2String(WorkflowScene * scene, const Metadata & meta) { assert(scene != NULL); QString res; HRSchemaSerializer::addPart(res, HRSchemaSerializer::header2String(&meta)); HRSchemaSerializer::addPart(res, HRSchemaSerializer::makeBlock(HRSchemaSerializer::BODY_START, meta.name, bodyItself(scene), 0, true)); return res; } static QString itemsMeta(const QList & procs, const QList & items, const HRSchemaSerializer::NamesMap& nmap) { QString res; bool hasAliases = false; foreach(Actor * a, procs) { if(a->hasParamAliases()) { hasAliases = true; break; } } if(hasAliases) { res += HRSchemaSerializer::makeBlock(HRSchemaSerializer::ALIASES_START, HRSchemaSerializer::NO_NAME, HRSchemaSerializer::schemaAliases(procs, nmap), 2); } bool hasAliasHelp = false; foreach(Actor * a, procs) { if(a->hasAliasHelp()) { hasAliasHelp = true; break; } } if(hasAliasHelp) { res += HRSchemaSerializer::makeBlock(HRSchemaSerializer::ALIASES_HELP_START, HRSchemaSerializer::NO_NAME, HRSchemaSerializer::aliasesHelp(procs), 2); } return res + HRSchemaSerializer::makeBlock(HRSchemaSerializer::VISUAL_START, HRSchemaSerializer::NO_NAME, visualData(items, nmap)); } static QString itemsItself(const QList & items, const QList & iterations) { QList procs; foreach(QGraphicsItem * it, items) { if(it->type() == WorkflowProcessItemType) { procs << qgraphicsitem_cast(it)->getProcess(); } } QString res; HRSchemaSerializer::NamesMap nmap = HRSchemaSerializer::generateElementNames(procs); res += HRSchemaSerializer::elementsDefinition(procs, nmap); res += HRSchemaSerializer::dataflowDefinition(procs, nmap); res += HRSchemaSerializer::iterationsDefinition(iterations, nmap, false); res += HRSchemaSerializer::makeBlock(HRSchemaSerializer::META_START, HRSchemaSerializer::NO_NAME, itemsMeta(procs, items, nmap)); return res; } QString HRSceneSerializer::items2String(const QList & items, const QList & iterations) { assert(!items.isEmpty()); QString res; HRSchemaSerializer::addPart(res, HRSchemaSerializer::header2String(NULL)); HRSchemaSerializer::addPart(res, HRSchemaSerializer::makeBlock(HRSchemaSerializer::BODY_START, HRSchemaSerializer::NO_NAME, itemsItself(items, iterations), 0, true)); return res; } /*************************************** * Reading support ***************************************/ struct WorkflowSceneReaderData { WorkflowSceneReaderData(const QString & bytes, WorkflowScene * s, Metadata * m, bool se, bool ni) : scene(s), meta(m), select(se), pasteMode(ni) { tokenizer.tokenize(bytes); } HRSchemaSerializer::Tokenizer tokenizer; WorkflowScene * scene; Metadata * meta; bool select; // (actor name in file, created actor) QMap actorMap; // (actor name in file, created proc item) QMap procMap; QList iterations; QList > dataflowLinks; bool pasteMode; struct LinkData { LinkData(WorkflowPortItem * s, WorkflowPortItem * d) : src(s), dst(d) {} bool operator ==(const LinkData & data) const {return src == data.src && dst == data.dst;} WorkflowPortItem * src; WorkflowPortItem * dst; HRSchemaSerializer::ParsedPairs pairs; }; QList links; }; // WorkflowSceneReaderData static void parseActorDefinition(WorkflowSceneReaderData & data, const QString & actorName) { Actor * proc = HRSchemaSerializer::parseElementsDefinition(data.tokenizer, actorName, data.actorMap); WorkflowProcessItem * procIt = new WorkflowProcessItem(proc); data.scene->addItem(procIt); data.procMap[actorName] = procIt; if(data.select) { procIt->setSelected(true); } } static QPointF string2Point( const QString & str ) { QStringList list = str.split(QRegExp("\\s"), QString::SkipEmptyParts); if(list.size() != 2) { throw HRSchemaSerializer::ReadFailed(HRSceneSerializer::tr("Cannot parse coordinates from '%1'").arg(str)); } bool ok = false; qreal x = list.at(0).toDouble(&ok); if(!ok) { throw HRSchemaSerializer::ReadFailed(HRSceneSerializer::tr("Cannot parse real value from '%1'").arg(list.at(0))); } ok = false; qreal y = list.at(1).toDouble(&ok); if(!ok) { throw HRSchemaSerializer::ReadFailed(HRSceneSerializer::tr("Cannot parse real value from '%1'").arg(list.at(1))); } return QPointF(x, y); } static QColor string2Color(const QString & str) { int r = 0, g = 0, b = 0, a = 0; QTextStream stream(str.toAscii()); stream >> r >> g >> b >> a; if(stream.status() != QTextStream::Ok) { throw HRSchemaSerializer::ReadFailed(HRSceneSerializer::tr("Cannot parse 4 integer numbers from '%1'").arg(str)); } return QColor(r, g, b, a); } static void parseStyleData(HRSchemaSerializer::ParsedPairs & pairs, ItemViewStyle * style) { if( style == NULL ) { return; } QString bgColor = pairs.equalPairs.take(BG_COLOR + style->getId()); if(!bgColor.isEmpty()) { style->setBgColor(string2Color(bgColor)); } QString font = pairs.equalPairs.take(FONT + style->getId()); if(!font.isEmpty()) { QFont f; if(!f.fromString(font)) { throw HRSchemaSerializer::ReadFailed(HRSceneSerializer::tr("Cannot parse font from '%1'").arg(font)); } style->setDefaultFont(f); } } static QRectF string2Rect(const QString & str) { QStringList list = str.split(QRegExp("\\s")); if( list.size() != 4 ) { throw HRSchemaSerializer::ReadFailed(HRSceneSerializer::tr("Cannot parse rectangle from '%1'").arg(str)); } return QRectF(string2Point(list.at(0) + " " + list.at(1)), string2Point(list.at(2) + " " + list.at(3))); } static void parseExtendedStyleData(HRSchemaSerializer::ParsedPairs & pairs, ExtendedProcStyle * style) { if(style == NULL) { return; } QString bounds = pairs.equalPairs.take(BOUNDS); if(!bounds.isEmpty()) { style->setFixedBounds(string2Rect(bounds)); } } static void parseVisualActorParams(WorkflowSceneReaderData & data, const QString & actorName) { if(!data.actorMap.contains(actorName)) { throw HRSchemaSerializer::ReadFailed(HRSceneSerializer::tr("%1 element undefined in visual block").arg(actorName)); } HRSchemaSerializer::ParsedPairs pairs(data.tokenizer); if(!pairs.blockPairs.isEmpty()) { throw HRSchemaSerializer::ReadFailed(HRSceneSerializer::tr("No other blocks allowed in visual block '%1'").arg(actorName)); } WorkflowProcessItem * procItem = data.procMap.value(actorName); assert(procItem != NULL); // TODO: support custom descriptions QString description = pairs.equalPairs.take(DESCRIPTION_ATTR); Q_UNUSED(description); /*if( !description.isEmpty() ) { }*/ QString tooltip = pairs.equalPairs.take(TOOLTIP_ATTR); if(!tooltip.isEmpty()) { procItem->setToolTip(tooltip); } QString position = pairs.equalPairs.take(POSITION_ATTR); if( !position.isEmpty() ) { procItem->setPos(string2Point(position)); } QString style = pairs.equalPairs.take(STYLE_ATTR); if(!style.isEmpty()) { if( !procItem->containsStyle(style) ) { coreLog.details(HRSceneSerializer::tr("%1 does not has %2 style").arg(actorName).arg(style)); } else { procItem->setStyle(style); } } parseStyleData(pairs, procItem->getStyleById(ItemStyles::SIMPLE)); parseStyleData(pairs, procItem->getStyleById(ItemStyles::EXTENDED)); parseExtendedStyleData(pairs, qobject_cast(procItem->getStyleById(ItemStyles::EXTENDED))); foreach( const QString & key, pairs.equalPairs.keys() ) { QStringList list = key.split(HRSchemaSerializer::DOT); if(list.size() == 2 && list.at(1) == PORT_ANGLE) { QString portId = list.at(0); WorkflowPortItem * portItem = procItem->getPort(portId); if(portItem == NULL) { throw HRSchemaSerializer::ReadFailed(HRSceneSerializer::tr("Cannot find port '%1' at %2 element").arg(portId).arg(actorName)); } bool ok = false; QString strVal = pairs.equalPairs.value(key); qreal orientation = strVal.toDouble(&ok); if(!ok) { throw HRSchemaSerializer::ReadFailed(HRSceneSerializer::tr("Cannot parse real number from: '%1'").arg(strVal)); } portItem->setOrientation(orientation); } else { coreLog.details(HRSceneSerializer::tr("Undefined visual key: '%1' for actor %2").arg(key).arg(actorName)); } } } static void parseLinkVisualBlock(WorkflowSceneReaderData & data, const QString & from, const QString & to) { bool hasBlock = data.tokenizer.look() == HRSchemaSerializer::BLOCK_START; QString srcActorName = HRSchemaSerializer::parseAt(from, 0); Actor * srcActor = data.actorMap.value(srcActorName); if(srcActor == NULL) { throw HRSchemaSerializer::ReadFailed(HRSceneSerializer::tr("Undefined element id: '%1'").arg(srcActorName)); } QString srcPortId = HRSchemaSerializer::parseAt(from, 1); Port * srcPort = srcActor->getPort(srcPortId); if(srcPort == NULL) { throw HRSchemaSerializer::ReadFailed(HRSceneSerializer::tr("Cannot find '%1' port at '%2'").arg(srcPortId).arg(srcActorName)); } QString dstActorName = HRSchemaSerializer::parseAt(to, 0); Actor * dstActor = data.actorMap.value(dstActorName); if(dstActor == NULL) { throw HRSchemaSerializer::ReadFailed(HRSceneSerializer::tr("Undefined element id: '%1'").arg(dstActorName)); } QString dstPortId = HRSchemaSerializer::parseAt(to, 1); Port * dstPort = dstActor->getPort(dstPortId); if(dstPort == NULL) { throw HRSchemaSerializer::ReadFailed(HRSceneSerializer::tr("Cannot find '%1' port at '%2'").arg(dstPortId).arg(dstActorName)); } WorkflowSceneReaderData::LinkData link(data.procMap[srcActorName]->getPort(srcPortId), data.procMap[dstActorName]->getPort(dstPortId)); if(hasBlock) { data.tokenizer.assertToken(HRSchemaSerializer::BLOCK_START); HRSchemaSerializer::ParsedPairs pairs(data.tokenizer); data.tokenizer.assertToken(HRSchemaSerializer::BLOCK_END); if( !pairs.blockPairs.isEmpty() ) { throw HRSchemaSerializer::ReadFailed(HRSceneSerializer::tr("No other blocks allowed in link parameters block '%1'"). arg(HRSchemaSerializer::makeArrowPair(from, to, 0))); } link.pairs = pairs; } data.links << link; } static void parseVisual(WorkflowSceneReaderData & data) { while(data.tokenizer.look() != HRSchemaSerializer::BLOCK_END) { QString tok = data.tokenizer.take(); QString next = data.tokenizer.take(); if(next == HRSchemaSerializer::BLOCK_START) { QString actorName = str2aid(tok); parseVisualActorParams(data, actorName); data.tokenizer.assertToken(HRSchemaSerializer::BLOCK_END); } else if(next == HRSchemaSerializer::DATAFLOW_SIGN) { QString to = data.tokenizer.take(); parseLinkVisualBlock(data, tok, to); } } } static void parseMeta(WorkflowSceneReaderData & data) { while(data.tokenizer.look() != HRSchemaSerializer::BLOCK_END) { QString tok = data.tokenizer.take(); if(tok == HRSchemaSerializer::ALIASES_START) { data.tokenizer.assertToken(HRSchemaSerializer::BLOCK_START); HRSchemaSerializer::parseAliases(data.tokenizer, data.actorMap); data.tokenizer.assertToken(HRSchemaSerializer::BLOCK_END); } else if(tok == HRSchemaSerializer::VISUAL_START) { data.tokenizer.assertToken(HRSchemaSerializer::BLOCK_START); parseVisual(data); data.tokenizer.assertToken(HRSchemaSerializer::BLOCK_END); } else if(tok == HRSchemaSerializer::ALIASES_HELP_START) { data.tokenizer.assertToken(HRSchemaSerializer::BLOCK_START); HRSchemaSerializer::parseAliasesHelp(data.tokenizer, data.actorMap.values()); data.tokenizer.assertToken(HRSchemaSerializer::BLOCK_END); } else { throw HRSchemaSerializer::ReadFailed(HRSchemaSerializer::UNDEFINED_META_BLOCK.arg(tok)); } } } static void parseBodyItself(WorkflowSceneReaderData & data) { HRSchemaSerializer::Tokenizer & tokenizer = data.tokenizer; while(tokenizer.notEmpty() && tokenizer.look() != HRSchemaSerializer::BLOCK_END) { QString tok = tokenizer.take(); QString nextTok = tokenizer.look(); if(tok == HRSchemaSerializer::META_START) { tokenizer.assertToken(HRSchemaSerializer::BLOCK_START); parseMeta(data); tokenizer.assertToken(HRSchemaSerializer::BLOCK_END); } else if(tok == HRSchemaSerializer::DOT_ITERATION_START) { QString itName = tokenizer.look() == HRSchemaSerializer::BLOCK_START ? "" : tokenizer.take(); tokenizer.assertToken(HRSchemaSerializer::BLOCK_START); data.iterations << HRSchemaSerializer::parseIteration(tokenizer, itName, data.actorMap, data.pasteMode); tokenizer.assertToken(HRSchemaSerializer::BLOCK_END); } else if (tok == HRSchemaSerializer::ACTOR_BINDINGS) { HRSchemaSerializer::backwardIncapability(); } else if (tok == HRSchemaSerializer::FUNCTION_START) { HRSchemaSerializer::backwardIncapability(); } else if(nextTok == HRSchemaSerializer::DATAFLOW_SIGN) { data.dataflowLinks << HRSchemaSerializer::parseDataflow(tokenizer, tok, data.actorMap); } else if(nextTok == HRSchemaSerializer::BLOCK_START) { tokenizer.take(); parseActorDefinition(data, tok); tokenizer.assertToken(HRSchemaSerializer::BLOCK_END); } else { throw HRSchemaSerializer::ReadFailed(HRSchemaSerializer::UNDEFINED_CONSTRUCT.arg(tok).arg(nextTok)); } } } void setFlowParameters(const HRSchemaSerializer::ParsedPairs & p, WorkflowBusItem * bit) { assert(bit != NULL); HRSchemaSerializer::ParsedPairs pairs = p; QString textPos = pairs.equalPairs.take(TEXT_POS_ATTR); if(!textPos.isEmpty()) { bit->getText()->setPos(string2Point(textPos)); } foreach(const QString & key, pairs.equalPairs.keys()) { coreLog.details(HRSceneSerializer::tr("Key '%1' not recognized as flow parameter").arg(key)); } } static void tryToConnect(WorkflowPortItem * input, WorkflowPortItem * output, const HRSchemaSerializer::ParsedPairs & pairs, bool select) { Port * srcPort = input->getPort(); Port * destPort = output->getPort(); if( !input || !output || !input->tryBind(output) ) { throw HRSchemaSerializer::ReadFailed(HRSceneSerializer::tr("Cannot bind %1:%2 to %3:%4"). arg(srcPort->owner()->getId()).arg(srcPort->getId()).arg(destPort->owner()->getId()).arg(destPort->getId())); } WorkflowBusItem * bit = input->getDataFlow(output); if(select) { bit->setSelected(true); } setFlowParameters(pairs, bit); } static void setFlows(WorkflowSceneReaderData & data) { if(!data.links.isEmpty()) { // try to create connections from visual links description foreach(const WorkflowSceneReaderData::LinkData & link, data.links) { tryToConnect(link.src, link.dst, link.pairs, data.select); } } else { // try to create connections from FlowGraph (TODO: do not works for all schemas: see sitecon search schema in samples) HRSchemaSerializer::FlowGraph graph(data.dataflowLinks); graph.minimize(); foreach(Port * srcPort, graph.graph.keys()) { foreach(Port * destPort, graph.graph.value(srcPort)) { WorkflowPortItem * input = data.procMap[data.actorMap.key(srcPort->owner())]->getPort(srcPort->getId()); WorkflowPortItem * output = data.procMap[data.actorMap.key(destPort->owner())]->getPort(destPort->getId()); HRSchemaSerializer::ParsedPairs pairs; int ind = data.links.indexOf(WorkflowSceneReaderData::LinkData(input, output)); if(ind != -1) { pairs = data.links[ind].pairs; } tryToConnect(input, output, pairs, data.select); } } } } QString HRSceneSerializer::string2Scene(const QString & bytes, WorkflowScene * scene, Metadata * meta, bool select, bool pasteMode) { try{ WorkflowSceneReaderData data(bytes, scene, meta, select, pasteMode); HRSchemaSerializer::parseHeader(data.tokenizer, data.meta); data.tokenizer.removeCommentTokens(); HRSchemaSerializer::parseBodyHeader(data.tokenizer, data.meta, !pasteMode); if(scene != NULL) { data.tokenizer.assertToken(HRSchemaSerializer::BLOCK_START); parseBodyItself(data); data.tokenizer.assertToken(HRSchemaSerializer::BLOCK_END); if( data.iterations.isEmpty() ) { if(!pasteMode) { data.iterations << Iteration("Default iteration"); } } setFlows(data); HRSchemaSerializer::addEmptyValsToBindings(data.actorMap.values()); QPointF pnt = scene->sceneRect().center(); foreach(WorkflowProcessItem * wItem, data.procMap.values()) { if(wItem->pos() == QPointF(0,0)) { wItem->setPos(pnt); pnt += QPointF(100, 0); } } scene->setIterations(data.iterations); } } catch(const HRSchemaSerializer::ReadFailed & ex) { return ex.what; } catch(...) { return HRSchemaSerializer::UNKNOWN_ERROR; } return HRSchemaSerializer::NO_ERROR; } } // U2 ugene-1.9.8/src/plugins/workflow_designer/src/SchemaConfigurationDialog.h0000644000175000017500000000313511651544324025333 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_WCFG_DIALOG_CONTROLLER_H_ #define _U2_WCFG_DIALOG_CONTROLLER_H_ #include #include #include namespace U2 { class IterationListWidget; using namespace Workflow; class SchemaConfigurationDialog : public QDialog, public Ui_SchemaConfigurationDialog { Q_OBJECT public: SchemaConfigurationDialog(const Schema& schema, const QList &lst, QWidget* p = NULL); QList& getIterations() const; bool hasModifications() const {return modified;} private slots: void finishPropertyEditing(); void commit(); void setModified() {modified = true;} private: IterationListWidget* iterationList; bool modified; }; } //namespace #endif ugene-1.9.8/src/plugins/workflow_designer/src/CreateScriptWorker.cpp0000644000175000017500000005534111651544324024406 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "CreateScriptWorker.h" #include "WorkflowEditorDelegates.h" #include "library/ScriptWorker.h" #include #include #include #include #include #include #include #include #include #include namespace U2 { #define WORKFLOW_DOC "GB2WORKFLOW" #define ACTOR_ELEMENT "Actor" #define INPUT_PORT_ELEMENT "Input-port" #define OUTPUT_PORT_ELEMENT "Output-port" #define ATTRIBUTE_ELEMENT "Attributes" #define IN_SLOT_ELEMENT "In-Slots" #define OUT_SLOT_ELEMENT "Out-Slots" #define SLOT_ID "Slot" #define ATTR_ELEMENT "Attribute" #define NAME_ID "Name" #define TYPE_ID "Type" #define NAME_ELEMENT "Element-name" #define DESCR_ELEMENT "Element-description" #define DESCR_ID "Description" //Q_DECLARE_METATYPE(DataTypePtr); class MapForTypesDelegate { public: MapForTypesDelegate() {} static QVariantMap getAttrTypes() { QVariantMap res; DataTypePtr ptr = BaseTypes::BOOL_TYPE(); res[ptr->getDisplayName()] = BaseTypes::BOOL_TYPE()->getId(); ptr = BaseTypes::NUM_TYPE(); res[ptr->getDisplayName()] = BaseTypes::NUM_TYPE()->getId(); ptr = BaseTypes::STRING_TYPE(); res[ptr->getDisplayName()] = BaseTypes::STRING_TYPE()->getId(); return res; } static QVariantMap getPortTypes() { QVariantMap res; DataTypePtr ptr = BaseTypes::DNA_SEQUENCE_TYPE(); res[ptr->getDisplayName()] = BaseTypes::DNA_SEQUENCE_TYPE()->getId(); ptr = BaseTypes::ANNOTATION_TABLE_TYPE(); res[ptr->getDisplayName()] = BaseTypes::ANNOTATION_TABLE_TYPE()->getId(); ptr = BaseTypes::MULTIPLE_ALIGNMENT_TYPE(); res[ptr->getDisplayName()] = BaseTypes::MULTIPLE_ALIGNMENT_TYPE()->getId(); ptr = BaseTypes::STRING_TYPE(); res[ptr->getDisplayName()] = BaseTypes::STRING_TYPE()->getId(); /*Descriptor ptr = BaseSlots::DNA_SEQUENCE_SLOT(); res[ptr.getDisplayName()] = BaseSlots::DNA_SEQUENCE_SLOT().getId(); ptr = BaseSlots::ANNOTATION_TABLE_SLOT(); res[ptr.getDisplayName()] = BaseSlots::ANNOTATION_TABLE_SLOT().getId(); ptr = BaseSlots::MULTIPLE_ALIGNMENT_SLOT(); res[ptr.getDisplayName()] = BaseSlots::MULTIPLE_ALIGNMENT_SLOT().getId(); ptr = BaseSlots::TEXT_SLOT(); res[ptr.getDisplayName()] = BaseSlots::TEXT_SLOT().getId();*/ return res; } static QVariantMap portMap; static QVariantMap attrMap; }; QVariantMap MapForTypesDelegate::attrMap = MapForTypesDelegate::getAttrTypes(); QVariantMap MapForTypesDelegate::portMap = MapForTypesDelegate::getPortTypes(); enum DelegateType { DelegateForPort, DelegateForAttribute }; class CfgListItem { public: CfgListItem(DelegateType t) { if(t == DelegateForPort) { delegate = new ComboBoxDelegate(MapForTypesDelegate::portMap); dataTypeId = BaseTypes::DNA_SEQUENCE_TYPE()->getId(); } else if(t == DelegateForAttribute) { delegate = new ComboBoxDelegate(MapForTypesDelegate::attrMap); dataTypeId = BaseTypes::STRING_TYPE()->getId(); } else { assert(0); } } ~CfgListItem() {delete delegate;} PropertyDelegate *getDelegate() const {return delegate;} QString getDataType() const {return dataTypeId;} void setDataType(const QString& id) { dataTypeId = id; } QString getName() const {return name;} void setName(const QString &_name) {name = _name;} private: PropertyDelegate *delegate; QString dataTypeId; QString name; //DataTypePtr dataType; }; class CfgListModel: public QAbstractListModel { public: CfgListModel(QObject *obj = NULL): QAbstractListModel(obj) { items.append(new CfgListItem(DelegateForPort)); } ~CfgListModel() { foreach(CfgListItem *item, items) { delete item; } } QStringList getItems() const { QStringList result; foreach(CfgListItem *item, items) { result.append(item->getDataType()); } return result; } int rowCount(const QModelIndex & parent = QModelIndex()) const { Q_UNUSED(parent); return items.count(); } Qt::ItemFlags flags(const QModelIndex &) const{ return Qt::ItemIsEditable | Qt::ItemIsEnabled | Qt::ItemIsSelectable; } CfgListItem* getItem(const QModelIndex &index) const { //CfgListItem *item = static_cast(index.internalPointer()); return items.at(index.row()); } QModelIndex parent(const QModelIndex &) const{ return QModelIndex(); } QVariant data(const QModelIndex &index, int role /* = Qt::DisplayRole */) const { CfgListItem *item = getItem(index); PropertyDelegate *dg = item->getDelegate(); switch(role) { case Qt::DisplayRole: case Qt::ToolTipRole: return dg->getDisplayValue(item->getDataType()); case DelegateRole: return qVariantFromValue(dg); case Qt::EditRole: case ConfigurationEditor::ItemValueRole: return item->getDataType(); default: return QVariant(); } } bool setData(const QModelIndex &index, const QVariant &value, int role /* = Qt::EditRole */) { switch (role) { case Qt::EditRole: case ConfigurationEditor::ItemValueRole: CfgListItem * item = getItem(index); if(item->getDataType() != value.toString()) { if(!value.toString().isEmpty()) { item->setDataType(value.toString()); } } emit dataChanged(index, index); } return true; } bool insertRows ( int row, int count = 0, const QModelIndex & parent = QModelIndex() ) { Q_UNUSED(row); beginInsertRows(parent,items.size(), items.size() + count); for(int i = 0;i < count; i++) { items.append(new CfgListItem(DelegateForPort)); } endInsertRows(); return true; } bool removeRows(int row, int count, const QModelIndex &parent /* = QModelIndex */) { Q_UNUSED(count); if(rowCount() == 1 || row <0 || row > rowCount()) { return false; } beginRemoveRows(parent, row, row); items.removeAt(row); endRemoveRows(); return true; } private: QList items; }; class CfgTableModel: public QAbstractTableModel { public: CfgTableModel(QObject *obj = NULL): QAbstractTableModel(obj) { //attrs.append(new CfgListItem()); } int rowCount(const QModelIndex & /* = QModelIndex */) const{ return attrs.size(); } int columnCount(const QModelIndex & /* = QModelIndex */) const { return 2; } Qt::ItemFlags flags(const QModelIndex &) const{ return Qt::ItemIsEditable | Qt::ItemIsEnabled | Qt::ItemIsSelectable; } CfgListItem* getItem(const QModelIndex &index) const { //CfgListItem *item = static_cast(index.internalPointer()); return attrs.at(index.row()); } QList getItems() const { return attrs; } QVariant data(const QModelIndex &index, int role /* = Qt::DisplayRole */) const { CfgListItem *item = getItem(index); int col = index.column(); PropertyDelegate *dg = item->getDelegate(); switch(role) { case Qt::DisplayRole: if(col == 0) return item->getName(); else return dg->getDisplayValue(item->getDataType()); case DelegateRole: if(col == 1)return qVariantFromValue(dg); else return QVariant(); case Qt::EditRole: case ConfigurationEditor::ItemValueRole: if(col == 1) return item->getDataType(); else return QVariant(); default: return QVariant(); } } QVariant headerData ( int section, Qt::Orientation orientation, int role = Qt::DisplayRole ) const { if (orientation == Qt::Horizontal && role == Qt::DisplayRole) { switch(section) { case 0: return CreateScriptElementDialog::tr("Name"); case 1: return CreateScriptElementDialog::tr("type"); default: return QVariant(); } } return QVariant(); } bool setData(const QModelIndex &index, const QVariant &value, int role) { int col = index.column(); CfgListItem * item = getItem(index); switch (role) { case Qt::EditRole: case ConfigurationEditor::ItemValueRole: if(col == 1) { if(item->getDataType() != value.toString()) { if(!value.toString().isEmpty()) { item->setDataType(value.toString()); } } } else { if(item->getName() != value.toString()) { item->setName(value.toString()); } } emit dataChanged(index, index); } return true; } bool insertRows ( int row, int count = 0, const QModelIndex & parent = QModelIndex() ) { Q_UNUSED(row); Q_UNUSED(count); beginInsertRows(parent, attrs.size(), attrs.size()); attrs.append(new CfgListItem(DelegateForAttribute)); endInsertRows(); return true; } bool removeRows(int row, int count = 0, const QModelIndex & parent = QModelIndex()) { Q_UNUSED(count); if(row >= 0 && row < attrs.size()) { beginRemoveRows(parent, row,row); attrs.removeAt(row); endRemoveRows(); return true; } else { return false; } } private: QListattrs; }; CreateScriptElementDialog::CreateScriptElementDialog(QWidget *p, ActorPrototype* proto): QDialog(p), editing(false) { setupUi(this); inputList->setModel(new CfgListModel()); inputList->setItemDelegate(new ProxyDelegate()); outputList->setModel(new CfgListModel()); outputList->setItemDelegate(new ProxyDelegate()); attributeTable->setModel(new CfgTableModel()); attributeTable->setItemDelegate(new ProxyDelegate()); errorBox->hide(); connect(addInputButton, SIGNAL(clicked()), SLOT(sl_addInputClicked())); connect(addOutputButton, SIGNAL(clicked()), SLOT(sl_addOutputClicked())); connect(addAttributeButton, SIGNAL(clicked()), SLOT(sl_addAttribute())); connect(deleteInputButton, SIGNAL(clicked()), SLOT(sl_deleteInputClicked())); connect(deleteOutputButton, SIGNAL(clicked()), SLOT(sl_deleteOutputClicked())); connect(deleteAttributeButton, SIGNAL(clicked()), SLOT(sl_deleteAttributeClicked())); connect(fileButton, SIGNAL(clicked()), SLOT(sl_getDirectory())); connect(okButton, SIGNAL(clicked()), SLOT(sl_okClicked())); connect(cancelButton, SIGNAL(clicked()), SLOT(sl_cancelClicked())); attributeTable->horizontalHeader()->setStretchLastSection(true); if(proto) { fillFields(proto); editing = true; } } static DataTypePtr getDatatypeOfSlotDesc(const Descriptor & dt) { QString dtId = dt.getId(); if(dtId == BaseSlots::DNA_SEQUENCE_SLOT().getId()) { return BaseTypes::DNA_SEQUENCE_TYPE(); } if(dtId == BaseSlots::ANNOTATION_TABLE_SLOT().getId()) { return BaseTypes::ANNOTATION_TABLE_TYPE(); } if(dtId == BaseSlots::MULTIPLE_ALIGNMENT_SLOT().getId()) { return BaseTypes::MULTIPLE_ALIGNMENT_TYPE(); } if(dtId == BaseSlots::TEXT_SLOT().getId()) { return BaseTypes::STRING_TYPE(); } assert(false); return DataTypePtr(); } void CreateScriptElementDialog::fillFields(ActorPrototype *proto) { proto->getPortDesciptors(); int inputInd = 0; int outputInd = 0; foreach(const PortDescriptor *desc, proto->getPortDesciptors()) { if(desc->isInput()) { inputList->model()->insertRows(0,desc->getType()->getAllDescriptors().size() - 1, QModelIndex()); foreach(const Descriptor &d, desc->getType()->getAllDescriptors()) { QModelIndex mi = inputList->model()->index(inputInd,0); inputList->model()->setData(mi,getDatatypeOfSlotDesc(d)->getId()); inputInd++; } } else { outputList->model()->insertRows(0,desc->getType()->getAllDescriptors().size() - 1, QModelIndex()); foreach(const Descriptor &d, desc->getType()->getAllDescriptors()) { QModelIndex mi = outputList->model()->index(outputInd,0); outputList->model()->setData(mi,getDatatypeOfSlotDesc(d)->getId()); outputInd++; } } } int ind = 0; foreach(const Attribute*attr, proto->getAttributes()) { attributeTable->model()->insertRow(1, QModelIndex()); QModelIndex mi1 = attributeTable->model()->index(ind,0); QModelIndex mi2 = attributeTable->model()->index(ind,1); attributeTable->model()->setData(mi1, attr->getId()); attributeTable->model()->setData(mi2, attr->getAttributeType()->getId()); ind++; } nameEdit->setText(proto->getDisplayName()); descriptionEdit->setText(proto->getDocumentation()); } void CreateScriptElementDialog::sl_getDirectory() { /*Settings *s = AppContext::getSettings(); QString defaultPath = QDir::searchPaths( PATH_PREFIX_DATA ).first() + "/workflow_samples/" + "users/"; QString url = s->getValue(SETTINGS_ROOT + ACTORS_PATH, defaultPath).toString();*/ QString url = WorkflowSettings::getUserDirectory(); QFileDialog dialog(this); dialog.setFileMode(QFileDialog::Directory); dialog.setViewMode(QFileDialog::List); dialog.setDirectory(url); if(dialog.exec() == QDialog::Accepted) { QString dir = dialog.selectedFiles().first(); fileEdit->setText(dir); } } void CreateScriptElementDialog::sl_addInputClicked() { inputList->model()->insertRow(0,QModelIndex()); } void CreateScriptElementDialog::sl_addOutputClicked() { outputList->model()->insertRow(0,QModelIndex()); } void CreateScriptElementDialog::sl_addAttribute() { attributeTable->model()->insertRow(0,QModelIndex()); } void CreateScriptElementDialog::sl_deleteInputClicked() { QModelIndex index = inputList->currentIndex(); inputList->model()->removeRow(index.row()); } void CreateScriptElementDialog::sl_deleteOutputClicked() { QModelIndex index = outputList->currentIndex(); outputList->model()->removeRow(index.row()); } void CreateScriptElementDialog::sl_deleteAttributeClicked() { QModelIndex index = attributeTable->currentIndex(); attributeTable->model()->removeRow(index.row()); } void CreateScriptElementDialog::sl_cancelClicked() { reject(); } void CreateScriptElementDialog::sl_okClicked() { CfgListModel * inputPorts = static_cast(inputList->model()); QList typeIds = inputPorts->getItems(); DataTypeRegistry *dtr = WorkflowEnv::getDataTypeRegistry(); assert(dtr); input.clear(); foreach(const QString & id, typeIds) { DataTypePtr ptr = dtr->getById(id); if(input.contains(ptr)) { QMessageBox::critical(this, tr("error"), tr("Two identical types for input port")); coreLog.error(tr("two identical types for input port")); return; } input << ptr; } CfgListModel * outputPorts = static_cast(outputList->model()); typeIds = outputPorts->getItems(); assert(dtr); output.clear(); foreach(const QString & id, typeIds) { DataTypePtr ptr = dtr->getById(id); if(output.contains(ptr)) { QMessageBox::critical(this, tr("error"),tr("Two identical types for output port")); coreLog.error(tr("two identical types for output port")); return; } output << ptr; } CfgTableModel * attrTableModel = static_cast(attributeTable->model()); QList attributes = attrTableModel->getItems(); attrs.clear(); foreach(CfgListItem *item, attributes) { QString itemName = item->getName(); if(itemName.isEmpty()) { QMessageBox::critical(this, tr("error"),tr("Name for some attributes is empty")); coreLog.error(tr("Name for some attributes is empty")); return; } foreach(const Attribute *attr, attrs) { if(attr->getId() == itemName) { QMessageBox::critical(this, tr("error"),tr("Two attributes with name %1").arg(itemName)); coreLog.error(tr("Two attributes with name %1").arg(itemName)); return; } } DataTypePtr ptr = dtr->getById(item->getDataType()); Descriptor desc(itemName, itemName, ptr->getDisplayName()); if(ptr == BaseTypes::BOOL_TYPE()) { attrs << new Attribute(desc, ptr, false, QVariant(false)); } else { attrs << new Attribute(desc, ptr); } } name = nameEdit->text(); if(name.isEmpty()) { QMessageBox::critical(this, tr("error"),tr("Name for block is empty")); coreLog.error(tr("Name for block is empty")); return; } ActorPrototypeRegistry *pr = WorkflowEnv::getProtoRegistry(); if(pr) { if(pr->getProto(LocalWorkflow::ScriptWorkerFactory::ACTOR_ID+name) && !editing) { QMessageBox::critical(this, tr("error"),tr("Actor with this name already registered")); coreLog.error(tr("Actor with this name already registered")); return; } } description = descriptionEdit->toPlainText(); if(description.isEmpty()) { QMessageBox::critical(this, tr("error"),tr("Description for block is empty")); coreLog.error(tr("Description for block is empty")); return; } if(!fileEdit->text().isEmpty()) { changeDirectoryForActors(); } if(!saveParams()) { errorBox->show(); return; } accept(); } void CreateScriptElementDialog::changeDirectoryForActors() { QString url = WorkflowSettings::getUserDirectory(); QString newUrl = fileEdit->text() + "/"; if(url != newUrl) { WorkflowSettings::setUserDirectory(newUrl); QDir dir(url); if(!dir.exists()) { //coreLog.info(tr("There isn't directory with users workflow elements")); return; } dir.setNameFilters(QStringList() << "*.usa"); QFileInfoList fileList = dir.entryInfoList(); foreach(const QFileInfo &fileInfo, fileList) { QString newFileUrl = newUrl + fileInfo.fileName(); QFile::copy(fileInfo.filePath(), newFileUrl); } } } bool CreateScriptElementDialog::saveParams() { QDomDocument doc = saveXml(); QString url = WorkflowSettings::getUserDirectory(); QDir dir(url); if(!dir.exists()) { dir.mkpath(url); } IOAdapterFactory *iof = AppContext::getIOAdapterRegistry()->getIOAdapterFactoryById(BaseIOAdapters::LOCAL_FILE); IOAdapter *io = iof->createIOAdapter(); if(io->open( url + name + ".usa", IOAdapterMode_Write )) { io->writeBlock(doc.toByteArray()); io->close(); return true; } else { coreLog.error(tr("Can't save user's workflow element")); return false; } } QDomDocument CreateScriptElementDialog::saveXml() { QDomDocument xml(WORKFLOW_DOC); QDomElement actor = xml.createElement(ACTOR_ELEMENT); xml.appendChild(actor); CfgListModel * inputPorts = static_cast(inputList->model()); QList typeIds = inputPorts->getItems(); QDomElement inputPort = xml.createElement(INPUT_PORT_ELEMENT); actor.appendChild(inputPort); foreach(const QString & str, typeIds) { QDomElement slot = xml.createElement(IN_SLOT_ELEMENT); slot.setAttribute(SLOT_ID, str); inputPort.appendChild(slot); } CfgListModel * outputPorts = static_cast(outputList->model()); typeIds = outputPorts->getItems(); QDomElement outputPort = xml.createElement(OUTPUT_PORT_ELEMENT); actor.appendChild(outputPort); foreach(const QString & str, typeIds) { QDomElement slot = xml.createElement(OUT_SLOT_ELEMENT); slot.setAttribute(SLOT_ID, str); outputPort.appendChild(slot); } CfgTableModel * attrTableModel = static_cast(attributeTable->model()); QList attributes = attrTableModel->getItems(); QDomElement attribute = xml.createElement(ATTRIBUTE_ELEMENT); actor.appendChild(attribute); foreach(CfgListItem *item, attributes) { QString itemName = item->getName(); QString itemId = item->getDataType(); QDomElement attr = xml.createElement(ATTR_ELEMENT); attr.setAttribute(NAME_ID, itemName); attr.setAttribute(TYPE_ID, itemId); attribute.appendChild(attr); } QDomElement nameEl = xml.createElement(NAME_ELEMENT); nameEl.setAttribute(NAME_ID, name); actor.appendChild(nameEl); QDomElement descriptionEl = xml.createElement(DESCR_ELEMENT); descriptionEl.setAttribute(DESCR_ID, description); actor.appendChild(descriptionEl); return xml; } QList CreateScriptElementDialog::getInput() const{ return input; } QList CreateScriptElementDialog::getOutput() const{ return output; } QList CreateScriptElementDialog::getAttributes() const { return attrs; } const QString CreateScriptElementDialog::getName() const { return name; } const QString CreateScriptElementDialog::getDescription() const { return description; } } //namespace ugene-1.9.8/src/plugins/workflow_designer/src/WorkflowViewController.h0000644000175000017500000001567311651544325025007 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_WORKFLOW_VIEW_CONTROLLER_H_ #define _U2_WORKFLOW_VIEW_CONTROLLER_H_ #include #include #include #include #include #include #include class QComboBox; class QSplitter; class QDomDocument; class QListWidget; class QListWidgetItem; class QTabWidget; namespace U2 { using namespace Workflow; class WorkflowView; class WorkflowScene; class WorkflowPalette; class WorkflowEditor; class WorkflowGObject; class WorkflowRunTask; class WorkflowScene : public QGraphicsScene { Q_OBJECT public: WorkflowScene(WorkflowView *parent = 0); virtual ~WorkflowScene(); bool isModified() const {return modified;} //FIXME draft support bool isLocked() const {return locked;} WorkflowView* getController() const { return controller; } WorkflowAbstractRunner* getRunner() const {return runner;} void setRunner(WorkflowAbstractRunner* r) {runner = r;} QList getSelectedProcItems() const; QList getAllProcs() const; Actor* getActor(ActorId) const; Schema getSchema() const; QList getIterations() const {return iterations;} void setIterations(const QList& lst); void addProcess(Actor*, const QPointF&); Actor * createActor( ActorPrototype * proto, const QVariantMap & params = QVariantMap() ); void clearScene(); public slots: void sl_deleteItem(); void sl_selectAll(); void sl_deselectAll(); void sl_reset(); void setLocked(bool b) {locked = b;} void setModified(bool b); void centerView(); void setHint(int i) {hint=i; update();} signals: void processItemAdded(); void processDblClicked(); void configurationChanged(); protected: void mousePressEvent(QGraphicsSceneMouseEvent *mouseEvent); void mouseMoveEvent(QGraphicsSceneMouseEvent *mouseEvent); void mouseReleaseEvent(QGraphicsSceneMouseEvent *mouseEvent); void mouseDoubleClickEvent(QGraphicsSceneMouseEvent * mouseEvent); void contextMenuEvent(QGraphicsSceneContextMenuEvent * contextMenuEvent); void dragEnterEvent(QGraphicsSceneDragDropEvent * event); void dragMoveEvent(QGraphicsSceneDragDropEvent * event); void dropEvent(QGraphicsSceneDragDropEvent * event); void drawBackground(QPainter * painter, const QRectF & rect ); private: WorkflowView* controller; bool modified, locked; QList iterations; WorkflowAbstractRunner* runner; int hint; }; // WorkflowScene class WorkflowView : public MWMDIWindow { friend class WorkflowScene; Q_OBJECT public: WorkflowView(WorkflowGObject* go); ~WorkflowView(); //WorkflowDesignerService* getService() const {return service;} WorkflowEditor* getPropertyEditor() const { return propertyEditor; } virtual void setupMDIToolbar(QToolBar* tb); virtual void setupViewMenu(QMenu* n); void setupContextMenu(QMenu* menu); bool confirmModified(); ActorPrototype* selectedProto() const { return currentProc; } Actor* getActor() { return currentActor; } WorkflowScene* getScene() const {return scene;} Workflow::Metadata getMeta() const {return meta;} void refreshView() {sl_refreshActorDocs();} /** * Schema can run on local and remote machine * if it is run on remote machine then all needed files on local filesystem * are saved with schema and passed to remote machine (see WorkflowRemoteRunTask for details) */ enum RunMode { LOCAL_HOST, REMOTE_MACHINE }; // RunMode private slots: void sl_editItem(); void sl_onSelectionChanged(); void sl_showEditor(); void sl_selectProcess(Workflow::ActorPrototype*); void sl_procItemAdded(); void sl_rescaleScene(const QString &scale); void sl_exportScene(); void sl_saveScene(); void sl_saveSceneAs(); void sl_loadScene(); void sl_newScene(); void sl_updateTitle(); void sl_copyItems(); void sl_cutItems(); void sl_pasteItems(const QString& = QString()); void sl_pasteSample(const QString&); void sl_setStyle(); void sl_toggleStyle(); void sl_refreshActorDocs(); void sl_setRunMode(); void sl_changeScriptMode(); bool sl_validate(bool notify = true); void sl_pickInfo(QListWidgetItem*); void sl_launch(); void sl_stop(); void sl_configureIterations(); void sl_configureAliases(); void sl_toggleLock(bool = true); void sl_createScript(); void sl_editScript(); void sl_externalAction(); void sl_appendExternalToolWorker(); void sl_protoDeleted(const QString& id); void sl_xmlSchemaLoaded(Task*); protected: bool onCloseEvent(); private: void createActions(); void saveState(); void localHostLaunch(); void remoteLaunch(); WorkflowGObject* go; QGraphicsView* sceneView; WorkflowScene* scene; Workflow::Metadata meta; ActorPrototype* currentProc; Actor* currentActor; QAction* deleteAction; QAction* selectAction; //QAction* bringToFrontAction; //QAction* sendToBackAction; QComboBox* sceneScaleCombo; QAction* copyAction; QAction* pasteAction; QAction* cutAction; QString lastPaste; int pasteCount; QAction* exportAction; QAction* saveAction; QAction* saveAsAction; QAction* loadAction; QAction* newAction; QAction* createScriptAcction; QAction* editScriptAction; QAction* externalToolAction; QAction* appendExternalTool; QAction* configureIterationsAction; QAction* configureAliasesAction; QAction* runAction; QAction* stopAction; QAction* validateAction; QList styleActions; QList runModeActions; QList scriptingActions; QAction* unlockAction; QSplitter* splitter; WorkflowPalette* palette; WorkflowEditor* propertyEditor; QListWidget* infoList; QSplitter* infoSplitter; QTabWidget* tabs; bool scriptingMode; RunMode runMode; }; }//namespace #endif ugene-1.9.8/src/plugins/workflow_designer/src/HRSceneSerializer.h0000644000175000017500000000312011651544324023576 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_WORKLFOW_SUPPORT_HR_FORMAT_UTILS_H_ #define _U2_WORKLFOW_SUPPORT_HR_FORMAT_UTILS_H_ #include "WorkflowViewController.h" #include "WorkflowViewItems.h" #include "ItemViewStyle.h" namespace U2 { class HRSceneSerializer : QObject { Q_OBJECT public: static QString scene2String(WorkflowScene * scene, const Metadata & meta); // returns error or empty string static QString string2Scene(const QString & data, WorkflowScene * scene, Metadata * meta = NULL, bool select = false, bool pasteMode = false); static QString items2String(const QList & items, const QList & iterations); }; // HRSceneSerializer } // U2 #endif // _U2_WORKLFOW_SUPPORT_HR_FORMAT_UTILS_H_ ugene-1.9.8/src/plugins/workflow_designer/src/WorkflowDesignerPlugin.h0000644000175000017500000000373511651544324024743 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_FLOWCHART_H_ #define _U2_FLOWCHART_H_ #include #include #include #include class QAction; class QEvent; namespace U2 { class WorkflowDesignerPlugin : public Plugin { Q_OBJECT public: static const QString RUN_WORKFLOW; static const QString REMOTE_MACHINE; public: WorkflowDesignerPlugin (); //~WorkflowDesignerPlugin (); private: void registerCMDLineHelp(); void processCMDLineOptions(); private slots: void sl_saveSchemaImageTaskFinished(); }; class WorkflowDesignerService : public Service { Q_OBJECT public: WorkflowDesignerService(); bool closeViews(); protected: virtual Task* createServiceEnablingTask(); virtual Task* createServiceDisablingTask(); virtual void serviceStateChangedCallback(ServiceState oldState, bool enabledStateChanged); private slots: void sl_showDesignerWindow(); void sl_showManagerWindow(); void sl_startWorkflowPlugin(); private: QAction* designerAction; QAction* managerAction; }; } //namespace #endif ugene-1.9.8/src/plugins/workflow_designer/src/WorkflowMetaDialog.h0000644000175000017500000000255611651544324024032 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_WMETADIALOG_H_ #define _U2_WMETADIALOG_H_ #include "ui/ui_WorkflowMetaDialog.h" #include #include namespace U2 { using namespace Workflow; class WorkflowMetaDialog : public QDialog, public Ui_WorkflowMetaDialog { Q_OBJECT public: WorkflowMetaDialog(QWidget * p, const Workflow::Metadata& meta); public: Workflow::Metadata meta; private slots: void sl_onBrowse(); void sl_onSave(); void sl_onURLChanged(const QString & text); }; }//namespace #endif ugene-1.9.8/src/plugins/workflow_designer/src/ActorCfgModel.h0000644000175000017500000000704311651544324022736 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_ACTOR_CFG_H_ #define _U2_ACTOR_CFG_H_ #include #include #include #include #include #include #include #include #include namespace U2 { using namespace Workflow; class ActorCfgModel : public QAbstractTableModel { Q_OBJECT public: ActorCfgModel(QObject *parent, QList& lst); ~ActorCfgModel(); void setActor(Actor * cfg); void selectIteration(int i); void setIterations(QList& lst); int columnCount(const QModelIndex &) const; int rowCount ( const QModelIndex & parent = QModelIndex() ) const; Qt::ItemFlags flags( const QModelIndex & index ) const; QVariant headerData( int section, Qt::Orientation orientation, int role = Qt::DisplayRole ) const; /*Used to supply item data to views and delegates. Generally, models only need to supply data for Qt::DisplayRole and any application-specific user roles, but it is also good practice to provide data for Qt::ToolTipRole, Qt::AccessibleTextRole, and Qt::AccessibleDescriptionRole.*/ QVariant data ( const QModelIndex & index, int role = Qt::DisplayRole ) const; /*Used to modify the item of data associated with a specified model index. To be able to accept user input, provided by user interface elements, this function must handle data associated with Qt::EditRole. The implementation may also accept data associated with many different kinds of roles specified by Qt::ItemDataRole. After changing the item of data, models must emit the dataChanged() signal to inform other components of the change.*/ bool setData ( const QModelIndex & index, const QVariant & value, int role = Qt::EditRole ); void changeScriptMode(bool _mode); QModelIndex modelIndexById(const QString& id) { for (int i=0; igetId()==id) { QModelIndex modelIndex = index(i, 1); return modelIndex; } } return QModelIndex(); } private: bool setAttributeValue( const Attribute * attr, QVariant & attrValue ) const; void setupAttributesScripts(); Attribute *getAttributeByRow(int row) const; private: Actor* subject; QList attrs; AttributeScriptDelegate * scriptDelegate; QList& iterations; int iterationIdx; QVariantMap listValues; bool scriptMode; }; // ActorCfgModel }//namespace U2 #endif // _U2_ACTOR_CFG_H_ ugene-1.9.8/src/plugins/workflow_designer/transl/0000755000175000017500000000000011651544325020625 5ustar ilyailyaugene-1.9.8/src/plugins/workflow_designer/transl/russian.ts0000644000175000017500000046556711651544325022710 0ustar ilyailya ChooseItemDialog OK Создать Cancel Отменить Choose task type Выбор типа задачи Add a task of the following type: Возможно создать объект для следующих задач: CreateExternalProcessWorkerDialog Create Element with Command Line Tool <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> <html><head><meta name="qrichtext" content="1" /><style type="text/css"> p, li { white-space: pre-wrap; } </style></head><body style=" font-family:'MS Shell Dlg 2'; font-size:8.25pt; font-weight:400; font-style:normal;"> <p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-size:8pt;">Name and description for new workflow element.</span></p></body></html> Element description Name Имя Description <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> <html><head><meta name="qrichtext" content="1" /><style type="text/css"> p, li { white-space: pre-wrap; } </style></head><body style=" font-family:'MS Shell Dlg 2'; font-size:8.25pt; font-weight:400; font-style:normal;"> <p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-size:8pt;">Input and output data for external tool. Name is a command line parameter for input/output data in external tool. Set data type and format in which external tool reads/writes input/output data. You also can set description for workflow designer. Each input data will be represented as port in workflow designer. Each output data will be represented as slot of single slot.</span></p></body></html> Input data Входные данные Add input Delete Удалить Output data Выходные данные Add output <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> <html><head><meta name="qrichtext" content="1" /><style type="text/css"> p, li { white-space: pre-wrap; } </style></head><body style=" font-family:'MS Shell Dlg 2'; font-size:8.25pt; font-weight:400; font-style:normal;"> <p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-size:8pt;">Another parameters for external tool. You must set name for parameter and its type. You also can set description for workflow designer. Each parameter will be represented as parameter of workflow element.</span></p></body></html> Parameters Параметры Add attribute <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> <html><head><meta name="qrichtext" content="1" /><style type="text/css"> p, li { white-space: pre-wrap; } </style></head><body style=" font-family:'MS Shell Dlg 2'; font-size:8.25pt; font-weight:400; font-style:normal;"> <p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-size:8pt;">Execution string and element's description. To substitute input, output data or parameter, use it's name with prefix $ in execution string. You can set parameterized description for new element(description that appears not in property editor but on element itself). In parameterized description you also can use parameters substitution with prefix $.</span></p></body></html> Command line template Execution string Parameterized description CreateScriptBlockDialog Create Element with Script Name Имя ScriptBlock Description <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> <html><head><meta name="qrichtext" content="1" /><style type="text/css"> p, li { white-space: pre-wrap; } </style></head><body style=" font-family:'MS Shell Dlg 2'; font-size:8.25pt; font-weight:400; font-style:normal;"> <p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-size:8pt;">Evaluates user's script</span></p></body></html> Input Port Add input slot Delete input slot Output Port Add output slot Delete output slot Attributes Add Attribute Delete Attribute Error Error occured while saving new actor. Can't write to current directory. Choose another directory for store user's elements ... OK Сохранить Cancel CreateScriptElementDialog Name Имя RemoteDBFetcherWorker Sequence Последовательность SchemaAliasesConfigurationDialog Configure command line aliases Редактировать параметры запуска схемы черех консоль Objects Задачи Workflow elements Schema parameter Параметр схемы Command line alias Консольный параметр Help message Ok Готово Cancel Отмена SchemaConfigurationDialog Name Имя Default value Значение по умолчанию Configure Schema Конфигурация схемы Iterations Итерации Parameters Параметры U2::ActorCfgModel N/A U2::CreateExternalProcessDialog Name for command line parameter Type Format Description Name Имя Create Element Please set the input/output data. Please set the command line to run external tool. Please set the name for the new element. Invalid symbols in the element name. Element with this name already exists. For one or more parameter name was not set. Invalid symbols in a name. The same name of element parameters was found You don't use parameter %1 in template string. Continue? Continue Abort U2::CreateScriptElementDialog Name Имя type error Two identical types for input port two identical types for input port Two identical types for output port two identical types for output port Name for some attributes is empty Two attributes with name %1 Name for block is empty Actor with this name already registered Description for block is empty Can't save user's workflow element U2::ExtendedProcStyle Auto-resize to text Динамический размер U2::HRSceneSerializer Unexpected end of file Cannot parse coordinates from '%1' Cannot parse real value from '%1' Cannot parse 4 integer numbers from '%1' Cannot parse font from '%1' Cannot parse rectangle from '%1' %1 element undefined in visual block No other blocks allowed in visual block '%1' %1 does not has %2 style Cannot find port '%1' at %2 element Cannot parse real number from: '%1' Undefined visual key: '%1' for actor %2 Undefined element id: '%1' Cannot find '%1' port at '%2' No other blocks allowed in link parameters block '%1' Key '%1' not recognized as flow parameter Cannot bind %1:%2 to %3:%4 U2::ItemViewStyle Background color Цвет фона Font Шрифт U2::IterationListWidget Clone Копировать Add Добавить Remove Удалить All Все Default iteration Основная итерация Workflow Designer Дизайнер Схем Do you want to divide the list into separate iterations? Разделить список на независимые итерации? If you need to process each item in the list with different schema parameters, the Designer can create separate iterations for each item now. Otherwise, if all items should be processed uniformly, it is better to leave the list intact. Итерации полезны, если разные элементы списка необходимо обрабатывать с разными параметрами схемы. Иначе удобнее работать с целым списком. Copy of %1 Копия %1 New Iteration Новая итерация U2::LoadSamplesTask Load workflow samples Загрузка примеров Sample dir does not exist: %1 Папка с примерами не найдена: %1 Failed to load sample: %1 Не удалось загрузить пример %1 Failed to read sample: %1 (%2) Не удалось прочитать файл примера: %1 (%2) U2::LoadWorkflowSceneTask Load workflow scene Undefined format: plain text or xml expected Error while parsing file: %1 U2::LocalWorkflow::Alignment2SequencePrompter unset не указан from <u>%1</u> из <u>%1</u> Split alignment%1 into sequences Split alignment from %1 into sequences Разделить множественное выравнивание из %1 на последовательности U2::LocalWorkflow::Alignment2SequenceWorker empty input alignment Input alignment A alignment which will be split into sequences Output sequences Converted sequences Split alignment into sequences Splits input alignment into sequences U2::LocalWorkflow::BaseDocWriter Document format not set Формат документа не задан Unspecified URL to write %1 Не задан адрес для записи %1 Writing to %1 [%2] Запись %1 [формат %2] Save documents Сохранение документов U2::LocalWorkflow::CDSearchPrompter unset не указан from <u>%1</u> из <u>%1</u> For sequence %1 find conserved domains in database <u>%2</u> U2::LocalWorkflow::CDSearchWorker Input sequence The sequence to search the annotations for Annotations Found annotations Database База данных Currently, CD-Search is offered with the following search databases:<br><ul><li><b>CDD</b> - this is a superset including <a href="http://www.ncbi.nlm.nih.gov/Structure/cdd/cdd_help.shtml#CDSource_NCBI_curated">NCBI-curated domains</a> and <a href="http://www.ncbi.nlm.nih.gov/Structure/cdd/cdd_help.shtml#CDSource_external">data imported</a> from Pfam, SMART, COG, PRK, and TIGRFAM.</li><li><b>Pfam</b> - a mirror of a recent Pfam-A database of curated seed alignments. Pfam version numbers do change with incremental updates. As with SMART, families describing very short motifs or peptides may be missing from the mirror. An HMM-based search engine is offered on the <a href="http://pfam.sanger.ac.uk/">Pfam</a> site.</li><li><b>SMART</b> - a mirror of a recent SMART set of domain alignments. Note that some SMART families may be missing from the mirror due to update delays or because they describe very short conserved peptides and/or motifs, which would be difficult to detect using the CD-Search service. You may want to try the HMM-based search service offered on the <a href="http://smart.embl-heidelberg.de">SMART</a> site. Note also that some SMART domains are not mirrored in CD because they represent "superfamilies" encompassing several individual, but related, domains; the corresponding seed alignments may not be available from the source database in these cases. Note also that SMART version numbers do not change with incremental updates of the source database (and the mirrored CD-Search database).</li> <li><b>TIGRFAM</b> - a mirror of a recent TIGRFAM set of domain alignments. An HMM-based search engine is offered on the <a href="http://www.jcvi.org/cms/research/projects/tigrfams/overview/"><!-- a href="http://blast.jcvi.org/web-hmm/" -->TIGRFAM</a> site.</li><li><b>COG</b> - a mirror of the current COG database of orthologous protein families focusing on prokaryotes. Seed alignments have been generated by an automated process. An alternative search engine, "Cognitor", which runs protein-BLAST against a database of COG-assigned sequences, is offered on the <a href="http://www.ncbi.nlm.nih.gov/COG">COG</a> site.</li><li><b>KOG</b> - a eukaryotic counterpart to the COG database. KOGs are not included in the CDD superset, but are searchable as a separate data set.</li></ul><br>More information about each database is provided in the section on <a href="http://www.ncbi.nlm.nih.gov/Structure/cdd/cdd_help.shtml#CDSource">Where does CDD content come from?</a> Annotate as Аннотации Name of the result annotations marking found conserved domains. Local search Perform the search on local machine or submit the search to NCBI for remote execution. Expect value Modifies the <a href="http://www.ncbi.nlm.nih.gov/BLAST/blastcgihelp.shtml#expect">E-value</a> threshold used for filtering results. False positive results should be very rare with the default setting of 0.01 (use a more conservative, i.e. lower setting for more reliable results), results with E-values in the range of 1 and above should be considered putative false positives. Database directory Specifies database directory for local search. CD-Search Finds conserved domains in protein sequences. In case conserved domains database is downloaded the search can be executed on local machine. The search also can be submitted to the NCBI for remote execution. 'External tools' plugin has to be loaded. 'Remote blast' plugin has to be loaded. U2::LocalWorkflow::DNAStatWorker Input sequence Sequence for which GC-content and GC3-content will be evaluated. Result annotation Resulted annotations, with GC-content and GC3-content. GC-content Evaluate GC-content GC1-content Evaluate GC1-content GC2-content Evaluate GC2-content GC3-content Evaluate GC3-content DNA statistics Evaluates statistics for DNA sequences Sequence must be nucleotide No statistics was selected U2::LocalWorkflow::DNAStatWorkerPrompter Evaluates GC-Content and GC3-Content U2::LocalWorkflow::ExternalProcessWorker output data Can't open document U2::LocalWorkflow::ExternalProcessWorkerPrompter unset не указан <u>%1</u> U2::LocalWorkflow::FastaReader Reading FASTA from %1 Читается блок данных FASTA из %1 U2::LocalWorkflow::FilterAnnotationsPrompter unset не указан Filter annotations from <u>%1</u> by supplied names. U2::LocalWorkflow::FilterAnnotationsTask Filter annotations task U2::LocalWorkflow::FilterAnnotationsWorker Input annotations Annotations to be filtered by name. Result annotations Resulted annotations, filtered by name. Annotation names File with annotation names, separated with whitespaces or list of annotation names which will be accepted or filtered. Use space as the separator. Accept or filter Selects the name filter: accept specified names or accept all except specified Filter annotations by name Filters annotations by name U2::LocalWorkflow::FindAllRegionsTask FindAllRegionsTask U2::LocalWorkflow::FindPrompter unset не указан translated транслированной A substring must %1. match a pattern exactly Maximum number of mismatches is %1. A substring must <u>match a pattern exactly</u>. Подпоследовательность должна <u>в точности совпадать с паттерном</u>. Maximum <u>number of mismatches is %1</u>. Максимальное <u>число несовпадений: %1</u>. Searches regions in each sequence from <u>%1</u> similar to <u>%2</u> pattern(s).<br/>%3<br/>Searches in <u>%4</u> of a %5sequence. Outputs the regions found annotated as <u>%6</u>. В каждой последовательности, полученной от <u>%1</u> ищет регионы, похожие на паттерн(ы) <u>%2</u>.<br/>%3<br/>Поиск ведется в <u>%4</u> %5последовательности.<br/>Возвращает найденные регионы как <u>%6</u> аннотации. U2::LocalWorkflow::FindWorker Found %1 matches of pattern '%2' Найдено %1 вхождений паттерна "%2" Input Data Входная последовательность An input sequence to search in. Последовательность, для которой применяется алгоритм поиска. Pattern Annotations Найденные аннотации The regions found. Аннотации, найденные для последовательности. Name of the result annotations. Имя аннотаций для найденных регионов. Pattern(s) Паттерн(ы) Semicolon-separated list of patterns to search for. Список паттернов для поиска. Max Mismatches Допустимо несовпадений Maximum number of mismatches between a substring and a pattern. Максимальное допустимое число несовпадений между подпоследовательностью и паттерном. Allow Insertions/Deletions Разрешить вставки/делеции Takes into account possibility of insertions/deletions when searching. By default substitutions are only considered. В случае когда допустимы несовпадения между подпоследовательностью и паттерном учитывает вставки/делеции. По умолчанию учитываются только замены. Support ambiguous bases Performs correct handling of ambiguous bases. When this option is activated insertions and deletions are not considered. Search in Translation Искать в трансляции Translates a supplied nucleotide sequence to protein and searches in the translated sequence. Указывает транслировать входную нуклеотидную последовательность в протеиновую и искать указанный паттерн в полученной протеиновой последовательности. Find Substrings Поиск паттернов Searches regions in a sequence similar to a pattern sequence. Outputs a set of annotations. Поиск подпоследовательностей, похожих на указанный паттерн, в каждой входной последовательности (нуклеотидной или протеиновой). both strands в обеих цепях direct strand прямой цепи complement strand комплементарной цепи Empty pattern given Find algorithm subtasks Annotate as Аннотации Null sequence supplied to FindWorker: %1 Пустая последовательность для поиска подстрок: %1 U2::LocalWorkflow::GenbankReader Reading GENBANK data from %1 Читается запись Genbank из %1 U2::LocalWorkflow::ImportAnnotationsWorker Load documents with annotations Input annotations Input annotation table. Read annotations will be added to it Output annotations Output annotation table Merge annotations Read input annotation table and merge it with supplied annotation tables Merge input annotations with annotations from <u>%1</u>. U2::LocalWorkflow::LaunchExternalToolTask Can't launch %1 U2::LocalWorkflow::LoadMSATask File '%1' not exists Файл '%1' не существует Reading MSA from %1 [%2] Читается множественное выравнивание из %1 [формат %2] Read MSA from %1 Чтение выравнивания из %1 Unsupported document format Неподдерживаемый формат документа U2::LocalWorkflow::LoadSeqTask File '%1' not exists Файл '%1' не существует Reading sequences from %1 [%2] Читается последовательность из %1 [формат %2] Read sequences from %1 Чтение последовательности из %1 Unsupported document format Неподдерживаемый формат документа U2::LocalWorkflow::LocalDocWriter Writing to %1 [%2] Запись %1 [формат %2] Save documents Сохранение документов Unspecified URL to write %1 Пустой адрес для записи %1 U2::LocalWorkflow::MSAFromSequencesTask MSAFromSequencesTask U2::LocalWorkflow::MSAReader Reading MSA from %1 [%2] Читается множественное выравнивание из %1 U2::LocalWorkflow::MSAWriter Empty alignment passed for writing to %1 Пустое выравнивание для записи в %1 U2::LocalWorkflow::RCWorker Input sequence The sequence to be complemented Output sequence Reverse-complement sequence Operation type Select what to do with sequence Reverse Complement Converts input sequence into its reverse, complement or reverse-complement counterpart Null sequence supplied to FindWorker: %1 Пустая последовательность для поиска подстрок: %1 Can't complement amino sequence Can't find complement translation U2::LocalWorkflow::RCWorkerPrompter unset не указан from <u>%1</u> из <u>%1</u> Converts each input sequence from %1 into its %2 counterpart U2::LocalWorkflow::RemoteDBFetcherPrompter unset не указан U2::LocalWorkflow::RemoteDBFetcherWorker sequences последовательности sequence последовательность Save result to <u>%1</u> directory Сохранить результат в директорию <u>%1</u> Reads %1 identified with %2 from <u>%3</u> remote database. %4 Прочитать %1 с идентификтором %2 из удаленной базы данных <u>%3</u>. %4 Cannot create directory '%1' Не удается создать директорию '%1' failed to load item '%1' from '%2' DB : %3 Не удалось загрузить '%1' из базы данных '%2': %3 Read from remote database Загрузить из удаленной базы данных Reads sequences and annotations if any from a remote database. Читaen последовательности и аннотации из удаленной базы данных. Sequence Последовательность Database База данных The database to read from. База данных для чтения. Resource IDs ID Semicolon-separated list of resource IDs in the database. список ID в базе данных, разделенный точками с запятой. Save file to directory Сохранить файл в директорию Directory to store sequence files loaded from a database. Диретория в которую будет сохранены файлы, загруженные из базы данных. U2::LocalWorkflow::ScriptWorker For input port was set empty data type For output port was set empty data type input data output data no script text U2::LocalWorkflow::ScriptWorkerTask Error in line Script worker task U2::LocalWorkflow::SequenceSplitPromter from <u>%1</u>, из <u>%1</u>, which name is с именем which name is not если имя не or others, либо прочие, unset не указан from <u>%1</u> <u>translate</u> it if annotation marks translated subsequence, <u>транслировать</u> если аннотирована трансляция make it <u>reverse-complement</u> if annotation is located on complement strand, <u>комплементировать</u> если аннотация располагается на комплементарном стренде %1 it if annotation marks translated subsequence, translate make it %1 if annotation is located on complement strand, expand it to left with <u>%1</u>, расширить влево на <u>%1</u>, expand it to right with <u>%1</u> расширить враво на <u>%1</u> Extract each annotated sequence region %5 %2 %3%4 Extract each annotated sequence region%1 %2 %3%4 Извлечь каждый аннотированный регион последовательности%1 %2 %3%4 U2::LocalWorkflow::SequenceSplitWorker No sequence provided to split worker Nothing to extract. No annotations provided to split worker Nothing to extract: no sequence region match the constraints Input sequence A sequence which will be split into annotated regions. Annotated regions Resulted subsequences, translated and complemented according to corresponding annotations. Translate Translate the annotated regions. Complement Complement the annotated regions if the corresponding annotation is located on complement strand. Extend left Extend the resulted regions to left Extend right Extend the resulted regions to right Gap length Insert gap of specified length between merged locations of annotation. Get sequences by annotations Creates sequences from annotated regions of input sequence U2::LocalWorkflow::SequencesToMSAPromter Creates multiple sequence alignment from supplied sequences. U2::LocalWorkflow::SequencesToMSAWorker Input sequences Sequences to be joined into alignment. Result alignment Alignment created from the given sequences. Join sequences into alignment Creates multiple sequence alignment from sequences. U2::LocalWorkflow::Text2SequencePrompter unset не указан from <u>%1</u> из <u>%1</u> sequence with name <u>%1</u> Automatically detect sequence alphabet Set sequence alphabet to %1 skipped replaced with symbol Convert input text%1 to %2. %3. Unknown symbols are %4. U2::LocalWorkflow::Text2SequenceWorker Sequence name not set skip flag should be set or replace character defined Alphabet cannot be automatically detected Alphabet '%1' cannot be found Input text A text which will be converted to sequence Output sequence Converted sequence Sequence name Result sequence name Sequence alphabet Select one of the listed alphabets or choose auto to auto-detect Skip unknown symbols Do not include symbols that are not contained in alphabet Replace unknown symbols with Replace unknown symbols with given character Convert text to sequence Converts input text to sequence U2::LocalWorkflow::TextReader Can't load file %1 Не удается загрузить файл %1 Reading text from %1 Читается текст из файла: %1 U2::LocalWorkflow::WorkflowView Invalid content: duplicate process %1 Ошибка: дубликат процесса %1 Invalid content: unknown process type %1 Ошибка: неизвестный тип задачи "%1" Invalid content: unknown port %1 requested for %2 Ошибка: неизвестный порт "%1" у задачи "%2" Invalid content: no such process %1 to bind Ошибка: связь с неизвестным процессом %1 Invalid content: cannot bind [%1 : %2] to [%3 : %4] Ошибка: невозможно связать [%1 : %2] с [%3 : %4] failed to save image to %1 Не удалось сохранить изображение: %1 % % U2::ProduceSchemaImageLinkTask Save workflow schema image Cannot find schema: %1 U2::SamplePane Select a sample to start Выберите пример схемы U2::SamplesWidget Double click to load the sample Двойное нажатие мышью загрузит этот пример U2::SaveWorkflowSceneTask Save workflow scene task U2::SchemaConfigurationDialog Name Имя Default value Значение по умолчанию Run Запуск U2::Workflow::CoreLib Write FASTA Запись FASTA Write FASTQ Запись FASTQ Writes all supplied sequences to file(s) in FASTQ format. Записывает последовательности в файл в формате FASTQ. A sequence in FASTQ format along with PHRED quality scores. Последовательность в формате FASTQ вместе с PHRED качеством. Read plain text Чтение текста Reads text from local or remote files. Считывает текстовые данные из файлов, расположенных локально или удаленно. Write plain text Запись текста Write strings to a file Запись текстовых данных в файл Writes all supplied sequences to file(s) in selected format. Записывает последовательности в файл (ы) в заданном формате. Save all sequences from <u>%1</u> to <u>%2</u>. Сохранить все последовательности из <u>%1</u> в <u>%2</u>. Can't load actor %1 Write Genbank Запись Genbank Write ClustalW Запись ClustalW Write Stockholm Запись Stockholm Accumulate objects Аккумулировать данные Source URL Адрес источника Sequence Последовательность Plain text Текстовые данные Just a plain text w/o splitting to strings. Просто неформатированный текст. FASTA header Заголовок FASTA Save text from <u>%1</u> to document <u>%2</u>. Сохранить текстовые данные из <u>%1</u> в документ <u>%2</u>. Save all MSAs from <u>%1</u> to document <u>%2</u>. Сохранить все выравнивания из <u>%1</u> в документ <u>%2</u>. Location Путь к файлу Document format Формат документа Document format of output file Формат документа выходного файла Sequence and set of annotations Последовательность и набор аннотаций Reads text from <u>%1</u>. Прочитать текст из <u>%1</u>. Save text from <u>%1</u> to <u>%2</u>. Сохранить текст из <u>%1</u> в <u>%2</u>. Multiple sequence alignment Множественное выравнивание Save all MSAs from <u>%1</u> to <u>%2</u>. Сохранить множественные выравнивания из <u>%1</u> в <u>%2</u>. Write alignment Запись множественного выравнивания Writes all supplied alignments to file(s) in selected format Запись всех входных выравниваний в файл(ы) в выбранном формате Write sequence Запись последовательности Read sequence Чтение последовательности Reads sequence(s) from <u>%1</u>. Читает последовательнсоти из <u>%1</u>. Read alignment Чтение множественного выравнивания Reads MSA(s) from <u>%1</u>. Прочитать выравнивания из <u>%1</u>. Read all sequences from <u>%1</u> and output each in turn. Прочитать последовательности из <u>%1</u>. A sequence of any type (nucleotide, protein). Биологические последовательности разных видов (ДНК, РНК, протеины). Location of data file(s) Адрес файла данных Location of a corresponding input file. Адрес файла соответствующего выдаваемым данным. Accumulate all incoming data in one file or create separate files for each input.In the latter case, an incremental numerical suffix is added to the file name. Накапливать все входящие данные в один файл либо создавать отдельные файлы для каждого пакета данных. В последнем случае, к указанному имени файла добавляется числовой суффикс, инкрементируемый при каждой записи. Location for writing data Путь к файлу для записи данных A header line for the FASTA record. Строка заголовка FASTA. A sequence along with FASTA header line. Последовательность вместе с заголовком FASTA. Writes all supplied sequences to file(s) in FASTA format. Запись всех входящих данных в файл(ы) в формате FASTA. Writes all supplied sequences and related annotations to file(s) in Genbank format. Запись всех входящих данных в файл(ы) в формате Genbank. Input data Входные данные Writes all supplied alignments to file(s) in CLUSTALW format. Запись всех входящих выравниваний в файл(ы) в формате CLUSTALW. Reads multiple sequence alignments (MSAs) from local or remote files.<p>Besides the known alignment formats, it supports composing an alignment from a set of sequences in a corresponding file (e.g. FASTA or Genbank). Считывает выравнивания из файлов, расположенных локально или удаленно. <p>Помимо чтения готовых выравниваний известных форматов, поддерживается автоматическое составление выравниваний из наборов последовательностей, которые могут быть прочитаны из файла любого подходящего формата. Writes all supplied alignments to file(s) in Stockholm format. Запись всех входящих выравниваний в файл(ы) в формате Stockholm. Sequence reader Чтение последовательностей Reads sequences and annotations if any from local or remote files. Считывает последовательности вместе с аннотациями из файлов, расположенных локально или удаленно. Alignment reader Чтение выравниваний U2::Workflow::SeqReadPrompter Mode Режим If the file contains more than one sequence, "split" mode sends them as is to output,while "merge" appends all the sequences and outputs the sole merged sequence. При наличии более одной последовательности в файле, возможно выдавать их по одной либо сшить в одну объединённую последовательность. Merging gap Сшивка пропусками In the "merge" mode, insert the specified number of gaps between original sequences.This is helpful e.g. to avoid finding false positives at the merge boundaries. В режиме сшивки, добавлять указанное число пропусков между исходными последовательностиями. Это, в частности, помогает избежать нахождения ложных совпадений или сигналов на границах сшивки исходных последовательностей. Split Раздельные последовательности Merge Соединить последовательности в одну Accession filter Фильтр по Accession Only report sequence with the specified accession (id). Выдавать только последовательности с указанным accession (id). U2::Workflow::WriteDocPrompter unset не указан U2::Workflow::WriteFastaPrompter For each sequence from <u>%1</u>, add entry to document <u>%2</u>. Для каждой последовательности из <u>%1</u>, добавить блок FASTA в документ <u>%2</u>. Writes sequence(s) in %1 format to <u>%2</u>. Запись последовательностей в формате %1 в <u>%2</u>. Writes sequence(s) from <u>%1</u> in %2 format to <u>%3</u>. Запись последовательностей из <u>%1</u> в <u>%3</u> в формате %2. U2::Workflow::WriteGenbankPrompter sequence from <u>%1</u> последовательности из <u>%1</u> set of annotations from <u>%1</u> набора аннотаций из <u>%1</u> Write sequence(s) in Genbank format to <u>%1</u>. Запись последовательностей в формате Genbank в <u>%1</u>. each %1 and %2 каждые %1 и %2 each каждые Write %1 in Genbank format, to <u>%2</u>. Запись %1 в формате Genbank в <u>%2</u>. For each %1 and %2 Для каждых %1 и %2 For each Для каждого(ой) %1, add Genbank entry to document <u>%2</u>.%3 %1, добавить запись Genbank в документ <u>%2</u>.%3 U2::WorkflowDesignerPlugin Workflow Designer Дизайнер вычислительных схем Workflow Designer allows to create complex computational workflows. Дизайнер вычислительных схем позволяет создавать и переиспользовать многоэтапные алгоритмы обработки данных. Алгоритмы создаются в виде визуальных диаграмм потоков данных, не требуя навыков программирования или знания языков программирования. Runs the specified task. Выполняет указанную задачу. Runs the specified task. A path to a user-defined UGENE workflow schema can be used as a task name. Выполняет указанную задачу. Пусть у заданной пользоваталем workflow схеме не может использоваться как имя задачи. <task_name> [<task_parameter>=value ...] Close Designer Закрытие Дизайнера Схем Close Designer canceled Закрытие Дизайнера Схем отменено U2::WorkflowDesignerService Workflow Designer Дизайнер вычислительных схем Workflow Designer... Дизайнер вычислительных схем... U2::WorkflowDocFormat Invalid content: %1 Невалидное содержимое xml: %1 Workflow Schema Вычислительная схема UGENE Invalid header. %1 expected Неверный заголовок. Ожидается %1 U2::WorkflowEditor Element name: Имя элемента: Input data Входные данные Output data Выходные данные Select an element to inspect. Выберите элемент для просмотра или редактирования. To configure the parameters of the element go to "Parameters" area below. Параметры элемента можно отредактировать в таблице, расположенной ниже. You can observe data slots of the port and configure connections if any in the "Parameters" widget suited below. Слоты данных, входящие в порт, указаны в таблице, расположенной немного ниже. <br>Там же можно изменить привязку данных в связях, если они есть. <b>%1 "%2"</b> of task "%3":<br>%4<br><br>%5 <b>%1 "%2"</b> задачи "%3":<br>%4<br><br>%5 Parameters Параметры Output port Выходной порт Input port Входной порт Name Имя Value Значение Script Скрипт U2::WorkflowMetaDialog Save workflow schema to file Выберите файл для сохранения схемы U2::WorkflowPalette Expand all Развернуть все Collapse all Свернуть все Edit Изменить Remove Удалить Can't remove element %1 Не могу удалить элемент %1 U2::WorkflowRemoteRunFromCMDLineTask %1 parameter expected, but not set Не установлен параметр %1 Cannot read remote machine settings from %2 Не удается прочитать настройки удаленной машины из %2 U2::WorkflowRemoteRunTask Workflow run task on remote machine Запуск вычислительной схемы на удаленном компьютере remote machine settings Настройки удаленной машины Cannot create remote machine from remote machine settings: %1 Не удалось создать удаленную машину из следующих настроек:%1 remote task didn't produce result Удаленная задача не вернула результат Workflow run task runned on remote machine. Запуск вычислительной схемы на удаленной машине. Task finished with error Задача завершилась с ошибкой U2::WorkflowRunFromCMDLineBase Workflow run from cmdline no task to run Cannot find schema: %1 alias '%1' not set in schema actor parameter '%1' not found cannot parse value from '%1' Incorrect value for '%1', null or default value passed to schema U2::WorkflowScene Drop an element from the palette here Перетащите сюда элемент из палитры U2::WorkflowSettingsPageController Workflow Designer Дизайнер вычислительных схем U2::WorkflowSimpleLocalTask Workflow simple local task Внешняя задача запуска вычислительной схемы No settings given Не заданы настройки задания Workflow local task was canceled Внешняя задача запуска вычислительной схемы отменено Alien Workflow simple task from remote machine. Внешняя задача запуска вычислительной схемы с удаленного компьютера. Task finished with error Задача завершилась с ошибкой U2::WorkflowView Workflow Designer Дизайнер схем Error list Проблемы % % You opened obsolete schema in XML format. It is strongly recommended to clear working space and create schema from scratch. Вы открыли устаревшую схему в формате XML. Настоятельно рекомендуем очистить рабочее пространство и создать схему с нуля. Sorry! This schema is obsolete and cannot be opened. Эта схема устарела и не можеть быть открыта. Warning! Предупреждение! Undefined workflow format for %1 Неизвестный workflow формат в %1 file файл &Run schema &Выполнить схему S&top schema О&становить выполнение схемы &Validate schema &Проверить схему &New schema Создать &новую схему &Save schema &Сохранить схему &Save schema as... &Сохранить как схему как... &Load schema &Открыть схему &Export schema &Экспорт схемы Delete Удалить Create element with script... Edit script of the element... Create element with command line tool... Add element with command line tool... Open worker file Can't load element. Element style Стиль Configure iterations Редактировать итерации Configure command line aliases Редактировать параметры запуска схемы через консоль Select all elements Выбрать все элементы Bring to front На передний план Send to back На задний план &Copy &Копировать Cu&t &Вырезать &Paste &Вставить Minimal Упрощённый Extended Развёрнутый Add element Добавить элемент Local host Данный компьютер Remote machine Удаленный компьютер Hide scripting options Не показывать опции скриптинга Show scripting options Показывать опции скриптинга Edit script text Редактировать текст скрипта Run mode Тип запуска Scripting mode Element properties Empty schema! Пустая схема! Nothing to run: empty workflow schema Пустая схема Schema cannot be executed Схема не может быть выполнена Please fix issues listed in the error list (located under schema). Необходимо исправить ошибки (смотрите список внизу окна). Schema is valid Схема корректна Schema is valid. Well done! В схеме ошибок не найдено. Хорошая работа! Selecting machines error! Ошибка выбора удаленных машин! You didn't select a machine to run remote task! Не выбрана машина для удаленного запуска! Distributed run on many machines is not supported yet. Select 1 machine Распределенный запуск на нескольких машинах в данный пока не поддерживается. Выберите одну машину Bad input! Неверные входные данные! Aliases for schema parameters should be different! Параметры для схемы должны быть различны! Export workflow schema to image Выберите файл изорбражения Saving scene image to file: %1 Экспорт изображения схемы в файл: %1 failed to save image to %1 Не удалось сохранить изображение: %1 Open workflow schema file Выберите файл вычислительной схемы UGENE New schema Новая схема Workflow Designer - %1 Дизайнер схем - %1 The schema has been modified. Do you want to save changes? Схема была изменена. Сохранить изменения? Drag the palette element to the scene or just click on the scene to add the element. Перетащите элемент из палитры на плоскость или просто кликните мышью в нужном месте схемы. Elements Элементы Samples Примеры Configure command line aliases... Параметры для запуска схемы из консоли... Configure iterations... Итерации... Unlock Scene Разблокировать схему Item properties Свойства объекта Invalid content: duplicate process %1 Ошибка: дубликат процесса %1 Invalid content: unknown process type %1 Ошибка: неизвестный тип задачи "%1" Invalid content: unknown port %1 requested for %2 Ошибка: неизвестный порт "%1" у задачи "%2" Invalid content: no such process %1 to bind Ошибка: связь с неизвестным процессом %1 Invalid content: cannot bind [%1 : %2] to [%3 : %4] Ошибка: невозможно связать [%1 : %2] с [%3 : %4] U2::WorkflowViewFactory Open multiple views Открытие нескольких окон WorkflowEditor Name Имя Value Значение WorkflowEditorWidget Form Property Editor Редактор объектов TextLabel Iterations Итерации Parameters Параметры Input data Входные данные Output data Выходные данные WorkflowMetaDialog Workflow properties Описание схемы Location Путь ... Name Имя Comment Комментарий OK Сохранить Cancel Отменить WorkflowSettingsWidget Resource settings Scene appearance Сцена Element style Стиль Element font Шрифт Element background color Цвет фона Directory for custom elements with scripts Директория для элементов пользователя со скриптами Directory for custom elements with command line tools Директория для элементов пользователя с внешними утилитами Show grid Показывать сетку Track running progress Отображать прогресс выполнения схемы Directories Директории Run tasks in separate process Запускать задачи в отдельном процессе Snap to grid Привязываться к сетке Runtime settings Исполнение схем WorkflowUtils UGENE workflow element ugene-1.9.8/src/plugins/workflow_designer/transl/english.ts0000644000175000017500000037401411651544325022637 0ustar ilyailya ChooseItemDialog Choose task type Add a task of the following type: OK Cancel CreateExternalProcessWorkerDialog Create Element with Command Line Tool <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> <html><head><meta name="qrichtext" content="1" /><style type="text/css"> p, li { white-space: pre-wrap; } </style></head><body style=" font-family:'MS Shell Dlg 2'; font-size:8.25pt; font-weight:400; font-style:normal;"> <p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-size:8pt;">Name and description for new workflow element.</span></p></body></html> Element description Name Description <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> <html><head><meta name="qrichtext" content="1" /><style type="text/css"> p, li { white-space: pre-wrap; } </style></head><body style=" font-family:'MS Shell Dlg 2'; font-size:8.25pt; font-weight:400; font-style:normal;"> <p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-size:8pt;">Input and output data for external tool. Name is a command line parameter for input/output data in external tool. Set data type and format in which external tool reads/writes input/output data. You also can set description for workflow designer. Each input data will be represented as port in workflow designer. Each output data will be represented as slot of single slot.</span></p></body></html> Input data Add input Delete Output data Add output <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> <html><head><meta name="qrichtext" content="1" /><style type="text/css"> p, li { white-space: pre-wrap; } </style></head><body style=" font-family:'MS Shell Dlg 2'; font-size:8.25pt; font-weight:400; font-style:normal;"> <p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-size:8pt;">Another parameters for external tool. You must set name for parameter and its type. You also can set description for workflow designer. Each parameter will be represented as parameter of workflow element.</span></p></body></html> Parameters Add attribute <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> <html><head><meta name="qrichtext" content="1" /><style type="text/css"> p, li { white-space: pre-wrap; } </style></head><body style=" font-family:'MS Shell Dlg 2'; font-size:8.25pt; font-weight:400; font-style:normal;"> <p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-size:8pt;">Execution string and element's description. To substitute input, output data or parameter, use it's name with prefix $ in execution string. You can set parameterized description for new element(description that appears not in property editor but on element itself). In parameterized description you also can use parameters substitution with prefix $.</span></p></body></html> Command line template Execution string Parameterized description CreateScriptBlockDialog Create Element with Script Name ScriptBlock Description <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> <html><head><meta name="qrichtext" content="1" /><style type="text/css"> p, li { white-space: pre-wrap; } </style></head><body style=" font-family:'MS Shell Dlg 2'; font-size:8.25pt; font-weight:400; font-style:normal;"> <p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-size:8pt;">Evaluates user's script</span></p></body></html> Input Port Add input slot Delete input slot Output Port Add output slot Delete output slot Attributes Add Attribute Delete Attribute Error Error occured while saving new actor. Can't write to current directory. Choose another directory for store user's elements ... OK Cancel SchemaAliasesConfigurationDialog Configure command line aliases Workflow elements Schema parameter Command line alias Help message Ok Cancel SchemaConfigurationDialog Configure Schema Iterations Parameters U2::ActorCfgModel N/A U2::CreateExternalProcessDialog Name for command line parameter Type Format Description Name Create Element Please set the input/output data. Please set the command line to run external tool. Please set the name for the new element. Invalid symbols in the element name. Element with this name already exists. For one or more parameter name was not set. Invalid symbols in a name. The same name of element parameters was found You don't use parameter %1 in template string. Continue? Continue Abort U2::CreateScriptElementDialog Name type error Two identical types for input port two identical types for input port Two identical types for output port two identical types for output port Name for some attributes is empty Two attributes with name %1 Name for block is empty Actor with this name already registered Description for block is empty Can't save user's workflow element U2::ExtendedProcStyle Auto-resize to text U2::HRSceneSerializer Unexpected end of file Cannot parse coordinates from '%1' Cannot parse real value from '%1' Cannot parse 4 integer numbers from '%1' Cannot parse font from '%1' Cannot parse rectangle from '%1' %1 element undefined in visual block No other blocks allowed in visual block '%1' %1 does not has %2 style Cannot find port '%1' at %2 element Cannot parse real number from: '%1' Undefined visual key: '%1' for actor %2 Undefined element id: '%1' Cannot find '%1' port at '%2' No other blocks allowed in link parameters block '%1' Key '%1' not recognized as flow parameter Cannot bind %1:%2 to %3:%4 U2::ItemViewStyle Background color Font U2::IterationListWidget Copy of %1 New Iteration Clone Add Remove All Default iteration Workflow Designer Do you want to divide the list into separate iterations? If you need to process each item in the list with different schema parameters, the Designer can create separate iterations for each item now. Otherwise, if all items should be processed uniformly, it is better to leave the list intact. U2::LoadSamplesTask Load workflow samples Sample dir does not exist: %1 Failed to load sample: %1 U2::LoadWorkflowSceneTask Load workflow scene Undefined format: plain text or xml expected Error while parsing file: %1 U2::LocalWorkflow::Alignment2SequencePrompter unset from <u>%1</u> Split alignment%1 into sequences U2::LocalWorkflow::Alignment2SequenceWorker empty input alignment Input alignment A alignment which will be split into sequences Output sequences Converted sequences Split alignment into sequences Splits input alignment into sequences U2::LocalWorkflow::BaseDocWriter Document format not set Unspecified URL to write %1 Writing to %1 [%2] Save documents U2::LocalWorkflow::CDSearchPrompter unset from <u>%1</u> For sequence %1 find conserved domains in database <u>%2</u> U2::LocalWorkflow::CDSearchWorker Input sequence The sequence to search the annotations for Annotations Found annotations Database Currently, CD-Search is offered with the following search databases:<br><ul><li><b>CDD</b> - this is a superset including <a href="http://www.ncbi.nlm.nih.gov/Structure/cdd/cdd_help.shtml#CDSource_NCBI_curated">NCBI-curated domains</a> and <a href="http://www.ncbi.nlm.nih.gov/Structure/cdd/cdd_help.shtml#CDSource_external">data imported</a> from Pfam, SMART, COG, PRK, and TIGRFAM.</li><li><b>Pfam</b> - a mirror of a recent Pfam-A database of curated seed alignments. Pfam version numbers do change with incremental updates. As with SMART, families describing very short motifs or peptides may be missing from the mirror. An HMM-based search engine is offered on the <a href="http://pfam.sanger.ac.uk/">Pfam</a> site.</li><li><b>SMART</b> - a mirror of a recent SMART set of domain alignments. Note that some SMART families may be missing from the mirror due to update delays or because they describe very short conserved peptides and/or motifs, which would be difficult to detect using the CD-Search service. You may want to try the HMM-based search service offered on the <a href="http://smart.embl-heidelberg.de">SMART</a> site. Note also that some SMART domains are not mirrored in CD because they represent "superfamilies" encompassing several individual, but related, domains; the corresponding seed alignments may not be available from the source database in these cases. Note also that SMART version numbers do not change with incremental updates of the source database (and the mirrored CD-Search database).</li> <li><b>TIGRFAM</b> - a mirror of a recent TIGRFAM set of domain alignments. An HMM-based search engine is offered on the <a href="http://www.jcvi.org/cms/research/projects/tigrfams/overview/"><!-- a href="http://blast.jcvi.org/web-hmm/" -->TIGRFAM</a> site.</li><li><b>COG</b> - a mirror of the current COG database of orthologous protein families focusing on prokaryotes. Seed alignments have been generated by an automated process. An alternative search engine, "Cognitor", which runs protein-BLAST against a database of COG-assigned sequences, is offered on the <a href="http://www.ncbi.nlm.nih.gov/COG">COG</a> site.</li><li><b>KOG</b> - a eukaryotic counterpart to the COG database. KOGs are not included in the CDD superset, but are searchable as a separate data set.</li></ul><br>More information about each database is provided in the section on <a href="http://www.ncbi.nlm.nih.gov/Structure/cdd/cdd_help.shtml#CDSource">Where does CDD content come from?</a> Annotate as Name of the result annotations marking found conserved domains. Local search Perform the search on local machine or submit the search to NCBI for remote execution. Expect value Modifies the <a href="http://www.ncbi.nlm.nih.gov/BLAST/blastcgihelp.shtml#expect">E-value</a> threshold used for filtering results. False positive results should be very rare with the default setting of 0.01 (use a more conservative, i.e. lower setting for more reliable results), results with E-values in the range of 1 and above should be considered putative false positives. Database directory Specifies database directory for local search. CD-Search Finds conserved domains in protein sequences. In case conserved domains database is downloaded the search can be executed on local machine. The search also can be submitted to the NCBI for remote execution. 'External tools' plugin has to be loaded. 'Remote blast' plugin has to be loaded. U2::LocalWorkflow::DNAStatWorker Input sequence Sequence for which GC-content and GC3-content will be evaluated. Result annotation Resulted annotations, with GC-content and GC3-content. GC-content Evaluate GC-content GC1-content Evaluate GC1-content GC2-content Evaluate GC2-content GC3-content Evaluate GC3-content DNA statistics Evaluates statistics for DNA sequences Sequence must be nucleotide No statistics was selected U2::LocalWorkflow::DNAStatWorkerPrompter Evaluates GC-Content and GC3-Content U2::LocalWorkflow::ExternalProcessWorker output data Can't open document U2::LocalWorkflow::ExternalProcessWorkerPrompter unset <u>%1</u> U2::LocalWorkflow::FilterAnnotationsPrompter unset Filter annotations from <u>%1</u> by supplied names. U2::LocalWorkflow::FilterAnnotationsTask Filter annotations task U2::LocalWorkflow::FilterAnnotationsWorker Input annotations Annotations to be filtered by name. Result annotations Resulted annotations, filtered by name. Annotation names File with annotation names, separated with whitespaces or list of annotation names which will be accepted or filtered. Use space as the separator. Accept or filter Selects the name filter: accept specified names or accept all except specified Filter annotations by name Filters annotations by name U2::LocalWorkflow::FindAllRegionsTask FindAllRegionsTask U2::LocalWorkflow::FindPrompter unset translated A substring must %1. match a pattern exactly Maximum number of mismatches is %1. Searches regions in each sequence from <u>%1</u> similar to <u>%2</u> pattern(s).<br/>%3<br/>Searches in <u>%4</u> of a %5sequence. Outputs the regions found annotated as <u>%6</u>. U2::LocalWorkflow::FindWorker Input Data An input sequence to search in. Pattern Annotations The regions found. Name of the result annotations. Pattern(s) Semicolon-separated list of patterns to search for. Max Mismatches Maximum number of mismatches between a substring and a pattern. Allow Insertions/Deletions Takes into account possibility of insertions/deletions when searching. By default substitutions are only considered. Support ambiguous bases Performs correct handling of ambiguous bases. When this option is activated insertions and deletions are not considered. Search in Translation Translates a supplied nucleotide sequence to protein and searches in the translated sequence. Find Substrings Searches regions in a sequence similar to a pattern sequence. Outputs a set of annotations. both strands direct strand complement strand Null sequence supplied to FindWorker: %1 Empty pattern given Find algorithm subtasks Found %1 matches of pattern '%2' Annotate as U2::LocalWorkflow::ImportAnnotationsWorker Load documents with annotations Input annotations Input annotation table. Read annotations will be added to it Output annotations Output annotation table Merge annotations Read input annotation table and merge it with supplied annotation tables Merge input annotations with annotations from <u>%1</u>. U2::LocalWorkflow::LaunchExternalToolTask Can't launch %1 U2::LocalWorkflow::LoadMSATask File '%1' not exists Unsupported document format Reading MSA from %1 [%2] Read MSA from %1 U2::LocalWorkflow::LoadSeqTask File '%1' not exists Unsupported document format Reading sequences from %1 [%2] Read sequences from %1 U2::LocalWorkflow::MSAFromSequencesTask MSAFromSequencesTask U2::LocalWorkflow::MSAWriter Empty alignment passed for writing to %1 U2::LocalWorkflow::RCWorker Input sequence The sequence to be complemented Output sequence Reverse-complement sequence Operation type Select what to do with sequence Reverse Complement Converts input sequence into its reverse, complement or reverse-complement counterpart Null sequence supplied to FindWorker: %1 Can't complement amino sequence Can't find complement translation U2::LocalWorkflow::RCWorkerPrompter unset from <u>%1</u> Converts each input sequence from %1 into its %2 counterpart U2::LocalWorkflow::RemoteDBFetcherPrompter unset U2::LocalWorkflow::RemoteDBFetcherWorker sequences sequence Save result to <u>%1</u> directory Reads %1 identified with %2 from <u>%3</u> remote database. %4 Cannot create directory '%1' failed to load item '%1' from '%2' DB : %3 Read from remote database Reads sequences and annotations if any from a remote database. Sequence Database The database to read from. Resource IDs Semicolon-separated list of resource IDs in the database. Save file to directory Directory to store sequence files loaded from a database. U2::LocalWorkflow::ScriptWorker For input port was set empty data type For output port was set empty data type input data output data no script text U2::LocalWorkflow::ScriptWorkerTask Error in line Script worker task U2::LocalWorkflow::SequenceSplitPromter unset from <u>%1</u> %1 it if annotation marks translated subsequence, translate make it %1 if annotation is located on complement strand, expand it to left with <u>%1</u>, expand it to right with <u>%1</u> Extract each annotated sequence region %5 %2 %3%4 U2::LocalWorkflow::SequenceSplitWorker No sequence provided to split worker Nothing to extract. No annotations provided to split worker Nothing to extract: no sequence region match the constraints Input sequence A sequence which will be split into annotated regions. Annotated regions Resulted subsequences, translated and complemented according to corresponding annotations. Translate Translate the annotated regions. Complement Complement the annotated regions if the corresponding annotation is located on complement strand. Extend left Extend the resulted regions to left Extend right Extend the resulted regions to right Gap length Insert gap of specified length between merged locations of annotation. Get sequences by annotations Creates sequences from annotated regions of input sequence U2::LocalWorkflow::SequencesToMSAPromter Creates multiple sequence alignment from supplied sequences. U2::LocalWorkflow::SequencesToMSAWorker Input sequences Sequences to be joined into alignment. Result alignment Alignment created from the given sequences. Join sequences into alignment Creates multiple sequence alignment from sequences. U2::LocalWorkflow::Text2SequencePrompter unset from <u>%1</u> sequence with name <u>%1</u> Automatically detect sequence alphabet Set sequence alphabet to %1 skipped replaced with symbol Convert input text%1 to %2. %3. Unknown symbols are %4. U2::LocalWorkflow::Text2SequenceWorker Sequence name not set skip flag should be set or replace character defined Alphabet cannot be automatically detected Alphabet '%1' cannot be found Input text A text which will be converted to sequence Output sequence Converted sequence Sequence name Result sequence name Sequence alphabet Select one of the listed alphabets or choose auto to auto-detect Skip unknown symbols Do not include symbols that are not contained in alphabet Replace unknown symbols with Replace unknown symbols with given character Convert text to sequence Converts input text to sequence U2::LocalWorkflow::TextReader Can't load file %1 Reading text from %1 U2::ProduceSchemaImageLinkTask Save workflow schema image Cannot find schema: %1 U2::SaveWorkflowSceneTask Save workflow scene task U2::SchemaConfigurationDialog Name Default value Run U2::Workflow::CoreLib Location Location for writing data Write FASTA Writes all supplied sequences to file(s) in FASTA format. Sequence A sequence along with FASTA header line. Write FASTQ Writes all supplied sequences to file(s) in FASTQ format. A sequence in FASTQ format along with PHRED quality scores. Write Genbank Writes all supplied sequences and related annotations to file(s) in Genbank format. Sequence and set of annotations Read plain text Reads text from local or remote files. Plain text Reads text from <u>%1</u>. Write plain text Write strings to a file Save text from <u>%1</u> to <u>%2</u>. Write ClustalW Writes all supplied alignments to file(s) in CLUSTALW format. Multiple sequence alignment Save all MSAs from <u>%1</u> to <u>%2</u>. Write Stockholm Writes all supplied alignments to file(s) in Stockholm format. Write alignment Writes all supplied alignments to file(s) in selected format Write sequence Writes all supplied sequences to file(s) in selected format. Save all sequences from <u>%1</u> to <u>%2</u>. Can't load actor %1 Read sequence Reads sequences and annotations if any from local or remote files. A sequence of any type (nucleotide, protein). Reads sequence(s) from <u>%1</u>. Read alignment Reads multiple sequence alignments (MSAs) from local or remote files.<p>Besides the known alignment formats, it supports composing an alignment from a set of sequences in a corresponding file (e.g. FASTA or Genbank). Reads MSA(s) from <u>%1</u>. U2::Workflow::SeqReadPrompter Mode If the file contains more than one sequence, "split" mode sends them as is to output,while "merge" appends all the sequences and outputs the sole merged sequence. Merging gap In the "merge" mode, insert the specified number of gaps between original sequences.This is helpful e.g. to avoid finding false positives at the merge boundaries. Accession filter Only report sequence with the specified accession (id). U2::Workflow::WriteDocPrompter unset U2::Workflow::WriteFastaPrompter Writes sequence(s) in %1 format to <u>%2</u>. Writes sequence(s) from <u>%1</u> in %2 format to <u>%3</u>. U2::Workflow::WriteGenbankPrompter sequence from <u>%1</u> set of annotations from <u>%1</u> Write sequence(s) in Genbank format to <u>%1</u>. each %1 and %2 each Write %1 in Genbank format, to <u>%2</u>. U2::WorkflowDesignerPlugin Workflow Designer Workflow Designer allows to create complex computational workflows. Runs the specified task. Runs the specified task. A path to a user-defined UGENE workflow schema can be used as a task name. <task_name> [<task_parameter>=value ...] Close Designer Close Designer canceled U2::WorkflowDesignerService Workflow Designer Workflow Designer... U2::WorkflowDocFormat Workflow Schema Invalid header. %1 expected U2::WorkflowEditor Name Value Script Parameters Element name: To configure the parameters of the element go to "Parameters" area below. <b>%1 "%2"</b> of task "%3":<br>%4<br><br>%5 Output port Input port You can observe data slots of the port and configure connections if any in the "Parameters" widget suited below. Input data Output data Select an element to inspect. U2::WorkflowMetaDialog Save workflow schema to file U2::WorkflowPalette Expand all Collapse all Edit Remove Can't remove element %1 U2::WorkflowRemoteRunFromCMDLineTask %1 parameter expected, but not set Cannot read remote machine settings from %2 U2::WorkflowRunFromCMDLineBase Workflow run from cmdline no task to run Cannot find schema: %1 alias '%1' not set in schema actor parameter '%1' not found cannot parse value from '%1' Incorrect value for '%1', null or default value passed to schema U2::WorkflowScene Drop an element from the palette here U2::WorkflowSettingsPageController Workflow Designer U2::WorkflowView Invalid content: duplicate process %1 Invalid content: unknown process type %1 Minimal Extended % You opened obsolete schema in XML format. It is strongly recommended to clear working space and create schema from scratch. Sorry! This schema is obsolete and cannot be opened. Workflow Designer Elements Samples Error list Warning! Undefined workflow format for %1 file &Run schema S&top schema &Validate schema &New schema &Save schema &Save schema as... &Load schema &Export schema Delete Configure command line aliases... Configure iterations... Create element with script... Edit script of the element... Create element with command line tool... Add element with command line tool... Open worker file Can't load element. Element style Element properties Select all elements &Copy Cu&t &Paste Local host Remote machine Hide scripting options Show scripting options Unlock Scene Run mode Scripting mode Add element Empty schema! Nothing to run: empty workflow schema Schema cannot be executed Please fix issues listed in the error list (located under schema). Schema is valid Schema is valid. Well done! Bad input! Aliases for schema parameters should be different! Drag the palette element to the scene or just click on the scene to add the element. Open workflow schema file New schema Workflow Designer - %1 The schema has been modified. Do you want to save changes? U2::WorkflowViewFactory Open multiple views WorkflowEditorWidget Form Property Editor TextLabel Iterations Parameters Input data Output data WorkflowMetaDialog Workflow properties Location ... Name Comment OK Cancel WorkflowSettingsWidget Resource settings Scene appearance Element style Element font Element background color Directory for custom elements with scripts Directory for custom elements with command line tools Snap to grid Show grid Runtime settings Track running progress Directories Run tasks in separate process WorkflowUtils UGENE workflow element ugene-1.9.8/src/plugins/workflow_designer/workflow_designer.qrc0000644000175000017500000000176411651544325023573 0ustar ilyailya images/delete.png images/editcopy.png images/editcut.png images/editpaste.png images/export.png images/external_cmd_tool.png images/external_cmd_tool_add.png images/filenew.png images/fileopen.png images/filesave.png images/filesaveas.png images/green_circle.png images/leftarrow.png images/mag_circle.png images/ok.png images/rot_arrow.png images/rot_cur.png images/run.png images/script.png images/script_edit.png images/sendtoback.png images/stopTask.png images/table_relationship.png images/tag.png images/toggle.png images/toggle_expand.png images/wd.png ugene-1.9.8/src/plugins/workflow_designer/workflow_designer.pro0000644000175000017500000001005011651544325023572 0ustar ilyailyainclude (workflow_designer.pri) # Input HEADERS += src/ActorCfgModel.h \ src/ChooseItemDialog.h \ src/CreateScriptWorker.h \ src/HRSceneSerializer.h \ src/ItemViewStyle.h \ src/IterationListWidget.h \ src/SceneSerializer.h \ src/SchemaAliasesConfigurationDialogImpl.h \ src/SchemaConfigurationDialog.h \ src/WorkflowDesignerPlugin.h \ src/WorkflowDocument.h \ src/WorkflowEditor.h \ src/WorkflowEditorDelegates.h \ src/WorkflowMetaDialog.h \ src/WorkflowPalette.h \ src/WorkflowSamples.h \ src/WorkflowSceneIOTasks.h \ src/WorkflowSettingsController.h \ src/WorkflowViewController.h \ src/WorkflowViewItems.h \ src/cmdline/WorkflowCMDLineTasks.h \ src/library/BaseDocWorker.h \ src/library/CoreLib.h \ src/library/DocActors.h \ src/library/DocWorkers.h \ src/library/FindWorker.h \ src/library/GenericReadActor.h \ src/library/GenericReadWorker.h \ src/library/ImportAnnotationsWorker.h \ src/library/RemoteDBFetcherWorker.h \ src/library/ScriptWorker.h \ src/library/SequenceSplitWorker.h \ src/library/Text2SequenceWorker.h \ src/library/SequencesToMSAWorker.h \ src/library/FilterAnnotationsWorker.h \ src/library/CDSearchWorker.h \ src/library/ExternalProcessWorker.h \ src/library/StatisticWorkers.h \ src/library/ReverseComplementWorker.h \ src/library/MSA2SequenceWorker.h \ src/library/CreateExternalProcessDialog.h \ src/util/SaveSchemaImageUtils.h FORMS += src/ui/ChooseItemDialog.ui \ src/ui/CreateScriptBlockDialog.ui \ src/ui/SchemaAliasesConfigurationDialog.ui \ src/ui/SchemaConfigurationDialog.ui \ src/ui/WorkflowEditorWidget.ui \ src/ui/WorkflowMetaDialog.ui \ src/ui/WorkflowSettingsWidget.ui \ src/ui/ExternalProcessWorkerDialog.ui SOURCES += src/ActorCfgModel.cpp \ src/ChooseItemDialog.cpp \ src/CreateScriptWorker.cpp \ src/HRSceneSerializer.cpp \ src/ItemViewStyle.cpp \ src/IterationListWidget.cpp \ src/SceneSerializer.cpp \ src/SchemaAliasesConfigurationDialogImpl.cpp \ src/SchemaConfigurationDialog.cpp \ src/WorkflowDesignerPlugin.cpp \ src/WorkflowDocument.cpp \ src/WorkflowEditor.cpp \ src/WorkflowEditorDelegates.cpp \ src/WorkflowMetaDialog.cpp \ src/WorkflowPalette.cpp \ src/WorkflowSamples.cpp \ src/WorkflowSceneIOTasks.cpp \ src/WorkflowSettingsController.cpp \ src/WorkflowViewController.cpp \ src/WorkflowViewItems.cpp \ src/cmdline/WorkflowCMDLineTasks.cpp \ src/library/BaseDocWorker.cpp \ src/library/CoreLib.cpp \ src/library/DocActors.cpp \ src/library/DocWorkers.cpp \ src/library/FindWorker.cpp \ src/library/GenericReadActor.cpp \ src/library/GenericReadWorker.cpp \ src/library/ImportAnnotationsWorker.cpp \ src/library/RemoteDBFetcherWorker.cpp \ src/library/ScriptWorker.cpp \ src/library/SequenceSplitWorker.cpp \ src/library/Text2SequenceWorker.cpp \ src/library/FilterAnnotationsWorker.cpp \ src/library/SequencesToMSAWorker.cpp \ src/library/CDSearchWorker.cpp \ src/library/ExternalProcessWorker.cpp \ src/library/StatisticWorkers.cpp \ src/library/ReverseComplementWorker.cpp \ src/library/MSA2SequenceWorker.cpp \ src/library/CreateExternalProcessDialog.cpp \ src/util/SaveSchemaImageUtils.cpp RESOURCES += workflow_designer.qrc TRANSLATIONS += transl/english.ts transl/russian.ts ugene-1.9.8/src/plugins/biostruct3d_view/0000755000175000017500000000000011651544321017063 5ustar ilyailyaugene-1.9.8/src/plugins/biostruct3d_view/biostruct3d_view.qrc0000644000175000017500000000034511651544321023073 0ustar ilyailya images/logo.png images/restore.png images/lock.png images/world_go.png ugene-1.9.8/src/plugins/biostruct3d_view/images/0000755000175000017500000000000011651544321020330 5ustar ilyailyaugene-1.9.8/src/plugins/biostruct3d_view/images/world_go.png0000644000175000017500000000166011651544321022655 0ustar ilyailyaPNG  IHDRagAMA7tEXtSoftwareAdobe ImageReadyqe<BIDATO[uiO)-P( C0&LH.ꃉ2cL f{0&&F{1{ :87wŅmѴch>- Zs_} `j~7_Ϝ&B-T,<%!U7~0LO?}#'3/Q8,W t%Ŗs7'օ>=26HQx>!|Du vr =:ޏ(e-jԔ`ώPtTlnRV & ,Ƀ\^{#_L 2!|>Ze[Ol{G8,yU,I5g|?l2cX&z(mۮOi*M3,p4"H6px7@d۱;qJx;E^siWgR  E\ZשVLOr/>ֲj6'4=5!aJn7hUK ݜ EOj]HʦtW8oΟA(Z!D,ѿ='>d§O:ե޻pfiZ0rf )R~%U('"PS2}V 8ݸ;Y}IENDB`ugene-1.9.8/src/plugins/biostruct3d_view/images/lock.png0000644000175000017500000000060711651544321021771 0ustar ilyailyaPNG  IHDR7gAMA7tEXtSoftwareAdobe ImageReadyqe<IDAT(cπbZ*=S6MX,VrG [a(X$=č3X$CS0_dƽͭkA( Oгe~uP!w> Oy۽iVEjP؎)7D fNz5azy\gʭ\%ᾘ8Anj2䛑<^az嵌k'3od^Q'X{Mg1.ۚ%F5=',qpkEDR%HOIENDB`ugene-1.9.8/src/plugins/biostruct3d_view/images/logo.png0000644000175000017500000000170711651544321022003 0ustar ilyailyaPNG  IHDRatEXtSoftwareAdobe ImageReadyqe<iIDATx|S]lU=w~:ngwmw٥-PlR!5%>#15Jh4<ȃ(Ik]%[Pj*bmwwݙzsssG4 \ 'z!E%=]]Y}ԧy}23uas/9q0N pzYa=-V.X;:{{;* )xѻ폜-Kr AI5*x onMPl[Jw.PL\71rnWMAR2^[?dXvbٱu%WFQmď! >S?'X`'.! "ٻ.+@µVe9v (0r!m܇%mvP@%C=~少7ou \/e=^@nmwv5@"<)ګP>#хfWձ6Z]i)h\aAʫ %qf_ FUlB\IENDB`ugene-1.9.8/src/plugins/biostruct3d_view/images/restore.png0000644000175000017500000000116111651544321022520 0ustar ilyailyaPNG  IHDRagAMA7tEXtSoftwareAdobe ImageReadyqe<IDAT8˥OHQ7Zcf9UԢت fdPlQ RȕnE"à6e-r#apd6Yc|lDe{yDQؿ<>3;uDٖ47KgAg)g$ujUO 2kp s܍ { t?<(7YՔLX]`$7id? * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "BioStruct3DColorScheme.h" #include #include #include #include #include #include #include #include #include #include namespace U2 { /* class BioStruct3DColorSchemeRegistry */ const QString BioStruct3DColorSchemeRegistry::defaultFactoryName() { return SecStructColorScheme::schemeName; } const QList BioStruct3DColorSchemeRegistry::factoriesNames() { return getInstance()->factories.keys(); } const BioStruct3DColorSchemeFactory* BioStruct3DColorSchemeRegistry::getFactory(const QString &name) { return getInstance()->factories.value(name, 0); } BioStruct3DColorScheme* BioStruct3DColorSchemeRegistry::createColorScheme(const QString &name, const BioStruct3DObject *biostruct) { const BioStruct3DColorSchemeFactory *fact = getFactory(name); if (fact) { return fact->createInstance(biostruct); } return 0; } BioStruct3DColorSchemeRegistry::BioStruct3DColorSchemeRegistry() { registerFactories(); } BioStruct3DColorSchemeRegistry* BioStruct3DColorSchemeRegistry::getInstance() { static BioStruct3DColorSchemeRegistry *reg = new BioStruct3DColorSchemeRegistry(); return reg; } #define REGISTER_FACTORY(c) factories.insert(c::schemeName, new c::Factory) void BioStruct3DColorSchemeRegistry::registerFactories() { REGISTER_FACTORY(ChainsColorScheme); REGISTER_FACTORY(SecStructColorScheme); REGISTER_FACTORY(ChemicalElemColorScheme); REGISTER_FACTORY(SimpleColorScheme); } const QString ChainsColorScheme::schemeName(QObject::tr("Molecular Chains")); const QString ChemicalElemColorScheme::schemeName(QObject::tr("Chemical Elements")); const QString SecStructColorScheme::schemeName(QObject::tr("Secondary Structure")); const QString SimpleColorScheme::schemeName(QObject::tr("Simple colors")); /*class BioStruct3DColorScheme */ BioStruct3DColorScheme::BioStruct3DColorScheme(const BioStruct3DObject *biostruct) : defaultAtomColor(0.25f, 0.25f, 0.25f), selectionColor(1.0f, 1.0f, 0), selection(biostruct->getBioStruct3D()), unselectedShading(0.0) {} Color4f BioStruct3DColorScheme::getAtomColor(const SharedAtom& atom) const { Color4f c; if (isInSelection(atom)) { c = selectionColor; } else { c = getSchemeAtomColor(atom); if (!selection.isEmpty() && unselectedShading > 0.0) { // dim unselected c[3] *= (1.0 - unselectedShading); } } return c; } void BioStruct3DColorScheme::setSelectionColor(QColor color) { this->selectionColor = color; } void BioStruct3DColorScheme::setUnselectedShadingLevel(float shading) { assert(shading >= 0.0 && shading <= 1.0); unselectedShading = shading; } void BioStruct3DColorScheme::updateSelectionRegion(int chainId, const QVector& added, const QVector& removed) { selection.update(chainId, added, removed); } bool BioStruct3DColorScheme::isInSelection(const SharedAtom &atom) const { return selection.inSelection(atom->chainIndex, atom->residueIndex.toInt()); } Color4f BioStruct3DColorScheme::getSchemeAtomColor(const SharedAtom&) const { return defaultAtomColor; } /////////////////////////////////////////////////////////////////////////////////////////// // ChemicalElemColorScheme Color4f ChemicalElemColorScheme::getSchemeAtomColor( const SharedAtom& a ) const { Color4f color; if (elementColorMap.contains(a->atomicNumber)) { return elementColorMap.value(a->atomicNumber); } else { return defaultAtomColor; } } ChemicalElemColorScheme::ChemicalElemColorScheme(const BioStruct3DObject *biostruct) : BioStruct3DColorScheme(biostruct) { //CPK colors elementColorMap.insert(1, Color4f(1.0f, 1.0f, 1.0f)); elementColorMap.insert(6, Color4f(0.8f, 0.8f, 0.8f)); elementColorMap.insert(7, Color4f(0.7f, 0.7f, 1.0f)); elementColorMap.insert(8, Color4f(0.95f, 0.0f , 0.0f)); elementColorMap.insert(11, Color4f(0.0f, 0.0f , 1.0f)); elementColorMap.insert(12, Color4f(0.16f, 0.5f , 0.16f)); elementColorMap.insert(15, Color4f(1.0f, 0.63f , 0.0f)); elementColorMap.insert(16, Color4f(1.0f, 0.8f , 0.2f)); elementColorMap.insert(17, Color4f(0.0f, 1.0f , 0.0f)); elementColorMap.insert(20, Color4f(0.5f, 0.5f , 0.5f)); elementColorMap.insert(26, Color4f(1.0f, 0.63f , 0.0f)); elementColorMap.insert(30, Color4f(0.63f, 0.2f , 0.2f)); elementColorMap.insert(35, Color4f(0.63f, 0.2f , 0.2f)); } /* class ChainsColorScheme : public BioStruct3DColorScheme */ const QMap ChainsColorScheme::getChainColors(const BioStruct3DObject *biostrucObj) { QMap colorMap; //AnnotationSettingsRegistry* asr = AppContext::getAnnotationsSettingsRegistry(); Document *doc = biostrucObj->getDocument(); QList relations = biostrucObj->findRelatedObjectsByRole(GObjectRelationRole::ANNOTATION_TABLE); if (doc) { QList aObjs; foreach(GObjectRelation r, relations) { aObjs += GObjectUtils::selectObjectByReference(r.ref, doc->getObjects(), UOF_LoadedOnly ); } foreach (GObject* obj, aObjs ) { AnnotationTableObject* ao = qobject_cast(obj); assert(ao); foreach(Annotation* a, ao->getAnnotations()) { QString name = a->getAnnotationName(); if (name.startsWith(BioStruct3D::MoleculeAnnotationTag)) { bool ok = false; int chainId = a->findFirstQualifierValue(BioStruct3D::ChainIdQualifierName).toInt(&ok); assert(ok && chainId != 0); QColor color = FeatureColors::genLightColor(QString("chain_%1").arg(chainId)); colorMap.insert(chainId, color); } } } } return colorMap; } ChainsColorScheme::ChainsColorScheme(const BioStruct3DObject *biostruct) : BioStruct3DColorScheme(biostruct) { const QMap chainColors = getChainColors(biostruct); if (!chainColors.empty()) { QMapIterator i(chainColors); while (i.hasNext()) { i.next(); chainColorMap.insert(i.key(), Color4f(i.value())); } } } Color4f ChainsColorScheme::getSchemeAtomColor(const SharedAtom& atom) const { Color4f color; if (chainColorMap.contains(atom->chainIndex)) { return chainColorMap.value(atom->chainIndex); } else { return defaultAtomColor; } } /* class SecStructColorScheme : public BioStruct3DColorScheme */ const QMap SecStructColorScheme::getSecStructAnnotationColors(const BioStruct3DObject *biostruct) { QMap colors; AnnotationSettingsRegistry* asr = AppContext::getAnnotationsSettingsRegistry(); // bug-2857: GObject relations shoud be used Document *doc = biostruct->getDocument(); if (doc) { foreach (GObject* obj, doc->findGObjectByType(GObjectTypes::ANNOTATION_TABLE) ) { AnnotationTableObject *ao = qobject_cast(obj); assert(ao); foreach(Annotation *a, ao->getAnnotations()) { QString name = a->getAnnotationName(); if (name == BioStruct3D::SecStructAnnotationTag) { QString ssName = a->getQualifiers().first().value; AnnotationSettings* as = asr->getAnnotationSettings(ssName); colors.insert(ssName, as->color); } } } } return colors; } SecStructColorScheme::SecStructColorScheme(const BioStruct3DObject *biostruct) : BioStruct3DColorScheme(biostruct) { defaultAtomColor = Color4f(0.5f,0.9f,0.9f); const QMap secStrucColors = getSecStructAnnotationColors(biostruct); if (!secStrucColors.isEmpty()) { QMapIterator i(secStrucColors); while (i.hasNext()) { i.next(); secStrucColorMap.insert(i.key().toAscii(), Color4f(i.value())); } foreach (const SharedSecondaryStructure& struc, biostruct->getBioStruct3D().secondaryStructures) { for (int index = struc->startSequenceNumber; index <= struc->endSequenceNumber; ++index ) { QByteArray type = BioStruct3D::getSecStructTypeName(struc->type).toAscii(); Q_ASSERT( secStrucColorMap.contains(type)); Q_ASSERT( struc->chainIndex != 0); molMap[struc->chainIndex].strucResidueTable.insert(index, type); } } #ifdef _DEBUG // Verify indices with biostruct3d const BioStruct3D& bioStruc = biostruct->getBioStruct3D(); QMapIterator iter(molMap); while (iter.hasNext()) { iter.next(); assert(bioStruc.moleculeMap.contains(iter.key())); } #endif } } Color4f SecStructColorScheme::getSchemeAtomColor( const SharedAtom& atom ) const { Color4f c = defaultAtomColor; int residueIndex = atom->residueIndex.toInt(); if (molMap.contains(atom->chainIndex)) { const QHash& residueTable = molMap.value(atom->chainIndex).strucResidueTable; if (residueTable.contains(residueIndex)) { QByteArray type = residueTable.value(residueIndex); c = secStrucColorMap.value(type); } } return c; } /* class SimpleColorScheme : public BioStruct3DColorScheme */ QVector SimpleColorScheme::colors; void SimpleColorScheme::createColors() { if (colors.isEmpty()) { // rainbow colors colors.append( Color4f(QColor(0xff,0x00,0x00)) ); colors.append( Color4f(QColor(0xff,0x7f,0x00)) ); colors.append( Color4f(QColor(0xff,0xff,0x00)) ); colors.append( Color4f(QColor(0x00,0xff,0x00)) ); colors.append( Color4f(QColor(0x00,0xff,0xff)) ); colors.append( Color4f(QColor(0x00,0x00,0xff)) ); colors.append( Color4f(QColor(0x8b,0x00,0xff)) ); } } SimpleColorScheme::SimpleColorScheme(const BioStruct3DObject *biostruct) : BioStruct3DColorScheme(biostruct) { createColors(); static int idx = 0; defaultAtomColor = colors[(idx++) % colors.size()]; } } // namespace U2 ugene-1.9.8/src/plugins/biostruct3d_view/src/SelectModelsDialog.cpp0000644000175000017500000000560311651544321024065 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "SelectModelsDialog.h" #include #include namespace U2 { SelectModelsDialog::SelectModelsDialog(const QList &_modelIds, const QList &_selectedItems, QWidget *parent /*= 0*/) : QDialog(parent), Ui::SelectModelsDialog() { setupUi(this); QVector modelIds = _modelIds.toVector(); QSet selectedItems = _selectedItems.toSet(); for (int i = 0; i < modelIds.size(); ++i) { int modelId = modelIds[i]; QListWidgetItem *it = new QListWidgetItem(QString::number(modelId)); it->setCheckState((selectedItems.contains(i)) ? Qt::Checked : Qt::Unchecked); modelsList->addItem(it); } connect(modelsList, SIGNAL(itemDoubleClicked(QListWidgetItem*)), this, SLOT(sl_onItemDoubleClicked(QListWidgetItem*))); connect(allButton, SIGNAL(clicked()), this, SLOT(sl_onSlectAll())); connect(inverButton, SIGNAL(clicked()), this, SLOT(sl_onInvertSelection())); } /** Toggle item by double click */ void SelectModelsDialog::sl_onItemDoubleClicked(QListWidgetItem *item) { item->setCheckState((item->checkState() == Qt::Unchecked) ? Qt::Checked : Qt::Unchecked); } void SelectModelsDialog::sl_onSlectAll() { for (int i = 0; i < modelsList->count(); ++i) { modelsList->item(i)->setCheckState(Qt::Checked); } } void SelectModelsDialog::sl_onInvertSelection() { for (int i = 0; i < modelsList->count(); ++i) { QListWidgetItem *item = modelsList->item(i); item->setCheckState((item->checkState() == Qt::Unchecked) ? Qt::Checked : Qt::Unchecked); } } void SelectModelsDialog::accept() { for (int i = 0; i < modelsList->count(); ++i) { QListWidgetItem *item = modelsList->item(i); if (item->checkState() == Qt::Checked) { selectedModelsIndexes << i; } } if (selectedModelsIndexes.isEmpty()) { QMessageBox::warning(this, tr("Error"), tr("At least one model shoud be selected.")); return; } QDialog::accept(); } SelectModelsDialog::~SelectModelsDialog() {} } // namespace U2 ugene-1.9.8/src/plugins/biostruct3d_view/src/BioStruct3DViewPlugin.cpp0000644000175000017500000001457311651544321024507 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "BioStruct3DViewPlugin.h" #include "BioStruct3DSplitter.h" #include "BioStruct3DGLWidget.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include namespace U2 { /*! * \mainpage BioStruct3D Viewer Plugin Documentation * * \section viewer Introduction * * BioStruct3D Viewer is a macromolecular viewing / editing tool. * It is activated whenever UGENE loads document that contains BioStruct3DObject. * * * \subsection main Main Classes * * plugin classes: * - BioStruct3DGLWidget : Widget for rendering 3d representations of macromolecular structure. * - BioStruct3DSplitter : Multiple glWidgets layout and manipulation * - GLFrame : Class for manipulating the 3d viewpoint * * plugin interfaces: * - BioStruct3DGLRenderer : General interface for structure 3d graphical styles * - BioStruct3DColorScheme : Interface for coloring atoms, bonds, etc. * * */ extern "C" Q_DECL_EXPORT Plugin* U2_PLUGIN_INIT_FUNC() { if (AppContext::getMainWindow()) { BioStruct3DViewPlugin* plug = new BioStruct3DViewPlugin(); return plug; } return NULL; } BioStruct3DViewPlugin::BioStruct3DViewPlugin() : Plugin(tr("3D Structure Viewer"), tr("Visualizes 3D structures of biological molecules.")) { // Init plugin view context viewContext = new BioStruct3DViewContext(this); viewContext->init(); } BioStruct3DViewPlugin::~BioStruct3DViewPlugin() { } BioStruct3DViewContext::BioStruct3DViewContext(QObject* p) : GObjectViewWindowContext(p, ANNOTATED_DNA_VIEW_FACTORY_ID) { } void BioStruct3DViewContext::initViewContext(GObjectView* v) { AnnotatedDNAView* av = qobject_cast(v); DNASequenceObject* dna=av->getSequenceInFocus()->getSequenceObject(); Document* doc = dna->getDocument(); QList biostructObjs = doc->findGObjectByType(GObjectTypes::BIOSTRUCTURE_3D); if (biostructObjs.isEmpty()) { return; } QList seqWidgets = av->getSequenceWidgets(); foreach(ADVSequenceWidget* w, seqWidgets) { ADVSingleSequenceWidget* aw = qobject_cast(w); if (aw!=NULL) { aw->setDetViewCollapsed(true); aw->setOverviewCollapsed(true); } } foreach(GObject* obj, biostructObjs) { v->addObject(obj); } } bool BioStruct3DViewContext::canHandle(GObjectView* v, GObject* o) { Q_UNUSED(v); bool res = qobject_cast(o) != NULL; return res; } void BioStruct3DViewContext::onObjectAdded(GObjectView* view, GObject* obj) { //todo: add sequence & all objects associated with sequence to the view? BioStruct3DObject* obj3d = qobject_cast(obj); if (obj3d == NULL || view == NULL) { return; } AnnotatedDNAView* av = qobject_cast(view); BioStruct3DSplitter* splitter = NULL; if (splitterMap.contains(view)) { splitter = splitterMap.value(view); } else { splitter = new BioStruct3DSplitter(getClose3DViewAction(view), av); } av->insertWidgetIntoSplitter(splitter); splitter->addObject(obj3d); splitterMap.insert(view,splitter); } void BioStruct3DViewContext::onObjectRemoved(GObjectView* v, GObject* obj) { BioStruct3DObject* obj3d = qobject_cast(obj); if (obj3d == NULL) { return; } BioStruct3DSplitter* splitter = splitterMap.value(v); bool close = splitter->removeObject(obj3d); if (close) { splitter->close(); //unregister3DView(v,splitter); } } void BioStruct3DViewContext::unregister3DView(GObjectView* view, BioStruct3DSplitter* splitter) { assert(splitter->getChildWidgets().isEmpty()); splitter->close(); AnnotatedDNAView* av = qobject_cast(view); av->unregisterSplitWidget(splitter); splitterMap.remove(view); splitter->deleteLater(); } QAction* BioStruct3DViewContext::getClose3DViewAction(GObjectView* view) { QList resources = viewResources.value(view); foreach(QObject* r, resources) { GObjectViewAction* a= qobject_cast(r); if (a!=NULL) { return a; } } QAction* a = new GObjectViewAction(this, view, tr("Close 3D Structure Viewer")); connect(a, SIGNAL(triggered()), SLOT(sl_close3DView())); resources.append(a); return a; } void BioStruct3DViewContext::sl_close3DView() { GObjectViewAction* action = qobject_cast(sender()); GObjectView* ov = action->getObjectView(); QList objects = ov->getObjects(); foreach(GObject* obj, objects) { if (obj->getGObjectType() == GObjectTypes::BIOSTRUCTURE_3D) { ov->removeObject(obj); } } } void BioStruct3DViewContext::sl_windowClosing(MWMDIWindow* w) { GObjectViewWindow *gvw = qobject_cast(w); if (gvw) { GObjectView *view = gvw->getObjectView(); // safe to remove: splitter will be deleted with ADV splitterMap.remove(view); } GObjectViewWindowContext::sl_windowClosing(w); } }//namespace ugene-1.9.8/src/plugins/biostruct3d_view/src/BioStruct3DSubsetEditor.cpp0000644000175000017500000001424111651544321025022 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "BioStruct3DSubsetEditor.h" #include #include namespace U2 { static const QString ALL_CHAINS("All chains"); BioStruct3DSubsetEditor::BioStruct3DSubsetEditor(const QList &biostructs, const BioStruct3DObject *selected /*= 0*/, int selectedModel /*= -1*/, QWidget *parent /*= 0*/) : QWidget(parent) { setupUi(this); foreach (BioStruct3DObject *bs, biostructs) { objectCombo->addItem(bs->getGObjectName(), qVariantFromValue((void*)bs)); } if (selected) { int idx = objectCombo->findData(qVariantFromValue((void*)selected)); assert(idx != -1 && "Selected object must present in biostructs"); objectCombo->setCurrentIndex(idx); } fillChainCombo(); fillRegionEdit(); fillModelCombo(); if (selectedModel != -1) { int idx = modelCombo->findData(qVariantFromValue(selectedModel)); assert(idx != -1 && "Selected model must present in biostruct"); modelCombo->setCurrentIndex(idx); } connect(objectCombo, SIGNAL(currentIndexChanged(int)), this, SLOT(sl_onBiostructChanged(int))); connect(chainCombo, SIGNAL(currentIndexChanged(int)), this, SLOT(sl_onChainChanged(int))); } void BioStruct3DSubsetEditor::fillChainCombo() { BioStruct3DObject *bso = static_cast( objectCombo->itemData(objectCombo->currentIndex()).value() ); chainCombo->clear(); chainCombo->addItem(ALL_CHAINS); foreach (const int chainId, bso->getBioStruct3D().moleculeMap.keys()) { chainCombo->addItem(QString::number(chainId), qVariantFromValue(chainId)); } } void BioStruct3DSubsetEditor::fillModelCombo() { BioStruct3DObject *bso = static_cast( objectCombo->itemData(objectCombo->currentIndex()).value() ); modelCombo->clear(); foreach (const int modelId, bso->getBioStruct3D().modelMap.keys()) { modelCombo->addItem(QString::number(modelId), qVariantFromValue(modelId)); } } void BioStruct3DSubsetEditor::fillRegionEdit() { if (chainCombo->currentText() != ALL_CHAINS) { BioStruct3DObject *bso = static_cast( objectCombo->itemData(objectCombo->currentIndex()).value() ); int chainId = chainCombo->itemData(chainCombo->currentIndex()).value(); int length = bso->getBioStruct3D().moleculeMap.value(chainId)->residueMap.size(); setRegion(U2Region(0, length)); regionEdit->setEnabled(true); } else { regionEdit->setText(""); regionEdit->setDisabled(true); } } void BioStruct3DSubsetEditor::sl_onBiostructChanged(int) { fillModelCombo(); fillChainCombo(); fillRegionEdit(); } void BioStruct3DSubsetEditor::sl_onChainChanged(int idx) { if (idx != -1) { // reject chainCombo->clear() event from fillChainCombo() method fillRegionEdit(); } } BioStruct3DReference BioStruct3DSubsetEditor::getSubset() { assert(validate().isEmpty() && "validate first!"); BioStruct3DObject *obj = static_cast ( objectCombo->itemData(objectCombo->currentIndex()).value() ); int modelId = modelCombo->itemData(modelCombo->currentIndex()).value(); if (chainCombo->currentText() == ALL_CHAINS) { QList chains = obj->getBioStruct3D().moleculeMap.keys(); return BioStruct3DReference(obj, chains, modelId); } else { int chainId = chainCombo->itemData(chainCombo->currentIndex()).value(); U2Region chainRegion = getRegion(); return BioStruct3DReference(obj, chainId, chainRegion, modelId); } } QString BioStruct3DSubsetEditor::validate() { if (regionEdit->isEnabled()) { QString regionText = regionEdit->text(); if (!QRegExp("[0-9]*\\.\\.[0-9]*").exactMatch(regionText)) { return QString("invalid region spec %1").arg(regionText); } BioStruct3DObject *bso = static_cast( objectCombo->itemData(objectCombo->currentIndex()).value() ); int chainId = chainCombo->itemData(chainCombo->currentIndex()).value(); int length = bso->getBioStruct3D().moleculeMap.value(chainId)->residueMap.size(); U2Region region = getRegion(); if (region.startPos < 0 || region.startPos >= region.endPos() || region.endPos() > length) { return QString("region values out of range %1..%2 (%3..%4)").arg(region.startPos + 1).arg(region.endPos()).arg(1).arg(length); } } return QString(""); } U2Region BioStruct3DSubsetEditor::getRegion() { U2Region ret; QString text = regionEdit->text(); QStringList broken = text.split("..", QString::SkipEmptyParts); if (broken.size() != 2) return ret; bool ok = false; int start = broken.at(0).toInt(&ok); if (!ok) return ret; int end = broken.at(1).toInt(&ok); if (!ok) return ret; ret = U2Region(start - 1, end - start + 1); return ret; } void BioStruct3DSubsetEditor::setRegion(const U2Region ®ion) { QString text = QString("%1..%2").arg(region.startPos + 1).arg(region.endPos()); regionEdit->setText(text); } void BioStruct3DSubsetEditor::setBiostructDisabled() { objectCombo->setDisabled(true); } void BioStruct3DSubsetEditor::setModelDisabled() { modelCombo->setDisabled(true); } } // namespace U2 ugene-1.9.8/src/plugins/biostruct3d_view/src/GLFrameManager.h0000644000175000017500000000536611651544321022605 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_GL_FRAME_MANAGER_H_ #define _U2_GL_FRAME_MANAGER_H_ #include #include #include namespace U2 { class Vector3D; /*! * @brief Class for OpenGL 3d scene manipulation */ class GLFrame { static const GLfloat DEFAULT_ZOOM; //static const Vector3D DEFAULT_CAMERA; public: GLFrame(QGLWidget* widget); void setState(const QVariantMap& state); void writeStateToMap(QVariantMap& states); QGLWidget* getGLWidget() { return glWidget; } void makeCurrent() { glWidget->makeCurrent(); } void updateViewPort(int width, int height); void updateViewPort(); void updateGL() { glWidget->updateGL(); } GLfloat getZoomFactor() const { return zoomFactor; } float* getRotationMatrix() { return rotMatrix.data(); } void rotateCamera(const Vector3D& rotAxis, float rotAngle); void setCameraClip(float clipNear, float clipFar); const Vector3D getCameraPosition() const; void setCameraPosition(const Vector3D &v); void setCameraPosition(float x, float y, float z); void performZoom(float delta); void performShift(float deltaX, float deltaY); private: QGLWidget* glWidget; Matrix44 rotMatrix; bool synchLock; float cameraClipNear, cameraClipFar; GLfloat zoomFactor; Vector3D cameraPosition; }; class GLFrameManager { QMap widgetFrameMap; bool syncLock; public: GLFrameManager() : syncLock(false) {} ~GLFrameManager(); bool getSyncLock() const { return syncLock; } void setSyncLock(bool lockOn, QGLWidget* syncWidget); void addGLFrame(GLFrame* frame); GLFrame* getGLWidgetFrame(QGLWidget* widget); void removeGLWidgetFrame(QGLWidget* widget); void clear(); QList getGLFrames(); QList getActiveGLFrameList(GLFrame* currentFrame, bool syncModeOn); }; } // namespace #endif // _U2_GL_FRAME_MANAGER_H_ ugene-1.9.8/src/plugins/biostruct3d_view/src/BallAndStickGLRenderer.cpp0000644000175000017500000001155311651544321024570 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include #include #include #include #include "GraphicUtils.h" #include "BioStruct3DGLWidget.h" #include "BioStruct3DColorScheme.h" #include "BallAndStickGLRenderer.h" #include namespace U2 { const QString BallAndStickGLRenderer::ID(QObject::tr("Ball-and-Stick")); BallAndStickGLRenderer::BallAndStickGLRenderer(const BioStruct3D& struc, const BioStruct3DColorScheme* s, const QList &shownModels, const BioStruct3DRendererSettings *settings) : BioStruct3DGLRenderer(struc,s,shownModels,settings), dl(0) { create(); } BallAndStickGLRenderer::~BallAndStickGLRenderer() { if (glIsList(dl)) { glDeleteLists(dl, 1); } } void BallAndStickGLRenderer::create() { createDisplayList(); } void BallAndStickGLRenderer::drawBioStruct3D() { glCallList(dl); CHECK_GL_ERROR; } void BallAndStickGLRenderer::update() { createDisplayList(); } void BallAndStickGLRenderer::updateColorScheme() { createDisplayList(); } void BallAndStickGLRenderer::updateShownModels() { createDisplayList(); } void BallAndStickGLRenderer::updateSettings() { createDisplayList(); } static void drawAtomsBonds(const Color4f &viewAtomColor, float renderDetailLevel, const Molecule3DModel &model, const BioStruct3DColorScheme* colorScheme) { GLUquadricObj *pObj = gluNewQuadric(); gluQuadricNormals(pObj, GLU_SMOOTH); glMaterialfv(GL_FRONT, GL_AMBIENT_AND_DIFFUSE, viewAtomColor.getConstData()); static float bondThickness = 0.15f; float radius = 0.35f; int numSlices = 8 * renderDetailLevel; foreach(const SharedAtom atom, model.atoms) { Color4f atomColor = colorScheme->getAtomColor(atom); if (viewAtomColor==atomColor) { Vector3D pos = atom->coord3d; //glPushMatrix(); glTranslatef(pos.x, pos.y, pos.z); gluSphere(pObj, radius, numSlices, numSlices); glTranslatef(-pos.x, -pos.y, -pos.z); //glPopMatrix(); } } foreach (Bond bond, model.bonds) { const SharedAtom a1 = bond.getAtom1(); const SharedAtom a2 = bond.getAtom2(); const Color4f &a1Color = colorScheme->getAtomColor(a1); const Color4f &a2Color = colorScheme->getAtomColor(a2); Vector3D middle = (a1->coord3d + a2->coord3d) / 2; if (a1Color==viewAtomColor) { if (a1Color==a2Color) { //glMaterialfv(GL_FRONT, GL_AMBIENT_AND_DIFFUSE, a1Color); glDrawCylinder(pObj, a1->coord3d, a2->coord3d, bondThickness, renderDetailLevel); } else { //glMaterialfv(GL_FRONT, GL_AMBIENT_AND_DIFFUSE, a1Color); glDrawCylinder(pObj, a1->coord3d, middle, bondThickness, renderDetailLevel); } } if (a2Color == viewAtomColor) { //glMaterialfv(GL_FRONT, GL_AMBIENT_AND_DIFFUSE, a2Color); glDrawCylinder(pObj, middle, a2->coord3d, bondThickness, renderDetailLevel); } } gluDeleteQuadric(pObj); } void BallAndStickGLRenderer::createDisplayList() { dl = glGenLists(1); float renderDetailLevel = settings->detailLevel; QList colors; glNewList(dl, GL_COMPILE); foreach (const SharedMolecule mol, bioStruct.moleculeMap) { foreach (int index, shownModels) { const Molecule3DModel& model = mol->models.at(index); colors.clear(); foreach(const SharedAtom atom, model.atoms) { Color4f atomColor = colorScheme->getAtomColor(atom); if (colors.contains(atomColor)) { continue; // Atom and bonds with this color has been already viewed } else { drawAtomsBonds(atomColor, renderDetailLevel, model, colorScheme); colors.push_back(atomColor); } } } } glEndList(); CHECK_GL_ERROR; } } //namespace ugene-1.9.8/src/plugins/biostruct3d_view/src/BioStruct3DViewPlugin.h0000644000175000017500000000374511651544321024153 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_BIOSTRUCT3D_VIEW_PLUGIN_H_ #define _U2_BIOSTRUCT3D_VIEW_PLUGIN_H_ #include #include #include #include #include namespace U2 { class BioStruct3DSplitter; class BioStruct3DObject; class BioStruct3DViewPlugin : public Plugin { Q_OBJECT public: BioStruct3DViewPlugin(); ~BioStruct3DViewPlugin(); private: GObjectViewWindowContext* viewContext; }; class BioStruct3DViewContext: public GObjectViewWindowContext { Q_OBJECT QMap splitterMap; public: BioStruct3DViewContext(QObject* p); virtual bool canHandle(GObjectView* v, GObject* o); virtual void onObjectAdded(GObjectView* v, GObject* obj); virtual void onObjectRemoved(GObjectView* v, GObject* obj); protected: virtual void initViewContext(GObjectView* view); void unregister3DView(GObjectView* view, BioStruct3DSplitter* view3d); QAction* getClose3DViewAction(GObjectView* view); protected slots: void sl_close3DView(); virtual void sl_windowClosing(MWMDIWindow*); }; } //namespace #endif ugene-1.9.8/src/plugins/biostruct3d_view/src/GraphicUtils.cpp0000644000175000017500000004643411651544321022767 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include #include #include #include "GraphicUtils.h" #include #include #include namespace U2 { /////////////////////////////////////////////////////////////////////////////////////////// /// Color4f Color4f::Color4f() { color[0] = 0; color[1] = 0; color[2] = 0; color[3] = 1.0; } Color4f::Color4f(float r, float g, float b, float a) { color[0] = r; color[1] = g; color[2] = b; color[3] = a; } Color4f::Color4f( const QColor& qc) { color[0] = qc.redF(); color[1] = qc.greenF(); color[2] = qc.blueF(); color[3] = qc.alphaF(); } Color4f::Color4f(const Color4f &c) { for (int i = 0; i < 4; ++i) { color[i] = c.color[i]; } } float Color4f::operator[] (unsigned int i ) const { assert(i < 4); return color[i]; } float& Color4f::operator[] (unsigned int i) { assert(i < 4); return color[i]; } bool Color4f::operator== (const Color4f &a) const { //Do not affect alpha channel if (color[0]==a.color[0] && color[1]==a.color[1] && color[2]==a.color[2]) { return true; } else { return false; } } void glDrawCylinder(GLUquadric* pObj, const Vector3D& p1, const Vector3D& p2, double thickness, float renderDetailLevel) { int numSlices = (8 * renderDetailLevel); int numStacks = 1; static Vector3D zAxis(0.0, 0.0, 1.0); Vector3D vec(p2 - p1); float length = vec.length(); float rotAngle = Rad2Deg* acos( vec.z / length ); Vector3D rotAxis = vector_cross(zAxis, vec); glPushMatrix(); glTranslatef(p1.x, p1.y, p1.z); glRotatef(rotAngle, rotAxis.x, rotAxis.y, rotAxis.z); gluCylinder(pObj, thickness, thickness, length, numSlices, numStacks); glPopMatrix(); } /* class Helix3D : public Object3D */ Helix3D::Helix3D(const Color4f& cl, const Vector3D& c, const Vector3D& n, float r ) : Object3D(cl), cterm(c), nterm(n), radius(r) { pObj = gluNewQuadric(); gluQuadricNormals(pObj, GLU_SMOOTH); Vector3D vec(nterm - cterm); length = vec.length(); rotAngle = Rad2Deg* acos( vec.z / length ); Vector3D zAxis(0.0, 0.0, 1.0); rotAxis = vector_cross(zAxis, vec); } void Helix3D::draw(float renderDetailLevel) { glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE, color.getConstData()); int numSlices = 10 * renderDetailLevel; int numStacks = 1; static float smallLength = 1.2f; radius=1.0f; glPushMatrix(); glTranslatef(cterm.x, cterm.y, cterm.z); glRotatef(rotAngle, rotAxis.x, rotAxis.y, rotAxis.z); glPushMatrix(); glScalef(1,1,-1); gluDisk(pObj, 0, radius, numSlices, numSlices); glPopMatrix(); gluCylinder(pObj, radius, radius, length - smallLength, numSlices, numStacks); glTranslatef(0, 0, length - smallLength); glPushMatrix(); glScalef(1,1,-1); gluDisk(pObj, 0, radius*1.2f, numSlices, numSlices); glPopMatrix(); gluCylinder(pObj, radius*1.2f, radius*0.4f, smallLength, numSlices, numStacks); glTranslatef(0, 0, smallLength); gluDisk(pObj, 0, radius*0.4f, numSlices, numStacks); glPopMatrix(); } Helix3D::~Helix3D() { gluDeleteQuadric(pObj); } /* class Strand3D : public Object3D */ Strand3D::Strand3D( const Color4f& cl, const Vector3D& c, const Vector3D& n, const Vector3D& up ) : Object3D(cl), cterm(c), nterm(n), upVector(up) { Vector3D vec(nterm - cterm); length = vec.length(); rotAngle = Rad2Deg* acos( vec.z / length ); Vector3D zAxis(0.0, 0.0, 1.0); rotAxis = vector_cross(zAxis, vec); } void Strand3D::draw(float renderDetailLevel) { Q_UNUSED(renderDetailLevel); float width = 1.5f; float height = 0.4f; glMaterialfv(GL_FRONT, GL_AMBIENT_AND_DIFFUSE, color.getConstData()); glPushMatrix(); glTranslatef(cterm.x, cterm.y, cterm.z); glRotatef(rotAngle, rotAxis.x, rotAxis.y, rotAxis.z); glCreateArrowPrimitive(width, height, length); glPopMatrix(); } Strand3D::~Strand3D() { } void glDrawHalfWorm(const Vector3D& p0, const Vector3D& p1, const Vector3D& p2, const Vector3D& p3, double radius, bool cap1, bool cap2, double tension, float renderDetailLevel) { int i, j, k, m, offset=0; Vector3D R1, R2, Qt, p, dQt, H, V; double len, MG[4][3], T[4], t, prevlen=0.0, cosj, sinj; GLfloat *Nx=NULL, *Ny=NULL, *Nz=NULL, *Cx=NULL, *Cy=NULL, *Cz=NULL, *pNx=NULL, *pNy=NULL, *pNz=NULL, *pCx=NULL, *pCy=NULL, *pCz=NULL, *tmp; /* * The Hermite matrix Mh. */ static double Mh[4][4] = { { 2, -2, 1, 1}, {-3, 3, -2, -1}, { 0, 0, 1, 0}, { 1, 0, 0, 0} }; /* * Variables that affect the curve shape * a=b=0 = Catmull-Rom */ double a = tension, /* tension (adjustable) */ c = 0, /* continuity (should be 0) */ b = 0; /* bias (should be 0) */ int wormSegments = 10 * renderDetailLevel; int wormSides = 10 * renderDetailLevel; /* if (wormSides % 2) { WARNINGMSG("worm sides must be an even number"); ++wormSides; } */ GLfloat *fblock = NULL; /* First, calculate the coordinate points of the center of the worm, * using the Kochanek-Bartels variant of the Hermite curve. */ R1 = 0.5 * (1 - a) * (1 + b) * (1 + c) * (p1 - p0) + 0.5 * (1 - a) * (1 - b) * (1 - c) * ( p2 - p1); R2 = 0.5 * (1 - a) * (1 + b) * (1 - c) * (p2 - p1) + 0.5 * (1 - a) * (1 - b) * (1 + c) * (p3 - p2); /* * Multiply MG=Mh.Gh, where Gh = [ P(1) P(2) R(1) R(2) ]. This * 4x1 matrix of vectors is constant for each segment. */ for (i = 0; i < 4; ++i) { /* calculate Mh.Gh */ MG[i][0] = Mh[i][0] * p1.x + Mh[i][1] * p2.x + Mh[i][2] * R1.x + Mh[i][3] * R2.x; MG[i][1] = Mh[i][0] * p1.y + Mh[i][1] * p2.y + Mh[i][2] * R1.y + Mh[i][3] * R2.y; MG[i][2] = Mh[i][0] * p1.z + Mh[i][1] * p2.z + Mh[i][2] * R1.z + Mh[i][3] * R2.z; } for (i = 0; i <= wormSegments; ++i) { /* t goes from [0,1] from P(1) to P(2) (and we want to go halfway only), and the function Q(t) defines the curve of this segment. */ t = (0.5 / wormSegments) * i; /* * Q(t)=T.(Mh.Gh), where T = [ t^3 t^2 t 1 ] */ T[0] = t * t * t; T[1] = t * t; T[2] = t; //T[3] = 1; Qt.x = T[0] * MG[0][0] + T[1] * MG[1][0] + T[2] * MG[2][0] + MG[3][0] /* *T[3] */ ; Qt.y = T[0] * MG[0][1] + T[1] * MG[1][1] + T[2] * MG[2][1] + MG[3][1] /* *T[3] */ ; Qt.z = T[0] * MG[0][2] + T[1] * MG[1][2] + T[2] * MG[2][2] + MG[3][2] /* *T[3] */ ; if (radius == 0.0) { if (i > 0) { glBegin(GL_LINES); glVertex3d(p.x, p.y, p.z); glVertex3d(Qt.x, Qt.y, Qt.z); glEnd(); } /* save to use as previous point for connecting points together */ p = Qt; } else { /* construct a circle of points centered at and in a plane normal to the curve at t - these points will be used to construct the "thick" worm */ /* allocate single block of storage for two circles of points */ if (!Nx) { fblock = new GLfloat[12 * wormSides]; Nx = fblock; Ny = &Nx[wormSides]; Nz = &Nx[wormSides * 2]; Cx = &Nx[wormSides * 3]; Cy = &Nx[wormSides * 4]; Cz = &Nx[wormSides * 5]; pNx = &Nx[wormSides * 6]; pNy = &Nx[wormSides * 7]; pNz = &Nx[wormSides * 8]; pCx = &Nx[wormSides * 9]; pCy = &Nx[wormSides * 10]; pCz = &Nx[wormSides * 11]; } /* * The first derivative of Q(t), d(Q(t))/dt, is the slope * (tangent) at point Q(t); now T = [ 3t^2 2t 1 0 ] */ T[0] = t * t * 3; T[1] = t * 2; //T[2] = 1; //T[3] = 0; dQt.x = T[0] * MG[0][0] + T[1] * MG[1][0] + MG[2][0] /* *T[2] + T[3]*MG[3][0] */ ; dQt.y = T[0] * MG[0][1] + T[1] * MG[1][1] + MG[2][1] /* *T[2] + T[3]*MG[3][1] */ ; dQt.z = T[0] * MG[0][2] + T[1] * MG[1][2] + MG[2][2] /* *T[2] + T[3]*MG[3][2] */ ; /* use cross product of [1,0,0] x normal as horizontal */ H.set(0.0, -dQt.z, dQt.y); if (H.length() < 0.000001) /* nearly colinear - use [1,0.1,0] instead */ H.set(0.1 * dQt.z, -dQt.z, dQt.y - 0.1 * dQt.x); H.normalize(); /* and a vertical vector = normal x H */ V = vector_cross(dQt, H); V.normalize(); /* finally, the worm circumference points (C) and normals (N) are simple trigonometric combinations of H and V */ for (j = 0; j < wormSides; ++j) { cosj = cos(2 * PI * j / wormSides); sinj = sin(2 * PI * j / wormSides); Nx[j] = H.x * cosj + V.x * sinj; Ny[j] = H.y * cosj + V.y * sinj; Nz[j] = H.z * cosj + V.z * sinj; Cx[j] = Qt.x + Nx[j] * radius; Cy[j] = Qt.y + Ny[j] * radius; Cz[j] = Qt.z + Nz[j] * radius; } /* figure out which points on the previous circle "match" best with these, to minimize envelope twisting */ if (i > 0) { for (m = 0; m < wormSides; ++m) { len = 0.0; for (j = 0; j < wormSides; ++j) { k = j + m; if (k >= wormSides) k -= wormSides; len += (Cx[k] - pCx[j]) * (Cx[k] - pCx[j]) + (Cy[k] - pCy[j]) * (Cy[k] - pCy[j]) + (Cz[k] - pCz[j]) * (Cz[k] - pCz[j]); } if (m == 0 || len < prevlen) { prevlen = len; offset = m; } } } /* create triangles from points along this and previous circle */ if (i > 0) { glBegin(GL_TRIANGLE_STRIP); for (j = 0; j < wormSides; ++j) { k = j + offset; if (k >= wormSides) k -= wormSides; glNormal3d(Nx[k], Ny[k], Nz[k]); glVertex3d(Cx[k], Cy[k], Cz[k]); glNormal3d(pNx[j], pNy[j], pNz[j]); glVertex3d(pCx[j], pCy[j], pCz[j]); } glNormal3d(Nx[offset], Ny[offset], Nz[offset]); glVertex3d(Cx[offset], Cy[offset], Cz[offset]); glNormal3d(pNx[0], pNy[0], pNz[0]); glVertex3d(pCx[0], pCy[0], pCz[0]); glEnd(); } /* put caps on the end */ if (cap1 && i == 0) { dQt.normalize(); glBegin(GL_POLYGON); glNormal3d(-dQt.x, -dQt.y, -dQt.z); for (j = wormSides - 1; j >= 0; --j) { glVertex3d(Cx[j], Cy[j], Cz[j]); } glEnd(); } else if (cap2 && i == wormSegments) { dQt.normalize(); glBegin(GL_POLYGON); glNormal3d(dQt.x, dQt.y, dQt.z); for (j = 0; j < wormSides; ++j) { k = j + offset; if (k >= wormSides) k -= wormSides; glVertex3d(Cx[k], Cy[k], Cz[k]); } glEnd(); } /* store this circle as previous for next round; instead of copying all values, just swap pointers */ #define SWAPPTR(p1,p2) tmp=(p1); (p1)=(p2); (p2)=tmp SWAPPTR(Nx, pNx); SWAPPTR(Ny, pNy); SWAPPTR(Nz, pNz); SWAPPTR(Cx, pCx); SWAPPTR(Cy, pCy); SWAPPTR(Cz, pCz); } } delete[] fblock; } void glDrawHalfBond( GLUquadric *pObj, const Vector3D& p1, const Vector3D&p2, double thickness, float renderDetailLevel) { Vector3D middle = (p1 + p2) / 2; glDrawCylinder(pObj, p2, middle, thickness, renderDetailLevel); } void glDrawAtom( GLUquadric* pObj, const Vector3D& pos, double r, float renderDetailLevel) { int numSlices = 10 * renderDetailLevel; glPushMatrix(); glTranslatef(pos.x, pos.y, pos.z); gluSphere(pObj, r, numSlices, numSlices); glPopMatrix(); } /* / This function and helix drawing approach are taken from VMD (www.ks.uiuc.edu/Research/vmd/) / Find x = a*i + b where i = 0..n-1 */ static void least_squares(int n, const float *x, float *a, float *b) { float sum = 0; int i; for (i=0; i calcBestAxisThroughPoints( const QVector& points ) { float a[3], b[3]; int n = points.count(); QVector buf; buf.resize(3*n); for (int i = 0; i < n; i++) { buf[i] = points[i].x; buf[n + i] = points[i].y; buf[2*n + i] = points[i].z; } least_squares(n, buf.data(), a, b); least_squares(n, buf.data() + n, a + 1, b + 1); least_squares(n, buf.data() + 2*n, a + 2, b + 2); Vector3D pointA(b[0], b[1], b[2]); Vector3D pointB(a[0]*(n-1) + b[0], a[1]*(n-1) + b[1], a[2]*(n-1) + b[2]); return QPair(pointA, pointB); } Vector3D calcMiddlePoint( const QVector& points ) { Vector3D point(0,0,0); foreach (Vector3D v, points) { point += v; } return (point / points.count()); } Vector3D projectPointOnAxis( const Vector3D& point, const Vector3D& axisUnitVector, const Vector3D& axisPoint ) { Vector3D projection(point - axisPoint); float projectedLength = vector_dot(projection,axisUnitVector); projection = projectedLength*axisUnitVector + axisPoint; return projection; } void glCreateArrowPrimitive( float width, float height, float length ) { float widthOffset = 1; float heightOffset = 1; GLfloat b00[3] = {-width / 2, -height / 2, 0 }; GLfloat b01[3] = {-width / 2, height / 2, 0 }; GLfloat b02[3] = {width / 2, height / 2, 0 }; GLfloat b03[3] = {width / 2, -height / 2 , 0 }; GLfloat b04[3] = {-width / 2, -height / 2, length }; GLfloat b05[3] = {-width / 2, height / 2, length }; GLfloat b06[3] = {width / 2, height / 2, length }; GLfloat b07[3] = {width / 2, -height / 2, length }; GLfloat b08[3] = {- (width + widthOffset) / 2, height / 2, length }; GLfloat b09[3] = {- (width + widthOffset) / 2, -height / 2, length }; GLfloat b10[3] = { (width + widthOffset) / 2, height / 2, length }; GLfloat b11[3] = {(width + widthOffset) / 2, -height / 2, length }; GLfloat b12[3] = {0, height / 2, length + heightOffset }; GLfloat b13[3] = {0, -height / 2, length + heightOffset }; static GLfloat n00[3] = { 1, 0, 0 } ; static GLfloat n01[3] = { -1, 0, 0 } ; static GLfloat n02[3] = { 0, 1, 0 } ; static GLfloat n03[3] = { 0, -1, 0 } ; static GLfloat n05[3] = { 0, 0, -1 } ; static GLfloat n06[3] = { -0.7071f, 0, 0.7071f } ; static GLfloat n07[3] = { 0.7071f, 0, 0.7071f } ; glBegin(GL_QUADS); // Draw arrow body as brick glNormal3fv(n02); glVertex3fv(b05); glVertex3fv(b06); //glNormal3fv(n02); glVertex3fv(b02); //glNormal3fv(n02); glVertex3fv(b01); //glNormal3fv(n02); glNormal3fv(n01); glVertex3fv(b04); glVertex3fv(b05); //glNormal3fv(n01); glVertex3fv(b01); //glNormal3fv(n01); glVertex3fv(b00); //glNormal3fv(n01); glNormal3fv(n03); glVertex3fv(b07); glVertex3fv(b04); //glNormal3fv(n03); glVertex3fv(b00); //glNormal3fv(n03); glVertex3fv(b03); //glNormal3fv(n03); glNormal3fv(n00); glVertex3fv(b06); glVertex3fv(b07); //glNormal3fv(n00); glVertex3fv(b03); //glNormal3fv(n00); glVertex3fv(b02); //glNormal3fv(n00); glNormal3fv(n05); glVertex3fv(b00); glVertex3fv(b01); //glNormal3fv(n05); glVertex3fv(b02); //glNormal3fv(n05); glVertex3fv(b03); //glNormal3fv(n05); // Draw arrow head glNormal3fv(n05); glVertex3fv(b09); glVertex3fv(b08); glVertex3fv(b10); glVertex3fv(b11); glNormal3fv(n06); glVertex3fv(b08); glVertex3fv(b09); glVertex3fv(b13); glVertex3fv(b12); glNormal3fv(n07); glVertex3fv(b12); glVertex3fv(b13); glVertex3fv(b11); glVertex3fv(b10); glEnd(); glBegin(GL_TRIANGLES); // Continue arrow head glNormal3fv(n02); glVertex3fv(b08); glVertex3fv(b12); //glNormal3fv(n02); glVertex3fv(b10); //glNormal3fv(n02); glNormal3fv(n03); glVertex3fv(b13); glVertex3fv(b09); //glNormal3fv(n03); glVertex3fv(b11); //glNormal3fv(n03); glEnd(); } void accFrustum(GLdouble left, GLdouble right, GLdouble bottom, GLdouble top, GLdouble _near, GLdouble _far, GLdouble pixdx, GLdouble pixdy, GLdouble eyedx, GLdouble eyedy, GLdouble focus) { GLdouble xwsize, ywsize; GLdouble dx, dy; GLint viewport[4]; glGetIntegerv (GL_VIEWPORT, viewport); xwsize = right - left; ywsize = top - bottom; dx = -( pixdx*xwsize / (GLdouble) viewport[2] + eyedx * _near / focus ); dy = -(pixdy*ywsize/(GLdouble) viewport[3] + eyedy * _near/ focus); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glFrustum (left + dx, right + dx, bottom + dy, top + dy, _near, _far); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glTranslatef (-eyedx, -eyedy, 0.0); } void accPerspective(GLdouble fovy, GLdouble aspect, GLdouble _near, GLdouble _far, GLdouble pixdx, GLdouble pixdy, GLdouble eyedx, GLdouble eyedy, GLdouble focus) { GLdouble fov2,left,right,bottom,top; fov2 = ((fovy*PI) / 180.0) / 2.0; top = _near / (cos(fov2) / sin(fov2)); bottom = -top; right = top * aspect; left = -right; accFrustum (left, right, bottom, top, _near, _far, pixdx, pixdy, eyedx, eyedy, focus); } } //namespace ugene-1.9.8/src/plugins/biostruct3d_view/src/BioStruct3DGLRender.cpp0000644000175000017500000000666611651544321024064 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "BioStruct3DColorScheme.h" #include "BioStruct3DGLRender.h" #include "BallAndStickGLRenderer.h" #include "TubeGLRenderer.h" #include "VanDerWaalsGLRenderer.h" #include "WormsGLRenderer.h" namespace U2 { /* class BioStruct3DGLRendererRegistry */ const QString BioStruct3DGLRendererRegistry::defaultFactoryName() { return WormsGLRenderer::ID; } const QList BioStruct3DGLRendererRegistry::factoriesNames() { return getInstance()->factories.keys(); } const BioStruct3DGLRendererFactory* BioStruct3DGLRendererRegistry::getFactory(const QString &name) { return getInstance()->factories.value(name, 0); } BioStruct3DGLRenderer* BioStruct3DGLRendererRegistry::createRenderer(const QString &name, const BioStruct3D &bs, const BioStruct3DColorScheme* s, const QList &sm, const BioStruct3DRendererSettings *settings) { const BioStruct3DGLRendererFactory *fact = getFactory(name); if (fact) { return fact->createInstance(bs,s,sm,settings); } return 0; } BioStruct3DGLRendererRegistry::BioStruct3DGLRendererRegistry() { registerFactories(); } BioStruct3DGLRendererRegistry* BioStruct3DGLRendererRegistry::getInstance() { static BioStruct3DGLRendererRegistry *reg = new BioStruct3DGLRendererRegistry(); return reg; } bool BioStruct3DGLRendererRegistry::isAvailableFor(const QString &name, const BioStruct3D &biostruct) { const BioStruct3DGLRendererFactory *fact = getFactory(name); return fact->isAvailableFor(biostruct); } QList BioStruct3DGLRendererRegistry::getRenderersAvailableFor(const BioStruct3D &biostruct) { BioStruct3DGLRendererRegistry *reg = getInstance(); QList ret; foreach (const BioStruct3DGLRendererFactory *fact, reg->factories) { if (fact->isAvailableFor(biostruct)) { ret.append(fact->getName()); } } return ret; } #define REGISTER_FACTORY(c) factories.insert(c::ID, new c::Factory(c::ID)) void BioStruct3DGLRendererRegistry::registerFactories() { REGISTER_FACTORY(BallAndStickGLRenderer); REGISTER_FACTORY(VanDerWaalsGLRenderer); REGISTER_FACTORY(TubeGLRenderer); REGISTER_FACTORY(WormsGLRenderer); } /* class BioStruct3DGLRenderer */ BioStruct3DGLRenderer::BioStruct3DGLRenderer( const BioStruct3D& _bioStruct, const BioStruct3DColorScheme* _s, const QList &_shownModels, const BioStruct3DRendererSettings *_settings) : bioStruct(_bioStruct), colorScheme(_s), shownModels(_shownModels), settings(_settings) {} void BioStruct3DGLRenderer::setColorScheme( const BioStruct3DColorScheme* s ) { colorScheme = s; updateColorScheme(); } } //namespace ugene-1.9.8/src/plugins/biostruct3d_view/src/ExportImage3DGLDialog.cpp0000644000175000017500000000425311651544321024340 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "ExportImage3DGLDialog.h" #include "BioStruct3DGLWidget.h" #include "gl2ps/gl2ps.h" #include #include #include #include #include #include namespace U2 { ExportImage3DGLDialog::ExportImage3DGLDialog( BioStruct3DGLWidget* widget ) : ExportImageDialog(widget, true, true), glWidget(widget) { } bool ExportImage3DGLDialog::exportToSVG(){ int opt = GL2PS_NONE; glWidget->writeImage2DToFile(GL2PS_SVG, opt, 2, qPrintable(getFilename())); return true; //TODO: need check on error } bool ExportImage3DGLDialog::exportToPDF(){ int opt = GL2PS_NONE; if(getFormat() == "ps"){ glWidget->writeImage2DToFile(GL2PS_PS, opt, 2, qPrintable(getFilename())); return true; //TODO: need check on error }else if(getFormat() == "pdf"){ glWidget->writeImage2DToFile(GL2PS_PDF, opt, 2, qPrintable(getFilename())); return true; //TODO: need check on error } return false; } bool ExportImage3DGLDialog::exportToBitmap(){ QPixmap image = glWidget->renderPixmap(getWidth(), getHeight()); if(hasQuality()){ return image.save(getFilename(), qPrintable(getFormat()), getQuality()); }else{ return image.save(getFilename(), qPrintable(getFormat())); } } } // namespace ugene-1.9.8/src/plugins/biostruct3d_view/src/VanDerWaalsGLRenderer.h0000644000175000017500000000310111651544321024077 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_BIOSTRUCT3D_VANDERWAALS_RENDERER_H_ #define _U2_BIOSTRUCT3D_VANDERWAALS_RENDERER_H_ #include "BioStruct3DGLRender.h" namespace U2 { class VanDerWaalsGLRenderer : public BioStruct3DGLRenderer { protected: VanDerWaalsGLRenderer(const BioStruct3D& struc, const BioStruct3DColorScheme* s, const QList &shownModels, const BioStruct3DRendererSettings *settings); public: void drawBioStruct3D(); virtual void create() {}; virtual void updateColorScheme() {}; virtual void updateShownModels() {}; virtual void updateSettings() {}; private: void drawAtoms(const BioStruct3DColorScheme* s); RENDERER_FACTORY(VanDerWaalsGLRenderer) }; } //namespace #endif // _U2_BIOSTRUCT3D_VANDERWAALS_RENDERER_H_ ugene-1.9.8/src/plugins/biostruct3d_view/src/GLFrameManager.cpp0000644000175000017500000001260411651544321023131 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include #include "GLFrameManager.h" #include namespace U2 { const GLfloat GLFrame::DEFAULT_ZOOM = 45.0f; //const Vector3D GLFrame::DEFAULT_CAMERA = Vector3D(0, 0, 0); /////////////////////////////////////////////////////////////////////////////////////////// /// GLFrame GLFrame::GLFrame(QGLWidget* widget) : glWidget(widget), rotMatrix(), synchLock(false), cameraClipNear(0), cameraClipFar(0), zoomFactor(DEFAULT_ZOOM), cameraPosition(0,0,0) { rotMatrix.loadIdentity(); } void GLFrame::performZoom( float delta ) { static const float maxZoom = 150.0; static const float minZoom = 2.0; zoomFactor += delta; if (zoomFactor < minZoom) { zoomFactor = minZoom; return; } if (zoomFactor > maxZoom) { zoomFactor = maxZoom; return; } } void GLFrame::performShift(float deltaX, float deltaY) { static float defaultWidth=1092; Vector3D shiftVector; float frameFactor = glWidget->width()/defaultWidth; shiftVector.set(deltaX*zoomFactor*frameFactor, deltaY*zoomFactor*frameFactor, 0); cameraPosition+=shiftVector; } const Vector3D GLFrame::getCameraPosition()const { return cameraPosition; } void GLFrame::setCameraPosition(float x, float y, float z) { cameraPosition.set(x, y, z); } void GLFrame::setCameraPosition(const Vector3D &v) { cameraPosition = v; } void GLFrame::setCameraClip(float clipNear, float clipFar) { cameraClipNear = clipNear; cameraClipFar = clipFar; } void GLFrame::rotateCamera(const Vector3D& rotAxis, float rotAngle ) { glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glRotatef(rotAngle, rotAxis.x, rotAxis.y, rotAxis.z ); glMultMatrixf(rotMatrix.data()); glGetFloatv( GL_MODELVIEW_MATRIX, rotMatrix.data()); } #define ZOOM_FACTOR_ID "ZOOM_FACTOR" #define CAMERA_STATE_POSITION_X_ID "CAMERA_STATE_POSITION_X" #define CAMERA_STATE_POSITION_Y_ID "CAMERA_STATE_POSITION_Y" #define ROTATION_MATRIX_ID "ROTATION_MATRIX" void GLFrame::setState( const QVariantMap& state ) { cameraPosition.x = state.value(CAMERA_STATE_POSITION_X_ID, 0).value(); cameraPosition.y = state.value(CAMERA_STATE_POSITION_Y_ID, 0).value(); zoomFactor = state.value(ZOOM_FACTOR_ID, DEFAULT_ZOOM).value(); QVariantList rotML = state.value(ROTATION_MATRIX_ID).value(); if (!rotML.isEmpty()) { rotMatrix.load(rotML); } } void GLFrame::writeStateToMap( QVariantMap& state ) { state[CAMERA_STATE_POSITION_X_ID] = QVariant::fromValue(cameraPosition.x); state[CAMERA_STATE_POSITION_Y_ID] = QVariant::fromValue(cameraPosition.y); state[ZOOM_FACTOR_ID] = QVariant::fromValue(zoomFactor); state[ROTATION_MATRIX_ID] = rotMatrix.store(); } void GLFrame::updateViewPort( int width, int height ) { glViewport(0, 0, width, height); glMatrixMode(GL_PROJECTION); glLoadIdentity(); // Set view settings GLfloat aspect = GLfloat(width) / height; gluPerspective(zoomFactor, aspect, cameraClipNear, cameraClipFar); } void GLFrame::updateViewPort() { updateViewPort(glWidget->width(), glWidget->height()); } GLFrameManager::~GLFrameManager() { } void GLFrameManager::addGLFrame( GLFrame* glFrame) { widgetFrameMap.insert(glFrame->getGLWidget(), glFrame); } GLFrame* GLFrameManager::getGLWidgetFrame( QGLWidget* widget ) { if (widgetFrameMap.contains(widget)) { return widgetFrameMap.value(widget); } else { return NULL; } } QList GLFrameManager::getGLFrames() { return widgetFrameMap.values(); } void GLFrameManager::setSyncLock( bool lockOn, QGLWidget* syncWidget ) { syncLock = lockOn; if (lockOn) { GLFrame* syncFrame = getGLWidgetFrame(syncWidget); QVariantMap state; syncFrame->writeStateToMap(state); foreach(GLFrame* frame, widgetFrameMap.values()) { if (frame != syncFrame) { frame->makeCurrent(); frame->setState(state); frame->updateViewPort(); frame->updateGL(); } } } } void GLFrameManager::removeGLWidgetFrame( QGLWidget* widget ) { Q_ASSERT(widgetFrameMap.contains(widget)); widgetFrameMap.remove(widget); } QList GLFrameManager::getActiveGLFrameList( GLFrame* currentFrame, bool syncModeOn ) { if (syncModeOn) { return widgetFrameMap.values(); } else { QList lst; lst.append(currentFrame); return lst; } } void GLFrameManager::clear() { widgetFrameMap.clear(); } } //namespace ugene-1.9.8/src/plugins/biostruct3d_view/src/BioStruct3DGLWidget.h0000644000175000017500000002535711651544321023533 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_OPENGL_WIDGET_H_ #define _U2_OPENGL_WIDGET_H_ #include "BioStruct3DGLRender.h" #include "BioStruct3DColorScheme.h" #include "AnaglyphRenderer.h" #include #include #include #include #include #include #include #include #include #include namespace U2 { class Document; class BioStruct3D; class BioStruct3DColorSchemeFactory; class BioStruct3DGLRendererFactory; class MolecularSurfaceRendererFactory; class AnnotatedDNAView; class Annotation; class AnnotationTableObject; class MolecularSurfaceCalcTask; class Task; class AnnotationSelection; class DNASequenceObject; class ADVSequenceObjectContext; class LRegionsSelection; class GLFrameManager; class GLFrame; class MolecularSurface; class MolecularSurfaceRenderer; class U2Region; /** Each biostruct added to scene should be represented by context */ class BioStruct3DRendererContext { public: BioStruct3DRendererContext(const BioStruct3DObject *obj) : obj(obj), biostruct(&obj->getBioStruct3D()) {} const BioStruct3DObject *obj; const BioStruct3D *biostruct; QSharedPointer renderer; QSharedPointer colorScheme; }; /*! * @class BioStruct3DGLWidget BioStruct3DGLWidget.h * @brief Class for BioStruct3DObject visualization. * * This widget provides a 3D graphical view of a macromolecular structure. In terms * of the Model-View architecture we consider * the BioStruct3D the model and GLWidget a view of this model. * * The widget relies on various GLRenderer and ColorScheme subclasses to handle the * rendering of the 3d objects. * * Also it includes actions for visualization control. */ class BioStruct3DGLWidget : public QGLWidget { Q_OBJECT static int widgetCount; public: /*! * Constructor. * @param bsObj BioStruct3DObject contains 3d model for visualization * @param view DnaView context for connecting structure 3D representation and sequence view * @param manager GlFrameManager is required for OpenGL frame manipulation * @param parent Parent widget */ BioStruct3DGLWidget(BioStruct3DObject* bsObj, const AnnotatedDNAView* view, GLFrameManager* manager, QWidget *parent); //! Destructor. ~BioStruct3DGLWidget(); //! @return BioStruct3D const reference. const BioStruct3D& getBioStruct3D() const { return *(contexts.first().biostruct); } //! @return BioStruct3D Protein Data Bank id. const QString getPDBId() const { return contexts.first().biostruct->pdbId; } //! @return BioStruct3DObject name. const QString getBioStruct3DObjectName() const { return contexts.first().obj->getGObjectName(); } /*! * @return Menu containing display actions: renderers, color schemes etc. */ QMenu* getDisplayMenu(); /*! * Records widget active settings (part of UGENE architecture). * @return Current widgets settings. */ QVariantMap getState(); /*! * Restores widget settings with given (part of UGENE architecture). * @param state Widgets settings. */ void setState(const QVariantMap& state); /*! * Restores default widget settings (viewMatrix, glRenderer, color scheme) */ void restoreDefaultSettigns(); /*! * @param delta Positive value: zoom in, negative value: zoom out. */ void zoom(float delta); void shift(float deltaX, float deltaY); /*! * Creates 2d vector image of BioStruct3DGLWidget contents using gl2ps. */ void writeImage2DToFile(int format, int options, int nbcol, const char *fileName); void setBackgroundColor(QColor backgroundColor); /** @returns This widget GLFrame */ GLFrame *getGLFrame() { return glFrame.get(); } /** Draws scene without setting camera */ void draw(); /** @returns scene rotation center */ Vector3D getSceneCenter() const; /** @returns scene bounding sphere radius */ float getSceneRadius() const; protected: /*! * QGlWidget virtual function, initializes OpenGL params. See, Qt docs "QGLWidget" for details. */ void initializeGL(); /*! * QGlWidget virtual function, sets viewport * @param width GLWidget width * @param height GLWidget height */ void resizeGL(int width, int height); /*! * QGlWidget virtual function, draw GL scene. */ void paintGL(); /*! * QWidget virtual function, mouse button down event handler. */ void mousePressEvent(QMouseEvent *event); /*! * QWidget virtual function, mouse move event handler. */ void mouseMoveEvent(QMouseEvent *event); /*! * QWidget virtual function, mouse wheel event handler. */ void wheelEvent ( QWheelEvent * event ); /*! * QWidget virtual function, executes context menu. */ void contextMenuEvent(QContextMenuEvent *_event); private: //! Sets unselected regions shading level void setUnselectedShadingLevel(int shading); /*! * Sets light position. * @param pos New light source position. Directional light is being used. */ void setLightPosition(const Vector3D& pos); // controller logic //! Creates actions for existing GLRenderers, loads default renderer. void loadGLRenderers(const QList &availableRenderers); //! Creates actions for existing ColorSchemes, loads default color scheme. void loadColorSchemes(); //! Creates actions for structural alignment void createStrucluralAlignmentActions(); //! Creates menu for structural alignment QMenu* createStructuralAlignmentMenu(); void createActions(); void createMenus(); // view logic /** Adds biostruct object to scene. * @param shownModels is a modelId list (same as in PDB) */ void addBiostruct(const BioStruct3DObject *biostruct, const QList &shownModels = QList()); //! Creates renderers for all biostructs. void setupRenderer(const QString &name); //! Creates color scheme for all biostructs. void setupColorScheme(const QString &name); //! Updates color scheme for all renderers. void updateAllColorSchemes(); /** Updates all renderers. * Should be called from initializeGL for display list recreation */ void updateAllRenderers(); //! Show/hide selected model for first biostruct //! @param modelId - key from BioStruct3D::modelMap void showModel(int modelId, bool show); //! Show/hide all models for first biostruct void showAllModels(bool show); /** Setup frame settings: camera clip, camera position */ void setupFrame(); void saveDefaultSettings(); void connectExternalSignals(); Vector3D getTrackballMapping(int x, int y); static int getWidgetCount(QString objectName); bool isSyncModeOn(); private: // related sequences view const AnnotatedDNAView* dnaView; QList contexts; // Settings common for all renderers, such as detail level BioStruct3DRendererSettings rendererSettings; GLFrameManager* frameManager; std::auto_ptr glFrame; std::auto_ptr molSurface; std::auto_ptr surfaceRenderer; MolecularSurfaceCalcTask* surfaceCalcTask; AnaglyphStatus anaglyphStatus; std::auto_ptr anaglyph; QVariantMap defaultsSettings; // controller logic QString currentColorSchemeName; QString currentGLRendererName; // camera GLfloat rotAngle, spinAngle; Vector3D rotAxis, lastPos; // light GLfloat lightPostion[4]; QColor backgroundColor; QColor selectionColor; QTimer* animationTimer; int unselectedShadingLevel; // controller logic QAction *spinAction; QAction *settingsAction; QAction *closeAction; QAction *exportImageAction; // actions for selecting/deselecting shown models QAction *selectModelsAction; // structural alignment related actions QAction *alignWithAction; QAction *resetAlignmentAction; QActionGroup *colorSchemeActions; QActionGroup *rendererActions; QActionGroup *molSurfaceRenderActions; QActionGroup *molSurfaceTypeActions; QMenu *selectColorSchemeMenu; QMenu *selectRendererMenu; QMenu *displayMenu; private slots: void sl_selectColorScheme(QAction* action); void sl_selectGLRenderer(QAction* action); void sl_updateRenderSettings(const QStringList& list); void sl_acitvateSpin(); void sl_updateAnnimation(); void sl_settings(); void sl_exportImage(); // structural alignment relalated slots void sl_alignWith(); void sl_resetAlignment(); void sl_onAlignmentDone(Task*); // slots for handling sequence selection void sl_onSequenceAddedToADV(ADVSequenceObjectContext *ctx); void sl_onSequenceRemovedFromADV(ADVSequenceObjectContext *ctx); void sl_onSequenceSelectionChanged(LRegionsSelection* s, const QVector& added, const QVector& removed); // slots for select/deselect shown models actions // they affects only first biostruct void sl_selectModels(); // slots for surface renderers void sl_showSurface(); void sl_hideSurface(); void sl_selectSurfaceRenderer(QAction* surfaceRenderer); // used only for handling MolecularSurfaceCalcTask // should be in special MolecularSurfaceProxy void sl_onTaskFinished(Task* task); public: static const QString BACKGROUND_COLOR_NAME; static const QString PRODUCT_NAME; static const QString PLUGIN_NAME; static const QString COLOR_SCHEME_NAME; static const QString RENDERER_NAME; static const QString OBJECT_ID_NAME; static const QString SELECTION_COLOR_NAME; static const QString RENDER_DETAIL_LEVEL_NAME; static const QString SHADING_LEVEL_NAME; static const QString ANAGLYPH_STATUS_NAME; }; } // namespace U2 #endif // _U2_OPENGL_WIDGET_H ugene-1.9.8/src/plugins/biostruct3d_view/src/WormsGLRenderer.cpp0000644000175000017500000002762111651544321023407 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include #include #include "GraphicUtils.h" #include "BioStruct3DColorScheme.h" #include "BioStruct3DGLWidget.h" #include "WormsGLRenderer.h" namespace U2 { const QString WormsGLRenderer::ID(QObject::tr("Worms")); WormsGLRenderer::WormsGLRenderer( const BioStruct3D& struc, const BioStruct3DColorScheme* s, const QList &shownModels, const BioStruct3DRendererSettings *settings) : BioStruct3DGLRenderer(struc,s,shownModels,settings) { create(); } bool WormsGLRenderer::isAvailableFor(const BioStruct3D &bioStruct) { bool available = false; const char* alphaCarbonTag = "CA"; const char* phosophorTag = "P"; const char* carbonylOxygenTag = "O"; foreach (const SharedMolecule &mol, bioStruct.moleculeMap) { int modelId = 0; foreach (const Molecule3DModel& model, mol->models) { foreach (const SharedAtom atom, model.atoms) { if ( (atom->name.trimmed() == alphaCarbonTag) || (atom->name.trimmed() == phosophorTag) || (atom->name.trimmed() == carbonylOxygenTag) ) { available = true; } } ++modelId; } } return available; } void WormsGLRenderer::create() { assert(isAvailableFor(bioStruct) && "Availability must be checked first!"); const char* alphaCarbonTag = "CA"; const char* phosophorTag = "P"; const char* carbonylOxygenTag = "O"; int numModels = bioStruct.modelMap.count(); QMapIterator i(bioStruct.moleculeMap); while (i.hasNext()) { i.next(); const SharedMolecule mol = i.value(); BioPolymer bioPolymer; bioPolymer.bpModels.resize(numModels); int modelId = 0; foreach (const Molecule3DModel& model, mol->models) { BioPolymerModel& bpModel = bioPolymer.bpModels[modelId]; foreach (const SharedAtom atom, model.atoms) { if ((atom->name.trimmed() == alphaCarbonTag) || (atom->name.trimmed() == phosophorTag)) { bpModel.monomerMap[atom->residueIndex.toInt()].alphaCarbon = atom; } if ( (atom->name.trimmed() == carbonylOxygenTag) && (bpModel.monomerMap.contains(atom->residueIndex.toInt()))) { bpModel.monomerMap[atom->residueIndex.toInt()].carbonylOxygen = atom; } } ++modelId; } bioPolymerMap.insert(i.key(), bioPolymer); } createWorms(); } void WormsGLRenderer::drawWorms( ) { GLUquadricObj *pObj; // Quadric Object // Draw atoms as spheres pObj = gluNewQuadric(); gluQuadricNormals(pObj, GLU_SMOOTH); static float ribbonThickness = 0.3f; static float tension = 0.01f; foreach (int chainId, wormMap.keys()) { const Worm worm = wormMap.value(chainId); foreach (int index, shownModels) { const WormModel& model = worm.models.at(index); //Draw worm bodies (let the bodies set the scene!!!) const AtomsVector wormCoords = model.atoms; int size = wormCoords.size(); Color4f atomColor; for (int i = 0; i + 3 < size; ++i) { const SharedAtom a0 = wormCoords.at(i); const SharedAtom a1 = wormCoords.at(i+1); const SharedAtom a2 = wormCoords.at(i+2); const SharedAtom a3 = wormCoords.at(i+3); // draw worms only between sequential residues if (a2->residueIndex.toInt() - a1->residueIndex.toInt() != 1) { continue; } glMaterialfv(GL_FRONT, GL_AMBIENT_AND_DIFFUSE, getAtomColor(a1)); glDrawHalfWorm(a0->coord3d, a1->coord3d, a2->coord3d, a3->coord3d, ribbonThickness, false, false, tension, settings->detailLevel); glMaterialfv(GL_FRONT, GL_AMBIENT_AND_DIFFUSE, getAtomColor(a2)); glDrawHalfWorm(a3->coord3d, a2->coord3d, a1->coord3d, a0->coord3d, ribbonThickness, false, false, tension, settings->detailLevel); } if (wormCoords.size() >= 3) { // Draw worm opening const SharedAtom a0 = wormCoords.at(0); const SharedAtom a1 = wormCoords.at(1); const SharedAtom a2 = wormCoords.at(2); Vector3D atomCoordFirst = model.openingAtom; glMaterialfv(GL_FRONT, GL_AMBIENT_AND_DIFFUSE, getAtomColor(a0)); glDrawHalfWorm(atomCoordFirst, a0->coord3d, a1->coord3d, a2->coord3d, ribbonThickness, true, false, tension, settings->detailLevel); glDrawHalfWorm(a2->coord3d, a1->coord3d, a0->coord3d, atomCoordFirst, ribbonThickness, false, false, tension, settings->detailLevel); // Draw worm ending const SharedAtom aN1 = wormCoords.at(size - 1); const SharedAtom aN2 = wormCoords.at(size - 2); const SharedAtom aN3 = wormCoords.at(size - 3); Vector3D atomCoordLast = model.closingAtom; glMaterialfv(GL_FRONT, GL_AMBIENT_AND_DIFFUSE, getAtomColor(aN1)); glDrawHalfWorm(atomCoordLast, aN1->coord3d, aN2->coord3d, aN3->coord3d, ribbonThickness, true, false, tension, settings->detailLevel); glDrawHalfWorm(aN3->coord3d, aN2->coord3d, aN1->coord3d, atomCoordLast, ribbonThickness, false, false, tension, settings->detailLevel); } //Draw 3d objects if (shownModels.count() == 1) { foreach( Object3D* obj, model.objects) { obj->draw(settings->detailLevel); } } } } gluDeleteQuadric(pObj); } void WormsGLRenderer::drawBioStruct3D() { drawWorms(); } void WormsGLRenderer::updateColorScheme() { foreach (int id, wormMap.keys() ) { Worm& worm = wormMap[id]; int numModels = worm.models.count(); for (int i= 0; i < numModels; ++i) { WormModel& model = worm.models[i]; qDeleteAll(model.objects); model.objects.clear(); } } //TODO: optimization -> don't have to create everything again createObjects3D(); } void WormsGLRenderer::updateShownModels() { updateColorScheme(); } void WormsGLRenderer::updateSettings() { updateColorScheme(); } void WormsGLRenderer::createObjects3D() { foreach (const SharedSecondaryStructure ss, bioStruct.secondaryStructures) { int startId = ss->startSequenceNumber; int endId = ss->endSequenceNumber; int chainId = ss->chainIndex; Q_ASSERT( chainId != 0 ); if (bioPolymerMap.contains(chainId)) { const BioPolymer& bpolymer = bioPolymerMap.value(chainId); int modelId = 0; foreach (const BioPolymerModel& bpModel, bpolymer.bpModels ) { if (bpModel.monomerMap.contains(startId) && bpModel.monomerMap.contains(endId)) { Object3D* obj = NULL; if (ss->type == SecondaryStructure::Type_AlphaHelix ) { obj = createHelix3D(startId, endId, bpModel); } else if (ss->type == SecondaryStructure::Type_BetaStrand) { obj = createStrand3D(startId, endId, bpModel); } if (obj != NULL) { wormMap[chainId].models[modelId].objects.append(obj); } } ++modelId; } } } } void WormsGLRenderer::createWorms() { // Create worms coordinates QMapIterator i(bioPolymerMap); while (i.hasNext()) { i.next(); int chainID = i.key(); const BioPolymer& bioPolymer = i.value(); Vector3D r1, r2,a,b; Vector3D openingVector, closingVector; Worm worm; foreach (const BioPolymerModel& bpModel, bioPolymer.bpModels) { WormModel wormModel; const QMap monomers = bpModel.monomerMap; QMap::const_iterator iter(monomers.constBegin()); // Calculate opening atom coords Monomer m = iter.value(); r1 = iter.value().alphaCarbon.constData()->coord3d; r2 = (++iter).value().alphaCarbon.constData()->coord3d; a = r1; b = (r2 - r1) / 100.f; wormModel.openingAtom = a + b*(-10.f); // Calculate closing atom coords iter = bpModel.monomerMap.constEnd(); r1 = (--iter).value().alphaCarbon.constData()->coord3d; r2 = (--iter).value().alphaCarbon.constData()->coord3d; a = r1; b = (r2 - r1) / 100.f; wormModel.closingAtom = a + b*(-10.f); // Add worm-building atom coords foreach (const Monomer& monomer, monomers) { const SharedAtom& atom = monomer.alphaCarbon; wormModel.atoms.append(atom); } worm.models.append(wormModel); } wormMap.insert(chainID, worm); } createObjects3D(); } WormsGLRenderer::~WormsGLRenderer() { foreach (Worm worm, wormMap) { foreach (WormModel model, worm.models) { qDeleteAll(model.objects); } } } const float* WormsGLRenderer::getAtomColor(const SharedAtom& atom) { atomColor = colorScheme->getAtomColor(atom); return atomColor.getConstData(); } Object3D* WormsGLRenderer::createHelix3D( int startId, int endId, const BioPolymerModel &bpModel ) { static float radius = 1.5f; QVector helixPoints; Color4f color(0,0,0,0); for (int i = startId; i <= endId; ++i) { if (!bpModel.monomerMap.contains(i)) continue; helixPoints.append(bpModel.monomerMap.value(i).alphaCarbon->coord3d); // getting "average" color const Color4f c = colorScheme->getAtomColor(bpModel.monomerMap.value(i).alphaCarbon); for (int i = 0; i < 4; ++i) { color[i] += c[i]; } } QPair axis = calcBestAxisThroughPoints(helixPoints); // getting "average" color for (int i = 0; i < 4; ++i) { color[i] /= (endId - startId + 1); } return new Helix3D(color, axis.first, axis.second, radius); } Object3D* WormsGLRenderer::createStrand3D( int startId, int endId, const BioPolymerModel &bpModel ) { QVector arrowPoints; Color4f color(0,0,0,0); for (int i = startId; i <= endId; ++i) { if (!bpModel.monomerMap.contains(i)) continue; arrowPoints.append(bpModel.monomerMap.value(i).alphaCarbon->coord3d); // getting "average" color const Color4f c = colorScheme->getAtomColor(bpModel.monomerMap.value(i).alphaCarbon); for (int i = 0; i < 4; ++i) { color[i] += c[i]; } } QPair axis = calcBestAxisThroughPoints(arrowPoints); // getting "average" color for (int i = 0; i < 4; ++i) { color[i] /= (endId - startId + 1); } return new Strand3D(color, axis.first, axis.second); } } //namespace ugene-1.9.8/src/plugins/biostruct3d_view/src/ui/0000755000175000017500000000000011651544321020267 5ustar ilyailyaugene-1.9.8/src/plugins/biostruct3d_view/src/ui/BioStruct3DSubsetEditor.ui0000644000175000017500000000415111651544321025271 0ustar ilyailya BioStruct3DSubsetEditor 0 0 195 115 Form Structure 0 0 Chain 0 0 Region Model 0 0 ugene-1.9.8/src/plugins/biostruct3d_view/src/ui/StructuralAlignmentDialog.ui0000644000175000017500000000647111651544321025765 0ustar ilyailya StructuralAlignmentDialog 0 0 385 86 Structural Alignment Algorithm 0 0 0 0 Reference true 0 0 Mobile Qt::Vertical QSizePolicy::Maximum 20 60 Qt::Horizontal QDialogButtonBox::Cancel|QDialogButtonBox::Ok buttonBox accepted() StructuralAlignmentDialog accept() 248 254 157 274 buttonBox rejected() StructuralAlignmentDialog reject() 316 260 286 274 ugene-1.9.8/src/plugins/biostruct3d_view/src/ui/SettingsDialog.ui0000644000175000017500000004014111651544321023546 0ustar ilyailya SettingsDialog 0 0 296 394 Settings 10 0 0 Set background color... 0 0 Set selection color... Detail level 50 200 Qt::Horizontal Unselected regions shading Qt::Horizontal Qt::Vertical 20 40 Qt::Horizontal 111 22 OK Cancel 0 170 Anaglyph view true false Eyes shift 0 199 0 Qt::Horizontal Qt::Horizontal 0 0 110 0 110 16777215 Glasses colors 0 0 130 0 Qt::LeftToRight Left Qt::AlignCenter Right Qt::AlignCenter 0 0 40 40 false false 40 40 false false false Qt::Vertical 72 13 Qt::Horizontal 40 20 0 0 Swap colors false Qt::Horizontal 40 20 Qt::Vertical 72 13 setBackgroundColorButton setSelectionColorButton renderDetailLevelSlider shadingSlider anaglyphViewGroupBox eyesShiftSlider glassesColorSchemeComboBox leftEyeColorChangeButton rightEyeColorChangeButton swapColorsButton okButton cancelButton setBackgroundColorButton clicked() SettingsDialog sl_setBackgroundColor() 155 27 137 62 setSelectionColorButton clicked() SettingsDialog sl_setSelectionColor() 155 52 137 62 renderDetailLevelSlider sliderMoved(int) SettingsDialog sl_setRenderDetailLevel() 173 105 137 100 eyesShiftSlider sliderMoved(int) SettingsDialog sl_setEyesShift() 102 229 125 179 anaglyphViewGroupBox clicked() SettingsDialog sl_setAnaglyph() 125 256 125 179 glassesColorSchemeComboBox currentIndexChanged(int) SettingsDialog sl_setGlassesColorScheme() 209 255 134 233 leftEyeColorChangeButton clicked() SettingsDialog sl_setLeftEyeColor() 59 315 134 233 rightEyeColorChangeButton clicked() SettingsDialog sl_setRightEyeColor() 105 315 134 233 swapColorsButton clicked() SettingsDialog sl_swapColors() 276 297 134 233 shadingSlider sliderMoved(int) SettingsDialog sl_setShadingLevel() 148 143 145 194 okButton clicked() SettingsDialog accept() 173 377 20 358 cancelButton clicked() SettingsDialog reject() 269 369 89 364 sl_setBackgroundColor() sl_setSelectionColor() sl_setAtomSize() sl_setRenderDetailLevel() sl_setAnaglyph() sl_setGlassesColorScheme() sl_setLeftEyeColor() sl_setRightEyeColor() sl_swapColors() sl_setEyesShift() ugene-1.9.8/src/plugins/biostruct3d_view/src/ui/SelectModelsDialog.ui0000644000175000017500000000441011651544321024330 0ustar ilyailya SelectModelsDialog 0 0 282 533 Select Models All Invert Qt::Horizontal 40 20 Qt::Horizontal QDialogButtonBox::Cancel|QDialogButtonBox::Ok buttonBox accepted() SelectModelsDialog accept() 248 254 157 274 buttonBox rejected() SelectModelsDialog reject() 316 260 286 274 ugene-1.9.8/src/plugins/biostruct3d_view/src/AnaglyphRenderer.cpp0000644000175000017500000001523511651544321023616 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "AnaglyphRenderer.h" #include "BioStruct3DGLWidget.h" #include "GLFrameManager.h" #include "GraphicUtils.h" namespace U2 { static const QString EYES_SHIFT_NAME("EyesShift"); static const QString LEFT_EYE_COLOR_NAME("LeftEyeColor"); static const QString RIGHT_EYE_COLOR_NAME("RightEyeColor"); QVariantMap AnaglyphSettings::toMap(QVariantMap &map) const { map[EYES_SHIFT_NAME] = qVariantFromValue(eyesShift); map[LEFT_EYE_COLOR_NAME] = qVariantFromValue(leftEyeColor); map[RIGHT_EYE_COLOR_NAME] = qVariantFromValue(rightEyeColor); return map; } AnaglyphSettings AnaglyphSettings::fromMap(const QVariantMap &map) { float eyesShift = map[EYES_SHIFT_NAME].value(); QColor leftEyeColor = map[LEFT_EYE_COLOR_NAME].value(); QColor rightEyeColor= map[RIGHT_EYE_COLOR_NAME].value(); return AnaglyphSettings(eyesShift, leftEyeColor, rightEyeColor); } void AnaglyphRenderer::init() { createEmptyTextures(); } void AnaglyphRenderer::resize(int _width, int _height) { CHECK_GL_ERROR width = _width, height = _height; if ( !(width > 0 && height > 0) ) { return; } createEmptyTextures(); CHECK_GL_ERROR } void AnaglyphRenderer::draw() { CHECK_GL_ERROR GLFrame *glFrame = renderer->getGLFrame(); float eyesShift = 5.0 * settings.eyesShift * glFrame->getCameraPosition().z / 200.0; glMatrixMode(GL_MODELVIEW); // Prepare anaglyph textures glPushMatrix(); //glTranslatef(eyesShift, 0, 0); glLoadIdentity(); gluLookAt(eyesShift, 0.0, glFrame->getCameraPosition().z, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0); // at this moment buffer must be clean glClear omitted as a slow operation //glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // isolate errors from main scene renderer CHECK_GL_ERROR renderer->draw(); glGetError(); glBindTexture(GL_TEXTURE_2D, anaglyphRenderTextureRight); glCopyTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, 0, 0, width, height, 0); glPopMatrix(); glPushMatrix(); //glTranslatef(-eyesShift, 0, 0); glLoadIdentity(); gluLookAt(-eyesShift, 0.0, glFrame->getCameraPosition().z, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // isolate errors from main scene renderer CHECK_GL_ERROR renderer->draw(); glGetError(); glBindTexture(GL_TEXTURE_2D, anaglyphRenderTextureLeft); glCopyTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, 0, 0, width, height, 0); glPopMatrix(); // Draw anaglyph textures in ortho projection glMatrixMode(GL_MODELVIEW); glPushMatrix(); glLoadIdentity(); glMatrixMode(GL_PROJECTION); glPushMatrix(); setOrthoProjection(); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); drawTexturesAnaglyph(); glMatrixMode(GL_PROJECTION); glPopMatrix(); glMatrixMode(GL_MODELVIEW); glPopMatrix(); CHECK_GL_ERROR } void AnaglyphRenderer::setOrthoProjection() { CHECK_GL_ERROR glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrtho(0, 1, 1, 0, -1, 1); glMatrixMode(GL_MODELVIEW); CHECK_GL_ERROR } void AnaglyphRenderer::createEmptyTextures() { CHECK_GL_ERROR glDeleteTextures(1, &anaglyphRenderTextureLeft); glDeleteTextures(1, &anaglyphRenderTextureRight); glDeleteTextures(1, &tempAnaglyphRenderTexture); // TODO : check for NPOT sizes GLuint texwidth = width, texheight = height; GLuint txtnumbers[3] = {0}; glGenTextures(3, txtnumbers); char *txtdata = new char[texwidth * texheight * 4]; for (GLuint *txtnumber = txtnumbers; txtnumber < txtnumbers + 3; ++txtnumber) { glBindTexture(GL_TEXTURE_2D, *txtnumber); glTexImage2D(GL_TEXTURE_2D, 0, 4, texwidth, texheight, 0, GL_RGBA, GL_UNSIGNED_BYTE, (GLvoid*) txtdata); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER,GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER,GL_LINEAR); } delete[] txtdata; anaglyphRenderTextureLeft = txtnumbers[0]; anaglyphRenderTextureRight = txtnumbers[1]; tempAnaglyphRenderTexture = txtnumbers[2]; CHECK_GL_ERROR } void AnaglyphRenderer::drawTexturesAnaglyph() { CHECK_GL_ERROR drawTexture(anaglyphRenderTextureLeft, settings.rightEyeColor.red(), settings.rightEyeColor.green(), settings.rightEyeColor.blue(), 0.5f, false); // colored left image glBindTexture(GL_TEXTURE_2D, tempAnaglyphRenderTexture); glCopyTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, 0, 0, width, height, 0); // Copy Our ViewPort To The Blur Texture (From 0,0 To 128,128... No Border) drawTexture(anaglyphRenderTextureRight, settings.leftEyeColor.red(), settings.leftEyeColor.green(), settings.leftEyeColor.blue(), 0.5f, false); // colored right image drawTexture(tempAnaglyphRenderTexture, 255, 255, 255, 1.0f, true); CHECK_GL_ERROR } void AnaglyphRenderer::drawTexture(GLuint anaglyphRenderTexture, int red, int green, int blue, float alpha, bool alphaOnly) { CHECK_GL_ERROR glEnable(GL_TEXTURE_2D); if (alphaOnly){ // the second image is this, it has needed alpha color glBlendFunc(GL_DST_ALPHA, GL_DST_ALPHA); } else { glBlendFunc(GL_ONE, GL_ONE); } glBindTexture(GL_TEXTURE_2D, anaglyphRenderTexture); glColor4ub(red, green, blue, (GLubyte) (alpha * 255.0)); glBegin(GL_QUADS); glTexCoord2f(0, 1); glVertex2f(0,0); glTexCoord2f(0, 0); glVertex2f(0, 1); glTexCoord2f(1, 0); glVertex2f(1, 1); glTexCoord2f(1, 1); glVertex2f(1, 0); glEnd(); // Unbind the blur texture glBindTexture(GL_TEXTURE_2D, 0); glDisable(GL_TEXTURE_2D); CHECK_GL_ERROR } bool AnaglyphRenderer::isAvailable() { draw(); return !hasErrors; } } // namespace U2 ugene-1.9.8/src/plugins/biostruct3d_view/src/MolecularSurfaceRenderer.cpp0000644000175000017500000000752011651544321025305 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "MolecularSurfaceRenderer.h" #include #include #include namespace U2 { /* class MolecularSurfaceRendererRegistry */ const QString MolecularSurfaceRendererRegistry::defaultFactoryName() { return ConvexMapRenderer::ID; } const QList MolecularSurfaceRendererRegistry::factoriesNames() { return getInstance()->factories.keys(); } const MolecularSurfaceRendererFactory* MolecularSurfaceRendererRegistry::getFactory(const QString &name) { return getInstance()->factories.value(name, 0); } MolecularSurfaceRenderer* MolecularSurfaceRendererRegistry::createMSRenderer(const QString &name) { const MolecularSurfaceRendererFactory *fact = getFactory(name); if (fact) { return fact->createInstance(); } return 0; } MolecularSurfaceRendererRegistry::MolecularSurfaceRendererRegistry() { registerFactories(); } MolecularSurfaceRendererRegistry* MolecularSurfaceRendererRegistry::getInstance() { static MolecularSurfaceRendererRegistry *reg = new MolecularSurfaceRendererRegistry(); return reg; } #define REGISTER_FACTORY(c) factories.insert(c::ID, new c::Factory) void MolecularSurfaceRendererRegistry::registerFactories() { REGISTER_FACTORY(DotsRenderer); REGISTER_FACTORY(ConvexMapRenderer); } const QString DotsRenderer::ID(QObject::tr("Dots")); const QString ConvexMapRenderer::ID(QObject::tr("Convex Map")); /* class DotsRenderer : public MolecularSurfaceRenderer */ void DotsRenderer::drawSurface( MolecularSurface& surface ) { GLboolean ligting = glIsEnabled(GL_LIGHTING); glDisable(GL_LIGHTING); glPointSize(1.0f); glColor3f(1.0f, 1.0f, 1.0f); glBegin(GL_POINTS); foreach(const Face& face, surface.getFaces()) { float vct[3][3] = { {face.v[0].x,face.v[0].y,face.v[0].z}, {face.v[1].x,face.v[1].y,face.v[1].z}, {face.v[2].x,face.v[2].y,face.v[2].z}, }; glVertex3fv(vct[0]); glVertex3fv(vct[1]); glVertex3fv(vct[2]); /*glVertex3f(face.v[0].x, face.v[0].y, face.v[0].z); glVertex3f(face.v[1].x, face.v[1].y, face.v[1].z); glVertex3f(face.v[2].x, face.v[2].y, face.v[2].z);*/ } glEnd(); if (ligting) glEnable(GL_LIGHTING); CHECK_GL_ERROR; } /* class ConvexMapRenderer : public MolecularSurfaceRenderer */ void ConvexMapRenderer::drawSurface( MolecularSurface& surface ) { static GLfloat wall_mat[] = {1.f, 1.f, 1.f, 0.3f}; glMaterialfv(GL_FRONT, GL_AMBIENT_AND_DIFFUSE, wall_mat); glBegin(GL_TRIANGLES); foreach(const Face& face, surface.getFaces()) { glNormal3f(face.n[0].x, face.n[0].y, face.n[0].z); glVertex3f(face.v[0].x, face.v[0].y, face.v[0].z); glNormal3f(face.n[1].x, face.n[1].y, face.n[1].z); glVertex3f(face.v[1].x, face.v[1].y, face.v[1].z); glNormal3f(face.n[2].x, face.n[2].y, face.n[2].z); glVertex3f(face.v[2].x, face.v[2].y, face.v[2].z); } glEnd( ); CHECK_GL_ERROR; } } // namespace ugene-1.9.8/src/plugins/biostruct3d_view/src/SelectModelsDialog.h0000644000175000017500000000306111651544321023526 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef U2_SELECTMODELSDIALOG_H #define U2_SELECTMODELSDIALOG_H #include "ui_SelectModelsDialog.h" #include namespace U2 { class SelectModelsDialog : public QDialog, public Ui::SelectModelsDialog { Q_OBJECT public: SelectModelsDialog(const QList &modelIds, const QList &selectedItems, QWidget *parent = 0); ~SelectModelsDialog(); const QList &getSelectedModelsIndexes() const { return selectedModelsIndexes; } public slots: virtual void accept(); void sl_onItemDoubleClicked(QListWidgetItem *item); void sl_onSlectAll(); void sl_onInvertSelection(); private: QList selectedModelsIndexes; }; } // namespace U2 #endif // #ifndef U2_SELECTMODELSDIALOG_H ugene-1.9.8/src/plugins/biostruct3d_view/src/BioStruct3DGLWidget.cpp0000644000175000017500000011053711651544321024061 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "BioStruct3DGLWidget.h" #include "BioStruct3DGLRender.h" #include "BioStruct3DColorScheme.h" #include "GLFrameManager.h" #include "ExportImage3DGLDialog.h" #include "SettingsDialog.h" #include "MolecularSurfaceRenderer.h" #include "SelectModelsDialog.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "gl2ps/gl2ps.h" #include "StructuralAlignmentDialog.h" #include #include // disable "unsafe functions" deprecation warnings on MS VS #ifdef Q_OS_WIN #pragma warning(disable : 4996) #endif namespace U2 { int BioStruct3DGLWidget::widgetCount = 0; static QColor DEFAULT_BACKGROUND_COLOR = Qt::black; static QColor DEFAULT_SELECTION_COLOR = Qt::yellow; static float DEFAULT_RENDER_DETAIL_LEVEL = 1.0; static int DEFAULT_SHADING_LEVEL = 50; const QString BioStruct3DGLWidget::BACKGROUND_COLOR_NAME("BackgroundColor"); const QString BioStruct3DGLWidget::PRODUCT_NAME("Unipro Ugene"); const QString BioStruct3DGLWidget::PLUGIN_NAME("BioStruct3D Viewer Plugin"); const QString BioStruct3DGLWidget::COLOR_SCHEME_NAME("ColorScheme"); const QString BioStruct3DGLWidget::RENDERER_NAME("GLRenderer"); const QString BioStruct3DGLWidget::OBJECT_ID_NAME("OBJECT_ID"); const QString BioStruct3DGLWidget::SELECTION_COLOR_NAME("SelectionColor"); const QString BioStruct3DGLWidget::SHADING_LEVEL_NAME("Shading Unselected Regions Level"); const QString BioStruct3DGLWidget::RENDER_DETAIL_LEVEL_NAME("RenderDetailLevel"); const QString BioStruct3DGLWidget::ANAGLYPH_STATUS_NAME("AnaglyphStatus"); BioStruct3DGLWidget::BioStruct3DGLWidget(BioStruct3DObject* obj, const AnnotatedDNAView *_dnaView, GLFrameManager* manager, QWidget *parent /* = 0*/) : QGLWidget(parent), dnaView(_dnaView), contexts(), rendererSettings(DEFAULT_RENDER_DETAIL_LEVEL), frameManager(manager), glFrame(new GLFrame(this)), molSurface(0), surfaceRenderer(), surfaceCalcTask(0), anaglyphStatus(DISABLED), anaglyph(new AnaglyphRenderer(this, AnaglyphSettings::defaultSettings())), defaultsSettings(), currentColorSchemeName(), currentGLRendererName(), rotAngle(0), spinAngle(0), rotAxis(), lastPos(), lightPostion(), backgroundColor(DEFAULT_BACKGROUND_COLOR), selectionColor(DEFAULT_SELECTION_COLOR), animationTimer(0), unselectedShadingLevel(DEFAULT_SHADING_LEVEL), spinAction(0), settingsAction(0), closeAction(0), exportImageAction(0), selectModelsAction(0), alignWithAction(0), resetAlignmentAction(0), colorSchemeActions(0), rendererActions(0), molSurfaceRenderActions(0), molSurfaceTypeActions(0), selectColorSchemeMenu(0), selectRendererMenu(0), displayMenu(0) { GCOUNTER( cvar, tvar, "BioStruct3DGLWidget" ); QString currentModelID = obj->getBioStruct3D().pdbId; setObjectName(QString("%1-%2").arg(++widgetCount).arg(currentModelID)); setWindowIcon(GObjectTypes::getTypeInfo(GObjectTypes::BIOSTRUCTURE_3D).icon); connectExternalSignals(); currentColorSchemeName = BioStruct3DColorSchemeRegistry::defaultFactoryName(); currentGLRendererName = BioStruct3DGLRendererRegistry::defaultFactoryName(); QList availableRenders = BioStruct3DGLRendererRegistry::getRenderersAvailableFor(obj->getBioStruct3D()); if (!availableRenders.contains(currentGLRendererName)) { currentGLRendererName = availableRenders.first(); } addBiostruct(obj); createActions(); createMenus(); loadColorSchemes(); loadGLRenderers(availableRenders); frameManager->addGLFrame(glFrame.get()); saveDefaultSettings(); } BioStruct3DGLWidget::~BioStruct3DGLWidget() { uiLog.trace("Biostruct3DGLWdiget "+objectName()+" deleted"); } void BioStruct3DGLWidget::setupFrame() { const float scaleFactor = 2.5; float radius = getSceneRadius(); float camZ = scaleFactor * radius; float cameraClipNear = (camZ - radius) * 0.66f; float cameraClipFar = (camZ + radius) * 1.2f; glFrame->setCameraClip(cameraClipNear, cameraClipFar); Vector3D pos = glFrame->getCameraPosition(); pos.z = camZ; glFrame->setCameraPosition(pos); glFrame->makeCurrent(); glFrame->updateViewPort(); glFrame->updateGL(); } float BioStruct3DGLWidget::getSceneRadius() const { // good idea: ask renderer for radius instead of asking biostruct float maxRadius = 0; const Vector3D sceneCenter = getSceneCenter(); foreach (const BioStruct3DRendererContext &ctx, contexts) { Vector3D center = ctx.biostruct->getCenter(); float radius = (center - sceneCenter).length() + ctx.biostruct->getRadius(); if (maxRadius < radius) { maxRadius = radius; } } return maxRadius; } Vector3D BioStruct3DGLWidget::getSceneCenter() const { // good idea: ask renderer for center instead of asking biostruct Vector3D c; foreach (const BioStruct3DRendererContext &ctx, contexts) { // TODO: transform should be applied in BioStruct Vector3D tmp = ctx.biostruct->getCenter(); c += tmp.dot(ctx.biostruct->getTransform()); } return c / float(contexts.length()); } void BioStruct3DGLWidget::initializeGL() { setLightPosition(Vector3D(0, 0.0, 1.0)); GLfloat light_diffuse[] = { 0.8f, 0.8f, 0.8f, 1.0 }; GLfloat light_specular[] = { 0.6f, 0.6f, 0.6f, 1.0 }; GLfloat mat_specular[] = { 0.6f, 0.6f, 0.6f, 1.0 }; GLfloat mat_shininess[] = { 90.0 }; qglClearColor(backgroundColor); glShadeModel (GL_SMOOTH); glMaterialfv(GL_FRONT, GL_SPECULAR, mat_specular); glMaterialfv(GL_FRONT, GL_SHININESS, mat_shininess); glLightfv(GL_LIGHT0, GL_DIFFUSE, light_diffuse); glLightfv(GL_LIGHT0, GL_SPECULAR, light_specular); glLightfv(GL_LIGHT0, GL_POSITION, lightPostion); glEnable(GL_BLEND); // Enable Blending glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); updateAllRenderers(); anaglyph->init(); if (!anaglyph->isAvailable()) { anaglyphStatus = NOT_AVAILABLE; } } void BioStruct3DGLWidget::resizeGL(int width, int height) { glFrame->updateViewPort(width, height); if (anaglyphStatus == ENABLED) { anaglyph->resize(width, height); } } void BioStruct3DGLWidget::paintGL() { if (!isVisible()) { return; } clock_t frameStart = clock(); // Clear buffers, setup modelview matrix // Scene render unable to do this since it used by anaglyph renderer glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); gluLookAt(0.0, 0.0, glFrame->getCameraPosition().z, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0); if (anaglyphStatus == ENABLED) { // draw using anaglyph renderer anaglyph->draw(); } else { // draw using default scene renderer (this) draw(); } clock_t frameEnd = clock(); double frameTime = (frameEnd - frameStart) / (double)CLOCKS_PER_SEC; perfLog.trace( QString("BioStruct3DView frame rendering time %1 s").arg(frameTime) ); } void BioStruct3DGLWidget::draw() { glEnable(GL_DEPTH_TEST); glEnable(GL_LIGHTING); glEnable(GL_LIGHT0); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); Vector3D rotCenter = getSceneCenter(); glTranslatef(glFrame->getCameraPosition().x, glFrame->getCameraPosition().y, 0); glMultMatrixf(glFrame->getRotationMatrix()); glTranslatef(-rotCenter.x ,-rotCenter.y, -rotCenter.z); foreach (const BioStruct3DRendererContext &ctx, contexts) { glPushMatrix(); #ifdef GL_VERSION_1_3 glMultTransposeMatrixf(ctx.biostruct->getTransform().data()); #else // on OpenGL versions below 1.3 glMultTransposeMatrix not suported // see http://www.opengl.org/resources/faq/technical/extensions.htm Matrix44 colmt = ctx.biostruct->getTransform(); colmt.transpose(); glMultMatrixf(colmt.data()); #endif ctx.renderer->drawBioStruct3D(); glPopMatrix(); } if(NULL != molSurface.get()) { glEnable(GL_CULL_FACE); glCullFace(GL_FRONT); surfaceRenderer->drawSurface(*molSurface); glCullFace(GL_BACK); surfaceRenderer->drawSurface(*molSurface); glDisable(GL_CULL_FACE); CHECK_GL_ERROR; } glDisable(GL_LIGHTING); glDisable(GL_LIGHT0); glDisable(GL_DEPTH_TEST); } Vector3D BioStruct3DGLWidget::getTrackballMapping(int x, int y) { Vector3D pos; /* project x,y onto a hemisphere centered within width, height */ pos.x = (2.0f*x - width()) / width(); pos.y = (height() - 2.0f*y) / height(); pos.z = 0; float d = pos.length(); d = (d < 1.0) ? d : 1.0; pos.z = sqrtf(1.0f - d*d); pos.normalize(); return pos; } void BioStruct3DGLWidget::contextMenuEvent(QContextMenuEvent *event) { QMenu menu; foreach(QAction* action, getDisplayMenu()->actions()) { menu.addAction(action); } menu.addAction(closeAction); menu.exec(event->globalPos()); } void BioStruct3DGLWidget::setLightPosition( const Vector3D& pos ) { lightPostion[0] = pos.x; lightPostion[1] = pos.y; lightPostion[2] = pos.z; lightPostion[3] = 1.0; } static int getSequenceChainId(const DNASequenceObject* seqObj) { const QVariantMap &info = seqObj->getDNASequence().info; int id = info.value(DNAInfo::CHAIN_ID, qVariantFromValue(-1)).toInt(); return id; } void BioStruct3DGLWidget::sl_onSequenceSelectionChanged(LRegionsSelection *s, const QVector &added, const QVector &removed) { if (!isVisible()) return; DNASequenceSelection* selection = qobject_cast(s); const DNASequenceObject* seqObj = selection->getSequenceObject(); assert(seqObj); const BioStruct3DRendererContext &ctx = contexts.first(); // check that biostruct and sequence objects are from the same doucment // apropriate relation check must be here if (seqObj->getDocument() == ctx.obj->getDocument()) { int chainId = getSequenceChainId(seqObj); assert(ctx.biostruct->moleculeMap.contains(chainId)); ctx.colorScheme->updateSelectionRegion(chainId, added, removed); updateAllColorSchemes(); update(); } } QVariantMap BioStruct3DGLWidget::getState() { QVariantMap state; glFrame->writeStateToMap(state); anaglyph->getSettings().toMap(state); state[ANAGLYPH_STATUS_NAME] = qVariantFromValue((int)anaglyphStatus); state[COLOR_SCHEME_NAME] = QVariant::fromValue(currentColorSchemeName); state[RENDERER_NAME] = QVariant::fromValue(currentGLRendererName); state[OBJECT_ID_NAME] = QVariant::fromValue(getBioStruct3DObjectName()); state[BACKGROUND_COLOR_NAME] = QVariant::fromValue(backgroundColor); state[SELECTION_COLOR_NAME] = QVariant::fromValue(selectionColor); state[RENDER_DETAIL_LEVEL_NAME] = QVariant::fromValue(rendererSettings.detailLevel); state[SHADING_LEVEL_NAME] = QVariant::fromValue(unselectedShadingLevel); return state; } void BioStruct3DGLWidget::setState( const QVariantMap& state ) { // bug-2859: correct save/restore current selection. if (state.isEmpty()) { return; } glFrame->makeCurrent(); glFrame->setState(state); anaglyphStatus = (AnaglyphStatus) state.value(ANAGLYPH_STATUS_NAME).value(); anaglyph->setSettings(AnaglyphSettings::fromMap(state)); backgroundColor = state.value(BACKGROUND_COLOR_NAME, DEFAULT_BACKGROUND_COLOR).value(); setBackgroundColor(backgroundColor); selectionColor = state.value(SELECTION_COLOR_NAME, DEFAULT_SELECTION_COLOR).value(); rendererSettings.detailLevel = state.value(RENDER_DETAIL_LEVEL_NAME, DEFAULT_RENDER_DETAIL_LEVEL).value(); QString previousColorSchemeName = currentColorSchemeName; QString previousGLRendererName = currentGLRendererName; currentColorSchemeName = state.value(COLOR_SCHEME_NAME, BioStruct3DColorSchemeRegistry::defaultFactoryName()).value(); currentGLRendererName = state.value(RENDERER_NAME, BioStruct3DGLRendererRegistry::defaultFactoryName()).value(); if (previousColorSchemeName != currentColorSchemeName){ setupColorScheme(currentColorSchemeName); } unselectedShadingLevel = state.value(SHADING_LEVEL_NAME, DEFAULT_SHADING_LEVEL).value(); setUnselectedShadingLevel(unselectedShadingLevel); if (previousGLRendererName != currentGLRendererName) { setupRenderer(currentGLRendererName); } resizeGL(width(), height()); updateGL(); } void BioStruct3DGLWidget::setupColorScheme(const QString &name) { QList::iterator i = contexts.begin(); for (; i != contexts.end(); ++i) { BioStruct3DRendererContext &ctx = *(i); // TODO: this situation may be potentialy dangerous // if renderer starts draw right now, maybe SharedPointer will be good solution BioStruct3DColorScheme *scheme = BioStruct3DColorSchemeRegistry::createColorScheme(name, ctx.obj); assert(scheme); scheme->setSelectionColor(selectionColor); scheme->setUnselectedShadingLevel((double)unselectedShadingLevel/100.0); ctx.colorScheme = QSharedPointer(scheme); ctx.renderer->setColorScheme(scheme); } } void BioStruct3DGLWidget::setupRenderer(const QString &name) { QList::iterator i = contexts.begin(); for (; i != contexts.end(); ++i) { BioStruct3DRendererContext &ctx = *(i); // TODO: this situation may be potentialy dangerous // if renderer starts draw right now, maybe SharedPointer will be good solution const QList &shownModelsIndexes = ctx.renderer->getShownModelsIndexes(); BioStruct3DGLRenderer *rend = BioStruct3DGLRendererRegistry::createRenderer(name, *ctx.biostruct, ctx.colorScheme.data(), shownModelsIndexes, &rendererSettings); assert(rend); ctx.renderer = QSharedPointer(rend); } } void BioStruct3DGLWidget::updateAllColorSchemes() { foreach (const BioStruct3DRendererContext &ctx, contexts) { ctx.renderer->updateColorScheme(); } } void BioStruct3DGLWidget::updateAllRenderers() { foreach (const BioStruct3DRendererContext &ctx, contexts) { ctx.renderer->update(); } } void BioStruct3DGLWidget::setBackgroundColor(QColor backgroundColor) { this->backgroundColor=backgroundColor; qglClearColor(backgroundColor); } void BioStruct3DGLWidget::zoom( float delta ) { bool syncLock = isSyncModeOn(); QList frames = frameManager->getActiveGLFrameList(glFrame.get(), syncLock); foreach( GLFrame* frame, frames) { frame->makeCurrent(); frame->performZoom(delta); frame->updateViewPort(); frame->updateGL(); } } void BioStruct3DGLWidget::shift( float deltaX, float deltaY) { bool syncLock = isSyncModeOn(); QList frames = frameManager->getActiveGLFrameList(glFrame.get(), syncLock); foreach( GLFrame* frame, frames) { frame->makeCurrent(); frame->performShift(deltaX, deltaY); frame->updateViewPort(); frame->updateGL(); } } void BioStruct3DGLWidget::saveDefaultSettings() { glFrame->writeStateToMap(defaultsSettings); defaultsSettings[COLOR_SCHEME_NAME] = QVariant::fromValue(currentColorSchemeName); defaultsSettings[RENDERER_NAME] = QVariant::fromValue(currentGLRendererName); } void BioStruct3DGLWidget::restoreDefaultSettigns() { assert(!defaultsSettings.isEmpty()); bool syncLock = isSyncModeOn(); QList frames = frameManager->getActiveGLFrameList(glFrame.get(), syncLock); foreach( GLFrame* frame, frames) { frame->makeCurrent(); frame->setState(defaultsSettings); frame->updateViewPort(); frame->updateGL(); } } void BioStruct3DGLWidget::showModel(int modelId, bool show) { BioStruct3DRendererContext &ctx = contexts.first(); // this function uses modelId - key from BioStruct3D::modelMap int idx = ctx.biostruct->modelMap.keys().indexOf(modelId); assert(idx != -1); QList shownModelsIndexes = ctx.renderer->getShownModelsIndexes(); if (show && !shownModelsIndexes.contains(idx)) { shownModelsIndexes.append(idx); } else if (!show) { shownModelsIndexes.removeAll(idx); } ctx.renderer->setShownModelsIndexes(shownModelsIndexes); } void BioStruct3DGLWidget::showAllModels(bool show) { BioStruct3DRendererContext &ctx = contexts.first(); QList shownModelsIndexes; if (show) { int numModels = ctx.biostruct->modelMap.size(); for (int i = 0; i < numModels; ++i) { shownModelsIndexes.append(i); } } ctx.renderer->setShownModelsIndexes(shownModelsIndexes); } void BioStruct3DGLWidget::sl_selectModels() { BioStruct3DRendererContext &ctx = contexts.first(); SelectModelsDialog dlg(ctx.biostruct->getModelsNames(), ctx.renderer->getShownModelsIndexes(), this); if (dlg.exec() == QDialog::Accepted) { ctx.renderer->setShownModelsIndexes(dlg.getSelectedModelsIndexes()); contexts.first().renderer->updateShownModels(); updateGL(); } } void BioStruct3DGLWidget::writeImage2DToFile( int format, int options, int nbcol, const char *fileName ) { FILE *fp = NULL; const char* FOPEN_ARGS = "wb"; const QByteArray title(fileName); int state = GL2PS_OVERFLOW, buffsize = 0; GLint viewport[4]; int sort = GL2PS_SIMPLE_SORT; fp = fopen(fileName, FOPEN_ARGS); if(!fp){ QMessageBox::warning(this, tr("Error"),tr("Unable to open file %1 for writing").arg(fileName)); return; } glGetIntegerv(GL_VIEWPORT,viewport); if (format == GL2PS_EPS) { // hack -> make widget aspect ratio 1:1 if (width() > height()) { int size = height(); resize(size, size); } } while(state == GL2PS_OVERFLOW){ buffsize += 2048*2048; gl2psBeginPage(title.constData(), "Unipro UGENE BioStruct3D Viewer plugin", viewport, format, sort, options, GL_RGBA, 0, NULL, nbcol, nbcol, nbcol, buffsize, fp, fileName); paintGL(); state = gl2psEndPage(); } fclose(fp); if (format == GL2PS_EPS) { // restore sizes updateGeometry(); } } void BioStruct3DGLWidget::loadColorSchemes() { currentColorSchemeName = BioStruct3DColorSchemeRegistry::defaultFactoryName(); // highlight default color scheme in menu QList::iterator iter; QList schemeActions = colorSchemeActions->actions(); for (iter = schemeActions.begin(); iter != schemeActions.end(); ++iter) { if ((*iter)->text() == currentColorSchemeName) { (*iter)->setChecked(true); break; } } assert(iter != schemeActions.end()); } void BioStruct3DGLWidget::loadGLRenderers(const QList &availableRenderers) { // highlight current renderer in menu foreach (QAction *ac, rendererActions->actions()) { // disable all unavailable renderers in menu if (!availableRenderers.contains(ac->text())) { ac->setDisabled(true); } if (ac->text() == currentGLRendererName) { ac->setChecked(true); } } QString surfaceRendererName = ConvexMapRenderer::ID; surfaceRenderer.reset(MolecularSurfaceRendererRegistry::createMSRenderer(surfaceRendererName)); } bool BioStruct3DGLWidget::isSyncModeOn() { Qt::KeyboardModifiers km = QApplication::keyboardModifiers(); bool synchronizationMode = km.testFlag(Qt::ShiftModifier) || frameManager->getSyncLock(); synchronizationMode &= frameManager->getGLFrames().count() > 1 ; return synchronizationMode; } void BioStruct3DGLWidget::setUnselectedShadingLevel(int shading) { foreach (const BioStruct3DRendererContext &ctx, contexts) { ctx.colorScheme->setUnselectedShadingLevel((double)shading/100.0); } updateAllColorSchemes(); } QMenu* BioStruct3DGLWidget::getDisplayMenu() { assert(displayMenu != NULL); return displayMenu; } void BioStruct3DGLWidget::mousePressEvent(QMouseEvent *event) { lastPos = getTrackballMapping(event->x(), event->y()); } void BioStruct3DGLWidget::mouseMoveEvent(QMouseEvent *event) { if (event->buttons() & Qt::LeftButton) { Vector3D curPos = getTrackballMapping(event->x(), event->y()); Vector3D delta = curPos - lastPos; if (delta.x || delta.y || delta.z) { rotAngle = 90.0f*delta.length(); rotAxis = vector_cross(lastPos,curPos); bool syncLock = isSyncModeOn(); QList frames = frameManager->getActiveGLFrameList(glFrame.get(), syncLock); foreach( GLFrame* frame, frames) { frame->makeCurrent(); if (event->modifiers() & Qt::CTRL) frame->performShift(delta.x, delta.y); else frame->rotateCamera(rotAxis, rotAngle); frame->updateGL(); } } lastPos = curPos; } } void BioStruct3DGLWidget::wheelEvent ( QWheelEvent * event ) { float numDegrees = event->delta() / 8; zoom(numDegrees / 10); } void BioStruct3DGLWidget::createActions() { QAction* action = NULL; animationTimer = new QTimer(this); animationTimer->setInterval(20); // fixed interval connect(animationTimer, SIGNAL(timeout()), this, SLOT(sl_updateAnnimation())); rendererActions = new QActionGroup(this); connect(rendererActions, SIGNAL(triggered(QAction *)), this, SLOT(sl_selectGLRenderer(QAction *))); foreach(const QString &key, BioStruct3DGLRendererRegistry::factoriesNames()) { action = new QAction(key, rendererActions); action->setCheckable(true); } colorSchemeActions = new QActionGroup(this); connect(colorSchemeActions, SIGNAL(triggered(QAction *)), this, SLOT(sl_selectColorScheme(QAction *))); foreach(const QString &key, BioStruct3DColorSchemeRegistry::factoriesNames()) { action = new QAction(key, colorSchemeActions); action->setCheckable(true); } molSurfaceRenderActions = new QActionGroup(this); connect(molSurfaceRenderActions, SIGNAL(triggered(QAction *)), this, SLOT(sl_selectSurfaceRenderer(QAction*))); foreach(const QString &key, MolecularSurfaceRendererRegistry::factoriesNames()) { action = new QAction(key, molSurfaceRenderActions); action->setCheckable(true); if (key == ConvexMapRenderer::ID) { action->setChecked(true); } } molSurfaceTypeActions = new QActionGroup(this); foreach(QString key, AppContext::getMolecularSurfaceFactoryRegistry()->getSurfNameList()) { action = new QAction(key, molSurfaceTypeActions); connect(action, SIGNAL(triggered()), this, SLOT(sl_showSurface())); action->setCheckable(true); bool hasConstraints = AppContext::getMolecularSurfaceFactoryRegistry()->getSurfaceFactory(key)->hasConstraints(*contexts.first().biostruct); action->setEnabled(!hasConstraints); } action = new QAction(tr("Off"), molSurfaceTypeActions); connect(action, SIGNAL(triggered()), this, SLOT(sl_hideSurface())); action->setCheckable(true); action->setChecked(true); selectModelsAction = 0; if (!contexts.isEmpty() && contexts.first().biostruct->getModelsNames().size() > 1) { selectModelsAction = new QAction(tr("Models.."), this); connect(selectModelsAction, SIGNAL(triggered()), this, SLOT(sl_selectModels())); } spinAction = new QAction(tr("Spin"), this); spinAction->setCheckable(true); connect(spinAction, SIGNAL(triggered()), this, SLOT(sl_acitvateSpin())); settingsAction = new QAction(tr("Settings..."), this); connect(settingsAction, SIGNAL(triggered()), this, SLOT(sl_settings())); closeAction = new QAction(tr("Close"), this); connect(closeAction, SIGNAL(triggered()), this, SLOT(close())); exportImageAction = new QAction(tr("Export Image..."), this); connect(exportImageAction, SIGNAL(triggered()), this, SLOT(sl_exportImage())); createStrucluralAlignmentActions(); connect(AppContext::getTaskScheduler(), SIGNAL(si_stateChanged(Task*)), SLOT(sl_onTaskFinished(Task*))); } void BioStruct3DGLWidget::createStrucluralAlignmentActions() { alignWithAction = new QAction(tr("Align With..."), this); connect(alignWithAction, SIGNAL(triggered()), this, SLOT(sl_alignWith())); resetAlignmentAction = new QAction(tr("Reset"), this); connect(resetAlignmentAction, SIGNAL(triggered()), this, SLOT(sl_resetAlignment())); } void BioStruct3DGLWidget::createMenus() { // Renderer selection selectRendererMenu = new QMenu(tr("Render Style")); selectRendererMenu->addActions(rendererActions->actions()); // Color scheme selection selectColorSchemeMenu = new QMenu(tr("Coloring Scheme")); selectColorSchemeMenu->addActions(colorSchemeActions->actions()); // Molecular surface QMenu* surfaceMenu = new QMenu(tr("Molecular Surface Render Style")); surfaceMenu->addActions(molSurfaceRenderActions->actions()); QMenu *surfaceTypeMenu = new QMenu(tr("Molecular Surface")); surfaceTypeMenu->addActions(molSurfaceTypeActions->actions()); // Display (context) menu displayMenu = new QMenu(this); displayMenu->addMenu(selectRendererMenu); displayMenu->addMenu(selectColorSchemeMenu); displayMenu->addMenu(surfaceMenu); displayMenu->addMenu(surfaceTypeMenu); if (selectModelsAction) { displayMenu->addAction(selectModelsAction); } displayMenu->addAction(spinAction); displayMenu->addAction(settingsAction); displayMenu->addAction(exportImageAction); QMenu *saMenu = createStructuralAlignmentMenu(); displayMenu->addMenu(saMenu); } QMenu* BioStruct3DGLWidget::createStructuralAlignmentMenu() { QMenu *saMenu = new QMenu(tr("Structural Alignment")); saMenu->addAction(alignWithAction); saMenu->addAction(resetAlignmentAction); return saMenu; } void BioStruct3DGLWidget::connectExternalSignals() { AnnotationSettingsRegistry* asr = AppContext::getAnnotationsSettingsRegistry(); connect(asr, SIGNAL(si_annotationSettingsChanged(const QStringList& )), this, SLOT(sl_updateRenderSettings(const QStringList& )) ); const QList seqContexts = dnaView->getSequenceContexts(); foreach (ADVSequenceObjectContext* ctx, seqContexts) { connect(ctx->getSequenceSelection(), SIGNAL(si_selectionChanged(LRegionsSelection*, const QVector&, const QVector&)), SLOT(sl_onSequenceSelectionChanged(LRegionsSelection*, const QVector& , const QVector&))); } connect(dnaView, SIGNAL(si_sequenceAdded(ADVSequenceObjectContext*)), SLOT(sl_onSequenceAddedToADV(ADVSequenceObjectContext*))); connect(dnaView, SIGNAL(si_sequenceRemoved(ADVSequenceObjectContext*)), SLOT(sl_onSequenceRemovedFromADV(ADVSequenceObjectContext*))); } void BioStruct3DGLWidget::sl_onSequenceAddedToADV(ADVSequenceObjectContext *ctx) { connect(ctx->getSequenceSelection(), SIGNAL(si_selectionChanged(LRegionsSelection*, const QVector&, const QVector&)), SLOT(sl_onSequenceSelectionChanged(LRegionsSelection*, const QVector& , const QVector&))); } void BioStruct3DGLWidget::sl_onSequenceRemovedFromADV(ADVSequenceObjectContext *ctx) { disconnect(ctx->getSequenceSelection(), SIGNAL(si_selectionChanged(LRegionsSelection*, const QVector&, const QVector&)), this, SLOT(sl_onSequenceSelectionChanged(LRegionsSelection*, const QVector& , const QVector&))); } void BioStruct3DGLWidget::sl_selectColorScheme(QAction* action) { QString schemeName = action->text(); currentColorSchemeName = schemeName; setupColorScheme(schemeName); GLFrame* frame = frameManager->getGLWidgetFrame(this); frame->makeCurrent(); frame->updateGL(); } void BioStruct3DGLWidget::sl_updateRenderSettings(const QStringList& list ) { Q_UNUSED(list); sl_selectColorScheme(colorSchemeActions->checkedAction()); } void BioStruct3DGLWidget::sl_acitvateSpin() { if (spinAction->isChecked()) { animationTimer->start(); } else { animationTimer->stop(); } updateGL(); } void BioStruct3DGLWidget::sl_updateAnnimation() { static float velocity = 0.05f; spinAngle = velocity* animationTimer->interval(); Vector3D rotAxis(0,1,0); bool syncLock = isSyncModeOn(); QList frames = frameManager->getActiveGLFrameList(glFrame.get(), syncLock); foreach( GLFrame* frame, frames) { frame->makeCurrent(); frame->rotateCamera(rotAxis, spinAngle); frame->updateGL(); } updateGL(); } void BioStruct3DGLWidget::sl_selectGLRenderer(QAction* action) { QString rendererName = action->text(); currentGLRendererName = rendererName; setupRenderer(currentGLRendererName); GLFrame* frame = frameManager->getGLWidgetFrame(this); frame->makeCurrent(); frame->updateGL(); } void BioStruct3DGLWidget::sl_settings() { BioStruct3DSettingsDialog dialog; dialog.setWidget(this); dialog.setBackgroundColor(backgroundColor); dialog.setSelectionColor(selectionColor); dialog.setRenderDetailLevel(rendererSettings.detailLevel); dialog.setShadingLevel(unselectedShadingLevel); dialog.setAnaglyphStatus(anaglyphStatus); dialog.setAnaglyphSettings(anaglyph->getSettings()); QVariantMap previousState = getState(); if (QDialog::Accepted == dialog.exec()) { backgroundColor = dialog.getBackgroundColor(); selectionColor = dialog.getSelectionColor(); unselectedShadingLevel = dialog.getShadingLevel(); foreach (const BioStruct3DRendererContext &ctx, contexts) { ctx.colorScheme->setSelectionColor(selectionColor); } setUnselectedShadingLevel(unselectedShadingLevel); rendererSettings.detailLevel = dialog.getRenderDetailLevel(); anaglyphStatus = dialog.getAnaglyphStatus(); anaglyph->setSettings(dialog.getAnaglyphSettings()); this->makeCurrent(); setBackgroundColor(backgroundColor); updateGL(); } else { setState(previousState); } } void BioStruct3DGLWidget::sl_exportImage() { ExportImage3DGLDialog dialog(this); dialog.exec(); } void BioStruct3DGLWidget::sl_showSurface() { QList atoms; int index = contexts.first().renderer->getShownModelsIndexes().first(); foreach (const SharedMolecule &mol, contexts.first().biostruct->moleculeMap) { const Molecule3DModel& model = mol->models.at(index); atoms += model.atoms; } QString surfaceType = qobject_cast( sender() )->text(); surfaceCalcTask = new MolecularSurfaceCalcTask(surfaceType, atoms); AppContext::getTaskScheduler()->registerTopLevelTask(surfaceCalcTask); } void BioStruct3DGLWidget::sl_hideSurface() { molSurface.reset(); makeCurrent(); updateGL(); } void BioStruct3DGLWidget::sl_selectSurfaceRenderer(QAction* action) { QString msRendererName = action->text(); surfaceRenderer.reset(MolecularSurfaceRendererRegistry::createMSRenderer(msRendererName)); makeCurrent(); updateGL(); } void BioStruct3DGLWidget::sl_onTaskFinished( Task* task ) { if ( surfaceCalcTask != task || surfaceCalcTask->getState()!= Task::State_Finished) { return; } molSurface.reset(); molSurface = surfaceCalcTask->getCalculatedSurface(); makeCurrent(); updateGL(); } /** Convert modelId's list to modelIndexes list */ static QList modelIdsToModelIdx(const BioStruct3D &bs, const QList &modelsIds) { QList modelsIdx; foreach (int modelId, modelsIds) { int idx = bs.getModelsNames().indexOf(modelId); assert(idx != -1 && "No such modelId in biostruct"); modelsIdx << idx; } return modelsIdx; } void BioStruct3DGLWidget::addBiostruct(const BioStruct3DObject *obj, const QList &shownModels /*= QList()*/) { assert(contexts.size() < 2 && "Multiple models in one view is unsupported now"); BioStruct3DRendererContext ctx(obj); QList shownModelsIdx = modelIdsToModelIdx(*ctx.biostruct, shownModels); // show only first model if model list is empty if (shownModelsIdx.isEmpty()) { shownModelsIdx << 0; } BioStruct3DColorScheme *colorScheme = BioStruct3DColorSchemeRegistry::createColorScheme(currentColorSchemeName, ctx.obj); assert(colorScheme); ctx.colorScheme = QSharedPointer(colorScheme); ctx.colorScheme->setSelectionColor(selectionColor); ctx.colorScheme->setUnselectedShadingLevel((double)unselectedShadingLevel/100.0); BioStruct3DGLRenderer *renderer = BioStruct3DGLRendererRegistry::createRenderer(currentGLRendererName, *ctx.biostruct, ctx.colorScheme.data(), shownModelsIdx, &rendererSettings); assert(renderer); ctx.renderer = QSharedPointer(renderer); contexts.append(ctx); setupFrame(); } void BioStruct3DGLWidget::sl_alignWith() { const BioStruct3DRendererContext &ctx = contexts.first(); int currentModelId = ctx.biostruct->getModelsNames().at(ctx.renderer->getShownModelsIndexes().first()); StructuralAlignmentDialog dlg(contexts.first().obj, currentModelId); if (dlg.execIfAlgorithmAvailable() == QDialog::Accepted) { sl_resetAlignment(); Task *task = dlg.getTask(); assert(task && "If dialog accepded it must return valid task"); TaskSignalMapper *taskMapper = new TaskSignalMapper(task); connect(taskMapper, SIGNAL(si_taskFinished(Task*)), this, SLOT(sl_onAlignmentDone(Task*))); AppContext::getTaskScheduler()->registerTopLevelTask(task); } } void BioStruct3DGLWidget::sl_resetAlignment() { assert(contexts.size() < 3 && "Multiple models in one view is unsupported now"); if (contexts.size() == 2) { contexts.removeLast(); setupFrame(); glFrame->makeCurrent(); update(); } } void BioStruct3DGLWidget::sl_onAlignmentDone(Task *task) { if (!task->hasError()) { StructuralAlignmentTask *saTask = qobject_cast (task); assert(saTask && "Task shoud have type StructuralAlignmentTask"); StructuralAlignment result = saTask->getResult(); StructuralAlignmentTaskSettings settings = saTask->getSettings(); const Matrix44 &mt = result.transform; const_cast(&settings.alt.obj->getBioStruct3D())->setTransform(mt); addBiostruct(settings.alt.obj, QList() << settings.alt.modelId); glFrame->makeCurrent(); update(); } } } // namespace U2 ugene-1.9.8/src/plugins/biostruct3d_view/src/gl2ps/0000755000175000017500000000000011651544321020701 5ustar ilyailyaugene-1.9.8/src/plugins/biostruct3d_view/src/gl2ps/gl2ps.h0000644000175000017500000001460111651544321022103 0ustar ilyailya/* $Id: gl2ps.h,v 1.113 2006/11/06 00:48:06 geuzaine Exp $ */ /* * GL2PS, an OpenGL to PostScript Printing Library * Copyright (C) 1999-2006 Christophe Geuzaine * * This program is free software; you can redistribute it and/or * modify it under the terms of either: * * a) the GNU Library General Public License as published by the Free * Software Foundation, either version 2 of the License, or (at your * option) any later version; or * * b) the GL2PS License as published by Christophe Geuzaine, either * version 2 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See either * the GNU Library General Public License or the GL2PS License for * more details. * * You should have received a copy of the GNU Library General Public * License along with this library in the file named "COPYING.LGPL"; * if not, write to the Free Software Foundation, Inc., 675 Mass Ave, * Cambridge, MA 02139, USA. * * You should have received a copy of the GL2PS License with this * library in the file named "COPYING.GL2PS"; if not, I will be glad * to provide one. * * For the latest info about gl2ps, see http://www.geuz.org/gl2ps/. * Please report all bugs and problems to . */ #ifndef __GL2PS_H__ #define __GL2PS_H__ #include #include /* Define GL2PSDLL at compile time to build a Windows DLL */ #if defined(WIN32) || defined(_WIN32) || defined(__WIN32__) || defined(__NT__) # if defined(_MSC_VER) # pragma warning(disable:4115) # endif # include # if defined(GL2PSDLL) # if defined(GL2PSDLL_EXPORTS) # define GL2PSDLL_API __declspec(dllexport) # else # define GL2PSDLL_API __declspec(dllimport) # endif # else # define GL2PSDLL_API # endif #else # define GL2PSDLL_API #endif #if defined(__APPLE__) || defined(HAVE_OPENGL_GL_H) # include #else # include #endif /* Support for compressed PostScript/PDF/SVG and for embedded PNG images in SVG */ #if defined(HAVE_ZLIB) || defined(HAVE_LIBZ) # define GL2PS_HAVE_ZLIB # if defined(HAVE_LIBPNG) || defined(HAVE_PNG) # define GL2PS_HAVE_LIBPNG # endif #endif /* Version number */ #define GL2PS_MAJOR_VERSION 1 #define GL2PS_MINOR_VERSION 3 #define GL2PS_PATCH_VERSION 2 #define GL2PS_EXTRA_VERSION "" #define GL2PS_VERSION (GL2PS_MAJOR_VERSION + \ 0.01 * GL2PS_MINOR_VERSION + \ 0.0001 * GL2PS_PATCH_VERSION) #define GL2PS_COPYRIGHT "(C) 1999-2006 Christophe Geuzaine (geuz@geuz.org)" /* Output file formats (the values and the ordering are important!) */ #define GL2PS_PS 0 #define GL2PS_EPS 1 #define GL2PS_TEX 2 #define GL2PS_PDF 3 #define GL2PS_SVG 4 #define GL2PS_PGF 5 /* Sorting algorithms */ #define GL2PS_NO_SORT 1 #define GL2PS_SIMPLE_SORT 2 #define GL2PS_BSP_SORT 3 /* Message levels and error codes */ #define GL2PS_SUCCESS 0 #define GL2PS_INFO 1 #define GL2PS_WARNING 2 #define GL2PS_ERROR 3 #define GL2PS_NO_FEEDBACK 4 #define GL2PS_OVERFLOW 5 #define GL2PS_UNINITIALIZED 6 /* Options for gl2psBeginPage */ #define GL2PS_NONE 0 #define GL2PS_DRAW_BACKGROUND (1<<0) #define GL2PS_SIMPLE_LINE_OFFSET (1<<1) #define GL2PS_SILENT (1<<2) #define GL2PS_BEST_ROOT (1<<3) #define GL2PS_OCCLUSION_CULL (1<<4) #define GL2PS_NO_TEXT (1<<5) #define GL2PS_LANDSCAPE (1<<6) #define GL2PS_NO_PS3_SHADING (1<<7) #define GL2PS_NO_PIXMAP (1<<8) #define GL2PS_USE_CURRENT_VIEWPORT (1<<9) #define GL2PS_COMPRESS (1<<10) #define GL2PS_NO_BLENDING (1<<11) #define GL2PS_TIGHT_BOUNDING_BOX (1<<12) /* Arguments for gl2psEnable/gl2psDisable */ #define GL2PS_POLYGON_OFFSET_FILL 1 #define GL2PS_POLYGON_BOUNDARY 2 #define GL2PS_LINE_STIPPLE 3 #define GL2PS_BLEND 4 /* Text alignment (o=raster position; default mode is BL): +---+ +---+ +---+ +---+ +---+ +---+ +-o-+ o---+ +---o | o | o | | o | | | | | | | | | | | | +---+ +---+ +---+ +-o-+ o---+ +---o +---+ +---+ +---+ C CL CR B BL BR T TL TR */ #define GL2PS_TEXT_C 1 #define GL2PS_TEXT_CL 2 #define GL2PS_TEXT_CR 3 #define GL2PS_TEXT_B 4 #define GL2PS_TEXT_BL 5 #define GL2PS_TEXT_BR 6 #define GL2PS_TEXT_T 7 #define GL2PS_TEXT_TL 8 #define GL2PS_TEXT_TR 9 typedef GLfloat GL2PSrgba[4]; #if defined(__cplusplus) extern "C" { #endif GL2PSDLL_API GLint gl2psBeginPage(const char *title, const char *producer, GLint viewport[4], GLint format, GLint sort, GLint options, GLint colormode, GLint colorsize, GL2PSrgba *colormap, GLint nr, GLint ng, GLint nb, GLint buffersize, FILE *stream, const char *filename); GL2PSDLL_API GLint gl2psEndPage(void); GL2PSDLL_API GLint gl2psSetOptions(GLint options); GL2PSDLL_API GLint gl2psBeginViewport(GLint viewport[4]); GL2PSDLL_API GLint gl2psEndViewport(void); GL2PSDLL_API GLint gl2psText(const char *str, const char *fontname, GLshort fontsize); GL2PSDLL_API GLint gl2psTextOpt(const char *str, const char *fontname, GLshort fontsize, GLint align, GLfloat angle); GL2PSDLL_API GLint gl2psSpecial(GLint format, const char *str); GL2PSDLL_API GLint gl2psDrawPixels(GLsizei width, GLsizei height, GLint xorig, GLint yorig, GLenum format, GLenum type, const void *pixels); GL2PSDLL_API GLint gl2psEnable(GLint mode); GL2PSDLL_API GLint gl2psDisable(GLint mode); GL2PSDLL_API GLint gl2psPointSize(GLfloat value); GL2PSDLL_API GLint gl2psLineWidth(GLfloat value); GL2PSDLL_API GLint gl2psBlendFunc(GLenum sfactor, GLenum dfactor); /* undocumented */ GL2PSDLL_API GLint gl2psDrawImageMap(GLsizei width, GLsizei height, const GLfloat position[3], const unsigned char *imagemap); GL2PSDLL_API const char *gl2psGetFileExtension(GLint format); GL2PSDLL_API const char *gl2psGetFormatDescription(GLint format); #if defined(__cplusplus) } #endif #endif /* __GL2PS_H__ */ ugene-1.9.8/src/plugins/biostruct3d_view/src/gl2ps/gl2ps.cpp0000644000175000017500000054247711651544321022457 0ustar ilyailya/* $Id: gl2ps.c,v 1.243 2006/11/06 00:53:53 geuzaine Exp $ */ /* * GL2PS, an OpenGL to PostScript Printing Library * Copyright (C) 1999-2006 Christophe Geuzaine * * This program is free software; you can redistribute it and/or * modify it under the terms of either: * * a) the GNU Library General Public License as published by the Free * Software Foundation, either version 2 of the License, or (at your * option) any later version; or * * b) the GL2PS License as published by Christophe Geuzaine, either * version 2 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See either * the GNU Library General Public License or the GL2PS License for * more details. * * You should have received a copy of the GNU Library General Public * License along with this library in the file named "COPYING.LGPL"; * if not, write to the Free Software Foundation, Inc., 675 Mass Ave, * Cambridge, MA 02139, USA. * * You should have received a copy of the GL2PS License with this * library in the file named "COPYING.GL2PS"; if not, I will be glad * to provide one. * * Contributors: * Michael Sweet * Marc Ume * Jean-Francois Remacle * Bart Kaptein * Quy Nguyen-Dai * Sam Buss * Shane Hill * Romain Boman * Rouben Rostamian * Diego Santa Cruz * Shahzad Muzaffar * Lassi Tuura * Guy Barrand * Prabhu Ramachandran * Micha Bieber * Olivier Couet * Shai Ayal * Fabian Wenzel * Ian D. Gay * Cosmin Truta * Baiju Devani * Alexander Danilov * * For the latest info about gl2ps, see http://www.geuz.org/gl2ps/. * Please report all bugs and problems to . */ #include "gl2ps.h" #include #include #include #include #include #include #include //disable "unsafe functions" deprecation warnings on MS VS #ifdef Q_OS_WIN #pragma warning(disable: 4996) #endif #if defined(GL2PS_HAVE_ZLIB) #include #endif #if defined(GL2PS_HAVE_LIBPNG) #include #endif /********************************************************************* * * Private definitions, data structures and prototypes * *********************************************************************/ /* Magic numbers (assuming that the order of magnitude of window coordinates is 10^3) */ #define GL2PS_EPSILON 5.0e-3F #define GL2PS_ZSCALE 1000.0F #define GL2PS_ZOFFSET 5.0e-2F #define GL2PS_ZOFFSET_LARGE 20.0F #define GL2PS_ZERO(arg) (fabs(arg) < 1.e-20) /* Primitive types */ #define GL2PS_NO_TYPE -1 #define GL2PS_TEXT 1 #define GL2PS_POINT 2 #define GL2PS_LINE 3 #define GL2PS_QUADRANGLE 4 #define GL2PS_TRIANGLE 5 #define GL2PS_PIXMAP 6 #define GL2PS_IMAGEMAP 7 #define GL2PS_IMAGEMAP_WRITTEN 8 #define GL2PS_IMAGEMAP_VISIBLE 9 #define GL2PS_SPECIAL 10 /* BSP tree primitive comparison */ #define GL2PS_COINCIDENT 1 #define GL2PS_IN_FRONT_OF 2 #define GL2PS_IN_BACK_OF 3 #define GL2PS_SPANNING 4 /* 2D BSP tree primitive comparison */ #define GL2PS_POINT_COINCIDENT 0 #define GL2PS_POINT_INFRONT 1 #define GL2PS_POINT_BACK 2 /* Internal feedback buffer pass-through tokens */ #define GL2PS_BEGIN_OFFSET_TOKEN 1 #define GL2PS_END_OFFSET_TOKEN 2 #define GL2PS_BEGIN_BOUNDARY_TOKEN 3 #define GL2PS_END_BOUNDARY_TOKEN 4 #define GL2PS_BEGIN_STIPPLE_TOKEN 5 #define GL2PS_END_STIPPLE_TOKEN 6 #define GL2PS_POINT_SIZE_TOKEN 7 #define GL2PS_LINE_WIDTH_TOKEN 8 #define GL2PS_BEGIN_BLEND_TOKEN 9 #define GL2PS_END_BLEND_TOKEN 10 #define GL2PS_SRC_BLEND_TOKEN 11 #define GL2PS_DST_BLEND_TOKEN 12 #define GL2PS_IMAGEMAP_TOKEN 13 #define GL2PS_DRAW_PIXELS_TOKEN 14 #define GL2PS_TEXT_TOKEN 15 typedef enum { T_UNDEFINED = -1, T_CONST_COLOR = 1, T_VAR_COLOR = 1<<1, T_ALPHA_1 = 1<<2, T_ALPHA_LESS_1 = 1<<3, T_VAR_ALPHA = 1<<4 } GL2PS_TRIANGLE_PROPERTY; typedef GLfloat GL2PSxyz[3]; typedef GLfloat GL2PSplane[4]; typedef struct _GL2PSbsptree2d GL2PSbsptree2d; struct _GL2PSbsptree2d { GL2PSplane plane; GL2PSbsptree2d *front, *back; }; typedef struct { GLint nmax, size, incr, n; char *array; } GL2PSlist; typedef struct _GL2PSbsptree GL2PSbsptree; struct _GL2PSbsptree { GL2PSplane plane; GL2PSlist *primitives; GL2PSbsptree *front, *back; }; typedef struct { GL2PSxyz xyz; GL2PSrgba rgba; } GL2PSvertex; typedef struct { GL2PSvertex vertex[3]; int prop; } GL2PStriangle; typedef struct { GLshort fontsize; char *str, *fontname; /* Note: for a 'special' string, 'alignment' holds the format (PostScript, PDF, etc.) of the special string */ GLint alignment; GLfloat angle; } GL2PSstring; typedef struct { GLsizei width, height; /* Note: for an imagemap, 'type' indicates if it has already been written to the file or not, and 'format' indicates if it is visible or not */ GLenum format, type; GLfloat *pixels; } GL2PSimage; typedef struct _GL2PSimagemap GL2PSimagemap; struct _GL2PSimagemap { GL2PSimage *image; GL2PSimagemap *next; }; typedef struct { GLshort type, numverts; GLushort pattern; char boundary, offset, culled; GLint factor; GLfloat width; GL2PSvertex *verts; union { GL2PSstring *text; GL2PSimage *image; } data; } GL2PSprimitive; typedef struct { #if defined(GL2PS_HAVE_ZLIB) Bytef *dest, *src, *start; uLongf destLen, srcLen; #else int dummy; #endif } GL2PScompress; typedef struct{ GL2PSlist* ptrlist; int gsno, fontno, imno, shno, maskshno, trgroupno; int gsobjno, fontobjno, imobjno, shobjno, maskshobjno, trgroupobjno; } GL2PSpdfgroup; typedef struct { /* General */ GLint format, sort, options, colorsize, colormode, buffersize; char *title, *producer, *filename; GLboolean boundary, blending; GLfloat *feedback, offset[2], lastlinewidth; GLint viewport[4], blendfunc[2], lastfactor; GL2PSrgba *colormap, lastrgba, threshold, bgcolor; GLushort lastpattern; GL2PSvertex lastvertex; GL2PSlist *primitives, *auxprimitives; FILE *stream; GL2PScompress *compress; GLboolean header; /* BSP-specific */ GLint maxbestroot; /* Occlusion culling-specific */ GLboolean zerosurfacearea; GL2PSbsptree2d *imagetree; GL2PSprimitive *primitivetoadd; /* PDF-specific */ int streamlength; GL2PSlist *pdfprimlist, *pdfgrouplist; int *xreflist; int objects_stack; /* available objects */ int extgs_stack; /* graphics state object number */ int font_stack; /* font object number */ int im_stack; /* image object number */ int trgroupobjects_stack; /* xobject numbers */ int shader_stack; /* shader object numbers */ int mshader_stack; /* mask shader object numbers */ /* for image map list */ GL2PSimagemap *imagemap_head; GL2PSimagemap *imagemap_tail; } GL2PScontext; typedef struct { void (*printHeader)(void); void (*printFooter)(void); void (*beginViewport)(GLint viewport[4]); GLint (*endViewport)(void); void (*printPrimitive)(void *data); void (*printFinalPrimitive)(void); const char *file_extension; const char *description; } GL2PSbackend; /* The gl2ps context. gl2ps is not thread safe (we should create a local GL2PScontext during gl2psBeginPage) */ static GL2PScontext *gl2ps = NULL; /* Need to forward-declare this one */ static GLint gl2psPrintPrimitives(void); /********************************************************************* * * Utility routines * *********************************************************************/ static void gl2psMsg(GLint level, const char *fmt, ...) { if(!(gl2ps->options & GL2PS_SILENT)){ va_list args; switch(level){ case GL2PS_INFO : fprintf(stderr, "GL2PS info: "); break; case GL2PS_WARNING : fprintf(stderr, "GL2PS warning: "); break; case GL2PS_ERROR : fprintf(stderr, "GL2PS error: "); break; } va_start(args, fmt); vfprintf(stderr, fmt, args); va_end(args); fprintf(stderr, "\n"); } /* if(level == GL2PS_ERROR) exit(1); */ } static void *gl2psMalloc(size_t size) { void *ptr; if(!size) return(NULL); ptr = malloc(size); if(!ptr){ gl2psMsg(GL2PS_ERROR, "Couldn't allocate requested memory"); exit(1); } return(ptr); } static void *gl2psRealloc(void *ptr, size_t size) { if(!size) return(NULL); ptr = realloc(ptr, size); if(!ptr){ gl2psMsg(GL2PS_ERROR, "Couldn't reallocate requested memory"); exit(1); } return(ptr); } static void gl2psFree(void *ptr) { if(!ptr) return; free(ptr); } static size_t gl2psWriteBigEndian(unsigned long data, size_t bytes) { size_t i; size_t size = sizeof(unsigned long); for(i = 1; i <= bytes; ++i){ fputc(0xff & (data >> (size-i) * 8), gl2ps->stream); } return bytes; } /* zlib compression helper routines */ #if defined(GL2PS_HAVE_ZLIB) static void gl2psSetupCompress(void) { gl2ps->compress = (GL2PScompress*)gl2psMalloc(sizeof(GL2PScompress)); gl2ps->compress->src = NULL; gl2ps->compress->start = NULL; gl2ps->compress->dest = NULL; gl2ps->compress->srcLen = 0; gl2ps->compress->destLen = 0; } static void gl2psFreeCompress(void) { if(!gl2ps->compress) return; gl2psFree(gl2ps->compress->start); gl2psFree(gl2ps->compress->dest); gl2ps->compress->src = NULL; gl2ps->compress->start = NULL; gl2ps->compress->dest = NULL; gl2ps->compress->srcLen = 0; gl2ps->compress->destLen = 0; } static int gl2psAllocCompress(unsigned int srcsize) { gl2psFreeCompress(); if(!gl2ps->compress || !srcsize) return GL2PS_ERROR; gl2ps->compress->srcLen = srcsize; gl2ps->compress->destLen = (int)ceil(1.001 * gl2ps->compress->srcLen + 12); gl2ps->compress->src = (Bytef*)gl2psMalloc(gl2ps->compress->srcLen); gl2ps->compress->start = gl2ps->compress->src; gl2ps->compress->dest = (Bytef*)gl2psMalloc(gl2ps->compress->destLen); return GL2PS_SUCCESS; } static void *gl2psReallocCompress(unsigned int srcsize) { if(!gl2ps->compress || !srcsize) return NULL; if(srcsize < gl2ps->compress->srcLen) return gl2ps->compress->start; gl2ps->compress->srcLen = srcsize; gl2ps->compress->destLen = (int)ceil(1.001 * gl2ps->compress->srcLen + 12); gl2ps->compress->src = (Bytef*)gl2psRealloc(gl2ps->compress->src, gl2ps->compress->srcLen); gl2ps->compress->start = gl2ps->compress->src; gl2ps->compress->dest = (Bytef*)gl2psRealloc(gl2ps->compress->dest, gl2ps->compress->destLen); return gl2ps->compress->start; } static size_t gl2psWriteBigEndianCompress(unsigned long data, size_t bytes) { size_t i; size_t size = sizeof(unsigned long); for(i = 1; i <= bytes; ++i){ *gl2ps->compress->src = (Bytef)(0xff & (data >> (size-i) * 8)); ++gl2ps->compress->src; } return bytes; } static int gl2psDeflate(void) { /* For compatibility with older zlib versions, we use compress(...) instead of compress2(..., Z_BEST_COMPRESSION) */ return compress(gl2ps->compress->dest, &gl2ps->compress->destLen, gl2ps->compress->start, gl2ps->compress->srcLen); } #endif static int gl2psPrintf(const char* fmt, ...) { int ret; va_list args; #if defined(GL2PS_HAVE_ZLIB) unsigned int oldsize = 0; static char buf[1000]; if(gl2ps->options & GL2PS_COMPRESS){ va_start(args, fmt); ret = vsprintf(buf, fmt, args); va_end(args); oldsize = gl2ps->compress->srcLen; gl2ps->compress->start = (Bytef*)gl2psReallocCompress(oldsize + ret); memcpy(gl2ps->compress->start+oldsize, buf, ret); ret = 0; } else{ #endif va_start(args, fmt); ret = vfprintf(gl2ps->stream, fmt, args); va_end(args); #if defined(GL2PS_HAVE_ZLIB) } #endif return ret; } static void gl2psPrintGzipHeader() { #if defined(GL2PS_HAVE_ZLIB) char tmp[10] = {'\x1f', '\x8b', /* magic numbers: 0x1f, 0x8b */ 8, /* compression method: Z_DEFLATED */ 0, /* flags */ 0, 0, 0, 0, /* time */ 2, /* extra flags: max compression */ '\x03'}; /* OS code: 0x03 (Unix) */ if(gl2ps->options & GL2PS_COMPRESS){ gl2psSetupCompress(); /* add the gzip file header */ fwrite(tmp, 10, 1, gl2ps->stream); } #endif } static void gl2psPrintGzipFooter() { #if defined(GL2PS_HAVE_ZLIB) if(gl2ps->options & GL2PS_COMPRESS){ char tmp[8]; if(Z_OK != gl2psDeflate()){ gl2psMsg(GL2PS_ERROR, "Zlib deflate error"); } else{ /* determine the length of the header in the zlib stream */ int n = 2; /* CMF+FLG */ if(gl2ps->compress->dest[1] & (1<<5)){ n += 4; /* DICTID */ } /* write the data, without the zlib header and footer */ fwrite(gl2ps->compress->dest+n, gl2ps->compress->destLen-(n+4), 1, gl2ps->stream); /* add the gzip file footer */ uLong crc = crc32(0L, gl2ps->compress->start, gl2ps->compress->srcLen); for(n = 0; n < 4; ++n){ tmp[n] = (char)(crc & 0xff); crc >>= 8; } uLong len = gl2ps->compress->srcLen; for(n = 4; n < 8; ++n){ tmp[n] = (char)(len & 0xff); len >>= 8; } fwrite(tmp, 8, 1, gl2ps->stream); } gl2psFreeCompress(); gl2psFree(gl2ps->compress); gl2ps->compress = NULL; } #endif } /* The list handling routines */ static void gl2psListRealloc(GL2PSlist *list, GLint n) { if(!list){ gl2psMsg(GL2PS_ERROR, "Cannot reallocate NULL list"); return; } if(n <= 0) return; if(!list->array){ list->nmax = n; list->array = (char*)gl2psMalloc(list->nmax * list->size); } else{ if(n > list->nmax){ list->nmax = ((n - 1) / list->incr + 1) * list->incr; list->array = (char*)gl2psRealloc(list->array, list->nmax * list->size); } } } static GL2PSlist *gl2psListCreate(GLint n, GLint incr, GLint size) { GL2PSlist *list; if(n < 0) n = 0; if(incr <= 0) incr = 1; list = (GL2PSlist*)gl2psMalloc(sizeof(GL2PSlist)); list->nmax = 0; list->incr = incr; list->size = size; list->n = 0; list->array = NULL; gl2psListRealloc(list, n); return(list); } static void gl2psListReset(GL2PSlist *list) { if(!list) return; list->n = 0; } static void gl2psListDelete(GL2PSlist *list) { if(!list) return; gl2psFree(list->array); gl2psFree(list); } static void gl2psListAdd(GL2PSlist *list, void *data) { if(!list){ gl2psMsg(GL2PS_ERROR, "Cannot add into unallocated list"); return; } list->n++; gl2psListRealloc(list, list->n); memcpy(&list->array[(list->n - 1) * list->size], data, list->size); } static int gl2psListNbr(GL2PSlist *list) { if(!list) return 0; return(list->n); } static void *gl2psListPointer(GL2PSlist *list, GLint index) { if(!list){ gl2psMsg(GL2PS_ERROR, "Cannot point into unallocated list"); return NULL; } if((index < 0) || (index >= list->n)){ gl2psMsg(GL2PS_ERROR, "Wrong list index in gl2psListPointer"); return NULL; } return(&list->array[index * list->size]); } static void gl2psListSort(GL2PSlist *list, int (*fcmp)(const void *a, const void *b)) { if(!list) return; qsort(list->array, list->n, list->size, fcmp); } static void gl2psListAction(GL2PSlist *list, void (*action)(void *data)) { GLint i; for(i = 0; i < gl2psListNbr(list); i++){ (*action)(gl2psListPointer(list, i)); } } static void gl2psListActionInverse(GL2PSlist *list, void (*action)(void *data)) { GLint i; for(i = gl2psListNbr(list); i > 0; i--){ (*action)(gl2psListPointer(list, i-1)); } } #if defined(GL2PS_HAVE_LIBPNG) static void gl2psListRead(GL2PSlist *list, int index, void *data) { if((index < 0) || (index >= list->n)) gl2psMsg(GL2PS_ERROR, "Wrong list index in gl2psListRead"); memcpy(data, &list->array[index * list->size], list->size); } static void gl2psEncodeBase64Block(unsigned char in[3], unsigned char out[4], int len) { static const char cb64[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; out[0] = cb64[ in[0] >> 2 ]; out[1] = cb64[ ((in[0] & 0x03) << 4) | ((in[1] & 0xf0) >> 4) ]; out[2] = (len > 1) ? cb64[ ((in[1] & 0x0f) << 2) | ((in[2] & 0xc0) >> 6) ] : '='; out[3] = (len > 2) ? cb64[ in[2] & 0x3f ] : '='; } static void gl2psListEncodeBase64(GL2PSlist *list) { unsigned char *buffer, in[3], out[4]; int i, n, index, len; n = list->n * list->size; buffer = (unsigned char*)gl2psMalloc(n * sizeof(unsigned char)); memcpy(buffer, list->array, n * sizeof(unsigned char)); gl2psListReset(list); index = 0; while(index < n) { len = 0; for(i = 0; i < 3; i++) { if(index < n){ in[i] = buffer[index]; len++; } else{ in[i] = 0; } index++; } if(len) { gl2psEncodeBase64Block(in, out, len); for(i = 0; i < 4; i++) gl2psListAdd(list, &out[i]); } } gl2psFree(buffer); } #endif /* Helpers for rgba colors */ static GLboolean gl2psSameColor(GL2PSrgba rgba1, GL2PSrgba rgba2) { if(!GL2PS_ZERO(rgba1[0] - rgba2[0]) || !GL2PS_ZERO(rgba1[1] - rgba2[1]) || !GL2PS_ZERO(rgba1[2] - rgba2[2])) return GL_FALSE; return GL_TRUE; } static GLboolean gl2psVertsSameColor(const GL2PSprimitive *prim) { int i; for(i = 1; i < prim->numverts; i++){ if(!gl2psSameColor(prim->verts[0].rgba, prim->verts[i].rgba)){ return GL_FALSE; } } return GL_TRUE; } static GLboolean gl2psSameColorThreshold(int n, GL2PSrgba rgba[], GL2PSrgba threshold) { int i; if(n < 2) return GL_TRUE; for(i = 1; i < n; i++){ if(fabs(rgba[0][0] - rgba[i][0]) > threshold[0] || fabs(rgba[0][1] - rgba[i][1]) > threshold[1] || fabs(rgba[0][2] - rgba[i][2]) > threshold[2]) return GL_FALSE; } return GL_TRUE; } static void gl2psSetLastColor(GL2PSrgba rgba) { int i; for(i = 0; i < 3; ++i){ gl2ps->lastrgba[i] = rgba[i]; } } static GLfloat gl2psGetRGB(GL2PSimage *im, GLuint x, GLuint y, GLfloat *red, GLfloat *green, GLfloat *blue) { GLsizei width = im->width; GLsizei height = im->height; GLfloat *pixels = im->pixels; GLfloat *pimag; /* OpenGL image is from down to up, PS image is up to down */ switch(im->format){ case GL_RGBA: pimag = pixels + 4 * (width * (height - 1 - y) + x); break; case GL_RGB: default: pimag = pixels + 3 * (width * (height - 1 - y) + x); break; } *red = *pimag; pimag++; *green = *pimag; pimag++; *blue = *pimag; pimag++; return (im->format == GL_RGBA) ? *pimag : 1.0F; } /* Helper routines for pixmaps */ static GL2PSimage *gl2psCopyPixmap(GL2PSimage *im) { int size; GL2PSimage *image = (GL2PSimage*)gl2psMalloc(sizeof(GL2PSimage)); image->width = im->width; image->height = im->height; image->format = im->format; image->type = im->type; switch(image->format){ case GL_RGBA: size = image->height * image->width * 4 * sizeof(GLfloat); break; case GL_RGB: default: size = image->height * image->width * 3 * sizeof(GLfloat); break; } image->pixels = (GLfloat*)gl2psMalloc(size); memcpy(image->pixels, im->pixels, size); return image; } static void gl2psFreePixmap(GL2PSimage *im) { if(!im) return; gl2psFree(im->pixels); gl2psFree(im); } #if defined(GL2PS_HAVE_LIBPNG) #if !defined(png_jmpbuf) # define png_jmpbuf(png_ptr) ((png_ptr)->jmpbuf) #endif static void gl2psUserWritePNG(png_structp png_ptr, png_bytep data, png_size_t length) { unsigned int i; GL2PSlist *png = (GL2PSlist*)png_get_io_ptr(png_ptr); for(i = 0; i < length; i++) gl2psListAdd(png, &data[i]); } static void gl2psUserFlushPNG(png_structp png_ptr) { } static void gl2psConvertPixmapToPNG(GL2PSimage *pixmap, GL2PSlist *png) { png_structp png_ptr; png_infop info_ptr; unsigned char *row_data; GLfloat dr, dg, db; int row, col; if(!(png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL))) return; if(!(info_ptr = png_create_info_struct(png_ptr))){ png_destroy_write_struct(&png_ptr, NULL); return; } if(setjmp(png_jmpbuf(png_ptr))) { png_destroy_write_struct(&png_ptr, &info_ptr); return; } png_set_write_fn(png_ptr, (void *)png, gl2psUserWritePNG, gl2psUserFlushPNG); png_set_compression_level(png_ptr, Z_DEFAULT_COMPRESSION); png_set_IHDR(png_ptr, info_ptr, pixmap->width, pixmap->height, 8, PNG_COLOR_TYPE_RGB, PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE); png_write_info(png_ptr, info_ptr); row_data = (unsigned char*)gl2psMalloc(3 * pixmap->width * sizeof(unsigned char)); for(row = 0; row < pixmap->height; row++){ for(col = 0; col < pixmap->width; col++){ gl2psGetRGB(pixmap, col, row, &dr, &dg, &db); row_data[3*col] = (unsigned char)(255. * dr); row_data[3*col+1] = (unsigned char)(255. * dg); row_data[3*col+2] = (unsigned char)(255. * db); } png_write_row(png_ptr, (png_bytep)row_data); } gl2psFree(row_data); png_write_end(png_ptr, info_ptr); png_destroy_write_struct(&png_ptr, &info_ptr); } #endif /* Helper routines for text strings */ static GLint gl2psAddText(GLint type, const char *str, const char *fontname, GLshort fontsize, GLint alignment, GLfloat angle) { GLfloat pos[4]; GL2PSprimitive *prim; GLboolean valid; if(!gl2ps || !str || !fontname) return GL2PS_UNINITIALIZED; if(gl2ps->options & GL2PS_NO_TEXT) return GL2PS_SUCCESS; glGetBooleanv(GL_CURRENT_RASTER_POSITION_VALID, &valid); if(GL_FALSE == valid) return GL2PS_SUCCESS; /* the primitive is culled */ glGetFloatv(GL_CURRENT_RASTER_POSITION, pos); prim = (GL2PSprimitive*)gl2psMalloc(sizeof(GL2PSprimitive)); prim->type = type; prim->boundary = 0; prim->numverts = 1; prim->verts = (GL2PSvertex*)gl2psMalloc(sizeof(GL2PSvertex)); prim->verts[0].xyz[0] = pos[0]; prim->verts[0].xyz[1] = pos[1]; prim->verts[0].xyz[2] = pos[2]; prim->culled = 0; prim->offset = 0; prim->pattern = 0; prim->factor = 0; prim->width = 1; glGetFloatv(GL_CURRENT_RASTER_COLOR, prim->verts[0].rgba); prim->data.text = (GL2PSstring*)gl2psMalloc(sizeof(GL2PSstring)); prim->data.text->str = (char*)gl2psMalloc((strlen(str)+1)*sizeof(char)); strcpy(prim->data.text->str, str); prim->data.text->fontname = (char*)gl2psMalloc((strlen(fontname)+1)*sizeof(char)); strcpy(prim->data.text->fontname, fontname); prim->data.text->fontsize = fontsize; prim->data.text->alignment = alignment; prim->data.text->angle = angle; gl2psListAdd(gl2ps->auxprimitives, &prim); glPassThrough(GL2PS_TEXT_TOKEN); return GL2PS_SUCCESS; } static GL2PSstring *gl2psCopyText(GL2PSstring *t) { GL2PSstring *text = (GL2PSstring*)gl2psMalloc(sizeof(GL2PSstring)); text->str = (char*)gl2psMalloc((strlen(t->str)+1)*sizeof(char)); strcpy(text->str, t->str); text->fontname = (char*)gl2psMalloc((strlen(t->fontname)+1)*sizeof(char)); strcpy(text->fontname, t->fontname); text->fontsize = t->fontsize; text->alignment = t->alignment; text->angle = t->angle; return text; } static void gl2psFreeText(GL2PSstring *text) { if(!text) return; gl2psFree(text->str); gl2psFree(text->fontname); gl2psFree(text); } /* Helpers for blending modes */ static GLboolean gl2psSupportedBlendMode(GLenum sfactor, GLenum dfactor) { /* returns TRUE if gl2ps supports the argument combination: only two blending modes have been implemented so far */ if( (sfactor == GL_SRC_ALPHA && dfactor == GL_ONE_MINUS_SRC_ALPHA) || (sfactor == GL_ONE && dfactor == GL_ZERO) ) return GL_TRUE; return GL_FALSE; } static void gl2psAdaptVertexForBlending(GL2PSvertex *v) { /* Transforms vertex depending on the actual blending function - currently the vertex v is considered as source vertex and his alpha value is changed to 1.0 if source blending GL_ONE is active. This might be extended in the future */ if(!v || !gl2ps) return; if(gl2ps->options & GL2PS_NO_BLENDING || !gl2ps->blending){ v->rgba[3] = 1.0F; return; } switch(gl2ps->blendfunc[0]){ case GL_ONE: v->rgba[3] = 1.0F; break; default: break; } } static void gl2psAssignTriangleProperties(GL2PStriangle *t) { /* int i; */ t->prop = T_VAR_COLOR; /* Uncommenting the following lines activates an even more fine grained distinction between triangle types - please don't delete, a remarkable amount of PDF handling code inside this file depends on it if activated */ /* t->prop = T_CONST_COLOR; for(i = 0; i < 3; ++i){ if(!GL2PS_ZERO(t->vertex[0].rgba[i] - t->vertex[1].rgba[i]) || !GL2PS_ZERO(t->vertex[1].rgba[i] - t->vertex[2].rgba[i])){ t->prop = T_VAR_COLOR; break; } } */ if(!GL2PS_ZERO(t->vertex[0].rgba[3] - t->vertex[1].rgba[3]) || !GL2PS_ZERO(t->vertex[1].rgba[3] - t->vertex[2].rgba[3])){ t->prop |= T_VAR_ALPHA; } else{ if(t->vertex[0].rgba[3] < 1) t->prop |= T_ALPHA_LESS_1; else t->prop |= T_ALPHA_1; } } static void gl2psFillTriangleFromPrimitive(GL2PStriangle *t, GL2PSprimitive *p, GLboolean assignprops) { t->vertex[0] = p->verts[0]; t->vertex[1] = p->verts[1]; t->vertex[2] = p->verts[2]; if(GL_TRUE == assignprops) gl2psAssignTriangleProperties(t); } static void gl2psInitTriangle(GL2PStriangle *t) { int i; GL2PSvertex vertex = { {-1.0F, -1.0F, -1.0F}, {-1.0F, -1.0F, -1.0F, -1.0F} }; for(i = 0; i < 3; i++) t->vertex[i] = vertex; t->prop = T_UNDEFINED; } /* Miscellaneous helper routines */ static GL2PSprimitive *gl2psCopyPrimitive(GL2PSprimitive *p) { GL2PSprimitive *prim; if(!p){ gl2psMsg(GL2PS_ERROR, "Trying to copy an empty primitive"); return NULL; } prim = (GL2PSprimitive*)gl2psMalloc(sizeof(GL2PSprimitive)); prim->type = p->type; prim->numverts = p->numverts; prim->boundary = p->boundary; prim->offset = p->offset; prim->pattern = p->pattern; prim->factor = p->factor; prim->culled = p->culled; prim->width = p->width; prim->verts = (GL2PSvertex*)gl2psMalloc(p->numverts*sizeof(GL2PSvertex)); memcpy(prim->verts, p->verts, p->numverts * sizeof(GL2PSvertex)); switch(prim->type){ case GL2PS_PIXMAP : prim->data.image = gl2psCopyPixmap(p->data.image); break; case GL2PS_TEXT : case GL2PS_SPECIAL : prim->data.text = gl2psCopyText(p->data.text); break; default: break; } return prim; } static GLboolean gl2psSamePosition(GL2PSxyz p1, GL2PSxyz p2) { if(!GL2PS_ZERO(p1[0] - p2[0]) || !GL2PS_ZERO(p1[1] - p2[1]) || !GL2PS_ZERO(p1[2] - p2[2])) return GL_FALSE; return GL_TRUE; } /********************************************************************* * * 3D sorting routines * *********************************************************************/ static GLfloat gl2psComparePointPlane(GL2PSxyz point, GL2PSplane plane) { return(plane[0] * point[0] + plane[1] * point[1] + plane[2] * point[2] + plane[3]); } static GLfloat gl2psPsca(GLfloat *a, GLfloat *b) { return(a[0]*b[0] + a[1]*b[1] + a[2]*b[2]); } static void gl2psPvec(GLfloat *a, GLfloat *b, GLfloat *c) { c[0] = a[1]*b[2] - a[2]*b[1]; c[1] = a[2]*b[0] - a[0]*b[2]; c[2] = a[0]*b[1] - a[1]*b[0]; } static GLfloat gl2psNorm(GLfloat *a) { return (GLfloat)sqrt(a[0]*a[0] + a[1]*a[1] + a[2]*a[2]); } static void gl2psGetNormal(GLfloat *a, GLfloat *b, GLfloat *c) { GLfloat norm; gl2psPvec(a, b, c); if(!GL2PS_ZERO(norm = gl2psNorm(c))){ c[0] = c[0] / norm; c[1] = c[1] / norm; c[2] = c[2] / norm; } else{ /* The plane is still wrong despite our tests in gl2psGetPlane. Let's return a dummy value for now (this is a hack: we should do more intelligent tests in GetPlane) */ c[0] = c[1] = 0.0F; c[2] = 1.0F; } } static void gl2psGetPlane(GL2PSprimitive *prim, GL2PSplane plane) { GL2PSxyz v = {0.0F, 0.0F, 0.0F}, w = {0.0F, 0.0F, 0.0F}; switch(prim->type){ case GL2PS_TRIANGLE : case GL2PS_QUADRANGLE : v[0] = prim->verts[1].xyz[0] - prim->verts[0].xyz[0]; v[1] = prim->verts[1].xyz[1] - prim->verts[0].xyz[1]; v[2] = prim->verts[1].xyz[2] - prim->verts[0].xyz[2]; w[0] = prim->verts[2].xyz[0] - prim->verts[0].xyz[0]; w[1] = prim->verts[2].xyz[1] - prim->verts[0].xyz[1]; w[2] = prim->verts[2].xyz[2] - prim->verts[0].xyz[2]; if((GL2PS_ZERO(v[0]) && GL2PS_ZERO(v[1]) && GL2PS_ZERO(v[2])) || (GL2PS_ZERO(w[0]) && GL2PS_ZERO(w[1]) && GL2PS_ZERO(w[2]))){ plane[0] = plane[1] = 0.0F; plane[2] = 1.0F; plane[3] = -prim->verts[0].xyz[2]; } else{ gl2psGetNormal(v, w, plane); plane[3] = - plane[0] * prim->verts[0].xyz[0] - plane[1] * prim->verts[0].xyz[1] - plane[2] * prim->verts[0].xyz[2]; } break; case GL2PS_LINE : v[0] = prim->verts[1].xyz[0] - prim->verts[0].xyz[0]; v[1] = prim->verts[1].xyz[1] - prim->verts[0].xyz[1]; v[2] = prim->verts[1].xyz[2] - prim->verts[0].xyz[2]; if(GL2PS_ZERO(v[0]) && GL2PS_ZERO(v[1]) && GL2PS_ZERO(v[2])){ plane[0] = plane[1] = 0.0F; plane[2] = 1.0F; plane[3] = -prim->verts[0].xyz[2]; } else{ if(GL2PS_ZERO(v[0])) w[0] = 1.0F; else if(GL2PS_ZERO(v[1])) w[1] = 1.0F; else w[2] = 1.0F; gl2psGetNormal(v, w, plane); plane[3] = - plane[0] * prim->verts[0].xyz[0] - plane[1] * prim->verts[0].xyz[1] - plane[2] * prim->verts[0].xyz[2]; } break; case GL2PS_POINT : case GL2PS_PIXMAP : case GL2PS_TEXT : case GL2PS_SPECIAL : case GL2PS_IMAGEMAP: plane[0] = plane[1] = 0.0F; plane[2] = 1.0F; plane[3] = -prim->verts[0].xyz[2]; break; default : gl2psMsg(GL2PS_ERROR, "Unknown primitive type in BSP tree"); plane[0] = plane[1] = plane[3] = 0.0F; plane[2] = 1.0F; break; } } static void gl2psCutEdge(GL2PSvertex *a, GL2PSvertex *b, GL2PSplane plane, GL2PSvertex *c) { GL2PSxyz v; GLfloat sect; v[0] = b->xyz[0] - a->xyz[0]; v[1] = b->xyz[1] - a->xyz[1]; v[2] = b->xyz[2] - a->xyz[2]; sect = - gl2psComparePointPlane(a->xyz, plane) / gl2psPsca(plane, v); c->xyz[0] = a->xyz[0] + v[0] * sect; c->xyz[1] = a->xyz[1] + v[1] * sect; c->xyz[2] = a->xyz[2] + v[2] * sect; c->rgba[0] = (1 - sect) * a->rgba[0] + sect * b->rgba[0]; c->rgba[1] = (1 - sect) * a->rgba[1] + sect * b->rgba[1]; c->rgba[2] = (1 - sect) * a->rgba[2] + sect * b->rgba[2]; c->rgba[3] = (1 - sect) * a->rgba[3] + sect * b->rgba[3]; } static void gl2psCreateSplitPrimitive(GL2PSprimitive *parent, GL2PSplane plane, GL2PSprimitive *child, GLshort numverts, GLshort *index0, GLshort *index1) { GLshort i; if(parent->type == GL2PS_IMAGEMAP){ child->type = GL2PS_IMAGEMAP; child->data.image = parent->data.image; } else{ if(numverts > 4){ gl2psMsg(GL2PS_WARNING, "%d vertices in polygon", numverts); numverts = 4; } switch(numverts){ case 1 : child->type = GL2PS_POINT; break; case 2 : child->type = GL2PS_LINE; break; case 3 : child->type = GL2PS_TRIANGLE; break; case 4 : child->type = GL2PS_QUADRANGLE; break; default: child->type = GL2PS_NO_TYPE; break; } } child->boundary = 0; /* FIXME: not done! */ child->culled = parent->culled; child->offset = parent->offset; child->pattern = parent->pattern; child->factor = parent->factor; child->width = parent->width; child->numverts = numverts; child->verts = (GL2PSvertex*)gl2psMalloc(numverts * sizeof(GL2PSvertex)); for(i = 0; i < numverts; i++){ if(index1[i] < 0){ child->verts[i] = parent->verts[index0[i]]; } else{ gl2psCutEdge(&parent->verts[index0[i]], &parent->verts[index1[i]], plane, &child->verts[i]); } } } static void gl2psAddIndex(GLshort *index0, GLshort *index1, GLshort *nb, GLshort i, GLshort j) { GLint k; for(k = 0; k < *nb; k++){ if((index0[k] == i && index1[k] == j) || (index1[k] == i && index0[k] == j)) return; } index0[*nb] = i; index1[*nb] = j; (*nb)++; } static GLshort gl2psGetIndex(GLshort i, GLshort num) { return (i < num - 1) ? i + 1 : 0; } static GLint gl2psTestSplitPrimitive(GL2PSprimitive *prim, GL2PSplane plane) { GLint type = GL2PS_COINCIDENT; GLshort i, j; GLfloat d[5]; for(i = 0; i < prim->numverts; i++){ d[i] = gl2psComparePointPlane(prim->verts[i].xyz, plane); } if(prim->numverts < 2){ return 0; } else{ for(i = 0; i < prim->numverts; i++){ j = gl2psGetIndex(i, prim->numverts); if(d[j] > GL2PS_EPSILON){ if(type == GL2PS_COINCIDENT) type = GL2PS_IN_BACK_OF; else if(type != GL2PS_IN_BACK_OF) return 1; if(d[i] < -GL2PS_EPSILON) return 1; } else if(d[j] < -GL2PS_EPSILON){ if(type == GL2PS_COINCIDENT) type = GL2PS_IN_FRONT_OF; else if(type != GL2PS_IN_FRONT_OF) return 1; if(d[i] > GL2PS_EPSILON) return 1; } } } return 0; } static GLint gl2psSplitPrimitive(GL2PSprimitive *prim, GL2PSplane plane, GL2PSprimitive **front, GL2PSprimitive **back) { GLshort i, j, in = 0, out = 0, in0[5], in1[5], out0[5], out1[5]; GLint type; GLfloat d[5]; type = GL2PS_COINCIDENT; for(i = 0; i < prim->numverts; i++){ d[i] = gl2psComparePointPlane(prim->verts[i].xyz, plane); } switch(prim->type){ case GL2PS_POINT : if(d[0] > GL2PS_EPSILON) type = GL2PS_IN_BACK_OF; else if(d[0] < -GL2PS_EPSILON) type = GL2PS_IN_FRONT_OF; else type = GL2PS_COINCIDENT; break; default : for(i = 0; i < prim->numverts; i++){ j = gl2psGetIndex(i, prim->numverts); if(d[j] > GL2PS_EPSILON){ if(type == GL2PS_COINCIDENT) type = GL2PS_IN_BACK_OF; else if(type != GL2PS_IN_BACK_OF) type = GL2PS_SPANNING; if(d[i] < -GL2PS_EPSILON){ gl2psAddIndex(in0, in1, &in, i, j); gl2psAddIndex(out0, out1, &out, i, j); type = GL2PS_SPANNING; } gl2psAddIndex(out0, out1, &out, j, -1); } else if(d[j] < -GL2PS_EPSILON){ if(type == GL2PS_COINCIDENT) type = GL2PS_IN_FRONT_OF; else if(type != GL2PS_IN_FRONT_OF) type = GL2PS_SPANNING; if(d[i] > GL2PS_EPSILON){ gl2psAddIndex(in0, in1, &in, i, j); gl2psAddIndex(out0, out1, &out, i, j); type = GL2PS_SPANNING; } gl2psAddIndex(in0, in1, &in, j, -1); } else{ gl2psAddIndex(in0, in1, &in, j, -1); gl2psAddIndex(out0, out1, &out, j, -1); } } break; } if(type == GL2PS_SPANNING){ *back = (GL2PSprimitive*)gl2psMalloc(sizeof(GL2PSprimitive)); *front = (GL2PSprimitive*)gl2psMalloc(sizeof(GL2PSprimitive)); gl2psCreateSplitPrimitive(prim, plane, *back, out, out0, out1); gl2psCreateSplitPrimitive(prim, plane, *front, in, in0, in1); } return type; } static void gl2psDivideQuad(GL2PSprimitive *quad, GL2PSprimitive **t1, GL2PSprimitive **t2) { *t1 = (GL2PSprimitive*)gl2psMalloc(sizeof(GL2PSprimitive)); *t2 = (GL2PSprimitive*)gl2psMalloc(sizeof(GL2PSprimitive)); (*t1)->type = (*t2)->type = GL2PS_TRIANGLE; (*t1)->numverts = (*t2)->numverts = 3; (*t1)->culled = (*t2)->culled = quad->culled; (*t1)->offset = (*t2)->offset = quad->offset; (*t1)->pattern = (*t2)->pattern = quad->pattern; (*t1)->factor = (*t2)->factor = quad->factor; (*t1)->width = (*t2)->width = quad->width; (*t1)->verts = (GL2PSvertex*)gl2psMalloc(3 * sizeof(GL2PSvertex)); (*t2)->verts = (GL2PSvertex*)gl2psMalloc(3 * sizeof(GL2PSvertex)); (*t1)->verts[0] = quad->verts[0]; (*t1)->verts[1] = quad->verts[1]; (*t1)->verts[2] = quad->verts[2]; (*t1)->boundary = ((quad->boundary & 1) ? 1 : 0) | ((quad->boundary & 2) ? 2 : 0); (*t2)->verts[0] = quad->verts[0]; (*t2)->verts[1] = quad->verts[2]; (*t2)->verts[2] = quad->verts[3]; (*t1)->boundary = ((quad->boundary & 4) ? 2 : 0) | ((quad->boundary & 4) ? 2 : 0); } static int gl2psCompareDepth(const void *a, const void *b) { GL2PSprimitive *q, *w; GLfloat dq = 0.0F, dw = 0.0F, diff; int i; q = *(GL2PSprimitive**)a; w = *(GL2PSprimitive**)b; for(i = 0; i < q->numverts; i++){ dq += q->verts[i].xyz[2]; } dq /= (GLfloat)q->numverts; for(i = 0; i < w->numverts; i++){ dw += w->verts[i].xyz[2]; } dw /= (GLfloat)w->numverts; diff = dq - dw; if(diff > 0.){ return -1; } else if(diff < 0.){ return 1; } else{ return 0; } } static int gl2psTrianglesFirst(const void *a, const void *b) { GL2PSprimitive *q, *w; q = *(GL2PSprimitive**)a; w = *(GL2PSprimitive**)b; return(q->type < w->type ? 1 : -1); } static GLint gl2psFindRoot(GL2PSlist *primitives, GL2PSprimitive **root) { GL2PSplane plane; if(!gl2psListNbr(primitives)){ gl2psMsg(GL2PS_ERROR, "Cannot fint root in empty primitive list"); return 0; } *root = *(GL2PSprimitive**)gl2psListPointer(primitives, 0); if(gl2ps->options & GL2PS_BEST_ROOT){ GLint i, best = 1000000, index = 0, maxp; maxp = gl2psListNbr(primitives); if(maxp > gl2ps->maxbestroot){ maxp = gl2ps->maxbestroot; } for(i = 0; i < maxp; i++){ GL2PSprimitive *prim1, *prim2; prim1 = *(GL2PSprimitive**)gl2psListPointer(primitives, i); gl2psGetPlane(prim1, plane); GLint count = 0; GLint j; for(j = 0; j < gl2psListNbr(primitives); j++){ if(j != i){ prim2 = *(GL2PSprimitive**)gl2psListPointer(primitives, j); count += gl2psTestSplitPrimitive(prim2, plane); } if(count > best) break; } if(count < best){ best = count; index = i; *root = prim1; if(!count) return index; } } /* if(index) gl2psMsg(GL2PS_INFO, "GL2PS_BEST_ROOT was worth it: %d", index); */ return index; } else{ return 0; } } static void gl2psFreeImagemap(GL2PSimagemap *list){ GL2PSimagemap *next; while(list != NULL){ next = list->next; gl2psFree(list->image->pixels); gl2psFree(list->image); gl2psFree(list); list = next; } } static void gl2psFreePrimitive(void *data) { GL2PSprimitive *q; q = *(GL2PSprimitive**)data; gl2psFree(q->verts); if(q->type == GL2PS_TEXT || q->type == GL2PS_SPECIAL){ gl2psFreeText(q->data.text); } else if(q->type == GL2PS_PIXMAP){ gl2psFreePixmap(q->data.image); } gl2psFree(q); } static void gl2psAddPrimitiveInList(GL2PSprimitive *prim, GL2PSlist *list) { GL2PSprimitive *t1, *t2; if(prim->type != GL2PS_QUADRANGLE){ gl2psListAdd(list, &prim); } else{ gl2psDivideQuad(prim, &t1, &t2); gl2psListAdd(list, &t1); gl2psListAdd(list, &t2); gl2psFreePrimitive(&prim); } } static void gl2psFreeBspTree(GL2PSbsptree **tree) { if(*tree){ if((*tree)->back) gl2psFreeBspTree(&(*tree)->back); if((*tree)->primitives){ gl2psListAction((*tree)->primitives, gl2psFreePrimitive); gl2psListDelete((*tree)->primitives); } if((*tree)->front) gl2psFreeBspTree(&(*tree)->front); gl2psFree(*tree); *tree = NULL; } } static GLboolean gl2psGreater(GLfloat f1, GLfloat f2) { if(f1 > f2) return GL_TRUE; else return GL_FALSE; } static GLboolean gl2psLess(GLfloat f1, GLfloat f2) { if(f1 < f2) return GL_TRUE; else return GL_FALSE; } static void gl2psBuildBspTree(GL2PSbsptree *tree, GL2PSlist *primitives) { GL2PSprimitive *prim, *frontprim = NULL, *backprim = NULL; GL2PSlist *frontlist, *backlist; GLint i, index; tree->front = NULL; tree->back = NULL; tree->primitives = gl2psListCreate(1, 2, sizeof(GL2PSprimitive*)); index = gl2psFindRoot(primitives, &prim); gl2psGetPlane(prim, tree->plane); gl2psAddPrimitiveInList(prim, tree->primitives); frontlist = gl2psListCreate(1, 2, sizeof(GL2PSprimitive*)); backlist = gl2psListCreate(1, 2, sizeof(GL2PSprimitive*)); for(i = 0; i < gl2psListNbr(primitives); i++){ if(i != index){ prim = *(GL2PSprimitive**)gl2psListPointer(primitives,i); switch(gl2psSplitPrimitive(prim, tree->plane, &frontprim, &backprim)){ case GL2PS_COINCIDENT: gl2psAddPrimitiveInList(prim, tree->primitives); break; case GL2PS_IN_BACK_OF: gl2psAddPrimitiveInList(prim, backlist); break; case GL2PS_IN_FRONT_OF: gl2psAddPrimitiveInList(prim, frontlist); break; case GL2PS_SPANNING: gl2psAddPrimitiveInList(backprim, backlist); gl2psAddPrimitiveInList(frontprim, frontlist); gl2psFreePrimitive(&prim); break; } } } if(gl2psListNbr(tree->primitives)){ gl2psListSort(tree->primitives, gl2psTrianglesFirst); } if(gl2psListNbr(frontlist)){ gl2psListSort(frontlist, gl2psTrianglesFirst); tree->front = (GL2PSbsptree*)gl2psMalloc(sizeof(GL2PSbsptree)); gl2psBuildBspTree(tree->front, frontlist); } else{ gl2psListDelete(frontlist); } if(gl2psListNbr(backlist)){ gl2psListSort(backlist, gl2psTrianglesFirst); tree->back = (GL2PSbsptree*)gl2psMalloc(sizeof(GL2PSbsptree)); gl2psBuildBspTree(tree->back, backlist); } else{ gl2psListDelete(backlist); } gl2psListDelete(primitives); } static void gl2psTraverseBspTree(GL2PSbsptree *tree, GL2PSxyz eye, GLfloat epsilon, GLboolean (*compare)(GLfloat f1, GLfloat f2), void (*action)(void *data), int inverse) { GLfloat result; if(!tree) return; result = gl2psComparePointPlane(eye, tree->plane); if(GL_TRUE == compare(result, epsilon)){ gl2psTraverseBspTree(tree->back, eye, epsilon, compare, action, inverse); if(inverse){ gl2psListActionInverse(tree->primitives, action); } else{ gl2psListAction(tree->primitives, action); } gl2psTraverseBspTree(tree->front, eye, epsilon, compare, action, inverse); } else if(GL_TRUE == compare(-epsilon, result)){ gl2psTraverseBspTree(tree->front, eye, epsilon, compare, action, inverse); if(inverse){ gl2psListActionInverse(tree->primitives, action); } else{ gl2psListAction(tree->primitives, action); } gl2psTraverseBspTree(tree->back, eye, epsilon, compare, action, inverse); } else{ gl2psTraverseBspTree(tree->front, eye, epsilon, compare, action, inverse); gl2psTraverseBspTree(tree->back, eye, epsilon, compare, action, inverse); } } static void gl2psRescaleAndOffset() { GL2PSprimitive *prim; GLfloat minZ, maxZ, rangeZ, scaleZ; GLfloat factor, units, area, dZ, dZdX, dZdY, maxdZ; int i, j; if(!gl2psListNbr(gl2ps->primitives)) return; /* get z-buffer range */ prim = *(GL2PSprimitive**)gl2psListPointer(gl2ps->primitives, 0); minZ = maxZ = prim->verts[0].xyz[2]; for(i = 1; i < prim->numverts; i++){ if(prim->verts[i].xyz[2] < minZ) minZ = prim->verts[i].xyz[2]; if(prim->verts[i].xyz[2] > maxZ) maxZ = prim->verts[i].xyz[2]; } for(i = 1; i < gl2psListNbr(gl2ps->primitives); i++){ prim = *(GL2PSprimitive**)gl2psListPointer(gl2ps->primitives, i); for(j = 0; j < prim->numverts; j++){ if(prim->verts[j].xyz[2] < minZ) minZ = prim->verts[j].xyz[2]; if(prim->verts[j].xyz[2] > maxZ) maxZ = prim->verts[j].xyz[2]; } } rangeZ = (maxZ - minZ); /* rescale z-buffer coordinate in [0,GL2PS_ZSCALE], to make it of the same order of magnitude as the x and y coordinates */ scaleZ = GL2PS_ZERO(rangeZ) ? GL2PS_ZSCALE : (GL2PS_ZSCALE / rangeZ); /* avoid precision loss (we use floats!) */ if(scaleZ > 100000.F) scaleZ = 100000.F; /* apply offsets */ for(i = 0; i < gl2psListNbr(gl2ps->primitives); i++){ prim = *(GL2PSprimitive**)gl2psListPointer(gl2ps->primitives, i); for(j = 0; j < prim->numverts; j++){ prim->verts[j].xyz[2] = (prim->verts[j].xyz[2] - minZ) * scaleZ; } if((gl2ps->options & GL2PS_SIMPLE_LINE_OFFSET) && (prim->type == GL2PS_LINE)){ if(gl2ps->sort == GL2PS_SIMPLE_SORT){ prim->verts[0].xyz[2] -= GL2PS_ZOFFSET_LARGE; prim->verts[1].xyz[2] -= GL2PS_ZOFFSET_LARGE; } else{ prim->verts[0].xyz[2] -= GL2PS_ZOFFSET; prim->verts[1].xyz[2] -= GL2PS_ZOFFSET; } } else if(prim->offset && (prim->type == GL2PS_TRIANGLE)){ factor = gl2ps->offset[0]; units = gl2ps->offset[1]; area = (prim->verts[1].xyz[0] - prim->verts[0].xyz[0]) * (prim->verts[2].xyz[1] - prim->verts[1].xyz[1]) - (prim->verts[2].xyz[0] - prim->verts[1].xyz[0]) * (prim->verts[1].xyz[1] - prim->verts[0].xyz[1]); dZdX = ((prim->verts[2].xyz[1] - prim->verts[1].xyz[1]) * (prim->verts[1].xyz[2] - prim->verts[0].xyz[2]) - (prim->verts[1].xyz[1] - prim->verts[0].xyz[1]) * (prim->verts[2].xyz[2] - prim->verts[1].xyz[2])) / area; dZdY = ((prim->verts[1].xyz[0] - prim->verts[0].xyz[0]) * (prim->verts[2].xyz[2] - prim->verts[1].xyz[2]) - (prim->verts[2].xyz[0] - prim->verts[1].xyz[0]) * (prim->verts[1].xyz[2] - prim->verts[0].xyz[2])) / area; maxdZ = (GLfloat)sqrt(dZdX * dZdX + dZdY * dZdY); dZ = factor * maxdZ + units; prim->verts[0].xyz[2] += dZ; prim->verts[1].xyz[2] += dZ; prim->verts[2].xyz[2] += dZ; } } } /********************************************************************* * * 2D sorting routines (for occlusion culling) * *********************************************************************/ static GLint gl2psGetPlaneFromPoints(GL2PSxyz a, GL2PSxyz b, GL2PSplane plane) { GLfloat n; plane[0] = b[1] - a[1]; plane[1] = a[0] - b[0]; n = (GLfloat)sqrt(plane[0]*plane[0] + plane[1]*plane[1]); plane[2] = 0.0F; if(!GL2PS_ZERO(n)){ plane[0] /= n; plane[1] /= n; plane[3] = -plane[0]*a[0]-plane[1]*a[1]; return 1; } else{ plane[0] = -1.0F; plane[1] = 0.0F; plane[3] = a[0]; return 0; } } static void gl2psFreeBspImageTree(GL2PSbsptree2d **tree) { if(*tree){ if((*tree)->back) gl2psFreeBspImageTree(&(*tree)->back); if((*tree)->front) gl2psFreeBspImageTree(&(*tree)->front); gl2psFree(*tree); *tree = NULL; } } static GLint gl2psCheckPoint(GL2PSxyz point, GL2PSplane plane) { GLfloat pt_dis; pt_dis = gl2psComparePointPlane(point, plane); if(pt_dis > GL2PS_EPSILON) return GL2PS_POINT_INFRONT; else if(pt_dis < -GL2PS_EPSILON) return GL2PS_POINT_BACK; else return GL2PS_POINT_COINCIDENT; } static void gl2psAddPlanesInBspTreeImage(GL2PSprimitive *prim, GL2PSbsptree2d **tree) { if((*tree == NULL) && (prim->numverts > 2)){ GL2PSbsptree2d *head = NULL, *cur = NULL; head = (GL2PSbsptree2d*)gl2psMalloc(sizeof(GL2PSbsptree2d)); GLint i; GLint offset = 0; for(i = 0; i < prim->numverts-1; i++){ if(!gl2psGetPlaneFromPoints(prim->verts[i].xyz, prim->verts[i+1].xyz, head->plane)){ if(prim->numverts-i > 3){ offset++; } else{ gl2psFree(head); return; } } else{ break; } } head->back = NULL; head->front = NULL; GLint ret = 0; for(i = 2+offset; i < prim->numverts; i++){ ret = gl2psCheckPoint(prim->verts[i].xyz, head->plane); if(ret != GL2PS_POINT_COINCIDENT) break; } switch(ret){ case GL2PS_POINT_INFRONT : cur = head; for(i = 1+offset; i < prim->numverts-1; i++){ if(cur->front == NULL){ cur->front = (GL2PSbsptree2d*)gl2psMalloc(sizeof(GL2PSbsptree2d)); } if(gl2psGetPlaneFromPoints(prim->verts[i].xyz, prim->verts[i+1].xyz, cur->front->plane)){ cur = cur->front; cur->front = NULL; cur->back = NULL; } } if(cur->front == NULL){ cur->front = (GL2PSbsptree2d*)gl2psMalloc(sizeof(GL2PSbsptree2d)); } if(gl2psGetPlaneFromPoints(prim->verts[i].xyz, prim->verts[offset].xyz, cur->front->plane)){ cur->front->front = NULL; cur->front->back = NULL; } else{ gl2psFree(cur->front); cur->front = NULL; } break; case GL2PS_POINT_BACK : for(i = 0; i < 4; i++){ head->plane[i] = -head->plane[i]; } cur = head; for(i = 1+offset; i < prim->numverts-1; i++){ if(cur->front == NULL){ cur->front = (GL2PSbsptree2d*)gl2psMalloc(sizeof(GL2PSbsptree2d)); } if(gl2psGetPlaneFromPoints(prim->verts[i+1].xyz, prim->verts[i].xyz, cur->front->plane)){ cur = cur->front; cur->front = NULL; cur->back = NULL; } } if(cur->front == NULL){ cur->front = (GL2PSbsptree2d*)gl2psMalloc(sizeof(GL2PSbsptree2d)); } if(gl2psGetPlaneFromPoints(prim->verts[offset].xyz, prim->verts[i].xyz, cur->front->plane)){ cur->front->front = NULL; cur->front->back = NULL; } else{ gl2psFree(cur->front); cur->front = NULL; } break; default: gl2psFree(head); return; } (*tree) = head; } } static GLint gl2psCheckPrimitive(GL2PSprimitive *prim, GL2PSplane plane) { GLint i; GLint pos; pos = gl2psCheckPoint(prim->verts[0].xyz, plane); for(i = 1; i < prim->numverts; i++){ pos |= gl2psCheckPoint(prim->verts[i].xyz, plane); if(pos == (GL2PS_POINT_INFRONT | GL2PS_POINT_BACK)) return GL2PS_SPANNING; } if(pos & GL2PS_POINT_INFRONT) return GL2PS_IN_FRONT_OF; else if(pos & GL2PS_POINT_BACK) return GL2PS_IN_BACK_OF; else return GL2PS_COINCIDENT; } static GL2PSprimitive *gl2psCreateSplitPrimitive2D(GL2PSprimitive *parent, GLshort numverts, GL2PSvertex *vertx) { GLint i; GL2PSprimitive *child = (GL2PSprimitive*)gl2psMalloc(sizeof(GL2PSprimitive)); if(parent->type == GL2PS_IMAGEMAP){ child->type = GL2PS_IMAGEMAP; child->data.image = parent->data.image; } else { switch(numverts){ case 1 : child->type = GL2PS_POINT; break; case 2 : child->type = GL2PS_LINE; break; case 3 : child->type = GL2PS_TRIANGLE; break; case 4 : child->type = GL2PS_QUADRANGLE; break; default: child->type = GL2PS_NO_TYPE; break; /* FIXME */ } } child->boundary = 0; /* FIXME: not done! */ child->culled = parent->culled; child->offset = parent->offset; child->pattern = parent->pattern; child->factor = parent->factor; child->width = parent->width; child->numverts = numverts; child->verts = (GL2PSvertex*)gl2psMalloc(numverts * sizeof(GL2PSvertex)); for(i = 0; i < numverts; i++){ child->verts[i] = vertx[i]; } return child; } static void gl2psSplitPrimitive2D(GL2PSprimitive *prim, GL2PSplane plane, GL2PSprimitive **front, GL2PSprimitive **back) { /* cur will hold the position of the current vertex prev will hold the position of the previous vertex prev0 will hold the position of the vertex number 0 v1 and v2 represent the current and previous vertices, respectively flag is set if the current vertex should be checked against the plane */ GLint cur = -1, prev = -1, i, v1 = 0, v2 = 0, flag = 1, prev0 = -1; /* list of vertices that will go in front and back primitive */ GL2PSvertex *front_list = NULL, *back_list = NULL; /* number of vertices in front and back list */ GLshort front_count = 0, back_count = 0; for(i = 0; i <= prim->numverts; i++){ v1 = i; if(v1 == prim->numverts){ if(prim->numverts < 3) break; v1 = 0; v2 = prim->numverts-1; cur = prev0; } else if(flag){ cur = gl2psCheckPoint(prim->verts[v1].xyz, plane); if(i == 0){ prev0 = cur; } } if(((prev == -1) || (prev == cur) || (prev == 0) || (cur == 0)) && (i < prim->numverts)){ if(cur == GL2PS_POINT_INFRONT){ front_count++; front_list = (GL2PSvertex*)gl2psRealloc(front_list, sizeof(GL2PSvertex)*front_count); front_list[front_count-1] = prim->verts[v1]; } else if(cur == GL2PS_POINT_BACK){ back_count++; back_list = (GL2PSvertex*)gl2psRealloc(back_list, sizeof(GL2PSvertex)*back_count); back_list[back_count-1] = prim->verts[v1]; } else{ front_count++; front_list = (GL2PSvertex*)gl2psRealloc(front_list, sizeof(GL2PSvertex)*front_count); front_list[front_count-1] = prim->verts[v1]; back_count++; back_list = (GL2PSvertex*)gl2psRealloc(back_list, sizeof(GL2PSvertex)*back_count); back_list[back_count-1] = prim->verts[v1]; } flag = 1; } else if((prev != cur) && (cur != 0) && (prev != 0)){ if(v1 != 0){ v2 = v1-1; i--; } front_count++; front_list = (GL2PSvertex*)gl2psRealloc(front_list, sizeof(GL2PSvertex)*front_count); gl2psCutEdge(&prim->verts[v2], &prim->verts[v1], plane, &front_list[front_count-1]); back_count++; back_list = (GL2PSvertex*)gl2psRealloc(back_list, sizeof(GL2PSvertex)*back_count); back_list[back_count-1] = front_list[front_count-1]; flag = 0; } prev = cur; } *front = gl2psCreateSplitPrimitive2D(prim, front_count, front_list); *back = gl2psCreateSplitPrimitive2D(prim, back_count, back_list); gl2psFree(front_list); gl2psFree(back_list); } static GLint gl2psAddInBspImageTree(GL2PSprimitive *prim, GL2PSbsptree2d **tree) { /* FIXME: until we consider the actual extent of text strings and pixmaps, never cull them. Otherwise the whole string/pixmap gets culled as soon as the reference point is hidden */ if(prim->type == GL2PS_PIXMAP || prim->type == GL2PS_TEXT || prim->type == GL2PS_SPECIAL){ return 1; } if(*tree == NULL){ if((prim->type != GL2PS_IMAGEMAP) && (GL_FALSE == gl2ps->zerosurfacearea)){ gl2psAddPlanesInBspTreeImage(gl2ps->primitivetoadd, tree); } return 1; } else{ GL2PSprimitive *frontprim = NULL, *backprim = NULL; GLint ret = 0; switch(gl2psCheckPrimitive(prim, (*tree)->plane)){ case GL2PS_IN_BACK_OF: return gl2psAddInBspImageTree(prim, &(*tree)->back); case GL2PS_IN_FRONT_OF: if((*tree)->front != NULL) return gl2psAddInBspImageTree(prim, &(*tree)->front); else return 0; case GL2PS_SPANNING: gl2psSplitPrimitive2D(prim, (*tree)->plane, &frontprim, &backprim); ret = gl2psAddInBspImageTree(backprim, &(*tree)->back); if((*tree)->front != NULL){ if(gl2psAddInBspImageTree(frontprim, &(*tree)->front)){ ret = 1; } } gl2psFree(frontprim->verts); gl2psFree(frontprim); gl2psFree(backprim->verts); gl2psFree(backprim); return ret; case GL2PS_COINCIDENT: if((*tree)->back != NULL){ gl2ps->zerosurfacearea = GL_TRUE; ret = gl2psAddInBspImageTree(prim, &(*tree)->back); gl2ps->zerosurfacearea = GL_FALSE; if(ret) return ret; } if((*tree)->front != NULL){ gl2ps->zerosurfacearea = GL_TRUE; ret = gl2psAddInBspImageTree(prim, &(*tree)->front); gl2ps->zerosurfacearea = GL_FALSE; if(ret) return ret; } if(prim->type == GL2PS_LINE) return 1; else return 0; } } return 0; } static void gl2psAddInImageTree(void *data) { GL2PSprimitive *prim = *(GL2PSprimitive **)data; gl2ps->primitivetoadd = prim; if(prim->type == GL2PS_IMAGEMAP && prim->data.image->format == GL2PS_IMAGEMAP_VISIBLE){ prim->culled = 1; } else if(!gl2psAddInBspImageTree(prim, &gl2ps->imagetree)){ prim->culled = 1; } else if(prim->type == GL2PS_IMAGEMAP){ prim->data.image->format = GL2PS_IMAGEMAP_VISIBLE; } } /* Boundary construction */ static void gl2psAddBoundaryInList(GL2PSprimitive *prim, GL2PSlist *list) { GL2PSprimitive *b; GLshort i; GL2PSxyz c; c[0] = c[1] = c[2] = 0.0F; for(i = 0; i < prim->numverts; i++){ c[0] += prim->verts[i].xyz[0]; c[1] += prim->verts[i].xyz[1]; } c[0] /= prim->numverts; c[1] /= prim->numverts; for(i = 0; i < prim->numverts; i++){ if(prim->boundary & (GLint)pow(2., i)){ b = (GL2PSprimitive*)gl2psMalloc(sizeof(GL2PSprimitive)); b->type = GL2PS_LINE; b->offset = prim->offset; b->pattern = prim->pattern; b->factor = prim->factor; b->culled = prim->culled; b->width = prim->width; b->boundary = 0; b->numverts = 2; b->verts = (GL2PSvertex*)gl2psMalloc(2 * sizeof(GL2PSvertex)); #if 0 /* FIXME: need to work on boundary offset... */ v[0] = c[0] - prim->verts[i].xyz[0]; v[1] = c[1] - prim->verts[i].xyz[1]; v[2] = 0.0F; norm = gl2psNorm(v); v[0] /= norm; v[1] /= norm; b->verts[0].xyz[0] = prim->verts[i].xyz[0] +0.1*v[0]; b->verts[0].xyz[1] = prim->verts[i].xyz[1] +0.1*v[1]; b->verts[0].xyz[2] = prim->verts[i].xyz[2]; v[0] = c[0] - prim->verts[gl2psGetIndex(i, prim->numverts)].xyz[0]; v[1] = c[1] - prim->verts[gl2psGetIndex(i, prim->numverts)].xyz[1]; norm = gl2psNorm(v); v[0] /= norm; v[1] /= norm; b->verts[1].xyz[0] = prim->verts[gl2psGetIndex(i, prim->numverts)].xyz[0] +0.1*v[0]; b->verts[1].xyz[1] = prim->verts[gl2psGetIndex(i, prim->numverts)].xyz[1] +0.1*v[1]; b->verts[1].xyz[2] = prim->verts[gl2psGetIndex(i, prim->numverts)].xyz[2]; #else b->verts[0].xyz[0] = prim->verts[i].xyz[0]; b->verts[0].xyz[1] = prim->verts[i].xyz[1]; b->verts[0].xyz[2] = prim->verts[i].xyz[2]; b->verts[1].xyz[0] = prim->verts[gl2psGetIndex(i, prim->numverts)].xyz[0]; b->verts[1].xyz[1] = prim->verts[gl2psGetIndex(i, prim->numverts)].xyz[1]; b->verts[1].xyz[2] = prim->verts[gl2psGetIndex(i, prim->numverts)].xyz[2]; #endif b->verts[0].rgba[0] = 0.0F; b->verts[0].rgba[1] = 0.0F; b->verts[0].rgba[2] = 0.0F; b->verts[0].rgba[3] = 0.0F; b->verts[1].rgba[0] = 0.0F; b->verts[1].rgba[1] = 0.0F; b->verts[1].rgba[2] = 0.0F; b->verts[1].rgba[3] = 0.0F; gl2psListAdd(list, &b); } } } static void gl2psBuildPolygonBoundary(GL2PSbsptree *tree) { GLint i; GL2PSprimitive *prim; if(!tree) return; gl2psBuildPolygonBoundary(tree->back); for(i = 0; i < gl2psListNbr(tree->primitives); i++){ prim = *(GL2PSprimitive**)gl2psListPointer(tree->primitives, i); if(prim->boundary) gl2psAddBoundaryInList(prim, tree->primitives); } gl2psBuildPolygonBoundary(tree->front); } /********************************************************************* * * Feedback buffer parser * *********************************************************************/ static void gl2psAddPolyPrimitive(GLshort type, GLshort numverts, GL2PSvertex *verts, GLint offset, GLushort pattern, GLint factor, GLfloat width, char boundary) { GL2PSprimitive *prim; prim = (GL2PSprimitive*)gl2psMalloc(sizeof(GL2PSprimitive)); prim->type = type; prim->numverts = numverts; prim->verts = (GL2PSvertex*)gl2psMalloc(numverts * sizeof(GL2PSvertex)); memcpy(prim->verts, verts, numverts * sizeof(GL2PSvertex)); prim->boundary = boundary; prim->offset = offset; prim->pattern = pattern; prim->factor = factor; prim->width = width; prim->culled = 0; /* FIXME: here we should have an option to split stretched tris/quads to enhance SIMPLE_SORT */ gl2psListAdd(gl2ps->primitives, &prim); } static GLint gl2psGetVertex(GL2PSvertex *v, GLfloat *p) { v->xyz[0] = p[0]; v->xyz[1] = p[1]; v->xyz[2] = p[2]; if(gl2ps->colormode == GL_COLOR_INDEX && gl2ps->colorsize > 0){ GLint i = (GLint)(p[3] + 0.5); v->rgba[0] = gl2ps->colormap[i][0]; v->rgba[1] = gl2ps->colormap[i][1]; v->rgba[2] = gl2ps->colormap[i][2]; v->rgba[3] = gl2ps->colormap[i][3]; return 4; } else{ v->rgba[0] = p[3]; v->rgba[1] = p[4]; v->rgba[2] = p[5]; v->rgba[3] = p[6]; return 7; } } static void gl2psParseFeedbackBuffer(GLint used) { char flag; GLushort pattern = 0; GLboolean boundary; GLint i, sizeoffloat, count, v, vtot, offset = 0, factor = 0, auxindex = 0; GLfloat lwidth = 1.0F, psize = 1.0F; GLfloat *current; GL2PSvertex vertices[3]; GL2PSprimitive *prim; GL2PSimagemap *node; current = gl2ps->feedback; boundary = gl2ps->boundary = GL_FALSE; while(used > 0){ if(GL_TRUE == boundary) gl2ps->boundary = GL_TRUE; switch((GLint)*current){ case GL_POINT_TOKEN : current ++; used --; i = gl2psGetVertex(&vertices[0], current); current += i; used -= i; gl2psAddPolyPrimitive(GL2PS_POINT, 1, vertices, 0, pattern, factor, psize, 0); break; case GL_LINE_TOKEN : case GL_LINE_RESET_TOKEN : current ++; used --; i = gl2psGetVertex(&vertices[0], current); current += i; used -= i; i = gl2psGetVertex(&vertices[1], current); current += i; used -= i; gl2psAddPolyPrimitive(GL2PS_LINE, 2, vertices, 0, pattern, factor, lwidth, 0); break; case GL_POLYGON_TOKEN : count = (GLint)current[1]; current += 2; used -= 2; v = vtot = 0; while(count > 0 && used > 0){ i = gl2psGetVertex(&vertices[v], current); gl2psAdaptVertexForBlending(&vertices[v]); current += i; used -= i; count --; vtot++; if(v == 2){ if(GL_TRUE == boundary){ if(!count && vtot == 2) flag = 1|2|4; else if(!count) flag = 2|4; else if(vtot == 2) flag = 1|2; else flag = 2; } else flag = 0; gl2psAddPolyPrimitive(GL2PS_TRIANGLE, 3, vertices, offset, pattern, factor, 1, flag); vertices[1] = vertices[2]; } else v ++; } break; case GL_BITMAP_TOKEN : case GL_DRAW_PIXEL_TOKEN : case GL_COPY_PIXEL_TOKEN : current ++; used --; i = gl2psGetVertex(&vertices[0], current); current += i; used -= i; break; case GL_PASS_THROUGH_TOKEN : switch((GLint)current[1]){ case GL2PS_BEGIN_OFFSET_TOKEN : offset = 1; break; case GL2PS_END_OFFSET_TOKEN : offset = 0; break; case GL2PS_BEGIN_BOUNDARY_TOKEN : boundary = GL_TRUE; break; case GL2PS_END_BOUNDARY_TOKEN : boundary = GL_FALSE; break; case GL2PS_END_STIPPLE_TOKEN : pattern = factor = 0; break; case GL2PS_BEGIN_BLEND_TOKEN : gl2ps->blending = GL_TRUE; break; case GL2PS_END_BLEND_TOKEN : gl2ps->blending = GL_FALSE; break; case GL2PS_BEGIN_STIPPLE_TOKEN : current += 2; used -= 2; pattern = (GLushort)current[1]; current += 2; used -= 2; factor = (GLint)current[1]; break; case GL2PS_SRC_BLEND_TOKEN : current += 2; used -= 2; gl2ps->blendfunc[0] = (GLint)current[1]; break; case GL2PS_DST_BLEND_TOKEN : current += 2; used -= 2; gl2ps->blendfunc[1] = (GLint)current[1]; break; case GL2PS_POINT_SIZE_TOKEN : current += 2; used -= 2; psize = current[1]; break; case GL2PS_LINE_WIDTH_TOKEN : current += 2; used -= 2; lwidth = current[1]; break; case GL2PS_IMAGEMAP_TOKEN : prim = (GL2PSprimitive *)gl2psMalloc(sizeof(GL2PSprimitive)); prim->type = GL2PS_IMAGEMAP; prim->boundary = 0; prim->numverts = 4; prim->verts = (GL2PSvertex *)gl2psMalloc(4 * sizeof(GL2PSvertex)); prim->culled = 0; prim->offset = 0; prim->pattern = 0; prim->factor = 0; prim->width = 1; node = (GL2PSimagemap*)gl2psMalloc(sizeof(GL2PSimagemap)); node->image = (GL2PSimage*)gl2psMalloc(sizeof(GL2PSimage)); node->image->type = 0; node->image->format = 0; node->next = NULL; if(gl2ps->imagemap_head == NULL) gl2ps->imagemap_head = node; else gl2ps->imagemap_tail->next = node; gl2ps->imagemap_tail = node; prim->data.image = node->image; current += 2; used -= 2; i = gl2psGetVertex(&prim->verts[0], ¤t[1]); current += i; used -= i; node->image->width = (GLint)current[2]; current += 2; used -= 2; node->image->height = (GLint)current[2]; prim->verts[0].xyz[0] = prim->verts[0].xyz[0] - (int)(node->image->width / 2) + 0.5f; prim->verts[0].xyz[1] = prim->verts[0].xyz[1] - (int)(node->image->height / 2) + 0.5f; for(i = 1; i < 4; i++){ for(v = 0; v < 3; v++){ prim->verts[i].xyz[v] = prim->verts[0].xyz[v]; prim->verts[i].rgba[v] = prim->verts[0].rgba[v]; } prim->verts[i].rgba[v] = prim->verts[0].rgba[v]; } prim->verts[1].xyz[0] = prim->verts[1].xyz[0] + node->image->width; prim->verts[2].xyz[0] = prim->verts[1].xyz[0]; prim->verts[2].xyz[1] = prim->verts[2].xyz[1] + node->image->height; prim->verts[3].xyz[1] = prim->verts[2].xyz[1]; sizeoffloat = sizeof(GLfloat); v = 2 * sizeoffloat; vtot = node->image->height + node->image->height * ((node->image->width-1)/8); node->image->pixels = (GLfloat*)gl2psMalloc(v + vtot); node->image->pixels[0] = prim->verts[0].xyz[0]; node->image->pixels[1] = prim->verts[0].xyz[1]; for(i = 0; i < vtot; i += sizeoffloat){ current += 2; used -= 2; if((vtot - i) >= 4) memcpy(&(((char*)(node->image->pixels))[i + v]), &(current[2]), sizeoffloat); else memcpy(&(((char*)(node->image->pixels))[i + v]), &(current[2]), vtot - i); } current++; used--; gl2psListAdd(gl2ps->primitives, &prim); break; case GL2PS_DRAW_PIXELS_TOKEN : case GL2PS_TEXT_TOKEN : if(auxindex < gl2psListNbr(gl2ps->auxprimitives)) gl2psListAdd(gl2ps->primitives, gl2psListPointer(gl2ps->auxprimitives, auxindex++)); else gl2psMsg(GL2PS_ERROR, "Wrong number of auxiliary tokens in buffer"); break; } current += 2; used -= 2; break; default : gl2psMsg(GL2PS_WARNING, "Unknown token in buffer"); current ++; used --; break; } } gl2psListReset(gl2ps->auxprimitives); } /********************************************************************* * * PostScript routines * *********************************************************************/ static void gl2psWriteByte(unsigned char byte) { unsigned char h = byte / 16; unsigned char l = byte % 16; gl2psPrintf("%x%x", h, l); } static void gl2psPrintPostScriptPixmap(GLfloat x, GLfloat y, GL2PSimage *im) { GLuint nbyte, nrgb, nbits; GLuint row, col, ibyte, icase; GLfloat dr, dg, db; unsigned char red = 0, green = 0, blue = 0, b, grey; GLuint width = (GLuint)im->width; GLuint height = (GLuint)im->height; /* FIXME: should we define an option for these? Or just keep the 8-bit per component case? */ int greyscale = 0; /* set to 1 to output greyscale image */ int nbit = 8; /* number of bits per color compoment (2, 4 or 8) */ if((width <= 0) || (height <= 0)) return; gl2psPrintf("gsave\n"); gl2psPrintf("%.2f %.2f translate\n", x, y); gl2psPrintf("%d %d scale\n", width, height); if(greyscale){ /* greyscale */ gl2psPrintf("/picstr %d string def\n", width); gl2psPrintf("%d %d %d\n", width, height, 8); gl2psPrintf("[ %d 0 0 -%d 0 %d ]\n", width, height, height); gl2psPrintf("{ currentfile picstr readhexstring pop }\n"); gl2psPrintf("image\n"); GLfloat fgrey; for(row = 0; row < height; row++){ for(col = 0; col < width; col++){ gl2psGetRGB(im, col, row, &dr, &dg, &db); fgrey = (0.30f * dr + 0.59f * dg + 0.11f * db); grey = (unsigned char)(255. * fgrey); gl2psWriteByte(grey); } gl2psPrintf("\n"); } GLuint nbhex = width * height * 2; gl2psPrintf("%%%% nbhex digit :%d\n", nbhex); } else if(nbit == 2){ /* color, 2 bits for r and g and b; rgbs following each other */ nrgb = width * 3; nbits = nrgb * nbit; nbyte = nbits/8; if((nbyte * 8) != nbits) nbyte++; gl2psPrintf("/rgbstr %d string def\n", nbyte); gl2psPrintf("%d %d %d\n", width, height, nbit); gl2psPrintf("[ %d 0 0 -%d 0 %d ]\n", width, height, height); gl2psPrintf("{ currentfile rgbstr readhexstring pop }\n"); gl2psPrintf("false 3\n"); gl2psPrintf("colorimage\n"); for(row = 0; row < height; row++){ icase = 1; col = 0; b = 0; for(ibyte = 0; ibyte < nbyte; ibyte++){ if(icase == 1) { if(col < width) { gl2psGetRGB(im, col, row, &dr, &dg, &db); } else { dr = dg = db = 0; } col++; red = (unsigned char)(3. * dr); green = (unsigned char)(3. * dg); blue = (unsigned char)(3. * db); b = red; b = (b<<2) + green; b = (b<<2) + blue; if(col < width) { gl2psGetRGB(im, col, row, &dr, &dg, &db); } else { dr = dg = db = 0; } col++; red = (unsigned char)(3. * dr); green = (unsigned char)(3. * dg); blue = (unsigned char)(3. * db); b = (b<<2) + red; gl2psWriteByte(b); b = 0; icase++; } else if(icase == 2) { b = green; b = (b<<2) + blue; if(col < width) { gl2psGetRGB(im, col, row, &dr, &dg, &db); } else { dr = dg = db = 0; } col++; red = (unsigned char)(3. * dr); green = (unsigned char)(3. * dg); blue = (unsigned char)(3. * db); b = (b<<2) + red; b = (b<<2) + green; gl2psWriteByte(b); b = 0; icase++; } else if(icase == 3) { b = blue; if(col < width) { gl2psGetRGB(im, col, row, &dr, &dg, &db); } else { dr = dg = db = 0; } col++; red = (unsigned char)(3. * dr); green = (unsigned char)(3. * dg); blue = (unsigned char)(3. * db); b = (b<<2) + red; b = (b<<2) + green; b = (b<<2) + blue; gl2psWriteByte(b); b = 0; icase = 1; } } gl2psPrintf("\n"); } } else if(nbit == 4){ /* color, 4 bits for r and g and b; rgbs following each other */ nrgb = width * 3; nbits = nrgb * nbit; nbyte = nbits/8; if((nbyte * 8) != nbits) nbyte++; gl2psPrintf("/rgbstr %d string def\n", nbyte); gl2psPrintf("%d %d %d\n", width, height, nbit); gl2psPrintf("[ %d 0 0 -%d 0 %d ]\n", width, height, height); gl2psPrintf("{ currentfile rgbstr readhexstring pop }\n"); gl2psPrintf("false 3\n"); gl2psPrintf("colorimage\n"); for(row = 0; row < height; row++){ col = 0; icase = 1; for(ibyte = 0; ibyte < nbyte; ibyte++){ if(icase == 1) { if(col < width) { gl2psGetRGB(im, col, row, &dr, &dg, &db); } else { dr = dg = db = 0; } col++; red = (unsigned char)(15. * dr); green = (unsigned char)(15. * dg); gl2psPrintf("%x%x", red, green); icase++; } else if(icase == 2) { blue = (unsigned char)(15. * db); if(col < width) { gl2psGetRGB(im, col, row, &dr, &dg, &db); } else { dr = dg = db = 0; } col++; red = (unsigned char)(15. * dr); gl2psPrintf("%x%x", blue, red); icase++; } else if(icase == 3) { green = (unsigned char)(15. * dg); blue = (unsigned char)(15. * db); gl2psPrintf("%x%x", green, blue); icase = 1; } } gl2psPrintf("\n"); } } else{ /* 8 bit for r and g and b */ nbyte = width * 3; gl2psPrintf("/rgbstr %d string def\n", nbyte); gl2psPrintf("%d %d %d\n", width, height, 8); gl2psPrintf("[ %d 0 0 -%d 0 %d ]\n", width, height, height); gl2psPrintf("{ currentfile rgbstr readhexstring pop }\n"); gl2psPrintf("false 3\n"); gl2psPrintf("colorimage\n"); for(row = 0; row < height; row++){ for(col = 0; col < width; col++){ gl2psGetRGB(im, col, row, &dr, &dg, &db); red = (unsigned char)(255. * dr); gl2psWriteByte(red); green = (unsigned char)(255. * dg); gl2psWriteByte(green); blue = (unsigned char)(255. * db); gl2psWriteByte(blue); } gl2psPrintf("\n"); } } gl2psPrintf("grestore\n"); } static void gl2psPrintPostScriptImagemap(GLfloat x, GLfloat y, GLsizei width, GLsizei height, const unsigned char *imagemap){ int i, size; if((width <= 0) || (height <= 0)) return; size = height + height * (width-1)/8; gl2psPrintf("gsave\n"); gl2psPrintf("%.2f %.2f translate\n", x, y); gl2psPrintf("%d %d scale\n%d %d\ntrue\n", width, height,width, height); gl2psPrintf("[ %d 0 0 -%d 0 %d ] {<", width, height); for(i = 0; i < size; i++){ gl2psWriteByte(*imagemap); imagemap++; } gl2psPrintf(">} imagemask\ngrestore\n"); } static void gl2psPrintPostScriptHeader(void) { time_t now; /* Since compression is not part of the PostScript standard, compressed PostScript files are just gzipped PostScript files ("ps.gz" or "eps.gz") */ gl2psPrintGzipHeader(); time(&now); if(gl2ps->format == GL2PS_PS){ gl2psPrintf("%%!PS-Adobe-3.0\n"); } else{ gl2psPrintf("%%!PS-Adobe-3.0 EPSF-3.0\n"); } gl2psPrintf("%%%%Title: %s\n" "%%%%Creator: GL2PS %d.%d.%d%s, %s\n" "%%%%For: %s\n" "%%%%CreationDate: %s" "%%%%LanguageLevel: 3\n" "%%%%DocumentData: Clean7Bit\n" "%%%%Pages: 1\n", gl2ps->title, GL2PS_MAJOR_VERSION, GL2PS_MINOR_VERSION, GL2PS_PATCH_VERSION, GL2PS_EXTRA_VERSION, GL2PS_COPYRIGHT, gl2ps->producer, ctime(&now)); if(gl2ps->format == GL2PS_PS){ gl2psPrintf("%%%%Orientation: %s\n" "%%%%DocumentMedia: Default %d %d 0 () ()\n", (gl2ps->options & GL2PS_LANDSCAPE) ? "Landscape" : "Portrait", (gl2ps->options & GL2PS_LANDSCAPE) ? (int)gl2ps->viewport[3] : (int)gl2ps->viewport[2], (gl2ps->options & GL2PS_LANDSCAPE) ? (int)gl2ps->viewport[2] : (int)gl2ps->viewport[3]); } gl2psPrintf("%%%%BoundingBox: %d %d %d %d\n" "%%%%EndComments\n", (gl2ps->options & GL2PS_LANDSCAPE) ? (int)gl2ps->viewport[1] : (int)gl2ps->viewport[0], (gl2ps->options & GL2PS_LANDSCAPE) ? (int)gl2ps->viewport[0] : (int)gl2ps->viewport[1], (gl2ps->options & GL2PS_LANDSCAPE) ? (int)gl2ps->viewport[3] : (int)gl2ps->viewport[2], (gl2ps->options & GL2PS_LANDSCAPE) ? (int)gl2ps->viewport[2] : (int)gl2ps->viewport[3]); /* RGB color: r g b C (replace C by G in output to change from rgb to gray) Grayscale: r g b G Font choose: size fontname FC Text string: (string) x y size fontname S?? Rotated text string: (string) angle x y size fontname S??R Point primitive: x y size P Line width: width W Line start: x y LS Line joining last point: x y L Line end: x y LE Flat-shaded triangle: x3 y3 x2 y2 x1 y1 T Smooth-shaded triangle: x3 y3 r3 g3 b3 x2 y2 r2 g2 b2 x1 y1 r1 g1 b1 ST */ gl2psPrintf("%%%%BeginProlog\n" "/gl2psdict 64 dict def gl2psdict begin\n" "0 setlinecap 0 setlinejoin\n" "/tryPS3shading %s def %% set to false to force subdivision\n" "/rThreshold %g def %% red component subdivision threshold\n" "/gThreshold %g def %% green component subdivision threshold\n" "/bThreshold %g def %% blue component subdivision threshold\n", (gl2ps->options & GL2PS_NO_PS3_SHADING) ? "false" : "true", gl2ps->threshold[0], gl2ps->threshold[1], gl2ps->threshold[2]); gl2psPrintf("/BD { bind def } bind def\n" "/C { setrgbcolor } BD\n" "/G { 0.082 mul exch 0.6094 mul add exch 0.3086 mul add neg 1.0 add setgray } BD\n" "/W { setlinewidth } BD\n"); gl2psPrintf("/FC { findfont exch /SH exch def SH scalefont setfont } BD\n" "/SW { dup stringwidth pop } BD\n" "/S { FC moveto show } BD\n" "/SBC{ FC moveto SW -2 div 0 rmoveto show } BD\n" "/SBR{ FC moveto SW neg 0 rmoveto show } BD\n" "/SCL{ FC moveto 0 SH -2 div rmoveto show } BD\n" "/SCC{ FC moveto SW -2 div SH -2 div rmoveto show } BD\n" "/SCR{ FC moveto SW neg SH -2 div rmoveto show } BD\n" "/STL{ FC moveto 0 SH neg rmoveto show } BD\n" "/STC{ FC moveto SW -2 div SH neg rmoveto show } BD\n" "/STR{ FC moveto SW neg SH neg rmoveto show } BD\n"); /* rotated text routines: same nameanem with R appended */ gl2psPrintf("/FCT { FC translate 0 0 } BD\n" "/SR { gsave FCT moveto rotate show grestore } BD\n" "/SBCR{ gsave FCT moveto rotate SW -2 div 0 rmoveto show grestore } BD\n" "/SBRR{ gsave FCT moveto rotate SW neg 0 rmoveto show grestore } BD\n" "/SCLR{ gsave FCT moveto rotate 0 SH -2 div rmoveto show grestore} BD\n"); gl2psPrintf("/SCCR{ gsave FCT moveto rotate SW -2 div SH -2 div rmoveto show grestore} BD\n" "/SCRR{ gsave FCT moveto rotate SW neg SH -2 div rmoveto show grestore} BD\n" "/STLR{ gsave FCT moveto rotate 0 SH neg rmoveto show grestore } BD\n" "/STCR{ gsave FCT moveto rotate SW -2 div SH neg rmoveto show grestore } BD\n" "/STRR{ gsave FCT moveto rotate SW neg SH neg rmoveto show grestore } BD\n"); gl2psPrintf("/P { newpath 0.0 360.0 arc closepath fill } BD\n" "/LS { newpath moveto } BD\n" "/L { lineto } BD\n" "/LE { lineto stroke } BD\n" "/T { newpath moveto lineto lineto closepath fill } BD\n"); /* Smooth-shaded triangle with PostScript level 3 shfill operator: x3 y3 r3 g3 b3 x2 y2 r2 g2 b2 x1 y1 r1 g1 b1 STshfill */ gl2psPrintf("/STshfill {\n" " /b1 exch def /g1 exch def /r1 exch def /y1 exch def /x1 exch def\n" " /b2 exch def /g2 exch def /r2 exch def /y2 exch def /x2 exch def\n" " /b3 exch def /g3 exch def /r3 exch def /y3 exch def /x3 exch def\n" " gsave << /ShadingType 4 /ColorSpace [/DeviceRGB]\n" " /DataSource [ 0 x1 y1 r1 g1 b1 0 x2 y2 r2 g2 b2 0 x3 y3 r3 g3 b3 ] >>\n" " shfill grestore } BD\n"); /* Flat-shaded triangle with middle color: x3 y3 r3 g3 b3 x2 y2 r2 g2 b2 x1 y1 r1 g1 b1 Tm */ gl2psPrintf(/* stack : x3 y3 r3 g3 b3 x2 y2 r2 g2 b2 x1 y1 r1 g1 b1 */ "/Tm { 3 -1 roll 8 -1 roll 13 -1 roll add add 3 div\n" /* r = (r1+r2+r3)/3 */ /* stack : x3 y3 g3 b3 x2 y2 g2 b2 x1 y1 g1 b1 r */ " 3 -1 roll 7 -1 roll 11 -1 roll add add 3 div\n" /* g = (g1+g2+g3)/3 */ /* stack : x3 y3 b3 x2 y2 b2 x1 y1 b1 r g b */ " 3 -1 roll 6 -1 roll 9 -1 roll add add 3 div" /* b = (b1+b2+b3)/3 */ /* stack : x3 y3 x2 y2 x1 y1 r g b */ " C T } BD\n"); /* Split triangle in four sub-triangles (at sides middle points) and call the STnoshfill procedure on each, interpolating the colors in RGB space: x3 y3 r3 g3 b3 x2 y2 r2 g2 b2 x1 y1 r1 g1 b1 STsplit (in procedure comments key: (Vi) = xi yi ri gi bi) */ gl2psPrintf("/STsplit {\n" " 4 index 15 index add 0.5 mul\n" /* x13 = (x1+x3)/2 */ " 4 index 15 index add 0.5 mul\n" /* y13 = (y1+y3)/2 */ " 4 index 15 index add 0.5 mul\n" /* r13 = (r1+r3)/2 */ " 4 index 15 index add 0.5 mul\n" /* g13 = (g1+g3)/2 */ " 4 index 15 index add 0.5 mul\n" /* b13 = (b1+b3)/2 */ " 5 copy 5 copy 25 15 roll\n"); /* at his point, stack = (V3) (V13) (V13) (V13) (V2) (V1) */ gl2psPrintf(" 9 index 30 index add 0.5 mul\n" /* x23 = (x2+x3)/2 */ " 9 index 30 index add 0.5 mul\n" /* y23 = (y2+y3)/2 */ " 9 index 30 index add 0.5 mul\n" /* r23 = (r2+r3)/2 */ " 9 index 30 index add 0.5 mul\n" /* g23 = (g2+g3)/2 */ " 9 index 30 index add 0.5 mul\n" /* b23 = (b2+b3)/2 */ " 5 copy 5 copy 35 5 roll 25 5 roll 15 5 roll\n"); /* stack = (V3) (V13) (V23) (V13) (V23) (V13) (V23) (V2) (V1) */ gl2psPrintf(" 4 index 10 index add 0.5 mul\n" /* x12 = (x1+x2)/2 */ " 4 index 10 index add 0.5 mul\n" /* y12 = (y1+y2)/2 */ " 4 index 10 index add 0.5 mul\n" /* r12 = (r1+r2)/2 */ " 4 index 10 index add 0.5 mul\n" /* g12 = (g1+g2)/2 */ " 4 index 10 index add 0.5 mul\n" /* b12 = (b1+b2)/2 */ " 5 copy 5 copy 40 5 roll 25 5 roll 15 5 roll 25 5 roll\n"); /* stack = (V3) (V13) (V23) (V13) (V12) (V23) (V13) (V1) (V12) (V23) (V12) (V2) */ gl2psPrintf(" STnoshfill STnoshfill STnoshfill STnoshfill } BD\n"); /* Gouraud shaded triangle using recursive subdivision until the difference between corner colors does not exceed the thresholds: x3 y3 r3 g3 b3 x2 y2 r2 g2 b2 x1 y1 r1 g1 b1 STnoshfill */ gl2psPrintf("/STnoshfill {\n" " 2 index 8 index sub abs rThreshold gt\n" /* |r1-r2|>rth */ " { STsplit }\n" " { 1 index 7 index sub abs gThreshold gt\n" /* |g1-g2|>gth */ " { STsplit }\n" " { dup 6 index sub abs bThreshold gt\n" /* |b1-b2|>bth */ " { STsplit }\n" " { 2 index 13 index sub abs rThreshold gt\n" /* |r1-r3|>rht */ " { STsplit }\n" " { 1 index 12 index sub abs gThreshold gt\n" /* |g1-g3|>gth */ " { STsplit }\n" " { dup 11 index sub abs bThreshold gt\n" /* |b1-b3|>bth */ " { STsplit }\n" " { 7 index 13 index sub abs rThreshold gt\n"); /* |r2-r3|>rht */ gl2psPrintf(" { STsplit }\n" " { 6 index 12 index sub abs gThreshold gt\n" /* |g2-g3|>gth */ " { STsplit }\n" " { 5 index 11 index sub abs bThreshold gt\n" /* |b2-b3|>bth */ " { STsplit }\n" " { Tm }\n" /* all colors sufficiently similar */ " ifelse }\n" " ifelse }\n" " ifelse }\n" " ifelse }\n" " ifelse }\n" " ifelse }\n" " ifelse }\n" " ifelse }\n" " ifelse } BD\n"); gl2psPrintf("tryPS3shading\n" "{ /shfill where\n" " { /ST { STshfill } BD }\n" " { /ST { STnoshfill } BD }\n" " ifelse }\n" "{ /ST { STnoshfill } BD }\n" "ifelse\n"); gl2psPrintf("end\n" "%%%%EndProlog\n" "%%%%BeginSetup\n" "/DeviceRGB setcolorspace\n" "gl2psdict begin\n" "%%%%EndSetup\n" "%%%%Page: 1 1\n" "%%%%BeginPageSetup\n"); if(gl2ps->options & GL2PS_LANDSCAPE){ gl2psPrintf("%d 0 translate 90 rotate\n", (int)gl2ps->viewport[3]); } gl2psPrintf("%%%%EndPageSetup\n" "mark\n" "gsave\n" "1.0 1.0 scale\n"); if(gl2ps->options & GL2PS_DRAW_BACKGROUND){ gl2psPrintf("%g %g %g C\n" "newpath %d %d moveto %d %d lineto %d %d lineto %d %d lineto\n" "closepath fill\n", gl2ps->bgcolor[0], gl2ps->bgcolor[1], gl2ps->bgcolor[2], (int)gl2ps->viewport[0], (int)gl2ps->viewport[1], (int)gl2ps->viewport[2], (int)gl2ps->viewport[1], (int)gl2ps->viewport[2], (int)gl2ps->viewport[3], (int)gl2ps->viewport[0], (int)gl2ps->viewport[3]); } } static void gl2psPrintPostScriptColor(GL2PSrgba rgba) { if(!gl2psSameColor(gl2ps->lastrgba, rgba)){ gl2psSetLastColor(rgba); gl2psPrintf("%g %g %g C\n", rgba[0], rgba[1], rgba[2]); } } static void gl2psResetPostScriptColor(void) { gl2ps->lastrgba[0] = gl2ps->lastrgba[1] = gl2ps->lastrgba[2] = -1.; } static void gl2psEndPostScriptLine(void) { if(gl2ps->lastvertex.rgba[0] >= 0.){ gl2psPrintf("%g %g LE\n", gl2ps->lastvertex.xyz[0], gl2ps->lastvertex.xyz[1]); int i =0; for(;i < 3; i++) gl2ps->lastvertex.xyz[i] = -1.; for(i = 0; i < 4; i++) gl2ps->lastvertex.rgba[i] = -1.; } } static void gl2psParseStipplePattern(GLushort pattern, GLint factor, int *nb, int array[10]) { int i, n; int on[8] = {0, 0, 0, 0, 0, 0, 0, 0}; int off[8] = {0, 0, 0, 0, 0, 0, 0, 0}; char tmp[16]; /* extract the 16 bits from the OpenGL stipple pattern */ for(n = 15; n >= 0; n--){ tmp[n] = (char)(pattern & 0x01); pattern >>= 1; } /* compute the on/off pixel sequence */ n = 0; for(i = 0; i < 8; i++){ while(n < 16 && !tmp[n]){ off[i]++; n++; } while(n < 16 && tmp[n]){ on[i]++; n++; } if(n >= 15){ i++; break; } } /* store the on/off array from right to left, starting with off pixels. The PostScript specification allows for at most 11 elements in the on/off array, so we limit ourselves to 5 on/off couples (our longest possible array is thus [on4 off4 on3 off3 on2 off2 on1 off1 on0 off0]) */ *nb = 0; for(n = i - 1; n >= 0; n--){ array[(*nb)++] = factor * on[n]; array[(*nb)++] = factor * off[n]; if(*nb == 10) break; } } static int gl2psPrintPostScriptDash(GLushort pattern, GLint factor, const char *str) { int len = 0, n, array[10]; if(pattern == gl2ps->lastpattern && factor == gl2ps->lastfactor) return 0; gl2ps->lastpattern = pattern; gl2ps->lastfactor = factor; if(!pattern || !factor){ /* solid line */ len += gl2psPrintf("[] 0 %s\n", str); } else{ gl2psParseStipplePattern(pattern, factor, &n, array); len += gl2psPrintf("["); int i = 0; for(; i < n; i++){ if(i) len += gl2psPrintf(" "); len += gl2psPrintf("%d", array[i]); } len += gl2psPrintf("] 0 %s\n", str); } return len; } static void gl2psPrintPostScriptPrimitive(void *data) { int newline; GL2PSprimitive *prim; prim = *(GL2PSprimitive**)data; if((gl2ps->options & GL2PS_OCCLUSION_CULL) && prim->culled) return; /* Every effort is made to draw lines as connected segments (i.e., using a single PostScript path): this is the only way to get nice line joins and to not restart the stippling for every line segment. So if the primitive to print is not a line we must first finish the current line (if any): */ if(prim->type != GL2PS_LINE) gl2psEndPostScriptLine(); switch(prim->type){ case GL2PS_POINT : gl2psPrintPostScriptColor(prim->verts[0].rgba); gl2psPrintf("%g %g %g P\n", prim->verts[0].xyz[0], prim->verts[0].xyz[1], 0.5 * prim->width); break; case GL2PS_LINE : if(!gl2psSamePosition(gl2ps->lastvertex.xyz, prim->verts[0].xyz) || !gl2psSameColor(gl2ps->lastrgba, prim->verts[0].rgba) || gl2ps->lastlinewidth != prim->width || gl2ps->lastpattern != prim->pattern || gl2ps->lastfactor != prim->factor){ /* End the current line if the new segment does not start where the last one ended, or if the color, the width or the stippling have changed (multi-stroking lines with changing colors is necessary until we use /shfill for lines; unfortunately this means that at the moment we can screw up line stippling for smooth-shaded lines) */ gl2psEndPostScriptLine(); newline = 1; } else{ newline = 0; } if(gl2ps->lastlinewidth != prim->width){ gl2ps->lastlinewidth = prim->width; gl2psPrintf("%g W\n", gl2ps->lastlinewidth); } gl2psPrintPostScriptDash(prim->pattern, prim->factor, "setdash"); gl2psPrintPostScriptColor(prim->verts[0].rgba); gl2psPrintf("%g %g %s\n", prim->verts[0].xyz[0], prim->verts[0].xyz[1], newline ? "LS" : "L"); gl2ps->lastvertex = prim->verts[1]; break; case GL2PS_TRIANGLE : if(!gl2psVertsSameColor(prim)){ gl2psResetPostScriptColor(); gl2psPrintf("%g %g %g %g %g %g %g %g %g %g %g %g %g %g %g ST\n", prim->verts[2].xyz[0], prim->verts[2].xyz[1], prim->verts[2].rgba[0], prim->verts[2].rgba[1], prim->verts[2].rgba[2], prim->verts[1].xyz[0], prim->verts[1].xyz[1], prim->verts[1].rgba[0], prim->verts[1].rgba[1], prim->verts[1].rgba[2], prim->verts[0].xyz[0], prim->verts[0].xyz[1], prim->verts[0].rgba[0], prim->verts[0].rgba[1], prim->verts[0].rgba[2]); } else{ gl2psPrintPostScriptColor(prim->verts[0].rgba); gl2psPrintf("%g %g %g %g %g %g T\n", prim->verts[2].xyz[0], prim->verts[2].xyz[1], prim->verts[1].xyz[0], prim->verts[1].xyz[1], prim->verts[0].xyz[0], prim->verts[0].xyz[1]); } break; case GL2PS_QUADRANGLE : gl2psMsg(GL2PS_WARNING, "There should not be any quad left to print"); break; case GL2PS_PIXMAP : gl2psPrintPostScriptPixmap(prim->verts[0].xyz[0], prim->verts[0].xyz[1], prim->data.image); break; case GL2PS_IMAGEMAP : if(prim->data.image->type != GL2PS_IMAGEMAP_WRITTEN){ gl2psPrintPostScriptColor(prim->verts[0].rgba); gl2psPrintPostScriptImagemap(prim->data.image->pixels[0], prim->data.image->pixels[1], prim->data.image->width, prim->data.image->height, (const unsigned char*)(&(prim->data.image->pixels[2]))); prim->data.image->type = GL2PS_IMAGEMAP_WRITTEN; } break; case GL2PS_TEXT : gl2psPrintPostScriptColor(prim->verts[0].rgba); gl2psPrintf("(%s) ", prim->data.text->str); if(prim->data.text->angle) gl2psPrintf("%g ", prim->data.text->angle); gl2psPrintf("%g %g %d /%s ", prim->verts[0].xyz[0], prim->verts[0].xyz[1], prim->data.text->fontsize, prim->data.text->fontname); switch(prim->data.text->alignment){ case GL2PS_TEXT_C: gl2psPrintf(prim->data.text->angle ? "SCCR\n" : "SCC\n"); break; case GL2PS_TEXT_CL: gl2psPrintf(prim->data.text->angle ? "SCLR\n" : "SCL\n"); break; case GL2PS_TEXT_CR: gl2psPrintf(prim->data.text->angle ? "SCRR\n" : "SCR\n"); break; case GL2PS_TEXT_B: gl2psPrintf(prim->data.text->angle ? "SBCR\n" : "SBC\n"); break; case GL2PS_TEXT_BR: gl2psPrintf(prim->data.text->angle ? "SBRR\n" : "SBR\n"); break; case GL2PS_TEXT_T: gl2psPrintf(prim->data.text->angle ? "STCR\n" : "STC\n"); break; case GL2PS_TEXT_TL: gl2psPrintf(prim->data.text->angle ? "STLR\n" : "STL\n"); break; case GL2PS_TEXT_TR: gl2psPrintf(prim->data.text->angle ? "STRR\n" : "STR\n"); break; case GL2PS_TEXT_BL: default: gl2psPrintf(prim->data.text->angle ? "SR\n" : "S\n"); break; } break; case GL2PS_SPECIAL : /* alignment contains the format for which the special output text is intended */ if(prim->data.text->alignment == GL2PS_PS || prim->data.text->alignment == GL2PS_EPS) gl2psPrintf("%s\n", prim->data.text->str); break; default : break; } } static void gl2psPrintPostScriptFooter(void) { gl2psPrintf("grestore\n" "showpage\n" "cleartomark\n" "%%%%PageTrailer\n" "%%%%Trailer\n" "end\n" "%%%%EOF\n"); gl2psPrintGzipFooter(); } static void gl2psPrintPostScriptBeginViewport(GLint viewport[4]) { GLint index; GLfloat rgba[4]; int x = viewport[0], y = viewport[1], w = viewport[2], h = viewport[3]; glRenderMode(GL_FEEDBACK); if(gl2ps->header){ gl2psPrintPostScriptHeader(); gl2ps->header = GL_FALSE; } gl2psPrintf("gsave\n" "1.0 1.0 scale\n"); if(gl2ps->options & GL2PS_DRAW_BACKGROUND){ if(gl2ps->colormode == GL_RGBA || gl2ps->colorsize == 0){ glGetFloatv(GL_COLOR_CLEAR_VALUE, rgba); } else{ glGetIntegerv(GL_INDEX_CLEAR_VALUE, &index); rgba[0] = gl2ps->colormap[index][0]; rgba[1] = gl2ps->colormap[index][1]; rgba[2] = gl2ps->colormap[index][2]; rgba[3] = 1.0F; } gl2psPrintf("%g %g %g C\n" "newpath %d %d moveto %d %d lineto %d %d lineto %d %d lineto\n" "closepath fill\n", rgba[0], rgba[1], rgba[2], x, y, x+w, y, x+w, y+h, x, y+h); } gl2psPrintf("newpath %d %d moveto %d %d lineto %d %d lineto %d %d lineto\n" "closepath clip\n", x, y, x+w, y, x+w, y+h, x, y+h); } static GLint gl2psPrintPostScriptEndViewport(void) { GLint res; res = gl2psPrintPrimitives(); gl2psPrintf("grestore\n"); return res; } static void gl2psPrintPostScriptFinalPrimitive(void) { /* End any remaining line, if any */ gl2psEndPostScriptLine(); } /* definition of the PostScript and Encapsulated PostScript backends */ static GL2PSbackend gl2psPS = { gl2psPrintPostScriptHeader, gl2psPrintPostScriptFooter, gl2psPrintPostScriptBeginViewport, gl2psPrintPostScriptEndViewport, gl2psPrintPostScriptPrimitive, gl2psPrintPostScriptFinalPrimitive, "ps", "Postscript" }; static GL2PSbackend gl2psEPS = { gl2psPrintPostScriptHeader, gl2psPrintPostScriptFooter, gl2psPrintPostScriptBeginViewport, gl2psPrintPostScriptEndViewport, gl2psPrintPostScriptPrimitive, gl2psPrintPostScriptFinalPrimitive, "eps", "Encapsulated Postscript" }; /********************************************************************* * * LaTeX routines * *********************************************************************/ static void gl2psPrintTeXHeader(void) { char name[256]; time_t now; if(gl2ps->filename && strlen(gl2ps->filename) < 256){ int i = strlen(gl2ps->filename)-1; for(; i >= 0; i--){ if(gl2ps->filename[i] == '.'){ strncpy(name, gl2ps->filename, i); name[i] = '\0'; break; } } if(i <= 0) strcpy(name, gl2ps->filename); } else{ strcpy(name, "untitled"); } time(&now); fprintf(gl2ps->stream, "%% Title: %s\n" "%% Creator: GL2PS %d.%d.%d%s, %s\n" "%% For: %s\n" "%% CreationDate: %s", gl2ps->title, GL2PS_MAJOR_VERSION, GL2PS_MINOR_VERSION, GL2PS_PATCH_VERSION, GL2PS_EXTRA_VERSION, GL2PS_COPYRIGHT, gl2ps->producer, ctime(&now)); fprintf(gl2ps->stream, "\\setlength{\\unitlength}{1pt}\n" "\\begin{picture}(0,0)\n" "\\includegraphics{%s}\n" "\\end{picture}%%\n" "%s\\begin{picture}(%d,%d)(0,0)\n", name, (gl2ps->options & GL2PS_LANDSCAPE) ? "\\rotatebox{90}{" : "", (int)gl2ps->viewport[2], (int)gl2ps->viewport[3]); } static void gl2psPrintTeXPrimitive(void *data) { GL2PSprimitive *prim; prim = *(GL2PSprimitive**)data; switch(prim->type){ case GL2PS_TEXT : fprintf(gl2ps->stream, "\\fontsize{%d}{0}\n\\selectfont", prim->data.text->fontsize); fprintf(gl2ps->stream, "\\put(%g,%g){\\makebox(0,0)", prim->verts[0].xyz[0], prim->verts[0].xyz[1]); switch(prim->data.text->alignment){ case GL2PS_TEXT_C: fprintf(gl2ps->stream, "{"); break; case GL2PS_TEXT_CL: fprintf(gl2ps->stream, "[l]{"); break; case GL2PS_TEXT_CR: fprintf(gl2ps->stream, "[r]{"); break; case GL2PS_TEXT_B: fprintf(gl2ps->stream, "[b]{"); break; case GL2PS_TEXT_BR: fprintf(gl2ps->stream, "[br]{"); break; case GL2PS_TEXT_T: fprintf(gl2ps->stream, "[t]{"); break; case GL2PS_TEXT_TL: fprintf(gl2ps->stream, "[tl]{"); break; case GL2PS_TEXT_TR: fprintf(gl2ps->stream, "[tr]{"); break; case GL2PS_TEXT_BL: default: fprintf(gl2ps->stream, "[bl]{"); break; } if(prim->data.text->angle) fprintf(gl2ps->stream, "\\rotatebox{%g}{", prim->data.text->angle); fprintf(gl2ps->stream, "\\textcolor[rgb]{%g,%g,%g}{{%s}}", prim->verts[0].rgba[0], prim->verts[0].rgba[1], prim->verts[0].rgba[2], prim->data.text->str); if(prim->data.text->angle) fprintf(gl2ps->stream, "}"); fprintf(gl2ps->stream, "}}\n"); break; case GL2PS_SPECIAL : /* alignment contains the format for which the special output text is intended */ if (prim->data.text->alignment == GL2PS_TEX) fprintf(gl2ps->stream, "%s\n", prim->data.text->str); break; default : break; } } static void gl2psPrintTeXFooter(void) { fprintf(gl2ps->stream, "\\end{picture}%s\n", (gl2ps->options & GL2PS_LANDSCAPE) ? "}" : ""); } static void gl2psPrintTeXBeginViewport(GLint viewport[4]) { Q_UNUSED(viewport); glRenderMode(GL_FEEDBACK); if(gl2ps->header){ gl2psPrintTeXHeader(); gl2ps->header = GL_FALSE; } } static GLint gl2psPrintTeXEndViewport(void) { return gl2psPrintPrimitives(); } static void gl2psPrintTeXFinalPrimitive(void) { } /* definition of the LaTeX backend */ static GL2PSbackend gl2psTEX = { gl2psPrintTeXHeader, gl2psPrintTeXFooter, gl2psPrintTeXBeginViewport, gl2psPrintTeXEndViewport, gl2psPrintTeXPrimitive, gl2psPrintTeXFinalPrimitive, "tex", "LaTeX text" }; /********************************************************************* * * PDF routines * *********************************************************************/ static int gl2psPrintPDFCompressorType(void) { #if defined(GL2PS_HAVE_ZLIB) if(gl2ps->options & GL2PS_COMPRESS){ return fprintf(gl2ps->stream, "/Filter [/FlateDecode]\n"); } #endif return 0; } static int gl2psPrintPDFStrokeColor(GL2PSrgba rgba) { int i, offs = 0; gl2psSetLastColor(rgba); for(i = 0; i < 3; ++i){ if(GL2PS_ZERO(rgba[i])) offs += gl2psPrintf("%.0f ", 0.); else if(rgba[i] < 1e-4 || rgba[i] > 1e6) /* avoid %e formatting */ offs += gl2psPrintf("%f ", rgba[i]); else offs += gl2psPrintf("%g ", rgba[i]); } offs += gl2psPrintf("RG\n"); return offs; } static int gl2psPrintPDFFillColor(GL2PSrgba rgba) { int i, offs = 0; for(i = 0; i < 3; ++i){ if(GL2PS_ZERO(rgba[i])) offs += gl2psPrintf("%.0f ", 0.); else if(rgba[i] < 1e-4 || rgba[i] > 1e6) /* avoid %e formatting */ offs += gl2psPrintf("%f ", rgba[i]); else offs += gl2psPrintf("%g ", rgba[i]); } offs += gl2psPrintf("rg\n"); return offs; } static int gl2psPrintPDFLineWidth(GLfloat lw) { if(GL2PS_ZERO(lw)) return gl2psPrintf("%.0f w\n", 0.); else if(lw < 1e-4 || lw > 1e6) /* avoid %e formatting */ return gl2psPrintf("%f w\n", lw); else return gl2psPrintf("%g w\n", lw); } static void gl2psPutPDFText(GL2PSstring *text, int cnt, GLfloat x, GLfloat y) { gl2ps->streamlength += gl2psPrintf("BT\n" "/F%d %d Tf\n" "%f %f Td\n" "(%s) Tj\n" "ET\n", cnt, text->fontsize, x, y, text->str); } static void gl2psPutPDFImage(GL2PSimage *image, int cnt, GLfloat x, GLfloat y) { gl2ps->streamlength += gl2psPrintf("q\n" "%d 0 0 %d %f %f cm\n" "/Im%d Do\n" "Q\n", (int)image->width, (int)image->height, x, y, cnt); } static void gl2psPDFstacksInit(void) { gl2ps->objects_stack = 7 /* FIXED_XREF_ENTRIES */ + 1; gl2ps->extgs_stack = 0; gl2ps->font_stack = 0; gl2ps->im_stack = 0; gl2ps->trgroupobjects_stack = 0; gl2ps->shader_stack = 0; gl2ps->mshader_stack = 0; } static void gl2psPDFgroupObjectInit(GL2PSpdfgroup *gro) { if(!gro) return; gro->ptrlist = NULL; gro->fontno = gro->gsno = gro->imno = gro->maskshno = gro->shno = gro->trgroupno = gro->fontobjno = gro->imobjno = gro->shobjno = gro->maskshobjno = gro->gsobjno = gro->trgroupobjno = -1; } /* Build up group objects and assign name and object numbers */ static void gl2psPDFgroupListInit(void) { int i; GL2PSprimitive *p = NULL; GL2PSpdfgroup gro; int lasttype = GL2PS_NO_TYPE; GL2PSrgba lastrgba = {-1.0F, -1.0F, -1.0F, -1.0F}; GLushort lastpattern = 0; GLint lastfactor = 0; GLfloat lastwidth = 1; GL2PStriangle lastt, tmpt; int lastTriangleWasNotSimpleWithSameColor = 0; if(!gl2ps->pdfprimlist) return; gl2ps->pdfgrouplist = gl2psListCreate(500, 500, sizeof(GL2PSpdfgroup)); gl2psInitTriangle(&lastt); for(i = 0; i < gl2psListNbr(gl2ps->pdfprimlist); ++i){ p = *(GL2PSprimitive**)gl2psListPointer(gl2ps->pdfprimlist, i); switch(p->type){ case GL2PS_PIXMAP: gl2psPDFgroupObjectInit(&gro); gro.ptrlist = gl2psListCreate(1, 2, sizeof(GL2PSprimitive*)); gro.imno = gl2ps->im_stack++; gl2psListAdd(gro.ptrlist, &p); gl2psListAdd(gl2ps->pdfgrouplist, &gro); break; case GL2PS_TEXT: gl2psPDFgroupObjectInit(&gro); gro.ptrlist = gl2psListCreate(1, 2, sizeof(GL2PSprimitive*)); gro.fontno = gl2ps->font_stack++; gl2psListAdd(gro.ptrlist, &p); gl2psListAdd(gl2ps->pdfgrouplist, &gro); break; case GL2PS_LINE: if(lasttype != p->type || lastwidth != p->width || lastpattern != p->pattern || lastfactor != p->factor || !gl2psSameColor(p->verts[0].rgba, lastrgba)){ gl2psPDFgroupObjectInit(&gro); gro.ptrlist = gl2psListCreate(1, 2, sizeof(GL2PSprimitive*)); gl2psListAdd(gro.ptrlist, &p); gl2psListAdd(gl2ps->pdfgrouplist, &gro); } else{ gl2psListAdd(gro.ptrlist, &p); } lastpattern = p->pattern; lastfactor = p->factor; lastwidth = p->width; lastrgba[0] = p->verts[0].rgba[0]; lastrgba[1] = p->verts[0].rgba[1]; lastrgba[2] = p->verts[0].rgba[2]; break; case GL2PS_POINT: if(lasttype != p->type || lastwidth != p->width || !gl2psSameColor(p->verts[0].rgba, lastrgba)){ gl2psPDFgroupObjectInit(&gro); gro.ptrlist = gl2psListCreate(1,2,sizeof(GL2PSprimitive*)); gl2psListAdd(gro.ptrlist, &p); gl2psListAdd(gl2ps->pdfgrouplist, &gro); } else{ gl2psListAdd(gro.ptrlist, &p); } lastwidth = p->width; lastrgba[0] = p->verts[0].rgba[0]; lastrgba[1] = p->verts[0].rgba[1]; lastrgba[2] = p->verts[0].rgba[2]; break; case GL2PS_TRIANGLE: gl2psFillTriangleFromPrimitive(&tmpt, p, GL_TRUE); lastTriangleWasNotSimpleWithSameColor = !(tmpt.prop & T_CONST_COLOR && tmpt.prop & T_ALPHA_1) || !gl2psSameColor(tmpt.vertex[0].rgba, lastt.vertex[0].rgba); if(lasttype == p->type && tmpt.prop == lastt.prop && lastTriangleWasNotSimpleWithSameColor){ /* TODO Check here for last alpha */ gl2psListAdd(gro.ptrlist, &p); } else{ gl2psPDFgroupObjectInit(&gro); gro.ptrlist = gl2psListCreate(1, 2, sizeof(GL2PSprimitive*)); gl2psListAdd(gro.ptrlist, &p); gl2psListAdd(gl2ps->pdfgrouplist, &gro); } lastt = tmpt; break; default: break; } lasttype = p->type; } } static void gl2psSortOutTrianglePDFgroup(GL2PSpdfgroup *gro) { GL2PStriangle t; GL2PSprimitive *prim = NULL; if(!gro) return; if(!gl2psListNbr(gro->ptrlist)) return; prim = *(GL2PSprimitive**)gl2psListPointer(gro->ptrlist, 0); if(prim->type != GL2PS_TRIANGLE) return; gl2psFillTriangleFromPrimitive(&t, prim, GL_TRUE); if(t.prop & T_CONST_COLOR && t.prop & T_ALPHA_LESS_1){ gro->gsno = gl2ps->extgs_stack++; gro->gsobjno = gl2ps->objects_stack ++; } else if(t.prop & T_CONST_COLOR && t.prop & T_VAR_ALPHA){ gro->gsno = gl2ps->extgs_stack++; gro->gsobjno = gl2ps->objects_stack++; gro->trgroupno = gl2ps->trgroupobjects_stack++; gro->trgroupobjno = gl2ps->objects_stack++; gro->maskshno = gl2ps->mshader_stack++; gro->maskshobjno = gl2ps->objects_stack++; } else if(t.prop & T_VAR_COLOR && t.prop & T_ALPHA_1){ gro->shno = gl2ps->shader_stack++; gro->shobjno = gl2ps->objects_stack++; } else if(t.prop & T_VAR_COLOR && t.prop & T_ALPHA_LESS_1){ gro->gsno = gl2ps->extgs_stack++; gro->gsobjno = gl2ps->objects_stack++; gro->shno = gl2ps->shader_stack++; gro->shobjno = gl2ps->objects_stack++; } else if(t.prop & T_VAR_COLOR && t.prop & T_VAR_ALPHA){ gro->gsno = gl2ps->extgs_stack++; gro->gsobjno = gl2ps->objects_stack++; gro->shno = gl2ps->shader_stack++; gro->shobjno = gl2ps->objects_stack++; gro->trgroupno = gl2ps->trgroupobjects_stack++; gro->trgroupobjno = gl2ps->objects_stack++; gro->maskshno = gl2ps->mshader_stack++; gro->maskshobjno = gl2ps->objects_stack++; } } /* Main stream data */ static void gl2psPDFgroupListWriteMainStream(void) { int i, j, lastel; GL2PSprimitive *prim = NULL, *prev = NULL; GL2PSpdfgroup *gro; GL2PStriangle t; if(!gl2ps->pdfgrouplist) return; for(i = 0; i < gl2psListNbr(gl2ps->pdfgrouplist); ++i){ gro = (GL2PSpdfgroup*)gl2psListPointer(gl2ps->pdfgrouplist, i); lastel = gl2psListNbr(gro->ptrlist) - 1; if(lastel < 0) continue; prim = *(GL2PSprimitive**)gl2psListPointer(gro->ptrlist, 0); switch(prim->type){ case GL2PS_POINT: gl2ps->streamlength += gl2psPrintf("1 J\n"); gl2ps->streamlength += gl2psPrintPDFLineWidth(prim->width); gl2ps->streamlength += gl2psPrintPDFStrokeColor(prim->verts[0].rgba); for(j = 0; j <= lastel; ++j){ prim = *(GL2PSprimitive**)gl2psListPointer(gro->ptrlist, j); gl2ps->streamlength += gl2psPrintf("%f %f m %f %f l\n", prim->verts[0].xyz[0], prim->verts[0].xyz[1], prim->verts[0].xyz[0], prim->verts[0].xyz[1]); } gl2ps->streamlength += gl2psPrintf("S\n"); gl2ps->streamlength += gl2psPrintf("0 J\n"); break; case GL2PS_LINE: /* We try to use as few paths as possible to draw lines, in order to get nice stippling even when the individual segments are smaller than the stipple */ gl2ps->streamlength += gl2psPrintPDFLineWidth(prim->width); gl2ps->streamlength += gl2psPrintPDFStrokeColor(prim->verts[0].rgba); gl2ps->streamlength += gl2psPrintPostScriptDash(prim->pattern, prim->factor, "d"); /* start new path */ gl2ps->streamlength += gl2psPrintf("%f %f m\n", prim->verts[0].xyz[0], prim->verts[0].xyz[1]); for(j = 1; j <= lastel; ++j){ prev = prim; prim = *(GL2PSprimitive**)gl2psListPointer(gro->ptrlist, j); if(!gl2psSamePosition(prim->verts[0].xyz, prev->verts[1].xyz)){ /* the starting point of the new segment does not match the end point of the previous line, so we end the current path and start a new one */ gl2ps->streamlength += gl2psPrintf("%f %f l\n", prev->verts[1].xyz[0], prev->verts[1].xyz[1]); gl2ps->streamlength += gl2psPrintf("%f %f m\n", prim->verts[0].xyz[0], prim->verts[0].xyz[1]); } else{ /* the two segements are connected, so we just append to the current path */ gl2ps->streamlength += gl2psPrintf("%f %f l\n", prim->verts[0].xyz[0], prim->verts[0].xyz[1]); } } /* end last path */ gl2ps->streamlength += gl2psPrintf("%f %f l\n", prim->verts[1].xyz[0], prim->verts[1].xyz[1]); gl2ps->streamlength += gl2psPrintf("S\n"); break; case GL2PS_TRIANGLE: gl2psFillTriangleFromPrimitive(&t, prim, GL_TRUE); gl2psSortOutTrianglePDFgroup(gro); /* No alpha and const color: Simple PDF draw orders */ if(t.prop & T_CONST_COLOR && t.prop & T_ALPHA_1){ gl2ps->streamlength += gl2psPrintPDFFillColor(t.vertex[0].rgba); for(j = 0; j <= lastel; ++j){ prim = *(GL2PSprimitive**)gl2psListPointer(gro->ptrlist, j); gl2psFillTriangleFromPrimitive(&t, prim, GL_FALSE); gl2ps->streamlength += gl2psPrintf("%f %f m\n" "%f %f l\n" "%f %f l\n" "h f\n", t.vertex[0].xyz[0], t.vertex[0].xyz[1], t.vertex[1].xyz[0], t.vertex[1].xyz[1], t.vertex[2].xyz[0], t.vertex[2].xyz[1]); } } /* Const alpha < 1 and const color: Simple PDF draw orders and an extra extended Graphics State for the alpha const */ else if(t.prop & T_CONST_COLOR && t.prop & T_ALPHA_LESS_1){ gl2ps->streamlength += gl2psPrintf("q\n" "/GS%d gs\n", gro->gsno); gl2ps->streamlength += gl2psPrintPDFFillColor(prim->verts[0].rgba); for(j = 0; j <= lastel; ++j){ prim = *(GL2PSprimitive**)gl2psListPointer(gro->ptrlist, j); gl2psFillTriangleFromPrimitive(&t, prim, GL_FALSE); gl2ps->streamlength += gl2psPrintf("%f %f m\n" "%f %f l\n" "%f %f l\n" "h f\n", t.vertex[0].xyz[0], t.vertex[0].xyz[1], t.vertex[1].xyz[0], t.vertex[1].xyz[1], t.vertex[2].xyz[0], t.vertex[2].xyz[1]); } gl2ps->streamlength += gl2psPrintf("Q\n"); } /* Variable alpha and const color: Simple PDF draw orders and an extra extended Graphics State + Xobject + Shader object for the alpha mask */ else if(t.prop & T_CONST_COLOR && t.prop & T_VAR_ALPHA){ gl2ps->streamlength += gl2psPrintf("q\n" "/GS%d gs\n" "/TrG%d Do\n", gro->gsno, gro->trgroupno); gl2ps->streamlength += gl2psPrintPDFFillColor(prim->verts[0].rgba); for(j = 0; j <= lastel; ++j){ prim = *(GL2PSprimitive**)gl2psListPointer(gro->ptrlist, j); gl2psFillTriangleFromPrimitive(&t, prim, GL_FALSE); gl2ps->streamlength += gl2psPrintf("%f %f m\n" "%f %f l\n" "%f %f l\n" "h f\n", t.vertex[0].xyz[0], t.vertex[0].xyz[1], t.vertex[1].xyz[0], t.vertex[1].xyz[1], t.vertex[2].xyz[0], t.vertex[2].xyz[1]); } gl2ps->streamlength += gl2psPrintf("Q\n"); } /* Variable color and no alpha: Shader Object for the colored triangle(s) */ else if(t.prop & T_VAR_COLOR && t.prop & T_ALPHA_1){ gl2ps->streamlength += gl2psPrintf("/Sh%d sh\n", gro->shno); } /* Variable color and const alpha < 1: Shader Object for the colored triangle(s) and an extra extended Graphics State for the alpha const */ else if(t.prop & T_VAR_COLOR && t.prop & T_ALPHA_LESS_1){ gl2ps->streamlength += gl2psPrintf("q\n" "/GS%d gs\n" "/Sh%d sh\n" "Q\n", gro->gsno, gro->shno); } /* Variable alpha and color: Shader Object for the colored triangle(s) and an extra extended Graphics State + Xobject + Shader object for the alpha mask */ else if(t.prop & T_VAR_COLOR && t.prop & T_VAR_ALPHA){ gl2ps->streamlength += gl2psPrintf("q\n" "/GS%d gs\n" "/TrG%d Do\n" "/Sh%d sh\n" "Q\n", gro->gsno, gro->trgroupno, gro->shno); } break; case GL2PS_PIXMAP: for(j = 0; j <= lastel; ++j){ prim = *(GL2PSprimitive**)gl2psListPointer(gro->ptrlist, j); gl2psPutPDFImage(prim->data.image, gro->imno, prim->verts[0].xyz[0], prim->verts[0].xyz[1]); } break; case GL2PS_TEXT: for(j = 0; j <= lastel; ++j){ prim = *(GL2PSprimitive**)gl2psListPointer(gro->ptrlist, j); gl2ps->streamlength += gl2psPrintPDFFillColor(prim->verts[0].rgba); gl2psPutPDFText(prim->data.text, gro->fontno, prim->verts[0].xyz[0], prim->verts[0].xyz[1]); } break; default: break; } } } /* Graphics State names */ static int gl2psPDFgroupListWriteGStateResources(void) { GL2PSpdfgroup *gro; int offs = 0; int i; offs += fprintf(gl2ps->stream, "/ExtGState\n" "<<\n" "/GSa 7 0 R\n"); for(i = 0; i < gl2psListNbr(gl2ps->pdfgrouplist); ++i){ gro = (GL2PSpdfgroup*)gl2psListPointer(gl2ps->pdfgrouplist, i); if(gro->gsno >= 0) offs += fprintf(gl2ps->stream, "/GS%d %d 0 R\n", gro->gsno, gro->gsobjno); } offs += fprintf(gl2ps->stream, ">>\n"); return offs; } /* Main Shader names */ static int gl2psPDFgroupListWriteShaderResources(void) { GL2PSpdfgroup *gro; int offs = 0; int i; offs += fprintf(gl2ps->stream, "/Shading\n" "<<\n"); for(i = 0; i < gl2psListNbr(gl2ps->pdfgrouplist); ++i){ gro = (GL2PSpdfgroup*)gl2psListPointer(gl2ps->pdfgrouplist, i); if(gro->shno >= 0) offs += fprintf(gl2ps->stream, "/Sh%d %d 0 R\n", gro->shno, gro->shobjno); if(gro->maskshno >= 0) offs += fprintf(gl2ps->stream, "/TrSh%d %d 0 R\n", gro->maskshno, gro->maskshobjno); } offs += fprintf(gl2ps->stream,">>\n"); return offs; } /* Images & Mask Shader XObject names */ static int gl2psPDFgroupListWriteXObjectResources(void) { int i; GL2PSprimitive *p = NULL; GL2PSpdfgroup *gro; int offs = 0; offs += fprintf(gl2ps->stream, "/XObject\n" "<<\n"); for(i = 0; i < gl2psListNbr(gl2ps->pdfgrouplist); ++i){ gro = (GL2PSpdfgroup*)gl2psListPointer(gl2ps->pdfgrouplist, i); if(!gl2psListNbr(gro->ptrlist)) continue; p = *(GL2PSprimitive**)gl2psListPointer(gro->ptrlist, 0); switch(p->type){ case GL2PS_PIXMAP: gro->imobjno = gl2ps->objects_stack++; if(GL_RGBA == p->data.image->format) /* reserve one object for image mask */ gl2ps->objects_stack++; offs += fprintf(gl2ps->stream, "/Im%d %d 0 R\n", gro->imno, gro->imobjno); case GL2PS_TRIANGLE: if(gro->trgroupno >=0) offs += fprintf(gl2ps->stream, "/TrG%d %d 0 R\n", gro->trgroupno, gro->trgroupobjno); break; default: break; } } offs += fprintf(gl2ps->stream,">>\n"); return offs; } /* Font names */ static int gl2psPDFgroupListWriteFontResources(void) { int i; GL2PSpdfgroup *gro; int offs = 0; offs += fprintf(gl2ps->stream, "/Font\n<<\n"); for(i = 0; i < gl2psListNbr(gl2ps->pdfgrouplist); ++i){ gro = (GL2PSpdfgroup*)gl2psListPointer(gl2ps->pdfgrouplist, i); if(gro->fontno < 0) continue; gro->fontobjno = gl2ps->objects_stack++; offs += fprintf(gl2ps->stream, "/F%d %d 0 R\n", gro->fontno, gro->fontobjno); } offs += fprintf(gl2ps->stream, ">>\n"); return offs; } static void gl2psPDFgroupListDelete(void) { int i; GL2PSpdfgroup *gro = NULL; if(!gl2ps->pdfgrouplist) return; for(i = 0; i < gl2psListNbr(gl2ps->pdfgrouplist); ++i){ gro = (GL2PSpdfgroup*)gl2psListPointer(gl2ps->pdfgrouplist,i); gl2psListDelete(gro->ptrlist); } gl2psListDelete(gl2ps->pdfgrouplist); gl2ps->pdfgrouplist = NULL; } /* Print 1st PDF object - file info */ static int gl2psPrintPDFInfo(void) { int offs; time_t now; struct tm *newtime; time(&now); newtime = gmtime(&now); offs = fprintf(gl2ps->stream, "1 0 obj\n" "<<\n" "/Title (%s)\n" "/Creator (GL2PS %d.%d.%d%s, %s)\n" "/Producer (%s)\n", gl2ps->title, GL2PS_MAJOR_VERSION, GL2PS_MINOR_VERSION, GL2PS_PATCH_VERSION, GL2PS_EXTRA_VERSION, GL2PS_COPYRIGHT, gl2ps->producer); if(!newtime){ offs += fprintf(gl2ps->stream, ">>\n" "endobj\n"); return offs; } offs += fprintf(gl2ps->stream, "/CreationDate (D:%d%02d%02d%02d%02d%02d)\n" ">>\n" "endobj\n", newtime->tm_year+1900, newtime->tm_mon+1, newtime->tm_mday, newtime->tm_hour, newtime->tm_min, newtime->tm_sec); return offs; } /* Create catalog and page structure - 2nd and 3th PDF object */ static int gl2psPrintPDFCatalog(void) { return fprintf(gl2ps->stream, "2 0 obj\n" "<<\n" "/Type /Catalog\n" "/Pages 3 0 R\n" ">>\n" "endobj\n"); } static int gl2psPrintPDFPages(void) { return fprintf(gl2ps->stream, "3 0 obj\n" "<<\n" "/Type /Pages\n" "/Kids [6 0 R]\n" "/Count 1\n" ">>\n" "endobj\n"); } /* Open stream for data - graphical objects, fonts etc. PDF object 4 */ static int gl2psOpenPDFDataStream(void) { int offs = 0; offs += fprintf(gl2ps->stream, "4 0 obj\n" "<<\n" "/Length 5 0 R\n" ); offs += gl2psPrintPDFCompressorType(); offs += fprintf(gl2ps->stream, ">>\n" "stream\n"); return offs; } /* Stream setup - Graphics state, fill background if allowed */ static int gl2psOpenPDFDataStreamWritePreface(void) { int offs; offs = gl2psPrintf("/GSa gs\n"); if(gl2ps->options & GL2PS_DRAW_BACKGROUND){ offs += gl2psPrintPDFFillColor(gl2ps->bgcolor); offs += gl2psPrintf("%d %d %d %d re\n", (int)gl2ps->viewport[0], (int)gl2ps->viewport[1], (int)gl2ps->viewport[2], (int)gl2ps->viewport[3]); offs += gl2psPrintf("f\n"); } return offs; } /* Use the functions above to create the first part of the PDF*/ static void gl2psPrintPDFHeader(void) { int offs = 0; gl2ps->pdfprimlist = gl2psListCreate(500, 500, sizeof(GL2PSprimitive*)); gl2psPDFstacksInit(); gl2ps->xreflist = (int*)gl2psMalloc(sizeof(int) * gl2ps->objects_stack); #if defined(GL2PS_HAVE_ZLIB) if(gl2ps->options & GL2PS_COMPRESS){ gl2psSetupCompress(); } #endif gl2ps->xreflist[0] = 0; offs += fprintf(gl2ps->stream, "%%PDF-1.4\n"); gl2ps->xreflist[1] = offs; offs += gl2psPrintPDFInfo(); gl2ps->xreflist[2] = offs; offs += gl2psPrintPDFCatalog(); gl2ps->xreflist[3] = offs; offs += gl2psPrintPDFPages(); gl2ps->xreflist[4] = offs; offs += gl2psOpenPDFDataStream(); gl2ps->xreflist[5] = offs; /* finished in gl2psPrintPDFFooter */ gl2ps->streamlength = gl2psOpenPDFDataStreamWritePreface(); } /* The central primitive drawing */ static void gl2psPrintPDFPrimitive(void *data) { GL2PSprimitive *prim = *(GL2PSprimitive**)data; if((gl2ps->options & GL2PS_OCCLUSION_CULL) && prim->culled) return; prim = gl2psCopyPrimitive(prim); /* deep copy */ gl2psListAdd(gl2ps->pdfprimlist, &prim); } /* close stream and ... */ static int gl2psClosePDFDataStream(void) { int offs = 0; #if defined(GL2PS_HAVE_ZLIB) if(gl2ps->options & GL2PS_COMPRESS){ if(Z_OK != gl2psDeflate()) gl2psMsg(GL2PS_ERROR, "Zlib deflate error"); else fwrite(gl2ps->compress->dest, gl2ps->compress->destLen, 1, gl2ps->stream); gl2ps->streamlength += gl2ps->compress->destLen; offs += gl2ps->streamlength; gl2psFreeCompress(); } #endif offs += fprintf(gl2ps->stream, "endstream\n" "endobj\n"); return offs; } /* ... write the now known length object */ static int gl2psPrintPDFDataStreamLength(int val) { return fprintf(gl2ps->stream, "5 0 obj\n" "%d\n" "endobj\n", val); } /* Put the info created before in PDF objects */ static int gl2psPrintPDFOpenPage(void) { int offs; /* Write fixed part */ offs = fprintf(gl2ps->stream, "6 0 obj\n" "<<\n" "/Type /Page\n" "/Parent 3 0 R\n" "/MediaBox [%d %d %d %d]\n", (int)gl2ps->viewport[0], (int)gl2ps->viewport[1], (int)gl2ps->viewport[2], (int)gl2ps->viewport[3]); if(gl2ps->options & GL2PS_LANDSCAPE) offs += fprintf(gl2ps->stream, "/Rotate -90\n"); offs += fprintf(gl2ps->stream, "/Contents 4 0 R\n" "/Resources\n" "<<\n" "/ProcSet [/PDF /Text /ImageB /ImageC] %%/ImageI\n"); return offs; /* End fixed part, proceeds in gl2psPDFgroupListWriteVariableResources() */ } static int gl2psPDFgroupListWriteVariableResources(void) { int offs = 0; /* a) Graphics States for shader alpha masks*/ offs += gl2psPDFgroupListWriteGStateResources(); /* b) Shader and shader masks */ offs += gl2psPDFgroupListWriteShaderResources(); /* c) XObjects (Images & Shader Masks) */ offs += gl2psPDFgroupListWriteXObjectResources(); /* d) Fonts */ offs += gl2psPDFgroupListWriteFontResources(); /* End resources and page */ offs += fprintf(gl2ps->stream, ">>\n" ">>\n" "endobj\n"); return offs; } /* Standard Graphics State */ static int gl2psPrintPDFGSObject(void) { return fprintf(gl2ps->stream, "7 0 obj\n" "<<\n" "/Type /ExtGState\n" "/SA false\n" "/SM 0.02\n" "/OP false\n" "/op false\n" "/OPM 0\n" "/BG2 /Default\n" "/UCR2 /Default\n" "/TR2 /Default\n" ">>\n" "endobj\n"); } /* Put vertex' edge flag (8bit) and coordinates (32bit) in shader stream */ static int gl2psPrintPDFShaderStreamDataCoord(GL2PSvertex *vertex, size_t (*action)(unsigned long data, size_t size), GLfloat dx, GLfloat dy, GLfloat xmin, GLfloat ymin) { int offs = 0; unsigned long imap; double dmax = ~1UL; char edgeflag = 0; /* FIXME: temp bux fix for 64 bit archs: */ if(sizeof(unsigned long) == 8) dmax = dmax - 2048.; offs += (*action)(edgeflag, 1); /* The Shader stream in PDF requires to be in a 'big-endian' order */ if(GL2PS_ZERO(dx*dy)){ offs += (*action)(0, 4); offs += (*action)(0, 4); } else{ GLfloat diff = (vertex->xyz[0] - xmin) / dx; if(diff > 1) diff = 1.0F; else if(diff < 0) diff = 0.0F; imap = (unsigned long)(diff * dmax); offs += (*action)(imap, 4); diff = (vertex->xyz[1] - ymin) / dy; if(diff > 1) diff = 1.0F; else if(diff < 0) diff = 0.0F; imap = (unsigned long)(diff * dmax); offs += (*action)(imap, 4); } return offs; } /* Put vertex' rgb value (8bit for every component) in shader stream */ static int gl2psPrintPDFShaderStreamDataRGB(GL2PSvertex *vertex, size_t (*action)(unsigned long data, size_t size)) { int offs = 0; unsigned long imap; double dmax = ~1UL; /* FIXME: temp bux fix for 64 bit archs: */ if(sizeof(unsigned long) == 8) dmax = dmax - 2048.; imap = (unsigned long)((vertex->rgba[0]) * dmax); offs += (*action)(imap, 1); imap = (unsigned long)((vertex->rgba[1]) * dmax); offs += (*action)(imap, 1); imap = (unsigned long)((vertex->rgba[2]) * dmax); offs += (*action)(imap, 1); return offs; } /* Put vertex' alpha (8/16bit) in shader stream */ static int gl2psPrintPDFShaderStreamDataAlpha(GL2PSvertex *vertex, size_t (*action)(unsigned long data, size_t size), int sigbyte) { int offs = 0; unsigned long imap; double dmax = ~1UL; /* FIXME: temp bux fix for 64 bit archs: */ if(sizeof(unsigned long) == 8) dmax = dmax - 2048.; if(sigbyte != 8 && sigbyte != 16) sigbyte = 8; sigbyte /= 8; imap = (unsigned long)((vertex->rgba[3]) * dmax); offs += (*action)(imap, sigbyte); return offs; } /* Put a triangles raw data in shader stream */ static int gl2psPrintPDFShaderStreamData(GL2PStriangle *triangle, GLfloat dx, GLfloat dy, GLfloat xmin, GLfloat ymin, size_t (*action)(unsigned long data, size_t size), int gray) { int i, offs = 0; GL2PSvertex v; if(gray && gray != 8 && gray != 16) gray = 8; for(i = 0; i < 3; ++i){ offs += gl2psPrintPDFShaderStreamDataCoord(&triangle->vertex[i], action, dx, dy, xmin, ymin); if(gray){ v = triangle->vertex[i]; offs += gl2psPrintPDFShaderStreamDataAlpha(&v, action, gray); } else{ offs += gl2psPrintPDFShaderStreamDataRGB(&triangle->vertex[i], action); } } return offs; } static void gl2psPDFRectHull(GLfloat *xmin, GLfloat *xmax, GLfloat *ymin, GLfloat *ymax, GL2PStriangle *triangles, int cnt) { int i, j; *xmin = triangles[0].vertex[0].xyz[0]; *xmax = triangles[0].vertex[0].xyz[0]; *ymin = triangles[0].vertex[0].xyz[1]; *ymax = triangles[0].vertex[0].xyz[1]; for(i = 0; i < cnt; ++i){ for(j = 0; j < 3; ++j){ if(*xmin > triangles[i].vertex[j].xyz[0]) *xmin = triangles[i].vertex[j].xyz[0]; if(*xmax < triangles[i].vertex[j].xyz[0]) *xmax = triangles[i].vertex[j].xyz[0]; if(*ymin > triangles[i].vertex[j].xyz[1]) *ymin = triangles[i].vertex[j].xyz[1]; if(*ymax < triangles[i].vertex[j].xyz[1]) *ymax = triangles[i].vertex[j].xyz[1]; } } } /* Writes shaded triangle gray == 0 means write RGB triangles gray == 8 8bit-grayscale (for alpha masks) gray == 16 16bit-grayscale (for alpha masks) */ static int gl2psPrintPDFShader(int obj, GL2PStriangle *triangles, int size, int gray) { int i, offs = 0, vertexbytes, done = 0; GLfloat xmin, xmax, ymin, ymax; switch(gray){ case 0: vertexbytes = 1+4+4+1+1+1; break; case 8: vertexbytes = 1+4+4+1; break; case 16: vertexbytes = 1+4+4+2; break; default: gray = 8; vertexbytes = 1+4+4+1; break; } gl2psPDFRectHull(&xmin, &xmax, &ymin, &ymax, triangles, size); offs += fprintf(gl2ps->stream, "%d 0 obj\n" "<< " "/ShadingType 4 " "/ColorSpace %s " "/BitsPerCoordinate 32 " "/BitsPerComponent %d " "/BitsPerFlag 8 " "/Decode [%f %f %f %f 0 1 %s] ", obj, (gray) ? "/DeviceGray" : "/DeviceRGB", (gray) ? gray : 8, xmin, xmax, ymin, ymax, (gray) ? "" : "0 1 0 1"); #if defined(GL2PS_HAVE_ZLIB) if(gl2ps->options & GL2PS_COMPRESS){ gl2psAllocCompress(vertexbytes * size * 3); for(i = 0; i < size; ++i) gl2psPrintPDFShaderStreamData(&triangles[i], xmax-xmin, ymax-ymin, xmin, ymin, gl2psWriteBigEndianCompress, gray); if(Z_OK == gl2psDeflate() && 23 + gl2ps->compress->destLen < gl2ps->compress->srcLen){ offs += gl2psPrintPDFCompressorType(); offs += fprintf(gl2ps->stream, "/Length %d " ">>\n" "stream\n", (int)gl2ps->compress->destLen); offs += gl2ps->compress->destLen * fwrite(gl2ps->compress->dest, gl2ps->compress->destLen, 1, gl2ps->stream); done = 1; } gl2psFreeCompress(); } #endif if(!done){ /* no compression, or too long after compression, or compress error -> write non-compressed entry */ offs += fprintf(gl2ps->stream, "/Length %d " ">>\n" "stream\n", vertexbytes * 3 * size); for(i = 0; i < size; ++i) offs += gl2psPrintPDFShaderStreamData(&triangles[i], xmax-xmin, ymax-ymin, xmin, ymin, gl2psWriteBigEndian, gray); } offs += fprintf(gl2ps->stream, "\nendstream\n" "endobj\n"); return offs; } /* Writes a XObject for a shaded triangle mask */ static int gl2psPrintPDFShaderMask(int obj, int childobj) { int offs = 0, len; offs += fprintf(gl2ps->stream, "%d 0 obj\n" "<<\n" "/Type /XObject\n" "/Subtype /Form\n" "/BBox [ %d %d %d %d ]\n" "/Group \n<<\n/S /Transparency /CS /DeviceRGB\n" ">>\n", obj, (int)gl2ps->viewport[0], (int)gl2ps->viewport[1], (int)gl2ps->viewport[2], (int)gl2ps->viewport[3]); len = (childobj>0) ? strlen("/TrSh sh\n") + (int)log10((double)childobj)+1 : strlen("/TrSh0 sh\n"); offs += fprintf(gl2ps->stream, "/Length %d\n" ">>\n" "stream\n", len); offs += fprintf(gl2ps->stream, "/TrSh%d sh\n", childobj); offs += fprintf(gl2ps->stream, "endstream\n" "endobj\n"); return offs; } /* Writes a Extended graphics state for a shaded triangle mask if simplealpha ist true the childobj argument is ignored and a /ca statement will be written instead */ static int gl2psPrintPDFShaderExtGS(int obj, int childobj) { int offs = 0; offs += fprintf(gl2ps->stream, "%d 0 obj\n" "<<\n", obj); offs += fprintf(gl2ps->stream, "/SMask << /S /Alpha /G %d 0 R >> ", childobj); offs += fprintf(gl2ps->stream, ">>\n" "endobj\n"); return offs; } /* a simple graphics state */ static int gl2psPrintPDFShaderSimpleExtGS(int obj, GLfloat alpha) { int offs = 0; offs += fprintf(gl2ps->stream, "%d 0 obj\n" "<<\n" "/ca %g" ">>\n" "endobj\n", obj, alpha); return offs; } /* Similar groups of functions for pixmaps and text */ static int gl2psPrintPDFPixmapStreamData(GL2PSimage *im, size_t (*action)(unsigned long data, size_t size), int gray) { int x, y; GLfloat r, g, b, a; if(im->format != GL_RGBA && gray) return 0; if(gray && gray !=8 && gray != 16) gray = 8; gray /= 8; for(y = 0; y < im->height; ++y){ for(x = 0; x < im->width; ++x){ a = gl2psGetRGB(im, x, y, &r, &g, &b); if(im->format == GL_RGBA && gray){ (*action)((unsigned long)(a*255) << 24, gray); } else{ (*action)((unsigned long)(r*255) << 24, 1); (*action)((unsigned long)(g*255) << 24, 1); (*action)((unsigned long)(b*255) << 24, 1); } } } switch(gray){ case 0: return 3 * im->width * im->height; case 1: return im->width * im->height; case 2: return 2 * im->width * im->height; default: return 3 * im->width * im->height; } } static int gl2psPrintPDFPixmap(int obj, int childobj, GL2PSimage *im, int gray) { int offs = 0, done = 0, sigbytes = 3; if(gray && gray !=8 && gray != 16) gray = 8; if(gray) sigbytes = gray / 8; offs += fprintf(gl2ps->stream, "%d 0 obj\n" "<<\n" "/Type /XObject\n" "/Subtype /Image\n" "/Width %d\n" "/Height %d\n" "/ColorSpace %s \n" "/BitsPerComponent 8\n", obj, (int)im->width, (int)im->height, (gray) ? "/DeviceGray" : "/DeviceRGB" ); if(GL_RGBA == im->format && gray == 0){ offs += fprintf(gl2ps->stream, "/SMask %d 0 R\n", childobj); } #if defined(GL2PS_HAVE_ZLIB) if(gl2ps->options & GL2PS_COMPRESS){ gl2psAllocCompress((int)(im->width * im->height * sigbytes)); gl2psPrintPDFPixmapStreamData(im, gl2psWriteBigEndianCompress, gray); if(Z_OK == gl2psDeflate() && 23 + gl2ps->compress->destLen < gl2ps->compress->srcLen){ offs += gl2psPrintPDFCompressorType(); offs += fprintf(gl2ps->stream, "/Length %d " ">>\n" "stream\n", (int)gl2ps->compress->destLen); offs += gl2ps->compress->destLen * fwrite(gl2ps->compress->dest, gl2ps->compress->destLen, 1, gl2ps->stream); done = 1; } gl2psFreeCompress(); } #endif if(!done){ /* no compression, or too long after compression, or compress error -> write non-compressed entry */ offs += fprintf(gl2ps->stream, "/Length %d " ">>\n" "stream\n", (int)(im->width * im->height * sigbytes)); offs += gl2psPrintPDFPixmapStreamData(im, gl2psWriteBigEndian, gray); } offs += fprintf(gl2ps->stream, "\nendstream\n" "endobj\n"); return offs; } static int gl2psPrintPDFText(int obj, GL2PSstring *s, int fontnumber) { int offs = 0; offs += fprintf(gl2ps->stream, "%d 0 obj\n" "<<\n" "/Type /Font\n" "/Subtype /Type1\n" "/Name /F%d\n" "/BaseFont /%s\n" "/Encoding /MacRomanEncoding\n" ">>\n" "endobj\n", obj, fontnumber, s->fontname); return offs; } /* Write the physical objects */ static int gl2psPDFgroupListWriteObjects(int entryoffs) { int i,j; GL2PSprimitive *p = NULL; GL2PSpdfgroup *gro; int offs = entryoffs; GL2PStriangle *triangles; int size = 0; if(!gl2ps->pdfgrouplist) return offs; for(i = 0; i < gl2psListNbr(gl2ps->pdfgrouplist); ++i){ gro = (GL2PSpdfgroup*)gl2psListPointer(gl2ps->pdfgrouplist, i); if(!gl2psListNbr(gro->ptrlist)) continue; p = *(GL2PSprimitive**)gl2psListPointer(gro->ptrlist, 0); switch(p->type){ case GL2PS_POINT: break; case GL2PS_LINE: break; case GL2PS_TRIANGLE: size = gl2psListNbr(gro->ptrlist); triangles = (GL2PStriangle*)gl2psMalloc(sizeof(GL2PStriangle) * size); for(j = 0; j < size; ++j){ p = *(GL2PSprimitive**)gl2psListPointer(gro->ptrlist, j); gl2psFillTriangleFromPrimitive(&triangles[j], p, GL_TRUE); } if(triangles[0].prop & T_VAR_COLOR){ gl2ps->xreflist[gro->shobjno] = offs; offs += gl2psPrintPDFShader(gro->shobjno, triangles, size, 0); } if(triangles[0].prop & T_ALPHA_LESS_1){ gl2ps->xreflist[gro->gsobjno] = offs; offs += gl2psPrintPDFShaderSimpleExtGS(gro->gsobjno, triangles[0].vertex[0].rgba[3]); } if(triangles[0].prop & T_VAR_ALPHA){ gl2ps->xreflist[gro->gsobjno] = offs; offs += gl2psPrintPDFShaderExtGS(gro->gsobjno, gro->trgroupobjno); gl2ps->xreflist[gro->trgroupobjno] = offs; offs += gl2psPrintPDFShaderMask(gro->trgroupobjno, gro->maskshno); gl2ps->xreflist[gro->maskshobjno] = offs; offs += gl2psPrintPDFShader(gro->maskshobjno, triangles, size, 8); } gl2psFree(triangles); break; case GL2PS_PIXMAP: gl2ps->xreflist[gro->imobjno] = offs; offs += gl2psPrintPDFPixmap(gro->imobjno, gro->imobjno+1, p->data.image, 0); if(p->data.image->format == GL_RGBA){ gl2ps->xreflist[gro->imobjno+1] = offs; offs += gl2psPrintPDFPixmap(gro->imobjno+1, -1, p->data.image, 8); } break; case GL2PS_TEXT: gl2ps->xreflist[gro->fontobjno] = offs; offs += gl2psPrintPDFText(gro->fontobjno,p->data.text,gro->fontno); break; case GL2PS_SPECIAL : /* alignment contains the format for which the special output text is intended */ if(p->data.text->alignment == GL2PS_PDF) offs += fprintf(gl2ps->stream, "%s\n", p->data.text->str); break; default: break; } } return offs; } /* All variable data has been written at this point and all required functioninality has been gathered, so we can write now file footer with cross reference table and trailer */ static void gl2psPrintPDFFooter(void) { int i, offs; gl2psPDFgroupListInit(); gl2psPDFgroupListWriteMainStream(); offs = gl2ps->xreflist[5] + gl2ps->streamlength; offs += gl2psClosePDFDataStream(); gl2ps->xreflist[5] = offs; offs += gl2psPrintPDFDataStreamLength(gl2ps->streamlength); gl2ps->xreflist[6] = offs; gl2ps->streamlength = 0; offs += gl2psPrintPDFOpenPage(); offs += gl2psPDFgroupListWriteVariableResources(); gl2ps->xreflist = (int*)gl2psRealloc(gl2ps->xreflist, sizeof(int) * (gl2ps->objects_stack + 1)); gl2ps->xreflist[7] = offs; offs += gl2psPrintPDFGSObject(); gl2ps->xreflist[8] = offs; gl2ps->xreflist[gl2ps->objects_stack] = gl2psPDFgroupListWriteObjects(gl2ps->xreflist[8]); /* Start cross reference table. The file has to been opened in binary mode to preserve the 20 digit string length! */ fprintf(gl2ps->stream, "xref\n" "0 %d\n" "%010d 65535 f \n", gl2ps->objects_stack, 0); for(i = 1; i < gl2ps->objects_stack; ++i) fprintf(gl2ps->stream, "%010d 00000 n \n", gl2ps->xreflist[i]); fprintf(gl2ps->stream, "trailer\n" "<<\n" "/Size %d\n" "/Info 1 0 R\n" "/Root 2 0 R\n" ">>\n" "startxref\n%d\n" "%%%%EOF\n", gl2ps->objects_stack, gl2ps->xreflist[gl2ps->objects_stack]); /* Free auxiliary lists and arrays */ gl2psFree(gl2ps->xreflist); gl2psListDelete(gl2ps->pdfprimlist); gl2psPDFgroupListDelete(); #if defined(GL2PS_HAVE_ZLIB) if(gl2ps->options & GL2PS_COMPRESS){ gl2psFreeCompress(); gl2psFree(gl2ps->compress); gl2ps->compress = NULL; } #endif } /* PDF begin viewport */ static void gl2psPrintPDFBeginViewport(GLint viewport[4]) { int offs = 0; GLint index; GLfloat rgba[4]; int x = viewport[0], y = viewport[1], w = viewport[2], h = viewport[3]; glRenderMode(GL_FEEDBACK); if(gl2ps->header){ gl2psPrintPDFHeader(); gl2ps->header = GL_FALSE; } offs += gl2psPrintf("q\n"); if(gl2ps->options & GL2PS_DRAW_BACKGROUND){ if(gl2ps->colormode == GL_RGBA || gl2ps->colorsize == 0){ glGetFloatv(GL_COLOR_CLEAR_VALUE, rgba); } else{ glGetIntegerv(GL_INDEX_CLEAR_VALUE, &index); rgba[0] = gl2ps->colormap[index][0]; rgba[1] = gl2ps->colormap[index][1]; rgba[2] = gl2ps->colormap[index][2]; rgba[3] = 1.0F; } offs += gl2psPrintPDFFillColor(rgba); offs += gl2psPrintf("%d %d %d %d re\n" "W\n" "f\n", x, y, w, h); } else{ offs += gl2psPrintf("%d %d %d %d re\n" "W\n" "n\n", x, y, w, h); } gl2ps->streamlength += offs; } static GLint gl2psPrintPDFEndViewport(void) { GLint res; res = gl2psPrintPrimitives(); gl2ps->streamlength += gl2psPrintf("Q\n"); return res; } static void gl2psPrintPDFFinalPrimitive(void) { } /* definition of the PDF backend */ static GL2PSbackend gl2psPDF = { gl2psPrintPDFHeader, gl2psPrintPDFFooter, gl2psPrintPDFBeginViewport, gl2psPrintPDFEndViewport, gl2psPrintPDFPrimitive, gl2psPrintPDFFinalPrimitive, "pdf", "Portable Document Format" }; /********************************************************************* * * SVG routines * *********************************************************************/ static void gl2psSVGGetCoordsAndColors(int n, GL2PSvertex *verts, GL2PSxyz *xyz, GL2PSrgba *rgba) { int i, j; for(i = 0; i < n; i++){ xyz[i][0] = verts[i].xyz[0]; xyz[i][1] = gl2ps->viewport[3] - verts[i].xyz[1]; xyz[i][2] = 0.0F; for(j = 0; j < 4; j++) rgba[i][j] = verts[i].rgba[j]; } } static void gl2psSVGGetColorString(GL2PSrgba rgba, char str[32]) { int r = (int)(255. * rgba[0]); int g = (int)(255. * rgba[1]); int b = (int)(255. * rgba[2]); int rc = (r < 0) ? 0 : (r > 255) ? 255 : r; int gc = (g < 0) ? 0 : (g > 255) ? 255 : g; int bc = (b < 0) ? 0 : (b > 255) ? 255 : b; sprintf(str, "#%2.2x%2.2x%2.2x", rc, gc, bc); } static void gl2psPrintSVGHeader(void) { int x, y, width, height; char col[32]; time_t now; time(&now); if (gl2ps->options & GL2PS_LANDSCAPE){ x = (int)gl2ps->viewport[1]; y = (int)gl2ps->viewport[0]; width = (int)gl2ps->viewport[3]; height = (int)gl2ps->viewport[2]; } else{ x = (int)gl2ps->viewport[0]; y = (int)gl2ps->viewport[1]; width = (int)gl2ps->viewport[2]; height = (int)gl2ps->viewport[3]; } /* Compressed SVG files (.svgz) are simply gzipped SVG files */ gl2psPrintGzipHeader(); gl2psPrintf("\n"); gl2psPrintf("\n", width, height, x, y, width, height); gl2psPrintf("%s\n", gl2ps->title); gl2psPrintf("\n"); gl2psPrintf("Creator: GL2PS %d.%d.%d%s, %s\n" "For: %s\n" "CreationDate: %s", GL2PS_MAJOR_VERSION, GL2PS_MINOR_VERSION, GL2PS_PATCH_VERSION, GL2PS_EXTRA_VERSION, GL2PS_COPYRIGHT, gl2ps->producer, ctime(&now)); gl2psPrintf("\n"); gl2psPrintf("\n"); gl2psPrintf("\n"); if(gl2ps->options & GL2PS_DRAW_BACKGROUND){ gl2psSVGGetColorString(gl2ps->bgcolor, col); gl2psPrintf("\n", col, (int)gl2ps->viewport[0], (int)gl2ps->viewport[1], (int)gl2ps->viewport[2], (int)gl2ps->viewport[1], (int)gl2ps->viewport[2], (int)gl2ps->viewport[3], (int)gl2ps->viewport[0], (int)gl2ps->viewport[3]); } gl2psPrintf("\n"); } static void gl2psPrintSVGSmoothTriangle(GL2PSxyz xyz[3], GL2PSrgba rgba[3]) { GL2PSxyz xyz2[3]; GL2PSrgba rgba2[3]; char col[32]; /* Apparently there is no easy way to do Gouraud shading in SVG without explicitly pre-defining gradients, so for now we just do recursive subdivision */ if(gl2psSameColorThreshold(3, rgba, gl2ps->threshold)){ gl2psSVGGetColorString(rgba[0], col); gl2psPrintf("\n", xyz[0][0], xyz[0][1], xyz[1][0], xyz[1][1], xyz[2][0], xyz[2][1]); } else{ /* subdivide into 4 subtriangles */ int i = 0; for(; i < 3; i++){ xyz2[0][i] = xyz[0][i]; xyz2[1][i] = 0.5f * (xyz[0][i] + xyz[1][i]); xyz2[2][i] = 0.5f * (xyz[0][i] + xyz[2][i]); } for(i = 0; i < 4; i++){ rgba2[0][i] = rgba[0][i]; rgba2[1][i] = 0.5f * (rgba[0][i] + rgba[1][i]); rgba2[2][i] = 0.5f * (rgba[0][i] + rgba[2][i]); } gl2psPrintSVGSmoothTriangle(xyz2, rgba2); for(i = 0; i < 3; i++){ xyz2[0][i] = 0.5f * (xyz[0][i] + xyz[1][i]); xyz2[1][i] = xyz[1][i]; xyz2[2][i] = 0.5f * (xyz[1][i] + xyz[2][i]); } for(i = 0; i < 4; i++){ rgba2[0][i] = 0.5f * (rgba[0][i] + rgba[1][i]); rgba2[1][i] = rgba[1][i]; rgba2[2][i] = 0.5f * (rgba[1][i] + rgba[2][i]); } gl2psPrintSVGSmoothTriangle(xyz2, rgba2); for(i = 0; i < 3; i++){ xyz2[0][i] = 0.5f * (xyz[0][i] + xyz[2][i]); xyz2[1][i] = xyz[2][i]; xyz2[2][i] = 0.5f * (xyz[1][i] + xyz[2][i]); } for(i = 0; i < 4; i++){ rgba2[0][i] = 0.5f * (rgba[0][i] + rgba[2][i]); rgba2[1][i] = rgba[2][i]; rgba2[2][i] = 0.5f * (rgba[1][i] + rgba[2][i]); } gl2psPrintSVGSmoothTriangle(xyz2, rgba2); for(i = 0; i < 3; i++){ xyz2[0][i] = 0.5f * (xyz[0][i] + xyz[1][i]); xyz2[1][i] = 0.5f * (xyz[1][i] + xyz[2][i]); xyz2[2][i] = 0.5f * (xyz[0][i] + xyz[2][i]); } for(i = 0; i < 4; i++){ rgba2[0][i] = 0.5f * (rgba[0][i] + rgba[1][i]); rgba2[1][i] = 0.5f * (rgba[1][i] + rgba[2][i]); rgba2[2][i] = 0.5f * (rgba[0][i] + rgba[2][i]); } gl2psPrintSVGSmoothTriangle(xyz2, rgba2); } } static void gl2psPrintSVGDash(GLushort pattern, GLint factor) { int i, n, array[10]; if(!pattern || !factor) return; /* solid line */ gl2psParseStipplePattern(pattern, factor, &n, array); gl2psPrintf("stroke-dasharray=\""); for(i = 0; i < n; i++){ if(i) gl2psPrintf(","); gl2psPrintf("%d", array[i]); } gl2psPrintf("\" "); } static void gl2psEndSVGLine(void) { if(gl2ps->lastvertex.rgba[0] >= 0.){ gl2psPrintf("%g,%g\"/>\n", gl2ps->lastvertex.xyz[0], gl2ps->viewport[3] - gl2ps->lastvertex.xyz[1]); int i = 0; for(; i < 3; i++) gl2ps->lastvertex.xyz[i] = -1.; for(i = 0; i < 4; i++) gl2ps->lastvertex.rgba[i] = -1.; } } static void gl2psPrintSVGPixmap(GLfloat x, GLfloat y, GL2PSimage *pixmap) { #if defined(GL2PS_HAVE_LIBPNG) GL2PSlist *png; unsigned char c; int i; /* The only image types supported by the SVG standard are JPEG, PNG and SVG. Here we choose PNG, and since we want to embed the image directly in the SVG stream (and not link to an external image file), we need to encode the pixmap into PNG in memory, then encode it into base64. */ png = gl2psListCreate(pixmap->width * pixmap->height * 3, 1000, sizeof(unsigned char)); gl2psConvertPixmapToPNG(pixmap, png); gl2psListEncodeBase64(png); gl2psPrintf("height, pixmap->width, pixmap->height); gl2psPrintf("xlink:href=\"data:image/png;base64,"); for(i = 0; i < gl2psListNbr(png); i++){ gl2psListRead(png, i, &c); gl2psPrintf("%c", c); } gl2psPrintf("\"/>\n"); gl2psListDelete(png); #else Q_UNUSED(x); Q_UNUSED(y); Q_UNUSED(pixmap); gl2psMsg(GL2PS_WARNING, "GL2PS has to be compiled with PNG support in " "order to embed images in SVG streams"); #endif } static void gl2psPrintSVGPrimitive(void *data) { GL2PSprimitive *prim; GL2PSxyz xyz[4]; GL2PSrgba rgba[4]; char col[32]; int newline; prim = *(GL2PSprimitive**)data; if((gl2ps->options & GL2PS_OCCLUSION_CULL) && prim->culled) return; /* We try to draw connected lines as a single path to get nice line joins and correct stippling. So if the primitive to print is not a line we must first finish the current line (if any): */ if(prim->type != GL2PS_LINE) gl2psEndSVGLine(); gl2psSVGGetCoordsAndColors(prim->numverts, prim->verts, xyz, rgba); switch(prim->type){ case GL2PS_POINT : gl2psSVGGetColorString(rgba[0], col); gl2psPrintf("\n", xyz[0][0], xyz[0][1], 0.5 * prim->width); break; case GL2PS_LINE : if(!gl2psSamePosition(gl2ps->lastvertex.xyz, prim->verts[0].xyz) || !gl2psSameColor(gl2ps->lastrgba, prim->verts[0].rgba) || gl2ps->lastlinewidth != prim->width || gl2ps->lastpattern != prim->pattern || gl2ps->lastfactor != prim->factor){ /* End the current line if the new segment does not start where the last one ended, or if the color, the width or the stippling have changed (we will need to use multi-point gradients for smooth-shaded lines) */ gl2psEndSVGLine(); newline = 1; } else{ newline = 0; } gl2ps->lastvertex = prim->verts[1]; gl2psSetLastColor(prim->verts[0].rgba); gl2ps->lastlinewidth = prim->width; gl2ps->lastpattern = prim->pattern; gl2ps->lastfactor = prim->factor; if(newline){ gl2psSVGGetColorString(rgba[0], col); gl2psPrintf("width); if(rgba[0][3] < 1.0F) gl2psPrintf("stroke-opacity=\"%g\" ", rgba[0][3]); gl2psPrintSVGDash(prim->pattern, prim->factor); gl2psPrintf("points=\"%g,%g ", xyz[0][0], xyz[0][1]); } else{ gl2psPrintf("%g,%g ", xyz[0][0], xyz[0][1]); } break; case GL2PS_TRIANGLE : gl2psPrintSVGSmoothTriangle(xyz, rgba); break; case GL2PS_QUADRANGLE : gl2psMsg(GL2PS_WARNING, "There should not be any quad left to print"); break; case GL2PS_PIXMAP : gl2psPrintSVGPixmap(xyz[0][0], xyz[0][1], prim->data.image); break; case GL2PS_TEXT : gl2psSVGGetColorString(prim->verts[0].rgba, col); gl2psPrintf("%s\n", col, xyz[0][0], xyz[0][1], prim->data.text->fontsize, prim->data.text->fontname, prim->data.text->str); break; case GL2PS_SPECIAL : /* alignment contains the format for which the special output text is intended */ if(prim->data.text->alignment == GL2PS_SVG) gl2psPrintf("%s\n", prim->data.text->str); break; default : break; } } static void gl2psPrintSVGFooter(void) { gl2psPrintf("\n"); gl2psPrintf("\n"); gl2psPrintGzipFooter(); } static void gl2psPrintSVGBeginViewport(GLint viewport[4]) { GLint index; char col[32]; GLfloat rgba[4]; int x = viewport[0], y = viewport[1], w = viewport[2], h = viewport[3]; glRenderMode(GL_FEEDBACK); if(gl2ps->header){ gl2psPrintSVGHeader(); gl2ps->header = GL_FALSE; } if(gl2ps->options & GL2PS_DRAW_BACKGROUND){ if(gl2ps->colormode == GL_RGBA || gl2ps->colorsize == 0){ glGetFloatv(GL_COLOR_CLEAR_VALUE, rgba); } else{ glGetIntegerv(GL_INDEX_CLEAR_VALUE, &index); rgba[0] = gl2ps->colormap[index][0]; rgba[1] = gl2ps->colormap[index][1]; rgba[2] = gl2ps->colormap[index][2]; rgba[3] = 1.0F; } gl2psSVGGetColorString(rgba, col); gl2psPrintf("\n", col, x, gl2ps->viewport[3] - y, x + w, gl2ps->viewport[3] - y, x + w, gl2ps->viewport[3] - (y + h), x, gl2ps->viewport[3] - (y + h)); } gl2psPrintf("\n", x, y, w, h); gl2psPrintf(" \n", x, gl2ps->viewport[3] - y, x + w, gl2ps->viewport[3] - y, x + w, gl2ps->viewport[3] - (y + h), x, gl2ps->viewport[3] - (y + h)); gl2psPrintf("\n"); gl2psPrintf("\n", x, y, w, h); } static GLint gl2psPrintSVGEndViewport(void) { GLint res; res = gl2psPrintPrimitives(); gl2psPrintf("\n"); return res; } static void gl2psPrintSVGFinalPrimitive(void) { /* End any remaining line, if any */ gl2psEndSVGLine(); } /* definition of the SVG backend */ static GL2PSbackend gl2psSVG = { gl2psPrintSVGHeader, gl2psPrintSVGFooter, gl2psPrintSVGBeginViewport, gl2psPrintSVGEndViewport, gl2psPrintSVGPrimitive, gl2psPrintSVGFinalPrimitive, "svg", "Scalable Vector Graphics" }; /********************************************************************* * * PGF routines * *********************************************************************/ static void gl2psPrintPGFColor(GL2PSrgba rgba) { if(!gl2psSameColor(gl2ps->lastrgba, rgba)){ gl2psSetLastColor(rgba); fprintf(gl2ps->stream, "\\color[rgb]{%f,%f,%f}\n", rgba[0], rgba[1], rgba[2]); } } static void gl2psPrintPGFHeader(void) { time_t now; time(&now); fprintf(gl2ps->stream, "%% Title: %s\n" "%% Creator: GL2PS %d.%d.%d%s, %s\n" "%% For: %s\n" "%% CreationDate: %s", gl2ps->title, GL2PS_MAJOR_VERSION, GL2PS_MINOR_VERSION, GL2PS_PATCH_VERSION, GL2PS_EXTRA_VERSION, GL2PS_COPYRIGHT, gl2ps->producer, ctime(&now)); fprintf(gl2ps->stream, "\\begin{pgfpicture}\n"); if(gl2ps->options & GL2PS_DRAW_BACKGROUND){ gl2psPrintPGFColor(gl2ps->bgcolor); fprintf(gl2ps->stream, "\\pgfpathrectanglecorners{" "\\pgfpoint{%dpt}{%dpt}}{\\pgfpoint{%dpt}{%dpt}}\n" "\\pgfusepath{fill}\n", (int)gl2ps->viewport[0], (int)gl2ps->viewport[1], (int)gl2ps->viewport[2], (int)gl2ps->viewport[3]); } } static void gl2psPrintPGFDash(GLushort pattern, GLint factor) { int n, array[10]; if(pattern == gl2ps->lastpattern && factor == gl2ps->lastfactor) return; gl2ps->lastpattern = pattern; gl2ps->lastfactor = factor; if(!pattern || !factor){ /* solid line */ fprintf(gl2ps->stream, "\\pgfsetdash{}{0pt}\n"); } else{ gl2psParseStipplePattern(pattern, factor, &n, array); fprintf(gl2ps->stream, "\\pgfsetdash{"); int i = 0; for(; i < n; i++) fprintf(gl2ps->stream, "{%dpt}", array[i]); fprintf(gl2ps->stream, "}{0pt}\n"); } } static const char *gl2psPGFTextAlignment(int align) { switch(align){ case GL2PS_TEXT_C : return "center"; case GL2PS_TEXT_CL : return "west"; case GL2PS_TEXT_CR : return "east"; case GL2PS_TEXT_B : return "south"; case GL2PS_TEXT_BR : return "south east"; case GL2PS_TEXT_T : return "north"; case GL2PS_TEXT_TL : return "north west"; case GL2PS_TEXT_TR : return "north east"; case GL2PS_TEXT_BL : default : return "south west"; } } static void gl2psPrintPGFPrimitive(void *data) { GL2PSprimitive *prim; prim = *(GL2PSprimitive**)data; switch(prim->type){ case GL2PS_POINT : /* Points in openGL are rectangular */ gl2psPrintPGFColor(prim->verts[0].rgba); fprintf(gl2ps->stream, "\\pgfpathrectangle{\\pgfpoint{%fpt}{%fpt}}" "{\\pgfpoint{%fpt}{%fpt}}\n\\pgfusepath{fill}\n", prim->verts[0].xyz[0]-0.5*prim->width, prim->verts[0].xyz[1]-0.5*prim->width, prim->width,prim->width); break; case GL2PS_LINE : gl2psPrintPGFColor(prim->verts[0].rgba); if(gl2ps->lastlinewidth != prim->width){ gl2ps->lastlinewidth = prim->width; fprintf(gl2ps->stream, "\\pgfsetlinewidth{%fpt}\n", gl2ps->lastlinewidth); } gl2psPrintPGFDash(prim->pattern, prim->factor); fprintf(gl2ps->stream, "\\pgfpathmoveto{\\pgfpoint{%fpt}{%fpt}}\n" "\\pgflineto{\\pgfpoint{%fpt}{%fpt}}\n" "\\pgfusepath{stroke}\n", prim->verts[1].xyz[0], prim->verts[1].xyz[1], prim->verts[0].xyz[0], prim->verts[0].xyz[1]); break; case GL2PS_TRIANGLE : if(gl2ps->lastlinewidth != 0){ gl2ps->lastlinewidth = 0; fprintf(gl2ps->stream, "\\pgfsetlinewidth{0.01pt}\n"); } gl2psPrintPGFColor(prim->verts[0].rgba); fprintf(gl2ps->stream, "\\pgfpathmoveto{\\pgfpoint{%fpt}{%fpt}}\n" "\\pgflineto{\\pgfpoint{%fpt}{%fpt}}\n" "\\pgflineto{\\pgfpoint{%fpt}{%fpt}}\n" "\\pgfpathclose\n" "\\pgfusepath{fill,stroke}\n", prim->verts[2].xyz[0], prim->verts[2].xyz[1], prim->verts[1].xyz[0], prim->verts[1].xyz[1], prim->verts[0].xyz[0], prim->verts[0].xyz[1]); break; case GL2PS_TEXT : fprintf(gl2ps->stream, "{\n\\pgftransformshift{\\pgfpoint{%fpt}{%fpt}}\n", prim->verts[0].xyz[0], prim->verts[0].xyz[1]); if(prim->data.text->angle) fprintf(gl2ps->stream, "\\pgftransformrotate{%f}{", prim->data.text->angle); fprintf(gl2ps->stream, "\\pgfnode{rectangle}{%s}{\\fontsize{%d}{0}\\selectfont", gl2psPGFTextAlignment(prim->data.text->alignment), prim->data.text->fontsize); fprintf(gl2ps->stream, "\\textcolor[rgb]{%g,%g,%g}{{%s}}", prim->verts[0].rgba[0], prim->verts[0].rgba[1], prim->verts[0].rgba[2], prim->data.text->str); fprintf(gl2ps->stream, "}{}{\\pgfusepath{discard}}}\n"); break; case GL2PS_SPECIAL : /* alignment contains the format for which the special output text is intended */ if (prim->data.text->alignment == GL2PS_PGF) fprintf(gl2ps->stream, "%s\n", prim->data.text->str); break; default : break; } } static void gl2psPrintPGFFooter(void) { fprintf(gl2ps->stream, "\\end{pgfpicture}\n"); } static void gl2psPrintPGFBeginViewport(GLint viewport[4]) { GLint index; GLfloat rgba[4]; int x = viewport[0], y = viewport[1], w = viewport[2], h = viewport[3]; glRenderMode(GL_FEEDBACK); if(gl2ps->header){ gl2psPrintPGFHeader(); gl2ps->header = GL_FALSE; } fprintf(gl2ps->stream, "\\begin{pgfscope}\n"); if(gl2ps->options & GL2PS_DRAW_BACKGROUND){ if(gl2ps->colormode == GL_RGBA || gl2ps->colorsize == 0){ glGetFloatv(GL_COLOR_CLEAR_VALUE, rgba); } else{ glGetIntegerv(GL_INDEX_CLEAR_VALUE, &index); rgba[0] = gl2ps->colormap[index][0]; rgba[1] = gl2ps->colormap[index][1]; rgba[2] = gl2ps->colormap[index][2]; rgba[3] = 1.0F; } gl2psPrintPGFColor(rgba); fprintf(gl2ps->stream, "\\pgfpathrectangle{\\pgfpoint{%dpt}{%dpt}}" "{\\pgfpoint{%dpt}{%dpt}}\n" "\\pgfusepath{fill}\n", x, y, w, h); } fprintf(gl2ps->stream, "\\pgfpathrectangle{\\pgfpoint{%dpt}{%dpt}}" "{\\pgfpoint{%dpt}{%dpt}}\n" "\\pgfusepath{clip}\n", x, y, w, h); } static GLint gl2psPrintPGFEndViewport(void) { GLint res; res = gl2psPrintPrimitives(); fprintf(gl2ps->stream, "\\end{pgfscope}\n"); return res; } static void gl2psPrintPGFFinalPrimitive(void) { } /* definition of the PGF backend */ static GL2PSbackend gl2psPGF = { gl2psPrintPGFHeader, gl2psPrintPGFFooter, gl2psPrintPGFBeginViewport, gl2psPrintPGFEndViewport, gl2psPrintPGFPrimitive, gl2psPrintPGFFinalPrimitive, "tex", "PGF Latex Graphics" }; /********************************************************************* * * General primitive printing routine * *********************************************************************/ /* Warning: the ordering of the backends must match the format #defines in gl2ps.h */ static GL2PSbackend *gl2psbackends[] = { &gl2psPS, /* 0 */ &gl2psEPS, /* 1 */ &gl2psTEX, /* 2 */ &gl2psPDF, /* 3 */ &gl2psSVG, /* 4 */ &gl2psPGF /* 5 */ }; static void gl2psComputeTightBoundingBox(void *data) { GL2PSprimitive *prim; int i; prim = *(GL2PSprimitive**)data; for(i = 0; i < prim->numverts; i++){ if(prim->verts[i].xyz[0] < gl2ps->viewport[0]) gl2ps->viewport[0] = (GLint)prim->verts[i].xyz[0]; if(prim->verts[i].xyz[0] > gl2ps->viewport[2]) gl2ps->viewport[2] = (GLint)(prim->verts[i].xyz[0] + 0.5F); if(prim->verts[i].xyz[1] < gl2ps->viewport[1]) gl2ps->viewport[1] = (GLint)prim->verts[i].xyz[1]; if(prim->verts[i].xyz[1] > gl2ps->viewport[3]) gl2ps->viewport[3] = (GLint)(prim->verts[i].xyz[1] + 0.5F); } } static GLint gl2psPrintPrimitives(void) { GL2PSbsptree *root; GL2PSxyz eye = {0.0F, 0.0F, 100.0F * GL2PS_ZSCALE}; GLint used; used = glRenderMode(GL_RENDER); if(used < 0){ gl2psMsg(GL2PS_INFO, "OpenGL feedback buffer overflow"); return GL2PS_OVERFLOW; } if(used > 0) gl2psParseFeedbackBuffer(used); gl2psRescaleAndOffset(); if(gl2ps->header){ if(gl2psListNbr(gl2ps->primitives) && (gl2ps->options & GL2PS_TIGHT_BOUNDING_BOX)){ gl2ps->viewport[0] = gl2ps->viewport[1] = 100000; gl2ps->viewport[2] = gl2ps->viewport[3] = -100000; gl2psListAction(gl2ps->primitives, gl2psComputeTightBoundingBox); } (gl2psbackends[gl2ps->format]->printHeader)(); gl2ps->header = GL_FALSE; } if(!gl2psListNbr(gl2ps->primitives)){ /* empty feedback buffer and/or nothing else to print */ return GL2PS_NO_FEEDBACK; } switch(gl2ps->sort){ case GL2PS_NO_SORT : gl2psListAction(gl2ps->primitives, gl2psbackends[gl2ps->format]->printPrimitive); gl2psListAction(gl2ps->primitives, gl2psFreePrimitive); /* reset the primitive list, waiting for the next viewport */ gl2psListReset(gl2ps->primitives); break; case GL2PS_SIMPLE_SORT : gl2psListSort(gl2ps->primitives, gl2psCompareDepth); if(gl2ps->options & GL2PS_OCCLUSION_CULL){ gl2psListActionInverse(gl2ps->primitives, gl2psAddInImageTree); gl2psFreeBspImageTree(&gl2ps->imagetree); } gl2psListAction(gl2ps->primitives, gl2psbackends[gl2ps->format]->printPrimitive); gl2psListAction(gl2ps->primitives, gl2psFreePrimitive); /* reset the primitive list, waiting for the next viewport */ gl2psListReset(gl2ps->primitives); break; case GL2PS_BSP_SORT : root = (GL2PSbsptree*)gl2psMalloc(sizeof(GL2PSbsptree)); gl2psBuildBspTree(root, gl2ps->primitives); if(GL_TRUE == gl2ps->boundary) gl2psBuildPolygonBoundary(root); if(gl2ps->options & GL2PS_OCCLUSION_CULL){ gl2psTraverseBspTree(root, eye, -GL2PS_EPSILON, gl2psLess, gl2psAddInImageTree, 1); gl2psFreeBspImageTree(&gl2ps->imagetree); } gl2psTraverseBspTree(root, eye, GL2PS_EPSILON, gl2psGreater, gl2psbackends[gl2ps->format]->printPrimitive, 0); gl2psFreeBspTree(&root); /* reallocate the primitive list (it's been deleted by gl2psBuildBspTree) in case there is another viewport */ gl2ps->primitives = gl2psListCreate(500, 500, sizeof(GL2PSprimitive*)); break; } gl2psbackends[gl2ps->format]->printFinalPrimitive(); return GL2PS_SUCCESS; } /********************************************************************* * * Public routines * *********************************************************************/ GL2PSDLL_API GLint gl2psBeginPage(const char *title, const char *producer, GLint viewport[4], GLint format, GLint sort, GLint options, GLint colormode, GLint colorsize, GL2PSrgba *colormap, GLint nr, GLint ng, GLint nb, GLint buffersize, FILE *stream, const char *filename) { GLint index; int i; if(gl2ps){ gl2psMsg(GL2PS_ERROR, "gl2psBeginPage called in wrong program state"); return GL2PS_ERROR; } gl2ps = (GL2PScontext*)gl2psMalloc(sizeof(GL2PScontext)); if(format >= 0 && format < (GLint)(sizeof(gl2psbackends)/sizeof(gl2psbackends[0]))){ gl2ps->format = format; } else { gl2psMsg(GL2PS_ERROR, "Unknown output format: %d", format); gl2psFree(gl2ps); gl2ps = NULL; return GL2PS_ERROR; } switch(sort){ case GL2PS_NO_SORT : case GL2PS_SIMPLE_SORT : case GL2PS_BSP_SORT : gl2ps->sort = sort; break; default : gl2psMsg(GL2PS_ERROR, "Unknown sorting algorithm: %d", sort); gl2psFree(gl2ps); gl2ps = NULL; return GL2PS_ERROR; } if(stream){ gl2ps->stream = stream; } else{ gl2psMsg(GL2PS_ERROR, "Bad file pointer"); gl2psFree(gl2ps); gl2ps = NULL; return GL2PS_ERROR; } gl2ps->header = GL_TRUE; gl2ps->maxbestroot = 10; gl2ps->options = options; gl2ps->compress = NULL; gl2ps->imagemap_head = NULL; gl2ps->imagemap_tail = NULL; if(gl2ps->options & GL2PS_USE_CURRENT_VIEWPORT){ glGetIntegerv(GL_VIEWPORT, gl2ps->viewport); } else{ for(i = 0; i < 4; i++){ gl2ps->viewport[i] = viewport[i]; } } if(!gl2ps->viewport[2] || !gl2ps->viewport[3]){ gl2psMsg(GL2PS_ERROR, "Incorrect viewport (x=%d, y=%d, width=%d, height=%d)", gl2ps->viewport[0], gl2ps->viewport[1], gl2ps->viewport[2], gl2ps->viewport[3]); gl2psFree(gl2ps); gl2ps = NULL; return GL2PS_ERROR; } gl2ps->threshold[0] = nr ? 1.0F/(GLfloat)nr : 0.064F; gl2ps->threshold[1] = ng ? 1.0F/(GLfloat)ng : 0.034F; gl2ps->threshold[2] = nb ? 1.0F/(GLfloat)nb : 0.100F; gl2ps->colormode = colormode; gl2ps->buffersize = buffersize > 0 ? buffersize : 2048 * 2048; for(i = 0; i < 3; i++){ gl2ps->lastvertex.xyz[i] = -1.0F; } for(i = 0; i < 4; i++){ gl2ps->lastvertex.rgba[i] = -1.0F; gl2ps->lastrgba[i] = -1.0F; } gl2ps->lastlinewidth = -1.0F; gl2ps->lastpattern = 0; gl2ps->lastfactor = 0; gl2ps->imagetree = NULL; gl2ps->primitivetoadd = NULL; gl2ps->zerosurfacearea = GL_FALSE; gl2ps->pdfprimlist = NULL; gl2ps->pdfgrouplist = NULL; gl2ps->xreflist = NULL; /* get default blending mode from current OpenGL state (enabled by default for SVG) */ gl2ps->blending = (gl2ps->format == GL2PS_SVG) ? GL_TRUE : glIsEnabled(GL_BLEND); glGetIntegerv(GL_BLEND_SRC, &gl2ps->blendfunc[0]); glGetIntegerv(GL_BLEND_DST, &gl2ps->blendfunc[1]); if(gl2ps->colormode == GL_RGBA){ gl2ps->colorsize = 0; gl2ps->colormap = NULL; glGetFloatv(GL_COLOR_CLEAR_VALUE, gl2ps->bgcolor); } else if(gl2ps->colormode == GL_COLOR_INDEX){ if(!colorsize || !colormap){ gl2psMsg(GL2PS_ERROR, "Missing colormap for GL_COLOR_INDEX rendering"); gl2psFree(gl2ps); gl2ps = NULL; return GL2PS_ERROR; } gl2ps->colorsize = colorsize; gl2ps->colormap = (GL2PSrgba*)gl2psMalloc(gl2ps->colorsize * sizeof(GL2PSrgba)); memcpy(gl2ps->colormap, colormap, gl2ps->colorsize * sizeof(GL2PSrgba)); glGetIntegerv(GL_INDEX_CLEAR_VALUE, &index); gl2ps->bgcolor[0] = gl2ps->colormap[index][0]; gl2ps->bgcolor[1] = gl2ps->colormap[index][1]; gl2ps->bgcolor[2] = gl2ps->colormap[index][2]; gl2ps->bgcolor[3] = 1.0F; } else{ gl2psMsg(GL2PS_ERROR, "Unknown color mode in gl2psBeginPage"); gl2psFree(gl2ps); gl2ps = NULL; return GL2PS_ERROR; } if(!title){ gl2ps->title = (char*)gl2psMalloc(sizeof(char)); gl2ps->title[0] = '\0'; } else{ gl2ps->title = (char*)gl2psMalloc((strlen(title)+1)*sizeof(char)); strcpy(gl2ps->title, title); } if(!producer){ gl2ps->producer = (char*)gl2psMalloc(sizeof(char)); gl2ps->producer[0] = '\0'; } else{ gl2ps->producer = (char*)gl2psMalloc((strlen(producer)+1)*sizeof(char)); strcpy(gl2ps->producer, producer); } if(!filename){ gl2ps->filename = (char*)gl2psMalloc(sizeof(char)); gl2ps->filename[0] = '\0'; } else{ gl2ps->filename = (char*)gl2psMalloc((strlen(filename)+1)*sizeof(char)); strcpy(gl2ps->filename, filename); } gl2ps->primitives = gl2psListCreate(500, 500, sizeof(GL2PSprimitive*)); gl2ps->auxprimitives = gl2psListCreate(100, 100, sizeof(GL2PSprimitive*)); gl2ps->feedback = (GLfloat*)gl2psMalloc(gl2ps->buffersize * sizeof(GLfloat)); glFeedbackBuffer(gl2ps->buffersize, GL_3D_COLOR, gl2ps->feedback); glRenderMode(GL_FEEDBACK); return GL2PS_SUCCESS; } GL2PSDLL_API GLint gl2psEndPage(void) { GLint res; if(!gl2ps) return GL2PS_UNINITIALIZED; res = gl2psPrintPrimitives(); if(res != GL2PS_OVERFLOW) (gl2psbackends[gl2ps->format]->printFooter)(); fflush(gl2ps->stream); gl2psListDelete(gl2ps->primitives); gl2psListDelete(gl2ps->auxprimitives); gl2psFreeImagemap(gl2ps->imagemap_head); gl2psFree(gl2ps->colormap); gl2psFree(gl2ps->title); gl2psFree(gl2ps->producer); gl2psFree(gl2ps->filename); gl2psFree(gl2ps->feedback); gl2psFree(gl2ps); gl2ps = NULL; return res; } GL2PSDLL_API GLint gl2psBeginViewport(GLint viewport[4]) { if(!gl2ps) return GL2PS_UNINITIALIZED; (gl2psbackends[gl2ps->format]->beginViewport)(viewport); return GL2PS_SUCCESS; } GL2PSDLL_API GLint gl2psEndViewport(void) { GLint res; if(!gl2ps) return GL2PS_UNINITIALIZED; res = (gl2psbackends[gl2ps->format]->endViewport)(); return res; } GL2PSDLL_API GLint gl2psTextOpt(const char *str, const char *fontname, GLshort fontsize, GLint alignment, GLfloat angle) { return gl2psAddText(GL2PS_TEXT, str, fontname, fontsize, alignment, angle); } GL2PSDLL_API GLint gl2psText(const char *str, const char *fontname, GLshort fontsize) { return gl2psAddText(GL2PS_TEXT, str, fontname, fontsize, GL2PS_TEXT_BL, 0.0F); } GL2PSDLL_API GLint gl2psSpecial(GLint format, const char *str) { return gl2psAddText(GL2PS_SPECIAL, str, "", 0, format, 0.0F); } GL2PSDLL_API GLint gl2psDrawPixels(GLsizei width, GLsizei height, GLint xorig, GLint yorig, GLenum format, GLenum type, const void *pixels) { int size, i; GLfloat pos[4], *piv; GL2PSprimitive *prim; GLboolean valid; if(!gl2ps || !pixels) return GL2PS_UNINITIALIZED; if((width <= 0) || (height <= 0)) return GL2PS_ERROR; if(gl2ps->options & GL2PS_NO_PIXMAP) return GL2PS_SUCCESS; if((format != GL_RGB && format != GL_RGBA) || type != GL_FLOAT){ gl2psMsg(GL2PS_ERROR, "gl2psDrawPixels only implemented for " "GL_RGB/GL_RGBA, GL_FLOAT pixels"); return GL2PS_ERROR; } glGetBooleanv(GL_CURRENT_RASTER_POSITION_VALID, &valid); if(GL_FALSE == valid) return GL2PS_SUCCESS; /* the primitive is culled */ glGetFloatv(GL_CURRENT_RASTER_POSITION, pos); prim = (GL2PSprimitive*)gl2psMalloc(sizeof(GL2PSprimitive)); prim->type = GL2PS_PIXMAP; prim->boundary = 0; prim->numverts = 1; prim->verts = (GL2PSvertex*)gl2psMalloc(sizeof(GL2PSvertex)); prim->verts[0].xyz[0] = pos[0] + xorig; prim->verts[0].xyz[1] = pos[1] + yorig; prim->verts[0].xyz[2] = pos[2]; prim->culled = 0; prim->offset = 0; prim->pattern = 0; prim->factor = 0; prim->width = 1; glGetFloatv(GL_CURRENT_RASTER_COLOR, prim->verts[0].rgba); prim->data.image = (GL2PSimage*)gl2psMalloc(sizeof(GL2PSimage)); prim->data.image->width = width; prim->data.image->height = height; prim->data.image->format = format; prim->data.image->type = type; switch(format){ case GL_RGBA: if(gl2ps->options & GL2PS_NO_BLENDING || !gl2ps->blending){ /* special case: blending turned off */ prim->data.image->format = GL_RGB; size = height * width * 3; prim->data.image->pixels = (GLfloat*)gl2psMalloc(size * sizeof(GLfloat)); piv = (GLfloat*)pixels; for(i = 0; i < size; ++i, ++piv){ prim->data.image->pixels[i] = *piv; if(!((i+1)%3)) ++piv; } } else{ size = height * width * 4; prim->data.image->pixels = (GLfloat*)gl2psMalloc(size * sizeof(GLfloat)); memcpy(prim->data.image->pixels, pixels, size * sizeof(GLfloat)); } break; case GL_RGB: default: size = height * width * 3; prim->data.image->pixels = (GLfloat*)gl2psMalloc(size * sizeof(GLfloat)); memcpy(prim->data.image->pixels, pixels, size * sizeof(GLfloat)); break; } gl2psListAdd(gl2ps->auxprimitives, &prim); glPassThrough(GL2PS_DRAW_PIXELS_TOKEN); return GL2PS_SUCCESS; } GL2PSDLL_API GLint gl2psDrawImageMap(GLsizei width, GLsizei height, const GLfloat position[3], const unsigned char *imagemap){ int size, i; int sizeoffloat = sizeof(GLfloat); if(!gl2ps || !imagemap) return GL2PS_UNINITIALIZED; if((width <= 0) || (height <= 0)) return GL2PS_ERROR; size = height + height * ((width-1)/8); glPassThrough(GL2PS_IMAGEMAP_TOKEN); glBegin(GL_POINTS); glVertex3f(position[0], position[1],position[2]); glEnd(); glPassThrough((GLfloat)width); glPassThrough((GLfloat)height); for(i = 0; i < size; i += sizeoffloat){ float *value = (float*)imagemap; glPassThrough(*value); imagemap += sizeoffloat; } return GL2PS_SUCCESS; } GL2PSDLL_API GLint gl2psEnable(GLint mode) { GLint tmp; if(!gl2ps) return GL2PS_UNINITIALIZED; switch(mode){ case GL2PS_POLYGON_OFFSET_FILL : glPassThrough(GL2PS_BEGIN_OFFSET_TOKEN); glGetFloatv(GL_POLYGON_OFFSET_FACTOR, &gl2ps->offset[0]); glGetFloatv(GL_POLYGON_OFFSET_UNITS, &gl2ps->offset[1]); break; case GL2PS_POLYGON_BOUNDARY : glPassThrough(GL2PS_BEGIN_BOUNDARY_TOKEN); break; case GL2PS_LINE_STIPPLE : glPassThrough(GL2PS_BEGIN_STIPPLE_TOKEN); glGetIntegerv(GL_LINE_STIPPLE_PATTERN, &tmp); glPassThrough((GLfloat)tmp); glGetIntegerv(GL_LINE_STIPPLE_REPEAT, &tmp); glPassThrough((GLfloat)tmp); break; case GL2PS_BLEND : glPassThrough(GL2PS_BEGIN_BLEND_TOKEN); break; default : gl2psMsg(GL2PS_WARNING, "Unknown mode in gl2psEnable: %d", mode); return GL2PS_WARNING; } return GL2PS_SUCCESS; } GL2PSDLL_API GLint gl2psDisable(GLint mode) { if(!gl2ps) return GL2PS_UNINITIALIZED; switch(mode){ case GL2PS_POLYGON_OFFSET_FILL : glPassThrough(GL2PS_END_OFFSET_TOKEN); break; case GL2PS_POLYGON_BOUNDARY : glPassThrough(GL2PS_END_BOUNDARY_TOKEN); break; case GL2PS_LINE_STIPPLE : glPassThrough(GL2PS_END_STIPPLE_TOKEN); break; case GL2PS_BLEND : glPassThrough(GL2PS_END_BLEND_TOKEN); break; default : gl2psMsg(GL2PS_WARNING, "Unknown mode in gl2psDisable: %d", mode); return GL2PS_WARNING; } return GL2PS_SUCCESS; } GL2PSDLL_API GLint gl2psPointSize(GLfloat value) { if(!gl2ps) return GL2PS_UNINITIALIZED; glPassThrough(GL2PS_POINT_SIZE_TOKEN); glPassThrough(value); return GL2PS_SUCCESS; } GL2PSDLL_API GLint gl2psLineWidth(GLfloat value) { if(!gl2ps) return GL2PS_UNINITIALIZED; glPassThrough(GL2PS_LINE_WIDTH_TOKEN); glPassThrough(value); return GL2PS_SUCCESS; } GL2PSDLL_API GLint gl2psBlendFunc(GLenum sfactor, GLenum dfactor) { if(!gl2ps) return GL2PS_UNINITIALIZED; if(GL_FALSE == gl2psSupportedBlendMode(sfactor, dfactor)) return GL2PS_WARNING; glPassThrough(GL2PS_SRC_BLEND_TOKEN); glPassThrough((GLfloat)sfactor); glPassThrough(GL2PS_DST_BLEND_TOKEN); glPassThrough((GLfloat)dfactor); return GL2PS_SUCCESS; } GL2PSDLL_API GLint gl2psSetOptions(GLint options) { if(!gl2ps) return GL2PS_UNINITIALIZED; gl2ps->options = options; return GL2PS_SUCCESS; } GL2PSDLL_API const char *gl2psGetFileExtension(GLint format) { if(format >= 0 && format < (GLint)(sizeof(gl2psbackends)/sizeof(gl2psbackends[0]))) return gl2psbackends[format]->file_extension; else return "Unknown format"; } GL2PSDLL_API const char *gl2psGetFormatDescription(GLint format) { if(format >= 0 && format < (GLint)(sizeof(gl2psbackends)/sizeof(gl2psbackends[0]))) return gl2psbackends[format]->description; else return "Unknown format"; } ugene-1.9.8/src/plugins/biostruct3d_view/src/BioStruct3DGLRender.h0000644000175000017500000001401611651544321023515 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_BIOSTRUCT3D_RENDERER_H_ #define _U2_BIOSTRUCT3D_RENDERER_H_ #include #include namespace U2 { class BioStruct3D; class BioStruct3DGLRenderer; class BioStruct3DGLRendererFactory; class BioStruct3DColorScheme; class BioStruct3DRendererSettings; //! Singleton regisrtry for renderers fabrics. class BioStruct3DGLRendererRegistry { public: //! @return Default renderer factory name. static const QString defaultFactoryName(); //! @return List of all factories names. static const QList factoriesNames(); //! @return Concreete factory by name. static const BioStruct3DGLRendererFactory* getFactory(const QString &name); //! @return Constructed renderer by factory name. static BioStruct3DGLRenderer* createRenderer(const QString &name, const BioStruct3D&, const BioStruct3DColorScheme*, const QList&, const BioStruct3DRendererSettings*); /** Check if biostruct can be drawn with renderer */ static bool isAvailableFor(const QString &name, const BioStruct3D &biostruct); /** @returns List of renderer names available for biostruct */ static QList getRenderersAvailableFor(const BioStruct3D &biostruct); private: //! Hidden constructor. Called by getInstance() BioStruct3DGLRendererRegistry(); //! Returns singleton instance of registry. static BioStruct3DGLRendererRegistry* getInstance(); //! Registers all render factories. void registerFactories(); private: QMap factories; }; // class BioStruct3DGLRendererRegistry /** BioStruct3DGLRenderer abstract factory */ class BioStruct3DGLRendererFactory { public: BioStruct3DGLRendererFactory(const QString &_name) : name(_name) {} /** @returns Factory name */ const QString getName() const { return name; } /** Check if biostruct can be drawn with renderer */ virtual bool isAvailableFor(const BioStruct3D &biostruct) const = 0; /** @returns Contructed renderer */ virtual BioStruct3DGLRenderer* createInstance(const BioStruct3D&, const BioStruct3DColorScheme*, const QList &shownModels, const BioStruct3DRendererSettings*) const = 0; private: QString name; }; /** Macro helper for factories defining */ #define RENDERER_FACTORY(c) \ public: \ static const QString ID; \ \ class Factory : public BioStruct3DGLRendererFactory { \ public: \ Factory(const QString &name) : BioStruct3DGLRendererFactory(name) {} \ \ virtual BioStruct3DGLRenderer* createInstance(const BioStruct3D &biostruct, const BioStruct3DColorScheme *cscheme, \ const QList &shownModels, const BioStruct3DRendererSettings *settings) const { \ return new c(biostruct, cscheme, shownModels, settings); \ } \ \ virtual bool isAvailableFor(const BioStruct3D &biostruct) const { \ return c::isAvailableFor(biostruct); \ } \ }; /** Settings common for all renderers */ class BioStruct3DRendererSettings { public: BioStruct3DRendererSettings(float _detailLevel) : detailLevel(_detailLevel) {} float detailLevel; }; //! Abstract biological 3D structure OpenGL renderer class BioStruct3DGLRenderer { protected: BioStruct3DGLRenderer(const BioStruct3D &biostruct, const BioStruct3DColorScheme *scheme, const QList &shownModels, const BioStruct3DRendererSettings *settings); public: virtual ~BioStruct3DGLRenderer() {} /** Create and initialize all stuff. Can be called for full reinialization */ virtual void create() = 0; //! Visualizes macromolecule. virtual void drawBioStruct3D() = 0; //! Used to completely update model, for ex to recreate display lists. virtual void update() {} //! Used to update current color scheme, whenever it is changed. virtual void updateColorScheme() = 0; //! Used to update shown models list, whenever it is changed. virtual void updateShownModels() = 0; /** Used for settings updating */ virtual void updateSettings() = 0; //! Sets new color scheme. void setColorScheme(const BioStruct3DColorScheme* s); //! @returns current color scheme. const BioStruct3DColorScheme *getColorScheme() const { return colorScheme; } /** @returns shown models indexes list reference. * indexes are just index numbers of models, NOT modelIds */ const QList& getShownModelsIndexes() const { return shownModels; } /** Sets shown models models list. */ void setShownModelsIndexes(const QList &_shownModels) { shownModels = _shownModels; } public: /** Check if biostruct can be visualized by renderer */ static bool isAvailableFor(const BioStruct3D &) { return true; } protected: const BioStruct3D& bioStruct; const BioStruct3DColorScheme* colorScheme; protected: QList shownModels; protected: const BioStruct3DRendererSettings* settings; }; } //namespace #endif // _U2_BIOSTRUCT3D_RENDERER_H_ ugene-1.9.8/src/plugins/biostruct3d_view/src/SettingsDialog.cpp0000644000175000017500000002016211651544321023277 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "SettingsDialog.h" #include namespace U2 { BioStruct3DSettingsDialog::BioStruct3DSettingsDialog() : anaglyphStatus(NOT_AVAILABLE), anaglyphSettings(AnaglyphSettings::defaultSettings()) { setupUi(this); glWidget = NULL; initColorSchemes(); } void BioStruct3DSettingsDialog::setWidget(BioStruct3DGLWidget *glWidget) { this->glWidget = glWidget; state = glWidget->getState(); } void BioStruct3DSettingsDialog::initColorSchemes() { glassesColorSchemes.insert(0, GlassesColorScheme(QString(tr("Custom")), QColor(0, 0, 0), QColor(0, 0, 0))); glassesColorSchemes.append(GlassesColorScheme(QString(tr("Red - Blue")), QColor(255, 0, 0), QColor(0, 0, 255))); glassesColorSchemes.append(GlassesColorScheme(QString(tr("Cyan - Red")), QColor(0, 255, 255), QColor(255, 0, 0))); glassesColorSchemes.append(GlassesColorScheme(QString(tr("Red - Dark Cyan")), QColor(255, 0, 0), QColor(0, 139, 139))); glassesColorSchemes.append(GlassesColorScheme(QString(tr("Red - Green")), QColor(255, 0, 0), QColor(0, 150, 0))); glassesColorSchemes.append(GlassesColorScheme(QString(tr("Magenta - Green")), QColor(255, 0, 150), QColor(0, 150, 0))); foreach (const GlassesColorScheme &scheme, glassesColorSchemes) BioStruct3DSettingsDialog::glassesColorSchemeComboBox->addItem(scheme.name); } void BioStruct3DSettingsDialog::sl_setBackgroundColor() { backgroundColor=QColorDialog::getColor(backgroundColor,this); state[glWidget->BACKGROUND_COLOR_NAME] = QVariant::fromValue(backgroundColor); glWidget->setState(state); } void BioStruct3DSettingsDialog::sl_setSelectionColor() { selectionColor=QColorDialog::getColor(selectionColor,this); state[glWidget->SELECTION_COLOR_NAME] = QVariant::fromValue(selectionColor); glWidget->setState(state); } void BioStruct3DSettingsDialog::sl_setRenderDetailLevel() { renderDetailLevel=renderDetailLevelSlider->sliderPosition(); state[glWidget->RENDER_DETAIL_LEVEL_NAME] = QVariant::fromValue((float) renderDetailLevel/100.0); glWidget->setState(state); } void BioStruct3DSettingsDialog::sl_setShadingLevel() { shadingLevel = shadingSlider->sliderPosition(); state[glWidget->SHADING_LEVEL_NAME] = QVariant::fromValue(shadingLevel); glWidget->setState(state); } void BioStruct3DSettingsDialog::sl_setAnaglyph() { anaglyphStatus = (anaglyphViewGroupBox->isChecked()) ? ENABLED : DISABLED; state[glWidget->ANAGLYPH_STATUS_NAME] = qVariantFromValue((int)anaglyphStatus); glWidget->setState(state); } void BioStruct3DSettingsDialog::sl_setEyesShift() { anaglyphSettings.eyesShift = (float) eyesShiftSlider->sliderPosition() / 100.0; anaglyphSettings.toMap(state); glWidget->setState(state); } void BioStruct3DSettingsDialog::sl_setGlassesColorScheme() { int itemNum = glassesColorSchemeComboBox->currentIndex(); setGlassesColorScheme(itemNum); } void BioStruct3DSettingsDialog::sl_setLeftEyeColor() { QColor changed(QColorDialog::getColor(anaglyphSettings.leftEyeColor, this)); if (changed.red()!=0 || changed.green()!=0 || changed.blue()!=0) { setGlassesColorScheme(changed, anaglyphSettings.rightEyeColor); } } void BioStruct3DSettingsDialog::sl_setRightEyeColor() { QColor changed(QColorDialog::getColor(anaglyphSettings.rightEyeColor, this)); if (changed.red()!=0 || changed.green()!=0 || changed.blue()!=0) { setGlassesColorScheme(anaglyphSettings.leftEyeColor, changed); } } void BioStruct3DSettingsDialog::sl_swapColors() { QColor right(anaglyphSettings.rightEyeColor); QColor left(anaglyphSettings.leftEyeColor); setGlassesColorScheme(right, left); } QColor BioStruct3DSettingsDialog::getBackgroundColor()const { return backgroundColor; } QColor BioStruct3DSettingsDialog::getSelectionColor()const { return selectionColor; } float BioStruct3DSettingsDialog::getRenderDetailLevel()const { return renderDetailLevel / 100.0; } void BioStruct3DSettingsDialog::setGlassesColorScheme(QColor &leftEyeColor, QColor &rightEyeColor) { setLeftEyeColor(leftEyeColor); setRightEyeColor(rightEyeColor); int currentNumber=0; foreach(const GlassesColorScheme& scheme, glassesColorSchemes) { if (scheme.leftEyeColor==leftEyeColor && scheme.rightEyeColor==rightEyeColor) { glassesColorSchemeComboBox->setCurrentIndex(currentNumber); return; } currentNumber++; } glassesColorSchemeComboBox->setCurrentIndex(0); } void BioStruct3DSettingsDialog::setGlassesColorScheme(int num) { if (num<=0 || num>glassesColorSchemes.size()) return; GlassesColorScheme need(glassesColorSchemes.at(num)); setLeftEyeColor(need.leftEyeColor); setRightEyeColor(need.rightEyeColor); } void BioStruct3DSettingsDialog::setBackgroundColor(QColor color) { this->backgroundColor=color; } void BioStruct3DSettingsDialog::setSelectionColor(QColor color) { this->selectionColor=color; } void BioStruct3DSettingsDialog::setRenderDetailLevel(float renderDetailLevel_) { renderDetailLevel = renderDetailLevel_ * 100; renderDetailLevelSlider->setSliderPosition(renderDetailLevel); } static const QString COLOR_STYLE("QPushButton { background-color : %1;}");// color : %2; void BioStruct3DSettingsDialog::setLeftEyeColor(QColor leftEyecolor) { anaglyphSettings.leftEyeColor = leftEyecolor; leftEyeColorChangeButton->setStyleSheet(COLOR_STYLE.arg(anaglyphSettings.leftEyeColor.name())); anaglyphSettings.toMap(state); glWidget->setState(state); } void BioStruct3DSettingsDialog::setRightEyeColor(QColor rightEyecolor) { anaglyphSettings.rightEyeColor = rightEyecolor; rightEyeColorChangeButton->setStyleSheet(COLOR_STYLE.arg(anaglyphSettings.rightEyeColor.name())); anaglyphSettings.toMap(state); glWidget->setState(state); } int BioStruct3DSettingsDialog::getShadingLevel() const { return shadingLevel; } void BioStruct3DSettingsDialog::setShadingLevel(int shading) { shadingLevel = shading; shadingSlider->setSliderPosition(shading); } // anaglyph related settings AnaglyphStatus BioStruct3DSettingsDialog::getAnaglyphStatus() const { return anaglyphStatus; } const AnaglyphSettings& BioStruct3DSettingsDialog::getAnaglyphSettings() const { return anaglyphSettings; } void BioStruct3DSettingsDialog::setAnaglyphStatus(AnaglyphStatus status) { anaglyphStatus = status; if (anaglyphStatus == NOT_AVAILABLE) { anaglyphViewGroupBox->setDisabled(true); QString anaglyphTitile = anaglyphViewGroupBox->title(); anaglyphViewGroupBox->setTitle(anaglyphTitile + QString(" ") + QString(tr("(not supported by your videocard)"))); } else if (anaglyphStatus == DISABLED) { anaglyphViewGroupBox->setEnabled(true); anaglyphViewGroupBox->setChecked(false); } else if (anaglyphStatus == ENABLED) { anaglyphViewGroupBox->setEnabled(true); anaglyphViewGroupBox->setChecked(true); } else { assert(!"Invalid AnaglyphStatus value"); } } void BioStruct3DSettingsDialog::setAnaglyphSettings(const AnaglyphSettings &settings) { anaglyphSettings = settings; setLeftEyeColor(anaglyphSettings.leftEyeColor); setRightEyeColor(anaglyphSettings.rightEyeColor); eyesShiftSlider->setSliderPosition(anaglyphSettings.eyesShift * 100.0); } } // namespace ugene-1.9.8/src/plugins/biostruct3d_view/src/SettingsDialog.h0000644000175000017500000000622211651544321022745 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_SETTINGSDIALOG_H_ #define _U2_SETTINGSDIALOG_H_ #include "BioStruct3DGLWidget.h" #include "ui_SettingsDialog.h" #include "AnaglyphRenderer.h" #include namespace U2 { class GlassesColorScheme { public: QColor leftEyeColor; QColor rightEyeColor; QString name; GlassesColorScheme() { name=""; leftEyeColor=QColor(0, 0, 0); rightEyeColor = leftEyeColor; } GlassesColorScheme(QString name, QColor leftEyeColor, QColor rightEyeColor) { this->name = name; this->leftEyeColor = leftEyeColor; this->rightEyeColor = rightEyeColor; } }; class BioStruct3DSettingsDialog : public QDialog, private Ui::SettingsDialog { Q_OBJECT public: BioStruct3DSettingsDialog(); private slots: void sl_setBackgroundColor(); void sl_setSelectionColor(); void sl_setShadingLevel(); void sl_setRenderDetailLevel(); void sl_setAnaglyph(); void sl_setEyesShift(); void sl_setGlassesColorScheme(); void sl_setLeftEyeColor(); void sl_setRightEyeColor(); void sl_swapColors(); public: // anaglyph related settings AnaglyphStatus getAnaglyphStatus() const; const AnaglyphSettings& getAnaglyphSettings() const; void setAnaglyphStatus(AnaglyphStatus status); void setAnaglyphSettings(const AnaglyphSettings &settings); void setRightEyeColor(QColor rightEyecolor); void setLeftEyeColor(QColor leftEyecolor); QColor getBackgroundColor()const; QColor getSelectionColor()const; float getRenderDetailLevel()const; int getShadingLevel()const; void setBackgroundColor(QColor color); void setSelectionColor(QColor color); void setGlassesColorScheme(QColor &leftEyeColor, QColor &rightEyeColor); void setGlassesColorScheme(int num); void setRenderDetailLevel(float renderDetailLevel); void setShadingLevel(int shading); void setWidget(BioStruct3DGLWidget *glWidget); private: QVariantMap state; BioStruct3DGLWidget *glWidget; QList glassesColorSchemes; void initColorSchemes(); QColor backgroundColor; QColor selectionColor; int renderDetailLevel; int shadingLevel; AnaglyphStatus anaglyphStatus; AnaglyphSettings anaglyphSettings; }; } // namespace #endif // _U2_SETTINGSDIALOG_H_ ugene-1.9.8/src/plugins/biostruct3d_view/src/StructuralAlignmentDialog.cpp0000644000175000017500000001102511651544321025504 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "StructuralAlignmentDialog.h" #include "BioStruct3DSubsetEditor.h" #include #include #include #include #include #include #include #include namespace U2 { /* class StructuralAlignmentDialog : public QDialog, public Ui::StructuralAlignmentDialog */ static QList findAvailableBioStructs() { QList objs = GObjectUtils::findAllObjects(UOF_LoadedOnly, GObjectTypes::BIOSTRUCTURE_3D); QList biostructs; foreach (GObject *obj, objs) { BioStruct3DObject *bso = qobject_cast (obj); assert(bso); biostructs << bso; } return biostructs; } StructuralAlignmentDialog::StructuralAlignmentDialog(const BioStruct3DObject *fixedRef/* = 0*/, int fixedRefModel/* = -1*/, QWidget *parent/* = 0*/) : QDialog(parent), task(0) { setupUi(this); StructuralAlignmentAlgorithmRegistry *reg = AppContext::getStructuralAlignmentAlgorithmRegistry(); foreach (const QString &id, reg->getFactoriesIds()) { algorithmCombo->addItem(id, qVariantFromValue(id)); } QList biostructs = findAvailableBioStructs(); ref = new BioStruct3DSubsetEditor(biostructs, fixedRef, fixedRefModel); mob = new BioStruct3DSubsetEditor(biostructs); if (fixedRef) { ref->setBiostructDisabled(); } if (fixedRefModel != -1) { ref->setModelDisabled(); } QVBoxLayout *refBox = new QVBoxLayout(); refBox->addWidget(ref); refGroup->setLayout(refBox); QVBoxLayout *altBox = new QVBoxLayout(); altBox->addWidget(mob); altGroup->setLayout(altBox); updateGeometry(); } void StructuralAlignmentDialog::accept() { if (algorithmCombo->count() < 1) { return; } QString msg, err; err = ref->validate(); if (!err.isEmpty()) { msg += QString("Reference: ") + err + "\n"; } err = mob->validate(); if (!err.isEmpty()) { msg += QString("Mobile: ") + err + "\n"; } if (!msg.isEmpty()) { QMessageBox::warning(this, "Error", msg); return; } BioStruct3DReference refSubset(ref->getSubset()); BioStruct3DReference mobSubset(mob->getSubset()); // Since we unable to change mob structure we clone the GObject BioStruct3DObject *mobClone = qobject_cast (mobSubset.obj->clone()); mobSubset.obj = mobClone; StructuralAlignmentTaskSettings settings(refSubset, mobSubset); StructuralAlignmentAlgorithmRegistry *reg = AppContext::getStructuralAlignmentAlgorithmRegistry(); QString algorithmId = algorithmCombo->itemData(algorithmCombo->currentIndex()).value(); StructuralAlignmentAlgorithm *algorithm = reg->createStructuralAlignmentAlgorithm(algorithmId); err = algorithm->validate(settings); if (!err.isEmpty()) { msg = QString("%1 validate failed: %2").arg(algorithmId).arg(err); QMessageBox::warning(this, "Error", msg); return; } task = new StructuralAlignmentTask(algorithm, settings); QDialog::accept(); } int StructuralAlignmentDialog::execIfAlgorithmAvailable() { StructuralAlignmentAlgorithmRegistry *reg = AppContext::getStructuralAlignmentAlgorithmRegistry(); if (reg->getFactoriesIds().isEmpty()) { QMessageBox::warning(this, "Error", "No available algorithms, make sure that apropriate plugin loaded (for ex. PTools)"); return Rejected; } else { return exec(); } } } // namespace U2 ugene-1.9.8/src/plugins/biostruct3d_view/src/WormsGLRenderer.h0000644000175000017500000000576711651544321023063 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_BIOSTRUCT3D_WORMS_RENDERER_H_ #define _U2_BIOSTRUCT3D_WORMS_RENDERER_H_ #include #include #include #include #include #include "BioStruct3DGLRender.h" #include "GraphicUtils.h" class Object3D; class AtomData; namespace U2 { class WormsGLRenderer : public BioStruct3DGLRenderer { // BioPolymer molecule struct Monomer { Monomer() : alphaCarbon(NULL), carbonylOxygen(NULL) {} QSharedDataPointer alphaCarbon; QSharedDataPointer carbonylOxygen; }; struct BioPolymerModel { QMap monomerMap; }; struct BioPolymer { // multiple models QVector bpModels; }; QMap bioPolymerMap; // Worm Model typedef QVector AtomsVector; struct WormModel { //! These coords required to draw worms endings correctly Vector3D openingAtom, closingAtom; // Worm building atom coords AtomsVector atoms; // Objects representing secondary structure QVector objects; }; struct Worm { QVector models; }; QMap wormMap; Color4f atomColor; void createObjects3D(); Object3D* createStrand3D( int startId, int endId, const BioPolymerModel &bpModel ); Object3D* createHelix3D( int startId, int endId, const BioPolymerModel &bpModel ); void createWorms(); void drawWorms(); void drawSecondaryStructure(); const float* getAtomColor(const SharedAtom& atom); protected: WormsGLRenderer(const BioStruct3D& struc, const BioStruct3DColorScheme* s, const QList &shownModels, const BioStruct3DRendererSettings *settings); public: virtual ~WormsGLRenderer(); virtual void create(); virtual void drawBioStruct3D(); virtual void updateColorScheme(); virtual void updateShownModels(); virtual void updateSettings(); public: static bool isAvailableFor(const BioStruct3D &); RENDERER_FACTORY(WormsGLRenderer) }; } //namespace #endif // _U2_BIOSTRUCT3D_WORMS_RENDERER_H_ ugene-1.9.8/src/plugins/biostruct3d_view/src/BioStruct3DSplitter.h0000644000175000017500000001500711651544321023662 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include #include #include #include #include #include #include #include namespace U2 { class BioStruct3DObject; class BioStruct3DGLWidget; class AnnotatedDNAView; class GObject; class GObjectView; class SplitterHeaderWidget; class Document; class GLFrameManager; /*! * @class BioStruct3DSplitter BioStruct3DSplitter.h * @brief Class for multiple BioStruct3DWidget layout. * * This widget provides insertion of BioStruct3DGLWidgets into active UGENE view. There * could be one or more glWidgets controlled by the splitter. One can add new glWidgets using * the splitter. */ class BioStruct3DSplitter : public ADVSplitWidget { Q_OBJECT public: /*! * Constructor. * @param closeAction QAction provided for correct widget closing * @param view DnaView context for connecting structure 3D representation and sequence view */ BioStruct3DSplitter(QAction* closeAction, AnnotatedDNAView* view); /*! * Destructor. */ ~BioStruct3DSplitter(); /*! * @return True, if GObject has type BioStruct3D and could be added to splitter. */ virtual bool acceptsGObject(GObject* obj); /*! * Creates BioStruct3DWidget for object visualization and adds it to the splitter. */ BioStruct3DGLWidget* addBioStruct3DGLWidget(BioStruct3DObject* obj); /*! * @return First found BioStruct3DObject with corresponding name, NULL if nothing is found. */ BioStruct3DObject* findBioStruct3DObjByName(const QString& objName); virtual void saveState(QVariantMap& m); virtual void updateState(const QVariantMap& m); /*! * @return List of splitter children widgets. */ QList getChildWidgets(); /*! * @return Current active view. */ const QList getSettingsMenuActions() const; /*! * @return ADVDNAView splitter, parent widget for BioStruct3DSplitter. */ int getNumVisibleWidgets(); /*! * @return If number of visible children is null, sets splitter view collapsed, else restores it. */ void adaptSize(int numVisibleWidgets); /*! * @return GLFrameManager for splitter child widgets. */ GLFrameManager* getGLFrameManager(); /*! *Removes widgets, updates context */ void removeBioStruct3DGLWidget(BioStruct3DGLWidget* widget); /*! * This is used to close 3D split widget from toolbar */ QAction* getCloseSplitterAction() { return closeAction; } /*! * QWidget virtual function, returns preferred widget size. */ virtual QSize sizeHint () const {return QSize(0, 400);} /*! * Adds object and its new view. */ void addObject(BioStruct3DObject* obj); /*! * AddModelTask helper function. */ void addModelFromObject(BioStruct3DObject* obj); /*! * Removes object and its views. */ bool removeObject(BioStruct3DObject* obj); signals: void si_bioStruct3DGLWidgetAdded(BioStruct3DGLWidget* widget); void si_bioStruct3DGLWidgetRemoved(BioStruct3DGLWidget* widget); protected: void dragEnterEvent(QDragEnterEvent *event); void dropEvent(QDropEvent *event); bool eventFilter(QObject* o, QEvent* e); private: QSplitter* getParentSplitter(); QMultiMap biostrucViewMap; std::auto_ptr glFrameManager; QSplitter* splitter; QSplitter* parentSplitter; QAction* closeAction; QLayout* layout; QList toggleActions; int splitterHeight; bool isViewCollapsed; SplitterHeaderWidget* header; }; struct DBLink { DBLink(const QString& _name, QString _url) : name(_name), url(_url) { } QString name; QString url; }; class DBLinksFile { QList links; public: bool load(); QList getLinks() { return links; }; }; // Implemented as Task for unloaded documents support class AddModelToSplitterTask : public Task { Q_OBJECT public: AddModelToSplitterTask(GObject* o, BioStruct3DSplitter* s); virtual void prepare(); virtual void run(); virtual ReportResult report(); private: Document* doc; GObject* obj; BioStruct3DObject* bObj; BioStruct3DSplitter* splitter; }; class SplitterHeaderWidget : public QWidget { Q_OBJECT public: SplitterHeaderWidget(BioStruct3DSplitter* splitter); private: BioStruct3DSplitter* splitter; QToolButton* widgetStateMenuButton; QToolButton* addModelButton; QToolButton* settingsMenuButton; QToolButton* webMenuButton; QToolButton* displayMenuButton; QToolButton* restoreDefaultsButton; QToolButton* zoomInButton; QToolButton* zoomOutButton; QToolButton* syncLockButton; QComboBox* activeWidgetBox; QMap webActionMap; QList toggleActions; protected: bool eventFilter(QObject *obj, QEvent *event); private slots: void sl_bioStruct3DGLWidgetAdded(BioStruct3DGLWidget* glWidget); void sl_bioStruct3DGLWidgetRemoved(BioStruct3DGLWidget* glWidget); void sl_toggleBioStruct3DWidget(bool visible); void sl_toggleSyncLock(bool on); void sl_addModel(); void sl_showStateMenu(); void sl_showDisplayMenu(); void sl_showSettingsMenu(); void sl_showWebMenu(); void sl_zoomIn(); void sl_zoomOut(); void sl_restoreDefaults(); void sl_openBioStructUrl(); private: BioStruct3DGLWidget* getActiveWidget(); void updateToolbar(); void updateActiveWidgetBox(); void enableToolbar(); void registerWebUrls(); void setActiveView(BioStruct3DGLWidget* glWidget); }; } //namespace ugene-1.9.8/src/plugins/biostruct3d_view/src/TubeGLRenderer.h0000644000175000017500000000353211651544321022637 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_BIOSTRUCT3D_TUBE_RENDERER_H_ #define _U2_BIOSTRUCT3D_TUBE_RENDERER_H_ #include #include #include #include "BioStruct3DGLRender.h" namespace U2 { class TubeGLRenderer : public BioStruct3DGLRenderer { typedef QVector< SharedAtom > AtomsVector; struct Tube { QMap modelsMap; }; QMap tubeMap; void drawTubes(const BioStruct3DColorScheme* colorScheme); protected: TubeGLRenderer(const BioStruct3D& struc, const BioStruct3DColorScheme* s, const QList &shownModels, const BioStruct3DRendererSettings *settings); public: void drawBioStruct3D(); virtual void create(); virtual void updateColorScheme() {}; virtual void updateShownModels() {}; virtual void updateSettings() {}; public: static bool isAvailableFor(const BioStruct3D &); RENDERER_FACTORY(TubeGLRenderer) }; } //namespace #endif // _U2_BIOSTRUCT3D_TUBE_RENDERER_H_ ugene-1.9.8/src/plugins/biostruct3d_view/src/MolecularSurfaceRenderer.h0000644000175000017500000000617011651544321024752 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_MOLECULAR_SURFACE_RENDERER_H_ #define _U2_MOLECULAR_SURFACE_RENDERER_H_ #include #include namespace U2 { class MolecularSurface; class MolecularSurfaceRenderer; class MolecularSurfaceRendererFactory; //! Singleton regisrtry for molecular surface(ms) renderers fabrics. class MolecularSurfaceRendererRegistry { public: //! @return Default ms renderer factory name. static const QString defaultFactoryName(); //! @return List of all factories names. static const QList factoriesNames(); //! @return Concreete factory by name. static const MolecularSurfaceRendererFactory* getFactory(const QString &name); //! @return Constructed ms renderer by factory name. static MolecularSurfaceRenderer* createMSRenderer(const QString &name); private: //! Hidden constructor. Called by getInstance() MolecularSurfaceRendererRegistry(); //! Returns singleton instance of registry. static MolecularSurfaceRendererRegistry* getInstance(); //! Registers all ms render factories. void registerFactories(); private: QMap factories; }; // class MolecularSurfaceRendererRegistry //! MolecularSurfaceRenderer abstract factory class MolecularSurfaceRendererFactory { public: virtual MolecularSurfaceRenderer* createInstance() const = 0; }; // class MolecularSurfaceRendererFactory #define SURF_RENDERER_FACTORY(c) \ public: \ static const QString ID; \ class Factory : public MolecularSurfaceRendererFactory { \ public: \ MolecularSurfaceRenderer* createInstance() const { return new c; } \ }; class MolecularSurfaceRenderer { protected: MolecularSurfaceRenderer() {}; public: virtual ~MolecularSurfaceRenderer() {}; virtual void drawSurface(MolecularSurface& surface) = 0; }; class DotsRenderer : public MolecularSurfaceRenderer { private: DotsRenderer() : MolecularSurfaceRenderer() {} public: virtual void drawSurface(MolecularSurface& surface); SURF_RENDERER_FACTORY(DotsRenderer) }; class ConvexMapRenderer : public MolecularSurfaceRenderer { public: ConvexMapRenderer() {} virtual void drawSurface(MolecularSurface& surface); SURF_RENDERER_FACTORY(ConvexMapRenderer) }; } //namespace #endif //_U2_MOLECULAR_SURFACE_RENDERER_H_ ugene-1.9.8/src/plugins/biostruct3d_view/src/BioStruct3DSubsetEditor.h0000644000175000017500000000455511651544321024476 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_BIOSTRUCT3D_SUBSET_EDITOR_H_ #define _U2_BIOSTRUCT3D_SUBSET_EDITOR_H_ #include "ui_BioStruct3DSubsetEditor.h" #include namespace U2 { class U2Region; class BioStruct3DObject; class BioStruct3DReference; class BioStruct3DSubsetEditor : public QWidget, public Ui::BioStruct3DSubsetEditor { Q_OBJECT public: /** @param biostructs List of biostruct objects in which user can select * @param selected Pre selected biostruct * @param selectedModel Pre selected model */ BioStruct3DSubsetEditor(const QList &biostructs, const BioStruct3DObject *selected = 0, int selectedModel = -1, QWidget *parent = 0); /** Fill model ComboBox respectively with current biostruct */ void fillModelCombo(); /** Fill chain ComboBox respectively with current biostruct */ void fillChainCombo(); /** Fill region Edit respectively with current chain */ void fillRegionEdit(); /** Validate the subset. * @returns "" on 0k, error message on fail */ QString validate(); /** Fill and @return choosen subset */ BioStruct3DReference getSubset(); void setBiostructDisabled(); void setModelDisabled(); private: /** Convert text from region Edit to U2Region */ U2Region getRegion(); /** Set text in region Edit from U2Region */ void setRegion(const U2Region ®ion); private slots: void sl_onBiostructChanged(int); void sl_onChainChanged(int); }; } // namespace U2 #endif // #ifndef _U2_BIOSTRUCT3D_SUBSET_EDITOR_H_ ugene-1.9.8/src/plugins/biostruct3d_view/src/ExportImage3DGLDialog.h0000644000175000017500000000251311651544321024002 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_EXPORT_IMAGE_3DGL_DIALOG_H_ #define _U2_EXPORT_IMAGE_3DGL_DIALOG_H_ #include namespace U2 { class BioStruct3DGLWidget; class ExportImage3DGLDialog : public ExportImageDialog { Q_OBJECT public: ExportImage3DGLDialog(BioStruct3DGLWidget* widget); virtual bool exportToSVG(); virtual bool exportToPDF(); virtual bool exportToBitmap(); private: BioStruct3DGLWidget* glWidget; }; // class ExportImage3DGLDialog } // namespace #endif ugene-1.9.8/src/plugins/biostruct3d_view/src/BallAndStickGLRenderer.h0000644000175000017500000000322711651544321024234 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_BIOSTRUCT3D_BALLANDSTICK_RENDERER_H_ #define _U2_BIOSTRUCT3D_BALLANDSTICK_RENDERER_H_ #include "BioStruct3DGLRender.h" #include namespace U2 { class BallAndStickGLRenderer : public BioStruct3DGLRenderer { protected: BallAndStickGLRenderer(const BioStruct3D& struc, const BioStruct3DColorScheme* s, const QList &shownModels, const BioStruct3DRendererSettings *settings); public: virtual ~BallAndStickGLRenderer(); void drawBioStruct3D(); virtual void create(); virtual void update(); virtual void updateColorScheme(); virtual void updateShownModels(); virtual void updateSettings(); private: void createDisplayList(); private: GLuint dl; RENDERER_FACTORY(BallAndStickGLRenderer) }; } //namespace #endif // _U2_BIOSTRUCT3D_BALLANDSTICK_RENDERER_H_ ugene-1.9.8/src/plugins/biostruct3d_view/src/BioStruct3DColorScheme.h0000644000175000017500000001263311651544321024261 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_BIOSTRUCT3D_COLORSCHEME_H #define _U2_BIOSTRUCT3D_COLORSCHEME_H #include #include #include #include #include #include #include "GraphicUtils.h" namespace U2 { class BioStruct3DObject; class BioStruct3DColorScheme; class BioStruct3DColorSchemeFactory; class LRegionsSelection; class U2Region; //! Singleton regisrtry for color scheme fabrics. class BioStruct3DColorSchemeRegistry { public: //! @return Default colo scheme factory name. static const QString defaultFactoryName(); //! @return List of all factories names. static const QList factoriesNames(); //! @return Concreete factory by name. static const BioStruct3DColorSchemeFactory* getFactory(const QString &name); //! @return Constructed color scheme by factory name. static BioStruct3DColorScheme* createColorScheme(const QString &name, const BioStruct3DObject *biostruct); private: //! Hidden constructor. Called by getInstance() BioStruct3DColorSchemeRegistry(); //! Returns singleton instance of registry. static BioStruct3DColorSchemeRegistry* getInstance(); //! Registers all render factories. void registerFactories(); private: QMap factories; }; // class BioStruct3DColorSchemeRegistry //! Abstract factory for BioStruct3DColorScheme class BioStruct3DColorSchemeFactory { public: virtual BioStruct3DColorScheme* createInstance(const BioStruct3DObject *biostruct) const = 0; //! Method creates factories }; #define COLOR_SCHEME_FACTORY(c) \ public: \ static const QString schemeName; \ class Factory : public BioStruct3DColorSchemeFactory { \ public: \ BioStruct3DColorScheme* createInstance(const BioStruct3DObject *biostrucObj) const { return new c(biostrucObj); } \ }; //! Abstract BioStruct3DColorScheme /*! * Color scheme determines 3d structure coloring style. For example, we could use colors to mark chemical * elements or secondary structure. */ class BioStruct3DColorScheme { protected: BioStruct3DColorScheme(const BioStruct3DObject *biostruct); public: virtual ~BioStruct3DColorScheme() {}; Color4f getAtomColor(const SharedAtom& atom) const; void updateSelectionRegion(int chainID, const QVector& added, const QVector& removed); bool isInSelection(const SharedAtom& atom) const; void setSelectionColor(QColor color); void setUnselectedShadingLevel(float shading); protected: virtual Color4f getSchemeAtomColor(const SharedAtom& atom) const; protected: Color4f defaultAtomColor; Color4f selectionColor; BioStruct3DChainSelection selection; private: float unselectedShading; }; // class BioStruct3DColorScheme class ChemicalElemColorScheme : public BioStruct3DColorScheme { QHash elementColorMap; ChemicalElemColorScheme(const BioStruct3DObject *biostruct); virtual Color4f getSchemeAtomColor(const SharedAtom& atom) const; public: COLOR_SCHEME_FACTORY(ChemicalElemColorScheme) }; // class ChemicalElemColorScheme class ChainsColorScheme : public BioStruct3DColorScheme { QMap chainColorMap; ChainsColorScheme(const BioStruct3DObject *biostruct); virtual Color4f getSchemeAtomColor(const SharedAtom& atom) const; private: //! @return Molecular chain colors for biostruct object. static const QMap getChainColors(const BioStruct3DObject *biostruct); public: COLOR_SCHEME_FACTORY(ChainsColorScheme) }; // class ChainsColorScheme class SecStructColorScheme : public BioStruct3DColorScheme { struct MolStructs { QHash strucResidueTable; }; QMap secStrucColorMap; QMap molMap; SecStructColorScheme(const BioStruct3DObject *biostruct); virtual Color4f getSchemeAtomColor(const SharedAtom& atom) const; private: //! @return Secondary structure annotation colors for biostruct object. static const QMap getSecStructAnnotationColors(const BioStruct3DObject *biostruct); public: COLOR_SCHEME_FACTORY(SecStructColorScheme) }; // class SecStructColorScheme /** One color scheme for debug purposes */ class SimpleColorScheme : public BioStruct3DColorScheme { SimpleColorScheme(const BioStruct3DObject *biostruct); private: static QVector colors; static void createColors(); public: COLOR_SCHEME_FACTORY(SimpleColorScheme) }; // class SimpleColorScheme } // namespace U2 #endif //_U2_BIOSTRUCT3D_COLORSCHEME_H_ ugene-1.9.8/src/plugins/biostruct3d_view/src/TubeGLRenderer.cpp0000644000175000017500000001075711651544321023201 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include #include "GraphicUtils.h" #include "BioStruct3DColorScheme.h" #include "BioStruct3DGLWidget.h" #include "TubeGLRenderer.h" namespace U2 { const QString TubeGLRenderer::ID(QObject::tr("Tubes")); void TubeGLRenderer::drawTubes( const BioStruct3DColorScheme* colorScheme ) { GLUquadricObj *pObj; // Quadric Object pObj = gluNewQuadric(); gluQuadricNormals(pObj, GLU_SMOOTH); bool firstPass = true; static float ribbonThickness = 0.3f; SharedAtom bufAtom; foreach (Tube tube, tubeMap) { foreach (int index, shownModels) { const AtomsVector& tubeAtoms = tube.modelsMap.value(index); foreach(const SharedAtom atom, tubeAtoms) { Color4f atomColor = colorScheme->getAtomColor(atom); Vector3D pos = atom.constData()->coord3d; glMaterialfv(GL_FRONT, GL_AMBIENT_AND_DIFFUSE, atomColor.getConstData()); glDrawAtom(pObj, pos, ribbonThickness, settings->detailLevel); if (!firstPass) { // Draw bonds only between atoms of the same molecular chain if (atom.constData()->chainIndex == bufAtom.constData()->chainIndex) { // ... and when they are sequential if (atom.constData()->residueIndex.toInt() - bufAtom.constData()->residueIndex.toInt() == 1) { Vector3D bufPos = bufAtom.constData()->coord3d; Color4f bufAtomColor = colorScheme->getAtomColor(bufAtom); glDrawHalfBond(pObj, bufPos, pos, ribbonThickness, settings->detailLevel); glMaterialfv(GL_FRONT, GL_AMBIENT_AND_DIFFUSE, bufAtomColor.getConstData()); glDrawHalfBond(pObj, pos, bufPos, ribbonThickness, settings->detailLevel); } } } else { firstPass = false; } bufAtom = atom; } } } gluDeleteQuadric(pObj); } void TubeGLRenderer::drawBioStruct3D() { drawTubes(colorScheme); } TubeGLRenderer::TubeGLRenderer( const BioStruct3D& struc, const BioStruct3DColorScheme* s, const QList &shownModels, const BioStruct3DRendererSettings *settings ) : BioStruct3DGLRenderer(struc,s,shownModels,settings) { create(); } bool TubeGLRenderer::isAvailableFor(const BioStruct3D &bioStruct) { bool available = false; const char* alphaCarbonTag = "CA"; const char* phosporTag = "P"; foreach (const SharedMolecule mol, bioStruct.moleculeMap) { int modelId = 0; foreach (const Molecule3DModel& model, mol->models) { foreach (const SharedAtom atom, model.atoms) { if ( (atom->name.trimmed() == alphaCarbonTag) || (atom->name.trimmed() == phosporTag)) { available = true; } } ++modelId; } } return available; } void TubeGLRenderer::create() { assert(isAvailableFor(bioStruct) && "Availability must be checked first!"); tubeMap.clear(); const char* alphaCarbonTag = "CA"; const char* phosporTag = "P"; foreach (const SharedMolecule mol, bioStruct.moleculeMap) { int modelId = 0; foreach (const Molecule3DModel& model, mol->models) { foreach (const SharedAtom atom, model.atoms) { if ( (atom->name.trimmed() == alphaCarbonTag) || (atom->name.trimmed() == phosporTag)) { tubeMap[atom->chainIndex].modelsMap[modelId].append(atom); } } ++modelId; } } } } //namespace ugene-1.9.8/src/plugins/biostruct3d_view/src/BioStruct3DSplitter.cpp0000644000175000017500000006057511651544321024227 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "BioStruct3DSplitter.h" #include "BioStruct3DGLWidget.h" #include "GLFrameManager.h" namespace U2 { #define HEADER_HEIGHT 24 #define MAX_SPLITTER_HEIGHT 1000 BioStruct3DSplitter::BioStruct3DSplitter(QAction* _closeAction, AnnotatedDNAView* view) : ADVSplitWidget(view), glFrameManager(new GLFrameManager), parentSplitter(NULL) { closeAction = _closeAction; layout = new QVBoxLayout; layout->setSpacing(0); layout->setContentsMargins(0,0,3,0); splitter = new QSplitter(Qt::Horizontal); splitterHeight = 400; setMinimumHeight(HEADER_HEIGHT); setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred); setAcceptDrops(true); header = new SplitterHeaderWidget(this); layout->addWidget(header); layout->addWidget(splitter); isViewCollapsed = false; setLayout(layout); } bool BioStruct3DSplitter::acceptsGObject( GObject* obj ) { if (obj->getGObjectType() == GObjectTypes::BIOSTRUCTURE_3D) { return true; } else { return false; } } BioStruct3DGLWidget* BioStruct3DSplitter::addBioStruct3DGLWidget( BioStruct3DObject* bioStructObj ) { if (isViewCollapsed) { adaptSize(1); } BioStruct3DGLWidget* glWidget = new BioStruct3DGLWidget(bioStructObj, dnaView, getGLFrameManager(), this); glWidget->installEventFilter(this); // Add widget to splitter biostrucViewMap.insert(bioStructObj, glWidget); splitter->addWidget(glWidget); emit si_bioStruct3DGLWidgetAdded(glWidget); return glWidget; } void BioStruct3DSplitter::removeBioStruct3DGLWidget( BioStruct3DGLWidget* glw ) { // safe to remove widgets from map - it will be deleted later when // splitter is deleted QMutableMapIterator i(biostrucViewMap); while (i.hasNext()) { if (i.next().value() == glw) { i.remove(); break; } } glFrameManager->removeGLWidgetFrame(glw); emit si_bioStruct3DGLWidgetRemoved(glw); glw->deleteLater(); } bool BioStruct3DSplitter::eventFilter(QObject* o, QEvent* e) { Q_UNUSED(o); Q_UNUSED(e); BioStruct3DGLWidget* glw = qobject_cast(o); #ifdef Q_WS_X11 //first variant of fix of QT4 bug: GL widget is frozen after minimize/maximize if (e->type() == QEvent::Hide) { glw->makeCurrent(); //these 2 lines can be removed glFinish(); return true; } //second variant of fix of QT4 bug: GL widget is frozen after minimize/maximize if (e->type() == QEvent::WindowActivate) { // ((QGLContext*)glw->context())->create(); } #endif if (e->type() == QEvent::Close && glw != NULL) { removeBioStruct3DGLWidget(glw); if (biostrucViewMap.isEmpty()) { closeAction->trigger(); } } return false; } void BioStruct3DSplitter::addObject(BioStruct3DObject* bioStructObj) { if (!biostrucViewMap.contains(bioStructObj)) { setVisible(true); addBioStruct3DGLWidget(bioStructObj); } } bool BioStruct3DSplitter::removeObject(BioStruct3DObject* obj) { QList toDelete = biostrucViewMap.values(obj); foreach(BioStruct3DGLWidget* glw, toDelete) { removeBioStruct3DGLWidget(glw); } biostrucViewMap.remove(obj); bool isEmpty = biostrucViewMap.isEmpty(); return isEmpty; } void BioStruct3DSplitter::dragEnterEvent(QDragEnterEvent *event) { const QMimeData* md = event->mimeData(); const GObjectMimeData* gomd = qobject_cast(md); if (gomd != NULL) { GObject* obj = gomd->objPtr.data(); if (obj->getGObjectType() == GObjectTypes::BIOSTRUCTURE_3D) { BioStruct3DObject* bioStrucObj = qobject_cast(gomd->objPtr.data()); if (biostrucViewMap.contains(bioStrucObj)) event->acceptProposedAction(); } } } void BioStruct3DSplitter::dropEvent(QDropEvent *event) { const GObjectMimeData* gomd = qobject_cast(event->mimeData()); BioStruct3DObject* bioStrucObj = qobject_cast(gomd->objPtr.data()); Q_ASSERT(bioStrucObj != NULL); addBioStruct3DGLWidget(bioStrucObj); } #define SPLITTER_STATE_MAP_NAME "BIOSTRUCT3DSPLITTER_MAP" #define WIDGET_STATE_LIST_NAME "WIDGET_STATE_MAP" #define OBJECT_ID_NAME "OBJECT_ID" BioStruct3DSplitter::~BioStruct3DSplitter() { uiLog.trace("BioStruct3DSplitter deleted"); } void BioStruct3DSplitter::saveState( QVariantMap& m ) { QVariantMap splitterStateMap = m.value(SPLITTER_STATE_MAP_NAME).toMap(); QVariantList glWidgetStateList = m.value(WIDGET_STATE_LIST_NAME).toList(); foreach (BioStruct3DGLWidget* glWidget, biostrucViewMap) { QVariantMap widgetState = glWidget->getState(); glWidgetStateList.append(widgetState); } splitterStateMap[WIDGET_STATE_LIST_NAME] = glWidgetStateList; m[SPLITTER_STATE_MAP_NAME] = splitterStateMap; } void BioStruct3DSplitter::updateState( const QVariantMap& m ) { const QVariantMap splitterStateMap = m.value(SPLITTER_STATE_MAP_NAME).toMap(); const QVariantList glWidgetStateList = splitterStateMap.value(WIDGET_STATE_LIST_NAME).toList(); // do nothing if the widget was closed if (glWidgetStateList.isEmpty()) { return; } foreach (BioStruct3DGLWidget* widget, biostrucViewMap.values()) { widget->hide(); removeBioStruct3DGLWidget(widget); } assert(biostrucViewMap.isEmpty()); setVisible(true); QListIterator iter(glWidgetStateList); iter.toBack(); while (iter.hasPrevious()) { QVariantMap state = iter.previous().toMap(); QString objName = state.value(OBJECT_ID_NAME).value(); BioStruct3DObject* obj = findBioStruct3DObjByName(objName); if (obj == NULL) continue; BioStruct3DGLWidget* glWidget = addBioStruct3DGLWidget(obj); if (!dnaView->getObjects().contains(obj)) { dnaView->addObject(obj); } glWidget->setState(state); } splitter->update(); } BioStruct3DObject* BioStruct3DSplitter::findBioStruct3DObjByName( const QString& objName ) { // TODO: optimize this by caching objects QList docs = AppContext::getProject()->getDocuments(); foreach (Document* doc, docs) { QList biostructObjs = doc->findGObjectByType(GObjectTypes::BIOSTRUCTURE_3D); if (!biostructObjs.empty()) { Q_ASSERT(biostructObjs.size() == 1); BioStruct3DObject* obj = qobject_cast(biostructObjs.first()); Q_ASSERT(obj != NULL); if (obj->getGObjectName() == objName) { return obj; } } } return NULL; } QSplitter* BioStruct3DSplitter::getParentSplitter() { if (parentSplitter == NULL) { QWidget* widget = parentWidget(); Q_ASSERT(widget != NULL); parentSplitter = qobject_cast (widget); } return parentSplitter; } void BioStruct3DSplitter::adaptSize( int numVisibleWidgets ) { if (numVisibleWidgets > 0) { isViewCollapsed = false; setMaximumHeight(1000); getParentSplitter(); // TODO: Simplify resizing int index = parentSplitter->indexOf(this); QList sizes = parentSplitter->sizes(); for(int i = 0; i < sizes.count(); ++i) { if (sizes.at(i) >= splitterHeight) { sizes[i] = sizes.at(i) - splitterHeight; break; } } sizes[index] = splitterHeight; parentSplitter->setSizes(sizes); } else { splitterHeight = splitter->height(); setFixedHeight(HEADER_HEIGHT); isViewCollapsed = true; } } const QList BioStruct3DSplitter::getSettingsMenuActions() const { QList actions; return actions; } QList BioStruct3DSplitter::getChildWidgets() { return biostrucViewMap.values(); } int BioStruct3DSplitter::getNumVisibleWidgets() { int numVisibleWidgets = 0; foreach (BioStruct3DGLWidget* widget, biostrucViewMap) { if (widget->isVisible()) { ++numVisibleWidgets; } } return numVisibleWidgets; } void BioStruct3DSplitter::addModelFromObject( BioStruct3DObject* obj ) { QList objects = dnaView->getObjects(); if (objects.contains(obj)) { addBioStruct3DGLWidget(obj); } else { dnaView->addObject(obj); } } GLFrameManager* BioStruct3DSplitter::getGLFrameManager() { return glFrameManager.get(); } /////////////////////////////////////////////////////////////////////////////////////////// // Header widget SplitterHeaderWidget::SplitterHeaderWidget(BioStruct3DSplitter* sp) : splitter(sp) { setFixedHeight(HEADER_HEIGHT); setMinimumHeight(HEADER_HEIGHT); setBackgroundRole(QPalette::Window); setAutoFillBackground(true); registerWebUrls(); QHBoxLayout *layout = new QHBoxLayout(); layout->setContentsMargins(10,0,0,0); layout->setSpacing(10); connect(splitter, SIGNAL(si_bioStruct3DGLWidgetAdded(BioStruct3DGLWidget* )), SLOT(sl_bioStruct3DGLWidgetAdded(BioStruct3DGLWidget*))); connect(splitter, SIGNAL(si_bioStruct3DGLWidgetRemoved(BioStruct3DGLWidget* )), SLOT(sl_bioStruct3DGLWidgetRemoved(BioStruct3DGLWidget*))); // Menu toolbar HBar* toolbar = new HBar(this); toolbar->layout()->setSpacing(10); toolbar->layout()->setMargin(0); QLabel* pixLabel= new QLabel(this); QFont f = pixLabel->font(); if (f.pixelSize() > HEADER_HEIGHT) { f.setPixelSize(HEADER_HEIGHT-8); } QIcon objIcon(":biostruct3d_view/images/logo.png"); Q_ASSERT(!objIcon.isNull()); QPixmap pix = objIcon.pixmap(QSize(32, 32), QIcon::Active); pixLabel->setPixmap(pix); pixLabel->setFont(f); layout->addWidget(pixLabel); layout->addWidget(new QLabel(tr("3D Structure Viewer"))); layout->addStretch(); layout->addWidget(toolbar); setLayout(layout); // Build header menu QLabel* activeWidgetLabel = new QLabel(this); activeWidgetLabel->setText(tr("Active view:")); toolbar->addWidget(activeWidgetLabel); activeWidgetBox = new QComboBox(this); toolbar->addWidget(activeWidgetBox); restoreDefaultsButton = new QToolButton(this); restoreDefaultsButton->setToolTip(tr("Restore Default View")); restoreDefaultsButton->setIcon(QIcon(":biostruct3d_view/images/restore.png")); restoreDefaultsButton->setFixedWidth(20); toolbar->addWidget(restoreDefaultsButton); connect(restoreDefaultsButton, SIGNAL(pressed()), this, SLOT(sl_restoreDefaults())); zoomInButton = new QToolButton(this); zoomInButton->setToolTip(tr("Zoom In")); zoomInButton->setIcon(QIcon(":core/images/zoom_in.png")); zoomInButton->setFixedWidth(20); toolbar->addWidget(zoomInButton); connect(zoomInButton, SIGNAL(pressed()), this, SLOT(sl_zoomIn())); zoomOutButton = new QToolButton(this); zoomOutButton->setIcon(QIcon(":core/images/zoom_out.png")); zoomOutButton->setToolTip(tr("Zoom Out")); zoomOutButton->setFixedWidth(20); toolbar->addWidget(zoomOutButton); connect(zoomOutButton, SIGNAL(pressed()), this, SLOT(sl_zoomOut())); syncLockButton = new QToolButton(this); syncLockButton->setIcon(QIcon(":biostruct3d_view/images/lock.png")); syncLockButton->setToolTip(tr("Synchronize 3D Structure Views")); syncLockButton->setFixedWidth(20); syncLockButton->setCheckable(true); toolbar->addWidget(syncLockButton); connect(syncLockButton, SIGNAL(toggled(bool)), this, SLOT(sl_toggleSyncLock(bool))); displayMenuButton = new QToolButton(this); displayMenuButton->setText(tr("Display")); toolbar->addWidget(displayMenuButton); connect(displayMenuButton, SIGNAL(pressed()), this, SLOT(sl_showDisplayMenu())); if (webActionMap.count() != 0) { webMenuButton = new QToolButton(this); webMenuButton->setText(tr("Links")); toolbar->addWidget(webMenuButton); connect(webMenuButton, SIGNAL(pressed()), this, SLOT(sl_showWebMenu())); } addModelButton = new QToolButton(this); addModelButton->setText(tr("Add")); toolbar->addWidget(addModelButton); connect(addModelButton, SIGNAL(pressed()), this, SLOT(sl_addModel())); // TODO: add settings functionality //settingsMenuButton = new QToolButton(this); //settingsMenuButton->setText(tr("settings")); // toolbar->addWidget(settingsMenuButton); widgetStateMenuButton = new QToolButton(this); widgetStateMenuButton->setIcon(QIcon(":core/images/adv_widget_menu.png")); widgetStateMenuButton->setFixedWidth(20); toolbar->addWidget(widgetStateMenuButton); connect(widgetStateMenuButton, SIGNAL(pressed()), this, SLOT(sl_showStateMenu())); } void SplitterHeaderWidget::sl_showStateMenu() { QPointer widgetStateMenuButtonPtr(widgetStateMenuButton); QMenu m; foreach(QAction* action, toggleActions) { m.addAction(action); } m.addAction(splitter->getCloseSplitterAction()); m.exec(QCursor::pos()); if (!widgetStateMenuButtonPtr.isNull()) { //if not self closed widgetStateMenuButtonPtr->setDown(false); } } void SplitterHeaderWidget::sl_showDisplayMenu() { QPointer displayMenuButtonPtr(displayMenuButton); BioStruct3DGLWidget* activeWidget = getActiveWidget(); QMenu* displayMenu = activeWidget->getDisplayMenu(); displayMenu->exec(QCursor::pos()); if (!displayMenuButtonPtr.isNull()) { //if not self closed displayMenuButtonPtr->setDown(false); } } #define ZOOM_DELTA 2.0f void SplitterHeaderWidget::sl_zoomIn() { BioStruct3DGLWidget* w = getActiveWidget(); w->zoom(-ZOOM_DELTA); } void SplitterHeaderWidget::sl_zoomOut() { BioStruct3DGLWidget* w = getActiveWidget(); w->zoom(ZOOM_DELTA); } void SplitterHeaderWidget::sl_showSettingsMenu() { QPointer settingsMenuButtonPtr(settingsMenuButton); QMenu m; const QList settingsMenuActions = splitter->getSettingsMenuActions(); foreach (QAction* action, settingsMenuActions) { m.addAction(action); } m.exec(QCursor::pos()); if (!settingsMenuButtonPtr.isNull()) { //if not self closed settingsMenuButtonPtr->setDown(false); } } void SplitterHeaderWidget::sl_restoreDefaults() { BioStruct3DGLWidget* w = getActiveWidget(); w->restoreDefaultSettigns(); } void SplitterHeaderWidget::sl_bioStruct3DGLWidgetAdded( BioStruct3DGLWidget* glWidget ) { int index = activeWidgetBox->count() + 1; const char* pdbId = glWidget->getBioStruct3D().pdbId.constData(); QString name = QString("%1: %2").arg(index).arg(pdbId) ; activeWidgetBox->addItem(name); activeWidgetBox->setCurrentIndex(index - 1); glWidget->installEventFilter(this); // Add show widget action QString actionName( tr("Show %1").arg(pdbId) ); QAction* action = new QAction(actionName, glWidget); action->setCheckable(true); action->setChecked(true); connect(action, SIGNAL(triggered(bool)), SLOT(sl_toggleBioStruct3DWidget(bool))); toggleActions.append(action); enableToolbar(); } void SplitterHeaderWidget::sl_bioStruct3DGLWidgetRemoved( BioStruct3DGLWidget* glWidget ) { glWidget->disconnect(this); updateActiveWidgetBox(); updateToolbar(); foreach (QAction* action, toggleActions) { if (action->parent() == glWidget) { toggleActions.removeOne(action); } } } bool SplitterHeaderWidget::eventFilter(QObject *obj, QEvent *event) { if (event->type() == QEvent::MouseButtonPress || event->type() == QEvent::Wheel) { BioStruct3DGLWidget* glWidget = qobject_cast(obj); if (glWidget) { setActiveView(glWidget); } } return QObject::eventFilter(obj, event); } BioStruct3DGLWidget* SplitterHeaderWidget::getActiveWidget() { int idx = activeWidgetBox->currentIndex(); GLFrameManager* manager = splitter->getGLFrameManager(); GLFrame* frame = manager->getGLFrames().at(idx); frame->makeCurrent(); return qobject_cast(frame->getGLWidget()); } void SplitterHeaderWidget::enableToolbar() { activeWidgetBox->setEnabled(true); restoreDefaultsButton->setEnabled(true); zoomInButton->setEnabled(true); zoomOutButton->setEnabled(true); displayMenuButton->setEnabled(true); widgetStateMenuButton->setEnabled(true); syncLockButton->setEnabled(splitter->getGLFrameManager()->getGLFrames().count() > 1); } void SplitterHeaderWidget::updateActiveWidgetBox() { activeWidgetBox->clear(); int index = 0; QList widgets = splitter->getChildWidgets(); foreach(BioStruct3DGLWidget* widget, widgets) { ++index; const char* pdbId = widget->getBioStruct3D().pdbId.constData(); QString name = QString("%1: %2").arg(index).arg(pdbId); activeWidgetBox->addItem(name); } } void SplitterHeaderWidget::updateToolbar() { int numVisibleWidgets = splitter->getNumVisibleWidgets(); activeWidgetBox->setEnabled(true); restoreDefaultsButton->setEnabled(true); zoomInButton->setEnabled(true); zoomOutButton->setEnabled(true); syncLockButton->setEnabled(numVisibleWidgets > 1); displayMenuButton->setEnabled(true); widgetStateMenuButton->setEnabled(!splitter->getChildWidgets().isEmpty()); } void SplitterHeaderWidget::sl_toggleBioStruct3DWidget( bool show ) { BioStruct3DGLWidget* glWidget = qobject_cast (sender()->parent()); Q_ASSERT(glWidget != NULL); glWidget->setVisible(show); int numVisibleWidgets = splitter->getNumVisibleWidgets(); if ( (show == true && numVisibleWidgets == 1) || (show == false && numVisibleWidgets == 0) ) { splitter->adaptSize(numVisibleWidgets); } updateToolbar(); } void SplitterHeaderWidget::sl_addModel() { QPointer addModelButtonPtr(addModelButton); if (!addModelButtonPtr.isNull()) { //if not self closed addModelButtonPtr->setDown(false); } ProjectTreeControllerModeSettings settings; settings.objectTypesToShow.append(GObjectTypes::BIOSTRUCTURE_3D); QList objects = ProjectTreeItemSelectorDialog::selectObjects(settings, this); if (!objects.isEmpty()) { foreach(GObject* obj, objects) { Task* t = new AddModelToSplitterTask(obj, splitter); AppContext::getTaskScheduler()->registerTopLevelTask(t); } } } void SplitterHeaderWidget::sl_showWebMenu() { QPointer webMenuButtonPtr(webMenuButton); QMenu m; QString pdbId(getActiveWidget()->getBioStruct3D().pdbId); const QList& webMenuActions = webActionMap.keys(); foreach (QAction* action, webMenuActions) { QString wikiName = action->text().split(": ", QString::SkipEmptyParts).last(); action->setText(pdbId+": "+wikiName); m.addAction(action); } m.exec(QCursor::pos()); if (!webMenuButtonPtr.isNull()) { //if not self closed webMenuButtonPtr->setDown(false); } } void SplitterHeaderWidget::registerWebUrls() { DBLinksFile linksFile; if (!linksFile.load()) { return; } QList links = linksFile.getLinks(); foreach (const DBLink& link, links) { QAction* webAction = new QAction(link.name,this); webActionMap.insert(webAction, link.url); connect(webAction, SIGNAL(triggered(bool)), this, SLOT(sl_openBioStructUrl())); } } void SplitterHeaderWidget::sl_openBioStructUrl() { QAction* webAction = qobject_cast(QObject::sender()); if (webAction == NULL) return; const QString& urlHeader = webActionMap.value(webAction); QString pdbId(getActiveWidget()->getBioStruct3D().pdbId.toLower()); QString urlName = urlHeader.arg(pdbId); QUrl url(urlName); QDesktopServices::openUrl(urlName); } void SplitterHeaderWidget::setActiveView( BioStruct3DGLWidget* glWidget ) { int index = 0; QList frames = splitter->getGLFrameManager()->getGLFrames(); foreach (GLFrame* frame, frames) { if ( frame->getGLWidget() == glWidget ) { frame->makeCurrent(); activeWidgetBox->setCurrentIndex(index); break; } ++index; } } void SplitterHeaderWidget::sl_toggleSyncLock( bool toggle ) { QList widgets = splitter->getChildWidgets(); splitter->getGLFrameManager()->setSyncLock(toggle, widgets[0]); } /////////////////////////////////////////////////////////////////////////////////////////// // DBLinksFile #define DB_LINKS_FILE_NAME "biostruct3d_plugin/BioStruct3DLinks.txt" bool DBLinksFile::load() { QFile file( QString(PATH_PREFIX_DATA)+ ":" + DB_LINKS_FILE_NAME ); if(!file.exists() || !file.open(QIODevice::ReadOnly)){ ioLog.error(SplitterHeaderWidget::tr("File not found: %1").arg(DB_LINKS_FILE_NAME)); return false; } QTextStream in(&file); while (!in.atEnd()) { QString line = in.readLine(); if(line.length()==0 || line.startsWith("#")) { continue; } QStringList fields = line.split("|"); if (fields.size() != 2) { ioLog.error(SplitterHeaderWidget::tr("Illegal entry: %1").arg(line)); continue; } DBLink linkInfo(fields[0], fields[1].trimmed()); links.append(linkInfo); } file.close(); return true; } /////////////////////////////////////////////////////////////////////////////////////////// // AddModelToSplitterTask AddModelToSplitterTask::AddModelToSplitterTask( GObject* o, BioStruct3DSplitter* s ) : Task("", TaskFlags_FOSCOE), doc(NULL), obj(o), bObj(NULL), splitter(s) { setTaskName(tr("Add 3d model '%1' to BioStruct3DSplitter").arg(o->getGObjectName())); } void AddModelToSplitterTask::prepare() { if (obj->isUnloaded()) { doc = obj->getDocument(); addSubTask(new LoadUnloadedDocumentTask(doc)); } } void AddModelToSplitterTask::run() { if (doc == NULL) { bObj = qobject_cast (obj); } else { Q_ASSERT(doc->isLoaded()); QList lst = doc->findGObjectByType(GObjectTypes::BIOSTRUCTURE_3D); Q_ASSERT(!lst.isEmpty()); bObj = qobject_cast (lst.first()); } } Task::ReportResult AddModelToSplitterTask::report() { if ( (bObj == NULL) || ( propagateSubtaskError() == true) ) { stateInfo.setError(tr("Model %1 wasn't added").arg(obj->getGObjectName())); } else { splitter->addModelFromObject(bObj); } return ReportResult_Finished; } } //namespace ugene-1.9.8/src/plugins/biostruct3d_view/src/StructuralAlignmentDialog.h0000644000175000017500000000326711651544321025162 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_STRUCTURAL_ALIGNMENT_DIALOG_H_ #define _U2_STRUCTURAL_ALIGNMENT_DIALOG_H_ #include "ui_StructuralAlignmentDialog.h" namespace U2 { class StructuralAlignmentTask; class BioStruct3DObject; class BioStruct3DSubsetEditor; class StructuralAlignmentDialog : public QDialog, public Ui::StructuralAlignmentDialog { Q_OBJECT public: StructuralAlignmentDialog(const BioStruct3DObject *fixedRef = 0, int fixedRefModel = -1, QWidget *parent = 0); /** Check if algorithm available and ::exec() */ int execIfAlgorithmAvailable(); /** @returns set up StructuralAlignmentTask */ StructuralAlignmentTask* getTask() { return task; } public slots: virtual void accept(); private: StructuralAlignmentTask *task; BioStruct3DSubsetEditor *ref, *mob; }; } // namespace U2 #endif // #ifndef _U2_STRUCTURAL_ALIGNMENT_DIALOG_H_ ugene-1.9.8/src/plugins/biostruct3d_view/src/GraphicUtils.h0000644000175000017500000001143311651544321022423 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_GRAPHIC_UTILS_H_ #define _U2_GRAPHIC_UTILS_H_ #include #include #include class GLUquadric; namespace U2 { class BioStruct3D; class BioStruct3DColorScheme; class Molecule3DModel; //! Color /*! This class is convenient for OpenGL rendering purposes, connected with QColor */ class Color4f { private: float color[4]; public: Color4f(); Color4f(float r, float g, float b, float a = 1.0); Color4f(const Color4f &c); Color4f(const QColor &qc); float operator[] (unsigned int i) const; float& operator[] (unsigned int i); bool operator == (const Color4f &a) const; const float* getConstData() const { return color; } }; //! OpenGL drawable object class Object3D { protected: Color4f color; public: Object3D(const Color4f& color_) : color(color_) {}; virtual void draw(float renderDetailLevel) = 0; virtual ~Object3D() {}; const Color4f& getColor() const { return color; } void setColor(const Color4f &c) { color = Color4f(c); } }; // class Strand3D //! Alpha Helix 3D representation class Helix3D : public Object3D { GLUquadric* pObj; Vector3D cterm; Vector3D nterm; Vector3D rotAxis; float radius,length,rotAngle; public: Helix3D(const Color4f& color, const Vector3D& c, const Vector3D& n, float r); virtual ~Helix3D(); virtual void draw(float renderDetailLevel); }; // class Helix3D //! Beta Strand 3D representation class Strand3D : public Object3D { GLUquadric* pObj; Vector3D cterm; Vector3D nterm; Vector3D upVector; Vector3D rotAxis; float length, rotAngle; public: Strand3D(const Color4f& color, const Vector3D& c, const Vector3D& n, const Vector3D& up = Vector3D() ); virtual ~Strand3D(); virtual void draw(float renderDetailLevel); }; // class Strand3D //! Draw arrow void glCreateArrowPrimitive(float width, float height, float length); //! Draw atom as sphere with center = pos and radius = r void glDrawAtom(GLUquadric* pObj, const Vector3D& pos, double r, float renderDetailLevel); //! Draw cylinder from one point to another void glDrawCylinder(GLUquadric* pObj, const Vector3D& p1, const Vector3D& p2, double thickness, float renderDetailLevel); //! Draw a spline (worm) /*! Function straight from CN3D Viewer, uses Catmull-Rom interpolation add a thick splined curve from point 1 *halfway* to point 2 */ void glDrawHalfWorm(const Vector3D& p0, const Vector3D& p1, const Vector3D& p2, const Vector3D& p3, double radius, bool cap1, bool cap2, double tension, float renderDetailLevel); void glDrawHalfBond(GLUquadric *pObj, const Vector3D& p1, const Vector3D&p2, double thickness, float renderDetailLevel); //! Project point on axis Vector3D projectPointOnAxis(const Vector3D& point, const Vector3D& axisUnitVector, const Vector3D& axisPoint); //! Calculates average point Vector3D calcMiddlePoint(const QVector& points); void accPerspective(double fovy, double aspect, double near, double far, double pixdx, double pixdy, double eyedx, double eyedy, double focus); void accFrustum(double left, double right, double bottom, double top, double near, double far, double pixdx, double pixdy, double eyedx, double eyedy, double focus); //! Calculates axis through points using least linear square method QPair calcBestAxisThroughPoints(const QVector& points); //! Checks for OpenGL errors and reports them to log #define CHECK_GL_ERROR do { checkGlError(__FILE__, __LINE__); } while (0); inline void checkGlError(const char *file, int line) { GLenum error = glGetError(); if (error != GL_NO_ERROR) { QString where = QString("%1:%2: ").arg(file).arg(line); QString msg = QString("OpenGL error (%1): %2").arg(error).arg((char*)gluErrorString(error)); uiLog.trace(where + msg); } } } //namespace #endif // _U2_GRAPHIC_UTILS_H_ ugene-1.9.8/src/plugins/biostruct3d_view/src/VanDerWaalsGLRenderer.cpp0000644000175000017500000000516011651544321024441 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include #include #include #include #include #include "GraphicUtils.h" #include "BioStruct3DGLWidget.h" #include "BioStruct3DColorScheme.h" #include "VanDerWaalsGLRenderer.h" namespace U2 { const QString VanDerWaalsGLRenderer::ID(QObject::tr("Space Fill")); //unsigned int DisplayLists::atomDL = -1; void VanDerWaalsGLRenderer::drawBioStruct3D( ) { drawAtoms(colorScheme); } void VanDerWaalsGLRenderer::drawAtoms( const BioStruct3DColorScheme* colorScheme ) { static float tolerance = 0.45f; int numSlices = 10 * settings->detailLevel; GLUquadricObj *pObj = gluNewQuadric(); gluQuadricNormals(pObj, GLU_SMOOTH); // Draw atoms as spheres foreach (const SharedMolecule mol, bioStruct.moleculeMap) { foreach (int index, shownModels) { const Molecule3DModel& model = mol->models.at(index); foreach(const SharedAtom atom, model.atoms) { float radius = AtomConstants::getAtomCovalentRadius(atom->atomicNumber); Vector3D pos = atom->coord3d; Color4f atomColor = colorScheme->getAtomColor(atom); glMaterialfv(GL_FRONT, GL_AMBIENT_AND_DIFFUSE, atomColor.getConstData()); glPushMatrix(); glTranslatef(pos.x, pos.y, pos.z); gluSphere(pObj, radius + tolerance, numSlices, numSlices); glPopMatrix(); } } } gluDeleteQuadric(pObj); } VanDerWaalsGLRenderer::VanDerWaalsGLRenderer( const BioStruct3D& struc, const BioStruct3DColorScheme* s, const QList &shownModels, const BioStruct3DRendererSettings *settings) : BioStruct3DGLRenderer(struc,s,shownModels,settings) { create(); } } //namespace ugene-1.9.8/src/plugins/biostruct3d_view/src/AnaglyphRenderer.h0000644000175000017500000000675111651544321023266 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_ANAGLYPH_RENDERER_H_ #define _U2_ANAGLYPH_RENDERER_H_ #include #include #include namespace U2 { class BioStruct3DGLWidget; enum AnaglyphStatus {NOT_AVAILABLE = -1, DISABLED = 0, ENABLED = 1}; class AnaglyphSettings { public: AnaglyphSettings(float _eyesShift, const QColor &_leftEyeColor, const QColor &_rightEyeColor) : eyesShift(_eyesShift), leftEyeColor(_leftEyeColor), rightEyeColor(_rightEyeColor) {} float eyesShift; QColor leftEyeColor, rightEyeColor; public: static AnaglyphSettings defaultSettings() { return AnaglyphSettings(1.6f, QColor(0, 255, 255), QColor(255, 0, 0)); } public: QVariantMap toMap(QVariantMap &map) const; static AnaglyphSettings fromMap(const QVariantMap &map); }; /** Anaglyph effect renderer */ class AnaglyphRenderer { public: /** Construct anaglyph renderer over scene renderer */ AnaglyphRenderer(BioStruct3DGLWidget *_renderer, const AnaglyphSettings &_settings) : renderer(_renderer), settings(_settings), width(1), height(1), anaglyphRenderTextureLeft(0), anaglyphRenderTextureRight(0), tempAnaglyphRenderTexture(0), hasErrors(false) {} /** Checks if possible to enable anaglyph. Performs test rendering */ virtual bool isAvailable(); virtual void init(); virtual void resize(int w, int h); virtual void draw(); const AnaglyphSettings& getSettings() const { return settings; } void setSettings(const AnaglyphSettings &_settings) { settings = _settings; } private: /** Set up an ortho projection. For textures rendering */ void setOrthoProjection(); /** Creates empty textures sized width*height */ void createEmptyTextures(); void drawTexturesAnaglyph(); void drawTexture(GLuint anaglyphRenderTexture, int red, int green, int blue, float alpha, bool alphaOnly); private: // this will redefine CHECK_GL_ERROR macro inline void checkGlError(const char *file, int line); private: BioStruct3DGLWidget *renderer; AnaglyphSettings settings; int width, height; private: GLuint anaglyphRenderTextureLeft, anaglyphRenderTextureRight, tempAnaglyphRenderTexture; bool hasErrors; }; inline void AnaglyphRenderer::checkGlError(const char *file, int line) { GLenum error = glGetError(); if (error != GL_NO_ERROR) { QString where = QString("%1:%2: ").arg(file).arg(line); QString msg = QString("OpenGL error (%1): %2").arg(error).arg((char*)gluErrorString(error)); uiLog.trace(where + msg); hasErrors = true; } } } // namespace U2 #endif // #ifndef _U2_ANAGLYPH_RENDERER_H_ ugene-1.9.8/src/plugins/biostruct3d_view/transl/0000755000175000017500000000000011651544321020366 5ustar ilyailyaugene-1.9.8/src/plugins/biostruct3d_view/transl/russian.ts0000644000175000017500000004262411651544321022432 0ustar ilyailya ImageExportForm Export Image Экспорт изображения File name Имя файла ... Format Формат изображения Width Ширина px Height Высота OK Сохранить Cancel Отмена QObject Tubes Трубки Worms Каркас Space Fill Заполнение Dots Точки Convex Map Выпуклая структура Ball-and-Stick Шаростержневая модель Molecular Chains Молекулярные цепи Chemical Elements Химические элементы Secondary Structure Вторичная структура SettingsDialog Anaglyph view Стереоизображение Eyes shift Сдвиг слоев Settings Настройки Set background color... Выбрать цвет фона... Set selection color... Выбрать цвет выделения... Detail level Уровень детализации Unselected regions shading Затемнение невыбранных регионов OK Применить Cancel Отмена Glasses colors Цвета очков Left Левый Right Правый Swap colors Поменять местами StructuralAlignmentDialog Structural Alignment Reference 3D structure Model Mobile U2::AddModelToSplitterTask Add 3d model '%1' to BioStruct3DSplitter Добавить 3D модель '%1' в BioStruct3DSplitter Model %1 wasn't added Модель %1 не была добавлена U2::BioStruct3DGLWidget Spin Вращение Off Нет Molecular Surface Render Style Стиль отрисовки поверхности Molecular Surface Молекулярная поверхность Models Модели Error Ошибка Unable to open file %1 for writing Невозможно открыть файл %1 для записи Exclusive Выбрать одну Select All Выбрать все Settings... Настройки... Close Закрыть Export Image... Экспортировать изображение... Align With... Render Style Стиль отрисовки Coloring Scheme Цветовая схема U2::BioStruct3DSettingsDialog Custom Выбранные Red - Blue Красный - Синий Cyan - Red Голубой - Красный Red - Dark Cyan Красный - Темно-голубой Red - Green Красный - Зеленый Magenta - Green Пурпурный - Зеленый (not supported by your videocard) (не поддерживается видеокартой) U2::BioStruct3DViewContext Close 3D Structure Viewer Закрыть визуализатор 3D структур U2::BioStruct3DViewPlugin 3D Structure Viewer Визуализатор 3D структур Visualizes 3D structures of biological molecules. Визуализирует 3D структуры биологических молекул. U2::ExportImageDialog Error Ошибка The filename is empty! Не указано имя файла! Overwrite file? Перезаписать файл? The file "%1" already exists. Do you wish to overwrite it? Файл "%1" уже существует. Перезаписать? Save image to... Выберите файл для сохранения изображения... Saving image to '%1'... Запись изображения в '%1'... U2::SplitterHeaderWidget 3D Structure Viewer Визуализатор 3D структур Active view: Активная: Restore Default View Восстановить вид по умолчанию Zoom In Увеличить Zoom Out Уменьшить Synchronize 3D Structure Views Синхронизировать изображения Display Изображение Show %1 Показывать %1 File not found: %1 Файл не найден: %1 Illegal entry: %1 Некорректные входные данные: %1 Links Ссылки Add Добавить ugene-1.9.8/src/plugins/biostruct3d_view/transl/english.ts0000644000175000017500000003647411651544321022405 0ustar ilyailya ImageExportForm Export Image File name ... Format Width px Height OK Cancel QObject Tubes Worms Space Fill Dots Convex Map Molecular Chains Chemical Elements Secondary Structure Ball-and-Stick SettingsDialog Anaglyph view Eyes shift Settings Set background color... Set selection color... Detail level Unselected regions shading OK Cancel Glasses colors Left Right Swap colors StructuralAlignmentDialog Structural Alignment Reference 3D structure Model Mobile U2::AddModelToSplitterTask Add 3d model '%1' to BioStruct3DSplitter Model %1 wasn't added U2::BioStruct3DGLWidget Spin Off Exclusive Select All Settings... Close Export Image... Align With... Render Style Coloring Scheme Molecular Surface Render Style Molecular Surface Models Error Unable to open file %1 for writing U2::BioStruct3DSettingsDialog Custom Red - Blue Cyan - Red Red - Dark Cyan Red - Green Magenta - Green (not supported by your videocard) U2::BioStruct3DViewContext Close 3D Structure Viewer U2::BioStruct3DViewPlugin 3D Structure Viewer Visualizes 3D structures of biological molecules. U2::ExportImageDialog Error The filename is empty! Overwrite file? The file "%1" already exists. Do you wish to overwrite it? Save image to... Saving image to '%1'... U2::SplitterHeaderWidget 3D Structure Viewer Active view: Restore Default View Zoom In Zoom Out Synchronize 3D Structure Views Display Show %1 File not found: %1 Illegal entry: %1 Links Add ugene-1.9.8/src/plugins/biostruct3d_view/biostruct3d_view.pri0000644000175000017500000000027111651544321023076 0ustar ilyailya# include (biostruct3d_view.pri) QT += opengl PLUGIN_ID=biostruct3d_view PLUGIN_NAME=3D structure viewer PLUGIN_VENDOR=Unipro PLUGIN_MODE=ui include( ../../ugene_plugin_common.pri ) ugene-1.9.8/src/plugins/biostruct3d_view/biostruct3d_view.pro0000644000175000017500000000334311651544321023107 0ustar ilyailyainclude (biostruct3d_view.pri) # Input HEADERS += src/BallAndStickGLRenderer.h \ src/BioStruct3DColorScheme.h \ src/BioStruct3DGLRender.h \ src/BioStruct3DGLWidget.h \ src/BioStruct3DSplitter.h \ src/BioStruct3DViewPlugin.h \ src/ExportImage3DGLDialog.h \ src/GLFrameManager.h \ src/GraphicUtils.h \ src/MolecularSurfaceRenderer.h \ src/TubeGLRenderer.h \ src/VanDerWaalsGLRenderer.h \ src/WormsGLRenderer.h \ src/SettingsDialog.h \ src/StructuralAlignmentDialog.h \ src/gl2ps/gl2ps.h \ src/BioStruct3DSubsetEditor.h \ src/SelectModelsDialog.h \ src/AnaglyphRenderer.h FORMS += src/ui/SettingsDialog.ui \ src/ui/StructuralAlignmentDialog.ui \ src/ui/BioStruct3DSubsetEditor.ui \ src/ui/SelectModelsDialog.ui SOURCES += src/BallAndStickGLRenderer.cpp \ src/BioStruct3DColorScheme.cpp \ src/BioStruct3DGLRender.cpp \ src/BioStruct3DGLWidget.cpp \ src/BioStruct3DSplitter.cpp \ src/BioStruct3DViewPlugin.cpp \ src/ExportImage3DGLDialog.cpp \ src/GLFrameManager.cpp \ src/GraphicUtils.cpp \ src/MolecularSurfaceRenderer.cpp \ src/TubeGLRenderer.cpp \ src/VanDerWaalsGLRenderer.cpp \ src/WormsGLRenderer.cpp \ src/SettingsDialog.cpp \ src/StructuralAlignmentDialog.cpp \ src/gl2ps/gl2ps.cpp \ src/BioStruct3DSubsetEditor.cpp \ src/SelectModelsDialog.cpp \ src/AnaglyphRenderer.cpp RESOURCES += biostruct3d_view.qrc TRANSLATIONS += transl/english.ts transl/russian.ts ugene-1.9.8/src/plugins/expert_discovery/0000755000175000017500000000000011651544323017164 5ustar ilyailyaugene-1.9.8/src/plugins/expert_discovery/expert_discovery.pro0000644000175000017500000000432211651544322023304 0ustar ilyailyainclude (expert_discovery.pri) # Input HEADERS += src/ExpertDiscoveryPlugin.h \ src/ExpertDiscoveryView.h \ src/ExpertDiscoveryViewCtx.h \ src/ExpertDiscoveryPosNegDialog.h \ src/ExpertDiscoveryControlDialog.h \ src/ExpertDiscoveryPosNegMrkDialog.h \ src/ExpertDiscoveryControlMrkDialog.h \ src/ExpertDiscoveryAdvSetDialog.h \ src/ExpertDiscoverySetupRecBoundDialog.h \ src/ExpertDiscoveryPropTable.h \ src/ExpertDiscoveryTask.h \ src/ExpertDiscoveryData.h \ src/ExpertDiscoverySet.h \ src/ExpertDiscoveryExtSigWiz.h \ src/ExpertDiscoveryCSUtil.h \ src/ExpertDiscoveryTreeWidgets.h \ src/ExpertDiscoveryTreeWidgetsCtrl.h \ src/ExpertDiscoveryPersistent.h \ src/DDisc/definitions.h \ src/DDisc/statmath.h \ src/DDisc/Signal.h \ src/DDisc/Sequence.h \ src/DDisc/MetaInfo.h \ src/DDisc/Extractor.h \ src/DDisc/Context.h FORMS += src/ui/ExpertDiscoveryPosNegDialog.ui \ src/ui/ExpertDiscoveryControlDialog.ui \ src/ui/ExpertDiscoveryPosNegMrkDialog.ui \ src/ui/ExpertDiscoveryControlMrkDialog.ui \ src/ui/ExpertDiscoveryAdvSetDialog.ui \ src/ui/ExpertDiscoverySigExtrWiz.ui \ src/ui/ExpertDiscoverySetupRecBoundDialog.ui SOURCES += src/ExpertDiscoveryPlugin.cpp \ src/ExpertDiscoveryView.cpp \ src/ExpertDiscoveryViewCtx.cpp \ src/ExpertDiscoveryPosNegDialog.cpp \ src/ExpertDiscoveryControlDialog.cpp \ src/ExpertDiscoveryPosNegMrkDialog.cpp \ src/ExpertDiscoveryControlMrkDialog.cpp \ src/ExpertDiscoveryAdvSetDialog.cpp \ src/ExpertDiscoverySetupRecBoundDialog.cpp \ src/ExpertDiscoveryPropTable.cpp \ src/ExpertDiscoveryTask.cpp \ src/ExpertDiscoveryData.cpp \ src/ExpertDiscoverySet.cpp \ src/ExpertDiscoveryExtSigWiz.cpp \ src/ExpertDiscoveryCSUtil.cpp \ src/ExpertDiscoveryTreeWidgets.cpp \ src/ExpertDiscoveryTreeWidgetsCtrl.cpp \ src/ExpertDiscoveryPersistent.cpp \ src/DDisc/Definitions.cpp \ src/DDisc/statmath.cpp \ src/DDisc/Signal.cpp \ src/DDisc/Sequence.cpp \ src/DDisc/MetaInfo.cpp \ src/DDisc/Extractor.cpp \ src/DDisc/Context.cpp RESOURCES += expert_discovery.qrc TRANSLATIONS += transl/english.ts transl/russian.ts ugene-1.9.8/src/plugins/expert_discovery/expert_discovery.qrc0000644000175000017500000000172611651544322023276 0ustar ilyailya images/control.png images/cs.png images/csroot.png images/distance.png images/folder.png images/interval.png images/mrkroot.png images/negseq.png images/posseq.png images/repetition.png images/sequence.png images/sequences.png images/ts.png images/undefined.png images/extractSignals.png images/extractSignals2.png images/genRep.png images/loadControlsSeq.png images/loadControlsSeqAnnot.png images/loadMarkup.png images/newDoc.png images/optRecBound.png images/setRecBound.png images/fileopen.png images/filenew.png images/filesave.png ugene-1.9.8/src/plugins/expert_discovery/images/0000755000175000017500000000000011651544322020430 5ustar ilyailyaugene-1.9.8/src/plugins/expert_discovery/images/ExpertDiscoveryDoc.png0000644000175000017500000000616611651544322024734 0ustar ilyailyaPNG  IHDR tRNS7X} +IDATx ????????????@@@???????????????????????????h IENDB`ugene-1.9.8/src/plugins/expert_discovery/images/sequences.png0000644000175000017500000000154611651544322023137 0ustar ilyailyaPNG  IHDRh6tRNS7X}IDATx/88444444442aěIENDB`ugene-1.9.8/src/plugins/expert_discovery/images/filenew.png0000644000175000017500000000124211651544322022566 0ustar ilyailyaPNG  IHDRatEXtSoftwareAdobe ImageReadyqe<DIDATx|SMhAvm#HA"EQPH"6њSmV4J`5` E,"-?Mdg3a#voތ9( lcEԛq}+P3xFy&{w ē܆!" նmnY/JRX,r0ZD(RVJpGeYQ$fl!-0DYr"Zd2I^5[4G,ոCrV+=܄[1a&D5-x*ncwa=uDb} AqY dy8=FkwD##'E 0JKf?`&o&\y,}oܖ$~ntnم{R/۪0:27 B8P pxڙj9HǙpE2X5^yՋ+zy&b]8-O#j xWGˏЦh[zM AѸzx߹mB]P</N0}ϣ@/IENDB`ugene-1.9.8/src/plugins/expert_discovery/images/icon1.png0000644000175000017500000000616611651544322022160 0ustar ilyailyaPNG  IHDR tRNS7X} +IDATx =1&IENDB`ugene-1.9.8/src/plugins/expert_discovery/images/sequence.ico0000644000175000017500000000257611651544322022746 0ustar ilyailyah( ʦ """)))UUUMMMBBB999|PP3f3333f333ff3fffff3f3f̙f3333f3333333333f3333333f3f33ff3f3f3f3333f3333333f3̙33333f333ff3ffffff3f33f3ff3f3f3ffff3fffffffff3fffffff3f̙ffff3ff333f3ff33fff33f3ff̙3f3f3333f333ff3fffff̙̙3̙f̙̙̙3f̙3f3f3333f333ff3fffff3f3f̙3ffffffffff!___wwwHH_HH__HH_HH_H_H_H_H_H__H_H_H_HH__HH__s{quus1sugene-1.9.8/src/plugins/expert_discovery/images/icon1.ico0000644000175000017500000000206611651544322022141 0ustar ilyailya &(( @(     ??ugene-1.9.8/src/plugins/expert_discovery/images/cs.png0000644000175000017500000000154611651544322021551 0ustar ilyailyaPNG  IHDRh6tRNS7X}IDATx        gIENDB`ugene-1.9.8/src/plugins/expert_discovery/images/negseq.png0000644000175000017500000000154611651544322022426 0ustar ilyailyaPNG  IHDRh6tRNS7X}IDATx4ff33mx =(WIENDB`ugene-1.9.8/src/plugins/expert_discovery/images/folder.ico0000644000175000017500000000257611651544322022411 0ustar ilyailyah( ʦ """)))UUUMMMBBB999|PP3f3333f333ff3fffff3f3f̙f3333f3333333333f3333333f3f33ff3f3f3f3333f3333333f3̙33333f333ff3ffffff3f33f3ff3f3f3ffff3fffffffff3fffffff3f̙ffff3ff333f3ff33fff33f3ff̙3f3f3333f333ff3fffff̙̙3̙f̙̙̙3f̙3f3f3333f333ff3fffff3f3f̙3ffffffffff!___www QQQQQQQQQQ Q^^^^^^^^Q Q^^^^^^^^Q Q^^^^^^^^Q Q^^^^^^^^Q QQQQQQQQQQ QQQQQ ^^^ ugene-1.9.8/src/plugins/expert_discovery/images/ExpertDiscoveryDoc.ico0000644000175000017500000000206611651544322024715 0ustar ilyailya &(( @?( wppwp`wwww`pwwwww?ugene-1.9.8/src/plugins/expert_discovery/images/filesave.png0000644000175000017500000000132411651544322022734 0ustar ilyailyaPNG  IHDRatEXtSoftwareAdobe ImageReadyqe<vIDATx|Ska}٤!B* *U^JA/ĢA Ă9YAj*xAJQAf6oK7~3oޛ 31B";c3< 2}aL2d1' j4T4M*JX,R6!Q2Ij6qJ%/h&(}Jmۊ8+^[kǕ[EcI04Ih]}Tq{ TUT*$i(>myȽ*c@xG_o/iZ[V18S{pz4~a?m 0P7Μ<vş^Y*u *f62klICy]_`.9 !>#!`n AHEqdW`.xL$(kyw{5}!=,3I v66[.šT?TWbQ#; X5J Z0;v$b;9AG)ʃn)AT F#7q#CJ>[<"ù2{w+8t㽻Yp ߯VxAL<IENDB`ugene-1.9.8/src/plugins/expert_discovery/images/cs.ico0000644000175000017500000000257611651544322021543 0ustar ilyailyah( ʦ """)))UUUMMMBBB999|PP3f3333f333ff3fffff3f3f̙f3333f3333333333f3333333f3f33ff3f3f3f3333f3333333f3̙33333f333ff3ffffff3f33f3ff3f3f3ffff3fffffffff3fffffff3f̙ffff3ff333f3ff33fff33f3ff̙3f3f3333f333ff3fffff̙̙3̙f̙̙̙3f̙3f3f3333f333ff3fffff3f3f̙3ffffffffff!___www ugene-1.9.8/src/plugins/expert_discovery/images/optRecBound.png0000644000175000017500000000154611651544322023370 0ustar ilyailyaPNG  IHDRh6tRNS7X}IDATx(+$_IjIENDB`ugene-1.9.8/src/plugins/expert_discovery/images/extractSignals.png0000644000175000017500000000154611651544322024137 0ustar ilyailyaPNG  IHDRh6tRNS7X}IDATx2M#AGIENDB`ugene-1.9.8/src/plugins/expert_discovery/images/loadControlsSeqAnnot.ico0000644000175000017500000000047611651544322025247 0ustar ilyailya(( 3333"03""""33""""!01"""""!01""""""""""3"#3"3""!"""""""""""""""""""""""""""""""""""""33333333ugene-1.9.8/src/plugins/expert_discovery/images/posseq.ico0000644000175000017500000000257611651544322022450 0ustar ilyailyah( ʦ """)))UUUMMMBBB999|PP3f3333f333ff3fffff3f3f̙f3333f3333333333f3333333f3f33ff3f3f3f3333f3333333f3̙33333f333ff3ffffff3f33f3ff3f3f3ffff3fffffffff3fffffff3f̙ffff3ff333f3ff33fff33f3ff̙3f3f3333f333ff3fffff̙̙3̙f̙̙̙3f̙3f3f3333f333ff3fffff3f3f̙3ffffffffff!___www??????????????????????????????????????????ugene-1.9.8/src/plugins/expert_discovery/images/posseq.png0000644000175000017500000000154611651544322022456 0ustar ilyailyaPNG  IHDRh6tRNS7X}IDATx4fff44f333f3333U^PTIENDB`ugene-1.9.8/src/plugins/expert_discovery/images/setRecBound.png0000644000175000017500000000154611651544322023361 0ustar ilyailyaPNG  IHDRh6tRNS7X}IDATx_# JIENDB`ugene-1.9.8/src/plugins/expert_discovery/images/undefined.png0000644000175000017500000000154611651544322023105 0ustar ilyailyaPNG  IHDRh6tRNS7X}IDATx, IENDB`ugene-1.9.8/src/plugins/expert_discovery/images/distance.png0000644000175000017500000000154611651544322022736 0ustar ilyailyaPNG  IHDRh6tRNS7X}IDATxZ`VIENDB`ugene-1.9.8/src/plugins/expert_discovery/images/repetition.png0000644000175000017500000000154611651544322023326 0ustar ilyailyaPNG  IHDRh6tRNS7X}IDATxԘ!%IENDB`ugene-1.9.8/src/plugins/expert_discovery/images/mrkroot.png0000644000175000017500000000154611651544322022641 0ustar ilyailyaPNG  IHDRh6tRNS7X}IDATx33333ћEIENDB`ugene-1.9.8/src/plugins/expert_discovery/images/optRecBound.ico0000644000175000017500000000030611651544322023347 0ustar ilyailya( ??????????ugene-1.9.8/src/plugins/expert_discovery/images/loadMarkup.png0000644000175000017500000000154611651544322023243 0ustar ilyailyaPNG  IHDRh6tRNS7X}IDATxQ]|IENDB`ugene-1.9.8/src/plugins/expert_discovery/images/mrkroot.ico0000644000175000017500000000257611651544322022633 0ustar ilyailyah( ʦ """)))UUUMMMBBB999|PP3f3333f333ff3fffff3f3f̙f3333f3333333333f3333333f3f33ff3f3f3f3333f3333333f3̙33333f333ff3ffffff3f33f3ff3f3f3ffff3fffffffff3fffffff3f̙ffff3ff333f3ff33fff33f3ff̙3f3f3333f333ff3fffff̙̙3̙f̙̙̙3f̙3f3f3333f333ff3fffff3f3f̙3ffffffffff!___www A A A A A A A A A A ?ugene-1.9.8/src/plugins/expert_discovery/images/csroot.ico0000644000175000017500000000257611651544322022447 0ustar ilyailyah( ʦ """)))UUUMMMBBB999|PP3f3333f333ff3fffff3f3f̙f3333f3333333333f3333333f3f33ff3f3f3f3333f3333333f3̙33333f333ff3ffffff3f33f3ff3f3f3ffff3fffffffff3fffffff3f̙ffff3ff333f3ff33fff33f3ff̙3f3f3333f333ff3fffff̙̙3̙f̙̙̙3f̙3f3f3333f333ff3fffff3f3f̙3ffffffffff!___www AAAA AAAA ???___`pugene-1.9.8/src/plugins/expert_discovery/images/extractSignals.ico0000644000175000017500000000047611651544322024126 0ustar ilyailya(( UUU335UUU335U1DADAQDADA3UU30"!"!????1 1ugene-1.9.8/src/plugins/expert_discovery/images/interval.png0000644000175000017500000000154611651544322022770 0ustar ilyailyaPNG  IHDRh6tRNS7X}IDATx$qKIENDB`ugene-1.9.8/src/plugins/expert_discovery/images/loadControlsSeq.png0000644000175000017500000000154611651544322024260 0ustar ilyailyaPNG  IHDRh6tRNS7X}IDATx@Q(e#iIENDB`ugene-1.9.8/src/plugins/expert_discovery/images/loadMarkup.ico0000644000175000017500000000047611651544322023232 0ustar ilyailya(( ffffffffffffffffUUUUUUUUDD"3"DB$DB3D3"C$B#DDD3#$C4DDDD3$D4DDD33$UDUTEUDUDDDDD@DDDDD@DDAD@ADD@@DDUUUUUUUUffffffffugene-1.9.8/src/plugins/expert_discovery/images/ts.png0000644000175000017500000000154611651544322021572 0ustar ilyailyaPNG  IHDRh6tRNS7X}IDATx4444444433334433333333444444444444440}IENDB`ugene-1.9.8/src/plugins/expert_discovery/images/genRep.ico0000644000175000017500000000047611651544322022353 0ustar ilyailya(( 33330033330033330333300!301!33"""""!!ugene-1.9.8/src/plugins/expert_discovery/images/extractSignals2.png0000644000175000017500000000154611651544322024221 0ustar ilyailyaPNG  IHDRh6tRNS7X}IDATxy\Z8IENDB`ugene-1.9.8/src/plugins/expert_discovery/images/negseq.ico0000644000175000017500000000257611651544322022420 0ustar ilyailyah( ʦ """)))UUUMMMBBB999|PP3f3333f333ff3fffff3f3f̙f3333f3333333333f3333333f3f33ff3f3f3f3333f3333333f3̙33333f333ff3ffffff3f33f3ff3f3f3ffff3fffffffff3fffffff3f̙ffff3ff333f3ff33fff33f3ff̙3f3f3333f333ff3fffff̙̙3̙f̙̙̙3f̙3f3f3333f333ff3fffff3f3f̙3ffffffffff!___www????????????????????????ugene-1.9.8/src/plugins/expert_discovery/images/extractSignals2.ico0000644000175000017500000000047611651544322024210 0ustar ilyailya(( ""    ""30303030" " NN[[ugene-1.9.8/src/plugins/expert_discovery/images/repetition.ico0000644000175000017500000000257611651544322023320 0ustar ilyailyah( ʦ """)))UUUMMMBBB999|PP3f3333f333ff3fffff3f3f̙f3333f3333333333f3333333f3f33ff3f3f3f3333f3333333f3̙33333f333ff3ffffff3f33f3ff3f3f3ffff3fffffffff3fffffff3f̙ffff3ff333f3ff33fff33f3ff̙3f3f3333f333ff3fffff̙̙3̙f̙̙̙3f̙3f3f3333f333ff3fffff3f3f̙3ffffffffff!___www ?ssugene-1.9.8/src/plugins/expert_discovery/images/fileopen.png0000644000175000017500000000100611651544322022734 0ustar ilyailyaPNG  IHDRatEXtSoftwareAdobe ImageReadyqe<IDATxڌKPƿ[t N.Nڎ Z|,p .;( N(uA"EDS{Ii6&9sΗðB@HػCfbl&|Fdb~HI `] IENDB`ugene-1.9.8/src/plugins/expert_discovery/images/newDoc.ico0000644000175000017500000000047611651544322022352 0ustar ilyailya(( ugene-1.9.8/src/plugins/expert_discovery/images/interval.ico0000644000175000017500000000257611651544322022762 0ustar ilyailyah( ʦ """)))UUUMMMBBB999|PP3f3333f333ff3fffff3f3f̙f3333f3333333333f3333333f3f33ff3f3f3f3333f3333333f3̙33333f333ff3ffffff3f33f3ff3f3f3ffff3fffffffff3fffffff3f̙ffff3ff333f3ff33fff33f3ff̙3f3f3333f333ff3fffff̙̙3̙f̙̙̙3f̙3f3f3333f333ff3fffff3f3f̙3ffffffffff!___www effugene-1.9.8/src/plugins/expert_discovery/images/ts.ico0000644000175000017500000000257611651544322021564 0ustar ilyailyah( ʦ """)))UUUMMMBBB999|PP3f3333f333ff3fffff3f3f̙f3333f3333333333f3333333f3f33ff3f3f3f3333f3333333f3̙33333f333ff3ffffff3f33f3ff3f3f3ffff3fffffffff3fffffff3f̙ffff3ff333f3ff33fff33f3ff̙3f3f3333f333ff3fffff̙̙3̙f̙̙̙3f̙3f3f3333f333ff3fffff3f3f̙3ffffffffff!___www""""""""""""""""""""""""""""""""""""""""""""""""""""7w{{Wugene-1.9.8/src/plugins/expert_discovery/images/csroot.png0000644000175000017500000000154611651544322022455 0ustar ilyailyaPNG  IHDRh6tRNS7X}IDATx334333?\-T/IENDB`ugene-1.9.8/src/plugins/expert_discovery/images/control.png0000644000175000017500000000154611651544322022624 0ustar ilyailyaPNG  IHDRh6tRNS7X}IDATx&#,IENDB`ugene-1.9.8/src/plugins/expert_discovery/images/folder.png0000644000175000017500000000154611651544322022417 0ustar ilyailyaPNG  IHDRh6tRNS7X}IDATx/3kk/ff0$ S}IENDB`ugene-1.9.8/src/plugins/expert_discovery/images/undefined.ico0000644000175000017500000000257611651544322023077 0ustar ilyailyah( ʦ """)))UUUMMMBBB999|PP3f3333f333ff3fffff3f3f̙f3333f3333333333f3333333f3f33ff3f3f3f3333f3333333f3̙33333f333ff3ffffff3f33f3ff3f3f3ffff3fffffffff3fffffff3f̙ffff3ff333f3ff33fff33f3ff̙3f3f3333f333ff3fffff̙̙3̙f̙̙̙3f̙3f3f3333f333ff3fffff3f3f̙3ffffffffff!___www ??ugene-1.9.8/src/plugins/expert_discovery/images/loadControlsSeqAnnot.png0000644000175000017500000000154611651544322025260 0ustar ilyailyaPNG  IHDRh6tRNS7X}IDATx08IENDB`ugene-1.9.8/src/plugins/expert_discovery/images/setRecBound.ico0000644000175000017500000000047611651544322023350 0ustar ilyailya(( """"""""""""""""""!""""""!"""""""""""""""""! """!!""""!"""""""""""""""""""""""""""""""""""" """?????  '?ugene-1.9.8/src/plugins/expert_discovery/images/distance.ico0000644000175000017500000000257611651544322022730 0ustar ilyailyah( ʦ """)))UUUMMMBBB999|PP3f3333f333ff3fffff3f3f̙f3333f3333333333f3333333f3f33ff3f3f3f3333f3333333f3̙33333f333ff3ffffff3f33f3ff3f3f3ffff3fffffffff3fffffff3f̙ffff3ff333f3ff33fff33f3ff̙3f3f3333f333ff3fffff̙̙3̙f̙̙̙3f̙3f3f3333f333ff3fffff3f3f̙3ffffffffff!___www Yugene-1.9.8/src/plugins/expert_discovery/images/loadControlsSeq.ico0000644000175000017500000000047611651544322024247 0ustar ilyailya(( UUUUUUUPUQUPUQ"!UUUU#1UPU#2PQ#2PQ#2B #2"2U#333"#333""""2 ??ugene-1.9.8/src/plugins/expert_discovery/images/ExpertDiscovery.ico0000644000175000017500000005217611651544322024276 0ustar ilyailya 00h ( 00 h^"00'  nDhQ(0`wwwwwwwwwwwwwwwwwwwwww׈wwwwwwwwwwwwwwwwwwwwwwxxx}׈xxx}wwwwwww}}}}}}}}}}}}}}}}}wwwwwwwwwww}׈x}wwwwwwww݀??( @wwwwwwwwwwwwww׈wwwwwwwwwwwwwwxx}׈xxx}www}}}}}}}}}wwwwwww}׈x}wwww݀?( wwwwwww}x}x}x}x}x}x}x}wwwwwww}ׇw}ׁׁׁ׈wwww(0`wXkqN]tno0-1-6-˭ymC,B,w:"o\hP]>te=ggrlgNɓbћit5u6ˑXČV۰̯À5ˎI٦nڧo仐Á6dž:ʋ=ȋAغˌ=ݭlܭpޱw彉ղʌ7ΗF{Ҩ~Ȋ'۩]Ϡ޸ڤJ֡بڭ۰ݴ١/͊ώєҖӚ՟ץmz˃N]:IH\OUJI=cY\ULGa]gcqmjernyvnkQOWV|z‰Ďǔȕʚ˝ə̞̟ΤհܾЩִںL]dn“@b~ϧֶ>88+/h\^}qq[`//"QRT$1=>>8+2j\^sccy\`2/"OQ$%=>>*2i\^sccy\a//"NO66**L=>(2i\]~rccy\a//"WNFTHI*++LL=(/h\^|~rccs\`//'VWRFTHJCDKLL)2j\]x|~rccp~\_//'VVQRFTHJCDKL(/i\^wx|~pcccccb\`//'UVOQRFGHJCDK(/i\]wwx|pcckrss\a//0UUNOQRSGHIJD(2i\^vwwxpccr\`///YUWNOQRFTHIJ)/j\]uvwwmccp\`//9YYVWNO5;*THI)2j\]uuvwmccp\a//9XYVVWNSTH)2i\]ouuvmccbbbbbs\a//@XX0RST)/i\]oouulefffggkt\`/2@ZXX:;NPRF(/h\]loouuvwwx|~\_2/@ZZXXYYUUUVWNOPQ(/i\]ffggkkqqqzzz{{{\_//?MMMMEEEAAAA33452i\\\\\\\\\\\\\\\\\\\`//&&&&&--&&&&-&&&&./illlllllll##"      пѻ  пҿ ǿ ĭѻѬĮĮпĮдĭϳγι͹ƹĮ̸˷հ®ŭᨼ켨켼ǻ??( @nPhixѶҷ1-ŦvyufbJƝŜO1aAgO`>eDl™d=iIŽpȢַd8hEsrHg͹ˆXOດȧÀ5ĝĄ:ʋ=ݰzԶˌ=ҚSܭn澋ݿΐ;ҘH۩^仁ȗі;qӦٲ۸ݩL߯_ب֩ڭ۰߹٢5͊ѕӚԟj̅ؠL3_s-GCBHBvBuAuBvD7m3eH%0_J.M5>w+I4D2P=F9I=J=TGf[MEaYg^og`Zf_rld`ytzuqqn~ƔŎșʞ̞ʙ̞˞ΥҩٷںܾԱ׿|ʣЭطZ7s8t5uX^d3Zz#$$8?IS\b*>Z~##$WpWo/38<Xe`dlstyTryyhz@sGxv6gDrKvNxU8^j}!9,']ZZZZZZZZZZZWV-1---------1-\gmV2.AHBC5D;<<(-^iz|kV2.P:#!!+=>(-\ecokV239 $=(-]e{cokV73@ GJ'0<(-^e~xcokV78@ OGJKD;*1]d}~wca``kV78F OOGJKD*1\dy}rch{kV7EF MNOGIK/1\buyrcjkV?EE RR.#:I/-[btuncfssvkV?LE&%"9G41]_ptqhhhjjkV?LTE@NO41]_mptuy}~lV6SUTTQQQRRN91[WXXXYXXYXYYWV-)))))))))),,$ ſ ū ˷ʪڪٶ׶ֽսԼϮ󹺺ū¿?( uVhtzԷ™T,d<ڼʔrʔsd6c6YŠ`ϛoˆU֡qաp֢qݱҘXҙYԟeӞȅIӜYҙXӚQӛQȈ)Ȍ7ȔݾЖ8ї<Ҙ?Çٲҟצ_s-C<<==.ECK2LPV.$ E@J3MOU.  !D?H31IT.-,%B;G1JKS.( ) *E9A011R.&#++E/4678:."&' NQWhX^XXXe rpqt}~]mv\l{[izZjywYdjklnocsgba`_f|ux||||d}caV7 GJ*1dychV7 OG/1(0` # # # # # # # #! # #! #! # # # # # # # #gdc # # #! # # # # # # # # # # # # # # # # #BuAuBvBvBvBvAuAuBvBvAuBuBvBvBvBvAuAuBv! #o3t5t5t5t5t5t5t5t5t6t5t5u6t5t5t5t6t5t5t5! #! #aZIIIIHIIHIIIIIHHHIIIBvʋ=ʋ=ˌ=ʋ=ʋ=ʋ=ˋ=ˋ=ʋ=ʋ=ʋ=ʋ=ˋ=ʋ=ʋ=ˌ=ʋ=ʋ=ˌ=ʋ=lR! #aYIHRΗFd7d8d9dHRZ`invyʁˆ΍єҙڦnʋ=lS! #bZH=zB2D4E9F:H?H@KDLHNJQOROUSVUWWYZM^IBuʋ=ˌ=~؟!ؠ*٢6٢;٣CڥKڦPڧWۨZ۪`۪c۬jݭnݮqݰwҙ`ˌ=lR! #bZIIIIIIHHIHIIHHIIIHHAuˌ=ˌ=À5Á5À5À5À5À5€5À5Á5À5Á5À5Á5Á5À5À5dž:ʋ=lR! #~T>jZfWeVaS`Q]OZLZK@b;wi=ua=ua=ua=uanglq,,,,2#4@egdc$s$;kcgm,,,,1$4@egdc%s#:j_cg"=, 9y!:, 91#5@fgdc%t$8iZ_cgmqv{1#5Afgdc$s$0[FHLQSY[_aehjoqum.#5@egdc%s$$$###$#$$$$#$##$##$5@fgdc8w##$$#$#$$$##$##$$##$Xf\{|vkkh\{qvh\{h\{ąxxttqommkkkh??( @ # # # # # # # # # # # # # # # # # # # # # # # # # #BL@BM@BM@BL@BL@BL@BL@BM@CMABM@BL@BL@ #w\Rv\Rw]Sw\Rw\Rw\Sv\Rv\Rw\Rw]Sw]Sw]StYQ1-/ #AuHIHHHHHIHHHI_s-ʋ=ˌ=ˋ=ʋ=ʋ=ˌ=ʋ=ˋ=ʋ=ˌ=ˌ=ʋ=t6REE #BuI5|ҭ׵ظܿŷͺPF_s-ӛVݯ}Ԧթٳ۷޿ťt6RDD #AuP=˝ҩʞqnI<_s-ӚTݰyԟɘknrsʬt5REE #BvN8ɘ̞0_OH۾I=^s,ҚQݮp彂aAL.hEiJX7bIεȧt5RDE #BvM6Ŏʙ0`LDڻ۾I=_s-ҙM۫kq1.fHب۰ດÍqԶǤu6RDD #AuK2Ŏ~y0_LDհٸܾI=_s-ҙK۩_l1.fFӜب۰şʋ=REE #BvJ.~yt0_3f6l6mÔܾI=^s,ҙFܪ]b1.dCҗӛةۯߺěˌ=REE #AuI+uq}rj0_E5Υط۾I=_s-їEڦP߯]1-eA͊ҕӜب٭ߺʋ=SEE #BuH'rmuqnf0_G9Ȕ̞ҩԯٷI=_s-ї>٥IެQ0-d=ʃ̇ޱxŠcȘڭʋ=REE #BuG!f_rmf[0_>w+^Wa\c_ȚԮI=^s,җ=٢<ݪHB,T4OˆXrHa?㸀ب彊ʋ=REE #BuFaXg_g]B.D3D4G8G:ΤI=_s-і7١/HMc6d8d;e?vѕӛ澊ˌ=SEE #BvCWHbYf^pkuq}ōǔ̞I<^s,ΐ;ؠ2GV_lt˃ˇє廂ʋ=SEE #AuFBCCCCBCCBCG_s-ʋ=À5À5À5À5€5À5Á5Á5À5À5Ń8„;tcc #Ʋ׿ӶͫɢZ5u7t7s7t7t7t3ZzWoWpWpWpWoTriwlÙȡֶ˼˼`#STWY[^_ccf]$vWjuezƦֶd$$pM\gOzl}r\$6_,U܏,!9$XBecX|tzly$9\;ki,#4@ey#Nx2cd',$?Ruz$yJv,$CXzy#rxGta,,$CXzy$krDr(t!:,#CYzy#clAoJvԇ,,$CXzy$^eAs,Gxۂ,,#BXzz#V`eltyls#CXzz$/034578;<=<$CY{=[WTQMHE?=86+s}}_˘}_˘࠸؛؛؛؛؛؛ؘ?( GI=J=I=I=I=_s-̏IҘXҘXҙYҘXҙY|Xfdcd`ѩ;w _s-ԞdȔd7d6ޫZgec]U˜;w ۽и_s-ӜYc6Zݰʔr˫ZfdcXO;w _s-LJ)і9җ<ԛQӜYӞe\փԹv,i;z;z;z;z #include "ExpertDiscoveryCSUtil.h" #include #include namespace U2 { struct State{ double dProbability; double dCoverage; double dFisher; double dIntProbability; double dIntFisher; int nMinComplexity; int nMaxComplexity; double dMinPosCorrelation; double dMaxPosCorrelation; double dMinNegCorrelation; double dMaxNegCorrelation; bool bCorrelationImportant; bool bCheckFisherMinimization; bool bStoreOnlyDifferent; bool bUmEnabled; int nUmSamplesBound; double dUmBound; void setDefaultState(){ dProbability = 25; dCoverage = 25; dFisher = 0.05; dIntProbability = 0; dIntFisher = 0.2; nMinComplexity = 1; nMaxComplexity = 5; dMinPosCorrelation = 0.5; dMaxPosCorrelation = 1; dMinNegCorrelation = -1; dMaxNegCorrelation = 1; bCorrelationImportant = false; bCheckFisherMinimization = false; bStoreOnlyDifferent = true; bUmEnabled = false; dUmBound = 0.05; nUmSamplesBound = 50; } }; using namespace DDisc; class OperationSet : public QWidget{ Q_OBJECT public: OperationSet(QWidget* parent):QWidget(parent){}; virtual void loadData(void *pData){}; virtual void saveData(void *pData){}; virtual bool isReadyToClose(){return true;} }; class ExpertDiscoveryExtSigWiz : public QWizard, public Ui_SignalsExtrWiz{ Q_OBJECT public: ExpertDiscoveryExtSigWiz(QWidget *parent, CSFolder* f, int positiveSize); virtual ~ExpertDiscoveryExtSigWiz(); double getProbability() {return state.dProbability/100;} double getCoverage() {return state.dCoverage/100;} double getFisher() {return state.dFisher;} double getIntProbability() {return state.dIntProbability/100;} double getIntFisher() {return state.dIntFisher;} int getMinComplexity() {return state.nMinComplexity;} int getMaxComplexity() {return state.nMaxComplexity;} double getMinPosCorrelation() {return state.dMinPosCorrelation;} double getMaxPosCorrelation() {return state.dMaxPosCorrelation;} double getMinNegCorrelation() {return state.dMinNegCorrelation;} double getMaxNegCorrelation() {return state.dMaxNegCorrelation;} bool getCorrelationImportant() {return state.bCorrelationImportant;} bool getCheckFisherMinimization() {return state.bCheckFisherMinimization;} bool getStoreOnlyDifferent() {return state.bStoreOnlyDifferent;} bool getUmEnabled() {return state.bUmEnabled;} int getUmSamplesBound() {return state.nUmSamplesBound;} double getUmBound() {return state.dUmBound;} std::vector& getPredicates() {return predicates;} void setFolder(CSFolder* f){folder = f;} CSFolder* getFolder(){return folder;} virtual void accept(); protected slots: void sl_advButton(); void sl_distButton(); void sl_repetButton(); void sl_intervButton(); void sl_deleteButton(); void sl_idChanged(int id); void sl_selectionChanged (QTreeWidgetItem * current, QTreeWidgetItem * previous); private: int posSize; State state; std::vector predicates; CSFolder* folder; QTreeWidgetItem *distItem, *intervItem, *repetItem; OperationSet* sigSet[4]; QStackedLayout* sigSetLayout; void initSet(); void updateTree(const CSFolder* pFolder = NULL, QTreeWidgetItem* treeItem = NULL); bool checkD(const QLineEdit* lineE) const; void hideParameters(); }; class DistanceSet : public OperationSet{ Q_OBJECT private: int to; int from; bool isOrderImportant; bool isMaxUNL; QLineEdit* fromEditD; QLineEdit* toEditD; QCheckBox* unlimCheckBoxD; QCheckBox* orderCheckBoxD; public: DistanceSet (QWidget* parent); virtual void loadData(void *pData); virtual void saveData(void *pData); virtual bool isReadyToClose(); void updateData(bool side=true); protected slots: void sl_unlim(); void sl_order(); }; class IntervalSet : public OperationSet{ Q_OBJECT private: int from; int to; bool isMaxUNL; QLineEdit* fromIEdit; QLineEdit* toIEdit; QCheckBox* unlimCheckBoxI; public: IntervalSet (QWidget* parent); virtual void loadData(void *pData); virtual void saveData(void *pData); virtual bool isReadyToClose(); void updateData(bool side=true); protected slots: void sl_unlim(); }; class RepetitionSet : public OperationSet{ Q_OBJECT private: int nmin; int nmax; int min; int max; bool isMaxUNL; QLineEdit* fromDEdit; QLineEdit* toDEditR; QCheckBox* unlimCheckBoxR; QLineEdit* fromCEditR; QLineEdit* toCEditR; public: RepetitionSet (QWidget* parent); virtual void loadData(void *pData); virtual void saveData(void *pData); virtual bool isReadyToClose(); void updateData(bool side=true); protected slots: void sl_unlim(); }; enum { T_UNDEFINED, T_DISTANCE, T_REITERATION, T_INTERVAL }; }//namespace ugene-1.9.8/src/plugins/expert_discovery/src/ExpertDiscoverySetupRecBoundDialog.cpp0000644000175000017500000000300411651544323027376 0ustar ilyailya#include "ExpertDiscoverySetupRecBoundDialog.h" #include namespace U2 { ExpertDiscoverySetupRecBoundDialog::ExpertDiscoverySetupRecBoundDialog(double dRecognizationBound, const std::vector& vPosScore, const std::vector& vNegScore) : QDialog() , recognizationBound(dRecognizationBound) , probNegRec(0) , probPosRej(0) , posScore( vPosScore ) , negScore( vNegScore ){ setupUi(this); recBoundSpinBox->setValue(recognizationBound); posRecLineEdit->setText(QString("%1").arg(probPosRej)); negRecLineEdit->setText(QString("%1").arg(probNegRec)); connect(recBoundSpinBox, SIGNAL(valueChanged ( double )), SLOT(sl_recBoundChaged(double))); sl_recBoundChaged(recognizationBound); } void ExpertDiscoverySetupRecBoundDialog::accept(){ recognizationBound = recBoundSpinBox->value(); QDialog::accept(); } void ExpertDiscoverySetupRecBoundDialog::sl_recBoundChaged(double val){ recognizationBound = val; updateProbs(); posRecLineEdit->setText(QString("%1").arg(probPosRej)); negRecLineEdit->setText(QString("%1").arg(probNegRec)); } void ExpertDiscoverySetupRecBoundDialog::updateProbs(){ probPosRej = 0; for (int i=0; i<(int)posScore.size(); i++) if (posScore[i] <= recognizationBound) probPosRej++; probPosRej /= posScore.size(); probNegRec = 0; for (int i=0; i<(int)negScore.size(); i++) if (negScore[i] > recognizationBound) probNegRec++; probNegRec /= negScore.size(); } }//namespace ugene-1.9.8/src/plugins/expert_discovery/src/ExpertDiscoveryTreeWidgets.cpp0000644000175000017500000013021511651544323025767 0ustar ilyailya#include "ExpertDiscoveryTreeWidgets.h" #include #include #include using std::strstream; using std::ws; namespace U2 { //////////////////////////////////////////////////////////// EDPIPropertyType::EDPIPropertyType(){ } EDPIPropertyType::~EDPIPropertyType(){ } ////////////////////////////////////////////////////////////////// EDPIProperty::EDPIProperty(const EDPIProperty& rProperty) : m_pType(NULL) , m_pCallback(NULL) { *this = rProperty; } EDPIProperty::EDPIProperty(QString strName /* ="" */) : m_pType(NULL) , m_pCallback(NULL) { setType(EDPIPropertyTypeStaticString::getInstance()); setName( strName ); } EDPIProperty::~EDPIProperty() { delete m_pCallback; } const EDPIProperty& EDPIProperty::operator =(const EDPIProperty& rProperty) { setType( rProperty.m_pType); setName( rProperty.getName() ); if (rProperty.m_pCallback) m_pCallback = rProperty.m_pCallback->clone(); else m_pCallback = NULL; return *this; } QString EDPIProperty::getName() const { return m_strName; } void EDPIProperty::setName(QString strName) { m_strName = strName; } QString EDPIProperty::getValue() const { if (m_pCallback) return m_pCallback->call(); else { QString strUndefined = "Undefined"; return strUndefined; } } void EDPIProperty::setCallback(ICallback* pCallback) { m_pCallback = pCallback; } const EDPIPropertyType* EDPIProperty::getType() const { return m_pType; } void EDPIProperty::setType(EDPIPropertyType* pType) { m_pType = pType; } //////////////////////////////////////////////////////////////////////////////////////////////////////// EDPIPropertyGroup::EDPIPropertyGroup(QString strName /*=""*/) { setName(strName); } EDPIPropertyGroup::EDPIPropertyGroup(const EDPIPropertyGroup& rGroup) { *this = rGroup; } EDPIPropertyGroup::~EDPIPropertyGroup() { } const EDPIPropertyGroup& EDPIPropertyGroup::operator=(const EDPIPropertyGroup& rGroup) { m_strName = rGroup.getName(); m_arProperties = rGroup.m_arProperties; return *this; } QString EDPIPropertyGroup::getName() const { return m_strName; } void EDPIPropertyGroup::setName(QString strName) { m_strName = strName; } int EDPIPropertyGroup::getPropertiesNumber() const { return m_arProperties.size(); } EDPIProperty& EDPIPropertyGroup::getProperty(int nProp) { assert( nProp>=0 && nProp=0 && nProp> value; str >> ws; if (value>=0 && str.eof()) return true; return false; } ////////////////////////////////////////////////////////////////////////////// IMPLEMENT_GETINSTANCE(EDPIPropertyTypeUnsignedIntWithUnl) EDPIPropertyTypeUnsignedIntWithUnl::EDPIPropertyTypeUnsignedIntWithUnl() : EDPIPropertyTypeListEdit() { addValue("Unlimited"); } EDPIPropertyTypeUnsignedIntWithUnl::~EDPIPropertyTypeUnsignedIntWithUnl() { } bool EDPIPropertyTypeUnsignedIntWithUnl::isNumber() const { return true; } bool EDPIPropertyTypeUnsignedIntWithUnl::isValidValue(QString strValue) const { int nId = getValueId(strValue); if (nId >= 0) return true; int nValue = 0; strstream str; str << strValue.toStdString(); str >> nValue; str >> ws; if (str.eof() && nValue>=0) return true; return false; } ////////////////////////////////////////////////////////////////////////////// EDPIPropertyTypeList::EDPIPropertyTypeList() { } EDPIPropertyTypeList::~EDPIPropertyTypeList() { } bool EDPIPropertyTypeList::isNumber() const { return false; } bool EDPIPropertyTypeList::hasEdit() const { return false; } bool EDPIPropertyTypeList::hasPredefinedValues() const { return true; } int EDPIPropertyTypeList::getValueNumber() const { return m_arValues.size(); } QString EDPIPropertyTypeList::getValue(int i) const { return m_arValues[i]; } bool EDPIPropertyTypeList::isValidValue(QString strValue) const { return getValueId(strValue) >= 0; } void EDPIPropertyTypeList::addValue(QString strValue) { m_arValues.append(strValue); } int EDPIPropertyTypeList::getValueId(QString strValue) const { int nValNum = getValueNumber(); for (int i=0; i=0 && nGroup=0 && nGroup(child(i)); if(item){ const EDProjectItem* cItem = item->findItemConnectedTo(pData); if(cItem){ return cItem; } } } return NULL; } bool EDProjectItem::operator<(const QTreeWidgetItem &other) const{ const EDProjectItem* pItem1 = dynamic_cast(this); const EDProjectItem* pItem2 = dynamic_cast(&other); if(!pItem2 || !pItem1){ return QTreeWidgetItem::operator<(other); } EItemType type1 = pItem1->getType(); EItemType type2 = pItem2->getType(); if(sortOrd == ED_ORDER_DECREASING){ if (type1 == PIT_CS && type2 == PIT_CS){ const EDProjectItem* pItem3; pItem3 = pItem1; pItem1 = pItem2; pItem2 = pItem3; } } if (type1 == PIT_CS && type2 == PIT_CS){ const Signal* pSnl1 = ((EDPICS*) pItem1)->getSignal(); const Signal* pSnl2 = ((EDPICS*) pItem2)->getSignal(); switch (sortField) { case ED_FIELD_UNDEFINED: return QTreeWidgetItem::operator<(other); case ED_FIELD_PROBABILITY: return (pSnl1->getPriorProbability()getPriorProbability()); case ED_FIELD_COVERAGE: return (pSnl1->getPriorPosCoverage()getPriorPosCoverage()); case ED_FIELD_FISHER: return (pSnl1->getPriorFisher()getPriorFisher()); case ED_FIELD_NAME: default: return pItem1->getName() < pItem2->getName(); } }else if ( (type1 == PIT_CS_FOLDER || type1 == PIT_CS || type1 == PIT_MRK_ITEM) && (type2 == PIT_CS_FOLDER || type2 == PIT_CS || type2 == PIT_MRK_ITEM)) { if ((int)type1 < (int)type2) return false; else if ((int)type1 > (int)type2) return true; else return pItem1->getName() < pItem2->getName(); }else{ const EDProjectItem *pParent = dynamic_cast(dynamic_cast(pItem1)->parent()); if (pParent != NULL && pParent->getType() == PIT_CSN_DISTANCE) { return (pParent->child(0) == pItem1) ? true : false; } else{ return QTreeWidgetItem::operator<(other); } } } ///////////////////////////////////////////////////////////////////////////////////// EDPISequenceRoot::EDPISequenceRoot(ExpertDiscoveryData& edD) :edData(edD) { update(true); } EDPISequenceRoot::~EDPISequenceRoot() { } EItemType EDPISequenceRoot::getType() const { return PIT_SEQUENCEROOT; } void EDPISequenceRoot::update(bool bUpdateChildren) { QString strName = "Sequences"; setName(strName); clearGroups(); if (bUpdateChildren) { takeChildren(); addChild(new EDPIPosSequenceBase(edData.getPosSeqBase(), edData)); addChild(new EDPINegSequenceBase(edData.getNegSeqBase(), edData)); //if (pDoc->GetControlSeqBase().getSize() != 0) addChild(new EDPIControlSequenceBase(edData.getConSeqBase(), edData)); } } bool EDPISequenceRoot::isConnectedTo(void *pData) const { return false; } ///////////////////////////////////////////////////////////////////////////////////// EDPISequenceBase::EDPISequenceBase(QString strName, const SequenceBase& rSeqBase, ExpertDiscoveryData& edD) : m_rSeqBase (rSeqBase) ,edData(edD) { //assert(strName != NULL); setName(strName); update(true); } void EDPISequenceBase::update(bool bUpdateChildren) { clearGroups(); takeChildren(); int nSize = m_rSeqBase.getSize(); QString strSize = "Size"; QString strGenInfo = "General information"; EDPIProperty PropSize(strSize); PropSize.setCallback(new Callback(&m_rSeqBase, &DDisc::SequenceBase::getSize)); EDPIPropertyGroup GenInfo(strGenInfo); GenInfo.addProperty(PropSize); addGroup(GenInfo); if (bUpdateChildren) { for (int id=0; id(&m_rSeqBase, &DDisc::SequenceBase::getSize)); EDPIPropertyGroup GenInfo(strGenInfo); GenInfo.addProperty(PropSize); addGroup(GenInfo); if (bUpdateChildren) { takeChildren(); for (int id=0; id=0 && id(&m_rSeq, &DDisc::Sequence::getName)); PropSize.setCallback(new Callback(&m_rSeq, &DDisc::Sequence::getSize)); EDPIPropertyGroup GenInfo(strGenInfo); GenInfo.addProperty(PropName); GenInfo.addProperty(PropSize); addGroup(GenInfo); double dScore = m_rSeq.getScore(); double dBound = edData.getRecognizationBound(); EDPIProperty PropScore(strScore); PropScore.setCallback(new Callback(this, &EDPISequence::getScore)); EDPIProperty PropBound(strBound); PropBound.setCallback(new Callback(&edData, &ExpertDiscoveryData::getRecognizationBound)); EDPIProperty PropResult(strRecResult); PropResult.setCallback(new Callback(this, &EDPISequence::getResult)); EDPIPropertyGroup RecInfo(strRecognizationInfo); RecInfo.addProperty(PropScore); RecInfo.addProperty(PropBound); RecInfo.addProperty(PropResult); addGroup(RecInfo); //} } QString EDPISequence::getScore() const { if (getType() == PIT_CONTROLSEQUENCE) return "0"; if (m_rSeq.isHasScore() || edData.updateScore(const_cast(m_rSeq))) return toString(m_rSeq.getScore()); return "0"; } QString EDPISequence::getResult() const { if (getType() == PIT_CONTROLSEQUENCE) return "False"; if ((m_rSeq.isHasScore() || edData.updateScore(const_cast(m_rSeq))) && m_rSeq.getScore() > edData.getRecognizationBound()) return "True"; else return "False"; } EDPISequence::~EDPISequence() { } EItemType EDPISequence::getType() const { return PIT_SEQUENCE; } QString EDPISequence::getSequenceCode() { return QString::fromStdString(m_rSeq.getSequence()); } QString EDPISequence::getSequenceName() { return QString::fromStdString(m_rSeq.getName()); } bool EDPISequence::isConnectedTo(void *pData) const { return ((void*) &m_rSeq) == pData; } //////////////////////////////////////////////////////////// const CSFolder* EDPICSDirectory::getFolder() const{ return folder; } void EDPICSDirectory::setFolder(const CSFolder* pFolder){ folder = pFolder; } void EDPICSDirectory::update(bool bupdateChildren){ if (bupdateChildren) { takeChildren(); const CSFolder* pFolder = getFolder(); int nSubfolderNum = pFolder->getFolderNumber(); for (int nSubfolder=0; nSubfoldergetSubfolder(nSubfolder)); addChild(dynamic_cast(nFol)); } int nSignalNum = pFolder->getSignalNumber(); for (int nSignal=0; nSignalgetSignal(nSignal) ); addChild(dynamic_cast(nSig)); } } } bool EDPICSDirectory::isConnectedTo(void *pData) const{ return ((void*) folder) == pData; } //////////////////////////////////////////////// EDPICSFolder::EDPICSFolder(const CSFolder *pFolder) : EDPICSDirectory(pFolder){ update(true); } EDPICSFolder::~EDPICSFolder(){ } EItemType EDPICSFolder::getType() const{ return PIT_CS_FOLDER; } void EDPICSFolder::update(bool bupdateChildren){ clearGroups(); QString strName = "Name"; QString strEditor = "Editor"; EDPIProperty propName(strName); propName.setCallback(new Callback(getFolder(), &CSFolder::getName)); propName.setType(EDPIPropertyTypeString::getInstance()); EDPIPropertyGroup editor(strEditor); editor.addProperty(propName); addGroup(editor); EDPICSDirectory::update(bupdateChildren); } //virtual CExtPopupMenuWnd* CreatePopupMenu(HWND hWndCmdRecieve) const; QString EDPICSFolder::getName() const{ return getFolder()->getName(); } //////////////////////////////////////////////// EDPICSRoot::EDPICSRoot(CSFolder& rootF) : EDPICSDirectory(NULL) { setFolder(&rootF); update(true); } void EDPICSRoot::update(bool bUpdateChildren) { QString strCSRoot = "Complex signals"; setName(strCSRoot); EDPICSDirectory::update(bUpdateChildren); } EDPICSRoot::~EDPICSRoot() { } EItemType EDPICSRoot::getType() const { return PIT_CS_ROOT; } /////////////////////////////////////////////////// EDPICSNode::EDPICSNode(Operation *pOp1) :pOp(pOp1) ,m_pPS(NULL) { } EDPICSNode::~EDPICSNode(){ delete m_pPS; } Operation* EDPICSNode::getOperation(){ return pOp; } void EDPICSNode::setOperation(Operation *pOp){ this->pOp = pOp; } const Operation* EDPICSNode::getOperation() const{ return pOp; } void EDPICSNode::update(bool bupdateChildren){ delete m_pPS; m_pPS = NULL; if (pOp == NULL) { setName("Undefined"); } else { setName(QString::fromStdString(pOp->getDescription())); if (bupdateChildren) { takeChildren(); int nArgNum = pOp->getArgumentNumber(); for (int nArg=0; nArg(EDPICSNode::createCSN(pOp->getArgument(nArg))); emit si_getMetaInfoBase(); ch->setMetainfoBase(getMinfo()); addChild( ch ); if(ch->getType() != PIT_CSN_UNDEFINED){ ch->update(true); } //addChild(dynamic_cast( EDPICSNode::createCSN( pOp->getArgument(nArg) ))); } } } } EDPICSNode* EDPICSNode::createCSN( Operation *pOp ) { if (pOp == NULL) return new EDPICSNUndefined(); switch (pOp->getType()) { case OP_DISTANCE : return new EDPICSNDistance(dynamic_cast(pOp)); case OP_REITERATION : return new EDPICSNRepetition(dynamic_cast(pOp)); case OP_INTERVAL : return new EDPICSNInterval(dynamic_cast(pOp)); case OP_TS : { TS* pTS = dynamic_cast(pOp); if (!pTS->isFromMarking()) return new EDPICSNTSWord(pTS); else{ return new EDPICSNTSMrkItem(pTS); } } } assert(0); return NULL; } bool EDPICSNode::isConnectedTo(void *pData) const{ return ((void*) pOp) == pData; } const EDProcessedSignal* EDPICSNode::getProcessedSignal(ExpertDiscoveryData& edData){ if (m_pPS == NULL) { m_pPS = EDProcessedSignal::processSignal(pOp, &edData.getPosSeqBase(), &edData.getNegSeqBase()); if (m_pPS != NULL) { QString strGenInfo = "General information"; EDPIPropertyGroup GenInfo(strGenInfo); EDPIProperty prob("Probability"); EDPIProperty posCoverage("Pos. coverage"); EDPIProperty negCoverage("Neg. coverage"); EDPIProperty fisher("Fisher"); //EDPIProperty ul("ul"); prob.setCallback(new Callback(this, &EDPICSNode::getProbability)); posCoverage.setCallback(new Callback(this, &EDPICSNode::getPosCoverage)); negCoverage.setCallback(new Callback(this, &EDPICSNode::getNegCoverage)); fisher.setCallback(new Callback(this, &EDPICSNode::getFisher)); //ul.setCallback(new Callback(this, &EDPICSNode::getUl)); GenInfo.addProperty(prob); GenInfo.addProperty(posCoverage); GenInfo.addProperty(negCoverage); GenInfo.addProperty(fisher); // GenInfo.addProperty(ul); addGroup(GenInfo); } } return m_pPS; } QString EDPICSNode::getProbability() const{ if (m_pPS) return m_pPS->getPropertyValue("Probability"); return QString(); } QString EDPICSNode::getFisher() const{ if (m_pPS) return m_pPS->getPropertyValue("Fisher"); return QString(); } QString EDPICSNode::getUl() const{ if (m_pPS) return m_pPS->getPropertyValue("Ul"); return QString(); } QString EDPICSNode::getPosCoverage() const{ if (m_pPS) return m_pPS->getPropertyValue("Pos. coverage"); return QString(); } QString EDPICSNode::getNegCoverage() const{ if (m_pPS) return m_pPS->getPropertyValue("Neg. coverage"); return QString(); } QString EDPICSNode::getTypeAsString() const{ QString str; EDPIPropertyTypeList *pTList = EDPIPropertyTypeListCSNodeTypes::getInstance(); switch (getType()) { case PIT_CSN_UNDEFINED: str = "Undefined"; break; case PIT_CSN_DISTANCE: str = pTList->getValue(EDPIPropertyTypeListCSNodeTypes::DISTANCE); break; case PIT_CSN_REPETITION:str = pTList->getValue(EDPIPropertyTypeListCSNodeTypes::REPETITION); break; case PIT_CSN_INTERVAL: str = pTList->getValue(EDPIPropertyTypeListCSNodeTypes::INTERVAL); break; case PIT_CSN_WORD: str = pTList->getValue(EDPIPropertyTypeListCSNodeTypes::WORD); break; case PIT_CSN_MRK_ITEM: str = pTList->getValue(EDPIPropertyTypeListCSNodeTypes::MRK_ITEM); break; } return str; } EDPICS::EDPICS(const Signal *pSignal) : EDPICSNode(pSignal->getSignal()) , m_pSignal(pSignal) { update(true); } EDPICS::~EDPICS(){ pOp = NULL; } EItemType EDPICS::getType() const{ return PIT_CS; } const Signal* EDPICS::getSignal() const{ return m_pSignal; } void EDPICS::update(bool bupdateChildren){ clearGroups(); QString strName = "Name"; QString strEditor = "Editor"; QString strDescription = "Description"; QString strPriorParams = "Prior parameter"; QString strPriorProb = "Probability"; QString strPriorFisher = "Fisher criteria"; QString strPriorPosCoverage = "Pos. Coverage"; QString strPriorNegCoverage = "Neg. Coverage"; EDPIProperty PropName(strName); PropName.setCallback(new Callback(m_pSignal, &DDisc::Signal::getName)); PropName.setType(EDPIPropertyTypeString::getInstance()); EDPIProperty PropDesc(strDescription); PropDesc.setCallback(new Callback(m_pSignal, &DDisc::Signal::getDescription)); PropDesc.setType(EDPIPropertyTypeString::getInstance()); EDPIPropertyGroup Editor(strEditor); Editor.addProperty(PropName); Editor.addProperty(PropDesc); addGroup(Editor); EDPICSNode::update(false); setName(m_pSignal->getName().c_str()); // if (m_pSignal->isPriorParamsDefined()) { // EDPIProperty PropPriorProb(strPriorProb); // PropPriorProb.setCallback(new Callback(this, &EDPICS::getPriorProbability)); // PropPriorProb.setType(EDPIPropertyTypeStaticString::getInstance()); // // EDPIProperty PropPriorPosCoverage(strPriorPosCoverage); // PropPriorPosCoverage.setCallback(new Callback(this, &EDPICS::getPriorPosCoverage)); // PropPriorPosCoverage.setType(EDPIPropertyTypeStaticString::getInstance()); // // EDPIProperty PropPriorNegCoverage(strPriorNegCoverage); // PropPriorNegCoverage.setCallback(new Callback(this, &EDPICS::getPriorNegCoverage)); // PropPriorNegCoverage.setType(EDPIPropertyTypeStaticString::getInstance()); // // EDPIProperty PropPriorFisher(strPriorFisher); // PropPriorFisher.setCallback(new Callback(this, &EDPICS::getPriorFisher)); // PropPriorFisher.setType(EDPIPropertyTypeStaticString::getInstance()); // // EDPIPropertyGroup PriorParams(strPriorParams); // PriorParams.addProperty(PropPriorProb); // PriorParams.addProperty(PropPriorFisher); // PriorParams.addProperty(PropPriorPosCoverage); // PriorParams.addProperty(PropPriorNegCoverage); // addGroup(PriorParams); // } if (bupdateChildren) { takeChildren(); if (m_pSignal->getSignal() == NULL) { addChild(dynamic_cast( new EDPICSNUndefined() )); } else { EDProjectItem* ch = dynamic_cast(EDPICSNode::createCSN(m_pSignal->getSignal())); emit si_getMetaInfoBase(); ch->setMetainfoBase(getMinfo()); addChild( ch ); ch->update(true); } } } bool EDPICS::isConnectedTo(void *pData) const{ return ((void*) m_pSignal) == pData; } //virtual CExtPopupMenuWnd* CreatePopupMenu(HWND hWndCmdRecieve) const; //virtual bool isSelected() const; QString EDPICS::getPriorProbability() const{ QString str = "%1"; if (m_pSignal->getPriorProbability() != UNDEFINED_VALUE) str = str.arg(m_pSignal->getPriorProbability()); else str = "Undefined"; return str; } QString EDPICS::getPriorFisher() const{ QString str = "%1"; if (m_pSignal->getPriorFisher() != UNDEFINED_VALUE) str = str.arg(m_pSignal->getPriorFisher()); else str = "Undefined"; return str; } QString EDPICS::getPriorPosCoverage() const{ QString str = "%1"; if (m_pSignal->getPriorPosCoverage() != UNDEFINED_VALUE) str = str.arg(m_pSignal->getPriorPosCoverage()); else str = "Undefined"; return str; } QString EDPICS::getPriorNegCoverage() const{ QString str = "%1"; if (m_pSignal->getPriorNegCoverage() != UNDEFINED_VALUE) str = str.arg(m_pSignal->getPriorNegCoverage()); else str = "Undefined"; return str; } //////////////////////////////////////////////////////////// EDPICSNUndefined::EDPICSNUndefined() : EDPICSNode(NULL) { update(true); } void EDPICSNUndefined::update(bool bupdateChildren) { QString strType = "Type"; QString strEditor = "Editor"; EDPIProperty PropType(strType); PropType.setCallback(new Callback(this, &EDPICSNode::getTypeAsString)); PropType.setType(EDPIPropertyTypeListCSNodeTypes::getInstance()); EDPIPropertyGroup Editor(strEditor); Editor.addProperty(PropType); addGroup(Editor); EDPICSNode::update(bupdateChildren); } EDPICSNUndefined::~EDPICSNUndefined() { } EItemType EDPICSNUndefined::getType() const { return PIT_CSN_UNDEFINED; } /////////////////////////////////////////////////////////////////////////////////////// EDPICSNDistance::EDPICSNDistance(OpDistance *pOp) : EDPICSNode(pOp) { update(true); } void EDPICSNDistance::update(bool bupdateChildren) { clearGroups(); QString strType = "Type"; QString strFrom = "Distance from"; QString strTo = "Distance to"; QString strEditor = "Editor"; QString strOrder = "Order"; QString strDistanceType = "Distance type"; OpDistance* pOp = dynamic_cast(getOperation()); assert(pOp != NULL); EDPIPropertyTypeList *pTList = EDPIPropertyTypeListCSNodeTypes::getInstance(); EDPIProperty PropType(strType); PropType.setCallback(new Callback(this, &EDPICSNode::getTypeAsString)); PropType.setType(pTList); EDPIProperty PropFrom(strFrom); PropFrom.setCallback(new Callback(this, &EDPICSNDistance::getPropFrom)); PropFrom.setType(EDPIPropertyTypeUnsignedInt::getInstance()); EDPIProperty PropTo(strTo); PropTo.setCallback(new Callback(this, &EDPICSNDistance::getPropTo)); PropTo.setType(EDPIPropertyTypeUnsignedIntWithUnl::getInstance()); EDPIProperty PropOrder(strOrder); PropOrder.setType(EDPIPropertyTypeBool::getInstance()); PropOrder.setCallback(new Callback(this, &EDPICSNDistance::getPropOrder)); EDPIProperty PropDistType(strDistanceType); PropDistType.setType(EDPIPropertyTypeDistType::getInstance()); PropDistType.setCallback(new Callback(this, &EDPICSNDistance::getPropDistType)); EDPIPropertyGroup Editor(strEditor); Editor.addProperty(PropType); Editor.addProperty(PropDistType); Editor.addProperty(PropFrom); Editor.addProperty(PropTo); Editor.addProperty(PropOrder); addGroup(Editor); emit si_getMetaInfoBase(); EDPICSNode::update(bupdateChildren); } EDPICSNDistance::~EDPICSNDistance() { } EItemType EDPICSNDistance::getType() const { return PIT_CSN_DISTANCE; } QString EDPICSNDistance::getPropDistType() const { const OpDistance* pOp = dynamic_cast(getOperation()); assert(pOp != NULL); int nType = (int) pOp->getDistanceType(); return EDPIPropertyTypeDistType::getInstance()->getValue(nType); } QString EDPICSNDistance::getPropFrom() const { const OpDistance* pOp = dynamic_cast(getOperation()); assert(pOp != NULL); return QString("%1").arg(pOp->getDistance().getFrom()); } QString EDPICSNDistance::getPropTo() const { const OpDistance* pOp = dynamic_cast(getOperation()); assert(pOp != NULL); int nTo = pOp->getDistance().getTo(); if (nTo == PINF) return EDPIPropertyTypeUnsignedIntWithUnl::getInstance()->getValue(0); else return QString("%1").arg(nTo); } QString EDPICSNDistance::getPropOrder() const { const OpDistance* pOp = dynamic_cast(getOperation()); assert(pOp != NULL); bool bOrder = pOp->isOrderImportant(); return EDPIPropertyTypeBool::getInstance()->getValue((!bOrder)?EDPIPropertyTypeBool::False : EDPIPropertyTypeBool::True); } /////////////////////////////////////////////////////////////////////////////////////// EDPICSNRepetition::EDPICSNRepetition(OpReiteration *pOp) : EDPICSNode(pOp) { update(true); } void EDPICSNRepetition::update(bool bupdateChildren) { clearGroups(); QString strType = "Type"; QString strCountFrom = "Count from"; QString strCountTo = "Count to"; QString strFrom = "Distance from"; QString strTo = "Distance to"; QString strEditor = "Editor"; QString strDistanceType = "Distance type"; OpReiteration* pOp = dynamic_cast(getOperation()); assert(pOp != NULL); EDPIPropertyTypeList *pTList = EDPIPropertyTypeListCSNodeTypes::getInstance(); EDPIProperty PropType(strType); PropType.setCallback(new Callback(this, &EDPICSNode::getTypeAsString)); PropType.setType(pTList); EDPIProperty PropFrom(strFrom); PropFrom.setCallback(new Callback(this, &EDPICSNRepetition::getPropFrom)); PropFrom.setType(EDPIPropertyTypeUnsignedInt::getInstance()); EDPIProperty PropTo(strTo); PropTo.setCallback(new Callback(this, &EDPICSNRepetition::getPropTo)); PropTo.setType(EDPIPropertyTypeUnsignedIntWithUnl::getInstance()); EDPIProperty PropDistType(strDistanceType); PropDistType.setType(EDPIPropertyTypeDistType::getInstance()); PropDistType.setCallback(new Callback(this, &EDPICSNRepetition::getPropDistType)); EDPIProperty PropCountFrom(strCountFrom); PropCountFrom.setType(EDPIPropertyTypeUnsignedInt::getInstance()); PropCountFrom.setCallback(new Callback(this, &EDPICSNRepetition::getCountFrom)); EDPIProperty PropCountTo(strCountTo); PropCountTo.setType(EDPIPropertyTypeUnsignedInt::getInstance()); PropCountTo.setCallback(new Callback(this, &EDPICSNRepetition::getCountTo)); EDPIPropertyGroup Editor(strEditor); Editor.addProperty(PropType); Editor.addProperty(PropCountFrom); Editor.addProperty(PropCountTo); Editor.addProperty(PropDistType); Editor.addProperty(PropFrom); Editor.addProperty(PropTo); addGroup(Editor); emit si_getMetaInfoBase(); EDPICSNode::update(bupdateChildren); } EDPICSNRepetition::~EDPICSNRepetition() { } EItemType EDPICSNRepetition::getType() const { return PIT_CSN_REPETITION; } QString EDPICSNRepetition::getPropDistType() const { const OpReiteration* pOp = dynamic_cast(getOperation()); assert(pOp != NULL); int nType = (int) pOp->getDistanceType(); return EDPIPropertyTypeDistType::getInstance()->getValue(nType); } QString EDPICSNRepetition::getPropFrom() const { const OpReiteration* pOp = dynamic_cast(getOperation()); assert(pOp != NULL); return QString("%1").arg(pOp->getDistance().getFrom()); } QString EDPICSNRepetition::getPropTo() const { const OpReiteration* pOp = dynamic_cast(getOperation()); assert(pOp != NULL); int nTo = pOp->getDistance().getTo(); if (nTo == PINF) return EDPIPropertyTypeUnsignedIntWithUnl::getInstance()->getValue(0); else return QString("%1").arg(nTo); } QString EDPICSNRepetition::getCountFrom() const { const OpReiteration* pOp = dynamic_cast(getOperation()); assert(pOp != NULL); return QString("%1").arg(pOp->getCount().getFrom()); } QString EDPICSNRepetition::getCountTo() const { const OpReiteration* pOp = dynamic_cast(getOperation()); assert(pOp != NULL); return QString("%1").arg(pOp->getCount().getTo()); } /////////////////////////////////////////////////////////////////////////////////////// EDPICSNInterval::EDPICSNInterval(OpInterval *pOp) : EDPICSNode(pOp) { update(true); } void EDPICSNInterval::update(bool bupdateChildren) { clearGroups(); QString strType = "Type"; QString strFrom = "Distance from"; QString strTo = "Distance to"; QString strEditor = "Editor"; OpInterval* pOp = dynamic_cast(getOperation()); EDPIPropertyTypeList *pTList = EDPIPropertyTypeListCSNodeTypes::getInstance(); EDPIProperty PropType(strType); PropType.setCallback(new Callback(this, &EDPICSNode::getTypeAsString)); PropType.setType(pTList); EDPIProperty PropFrom(strFrom); PropFrom.setCallback(new Callback(this, &EDPICSNInterval::getPropFrom)); PropFrom.setType(EDPIPropertyTypeUnsignedInt::getInstance()); EDPIProperty PropTo(strTo); PropTo.setCallback(new Callback(this, &EDPICSNInterval::getPropTo)); PropTo.setType(EDPIPropertyTypeUnsignedIntWithUnl::getInstance()); EDPIPropertyGroup Editor(strEditor); Editor.addProperty(PropType); Editor.addProperty(PropFrom); Editor.addProperty(PropTo); addGroup(Editor); emit si_getMetaInfoBase(); EDPICSNode::update(bupdateChildren); } EDPICSNInterval::~EDPICSNInterval() { } EItemType EDPICSNInterval::getType() const { return PIT_CSN_INTERVAL; } QString EDPICSNInterval::getPropFrom() const { const OpInterval* pOp = dynamic_cast(getOperation()); assert(pOp != NULL); return QString("%1").arg(pOp->getInt().getFrom()); } QString EDPICSNInterval::getPropTo() const { const OpInterval* pOp = dynamic_cast(getOperation()); assert(pOp != NULL); int nTo = pOp->getInt().getTo(); if (nTo == PINF) return EDPIPropertyTypeUnsignedIntWithUnl::getInstance()->getValue(0); else return QString("%1").arg(nTo); } /////////////////////////////////////////////////////////////////////////////////////// EDPICSNTSWord::EDPICSNTSWord(TS *pTS) : EDPICSNode(pTS) { update(true); } void EDPICSNTSWord::update(bool bupdateChildren) { clearGroups(); QString strType = "Type"; QString strEditor = "Editor"; QString strWord = "Word"; EDPIPropertyTypeList *pTList = EDPIPropertyTypeListCSNodeTypes::getInstance(); EDPIProperty PropType(strType); PropType.setCallback(new Callback(this, &EDPICSNode::getTypeAsString)); PropType.setType(pTList); EDPIProperty PropWord(strWord); PropWord.setType(EDPIPropertyTypeString::getInstance()); PropWord.setCallback(new Callback(this, &EDPICSNTSWord::getPropWord)); EDPIPropertyGroup Editor(strEditor); Editor.addProperty(PropType); Editor.addProperty(PropWord); addGroup(Editor); EDPICSNode::update(bupdateChildren); } EDPICSNTSWord::~EDPICSNTSWord() { } EItemType EDPICSNTSWord::getType() const { return PIT_CSN_WORD; } QString EDPICSNTSWord::getPropWord() const { const TS *pTS = dynamic_cast(getOperation()); assert(pTS != NULL); return pTS->getWord().c_str(); } /////////////////////////////////////////////////////////////////////////////////////// EDPICSNTSMrkItem::EDPICSNTSMrkItem(TS *pTS) : EDPICSNode(pTS) { update(true); } void EDPICSNTSMrkItem::update(bool bupdateChildren) { clearGroups(); QString strType = "Type"; QString strEditor = "Editor"; QString strFamily = "Family"; QString strSignal = "Signal"; TS *pTS = dynamic_cast(getOperation()); EDPIPropertyTypeList *pTList = EDPIPropertyTypeListCSNodeTypes::getInstance(); EDPIProperty PropType(strType); PropType.setCallback(new Callback(this, &EDPICSNode::getTypeAsString)); PropType.setType(pTList); emit si_getMetaInfoBase(); if(getMinfo()){ const MetaInfoBase& rDesc = *getMinfo(); EDPIPropertyTypeDynamicList *pTFamily = EDPIPropertyTypeDynamicList::getInstance(); int nFamilyNum = rDesc.getFamilyNumber(); for (int i=0; iaddValue(rDesc.getSignalFamily(i).getName().c_str()); EDPIProperty PropFamily(strFamily); PropFamily.setType(pTFamily); PropFamily.setCallback(new Callback(this, &EDPICSNTSMrkItem::getPropFamily)); EDPIPropertyTypeDynamicList *pTSignal = EDPIPropertyTypeDynamicList::getInstance(); try { const Family& rFamily = rDesc.getSignalFamily(pTS->getFamily()); int nSigNum = rFamily.getSignalNumber(); for (int i=0;iaddValue(rFamily.getMetaInfo(i).getName().c_str()); } catch (exception) { } EDPIProperty PropSignal(strSignal); PropSignal.setType(pTSignal); PropSignal.setCallback(new Callback(this, &EDPICSNTSMrkItem::getPropSignal)); EDPIPropertyGroup Editor(strEditor); Editor.addProperty(PropType); Editor.addProperty(PropFamily); Editor.addProperty(PropSignal); addGroup(Editor); } EDPICSNode::update(bupdateChildren); } EDPICSNTSMrkItem::~EDPICSNTSMrkItem() { } EItemType EDPICSNTSMrkItem::getType() const { return PIT_CSN_MRK_ITEM; } QString EDPICSNTSMrkItem::getPropFamily() const { const TS *pTS = dynamic_cast(getOperation()); return pTS->getFamily().c_str(); } QString EDPICSNTSMrkItem::getPropSignal() const { const TS *pTS = dynamic_cast(getOperation()); return pTS->getName().c_str(); } /////////////////////////////////////////////////////////////////////////////////////// EDPIMrkRoot::EDPIMrkRoot() : EDProjectItem() { update(true); } EDPIMrkRoot::~EDPIMrkRoot() { } EItemType EDPIMrkRoot::getType() const { return PIT_MRK_ROOT; } void EDPIMrkRoot::update( bool bUpdateChildren) { setName("Markup"); } void EDPIMrkRoot::updMarkup(const ExpertDiscoveryData& d){ takeChildren(); const MetaInfoBase& rDesc = d.getDescriptionBase(); int nFamilyNum = rDesc.getFamilyNumber(); for (int i=0; igetDescriptionBase()); return NULL; } /////////////////////////////////////////////////////////////////////////////////////// EDPIMrkFamily::EDPIMrkFamily(const Family& rFamily) : EDProjectItem() , m_rFamily (rFamily) { update(true); } EDPIMrkFamily::~EDPIMrkFamily() { } EItemType EDPIMrkFamily::getType() const { return PIT_MRK_FAMILY; } void EDPIMrkFamily::update(bool bupdateChildren) { QString strName = m_rFamily.getName().c_str(); setName( strName ); if (bupdateChildren) { takeChildren(); int nSigNum = m_rFamily.getSignalNumber(); for (int i=0; i( new EDPIMrkItem(strName, m_rFamily.getMetaInfo(i)) )); } } bool EDPIMrkFamily::isConnectedTo(void *pData) const { return (pData == (void *) &m_rFamily); } /////////////////////////////////////////////////////////////////////////////////////// EDPIMrkItem::EDPIMrkItem(QString strFamilyName, const MetaInfo& rMetaInfo) : EDPICSNode(NULL) , m_rMetaInfo(rMetaInfo) { TS* pTS = new TS; pTS->setFromMarking(true); pTS->setName(m_rMetaInfo.getName()); pTS->setFamily(strFamilyName.toStdString()); pOp = pTS; update(true); setName(m_rMetaInfo.getName().c_str()); } EDPIMrkItem::~EDPIMrkItem() { delete pOp; } EItemType EDPIMrkItem::getType() const { return PIT_MRK_ITEM; } void EDPIMrkItem::update(bool bupdateChildren) { setName( m_rMetaInfo.getName().c_str() ); EDPICSNode::update(true); } bool EDPIMrkItem::isConnectedTo(void *pData) const { return (pData == (void *) &m_rMetaInfo); } } //namespace ugene-1.9.8/src/plugins/expert_discovery/src/ExpertDiscoveryView.cpp0000644000175000017500000010015611651544323024454 0ustar ilyailya#include "ExpertDiscoveryView.h" #include "ExpertDiscoveryTask.h" #include "ExpertDiscoveryPosNegDialog.h" #include "ExpertDiscoveryControlDialog.h" #include "ExpertDiscoveryPosNegMrkDialog.h" #include "ExpertDiscoveryControlMrkDialog.h" #include "ExpertDiscoveryExtSigWiz.h" #include "ExpertDiscoveryPlugin.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include namespace U2{ using namespace DDisc; ExpertDiscoveryView::ExpertDiscoveryView(GObjectViewFactoryId factoryId, const QString& viewName, QObject* p) :GObjectView(factoryId, viewName, p) ,wizzard(false) ,splitter(NULL) ,currentAdv(NULL) ,edAutoAnnotationsUpdater(NULL) ,curPS(NULL) ,updatePS(false) ,curEDsequence(NULL) ,posUDoc(NULL) ,negUDoc(NULL) ,conUDoc(NULL) ,extrTask(NULL) ,updatesCount(0){ createActions(); edAutoAnnotationsUpdater = new ExpertDiscoverySignalsAutoAnnotationUpdater; AppContext::getAutoAnnotationsSupport()->registerAutoAnnotationsUpdater(edAutoAnnotationsUpdater); edAutoAnnotationsUpdater->setEDData(&d); edAutoAnnotationsUpdater->setEDProcSignals(curPS); edAutoAnnotationsUpdater->setEDMutex(&mutex); } ExpertDiscoveryView::~ExpertDiscoveryView(){ clearSequencesView(); delete posUDoc; delete negUDoc; delete conUDoc; delete curEDsequence; AppContext::getAutoAnnotationsSupport()->unregisterAutoAnnotationsUpdater(edAutoAnnotationsUpdater); //delete splitter; } QWidget* ExpertDiscoveryView::createWidget(){ splitter = new QSplitter(Qt::Horizontal); signalsWidget = new EDProjectTree(splitter, d); signalsWidget->setHeaderLabel("Items"); propWidget = new EDPropertiesTable(splitter); QSplitter* verticalSplitter = new QSplitter(Qt::Vertical); verticalSplitter->addWidget(signalsWidget); verticalSplitter->addWidget(propWidget); splitter->addWidget(verticalSplitter); QHBoxLayout* layout = new QHBoxLayout(); layout->addWidget(splitter); layout->setSpacing(0); layout->setMargin(0); layout->setContentsMargins(0, 0, 0, 0); //setLayout(layout); //connect(signalsWidget, SIGNAL(itemClicked ( QTreeWidgetItem * , int )), SLOT(sl_treeItemSelChanged(QTreeWidgetItem *))); connect(signalsWidget, SIGNAL(itemActivated ( QTreeWidgetItem * , int )), SLOT(sl_treeItemSelChanged(QTreeWidgetItem *))); connect(signalsWidget, SIGNAL(currentItemChanged ( QTreeWidgetItem * , QTreeWidgetItem * ) ), SLOT(sl_treeItemSelChanged(QTreeWidgetItem *))); connect(signalsWidget, SIGNAL(si_loadMarkup(bool ) ), SLOT(sl_treeWidgetMarkup(bool ))); connect(signalsWidget, SIGNAL(si_showSequence() ), SLOT(sl_showSequence())); connect(signalsWidget, SIGNAL(si_addToShown() ), SLOT(sl_addToShown())); connect(signalsWidget, SIGNAL(si_clearDisplayed() ), SLOT(sl_clearDisplayed())); connect(signalsWidget, SIGNAL(si_showFirstSequences() ), SLOT(sl_showFirstSequences())); connect(signalsWidget, SIGNAL(si_changeProp(QTreeWidgetItem*)), propWidget, SLOT(sl_treeSelChanged(QTreeWidgetItem*))); connect(propWidget, SIGNAL(si_propChanged(EDProjectItem*, const EDPIProperty*, QString )), signalsWidget, SLOT(sl_propChanged(EDProjectItem* , const EDPIProperty* , QString ))); GObjectViewFactory* factory = AppContext::getObjectViewFactoryRegistry()->getFactoryById("ED"); ExpertDiscoveryViewFactory* edFactory = dynamic_cast(factory); assert(edFactory); connect(edFactory, SIGNAL(si_newTaskCreation(Task* )), SLOT(sl_newViewTask(Task*))); return splitter; } void ExpertDiscoveryView::insertSeqView( QWidget* view ){ splitter->addWidget(view); } void ExpertDiscoveryView::createActions(){ newDoc = new QAction(tr("New Expert Discovery Document"), this); newDoc->setIcon(QIcon(":expert_discovery/images/filenew.png")); connect(newDoc, SIGNAL(triggered()), SLOT(sl_newDoc())); openDoc = new QAction(tr("Open Expert Discovery Document"), this); openDoc->setIcon(QIcon(":expert_discovery/images/fileopen.png")); connect(openDoc, SIGNAL(triggered()), SLOT(sl_openDoc())); saveDoc = new QAction(tr("Save Expert Discovery Document"), this); saveDoc->setIcon(QIcon(":expert_discovery/images/filesave.png")); connect(saveDoc, SIGNAL(triggered()), SLOT(sl_saveDoc())); setUpRecBound = new QAction(tr("Set Recognition Bound"), this); setUpRecBound->setIcon(QIcon(":expert_discovery/images/setRecBound.png")); connect(setUpRecBound, SIGNAL(triggered()), SLOT(sl_setRecBound())); optimizeRecBound = new QAction(tr("Optimize Recognition Bound"), this); optimizeRecBound->setIcon(QIcon(":expert_discovery/images/optRecBound.png")); connect(optimizeRecBound, SIGNAL(triggered()), SLOT(sl_optimizeRecBound())); loadControlSeqAction = new QAction(tr("Load control sequences"), this); loadControlSeqAction->setIcon(QIcon(":expert_discovery/images/loadControlsSeq.png")); connect(loadControlSeqAction, SIGNAL(triggered()), SLOT(sl_showExpertDiscoveryControlDialog())); extractSignalsAction = new QAction(tr("Extract signals"), this); extractSignalsAction->setIcon(QIcon(":expert_discovery/images/extractSignals2.png")); connect(extractSignalsAction, SIGNAL(triggered()), SLOT(sl_extractSignals())); loadMarkupAction = new QAction(tr("Load markup"), this); loadMarkupAction->setIcon(QIcon(":expert_discovery/images/loadMarkup.png")); connect(loadMarkupAction, SIGNAL(triggered()), SLOT(sl_showExpertDiscoveryPosNegMrkDialog())); loadControlMarkupAction = new QAction(tr("Load control sequences markup"), this); loadControlMarkupAction->setIcon(QIcon(":expert_discovery/images/loadControlsSeqAnnot.png")); connect(loadControlMarkupAction, SIGNAL(triggered()), SLOT(sl_showExpertDiscoveryControlMrkDialog())); generateFullReportAction = new QAction(tr("Generate recognition report"), this); generateFullReportAction->setIcon(QIcon(":expert_discovery/images/genRep.png")); connect(generateFullReportAction, SIGNAL(triggered()), SLOT(sl_generateFullReport())); setUpRecBound->setEnabled(false); optimizeRecBound->setEnabled(false); loadControlSeqAction->setEnabled(false); extractSignalsAction->setEnabled(false); loadMarkupAction->setEnabled(false); loadControlMarkupAction->setEnabled(false); generateFullReportAction->setEnabled(false); } void ExpertDiscoveryView::sl_newDoc(){ wizzard = true; if (askForSave()){ sl_saveDoc(); } setUpRecBound->setEnabled(false); optimizeRecBound->setEnabled(false); loadControlSeqAction->setEnabled(false); extractSignalsAction->setEnabled(false); loadMarkupAction->setEnabled(false); loadControlMarkupAction->setEnabled(false); generateFullReportAction->setEnabled(false); d.setRecBound(0); d.cleanup(); propWidget->clearAll(); clearSequencesView(); edObjects.clear(); curPS = NULL; signalsWidget->clearTree(); signalsWidget->updateTree(ED_UPDATE_ALL); d.setModifed(false); sl_showExpertDiscoveryPosNegDialog(); } void ExpertDiscoveryView::sl_openDoc(){ LastOpenDirHelper lod("ExpertDiscovery"); lod.url = QFileDialog::getOpenFileName(NULL, tr("Load ExpertDiscovery document"), lod.dir, tr("ExpertDiscovery files (*.exd)")); if (lod.url.length() <= 0) { return; } d.cleanup(); propWidget->clearAll(); clearSequencesView(); edObjects.clear(); curPS = NULL; signalsWidget->clearTree(); signalsWidget->updateTree(ED_UPDATE_ALL); Task* t = new ExpertDiscoveryLoadDocumentTask(d, lod.url); connect( t, SIGNAL( si_stateChanged() ), SLOT( sl_updateAll() ) ); AppContext::getTaskScheduler()->registerTopLevelTask(t); } void ExpertDiscoveryView::sl_saveDoc(){ LastOpenDirHelper lod("ExpertDiscovery"); lod.url = QFileDialog::getSaveFileName(NULL, tr("Save ExpertDiscovery document"), lod.dir, tr("ExpertDiscovery files (*.exd)")); if (lod.url.length() <= 0) { return; } Task* t = new ExpertDiscoverySaveDocumentTask(d, lod.url); AppContext::getTaskScheduler()->registerTopLevelTask(t); } bool ExpertDiscoveryView::askForSave(){ if(!d.isModified()){ return false; } QMessageBox mb(QMessageBox::Question, tr("Save ExpertDiscovery document"), tr("Do you want to save current ExpertDiscovery document?"), QMessageBox::Yes|QMessageBox::No); if(mb.exec()==QMessageBox::Yes) return true; else return false; } void ExpertDiscoveryView::sl_showExpertDiscoveryPosNegDialog(){ Task *tasks = new Task("Loading positive and negative sequences", TaskFlag_NoRun); ExpertDiscoveryPosNegDialog d(QApplication::activeWindow()); if (d.exec()) { if (!AppContext::getProject()) { tasks->addSubTask( AppContext::getProjectLoader()->createNewProjectTask() ); } ExpertDiscoveryLoadPosNegTask *t = new ExpertDiscoveryLoadPosNegTask(d.getFirstFileName(), d.getSecondFileName(), d.isGenerateNegative()); connect( t, SIGNAL( si_stateChanged() ), SLOT( sl_loadPosNegTaskStateChanged() ) ); tasks->addSubTask(t); } AppContext::getTaskScheduler()->registerTopLevelTask(tasks); } void ExpertDiscoveryView::sl_loadPosNegTaskStateChanged(){ ExpertDiscoveryLoadPosNegTask *loadTask = qobject_cast(sender()); if (!loadTask || !loadTask->isFinished()) { return; } if (loadTask->getStateInfo().hasError()) { ExpertDiscoveryErrors::fileOpenError(); return; } QList docs = loadTask->getDocuments(); Q_ASSERT(!docs.isEmpty()); Q_ASSERT(docs.count() > 1); posUDoc = docs.first(); d.setPosBase(posUDoc->getObjects()); foreach(GObject* gobj, posUDoc->getObjects()){ //addObject(gobj); edObjects.push_back(gobj); } if(posUDoc->isStateLocked()){ posUDoc = NULL; } negUDoc = docs.at(1); d.setNegBase(negUDoc->getObjects()); foreach(GObject* gobj, negUDoc->getObjects()){ //addObject(gobj); edObjects.push_back(gobj); } if(negUDoc->isStateLocked()){ negUDoc = NULL; } signalsWidget->updateSequenceBase(PIT_POSSEQUENCEBASE); signalsWidget->updateSequenceBase(PIT_NEGSEQUENCEBASE); setUpRecBound->setEnabled(true); optimizeRecBound->setEnabled(true); loadControlSeqAction->setEnabled(true); loadMarkupAction->setEnabled(true); generateFullReportAction->setEnabled(true); if(!loadTask->isGenerateNeg()){ //markup sl_showExpertDiscoveryPosNegMrkDialog(); } wizzard = false; } void ExpertDiscoveryView::sl_showExpertDiscoveryPosNegMrkDialog(){ Task *tasks = new Task("Loading positive and negative sequences markups", TaskFlag_NoRun); ExpertDiscoveryPosNegMrkDialog dialog(QApplication::activeWindow()); if (dialog.exec()) { ExpertDiscoveryLoadPosNegMrkTask *t = new ExpertDiscoveryLoadPosNegMrkTask(dialog.getFirstFileName(), dialog.getSecondFileName(), dialog.getThirdFileName(), dialog.isGenerateDescr(), dialog.isAppendToCurrentMarkup(), d ); connect( t, SIGNAL( si_stateChanged() ), SLOT( sl_loadPosNegMrkTaskStateChanged() ) ); tasks->addSubTask(t); } AppContext::getTaskScheduler()->registerTopLevelTask(tasks); } void ExpertDiscoveryView::sl_loadPosNegMrkTaskStateChanged(){ ExpertDiscoveryLoadPosNegMrkTask *loadTask = qobject_cast(sender()); if (!loadTask || !loadTask->isFinished()) { return; } if (loadTask->getStateInfo().hasError()) { ExpertDiscoveryErrors::markupLoadError(); return; } signalsWidget->updateMarkup(); extractSignalsAction->setEnabled(true); } void ExpertDiscoveryView::sl_showExpertDiscoveryControlMrkDialog(){ Task *tasks = new Task("Loading control sequences markups", TaskFlag_NoRun); ExpertDiscoveryControlMrkDialog dialog(QApplication::activeWindow()); if (dialog.exec()) { ExpertDiscoveryLoadControlMrkTask *t = new ExpertDiscoveryLoadControlMrkTask(dialog.getFirstFileName(), d ); connect( t, SIGNAL( si_stateChanged() ), SLOT( sl_loadControlMrkTaskStateChanged() ) ); tasks->addSubTask(t); } AppContext::getTaskScheduler()->registerTopLevelTask(tasks); } void ExpertDiscoveryView::sl_loadControlMrkTaskStateChanged(){ ExpertDiscoveryLoadControlMrkTask *loadTask = qobject_cast(sender()); if (!loadTask || !loadTask->isFinished()) { return; } if (loadTask->getStateInfo().hasError()) { ExpertDiscoveryErrors::markupLoadError(); return; } } void ExpertDiscoveryView::initADVView(AnnotatedDNAView* adv){ if(!adv){ return; } clearSequencesView(); foreach(GObject* gobj, adv->getObjects()){ GHints* edHints = new GHintsDefaultImpl(); edHints->set("EDHint", QVariant(true)); gobj->setGHints(edHints); addObject(gobj); } adv->setClosingInterface(closeInterface); currentAdv = adv; splitter->addWidget(adv->getWidget()); // adv->addAutoAnnotationsUpdated(edAutoAnnotationsUpdater); QList curSequenceWidgets = currentAdv->getSequenceWidgets(); foreach(ADVSequenceWidget* seqWidget, curSequenceWidgets){ ADVSingleSequenceWidget* singleSeqWidget = dynamic_cast(seqWidget); if(singleSeqWidget){ DetView* dv = singleSeqWidget->getDetView(); if(dv){ dv->setShowComplement(false); dv->setShowTranslation(false); } } } foreach(ADVSequenceObjectContext* sctx, currentAdv->getSequenceContexts()){ AutoAnnotationsADVAction* aaAction = AutoAnnotationUtils::findAutoAnnotationADVAction( sctx ); assert(aaAction); AutoAnnotationObject* aaobj = aaAction->getAAObj(); assert(aaobj); connect(aaobj, SIGNAL(si_updateStarted()), SLOT(sl_autoAnnotationUpdateStarted())); connect(aaobj, SIGNAL(si_updateFinshed()), SLOT(sl_autoAnnotationUpdateFinished())); } connect(adv, SIGNAL( si_focusChanged(ADVSequenceWidget*, ADVSequenceWidget*) ), SLOT( sl_sequenceItemSelChanged(ADVSequenceWidget*) )); createEDSequence(); } void ExpertDiscoveryView::sl_testView(){ Task *loadTask = qobject_cast(sender()); if (!loadTask || !loadTask->isFinished()) { return; } if (loadTask->getStateInfo().hasError()) { return; } ExpertDiscoveryCreateViewTask* viewTask = dynamic_cast(loadTask); if(!viewTask){ return; } AnnotatedDNAView* adv = viewTask->getADV(); initADVView(adv); } void ExpertDiscoveryView::sl_newViewTask(Task* t){ ExpertDiscoveryCreateViewTask* edTask = dynamic_cast(t); if(!edTask){ return; } connect(edTask,SIGNAL( si_stateChanged() ), SLOT( sl_testView() ) ); } void ExpertDiscoveryView::sl_updateAll(){ ExpertDiscoveryLoadDocumentTask *loadTask = qobject_cast(sender()); if (!loadTask || !loadTask->isFinished()) { return; } if (loadTask->getStateInfo().hasError()) { return; } signalsWidget->updateTree(ED_CURRENT_ITEM_CHANGED,NULL); signalsWidget->updateSequenceBase(PIT_POSSEQUENCEBASE); signalsWidget->updateSequenceBase(PIT_NEGSEQUENCEBASE); signalsWidget->updateSequenceBase(PIT_CONTROLSEQUENCEBASE); signalsWidget->updateTree(ED_UPDATE_ALL); bool enableActions = d.getPosSeqBase().getSize() != 0 || d.getNegSeqBase().getSize() != 0; setUpRecBound->setEnabled(enableActions); optimizeRecBound->setEnabled(enableActions); loadControlSeqAction->setEnabled(enableActions); extractSignalsAction->setEnabled(enableActions); loadMarkupAction->setEnabled(enableActions); loadControlMarkupAction->setEnabled(d.getConSeqBase().getSize() != 0); generateFullReportAction->setEnabled(enableActions); } void ExpertDiscoveryView::sl_autoAnnotationUpdateStarted(){ updatesCount++; if(updatesCount > 0){ signalsWidget->setEnabled(false); } } void ExpertDiscoveryView::sl_autoAnnotationUpdateFinished(){ updatesCount--; if(updatesCount <= 0){ signalsWidget->setEnabled(true); signalsWidget->setFocus(); updatesCount = 0; } } void ExpertDiscoveryView::sl_showExpertDiscoveryControlDialog(){ Task *tasks = new Task("Loading control sequences", TaskFlag_NoRun); ExpertDiscoveryControlDialog d(QApplication::activeWindow()); if (d.exec()) { Q_ASSERT(AppContext::getProject()); ExpertDiscoveryLoadControlTask *t = new ExpertDiscoveryLoadControlTask(d.getFirstFileName()); connect( t, SIGNAL( si_stateChanged() ), SLOT( sl_loadControlTaskStateChanged() ) ); tasks->addSubTask(t); } AppContext::getTaskScheduler()->registerTopLevelTask(tasks); } void ExpertDiscoveryView::sl_loadControlTaskStateChanged(){ ExpertDiscoveryLoadControlTask *loadTask = qobject_cast(sender()); if (!loadTask || !loadTask->isFinished()) { return; } if (loadTask->getStateInfo().hasError()) { ExpertDiscoveryErrors::fileOpenError(); return; } QList docs = loadTask->getDocuments(); Q_ASSERT(!docs.isEmpty()); conUDoc = docs.first(); propWidget->clearAll(); if(d.getConSeqBase().getSize() != 0){ clearSequencesView(); QList selSeqList = d.getSelectetSequencesList(); d.clearSelectedSequencesList(); foreach(EDPISequence* curS, selSeqList){ signalsWidget->updateItem(curS); } foreach(GObject* gobj, edObjects){ SequenceType seqType = d.getSequenceTypeByName(gobj->getGObjectName()); if(seqType == CONTROL_SEQUENCE){ edObjects.removeOne(gobj); } } } curPS = NULL; d.clearContrBase(); d.clearContrAnnot(); d.setConBase(conUDoc->getObjects()); foreach(GObject* gobj, conUDoc->getObjects()){ edObjects.push_back(gobj); } if(conUDoc->isStateLocked()){ conUDoc = NULL; } if (d.isLettersMarkedUp() && d.getConSeqBase().getSize() != 0) d.markupLetters(d.getConSeqBase(), d.getConMarkBase()); signalsWidget->updateSequenceBase(PIT_CONTROLSEQUENCEBASE); loadControlMarkupAction->setEnabled(true); } void ExpertDiscoveryView::sl_newSignalReady(DDisc::Signal* signal, CSFolder* folder){ Signal* ps = signal; CSFolder *pFolder = folder; ps->setName(pFolder->makeUniqueSignalName().toStdString()); pFolder->addSignal(ps); EDProjectItem* pParent = signalsWidget->findEDItem(pFolder); EDPICS* pItem = new EDPICS(ps); signalsWidget->addSubitem(pItem, pParent); signalsWidget->updateSorting(); } void ExpertDiscoveryView::sl_optimizeRecBound(){ d.optimizeRecognizationBound(); propWidget->updateCurrentProperties(); } void ExpertDiscoveryView::sl_setRecBound(){ d.setRecBound(); propWidget->updateCurrentProperties(); } void ExpertDiscoveryView::sl_extractSignals(){ Task *tasks = new Task("Extracting signals", TaskFlag_NoRun); ExpertDiscoverySignalExtractorTask *t = new ExpertDiscoverySignalExtractorTask(&d); extrTask = t; connect(t, SIGNAL(si_newSignalReady(DDisc::Signal* , CSFolder* )), SLOT(sl_newSignalReady(DDisc::Signal* , CSFolder* ))); tasks->addSubTask(t); AppContext::getTaskScheduler()->registerTopLevelTask(tasks); } void ExpertDiscoveryView::sl_treeItemSelChanged(QTreeWidgetItem* tItem){ if(!tItem){ propWidget->sl_treeSelChanged(NULL); return; } EDProjectItem* pItem = dynamic_cast(tItem); if(!pItem){ propWidget->sl_treeSelChanged(NULL); curPS = NULL; return; } switch(pItem->getType()){ case PIT_CS: case PIT_CSN_WORD: case PIT_CSN_INTERVAL: case PIT_CSN_REPETITION: case PIT_CSN_DISTANCE: case PIT_CSN_MRK_ITEM: case PIT_MRK_ITEM:{ EDPICSNode* pPICSN = dynamic_cast(pItem); if (curPS == pPICSN->getProcessedSignal(d)) { updatePS = false; } else { //mutex.lock(); curPS = pPICSN->getProcessedSignal(d); updatePS = true; //mutex.unlock(); } if (curPS == NULL) { updateAnnotations(); updatePS = false; propWidget->sl_treeSelChanged(pItem); return; } if(updatePS){ updateAnnotations(); updatePS = false; } break; } default: //mutex.lock(); curPS = NULL; //mutex.unlock(); } propWidget->sl_treeSelChanged(tItem); } void ExpertDiscoveryView::updateAnnotations(){ if(!currentAdv || !signalsWidget->isEnabled() || signalsWidget->isUpdatingItem()){ return; } edAutoAnnotationsUpdater->setEDProcSignals(curPS); //AppContext::getAutoAnnotationsSupport()->registerAutoAnnotationsUpdater(edAutoAnnotationsUpdater); foreach(ADVSequenceObjectContext* sctx, currentAdv->getSequenceContexts()){ AutoAnnotationUtils::triggerAutoAnnotationsUpdate(sctx, "ExpertDiscover Signals"); } //AppContext::getAutoAnnotationsSupport()->unregisterAutoAnnotationsUpdater(edAutoAnnotationsUpdater); } void ExpertDiscoveryView::createEDSequence(){ if(!currentAdv){ return; } ADVSequenceObjectContext* seqInfocus = currentAdv->getSequenceInFocus(); if(!seqInfocus){ return; } DNASequenceObject* dnaSeqObject = seqInfocus->getSequenceObject(); const QString& seqName = dnaSeqObject->getSequenceName(); SequenceType seqType = d.getSequenceTypeByName(seqName); if(seqType != UNKNOWN_SEQUENCE && curEDsequence !=NULL){ delete curEDsequence; curEDsequence = NULL; } switch(seqType){ case POSITIVE_SEQUENCE: curEDsequence = new EDPISequence(d.getPosSeqBase(), d.getPosSeqBase().getObjNo(seqName.toStdString().c_str()), d); break; case NEGATIVE_SEQUENCE: curEDsequence = new EDPISequence(d.getNegSeqBase(), d.getNegSeqBase().getObjNo(seqName.toStdString().c_str()), d); break; case CONTROL_SEQUENCE: curEDsequence = new EDPIControlSequence(d.getConSeqBase(), d.getConSeqBase().getObjNo(seqName.toStdString().c_str()), d); break; } updateEDSequenceProperties(); } void ExpertDiscoveryView::updateEDSequenceProperties(){ if(!curEDsequence){ return; } propWidget->sl_treeSelChanged(curEDsequence); } DNASequenceObject* ExpertDiscoveryView::getSeqObjectFromEDSequence(EDPISequence* sItem){ DNASequenceObject* dnaSeqObj = NULL; bool seqFound = false; foreach(GObject* obj, edObjects){ dnaSeqObj = dynamic_cast(obj); if(dnaSeqObj){ if(dnaSeqObj->getSequenceName().compare(sItem->getSequenceName(), Qt::CaseInsensitive) == 0){ seqFound = true; return dnaSeqObj; } } } if(!seqFound){ //add to edObjects QByteArray seqarray = QByteArray(sItem->getSequenceCode().toAscii()); DNASequence dnaseq (sItem->getSequenceName(), seqarray); dnaseq.alphabet = AppContext::getDNAAlphabetRegistry()->findById(BaseDNAAlphabetIds::NUCL_DNA_EXTENDED()); DNASequenceObject* danseqob = new DNASequenceObject(sItem->getSequenceName(), dnaseq); edObjects.append(danseqob); SequenceType sType = d.getSequenceTypeByName(sItem->getSequenceName()); switch(sType){ case POSITIVE_SEQUENCE: if(!posUDoc){ posUDoc = createUDocument(sType); posUDoc->setName("Positive"); } posUDoc->addObject(danseqob); break; case NEGATIVE_SEQUENCE: if(!negUDoc){ negUDoc = createUDocument(sType); negUDoc->setName("Negative"); } negUDoc->addObject(danseqob); break; case CONTROL_SEQUENCE: if(!conUDoc){ conUDoc = createUDocument(sType); conUDoc->setName("Control"); } conUDoc->addObject(danseqob); break; default: return NULL; } return danseqob; } return NULL; } Document* ExpertDiscoveryView::createUDocument(SequenceType sType){ QString baseName = AppContext::getAppSettings()->getUserAppsSettings()->getTemporaryDirPath()+"/ED"; switch(sType){ case POSITIVE_SEQUENCE: baseName.append("_Positive"); break; case NEGATIVE_SEQUENCE: baseName.append("_Negative"); break; case CONTROL_SEQUENCE: baseName.append("_Control"); break; } QString suffix = QString(".fa"); baseName.append(suffix); GUrl URL(baseName); IOAdapterFactory* iof = AppContext::getIOAdapterRegistry()->getIOAdapterFactoryById(BaseIOAdapters::url2io(URL)); DocumentFormat* dformat = AppContext::getDocumentFormatRegistry()->getFormatById(BaseDocumentFormats::PLAIN_FASTA); Document* doc = new Document(dformat,iof,URL); doc->setLoaded(true); return doc; } void ExpertDiscoveryView::sl_sequenceItemSelChanged(ADVSequenceWidget* seqWidget){ createEDSequence(); } void ExpertDiscoveryView::sl_treeWidgetMarkup(bool isLetters){ if(isLetters){ extractSignalsAction->setEnabled(true); }else{ sl_showExpertDiscoveryPosNegMrkDialog(); } } void ExpertDiscoveryView::sl_generateFullReport(){ if(d.getSelectedSignalsContainer().GetSelectedSignals().size() == 0){ QMessageBox mb(QMessageBox::Critical, tr("Error"), tr("No signals are selected to generate report")); mb.exec(); }else{ d.generateRecognitionReportFull(); } } void ExpertDiscoveryView::sl_showSequence(){ EDPISequence* sItem = dynamic_cast(signalsWidget->currentItem()); if(!sItem){ return; } DNASequenceObject* dnaSeqObj = getSeqObjectFromEDSequence(sItem); QList selSeqList = d.getSelectetSequencesList(); d.clearSelectedSequencesList(); foreach(EDPISequence* curS, selSeqList){ signalsWidget->updateItem(curS); } d.addSequenceToSelected(sItem); QList listdna; listdna.append(dynamic_cast(dnaSeqObj)); AnnotatedDNAView* danadv = new AnnotatedDNAView(dnaSeqObj->getSequenceName(),listdna); initADVView(danadv); signalsWidget->updateItem(sItem); } #define MAX_SEQUENCES_COUNT_ON_WIDGET 50 void ExpertDiscoveryView::sl_addToShown(){ EDPISequence* sItem = dynamic_cast(signalsWidget->currentItem()); if(!sItem){ return; } DNASequenceObject* dnaSeqObj = getSeqObjectFromEDSequence(sItem); if(currentAdv){ if(currentAdv->getSequenceContexts().size() >= MAX_SEQUENCES_COUNT_ON_WIDGET){ return; } } //currentAdv->addObject(dnaSeqObj); //auto annotations bug d.addSequenceToSelected(sItem); QList listdna; listdna.append(dynamic_cast(dnaSeqObj)); if(currentAdv){ foreach(ADVSequenceObjectContext* curSoc, currentAdv->getSequenceContexts()){ listdna.append(curSoc->getSequenceObject()); } } AnnotatedDNAView* danadv = new AnnotatedDNAView(dnaSeqObj->getSequenceName(),listdna); initADVView(danadv); signalsWidget->updateItem(sItem); } #define MAX_SEQUENCES_COUNT_TO_ONCE_DISPLAY 25 void ExpertDiscoveryView::sl_showFirstSequences(){ EDPISequenceBase* sItem = dynamic_cast(signalsWidget->currentItem()); if(!sItem){ return; } clearSequencesView(); QList selSeqList = d.getSelectetSequencesList(); d.clearSelectedSequencesList(); foreach(EDPISequence* curS, selSeqList){ signalsWidget->updateItem(curS); } const SequenceBase& seqBase = sItem->getSequenceBase(); int baseSize = seqBase.getSize(); int widgetItemsCount = baseSize < MAX_SEQUENCES_COUNT_TO_ONCE_DISPLAY ? baseSize : MAX_SEQUENCES_COUNT_TO_ONCE_DISPLAY; QList listdna; for(int i = 0; i < widgetItemsCount; i++){ QTreeWidgetItem* tItem = sItem->child(i); EDPISequence* pItemSequence = dynamic_cast(tItem); if(!pItemSequence){ continue; } DNASequenceObject* dnaSeqObj = getSeqObjectFromEDSequence(pItemSequence); d.addSequenceToSelected(pItemSequence); signalsWidget->updateItem(pItemSequence); listdna.append(dynamic_cast(dnaSeqObj)); } AnnotatedDNAView* danadv = new AnnotatedDNAView("Base",listdna); initADVView(danadv); } void ExpertDiscoveryView::sl_clearDisplayed(){ clearSequencesView(); QList selSeqList = d.getSelectetSequencesList(); d.clearSelectedSequencesList(); foreach(EDPISequence* curS, selSeqList){ signalsWidget->updateItem(curS); } } void ExpertDiscoveryView::clearSequencesView() { if(currentAdv){ foreach(ADVSequenceObjectContext* sctx, currentAdv->getSequenceContexts()){ AutoAnnotationsADVAction* aaAction = AutoAnnotationUtils::findAutoAnnotationADVAction( sctx ); assert(aaAction); AutoAnnotationObject* aaobj = aaAction->getAAObj(); assert(aaobj); disconnect(aaobj, SIGNAL(si_updateStarted()),this, SLOT(sl_autoAnnotationUpdateStarted())); disconnect(aaobj, SIGNAL(si_updateFinshed()), this, SLOT(sl_autoAnnotationUpdateFinished())); } disconnect(currentAdv, SIGNAL( si_focusChanged(ADVSequenceWidget*, ADVSequenceWidget*) ), this, SLOT( sl_sequenceItemSelChanged(ADVSequenceWidget*) )); foreach(GObject* obj, objects){ removeObject(obj); } delete currentAdv->getWidget(); delete currentAdv; currentAdv = NULL; } } ExpertDiscoveryViewWindow::ExpertDiscoveryViewWindow(GObjectView* view, const QString& viewName, bool persistent) :GObjectViewWindow(view, viewName, persistent){ } void ExpertDiscoveryViewWindow::setupMDIToolbar(QToolBar* tb){ ExpertDiscoveryView* curEdView = dynamic_cast(view); assert(curEdView); tb->addAction(curEdView->getNewDocAction()); tb->addAction(curEdView->getOpenDocAction()); tb->addAction(curEdView->getSaveDocAction()); tb->addSeparator(); tb->addAction(curEdView->getLoadMarkupAction()); tb->addSeparator(); tb->addAction(curEdView->getLoadControlSeqAction()); tb->addAction(curEdView->getLoadControlMarkupAction()); tb->addSeparator(); tb->addAction(curEdView->getExtractSignalsAction()); tb->addSeparator(); tb->addAction(curEdView->getSetUpRecBoundAction()); tb->addAction(curEdView->getOptimizeRecBoundAction()); tb->addSeparator(); tb->addAction(curEdView->getGenerateFullReportAction()); } bool ExpertDiscoveryViewWindow::onCloseEvent(){ ExpertDiscoveryView* curEdView = dynamic_cast(view); assert(curEdView); Task* t = curEdView->getExtractTask(); if(t && (t->isRunning())){ QMessageBox mb(QMessageBox::Critical, tr("Closing error"), tr("There are unfinished extracting tasks. Cancel them before closing")); mb.exec(); return false; } if(curEdView->askForSave()){ curEdView->getSaveDocAction()->trigger(); return false; } return true; } }//namespace ugene-1.9.8/src/plugins/expert_discovery/src/ExpertDiscoveryPosNegDialog.cpp0000644000175000017500000000472211651544323026057 0ustar ilyailya#include "ExpertDiscoveryPosNegDialog.h" #include #include #include #include namespace U2 { ExpertDiscoveryPosNegDialog::ExpertDiscoveryPosNegDialog(QWidget *parent) : QDialog(parent), generateNeg(false){ setupUi(this); connect(openFirstButton, SIGNAL(clicked()), SLOT(sl_openFirstFile())); connect(openSecondButton, SIGNAL(clicked()), SLOT(sl_openSecondFile())); connect(oneSequenceCheckBox, SIGNAL(clicked()), SLOT(sl_oneSequence())); filter = DialogUtils::prepareDocumentsFileFilterByObjType(GObjectTypes::SEQUENCE, true); } void ExpertDiscoveryPosNegDialog::accept(){ Q_ASSERT(firstFileEdit); Q_ASSERT(secondFileEdit); firstFileName = firstFileEdit->text(); secondFileName = secondFileEdit->text(); if (oneSequenceCheckBox->isChecked()) { secondFileName = firstFileName; } if (!firstFileName.isEmpty() && !secondFileName.isEmpty()) { if(secondFileName == firstFileName && !generateNeg){ QMessageBox mb(QMessageBox::Critical, tr("Select files"), tr("Positive and negative sequences can't be in the one file. Select another file for one of them")); mb.exec(); }else{ QDialog::accept(); } }else { QMessageBox mb(QMessageBox::Critical, tr("Select files"), tr("Select files for ExpertDiscovery")); mb.exec(); } } void ExpertDiscoveryPosNegDialog::sl_oneSequence() { secondFileEdit->setDisabled(oneSequenceCheckBox->isChecked()); openSecondButton->setDisabled(oneSequenceCheckBox->isChecked()); generateNeg = oneSequenceCheckBox->isChecked(); } void ExpertDiscoveryPosNegDialog::sl_openFirstFile(){ LastOpenDirHelper lod("ExpertDiscovery positive sequences file"); lod.url = QFileDialog::getOpenFileName(NULL, tr("Open positive sequences file"), lod.dir, filter); Q_ASSERT(firstFileEdit); if (!lod.url.isEmpty()) { firstFileEdit->setText(lod.url); } } void ExpertDiscoveryPosNegDialog::sl_openSecondFile() { LastOpenDirHelper lod("ExpertDiscovery negative sequences file"); if (lod.dir.isEmpty()) { LastOpenDirHelper lodFirst("Open negative sequences file"); lod.dir = lodFirst.dir; } lod.url = QFileDialog::getOpenFileName(NULL, tr("Open second file"), lod.dir, filter); Q_ASSERT(secondFileEdit); if (!lod.url.isEmpty()) { secondFileEdit->setText(lod.url); } } }//namespace ugene-1.9.8/src/plugins/expert_discovery/src/ExpertDiscoveryControlDialog.h0000644000175000017500000000070711651544323025750 0ustar ilyailya#pragma once #include namespace U2 { class ExpertDiscoveryControlDialog : public QDialog, public Ui_ExpertDiscoveryControlDialog{ Q_OBJECT public: ExpertDiscoveryControlDialog(QWidget *parent); virtual void accept(); QString getFirstFileName() const {return firstFileName;} protected slots: void sl_openFirstFile(); private: QString firstFileName; QString filter; }; }//namespace ugene-1.9.8/src/plugins/expert_discovery/src/ExpertDiscoveryControlDialog.cpp0000644000175000017500000000220111651544323026272 0ustar ilyailya#include "ExpertDiscoveryControlDialog.h" #include #include #include #include namespace U2 { ExpertDiscoveryControlDialog::ExpertDiscoveryControlDialog(QWidget *parent) : QDialog(parent){ setupUi(this); connect(openFirstButton, SIGNAL(clicked()), SLOT(sl_openFirstFile())); filter = DialogUtils::prepareDocumentsFileFilterByObjType(GObjectTypes::SEQUENCE, true); } void ExpertDiscoveryControlDialog::accept(){ Q_ASSERT(firstFileEdit); firstFileName = firstFileEdit->text(); if (!firstFileName.isEmpty()) { QDialog::accept(); }else { QMessageBox mb(QMessageBox::Critical, tr("Select files"), tr("Select files for ExpertDiscovery")); mb.exec(); } } void ExpertDiscoveryControlDialog::sl_openFirstFile(){ LastOpenDirHelper lod("ExpertDiscovery control sequences file"); lod.url = QFileDialog::getOpenFileName(NULL, tr("Open control sequences file"), lod.dir, filter); Q_ASSERT(firstFileEdit); if (!lod.url.isEmpty()) { firstFileEdit->setText(lod.url); } } }//namespace ugene-1.9.8/src/plugins/expert_discovery/src/ExpertDiscoveryPlugin.h0000644000175000017500000000236711651544323024452 0ustar ilyailya#ifndef _U2_EXPERT_DIS_PLUGIN_H_ #define _U2_EXPERT_DIS_PLUGIN_H_ #include #include namespace U2 { class ExpertDiscoveryPlugin : public Plugin { Q_OBJECT public: ExpertDiscoveryPlugin(); private slots: void sl_initExpertDiscoveryViewCtx(); void sl_expertDiscoveryView(); void sl_expertDiscoveryViewDelay(); private: GObjectViewWindowContext* viewCtx; bool delay; int windowId; }; class ExpertDiscoveryViewFactory : public GObjectViewFactory{ Q_OBJECT public: ExpertDiscoveryViewFactory(GObjectViewFactoryId id, const QString& name, QObject* p = NULL); virtual bool canCreateView(const MultiGSelection& multiSelection); virtual Task* createViewTask(const MultiGSelection& multiSelection, bool single = false); //virtual bool isStateInSelection(const MultiGSelection& multiSelection, const QVariantMap& stateData); //virtual Task* createViewTask(const QString& viewName, const QVariantMap& stateData); virtual bool supportsSavedStates() const {return true;} static const GObjectViewFactoryId ID; private: bool checkSelection(const MultiGSelection& multiSelection); signals: void si_newTaskCreation(Task* t); }; } //namespace #endif ugene-1.9.8/src/plugins/expert_discovery/src/ExpertDiscoveryView.h0000644000175000017500000001034711651544323024123 0ustar ilyailya#pragma once #include "ExpertDiscoveryData.h" #include "ExpertDiscoveryTreeWidgetsCtrl.h" #include "ExpertDiscoveryPropTable.h" #include #include #include #include #include #include namespace U2{ class ExpertDiscoverySignalsAutoAnnotationUpdater; class ExpertDiscoveryView : public GObjectView{ Q_OBJECT public: ExpertDiscoveryView(GObjectViewFactoryId factoryId, const QString& viewName, QObject* p=NULL); virtual ~ExpertDiscoveryView(); void insertSeqView(QWidget* view); QAction* getNewDocAction(){return newDoc;} QAction* getOpenDocAction(){return openDoc;} QAction* getSaveDocAction(){return saveDoc;} QAction* getSetUpRecBoundAction(){return setUpRecBound;} QAction* getOptimizeRecBoundAction(){return optimizeRecBound;} QAction* getLoadControlSeqAction(){return loadControlSeqAction;} QAction* getExtractSignalsAction(){return extractSignalsAction;} QAction* getLoadMarkupAction(){return loadMarkupAction;} QAction* getLoadControlMarkupAction(){return loadControlMarkupAction;} QAction* getGenerateFullReportAction(){return generateFullReportAction;} Task* getExtractTask(){return extrTask;} QList getEDObjects(){ return edObjects;} bool askForSave(); private slots: void sl_showExpertDiscoveryPosNegDialog(); void sl_loadPosNegTaskStateChanged(); void sl_showExpertDiscoveryControlDialog(); void sl_loadControlTaskStateChanged(); void sl_showExpertDiscoveryPosNegMrkDialog(); void sl_loadPosNegMrkTaskStateChanged(); void sl_showExpertDiscoveryControlMrkDialog(); void sl_loadControlMrkTaskStateChanged(); void sl_newDoc(); void clearSequencesView(); void sl_openDoc(); void sl_saveDoc(); void sl_newSignalReady(DDisc::Signal* signal, CSFolder* folder); void sl_optimizeRecBound(); void sl_setRecBound(); void sl_extractSignals(); void sl_treeItemSelChanged(QTreeWidgetItem* tItem); void sl_sequenceItemSelChanged(ADVSequenceWidget*); void sl_treeWidgetMarkup(bool isLetters); void sl_generateFullReport(); void sl_showSequence(); void sl_addToShown(); void sl_showFirstSequences(); void sl_clearDisplayed(); void sl_testView(); void sl_newViewTask(Task* t); void sl_updateAll(); void sl_autoAnnotationUpdateStarted(); void sl_autoAnnotationUpdateFinished(); //void sl_propChanged(QTreeWidgetItem* item); protected: virtual void onObjectAdded(GObject* o){ //add implementation } private: virtual QWidget* createWidget(); void createActions(); void initADVView(AnnotatedDNAView* adv); void updateAnnotations(); void createEDSequence(); void updateEDSequenceProperties(); DNASequenceObject* getSeqObjectFromEDSequence(EDPISequence* sItem); Document* createUDocument(SequenceType sType); bool wizzard; int updatesCount; QSplitter* splitter; EDProjectTree* signalsWidget; EDPropertiesTable* propWidget; AnnotatedDNAView* currentAdv; ExpertDiscoveryData d; QAction* newDoc; QAction* openDoc; QAction* saveDoc; QAction* setUpRecBound; QAction* optimizeRecBound; QAction* loadControlSeqAction; QAction* extractSignalsAction; QAction* loadMarkupAction; QAction* loadControlMarkupAction; QAction* generateFullReportAction; QList edObjects; EDPISequence* curEDsequence; Document* posUDoc; Document* negUDoc; Document* conUDoc; Task* extrTask; ExpertDiscoverySignalsAutoAnnotationUpdater* edAutoAnnotationsUpdater; const EDProcessedSignal* curPS; bool updatePS; QMutex mutex; signals: void si_insertSeqGObjects(const QList& objects); }; class ExpertDiscoveryViewWindow : public GObjectViewWindow{ Q_OBJECT public: ExpertDiscoveryViewWindow(GObjectView* view, const QString& viewName, bool persistent = false); virtual void setupMDIToolbar(QToolBar* tb); protected: bool onCloseEvent(); }; }//namespace ugene-1.9.8/src/plugins/expert_discovery/src/ExpertDiscoveryCSUtil.cpp0000644000175000017500000004230111651544323024702 0ustar ilyailya#include "ExpertDiscoveryCSUtil.h" #include "DDisc/statmath.h" #include "DDisc/Context.h" namespace U2 { CSFolder::CSFolder(CSFolder* pParentFolder) : QObject(pParentFolder) { setName(""); } CSFolder::~CSFolder(void) { /*CSelectedSignalsContainer& rSel = GlobalGetDocument()->GetSelectedSignalsContainer(); for (int id=0; id<(int) m_Signals.GetSize(); id++) { if (rSel.IsSelected(m_Signals[id])) rSel.RemoveSignal(m_Signals[id]); }*/ } void CSFolder::clear() { for(uint i = 0; i < signalsVect.size(); i++){ delete signalsVect[i]; } signalsVect.clear(); for(int i = 0; i < folders.size(); i++){ delete folders[i]; } folders.clear(); } QString CSFolder::getName() const { return strName; } void CSFolder::setName(QString strName) { this->strName = strName; } CSFolder* CSFolder::getParentFolder() const { return (CSFolder*)parent(); } void CSFolder::setParentFolder(CSFolder* pParentFolder) { setParent(pParentFolder); } int CSFolder::getSignalNumber() const { return (int) signalsVect.size(); } Signal* CSFolder::getSignal(int id) { return signalsVect[id]; } const Signal* CSFolder::getSignal(int id) const { return signalsVect[id]; } int CSFolder::addSignal(Signal *pSignal, bool bReplace) { int nIndex = getSignalIndexByName(pSignal->getName().c_str()); if (nIndex>=0) { if (bReplace) { delete signalsVect[nIndex]; signalsVect.erase(signalsVect.begin()+nIndex); } else { return -1; } } signalsVect.push_back(pSignal); return 0; } int CSFolder::getSignalIndexByName(QString strName) const { int nSigNum = (int) signalsVect.size(); for (int i=0; igetName()), strName)==0) return i; } return -1; } void CSFolder::deleteSignal(int id) { delete signalsVect[id]; signalsVect.erase(signalsVect.begin()+id); } int CSFolder::getFolderNumber() const { return folders.size(); } CSFolder* CSFolder::getSubfolder(int id) { return folders[id]; } const CSFolder* CSFolder::getSubfolder(int id) const { return folders[id]; } int CSFolder::addFolder(CSFolder *pFolder, bool bReplace) { int nIndex = getFolderIndexByName(pFolder->getName()); if (nIndex>=0) { if (bReplace) { CSFolder *pDestFolder = getSubfolder(nIndex); for (int i=0; igetFolderNumber(); i++) pDestFolder->addFolder(pFolder->getSubfolder(i), true); for (int i=0; igetSignalNumber(); i++) pDestFolder->addSignal(pFolder->getSignal(i), true); return nIndex; } else return -1; } else { pFolder->setParentFolder(this); folders.append(pFolder); return 0; } } int CSFolder::getFolderIndexByName(QString strName) const { int nFolderNum = (int) folders.size(); for (int i=0; igetName(), strName)==0) return i; } return -1; } QString CSFolder::makeUniqueSignalName() const { QString strPrefix = "NewSignal"; //if (!strPrefix.LoadString(IDS_PFX_SIGNAL)) ASSERT(0); int n = 0; QString strResult = "NewSignal"; while (getSignalIndexByName(strResult)>=0) { strResult = strPrefix + QString("%1").arg(n); n++; } return strResult; } QString CSFolder::makeUniqueFolderName() const { QString strPrefix= "NewFolder"; //if (!strPrefix.LoadString(IDS_PFX_FOLDER)) ASSERT(0); int n = 0; QString strResult = "NewFolder"; while (getFolderIndexByName(strResult)>=0) { strResult = strPrefix + QString("%1").arg(n); n++; } return strResult; } void CSFolder::deleteFolder(int id) { delete folders[id]; folders.erase(folders.begin()+id); } bool CSFolder::doConstructPath(QString& strPath, const Signal* pSignal) const { for (int i=0; igetName()); return true; } } for (int i=0; igetName(); if (pFolder->doConstructPath(strLocalPath, pSignal)) { strPath = strLocalPath; return true; } } return false; } QString CSFolder::getPathToSignal(const Signal* pSignal) const { QString strPath; doConstructPath(strPath, pSignal); return strPath; } const Signal* CSFolder::getSignalByPath(QString strPath) const { int nPos = strPath.indexOf("\\"); if (nPos == 0) { strPath = strPath.right(strPath.length()-1); nPos = strPath.indexOf("\\"); } if (nPos <= 0) { int nIndex = getSignalIndexByName(strPath); if (nIndex < 0) return NULL; else return getSignal(nIndex); } QString strFolderName(strPath.left(nPos)); QString strNewPath(strPath.right(strPath.length() - nPos - 1)); int nIndex = getFolderIndexByName(strFolderName); if (nIndex < 0) return NULL; return getSubfolder(nIndex)->getSignalByPath(strNewPath); } CSFolder* CSFolder::clone() const { CSFolder* pFolder = new CSFolder; pFolder->setName(getName()); for (int i=0; iaddFolder(getSubfolder(i)->clone()); } for (int i=0; iaddSignal(getSignal(i)->clone()); } return pFolder; } EDProcessedSignal::EDProcessedSignal() : m_dProbability (UNDEFINED_VALUE) , m_dFisher (UNDEFINED_VALUE) , m_dUl (UNDEFINED_VALUE) , m_dPosCoverage (UNDEFINED_VALUE) , m_dNegCoverage (UNDEFINED_VALUE) { } EDProcessedSignal* EDProcessedSignal::processSignal(Operation *pOp, const SequenceBase *pYesBase, const SequenceBase *pNoBase) { EDProcessedSignal* pPS = NULL; if (pOp==NULL || !pOp->check()) return NULL; switch (pOp->getType()) { case OP_INTERVAL : pPS = new EDProcessedInterval(); break; case OP_REITERATION : pPS = new EDProcessedReiteration(); break; case OP_DISTANCE : pPS = new EDProcessedDistance(); break; case OP_TS : pPS = new EDProcessedTS(); break; }; if (pPS != NULL) { pPS->setYesSequenceNumber(pYesBase->getSize()); pPS->setNoSequenceNumber(pNoBase->getSize()); pPS->setTextDescription(pOp->getDescription().c_str()); // for (int i=0; igetArgumentNumber(); i++) // pPS->AddChild(ProcessSignal(pOp->getArgument(i), pYesBase, pNoBase)); pPS->makeStandardProcessing(pOp, pYesBase, pNoBase); pPS->process(pOp, pYesBase, pNoBase); } return pPS; } void EDProcessedSignal::makeStandardProcessing(Operation *pOp, const SequenceBase *pYesBase, const SequenceBase *pNoBase) { bool first; int a[2][2] = {{0,0},{0,0}}; int aseq[2][2] = {{0,0},{0,0}}; int nSeqNum = pYesBase->getSize(); Signal sig(pOp); Context& rContext = sig.createCompartibleContext(); for (int i=0; igetSequence(i); Set set; set.init((unsigned)rSeq.getSize()); while (sig.find(rSeq, rContext)) { if (first) { first = false; aseq[1][1]++; } a[1][1]++; int nPos = rContext.getPosition(); int nLen = rContext.getLength(); for (int k=nPos; kgetSize(); for (int i=0; igetSequence(i); Set set; set.init((unsigned)rSeq.getSize()); while (sig.find(rSeq, rContext)) { if (first) { first = false; aseq[1][0]++; } a[1][0]++; int nPos = rContext.getPosition(); int nLen = rContext.getLength(); for (int k=nPos; k(pOp); assert(pDist != 0); int ai[2][2][2] = {{{0,0},{0,0}},{{0,0},{0,0}}}; const SequenceBase *pBasei[2] = {pYesBase, pNoBase}; Signal sig1(pDist->getArgument(0)); Signal sig2(pDist->getArgument(1)); Context& rContext1 = sig1.createCompartibleContext(); Context& rContext2 = sig2.createCompartibleContext(); for (int b=0; b<2; b++) { int (&a)[2][2] = ai[b]; const SequenceBase* pBase = pBasei[b]; int nSeqNum = pBase->getSize(); int r1 = 0, r2 = 0; for (int i=0; igetSequence(i); if (sig1.find(rSeq, rContext1)) r1 = 1; else r1 = 0; if (sig2.find(rSeq, rContext2)) r2 = 1; else r2 = 0; a[r1][r2]++; rContext1.reset(); rContext2.reset(); } } rContext1.destroy(); rContext2.destroy(); sig1.detach(); sig2.detach(); QString str; double dCC = corelation(ai[0][0][0], ai[0][0][1], ai[0][1][0], ai[0][1][1]); if (dCC == CORELATION_UNDEFINED) str = "Undefined"; else str =QString("%1").arg(dCC); addProperty("Param. corelation on pos.", str); dCC = corelation(ai[1][0][0], ai[1][0][1], ai[1][1][0], ai[1][1][1]); if (dCC == CORELATION_UNDEFINED) str = "Undefined"; else //str = to_string(dCC); str = QString("%1").arg(dCC); addProperty("Param. corelation on neg.", str); } void EDProcessedReiteration::process(Operation *pOp, const SequenceBase *pYesBase, const SequenceBase *pNoBase) { } void EDProcessedTS::process(Operation *pOp, const SequenceBase *pYesBase, const SequenceBase *pNoBase) { } ////////////////////////////////////////////////////////////////////////////////// SelectedSignalsContainer::SelectedSignalsContainer(void) { } SelectedSignalsContainer::~SelectedSignalsContainer(void) { } void SelectedSignalsContainer::AddSignal(const Signal* pSignal) { m_SelectedSignals.insert(pSignal); } void SelectedSignalsContainer::RemoveSignal(const Signal* pSignal) { SignalList::iterator it = m_SelectedSignals.find(pSignal); if (m_SelectedSignals.end() != it) m_SelectedSignals.erase(it); } const SignalList& SelectedSignalsContainer::GetSelectedSignals() const { return m_SelectedSignals; } bool SelectedSignalsContainer::IsSelected(const Signal *pSignal) const { SignalList::const_iterator it = m_SelectedSignals.find(pSignal); if (m_SelectedSignals.end() != it) return true; else return false; } void SelectedSignalsContainer::save(QDataStream& ar, CSFolder& rootF){ SignalList::iterator it = m_SelectedSignals.begin(); int nSize = (int) m_SelectedSignals.size(); ar << nSize; while (m_SelectedSignals.end() != it) { QString strPath = rootF.getPathToSignal((*it)); assert(!strPath.isEmpty()); ar << strPath; it++; } } void SelectedSignalsContainer::load(QDataStream& ar, CSFolder& rootF){ int nSize; ar >> nSize; for (int i=0; i> strPath; const Signal* pSignal = rootF.getSignalByPath(strPath); assert(pSignal != NULL); if (pSignal) AddSignal(pSignal); } } RecognizationDataStorage::~RecognizationDataStorage(){ clear(); } void RecognizationDataStorage::clear(){ foreach(RecognizationData* d, recMap){ if (d){ delete d; } } recMap.clear(); } void RecognizationDataStorage::addSequence(QString& seqName){ if (recMap.contains(seqName)){ RecognizationData *d = recMap.value(seqName); if(d){ delete d; } } recMap.insert(seqName, NULL); } bool RecognizationDataStorage::getRecognizationData(RecognizationData& data, const Sequence* seq, const SelectedSignalsContainer& rSe){ if (seq->isHasScore() && !(getRecData(seq) == NULL)){ data = *getRecData(seq); return !data.empty(); } const SignalList& rSelList = rSe.GetSelectedSignals(); if (rSelList.size() == 0) return false; data.resize(seq->getSize()); fill(data.begin(), data.end(), 0); SignalList::const_iterator iter = rSelList.begin(); while (iter != rSelList.end()) { const Signal* pSignal = (*iter); Context& context = pSignal->createCompartibleContext(); while (pSignal->find(*seq,context)) { double t = pSignal->getPriorProbability()/100; if (t>=1) t = 0.999999; int nPos = context.getPosition(); int not_null_length = 0; double value = -log(1-t); for (int i=0; igetName())); if(d != NULL){ delete d; } d = new RecognizationData(data); return true; } RecognizationData* RecognizationDataStorage::getRecData(const Sequence* seq){ if(!recMap.contains(QString::fromStdString(seq->getName())) ){ return NULL; }else{ return recMap.value(QString::fromStdString(seq->getName())); } } } //namespace ugene-1.9.8/src/plugins/expert_discovery/src/DDisc/0000755000175000017500000000000011651544323020741 5ustar ilyailyaugene-1.9.8/src/plugins/expert_discovery/src/DDisc/Signal.cpp0000644000175000017500000004570111651544323022671 0ustar ilyailya// Signal.cpp: implementation of the Signal class. // ////////////////////////////////////////////////////////////////////// #include "Signal.h" #include "Context.h" #include "Sequence.h" #include #include using namespace std; namespace DDisc { static int Prime(int n) { static const int CACHE = 5; static vector Prime; if (n >= (int) Prime.size()) { int old_size = (int) Prime.size(); int new_size = n + CACHE; Prime.resize( n + CACHE ); if (old_size == 0) { Prime[0] = 2; old_size++; } for (int i=old_size; i inline size_t _Hash_value(_Init _Begin, _Init _End) { // hash range of elements size_t _Val = 2166136261U; while(_Begin != _End) _Val = 16777619U * _Val ^ (size_t)*_Begin++; return (_Val); } template inline int hash_value(const basic_string<_Elem, _Traits, _Alloc>& _Str) { // hash string to size_t value return (int)(_Hash_value(_Str.begin(), _Str.end())); } ////////////////////////////////////////////////////////////////////// // Signal: complex signal ////////////////////////////////////////////////////////////////////// Signal::Signal(const string name, const string description) { setPriorParamsDefined(false); setPriorProbability(0); setPriorFisher(1); setPriorPosCoverage(0); setPriorNegCoverage(0); setName(name); setDescription(description); pSignal = NULL; } Signal::Signal(Operation *pOperation, const string name, const string description) { setPriorParamsDefined(false); setPriorProbability(0); setPriorFisher(1); setPriorPosCoverage(0); setPriorNegCoverage(0); setName(name); setDescription(description); pSignal = pOperation; } Signal::~Signal() { delete pSignal; } void Signal::attach(Operation *pOperation) { setPriorParamsDefined(false); setPriorProbability(0); setPriorFisher(1); setPriorPosCoverage(0); setPriorNegCoverage(0); pSignal = pOperation; } void Signal::detach() { pSignal = NULL; } bool Signal::find(const Sequence& rSeq, Context &rContext) const { int from = 0, to = static_cast(rSeq.getSequence().length()) -1; if (rContext.getSearchRegion() == Interval()) rContext.setSearchRegion( Interval(from, to) ); if (getSignal()->find(rSeq,rContext)) return true; return false; } Context& Signal::createCompartibleContext() const { return pSignal->createCompartibleContext(); } Signal* Signal::clone() const { Operation *pOp = getSignal() ? getSignal()->Clone() : NULL; Signal* pSignal = new Signal(pOp, getName(), getDescription()); pSignal->setPriorParamsDefined(isPriorParamsDefined()); pSignal->setPriorProbability(getPriorProbability()); pSignal->setPriorFisher(getPriorFisher()); pSignal->setPriorPosCoverage(getPriorPosCoverage()); pSignal->setPriorNegCoverage(getPriorNegCoverage()); return pSignal; } int Signal::getHash() const { return getSignal()->getHash(); } bool Signal::check() const { return pSignal && pSignal->check(); } ////////////////////////////////////////////////////////////////////// // Operation: abstract complex signal node ////////////////////////////////////////////////////////////////////// Operation::Operation() { } Operation::~Operation() { } void Operation::detach() { for (int i=0; icheck()) return false; } return true; } ////////////////////////////////////////////////////////////////////// // UnaryOperation: abstract unary operation ////////////////////////////////////////////////////////////////////// UnaryOperation::UnaryOperation() : Operation() { setArgument(NULL); } UnaryOperation::~UnaryOperation() { delete getArgument(); } Operation* UnaryOperation::getArgument(int i) const { if (i!=0) throw logic_error("Invalid argument number"); return pArgument; } void UnaryOperation::setArgument(Operation* pArgument, int i) { if (i!=0) throw logic_error("Invalid argument number"); this->pArgument = pArgument; } int UnaryOperation::getArgumentNumber() const { return 1; } ////////////////////////////////////////////////////////////////////// // BinaryOperation: abstract binary operation ////////////////////////////////////////////////////////////////////// BinaryOperation::BinaryOperation() : Operation() { detach(); } BinaryOperation::~BinaryOperation() { delete getArgument(0); delete getArgument(1); } Operation* BinaryOperation::getArgument(int i) const { switch (i) { case 0: return pArgument1; case 1: return pArgument2; default: throw logic_error("Invalid argument number"); }; } void BinaryOperation::setArgument(Operation* pArgument, int i) { switch (i) { case 0: pArgument1 = pArgument; break; case 1: pArgument2 = pArgument; break; default: throw logic_error("Invalid argument number"); }; } int BinaryOperation::getArgumentNumber() const { return 2; } ////////////////////////////////////////////////////////////////////// // OpInterval: Interval operation ////////////////////////////////////////////////////////////////////// OpInterval::OpInterval() : UnaryOperation() { setInt( Interval(0, PINF) ); } OpInterval::~OpInterval() { } Context& OpInterval::createCompartibleContext() const { ConInterval &context = *new ConInterval(); context.setSubContext(getArgument()->createCompartibleContext()); return context; } bool OpInterval::find(const Sequence& rSeq, Context &rContext) const { ConInterval& context = dynamic_cast(rContext); if (context.isEOF()) return false; if (context.getSearchRegion().isEmpty()) { context.setEOF(true); return false; } if (context.getSubContext().getSearchRegion()==Interval()) context.getSubContext().setSearchRegion(context.getSearchRegion().intersect(getInt())); bool bResult = getArgument()->find(rSeq, context.getSubContext()); if (!bResult) context.setEOF(true); else { context.setPosition( context.getSubContext().getPosition() ); context.setLength( context.getSubContext().getLength() ); } return bResult; } const string OpInterval::getDescription() const { string result = string("Interval from ") + to_string(getInt().getFrom()) + string(" to ") + to_string(getInt().getTo()); return result; } EOpType OpInterval::getType() const { return OP_INTERVAL; } Operation* OpInterval::Clone() const { OpInterval* pResult = new OpInterval; Operation* pArg = getArgument(0); if (pArg) pResult->setArgument( pArg->Clone() ); pResult->setInt( getInt() ); return pResult; } int OpInterval::getHash(int level) const { return 3*Prime(level)*getArgument()->getHash(level + 1); } ////////////////////////////////////////////////////////////////////// // OpReiteration: Repetition operation ////////////////////////////////////////////////////////////////////// OpReiteration::OpReiteration() : UnaryOperation() { setCount( Interval(1,1) ); setDistance( Interval(0, PINF) ); setDistanceType( DIST_FINISH_TO_START ); } OpReiteration::~OpReiteration() { } Context& OpReiteration::createCompartibleContext() const { ConReiteration &context = *new ConReiteration(); context.setSubContext(getArgument()->createCompartibleContext()); context.init(this); return context; } bool OpReiteration::find(const Sequence& rSeq, Context &rContext) const { ConReiteration& context = dynamic_cast(rContext); if (context.isEOF()) return false; if (context.getSearchRegion().isEmpty()) { context.setEOF(true); return false; } do { ConReiteration& NRContext = *context.getNextReiterationContext(); if (context.isFound() && context.getReiterationNo()find(rSeq, context.getSubContext())); if (context.isFound()) { int from = getDistance().getFrom(); if (from == MINF) from = 0; else from += DistanceCalculator::getStartPos( getDistanceType(), context.getSubContext().getPosition(), context.getSubContext().getLength()); NRContext.reset(); NRContext.setSearchRegion( Interval( from, context.getSearchRegion().getTo() ) ); if (getCount().isInInterval(context.getReiterationNo())) { context.setPosition(context.getSubContext().getPosition()); context.setLength(context.getSubContext().getLength()); return true; } } } while (context.isFound()); context.setEOF(true); return false; } const string OpReiteration::getDescription() const { string result = string("Repeated signals from ") + to_string(getCount().getFrom()) + string(" to ") + to_string(getCount().getTo()) + string(" times with distance from ") + to_string(getDistance().getFrom()) + string(" to ") + to_string(getDistance().getTo()); return result; } EOpType OpReiteration::getType() const { return OP_REITERATION; } Operation* OpReiteration::Clone() const { OpReiteration* pResult = new OpReiteration; Operation* pArg = getArgument(0); if (pArg) pResult->setArgument( pArg->Clone() ); pResult->setDistance( getDistance() ); pResult->setCount( getCount() ); return pResult; } int OpReiteration::getHash(int level) const { return 5*Prime(level)*getArgument()->getHash(level + 1); } ////////////////////////////////////////////////////////////////////// // OpDistance: distance operation ////////////////////////////////////////////////////////////////////// OpDistance::OpDistance() : BinaryOperation() { setDistance( Interval(0, PINF) ); setDistanceType(DIST_FINISH_TO_START); setOrderImportant(true); } OpDistance::~OpDistance() { } Context& OpDistance::createCompartibleContext() const { ConDistance &context = *new ConDistance(); context.setSubContext1(getArgument(0)->createCompartibleContext()); context.setSubContext2(getArgument(1)->createCompartibleContext()); return context; } bool OpDistance::find(const Sequence& rSeq, Context &rContext) const { ConDistance& context = dynamic_cast(rContext); if (context.isEOF()) return false; if (context.getSearchRegion().isEmpty()) { context.setEOF(true); return false; } const Operation *arg[] = {getArgument(0), getArgument(1)}; Context *con[] = {&context.getSubContext1(), &context.getSubContext2()}; for (int i=context.getI(); i<=static_cast(!isOrderImportant()); i++) { context.setI(i); if (con[i]->getSearchRegion() == Interval()) con[i]->setSearchRegion( context.getSearchRegion() ); bool found; do { if (!context.isBOF()) { int nFrom = getDistance().getFrom(); if (nFrom == MINF) nFrom = 0; int nStart = nFrom + DistanceCalculator::getStartPos( getDistanceType(), con[i]->getPosition(), con[i]->getLength()); int nTo = getDistance().getTo(); if (nTo != PINF) nTo += nStart; if (con[1-i]->getSearchRegion() == Interval()) { Interval iSearchRegion = context.getSearchRegion(); con[1-i]->setSearchRegion(iSearchRegion.intersect(Interval(nStart, PINF))); } // Bug while (arg[1-i]->find(rSeq, *con[1-i]) && con[1-i]->getPosition() <= nTo) { int nEnd = DistanceCalculator::getEndPos( getDistanceType(), con[1-i]->getPosition(), con[1-i]->getLength()); if (nEnd - nStart <= getDistance().getLength()-1) { int nPos = min(con[i]->getPosition(), con[1-i]->getPosition()); int nLen = max( con[i]->getPosition()+con[i]->getLength(), con[1-i]->getPosition()+con[1-i]->getLength() ) - nPos; context.setPosition( nPos ); context.setLength( nLen ); return true; } } con[1-i]->reset(); } context.setBOF(false); found = arg[i]->find(rSeq, *con[i]); } while ( found ); context.setBOF(true); con[i]->reset(); } context.setEOF(true); return false; } const string OpDistance::getDescription() const { string result = string("Distance from ") + to_string(getDistance().getFrom()) + string(" to ") + to_string(getDistance().getTo()); if (isOrderImportant()) result += " taking into account order"; return result; } EOpType OpDistance::getType() const { return OP_DISTANCE; } Operation* OpDistance::Clone() const { OpDistance* pResult = new OpDistance; Operation* pArg0 = getArgument(0); if (pArg0) pResult->setArgument( pArg0->Clone(), 0 ); Operation* pArg1 = getArgument(1); if (pArg1) pResult->setArgument( pArg1->Clone(), 1 ); pResult->setDistance( getDistance() ); pResult->setOrderImportant( isOrderImportant() ); return pResult; } int OpDistance::getHash(int level) const { if (isOrderImportant()) return Prime(level)*(7*getArgument(0)->getHash(level + 1) + 17*getArgument(1)->getHash(level + 1)); else return Prime(level)*(getArgument(0)->getHash(level + 1) + getArgument(1)->getHash(level + 1)); } ////////////////////////////////////////////////////////////////////// // TS: terminal symbol ////////////////////////////////////////////////////////////////////// TS::TS() { } TS::~TS() { } Context& TS::createCompartibleContext() const { if (isFromMarking()) { ConTS& context = *new ConTS(getFamily() + ":" + getName()); return context; } else { ConTS& context = *new ConTS(getWord()); return context; } } inline bool TS::compare(const char* seq, unsigned nSeqLen, const char *word, unsigned nWordLen) { static const char comparator[26][26] = { /*A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U.V,W,X,Y,Z*/ { 1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 }, // A { 0,0,1,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0 }, // B { 0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 }, // C { 1,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0 }, // D { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 }, // E { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 }, // F { 0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 }, // G { 1,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0 }, // H { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 }, // I { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 }, // J { 0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0 }, // K { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 }, // L { 1,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 }, // M { 1,0,1,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0 }, // N { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 }, // O { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 }, // P { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 }, // Q { 1,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 }, // R { 0,0,1,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 }, // S { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0 }, // T { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 }, // U { 1,0,1,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 }, // V { 1,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0 }, // W { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 }, // X { 0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0 }, // Y { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 }, // Z }; if (nWordLen > nSeqLen) return false; for (unsigned i=0; i(rContext); if (context.isEOF()) return false; if (context.getSearchRegion().isEmpty()) { context.setEOF(true); return false; } if (isFromMarking()) { Interval inter = context.getSearchRegion(); string name = getName(); string family = getFamily(); Interval location; try { location = rSeq.getSequenceMarking().hasSignalAt(inter, name, family); } catch (exception) { location = Interval(); } if (location != Interval()) { context.setPosition( location.getFrom() ); context.setLength( location.getLength() ); context.setSearchRegion( Interval(location.getFrom() + 1, context.getSearchRegion().getTo())); return true; } context.setEOF(true); return false; } else { string strWord = getWord(); int nWrdLen = (int) strWord.length(); if (nWrdLen != 0) { string strSeq = rSeq.getSequence().substr( context.getSearchRegion().getFrom(), context.getSearchRegion().getLength() ); int nSeqLen = (int) strSeq.length(); const char* pWord = strWord.c_str(); const char *pSeq = strSeq.c_str(); const char *pStart = pSeq; while (nWrdLen <= nSeqLen) { if (compare(pSeq, nSeqLen, pWord, nWrdLen)) { context.setPosition(context.getSearchRegion().getFrom()+int(pSeq-pStart)); context.setSearchRegion(Interval(context.getPosition()+1, context.getSearchRegion().getTo())); context.setLength(nWrdLen); return true; } pSeq++; nSeqLen--; } } context.setEOF(true); return false; } } const string TS::getDescription() const { string result; if (isFromMarking()) result += "\"" + getName() + "\" from family \"" + getFamily() + "\""; else result += getWord(); return result; } Operation* TS::getArgument(int i) const { throw logic_error("TS do not have any arguments"); } void TS::setArgument(Operation*, int i) { throw logic_error("TS do not have any arguments"); } int TS::getArgumentNumber() const { return 0; } EOpType TS::getType() const { return OP_TS; } Operation* TS::Clone() const { TS* pResult = new TS; pResult->setFromMarking( isFromMarking() ); pResult->setWord( getWord() ); pResult->setName( getName() ); pResult->setFamily( getFamily() ); return pResult; } bool TS::check() const { if (isFromMarking()) { if (getName().empty() || getFamily().empty()) return false; } else { if (getWord().empty()) return false; } return Operation::check(); } int TS::getHash(int level) const { if (isFromMarking()) return Prime(level)*(11*hash_value(getName()) + 13*hash_value(getFamily())); else return Prime(level)*(hash_value(getWord())); } }; ugene-1.9.8/src/plugins/expert_discovery/src/DDisc/Definitions.cpp0000644000175000017500000000575311651544323023732 0ustar ilyailya#include "definitions.h" #include #include #include #include #include #include namespace DDisc { using namespace std; /** * Converts integer to string */ string to_string(int v) { if (v==PINF || v==MINF) return "UNL"; char buffer[MAX_STR_INT]; sprintf(buffer,"%d",v); return string(buffer); } /** * Converts double to string */ string to_string(double v) { if (v==PINF || v==MINF) return "UNL"; char buffer[MAX_STR_INT]; sprintf(buffer,"%f",v); return string(buffer); } string readTAG(istream& in) { char buf[BUF_SIZE]; string result; in >> ws; in.clear(); if (in.get() != '<' || in.fail()) throw runtime_error("Invalid file format"); do { try { in.clear(); in.getline(buf, BUF_SIZE, '>'); result += buf; } catch (exception &ex) { cout << ex.what(); exit(0); } } while (in.fail() && !in.eof()); return result; } string& to_upper(string &str) { for (unsigned i=0; i> ws; f >> ws; while (s.good() && f.good()) { s.get(cs); f.get(cf); if (!f.good()) continue; if (cf == '%') { s.putback(cs); f.get(cf); switch (cf) { case 'd': { int &i = *va_arg(marker, int*); s >> i; if (s.fail()) { s.clear(); char buf[4]; buf[3] = 0; s.read(buf,3); if (strnicmp(buf,"UNL",3)) { va_end(marker); return false; } i = INF; } if (s.eof()) f.putback(f.get()); } break; case 's': { char *str = va_arg(marker, char*); f.get(cf); if (f.eof()) cf = ' '; if (isspace(cf)) s >> str; else s.getline(str,BUF_SIZE,cf); if (!f.eof()) { f.putback(cf); s.putback(cf); } s.clear(); } break; default: va_end(marker); return false; } } else if (isspace(cf)) { f >> ws; s >> ws; } else if (toupper(cf) != toupper(cs)) { va_end(marker); return false; } } va_end(marker); if (!f.eof()) { return false; } return true; } ostream& writeInt(ostream& out, int v) { if ( v==MINF || v==PINF) out << "UNL"; else out << v; return out; } bool isValidWord15(const char* strWord) { static const char complementator[26] = { // 'E' = error /* 'A','B','C','D','E','F','G','H','I','J','K','L','M', */ 'T','V','G','H','E','E','C','D','E','E','M','E','K', /* 'N','O','P','Q','R','S','T','U','V','W','X','Y','Z */ 'N','E','E','E','Y','S','A','U','B','W','E','R','E' }; const char *pChar = strWord; while (*pChar) { char ch = toupper(*pChar); if (ch<'A' || ch >'Z' || complementator[ch-'A'] == 'E') return false; pChar++; } return true; } #ifdef __TARGET_UNIX char *strupr(char *s) { int length = strlen(s); for (int i=0; i #include using namespace std; namespace DDisc { ////////////////////////////////////////////////////////////////////// // MetaInfo: ////////////////////////////////////////////////////////////////////// MetaInfo::MetaInfo(void) { } MetaInfo::~MetaInfo(void) { } MetaInfo::MetaInfo(const MetaInfo& mi) { *this = mi; } const MetaInfo& MetaInfo::operator =(const MetaInfo& mi) { setNo(mi.getNo()); setName(mi.getName()); setMethodName(mi.getMethodName()); return *this; } istream& MetaInfo::load(istream& in) { char buf[BUF_SIZE]; in >> ws; string eof = ""; int no; if (!parse(eof.c_str(),"", &no)) throw runtime_error("Invalid file format"); setNo(no); in >> ws; in.getline(buf, BUF_SIZE); string loaded = strupr(buf); if (!parse(loaded.c_str(),"NAME %s", buf)) throw runtime_error("Invalid file format"); if (!strlen(buf)) throw runtime_error("Invalid file format"); setName(buf); in >> ws; in.getline(buf, BUF_SIZE); loaded = strupr(buf); if (!parse(loaded.c_str(),"METHOD_NAME %s", buf)) throw runtime_error("Invalid file format"); if (!strlen(buf)) throw runtime_error("Invalid file format"); setMethodName(buf); bool err; do { in >> ws; in.getline(buf, BUF_SIZE); err = (strnicmp(buf, eof.c_str(), eof.length())!=0); } while (err && !in.eof()); if (err) throw runtime_error("Invalid file format"); return in; } ostream& MetaInfo::save(ostream& out) const { runtime_error("MetaInfo::save() not implemented"); return out; } ////////////////////////////////////////////////////////////////////// // Family: , ////////////////////////////////////////////////////////////////////// Family::Family(void) { } Family::~Family(void) { } Family::Family(const Family& family) { *this = family; } const Family& Family::operator =(const Family& family) { setName( family.getName() ); data = family.data; return *this; } istream& Family::load(istream& in) { char buf[BUF_SIZE]; string s = readTAG(in); string name = to_upper(s); setName(name); in >> ws; in.getline(buf, BUF_SIZE); if (in.fail()) throw runtime_error("Invalid file format"); int signumber; if (!parse(strupr(buf),"SIGNAL_NUMBER %d", &signumber)) throw runtime_error("Invalid file format"); MetaInfo metainfo; while (signumber--) { metainfo.load(in); data.push_back(metainfo); in >> ws; } in >> ws; in.getline(buf, BUF_SIZE); if (in.fail()) throw runtime_error("Invalid file format"); string eof = ""; if (strnicmp(buf, eof.c_str(), eof.length())) throw runtime_error("Invalid file format"); return in; } ostream& Family::save(ostream& out) const { runtime_error("Family::save() not implemented"); return out; } const MetaInfo& Family::getMetaInfo(int no) const { return data[no]; } const MetaInfo& Family::getMetaInfo(const string name) const { int nSize = (int) data.size(); for (int i=0; i> ws; while (!in.eof()) { Family family; family.load(in); data.push_back(family); in >> ws; } return in; } ostream& MetaInfoBase::save(ostream& out) const { throw runtime_error("MetaInfoBase::save() not implemented"); return out; } const Family& MetaInfoBase::getSignalFamily(int no) const { return data[no]; } Family& MetaInfoBase::getSignalFamily(int no) { return data[no]; } void MetaInfoBase::addFamily(const Family& rFamily) { data.push_back(rFamily); } const Family& MetaInfoBase::getSignalFamily(const string name) const { for (unsigned i=0; i(data.size()); } void MetaInfoBase::insert(const char* family, MetaInfo& mi) { try { Family& f = const_cast(getSignalFamily(family)); try { f.getMetaInfo(mi.getName()); } catch (...) { f.AddInfo(mi); } } catch (...) { Family f; f.AddInfo(mi); f.setName(family); addFamily(f); } } }; ugene-1.9.8/src/plugins/expert_discovery/src/DDisc/Sequence.cpp0000644000175000017500000002160211651544323023216 0ustar ilyailya// Sequence.cpp: implementation of the Sequence class. // ////////////////////////////////////////////////////////////////////// #include "Sequence.h" #include #include #include using namespace std; namespace DDisc { ////////////////////////////////////////////////////////////////////// // Marking: ////////////////////////////////////////////////////////////////////// Marking::Marking() { } Marking::~Marking() { } Marking::Marking(const Marking& m) { *this = m; } const Marking& Marking::operator = (const Marking& m) { marking = m.marking; return *this; } bool Marking::Comparator::operator ()(const Interval& a, const Interval& b) const { if (a.getFrom()b.getFrom()) return false; else if (a.getTo()second; FamilyMarking::const_iterator signal_pos = family_marking.find(name); if (signal_pos == family_marking.end()) return Interval(); const IntervalSet& set = signal_pos->second; IntervalSet::const_iterator iter = set.begin(); while (iter != set.end()) { const Interval& sig = *iter; if (interval.isInInterval(sig.getFrom()) && interval.isInInterval(sig.getTo())) return sig; iter++; } return Interval(); } void Marking::clear() { marking.clear(); } void Marking::set(string name, string family, Interval interval) { to_upper(name); to_upper(family); IntervalSet& set = marking[family][name]; set.insert(interval); } ////////////////////////////////////////////////////////////////////// // Sequence: ////////////////////////////////////////////////////////////////////// Sequence::Sequence() { pMarking = NULL; setHasScore(false); setScore(0); } Sequence::~Sequence() { } Sequence::Sequence(const Sequence& seq) { *this = seq; } Sequence::Sequence (const string & name, const string& seq){ setName(name); setSequence(seq); } const Sequence& Sequence::operator = (const Sequence& seq) { setName(seq.getName()); setSequence(seq.getSequence()); setHasScore(seq.isHasScore()); setScore(seq.getScore()); pMarking = seq.pMarking; return *this; } Marking& Sequence::getSequenceMarking() { if (!pMarking) throw runtime_error("No marking for this sequence"); return *const_cast(pMarking); } const Marking& Sequence::getSequenceMarking() const { if (!pMarking) throw runtime_error("No marking for this sequence"); return *pMarking; } void Sequence::setSequenceMarking(const Marking& rMarking) { pMarking = &rMarking; } istream& Sequence::load(istream& in) { char buf[BUF_SIZE]; in >> ws; if (in.get() != '>' || in.fail()) throw runtime_error("Invalid file format"); in >> ws; in.getline(buf,BUF_SIZE); int end = strlen(buf) - 1; while (end>=0 &&isspace(buf[end])) { buf[end] = 0; end--; } if (end == 0) throw runtime_error("Invalid file format"); setName(buf); setSequence(""); do { in.clear(); in.getline(buf,BUF_SIZE,'>'); char *token = strtok(buf, " \n\t"); while (token) { setSequence( getSequence() + strupr(token) ); token = strtok(NULL, " \n\t"); } } while (in.fail() && !in.eof()); if (!in.eof()) in.putback('>'); return in; } ostream& Sequence::save(ostream& out) const { out << "> " << getName().c_str() << endl; out << getSequence().c_str() << endl; return out; } size_t Sequence::getSize() const { return getSequence().size(); } void DDisc::Sequence::clearMarking(void) { pMarking = NULL; } ////////////////////////////////////////////////////////////////////// // MarkingBase: ////////////////////////////////////////////////////////////////////// MarkingBase::MarkingBase() { } MarkingBase::~MarkingBase() { } const Marking& MarkingBase::getMarking(int objno) const { Data::const_iterator i = data.find(objno); if (i == data.end()) throw range_error("No marking for this index"); return i->second; } void MarkingBase::clear() { data.clear(); } Marking& MarkingBase::getMarking(int objno) { Data::iterator i = data.find(objno); if (i == data.end()) throw range_error("No marking for this index"); return i->second; } void MarkingBase::setMarking(int objno, const Marking& rMrk) { data[objno] = rMrk; } istream& MarkingBase::load(istream& in) { data.clear(); in >> ws; while (!in.eof()) { string s = readTAG(in); string family = to_upper(s); string family_eof = "/" + family; string object; s = readTAG(in); object = to_upper(s); while (strnicmp(object.c_str(), family_eof.c_str(), family_eof.length())!=0) { int objno; if (!parse(object.c_str(),"OBJECT %d",&objno)) runtime_error("Invalid file format"); objno--; string object_eof = ""; char item[BUF_SIZE]; in >> ws; in.clear(); in.getline(item, BUF_SIZE); while (strnicmp(item, object_eof.c_str(), object_eof.length())!=0) { int from, to; char name[BUF_SIZE]; strupr(item); if (!parse(item,"%d..%d %s ", &from, &to, &name[0])) { throw runtime_error("Invalid file format"); } strupr(name); data[objno].set(name, family, Interval(from-1, to-1)); in >> ws; in.clear(); in.getline(item, BUF_SIZE); } in >> ws; s = readTAG(in); object = to_upper(s); } in >> ws; if (in.eof()) continue; s = readTAG(in); object = to_upper(s); } return in; } ostream& MarkingBase::save(ostream& out) const { throw logic_error("Marking::save() not implemented"); return out; } ////////////////////////////////////////////////////////////////////// // SequenceBase: ////////////////////////////////////////////////////////////////////// SequenceBase::SequenceBase() { } SequenceBase::~SequenceBase() { } void SequenceBase::setMarking(const MarkingBase& rBase) { for (int i=0; i(data.size()); } void SequenceBase::clear() { data.clear(); } void SequenceBase::clearScores() { for (int i=0; i<(int)data.size(); i++) { data[i].setHasScore(false); data[i].setScore(0); } } istream& SequenceBase::load(istream& in) { data.clear(); in.clear(); Sequence seq; do { seq.load(in); data.push_back(seq); } while (!in.eof()); return in; } ostream& SequenceBase::save(ostream& out) const { for (unsigned i=0; i SequenceBase::getScores() { int nSize = getSize(); vector vScores; vScores.resize(nSize); for (int i=0; i #define CORELATION_UNDEFINED -2 #ifndef min #define min(a,b) (a a * d) { m00 = c; m01 = d; m10 = a; m11 = b; } int lowestNum = min(m01, m10); for (int i1 = 0; i1 <= lowestNum; i1++) { double variable = -factln(m11) - factln(m01) - factln(m10) - factln(m00); result += exp(constant + variable); m11 = m11 + 1; m01 = m01 - 1; m10 = m10 - 1; m00 = m00 + 1; } return result; } inline double corelation(int a, int b, int c, int d) { double dSqrt = sqrt((double)(b + d) * (a + c) * (c + d) * (a + b)); if (dSqrt != 0) return (a * d - c * b) / dSqrt; else return CORELATION_UNDEFINED; } inline double ul(int a, int b, int c, int d) { if (b == 0 || c == 0) { return 1; } else if (a == 0 || d == 0) { return -1; } double Q = (a * d - b * c) / (double) (a * d + b * c); double D = 0.5 * (1 - Q * Q) * sqrt((double)(1.0 / a) + (1.0 / b) + (1.0 / c) + (1.0 / d)); double Q005 = Q - 1.96 * D; return Q005; } }ugene-1.9.8/src/plugins/expert_discovery/src/DDisc/Context.cpp0000644000175000017500000001253211651544323023074 0ustar ilyailya// Context.cpp: implementation of the Context interface. // ////////////////////////////////////////////////////////////////////// #include "Context.h" #include "Signal.h" namespace DDisc { ////////////////////////////////////////////////////////////////////// // Context: Abstract search context ////////////////////////////////////////////////////////////////////// Context::Context() { reset(); } Context::~Context() { } void Context::reset() { setEOF(false); setSearchRegion(Interval()); setPosition(0); setLength(0); } void Context::destroy() { delete this; } ////////////////////////////////////////////////////////////////////// // ConInterval: Search context for interval operation ////////////////////////////////////////////////////////////////////// ConInterval::ConInterval() : Context() { pSubContext = NULL; } ConInterval::~ConInterval() { if (pSubContext) pSubContext->destroy(); } void ConInterval::reset() { Context::reset(); getSubContext().reset(); } void ConInterval::setSubContext(Context &rContext) { if (pSubContext) pSubContext->destroy(); pSubContext = &rContext; } Context& ConInterval::getSubContext() const { return *pSubContext; } bool ConInterval::isSignalPart(int nPos) const { return pSubContext->isSignalPart(nPos); } std::string ConInterval::getTSName(int nPos) const { return pSubContext->getTSName(nPos); } int ConInterval::getDistributionHash() const { return pSubContext->getDistributionHash(); } ////////////////////////////////////////////////////////////////////// // ConReiteration: Search context for reiteration operation ////////////////////////////////////////////////////////////////////// ConReiteration::ConReiteration() : Context() { pSubContext = NULL; setReiterationNo(1); setNextReiterationContext(NULL); setFound(false); } ConReiteration::~ConReiteration() { if (pSubContext) pSubContext->destroy(); delete getNextReiterationContext(); } void ConReiteration::reset() { setFound(false); Context::reset(); getSubContext().reset(); ConReiteration* pNR = getNextReiterationContext(); if (pNR) pNR->reset(); } void ConReiteration::setSubContext(Context &rContext) { if (pSubContext) pSubContext->destroy(); pSubContext = &rContext; } Context& ConReiteration::getSubContext() const { return *pSubContext; } void ConReiteration::init(const OpReiteration* pOp) { if (getReiterationNo()<=pOp->getCount().getTo()) { setNextReiterationContext(new ConReiteration()); ConReiteration& rNR = *getNextReiterationContext(); rNR.setSearchRegion( Interval(0,0) ); rNR.setReiterationNo( getReiterationNo() + 1 ); rNR.setSubContext(pOp->getArgument()->createCompartibleContext()); rNR.init(pOp); } } bool ConReiteration::isSignalPart(int nPos) const { return pSubContext->isSignalPart(nPos) || (getNextReiterationContext() && getNextReiterationContext()->isSignalPart(nPos)); } std::string ConReiteration::getTSName(int nPos) const { if (pSubContext->isSignalPart(nPos)) return pSubContext->getTSName(nPos); else if (getNextReiterationContext()) return getNextReiterationContext()->getTSName(nPos); else return std::string(); } int ConReiteration::getDistributionHash() const { int result = 1; if (getNextReiterationContext()) result = getNextReiterationContext()->getDistributionHash(); result *= pSubContext->getDistributionHash(); return result; } ////////////////////////////////////////////////////////////////////// // ConDistance: Search context for distance operation ////////////////////////////////////////////////////////////////////// ConDistance::ConDistance() : Context() { pSubContext1 = NULL; pSubContext2 = NULL; setBOF(true); setI(0); } ConDistance::~ConDistance() { if (pSubContext1) pSubContext1->destroy(); if (pSubContext2) pSubContext2->destroy(); } void ConDistance::reset() { setBOF(true); setI(0); Context::reset(); getSubContext1().reset(); getSubContext2().reset(); } void ConDistance::setSubContext1(Context &rContext) { if (pSubContext1) pSubContext1->destroy(); pSubContext1 = &rContext; } Context& ConDistance::getSubContext1() const { return *pSubContext1; } void ConDistance::setSubContext2(Context &rContext) { if (pSubContext2) pSubContext2->destroy(); pSubContext2 = &rContext; } Context& ConDistance::getSubContext2() const { return *pSubContext2; } bool ConDistance::isSignalPart(int nPos) const { return pSubContext1->isSignalPart(nPos) || pSubContext2->isSignalPart(nPos); } std::string ConDistance::getTSName(int nPos) const { if (pSubContext1->isSignalPart(nPos)) return pSubContext1->getTSName(nPos); else return pSubContext2->getTSName(nPos); } int ConDistance::getDistributionHash() const { return pSubContext1->getDistributionHash() * pSubContext2->getDistributionHash(); } ////////////////////////////////////////////////////////////////////// // ConTS: Search context for terminal symbol ////////////////////////////////////////////////////////////////////// ConTS::ConTS(std::string name) : Context() { this->name = name; } ConTS::~ConTS() { } void ConTS::reset() { Context::reset(); } bool ConTS::isSignalPart(int nPos) const { return (nPos >= getPosition() && nPos < getPosition() + getLength()); } std::string ConTS::getTSName(int nPos) const { if (isSignalPart(nPos)) return name; else return std::string(); } int ConTS::getDistributionHash() const { return getPosition() + getLength(); } }; ugene-1.9.8/src/plugins/expert_discovery/src/DDisc/definitions.h0000644000175000017500000001121611651544323023426 0ustar ilyailya#ifndef DEFINITIONS_H__INCLUDED_ #define DEFINITIONS_H__INCLUDED_ #include #include #include #ifndef _WIN32 #define __TARGET_UNIX #endif #ifdef __TARGET_UNIX #define strnicmp strncasecmp #define stricmp strcasecmp #endif /** * Defines class property of type 'type' and name 'name' and * get and set functions. */ #define PROPERTY(type, name) \ private:\ type property_##name; \ public:\ inline const type get##name() const { return property_##name; } \ inline void set##name(type value) { property_##name = value; } /** * Defines property that can be changed through get accessor */ #define VAR_PROPERTY(type, name) \ private:\ type property_##name; \ public:\ inline type get##name() const { return property_##name; } \ inline void set##name(type value) { property_##name = value; } /** * Defines property that managed through type references */ #define REF_PROPERTY(type, name) \ private:\ type* refproperty_##name; \ public: \ inline const type& get##name() const { return *refproperty_##name;} \ inline void set##name(type &value) { refproperty_##name = &value; } /** * Defines property that managed through const type references */ #define CREF_PROPERTY(type, name) \ private:\ const type* refproperty_##name; \ public: \ inline const type& get##name() const { return *refproperty_##name;} \ inline void set##name(const type &value) { refproperty_##name = &value; } /** * Defines flag and set and is accessors, set accessor can be called only * inside class. */ #define FLAG(name) \ private: \ bool flag_##name; \ protected: \ void set##name(bool value) { flag_##name = value; } \ public: \ inline bool is##name() const { return flag_##name; } /** * Defines flag and set and is accessors. */ #define MODIFIABLE_FLAG(name) \ private: \ bool flag_##name; \ public: \ void set##name(bool value) { flag_##name = value; } \ inline bool is##name() const { return flag_##name; } #define BUF_SIZE 1024 #include /** * Plus infinity constant */ #define PINF INT_MAX /** * Minus infinity constant */ #define MINF INT_MIN /** * Infinity constant */ #define INF PINF #define MAX(a,b) (a>b)?a:b #define MIN(a,b) (agetTo(); } /** * @return length of interval */ inline int getLength() const { if (getTo() == PINF) return PINF; int len = getTo() - getFrom() + 1; return (len>0)?len:0; } /** * Start value of interval */ PROPERTY(int, From); /** * End value of interval */ PROPERTY(int, To); }; /** * */ enum EDistType { DIST_FINISH_TO_START, DIST_START_TO_START, DIST_MIDDLE_TO_START }; class DistanceCalculator { public: inline static int getStartPos(EDistType eType, int nPos, int nLength) { int nStartPos = 0; switch (eType) { case DIST_FINISH_TO_START : nStartPos = nPos + nLength; break; case DIST_START_TO_START : nStartPos = nPos; break; case DIST_MIDDLE_TO_START : nStartPos = nPos + nLength/2; break; default: assert(0); }; return nStartPos; } inline static int getEndPos(EDistType eType, int nPos, int nLength) { return nPos; } private: DistanceCalculator(); DistanceCalculator(const DistanceCalculator&); ~DistanceCalculator(); }; #define MAX_STR_INT 100 extern std::string to_string(int); extern std::string to_string(double); extern std::string readTAG(std::istream& in); extern std::string& to_upper(std::string &str); extern bool parse(const char* source, const char* format,...); extern std::ostream& writeInt(std::ostream& out, int v); extern bool isValidWord15(const char* strWord); #ifdef __TARGET_UNIX extern char *strupr(char *); #endif }; #endif // !defined(DEFINITIONS_H__INCLUDED_) ugene-1.9.8/src/plugins/expert_discovery/src/DDisc/Sequence.h0000644000175000017500000001214711651544323022667 0ustar ilyailya// Sequence.h: interface for the Sequence class. // ////////////////////////////////////////////////////////////////////// #if !defined(SEQUENCE_H__INCLUDED_) #define SEQUENCE_H__INCLUDED_ #include "definitions.h" #include #include #include #include namespace DDisc { /** * Sequence marking. This class contains positions of * particular signal on particular sequence. */ class Marking { public: Marking(); virtual ~Marking(); /** * Checks if sequence in region has signal name from family. * @return location of signal if sequence has, Interval() if no. */ Interval hasSignalAt(Interval region, std::string name, std::string family) const; /** * Add position of signal to the marking. * @param name name of the signal * @param family family of the signal * @param interval region where signal is located */ void set(std::string name, std::string family, Interval interval); /** * Clears sequence marking */ void clear(); std::set getFamilies() { std::set result; MarkingData::iterator i = marking.begin(); while (i != marking.end()) { result.insert(i->first); i++; } return result; } std::set getSignals(std::string family) { std::set result; const FamilyMarking& familyMrk = marking[family]; FamilyMarking::const_iterator i = familyMrk.begin(); while (i != familyMrk.end()) { result.insert(i->first); i++; } return result; } Marking(const Marking&); const Marking& operator = (const Marking&); struct Comparator { bool operator()(const Interval& _Left, const Interval& _Right) const; }; typedef std::set IntervalSet; typedef std::map FamilyMarking; typedef std::map MarkingData; MarkingData marking; }; /** * Class representing genome sequence */ class Sequence { public: Sequence(); Sequence(const Sequence&); Sequence (const std::string& name, const std::string& seq); const Sequence& operator = (const Sequence&); virtual ~Sequence(); /** * Deserialize class from stream */ virtual std::istream& load(std::istream& in); /** * Serialize class from stream */ virtual std::ostream& save(std::ostream& out) const; /** * @return marking of sequence */ Marking &getSequenceMarking(); /** * @return marking of sequence (const version) */ const Marking &getSequenceMarking() const; /** * Sets marking for sequence */ void setSequenceMarking(const Marking&); /** * Clears marking */ void clearMarking(void); /** * @return number of signals in marking */ size_t getSize() const; private: /** * Name of sequence */ PROPERTY(std::string, Name); /** * Code of sequence */ PROPERTY(std::string, Sequence); /** * True if sequence score setup */ MODIFIABLE_FLAG( HasScore ); /** * Sequence score */ PROPERTY(double, Score); /** * Pointer to sequence marking */ const Marking* pMarking; }; /** * Marking database */ class MarkingBase { public: MarkingBase(); virtual ~MarkingBase(); /** * @return marking number objno */ const Marking& getMarking(int objno) const; /** * @return marking number objno */ Marking& getMarking(int objno); /** * Set marking number objno equal to mrk */ void setMarking(int objno, const Marking& mrk); /** * Deserialize class from stream */ virtual std::istream& load(std::istream& in); /** * Serialize class from stream */ virtual std::ostream& save(std::ostream& out) const; /** * Clears DB */ void clear(); /** * @return size of internal map * @deprecated */ //int getSize() { return static_cast(data.size()); } private: typedef std::map Data; Data data; }; /** * Class representing set of sequences */ class SequenceBase { public: SequenceBase(); virtual ~SequenceBase(); /** * Set corresponding marking DB */ void setMarking(const MarkingBase& rBase); /** * Clears marking */ void clearMarking(void); /** * @return Sequence number objno */ Sequence& getSequence(int objno); /** * @return Sequence number objno */ const Sequence& getSequence(int objno) const; /** * @return index of sequence with code */ int findSequence(std::string code); int getSize() const; /** * Deserialize class from stream */ virtual std::istream& load(std::istream& in); /** * Serialize class from stream */ virtual std::ostream& save(std::ostream& out) const; /** * Clears DB */ void clear(); /** * Adds sequence to DB */ int addSequence(const Sequence& rSeq); /** * Clears sequence scores */ void clearScores(); /** * Get scores of all sequences in DB */ std::vector getScores(); int getObjNo(const char* strId) const; private: typedef std::vector Data; Data data; }; }; #endif // !defined(SEQUENCE_H__INCLUDED_) ugene-1.9.8/src/plugins/expert_discovery/src/DDisc/Context.h0000644000175000017500000001325011651544323022537 0ustar ilyailya#if !defined(CONTEXT_H__INCLUDED_) #define CONTEXT_H__INCLUDED_ #include "definitions.h" #include "Signal.h" namespace DDisc { /** * Context is a general interface used to store current * search position for signal node and describe it. */ class Context { public: /** * Resets context. This method should be called when * when you are going to find signal on next sequence. */ virtual void reset(); /** * Context class cannot be destroyed using delete. To * destroy it call this method. */ void destroy(); /** * Checks when position nPos of sequence is part of * current signal realization. * * @param nPos position on sequence * @return true if nPos is part of current signal realization */ virtual bool isSignalPart(int nPos) const = 0; /** * Checks when position nPos of sequence is part of * current signal realization and return name of terminal symbol. * * @param nPos position on sequence * @return name of TS in position or empty string */ virtual std::string getTSName(int nPos) const = 0; /** * Calculates hash of current signal realization. This is * used to avoid search of equivalent signals. */ virtual int getDistributionHash() const = 0; protected: /** * This class cannot be constructed or copied, so constructors * destructor and operator = declared as protected */ Context(); Context(const Context &); const Context& operator =(const Context &rContext); virtual ~Context(); /** * Flag EOF become true if search is done for current sequence */ FLAG(EOF); /** * Interval of sequence where search is performed */ PROPERTY(Interval, SearchRegion); /** * Position of signal node associated with context */ PROPERTY(int, Position); /** * Length of signal node associated with context */ PROPERTY(int, Length); }; /** * Realization of Context interface for interval operation * @see OpInterval */ class ConInterval : public Context { public: virtual void reset(); protected: ConInterval(); ConInterval(const ConInterval &); virtual ~ConInterval(); const ConInterval& operator =(const ConInterval &rContext); /** * Sets context of operation argument * @param rContext reference to operation argument context */ void setSubContext(Context &rContext); /** * Gets context of operation argument * @return reference to operation argument context */ Context& getSubContext() const; virtual bool isSignalPart(int nPos) const; virtual std::string getTSName(int nPos) const; virtual int getDistributionHash() const; private: /** * Pointer to operation argument context */ Context *pSubContext; friend class OpInterval; }; /** * Realization of Context interface for reiteration operation * @see OpReiteration */ class ConReiteration : public Context { friend class OpReiteration; public: virtual void reset(); void init(const OpReiteration*); protected: ConReiteration(); ConReiteration(const ConReiteration&); virtual ~ConReiteration(); const ConReiteration& operator =(const ConReiteration &rContext); /** * Sets context of operation argument * @param rContext reference to operation argument context */ void setSubContext(Context &rContext); /** * Gets context of operation argument * @return reference to operation argument context */ Context& getSubContext() const; virtual bool isSignalPart(int nPos) const; virtual std::string getTSName(int nPos) const; virtual int getDistributionHash() const; private: /** * Pointer to operation argument context */ Context *pSubContext; /** * Context of next reiteration instance */ VAR_PROPERTY(ConReiteration*, NextReiterationContext); /** * Number of current reiteration */ PROPERTY(int, ReiterationNo); /** * Found is set to true, if next reiteration was found */ FLAG(Found); }; /** * Realization of Context interface for Distance operation * @see OpDistance */ class ConDistance : public Context { public: virtual void reset(); protected: ConDistance(); ConDistance(const ConDistance&); virtual ~ConDistance(); const ConDistance& operator =(const ConDistance &rContext); /** * Sets context of first operation argument * @param rContext reference to operation argument context */ void setSubContext1(Context &rContext); /** * Gets context of first operation argument * @return reference to first operation argument context */ Context& getSubContext1() const; /** * Sets context of second operation argument * @param rContext reference to operation argument context */ void setSubContext2(Context &rContext); /** * Gets context of second operation argument * @return reference to second operation argument context */ Context& getSubContext2() const; virtual bool isSignalPart(int nPos) const; virtual std::string getTSName(int nPos) const; virtual int getDistributionHash() const; private: /** * Pointer to first operation argument context */ Context *pSubContext1; /** * Pointer to second operation argument context */ Context *pSubContext2; FLAG(BOF); PROPERTY(int, I); friend class OpDistance; }; /** * Realization of Context interface for terminal symbol * @see TS */ class ConTS : public Context { public: virtual void reset(); protected: ConTS(std::string name); ConTS(const ConTS&); virtual ~ConTS(); const ConTS& operator =(const ConTS &rContext); virtual bool isSignalPart(int nPos) const; virtual std::string getTSName(int nPos) const; virtual int getDistributionHash() const; friend class TS; private: std::string name; }; }; #endif // !defined(CONTEXT_H__INCLUDED_) ugene-1.9.8/src/plugins/expert_discovery/src/DDisc/Extractor.cpp0000644000175000017500000003766311651544323023437 0ustar ilyailya#include "Extractor.h" #include "Context.h" #include "statmath.h" #include using namespace std; #define INVALID_VALUE -1 #define UNDEFINED_VALUE (double) 0xFFFFFFFF namespace DDisc { const double EPS = 0.00000000001; const TSNO INVALID_TSNO = {-1,-1}; ///////////////////////////////////////////////////////////////////////// // Predicat Base ///////////////////////////////////////////////////////////////////////// PredicatBase::PredicatBase(const MetaInfoBase &rBase) : rMIBase(rBase) { } PredicatBase::~PredicatBase() { for (int i=0; i& rPredicates) { base = rPredicates; setPredicatNumber((int)base.size()); int family_num = rMIBase.getFamilyNumber(); family_size.resize(family_num+1); family_size[0] = 0; for (int i=1; iClone(); } void PredicatBase::getFirstTSNO(TSNO& no) const { no.iFamily = 0; no.iSignal = 0; } TS* PredicatBase::getPrevTS(TSNO& no) const { no.iSignal--; while (no.iSignal<0) { no.iFamily--; if (no.iFamily < 0) break; no.iSignal = rMIBase.getSignalFamily(no.iFamily).getSignalNumber() - 1; } if (no.iFamily < 0) return NULL; int family_num = rMIBase.getFamilyNumber(); const Family& family = rMIBase.getSignalFamily(no.iFamily); int signal_num = family.getSignalNumber(); if (no.iSignal >= signal_num) return NULL; const MetaInfo& rMI = family.getMetaInfo(no.iSignal); TS *pTS = new TS; pTS->setFromMarking(true); pTS->setFamily(family.getName()); pTS->setName(rMI.getName()); return pTS; } TS* PredicatBase::getNextTS(TSNO& no) const { int family_num = rMIBase.getFamilyNumber(); if (no.iFamily >= family_num) return NULL; const Family& family = rMIBase.getSignalFamily(no.iFamily); int signal_num = family.getSignalNumber(); if (no.iSignal >= signal_num) return NULL; const MetaInfo& rMI = family.getMetaInfo(no.iSignal); TS *pTS = new TS; pTS->setFromMarking(true); pTS->setFamily(family.getName()); pTS->setName(rMI.getName()); no.iSignal++; while (no.iSignal >= signal_num) { no.iFamily++; no.iSignal = 0; if (no.iFamily >= family_num) break; else signal_num = rMIBase.getSignalFamily(no.iFamily).getSignalNumber(); } return pTS; } int PredicatBase::getAbsoletePos(const TSNO& no) const { return family_size[no.iFamily] + no.iSignal; } int PredicatBase::getTSNumber() { return family_size.back(); } ///////////////////////////////////////////////////////////////////////// // Signal Extractor ///////////////////////////////////////////////////////////////////////// Extractor::Extractor(const SequenceBase* pYesBase, const SequenceBase* pNoBase, PredicatBase* pPredicatBase) : m_pYesBase(pYesBase) , m_pNoBase(pNoBase) , m_pPredicatBase(pPredicatBase) , m_bFirst(true) { } Extractor::~Extractor(void) { clearInternalData(); } bool Extractor::step(Signal **result) { Signal* pSignal; *result = NULL; if (m_bFirst) { pSignal = getNextSignal(); m_bFirst = false; } else { do { pSignal = getNextSignal(&m_SP); } while (pSignal && alreadyFound(pSignal)); } if (pSignal) { if (check(pSignal, &m_SP)) { if (!isStoreOnlyDifferent() || isNewDistribution(m_SP.distribution_hash)) { addToFound(pSignal); storeDistribution(m_SP.distribution_hash); pSignal->setPriorParamsDefined(true); pSignal->setPriorProbability(100*m_SP.condition_probability); pSignal->setPriorFisher(m_SP.fisher_criterion); pSignal->setPriorPosCoverage(100*m_SP.coverage); pSignal->setPriorNegCoverage(100*m_SP.neg_coverage); *result = pSignal; } } return true; } else { return false; } } double Extractor::progress() { double progress; if (selection_stack.size()==0) { progress = 100; } else { SelectionNode &node = selection_stack.front(); progress = 100*( (m_pPredicatBase->getAbsoletePos(node.tsno) -1 + node.predicat/(1.0*m_pPredicatBase->getPredicatNumber()) ) / (1.0*m_pPredicatBase->getTSNumber())); } return progress; } Signal* Extractor::getNextSignal(const SignalParams* prev_res /* = NULL*/) { SelectionNode cur; if (prev_res == NULL) { clearInternalData(); m_pPredicatBase->getFirstTSNO(cur.tsno); cur.structure = m_pPredicatBase->getNextTS(cur.tsno); cur.ts = 0; cur.min_probability = 0; cur.max_fisher = 1; cur.predicat = INVALID_VALUE; cur.predicat_tsno = INVALID_TSNO; signal.attach(cur.structure); selection_stack.push_back(cur); return &signal; } else { assert(!selection_stack.empty()); selection_stack.back().min_probability = prev_res->condition_probability; selection_stack.back().max_fisher = prev_res->fisher_criterion; } assert(!selection_stack.empty()); if (selection_stack.empty()) return NULL; if (needBranchThisNode(prev_res)) { if (!doBranch()) if (!doNext()) return NULL; } else if (!doNext()) return NULL; signal.attach(selection_stack.back().structure); return &signal; } void Extractor::clearInternalData(void) { signal.detach(); while (!selection_stack.empty()) { delete selection_stack.back().structure; selection_stack.pop_back(); } } bool Extractor::doBranch() { assert(selection_stack.size()!=0); SelectionNode& cur = selection_stack.back(); TS* pTS = NULL; if (cur.predicat == INVALID_VALUE) { cur.predicat = 0; cur.predicat_tsno = INVALID_TSNO; } else { if (cur.predicat_tsno == INVALID_TSNO) { cur.predicat++; cur.predicat_tsno = INVALID_TSNO; } else { pTS = m_pPredicatBase->getNextTS(cur.predicat_tsno); if (pTS == NULL) { cur.predicat++; cur.predicat_tsno = INVALID_TSNO; } } } if (cur.predicat >= m_pPredicatBase->getPredicatNumber()) { cur.ts++; cur.predicat = 0; cur.predicat_tsno = INVALID_TSNO; } Operation* predicat = m_pPredicatBase->getPredicat(cur.predicat); SelectionNode new_node; new_node.structure = cur.structure->Clone(); new_node.predicat = INVALID_VALUE; new_node.predicat_tsno = INVALID_TSNO; new_node.ts = cur.ts; new_node.tsno = cur.tsno; //new_node.min_probability = switch (predicat->getArgumentNumber()) { case 1: assert(pTS == NULL); break; case 2: if (cur.predicat_tsno == INVALID_TSNO) { assert(pTS == NULL); m_pPredicatBase->getFirstTSNO(cur.predicat_tsno); pTS = m_pPredicatBase->getNextTS(cur.predicat_tsno); } if (!pTS) { delete new_node.structure; return false; } predicat->setArgument(pTS, 1); break; default: assert(0); } if (insertPredicat(new_node.structure, new_node.ts, predicat)) { selection_stack.push_back(new_node); return true; } else { delete new_node.structure; delete predicat; return false; } } bool Extractor::insertPredicat(Operation *&structure, int ts, Operation* predicat, int *pId, Operation *pParent) { int id=0; if (!pId) pId = &id; int arg_num = structure->getArgumentNumber(); switch ( arg_num ) { case 0: if (*pId == ts) { predicat->setArgument(structure,0); if (pParent) { int parent_arg_num = pParent->getArgumentNumber(); int i; for (i=0;igetArgument(i) == structure) break; } assert( i != parent_arg_num ); pParent->setArgument(predicat,i); } else structure = predicat; return true; } (*pId)++; break; case 1: { Operation *pOp = structure->getArgument(0); if (insertPredicat(pOp,ts,predicat,pId,structure)) { return true; } break; } case 2: { Operation *pOp1 = structure->getArgument(0); Operation *pOp2 = structure->getArgument(1); if (insertPredicat(pOp1,ts,predicat,pId,structure) || insertPredicat(pOp2,ts,predicat,pId,structure)) { return true; } break; } } return false; } bool Extractor::doNext() { assert(selection_stack.size()!=0); signal.detach(); SelectionNode cur; while (1) { cur = selection_stack.back(); if (selection_stack.size() == 1) { delete cur.structure; cur.structure = m_pPredicatBase->getNextTS(cur.tsno); cur.ts = 0; cur.min_probability = 0; cur.max_fisher = 1; cur.predicat = INVALID_VALUE; cur.predicat_tsno = INVALID_TSNO; if (!cur.structure) { selection_stack.pop_back(); return false; } else { selection_stack.back() = cur; signal.attach(cur.structure); return true; } } else { delete cur.structure; selection_stack.pop_back(); if (doBranch()) { signal.attach(selection_stack.back().structure); return true; } } } return false; } bool Extractor::needBranchThisNode(const SignalParams* prev_res) const { if (prev_res->coverage < getCoverageBound()) return false; bool prob_inc; bool fish_dec; if (prev_res->condition_probability >= 1) return false; if (getMaxComplexity() != 0 && (int)selection_stack.size() >= getMaxComplexity()) return false; if ((int)selection_stack.size() <= getMinComplexity()) return true; if (selection_stack.size()>=2) { SelectionStack::const_iterator iter = selection_stack.end(); iter--; iter--; prob_inc = (*iter).min_probability < prev_res->condition_probability; if (isCheckFisherMinimization()) fish_dec = (*iter).max_fisher > prev_res->fisher_criterion; else fish_dec = true; } else { prob_inc = true; fish_dec = true; } if (!prob_inc || !fish_dec || prev_res->condition_probability < getInterestProbability() || prev_res->fisher_criterion > getInterestFisher() ) return false; else return true; } bool Extractor::check(Signal *pSignal, SignalParams *pSP /* = NULL */) { SignalParams& sp = *pSP; int t00 = 0; int t01 = 0; int t10 = 0; int t11 = 0; Context& context = pSignal->createCompartibleContext(); bool first; int found_count = 0; sp.distribution_hash = 0; for (int i=0; igetSize(); i++) { const Sequence& rSeq = m_pYesBase->getSequence(i); int count = 0; first = true; while (pSignal->find(rSeq, context)) { if (first) { first = false; found_count++; } sp.distribution_hash += i * context.getDistributionHash(); count++; } if (!count) t01++; else t11 += count; context.reset(); } context.reset(); sp.coverage = found_count / double(m_pYesBase->getSize()); sp.um_criterion = UNDEFINED_VALUE; if (sp.coverage < getCoverageBound()) { sp.condition_probability = 0; sp.fisher_criterion = 1; context.destroy(); return false; } found_count = 0; for (int i=0; igetSize(); i++) { const Sequence& rSeq = m_pNoBase->getSequence(i); int count = 0; first = true; while (pSignal->find(rSeq, context)) { if (first) { first = false; found_count++; } count++; sp.distribution_hash += i * context.getDistributionHash(); } if (!count) t00++; else t10 += count; context.reset(); } context.destroy(); sp.neg_coverage = found_count / double(m_pNoBase->getSize()); double total_found = t10 + t11; if (total_found) sp.condition_probability = t11 / total_found; else sp.condition_probability = 0; sp.fisher_criterion = fisher(t00, t01, t10, t11); bool prob_inc; bool fish_dec; if (selection_stack.size() >= 2 && (int) selection_stack.size() > getMinComplexity()) { SelectionStack::const_iterator iter = selection_stack.end(); iter--; iter--; prob_inc = (*iter).min_probability < sp.condition_probability; if (isCheckFisherMinimization()) fish_dec = (*iter).max_fisher > sp.fisher_criterion; else fish_dec = true; } else { prob_inc = true; fish_dec = true; } if (prob_inc && fish_dec && sp.condition_probability - getProbabilityBound() >= -EPS && sp.fisher_criterion - getFisherBound() <= EPS) { if (isUmEnabled() && t00 + t01 + t10 + t11 >= getUmSamplesBound()) { sp.um_criterion = ul(t00, t01, t10, t11); if (sp.um_criterion <= getUmBound()) return false; } if (isCorrelationImportant()) return checkCorrelation(pSignal->getSignal()); else return true; } else { return false; } } bool Extractor::checkCorrelation(Operation *pOp) { assert(pOp != NULL); if (pOp->getType() == OP_DISTANCE) { int sp[2][2] = {{0,0},{0,0}}; // positive statistics int sn[2][2] = {{0,0},{0,0}}; // negative statistics Signal s1(pOp->getArgument(0)); Signal s2(pOp->getArgument(1)); Context& con1 = s1.createCompartibleContext(); Context& con2 = s2.createCompartibleContext(); int bs1, bs2; for (int i=0; igetSize(); i++) { const Sequence& rSeq = m_pYesBase->getSequence(i); if (s1.find(rSeq, con1)) bs1 = 1; else bs1 = 0; if (s2.find(rSeq, con2)) bs2 = 1; else bs2 = 0; sp[bs1][bs2]++; con1.reset(); con2.reset(); } double CorrelationOnPositive = corelation(sp[0][0], sp[0][1], sp[1][0], sp[1][1]); if (CorrelationOnPositive == CORELATION_UNDEFINED || CorrelationOnPositive <= getMinCorrelationOnPos() || CorrelationOnPositive >= getMaxCorrelationOnPos()) { con1.destroy(); con2.destroy(); s1.detach(); s2.detach(); return false; } for (int i=0; igetSize(); i++) { const Sequence& rSeq = m_pNoBase->getSequence(i); if (s1.find(rSeq, con1)) bs1 = 1; else bs1 = 0; if (s2.find(rSeq, con2)) bs2 = 1; else bs2 = 0; sn[bs1][bs2]++; con1.reset(); con2.reset(); } con1.destroy(); con2.destroy(); s1.detach(); s2.detach(); double CorrelationOnNegative = corelation(sn[0][0], sn[0][1], sn[1][0], sn[1][1]); if (CorrelationOnNegative == CORELATION_UNDEFINED || CorrelationOnNegative <= getMinCorrelationOnNeg() || CorrelationOnNegative >= getMaxCorrelationOnNeg()) { return false; } } int arg_num = pOp->getArgumentNumber(); if (arg_num == 0) return true; else { for (int i=0; igetArgument(i))) return false; } return true; } bool Extractor::alreadyFound(Signal *pSignal) const { int hash = pSignal->getHash(); return m_AlreadyFound.find(hash) != m_AlreadyFound.end(); } void Extractor::addToFound(Signal *pSignal) { m_AlreadyFound.insert(pSignal->getHash()); } bool Extractor::isNewDistribution(int distribution_hash) const { return m_DistributionHash.find(distribution_hash) == m_DistributionHash.end(); } void Extractor::storeDistribution(int distribution_hash) { m_DistributionHash.insert(distribution_hash); } }ugene-1.9.8/src/plugins/expert_discovery/src/DDisc/Extractor.h0000644000175000017500000000604711651544323023074 0ustar ilyailya#ifndef _EXTRACTOR_H #define _EXTRACTOR_H #include "definitions.h" #include "MetaInfo.h" #include "Signal.h" #include "Sequence.h" #include #include #include #include namespace DDisc { struct SignalParams; struct TSNO { int iFamily; int iSignal; inline bool operator ==(const TSNO& tsno) { return (iFamily ==tsno.iFamily && iSignal==tsno.iSignal); } }; class PredicatBase { public: PredicatBase(const MetaInfoBase &rBase); ~PredicatBase(); void create(vector& rPredicates); Operation *getPredicat(int i) const; void getFirstTSNO(TSNO& no) const; TS* getNextTS(TSNO& no) const; TS* getPrevTS(TSNO& no) const; int getAbsoletePos(const TSNO& no) const; int getTSNumber(); private: vector family_size; vector base; const MetaInfoBase &rMIBase; PROPERTY(int, PredicatNumber); }; typedef vector Optimizer; struct SelectionNode { Operation *structure; int ts; TSNO tsno; int predicat; TSNO predicat_tsno; double min_probability; double max_fisher; }; struct SignalParams { double condition_probability; double fisher_criterion; double coverage; double neg_coverage; int distribution_hash; double um_criterion; }; typedef list SelectionStack; class Extractor { public: Extractor(const SequenceBase* pYesBase, const SequenceBase* pNoBase, PredicatBase* pPredicatBase); ~Extractor(void); double progress(); bool step(Signal **result); protected: bool check(Signal *pSignal, SignalParams *pSP); Signal* getNextSignal(const SignalParams* prev_res = NULL); void clearInternalData(void); bool needBranchThisNode(const SignalParams* prev_res) const; bool doBranch(); bool doNext(); bool insertPredicat(Operation *&structure, int ts, Operation* predicat, int *pId = 0, Operation *pParent = 0); bool checkCorrelation(Operation *pOp); bool alreadyFound(Signal *pSignal) const; void addToFound(Signal *pSignal); bool isNewDistribution(int distribution_hash) const; void storeDistribution(int distribution_hash); private: bool m_bFirst; Signal signal; SelectionStack selection_stack; SignalParams m_SP; const SequenceBase* m_pYesBase; const SequenceBase* m_pNoBase; PredicatBase* m_pPredicatBase; set m_AlreadyFound; set m_DistributionHash; PROPERTY(double, FisherBound); PROPERTY(double, ProbabilityBound); PROPERTY(double, InterestFisher); PROPERTY(double, InterestProbability); PROPERTY(double, CoverageBound); PROPERTY(int, MaxComplexity); PROPERTY(int, MinComplexity); PROPERTY(double, MinCorrelationOnPos); PROPERTY(double, MaxCorrelationOnPos); PROPERTY(double, MinCorrelationOnNeg); PROPERTY(double, MaxCorrelationOnNeg); MODIFIABLE_FLAG( CorrelationImportant ); MODIFIABLE_FLAG( CheckFisherMinimization ); MODIFIABLE_FLAG( StoreOnlyDifferent ); PROPERTY(double, UmBound); PROPERTY(int, UmSamplesBound); MODIFIABLE_FLAG( UmEnabled); }; } #endif // _EXTRACTOR_Hugene-1.9.8/src/plugins/expert_discovery/src/DDisc/statmath.cpp0000644000175000017500000000064211651544323023274 0ustar ilyailya//**************************************************************************** // File name: StatMath.cpp // Title: DiscoveryLib // Version: 1.0 // Author: // Creation Date: 26.02.2005 . // // Description: // //**************************************************************************** #include "statmath.h" ugene-1.9.8/src/plugins/expert_discovery/src/DDisc/Signal.h0000644000175000017500000002012711651544323022331 0ustar ilyailya// Signal.h: Complex signal logic realiztion classes // ////////////////////////////////////////////////////////////////////// #if !defined(ISIGNAL_H__INCLUDED_) #define ISIGNAL_H__INCLUDED_ #include #include "definitions.h" namespace DDisc { /** * Type of operation in complex signal */ enum EOpType { OP_UNDEFINED, OP_INTERVAL, OP_REITERATION, OP_DISTANCE, OP_TS }; class Context; class Sequence; class Operation; /** * Class representing complex signal */ class Signal { public: /** * Constructs signal * @param name name of the signal * @param description description of the signal */ Signal(const std::string name = "", const std::string description = ""); /** * Constructs signal * @param operation root operation of the signal * @param name name of the signal * @param description description of the signal */ Signal(Operation *operation, const std::string name = "", const std::string description = ""); virtual ~Signal(); /** * Attaches operation to the signal * @param operation root operation of the signal */ void attach(Operation *operation); /** * Detaches all operations */ void detach(); /** * Creates compatible search context * @return Search context, that can be used to find signal */ Context& createCompartibleContext() const; /** * Searches for the next occurence of signal in the sequence. * @param rSeq sequence to find in * @param rContext search context * @return true if signal was found, else false */ virtual bool find(const Sequence& rSeq, Context &rContext) const; /** * Returns root operation of the signal */ inline Operation *getSignal() const { return pSignal; } /** * Makes a signal copy and return it */ Signal* clone() const; /** * Calculates hash code of signal */ int getHash() const; /** * Checks if signal is well defined */ bool check() const; private: Operation *pSignal; /** * Signal name */ PROPERTY(std::string, Name); /** * Signal description */ PROPERTY(std::string, Description); /** * If PriorParamsDefined set to true, then prior * parameters of signal was define */ MODIFIABLE_FLAG(PriorParamsDefined); /** * Expected signal probability */ PROPERTY(double, PriorProbability); /** * Expected signal fisher criteria level */ PROPERTY(double, PriorFisher); /** * Expected positive coverage */ PROPERTY(double, PriorPosCoverage); /** * Expected negative coverage */ PROPERTY(double, PriorNegCoverage); }; /** * Abstract complex signal operation. */ class Operation { public: Operation(); virtual ~Operation(); /** * Creates compatible search context * @return Search context, that can be used to find operation */ virtual Context& createCompartibleContext() const = 0; /** * Searches for the next occurence of operation in the sequence. * @param rSeq sequence to find in * @param rContext search context * @return true if signal was found, else false */ virtual bool find(const Sequence& rSeq, Context &rContext) const = 0; /** * @return string description of operation and parameters */ virtual const std::string getDescription() const = 0; /** * Retrieves i-th operation argument * @param i index of argument to be returned * @return i-th argument of operation */ virtual Operation* getArgument(int i) const =0; /** * Sets i-th operation argument * @param operation argument to be set * @param i index of argument to be set */ virtual void setArgument(Operation* operation, int i) =0; /** * @return number of arguments */ virtual int getArgumentNumber() const =0; /** * @return operation type * @see EOpType */ virtual EOpType getType() const =0; /** * Makes an operation copy and return it */ virtual Operation* Clone() const =0; /** * Checks if operation is well defined */ virtual bool check() const; /** * Clear operation arguments */ void detach(); /** * Calculates hash code of operation */ virtual int getHash(int level = 0) const =0; }; /** * Abstract unary operation */ class UnaryOperation : public Operation { public: UnaryOperation(); virtual ~UnaryOperation(); virtual Operation* getArgument(int i = 0) const; virtual void setArgument(Operation*, int i = 0); virtual int getArgumentNumber() const; private: Operation *pArgument; }; /** * Abstract binary operation */ class BinaryOperation : public Operation { public: BinaryOperation(); virtual ~BinaryOperation(); virtual Operation* getArgument(int i) const; virtual void setArgument(Operation*, int i); virtual int getArgumentNumber() const; private: Operation *pArgument1; Operation *pArgument2; }; /** * Interval operation realization. This operation is used * to restrict interval of sequence where argument should be searched. */ class OpInterval : public UnaryOperation { public: OpInterval(); virtual ~OpInterval(); virtual Context& createCompartibleContext() const; virtual bool find(const Sequence& rSeq, Context &rContext) const; virtual const std::string getDescription() const; virtual EOpType getType() const; virtual Operation* Clone() const; virtual int getHash(int level = 0) const; /** * Interval of sequence where argument should be searched */ PROPERTY(Interval, Int); }; /** * Reiteration operation realization. This operation is used * to find repetitions of argument. */ class OpReiteration : public UnaryOperation { public: OpReiteration(); virtual ~OpReiteration(); virtual Context& createCompartibleContext() const; virtual bool find(const Sequence& rSeq, Context &rContext) const; virtual const std::string getDescription() const; virtual EOpType getType() const; virtual Operation* Clone() const; virtual int getHash(int level = 0) const; /** * Range of repetitions to find */ PROPERTY(Interval, Count); /** * Distance between repetitions */ PROPERTY(Interval, Distance); /** * Type of measurement to use * @see EDistType */ PROPERTY(EDistType, DistanceType); }; /** * Distance operation realization. This binary operation is used to * to find two arguments in specified distance. */ class OpDistance : public BinaryOperation { public: OpDistance(); virtual ~OpDistance(); virtual Context& createCompartibleContext() const; virtual bool find(const Sequence& rSeq, Context &rContext) const; virtual const std::string getDescription() const; virtual EOpType getType() const; virtual Operation* Clone() const; virtual int getHash(int level = 0) const; /** * Set to true if order of arguments is important */ MODIFIABLE_FLAG(OrderImportant); /** * Distance range */ PROPERTY(Interval, Distance); /** * Type of measurement to use * @see EDistType */ PROPERTY(EDistType, DistanceType); }; /** * Terminal symbol(TS) - operation that don't have arguments. TS can be * from marking or can be defined by the word to find in the sequence. */ class TS : public Operation { public: TS(); virtual ~TS(); virtual Context& createCompartibleContext() const; virtual bool find(const Sequence& rSeq, Context &rContext) const; virtual const std::string getDescription() const; virtual Operation* getArgument(int i) const; virtual void setArgument(Operation*, int i); virtual int getArgumentNumber() const; virtual EOpType getType() const; virtual Operation* Clone() const; virtual bool check() const; virtual int getHash(int level = 0) const; protected: static bool compare(const char* seq, unsigned nSeqLen, const char *word, unsigned nWordLen); /** * Set to true if TS is from marking */ MODIFIABLE_FLAG(FromMarking); /** * Word to find in the sequence, if FromMarking is false */ PROPERTY(std::string, Word); /** * Name from marking. Set if from marking true. */ PROPERTY(std::string, Name); /** * Family from marking. Set if from marking true. */ PROPERTY(std::string, Family); }; }; #endif // !defined(ISIGNAL_H__INCLUDED_) ugene-1.9.8/src/plugins/expert_discovery/src/DDisc/MetaInfo.h0000644000175000017500000000712311651544323022617 0ustar ilyailya#if !defined(META_INFO_H__INCLUDED_) #define META_INFO_H__INCLUDED_ #include "definitions.h" #include #include using namespace std; namespace DDisc { /** * This class contains description about elementary signal from marking (also * known as terminal symbol). */ class MetaInfo { public: MetaInfo(void); MetaInfo(const MetaInfo&); const MetaInfo& operator =(const MetaInfo&); virtual ~MetaInfo(void); /** * Deserialize class from stream */ virtual std::istream& load(std::istream& in); /** * Serialize class from stream */ virtual std::ostream& save(std::ostream& out) const; PROPERTY(int, No); /** * Name of item */ PROPERTY(string, Name); /** * Method, used to find this item */ PROPERTY(string, MethodName); }; /** * Family of elementary signals from marking */ class Family { public: Family(); Family(const Family&); const Family& operator =(const Family&); virtual ~Family(); /** * Deserialize class from stream */ virtual std::istream& load(std::istream& in); /** * Serialize class from stream */ virtual std::ostream& save(std::ostream& out) const; /** * Extracts particular signal information from family * @param no number of elementary signal to extract * @return elementary signal information * @see MetaInfo */ const MetaInfo& getMetaInfo(int no) const; /** * Extracts particular signal information from family (const version) * @param no number of elementary signal to extract * @return elementary signal information * @see MetaInfo */ MetaInfo& getMetaInfo(int no); /** * Extracts particular signal information from family * @param name name of elementary signal to extract * @return elementary signal information * @see MetaInfo */ const MetaInfo& getMetaInfo(const string name) const; /** * @return number of signals in family */ int getSignalNumber() const; /** * Add signal information to family */ void AddInfo(const MetaInfo& info); private: typedef vector Data; Data data; /** * Name of the family */ PROPERTY(string, Name); }; /** * Elementary signal description database */ class MetaInfoBase { public: MetaInfoBase(); virtual ~MetaInfoBase(); /** * Deserialize class from stream */ virtual std::istream& load(std::istream& in); /** * Serialize class from stream */ virtual std::ostream& save(std::ostream& out) const; /** * Extracts particular family from DB * @param no number of family to extract * @return signal family * @see Family */ const Family& getSignalFamily(int no) const; /** * Extracts particular family from DB (const version) * @param no number of family to extract * @return signal family * @see Family */ Family& getSignalFamily(int no); /** * Extracts particular family from DB * @param name name of family to extract * @return signal family * @see Family */ const Family& getSignalFamily(const string name) const; /** * @return number of families in DB */ int getFamilyNumber() const; /** * Clears database */ void clear(); /** * Adds family to DB */ void addFamily(const Family& rFamily); /** * inserts signal to family * @param family name of family * @param mi signal information to insert */ void insert(const char* family, MetaInfo& mi); private: MetaInfoBase(const MetaInfoBase&); const MetaInfoBase& operator =(const MetaInfoBase&); typedef vector Data; Data data; }; }; #endif // META_INFO_H__INCLUDED_ ugene-1.9.8/src/plugins/expert_discovery/src/ExpertDiscoveryControlMrkDialog.h0000644000175000017500000000072311651544323026420 0ustar ilyailya#pragma once #include namespace U2 { class ExpertDiscoveryControlMrkDialog : public QDialog, public Ui_ExpertDiscoveryControlMrkDialog{ Q_OBJECT public: ExpertDiscoveryControlMrkDialog(QWidget *parent); virtual void accept(); QString getFirstFileName() const {return firstFileName;} protected slots: void sl_openFirstFile(); private: QString firstFileName; QString filter; }; }//namespace ugene-1.9.8/src/plugins/expert_discovery/src/ExpertDiscoveryTreeWidgetsCtrl.cpp0000644000175000017500000012464711651544323026630 0ustar ilyailya#include "ExpertDiscoveryTreeWidgetsCtrl.h" #include #include #include namespace U2 { EDProjectTree::EDProjectTree(QWidget *parent, ExpertDiscoveryData &d) :QTreeWidget(parent) ,edData(d) ,root(edData.getRootFolder()) ,seqRoot(d) ,sortField(ED_FIELD_PROBABILITY) ,sortOrd(ED_ORDER_DECREASING) ,updatingItem(false) { createPopupsAndActions(); updateTree(ED_UPDATE_ALL); } EDProjectItem* EDProjectTree::findEDItem(void* pData){ return const_cast(root.findItemConnectedTo(pData)); } CSFolder* EDProjectTree::findFolder(EDPICSDirectory *pFolder) const { return const_cast(pFolder->getFolder()); } Signal*EDProjectTree::findSignal(const Signal* pSignal) const { return const_cast(pSignal); } void EDProjectTree::addSubitem(EDProjectItem* subItem, EDProjectItem* parent){ parent->addChild(subItem); updateTree(ED_ITEM_ADDED, subItem); } void EDProjectTree::updateTree(int flag, EDProjectItem* item){ switch (flag) { case ED_UPDATE_ALL : remake(); break; case ED_ITEM_NAME_CHANGED : updateItem(item); break; case ED_ITEM_STATE_CHANGED : updateItemState(item); break; case ED_ITEM_ADDED : internalRemake(item, dynamic_cast(dynamic_cast(item)->parent())); break; case ED_ITEM_DELETED : /*deleteItem(pItem);*/ break; case ED_CURRENT_ITEM_CHANGED : setCurrentItem(item); break; case ED_UPDATE_CHILDREN : updateChildren(item); break; case ED_MRK_UPDATE : updateMarkup(); break; }; } void EDProjectTree::remake(){ addTopLevelItem(&seqRoot); seqRoot.setText(0,"Sequences"); seqRoot.setIcon(0,QIcon(":expert_discovery/images/sequences.png")); seqRoot.setExpanded(true); seqRoot.update(true); for (int i = 0; i < seqRoot.childCount(); i++){ EDProjectItem* item = dynamic_cast(seqRoot.child(i)); if(item){ internalRemake(item, &seqRoot); } } addTopLevelItem(&mrkRoot); mrkRoot.setText(0,"Markup"); mrkRoot.setIcon(0,QIcon(":expert_discovery/images/mrkroot.png")); mrkRoot.updMarkup(edData); for (int i = 0; i < mrkRoot.childCount(); i++){ EDProjectItem* item = dynamic_cast(mrkRoot.child(i)); if(item){ internalRemake(item, &mrkRoot); } } addTopLevelItem(&root); root.setText(0,"Complex signals"); root.setIcon(0,QIcon(":expert_discovery/images/csroot.png")); root.update(true); for (int i = 0; i < root.childCount(); i++){ EDProjectItem* item = dynamic_cast(root.child(i)); if(item){ internalRemake(item, &root); } } } void EDProjectTree::clearTree(){ root.takeChildren(); mrkRoot.takeChildren(); } void EDProjectTree::internalRemake(EDProjectItem* subItem, EDProjectItem* parent){ subItem->setText(0, subItem->getName()); subItem->setIcon(0, getItemIcon(subItem)); subItem->setSortOrd(sortOrd); subItem->setSortField(sortField); for(int i = 0; i < subItem->childCount(); i++){ EDProjectItem* item = dynamic_cast(subItem->child(i)); if (item){ connect(item, SIGNAL(si_getMetaInfoBase()), SLOT(sl_setMetainfoBase())); internalRemake(item, subItem); } } subItem->sortChildren(0, Qt::AscendingOrder); updateItemState(subItem); } void EDProjectTree::updateItem(EDProjectItem* pItem){ pItem->setText(0, pItem->getName()); pItem->setIcon(0, getItemIcon(pItem)); QFont curFont = pItem->font(0); if (edData.isSignalSelected(pItem)) curFont.setBold(true); else curFont.setBold(false); EDPISequence* seq = dynamic_cast(pItem); if(seq){ if(edData.isSequenceSelected(seq)){ curFont.setBold(true); } else{ curFont.setBold(false); } } pItem->setFont(0, curFont); } void EDProjectTree::updateItemState(EDProjectItem *pItem) { QFont curFont = pItem->font(0); if (edData.isSignalSelected(pItem)) curFont.setBold(true); else curFont.setBold(false); pItem->setFont(0, curFont); } void EDProjectTree::updateChildren(EDProjectItem* pItem){ for (int i=0; ichildCount(); i++){ EDProjectItem* ch = dynamic_cast(pItem->child(i)); internalRemake(ch, pItem); } pItem->sortChildren(0, Qt::AscendingOrder); } void EDProjectTree::updateMarkup(){ mrkRoot.updMarkup(edData); for (int i = 0; i < mrkRoot.childCount(); i++){ EDProjectItem* item = dynamic_cast(mrkRoot.child(i)); if(item){ internalRemake(item, &mrkRoot); } } } void EDProjectTree::updateSequenceBase(EItemType type){ if(type == PIT_SEQUENCEROOT){ seqRoot.update(true); for (int i = 0; i < seqRoot.childCount(); i++){ EDProjectItem* item = dynamic_cast(seqRoot.child(i)); if(item){ item->update(true); internalRemake(item, &seqRoot); } } }else{ for (int i = 0; i < seqRoot.childCount(); i++){ EDProjectItem* item = dynamic_cast(seqRoot.child(i)); if(item){ if(item->getType() == type){ item->update(true); internalRemake(item, &seqRoot); } } } } } void EDProjectTree::sl_propChanged(EDProjectItem* item, const EDPIProperty* prop, QString newVal){ switch (item->getType()) { case PIT_CS_FOLDER: if (prop->getName().compare("Name", Qt::CaseInsensitive) == NULL) { EDPICSDirectory* pPI = dynamic_cast(item); CSFolder* pFolder = findFolder(pPI); const CSFolder* pParentFolder = pFolder->getParentFolder(); int nIndex = pParentFolder->getFolderIndexByName(newVal); if (nIndex>=0) { QMessageBox mb(QMessageBox::Critical, tr("Rename error"), tr("Folder already exist")); mb.exec(); return; } pFolder->setName(newVal); updateTree(ED_ITEM_NAME_CHANGED, (EDProjectItem *)pPI); updateTree(ED_CURRENT_ITEM_CHANGED, (EDProjectItem *) pPI); } return; case PIT_CS:{ //updatingItem = true; EDPICS *pPI = dynamic_cast(item); EDPICSDirectory *pParent = dynamic_cast(dynamic_cast(pPI)->parent()); assert(pPI != NULL); assert(pParent != NULL); Signal *pSignal = findSignal(pPI->getSignal()); QString strName = "Name"; QString strDescription = "Description"; QString strPropName = prop->getName(); if (strPropName.compare(strName, Qt::CaseInsensitive)==0) { CSFolder* pFolder = findFolder(pParent); int nIndex = pFolder->getSignalIndexByName(newVal); if (nIndex >= 0) { QMessageBox mb(QMessageBox::Question, tr("Signal rename"), tr("Signal with the same name already exist. Replace?"), QMessageBox::Ok|QMessageBox::Cancel); if(mb.exec()==QMessageBox::Ok) pFolder->deleteSignal(nIndex); else return; } pSignal->setName(newVal.toStdString()); } else if (strPropName.compare(strDescription, Qt::CaseInsensitive) == 0) { pSignal->setDescription(newVal.toStdString()); } else assert(0); pParent->update(true); // updatingItem = false; EDProjectItem* pCurItem = const_cast(pParent->findItemConnectedTo(pSignal)); updateTree(ED_UPDATE_CHILDREN, (EDProjectItem* ) pParent); updateTree(ED_CURRENT_ITEM_CHANGED, pCurItem); return; } case PIT_CSN_UNDEFINED: case PIT_CSN_DISTANCE: case PIT_CSN_REPETITION: case PIT_CSN_INTERVAL: case PIT_CSN_WORD: case PIT_CSN_MRK_ITEM: onCSNPropertyChanged(item, prop, newVal); return; } } void EDProjectTree::mousePressEvent(QMouseEvent *e){ if(e->button() == Qt::RightButton){ QTreeWidgetItem* curItem = itemAt(e->pos()); setCurrentItem(curItem, 0); EDProjectItem* projItem = dynamic_cast(curItem); if(projItem){ QMenu* curMenu = chosePopupMen(projItem); if(curMenu){ curMenu->popup(e->globalPos()); } } } QTreeWidget::mousePressEvent(e); } void EDProjectTree::mouseDoubleClickEvent(QMouseEvent *e){ QTreeWidgetItem* curItem = itemAt(e->pos()); setCurrentItem(curItem, 0); sl_addToShown(); QTreeWidget::mouseDoubleClickEvent(e); } QMenu* EDProjectTree::chosePopupMen(EDProjectItem* pItem){ if(pItem->getType() == PIT_CS){ EDPICS* pItem = dynamic_cast(currentItem()); if(pItem){ if(!edData.isSignalSelected(pItem)){ selDeselSigAction->setText(tr("Select signal")); }else{ selDeselSigAction->setText(tr("Deselect signal")); } setCurPriorAction->setEnabled(pItem->getProcessedSignal(edData) != NULL); clearCurPriorAction->setEnabled(pItem->getSignal()->isPriorParamsDefined() && !edData.isSignalSelected(pItem)); }else{ selDeselSigAction->setText(tr("Select/deselect signal")); setCurPriorAction->setEnabled(true); clearCurPriorAction->setEnabled(true); } return popupMenuCS; }else if(pItem->getType() == PIT_CS_FOLDER){ EDPICSDirectory* piDir = dynamic_cast(pItem); if(!piDir){ return NULL; } return popupMenuDir; }else if (pItem->getType() == PIT_CS_ROOT){ return popupMenuDirRoot; }else if(pItem->getType() == PIT_MRK_ROOT){ markupLettersAction->setEnabled(!edData.isLettersMarkedUp() && (edData.getNegSeqBase().getSize() > 0) && (edData.getPosSeqBase().getSize() > 0) ); loadMarkupAction->setEnabled(edData.getPosSeqBase().getSize() > 0 && edData.getNegSeqBase().getSize() > 0); return popupMenuMrkRoot; }else if(pItem->getType() == PIT_SEQUENCE || pItem->getType() == PIT_CONTROLSEQUENCE){ return popupMenuSequence; }else if(pItem->getType() == PIT_POSSEQUENCEBASE || pItem->getType() == PIT_NEGSEQUENCEBASE || pItem->getType() == PIT_CONTROLSEQUENCEBASE){ EDPISequenceBase* pBaseItem = dynamic_cast(pItem); if (!pItem) { return NULL; } generateReportAction->setEnabled(pBaseItem->getSequenceBase().getSize() != 0); showFirstSequencesAction->setEnabled(pBaseItem->getSequenceBase().getSize() != 0); return popupMenuSequenceBase; } return NULL; } QIcon EDProjectTree::getItemIcon(EDProjectItem* pItem){ EItemType iType = pItem->getType(); switch (iType) { case PIT_SEQUENCEROOT: return QIcon(":expert_discovery/images/sequences.png"); case PIT_POSSEQUENCEBASE: return QIcon(":expert_discovery/images/posseq.png"); case PIT_NEGSEQUENCEBASE: return QIcon(":expert_discovery/images/negseq.png"); case PIT_CONTROLSEQUENCEBASE: return QIcon(":expert_discovery/images/control.png"); case PIT_SEQUENCE: return QIcon(":expert_discovery/images/sequence.png"); case PIT_CONTROLSEQUENCE: return QIcon(":expert_discovery/images/sequence.png"); case PIT_CS_ROOT: return QIcon(":expert_discovery/images/csroot.png"); case PIT_CS_FOLDER: return QIcon(":expert_discovery/images/folder.png"); case PIT_CS: return QIcon(":expert_discovery/images/cs.png"); case PIT_CSN_UNDEFINED: return QIcon(":expert_discovery/images/undefined.png"); case PIT_CSN_DISTANCE: return QIcon(":expert_discovery/images/distance.png"); case PIT_CSN_REPETITION: return QIcon(":expert_discovery/images/repetition.png"); case PIT_CSN_INTERVAL: return QIcon(":expert_discovery/images/interval.png"); case PIT_CSN_MRK_ITEM: return QIcon(":expert_discovery/images/ts.png"); case PIT_MRK_ITEM: return QIcon(":expert_discovery/images/ts.png"); case PIT_CSN_WORD: return QIcon(":expert_discovery/images/ts.png"); case PIT_MRK_ROOT: return QIcon(":expert_discovery/images/mrkroot.png"); case PIT_MRK_FAMILY: return QIcon(":expert_discovery/images/folder.png"); default: return QIcon(); } return QIcon(); } void EDProjectTree::createPopupsAndActions(){ newFolderAction = new QAction(tr("New folder"), this); connect(newFolderAction, SIGNAL(triggered(bool)), SLOT(sl_newFolder())); newSignalAction= new QAction(tr("New signal"), this); connect(newSignalAction, SIGNAL(triggered(bool)), SLOT(sl_newSignal())); deletePIAction = new QAction(tr("Delete"), this); connect(deletePIAction, SIGNAL(triggered(bool)), SLOT(sl_deletePI())); selAllSigAction = new QAction(tr("Select all signals"), this); connect(selAllSigAction, SIGNAL(triggered(bool)), SLOT(sl_selAllSig())); deselAllSigAction = new QAction(tr("Deselect all signals"), this); connect(deselAllSigAction, SIGNAL(triggered(bool)), SLOT(sl_deselAllSig())); setPriorAllSigAction = new QAction(tr("Set prior parameters of all signals"), this); connect(setPriorAllSigAction, SIGNAL(triggered(bool)), SLOT(sl_setPriorAllSig())); clearPriorAllSigAction = new QAction(tr("Clear prior parameters of all signals"), this); connect(clearPriorAllSigAction, SIGNAL(triggered(bool)), SLOT(sl_clearPriorAllSig())); selDeselSigAction = new QAction(tr("Select/deselect signal"), this); connect(selDeselSigAction, SIGNAL(triggered(bool)), SLOT(sl_selDeselSig())); setCurPriorAction = new QAction(tr("Set current params as prior"), this); connect(setCurPriorAction, SIGNAL(triggered(bool)), SLOT(sl_setCurPrior())); clearCurPriorAction = new QAction(tr("Clear prior params"), this); connect(clearCurPriorAction, SIGNAL(triggered(bool)), SLOT(sl_clearCurPrior())); markupLettersAction = new QAction(tr("Markup letters"), this); connect(markupLettersAction, SIGNAL(triggered(bool)), SLOT(sl_markupLetters())); loadMarkupAction = new QAction(tr("Load markup"), this); connect(loadMarkupAction, SIGNAL(triggered(bool)), SLOT(sl_loadMarkup())); showSequenceAction = new QAction(tr("Show one sequence"), this); connect(showSequenceAction, SIGNAL(triggered(bool)), SLOT(sl_showSequence())); addToShownAction = new QAction(tr("Add to displayed"), this); connect(addToShownAction, SIGNAL(triggered(bool)), SLOT(sl_addToShown())); generateReportAction = new QAction(tr("Generate report"), this); connect(generateReportAction, SIGNAL(triggered(bool)), SLOT(sl_generateReport())); clearDisplayedAction = new QAction(tr("Clear displayed sequences area"), this); connect(clearDisplayedAction, SIGNAL(triggered(bool)), SLOT(sl_clearDisplayed())); showFirstSequencesAction = new QAction(tr("Show sequences"), this); connect(showFirstSequencesAction, SIGNAL(triggered(bool)), SLOT(sl_showFirstSequences())); sortGroup = new QActionGroup(this); sortOrdGroup = new QActionGroup(this); sortFieldGroup = new QActionGroup(this); connect(sortOrdGroup, SIGNAL(triggered(QAction* )), SLOT(sl_sortOrd(QAction* ))); connect(sortFieldGroup, SIGNAL(triggered(QAction* )), SLOT(sl_sortField(QAction* ))); sortOrdIncrAction = new QAction(tr("Increasing"), this); sortOrdDecrAction = new QAction(tr("Decreasing"), this); sortFieldCoverAction = new QAction(tr("Coverage"), this); sortFieldFisherAction = new QAction(tr("Fisher"), this); sortFieldNameAction = new QAction(tr("Name"), this); sortFieldProbAction = new QAction(tr("Probability"), this); sortOrdIncrAction->setCheckable(true); sortOrdDecrAction->setCheckable(true); sortOrdDecrAction->setChecked(true); sortFieldCoverAction->setCheckable(true); sortFieldFisherAction->setCheckable(true); sortFieldNameAction->setCheckable(true); sortFieldProbAction->setCheckable(true); sortFieldProbAction->setChecked(true); sortOrdGroup->addAction(sortOrdIncrAction); sortOrdGroup->addAction(sortOrdDecrAction); sortFieldGroup->addAction(sortFieldCoverAction); sortFieldGroup->addAction(sortFieldFisherAction); sortFieldGroup->addAction(sortFieldNameAction); sortFieldGroup->addAction(sortFieldProbAction); popupMenuCS = new QMenu(this); popupMenuCS->addAction(selDeselSigAction); popupMenuCS->addAction(deletePIAction); popupMenuCS->addSeparator(); popupMenuCS->addAction(setCurPriorAction); popupMenuCS->addAction(clearCurPriorAction); popupMenuDir = new QMenu(this); popupMenuDir->addAction(newFolderAction); popupMenuDir->addAction(newSignalAction); popupMenuDir->addSeparator(); popupMenuDir->addAction(deletePIAction); popupMenuDir->addSeparator(); popupMenuDir->addAction(selAllSigAction); popupMenuDir->addAction(deselAllSigAction); //popupMenuDir->addAction(setPriorAllSigAction); //popupMenuDir->addAction(clearPriorAllSigAction); popupMenuDirRoot = new QMenu(this); popupMenuDirRoot->addAction(newFolderAction); popupMenuDirRoot->addAction(newSignalAction); popupMenuDirRoot->addSeparator(); popupMenuDirRoot->addAction(selAllSigAction); popupMenuDirRoot->addAction(deselAllSigAction); //popupMenuDirRoot->addAction(setPriorAllSigAction); //popupMenuDirRoot->addAction(clearPriorAllSigAction); QMenu* sortMenu = new QMenu(tr("Sort"), this); QMenu* fieldMenu = new QMenu(tr("Field"), this); QMenu* ordMenu = new QMenu(tr("Order"), this); fieldMenu->addActions(sortFieldGroup->actions()); ordMenu->addActions(sortOrdGroup->actions()); sortMenu->addMenu(ordMenu); sortMenu->addMenu(fieldMenu); popupMenuDirRoot->addMenu(sortMenu); popupMenuMrkRoot = new QMenu(this); popupMenuMrkRoot->addAction(markupLettersAction); popupMenuMrkRoot->addAction(loadMarkupAction); popupMenuSequence = new QMenu(this); popupMenuSequence->addAction(showSequenceAction); popupMenuSequence->addAction(addToShownAction); popupMenuSequence->addAction(clearDisplayedAction); popupMenuSequenceBase = new QMenu(this); popupMenuSequenceBase->addAction(generateReportAction); popupMenuSequenceBase->addAction(showFirstSequencesAction); } void EDProjectTree::onCSNPropertyChanged(EDProjectItem* pItem, const EDPIProperty* pProperty, QString strNewValue){ EDPICSNode* pCSN = dynamic_cast(pItem); Operation* pOp = pCSN->getOperation(); EDProjectItem *pParent = dynamic_cast(dynamic_cast(pItem)->parent()); QString strType = "Type"; if (pProperty->getName().compare(strType, Qt::CaseInsensitive) == 0) { Operation* pNewOp = createCSN(EDPIPropertyTypeListCSNodeTypes::getInstance()->getValueId(strNewValue)); assert(pNewOp != NULL); if (pParent->getType() == PIT_CS) { updatingItem = true; EDPICS *pPICS = dynamic_cast(pParent); connect(pPICS, SIGNAL(si_getMetaInfoBase()), SLOT(sl_setMetainfoBase())); Signal *pSignal = findSignal(pPICS->getSignal()); pSignal->attach(pNewOp); Operation* op = pPICS->getOperation(); //if(op==NULL){ pPICS->setOperation(pSignal->getSignal()); //} pPICS->update(true); updatingItem = false; } else { updatingItem = true; EDPICSNode *pPICS = dynamic_cast(pParent); Operation* pParentOp = pPICS->getOperation(); int id; for (id=0; idgetArgumentNumber(); id++) { if (pParentOp->getArgument(id) == pOp) break; } assert( id >=0 && id < pParentOp->getArgumentNumber() ); pParentOp->setArgument(pNewOp, id); connect(pParent, SIGNAL(si_getMetaInfoBase()), SLOT(sl_setMetainfoBase())); pParent->update(true); updatingItem = false; } delete pOp; const EDProjectItem *pNewItemc = pParent->findItemConnectedTo(pNewOp); EDProjectItem *pNewItem = const_cast(pNewItemc); connect(pNewItem, SIGNAL(si_getMetaInfoBase()), SLOT(sl_setMetainfoBase())); updateTree(ED_UPDATE_CHILDREN, (EDProjectItem* ) pParent); updateTree(ED_CURRENT_ITEM_CHANGED, pNewItem); } else { switch (pCSN->getType()) { case PIT_CSN_DISTANCE : onDistancePropertyChanged(pCSN, pProperty, strNewValue); break; case PIT_CSN_REPETITION : onRepetitionPropertyChanged(pCSN, pProperty, strNewValue); break; case PIT_CSN_INTERVAL : onIntervalPropertyChanged(pCSN, pProperty, strNewValue); break; case PIT_CSN_WORD : onWordPropertyChanged(pCSN, pProperty, strNewValue); break; case PIT_CSN_MRK_ITEM : onMrkItemPropertyChanged(pCSN, pProperty, strNewValue); break; default: assert(0); } } while (pParent->getType() != PIT_CS) { pParent->update(false); //pParent = findEDItem(dynamic_cast(dynamic_cast(pParent)->parent())); pParent = dynamic_cast(dynamic_cast(pParent)->parent()); connect(pParent, SIGNAL(si_getMetaInfoBase()), SLOT(sl_setMetainfoBase())); } pParent->update(false); if(edData.isSignalSelected(pItem)) edData.clearScores(); } void EDProjectTree::onDistancePropertyChanged(EDProjectItem* pItem, const EDPIProperty* pProperty, QString strNewValue){ EDPICSNDistance* pDist = dynamic_cast(pItem); OpDistance* pOp = dynamic_cast(pDist->getOperation()); QString strFrom = "Distance from"; QString strTo = "Distance to"; QString strOrder = "Order"; QString strDistanceType = "Distance type"; if (pProperty->getName().compare(strFrom, Qt::CaseInsensitive) == 0) { DDisc::Interval iDist = pOp->getDistance(); int nValue =0; if (parse(strNewValue.toStdString().c_str(),"%d", &nValue) && nValue>=0 && nValue<=iDist.getTo()) { iDist.setFrom(nValue); pOp->setDistance(iDist); } else{ QMessageBox mb(QMessageBox::Critical, tr("Error"), tr("The value must be positive integer which is less than the higher bound")); mb.exec(); } } else if (pProperty->getName().compare(strTo, Qt::CaseInsensitive) == 0) { DDisc::Interval iDist = pOp->getDistance(); int nId = EDPIPropertyTypeUnsignedIntWithUnl::getInstance()->getValueId(strNewValue); int nValue =0; bool bError = false; if (nId < 0) { if (bError = !parse(strNewValue.toStdString().c_str(),"%d", &nValue) || nValue<0) { QMessageBox mb(QMessageBox::Critical, tr("Error"), tr("The value must be positive integer which is less than the higher bound")); mb.exec(); } } else nValue = PINF; if (!bError) { if (nValue >= iDist.getFrom()) { iDist.setTo(nValue); pOp->setDistance(iDist); } else{ QMessageBox mb(QMessageBox::Critical, tr("Error"), tr("The value must be grater than the lower bound")); mb.exec(); } } } else if (pProperty->getName().compare(strOrder, Qt::CaseInsensitive) == 0) { int nId = EDPIPropertyTypeBool::getInstance()->getValueId(strNewValue); if (nId == EDPIPropertyTypeBool::False) pOp->setOrderImportant(false); else pOp->setOrderImportant(true); } else if (pProperty->getName().compare(strDistanceType, Qt::CaseInsensitive) == 0) { int nId = EDPIPropertyTypeDistType::getInstance()->getValueId(strNewValue); pOp->setDistanceType((EDistType)nId); } else assert(0); pDist->update(true); EDProjectItem* pIt = dynamic_cast(dynamic_cast(pDist)->parent()); updateTree(ED_UPDATE_CHILDREN, (EDProjectItem* ) pIt); updateTree(ED_CURRENT_ITEM_CHANGED, pDist); } void EDProjectTree::onRepetitionPropertyChanged(EDProjectItem* pItem, const EDPIProperty* pProperty, QString strNewValue){ EDPICSNRepetition* pDist = dynamic_cast(pItem); OpReiteration* pOp = dynamic_cast(pDist->getOperation()); QString strFrom = "Distance from"; QString strTo = "Distance to"; QString strDistanceType = "Distance type"; QString strCountFrom = "Count from"; QString strCountTo = "Count to"; if (pProperty->getName().compare(strFrom, Qt::CaseInsensitive) == 0) { DDisc::Interval iDist = pOp->getDistance(); int nValue =0; if (parse(strNewValue.toStdString().c_str(),"%d", &nValue) && nValue>=0 && nValue<=iDist.getTo()) { iDist.setFrom(nValue); pOp->setDistance(iDist); } else{ QMessageBox mb(QMessageBox::Critical, tr("Error"), tr("The value must be positive integer which is less than the higher bound")); mb.exec(); } } else if (pProperty->getName().compare(strTo, Qt::CaseInsensitive) == 0) { DDisc::Interval iDist = pOp->getDistance(); int nId = EDPIPropertyTypeUnsignedIntWithUnl::getInstance()->getValueId(strNewValue); int nValue =0; bool bError = false; if (nId < 0) { if (bError = !parse(strNewValue.toStdString().c_str(),"%d", &nValue)) { QMessageBox mb(QMessageBox::Critical, tr("Error"), tr("The value must be positive integer which is less than the higher bound")); mb.exec(); } } else nValue = PINF; if (!bError) { if (nValue >= iDist.getFrom()) { iDist.setTo(nValue); pOp->setDistance(iDist); } else{ QMessageBox mb(QMessageBox::Critical, tr("Error"), tr("The value must be grater than the lower bound")); mb.exec(); } } } else if (pProperty->getName().compare(strCountFrom, Qt::CaseInsensitive) == 0) { DDisc::Interval iCount = pOp->getCount(); int nValue =0; if (parse(strNewValue.toStdString().c_str(),"%d", &nValue) && nValue>=0 && nValue<=iCount.getTo() && nValue<=10) { iCount.setFrom(nValue); pOp->setCount(iCount); } else { QMessageBox mb(QMessageBox::Critical, tr("Error"), tr("The value must be positive integer which is less than the higher bound")); mb.exec(); } } else if (pProperty->getName().compare(strCountTo, Qt::CaseInsensitive) == 0) { DDisc::Interval iCount = pOp->getCount(); int nValue =0; if (!parse(strNewValue.toStdString().c_str(),"%d", &nValue)) { QMessageBox mb(QMessageBox::Critical, tr("Error"), tr("The value must be positive integer which is less than the higher bound")); mb.exec(); } else { if (nValue >= iCount.getFrom()) { iCount.setTo(nValue); pOp->setCount(iCount); } else{ QMessageBox mb(QMessageBox::Critical, tr("Error"), tr("The value must be grater than the lower bound")); mb.exec(); } } } else if (pProperty->getName().compare(strDistanceType, Qt::CaseInsensitive) == 0) { int nId = EDPIPropertyTypeDistType::getInstance()->getValueId(strNewValue); pOp->setDistanceType((EDistType)nId); } else assert(0); pDist->update(true); EDProjectItem* pIt = dynamic_cast(dynamic_cast(pDist)->parent()); updateTree(ED_UPDATE_CHILDREN, (EDProjectItem* ) pIt); updateTree(ED_CURRENT_ITEM_CHANGED, pDist); } void EDProjectTree::onIntervalPropertyChanged(EDProjectItem* pItem, const EDPIProperty* pProperty, QString strNewValue){ EDPICSNInterval* pInt = dynamic_cast(pItem); OpInterval* pOp = dynamic_cast(pInt->getOperation()); QString strFrom = "Distance from"; QString strTo = "Distance to"; if (pProperty->getName().compare(strFrom, Qt::CaseInsensitive) == 0) { DDisc::Interval iInt = pOp->getInt(); int nValue =0; if (parse(strNewValue.toStdString().c_str(),"%d", &nValue) && nValue>=0 && nValue<=iInt.getTo()) { iInt.setFrom(nValue); pOp->setInt(iInt); } else{ QMessageBox mb(QMessageBox::Critical, tr("Error"), tr("The value must be positive integer which is less than the higher bound")); mb.exec(); } } else if (pProperty->getName().compare(strTo, Qt::CaseInsensitive) == 0) { DDisc::Interval iInt = pOp->getInt(); int nId = EDPIPropertyTypeUnsignedIntWithUnl::getInstance()->getValueId(strNewValue); int nValue =0; bool bError = false; if (nId < 0) { if (bError = !parse(strNewValue.toStdString().c_str(),"%d", &nValue)) { QMessageBox mb(QMessageBox::Critical, tr("Error"), tr("The value must be positive integer which is less than the higher bound")); mb.exec(); } } else nValue = PINF; if (!bError) { if (nValue >= iInt.getFrom()) { iInt.setTo(nValue); pOp->setInt(iInt); } else{ QMessageBox mb(QMessageBox::Critical, tr("Error"), tr("The value must be grater than the lower bound")); mb.exec(); } } } else assert(0); pInt->update(true); EDProjectItem* pIt = dynamic_cast(dynamic_cast(pInt)->parent()); updateTree(ED_UPDATE_CHILDREN, (EDProjectItem* ) pIt); updateTree(ED_CURRENT_ITEM_CHANGED, pInt); } void EDProjectTree::onWordPropertyChanged(EDProjectItem* pItem, const EDPIProperty* pProperty, QString strNewValue){ EDPICSNTSWord* pPITS = dynamic_cast(pItem); TS* pOp = dynamic_cast(pPITS->getOperation()); QString strWord = "Word"; if (pProperty->getName().compare(strWord, Qt::CaseInsensitive) == 0) { if (isValidWord15(strNewValue.toStdString().c_str())) pOp->setWord(strNewValue.toUpper().toStdString()); else { QMessageBox mb(QMessageBox::Critical, tr("Error"), tr("The word must be in 15-character code")); mb.exec(); return; } } else assert(0); pPITS->update(true); EDProjectItem* pIt = dynamic_cast(dynamic_cast(pPITS)->parent()); updateTree(ED_UPDATE_CHILDREN, (EDProjectItem* ) pIt); updateTree(ED_CURRENT_ITEM_CHANGED, pPITS); } void EDProjectTree::onMrkItemPropertyChanged(EDProjectItem* pItem, const EDPIProperty* pProperty, QString strNewValue){ QString strFamily = "Family"; QString strSignal = "Signal"; EDPICSNTSMrkItem* pPITS = dynamic_cast(pItem); assert(pPITS!=NULL); TS *pTS = dynamic_cast(pPITS->getOperation()); assert(pTS!=NULL); if (pProperty->getName().compare(strFamily, Qt::CaseInsensitive) == 0) { pTS->setFamily(strNewValue.toStdString().c_str()); } else if (pProperty->getName().compare(strSignal, Qt::CaseInsensitive) == 0) { pTS->setName(strNewValue.toStdString().c_str()); } else assert(0); pPITS->update(true); EDProjectItem* pIt = dynamic_cast(dynamic_cast(pPITS)->parent()); updateTree(ED_UPDATE_CHILDREN, (EDProjectItem* ) pIt); updateTree(ED_CURRENT_ITEM_CHANGED, pPITS); emit si_changeProp(pPITS); } Operation* EDProjectTree::createCSN(int ValueId) const{ switch (ValueId) { case EDPIPropertyTypeListCSNodeTypes::DISTANCE : return new OpDistance; case EDPIPropertyTypeListCSNodeTypes::REPETITION : return new OpReiteration; case EDPIPropertyTypeListCSNodeTypes::INTERVAL : return new OpInterval; case EDPIPropertyTypeListCSNodeTypes::WORD : { TS* pTS = new TS; pTS->setFromMarking(false); return pTS; } case EDPIPropertyTypeListCSNodeTypes::MRK_ITEM : { TS* pTS = new TS; pTS->setFromMarking(true); return pTS; } } return NULL; } void EDProjectTree::sl_newFolder(){ QTreeWidgetItem* curItem = currentItem(); EDPICSDirectory* pItem = dynamic_cast(curItem); assert(pItem); CSFolder* pFolder = findFolder(pItem); CSFolder* pNewFolder = new CSFolder(); pNewFolder->setName(pFolder->makeUniqueFolderName()); if (pFolder->addFolder( pNewFolder ) < 0) { delete pNewFolder; return; } EDPICSFolder* newFol = new EDPICSFolder(pNewFolder); pItem->addChild(dynamic_cast(newFol)); updateTree(ED_UPDATE_CHILDREN, pItem); updateTree(ED_CURRENT_ITEM_CHANGED, newFol); } void EDProjectTree::sl_newSignal(){ QTreeWidgetItem* curItem = currentItem(); EDPICSDirectory* pItem = dynamic_cast(curItem); assert(pItem); CSFolder* pFolder = findFolder(pItem); Signal *pNewSignal = new Signal(NULL); pNewSignal->setName(pFolder->makeUniqueSignalName().toStdString()); if (pFolder->addSignal( pNewSignal ) < 0) { delete pNewSignal; return; } EDPICS* pNewItem = new EDPICS(pNewSignal); pItem->addChild(dynamic_cast(pNewItem)); updateTree(ED_UPDATE_CHILDREN, pItem); updateTree(ED_CURRENT_ITEM_CHANGED, pNewItem); } void EDProjectTree::sl_deletePI(){ QTreeWidgetItem* curItem = currentItem(); EDProjectItem* pItem= dynamic_cast(curItem); assert(pItem); switch (pItem->getType()){ case PIT_CS_FOLDER: deleteFolder(dynamic_cast(pItem)); break; case PIT_CS: deleteSignal(dynamic_cast(pItem)); break; default: assert(0); } } void EDProjectTree::deleteFolder(EDPICSFolder* pPI){ EDProjectItem *pItem = dynamic_cast(dynamic_cast(pPI)->parent()); CSFolder* pFolder = findFolder(dynamic_cast(pItem)); assert(pFolder != NULL); int id = pFolder->getFolderIndexByName(pPI->getName()); assert(id>=0); pFolder->deleteFolder(id); updateTree(ED_CURRENT_ITEM_CHANGED, NULL); pItem->update(true); updateTree(ED_UPDATE_CHILDREN, pItem); edData.clearScores(); } void EDProjectTree::deleteSignal(EDPICS* pPI){ if(edData.isSignalSelected(pPI)){ edData.clearScores(); } EDProjectItem *pItem = dynamic_cast(dynamic_cast(pPI)->parent()); CSFolder* pFolder = findFolder(dynamic_cast(pItem)); assert(pFolder != NULL); int id = pFolder->getSignalIndexByName(pPI->getName()); assert(id>=0); pFolder->deleteSignal(id); updateTree(ED_CURRENT_ITEM_CHANGED, NULL); pItem->update(true); updateTree(ED_UPDATE_CHILDREN, pItem); } void EDProjectTree::updateSorting(){ // for (int i = 0; i < seqRoot.childCount(); i++){ // EDProjectItem* item = dynamic_cast(seqRoot.child(i)); // if(item){ // item->setSortField(sortField); // item->setSortOrd(sortOrd); // updateSortingRecurs(item); // } // } // // for (int i = 0; i < mrkRoot.childCount(); i++){ // EDProjectItem* item = dynamic_cast(mrkRoot.child(i)); // if(item){ // item->setSortField(sortField); // item->setSortOrd(sortOrd); // updateSortingRecurs(item); // } // } for (int i = 0; i < root.childCount(); i++){ EDProjectItem* item = dynamic_cast(root.child(i)); if(item){ item->setSortField(sortField); item->setSortOrd(sortOrd); updateSortingRecurs(item); } } // seqRoot.sortChildren(0, Qt::AscendingOrder); // mrkRoot.sortChildren(0, Qt::AscendingOrder); root.sortChildren(0, Qt::AscendingOrder); } void EDProjectTree::updateSortingRecurs(EDProjectItem* pItem){ for (int i = 0; i < pItem->childCount(); i++){ EDProjectItem* item = dynamic_cast(pItem->child(i)); if(item){ item->setSortField(sortField); item->setSortOrd(sortOrd); updateSortingRecurs(item); } } pItem->sortChildren(0, Qt::AscendingOrder); } void EDProjectTree::sl_selAllSig(){ EDProjectItem* pItem = dynamic_cast(currentItem()); if (!pItem) return; for (int i=0; ichildCount(); i++) { EDProjectItem* pSI = dynamic_cast(pItem->child(i)); if(!pSI){ continue; } if (!edData.isSignalSelected(pSI)) edData.switchSelection(const_cast(pSI), true); updateTree(ED_ITEM_STATE_CHANGED, pSI); } } void EDProjectTree::sl_deselAllSig(){ EDProjectItem* pItem = dynamic_cast(currentItem()); if (!pItem) return; for (int i=0; ichildCount(); i++) { EDProjectItem* pSI = dynamic_cast(pItem->child(i)); if(!pSI){ continue; } if (edData.isSignalSelected(pSI)) edData.switchSelection(const_cast(pSI), true); updateTree(ED_ITEM_STATE_CHANGED, pSI); } } void EDProjectTree::sl_setPriorAllSig(){ EDProjectItem* pItem = dynamic_cast(currentItem()); if (!pItem) return; for (int i=0; ichildCount(); i++) { EDProjectItem* pSI = dynamic_cast(pItem->child(i)); if(!pSI){ continue; } EDPICS* pCS = dynamic_cast(pSI); if (pCS){ edData.onSetCurrentSignalParamsAsPrior(pCS, false); updateTree(ED_CURRENT_ITEM_CHANGED, pCS); } } } void EDProjectTree::sl_clearPriorAllSig(){ EDProjectItem* pItem = dynamic_cast(currentItem()); if (!pItem) return; for (int i=0; ichildCount(); i++) { EDProjectItem* pSI = dynamic_cast(pItem->child(i)); if(!pSI){ continue; } EDPICS* pCS = dynamic_cast(pSI); if (pCS){ edData.onClearSignalPriorParams(pCS); updateTree(ED_CURRENT_ITEM_CHANGED, pCS); } } } void EDProjectTree::sl_selDeselSig(){ EDProjectItem* pItem = dynamic_cast(currentItem()); if (pItem){ edData.switchSelection(pItem, true); updateTree(ED_ITEM_STATE_CHANGED, pItem); } } void EDProjectTree::sl_setCurPrior(){ EDPICS* pItem = dynamic_cast(currentItem()); if (!pItem) { assert(0); return; } edData.onSetCurrentSignalParamsAsPrior(pItem, true); updateTree(ED_CURRENT_ITEM_CHANGED, pItem); } void EDProjectTree::sl_clearCurPrior(){ EDPICS* pItem = dynamic_cast(currentItem()); if (!pItem) { assert(0); return; } edData.onClearSignalPriorParams(pItem); updateTree(ED_CURRENT_ITEM_CHANGED, pItem); } void EDProjectTree::sl_markupLetters(){ edData.markupLetters(); updateMarkup(); emit si_loadMarkup(true); } void EDProjectTree::sl_loadMarkup(){ emit si_loadMarkup(false); } void EDProjectTree::sl_showSequence(){ emit si_showSequence(); } void EDProjectTree::sl_addToShown(){ emit si_addToShown(); } void EDProjectTree::sl_clearDisplayed(){ emit si_clearDisplayed(); } void EDProjectTree::sl_showFirstSequences(){ emit si_showFirstSequences(); } void EDProjectTree::sl_setMetainfoBase(){ EDProjectItem* item = dynamic_cast(sender()); if(!item){ return; } item->setMetainfoBase(&edData.getDescriptionBase()); } void EDProjectTree::sl_generateReport(){ EDPISequenceBase* pItem = dynamic_cast(currentItem()); if (!pItem) { return; } edData.generateRecognizationReport(pItem); } void EDProjectTree::sl_sortField(QAction* action){ EDSortParameters cursortField = ED_FIELD_UNDEFINED; QString actName = action->text(); if(actName == tr("Coverage")){ cursortField = ED_FIELD_COVERAGE; }else if(actName == tr("Fisher")){ cursortField = ED_FIELD_FISHER; }else if(actName == tr("Name")){ cursortField = ED_FIELD_NAME; }else if(actName == tr("Probability")){ cursortField = ED_FIELD_PROBABILITY; } if(cursortField != ED_FIELD_UNDEFINED){ sortField = cursortField; updateSorting(); } } void EDProjectTree::sl_sortOrd(QAction* action){ EDSortParameters cursortField = ED_FIELD_UNDEFINED; QString actName = action->text(); if(actName == tr("Increasing")){ cursortField = ED_ORDER_INCREASING; }else if(actName == tr("Decreasing")){ cursortField = ED_ORDER_DECREASING; } if(cursortField != ED_FIELD_UNDEFINED){ sortOrd = cursortField; updateSorting(); } } }//namespaceugene-1.9.8/src/plugins/expert_discovery/src/ExpertDiscoveryAdvSetDialog.h0000644000175000017500000000201711651544323025512 0ustar ilyailya#pragma once #include #include #include namespace U2 { class ExpertDiscoveryAdvSetDialog : public QDialog, public Ui_ExpertDiscoveryAdvSetDialog{ Q_OBJECT public: ExpertDiscoveryAdvSetDialog(QWidget *parent, double& dIntProbability, double& dIntFisher, int& nMinComplexity, int& nMaxComplexity, double& dMinPosCorrelation, double& dMaxPosCorrelation, double& dMinNegCorrelation, double& dMaxNegCorrelation, bool& bCorrelationImportant); virtual void accept(); private: double& dIntProbability; double& dIntFisher; int& nMinComplexity; int& nMaxComplexity; double& dMinPosCorrelation; double& dMaxPosCorrelation; double& dMinNegCorrelation; double& dMaxNegCorrelation; bool& bCorrelationImportant; bool check(const QLineEdit* lineE); void hideParameters(); protected slots: void sl_checkCorrel(); }; }//namespace ugene-1.9.8/src/plugins/expert_discovery/src/ExpertDiscoveryTask.h0000644000175000017500000001414511651544323024113 0ustar ilyailya#pragma once #include "DDisc/Extractor.h" #include "DDisc/Sequence.h" #include "DDisc/MetaInfo.h" #include "ExpertDiscoveryData.h" #include "ExpertDiscoveryCSUtil.h" #include #include #include #include #include #include #include #include #include #include namespace U2 { class Document; class ExpertDiscoveryLoadPosNegTask: public Task{ Q_OBJECT public: ExpertDiscoveryLoadPosNegTask(QString firstF, QString secondF, bool generateNeg); ~ExpertDiscoveryLoadPosNegTask(); void run(){}; void prepare(); QList getDocuments() const {return docs;} bool isGenerateNeg() {return generateNeg;} private: QString firstFile, secondFile; bool generateNeg; QList docs; Document* loadFile(QString inFile); QList sequencesGenerator(const QList &); QByteArray generateRandomSequence(const int* acgtContent, int seqLen); void calculateACGTContent(const DNASequenceObject& seq, int* acgtContent); protected slots: void sl_generateNegativeSample(Task* task); signals: void si_stateChanged(Task* task); }; class ExpertDiscoveryLoadControlTask: public Task{ Q_OBJECT public: ExpertDiscoveryLoadControlTask(QString firstF); ~ExpertDiscoveryLoadControlTask(); void run(){}; void prepare(); QList getDocuments() const {return docs;} private: QString firstFile; QList docs; Document* loadFile(QString inFile); signals: void si_stateChanged(Task* task); }; class ExpertDiscoveryLoadPosNegMrkTask: public Task{ Q_OBJECT public: ExpertDiscoveryLoadPosNegMrkTask(QString firstF, QString secondF, QString thirdF, bool generateDescr, bool appendToCurrentMrk, ExpertDiscoveryData& edData); void run(){}; void prepare(); ReportResult report(); private: QString firstFile, secondFile, thirdFile; bool generateDescr; bool appendToCurrent; ExpertDiscoveryData& edData; Document* posDoc; Document* negDoc; bool loadAnnotationFromUgeneDocument(MarkingBase& base, const SequenceBase& seqBase, Document* doc); //Document* loadFile(QString inFile); signals: void si_stateChanged(Task* task); }; class ExpertDiscoveryLoadControlMrkTask: public Task{ Q_OBJECT public: ExpertDiscoveryLoadControlMrkTask(QString firstF, ExpertDiscoveryData& edD ); void run(){}; void prepare(); private: QString firstFile; ExpertDiscoveryData& edData; //Document* loadFile(QString inFile); signals: void si_stateChanged(Task* task); }; class ExpertDiscoverySignalExtractorTask: public Task{ Q_OBJECT public: ExpertDiscoverySignalExtractorTask(ExpertDiscoveryData* d); ~ExpertDiscoverySignalExtractorTask(); void run(); void prepare(); private: DDisc::Extractor *extractor; CSFolder* folder; ExpertDiscoveryData* data; bool performNextStep(); signals: void si_newSignalReady(DDisc::Signal* signal, CSFolder* folder); }; class ExpertDiscoveryCreateADVTask: public Task{ Q_OBJECT public: ExpertDiscoveryCreateADVTask(const MultiGSelection& selObjects); AnnotatedDNAView* getView() {return adv;} void run(); void prepare() {}; private: const MultiGSelection& multiSelection; AnnotatedDNAView* adv; signals: void si_stateChanged(Task* task); }; // error messages and dialogs class ExpertDiscoveryErrors: QObject { Q_OBJECT public: enum Errors {ErrorOpen, NoErrors}; static void fileOpenError(const QString &filename = ""); static void markupLoadError(); }; class ExpertDiscoveryCreateViewTask: public ObjectViewTask{ Q_OBJECT public: //opens a single view for all sequence object in the list of sequence objects related to the objects in the list ExpertDiscoveryCreateViewTask(const QList& objects); virtual void open(); AnnotatedDNAView* getADV(){return adv;} private: QList sequenceObjectRefs; AnnotatedDNAView* adv; }; class ExpertDiscoverySignalsAutoAnnotationUpdater : public AutoAnnotationsUpdater{ public: ExpertDiscoverySignalsAutoAnnotationUpdater(); Task* createAutoAnnotationsUpdateTask(const AutoAnnotationObject* aa); bool checkConstraints(const AutoAnnotationConstraints& constraints); void setEDData(ExpertDiscoveryData* d){edData = d;} void setEDProcSignals(const EDProcessedSignal* ps){curPS = ps;} void setEDMutex(QMutex* mut){mutex = mut;} private: ExpertDiscoveryData* edData; const EDProcessedSignal* curPS; QMutex* mutex; }; class ExpertDiscoveryToAnnotationTask : public Task{ Q_OBJECT public: ExpertDiscoveryToAnnotationTask(AnnotationTableObject* aobj, const DNASequence& seq, ExpertDiscoveryData* d, const EDProcessedSignal* ps, QMutex& mut); void run(); ReportResult report(); private: void recDataToAnnotation(); void csToAnnotation(int seqNumberm, unsigned int seqLen); const DNASequence& dna; ExpertDiscoveryData* edData; const EDProcessedSignal* curPS; QList resultList; U2Region seqRange; QPointer aObj; RecognizationData recData; bool hasRecData; bool isControl; bool isPos; QMutex& mutex; }; class ExpertDiscoverySaveDocumentTask : public Task{ Q_OBJECT public: ExpertDiscoverySaveDocumentTask(ExpertDiscoveryData& data, const QString& fileName); void run(); private: ExpertDiscoveryData& edData; QString filename; }; class ExpertDiscoveryLoadDocumentTask : public Task{ Q_OBJECT public: ExpertDiscoveryLoadDocumentTask(ExpertDiscoveryData& data, const QString& fileName); void run(); private: ExpertDiscoveryData& edData; QString filename; }; }//namespace ugene-1.9.8/src/plugins/expert_discovery/src/ExpertDiscoverySet.cpp0000644000175000017500000000071611651544323024276 0ustar ilyailya//**************************************************************************** // File name: Set.cpp // Title: DiscoveryLib // Version: 1.0 // Author: // Creation Date: 26.02.2005 . // // Description: // //**************************************************************************** #include "ExpertDiscoverySet.h" namespace U2{ char Set::number_of_1[65536]; }ugene-1.9.8/src/plugins/expert_discovery/src/ExpertDiscoveryPropTable.h0000644000175000017500000000341311651544323025075 0ustar ilyailya#pragma once #include "ExpertDiscoveryTreeWidgets.h" #include #include namespace U2 { class EDPropertiesTable : public QTableWidget{ Q_OBJECT public: EDPropertiesTable(QWidget* parent); void representPIProperties(EDProjectItem* pItem); void updateCurrentProperties(); void clearAll(); private: void addNewGroup(const QString& name); void addNewField(const QString& name); void cleanup(); EDProjectItem* curPItem; bool isSeq; int seqOffset; protected slots: void sl_cellChanged(QTableWidgetItem * tItem); void sl_cellDataChanged(int row, int column); void sl_comboEditTextChangerd(const QString& t); public slots: void sl_treeSelChanged(QTreeWidgetItem * tItem); signals: void si_propChanged(EDProjectItem* item, const EDPIProperty* prop, QString newVal); }; class EDPropertyItem : public QTableWidgetItem{ public: EDPropertyItem(const QString& val, int nGroup, int nProp, bool editable); //EDPropertyItem(const QString& val, int nGroup, int nProp, const EDPIPropertyTypeList* pType, bool editable); int getGroup(){return nGroup;} int getProp(){return nProp;} QString getData() {return data;} void setData(const QString& d){data = d;} private: int nGroup; int nProp; QString data; }; class EDPropertyItemList : public QComboBox{ public: //EDPropertyItem(const QString& val, int nGroup, int nProp, bool editable); EDPropertyItemList(const QString& val, int nGroup, int nProp, const EDPIPropertyTypeList* pType, bool editable); int getGroup(){return nGroup;} int getProp(){return nProp;} QString getData() {return data;} void setData(const QString& d){data = d;} private: int nGroup; int nProp; QString data; }; }//namespace ugene-1.9.8/src/plugins/expert_discovery/src/ui/0000755000175000017500000000000011651544323020370 5ustar ilyailyaugene-1.9.8/src/plugins/expert_discovery/src/ui/ExpertDiscoveryPosNegDialog.ui0000644000175000017500000001217011651544323026323 0ustar ilyailya ExpertDiscoveryPosNegDialog Qt::ApplicationModal 0 0 476 194 0 0 Positive and Negative sequences :/repeat_finder/repeats_image:/repeat_finder/repeats_image true File with positive sequences ... Qt::Vertical 20 18 Generate negative sequences Qt::Vertical 20 18 File with negative sequences true ... Qt::Vertical 20 5 Qt::Horizontal 40 20 Ok true Cancel firstFileEdit openFirstButton secondFileEdit openSecondButton startButton cancelButton oneSequenceCheckBox startButton clicked() ExpertDiscoveryPosNegDialog accept() 416 518 273 270 cancelButton clicked() ExpertDiscoveryPosNegDialog reject() 499 518 273 270 ugene-1.9.8/src/plugins/expert_discovery/src/ui/ExpertDiscoveryControlDialog.ui0000644000175000017500000000701211651544323026547 0ustar ilyailya ExpertDiscoveryControlDialog Qt::ApplicationModal 0 0 473 87 0 0 Load Control sequences :/repeat_finder/repeats_image:/repeat_finder/repeats_image true File with control sequences ... Qt::Vertical 20 5 Qt::Horizontal 40 20 Ok true Cancel firstFileEdit openFirstButton startButton cancelButton startButton clicked() ExpertDiscoveryControlDialog accept() 416 518 273 270 cancelButton clicked() ExpertDiscoveryControlDialog reject() 499 518 273 270 ugene-1.9.8/src/plugins/expert_discovery/src/ui/ExpertDiscoverySigExtrWiz.ui0000644000175000017500000002560511651544323026076 0ustar ilyailya SignalsExtrWiz Qt::ApplicationModal 0 0 447 465 Extractor Parameters setup false false true QWizard::ClassicStyle Qt::AutoText Setup algorithm parameters This wizard will help you automaticaly extract complex signals from sequences. 1 Please fill in selection parameters Condition probability level Coverage bound Fisher criteria level Qt::Horizontal 40 20 Check minimization of Fisher criteria Store only signals with different behaviour Minimal Complexity Maximal Complexity Qt::Horizontal 40 20 Check Ul criteria Samples bound Qt::Horizontal 40 20 Level bound Qt::Horizontal 40 20 Advanced... Setup predicates Please create some predicates that will be used in complex signal construction process. 2 10 0 401 351 QFrame::StyledPanel QFrame::Sunken false 1 QLayout::SetDefaultConstraint Distance Repetition Interval Qt::Vertical 20 40 Delete Aligned true Editor false Select folder Select folder to store extracted complex signals 3 false 1 ugene-1.9.8/src/plugins/expert_discovery/src/ui/ExpertDiscoveryPosNegMrkDialog.ui0000644000175000017500000001372111651544323027000 0ustar ilyailya ExpertDiscoveryPosNegMrkDialog Qt::ApplicationModal 0 0 476 221 0 0 Positive and Negative sequences markup :/repeat_finder/repeats_image:/repeat_finder/repeats_image true File with positive sequences markup ... Qt::Vertical 20 18 Generate description file Qt::Vertical 20 18 ... true File with negative sequences markup Description file true ... Append to Current Markup true Qt::Vertical 20 5 Qt::Horizontal 40 20 Ok true Cancel firstFileEdit openFirstButton secondFileEdit openSecondButton startButton cancelButton startButton clicked() ExpertDiscoveryPosNegMrkDialog accept() 416 518 273 270 cancelButton clicked() ExpertDiscoveryPosNegMrkDialog reject() 499 518 273 270 ugene-1.9.8/src/plugins/expert_discovery/src/ui/ExpertDiscoveryControlMrkDialog.ui0000644000175000017500000000703011651544323027221 0ustar ilyailya ExpertDiscoveryControlMrkDialog Qt::ApplicationModal 0 0 473 84 0 0 Load Control sequences markup :/repeat_finder/repeats_image:/repeat_finder/repeats_image true File with control sequences markup ... Qt::Vertical 20 5 Qt::Horizontal 40 20 Ok true Cancel firstFileEdit openFirstButton startButton cancelButton startButton clicked() ExpertDiscoveryControlMrkDialog accept() 416 518 273 270 cancelButton clicked() ExpertDiscoveryControlMrkDialog reject() 499 518 273 270 ugene-1.9.8/src/plugins/expert_discovery/src/ui/ExpertDiscoverySetupRecBoundDialog.ui0000644000175000017500000001240411651544323027652 0ustar ilyailya EDSetupRecBoundDlg Qt::ApplicationModal 0 0 372 239 Setup Recognition Bound Recognition Bound true 6 999999999.000000000000000 0.100000000000000 Information Probability of negative sequence recognition: Qt::Horizontal 40 20 false true Qt::Vertical 20 40 Probability of positive sequence rejection: Qt::Horizontal 40 20 false true Qt::Vertical 20 40 Qt::Horizontal QDialogButtonBox::Cancel|QDialogButtonBox::Ok buttonBox accepted() EDSetupRecBoundDlg accept() 248 254 157 274 buttonBox rejected() EDSetupRecBoundDlg reject() 316 260 286 274 ugene-1.9.8/src/plugins/expert_discovery/src/ui/ExpertDiscoveryAdvSetDialog.ui0000644000175000017500000001516411651544323026324 0ustar ilyailya ExpertDiscoveryAdvSetDialog 0 0 343 341 Advanced Extract Parameters true -10 310 341 32 Qt::Horizontal QDialogButtonBox::Cancel|QDialogButtonBox::Ok 9 9 321 291 Branch bounds 9 9 291 121 Condition probability level Fisher criteria level Minimal complexity Maximal complexity Qt::Horizontal 40 20 Check for distance argument correlation Disrance argument correlation bounds 10 10 291 121 Min. correlation on positive Max. correlation on positive Min. correlation on negative Max. correlation on negative Qt::Horizontal 40 20 buttonBox accepted() ExpertDiscoveryAdvSetDialog accept() 248 254 157 274 buttonBox rejected() ExpertDiscoveryAdvSetDialog reject() 316 260 286 274 ugene-1.9.8/src/plugins/expert_discovery/src/ExpertDiscoveryPosNegMrkDialog.h0000644000175000017500000000157511651544323026201 0ustar ilyailya#pragma once #include namespace U2 { class ExpertDiscoveryPosNegMrkDialog : public QDialog, public Ui_ExpertDiscoveryPosNegMrkDialog{ Q_OBJECT public: ExpertDiscoveryPosNegMrkDialog(QWidget *parent); virtual void accept(); QString getFirstFileName() const {return firstFileName;} QString getSecondFileName() const {return secondFileName;} QString getThirdFileName() const {return thirdFileName;} bool isGenerateDescr() const {return generateDescr;} bool isAppendToCurrentMarkup() const {return addToCurrentCheck->isChecked();} protected slots: void sl_openFirstFile(); void sl_openSecondFile(); void sl_openThirdFile(); void sl_oneSequence(); private: QString firstFileName; QString secondFileName; QString thirdFileName; bool generateDescr; QString filter; }; }//namespace ugene-1.9.8/src/plugins/expert_discovery/src/ExpertDiscoveryPlugin.cpp0000644000175000017500000002360611651544323025004 0ustar ilyailya#include "ExpertDiscoveryPlugin.h" #include "ExpertDiscoveryView.h" #include "ExpertDiscoveryViewCtx.h" #include "ExpertDiscoveryTask.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include namespace U2 { extern "C" Q_DECL_EXPORT Plugin * U2_PLUGIN_INIT_FUNC() { if (AppContext::getMainWindow()) { ExpertDiscoveryPlugin * plug = new ExpertDiscoveryPlugin(); return plug; } return NULL; } ExpertDiscoveryPlugin::ExpertDiscoveryPlugin() : Plugin( tr("Expert Discovery"), tr("Expert Discovery plugin") ),viewCtx(NULL), delay(false) { connect( AppContext::getPluginSupport(), SIGNAL( si_allStartUpPluginsLoaded() ), SLOT(sl_initExpertDiscoveryViewCtx())); windowId = 0; ExpertDiscoveryViewFactory* edFactory = new ExpertDiscoveryViewFactory("ED", "ED", this); AppContext::getObjectViewFactoryRegistry()->registerGObjectViewFactory(edFactory); } void ExpertDiscoveryPlugin::sl_initExpertDiscoveryViewCtx() { if (AppContext::getMainWindow()) { viewCtx = new ExpertDiscoveryViewCtx(this); Q_ASSERT(viewCtx); viewCtx->init(); //AppContext::getAutoAnnotationsSupport()->registerAutoAnnotationsUpdater(new ExpertDiscoverySignalsAutoAnnotationUpdater ); //change the icon QAction* action = new QAction( tr("Expert Discovery (alpha)"), this ); connect( action, SIGNAL( triggered() ), SLOT( sl_expertDiscoveryView() ) ); AppContext::getMainWindow()->getTopLevelMenu( MWMENU_TOOLS )->addAction( action ); } } void ExpertDiscoveryPlugin::sl_expertDiscoveryView(){ //create project here if (!AppContext::getProject()) { Task *tasks = new Task("Creating empty project", TaskFlag_NoRun); Task* t = AppContext::getProjectLoader()->createNewProjectTask(); connect( t, SIGNAL( si_stateChanged() ), SLOT( sl_expertDiscoveryViewDelay() ) ); tasks->addSubTask(t); AppContext::getTaskScheduler()->registerTopLevelTask(tasks); delay = true; }else{ delay = false; sl_expertDiscoveryViewDelay(); } } void ExpertDiscoveryPlugin::sl_expertDiscoveryViewDelay(){ if(delay){ if(!AppContext::getProject()){ return; } delay = false; } MWMDIManager* mdi = AppContext::getMainWindow()->getMDIManager(); MWMDIWindow* mdiWindow = mdi->getWindowById(windowId); if (mdiWindow==NULL) { ExpertDiscoveryView* v = new ExpertDiscoveryView("ED", "EDView", this); v->addObjectHandler(viewCtx); ExpertDiscoveryViewWindow* wind = new ExpertDiscoveryViewWindow(v, "Expert Discovery"); windowId = wind->getId(); AppContext::getMainWindow()->getMDIManager()->addMDIWindow(wind); AppContext::getMainWindow()->getMDIManager()->activateWindow(wind); }else{ AppContext::getMainWindow()->getMDIManager()->activateWindow(mdiWindow); } } const GObjectViewFactoryId ExpertDiscoveryViewFactory::ID("ED"); ExpertDiscoveryViewFactory::ExpertDiscoveryViewFactory(GObjectViewFactoryId id, const QString& name, QObject* p) :GObjectViewFactory(id,name,p){ } bool ExpertDiscoveryViewFactory::canCreateView(const MultiGSelection& multiSelection) { //return true if //0. All the documents in the selection are from ExperDiscoveryData //1. selection has loaded of unloaded DNA sequence object //2. selection has any object with SEQUENCE relation to DNA sequence object that is in the project //3. selection has document that have sequence object or object assosiated with sequence //0. if(!checkSelection(multiSelection)){ return false; } //1. QList selectedObjects = SelectionUtils::findObjects("", &multiSelection, UOF_LoadedAndUnloaded); QList selectedSequences = GObjectUtils::select(selectedObjects, GObjectTypes::SEQUENCE, UOF_LoadedAndUnloaded); if (!selectedSequences.isEmpty()) { return true; } //2. QList objectsWithSeqRelation = GObjectUtils::selectObjectsWithRelation(selectedObjects, GObjectTypes::SEQUENCE, GObjectRelationRole::SEQUENCE, UOF_LoadedAndUnloaded, true); if (!objectsWithSeqRelation.isEmpty()) { return true; } //3. const DocumentSelection* ds = qobject_cast(multiSelection.findSelectionByType(GSelectionTypes::DOCUMENTS)); if (ds == NULL) { return false; } foreach(Document* doc, ds->getSelectedDocuments()) { if (!doc->findGObjectByType(GObjectTypes::SEQUENCE, UOF_LoadedAndUnloaded).isEmpty()) { return true; } objectsWithSeqRelation = GObjectUtils::selectObjectsWithRelation(doc->getObjects(), GObjectTypes::SEQUENCE, GObjectRelationRole::SEQUENCE, UOF_LoadedAndUnloaded, true); if (!objectsWithSeqRelation.isEmpty()) { return true; } } return false; } Task* ExpertDiscoveryViewFactory::createViewTask(const MultiGSelection& multiSelection, bool single /*=false*/) { Q_UNUSED(single); QList objectsToOpen = SelectionUtils::findObjects(GObjectTypes::SEQUENCE, &multiSelection, UOF_LoadedAndUnloaded); QList selectedObjects = SelectionUtils::findObjects("", &multiSelection, UOF_LoadedAndUnloaded); QList objectsWithSequenceRelation = GObjectUtils::selectObjectsWithRelation(selectedObjects, GObjectTypes::SEQUENCE, GObjectRelationRole::SEQUENCE, UOF_LoadedAndUnloaded, true); objectsToOpen.append(objectsWithSequenceRelation); const DocumentSelection* ds = qobject_cast(multiSelection.findSelectionByType(GSelectionTypes::DOCUMENTS)); if (ds != NULL) { foreach(Document* doc, ds->getSelectedDocuments()) { objectsToOpen.append(doc->findGObjectByType(GObjectTypes::SEQUENCE, UOF_LoadedAndUnloaded)); objectsToOpen.append(GObjectUtils::selectObjectsWithRelation(doc->getObjects(), GObjectTypes::SEQUENCE, GObjectRelationRole::SEQUENCE, UOF_LoadedAndUnloaded, true)); } } ExpertDiscoveryCreateViewTask* task = new ExpertDiscoveryCreateViewTask(objectsToOpen); emit si_newTaskCreation(task); return task; } bool ExpertDiscoveryViewFactory::checkSelection(const MultiGSelection& multiSelection){ QList views; QList windows = AppContext::getMainWindow()->getMDIManager()->getWindows(); GObjectSelection* objectsSelection = (GObjectSelection*)multiSelection.findSelectionByType(GSelectionTypes::GOBJECTS); if (objectsSelection!=NULL) { QSet objectsInSelection = objectsSelection->getSelectedObjects().toSet(); foreach(MWMDIWindow* w, windows) { GObjectViewWindow* ov = qobject_cast(w); if (ov==NULL) { continue; } if (ov->getViewFactoryId() != ID) { continue; } ExpertDiscoveryViewWindow* edViewWindow = dynamic_cast(ov); if(!edViewWindow){ continue; } ExpertDiscoveryView* edView = dynamic_cast(edViewWindow->getObjectView()); if(!edView){ continue; } const QList& viewObjects = edView->getEDObjects(); bool allIn = true; foreach(GObject* o, objectsInSelection) { if (!viewObjects.contains(o)) { allIn = false; break; } } return allIn; } } return false; } // bool ExpertDiscoveryViewFactory::isStateInSelection(const MultiGSelection& multiSelection, const QVariantMap& stateData) { // AnnotatedDNAViewState state(stateData); // if (!state.isValid()) { // return false; // } // QList refs = state.getSequenceObjects(); // assert(!refs.isEmpty()); // foreach (const GObjectReference& ref, refs) { // Document* doc = AppContext::getProject()->findDocumentByURL(ref.docUrl); // if (doc == NULL) { //todo: accept to use invalid state removal routines of ObjectViewTask ??? // return false; // } // //check that document is in selection // QList selectedDocs = SelectionUtils::getSelectedDocs(multiSelection); // bool docIsSelected = selectedDocs.contains(doc); // // //check that object is in selection // QList selectedObjects = SelectionUtils::getSelectedObjects(multiSelection); // GObject* obj = doc->findGObjectByName(ref.objName); // bool objIsSelected = obj!=NULL && selectedObjects.contains(obj); // // //check that object associated with sequence object is in selection // bool refIsSelected = false; // foreach (const GObject* selObject, selectedObjects) { // GObjectReference selRef(selObject); // if (ref == selRef) { // refIsSelected = true; // break; // } // } // if (!docIsSelected && !objIsSelected && !refIsSelected) { // return false; // } // } // // return true; // } // Task* ExpertDiscoveryViewFactory::createViewTask(const QString& viewName, const QVariantMap& stateData) { // return new OpenSavedAnnotatedDNAViewTask(viewName, stateData); // } } //namespace ugene-1.9.8/src/plugins/expert_discovery/src/ExpertDiscoveryTreeWidgetsCtrl.h0000644000175000017500000001116111651544323026257 0ustar ilyailya#ifndef _U2_EXPERT_DIS_TREEWIDGETSCTR_H_ #define _U2_EXPERT_DIS_TREEWIDGETSCTR_H_ #include "DDisc/Signal.h" #include "DDisc/MetaInfo.h" #include "ExpertDiscoveryTreeWidgets.h" #include "ExpertDiscoveryData.h" #include #include #include #include #include namespace U2 { // class MyTreeWidget : public QTreeView{ // Q_OBJECT // public: // MyTreeWidget(QWidget *parent); // // }; class EDProjectTree : public QTreeWidget{ Q_OBJECT public: EDProjectTree(QWidget *parent, ExpertDiscoveryData &data); CSFolder &getRootItem(){edData.getRootFolder();}; EDProjectItem* findEDItem(void* pData); CSFolder* findFolder(EDPICSDirectory *pFolder) const; Signal* findSignal(const Signal* pSignal) const; void addSubitem(EDProjectItem* subItem, EDProjectItem* parent); void updateTree(int flag, EDProjectItem* item = NULL); void remake(); void clearTree(); void internalRemake(EDProjectItem* subItem, EDProjectItem* parent); void updateItem(EDProjectItem* pItem); void updateItemState(EDProjectItem* pItem); void updateChildren(EDProjectItem* pItem); void updateMarkup(); void updateSequenceBase(EItemType type); void deleteFolder(EDPICSFolder* folder); void deleteSignal(EDPICS* signal); void updateSorting(); void updateSortingRecurs(EDProjectItem* pItem); bool isUpdatingItem() {return updatingItem;} protected slots: void sl_newFolder(); void sl_newSignal(); void sl_deletePI(); void sl_selAllSig(); void sl_deselAllSig(); void sl_setPriorAllSig(); void sl_clearPriorAllSig(); void sl_selDeselSig(); void sl_setCurPrior(); void sl_clearCurPrior(); void sl_markupLetters(); void sl_loadMarkup(); void sl_showSequence(); void sl_addToShown(); void sl_clearDisplayed(); void sl_showFirstSequences(); void sl_setMetainfoBase(); void sl_generateReport(); void sl_sortField(QAction* action); void sl_sortOrd(QAction* action); private: QMenu* chosePopupMen(EDProjectItem* pItem); void createPopupsAndActions(); QIcon getItemIcon(EDProjectItem* pItem); void onCSNPropertyChanged(EDProjectItem* pItem, const EDPIProperty* pProperty, QString strNewValue); void onDistancePropertyChanged(EDProjectItem* pItem, const EDPIProperty* pProperty, QString strNewValue); void onRepetitionPropertyChanged(EDProjectItem* pItem, const EDPIProperty* pProperty, QString strNewValue); void onIntervalPropertyChanged(EDProjectItem* pItem, const EDPIProperty* pProperty, QString strNewValue); void onWordPropertyChanged(EDProjectItem* pItem, const EDPIProperty* pProperty, QString strNewValue); void onMrkItemPropertyChanged(EDProjectItem* pItem, const EDPIProperty* pProperty, QString strNewValue); Operation* createCSN(int ValueId) const; ExpertDiscoveryData &edData; EDPICSRoot root; EDPIMrkRoot mrkRoot; EDPISequenceRoot seqRoot; QMenu* popupMenuCS; QMenu* popupMenuDir; QMenu* popupMenuDirRoot; QMenu* popupMenuMrkRoot; QMenu* popupMenuSequence; QMenu* popupMenuSequenceBase; QAction* newFolderAction; QAction* newSignalAction; QAction* deletePIAction; QAction* selAllSigAction; QAction* deselAllSigAction; QAction* setPriorAllSigAction; QAction* clearPriorAllSigAction; QAction* selDeselSigAction; QAction* setCurPriorAction; QAction* clearCurPriorAction; QAction* markupLettersAction; QAction* loadMarkupAction; QAction* showSequenceAction; QAction* addToShownAction; QAction* generateReportAction; QAction* clearDisplayedAction; QAction* showFirstSequencesAction; QActionGroup* sortGroup; QActionGroup* sortOrdGroup; QActionGroup* sortFieldGroup; QAction* sortOrdIncrAction; QAction* sortOrdDecrAction; QAction* sortFieldCoverAction; QAction* sortFieldFisherAction; QAction* sortFieldNameAction; QAction* sortFieldProbAction; EDSortParameters sortField; EDSortParameters sortOrd; bool updatingItem; protected: virtual void mousePressEvent(QMouseEvent *e); virtual void mouseDoubleClickEvent(QMouseEvent *event); public slots: void sl_propChanged(EDProjectItem* item, const EDPIProperty* prop, QString newVal); signals: void si_loadMarkup(bool isLetters); void si_showSequence(); void si_addToShown(); void si_showFirstSequences(); void si_clearDisplayed(); void si_changeProp(QTreeWidgetItem* item); }; } //namespace #endif ugene-1.9.8/src/plugins/expert_discovery/src/ExpertDiscoveryTask.cpp0000644000175000017500000011303311651544323024442 0ustar ilyailya#include "ExpertDiscoveryTask.h" #include "ExpertDiscoveryExtSigWiz.h" #include "ExpertDiscoveryPersistent.h" //#include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include namespace U2 { ExpertDiscoveryLoadPosNegTask::ExpertDiscoveryLoadPosNegTask(QString firstF, QString secondF, bool generateNeg) : Task(tr("ExpertDiscovery loading"), TaskFlags(TaskFlag_NoRun | TaskFlag_FailOnSubtaskCancel)){ firstFile = firstF; secondFile = secondF; this->generateNeg = generateNeg; } ExpertDiscoveryLoadPosNegTask::~ExpertDiscoveryLoadPosNegTask(){ // error while loading documents if (hasError()) { Project *project = AppContext::getProject(); // skip added to the project documents if (project) { QList projectDocs = project->getDocuments(); foreach (Document *doc, projectDocs) { docs.removeAll(doc); } } // delete loaded but not added to the project documents // qDeleteAll(docs); foreach (Document *doc, docs) { // docs.removeAll(doc); delete doc; } } } void ExpertDiscoveryLoadPosNegTask::prepare(){ // load sequences Document *doc = loadFile(firstFile); if (doc) { doc->setName("Positive"); docs << doc; } if (hasError()) { return; } if(!generateNeg){ doc = loadFile(secondFile); if (doc) { doc->setName("Negative"); docs << doc; } } } Document* ExpertDiscoveryLoadPosNegTask::loadFile(QString inFile){ GUrl URL(inFile); //Project *project = AppContext::getProject(); //Q_ASSERT(project); //Document *doc = project->findDocumentByURL(URL); // document already present in the project // if (doc) { // return doc; // } QList formats = DocumentUtils::detectFormat(inFile); if (formats.isEmpty()) { stateInfo.setError(tr("Detecting format error for file %1").arg(inFile)); return NULL; } DocumentFormat* format = formats.first().format; Q_ASSERT(format); IOAdapterFactory* iof = AppContext::getIOAdapterRegistry()->getIOAdapterFactoryById(BaseIOAdapters::url2io(URL)); Document* doc = new Document(format, iof, URL, QList()); //addSubTask(new AddDocumentTask(doc)); // add document to the project LoadUnloadedDocumentTask* ld = new LoadUnloadedDocumentTask(doc); if(generateNeg){ connect(AppContext::getTaskScheduler(),SIGNAL(si_stateChanged(Task*)), SLOT(sl_generateNegativeSample(Task*))); } addSubTask(ld); // load document return doc; } void ExpertDiscoveryLoadPosNegTask::sl_generateNegativeSample(Task* task){ LoadUnloadedDocumentTask *loadTask = qobject_cast(task); if (!loadTask || !loadTask->isFinished()) { return; } if (loadTask->getStateInfo().hasError()) { ExpertDiscoveryErrors::fileOpenError(); return; } if(docs.isEmpty()){ return; } Document* positiveDoc = docs.first(); Document* negativeDoc; QString baseName = positiveDoc->getURL().baseFileName(); baseName = baseName.append("_negative_generated"); QString suffix = positiveDoc->getURL().completeFileSuffix(); if(suffix!=""){ suffix = QString(".").append(suffix); } baseName.append(suffix); QString negFileName = positiveDoc->getURL().dirPath().append("/"+baseName); GUrl URL(negFileName); IOAdapterFactory* iof = AppContext::getIOAdapterRegistry()->getIOAdapterFactoryById(BaseIOAdapters::url2io(URL)); QList negObjects = sequencesGenerator(positiveDoc->getObjects()); negativeDoc = new Document(positiveDoc->getDocumentFormat(),iof,URL,negObjects); negativeDoc->setLoaded(true); Project *project = AppContext::getProject(); //project->addDocument(negativeDoc); if (negativeDoc) { negativeDoc->setName("Negative"); docs << negativeDoc; } } #define NUMBER_OF_NEGATIVE_PER_POSITIVE 10 QList ExpertDiscoveryLoadPosNegTask::sequencesGenerator(const QList &objects){ QList neg; int acgtContent[4]; foreach(GObject* obj, objects){ if(obj->getGObjectType() == GObjectTypes::SEQUENCE){ DNASequenceObject* seq = (DNASequenceObject*)obj; calculateACGTContent(*seq,acgtContent); for (int i = 0; i < NUMBER_OF_NEGATIVE_PER_POSITIVE; i++){ QByteArray curArr = generateRandomSequence(acgtContent, seq->getSequenceLen()); QString name = seq->getGObjectName(); name = name.append(QString("_neg%1").arg(i)); DNASequence curSeq = DNASequence(seq->getDNASequence().getName().append(QString("_neg%1").arg(i)), curArr,seq->getAlphabet()); DNASequenceObject* curSeqObj = new DNASequenceObject(name, curSeq); neg.append(curSeqObj); } } } return neg; } void ExpertDiscoveryLoadPosNegTask::calculateACGTContent(const DNASequenceObject& seq, int* acgtContent) { //assert(seq.getAlphabet()->isNucleic()); acgtContent[0] = acgtContent[1] = acgtContent[2] = acgtContent[3] = 0; int seqLen = seq.getSequenceLen(); int total = seq.getSequenceLen(); for (int i=0; i < seqLen; i++) { char c = seq.getSequence().at(i); if (c == 'A') { acgtContent[0]++; } else if (c == 'C') { acgtContent[1]++; } else if (c == 'G') { acgtContent[2]++; } else if (c == 'T') { acgtContent[3]++; } else { total--; } } for (int i=0;i<4;i++) { acgtContent[i] = qRound(acgtContent[i] * 100. / total); } } QByteArray ExpertDiscoveryLoadPosNegTask::generateRandomSequence(const int* acgtContent, int seqLen) { QByteArray randomSequence; randomSequence.reserve(seqLen); int aPercentRange = acgtContent[0]; int cPercentRange = aPercentRange + acgtContent[1]; int gPercentRange = cPercentRange + acgtContent[2]; assert(gPercentRange + acgtContent[3] > 0); for (int i=0; i < seqLen; i++) { int r = qrand(); float perc = 100 * (float(r) / RAND_MAX); char c = 'T'; if (perc <= aPercentRange) { c = 'A'; } else if (perc <= cPercentRange) { c = 'C'; } else if (perc <= gPercentRange) { c = 'G'; } randomSequence.append(c); } return randomSequence; } ExpertDiscoveryLoadPosNegMrkTask::ExpertDiscoveryLoadPosNegMrkTask(QString firstF, QString secondF, QString thirdF, bool generateDescr, bool appendToCurrentMrk, ExpertDiscoveryData& edD) : Task(tr("ExpertDiscovery loading"), TaskFlags(TaskFlag_NoRun | TaskFlag_FailOnSubtaskCancel |TaskFlag_FailOnSubtaskError)) ,edData(edD) ,posDoc(NULL) ,negDoc(NULL) { firstFile = firstF; secondFile = secondF; thirdFile = thirdF; this->generateDescr = generateDescr; appendToCurrent = appendToCurrentMrk; } void ExpertDiscoveryLoadPosNegMrkTask::prepare(){ edData.clearScores(); if(!appendToCurrent){ edData.getPosMarkBase().clear(); edData.getNegMarkBase().clear(); } edData.getDescriptionBaseNoConst().clear(); QString strPosName = firstFile; try { if (strPosName.right(4).compare(".xml", Qt::CaseInsensitive) == 0) { if (!edData.loadAnnotation(edData.getPosMarkBase(), edData.getPosSeqBase(), strPosName)) { throw std::exception(); } } else { QList curFormats = DocumentUtils::detectFormat(firstFile); if (!curFormats.isEmpty()){ if(curFormats.first().format->getFormatId() == BaseDocumentFormats::PLAIN_GENBANK){ GUrl URL(strPosName); IOAdapterFactory* iof = AppContext::getIOAdapterRegistry()->getIOAdapterFactoryById(BaseIOAdapters::url2io(URL)); DocumentFormat* f = AppContext::getDocumentFormatRegistry()->getFormatById(BaseDocumentFormats::PLAIN_GENBANK); posDoc = new Document(f , iof, URL, QList()); addSubTask(new LoadUnloadedDocumentTask(posDoc)); } else { ifstream fPosAnn(strPosName.toStdString().c_str()); edData.getPosMarkBase().load(fPosAnn); } } } } catch (exception& ex) { edData.getPosMarkBase().clear(); QString str = "Positive annotation: "; str += ex.what(); QMessageBox mb(QMessageBox::Critical, tr("Error"), str); mb.exec(); setError(str); return; // return false; } QString strNegName = secondFile; try { if (strNegName.right(4).compare(".xml", Qt::CaseInsensitive) == 0) { if (!edData.loadAnnotation(edData.getNegMarkBase(), edData.getNegSeqBase(), strNegName)) throw std::exception(); } else { QList curFormats = DocumentUtils::detectFormat(strNegName); if (!curFormats.isEmpty()) { if(curFormats.first().format->getFormatId() == BaseDocumentFormats::PLAIN_GENBANK){ GUrl URL(strNegName); IOAdapterFactory* iof = AppContext::getIOAdapterRegistry()->getIOAdapterFactoryById(BaseIOAdapters::url2io(URL)); DocumentFormat* f = AppContext::getDocumentFormatRegistry()->getFormatById(BaseDocumentFormats::PLAIN_GENBANK); negDoc = new Document(f, iof, URL, QList()); addSubTask(new LoadUnloadedDocumentTask(negDoc)); } else { ifstream fNegAnn(strNegName.toStdString().c_str()); edData.getNegMarkBase().load(fNegAnn); } } } } catch (exception& ex) { edData.getPosMarkBase().clear(); edData.getNegMarkBase().clear(); QString str = "Negative annotation: "; str += ex.what(); QMessageBox mb(QMessageBox::Critical, tr("Error"), str); mb.exec(); setError(str); return; // return false; } // return true; } Task::ReportResult ExpertDiscoveryLoadPosNegMrkTask::report(){ if (isCanceled() || hasError()) { return ReportResult_Finished; } if(posDoc){ try { if (!loadAnnotationFromUgeneDocument(edData.getPosMarkBase(), edData.getPosSeqBase(), posDoc)) throw std::exception(); }catch (exception& ex) { edData.getPosMarkBase().clear(); QString str = "Positive annotation: "; str += ex.what(); QMessageBox mb(QMessageBox::Critical, tr("Error"), str); mb.exec(); setError(str); return ReportResult_Finished; } } if(negDoc){ try { if (!loadAnnotationFromUgeneDocument(edData.getNegMarkBase(), edData.getNegSeqBase(), negDoc)) throw std::exception(); } catch (exception& ex) { edData.getPosMarkBase().clear(); edData.getNegMarkBase().clear(); QString str = "Negative annotation: "; str += ex.what(); QMessageBox mb(QMessageBox::Critical, tr("Error"), str); mb.exec(); setError(str); return ReportResult_Finished; } } try { if (generateDescr) { if (!edData.generateDescription(!appendToCurrent)) throw std::exception(); } else { ifstream fDesc( thirdFile.toStdString().c_str() ); edData.getDescriptionBaseNoConst().load(fDesc); } } catch (exception& ex) { edData.getPosMarkBase().clear(); edData.getNegMarkBase().clear(); edData.getDescriptionBaseNoConst().clear(); QString str = "Description: "; str += ex.what(); QMessageBox mb(QMessageBox::Critical, tr("Error"), str); mb.exec(); setError(str); return ReportResult_Finished; // return false; } edData.getPosSeqBase().setMarking(edData.getPosMarkBase()); edData.getNegSeqBase().setMarking(edData.getNegMarkBase()); return ReportResult_Finished; } bool ExpertDiscoveryLoadPosNegMrkTask::loadAnnotationFromUgeneDocument(MarkingBase& base, const SequenceBase& seqBase, Document* doc){ QList seqList = doc->findGObjectByType(GObjectTypes::SEQUENCE); QList allSeqAnnotations = doc->findGObjectByType(GObjectTypes::ANNOTATION_TABLE); foreach(GObject* seqObj, seqList){ int objN = seqBase.getObjNo(seqObj->getGObjectName().toStdString().c_str()); if(objN < 0){ QString sequenceId = seqObj->getGObjectName(); int cutPos = sequenceId.indexOf("sequence"); if(cutPos >= 0){ sequenceId = sequenceId.left(cutPos); } sequenceId = sequenceId.trimmed(); objN = seqBase.getObjNo(sequenceId.toStdString().c_str()); } if(objN >= 0){ Marking mrk; try { mrk = base.getMarking(objN); }catch(...){} QList annotations = GObjectUtils::findObjectsRelatedToObjectByRole(seqObj, GObjectTypes::ANNOTATION_TABLE, GObjectRelationRole::SEQUENCE, allSeqAnnotations, UOF_LoadedOnly); foreach(GObject* ao, annotations) { AnnotationTableObject* atobj = qobject_cast(ao); if(atobj){ const QList& annotations = atobj->getAnnotations(); foreach(Annotation* a, annotations){ const QVector& regions = a->getRegions(); foreach(U2Region reg, regions){ reg.length; int startPos = reg.startPos; int endPos = reg.startPos + reg.length - 1; if (endPos >= startPos && startPos >= 0) { //mrk.set(signalName.toStdString(), familyName.toStdString(), DDisc::Interval(startPos, endPos)); mrk.set(a->getAnnotationName().toStdString(), "UGENE Annotation", DDisc::Interval(startPos, endPos)); } } } } } base.setMarking(objN, mrk); } } return true; } ExpertDiscoveryLoadControlMrkTask::ExpertDiscoveryLoadControlMrkTask(QString firstF, ExpertDiscoveryData& edD) : Task(tr("ExpertDiscovery loading"), TaskFlags(TaskFlag_NoRun | TaskFlag_FailOnSubtaskCancel)) ,edData(edD){ firstFile = firstF; } void ExpertDiscoveryLoadControlMrkTask::prepare(){ edData.loadControlSequenceAnnotation(firstFile); } ExpertDiscoveryLoadControlTask::ExpertDiscoveryLoadControlTask(QString firstF) : Task(tr("ExpertDiscovery loading"), TaskFlags(TaskFlag_NoRun | TaskFlag_FailOnSubtaskCancel)){ firstFile = firstF; } ExpertDiscoveryLoadControlTask::~ExpertDiscoveryLoadControlTask(){ // error while loading documents if (hasError()) { Project *project = AppContext::getProject(); // skip added to the project documents if (project) { QList projectDocs = project->getDocuments(); foreach (Document *doc, projectDocs) { docs.removeAll(doc); } } // delete loaded but not added to the project documents // qDeleteAll(docs); foreach (Document *doc, docs) { // docs.removeAll(doc); delete doc; } } } void ExpertDiscoveryLoadControlTask::prepare(){ // load sequences Document *doc = loadFile(firstFile); if (doc) { doc->setName("Control"); docs << doc; } } Document* ExpertDiscoveryLoadControlTask::loadFile(QString inFile){ GUrl URL(inFile); // Project *project = AppContext::getProject(); // // Q_ASSERT(project); // Document *doc = project->findDocumentByURL(URL); // // // document already present in the project // if (doc) { // return doc; // } QList formats = DocumentUtils::detectFormat(inFile); if (formats.isEmpty()) { stateInfo.setError(tr("Detecting format error for file %1").arg(inFile)); return NULL; } DocumentFormat* format = formats.first().format; IOAdapterFactory* iof = AppContext::getIOAdapterRegistry()->getIOAdapterFactoryById(BaseIOAdapters::url2io(URL)); Document* doc = new Document(format, iof, URL, QList()); //addSubTask(new AddDocumentTask(doc)); // add document to the project addSubTask(new LoadUnloadedDocumentTask(doc)); // load document return doc; } void ExpertDiscoveryErrors::fileOpenError(const QString &filename) { QMessageBox mb(QMessageBox::Critical, tr("File opening error"), tr("Error opening file %1").arg(filename)); mb.exec(); } void ExpertDiscoveryErrors::markupLoadError() { QMessageBox mb(QMessageBox::Critical, tr("Error"), tr("Error loading markups")); mb.exec(); } ExpertDiscoverySignalExtractorTask::ExpertDiscoverySignalExtractorTask(ExpertDiscoveryData* d) : Task(tr("ExpertDiscovery signals extracting"), TaskFlags(TaskFlag_FailOnSubtaskCancel)){ data = d; extractor = NULL; } ExpertDiscoverySignalExtractorTask::~ExpertDiscoverySignalExtractorTask(){ delete extractor; } void ExpertDiscoverySignalExtractorTask::run(){ //test //folder = &data->getRootFolder(); //performNextStep(); // if(!extractor){ return; } stateInfo.progress = 0; //test // Signal* ps = NULL; // OpReiteration *op = new OpReiteration(); // op->setCount(Interval(1,2)); // op->setDistance(Interval(1,2)); // ps = new Signal(op,"olegSig","descrSig"); // emit si_newSignalReady(ps->clone(), folder); // // Signal* ps1 = NULL; // OpReiteration *op1 = new OpReiteration(); // op->setCount(Interval(1,2)); // op->setDistance(Interval(1,2)); // ps1 = new Signal(op,"olegSig","descrSig1"); // emit si_newSignalReady(ps1->clone(), folder); //test while(performNextStep()){ if (stateInfo.cancelFlag) break; stateInfo.progress = short(extractor->progress() + 0.5); } stateInfo.progress = 100; } void ExpertDiscoverySignalExtractorTask::prepare(){ //relocate //data->markupLetters(); ExpertDiscoveryExtSigWiz w(QApplication::activeWindow(), &data->getRootFolder(), data->getMaxPosSequenceLen()); if(w.exec()){ PredicatBase* predicatBase = new PredicatBase(data->getDescriptionBase()); predicatBase->create(w.getPredicates()); extractor = new Extractor(&data->getPosSeqBase(), &data->getNegSeqBase(), predicatBase); extractor->setFisherBound ( w.getFisher()); extractor->setProbabilityBound ( w.getProbability()); extractor->setInterestFisher ( w.getIntFisher()); extractor->setInterestProbability ( w.getIntProbability()); extractor->setCoverageBound ( w.getCoverage()); extractor->setMaxComplexity ( w.getMaxComplexity()); extractor->setMinComplexity ( w.getMinComplexity()); extractor->setMinCorrelationOnPos ( w.getMinPosCorrelation()); extractor->setMaxCorrelationOnPos ( w.getMaxPosCorrelation()); extractor->setMinCorrelationOnNeg ( w.getMinNegCorrelation()); extractor->setMaxCorrelationOnNeg ( w.getMaxNegCorrelation()); extractor->setCorrelationImportant ( w.getCorrelationImportant()); extractor->setCheckFisherMinimization ( w.getCheckFisherMinimization()); extractor->setStoreOnlyDifferent ( w.getStoreOnlyDifferent()); extractor->setUmEnabled( w.getUmEnabled()); extractor->setUmSamplesBound( w.getUmSamplesBound()); extractor->setUmBound( w.getUmBound()); folder = w.getFolder(); } } bool ExpertDiscoverySignalExtractorTask::performNextStep(){ Signal* pSignal = NULL; bool needOneMore = extractor->step(&pSignal); if (pSignal){ //void* pointer = (void*)(pSignal->clone()); //QVariant signal = qVariantFromValue(pointer); emit si_newSignalReady(pSignal->clone(), folder); } return needOneMore; //test /*Signal* ps = NULL; OpReiteration *op = new OpReiteration(); op->setCount(Interval(1,2)); op->setDistance(Interval(1,2)); ps = new Signal(op,"olegSig","descrSig"); emit si_newSignalReady(ps->clone(), folder); Signal* ps1 = NULL; OpReiteration *op1 = new OpReiteration(); op->setCount(Interval(1,2)); op->setDistance(Interval(1,2)); ps1 = new Signal(op,"olegSig","descrSig1"); emit si_newSignalReady(ps1->clone(), folder); return false;*/ } ExpertDiscoveryCreateADVTask::ExpertDiscoveryCreateADVTask(const MultiGSelection& selObjects) : Task(tr("ExpertDiscovery sequence view"), TaskFlags(TaskFlag_NoRun)) ,adv(NULL) ,multiSelection(selObjects) { } void ExpertDiscoveryCreateADVTask::run(){ // QSet objectsToOpen = SelectionUtils::findObjects(GObjectTypes::SEQUENCE, &multiSelection, UOF_LoadedAndUnloaded); // // QSet selectedObjects = SelectionUtils::findObjects("", &multiSelection, UOF_LoadedAndUnloaded); // QList objectsWithSequenceRelation = GObjectUtils::selectObjectsWithRelation(selectedObjects.toList(), // GObjectTypes::SEQUENCE, GObjectRelationRole::SEQUENCE, UOF_LoadedAndUnloaded, true); // // objectsToOpen.unite(objectsWithSequenceRelation.toSet()); // // const DocumentSelection* ds = qobject_cast(multiSelection.findSelectionByType(GSelectionTypes::DOCUMENTS)); // if (ds != NULL) { // foreach(Document* doc, ds->getSelectedDocuments()) { // objectsToOpen.unite(doc->findGObjectByType(GObjectTypes::SEQUENCE, UOF_LoadedAndUnloaded).toSet()); // objectsToOpen.unite(GObjectUtils::selectObjectsWithRelation(doc->getObjects(), GObjectTypes::SEQUENCE, // GObjectRelationRole::SEQUENCE, UOF_LoadedAndUnloaded, true).toSet()); // } // } // OpenAnnotatedDNAViewTask* task = new OpenAnnotatedDNAViewTask(objectsToOpen.toList()); } ExpertDiscoveryCreateViewTask::ExpertDiscoveryCreateViewTask(const QList& objects) : ObjectViewTask("ED") ,adv(NULL) { // remember only sequence objects -> other added automatically // load all objects QSet docsToLoadSet; QSet refsAdded; QList allSequenceObjects = GObjectUtils::findAllObjects(UOF_LoadedAndUnloaded, GObjectTypes::SEQUENCE); foreach(GObject* obj, objects) { uiLog.trace("Object to open sequence view: '" + obj->getGObjectName()+"'"); Document* doc = obj->getDocument(); if (!doc->isLoaded()) { docsToLoadSet.insert(doc); } if (GObjectUtils::hasType(obj, GObjectTypes::SEQUENCE)) { sequenceObjectRefs.append(GObjectReference(doc->getURLString(), obj->getGObjectName(), GObjectTypes::SEQUENCE)); refsAdded.insert(obj); continue; } //look for sequence object using relations QList objWithSeqRelation = GObjectUtils::selectRelations(obj, GObjectTypes::SEQUENCE, GObjectRelationRole::SEQUENCE, allSequenceObjects, UOF_LoadedAndUnloaded); foreach(GObject* robj, objWithSeqRelation) { if (!GObjectUtils::hasType(robj, GObjectTypes::SEQUENCE)) { continue; } if (refsAdded.contains(robj)) { continue; } Document* rdoc = robj->getDocument(); if (!rdoc->isLoaded()) { docsToLoadSet.insert(rdoc); } refsAdded.insert(robj); sequenceObjectRefs.append(GObjectReference(rdoc->getURLString(), robj->getGObjectName(), GObjectTypes::SEQUENCE)); } } foreach(Document* doc, docsToLoadSet) { uiLog.trace("Document to load: '" + doc->getURLString()+"'"); documentsToLoad.append(doc); } } #define MAX_SEQ_OBJS_PER_VIEW 50 static QString deriveViewName(const QList& seqObjects) { QString viewName; if (seqObjects.size() > 1) { bool singleDocument = true; Document* doc = seqObjects.first()->getDocument(); foreach(GObject* obj, seqObjects) { if (doc != obj->getDocument()) { singleDocument = false; break; } } if (singleDocument) { viewName = GObjectViewUtils::genUniqueViewName(doc->getName()); } else { viewName = GObjectViewUtils::genUniqueViewName(ExpertDiscoveryCreateViewTask::tr("ED")); } } else { GObject* obj = seqObjects.first(); viewName = GObjectViewUtils::genUniqueViewName(obj->getDocument(), obj); } return viewName; } static bool objLessThan(const DNASequenceObject* o1 , const DNASequenceObject* o2) { if (o1->getDocument() == o2->getDocument()) { return o1->getGObjectName() < o2->getGObjectName(); } return o1->getDocument()->getURLString() < o2->getDocument()->getURLString(); } void ExpertDiscoveryCreateViewTask::open() { if (stateInfo.hasError() || sequenceObjectRefs.isEmpty()) { return; } QList seqObjects; QList allSequenceObjects = GObjectUtils::findAllObjects(UOF_LoadedOnly, GObjectTypes::SEQUENCE); foreach(const GObjectReference& r, sequenceObjectRefs) { GObject* obj = GObjectUtils::selectObjectByReference(r, allSequenceObjects, UOF_LoadedOnly); DNASequenceObject* seqObj = qobject_cast(obj); if (seqObj!=NULL) { seqObjects.append(seqObj); if (seqObjects.size() > MAX_SEQ_OBJS_PER_VIEW) { uiLog.details(tr("Maximum number of objects per view reached: %1").arg(MAX_SEQ_OBJS_PER_VIEW)); break; } } else { uiLog.details(tr("Sequence object not available! URL %1, name %2").arg(r.docUrl).arg(r.objName)); } } if (seqObjects.isEmpty()) { //object was removed asynchronously with the task stateInfo.setError(tr("No sequence objects found")); return; } qSort(seqObjects.begin(), seqObjects.end(), objLessThan); QString viewName = deriveViewName(seqObjects); AnnotatedDNAView* v = new AnnotatedDNAView(viewName, seqObjects); adv = v; // GObjectViewWindow* w = new GObjectViewWindow(v, viewName, false); // MWMDIManager* mdiManager = AppContext::getMainWindow()->getMDIManager(); // mdiManager->addMDIWindow(w); } ExpertDiscoverySignalsAutoAnnotationUpdater::ExpertDiscoverySignalsAutoAnnotationUpdater() :AutoAnnotationsUpdater(tr("Signals"), "ExpertDiscover Signals") ,curPS(NULL) ,edData(NULL) ,mutex(NULL) { } Task* ExpertDiscoverySignalsAutoAnnotationUpdater::createAutoAnnotationsUpdateTask(const AutoAnnotationObject* aa){ if(!edData){ return NULL; } AnnotationTableObject* aObj = aa->getAnnotationObject(); const DNASequence& dna = aa->getSeqObject()->getDNASequence(); Task* task = new ExpertDiscoveryToAnnotationTask(aObj, dna, edData, curPS, *mutex); return task; } bool ExpertDiscoverySignalsAutoAnnotationUpdater::checkConstraints(const AutoAnnotationConstraints& constraints){ if (constraints.alphabet == NULL) { return false; } bool edEnabled = false; if(constraints.hints != NULL){ QVariant hint = constraints.hints->get("EDHint"); if(hint.isNull()){ return false; } edEnabled = hint.toBool(); } return constraints.alphabet->isNucleic() && edEnabled; } ExpertDiscoveryToAnnotationTask::ExpertDiscoveryToAnnotationTask(AnnotationTableObject* aobj, const DNASequence& seq, ExpertDiscoveryData* d, const EDProcessedSignal* ps, QMutex& mut) :Task(tr("Find and store expert discovery signals on a sequence"), TaskFlags_FOSCOE), dna(seq), edData(d), aObj(aobj), curPS(ps), mutex(mut){ seqRange = U2Region(0, seq.length()); } void ExpertDiscoveryToAnnotationTask::run(){ if (isCanceled() || hasError()) { return; } if (aObj.isNull()) { stateInfo.setError( tr("Annotation table does not exist") ); return; } if (aObj->isStateLocked()) { stateInfo.setError( tr("Annotation table is read-only") ); return; } assert(edData); int seqNumber = -1; DDisc::Sequence edSeq; seqNumber = edData->getPosSeqBase().getObjNo(dna.getName().toStdString().c_str()); if(seqNumber == -1){ seqNumber = edData->getNegSeqBase().getObjNo(dna.getName().toStdString().c_str()); if(seqNumber == -1){ seqNumber = edData->getConSeqBase().getObjNo(dna.getName().toStdString().c_str()); if(seqNumber == -1){ stateInfo.setError(tr("No expert discovery sequence")); return; }else{ edSeq = edData->getConSeqBase().getSequence(seqNumber); isControl = true; } }else{ edSeq = edData->getNegSeqBase().getSequence(seqNumber); isControl = false; isPos = false; } } else{ edSeq = edData->getPosSeqBase().getSequence(seqNumber); isControl = false; isPos = true; } //cs start // mutex.lock(); csToAnnotation(seqNumber, edSeq.getSize()); hasRecData = edData->recDataStorage.getRecognizationData(recData, &edSeq, edData->getSelectedSignalsContainer()); if(hasRecData){ recDataToAnnotation(); } // mutex.unlock(); //cs end } Task::ReportResult ExpertDiscoveryToAnnotationTask::report(){ if (isCanceled() || hasError()) { return ReportResult_Finished; } if (aObj->isStateLocked()) { setError(tr("Annotation obj %1 is locked for modifications").arg(aObj->getGObjectName())); return ReportResult_Finished; } QList annotations; foreach (const SharedAnnotationData& data, resultList) { annotations.append(new Annotation(data)); } aObj->addAnnotations(annotations, "ExpertDiscover Signals"); return ReportResult_Finished; } void ExpertDiscoveryToAnnotationTask::csToAnnotation(int seqNumber, unsigned int seqLen){ assert(seqNumber!=-1); if(isControl || !curPS){ return; } //EDProcessedSignal curPsCopy = *curPS; if(isPos){ if(curPS->getYesSequenceNumber() <= seqNumber){ return; } }else{ if(curPS->getNoSequenceNumber() <= seqNumber){ return; } } const Set& set = isPos? curPS->getYesRealizations(seqNumber) : curPS->getNoRealizations(seqNumber); unsigned int i = 0; unsigned int j = 0; QString first_data = ""; QString second_data = ""; while(i < seqLen){ first_data = ""; if(set.is_set(i)){ first_data = QString::fromStdString(set.association(i)); } j = i+1; while(j < seqLen){ second_data = ""; if(set.is_set(j)){ second_data = QString::fromStdString(set.association(i)); } if(first_data != second_data || second_data.isEmpty()){ break; } j++; } if(!first_data.isEmpty()){ SharedAnnotationData data; data = new AnnotationData; data->name = "signal"; data->location->regions << U2Region(i,j-i); data->qualifiers.append(U2Qualifier("name", first_data)); resultList.append(data); } i = j; } // QMap> sigMap; // QList regions; // for(unsigned int i = 0; i emptyList; // sigMap.insert(sigName, emptyList); // // } // // sigMap[sigName].append(U2Region(i,1)); // //regions.append(U2Region(i,1)); // // //data->location->regions << U2Region(i,1); // } // } // foreach(QString name, sigMap.keys()){ // // QString sigName = QString::fromStdString(set.association(i)); // SharedAnnotationData data; // data = new AnnotationData; // data->name = "signal"; // const QList& regions = sigMap.value(name); // foreach(U2Region reg, regions){ // data->location->regions << reg; // } // // data->qualifiers.append(U2Qualifier("name", name)); // resultList.append(data); // } } void ExpertDiscoveryToAnnotationTask::recDataToAnnotation(){ unsigned int recSize= recData.size(); unsigned int i = 0; unsigned int j = 0; double first_rec_data = 0; double second_rec_data = 0; while(i < recSize){ first_rec_data = recData[i]; j = i+1; while(j < recSize){ second_rec_data = recData[j]; if(first_rec_data != second_rec_data){ break; } j++; } if(first_rec_data!=0){ SharedAnnotationData data; data = new AnnotationData; data->name = "rec.data"; data->location->regions << U2Region(i,j-i); data->qualifiers.append(U2Qualifier("criteria", QString::number(first_rec_data))); resultList.append(data); } i = j; } // SharedAnnotationData data; // data = new AnnotationData; // data->name = "rec.data"; // data->location->regions << U2Region(1,3); // data->qualifiers.append(U2Qualifier("ed_rec_criteria", "3")); // // return data; } ExpertDiscoverySaveDocumentTask::ExpertDiscoverySaveDocumentTask(ExpertDiscoveryData& data, const QString& fileName) :Task("Save ExpertDiscovery document task", TaskFlag_None) ,edData(data) ,filename(fileName) { } void ExpertDiscoverySaveDocumentTask::run(){ if(hasError()) { return; } QFile file(filename); if(!file.open(QIODevice::WriteOnly)) { setError(L10N::errorOpeningFileWrite(filename)); return; } QDataStream out(&file); //out.setByteOrder(QDataStream::LittleEndian); EDPMCSFolder::save(out, &edData.getRootFolder()); out << edData.getRecognizationBound(); out << false; EDPMSeqBase::save(out, edData.getPosSeqBase()); EDPMSeqBase::save(out,edData.getNegSeqBase()); EDPMSeqBase::save(out,edData.getConSeqBase()); EDPMMrkBase::save(out, edData.getPosMarkBase(), edData.getPosSeqBase().getSize()); EDPMMrkBase::save(out, edData.getNegMarkBase(), edData.getNegSeqBase().getSize()); EDPMMrkBase::save(out,edData.getConMarkBase(), edData.getConSeqBase().getSize()); EDPMDescription::save(out, edData.getDescriptionBaseNoConst()); edData.getPosSeqBase().setMarking(edData.getPosMarkBase()); edData.getNegSeqBase().setMarking(edData.getNegMarkBase()); edData.getConSeqBase().setMarking(edData.getConMarkBase()); edData.getSelectedSignalsContainer().save(out, edData.getRootFolder()); out << false << 1; //LargeSequeceMode (for compatibility with the old version) edData.setModifed(false); } ExpertDiscoveryLoadDocumentTask::ExpertDiscoveryLoadDocumentTask(ExpertDiscoveryData& data, const QString& fileName) :Task("Load ExpertDiscovery document task", TaskFlag_None) ,edData(data) ,filename(fileName) { } void ExpertDiscoveryLoadDocumentTask::run(){ if(hasError()) { return; } QFile file(filename); if(!file.open(QIODevice::ReadOnly)) { setError(L10N::errorOpeningFileRead(filename)); return; } QDataStream inStream(&file); EDPMCSFolder::load(inStream, &edData.getRootFolder()); bool m_bOptimizeRecogniztionBound; double m_dRecognizationBound; inStream >> m_dRecognizationBound; inStream >> m_bOptimizeRecogniztionBound; edData.setRecBound(m_dRecognizationBound); EDPMSeqBase::load(inStream, edData.getPosSeqBase()); EDPMSeqBase::load(inStream, edData.getNegSeqBase()); EDPMSeqBase::load(inStream, edData.getConSeqBase()); EDPMMrkBase::load(inStream, edData.getPosMarkBase(), edData.getPosSeqBase().getSize()); EDPMMrkBase::load(inStream, edData.getNegMarkBase(), edData.getNegSeqBase().getSize()); EDPMMrkBase::load(inStream, edData.getConMarkBase(), edData.getConSeqBase().getSize()); EDPMDescription::load(inStream, edData.getDescriptionBaseNoConst()); edData.getPosSeqBase().setMarking(edData.getPosMarkBase()); edData.getNegSeqBase().setMarking(edData.getNegMarkBase()); edData.getConSeqBase().setMarking(edData.getConMarkBase()); edData.getSelectedSignalsContainer().load(inStream, edData.getRootFolder()); } }//namespace ugene-1.9.8/src/plugins/expert_discovery/src/ExpertDiscoveryData.h0000644000175000017500000001026411651544323024060 0ustar ilyailya#ifndef _EXPERTDISCOVERIDATAHEADER_ #define _EXPERTDISCOVERIDATAHEADER_ #include "DDisc/Sequence.h" #include "DDisc/MetaInfo.h" #include "ExpertDiscoveryCSUtil.h" #include "ExpertDiscoveryTreeWidgets.h" #include #include namespace U2 { using namespace DDisc; class EDProjectItem; class EDPICS; class EDPISequence; const int ED_UPDATE_ALL = 0; const int ED_CURRENT_ITEM_CHANGED = 1; const int ED_ITEM_NAME_CHANGED = 2; const int ED_ITEM_STATE_CHANGED = 3; const int ED_ITEM_ADDED = 4; const int ED_ITEM_DELETED = 5; const int ED_UPDATE_CHILDREN = 6; const int ED_PROPERTY_CHANGED = 7; const int ED_MRK_UPDATE = 8; enum SequenceType {POSITIVE_SEQUENCE, NEGATIVE_SEQUENCE, CONTROL_SEQUENCE, UNKNOWN_SEQUENCE}; class ExpertDiscoveryData : public QObject{ Q_OBJECT public: static const std::string FAMILY_LETTERS; static const std::string FAMILY_LETTERS_METHOD; ExpertDiscoveryData (); void setPosBase(const QList &); void setNegBase(const QList &); void setConBase(const QList &); void markupLetters(void); void markupLetters(SequenceBase& rBase, MarkingBase& rAnn); bool isLettersMarkedUp(void) const; void clearScores(); const MetaInfoBase& getDescriptionBase() const { return desc;} MetaInfoBase& getDescriptionBaseNoConst() { return desc;} SequenceBase& getPosSeqBase() {return posBase;} SequenceBase& getNegSeqBase() {return negBase;} SequenceBase& getConSeqBase() {return conBase;} MarkingBase& getPosMarkBase() {return posAnn;} MarkingBase& getNegMarkBase() {return negAnn;} MarkingBase& getConMarkBase() {return conAnn;} void clearContrBase(); void clearContrAnnot(); CSFolder& getRootFolder(){return rootFolder;} bool updateScore(Sequence& rSeq); double getRecognizationBound() const { return recognizationBound; } void setRecBound(double val){recognizationBound = val;} void optimizeRecognizationBound(); void setRecBound(); bool updateScores(); bool isSignalSelected(const EDProjectItem* pItem); void switchSelection(EDProjectItem* pItem, bool upd); SelectedSignalsContainer& getSelectedSignalsContainer() { return selectedSignals; } void onSetCurrentSignalParamsAsPrior(EDPICS *pItem, bool bUpdate); void onClearSignalPriorParams(EDPICS *pItem); SequenceType getSequenceTypeByName(const QString& seqName); bool loadMarkup(const QString& firstF, const QString& secondF, const QString& thirdF, bool generateDescr); bool loadAnnotation(MarkingBase& base, const SequenceBase& seqBase, QString strFileName); bool generateDescription(bool clearDescr = true); void loadControlSequenceAnnotation(const QString& fileName); void cleanup(); void addSequenceToSelected(EDPISequence* seq); void clearSelectedSequencesList(); bool isSequenceSelected(EDPISequence* seq); QList getSelectetSequencesList(); void generateRecognitionReportFull(); bool generateRecognizationReportHeader(ostream& out) const; bool generateRecognizationReportFooter(ostream& out) const; bool generateRecognizationReport(ostream& out, const SequenceBase& rBase, QString strName, bool bSuppressNulls); bool generateRecognizationReportPositive(ostream& out, QString strName, bool bSuppressNulls); int getSequencesCountWithScoreMoreThan(double dScore, const SequenceBase& rBase) const; void generateRecognizationReport(EDProjectItem* pItem); bool isModified() {return modified;} void setModifed(bool modFlag = true){modified = modFlag;} int getMaxPosSequenceLen(); double recognizationBound; RecognizationDataStorage recDataStorage; QList selSequences; private: SequenceBase posBase; SequenceBase negBase; SequenceBase conBase; MetaInfoBase desc; MarkingBase posAnn; MarkingBase negAnn; MarkingBase conAnn; CSFolder rootFolder; bool modified; SelectedSignalsContainer selectedSignals; inline Sequence prerareSequence(const GObject* obj) const; static std::string char2string(char ch); }; }//namespace #endif ugene-1.9.8/src/plugins/expert_discovery/src/ExpertDiscoveryTreeWidgets.h0000644000175000017500000004006311651544323025435 0ustar ilyailya#ifndef _U2_EXPERT_DIS_TREEWIDGETS_H_ #define _U2_EXPERT_DIS_TREEWIDGETS_H_ #include "DDisc/Signal.h" #include "DDisc/MetaInfo.h" //#include "ExpertDiscoveryCSUtil.h" #include "ExpertDiscoveryData.h" #include #include #include namespace U2 { using namespace DDisc; inline QString toString(double v) { QString str = "%1"; return str.arg(v); } inline QString toString(int v) { QString str = "%1"; return str.arg(v); } inline QString toString(QString v) { return v; } inline QString toString(std::string v) { return QString::fromStdString(v); } inline QString toString(size_t v) { return toString((int) v); } class ICallback { public: virtual ~ICallback() {} virtual QString call() = 0; virtual ICallback* clone() = 0; }; template class Callback : public ICallback{ public: typedef Result (T::*PFUNK)() const; typedef PFUNK PCALLBACK; Callback(T* object, PCALLBACK callback) { m_callback = callback; m_object = object; } virtual ~Callback() {} virtual QString call() { return toString((m_object->*m_callback)()); } virtual ICallback* clone() { return new Callback(m_object, m_callback); } private: PCALLBACK m_callback; T* m_object; }; enum EItemType { PIT_NONE, PIT_SEQUENCEROOT, PIT_POSSEQUENCEBASE, PIT_NEGSEQUENCEBASE, PIT_CONTROLSEQUENCEBASE, PIT_SEQUENCE, PIT_CONTROLSEQUENCE, PIT_CS_ROOT, PIT_CS_FOLDER, PIT_CS, PIT_CSN_UNDEFINED, PIT_CSN_DISTANCE, PIT_CSN_REPETITION, PIT_CSN_INTERVAL, PIT_CSN_WORD, PIT_CSN_MRK_ITEM, PIT_MRK_ROOT, PIT_MRK_FAMILY, PIT_MRK_ITEM, PIT_WORK_ROOT, PIT_WORK_RUNNING, PIT_WORK_PAUSED }; class EDPIPropertyType : public QObject { Q_OBJECT public: EDPIPropertyType(); virtual ~EDPIPropertyType(); virtual bool isNumber() const = 0; virtual bool hasEdit() const = 0; virtual bool hasPredefinedValues() const = 0; virtual int getValueNumber() const = 0; virtual QString getValue(int i) const = 0; virtual bool isValidValue(QString strValue) const = 0; }; class EDPIProperty : public QObject { Q_OBJECT public: EDPIProperty(const EDPIProperty& rProperty); EDPIProperty(QString strName = ""); ~EDPIProperty(); const EDPIProperty& operator =(const EDPIProperty&); const EDPIPropertyType* getType() const; void setType(EDPIPropertyType*); QString getName() const; void setName(QString strName); QString getValue() const; void setCallback(ICallback* pCallback); private: QString m_strName; EDPIPropertyType* m_pType; ICallback* m_pCallback; }; class EDPIPropertyGroup : public QObject { Q_OBJECT public: EDPIPropertyGroup(QString strName =""); EDPIPropertyGroup(const EDPIPropertyGroup&); ~EDPIPropertyGroup(); const EDPIPropertyGroup& operator=(const EDPIPropertyGroup&); QString getName() const; void setName(QString strName); int getPropertiesNumber() const; EDPIProperty& getProperty(int nProp); const EDPIProperty& getProperty(int nProp) const; void addProperty(EDPIProperty &rProperty); private: QString m_strName; QVector m_arProperties; }; /////////////////////////////////////////////////////////////////////// #define DEFINE_GETINSTANCE(class_name) \ public: inline static class_name* getInstance() { return &s_##class_name##Instance; } \ virtual void Release() {}; \ virtual EDPIPropertyType* Clone() { return this;}; \ private: static class_name s_##class_name##Instance; #define IMPLEMENT_GETINSTANCE(class_name) \ class_name class_name::s_##class_name##Instance; class EDPIPropertyTypeStaticString : public EDPIPropertyType { DEFINE_GETINSTANCE(EDPIPropertyTypeStaticString) public: EDPIPropertyTypeStaticString(); virtual ~EDPIPropertyTypeStaticString(); virtual bool isNumber() const; virtual bool hasEdit() const; virtual bool hasPredefinedValues() const; virtual int getValueNumber() const; virtual QString getValue(int i) const; virtual bool isValidValue(QString strValue) const; }; class EDPIPropertyTypeString : public EDPIPropertyTypeStaticString { DEFINE_GETINSTANCE(EDPIPropertyTypeString) public: EDPIPropertyTypeString(); virtual ~EDPIPropertyTypeString(); virtual bool hasEdit() const; }; class EDPIPropertyTypeUnsignedInt : public EDPIPropertyType { DEFINE_GETINSTANCE(EDPIPropertyTypeUnsignedInt) public: EDPIPropertyTypeUnsignedInt(); virtual ~EDPIPropertyTypeUnsignedInt(); virtual bool isNumber() const; virtual bool hasEdit() const; virtual bool hasPredefinedValues() const; virtual int getValueNumber() const; virtual QString getValue(int i) const; virtual bool isValidValue(QString strValue) const; }; class EDPIPropertyTypeList : public EDPIPropertyType { public: EDPIPropertyTypeList(); EDPIPropertyTypeList(const EDPIPropertyTypeList& rList) { m_arValues.clear(); m_arValues = rList.m_arValues; } virtual ~EDPIPropertyTypeList(); virtual bool isNumber() const; virtual bool hasEdit() const; virtual bool hasPredefinedValues() const; virtual int getValueNumber() const; virtual QString getValue(int i) const; virtual bool isValidValue(QString strValue) const; int getValueId(QString strValue) const; protected: void addValue(QString strValue); private: QStringList m_arValues; }; class EDPIPropertyTypeDynamicList : public EDPIPropertyTypeList { public: EDPIPropertyTypeDynamicList() {}; EDPIPropertyTypeDynamicList(const EDPIPropertyTypeDynamicList& rList) : EDPIPropertyTypeList(rList) {}; virtual ~EDPIPropertyTypeDynamicList() {}; void addValue(QString strValue) {EDPIPropertyTypeList::addValue(strValue);}; inline static EDPIPropertyTypeDynamicList* getInstance() { return new EDPIPropertyTypeDynamicList(); } virtual void Release() { delete this;} virtual EDPIPropertyType* Clone() { return new EDPIPropertyTypeDynamicList(*this);} }; class EDPIPropertyTypeListEdit : public EDPIPropertyTypeList { public: EDPIPropertyTypeListEdit() : EDPIPropertyTypeList() {} virtual ~EDPIPropertyTypeListEdit() {} virtual bool isNumber() const {return false;} virtual bool hasEdit() const {return true;} virtual bool isValidValue(QString strValue) const {return true;} }; class EDPIPropertyTypeUnsignedIntWithUnl : public EDPIPropertyTypeListEdit { DEFINE_GETINSTANCE(EDPIPropertyTypeUnsignedIntWithUnl) public: EDPIPropertyTypeUnsignedIntWithUnl(); virtual ~EDPIPropertyTypeUnsignedIntWithUnl(); virtual bool isNumber() const; virtual bool isValidValue(QString strValue) const; }; class EDPIPropertyTypeListCSNodeTypes : public EDPIPropertyTypeList { DEFINE_GETINSTANCE(EDPIPropertyTypeListCSNodeTypes); public: enum { DISTANCE, REPETITION, INTERVAL, WORD, MRK_ITEM }; EDPIPropertyTypeListCSNodeTypes(); }; class EDPIPropertyTypeBool : public EDPIPropertyTypeList { DEFINE_GETINSTANCE(EDPIPropertyTypeBool); public: enum { False, True }; EDPIPropertyTypeBool(); }; class EDPIPropertyTypeDistType : public EDPIPropertyTypeList { DEFINE_GETINSTANCE(EDPIPropertyTypeDistType); public: enum { FINISH_TO_START, START_TO_START, MIDDLE_TO_START }; EDPIPropertyTypeDistType(); }; //////////////////////////////////////////////////// enum EDSortParameters{ ED_ORDER_INCREASING, ED_ORDER_DECREASING, ED_FIELD_NAME, ED_FIELD_PROBABILITY, ED_FIELD_FISHER, ED_FIELD_COVERAGE, ED_FIELD_UNDEFINED }; class EDProjectItem : public QObject, public QTreeWidgetItem { Q_OBJECT public: //CProjectItem(QTreeWidget * parent); EDProjectItem(); virtual ~EDProjectItem(); virtual QString getName() const {return name;} virtual void setName(const QString& strName){ name = strName;} int getGroupNumber() const; EDPIPropertyGroup& getGroup(int nGroup); const EDPIPropertyGroup& getGroup(int nGroup) const; int addGroup(const EDPIPropertyGroup& rGroup); virtual EItemType getType() const; virtual void update(bool bUpdateChildren) = 0; virtual bool isConnectedTo(void *pData) const = 0; const EDProjectItem* findItemConnectedTo(void *pData) const; void setMetainfoBase(const MetaInfoBase* base){mInf = base;} const MetaInfoBase* getMinfo(){return mInf;} virtual bool operator<(const QTreeWidgetItem &other) const; void setSortField(EDSortParameters par) {sortField = par;} void setSortOrd(EDSortParameters par) {sortOrd = par;} private: QString name; EDSortParameters sortField; EDSortParameters sortOrd; protected: void clearGroups(); private: //mutable int m_nArgNo; //mutable HTREEITEM m_hTreeItem; QVector m_arGroups; //CArray m_arSubitems; const MetaInfoBase* mInf; signals: void si_getMetaInfoBase(); }; class ExpertDiscoveryData; class EDPISequenceRoot : public EDProjectItem { public: EDPISequenceRoot(ExpertDiscoveryData& edD); virtual ~EDPISequenceRoot(); EItemType getType() const; virtual void update(bool bUpdateChildren); virtual bool isConnectedTo(void *pData) const; private: ExpertDiscoveryData& edData; }; class EDPISequenceBase : public EDProjectItem { public: EDPISequenceBase(QString strName, const SequenceBase& , ExpertDiscoveryData& edD); virtual ~EDPISequenceBase(); const SequenceBase& getSequenceBase() const; virtual void update(bool bUpdateChildren); virtual bool isConnectedTo(void *pData) const; protected: const SequenceBase& m_rSeqBase; ExpertDiscoveryData& edData; }; class EDPIPosSequenceBase : public EDPISequenceBase { public: EDPIPosSequenceBase(const SequenceBase& rBase, ExpertDiscoveryData& edD); virtual ~EDPIPosSequenceBase(); EItemType getType() const; virtual void update(bool bUpdateChildren); }; class EDPINegSequenceBase : public EDPISequenceBase { public: EDPINegSequenceBase(const SequenceBase& rBase, ExpertDiscoveryData& edD); virtual ~EDPINegSequenceBase(); EItemType getType() const; virtual void update(bool bUpdateChildren); }; class EDPIControlSequenceBase : public EDPISequenceBase { public: EDPIControlSequenceBase(const SequenceBase& rBase, ExpertDiscoveryData& edD); virtual ~EDPIControlSequenceBase(); EItemType getType() const; virtual void update(bool bUpdateChildren); }; class EDPISequence : public EDProjectItem { public: EDPISequence(const SequenceBase&, int id, ExpertDiscoveryData& edD); virtual ~EDPISequence(); virtual EItemType getType() const; QString getSequenceCode(); QString getSequenceName(); virtual void update(bool bUpdateChildren); virtual bool isConnectedTo(void *pData) const; QString getScore() const; QString getResult() const; private: ExpertDiscoveryData& edData; int m_id; bool m_firstCall; const Sequence& m_rSeq; }; class EDPIControlSequence : public EDPISequence { public: EDPIControlSequence(const SequenceBase& base, int id, ExpertDiscoveryData& edD) : EDPISequence(base, id, edD) {} virtual ~EDPIControlSequence() {} virtual EItemType getType() const { return PIT_CONTROLSEQUENCE; } }; class EDPICSDirectory : public EDProjectItem { public: EDPICSDirectory(const CSFolder* pFolder) : folder (pFolder) {} virtual ~EDPICSDirectory() {} const CSFolder* getFolder() const; void setFolder(const CSFolder* pFolder); virtual void update(bool bUpdateChildren); virtual bool isConnectedTo(void *pData) const; private: const CSFolder* folder; }; class EDPICSFolder : public EDPICSDirectory { public: EDPICSFolder(const CSFolder *pFolder); virtual ~EDPICSFolder(); EItemType getType() const; virtual void update(bool bUpdateChildren); //virtual CExtPopupMenuWnd* CreatePopupMenu(HWND hWndCmdRecieve) const; virtual QString getName() const; }; class EDPICSNode : public EDProjectItem { public: EDPICSNode(Operation *pOp); virtual ~EDPICSNode(); Operation* getOperation(); void setOperation(Operation *pOp); const Operation* getOperation() const; virtual void update(bool bUpdateChildren); static EDPICSNode* createCSN(Operation *pOp); virtual bool isConnectedTo(void *pData) const; const EDProcessedSignal* getProcessedSignal(ExpertDiscoveryData& edData); QString getProbability() const; QString getFisher() const; QString getUl() const; QString getPosCoverage() const; QString getNegCoverage() const; QString getTypeAsString() const; protected: Operation* pOp; EDProcessedSignal* m_pPS; }; class EDPICSRoot : public EDPICSDirectory { public: EDPICSRoot(CSFolder &root); virtual ~EDPICSRoot(); EItemType getType() const; virtual void update(bool bUpdateChildren); }; class EDPICS : public EDPICSNode { public: EDPICS(const Signal *pSignal); virtual ~EDPICS(); EItemType getType() const; const Signal* getSignal() const; virtual void update(bool bUpdateChildren); virtual bool isConnectedTo(void *pData) const; //virtual CExtPopupMenuWnd* CreatePopupMenu(HWND hWndCmdRecieve) const; //virtual bool IsSelected() const; QString getPriorProbability() const; QString getPriorFisher() const; QString getPriorPosCoverage() const; QString getPriorNegCoverage() const; private: const Signal *m_pSignal; }; class EDPICSNUndefined : public EDPICSNode { public: EDPICSNUndefined(); virtual ~EDPICSNUndefined(); EItemType getType() const; virtual void update(bool bUpdateChildren); }; class EDPICSNDistance : public EDPICSNode { public: EDPICSNDistance(OpDistance *pOp); virtual ~EDPICSNDistance(); EItemType getType() const; virtual void update(bool bUpdateChildren); QString getPropDistType() const; QString getPropFrom() const; QString getPropTo() const; QString getPropOrder() const; }; class EDPICSNRepetition : public EDPICSNode { public: EDPICSNRepetition(OpReiteration *pOp); virtual ~EDPICSNRepetition(); EItemType getType() const; virtual void update(bool bUpdateChildren); QString getPropDistType() const; QString getPropFrom() const; QString getPropTo() const; QString getCountFrom() const; QString getCountTo() const; }; class EDPICSNInterval : public EDPICSNode { public: EDPICSNInterval(OpInterval *pOp); virtual ~EDPICSNInterval(); EItemType getType() const; virtual void update(bool bUpdateChildren); QString getPropFrom() const; QString getPropTo() const; }; class EDPICSNTSWord : public EDPICSNode { public: EDPICSNTSWord(TS *pTS); virtual ~EDPICSNTSWord(); EItemType getType() const; virtual void update(bool bUpdateChildren); QString getPropWord() const; }; class EDPICSNTSMrkItem : public EDPICSNode { public: EDPICSNTSMrkItem(TS *pTS); virtual ~EDPICSNTSMrkItem(); EItemType getType() const; virtual void update(bool bUpdateChildren); QString getPropFamily() const; QString getPropSignal() const; }; class EDPIMrkRoot : public EDProjectItem { public: EDPIMrkRoot(); virtual ~EDPIMrkRoot(); EItemType getType() const; virtual void update(bool bUpdateChildren); void updMarkup(const ExpertDiscoveryData& d); virtual bool isConnectedTo(void *pData) const; //virtual CExtPopupMenuWnd* CreatePopupMenu(HWND hWndCmdRecieve) const; }; class EDPIMrkFamily : public EDProjectItem { public: EDPIMrkFamily(const DDisc::Family& rFamily); virtual ~EDPIMrkFamily(); EItemType getType() const; virtual void update(bool bUpdateChildren); virtual bool isConnectedTo(void *pData) const; private: const DDisc::Family& m_rFamily; }; class EDPIMrkItem : public EDPICSNode { public: EDPIMrkItem(QString strFamilyName, const MetaInfo& rMetaInfo); virtual ~EDPIMrkItem(); EItemType getType() const; virtual void update(bool bUpdateChildren); virtual bool isConnectedTo(void *pData) const; private: const MetaInfo& m_rMetaInfo; }; } //namespace #endif ugene-1.9.8/src/plugins/expert_discovery/src/ExpertDiscoveryExtSigWiz.cpp0000644000175000017500000005340511651544323025443 0ustar ilyailya#include "ExpertDiscoveryExtSigWiz.h" #include "ExpertDiscoveryAdvSetDialog.h" #include namespace U2 { ExpertDiscoveryExtSigWiz::ExpertDiscoveryExtSigWiz(QWidget *parent, CSFolder* f, int positiveSize) : QWizard(parent) ,posSize(positiveSize){ setupUi(this); //1 page connect(advancedButton, SIGNAL(clicked()), SLOT(sl_advButton())); state.setDefaultState(); condProbLevEdit->setText(QString("%1").arg(state.dProbability)); coverBoundEdit->setText(QString("%1").arg(state.dCoverage)); fishCritEdit->setText(QString("%1").arg(state.dFisher)); minimFishCritCheck->setChecked(state.bCheckFisherMinimization); storeCheck->setChecked(state.bStoreOnlyDifferent); ulCritCheck->setChecked(state.bUmEnabled); samplesBoundEdit->setText(QString("%1").arg(state.nUmSamplesBound)); levelBoundEdit->setText(QString("%1").arg(state.dUmBound)); minComplexityEdit->setText(QString("%1").arg(state.nMinComplexity)); maxComplexityEdit->setText(QString("%1").arg(state.nMaxComplexity)); QDoubleValidator* d0_100Valid = new QDoubleValidator(0,100,5,this); QDoubleValidator* d0_1Valid = new QDoubleValidator(0,1,5,this); QDoubleValidator* d0_maxValid = new QDoubleValidator(0,LONG_MAX,0,this); condProbLevEdit->setValidator(d0_100Valid); coverBoundEdit->setValidator(d0_100Valid); fishCritEdit->setValidator(d0_1Valid); samplesBoundEdit->setValidator(d0_maxValid); levelBoundEdit->setValidator(d0_1Valid); //2 page initSet(); predicatesTree->setSelectionMode(QAbstractItemView::SingleSelection); connect(distanseButton,SIGNAL(clicked()), SLOT(sl_distButton())); connect(repetitionButton,SIGNAL(clicked()), SLOT(sl_repetButton())); connect(intervalButton,SIGNAL(clicked()), SLOT(sl_intervButton())); connect(deleteButton,SIGNAL(clicked()), SLOT(sl_deleteButton())); distItem = new QTreeWidgetItem(predicatesTree); repetItem = new QTreeWidgetItem(predicatesTree); intervItem = new QTreeWidgetItem(predicatesTree); distItem->setText(0,"Distance"); repetItem->setText(0,"Repetition"); intervItem->setText(0,"Interval"); connect(predicatesTree, SIGNAL(currentItemChanged (QTreeWidgetItem*, QTreeWidgetItem*)), SLOT(sl_selectionChanged (QTreeWidgetItem*, QTreeWidgetItem*))); //page 3 folder = f; updateTree(); connect(this, SIGNAL(currentIdChanged ( int )), this, SLOT( sl_idChanged(int ))); hideParameters(); } ExpertDiscoveryExtSigWiz::~ExpertDiscoveryExtSigWiz(){ delete distItem; delete repetItem; delete intervItem; delete sigSetLayout; } void ExpertDiscoveryExtSigWiz::sl_advButton(){ ExpertDiscoveryAdvSetDialog adv (this, state.dIntProbability, state.dIntFisher, state.nMinComplexity, state.nMaxComplexity, state.dMinPosCorrelation, state.dMaxPosCorrelation, state.dMinNegCorrelation, state.dMaxNegCorrelation, state.bCorrelationImportant); if(adv.exec()){ } } void ExpertDiscoveryExtSigWiz::sl_distButton(){ OpDistance *pOp = new OpDistance; QTreeWidgetItem *op = new QTreeWidgetItem(distItem); op->setText(0, QString::fromStdString(pOp->getDescription())); void* pointer = (void*)pOp; QVariant variant = qVariantFromValue(pointer); op->setData(0, Qt::UserRole, variant); predicatesTree->setCurrentItem(op); distItem->setExpanded(true); //op->setSelected(true); } void ExpertDiscoveryExtSigWiz::sl_repetButton(){ OpReiteration *pOp = new OpReiteration; QTreeWidgetItem *op = new QTreeWidgetItem(repetItem); op->setText(0, QString::fromStdString(pOp->getDescription())); void* pointer = (void*)pOp; QVariant variant = qVariantFromValue(pointer); op->setData(0, Qt::UserRole, variant); //predicatesTree->clearSelection(); predicatesTree->setCurrentItem(op); repetItem->setExpanded(true); //op->setSelected(true); } void ExpertDiscoveryExtSigWiz::sl_intervButton(){ OpInterval *pOp = new OpInterval; QTreeWidgetItem *op = new QTreeWidgetItem(intervItem); op->setText(0, QString::fromStdString(pOp->getDescription())); void* pointer = (void*)pOp; QVariant variant = qVariantFromValue(pointer); op->setData(0, Qt::UserRole, variant); //predicatesTree->clearSelection(); predicatesTree->setCurrentItem(op); intervItem->setExpanded(true); //op->setSelected(true); } void ExpertDiscoveryExtSigWiz::sl_deleteButton(){ if(predicatesTree->selectedItems().isEmpty()){ return ; } QTreeWidgetItem* item = predicatesTree->selectedItems().first(); QVariant variant = item->data(0, Qt::UserRole); void* pointer = qVariantValue(variant); Operation* pOp = (Operation*) pointer; if (pOp == NULL) return; if (sigSetLayout->currentIndex() != T_UNDEFINED) { sigSetLayout->setCurrentIndex(T_UNDEFINED); } delete pOp; predicatesTree->removeItemWidget(item,0); delete item; } void ExpertDiscoveryExtSigWiz::sl_idChanged(int id){ switch (id){ case 2:{ int minCom = 0; int maxCom = 0; minCom = minComplexityEdit->text().toInt(); maxCom = maxComplexityEdit->text().toInt(); if(minCom>maxCom || minCom<0){ back(); QMessageBox mb(QMessageBox::Critical, tr("Wrong parameters"), tr("Minimal complexity must not be grater then maximal complexity and positive")); mb.exec(); break; }else{ if(!(checkD(condProbLevEdit) && checkD(coverBoundEdit) && checkD(fishCritEdit) && checkD(levelBoundEdit) && checkD(samplesBoundEdit))){ back(); } } break; } case 3: if((intervItem->childCount() == 0 ) && (repetItem->childCount() == 0 ) && (distItem->childCount() == 0 ) && !alignedCheck->isChecked()){ back(); QMessageBox mb(QMessageBox::Critical, tr("No predicates"), tr("Create a predicate to perform signal generation")); mb.exec(); } } } void ExpertDiscoveryExtSigWiz::accept(){ //page2 QVariant variant; void* pointer = NULL; Operation* pOp = NULL; QList ch = distItem->takeChildren(); foreach(QTreeWidgetItem* item, ch){ variant = item->data(0, Qt::UserRole); pointer = qVariantValue(variant); pOp = (Operation*) pointer; predicates.push_back(pOp); delete item; } ch = repetItem->takeChildren(); foreach(QTreeWidgetItem* item, ch){ variant = item->data(0, Qt::UserRole); pointer = qVariantValue(variant); pOp = (Operation*) pointer; predicates.push_back(pOp); delete item; } ch = intervItem->takeChildren(); foreach(QTreeWidgetItem* item, ch){ variant = item->data(0, Qt::UserRole); pointer = qVariantValue(variant); pOp = (Operation*) pointer; predicates.push_back(pOp); delete item; } if(alignedCheck->isChecked()){ for(int i = 0; i < posSize; i++){ OpInterval *pOp = new OpInterval; pOp->setInt(Interval(i, i)); predicates.push_back((Operation*)pOp); } } if(predicates.empty()){ QMessageBox mb(QMessageBox::Critical, tr("No predicates"), tr("Create a predicate to perform signal generation")); mb.exec(); }else{ //page 1 state.dProbability = condProbLevEdit->text().toDouble(); state.dCoverage = coverBoundEdit->text().toDouble(); state.dFisher = fishCritEdit->text().toDouble(); state.bCheckFisherMinimization = minimFishCritCheck->isChecked(); state.bStoreOnlyDifferent = storeCheck->isChecked(); state.bUmEnabled = ulCritCheck->isChecked(); state.nUmSamplesBound = (int)(samplesBoundEdit->text().toDouble()); state.dUmBound = levelBoundEdit->text().toDouble(); state.nMinComplexity = minComplexityEdit->text().toInt(); state.nMaxComplexity = maxComplexityEdit->text().toInt(); //page 3 if(!treeFoldersWidget->selectedItems().isEmpty()){ QTreeWidgetItem* item = treeFoldersWidget->selectedItems().first(); QVariant variant = item->data(0, Qt::UserRole); void* pointer = qVariantValue(variant); CSFolder* f = (CSFolder*) pointer; folder = f; } QWizard::accept(); } } void ExpertDiscoveryExtSigWiz::hideParameters(){ // label_4->hide(); // fishCritEdit->hide(); // minimFishCritCheck->hide(); // storeCheck->hide(); ulCritCheck->hide(); label_5->hide(); samplesBoundEdit->hide(); label_6->hide(); levelBoundEdit->hide(); advancedButton->hide(); } bool ExpertDiscoveryExtSigWiz::checkD(const QLineEdit* lineE) const{ if(!lineE->validator()){ return false; } const QDoubleValidator* validator = qobject_cast(lineE->validator()); int pos = 0; QString textValue=lineE->text(); if(validator->validate(textValue,pos)!=QValidator::Acceptable){ QString msg = QString("Entered value must be from %1 to %2").arg(validator->bottom()).arg(validator->top()); QMessageBox mb(QMessageBox::Critical, tr("Wrong parameters"), tr(msg.toStdString().c_str())); mb.exec(); return false; } return true; } void ExpertDiscoveryExtSigWiz::updateTree(const CSFolder* pFolder, QTreeWidgetItem* treeItem){ QString strName; QTreeWidgetItem* nTreeItem = NULL; if(pFolder == NULL){ treeFoldersWidget->clear(); pFolder = folder; strName = tr("Complex signals"); nTreeItem = new QTreeWidgetItem(treeFoldersWidget); }else{ strName = pFolder->getName(); nTreeItem = new QTreeWidgetItem(treeItem); } nTreeItem->setText(0,strName); void* pointer = (void*)pFolder; QVariant variant = qVariantFromValue(pointer); nTreeItem->setData(0, Qt::UserRole, variant); int nFolderNum = pFolder->getFolderNumber(); for (int i=0; igetSubfolder(i), nTreeItem); } void ExpertDiscoveryExtSigWiz::sl_selectionChanged (QTreeWidgetItem * current, QTreeWidgetItem * previous){ //saving data to the deselected item int curIndex = sigSetLayout->currentIndex(); if(previous== NULL){ return ; } if(previous != distItem && previous != intervItem && previous != repetItem && sigSet[curIndex]->isReadyToClose() && curIndex != T_UNDEFINED){ QVariant variant = previous->data(0, Qt::UserRole); void* pointer = qVariantValue(variant); Operation* pOp = (Operation*) pointer; sigSet[curIndex]->saveData(pOp); previous->setText(0, QString::fromStdString(pOp->getDescription())); variant = qVariantFromValue(pointer); previous->setData(0, Qt::UserRole, variant); sigSetLayout->setCurrentIndex(T_UNDEFINED); } //loading data to the form if(current == NULL || current == distItem || current == intervItem || current == repetItem){ sigSetLayout->setCurrentIndex(T_UNDEFINED); return ; }else if(current->parent()==distItem){ sigSetLayout->setCurrentIndex(T_DISTANCE); QVariant variant = current->data(0,Qt::UserRole); void* dataP = qVariantValue(variant); ((DistanceSet*)sigSet[T_DISTANCE])->loadData(dataP); }else if(current->parent()==intervItem){ sigSetLayout->setCurrentIndex(T_INTERVAL); QVariant variant = current->data(0,Qt::UserRole); void* dataP = qVariantValue(variant); ((IntervalSet*)sigSet[T_INTERVAL])->loadData(dataP); }else if(current->parent()==repetItem){ sigSetLayout->setCurrentIndex(T_REITERATION); QVariant variant = current->data(0,Qt::UserRole); void* dataP = qVariantValue(variant); ((RepetitionSet*)sigSet[T_REITERATION])->loadData(dataP); } } void ExpertDiscoveryExtSigWiz::initSet(){ sigSetLayout = new QStackedLayout(editorBox); //undef sigSet[T_UNDEFINED] = new OperationSet(editorBox); sigSet[T_UNDEFINED]->setEnabled(true); QGridLayout* gridLayoutUndef = new QGridLayout(sigSet[T_UNDEFINED]); QLabel* labelUndef = new QLabel(sigSet[T_UNDEFINED]); labelUndef->setText(tr("Select predicate on the tree above or create a new one using buttons.")); gridLayoutUndef->addWidget(labelUndef, 0, 0, 1, 1); QSpacerItem* verticalSpacerUndef = new QSpacerItem(20, 40, QSizePolicy::Minimum, QSizePolicy::Expanding); gridLayoutUndef->addItem(verticalSpacerUndef, 1, 0, 1, 1); sigSetLayout->insertWidget(T_UNDEFINED,sigSet[T_UNDEFINED]); sigSet[T_DISTANCE] = new DistanceSet(editorBox); sigSetLayout->insertWidget(T_DISTANCE,sigSet[T_DISTANCE]); sigSet[T_REITERATION] = new RepetitionSet(editorBox); sigSetLayout->insertWidget(T_REITERATION,sigSet[T_REITERATION]); sigSet[T_INTERVAL] = new IntervalSet(editorBox); sigSetLayout->insertWidget(T_INTERVAL,sigSet[T_INTERVAL]); sigSetLayout->setCurrentIndex(T_UNDEFINED); verticalLayout_4->addLayout(sigSetLayout); } DistanceSet::DistanceSet (QWidget* parent) : OperationSet(parent) , to(0) , from(0) , isOrderImportant(false) , isMaxUNL(true){ setEnabled(true); QGridLayout* gridLayoutD = new QGridLayout(this); QLabel* label1D = new QLabel(this); label1D->setText(tr("Distance from")); gridLayoutD->addWidget(label1D, 0, 0, 1, 1); QLabel* label2D = new QLabel(this); label2D->setText(tr("Distance to")); gridLayoutD->addWidget(label2D, 1, 0, 1, 1); fromEditD = new QLineEdit(this); gridLayoutD->addWidget(fromEditD, 0, 2, 1, 1); toEditD = new QLineEdit(this); gridLayoutD->addWidget(toEditD, 1, 2, 1, 1); unlimCheckBoxD = new QCheckBox(this); unlimCheckBoxD->setText(tr("Unlimited")); gridLayoutD->addWidget(unlimCheckBoxD, 1, 3, 1, 1); orderCheckBoxD = new QCheckBox(this); orderCheckBoxD->setText(tr("Take order into account")); gridLayoutD->addWidget(orderCheckBoxD, 2, 2, 1, 1); QSpacerItem* horizontalSpacerD = new QSpacerItem(40, 20, QSizePolicy::Expanding, QSizePolicy::Minimum); gridLayoutD->addItem(horizontalSpacerD, 0, 3, 1, 1); QIntValidator* validator = new QIntValidator(0, 65535, this); fromEditD->setValidator(validator); toEditD->setValidator(validator); connect(unlimCheckBoxD, SIGNAL(clicked()), SLOT(sl_unlim())); connect(orderCheckBoxD, SIGNAL(clicked()), SLOT(sl_order())); } void DistanceSet::loadData(void *pData){ OpDistance *pOp = reinterpret_cast(pData); Interval i = pOp->getDistance(); from = i.getFrom(); to = i.getTo(); isOrderImportant = pOp->isOrderImportant(); isMaxUNL = (to == PINF); if (isMaxUNL) to = from + 1; toEditD->setEnabled(!isMaxUNL); updateData(false); } void DistanceSet::saveData(void *pData){ OpDistance *pOp = reinterpret_cast(pData); updateData(); if (isMaxUNL) to = PINF; pOp->setDistance( Interval(from, to) ); pOp->setOrderImportant( isOrderImportant == true ); } bool DistanceSet::isReadyToClose(){ updateData(); if (isMaxUNL) to = PINF; if ( from > to ) { QMessageBox mb(QMessageBox::Critical, tr("Wrong parameters"), tr("Higher bound must be grater then lower bound")); mb.exec(); return false; } else return true; } void DistanceSet::updateData(bool side){ if(side){ to = toEditD->text().toInt(); from = fromEditD->text().toInt(); isOrderImportant = orderCheckBoxD->isChecked(); isMaxUNL = unlimCheckBoxD->isChecked(); }else{ toEditD->setText(QString("%1").arg(to)); fromEditD->setText(QString("%1").arg(from)); orderCheckBoxD->setChecked(isOrderImportant); unlimCheckBoxD->setChecked(isMaxUNL); } } void DistanceSet::sl_unlim(){ isMaxUNL = unlimCheckBoxD->isChecked(); toEditD->setEnabled( !isMaxUNL); } void DistanceSet::sl_order(){ isOrderImportant = orderCheckBoxD->isChecked(); } IntervalSet::IntervalSet (QWidget* parent) : OperationSet(parent) , from(0) , to(0) , isMaxUNL(true){ setEnabled(true); QGridLayout* gridLayoutI = new QGridLayout(this); QLabel* label1I = new QLabel(this); label1I->setText(tr("Interval from")); gridLayoutI->addWidget(label1I, 0, 0, 1, 1); QLabel* label2I = new QLabel(this); label2I->setText(tr("Interval to")); gridLayoutI->addWidget(label2I, 2, 0, 1, 1); fromIEdit = new QLineEdit(this); gridLayoutI->addWidget(fromIEdit, 0, 2, 1, 1); toIEdit = new QLineEdit(this); gridLayoutI->addWidget(toIEdit, 2, 2, 1, 1); QSpacerItem* horizontalSpacer_4 = new QSpacerItem(40, 20, QSizePolicy::Expanding, QSizePolicy::Minimum); gridLayoutI->addItem(horizontalSpacer_4, 2, 4, 1, 1); unlimCheckBoxI = new QCheckBox(this); unlimCheckBoxI->setText(tr("Unlimited")); gridLayoutI->addWidget(unlimCheckBoxI, 2, 3, 1, 1); QIntValidator* validator = new QIntValidator(0, 65535, this); fromIEdit->setValidator(validator); toIEdit->setValidator(validator); connect(unlimCheckBoxI, SIGNAL(clicked()), SLOT(sl_unlim())); } void IntervalSet::loadData(void *pData){ OpInterval *pOp = reinterpret_cast(pData); Interval i = pOp->getInt(); from = i.getFrom(); to = i.getTo(); isMaxUNL = (to == PINF); if (isMaxUNL) to = from+1; toIEdit->setEnabled( !isMaxUNL); updateData(false); } void IntervalSet::saveData(void *pData){ OpInterval *pOp = reinterpret_cast(pData); updateData(); if (isMaxUNL) to = PINF; pOp->setInt( Interval(from, to) ); } bool IntervalSet::isReadyToClose(){ updateData(); if (isMaxUNL) to = PINF; if ( from > to ) { QMessageBox mb(QMessageBox::Critical, tr("Wrong parameters"), tr("Higher bound must be grater then lower bound")); mb.exec(); return false; } else return true; } void IntervalSet::updateData(bool side){ if(side){ to = toIEdit->text().toInt(); from = fromIEdit->text().toInt(); isMaxUNL = unlimCheckBoxI->isChecked(); }else{ toIEdit->setText(QString("%1").arg(to)); fromIEdit->setText(QString("%1").arg(from)); unlimCheckBoxI->setChecked(isMaxUNL); } } void IntervalSet::sl_unlim(){ isMaxUNL = unlimCheckBoxI->isChecked(); toIEdit->setEnabled( !isMaxUNL); } RepetitionSet::RepetitionSet (QWidget* parent) : OperationSet(parent) , nmin(0) , nmax(0) , min(0) , max(0) , isMaxUNL(true){ setEnabled(true); QGridLayout* gridLayoutR = new QGridLayout(this); QLabel* label1R = new QLabel(this); label1R->setText(tr("Distance from")); gridLayoutR->addWidget(label1R, 0, 0, 1, 1); QLabel* label2R = new QLabel(this); label2R->setText(tr("Distance to")); gridLayoutR->addWidget(label2R, 1, 0, 1, 1); fromDEdit = new QLineEdit(this); gridLayoutR->addWidget(fromDEdit, 0, 2, 1, 1); toDEditR = new QLineEdit(this); gridLayoutR->addWidget(toDEditR, 1, 2, 1, 1); unlimCheckBoxR = new QCheckBox(this); unlimCheckBoxR->setText(tr("Unlimited")); gridLayoutR->addWidget(unlimCheckBoxR, 2, 2, 1, 1); QLabel* label3R = new QLabel(this); label3R->setText(tr("Count from")); gridLayoutR->addWidget(label3R, 0, 3, 1, 1); QLabel* label4R = new QLabel(this); label4R->setText(tr("Count to")); gridLayoutR->addWidget(label4R, 1, 3, 1, 1); fromCEditR = new QLineEdit(this); gridLayoutR->addWidget(fromCEditR, 0, 4, 1, 1); toCEditR = new QLineEdit(this); gridLayoutR->addWidget(toCEditR, 1, 4, 1, 1); QIntValidator* validator = new QIntValidator(0, 65535, this); fromDEdit->setValidator(validator); toDEditR->setValidator(validator); QIntValidator* validator1 = new QIntValidator(1, 65535, this); fromCEditR->setValidator(validator1); toCEditR->setValidator(validator1); connect(unlimCheckBoxR, SIGNAL(clicked()), SLOT(sl_unlim())); } void RepetitionSet::loadData(void *pData){ OpReiteration *pOp = reinterpret_cast(pData); Interval i = pOp->getCount(); nmin = i.getFrom(); nmax = i.getTo(); i = pOp->getDistance(); min = i.getFrom(); max = i.getTo(); isMaxUNL = (max == PINF); if (isMaxUNL) max = min + 1; toDEditR->setEnabled( !isMaxUNL); updateData(false); } void RepetitionSet::saveData(void *pData){ OpReiteration *pOp = reinterpret_cast(pData); updateData(); if (isMaxUNL) max = PINF; pOp->setCount( Interval(nmin, nmax) ); pOp->setDistance( Interval(min, max) ); } bool RepetitionSet::isReadyToClose(){ updateData(); if ( isMaxUNL ) max = PINF; if ( min > max ) { QMessageBox mb(QMessageBox::Critical, tr("Wrong parameters"), tr("Higher bound must be grater then lower bound")); mb.exec(); return false; } else if ( nmin > nmax ) { QMessageBox mb(QMessageBox::Critical, tr("Wrong parameters"), tr("Higher bound must be grater then lower bound")); mb.exec(); return false; } else return true; } void RepetitionSet::updateData(bool side){ if(side){ nmin = fromCEditR->text().toInt(); nmax = toCEditR->text().toInt(); min = fromDEdit->text().toInt(); max = toDEditR->text().toInt(); isMaxUNL = unlimCheckBoxR->isChecked(); }else{ fromDEdit->setText(QString("%1").arg(min)); toDEditR->setText(QString("%1").arg(max)); fromCEditR->setText(QString("%1").arg(nmin)); toCEditR->setText(QString("%1").arg(nmax)); unlimCheckBoxR->setChecked(isMaxUNL); } } void RepetitionSet::sl_unlim(){ isMaxUNL = unlimCheckBoxR->isChecked(); toDEditR->setEnabled( !isMaxUNL); } }//namespace ugene-1.9.8/src/plugins/expert_discovery/src/ExpertDiscoveryViewCtx.h0000644000175000017500000000103111651544323024570 0ustar ilyailya#pragma once #include "ExpertDiscoveryView.h" #include namespace U2{ class ExpertDiscoveryViewCtx: public GObjectViewWindowContext{ Q_OBJECT public: ExpertDiscoveryViewCtx(QObject* p); virtual bool canHandle(GObjectView* v, GObject* obj); void addView(ExpertDiscoveryView* v); protected: virtual void initViewContext(GObjectView* view); // protected slots: // virtual void sl_windowAdded(MWMDIWindow*); private: QList viewList; }; }//namespace ugene-1.9.8/src/plugins/expert_discovery/src/ExpertDiscoveryPersistent.cpp0000644000175000017500000002735311651544323025711 0ustar ilyailya#include "ExpertDiscoveryPersistent.h" namespace U2 { void EDPMSequence::save(QDataStream& ar, Sequence& rSequence) { ar << QString::fromStdString(rSequence.getName()); ar << QString::fromStdString(rSequence.getSequence()); ar << rSequence.isHasScore(); ar << rSequence.getScore(); } void EDPMSequence::load(QDataStream& ar, Sequence& rSequence){ QString strName; QString strSequence; bool bHasScore = false; double dScore = 0; ar >> strName; ar >> strSequence; ar >> bHasScore; ar >> dScore; rSequence.setName(strName.toStdString()); rSequence.setSequence(strSequence.toStdString()); rSequence.setHasScore(bHasScore); rSequence.setScore(dScore); } void EDPMSeqBase::save(QDataStream& ar, SequenceBase& rSeqBase) { int nSize = rSeqBase.getSize(); ar << nSize; for (int i=0; i> nSize; assert( nSize >= 0 ); Sequence seq; for (int i=0; i> nSize; for (int i=0; i> nFrom; int nTo = 0; ar >> nTo; rMrk.insert(DDisc::Interval(nFrom, nTo)); } } void EDPMMrkFamily::save(QDataStream& ar, Marking::FamilyMarking& rMrk) { ar << (int)(rMrk.size()); Marking::FamilyMarking::iterator i = rMrk.begin(); while (i!=rMrk.end()) { ar << QString::fromStdString(i->first); EDPMMrkSignal::save(ar, i->second); i++; } } void EDPMMrkFamily::load(QDataStream& ar, Marking::FamilyMarking& rMrk){ int nSize = 0; ar >> nSize; for (int i=0; i> strSignalName; EDPMMrkSignal::load(ar, SignalMrk); rMrk[strSignalName.toStdString()] = SignalMrk; } } void EDPMMrk::save(QDataStream& ar, Marking& rMrk) { Marking::MarkingData& rData = rMrk.marking; ar << (int)(rData.size()); Marking::MarkingData::iterator i = rData.begin(); while (i!=rData.end()) { ar << QString::fromStdString(i->first); EDPMMrkFamily::save(ar, i->second); i++; } } void EDPMMrk::load(QDataStream& ar, Marking& rMrk){ Marking::MarkingData& rData = rMrk.marking; int nSize = 0; ar >> nSize; for (int i=0; i> strFamilyName; EDPMMrkFamily::load(ar, FamilyMrk); rData[strFamilyName.toStdString()] = FamilyMrk; } } void EDPMMrkBase::save(QDataStream& ar, MarkingBase& rMrkBase, int nSeqCount) { ar << nSeqCount; for (int i=0; i> nSize; for (int i=0; i> nNo; QString strName; QString strMethodName; ar >> strName; ar >> strMethodName; rInfo.setNo(nNo); rInfo.setName(strName.toStdString()); rInfo.setMethodName(strMethodName.toStdString()); } void EDPMDescFamily::save(QDataStream& ar, Family& rFamily) { ar << QString::fromStdString(rFamily.getName()); int nSize = rFamily.getSignalNumber(); ar << nSize; for (int i=0; i> strName; rFamily.setName(strName.toStdString()); int nSize = 0; ar >> nSize; for (int i=0; i> nSize; for (int i=0; igetName()); ar << QString::fromStdString(pSignal->getDescription()); ar << bool(pSignal->isPriorParamsDefined()); if (pSignal->isPriorParamsDefined()) { ar << pSignal->getPriorProbability(); ar << pSignal->getPriorFisher(); ar << pSignal->getPriorPosCoverage(); ar << pSignal->getPriorNegCoverage(); } Operation *pOp = pSignal->getSignal(); EDPMOperation::save(ar, pOp); } void EDPMCS::load(QDataStream& ar, Signal* pSignal){ QString strName; QString strDescription; bool bPriorParamsDefined; double dPriorProb = 0; double dPriorFisher = 1; double dPriorPosCoverage = 0; double dPriorNegCoverage = 0; ar >> strName; ar >> strDescription; ar >> bPriorParamsDefined; if (bPriorParamsDefined) { ar >> dPriorProb; ar >> dPriorFisher; ar >> dPriorPosCoverage; ar >> dPriorNegCoverage; } pSignal->setName(strName.toStdString()); pSignal->setDescription(strDescription.toStdString()); Operation *pOp = 0; EDPMOperation::load(ar, pOp); pSignal->attach(pOp); pSignal->setPriorParamsDefined(bPriorParamsDefined != 0); if (pSignal->isPriorParamsDefined()) { pSignal->setPriorProbability(dPriorProb); pSignal->setPriorFisher(dPriorFisher); pSignal->setPriorPosCoverage(dPriorPosCoverage); pSignal->setPriorNegCoverage(dPriorNegCoverage); } } void EDPMCSFolder::save(QDataStream& ar, CSFolder* pFolder) { ar << pFolder->getName(); int nFolderNumber = pFolder->getFolderNumber(); ar << nFolderNumber; for (int i=0; igetSubfolder(i)); int nSignalNumber = pFolder->getSignalNumber(); ar << nSignalNumber; for (int i=0; igetSignal(i)); } void EDPMCSFolder::load(QDataStream& ar, CSFolder* pFolder){ QString strName; ar >> strName; pFolder->setName(strName); int nFolderNumber = 0; ar >> nFolderNumber; for (int i=0; iaddFolder(pSubfolder); } int nSignalNumber = 0; ar >> nSignalNumber; for (int i=0; iaddSignal(pSignal); } } void EDPMOperation::save(QDataStream& ar, Operation*& pOp) { EOpType eType; if (pOp) eType = pOp->getType(); else eType = OP_UNDEFINED; ar << (int)eType; switch (eType) { case OP_DISTANCE : saveDistance(ar, dynamic_cast(pOp)); break; case OP_REITERATION : saveReiteration(ar, dynamic_cast(pOp)); break; case OP_INTERVAL : saveInterval(ar, dynamic_cast(pOp)); break; case OP_TS : saveTS(ar, dynamic_cast(pOp)); break; case OP_UNDEFINED : return; default: assert(0); } for (int i=0; igetArgumentNumber(); i++) { Operation *pArg = pOp->getArgument(i); EDPMOperation::save(ar,pArg); pOp->setArgument(pArg,i); } } void EDPMOperation::saveDistance(QDataStream& ar, OpDistance* pOp) { ar << pOp->getDistance().getFrom(); ar << pOp->getDistance().getTo(); ar << pOp->getDistanceType(); ar << pOp->isOrderImportant(); } void EDPMOperation::saveReiteration(QDataStream& ar, OpReiteration* pOp) { ar << pOp->getDistance().getFrom(); ar << pOp->getDistance().getTo(); ar << pOp->getCount().getFrom(); ar << pOp->getCount().getTo(); ar << pOp->getDistanceType(); } void EDPMOperation::saveInterval(QDataStream& ar, OpInterval* pOp) { ar << pOp->getInt().getFrom(); ar << pOp->getInt().getTo(); } void EDPMOperation::saveTS(QDataStream& ar, TS* pOp) { ar << pOp->isFromMarking(); ar << QString::fromStdString(pOp->getWord()); ar << QString::fromStdString(pOp->getName()); ar << QString::fromStdString(pOp->getFamily()); } void EDPMOperation::load(QDataStream& ar, Operation*& pOp){ EOpType eType; int tmp; ar>>tmp; eType = (EOpType)tmp; switch (eType) { case OP_DISTANCE : pOp = new OpDistance(); break; case OP_REITERATION : pOp = new OpReiteration(); break; case OP_INTERVAL : pOp = new OpInterval(); break; case OP_TS : pOp = new TS(); break; case OP_UNDEFINED : pOp = NULL; break; } switch (eType) { case OP_DISTANCE : loadDistance(ar, dynamic_cast(pOp)); break; case OP_REITERATION : loadReiteration(ar, dynamic_cast(pOp)); break; case OP_INTERVAL : loadInterval(ar, dynamic_cast(pOp)); break; case OP_TS : loadTS(ar, dynamic_cast(pOp)); break; case OP_UNDEFINED : return; default: assert(0); } for (int i=0; igetArgumentNumber(); i++) { Operation *pArg = pOp->getArgument(i); EDPMOperation::load(ar,pArg); pOp->setArgument(pArg,i); } } void EDPMOperation::loadDistance(QDataStream& ar, OpDistance* pOp){ DDisc::Interval dist; int tmp = 0; ar >> tmp; dist.setFrom(tmp); ar >> tmp; dist.setTo(tmp); pOp->setDistance(dist); EDistType type; ar >> tmp; type = (EDistType)tmp; pOp->setDistanceType( type); bool bOrder; ar >> bOrder; pOp->setOrderImportant(bOrder); } void EDPMOperation::loadReiteration(QDataStream& ar, OpReiteration* pOp){ DDisc::Interval dist; DDisc::Interval count; int tmp = 0; ar >> tmp; dist.setFrom(tmp); ar >> tmp; dist.setTo(tmp); ar >> tmp; count.setFrom(tmp); ar >> tmp; count.setTo(tmp); pOp->setDistance(dist); EDistType type; ar >> tmp; type = (EDistType)tmp; pOp->setDistanceType( type ); pOp->setCount(count); } void EDPMOperation::loadInterval(QDataStream& ar, OpInterval* pOp){ DDisc::Interval interval; int tmp = 0; ar >> tmp; interval.setFrom(tmp); ar >> tmp; interval.setTo(tmp); pOp->setInt(interval); } void EDPMOperation::loadTS(QDataStream& ar, TS* pOp){ bool bFromMarking; ar >> bFromMarking; pOp->setFromMarking(bFromMarking); QString strWord; QString strName; QString strFamily; ar >> strWord; ar >> strName; ar >> strFamily; pOp->setWord(strWord.toStdString()); pOp->setName(strName.toStdString()); pOp->setFamily(strFamily.toStdString()); } } //namespace ugene-1.9.8/src/plugins/expert_discovery/src/ExpertDiscoveryPosNegDialog.h0000644000175000017500000000125111651544323025516 0ustar ilyailya#pragma once #include namespace U2 { class ExpertDiscoveryPosNegDialog : public QDialog, public Ui_ExpertDiscoveryPosNegDialog{ Q_OBJECT public: ExpertDiscoveryPosNegDialog(QWidget *parent); virtual void accept(); QString getFirstFileName() const {return firstFileName;} QString getSecondFileName() const {return secondFileName;} bool isGenerateNegative() const {return generateNeg;} protected slots: void sl_openFirstFile(); void sl_openSecondFile(); void sl_oneSequence(); private: QString firstFileName; QString secondFileName; bool generateNeg; QString filter; }; }//namespace ugene-1.9.8/src/plugins/expert_discovery/src/ExpertDiscoveryPropTable.cpp0000644000175000017500000001673511651544323025443 0ustar ilyailya#include "ExpertDiscoveryPropTable.h" #include #include namespace U2 { EDPropertiesTable::EDPropertiesTable(QWidget* parent) :QTableWidget(parent) ,curPItem(NULL) ,isSeq(false) ,seqOffset(0) { setColumnCount(2); verticalHeader()->hide(); horizontalHeader()->hide(); //connect(this, SIGNAL(cellChanged ( int , int )), SLOT(sl_cellDataChanged(int , int ))); connect(this, SIGNAL(itemChanged ( QTableWidgetItem* )), SLOT( sl_cellChanged(QTableWidgetItem*) )); setWordWrap(true); } void EDPropertiesTable::representPIProperties(EDProjectItem* pItem){ curPItem = pItem; cleanup(); if(pItem == NULL){ return; } int nGroupNum = pItem->getGroupNumber(); for (int nGroup=0; nGroupgetGroup(nGroup); addNewGroup(rGroup.getName()); int nPropNum = rGroup.getPropertiesNumber(); for(int nProp=0; nProphasPredefinedValues()){ pPropertyItem = new EDPropertyItem(rProp.getValue(), nGroup, nProp, pType->hasEdit()); } else{ const EDPIPropertyTypeList* pType = dynamic_cast(rProp.getType()); pPropertyItemList = new EDPropertyItemList(rProp.getValue(), nGroup, nProp, pType, pType->hasEdit()); connect (pPropertyItemList, SIGNAL(currentIndexChanged ( const QString& )), this, SLOT(sl_comboEditTextChangerd(const QString& ))); } int itemToSetPos = isSeq? rowCount() - 1 : seqOffset - 1; if(!pType->hasPredefinedValues()){ setItem(itemToSetPos, 1, pPropertyItem); }else{ setCellWidget(itemToSetPos, 1, pPropertyItemList); } } } resizeColumnsToContents(); } void EDPropertiesTable::updateCurrentProperties(){ representPIProperties(curPItem); } void EDPropertiesTable::addNewGroup(const QString& name){ int rowPos = isSeq ? rowCount() : seqOffset; insertRow(rowPos); setSpan(rowPos, 0, 1, 2); QTableWidgetItem* item = new QTableWidgetItem(); item->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEditable); item->setText(name); item->setBackgroundColor(Qt::lightGray); item->setTextColor(Qt::black); QFont font = item->font(); font.setBold(true); item->setFont(font); setItem(rowPos, 0, item); if(!isSeq){ seqOffset++; } } void EDPropertiesTable::addNewField(const QString& name){ int rowPos = isSeq ? rowCount() : seqOffset; insertRow(rowPos); QTableWidgetItem* item = new QTableWidgetItem(); item->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEditable); item->setText(name); item->setTextColor(Qt::black); setItem(rowPos, 0, item); if(!isSeq){ seqOffset++; } } EDPropertyItem::EDPropertyItem(const QString& val, int nGroup, int nProp, bool editable) :QTableWidgetItem() { this->nGroup = nGroup; this->nProp = nProp; if(!editable){ setFlags(Qt::ItemIsEditable); } setData(val); setText(val); } // EDPropertyItem::EDPropertyItem(const QString& val, int nGroup, int nProp, const EDPIPropertyTypeList* pType, bool editable) // :QTableWidgetItem() // { // this->nGroup = nGroup; // this->nProp = nProp; // if(!editable){ // setFlags(Qt::ItemIsSelectable |Qt::ItemIsEditable); // } // setData(val); // setText(val); // } // EDPropertyItem::EDPropertyItem(const QString& val, int nGroup, int nProp, bool editable) // :QTableWidgetItem() // { // this->nGroup = nGroup; // this->nProp = nProp; // if(!editable){ // setFlags(Qt::ItemIsEditable); // } // setData(val); // setText(val); // } EDPropertyItemList::EDPropertyItemList(const QString& val, int nGroup, int nProp, const EDPIPropertyTypeList* pType, bool editable) :QComboBox() { this->nGroup = nGroup; this->nProp = nProp; if(!editable){ //setFlags(Qt::ItemIsSelectable |Qt::ItemIsEditable); } for (int i = 0; i < pType->getValueNumber(); i ++){ insertItem(i, pType->getValue(i)); } setData(val); int curInd = pType->getValueId(val); if(curInd == -1){ insertItem(0, val); setCurrentIndex(0); }else{ setCurrentIndex(curInd); } setEditable(editable); //setFrame(false); //setInsertPolicy(NoInsert); } void EDPropertiesTable::sl_treeSelChanged(QTreeWidgetItem * tItem){ EDProjectItem* pItem = dynamic_cast(tItem); // if(pItem && (pItem->getType() == PIT_SEQUENCE || pItem->getType() ==PIT_CONTROLSEQUENCE)){ // isSeq = true; // }else{ // isSeq = false; // } representPIProperties(pItem); } void EDPropertiesTable::cleanup(){ if(isSeq){ int rowC = rowCount(); for(int i = seqOffset; i < rowC; i++){ removeRow(seqOffset); } seqOffset = rowCount(); }else{ for(int i = 0; i < seqOffset; i++){ removeRow(0); } seqOffset = 0; } } void EDPropertiesTable::clearAll(){ isSeq = false; seqOffset = 0; curPItem = NULL; clear(); setRowCount(0); } void EDPropertiesTable::sl_cellChanged(QTableWidgetItem* tItem){ /*QTableWidgetItem* tItem = item(row, column); if(!tItem){ return; }*/ EDPropertyItem* edPropItem = dynamic_cast(tItem); if(!edPropItem){ return; } int nGroup = edPropItem->getGroup(); int nProp = edPropItem->getProp(); const EDPIPropertyGroup& rGroup = curPItem->getGroup(nGroup); const EDPIProperty& rProp = rGroup.getProperty(nProp); QString strNewValue = edPropItem->text(); if(strNewValue!=edPropItem->getData()){ edPropItem->setData(strNewValue); emit si_propChanged(curPItem, &rProp, strNewValue); } } void EDPropertiesTable::sl_cellDataChanged(int row, int column){ QWidget* w = cellWidget(row, column); if(w == NULL){ return; } EDPropertyItemList* edPropItem = dynamic_cast(w); if(!edPropItem){ return; } int nGroup = edPropItem->getGroup(); int nProp = edPropItem->getProp(); const EDPIPropertyGroup& rGroup = curPItem->getGroup(nGroup); const EDPIProperty& rProp = rGroup.getProperty(nProp); QString strNewValue = edPropItem->currentText(); if(strNewValue!=edPropItem->getData()){ edPropItem->setData(strNewValue); emit si_propChanged(curPItem, &rProp, strNewValue); } } void EDPropertiesTable::sl_comboEditTextChangerd(const QString& t){ EDPropertyItemList* edPropItem = dynamic_cast(sender()); if(!edPropItem){ return; } int nGroup = edPropItem->getGroup(); int nProp = edPropItem->getProp(); const EDPIPropertyGroup& rGroup = curPItem->getGroup(nGroup); const EDPIProperty& rProp = rGroup.getProperty(nProp); QString strNewValue = edPropItem->currentText(); if(strNewValue!=edPropItem->getData()){ edPropItem->setData(strNewValue); emit si_propChanged(curPItem, &rProp, strNewValue); } } }//namespace ugene-1.9.8/src/plugins/expert_discovery/src/ExpertDiscoveryPosNegMrkDialog.cpp0000644000175000017500000000634011651544323026527 0ustar ilyailya#include "ExpertDiscoveryPosNegMrkDialog.h" #include #include #include #include namespace U2 { ExpertDiscoveryPosNegMrkDialog::ExpertDiscoveryPosNegMrkDialog(QWidget *parent) : QDialog(parent), generateDescr(true){ setupUi(this); connect(openFirstButton, SIGNAL(clicked()), SLOT(sl_openFirstFile())); connect(openSecondButton, SIGNAL(clicked()), SLOT(sl_openSecondFile())); connect(openThirdButton, SIGNAL(clicked()), SLOT(sl_openThirdFile())); connect(oneSequenceCheckBox, SIGNAL(clicked()), SLOT(sl_oneSequence())); oneSequenceCheckBox->click(); filter = DialogUtils::prepareFileFilter("Markup files", QStringList() << "xml" << "gb"); } void ExpertDiscoveryPosNegMrkDialog::accept(){ Q_ASSERT(firstFileEdit); Q_ASSERT(secondFileEdit); Q_ASSERT(thirdFileEdit); firstFileName = firstFileEdit->text(); secondFileName = secondFileEdit->text(); thirdFileName = thirdFileEdit->text(); if (!firstFileName.isEmpty() && !secondFileName.isEmpty()) { if(secondFileName == firstFileName){ QMessageBox mb(QMessageBox::Critical, tr("Select files"), tr("Positive and negative sequences markups can't be in the one file. Select another file for one of them")); mb.exec(); }else if(!generateDescr && thirdFileName.isEmpty()){ QMessageBox mb(QMessageBox::Critical, tr("Select files"), tr("Select description file")); mb.exec(); }else{ QDialog::accept(); } }else { QMessageBox mb(QMessageBox::Critical, tr("Select files"), tr("Select files for ExpertDiscovery")); mb.exec(); } } void ExpertDiscoveryPosNegMrkDialog::sl_oneSequence() { thirdFileEdit->setDisabled(oneSequenceCheckBox->isChecked()); openThirdButton->setDisabled(oneSequenceCheckBox->isChecked()); generateDescr = oneSequenceCheckBox->isChecked(); } void ExpertDiscoveryPosNegMrkDialog::sl_openFirstFile(){ LastOpenDirHelper lod("ExpertDiscovery positive sequences markup file"); lod.url = QFileDialog::getOpenFileName(NULL, tr("Open positive sequences markup file"), lod.dir, filter); Q_ASSERT(firstFileEdit); if (!lod.url.isEmpty()) { firstFileEdit->setText(lod.url); } } void ExpertDiscoveryPosNegMrkDialog::sl_openSecondFile() { LastOpenDirHelper lod("ExpertDiscovery negative sequences markup file"); if (lod.dir.isEmpty()) { LastOpenDirHelper lodFirst("Open negative sequences file"); lod.dir = lodFirst.dir; } lod.url = QFileDialog::getOpenFileName(NULL, tr("Open second file"), lod.dir, filter); Q_ASSERT(secondFileEdit); if (!lod.url.isEmpty()) { secondFileEdit->setText(lod.url); } } void ExpertDiscoveryPosNegMrkDialog::sl_openThirdFile() { LastOpenDirHelper lod("ExpertDiscovery description file"); if (lod.dir.isEmpty()) { LastOpenDirHelper lodFirst("ExpertDiscovery description file"); lod.dir = lodFirst.dir; } lod.url = QFileDialog::getOpenFileName(NULL, tr("Open description file"), lod.dir, filter); Q_ASSERT(thirdFileEdit); if (!lod.url.isEmpty()) { thirdFileEdit->setText(lod.url); } } }//namespace ugene-1.9.8/src/plugins/expert_discovery/src/ExpertDiscoveryControlMrkDialog.cpp0000644000175000017500000000222611651544323026753 0ustar ilyailya#include "ExpertDiscoveryControlMrkDialog.h" #include #include #include #include namespace U2 { ExpertDiscoveryControlMrkDialog::ExpertDiscoveryControlMrkDialog(QWidget *parent) : QDialog(parent){ setupUi(this); connect(openFirstButton, SIGNAL(clicked()), SLOT(sl_openFirstFile())); filter = DialogUtils::prepareFileFilter("Markup files", QStringList() << "xml"); } void ExpertDiscoveryControlMrkDialog::accept(){ Q_ASSERT(firstFileEdit); firstFileName = firstFileEdit->text(); if (!firstFileName.isEmpty()) { QDialog::accept(); }else { QMessageBox mb(QMessageBox::Critical, tr("Select files"), tr("Select files for ExpertDiscovery")); mb.exec(); } } void ExpertDiscoveryControlMrkDialog::sl_openFirstFile(){ LastOpenDirHelper lod("ExpertDiscovery control sequences markup file"); lod.url = QFileDialog::getOpenFileName(NULL, tr("Open control sequences markup file"), lod.dir, filter); Q_ASSERT(firstFileEdit); if (!lod.url.isEmpty()) { firstFileEdit->setText(lod.url); } } }//namespace ugene-1.9.8/src/plugins/expert_discovery/src/ExpertDiscoveryAdvSetDialog.cpp0000644000175000017500000001060111651544323026043 0ustar ilyailya#include "ExpertDiscoveryAdvSetDialog.h" #include #include #include namespace U2 { ExpertDiscoveryAdvSetDialog::ExpertDiscoveryAdvSetDialog(QWidget *parent, double& dIntProbability1, double& dIntFisher1, int& nMinComplexity1, int& nMaxComplexity1, double& dMinPosCorrelation1, double& dMaxPosCorrelation1, double& dMinNegCorrelation1, double& dMaxNegCorrelation1, bool& bCorrelationImportant1) : QDialog(parent), dIntProbability(dIntProbability1), dIntFisher(dIntFisher1), nMinComplexity(nMinComplexity1), nMaxComplexity(nMaxComplexity1), dMinPosCorrelation(dMinPosCorrelation1), dMaxPosCorrelation(dMaxPosCorrelation1), dMinNegCorrelation(dMinNegCorrelation1), dMaxNegCorrelation(dMaxNegCorrelation1), bCorrelationImportant(bCorrelationImportant1){ setupUi(this); groupBox_2->setDisabled(true); condProbEdit->setText(QString("%1").arg(dIntProbability)); fishCritEdit->setText(QString("%1").arg(dIntFisher)); minComplexEdit->setText(QString("%1").arg(nMinComplexity)); maxComplEdit->setText(QString("%1").arg(nMaxComplexity)); minCorPosEdit->setText(QString("%1").arg(dMinPosCorrelation)); maxCorPosEdit->setText(QString("%1").arg(dMaxPosCorrelation)); minCorNegEdit->setText(QString("%1").arg(dMinNegCorrelation)); maxCorNegEdit->setText(QString("%1").arg(bCorrelationImportant)); QDoubleValidator* dIntProbabilityValid = new QDoubleValidator(0,100,5,this); QDoubleValidator* dIntFisherValid = new QDoubleValidator(0,1,5,this); QIntValidator* nComplexityValid = new QIntValidator(0,1000,this); QDoubleValidator* dCorrelationValid = new QDoubleValidator(-1,1,5,this); condProbEdit->setValidator(dIntProbabilityValid); fishCritEdit->setValidator(dIntFisherValid); minComplexEdit->setValidator(nComplexityValid); maxComplEdit->setValidator(nComplexityValid); minCorPosEdit->setValidator(dCorrelationValid); maxCorPosEdit->setValidator(dCorrelationValid); minCorNegEdit->setValidator(dCorrelationValid); maxCorNegEdit->setValidator(dCorrelationValid); connect( checkCorrel, SIGNAL(clicked()), SLOT(sl_checkCorrel()) ); hideParameters(); } void ExpertDiscoveryAdvSetDialog::accept(){ int minCom = 0; int maxCom = 0; minCom = minComplexEdit->text().toInt(); maxCom = maxComplEdit->text().toInt(); if(minCom>maxCom || minCom<0){ QMessageBox mb(QMessageBox::Critical, tr("Wrong parameters"), tr("Minimal complexity must not be grater then maximal complexity and positive")); mb.exec(); }else{ if(check(condProbEdit) && check(fishCritEdit) && check(minCorPosEdit) && check(maxCorPosEdit) && check(minCorNegEdit) && check(maxCorNegEdit) ){ dIntProbability = condProbEdit->text().toDouble(); dIntFisher = fishCritEdit->text().toDouble(); nMinComplexity = minCom; nMaxComplexity = maxCom; bCorrelationImportant = checkCorrel->isChecked(); if(bCorrelationImportant){ dMinPosCorrelation = minCorPosEdit->text().toDouble(); dMaxPosCorrelation = maxCorPosEdit->text().toDouble(); dMinNegCorrelation = minCorNegEdit->text().toDouble(); dMaxNegCorrelation = maxCorNegEdit->text().toDouble(); } QDialog::accept(); } } } void ExpertDiscoveryAdvSetDialog::sl_checkCorrel(){ groupBox_2->setEnabled(checkCorrel->isChecked()); } bool ExpertDiscoveryAdvSetDialog::check(const QLineEdit* lineE){ if(!lineE->validator()){ return false; } const QDoubleValidator* validator = qobject_cast(lineE->validator()); int pos = 0; QString textValue=lineE->text(); if(validator->validate(textValue,pos)!=QValidator::Acceptable){ QString msg = QString("Entered value must be from %1 to %2").arg(validator->bottom()).arg(validator->top()); QMessageBox mb(QMessageBox::Critical, tr("Wrong parameters"), tr(msg.toStdString().c_str())); mb.exec(); return false; } return true; } void ExpertDiscoveryAdvSetDialog::hideParameters(){ groupBox_2->hide(); fishCritEdit->hide(); label->hide(); label_2->hide(); condProbEdit->hide(); checkCorrel->hide(); } }//namespace ugene-1.9.8/src/plugins/expert_discovery/src/ExpertDiscoveryViewCtx.cpp0000644000175000017500000000260011651544323025126 0ustar ilyailya#include "ExpertDiscoveryViewCtx.h" #include #include #include #include #include namespace U2{ ExpertDiscoveryViewCtx::ExpertDiscoveryViewCtx(QObject* p):GObjectViewWindowContext(p, AnnotatedDNAViewFactory::ID){ } void ExpertDiscoveryViewCtx::initViewContext(GObjectView* view){ AnnotatedDNAView* av = qobject_cast(view); if(av){ foreach(ExpertDiscoveryView* v, viewList){ // v->insertSeqView(av); } } // ADVGlobalAction* a = new ADVGlobalAction(av, // QIcon(":query_designer/images/query_designer.png"), // tr("Analyze with query schema..."), 50, ADVGlobalActionFlag_AddToAnalyseMenu); //connect(a, SIGNAL(triggered()), SLOT(sl_showDialog())); } bool ExpertDiscoveryViewCtx::canHandle(GObjectView* v, GObject* obj){ if(v->getFactoryId() == "ED"){ return true; } else{ return false; } } void ExpertDiscoveryViewCtx::addView(ExpertDiscoveryView* v){ viewList.append(v); } // void ExpertDiscoveryViewCtx::sl_windowAdded(MWMDIWindow* wind){ // // int a = 1; // if(wind->getWindowName()!="Expert Discovery"){ // foreach(ExpertDiscoveryView* v, viewList){ // //v->insertSeqView(wind); // } // } // } }//namespace ugene-1.9.8/src/plugins/expert_discovery/src/ExpertDiscoverySet.h0000644000175000017500000001617311651544323023747 0ustar ilyailya//**************************************************************************** // File name: Set.h // Title: DiscoveryLib // Version: 1.0 // Author: // Creation Date: 26.02.2005 . // // Description: // //**************************************************************************** #pragma once #include #include #include #include #include using std::istream; using std::ostream; //typedef __int64 SET_TYPE; namespace U2{ typedef int SET_TYPE; // Representing bitset with fast size determination class Set { public: // Construction and destruction methods Set(); ~Set(); Set(const Set&); // Every set must be initialized through this functions void init(unsigned obj_num); bool is_init() const; size_t max_elem() const; // Maximum index of the element in the set size_t size() const; // Current number of 1 elements void set(unsigned obj); // Set the element with index obj to 1 void unset(unsigned obj); // Set the element with index obj to 0 void clear(); // Clear all elements to 0 bool is_set(unsigned obj) const; // Test whether element obj is set to 1 const Set& operator =(const Set&); // copies the set const Set& operator *=(const Set&); // bitwise "and" operator const Set& operator +=(const Set&); // bitwise "or" operator const Set& operator -=(const Set&); // exclude elements from set that is set to 1 in param set Set operator *(const Set&) const; // bitwise "and" operator Set operator +(const Set&) const; // bitwise "or" operator Set operator -(const Set&) const; // exclude elements from set that is set to 1 in param set void associate(int pos, std::string str); std::string association(int pos) const; private: static char number_of_1[65536]; // contain number of bits set to 1 in index value bool bIsInit; // this flag is set to true when set initialized unsigned obj_num; // number of objects in set size_t data_size; // size of data array size_t short_size; // size of data array in short elements SET_TYPE *data; // array that contains set data std::map m_associations; // Friend IO functions friend istream& operator >>(istream& in, Set& set); friend ostream& operator <<(ostream& out, const Set& set); //friend CArchive& operator >>(CArchive& ar, Set& set); //friend CArchive& operator <<(CArchive& ar, const Set& set); }; /////////////////////////////////////////////////////////////////////// // Inline realization of IO operations /////////////////////////////////////////////////////////////////////// inline istream& operator >>(istream& in, Set& set) { int obj_num; in.read((char *)&obj_num, sizeof(int)); set.init(obj_num); in.read((char *)set.data, sizeof(SET_TYPE)*int(set.data_size)); return in; } inline ostream& operator <<(ostream& out, const Set& set) { out.write((char*)&set.obj_num, sizeof(int)); out.write((char*)set.data, sizeof(SET_TYPE)*int(set.data_size)); return out; } /*inline CArchive& operator <<(CArchive& ar, const Set& set) { ar.Write((const void *)&set.obj_num, sizeof(int)); ar.Write((const void *)set.data, sizeof(SET_TYPE)*int(set.data_size)); return ar; } inline CArchive& operator >>(CArchive& ar, Set& set) { int obj_num; ar.Read((void *)&obj_num, sizeof(int)); set.init(obj_num); ar.Read((void *)set.data, sizeof(SET_TYPE)*int(set.data_size)); return ar; }*/ /////////////////////////////////////////////////////////////////////// // Inline realization of Set class /////////////////////////////////////////////////////////////////////// inline Set::Set() { bIsInit = false; data_size = 0; short_size = 0; data = NULL; } inline Set::Set(const Set& set) { bIsInit = false; data_size = 0; short_size = 0; data = NULL; *this = set; } inline Set::~Set() { delete [] data; } inline void Set::init(unsigned obj_num) { this->obj_num = obj_num; data_size = obj_num/(8*sizeof(SET_TYPE)) + (obj_num%(8*sizeof(SET_TYPE))!=0); short_size = data_size*sizeof(SET_TYPE)/sizeof(short); data = new SET_TYPE[data_size]; clear(); if (number_of_1[1] == 0) { for (int i=0; i<65536; i++) { number_of_1[i] = 0; for (int j=1; j<65536; j<<=1) { if (i & j) number_of_1[i]++; } } } bIsInit = true; } inline bool Set::is_init() const { return bIsInit; } inline size_t Set::max_elem() const { return data_size*8*sizeof(SET_TYPE); } inline size_t Set::size() const { size_t result = 0; unsigned short * const short_data = reinterpret_cast (data); for (size_t i=0; i::const_iterator it = m_associations.find(pos); if (it != m_associations.end()) return it->second; else return std::string(); } } ugene-1.9.8/src/plugins/expert_discovery/src/ExpertDiscoveryPersistent.h0000644000175000017500000000764311651544323025356 0ustar ilyailya#ifndef _U2_EXPERT_DIS_PERSISTENT_H_ #define _U2_EXPERT_DIS_PERSISTENT_H_ #include "DDisc/Sequence.h" #include "DDisc/MetaInfo.h" #include "DDisc/Signal.h" #include "ExpertDiscoveryCSUtil.h" #include namespace U2 { using namespace DDisc; class EDPMSequence { public: static void save(QDataStream& ds, Sequence& rSequence); static void load(QDataStream& ds, Sequence& rSequence); private: EDPMSequence(void); ~EDPMSequence(void); const EDPMSequence& operator =(const EDPMSequence&); }; class EDPMSeqBase { public: static void save(QDataStream& ar, SequenceBase& rSeqBase); static void load(QDataStream& ar, SequenceBase& rSeqBase); private: EDPMSeqBase(void); ~EDPMSeqBase(void); const EDPMSeqBase& operator =(const EDPMSeqBase&); }; class EDPMMrkSignal { public: static void save(QDataStream& ar, Marking::IntervalSet& rMrk); static void load(QDataStream& ar, Marking::IntervalSet& rMrk); private: EDPMMrkSignal(void); ~EDPMMrkSignal(void); const EDPMMrkSignal& operator =(const EDPMMrkSignal&); }; class EDPMMrkFamily { public: static void save(QDataStream& ar, Marking::FamilyMarking& rMrk); static void load(QDataStream& ar, Marking::FamilyMarking& rMrk); private: EDPMMrkFamily(void); ~EDPMMrkFamily(void); const EDPMMrkFamily& operator =(const EDPMMrkFamily&); }; class EDPMMrk { public: static void save(QDataStream& ar, Marking& rMrk); static void load(QDataStream& ar, Marking& rMrk); private: EDPMMrk(void); ~EDPMMrk(void); const EDPMMrk& operator =(const EDPMMrk&); }; class EDPMMrkBase { public: static void save(QDataStream& ar, MarkingBase& rMrkBase, int nSeqCount); static void load(QDataStream& ar, MarkingBase& rMrkBase, int nSeqCount); private: EDPMMrkBase(void); ~EDPMMrkBase(void); const EDPMMrkBase& operator =(const EDPMMrkBase&); }; class EDPMDescInfo { public: static void save(QDataStream& ar, MetaInfo& rInfo); static void load(QDataStream& ar, MetaInfo& rInfo); private: EDPMDescInfo(void); ~EDPMDescInfo(void); const EDPMDescInfo& operator =(const EDPMDescInfo&); }; class EDPMDescFamily { public: static void save(QDataStream& ar, Family& rFamily); static void load(QDataStream& ar, Family& rFamily); private: EDPMDescFamily(void); ~EDPMDescFamily(void); const EDPMDescFamily& operator =(const EDPMDescFamily&); }; class EDPMDescription { public: static void save(QDataStream& ar, MetaInfoBase& rDesc); static void load(QDataStream& ar, MetaInfoBase& rDesc); private: EDPMDescription(void); ~EDPMDescription(void); const EDPMDescription& operator =(const EDPMDescription&); }; class EDPMCS { public: static void save(QDataStream& ar, Signal* pSignal); static void load(QDataStream& ar, Signal* pSignal); private: EDPMCS(void); ~EDPMCS(void); const EDPMCS& operator =(const EDPMCS&); }; class EDPMCSFolder { public: static void save(QDataStream& ar, CSFolder* pFolder); static void load(QDataStream& ar, CSFolder* pFolder); private: EDPMCSFolder(void); ~EDPMCSFolder(void); const EDPMCSFolder& operator =(const EDPMCSFolder&); }; class EDPMOperation { public: static void save(QDataStream& ar, Operation*& pOp); static void saveDistance(QDataStream& ar, OpDistance* pOp); static void saveReiteration(QDataStream& ar, OpReiteration* pOp); static void saveInterval(QDataStream& ar, OpInterval* pOp); static void saveTS(QDataStream& ar, TS* pOp); static void load(QDataStream& ar, Operation*& pOp); static void loadDistance(QDataStream& ar, OpDistance* pOp); static void loadReiteration(QDataStream& ar, OpReiteration* pOp); static void loadInterval(QDataStream& ar, OpInterval* pOp); static void loadTS(QDataStream& ar, TS* pOp); private: EDPMOperation(void); ~EDPMOperation(void); const EDPMOperation& operator =(const EDPMOperation&); }; } //namespace #endif ugene-1.9.8/src/plugins/expert_discovery/src/ExpertDiscoverySetupRecBoundDialog.h0000644000175000017500000000135511651544323027052 0ustar ilyailya#pragma once #include #include namespace U2 { class ExpertDiscoverySetupRecBoundDialog : public QDialog, public Ui_EDSetupRecBoundDlg{ Q_OBJECT public: ExpertDiscoverySetupRecBoundDialog(double dRecognizationBound, const std::vector& vPosScore, const std::vector& vNegScore); virtual void accept(); double getRecognizationBound() const { return recognizationBound; } private: double recognizationBound; double probNegRec; double probPosRej; const std::vector& posScore; const std::vector& negScore; void updateProbs(); protected slots: void sl_recBoundChaged(double val); }; }//namespace ugene-1.9.8/src/plugins/expert_discovery/src/ExpertDiscoveryData.cpp0000644000175000017500000006522311651544323024420 0ustar ilyailya#include "ExpertDiscoveryData.h" #include "ExpertDiscoverySetupRecBoundDialog.h" #include #include #include #include #include #include #include #include #include #include #include namespace U2 { const std::string ExpertDiscoveryData::FAMILY_LETTERS = "_LETTERS_"; const std::string ExpertDiscoveryData::FAMILY_LETTERS_METHOD = "EXPERT_DISCOVERY_LETTERS_MARKUP_METHOD"; ExpertDiscoveryData::ExpertDiscoveryData (){ recognizationBound = 0; modified = false; } void ExpertDiscoveryData::setPosBase(const QList & objects){ foreach(GObject* obj, objects){ if(obj->getGObjectType() == GObjectTypes::SEQUENCE){ Sequence seq = prerareSequence(obj); seq.setHasScore(false); posBase.addSequence(seq); QString name=QString::fromStdString(seq.getName()); recDataStorage.addSequence(name); } } } void ExpertDiscoveryData::setNegBase(const QList & objects){ foreach(GObject* obj, objects){ if(obj->getGObjectType() == GObjectTypes::SEQUENCE){ Sequence seq = prerareSequence(obj); seq.setHasScore(false); negBase.addSequence(seq); QString name=QString::fromStdString(seq.getName()); recDataStorage.addSequence(name); } } } void ExpertDiscoveryData::setConBase(const QList & objects){ foreach(GObject* obj, objects){ if(obj->getGObjectType() == GObjectTypes::SEQUENCE){ Sequence seq = prerareSequence(obj); seq.setHasScore(false); conBase.addSequence(seq); QString name=QString::fromStdString(seq.getName()); recDataStorage.addSequence(name); } } } Sequence ExpertDiscoveryData::prerareSequence(const GObject* obj) const{ const QString& name = obj->getGObjectName(); std::string n = name.toStdString(); DNASequenceObject* seq = (DNASequenceObject*)obj; const QByteArray& seqArr = seq->getSequence(); std::string seqStr = std::string(seqArr.data(),seqArr.length()); Sequence seqReady = Sequence(n, seqStr); return seqReady; } void ExpertDiscoveryData::clearContrBase(){ conBase.clear(); } void ExpertDiscoveryData::clearContrAnnot(){ conAnn.clear(); } void ExpertDiscoveryData::markupLetters(void){ clearScores(); // If already exist return if (isLettersMarkedUp()) return; // Adding new signal family for letters std::string strFamilyName = ExpertDiscoveryData::FAMILY_LETTERS; std::string strMethodName = ExpertDiscoveryData::FAMILY_LETTERS_METHOD; const char letter[] = {'A','C','T','G','\0'}; Family letters; letters.setName(strFamilyName); for (int i=0; letter[i] != 0; i++) { MetaInfo mi; mi.setName(char2string(letter[i])); mi.setNo(i); mi.setMethodName(strMethodName); letters.AddInfo(mi); } desc.addFamily(letters); markupLetters(posBase, posAnn); markupLetters(negBase, negAnn); if (conBase.getSize() != 0) markupLetters(conBase, conAnn); setModifed(); } void ExpertDiscoveryData::markupLetters(SequenceBase& rBase, MarkingBase& rAnn){ std::string strFamilyName = ExpertDiscoveryData::FAMILY_LETTERS; const char letter[] = {'A','C','T','G','\0'}; int size = rBase.getSize(); std::string seq; for (int i=0; i vPosScore = posBase.getScores(); vector vNegScore = negBase.getScores(); ExpertDiscoverySetupRecBoundDialog dlg(recognizationBound, vPosScore, vNegScore); if(dlg.exec()){ recognizationBound = dlg.getRecognizationBound(); conBase.clearScores(); } setModifed(); } bool ExpertDiscoveryData::updateScores(){ QProgressDialog pd(tr("Setting up recognization bound. Please wait"), tr("Cancel"), 0, 100); pd.setWindowModality(Qt::WindowModal); pd.show(); pd.setLabelText(tr("Updating positive sequences")); pd.setValue(0); int sizeTotal = posBase.getSize() + negBase.getSize() + conBase.getSize(); for (int i=0; i(pItem); if (!pPICS) return; Signal* pSignal = const_cast(pPICS->getSignal()); if (!pSignal->check()) return; if (selectedSignals.IsSelected(pSignal)) selectedSignals.RemoveSignal(pSignal); else { if (!pSignal->isPriorParamsDefined()) { onSetCurrentSignalParamsAsPrior(pPICS, upd); } selectedSignals.AddSignal(pSignal); } clearScores(); setModifed(); } bool ExpertDiscoveryData::isSignalSelected(const EDProjectItem* pItem){ const EDPICS* signal = dynamic_cast(pItem); if(!signal){ return false; } return selectedSignals.IsSelected(signal->getSignal()); } void ExpertDiscoveryData::onSetCurrentSignalParamsAsPrior(EDPICS *pItem, bool bUpdate){ Signal* pSignal = const_cast(pItem->getSignal()); const EDProcessedSignal* pPS = pItem->getProcessedSignal(*this); if (pPS && pSignal) { pSignal->setPriorParamsDefined(true); pSignal->setPriorProbability(pPS->getProbability()); pSignal->setPriorFisher(pPS->getFisher()); pSignal->setPriorPosCoverage(pPS->getPosCoverage()); pSignal->setPriorNegCoverage(pPS->getNegCoverage()); pItem->update(false); if (bUpdate) { //UpdateAllViews(NULL, CURRENT_ITEM_CHANGED, pItem); clearScores(); } setModifed(); } } void ExpertDiscoveryData::onClearSignalPriorParams(EDPICS *pItem){ Signal* pSignal = const_cast(pItem->getSignal()); if (pSignal) { pSignal->setPriorParamsDefined(false); pSignal->setPriorProbability(0); pSignal->setPriorFisher(1); pSignal->setPriorPosCoverage(0); pSignal->setPriorNegCoverage(0); pItem->update(false); //UpdateAllViews(NULL, CURRENT_ITEM_CHANGED, pItem); clearScores(); setModifed(); } } SequenceType ExpertDiscoveryData::getSequenceTypeByName(const QString& seqName){ if(posBase.getObjNo(seqName.toStdString().c_str()) != -1){ return POSITIVE_SEQUENCE; }else if(negBase.getObjNo(seqName.toStdString().c_str()) != -1){ return NEGATIVE_SEQUENCE; }else if(conBase.getObjNo(seqName.toStdString().c_str()) != -1){ return CONTROL_SEQUENCE; }else{ return UNKNOWN_SEQUENCE; } } bool ExpertDiscoveryData::loadMarkup(const QString& firstF, const QString& secondF, const QString& thirdF, bool generateDescr){ clearScores(); posAnn.clear(); negAnn.clear(); desc.clear(); QString strPosName = firstF; try { if (strPosName.right(4).compare(".xml", Qt::CaseInsensitive) == 0) { if (!loadAnnotation(posAnn, posBase, strPosName)) throw std::exception(); } else { ifstream fPosAnn(strPosName.toStdString().c_str()); posAnn.load(fPosAnn); } } catch (exception& ex) { posAnn.clear(); QString str = "Positive annotation: "; str += ex.what(); QMessageBox mb(QMessageBox::Critical, tr("Error"), str); mb.exec(); return false; } QString strNegName = secondF; try { if (strPosName.right(4).compare(".xml", Qt::CaseInsensitive) == 0) { if (!loadAnnotation(negAnn, negBase, strNegName)) throw std::exception(); } else { ifstream fNegAnn(strNegName.toStdString().c_str()); negAnn.load(fNegAnn); } } catch (exception& ex) { posAnn.clear(); negAnn.clear(); QString str = "Negative annotation: "; str += ex.what(); QMessageBox mb(QMessageBox::Critical, tr("Error"), str); mb.exec(); return false; } try { if (generateDescr) { if (!generateDescription()) throw std::exception(); } else { ifstream fDesc( thirdF.toStdString().c_str() ); desc.load(fDesc); } } catch (exception& ex) { posAnn.clear(); negAnn.clear(); desc.clear(); QString str = "Description: "; str += ex.what(); QMessageBox mb(QMessageBox::Critical, tr("Error"), str); mb.exec(); return false; } posBase.setMarking(posAnn); negBase.setMarking(negAnn); return true; } bool ExpertDiscoveryData::loadAnnotation(MarkingBase& base, const SequenceBase& seqBase, QString strFileName){ QDomDocument pDoc; QFile xmlFile (strFileName); if(!xmlFile.open(QIODevice::ReadOnly)){ return false; } if (!pDoc.setContent(&xmlFile)) { xmlFile.close(); return false; } xmlFile.close(); QDomElement pFamilies = pDoc.documentElement(); if(pFamilies.tagName() != "markup"){ return false; } QDomNode pFamilyNode = pFamilies.firstChild(); while(!pFamilyNode.isNull()){ QDomElement pFamily = pFamilyNode.toElement(); if(pFamily.tagName() == "family"){ QString familyName = pFamily.attribute("name"); //family QDomNode pSignalNode = pFamily.firstChild(); if(pSignalNode.toElement().tagName() != "signal"){ return false; } while(!pSignalNode.isNull()){ QDomElement pSignal = pSignalNode.toElement(); if(pSignal.tagName() == "signal"){ QString signalName = pSignal.attribute("name"); //signal QDomNode pSequenceNode = pSignal.firstChild(); if(pSequenceNode.toElement().tagName() != "sequence"){ return false; } while(!pSequenceNode.isNull()){ QDomElement pSequence = pSequenceNode.toElement(); if(pSequence.tagName() == "sequence"){ QString sequenceId = pSequence.attribute("id"); int cutPos = sequenceId.indexOf(">"); if(cutPos >= 0){ sequenceId = sequenceId.right(sequenceId.length() - cutPos - 1); } sequenceId = sequenceId.trimmed(); //sequence int objN = seqBase.getObjNo(sequenceId.toStdString().c_str()); if(objN >= 0){ QDomNode pInstanceNode = pSequence.firstChild(); if(pInstanceNode.toElement().tagName() != "instance"){ return false; } Marking mrk; try { mrk = base.getMarking(objN); } catch (...) {} while(!pInstanceNode.isNull()){ QDomElement pInstance = pInstanceNode.toElement(); if(pInstance.tagName() == "instance"){ int startPos = pInstance.attribute("start").toInt() - 1; int endPos = pInstance.attribute("end").toInt() - 1; if (endPos >= startPos && startPos >= 0) { mrk.set(signalName.toStdString(), familyName.toStdString(), DDisc::Interval(startPos, endPos)); } //instance } pInstanceNode = pInstanceNode.nextSibling(); } base.setMarking(objN, mrk); } } pSequenceNode = pSequenceNode.nextSibling(); } } pSignalNode = pSignalNode.nextSibling(); } } pFamilyNode = pFamilyNode.nextSibling(); } return true; } // bool ExpertDiscoveryData::loadAnnotationFromUgeneDocument(MarkingBase& base, const SequenceBase& seqBase, Document* doc){ // // foreach(GObject* obj, doc->getObjects()){ // GObject* objk1 = obj; // } // // int objN = seqBase.getObjNo(sequenceId.toStdString().c_str()); // // if(objN >= 0){ // // QDomNode pInstanceNode = pSequence.firstChild(); // // if(pInstanceNode.toElement().tagName() != "instance"){ // // return false; // // } // // Marking mrk; // // try { // // mrk = base.getMarking(objN); // // } // // catch (...) {} // // while(!pInstanceNode.isNull()){ // // QDomElement pInstance = pInstanceNode.toElement(); // // if(pInstance.tagName() == "instance"){ // // int startPos = pInstance.attribute("start").toInt() - 1; // // int endPos = pInstance.attribute("end").toInt() - 1; // // if (endPos >= startPos && startPos >= 0) { // // mrk.set(signalName.toStdString(), familyName.toStdString(), DDisc::Interval(startPos, endPos)); // // } // // //instance // // } // // pInstanceNode = pInstanceNode.nextSibling(); // // } // // base.setMarking(objN, mrk); // // } // return true; // } bool ExpertDiscoveryData::generateDescription(bool clearDescr){ if(clearDescr){ desc.clear(); } SequenceBase* seqBase = &posBase; MarkingBase* base = &posAnn; for (int k=0; k<2; k++) { for (int i=0; igetSize(); i++) { try { Marking mrk = base->getMarking(i); set families = mrk.getFamilies(); set::iterator i = families.begin(); while (i != families.end()) { set edsignals = mrk.getSignals(*i); set::iterator j = edsignals.begin(); while (j != edsignals.end()) { MetaInfo mi; mi.setName(*j); mi.setMethodName("Generated"); desc.insert((*i).c_str(), mi); j++; } i++; } } catch (...) {} } seqBase = &negBase; base = &negAnn; } return true; } void ExpertDiscoveryData::loadControlSequenceAnnotation(const QString& fileName){ ifstream in(fileName.toStdString().c_str()); if (!in.is_open()) { QMessageBox mb(QMessageBox::Critical, tr("Error"), "Can't open file"); mb.exec(); } try { conAnn.load(in); conBase.setMarking(conAnn); } catch (exception& ) { conBase.clearMarking(); conAnn.clear(); QMessageBox mb(QMessageBox::Critical, tr("Error"), "Error loading control markup"); mb.exec(); } if (isLettersMarkedUp() && conBase.getSize() != 0) markupLetters(conBase, conAnn); } void ExpertDiscoveryData::cleanup(){ recDataStorage.clear(); selectedSignals.Clear(); posBase.clear(); negBase.clear(); conBase.clear(); desc.clear(); posAnn.clear(); negAnn.clear(); conAnn.clear(); rootFolder.clear(); clearSelectedSequencesList(); } void ExpertDiscoveryData::addSequenceToSelected(EDPISequence* seq){ selSequences.append(seq); } void ExpertDiscoveryData::clearSelectedSequencesList(){ selSequences.clear(); } bool ExpertDiscoveryData::isSequenceSelected(EDPISequence* seq){ return selSequences.contains(seq); } QList ExpertDiscoveryData::getSelectetSequencesList(){ return selSequences; } void ExpertDiscoveryData::generateRecognitionReportFull(){ QFileDialog saveRepDialog; saveRepDialog.setFileMode(QFileDialog::AnyFile); saveRepDialog.setNameFilter(tr("Hypertext files (*.htm *.html)")); saveRepDialog.setViewMode(QFileDialog::Detail); if(saveRepDialog.exec()){ QStringList fileNames = saveRepDialog.selectedFiles(); if(fileNames.isEmpty()) return; QString fileName = fileNames.first(); fileName = fileName+".htm"; ofstream out(fileName.toStdString().c_str()); if(!updateScores()){ return; } if(!out.is_open()){ QMessageBox mb(QMessageBox::Critical, tr("Error"), tr("Report generation failed")); mb.exec(); return; } if(!generateRecognizationReportHeader(out) || !generateRecognizationReport(out, posBase, "Positive", false) || !generateRecognizationReport(out, negBase, "Negative", true) || (conBase.getSize() != 0 && !generateRecognizationReport(out, conBase, "Control", true)) || !generateRecognizationReportFooter(out)) { QMessageBox mb(QMessageBox::Critical, tr("Error"), tr("Report generation failed")); mb.exec(); return; } } } bool ExpertDiscoveryData::generateRecognizationReportHeader(ostream& out) const{ out << " UGENE (ExpertDiscovery plugin): Recognition report" << endl << "

    ExpertDiscovery 2.0 and UGENE: Recognization report


    " << endl << "Report genrated at " << (QDateTime::currentDateTime().toString("hh:mm on dd/MM/yyyy").toStdString()) << "
    Recognization bound was set to " << recognizationBound << "



    " << endl; return true; } bool ExpertDiscoveryData::generateRecognizationReportFooter(ostream& out) const{ out << ""; return true; } bool ExpertDiscoveryData::generateRecognizationReport(ostream& out, const SequenceBase& rBase, QString strName, bool bSuppressNulls){ if (&rBase == &posBase) { return generateRecognizationReportPositive(out, strName, bSuppressNulls); } if(rBase.getSize() == 0){ return true; } int nRecognized = 0; int nNulls = 0; for (int i=0; i(rBase.getSequence(i)); updateScore(rSeq); double dScore = rSeq.getScore(); if (dScore > recognizationBound) nRecognized++; if (dScore == 0) nNulls++; } out << "

    " << strName.toStdString() << " base


    " << "Total sequences: " << rBase.getSize() << "
    " << "Recognized sequences: " << nRecognized << "
    "; if (bSuppressNulls) out << "Sequences with zero score: " << nNulls << "
    "; out << "Details:
    " << "" << "" << endl; for (int i=0; i= recognizationBound)?"Recognized":"Not recognized"; out << "" << "" << "" << "" << endl; } out << "
    Sequence NoSequence NameScoreResult
    " << i+1 << "" << rSeq.getName() << "" << rSeq.getScore() << "" << result << "

    "; return true; } bool ExpertDiscoveryData::generateRecognizationReportPositive(ostream& out, QString strName, bool bSuppressNulls){ const SequenceBase& rBase = posBase; int nRecognized = 0; int nNulls = 0; for (int i=0; i(rBase.getSequence(i)); updateScore(rSeq); double dScore = rSeq.getScore(); if (dScore > recognizationBound) nRecognized++; if (dScore == 0) nNulls++; } out << "

    " << strName.toStdString() << " base


    " << "Total sequences: " << rBase.getSize() << "
    " << "Recognized sequences: " << nRecognized << "
    "; if (bSuppressNulls) out << "Sequences with zero score: " << nNulls << "
    "; out << "Details:
    " << "" << "" << endl; for (int i=0; i= recognizationBound)?"Recognized":"Not recognized"; out << "" << "" << "" << "" << "" << "" << endl; } out << "
    Sequence NoSequence NameScoreResultFP_LearningFP_Control
    " << i+1 << "" << rSeq.getName() << "" << rSeq.getScore() << "" << result << "" << setiosflags(ios::scientific) << fp_learning << "" << fp_control << resetiosflags(ios::scientific) << "

    "; return true; } int ExpertDiscoveryData::getSequencesCountWithScoreMoreThan(double dScore, const SequenceBase& rBase) const{ int result = 0; for (int i=0; i dScore) result++; } return result; } void ExpertDiscoveryData::generateRecognizationReport(EDProjectItem* pItem){ EDPISequenceBase* pBase = dynamic_cast(pItem); if (!pBase) { assert(0); return; } QFileDialog saveRepDialog; saveRepDialog.setFileMode(QFileDialog::AnyFile); saveRepDialog.setNameFilter(tr("Hypertext files (*.htm *.html)")); saveRepDialog.setViewMode(QFileDialog::Detail); saveRepDialog.setAcceptMode(QFileDialog::AcceptSave); if(saveRepDialog.exec()){ QStringList fileNames = saveRepDialog.selectedFiles(); if(fileNames.isEmpty()) return; QString fileName = fileNames.first(); fileName = fileName+".htm"; ofstream out(fileName.toStdString().c_str()); if(!updateScores()){ return; } if(!out.is_open()){ QMessageBox mb(QMessageBox::Critical, tr("Error"), tr("Report generation failed")); mb.exec(); return; } if(!generateRecognizationReportHeader(out) || !generateRecognizationReport(out, pBase->getSequenceBase(), pBase->getName(), true) || !generateRecognizationReportFooter(out)) { QMessageBox mb(QMessageBox::Critical, tr("Error"), tr("Report generation failed")); mb.exec(); return; } } } int ExpertDiscoveryData::getMaxPosSequenceLen(){ int maxLen = 0; int curLen = 0; for (int i = 0; i < posBase.getSize(); i++){ curLen = posBase.getSequence(i).getSize(); if(curLen > maxLen){ maxLen = curLen; } } return maxLen; } }//namespace ugene-1.9.8/src/plugins/expert_discovery/src/ExpertDiscoveryCSUtil.h0000644000175000017500000001353211651544323024353 0ustar ilyailya#ifndef _U2_EXPERT_DIS_CSUTIL_H_ #define _U2_EXPERT_DIS_CSUTIL_H_ #include "DDisc/Signal.h" #include "DDisc/Sequence.h" #include "ExpertDiscoverySet.h" #include #include #include #include #include #include namespace U2 { using std::set; using namespace DDisc; class CSFolder: public QObject{ Q_OBJECT public: CSFolder(CSFolder* parentFolder = NULL); ~CSFolder(); QString getName() const; void setName(QString strName); CSFolder* getParentFolder() const; void setParentFolder(CSFolder* pParentFolder); void clear(); int getSignalNumber() const; Signal* getSignal(int id); const Signal* getSignal(int id) const; int addSignal(Signal *pSignal, bool bReplace = false); int getSignalIndexByName(QString strName) const; void deleteSignal(int id); QString makeUniqueSignalName() const; CSFolder* clone() const; int getFolderNumber() const; CSFolder* getSubfolder(int id); const CSFolder* getSubfolder(int id) const; int addFolder(CSFolder *pFolder, bool bMerge = false); int getFolderIndexByName(QString strName) const; void deleteFolder(int id); QString makeUniqueFolderName() const; QString getPathToSignal(const Signal* pSignal) const; const Signal* getSignalByPath(QString strPath) const; protected: bool doConstructPath(QString& strPath, const Signal* pSignal) const; private: std::vector signalsVect; QVector folders; QString strName; }; #define UNDEFINED_VALUE (double) 0xFFFFFFFF class EDProcessedSignal { protected: virtual void process(Operation *pOp, const SequenceBase *pYesBase, const SequenceBase *pNoBase) {} public: virtual ~EDProcessedSignal() {} static EDProcessedSignal* processSignal(Operation *pOp, const SequenceBase *pYesBase, const SequenceBase *pNoBase); void makeStandardProcessing(Operation *pOp, const SequenceBase *pYesBase, const SequenceBase *pNoBase); const Set& getYesRealizations(int iSequence) const { return m_arYesRealizations[iSequence];} const Set& getNoRealizations(int iSequence) const { return m_arNoRealizations[iSequence];} QString getTextDescription() const { return m_strDescription; } int getPropertyNumber() const { return (int) m_arNames.size(); } QString getPropertyName (int iProperty) const { return m_arNames[iProperty]; } QString getPropertyValue(int iProperty) const { return m_arValues[iProperty]; } QString getPropertyValue(QString name) const; int getYesSequenceNumber() const { return (int)m_arYesRealizations.size(); } int getNoSequenceNumber() const { return (int)m_arNoRealizations.size(); } double getProbability() const { return m_dProbability; } double getFisher() const { return m_dFisher; } double getUl() const { return m_dUl; } double getPosCoverage() const { return m_dPosCoverage; } double getNegCoverage() const { return m_dNegCoverage; } protected: void addProperty(QString strName, QString strValue) { m_arNames.push_back(strName); m_arValues.push_back(strValue); } EDProcessedSignal(); private: const EDProcessedSignal& operator=(const EDProcessedSignal&); EDProcessedSignal(const EDProcessedSignal&); void setYesRealizations(int iSequence, const Set& set) { m_arYesRealizations[iSequence] = set; } void setNoRealizations(int iSequence, const Set& set) { m_arNoRealizations[iSequence] = set; } void setYesSequenceNumber(int nSeqNum) { m_arYesRealizations.resize(nSeqNum); } void setNoSequenceNumber(int nSeqNum) { m_arNoRealizations.resize(nSeqNum); } void setTextDescription(QString strDesc) { m_strDescription = strDesc; } private: QVector m_arNames; QVector m_arValues; QString m_strDescription; std::vector m_arYesRealizations; std::vector m_arNoRealizations; double m_dProbability; double m_dFisher; double m_dUl; double m_dPosCoverage; double m_dNegCoverage; }; class EDProcessedInterval : public EDProcessedSignal { protected: virtual void process(Operation *pOp, const SequenceBase *pYesBase, const SequenceBase *pNoBase); }; class EDProcessedDistance : public EDProcessedSignal { protected: virtual void process(Operation *pOp, const SequenceBase *pYesBase, const SequenceBase *pNoBase); }; class EDProcessedReiteration : public EDProcessedSignal { protected: virtual void process(Operation *pOp, const SequenceBase *pYesBase, const SequenceBase *pNoBase); }; class EDProcessedTS : public EDProcessedSignal { protected: virtual void process(Operation *pOp, const SequenceBase *pYesBase, const SequenceBase *pNoBase); }; using std::set; typedef set SignalList; class SelectedSignalsContainer { public: SelectedSignalsContainer(void); ~SelectedSignalsContainer(void); void AddSignal(const Signal* pSignal); void RemoveSignal(const Signal* pSignal); const SignalList& GetSelectedSignals() const; bool IsSelected(const Signal *pSignal) const; void save(QDataStream& ar, CSFolder& rootF); void load(QDataStream& ar, CSFolder& rootF); void Clear() { m_SelectedSignals.clear(); } private: SignalList m_SelectedSignals; }; typedef std::vector RecognizationData; class RecognizationDataStorage { public: ~RecognizationDataStorage(); void clear(); void addSequence(QString& seqName); bool getRecognizationData(RecognizationData& d, const Sequence* seq, const SelectedSignalsContainer& rSe); private: RecognizationData* getRecData(const Sequence* seq); QMap recMap; }; } //namespace #endif ugene-1.9.8/src/plugins/expert_discovery/transl/0000755000175000017500000000000011651544323020467 5ustar ilyailyaugene-1.9.8/src/plugins/expert_discovery/transl/russian.ts0000644000175000017500000010777111651544323022540 0ustar ilyailya EDSetupRecBoundDlg Information Информация Probability of positive sequence rejection: Вероятность неузнавания позитивной последовательности: Setup Recognition Bound Установка порога распознавания Recognition Bound Порог распознавания Probability of negative sequence recognition: Вероятность узнавания негативной последовательности: ExpertDiscoveryAdvSetDialog Branch bounds Параметры ветвления Condition probability level Уровень условной вероятности Fisher criteria level Уровень значимости (Фишер) Minimal complexity Минимальная сложность сигнала Maximal complexity Максимальная сложность сигнала Check for distance argument correlation Проверять коррелцию аргументов операции дистанция Disrance argument correlation bounds Параметры корреляции аргументов операции дистанция Min. correlation on positive Мин. корреляция на позитивный Max. correlation on positive Макс. корреляция на позитивный Min. correlation on negative Мин. корреляция на негативных Max. correlation on negative Макс. корреляция на негативных Advanced Extract Parameters Расширенные параметры выделения сигналов ExpertDiscoveryControlDialog Load Control sequences Загрузка контрольных последовательностей File with control sequences Файл с контрольными последовательностями ... ... Cancel Отмена Ok Ок ExpertDiscoveryControlMrkDialog Load Control sequences markup Загрузка разметки контрольных последовательностей File with control sequences markup Файл с разметками контрольных последовательностей ... ... Cancel Отмена Ok Ок ExpertDiscoveryPosNegDialog File with positive sequences Файл с позитивными последовательностями ... ... Generate negative sequences Генерация негативных последовательностей File with negative sequences Файл с негативными последовательностями Cancel Отмена Positive and Negative sequences Позитивные и негативные последовательности Ok Ок ExpertDiscoveryPosNegMrkDialog File with positive sequences markup Файл с разметками позититивных последовательностей ... ... Generate description file Генерировать описание File with negative sequences markup Файл с разметками негативных последовательнстей Description file Файл описания Cancel Отмена Positive and Negative sequences markup Разметка позитивных и негативных последовательностей Ok Ок Append to Current Markup Добавить к текущей разметке SignalsExtrWiz Setup algorithm parameters Установка параметров алгоритма This wizard will help you automaticaly extract complex signals from sequences. Автоматическое выделение комплексных сигналов из последовательностей. Please fill in selection parameters Параметры отбора сигналов Condition probability level Уровень условной вероятности Coverege bound Порог покрытия Fisher criteria level Уровень значимости по критерию Фишера Check minimization of Fisher criteria Минимизация критерия Фишера Store only signals with different behaviour Сохранять только сигналы с различным поведением Check Ul criteria Учитывать U-критерий Samples bound Порог по выборкам Level bound Порог по уровню Advanced... Дополнительно... Setup predicates Установка предикатов Distance Дистанция Repetition Повторение Interval Интервал Delete Удалить Editor Редактор Select folder Выбор директории Select folder to store extracted complex signals Выбор директории для сохранения комплексных сигналов Extractor Parameters setup Установка параметров выделения сигналов Please create some predicates that will be used in complex signal construction process. Необходимо создать пердикаты, которые будут использоваться при конструировании комплексных сигналов. Minimal Complexity Минимальная сложность Maximal Complexity Максимальная сложность Aligned Выровненная выборка Coverage bound Порог покрытия U2::CSFolder NewSignal Новый сигнал NewFolder Новая папка U2::DistanceSet Distance from Дистанция от Distance to Дистанция до Unlimited Неограниченный Take order into account учитывать порядок Wrong parameters Неправильные парметры Higher bound must be grater then lower bound Верхняя грнаица должна быть больше нижней границы U2::EDProjectTree Rename error Ошибка переименовывания Folder already exist Папка уже существует Signal rename Переименовать сигнал Signal with the same name already exist. Replace? Сигнал с таким именем уже существует. Заменить? Select/deselect signal Селектировать/деселктировать сигнал New folder Новая папка New signal Новый сигнал Delete Удалить Select all signals Селектировать все сигналы Deselect all signals Деселектировать все сигналы Set prior parameters of all signals Установить ожидаемые параметры всех сигналов Clear prior parameters of all signals Очистить ожидаемые параметры всех сигналов Set current params as prior Установить текущие параметры, как ожидаемые Clear prior params Очистить ожидаемые параметры Markup letters Разметка буквами Load markup Загрузка разметок Show sequence Показать последовательность Add to shown Добавить к отображаемым последовательностям Generate report Генерировать отчет Increasing Возрастание Decreasing Убывание Coverage Покрытие Fisher Фишер Name Имя Probability Вероятность Error Ошибка The value must be positive integer which is less than the higher bound Значение должно быть положительным целым и ниже верхней границы The value must be grater than the lower bound Значение должно быть выше нижней границы The word must be in 15-character code Слово должно быть в 15-буквенном алфавите Select signal Селектировать сигнал Deselect signal Деселектировать сигнал Show one sequence Показать одну последовательность Add to displayed Добавить к отображаемым Clear displayed sequences area Очистить область отображения Show sequences Отобразить последовательности Sort Сортировка Field Поле Order Порядок U2::ExpertDiscoveryAdvSetDialog Wrong parameters Неверные параметры Minimal complexity must not be grater then maximal complexity and positive Минимальная сложность должна быть меньше, чем максимальная и положительной U2::ExpertDiscoveryControlDialog Select files Выберети файлы Select files for ExpertDiscovery Выберете файлы для ExpertDiscovery Open control sequences file Открыть файл с контрольными последовательностями U2::ExpertDiscoveryControlMrkDialog Select files выберете файлы Select files for ExpertDiscovery Выбрете файлы для ExpertDiscovery Open control sequences markup file Открыть файс с разметками конторольных последовательностей U2::ExpertDiscoveryCreateADVTask ExpertDiscovery sequence view ExpertDiscovery sequence view U2::ExpertDiscoveryCreateViewTask ED ED Maximum number of objects per view reached: %1 Максимальное число последовательностей для отображения достигнуто: %1 Sequence object not available! URL %1, name %2 Последовательность не доступан! URL %1, name %2 No sequence objects found Не найдены последовательности U2::ExpertDiscoveryData Setting up recognization bound. Please wait Установка порога распознования. Пожалуйста, подождите Cancel Отмена Updating positive sequences Обновление позитивной выборки Updating negative sequences Обновление негативной выборки Updating control sequences Обновление контрольной выборки Error Ошибка Hypertext files (*.htm *.html) Hypertext files (*htm *html) Report generation failed Ошибка генерации отчета U2::ExpertDiscoveryErrors File opening error Ошибка открытия файла Error opening file %1 Ошибка открытия файла %1 Error Ошибка Error loading markups Ошибка загрузки разметок U2::ExpertDiscoveryExtSigWiz No predicates нет предикатов Create a predicate to perform signal generation Создайте предикат, чтобы запустить выделение сигналов Wrong parameters Неверные параметры Complex signals Комплексные сигналы Select predicate on the tree above or create a new one using buttons. Создайте предикаты и задайте их параметры. Minimal complexity must not be grater then maximal complexity and positive Минимальная сложность должна быть меньше, чем максимальная и положительной U2::ExpertDiscoveryLoadControlMrkTask ExpertDiscovery loading Загрузка ExpertDiscovery U2::ExpertDiscoveryLoadControlTask ExpertDiscovery loading ExpertDiscovery загрузка Detecting format error for file %1 Ошибка определения формата для файла %1 U2::ExpertDiscoveryLoadPosNegMrkTask ExpertDiscovery loading Загрузка ExpertDiscovery Error Ошибка U2::ExpertDiscoveryLoadPosNegTask ExpertDiscovery loading Загрузка ExpertDiscovery Detecting format error for file %1 Ошибка определения формата для файла %1 U2::ExpertDiscoveryPlugin Expert Discovery ExpertDiscovery Expert Discovery plugin ExpertDiscovery plugin ExpertDiscovery ExpertDiscovery Expert Discovery (alpha) U2::ExpertDiscoveryPosNegDialog Select files Выберете файлы Positive and negative sequences can't be in the one file. Select another file for one of them Позитивная и негативня выборка не может быть в одном и том же файле. Выберете другой файл для одной из них Select files for ExpertDiscovery Выберете файлы для ExpertDiscovery Open positive sequences file Открыть файл с позитивными последовательностями Open second file Открыть второй файл U2::ExpertDiscoveryPosNegMrkDialog Select files Выберете файлы Positive and negative sequences markups can't be in the one file. Select another file for one of them Разметка позитивной и негативной выборки не может быть в одном и том же файле. Выберете другой файл для одной из них Select description file Выберете файл описания Select files for ExpertDiscovery Выберете файлы для ExpertDiscovery Open positive sequences markup file Открыть файл с разместкой позитивных последовательностей Open second file Открыть второй файл Open description file Открыть файл описания U2::ExpertDiscoverySignalExtractorTask ExpertDiscovery signals extracting ExpertDiscovery выделение сигналов U2::ExpertDiscoverySignalsAutoAnnotationUpdater Signals Комплексные сигналы U2::ExpertDiscoveryToAnnotationTask Find and store expert discovery signals on a sequence Найти и сохранить комплксные сигналы на последовательности Annotation table does not exist Таблица аннотаций не существует Annotation table is read-only Таблица аннотаций только для чтения No expert discovery sequence Нет последовательности ExpertDiscovery Annotation obj %1 is locked for modifications Аннотация %1 заблокирована U2::ExpertDiscoveryView New ExpertDiscovery Document Создать новый лдокумент ExpertDiscovery Open ExpertDiscovery Document Открыть документ ExpertDiscovery Save ExpertDiscovery Document Сохранить документ ExpertDiscovery Load control sequences Загрузка контрольных последовательностей Extract signals Выделение сигналов Load markup Загрузка разметок Load control sequences markup Загрузка разметок контрольных последовательностей Generate recognition report Генерация отчета о распозновании Load ExpertDiscovery document Загрузка документа ExpeertDiscovery ExpertDiscovery files (*.exd) Файлы ExpertDiscovery (*.exd) Save ExpertDiscovery document Сохранить документ ExpertDiscovery Do you want to save current ExpertDiscovery document? Вы хотите сохранить текущий документ ExpertDiscovery? Error Ошибка No signals are selected to generate report Не выбраны сигналы для генерации отчета Set Recognition Bound Установка порога распознования Optimize Recognition Bound Оптимизация порога распознования New Expert Discovery Document Создать новый документ Expert Discovery Open Expert Discovery Document Открыть документ Expert Discovery Save Expert Discovery Document Сохранить документ Expert Discovery U2::ExpertDiscoveryViewWindow Closing error Ошибка при закрытии There are unfinished extracting tasks. Cancel them before closing Задание по загрузке сигналов не завершено. Отмените его перед закрытием U2::IntervalSet Interval from Интервал от Interval to Интервал до Unlimited Неограниченный Wrong parameters Неправильные парметры Higher bound must be grater then lower bound Верхняя грнаица должна быть больше нижней границы U2::RepetitionSet Distance from Дистанция от Distance to Дистанция до Unlimited Неограниченный Count from Считая от Count to Считая до Wrong parameters Неправильные парметры Higher bound must be grater then lower bound Верхняя грнаица должна быть больше нижней границы ugene-1.9.8/src/plugins/expert_discovery/transl/czech.ts0000644000175000017500000000013511651544323022132 0ustar ilyailya ugene-1.9.8/src/plugins/expert_discovery/transl/english.ts0000644000175000017500000006105511651544323022477 0ustar ilyailya EDSetupRecBoundDlg Information Probability of positive sequence rejection: Setup Recognition Bound Recognition Bound Probability of negative sequence recognition: ExpertDiscoveryAdvSetDialog Branch bounds Condition probability level Fisher criteria level Minimal complexity Maximal complexity Check for distance argument correlation Disrance argument correlation bounds Min. correlation on positive Max. correlation on positive Min. correlation on negative Max. correlation on negative Advanced Extract Parameters ExpertDiscoveryControlDialog Load Control sequences File with control sequences ... Cancel Ok ExpertDiscoveryControlMrkDialog Load Control sequences markup File with control sequences markup ... Cancel Ok ExpertDiscoveryPosNegDialog File with positive sequences ... Generate negative sequences File with negative sequences Cancel Positive and Negative sequences Ok ExpertDiscoveryPosNegMrkDialog File with positive sequences markup ... Generate description file File with negative sequences markup Description file Cancel Positive and Negative sequences markup Ok Append to Current Markup SignalsExtrWiz Setup algorithm parameters This wizard will help you automaticaly extract complex signals from sequences. Please fill in selection parameters Condition probability level Fisher criteria level Check minimization of Fisher criteria Store only signals with different behaviour Check Ul criteria Samples bound Level bound Advanced... Setup predicates Distance Repetition Interval Delete Editor Select folder Select folder to store extracted complex signals Extractor Parameters setup Please create some predicates that will be used in complex signal construction process. Minimal Complexity Maximal Complexity Aligned Coverage bound U2::DistanceSet Distance from Distance to Unlimited Take order into account Wrong parameters Higher bound must be grater then lower bound U2::EDProjectTree Rename error Folder already exist Signal rename Signal with the same name already exist. Replace? Select/deselect signal New folder New signal Delete Select all signals Deselect all signals Set prior parameters of all signals Clear prior parameters of all signals Set current params as prior Clear prior params Markup letters Load markup Generate report Increasing Decreasing Coverage Fisher Name Probability Error The value must be positive integer which is less than the higher bound The value must be grater than the lower bound The word must be in 15-character code Select signal Deselect signal Show one sequence Add to displayed Clear displayed sequences area Show sequences Sort Field Order U2::ExpertDiscoveryAdvSetDialog Wrong parameters Minimal complexity must not be grater then maximal complexity and positive U2::ExpertDiscoveryControlDialog Select files Select files for ExpertDiscovery Open control sequences file U2::ExpertDiscoveryControlMrkDialog Select files Select files for ExpertDiscovery Open control sequences markup file U2::ExpertDiscoveryCreateADVTask ExpertDiscovery sequence view U2::ExpertDiscoveryCreateViewTask ED Maximum number of objects per view reached: %1 Sequence object not available! URL %1, name %2 No sequence objects found U2::ExpertDiscoveryData Setting up recognization bound. Please wait Cancel Updating positive sequences Updating negative sequences Updating control sequences Error Hypertext files (*.htm *.html) Report generation failed U2::ExpertDiscoveryErrors File opening error Error opening file %1 Error Error loading markups U2::ExpertDiscoveryExtSigWiz No predicates Create a predicate to perform signal generation Wrong parameters Complex signals Select predicate on the tree above or create a new one using buttons. Minimal complexity must not be grater then maximal complexity and positive U2::ExpertDiscoveryLoadControlMrkTask ExpertDiscovery loading U2::ExpertDiscoveryLoadControlTask ExpertDiscovery loading Detecting format error for file %1 U2::ExpertDiscoveryLoadPosNegMrkTask ExpertDiscovery loading Error U2::ExpertDiscoveryLoadPosNegTask ExpertDiscovery loading Detecting format error for file %1 U2::ExpertDiscoveryPlugin Expert Discovery Expert Discovery plugin Expert Discovery (alpha) U2::ExpertDiscoveryPosNegDialog Select files Positive and negative sequences can't be in the one file. Select another file for one of them Select files for ExpertDiscovery Open positive sequences file Open second file U2::ExpertDiscoveryPosNegMrkDialog Select files Positive and negative sequences markups can't be in the one file. Select another file for one of them Select description file Select files for ExpertDiscovery Open positive sequences markup file Open second file Open description file U2::ExpertDiscoverySignalExtractorTask ExpertDiscovery signals extracting U2::ExpertDiscoverySignalsAutoAnnotationUpdater Signals U2::ExpertDiscoveryToAnnotationTask Find and store expert discovery signals on a sequence Annotation table does not exist Annotation table is read-only No expert discovery sequence Annotation obj %1 is locked for modifications U2::ExpertDiscoveryView Load control sequences Extract signals Load markup Load control sequences markup Generate recognition report Load ExpertDiscovery document ExpertDiscovery files (*.exd) Save ExpertDiscovery document Do you want to save current ExpertDiscovery document? Error No signals are selected to generate report Set Recognition Bound Optimize Recognition Bound New Expert Discovery Document Open Expert Discovery Document Save Expert Discovery Document U2::ExpertDiscoveryViewWindow Closing error There are unfinished extracting tasks. Cancel them before closing U2::IntervalSet Interval from Interval to Unlimited Wrong parameters Higher bound must be grater then lower bound U2::RepetitionSet Distance from Distance to Unlimited Count from Count to Wrong parameters Higher bound must be grater then lower bound ugene-1.9.8/src/plugins/expert_discovery/expert_discovery.pri0000644000175000017500000000030211651544322023270 0ustar ilyailya# include (expert_discovery.pri) PLUGIN_ID=expert_discovery PLUGIN_NAME=Expert Discovery PLUGIN_VENDOR=Unipro PLUGIN_MODE=ui CONFIG += warn_off include( ../../ugene_plugin_common.pri ) ugene-1.9.8/src/plugins/workflow_dump/0000755000175000017500000000000011651544325016467 5ustar ilyailyaugene-1.9.8/src/plugins/workflow_dump/workflow_dump.pro0000644000175000017500000000016711651544325022114 0ustar ilyailyainclude (workflow_dump.pri) # Input HEADERS += src/WorkflowDumpPlugin.h SOURCES += src/WorkflowDumpPlugin.cpp ugene-1.9.8/src/plugins/workflow_dump/workflow_dump.pri0000644000175000017500000000036611651544325022107 0ustar ilyailya# include (workflow_dump.pri) PLUGIN_ID=workflow_dump PLUGIN_NAME=Workflow Dump PLUGIN_VENDOR=Unipro #Uncomment to enable workflow dump #DEFINES+=WORKFLOW_DUMP include( ../../ugene_plugin_common.pri ) INCLUDEPATH += ../../corelibs/U2Misc/_tmpugene-1.9.8/src/plugins/workflow_dump/src/0000755000175000017500000000000011651544325017256 5ustar ilyailyaugene-1.9.8/src/plugins/workflow_dump/src/WorkflowDumpPlugin.h0000644000175000017500000000231211651544325023244 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_FLOWCHART_H_ #define _U2_FLOWCHART_H_ #include class QAction; class QEvent; namespace U2 { class WorkflowDumpPlugin : public Plugin { Q_OBJECT public: WorkflowDumpPlugin (); //~WorkflowDumpPlugin (); private slots: void sl_dumpWorkers(); }; } //namespace #endif ugene-1.9.8/src/plugins/workflow_dump/src/WorkflowDumpPlugin.cpp0000644000175000017500000002653611651544325023615 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "WorkflowDumpPlugin.h" #include #include #include #include #include #include #include #include /* TRANSLATOR U2::LocalWorkflow::WorkflowView */ /* TRANSLATOR U2::LocalWorkflow::WorkflowDumpPlugin */ namespace U2 { using namespace Workflow; extern "C" Q_DECL_EXPORT Plugin* U2_PLUGIN_INIT_FUNC() { WorkflowDumpPlugin * plug = new WorkflowDumpPlugin(); return plug; } WorkflowDumpPlugin::WorkflowDumpPlugin() : Plugin(tr("Workflow Dump"), tr("Workflow Dump exports workflow data.")){ #ifdef WORKFLOW_DUMP if (AppContext::getMainWindow()) { QAction* dumpAction = new QAction(tr("Dump workers"), this); QMenu* tools = AppContext::getMainWindow()->getTopLevelMenu(MWMENU_TOOLS); tools->addAction(dumpAction); connect(dumpAction,SIGNAL(triggered()),SLOT(sl_dumpWorkers())); } #endif /*WORKFLOW_DUMP*/ } class JsonWriter { public: JsonWriter() : separator(":"), lenient(false), indent(" ") { stack.append(EMPTY_DOCUMENT); } JsonWriter& name(QString name) { //if (name == null) { // throw new NullPointerException("name == null"); //} beforeName(); string(name); return *this; } JsonWriter& value(QString value) { beforeValue(false); string(value); return *this; } JsonWriter& boolValue(bool value) { beforeValue(false); out.append(value ? "true" : "false"); return *this; } JsonWriter& intValue(int value) { beforeValue(false); out.append(QString::number(value)); return *this; } JsonWriter& doubleValue(double value) { beforeValue(false); out.append(QString::number(value)); return *this; } JsonWriter& longValue(long value) { beforeValue(false); out.append(QString::number(value)); return *this; } JsonWriter& plainValue(QByteArray value) { /*if (value == null) { return nullValue(); }*/ beforeValue(false); out.append(value); return *this; } JsonWriter& beginArray() { return open(EMPTY_ARRAY, "["); } JsonWriter& beginObject() { return open(EMPTY_OBJECT, "{"); } JsonWriter& endArray() { return close(EMPTY_ARRAY, NONEMPTY_ARRAY, "]"); } JsonWriter& endObject() { return close(EMPTY_OBJECT, NONEMPTY_OBJECT, "}"); } QByteArray& getBytes() { return out; } private: enum JsonScope { EMPTY_ARRAY, NONEMPTY_ARRAY, EMPTY_OBJECT, DANGLING_NAME, NONEMPTY_OBJECT, EMPTY_DOCUMENT, NONEMPTY_DOCUMENT, CLOSED }; const QString separator; bool lenient; QString indent; QList stack; QByteArray out; void string(QString value) { out.append("\""); for (int i = 0, length = value.length(); i < length; i++) { char c = value[i].toAscii(); /* * From RFC 4627, "All Unicode characters may be placed within the * quotation marks except for the characters that must be escaped: * quotation mark, reverse solidus, and the control characters * (U+0000 through U+001F)." */ switch (c) { case '"': case '\\': out.append('\\'); out.append(c); break; case '\t': out.append("\\t"); break; case '\b': out.append("\\b"); break; case '\n': out.append("\\n"); break; case '\r': out.append("\\r"); break; case '\f': out.append("\\f"); break; case '<': case '>': case '&': case '=': case '\'': out.append(c); break; default: /*if (c <= 0x1F) { out.append(String.format("\\u%04x", (int) c)); } else {*/ out.append(c); //} break; } } out.append("\""); } JsonWriter& open(JsonScope empty, QString openBracket) { beforeValue(true); stack.append(empty); out.append(openBracket); return *this; } JsonWriter& close(JsonScope empty, JsonScope nonempty, QString closeBracket) { JsonScope context = peek(); if (context != nonempty && context != empty) { throw QString("Nesting problem:"); } stack.takeAt(stack.size() - 1); if (context == nonempty) { newline(); } out.append(closeBracket); return *this; } void newline() { if (indent.isEmpty()) { return; } out.append("\r\n"); for (int i = 1; i < stack.size(); i++) { out.append(indent); } } JsonScope peek() { return stack.at(stack.size() - 1); } void replaceTop(JsonScope topOfStack) { stack[stack.size() - 1] = topOfStack; } void beforeName() { JsonScope context = peek(); if (context == NONEMPTY_OBJECT) { // first in object out.append(','); } else if (context != EMPTY_OBJECT) { // not in an object! throw QString("Nesting problem"); } newline(); replaceTop(DANGLING_NAME); } void beforeValue(bool root) { switch (peek()) { case EMPTY_DOCUMENT: // first in document if (!lenient && !root) { throw QString("JSON must start with an array or an object."); } replaceTop(NONEMPTY_DOCUMENT); break; case EMPTY_ARRAY: // first in array replaceTop(NONEMPTY_ARRAY); newline(); break; case NONEMPTY_ARRAY: // another in array out.append(','); newline(); break; case DANGLING_NAME: // value for name out.append(separator); replaceTop(NONEMPTY_OBJECT); break; case NONEMPTY_DOCUMENT: throw QString("JSON must have only one top-level value."); default: throw QString("Nesting problem"); } } }; static QByteArray type2json(DataTypePtr type) { JsonWriter w; w.beginObject() .name("id").value(type->getId()) .name("kind"); switch(type->kind()) { case DataType::Single: w.value("Single"); break; case DataType::List: w.value("List") .name("type").plainValue(type2json(type->getDatatypeByDescriptor())); break; case DataType::Map: w.value("Map").name("type").beginObject(); foreach(const Descriptor& desc, type->getDatatypesMap().keys()) { w.name(desc.getId()) .plainValue(type2json(type->getDatatypesMap()[desc])); } w.endObject(); break; } w.endObject(); return w.getBytes(); } void WorkflowDumpPlugin::sl_dumpWorkers() { const QMap >& map = WorkflowEnv::getProtoRegistry()->getProtos(); JsonWriter w; w.beginObject(); w.name("types"); w.beginArray(); foreach(const DataTypePtr desc, WorkflowEnv::getDataTypeRegistry()->getAllEntries()) { w.beginObject() .name("id").value(desc->getId()) .name("name").value(desc->getDisplayName()) .name("desc").value(desc->getDocumentation()) .endObject(); } w.endArray(); w.name("groups"); w.beginArray(); foreach(const Descriptor& desc, WorkflowEnv::getProtoRegistry()->getProtos().keys()) { w.beginObject() .name("id").value(desc.getId()) .name("name").value(desc.getDisplayName()) .name("desc").value(desc.getDocumentation()) .endObject(); } w.endArray(); w.name("workers"); w.beginArray(); foreach(const Descriptor& desc, map.keys()) { foreach(const ActorPrototype* proto, map[desc]) { w.beginObject() .name("group").value(desc.getId()) .name("id").value(proto->getId()) .name("name").value(proto->getDisplayName()) .name("desc").value(proto->getDocumentation()) .name("icon").value(proto->getIconPath()) .name("attrs").beginArray(); foreach(const Attribute* attr, proto->getAttributes()) { w.beginObject() .name("id").value(attr->getId()) .name("name").value(attr->getDisplayName()) .name("desc").value(attr->getDocumentation()) .name("type").plainValue(type2json(attr->getAttributeType())) .name("value").value(attr->getAttributeValue()) .name("required").boolValue(attr->isRequiredAttribute()) .endObject(); } w.endArray() .name("ports").beginArray(); foreach(const PortDescriptor* port, proto->getPortDesciptors()) { w.beginObject() .name("id").value(port->getId()) .name("name").value(port->getDisplayName()) .name("desc").value(port->getDocumentation()) .name("type").plainValue(type2json(port->getType())) .name("input").boolValue(port->isInput()) .name("multi").boolValue(port->isMulti()) .name("flags").intValue(port->getFlags()) .endObject(); } w.endArray() .endObject(); } } w.endArray(); w.endObject(); QFile file("D:\\workers.dump"); if(file.open(QFile::WriteOnly)) { file.write(w.getBytes()); } else { printf("Can't open file to write: %s", file.fileName().toAscii().constData()); } file.close(); } }//namespace ugene-1.9.8/src/plugins/cuda_support/0000755000175000017500000000000011651544321016274 5ustar ilyailyaugene-1.9.8/src/plugins/cuda_support/cuda_support.pro0000644000175000017500000000035111651544321021525 0ustar ilyailyainclude (cuda_support.pri) # Input HEADERS += src/CudaSupportPlugin.h src/CudaSupportSettingsController.h SOURCES += src/CudaSupportPlugin.cpp src/CudaSupportSettingsController.cpp TRANSLATIONS += transl/english.ts transl/russian.tsugene-1.9.8/src/plugins/cuda_support/src/0000755000175000017500000000000011651544321017063 5ustar ilyailyaugene-1.9.8/src/plugins/cuda_support/src/CudaSupportPlugin.h0000644000175000017500000000311111651544321022660 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef __CUDA_SUPPORT_PLUGIN_H__ #define __CUDA_SUPPORT_PLUGIN_H__ #include #include #include namespace U2 { #define ULOG_CAT_PLUGIN_CUDA_SUPPORT "Plugin: CudaSupport" class CudaSupportPlugin : public Plugin { Q_OBJECT public: enum Error { Error_NoError, Error_NoDriverLib, Error_BadDriverLib, Error_CudaError }; CudaSupportPlugin(); private: Error obtainGpusInfo( QString & err ); void loadGpusSettings(); void registerAvailableGpus(); static QString getCudaErrorString( CUresult code ); static QString getSettingsErrorString( Error err ); QList gpus; }; } #endif //__CUDA_SUPPORT_PLUGIN_H__ ugene-1.9.8/src/plugins/cuda_support/src/CudaSupportSettingsController.h0000644000175000017500000000421211651544321025271 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef __CUDA_SUPPORT_SETTINGS_CONTROLLER__ #define __CUDA_SUPPORT_SETTINGS_CONTROLLER__ #include #include #include #include namespace U2 { #define CudaSupportSettingsPageId QString("css") class CudaSupportSettingsPageController : public AppSettingsGUIPageController { Q_OBJECT public: CudaSupportSettingsPageController( const QString & _displayMsg, QObject * p = 0 ); virtual AppSettingsGUIPageState * getSavedState(); virtual void saveState( AppSettingsGUIPageState * s ); virtual AppSettingsGUIPageWidget * createWidget( AppSettingsGUIPageState* state ); private: QString displayMsg; }; class CudaSupportSettingsPageState : public AppSettingsGUIPageState { Q_OBJECT public: CudaSupportSettingsPageState( int num_gpus ); QVector enabledGpus; }; class CudaSupportSettingsPageWidget : public AppSettingsGUIPageWidget { Q_OBJECT public: CudaSupportSettingsPageWidget( const QString & _msg, CudaSupportSettingsPageController * ctrl ); virtual void setState( AppSettingsGUIPageState * state ); virtual AppSettingsGUIPageState* getState( QString & err ) const; QString onlyMsg; QList gpuEnableChecks; }; } //namespace #endif //__CUDA_SUPPORT_SETTINGS_CONTROLLER__ ugene-1.9.8/src/plugins/cuda_support/src/CudaSupportPlugin.cpp0000644000175000017500000002306211651544321023222 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include #include #include #include #include #include #include "CudaSupportPlugin.h" #include "CudaSupportSettingsController.h" namespace U2 { extern "C" Q_DECL_EXPORT Plugin * U2_PLUGIN_INIT_FUNC() { CudaSupportPlugin * plug = new CudaSupportPlugin(); return plug; } const static char * RESOURCE_CUDA_GPU_NAME = "CudaGpu"; CudaSupportPlugin::CudaSupportPlugin() : Plugin( tr("CUDA Support"), tr("Utility plugin for CUDA-enabled GPUs support") ) { QString err_str; Error err = obtainGpusInfo( err_str ); if( err_str.isEmpty() && gpus.empty() ) { err_str = "No CUDA-enabled GPUs found."; } if( Error_NoError == err ) { loadGpusSettings(); registerAvailableGpus(); } else { coreLog.details( err_str ); } //adding settings page if (AppContext::getMainWindow()) { QString settingsPageMsg = getSettingsErrorString(err); AppContext::getAppSettingsGUI()->registerPage( new CudaSupportSettingsPageController(settingsPageMsg) ); } //registering gpu resource if( !gpus.empty() ) { AppResource * gpuResource = new AppResource( RESOURCE_CUDA_GPU, gpus.size(), RESOURCE_CUDA_GPU_NAME ); AppResourcePool::instance()->registerResource( gpuResource ); } } QString CudaSupportPlugin::getCudaErrorString( CUresult code ) { switch(code) { case CUDA_SUCCESS: return QString(); case CUDA_ERROR_INVALID_DEVICE: return tr( "Invalid device" ); case CUDA_ERROR_NO_DEVICE: return tr( "No cuda-enabled devices found" ); default: return tr( "Unknown error" ); //TODO } } QString CudaSupportPlugin::getSettingsErrorString( Error err ) { switch(err) { case Error_NoError: return QString(""); case Error_NoDriverLib: return tr( "\ Cannot load CUDA driver dynamic library.

    \ It is necessary to install latest Nvidia GPU driver for running
    \ GPU-accelerated algorithms on Nvidia hardware." ); case Error_BadDriverLib: return tr( "\ Cannot obtain needed info about Nvidia GPU.

    \ Consider reinstallation of GPU driver.
    \ See CUDA Support plugin log for details." ); case Error_CudaError: return tr( "\ An error occurred while obtaining information about installed Nvidia GPUs.
    \ See CUDA Support plugin log for details" ); default: assert(false); return QString(); } } #ifdef Q_OS_WIN #define CUDA_DRIVER_LIB "nvcuda" #else #define CUDA_DRIVER_LIB "cuda" #endif #ifdef Q_OS_WIN #define CALLING_CONVENTION __stdcall #else #define CALLING_CONVENTION #endif typedef CUresult ( CALLING_CONVENTION *cuinit_f)(int); const static char * cuinit_n = "cuInit"; typedef CUresult ( CALLING_CONVENTION *cu_device_get_count_f)(int*); const static char * cu_device_get_count_n = "cuDeviceGetCount"; typedef CUresult ( CALLING_CONVENTION *cu_device_get_f)(CUdevice*, int); const static char * cu_device_get_n = "cuDeviceGet"; typedef CUresult ( CALLING_CONVENTION *cu_device_get_name_f)(char *, int, CUdevice ); const static char * cu_device_get_name_n = "cuDeviceGetName"; typedef CUresult ( CALLING_CONVENTION *cu_device_total_mem_f)(unsigned int*, CUdevice ); const static char * cu_device_total_mem_n = "cuDeviceTotalMem"; typedef CUresult ( CALLING_CONVENTION *cu_device_get_properties_f)(CUdevprop * prop, CUdevice dev); const static char * cu_device_get_properties_n = "cuDeviceGetProperties"; CudaSupportPlugin::Error CudaSupportPlugin::obtainGpusInfo( QString & err ) { //load driver library coreLog.details( tr("Loading CUDA driver library") ); QLibrary cudaLib( CUDA_DRIVER_LIB ); cudaLib.load(); if( !cudaLib.isLoaded() ) { QString message = tr( "Cannot load driver library. Error while loading %1: " ).arg(cudaLib.fileName()) + cudaLib.errorString(); coreLog.details(message); return Error_NoDriverLib; } CUresult cudaRetCode = CUDA_SUCCESS; //call cuInit() coreLog.details( tr("Initializing CUDA") ); cuinit_f c_i = cuinit_f( cudaLib.resolve(cuinit_n) ); if( !c_i ) { err = tr("Cannot resolve symbol ") + cuinit_n; return Error_BadDriverLib; } cudaRetCode = c_i(0); // 0 is required by reference manual if( CUDA_SUCCESS != cudaRetCode ) { err = getCudaErrorString(cudaRetCode); return Error_CudaError; } //call cuDeviceGetCount() coreLog.details( tr("Obtaining number of CUDA-enabled devices") ); cu_device_get_count_f c_dgc = cu_device_get_count_f( cudaLib.resolve(cu_device_get_count_n) ); if( !c_dgc ) { err = tr("Cannot resolve symbol ") + cu_device_get_count_n; return Error_BadDriverLib; } int num_devices = 0; cudaRetCode = c_dgc( &num_devices ); if( CUDA_SUCCESS != cudaRetCode ) { err = getCudaErrorString(cudaRetCode); return Error_CudaError; } //for each device - get it's parameters for( int i = 0; i < num_devices; ++i ) { CUdevice cuDevice; //call cuDeviceGet() cu_device_get_f c_dg = cu_device_get_f( cudaLib.resolve(cu_device_get_n) ); if( !c_dg ) { err = tr("Cannot resolve symbol ") + cu_device_get_n; return Error_BadDriverLib; } cudaRetCode = c_dg( &cuDevice, i ); if( CUDA_SUCCESS != cudaRetCode ) { err = getCudaErrorString(cudaRetCode); return Error_CudaError; } //obtain device name const int maxname = 256; QByteArray name(maxname, 0); cu_device_get_name_f c_dgn = cu_device_get_name_f( cudaLib.resolve(cu_device_get_name_n) ); if( !c_dgn ) { err = tr( "Cannot resolve symbol " ) + cu_device_get_name_n; return Error_BadDriverLib; } cudaRetCode = c_dgn( name.data(), maxname, cuDevice ); if( CUDA_SUCCESS != cudaRetCode ) { err = getCudaErrorString(cudaRetCode); return Error_CudaError; } //obtain device global memory size unsigned int mem = 0; cu_device_total_mem_f c_dtm = cu_device_total_mem_f( cudaLib.resolve(cu_device_total_mem_n) ); if( !c_dtm ) { err = tr( "Cannot resolve symbol" ) + cu_device_total_mem_n; return Error_BadDriverLib; } cudaRetCode = c_dtm( &mem, cuDevice ); if( CUDA_SUCCESS != cudaRetCode ) { err = getCudaErrorString(cudaRetCode); return Error_CudaError; } //obtain device shared memory size cu_device_get_properties_f c_dgp = cu_device_get_properties_f( cudaLib.resolve(cu_device_get_properties_n) ); if( !c_dgp ) { err = tr( "Cannot resolve symbol" ) + cu_device_get_properties_n; return Error_BadDriverLib; } CUdevprop props; cudaRetCode = c_dgp( &props, cuDevice ); if( CUDA_SUCCESS != cudaRetCode ) { err = getCudaErrorString(cudaRetCode); return Error_CudaError; } // log.info("props.sharedMemPerBlock " + QString::number(props.sharedMemPerBlock)); // log.info("props.clockRate) " + QString::number(props.clockRate)); // log.info("props.maxGridSize[0] " + QString::number(props.maxGridSize[0])); // log.info("props.maxThreadsDim[0] " + QString::number(props.maxThreadsDim[0])); // log.info("props.maxThreadsPerBlock " + QString::number(props.maxThreadsPerBlock)); // log.info("props.memPitch " + QString::number(props.memPitch)); // log.info("props.regsPerBlock " + QString::number(props.regsPerBlock)); // log.info("props.SIMDWidth " + QString::number(props.SIMDWidth)); // log.info("props.textureAlign " + QString::number(props.textureAlign)); // log.info("props.totalConstantMemory " + QString::number(props.totalConstantMemory)); CudaGpuModel * m = new CudaGpuModel( QString(name), CudaGpuId(cuDevice), mem ); gpus.push_back(m); coreLog.details( tr("Registering CUDA-enabled GPU: %1, id: %2").arg(m->getName(), QString::number(m->getId())) ); } return Error_NoError; } void CudaSupportPlugin::registerAvailableGpus() { foreach( CudaGpuModel * m, gpus ) { AppContext::getCudaGpuRegistry()->registerCudaGpu(m); } } void CudaSupportPlugin::loadGpusSettings() { Settings * s = AppContext::getSettings(); foreach( CudaGpuModel * m, gpus ) { QString key = CUDA_GPU_REGISTRY_SETTINGS_GPU_SPECIFIC + QString::number(m->getId()) + CUDA_GPU_SETTINGS_ENABLED; QVariant enabled_v = s->getValue( key ); if( !enabled_v.isNull() ) { m->setEnabled( enabled_v.toBool() ); } else { m->setEnabled( true ); } } } } //namespace ugene-1.9.8/src/plugins/cuda_support/src/CudaSupportSettingsController.cpp0000644000175000017500000001300311651544321025622 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include #include #include #include #include #include #include "CudaSupportSettingsController.h" namespace U2 { CudaSupportSettingsPageController::CudaSupportSettingsPageController( const QString & _displayMsg, QObject * p /* = 0 */ ) : AppSettingsGUIPageController( tr("CUDA"), CudaSupportSettingsPageId, p ), displayMsg(_displayMsg) {} AppSettingsGUIPageState * CudaSupportSettingsPageController::getSavedState() { QList registeredGpus = AppContext::getCudaGpuRegistry()->getRegisteredGpus(); CudaSupportSettingsPageState * s = new CudaSupportSettingsPageState( registeredGpus.size() ); for( int i = 0, end = s->enabledGpus.size(); i < end; ++i ) { s->enabledGpus[i] = registeredGpus.at(i)->isEnabled(); } return s; } void CudaSupportSettingsPageController::saveState( AppSettingsGUIPageState * _s ) { QList registeredGpus = AppContext::getCudaGpuRegistry()->getRegisteredGpus(); CudaSupportSettingsPageState * s = qobject_cast(_s); //saving state of enabled/disabled GPUs into registry for( int i = 0, end = s->enabledGpus.size(); i < end; ++i ) { registeredGpus[i]->setEnabled( s->enabledGpus[i] ); } //increasing/decreasing maxuse of according resource int totalEnabled = s->enabledGpus.count(true); AppResource * gpuResource = AppResourcePool::instance()->getResource( RESOURCE_CUDA_GPU ); if( gpuResource ) { gpuResource->maxUse = totalEnabled; } //else - resource was not registered, nothing to do. } AppSettingsGUIPageWidget * CudaSupportSettingsPageController::createWidget( AppSettingsGUIPageState* state ) { CudaSupportSettingsPageWidget * w = new CudaSupportSettingsPageWidget(displayMsg, this); w->setState(state); return w; } CudaSupportSettingsPageState::CudaSupportSettingsPageState( int num_gpus ) { assert( num_gpus >= 0 ); enabledGpus.resize( num_gpus ); } const static char * gpusDiscoveredText = "The following CUDA-enabled GPUs are detected.
    \ Check the GPUs to use for accelerating algorithms computations."; const static char * noGpusDiscoveredText = "No CUDA-enabled GPU detected."; CudaSupportSettingsPageWidget::CudaSupportSettingsPageWidget( const QString & _msg, CudaSupportSettingsPageController * /*ctrl*/ ) : onlyMsg(_msg){ if( !onlyMsg.isEmpty() ) { //just display the centered warning message QHBoxLayout* hLayout = new QHBoxLayout(this); QLabel * msgLabel = new QLabel( onlyMsg, this ); msgLabel->setAlignment( Qt::AlignLeft ); hLayout->setAlignment( Qt::AlignTop | Qt::AlignLeft); hLayout->addWidget(msgLabel); hLayout->addStretch(); setLayout(hLayout); } else { //everything is OK - adding info about all available GPUs QVBoxLayout * vLayout = new QVBoxLayout(this); QList gpus = AppContext::getCudaGpuRegistry()->getRegisteredGpus(); const QString & actualText = gpus.empty() ? tr(noGpusDiscoveredText) : tr(gpusDiscoveredText); QLabel * gpusDiscoveredLabel = new QLabel( actualText, this ); vLayout->addWidget( gpusDiscoveredLabel ); foreach( CudaGpuModel * m, gpus ) { vLayout->setAlignment( Qt::AlignLeft | Qt::AlignTop ); QHBoxLayout * hLayout = new QHBoxLayout(this); QString gpuText = m->getName() + " " + QString::number(m->getGlobalMemorySizeBytes() / (1024*1024)) + " Mb"; QCheckBox * check = new QCheckBox( gpuText, this ); check->setChecked(true); gpuEnableChecks.push_back(check); hLayout->addWidget(check); vLayout->addLayout( hLayout ); } setLayout(vLayout); } } void CudaSupportSettingsPageWidget::setState( AppSettingsGUIPageState * _state ) { CudaSupportSettingsPageState * state = qobject_cast(_state); assert( state->enabledGpus.size() == gpuEnableChecks.size() ); for( int i = 0, end = state->enabledGpus.size(); i < end; ++i ) { gpuEnableChecks.at(i)->setChecked( state->enabledGpus.at(i) ); } } AppSettingsGUIPageState* CudaSupportSettingsPageWidget::getState( QString & /*err*/ ) const { CudaSupportSettingsPageState * state = new CudaSupportSettingsPageState( gpuEnableChecks.size() ); assert( state->enabledGpus.size() == gpuEnableChecks.size() ); for( int i = 0, end = state->enabledGpus.size(); i < end; ++i ) { state->enabledGpus[i] = gpuEnableChecks.at(i)->isChecked(); } return state; } } //namespace ugene-1.9.8/src/plugins/cuda_support/cuda_support.pri0000644000175000017500000000037211651544321021522 0ustar ilyailya# include (cuda_support.pri) include( ../../ugene_globals.pri ) use_cuda() { INCLUDEPATH += $$UGENE_CUDA_INC_DIR PLUGIN_ID=cuda_support PLUGIN_NAME=CUDA support PLUGIN_VENDOR=Unipro include( ../../ugene_plugin_common.pri ) } #use_cudaugene-1.9.8/src/plugins/cuda_support/transl/0000755000175000017500000000000011651544321017577 5ustar ilyailyaugene-1.9.8/src/plugins/cuda_support/transl/russian.ts0000644000175000017500000001152211651544321021634 0ustar ilyailya U2::CudaSupportPlugin CUDA Support Поддержка CUDA Utility plugin for CUDA-enabled GPUs support Вспомогательный модуль для поддержки GPU с использованием технологии CUDA Invalid device No cuda-enabled devices found Unknown error Cannot load CUDA driver dynamic library. It is necessary to install latest Nvidia GPU driver for running GPU-accelerated algorithms on Nvidia hardware. Невозможно загрузить динамическую библиотеку драйвера CUDA Необходимо установить последний драйвер Nvidia GPU для запуска алгоритмов с использованием ускорения GPU на аппаратной основе Nvidia. Cannot load CUDA driver dynamic library.<p>It is necessary to install latest Nvidia GPU driver for running<br>GPU-accelerated algorithms on Nvidia hardware. Cannot obtain needed info about Nvidia GPU.<p>Consider reinstallation of GPU driver.<br>See CUDA Support plugin log for details. An error occurred while obtaining information about installed Nvidia GPUs.<br>See CUDA Support plugin log for details Loading CUDA driver library Cannot load driver library. Error while loading %1: Initializing CUDA Cannot resolve symbol Obtaining number of CUDA-enabled devices Cannot resolve symbol Registering CUDA-enabled GPU: %1, id: %2 U2::CudaSupportSettingsPageController CUDA Support Поддержка CUDA ugene-1.9.8/src/plugins/cuda_support/transl/czech.ts0000644000175000017500000001510311651544321021243 0ustar ilyailya Loading CUDA driver library Loading CUDA driver library Cannot load driver library. Error while loading %1: Cannot load driver library. Error while loading %1: Initializing CUDA Initializing CUDA Cannot resolve symbol Cannot resolve symbol Obtaining number of CUDA-enabled devices Obtaining number of CUDA-enabled devices Cannot resolve symbol Cannot resolve symbol Registering CUDA-enabled GPU: %1, id: %2 Registering CUDA-enabled GPU: %1, id: %2 U2::CudaSupportPlugin CUDA Support CUDA Support Utility plugin for CUDA-enabled GPUs support Utility plugin for CUDA-enabled GPUs support Invalid device Invalid device No cuda-enabled devices found No cuda-enabled devices found Unknown error Unknown error Cannot load CUDA driver dynamic library. It is necessary to install latest Nvidia GPU driver for running GPU-accelerated algorithms on Nvidia hardware. Cannot load CUDA driver dynamic library.It is necessary to install latest Nvidia GPU driver for running GPU-accelerated algorithms on Nvidia hardware. Cannot obtain needed info about Nvidia GPU. Consider reinstallation of GPU driver. See CUDA Support plugin log for details. Cannot obtain needed info about Nvidia GPU.Consider reinstallation of GPU driver. See CUDA Support plugin log for details. An error occured while obtaining information about installed Nvidia GPUs. See CUDA Support plugin log for details An error occured while obtaining information about installed Nvidia GPUs.See CUDA Support plugin log for details Cannot load CUDA driver dynamic library.<p>It is necessary to install latest Nvidia GPU driver for running<br>GPU-accelerated algorithms on Nvidia hardware. Cannot obtain needed info about Nvidia GPU.<p>Consider reinstallation of GPU driver.<br>See CUDA Support plugin log for details. An error occurred while obtaining information about installed Nvidia GPUs.<br>See CUDA Support plugin log for details Loading CUDA driver library Loading CUDA driver library Cannot load driver library. Error while loading %1: Cannot load driver library. Error while loading %1: Initializing CUDA Initializing CUDA Cannot resolve symbol Cannot resolve symbol Obtaining number of CUDA-enabled devices Obtaining number of CUDA-enabled devices Cannot resolve symbol Cannot resolve symbol Registering CUDA-enabled GPU: %1, id: %2 Registering CUDA-enabled GPU: %1, id: %2 U2::CudaSupportSettingsPageController CUDA Support CUDA Support ugene-1.9.8/src/plugins/cuda_support/transl/english.ts0000644000175000017500000001510311651544321021600 0ustar ilyailya Loading CUDA driver library Loading CUDA driver library Cannot load driver library. Error while loading %1: Cannot load driver library. Error while loading %1: Initializing CUDA Initializing CUDA Cannot resolve symbol Cannot resolve symbol Obtaining number of CUDA-enabled devices Obtaining number of CUDA-enabled devices Cannot resolve symbol Cannot resolve symbol Registering CUDA-enabled GPU: %1, id: %2 Registering CUDA-enabled GPU: %1, id: %2 U2::CudaSupportPlugin CUDA Support CUDA Support Utility plugin for CUDA-enabled GPUs support Utility plugin for CUDA-enabled GPUs support Invalid device Invalid device No cuda-enabled devices found No cuda-enabled devices found Unknown error Unknown error Cannot load CUDA driver dynamic library. It is necessary to install latest Nvidia GPU driver for running GPU-accelerated algorithms on Nvidia hardware. Cannot load CUDA driver dynamic library.It is necessary to install latest Nvidia GPU driver for running GPU-accelerated algorithms on Nvidia hardware. Cannot obtain needed info about Nvidia GPU. Consider reinstallation of GPU driver. See CUDA Support plugin log for details. Cannot obtain needed info about Nvidia GPU.Consider reinstallation of GPU driver. See CUDA Support plugin log for details. An error occured while obtaining information about installed Nvidia GPUs. See CUDA Support plugin log for details An error occured while obtaining information about installed Nvidia GPUs.See CUDA Support plugin log for details Cannot load CUDA driver dynamic library.<p>It is necessary to install latest Nvidia GPU driver for running<br>GPU-accelerated algorithms on Nvidia hardware. Cannot obtain needed info about Nvidia GPU.<p>Consider reinstallation of GPU driver.<br>See CUDA Support plugin log for details. An error occurred while obtaining information about installed Nvidia GPUs.<br>See CUDA Support plugin log for details Loading CUDA driver library Loading CUDA driver library Cannot load driver library. Error while loading %1: Cannot load driver library. Error while loading %1: Initializing CUDA Initializing CUDA Cannot resolve symbol Cannot resolve symbol Obtaining number of CUDA-enabled devices Obtaining number of CUDA-enabled devices Cannot resolve symbol Cannot resolve symbol Registering CUDA-enabled GPU: %1, id: %2 Registering CUDA-enabled GPU: %1, id: %2 U2::CudaSupportSettingsPageController CUDA Support CUDA Support ugene-1.9.8/src/plugins/annotator/0000755000175000017500000000000011651544321015571 5ustar ilyailyaugene-1.9.8/src/plugins/annotator/annotator.pro0000644000175000017500000000111411651544321020315 0ustar ilyailyainclude (annotator.pri) # Input HEADERS += src/AnnotatorPlugin.h \ src/AnnotatorTests.h \ src/CollocationsDialogController.h \ src/CollocationsSearchAlgorithm.h \ src/CollocationWorker.h FORMS += src/ui/FindAnnotationCollocationsDialog.ui SOURCES += src/AnnotatorPlugin.cpp \ src/AnnotatorTests.cpp \ src/CollocationsDialogController.cpp \ src/CollocationsSearchAlgorithm.cpp \ src/CollocationWorker.cpp RESOURCES += annotator.qrc TRANSLATIONS += transl/czech.ts transl/english.ts transl/russian.ts ugene-1.9.8/src/plugins/annotator/annotator.qrc0000644000175000017500000000015211651544321020303 0ustar ilyailya images/regions.png ugene-1.9.8/src/plugins/annotator/images/0000755000175000017500000000000011651544321017036 5ustar ilyailyaugene-1.9.8/src/plugins/annotator/images/regions.png0000644000175000017500000000132111651544321021207 0ustar ilyailyaPNG  IHDRatEXtSoftwareAdobe ImageReadyqe<sIDATxڜS]HSa~P\s4ۍ- Bh*uaQ E) "XwB]wJt' A1d9]99;,!{?}czU εs[$L¼RHA\#;]?Vrݽxgk^ Y;QCR~ff.KN;c-鴂049Svn4XE; H"j4>LLLߜC}9! ]ֹRhȐU| ǿqxEQm+O4~dU ,@ * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_ANNOTATOR_WORKER_H_ #define _U2_ANNOTATOR_WORKER_H_ #include #include #include #include "CollocationsSearchAlgorithm.h" namespace U2 { namespace LocalWorkflow { class CollocationPrompter; typedef PrompterBase CollocationPrompterBase; class CollocationPrompter : public CollocationPrompterBase { Q_OBJECT public: CollocationPrompter(Actor* p = 0) : CollocationPrompterBase(p) {} virtual ~CollocationPrompter() {} protected: QString composeRichDoc(); }; class CollocationWorker : public BaseWorker { Q_OBJECT public: CollocationWorker(Actor* a) : BaseWorker(a), input(NULL), output(NULL) {} virtual ~CollocationWorker() {} virtual void init() ; virtual bool isReady(); virtual Task* tick() ; virtual bool isDone() ; virtual void cleanup() {} private slots: void sl_taskFinished(); protected: CommunicationChannel *input, *output; QString resultName; QSet names; CollocationsAlgorithmSettings cfg; }; class CollocationWorkerFactory : public DomainFactory { public: static const QString ACTOR_ID; static void init(); CollocationWorkerFactory() : DomainFactory(ACTOR_ID) {} virtual ~CollocationWorkerFactory() {} virtual Worker* createWorker(Actor* a) {return new CollocationWorker(a);} }; }//Workflow namespace }//U2 namespace #endif ugene-1.9.8/src/plugins/annotator/src/CollocationsDialogController.cpp0000644000175000017500000003000211651544321024674 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "CollocationsDialogController.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include namespace U2 { class DNASequenceObject; //TODO: support results separation on complement and direct strands CollocationsDialogController::CollocationsDialogController(QStringList _names, ADVSequenceObjectContext* _ctx) : allNames(_names), ctx(_ctx) { task = NULL; qSort(allNames); setupUi(this); QStringList list; list.append(tr("click_to_add_new_annotation")); QTreeWidgetItem* item = new QTreeWidgetItem(annotationsTree, list); plusButton = new QToolButton(annotationsTree); plusButton->setText("+"); annotationsTree->addTopLevelItem(item); annotationsTree->setItemWidget(item, 1, plusButton); int w = annotationsTree->minimumWidth(); annotationsTree->setColumnWidth(1, 20); annotationsTree->setColumnWidth(0, w - 30); annotationsTree->setUniformRowHeights(true); connect(plusButton, SIGNAL(clicked()), SLOT(sl_plusClicked())); connect(searchButton, SIGNAL(clicked()), SLOT(sl_searchClicked())); connect(cancelButton, SIGNAL(clicked()), SLOT(sl_cancelClicked())); connect(clearResultsButton, SIGNAL(clicked()), SLOT(sl_clearClicked())); connect(saveResultsButton, SIGNAL(clicked()), SLOT(sl_saveClicked())); connect(resultsList, SIGNAL(itemActivated(QListWidgetItem*)), SLOT(sl_onResultActivated(QListWidgetItem*))); timer = new QTimer(this); connect(AppContext::getTaskScheduler(), SIGNAL(si_stateChanged(Task*)), SLOT(sl_onTaskFinished(Task*))); connect(timer, SIGNAL(timeout()), SLOT(sl_onTimer())); updateState(); setWindowIcon(QIcon(":/ugene/images/ugene_16.png")); } void CollocationsDialogController::updateState() { bool hasActiveTask = task!=NULL; searchButton->setEnabled(!hasActiveTask); bool readyToSearch = usedNames.size() >= 2; searchButton->setEnabled(!hasActiveTask && readyToSearch); saveResultsButton->setEnabled(!hasActiveTask && resultsList->count() > 0); clearResultsButton->setEnabled(!hasActiveTask && resultsList->count() > 0); cancelButton->setText(hasActiveTask ? tr("stop") : tr("cancel")); updateStatus(); } void CollocationsDialogController::updateStatus() { if (task!=NULL) { statusBar->setText(tr("searching__found_%1_items_progress_%2").arg(resultsList->count()).arg(task->getProgress())); } else if (resultsList->count() > 0) { statusBar->setText(tr("found_%1_items").arg(resultsList->count())); } else { statusBar->setText(searchButton->isEnabled() ? tr("ready") : tr("select_annotations")); } } void CollocationsDialogController::sl_plusClicked() { if (task != NULL) { return; } QMenu m; AnnotationSettingsRegistry* asr = AppContext::getAnnotationsSettingsRegistry(); foreach(const QString& name, allNames) { if (usedNames.contains(name)) { continue; } QColor c = asr->getAnnotationSettings(name)->color; QAction* a = m.addAction(GUIUtils::createSquareIcon(c, 10), name, this, SLOT(sl_addName())); assert(a->parent() == &m); Q_UNUSED(a); } if (m.isEmpty()) { m.addAction(tr("no_more_annotations_left")); } m.exec(QCursor::pos()); } void CollocationsDialogController::sl_addName() { QString name = ((QAction*)sender())->text(); assert(allNames.contains(name)); assert(!usedNames.contains(name)); usedNames.insert(name); AnnotationSettingsRegistry* asr = AppContext::getAnnotationsSettingsRegistry(); QColor c = asr->getAnnotationSettings(name)->color; QTreeWidgetItem* item = new QTreeWidgetItem(); item->setText(0, name); item->setIcon(0, GUIUtils::createSquareIcon(c, 10)); QToolButton* minusButton = new QToolButton(annotationsTree); minusButton->setMinimumSize(plusButton->size()); minusButton->setText("-"); minusButton->setObjectName(name); annotationsTree->insertTopLevelItem(annotationsTree->topLevelItemCount()-1, item); annotationsTree->setItemWidget(item, 1, minusButton); connect(minusButton, SIGNAL(clicked()), SLOT(sl_minusClicked())); updateState(); } void CollocationsDialogController::sl_minusClicked() { if (task != NULL) { return; } QObject* o = sender(); QString name = o->objectName(); assert(usedNames.contains(name)); usedNames.remove(name); for (int i=0, n = annotationsTree->topLevelItemCount(); itopLevelItem(i); if (item->text(0) == name) { annotationsTree->takeTopLevelItem(i); delete item; break; } } updateState(); } /* static U2Region getRange(const QList& aObjects) { U2Region res; foreach(AnnotationTableObject* ao, aObjects) { foreach(Annotation*a, ao->getAnnotations()) { foreach(const U2Region& r, a->getLocation()) { res = U2Region::join(res, r); } } } return res; } */ void CollocationsDialogController::sl_searchClicked() { resultsList->clear(); assert(usedNames.size() >= 2); CollocationsAlgorithmSettings cfg; cfg.distance = regionSpin->value(); assert(task == NULL); const QList& aObjects = ctx->getAnnotationObjects().toList(); cfg.searchRegion = U2Region(0, ctx->getSequenceLen()); if (!wholeAnnotationsBox->isChecked()) { cfg.st = CollocationsAlgorithm::PartialSearch; } task = new CollocationSearchTask(aObjects, usedNames, cfg); AppContext::getTaskScheduler()->registerTopLevelTask(task); timer->start(400); updateState(); } void CollocationsDialogController::sl_cancelClicked() { reject(); } void CollocationsDialogController::sl_clearClicked() { resultsList->clear(); updateState(); } void CollocationsDialogController::sl_saveClicked() { assert(resultsList->count() > 0); CreateAnnotationModel m; m.sequenceObjectRef = ctx->getSequenceGObject(); m.hideLocation = true; m.sequenceLen = ctx->getSequenceObject()->getSequenceLen(); CreateAnnotationDialog d(this, m); int rc = d.exec(); if (rc != QDialog::Accepted) { return; } QList list; for (int i=0, n = resultsList->count(); i(resultsList->item(i)); SharedAnnotationData data = m.data; data->location->regions.append(item->r); data->setStrand(U2Strand::Direct); list.append(data); } ADVCreateAnnotationsTask* t = new ADVCreateAnnotationsTask(ctx->getAnnotatedDNAView(), m.getAnnotationObject(), m.groupName, list); AppContext::getTaskScheduler()->registerTopLevelTask(t); } void CollocationsDialogController::reject() { if (task!=NULL) { task->cancel(); return; } QDialog::reject(); } void CollocationsDialogController::sl_onTimer() { importResults(); updateState(); } void CollocationsDialogController::sl_onTaskFinished(Task* t) { if (t != task || t->getState()!= Task::State_Finished) { return; } importResults(); task = NULL; updateState(); timer->stop(); } void CollocationsDialogController::importResults() { if (task == NULL) { return; } QVector newResults = task->popResults(); foreach(const U2Region& r, newResults) { CDCResultItem* item = new CDCResultItem(r); bool inserted = false; for(int i=0, n = resultsList->count(); i(resultsList->item(i)); assert(!tmp->r.contains(r) && !r.contains(tmp->r)); if (tmp->r.startPos > r.startPos) { resultsList->insertItem(i, item); inserted = true; } } if (!inserted) { resultsList->addItem(item); } } } void CollocationsDialogController::sl_onResultActivated(QListWidgetItem * item) { assert(item!=NULL); CDCResultItem* ri = static_cast(item); Q_UNUSED(ri); //todo: add to selection? //ctx->getPanView()->setVisibleRange(ri->r); //ctx->getDetView()->setCenterPos(ri->r.startPos); } CDCResultItem::CDCResultItem(const U2Region& _r) : r(_r) { setText(QString("[%1, %2]").arg(QString::number(r.startPos+1)).arg(r.endPos())); } ////////////////////////////////////////////////////////////////////////// // task CollocationSearchTask::CollocationSearchTask(const QList &table, const QSet& names, const CollocationsAlgorithmSettings& cfg) : Task(tr("collocation_search_task"), TaskFlag_None), cfg(cfg) { GCOUNTER(cvar, tvar, "CollocationSearchTask"); assert(cfg.distance >= 0); assert(!names.isEmpty()); foreach(const QString& name, names) { getItem(name); } foreach(AnnotationTableObject* ao, table) { foreach(Annotation* a, ao->getAnnotations()) { const QString& name = a->getAnnotationName(); if (names.contains(name)) { CollocationsAlgorithmItem& item = getItem(name); foreach(const U2Region& r, a->getRegions()) { if (cfg.searchRegion.intersects(r)) { item.regions.append(r); } } } } } } CollocationSearchTask::CollocationSearchTask(const QList &table, const QSet& names, const CollocationsAlgorithmSettings& cfg) : Task(tr("collocation_search_task"), TaskFlag_None), cfg(cfg) { assert(cfg.distance >= 0); assert(!names.isEmpty()); foreach(const QString& name, names) { getItem(name); } foreach(SharedAnnotationData a, table) { const QString& name = a->name; if (names.contains(name)) { CollocationsAlgorithmItem& item = getItem(name); foreach(const U2Region& r, a->location->regions) { if (cfg.searchRegion.intersects(r)) { item.regions.append(r); } } } } } CollocationsAlgorithmItem& CollocationSearchTask::getItem(const QString& name) { if (!items.contains(name)) { items[name] = CollocationsAlgorithmItem(name); } return items[name]; } void CollocationSearchTask::run() { CollocationsAlgorithm::find(items.values(), stateInfo, this, cfg); } void CollocationSearchTask::onResult(const U2Region& r) { lock.lock(); results.append(r); lock.unlock(); } QVector CollocationSearchTask::popResults() { lock.lock(); QVector tmp = results; results.clear(); lock.unlock(); return tmp; } }//namespace ugene-1.9.8/src/plugins/annotator/src/AnnotatorTests.cpp0000644000175000017500000001356511651544321022066 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "AnnotatorTests.h" #include #include #include #include #include #include #include #include /* TRANSLATOR U2::GTest */ namespace U2 { #define GROUPS_ATTR "groups" #define REGION_SIZE_ATTR "region_size" #define FIT_TO_REGION_ATTR "is_fit_to_region" #define DOC_ATTR "doc" #define SEQ_ATTR "seq" #define EXPECTED_RESULTS_ATTR "expected_results" void GTest_AnnotatorSearch::init(XMLTestFormat *tf, const QDomElement& el) { Q_UNUSED(tf); docName = el.attribute(DOC_ATTR); if (docName.isEmpty()) { failMissingValue(DOC_ATTR); return; } seqName = el.attribute(SEQ_ATTR); if (seqName.isEmpty()) { failMissingValue(SEQ_ATTR); return; } QString groups = el.attribute(GROUPS_ATTR); if (groups.isEmpty()) { failMissingValue(GROUPS_ATTR); return; } groupsToSearch = (groups.split(QRegExp("\\,"))).toSet(); //may be QRegExp("\\,") QString expected = el.attribute(EXPECTED_RESULTS_ATTR); if (!expected.isEmpty()) { QStringList expectedList = expected.split(QRegExp("\\,")); //may be QRegExp("\\,") foreach(QString region, expectedList) { QStringList bounds = region.split(QRegExp("\\..")); if (bounds.size() != 2) { stateInfo.setError( QString("wrong value for %1").arg(EXPECTED_RESULTS_ATTR) ); return; } bool startOk, finishOk; int start = bounds.first().toInt(&startOk), finish = bounds.last().toInt(&finishOk); if (startOk && finishOk != true) { stateInfo.setError( QString("wrong value for %1").arg(EXPECTED_RESULTS_ATTR) ); return; } start--; expectedResults.append(U2Region(start, finish - start)); } } QString strRegionSize = el.attribute(REGION_SIZE_ATTR); if (strRegionSize.isEmpty()) { failMissingValue(REGION_SIZE_ATTR); return; } bool isOk = false; regionSize = strRegionSize.toInt(&isOk); if (!isOk) { stateInfo.setError( QString("Unable to convert. Value wrong %1").arg(REGION_SIZE_ATTR) ); return; } QString strFitToRegion = el.attribute(FIT_TO_REGION_ATTR); if (strRegionSize.isEmpty()) { failMissingValue(FIT_TO_REGION_ATTR); return; } if (strFitToRegion == "true") { st = CollocationsAlgorithm::NormalSearch; } else if (strFitToRegion == "false"){ st = CollocationsAlgorithm::PartialSearch; } else { stateInfo.setError( QString("Unable to convert. Value wrong %1").arg(FIT_TO_REGION_ATTR) ); return; } } void GTest_AnnotatorSearch::prepare() { /**/ searchTask = NULL; Document* doc = getContext(this, docName); if (doc == NULL) { stateInfo.setError( QString("context not found %1").arg(docName) ); return; } QList list = doc->findGObjectByType(GObjectTypes::SEQUENCE); if (list.size() == 0) { stateInfo.setError( QString("container of object with type \"%1\" is empty").arg(GObjectTypes::SEQUENCE) ); return; } GObject *obj = list.first(); if(obj==NULL){ stateInfo.setError( QString("object with type \"%1\" not found").arg(GObjectTypes::SEQUENCE) ); return; } assert(obj!=NULL); DNASequenceObject * mySequence = qobject_cast(obj); if(mySequence==NULL){ stateInfo.setError( QString("error can't cast to sequence from GObject") ); return; } AnnotationTableObject* ao = getContext(this, seqName); if(ao==NULL){ stateInfo.setError( QString("context not found %1").arg(seqName) ); return; } QList aoList; aoList.append(ao); CollocationsAlgorithmSettings cfg; cfg.distance = regionSize; cfg.searchRegion = mySequence->getSequenceRange(); cfg.st = st; searchTask = new CollocationSearchTask(aoList, groupsToSearch, cfg); addSubTask(searchTask); } Task::ReportResult GTest_AnnotatorSearch::report() { if(searchTask != NULL){ if (!searchTask->hasError()){ QVector actualResults = searchTask->popResults(); int actualSize = actualResults.size(), expectedSize = expectedResults.size(); if (actualSize != expectedSize) { stateInfo.setError( QString("Expected and Actual lists of regions are different: %1 %2").arg(expectedSize).arg(actualSize) ); return ReportResult_Finished; } qSort(actualResults); qSort(expectedResults); if (actualResults != expectedResults) { stateInfo.setError( QString("One of the expected regions not found in results").arg(expectedSize).arg(actualSize) ); } } } return ReportResult_Finished; } } //namespace ugene-1.9.8/src/plugins/annotator/src/CollocationsDialogController.h0000644000175000017500000000626711651544321024361 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_COLLOCATION_DIALOG_CONTROLLER_H_ #define _U2_COLLOCATION_DIALOG_CONTROLLER_H_ #include "CollocationsSearchAlgorithm.h" #include #include #include #include //#include "gobjects/AnnotationTableObject.h" #include #include #include #include namespace U2 { class ADVSequenceObjectContext; class CollocationSearchTask; class AnnotationTableObject; //TODO: listen for allocation add/remove to the view class CollocationsDialogController : public QDialog, Ui_FindAnnotationCollocationsDialog { Q_OBJECT public: CollocationsDialogController(QStringList names, ADVSequenceObjectContext* ctx); public slots: void reject(); private slots: void sl_searchClicked(); void sl_cancelClicked(); void sl_plusClicked(); void sl_minusClicked(); void sl_addName(); void sl_onTaskFinished(Task*); void sl_onTimer(); void sl_onResultActivated(QListWidgetItem * item ); void sl_clearClicked(); void sl_saveClicked(); private: void updateState(); void updateStatus(); void importResults(); QStringList allNames; QSet usedNames; ADVSequenceObjectContext* ctx; QToolButton* plusButton; CollocationSearchTask* task; QTimer* timer; }; class CDCResultItem : public QListWidgetItem { public: CDCResultItem(const U2Region& _r); U2Region r; }; ////////////////////////////////////////////////////////////////////////// // task class CollocationSearchTask : public Task , public CollocationsAlgorithmListener{ Q_OBJECT public: CollocationSearchTask(const QList &table, const QSet& names, const CollocationsAlgorithmSettings& cfg); CollocationSearchTask(const QList &table, const QSet& names, const CollocationsAlgorithmSettings& cfg); void run(); QVector popResults(); virtual void onResult(const U2Region& r); private: CollocationsAlgorithmItem& getItem(const QString& name); QMap items; CollocationsAlgorithmSettings cfg; QVector results; QMutex lock; }; }//namespace #endif ugene-1.9.8/src/plugins/annotator/src/AnnotatorPlugin.h0000644000175000017500000000307311651544321021660 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_ANNOTATION_COLLOCATOR_PLUGIN_H_ #define _U2_ANNOTATION_COLLOCATOR_PLUGIN_H_ #include #include #include #include namespace U2 { class XMLTestFactory; class AnnotatorPlugin : public Plugin { Q_OBJECT public: AnnotatorPlugin(); private: GObjectViewWindowContext* viewCtx; }; class AnnotatorViewContext: public GObjectViewWindowContext { Q_OBJECT public: AnnotatorViewContext(QObject* p); protected slots: void sl_showCollocationDialog(); protected: virtual void initViewContext(GObjectView* view); }; class AnnotatorTests { public: static QList createTestFactories(); }; } //namespace #endif ugene-1.9.8/src/plugins/annotator/src/ui/0000755000175000017500000000000011651544321016775 5ustar ilyailyaugene-1.9.8/src/plugins/annotator/src/ui/FindAnnotationCollocationsDialog.ui0000644000175000017500000001441411651544321025745 0ustar ilyailya FindAnnotationCollocationsDialog 0 0 656 434 dialog_tittle 300 0 false false true 2 1 2 Qt::Vertical 20 40 300 0 region_size_label 100 0 Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter 10 100000000 1000 Qt::Horizontal 40 20 search_button Qt::Horizontal 40 20 save_annotations_button clear_results_button whole annotations Qt::Horizontal 228 20 cancel_button 100 0 ugene-1.9.8/src/plugins/annotator/src/AnnotatorTests.h0000644000175000017500000000320711651544321021523 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_ANNOTATOR_TESTS_H_ #define _U2_ANNOTATOR_TESTS_H_ #include #include #include #include #include #include #include "CollocationsDialogController.h" namespace U2 { class GTest_AnnotatorSearch : public GTest { Q_OBJECT public: SIMPLE_XML_TEST_BODY_WITH_FACTORY(GTest_AnnotatorSearch, "plugin_dna-annotator-search"); void prepare(); Task::ReportResult report(); private: QString seqName; QString docName; QString resultDocContextName; QSet groupsToSearch; int regionSize; CollocationsAlgorithm::SearchType st; CollocationSearchTask *searchTask; QVector expectedResults; }; } //namespace #endif ugene-1.9.8/src/plugins/annotator/src/AnnotatorPlugin.cpp0000644000175000017500000000735411651544321022221 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "AnnotatorPlugin.h" #include "CollocationsDialogController.h" #include "AnnotatorTests.h" #include #include #include #include #include #include #include #include #include #include #include #include #include "CollocationWorker.h" namespace U2 { extern "C" Q_DECL_EXPORT Plugin* U2_PLUGIN_INIT_FUNC() { AnnotatorPlugin * plug = new AnnotatorPlugin(); return plug; } AnnotatorPlugin::AnnotatorPlugin() : Plugin(tr("dna_annotator_plugin"), tr("dna_annotator_plugin_desc")), viewCtx(NULL) { if (AppContext::getMainWindow()) { viewCtx = new AnnotatorViewContext(this); viewCtx->init(); } LocalWorkflow::CollocationWorkerFactory::init(); //Annotator test GTestFormatRegistry* tfr = AppContext::getTestFramework()->getTestFormatRegistry(); XMLTestFormat *xmlTestFormat = qobject_cast(tfr->findFormat("XML")); assert(xmlTestFormat!=NULL); GAutoDeleteList* l = new GAutoDeleteList(this); l->qlist = AnnotatorTests::createTestFactories(); foreach(XMLTestFactory* f, l->qlist) { bool res = xmlTestFormat->registerTestFactory(f); Q_UNUSED(res); assert(res); } } AnnotatorViewContext::AnnotatorViewContext(QObject* p) : GObjectViewWindowContext(p, ANNOTATED_DNA_VIEW_FACTORY_ID) { } void AnnotatorViewContext::initViewContext(GObjectView* v) { AnnotatedDNAView* av = qobject_cast(v); ADVGlobalAction* a = new ADVGlobalAction(av, QIcon(":annotator/images/regions.png"), tr("Find annotated regions..."), 30); connect(a, SIGNAL(triggered()), SLOT(sl_showCollocationDialog())); } void AnnotatorViewContext::sl_showCollocationDialog() { QAction* a = (QAction*)sender(); GObjectViewAction* viewAction = qobject_cast(a); AnnotatedDNAView* av = qobject_cast(viewAction->getObjectView()); assert(av); QSet allNames; foreach(AnnotationTableObject* ao, av->getAnnotationObjects()) { foreach(Annotation* a, ao->getAnnotations()) { allNames.insert(a->getAnnotationName()); } } if (allNames.isEmpty()) { QMessageBox::warning(av->getWidget(), tr("warning"),tr("no_annotations_found")); return; } ADVSequenceObjectContext* seqCtx = av->getSequenceInFocus(); if (seqCtx == NULL) { return; } CollocationsDialogController d(allNames.toList(), seqCtx); d.exec(); } QList AnnotatorTests::createTestFactories() { QList res; res.append(GTest_AnnotatorSearch::createFactory()); return res; } }//namespace ugene-1.9.8/src/plugins/annotator/src/CollocationsSearchAlgorithm.h0000644000175000017500000000442111651544321024160 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_COLLOCATION_SEARCH_ALGORITHM_H_ #define _U2_COLLOCATION_SEARCH_ALGORITHM_H_ #include #include namespace U2 { class CollocationsAlgorithmListener { public: virtual ~CollocationsAlgorithmListener(){}; virtual void onResult(const U2Region& r) = 0; }; class CollocationsAlgorithmItem { public: CollocationsAlgorithmItem(){} CollocationsAlgorithmItem(const QString& _name) : name(_name){} QString name; QVector regions; }; class CollocationsAlgorithmSettings; class CollocationsAlgorithm { public: enum SearchType {NormalSearch, PartialSearch}; static void find(const QList& items, TaskStateInfo& si, CollocationsAlgorithmListener* l, const CollocationsAlgorithmSettings& cfg); private: static void findN(const QList& items, TaskStateInfo& si, CollocationsAlgorithmListener* l, const U2Region& searchRegion, qint64 distance); static void findP(const QList& items, TaskStateInfo& si, CollocationsAlgorithmListener* l, const U2Region& searchRegion, qint64 distance); }; class CollocationsAlgorithmSettings { public: CollocationsAlgorithmSettings() : distance(-1), st(CollocationsAlgorithm::NormalSearch) {} U2Region searchRegion; int distance; CollocationsAlgorithm::SearchType st; }; } //namespace U2 #endif ugene-1.9.8/src/plugins/annotator/src/CollocationWorker.cpp0000644000175000017500000002431611651544321022532 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "CollocationWorker.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "CollocationsSearchAlgorithm.h" #include "CollocationsDialogController.h" /* TRANSLATOR U2::LocalWorkflow::CollocationWorker */ namespace U2 { namespace LocalWorkflow { static const QString NAME_ATTR("result-name"); static const QString ANN_ATTR("annotations"); static const QString LEN_ATTR("region-size"); static const QString FIT_ATTR("must-fit"); const QString SEQ_SLOT = BaseSlots::DNA_SEQUENCE_SLOT().getId(); const QString FEATURE_TABLE_SLOT = BaseSlots::ANNOTATION_TABLE_SLOT().getId(); const QString CollocationWorkerFactory::ACTOR_ID("collocated-annotation-search"); class CollocationValidator : public ConfigurationValidator { public: virtual bool validate(const Configuration* cfg, QStringList& output) const { QString annotations = cfg->getParameter(ANN_ATTR)->getAttributeValue(); QSet names = QSet::fromList(annotations.split(QRegExp("\\W+"), QString::SkipEmptyParts)); if (names.size() < 2) { output.append(CollocationWorker::tr("At least 2 annotations are required for collocation search.")); return false; } return true; } }; void CollocationWorkerFactory::init() { QMap m; { //Descriptor sd(DNA_SEQUENCE_SLOT, CollocationWorker::tr("sequence-slot"), CollocationWorker::tr("seq-slot-doc")); //Descriptor fd(ANNOTATION_TABLE_SLOT, CollocationWorker::tr("feature-table"), CollocationWorker::tr("feature-table-doc")); m[BaseSlots::DNA_SEQUENCE_SLOT()] = BaseTypes::DNA_SEQUENCE_TYPE(); m[BaseSlots::ANNOTATION_TABLE_SLOT()] = BaseTypes::ANNOTATION_TABLE_LIST_TYPE(); } DataTypePtr inSet(new MapDataType(Descriptor("regioned.sequence"), m)); DataTypeRegistry* dr = WorkflowEnv::getDataTypeRegistry(); assert(dr); dr->registerEntry(inSet); QList p; QList a; p << new PortDescriptor(Descriptor(BasePorts::IN_SEQ_PORT_ID(), CollocationWorker::tr("Input data"), CollocationWorker::tr("An input sequence and a set of annotations to search in.")), inSet, true /*input*/); QMap outM; outM[BaseSlots::ANNOTATION_TABLE_SLOT()] = BaseTypes::ANNOTATION_TABLE_TYPE(); p << new PortDescriptor(Descriptor(BasePorts::OUT_ANNOTATIONS_PORT_ID(), CollocationWorker::tr("Group annotations"), CollocationWorker::tr("Annotated regions containing found collocations.")), DataTypePtr(new MapDataType(Descriptor("collocation.annotations"), outM)), false /*input*/, true/*multi*/); { //U2Region searchRegion; Descriptor nd(NAME_ATTR, CollocationWorker::tr("Result annotation"), CollocationWorker::tr("Name of the result annotations to mark found collocations")); Descriptor ad(ANN_ATTR, CollocationWorker::tr("Group of annotations"), CollocationWorker::tr("A list of annotation names to search. Found regions will contain all the named annotations.")); Descriptor ld(LEN_ATTR, CollocationWorker::tr("Region size"), CollocationWorker::tr("Effectively this is the maximum allowed distance between the interesting annotations in a group")); Descriptor fd(FIT_ATTR, CollocationWorker::tr("Must fit into region"), CollocationWorker::tr("Whether the interesting annotations should entirely fit into the specified region to form a group")); a << new Attribute(nd, BaseTypes::STRING_TYPE(), true, QVariant("misc_feature")); a << new Attribute(ad, BaseTypes::STRING_TYPE(), true); a << new Attribute(ld, BaseTypes::NUM_TYPE(), false, QVariant(1000)); a << new Attribute(fd, BaseTypes::BOOL_TYPE(), false, QVariant(false)); } Descriptor desc(ACTOR_ID, CollocationWorker::tr("Collocation search"), CollocationWorker::tr("Finds groups of specified annotations in each supplied set of annotations, stores found regions as annotations.")); ActorPrototype* proto = new IntegralBusActorPrototype(desc, p, a); QMap delegates; QVariantMap lenMap; lenMap["minimum"] = QVariant(0); lenMap["maximum"] = QVariant(INT_MAX); delegates[LEN_ATTR] = new SpinBoxDelegate(lenMap); proto->setEditor(new DelegateEditor(delegates)); proto->setValidator(new CollocationValidator()); proto->setIconPath(":annotator/images/regions.png"); proto->setPrompter(new CollocationPrompter()); WorkflowEnv::getProtoRegistry()->registerProto(BaseActorCategories::CATEGORY_BASIC(), proto); DomainFactory* localDomain = WorkflowEnv::getDomainRegistry()->getById(LocalDomainFactory::ID); localDomain->registerEntry(new CollocationWorkerFactory()); } QString CollocationPrompter::composeRichDoc() { IntegralBusPort* input = qobject_cast(target->getPort(BasePorts::IN_SEQ_PORT_ID())); Actor* seqProducer = input->getProducer(SEQ_SLOT); QString seqName = seqProducer ? tr(" sequence from %1").arg(seqProducer->getLabel()) : ""; QString annName = getProducers(BasePorts::IN_SEQ_PORT_ID(), FEATURE_TABLE_SLOT); if (!annName.isEmpty()) { annName = tr(" set of annotations from %1").arg(annName); } QString data; if (seqName.isEmpty() && annName.isEmpty()) { //return ""+tr("unset")+""; } else if (!seqName.isEmpty() && !annName.isEmpty()) { data = tr("For each %1 and %2,").arg(seqName).arg(annName); } else { data = tr("For each %1%2,").arg(seqName).arg(annName); } QString annotations; QStringList names = annotations.split(QRegExp("\\W+"), QString::SkipEmptyParts).toSet().toList(); annotations = names.join(", "); if (annotations.isEmpty()) { annotations = getRequiredParam(ANN_ATTR); } annotations = getHyperlink(ANN_ATTR, annotations); int distance = getParameter(LEN_ATTR).toInt(); bool mode = getParameter(FIT_ATTR).toBool(); QString extra; if (mode) { extra = tr(" Annotations themselves may not span beyond the region."); } QString resultName = getHyperlink(NAME_ATTR, getRequiredParam(NAME_ATTR)); QString doc = tr("%1 look if %2 annotations appear collocated within same region of length %3.%4" "
    Output the list of found regions annotated as %5.") .arg(data) //sequence from Read Fasta 1 .arg(annotations) .arg(getHyperlink(LEN_ATTR, distance)) .arg(extra) .arg(resultName); return doc; } void CollocationWorker::init() { input = ports.value(BasePorts::IN_SEQ_PORT_ID()); output = ports.value(BasePorts::OUT_ANNOTATIONS_PORT_ID()); } bool CollocationWorker::isReady() { return (input && input->hasMessage()); } Task* CollocationWorker::tick() { Message inputMessage = getMessageAndSetupScriptValues(input); cfg.distance = actor->getParameter(LEN_ATTR)->getAttributeValue(); cfg.st = actor->getParameter(FIT_ATTR)->getAttributeValue() ? CollocationsAlgorithm::NormalSearch : CollocationsAlgorithm::PartialSearch; resultName = actor->getParameter(NAME_ATTR)->getAttributeValue(); QString annotations = actor->getParameter(ANN_ATTR)->getAttributeValue(); names = QSet::fromList(annotations.split(QRegExp("\\W+"), QString::SkipEmptyParts)); QVariantMap qm = inputMessage.getData().toMap(); DNASequence seq = qm.value(SEQ_SLOT).value(); QList atl = QVariantUtils::var2ftl(qm.value(FEATURE_TABLE_SLOT).toList()); if (!seq.isNull() && !atl.isEmpty()) { cfg.searchRegion.length = seq.length(); Task* t = new CollocationSearchTask(atl, names, cfg); connect(t, SIGNAL(si_stateChanged()), SLOT(sl_taskFinished())); return t; } else { // void tick output->put(Message(BaseTypes::ANNOTATION_TABLE_TYPE(), QVariant())); if (input->isEnded()) { output->setEnded(); } return NULL; } } void CollocationWorker::sl_taskFinished() { CollocationSearchTask* t = qobject_cast(sender()); if (t->getState() != Task::State_Finished) return; QVector res = t->popResults(); if (output) { QList list; foreach(U2Region r, res) { SharedAnnotationData data; data = new AnnotationData(); data->location->regions.append(r); data->setStrand(U2Strand::Direct); data->name = resultName; list.append(data); } QVariant v = qVariantFromValue >(list); output->put(Message(BaseTypes::ANNOTATION_TABLE_TYPE(), v)); if (input->isEnded()) { output->setEnded(); } algoLog.info(tr("Found %1 collocations").arg(res.size())); } } bool CollocationWorker::isDone() { return !input || input->isEnded(); } } //namespace LocalWorkflow } //namespace U2 ugene-1.9.8/src/plugins/annotator/src/CollocationsSearchAlgorithm.cpp0000644000175000017500000001704511651544321024521 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "CollocationsSearchAlgorithm.h" namespace U2 { void CollocationsAlgorithm::find(const QList& items, TaskStateInfo& si, CollocationsAlgorithmListener* l, const CollocationsAlgorithmSettings& cfg) { cfg.st == NormalSearch ? findN(items, si, l, cfg.searchRegion, cfg.distance) : findP(items, si, l, cfg.searchRegion, cfg.distance); } void CollocationsAlgorithm::findN(const QList& items, TaskStateInfo& si, CollocationsAlgorithmListener* l, const U2Region& searchRegion, qint64 distance) { //todo: progress qint64 i = searchRegion.endPos(); foreach(const CollocationsAlgorithmItem& item, items) { foreach(const U2Region& r, item.regions) { assert(searchRegion.contains(r)); i = qMin(i, r.startPos); } } if (i == searchRegion.endPos()) { return; } U2Region prevResult; do { U2Region res; U2Region currentRegion(i, qMin(i + distance, searchRegion.endPos()) - i); bool onResult = true; qint64 nextI = currentRegion.endPos(); foreach(const CollocationsAlgorithmItem& item, items) { bool foundItem = false; qint64 nextItemStart = currentRegion.endPos(); foreach(const U2Region& r, item.regions) { if (r.startPos > currentRegion.startPos) { nextItemStart = qMin(nextItemStart, r.startPos); } if (onResult && currentRegion.contains(r)) { foundItem = true; res = res.length == 0 ? r : U2Region::containingRegion(res, r); } } nextI = qMin(nextI, nextItemStart); onResult = onResult && foundItem; } if (onResult && res.startPos == i) { assert(res.length > 0); if (prevResult.contains(res)) { //nothing to do; } else { assert(!res.contains(prevResult) || prevResult.length == 0); assert(prevResult.endPos() < res.endPos()); l->onResult(res); prevResult = res; } } assert(nextI > i); i = nextI; si.progress = int(100*float(i - searchRegion.startPos)/searchRegion.length); } while (i + distance < searchRegion.endPos()); } void averagingRes(U2Region& res, const U2Region& min, const U2Region& max, int distance, const U2Region& searchRegion) { //? if (!min.intersects(max)) { res.startPos = min.endPos()-1; res.length = max.startPos - min.endPos() + 2; } else { res.startPos = max.startPos; res.length = min.endPos() - max.startPos; } int tmp = distance - res.length; res.startPos -= tmp*min.length/(max.length+min.length); if (res.startPos<0) res.startPos = 0; res.length = distance; if (res.endPos() > searchRegion.endPos()) { res.startPos -= (res.endPos()-searchRegion.endPos()); //res.len = (searchRegion.endPos() - res.startPos); } if (res.endPos() > max.endPos()) { res.startPos -= (res.endPos()-max.endPos()); } if (res.startPos<0) res.startPos = 0; } void CollocationsAlgorithm::findP(const QList& items, TaskStateInfo& si, CollocationsAlgorithmListener* l, const U2Region& searchRegion, qint64 distance) { //printf("partial_search!\n"); qint64 i = searchRegion.endPos(); foreach(const CollocationsAlgorithmItem& item, items) { foreach(const U2Region& r, item.regions) { assert(searchRegion.contains(r)); if (i > r.endPos()-1) { i = r.endPos()-1; } } } if (i == searchRegion.endPos()) { return; } U2Region prevResult; U2Region prevMax; do { U2Region res; U2Region currentRegion(i, qMin(i+distance, searchRegion.endPos()) - i); U2Region min, max; min.startPos = searchRegion.endPos() - 1; max.startPos = 0; bool onResult = true; qint64 nextI = currentRegion.endPos(); foreach(const CollocationsAlgorithmItem& item, items) { bool foundItem = false; qint64 nextItemEnd = searchRegion.endPos(); foreach(const U2Region& r, item.regions) { if (r.endPos() <= searchRegion.endPos() && r.endPos()-1 > currentRegion.startPos && nextItemEnd > r.endPos()-1) { nextItemEnd = r.endPos()-1; } if (onResult && currentRegion.intersects(r)) { foundItem = true; if (r.endPos() < min.endPos()) min = r; if (max < r) max = r; res = res.length == 0 ? r : U2Region::containingRegion(res, r); } } nextI = qMin(nextI, nextItemEnd); onResult = onResult && foundItem; } //error mb use list of prev included anno? // if (onResult && prevMax != max //!prevResult.contains(res) ) { prevResult = res; prevMax = max; if (res.length > distance) { //function res averaging //void averagingRes(U2Region& res, const U2Region& min, const U2Region& max, int distance) /* if (!min.intersects(max)) { res.startPos = min.endPos()-1; res.len = max.startPos - min.endPos() + 2; int tmp = distance - res.len; res.startPos -= tmp*min.len/(max.len+min.len); if (res.startPos<0) res.startPos = 0; res.len = distance; if (res.endPos() > searchRegion.endPos()) res.len = (searchRegion.endPos() - res.startPos); } else { res.startPos = max.startPos; res.len = min.endPos() - max.startPos; int tmp = distance - res.len; res.startPos -= tmp*min.len/(max.len+min.len); if (res.startPos<0) res.startPos = 0; res.len = distance; if (res.endPos() > searchRegion.endPos()) res.len = (searchRegion.endPos() - res.startPos); }*/ averagingRes(res, min, max, distance, searchRegion); } assert(res.length > 0); l->onResult(res); } assert(nextI > i); i = nextI; si.progress = int(100*float(i - searchRegion.startPos)/searchRegion.length); } while (i < searchRegion.endPos()); } }//namespace ugene-1.9.8/src/plugins/annotator/transl/0000755000175000017500000000000011651544321017074 5ustar ilyailyaugene-1.9.8/src/plugins/annotator/transl/russian.ts0000644000175000017500000003061411651544321021134 0ustar ilyailya FindAnnotationCollocationsDialog dialog_tittle Поиск сгруппировавнных аннотаций region_size_label Размер региона: search_button Искать save_annotations_button Сохранить как аннотации clear_results_button Сбросить результаты cancel_button Отменить 1 2 whole annotations Аннотации не должны пересекать регион U2::AnnotatorPlugin dna_annotator_plugin Поиск сгруппированных аннотаций dna_annotator_plugin_desc Поиск сгруппированных аннотаций U2::AnnotatorViewContext Find annotated regions... Найти сгруппированные аннотации... warning Информация no_annotations_found Ничего не нашли U2::CollocationSearchTask collocation_search_task Поиск сгруппированных аннотаций U2::CollocationsDialogController click_to_add_new_annotation << Кликните '+' чтобы добавить аннотацию >> stop Остановить cancel Отменить searching__found_%1_items_progress_%2 Сканируется последовательность, прогресс %2. Найдено %1 регионов. found_%1_items Найдено %1 ready Готов к поиску select_annotations Выберите аннотации no_more_annotations_left Аннотаций больше нет. U2::LocalWorkflow::CollocationPrompter sequence from <u>%1</u> последовательности из <u>%1</u> set of annotations from <u>%1</u> набора аннотаций из <u>%1</u> For each %1 and %2, Для каждых %1 и %2, For each %1%2, Для каждого %1%2, Annotations themselves may not span beyond the region. целиком %1 look if <u>%2</u> annotations appear collocated within same region of length <u>%3</u>.%4<br>Output the list of found regions annotated as <u>%5</u>. %1 искать группы аннотаций <u>%2</u> расположенные <u>%4</u> внутри регионов не длиннее <u>%3</u>.<br>Выдать список найденных групп в виде аннотаций "<u>%5</u>". U2::LocalWorkflow::CollocationWorker Found %1 collocations Найдено %1 групп Group annotations Найденные регионы Result annotation Имя аннотации Group of annotations Аннотации в группе Region size Размер региона Must fit into region Компактные группы Collocation search Поиск групп аннотаций At least 2 annotations are required for collocation search. Необходимо указать не менее 2-х различных имён аннотаций для поиска. Annotated regions containing found collocations. Список аннотаций отмечающих найденные группы аннотаций. Name of the result annotations to mark found collocations Имя результирующих аннотаций отмечающих найденные группы A list of annotation names to search. Found regions will contain all the named annotations. Список имён интересующих аннотаций в группе. Ищутся регионы содержащие все указанные аннотации. Effectively this is the maximum allowed distance between the interesting annotations in a group Фактически, это максимальная допустимая дистанция между аннотациями в одной группе. Whether the interesting annotations should entirely fit into the specified region to form a group Аннотации в группе должны целиком входить в указанный регион - т.е. дистанция в группе считается по внешним границам аннотаций. Finds groups of specified annotations in each supplied set of annotations, stores found regions as annotations. Поиск сгруппированных аннотаций. Ищутся регионы последовательности, содержащие все аннотации из заданного списка, расположенные друг от друга на расстоянии не более заданного. Input data Входные данные An input sequence and a set of annotations to search in. Входные последовательность и набор аннотированных регионов для поиска. ugene-1.9.8/src/plugins/annotator/transl/czech.ts0000644000175000017500000002363011651544321020544 0ustar ilyailya FindAnnotationCollocationsDialog dialog_tittle Find groups of annotated regions region_size_label Region size: search_button Search save_annotations_button Save regions as annotations.. clear_results_button Clear resutls cancel_button Cancel 1 2 whole annotations Annotation must fit into region U2::AnnotatorPlugin dna_annotator_plugin DNA Annotator dna_annotator_plugin_desc This plugin contains routines to manipulate and search DNA sequence annotations U2::AnnotatorViewContext Find annotated regions... Find annotated regions... warning Warning! no_annotations_found No annotations found! U2::CollocationSearchTask collocation_search_task Search for annotated regions U2::CollocationsDialogController click_to_add_new_annotation <<click '+' button to add new annotation>> stop Stop cancel Cancel searching__found_%1_items_progress_%2 Searching... found %1 regions. Progress: %2% found_%1_items Found %1 regions ready Ready select_annotations Select annotation names to search no_more_annotations_left No annotations left U2::LocalWorkflow::CollocationPrompter sequence from <u>%1</u> set of annotations from <u>%1</u> For each %1 and %2, For each %1%2, Annotations themselves may not span beyond the region. %1 look if <u>%2</u> annotations appear collocated within same region of length <u>%3</u>.%4<br>Output the list of found regions annotated as <u>%5</u>. U2::LocalWorkflow::CollocationWorker Found %1 collocations Group annotations Result annotation Group of annotations Region size Must fit into region Collocation search At least 2 annotations are required for collocation search. Annotated regions containing found collocations. Name of the result annotations to mark found collocations A list of annotation names to search. Found regions will contain all the named annotations. Effectively this is the maximum allowed distance between the interesting annotations in a group Whether the interesting annotations should entirely fit into the specified region to form a group Finds groups of specified annotations in each supplied set of annotations, stores found regions as annotations. Input data An input sequence and a set of annotations to search in. ugene-1.9.8/src/plugins/annotator/transl/english.ts0000644000175000017500000002357711651544321021113 0ustar ilyailya FindAnnotationCollocationsDialog dialog_tittle Find groups of annotated regions region_size_label Region size: search_button Search save_annotations_button Save regions as annotations.. clear_results_button Clear resutls cancel_button Cancel 1 2 whole annotations Annotation must fit into region U2::AnnotatorPlugin dna_annotator_plugin DNA Annotator dna_annotator_plugin_desc This plugin contains routines to manipulate and search DNA sequence annotations U2::AnnotatorViewContext Find annotated regions... warning Warning! no_annotations_found No annotations found! U2::CollocationSearchTask collocation_search_task Search for annotated regions U2::CollocationsDialogController click_to_add_new_annotation <<click '+' button to add new annotation>> stop Stop cancel Cancel searching__found_%1_items_progress_%2 Searching... found %1 regions. Progress: %2% found_%1_items Found %1 regions ready Ready select_annotations Select annotation names to search no_more_annotations_left No annotations left U2::LocalWorkflow::CollocationPrompter sequence from <u>%1</u> set of annotations from <u>%1</u> For each %1 and %2, For each %1%2, Annotations themselves may not span beyond the region. %1 look if <u>%2</u> annotations appear collocated within same region of length <u>%3</u>.%4<br>Output the list of found regions annotated as <u>%5</u>. U2::LocalWorkflow::CollocationWorker Found %1 collocations Group annotations Result annotation Group of annotations Region size Must fit into region Collocation search At least 2 annotations are required for collocation search. Annotated regions containing found collocations. Name of the result annotations to mark found collocations A list of annotation names to search. Found regions will contain all the named annotations. Effectively this is the maximum allowed distance between the interesting annotations in a group Whether the interesting annotations should entirely fit into the specified region to form a group Finds groups of specified annotations in each supplied set of annotations, stores found regions as annotations. Input data An input sequence and a set of annotations to search in. ugene-1.9.8/src/plugins/repeat_finder/0000755000175000017500000000000011651544324016376 5ustar ilyailyaugene-1.9.8/src/plugins/repeat_finder/repeat_finder.pri0000644000175000017500000000057711651544324021732 0ustar ilyailya# include (repeat_finder.pri) PLUGIN_ID=repeat_finder PLUGIN_NAME=Repeat finder PLUGIN_VENDOR=Unipro include( ../../ugene_plugin_common.pri ) #DEFINES+=GTEST_LINKED_AS_SHARED_LIBRARY=1 #LIBS += -lgtest #!debug_and_release|build_pass { # # CONFIG(debug, debug|release) { # LIBS -= -lgtest # LIBS += -lgtestd # } #} #INCLUDEPATH += ../../libs_3rdparty/gtest/srcugene-1.9.8/src/plugins/repeat_finder/repeat_finder.pro0000644000175000017500000000237011651544324021731 0ustar ilyailyainclude (repeat_finder.pri) # Input HEADERS += src/FindRepeatsDialog.h \ src/FindRepeatsTask.h \ src/FindTandemsDialog.h \ src/RepeatFinderPlugin.h \ src/RepeatFinderTests.h \ src/RepeatWorker.h \ src/RF_BitMask.h \ src/RF_SArray_TandemFinder.h \ src/RF_SuffixArray.h \ src/RFBase.h \ src/RFConstants.h \ src/RFDiagonal.h \ src/RFSArray.h \ src/RFSArrayWK.h \ src/RFTaskFactory.h \ src/RepeatQuery.h \ src/RepeatTest.h FORMS += src/ui/FindRepeatsDialog.ui src/ui/FindTandemsDialog.ui SOURCES += src/FindRepeatsDialog.cpp \ src/FindRepeatsTask.cpp \ src/FindTandemsDialog.cpp \ src/RepeatFinderPlugin.cpp \ src/RepeatFinderTests.cpp \ src/RepeatWorker.cpp \ src/RF_SArray_TandemFinder.cpp \ src/RF_SuffixArray.cpp \ src/RFBase.cpp \ src/RFDiagonal.cpp \ src/RFSArray.cpp \ src/RFSArrayWK.cpp \ src/RFTaskFactory.cpp \ src/RepeatQuery.cpp \ src/RepeatTest.cpp RESOURCES += repeat_finder.qrc TRANSLATIONS += transl/english.ts transl/russian.ts ugene-1.9.8/src/plugins/repeat_finder/repeat_finder.qrc0000644000175000017500000000023611651544324021715 0ustar ilyailya images/repeats.png images/repeats_tandem.png ugene-1.9.8/src/plugins/repeat_finder/images/0000755000175000017500000000000011651544324017643 5ustar ilyailyaugene-1.9.8/src/plugins/repeat_finder/images/repeats.png0000644000175000017500000000153611651544324022021 0ustar ilyailyaPNG  IHDRatEXtSoftwareAdobe ImageReadyqe<IDATxtSmHSa>w.hS2!BJ$?0!C@@0$0_ RRA"Q(" BSjM#ilcl_ y999ye,k2?Ky]nE8"G}c>&L2֝:B5hrBI`2M B躾GB J҇-Eز5H; 0`0nMYp8ws'odٶѹH$]~FR2hM33xx`x$ʉ < ԞaSȂ"$)&5jwwT$b1I\v%B4(#CCBnukN1*@ b1Nd_(gƃ 󫡌Z~PCʬ,6WU5:@p`G(sbzzyV;`Oyi[9}ܢ7w ȲIm},8̂WᆮB[C3#D]COM^UimnwPPˍ{6tfaIߕ<_XYs0(Ap$RqraxF;>[[{+F+MdXhNJ̣.yId*/PB@U~&U< d&_ H@rS4Q189;nQrQ? zIENDB`ugene-1.9.8/src/plugins/repeat_finder/images/repeats_tandem.png0000644000175000017500000000173211651544324023347 0ustar ilyailyaPNG  IHDRhtEXtSoftwareAdobe ImageReadyqe<|IDATxb80 @1 A bp }1or9KL޼ @@x008209tSׯ?9UнDo= ~d@mAfǏ 3/>ї*Cᾆq.WWcE1w^02202ySU# ^3tʱo_Q-A߾2?@ YߟYYYj%#q~Ԧ8Bͳ-gY@&H唡m _X$@,@ !g {/~~r~O/0|zן ~I4c)0p8w#?|ɦwA%{P\*p(;ćׯ:߿F$̥wfP0=*P %TC7}wN'a 2/(]1A%@G.+K]F7oJJf<E*eYb?0d>q)Q-QRRwɳR<54@j_33Mv>Go & 6(ݰht&H nٓL|.ϟEL_fb+oO_~3,)/q=N6 >]8gҞ2…;Ws,mMA.70S0۷V: PF9{7(ьE 5FEIENDB`ugene-1.9.8/src/plugins/repeat_finder/src/0000755000175000017500000000000011651544324017165 5ustar ilyailyaugene-1.9.8/src/plugins/repeat_finder/src/FindTandemsDialog.cpp0000644000175000017500000002473311651544324023216 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "FindTandemsDialog.h" #include #include #include #include #include #include #include #include #include #include #include namespace U2 { #define SETTINGS_ROOT QString("plugin_find_repeats/") #define MIN_LEN_SETTINGS QString("min_len") #define IDENTITY_SETTINGS QString("identity") FindTandemsTaskSettings FindTandemsDialog::defaultSettings() { FindTandemsTaskSettings res; Settings* s = AppContext::getSettings(); res.minPeriod = (s->getValue(SETTINGS_ROOT + MIN_LEN_SETTINGS, 1).toInt()); //res.(s->getValue(SETTINGS_ROOT + IDENTITY_SETTINGS, 100).toInt()); //bool minDistCheck = (s->getValue(SETTINGS_ROOT + MIN_DIST_CHECK_SETTINGS, true).toBool()); //bool maxDistCheck = (s->getValue(SETTINGS_ROOT + MAX_DIST_CHECK_SETTINGS, true).toBool()); //res.minDist = !minDistCheck ? 0 : (s->getValue(SETTINGS_ROOT + MIN_DIST_SETTINGS, 0).toInt()); //res.maxDist = !maxDistCheck ? 0 : (s->getValue(SETTINGS_ROOT + MAX_DIST_SETTINGS, 5000).toInt()); //res.inverted = (s->getValue(SETTINGS_ROOT + INVERT_CHECK_SETTINGS, false).toBool()); return res; } FindTandemsDialog::FindTandemsDialog(ADVSequenceObjectContext* _sc) : QDialog(_sc->getAnnotatedDNAView()->getWidget()) { sc = _sc; setupUi(this); CreateAnnotationModel m; m.hideLocation = true; m.data->name = GBFeatureUtils::getKeyInfo(GBFeatureKey_repeat_unit).text; m.sequenceObjectRef = sc->getSequenceObject(); m.useUnloadedObjects = true; m.sequenceLen = sc->getSequenceObject()->getSequenceLen(); ac = new CreateAnnotationWidgetController(m, this); QWidget* caw = ac->getWidget(); QVBoxLayout* l = new QVBoxLayout(); l->setMargin(0); l->addWidget(caw); annotationsWidget->setLayout(l); annotationsWidget->setMinimumSize(caw->layout()->minimumSize()); algoComboBox->addItem(tr("Suffix array"), TSConstants::AlgoSuffix); algoComboBox->addItem(tr("Suffix array (optimized)"), TSConstants::AlgoSuffixBinary); algoComboBox->setCurrentIndex(TSConstants::AlgoSuffixBinary); repeatLenComboBox->addItem(tr("All"), TSConstants::PresetAll); repeatLenComboBox->addItem(tr("Micro-satellites"), TSConstants::PresetMicro); repeatLenComboBox->addItem(tr("Mini-satellites"), TSConstants::PresetMini); repeatLenComboBox->addItem(tr("Big-period tandems"), TSConstants::PresetBigPeriod); repeatLenComboBox->addItem(tr("Custom"), TSConstants::PresetCustom); repeatLenComboBox->setCurrentIndex(TSConstants::PresetAll); bool hasSelection = !sc->getSequenceSelection()->isEmpty(); selectionRangeButton->setEnabled(hasSelection); selectionRangeButton->setChecked(hasSelection); int seqLen = sc->getSequenceLen(); // Settings* s = AppContext::getSettings(); // connect(minLenBox, SIGNAL(valueChanged(int)), SLOT(sl_repeatParamsChanged(int))); // connect(identityBox, SIGNAL(valueChanged(int)), SLOT(sl_repeatParamsChanged(int))); customRangeStartBox->setMaximum(seqLen); customRangeEndBox->setMaximum(seqLen); customRangeEndBox->setValue(seqLen); connect(customRangeStartBox, SIGNAL(valueChanged(int)), SLOT(sl_startRangeChanged(int))); connect(customRangeEndBox, SIGNAL(valueChanged(int)), SLOT(sl_endRangeChanged(int))); //connect(minDistBox, SIGNAL(valueChanged(int)), SLOT(sl_minDistChanged(int))); //connect(maxDistBox, SIGNAL(valueChanged(int)), SLOT(sl_maxDistChanged(int))); updateStatus(); setWindowIcon(QIcon(":/ugene/images/ugene_16.png")); } QStringList FindTandemsDialog::getAvailableAnnotationNames() const { QStringList res; const QSet& objs = sc->getAnnotationObjects(); QSet names; foreach(AnnotationTableObject* o, objs) { foreach(const Annotation* a, o->getAnnotations()) { names.insert(a->getAnnotationName()); } } res = names.toList(); res.sort(); return res; } /* void FindTandemsDialog::sl_setPredefinedAnnotationName() { SetAnnotationNameAction* a = qobject_cast(sender()); QString text = a->text(); a->le->setText(text); } */ void FindTandemsDialog::minPeriodChanged(int min){ maxPeriodBox->setValue(qMax(min,maxPeriodBox->value())); } void FindTandemsDialog::maxPeriodChanged(int max){ minPeriodBox->setValue(qMin(max,minPeriodBox->value())); } void FindTandemsDialog::customization(){ repeatLenComboBox->setCurrentIndex(TSConstants::PresetCustom); } void FindTandemsDialog::presetSelected(int preset){ int minPeriod = 1; int maxPeriod = INT_MAX; const unsigned maxMicro=6; const unsigned maxMini=30; switch (preset){ case TSConstants::PresetAll: break; case TSConstants::PresetMicro: maxPeriod=maxMicro; break; case TSConstants::PresetMini: minPeriod=maxMicro+1; maxPeriod=maxMini; break; case TSConstants::PresetBigPeriod: minPeriod=maxMini+1; break; case TSConstants::PresetCustom: return; default: break; } minPeriodBox->setValue(minPeriod); maxPeriodBox->setValue(maxPeriod); } void FindTandemsDialog::sl_startRangeChanged(int i) { if (i > customRangeEndBox->value()) { customRangeEndBox->setValue(i); } updateStatus(); } void FindTandemsDialog::sl_endRangeChanged(int i) { if (i < customRangeStartBox->value()) { customRangeStartBox->setValue(i); } updateStatus(); } bool FindTandemsDialog::getRegions(QCheckBox* cb, QLineEdit* le, QVector& res) { bool enabled = cb->isChecked(); QString names = le->text(); if (!enabled || names.isEmpty()) { return true; } QSet aNames = names.split(',', QString::SkipEmptyParts).toSet(); const QSet aObjs = sc->getAnnotationObjects(); foreach(AnnotationTableObject* obj, aObjs) { foreach(Annotation* a, obj->getAnnotations()) { if (aNames.contains(a->getAnnotationName())) { res << a->getRegions(); } } } if (res.isEmpty()) { le->setFocus(); QMessageBox::critical(this, tr("Error"), tr("No annotations found: %1").arg(names)); return false; } return true; } U2Region FindTandemsDialog::getActiveRange() const { U2Region range(0, sc->getSequenceLen()); if (selectionRangeButton->isChecked() && !sc->getSequenceSelection()->isEmpty()) { range = sc->getSequenceSelection()->getSelectedRegions().at(0); } else if (customRangeButton->isChecked()) { range.startPos = customRangeStartBox->value(); range.length = customRangeEndBox->value() - range.startPos; } return range; } void FindTandemsDialog::accept() { int minPeriod = minPeriodBox->value(); int maxPeriod = maxPeriodBox->value(); // int identPerc = identityBox->value(); U2Region range = getActiveRange(); assert(range.length > 0); QString err = ac->validate(); if (!err.isEmpty()) { QMessageBox::critical(this, tr("Error"), err); return; } ac->prepareAnnotationObject(); const DNASequence& seq = sc->getSequenceObject()->getDNASequence(); FindTandemsTaskSettings settings; const CreateAnnotationModel& cam = ac->getModel(); settings.minPeriod = minPeriod; settings.maxPeriod = maxPeriod; // settings.mismatches = (100-identPerc) * minPeriod / 100; settings.seqRegion = range; settings.seqRegion = range; settings.algo = (TSConstants::TSAlgo)algoComboBox->currentIndex(); settings.minRepeatCount = minRepeatsBox->value(); settings.minTandemSize = qMax(FindTandemsTaskSettings::DEFAULT_MIN_TANDEM_SIZE, minTandemSizeBox->value()); settings.showOverlappedTandems = overlappedTandemsCheckBox->isChecked(); FindTandemsToAnnotationsTask* t = new FindTandemsToAnnotationsTask(settings, seq, cam.data->name, cam.groupName, cam.annotationObjectRef); AppContext::getTaskScheduler()->registerTopLevelTask(t); saveState(); QDialog::accept(); } void FindTandemsDialog::saveState() { Settings* s = AppContext::getSettings(); int identPerc = identityBox->value(); s->setValue(SETTINGS_ROOT + IDENTITY_SETTINGS, identPerc); } quint64 FindTandemsDialog::areaSize() const { quint64 range = getActiveRange().length; if (range <=0) { return 0; } int minDist = 0; int maxDist = sc->getSequenceLen(); quint64 dRange = qMax(0, maxDist - minDist); quint64 res = range * dRange; return res; } int FindTandemsDialog::estimateResultsCount() const { assert(identityBox->value() == 100); int len = 1; quint64 nVariations = areaSize(); //max possible results double variationsPerLen = pow(double(4), double(len)); quint64 res = quint64(nVariations / variationsPerLen); res = (res > 20) ? (res / 10) * 10 : res; res = (res > 200) ? (res / 100) * 100 : res; res = (res > 2000) ? (res / 1000) * 1000 : res; return res; } void FindTandemsDialog::updateStatus() { /* if (identityBox->value() == 100) { int r = estimateResultsCount(); statusLabel->setText(tr("Estimated repeats count: %1").arg(r)); statusLabel->setToolTip(tr("Estimated repeats count hint is based on the active settings and random sequence model")); } else { statusLabel->setText(""); statusLabel->setToolTip(""); } */ } }//namespace ugene-1.9.8/src/plugins/repeat_finder/src/RFConstants.h0000644000175000017500000000162011651544324021541 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include namespace U2 { } //namespace ugene-1.9.8/src/plugins/repeat_finder/src/RepeatFinderTests.cpp0000644000175000017500000004744311651544324023300 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "RepeatFinderTests.h" #include "FindRepeatsTask.h" #include "RF_SArray_TandemFinder.h" #include #include #include #include #include #include #include namespace U2 { #define SEQ_ATTR "seq" #define SEQ2_ATTR "seq2" #define REG_ATTR "reg" #define W_ATTR "w" #define C_ATTR "c" #define INV_ATTR "inverted" #define MIND_ATTR "mind" #define MAXD_ATTR "maxd" #define RESULT_ATTR "expected_result" #define REFL_ATTR "reflect" #define EXCL_ATTR "exclude" #define SEQUENCE "sequence" #define QUERY "query" #define USE_BITMASK "bit-mask" #define MISMATCHES "mismatches" #define ALG_ATTR "alg" U2Region GTest_FindSingleSequenceRepeatsTask::parseRegion(const QString& n, const QDomElement& el) { U2Region res; QString v = el.attribute(n); if (v.isEmpty()) { return res; } int idx = v.indexOf(".."); if (idx == -1 || idx+2 >= v.length()) { return res; } QString v1 = v.left(idx); QString v2 = v.mid(idx+2); int startPos = v1.toInt(); int endPos = v2.toInt(); if (startPos >= 0 && endPos > startPos) { res.startPos = startPos - 1; res.length = endPos - startPos + 1; } return res; } void GTest_FindSingleSequenceRepeatsTask::init(XMLTestFormat *tf, const QDomElement& el) { Q_UNUSED(tf); seq = el.attribute(SEQ_ATTR); if (seq.isEmpty()) { stateInfo.setError(QString("Value not found '%1'").arg(SEQ_ATTR)); return; } seq2 = el.attribute(SEQ2_ATTR); if (seq2.isEmpty()) { seq2 = seq; } region = parseRegion(REG_ATTR, el); QString algStr = el.attribute(ALG_ATTR); if (algStr == "suffix") { alg = RFAlgorithm_Suffix; } else { if (algStr == "diagonal") { alg = RFAlgorithm_Diagonal; } else { alg = RFAlgorithm_Auto; } } minD = el.attribute(MIND_ATTR, "-1").toInt(); maxD = el.attribute(MAXD_ATTR, "-1").toInt(); QString wStr = el.attribute(W_ATTR); if (wStr.isEmpty()) { stateInfo.setError(QString("Value not found '%1'").arg(W_ATTR)); return; } w = wStr.toInt(); if (w < 2) { stateInfo.setError(QString("Illegal value for '%1': %2").arg(W_ATTR).arg(wStr)); return; } QString cStr = el.attribute(C_ATTR, "0"); c = cStr.toInt(); if (c < 0 || c >= w) { stateInfo.setError(QString("Illegal value for '%1': %2").arg(C_ATTR).arg(cStr)); return; } inverted = el.attribute("invert") == "true"; reflect = el.attribute("reflect", "true") == "true"; filterNested = el.attribute("filterNested", "false") == "true"; resultFile = el.attribute(RESULT_ATTR); if (resultFile.isEmpty()) { stateInfo.setError(QString("Value not found '%1'").arg(RESULT_ATTR)); return; } excludeList = el.attribute(EXCL_ATTR).split(',', QString::SkipEmptyParts); } static QString getAlgName(RFAlgorithm alg) { QString res; switch(alg) { case RFAlgorithm_Diagonal: res = "diagonal"; break; case RFAlgorithm_Suffix: res = "suffix"; break; default: res = "UNKNOWN"; break; } return res; } void GTest_FindSingleSequenceRepeatsTask::prepare() { if (hasError() || isCanceled()) { return; } DNASequenceObject * seqObj = getContext(this, seq); if (seqObj == NULL){ stateInfo.setError("can't find sequence1"); return; } DNASequenceObject * seq2Obj = seqObj; if (seq != seq2) { seq2Obj = getContext(this, seq2); if (seq2Obj == NULL){ stateInfo.setError("can't find sequence2"); return; } } if (region.isEmpty()) { region = seqObj->getSequenceRange(); } int maxLen = seqObj->getSequenceLen(); if (minD == -1) { minD = -maxLen; } if (maxD == -1) { maxD = maxLen; } QList algos; if (alg == RFAlgorithm_Auto) { algos << RFAlgorithm_Diagonal << RFAlgorithm_Suffix; } else { algos << alg; } FindRepeatsTaskSettings s; s.minLen = w; s.mismatches = c; s.minDist = minD; s.maxDist = maxD; s.inverted = inverted; s.seqRegion = region; s.reportReflected = reflect; s.filterNested = filterNested; s.nThreads = 1;//todo: add to settings foreach(RFAlgorithm algo, algos) { QString algName = getAlgName(algo); if (excludeList.contains(algName)) { continue; } s.algo = algo; Task* sub = new FindRepeatsTask(s, seqObj->getDNASequence(), seq2Obj->getDNASequence()); addSubTask(sub); } } void GTest_FindSingleSequenceRepeatsTask::run() { if (hasError() || isCanceled()) { return; } QVector expectedResults; // load file with results QString fname = env->getVar("COMMON_DATA_DIR") + "/" + resultFile; QFile file(fname); if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) { stateInfo.setError(QString("Can't open results file %1").arg(fname)); return; } while (!file.atEnd()) { QString line = file.readLine(); QStringList hit = line.split(' ', QString::SkipEmptyParts); if (hit.size()!=3) { stateInfo.setError(QString("Can't parse results line: %1").arg(line)); return; } RFResult r; r.x = hit[0].toInt() - 1; r.y = hit[1].toInt() - 1; r.l = hit[2].toInt(); if (r.x < 0 || r.y < 0 || r.l < 0) { stateInfo.setError(QString("Can't parse results line: %1").arg(line)); return; } expectedResults.append(r); } file.close(); qSort(expectedResults); //check all subtasks foreach(Task* t, getSubtasks()) { FindRepeatsTask* sub = qobject_cast(t); QVector calcResults = sub->getResults(); if (expectedResults.size()!=calcResults.size()) { stateInfo.setError(QString("Results count not matched, num = %1, expected = %2, alg = %3") .arg(calcResults.size()).arg(expectedResults.size()).arg(getAlgName(sub->getSettings().algo))); return; } qSort(calcResults); for (int i=0, n = expectedResults.size(); i < n; i++) { RFResult re = expectedResults[i]; RFResult rc = calcResults[i]; if (re!=rc) { stateInfo.setError(QString("Results not matched, expected(%1, %2, %3), computed(%4, %5, %6), algo = %7") .arg(re.x).arg(re.y).arg(re.l).arg(rc.x).arg(rc.y).arg(rc.l).arg(getAlgName(sub->getSettings().algo))); return; } } } } //--------------------------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------------------------- void GTest_FindTandemRepeatsTask::init(XMLTestFormat *tf, const QDomElement& el) { Q_UNUSED(tf); minD = el.attribute(MIND_ATTR, "-1").toInt(); maxD = el.attribute(MAXD_ATTR, "-1").toInt(); minSize = el.attribute("minSize", "3").toInt(); repeatCount = el.attribute("repeatCount", "3").toInt(); inverted = el.attribute("invert") == "true"; reflect = el.attribute("reflect", "true") == "true"; filterNested = el.attribute("filterNested", "false") == "true"; results = el.attribute(RESULT_ATTR); sequence = el.attribute("sequence"); } void GTest_FindTandemRepeatsTask::prepare() { if (hasError() || isCanceled()) { return; } //this->getContext(this,"") //new DNAAlphabetRegistryImpl( // TaskResourceUsage* tru = AppContext::getTaskScheduler()->getTaskResources(NULL).constData(); DNAAlphabet* alph = AppContext::getDNAAlphabetRegistry()->findById(BaseDNAAlphabetIds::NUCL_DNA_DEFAULT()); seqObj = new DNASequence(QString("sequence"), sequence.toAscii(), alph ); if (seqObj == NULL){ stateInfo.setError("can't find sequence1"); return; } string = (char*)(seqObj->constData()); int maxLen = sequence.length(); if (minD == -1) { minD = -maxLen; } if (maxD == -1) { maxD = maxLen; } if (maxSize == 0) { maxSize = maxLen; } FindTandemsTaskSettings s; s.minPeriod = minSize; s.minRepeatCount = repeatCount; s.seqRegion = region; s.nThreads = 1;//todo: add to settings addSubTask( new TandemFinder(s, *seqObj) ); } void GTest_FindTandemRepeatsTask::run() { if (hasError() || isCanceled()) { return; } QList expectedResults; // load file with results QStringList resList = results.split(';', QString::SkipEmptyParts); foreach(const QString& result, resList){ QStringList hit = result.split(',', QString::SkipEmptyParts); if (hit.size()!=3) { stateInfo.setError(QString("Can't parse results line: %1").arg(result)); return; } bool offsetConverted; Tandem tnd(hit[0].toInt(&offsetConverted), hit[2].toInt(), hit[1].toInt()); if ( !offsetConverted || tnd.size == 0 || tnd.repeatLen==0) { stateInfo.setError(QString("Can't parse results line: %1").arg(result)); return; } expectedResults.append(tnd); } //check all subtasks TandemFinder* sub = qobject_cast(this->getSubtasks()[0]); QList calcResults = sub->getResults(); if (expectedResults.size()!=calcResults.size()) { QString results("First results are:\n"); for (int i=0, n = qMin(calcResults.size(),3); i < n; i++) { Tandem rc = calcResults[i]; results.append(QString("%1 %2 %3\n").arg(rc.offset).arg(rc.size).arg(rc.repeatLen)); } stateInfo.setError(QString("Results count not matched, num = %1, expected = %2\n%3").arg(calcResults.size()).arg(expectedResults.size()).arg(results)); return; } qSort(expectedResults); qSort(calcResults); for (int i=0, n = expectedResults.size(); i < n; i++) { Tandem re = expectedResults[i]; Tandem rc = calcResults[i]; if (re.offset!=rc.offset || re.size != rc.size || re.repeatLen!=rc.repeatLen) { stateInfo.setError(QString("Results not matched, expected(%1, %2, %3), computed(%4, %5, %6)") .arg(re.offset).arg(re.size).arg(re.repeatLen) .arg(rc.offset).arg(rc.size).arg(rc.repeatLen) ); return; } } delete seqObj; } //--------------------------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------------------------- U2Region GTest_FindRealTandemRepeatsTask::parseRegion(const QString& n, const QDomElement& el) { U2Region res; QString v = el.attribute(n); if (v.isEmpty()) { return res; } int idx = v.indexOf(".."); if (idx == -1 || idx+2 >= v.length()) { return res; } QString v1 = v.left(idx); QString v2 = v.mid(idx+2); int startPos = v1.toInt(); int endPos = v2.toInt(); if (startPos >= 0 && endPos > startPos) { res.startPos = startPos - 1; res.length = endPos - startPos + 1; } return res; } void GTest_FindRealTandemRepeatsTask::init(XMLTestFormat *tf, const QDomElement& el) { Q_UNUSED(tf); minD = el.attribute(MIND_ATTR, "-1").toInt(); maxD = el.attribute(MAXD_ATTR, "-1").toInt(); minSize = el.attribute("minSize", "1").toInt(); repeatCount = el.attribute("repeatCount", "3").toInt(); inverted = el.attribute("invert") == "true"; reflect = el.attribute("reflect", "true") == "true"; filterNested = el.attribute("filterNested", "false") == "true"; results = el.attribute(RESULT_ATTR); if (results.isEmpty()) { stateInfo.setError(QString("Value not found '%1'").arg(RESULT_ATTR)); return; } sequence = el.attribute("sequence"); if (sequence.isEmpty()) { stateInfo.setError(QString("Value not found '%1'").arg("sequence")); return; } } void GTest_FindRealTandemRepeatsTask::prepare() { if (hasError() || isCanceled()) { return; } DNASequenceObject * seqObj = getContext(this, sequence); if (seqObj == NULL){ stateInfo.setError("can't find sequence1"); return; } if (region.isEmpty()) { region = seqObj->getSequenceRange(); } int maxLen = seqObj->getSequenceLen(); if (minD == -1) { minD = -maxLen; } if (maxD == -1) { maxD = maxLen; } FindTandemsTaskSettings s; s.minPeriod = minSize; s.minRepeatCount = repeatCount; s.seqRegion = region; s.nThreads = 1;//todo: add to settings addSubTask( new TandemFinder(s, seqObj->getDNASequence()) ); } void GTest_FindRealTandemRepeatsTask::run() { if (hasError() || isCanceled()) { return; } QList expectedResults; // load file with results QString fname = env->getVar("COMMON_DATA_DIR") + "/" + results; QFile file(fname); if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) { stateInfo.setError(QString("Can't open results file %1").arg(fname)); return; } while (!file.atEnd()) { QString line = file.readLine(); QStringList hit = line.split(' ', QString::SkipEmptyParts); if (hit.size()!=5) { stateInfo.setError(QString("Can't parse results line: %1").arg(line)); return; } bool h1ok, h2ok, h3ok; Tandem t(hit[0].toInt(&h1ok)-1, hit[3].toInt(&h2ok), hit[2].toInt(&h3ok)); if (!h1ok || !h2ok || !h3ok) { stateInfo.setError(QString("Can't parse results line: %1").arg(line)); return; } expectedResults.append(t); } file.close(); qSort(expectedResults); //check all subtasks TandemFinder* sub = qobject_cast(this->getSubtasks()[0]); QList calcResults = sub->getResults(); QMutableListIterator cIt(calcResults); QMutableListIterator eIt(expectedResults); while (cIt.hasNext() && eIt.hasNext()){ Tandem er = eIt.peekNext(); Tandem cr = cIt.peekNext(); if (er(this, seqObjName); if (seqObj == NULL){ stateInfo.setError(QString("Can't find index sequence %1").arg(seqObjName)); return; } DNAAlphabetType seqType = seqObj->getAlphabet()->getType(); char unknownChar = seqType == DNAAlphabet_AMINO ? 'X' : seqType==DNAAlphabet_NUCL ? 'N' : '\0'; const quint32* bitMask = NULL; int bitCharLen = 0; if (useBitMask) { bitCharLen = bt.getBitMaskCharBitsNum(seqType); bitMask = bt.getBitMaskCharBits(seqType); } int prefixSize = query.size(); if (nMismatches > 0) { prefixSize = prefixSize / (nMismatches + 1); } index = new SArrayIndex(seqObj->getSequence().constData(), seqObj->getSequenceLen(), prefixSize, stateInfo, unknownChar, bitMask, bitCharLen); if (hasError()) { return; } SArrayBasedSearchSettings s; s.query = query.toAscii(); s.useBitMask = useBitMask; s.bitMask = bitMask; s.nMismatches = nMismatches; s.bitMaskCharBitsNum = bitCharLen; s.unknownChar = unknownChar; findTask = new SArrayBasedFindTask(index, s); addSubTask( findTask ); } void GTest_SArrayBasedFindTask::run() { if (hasError() || isCanceled()) { return; } qSort(expectedResults); QList calcResults = findTask->getResults(); if ( expectedResults.size() != calcResults.size() ) { stateInfo.setError(QString("Results count do not match, num = %1, expected = %2") .arg(calcResults.size()).arg(expectedResults.size() ) ); return; } qSort(calcResults); for (int i = 0, n = expectedResults.size(); i < n; i++) { int re = expectedResults[i]; int rc = calcResults[i]; if (re != rc) { stateInfo.setError(QString("Results not matched, expected %1, computed %2") .arg(re).arg(rc) ); return; } } } //--------------------------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------------------------- QList RepeatFinderTests::createTestFactories() { QList res; res.append(GTest_FindSingleSequenceRepeatsTask::createFactory()); res.append(GTest_FindTandemRepeatsTask::createFactory()); res.append(GTest_FindRealTandemRepeatsTask::createFactory()); res.append( GTest_SArrayBasedFindTask::createFactory() ); return res; } } //namespace ugene-1.9.8/src/plugins/repeat_finder/src/RFDiagonal.h0000644000175000017500000000420511651544324021305 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_RF_DIAGONAL_ALG_H_ #define _U2_RF_DIAGONAL_ALG_H_ #include "RFBase.h" #include namespace U2 { class RFDiagonalWKSubtask; class RFDiagonalAlgorithmWK : public RFAlgorithmBase { Q_OBJECT friend class RFDiagonalWKSubtask; public: RFDiagonalAlgorithmWK(RFResultsListener* rl, const char* seqX, int sizeX, const char* seqY, int sizeY, DNAAlphabetType seqType, int w, int k); void prepare(); protected: int START_DIAG; int END_DIAG; }; class RFDiagonalWKSubtask : public Task { Q_OBJECT friend class RFDiagonalAlgorithmWK; public: RFDiagonalWKSubtask(RFDiagonalAlgorithmWK* owner, int threadNum, int totalThreads); void run(); private: void processDiagonal(int x, int y); int getDiagLen(int d) const; int processMatch(const char* x, const char* y, const char* xEnd, const char* yEnd, int c); RFDiagonalAlgorithmWK* owner; int threadNum; int nThreads; const char* dataX; const char* dataY; QVector diagResults; quint64 areaS; quint64 currentS; quint64 nextPercentS; }; } //namespace #endif ugene-1.9.8/src/plugins/repeat_finder/src/RFBase.h0000644000175000017500000000713511651544324020446 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_RF_BASE_ALG_H_ #define _U2_RF_BASE_ALG_H_ #include #include #include #include namespace U2 { #define PCHAR_MATCHES(x, y) (*(x) == *(y) && *(x) != unknownChar) #define CHAR_MATCHES(x, y) ((x) == (y) && (x) != unknownChar) class Tandem{ public: Tandem(quint32 _offset, quint32 _repeatLen, quint32 _size): offset(_offset),repeatLen(_repeatLen),size(_size),rightSide(_offset+_size-_repeatLen) { } Tandem(const Tandem& t): offset(t.offset),repeatLen(t.repeatLen),size(t.size),rightSide(t.rightSide) { } Tandem& operator =(const Tandem& t){ offset=t.offset; repeatLen=t.repeatLen; size=t.size; rightSide=t.rightSide; return *this; } bool operator < (const Tandem& t) const; bool extend (const Tandem& t); // offset of tandem from beginning of the sequence quint64 offset; // repeat len int repeatLen; //size of tandem in nucleotides int size; quint64 rightSide; }; class RFAlgorithmBase : public Task { Q_OBJECT public: RFAlgorithmBase(RFResultsListener* l, const char* seqX, int sizeX, const char* seqY, int sizeY, DNAAlphabetType seqType, int w, int k, TaskFlags flags = TaskFlags_NR_FOSCOE); void setReportReflected(bool v) {reportReflected = v;} void setRFResultsListener(RFResultsListener*); void prepare(); static RFAlgorithmBase* createTask(RFResultsListener* l, const char *seqx, int sizeX, const char *seqY, int sizeY, DNAAlphabet *al, int w, int mismatches = 0, RFAlgorithm alg = RFAlgorithm_Auto, int nThreads = MAX_PARALLEL_SUBTASKS_AUTO); protected: // adds single result to global results void addToResults(const RFResult& r); // adds multiple results to global results void addToResults(const QVector& newResults); //always return true. bool -> to use in assertions bool checkResults(const QVector& v); bool checkResult(const RFResult& v); const char* seqX; const char* seqY; const int SIZE_X; const int SIZE_Y; const DNAAlphabetType SEQ_TYPE; const int WINDOW_SIZE; const int K; const int C; bool reflective; char unknownChar; RFResultsListener* resultsListener; bool reportReflected; }; } //namespace #endif ugene-1.9.8/src/plugins/repeat_finder/src/RFSArrayWK.cpp0000644000175000017500000001745311651544324021576 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "RFSArrayWK.h" namespace U2 { RFSArrayWKAlgorithm::RFSArrayWKAlgorithm(RFResultsListener* rl, const char* seqX, int sizeX, const char* seqY, int sizeY, DNAAlphabetType seqType, int w, int k) : RFAlgorithmBase(rl, seqX, sizeX, seqY, sizeY, seqType, w, k, TaskFlags_NR_FOSCOE) { q = WINDOW_SIZE/(C+1); indexTask = NULL; if (sizeX > sizeY) { arrayIsX = false; SEARCH_SIZE = sizeX; ARRAY_SIZE = sizeY; searchSeq = seqX; arraySeq = seqY; } else { arrayIsX = true; SEARCH_SIZE = sizeY; ARRAY_SIZE = sizeX; searchSeq = seqY; arraySeq = seqX; } } void RFSArrayWKAlgorithm::prepare() { RFAlgorithmBase::prepare(); if (hasError()) { return; } // ARRAY_SIZE is smaller than SEARCH_SIZE. Allocate diags only for ARRAY_SIZE elements -> // when ARRAY_SIZE diags are processed, 0 one becomes unused and ARRAY_SIZE+1 one is placed to 0 cell diagOffsets.resize(ARRAY_SIZE); if (diagOffsets.isEmpty()) { stateInfo.setError(tr("Memory allocation error, size: %1").arg(ARRAY_SIZE)); return; } diagOffsets.fill(-1); nThreads = qBound(1, getNumParallelSubtasks(), SEARCH_SIZE / (20*1000)); indexTask = new CreateSArrayIndexTask(arraySeq, ARRAY_SIZE, q, unknownChar); int arrayPercent = 10; indexTask->setSubtaskProgressWeight(arrayPercent/100.0F); addSubTask(indexTask); setMaxParallelSubtasks(1); for (int i = 0; i < nThreads; i++) { RFSArrayWKSubtask* t = new RFSArrayWKSubtask(this, i); t->setSubtaskProgressWeight((100 - arrayPercent) / (100.0F*nThreads)); addSubTask(t); } } void RFSArrayWKAlgorithm::cleanup() { diagOffsets.resize(0); } QList RFSArrayWKAlgorithm::onSubTaskFinished(Task* subTask) { if (subTask == indexTask) { setMaxParallelSubtasks(nThreads); } return QList(); } #define IS_THREAD_DIAG(diagNum) \ ((nThreads == 1) || (diagNum % nThreads == t->tid)) void RFSArrayWKAlgorithm::calculate(RFSArrayWKSubtask* t) { SArrayIndex* _index = indexTask->index; int W = WINDOW_SIZE; int CMAX = C; const char* dataA = arraySeq; const char* dataAEnd = dataA + ARRAY_SIZE; int aSize = ARRAY_SIZE; const char* dataS = searchSeq; const char* dataSEnd = searchSeq + SEARCH_SIZE; int sSize = SEARCH_SIZE; int percentLen = (dataSEnd - dataS) / 100; int reportS = percentLen; int* diags = diagOffsets.data(); for (int s = 0, maxS = sSize - W + 1, s0diag = 0; s < maxS && !t->isCanceled(); s++, s0diag = (s0diag == aSize - 1) ? 0 : s0diag + 1) { if (IS_THREAD_DIAG(s0diag)) { // s0diag is a border position for rolling (over 2 sequences) diagOffsets. // Remember: diagOffset size is not sizeS+sizeA, but sizeA (that is < sizeS) only size // and it's zero point 'rolls' (or shifts) as scope of possible active diagonals shifts diags[s0diag] = -1; } if (s == reportS) { t->stateInfo.progress++; reportS+=percentLen; } if (!_index->find(t, dataS + s)) { continue; } //here we have iterator set to the first match in A, guaranteed match length for all values returned by iterator = Q int a; while ((a = _index->nextArrSeqPos(t))!=-1) { if (reflective && s >= a) { continue; } int diag = a > s0diag ? aSize + s0diag - a : s0diag - a ; assert(diag >=0 && diag < diagOffsets.size()); if (!IS_THREAD_DIAG(diag)) { //this diagonal is assigned to another thread -> skip it continue; } int checkedS = diags[diag]; if (checkedS >= s || a + W > aSize || s + W > sSize) { continue; } assert(s == 0 || a == 0 || !PCHAR_MATCHES(dataS + s - 1, dataA + a - 1)); //this result must be processed on prev s step! // construct initial window, startS/startA - start positions for potential hit const char* startS = dataS + s; const char* startA = dataA + a; const char* posS = startS + q; const char* posA = startA + q; assert(PCHAR_MATCHES(startS, startA)); const char* endS = startS + W; //find first mismatch -> need it to update diags for (; PCHAR_MATCHES(posS, posA) && posS < endS; posS++, posA++){} int c = 0; if (posS != endS) { //there was mismatch on W range -> save its pos and find all other mismatches on W range const char* firstMismatchPosS = posS; for (c = 1; (c += PCHAR_MATCHES(posS, posA) ? 0 : 1) <= CMAX && posS < endS; posS++, posA++) {} assert(posS - startS <= W); if (c > CMAX) {// to many mismatches on forward strand assert(!PCHAR_MATCHES(firstMismatchPosS, posA - (posS - firstMismatchPosS))); diags[diag] = firstMismatchPosS - dataS; continue; } } // have a hit! -> expand window forward as much as possible // posS/A points to the first unchecked base here assert(posS - startS == W); for (; c <= CMAX && posA < dataAEnd && posS < dataSEnd; posA++, posS++) { int popVal = PCHAR_MATCHES(posA - W, posS - W) ? 0 : 1; int pushVal = PCHAR_MATCHES(posA, posS) ? 0 : 1; assert(c>=0); c += pushVal - popVal; } int len = posS - startS; int lastCheckedS = s + len - (W - q + 1); // the first point of the last window checked //now shift to the first mismatch pos and save value in diags const char* firstMismatchPosS = dataS + lastCheckedS - 1; const char* firstMismatchPosA = dataA + a + (lastCheckedS - 1 - s); while (++firstMismatchPosS < dataSEnd && ++firstMismatchPosA < dataAEnd && PCHAR_MATCHES(firstMismatchPosS, firstMismatchPosA)) {} assert(firstMismatchPosS<=posS); diags[diag] = firstMismatchPosS - dataS; //ensure that match with len > W ends with hit while (len > W && !PCHAR_MATCHES(startS + len - 1, startA + len - 1)){len--;} //save result addResult(a, s, len); assert(len >= W);//a place for a break-point } } } void RFSArrayWKAlgorithm::addResult(int a, int s, int l) { RFResult res((arrayIsX ? a : s), (arrayIsX ? s : a), l); assert(checkResult(res)); addToResults(res); } RFSArrayWKSubtask::RFSArrayWKSubtask(RFSArrayWKAlgorithm* _owner, int _tid) : Task(tr("Find repeats subtask (suffixWK)"), TaskFlag_None), owner(_owner), tid(_tid) { tpm = Task::Progress_Manual; } void RFSArrayWKSubtask::run() { stateInfo.progress = 0; owner->calculate(this); } } //namespace ugene-1.9.8/src/plugins/repeat_finder/src/RepeatTest.h0000644000175000017500000000060411651544324021416 0ustar ilyailya#ifdef _U2_REPTEST_H_ #include #include namespace U2 { class TestData { public: QString factoryId; }; class RepeatTest : public ::testing::TestWithParam { protected: virtual void SetUp() { testData = GetParam(); } virtual void TearDown() {} protected: TestData testData; }; } // namespace #endif ugene-1.9.8/src/plugins/repeat_finder/src/RepeatWorker.cpp0000644000175000017500000002541711651544324022314 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "RepeatWorker.h" #include "FindRepeatsDialog.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include /* TRANSLATOR U2::LocalWorkflow::RepeatWorker */ namespace U2 { namespace LocalWorkflow { /****************************** * RepeatWorkerFactory ******************************/ static const QString NAME_ATTR("result-name"); static const QString LEN_ATTR("min-length"); static const QString IDENTITY_ATTR("identity"); static const QString MIN_DIST_ATTR("min-distance"); static const QString MAX_DIST_ATTR("max-distance"); static const QString INVERT_ATTR("inverted"); static const QString NESTED_ATTR("filter-nested"); static const QString ALGO_ATTR("algorithm"); static const QString THREADS_ATTR("threads"); const QString RepeatWorkerFactory::ACTOR_ID("repeats-search"); void RepeatWorkerFactory::init() { QList p; QList a; { Descriptor id(BasePorts::IN_SEQ_PORT_ID(), RepeatWorker::tr("Input sequences"), RepeatWorker::tr("A nucleotide sequence to search repeats in.")); Descriptor od(BasePorts::OUT_ANNOTATIONS_PORT_ID(), RepeatWorker::tr("Repeat annotations"), RepeatWorker::tr("A set of annotations marking repeats found in the sequence.")); QMap inM; inM[BaseSlots::DNA_SEQUENCE_SLOT()] = BaseTypes::DNA_SEQUENCE_TYPE(); p << new PortDescriptor(id, DataTypePtr(new MapDataType("repeat.seq", inM)), true /*input*/); QMap outM; outM[BaseSlots::ANNOTATION_TABLE_SLOT()] = BaseTypes::ANNOTATION_TABLE_TYPE(); p << new PortDescriptor(od, DataTypePtr(new MapDataType("repeat.annotations", outM)), false /*input*/, true /*multi*/); } { Descriptor nd(NAME_ATTR, RepeatWorker::tr("Annotate as"), RepeatWorker::tr("Name of the result annotations marking found repeats.")); Descriptor idd(IDENTITY_ATTR, RepeatWorker::tr("Identity"), RepeatWorker::tr("Repeats identity.")); Descriptor ld(LEN_ATTR, RepeatWorker::tr("Min length"), RepeatWorker::tr("Minimum length of repeats.")); Descriptor mid(MIN_DIST_ATTR, RepeatWorker::tr("Min distance"), RepeatWorker::tr("Minimum distance between repeats.")); Descriptor mad(MAX_DIST_ATTR, RepeatWorker::tr("Max distance"), RepeatWorker::tr("Maximum distance between repeats.")); Descriptor ind(INVERT_ATTR, RepeatWorker::tr("Inverted"), RepeatWorker::tr("Search for inverted repeats.")); Descriptor nsd(NESTED_ATTR, RepeatWorker::tr("Filter nested"), RepeatWorker::tr("Filter nested repeats.")); Descriptor ald(ALGO_ATTR, RepeatWorker::tr("Algorithm"), RepeatWorker::tr("Control over variations of algorithm.")); Descriptor thd(THREADS_ATTR, RepeatWorker::tr("Parallel threads"), RepeatWorker::tr("Number of parallel threads used for the task.")); FindRepeatsTaskSettings cfg = FindRepeatsDialog::defaultSettings(); a << new Attribute(nd, BaseTypes::STRING_TYPE(), true, "repeat_unit"); a << new Attribute(ld, BaseTypes::NUM_TYPE(), false, cfg.minLen); a << new Attribute(idd, BaseTypes::NUM_TYPE(), false, cfg.getIdentity()); a << new Attribute(mid, BaseTypes::NUM_TYPE(), false, cfg.minDist); a << new Attribute(mad, BaseTypes::NUM_TYPE(), false, cfg.maxDist); a << new Attribute(ind, BaseTypes::BOOL_TYPE(), false, cfg.inverted); a << new Attribute(nsd, BaseTypes::BOOL_TYPE(), false, cfg.filterNested); a << new Attribute(ald, BaseTypes::NUM_TYPE(), false, cfg.algo); a << new Attribute(thd, BaseTypes::NUM_TYPE(), false, cfg.nThreads); } Descriptor desc(ACTOR_ID, RepeatWorker::tr("Find repeats"), RepeatWorker::tr("Finds repeats in each supplied sequence, stores found regions as annotations.") ); ActorPrototype* proto = new IntegralBusActorPrototype(desc, p, a); QMap delegates; { QVariantMap m; m["minimum"] = 0; m["maximum"] = INT_MAX; m["suffix"] = L10N::suffixBp(); delegates[MIN_DIST_ATTR] = new SpinBoxDelegate(m); m["specialValueText"] = RepeatWorker::tr("Any"); delegates[MAX_DIST_ATTR] = new SpinBoxDelegate(m); m["minimum"] = 2; delegates[LEN_ATTR] = new SpinBoxDelegate(m); } { QVariantMap m; m["minimum"] = 50; m["maximum"] = 100; m["suffix"] = "%"; delegates[IDENTITY_ATTR] = new SpinBoxDelegate(m); } { QVariantMap m; m["specialValueText"] = "Auto"; delegates[THREADS_ATTR] = new SpinBoxDelegate(m); } { QVariantMap m; m["Auto"] = RFAlgorithm_Auto; m["Diagonals"] = RFAlgorithm_Diagonal; m["Suffix index"] = RFAlgorithm_Suffix; delegates[ALGO_ATTR] = new ComboBoxDelegate(m); } proto->setPrompter(new RepeatPrompter()); proto->setEditor(new DelegateEditor(delegates)); proto->setIconPath(":repeat_finder/images/repeats.png"); WorkflowEnv::getProtoRegistry()->registerProto(BaseActorCategories::CATEGORY_BASIC(), proto); DomainFactory* localDomain = WorkflowEnv::getDomainRegistry()->getById(LocalDomainFactory::ID); localDomain->registerEntry(new RepeatWorkerFactory()); } /****************************** * RepeatPrompter ******************************/ QString RepeatPrompter::composeRichDoc() { IntegralBusPort* input = qobject_cast(target->getPort(BasePorts::IN_SEQ_PORT_ID())); Actor* producer = input->getProducer(BaseSlots::DNA_SEQUENCE_SLOT().getId()); QString unsetStr = ""+tr("unset")+""; QString producerName = tr(" from %1").arg(producer ? producer->getLabel() : unsetStr); // TODO extend ? QString resultName = getRequiredParam(NAME_ATTR); QString inverted = getParameter(INVERT_ATTR).toBool() ? tr("inverted") : tr("direct"); QString doc = tr("For each sequence%1, find %2 repeats." "
    Detect %3% identical repeats not shorter than %4 bps." "
    Output the list of found regions annotated as %5.") .arg(producerName) //sequence from Read Fasta 1 .arg(getHyperlink(INVERT_ATTR, inverted)) .arg(getHyperlink(IDENTITY_ATTR, getParameter(IDENTITY_ATTR).toInt())) .arg(getHyperlink(LEN_ATTR, getParameter(LEN_ATTR).toInt())) .arg(getHyperlink(NAME_ATTR, resultName)); return doc; } /****************************** * RepeatWorker ******************************/ RepeatWorker::RepeatWorker(Actor* a) : BaseWorker(a), input(NULL), output(NULL) { } void RepeatWorker::init() { input = ports.value(BasePorts::IN_SEQ_PORT_ID()); output = ports.value(BasePorts::OUT_ANNOTATIONS_PORT_ID()); } bool RepeatWorker::isReady() { return (input && input->hasMessage()); } Task* RepeatWorker::tick() { Message inputMessage = getMessageAndSetupScriptValues(input); cfg.algo = RFAlgorithm(actor->getParameter(ALGO_ATTR)->getAttributeValue()); cfg.minLen = actor->getParameter(LEN_ATTR)->getAttributeValue(); cfg.minDist = actor->getParameter(MIN_DIST_ATTR)->getAttributeValue(); cfg.maxDist = actor->getParameter(MAX_DIST_ATTR)->getAttributeValue(); int identity = actor->getParameter(IDENTITY_ATTR)->getAttributeValue(); cfg.setIdentity(identity); cfg.nThreads = actor->getParameter(THREADS_ATTR)->getAttributeValue(); cfg.inverted = actor->getParameter(INVERT_ATTR)->getAttributeValue(); cfg.filterNested = actor->getParameter(NESTED_ATTR)->getAttributeValue(); resultName = actor->getParameter(NAME_ATTR)->getAttributeValue(); if(resultName.isEmpty()){ resultName = "repeat_unit"; algoLog.error(tr("result name is empty, default name used")); } if(identity > 100 || identity < 0){ algoLog.error(tr("Incorrect value: identity value must be between 0 and 100")); return new FailTask(tr("Incorrect value: identity value must be between 0 and 100")); } QVariantMap map = inputMessage.getData().toMap(); DNASequence seq = map.value(BaseSlots::DNA_SEQUENCE_SLOT().getId()).value(); if(cfg.minDist < 0){ algoLog.error(tr("Incorrect value: minimal distance must be greater then zero")); return new FailTask(tr("Incorrect value: minimal distance must be greater then zero")); } if (!seq.alphabet->isNucleic()) { QString err = tr("Sequence alphabet is not nucleic!"); //if (failFast) { return new FailTask(err); /*} else { algoLog.error(err); return NULL; }*/ } Task* t = new FindRepeatsToAnnotationsTask(cfg, seq, resultName, QString(), GObjectReference()); connect(t, SIGNAL(si_stateChanged()), SLOT(sl_taskFinished())); return t; } void RepeatWorker::sl_taskFinished() { FindRepeatsToAnnotationsTask* t = qobject_cast(sender()); if (t->getState() != Task::State_Finished || t->hasError()) return; if (output) { const QList& res = t->importAnnotations(); QVariant v = qVariantFromValue >(res); output->put(Message(BaseTypes::ANNOTATION_TABLE_TYPE(), v)); if (input->isEnded()) { output->setEnded(); } algoLog.info(tr("Found %1 repeats").arg(res.size())); } } bool RepeatWorker::isDone() { return !input || input->isEnded(); } void RepeatWorker::cleanup() { } } //namespace LocalWorkflow } //namespace U2 ugene-1.9.8/src/plugins/repeat_finder/src/RF_SArray_TandemFinder.cpp0000644000175000017500000006123111651544324024104 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "RF_SArray_TandemFinder.h" #include "RFConstants.h" #include #include #include #include #include #include #include namespace U2 { const int FindTandemsTaskSettings::DEFAULT_MIN_REPEAT_COUNT = 0; const int FindTandemsTaskSettings::DEFAULT_MIN_TANDEM_SIZE = 9; FindTandemsToAnnotationsTask::FindTandemsToAnnotationsTask(const FindTandemsTaskSettings& s, const DNASequence& seq, const QString& _an, const QString& _gn, const GObjectReference& _aor): Task(tr("Find repeats to annotations"), TaskFlags_NR_FOSCOE), annName(_an), annGroup(_gn), annObjRef(_aor){ setVerboseLogMode(true); if (annObjRef.isValid()) { LoadUnloadedDocumentTask::addLoadingSubtask(this, LoadDocumentTaskConfig(true, annObjRef, new LDTObjectFactory(this))); } addSubTask(new TandemFinder(s, seq)); } QList FindTandemsToAnnotationsTask::onSubTaskFinished(Task* subTask) { QList res; if (hasError() || isCanceled()) { return res; } if (qobject_cast(subTask)!=NULL){ TandemFinder* tandemFinderTask = qobject_cast(subTask); QList annotations = importTandemAnnotations( tandemFinderTask->getResults(), tandemFinderTask->getSettings().seqRegion.startPos, tandemFinderTask->getSettings().showOverlappedTandems ); if (!annotations.isEmpty()) { algoLog.info(tr("Found %1 repeat regions").arg(annotations.size())); Task* createTask = new CreateAnnotationsTask(annObjRef, annGroup, annotations); createTask->setSubtaskProgressWeight(0); res.append(createTask); } } return res; } QList FindTandemsToAnnotationsTask::importTandemAnnotations(const QList& tandems, const quint32 seqStart, const bool showOverlapped) { QList res; foreach(const Tandem& tan, tandems) { unsigned offset = 0; const unsigned maxOffset = tan.size % tan.repeatLen; do{ SharedAnnotationData ad(new AnnotationData()); ad->name = annName; const quint32 tandemEnd = tan.offset+tan.size+seqStart; quint32 pos = tan.offset+seqStart+offset; for(; pos<=tandemEnd-tan.repeatLen; pos+=tan.repeatLen){ ad->location->regions << U2Region(pos, tan.repeatLen); } if (ad->location->isEmpty()){ continue; } ad->qualifiers.append(U2Qualifier("repeat_len", QString::number(tan.repeatLen))); ad->qualifiers.append(U2Qualifier("tandem_size", QString::number(tan.size))); res.append(ad); offset++; }while(showOverlapped && offset<=maxOffset); } return res; } TandemFinder::TandemFinder(const FindTandemsTaskSettings& _settings, const DNASequence& directSequence): Task(tr("Find tandems"), TaskFlags_FOSCOE), settings(_settings),regionCount(0){ if (settings.seqRegion.length == 0) { settings.seqRegion= U2Region(0, directSequence.length()); } startTime = GTimer::currentTimeMicros(); sequence = (char*)directSequence.constData() + settings.seqRegion.startPos; } class TF_WalkerConfig: public SequenceWalkerConfig{ public: // TODO: check seqSize type compatibility! TF_WalkerConfig(const char* _sequence, quint32 _seqSize, quint32 _chunkSize){ seq=_sequence; seqSize=_seqSize; chunkSize=_chunkSize; lastChunkExtraLen=_chunkSize/2; overlapSize=TandemFinder::maxCheckPeriod; } }; void TandemFinder::prepare(){ // Q_ASSERT(settings.minLen>=3); Q_ASSERT(settings.minRepeatCount>=3); //AppResourcePool* resPool = AppContext::getAppSettings()->getAppResourcePool(); int chunkSize = 32*1024*1024; // optimized for 32Mb mem-chunk addSubTask( new SequenceWalkerTask( TF_WalkerConfig(sequence, settings.seqRegion.length, chunkSize), this, tr("Find tandems"), TaskFlags_NR_FOSCOE ) ); } void TandemFinder::run(){ algoLog.trace(tr("Find tandems finished %1").arg(GTimer::currentTimeMicros()-startTime)); } QList TandemFinder::onSubTaskFinished(Task* subTask){ if (qobject_cast(subTask)!=NULL){ setMaxParallelSubtasks(AppContext::getAppSettings()->getAppResourcePool()->getIdealThreadCount()); return regionTasks; } if (qobject_cast(subTask)!=NULL){ TandemFinder_Region* regionTask = qobject_cast(subTask); const quint64 offs = regionTask->getRegionOffset(); QMutexLocker foundTandemsLocker(&tandemsAccessMutex); QList regionTandems = regionTask->getResult(); QMutableListIterator comTandIt(foundTandems); foreach(Tandem t, regionTandems){ t.offset += offs; t.rightSide += offs; while(comTandIt.hasNext() && comTandIt.peekNext()(); } void TandemFinder::onRegion(SequenceWalkerSubtask* t, TaskStateInfo& ti){ if(ti.hasError()){return;} quint64 offs = t->getRegionSequence() - t->getGlobalConfig().seq; QMutexLocker lock(&subtasksQueue); //TODO: fix me regionTasks.append(new TandemFinder_Region(regionCount++, t->getRegionSequence(), t->getRegionSequenceLen(), offs, settings)); } TandemFinder_Region::~TandemFinder_Region(){ QMutexLocker tandemsAccessLocker(&tandemsAccessMutex); } QList TandemFinder_Region::onSubTaskFinished(Task* subTask){ if (qobject_cast(subTask)!=NULL){ subTask->cleanup(); } return QList(); } void TandemFinder_Region::prepare(){ Q_ASSERT(settings.minPeriod<=settings.maxPeriod); int period=1; for (; period<=16; period = period*2+1){ if (period*2settings.maxPeriod) continue; addSubTask( new ExactSizedTandemFinder(sequence, seqSize, settings, period) ); } { if (period>settings.maxPeriod ) return; addSubTask( new LargeSizedTandemFinder(sequence, seqSize, settings, period) ); } // setMaxParallelSubtasks(AppContext::getAppSettings()->getAppResourcePool()->getIdealThreadCount()); } void TandemFinder_Region::addResult(const Tandem& tandem){ QMutexLocker tandemsAccessLocker(&tandemsAccessMutex); foundTandems.append(tandem); } void TandemFinder_Region::addResults(const QMap& tandems){ /* QList checkedTandems; foreach(const Tandem& t, tandems){ if(t.repeatLen*minCount>t.size)continue; checkedTandems.append(t); } */ QMutexLocker tandemsAccessLocker(&tandemsAccessMutex); foundTandems.append( tandems.values() ); } ConcreteTandemFinder::ConcreteTandemFinder(QString taskName, const char* _sequence, const long _seqSize, const FindTandemsTaskSettings& _settings, const int _prefixLength): Task(taskName, TaskFlags_FOSCOE), sequence(_sequence), seqSize(_seqSize), index(NULL), suffixArray(NULL), settings(_settings),prefixLength(_prefixLength),suffArrSize(_seqSize-_prefixLength+1){ Q_ASSERT( settings.minRepeatCount>1 ); int suffArrMemory; if (settings.algo == TSConstants::AlgoSuffixBinary){ suffArrMemory = seqSize/4 + seqSize*sizeof(quint32) + (1<setSubtaskProgressWeight(arrayPercent/100.0F); // TODO fix algorithm selection if( qobject_cast(this)!=NULL){ addSubTask(indexTask); } } } QList ConcreteTandemFinder::onSubTaskFinished(Task* subTask){ if (qobject_cast(subTask)!=NULL){ index = qobject_cast(subTask)->index; } return QList(); } void ConcreteTandemFinder::cleanup(){ if (getSubtasks().size()==0) { return; } getSubtasks().first()->cleanup(); } ExactSizedTandemFinder::ExactSizedTandemFinder(const char* _sequence, const long _seqSize, const FindTandemsTaskSettings& _settings, const int _analysisSize) : ConcreteTandemFinder(tr("Find %1-period tandems").arg(_analysisSize),_sequence,_seqSize,_settings,_analysisSize*2) { } ExactSizedTandemFinder::~ExactSizedTandemFinder() { }; inline char* seqCast(const quint32* suffArr, int ind){ return reinterpret_cast( suffArr[ind] ); } void ExactSizedTandemFinder::run(){ if (seqSizegetBitMask(); const quint32* sArray = suffixArray->getArray(); quint32* currentDiffPos = (quint32*)sArray; const quint32* sArrayLast = sArray +suffArrSize-1; while(currentDiffPos=minPeriod && diff<=maxPeriod){ //only our exact size quint32 suffixOffset = qMax(1, (settings.minTandemSize-prefixLength)/diff ); /*diff==(signed)minRepeatLen ? qMax(3u-2u, (tandemMinSize-prefixLength)/diff ): qMax(3u-1u, (tandemMinSize-prefixLength)/diff );*/ if (currentDiffPos+suffixOffset<=sArrayLast && currentDiffPos[suffixOffset]-currentDiffPos[0] == suffixOffset*diff){ if (bitMask[currentDiffPos[0]]==bitMask[currentDiffPos[suffixOffset]]){ currentDiffPos = checkAndSpreadTandem_bv(currentDiffPos,currentDiffPos+suffixOffset, diff); continue; } } } currentDiffPos++; } delete suffixArray;//TODO: remove all deletes }else{ const quint32* sArray = index->getSArray(); const quint32* sArrayLast = const_cast(sArray + index->getSArraySize() - 1); quint32* currentDiffPos = (quint32*)sArray; // const quint32* bitMaskArray = index->getMaskedSequence(); while(currentDiffPos=minPeriod && diff<=maxPeriod){ //only our exact size unsigned suffixOffset = qMax(1, signed(settings.minTandemSize-prefixLength)/diff ); if (currentDiffPos+suffixOffset>sArrayLast || currentDiffPos[suffixOffset]-currentDiffPos[0]!=suffixOffset*diff){ // currentDiffPos += suffixOffset;continue; }else{ const char* seq0 = seqCast(currentDiffPos,0); const char* seq1 = seqCast(currentDiffPos,suffixOffset); // in the other words prefix currentDiffPos[0]==currentDiffPos[suffixOffset] if (comparePrefixChars(seq0,seq1)){ currentDiffPos = checkAndSpreadTandem(currentDiffPos,currentDiffPos+suffixOffset, diff); continue; } } } currentDiffPos++; } } qobject_cast(getParentTask())->addResults(rawTandems); } bool ExactSizedTandemFinder::comparePrefixChars(const char* first,const char* second){ return strncmp(first,second,prefixLength)==0; } quint32* ExactSizedTandemFinder::checkAndSpreadTandem(const quint32* tandemStartIndex, const quint32* tandemLastIndex, quint32 repeatLen){ const char* tandemStart = seqCast(tandemStartIndex,0); /* const Tandem small_tandem(tandemStart - sequence, repeatLen, ((char*)tandemLastIndex[0]+repeatLen)-tandemStart); QMap::iterator it = rawTandems.find(small_tandem); if (it!=rawTandems.end()){ // there are close tandems Tandem t = *it; if (t.extend(small_tandem)){ rawTandems.erase(it); rawTandems.insert(t,t); return (quint32*)tandemLastIndex-1; } } */ quint32* arrRunner = (quint32*)tandemLastIndex-1; { const quint32* sArrayLast = const_cast(index->getSArray() + index->getSArraySize() - 1); // run until distance become incorrect, it is incredible if we run far with changing prefix do{ ++arrRunner; }while (arrRunnergetMaskedSequence()!=NULL){ if (false){ }else{ // in this case seqCast(tandemStartIndex,1)==seqCast(tandemStartIndex,0)+repeatLen char* seqRunner = seqCast(arrRunner,0); //move forward by 0.5-1.0 repeatlen to find exact lower bound const char* seqEnd = sequence + seqSize; while(seqRunner<=seqEnd-repeatLen && strncmp(tandemStart, seqRunner, repeatLen)==0 ){ seqRunner += repeatLen; } const quint32 size = seqRunner-tandemStart; const Tandem tandem(tandemStart - sequence, repeatLen, size); //check if there is already marked area QMap::iterator it = rawTandems.find(tandem); if (it==rawTandems.end()){ // there are no close tandems int tandemMinSize = qMax(settings.minTandemSize, settings.minRepeatCount*tandem.repeatLen); if (tandem.size>=tandemMinSize){ rawTandems.insert(tandem, tandem); } }else{ Tandem t = *it; rawTandems.erase(it); t.extend(tandem); rawTandems.insert(t,t); } } return arrRunner; } quint32* ExactSizedTandemFinder::checkAndSpreadTandem_bv(const quint32* tandemStartIndex, const quint32* tandemLastIndex, quint32 repeatLen){ const BitMask& bitMask = suffixArray->getBitMask(); const quint32 tandemStart = tandemStartIndex[0]; /* const Tandem small_tandem(tandemStart, repeatLen, tandemLastIndex[0]+repeatLen-tandemStart); QMap::iterator it = rawTandems.find(small_tandem); if (it!=rawTandems.end()){ // there are close tandems Tandem t = *it; if (t.extend(small_tandem)){ rawTandems.erase(it); rawTandems.insert(t,t); return (quint32*)tandemLastIndex-1; } } */ const quint64 matchRepeat = bitMask[tandemStart]; quint32* arrRunner = (quint32*)tandemLastIndex-1; { const quint32* sArrayLast = suffixArray->getArray()+suffArrSize-1; // run until distance become incorrect, it is incredible if we would run far with changing prefix do{ ++arrRunner; }while (arrRunnergetMaskedSequence()!=NULL){ if (false){ }else{ // in this case seqCast(tandemStartIndex,1)==seqCast(tandemStartIndex,0)+repeatLen quint32 seqRunner = arrRunner[0]; //move forward by 0.5-1.0 repeatlen to find exact lower bound const quint32& seqEnd = seqSize; const quint64 periodMask = ~(~0ull>>(2*repeatLen)); while(seqRunner<=seqEnd-repeatLen && ((matchRepeat^bitMask[seqRunner])&periodMask)==0 ){ seqRunner += repeatLen; } const quint32 size = seqRunner-tandemStart; const Tandem tandem(tandemStart, repeatLen, size); //check if there is already marked area QMap::iterator it = rawTandems.find(tandem); if (it==rawTandems.end()){ // there are no close tandems int tandemMinSize = qMax(settings.minTandemSize, settings.minRepeatCount*tandem.repeatLen); if (tandem.size >= tandemMinSize){ rawTandems.insert(tandem, tandem); } }else{ Tandem t = *it; rawTandems.erase(it); t.extend(tandem); rawTandems.insert(t,t); } } return arrRunner; } LargeSizedTandemFinder::LargeSizedTandemFinder(const char* _sequence, const long _seqSize, const FindTandemsTaskSettings& _settings, const int _analysisSize): ConcreteTandemFinder(tr("Find big-period tandems"),_sequence,_seqSize,_settings,_analysisSize){} LargeSizedTandemFinder::~LargeSizedTandemFinder(){} void LargeSizedTandemFinder::run(){ if (seqSizegetBitMask(); const quint32* sArray = suffixArray->getArray(); quint32* currentDiffPos = (quint32*)sArray; const quint32* sArrayLast = sArray+suffArrSize-1; while(currentDiffPos=minPeriod && diff<=maxPeriod){ quint32 firstSuffixPos = currentDiffPos[0]; quint32 secondSuffixPos = currentDiffPos[1]; const quint32 endSuffixPos = secondSuffixPos; bool correctRepeat = false; do{ correctRepeat = bitMask[firstSuffixPos]==bitMask[secondSuffixPos]; firstSuffixPos += prefixLength; secondSuffixPos += prefixLength; }while( correctRepeat && firstSuffixPosgetSArray(); const quint32* sArrayLast = const_cast(sArray + index->getSArraySize() - 1); quint32* currentDiffPos = (quint32*)sArray; //const quint32* bitMaskArray = index->getMaskedSequence(); // TODO: rewrite this code while(currentDiffPos=minPeriod && diff<=maxPeriod){ //skip already found tandems unsigned suffixOffset = qMax(1, signed(settings.minTandemSize-prefixLength)/diff ); if (currentDiffPos+suffixOffset>sArrayLast || currentDiffPos[suffixOffset]-currentDiffPos[0]!=suffixOffset*diff){ // currentDiffPos += suffixOffset;continue; }else{ const char* seq0 = seqCast(currentDiffPos,0); const char* seq1 = seqCast(currentDiffPos,suffixOffset); // in the other words prefix currentDiffPos[0]==currentDiffPos[1] if (comparePrefixChars(seq0,seq1)){ currentDiffPos = checkAndSpreadTandem(currentDiffPos,currentDiffPos+suffixOffset, diff); continue; } } } currentDiffPos++; } } qobject_cast(getParentTask())->addResults(rawTandems); } bool LargeSizedTandemFinder::comparePrefixChars(const char* first,const char* second){ return strncmp(first,second,prefixLength)==0; } quint32* LargeSizedTandemFinder::checkAndSpreadTandem(const quint32* tandemStartIndex, const quint32* tandemLastIndex, const unsigned repeatLen){ const char* tandemStart = seqCast(tandemStartIndex,0); /* const Tandem small_tandem(tandemStart - sequence, repeatLen, ((char*)tandemLastIndex[0]+repeatLen)-tandemStart); QMap::iterator it = rawTandems.find(small_tandem); if (it!=rawTandems.end()){ // there are close tandems Tandem t = *it; if (t.extend(small_tandem)){ rawTandems.erase(it); rawTandems.insert(t,t); return (quint32*)tandemLastIndex-1; } } */ quint32* arrRunner = (quint32*)tandemLastIndex-1; { const quint32* sArrayLast = const_cast(index->getSArray() + index->getSArraySize() - 1); // run until distance become incorrect, it is incredible if we run far with changing prefix do{ ++arrRunner; }while (arrRunnergetMaskedSequence()!=NULL){ if (false){ }else{ // in this case seqCast(tandemStartIndex,1)==seqCast(tandemStartIndex,0)+repeatLen char* seqRunner = seqCast(arrRunner,0); //move forward by 0.5-1.0 of repeat len to find exact lower bound const char* seqEnd = sequence + seqSize; while(seqRunner<=seqEnd-repeatLen && strncmp(tandemStart, seqRunner, repeatLen)==0 ){ seqRunner += repeatLen; } const quint32 size = seqRunner-tandemStart; const Tandem tandem(tandemStart - sequence, repeatLen, size); //check if there is already marked area QMap::iterator it = rawTandems.find(tandem); if (it==rawTandems.end()){ // there are no close tandems rawTandems.insert(tandem, tandem); }else{ Tandem t = *it; rawTandems.erase(it); t.extend(tandem); rawTandems.insert(t,t); } } return arrRunner; } quint32* LargeSizedTandemFinder::checkAndSpreadTandem_bv(const quint32* tandemStartIndex, const quint32* tandemLastIndex, const unsigned repeatLen){ const BitMask& bitMask = suffixArray->getBitMask(); const quint32 tandemStart = tandemStartIndex[0]; quint32 tandemLast = tandemLastIndex[0]; const quint32& seqEnd = seqSize; // repeatLen > prefixLength while(tandemLast::iterator it = rawTandems.find(tandem); if (it==rawTandems.end()){ // there are no close tandems int tandemMinSize = qMax(settings.minTandemSize, 2*tandem.repeatLen); if (tandem.size>=tandemMinSize){ rawTandems.insert(tandem, tandem); } }else{ Tandem t = *it; rawTandems.erase(it); t.extend(tandem); rawTandems.insert(t,t); } return const_cast(tandemStartIndex + size/repeatLen); } } //namespace ugene-1.9.8/src/plugins/repeat_finder/src/RepeatTest.cpp0000644000175000017500000000143211651544324021751 0ustar ilyailya#ifdef _U2_REPTEST_H_ #include "RepeatTest.h" #include #include namespace U2 { static TestData createData() { TestData d; d.factoryId = ""; return d; } TEST_P(RepeatTest, t01) { RepeatFinderTaskFactoryRegistry* r = AppContext::getRepeatFinderTaskFactoryRegistry(); ASSERT_NE(r, (RepeatFinderTaskFactoryRegistry*)NULL); RepeatFinderTaskFactory* t = AppContext::getRepeatFinderTaskFactoryRegistry()->getFactory(testData.factoryId); ASSERT_NE(t, (RepeatFinderTaskFactory*)NULL); } INSTANTIATE_TEST_CASE_P( RepeatTestInstance, RepeatTest, ::testing::Values(createData())); } //namespace #endifugene-1.9.8/src/plugins/repeat_finder/src/RF_SuffixArray.h0000644000175000017500000000422711651544324022175 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _RF_SUFFIX_ARRAY_H_ #define _RF_SUFFIX_ARRAY_H_ #include "RF_BitMask.h" #include #include // Attention! Currently constructs suffix array sorted by prefix up to 32 symbols in length namespace U2 { class SuffixArray{ const unsigned prefixLen; const unsigned usablePrefixLen; const quint32 seqSize; const char* sequence; const unsigned prefixNum; quint32 maxSuffixesPerPrefix; quint64* qSortBuffer; clock_t startt; quint32* suffixes; quint32* prefixes; BitMask* bitMask; // static quint64 getAvailableMemory(){return 128*1024*1024;} public: SuffixArray(const char* _sequence, int size, int _prefixLen); private: void sort(); void sortDeeper(const quint32 begin, const quint32 end); void sortUndefinedDeeper(const quint32 begin, const quint32 end); void qsort(const quint32 first, const quint32 last); inline bool less(const quint32 li, const quint32 ri); public: const BitMask& getBitMask()const {return *bitMask;} // inline quint32& SuffixArray::operator[](const quint32 index) {return suffixes[index];} // inline const quint32& SuffixArray::operator[](const quint32 index)const {return suffixes[index];} inline quint32* getArray() {return suffixes;} ~SuffixArray(); }; } //U2 #endif ugene-1.9.8/src/plugins/repeat_finder/src/FindRepeatsDialog.h0000644000175000017500000000471111651544324022665 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_FIND_REPEATS_DIALOG_H_ #define _U2_FIND_REPEATS_DIALOG_H_ #include #include "FindRepeatsTask.h" #include #include #include #include namespace U2 { class CreateAnnotationWidgetController; class ADVSequenceObjectContext; class FindRepeatsDialog : public QDialog, public Ui_FindRepeatsDialog { Q_OBJECT public: FindRepeatsDialog(ADVSequenceObjectContext* seq); static FindRepeatsTaskSettings defaultSettings(); virtual void accept(); protected slots: void sl_setPredefinedAnnotationName(); void sl_minDistChanged(int i); void sl_maxDistChanged(int i); void sl_startRangeChanged(int i); void sl_endRangeChanged(int i); void sl_minLenHeuristics(); void sl_hundredPercent(); void sl_repeatParamsChanged(int); void sl_minMaxToggle(bool); private: U2Region getActiveRange() const; void saveState(); QStringList getAvailableAnnotationNames() const; bool getRegions(QCheckBox* cb, QLineEdit* le, QVector& res); void prepareAMenu(QToolButton* tb, QLineEdit* le, const QStringList& names); void updateStatus(); //methods for results count estimation quint64 areaSize() const ; int estimateResultsCount() const; ADVSequenceObjectContext* sc; CreateAnnotationWidgetController* ac; }; class SetAnnotationNameAction : public QAction { Q_OBJECT public: SetAnnotationNameAction(const QString& txt, QObject* p, QLineEdit* _le) : QAction(txt, p), le(_le) {} QLineEdit* le; }; } //namespace #endif ugene-1.9.8/src/plugins/repeat_finder/src/FindTandemsDialog.h0000644000175000017500000000455111651544324022657 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_FIND_TANDEMS_DIALOG_H_ #define _U2_FIND_TANDEMS_DIALOG_H_ #include #include "RF_SArray_TandemFinder.h" #include #include #include #include #include #include namespace U2 { class CreateAnnotationWidgetController; class ADVSequenceObjectContext; class FindTandemsDialog : public QDialog, public Ui_FindTandemsDialog { Q_OBJECT public: FindTandemsDialog(ADVSequenceObjectContext* seq); static FindTandemsTaskSettings defaultSettings(); virtual void accept(); protected slots: //void sl_setPredefinedAnnotationName(); void sl_startRangeChanged(int i); void sl_endRangeChanged(int i); void minPeriodChanged(int min); void maxPeriodChanged(int max); void presetSelected(int preset); void customization(); //void sl_hundredPercent(); //void sl_repeatParamsChanged(int); //void sl_minMaxToggle(bool); private: U2Region getActiveRange() const; void saveState(); QStringList getAvailableAnnotationNames() const; bool getRegions(QCheckBox* cb, QLineEdit* le, QVector& res); void prepareAMenu(QToolButton* tb, QLineEdit* le, const QStringList& names); void updateStatus(); //methods for results count estimation quint64 areaSize() const ; int estimateResultsCount() const; ADVSequenceObjectContext* sc; CreateAnnotationWidgetController* ac; }; } //namespace #endif ugene-1.9.8/src/plugins/repeat_finder/src/RF_SuffixArray.cpp0000644000175000017500000002173111651544324022527 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "RF_SuffixArray.h" #include "RFConstants.h" #include #include #include namespace U2 { /* void memset(void* _arr, const char _val, const size_t _size){ char* arr = (char*)_arr; for (size_t i=0;i<_size;i++){ arr[i]=_val; } } void memmove(void* _src, void* _dst, const size_t _size){ char* src = (char*)_src; char* dst = (char*)_dst; if (_src<_dst){ const char* srcend = src+_size; for (;src=src;){ *srclast--=*dstlast--; } } } */ #define time ((clock()-startt)*1./CLOCKS_PER_SEC) using namespace std; class exc : public exception{ const char* msg; public: exc(const char* _msg): msg(_msg){} const char* what() const throw(){ return msg; } }; SuffixArray::SuffixArray(const char* _sequence, int size, int _prefixLen): prefixLen(_prefixLen),usablePrefixLen(qMin(_prefixLen,12)),seqSize(size),sequence(_sequence),prefixNum(1<<(2*usablePrefixLen)) { startt = clock(); bitMask = new BitMask(sequence, seqSize); bitMask->setPrefixLen(prefixLen); perfLog.trace(QString("Construct finished: %1").arg(time)); prefixes = new quint32[prefixNum]; U2::memset(prefixes, 0, prefixNum*sizeof(quint32)); //init prefixes const BitMask& mask = *bitMask; for (quint32 i=0;i<=seqSize-prefixLen;i++){ const quint32 ind = ( mask[i]>>(64-usablePrefixLen*2) ); #ifdef _DEBUG if (ind>=prefixNum){ algoLog.error(QString("Error init! charIndex: %1, prefInd: %2, prefixLen: %3").arg(i).arg(ind).arg(prefixLen)); } #endif prefixes[ ind ]++; } /* int usedPrefixes = 0; for (unsigned i=0;i0){ usedPrefixes++; if (prefixLen==14) cout << "Prefix "<< i << " x " << prefixes[i] << endl; } } cout << "Used prefixes: " << usedPrefixes << " of total " << (1<<(2*prefixLen)) << endl; */ perfLog.trace(QString("Init prefixes finished: %1").arg(time)); quint32 oldV = prefixes[0]; maxSuffixesPerPrefix = oldV; prefixes[0]=0; for (unsigned i=1;i>(64-usablePrefixLen*2); #ifdef _DEBUG if (ind>=prefixNum){ algoLog.error(QString("Error sorting! charIndex: %1, prefInd: %2, prefixLen: %3").arg(i).arg(ind).arg(prefixLen)); } #endif suffixes[prefixes[ind]++] = i; } /* for (unsigned i=1;i prefixes[i-1]){ cout<<"Prefix "<usablePrefixLen){ const quint32 secondSuffixIndex = prefixes[0]; if (0=last) return; if (last-first==1){ const quint32 t = suffixes[first]; suffixes[first] = suffixes[last]; suffixes[last] = t; return; } const quint64* alignedSortBuf = qSortBuffer-first; quint32 lrunner = first; quint32 rrunner = last; const quint64 midv = alignedSortBuf[(first+last)/2]; do{ while (alignedSortBuf[lrunner]=rrunner){ //lrunner == rrunner == middle break; }else{ const quint32 t = suffixes[lrunner]; suffixes[lrunner] = suffixes[rrunner]; suffixes[rrunner] = t; ++lrunner; --rrunner; } }while(lrunner * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_REPEAT_FINDER_TESTS_H_ #define _U2_REPEAT_FINDER_TESTS_H_ #include "RFBase.h" #include #include #include #include #include #include #include #include namespace U2 { class FindRepeatsTask; class TandemFinder; class GTest_FindSingleSequenceRepeatsTask : public GTest { Q_OBJECT public: SIMPLE_XML_TEST_BODY_WITH_FACTORY_EXT(GTest_FindSingleSequenceRepeatsTask, "find-repeats", TaskFlags_FOSCOE); void prepare(); void run(); U2Region parseRegion(const QString& n, const QDomElement& el); QString seq, seq2; RFAlgorithm alg; U2Region region; int w, c, minD, maxD; bool inverted; bool reflect; bool filterNested; QStringList excludeList; QString resultFile; }; class GTest_FindTandemRepeatsTask : public GTest { Q_OBJECT public: SIMPLE_XML_TEST_BODY_WITH_FACTORY_EXT(GTest_FindTandemRepeatsTask, "find-tandems", TaskFlags_FOSCOE); void prepare(); void run(); U2Region parseRegion(const QString& n, const QDomElement& el); U2Region region; char* string; int minD, maxD; int minSize, maxSize, repeatCount; bool inverted; bool reflect; bool filterNested; DNASequence* seqObj; QString sequence; QString results; }; class GTest_FindRealTandemRepeatsTask : public GTest { Q_OBJECT public: SIMPLE_XML_TEST_BODY_WITH_FACTORY_EXT(GTest_FindRealTandemRepeatsTask, "find-tandems-real", TaskFlags_FOSCOE); void prepare(); void run(); U2Region parseRegion(const QString& n, const QDomElement& el); U2Region region; char* string; int minD, maxD; int minSize, repeatCount; bool inverted; bool reflect; bool filterNested; DNASequence* seqObj; QString sequence; QString results; }; class SArrayIndex; class SArrayBasedFindTask; class GTest_SArrayBasedFindTask : public GTest { Q_OBJECT public: SIMPLE_XML_TEST_BODY_WITH_FACTORY_EXT(GTest_SArrayBasedFindTask, "sarray-based-find", TaskFlags_FOSCOE); void prepare(); void run(); QString seqObjName; QString query; bool useBitMask; BitsTable bt; int nMismatches; DNASequence* seqObj; SArrayIndex* index; SArrayBasedFindTask* findTask; QList expectedResults; }; class RepeatFinderTests { public: static QList createTestFactories(); }; } //namespace #endif ugene-1.9.8/src/plugins/repeat_finder/src/ui/0000755000175000017500000000000011651544324017602 5ustar ilyailyaugene-1.9.8/src/plugins/repeat_finder/src/ui/FindRepeatsDialog.ui0000644000175000017500000006752411651544324023503 0ustar ilyailya FindRepeatsDialog Qt::ApplicationModal 0 0 566 315 Find repeats :/repeat_finder/repeats_image:/repeat_finder/repeats_image 0 Base Repeat finder parameters 0 0 Minimum repeat length Qt::Horizontal 87 20 0 0 0 0 Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter bp 2 1000000 1 100 0 0 Heuristic based selection of repeat length so the number of repeats in the sequence will not exceed 1000 1k Repeats identity Qt::Horizontal 87 20 0 0 0 0 Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter % 50 100 100 0 0 Resets repeats identity to 100% 100 0 0 QFrame::Sunken Qt::Horizontal Minimum distance between repeats false false 0 0 0 0 Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter bp 0 100000000 0 Maximum distance between repeats false Qt::Horizontal 87 20 false 0 0 0 0 Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter bp 0 1000000 5000 Region to process Whole sequence true Qt::Horizontal 40 20 Selection Qt::Horizontal 40 20 Custom range false 100 0 Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter 1 - false 100 0 Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter 1 0 0 0 0 Qt::Vertical 20 37 Advanced Advanced parameters Custom algorithm Qt::Horizontal 71 13 false Search only for repeats that lie inside of an annotated region Qt::Horizontal 87 20 false 0 0 0 0 false ... Search only for repeats that have an annotated region inside Qt::Horizontal 71 13 false 0 0 0 0 false ... Filter repeats that have an annotated region inside Qt::Horizontal 71 13 false 0 0 0 0 false ... Do not filter nested repeats Qt::Horizontal 247 12 Search for inverted repeats Qt::Horizontal 257 20 Qt::Vertical 20 33 Qt::Horizontal 40 20 Start true Cancel startButton clicked() FindRepeatsDialog accept() 416 518 273 270 cancelButton clicked() FindRepeatsDialog reject() 499 518 273 270 maxDistCheck toggled(bool) maxDistBox setEnabled(bool) 140 165 446 165 minDistCheck toggled(bool) minDistBox setEnabled(bool) 140 138 446 138 annotationFitCheck toggled(bool) annotationFitEdit setEnabled(bool) 140 194 431 194 annotationFitCheck toggled(bool) annotationFitButton setEnabled(bool) 140 194 516 194 customRangeButton toggled(bool) customRangeEndBox setEnabled(bool) 260 285 478 285 customRangeButton toggled(bool) customRangeStartBox setEnabled(bool) 260 285 362 285 algoCheck toggled(bool) algoCombo setEnabled(bool) 140 228 446 228 annotationAroundFilterCheck toggled(bool) annotationAroundFilterEdit setEnabled(bool) 145 254 485 254 annotationAroundFilterCheck toggled(bool) annotationAroundFilterButton setEnabled(bool) 145 254 570 254 annotationAroundKeepCheck toggled(bool) annotationAroundKeepEdit setEnabled(bool) 145 227 485 227 annotationAroundKeepCheck toggled(bool) annotationAroundKeepButton setEnabled(bool) 145 227 570 227 ugene-1.9.8/src/plugins/repeat_finder/src/ui/FindTandemsDialog.ui0000644000175000017500000005200411651544324023456 0ustar ilyailya FindTandemsDialog Qt::ApplicationModal 0 0 566 280 Find tandems :/repeat_finder/repeats_image:/repeat_finder/repeats_image 0 Base Tandem finder parameters 0 0 Tandem preset Qt::Horizontal 40 20 0 0 0 0 -1 QComboBox::AdjustToContents 10 Min period Qt::Horizontal 40 20 n 1 1000000 Max period Qt::Horizontal 40 20 n 1 1000000 1000000 Region to process Whole sequence true Qt::Horizontal 40 20 Selection Qt::Horizontal 40 20 Custom range false 100 0 Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter 1 - false 100 0 Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter 1 0 0 0 0 Qt::Vertical 20 357 Advanced Advanced parameters Repeats identity Qt::Horizontal 87 20 false 0 0 0 0 Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter true QAbstractSpinBox::UpDownArrows % 50 100 100 Algorithm Qt::Horizontal 40 20 QComboBox::AdjustToContents 10 Minimum tandem size Qt::Horizontal 40 20 3 1000000000 9 Minimum repeat count Qt::Horizontal 40 20 x 3 1000000000 Show overlapped tandems Qt::Vertical 20 24 Qt::Horizontal 40 20 Start true Cancel startButton clicked() FindTandemsDialog accept() 540 337 273 270 cancelButton clicked() FindTandemsDialog reject() 623 337 273 270 customRangeButton toggled(bool) customRangeEndBox setEnabled(bool) 391 286 613 287 customRangeButton toggled(bool) customRangeStartBox setEnabled(bool) 391 286 497 287 repeatLenComboBox activated(int) FindTandemsDialog presetSelected(int) 613 53 344 298 minPeriodBox valueChanged(int) FindTandemsDialog minPeriodChanged(int) 564 73 324 0 maxPeriodBox valueChanged(int) FindTandemsDialog maxPeriodChanged(int) 583 96 388 3 algoComboBox currentIndexChanged(int) FindTandemsDialog customization() 544 148 237 151 minTandemSizeBox editingFinished() FindTandemsDialog customization() 558 175 342 176 minRepeatsBox editingFinished() FindTandemsDialog customization() 558 197 235 201 identityBox editingFinished() FindTandemsDialog customization() 548 120 337 125 maxPeriodBox editingFinished() FindTandemsDialog customization() 544 98 238 97 minPeriodBox editingFinished() FindTandemsDialog customization() 547 70 336 70 presetSelected(int) minPeriodChanged(int) maxPeriodChanged(int) customization() ugene-1.9.8/src/plugins/repeat_finder/src/RFSArray.h0000644000175000017500000001021211651544324020763 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_RF_SARRAY_ALG_H_ #define _U2_RF_SARRAY_ALG_H_ #include #include #include #include #include #include "RFBase.h" namespace U2 { class RFSArrayWSubtask; // finds exact matches using SArray index class RFSArrayWAlgorithm : public RFAlgorithmBase { Q_OBJECT friend class RFSArrayWSubtask; public: RFSArrayWAlgorithm(RFResultsListener* rl, const char* seqX, int sizeX, const char* seqY, int sizeY, DNAAlphabet *al, int w); void prepare(); QList onSubTaskFinished(Task* subTask); void run(); /** 8x/GAP mem usage (GAP~=W/2)*/ void calculate(RFSArrayWSubtask* t); private: void run(RFSArrayWSubtask* t); void addResult(int a, int s, int l, RFSArrayWSubtask* t); void processBoundaryResults(); static int getWGap(int w); const char* arraySeq; const char* searchSeq; int ARRAY_SIZE; int SEARCH_SIZE; bool arrayIsX; int arrayPercent; QMutex boundaryMutex; quint32 bitMaskCharBitsNum; const quint32* bitMask; BitsTable bt; /** boundary results */ QVector bresults; CreateSArrayIndexTask* indexTask; int nThreads; }; class RFSArrayWSubtask : public Task, public SArrayIndex::SAISearchContext { Q_OBJECT friend class RFSArrayWAlgorithm; public: RFSArrayWSubtask(RFSArrayWAlgorithm* owner, int sStart, int sEnd, int _tid); void run(); RFSArrayWAlgorithm* owner; const int sStart; const int sEnd; const int tid; }; class CheckEdge { public: CheckEdge(const char* _posS = NULL, const char* _lastS = NULL, qint32 _diag = 0) : posS(_posS), lastS(_lastS), diag(_diag){ next = this; prev = this;} void fromChain() { prev->next = next; next->prev = prev; } void toChain(CheckEdge* chain) { next = chain; prev = chain->prev; chain->prev->next = this; chain->prev = this; } const char* posS; const char* lastS; CheckEdge* next; CheckEdge* prev; int diag; }; class EdgePool { public: EdgePool(int size) { pool.resize(size); for (int i = 0; i < size; i++) { pool[i] = new CheckEdge(); } nAvailable = size; } ~EdgePool() {qDeleteAll(pool);} CheckEdge* allocEdge(const char* posS, const char* lastS, int diag) { if (nAvailable != 0) { assert(nAvailable > 0); CheckEdge* edge = pool[--nAvailable]; edge->posS = posS; edge->lastS = lastS; edge->diag = diag; edge->next = NULL; edge->prev = edge; pool[nAvailable] = NULL; return edge; } return new CheckEdge(posS, lastS, diag); } void returnEdge(CheckEdge* e) { if (nAvailable != pool.size()) { assert(nAvailable < pool.size() && nAvailable >=0); assert(pool[nAvailable] == NULL); pool[nAvailable++] = e; } else { delete e; } } int nAvailable; QVector pool; }; }//namespace #endif ugene-1.9.8/src/plugins/repeat_finder/src/RepeatWorker.h0000644000175000017500000000373711651544324021762 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_REPEAT_WORKER_H_ #define _U2_REPEAT_WORKER_H_ #include #include #include "FindRepeatsTask.h" namespace U2 { namespace LocalWorkflow { class RepeatPrompter; typedef PrompterBase RepeatPrompterBase; class RepeatPrompter : public RepeatPrompterBase { Q_OBJECT public: RepeatPrompter(Actor* p = 0) : RepeatPrompterBase(p) {} protected: QString composeRichDoc(); }; class RepeatWorker : public BaseWorker { Q_OBJECT public: RepeatWorker(Actor* a); virtual void init(); virtual bool isReady(); virtual Task* tick(); virtual bool isDone(); virtual void cleanup(); private slots: void sl_taskFinished(); protected: CommunicationChannel *input, *output; QString resultName,transId; FindRepeatsTaskSettings cfg; }; class RepeatWorkerFactory : public DomainFactory { public: static const QString ACTOR_ID; static void init(); RepeatWorkerFactory() : DomainFactory(ACTOR_ID) {} virtual Worker* createWorker(Actor* a) {return new RepeatWorker(a);} }; } // Workflow namespace } // U2 namespace #endif ugene-1.9.8/src/plugins/repeat_finder/src/RepeatFinderPlugin.cpp0000644000175000017500000001047711651544324023431 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "RepeatFinderPlugin.h" #include "RepeatFinderTests.h" #include "RepeatWorker.h" #include "FindRepeatsDialog.h" #include "FindTandemsDialog.h" #include "RepeatQuery.h" #include "RFTaskFactory.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include namespace U2 { extern "C" Q_DECL_EXPORT Plugin* U2_PLUGIN_INIT_FUNC() { RepeatFinderPlugin* plug = new RepeatFinderPlugin(); return plug; } RepeatFinderPlugin::RepeatFinderPlugin() : Plugin(tr("Repeats Finder"), tr("Search for repeated elements in genetic sequences")), viewCtx(NULL) { if (AppContext::getMainWindow()) { viewCtx = new RepeatViewContext(this); viewCtx->init(); } LocalWorkflow::RepeatWorkerFactory::init(); QDActorPrototypeRegistry* pr = AppContext::getQDActorProtoRegistry(); pr->registerProto(new QDRepeatActorPrototype()); //tests GTestFormatRegistry* tfr = AppContext::getTestFramework()->getTestFormatRegistry(); XMLTestFormat *xmlTestFormat = qobject_cast(tfr->findFormat("XML")); assert(xmlTestFormat!=NULL); GAutoDeleteList* l = new GAutoDeleteList(this); l->qlist = RepeatFinderTests::createTestFactories(); foreach(XMLTestFactory* f, l->qlist) { bool res = xmlTestFormat->registerTestFactory(f); assert(res); Q_UNUSED(res); } RepeatFinderTaskFactoryRegistry *rfTfr = AppContext::getRepeatFinderTaskFactoryRegistry(); Q_ASSERT(rfTfr); rfTfr->registerFactory(new RFTaskFactory(), ""); } RepeatViewContext::RepeatViewContext(QObject* p) : GObjectViewWindowContext(p, AnnotatedDNAViewFactory::ID) { } void RepeatViewContext::initViewContext(GObjectView* v) { AnnotatedDNAView* av = qobject_cast(v); ADVGlobalAction* a = new ADVGlobalAction(av, QIcon(":repeat_finder/images/repeats.png"), tr("Find repeats..."), 40); a->addAlphabetFilter(DNAAlphabet_NUCL); connect(a, SIGNAL(triggered()), SLOT(sl_showDialog())); ADVGlobalAction* a2 = new ADVGlobalAction(av, QIcon(":repeat_finder/images/repeats_tandem.png"), tr("Find tandems..."), 41); a2->addAlphabetFilter(DNAAlphabet_NUCL); connect(a2, SIGNAL(triggered()), SLOT(sl_showTandemDialog())); } void RepeatViewContext::sl_showDialog() { QAction* a = (QAction*)sender(); GObjectViewAction* viewAction = qobject_cast(a); AnnotatedDNAView* av = qobject_cast(viewAction->getObjectView()); ADVSequenceObjectContext* sctx = av->getSequenceInFocus(); assert(sctx!=NULL && sctx->getAlphabet()->isNucleic()); FindRepeatsDialog d(sctx); d.exec(); } void RepeatViewContext::sl_showTandemDialog() { QAction* a = (QAction*)sender(); GObjectViewAction* viewAction = qobject_cast(a); AnnotatedDNAView* av = qobject_cast(viewAction->getObjectView()); ADVSequenceObjectContext* sctx = av->getSequenceInFocus(); assert(sctx!=NULL && sctx->getAlphabet()->isNucleic()); FindTandemsDialog d(sctx); d.exec(); } }//namespace ugene-1.9.8/src/plugins/repeat_finder/src/FindRepeatsTask.h0000644000175000017500000001074511651544324022374 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_FIND_REPEATS_TASK_H_ #define _U2_FIND_REPEATS_TASK_H_ #include "RFBase.h" #include #include #include #include #include namespace U2 { class FindRepeatsTaskSettings { public: FindRepeatsTaskSettings() : minLen(2), mismatches(0), minDist(0), maxDist(0), inverted(false), reportReflected(false), filterNested(true), maxResults(10*1000*100), algo(RFAlgorithm_Auto), nThreads(MAX_PARALLEL_SUBTASKS_AUTO){} int minLen; int mismatches; int minDist; int maxDist; bool inverted; bool reportReflected; bool filterNested; int maxResults; U2Region seqRegion, seq2Region; //all these regions are in global sequence coordinates QVector midRegionsToInclude; //reported repeat must contain one of these regions QVector midRegionsToExclude; //reported repeat must not contain none of these regions QVector allowedRegions; //reported repeat must fit one of these regions RFAlgorithm algo; int nThreads; void setIdentity(int percent) {mismatches = int((minLen / 100.0) * (100 - percent));} int getIdentity() const {return qBound(50, int(100.0 - mismatches * 100. /minLen), 100);} bool hasRegionFilters() const {return !midRegionsToInclude.isEmpty() || !midRegionsToExclude.isEmpty() || !allowedRegions.isEmpty();} }; //WARNING: this task is suitable only for a single sequence processing -> check addResults x/y sorting class RevComplSequenceTask; class FindRepeatsTask : public Task, public RFResultsListener { Q_OBJECT public: FindRepeatsTask(const FindRepeatsTaskSettings& s, const DNASequence& seq, const DNASequence& seq2); void run(); ReportResult report(); void cleanup(); QList onSubTaskFinished(Task* subTask); virtual void onResult(const RFResult& r); virtual void onResults(const QVector& v) ; QVector getResults() const {return results;} // used if createAnnotations == false const FindRepeatsTaskSettings& getSettings() const {return settings;} protected: void addResult(const RFResult& r); void _addResult(int x, int y, int l); bool isFilteredByRegions(const RFResult& r); RFAlgorithmBase* createRFTask(); void filterNestedRepeats(); FindRepeatsTaskSettings settings; DNASequence directSequence, directSequence2; QVector results; QMutex resultsLock; RevComplSequenceTask* revComplTask; RFAlgorithmBase* rfTask; quint64 startTime; }; class FindRepeatsToAnnotationsTask : public Task { Q_OBJECT public: FindRepeatsToAnnotationsTask(const FindRepeatsTaskSettings& s, const DNASequence& seq, const QString& annName, const QString& groupName, const GObjectReference& annObjRef); QList onSubTaskFinished(Task* subTask); QList importAnnotations(); private: QString annName; QString annGroup; GObjectReference annObjRef; FindRepeatsTask* findTask; }; class RevComplSequenceTask : public Task { Q_OBJECT public: RevComplSequenceTask(const DNASequence& s, const U2Region& reg); void run(); void cleanup(); DNASequence sequence; U2Region region; DNASequence complementSequence; }; } //namespace #endif ugene-1.9.8/src/plugins/repeat_finder/src/RFSArray.cpp0000644000175000017500000003063511651544324021331 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "RFSArray.h" #include "RFConstants.h" #include #include #include #include namespace U2 { RFSArrayWAlgorithm::RFSArrayWAlgorithm(RFResultsListener* rl, const char* seqX, int sizeX, const char* seqY, int sizeY, DNAAlphabet *al, int w) : RFAlgorithmBase(rl, seqX, sizeX, seqY, sizeY, al->getType(), w, w, TaskFlags_FOSCOE) { indexTask = NULL; nThreads = 1; int maxSize = qMax(SIZE_X, SIZE_Y); int minSize = qMin(SIZE_X, SIZE_Y); bool arrayIsMax = true; int gap = w - getWGap(w); int maxWithGapSize = maxSize/(gap+1); int minWithGapSize = minSize/(gap+1); if (maxSize > 1000*1000) { if (maxWithGapSize > minSize) { arrayIsMax=false; } else if (maxWithGapSize * 8 > 128*1000*1000) { //too many mem to use max -> using min will reduce mem usage arrayIsMax=false; } else { double searchK = 1.3; int tMinIndexed = minWithGapSize + searchK*maxSize; int tMaxIndexed = maxWithGapSize + searchK*minSize; if (tMinIndexed < tMaxIndexed) { arrayIsMax=false; } else if /*practical*/ ((gap < 16 && maxSize > 50*1000*1000) || (gap < 20 && maxSize > 100*1000*1000) || (gap < 25 && maxSize > 200*1000*1000) || (gap < 32 && maxSize > 400*1000*1000) || (gap < 37 && maxSize > 500*1000*1000)) { arrayIsMax = false; } } } arrayIsX = arrayIsMax && SIZE_X >=SIZE_Y; arraySeq = arrayIsX ? seqX : seqY; searchSeq = arrayIsX ? seqY : seqX; ARRAY_SIZE = arrayIsX ? SIZE_X: SIZE_Y; SEARCH_SIZE = arrayIsX ? SIZE_Y: SIZE_X; bitMaskCharBitsNum = bt.getBitMaskCharBitsNum(al->getType()); if ((al->getId() == BaseDNAAlphabetIds::NUCL_DNA_DEFAULT()) || (al->getId() == BaseDNAAlphabetIds::NUCL_RNA_DEFAULT())) { bitMask = bt.getBitMaskCharBits(al->getType()); } else { bitMask = NULL; } //single thread approximation (re-estimated in some algorithms) arrayPercent = int((ARRAY_SIZE / double(ARRAY_SIZE + SEARCH_SIZE)) * 100 / 5); //array creation time ~5 times faster than search } void RFSArrayWAlgorithm::prepare() { RFAlgorithmBase::prepare(); if (hasError()) { return; } int sSize = SEARCH_SIZE; nThreads = qBound(1, getNumParallelSubtasks(), SEARCH_SIZE / (20*1000)); //create index task that must be executed before all other tasks int matchSize = getWGap(WINDOW_SIZE); int gap = WINDOW_SIZE - matchSize; indexTask = new CreateSArrayIndexTask(arraySeq, ARRAY_SIZE, matchSize, unknownChar, bitMask, bitMaskCharBitsNum, gap); indexTask->setSubtaskProgressWeight(arrayPercent/100.0F); addSubTask(indexTask); setMaxParallelSubtasks(1); // create all other tasks that will use index int start = 0; int len = sSize / nThreads; for (int i = 0; i < nThreads; i++) { int sStart = start ? start - WINDOW_SIZE+1:0; int sEnd = i < nThreads - 1 ? start + len : sSize; RFSArrayWSubtask* t = new RFSArrayWSubtask(this, sStart, sEnd, i); t->setSubtaskProgressWeight((100 - arrayPercent) / (100.0F*nThreads)); addSubTask(t); start+=len; } } QList RFSArrayWAlgorithm::onSubTaskFinished(Task* subTask) { if (subTask == indexTask) { setMaxParallelSubtasks(nThreads); } return QList(); } void RFSArrayWAlgorithm::run(RFSArrayWSubtask* t) { calculate(t); } void RFSArrayWAlgorithm::run() { processBoundaryResults(); } void RFSArrayWAlgorithm::calculate(RFSArrayWSubtask* t) { quint64 t0 = GTimer::currentTimeMicros(); int W = WINDOW_SIZE; int W_GAP = getWGap(W); int GAP = W - W_GAP; int aSize = ARRAY_SIZE; int sSize = t->sEnd - t->sStart; const char* dataA = arraySeq; const char* dataS = searchSeq + t->sStart; const char* dataAEnd = dataA + aSize; const char* dataSEnd = dataS + sSize; const char* dataSCheckEnd= dataSEnd-W_GAP+1; int reportLen = sSize / (100 - arrayPercent); const char* reportPos = dataS + reportLen; EdgePool edgePool(3000); QVector chains(GAP+1); for (int i = 0 ;i < chains.size(); i++) { chains[i] = new CheckEdge(); } bool _useBitMask = bitMask!=NULL; SArrayIndex* index = indexTask->index; assert(index!=NULL); quint32 bitValue = 0xFFFFFFFF; quint32 charBitsNum = bitMaskCharBitsNum; int wCharsInMask = index->getCharsInMask(); const quint32* bm = bitMask; quint32 bitFilter = index->getBitFilter(); int nNew = 0; int nMatches = 0; int chainIdx = 0; int& progress = t->stateInfo.progress; for (const char* posS = dataS; posS < dataSCheckEnd && !stateInfo.cancelFlag; posS++, chainIdx = chainIdx == GAP ? 0 : chainIdx + 1) { if (posS >= reportPos) { progress++; reportPos += reportLen; } //validate edges from prev steps CheckEdge* chain = chains[chainIdx]; for (CheckEdge *edge = chain->next, *next = NULL; edge->lastS < posS && edge!=chain; edge = next) { next = edge->next; edge->fromChain(); // now extend result forward const char* lastS = edge->lastS; const char* lastA = dataA + (lastS-dataS) + edge->diag; for (;lastS < dataSEnd && lastA < dataAEnd && PCHAR_MATCHES(lastS, lastA); lastS++, lastA++){}; int len = lastS - edge->posS; if (len >= W) { int s = edge->posS - dataS; int a = edge->diag + s; addResult(a, s, len, t); } edgePool.returnEdge(edge); } //setup iterator if (_useBitMask ) { uchar c = *(posS + wCharsInMask - 1); bool bitValueCreated = true; if (c != unknownChar && posS!= dataS) { bitValue = ((bitValue< rebuild mask starting from the first W without unknown chars bitValue = 0; if (posS!=dataS) { posS+=wCharsInMask; } int cleanChars; for (cleanChars = 0; cleanChars < wCharsInMask && posS < dataSEnd; posS++) { if (*posS==unknownChar) { cleanChars = 0; bitValue = 0; } else { bitValue = (bitValue< 0; posS-=wCharsInMask; if(posS >= dataSCheckEnd) { break; } chainIdx=(posS-dataS)%(GAP+1); chain = chains[chainIdx]; } if (bitValueCreated && !index->findBit(t, bitValue, posS)) { // if there were not unknown chars, bitValue is initialized continue; } } else { if (!index->find(t, posS)) { continue; } } //iterate over sarray hits int s = posS - dataS; int a = 0; while ((a = index->nextArrSeqPos(t))!=-1) { nMatches++; if (reflective && s + t->sStart >= a) { continue; } //check if this hit can be merged with older one int diag = a-s; bool merged = false; CheckEdge* edge = chain->next; for (; edge!=chain; edge=edge->next) { if (edge->diag != diag) { continue; } if (edge->lastS < posS) { // gap while passing unknownChar break; } merged = true; edge->lastS = posS + W_GAP; edge->fromChain(); edge->toChain(chain);//making edge last break; } if (!merged) { //extend backward const char* edgeS = posS - 1; const char* edgeA = dataA + a - 1; for (;edgeS >= dataS && edgeA >= dataA && PCHAR_MATCHES(edgeS, edgeA); edgeS--, edgeA--){}; edgeS++; edge = edgePool.allocEdge(edgeS, posS + W_GAP, diag); edge->toChain(chain); } } } for (chainIdx=0; chainIdx < chains.size(); chainIdx++) { CheckEdge* chain = chains[chainIdx]; for (CheckEdge *edge = chain->next, *next = NULL; edge!=chain; edge = next) { //expand forward next = edge->next; const char* lastS = edge->lastS; const char* lastA = dataA + (lastS-dataS) + edge->diag; for (;lastS < dataSEnd && lastA < dataAEnd && PCHAR_MATCHES(lastS, lastA); lastS++, lastA++){} edge->lastS = lastS; int len = edge->lastS - edge->posS; int s = edge->posS - dataS; int a = edge->diag + s; if (len >= W) { addResult(a, s, len, t); } delete edge; } delete chains[chainIdx]; } quint64 t1 = GTimer::currentTimeMicros(); algoLog.trace(QString("Done, nNew %1, nMatches %2").arg(nNew).arg(nMatches)); algoLog.trace(QString("Done. Thread %1, Search time: %2 sec").arg(t->tid).arg(double(t1-t0)/(1000*1000))); } void RFSArrayWAlgorithm::processBoundaryResults() { //called after all subtasks finished -> merge boundary results RFResult* rs = bresults.data(); for (int j=0, n = bresults.size(); j < n; j++) { RFResult& rj = rs[j]; if (rj.l == -1) { //was merged continue; } int dj = rj.x - rj.y; for (int i = j + 1; i < n; i++) { RFResult& ri = rs[i]; if (ri.l == -1) { //was merged continue; } int di = ri.x - ri.y; if (dj != di) { continue; } if (ri.x + ri.l >= rj.x) { ri.l = rj.x + rj.l - ri.x; rj.l = -1; } else if (rj.x + rj.l >= ri.x) { rj.l = ri.x + ri.l - rj.x; ri.l = -1; } } } QVector mergedResults; for (int j=0, n = bresults.size(); j < n; j++) { const RFResult& rj = rs[j]; if (rj.l != -1) { mergedResults.append(rj); } } assert(checkResults(mergedResults)); addToResults(mergedResults); } // ast: add one hit in sequence void RFSArrayWAlgorithm::addResult(int a, int s, int l, RFSArrayWSubtask* t) { bool boundary = nThreads > 1 && (s == 0 || s + l == t->sEnd - t->sStart); s+=t->sStart; RFResult r((arrayIsX ? a : s), (arrayIsX ? s : a), l); if (boundary) { QMutexLocker ml(&boundaryMutex); bresults.append(r); } else { assert(checkResult(r)); addToResults(r); } } int RFSArrayWAlgorithm::getWGap(int W) { return W < 8? W : W < 10? W - 1: W < 12 ? W-2: W < 16 ? W-3: W < 20 ? W-4: W < 30 ? 16 : W/2+1; } ////////////////////////////////////////////////////////////////////////// //Worker RFSArrayWSubtask::RFSArrayWSubtask(RFSArrayWAlgorithm* _owner, int _sStart, int _sEnd, int _tid) : Task(tr("Find repeats subtask (suffix)"), TaskFlag_None), owner(_owner), sStart(_sStart), sEnd(_sEnd), tid(_tid) { tpm = Task::Progress_Manual; } void RFSArrayWSubtask::run() { owner->run(this); } } //namespace ugene-1.9.8/src/plugins/repeat_finder/src/RFTaskFactory.cpp0000644000175000017500000000450411651544324022356 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "RFTaskFactory.h" #include "RFBase.h" #include "FindRepeatsTask.h" namespace U2 { Task* RFTaskFactory::getTaskInstance( const RepeatFinderSettings& c) const { if (c.inverted) { return new ReverseAndCreateTask(c); } else { return RFAlgorithmBase::createTask( c.l, c.seqX, c.sizeX, c.seqY, c.sizeY, c.al, c.w, c.mismatches, c.alg, c.nThreads ); } } void RFTaskFactory::setRFResultsListener(Task* b, RFResultsListener* l) { RFAlgorithmBase* rfTask = qobject_cast(b); if (rfTask) { rfTask->setRFResultsListener(l); } } ReverseAndCreateTask::ReverseAndCreateTask(const RepeatFinderSettings& c) : Task("Make reverse sequence and find repeats", TaskFlag_NoRun) { this->c = c; revTask = new RevComplSequenceTask(DNASequence(QByteArray(c.seqX), c.al), U2Region(0, c.sizeX)); addSubTask(revTask); } QList ReverseAndCreateTask::onSubTaskFinished(Task* subTask) { QList subTasks; if (revTask == subTask) { Task *rfBase = RFAlgorithmBase::createTask( c.l, revTask->complementSequence.constData(), c.sizeX, c.seqY, c.sizeY, c.al, c.w, c.mismatches, c.alg, c.nThreads ); subTasks.append(rfBase); } return subTasks; } } // namespace ugene-1.9.8/src/plugins/repeat_finder/src/RepeatFinderPlugin.h0000644000175000017500000000261711651544324023073 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_REPEAT_PLUGIN_H_ #define _U2_REPEAT_PLUGIN_H_ #include #include namespace U2 { class RepeatFinderPlugin : public Plugin { Q_OBJECT public: RepeatFinderPlugin(); private: GObjectViewWindowContext* viewCtx; }; class RepeatViewContext: public GObjectViewWindowContext { Q_OBJECT public: RepeatViewContext(QObject* p); protected slots: void sl_showDialog(); void sl_showTandemDialog(); protected: virtual void initViewContext(GObjectView* view); }; } //namespace #endif ugene-1.9.8/src/plugins/repeat_finder/src/RF_BitMask.h0000644000175000017500000001416611651544324021267 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include #include #include #include #include // Attention! Works correctly only on little-endian systems! namespace U2{ inline void memset(void* _arr, const char _val, const size_t _size){ char* arr = (char*)_arr; for (size_t i=0;i<_size;i++){ arr[i]=_val; } } inline void memmove(void* _src, void* _dst, const size_t _size){ char* src = (char*)_src; char* dst = (char*)_dst; if (_src<_dst){ const char* srcend = src+_size; for (;src=src;){ *srclast--=*dstlast--; } } } } static const quint64 c01 = 0x0101010101010101LL; static const quint64 c1f = 0x1f1f1f1f1f1f1f1fLL; static const quint64 c03 = 0x0303030303030303LL; #define word1(a) w1(decode(a)) #define word2(a) w2(decode(a)) #define word3(a) w3(decode(a)) #define word4(a) w4(decode(a)) class BitMask{ BitMask():origSequence(NULL),origSequenceSize(0){} const char* origSequence; const quint32 origSequenceSize; quint64* bitSequence; quint32 bitSequenceSize; const static int SYMB_PER_INTEGER = sizeof(quint64)*8/2; //32 symbols per one request int maskSize; quint64 mask; quint32 currentPosition; int currBitPosition; quint64 currentPrefix; quint64 nextPrefix; public: BitMask(const char* sequence, const quint32 size):origSequence(sequence),origSequenceSize(size){ bitSequenceSize = origSequenceSize / SYMB_PER_INTEGER + 2; bitSequence = new quint64[bitSequenceSize]; quint64* bitSeqRunner = bitSequence; quint64* charSeqRunner = (quint64*)origSequence; //number of bytes multiple to 32 const quint64* charSeqRunnerStop = (quint64*)(origSequence + (origSequenceSize&(~0x1f))); //construct bitSequence while(charSeqRunner>62)&3]){ char numstr[10]; char c = decAlph[(bits[i]>>62)&3]; //throw std::exception((_itoa(i,numstr,10),numstr)); } } */ #endif } ~BitMask(){ delete[] bitSequence; bitSequence=NULL; } void setPrefixLen(const int prefLen){ Q_ASSERT(prefLen<=SYMB_PER_INTEGER); maskSize = 2*prefLen;//number of bits in prefix mask = ~((quint64)~0>>maskSize); } inline quint64 operator[](const quint64 index)const{ const quint64* localCell = bitSequence + index/SYMB_PER_INTEGER; const int bitPosition = index%SYMB_PER_INTEGER*2; const int& q0 = bitPosition; //const int q1 = (q0+maskSize)%(SYMB_PER_INTEGER*2); return q0==0 ? (mask & localCell[0]) : mask & ( (localCell[0]<>(64-q0)) ); } inline quint64 next(){ // not implemented Q_ASSERT(0); quint64 res = currentPrefix & mask; currentPrefix = (currentPrefix<<2) | (nextPrefix>>62); nextPrefix <<= 2; --currBitPosition; if (currBitPosition==0){ currBitPosition = 32; currentPosition++; currentPrefix = bitSequence[currentPosition]; nextPrefix = bitSequence[currentPosition+1]; } return res; } inline quint64 next()const{ return const_cast(this)->next(); } inline quint64 w1(const quint64& v) const { return ((v>>16)|(v>>56))&0x0000ffffLL; } inline quint64 w2(const quint64& v) const { return ((v>>0)|(v>>40))&0xffff0000; } inline quint64 w3(const quint64& v) const { return ((v<<16)|(v>>24))&0x0000ffff00000000LL; } inline quint64 w4(const quint64& v) const { return ((v<<32)|(v>>8))&0xffff000000000000LL; } inline quint64 decode(const quint64& str){ //decode symbols const quint64 r = (str & c1f) - c01; const quint64 s = r+(r<<1); const quint64 t = s^((s&c01)<<2); const quint64 u = (t>>1)&c03; //compress const quint64 v = u | (u<<10); return (v | (v<<20)) & 0xff000000ff000000LL; } }; ugene-1.9.8/src/plugins/repeat_finder/src/RFSArrayWK.h0000644000175000017500000000444411651544324021237 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_RF_SARRAYWK_ALG_H_ #define _U2_RF_SARRAYWK_ALG_H_ #include #include #include "RFBase.h" #include namespace U2 { class SArrayIndex; class RFSArrayWKSubtask; class RFRollingArray; class RFSArrayWKAlgorithm : public RFAlgorithmBase { Q_OBJECT friend class RFSArrayWKSubtask; public: RFSArrayWKAlgorithm(RFResultsListener* rl, const char* seqX, int sizeX, const char* seqY, int sizeY, DNAAlphabetType seqType, int w, int k); ~RFSArrayWKAlgorithm() {cleanup();} void prepare(); QList onSubTaskFinished(Task* subTask); void cleanup(); private: void addResult(int a, int s, int l); void calculate(RFSArrayWKSubtask* t); public: QVector diagOffsets; //holds start position for the last checked window int ARRAY_SIZE; int SEARCH_SIZE; const char *arraySeq; const char *searchSeq; bool arrayIsX; quint32 q; CreateSArrayIndexTask* indexTask; int nThreads; }; class RFSArrayWKSubtask : public Task, public SArrayIndex::SAISearchContext { Q_OBJECT friend class RFSArrayWKAlgorithm; public: RFSArrayWKSubtask(RFSArrayWKAlgorithm* owner, int _tid); virtual ~RFSArrayWKSubtask(){} void run(); RFSArrayWKAlgorithm* owner; const int tid; }; } //namespace #endif ugene-1.9.8/src/plugins/repeat_finder/src/FindRepeatsDialog.cpp0000644000175000017500000003345411651544324023226 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "FindRepeatsDialog.h" //#include "FindRepeatsTask.h" #include #include #include #include #include #include #include #include #include #include namespace U2 { #define SETTINGS_ROOT QString("plugin_find_repeats/") #define MIN_LEN_SETTINGS QString("min_len") #define IDENTITY_SETTINGS QString("identity") #define MIN_DIST_SETTINGS QString("min_dist") #define MAX_DIST_SETTINGS QString("max_dist") #define MIN_DIST_CHECK_SETTINGS QString("min_dist_check") #define MAX_DIST_CHECK_SETTINGS QString("max_dist_check") #define INVERT_CHECK_SETTINGS QString("invert_check") FindRepeatsTaskSettings FindRepeatsDialog::defaultSettings() { FindRepeatsTaskSettings res; Settings* s = AppContext::getSettings(); res.minLen = (s->getValue(SETTINGS_ROOT + MIN_LEN_SETTINGS, 5).toInt()); res.setIdentity(s->getValue(SETTINGS_ROOT + IDENTITY_SETTINGS, 100).toInt()); bool minDistCheck = (s->getValue(SETTINGS_ROOT + MIN_DIST_CHECK_SETTINGS, true).toBool()); bool maxDistCheck = (s->getValue(SETTINGS_ROOT + MAX_DIST_CHECK_SETTINGS, true).toBool()); res.minDist = !minDistCheck ? 0 : (s->getValue(SETTINGS_ROOT + MIN_DIST_SETTINGS, 0).toInt()); res.maxDist = !maxDistCheck ? 0 : (s->getValue(SETTINGS_ROOT + MAX_DIST_SETTINGS, 5000).toInt()); res.inverted = (s->getValue(SETTINGS_ROOT + INVERT_CHECK_SETTINGS, false).toBool()); return res; } FindRepeatsDialog::FindRepeatsDialog(ADVSequenceObjectContext* _sc) : QDialog(_sc->getAnnotatedDNAView()->getWidget()) { sc = _sc; setupUi(this); CreateAnnotationModel m; m.hideLocation = true; m.data->name = GBFeatureUtils::getKeyInfo(GBFeatureKey_repeat_unit).text; m.sequenceObjectRef = sc->getSequenceObject(); m.useUnloadedObjects = true; m.sequenceLen = sc->getSequenceObject()->getSequenceLen(); ac = new CreateAnnotationWidgetController(m, this); QWidget* caw = ac->getWidget(); QVBoxLayout* l = new QVBoxLayout(); l->setMargin(0); l->addWidget(caw); annotationsWidget->setLayout(l); annotationsWidget->setMinimumSize(caw->layout()->minimumSize()); algoCombo->addItem(tr("Auto"), RFAlgorithm_Auto); algoCombo->addItem(tr("Suffix index"), RFAlgorithm_Suffix); algoCombo->addItem(tr("Diagonals"), RFAlgorithm_Diagonal); bool hasSelection = !sc->getSequenceSelection()->isEmpty(); selectionRangeButton->setEnabled(hasSelection); selectionRangeButton->setChecked(hasSelection); int seqLen = sc->getSequenceLen(); Settings* s = AppContext::getSettings(); minLenBox->setValue(s->getValue(SETTINGS_ROOT + MIN_LEN_SETTINGS, qBound(5, seqLen / 100, 100)).toInt()); minLenBox->setMaximum(seqLen); identityBox->setValue(s->getValue(SETTINGS_ROOT + IDENTITY_SETTINGS, 100).toInt()); minDistBox->setValue(s->getValue(SETTINGS_ROOT + MIN_DIST_SETTINGS, 0).toInt()); maxDistBox->setValue(s->getValue(SETTINGS_ROOT + MAX_DIST_SETTINGS, 5000).toInt()); minDistCheck->setChecked(s->getValue(SETTINGS_ROOT + MIN_DIST_CHECK_SETTINGS, true).toBool()); maxDistCheck->setChecked(s->getValue(SETTINGS_ROOT + MAX_DIST_CHECK_SETTINGS, true).toBool()); invertCheck->setChecked(s->getValue(SETTINGS_ROOT + INVERT_CHECK_SETTINGS, false).toBool()); connect(minLenHeuristicsButton, SIGNAL(clicked()), SLOT(sl_minLenHeuristics())); connect(hundredPercentButton, SIGNAL(clicked()), SLOT(sl_hundredPercent())); connect(minLenBox, SIGNAL(valueChanged(int)), SLOT(sl_repeatParamsChanged(int))); connect(identityBox, SIGNAL(valueChanged(int)), SLOT(sl_repeatParamsChanged(int))); customRangeStartBox->setMaximum(seqLen); customRangeEndBox->setMaximum(seqLen); customRangeEndBox->setValue(seqLen); QStringList annotationNames = getAvailableAnnotationNames(); bool haveAnnotations = !annotationNames.isEmpty(); annotationFitCheck->setEnabled(haveAnnotations); annotationAroundKeepCheck->setEnabled(haveAnnotations); annotationAroundFilterCheck->setEnabled(haveAnnotations); if (haveAnnotations) { prepareAMenu(annotationFitButton, annotationFitEdit, annotationNames); prepareAMenu(annotationAroundKeepButton, annotationAroundKeepEdit, annotationNames); prepareAMenu(annotationAroundFilterButton, annotationAroundFilterEdit, annotationNames); } connect(customRangeStartBox, SIGNAL(valueChanged(int)), SLOT(sl_startRangeChanged(int))); connect(customRangeEndBox, SIGNAL(valueChanged(int)), SLOT(sl_endRangeChanged(int))); connect(minDistBox, SIGNAL(valueChanged(int)), SLOT(sl_minDistChanged(int))); connect(maxDistBox, SIGNAL(valueChanged(int)), SLOT(sl_maxDistChanged(int))); connect(minDistCheck, SIGNAL(toggled(bool)), SLOT(sl_minMaxToggle(bool))); connect(maxDistCheck, SIGNAL(toggled(bool)), SLOT(sl_minMaxToggle(bool))); updateStatus(); setWindowIcon(QIcon(":/ugene/images/ugene_16.png")); } void FindRepeatsDialog::prepareAMenu(QToolButton* tb, QLineEdit* le, const QStringList& names) { assert(!names.isEmpty()); QMenu* m = new QMenu(this); foreach(const QString& n, names) { QAction* a = new SetAnnotationNameAction(n, this, le); connect(a, SIGNAL(triggered()), SLOT(sl_setPredefinedAnnotationName())); m->addAction(a); } tb->setMenu(m); tb->setPopupMode(QToolButton::InstantPopup); tb->setIcon(QIcon(":/core/images/predefined_annotation_groups.png")); } QStringList FindRepeatsDialog::getAvailableAnnotationNames() const { QStringList res; const QSet& objs = sc->getAnnotationObjects(); QSet names; foreach(AnnotationTableObject* o, objs) { foreach(const Annotation* a, o->getAnnotations()) { names.insert(a->getAnnotationName()); } } res = names.toList(); res.sort(); return res; } void FindRepeatsDialog::sl_setPredefinedAnnotationName() { SetAnnotationNameAction* a = qobject_cast(sender()); QString text = a->text(); a->le->setText(text); } void FindRepeatsDialog::sl_minDistChanged(int i) { if (i > maxDistBox->value()) { maxDistBox->setValue(i); } updateStatus(); } void FindRepeatsDialog::sl_maxDistChanged(int i) { if (i < minDistBox->value()) { minDistBox->setValue(i); } updateStatus(); } void FindRepeatsDialog::sl_startRangeChanged(int i) { if (i > customRangeEndBox->value()) { customRangeEndBox->setValue(i); } updateStatus(); } void FindRepeatsDialog::sl_endRangeChanged(int i) { if (i < customRangeStartBox->value()) { customRangeStartBox->setValue(i); } updateStatus(); } bool FindRepeatsDialog::getRegions(QCheckBox* cb, QLineEdit* le, QVector& res) { bool enabled = cb->isChecked(); QString names = le->text(); if (!enabled || names.isEmpty()) { return true; } QSet aNames = names.split(',', QString::SkipEmptyParts).toSet(); const QSet aObjs = sc->getAnnotationObjects(); foreach(AnnotationTableObject* obj, aObjs) { foreach(Annotation* a, obj->getAnnotations()) { if (aNames.contains(a->getAnnotationName())) { res << a->getRegions(); } } } if (res.isEmpty()) { le->setFocus(); QMessageBox::critical(this, tr("Error"), tr("No annotations found: %1").arg(names)); return false; } return true; } U2Region FindRepeatsDialog::getActiveRange() const { U2Region range(0, sc->getSequenceLen()); if (selectionRangeButton->isChecked() && !sc->getSequenceSelection()->isEmpty()) { range = sc->getSequenceSelection()->getSelectedRegions().at(0); } else if (customRangeButton->isChecked()) { range.startPos = customRangeStartBox->value(); range.length = customRangeEndBox->value() - range.startPos; } return range; } void FindRepeatsDialog::accept() { int minLen = minLenBox->value(); int identPerc = identityBox->value(); int minDist = minDistCheck->isChecked() ? minDistBox->value() : 0; int maxDist = maxDistCheck->isChecked() ? maxDistBox->value(): sc->getSequenceLen(); bool inverted = invertCheck->isChecked(); U2Region range = getActiveRange(); assert(range.length > 0); assert(minDist <= maxDist); QString err = ac->validate(); if (!err.isEmpty()) { QMessageBox::critical(this, tr("Error"), err); return; } QVector fitRegions, aroundRegions, filterRegions; if (!getRegions(annotationFitCheck, annotationFitEdit, fitRegions) || !getRegions(annotationAroundKeepCheck, annotationAroundKeepEdit, aroundRegions) || !getRegions(annotationAroundFilterCheck, annotationAroundFilterEdit, filterRegions)) { return; } RFAlgorithm algo = algoCheck->isChecked() ? RFAlgorithm(algoCombo->itemData(algoCombo->currentIndex()).toInt()) : RFAlgorithm_Auto; ac->prepareAnnotationObject(); const DNASequence& seq = sc->getSequenceObject()->getDNASequence(); FindRepeatsTaskSettings settings; const CreateAnnotationModel& cam = ac->getModel(); settings.minLen = minLen; settings.mismatches = (100-identPerc) * minLen / 100; settings.inverted = inverted; settings.maxDist = maxDist; settings.minDist = minDist; settings.seqRegion = range; settings.algo = algo; settings.allowedRegions = fitRegions; settings.midRegionsToInclude = aroundRegions; settings.midRegionsToExclude = filterRegions; settings.reportReflected = false; settings.filterNested = !allowNestedCheck->isChecked(); FindRepeatsToAnnotationsTask* t = new FindRepeatsToAnnotationsTask(settings, seq, cam.data->name, cam.groupName, cam.annotationObjectRef); AppContext::getTaskScheduler()->registerTopLevelTask(t); saveState(); QDialog::accept(); } void FindRepeatsDialog::saveState() { Settings* s = AppContext::getSettings(); int minLen = minLenBox->value(); int identPerc = identityBox->value(); int minDist = minDistBox->value(); int maxDist = maxDistBox->value(); bool minDistChecked = minDistCheck->isChecked(); bool maxDistChecked = maxDistCheck->isChecked(); bool invertChecked = invertCheck->isChecked(); s->setValue(SETTINGS_ROOT + MIN_LEN_SETTINGS, minLen); s->setValue(SETTINGS_ROOT + IDENTITY_SETTINGS, identPerc); s->setValue(SETTINGS_ROOT + MIN_DIST_SETTINGS, minDist); s->setValue(SETTINGS_ROOT + MAX_DIST_SETTINGS, maxDist); s->setValue(SETTINGS_ROOT + MIN_DIST_CHECK_SETTINGS, minDistChecked); s->setValue(SETTINGS_ROOT + MAX_DIST_CHECK_SETTINGS, maxDistChecked); s->setValue(SETTINGS_ROOT + INVERT_CHECK_SETTINGS, invertChecked); } quint64 FindRepeatsDialog::areaSize() const { quint64 range = getActiveRange().length; if (range <=0) { return 0; } int minDist = minDistCheck->isChecked() ? minDistBox->value() : 0; int maxDist = maxDistCheck->isChecked() ? maxDistBox->value(): sc->getSequenceLen(); quint64 dRange = qMax(0, maxDist - minDist); quint64 res = range * dRange; return res; } int FindRepeatsDialog::estimateResultsCount() const { assert(identityBox->value() == 100); int len = minLenBox->value(); quint64 nVariations = areaSize(); //max possible results double variationsPerLen = pow(double(4), double(len)); quint64 res = quint64(nVariations / variationsPerLen); res = (res > 20) ? (res / 10) * 10 : res; res = (res > 200) ? (res / 100) * 100 : res; res = (res > 2000) ? (res / 1000) * 1000 : res; return res; } void FindRepeatsDialog::sl_minLenHeuristics() { identityBox->setValue(100); // formula used here: nVariations / lenVariations = wantedResCount (==1000) // where nVariations == area size // lenVariations = 4^len where len is result // so we have len = ln(nVariations/wantedResCount)/ln(4) double nVariations = areaSize(); double resCount = 1000; double len = log(nVariations / resCount) / log(double(4)); minLenBox->setValue((int)len); } void FindRepeatsDialog::sl_repeatParamsChanged(int v) { Q_UNUSED(v); updateStatus(); minLenBox->setSingleStep(minLenBox->value() >= 20 ? 10 : 1); } void FindRepeatsDialog::sl_minMaxToggle(bool v) { Q_UNUSED(v); updateStatus(); } void FindRepeatsDialog::updateStatus() { if (identityBox->value() == 100) { int r = estimateResultsCount(); statusLabel->setText(tr("Estimated repeats count: %1").arg(r)); statusLabel->setToolTip(tr("Estimated repeats count hint is based on the active settings and random sequence model")); } else { statusLabel->setText(""); statusLabel->setToolTip(""); } } void FindRepeatsDialog::sl_hundredPercent() { identityBox->setValue(100); } }//namespace ugene-1.9.8/src/plugins/repeat_finder/src/RFBase.cpp0000644000175000017500000001602111651544324020773 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "RFBase.h" #include "RFConstants.h" #include "RFSArray.h" #include "RFSArrayWK.h" #include "RFDiagonal.h" #include namespace U2 { //factory method RFAlgorithmBase* RFAlgorithmBase::createTask(RFResultsListener* l, const char *seqX, int sizeX, const char *seqY, int sizeY, DNAAlphabet *al, int w, int mismatches, RFAlgorithm alg, int nThreads) { assert(l!=NULL); assert(mismatches < w); algoLog.trace(QString("Repeat finder: sizex=%1, sizey=%2, alphabet=%3, w=%4, mismatches=%5, threads=%6") .arg(sizeX).arg(sizeY).arg(al->getType()).arg(w).arg(mismatches).arg(nThreads)); RFAlgorithmBase* res = NULL; if (alg == RFAlgorithm_Auto) { //alg = RFAlgorithm_Diagonal; //the slowest but tested better alg = RFAlgorithm_Suffix; } if (mismatches == 0) { if (alg == RFAlgorithm_Diagonal) { res = new RFDiagonalAlgorithmWK(l, seqX, sizeX, seqY, sizeY, al->getType(), w, w); } else { res = new RFSArrayWAlgorithm(l, seqX, sizeX, seqY, sizeY, al, w); } } else { int matches = w - mismatches; bool suffix = false; if (alg!=RFAlgorithm_Diagonal) { int q = w / (mismatches +1); if (q >= 4 || (q == 3 && (al->getType() ==DNAAlphabet_AMINO || al->getType() ==DNAAlphabet_RAW))) { suffix = true; } } algoLog.trace(QString("using %1 algorithm").arg(suffix ? "suffix" : "diagonal")); if (suffix) { res = new RFSArrayWKAlgorithm(l, seqX, sizeX, seqY, sizeY, al->getType(), w, matches); } else { res = new RFDiagonalAlgorithmWK(l, seqX, sizeX, seqY, sizeY, al->getType(), w, matches); } } res->setMaxParallelSubtasks(nThreads); return res; } ////////////////////////////////////////////////////////////////////////// // Task RFAlgorithmBase::RFAlgorithmBase(RFResultsListener* l, const char* seqx, int sizex, const char* seqy, int sizey, DNAAlphabetType seqType, int w, int k, TaskFlags flags) : Task(tr("Find repeats"), flags), seqX(seqx), seqY(seqy), SIZE_X(sizex), SIZE_Y(sizey), SEQ_TYPE(seqType), WINDOW_SIZE(w), K(k), C(w-k), resultsListener(l), reportReflected(true) { reflective = seqX == seqY && SIZE_X==SIZE_Y; unknownChar = seqType == DNAAlphabet_AMINO ? 'X' : seqType==DNAAlphabet_NUCL ? 'N' : '\0'; } void RFAlgorithmBase::setRFResultsListener(RFResultsListener* newListener) { resultsListener = newListener; } // adds single result to global results void RFAlgorithmBase::addToResults(const RFResult& r){ #ifdef _DEBUG // checkResult(r); #endif if (!resultsListener) { cancel(); return; } resultsListener->onResult(r); if (reflective && reportReflected) { assert(r.x!=r.y); resultsListener->onResult(RFResult(r.y, r.x, r.l)); } } // adds single result to global results void RFAlgorithmBase::addToResults(const QVector& results) { #ifdef _DEBUG // checkResults(results); #endif if (!resultsListener) { cancel(); return; } resultsListener->onResults(results); if (reflective && reportReflected) { QVector complResults; complResults.reserve(results.size()); foreach(const RFResult& r, results) { if (r.x == r.y) { assert(r.l == qMin(SIZE_X, SIZE_Y)); continue; } complResults.append(RFResult(r.y, r.x, r.l)); } resultsListener->onResults(complResults); } } void RFAlgorithmBase::prepare() { if (WINDOW_SIZE > qMin(SIZE_X, SIZE_Y)) { stateInfo.setError(tr("Repeat length is too large: %1, sequence size: %2").arg(WINDOW_SIZE).arg(qMin(SIZE_X, SIZE_Y))); return; } if (reflective && reportReflected) { assert(SIZE_X == SIZE_Y); resultsListener->onResult(RFResult(0, 0, SIZE_X)); } } bool RFAlgorithmBase::checkResults(const QVector& v) { //debug mode self-check routine foreach(const RFResult& r, v) { checkResult(r); } return true; } bool RFAlgorithmBase::checkResult(const RFResult& r) { assert(r.x >= 0 && r.y >=0 && r.x + r.l <= SIZE_X && r.y + r.l <= SIZE_Y); //check that there is mismatch before and after the result if (r.x > 0 && r.y > 0) { char cx = seqX[r.x - 1]; Q_UNUSED(cx); char cy = seqY[r.y - 1]; Q_UNUSED(cy); assert(!CHAR_MATCHES(cx, cy)); } if (r.x + r.l < int(SIZE_X) && r.y + r.l < int(SIZE_Y)) { char cx = seqX[r.x + r.l]; Q_UNUSED(cx); char cy = seqY[r.y + r.l]; Q_UNUSED(cy); assert(!CHAR_MATCHES(cx, cy)); } //check that result starts and ends with match if len > W if (r.l > int(WINDOW_SIZE)) { char cx = seqX[r.x]; char cy = seqY[r.y]; assert(CHAR_MATCHES(cx, cy));Q_UNUSED(cx);Q_UNUSED(cy); cx = seqX[r.x + r.l - 1]; cy = seqY[r.y + r.l - 1]; assert(CHAR_MATCHES(cx, cy)); } //check that for every window W inside of the result the match rate is valid int c = 0; for (int i=0; i < r.l; i++) { char cx = seqX[r.x + i]; char cy = seqY[r.y + i]; c+=CHAR_MATCHES(cx, cy) ? 0 : 1; if (i >= int(WINDOW_SIZE)) { char cxp = seqX[r.x + i - WINDOW_SIZE]; char cyp = seqY[r.y + i - WINDOW_SIZE]; c-=CHAR_MATCHES(cxp, cyp) ? 0 : 1; } assert(c <= C); } return true; } bool Tandem::extend (const Tandem& t){ int newEnd = qMax(offset+size, t.offset+t.size); offset = qMin(offset, t.offset); int oldSize = size; size = newEnd - offset; return size > oldSize; } bool Tandem::operator < (const Tandem& t) const{ return repeatLen * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "RepeatQuery.h" #include "FindRepeatsDialog.h" #include #include #include #include "U2Core/FailTask.h" #include #include #include namespace U2 { static const QString LEN_ATTR("min-length"); static const QString IDENTITY_ATTR("identity"); static const QString MIN_DIST_ATTR("min_dist"); static const QString MAX_DIST_ATTR("max_dist"); static const QString INVERT_ATTR("invert"); static const QString NESTED_ATTR("filter-nested"); static const QString ALGO_ATTR("algorithm"); static const QString THREADS_ATTR("threads"); static const QString MAX_LEN_ATTR("max-length"); QDRepeatActor::QDRepeatActor(QDActorPrototype const* proto) : QDActor(proto) { simmetric = true; cfg->setAnnotationKey("repeat_unit"); units["left"] = new QDSchemeUnit(this); units["right"] = new QDSchemeUnit(this); paramConstraints << new QDDistanceConstraint(units.values(), E2S, 0, 5000); } static const QString ALGO_SUFFIX = "suffix"; static const QString ALGO_DIAG = "diagonals"; static const QString ALGO_AUTO = "auto"; QList< QPair > QDRepeatActor::saveConfiguration() const { QList< QPair > res = QDActor::saveConfiguration(); Attribute* a = cfg->getParameter(ALGO_ATTR); for (int i=0; i& attr = res[i]; if (attr.first==a->getId()) { RFAlgorithm alg = RFAlgorithm(a->getAttributeValue()); switch (alg) { case RFAlgorithm_Auto: attr.second = ALGO_AUTO; break; case RFAlgorithm_Diagonal: attr.second = ALGO_DIAG; break; case RFAlgorithm_Suffix: attr.second = ALGO_SUFFIX; break; default: break; } } } return res; } void QDRepeatActor::loadConfiguration(const QList< QPair >& strMap) { QDActor::loadConfiguration(strMap); foreach(const StringAttribute& attr, strMap) { if (attr.first==ALGO_ATTR) { int alg; const QString& strandVal = attr.second; if (strandVal==ALGO_AUTO) { alg = 0; } else if (strandVal==ALGO_DIAG) { alg = 1; } else if (strandVal==ALGO_SUFFIX) { alg = 2; } cfg->setParameter(ALGO_ATTR, qVariantFromValue(alg)); } } } int QDRepeatActor::getMinResultLen() const { return cfg->getParameter(LEN_ATTR)->getAttributeValue(); } int QDRepeatActor::getMaxResultLen() const { return cfg->getParameter(MAX_LEN_ATTR)->getAttributeValue(); } QString QDRepeatActor::getText() const { QString inverted = cfg->getParameter(INVERT_ATTR)->getAttributePureValue().toBool() ? QDRepeatActor::tr("inverted") : QDRepeatActor::tr("direct"); inverted = QString("%2").arg(INVERT_ATTR).arg(inverted); int identity = cfg->getParameter(IDENTITY_ATTR)->getAttributeValue(); QString identityStr = QString("%2%").arg(IDENTITY_ATTR).arg(identity); int minLen = cfg->getParameter(LEN_ATTR)->getAttributeValue(); QString minLenStr = QString("%2").arg(LEN_ATTR).arg(minLen); QString doc = QDRepeatActor::tr("Finds %1 repeats." "
    Detects %2 identical repeats not shorter than %3 bps.") .arg(inverted) .arg(identityStr) .arg(minLenStr); return doc; } Task* QDRepeatActor::getAlgorithmTask(const QVector& location) { assert(scheme); Task* t = NULL; settings.algo = RFAlgorithm(cfg->getParameter(ALGO_ATTR)->getAttributeValue()); settings.minLen = cfg->getParameter(LEN_ATTR)->getAttributeValue(); int identity = cfg->getParameter(IDENTITY_ATTR)->getAttributeValue(); settings.setIdentity(identity); settings.nThreads = cfg->getParameter(THREADS_ATTR)->getAttributeValue(); settings.inverted = cfg->getParameter(INVERT_ATTR)->getAttributeValue(); settings.filterNested = cfg->getParameter(NESTED_ATTR)->getAttributeValue(); QDDistanceConstraint* dc = static_cast(paramConstraints.first()); settings.minDist = dc->getMin(); settings.maxDist = dc->getMax(); assert(identity <= 100 && identity >= 0); assert(settings.minDist>=0); DNASequenceObject* dna = scheme->getDNA(); if (!dna->getAlphabet()->isNucleic()) { return new FailTask(tr("Sequence should be nucleic")); } t = new Task(tr("RepeatQDTask"), TaskFlag_NoRun); foreach(const U2Region& r, location) { FindRepeatsTaskSettings stngs(settings); stngs.seqRegion = r; FindRepeatsToAnnotationsTask* st = new FindRepeatsToAnnotationsTask(stngs, dna->getDNASequence(), "repeat unit", QString(), GObjectReference()); t->addSubTask(st); repTasks.append(st); } connect(new TaskSignalMapper(t), SIGNAL(si_taskFinished(Task*)), SLOT(sl_onAlgorithmTaskFinished())); return t; } void QDRepeatActor::sl_onAlgorithmTaskFinished() { QList res; foreach(FindRepeatsToAnnotationsTask* frt, repTasks) { res = frt->importAnnotations(); } repTasks.clear(); foreach(const SharedAnnotationData& ad, res) { if (ad->location->regions[0].length > getMaxResultLen()) { continue; } ////////////////////////////////////////////////////////////////////////// QDResultUnit ru1(new QDResultUnitData); QDResultUnit ru2(new QDResultUnitData); ru1->quals = ad->qualifiers; ru2->quals = ad->qualifiers; ru1->region = ad->location->regions[0]; ru2->region = ad->location->regions[1]; ru1->owner = units.value("left"); ru2->owner = units.value("right"); ru1->strand = U2Strand::Direct; ru2->strand = U2Strand::Direct; QDResultGroup* g = new QDResultGroup(QDStrand_Both); g->add(ru1); g->add(ru2); results.append(g); ////////////////////////////////////////////////////////////////////////// /*if (scheme->getStrand()==QDStrand_DirectOnly) { addResults(ad, false); } else if (scheme->getStrand()==QDStrand_ComplementOnly) { addResults(ad, true); } else { addResults(ad, true); addResults(ad, false); }*/ } } //void QDRepeatActor::addResults( const SharedAnnotationData& ad, bool complement ) { // QDResultUnit ru1(new QDResultUnitData); // QDResultUnit ru2(new QDResultUnitData); // ru1->quals = ad->qualifiers; // ru2->quals = ad->qualifiers; // ru1->region = ad->location->regions[0]; // ru2->region = ad->location->regions[1]; // // QDResultGroup* g = NULL; // if (complement) { // ru1->owner = units.value("right"); // ru2->owner = units.value("left"); // ru1->strand = U2Strand::Complementary; // ru2->strand = U2Strand::Complementary; // g = new QDResultGroup(QDStrand_ComplementOnly); // } else { // ru1->owner = units.value("left"); // ru2->owner = units.value("right"); // ru1->strand = U2Strand::Direct; // ru2->strand = U2Strand::Direct; // g = new QDResultGroup(QDStrand_DirectOnly); // } // g->add(ru1); g->add(ru2); // results.append(g); //} QDRepeatActorPrototype::QDRepeatActorPrototype() { descriptor.setId("repeats"); descriptor.setDisplayName(QDRepeatActor::tr("Repeats")); descriptor.setDocumentation(QDRepeatActor::tr("Finds repeats in supplied sequence, stores found regions as annotations.")); Descriptor idd(IDENTITY_ATTR, QDRepeatActor::tr("Identity"), QDRepeatActor::tr("Repeats identity.")); Descriptor ld(LEN_ATTR, QDRepeatActor::tr("Min length"), QDRepeatActor::tr("Minimum length of repeats.")); Descriptor ind(INVERT_ATTR, QDRepeatActor::tr("Inverted"), QDRepeatActor::tr("Search for inverted repeats.")); Descriptor nsd(NESTED_ATTR, QDRepeatActor::tr("Filter nested"), QDRepeatActor::tr("Filter nested repeats.")); Descriptor ald(ALGO_ATTR, QDRepeatActor::tr("Algorithm"), QDRepeatActor::tr("Control over variations of algorithm.")); Descriptor thd(THREADS_ATTR, QDRepeatActor::tr("Parallel threads"), QDRepeatActor::tr("Number of parallel threads used for the task.")); Descriptor mld(MAX_LEN_ATTR, QDRepeatActor::tr("Max length"), QDRepeatActor::tr("Maximum length of repeats.")); FindRepeatsTaskSettings stngs = FindRepeatsDialog::defaultSettings(); attributes << new Attribute(ld, BaseTypes::NUM_TYPE(), true, stngs.minLen); attributes << new Attribute(idd, BaseTypes::NUM_TYPE(), false, stngs.getIdentity()); attributes << new Attribute(ind, BaseTypes::BOOL_TYPE(), false, stngs.inverted); attributes << new Attribute(nsd, BaseTypes::BOOL_TYPE(), false, stngs.filterNested); attributes << new Attribute(ald, BaseTypes::NUM_TYPE(), false, stngs.algo); attributes << new Attribute(thd, BaseTypes::NUM_TYPE(), false, stngs.nThreads); attributes << new Attribute(mld, BaseTypes::NUM_TYPE(), true, QDActor::DEFAULT_MAX_RESULT_LENGTH); QMap delegates; { QVariantMap m; m["minimum"] = 2; m["maximum"] = INT_MAX; m["suffix"] = L10N::suffixBp(); delegates[LEN_ATTR] = new SpinBoxDelegate(m); delegates[MAX_LEN_ATTR] = new SpinBoxDelegate(m); } { QVariantMap m; m["minimum"] = 50; m["maximum"] = 100; m["suffix"] = "%"; delegates[IDENTITY_ATTR] = new SpinBoxDelegate(m); } { QVariantMap m; m["specialValueText"] = "Auto"; delegates[THREADS_ATTR] = new SpinBoxDelegate(m); } { QVariantMap m; m["Auto"] = RFAlgorithm_Auto; m["Diagonals"] = RFAlgorithm_Diagonal; m["Suffix index"] = RFAlgorithm_Suffix; delegates[ALGO_ATTR] = new ComboBoxDelegate(m); } editor = new DelegateEditor(delegates); } }//namespace ugene-1.9.8/src/plugins/repeat_finder/src/RepeatQuery.h0000644000175000017500000000410011651544324021577 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_REPEAT_QUERY_H_ #define _U2_REPEAT_QUERY_H_ #include "FindRepeatsTask.h" #include "U2Lang/QDScheme.h" #include namespace U2 { class QDRepeatActor : public QDActor { Q_OBJECT public: int getMinResultLen() const; int getMaxResultLen() const; QString getText() const; Task* getAlgorithmTask(const QVector& location); QList< QPair > saveConfiguration() const; void loadConfiguration(const QList< QPair >& strMap); QColor defaultColor() const { return QColor(0x66,0xa3,0xd2); } virtual bool hasStrand() const { return false; } protected: QDRepeatActor(QDActorPrototype const* proto); friend class QDRepeatActorPrototype; private slots: void sl_onAlgorithmTaskFinished(); private: //void addResults( const SharedAnnotationData& ad, bool complement ); FindRepeatsTaskSettings settings; QList repTasks; }; class QDRepeatActorPrototype : public QDActorPrototype { public: QDRepeatActorPrototype(); QIcon getIcon() const { return QIcon(":repeat_finder/images/repeats.png"); } QDActor* createInstance() const { return new QDRepeatActor(this); } }; }//namespace #endif ugene-1.9.8/src/plugins/repeat_finder/src/RFDiagonal.cpp0000644000175000017500000001265211651544324021645 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "RFDiagonal.h" #include #include namespace U2 { RFDiagonalAlgorithmWK::RFDiagonalAlgorithmWK(RFResultsListener* rl, const char* seqX, int sizeX, const char* seqY, int sizeY, DNAAlphabetType seqType, int w, int k) : RFAlgorithmBase(rl, seqX, sizeX, seqY, sizeY, seqType, w, k) { setMaxParallelSubtasks(MAX_PARALLEL_SUBTASKS_AUTO); START_DIAG = SIZE_X - WINDOW_SIZE; END_DIAG = reflective ? 1 : -int(SIZE_Y - WINDOW_SIZE); } void RFDiagonalAlgorithmWK::prepare(){ RFAlgorithmBase::prepare(); if (hasError()) { return; } int nThreads = getNumParallelSubtasks(); for (int i = 0; i < nThreads; i++) { addSubTask(new RFDiagonalWKSubtask(this, i, nThreads)); } } ////////////////////////////////////////////////////////////////////////// /// RFDiagonalWKSubtask methods RFDiagonalWKSubtask::RFDiagonalWKSubtask(RFDiagonalAlgorithmWK* owner, int tn, int totalThreads) : Task(tr("Find repeats subtask (diagonal)"), TaskFlag_None), owner(owner), threadNum(tn), nThreads(totalThreads), dataX(owner->seqX), dataY(owner->seqY) { assert(totalThreads >= 1); //progress is approximated by area processed if ((owner->END_DIAG <= 0 && owner->START_DIAG <= 0) || (owner->END_DIAG >= 0 && owner->START_DIAG >= 0)) { int diagRange = owner->START_DIAG - owner->END_DIAG + 1; int medDiag = (owner->START_DIAG + owner->END_DIAG) / 2; areaS = quint64(getDiagLen(medDiag)) * diagRange / totalThreads; } else { int medDiag1 = owner->START_DIAG / 2; int medDiag2 = owner->END_DIAG / 2; quint64 areaS1 = quint64(getDiagLen(medDiag1)) * qAbs(owner->START_DIAG) / totalThreads; quint64 areaS2 = quint64(getDiagLen(medDiag2)) * qAbs(owner->END_DIAG) / totalThreads; areaS = areaS1 + areaS2; } assert(areaS > 0); currentS = 0; tpm = Task::Progress_Manual; } int RFDiagonalWKSubtask::getDiagLen(int d) const { return (d > 0) ? qMin(owner->SIZE_X - d, owner->SIZE_Y) : qMin(owner->SIZE_Y + d, owner->SIZE_X); } void RFDiagonalWKSubtask::run(){ int start_diag = owner->START_DIAG; int end_diag = owner->END_DIAG; int d = start_diag - threadNum; while (d >= end_diag && !isCanceled()) { int x = d > 0 ? d : 0; int y = d > 0 ? 0 : -d; processDiagonal(x, y); d -= nThreads; currentS+= getDiagLen(d); stateInfo.progress = qMin(100, int(100 * currentS / areaS)); } } void RFDiagonalWKSubtask::processDiagonal(int x, int y){ //make stack local copies int W = owner->WINDOW_SIZE; int C = owner->C; char unknownChar = owner->unknownChar; const char* xseq = dataX + x + W - 1; //point to the last pos in window -> will be checked first const char* yseq = dataY + y + W - 1; const char* xseqMax = dataX + owner->SIZE_X; const char* yseqMax = dataY + owner->SIZE_Y; assert(xseqMax - xseq >= 0 && yseqMax - yseq >= 0); while (xseq < xseqMax && yseq < yseqMax) { int c = 0; //number of mismatches for (const char* s = xseq - W; xseq > s && (c += (PCHAR_MATCHES(xseq, yseq) ? 0 : 1)) <= C; xseq--, yseq--){} if (c > C) { xseq += W; yseq += W; continue; } assert(xseq < dataX || yseq < dataY || !PCHAR_MATCHES(xseq, yseq)); xseq++; yseq++; int len = processMatch(xseq, yseq, xseqMax, yseqMax, c); assert(len >= W); while (len > W && !PCHAR_MATCHES(xseq, yseq)){len--; xseq++; yseq++;} //ensure that match with len > W starts with hit int step = len; while (len > W && !PCHAR_MATCHES(xseq + len - 1, yseq + len - 1)){len--;} //ensure that match with len > W ends with hit RFResult r(xseq - dataX, yseq - dataY, len); assert(owner->checkResult(r)); diagResults.append(r); xseq += step + 1; yseq += step + 1; } if (!diagResults.isEmpty()) { owner->addToResults(diagResults); diagResults.clear(); } } int RFDiagonalWKSubtask::processMatch(const char* x, const char* y, const char* xEnd, const char* yEnd, int c) { int W = owner->WINDOW_SIZE; int K = owner->K; int k = W - c; char unknownChar = owner->unknownChar; const char *xr = x + W, *yr = y + W; for (; xr < xEnd && yr < yEnd; ++xr, ++yr) { int pushV = PCHAR_MATCHES(xr, yr) ? 1 : 0; int popV = PCHAR_MATCHES(xr-W, yr-W) ? 1 : 0; k += pushV - popV; if (k < K) { //end of the match break; } } return xr - x; } } //namespace ugene-1.9.8/src/plugins/repeat_finder/src/RF_SArray_TandemFinder.h0000644000175000017500000001505611651544324023555 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef RF_SARRAYTANDEMFINDER_H #define RF_SARRAYTANDEMFINDER_H #include #include #include #include #include #include #include #include #include #include #include "RF_SuffixArray.h" #include "RFBase.h" namespace U2 { namespace TSConstants{ enum TSAlgo{AlgoSuffix=0, AlgoSuffixBinary=1}; enum TSPreset{PresetAll=0, PresetMicro=1, PresetMini=2, PresetBigPeriod=3, PresetCustom=4}; } class FindTandemsTaskSettings { public: static const int DEFAULT_MIN_TANDEM_SIZE; static const int DEFAULT_MIN_REPEAT_COUNT; static const TSConstants::TSAlgo DEFAULT_ALGO = TSConstants::AlgoSuffixBinary; public: FindTandemsTaskSettings() : minPeriod(1), maxPeriod(INT_MAX), minTandemSize(DEFAULT_MIN_TANDEM_SIZE), minRepeatCount(DEFAULT_MIN_REPEAT_COUNT), accuracy(0), maxResults(10*1000*100), showOverlappedTandems(false), algo(DEFAULT_ALGO), nThreads(MAX_PARALLEL_SUBTASKS_AUTO) {} int minPeriod; int maxPeriod; int minTandemSize; int minRepeatCount; int accuracy; int maxResults; U2Region seqRegion; bool showOverlappedTandems; TSConstants::TSAlgo algo; int nThreads; }; class FindTandemsToAnnotationsTask : public Task { Q_OBJECT public: FindTandemsToAnnotationsTask(const FindTandemsTaskSettings& s, const DNASequence& seq, const QString& annName, const QString& groupName, const GObjectReference& annObjRef); QList onSubTaskFinished(Task* subTask); QList importTandemAnnotations(const QList& tandems, const quint32 seqStart, const bool showOverlapped); private: QString annName; QString annGroup; GObjectReference annObjRef; }; class TandemFinder: public Task, public SequenceWalkerCallback { Q_OBJECT public: TandemFinder(const FindTandemsTaskSettings& s, const DNASequence& seq); void prepare(); void run(); const QList& getResults(){return foundTandems;} const FindTandemsTaskSettings& getSettings() const{return settings;} const static quint32 maxCheckPeriod = 1024; //max period is 1k protected: //main sequence char* sequence; FindTandemsTaskSettings settings; QMutex tandemsAccessMutex; QList foundTandems; QList onSubTaskFinished(Task* subTask); void onRegion(SequenceWalkerSubtask* t, TaskStateInfo& ti); private: QMutex subtasksQueue; quint32 regionCount; quint64 startTime; QList regionTasks; }; class TandemFinder_Region: public Task{ Q_OBJECT public: TandemFinder_Region(const int regionId, const char* _sequence, const quint32 _seqSize, const quint64 _regionOffset, const FindTandemsTaskSettings& _settings): Task(tr("Find tandems in %1 region").arg(regionId), TaskFlags_NR_FOSCOE), sequence(_sequence),seqSize(_seqSize),id(regionId),regionOffset(_regionOffset),settings(_settings) {} ~TandemFinder_Region(); const QList getResult(){ QMutexLocker tandemsAccessLocker(&tandemsAccessMutex); return foundTandems; }; quint64 getRegionId()const{ return id;} quint64 getRegionOffset()const{ return regionOffset;} void prepare(); protected: //main sequence const char* sequence; const long seqSize; QList onSubTaskFinished(Task* subTask); private: const int id; const quint64 regionOffset; const FindTandemsTaskSettings& settings; QList foundTandems; QMutex tandemsAccessMutex; friend class ExactSizedTandemFinder; friend class LargeSizedTandemFinder; void addResult(const Tandem& tandem); void addResults(const QMap& tandems); }; class ConcreteTandemFinder: public Task{ Q_OBJECT public: ConcreteTandemFinder(QString taskName, const char* _sequence, const long _seqSize, const FindTandemsTaskSettings& _settings, const int _analysisSize); ~ConcreteTandemFinder(){}; void prepare(); void cleanup(); protected: //main sequence const char* sequence; const int seqSize; SArrayIndex* index; SuffixArray* suffixArray; const FindTandemsTaskSettings& settings; const int prefixLength; const quint32 suffArrSize; QList onSubTaskFinished(Task* subTask); private: const BitsTable bitsTable; protected: QMap rawTandems; }; class ExactSizedTandemFinder: public ConcreteTandemFinder{ Q_OBJECT public: ExactSizedTandemFinder(const char* _sequence, const long _seqSize, const FindTandemsTaskSettings& _settings, const int _analysisSize); ~ExactSizedTandemFinder(); void run(); private: quint32* checkAndSpreadTandem(const quint32* tandemStart, const quint32* tandemLast, quint32 repeatLen); quint32* checkAndSpreadTandem_bv(const quint32* tandemStart, const quint32* tandemLast, quint32 repeatLen); bool comparePrefixChars(const char*,const char*); }; class LargeSizedTandemFinder: public ConcreteTandemFinder{ Q_OBJECT public: LargeSizedTandemFinder(const char* _sequence, const long _seqSize, const FindTandemsTaskSettings& _settings, const int _analysisSize); ~LargeSizedTandemFinder(); void run(); private: quint32* checkAndSpreadTandem(const quint32* tandemStart, const quint32* tandemLast, const unsigned repeatLen); quint32* checkAndSpreadTandem_bv(const quint32* tandemStart, const quint32* tandemLast, const unsigned repeatLen); bool comparePrefixChars(const char*,const char*); }; } //namespace #endif // RF_SARRAYTANDEMFINDER_H ugene-1.9.8/src/plugins/repeat_finder/src/FindRepeatsTask.cpp0000644000175000017500000003055011651544324022723 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "FindRepeatsTask.h" #include "RFBase.h" #include "RFDiagonal.h" #include "RFConstants.h" #include #include #include #include #include #include #include #include #include namespace U2 { RevComplSequenceTask::RevComplSequenceTask(const DNASequence& s, const U2Region& reg) : Task(tr("Reverse complement sequence"), TaskFlag_None), sequence(s), region(reg) { } void RevComplSequenceTask::run() { DNATranslation* complT = AppContext::getDNATranslationRegistry()->lookupComplementTranslation(sequence.alphabet); if (complT == NULL) { stateInfo.setError(tr("Can't find complement translation for alphabet: %1").arg(sequence.alphabet->getId())); return; } complementSequence.alphabet = complT->getDstAlphabet(); complementSequence.seq.resize(region.length); const char* src = sequence.constData(); char* dst = complementSequence.seq.data(); complT->translate(src + region.startPos, region.length, dst, region.length); TextUtils::reverse(dst, region.length); } void RevComplSequenceTask::cleanup() { sequence.seq.clear(); complementSequence.seq.clear(); } FindRepeatsTask::FindRepeatsTask(const FindRepeatsTaskSettings& s, const DNASequence& seq, const DNASequence& seq2) : Task(tr("Find repeats in a single sequence"), TaskFlags_FOSCOE), settings(s), directSequence(seq), directSequence2(seq2) { GCOUNTER( cvar, tvar, "FindRepeatsTask" ); if (settings.seqRegion.length == 0) { settings.seqRegion= U2Region(0, directSequence.length()); } if (seq.constData() == seq2.constData()) { settings.seq2Region = settings.seqRegion; } else { settings.seq2Region = U2Region(0, directSequence2.length()); } revComplTask = NULL; rfTask = NULL; startTime = GTimer::currentTimeMicros(); if (settings.inverted) { stateInfo.setDescription(tr("Rev-complementing sequence")); assert(directSequence.alphabet->isNucleic()); revComplTask = new RevComplSequenceTask(directSequence, settings.seqRegion); revComplTask->setSubtaskProgressWeight(0); addSubTask(revComplTask); } else { rfTask = createRFTask(); addSubTask(rfTask); } } QList FindRepeatsTask::onSubTaskFinished(Task* subTask) { QList res; if (hasError() || isCanceled()) { return res; } if (subTask == revComplTask) { startTime = GTimer::currentTimeMicros(); rfTask = createRFTask(); res.append(rfTask); } return res; } RFAlgorithmBase* FindRepeatsTask::createRFTask() { stateInfo.setDescription(tr("Searching repeats ...")); const char* seqX = directSequence.constData() + settings.seqRegion.startPos; const char* seqY = revComplTask == NULL ? seqX : revComplTask->complementSequence.constData(); int seqXLen = settings.seqRegion.length; int seqYLen = settings.seqRegion.length; if (directSequence.constData() != directSequence2.constData()) { seqY = directSequence2.constData(); seqYLen = directSequence2.length(); } RFAlgorithmBase* t = RFAlgorithmBase::createTask(this, seqX, seqXLen, seqY, seqYLen, directSequence.alphabet, settings.minLen, settings.mismatches, settings.algo, settings.nThreads); t->setReportReflected(settings.reportReflected); return t; } void FindRepeatsTask::run() { if (settings.filterNested) { stateInfo.setDescription(tr("Filtering nested results")); filterNestedRepeats(); } } Task::ReportResult FindRepeatsTask::report() { stateInfo.setDescription(""); if (hasError()) { return ReportResult_Finished; } quint64 endTime = GTimer::currentTimeMicros(); perfLog.details(tr("Repeat search time %1 sec").arg((endTime-startTime)/(1000*1000.0))); return ReportResult_Finished; } void FindRepeatsTask::filterNestedRepeats() { //if one repeats fits into another repeat -> filter it quint64 t1 = GTimer::currentTimeMicros(); qSort(results); bool changed = false; int extraLen = settings.mismatches; //extra len added to repeat region to search for duplicates for (int i=0, n = results.size(); i < n; i++) { RFResult& ri = results[i]; if (ri.l == -1) { //this result was filtered continue; } for (int j=i+1; j < n; j++) { RFResult& rj = results[j]; assert(rj.x >= ri.x); if (rj.l == -1) {//was filtered continue; } if (rj.x > ri.x + ri.l) { //no more intersection will found with later repeats in first region break; } U2Region ri1(ri.x, ri.l), ri2(ri.y, ri.l), rj1(rj.x, rj.l), rj2(rj.y, rj.l); bool filteri = false, filterj = false; if (rj.l > ri.l) { rj1.startPos-=extraLen; rj1.length+=2*extraLen; rj2.startPos-=extraLen; rj2.length+=2*extraLen; filteri = rj1.contains(ri1) && rj2.contains(ri2); } else { ri1.startPos-=extraLen; ri1.length+=2*extraLen; ri2.startPos-=extraLen; ri2.length+=2*extraLen; filterj = ri1.contains(rj1) && ri2.contains(rj2); } if (filteri || filterj) { changed = true; if (filteri) { ri.l = -1; break; } else { rj.l = -1; } } } } int nBefore = results.size(); if (changed) { QVector prev = results; results.clear(); foreach(const RFResult& r, prev) { if (r.l!=-1) { results.append(r); } } } int nAfter = results.size(); quint64 t2 = GTimer::currentTimeMicros(); perfLog.details(tr("Nested repeats filtering time %1 sec, results before: %2, filtered: %3, after %4") .arg(double((t2-t1))/(1000*1000)).arg(nBefore).arg(nBefore - nAfter).arg(nAfter)); } void FindRepeatsTask::cleanup() { directSequence.seq.clear(); results.clear(); } void FindRepeatsTask::addResult(const RFResult& r) { int x = r.x + settings.seqRegion.startPos; int y = settings.inverted ? settings.seqRegion.endPos() - r.y - r.l : r.y + settings.seq2Region.startPos; int l = r.l; assert(x >= settings.seqRegion.startPos && x + r.l <= settings.seqRegion.endPos()); assert(y >= settings.seq2Region.startPos && y + r.l <= settings.seq2Region.endPos()); int dist = qAbs(x - y) - l; if (dist < settings.minDist || dist > settings.maxDist) { // dist < 0 -> overlapping repeat. Try to reduce its length to fit min/max constraints if possible if (dist < 0) { // match if prefixes fits dist int plen = qAbs(x - y) - settings.minDist; if (plen >= settings.minLen) { _addResult(x, y, plen); } // match if suffixes fits dist int dlen = settings.minDist - dist; if (l - dlen >= settings.minLen) { _addResult(x + dlen, y + dlen, l - dlen); } } return; } _addResult(x, y, l); } void FindRepeatsTask::_addResult(int x, int y, int l) { if (settings.reportReflected || x <= y) { results.append(RFResult(x, y, l)); } else { results.append(RFResult(y, x, l)); } } void FindRepeatsTask::onResult(const RFResult& r) { if (settings.hasRegionFilters() && isFilteredByRegions(r)) { return; } QMutexLocker ml(&resultsLock); addResult(r); } void FindRepeatsTask::onResults(const QVector& results) { QVector filteredResults = results; if (settings.hasRegionFilters()) { filteredResults.clear(); foreach(const RFResult& r, results) { if (!isFilteredByRegions(r)) { filteredResults.append(r); } } } QMutexLocker ml(&resultsLock); foreach(const RFResult& r, filteredResults) { addResult(r); } } bool FindRepeatsTask::isFilteredByRegions(const RFResult& r) { int x1 = r.x + settings.seqRegion.startPos; int y1 = settings.inverted ? settings.seqRegion.endPos() - r.y - 1 : r.y + settings.seqRegion.startPos; if (x1 > y1) { qSwap(x1, y1); } int x2 = x1 + r.l; int y2 = y1 + r.l; //check mid range includes if (!settings.midRegionsToInclude.isEmpty()) { bool checkOk = false; foreach(const U2Region& r, settings.midRegionsToInclude) { if (r.startPos >= x2 && r.endPos() <= y1) { checkOk = true; break; } } if (!checkOk) { return true; } } //check mid range excludes if (!settings.midRegionsToExclude.isEmpty()) { foreach(const U2Region& r, settings.midRegionsToExclude) { if (r.intersects(U2Region(x1, y2-x1))) { return true; } } } //check allowed regions if (!settings.allowedRegions.isEmpty()) { bool checkOk = false; foreach(const U2Region& r, settings.allowedRegions) { if (r.startPos <= x1 && r.endPos() >= y2) { checkOk = true; break; } } if (!checkOk) { return true; } } return false; } FindRepeatsToAnnotationsTask::FindRepeatsToAnnotationsTask(const FindRepeatsTaskSettings& s, const DNASequence& seq, const QString& _an, const QString& _gn, const GObjectReference& _aor) : Task(tr("Find repeats to annotations"), TaskFlags_NR_FOSCOE), annName(_an), annGroup(_gn), annObjRef(_aor), findTask(NULL) { setVerboseLogMode(true); if (annObjRef.isValid()) { LoadUnloadedDocumentTask::addLoadingSubtask(this, LoadDocumentTaskConfig(true, annObjRef, new LDTObjectFactory(this))); } addSubTask(findTask = new FindRepeatsTask(s, seq, seq)); } QList FindRepeatsToAnnotationsTask::onSubTaskFinished(Task* subTask) { QList res; if (hasError() || isCanceled()) { return res; } if (subTask == findTask && annObjRef.isValid()) { QList annotations = importAnnotations(); if (!annotations.isEmpty()) { algoLog.info(tr("Found %1 repeat regions").arg(annotations.size())); Task* createTask = new CreateAnnotationsTask(annObjRef, annGroup, annotations); createTask->setSubtaskProgressWeight(0); res.append(createTask); } } return res; } QList FindRepeatsToAnnotationsTask::importAnnotations() { QList res; foreach(const RFResult& r, findTask->getResults()) { SharedAnnotationData ad(new AnnotationData()); ad->name = annName; U2Region l1(r.x, r.l); U2Region l2(r.y, r.l); if (l1.startPos <= l2.startPos) { ad->location->regions << l1 << l2; } else { ad->location->regions << l2 << l1; } int dist = qAbs(r.x - r.y) - r.l; ad->qualifiers.append(U2Qualifier("repeat_len", QString::number(r.l))); ad->qualifiers.append(U2Qualifier("repeat_dist", QString::number(dist))); if (findTask->getSettings().inverted) { ad->qualifiers.append(U2Qualifier("rpt_type", "inverted")); } res.append(ad); } return res; } }//namespace ugene-1.9.8/src/plugins/repeat_finder/src/RFTaskFactory.h0000644000175000017500000000323411651544324022022 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_REPEAT_FINDER_ALG_IMPL_H_ #define _U2_REPEAT_FINDER_ALG_IMPL_H_ #include #include #include #include namespace U2 { class RevComplSequenceTask; class RFTaskFactory: public RepeatFinderTaskFactory { public: RFTaskFactory() {}; virtual Task* getTaskInstance(const RepeatFinderSettings& config) const; virtual void setRFResultsListener(Task*, RFResultsListener*); }; /** Reverses X sequence and runs repeat finder task */ class ReverseAndCreateTask : public Task { Q_OBJECT public: ReverseAndCreateTask(const RepeatFinderSettings& c); QList onSubTaskFinished(Task* subTask); private: RepeatFinderSettings c; RevComplSequenceTask *revTask; }; } // namespace #endif ugene-1.9.8/src/plugins/repeat_finder/transl/0000755000175000017500000000000011651544324017701 5ustar ilyailyaugene-1.9.8/src/plugins/repeat_finder/transl/russian.ts0000644000175000017500000012305711651544324021745 0ustar ilyailya FindRepeatsDialog Find repeats Поиск повторов Repeat parameters Параметры Minimum repeat length Мин длина повторов bp нк Heuristic based selection of repeat length so the number of repeats in the sequence will not exceed 1000 Эвристический подбор длины повторов, с тем чтобы кол-во повторов в последовательности не превысило 1000 1k Repeats identity Идентичность повторов % Resets repeats identity to 100% Сбросить к 100% 100 Minimum distance between repeats Мин дистанция между повторами Maximum distance between repeats Макс дистанция между повторами Advanced Дополнительные настройки Advanced parameters Дополнительные параметры Custom algorithm Выбранный алгоритм Search only for repeats that lie inside of an annotated region Искать только те повторы, что лежат внутри аннотированного региона Search only for repeats that have an annotated region inside Искать только те повторы, что содержат аннотированный регион Filter repeats that have an annotated region inside Исключить из поиска повторы, содержащие аннотированный регион Search only repeats inside of annotated region Искать повторы только внутри аннотированных регионов ... Search only repeats with annotated region inside Искать только повторы с аннотированными регионами внутри Filter repeats with annotated region inside Исключать повторы с аннотированными регионами Do not filter nested repeats Не исключать вложенные повторы Search for inverted repeats Искать инвертированные повторы Region to process Регион поиска Base Основные настройки Repeat finder parameters Параметры поиска повторов Whole sequence Вся последовательность Selection Выбранный Custom range Указанный - Start Искать Cancel Отменить FindTandemsDialog Find tandems Поиск тандемов Repeat parameters Параметры Tandem preset Предустановки тандемов Min period Мин период n н Max period Макс период Advanced Дополнительные настройки Advanced parameters Дополнительные параметры Repeats identity Идентичность повторов % % Algorithm Алгоритм Minimum tandem size Минимальный размер тандема Minimum repeat count Минимальное число повторений x Show overlapped tandems Показать перекрывающиеся тандемы Region to process Регион поиска Base Основные настройки Tandem finder parameters Параметры поиска тандемов Whole sequence Вся последовательность Selection Выбранный Custom range Указанный - Start Искать Cancel Отменить U2::ExactSizedTandemFinder Find %1-period tandems Поиск %1-периодных тандемов U2::FindRepeatsDialog Auto Автовыбор Suffix index Суффиксный индекс Diagonals Диагональный Error Проблема No annotations found: %1 Аннотации не найдены: %1 Estimated repeats count: %1 Оценка возможного кол-ва результатов: %1 Estimated repeats count hint is based on the active settings and random sequence model Оценка основана на текущих параметрах поиска и модели случайной последовательности U2::FindRepeatsTask Find repeats in a single sequence Поиск повторов в одиночной последовательности Rev-complementing sequence Перевод последовательности к комплементарной Searching repeats ... Поиск повторов ... Filtering nested results Фильтрация результатов Repeat search time %1 sec Время поиска повторов: %1 сек Nested repeats filtering time %1 sec, results before: %2, filtered: %3, after %4 Время фильтрации вложенных повторов: %1 сек. Результатов было %2, отброшено %3, осталось %4 U2::FindRepeatsToAnnotationsTask Find repeats to annotations Сохранение повторов в аннотации Found %1 repeat regions Найдено повторов: %1 U2::FindTandemsDialog Suffix array Суффиксный массив Suffix array (optimized) Суффиксный массив (оптимизированный) All Все Micro-satellites Микро-сателлиты Mini-satellites Мини-сателлиты Big-period tandems Танемы с большим периодом Custom Особые Error Проблема No annotations found: %1 Аннотации не найдены: %1 Estimated repeats count: %1 Оценка возможного кол-ва результатов: %1 Estimated repeats count hint is based on the active settings and random sequence model Оценка основана на текущих параметрах поиска и модели случайной последовательности U2::FindTandemsToAnnotationsTask Find repeats to annotations Сохранение повторов в аннотации Found %1 repeat regions Найдено повторов: %1 U2::LargeSizedTandemFinder Find big-period tandems Поиск тандемов с большим периодом U2::LocalWorkflow::RepeatPrompter from %1 из %1 inverted инвертированные direct прямые For each sequence<u>%1</u>, find <u>%2</u> repeats.<br>Detect <u>%3% identical</u> repeats <u>not shorter than %4 bps</u>.<br>Output the list of found regions annotated as <u>%5</u>. Для каждой последовательности<u>%1</u>, искать <u>%2</u> повторы.<br>Учитывать <u>%3% идентичные</u> повторы <u>не короче %4 нк</u>.<br>Выдать список найденных регионов аннотированных как <u>%5</u>. U2::LocalWorkflow::RepeatWorker Input sequences Входные последовательности A nucleotide sequence to search repeats in. Входные нуклеотидные последовательности для поиска повторов. Repeat annotations Аннотированные повторы A set of annotations marking repeats found in the sequence. Список аннотаций маркирующих найденные повторы. Annotate as Аннотации Name of the result annotations marking found repeats. Имя аннотации для разметки найденных повторов. Identity Идентичность Repeats identity. Идентичность повторов. Min length Мин длина Minimum length of repeats. Мин длина повторов. Min distance Мин дистанция Minimum distance between repeats. Мин дистанция между повторами. Max distance Макс дистанция Maximum distance between repeats. Макс дистанция между повторами. Inverted Инвертированные Search for inverted repeats. Искать инвертированные повторы. Filter nested Исключать вложенные Filter nested repeats. Не исключать вложенные повторы. Algorithm Алгоритм Control over variations of algorithm. Выбор алгоритма. Parallel threads Параллельные потоки Number of parallel threads used for the task. Кол-во параллельных потоков для задачи. Find repeats Поиск повторов Finds repeats in each supplied sequence, stores found regions as annotations. Ищет повторы в нуклеотидных последовательностях, выдаёт найденные регионы как аннотации. bp нк Any Не ограничивать result name is empty, default name used Incorrect value: identity value must be between 0 and 100 Incorrect value: minimal distance must be greater then zero Sequence alphabet is not nucleic! Found %1 repeats Найдено повторов: %1 U2::QDRepeatActor inverted инвертированные direct прямые Finds <u>%1</u> repeats.<br>Detects <u>%2 identical</u> repeats <u>not shorter than %3 bps</u>. Искать <u>%1</u> повторы.<br>Учитывать <u>%2 идентичные</u> повторы <u>не короче %3 нк</u>. RepeatQDTask Repeats Finds repeats in supplied sequence, stores found regions as annotations. Ищет повторы в нуклеотидных последовательностях, выдаёт найденные регионы как аннотации. Identity Идентичность Repeats identity. Идентичность повторов. Min length Мин длина Minimum length of repeats. Мин длина повторов. Inverted Инвертированные Search for inverted repeats. Искать инвертированные повторы. Filter nested Исключать вложенные Filter nested repeats. Не исключать вложенные повторы. Algorithm Алгоритм Control over variations of algorithm. Выбор алгоритма. Parallel threads Параллельные потоки Number of parallel threads used for the task. Кол-во параллельных потоков для задачи. Max length Макс длина Maximum length of repeats. Макс. длина повторов. bp нк U2::RFAlgorithmBase Find repeats Поиск повторов Repeat length is too large: %1, sequence size: %2 Длина повтора слишком велика: %1, размер последовательности: %2 U2::RFDiagonalWKSubtask Find repeats subtask (diagonal) Подзазадача поискв повторов (диагональный алгоритм) U2::RFSArrayWKAlgorithm Memory allocation error, size: %1 Ошибка выделения памяти, размер: %1 U2::RFSArrayWKSubtask Find repeats subtask (suffixWK) Подзазадача поискв повторов (суффиксный алгоритм) U2::RFSArrayWSubtask Find repeats subtask (suffix) Подзазадача поискв повторов (суффиксный алгоритм) U2::RepeatFinderPlugin Repeats Finder Поиск Повторов Search for repeated elements in genetic sequences Поиск повторяющихся элементов в генетических последовательностях U2::RepeatQDActor inverted инвертированные direct прямые Find repeats Поиск повторов Finds <u>%1</u> repeats.<br>Detects <u>%2 identical</u> repeats <u>not shorter than %3 bps</u>.<br>Outputs the list of found regions annotated as <u>%4</u>. Искать %1 повторы. <br>Учитывать %2 идентичные повторы не короче чем %3 нк. Сохранить список найденных регионов как %4. Finds repeats in supplied sequence, stores found regions as annotations. Ищет повторы в нуклеотидных последовательностях, выдаёт найденные регионы как аннотации. Annotate as Аннотации Name of the result annotations marking found repeats. Имя аннотации для разметки найденных повторов. Identity Идентичность Repeats identity. Идентичность повторов. Min length Мин длина Minimum length of repeats. Мин длина повторов. Inverted Инвертированные Search for inverted repeats. Искать инвертированные повторы. Filter nested Исключать вложенные Filter nested repeats. Не исключать вложенные повторы. Algorithm Алгоритм Control over variations of algorithm. Выбор алгоритма. Parallel threads Параллельные потоки Number of parallel threads used for the task. Кол-во параллельных потоков для задачи. Max length Макс. длина Maximum length of repeats. Макс. длина повторов. bp нк U2::RepeatViewContext Find repeats... Поиск повторов... Find tandems... Поиск тандемов... U2::RevComplSequenceTask Reverse complement sequence Перевод последовательности к комплементарной Can't find complement translation for alphabet: %1 Не найдена комплементарная трансляция для алфавита: %1 U2::TandemFinder Find tandems finished %1 Поиск тандемов завершен %1 Find tandems Поиск тандемов U2::TandemFinder_Region Find tandems in %1 region Поиск тандемов в %1 регионе ugene-1.9.8/src/plugins/repeat_finder/transl/czech.ts0000644000175000017500000006272311651544324021357 0ustar ilyailya FindRepeatsDialog Find repeats Repeat parameters Minimum repeat length bp Heuristic based selection of repeat length so the number of repeats in the sequence will not exceed 1000 1k Repeats identity % Resets repeats identity to 100% 100 Minimum distance between repeats Maximum distance between repeats Custom algorithm Search only for repeats that lie inside of an annotated region ... Search only for repeats that have an annotated region inside Filter repeats that have an annotated region inside Do not filter nested repeats Search for inverted repeats Region to process Whole sequence Selection Custom range - Start Cancel FindTandemsDialog Find tandems Find tandems Repeat parameters Repeat parameters Tandem preset Tandem preset Min period Min period n n Max period Max period Repeats identity Repeats identity % % Algorithm Algorithm Minimum tandem size Minimum tandem size Minimum repeat count Minimum repeat count x x Show overlapped tandems Show overlapped tandems Region to process Region to process Whole sequence Whole sequence Selection Selection Custom range Custom range - Start Start Cancel Cancel U2::ExactSizedTandemFinder Find %1-period tandems Find %1-period tandems U2::FindRepeatsDialog Auto Suffix index Diagonals Error No annotations found: %1 Estimated repeats count: %1 Estimated repeats count hint is based on the active settings and random sequence model U2::FindRepeatsTask Find repeats in a single sequence Rev-complementing sequence Searching repeats ... Filtering nested results Repeat search time %1 sec Nested repeats filtering time %1 sec, results before: %2, filtered: %3, after %4 U2::FindRepeatsToAnnotationsTask Find repeats to annotations Found %1 repeat regions U2::FindTandemsDialog Suffix array Suffix array Suffix array (optimized) Suffix array (optimized) All All Micro-satellites Micro-satellites Mini-satellites Mini-satellites Big-period tandems Big-period tandems Custom Custom Error Error No annotations found: %1 "No annotations found: %1 Estimated repeats count: %1 Estimated repeats count: %1 Estimated repeats count hint is based on the active settings and random sequence model Estimated repeats count hint is based on the active settings and random sequence model" U2::FindTandemsToAnnotationsTask Find repeats to annotations Find repeats to annotations Found %1 repeat regions Found %1 repeat regions U2::LargeSizedTandemFinder Find big-period tandems Find big-period tandems U2::LocalWorkflow::RepeatPrompter from %1 inverted direct For each sequence<u>%1</u>, find <u>%2</u> repeats.<br>Detect <u>%3% identical</u> repeats <u>not shorter than %4 bps</u>.<br>Output the list of found regions annotated as <u>%5</u>. U2::LocalWorkflow::RepeatWorker Input sequences A nucleotide sequence to search repeats in. Repeat annotations A set of annotations marking repeats found in the sequence. Annotate as Name of the result annotations marking found repeats. Identity Repeats identity. Min length Minimum length of repeats. Min distance Minimum distance between repeats. Max distance Maximum distance between repeats. Inverted Search for inverted repeats. Filter nested Filter nested repeats. Algorithm Control over variations of algorithm. Parallel threads Number of parallel threads used for the task. Find repeats Finds repeats in each supplied sequence, stores found regions as annotations. bp Any result name is empty, default name used Incorrect value: identity value must be between 0 and 100 Incorrect value: minimal distance must be greater then zero Sequence alphabet is not nucleic! Found %1 repeats U2::RFAlgorithmBase Find repeats Repeat length is too large: %1, sequence size: %2 U2::RFDiagonalWKSubtask Find repeats subtask (diagonal) U2::RFSArrayWKAlgorithm Memory allocation error, size: %1 U2::RFSArrayWKSubtask Find repeats subtask (suffixWK) U2::RFSArrayWSubtask Find repeats subtask (suffix) U2::RepeatFinderPlugin Repeats Finder Search for repeated elements in genetic sequences U2::RepeatViewContext Find Repeats Find repeats Find Tandems Find tandems U2::RevComplSequenceTask Reverse complement sequence Can't find complement translation for alphabet: %1 U2::TandemFinder Find tandems finished %1 Find tandems finished %1 Find tandems Find tandems U2::TandemFinder_Region Find tandems in %1 region Find tandems in %1 region ugene-1.9.8/src/plugins/repeat_finder/transl/english.ts0000644000175000017500000007461311651544324021715 0ustar ilyailya FindRepeatsDialog Find repeats Minimum repeat length bp Heuristic based selection of repeat length so the number of repeats in the sequence will not exceed 1000 1k Repeats identity % Resets repeats identity to 100% 100 Minimum distance between repeats Maximum distance between repeats Advanced Advanced parameters Custom algorithm Search only for repeats that lie inside of an annotated region ... Search only for repeats that have an annotated region inside Filter repeats that have an annotated region inside Do not filter nested repeats Search for inverted repeats Region to process Base Repeat finder parameters Whole sequence Selection Custom range - Start Cancel FindTandemsDialog Find tandems Find tandems Repeat parameters Repeat parameters Tandem preset Tandem preset Min period Min period n n Max period Max period Advanced Advanced parameters Repeats identity Repeats identity % % Algorithm Algorithm Minimum tandem size Minimum tandem size Minimum repeat count Minimum repeat count x x Show overlapped tandems Show overlapped tandems Region to process Region to process Base Tandem finder parameters Whole sequence Whole sequence Selection Selection Custom range Custom range - Start Start Cancel Cancel U2::ExactSizedTandemFinder Find %1-period tandems Find %1-period tandems U2::FindRepeatsDialog Auto Suffix index Diagonals Error No annotations found: %1 Estimated repeats count: %1 Estimated repeats count hint is based on the active settings and random sequence model U2::FindRepeatsTask Find repeats in a single sequence Rev-complementing sequence Searching repeats ... Filtering nested results Repeat search time %1 sec Nested repeats filtering time %1 sec, results before: %2, filtered: %3, after %4 U2::FindRepeatsToAnnotationsTask Find repeats to annotations Found %1 repeat regions U2::FindTandemsDialog Suffix array Suffix array Suffix array (optimized) Suffix array (optimized) All All Micro-satellites Micro-satellites Mini-satellites Mini-satellites Big-period tandems Big-period tandems Custom Custom Error Error No annotations found: %1 "No annotations found: %1 Estimated repeats count: %1 Estimated repeats count: %1 Estimated repeats count hint is based on the active settings and random sequence model Estimated repeats count hint is based on the active settings and random sequence model" U2::FindTandemsToAnnotationsTask Find repeats to annotations Find repeats to annotations Found %1 repeat regions Found %1 repeat regions U2::LargeSizedTandemFinder Find big-period tandems Find big-period tandems U2::LocalWorkflow::RepeatPrompter from %1 inverted direct For each sequence<u>%1</u>, find <u>%2</u> repeats.<br>Detect <u>%3% identical</u> repeats <u>not shorter than %4 bps</u>.<br>Output the list of found regions annotated as <u>%5</u>. U2::LocalWorkflow::RepeatWorker Input sequences A nucleotide sequence to search repeats in. Repeat annotations A set of annotations marking repeats found in the sequence. Annotate as Name of the result annotations marking found repeats. Identity Repeats identity. Min length Minimum length of repeats. Min distance Minimum distance between repeats. Max distance Maximum distance between repeats. Inverted Search for inverted repeats. Filter nested Filter nested repeats. Algorithm Control over variations of algorithm. Parallel threads Number of parallel threads used for the task. Find repeats Finds repeats in each supplied sequence, stores found regions as annotations. Any result name is empty, default name used Incorrect value: identity value must be between 0 and 100 Incorrect value: minimal distance must be greater then zero Sequence alphabet is not nucleic! Found %1 repeats U2::QDRepeatActor inverted direct Finds <u>%1</u> repeats.<br>Detects <u>%2 identical</u> repeats <u>not shorter than %3 bps</u>. RepeatQDTask Repeats Finds repeats in supplied sequence, stores found regions as annotations. Identity Repeats identity. Min length Minimum length of repeats. Inverted Search for inverted repeats. Filter nested Filter nested repeats. Algorithm Algorithm Control over variations of algorithm. Parallel threads Number of parallel threads used for the task. Max length Maximum length of repeats. U2::RFAlgorithmBase Find repeats Repeat length is too large: %1, sequence size: %2 U2::RFDiagonalWKSubtask Find repeats subtask (diagonal) U2::RFSArrayWKAlgorithm Memory allocation error, size: %1 U2::RFSArrayWKSubtask Find repeats subtask (suffixWK) U2::RFSArrayWSubtask Find repeats subtask (suffix) U2::RepeatFinderPlugin Repeats Finder Search for repeated elements in genetic sequences U2::RepeatQDActor Algorithm Algorithm U2::RepeatViewContext Find repeats... Find tandems... U2::RevComplSequenceTask Reverse complement sequence Can't find complement translation for alphabet: %1 U2::TandemFinder Find tandems finished %1 Find tandems finished %1 Find tandems Find tandems U2::TandemFinder_Region Find tandems in %1 region Find tandems in %1 region ugene-1.9.8/src/plugins/remote_service/0000755000175000017500000000000011651544324016602 5ustar ilyailyaugene-1.9.8/src/plugins/remote_service/remote_service.pri0000644000175000017500000000022111651544324022324 0ustar ilyailya# include (remote_service.pri) PLUGIN_ID=remote_service PLUGIN_NAME=Remote tasks PLUGIN_VENDOR=Unipro include( ../../ugene_plugin_common.pri ) ugene-1.9.8/src/plugins/remote_service/src/0000755000175000017500000000000011651544324017371 5ustar ilyailyaugene-1.9.8/src/plugins/remote_service/src/UctpRequestBuilders.cpp0000644000175000017500000001237411651544324024062 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include #include #include #include #include "UctpRequestBuilders.h" #include "Base64File.h" namespace U2 { InitSessionRequest::InitSessionRequest( const QString& username, const QString& passwd ) : UctpRequestBuilder(UctpCommands::AUTH), name(username), pass(passwd) { } void InitSessionRequest::formContents( QXmlStreamWriter& stream ) { stream.writeStartElement(UctpElements::SESSION); stream.writeAttribute(UctpElements::USER_NAME, name); stream.writeAttribute(UctpElements::PASSWD, pass); stream.writeEndElement(); } ////////////////////////////////////////////////////////////////////////// #define TRANSITION_MARKER "0000_1111____TRANSITION____MARKER____1111____0000" static qint64 getFileSize(const QString& url) { QFileInfo info(url); return info.size(); } RunRemoteTaskRequest::RunRemoteTaskRequest( UctpSession* s, const QByteArray& ts, const QStringList& input ) : UctpRequestBuilder(UctpCommands::RUN_TASK), session(s), taskSchema(ts), inputUrls(input) { QByteArray requestTemplate = prepareRequestTemplate(); reader = new BufferedDataReader(input, requestTemplate, TRANSITION_MARKER); } void RunRemoteTaskRequest::formContents( QXmlStreamWriter& stream ) { stream.writeStartDocument(); stream.writeStartElement(UctpElements::REQUEST); stream.writeAttribute(UctpAttributes::COMMAND_TYPE, UctpCommands::RUN_TASK); stream.writeAttribute(UctpElements::APP_VERSION, Version::ugeneVersion().text ); stream.writeAttribute(UctpAttributes::SESSION_ID, session->getUid()); // save schema stream.writeStartElement(UctpElements::TASK); stream.writeAttribute(UctpAttributes::ENCODING, UctpValues::BASE64); stream.writeCharacters(taskSchema.toBase64()); stream.writeEndElement(); // save data foreach(const QString url, inputUrls) { stream.writeStartElement(UctpElements::DATA); stream.writeAttribute(UctpAttributes::IS_GZIPPED, UctpValues::UCTP_FALSE); stream.writeAttribute(UctpAttributes::ENCODING, UctpValues::BASE64); stream.writeAttribute(UctpAttributes::NAME, GUrl(url).fileName()); stream.writeAttribute(UctpAttributes::SIZE, QString("%1").arg(getFileSize(url))); stream.writeCharacters(TRANSITION_MARKER); stream.writeEndElement(); } stream.writeEndElement(); stream.writeEndDocument(); } QByteArray RunRemoteTaskRequest::prepareRequestTemplate() { QByteArray requestTemplate; QXmlStreamWriter stream(&requestTemplate); formContents(stream); return requestTemplate; } RunRemoteTaskRequest::~RunRemoteTaskRequest() { delete reader; reader = NULL; } QIODevice* RunRemoteTaskRequest::getDataSource() { reader->open(QIODevice::ReadOnly); return reader; } ////////////////////////////////////////////////////////////////////////// void GetRemoteTaskPropertyRequest::formContents( QXmlStreamWriter& stream ) { stream.writeAttribute(UctpAttributes::SESSION_ID, session->getUid()); QString id = QString("%1").arg(taskId); //this is task property stream.writeStartElement(UctpElements::PROPERTY); stream.writeAttribute(UctpAttributes::TASK_ID, id); QString propRequest = properties.join(","); stream.writeAttribute(UctpAttributes::NAME, propRequest); stream.writeEndElement(); } ////////////////////////////////////////////////////////////////////////// void UpdateRemoteTaskRequest::formContents( QXmlStreamWriter& stream ) { stream.writeAttribute(UctpAttributes::SESSION_ID, session->getUid()); QString id = QString("%1").arg(taskId); stream.writeStartElement(UctpElements::TASK); stream.writeAttribute(UctpAttributes::TASK_ID, id); stream.writeEndElement(); } ////////////////////////////////////////////////////////////////////////// void GetGlobalPropertyRequest::formContents( QXmlStreamWriter& stream ) { stream.writeAttribute(UctpAttributes::SESSION_ID, session->getUid()); stream.writeStartElement(UctpElements::PROPERTY); stream.writeAttribute(UctpAttributes::NAME, propName); stream.writeEndElement(); } void GetRemoteTaskResultRequst::formContents( QXmlStreamWriter& stream ) { stream.writeAttribute(UctpAttributes::SESSION_ID, session->getUid()); stream.writeStartElement(UctpElements::TASK); stream.writeAttribute(UctpAttributes::TASK_ID, QString("%1").arg(taskId)); stream.writeEndElement(); } } // ~namespace ugene-1.9.8/src/plugins/remote_service/src/Base64File.cpp0000644000175000017500000000507011651544324021723 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include #include #include "Base64File.h" #include namespace U2 { #define BUFSIZE 8192 Base64File::Base64File( const QString& url ) : file(url) { base64_init_encodestate(&encodeState); buf.reserve(BUFSIZE*2); bufLen = 0; bufOffset = 0; } bool Base64File::open( OpenMode mode ) { bool ok = file.open(mode); if (ok) { setOpenMode(mode); } return ok; } qint64 Base64File::size() const { return QFileInfo(file).size() * 4/3; } qint64 Base64File::readData( char *data, qint64 maxlen ) { qint64 bytesRead = 0; if (file.atEnd() && bufLen == 0) { return -1; } forever { if (bufLen == 0) { // fill buffer QByteArray fileData; fileData.reserve(BUFSIZE); bufOffset = 0; qint64 len = file.read(fileData.data(), BUFSIZE); if (len <= 0) { // EOF is reached break; } qint64 codelen = base64_encode_block(fileData.constData(), len, buf.data(), &encodeState); bufLen += codelen; if (file.atEnd()) { bufLen += base64_encode_blockend(buf.data() + codelen, &encodeState); } } qint64 bytesToRead = maxlen - bytesRead; qint64 len = bufLen > bytesToRead ? bytesToRead : bufLen; qMemCopy(data + bytesRead, buf.data() + bufOffset, len ); bufOffset += len; bytesRead += len; bufLen -= len; if (bytesRead == maxlen) { break; } assert(bufLen == 0); } return bytesRead; } qint64 Base64File::writeData( const char* , qint64 ) { return -1; } } //namespace ugene-1.9.8/src/plugins/remote_service/src/RemoteTasksDialog.h0000644000175000017500000000377411651544324023136 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _REMOTE_TASKS_DIALOG_H_ #define _REMOTE_TASKS_DIALOG_H_ #include #include #include "ui/ui_TaskStatisticsDialog.h" namespace U2 { class RemoteServiceMachineSettings; class RemoteServiceMachine; class GetUserTasksInfoTask; class FetchRemoteTaskResultTask; class DeleteRemoteDataTask; struct RemoteTaskInfo; class RemoteTasksDialog : public QDialog, public Ui::RemoteTasksDialog { Q_OBJECT public: RemoteTasksDialog(const RemoteServiceMachineSettings* s,QWidget* parent = NULL); private slots: void sl_onRefreshFinished(); void sl_onRefreshButtonClicked(); void sl_onFetchButtonClicked(); void sl_onRemoveButtonClicked(); void sl_onRemoveTaskFinished(); void sl_onFetchFinished(); void sl_onSelectionChanged(); void sl_onDialogClosed(); private: void addItemToView(const RemoteTaskInfo& info); void refresh(); void updateState(); void clearTreeWidget(); GetUserTasksInfoTask* getInfoTask; FetchRemoteTaskResultTask* fetchResultTask; DeleteRemoteDataTask* deleteRemoteDataTask; std::auto_ptr machine; }; } // namespace U2 #endif // _REMOTE_TASKS_DIALOG_H_ ugene-1.9.8/src/plugins/remote_service/src/RemoteServiceCommon.h0000644000175000017500000000035411651544324023471 0ustar ilyailya#ifndef _REMOTE_SERVICE_COMMON_H_ #define _REMOTE_SERVICE_COMMON_H_ namespace U2 { class RemoteServiceCommon { public: static const QString WEB_TRANSPORT_PROTOCOL_ID; }; } // namespace U2 #endif // _REMOTE_SERVICE_COMMON_H_ugene-1.9.8/src/plugins/remote_service/src/RemoteServiceUtilTasks.cpp0000644000175000017500000000704511651544324024523 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include #include #include "RemoteServiceMachine.h" #include "WebTransportProtocol.h" #include "RemoteServiceUtilTasks.h" #define REMOTE_SERVICE_TASKS_LOG "remote-service-tasks" namespace U2 { GetUserTasksInfoTask::GetUserTasksInfoTask( RemoteServiceMachine* m ) : Task( tr( "GetUserTasksInfo" ), TaskFlags( TaskFlags_FOSCOE ) ), machine(m) { GCOUNTER(cvar,tvar,"GetUserTasksInfo"); properties.insert(UctpElements::TASK_STATE, QString()); properties.insert(UctpElements::DATE_SUBMITTED, QString()); properties.insert(UctpElements::TASK_RESULTS, QString()); } void GetUserTasksInfoTask::run() { assert(machine != NULL); if (isCanceled() || hasError()) { return; } rsLog.details(tr("Retrieving remote tasks list for: %1").arg(machine->getSettings()->getName())); machine->initSession(stateInfo); if (hasError()) { return; } QList runningTaskIds; runningTaskIds = machine->getActiveTasks(stateInfo); if (hasError()) { return; } rsLog.details(tr("Found %1 active remote tasks").arg(runningTaskIds.size())); QList finishedTaskIds; finishedTaskIds = machine->getFinishedTasks(stateInfo); if (hasError()) { return; } rsLog.details(tr("Found %1 finished remote tasks").arg(finishedTaskIds.size())); QList taskIds; taskIds << runningTaskIds << finishedTaskIds; foreach(qint64 taskId, taskIds) { machine->getTaskProperties(stateInfo, taskId, properties); if (hasError()) { break; } RemoteTaskInfo info; info.taskId = QString("%1").arg(taskId); info.date = properties.value(UctpElements::DATE_SUBMITTED); info.taskState = properties.value(UctpElements::TASK_STATE); info.result = properties.value(UctpElements::TASK_RESULTS); infoList.append(info); } } FetchRemoteTaskResultTask::FetchRemoteTaskResultTask( RemoteServiceMachine* m, const QStringList& urls, qint64 id ) : Task( tr( "FetchRemoteTaskResult" ), TaskFlags( TaskFlags_FOSCOE ) ), machine(m), resultUrls(urls), taskId(id) { } void FetchRemoteTaskResultTask::run() { assert(machine != NULL); if (isCanceled() || hasError()) { return; } machine->getTaskResult(stateInfo, taskId, resultUrls, "out/"); } DeleteRemoteDataTask::DeleteRemoteDataTask( RemoteServiceMachine* m, qint64 id ) : Task("DeleteRemoteDataTask", TaskFlags_FOSCOE), machine(m), taskId(id) { } void DeleteRemoteDataTask::run() { assert(machine != NULL); if (isCanceled() || hasError()) { return; } machine->deleteRemoteTask(stateInfo, taskId); } } // namespace U2 ugene-1.9.8/src/plugins/remote_service/src/RemoteServiceMachine.cpp0000644000175000017500000004704611651544324024151 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include #include #include #include #include #ifndef QT_NO_OPENSSL #include #endif #include #include #include #include #include #include #include #include "RemoteServiceCommon.h" #include "RemoteServiceMachine.h" #include "UctpRequestBuilders.h" namespace U2 { const QString RemoteServiceMachineSettings::GUEST_ACCOUNT("guest"); #ifndef QT_NO_OPENSSL static bool registerMeta() { qRegisterMetaType("QSslError"); qRegisterMetaType< QList >("QList"); return true; } static bool regMetaType = registerMeta(); #endif // RemoteServiceMachine RemoteServiceMachine::RemoteServiceMachine(RemoteServiceMachineSettings* s) : settings(s), protocolHandler(new Uctp()), session(NULL) { remoteServiceUrl = settings->getUrl(); NetworkConfiguration* nc = AppContext::getAppSettings()->getNetworkConfiguration(); proxy = nc->getProxyByUrl(remoteServiceUrl); #ifndef QT_NO_OPENSSL sslProtocol = nc->getSslProtocol(); #endif //QT_NO_OPENSSL QByteArray sid = settings->getSessionId().toAscii(); if (!sid.isEmpty() ) { session.reset(new UctpSession(sid)); } rsLog.trace("Started remote service machine instance"); parentThreadId = (qlonglong) QThread::currentThreadId(); rsLog.trace(QString("RemoteServiceMachine(): current thread is %1").arg( parentThreadId )); } RemoteServiceMachine::~RemoteServiceMachine() { UserCredentials* credentials = settings->getUserCredentials(); if (credentials != NULL) { if (!credentials->permanent) { settings->flushCredentials(); } } } qint64 RemoteServiceMachine::runTask(TaskStateInfo& si, const QString & taskFactoryId, const QVariant & settings) { qint64 taskId = -1; if (taskFactoryId != Workflow::CoreLibConstants::WORKFLOW_ON_CLOUD_TASK_ID) { si.setError(tr("Unsupported task type")); return taskId; } initSession(si); if (si.hasError()) { return taskId; } rsLog.trace("Init session successful"); QVariantMap settingsMap = settings.toMap(); const QByteArray schema = settingsMap.value(Workflow::CoreLibConstants::WORKFLOW_SCHEMA_ATTR).toByteArray(); const QStringList inUrls = settingsMap.value(Workflow::CoreLibConstants::DATA_IN_ATTR).toStringList(); RunRemoteTaskRequest request(session.get(), schema, inUrls); QMap replyData = sendRequest(si, request); if (si.hasError()) { return taskId; } UctpElementData elData = replyData.value(UctpElements::TASK); QString taskIdStr (elData.attributesMap.value(UctpAttributes::TASK_ID)); bool ok = false; taskId = taskIdStr.toLongLong(&ok); if (!ok) { si.setError(tr("Illegal task id format: %1").arg(taskId)); return taskId; } return taskId; } void RemoteServiceMachine::cancelTask(TaskStateInfo& si, qint64 taskId) { UpdateRemoteTaskRequest request(UctpCommands::CANCEL_TASK, session.get(), taskId); sendRequest(si, request); } static QString getElementValueByNameAttr(const QString& name, const QList elements) { QString result; foreach (const UctpElementData& data, elements) { if (data.attributesMap.value(UctpAttributes::NAME) == name) { result = data.textData; break; } } return result; } Task::State RemoteServiceMachine::getTaskState(TaskStateInfo& si, qint64 taskId) { Task::State state = Task::State_Running; QStringList properties; properties.append(UctpElements::TASK_STATE); properties.append(UctpElements::TASK_ERROR); GetRemoteTaskPropertyRequest request(session.get(), taskId, properties); QMap replyData = sendRequest(si, request); if (si.hasError()) { return state; } QList propertyList = replyData.values(UctpElements::PROPERTY); QByteArray stateText = getElementValueByNameAttr(UctpElements::TASK_STATE, propertyList).toAscii(); if (stateText == UctpValues::UCTP_STATE_FINISHED) { state = Task::State_Finished; QByteArray errorText = getElementValueByNameAttr(UctpElements::TASK_ERROR, propertyList).toAscii(); if (!errorText.isEmpty()) { si.setError(errorText); } } else if (stateText.isEmpty()) { si.setError(tr("Empty task state property")); } return state; } int RemoteServiceMachine::getTaskProgress(TaskStateInfo& si, qint64 taskId) { int res = 0; QStringList properties; properties.append(UctpElements::TASK_PROGRESS); GetRemoteTaskPropertyRequest request(session.get(), taskId, properties); QMap replyData = sendRequest(si, request); if (si.hasError()) { return res; } QList propertyList = replyData.values(UctpElements::PROPERTY); QString buf = getElementValueByNameAttr(UctpElements::TASK_PROGRESS, propertyList); bool ok = false; res = buf.toInt(&ok); if (!ok) { si.setError(tr("Failed to parse task progress: %1").arg(buf)); } return res; } void RemoteServiceMachine::getTaskResult(TaskStateInfo& si, qint64 taskId, const QStringList& urls, const QString& urlPrefix) { try { if (urls.isEmpty()) { si.setError(tr("No files specified")); return; } GetRemoteTaskResultRequst request(session.get(), taskId); QMap replyData = sendRequest(si, request); if (si.hasError()) { return; } QList elements = replyData.values(UctpElements::DATA); if (!elements.isEmpty()) { foreach( const GUrl& url, urls ) { QString dataName = urlPrefix + url.fileName(); const QByteArray data = getElementValueByNameAttr(dataName, elements).toAscii(); if (data.isEmpty()) { si.setError(tr("Result {%1} is not found.").arg(dataName)); return; } saveResult( QByteArray::fromBase64(data), url.getURLString()); } } } catch (UctpError& e) { si.setError(e.getErrorMessage()); } } QString RemoteServiceMachine::getTaskErrorMessage(TaskStateInfo& si, qint64 taskId) { QString res; QStringList properties; properties.append(UctpElements::TASK_ERROR); GetRemoteTaskPropertyRequest request(session.get(), taskId, properties); QMap replyData = sendRequest(si, request); if (si.hasError()) { return res; } QList propertyList = replyData.values(UctpElements::PROPERTY); res = getElementValueByNameAttr(UctpElements::TASK_ERROR, propertyList); return res; } void RemoteServiceMachine::ping(TaskStateInfo& si) { PingRequest request; sendRequest(si, request); } QString RemoteServiceMachine::getServerName(TaskStateInfo& si) { QString res; initSession(si); if (si.hasError()) { return res; } GetGlobalPropertyRequest request(session.get(), BaseGlobalProperties::HOST_NAME); QMap replyData = sendRequest(si, request); if (si.hasError()) { return res; } UctpElementData elData = replyData.value(UctpElements::PROPERTY); if (elData.attributesMap.value(UctpAttributes::NAME) == BaseGlobalProperties::HOST_NAME ) { res = elData.textData; } return res; } void RemoteServiceMachineReplyHandler::sl_onReplyFinished(QNetworkReply* reply ) { assert(reply != NULL); assert(eventLoop != NULL); si->setDescription(""); if (reply->error() == QNetworkReply::NoError) { bool parseOk = protocolHandler->parseReply(reply, command, *replyData); if (!parseOk) { si->setError(QString(tr("Failed to parse server response. %1")).arg(protocolHandler->getErrorText())); } } else { if(!si->hasError()) { si->setError(reply->errorString()); } } eventLoop->exit(); } void RemoteServiceMachineReplyHandler::sl_onUploadProgress(qint64 bytesSent, qint64 bytesTotal) { if(bytesTotal != -1) { si->setDescription(RemoteServiceMachineReplyHandler::tr("Uploading %1%").arg((int)(bytesSent / (float)bytesTotal * 100))); } inactiveCount = 0; } void RemoteServiceMachineReplyHandler::sl_onDownloadProgress(qint64 bytesSent, qint64 bytesTotal) { if(bytesTotal != -1) { si->setDescription(RemoteServiceMachineReplyHandler::tr("Downloading %1%").arg((int)(bytesSent / (float)bytesTotal * 100))); } inactiveCount = 0; } void RemoteServiceMachineReplyHandler::sl_onTimer() { if(si->cancelFlag) { reply->abort(); } if(static_cast(sender())->interval() * inactiveCount > requestTimeout ) { si->setError(RemoteServiceMachineReplyHandler::tr("Request inactivity time is up")); reply->abort(); } inactiveCount++; } QMap RemoteServiceMachine::sendRequest(TaskStateInfo& si, UctpRequestBuilder& requestBuilder ) { QByteArray command = requestBuilder.getCommand(); rsLog.trace(QString("SendRequest(%1): current thread is %2").arg(command.constData()).arg(( qlonglong) QThread::currentThreadId() )); QMap replyData; QIODevice* dataSource = requestBuilder.getDataSource(); if (dataSource == NULL) { si.setError(tr("Send request failed: empty message data")); return replyData; } //qint64 dataLength = dataSource->size(); QEventLoop eventLoop; QNetworkAccessManager networkManager; QNetworkRequest request (remoteServiceUrl); request.setHeader(QNetworkRequest::ContentTypeHeader, "application/xml"); #ifndef QT_NO_OPENSSL QSslConfiguration sslConf = QSslConfiguration::defaultConfiguration(); sslConf.setProtocol(sslProtocol); request.setSslConfiguration(sslConf); #endif QNetworkReply *reply = networkManager.post(request, dataSource ); QTimer timer; RemoteServiceMachineReplyHandler handler(protocolHandler.get(), &eventLoop, &replyData, command, &si, reply, AppContext::getAppSettings()->getNetworkConfiguration()->remoteRequestTimeout() * 1000); connect(&networkManager, SIGNAL(finished(QNetworkReply*)), &handler, SLOT(sl_onReplyFinished(QNetworkReply*))); connect(reply, SIGNAL(uploadProgress(qint64, qint64)), &handler, SLOT(sl_onUploadProgress(qint64, qint64))); connect(reply, SIGNAL(downloadProgress(qint64, qint64)), &handler, SLOT(sl_onDownloadProgress(qint64, qint64))); connect(&timer, SIGNAL(timeout()), &handler, SLOT(sl_onTimer())); #ifndef QT_NO_OPENSSL // QNetworkAccessManager bug workaround: // If the network reply and the manager are created in different threads // blocked connection is required for ssl errors signal qlonglong threadId = (qlonglong) QThread::currentThreadId(); Qt::ConnectionType connectionType = threadId == parentThreadId ? Qt::AutoConnection : Qt::BlockingQueuedConnection; connect(&networkManager, SIGNAL(sslErrors( QNetworkReply *, const QList & )), SLOT(sl_onSslErrors( QNetworkReply*, const QList& )), connectionType ); #endif timer.start(1000); eventLoop.exec(); timer.stop(); return replyData; } void RemoteServiceMachine::initSession(TaskStateInfo& si) { if (settings->getUserCredentials() == NULL) { si.setError(tr("User auth info is not available")); return; } if (session.get() != NULL) { return; } QByteArray userName = settings->getUserName().toAscii(); QByteArray pass = settings->getPasswd().toAscii(); if (userName == RemoteServiceMachineSettings::GUEST_ACCOUNT) { // in this case we set the password pass = RemoteServiceMachineSettings::GUEST_ACCOUNT.toAscii(); } InitSessionRequest request(userName, pass); QMap replyData = sendRequest(si, request); if (si.hasError()) { return; } UctpElementData elData = replyData.value(UctpElements::SESSION); QByteArray id = elData.attributesMap.value(UctpAttributes::SESSION_ID); session.reset(new UctpSession(id)); updateGlobalSettings(); } void RemoteServiceMachine::saveResult( const QByteArray& result, const QString& path ) { QFile resultFile(path); if ( !resultFile.open(QIODevice::WriteOnly) ) { throw UctpError("Can not open file to write results"); } qint64 bytesWrittern = resultFile.write(result); if (bytesWrittern != result.size()) { throw UctpError("Error writing results"); } } void RemoteServiceMachine::updateGlobalSettings() { settings->setSessionId(session->getUid()); } #ifndef QT_NO_OPENSSL void RemoteServiceMachine::sl_onSslErrors(QNetworkReply * reply, const QList & errors ) { QSslError error; foreach(const QSslError& e, errors) { rsLog.trace(tr("SSL connection errors: %1").arg(e.errorString())); } reply->ignoreSslErrors(); } #endif //QT_NO_OPENSSL void RemoteServiceMachine::getTaskProperties( TaskStateInfo& si, qint64 taskId, QMap& properties) { GetRemoteTaskPropertyRequest request( session.get(), taskId, properties.keys()); QMap replyData = sendRequest(si, request); if (si.hasError()) { return; } QList propertyList = replyData.values(UctpElements::PROPERTY); foreach (const QString& propertyName, properties.keys()) { QString propertyValue = getElementValueByNameAttr(propertyName, propertyList); properties.insert(propertyName, propertyValue); } } QList RemoteServiceMachine::getActiveTasks(TaskStateInfo& si) { return getTasksList(si, BaseGlobalProperties::TASKS_LIST_ACTIVE); } QList RemoteServiceMachine::getFinishedTasks(TaskStateInfo& si) { return getTasksList(si, BaseGlobalProperties::TASKS_LIST_FINISHED); } QList RemoteServiceMachine::getTasksList( TaskStateInfo& si, const QByteArray& taskState) { QList res; initSession(si); if (si.hasError()) { return res; } GetGlobalPropertyRequest request( session.get(), taskState); QMap replyData = sendRequest(si, request); if (si.hasError()) { return res; } QList propertyList = replyData.values(UctpElements::PROPERTY); QStringList ids = getElementValueByNameAttr(taskState, propertyList).split(",", QString::SkipEmptyParts); foreach(const QString& idStr, ids ) { bool ok = false; qint64 taskId = idStr.toLongLong(&ok); if (ok) { res.append(taskId); } } return res; } void RemoteServiceMachine::deleteRemoteTask(TaskStateInfo& si, qint64 taskId) { UpdateRemoteTaskRequest request(UctpCommands::DELETE_TASK, session.get(), taskId); sendRequest( si, request ); } // RemoteServiceMachineSettings RemoteServiceMachineSettings::RemoteServiceMachineSettings(): RemoteMachineSettings( AppContext::getProtocolInfoRegistry()->getProtocolInfo( RemoteServiceCommon::WEB_TRANSPORT_PROTOCOL_ID), RemoteMachineType_RemoteService) { } RemoteServiceMachineSettings::RemoteServiceMachineSettings(const QString &host): RemoteMachineSettings(AppContext::getProtocolInfoRegistry()->getProtocolInfo( RemoteServiceCommon::WEB_TRANSPORT_PROTOCOL_ID ), RemoteMachineType_RemoteService ), url(host) { } #define URL_ATTR "url" #define NAME_ATTR "login" #define PASSWD_ATTR "passwd" bool RemoteServiceMachineSettings::operator ==( const RemoteMachineSettings & m ) const { const RemoteMachineSettings * machine = &m; const RemoteServiceMachineSettings* cfg = dynamic_cast< const RemoteServiceMachineSettings* >( machine ); if( NULL == cfg ) { return false; } return url == cfg->getUrl(); } QString RemoteServiceMachineSettings::serialize() const { QStringList cfg; cfg.append(QString("%1=%2").arg(URL_ATTR).arg(url)); if (credentials != NULL) { cfg.append(QString("%1=%2").arg(NAME_ATTR).arg(credentials->name)); cfg.append(QString("%1=%2").arg(PASSWD_ATTR).arg(credentials->passwd)); } return cfg.join("\n"); } bool RemoteServiceMachineSettings::deserialize( const QString & data ) { QStringList lines = data.split("\n", QString::SkipEmptyParts); QString name, passwd; foreach (const QString cfgLine, lines) { if (cfgLine.startsWith("#")) { continue; } else if (cfgLine.startsWith(URL_ATTR)) { url = cfgLine.split("=").at(1).trimmed(); } else if (cfgLine.startsWith(NAME_ATTR)) { name =cfgLine.split("=").at(1).trimmed(); } else if (cfgLine.startsWith(PASSWD_ATTR)) { passwd = cfgLine.split("=").at(1).trimmed(); } } if (url.isEmpty()) { return false; } if (!name.isEmpty()) { if (name == GUEST_ACCOUNT || !passwd.isEmpty()){ setupCredentials(name, passwd, true); } } return true; } QString RemoteServiceMachineSettings::getUserName() const { assert(credentials != NULL); return credentials->name; } QString RemoteServiceMachineSettings::getPasswd() const { assert(credentials != NULL); return credentials->passwd; } bool RemoteServiceMachineSettings::usesGuestAccount() const { if (credentials == NULL) { return false; } if (credentials->name == GUEST_ACCOUNT) { return true; } else { return false; } } // RemoteServiceMachineFactory RemoteServiceMachineFactory::RemoteServiceMachineFactory() { } RemoteServiceMachineFactory::~RemoteServiceMachineFactory() { } RemoteMachine * RemoteServiceMachineFactory::createInstance( const QString & serializedSettings ) const { RemoteServiceMachineSettings settings; if(settings.deserialize(serializedSettings)) { return createInstance(&settings); } return NULL; } RemoteMachine * RemoteServiceMachineFactory::createInstance( RemoteMachineSettings * settings ) const { RemoteServiceMachineSettings *castedSettings = dynamic_cast(settings); if(NULL != castedSettings) { return new RemoteServiceMachine(castedSettings); } return NULL; } RemoteMachineSettings * RemoteServiceMachineFactory::createSettings( const QString & serializedSettings ) const { RemoteServiceMachineSettings * ret = new RemoteServiceMachineSettings(); if( ret->deserialize( serializedSettings ) ) { return ret; } delete ret; return NULL; } } // namespace U2 ugene-1.9.8/src/plugins/remote_service/src/ui/0000755000175000017500000000000011651544324020006 5ustar ilyailyaugene-1.9.8/src/plugins/remote_service/src/ui/RemoteServiceSupportUI.ui0000644000175000017500000001522411651544324024760 0ustar ilyailya RemoteServiceSupportUI 0 0 500 196 Form URL: Account information Existing account Qt::Horizontal QSizePolicy::Preferred 45 45 false User name: false 120 0 false Password false 120 0 QLineEdit::Password false Remember me true Qt::Horizontal 106 45 Qt::Vertical QSizePolicy::Preferred 140 2 Guest account true Qt::Vertical 20 10 existingRB toggled(bool) userNameEdit setEnabled(bool) 117 66 201 91 existingRB toggled(bool) passwdEdit setEnabled(bool) 117 66 201 117 existingRB toggled(bool) passwordLabel setEnabled(bool) 117 66 101 117 existingRB toggled(bool) userNameLabel setEnabled(bool) 117 66 101 91 existingRB toggled(bool) rememberEdit setEnabled(bool) 117 66 319 117 ugene-1.9.8/src/plugins/remote_service/src/ui/TaskStatisticsDialog.ui0000644000175000017500000001041611651544324024444 0ustar ilyailya RemoteTasksDialog 0 0 612 544 User Remote Tasks Remote service URL: <unknown> Qt::Horizontal 40 20 Task ID Submitted State Result Refresh Fetch data true Remove task data Qt::Vertical 20 40 Qt::Horizontal 40 20 OK Cancel okPushButton clicked() RemoteTasksDialog accept() 367 510 249 266 cancelPushButton clicked() RemoteTasksDialog accept() 450 510 249 266 ugene-1.9.8/src/plugins/remote_service/src/RemoteServicePingTask.cpp0000644000175000017500000000415711651544324024321 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include #include #include "RemoteServicePingTask.h" #include "RemoteServiceMachine.h" namespace U2 { #define PING_REMOTE_SERVICE_LOG "ping-remote-server" RemoteServicePingTask::RemoteServicePingTask( const QString& url ) :Task( tr( "RemoteServicePingTask" ), TaskFlags( TaskFlags_FOSCOE ) ), machinePath(url), machine(NULL), machineFactory(new RemoteServiceMachineFactory()) { } void RemoteServicePingTask::prepare() { RemoteMachineSettings* machineSettings; if( machinePath.isEmpty() ) { setError("Path to remote server settings file is not set"); return; } if( !SerializeUtils::deserializeRemoteMachineSettingsFromFile( machinePath, &machineSettings ) ) { setError( tr("Can not parse remote server settings file %1").arg(machinePath) ); return; } RemoteMachine* m = machineFactory->createInstance(machineSettings); machine.reset( static_cast (m) ); } void RemoteServicePingTask::run() { assert(machine.get() != NULL); if (isCanceled() || hasError()) { return; } machine->initSession(stateInfo); if (hasError()) { return; } QString hostName = machine->getServerName(stateInfo); } } // namespace U2 ugene-1.9.8/src/plugins/remote_service/src/RemoteTasksDialog.cpp0000644000175000017500000001526411651544324023466 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include #include #include #include #include "RemoteServiceMachine.h" #include "RemoteServiceUtilTasks.h" #include "RemoteTasksDialog.h" namespace U2 { RemoteTasksDialog::RemoteTasksDialog(const RemoteServiceMachineSettings* settings,QWidget* parent ) : QDialog(parent), getInfoTask(NULL), fetchResultTask(NULL), deleteRemoteDataTask(NULL), machine(NULL) { setupUi(this); machine.reset(new RemoteServiceMachine(const_cast(settings))); urlLabel->setText(settings->getName()); connect(this, SIGNAL(finished(int)), SLOT(sl_onDialogClosed())); connect(tasksTreeWidget, SIGNAL(itemSelectionChanged()),SLOT(sl_onSelectionChanged()) ); connect(refreshPushButton, SIGNAL(clicked()), SLOT(sl_onRefreshButtonClicked())); connect(fetchPushButton, SIGNAL(clicked()), SLOT(sl_onFetchButtonClicked())); connect(removePushButton, SIGNAL(clicked()), SLOT(sl_onRemoveButtonClicked())); refresh(); updateState(); } void RemoteTasksDialog::updateState() { bool enable = getInfoTask == NULL && machine.get() != NULL && fetchResultTask == NULL; bool itemSelected = tasksTreeWidget->selectedItems().size() > 0; refreshPushButton->setEnabled(enable); removePushButton->setEnabled(enable && itemSelected); fetchPushButton->setEnabled(enable && itemSelected); } void RemoteTasksDialog::refresh() { tasksTreeWidget->clear(); getInfoTask = new GetUserTasksInfoTask(machine.get()); getInfoTask->setErrorNotificationSuppression(true); connect(getInfoTask, SIGNAL(si_stateChanged()), SLOT(sl_onRefreshFinished())); AppContext::getTaskScheduler()->registerTopLevelTask(getInfoTask); } void RemoteTasksDialog::sl_onRefreshFinished() { if (getInfoTask->getState() != Task::State_Finished) { return; } QList infoItems = getInfoTask->getUserTasksInfo(); foreach(const RemoteTaskInfo& info, infoItems) { addItemToView(info); } QHeaderView * header = tasksTreeWidget->header(); header->resizeSections( QHeaderView::ResizeToContents ); getInfoTask = NULL; updateState(); } void RemoteTasksDialog::addItemToView( const RemoteTaskInfo& info ) { QStringList strings; strings.append(info.taskId); strings.append(info.date); strings.append(info.taskState); strings.append(info.result); tasksTreeWidget->addTopLevelItem(new QTreeWidgetItem(strings)); } void RemoteTasksDialog::sl_onRefreshButtonClicked() { refresh(); updateState(); } #define STATE_FINISHED "FINISHED" void RemoteTasksDialog::sl_onFetchButtonClicked() { QTreeWidgetItem* current = tasksTreeWidget->currentItem(); QString state = current->text(2); if (state != STATE_FINISHED) { QMessageBox::warning(this, tr("Fetch data error"), tr("The task is not finished yet.")); return; } QString result = current->text(3); if (result.isEmpty()) { QMessageBox::warning(this, tr("Fetch data error"), tr("No result available for task.")); return; } bool ok = false; qint64 taskId = current->text(0).toLongLong(&ok); if (!ok) { QMessageBox::warning(this, tr("Fetch data error"), tr("Failed to parse task id.")); return; } LastOpenDirHelper h; QString folder = QFileDialog::getExistingDirectory(this, tr("Select directory to save results: "), h.dir); if (folder.isEmpty()) { return; } QList urls = result.split(";"); for (int i = 0; i < urls.size(); ++i) { QString& str = urls[i]; str.prepend(folder + "/"); } fetchResultTask = new FetchRemoteTaskResultTask(machine.get(), urls, taskId); fetchResultTask->setErrorNotificationSuppression(true); connect(fetchResultTask, SIGNAL(si_stateChanged()), SLOT(sl_onFetchFinished())); AppContext::getTaskScheduler()->registerTopLevelTask(fetchResultTask); } void RemoteTasksDialog::sl_onFetchFinished() { if (fetchResultTask->getState() != Task::State_Finished) { return; } if (!fetchResultTask->hasError()) { QMessageBox::information(this, tr("Fetch data"), tr("Download finished successfully.")); } else { QMessageBox::critical(this, tr("Fetch data error"), tr("Failed to download task result. %1").arg(fetchResultTask->getError())); } fetchResultTask = NULL; updateState(); } void RemoteTasksDialog::sl_onSelectionChanged() { updateState(); } void RemoteTasksDialog::sl_onRemoveButtonClicked() { QTreeWidgetItem* current = tasksTreeWidget->currentItem(); bool ok = false; qint64 taskId = current->text(0).toLongLong(&ok); if (!ok) { QMessageBox::critical(this, "Error!", "Failed to parse task id."); return; } deleteRemoteDataTask = new DeleteRemoteDataTask(machine.get(), taskId); deleteRemoteDataTask->setErrorNotificationSuppression(true); connect(deleteRemoteDataTask, SIGNAL(si_stateChanged()), SLOT(sl_onRemoveTaskFinished())); AppContext::getTaskScheduler()->registerTopLevelTask(deleteRemoteDataTask); } void RemoteTasksDialog::sl_onRemoveTaskFinished() { if (deleteRemoteDataTask->getState() != Task::State_Finished) { return; } if (deleteRemoteDataTask->hasError()) { QMessageBox::critical(this, tr("Error"), tr("Failed to download task result. %1").arg(deleteRemoteDataTask->getError())); } deleteRemoteDataTask = NULL; refresh(); updateState(); } void RemoteTasksDialog::sl_onDialogClosed() { //cleanup resources if (fetchResultTask != NULL) { fetchResultTask->disconnect(this); } if (getInfoTask != NULL) { getInfoTask->disconnect(this); } if (deleteRemoteDataTask != NULL) { deleteRemoteDataTask->disconnect(this); } } }ugene-1.9.8/src/plugins/remote_service/src/RemoteServiceMachine.h0000644000175000017500000001421111651544324023602 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _REMOTE_SERVICE_MACHINE_H_ #define _REMOTE_SERVICE_MACHINE_H_ #include #include #include #include #ifndef QT_NO_OPENSSL #include #endif #include #include #include "WebTransportProtocol.h" namespace U2 { class RemoteServiceMachineSettings : public RemoteMachineSettings { public: RemoteServiceMachineSettings(); RemoteServiceMachineSettings(const QString &url); virtual bool operator==( const RemoteMachineSettings& machine ) const; QString getUrl()const {return url; } QString getUserName() const; QString getPasswd() const; QString getSessionId() const { return sessionId; } void setSessionId(const QString& id) { sessionId = id; } bool usesGuestAccount() const; virtual QString getName() const { return url; } virtual QString serialize() const; bool deserialize( const QString & data ); static const QString GUEST_ACCOUNT; private: QString url; QString sessionId; }; class UctpSession; class RemoteServiceMachine : public QObject, public RemoteMachine { Q_OBJECT public: RemoteServiceMachine(RemoteServiceMachineSettings* s); virtual ~RemoteServiceMachine(); // Runs task on remote machine. Returns remote taskId virtual qint64 runTask( TaskStateInfo& si, const QString & taskFactoryId, const QVariant & settings); // Cancels remote task virtual void cancelTask(TaskStateInfo& si, qint64 taskId ); // Retrieves remote task state virtual Task::State getTaskState(TaskStateInfo& si, qint64 taskId) ; // Retrieves remote task progress [0..100%] virtual int getTaskProgress(TaskStateInfo& si, qint64 taskId); // Retrieves remote task result virtual void getTaskResult(TaskStateInfo& si, qint64 taskId, const QStringList& resultUrls, const QString& urlPrefix ); // Retrieves remote task error message virtual QString getTaskErrorMessage(TaskStateInfo& si, qint64 taskId); // Returns remote machine server name. TODO: refactor virtual QString getServerName(TaskStateInfo& si); // Lists active tasks ids on remote machine virtual QList getActiveTasks(TaskStateInfo& si); // Pings remote machine virtual void ping(TaskStateInfo& si); virtual const RemoteMachineSettings* getSettings() const {return settings;} //non-virtual methods -> TODO: refactor or add to the base interface void initSession(TaskStateInfo& si); // for the given task property names fills values void getTaskProperties(TaskStateInfo& si, qint64 taskId, QMap& properties); // returns list of finished tasks QList getFinishedTasks(TaskStateInfo& si); // removes remote task and all its data void deleteRemoteTask(TaskStateInfo& si, qint64 taskId); #ifndef QT_NO_OPENSSL private slots: void sl_onSslErrors( QNetworkReply* reply, const QList & errors ); #endif private: QMap sendRequest(TaskStateInfo& si, UctpRequestBuilder& requestBuilder); void saveResult(const QByteArray& result, const QString& path); void updateGlobalSettings(); bool replyContainsData(const QString& dataName); QList getTasksList(TaskStateInfo& si, const QByteArray& taskState); RemoteServiceMachineSettings* settings; QNetworkProxy proxy; #ifndef QT_NO_OPENSSL QSsl::SslProtocol sslProtocol; #endif std::auto_ptr protocolHandler; std::auto_ptr session; QString remoteServiceUrl; qlonglong parentThreadId; }; // helper class to handle request/reply io class RemoteServiceMachineReplyHandler : public QObject { Q_OBJECT public: RemoteServiceMachineReplyHandler(Uctp* _ph, QEventLoop* _el, QMap* _rd, const QByteArray& _ac, TaskStateInfo* _si, QNetworkReply* _reply, const int _requestTimeout) : requestTimeout(_requestTimeout), protocolHandler(_ph), eventLoop(_el), replyData(_rd), command(_ac), si(_si), reply(_reply), inactiveCount(0) {} private slots: void sl_onReplyFinished(QNetworkReply* reply); void sl_onUploadProgress(qint64 bytesSent, qint64 bytesTotal); void sl_onDownloadProgress(qint64 bytesSent, qint64 bytesTotal); void sl_onTimer(); private: const int requestTimeout; Uctp* protocolHandler; QEventLoop* eventLoop; QMap* replyData; QByteArray command; TaskStateInfo* si; QNetworkReply* reply; int inactiveCount; }; class RemoteServiceMachineFactory : public RemoteMachineFactory { public: RemoteServiceMachineFactory(); virtual ~RemoteServiceMachineFactory(); virtual RemoteMachine * createInstance( const QString & serializedSettings ) const; virtual RemoteMachine * createInstance( RemoteMachineSettings * settings ) const; virtual RemoteMachineSettings * createSettings( const QString & serializedSettings ) const; }; } // namespace U2 #endif // _REMOTE_SERVICE_MACHINE_H_ ugene-1.9.8/src/plugins/remote_service/src/RemoteServiceUtilTasks.h0000644000175000017500000000373311651544324024170 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _REMOTE_SERVICE_UTIL_TASKS_H_ #define _REMOTE_SERVICE_UTIL_TASKS_H_ #include #include namespace U2 { class RemoteServiceMachine; struct RemoteTaskInfo { QString taskId; QString date; QString taskState; QString result; }; class GetUserTasksInfoTask: public Task { public: GetUserTasksInfoTask(RemoteServiceMachine* machine); virtual void run(); QList& getUserTasksInfo() { return infoList; } private: RemoteServiceMachine* machine; QMap properties; QList infoList; }; class FetchRemoteTaskResultTask : public Task { public: FetchRemoteTaskResultTask(RemoteServiceMachine* machine, const QStringList& resultUrls, qint64 taskId); virtual void run(); private: RemoteServiceMachine* machine; QStringList resultUrls; qint64 taskId; }; class DeleteRemoteDataTask : public Task { public: DeleteRemoteDataTask(RemoteServiceMachine* machine, qint64 taskId); virtual void run(); private: RemoteServiceMachine* machine; qint64 taskId; }; } // namespace U2 #endif // _REMOTE_SERVICE_UTIL_TASKS_H_ ugene-1.9.8/src/plugins/remote_service/src/BufferedDataReader.cpp0000644000175000017500000001170411651544324023537 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "BufferedDataReader.h" #include namespace U2 { static QList splitBuffers(const QByteArray& request, const QByteArray& splitMarker) { QList result; static int len = QByteArray(splitMarker).length() ; int start = 0; for (; ;) { int pos = request.indexOf(splitMarker,start); if (pos == -1 ) { QByteArray buf = request.mid(start); assert(buf.startsWith("")); result.append(buf); break; } QByteArray buf = request.mid(start, pos - start ); assert(buf.endsWith(">")); result.append(buf); start = pos + len; } return result; } BufferedDataReader::BufferedDataReader( const QStringList& inputUrls, const QByteArray& requestTemplate, const QByteArray& splitMarker ) : curIdx(0), hasErrors(false) { buffersData = splitBuffers(requestTemplate, splitMarker); foreach (const QString& url, inputUrls) { inputFiles.append(new Base64File(url)); } for (int i = 0; i < buffersData.count(); ++i) { inputBufs.append( new QBuffer(&buffersData[i])); } assert(buffersData.count() == inputFiles.count() + 1); setErrorString(""); } bool BufferedDataReader::open( OpenMode mode ) { if (mode != QIODevice::ReadOnly) { setError("Only ReadOnly open mode is supported for device."); return false; } if (buffersData.count() != inputFiles.count() + 1) { setError("Incorrect buffer splitting."); return false; } foreach (Base64File* file, inputFiles) { if (!file->open(QIODevice::ReadOnly)) { setError(QString("Failed to open file %").arg(file->fileName())); return false; } } foreach (QBuffer* buf, inputBufs) { if (!buf->open(QIODevice::ReadOnly)) { setError(QString("Failed to open buffer of RunRemoteTaskRequest data.")); return false; } } int numBufs = inputBufs.count(); for (int i = 0; i < numBufs; ++i) { inputDevs.append(inputBufs[i]); if (i + 1 < numBufs ) { inputDevs.append(inputFiles[i]); } } setOpenMode(QIODevice::ReadOnly); return true; } /* Each time this function is called, buffer of size=maxlen is prepared. The buffer can include data from fragments of request template or from actual file data. After the buffer is prepared it's contents is copied into data. */ qint64 BufferedDataReader::readData( char *data, qint64 maxlen ) { assert(isOpen()); QByteArray preparedBuf; preparedBuf.reserve(maxlen); qint64 len = 0; char* preparedData = preparedBuf.data(); const int MAX_INDEX = inputDevs.count() - 1; if (hasErrors || curIdx > MAX_INDEX) { return -1; } forever { QIODevice* dev = inputDevs[curIdx]; assert(dev->isOpen()); qint64 bytesToRead = maxlen - len; //TODO: support base64 encoding qint64 bytesRead = dev->read(preparedData, bytesToRead); if (-1 == bytesRead) { setError(QString("Failed to read from buffered device.")); return -1; } len += bytesRead; preparedData += bytesRead; if (dev->bytesAvailable() == 0 && curIdx == MAX_INDEX ) { curIdx++; break; } if (len == maxlen ) { break; } curIdx++; } qMemCopy(data, preparedBuf.constData(), len); return len; } qint64 BufferedDataReader::writeData( const char* , qint64 ) { assert(0); return -1; } BufferedDataReader::~BufferedDataReader() { qDeleteAll(inputBufs); qDeleteAll(inputFiles); } qint64 BufferedDataReader::size() const { qint64 dataLen = 0; foreach(QBuffer* buf, inputBufs) { dataLen += buf->size(); } foreach(Base64File* file, inputFiles) { dataLen += file->size(); } return dataLen + 100; } void BufferedDataReader::setError( const QString& errMsg ) { hasErrors = true; setErrorString(errMsg); } } //namespace ugene-1.9.8/src/plugins/remote_service/src/WebTransportProtocol.h0000644000175000017500000001331511651544324023721 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _WEB_TRANSPORT_PROTOCOL_H_ #define _WEB_TRANSPORT_PROTOCOL_H_ #include #include #include #include #include #include #include #include #include namespace U2 { // UGene Common Transport Protocol (UCTP) definitions typedef QByteArray UctpCommand; class UctpElements { public: static const QByteArray REQUEST; static const QByteArray RESPONSE; static const QByteArray APP_VERSION; static const QByteArray STATUS; static const QByteArray TASK_RESULTS; static const QByteArray MESSAGE; static const QByteArray SESSION; static const QByteArray USER_NAME; static const QByteArray PASSWD; static const QByteArray DATA; static const QByteArray PROPERTY; static const QByteArray TASK; static const QByteArray TASK_STATE; static const QByteArray TASK_PROGRESS; static const QByteArray TASK_ERROR; static const QByteArray DATE_SUBMITTED; }; class UctpAttributes { public: static const QByteArray TASK_ID; static const QByteArray SESSION_ID; static const QByteArray COMMAND_TYPE; static const QByteArray IS_GZIPPED; static const QByteArray ENCODING; static const QByteArray NAME; static const QByteArray SIZE; }; class UctpValues { public: static const QByteArray BASE64; static const QByteArray STATUS_OK; static const QByteArray UCTP_TRUE; static const QByteArray UCTP_FALSE; static const QByteArray UCTP_STATE_FINISHED; static const QByteArray UCTP_STATE_ENQUED; static const QByteArray UCTP_STATE_RUNNING; static const QByteArray STATUS_ERROR; }; class UctpCommands { public: static const UctpCommand AUTH; static const UctpCommand RUN_TASK; static const UctpCommand CANCEL_TASK; static const UctpCommand DELETE_TASK; static const UctpCommand GET_TASK_RESULT; static const UctpCommand GET_PROPERTY; static const UctpCommand PING; }; class BaseGlobalProperties { public: static const QByteArray TASKS_LIST_ACTIVE; static const QByteArray TASKS_LIST_FINISHED; static const QByteArray HOST_NAME; }; struct UctpAttribute { UctpAttribute() {} UctpAttribute(const QString& n, const QString& v) : name(n), value(v) {} QString name; QString value; }; struct UctpElementData { QString textData; QMap attributesMap; }; class UctpReplyContext { public: UctpReplyContext(const UctpCommand& cmd, const QList& elements ) : command(cmd), expectedElements(elements) {} bool hasElement(const QString& name) { return expectedElements.contains(name); } const UctpCommand& getCommand() const {return command;} const QList& getExpectedElements() const {return expectedElements;} private: UctpCommand command; QList expectedElements; }; class UctpReplyHandler : public QXmlDefaultHandler { QString curText; QString errorMessage; QString dataEntryName; bool replyResultOk; const UctpReplyContext context; QMap& replyData; QMap xmlAttrMap; // validation flags present bool envelope, header, contents; public: UctpReplyHandler(const UctpReplyContext& ctx, QMap& replyData); bool startElement(const QString &namespaceURI, const QString &localName, const QString &qName, const QXmlAttributes &attributes); bool endElement(const QString &namespaceURI, const QString &localName, const QString &qName); bool endDocument(); bool characters(const QString &str); QString errorString() const; private: bool validateContext(); }; class UctpRequestBuilder { UctpCommand command; private: QBuffer requestBuf; protected: virtual void formContents(QXmlStreamWriter& writer) = 0; public: virtual ~UctpRequestBuilder() {} UctpRequestBuilder(const UctpCommand& cmd) : command(cmd) {} const UctpCommand& getCommand() const { return command; } virtual QIODevice* getDataSource(); }; class UctpSession { public: UctpSession(const QByteArray& id) : uid(id) {} const QByteArray& getUid() const { return uid; } void buildQUuid(QUuid* uuid) const; private: QByteArray uid; }; class UctpError : public std::runtime_error { public: UctpError(QString message) : std::runtime_error(message.toAscii().constData()) {} const QString getErrorMessage() {return QString( what() ); } ~UctpError() throw(); private: QString errorMessage; }; class Uctp { QXmlSimpleReader xmlReader; QString errorString; public: bool parseReply(QIODevice* reply, const UctpCommand& command, QMap& replyData); const QString& getErrorText() const { return errorString; } }; } // namespace U2 #endif // _WEB_TRANSPORT_PROTOCOL_H_ ugene-1.9.8/src/plugins/remote_service/src/base64/0000755000175000017500000000000011651544324020455 5ustar ilyailyaugene-1.9.8/src/plugins/remote_service/src/base64/cencode.c0000644000175000017500000000755311651544324022233 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ /* cencoder.c - c source to a base64 encoding algorithm implementation This is part of the libb64 project, and has been placed in the public domain. For details, see http://sourceforge.net/projects/libb64 */ #include "cencode.h" const int CHARS_PER_LINE = 72; void base64_init_encodestate(base64_encodestate* state_in) { state_in->step = step_A; state_in->result = 0; state_in->stepcount = 0; } char base64_encode_value(char value_in) { static const char* encoding = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; if (value_in > 63) return '='; return encoding[(int)value_in]; } int base64_encode_block(const char* plaintext_in, int length_in, char* code_out, base64_encodestate* state_in) { const char* plainchar = plaintext_in; const char* const plaintextend = plaintext_in + length_in; char* codechar = code_out; char result; char fragment; result = state_in->result; switch (state_in->step) { while (1) { case step_A: if (plainchar == plaintextend) { state_in->result = result; state_in->step = step_A; return codechar - code_out; } fragment = *plainchar++; result = (fragment & 0x0fc) >> 2; *codechar++ = base64_encode_value(result); result = (fragment & 0x003) << 4; case step_B: if (plainchar == plaintextend) { state_in->result = result; state_in->step = step_B; return codechar - code_out; } fragment = *plainchar++; result |= (fragment & 0x0f0) >> 4; *codechar++ = base64_encode_value(result); result = (fragment & 0x00f) << 2; case step_C: if (plainchar == plaintextend) { state_in->result = result; state_in->step = step_C; return codechar - code_out; } fragment = *plainchar++; result |= (fragment & 0x0c0) >> 6; *codechar++ = base64_encode_value(result); result = (fragment & 0x03f) >> 0; *codechar++ = base64_encode_value(result); ++(state_in->stepcount); if (state_in->stepcount == CHARS_PER_LINE/4) { *codechar++ = '\n'; state_in->stepcount = 0; } } } /* control should not reach here */ return codechar - code_out; } int base64_encode_blockend(char* code_out, base64_encodestate* state_in) { char* codechar = code_out; switch (state_in->step) { case step_B: *codechar++ = base64_encode_value(state_in->result); *codechar++ = '='; *codechar++ = '='; break; case step_C: *codechar++ = base64_encode_value(state_in->result); *codechar++ = '='; break; case step_A: break; } *codechar++ = '\n'; return codechar - code_out; } ugene-1.9.8/src/plugins/remote_service/src/base64/cencode.h0000644000175000017500000000133711651544324022232 0ustar ilyailya/* cencode.h - c header for a base64 encoding algorithm This is part of the libb64 project, and has been placed in the public domain. For details, see http://sourceforge.net/projects/libb64 */ #ifndef BASE64_CENCODE_H #define BASE64_CENCODE_H typedef enum { step_A, step_B, step_C } base64_encodestep; typedef struct { base64_encodestep step; char result; int stepcount; } base64_encodestate; void base64_init_encodestate(base64_encodestate* state_in); char base64_encode_value(char value_in); int base64_encode_block(const char* plaintext_in, int length_in, char* code_out, base64_encodestate* state_in); int base64_encode_blockend(char* code_out, base64_encodestate* state_in); #endif /* BASE64_CENCODE_H */ ugene-1.9.8/src/plugins/remote_service/src/base64/cdecode.c0000644000175000017500000000753611651544324022222 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ /* cdecoder.c - c source to a base64 decoding algorithm implementation This is part of the libb64 project, and has been placed in the public domain. For details, see http://sourceforge.net/projects/libb64 */ #include "cdecode.h" int base64_decode_value(char value_in) { static const char decoding[] = {62,-1,-1,-1,63,52,53,54,55,56,57,58,59,60,61,-1,-1,-1,-2,-1,-1,-1,0,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,-1,-1,-1,-1,-1,-1,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}; static const char decoding_size = sizeof(decoding); value_in -= 43; if (value_in < 0 || value_in > decoding_size) return -1; return decoding[(int)value_in]; } void base64_init_decodestate(base64_decodestate* state_in) { state_in->step = step_a; state_in->plainchar = 0; } int base64_decode_block(const char* code_in, const int length_in, char* plaintext_out, base64_decodestate* state_in) { const char* codechar = code_in; char* plainchar = plaintext_out; char fragment; *plainchar = state_in->plainchar; switch (state_in->step) { while (1) { case step_a: do { if (codechar == code_in+length_in) { state_in->step = step_a; state_in->plainchar = *plainchar; return plainchar - plaintext_out; } fragment = (char)base64_decode_value(*codechar++); } while (fragment < 0); *plainchar = (fragment & 0x03f) << 2; case step_b: do { if (codechar == code_in+length_in) { state_in->step = step_b; state_in->plainchar = *plainchar; return plainchar - plaintext_out; } fragment = (char)base64_decode_value(*codechar++); } while (fragment < 0); *plainchar++ |= (fragment & 0x030) >> 4; *plainchar = (fragment & 0x00f) << 4; case step_c: do { if (codechar == code_in+length_in) { state_in->step = step_c; state_in->plainchar = *plainchar; return plainchar - plaintext_out; } fragment = (char)base64_decode_value(*codechar++); } while (fragment < 0); *plainchar++ |= (fragment & 0x03c) >> 2; *plainchar = (fragment & 0x003) << 6; case step_d: do { if (codechar == code_in+length_in) { state_in->step = step_d; state_in->plainchar = *plainchar; return plainchar - plaintext_out; } fragment = (char)base64_decode_value(*codechar++); } while (fragment < 0); *plainchar++ |= (fragment & 0x03f); } } /* control should not reach here */ return plainchar - plaintext_out; } ugene-1.9.8/src/plugins/remote_service/src/base64/cdecode.h0000644000175000017500000000122111651544324022210 0ustar ilyailya/* cdecode.h - c header for a base64 decoding algorithm This is part of the libb64 project, and has been placed in the public domain. For details, see http://sourceforge.net/projects/libb64 */ #ifndef BASE64_CDECODE_H #define BASE64_CDECODE_H typedef enum { step_a, step_b, step_c, step_d } base64_decodestep; typedef struct { base64_decodestep step; char plainchar; } base64_decodestate; void base64_init_decodestate(base64_decodestate* state_in); int base64_decode_value(char value_in); int base64_decode_block(const char* code_in, const int length_in, char* plaintext_out, base64_decodestate* state_in); #endif /* BASE64_CDECODE_H */ ugene-1.9.8/src/plugins/remote_service/src/RemoteServiceSettingsUI.h0000644000175000017500000000311211651544324024272 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _REMOTE_SERVICE_SETTINGS_UI_H_ #define _REMOTE_SERVICE_SETTINGS_UI_H_ #include #include "ui/ui_RemoteServiceSupportUI.h" namespace U2 { class RemoteServiceMachineSettings; class RemoteServiceSettingsUI : public ProtocolUI, public Ui::RemoteServiceSupportUI { Q_OBJECT public: RemoteServiceSettingsUI(); virtual ~RemoteServiceSettingsUI(); virtual RemoteMachineSettings * createMachine() const; virtual void initializeWidget(const RemoteMachineSettings *settings); virtual void clearWidget(); virtual QDialog* createUserTasksDialog(const RemoteMachineSettings* settings, QWidget* parent); virtual QString validate() const; }; } // namespace U2 #endif // _REMOTE_SERVICE_SETTINGS_UI_H_ ugene-1.9.8/src/plugins/remote_service/src/RemoteServiceSettingsUI.cpp0000644000175000017500000000674411651544324024643 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include #include "RemoteServiceMachine.h" #include "RemoteServiceSettingsUI.h" #include "RemoteTasksDialog.h" static const int PORT_MAX = 0x7fff; namespace U2 { RemoteServiceSettingsUI::RemoteServiceSettingsUI() { setupUi(this); } RemoteServiceSettingsUI::~RemoteServiceSettingsUI() { } RemoteMachineSettings * RemoteServiceSettingsUI::createMachine() const { if( !validate().isEmpty()) { return NULL; } QString url = urlLineEdit->text().trimmed(); RemoteServiceMachineSettings* s = new RemoteServiceMachineSettings(url); if (guestRB->isChecked()) { s->setupCredentials(RemoteServiceMachineSettings::GUEST_ACCOUNT, QString(), true); } else { bool permanent = rememberEdit->isChecked(); s->setupCredentials(userNameEdit->text().trimmed(), passwdEdit->text(), permanent); } return s; } void RemoteServiceSettingsUI::initializeWidget(const RemoteMachineSettings *settings) { const RemoteServiceMachineSettings *castedSettings = dynamic_cast(settings); if (NULL != castedSettings) { urlLineEdit->setText(castedSettings->getUrl()); if (castedSettings->usesGuestAccount()) { guestRB->setChecked(true); } else { existingRB->setChecked(true); UserCredentials* credentials = settings->getUserCredentials(); if (credentials != NULL) { userNameEdit->setText(castedSettings->getUserName()); passwdEdit->setText(castedSettings->getPasswd()); rememberEdit->setChecked(credentials->permanent); } } } } QString RemoteServiceSettingsUI::validate() const { QString url = urlLineEdit->text(); if( url.isEmpty() ) { return tr( "Url is empty!" ); } else if (!url.startsWith("http://") && !(url.startsWith("https://"))) { return tr("Unknown URL schema. The url must start from http(s)://"); } if (existingRB->isChecked()) { if( userNameEdit->text().isEmpty()) { return tr( "User name is not valid!" ); } if( passwdEdit->text().isEmpty()) { return tr( "Password is empty!" ); } } return QString(); } void RemoteServiceSettingsUI::clearWidget() { } QDialog* RemoteServiceSettingsUI::createUserTasksDialog( const RemoteMachineSettings* s, QWidget* parent ) { const RemoteServiceMachineSettings* settings = dynamic_cast< const RemoteServiceMachineSettings* >(s); if (settings == NULL) { return NULL; } return new RemoteTasksDialog(settings, parent); } } // namespace U2 ugene-1.9.8/src/plugins/remote_service/src/RemoteServicePlugin.cpp0000644000175000017500000000721311651544324024033 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include #include #include #include #include #include "RemoteServiceCommon.h" #include "RemoteServicePlugin.h" #include "RemoteServiceSettingsUI.h" #include "RemoteServicePingTask.h" namespace U2 { #define EC2_URL "http://184.73.180.209:80/rservice/engine" #define EC2_PASS "rulezzz" #define PING_REMOTE_SERVICE "ping-remote-service" extern "C" Q_DECL_EXPORT U2::Plugin* U2_PLUGIN_INIT_FUNC() { RemoteServicePlugin* plug = new RemoteServicePlugin(); return plug; } const QString RemoteServiceCommon::WEB_TRANSPORT_PROTOCOL_ID = "Web transport protocol"; static void cleanupRemoteMachineMonitor() { RemoteMachineMonitor* rmm = AppContext::getRemoteMachineMonitor(); QList items = rmm->getRemoteMachineMonitorItems(); foreach (const RemoteMachineMonitorItem& item, items) { rmm->removeMachine(item.machine); } } RemoteServicePlugin::RemoteServicePlugin(): Plugin(tr("UGENE Remote Service Support"), tr("Launching remote tasks via UGENE Remote Service")), protocolUI((NULL == AppContext::getMainWindow())? NULL:(new RemoteServiceSettingsUI())), protocolInfo( RemoteServiceCommon::WEB_TRANSPORT_PROTOCOL_ID , protocolUI.get(), &remoteMachineFactory ) { AppContext::getProtocolInfoRegistry()->registerProtocolInfo(&protocolInfo); if (thisIsFirstLaunch()) { cleanupRemoteMachineMonitor(); RemoteServiceMachineSettings* settings = new RemoteServiceMachineSettings(EC2_URL); settings->setupCredentials(RemoteServiceMachineSettings::GUEST_ACCOUNT, EC2_PASS, true); AppContext::getRemoteMachineMonitor()->addMachine(settings, false); } registerCMDLineHelp(); processCMDLineOptions(); } RemoteServicePlugin::~RemoteServicePlugin() { } void RemoteServicePlugin::registerCMDLineHelp() { } void RemoteServicePlugin::processCMDLineOptions() { CMDLineRegistry * cmdlineReg = AppContext::getCMDLineRegistry(); assert(cmdlineReg != NULL); if( cmdlineReg->hasParameter( PING_REMOTE_SERVICE ) ) { QString machinePath = cmdlineReg->getParameterValue(PING_REMOTE_SERVICE); Task * t = new RemoteServicePingTask(machinePath); connect(AppContext::getPluginSupport(), SIGNAL(si_allStartUpPluginsLoaded()), new TaskStarter(t), SLOT(registerTask())); } } #define NOT_FIRST_LAUNCH "remote_service/not_first_launch" bool RemoteServicePlugin::thisIsFirstLaunch() { Settings* settings = AppContext::getSettings(); QString key = settings->toVersionKey(NOT_FIRST_LAUNCH); if (settings->contains(key)) { return false; } else { settings->setValue(key, QVariant(true)); return true; } } } // namespace U2 ugene-1.9.8/src/plugins/remote_service/src/Base64File.h0000644000175000017500000000311211651544324021363 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _BASE64_FILE_H_ #define _BASE64_FILE_H_ #include extern "C" { #include "base64/cencode.h" } namespace U2 { class Base64File : public QIODevice { public: Base64File(const QString& url); virtual bool isSequential() const { return true; } virtual bool open(OpenMode mode); virtual qint64 size() const; QString fileName() const { return file.fileName(); } protected: virtual qint64 readData(char *data, qint64 maxlen); virtual qint64 writeData(const char* data, qint64 maxlen); private: QByteArray buf; qint64 bufLen; qint64 bufOffset; QFile file; base64_encodestate encodeState; }; } // namespace #endif // _BASE64_FILE_H_ ugene-1.9.8/src/plugins/remote_service/src/RemoteServicePingTask.h0000644000175000017500000000261111651544324023757 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _REMOTE_SERVICE_PING_TASK_H_ #define _REMOTE_SERVICE_PING_TASK_H_ #include #include namespace U2 { class RemoteServiceMachine; class RemoteServiceMachineFactory; class RemoteServicePingTask : public Task { public: RemoteServicePingTask(const QString& url); virtual void prepare(); virtual void run(); private: QString machinePath; std::auto_ptr machine; std::auto_ptr machineFactory; }; } // namespace U2 #endif // _REMOTE_SERVICE_PING_TASK_H_ ugene-1.9.8/src/plugins/remote_service/src/UctpRequestBuilders.h0000644000175000017500000000652211651544324023525 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _UCTP_REQUEST_BUILDERS_H_ #define _UCTP_REQUEST_BUILDERS_H_ #include "WebTransportProtocol.h" #include "BufferedDataReader.h" namespace U2 { class InitSessionRequest : public UctpRequestBuilder { QString name; QString pass; public: InitSessionRequest(const QString& username, const QString& passwd); protected: virtual void formContents(QXmlStreamWriter& stream); }; class PingRequest : public UctpRequestBuilder { public: PingRequest() : UctpRequestBuilder(UctpCommands::PING) {} protected: virtual void formContents(QXmlStreamWriter& ) {} }; class GetGlobalPropertyRequest : public UctpRequestBuilder { UctpSession* session; QByteArray propName; public: GetGlobalPropertyRequest(UctpSession* s, const QByteArray& propertyName) : UctpRequestBuilder(UctpCommands::GET_PROPERTY), session(s), propName(propertyName) {} protected: virtual void formContents(QXmlStreamWriter& writer); }; class GetRemoteTaskPropertyRequest : public UctpRequestBuilder { UctpSession* session; qint64 taskId; QStringList properties; public: GetRemoteTaskPropertyRequest(UctpSession* s, qint64 id, const QStringList& props) : UctpRequestBuilder(UctpCommands::GET_PROPERTY), session(s), taskId(id), properties(props) {} protected: virtual void formContents(QXmlStreamWriter& writer); }; class GetRemoteTaskResultRequst : public UctpRequestBuilder { UctpSession* session; qint64 taskId; public: GetRemoteTaskResultRequst(UctpSession* s, qint64 id) : UctpRequestBuilder(UctpCommands::GET_TASK_RESULT), session(s), taskId(id) {} protected: virtual void formContents(QXmlStreamWriter& writer); }; class RunRemoteTaskRequest : public UctpRequestBuilder { UctpSession* session; const QByteArray& taskSchema; const QStringList& inputUrls; BufferedDataReader* reader; QByteArray prepareRequestTemplate(); public: RunRemoteTaskRequest(UctpSession* session, const QByteArray& task, const QStringList& input); ~RunRemoteTaskRequest(); virtual QIODevice* getDataSource(); protected: virtual void formContents(QXmlStreamWriter& writer); }; class UpdateRemoteTaskRequest : public UctpRequestBuilder { UctpSession* session; qint64 taskId; public: UpdateRemoteTaskRequest(const UctpCommand& cmd, UctpSession* s, qint64 id) : UctpRequestBuilder(cmd), session(s), taskId(id) {} protected: virtual void formContents(QXmlStreamWriter& stream); }; } // namespace #endif // _UCTP_REQUEST_BUILDERS_H_ugene-1.9.8/src/plugins/remote_service/src/RemoteServicePlugin.h0000644000175000017500000000277611651544324023511 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _REMOTE_SERVICE_PLUGIN_H_ #define _REMOTE_SERVICE_PLUGIN_H_ #include #include #include #include "RemoteServiceMachine.h" namespace U2 { class RemoteServiceSettingsUI; class RemoteServicePlugin : public Plugin { Q_OBJECT public: RemoteServicePlugin(); virtual ~RemoteServicePlugin(); private: std::auto_ptr protocolUI; RemoteServiceMachineFactory remoteMachineFactory; ProtocolInfo protocolInfo; private: bool thisIsFirstLaunch(); void registerCMDLineHelp(); void processCMDLineOptions(); }; } // namespace U2 #endif // _REMOTE_SERVICE_PLUGIN_H_ugene-1.9.8/src/plugins/remote_service/src/BufferedDataReader.h0000644000175000017500000000347611651544324023213 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _BUFFERED_DATA_READER_H_ #define _BUFFERED_DATA_READER_H_ #include #include #include #include #include "Base64File.h" namespace U2 { class BufferedDataReader : public QIODevice { public: BufferedDataReader(const QStringList& inputUrls, const QByteArray& requestTemplate, const QByteArray& splitMarker); ~BufferedDataReader(); virtual bool isSequential() const { return true; } virtual bool open(OpenMode mode); virtual qint64 size() const; void setError(const QString& errMsg); protected: virtual qint64 readData(char *data, qint64 maxlen); virtual qint64 writeData(const char* data, qint64 maxlen); private: QList inputDevs; QList inputFiles; QList inputBufs; QList buffersData; int curIdx; bool hasErrors; }; } //namespace #endif // _BUFFERED_DATA_READER_H_ ugene-1.9.8/src/plugins/remote_service/src/WebTransportProtocol.cpp0000644000175000017500000001642711651544324024263 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include #include #include "WebTransportProtocol.h" namespace U2 { const QByteArray UctpElements::REQUEST("request"); const QByteArray UctpElements::RESPONSE("response"); const QByteArray UctpElements::STATUS("status"); const QByteArray UctpElements::APP_VERSION("app-version"); const QByteArray UctpElements::MESSAGE("message"); const QByteArray UctpElements::USER_NAME("username"); const QByteArray UctpElements::PASSWD("passwd"); const QByteArray UctpElements::PROPERTY("property"); const QByteArray UctpElements::TASK("task"); const QByteArray UctpElements::TASK_STATE("state"); const QByteArray UctpElements::TASK_ERROR("error"); const QByteArray UctpElements::TASK_PROGRESS("progress"); const QByteArray UctpElements::TASK_RESULTS("task-results"); const QByteArray UctpElements::DATA("data"); const QByteArray UctpElements::DATE_SUBMITTED("state.NEW"); const QByteArray UctpElements::SESSION("session"); const QByteArray UctpAttributes::TASK_ID("task-id"); const QByteArray UctpAttributes::SESSION_ID("session-id"); const QByteArray UctpAttributes::COMMAND_TYPE("type"); const QByteArray UctpAttributes::IS_GZIPPED("gzipped"); const QByteArray UctpAttributes::ENCODING("encoding"); const QByteArray UctpAttributes::NAME("name"); const QByteArray UctpAttributes::SIZE("size"); const UctpCommand UctpCommands::AUTH("AUTH"); const UctpCommand UctpCommands::RUN_TASK("RUN_TASK"); const UctpCommand UctpCommands::DELETE_TASK("DELETE_TASK"); const UctpCommand UctpCommands::PING("PING"); const UctpCommand UctpCommands::GET_TASK_RESULT("GET_TASK_RESULT"); const UctpCommand UctpCommands::GET_PROPERTY("GET_PROPERTY"); const UctpCommand UctpCommands::CANCEL_TASK("CANCEL_TASK"); const QByteArray UctpValues::BASE64("BASE64"); const QByteArray UctpValues::UCTP_TRUE("true"); const QByteArray UctpValues::UCTP_FALSE("false"); const QByteArray UctpValues::UCTP_STATE_FINISHED("FINISHED"); const QByteArray UctpValues::STATUS_ERROR("ERROR"); const QByteArray UctpValues::STATUS_OK("OK"); const QByteArray BaseGlobalProperties::HOST_NAME("server-name"); const QByteArray BaseGlobalProperties::TASKS_LIST_ACTIVE("tasks-list-active"); const QByteArray BaseGlobalProperties::TASKS_LIST_FINISHED("tasks-list-finished"); ////////////////////////////////////////////////////////////////////////// void UctpSession::buildQUuid( QUuid* uuid ) const { assert(uuid != NULL); // construct uuid from MD5 representation of session-id QByteArray digest = QByteArray::fromHex(uid); memcpy((unsigned char*)(uuid), digest.constData(), sizeof(QUuid)); assert(!uuid->isNull()); } QIODevice* UctpRequestBuilder::getDataSource() { QByteArray request; QXmlStreamWriter stream(&request); stream.writeStartDocument(); stream.writeStartElement(UctpElements::REQUEST); stream.writeAttribute(UctpAttributes::COMMAND_TYPE, getCommand()); stream.writeAttribute(UctpElements::APP_VERSION, Version::ugeneVersion().text ); // Contents section formContents(stream); stream.writeEndElement(); stream.writeEndDocument(); requestBuf.setData(request); return &requestBuf; } bool Uctp::parseReply( QIODevice* reply, const UctpCommand& command, QMap& data) { QXmlInputSource source(reply); QList expectedElements; // = getExpectedElements(command); UctpReplyContext context(command, expectedElements); UctpReplyHandler* handler = new UctpReplyHandler(context,data); xmlReader.setContentHandler(handler); xmlReader.setErrorHandler(handler); bool ok = xmlReader.parse(source); errorString = handler->errorString(); return ok; } ////////////////////////////////////////////////////////////////////////// UctpReplyHandler::UctpReplyHandler(const UctpReplyContext& ctx, QMap& data) : replyResultOk(false), context(ctx), replyData(data), envelope(false), header(false), contents(false) { } bool UctpReplyHandler::startElement( const QString &namespaceURI, const QString &localName, const QString &qName, const QXmlAttributes &attributes ) { Q_UNUSED(namespaceURI); Q_UNUSED(localName); if (qName == UctpElements::RESPONSE) { envelope = true; } xmlAttrMap.insert(qName, attributes); ioLog.trace(QString("Parsing element %1").arg(qName)); curText.clear(); return true; } bool UctpReplyHandler::endElement(const QString &namespaceURI, const QString &localName, const QString &qName) { Q_UNUSED(namespaceURI); Q_UNUSED(localName); const QXmlAttributes& currentAttributes = xmlAttrMap.value(qName); if (qName == UctpElements::RESPONSE) { QString status = currentAttributes.value(QString(UctpElements::STATUS)); if (status == UctpValues::STATUS_OK) { replyResultOk = true; coreLog.trace("Uctp request succeed"); } } UctpElementData data; data.textData = curText; for (int i = 0; i < currentAttributes.length(); ++i) { QString aName = currentAttributes.qName(i); QString aValue = currentAttributes.value(i); data.attributesMap.insert(aName.toAscii(),aValue.toAscii()); } replyData.insertMulti(qName, data); return true; } bool UctpReplyHandler::endDocument() { bool structureValid = envelope; if (!structureValid) { errorMessage = QString(QObject::tr("Invalid response structure")); return false; } if (!validateContext()) { errorMessage = QString(QObject::tr("Invalid response: missing elements")); return false; } if (!replyResultOk) { QString reason; if (replyData.contains(UctpElements::MESSAGE)) { reason = replyData.value(UctpElements::MESSAGE).textData; } else { reason = QString("status is not available"); } errorMessage = QString("RService request failed: %1.").arg(reason); return false; } return true; } bool UctpReplyHandler::characters(const QString &str) { curText += str; return true; } bool UctpReplyHandler::validateContext() { foreach (const QString& elemName, context.getExpectedElements()) { if(!replyData.contains(elemName)) { return false; } } return true; } QString UctpReplyHandler::errorString() const { if (errorMessage.isEmpty()) { return QString("Error processing XML response"); } else { return errorMessage; } } UctpError::~UctpError() throw() { } } // namespace U2 ugene-1.9.8/src/plugins/remote_service/remote_service.pro0000644000175000017500000000207011651544324022336 0ustar ilyailyainclude (remote_service.pri) # Input HEADERS += src/Base64File.h \ src/BufferedDataReader.h \ src/RemoteServiceCommon.h \ src/RemoteServiceMachine.h \ src/RemoteServicePingTask.h \ src/RemoteServicePlugin.h \ src/RemoteServiceSettingsUI.h \ src/RemoteServiceUtilTasks.h \ src/RemoteTasksDialog.h \ src/UctpRequestBuilders.h \ src/WebTransportProtocol.h \ src/base64/cdecode.h \ src/base64/cencode.h FORMS += src/ui/RemoteServiceSupportUI.ui src/ui/TaskStatisticsDialog.ui SOURCES += src/Base64File.cpp \ src/BufferedDataReader.cpp \ src/RemoteServiceMachine.cpp \ src/RemoteServicePingTask.cpp \ src/RemoteServicePlugin.cpp \ src/RemoteServiceSettingsUI.cpp \ src/RemoteServiceUtilTasks.cpp \ src/RemoteTasksDialog.cpp \ src/UctpRequestBuilders.cpp \ src/WebTransportProtocol.cpp \ src/base64/cdecode.c \ src/base64/cencode.c ugene-1.9.8/src/plugins/remote_service/transl/0000755000175000017500000000000011651544324020105 5ustar ilyailyaugene-1.9.8/src/gen_bin_script.cmd0000755000175000017500000000016011651544307015561 0ustar ilyailyaecho '#!/bin/bash' echo 'LD_LIBRARY_PATH=$LD_LIBRARY_PATH:'$1 echo 'export LD_LIBRARY_PATH' echo $1'/'$2 '"$@"' ugene-1.9.8/src/ugene_plugin_descriptor.pri0000644000175000017500000000701111651544307017541 0ustar ilyailya# This file generates plugin descriptor and puts it to the DESTDIR # # Plugin descriptor related fields that must/can be passed by caller # # PLUGIN_ID (required) - Unique plugin id # # PLUGIN_NAME (required) - Textual name, used only during the loading process for visualization # # PLUGIN_VENDOR (required) - Vendor of the plugin. For example: Unipro # # PLUGIN_VERSION (optional) - Version of the plugin. By default = UGENE_VERSION # Default value = UGENE_VERSION # # TARGET (optional) - Plugin binary file name. For example: libofmarker.so, orfmaker.dll # Default value is derived from PLUGIN_ID # # PLUGIN_DEPENDS (optional) - Depends line for the plugin: plugin_id1:version1;plugin_id2:version2 # For example: orf_marker:1.8.0;dna_export:1.7.2 # Default value = empty (no dependencies) # # PLUGIN_MODE (optional) - Valid values: 'ui', 'console'. Can be combined in a list with spaces or commas # Default value: 'console,ui' # # Unique plugin ID isEmpty(PLUGIN_ID) { error("PLUGIN_ID is not set!"); } # Visual name of the plugin. Not localized. Shown to user only if some error found during the loading stage isEmpty(PLUGIN_NAME) { error("PLUGIN_NAME is not set!"); } # Version of the plugin. If not set, UGENE version is used isEmpty(PLUGIN_VERSION) { PLUGIN_VERSION=$${UGENE_VERSION} } # Vendor of the plugin. Must be set isEmpty(PLUGIN_VENDOR) { error("PLUGIN_VENDOR is not set!"); } # Library of the plugin isEmpty(TARGET) { error("TARGET is not set") } PLUGIN_LIBRARY=$${TARGET} win32: PLUGIN_LIBRARY=$$join(PLUGIN_LIBRARY,"", "", ".dll") unix:!macx: PLUGIN_LIBRARY=$$join(PLUGIN_LIBRARY, "", "lib", ".so") macx: PLUGIN_LIBRARY=$$join(PLUGIN_LIBRARY, "", "lib", ".dylib") # Set platform info win32: PLATFORM_NAME="win" unix:!macx: PLATFORM_NAME="unix" macx: PLATFORM_NAME="macx" !contains(QMAKE_HOST.arch, x86_64) : PLATFORM_ARCH=32 contains (QMAKE_HOST.arch, x86_64) : PLATFORM_ARCH=64 # Set plugin mode isEmpty(PLUGIN_MODE) { PLUGIN_MODE="console,ui" } # Now generate the descriptor !debug_and_release|build_pass { CONFIG(debug, debug|release) { PLUGIN_DESC_FILE=_debug/plugins/$${PLUGIN_ID}.plugin } CONFIG(release, debug|release) { PLUGIN_DESC_FILE=_release/plugins/$${PLUGIN_ID}.plugin } } defineTest(write){ val = $$1 op = $$2 win32: val ~= s/>/^> win32: val ~= s/", >) write("", >>) write(" $${PLUGIN_NAME}", >>) write(" $${PLUGIN_VENDOR}", >>) write(" $${PLUGIN_MODE}", >>) write(" $${PLUGIN_LIBRARY}", >>) !isEmpty(PLUGIN_DEPENDS) { write(" $${PLUGIN_DEPENDS}", >>) } write(" ", >>) !debug_and_release|build_pass { CONFIG(debug, debug|release) { write(" true", >>) } } write("", >>) ugene-1.9.8/src/libs_3rdparty/0000755000175000017500000000000011654525446014676 5ustar ilyailyaugene-1.9.8/src/libs_3rdparty/gtest/0000755000175000017500000000000011651544307016016 5ustar ilyailyaugene-1.9.8/src/libs_3rdparty/gtest/gtest.pri0000644000175000017500000000173611651544307017667 0ustar ilyailya# include (gtest.pri) include( ../../ugene_globals.pri ) UGENE_RELATIVE_DESTDIR = '' TARGET = gtest TEMPLATE = lib CONFIG +=thread debug_and_release warn_off INCLUDEPATH += src LIBS += -L../../_release DEFINES+=GTEST_CREATE_SHARED_LIBRARY=1 #DEFINES+=GTEST_LINKED_AS_SHARED_LIBRARY=1 !debug_and_release|build_pass { CONFIG(debug, debug|release) { TARGET = gtestd DEFINES+=_DEBUG CONFIG +=console DESTDIR=../../_debug/ OBJECTS_DIR=_tmp/obj/debug LIBS -= -L../../_release LIBS += -L../../_debug } CONFIG(release, debug|release) { TARGET = gtest DEFINES+=NDEBUG DESTDIR=../../_release/ OBJECTS_DIR=_tmp/obj/release } } win32 { QMAKE_CXXFLAGS_WARN_ON = -W3 QMAKE_CFLAGS_WARN_ON = -W3 QMAKE_MSVC_PROJECT_NAME=lib_3rd_gtest } unix { target.path = $$UGENE_INSTALL_DIR/$$UGENE_RELATIVE_DESTDIR INSTALLS += target } ugene-1.9.8/src/libs_3rdparty/gtest/src/0000755000175000017500000000000011651544307016605 5ustar ilyailyaugene-1.9.8/src/libs_3rdparty/gtest/src/gtest_prod_test.cc0000644000175000017500000000424111651544307022326 0ustar ilyailya// Copyright 2006, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Author: wan@google.com (Zhanyong Wan) // // Unit test for include/gtest/gtest_prod.h. #include "gtest/gtest.h" #include "test/production.h" // Tests that private members can be accessed from a TEST declared as // a friend of the class. TEST(PrivateCodeTest, CanAccessPrivateMembers) { PrivateCode a; EXPECT_EQ(0, a.x_); a.set_x(1); EXPECT_EQ(1, a.x_); } typedef testing::Test PrivateCodeFixtureTest; // Tests that private members can be accessed from a TEST_F declared // as a friend of the class. TEST_F(PrivateCodeFixtureTest, CanAccessPrivateMembers) { PrivateCode a; EXPECT_EQ(0, a.x_); a.set_x(2); EXPECT_EQ(2, a.x_); } ugene-1.9.8/src/libs_3rdparty/gtest/src/gtest-all.cc0000644000175000017500000000416111651544307021012 0ustar ilyailya// Copyright 2008, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Author: mheule@google.com (Markus Heule) // // Google C++ Testing Framework (Google Test) // // Sometimes it's desirable to build Google Test by compiling a single file. // This file serves this purpose. // This line ensures that gtest.h can be compiled on its own, even // when it's fused. #include "gtest/gtest.h" // The following lines pull in the real gtest *.cc files. #include "src/gtest.cc" #include "src/gtest-death-test.cc" #include "src/gtest-filepath.cc" #include "src/gtest-port.cc" #include "src/gtest-printers.cc" #include "src/gtest-test-part.cc" #include "src/gtest-typed-test.cc" ugene-1.9.8/src/libs_3rdparty/gtest/src/gtest/0000755000175000017500000000000011651544307017733 5ustar ilyailyaugene-1.9.8/src/libs_3rdparty/gtest/src/gtest/gtest-typed-test.h0000644000175000017500000002400211651544307023330 0ustar ilyailya// Copyright 2008 Google Inc. // All Rights Reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Author: wan@google.com (Zhanyong Wan) #ifndef GTEST_INCLUDE_GTEST_GTEST_TYPED_TEST_H_ #define GTEST_INCLUDE_GTEST_GTEST_TYPED_TEST_H_ // This header implements typed tests and type-parameterized tests. // Typed (aka type-driven) tests repeat the same test for types in a // list. You must know which types you want to test with when writing // typed tests. Here's how you do it: #if 0 // First, define a fixture class template. It should be parameterized // by a type. Remember to derive it from testing::Test. template class FooTest : public testing::Test { public: ... typedef std::list List; static T shared_; T value_; }; // Next, associate a list of types with the test case, which will be // repeated for each type in the list. The typedef is necessary for // the macro to parse correctly. typedef testing::Types MyTypes; TYPED_TEST_CASE(FooTest, MyTypes); // If the type list contains only one type, you can write that type // directly without Types<...>: // TYPED_TEST_CASE(FooTest, int); // Then, use TYPED_TEST() instead of TEST_F() to define as many typed // tests for this test case as you want. TYPED_TEST(FooTest, DoesBlah) { // Inside a test, refer to TypeParam to get the type parameter. // Since we are inside a derived class template, C++ requires use to // visit the members of FooTest via 'this'. TypeParam n = this->value_; // To visit static members of the fixture, add the TestFixture:: // prefix. n += TestFixture::shared_; // To refer to typedefs in the fixture, add the "typename // TestFixture::" prefix. typename TestFixture::List values; values.push_back(n); ... } TYPED_TEST(FooTest, HasPropertyA) { ... } #endif // 0 // Type-parameterized tests are abstract test patterns parameterized // by a type. Compared with typed tests, type-parameterized tests // allow you to define the test pattern without knowing what the type // parameters are. The defined pattern can be instantiated with // different types any number of times, in any number of translation // units. // // If you are designing an interface or concept, you can define a // suite of type-parameterized tests to verify properties that any // valid implementation of the interface/concept should have. Then, // each implementation can easily instantiate the test suite to verify // that it conforms to the requirements, without having to write // similar tests repeatedly. Here's an example: #if 0 // First, define a fixture class template. It should be parameterized // by a type. Remember to derive it from testing::Test. template class FooTest : public testing::Test { ... }; // Next, declare that you will define a type-parameterized test case // (the _P suffix is for "parameterized" or "pattern", whichever you // prefer): TYPED_TEST_CASE_P(FooTest); // Then, use TYPED_TEST_P() to define as many type-parameterized tests // for this type-parameterized test case as you want. TYPED_TEST_P(FooTest, DoesBlah) { // Inside a test, refer to TypeParam to get the type parameter. TypeParam n = 0; ... } TYPED_TEST_P(FooTest, HasPropertyA) { ... } // Now the tricky part: you need to register all test patterns before // you can instantiate them. The first argument of the macro is the // test case name; the rest are the names of the tests in this test // case. REGISTER_TYPED_TEST_CASE_P(FooTest, DoesBlah, HasPropertyA); // Finally, you are free to instantiate the pattern with the types you // want. If you put the above code in a header file, you can #include // it in multiple C++ source files and instantiate it multiple times. // // To distinguish different instances of the pattern, the first // argument to the INSTANTIATE_* macro is a prefix that will be added // to the actual test case name. Remember to pick unique prefixes for // different instances. typedef testing::Types MyTypes; INSTANTIATE_TYPED_TEST_CASE_P(My, FooTest, MyTypes); // If the type list contains only one type, you can write that type // directly without Types<...>: // INSTANTIATE_TYPED_TEST_CASE_P(My, FooTest, int); #endif // 0 #include "gtest/internal/gtest-port.h" #include "gtest/internal/gtest-type-util.h" // Implements typed tests. #if GTEST_HAS_TYPED_TEST // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE. // // Expands to the name of the typedef for the type parameters of the // given test case. # define GTEST_TYPE_PARAMS_(TestCaseName) gtest_type_params_##TestCaseName##_ // The 'Types' template argument below must have spaces around it // since some compilers may choke on '>>' when passing a template // instance (e.g. Types) # define TYPED_TEST_CASE(CaseName, Types) \ typedef ::testing::internal::TypeList< Types >::type \ GTEST_TYPE_PARAMS_(CaseName) # define TYPED_TEST(CaseName, TestName) \ template \ class GTEST_TEST_CLASS_NAME_(CaseName, TestName) \ : public CaseName { \ private: \ typedef CaseName TestFixture; \ typedef gtest_TypeParam_ TypeParam; \ virtual void TestBody(); \ }; \ bool gtest_##CaseName##_##TestName##_registered_ GTEST_ATTRIBUTE_UNUSED_ = \ ::testing::internal::TypeParameterizedTest< \ CaseName, \ ::testing::internal::TemplateSel< \ GTEST_TEST_CLASS_NAME_(CaseName, TestName)>, \ GTEST_TYPE_PARAMS_(CaseName)>::Register(\ "", #CaseName, #TestName, 0); \ template \ void GTEST_TEST_CLASS_NAME_(CaseName, TestName)::TestBody() #endif // GTEST_HAS_TYPED_TEST // Implements type-parameterized tests. #if GTEST_HAS_TYPED_TEST_P // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE. // // Expands to the namespace name that the type-parameterized tests for // the given type-parameterized test case are defined in. The exact // name of the namespace is subject to change without notice. # define GTEST_CASE_NAMESPACE_(TestCaseName) \ gtest_case_##TestCaseName##_ // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE. // // Expands to the name of the variable used to remember the names of // the defined tests in the given test case. # define GTEST_TYPED_TEST_CASE_P_STATE_(TestCaseName) \ gtest_typed_test_case_p_state_##TestCaseName##_ // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE DIRECTLY. // // Expands to the name of the variable used to remember the names of // the registered tests in the given test case. # define GTEST_REGISTERED_TEST_NAMES_(TestCaseName) \ gtest_registered_test_names_##TestCaseName##_ // The variables defined in the type-parameterized test macros are // static as typically these macros are used in a .h file that can be // #included in multiple translation units linked together. # define TYPED_TEST_CASE_P(CaseName) \ static ::testing::internal::TypedTestCasePState \ GTEST_TYPED_TEST_CASE_P_STATE_(CaseName) # define TYPED_TEST_P(CaseName, TestName) \ namespace GTEST_CASE_NAMESPACE_(CaseName) { \ template \ class TestName : public CaseName { \ private: \ typedef CaseName TestFixture; \ typedef gtest_TypeParam_ TypeParam; \ virtual void TestBody(); \ }; \ static bool gtest_##TestName##_defined_ GTEST_ATTRIBUTE_UNUSED_ = \ GTEST_TYPED_TEST_CASE_P_STATE_(CaseName).AddTestName(\ __FILE__, __LINE__, #CaseName, #TestName); \ } \ template \ void GTEST_CASE_NAMESPACE_(CaseName)::TestName::TestBody() # define REGISTER_TYPED_TEST_CASE_P(CaseName, ...) \ namespace GTEST_CASE_NAMESPACE_(CaseName) { \ typedef ::testing::internal::Templates<__VA_ARGS__>::type gtest_AllTests_; \ } \ static const char* const GTEST_REGISTERED_TEST_NAMES_(CaseName) = \ GTEST_TYPED_TEST_CASE_P_STATE_(CaseName).VerifyRegisteredTestNames(\ __FILE__, __LINE__, #__VA_ARGS__) // The 'Types' template argument below must have spaces around it // since some compilers may choke on '>>' when passing a template // instance (e.g. Types) # define INSTANTIATE_TYPED_TEST_CASE_P(Prefix, CaseName, Types) \ bool gtest_##Prefix##_##CaseName GTEST_ATTRIBUTE_UNUSED_ = \ ::testing::internal::TypeParameterizedTestCase::type>::Register(\ #Prefix, #CaseName, GTEST_REGISTERED_TEST_NAMES_(CaseName)) #endif // GTEST_HAS_TYPED_TEST_P #endif // GTEST_INCLUDE_GTEST_GTEST_TYPED_TEST_H_ ugene-1.9.8/src/libs_3rdparty/gtest/src/gtest/gtest-message.h0000644000175000017500000002031311651544307022653 0ustar ilyailya// Copyright 2005, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Author: wan@google.com (Zhanyong Wan) // // The Google C++ Testing Framework (Google Test) // // This header file defines the Message class. // // IMPORTANT NOTE: Due to limitation of the C++ language, we have to // leave some internal implementation details in this header file. // They are clearly marked by comments like this: // // // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. // // Such code is NOT meant to be used by a user directly, and is subject // to CHANGE WITHOUT NOTICE. Therefore DO NOT DEPEND ON IT in a user // program! #ifndef GTEST_INCLUDE_GTEST_GTEST_MESSAGE_H_ #define GTEST_INCLUDE_GTEST_GTEST_MESSAGE_H_ #include #include "gtest/internal/gtest-string.h" #include "gtest/internal/gtest-internal.h" namespace testing { // The Message class works like an ostream repeater. // // Typical usage: // // 1. You stream a bunch of values to a Message object. // It will remember the text in a stringstream. // 2. Then you stream the Message object to an ostream. // This causes the text in the Message to be streamed // to the ostream. // // For example; // // testing::Message foo; // foo << 1 << " != " << 2; // std::cout << foo; // // will print "1 != 2". // // Message is not intended to be inherited from. In particular, its // destructor is not virtual. // // Note that stringstream behaves differently in gcc and in MSVC. You // can stream a NULL char pointer to it in the former, but not in the // latter (it causes an access violation if you do). The Message // class hides this difference by treating a NULL char pointer as // "(null)". class GTEST_API_ Message { private: // The type of basic IO manipulators (endl, ends, and flush) for // narrow streams. typedef std::ostream& (*BasicNarrowIoManip)(std::ostream&); public: // Constructs an empty Message. // We allocate the stringstream separately because otherwise each use of // ASSERT/EXPECT in a procedure adds over 200 bytes to the procedure's // stack frame leading to huge stack frames in some cases; gcc does not reuse // the stack space. Message() : ss_(new ::std::stringstream) { // By default, we want there to be enough precision when printing // a double to a Message. *ss_ << std::setprecision(std::numeric_limits::digits10 + 2); } // Copy constructor. Message(const Message& msg) : ss_(new ::std::stringstream) { // NOLINT *ss_ << msg.GetString(); } // Constructs a Message from a C-string. explicit Message(const char* str) : ss_(new ::std::stringstream) { *ss_ << str; } #if GTEST_OS_SYMBIAN // Streams a value (either a pointer or not) to this object. template inline Message& operator <<(const T& value) { StreamHelper(typename internal::is_pointer::type(), value); return *this; } #else // Streams a non-pointer value to this object. template inline Message& operator <<(const T& val) { ::GTestStreamToHelper(ss_.get(), val); return *this; } // Streams a pointer value to this object. // // This function is an overload of the previous one. When you // stream a pointer to a Message, this definition will be used as it // is more specialized. (The C++ Standard, section // [temp.func.order].) If you stream a non-pointer, then the // previous definition will be used. // // The reason for this overload is that streaming a NULL pointer to // ostream is undefined behavior. Depending on the compiler, you // may get "0", "(nil)", "(null)", or an access violation. To // ensure consistent result across compilers, we always treat NULL // as "(null)". template inline Message& operator <<(T* const& pointer) { // NOLINT if (pointer == NULL) { *ss_ << "(null)"; } else { ::GTestStreamToHelper(ss_.get(), pointer); } return *this; } #endif // GTEST_OS_SYMBIAN // Since the basic IO manipulators are overloaded for both narrow // and wide streams, we have to provide this specialized definition // of operator <<, even though its body is the same as the // templatized version above. Without this definition, streaming // endl or other basic IO manipulators to Message will confuse the // compiler. Message& operator <<(BasicNarrowIoManip val) { *ss_ << val; return *this; } // Instead of 1/0, we want to see true/false for bool values. Message& operator <<(bool b) { return *this << (b ? "true" : "false"); } // These two overloads allow streaming a wide C string to a Message // using the UTF-8 encoding. Message& operator <<(const wchar_t* wide_c_str) { return *this << internal::String::ShowWideCString(wide_c_str); } Message& operator <<(wchar_t* wide_c_str) { return *this << internal::String::ShowWideCString(wide_c_str); } #if GTEST_HAS_STD_WSTRING // Converts the given wide string to a narrow string using the UTF-8 // encoding, and streams the result to this Message object. Message& operator <<(const ::std::wstring& wstr); #endif // GTEST_HAS_STD_WSTRING #if GTEST_HAS_GLOBAL_WSTRING // Converts the given wide string to a narrow string using the UTF-8 // encoding, and streams the result to this Message object. Message& operator <<(const ::wstring& wstr); #endif // GTEST_HAS_GLOBAL_WSTRING // Gets the text streamed to this object so far as a String. // Each '\0' character in the buffer is replaced with "\\0". // // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. internal::String GetString() const { return internal::StringStreamToString(ss_.get()); } private: #if GTEST_OS_SYMBIAN // These are needed as the Nokia Symbian Compiler cannot decide between // const T& and const T* in a function template. The Nokia compiler _can_ // decide between class template specializations for T and T*, so a // tr1::type_traits-like is_pointer works, and we can overload on that. template inline void StreamHelper(internal::true_type /*dummy*/, T* pointer) { if (pointer == NULL) { *ss_ << "(null)"; } else { ::GTestStreamToHelper(ss_.get(), pointer); } } template inline void StreamHelper(internal::false_type /*dummy*/, const T& value) { ::GTestStreamToHelper(ss_.get(), value); } #endif // GTEST_OS_SYMBIAN // We'll hold the text streamed to this object here. const internal::scoped_ptr< ::std::stringstream> ss_; // We declare (but don't implement) this to prevent the compiler // from implementing the assignment operator. void operator=(const Message&); }; // Streams a Message to an ostream. inline std::ostream& operator <<(std::ostream& os, const Message& sb) { return os << sb.GetString(); } } // namespace testing #endif // GTEST_INCLUDE_GTEST_GTEST_MESSAGE_H_ ugene-1.9.8/src/libs_3rdparty/gtest/src/gtest/gtest-test-part.h0000644000175000017500000001450511651544307023160 0ustar ilyailya// Copyright 2008, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Author: mheule@google.com (Markus Heule) // #ifndef GTEST_INCLUDE_GTEST_GTEST_TEST_PART_H_ #define GTEST_INCLUDE_GTEST_GTEST_TEST_PART_H_ #include #include #include "gtest/internal/gtest-internal.h" #include "gtest/internal/gtest-string.h" namespace testing { // A copyable object representing the result of a test part (i.e. an // assertion or an explicit FAIL(), ADD_FAILURE(), or SUCCESS()). // // Don't inherit from TestPartResult as its destructor is not virtual. class GTEST_API_ TestPartResult { public: // The possible outcomes of a test part (i.e. an assertion or an // explicit SUCCEED(), FAIL(), or ADD_FAILURE()). enum Type { kSuccess, // Succeeded. kNonFatalFailure, // Failed but the test can continue. kFatalFailure // Failed and the test should be terminated. }; // C'tor. TestPartResult does NOT have a default constructor. // Always use this constructor (with parameters) to create a // TestPartResult object. TestPartResult(Type a_type, const char* a_file_name, int a_line_number, const char* a_message) : type_(a_type), file_name_(a_file_name), line_number_(a_line_number), summary_(ExtractSummary(a_message)), message_(a_message) { } // Gets the outcome of the test part. Type type() const { return type_; } // Gets the name of the source file where the test part took place, or // NULL if it's unknown. const char* file_name() const { return file_name_.c_str(); } // Gets the line in the source file where the test part took place, // or -1 if it's unknown. int line_number() const { return line_number_; } // Gets the summary of the failure message. const char* summary() const { return summary_.c_str(); } // Gets the message associated with the test part. const char* message() const { return message_.c_str(); } // Returns true iff the test part passed. bool passed() const { return type_ == kSuccess; } // Returns true iff the test part failed. bool failed() const { return type_ != kSuccess; } // Returns true iff the test part non-fatally failed. bool nonfatally_failed() const { return type_ == kNonFatalFailure; } // Returns true iff the test part fatally failed. bool fatally_failed() const { return type_ == kFatalFailure; } private: Type type_; // Gets the summary of the failure message by omitting the stack // trace in it. static internal::String ExtractSummary(const char* message); // The name of the source file where the test part took place, or // NULL if the source file is unknown. internal::String file_name_; // The line in the source file where the test part took place, or -1 // if the line number is unknown. int line_number_; internal::String summary_; // The test failure summary. internal::String message_; // The test failure message. }; // Prints a TestPartResult object. std::ostream& operator<<(std::ostream& os, const TestPartResult& result); // An array of TestPartResult objects. // // Don't inherit from TestPartResultArray as its destructor is not // virtual. class GTEST_API_ TestPartResultArray { public: TestPartResultArray() {} // Appends the given TestPartResult to the array. void Append(const TestPartResult& result); // Returns the TestPartResult at the given index (0-based). const TestPartResult& GetTestPartResult(int index) const; // Returns the number of TestPartResult objects in the array. int size() const; private: std::vector array_; GTEST_DISALLOW_COPY_AND_ASSIGN_(TestPartResultArray); }; // This interface knows how to report a test part result. class TestPartResultReporterInterface { public: virtual ~TestPartResultReporterInterface() {} virtual void ReportTestPartResult(const TestPartResult& result) = 0; }; namespace internal { // This helper class is used by {ASSERT|EXPECT}_NO_FATAL_FAILURE to check if a // statement generates new fatal failures. To do so it registers itself as the // current test part result reporter. Besides checking if fatal failures were // reported, it only delegates the reporting to the former result reporter. // The original result reporter is restored in the destructor. // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. class GTEST_API_ HasNewFatalFailureHelper : public TestPartResultReporterInterface { public: HasNewFatalFailureHelper(); virtual ~HasNewFatalFailureHelper(); virtual void ReportTestPartResult(const TestPartResult& result); bool has_new_fatal_failure() const { return has_new_fatal_failure_; } private: bool has_new_fatal_failure_; TestPartResultReporterInterface* original_reporter_; GTEST_DISALLOW_COPY_AND_ASSIGN_(HasNewFatalFailureHelper); }; } // namespace internal } // namespace testing #endif // GTEST_INCLUDE_GTEST_GTEST_TEST_PART_H_ ugene-1.9.8/src/libs_3rdparty/gtest/src/gtest/gtest_pred_impl.h0000644000175000017500000003544411651544307023277 0ustar ilyailya// Copyright 2006, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // This file is AUTOMATICALLY GENERATED on 09/24/2010 by command // 'gen_gtest_pred_impl.py 5'. DO NOT EDIT BY HAND! // // Implements a family of generic predicate assertion macros. #ifndef GTEST_INCLUDE_GTEST_GTEST_PRED_IMPL_H_ #define GTEST_INCLUDE_GTEST_GTEST_PRED_IMPL_H_ // Makes sure this header is not included before gtest.h. #ifndef GTEST_INCLUDE_GTEST_GTEST_H_ # error Do not include gtest_pred_impl.h directly. Include gtest.h instead. #endif // GTEST_INCLUDE_GTEST_GTEST_H_ // This header implements a family of generic predicate assertion // macros: // // ASSERT_PRED_FORMAT1(pred_format, v1) // ASSERT_PRED_FORMAT2(pred_format, v1, v2) // ... // // where pred_format is a function or functor that takes n (in the // case of ASSERT_PRED_FORMATn) values and their source expression // text, and returns a testing::AssertionResult. See the definition // of ASSERT_EQ in gtest.h for an example. // // If you don't care about formatting, you can use the more // restrictive version: // // ASSERT_PRED1(pred, v1) // ASSERT_PRED2(pred, v1, v2) // ... // // where pred is an n-ary function or functor that returns bool, // and the values v1, v2, ..., must support the << operator for // streaming to std::ostream. // // We also define the EXPECT_* variations. // // For now we only support predicates whose arity is at most 5. // Please email googletestframework@googlegroups.com if you need // support for higher arities. // GTEST_ASSERT_ is the basic statement to which all of the assertions // in this file reduce. Don't use this in your code. #define GTEST_ASSERT_(expression, on_failure) \ GTEST_AMBIGUOUS_ELSE_BLOCKER_ \ if (const ::testing::AssertionResult gtest_ar = (expression)) \ ; \ else \ on_failure(gtest_ar.failure_message()) // Helper function for implementing {EXPECT|ASSERT}_PRED1. Don't use // this in your code. template AssertionResult AssertPred1Helper(const char* pred_text, const char* e1, Pred pred, const T1& v1) { if (pred(v1)) return AssertionSuccess(); return AssertionFailure() << pred_text << "(" << e1 << ") evaluates to false, where" << "\n" << e1 << " evaluates to " << v1; } // Internal macro for implementing {EXPECT|ASSERT}_PRED_FORMAT1. // Don't use this in your code. #define GTEST_PRED_FORMAT1_(pred_format, v1, on_failure)\ GTEST_ASSERT_(pred_format(#v1, v1),\ on_failure) // Internal macro for implementing {EXPECT|ASSERT}_PRED1. Don't use // this in your code. #define GTEST_PRED1_(pred, v1, on_failure)\ GTEST_ASSERT_(::testing::AssertPred1Helper(#pred, \ #v1, \ pred, \ v1), on_failure) // Unary predicate assertion macros. #define EXPECT_PRED_FORMAT1(pred_format, v1) \ GTEST_PRED_FORMAT1_(pred_format, v1, GTEST_NONFATAL_FAILURE_) #define EXPECT_PRED1(pred, v1) \ GTEST_PRED1_(pred, v1, GTEST_NONFATAL_FAILURE_) #define ASSERT_PRED_FORMAT1(pred_format, v1) \ GTEST_PRED_FORMAT1_(pred_format, v1, GTEST_FATAL_FAILURE_) #define ASSERT_PRED1(pred, v1) \ GTEST_PRED1_(pred, v1, GTEST_FATAL_FAILURE_) // Helper function for implementing {EXPECT|ASSERT}_PRED2. Don't use // this in your code. template AssertionResult AssertPred2Helper(const char* pred_text, const char* e1, const char* e2, Pred pred, const T1& v1, const T2& v2) { if (pred(v1, v2)) return AssertionSuccess(); return AssertionFailure() << pred_text << "(" << e1 << ", " << e2 << ") evaluates to false, where" << "\n" << e1 << " evaluates to " << v1 << "\n" << e2 << " evaluates to " << v2; } // Internal macro for implementing {EXPECT|ASSERT}_PRED_FORMAT2. // Don't use this in your code. #define GTEST_PRED_FORMAT2_(pred_format, v1, v2, on_failure)\ GTEST_ASSERT_(pred_format(#v1, #v2, v1, v2),\ on_failure) // Internal macro for implementing {EXPECT|ASSERT}_PRED2. Don't use // this in your code. #define GTEST_PRED2_(pred, v1, v2, on_failure)\ GTEST_ASSERT_(::testing::AssertPred2Helper(#pred, \ #v1, \ #v2, \ pred, \ v1, \ v2), on_failure) // Binary predicate assertion macros. #define EXPECT_PRED_FORMAT2(pred_format, v1, v2) \ GTEST_PRED_FORMAT2_(pred_format, v1, v2, GTEST_NONFATAL_FAILURE_) #define EXPECT_PRED2(pred, v1, v2) \ GTEST_PRED2_(pred, v1, v2, GTEST_NONFATAL_FAILURE_) #define ASSERT_PRED_FORMAT2(pred_format, v1, v2) \ GTEST_PRED_FORMAT2_(pred_format, v1, v2, GTEST_FATAL_FAILURE_) #define ASSERT_PRED2(pred, v1, v2) \ GTEST_PRED2_(pred, v1, v2, GTEST_FATAL_FAILURE_) // Helper function for implementing {EXPECT|ASSERT}_PRED3. Don't use // this in your code. template AssertionResult AssertPred3Helper(const char* pred_text, const char* e1, const char* e2, const char* e3, Pred pred, const T1& v1, const T2& v2, const T3& v3) { if (pred(v1, v2, v3)) return AssertionSuccess(); return AssertionFailure() << pred_text << "(" << e1 << ", " << e2 << ", " << e3 << ") evaluates to false, where" << "\n" << e1 << " evaluates to " << v1 << "\n" << e2 << " evaluates to " << v2 << "\n" << e3 << " evaluates to " << v3; } // Internal macro for implementing {EXPECT|ASSERT}_PRED_FORMAT3. // Don't use this in your code. #define GTEST_PRED_FORMAT3_(pred_format, v1, v2, v3, on_failure)\ GTEST_ASSERT_(pred_format(#v1, #v2, #v3, v1, v2, v3),\ on_failure) // Internal macro for implementing {EXPECT|ASSERT}_PRED3. Don't use // this in your code. #define GTEST_PRED3_(pred, v1, v2, v3, on_failure)\ GTEST_ASSERT_(::testing::AssertPred3Helper(#pred, \ #v1, \ #v2, \ #v3, \ pred, \ v1, \ v2, \ v3), on_failure) // Ternary predicate assertion macros. #define EXPECT_PRED_FORMAT3(pred_format, v1, v2, v3) \ GTEST_PRED_FORMAT3_(pred_format, v1, v2, v3, GTEST_NONFATAL_FAILURE_) #define EXPECT_PRED3(pred, v1, v2, v3) \ GTEST_PRED3_(pred, v1, v2, v3, GTEST_NONFATAL_FAILURE_) #define ASSERT_PRED_FORMAT3(pred_format, v1, v2, v3) \ GTEST_PRED_FORMAT3_(pred_format, v1, v2, v3, GTEST_FATAL_FAILURE_) #define ASSERT_PRED3(pred, v1, v2, v3) \ GTEST_PRED3_(pred, v1, v2, v3, GTEST_FATAL_FAILURE_) // Helper function for implementing {EXPECT|ASSERT}_PRED4. Don't use // this in your code. template AssertionResult AssertPred4Helper(const char* pred_text, const char* e1, const char* e2, const char* e3, const char* e4, Pred pred, const T1& v1, const T2& v2, const T3& v3, const T4& v4) { if (pred(v1, v2, v3, v4)) return AssertionSuccess(); return AssertionFailure() << pred_text << "(" << e1 << ", " << e2 << ", " << e3 << ", " << e4 << ") evaluates to false, where" << "\n" << e1 << " evaluates to " << v1 << "\n" << e2 << " evaluates to " << v2 << "\n" << e3 << " evaluates to " << v3 << "\n" << e4 << " evaluates to " << v4; } // Internal macro for implementing {EXPECT|ASSERT}_PRED_FORMAT4. // Don't use this in your code. #define GTEST_PRED_FORMAT4_(pred_format, v1, v2, v3, v4, on_failure)\ GTEST_ASSERT_(pred_format(#v1, #v2, #v3, #v4, v1, v2, v3, v4),\ on_failure) // Internal macro for implementing {EXPECT|ASSERT}_PRED4. Don't use // this in your code. #define GTEST_PRED4_(pred, v1, v2, v3, v4, on_failure)\ GTEST_ASSERT_(::testing::AssertPred4Helper(#pred, \ #v1, \ #v2, \ #v3, \ #v4, \ pred, \ v1, \ v2, \ v3, \ v4), on_failure) // 4-ary predicate assertion macros. #define EXPECT_PRED_FORMAT4(pred_format, v1, v2, v3, v4) \ GTEST_PRED_FORMAT4_(pred_format, v1, v2, v3, v4, GTEST_NONFATAL_FAILURE_) #define EXPECT_PRED4(pred, v1, v2, v3, v4) \ GTEST_PRED4_(pred, v1, v2, v3, v4, GTEST_NONFATAL_FAILURE_) #define ASSERT_PRED_FORMAT4(pred_format, v1, v2, v3, v4) \ GTEST_PRED_FORMAT4_(pred_format, v1, v2, v3, v4, GTEST_FATAL_FAILURE_) #define ASSERT_PRED4(pred, v1, v2, v3, v4) \ GTEST_PRED4_(pred, v1, v2, v3, v4, GTEST_FATAL_FAILURE_) // Helper function for implementing {EXPECT|ASSERT}_PRED5. Don't use // this in your code. template AssertionResult AssertPred5Helper(const char* pred_text, const char* e1, const char* e2, const char* e3, const char* e4, const char* e5, Pred pred, const T1& v1, const T2& v2, const T3& v3, const T4& v4, const T5& v5) { if (pred(v1, v2, v3, v4, v5)) return AssertionSuccess(); return AssertionFailure() << pred_text << "(" << e1 << ", " << e2 << ", " << e3 << ", " << e4 << ", " << e5 << ") evaluates to false, where" << "\n" << e1 << " evaluates to " << v1 << "\n" << e2 << " evaluates to " << v2 << "\n" << e3 << " evaluates to " << v3 << "\n" << e4 << " evaluates to " << v4 << "\n" << e5 << " evaluates to " << v5; } // Internal macro for implementing {EXPECT|ASSERT}_PRED_FORMAT5. // Don't use this in your code. #define GTEST_PRED_FORMAT5_(pred_format, v1, v2, v3, v4, v5, on_failure)\ GTEST_ASSERT_(pred_format(#v1, #v2, #v3, #v4, #v5, v1, v2, v3, v4, v5),\ on_failure) // Internal macro for implementing {EXPECT|ASSERT}_PRED5. Don't use // this in your code. #define GTEST_PRED5_(pred, v1, v2, v3, v4, v5, on_failure)\ GTEST_ASSERT_(::testing::AssertPred5Helper(#pred, \ #v1, \ #v2, \ #v3, \ #v4, \ #v5, \ pred, \ v1, \ v2, \ v3, \ v4, \ v5), on_failure) // 5-ary predicate assertion macros. #define EXPECT_PRED_FORMAT5(pred_format, v1, v2, v3, v4, v5) \ GTEST_PRED_FORMAT5_(pred_format, v1, v2, v3, v4, v5, GTEST_NONFATAL_FAILURE_) #define EXPECT_PRED5(pred, v1, v2, v3, v4, v5) \ GTEST_PRED5_(pred, v1, v2, v3, v4, v5, GTEST_NONFATAL_FAILURE_) #define ASSERT_PRED_FORMAT5(pred_format, v1, v2, v3, v4, v5) \ GTEST_PRED_FORMAT5_(pred_format, v1, v2, v3, v4, v5, GTEST_FATAL_FAILURE_) #define ASSERT_PRED5(pred, v1, v2, v3, v4, v5) \ GTEST_PRED5_(pred, v1, v2, v3, v4, v5, GTEST_FATAL_FAILURE_) #endif // GTEST_INCLUDE_GTEST_GTEST_PRED_IMPL_H_ ugene-1.9.8/src/libs_3rdparty/gtest/src/gtest/gtest-param-test.h0000644000175000017500000022413111651544307023310 0ustar ilyailya// This file was GENERATED by command: // pump.py gtest-param-test.h.pump // DO NOT EDIT BY HAND!!! // Copyright 2008, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Authors: vladl@google.com (Vlad Losev) // // Macros and functions for implementing parameterized tests // in Google C++ Testing Framework (Google Test) // // This file is generated by a SCRIPT. DO NOT EDIT BY HAND! // #ifndef GTEST_INCLUDE_GTEST_GTEST_PARAM_TEST_H_ #define GTEST_INCLUDE_GTEST_GTEST_PARAM_TEST_H_ // Value-parameterized tests allow you to test your code with different // parameters without writing multiple copies of the same test. // // Here is how you use value-parameterized tests: #if 0 // To write value-parameterized tests, first you should define a fixture // class. It is usually derived from testing::TestWithParam (see below for // another inheritance scheme that's sometimes useful in more complicated // class hierarchies), where the type of your parameter values. // TestWithParam is itself derived from testing::Test. T can be any // copyable type. If it's a raw pointer, you are responsible for managing the // lifespan of the pointed values. class FooTest : public ::testing::TestWithParam { // You can implement all the usual class fixture members here. }; // Then, use the TEST_P macro to define as many parameterized tests // for this fixture as you want. The _P suffix is for "parameterized" // or "pattern", whichever you prefer to think. TEST_P(FooTest, DoesBlah) { // Inside a test, access the test parameter with the GetParam() method // of the TestWithParam class: EXPECT_TRUE(foo.Blah(GetParam())); ... } TEST_P(FooTest, HasBlahBlah) { ... } // Finally, you can use INSTANTIATE_TEST_CASE_P to instantiate the test // case with any set of parameters you want. Google Test defines a number // of functions for generating test parameters. They return what we call // (surprise!) parameter generators. Here is a summary of them, which // are all in the testing namespace: // // // Range(begin, end [, step]) - Yields values {begin, begin+step, // begin+step+step, ...}. The values do not // include end. step defaults to 1. // Values(v1, v2, ..., vN) - Yields values {v1, v2, ..., vN}. // ValuesIn(container) - Yields values from a C-style array, an STL // ValuesIn(begin,end) container, or an iterator range [begin, end). // Bool() - Yields sequence {false, true}. // Combine(g1, g2, ..., gN) - Yields all combinations (the Cartesian product // for the math savvy) of the values generated // by the N generators. // // For more details, see comments at the definitions of these functions below // in this file. // // The following statement will instantiate tests from the FooTest test case // each with parameter values "meeny", "miny", and "moe". INSTANTIATE_TEST_CASE_P(InstantiationName, FooTest, Values("meeny", "miny", "moe")); // To distinguish different instances of the pattern, (yes, you // can instantiate it more then once) the first argument to the // INSTANTIATE_TEST_CASE_P macro is a prefix that will be added to the // actual test case name. Remember to pick unique prefixes for different // instantiations. The tests from the instantiation above will have // these names: // // * InstantiationName/FooTest.DoesBlah/0 for "meeny" // * InstantiationName/FooTest.DoesBlah/1 for "miny" // * InstantiationName/FooTest.DoesBlah/2 for "moe" // * InstantiationName/FooTest.HasBlahBlah/0 for "meeny" // * InstantiationName/FooTest.HasBlahBlah/1 for "miny" // * InstantiationName/FooTest.HasBlahBlah/2 for "moe" // // You can use these names in --gtest_filter. // // This statement will instantiate all tests from FooTest again, each // with parameter values "cat" and "dog": const char* pets[] = {"cat", "dog"}; INSTANTIATE_TEST_CASE_P(AnotherInstantiationName, FooTest, ValuesIn(pets)); // The tests from the instantiation above will have these names: // // * AnotherInstantiationName/FooTest.DoesBlah/0 for "cat" // * AnotherInstantiationName/FooTest.DoesBlah/1 for "dog" // * AnotherInstantiationName/FooTest.HasBlahBlah/0 for "cat" // * AnotherInstantiationName/FooTest.HasBlahBlah/1 for "dog" // // Please note that INSTANTIATE_TEST_CASE_P will instantiate all tests // in the given test case, whether their definitions come before or // AFTER the INSTANTIATE_TEST_CASE_P statement. // // Please also note that generator expressions (including parameters to the // generators) are evaluated in InitGoogleTest(), after main() has started. // This allows the user on one hand, to adjust generator parameters in order // to dynamically determine a set of tests to run and on the other hand, // give the user a chance to inspect the generated tests with Google Test // reflection API before RUN_ALL_TESTS() is executed. // // You can see samples/sample7_unittest.cc and samples/sample8_unittest.cc // for more examples. // // In the future, we plan to publish the API for defining new parameter // generators. But for now this interface remains part of the internal // implementation and is subject to change. // // // A parameterized test fixture must be derived from testing::Test and from // testing::WithParamInterface, where T is the type of the parameter // values. Inheriting from TestWithParam satisfies that requirement because // TestWithParam inherits from both Test and WithParamInterface. In more // complicated hierarchies, however, it is occasionally useful to inherit // separately from Test and WithParamInterface. For example: class BaseTest : public ::testing::Test { // You can inherit all the usual members for a non-parameterized test // fixture here. }; class DerivedTest : public BaseTest, public ::testing::WithParamInterface { // The usual test fixture members go here too. }; TEST_F(BaseTest, HasFoo) { // This is an ordinary non-parameterized test. } TEST_P(DerivedTest, DoesBlah) { // GetParam works just the same here as if you inherit from TestWithParam. EXPECT_TRUE(foo.Blah(GetParam())); } #endif // 0 #include "gtest/internal/gtest-port.h" #if !GTEST_OS_SYMBIAN # include #endif // scripts/fuse_gtest.py depends on gtest's own header being #included // *unconditionally*. Therefore these #includes cannot be moved // inside #if GTEST_HAS_PARAM_TEST. #include "gtest/internal/gtest-internal.h" #include "gtest/internal/gtest-param-util.h" #include "gtest/internal/gtest-param-util-generated.h" #if GTEST_HAS_PARAM_TEST namespace testing { // Functions producing parameter generators. // // Google Test uses these generators to produce parameters for value- // parameterized tests. When a parameterized test case is instantiated // with a particular generator, Google Test creates and runs tests // for each element in the sequence produced by the generator. // // In the following sample, tests from test case FooTest are instantiated // each three times with parameter values 3, 5, and 8: // // class FooTest : public TestWithParam { ... }; // // TEST_P(FooTest, TestThis) { // } // TEST_P(FooTest, TestThat) { // } // INSTANTIATE_TEST_CASE_P(TestSequence, FooTest, Values(3, 5, 8)); // // Range() returns generators providing sequences of values in a range. // // Synopsis: // Range(start, end) // - returns a generator producing a sequence of values {start, start+1, // start+2, ..., }. // Range(start, end, step) // - returns a generator producing a sequence of values {start, start+step, // start+step+step, ..., }. // Notes: // * The generated sequences never include end. For example, Range(1, 5) // returns a generator producing a sequence {1, 2, 3, 4}. Range(1, 9, 2) // returns a generator producing {1, 3, 5, 7}. // * start and end must have the same type. That type may be any integral or // floating-point type or a user defined type satisfying these conditions: // * It must be assignable (have operator=() defined). // * It must have operator+() (operator+(int-compatible type) for // two-operand version). // * It must have operator<() defined. // Elements in the resulting sequences will also have that type. // * Condition start < end must be satisfied in order for resulting sequences // to contain any elements. // template internal::ParamGenerator Range(T start, T end, IncrementT step) { return internal::ParamGenerator( new internal::RangeGenerator(start, end, step)); } template internal::ParamGenerator Range(T start, T end) { return Range(start, end, 1); } // ValuesIn() function allows generation of tests with parameters coming from // a container. // // Synopsis: // ValuesIn(const T (&array)[N]) // - returns a generator producing sequences with elements from // a C-style array. // ValuesIn(const Container& container) // - returns a generator producing sequences with elements from // an STL-style container. // ValuesIn(Iterator begin, Iterator end) // - returns a generator producing sequences with elements from // a range [begin, end) defined by a pair of STL-style iterators. These // iterators can also be plain C pointers. // // Please note that ValuesIn copies the values from the containers // passed in and keeps them to generate tests in RUN_ALL_TESTS(). // // Examples: // // This instantiates tests from test case StringTest // each with C-string values of "foo", "bar", and "baz": // // const char* strings[] = {"foo", "bar", "baz"}; // INSTANTIATE_TEST_CASE_P(StringSequence, SrtingTest, ValuesIn(strings)); // // This instantiates tests from test case StlStringTest // each with STL strings with values "a" and "b": // // ::std::vector< ::std::string> GetParameterStrings() { // ::std::vector< ::std::string> v; // v.push_back("a"); // v.push_back("b"); // return v; // } // // INSTANTIATE_TEST_CASE_P(CharSequence, // StlStringTest, // ValuesIn(GetParameterStrings())); // // // This will also instantiate tests from CharTest // each with parameter values 'a' and 'b': // // ::std::list GetParameterChars() { // ::std::list list; // list.push_back('a'); // list.push_back('b'); // return list; // } // ::std::list l = GetParameterChars(); // INSTANTIATE_TEST_CASE_P(CharSequence2, // CharTest, // ValuesIn(l.begin(), l.end())); // template internal::ParamGenerator< typename ::testing::internal::IteratorTraits::value_type> ValuesIn(ForwardIterator begin, ForwardIterator end) { typedef typename ::testing::internal::IteratorTraits ::value_type ParamType; return internal::ParamGenerator( new internal::ValuesInIteratorRangeGenerator(begin, end)); } template internal::ParamGenerator ValuesIn(const T (&array)[N]) { return ValuesIn(array, array + N); } template internal::ParamGenerator ValuesIn( const Container& container) { return ValuesIn(container.begin(), container.end()); } // Values() allows generating tests from explicitly specified list of // parameters. // // Synopsis: // Values(T v1, T v2, ..., T vN) // - returns a generator producing sequences with elements v1, v2, ..., vN. // // For example, this instantiates tests from test case BarTest each // with values "one", "two", and "three": // // INSTANTIATE_TEST_CASE_P(NumSequence, BarTest, Values("one", "two", "three")); // // This instantiates tests from test case BazTest each with values 1, 2, 3.5. // The exact type of values will depend on the type of parameter in BazTest. // // INSTANTIATE_TEST_CASE_P(FloatingNumbers, BazTest, Values(1, 2, 3.5)); // // Currently, Values() supports from 1 to 50 parameters. // template internal::ValueArray1 Values(T1 v1) { return internal::ValueArray1(v1); } template internal::ValueArray2 Values(T1 v1, T2 v2) { return internal::ValueArray2(v1, v2); } template internal::ValueArray3 Values(T1 v1, T2 v2, T3 v3) { return internal::ValueArray3(v1, v2, v3); } template internal::ValueArray4 Values(T1 v1, T2 v2, T3 v3, T4 v4) { return internal::ValueArray4(v1, v2, v3, v4); } template internal::ValueArray5 Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5) { return internal::ValueArray5(v1, v2, v3, v4, v5); } template internal::ValueArray6 Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6) { return internal::ValueArray6(v1, v2, v3, v4, v5, v6); } template internal::ValueArray7 Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7) { return internal::ValueArray7(v1, v2, v3, v4, v5, v6, v7); } template internal::ValueArray8 Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8) { return internal::ValueArray8(v1, v2, v3, v4, v5, v6, v7, v8); } template internal::ValueArray9 Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9) { return internal::ValueArray9(v1, v2, v3, v4, v5, v6, v7, v8, v9); } template internal::ValueArray10 Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10) { return internal::ValueArray10(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10); } template internal::ValueArray11 Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11) { return internal::ValueArray11(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11); } template internal::ValueArray12 Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12) { return internal::ValueArray12(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12); } template internal::ValueArray13 Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13) { return internal::ValueArray13(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13); } template internal::ValueArray14 Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14) { return internal::ValueArray14(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14); } template internal::ValueArray15 Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15) { return internal::ValueArray15(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15); } template internal::ValueArray16 Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16) { return internal::ValueArray16(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16); } template internal::ValueArray17 Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17) { return internal::ValueArray17(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17); } template internal::ValueArray18 Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, T18 v18) { return internal::ValueArray18(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18); } template internal::ValueArray19 Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19) { return internal::ValueArray19(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19); } template internal::ValueArray20 Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20) { return internal::ValueArray20(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20); } template internal::ValueArray21 Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21) { return internal::ValueArray21(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21); } template internal::ValueArray22 Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22) { return internal::ValueArray22(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22); } template internal::ValueArray23 Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23) { return internal::ValueArray23(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23); } template internal::ValueArray24 Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24) { return internal::ValueArray24(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24); } template internal::ValueArray25 Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25) { return internal::ValueArray25(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25); } template internal::ValueArray26 Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, T26 v26) { return internal::ValueArray26(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26); } template internal::ValueArray27 Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, T26 v26, T27 v27) { return internal::ValueArray27(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27); } template internal::ValueArray28 Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, T26 v26, T27 v27, T28 v28) { return internal::ValueArray28(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28); } template internal::ValueArray29 Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, T26 v26, T27 v27, T28 v28, T29 v29) { return internal::ValueArray29(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29); } template internal::ValueArray30 Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, T26 v26, T27 v27, T28 v28, T29 v29, T30 v30) { return internal::ValueArray30(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30); } template internal::ValueArray31 Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31) { return internal::ValueArray31(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31); } template internal::ValueArray32 Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32) { return internal::ValueArray32(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32); } template internal::ValueArray33 Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33) { return internal::ValueArray33(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33); } template internal::ValueArray34 Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, T34 v34) { return internal::ValueArray34(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34); } template internal::ValueArray35 Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, T34 v34, T35 v35) { return internal::ValueArray35(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35); } template internal::ValueArray36 Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, T34 v34, T35 v35, T36 v36) { return internal::ValueArray36(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36); } template internal::ValueArray37 Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, T34 v34, T35 v35, T36 v36, T37 v37) { return internal::ValueArray37(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37); } template internal::ValueArray38 Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, T34 v34, T35 v35, T36 v36, T37 v37, T38 v38) { return internal::ValueArray38(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38); } template internal::ValueArray39 Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, T34 v34, T35 v35, T36 v36, T37 v37, T38 v38, T39 v39) { return internal::ValueArray39(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39); } template internal::ValueArray40 Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, T34 v34, T35 v35, T36 v36, T37 v37, T38 v38, T39 v39, T40 v40) { return internal::ValueArray40(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40); } template internal::ValueArray41 Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, T34 v34, T35 v35, T36 v36, T37 v37, T38 v38, T39 v39, T40 v40, T41 v41) { return internal::ValueArray41(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41); } template internal::ValueArray42 Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, T34 v34, T35 v35, T36 v36, T37 v37, T38 v38, T39 v39, T40 v40, T41 v41, T42 v42) { return internal::ValueArray42(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42); } template internal::ValueArray43 Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, T34 v34, T35 v35, T36 v36, T37 v37, T38 v38, T39 v39, T40 v40, T41 v41, T42 v42, T43 v43) { return internal::ValueArray43(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43); } template internal::ValueArray44 Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, T34 v34, T35 v35, T36 v36, T37 v37, T38 v38, T39 v39, T40 v40, T41 v41, T42 v42, T43 v43, T44 v44) { return internal::ValueArray44(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44); } template internal::ValueArray45 Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, T34 v34, T35 v35, T36 v36, T37 v37, T38 v38, T39 v39, T40 v40, T41 v41, T42 v42, T43 v43, T44 v44, T45 v45) { return internal::ValueArray45(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45); } template internal::ValueArray46 Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, T34 v34, T35 v35, T36 v36, T37 v37, T38 v38, T39 v39, T40 v40, T41 v41, T42 v42, T43 v43, T44 v44, T45 v45, T46 v46) { return internal::ValueArray46(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46); } template internal::ValueArray47 Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, T34 v34, T35 v35, T36 v36, T37 v37, T38 v38, T39 v39, T40 v40, T41 v41, T42 v42, T43 v43, T44 v44, T45 v45, T46 v46, T47 v47) { return internal::ValueArray47(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47); } template internal::ValueArray48 Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, T34 v34, T35 v35, T36 v36, T37 v37, T38 v38, T39 v39, T40 v40, T41 v41, T42 v42, T43 v43, T44 v44, T45 v45, T46 v46, T47 v47, T48 v48) { return internal::ValueArray48(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48); } template internal::ValueArray49 Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, T34 v34, T35 v35, T36 v36, T37 v37, T38 v38, T39 v39, T40 v40, T41 v41, T42 v42, T43 v43, T44 v44, T45 v45, T46 v46, T47 v47, T48 v48, T49 v49) { return internal::ValueArray49(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49); } template internal::ValueArray50 Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, T34 v34, T35 v35, T36 v36, T37 v37, T38 v38, T39 v39, T40 v40, T41 v41, T42 v42, T43 v43, T44 v44, T45 v45, T46 v46, T47 v47, T48 v48, T49 v49, T50 v50) { return internal::ValueArray50(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50); } // Bool() allows generating tests with parameters in a set of (false, true). // // Synopsis: // Bool() // - returns a generator producing sequences with elements {false, true}. // // It is useful when testing code that depends on Boolean flags. Combinations // of multiple flags can be tested when several Bool()'s are combined using // Combine() function. // // In the following example all tests in the test case FlagDependentTest // will be instantiated twice with parameters false and true. // // class FlagDependentTest : public testing::TestWithParam { // virtual void SetUp() { // external_flag = GetParam(); // } // } // INSTANTIATE_TEST_CASE_P(BoolSequence, FlagDependentTest, Bool()); // inline internal::ParamGenerator Bool() { return Values(false, true); } # if GTEST_HAS_COMBINE // Combine() allows the user to combine two or more sequences to produce // values of a Cartesian product of those sequences' elements. // // Synopsis: // Combine(gen1, gen2, ..., genN) // - returns a generator producing sequences with elements coming from // the Cartesian product of elements from the sequences generated by // gen1, gen2, ..., genN. The sequence elements will have a type of // tuple where T1, T2, ..., TN are the types // of elements from sequences produces by gen1, gen2, ..., genN. // // Combine can have up to 10 arguments. This number is currently limited // by the maximum number of elements in the tuple implementation used by Google // Test. // // Example: // // This will instantiate tests in test case AnimalTest each one with // the parameter values tuple("cat", BLACK), tuple("cat", WHITE), // tuple("dog", BLACK), and tuple("dog", WHITE): // // enum Color { BLACK, GRAY, WHITE }; // class AnimalTest // : public testing::TestWithParam > {...}; // // TEST_P(AnimalTest, AnimalLooksNice) {...} // // INSTANTIATE_TEST_CASE_P(AnimalVariations, AnimalTest, // Combine(Values("cat", "dog"), // Values(BLACK, WHITE))); // // This will instantiate tests in FlagDependentTest with all variations of two // Boolean flags: // // class FlagDependentTest // : public testing::TestWithParam > { // virtual void SetUp() { // // Assigns external_flag_1 and external_flag_2 values from the tuple. // tie(external_flag_1, external_flag_2) = GetParam(); // } // }; // // TEST_P(FlagDependentTest, TestFeature1) { // // Test your code using external_flag_1 and external_flag_2 here. // } // INSTANTIATE_TEST_CASE_P(TwoBoolSequence, FlagDependentTest, // Combine(Bool(), Bool())); // template internal::CartesianProductHolder2 Combine( const Generator1& g1, const Generator2& g2) { return internal::CartesianProductHolder2( g1, g2); } template internal::CartesianProductHolder3 Combine( const Generator1& g1, const Generator2& g2, const Generator3& g3) { return internal::CartesianProductHolder3( g1, g2, g3); } template internal::CartesianProductHolder4 Combine( const Generator1& g1, const Generator2& g2, const Generator3& g3, const Generator4& g4) { return internal::CartesianProductHolder4( g1, g2, g3, g4); } template internal::CartesianProductHolder5 Combine( const Generator1& g1, const Generator2& g2, const Generator3& g3, const Generator4& g4, const Generator5& g5) { return internal::CartesianProductHolder5( g1, g2, g3, g4, g5); } template internal::CartesianProductHolder6 Combine( const Generator1& g1, const Generator2& g2, const Generator3& g3, const Generator4& g4, const Generator5& g5, const Generator6& g6) { return internal::CartesianProductHolder6( g1, g2, g3, g4, g5, g6); } template internal::CartesianProductHolder7 Combine( const Generator1& g1, const Generator2& g2, const Generator3& g3, const Generator4& g4, const Generator5& g5, const Generator6& g6, const Generator7& g7) { return internal::CartesianProductHolder7( g1, g2, g3, g4, g5, g6, g7); } template internal::CartesianProductHolder8 Combine( const Generator1& g1, const Generator2& g2, const Generator3& g3, const Generator4& g4, const Generator5& g5, const Generator6& g6, const Generator7& g7, const Generator8& g8) { return internal::CartesianProductHolder8( g1, g2, g3, g4, g5, g6, g7, g8); } template internal::CartesianProductHolder9 Combine( const Generator1& g1, const Generator2& g2, const Generator3& g3, const Generator4& g4, const Generator5& g5, const Generator6& g6, const Generator7& g7, const Generator8& g8, const Generator9& g9) { return internal::CartesianProductHolder9( g1, g2, g3, g4, g5, g6, g7, g8, g9); } template internal::CartesianProductHolder10 Combine( const Generator1& g1, const Generator2& g2, const Generator3& g3, const Generator4& g4, const Generator5& g5, const Generator6& g6, const Generator7& g7, const Generator8& g8, const Generator9& g9, const Generator10& g10) { return internal::CartesianProductHolder10( g1, g2, g3, g4, g5, g6, g7, g8, g9, g10); } # endif // GTEST_HAS_COMBINE # define TEST_P(test_case_name, test_name) \ class GTEST_TEST_CLASS_NAME_(test_case_name, test_name) \ : public test_case_name { \ public: \ GTEST_TEST_CLASS_NAME_(test_case_name, test_name)() {} \ virtual void TestBody(); \ private: \ static int AddToRegistry() { \ ::testing::UnitTest::GetInstance()->parameterized_test_registry(). \ GetTestCasePatternHolder(\ #test_case_name, __FILE__, __LINE__)->AddTestPattern(\ #test_case_name, \ #test_name, \ new ::testing::internal::TestMetaFactory< \ GTEST_TEST_CLASS_NAME_(test_case_name, test_name)>()); \ return 0; \ } \ static int gtest_registering_dummy_; \ GTEST_DISALLOW_COPY_AND_ASSIGN_(\ GTEST_TEST_CLASS_NAME_(test_case_name, test_name)); \ }; \ int GTEST_TEST_CLASS_NAME_(test_case_name, \ test_name)::gtest_registering_dummy_ = \ GTEST_TEST_CLASS_NAME_(test_case_name, test_name)::AddToRegistry(); \ void GTEST_TEST_CLASS_NAME_(test_case_name, test_name)::TestBody() # define INSTANTIATE_TEST_CASE_P(prefix, test_case_name, generator) \ ::testing::internal::ParamGenerator \ gtest_##prefix##test_case_name##_EvalGenerator_() { return generator; } \ int gtest_##prefix##test_case_name##_dummy_ = \ ::testing::UnitTest::GetInstance()->parameterized_test_registry(). \ GetTestCasePatternHolder(\ #test_case_name, __FILE__, __LINE__)->AddTestCaseInstantiation(\ #prefix, \ >est_##prefix##test_case_name##_EvalGenerator_, \ __FILE__, __LINE__) } // namespace testing #endif // GTEST_HAS_PARAM_TEST #endif // GTEST_INCLUDE_GTEST_GTEST_PARAM_TEST_H_ ugene-1.9.8/src/libs_3rdparty/gtest/src/gtest/internal/0000755000175000017500000000000011651544307021547 5ustar ilyailyaugene-1.9.8/src/libs_3rdparty/gtest/src/gtest/internal/gtest-type-util.h.pump0000644000175000017500000002213711651544307025765 0ustar ilyailya$$ -*- mode: c++; -*- $var n = 50 $$ Maximum length of type lists we want to support. // Copyright 2008 Google Inc. // All Rights Reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Author: wan@google.com (Zhanyong Wan) // Type utilities needed for implementing typed and type-parameterized // tests. This file is generated by a SCRIPT. DO NOT EDIT BY HAND! // // Currently we support at most $n types in a list, and at most $n // type-parameterized tests in one type-parameterized test case. // Please contact googletestframework@googlegroups.com if you need // more. #ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_TYPE_UTIL_H_ #define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_TYPE_UTIL_H_ #include "gtest/internal/gtest-port.h" #include "gtest/internal/gtest-string.h" // #ifdef __GNUC__ is too general here. It is possible to use gcc without using // libstdc++ (which is where cxxabi.h comes from). # ifdef __GLIBCXX__ # include # elif defined(__HP_aCC) # include # endif // __GLIBCXX__ namespace testing { namespace internal { // GetTypeName() returns a human-readable name of type T. // NB: This function is also used in Google Mock, so don't move it inside of // the typed-test-only section below. template String GetTypeName() { # if GTEST_HAS_RTTI const char* const name = typeid(T).name(); # if defined(__GLIBCXX__) || defined(__HP_aCC) int status = 0; // gcc's implementation of typeid(T).name() mangles the type name, // so we have to demangle it. # ifdef __GLIBCXX__ using abi::__cxa_demangle; # endif // __GLIBCXX__ char* const readable_name = __cxa_demangle(name, 0, 0, &status); const String name_str(status == 0 ? readable_name : name); free(readable_name); return name_str; # else return name; # endif // __GLIBCXX__ || __HP_aCC # else return ""; # endif // GTEST_HAS_RTTI } #if GTEST_HAS_TYPED_TEST || GTEST_HAS_TYPED_TEST_P // AssertyTypeEq::type is defined iff T1 and T2 are the same // type. This can be used as a compile-time assertion to ensure that // two types are equal. template struct AssertTypeEq; template struct AssertTypeEq { typedef bool type; }; // A unique type used as the default value for the arguments of class // template Types. This allows us to simulate variadic templates // (e.g. Types, Type, and etc), which C++ doesn't // support directly. struct None {}; // The following family of struct and struct templates are used to // represent type lists. In particular, TypesN // represents a type list with N types (T1, T2, ..., and TN) in it. // Except for Types0, every struct in the family has two member types: // Head for the first type in the list, and Tail for the rest of the // list. // The empty type list. struct Types0 {}; // Type lists of length 1, 2, 3, and so on. template struct Types1 { typedef T1 Head; typedef Types0 Tail; }; $range i 2..n $for i [[ $range j 1..i $range k 2..i template <$for j, [[typename T$j]]> struct Types$i { typedef T1 Head; typedef Types$(i-1)<$for k, [[T$k]]> Tail; }; ]] } // namespace internal // We don't want to require the users to write TypesN<...> directly, // as that would require them to count the length. Types<...> is much // easier to write, but generates horrible messages when there is a // compiler error, as gcc insists on printing out each template // argument, even if it has the default value (this means Types // will appear as Types in the compiler // errors). // // Our solution is to combine the best part of the two approaches: a // user would write Types, and Google Test will translate // that to TypesN internally to make error messages // readable. The translation is done by the 'type' member of the // Types template. $range i 1..n template <$for i, [[typename T$i = internal::None]]> struct Types { typedef internal::Types$n<$for i, [[T$i]]> type; }; template <> struct Types<$for i, [[internal::None]]> { typedef internal::Types0 type; }; $range i 1..n-1 $for i [[ $range j 1..i $range k i+1..n template <$for j, [[typename T$j]]> struct Types<$for j, [[T$j]]$for k[[, internal::None]]> { typedef internal::Types$i<$for j, [[T$j]]> type; }; ]] namespace internal { # define GTEST_TEMPLATE_ template class // The template "selector" struct TemplateSel is used to // represent Tmpl, which must be a class template with one type // parameter, as a type. TemplateSel::Bind::type is defined // as the type Tmpl. This allows us to actually instantiate the // template "selected" by TemplateSel. // // This trick is necessary for simulating typedef for class templates, // which C++ doesn't support directly. template struct TemplateSel { template struct Bind { typedef Tmpl type; }; }; # define GTEST_BIND_(TmplSel, T) \ TmplSel::template Bind::type // A unique struct template used as the default value for the // arguments of class template Templates. This allows us to simulate // variadic templates (e.g. Templates, Templates, // and etc), which C++ doesn't support directly. template struct NoneT {}; // The following family of struct and struct templates are used to // represent template lists. In particular, TemplatesN represents a list of N templates (T1, T2, ..., and TN). Except // for Templates0, every struct in the family has two member types: // Head for the selector of the first template in the list, and Tail // for the rest of the list. // The empty template list. struct Templates0 {}; // Template lists of length 1, 2, 3, and so on. template struct Templates1 { typedef TemplateSel Head; typedef Templates0 Tail; }; $range i 2..n $for i [[ $range j 1..i $range k 2..i template <$for j, [[GTEST_TEMPLATE_ T$j]]> struct Templates$i { typedef TemplateSel Head; typedef Templates$(i-1)<$for k, [[T$k]]> Tail; }; ]] // We don't want to require the users to write TemplatesN<...> directly, // as that would require them to count the length. Templates<...> is much // easier to write, but generates horrible messages when there is a // compiler error, as gcc insists on printing out each template // argument, even if it has the default value (this means Templates // will appear as Templates in the compiler // errors). // // Our solution is to combine the best part of the two approaches: a // user would write Templates, and Google Test will translate // that to TemplatesN internally to make error messages // readable. The translation is done by the 'type' member of the // Templates template. $range i 1..n template <$for i, [[GTEST_TEMPLATE_ T$i = NoneT]]> struct Templates { typedef Templates$n<$for i, [[T$i]]> type; }; template <> struct Templates<$for i, [[NoneT]]> { typedef Templates0 type; }; $range i 1..n-1 $for i [[ $range j 1..i $range k i+1..n template <$for j, [[GTEST_TEMPLATE_ T$j]]> struct Templates<$for j, [[T$j]]$for k[[, NoneT]]> { typedef Templates$i<$for j, [[T$j]]> type; }; ]] // The TypeList template makes it possible to use either a single type // or a Types<...> list in TYPED_TEST_CASE() and // INSTANTIATE_TYPED_TEST_CASE_P(). template struct TypeList { typedef Types1 type; }; $range i 1..n template <$for i, [[typename T$i]]> struct TypeList > { typedef typename Types<$for i, [[T$i]]>::type type; }; #endif // GTEST_HAS_TYPED_TEST || GTEST_HAS_TYPED_TEST_P } // namespace internal } // namespace testing #endif // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_TYPE_UTIL_H_ ugene-1.9.8/src/libs_3rdparty/gtest/src/gtest/internal/gtest-filepath.h0000644000175000017500000002274111651544307024646 0ustar ilyailya// Copyright 2008, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Author: keith.ray@gmail.com (Keith Ray) // // Google Test filepath utilities // // This header file declares classes and functions used internally by // Google Test. They are subject to change without notice. // // This file is #included in . // Do not include this header file separately! #ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_FILEPATH_H_ #define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_FILEPATH_H_ #include "gtest/internal/gtest-string.h" namespace testing { namespace internal { // FilePath - a class for file and directory pathname manipulation which // handles platform-specific conventions (like the pathname separator). // Used for helper functions for naming files in a directory for xml output. // Except for Set methods, all methods are const or static, which provides an // "immutable value object" -- useful for peace of mind. // A FilePath with a value ending in a path separator ("like/this/") represents // a directory, otherwise it is assumed to represent a file. In either case, // it may or may not represent an actual file or directory in the file system. // Names are NOT checked for syntax correctness -- no checking for illegal // characters, malformed paths, etc. class GTEST_API_ FilePath { public: FilePath() : pathname_("") { } FilePath(const FilePath& rhs) : pathname_(rhs.pathname_) { } explicit FilePath(const char* pathname) : pathname_(pathname) { Normalize(); } explicit FilePath(const String& pathname) : pathname_(pathname) { Normalize(); } FilePath& operator=(const FilePath& rhs) { Set(rhs); return *this; } void Set(const FilePath& rhs) { pathname_ = rhs.pathname_; } String ToString() const { return pathname_; } const char* c_str() const { return pathname_.c_str(); } // Returns the current working directory, or "" if unsuccessful. static FilePath GetCurrentDir(); // Given directory = "dir", base_name = "test", number = 0, // extension = "xml", returns "dir/test.xml". If number is greater // than zero (e.g., 12), returns "dir/test_12.xml". // On Windows platform, uses \ as the separator rather than /. static FilePath MakeFileName(const FilePath& directory, const FilePath& base_name, int number, const char* extension); // Given directory = "dir", relative_path = "test.xml", // returns "dir/test.xml". // On Windows, uses \ as the separator rather than /. static FilePath ConcatPaths(const FilePath& directory, const FilePath& relative_path); // Returns a pathname for a file that does not currently exist. The pathname // will be directory/base_name.extension or // directory/base_name_.extension if directory/base_name.extension // already exists. The number will be incremented until a pathname is found // that does not already exist. // Examples: 'dir/foo_test.xml' or 'dir/foo_test_1.xml'. // There could be a race condition if two or more processes are calling this // function at the same time -- they could both pick the same filename. static FilePath GenerateUniqueFileName(const FilePath& directory, const FilePath& base_name, const char* extension); // Returns true iff the path is NULL or "". bool IsEmpty() const { return c_str() == NULL || *c_str() == '\0'; } // If input name has a trailing separator character, removes it and returns // the name, otherwise return the name string unmodified. // On Windows platform, uses \ as the separator, other platforms use /. FilePath RemoveTrailingPathSeparator() const; // Returns a copy of the FilePath with the directory part removed. // Example: FilePath("path/to/file").RemoveDirectoryName() returns // FilePath("file"). If there is no directory part ("just_a_file"), it returns // the FilePath unmodified. If there is no file part ("just_a_dir/") it // returns an empty FilePath (""). // On Windows platform, '\' is the path separator, otherwise it is '/'. FilePath RemoveDirectoryName() const; // RemoveFileName returns the directory path with the filename removed. // Example: FilePath("path/to/file").RemoveFileName() returns "path/to/". // If the FilePath is "a_file" or "/a_file", RemoveFileName returns // FilePath("./") or, on Windows, FilePath(".\\"). If the filepath does // not have a file, like "just/a/dir/", it returns the FilePath unmodified. // On Windows platform, '\' is the path separator, otherwise it is '/'. FilePath RemoveFileName() const; // Returns a copy of the FilePath with the case-insensitive extension removed. // Example: FilePath("dir/file.exe").RemoveExtension("EXE") returns // FilePath("dir/file"). If a case-insensitive extension is not // found, returns a copy of the original FilePath. FilePath RemoveExtension(const char* extension) const; // Creates directories so that path exists. Returns true if successful or if // the directories already exist; returns false if unable to create // directories for any reason. Will also return false if the FilePath does // not represent a directory (that is, it doesn't end with a path separator). bool CreateDirectoriesRecursively() const; // Create the directory so that path exists. Returns true if successful or // if the directory already exists; returns false if unable to create the // directory for any reason, including if the parent directory does not // exist. Not named "CreateDirectory" because that's a macro on Windows. bool CreateFolder() const; // Returns true if FilePath describes something in the file-system, // either a file, directory, or whatever, and that something exists. bool FileOrDirectoryExists() const; // Returns true if pathname describes a directory in the file-system // that exists. bool DirectoryExists() const; // Returns true if FilePath ends with a path separator, which indicates that // it is intended to represent a directory. Returns false otherwise. // This does NOT check that a directory (or file) actually exists. bool IsDirectory() const; // Returns true if pathname describes a root directory. (Windows has one // root directory per disk drive.) bool IsRootDirectory() const; // Returns true if pathname describes an absolute path. bool IsAbsolutePath() const; private: // Replaces multiple consecutive separators with a single separator. // For example, "bar///foo" becomes "bar/foo". Does not eliminate other // redundancies that might be in a pathname involving "." or "..". // // A pathname with multiple consecutive separators may occur either through // user error or as a result of some scripts or APIs that generate a pathname // with a trailing separator. On other platforms the same API or script // may NOT generate a pathname with a trailing "/". Then elsewhere that // pathname may have another "/" and pathname components added to it, // without checking for the separator already being there. // The script language and operating system may allow paths like "foo//bar" // but some of the functions in FilePath will not handle that correctly. In // particular, RemoveTrailingPathSeparator() only removes one separator, and // it is called in CreateDirectoriesRecursively() assuming that it will change // a pathname from directory syntax (trailing separator) to filename syntax. // // On Windows this method also replaces the alternate path separator '/' with // the primary path separator '\\', so that for example "bar\\/\\foo" becomes // "bar\\foo". void Normalize(); // Returns a pointer to the last occurence of a valid path separator in // the FilePath. On Windows, for example, both '/' and '\' are valid path // separators. Returns NULL if no path separator was found. const char* FindLastPathSeparator() const; String pathname_; }; // class FilePath } // namespace internal } // namespace testing #endif // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_FILEPATH_H_ ugene-1.9.8/src/libs_3rdparty/gtest/src/gtest/internal/gtest-type-util.h0000644000175000017500000055247411651544307025021 0ustar ilyailya// This file was GENERATED by command: // pump.py gtest-type-util.h.pump // DO NOT EDIT BY HAND!!! // Copyright 2008 Google Inc. // All Rights Reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Author: wan@google.com (Zhanyong Wan) // Type utilities needed for implementing typed and type-parameterized // tests. This file is generated by a SCRIPT. DO NOT EDIT BY HAND! // // Currently we support at most 50 types in a list, and at most 50 // type-parameterized tests in one type-parameterized test case. // Please contact googletestframework@googlegroups.com if you need // more. #ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_TYPE_UTIL_H_ #define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_TYPE_UTIL_H_ #include "gtest/internal/gtest-port.h" #include "gtest/internal/gtest-string.h" // #ifdef __GNUC__ is too general here. It is possible to use gcc without using // libstdc++ (which is where cxxabi.h comes from). # ifdef __GLIBCXX__ # include # elif defined(__HP_aCC) # include # endif // __GLIBCXX__ namespace testing { namespace internal { // GetTypeName() returns a human-readable name of type T. // NB: This function is also used in Google Mock, so don't move it inside of // the typed-test-only section below. template String GetTypeName() { # if GTEST_HAS_RTTI const char* const name = typeid(T).name(); # if defined(__GLIBCXX__) || defined(__HP_aCC) int status = 0; // gcc's implementation of typeid(T).name() mangles the type name, // so we have to demangle it. # ifdef __GLIBCXX__ using abi::__cxa_demangle; # endif // __GLIBCXX__ char* const readable_name = __cxa_demangle(name, 0, 0, &status); const String name_str(status == 0 ? readable_name : name); free(readable_name); return name_str; # else return name; # endif // __GLIBCXX__ || __HP_aCC # else return ""; # endif // GTEST_HAS_RTTI } #if GTEST_HAS_TYPED_TEST || GTEST_HAS_TYPED_TEST_P // AssertyTypeEq::type is defined iff T1 and T2 are the same // type. This can be used as a compile-time assertion to ensure that // two types are equal. template struct AssertTypeEq; template struct AssertTypeEq { typedef bool type; }; // A unique type used as the default value for the arguments of class // template Types. This allows us to simulate variadic templates // (e.g. Types, Type, and etc), which C++ doesn't // support directly. struct None {}; // The following family of struct and struct templates are used to // represent type lists. In particular, TypesN // represents a type list with N types (T1, T2, ..., and TN) in it. // Except for Types0, every struct in the family has two member types: // Head for the first type in the list, and Tail for the rest of the // list. // The empty type list. struct Types0 {}; // Type lists of length 1, 2, 3, and so on. template struct Types1 { typedef T1 Head; typedef Types0 Tail; }; template struct Types2 { typedef T1 Head; typedef Types1 Tail; }; template struct Types3 { typedef T1 Head; typedef Types2 Tail; }; template struct Types4 { typedef T1 Head; typedef Types3 Tail; }; template struct Types5 { typedef T1 Head; typedef Types4 Tail; }; template struct Types6 { typedef T1 Head; typedef Types5 Tail; }; template struct Types7 { typedef T1 Head; typedef Types6 Tail; }; template struct Types8 { typedef T1 Head; typedef Types7 Tail; }; template struct Types9 { typedef T1 Head; typedef Types8 Tail; }; template struct Types10 { typedef T1 Head; typedef Types9 Tail; }; template struct Types11 { typedef T1 Head; typedef Types10 Tail; }; template struct Types12 { typedef T1 Head; typedef Types11 Tail; }; template struct Types13 { typedef T1 Head; typedef Types12 Tail; }; template struct Types14 { typedef T1 Head; typedef Types13 Tail; }; template struct Types15 { typedef T1 Head; typedef Types14 Tail; }; template struct Types16 { typedef T1 Head; typedef Types15 Tail; }; template struct Types17 { typedef T1 Head; typedef Types16 Tail; }; template struct Types18 { typedef T1 Head; typedef Types17 Tail; }; template struct Types19 { typedef T1 Head; typedef Types18 Tail; }; template struct Types20 { typedef T1 Head; typedef Types19 Tail; }; template struct Types21 { typedef T1 Head; typedef Types20 Tail; }; template struct Types22 { typedef T1 Head; typedef Types21 Tail; }; template struct Types23 { typedef T1 Head; typedef Types22 Tail; }; template struct Types24 { typedef T1 Head; typedef Types23 Tail; }; template struct Types25 { typedef T1 Head; typedef Types24 Tail; }; template struct Types26 { typedef T1 Head; typedef Types25 Tail; }; template struct Types27 { typedef T1 Head; typedef Types26 Tail; }; template struct Types28 { typedef T1 Head; typedef Types27 Tail; }; template struct Types29 { typedef T1 Head; typedef Types28 Tail; }; template struct Types30 { typedef T1 Head; typedef Types29 Tail; }; template struct Types31 { typedef T1 Head; typedef Types30 Tail; }; template struct Types32 { typedef T1 Head; typedef Types31 Tail; }; template struct Types33 { typedef T1 Head; typedef Types32 Tail; }; template struct Types34 { typedef T1 Head; typedef Types33 Tail; }; template struct Types35 { typedef T1 Head; typedef Types34 Tail; }; template struct Types36 { typedef T1 Head; typedef Types35 Tail; }; template struct Types37 { typedef T1 Head; typedef Types36 Tail; }; template struct Types38 { typedef T1 Head; typedef Types37 Tail; }; template struct Types39 { typedef T1 Head; typedef Types38 Tail; }; template struct Types40 { typedef T1 Head; typedef Types39 Tail; }; template struct Types41 { typedef T1 Head; typedef Types40 Tail; }; template struct Types42 { typedef T1 Head; typedef Types41 Tail; }; template struct Types43 { typedef T1 Head; typedef Types42 Tail; }; template struct Types44 { typedef T1 Head; typedef Types43 Tail; }; template struct Types45 { typedef T1 Head; typedef Types44 Tail; }; template struct Types46 { typedef T1 Head; typedef Types45 Tail; }; template struct Types47 { typedef T1 Head; typedef Types46 Tail; }; template struct Types48 { typedef T1 Head; typedef Types47 Tail; }; template struct Types49 { typedef T1 Head; typedef Types48 Tail; }; template struct Types50 { typedef T1 Head; typedef Types49 Tail; }; } // namespace internal // We don't want to require the users to write TypesN<...> directly, // as that would require them to count the length. Types<...> is much // easier to write, but generates horrible messages when there is a // compiler error, as gcc insists on printing out each template // argument, even if it has the default value (this means Types // will appear as Types in the compiler // errors). // // Our solution is to combine the best part of the two approaches: a // user would write Types, and Google Test will translate // that to TypesN internally to make error messages // readable. The translation is done by the 'type' member of the // Types template. template struct Types { typedef internal::Types50 type; }; template <> struct Types { typedef internal::Types0 type; }; template struct Types { typedef internal::Types1 type; }; template struct Types { typedef internal::Types2 type; }; template struct Types { typedef internal::Types3 type; }; template struct Types { typedef internal::Types4 type; }; template struct Types { typedef internal::Types5 type; }; template struct Types { typedef internal::Types6 type; }; template struct Types { typedef internal::Types7 type; }; template struct Types { typedef internal::Types8 type; }; template struct Types { typedef internal::Types9 type; }; template struct Types { typedef internal::Types10 type; }; template struct Types { typedef internal::Types11 type; }; template struct Types { typedef internal::Types12 type; }; template struct Types { typedef internal::Types13 type; }; template struct Types { typedef internal::Types14 type; }; template struct Types { typedef internal::Types15 type; }; template struct Types { typedef internal::Types16 type; }; template struct Types { typedef internal::Types17 type; }; template struct Types { typedef internal::Types18 type; }; template struct Types { typedef internal::Types19 type; }; template struct Types { typedef internal::Types20 type; }; template struct Types { typedef internal::Types21 type; }; template struct Types { typedef internal::Types22 type; }; template struct Types { typedef internal::Types23 type; }; template struct Types { typedef internal::Types24 type; }; template struct Types { typedef internal::Types25 type; }; template struct Types { typedef internal::Types26 type; }; template struct Types { typedef internal::Types27 type; }; template struct Types { typedef internal::Types28 type; }; template struct Types { typedef internal::Types29 type; }; template struct Types { typedef internal::Types30 type; }; template struct Types { typedef internal::Types31 type; }; template struct Types { typedef internal::Types32 type; }; template struct Types { typedef internal::Types33 type; }; template struct Types { typedef internal::Types34 type; }; template struct Types { typedef internal::Types35 type; }; template struct Types { typedef internal::Types36 type; }; template struct Types { typedef internal::Types37 type; }; template struct Types { typedef internal::Types38 type; }; template struct Types { typedef internal::Types39 type; }; template struct Types { typedef internal::Types40 type; }; template struct Types { typedef internal::Types41 type; }; template struct Types { typedef internal::Types42 type; }; template struct Types { typedef internal::Types43 type; }; template struct Types { typedef internal::Types44 type; }; template struct Types { typedef internal::Types45 type; }; template struct Types { typedef internal::Types46 type; }; template struct Types { typedef internal::Types47 type; }; template struct Types { typedef internal::Types48 type; }; template struct Types { typedef internal::Types49 type; }; namespace internal { # define GTEST_TEMPLATE_ template class // The template "selector" struct TemplateSel is used to // represent Tmpl, which must be a class template with one type // parameter, as a type. TemplateSel::Bind::type is defined // as the type Tmpl. This allows us to actually instantiate the // template "selected" by TemplateSel. // // This trick is necessary for simulating typedef for class templates, // which C++ doesn't support directly. template struct TemplateSel { template struct Bind { typedef Tmpl type; }; }; # define GTEST_BIND_(TmplSel, T) \ TmplSel::template Bind::type // A unique struct template used as the default value for the // arguments of class template Templates. This allows us to simulate // variadic templates (e.g. Templates, Templates, // and etc), which C++ doesn't support directly. template struct NoneT {}; // The following family of struct and struct templates are used to // represent template lists. In particular, TemplatesN represents a list of N templates (T1, T2, ..., and TN). Except // for Templates0, every struct in the family has two member types: // Head for the selector of the first template in the list, and Tail // for the rest of the list. // The empty template list. struct Templates0 {}; // Template lists of length 1, 2, 3, and so on. template struct Templates1 { typedef TemplateSel Head; typedef Templates0 Tail; }; template struct Templates2 { typedef TemplateSel Head; typedef Templates1 Tail; }; template struct Templates3 { typedef TemplateSel Head; typedef Templates2 Tail; }; template struct Templates4 { typedef TemplateSel Head; typedef Templates3 Tail; }; template struct Templates5 { typedef TemplateSel Head; typedef Templates4 Tail; }; template struct Templates6 { typedef TemplateSel Head; typedef Templates5 Tail; }; template struct Templates7 { typedef TemplateSel Head; typedef Templates6 Tail; }; template struct Templates8 { typedef TemplateSel Head; typedef Templates7 Tail; }; template struct Templates9 { typedef TemplateSel Head; typedef Templates8 Tail; }; template struct Templates10 { typedef TemplateSel Head; typedef Templates9 Tail; }; template struct Templates11 { typedef TemplateSel Head; typedef Templates10 Tail; }; template struct Templates12 { typedef TemplateSel Head; typedef Templates11 Tail; }; template struct Templates13 { typedef TemplateSel Head; typedef Templates12 Tail; }; template struct Templates14 { typedef TemplateSel Head; typedef Templates13 Tail; }; template struct Templates15 { typedef TemplateSel Head; typedef Templates14 Tail; }; template struct Templates16 { typedef TemplateSel Head; typedef Templates15 Tail; }; template struct Templates17 { typedef TemplateSel Head; typedef Templates16 Tail; }; template struct Templates18 { typedef TemplateSel Head; typedef Templates17 Tail; }; template struct Templates19 { typedef TemplateSel Head; typedef Templates18 Tail; }; template struct Templates20 { typedef TemplateSel Head; typedef Templates19 Tail; }; template struct Templates21 { typedef TemplateSel Head; typedef Templates20 Tail; }; template struct Templates22 { typedef TemplateSel Head; typedef Templates21 Tail; }; template struct Templates23 { typedef TemplateSel Head; typedef Templates22 Tail; }; template struct Templates24 { typedef TemplateSel Head; typedef Templates23 Tail; }; template struct Templates25 { typedef TemplateSel Head; typedef Templates24 Tail; }; template struct Templates26 { typedef TemplateSel Head; typedef Templates25 Tail; }; template struct Templates27 { typedef TemplateSel Head; typedef Templates26 Tail; }; template struct Templates28 { typedef TemplateSel Head; typedef Templates27 Tail; }; template struct Templates29 { typedef TemplateSel Head; typedef Templates28 Tail; }; template struct Templates30 { typedef TemplateSel Head; typedef Templates29 Tail; }; template struct Templates31 { typedef TemplateSel Head; typedef Templates30 Tail; }; template struct Templates32 { typedef TemplateSel Head; typedef Templates31 Tail; }; template struct Templates33 { typedef TemplateSel Head; typedef Templates32 Tail; }; template struct Templates34 { typedef TemplateSel Head; typedef Templates33 Tail; }; template struct Templates35 { typedef TemplateSel Head; typedef Templates34 Tail; }; template struct Templates36 { typedef TemplateSel Head; typedef Templates35 Tail; }; template struct Templates37 { typedef TemplateSel Head; typedef Templates36 Tail; }; template struct Templates38 { typedef TemplateSel Head; typedef Templates37 Tail; }; template struct Templates39 { typedef TemplateSel Head; typedef Templates38 Tail; }; template struct Templates40 { typedef TemplateSel Head; typedef Templates39 Tail; }; template struct Templates41 { typedef TemplateSel Head; typedef Templates40 Tail; }; template struct Templates42 { typedef TemplateSel Head; typedef Templates41 Tail; }; template struct Templates43 { typedef TemplateSel Head; typedef Templates42 Tail; }; template struct Templates44 { typedef TemplateSel Head; typedef Templates43 Tail; }; template struct Templates45 { typedef TemplateSel Head; typedef Templates44 Tail; }; template struct Templates46 { typedef TemplateSel Head; typedef Templates45 Tail; }; template struct Templates47 { typedef TemplateSel Head; typedef Templates46 Tail; }; template struct Templates48 { typedef TemplateSel Head; typedef Templates47 Tail; }; template struct Templates49 { typedef TemplateSel Head; typedef Templates48 Tail; }; template struct Templates50 { typedef TemplateSel Head; typedef Templates49 Tail; }; // We don't want to require the users to write TemplatesN<...> directly, // as that would require them to count the length. Templates<...> is much // easier to write, but generates horrible messages when there is a // compiler error, as gcc insists on printing out each template // argument, even if it has the default value (this means Templates // will appear as Templates in the compiler // errors). // // Our solution is to combine the best part of the two approaches: a // user would write Templates, and Google Test will translate // that to TemplatesN internally to make error messages // readable. The translation is done by the 'type' member of the // Templates template. template struct Templates { typedef Templates50 type; }; template <> struct Templates { typedef Templates0 type; }; template struct Templates { typedef Templates1 type; }; template struct Templates { typedef Templates2 type; }; template struct Templates { typedef Templates3 type; }; template struct Templates { typedef Templates4 type; }; template struct Templates { typedef Templates5 type; }; template struct Templates { typedef Templates6 type; }; template struct Templates { typedef Templates7 type; }; template struct Templates { typedef Templates8 type; }; template struct Templates { typedef Templates9 type; }; template struct Templates { typedef Templates10 type; }; template struct Templates { typedef Templates11 type; }; template struct Templates { typedef Templates12 type; }; template struct Templates { typedef Templates13 type; }; template struct Templates { typedef Templates14 type; }; template struct Templates { typedef Templates15 type; }; template struct Templates { typedef Templates16 type; }; template struct Templates { typedef Templates17 type; }; template struct Templates { typedef Templates18 type; }; template struct Templates { typedef Templates19 type; }; template struct Templates { typedef Templates20 type; }; template struct Templates { typedef Templates21 type; }; template struct Templates { typedef Templates22 type; }; template struct Templates { typedef Templates23 type; }; template struct Templates { typedef Templates24 type; }; template struct Templates { typedef Templates25 type; }; template struct Templates { typedef Templates26 type; }; template struct Templates { typedef Templates27 type; }; template struct Templates { typedef Templates28 type; }; template struct Templates { typedef Templates29 type; }; template struct Templates { typedef Templates30 type; }; template struct Templates { typedef Templates31 type; }; template struct Templates { typedef Templates32 type; }; template struct Templates { typedef Templates33 type; }; template struct Templates { typedef Templates34 type; }; template struct Templates { typedef Templates35 type; }; template struct Templates { typedef Templates36 type; }; template struct Templates { typedef Templates37 type; }; template struct Templates { typedef Templates38 type; }; template struct Templates { typedef Templates39 type; }; template struct Templates { typedef Templates40 type; }; template struct Templates { typedef Templates41 type; }; template struct Templates { typedef Templates42 type; }; template struct Templates { typedef Templates43 type; }; template struct Templates { typedef Templates44 type; }; template struct Templates { typedef Templates45 type; }; template struct Templates { typedef Templates46 type; }; template struct Templates { typedef Templates47 type; }; template struct Templates { typedef Templates48 type; }; template struct Templates { typedef Templates49 type; }; // The TypeList template makes it possible to use either a single type // or a Types<...> list in TYPED_TEST_CASE() and // INSTANTIATE_TYPED_TEST_CASE_P(). template struct TypeList { typedef Types1 type; }; template struct TypeList > { typedef typename Types::type type; }; #endif // GTEST_HAS_TYPED_TEST || GTEST_HAS_TYPED_TEST_P } // namespace internal } // namespace testing #endif // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_TYPE_UTIL_H_ ugene-1.9.8/src/libs_3rdparty/gtest/src/gtest/internal/gtest-tuple.h.pump0000644000175000017500000002200711651544307025156 0ustar ilyailya$$ -*- mode: c++; -*- $var n = 10 $$ Maximum number of tuple fields we want to support. $$ This meta comment fixes auto-indentation in Emacs. }} // Copyright 2009 Google Inc. // All Rights Reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Author: wan@google.com (Zhanyong Wan) // Implements a subset of TR1 tuple needed by Google Test and Google Mock. #ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_TUPLE_H_ #define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_TUPLE_H_ #include // For ::std::pair. // The compiler used in Symbian has a bug that prevents us from declaring the // tuple template as a friend (it complains that tuple is redefined). This // hack bypasses the bug by declaring the members that should otherwise be // private as public. // Sun Studio versions < 12 also have the above bug. #if defined(__SYMBIAN32__) || (defined(__SUNPRO_CC) && __SUNPRO_CC < 0x590) # define GTEST_DECLARE_TUPLE_AS_FRIEND_ public: #else # define GTEST_DECLARE_TUPLE_AS_FRIEND_ \ template friend class tuple; \ private: #endif $range i 0..n-1 $range j 0..n $range k 1..n // GTEST_n_TUPLE_(T) is the type of an n-tuple. #define GTEST_0_TUPLE_(T) tuple<> $for k [[ $range m 0..k-1 $range m2 k..n-1 #define GTEST_$(k)_TUPLE_(T) tuple<$for m, [[T##$m]]$for m2 [[, void]]> ]] // GTEST_n_TYPENAMES_(T) declares a list of n typenames. $for j [[ $range m 0..j-1 #define GTEST_$(j)_TYPENAMES_(T) $for m, [[typename T##$m]] ]] // In theory, defining stuff in the ::std namespace is undefined // behavior. We can do this as we are playing the role of a standard // library vendor. namespace std { namespace tr1 { template <$for i, [[typename T$i = void]]> class tuple; // Anything in namespace gtest_internal is Google Test's INTERNAL // IMPLEMENTATION DETAIL and MUST NOT BE USED DIRECTLY in user code. namespace gtest_internal { // ByRef::type is T if T is a reference; otherwise it's const T&. template struct ByRef { typedef const T& type; }; // NOLINT template struct ByRef { typedef T& type; }; // NOLINT // A handy wrapper for ByRef. #define GTEST_BY_REF_(T) typename ::std::tr1::gtest_internal::ByRef::type // AddRef::type is T if T is a reference; otherwise it's T&. This // is the same as tr1::add_reference::type. template struct AddRef { typedef T& type; }; // NOLINT template struct AddRef { typedef T& type; }; // NOLINT // A handy wrapper for AddRef. #define GTEST_ADD_REF_(T) typename ::std::tr1::gtest_internal::AddRef::type // A helper for implementing get(). template class Get; // A helper for implementing tuple_element. kIndexValid is true // iff k < the number of fields in tuple type T. template struct TupleElement; $for i [[ template struct TupleElement [[]] { typedef T$i type; }; ]] } // namespace gtest_internal template <> class tuple<> { public: tuple() {} tuple(const tuple& /* t */) {} tuple& operator=(const tuple& /* t */) { return *this; } }; $for k [[ $range m 0..k-1 template class $if k < n [[GTEST_$(k)_TUPLE_(T)]] $else [[tuple]] { public: template friend class gtest_internal::Get; tuple() : $for m, [[f$(m)_()]] {} explicit tuple($for m, [[GTEST_BY_REF_(T$m) f$m]]) : [[]] $for m, [[f$(m)_(f$m)]] {} tuple(const tuple& t) : $for m, [[f$(m)_(t.f$(m)_)]] {} template tuple(const GTEST_$(k)_TUPLE_(U)& t) : $for m, [[f$(m)_(t.f$(m)_)]] {} $if k == 2 [[ template tuple(const ::std::pair& p) : f0_(p.first), f1_(p.second) {} ]] tuple& operator=(const tuple& t) { return CopyFrom(t); } template tuple& operator=(const GTEST_$(k)_TUPLE_(U)& t) { return CopyFrom(t); } $if k == 2 [[ template tuple& operator=(const ::std::pair& p) { f0_ = p.first; f1_ = p.second; return *this; } ]] GTEST_DECLARE_TUPLE_AS_FRIEND_ template tuple& CopyFrom(const GTEST_$(k)_TUPLE_(U)& t) { $for m [[ f$(m)_ = t.f$(m)_; ]] return *this; } $for m [[ T$m f$(m)_; ]] }; ]] // 6.1.3.2 Tuple creation functions. // Known limitations: we don't support passing an // std::tr1::reference_wrapper to make_tuple(). And we don't // implement tie(). inline tuple<> make_tuple() { return tuple<>(); } $for k [[ $range m 0..k-1 template inline GTEST_$(k)_TUPLE_(T) make_tuple($for m, [[const T$m& f$m]]) { return GTEST_$(k)_TUPLE_(T)($for m, [[f$m]]); } ]] // 6.1.3.3 Tuple helper classes. template struct tuple_size; $for j [[ template struct tuple_size { static const int value = $j; }; ]] template struct tuple_element { typedef typename gtest_internal::TupleElement< k < (tuple_size::value), k, Tuple>::type type; }; #define GTEST_TUPLE_ELEMENT_(k, Tuple) typename tuple_element::type // 6.1.3.4 Element access. namespace gtest_internal { $for i [[ template <> class Get<$i> { public: template static GTEST_ADD_REF_(GTEST_TUPLE_ELEMENT_($i, Tuple)) Field(Tuple& t) { return t.f$(i)_; } // NOLINT template static GTEST_BY_REF_(GTEST_TUPLE_ELEMENT_($i, Tuple)) ConstField(const Tuple& t) { return t.f$(i)_; } }; ]] } // namespace gtest_internal template GTEST_ADD_REF_(GTEST_TUPLE_ELEMENT_(k, GTEST_$(n)_TUPLE_(T))) get(GTEST_$(n)_TUPLE_(T)& t) { return gtest_internal::Get::Field(t); } template GTEST_BY_REF_(GTEST_TUPLE_ELEMENT_(k, GTEST_$(n)_TUPLE_(T))) get(const GTEST_$(n)_TUPLE_(T)& t) { return gtest_internal::Get::ConstField(t); } // 6.1.3.5 Relational operators // We only implement == and !=, as we don't have a need for the rest yet. namespace gtest_internal { // SameSizeTuplePrefixComparator::Eq(t1, t2) returns true if the // first k fields of t1 equals the first k fields of t2. // SameSizeTuplePrefixComparator(k1, k2) would be a compiler error if // k1 != k2. template struct SameSizeTuplePrefixComparator; template <> struct SameSizeTuplePrefixComparator<0, 0> { template static bool Eq(const Tuple1& /* t1 */, const Tuple2& /* t2 */) { return true; } }; template struct SameSizeTuplePrefixComparator { template static bool Eq(const Tuple1& t1, const Tuple2& t2) { return SameSizeTuplePrefixComparator::Eq(t1, t2) && ::std::tr1::get(t1) == ::std::tr1::get(t2); } }; } // namespace gtest_internal template inline bool operator==(const GTEST_$(n)_TUPLE_(T)& t, const GTEST_$(n)_TUPLE_(U)& u) { return gtest_internal::SameSizeTuplePrefixComparator< tuple_size::value, tuple_size::value>::Eq(t, u); } template inline bool operator!=(const GTEST_$(n)_TUPLE_(T)& t, const GTEST_$(n)_TUPLE_(U)& u) { return !(t == u); } // 6.1.4 Pairs. // Unimplemented. } // namespace tr1 } // namespace std $for j [[ #undef GTEST_$(j)_TUPLE_ ]] $for j [[ #undef GTEST_$(j)_TYPENAMES_ ]] #undef GTEST_DECLARE_TUPLE_AS_FRIEND_ #undef GTEST_BY_REF_ #undef GTEST_ADD_REF_ #undef GTEST_TUPLE_ELEMENT_ #endif // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_TUPLE_H_ ugene-1.9.8/src/libs_3rdparty/gtest/src/gtest/internal/gtest-string.h0000644000175000017500000003243311651544307024357 0ustar ilyailya// Copyright 2005, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Authors: wan@google.com (Zhanyong Wan), eefacm@gmail.com (Sean Mcafee) // // The Google C++ Testing Framework (Google Test) // // This header file declares the String class and functions used internally by // Google Test. They are subject to change without notice. They should not used // by code external to Google Test. // // This header file is #included by . // It should not be #included by other files. #ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_STRING_H_ #define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_STRING_H_ #ifdef __BORLANDC__ // string.h is not guaranteed to provide strcpy on C++ Builder. # include #endif #include #include "gtest/internal/gtest-port.h" #include namespace testing { namespace internal { // String - a UTF-8 string class. // // For historic reasons, we don't use std::string. // // TODO(wan@google.com): replace this class with std::string or // implement it in terms of the latter. // // Note that String can represent both NULL and the empty string, // while std::string cannot represent NULL. // // NULL and the empty string are considered different. NULL is less // than anything (including the empty string) except itself. // // This class only provides minimum functionality necessary for // implementing Google Test. We do not intend to implement a full-fledged // string class here. // // Since the purpose of this class is to provide a substitute for // std::string on platforms where it cannot be used, we define a copy // constructor and assignment operators such that we don't need // conditional compilation in a lot of places. // // In order to make the representation efficient, the d'tor of String // is not virtual. Therefore DO NOT INHERIT FROM String. class GTEST_API_ String { public: // Static utility methods // Returns the input enclosed in double quotes if it's not NULL; // otherwise returns "(null)". For example, "\"Hello\"" is returned // for input "Hello". // // This is useful for printing a C string in the syntax of a literal. // // Known issue: escape sequences are not handled yet. static String ShowCStringQuoted(const char* c_str); // Clones a 0-terminated C string, allocating memory using new. The // caller is responsible for deleting the return value using // delete[]. Returns the cloned string, or NULL if the input is // NULL. // // This is different from strdup() in string.h, which allocates // memory using malloc(). static const char* CloneCString(const char* c_str); #if GTEST_OS_WINDOWS_MOBILE // Windows CE does not have the 'ANSI' versions of Win32 APIs. To be // able to pass strings to Win32 APIs on CE we need to convert them // to 'Unicode', UTF-16. // Creates a UTF-16 wide string from the given ANSI string, allocating // memory using new. The caller is responsible for deleting the return // value using delete[]. Returns the wide string, or NULL if the // input is NULL. // // The wide string is created using the ANSI codepage (CP_ACP) to // match the behaviour of the ANSI versions of Win32 calls and the // C runtime. static LPCWSTR AnsiToUtf16(const char* c_str); // Creates an ANSI string from the given wide string, allocating // memory using new. The caller is responsible for deleting the return // value using delete[]. Returns the ANSI string, or NULL if the // input is NULL. // // The returned string is created using the ANSI codepage (CP_ACP) to // match the behaviour of the ANSI versions of Win32 calls and the // C runtime. static const char* Utf16ToAnsi(LPCWSTR utf16_str); #endif // Compares two C strings. Returns true iff they have the same content. // // Unlike strcmp(), this function can handle NULL argument(s). A // NULL C string is considered different to any non-NULL C string, // including the empty string. static bool CStringEquals(const char* lhs, const char* rhs); // Converts a wide C string to a String using the UTF-8 encoding. // NULL will be converted to "(null)". If an error occurred during // the conversion, "(failed to convert from wide string)" is // returned. static String ShowWideCString(const wchar_t* wide_c_str); // Similar to ShowWideCString(), except that this function encloses // the converted string in double quotes. static String ShowWideCStringQuoted(const wchar_t* wide_c_str); // Compares two wide C strings. Returns true iff they have the same // content. // // Unlike wcscmp(), this function can handle NULL argument(s). A // NULL C string is considered different to any non-NULL C string, // including the empty string. static bool WideCStringEquals(const wchar_t* lhs, const wchar_t* rhs); // Compares two C strings, ignoring case. Returns true iff they // have the same content. // // Unlike strcasecmp(), this function can handle NULL argument(s). // A NULL C string is considered different to any non-NULL C string, // including the empty string. static bool CaseInsensitiveCStringEquals(const char* lhs, const char* rhs); // Compares two wide C strings, ignoring case. Returns true iff they // have the same content. // // Unlike wcscasecmp(), this function can handle NULL argument(s). // A NULL C string is considered different to any non-NULL wide C string, // including the empty string. // NB: The implementations on different platforms slightly differ. // On windows, this method uses _wcsicmp which compares according to LC_CTYPE // environment variable. On GNU platform this method uses wcscasecmp // which compares according to LC_CTYPE category of the current locale. // On MacOS X, it uses towlower, which also uses LC_CTYPE category of the // current locale. static bool CaseInsensitiveWideCStringEquals(const wchar_t* lhs, const wchar_t* rhs); // Formats a list of arguments to a String, using the same format // spec string as for printf. // // We do not use the StringPrintf class as it is not universally // available. // // The result is limited to 4096 characters (including the tailing // 0). If 4096 characters are not enough to format the input, // "" is returned. static String Format(const char* format, ...); // C'tors // The default c'tor constructs a NULL string. String() : c_str_(NULL), length_(0) {} // Constructs a String by cloning a 0-terminated C string. String(const char* a_c_str) { // NOLINT if (a_c_str == NULL) { c_str_ = NULL; length_ = 0; } else { ConstructNonNull(a_c_str, strlen(a_c_str)); } } // Constructs a String by copying a given number of chars from a // buffer. E.g. String("hello", 3) creates the string "hel", // String("a\0bcd", 4) creates "a\0bc", String(NULL, 0) creates "", // and String(NULL, 1) results in access violation. String(const char* buffer, size_t a_length) { ConstructNonNull(buffer, a_length); } // The copy c'tor creates a new copy of the string. The two // String objects do not share content. String(const String& str) : c_str_(NULL), length_(0) { *this = str; } // D'tor. String is intended to be a final class, so the d'tor // doesn't need to be virtual. ~String() { delete[] c_str_; } // Allows a String to be implicitly converted to an ::std::string or // ::string, and vice versa. Converting a String containing a NULL // pointer to ::std::string or ::string is undefined behavior. // Converting a ::std::string or ::string containing an embedded NUL // character to a String will result in the prefix up to the first // NUL character. String(const ::std::string& str) { ConstructNonNull(str.c_str(), str.length()); } operator ::std::string() const { return ::std::string(c_str(), length()); } #if GTEST_HAS_GLOBAL_STRING String(const ::string& str) { ConstructNonNull(str.c_str(), str.length()); } operator ::string() const { return ::string(c_str(), length()); } #endif // GTEST_HAS_GLOBAL_STRING // Returns true iff this is an empty string (i.e. ""). bool empty() const { return (c_str() != NULL) && (length() == 0); } // Compares this with another String. // Returns < 0 if this is less than rhs, 0 if this is equal to rhs, or > 0 // if this is greater than rhs. int Compare(const String& rhs) const; // Returns true iff this String equals the given C string. A NULL // string and a non-NULL string are considered not equal. bool operator==(const char* a_c_str) const { return Compare(a_c_str) == 0; } // Returns true iff this String is less than the given String. A // NULL string is considered less than "". bool operator<(const String& rhs) const { return Compare(rhs) < 0; } // Returns true iff this String doesn't equal the given C string. A NULL // string and a non-NULL string are considered not equal. bool operator!=(const char* a_c_str) const { return !(*this == a_c_str); } // Returns true iff this String ends with the given suffix. *Any* // String is considered to end with a NULL or empty suffix. bool EndsWith(const char* suffix) const; // Returns true iff this String ends with the given suffix, not considering // case. Any String is considered to end with a NULL or empty suffix. bool EndsWithCaseInsensitive(const char* suffix) const; // Returns the length of the encapsulated string, or 0 if the // string is NULL. size_t length() const { return length_; } // Gets the 0-terminated C string this String object represents. // The String object still owns the string. Therefore the caller // should NOT delete the return value. const char* c_str() const { return c_str_; } // Assigns a C string to this object. Self-assignment works. const String& operator=(const char* a_c_str) { return *this = String(a_c_str); } // Assigns a String object to this object. Self-assignment works. const String& operator=(const String& rhs) { if (this != &rhs) { delete[] c_str_; if (rhs.c_str() == NULL) { c_str_ = NULL; length_ = 0; } else { ConstructNonNull(rhs.c_str(), rhs.length()); } } return *this; } private: // Constructs a non-NULL String from the given content. This // function can only be called when c_str_ has not been allocated. // ConstructNonNull(NULL, 0) results in an empty string (""). // ConstructNonNull(NULL, non_zero) is undefined behavior. void ConstructNonNull(const char* buffer, size_t a_length) { char* const str = new char[a_length + 1]; memcpy(str, buffer, a_length); str[a_length] = '\0'; c_str_ = str; length_ = a_length; } const char* c_str_; size_t length_; }; // class String // Streams a String to an ostream. Each '\0' character in the String // is replaced with "\\0". inline ::std::ostream& operator<<(::std::ostream& os, const String& str) { if (str.c_str() == NULL) { os << "(null)"; } else { const char* const c_str = str.c_str(); for (size_t i = 0; i != str.length(); i++) { if (c_str[i] == '\0') { os << "\\0"; } else { os << c_str[i]; } } } return os; } // Gets the content of the stringstream's buffer as a String. Each '\0' // character in the buffer is replaced with "\\0". GTEST_API_ String StringStreamToString(::std::stringstream* stream); // Converts a streamable value to a String. A NULL pointer is // converted to "(null)". When the input value is a ::string, // ::std::string, ::wstring, or ::std::wstring object, each NUL // character in it is replaced with "\\0". // Declared here but defined in gtest.h, so that it has access // to the definition of the Message class, required by the ARM // compiler. template String StreamableToString(const T& streamable); } // namespace internal } // namespace testing #endif // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_STRING_H_ ugene-1.9.8/src/libs_3rdparty/gtest/src/gtest/internal/gtest-param-util-generated.h0000644000175000017500000051241011651544307027056 0ustar ilyailya// This file was GENERATED by command: // pump.py gtest-param-util-generated.h.pump // DO NOT EDIT BY HAND!!! // Copyright 2008 Google Inc. // All Rights Reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Author: vladl@google.com (Vlad Losev) // Type and function utilities for implementing parameterized tests. // This file is generated by a SCRIPT. DO NOT EDIT BY HAND! // // Currently Google Test supports at most 50 arguments in Values, // and at most 10 arguments in Combine. Please contact // googletestframework@googlegroups.com if you need more. // Please note that the number of arguments to Combine is limited // by the maximum arity of the implementation of tr1::tuple which is // currently set at 10. #ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PARAM_UTIL_GENERATED_H_ #define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PARAM_UTIL_GENERATED_H_ // scripts/fuse_gtest.py depends on gtest's own header being #included // *unconditionally*. Therefore these #includes cannot be moved // inside #if GTEST_HAS_PARAM_TEST. #include "gtest/internal/gtest-param-util.h" #include "gtest/internal/gtest-port.h" #if GTEST_HAS_PARAM_TEST namespace testing { // Forward declarations of ValuesIn(), which is implemented in // include/gtest/gtest-param-test.h. template internal::ParamGenerator< typename ::testing::internal::IteratorTraits::value_type> ValuesIn(ForwardIterator begin, ForwardIterator end); template internal::ParamGenerator ValuesIn(const T (&array)[N]); template internal::ParamGenerator ValuesIn( const Container& container); namespace internal { // Used in the Values() function to provide polymorphic capabilities. template class ValueArray1 { public: explicit ValueArray1(T1 v1) : v1_(v1) {} template operator ParamGenerator() const { return ValuesIn(&v1_, &v1_ + 1); } private: // No implementation - assignment is unsupported. void operator=(const ValueArray1& other); const T1 v1_; }; template class ValueArray2 { public: ValueArray2(T1 v1, T2 v2) : v1_(v1), v2_(v2) {} template operator ParamGenerator() const { const T array[] = {v1_, v2_}; return ValuesIn(array); } private: // No implementation - assignment is unsupported. void operator=(const ValueArray2& other); const T1 v1_; const T2 v2_; }; template class ValueArray3 { public: ValueArray3(T1 v1, T2 v2, T3 v3) : v1_(v1), v2_(v2), v3_(v3) {} template operator ParamGenerator() const { const T array[] = {v1_, v2_, v3_}; return ValuesIn(array); } private: // No implementation - assignment is unsupported. void operator=(const ValueArray3& other); const T1 v1_; const T2 v2_; const T3 v3_; }; template class ValueArray4 { public: ValueArray4(T1 v1, T2 v2, T3 v3, T4 v4) : v1_(v1), v2_(v2), v3_(v3), v4_(v4) {} template operator ParamGenerator() const { const T array[] = {v1_, v2_, v3_, v4_}; return ValuesIn(array); } private: // No implementation - assignment is unsupported. void operator=(const ValueArray4& other); const T1 v1_; const T2 v2_; const T3 v3_; const T4 v4_; }; template class ValueArray5 { public: ValueArray5(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5) {} template operator ParamGenerator() const { const T array[] = {v1_, v2_, v3_, v4_, v5_}; return ValuesIn(array); } private: // No implementation - assignment is unsupported. void operator=(const ValueArray5& other); const T1 v1_; const T2 v2_; const T3 v3_; const T4 v4_; const T5 v5_; }; template class ValueArray6 { public: ValueArray6(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6) {} template operator ParamGenerator() const { const T array[] = {v1_, v2_, v3_, v4_, v5_, v6_}; return ValuesIn(array); } private: // No implementation - assignment is unsupported. void operator=(const ValueArray6& other); const T1 v1_; const T2 v2_; const T3 v3_; const T4 v4_; const T5 v5_; const T6 v6_; }; template class ValueArray7 { public: ValueArray7(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7) {} template operator ParamGenerator() const { const T array[] = {v1_, v2_, v3_, v4_, v5_, v6_, v7_}; return ValuesIn(array); } private: // No implementation - assignment is unsupported. void operator=(const ValueArray7& other); const T1 v1_; const T2 v2_; const T3 v3_; const T4 v4_; const T5 v5_; const T6 v6_; const T7 v7_; }; template class ValueArray8 { public: ValueArray8(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), v8_(v8) {} template operator ParamGenerator() const { const T array[] = {v1_, v2_, v3_, v4_, v5_, v6_, v7_, v8_}; return ValuesIn(array); } private: // No implementation - assignment is unsupported. void operator=(const ValueArray8& other); const T1 v1_; const T2 v2_; const T3 v3_; const T4 v4_; const T5 v5_; const T6 v6_; const T7 v7_; const T8 v8_; }; template class ValueArray9 { public: ValueArray9(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9) {} template operator ParamGenerator() const { const T array[] = {v1_, v2_, v3_, v4_, v5_, v6_, v7_, v8_, v9_}; return ValuesIn(array); } private: // No implementation - assignment is unsupported. void operator=(const ValueArray9& other); const T1 v1_; const T2 v2_; const T3 v3_; const T4 v4_; const T5 v5_; const T6 v6_; const T7 v7_; const T8 v8_; const T9 v9_; }; template class ValueArray10 { public: ValueArray10(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9), v10_(v10) {} template operator ParamGenerator() const { const T array[] = {v1_, v2_, v3_, v4_, v5_, v6_, v7_, v8_, v9_, v10_}; return ValuesIn(array); } private: // No implementation - assignment is unsupported. void operator=(const ValueArray10& other); const T1 v1_; const T2 v2_; const T3 v3_; const T4 v4_; const T5 v5_; const T6 v6_; const T7 v7_; const T8 v8_; const T9 v9_; const T10 v10_; }; template class ValueArray11 { public: ValueArray11(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9), v10_(v10), v11_(v11) {} template operator ParamGenerator() const { const T array[] = {v1_, v2_, v3_, v4_, v5_, v6_, v7_, v8_, v9_, v10_, v11_}; return ValuesIn(array); } private: // No implementation - assignment is unsupported. void operator=(const ValueArray11& other); const T1 v1_; const T2 v2_; const T3 v3_; const T4 v4_; const T5 v5_; const T6 v6_; const T7 v7_; const T8 v8_; const T9 v9_; const T10 v10_; const T11 v11_; }; template class ValueArray12 { public: ValueArray12(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9), v10_(v10), v11_(v11), v12_(v12) {} template operator ParamGenerator() const { const T array[] = {v1_, v2_, v3_, v4_, v5_, v6_, v7_, v8_, v9_, v10_, v11_, v12_}; return ValuesIn(array); } private: // No implementation - assignment is unsupported. void operator=(const ValueArray12& other); const T1 v1_; const T2 v2_; const T3 v3_; const T4 v4_; const T5 v5_; const T6 v6_; const T7 v7_; const T8 v8_; const T9 v9_; const T10 v10_; const T11 v11_; const T12 v12_; }; template class ValueArray13 { public: ValueArray13(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9), v10_(v10), v11_(v11), v12_(v12), v13_(v13) {} template operator ParamGenerator() const { const T array[] = {v1_, v2_, v3_, v4_, v5_, v6_, v7_, v8_, v9_, v10_, v11_, v12_, v13_}; return ValuesIn(array); } private: // No implementation - assignment is unsupported. void operator=(const ValueArray13& other); const T1 v1_; const T2 v2_; const T3 v3_; const T4 v4_; const T5 v5_; const T6 v6_; const T7 v7_; const T8 v8_; const T9 v9_; const T10 v10_; const T11 v11_; const T12 v12_; const T13 v13_; }; template class ValueArray14 { public: ValueArray14(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9), v10_(v10), v11_(v11), v12_(v12), v13_(v13), v14_(v14) {} template operator ParamGenerator() const { const T array[] = {v1_, v2_, v3_, v4_, v5_, v6_, v7_, v8_, v9_, v10_, v11_, v12_, v13_, v14_}; return ValuesIn(array); } private: // No implementation - assignment is unsupported. void operator=(const ValueArray14& other); const T1 v1_; const T2 v2_; const T3 v3_; const T4 v4_; const T5 v5_; const T6 v6_; const T7 v7_; const T8 v8_; const T9 v9_; const T10 v10_; const T11 v11_; const T12 v12_; const T13 v13_; const T14 v14_; }; template class ValueArray15 { public: ValueArray15(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9), v10_(v10), v11_(v11), v12_(v12), v13_(v13), v14_(v14), v15_(v15) {} template operator ParamGenerator() const { const T array[] = {v1_, v2_, v3_, v4_, v5_, v6_, v7_, v8_, v9_, v10_, v11_, v12_, v13_, v14_, v15_}; return ValuesIn(array); } private: // No implementation - assignment is unsupported. void operator=(const ValueArray15& other); const T1 v1_; const T2 v2_; const T3 v3_; const T4 v4_; const T5 v5_; const T6 v6_; const T7 v7_; const T8 v8_; const T9 v9_; const T10 v10_; const T11 v11_; const T12 v12_; const T13 v13_; const T14 v14_; const T15 v15_; }; template class ValueArray16 { public: ValueArray16(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9), v10_(v10), v11_(v11), v12_(v12), v13_(v13), v14_(v14), v15_(v15), v16_(v16) {} template operator ParamGenerator() const { const T array[] = {v1_, v2_, v3_, v4_, v5_, v6_, v7_, v8_, v9_, v10_, v11_, v12_, v13_, v14_, v15_, v16_}; return ValuesIn(array); } private: // No implementation - assignment is unsupported. void operator=(const ValueArray16& other); const T1 v1_; const T2 v2_; const T3 v3_; const T4 v4_; const T5 v5_; const T6 v6_; const T7 v7_; const T8 v8_; const T9 v9_; const T10 v10_; const T11 v11_; const T12 v12_; const T13 v13_; const T14 v14_; const T15 v15_; const T16 v16_; }; template class ValueArray17 { public: ValueArray17(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9), v10_(v10), v11_(v11), v12_(v12), v13_(v13), v14_(v14), v15_(v15), v16_(v16), v17_(v17) {} template operator ParamGenerator() const { const T array[] = {v1_, v2_, v3_, v4_, v5_, v6_, v7_, v8_, v9_, v10_, v11_, v12_, v13_, v14_, v15_, v16_, v17_}; return ValuesIn(array); } private: // No implementation - assignment is unsupported. void operator=(const ValueArray17& other); const T1 v1_; const T2 v2_; const T3 v3_; const T4 v4_; const T5 v5_; const T6 v6_; const T7 v7_; const T8 v8_; const T9 v9_; const T10 v10_; const T11 v11_; const T12 v12_; const T13 v13_; const T14 v14_; const T15 v15_; const T16 v16_; const T17 v17_; }; template class ValueArray18 { public: ValueArray18(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, T18 v18) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9), v10_(v10), v11_(v11), v12_(v12), v13_(v13), v14_(v14), v15_(v15), v16_(v16), v17_(v17), v18_(v18) {} template operator ParamGenerator() const { const T array[] = {v1_, v2_, v3_, v4_, v5_, v6_, v7_, v8_, v9_, v10_, v11_, v12_, v13_, v14_, v15_, v16_, v17_, v18_}; return ValuesIn(array); } private: // No implementation - assignment is unsupported. void operator=(const ValueArray18& other); const T1 v1_; const T2 v2_; const T3 v3_; const T4 v4_; const T5 v5_; const T6 v6_; const T7 v7_; const T8 v8_; const T9 v9_; const T10 v10_; const T11 v11_; const T12 v12_; const T13 v13_; const T14 v14_; const T15 v15_; const T16 v16_; const T17 v17_; const T18 v18_; }; template class ValueArray19 { public: ValueArray19(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9), v10_(v10), v11_(v11), v12_(v12), v13_(v13), v14_(v14), v15_(v15), v16_(v16), v17_(v17), v18_(v18), v19_(v19) {} template operator ParamGenerator() const { const T array[] = {v1_, v2_, v3_, v4_, v5_, v6_, v7_, v8_, v9_, v10_, v11_, v12_, v13_, v14_, v15_, v16_, v17_, v18_, v19_}; return ValuesIn(array); } private: // No implementation - assignment is unsupported. void operator=(const ValueArray19& other); const T1 v1_; const T2 v2_; const T3 v3_; const T4 v4_; const T5 v5_; const T6 v6_; const T7 v7_; const T8 v8_; const T9 v9_; const T10 v10_; const T11 v11_; const T12 v12_; const T13 v13_; const T14 v14_; const T15 v15_; const T16 v16_; const T17 v17_; const T18 v18_; const T19 v19_; }; template class ValueArray20 { public: ValueArray20(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9), v10_(v10), v11_(v11), v12_(v12), v13_(v13), v14_(v14), v15_(v15), v16_(v16), v17_(v17), v18_(v18), v19_(v19), v20_(v20) {} template operator ParamGenerator() const { const T array[] = {v1_, v2_, v3_, v4_, v5_, v6_, v7_, v8_, v9_, v10_, v11_, v12_, v13_, v14_, v15_, v16_, v17_, v18_, v19_, v20_}; return ValuesIn(array); } private: // No implementation - assignment is unsupported. void operator=(const ValueArray20& other); const T1 v1_; const T2 v2_; const T3 v3_; const T4 v4_; const T5 v5_; const T6 v6_; const T7 v7_; const T8 v8_; const T9 v9_; const T10 v10_; const T11 v11_; const T12 v12_; const T13 v13_; const T14 v14_; const T15 v15_; const T16 v16_; const T17 v17_; const T18 v18_; const T19 v19_; const T20 v20_; }; template class ValueArray21 { public: ValueArray21(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9), v10_(v10), v11_(v11), v12_(v12), v13_(v13), v14_(v14), v15_(v15), v16_(v16), v17_(v17), v18_(v18), v19_(v19), v20_(v20), v21_(v21) {} template operator ParamGenerator() const { const T array[] = {v1_, v2_, v3_, v4_, v5_, v6_, v7_, v8_, v9_, v10_, v11_, v12_, v13_, v14_, v15_, v16_, v17_, v18_, v19_, v20_, v21_}; return ValuesIn(array); } private: // No implementation - assignment is unsupported. void operator=(const ValueArray21& other); const T1 v1_; const T2 v2_; const T3 v3_; const T4 v4_; const T5 v5_; const T6 v6_; const T7 v7_; const T8 v8_; const T9 v9_; const T10 v10_; const T11 v11_; const T12 v12_; const T13 v13_; const T14 v14_; const T15 v15_; const T16 v16_; const T17 v17_; const T18 v18_; const T19 v19_; const T20 v20_; const T21 v21_; }; template class ValueArray22 { public: ValueArray22(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9), v10_(v10), v11_(v11), v12_(v12), v13_(v13), v14_(v14), v15_(v15), v16_(v16), v17_(v17), v18_(v18), v19_(v19), v20_(v20), v21_(v21), v22_(v22) {} template operator ParamGenerator() const { const T array[] = {v1_, v2_, v3_, v4_, v5_, v6_, v7_, v8_, v9_, v10_, v11_, v12_, v13_, v14_, v15_, v16_, v17_, v18_, v19_, v20_, v21_, v22_}; return ValuesIn(array); } private: // No implementation - assignment is unsupported. void operator=(const ValueArray22& other); const T1 v1_; const T2 v2_; const T3 v3_; const T4 v4_; const T5 v5_; const T6 v6_; const T7 v7_; const T8 v8_; const T9 v9_; const T10 v10_; const T11 v11_; const T12 v12_; const T13 v13_; const T14 v14_; const T15 v15_; const T16 v16_; const T17 v17_; const T18 v18_; const T19 v19_; const T20 v20_; const T21 v21_; const T22 v22_; }; template class ValueArray23 { public: ValueArray23(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9), v10_(v10), v11_(v11), v12_(v12), v13_(v13), v14_(v14), v15_(v15), v16_(v16), v17_(v17), v18_(v18), v19_(v19), v20_(v20), v21_(v21), v22_(v22), v23_(v23) {} template operator ParamGenerator() const { const T array[] = {v1_, v2_, v3_, v4_, v5_, v6_, v7_, v8_, v9_, v10_, v11_, v12_, v13_, v14_, v15_, v16_, v17_, v18_, v19_, v20_, v21_, v22_, v23_}; return ValuesIn(array); } private: // No implementation - assignment is unsupported. void operator=(const ValueArray23& other); const T1 v1_; const T2 v2_; const T3 v3_; const T4 v4_; const T5 v5_; const T6 v6_; const T7 v7_; const T8 v8_; const T9 v9_; const T10 v10_; const T11 v11_; const T12 v12_; const T13 v13_; const T14 v14_; const T15 v15_; const T16 v16_; const T17 v17_; const T18 v18_; const T19 v19_; const T20 v20_; const T21 v21_; const T22 v22_; const T23 v23_; }; template class ValueArray24 { public: ValueArray24(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9), v10_(v10), v11_(v11), v12_(v12), v13_(v13), v14_(v14), v15_(v15), v16_(v16), v17_(v17), v18_(v18), v19_(v19), v20_(v20), v21_(v21), v22_(v22), v23_(v23), v24_(v24) {} template operator ParamGenerator() const { const T array[] = {v1_, v2_, v3_, v4_, v5_, v6_, v7_, v8_, v9_, v10_, v11_, v12_, v13_, v14_, v15_, v16_, v17_, v18_, v19_, v20_, v21_, v22_, v23_, v24_}; return ValuesIn(array); } private: // No implementation - assignment is unsupported. void operator=(const ValueArray24& other); const T1 v1_; const T2 v2_; const T3 v3_; const T4 v4_; const T5 v5_; const T6 v6_; const T7 v7_; const T8 v8_; const T9 v9_; const T10 v10_; const T11 v11_; const T12 v12_; const T13 v13_; const T14 v14_; const T15 v15_; const T16 v16_; const T17 v17_; const T18 v18_; const T19 v19_; const T20 v20_; const T21 v21_; const T22 v22_; const T23 v23_; const T24 v24_; }; template class ValueArray25 { public: ValueArray25(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9), v10_(v10), v11_(v11), v12_(v12), v13_(v13), v14_(v14), v15_(v15), v16_(v16), v17_(v17), v18_(v18), v19_(v19), v20_(v20), v21_(v21), v22_(v22), v23_(v23), v24_(v24), v25_(v25) {} template operator ParamGenerator() const { const T array[] = {v1_, v2_, v3_, v4_, v5_, v6_, v7_, v8_, v9_, v10_, v11_, v12_, v13_, v14_, v15_, v16_, v17_, v18_, v19_, v20_, v21_, v22_, v23_, v24_, v25_}; return ValuesIn(array); } private: // No implementation - assignment is unsupported. void operator=(const ValueArray25& other); const T1 v1_; const T2 v2_; const T3 v3_; const T4 v4_; const T5 v5_; const T6 v6_; const T7 v7_; const T8 v8_; const T9 v9_; const T10 v10_; const T11 v11_; const T12 v12_; const T13 v13_; const T14 v14_; const T15 v15_; const T16 v16_; const T17 v17_; const T18 v18_; const T19 v19_; const T20 v20_; const T21 v21_; const T22 v22_; const T23 v23_; const T24 v24_; const T25 v25_; }; template class ValueArray26 { public: ValueArray26(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, T26 v26) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9), v10_(v10), v11_(v11), v12_(v12), v13_(v13), v14_(v14), v15_(v15), v16_(v16), v17_(v17), v18_(v18), v19_(v19), v20_(v20), v21_(v21), v22_(v22), v23_(v23), v24_(v24), v25_(v25), v26_(v26) {} template operator ParamGenerator() const { const T array[] = {v1_, v2_, v3_, v4_, v5_, v6_, v7_, v8_, v9_, v10_, v11_, v12_, v13_, v14_, v15_, v16_, v17_, v18_, v19_, v20_, v21_, v22_, v23_, v24_, v25_, v26_}; return ValuesIn(array); } private: // No implementation - assignment is unsupported. void operator=(const ValueArray26& other); const T1 v1_; const T2 v2_; const T3 v3_; const T4 v4_; const T5 v5_; const T6 v6_; const T7 v7_; const T8 v8_; const T9 v9_; const T10 v10_; const T11 v11_; const T12 v12_; const T13 v13_; const T14 v14_; const T15 v15_; const T16 v16_; const T17 v17_; const T18 v18_; const T19 v19_; const T20 v20_; const T21 v21_; const T22 v22_; const T23 v23_; const T24 v24_; const T25 v25_; const T26 v26_; }; template class ValueArray27 { public: ValueArray27(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, T26 v26, T27 v27) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9), v10_(v10), v11_(v11), v12_(v12), v13_(v13), v14_(v14), v15_(v15), v16_(v16), v17_(v17), v18_(v18), v19_(v19), v20_(v20), v21_(v21), v22_(v22), v23_(v23), v24_(v24), v25_(v25), v26_(v26), v27_(v27) {} template operator ParamGenerator() const { const T array[] = {v1_, v2_, v3_, v4_, v5_, v6_, v7_, v8_, v9_, v10_, v11_, v12_, v13_, v14_, v15_, v16_, v17_, v18_, v19_, v20_, v21_, v22_, v23_, v24_, v25_, v26_, v27_}; return ValuesIn(array); } private: // No implementation - assignment is unsupported. void operator=(const ValueArray27& other); const T1 v1_; const T2 v2_; const T3 v3_; const T4 v4_; const T5 v5_; const T6 v6_; const T7 v7_; const T8 v8_; const T9 v9_; const T10 v10_; const T11 v11_; const T12 v12_; const T13 v13_; const T14 v14_; const T15 v15_; const T16 v16_; const T17 v17_; const T18 v18_; const T19 v19_; const T20 v20_; const T21 v21_; const T22 v22_; const T23 v23_; const T24 v24_; const T25 v25_; const T26 v26_; const T27 v27_; }; template class ValueArray28 { public: ValueArray28(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, T26 v26, T27 v27, T28 v28) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9), v10_(v10), v11_(v11), v12_(v12), v13_(v13), v14_(v14), v15_(v15), v16_(v16), v17_(v17), v18_(v18), v19_(v19), v20_(v20), v21_(v21), v22_(v22), v23_(v23), v24_(v24), v25_(v25), v26_(v26), v27_(v27), v28_(v28) {} template operator ParamGenerator() const { const T array[] = {v1_, v2_, v3_, v4_, v5_, v6_, v7_, v8_, v9_, v10_, v11_, v12_, v13_, v14_, v15_, v16_, v17_, v18_, v19_, v20_, v21_, v22_, v23_, v24_, v25_, v26_, v27_, v28_}; return ValuesIn(array); } private: // No implementation - assignment is unsupported. void operator=(const ValueArray28& other); const T1 v1_; const T2 v2_; const T3 v3_; const T4 v4_; const T5 v5_; const T6 v6_; const T7 v7_; const T8 v8_; const T9 v9_; const T10 v10_; const T11 v11_; const T12 v12_; const T13 v13_; const T14 v14_; const T15 v15_; const T16 v16_; const T17 v17_; const T18 v18_; const T19 v19_; const T20 v20_; const T21 v21_; const T22 v22_; const T23 v23_; const T24 v24_; const T25 v25_; const T26 v26_; const T27 v27_; const T28 v28_; }; template class ValueArray29 { public: ValueArray29(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, T26 v26, T27 v27, T28 v28, T29 v29) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9), v10_(v10), v11_(v11), v12_(v12), v13_(v13), v14_(v14), v15_(v15), v16_(v16), v17_(v17), v18_(v18), v19_(v19), v20_(v20), v21_(v21), v22_(v22), v23_(v23), v24_(v24), v25_(v25), v26_(v26), v27_(v27), v28_(v28), v29_(v29) {} template operator ParamGenerator() const { const T array[] = {v1_, v2_, v3_, v4_, v5_, v6_, v7_, v8_, v9_, v10_, v11_, v12_, v13_, v14_, v15_, v16_, v17_, v18_, v19_, v20_, v21_, v22_, v23_, v24_, v25_, v26_, v27_, v28_, v29_}; return ValuesIn(array); } private: // No implementation - assignment is unsupported. void operator=(const ValueArray29& other); const T1 v1_; const T2 v2_; const T3 v3_; const T4 v4_; const T5 v5_; const T6 v6_; const T7 v7_; const T8 v8_; const T9 v9_; const T10 v10_; const T11 v11_; const T12 v12_; const T13 v13_; const T14 v14_; const T15 v15_; const T16 v16_; const T17 v17_; const T18 v18_; const T19 v19_; const T20 v20_; const T21 v21_; const T22 v22_; const T23 v23_; const T24 v24_; const T25 v25_; const T26 v26_; const T27 v27_; const T28 v28_; const T29 v29_; }; template class ValueArray30 { public: ValueArray30(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, T26 v26, T27 v27, T28 v28, T29 v29, T30 v30) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9), v10_(v10), v11_(v11), v12_(v12), v13_(v13), v14_(v14), v15_(v15), v16_(v16), v17_(v17), v18_(v18), v19_(v19), v20_(v20), v21_(v21), v22_(v22), v23_(v23), v24_(v24), v25_(v25), v26_(v26), v27_(v27), v28_(v28), v29_(v29), v30_(v30) {} template operator ParamGenerator() const { const T array[] = {v1_, v2_, v3_, v4_, v5_, v6_, v7_, v8_, v9_, v10_, v11_, v12_, v13_, v14_, v15_, v16_, v17_, v18_, v19_, v20_, v21_, v22_, v23_, v24_, v25_, v26_, v27_, v28_, v29_, v30_}; return ValuesIn(array); } private: // No implementation - assignment is unsupported. void operator=(const ValueArray30& other); const T1 v1_; const T2 v2_; const T3 v3_; const T4 v4_; const T5 v5_; const T6 v6_; const T7 v7_; const T8 v8_; const T9 v9_; const T10 v10_; const T11 v11_; const T12 v12_; const T13 v13_; const T14 v14_; const T15 v15_; const T16 v16_; const T17 v17_; const T18 v18_; const T19 v19_; const T20 v20_; const T21 v21_; const T22 v22_; const T23 v23_; const T24 v24_; const T25 v25_; const T26 v26_; const T27 v27_; const T28 v28_; const T29 v29_; const T30 v30_; }; template class ValueArray31 { public: ValueArray31(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9), v10_(v10), v11_(v11), v12_(v12), v13_(v13), v14_(v14), v15_(v15), v16_(v16), v17_(v17), v18_(v18), v19_(v19), v20_(v20), v21_(v21), v22_(v22), v23_(v23), v24_(v24), v25_(v25), v26_(v26), v27_(v27), v28_(v28), v29_(v29), v30_(v30), v31_(v31) {} template operator ParamGenerator() const { const T array[] = {v1_, v2_, v3_, v4_, v5_, v6_, v7_, v8_, v9_, v10_, v11_, v12_, v13_, v14_, v15_, v16_, v17_, v18_, v19_, v20_, v21_, v22_, v23_, v24_, v25_, v26_, v27_, v28_, v29_, v30_, v31_}; return ValuesIn(array); } private: // No implementation - assignment is unsupported. void operator=(const ValueArray31& other); const T1 v1_; const T2 v2_; const T3 v3_; const T4 v4_; const T5 v5_; const T6 v6_; const T7 v7_; const T8 v8_; const T9 v9_; const T10 v10_; const T11 v11_; const T12 v12_; const T13 v13_; const T14 v14_; const T15 v15_; const T16 v16_; const T17 v17_; const T18 v18_; const T19 v19_; const T20 v20_; const T21 v21_; const T22 v22_; const T23 v23_; const T24 v24_; const T25 v25_; const T26 v26_; const T27 v27_; const T28 v28_; const T29 v29_; const T30 v30_; const T31 v31_; }; template class ValueArray32 { public: ValueArray32(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9), v10_(v10), v11_(v11), v12_(v12), v13_(v13), v14_(v14), v15_(v15), v16_(v16), v17_(v17), v18_(v18), v19_(v19), v20_(v20), v21_(v21), v22_(v22), v23_(v23), v24_(v24), v25_(v25), v26_(v26), v27_(v27), v28_(v28), v29_(v29), v30_(v30), v31_(v31), v32_(v32) {} template operator ParamGenerator() const { const T array[] = {v1_, v2_, v3_, v4_, v5_, v6_, v7_, v8_, v9_, v10_, v11_, v12_, v13_, v14_, v15_, v16_, v17_, v18_, v19_, v20_, v21_, v22_, v23_, v24_, v25_, v26_, v27_, v28_, v29_, v30_, v31_, v32_}; return ValuesIn(array); } private: // No implementation - assignment is unsupported. void operator=(const ValueArray32& other); const T1 v1_; const T2 v2_; const T3 v3_; const T4 v4_; const T5 v5_; const T6 v6_; const T7 v7_; const T8 v8_; const T9 v9_; const T10 v10_; const T11 v11_; const T12 v12_; const T13 v13_; const T14 v14_; const T15 v15_; const T16 v16_; const T17 v17_; const T18 v18_; const T19 v19_; const T20 v20_; const T21 v21_; const T22 v22_; const T23 v23_; const T24 v24_; const T25 v25_; const T26 v26_; const T27 v27_; const T28 v28_; const T29 v29_; const T30 v30_; const T31 v31_; const T32 v32_; }; template class ValueArray33 { public: ValueArray33(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9), v10_(v10), v11_(v11), v12_(v12), v13_(v13), v14_(v14), v15_(v15), v16_(v16), v17_(v17), v18_(v18), v19_(v19), v20_(v20), v21_(v21), v22_(v22), v23_(v23), v24_(v24), v25_(v25), v26_(v26), v27_(v27), v28_(v28), v29_(v29), v30_(v30), v31_(v31), v32_(v32), v33_(v33) {} template operator ParamGenerator() const { const T array[] = {v1_, v2_, v3_, v4_, v5_, v6_, v7_, v8_, v9_, v10_, v11_, v12_, v13_, v14_, v15_, v16_, v17_, v18_, v19_, v20_, v21_, v22_, v23_, v24_, v25_, v26_, v27_, v28_, v29_, v30_, v31_, v32_, v33_}; return ValuesIn(array); } private: // No implementation - assignment is unsupported. void operator=(const ValueArray33& other); const T1 v1_; const T2 v2_; const T3 v3_; const T4 v4_; const T5 v5_; const T6 v6_; const T7 v7_; const T8 v8_; const T9 v9_; const T10 v10_; const T11 v11_; const T12 v12_; const T13 v13_; const T14 v14_; const T15 v15_; const T16 v16_; const T17 v17_; const T18 v18_; const T19 v19_; const T20 v20_; const T21 v21_; const T22 v22_; const T23 v23_; const T24 v24_; const T25 v25_; const T26 v26_; const T27 v27_; const T28 v28_; const T29 v29_; const T30 v30_; const T31 v31_; const T32 v32_; const T33 v33_; }; template class ValueArray34 { public: ValueArray34(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, T34 v34) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9), v10_(v10), v11_(v11), v12_(v12), v13_(v13), v14_(v14), v15_(v15), v16_(v16), v17_(v17), v18_(v18), v19_(v19), v20_(v20), v21_(v21), v22_(v22), v23_(v23), v24_(v24), v25_(v25), v26_(v26), v27_(v27), v28_(v28), v29_(v29), v30_(v30), v31_(v31), v32_(v32), v33_(v33), v34_(v34) {} template operator ParamGenerator() const { const T array[] = {v1_, v2_, v3_, v4_, v5_, v6_, v7_, v8_, v9_, v10_, v11_, v12_, v13_, v14_, v15_, v16_, v17_, v18_, v19_, v20_, v21_, v22_, v23_, v24_, v25_, v26_, v27_, v28_, v29_, v30_, v31_, v32_, v33_, v34_}; return ValuesIn(array); } private: // No implementation - assignment is unsupported. void operator=(const ValueArray34& other); const T1 v1_; const T2 v2_; const T3 v3_; const T4 v4_; const T5 v5_; const T6 v6_; const T7 v7_; const T8 v8_; const T9 v9_; const T10 v10_; const T11 v11_; const T12 v12_; const T13 v13_; const T14 v14_; const T15 v15_; const T16 v16_; const T17 v17_; const T18 v18_; const T19 v19_; const T20 v20_; const T21 v21_; const T22 v22_; const T23 v23_; const T24 v24_; const T25 v25_; const T26 v26_; const T27 v27_; const T28 v28_; const T29 v29_; const T30 v30_; const T31 v31_; const T32 v32_; const T33 v33_; const T34 v34_; }; template class ValueArray35 { public: ValueArray35(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, T34 v34, T35 v35) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9), v10_(v10), v11_(v11), v12_(v12), v13_(v13), v14_(v14), v15_(v15), v16_(v16), v17_(v17), v18_(v18), v19_(v19), v20_(v20), v21_(v21), v22_(v22), v23_(v23), v24_(v24), v25_(v25), v26_(v26), v27_(v27), v28_(v28), v29_(v29), v30_(v30), v31_(v31), v32_(v32), v33_(v33), v34_(v34), v35_(v35) {} template operator ParamGenerator() const { const T array[] = {v1_, v2_, v3_, v4_, v5_, v6_, v7_, v8_, v9_, v10_, v11_, v12_, v13_, v14_, v15_, v16_, v17_, v18_, v19_, v20_, v21_, v22_, v23_, v24_, v25_, v26_, v27_, v28_, v29_, v30_, v31_, v32_, v33_, v34_, v35_}; return ValuesIn(array); } private: // No implementation - assignment is unsupported. void operator=(const ValueArray35& other); const T1 v1_; const T2 v2_; const T3 v3_; const T4 v4_; const T5 v5_; const T6 v6_; const T7 v7_; const T8 v8_; const T9 v9_; const T10 v10_; const T11 v11_; const T12 v12_; const T13 v13_; const T14 v14_; const T15 v15_; const T16 v16_; const T17 v17_; const T18 v18_; const T19 v19_; const T20 v20_; const T21 v21_; const T22 v22_; const T23 v23_; const T24 v24_; const T25 v25_; const T26 v26_; const T27 v27_; const T28 v28_; const T29 v29_; const T30 v30_; const T31 v31_; const T32 v32_; const T33 v33_; const T34 v34_; const T35 v35_; }; template class ValueArray36 { public: ValueArray36(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, T34 v34, T35 v35, T36 v36) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9), v10_(v10), v11_(v11), v12_(v12), v13_(v13), v14_(v14), v15_(v15), v16_(v16), v17_(v17), v18_(v18), v19_(v19), v20_(v20), v21_(v21), v22_(v22), v23_(v23), v24_(v24), v25_(v25), v26_(v26), v27_(v27), v28_(v28), v29_(v29), v30_(v30), v31_(v31), v32_(v32), v33_(v33), v34_(v34), v35_(v35), v36_(v36) {} template operator ParamGenerator() const { const T array[] = {v1_, v2_, v3_, v4_, v5_, v6_, v7_, v8_, v9_, v10_, v11_, v12_, v13_, v14_, v15_, v16_, v17_, v18_, v19_, v20_, v21_, v22_, v23_, v24_, v25_, v26_, v27_, v28_, v29_, v30_, v31_, v32_, v33_, v34_, v35_, v36_}; return ValuesIn(array); } private: // No implementation - assignment is unsupported. void operator=(const ValueArray36& other); const T1 v1_; const T2 v2_; const T3 v3_; const T4 v4_; const T5 v5_; const T6 v6_; const T7 v7_; const T8 v8_; const T9 v9_; const T10 v10_; const T11 v11_; const T12 v12_; const T13 v13_; const T14 v14_; const T15 v15_; const T16 v16_; const T17 v17_; const T18 v18_; const T19 v19_; const T20 v20_; const T21 v21_; const T22 v22_; const T23 v23_; const T24 v24_; const T25 v25_; const T26 v26_; const T27 v27_; const T28 v28_; const T29 v29_; const T30 v30_; const T31 v31_; const T32 v32_; const T33 v33_; const T34 v34_; const T35 v35_; const T36 v36_; }; template class ValueArray37 { public: ValueArray37(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, T34 v34, T35 v35, T36 v36, T37 v37) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9), v10_(v10), v11_(v11), v12_(v12), v13_(v13), v14_(v14), v15_(v15), v16_(v16), v17_(v17), v18_(v18), v19_(v19), v20_(v20), v21_(v21), v22_(v22), v23_(v23), v24_(v24), v25_(v25), v26_(v26), v27_(v27), v28_(v28), v29_(v29), v30_(v30), v31_(v31), v32_(v32), v33_(v33), v34_(v34), v35_(v35), v36_(v36), v37_(v37) {} template operator ParamGenerator() const { const T array[] = {v1_, v2_, v3_, v4_, v5_, v6_, v7_, v8_, v9_, v10_, v11_, v12_, v13_, v14_, v15_, v16_, v17_, v18_, v19_, v20_, v21_, v22_, v23_, v24_, v25_, v26_, v27_, v28_, v29_, v30_, v31_, v32_, v33_, v34_, v35_, v36_, v37_}; return ValuesIn(array); } private: // No implementation - assignment is unsupported. void operator=(const ValueArray37& other); const T1 v1_; const T2 v2_; const T3 v3_; const T4 v4_; const T5 v5_; const T6 v6_; const T7 v7_; const T8 v8_; const T9 v9_; const T10 v10_; const T11 v11_; const T12 v12_; const T13 v13_; const T14 v14_; const T15 v15_; const T16 v16_; const T17 v17_; const T18 v18_; const T19 v19_; const T20 v20_; const T21 v21_; const T22 v22_; const T23 v23_; const T24 v24_; const T25 v25_; const T26 v26_; const T27 v27_; const T28 v28_; const T29 v29_; const T30 v30_; const T31 v31_; const T32 v32_; const T33 v33_; const T34 v34_; const T35 v35_; const T36 v36_; const T37 v37_; }; template class ValueArray38 { public: ValueArray38(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, T34 v34, T35 v35, T36 v36, T37 v37, T38 v38) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9), v10_(v10), v11_(v11), v12_(v12), v13_(v13), v14_(v14), v15_(v15), v16_(v16), v17_(v17), v18_(v18), v19_(v19), v20_(v20), v21_(v21), v22_(v22), v23_(v23), v24_(v24), v25_(v25), v26_(v26), v27_(v27), v28_(v28), v29_(v29), v30_(v30), v31_(v31), v32_(v32), v33_(v33), v34_(v34), v35_(v35), v36_(v36), v37_(v37), v38_(v38) {} template operator ParamGenerator() const { const T array[] = {v1_, v2_, v3_, v4_, v5_, v6_, v7_, v8_, v9_, v10_, v11_, v12_, v13_, v14_, v15_, v16_, v17_, v18_, v19_, v20_, v21_, v22_, v23_, v24_, v25_, v26_, v27_, v28_, v29_, v30_, v31_, v32_, v33_, v34_, v35_, v36_, v37_, v38_}; return ValuesIn(array); } private: // No implementation - assignment is unsupported. void operator=(const ValueArray38& other); const T1 v1_; const T2 v2_; const T3 v3_; const T4 v4_; const T5 v5_; const T6 v6_; const T7 v7_; const T8 v8_; const T9 v9_; const T10 v10_; const T11 v11_; const T12 v12_; const T13 v13_; const T14 v14_; const T15 v15_; const T16 v16_; const T17 v17_; const T18 v18_; const T19 v19_; const T20 v20_; const T21 v21_; const T22 v22_; const T23 v23_; const T24 v24_; const T25 v25_; const T26 v26_; const T27 v27_; const T28 v28_; const T29 v29_; const T30 v30_; const T31 v31_; const T32 v32_; const T33 v33_; const T34 v34_; const T35 v35_; const T36 v36_; const T37 v37_; const T38 v38_; }; template class ValueArray39 { public: ValueArray39(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, T34 v34, T35 v35, T36 v36, T37 v37, T38 v38, T39 v39) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9), v10_(v10), v11_(v11), v12_(v12), v13_(v13), v14_(v14), v15_(v15), v16_(v16), v17_(v17), v18_(v18), v19_(v19), v20_(v20), v21_(v21), v22_(v22), v23_(v23), v24_(v24), v25_(v25), v26_(v26), v27_(v27), v28_(v28), v29_(v29), v30_(v30), v31_(v31), v32_(v32), v33_(v33), v34_(v34), v35_(v35), v36_(v36), v37_(v37), v38_(v38), v39_(v39) {} template operator ParamGenerator() const { const T array[] = {v1_, v2_, v3_, v4_, v5_, v6_, v7_, v8_, v9_, v10_, v11_, v12_, v13_, v14_, v15_, v16_, v17_, v18_, v19_, v20_, v21_, v22_, v23_, v24_, v25_, v26_, v27_, v28_, v29_, v30_, v31_, v32_, v33_, v34_, v35_, v36_, v37_, v38_, v39_}; return ValuesIn(array); } private: // No implementation - assignment is unsupported. void operator=(const ValueArray39& other); const T1 v1_; const T2 v2_; const T3 v3_; const T4 v4_; const T5 v5_; const T6 v6_; const T7 v7_; const T8 v8_; const T9 v9_; const T10 v10_; const T11 v11_; const T12 v12_; const T13 v13_; const T14 v14_; const T15 v15_; const T16 v16_; const T17 v17_; const T18 v18_; const T19 v19_; const T20 v20_; const T21 v21_; const T22 v22_; const T23 v23_; const T24 v24_; const T25 v25_; const T26 v26_; const T27 v27_; const T28 v28_; const T29 v29_; const T30 v30_; const T31 v31_; const T32 v32_; const T33 v33_; const T34 v34_; const T35 v35_; const T36 v36_; const T37 v37_; const T38 v38_; const T39 v39_; }; template class ValueArray40 { public: ValueArray40(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, T34 v34, T35 v35, T36 v36, T37 v37, T38 v38, T39 v39, T40 v40) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9), v10_(v10), v11_(v11), v12_(v12), v13_(v13), v14_(v14), v15_(v15), v16_(v16), v17_(v17), v18_(v18), v19_(v19), v20_(v20), v21_(v21), v22_(v22), v23_(v23), v24_(v24), v25_(v25), v26_(v26), v27_(v27), v28_(v28), v29_(v29), v30_(v30), v31_(v31), v32_(v32), v33_(v33), v34_(v34), v35_(v35), v36_(v36), v37_(v37), v38_(v38), v39_(v39), v40_(v40) {} template operator ParamGenerator() const { const T array[] = {v1_, v2_, v3_, v4_, v5_, v6_, v7_, v8_, v9_, v10_, v11_, v12_, v13_, v14_, v15_, v16_, v17_, v18_, v19_, v20_, v21_, v22_, v23_, v24_, v25_, v26_, v27_, v28_, v29_, v30_, v31_, v32_, v33_, v34_, v35_, v36_, v37_, v38_, v39_, v40_}; return ValuesIn(array); } private: // No implementation - assignment is unsupported. void operator=(const ValueArray40& other); const T1 v1_; const T2 v2_; const T3 v3_; const T4 v4_; const T5 v5_; const T6 v6_; const T7 v7_; const T8 v8_; const T9 v9_; const T10 v10_; const T11 v11_; const T12 v12_; const T13 v13_; const T14 v14_; const T15 v15_; const T16 v16_; const T17 v17_; const T18 v18_; const T19 v19_; const T20 v20_; const T21 v21_; const T22 v22_; const T23 v23_; const T24 v24_; const T25 v25_; const T26 v26_; const T27 v27_; const T28 v28_; const T29 v29_; const T30 v30_; const T31 v31_; const T32 v32_; const T33 v33_; const T34 v34_; const T35 v35_; const T36 v36_; const T37 v37_; const T38 v38_; const T39 v39_; const T40 v40_; }; template class ValueArray41 { public: ValueArray41(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, T34 v34, T35 v35, T36 v36, T37 v37, T38 v38, T39 v39, T40 v40, T41 v41) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9), v10_(v10), v11_(v11), v12_(v12), v13_(v13), v14_(v14), v15_(v15), v16_(v16), v17_(v17), v18_(v18), v19_(v19), v20_(v20), v21_(v21), v22_(v22), v23_(v23), v24_(v24), v25_(v25), v26_(v26), v27_(v27), v28_(v28), v29_(v29), v30_(v30), v31_(v31), v32_(v32), v33_(v33), v34_(v34), v35_(v35), v36_(v36), v37_(v37), v38_(v38), v39_(v39), v40_(v40), v41_(v41) {} template operator ParamGenerator() const { const T array[] = {v1_, v2_, v3_, v4_, v5_, v6_, v7_, v8_, v9_, v10_, v11_, v12_, v13_, v14_, v15_, v16_, v17_, v18_, v19_, v20_, v21_, v22_, v23_, v24_, v25_, v26_, v27_, v28_, v29_, v30_, v31_, v32_, v33_, v34_, v35_, v36_, v37_, v38_, v39_, v40_, v41_}; return ValuesIn(array); } private: // No implementation - assignment is unsupported. void operator=(const ValueArray41& other); const T1 v1_; const T2 v2_; const T3 v3_; const T4 v4_; const T5 v5_; const T6 v6_; const T7 v7_; const T8 v8_; const T9 v9_; const T10 v10_; const T11 v11_; const T12 v12_; const T13 v13_; const T14 v14_; const T15 v15_; const T16 v16_; const T17 v17_; const T18 v18_; const T19 v19_; const T20 v20_; const T21 v21_; const T22 v22_; const T23 v23_; const T24 v24_; const T25 v25_; const T26 v26_; const T27 v27_; const T28 v28_; const T29 v29_; const T30 v30_; const T31 v31_; const T32 v32_; const T33 v33_; const T34 v34_; const T35 v35_; const T36 v36_; const T37 v37_; const T38 v38_; const T39 v39_; const T40 v40_; const T41 v41_; }; template class ValueArray42 { public: ValueArray42(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, T34 v34, T35 v35, T36 v36, T37 v37, T38 v38, T39 v39, T40 v40, T41 v41, T42 v42) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9), v10_(v10), v11_(v11), v12_(v12), v13_(v13), v14_(v14), v15_(v15), v16_(v16), v17_(v17), v18_(v18), v19_(v19), v20_(v20), v21_(v21), v22_(v22), v23_(v23), v24_(v24), v25_(v25), v26_(v26), v27_(v27), v28_(v28), v29_(v29), v30_(v30), v31_(v31), v32_(v32), v33_(v33), v34_(v34), v35_(v35), v36_(v36), v37_(v37), v38_(v38), v39_(v39), v40_(v40), v41_(v41), v42_(v42) {} template operator ParamGenerator() const { const T array[] = {v1_, v2_, v3_, v4_, v5_, v6_, v7_, v8_, v9_, v10_, v11_, v12_, v13_, v14_, v15_, v16_, v17_, v18_, v19_, v20_, v21_, v22_, v23_, v24_, v25_, v26_, v27_, v28_, v29_, v30_, v31_, v32_, v33_, v34_, v35_, v36_, v37_, v38_, v39_, v40_, v41_, v42_}; return ValuesIn(array); } private: // No implementation - assignment is unsupported. void operator=(const ValueArray42& other); const T1 v1_; const T2 v2_; const T3 v3_; const T4 v4_; const T5 v5_; const T6 v6_; const T7 v7_; const T8 v8_; const T9 v9_; const T10 v10_; const T11 v11_; const T12 v12_; const T13 v13_; const T14 v14_; const T15 v15_; const T16 v16_; const T17 v17_; const T18 v18_; const T19 v19_; const T20 v20_; const T21 v21_; const T22 v22_; const T23 v23_; const T24 v24_; const T25 v25_; const T26 v26_; const T27 v27_; const T28 v28_; const T29 v29_; const T30 v30_; const T31 v31_; const T32 v32_; const T33 v33_; const T34 v34_; const T35 v35_; const T36 v36_; const T37 v37_; const T38 v38_; const T39 v39_; const T40 v40_; const T41 v41_; const T42 v42_; }; template class ValueArray43 { public: ValueArray43(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, T34 v34, T35 v35, T36 v36, T37 v37, T38 v38, T39 v39, T40 v40, T41 v41, T42 v42, T43 v43) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9), v10_(v10), v11_(v11), v12_(v12), v13_(v13), v14_(v14), v15_(v15), v16_(v16), v17_(v17), v18_(v18), v19_(v19), v20_(v20), v21_(v21), v22_(v22), v23_(v23), v24_(v24), v25_(v25), v26_(v26), v27_(v27), v28_(v28), v29_(v29), v30_(v30), v31_(v31), v32_(v32), v33_(v33), v34_(v34), v35_(v35), v36_(v36), v37_(v37), v38_(v38), v39_(v39), v40_(v40), v41_(v41), v42_(v42), v43_(v43) {} template operator ParamGenerator() const { const T array[] = {v1_, v2_, v3_, v4_, v5_, v6_, v7_, v8_, v9_, v10_, v11_, v12_, v13_, v14_, v15_, v16_, v17_, v18_, v19_, v20_, v21_, v22_, v23_, v24_, v25_, v26_, v27_, v28_, v29_, v30_, v31_, v32_, v33_, v34_, v35_, v36_, v37_, v38_, v39_, v40_, v41_, v42_, v43_}; return ValuesIn(array); } private: // No implementation - assignment is unsupported. void operator=(const ValueArray43& other); const T1 v1_; const T2 v2_; const T3 v3_; const T4 v4_; const T5 v5_; const T6 v6_; const T7 v7_; const T8 v8_; const T9 v9_; const T10 v10_; const T11 v11_; const T12 v12_; const T13 v13_; const T14 v14_; const T15 v15_; const T16 v16_; const T17 v17_; const T18 v18_; const T19 v19_; const T20 v20_; const T21 v21_; const T22 v22_; const T23 v23_; const T24 v24_; const T25 v25_; const T26 v26_; const T27 v27_; const T28 v28_; const T29 v29_; const T30 v30_; const T31 v31_; const T32 v32_; const T33 v33_; const T34 v34_; const T35 v35_; const T36 v36_; const T37 v37_; const T38 v38_; const T39 v39_; const T40 v40_; const T41 v41_; const T42 v42_; const T43 v43_; }; template class ValueArray44 { public: ValueArray44(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, T34 v34, T35 v35, T36 v36, T37 v37, T38 v38, T39 v39, T40 v40, T41 v41, T42 v42, T43 v43, T44 v44) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9), v10_(v10), v11_(v11), v12_(v12), v13_(v13), v14_(v14), v15_(v15), v16_(v16), v17_(v17), v18_(v18), v19_(v19), v20_(v20), v21_(v21), v22_(v22), v23_(v23), v24_(v24), v25_(v25), v26_(v26), v27_(v27), v28_(v28), v29_(v29), v30_(v30), v31_(v31), v32_(v32), v33_(v33), v34_(v34), v35_(v35), v36_(v36), v37_(v37), v38_(v38), v39_(v39), v40_(v40), v41_(v41), v42_(v42), v43_(v43), v44_(v44) {} template operator ParamGenerator() const { const T array[] = {v1_, v2_, v3_, v4_, v5_, v6_, v7_, v8_, v9_, v10_, v11_, v12_, v13_, v14_, v15_, v16_, v17_, v18_, v19_, v20_, v21_, v22_, v23_, v24_, v25_, v26_, v27_, v28_, v29_, v30_, v31_, v32_, v33_, v34_, v35_, v36_, v37_, v38_, v39_, v40_, v41_, v42_, v43_, v44_}; return ValuesIn(array); } private: // No implementation - assignment is unsupported. void operator=(const ValueArray44& other); const T1 v1_; const T2 v2_; const T3 v3_; const T4 v4_; const T5 v5_; const T6 v6_; const T7 v7_; const T8 v8_; const T9 v9_; const T10 v10_; const T11 v11_; const T12 v12_; const T13 v13_; const T14 v14_; const T15 v15_; const T16 v16_; const T17 v17_; const T18 v18_; const T19 v19_; const T20 v20_; const T21 v21_; const T22 v22_; const T23 v23_; const T24 v24_; const T25 v25_; const T26 v26_; const T27 v27_; const T28 v28_; const T29 v29_; const T30 v30_; const T31 v31_; const T32 v32_; const T33 v33_; const T34 v34_; const T35 v35_; const T36 v36_; const T37 v37_; const T38 v38_; const T39 v39_; const T40 v40_; const T41 v41_; const T42 v42_; const T43 v43_; const T44 v44_; }; template class ValueArray45 { public: ValueArray45(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, T34 v34, T35 v35, T36 v36, T37 v37, T38 v38, T39 v39, T40 v40, T41 v41, T42 v42, T43 v43, T44 v44, T45 v45) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9), v10_(v10), v11_(v11), v12_(v12), v13_(v13), v14_(v14), v15_(v15), v16_(v16), v17_(v17), v18_(v18), v19_(v19), v20_(v20), v21_(v21), v22_(v22), v23_(v23), v24_(v24), v25_(v25), v26_(v26), v27_(v27), v28_(v28), v29_(v29), v30_(v30), v31_(v31), v32_(v32), v33_(v33), v34_(v34), v35_(v35), v36_(v36), v37_(v37), v38_(v38), v39_(v39), v40_(v40), v41_(v41), v42_(v42), v43_(v43), v44_(v44), v45_(v45) {} template operator ParamGenerator() const { const T array[] = {v1_, v2_, v3_, v4_, v5_, v6_, v7_, v8_, v9_, v10_, v11_, v12_, v13_, v14_, v15_, v16_, v17_, v18_, v19_, v20_, v21_, v22_, v23_, v24_, v25_, v26_, v27_, v28_, v29_, v30_, v31_, v32_, v33_, v34_, v35_, v36_, v37_, v38_, v39_, v40_, v41_, v42_, v43_, v44_, v45_}; return ValuesIn(array); } private: // No implementation - assignment is unsupported. void operator=(const ValueArray45& other); const T1 v1_; const T2 v2_; const T3 v3_; const T4 v4_; const T5 v5_; const T6 v6_; const T7 v7_; const T8 v8_; const T9 v9_; const T10 v10_; const T11 v11_; const T12 v12_; const T13 v13_; const T14 v14_; const T15 v15_; const T16 v16_; const T17 v17_; const T18 v18_; const T19 v19_; const T20 v20_; const T21 v21_; const T22 v22_; const T23 v23_; const T24 v24_; const T25 v25_; const T26 v26_; const T27 v27_; const T28 v28_; const T29 v29_; const T30 v30_; const T31 v31_; const T32 v32_; const T33 v33_; const T34 v34_; const T35 v35_; const T36 v36_; const T37 v37_; const T38 v38_; const T39 v39_; const T40 v40_; const T41 v41_; const T42 v42_; const T43 v43_; const T44 v44_; const T45 v45_; }; template class ValueArray46 { public: ValueArray46(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, T34 v34, T35 v35, T36 v36, T37 v37, T38 v38, T39 v39, T40 v40, T41 v41, T42 v42, T43 v43, T44 v44, T45 v45, T46 v46) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9), v10_(v10), v11_(v11), v12_(v12), v13_(v13), v14_(v14), v15_(v15), v16_(v16), v17_(v17), v18_(v18), v19_(v19), v20_(v20), v21_(v21), v22_(v22), v23_(v23), v24_(v24), v25_(v25), v26_(v26), v27_(v27), v28_(v28), v29_(v29), v30_(v30), v31_(v31), v32_(v32), v33_(v33), v34_(v34), v35_(v35), v36_(v36), v37_(v37), v38_(v38), v39_(v39), v40_(v40), v41_(v41), v42_(v42), v43_(v43), v44_(v44), v45_(v45), v46_(v46) {} template operator ParamGenerator() const { const T array[] = {v1_, v2_, v3_, v4_, v5_, v6_, v7_, v8_, v9_, v10_, v11_, v12_, v13_, v14_, v15_, v16_, v17_, v18_, v19_, v20_, v21_, v22_, v23_, v24_, v25_, v26_, v27_, v28_, v29_, v30_, v31_, v32_, v33_, v34_, v35_, v36_, v37_, v38_, v39_, v40_, v41_, v42_, v43_, v44_, v45_, v46_}; return ValuesIn(array); } private: // No implementation - assignment is unsupported. void operator=(const ValueArray46& other); const T1 v1_; const T2 v2_; const T3 v3_; const T4 v4_; const T5 v5_; const T6 v6_; const T7 v7_; const T8 v8_; const T9 v9_; const T10 v10_; const T11 v11_; const T12 v12_; const T13 v13_; const T14 v14_; const T15 v15_; const T16 v16_; const T17 v17_; const T18 v18_; const T19 v19_; const T20 v20_; const T21 v21_; const T22 v22_; const T23 v23_; const T24 v24_; const T25 v25_; const T26 v26_; const T27 v27_; const T28 v28_; const T29 v29_; const T30 v30_; const T31 v31_; const T32 v32_; const T33 v33_; const T34 v34_; const T35 v35_; const T36 v36_; const T37 v37_; const T38 v38_; const T39 v39_; const T40 v40_; const T41 v41_; const T42 v42_; const T43 v43_; const T44 v44_; const T45 v45_; const T46 v46_; }; template class ValueArray47 { public: ValueArray47(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, T34 v34, T35 v35, T36 v36, T37 v37, T38 v38, T39 v39, T40 v40, T41 v41, T42 v42, T43 v43, T44 v44, T45 v45, T46 v46, T47 v47) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9), v10_(v10), v11_(v11), v12_(v12), v13_(v13), v14_(v14), v15_(v15), v16_(v16), v17_(v17), v18_(v18), v19_(v19), v20_(v20), v21_(v21), v22_(v22), v23_(v23), v24_(v24), v25_(v25), v26_(v26), v27_(v27), v28_(v28), v29_(v29), v30_(v30), v31_(v31), v32_(v32), v33_(v33), v34_(v34), v35_(v35), v36_(v36), v37_(v37), v38_(v38), v39_(v39), v40_(v40), v41_(v41), v42_(v42), v43_(v43), v44_(v44), v45_(v45), v46_(v46), v47_(v47) {} template operator ParamGenerator() const { const T array[] = {v1_, v2_, v3_, v4_, v5_, v6_, v7_, v8_, v9_, v10_, v11_, v12_, v13_, v14_, v15_, v16_, v17_, v18_, v19_, v20_, v21_, v22_, v23_, v24_, v25_, v26_, v27_, v28_, v29_, v30_, v31_, v32_, v33_, v34_, v35_, v36_, v37_, v38_, v39_, v40_, v41_, v42_, v43_, v44_, v45_, v46_, v47_}; return ValuesIn(array); } private: // No implementation - assignment is unsupported. void operator=(const ValueArray47& other); const T1 v1_; const T2 v2_; const T3 v3_; const T4 v4_; const T5 v5_; const T6 v6_; const T7 v7_; const T8 v8_; const T9 v9_; const T10 v10_; const T11 v11_; const T12 v12_; const T13 v13_; const T14 v14_; const T15 v15_; const T16 v16_; const T17 v17_; const T18 v18_; const T19 v19_; const T20 v20_; const T21 v21_; const T22 v22_; const T23 v23_; const T24 v24_; const T25 v25_; const T26 v26_; const T27 v27_; const T28 v28_; const T29 v29_; const T30 v30_; const T31 v31_; const T32 v32_; const T33 v33_; const T34 v34_; const T35 v35_; const T36 v36_; const T37 v37_; const T38 v38_; const T39 v39_; const T40 v40_; const T41 v41_; const T42 v42_; const T43 v43_; const T44 v44_; const T45 v45_; const T46 v46_; const T47 v47_; }; template class ValueArray48 { public: ValueArray48(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, T34 v34, T35 v35, T36 v36, T37 v37, T38 v38, T39 v39, T40 v40, T41 v41, T42 v42, T43 v43, T44 v44, T45 v45, T46 v46, T47 v47, T48 v48) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9), v10_(v10), v11_(v11), v12_(v12), v13_(v13), v14_(v14), v15_(v15), v16_(v16), v17_(v17), v18_(v18), v19_(v19), v20_(v20), v21_(v21), v22_(v22), v23_(v23), v24_(v24), v25_(v25), v26_(v26), v27_(v27), v28_(v28), v29_(v29), v30_(v30), v31_(v31), v32_(v32), v33_(v33), v34_(v34), v35_(v35), v36_(v36), v37_(v37), v38_(v38), v39_(v39), v40_(v40), v41_(v41), v42_(v42), v43_(v43), v44_(v44), v45_(v45), v46_(v46), v47_(v47), v48_(v48) {} template operator ParamGenerator() const { const T array[] = {v1_, v2_, v3_, v4_, v5_, v6_, v7_, v8_, v9_, v10_, v11_, v12_, v13_, v14_, v15_, v16_, v17_, v18_, v19_, v20_, v21_, v22_, v23_, v24_, v25_, v26_, v27_, v28_, v29_, v30_, v31_, v32_, v33_, v34_, v35_, v36_, v37_, v38_, v39_, v40_, v41_, v42_, v43_, v44_, v45_, v46_, v47_, v48_}; return ValuesIn(array); } private: // No implementation - assignment is unsupported. void operator=(const ValueArray48& other); const T1 v1_; const T2 v2_; const T3 v3_; const T4 v4_; const T5 v5_; const T6 v6_; const T7 v7_; const T8 v8_; const T9 v9_; const T10 v10_; const T11 v11_; const T12 v12_; const T13 v13_; const T14 v14_; const T15 v15_; const T16 v16_; const T17 v17_; const T18 v18_; const T19 v19_; const T20 v20_; const T21 v21_; const T22 v22_; const T23 v23_; const T24 v24_; const T25 v25_; const T26 v26_; const T27 v27_; const T28 v28_; const T29 v29_; const T30 v30_; const T31 v31_; const T32 v32_; const T33 v33_; const T34 v34_; const T35 v35_; const T36 v36_; const T37 v37_; const T38 v38_; const T39 v39_; const T40 v40_; const T41 v41_; const T42 v42_; const T43 v43_; const T44 v44_; const T45 v45_; const T46 v46_; const T47 v47_; const T48 v48_; }; template class ValueArray49 { public: ValueArray49(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, T34 v34, T35 v35, T36 v36, T37 v37, T38 v38, T39 v39, T40 v40, T41 v41, T42 v42, T43 v43, T44 v44, T45 v45, T46 v46, T47 v47, T48 v48, T49 v49) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9), v10_(v10), v11_(v11), v12_(v12), v13_(v13), v14_(v14), v15_(v15), v16_(v16), v17_(v17), v18_(v18), v19_(v19), v20_(v20), v21_(v21), v22_(v22), v23_(v23), v24_(v24), v25_(v25), v26_(v26), v27_(v27), v28_(v28), v29_(v29), v30_(v30), v31_(v31), v32_(v32), v33_(v33), v34_(v34), v35_(v35), v36_(v36), v37_(v37), v38_(v38), v39_(v39), v40_(v40), v41_(v41), v42_(v42), v43_(v43), v44_(v44), v45_(v45), v46_(v46), v47_(v47), v48_(v48), v49_(v49) {} template operator ParamGenerator() const { const T array[] = {v1_, v2_, v3_, v4_, v5_, v6_, v7_, v8_, v9_, v10_, v11_, v12_, v13_, v14_, v15_, v16_, v17_, v18_, v19_, v20_, v21_, v22_, v23_, v24_, v25_, v26_, v27_, v28_, v29_, v30_, v31_, v32_, v33_, v34_, v35_, v36_, v37_, v38_, v39_, v40_, v41_, v42_, v43_, v44_, v45_, v46_, v47_, v48_, v49_}; return ValuesIn(array); } private: // No implementation - assignment is unsupported. void operator=(const ValueArray49& other); const T1 v1_; const T2 v2_; const T3 v3_; const T4 v4_; const T5 v5_; const T6 v6_; const T7 v7_; const T8 v8_; const T9 v9_; const T10 v10_; const T11 v11_; const T12 v12_; const T13 v13_; const T14 v14_; const T15 v15_; const T16 v16_; const T17 v17_; const T18 v18_; const T19 v19_; const T20 v20_; const T21 v21_; const T22 v22_; const T23 v23_; const T24 v24_; const T25 v25_; const T26 v26_; const T27 v27_; const T28 v28_; const T29 v29_; const T30 v30_; const T31 v31_; const T32 v32_; const T33 v33_; const T34 v34_; const T35 v35_; const T36 v36_; const T37 v37_; const T38 v38_; const T39 v39_; const T40 v40_; const T41 v41_; const T42 v42_; const T43 v43_; const T44 v44_; const T45 v45_; const T46 v46_; const T47 v47_; const T48 v48_; const T49 v49_; }; template class ValueArray50 { public: ValueArray50(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, T34 v34, T35 v35, T36 v36, T37 v37, T38 v38, T39 v39, T40 v40, T41 v41, T42 v42, T43 v43, T44 v44, T45 v45, T46 v46, T47 v47, T48 v48, T49 v49, T50 v50) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9), v10_(v10), v11_(v11), v12_(v12), v13_(v13), v14_(v14), v15_(v15), v16_(v16), v17_(v17), v18_(v18), v19_(v19), v20_(v20), v21_(v21), v22_(v22), v23_(v23), v24_(v24), v25_(v25), v26_(v26), v27_(v27), v28_(v28), v29_(v29), v30_(v30), v31_(v31), v32_(v32), v33_(v33), v34_(v34), v35_(v35), v36_(v36), v37_(v37), v38_(v38), v39_(v39), v40_(v40), v41_(v41), v42_(v42), v43_(v43), v44_(v44), v45_(v45), v46_(v46), v47_(v47), v48_(v48), v49_(v49), v50_(v50) {} template operator ParamGenerator() const { const T array[] = {v1_, v2_, v3_, v4_, v5_, v6_, v7_, v8_, v9_, v10_, v11_, v12_, v13_, v14_, v15_, v16_, v17_, v18_, v19_, v20_, v21_, v22_, v23_, v24_, v25_, v26_, v27_, v28_, v29_, v30_, v31_, v32_, v33_, v34_, v35_, v36_, v37_, v38_, v39_, v40_, v41_, v42_, v43_, v44_, v45_, v46_, v47_, v48_, v49_, v50_}; return ValuesIn(array); } private: // No implementation - assignment is unsupported. void operator=(const ValueArray50& other); const T1 v1_; const T2 v2_; const T3 v3_; const T4 v4_; const T5 v5_; const T6 v6_; const T7 v7_; const T8 v8_; const T9 v9_; const T10 v10_; const T11 v11_; const T12 v12_; const T13 v13_; const T14 v14_; const T15 v15_; const T16 v16_; const T17 v17_; const T18 v18_; const T19 v19_; const T20 v20_; const T21 v21_; const T22 v22_; const T23 v23_; const T24 v24_; const T25 v25_; const T26 v26_; const T27 v27_; const T28 v28_; const T29 v29_; const T30 v30_; const T31 v31_; const T32 v32_; const T33 v33_; const T34 v34_; const T35 v35_; const T36 v36_; const T37 v37_; const T38 v38_; const T39 v39_; const T40 v40_; const T41 v41_; const T42 v42_; const T43 v43_; const T44 v44_; const T45 v45_; const T46 v46_; const T47 v47_; const T48 v48_; const T49 v49_; const T50 v50_; }; # if GTEST_HAS_COMBINE // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE. // // Generates values from the Cartesian product of values produced // by the argument generators. // template class CartesianProductGenerator2 : public ParamGeneratorInterface< ::std::tr1::tuple > { public: typedef ::std::tr1::tuple ParamType; CartesianProductGenerator2(const ParamGenerator& g1, const ParamGenerator& g2) : g1_(g1), g2_(g2) {} virtual ~CartesianProductGenerator2() {} virtual ParamIteratorInterface* Begin() const { return new Iterator(this, g1_, g1_.begin(), g2_, g2_.begin()); } virtual ParamIteratorInterface* End() const { return new Iterator(this, g1_, g1_.end(), g2_, g2_.end()); } private: class Iterator : public ParamIteratorInterface { public: Iterator(const ParamGeneratorInterface* base, const ParamGenerator& g1, const typename ParamGenerator::iterator& current1, const ParamGenerator& g2, const typename ParamGenerator::iterator& current2) : base_(base), begin1_(g1.begin()), end1_(g1.end()), current1_(current1), begin2_(g2.begin()), end2_(g2.end()), current2_(current2) { ComputeCurrentValue(); } virtual ~Iterator() {} virtual const ParamGeneratorInterface* BaseGenerator() const { return base_; } // Advance should not be called on beyond-of-range iterators // so no component iterators must be beyond end of range, either. virtual void Advance() { assert(!AtEnd()); ++current2_; if (current2_ == end2_) { current2_ = begin2_; ++current1_; } ComputeCurrentValue(); } virtual ParamIteratorInterface* Clone() const { return new Iterator(*this); } virtual const ParamType* Current() const { return ¤t_value_; } virtual bool Equals(const ParamIteratorInterface& other) const { // Having the same base generator guarantees that the other // iterator is of the same type and we can downcast. GTEST_CHECK_(BaseGenerator() == other.BaseGenerator()) << "The program attempted to compare iterators " << "from different generators." << std::endl; const Iterator* typed_other = CheckedDowncastToActualType(&other); // We must report iterators equal if they both point beyond their // respective ranges. That can happen in a variety of fashions, // so we have to consult AtEnd(). return (AtEnd() && typed_other->AtEnd()) || ( current1_ == typed_other->current1_ && current2_ == typed_other->current2_); } private: Iterator(const Iterator& other) : base_(other.base_), begin1_(other.begin1_), end1_(other.end1_), current1_(other.current1_), begin2_(other.begin2_), end2_(other.end2_), current2_(other.current2_) { ComputeCurrentValue(); } void ComputeCurrentValue() { if (!AtEnd()) current_value_ = ParamType(*current1_, *current2_); } bool AtEnd() const { // We must report iterator past the end of the range when either of the // component iterators has reached the end of its range. return current1_ == end1_ || current2_ == end2_; } // No implementation - assignment is unsupported. void operator=(const Iterator& other); const ParamGeneratorInterface* const base_; // begin[i]_ and end[i]_ define the i-th range that Iterator traverses. // current[i]_ is the actual traversing iterator. const typename ParamGenerator::iterator begin1_; const typename ParamGenerator::iterator end1_; typename ParamGenerator::iterator current1_; const typename ParamGenerator::iterator begin2_; const typename ParamGenerator::iterator end2_; typename ParamGenerator::iterator current2_; ParamType current_value_; }; // class CartesianProductGenerator2::Iterator // No implementation - assignment is unsupported. void operator=(const CartesianProductGenerator2& other); const ParamGenerator g1_; const ParamGenerator g2_; }; // class CartesianProductGenerator2 template class CartesianProductGenerator3 : public ParamGeneratorInterface< ::std::tr1::tuple > { public: typedef ::std::tr1::tuple ParamType; CartesianProductGenerator3(const ParamGenerator& g1, const ParamGenerator& g2, const ParamGenerator& g3) : g1_(g1), g2_(g2), g3_(g3) {} virtual ~CartesianProductGenerator3() {} virtual ParamIteratorInterface* Begin() const { return new Iterator(this, g1_, g1_.begin(), g2_, g2_.begin(), g3_, g3_.begin()); } virtual ParamIteratorInterface* End() const { return new Iterator(this, g1_, g1_.end(), g2_, g2_.end(), g3_, g3_.end()); } private: class Iterator : public ParamIteratorInterface { public: Iterator(const ParamGeneratorInterface* base, const ParamGenerator& g1, const typename ParamGenerator::iterator& current1, const ParamGenerator& g2, const typename ParamGenerator::iterator& current2, const ParamGenerator& g3, const typename ParamGenerator::iterator& current3) : base_(base), begin1_(g1.begin()), end1_(g1.end()), current1_(current1), begin2_(g2.begin()), end2_(g2.end()), current2_(current2), begin3_(g3.begin()), end3_(g3.end()), current3_(current3) { ComputeCurrentValue(); } virtual ~Iterator() {} virtual const ParamGeneratorInterface* BaseGenerator() const { return base_; } // Advance should not be called on beyond-of-range iterators // so no component iterators must be beyond end of range, either. virtual void Advance() { assert(!AtEnd()); ++current3_; if (current3_ == end3_) { current3_ = begin3_; ++current2_; } if (current2_ == end2_) { current2_ = begin2_; ++current1_; } ComputeCurrentValue(); } virtual ParamIteratorInterface* Clone() const { return new Iterator(*this); } virtual const ParamType* Current() const { return ¤t_value_; } virtual bool Equals(const ParamIteratorInterface& other) const { // Having the same base generator guarantees that the other // iterator is of the same type and we can downcast. GTEST_CHECK_(BaseGenerator() == other.BaseGenerator()) << "The program attempted to compare iterators " << "from different generators." << std::endl; const Iterator* typed_other = CheckedDowncastToActualType(&other); // We must report iterators equal if they both point beyond their // respective ranges. That can happen in a variety of fashions, // so we have to consult AtEnd(). return (AtEnd() && typed_other->AtEnd()) || ( current1_ == typed_other->current1_ && current2_ == typed_other->current2_ && current3_ == typed_other->current3_); } private: Iterator(const Iterator& other) : base_(other.base_), begin1_(other.begin1_), end1_(other.end1_), current1_(other.current1_), begin2_(other.begin2_), end2_(other.end2_), current2_(other.current2_), begin3_(other.begin3_), end3_(other.end3_), current3_(other.current3_) { ComputeCurrentValue(); } void ComputeCurrentValue() { if (!AtEnd()) current_value_ = ParamType(*current1_, *current2_, *current3_); } bool AtEnd() const { // We must report iterator past the end of the range when either of the // component iterators has reached the end of its range. return current1_ == end1_ || current2_ == end2_ || current3_ == end3_; } // No implementation - assignment is unsupported. void operator=(const Iterator& other); const ParamGeneratorInterface* const base_; // begin[i]_ and end[i]_ define the i-th range that Iterator traverses. // current[i]_ is the actual traversing iterator. const typename ParamGenerator::iterator begin1_; const typename ParamGenerator::iterator end1_; typename ParamGenerator::iterator current1_; const typename ParamGenerator::iterator begin2_; const typename ParamGenerator::iterator end2_; typename ParamGenerator::iterator current2_; const typename ParamGenerator::iterator begin3_; const typename ParamGenerator::iterator end3_; typename ParamGenerator::iterator current3_; ParamType current_value_; }; // class CartesianProductGenerator3::Iterator // No implementation - assignment is unsupported. void operator=(const CartesianProductGenerator3& other); const ParamGenerator g1_; const ParamGenerator g2_; const ParamGenerator g3_; }; // class CartesianProductGenerator3 template class CartesianProductGenerator4 : public ParamGeneratorInterface< ::std::tr1::tuple > { public: typedef ::std::tr1::tuple ParamType; CartesianProductGenerator4(const ParamGenerator& g1, const ParamGenerator& g2, const ParamGenerator& g3, const ParamGenerator& g4) : g1_(g1), g2_(g2), g3_(g3), g4_(g4) {} virtual ~CartesianProductGenerator4() {} virtual ParamIteratorInterface* Begin() const { return new Iterator(this, g1_, g1_.begin(), g2_, g2_.begin(), g3_, g3_.begin(), g4_, g4_.begin()); } virtual ParamIteratorInterface* End() const { return new Iterator(this, g1_, g1_.end(), g2_, g2_.end(), g3_, g3_.end(), g4_, g4_.end()); } private: class Iterator : public ParamIteratorInterface { public: Iterator(const ParamGeneratorInterface* base, const ParamGenerator& g1, const typename ParamGenerator::iterator& current1, const ParamGenerator& g2, const typename ParamGenerator::iterator& current2, const ParamGenerator& g3, const typename ParamGenerator::iterator& current3, const ParamGenerator& g4, const typename ParamGenerator::iterator& current4) : base_(base), begin1_(g1.begin()), end1_(g1.end()), current1_(current1), begin2_(g2.begin()), end2_(g2.end()), current2_(current2), begin3_(g3.begin()), end3_(g3.end()), current3_(current3), begin4_(g4.begin()), end4_(g4.end()), current4_(current4) { ComputeCurrentValue(); } virtual ~Iterator() {} virtual const ParamGeneratorInterface* BaseGenerator() const { return base_; } // Advance should not be called on beyond-of-range iterators // so no component iterators must be beyond end of range, either. virtual void Advance() { assert(!AtEnd()); ++current4_; if (current4_ == end4_) { current4_ = begin4_; ++current3_; } if (current3_ == end3_) { current3_ = begin3_; ++current2_; } if (current2_ == end2_) { current2_ = begin2_; ++current1_; } ComputeCurrentValue(); } virtual ParamIteratorInterface* Clone() const { return new Iterator(*this); } virtual const ParamType* Current() const { return ¤t_value_; } virtual bool Equals(const ParamIteratorInterface& other) const { // Having the same base generator guarantees that the other // iterator is of the same type and we can downcast. GTEST_CHECK_(BaseGenerator() == other.BaseGenerator()) << "The program attempted to compare iterators " << "from different generators." << std::endl; const Iterator* typed_other = CheckedDowncastToActualType(&other); // We must report iterators equal if they both point beyond their // respective ranges. That can happen in a variety of fashions, // so we have to consult AtEnd(). return (AtEnd() && typed_other->AtEnd()) || ( current1_ == typed_other->current1_ && current2_ == typed_other->current2_ && current3_ == typed_other->current3_ && current4_ == typed_other->current4_); } private: Iterator(const Iterator& other) : base_(other.base_), begin1_(other.begin1_), end1_(other.end1_), current1_(other.current1_), begin2_(other.begin2_), end2_(other.end2_), current2_(other.current2_), begin3_(other.begin3_), end3_(other.end3_), current3_(other.current3_), begin4_(other.begin4_), end4_(other.end4_), current4_(other.current4_) { ComputeCurrentValue(); } void ComputeCurrentValue() { if (!AtEnd()) current_value_ = ParamType(*current1_, *current2_, *current3_, *current4_); } bool AtEnd() const { // We must report iterator past the end of the range when either of the // component iterators has reached the end of its range. return current1_ == end1_ || current2_ == end2_ || current3_ == end3_ || current4_ == end4_; } // No implementation - assignment is unsupported. void operator=(const Iterator& other); const ParamGeneratorInterface* const base_; // begin[i]_ and end[i]_ define the i-th range that Iterator traverses. // current[i]_ is the actual traversing iterator. const typename ParamGenerator::iterator begin1_; const typename ParamGenerator::iterator end1_; typename ParamGenerator::iterator current1_; const typename ParamGenerator::iterator begin2_; const typename ParamGenerator::iterator end2_; typename ParamGenerator::iterator current2_; const typename ParamGenerator::iterator begin3_; const typename ParamGenerator::iterator end3_; typename ParamGenerator::iterator current3_; const typename ParamGenerator::iterator begin4_; const typename ParamGenerator::iterator end4_; typename ParamGenerator::iterator current4_; ParamType current_value_; }; // class CartesianProductGenerator4::Iterator // No implementation - assignment is unsupported. void operator=(const CartesianProductGenerator4& other); const ParamGenerator g1_; const ParamGenerator g2_; const ParamGenerator g3_; const ParamGenerator g4_; }; // class CartesianProductGenerator4 template class CartesianProductGenerator5 : public ParamGeneratorInterface< ::std::tr1::tuple > { public: typedef ::std::tr1::tuple ParamType; CartesianProductGenerator5(const ParamGenerator& g1, const ParamGenerator& g2, const ParamGenerator& g3, const ParamGenerator& g4, const ParamGenerator& g5) : g1_(g1), g2_(g2), g3_(g3), g4_(g4), g5_(g5) {} virtual ~CartesianProductGenerator5() {} virtual ParamIteratorInterface* Begin() const { return new Iterator(this, g1_, g1_.begin(), g2_, g2_.begin(), g3_, g3_.begin(), g4_, g4_.begin(), g5_, g5_.begin()); } virtual ParamIteratorInterface* End() const { return new Iterator(this, g1_, g1_.end(), g2_, g2_.end(), g3_, g3_.end(), g4_, g4_.end(), g5_, g5_.end()); } private: class Iterator : public ParamIteratorInterface { public: Iterator(const ParamGeneratorInterface* base, const ParamGenerator& g1, const typename ParamGenerator::iterator& current1, const ParamGenerator& g2, const typename ParamGenerator::iterator& current2, const ParamGenerator& g3, const typename ParamGenerator::iterator& current3, const ParamGenerator& g4, const typename ParamGenerator::iterator& current4, const ParamGenerator& g5, const typename ParamGenerator::iterator& current5) : base_(base), begin1_(g1.begin()), end1_(g1.end()), current1_(current1), begin2_(g2.begin()), end2_(g2.end()), current2_(current2), begin3_(g3.begin()), end3_(g3.end()), current3_(current3), begin4_(g4.begin()), end4_(g4.end()), current4_(current4), begin5_(g5.begin()), end5_(g5.end()), current5_(current5) { ComputeCurrentValue(); } virtual ~Iterator() {} virtual const ParamGeneratorInterface* BaseGenerator() const { return base_; } // Advance should not be called on beyond-of-range iterators // so no component iterators must be beyond end of range, either. virtual void Advance() { assert(!AtEnd()); ++current5_; if (current5_ == end5_) { current5_ = begin5_; ++current4_; } if (current4_ == end4_) { current4_ = begin4_; ++current3_; } if (current3_ == end3_) { current3_ = begin3_; ++current2_; } if (current2_ == end2_) { current2_ = begin2_; ++current1_; } ComputeCurrentValue(); } virtual ParamIteratorInterface* Clone() const { return new Iterator(*this); } virtual const ParamType* Current() const { return ¤t_value_; } virtual bool Equals(const ParamIteratorInterface& other) const { // Having the same base generator guarantees that the other // iterator is of the same type and we can downcast. GTEST_CHECK_(BaseGenerator() == other.BaseGenerator()) << "The program attempted to compare iterators " << "from different generators." << std::endl; const Iterator* typed_other = CheckedDowncastToActualType(&other); // We must report iterators equal if they both point beyond their // respective ranges. That can happen in a variety of fashions, // so we have to consult AtEnd(). return (AtEnd() && typed_other->AtEnd()) || ( current1_ == typed_other->current1_ && current2_ == typed_other->current2_ && current3_ == typed_other->current3_ && current4_ == typed_other->current4_ && current5_ == typed_other->current5_); } private: Iterator(const Iterator& other) : base_(other.base_), begin1_(other.begin1_), end1_(other.end1_), current1_(other.current1_), begin2_(other.begin2_), end2_(other.end2_), current2_(other.current2_), begin3_(other.begin3_), end3_(other.end3_), current3_(other.current3_), begin4_(other.begin4_), end4_(other.end4_), current4_(other.current4_), begin5_(other.begin5_), end5_(other.end5_), current5_(other.current5_) { ComputeCurrentValue(); } void ComputeCurrentValue() { if (!AtEnd()) current_value_ = ParamType(*current1_, *current2_, *current3_, *current4_, *current5_); } bool AtEnd() const { // We must report iterator past the end of the range when either of the // component iterators has reached the end of its range. return current1_ == end1_ || current2_ == end2_ || current3_ == end3_ || current4_ == end4_ || current5_ == end5_; } // No implementation - assignment is unsupported. void operator=(const Iterator& other); const ParamGeneratorInterface* const base_; // begin[i]_ and end[i]_ define the i-th range that Iterator traverses. // current[i]_ is the actual traversing iterator. const typename ParamGenerator::iterator begin1_; const typename ParamGenerator::iterator end1_; typename ParamGenerator::iterator current1_; const typename ParamGenerator::iterator begin2_; const typename ParamGenerator::iterator end2_; typename ParamGenerator::iterator current2_; const typename ParamGenerator::iterator begin3_; const typename ParamGenerator::iterator end3_; typename ParamGenerator::iterator current3_; const typename ParamGenerator::iterator begin4_; const typename ParamGenerator::iterator end4_; typename ParamGenerator::iterator current4_; const typename ParamGenerator::iterator begin5_; const typename ParamGenerator::iterator end5_; typename ParamGenerator::iterator current5_; ParamType current_value_; }; // class CartesianProductGenerator5::Iterator // No implementation - assignment is unsupported. void operator=(const CartesianProductGenerator5& other); const ParamGenerator g1_; const ParamGenerator g2_; const ParamGenerator g3_; const ParamGenerator g4_; const ParamGenerator g5_; }; // class CartesianProductGenerator5 template class CartesianProductGenerator6 : public ParamGeneratorInterface< ::std::tr1::tuple > { public: typedef ::std::tr1::tuple ParamType; CartesianProductGenerator6(const ParamGenerator& g1, const ParamGenerator& g2, const ParamGenerator& g3, const ParamGenerator& g4, const ParamGenerator& g5, const ParamGenerator& g6) : g1_(g1), g2_(g2), g3_(g3), g4_(g4), g5_(g5), g6_(g6) {} virtual ~CartesianProductGenerator6() {} virtual ParamIteratorInterface* Begin() const { return new Iterator(this, g1_, g1_.begin(), g2_, g2_.begin(), g3_, g3_.begin(), g4_, g4_.begin(), g5_, g5_.begin(), g6_, g6_.begin()); } virtual ParamIteratorInterface* End() const { return new Iterator(this, g1_, g1_.end(), g2_, g2_.end(), g3_, g3_.end(), g4_, g4_.end(), g5_, g5_.end(), g6_, g6_.end()); } private: class Iterator : public ParamIteratorInterface { public: Iterator(const ParamGeneratorInterface* base, const ParamGenerator& g1, const typename ParamGenerator::iterator& current1, const ParamGenerator& g2, const typename ParamGenerator::iterator& current2, const ParamGenerator& g3, const typename ParamGenerator::iterator& current3, const ParamGenerator& g4, const typename ParamGenerator::iterator& current4, const ParamGenerator& g5, const typename ParamGenerator::iterator& current5, const ParamGenerator& g6, const typename ParamGenerator::iterator& current6) : base_(base), begin1_(g1.begin()), end1_(g1.end()), current1_(current1), begin2_(g2.begin()), end2_(g2.end()), current2_(current2), begin3_(g3.begin()), end3_(g3.end()), current3_(current3), begin4_(g4.begin()), end4_(g4.end()), current4_(current4), begin5_(g5.begin()), end5_(g5.end()), current5_(current5), begin6_(g6.begin()), end6_(g6.end()), current6_(current6) { ComputeCurrentValue(); } virtual ~Iterator() {} virtual const ParamGeneratorInterface* BaseGenerator() const { return base_; } // Advance should not be called on beyond-of-range iterators // so no component iterators must be beyond end of range, either. virtual void Advance() { assert(!AtEnd()); ++current6_; if (current6_ == end6_) { current6_ = begin6_; ++current5_; } if (current5_ == end5_) { current5_ = begin5_; ++current4_; } if (current4_ == end4_) { current4_ = begin4_; ++current3_; } if (current3_ == end3_) { current3_ = begin3_; ++current2_; } if (current2_ == end2_) { current2_ = begin2_; ++current1_; } ComputeCurrentValue(); } virtual ParamIteratorInterface* Clone() const { return new Iterator(*this); } virtual const ParamType* Current() const { return ¤t_value_; } virtual bool Equals(const ParamIteratorInterface& other) const { // Having the same base generator guarantees that the other // iterator is of the same type and we can downcast. GTEST_CHECK_(BaseGenerator() == other.BaseGenerator()) << "The program attempted to compare iterators " << "from different generators." << std::endl; const Iterator* typed_other = CheckedDowncastToActualType(&other); // We must report iterators equal if they both point beyond their // respective ranges. That can happen in a variety of fashions, // so we have to consult AtEnd(). return (AtEnd() && typed_other->AtEnd()) || ( current1_ == typed_other->current1_ && current2_ == typed_other->current2_ && current3_ == typed_other->current3_ && current4_ == typed_other->current4_ && current5_ == typed_other->current5_ && current6_ == typed_other->current6_); } private: Iterator(const Iterator& other) : base_(other.base_), begin1_(other.begin1_), end1_(other.end1_), current1_(other.current1_), begin2_(other.begin2_), end2_(other.end2_), current2_(other.current2_), begin3_(other.begin3_), end3_(other.end3_), current3_(other.current3_), begin4_(other.begin4_), end4_(other.end4_), current4_(other.current4_), begin5_(other.begin5_), end5_(other.end5_), current5_(other.current5_), begin6_(other.begin6_), end6_(other.end6_), current6_(other.current6_) { ComputeCurrentValue(); } void ComputeCurrentValue() { if (!AtEnd()) current_value_ = ParamType(*current1_, *current2_, *current3_, *current4_, *current5_, *current6_); } bool AtEnd() const { // We must report iterator past the end of the range when either of the // component iterators has reached the end of its range. return current1_ == end1_ || current2_ == end2_ || current3_ == end3_ || current4_ == end4_ || current5_ == end5_ || current6_ == end6_; } // No implementation - assignment is unsupported. void operator=(const Iterator& other); const ParamGeneratorInterface* const base_; // begin[i]_ and end[i]_ define the i-th range that Iterator traverses. // current[i]_ is the actual traversing iterator. const typename ParamGenerator::iterator begin1_; const typename ParamGenerator::iterator end1_; typename ParamGenerator::iterator current1_; const typename ParamGenerator::iterator begin2_; const typename ParamGenerator::iterator end2_; typename ParamGenerator::iterator current2_; const typename ParamGenerator::iterator begin3_; const typename ParamGenerator::iterator end3_; typename ParamGenerator::iterator current3_; const typename ParamGenerator::iterator begin4_; const typename ParamGenerator::iterator end4_; typename ParamGenerator::iterator current4_; const typename ParamGenerator::iterator begin5_; const typename ParamGenerator::iterator end5_; typename ParamGenerator::iterator current5_; const typename ParamGenerator::iterator begin6_; const typename ParamGenerator::iterator end6_; typename ParamGenerator::iterator current6_; ParamType current_value_; }; // class CartesianProductGenerator6::Iterator // No implementation - assignment is unsupported. void operator=(const CartesianProductGenerator6& other); const ParamGenerator g1_; const ParamGenerator g2_; const ParamGenerator g3_; const ParamGenerator g4_; const ParamGenerator g5_; const ParamGenerator g6_; }; // class CartesianProductGenerator6 template class CartesianProductGenerator7 : public ParamGeneratorInterface< ::std::tr1::tuple > { public: typedef ::std::tr1::tuple ParamType; CartesianProductGenerator7(const ParamGenerator& g1, const ParamGenerator& g2, const ParamGenerator& g3, const ParamGenerator& g4, const ParamGenerator& g5, const ParamGenerator& g6, const ParamGenerator& g7) : g1_(g1), g2_(g2), g3_(g3), g4_(g4), g5_(g5), g6_(g6), g7_(g7) {} virtual ~CartesianProductGenerator7() {} virtual ParamIteratorInterface* Begin() const { return new Iterator(this, g1_, g1_.begin(), g2_, g2_.begin(), g3_, g3_.begin(), g4_, g4_.begin(), g5_, g5_.begin(), g6_, g6_.begin(), g7_, g7_.begin()); } virtual ParamIteratorInterface* End() const { return new Iterator(this, g1_, g1_.end(), g2_, g2_.end(), g3_, g3_.end(), g4_, g4_.end(), g5_, g5_.end(), g6_, g6_.end(), g7_, g7_.end()); } private: class Iterator : public ParamIteratorInterface { public: Iterator(const ParamGeneratorInterface* base, const ParamGenerator& g1, const typename ParamGenerator::iterator& current1, const ParamGenerator& g2, const typename ParamGenerator::iterator& current2, const ParamGenerator& g3, const typename ParamGenerator::iterator& current3, const ParamGenerator& g4, const typename ParamGenerator::iterator& current4, const ParamGenerator& g5, const typename ParamGenerator::iterator& current5, const ParamGenerator& g6, const typename ParamGenerator::iterator& current6, const ParamGenerator& g7, const typename ParamGenerator::iterator& current7) : base_(base), begin1_(g1.begin()), end1_(g1.end()), current1_(current1), begin2_(g2.begin()), end2_(g2.end()), current2_(current2), begin3_(g3.begin()), end3_(g3.end()), current3_(current3), begin4_(g4.begin()), end4_(g4.end()), current4_(current4), begin5_(g5.begin()), end5_(g5.end()), current5_(current5), begin6_(g6.begin()), end6_(g6.end()), current6_(current6), begin7_(g7.begin()), end7_(g7.end()), current7_(current7) { ComputeCurrentValue(); } virtual ~Iterator() {} virtual const ParamGeneratorInterface* BaseGenerator() const { return base_; } // Advance should not be called on beyond-of-range iterators // so no component iterators must be beyond end of range, either. virtual void Advance() { assert(!AtEnd()); ++current7_; if (current7_ == end7_) { current7_ = begin7_; ++current6_; } if (current6_ == end6_) { current6_ = begin6_; ++current5_; } if (current5_ == end5_) { current5_ = begin5_; ++current4_; } if (current4_ == end4_) { current4_ = begin4_; ++current3_; } if (current3_ == end3_) { current3_ = begin3_; ++current2_; } if (current2_ == end2_) { current2_ = begin2_; ++current1_; } ComputeCurrentValue(); } virtual ParamIteratorInterface* Clone() const { return new Iterator(*this); } virtual const ParamType* Current() const { return ¤t_value_; } virtual bool Equals(const ParamIteratorInterface& other) const { // Having the same base generator guarantees that the other // iterator is of the same type and we can downcast. GTEST_CHECK_(BaseGenerator() == other.BaseGenerator()) << "The program attempted to compare iterators " << "from different generators." << std::endl; const Iterator* typed_other = CheckedDowncastToActualType(&other); // We must report iterators equal if they both point beyond their // respective ranges. That can happen in a variety of fashions, // so we have to consult AtEnd(). return (AtEnd() && typed_other->AtEnd()) || ( current1_ == typed_other->current1_ && current2_ == typed_other->current2_ && current3_ == typed_other->current3_ && current4_ == typed_other->current4_ && current5_ == typed_other->current5_ && current6_ == typed_other->current6_ && current7_ == typed_other->current7_); } private: Iterator(const Iterator& other) : base_(other.base_), begin1_(other.begin1_), end1_(other.end1_), current1_(other.current1_), begin2_(other.begin2_), end2_(other.end2_), current2_(other.current2_), begin3_(other.begin3_), end3_(other.end3_), current3_(other.current3_), begin4_(other.begin4_), end4_(other.end4_), current4_(other.current4_), begin5_(other.begin5_), end5_(other.end5_), current5_(other.current5_), begin6_(other.begin6_), end6_(other.end6_), current6_(other.current6_), begin7_(other.begin7_), end7_(other.end7_), current7_(other.current7_) { ComputeCurrentValue(); } void ComputeCurrentValue() { if (!AtEnd()) current_value_ = ParamType(*current1_, *current2_, *current3_, *current4_, *current5_, *current6_, *current7_); } bool AtEnd() const { // We must report iterator past the end of the range when either of the // component iterators has reached the end of its range. return current1_ == end1_ || current2_ == end2_ || current3_ == end3_ || current4_ == end4_ || current5_ == end5_ || current6_ == end6_ || current7_ == end7_; } // No implementation - assignment is unsupported. void operator=(const Iterator& other); const ParamGeneratorInterface* const base_; // begin[i]_ and end[i]_ define the i-th range that Iterator traverses. // current[i]_ is the actual traversing iterator. const typename ParamGenerator::iterator begin1_; const typename ParamGenerator::iterator end1_; typename ParamGenerator::iterator current1_; const typename ParamGenerator::iterator begin2_; const typename ParamGenerator::iterator end2_; typename ParamGenerator::iterator current2_; const typename ParamGenerator::iterator begin3_; const typename ParamGenerator::iterator end3_; typename ParamGenerator::iterator current3_; const typename ParamGenerator::iterator begin4_; const typename ParamGenerator::iterator end4_; typename ParamGenerator::iterator current4_; const typename ParamGenerator::iterator begin5_; const typename ParamGenerator::iterator end5_; typename ParamGenerator::iterator current5_; const typename ParamGenerator::iterator begin6_; const typename ParamGenerator::iterator end6_; typename ParamGenerator::iterator current6_; const typename ParamGenerator::iterator begin7_; const typename ParamGenerator::iterator end7_; typename ParamGenerator::iterator current7_; ParamType current_value_; }; // class CartesianProductGenerator7::Iterator // No implementation - assignment is unsupported. void operator=(const CartesianProductGenerator7& other); const ParamGenerator g1_; const ParamGenerator g2_; const ParamGenerator g3_; const ParamGenerator g4_; const ParamGenerator g5_; const ParamGenerator g6_; const ParamGenerator g7_; }; // class CartesianProductGenerator7 template class CartesianProductGenerator8 : public ParamGeneratorInterface< ::std::tr1::tuple > { public: typedef ::std::tr1::tuple ParamType; CartesianProductGenerator8(const ParamGenerator& g1, const ParamGenerator& g2, const ParamGenerator& g3, const ParamGenerator& g4, const ParamGenerator& g5, const ParamGenerator& g6, const ParamGenerator& g7, const ParamGenerator& g8) : g1_(g1), g2_(g2), g3_(g3), g4_(g4), g5_(g5), g6_(g6), g7_(g7), g8_(g8) {} virtual ~CartesianProductGenerator8() {} virtual ParamIteratorInterface* Begin() const { return new Iterator(this, g1_, g1_.begin(), g2_, g2_.begin(), g3_, g3_.begin(), g4_, g4_.begin(), g5_, g5_.begin(), g6_, g6_.begin(), g7_, g7_.begin(), g8_, g8_.begin()); } virtual ParamIteratorInterface* End() const { return new Iterator(this, g1_, g1_.end(), g2_, g2_.end(), g3_, g3_.end(), g4_, g4_.end(), g5_, g5_.end(), g6_, g6_.end(), g7_, g7_.end(), g8_, g8_.end()); } private: class Iterator : public ParamIteratorInterface { public: Iterator(const ParamGeneratorInterface* base, const ParamGenerator& g1, const typename ParamGenerator::iterator& current1, const ParamGenerator& g2, const typename ParamGenerator::iterator& current2, const ParamGenerator& g3, const typename ParamGenerator::iterator& current3, const ParamGenerator& g4, const typename ParamGenerator::iterator& current4, const ParamGenerator& g5, const typename ParamGenerator::iterator& current5, const ParamGenerator& g6, const typename ParamGenerator::iterator& current6, const ParamGenerator& g7, const typename ParamGenerator::iterator& current7, const ParamGenerator& g8, const typename ParamGenerator::iterator& current8) : base_(base), begin1_(g1.begin()), end1_(g1.end()), current1_(current1), begin2_(g2.begin()), end2_(g2.end()), current2_(current2), begin3_(g3.begin()), end3_(g3.end()), current3_(current3), begin4_(g4.begin()), end4_(g4.end()), current4_(current4), begin5_(g5.begin()), end5_(g5.end()), current5_(current5), begin6_(g6.begin()), end6_(g6.end()), current6_(current6), begin7_(g7.begin()), end7_(g7.end()), current7_(current7), begin8_(g8.begin()), end8_(g8.end()), current8_(current8) { ComputeCurrentValue(); } virtual ~Iterator() {} virtual const ParamGeneratorInterface* BaseGenerator() const { return base_; } // Advance should not be called on beyond-of-range iterators // so no component iterators must be beyond end of range, either. virtual void Advance() { assert(!AtEnd()); ++current8_; if (current8_ == end8_) { current8_ = begin8_; ++current7_; } if (current7_ == end7_) { current7_ = begin7_; ++current6_; } if (current6_ == end6_) { current6_ = begin6_; ++current5_; } if (current5_ == end5_) { current5_ = begin5_; ++current4_; } if (current4_ == end4_) { current4_ = begin4_; ++current3_; } if (current3_ == end3_) { current3_ = begin3_; ++current2_; } if (current2_ == end2_) { current2_ = begin2_; ++current1_; } ComputeCurrentValue(); } virtual ParamIteratorInterface* Clone() const { return new Iterator(*this); } virtual const ParamType* Current() const { return ¤t_value_; } virtual bool Equals(const ParamIteratorInterface& other) const { // Having the same base generator guarantees that the other // iterator is of the same type and we can downcast. GTEST_CHECK_(BaseGenerator() == other.BaseGenerator()) << "The program attempted to compare iterators " << "from different generators." << std::endl; const Iterator* typed_other = CheckedDowncastToActualType(&other); // We must report iterators equal if they both point beyond their // respective ranges. That can happen in a variety of fashions, // so we have to consult AtEnd(). return (AtEnd() && typed_other->AtEnd()) || ( current1_ == typed_other->current1_ && current2_ == typed_other->current2_ && current3_ == typed_other->current3_ && current4_ == typed_other->current4_ && current5_ == typed_other->current5_ && current6_ == typed_other->current6_ && current7_ == typed_other->current7_ && current8_ == typed_other->current8_); } private: Iterator(const Iterator& other) : base_(other.base_), begin1_(other.begin1_), end1_(other.end1_), current1_(other.current1_), begin2_(other.begin2_), end2_(other.end2_), current2_(other.current2_), begin3_(other.begin3_), end3_(other.end3_), current3_(other.current3_), begin4_(other.begin4_), end4_(other.end4_), current4_(other.current4_), begin5_(other.begin5_), end5_(other.end5_), current5_(other.current5_), begin6_(other.begin6_), end6_(other.end6_), current6_(other.current6_), begin7_(other.begin7_), end7_(other.end7_), current7_(other.current7_), begin8_(other.begin8_), end8_(other.end8_), current8_(other.current8_) { ComputeCurrentValue(); } void ComputeCurrentValue() { if (!AtEnd()) current_value_ = ParamType(*current1_, *current2_, *current3_, *current4_, *current5_, *current6_, *current7_, *current8_); } bool AtEnd() const { // We must report iterator past the end of the range when either of the // component iterators has reached the end of its range. return current1_ == end1_ || current2_ == end2_ || current3_ == end3_ || current4_ == end4_ || current5_ == end5_ || current6_ == end6_ || current7_ == end7_ || current8_ == end8_; } // No implementation - assignment is unsupported. void operator=(const Iterator& other); const ParamGeneratorInterface* const base_; // begin[i]_ and end[i]_ define the i-th range that Iterator traverses. // current[i]_ is the actual traversing iterator. const typename ParamGenerator::iterator begin1_; const typename ParamGenerator::iterator end1_; typename ParamGenerator::iterator current1_; const typename ParamGenerator::iterator begin2_; const typename ParamGenerator::iterator end2_; typename ParamGenerator::iterator current2_; const typename ParamGenerator::iterator begin3_; const typename ParamGenerator::iterator end3_; typename ParamGenerator::iterator current3_; const typename ParamGenerator::iterator begin4_; const typename ParamGenerator::iterator end4_; typename ParamGenerator::iterator current4_; const typename ParamGenerator::iterator begin5_; const typename ParamGenerator::iterator end5_; typename ParamGenerator::iterator current5_; const typename ParamGenerator::iterator begin6_; const typename ParamGenerator::iterator end6_; typename ParamGenerator::iterator current6_; const typename ParamGenerator::iterator begin7_; const typename ParamGenerator::iterator end7_; typename ParamGenerator::iterator current7_; const typename ParamGenerator::iterator begin8_; const typename ParamGenerator::iterator end8_; typename ParamGenerator::iterator current8_; ParamType current_value_; }; // class CartesianProductGenerator8::Iterator // No implementation - assignment is unsupported. void operator=(const CartesianProductGenerator8& other); const ParamGenerator g1_; const ParamGenerator g2_; const ParamGenerator g3_; const ParamGenerator g4_; const ParamGenerator g5_; const ParamGenerator g6_; const ParamGenerator g7_; const ParamGenerator g8_; }; // class CartesianProductGenerator8 template class CartesianProductGenerator9 : public ParamGeneratorInterface< ::std::tr1::tuple > { public: typedef ::std::tr1::tuple ParamType; CartesianProductGenerator9(const ParamGenerator& g1, const ParamGenerator& g2, const ParamGenerator& g3, const ParamGenerator& g4, const ParamGenerator& g5, const ParamGenerator& g6, const ParamGenerator& g7, const ParamGenerator& g8, const ParamGenerator& g9) : g1_(g1), g2_(g2), g3_(g3), g4_(g4), g5_(g5), g6_(g6), g7_(g7), g8_(g8), g9_(g9) {} virtual ~CartesianProductGenerator9() {} virtual ParamIteratorInterface* Begin() const { return new Iterator(this, g1_, g1_.begin(), g2_, g2_.begin(), g3_, g3_.begin(), g4_, g4_.begin(), g5_, g5_.begin(), g6_, g6_.begin(), g7_, g7_.begin(), g8_, g8_.begin(), g9_, g9_.begin()); } virtual ParamIteratorInterface* End() const { return new Iterator(this, g1_, g1_.end(), g2_, g2_.end(), g3_, g3_.end(), g4_, g4_.end(), g5_, g5_.end(), g6_, g6_.end(), g7_, g7_.end(), g8_, g8_.end(), g9_, g9_.end()); } private: class Iterator : public ParamIteratorInterface { public: Iterator(const ParamGeneratorInterface* base, const ParamGenerator& g1, const typename ParamGenerator::iterator& current1, const ParamGenerator& g2, const typename ParamGenerator::iterator& current2, const ParamGenerator& g3, const typename ParamGenerator::iterator& current3, const ParamGenerator& g4, const typename ParamGenerator::iterator& current4, const ParamGenerator& g5, const typename ParamGenerator::iterator& current5, const ParamGenerator& g6, const typename ParamGenerator::iterator& current6, const ParamGenerator& g7, const typename ParamGenerator::iterator& current7, const ParamGenerator& g8, const typename ParamGenerator::iterator& current8, const ParamGenerator& g9, const typename ParamGenerator::iterator& current9) : base_(base), begin1_(g1.begin()), end1_(g1.end()), current1_(current1), begin2_(g2.begin()), end2_(g2.end()), current2_(current2), begin3_(g3.begin()), end3_(g3.end()), current3_(current3), begin4_(g4.begin()), end4_(g4.end()), current4_(current4), begin5_(g5.begin()), end5_(g5.end()), current5_(current5), begin6_(g6.begin()), end6_(g6.end()), current6_(current6), begin7_(g7.begin()), end7_(g7.end()), current7_(current7), begin8_(g8.begin()), end8_(g8.end()), current8_(current8), begin9_(g9.begin()), end9_(g9.end()), current9_(current9) { ComputeCurrentValue(); } virtual ~Iterator() {} virtual const ParamGeneratorInterface* BaseGenerator() const { return base_; } // Advance should not be called on beyond-of-range iterators // so no component iterators must be beyond end of range, either. virtual void Advance() { assert(!AtEnd()); ++current9_; if (current9_ == end9_) { current9_ = begin9_; ++current8_; } if (current8_ == end8_) { current8_ = begin8_; ++current7_; } if (current7_ == end7_) { current7_ = begin7_; ++current6_; } if (current6_ == end6_) { current6_ = begin6_; ++current5_; } if (current5_ == end5_) { current5_ = begin5_; ++current4_; } if (current4_ == end4_) { current4_ = begin4_; ++current3_; } if (current3_ == end3_) { current3_ = begin3_; ++current2_; } if (current2_ == end2_) { current2_ = begin2_; ++current1_; } ComputeCurrentValue(); } virtual ParamIteratorInterface* Clone() const { return new Iterator(*this); } virtual const ParamType* Current() const { return ¤t_value_; } virtual bool Equals(const ParamIteratorInterface& other) const { // Having the same base generator guarantees that the other // iterator is of the same type and we can downcast. GTEST_CHECK_(BaseGenerator() == other.BaseGenerator()) << "The program attempted to compare iterators " << "from different generators." << std::endl; const Iterator* typed_other = CheckedDowncastToActualType(&other); // We must report iterators equal if they both point beyond their // respective ranges. That can happen in a variety of fashions, // so we have to consult AtEnd(). return (AtEnd() && typed_other->AtEnd()) || ( current1_ == typed_other->current1_ && current2_ == typed_other->current2_ && current3_ == typed_other->current3_ && current4_ == typed_other->current4_ && current5_ == typed_other->current5_ && current6_ == typed_other->current6_ && current7_ == typed_other->current7_ && current8_ == typed_other->current8_ && current9_ == typed_other->current9_); } private: Iterator(const Iterator& other) : base_(other.base_), begin1_(other.begin1_), end1_(other.end1_), current1_(other.current1_), begin2_(other.begin2_), end2_(other.end2_), current2_(other.current2_), begin3_(other.begin3_), end3_(other.end3_), current3_(other.current3_), begin4_(other.begin4_), end4_(other.end4_), current4_(other.current4_), begin5_(other.begin5_), end5_(other.end5_), current5_(other.current5_), begin6_(other.begin6_), end6_(other.end6_), current6_(other.current6_), begin7_(other.begin7_), end7_(other.end7_), current7_(other.current7_), begin8_(other.begin8_), end8_(other.end8_), current8_(other.current8_), begin9_(other.begin9_), end9_(other.end9_), current9_(other.current9_) { ComputeCurrentValue(); } void ComputeCurrentValue() { if (!AtEnd()) current_value_ = ParamType(*current1_, *current2_, *current3_, *current4_, *current5_, *current6_, *current7_, *current8_, *current9_); } bool AtEnd() const { // We must report iterator past the end of the range when either of the // component iterators has reached the end of its range. return current1_ == end1_ || current2_ == end2_ || current3_ == end3_ || current4_ == end4_ || current5_ == end5_ || current6_ == end6_ || current7_ == end7_ || current8_ == end8_ || current9_ == end9_; } // No implementation - assignment is unsupported. void operator=(const Iterator& other); const ParamGeneratorInterface* const base_; // begin[i]_ and end[i]_ define the i-th range that Iterator traverses. // current[i]_ is the actual traversing iterator. const typename ParamGenerator::iterator begin1_; const typename ParamGenerator::iterator end1_; typename ParamGenerator::iterator current1_; const typename ParamGenerator::iterator begin2_; const typename ParamGenerator::iterator end2_; typename ParamGenerator::iterator current2_; const typename ParamGenerator::iterator begin3_; const typename ParamGenerator::iterator end3_; typename ParamGenerator::iterator current3_; const typename ParamGenerator::iterator begin4_; const typename ParamGenerator::iterator end4_; typename ParamGenerator::iterator current4_; const typename ParamGenerator::iterator begin5_; const typename ParamGenerator::iterator end5_; typename ParamGenerator::iterator current5_; const typename ParamGenerator::iterator begin6_; const typename ParamGenerator::iterator end6_; typename ParamGenerator::iterator current6_; const typename ParamGenerator::iterator begin7_; const typename ParamGenerator::iterator end7_; typename ParamGenerator::iterator current7_; const typename ParamGenerator::iterator begin8_; const typename ParamGenerator::iterator end8_; typename ParamGenerator::iterator current8_; const typename ParamGenerator::iterator begin9_; const typename ParamGenerator::iterator end9_; typename ParamGenerator::iterator current9_; ParamType current_value_; }; // class CartesianProductGenerator9::Iterator // No implementation - assignment is unsupported. void operator=(const CartesianProductGenerator9& other); const ParamGenerator g1_; const ParamGenerator g2_; const ParamGenerator g3_; const ParamGenerator g4_; const ParamGenerator g5_; const ParamGenerator g6_; const ParamGenerator g7_; const ParamGenerator g8_; const ParamGenerator g9_; }; // class CartesianProductGenerator9 template class CartesianProductGenerator10 : public ParamGeneratorInterface< ::std::tr1::tuple > { public: typedef ::std::tr1::tuple ParamType; CartesianProductGenerator10(const ParamGenerator& g1, const ParamGenerator& g2, const ParamGenerator& g3, const ParamGenerator& g4, const ParamGenerator& g5, const ParamGenerator& g6, const ParamGenerator& g7, const ParamGenerator& g8, const ParamGenerator& g9, const ParamGenerator& g10) : g1_(g1), g2_(g2), g3_(g3), g4_(g4), g5_(g5), g6_(g6), g7_(g7), g8_(g8), g9_(g9), g10_(g10) {} virtual ~CartesianProductGenerator10() {} virtual ParamIteratorInterface* Begin() const { return new Iterator(this, g1_, g1_.begin(), g2_, g2_.begin(), g3_, g3_.begin(), g4_, g4_.begin(), g5_, g5_.begin(), g6_, g6_.begin(), g7_, g7_.begin(), g8_, g8_.begin(), g9_, g9_.begin(), g10_, g10_.begin()); } virtual ParamIteratorInterface* End() const { return new Iterator(this, g1_, g1_.end(), g2_, g2_.end(), g3_, g3_.end(), g4_, g4_.end(), g5_, g5_.end(), g6_, g6_.end(), g7_, g7_.end(), g8_, g8_.end(), g9_, g9_.end(), g10_, g10_.end()); } private: class Iterator : public ParamIteratorInterface { public: Iterator(const ParamGeneratorInterface* base, const ParamGenerator& g1, const typename ParamGenerator::iterator& current1, const ParamGenerator& g2, const typename ParamGenerator::iterator& current2, const ParamGenerator& g3, const typename ParamGenerator::iterator& current3, const ParamGenerator& g4, const typename ParamGenerator::iterator& current4, const ParamGenerator& g5, const typename ParamGenerator::iterator& current5, const ParamGenerator& g6, const typename ParamGenerator::iterator& current6, const ParamGenerator& g7, const typename ParamGenerator::iterator& current7, const ParamGenerator& g8, const typename ParamGenerator::iterator& current8, const ParamGenerator& g9, const typename ParamGenerator::iterator& current9, const ParamGenerator& g10, const typename ParamGenerator::iterator& current10) : base_(base), begin1_(g1.begin()), end1_(g1.end()), current1_(current1), begin2_(g2.begin()), end2_(g2.end()), current2_(current2), begin3_(g3.begin()), end3_(g3.end()), current3_(current3), begin4_(g4.begin()), end4_(g4.end()), current4_(current4), begin5_(g5.begin()), end5_(g5.end()), current5_(current5), begin6_(g6.begin()), end6_(g6.end()), current6_(current6), begin7_(g7.begin()), end7_(g7.end()), current7_(current7), begin8_(g8.begin()), end8_(g8.end()), current8_(current8), begin9_(g9.begin()), end9_(g9.end()), current9_(current9), begin10_(g10.begin()), end10_(g10.end()), current10_(current10) { ComputeCurrentValue(); } virtual ~Iterator() {} virtual const ParamGeneratorInterface* BaseGenerator() const { return base_; } // Advance should not be called on beyond-of-range iterators // so no component iterators must be beyond end of range, either. virtual void Advance() { assert(!AtEnd()); ++current10_; if (current10_ == end10_) { current10_ = begin10_; ++current9_; } if (current9_ == end9_) { current9_ = begin9_; ++current8_; } if (current8_ == end8_) { current8_ = begin8_; ++current7_; } if (current7_ == end7_) { current7_ = begin7_; ++current6_; } if (current6_ == end6_) { current6_ = begin6_; ++current5_; } if (current5_ == end5_) { current5_ = begin5_; ++current4_; } if (current4_ == end4_) { current4_ = begin4_; ++current3_; } if (current3_ == end3_) { current3_ = begin3_; ++current2_; } if (current2_ == end2_) { current2_ = begin2_; ++current1_; } ComputeCurrentValue(); } virtual ParamIteratorInterface* Clone() const { return new Iterator(*this); } virtual const ParamType* Current() const { return ¤t_value_; } virtual bool Equals(const ParamIteratorInterface& other) const { // Having the same base generator guarantees that the other // iterator is of the same type and we can downcast. GTEST_CHECK_(BaseGenerator() == other.BaseGenerator()) << "The program attempted to compare iterators " << "from different generators." << std::endl; const Iterator* typed_other = CheckedDowncastToActualType(&other); // We must report iterators equal if they both point beyond their // respective ranges. That can happen in a variety of fashions, // so we have to consult AtEnd(). return (AtEnd() && typed_other->AtEnd()) || ( current1_ == typed_other->current1_ && current2_ == typed_other->current2_ && current3_ == typed_other->current3_ && current4_ == typed_other->current4_ && current5_ == typed_other->current5_ && current6_ == typed_other->current6_ && current7_ == typed_other->current7_ && current8_ == typed_other->current8_ && current9_ == typed_other->current9_ && current10_ == typed_other->current10_); } private: Iterator(const Iterator& other) : base_(other.base_), begin1_(other.begin1_), end1_(other.end1_), current1_(other.current1_), begin2_(other.begin2_), end2_(other.end2_), current2_(other.current2_), begin3_(other.begin3_), end3_(other.end3_), current3_(other.current3_), begin4_(other.begin4_), end4_(other.end4_), current4_(other.current4_), begin5_(other.begin5_), end5_(other.end5_), current5_(other.current5_), begin6_(other.begin6_), end6_(other.end6_), current6_(other.current6_), begin7_(other.begin7_), end7_(other.end7_), current7_(other.current7_), begin8_(other.begin8_), end8_(other.end8_), current8_(other.current8_), begin9_(other.begin9_), end9_(other.end9_), current9_(other.current9_), begin10_(other.begin10_), end10_(other.end10_), current10_(other.current10_) { ComputeCurrentValue(); } void ComputeCurrentValue() { if (!AtEnd()) current_value_ = ParamType(*current1_, *current2_, *current3_, *current4_, *current5_, *current6_, *current7_, *current8_, *current9_, *current10_); } bool AtEnd() const { // We must report iterator past the end of the range when either of the // component iterators has reached the end of its range. return current1_ == end1_ || current2_ == end2_ || current3_ == end3_ || current4_ == end4_ || current5_ == end5_ || current6_ == end6_ || current7_ == end7_ || current8_ == end8_ || current9_ == end9_ || current10_ == end10_; } // No implementation - assignment is unsupported. void operator=(const Iterator& other); const ParamGeneratorInterface* const base_; // begin[i]_ and end[i]_ define the i-th range that Iterator traverses. // current[i]_ is the actual traversing iterator. const typename ParamGenerator::iterator begin1_; const typename ParamGenerator::iterator end1_; typename ParamGenerator::iterator current1_; const typename ParamGenerator::iterator begin2_; const typename ParamGenerator::iterator end2_; typename ParamGenerator::iterator current2_; const typename ParamGenerator::iterator begin3_; const typename ParamGenerator::iterator end3_; typename ParamGenerator::iterator current3_; const typename ParamGenerator::iterator begin4_; const typename ParamGenerator::iterator end4_; typename ParamGenerator::iterator current4_; const typename ParamGenerator::iterator begin5_; const typename ParamGenerator::iterator end5_; typename ParamGenerator::iterator current5_; const typename ParamGenerator::iterator begin6_; const typename ParamGenerator::iterator end6_; typename ParamGenerator::iterator current6_; const typename ParamGenerator::iterator begin7_; const typename ParamGenerator::iterator end7_; typename ParamGenerator::iterator current7_; const typename ParamGenerator::iterator begin8_; const typename ParamGenerator::iterator end8_; typename ParamGenerator::iterator current8_; const typename ParamGenerator::iterator begin9_; const typename ParamGenerator::iterator end9_; typename ParamGenerator::iterator current9_; const typename ParamGenerator::iterator begin10_; const typename ParamGenerator::iterator end10_; typename ParamGenerator::iterator current10_; ParamType current_value_; }; // class CartesianProductGenerator10::Iterator // No implementation - assignment is unsupported. void operator=(const CartesianProductGenerator10& other); const ParamGenerator g1_; const ParamGenerator g2_; const ParamGenerator g3_; const ParamGenerator g4_; const ParamGenerator g5_; const ParamGenerator g6_; const ParamGenerator g7_; const ParamGenerator g8_; const ParamGenerator g9_; const ParamGenerator g10_; }; // class CartesianProductGenerator10 // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE. // // Helper classes providing Combine() with polymorphic features. They allow // casting CartesianProductGeneratorN to ParamGenerator if T is // convertible to U. // template class CartesianProductHolder2 { public: CartesianProductHolder2(const Generator1& g1, const Generator2& g2) : g1_(g1), g2_(g2) {} template operator ParamGenerator< ::std::tr1::tuple >() const { return ParamGenerator< ::std::tr1::tuple >( new CartesianProductGenerator2( static_cast >(g1_), static_cast >(g2_))); } private: // No implementation - assignment is unsupported. void operator=(const CartesianProductHolder2& other); const Generator1 g1_; const Generator2 g2_; }; // class CartesianProductHolder2 template class CartesianProductHolder3 { public: CartesianProductHolder3(const Generator1& g1, const Generator2& g2, const Generator3& g3) : g1_(g1), g2_(g2), g3_(g3) {} template operator ParamGenerator< ::std::tr1::tuple >() const { return ParamGenerator< ::std::tr1::tuple >( new CartesianProductGenerator3( static_cast >(g1_), static_cast >(g2_), static_cast >(g3_))); } private: // No implementation - assignment is unsupported. void operator=(const CartesianProductHolder3& other); const Generator1 g1_; const Generator2 g2_; const Generator3 g3_; }; // class CartesianProductHolder3 template class CartesianProductHolder4 { public: CartesianProductHolder4(const Generator1& g1, const Generator2& g2, const Generator3& g3, const Generator4& g4) : g1_(g1), g2_(g2), g3_(g3), g4_(g4) {} template operator ParamGenerator< ::std::tr1::tuple >() const { return ParamGenerator< ::std::tr1::tuple >( new CartesianProductGenerator4( static_cast >(g1_), static_cast >(g2_), static_cast >(g3_), static_cast >(g4_))); } private: // No implementation - assignment is unsupported. void operator=(const CartesianProductHolder4& other); const Generator1 g1_; const Generator2 g2_; const Generator3 g3_; const Generator4 g4_; }; // class CartesianProductHolder4 template class CartesianProductHolder5 { public: CartesianProductHolder5(const Generator1& g1, const Generator2& g2, const Generator3& g3, const Generator4& g4, const Generator5& g5) : g1_(g1), g2_(g2), g3_(g3), g4_(g4), g5_(g5) {} template operator ParamGenerator< ::std::tr1::tuple >() const { return ParamGenerator< ::std::tr1::tuple >( new CartesianProductGenerator5( static_cast >(g1_), static_cast >(g2_), static_cast >(g3_), static_cast >(g4_), static_cast >(g5_))); } private: // No implementation - assignment is unsupported. void operator=(const CartesianProductHolder5& other); const Generator1 g1_; const Generator2 g2_; const Generator3 g3_; const Generator4 g4_; const Generator5 g5_; }; // class CartesianProductHolder5 template class CartesianProductHolder6 { public: CartesianProductHolder6(const Generator1& g1, const Generator2& g2, const Generator3& g3, const Generator4& g4, const Generator5& g5, const Generator6& g6) : g1_(g1), g2_(g2), g3_(g3), g4_(g4), g5_(g5), g6_(g6) {} template operator ParamGenerator< ::std::tr1::tuple >() const { return ParamGenerator< ::std::tr1::tuple >( new CartesianProductGenerator6( static_cast >(g1_), static_cast >(g2_), static_cast >(g3_), static_cast >(g4_), static_cast >(g5_), static_cast >(g6_))); } private: // No implementation - assignment is unsupported. void operator=(const CartesianProductHolder6& other); const Generator1 g1_; const Generator2 g2_; const Generator3 g3_; const Generator4 g4_; const Generator5 g5_; const Generator6 g6_; }; // class CartesianProductHolder6 template class CartesianProductHolder7 { public: CartesianProductHolder7(const Generator1& g1, const Generator2& g2, const Generator3& g3, const Generator4& g4, const Generator5& g5, const Generator6& g6, const Generator7& g7) : g1_(g1), g2_(g2), g3_(g3), g4_(g4), g5_(g5), g6_(g6), g7_(g7) {} template operator ParamGenerator< ::std::tr1::tuple >() const { return ParamGenerator< ::std::tr1::tuple >( new CartesianProductGenerator7( static_cast >(g1_), static_cast >(g2_), static_cast >(g3_), static_cast >(g4_), static_cast >(g5_), static_cast >(g6_), static_cast >(g7_))); } private: // No implementation - assignment is unsupported. void operator=(const CartesianProductHolder7& other); const Generator1 g1_; const Generator2 g2_; const Generator3 g3_; const Generator4 g4_; const Generator5 g5_; const Generator6 g6_; const Generator7 g7_; }; // class CartesianProductHolder7 template class CartesianProductHolder8 { public: CartesianProductHolder8(const Generator1& g1, const Generator2& g2, const Generator3& g3, const Generator4& g4, const Generator5& g5, const Generator6& g6, const Generator7& g7, const Generator8& g8) : g1_(g1), g2_(g2), g3_(g3), g4_(g4), g5_(g5), g6_(g6), g7_(g7), g8_(g8) {} template operator ParamGenerator< ::std::tr1::tuple >() const { return ParamGenerator< ::std::tr1::tuple >( new CartesianProductGenerator8( static_cast >(g1_), static_cast >(g2_), static_cast >(g3_), static_cast >(g4_), static_cast >(g5_), static_cast >(g6_), static_cast >(g7_), static_cast >(g8_))); } private: // No implementation - assignment is unsupported. void operator=(const CartesianProductHolder8& other); const Generator1 g1_; const Generator2 g2_; const Generator3 g3_; const Generator4 g4_; const Generator5 g5_; const Generator6 g6_; const Generator7 g7_; const Generator8 g8_; }; // class CartesianProductHolder8 template class CartesianProductHolder9 { public: CartesianProductHolder9(const Generator1& g1, const Generator2& g2, const Generator3& g3, const Generator4& g4, const Generator5& g5, const Generator6& g6, const Generator7& g7, const Generator8& g8, const Generator9& g9) : g1_(g1), g2_(g2), g3_(g3), g4_(g4), g5_(g5), g6_(g6), g7_(g7), g8_(g8), g9_(g9) {} template operator ParamGenerator< ::std::tr1::tuple >() const { return ParamGenerator< ::std::tr1::tuple >( new CartesianProductGenerator9( static_cast >(g1_), static_cast >(g2_), static_cast >(g3_), static_cast >(g4_), static_cast >(g5_), static_cast >(g6_), static_cast >(g7_), static_cast >(g8_), static_cast >(g9_))); } private: // No implementation - assignment is unsupported. void operator=(const CartesianProductHolder9& other); const Generator1 g1_; const Generator2 g2_; const Generator3 g3_; const Generator4 g4_; const Generator5 g5_; const Generator6 g6_; const Generator7 g7_; const Generator8 g8_; const Generator9 g9_; }; // class CartesianProductHolder9 template class CartesianProductHolder10 { public: CartesianProductHolder10(const Generator1& g1, const Generator2& g2, const Generator3& g3, const Generator4& g4, const Generator5& g5, const Generator6& g6, const Generator7& g7, const Generator8& g8, const Generator9& g9, const Generator10& g10) : g1_(g1), g2_(g2), g3_(g3), g4_(g4), g5_(g5), g6_(g6), g7_(g7), g8_(g8), g9_(g9), g10_(g10) {} template operator ParamGenerator< ::std::tr1::tuple >() const { return ParamGenerator< ::std::tr1::tuple >( new CartesianProductGenerator10( static_cast >(g1_), static_cast >(g2_), static_cast >(g3_), static_cast >(g4_), static_cast >(g5_), static_cast >(g6_), static_cast >(g7_), static_cast >(g8_), static_cast >(g9_), static_cast >(g10_))); } private: // No implementation - assignment is unsupported. void operator=(const CartesianProductHolder10& other); const Generator1 g1_; const Generator2 g2_; const Generator3 g3_; const Generator4 g4_; const Generator5 g5_; const Generator6 g6_; const Generator7 g7_; const Generator8 g8_; const Generator9 g9_; const Generator10 g10_; }; // class CartesianProductHolder10 # endif // GTEST_HAS_COMBINE } // namespace internal } // namespace testing #endif // GTEST_HAS_PARAM_TEST #endif // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PARAM_UTIL_GENERATED_H_ ugene-1.9.8/src/libs_3rdparty/gtest/src/gtest/internal/gtest-param-util-generated.h.pump0000644000175000017500000002227011651544307030036 0ustar ilyailya$$ -*- mode: c++; -*- $var n = 50 $$ Maximum length of Values arguments we want to support. $var maxtuple = 10 $$ Maximum number of Combine arguments we want to support. // Copyright 2008 Google Inc. // All Rights Reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Author: vladl@google.com (Vlad Losev) // Type and function utilities for implementing parameterized tests. // This file is generated by a SCRIPT. DO NOT EDIT BY HAND! // // Currently Google Test supports at most $n arguments in Values, // and at most $maxtuple arguments in Combine. Please contact // googletestframework@googlegroups.com if you need more. // Please note that the number of arguments to Combine is limited // by the maximum arity of the implementation of tr1::tuple which is // currently set at $maxtuple. #ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PARAM_UTIL_GENERATED_H_ #define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PARAM_UTIL_GENERATED_H_ // scripts/fuse_gtest.py depends on gtest's own header being #included // *unconditionally*. Therefore these #includes cannot be moved // inside #if GTEST_HAS_PARAM_TEST. #include "gtest/internal/gtest-param-util.h" #include "gtest/internal/gtest-port.h" #if GTEST_HAS_PARAM_TEST namespace testing { // Forward declarations of ValuesIn(), which is implemented in // include/gtest/gtest-param-test.h. template internal::ParamGenerator< typename ::testing::internal::IteratorTraits::value_type> ValuesIn(ForwardIterator begin, ForwardIterator end); template internal::ParamGenerator ValuesIn(const T (&array)[N]); template internal::ParamGenerator ValuesIn( const Container& container); namespace internal { // Used in the Values() function to provide polymorphic capabilities. template class ValueArray1 { public: explicit ValueArray1(T1 v1) : v1_(v1) {} template operator ParamGenerator() const { return ValuesIn(&v1_, &v1_ + 1); } private: // No implementation - assignment is unsupported. void operator=(const ValueArray1& other); const T1 v1_; }; $range i 2..n $for i [[ $range j 1..i template <$for j, [[typename T$j]]> class ValueArray$i { public: ValueArray$i($for j, [[T$j v$j]]) : $for j, [[v$(j)_(v$j)]] {} template operator ParamGenerator() const { const T array[] = {$for j, [[v$(j)_]]}; return ValuesIn(array); } private: // No implementation - assignment is unsupported. void operator=(const ValueArray$i& other); $for j [[ const T$j v$(j)_; ]] }; ]] # if GTEST_HAS_COMBINE // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE. // // Generates values from the Cartesian product of values produced // by the argument generators. // $range i 2..maxtuple $for i [[ $range j 1..i $range k 2..i template <$for j, [[typename T$j]]> class CartesianProductGenerator$i : public ParamGeneratorInterface< ::std::tr1::tuple<$for j, [[T$j]]> > { public: typedef ::std::tr1::tuple<$for j, [[T$j]]> ParamType; CartesianProductGenerator$i($for j, [[const ParamGenerator& g$j]]) : $for j, [[g$(j)_(g$j)]] {} virtual ~CartesianProductGenerator$i() {} virtual ParamIteratorInterface* Begin() const { return new Iterator(this, $for j, [[g$(j)_, g$(j)_.begin()]]); } virtual ParamIteratorInterface* End() const { return new Iterator(this, $for j, [[g$(j)_, g$(j)_.end()]]); } private: class Iterator : public ParamIteratorInterface { public: Iterator(const ParamGeneratorInterface* base, $for j, [[ const ParamGenerator& g$j, const typename ParamGenerator::iterator& current$(j)]]) : base_(base), $for j, [[ begin$(j)_(g$j.begin()), end$(j)_(g$j.end()), current$(j)_(current$j) ]] { ComputeCurrentValue(); } virtual ~Iterator() {} virtual const ParamGeneratorInterface* BaseGenerator() const { return base_; } // Advance should not be called on beyond-of-range iterators // so no component iterators must be beyond end of range, either. virtual void Advance() { assert(!AtEnd()); ++current$(i)_; $for k [[ if (current$(i+2-k)_ == end$(i+2-k)_) { current$(i+2-k)_ = begin$(i+2-k)_; ++current$(i+2-k-1)_; } ]] ComputeCurrentValue(); } virtual ParamIteratorInterface* Clone() const { return new Iterator(*this); } virtual const ParamType* Current() const { return ¤t_value_; } virtual bool Equals(const ParamIteratorInterface& other) const { // Having the same base generator guarantees that the other // iterator is of the same type and we can downcast. GTEST_CHECK_(BaseGenerator() == other.BaseGenerator()) << "The program attempted to compare iterators " << "from different generators." << std::endl; const Iterator* typed_other = CheckedDowncastToActualType(&other); // We must report iterators equal if they both point beyond their // respective ranges. That can happen in a variety of fashions, // so we have to consult AtEnd(). return (AtEnd() && typed_other->AtEnd()) || ($for j && [[ current$(j)_ == typed_other->current$(j)_ ]]); } private: Iterator(const Iterator& other) : base_(other.base_), $for j, [[ begin$(j)_(other.begin$(j)_), end$(j)_(other.end$(j)_), current$(j)_(other.current$(j)_) ]] { ComputeCurrentValue(); } void ComputeCurrentValue() { if (!AtEnd()) current_value_ = ParamType($for j, [[*current$(j)_]]); } bool AtEnd() const { // We must report iterator past the end of the range when either of the // component iterators has reached the end of its range. return $for j || [[ current$(j)_ == end$(j)_ ]]; } // No implementation - assignment is unsupported. void operator=(const Iterator& other); const ParamGeneratorInterface* const base_; // begin[i]_ and end[i]_ define the i-th range that Iterator traverses. // current[i]_ is the actual traversing iterator. $for j [[ const typename ParamGenerator::iterator begin$(j)_; const typename ParamGenerator::iterator end$(j)_; typename ParamGenerator::iterator current$(j)_; ]] ParamType current_value_; }; // class CartesianProductGenerator$i::Iterator // No implementation - assignment is unsupported. void operator=(const CartesianProductGenerator$i& other); $for j [[ const ParamGenerator g$(j)_; ]] }; // class CartesianProductGenerator$i ]] // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE. // // Helper classes providing Combine() with polymorphic features. They allow // casting CartesianProductGeneratorN to ParamGenerator if T is // convertible to U. // $range i 2..maxtuple $for i [[ $range j 1..i template <$for j, [[class Generator$j]]> class CartesianProductHolder$i { public: CartesianProductHolder$i($for j, [[const Generator$j& g$j]]) : $for j, [[g$(j)_(g$j)]] {} template <$for j, [[typename T$j]]> operator ParamGenerator< ::std::tr1::tuple<$for j, [[T$j]]> >() const { return ParamGenerator< ::std::tr1::tuple<$for j, [[T$j]]> >( new CartesianProductGenerator$i<$for j, [[T$j]]>( $for j,[[ static_cast >(g$(j)_) ]])); } private: // No implementation - assignment is unsupported. void operator=(const CartesianProductHolder$i& other); $for j [[ const Generator$j g$(j)_; ]] }; // class CartesianProductHolder$i ]] # endif // GTEST_HAS_COMBINE } // namespace internal } // namespace testing #endif // GTEST_HAS_PARAM_TEST #endif // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PARAM_UTIL_GENERATED_H_ ugene-1.9.8/src/libs_3rdparty/gtest/src/gtest/internal/gtest-param-util.h0000644000175000017500000005725211651544307025132 0ustar ilyailya// Copyright 2008 Google Inc. // All Rights Reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Author: vladl@google.com (Vlad Losev) // Type and function utilities for implementing parameterized tests. #ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PARAM_UTIL_H_ #define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PARAM_UTIL_H_ #include #include #include // scripts/fuse_gtest.py depends on gtest's own header being #included // *unconditionally*. Therefore these #includes cannot be moved // inside #if GTEST_HAS_PARAM_TEST. #include "gtest/internal/gtest-internal.h" #include "gtest/internal/gtest-linked_ptr.h" #include "gtest/internal/gtest-port.h" #include "gtest/gtest-printers.h" #if GTEST_HAS_PARAM_TEST namespace testing { namespace internal { // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE. // // Outputs a message explaining invalid registration of different // fixture class for the same test case. This may happen when // TEST_P macro is used to define two tests with the same name // but in different namespaces. GTEST_API_ void ReportInvalidTestCaseType(const char* test_case_name, const char* file, int line); template class ParamGeneratorInterface; template class ParamGenerator; // Interface for iterating over elements provided by an implementation // of ParamGeneratorInterface. template class ParamIteratorInterface { public: virtual ~ParamIteratorInterface() {} // A pointer to the base generator instance. // Used only for the purposes of iterator comparison // to make sure that two iterators belong to the same generator. virtual const ParamGeneratorInterface* BaseGenerator() const = 0; // Advances iterator to point to the next element // provided by the generator. The caller is responsible // for not calling Advance() on an iterator equal to // BaseGenerator()->End(). virtual void Advance() = 0; // Clones the iterator object. Used for implementing copy semantics // of ParamIterator. virtual ParamIteratorInterface* Clone() const = 0; // Dereferences the current iterator and provides (read-only) access // to the pointed value. It is the caller's responsibility not to call // Current() on an iterator equal to BaseGenerator()->End(). // Used for implementing ParamGenerator::operator*(). virtual const T* Current() const = 0; // Determines whether the given iterator and other point to the same // element in the sequence generated by the generator. // Used for implementing ParamGenerator::operator==(). virtual bool Equals(const ParamIteratorInterface& other) const = 0; }; // Class iterating over elements provided by an implementation of // ParamGeneratorInterface. It wraps ParamIteratorInterface // and implements the const forward iterator concept. template class ParamIterator { public: typedef T value_type; typedef const T& reference; typedef ptrdiff_t difference_type; // ParamIterator assumes ownership of the impl_ pointer. ParamIterator(const ParamIterator& other) : impl_(other.impl_->Clone()) {} ParamIterator& operator=(const ParamIterator& other) { if (this != &other) impl_.reset(other.impl_->Clone()); return *this; } const T& operator*() const { return *impl_->Current(); } const T* operator->() const { return impl_->Current(); } // Prefix version of operator++. ParamIterator& operator++() { impl_->Advance(); return *this; } // Postfix version of operator++. ParamIterator operator++(int /*unused*/) { ParamIteratorInterface* clone = impl_->Clone(); impl_->Advance(); return ParamIterator(clone); } bool operator==(const ParamIterator& other) const { return impl_.get() == other.impl_.get() || impl_->Equals(*other.impl_); } bool operator!=(const ParamIterator& other) const { return !(*this == other); } private: friend class ParamGenerator; explicit ParamIterator(ParamIteratorInterface* impl) : impl_(impl) {} scoped_ptr > impl_; }; // ParamGeneratorInterface is the binary interface to access generators // defined in other translation units. template class ParamGeneratorInterface { public: typedef T ParamType; virtual ~ParamGeneratorInterface() {} // Generator interface definition virtual ParamIteratorInterface* Begin() const = 0; virtual ParamIteratorInterface* End() const = 0; }; // Wraps ParamGeneratorInterface and provides general generator syntax // compatible with the STL Container concept. // This class implements copy initialization semantics and the contained // ParamGeneratorInterface instance is shared among all copies // of the original object. This is possible because that instance is immutable. template class ParamGenerator { public: typedef ParamIterator iterator; explicit ParamGenerator(ParamGeneratorInterface* impl) : impl_(impl) {} ParamGenerator(const ParamGenerator& other) : impl_(other.impl_) {} ParamGenerator& operator=(const ParamGenerator& other) { impl_ = other.impl_; return *this; } iterator begin() const { return iterator(impl_->Begin()); } iterator end() const { return iterator(impl_->End()); } private: linked_ptr > impl_; }; // Generates values from a range of two comparable values. Can be used to // generate sequences of user-defined types that implement operator+() and // operator<(). // This class is used in the Range() function. template class RangeGenerator : public ParamGeneratorInterface { public: RangeGenerator(T begin, T end, IncrementT step) : begin_(begin), end_(end), step_(step), end_index_(CalculateEndIndex(begin, end, step)) {} virtual ~RangeGenerator() {} virtual ParamIteratorInterface* Begin() const { return new Iterator(this, begin_, 0, step_); } virtual ParamIteratorInterface* End() const { return new Iterator(this, end_, end_index_, step_); } private: class Iterator : public ParamIteratorInterface { public: Iterator(const ParamGeneratorInterface* base, T value, int index, IncrementT step) : base_(base), value_(value), index_(index), step_(step) {} virtual ~Iterator() {} virtual const ParamGeneratorInterface* BaseGenerator() const { return base_; } virtual void Advance() { value_ = value_ + step_; index_++; } virtual ParamIteratorInterface* Clone() const { return new Iterator(*this); } virtual const T* Current() const { return &value_; } virtual bool Equals(const ParamIteratorInterface& other) const { // Having the same base generator guarantees that the other // iterator is of the same type and we can downcast. GTEST_CHECK_(BaseGenerator() == other.BaseGenerator()) << "The program attempted to compare iterators " << "from different generators." << std::endl; const int other_index = CheckedDowncastToActualType(&other)->index_; return index_ == other_index; } private: Iterator(const Iterator& other) : ParamIteratorInterface(), base_(other.base_), value_(other.value_), index_(other.index_), step_(other.step_) {} // No implementation - assignment is unsupported. void operator=(const Iterator& other); const ParamGeneratorInterface* const base_; T value_; int index_; const IncrementT step_; }; // class RangeGenerator::Iterator static int CalculateEndIndex(const T& begin, const T& end, const IncrementT& step) { int end_index = 0; for (T i = begin; i < end; i = i + step) end_index++; return end_index; } // No implementation - assignment is unsupported. void operator=(const RangeGenerator& other); const T begin_; const T end_; const IncrementT step_; // The index for the end() iterator. All the elements in the generated // sequence are indexed (0-based) to aid iterator comparison. const int end_index_; }; // class RangeGenerator // Generates values from a pair of STL-style iterators. Used in the // ValuesIn() function. The elements are copied from the source range // since the source can be located on the stack, and the generator // is likely to persist beyond that stack frame. template class ValuesInIteratorRangeGenerator : public ParamGeneratorInterface { public: template ValuesInIteratorRangeGenerator(ForwardIterator begin, ForwardIterator end) : container_(begin, end) {} virtual ~ValuesInIteratorRangeGenerator() {} virtual ParamIteratorInterface* Begin() const { return new Iterator(this, container_.begin()); } virtual ParamIteratorInterface* End() const { return new Iterator(this, container_.end()); } private: typedef typename ::std::vector ContainerType; class Iterator : public ParamIteratorInterface { public: Iterator(const ParamGeneratorInterface* base, typename ContainerType::const_iterator iterator) : base_(base), iterator_(iterator) {} virtual ~Iterator() {} virtual const ParamGeneratorInterface* BaseGenerator() const { return base_; } virtual void Advance() { ++iterator_; value_.reset(); } virtual ParamIteratorInterface* Clone() const { return new Iterator(*this); } // We need to use cached value referenced by iterator_ because *iterator_ // can return a temporary object (and of type other then T), so just // having "return &*iterator_;" doesn't work. // value_ is updated here and not in Advance() because Advance() // can advance iterator_ beyond the end of the range, and we cannot // detect that fact. The client code, on the other hand, is // responsible for not calling Current() on an out-of-range iterator. virtual const T* Current() const { if (value_.get() == NULL) value_.reset(new T(*iterator_)); return value_.get(); } virtual bool Equals(const ParamIteratorInterface& other) const { // Having the same base generator guarantees that the other // iterator is of the same type and we can downcast. GTEST_CHECK_(BaseGenerator() == other.BaseGenerator()) << "The program attempted to compare iterators " << "from different generators." << std::endl; return iterator_ == CheckedDowncastToActualType(&other)->iterator_; } private: Iterator(const Iterator& other) // The explicit constructor call suppresses a false warning // emitted by gcc when supplied with the -Wextra option. : ParamIteratorInterface(), base_(other.base_), iterator_(other.iterator_) {} const ParamGeneratorInterface* const base_; typename ContainerType::const_iterator iterator_; // A cached value of *iterator_. We keep it here to allow access by // pointer in the wrapping iterator's operator->(). // value_ needs to be mutable to be accessed in Current(). // Use of scoped_ptr helps manage cached value's lifetime, // which is bound by the lifespan of the iterator itself. mutable scoped_ptr value_; }; // class ValuesInIteratorRangeGenerator::Iterator // No implementation - assignment is unsupported. void operator=(const ValuesInIteratorRangeGenerator& other); const ContainerType container_; }; // class ValuesInIteratorRangeGenerator // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE. // // Stores a parameter value and later creates tests parameterized with that // value. template class ParameterizedTestFactory : public TestFactoryBase { public: typedef typename TestClass::ParamType ParamType; explicit ParameterizedTestFactory(ParamType parameter) : parameter_(parameter) {} virtual Test* CreateTest() { TestClass::SetParam(¶meter_); return new TestClass(); } private: const ParamType parameter_; GTEST_DISALLOW_COPY_AND_ASSIGN_(ParameterizedTestFactory); }; // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE. // // TestMetaFactoryBase is a base class for meta-factories that create // test factories for passing into MakeAndRegisterTestInfo function. template class TestMetaFactoryBase { public: virtual ~TestMetaFactoryBase() {} virtual TestFactoryBase* CreateTestFactory(ParamType parameter) = 0; }; // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE. // // TestMetaFactory creates test factories for passing into // MakeAndRegisterTestInfo function. Since MakeAndRegisterTestInfo receives // ownership of test factory pointer, same factory object cannot be passed // into that method twice. But ParameterizedTestCaseInfo is going to call // it for each Test/Parameter value combination. Thus it needs meta factory // creator class. template class TestMetaFactory : public TestMetaFactoryBase { public: typedef typename TestCase::ParamType ParamType; TestMetaFactory() {} virtual TestFactoryBase* CreateTestFactory(ParamType parameter) { return new ParameterizedTestFactory(parameter); } private: GTEST_DISALLOW_COPY_AND_ASSIGN_(TestMetaFactory); }; // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE. // // ParameterizedTestCaseInfoBase is a generic interface // to ParameterizedTestCaseInfo classes. ParameterizedTestCaseInfoBase // accumulates test information provided by TEST_P macro invocations // and generators provided by INSTANTIATE_TEST_CASE_P macro invocations // and uses that information to register all resulting test instances // in RegisterTests method. The ParameterizeTestCaseRegistry class holds // a collection of pointers to the ParameterizedTestCaseInfo objects // and calls RegisterTests() on each of them when asked. class ParameterizedTestCaseInfoBase { public: virtual ~ParameterizedTestCaseInfoBase() {} // Base part of test case name for display purposes. virtual const string& GetTestCaseName() const = 0; // Test case id to verify identity. virtual TypeId GetTestCaseTypeId() const = 0; // UnitTest class invokes this method to register tests in this // test case right before running them in RUN_ALL_TESTS macro. // This method should not be called more then once on any single // instance of a ParameterizedTestCaseInfoBase derived class. virtual void RegisterTests() = 0; protected: ParameterizedTestCaseInfoBase() {} private: GTEST_DISALLOW_COPY_AND_ASSIGN_(ParameterizedTestCaseInfoBase); }; // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE. // // ParameterizedTestCaseInfo accumulates tests obtained from TEST_P // macro invocations for a particular test case and generators // obtained from INSTANTIATE_TEST_CASE_P macro invocations for that // test case. It registers tests with all values generated by all // generators when asked. template class ParameterizedTestCaseInfo : public ParameterizedTestCaseInfoBase { public: // ParamType and GeneratorCreationFunc are private types but are required // for declarations of public methods AddTestPattern() and // AddTestCaseInstantiation(). typedef typename TestCase::ParamType ParamType; // A function that returns an instance of appropriate generator type. typedef ParamGenerator(GeneratorCreationFunc)(); explicit ParameterizedTestCaseInfo(const char* name) : test_case_name_(name) {} // Test case base name for display purposes. virtual const string& GetTestCaseName() const { return test_case_name_; } // Test case id to verify identity. virtual TypeId GetTestCaseTypeId() const { return GetTypeId(); } // TEST_P macro uses AddTestPattern() to record information // about a single test in a LocalTestInfo structure. // test_case_name is the base name of the test case (without invocation // prefix). test_base_name is the name of an individual test without // parameter index. For the test SequenceA/FooTest.DoBar/1 FooTest is // test case base name and DoBar is test base name. void AddTestPattern(const char* test_case_name, const char* test_base_name, TestMetaFactoryBase* meta_factory) { tests_.push_back(linked_ptr(new TestInfo(test_case_name, test_base_name, meta_factory))); } // INSTANTIATE_TEST_CASE_P macro uses AddGenerator() to record information // about a generator. int AddTestCaseInstantiation(const string& instantiation_name, GeneratorCreationFunc* func, const char* /* file */, int /* line */) { instantiations_.push_back(::std::make_pair(instantiation_name, func)); return 0; // Return value used only to run this method in namespace scope. } // UnitTest class invokes this method to register tests in this test case // test cases right before running tests in RUN_ALL_TESTS macro. // This method should not be called more then once on any single // instance of a ParameterizedTestCaseInfoBase derived class. // UnitTest has a guard to prevent from calling this method more then once. virtual void RegisterTests() { for (typename TestInfoContainer::iterator test_it = tests_.begin(); test_it != tests_.end(); ++test_it) { linked_ptr test_info = *test_it; for (typename InstantiationContainer::iterator gen_it = instantiations_.begin(); gen_it != instantiations_.end(); ++gen_it) { const string& instantiation_name = gen_it->first; ParamGenerator generator((*gen_it->second)()); Message test_case_name_stream; if ( !instantiation_name.empty() ) test_case_name_stream << instantiation_name << "/"; test_case_name_stream << test_info->test_case_base_name; int i = 0; for (typename ParamGenerator::iterator param_it = generator.begin(); param_it != generator.end(); ++param_it, ++i) { Message test_name_stream; test_name_stream << test_info->test_base_name << "/" << i; MakeAndRegisterTestInfo( test_case_name_stream.GetString().c_str(), test_name_stream.GetString().c_str(), NULL, // No type parameter. PrintToString(*param_it).c_str(), GetTestCaseTypeId(), TestCase::SetUpTestCase, TestCase::TearDownTestCase, test_info->test_meta_factory->CreateTestFactory(*param_it)); } // for param_it } // for gen_it } // for test_it } // RegisterTests private: // LocalTestInfo structure keeps information about a single test registered // with TEST_P macro. struct TestInfo { TestInfo(const char* a_test_case_base_name, const char* a_test_base_name, TestMetaFactoryBase* a_test_meta_factory) : test_case_base_name(a_test_case_base_name), test_base_name(a_test_base_name), test_meta_factory(a_test_meta_factory) {} const string test_case_base_name; const string test_base_name; const scoped_ptr > test_meta_factory; }; typedef ::std::vector > TestInfoContainer; // Keeps pairs of // received from INSTANTIATE_TEST_CASE_P macros. typedef ::std::vector > InstantiationContainer; const string test_case_name_; TestInfoContainer tests_; InstantiationContainer instantiations_; GTEST_DISALLOW_COPY_AND_ASSIGN_(ParameterizedTestCaseInfo); }; // class ParameterizedTestCaseInfo // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE. // // ParameterizedTestCaseRegistry contains a map of ParameterizedTestCaseInfoBase // classes accessed by test case names. TEST_P and INSTANTIATE_TEST_CASE_P // macros use it to locate their corresponding ParameterizedTestCaseInfo // descriptors. class ParameterizedTestCaseRegistry { public: ParameterizedTestCaseRegistry() {} ~ParameterizedTestCaseRegistry() { for (TestCaseInfoContainer::iterator it = test_case_infos_.begin(); it != test_case_infos_.end(); ++it) { delete *it; } } // Looks up or creates and returns a structure containing information about // tests and instantiations of a particular test case. template ParameterizedTestCaseInfo* GetTestCasePatternHolder( const char* test_case_name, const char* file, int line) { ParameterizedTestCaseInfo* typed_test_info = NULL; for (TestCaseInfoContainer::iterator it = test_case_infos_.begin(); it != test_case_infos_.end(); ++it) { if ((*it)->GetTestCaseName() == test_case_name) { if ((*it)->GetTestCaseTypeId() != GetTypeId()) { // Complain about incorrect usage of Google Test facilities // and terminate the program since we cannot guaranty correct // test case setup and tear-down in this case. ReportInvalidTestCaseType(test_case_name, file, line); posix::Abort(); } else { // At this point we are sure that the object we found is of the same // type we are looking for, so we downcast it to that type // without further checks. typed_test_info = CheckedDowncastToActualType< ParameterizedTestCaseInfo >(*it); } break; } } if (typed_test_info == NULL) { typed_test_info = new ParameterizedTestCaseInfo(test_case_name); test_case_infos_.push_back(typed_test_info); } return typed_test_info; } void RegisterTests() { for (TestCaseInfoContainer::iterator it = test_case_infos_.begin(); it != test_case_infos_.end(); ++it) { (*it)->RegisterTests(); } } private: typedef ::std::vector TestCaseInfoContainer; TestCaseInfoContainer test_case_infos_; GTEST_DISALLOW_COPY_AND_ASSIGN_(ParameterizedTestCaseRegistry); }; } // namespace internal } // namespace testing #endif // GTEST_HAS_PARAM_TEST #endif // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PARAM_UTIL_H_ ugene-1.9.8/src/libs_3rdparty/gtest/src/gtest/internal/gtest-internal.h0000644000175000017500000013433511651544307024671 0ustar ilyailya// Copyright 2005, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Authors: wan@google.com (Zhanyong Wan), eefacm@gmail.com (Sean Mcafee) // // The Google C++ Testing Framework (Google Test) // // This header file declares functions and macros used internally by // Google Test. They are subject to change without notice. #ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_INTERNAL_H_ #define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_INTERNAL_H_ #include "gtest/internal/gtest-port.h" #if GTEST_OS_LINUX # include # include # include # include #endif // GTEST_OS_LINUX #include #include #include #include #include #include "gtest/internal/gtest-string.h" #include "gtest/internal/gtest-filepath.h" #include "gtest/internal/gtest-type-util.h" // Due to C++ preprocessor weirdness, we need double indirection to // concatenate two tokens when one of them is __LINE__. Writing // // foo ## __LINE__ // // will result in the token foo__LINE__, instead of foo followed by // the current line number. For more details, see // http://www.parashift.com/c++-faq-lite/misc-technical-issues.html#faq-39.6 #define GTEST_CONCAT_TOKEN_(foo, bar) GTEST_CONCAT_TOKEN_IMPL_(foo, bar) #define GTEST_CONCAT_TOKEN_IMPL_(foo, bar) foo ## bar // Google Test defines the testing::Message class to allow construction of // test messages via the << operator. The idea is that anything // streamable to std::ostream can be streamed to a testing::Message. // This allows a user to use his own types in Google Test assertions by // overloading the << operator. // // util/gtl/stl_logging-inl.h overloads << for STL containers. These // overloads cannot be defined in the std namespace, as that will be // undefined behavior. Therefore, they are defined in the global // namespace instead. // // C++'s symbol lookup rule (i.e. Koenig lookup) says that these // overloads are visible in either the std namespace or the global // namespace, but not other namespaces, including the testing // namespace which Google Test's Message class is in. // // To allow STL containers (and other types that has a << operator // defined in the global namespace) to be used in Google Test assertions, // testing::Message must access the custom << operator from the global // namespace. Hence this helper function. // // Note: Jeffrey Yasskin suggested an alternative fix by "using // ::operator<<;" in the definition of Message's operator<<. That fix // doesn't require a helper function, but unfortunately doesn't // compile with MSVC. template inline void GTestStreamToHelper(std::ostream* os, const T& val) { *os << val; } class ProtocolMessage; namespace proto2 { class Message; } namespace testing { // Forward declarations. class AssertionResult; // Result of an assertion. class Message; // Represents a failure message. class Test; // Represents a test. class TestInfo; // Information about a test. class TestPartResult; // Result of a test part. class UnitTest; // A collection of test cases. template ::std::string PrintToString(const T& value); namespace internal { struct TraceInfo; // Information about a trace point. class ScopedTrace; // Implements scoped trace. class TestInfoImpl; // Opaque implementation of TestInfo class UnitTestImpl; // Opaque implementation of UnitTest // How many times InitGoogleTest() has been called. extern int g_init_gtest_count; // The text used in failure messages to indicate the start of the // stack trace. GTEST_API_ extern const char kStackTraceMarker[]; // A secret type that Google Test users don't know about. It has no // definition on purpose. Therefore it's impossible to create a // Secret object, which is what we want. class Secret; // Two overloaded helpers for checking at compile time whether an // expression is a null pointer literal (i.e. NULL or any 0-valued // compile-time integral constant). Their return values have // different sizes, so we can use sizeof() to test which version is // picked by the compiler. These helpers have no implementations, as // we only need their signatures. // // Given IsNullLiteralHelper(x), the compiler will pick the first // version if x can be implicitly converted to Secret*, and pick the // second version otherwise. Since Secret is a secret and incomplete // type, the only expression a user can write that has type Secret* is // a null pointer literal. Therefore, we know that x is a null // pointer literal if and only if the first version is picked by the // compiler. char IsNullLiteralHelper(Secret* p); char (&IsNullLiteralHelper(...))[2]; // NOLINT // A compile-time bool constant that is true if and only if x is a // null pointer literal (i.e. NULL or any 0-valued compile-time // integral constant). #ifdef GTEST_ELLIPSIS_NEEDS_POD_ // We lose support for NULL detection where the compiler doesn't like // passing non-POD classes through ellipsis (...). # define GTEST_IS_NULL_LITERAL_(x) false #else # define GTEST_IS_NULL_LITERAL_(x) \ (sizeof(::testing::internal::IsNullLiteralHelper(x)) == 1) #endif // GTEST_ELLIPSIS_NEEDS_POD_ // Appends the user-supplied message to the Google-Test-generated message. GTEST_API_ String AppendUserMessage(const String& gtest_msg, const Message& user_msg); // A helper class for creating scoped traces in user programs. class GTEST_API_ ScopedTrace { public: // The c'tor pushes the given source file location and message onto // a trace stack maintained by Google Test. ScopedTrace(const char* file, int line, const Message& message); // The d'tor pops the info pushed by the c'tor. // // Note that the d'tor is not virtual in order to be efficient. // Don't inherit from ScopedTrace! ~ScopedTrace(); private: GTEST_DISALLOW_COPY_AND_ASSIGN_(ScopedTrace); } GTEST_ATTRIBUTE_UNUSED_; // A ScopedTrace object does its job in its // c'tor and d'tor. Therefore it doesn't // need to be used otherwise. // Converts a streamable value to a String. A NULL pointer is // converted to "(null)". When the input value is a ::string, // ::std::string, ::wstring, or ::std::wstring object, each NUL // character in it is replaced with "\\0". // Declared here but defined in gtest.h, so that it has access // to the definition of the Message class, required by the ARM // compiler. template String StreamableToString(const T& streamable); // The Symbian compiler has a bug that prevents it from selecting the // correct overload of FormatForComparisonFailureMessage (see below) // unless we pass the first argument by reference. If we do that, // however, Visual Age C++ 10.1 generates a compiler error. Therefore // we only apply the work-around for Symbian. #if defined(__SYMBIAN32__) # define GTEST_CREF_WORKAROUND_ const& #else # define GTEST_CREF_WORKAROUND_ #endif // When this operand is a const char* or char*, if the other operand // is a ::std::string or ::string, we print this operand as a C string // rather than a pointer (we do the same for wide strings); otherwise // we print it as a pointer to be safe. // This internal macro is used to avoid duplicated code. #define GTEST_FORMAT_IMPL_(operand2_type, operand1_printer)\ inline String FormatForComparisonFailureMessage(\ operand2_type::value_type* GTEST_CREF_WORKAROUND_ str, \ const operand2_type& /*operand2*/) {\ return operand1_printer(str);\ }\ inline String FormatForComparisonFailureMessage(\ const operand2_type::value_type* GTEST_CREF_WORKAROUND_ str, \ const operand2_type& /*operand2*/) {\ return operand1_printer(str);\ } GTEST_FORMAT_IMPL_(::std::string, String::ShowCStringQuoted) #if GTEST_HAS_STD_WSTRING GTEST_FORMAT_IMPL_(::std::wstring, String::ShowWideCStringQuoted) #endif // GTEST_HAS_STD_WSTRING #if GTEST_HAS_GLOBAL_STRING GTEST_FORMAT_IMPL_(::string, String::ShowCStringQuoted) #endif // GTEST_HAS_GLOBAL_STRING #if GTEST_HAS_GLOBAL_WSTRING GTEST_FORMAT_IMPL_(::wstring, String::ShowWideCStringQuoted) #endif // GTEST_HAS_GLOBAL_WSTRING #undef GTEST_FORMAT_IMPL_ // The next four overloads handle the case where the operand being // printed is a char/wchar_t pointer and the other operand is not a // string/wstring object. In such cases, we just print the operand as // a pointer to be safe. #define GTEST_FORMAT_CHAR_PTR_IMPL_(CharType) \ template \ String FormatForComparisonFailureMessage(CharType* GTEST_CREF_WORKAROUND_ p, \ const T&) { \ return PrintToString(static_cast(p)); \ } GTEST_FORMAT_CHAR_PTR_IMPL_(char) GTEST_FORMAT_CHAR_PTR_IMPL_(const char) GTEST_FORMAT_CHAR_PTR_IMPL_(wchar_t) GTEST_FORMAT_CHAR_PTR_IMPL_(const wchar_t) #undef GTEST_FORMAT_CHAR_PTR_IMPL_ // Constructs and returns the message for an equality assertion // (e.g. ASSERT_EQ, EXPECT_STREQ, etc) failure. // // The first four parameters are the expressions used in the assertion // and their values, as strings. For example, for ASSERT_EQ(foo, bar) // where foo is 5 and bar is 6, we have: // // expected_expression: "foo" // actual_expression: "bar" // expected_value: "5" // actual_value: "6" // // The ignoring_case parameter is true iff the assertion is a // *_STRCASEEQ*. When it's true, the string " (ignoring case)" will // be inserted into the message. GTEST_API_ AssertionResult EqFailure(const char* expected_expression, const char* actual_expression, const String& expected_value, const String& actual_value, bool ignoring_case); // Constructs a failure message for Boolean assertions such as EXPECT_TRUE. GTEST_API_ String GetBoolAssertionFailureMessage( const AssertionResult& assertion_result, const char* expression_text, const char* actual_predicate_value, const char* expected_predicate_value); // This template class represents an IEEE floating-point number // (either single-precision or double-precision, depending on the // template parameters). // // The purpose of this class is to do more sophisticated number // comparison. (Due to round-off error, etc, it's very unlikely that // two floating-points will be equal exactly. Hence a naive // comparison by the == operation often doesn't work.) // // Format of IEEE floating-point: // // The most-significant bit being the leftmost, an IEEE // floating-point looks like // // sign_bit exponent_bits fraction_bits // // Here, sign_bit is a single bit that designates the sign of the // number. // // For float, there are 8 exponent bits and 23 fraction bits. // // For double, there are 11 exponent bits and 52 fraction bits. // // More details can be found at // http://en.wikipedia.org/wiki/IEEE_floating-point_standard. // // Template parameter: // // RawType: the raw floating-point type (either float or double) template class FloatingPoint { public: // Defines the unsigned integer type that has the same size as the // floating point number. typedef typename TypeWithSize::UInt Bits; // Constants. // # of bits in a number. static const size_t kBitCount = 8*sizeof(RawType); // # of fraction bits in a number. static const size_t kFractionBitCount = std::numeric_limits::digits - 1; // # of exponent bits in a number. static const size_t kExponentBitCount = kBitCount - 1 - kFractionBitCount; // The mask for the sign bit. static const Bits kSignBitMask = static_cast(1) << (kBitCount - 1); // The mask for the fraction bits. static const Bits kFractionBitMask = ~static_cast(0) >> (kExponentBitCount + 1); // The mask for the exponent bits. static const Bits kExponentBitMask = ~(kSignBitMask | kFractionBitMask); // How many ULP's (Units in the Last Place) we want to tolerate when // comparing two numbers. The larger the value, the more error we // allow. A 0 value means that two numbers must be exactly the same // to be considered equal. // // The maximum error of a single floating-point operation is 0.5 // units in the last place. On Intel CPU's, all floating-point // calculations are done with 80-bit precision, while double has 64 // bits. Therefore, 4 should be enough for ordinary use. // // See the following article for more details on ULP: // http://www.cygnus-software.com/papers/comparingfloats/comparingfloats.htm. static const size_t kMaxUlps = 4; // Constructs a FloatingPoint from a raw floating-point number. // // On an Intel CPU, passing a non-normalized NAN (Not a Number) // around may change its bits, although the new value is guaranteed // to be also a NAN. Therefore, don't expect this constructor to // preserve the bits in x when x is a NAN. explicit FloatingPoint(const RawType& x) { u_.value_ = x; } // Static methods // Reinterprets a bit pattern as a floating-point number. // // This function is needed to test the AlmostEquals() method. static RawType ReinterpretBits(const Bits bits) { FloatingPoint fp(0); fp.u_.bits_ = bits; return fp.u_.value_; } // Returns the floating-point number that represent positive infinity. static RawType Infinity() { return ReinterpretBits(kExponentBitMask); } // Non-static methods // Returns the bits that represents this number. const Bits &bits() const { return u_.bits_; } // Returns the exponent bits of this number. Bits exponent_bits() const { return kExponentBitMask & u_.bits_; } // Returns the fraction bits of this number. Bits fraction_bits() const { return kFractionBitMask & u_.bits_; } // Returns the sign bit of this number. Bits sign_bit() const { return kSignBitMask & u_.bits_; } // Returns true iff this is NAN (not a number). bool is_nan() const { // It's a NAN if the exponent bits are all ones and the fraction // bits are not entirely zeros. return (exponent_bits() == kExponentBitMask) && (fraction_bits() != 0); } // Returns true iff this number is at most kMaxUlps ULP's away from // rhs. In particular, this function: // // - returns false if either number is (or both are) NAN. // - treats really large numbers as almost equal to infinity. // - thinks +0.0 and -0.0 are 0 DLP's apart. bool AlmostEquals(const FloatingPoint& rhs) const { // The IEEE standard says that any comparison operation involving // a NAN must return false. if (is_nan() || rhs.is_nan()) return false; return DistanceBetweenSignAndMagnitudeNumbers(u_.bits_, rhs.u_.bits_) <= kMaxUlps; } private: // The data type used to store the actual floating-point number. union FloatingPointUnion { RawType value_; // The raw floating-point number. Bits bits_; // The bits that represent the number. }; // Converts an integer from the sign-and-magnitude representation to // the biased representation. More precisely, let N be 2 to the // power of (kBitCount - 1), an integer x is represented by the // unsigned number x + N. // // For instance, // // -N + 1 (the most negative number representable using // sign-and-magnitude) is represented by 1; // 0 is represented by N; and // N - 1 (the biggest number representable using // sign-and-magnitude) is represented by 2N - 1. // // Read http://en.wikipedia.org/wiki/Signed_number_representations // for more details on signed number representations. static Bits SignAndMagnitudeToBiased(const Bits &sam) { if (kSignBitMask & sam) { // sam represents a negative number. return ~sam + 1; } else { // sam represents a positive number. return kSignBitMask | sam; } } // Given two numbers in the sign-and-magnitude representation, // returns the distance between them as an unsigned number. static Bits DistanceBetweenSignAndMagnitudeNumbers(const Bits &sam1, const Bits &sam2) { const Bits biased1 = SignAndMagnitudeToBiased(sam1); const Bits biased2 = SignAndMagnitudeToBiased(sam2); return (biased1 >= biased2) ? (biased1 - biased2) : (biased2 - biased1); } FloatingPointUnion u_; }; // Typedefs the instances of the FloatingPoint template class that we // care to use. typedef FloatingPoint Float; typedef FloatingPoint Double; // In order to catch the mistake of putting tests that use different // test fixture classes in the same test case, we need to assign // unique IDs to fixture classes and compare them. The TypeId type is // used to hold such IDs. The user should treat TypeId as an opaque // type: the only operation allowed on TypeId values is to compare // them for equality using the == operator. typedef const void* TypeId; template class TypeIdHelper { public: // dummy_ must not have a const type. Otherwise an overly eager // compiler (e.g. MSVC 7.1 & 8.0) may try to merge // TypeIdHelper::dummy_ for different Ts as an "optimization". static bool dummy_; }; template bool TypeIdHelper::dummy_ = false; // GetTypeId() returns the ID of type T. Different values will be // returned for different types. Calling the function twice with the // same type argument is guaranteed to return the same ID. template TypeId GetTypeId() { // The compiler is required to allocate a different // TypeIdHelper::dummy_ variable for each T used to instantiate // the template. Therefore, the address of dummy_ is guaranteed to // be unique. return &(TypeIdHelper::dummy_); } // Returns the type ID of ::testing::Test. Always call this instead // of GetTypeId< ::testing::Test>() to get the type ID of // ::testing::Test, as the latter may give the wrong result due to a // suspected linker bug when compiling Google Test as a Mac OS X // framework. GTEST_API_ TypeId GetTestTypeId(); // Defines the abstract factory interface that creates instances // of a Test object. class TestFactoryBase { public: virtual ~TestFactoryBase() {} // Creates a test instance to run. The instance is both created and destroyed // within TestInfoImpl::Run() virtual Test* CreateTest() = 0; protected: TestFactoryBase() {} private: GTEST_DISALLOW_COPY_AND_ASSIGN_(TestFactoryBase); }; // This class provides implementation of TeastFactoryBase interface. // It is used in TEST and TEST_F macros. template class TestFactoryImpl : public TestFactoryBase { public: virtual Test* CreateTest() { return new TestClass; } }; #if GTEST_OS_WINDOWS // Predicate-formatters for implementing the HRESULT checking macros // {ASSERT|EXPECT}_HRESULT_{SUCCEEDED|FAILED} // We pass a long instead of HRESULT to avoid causing an // include dependency for the HRESULT type. GTEST_API_ AssertionResult IsHRESULTSuccess(const char* expr, long hr); // NOLINT GTEST_API_ AssertionResult IsHRESULTFailure(const char* expr, long hr); // NOLINT #endif // GTEST_OS_WINDOWS // Types of SetUpTestCase() and TearDownTestCase() functions. typedef void (*SetUpTestCaseFunc)(); typedef void (*TearDownTestCaseFunc)(); // Creates a new TestInfo object and registers it with Google Test; // returns the created object. // // Arguments: // // test_case_name: name of the test case // name: name of the test // type_param the name of the test's type parameter, or NULL if // this is not a typed or a type-parameterized test. // value_param text representation of the test's value parameter, // or NULL if this is not a type-parameterized test. // fixture_class_id: ID of the test fixture class // set_up_tc: pointer to the function that sets up the test case // tear_down_tc: pointer to the function that tears down the test case // factory: pointer to the factory that creates a test object. // The newly created TestInfo instance will assume // ownership of the factory object. GTEST_API_ TestInfo* MakeAndRegisterTestInfo( const char* test_case_name, const char* name, const char* type_param, const char* value_param, TypeId fixture_class_id, SetUpTestCaseFunc set_up_tc, TearDownTestCaseFunc tear_down_tc, TestFactoryBase* factory); // If *pstr starts with the given prefix, modifies *pstr to be right // past the prefix and returns true; otherwise leaves *pstr unchanged // and returns false. None of pstr, *pstr, and prefix can be NULL. GTEST_API_ bool SkipPrefix(const char* prefix, const char** pstr); #if GTEST_HAS_TYPED_TEST || GTEST_HAS_TYPED_TEST_P // State of the definition of a type-parameterized test case. class GTEST_API_ TypedTestCasePState { public: TypedTestCasePState() : registered_(false) {} // Adds the given test name to defined_test_names_ and return true // if the test case hasn't been registered; otherwise aborts the // program. bool AddTestName(const char* file, int line, const char* case_name, const char* test_name) { if (registered_) { fprintf(stderr, "%s Test %s must be defined before " "REGISTER_TYPED_TEST_CASE_P(%s, ...).\n", FormatFileLocation(file, line).c_str(), test_name, case_name); fflush(stderr); posix::Abort(); } defined_test_names_.insert(test_name); return true; } // Verifies that registered_tests match the test names in // defined_test_names_; returns registered_tests if successful, or // aborts the program otherwise. const char* VerifyRegisteredTestNames( const char* file, int line, const char* registered_tests); private: bool registered_; ::std::set defined_test_names_; }; // Skips to the first non-space char after the first comma in 'str'; // returns NULL if no comma is found in 'str'. inline const char* SkipComma(const char* str) { const char* comma = strchr(str, ','); if (comma == NULL) { return NULL; } while (IsSpace(*(++comma))) {} return comma; } // Returns the prefix of 'str' before the first comma in it; returns // the entire string if it contains no comma. inline String GetPrefixUntilComma(const char* str) { const char* comma = strchr(str, ','); return comma == NULL ? String(str) : String(str, comma - str); } // TypeParameterizedTest::Register() // registers a list of type-parameterized tests with Google Test. The // return value is insignificant - we just need to return something // such that we can call this function in a namespace scope. // // Implementation note: The GTEST_TEMPLATE_ macro declares a template // template parameter. It's defined in gtest-type-util.h. template class TypeParameterizedTest { public: // 'index' is the index of the test in the type list 'Types' // specified in INSTANTIATE_TYPED_TEST_CASE_P(Prefix, TestCase, // Types). Valid values for 'index' are [0, N - 1] where N is the // length of Types. static bool Register(const char* prefix, const char* case_name, const char* test_names, int index) { typedef typename Types::Head Type; typedef Fixture FixtureClass; typedef typename GTEST_BIND_(TestSel, Type) TestClass; // First, registers the first type-parameterized test in the type // list. MakeAndRegisterTestInfo( String::Format("%s%s%s/%d", prefix, prefix[0] == '\0' ? "" : "/", case_name, index).c_str(), GetPrefixUntilComma(test_names).c_str(), GetTypeName().c_str(), NULL, // No value parameter. GetTypeId(), TestClass::SetUpTestCase, TestClass::TearDownTestCase, new TestFactoryImpl); // Next, recurses (at compile time) with the tail of the type list. return TypeParameterizedTest ::Register(prefix, case_name, test_names, index + 1); } }; // The base case for the compile time recursion. template class TypeParameterizedTest { public: static bool Register(const char* /*prefix*/, const char* /*case_name*/, const char* /*test_names*/, int /*index*/) { return true; } }; // TypeParameterizedTestCase::Register() // registers *all combinations* of 'Tests' and 'Types' with Google // Test. The return value is insignificant - we just need to return // something such that we can call this function in a namespace scope. template class TypeParameterizedTestCase { public: static bool Register(const char* prefix, const char* case_name, const char* test_names) { typedef typename Tests::Head Head; // First, register the first test in 'Test' for each type in 'Types'. TypeParameterizedTest::Register( prefix, case_name, test_names, 0); // Next, recurses (at compile time) with the tail of the test list. return TypeParameterizedTestCase ::Register(prefix, case_name, SkipComma(test_names)); } }; // The base case for the compile time recursion. template class TypeParameterizedTestCase { public: static bool Register(const char* /*prefix*/, const char* /*case_name*/, const char* /*test_names*/) { return true; } }; #endif // GTEST_HAS_TYPED_TEST || GTEST_HAS_TYPED_TEST_P // Returns the current OS stack trace as a String. // // The maximum number of stack frames to be included is specified by // the gtest_stack_trace_depth flag. The skip_count parameter // specifies the number of top frames to be skipped, which doesn't // count against the number of frames to be included. // // For example, if Foo() calls Bar(), which in turn calls // GetCurrentOsStackTraceExceptTop(..., 1), Foo() will be included in // the trace but Bar() and GetCurrentOsStackTraceExceptTop() won't. GTEST_API_ String GetCurrentOsStackTraceExceptTop(UnitTest* unit_test, int skip_count); // Helpers for suppressing warnings on unreachable code or constant // condition. // Always returns true. GTEST_API_ bool AlwaysTrue(); // Always returns false. inline bool AlwaysFalse() { return !AlwaysTrue(); } // Helper for suppressing false warning from Clang on a const char* // variable declared in a conditional expression always being NULL in // the else branch. struct GTEST_API_ ConstCharPtr { ConstCharPtr(const char* str) : value(str) {} operator bool() const { return true; } const char* value; }; // A simple Linear Congruential Generator for generating random // numbers with a uniform distribution. Unlike rand() and srand(), it // doesn't use global state (and therefore can't interfere with user // code). Unlike rand_r(), it's portable. An LCG isn't very random, // but it's good enough for our purposes. class GTEST_API_ Random { public: static const UInt32 kMaxRange = 1u << 31; explicit Random(UInt32 seed) : state_(seed) {} void Reseed(UInt32 seed) { state_ = seed; } // Generates a random number from [0, range). Crashes if 'range' is // 0 or greater than kMaxRange. UInt32 Generate(UInt32 range); private: UInt32 state_; GTEST_DISALLOW_COPY_AND_ASSIGN_(Random); }; // Defining a variable of type CompileAssertTypesEqual will cause a // compiler error iff T1 and T2 are different types. template struct CompileAssertTypesEqual; template struct CompileAssertTypesEqual { }; // Removes the reference from a type if it is a reference type, // otherwise leaves it unchanged. This is the same as // tr1::remove_reference, which is not widely available yet. template struct RemoveReference { typedef T type; }; // NOLINT template struct RemoveReference { typedef T type; }; // NOLINT // A handy wrapper around RemoveReference that works when the argument // T depends on template parameters. #define GTEST_REMOVE_REFERENCE_(T) \ typename ::testing::internal::RemoveReference::type // Removes const from a type if it is a const type, otherwise leaves // it unchanged. This is the same as tr1::remove_const, which is not // widely available yet. template struct RemoveConst { typedef T type; }; // NOLINT template struct RemoveConst { typedef T type; }; // NOLINT // MSVC 8.0, Sun C++, and IBM XL C++ have a bug which causes the above // definition to fail to remove the const in 'const int[3]' and 'const // char[3][4]'. The following specialization works around the bug. // However, it causes trouble with GCC and thus needs to be // conditionally compiled. #if defined(_MSC_VER) || defined(__SUNPRO_CC) || defined(__IBMCPP__) template struct RemoveConst { typedef typename RemoveConst::type type[N]; }; #endif // A handy wrapper around RemoveConst that works when the argument // T depends on template parameters. #define GTEST_REMOVE_CONST_(T) \ typename ::testing::internal::RemoveConst::type // Turns const U&, U&, const U, and U all into U. #define GTEST_REMOVE_REFERENCE_AND_CONST_(T) \ GTEST_REMOVE_CONST_(GTEST_REMOVE_REFERENCE_(T)) // Adds reference to a type if it is not a reference type, // otherwise leaves it unchanged. This is the same as // tr1::add_reference, which is not widely available yet. template struct AddReference { typedef T& type; }; // NOLINT template struct AddReference { typedef T& type; }; // NOLINT // A handy wrapper around AddReference that works when the argument T // depends on template parameters. #define GTEST_ADD_REFERENCE_(T) \ typename ::testing::internal::AddReference::type // Adds a reference to const on top of T as necessary. For example, // it transforms // // char ==> const char& // const char ==> const char& // char& ==> const char& // const char& ==> const char& // // The argument T must depend on some template parameters. #define GTEST_REFERENCE_TO_CONST_(T) \ GTEST_ADD_REFERENCE_(const GTEST_REMOVE_REFERENCE_(T)) // ImplicitlyConvertible::value is a compile-time bool // constant that's true iff type From can be implicitly converted to // type To. template class ImplicitlyConvertible { private: // We need the following helper functions only for their types. // They have no implementations. // MakeFrom() is an expression whose type is From. We cannot simply // use From(), as the type From may not have a public default // constructor. static From MakeFrom(); // These two functions are overloaded. Given an expression // Helper(x), the compiler will pick the first version if x can be // implicitly converted to type To; otherwise it will pick the // second version. // // The first version returns a value of size 1, and the second // version returns a value of size 2. Therefore, by checking the // size of Helper(x), which can be done at compile time, we can tell // which version of Helper() is used, and hence whether x can be // implicitly converted to type To. static char Helper(To); static char (&Helper(...))[2]; // NOLINT // We have to put the 'public' section after the 'private' section, // or MSVC refuses to compile the code. public: // MSVC warns about implicitly converting from double to int for // possible loss of data, so we need to temporarily disable the // warning. #ifdef _MSC_VER # pragma warning(push) // Saves the current warning state. # pragma warning(disable:4244) // Temporarily disables warning 4244. static const bool value = sizeof(Helper(ImplicitlyConvertible::MakeFrom())) == 1; # pragma warning(pop) // Restores the warning state. #elif defined(__BORLANDC__) // C++Builder cannot use member overload resolution during template // instantiation. The simplest workaround is to use its C++0x type traits // functions (C++Builder 2009 and above only). static const bool value = __is_convertible(From, To); #else static const bool value = sizeof(Helper(ImplicitlyConvertible::MakeFrom())) == 1; #endif // _MSV_VER }; template const bool ImplicitlyConvertible::value; // IsAProtocolMessage::value is a compile-time bool constant that's // true iff T is type ProtocolMessage, proto2::Message, or a subclass // of those. template struct IsAProtocolMessage : public bool_constant< ImplicitlyConvertible::value || ImplicitlyConvertible::value> { }; // When the compiler sees expression IsContainerTest(0), if C is an // STL-style container class, the first overload of IsContainerTest // will be viable (since both C::iterator* and C::const_iterator* are // valid types and NULL can be implicitly converted to them). It will // be picked over the second overload as 'int' is a perfect match for // the type of argument 0. If C::iterator or C::const_iterator is not // a valid type, the first overload is not viable, and the second // overload will be picked. Therefore, we can determine whether C is // a container class by checking the type of IsContainerTest(0). // The value of the expression is insignificant. // // Note that we look for both C::iterator and C::const_iterator. The // reason is that C++ injects the name of a class as a member of the // class itself (e.g. you can refer to class iterator as either // 'iterator' or 'iterator::iterator'). If we look for C::iterator // only, for example, we would mistakenly think that a class named // iterator is an STL container. // // Also note that the simpler approach of overloading // IsContainerTest(typename C::const_iterator*) and // IsContainerTest(...) doesn't work with Visual Age C++ and Sun C++. typedef int IsContainer; template IsContainer IsContainerTest(int /* dummy */, typename C::iterator* /* it */ = NULL, typename C::const_iterator* /* const_it */ = NULL) { return 0; } typedef char IsNotContainer; template IsNotContainer IsContainerTest(long /* dummy */) { return '\0'; } // EnableIf::type is void when 'Cond' is true, and // undefined when 'Cond' is false. To use SFINAE to make a function // overload only apply when a particular expression is true, add // "typename EnableIf::type* = 0" as the last parameter. template struct EnableIf; template<> struct EnableIf { typedef void type; }; // NOLINT // Utilities for native arrays. // ArrayEq() compares two k-dimensional native arrays using the // elements' operator==, where k can be any integer >= 0. When k is // 0, ArrayEq() degenerates into comparing a single pair of values. template bool ArrayEq(const T* lhs, size_t size, const U* rhs); // This generic version is used when k is 0. template inline bool ArrayEq(const T& lhs, const U& rhs) { return lhs == rhs; } // This overload is used when k >= 1. template inline bool ArrayEq(const T(&lhs)[N], const U(&rhs)[N]) { return internal::ArrayEq(lhs, N, rhs); } // This helper reduces code bloat. If we instead put its logic inside // the previous ArrayEq() function, arrays with different sizes would // lead to different copies of the template code. template bool ArrayEq(const T* lhs, size_t size, const U* rhs) { for (size_t i = 0; i != size; i++) { if (!internal::ArrayEq(lhs[i], rhs[i])) return false; } return true; } // Finds the first element in the iterator range [begin, end) that // equals elem. Element may be a native array type itself. template Iter ArrayAwareFind(Iter begin, Iter end, const Element& elem) { for (Iter it = begin; it != end; ++it) { if (internal::ArrayEq(*it, elem)) return it; } return end; } // CopyArray() copies a k-dimensional native array using the elements' // operator=, where k can be any integer >= 0. When k is 0, // CopyArray() degenerates into copying a single value. template void CopyArray(const T* from, size_t size, U* to); // This generic version is used when k is 0. template inline void CopyArray(const T& from, U* to) { *to = from; } // This overload is used when k >= 1. template inline void CopyArray(const T(&from)[N], U(*to)[N]) { internal::CopyArray(from, N, *to); } // This helper reduces code bloat. If we instead put its logic inside // the previous CopyArray() function, arrays with different sizes // would lead to different copies of the template code. template void CopyArray(const T* from, size_t size, U* to) { for (size_t i = 0; i != size; i++) { internal::CopyArray(from[i], to + i); } } // The relation between an NativeArray object (see below) and the // native array it represents. enum RelationToSource { kReference, // The NativeArray references the native array. kCopy // The NativeArray makes a copy of the native array and // owns the copy. }; // Adapts a native array to a read-only STL-style container. Instead // of the complete STL container concept, this adaptor only implements // members useful for Google Mock's container matchers. New members // should be added as needed. To simplify the implementation, we only // support Element being a raw type (i.e. having no top-level const or // reference modifier). It's the client's responsibility to satisfy // this requirement. Element can be an array type itself (hence // multi-dimensional arrays are supported). template class NativeArray { public: // STL-style container typedefs. typedef Element value_type; typedef Element* iterator; typedef const Element* const_iterator; // Constructs from a native array. NativeArray(const Element* array, size_t count, RelationToSource relation) { Init(array, count, relation); } // Copy constructor. NativeArray(const NativeArray& rhs) { Init(rhs.array_, rhs.size_, rhs.relation_to_source_); } ~NativeArray() { // Ensures that the user doesn't instantiate NativeArray with a // const or reference type. static_cast(StaticAssertTypeEqHelper()); if (relation_to_source_ == kCopy) delete[] array_; } // STL-style container methods. size_t size() const { return size_; } const_iterator begin() const { return array_; } const_iterator end() const { return array_ + size_; } bool operator==(const NativeArray& rhs) const { return size() == rhs.size() && ArrayEq(begin(), size(), rhs.begin()); } private: // Initializes this object; makes a copy of the input array if // 'relation' is kCopy. void Init(const Element* array, size_t a_size, RelationToSource relation) { if (relation == kReference) { array_ = array; } else { Element* const copy = new Element[a_size]; CopyArray(array, a_size, copy); array_ = copy; } size_ = a_size; relation_to_source_ = relation; } const Element* array_; size_t size_; RelationToSource relation_to_source_; GTEST_DISALLOW_ASSIGN_(NativeArray); }; } // namespace internal } // namespace testing #define GTEST_MESSAGE_AT_(file, line, message, result_type) \ ::testing::internal::AssertHelper(result_type, file, line, message) \ = ::testing::Message() #define GTEST_MESSAGE_(message, result_type) \ GTEST_MESSAGE_AT_(__FILE__, __LINE__, message, result_type) #define GTEST_FATAL_FAILURE_(message) \ return GTEST_MESSAGE_(message, ::testing::TestPartResult::kFatalFailure) #define GTEST_NONFATAL_FAILURE_(message) \ GTEST_MESSAGE_(message, ::testing::TestPartResult::kNonFatalFailure) #define GTEST_SUCCESS_(message) \ GTEST_MESSAGE_(message, ::testing::TestPartResult::kSuccess) // Suppresses MSVC warnings 4072 (unreachable code) for the code following // statement if it returns or throws (or doesn't return or throw in some // situations). #define GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement) \ if (::testing::internal::AlwaysTrue()) { statement; } #define GTEST_TEST_THROW_(statement, expected_exception, fail) \ GTEST_AMBIGUOUS_ELSE_BLOCKER_ \ if (::testing::internal::ConstCharPtr gtest_msg = "") { \ bool gtest_caught_expected = false; \ try { \ GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \ } \ catch (expected_exception const&) { \ gtest_caught_expected = true; \ } \ catch (...) { \ gtest_msg.value = \ "Expected: " #statement " throws an exception of type " \ #expected_exception ".\n Actual: it throws a different type."; \ goto GTEST_CONCAT_TOKEN_(gtest_label_testthrow_, __LINE__); \ } \ if (!gtest_caught_expected) { \ gtest_msg.value = \ "Expected: " #statement " throws an exception of type " \ #expected_exception ".\n Actual: it throws nothing."; \ goto GTEST_CONCAT_TOKEN_(gtest_label_testthrow_, __LINE__); \ } \ } else \ GTEST_CONCAT_TOKEN_(gtest_label_testthrow_, __LINE__): \ fail(gtest_msg.value) #define GTEST_TEST_NO_THROW_(statement, fail) \ GTEST_AMBIGUOUS_ELSE_BLOCKER_ \ if (::testing::internal::AlwaysTrue()) { \ try { \ GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \ } \ catch (...) { \ goto GTEST_CONCAT_TOKEN_(gtest_label_testnothrow_, __LINE__); \ } \ } else \ GTEST_CONCAT_TOKEN_(gtest_label_testnothrow_, __LINE__): \ fail("Expected: " #statement " doesn't throw an exception.\n" \ " Actual: it throws.") #define GTEST_TEST_ANY_THROW_(statement, fail) \ GTEST_AMBIGUOUS_ELSE_BLOCKER_ \ if (::testing::internal::AlwaysTrue()) { \ bool gtest_caught_any = false; \ try { \ GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \ } \ catch (...) { \ gtest_caught_any = true; \ } \ if (!gtest_caught_any) { \ goto GTEST_CONCAT_TOKEN_(gtest_label_testanythrow_, __LINE__); \ } \ } else \ GTEST_CONCAT_TOKEN_(gtest_label_testanythrow_, __LINE__): \ fail("Expected: " #statement " throws an exception.\n" \ " Actual: it doesn't.") // Implements Boolean test assertions such as EXPECT_TRUE. expression can be // either a boolean expression or an AssertionResult. text is a textual // represenation of expression as it was passed into the EXPECT_TRUE. #define GTEST_TEST_BOOLEAN_(expression, text, actual, expected, fail) \ GTEST_AMBIGUOUS_ELSE_BLOCKER_ \ if (const ::testing::AssertionResult gtest_ar_ = \ ::testing::AssertionResult(expression)) \ ; \ else \ fail(::testing::internal::GetBoolAssertionFailureMessage(\ gtest_ar_, text, #actual, #expected).c_str()) #define GTEST_TEST_NO_FATAL_FAILURE_(statement, fail) \ GTEST_AMBIGUOUS_ELSE_BLOCKER_ \ if (::testing::internal::AlwaysTrue()) { \ ::testing::internal::HasNewFatalFailureHelper gtest_fatal_failure_checker; \ GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \ if (gtest_fatal_failure_checker.has_new_fatal_failure()) { \ goto GTEST_CONCAT_TOKEN_(gtest_label_testnofatal_, __LINE__); \ } \ } else \ GTEST_CONCAT_TOKEN_(gtest_label_testnofatal_, __LINE__): \ fail("Expected: " #statement " doesn't generate new fatal " \ "failures in the current thread.\n" \ " Actual: it does.") // Expands to the name of the class that implements the given test. #define GTEST_TEST_CLASS_NAME_(test_case_name, test_name) \ test_case_name##_##test_name##_Test // Helper macro for defining tests. #define GTEST_TEST_(test_case_name, test_name, parent_class, parent_id)\ class GTEST_TEST_CLASS_NAME_(test_case_name, test_name) : public parent_class {\ public:\ GTEST_TEST_CLASS_NAME_(test_case_name, test_name)() {}\ private:\ virtual void TestBody();\ static ::testing::TestInfo* const test_info_ GTEST_ATTRIBUTE_UNUSED_;\ GTEST_DISALLOW_COPY_AND_ASSIGN_(\ GTEST_TEST_CLASS_NAME_(test_case_name, test_name));\ };\ \ ::testing::TestInfo* const GTEST_TEST_CLASS_NAME_(test_case_name, test_name)\ ::test_info_ =\ ::testing::internal::MakeAndRegisterTestInfo(\ #test_case_name, #test_name, NULL, NULL, \ (parent_id), \ parent_class::SetUpTestCase, \ parent_class::TearDownTestCase, \ new ::testing::internal::TestFactoryImpl<\ GTEST_TEST_CLASS_NAME_(test_case_name, test_name)>);\ void GTEST_TEST_CLASS_NAME_(test_case_name, test_name)::TestBody() #endif // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_INTERNAL_H_ ugene-1.9.8/src/libs_3rdparty/gtest/src/gtest/internal/gtest-linked_ptr.h0000644000175000017500000001757711651544307025220 0ustar ilyailya// Copyright 2003 Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Authors: Dan Egnor (egnor@google.com) // // A "smart" pointer type with reference tracking. Every pointer to a // particular object is kept on a circular linked list. When the last pointer // to an object is destroyed or reassigned, the object is deleted. // // Used properly, this deletes the object when the last reference goes away. // There are several caveats: // - Like all reference counting schemes, cycles lead to leaks. // - Each smart pointer is actually two pointers (8 bytes instead of 4). // - Every time a pointer is assigned, the entire list of pointers to that // object is traversed. This class is therefore NOT SUITABLE when there // will often be more than two or three pointers to a particular object. // - References are only tracked as long as linked_ptr<> objects are copied. // If a linked_ptr<> is converted to a raw pointer and back, BAD THINGS // will happen (double deletion). // // A good use of this class is storing object references in STL containers. // You can safely put linked_ptr<> in a vector<>. // Other uses may not be as good. // // Note: If you use an incomplete type with linked_ptr<>, the class // *containing* linked_ptr<> must have a constructor and destructor (even // if they do nothing!). // // Bill Gibbons suggested we use something like this. // // Thread Safety: // Unlike other linked_ptr implementations, in this implementation // a linked_ptr object is thread-safe in the sense that: // - it's safe to copy linked_ptr objects concurrently, // - it's safe to copy *from* a linked_ptr and read its underlying // raw pointer (e.g. via get()) concurrently, and // - it's safe to write to two linked_ptrs that point to the same // shared object concurrently. // TODO(wan@google.com): rename this to safe_linked_ptr to avoid // confusion with normal linked_ptr. #ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_LINKED_PTR_H_ #define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_LINKED_PTR_H_ #include #include #include "gtest/internal/gtest-port.h" namespace testing { namespace internal { // Protects copying of all linked_ptr objects. GTEST_API_ GTEST_DECLARE_STATIC_MUTEX_(g_linked_ptr_mutex); // This is used internally by all instances of linked_ptr<>. It needs to be // a non-template class because different types of linked_ptr<> can refer to // the same object (linked_ptr(obj) vs linked_ptr(obj)). // So, it needs to be possible for different types of linked_ptr to participate // in the same circular linked list, so we need a single class type here. // // DO NOT USE THIS CLASS DIRECTLY YOURSELF. Use linked_ptr. class linked_ptr_internal { public: // Create a new circle that includes only this instance. void join_new() { next_ = this; } // Many linked_ptr operations may change p.link_ for some linked_ptr // variable p in the same circle as this object. Therefore we need // to prevent two such operations from occurring concurrently. // // Note that different types of linked_ptr objects can coexist in a // circle (e.g. linked_ptr, linked_ptr, and // linked_ptr). Therefore we must use a single mutex to // protect all linked_ptr objects. This can create serious // contention in production code, but is acceptable in a testing // framework. // Join an existing circle. // L < g_linked_ptr_mutex void join(linked_ptr_internal const* ptr) { MutexLock lock(&g_linked_ptr_mutex); linked_ptr_internal const* p = ptr; while (p->next_ != ptr) p = p->next_; p->next_ = this; next_ = ptr; } // Leave whatever circle we're part of. Returns true if we were the // last member of the circle. Once this is done, you can join() another. // L < g_linked_ptr_mutex bool depart() { MutexLock lock(&g_linked_ptr_mutex); if (next_ == this) return true; linked_ptr_internal const* p = next_; while (p->next_ != this) p = p->next_; p->next_ = next_; return false; } private: mutable linked_ptr_internal const* next_; }; template class linked_ptr { public: typedef T element_type; // Take over ownership of a raw pointer. This should happen as soon as // possible after the object is created. explicit linked_ptr(T* ptr = NULL) { capture(ptr); } ~linked_ptr() { depart(); } // Copy an existing linked_ptr<>, adding ourselves to the list of references. template linked_ptr(linked_ptr const& ptr) { copy(&ptr); } linked_ptr(linked_ptr const& ptr) { // NOLINT assert(&ptr != this); copy(&ptr); } // Assignment releases the old value and acquires the new. template linked_ptr& operator=(linked_ptr const& ptr) { depart(); copy(&ptr); return *this; } linked_ptr& operator=(linked_ptr const& ptr) { if (&ptr != this) { depart(); copy(&ptr); } return *this; } // Smart pointer members. void reset(T* ptr = NULL) { depart(); capture(ptr); } T* get() const { return value_; } T* operator->() const { return value_; } T& operator*() const { return *value_; } bool operator==(T* p) const { return value_ == p; } bool operator!=(T* p) const { return value_ != p; } template bool operator==(linked_ptr const& ptr) const { return value_ == ptr.get(); } template bool operator!=(linked_ptr const& ptr) const { return value_ != ptr.get(); } private: template friend class linked_ptr; T* value_; linked_ptr_internal link_; void depart() { if (link_.depart()) delete value_; } void capture(T* ptr) { value_ = ptr; link_.join_new(); } template void copy(linked_ptr const* ptr) { value_ = ptr->get(); if (value_) link_.join(&ptr->link_); else link_.join_new(); } }; template inline bool operator==(T* ptr, const linked_ptr& x) { return ptr == x.get(); } template inline bool operator!=(T* ptr, const linked_ptr& x) { return ptr != x.get(); } // A function to convert T* into linked_ptr // Doing e.g. make_linked_ptr(new FooBarBaz(arg)) is a shorter notation // for linked_ptr >(new FooBarBaz(arg)) template linked_ptr make_linked_ptr(T* ptr) { return linked_ptr(ptr); } } // namespace internal } // namespace testing #endif // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_LINKED_PTR_H_ ugene-1.9.8/src/libs_3rdparty/gtest/src/gtest/internal/gtest-port.h0000644000175000017500000017144311651544307024042 0ustar ilyailya// Copyright 2005, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Authors: wan@google.com (Zhanyong Wan) // // Low-level types and utilities for porting Google Test to various // platforms. They are subject to change without notice. DO NOT USE // THEM IN USER CODE. #ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PORT_H_ #define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PORT_H_ // The user can define the following macros in the build script to // control Google Test's behavior. If the user doesn't define a macro // in this list, Google Test will define it. // // GTEST_HAS_CLONE - Define it to 1/0 to indicate that clone(2) // is/isn't available. // GTEST_HAS_EXCEPTIONS - Define it to 1/0 to indicate that exceptions // are enabled. // GTEST_HAS_GLOBAL_STRING - Define it to 1/0 to indicate that ::string // is/isn't available (some systems define // ::string, which is different to std::string). // GTEST_HAS_GLOBAL_WSTRING - Define it to 1/0 to indicate that ::string // is/isn't available (some systems define // ::wstring, which is different to std::wstring). // GTEST_HAS_POSIX_RE - Define it to 1/0 to indicate that POSIX regular // expressions are/aren't available. // GTEST_HAS_PTHREAD - Define it to 1/0 to indicate that // is/isn't available. // GTEST_HAS_RTTI - Define it to 1/0 to indicate that RTTI is/isn't // enabled. // GTEST_HAS_STD_WSTRING - Define it to 1/0 to indicate that // std::wstring does/doesn't work (Google Test can // be used where std::wstring is unavailable). // GTEST_HAS_TR1_TUPLE - Define it to 1/0 to indicate tr1::tuple // is/isn't available. // GTEST_HAS_SEH - Define it to 1/0 to indicate whether the // compiler supports Microsoft's "Structured // Exception Handling". // GTEST_HAS_STREAM_REDIRECTION // - Define it to 1/0 to indicate whether the // platform supports I/O stream redirection using // dup() and dup2(). // GTEST_USE_OWN_TR1_TUPLE - Define it to 1/0 to indicate whether Google // Test's own tr1 tuple implementation should be // used. Unused when the user sets // GTEST_HAS_TR1_TUPLE to 0. // GTEST_LINKED_AS_SHARED_LIBRARY // - Define to 1 when compiling tests that use // Google Test as a shared library (known as // DLL on Windows). // GTEST_CREATE_SHARED_LIBRARY // - Define to 1 when compiling Google Test itself // as a shared library. // This header defines the following utilities: // // Macros indicating the current platform (defined to 1 if compiled on // the given platform; otherwise undefined): // GTEST_OS_AIX - IBM AIX // GTEST_OS_CYGWIN - Cygwin // GTEST_OS_HPUX - HP-UX // GTEST_OS_LINUX - Linux // GTEST_OS_LINUX_ANDROID - Google Android // GTEST_OS_MAC - Mac OS X // GTEST_OS_NACL - Google Native Client (NaCl) // GTEST_OS_SOLARIS - Sun Solaris // GTEST_OS_SYMBIAN - Symbian // GTEST_OS_WINDOWS - Windows (Desktop, MinGW, or Mobile) // GTEST_OS_WINDOWS_DESKTOP - Windows Desktop // GTEST_OS_WINDOWS_MINGW - MinGW // GTEST_OS_WINDOWS_MOBILE - Windows Mobile // GTEST_OS_ZOS - z/OS // // Among the platforms, Cygwin, Linux, Max OS X, and Windows have the // most stable support. Since core members of the Google Test project // don't have access to other platforms, support for them may be less // stable. If you notice any problems on your platform, please notify // googletestframework@googlegroups.com (patches for fixing them are // even more welcome!). // // Note that it is possible that none of the GTEST_OS_* macros are defined. // // Macros indicating available Google Test features (defined to 1 if // the corresponding feature is supported; otherwise undefined): // GTEST_HAS_COMBINE - the Combine() function (for value-parameterized // tests) // GTEST_HAS_DEATH_TEST - death tests // GTEST_HAS_PARAM_TEST - value-parameterized tests // GTEST_HAS_TYPED_TEST - typed tests // GTEST_HAS_TYPED_TEST_P - type-parameterized tests // GTEST_USES_POSIX_RE - enhanced POSIX regex is used. Do not confuse with // GTEST_HAS_POSIX_RE (see above) which users can // define themselves. // GTEST_USES_SIMPLE_RE - our own simple regex is used; // the above two are mutually exclusive. // GTEST_CAN_COMPARE_NULL - accepts untyped NULL in EXPECT_EQ(). // // Macros for basic C++ coding: // GTEST_AMBIGUOUS_ELSE_BLOCKER_ - for disabling a gcc warning. // GTEST_ATTRIBUTE_UNUSED_ - declares that a class' instances or a // variable don't have to be used. // GTEST_DISALLOW_ASSIGN_ - disables operator=. // GTEST_DISALLOW_COPY_AND_ASSIGN_ - disables copy ctor and operator=. // GTEST_MUST_USE_RESULT_ - declares that a function's result must be used. // // Synchronization: // Mutex, MutexLock, ThreadLocal, GetThreadCount() // - synchronization primitives. // GTEST_IS_THREADSAFE - defined to 1 to indicate that the above // synchronization primitives have real implementations // and Google Test is thread-safe; or 0 otherwise. // // Template meta programming: // is_pointer - as in TR1; needed on Symbian and IBM XL C/C++ only. // IteratorTraits - partial implementation of std::iterator_traits, which // is not available in libCstd when compiled with Sun C++. // // Smart pointers: // scoped_ptr - as in TR2. // // Regular expressions: // RE - a simple regular expression class using the POSIX // Extended Regular Expression syntax on UNIX-like // platforms, or a reduced regular exception syntax on // other platforms, including Windows. // // Logging: // GTEST_LOG_() - logs messages at the specified severity level. // LogToStderr() - directs all log messages to stderr. // FlushInfoLog() - flushes informational log messages. // // Stdout and stderr capturing: // CaptureStdout() - starts capturing stdout. // GetCapturedStdout() - stops capturing stdout and returns the captured // string. // CaptureStderr() - starts capturing stderr. // GetCapturedStderr() - stops capturing stderr and returns the captured // string. // // Integer types: // TypeWithSize - maps an integer to a int type. // Int32, UInt32, Int64, UInt64, TimeInMillis // - integers of known sizes. // BiggestInt - the biggest signed integer type. // // Command-line utilities: // GTEST_FLAG() - references a flag. // GTEST_DECLARE_*() - declares a flag. // GTEST_DEFINE_*() - defines a flag. // GetArgvs() - returns the command line as a vector of strings. // // Environment variable utilities: // GetEnv() - gets the value of an environment variable. // BoolFromGTestEnv() - parses a bool environment variable. // Int32FromGTestEnv() - parses an Int32 environment variable. // StringFromGTestEnv() - parses a string environment variable. #include // for isspace, etc #include // for ptrdiff_t #include #include #include #ifndef _WIN32_WCE # include # include #endif // !_WIN32_WCE #include // NOLINT #include // NOLINT #include // NOLINT #define GTEST_DEV_EMAIL_ "googletestframework@@googlegroups.com" #define GTEST_FLAG_PREFIX_ "gtest_" #define GTEST_FLAG_PREFIX_DASH_ "gtest-" #define GTEST_FLAG_PREFIX_UPPER_ "GTEST_" #define GTEST_NAME_ "Google Test" #define GTEST_PROJECT_URL_ "http://code.google.com/p/googletest/" // Determines the version of gcc that is used to compile this. #ifdef __GNUC__ // 40302 means version 4.3.2. # define GTEST_GCC_VER_ \ (__GNUC__*10000 + __GNUC_MINOR__*100 + __GNUC_PATCHLEVEL__) #endif // __GNUC__ // Determines the platform on which Google Test is compiled. #ifdef __CYGWIN__ # define GTEST_OS_CYGWIN 1 #elif defined __SYMBIAN32__ # define GTEST_OS_SYMBIAN 1 #elif defined _WIN32 # define GTEST_OS_WINDOWS 1 # ifdef _WIN32_WCE # define GTEST_OS_WINDOWS_MOBILE 1 # elif defined(__MINGW__) || defined(__MINGW32__) # define GTEST_OS_WINDOWS_MINGW 1 # else # define GTEST_OS_WINDOWS_DESKTOP 1 # endif // _WIN32_WCE #elif defined __APPLE__ # define GTEST_OS_MAC 1 #elif defined __linux__ # define GTEST_OS_LINUX 1 # ifdef ANDROID # define GTEST_OS_LINUX_ANDROID 1 # endif // ANDROID #elif defined __MVS__ # define GTEST_OS_ZOS 1 #elif defined(__sun) && defined(__SVR4) # define GTEST_OS_SOLARIS 1 #elif defined(_AIX) # define GTEST_OS_AIX 1 #elif defined(__hpux) # define GTEST_OS_HPUX 1 #elif defined __native_client__ # define GTEST_OS_NACL 1 #endif // __CYGWIN__ // Brings in definitions for functions used in the testing::internal::posix // namespace (read, write, close, chdir, isatty, stat). We do not currently // use them on Windows Mobile. #if !GTEST_OS_WINDOWS // This assumes that non-Windows OSes provide unistd.h. For OSes where this // is not the case, we need to include headers that provide the functions // mentioned above. # include # if !GTEST_OS_NACL // TODO(vladl@google.com): Remove this condition when Native Client SDK adds // strings.h (tracked in // http://code.google.com/p/nativeclient/issues/detail?id=1175). # include // Native Client doesn't provide strings.h. # endif #elif !GTEST_OS_WINDOWS_MOBILE # include # include #endif // Defines this to true iff Google Test can use POSIX regular expressions. #ifndef GTEST_HAS_POSIX_RE # define GTEST_HAS_POSIX_RE (!GTEST_OS_WINDOWS) #endif #if GTEST_HAS_POSIX_RE // On some platforms, needs someone to define size_t, and // won't compile otherwise. We can #include it here as we already // included , which is guaranteed to define size_t through // . # include // NOLINT # define GTEST_USES_POSIX_RE 1 #elif GTEST_OS_WINDOWS // is not available on Windows. Use our own simple regex // implementation instead. # define GTEST_USES_SIMPLE_RE 1 #else // may not be available on this platform. Use our own // simple regex implementation instead. # define GTEST_USES_SIMPLE_RE 1 #endif // GTEST_HAS_POSIX_RE #ifndef GTEST_HAS_EXCEPTIONS // The user didn't tell us whether exceptions are enabled, so we need // to figure it out. # if defined(_MSC_VER) || defined(__BORLANDC__) // MSVC's and C++Builder's implementations of the STL use the _HAS_EXCEPTIONS // macro to enable exceptions, so we'll do the same. // Assumes that exceptions are enabled by default. # ifndef _HAS_EXCEPTIONS # define _HAS_EXCEPTIONS 1 # endif // _HAS_EXCEPTIONS # define GTEST_HAS_EXCEPTIONS _HAS_EXCEPTIONS # elif defined(__GNUC__) && __EXCEPTIONS // gcc defines __EXCEPTIONS to 1 iff exceptions are enabled. # define GTEST_HAS_EXCEPTIONS 1 # elif defined(__SUNPRO_CC) // Sun Pro CC supports exceptions. However, there is no compile-time way of // detecting whether they are enabled or not. Therefore, we assume that // they are enabled unless the user tells us otherwise. # define GTEST_HAS_EXCEPTIONS 1 # elif defined(__IBMCPP__) && __EXCEPTIONS // xlC defines __EXCEPTIONS to 1 iff exceptions are enabled. # define GTEST_HAS_EXCEPTIONS 1 # elif defined(__HP_aCC) // Exception handling is in effect by default in HP aCC compiler. It has to // be turned of by +noeh compiler option if desired. # define GTEST_HAS_EXCEPTIONS 1 # else // For other compilers, we assume exceptions are disabled to be // conservative. # define GTEST_HAS_EXCEPTIONS 0 # endif // defined(_MSC_VER) || defined(__BORLANDC__) #endif // GTEST_HAS_EXCEPTIONS #if !defined(GTEST_HAS_STD_STRING) // Even though we don't use this macro any longer, we keep it in case // some clients still depend on it. # define GTEST_HAS_STD_STRING 1 #elif !GTEST_HAS_STD_STRING // The user told us that ::std::string isn't available. # error "Google Test cannot be used where ::std::string isn't available." #endif // !defined(GTEST_HAS_STD_STRING) #ifndef GTEST_HAS_GLOBAL_STRING // The user didn't tell us whether ::string is available, so we need // to figure it out. # define GTEST_HAS_GLOBAL_STRING 0 #endif // GTEST_HAS_GLOBAL_STRING #ifndef GTEST_HAS_STD_WSTRING // The user didn't tell us whether ::std::wstring is available, so we need // to figure it out. // TODO(wan@google.com): uses autoconf to detect whether ::std::wstring // is available. // Cygwin 1.7 and below doesn't support ::std::wstring. // Solaris' libc++ doesn't support it either. Android has // no support for it at least as recent as Froyo (2.2). # define GTEST_HAS_STD_WSTRING \ (!(GTEST_OS_LINUX_ANDROID || GTEST_OS_CYGWIN || GTEST_OS_SOLARIS)) #endif // GTEST_HAS_STD_WSTRING #ifndef GTEST_HAS_GLOBAL_WSTRING // The user didn't tell us whether ::wstring is available, so we need // to figure it out. # define GTEST_HAS_GLOBAL_WSTRING \ (GTEST_HAS_STD_WSTRING && GTEST_HAS_GLOBAL_STRING) #endif // GTEST_HAS_GLOBAL_WSTRING // Determines whether RTTI is available. #ifndef GTEST_HAS_RTTI // The user didn't tell us whether RTTI is enabled, so we need to // figure it out. # ifdef _MSC_VER # ifdef _CPPRTTI // MSVC defines this macro iff RTTI is enabled. # define GTEST_HAS_RTTI 1 # else # define GTEST_HAS_RTTI 0 # endif // Starting with version 4.3.2, gcc defines __GXX_RTTI iff RTTI is enabled. # elif defined(__GNUC__) && (GTEST_GCC_VER_ >= 40302) # ifdef __GXX_RTTI # define GTEST_HAS_RTTI 1 # else # define GTEST_HAS_RTTI 0 # endif // __GXX_RTTI // Starting with version 9.0 IBM Visual Age defines __RTTI_ALL__ to 1 if // both the typeid and dynamic_cast features are present. # elif defined(__IBMCPP__) && (__IBMCPP__ >= 900) # ifdef __RTTI_ALL__ # define GTEST_HAS_RTTI 1 # else # define GTEST_HAS_RTTI 0 # endif # else // For all other compilers, we assume RTTI is enabled. # define GTEST_HAS_RTTI 1 # endif // _MSC_VER #endif // GTEST_HAS_RTTI // It's this header's responsibility to #include when RTTI // is enabled. #if GTEST_HAS_RTTI # include #endif // Determines whether Google Test can use the pthreads library. #ifndef GTEST_HAS_PTHREAD // The user didn't tell us explicitly, so we assume pthreads support is // available on Linux and Mac. // // To disable threading support in Google Test, add -DGTEST_HAS_PTHREAD=0 // to your compiler flags. # define GTEST_HAS_PTHREAD (GTEST_OS_LINUX || GTEST_OS_MAC || GTEST_OS_HPUX) #endif // GTEST_HAS_PTHREAD #if GTEST_HAS_PTHREAD // gtest-port.h guarantees to #include when GTEST_HAS_PTHREAD is // true. # include // NOLINT // For timespec and nanosleep, used below. # include // NOLINT #endif // Determines whether Google Test can use tr1/tuple. You can define // this macro to 0 to prevent Google Test from using tuple (any // feature depending on tuple with be disabled in this mode). #ifndef GTEST_HAS_TR1_TUPLE // The user didn't tell us not to do it, so we assume it's OK. # define GTEST_HAS_TR1_TUPLE 1 #endif // GTEST_HAS_TR1_TUPLE // Determines whether Google Test's own tr1 tuple implementation // should be used. #ifndef GTEST_USE_OWN_TR1_TUPLE // The user didn't tell us, so we need to figure it out. // We use our own TR1 tuple if we aren't sure the user has an // implementation of it already. At this time, GCC 4.0.0+ and MSVC // 2010 are the only mainstream compilers that come with a TR1 tuple // implementation. NVIDIA's CUDA NVCC compiler pretends to be GCC by // defining __GNUC__ and friends, but cannot compile GCC's tuple // implementation. MSVC 2008 (9.0) provides TR1 tuple in a 323 MB // Feature Pack download, which we cannot assume the user has. # if (defined(__GNUC__) && !defined(__CUDACC__) && (GTEST_GCC_VER_ >= 40000)) \ || _MSC_VER >= 1600 # define GTEST_USE_OWN_TR1_TUPLE 0 # else # define GTEST_USE_OWN_TR1_TUPLE 1 # endif #endif // GTEST_USE_OWN_TR1_TUPLE // To avoid conditional compilation everywhere, we make it // gtest-port.h's responsibility to #include the header implementing // tr1/tuple. #if GTEST_HAS_TR1_TUPLE # if GTEST_USE_OWN_TR1_TUPLE # include "gtest/internal/gtest-tuple.h" # elif GTEST_OS_SYMBIAN // On Symbian, BOOST_HAS_TR1_TUPLE causes Boost's TR1 tuple library to // use STLport's tuple implementation, which unfortunately doesn't // work as the copy of STLport distributed with Symbian is incomplete. // By making sure BOOST_HAS_TR1_TUPLE is undefined, we force Boost to // use its own tuple implementation. # ifdef BOOST_HAS_TR1_TUPLE # undef BOOST_HAS_TR1_TUPLE # endif // BOOST_HAS_TR1_TUPLE // This prevents , which defines // BOOST_HAS_TR1_TUPLE, from being #included by Boost's . # define BOOST_TR1_DETAIL_CONFIG_HPP_INCLUDED # include # elif defined(__GNUC__) && (GTEST_GCC_VER_ >= 40000) // GCC 4.0+ implements tr1/tuple in the header. This does // not conform to the TR1 spec, which requires the header to be . # if !GTEST_HAS_RTTI && GTEST_GCC_VER_ < 40302 // Until version 4.3.2, gcc has a bug that causes , // which is #included by , to not compile when RTTI is // disabled. _TR1_FUNCTIONAL is the header guard for // . Hence the following #define is a hack to prevent // from being included. # define _TR1_FUNCTIONAL 1 # include # undef _TR1_FUNCTIONAL // Allows the user to #include // if he chooses to. # else # include // NOLINT # endif // !GTEST_HAS_RTTI && GTEST_GCC_VER_ < 40302 # else // If the compiler is not GCC 4.0+, we assume the user is using a // spec-conforming TR1 implementation. # include // NOLINT # endif // GTEST_USE_OWN_TR1_TUPLE #endif // GTEST_HAS_TR1_TUPLE // Determines whether clone(2) is supported. // Usually it will only be available on Linux, excluding // Linux on the Itanium architecture. // Also see http://linux.die.net/man/2/clone. #ifndef GTEST_HAS_CLONE // The user didn't tell us, so we need to figure it out. # if GTEST_OS_LINUX && !defined(__ia64__) # define GTEST_HAS_CLONE 1 # else # define GTEST_HAS_CLONE 0 # endif // GTEST_OS_LINUX && !defined(__ia64__) #endif // GTEST_HAS_CLONE // Determines whether to support stream redirection. This is used to test // output correctness and to implement death tests. #ifndef GTEST_HAS_STREAM_REDIRECTION // By default, we assume that stream redirection is supported on all // platforms except known mobile ones. # if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_SYMBIAN # define GTEST_HAS_STREAM_REDIRECTION 0 # else # define GTEST_HAS_STREAM_REDIRECTION 1 # endif // !GTEST_OS_WINDOWS_MOBILE && !GTEST_OS_SYMBIAN #endif // GTEST_HAS_STREAM_REDIRECTION // Determines whether to support death tests. // Google Test does not support death tests for VC 7.1 and earlier as // abort() in a VC 7.1 application compiled as GUI in debug config // pops up a dialog window that cannot be suppressed programmatically. #if (GTEST_OS_LINUX || GTEST_OS_MAC || GTEST_OS_CYGWIN || GTEST_OS_SOLARIS || \ (GTEST_OS_WINDOWS_DESKTOP && _MSC_VER >= 1400) || \ GTEST_OS_WINDOWS_MINGW || GTEST_OS_AIX || GTEST_OS_HPUX) # define GTEST_HAS_DEATH_TEST 1 # include // NOLINT #endif // We don't support MSVC 7.1 with exceptions disabled now. Therefore // all the compilers we care about are adequate for supporting // value-parameterized tests. #define GTEST_HAS_PARAM_TEST 1 // Determines whether to support type-driven tests. // Typed tests need and variadic macros, which GCC, VC++ 8.0, // Sun Pro CC, IBM Visual Age, and HP aCC support. #if defined(__GNUC__) || (_MSC_VER >= 1400) || defined(__SUNPRO_CC) || \ defined(__IBMCPP__) || defined(__HP_aCC) # define GTEST_HAS_TYPED_TEST 1 # define GTEST_HAS_TYPED_TEST_P 1 #endif // Determines whether to support Combine(). This only makes sense when // value-parameterized tests are enabled. The implementation doesn't // work on Sun Studio since it doesn't understand templated conversion // operators. #if GTEST_HAS_PARAM_TEST && GTEST_HAS_TR1_TUPLE && !defined(__SUNPRO_CC) # define GTEST_HAS_COMBINE 1 #endif // Determines whether the system compiler uses UTF-16 for encoding wide strings. #define GTEST_WIDE_STRING_USES_UTF16_ \ (GTEST_OS_WINDOWS || GTEST_OS_CYGWIN || GTEST_OS_SYMBIAN || GTEST_OS_AIX) // Determines whether test results can be streamed to a socket. #if GTEST_OS_LINUX # define GTEST_CAN_STREAM_RESULTS_ 1 #endif // Defines some utility macros. // The GNU compiler emits a warning if nested "if" statements are followed by // an "else" statement and braces are not used to explicitly disambiguate the // "else" binding. This leads to problems with code like: // // if (gate) // ASSERT_*(condition) << "Some message"; // // The "switch (0) case 0:" idiom is used to suppress this. #ifdef __INTEL_COMPILER # define GTEST_AMBIGUOUS_ELSE_BLOCKER_ #else # define GTEST_AMBIGUOUS_ELSE_BLOCKER_ switch (0) case 0: default: // NOLINT #endif // Use this annotation at the end of a struct/class definition to // prevent the compiler from optimizing away instances that are never // used. This is useful when all interesting logic happens inside the // c'tor and / or d'tor. Example: // // struct Foo { // Foo() { ... } // } GTEST_ATTRIBUTE_UNUSED_; // // Also use it after a variable or parameter declaration to tell the // compiler the variable/parameter does not have to be used. #if defined(__GNUC__) && !defined(COMPILER_ICC) # define GTEST_ATTRIBUTE_UNUSED_ __attribute__ ((unused)) #else # define GTEST_ATTRIBUTE_UNUSED_ #endif // A macro to disallow operator= // This should be used in the private: declarations for a class. #define GTEST_DISALLOW_ASSIGN_(type)\ void operator=(type const &) // A macro to disallow copy constructor and operator= // This should be used in the private: declarations for a class. #define GTEST_DISALLOW_COPY_AND_ASSIGN_(type)\ type(type const &);\ GTEST_DISALLOW_ASSIGN_(type) // Tell the compiler to warn about unused return values for functions declared // with this macro. The macro should be used on function declarations // following the argument list: // // Sprocket* AllocateSprocket() GTEST_MUST_USE_RESULT_; #if defined(__GNUC__) && (GTEST_GCC_VER_ >= 30400) && !defined(COMPILER_ICC) # define GTEST_MUST_USE_RESULT_ __attribute__ ((warn_unused_result)) #else # define GTEST_MUST_USE_RESULT_ #endif // __GNUC__ && (GTEST_GCC_VER_ >= 30400) && !COMPILER_ICC // Determine whether the compiler supports Microsoft's Structured Exception // Handling. This is supported by several Windows compilers but generally // does not exist on any other system. #ifndef GTEST_HAS_SEH // The user didn't tell us, so we need to figure it out. # if defined(_MSC_VER) || defined(__BORLANDC__) // These two compilers are known to support SEH. # define GTEST_HAS_SEH 1 # else // Assume no SEH. # define GTEST_HAS_SEH 0 # endif #endif // GTEST_HAS_SEH #ifdef _MSC_VER # if GTEST_LINKED_AS_SHARED_LIBRARY # define GTEST_API_ __declspec(dllimport) # elif GTEST_CREATE_SHARED_LIBRARY # define GTEST_API_ __declspec(dllexport) # endif #endif // _MSC_VER #ifndef GTEST_API_ # define GTEST_API_ #endif #ifdef __GNUC__ // Ask the compiler to never inline a given function. # define GTEST_NO_INLINE_ __attribute__((noinline)) #else # define GTEST_NO_INLINE_ #endif namespace testing { class Message; namespace internal { class String; // The GTEST_COMPILE_ASSERT_ macro can be used to verify that a compile time // expression is true. For example, you could use it to verify the // size of a static array: // // GTEST_COMPILE_ASSERT_(ARRAYSIZE(content_type_names) == CONTENT_NUM_TYPES, // content_type_names_incorrect_size); // // or to make sure a struct is smaller than a certain size: // // GTEST_COMPILE_ASSERT_(sizeof(foo) < 128, foo_too_large); // // The second argument to the macro is the name of the variable. If // the expression is false, most compilers will issue a warning/error // containing the name of the variable. template struct CompileAssert { }; #define GTEST_COMPILE_ASSERT_(expr, msg) \ typedef ::testing::internal::CompileAssert<(bool(expr))> \ msg[bool(expr) ? 1 : -1] // Implementation details of GTEST_COMPILE_ASSERT_: // // - GTEST_COMPILE_ASSERT_ works by defining an array type that has -1 // elements (and thus is invalid) when the expression is false. // // - The simpler definition // // #define GTEST_COMPILE_ASSERT_(expr, msg) typedef char msg[(expr) ? 1 : -1] // // does not work, as gcc supports variable-length arrays whose sizes // are determined at run-time (this is gcc's extension and not part // of the C++ standard). As a result, gcc fails to reject the // following code with the simple definition: // // int foo; // GTEST_COMPILE_ASSERT_(foo, msg); // not supposed to compile as foo is // // not a compile-time constant. // // - By using the type CompileAssert<(bool(expr))>, we ensures that // expr is a compile-time constant. (Template arguments must be // determined at compile-time.) // // - The outter parentheses in CompileAssert<(bool(expr))> are necessary // to work around a bug in gcc 3.4.4 and 4.0.1. If we had written // // CompileAssert // // instead, these compilers will refuse to compile // // GTEST_COMPILE_ASSERT_(5 > 0, some_message); // // (They seem to think the ">" in "5 > 0" marks the end of the // template argument list.) // // - The array size is (bool(expr) ? 1 : -1), instead of simply // // ((expr) ? 1 : -1). // // This is to avoid running into a bug in MS VC 7.1, which // causes ((0.0) ? 1 : -1) to incorrectly evaluate to 1. // StaticAssertTypeEqHelper is used by StaticAssertTypeEq defined in gtest.h. // // This template is declared, but intentionally undefined. template struct StaticAssertTypeEqHelper; template struct StaticAssertTypeEqHelper {}; #if GTEST_HAS_GLOBAL_STRING typedef ::string string; #else typedef ::std::string string; #endif // GTEST_HAS_GLOBAL_STRING #if GTEST_HAS_GLOBAL_WSTRING typedef ::wstring wstring; #elif GTEST_HAS_STD_WSTRING typedef ::std::wstring wstring; #endif // GTEST_HAS_GLOBAL_WSTRING // A helper for suppressing warnings on constant condition. It just // returns 'condition'. GTEST_API_ bool IsTrue(bool condition); // Defines scoped_ptr. // This implementation of scoped_ptr is PARTIAL - it only contains // enough stuff to satisfy Google Test's need. template class scoped_ptr { public: typedef T element_type; explicit scoped_ptr(T* p = NULL) : ptr_(p) {} ~scoped_ptr() { reset(); } T& operator*() const { return *ptr_; } T* operator->() const { return ptr_; } T* get() const { return ptr_; } T* release() { T* const ptr = ptr_; ptr_ = NULL; return ptr; } void reset(T* p = NULL) { if (p != ptr_) { if (IsTrue(sizeof(T) > 0)) { // Makes sure T is a complete type. delete ptr_; } ptr_ = p; } } private: T* ptr_; GTEST_DISALLOW_COPY_AND_ASSIGN_(scoped_ptr); }; // Defines RE. // A simple C++ wrapper for . It uses the POSIX Extended // Regular Expression syntax. class GTEST_API_ RE { public: // A copy constructor is required by the Standard to initialize object // references from r-values. RE(const RE& other) { Init(other.pattern()); } // Constructs an RE from a string. RE(const ::std::string& regex) { Init(regex.c_str()); } // NOLINT #if GTEST_HAS_GLOBAL_STRING RE(const ::string& regex) { Init(regex.c_str()); } // NOLINT #endif // GTEST_HAS_GLOBAL_STRING RE(const char* regex) { Init(regex); } // NOLINT ~RE(); // Returns the string representation of the regex. const char* pattern() const { return pattern_; } // FullMatch(str, re) returns true iff regular expression re matches // the entire str. // PartialMatch(str, re) returns true iff regular expression re // matches a substring of str (including str itself). // // TODO(wan@google.com): make FullMatch() and PartialMatch() work // when str contains NUL characters. static bool FullMatch(const ::std::string& str, const RE& re) { return FullMatch(str.c_str(), re); } static bool PartialMatch(const ::std::string& str, const RE& re) { return PartialMatch(str.c_str(), re); } #if GTEST_HAS_GLOBAL_STRING static bool FullMatch(const ::string& str, const RE& re) { return FullMatch(str.c_str(), re); } static bool PartialMatch(const ::string& str, const RE& re) { return PartialMatch(str.c_str(), re); } #endif // GTEST_HAS_GLOBAL_STRING static bool FullMatch(const char* str, const RE& re); static bool PartialMatch(const char* str, const RE& re); private: void Init(const char* regex); // We use a const char* instead of a string, as Google Test may be used // where string is not available. We also do not use Google Test's own // String type here, in order to simplify dependencies between the // files. const char* pattern_; bool is_valid_; #if GTEST_USES_POSIX_RE regex_t full_regex_; // For FullMatch(). regex_t partial_regex_; // For PartialMatch(). #else // GTEST_USES_SIMPLE_RE const char* full_pattern_; // For FullMatch(); #endif GTEST_DISALLOW_ASSIGN_(RE); }; // Formats a source file path and a line number as they would appear // in an error message from the compiler used to compile this code. GTEST_API_ ::std::string FormatFileLocation(const char* file, int line); // Formats a file location for compiler-independent XML output. // Although this function is not platform dependent, we put it next to // FormatFileLocation in order to contrast the two functions. GTEST_API_ ::std::string FormatCompilerIndependentFileLocation(const char* file, int line); // Defines logging utilities: // GTEST_LOG_(severity) - logs messages at the specified severity level. The // message itself is streamed into the macro. // LogToStderr() - directs all log messages to stderr. // FlushInfoLog() - flushes informational log messages. enum GTestLogSeverity { GTEST_INFO, GTEST_WARNING, GTEST_ERROR, GTEST_FATAL }; // Formats log entry severity, provides a stream object for streaming the // log message, and terminates the message with a newline when going out of // scope. class GTEST_API_ GTestLog { public: GTestLog(GTestLogSeverity severity, const char* file, int line); // Flushes the buffers and, if severity is GTEST_FATAL, aborts the program. ~GTestLog(); ::std::ostream& GetStream() { return ::std::cerr; } private: const GTestLogSeverity severity_; GTEST_DISALLOW_COPY_AND_ASSIGN_(GTestLog); }; #define GTEST_LOG_(severity) \ ::testing::internal::GTestLog(::testing::internal::GTEST_##severity, \ __FILE__, __LINE__).GetStream() inline void LogToStderr() {} inline void FlushInfoLog() { fflush(NULL); } // INTERNAL IMPLEMENTATION - DO NOT USE. // // GTEST_CHECK_ is an all-mode assert. It aborts the program if the condition // is not satisfied. // Synopsys: // GTEST_CHECK_(boolean_condition); // or // GTEST_CHECK_(boolean_condition) << "Additional message"; // // This checks the condition and if the condition is not satisfied // it prints message about the condition violation, including the // condition itself, plus additional message streamed into it, if any, // and then it aborts the program. It aborts the program irrespective of // whether it is built in the debug mode or not. #define GTEST_CHECK_(condition) \ GTEST_AMBIGUOUS_ELSE_BLOCKER_ \ if (::testing::internal::IsTrue(condition)) \ ; \ else \ GTEST_LOG_(FATAL) << "Condition " #condition " failed. " // An all-mode assert to verify that the given POSIX-style function // call returns 0 (indicating success). Known limitation: this // doesn't expand to a balanced 'if' statement, so enclose the macro // in {} if you need to use it as the only statement in an 'if' // branch. #define GTEST_CHECK_POSIX_SUCCESS_(posix_call) \ if (const int gtest_error = (posix_call)) \ GTEST_LOG_(FATAL) << #posix_call << "failed with error " \ << gtest_error // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE. // // Use ImplicitCast_ as a safe version of static_cast for upcasting in // the type hierarchy (e.g. casting a Foo* to a SuperclassOfFoo* or a // const Foo*). When you use ImplicitCast_, the compiler checks that // the cast is safe. Such explicit ImplicitCast_s are necessary in // surprisingly many situations where C++ demands an exact type match // instead of an argument type convertable to a target type. // // The syntax for using ImplicitCast_ is the same as for static_cast: // // ImplicitCast_(expr) // // ImplicitCast_ would have been part of the C++ standard library, // but the proposal was submitted too late. It will probably make // its way into the language in the future. // // This relatively ugly name is intentional. It prevents clashes with // similar functions users may have (e.g., implicit_cast). The internal // namespace alone is not enough because the function can be found by ADL. template inline To ImplicitCast_(To x) { return x; } // When you upcast (that is, cast a pointer from type Foo to type // SuperclassOfFoo), it's fine to use ImplicitCast_<>, since upcasts // always succeed. When you downcast (that is, cast a pointer from // type Foo to type SubclassOfFoo), static_cast<> isn't safe, because // how do you know the pointer is really of type SubclassOfFoo? It // could be a bare Foo, or of type DifferentSubclassOfFoo. Thus, // when you downcast, you should use this macro. In debug mode, we // use dynamic_cast<> to double-check the downcast is legal (we die // if it's not). In normal mode, we do the efficient static_cast<> // instead. Thus, it's important to test in debug mode to make sure // the cast is legal! // This is the only place in the code we should use dynamic_cast<>. // In particular, you SHOULDN'T be using dynamic_cast<> in order to // do RTTI (eg code like this: // if (dynamic_cast(foo)) HandleASubclass1Object(foo); // if (dynamic_cast(foo)) HandleASubclass2Object(foo); // You should design the code some other way not to need this. // // This relatively ugly name is intentional. It prevents clashes with // similar functions users may have (e.g., down_cast). The internal // namespace alone is not enough because the function can be found by ADL. template // use like this: DownCast_(foo); inline To DownCast_(From* f) { // so we only accept pointers // Ensures that To is a sub-type of From *. This test is here only // for compile-time type checking, and has no overhead in an // optimized build at run-time, as it will be optimized away // completely. if (false) { const To to = NULL; ::testing::internal::ImplicitCast_(to); } #if GTEST_HAS_RTTI // RTTI: debug mode only! GTEST_CHECK_(f == NULL || dynamic_cast(f) != NULL); #endif return static_cast(f); } // Downcasts the pointer of type Base to Derived. // Derived must be a subclass of Base. The parameter MUST // point to a class of type Derived, not any subclass of it. // When RTTI is available, the function performs a runtime // check to enforce this. template Derived* CheckedDowncastToActualType(Base* base) { #if GTEST_HAS_RTTI GTEST_CHECK_(typeid(*base) == typeid(Derived)); return dynamic_cast(base); // NOLINT #else return static_cast(base); // Poor man's downcast. #endif } #if GTEST_HAS_STREAM_REDIRECTION // Defines the stderr capturer: // CaptureStdout - starts capturing stdout. // GetCapturedStdout - stops capturing stdout and returns the captured string. // CaptureStderr - starts capturing stderr. // GetCapturedStderr - stops capturing stderr and returns the captured string. // GTEST_API_ void CaptureStdout(); GTEST_API_ String GetCapturedStdout(); GTEST_API_ void CaptureStderr(); GTEST_API_ String GetCapturedStderr(); #endif // GTEST_HAS_STREAM_REDIRECTION #if GTEST_HAS_DEATH_TEST // A copy of all command line arguments. Set by InitGoogleTest(). extern ::std::vector g_argvs; // GTEST_HAS_DEATH_TEST implies we have ::std::string. const ::std::vector& GetArgvs(); #endif // GTEST_HAS_DEATH_TEST // Defines synchronization primitives. #if GTEST_HAS_PTHREAD // Sleeps for (roughly) n milli-seconds. This function is only for // testing Google Test's own constructs. Don't use it in user tests, // either directly or indirectly. inline void SleepMilliseconds(int n) { const timespec time = { 0, // 0 seconds. n * 1000L * 1000L, // And n ms. }; nanosleep(&time, NULL); } // Allows a controller thread to pause execution of newly created // threads until notified. Instances of this class must be created // and destroyed in the controller thread. // // This class is only for testing Google Test's own constructs. Do not // use it in user tests, either directly or indirectly. class Notification { public: Notification() : notified_(false) {} // Notifies all threads created with this notification to start. Must // be called from the controller thread. void Notify() { notified_ = true; } // Blocks until the controller thread notifies. Must be called from a test // thread. void WaitForNotification() { while(!notified_) { SleepMilliseconds(10); } } private: volatile bool notified_; GTEST_DISALLOW_COPY_AND_ASSIGN_(Notification); }; // As a C-function, ThreadFuncWithCLinkage cannot be templated itself. // Consequently, it cannot select a correct instantiation of ThreadWithParam // in order to call its Run(). Introducing ThreadWithParamBase as a // non-templated base class for ThreadWithParam allows us to bypass this // problem. class ThreadWithParamBase { public: virtual ~ThreadWithParamBase() {} virtual void Run() = 0; }; // pthread_create() accepts a pointer to a function type with the C linkage. // According to the Standard (7.5/1), function types with different linkages // are different even if they are otherwise identical. Some compilers (for // example, SunStudio) treat them as different types. Since class methods // cannot be defined with C-linkage we need to define a free C-function to // pass into pthread_create(). extern "C" inline void* ThreadFuncWithCLinkage(void* thread) { static_cast(thread)->Run(); return NULL; } // Helper class for testing Google Test's multi-threading constructs. // To use it, write: // // void ThreadFunc(int param) { /* Do things with param */ } // Notification thread_can_start; // ... // // The thread_can_start parameter is optional; you can supply NULL. // ThreadWithParam thread(&ThreadFunc, 5, &thread_can_start); // thread_can_start.Notify(); // // These classes are only for testing Google Test's own constructs. Do // not use them in user tests, either directly or indirectly. template class ThreadWithParam : public ThreadWithParamBase { public: typedef void (*UserThreadFunc)(T); ThreadWithParam( UserThreadFunc func, T param, Notification* thread_can_start) : func_(func), param_(param), thread_can_start_(thread_can_start), finished_(false) { ThreadWithParamBase* const base = this; // The thread can be created only after all fields except thread_ // have been initialized. GTEST_CHECK_POSIX_SUCCESS_( pthread_create(&thread_, 0, &ThreadFuncWithCLinkage, base)); } ~ThreadWithParam() { Join(); } void Join() { if (!finished_) { GTEST_CHECK_POSIX_SUCCESS_(pthread_join(thread_, 0)); finished_ = true; } } virtual void Run() { if (thread_can_start_ != NULL) thread_can_start_->WaitForNotification(); func_(param_); } private: const UserThreadFunc func_; // User-supplied thread function. const T param_; // User-supplied parameter to the thread function. // When non-NULL, used to block execution until the controller thread // notifies. Notification* const thread_can_start_; bool finished_; // true iff we know that the thread function has finished. pthread_t thread_; // The native thread object. GTEST_DISALLOW_COPY_AND_ASSIGN_(ThreadWithParam); }; // MutexBase and Mutex implement mutex on pthreads-based platforms. They // are used in conjunction with class MutexLock: // // Mutex mutex; // ... // MutexLock lock(&mutex); // Acquires the mutex and releases it at the end // // of the current scope. // // MutexBase implements behavior for both statically and dynamically // allocated mutexes. Do not use MutexBase directly. Instead, write // the following to define a static mutex: // // GTEST_DEFINE_STATIC_MUTEX_(g_some_mutex); // // You can forward declare a static mutex like this: // // GTEST_DECLARE_STATIC_MUTEX_(g_some_mutex); // // To create a dynamic mutex, just define an object of type Mutex. class MutexBase { public: // Acquires this mutex. void Lock() { GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_lock(&mutex_)); owner_ = pthread_self(); } // Releases this mutex. void Unlock() { // We don't protect writing to owner_ here, as it's the caller's // responsibility to ensure that the current thread holds the // mutex when this is called. owner_ = 0; GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_unlock(&mutex_)); } // Does nothing if the current thread holds the mutex. Otherwise, crashes // with high probability. void AssertHeld() const { GTEST_CHECK_(owner_ == pthread_self()) << "The current thread is not holding the mutex @" << this; } // A static mutex may be used before main() is entered. It may even // be used before the dynamic initialization stage. Therefore we // must be able to initialize a static mutex object at link time. // This means MutexBase has to be a POD and its member variables // have to be public. public: pthread_mutex_t mutex_; // The underlying pthread mutex. pthread_t owner_; // The thread holding the mutex; 0 means no one holds it. }; // Forward-declares a static mutex. # define GTEST_DECLARE_STATIC_MUTEX_(mutex) \ extern ::testing::internal::MutexBase mutex // Defines and statically (i.e. at link time) initializes a static mutex. # define GTEST_DEFINE_STATIC_MUTEX_(mutex) \ ::testing::internal::MutexBase mutex = { PTHREAD_MUTEX_INITIALIZER, 0 } // The Mutex class can only be used for mutexes created at runtime. It // shares its API with MutexBase otherwise. class Mutex : public MutexBase { public: Mutex() { GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_init(&mutex_, NULL)); owner_ = 0; } ~Mutex() { GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_destroy(&mutex_)); } private: GTEST_DISALLOW_COPY_AND_ASSIGN_(Mutex); }; // We cannot name this class MutexLock as the ctor declaration would // conflict with a macro named MutexLock, which is defined on some // platforms. Hence the typedef trick below. class GTestMutexLock { public: explicit GTestMutexLock(MutexBase* mutex) : mutex_(mutex) { mutex_->Lock(); } ~GTestMutexLock() { mutex_->Unlock(); } private: MutexBase* const mutex_; GTEST_DISALLOW_COPY_AND_ASSIGN_(GTestMutexLock); }; typedef GTestMutexLock MutexLock; // Helpers for ThreadLocal. // pthread_key_create() requires DeleteThreadLocalValue() to have // C-linkage. Therefore it cannot be templatized to access // ThreadLocal. Hence the need for class // ThreadLocalValueHolderBase. class ThreadLocalValueHolderBase { public: virtual ~ThreadLocalValueHolderBase() {} }; // Called by pthread to delete thread-local data stored by // pthread_setspecific(). extern "C" inline void DeleteThreadLocalValue(void* value_holder) { delete static_cast(value_holder); } // Implements thread-local storage on pthreads-based systems. // // // Thread 1 // ThreadLocal tl(100); // 100 is the default value for each thread. // // // Thread 2 // tl.set(150); // Changes the value for thread 2 only. // EXPECT_EQ(150, tl.get()); // // // Thread 1 // EXPECT_EQ(100, tl.get()); // In thread 1, tl has the original value. // tl.set(200); // EXPECT_EQ(200, tl.get()); // // The template type argument T must have a public copy constructor. // In addition, the default ThreadLocal constructor requires T to have // a public default constructor. // // An object managed for a thread by a ThreadLocal instance is deleted // when the thread exits. Or, if the ThreadLocal instance dies in // that thread, when the ThreadLocal dies. It's the user's // responsibility to ensure that all other threads using a ThreadLocal // have exited when it dies, or the per-thread objects for those // threads will not be deleted. // // Google Test only uses global ThreadLocal objects. That means they // will die after main() has returned. Therefore, no per-thread // object managed by Google Test will be leaked as long as all threads // using Google Test have exited when main() returns. template class ThreadLocal { public: ThreadLocal() : key_(CreateKey()), default_() {} explicit ThreadLocal(const T& value) : key_(CreateKey()), default_(value) {} ~ThreadLocal() { // Destroys the managed object for the current thread, if any. DeleteThreadLocalValue(pthread_getspecific(key_)); // Releases resources associated with the key. This will *not* // delete managed objects for other threads. GTEST_CHECK_POSIX_SUCCESS_(pthread_key_delete(key_)); } T* pointer() { return GetOrCreateValue(); } const T* pointer() const { return GetOrCreateValue(); } const T& get() const { return *pointer(); } void set(const T& value) { *pointer() = value; } private: // Holds a value of type T. class ValueHolder : public ThreadLocalValueHolderBase { public: explicit ValueHolder(const T& value) : value_(value) {} T* pointer() { return &value_; } private: T value_; GTEST_DISALLOW_COPY_AND_ASSIGN_(ValueHolder); }; static pthread_key_t CreateKey() { pthread_key_t key; // When a thread exits, DeleteThreadLocalValue() will be called on // the object managed for that thread. GTEST_CHECK_POSIX_SUCCESS_( pthread_key_create(&key, &DeleteThreadLocalValue)); return key; } T* GetOrCreateValue() const { ThreadLocalValueHolderBase* const holder = static_cast(pthread_getspecific(key_)); if (holder != NULL) { return CheckedDowncastToActualType(holder)->pointer(); } ValueHolder* const new_holder = new ValueHolder(default_); ThreadLocalValueHolderBase* const holder_base = new_holder; GTEST_CHECK_POSIX_SUCCESS_(pthread_setspecific(key_, holder_base)); return new_holder->pointer(); } // A key pthreads uses for looking up per-thread values. const pthread_key_t key_; const T default_; // The default value for each thread. GTEST_DISALLOW_COPY_AND_ASSIGN_(ThreadLocal); }; # define GTEST_IS_THREADSAFE 1 #else // GTEST_HAS_PTHREAD // A dummy implementation of synchronization primitives (mutex, lock, // and thread-local variable). Necessary for compiling Google Test where // mutex is not supported - using Google Test in multiple threads is not // supported on such platforms. class Mutex { public: Mutex() {} void AssertHeld() const {} }; # define GTEST_DECLARE_STATIC_MUTEX_(mutex) \ extern ::testing::internal::Mutex mutex # define GTEST_DEFINE_STATIC_MUTEX_(mutex) ::testing::internal::Mutex mutex class GTestMutexLock { public: explicit GTestMutexLock(Mutex*) {} // NOLINT }; typedef GTestMutexLock MutexLock; template class ThreadLocal { public: ThreadLocal() : value_() {} explicit ThreadLocal(const T& value) : value_(value) {} T* pointer() { return &value_; } const T* pointer() const { return &value_; } const T& get() const { return value_; } void set(const T& value) { value_ = value; } private: T value_; }; // The above synchronization primitives have dummy implementations. // Therefore Google Test is not thread-safe. # define GTEST_IS_THREADSAFE 0 #endif // GTEST_HAS_PTHREAD // Returns the number of threads running in the process, or 0 to indicate that // we cannot detect it. GTEST_API_ size_t GetThreadCount(); // Passing non-POD classes through ellipsis (...) crashes the ARM // compiler and generates a warning in Sun Studio. The Nokia Symbian // and the IBM XL C/C++ compiler try to instantiate a copy constructor // for objects passed through ellipsis (...), failing for uncopyable // objects. We define this to ensure that only POD is passed through // ellipsis on these systems. #if defined(__SYMBIAN32__) || defined(__IBMCPP__) || defined(__SUNPRO_CC) // We lose support for NULL detection where the compiler doesn't like // passing non-POD classes through ellipsis (...). # define GTEST_ELLIPSIS_NEEDS_POD_ 1 #else # define GTEST_CAN_COMPARE_NULL 1 #endif // The Nokia Symbian and IBM XL C/C++ compilers cannot decide between // const T& and const T* in a function template. These compilers // _can_ decide between class template specializations for T and T*, // so a tr1::type_traits-like is_pointer works. #if defined(__SYMBIAN32__) || defined(__IBMCPP__) # define GTEST_NEEDS_IS_POINTER_ 1 #endif template struct bool_constant { typedef bool_constant type; static const bool value = bool_value; }; template const bool bool_constant::value; typedef bool_constant false_type; typedef bool_constant true_type; template struct is_pointer : public false_type {}; template struct is_pointer : public true_type {}; template struct IteratorTraits { typedef typename Iterator::value_type value_type; }; template struct IteratorTraits { typedef T value_type; }; template struct IteratorTraits { typedef T value_type; }; #if GTEST_OS_WINDOWS # define GTEST_PATH_SEP_ "\\" # define GTEST_HAS_ALT_PATH_SEP_ 1 // The biggest signed integer type the compiler supports. typedef __int64 BiggestInt; #else # define GTEST_PATH_SEP_ "/" # define GTEST_HAS_ALT_PATH_SEP_ 0 typedef long long BiggestInt; // NOLINT #endif // GTEST_OS_WINDOWS // Utilities for char. // isspace(int ch) and friends accept an unsigned char or EOF. char // may be signed, depending on the compiler (or compiler flags). // Therefore we need to cast a char to unsigned char before calling // isspace(), etc. inline bool IsAlpha(char ch) { return isalpha(static_cast(ch)) != 0; } inline bool IsAlNum(char ch) { return isalnum(static_cast(ch)) != 0; } inline bool IsDigit(char ch) { return isdigit(static_cast(ch)) != 0; } inline bool IsLower(char ch) { return islower(static_cast(ch)) != 0; } inline bool IsSpace(char ch) { return isspace(static_cast(ch)) != 0; } inline bool IsUpper(char ch) { return isupper(static_cast(ch)) != 0; } inline bool IsXDigit(char ch) { return isxdigit(static_cast(ch)) != 0; } inline char ToLower(char ch) { return static_cast(tolower(static_cast(ch))); } inline char ToUpper(char ch) { return static_cast(toupper(static_cast(ch))); } // The testing::internal::posix namespace holds wrappers for common // POSIX functions. These wrappers hide the differences between // Windows/MSVC and POSIX systems. Since some compilers define these // standard functions as macros, the wrapper cannot have the same name // as the wrapped function. namespace posix { // Functions with a different name on Windows. #if GTEST_OS_WINDOWS typedef struct _stat StatStruct; # ifdef __BORLANDC__ inline int IsATTY(int fd) { return isatty(fd); } inline int StrCaseCmp(const char* s1, const char* s2) { return stricmp(s1, s2); } inline char* StrDup(const char* src) { return strdup(src); } # else // !__BORLANDC__ # if GTEST_OS_WINDOWS_MOBILE inline int IsATTY(int /* fd */) { return 0; } # else inline int IsATTY(int fd) { return _isatty(fd); } # endif // GTEST_OS_WINDOWS_MOBILE inline int StrCaseCmp(const char* s1, const char* s2) { return _stricmp(s1, s2); } inline char* StrDup(const char* src) { return _strdup(src); } # endif // __BORLANDC__ # if GTEST_OS_WINDOWS_MOBILE inline int FileNo(FILE* file) { return reinterpret_cast(_fileno(file)); } // Stat(), RmDir(), and IsDir() are not needed on Windows CE at this // time and thus not defined there. # else inline int FileNo(FILE* file) { return _fileno(file); } inline int Stat(const char* path, StatStruct* buf) { return _stat(path, buf); } inline int RmDir(const char* dir) { return _rmdir(dir); } inline bool IsDir(const StatStruct& st) { return (_S_IFDIR & st.st_mode) != 0; } # endif // GTEST_OS_WINDOWS_MOBILE #else typedef struct stat StatStruct; inline int FileNo(FILE* file) { return fileno(file); } inline int IsATTY(int fd) { return isatty(fd); } inline int Stat(const char* path, StatStruct* buf) { return stat(path, buf); } inline int StrCaseCmp(const char* s1, const char* s2) { return strcasecmp(s1, s2); } inline char* StrDup(const char* src) { return strdup(src); } inline int RmDir(const char* dir) { return rmdir(dir); } inline bool IsDir(const StatStruct& st) { return S_ISDIR(st.st_mode); } #endif // GTEST_OS_WINDOWS // Functions deprecated by MSVC 8.0. #ifdef _MSC_VER // Temporarily disable warning 4996 (deprecated function). # pragma warning(push) # pragma warning(disable:4996) #endif inline const char* StrNCpy(char* dest, const char* src, size_t n) { return strncpy(dest, src, n); } // ChDir(), FReopen(), FDOpen(), Read(), Write(), Close(), and // StrError() aren't needed on Windows CE at this time and thus not // defined there. #if !GTEST_OS_WINDOWS_MOBILE inline int ChDir(const char* dir) { return chdir(dir); } #endif inline FILE* FOpen(const char* path, const char* mode) { return fopen(path, mode); } #if !GTEST_OS_WINDOWS_MOBILE inline FILE *FReopen(const char* path, const char* mode, FILE* stream) { return freopen(path, mode, stream); } inline FILE* FDOpen(int fd, const char* mode) { return fdopen(fd, mode); } #endif inline int FClose(FILE* fp) { return fclose(fp); } #if !GTEST_OS_WINDOWS_MOBILE inline int Read(int fd, void* buf, unsigned int count) { return static_cast(read(fd, buf, count)); } inline int Write(int fd, const void* buf, unsigned int count) { return static_cast(write(fd, buf, count)); } inline int Close(int fd) { return close(fd); } inline const char* StrError(int errnum) { return strerror(errnum); } #endif inline const char* GetEnv(const char* name) { #if GTEST_OS_WINDOWS_MOBILE // We are on Windows CE, which has no environment variables. return NULL; #elif defined(__BORLANDC__) || defined(__SunOS_5_8) || defined(__SunOS_5_9) // Environment variables which we programmatically clear will be set to the // empty string rather than unset (NULL). Handle that case. const char* const env = getenv(name); return (env != NULL && env[0] != '\0') ? env : NULL; #else return getenv(name); #endif } #ifdef _MSC_VER # pragma warning(pop) // Restores the warning state. #endif #if GTEST_OS_WINDOWS_MOBILE // Windows CE has no C library. The abort() function is used in // several places in Google Test. This implementation provides a reasonable // imitation of standard behaviour. void Abort(); #else inline void Abort() { abort(); } #endif // GTEST_OS_WINDOWS_MOBILE } // namespace posix // The maximum number a BiggestInt can represent. This definition // works no matter BiggestInt is represented in one's complement or // two's complement. // // We cannot rely on numeric_limits in STL, as __int64 and long long // are not part of standard C++ and numeric_limits doesn't need to be // defined for them. const BiggestInt kMaxBiggestInt = ~(static_cast(1) << (8*sizeof(BiggestInt) - 1)); // This template class serves as a compile-time function from size to // type. It maps a size in bytes to a primitive type with that // size. e.g. // // TypeWithSize<4>::UInt // // is typedef-ed to be unsigned int (unsigned integer made up of 4 // bytes). // // Such functionality should belong to STL, but I cannot find it // there. // // Google Test uses this class in the implementation of floating-point // comparison. // // For now it only handles UInt (unsigned int) as that's all Google Test // needs. Other types can be easily added in the future if need // arises. template class TypeWithSize { public: // This prevents the user from using TypeWithSize with incorrect // values of N. typedef void UInt; }; // The specialization for size 4. template <> class TypeWithSize<4> { public: // unsigned int has size 4 in both gcc and MSVC. // // As base/basictypes.h doesn't compile on Windows, we cannot use // uint32, uint64, and etc here. typedef int Int; typedef unsigned int UInt; }; // The specialization for size 8. template <> class TypeWithSize<8> { public: #if GTEST_OS_WINDOWS typedef __int64 Int; typedef unsigned __int64 UInt; #else typedef long long Int; // NOLINT typedef unsigned long long UInt; // NOLINT #endif // GTEST_OS_WINDOWS }; // Integer types of known sizes. typedef TypeWithSize<4>::Int Int32; typedef TypeWithSize<4>::UInt UInt32; typedef TypeWithSize<8>::Int Int64; typedef TypeWithSize<8>::UInt UInt64; typedef TypeWithSize<8>::Int TimeInMillis; // Represents time in milliseconds. // Utilities for command line flags and environment variables. // Macro for referencing flags. #define GTEST_FLAG(name) FLAGS_gtest_##name // Macros for declaring flags. #define GTEST_DECLARE_bool_(name) GTEST_API_ extern bool GTEST_FLAG(name) #define GTEST_DECLARE_int32_(name) \ GTEST_API_ extern ::testing::internal::Int32 GTEST_FLAG(name) #define GTEST_DECLARE_string_(name) \ GTEST_API_ extern ::testing::internal::String GTEST_FLAG(name) // Macros for defining flags. #define GTEST_DEFINE_bool_(name, default_val, doc) \ GTEST_API_ bool GTEST_FLAG(name) = (default_val) #define GTEST_DEFINE_int32_(name, default_val, doc) \ GTEST_API_ ::testing::internal::Int32 GTEST_FLAG(name) = (default_val) #define GTEST_DEFINE_string_(name, default_val, doc) \ GTEST_API_ ::testing::internal::String GTEST_FLAG(name) = (default_val) // Parses 'str' for a 32-bit signed integer. If successful, writes the result // to *value and returns true; otherwise leaves *value unchanged and returns // false. // TODO(chandlerc): Find a better way to refactor flag and environment parsing // out of both gtest-port.cc and gtest.cc to avoid exporting this utility // function. bool ParseInt32(const Message& src_text, const char* str, Int32* value); // Parses a bool/Int32/string from the environment variable // corresponding to the given Google Test flag. bool BoolFromGTestEnv(const char* flag, bool default_val); GTEST_API_ Int32 Int32FromGTestEnv(const char* flag, Int32 default_val); const char* StringFromGTestEnv(const char* flag, const char* default_val); } // namespace internal } // namespace testing #endif // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PORT_H_ ugene-1.9.8/src/libs_3rdparty/gtest/src/gtest/internal/gtest-death-test-internal.h0000644000175000017500000003114511651544307026724 0ustar ilyailya// Copyright 2005, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Authors: wan@google.com (Zhanyong Wan), eefacm@gmail.com (Sean Mcafee) // // The Google C++ Testing Framework (Google Test) // // This header file defines internal utilities needed for implementing // death tests. They are subject to change without notice. #ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_DEATH_TEST_INTERNAL_H_ #define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_DEATH_TEST_INTERNAL_H_ #include "gtest/internal/gtest-internal.h" #include namespace testing { namespace internal { GTEST_DECLARE_string_(internal_run_death_test); // Names of the flags (needed for parsing Google Test flags). const char kDeathTestStyleFlag[] = "death_test_style"; const char kDeathTestUseFork[] = "death_test_use_fork"; const char kInternalRunDeathTestFlag[] = "internal_run_death_test"; #if GTEST_HAS_DEATH_TEST // DeathTest is a class that hides much of the complexity of the // GTEST_DEATH_TEST_ macro. It is abstract; its static Create method // returns a concrete class that depends on the prevailing death test // style, as defined by the --gtest_death_test_style and/or // --gtest_internal_run_death_test flags. // In describing the results of death tests, these terms are used with // the corresponding definitions: // // exit status: The integer exit information in the format specified // by wait(2) // exit code: The integer code passed to exit(3), _exit(2), or // returned from main() class GTEST_API_ DeathTest { public: // Create returns false if there was an error determining the // appropriate action to take for the current death test; for example, // if the gtest_death_test_style flag is set to an invalid value. // The LastMessage method will return a more detailed message in that // case. Otherwise, the DeathTest pointer pointed to by the "test" // argument is set. If the death test should be skipped, the pointer // is set to NULL; otherwise, it is set to the address of a new concrete // DeathTest object that controls the execution of the current test. static bool Create(const char* statement, const RE* regex, const char* file, int line, DeathTest** test); DeathTest(); virtual ~DeathTest() { } // A helper class that aborts a death test when it's deleted. class ReturnSentinel { public: explicit ReturnSentinel(DeathTest* test) : test_(test) { } ~ReturnSentinel() { test_->Abort(TEST_ENCOUNTERED_RETURN_STATEMENT); } private: DeathTest* const test_; GTEST_DISALLOW_COPY_AND_ASSIGN_(ReturnSentinel); } GTEST_ATTRIBUTE_UNUSED_; // An enumeration of possible roles that may be taken when a death // test is encountered. EXECUTE means that the death test logic should // be executed immediately. OVERSEE means that the program should prepare // the appropriate environment for a child process to execute the death // test, then wait for it to complete. enum TestRole { OVERSEE_TEST, EXECUTE_TEST }; // An enumeration of the three reasons that a test might be aborted. enum AbortReason { TEST_ENCOUNTERED_RETURN_STATEMENT, TEST_THREW_EXCEPTION, TEST_DID_NOT_DIE }; // Assumes one of the above roles. virtual TestRole AssumeRole() = 0; // Waits for the death test to finish and returns its status. virtual int Wait() = 0; // Returns true if the death test passed; that is, the test process // exited during the test, its exit status matches a user-supplied // predicate, and its stderr output matches a user-supplied regular // expression. // The user-supplied predicate may be a macro expression rather // than a function pointer or functor, or else Wait and Passed could // be combined. virtual bool Passed(bool exit_status_ok) = 0; // Signals that the death test did not die as expected. virtual void Abort(AbortReason reason) = 0; // Returns a human-readable outcome message regarding the outcome of // the last death test. static const char* LastMessage(); static void set_last_death_test_message(const String& message); private: // A string containing a description of the outcome of the last death test. static String last_death_test_message_; GTEST_DISALLOW_COPY_AND_ASSIGN_(DeathTest); }; // Factory interface for death tests. May be mocked out for testing. class DeathTestFactory { public: virtual ~DeathTestFactory() { } virtual bool Create(const char* statement, const RE* regex, const char* file, int line, DeathTest** test) = 0; }; // A concrete DeathTestFactory implementation for normal use. class DefaultDeathTestFactory : public DeathTestFactory { public: virtual bool Create(const char* statement, const RE* regex, const char* file, int line, DeathTest** test); }; // Returns true if exit_status describes a process that was terminated // by a signal, or exited normally with a nonzero exit code. GTEST_API_ bool ExitedUnsuccessfully(int exit_status); // Traps C++ exceptions escaping statement and reports them as test // failures. Note that trapping SEH exceptions is not implemented here. # if GTEST_HAS_EXCEPTIONS # define GTEST_EXECUTE_DEATH_TEST_STATEMENT_(statement, death_test) \ try { \ GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \ } catch (const ::std::exception& gtest_exception) { \ fprintf(\ stderr, \ "\n%s: Caught std::exception-derived exception escaping the " \ "death test statement. Exception message: %s\n", \ ::testing::internal::FormatFileLocation(__FILE__, __LINE__).c_str(), \ gtest_exception.what()); \ fflush(stderr); \ death_test->Abort(::testing::internal::DeathTest::TEST_THREW_EXCEPTION); \ } catch (...) { \ death_test->Abort(::testing::internal::DeathTest::TEST_THREW_EXCEPTION); \ } # else # define GTEST_EXECUTE_DEATH_TEST_STATEMENT_(statement, death_test) \ GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement) # endif // This macro is for implementing ASSERT_DEATH*, EXPECT_DEATH*, // ASSERT_EXIT*, and EXPECT_EXIT*. # define GTEST_DEATH_TEST_(statement, predicate, regex, fail) \ GTEST_AMBIGUOUS_ELSE_BLOCKER_ \ if (::testing::internal::AlwaysTrue()) { \ const ::testing::internal::RE& gtest_regex = (regex); \ ::testing::internal::DeathTest* gtest_dt; \ if (!::testing::internal::DeathTest::Create(#statement, >est_regex, \ __FILE__, __LINE__, >est_dt)) { \ goto GTEST_CONCAT_TOKEN_(gtest_label_, __LINE__); \ } \ if (gtest_dt != NULL) { \ ::testing::internal::scoped_ptr< ::testing::internal::DeathTest> \ gtest_dt_ptr(gtest_dt); \ switch (gtest_dt->AssumeRole()) { \ case ::testing::internal::DeathTest::OVERSEE_TEST: \ if (!gtest_dt->Passed(predicate(gtest_dt->Wait()))) { \ goto GTEST_CONCAT_TOKEN_(gtest_label_, __LINE__); \ } \ break; \ case ::testing::internal::DeathTest::EXECUTE_TEST: { \ ::testing::internal::DeathTest::ReturnSentinel \ gtest_sentinel(gtest_dt); \ GTEST_EXECUTE_DEATH_TEST_STATEMENT_(statement, gtest_dt); \ gtest_dt->Abort(::testing::internal::DeathTest::TEST_DID_NOT_DIE); \ break; \ } \ default: \ break; \ } \ } \ } else \ GTEST_CONCAT_TOKEN_(gtest_label_, __LINE__): \ fail(::testing::internal::DeathTest::LastMessage()) // The symbol "fail" here expands to something into which a message // can be streamed. // A class representing the parsed contents of the // --gtest_internal_run_death_test flag, as it existed when // RUN_ALL_TESTS was called. class InternalRunDeathTestFlag { public: InternalRunDeathTestFlag(const String& a_file, int a_line, int an_index, int a_write_fd) : file_(a_file), line_(a_line), index_(an_index), write_fd_(a_write_fd) {} ~InternalRunDeathTestFlag() { if (write_fd_ >= 0) posix::Close(write_fd_); } String file() const { return file_; } int line() const { return line_; } int index() const { return index_; } int write_fd() const { return write_fd_; } private: String file_; int line_; int index_; int write_fd_; GTEST_DISALLOW_COPY_AND_ASSIGN_(InternalRunDeathTestFlag); }; // Returns a newly created InternalRunDeathTestFlag object with fields // initialized from the GTEST_FLAG(internal_run_death_test) flag if // the flag is specified; otherwise returns NULL. InternalRunDeathTestFlag* ParseInternalRunDeathTestFlag(); #else // GTEST_HAS_DEATH_TEST // This macro is used for implementing macros such as // EXPECT_DEATH_IF_SUPPORTED and ASSERT_DEATH_IF_SUPPORTED on systems where // death tests are not supported. Those macros must compile on such systems // iff EXPECT_DEATH and ASSERT_DEATH compile with the same parameters on // systems that support death tests. This allows one to write such a macro // on a system that does not support death tests and be sure that it will // compile on a death-test supporting system. // // Parameters: // statement - A statement that a macro such as EXPECT_DEATH would test // for program termination. This macro has to make sure this // statement is compiled but not executed, to ensure that // EXPECT_DEATH_IF_SUPPORTED compiles with a certain // parameter iff EXPECT_DEATH compiles with it. // regex - A regex that a macro such as EXPECT_DEATH would use to test // the output of statement. This parameter has to be // compiled but not evaluated by this macro, to ensure that // this macro only accepts expressions that a macro such as // EXPECT_DEATH would accept. // terminator - Must be an empty statement for EXPECT_DEATH_IF_SUPPORTED // and a return statement for ASSERT_DEATH_IF_SUPPORTED. // This ensures that ASSERT_DEATH_IF_SUPPORTED will not // compile inside functions where ASSERT_DEATH doesn't // compile. // // The branch that has an always false condition is used to ensure that // statement and regex are compiled (and thus syntactically correct) but // never executed. The unreachable code macro protects the terminator // statement from generating an 'unreachable code' warning in case // statement unconditionally returns or throws. The Message constructor at // the end allows the syntax of streaming additional messages into the // macro, for compilational compatibility with EXPECT_DEATH/ASSERT_DEATH. # define GTEST_UNSUPPORTED_DEATH_TEST_(statement, regex, terminator) \ GTEST_AMBIGUOUS_ELSE_BLOCKER_ \ if (::testing::internal::AlwaysTrue()) { \ GTEST_LOG_(WARNING) \ << "Death tests are not supported on this platform.\n" \ << "Statement '" #statement "' cannot be verified."; \ } else if (::testing::internal::AlwaysFalse()) { \ ::testing::internal::RE::PartialMatch(".*", (regex)); \ GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \ terminator; \ } else \ ::testing::Message() #endif // GTEST_HAS_DEATH_TEST } // namespace internal } // namespace testing #endif // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_DEATH_TEST_INTERNAL_H_ ugene-1.9.8/src/libs_3rdparty/gtest/src/gtest/internal/gtest-tuple.h0000644000175000017500000006673311651544307024214 0ustar ilyailya// This file was GENERATED by a script. DO NOT EDIT BY HAND!!! // Copyright 2009 Google Inc. // All Rights Reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Author: wan@google.com (Zhanyong Wan) // Implements a subset of TR1 tuple needed by Google Test and Google Mock. #ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_TUPLE_H_ #define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_TUPLE_H_ #include // For ::std::pair. // The compiler used in Symbian has a bug that prevents us from declaring the // tuple template as a friend (it complains that tuple is redefined). This // hack bypasses the bug by declaring the members that should otherwise be // private as public. // Sun Studio versions < 12 also have the above bug. #if defined(__SYMBIAN32__) || (defined(__SUNPRO_CC) && __SUNPRO_CC < 0x590) # define GTEST_DECLARE_TUPLE_AS_FRIEND_ public: #else # define GTEST_DECLARE_TUPLE_AS_FRIEND_ \ template friend class tuple; \ private: #endif // GTEST_n_TUPLE_(T) is the type of an n-tuple. #define GTEST_0_TUPLE_(T) tuple<> #define GTEST_1_TUPLE_(T) tuple #define GTEST_2_TUPLE_(T) tuple #define GTEST_3_TUPLE_(T) tuple #define GTEST_4_TUPLE_(T) tuple #define GTEST_5_TUPLE_(T) tuple #define GTEST_6_TUPLE_(T) tuple #define GTEST_7_TUPLE_(T) tuple #define GTEST_8_TUPLE_(T) tuple #define GTEST_9_TUPLE_(T) tuple #define GTEST_10_TUPLE_(T) tuple // GTEST_n_TYPENAMES_(T) declares a list of n typenames. #define GTEST_0_TYPENAMES_(T) #define GTEST_1_TYPENAMES_(T) typename T##0 #define GTEST_2_TYPENAMES_(T) typename T##0, typename T##1 #define GTEST_3_TYPENAMES_(T) typename T##0, typename T##1, typename T##2 #define GTEST_4_TYPENAMES_(T) typename T##0, typename T##1, typename T##2, \ typename T##3 #define GTEST_5_TYPENAMES_(T) typename T##0, typename T##1, typename T##2, \ typename T##3, typename T##4 #define GTEST_6_TYPENAMES_(T) typename T##0, typename T##1, typename T##2, \ typename T##3, typename T##4, typename T##5 #define GTEST_7_TYPENAMES_(T) typename T##0, typename T##1, typename T##2, \ typename T##3, typename T##4, typename T##5, typename T##6 #define GTEST_8_TYPENAMES_(T) typename T##0, typename T##1, typename T##2, \ typename T##3, typename T##4, typename T##5, typename T##6, typename T##7 #define GTEST_9_TYPENAMES_(T) typename T##0, typename T##1, typename T##2, \ typename T##3, typename T##4, typename T##5, typename T##6, \ typename T##7, typename T##8 #define GTEST_10_TYPENAMES_(T) typename T##0, typename T##1, typename T##2, \ typename T##3, typename T##4, typename T##5, typename T##6, \ typename T##7, typename T##8, typename T##9 // In theory, defining stuff in the ::std namespace is undefined // behavior. We can do this as we are playing the role of a standard // library vendor. namespace std { namespace tr1 { template class tuple; // Anything in namespace gtest_internal is Google Test's INTERNAL // IMPLEMENTATION DETAIL and MUST NOT BE USED DIRECTLY in user code. namespace gtest_internal { // ByRef::type is T if T is a reference; otherwise it's const T&. template struct ByRef { typedef const T& type; }; // NOLINT template struct ByRef { typedef T& type; }; // NOLINT // A handy wrapper for ByRef. #define GTEST_BY_REF_(T) typename ::std::tr1::gtest_internal::ByRef::type // AddRef::type is T if T is a reference; otherwise it's T&. This // is the same as tr1::add_reference::type. template struct AddRef { typedef T& type; }; // NOLINT template struct AddRef { typedef T& type; }; // NOLINT // A handy wrapper for AddRef. #define GTEST_ADD_REF_(T) typename ::std::tr1::gtest_internal::AddRef::type // A helper for implementing get(). template class Get; // A helper for implementing tuple_element. kIndexValid is true // iff k < the number of fields in tuple type T. template struct TupleElement; template struct TupleElement { typedef T0 type; }; template struct TupleElement { typedef T1 type; }; template struct TupleElement { typedef T2 type; }; template struct TupleElement { typedef T3 type; }; template struct TupleElement { typedef T4 type; }; template struct TupleElement { typedef T5 type; }; template struct TupleElement { typedef T6 type; }; template struct TupleElement { typedef T7 type; }; template struct TupleElement { typedef T8 type; }; template struct TupleElement { typedef T9 type; }; } // namespace gtest_internal template <> class tuple<> { public: tuple() {} tuple(const tuple& /* t */) {} tuple& operator=(const tuple& /* t */) { return *this; } }; template class GTEST_1_TUPLE_(T) { public: template friend class gtest_internal::Get; tuple() : f0_() {} explicit tuple(GTEST_BY_REF_(T0) f0) : f0_(f0) {} tuple(const tuple& t) : f0_(t.f0_) {} template tuple(const GTEST_1_TUPLE_(U)& t) : f0_(t.f0_) {} tuple& operator=(const tuple& t) { return CopyFrom(t); } template tuple& operator=(const GTEST_1_TUPLE_(U)& t) { return CopyFrom(t); } GTEST_DECLARE_TUPLE_AS_FRIEND_ template tuple& CopyFrom(const GTEST_1_TUPLE_(U)& t) { f0_ = t.f0_; return *this; } T0 f0_; }; template class GTEST_2_TUPLE_(T) { public: template friend class gtest_internal::Get; tuple() : f0_(), f1_() {} explicit tuple(GTEST_BY_REF_(T0) f0, GTEST_BY_REF_(T1) f1) : f0_(f0), f1_(f1) {} tuple(const tuple& t) : f0_(t.f0_), f1_(t.f1_) {} template tuple(const GTEST_2_TUPLE_(U)& t) : f0_(t.f0_), f1_(t.f1_) {} template tuple(const ::std::pair& p) : f0_(p.first), f1_(p.second) {} tuple& operator=(const tuple& t) { return CopyFrom(t); } template tuple& operator=(const GTEST_2_TUPLE_(U)& t) { return CopyFrom(t); } template tuple& operator=(const ::std::pair& p) { f0_ = p.first; f1_ = p.second; return *this; } GTEST_DECLARE_TUPLE_AS_FRIEND_ template tuple& CopyFrom(const GTEST_2_TUPLE_(U)& t) { f0_ = t.f0_; f1_ = t.f1_; return *this; } T0 f0_; T1 f1_; }; template class GTEST_3_TUPLE_(T) { public: template friend class gtest_internal::Get; tuple() : f0_(), f1_(), f2_() {} explicit tuple(GTEST_BY_REF_(T0) f0, GTEST_BY_REF_(T1) f1, GTEST_BY_REF_(T2) f2) : f0_(f0), f1_(f1), f2_(f2) {} tuple(const tuple& t) : f0_(t.f0_), f1_(t.f1_), f2_(t.f2_) {} template tuple(const GTEST_3_TUPLE_(U)& t) : f0_(t.f0_), f1_(t.f1_), f2_(t.f2_) {} tuple& operator=(const tuple& t) { return CopyFrom(t); } template tuple& operator=(const GTEST_3_TUPLE_(U)& t) { return CopyFrom(t); } GTEST_DECLARE_TUPLE_AS_FRIEND_ template tuple& CopyFrom(const GTEST_3_TUPLE_(U)& t) { f0_ = t.f0_; f1_ = t.f1_; f2_ = t.f2_; return *this; } T0 f0_; T1 f1_; T2 f2_; }; template class GTEST_4_TUPLE_(T) { public: template friend class gtest_internal::Get; tuple() : f0_(), f1_(), f2_(), f3_() {} explicit tuple(GTEST_BY_REF_(T0) f0, GTEST_BY_REF_(T1) f1, GTEST_BY_REF_(T2) f2, GTEST_BY_REF_(T3) f3) : f0_(f0), f1_(f1), f2_(f2), f3_(f3) {} tuple(const tuple& t) : f0_(t.f0_), f1_(t.f1_), f2_(t.f2_), f3_(t.f3_) {} template tuple(const GTEST_4_TUPLE_(U)& t) : f0_(t.f0_), f1_(t.f1_), f2_(t.f2_), f3_(t.f3_) {} tuple& operator=(const tuple& t) { return CopyFrom(t); } template tuple& operator=(const GTEST_4_TUPLE_(U)& t) { return CopyFrom(t); } GTEST_DECLARE_TUPLE_AS_FRIEND_ template tuple& CopyFrom(const GTEST_4_TUPLE_(U)& t) { f0_ = t.f0_; f1_ = t.f1_; f2_ = t.f2_; f3_ = t.f3_; return *this; } T0 f0_; T1 f1_; T2 f2_; T3 f3_; }; template class GTEST_5_TUPLE_(T) { public: template friend class gtest_internal::Get; tuple() : f0_(), f1_(), f2_(), f3_(), f4_() {} explicit tuple(GTEST_BY_REF_(T0) f0, GTEST_BY_REF_(T1) f1, GTEST_BY_REF_(T2) f2, GTEST_BY_REF_(T3) f3, GTEST_BY_REF_(T4) f4) : f0_(f0), f1_(f1), f2_(f2), f3_(f3), f4_(f4) {} tuple(const tuple& t) : f0_(t.f0_), f1_(t.f1_), f2_(t.f2_), f3_(t.f3_), f4_(t.f4_) {} template tuple(const GTEST_5_TUPLE_(U)& t) : f0_(t.f0_), f1_(t.f1_), f2_(t.f2_), f3_(t.f3_), f4_(t.f4_) {} tuple& operator=(const tuple& t) { return CopyFrom(t); } template tuple& operator=(const GTEST_5_TUPLE_(U)& t) { return CopyFrom(t); } GTEST_DECLARE_TUPLE_AS_FRIEND_ template tuple& CopyFrom(const GTEST_5_TUPLE_(U)& t) { f0_ = t.f0_; f1_ = t.f1_; f2_ = t.f2_; f3_ = t.f3_; f4_ = t.f4_; return *this; } T0 f0_; T1 f1_; T2 f2_; T3 f3_; T4 f4_; }; template class GTEST_6_TUPLE_(T) { public: template friend class gtest_internal::Get; tuple() : f0_(), f1_(), f2_(), f3_(), f4_(), f5_() {} explicit tuple(GTEST_BY_REF_(T0) f0, GTEST_BY_REF_(T1) f1, GTEST_BY_REF_(T2) f2, GTEST_BY_REF_(T3) f3, GTEST_BY_REF_(T4) f4, GTEST_BY_REF_(T5) f5) : f0_(f0), f1_(f1), f2_(f2), f3_(f3), f4_(f4), f5_(f5) {} tuple(const tuple& t) : f0_(t.f0_), f1_(t.f1_), f2_(t.f2_), f3_(t.f3_), f4_(t.f4_), f5_(t.f5_) {} template tuple(const GTEST_6_TUPLE_(U)& t) : f0_(t.f0_), f1_(t.f1_), f2_(t.f2_), f3_(t.f3_), f4_(t.f4_), f5_(t.f5_) {} tuple& operator=(const tuple& t) { return CopyFrom(t); } template tuple& operator=(const GTEST_6_TUPLE_(U)& t) { return CopyFrom(t); } GTEST_DECLARE_TUPLE_AS_FRIEND_ template tuple& CopyFrom(const GTEST_6_TUPLE_(U)& t) { f0_ = t.f0_; f1_ = t.f1_; f2_ = t.f2_; f3_ = t.f3_; f4_ = t.f4_; f5_ = t.f5_; return *this; } T0 f0_; T1 f1_; T2 f2_; T3 f3_; T4 f4_; T5 f5_; }; template class GTEST_7_TUPLE_(T) { public: template friend class gtest_internal::Get; tuple() : f0_(), f1_(), f2_(), f3_(), f4_(), f5_(), f6_() {} explicit tuple(GTEST_BY_REF_(T0) f0, GTEST_BY_REF_(T1) f1, GTEST_BY_REF_(T2) f2, GTEST_BY_REF_(T3) f3, GTEST_BY_REF_(T4) f4, GTEST_BY_REF_(T5) f5, GTEST_BY_REF_(T6) f6) : f0_(f0), f1_(f1), f2_(f2), f3_(f3), f4_(f4), f5_(f5), f6_(f6) {} tuple(const tuple& t) : f0_(t.f0_), f1_(t.f1_), f2_(t.f2_), f3_(t.f3_), f4_(t.f4_), f5_(t.f5_), f6_(t.f6_) {} template tuple(const GTEST_7_TUPLE_(U)& t) : f0_(t.f0_), f1_(t.f1_), f2_(t.f2_), f3_(t.f3_), f4_(t.f4_), f5_(t.f5_), f6_(t.f6_) {} tuple& operator=(const tuple& t) { return CopyFrom(t); } template tuple& operator=(const GTEST_7_TUPLE_(U)& t) { return CopyFrom(t); } GTEST_DECLARE_TUPLE_AS_FRIEND_ template tuple& CopyFrom(const GTEST_7_TUPLE_(U)& t) { f0_ = t.f0_; f1_ = t.f1_; f2_ = t.f2_; f3_ = t.f3_; f4_ = t.f4_; f5_ = t.f5_; f6_ = t.f6_; return *this; } T0 f0_; T1 f1_; T2 f2_; T3 f3_; T4 f4_; T5 f5_; T6 f6_; }; template class GTEST_8_TUPLE_(T) { public: template friend class gtest_internal::Get; tuple() : f0_(), f1_(), f2_(), f3_(), f4_(), f5_(), f6_(), f7_() {} explicit tuple(GTEST_BY_REF_(T0) f0, GTEST_BY_REF_(T1) f1, GTEST_BY_REF_(T2) f2, GTEST_BY_REF_(T3) f3, GTEST_BY_REF_(T4) f4, GTEST_BY_REF_(T5) f5, GTEST_BY_REF_(T6) f6, GTEST_BY_REF_(T7) f7) : f0_(f0), f1_(f1), f2_(f2), f3_(f3), f4_(f4), f5_(f5), f6_(f6), f7_(f7) {} tuple(const tuple& t) : f0_(t.f0_), f1_(t.f1_), f2_(t.f2_), f3_(t.f3_), f4_(t.f4_), f5_(t.f5_), f6_(t.f6_), f7_(t.f7_) {} template tuple(const GTEST_8_TUPLE_(U)& t) : f0_(t.f0_), f1_(t.f1_), f2_(t.f2_), f3_(t.f3_), f4_(t.f4_), f5_(t.f5_), f6_(t.f6_), f7_(t.f7_) {} tuple& operator=(const tuple& t) { return CopyFrom(t); } template tuple& operator=(const GTEST_8_TUPLE_(U)& t) { return CopyFrom(t); } GTEST_DECLARE_TUPLE_AS_FRIEND_ template tuple& CopyFrom(const GTEST_8_TUPLE_(U)& t) { f0_ = t.f0_; f1_ = t.f1_; f2_ = t.f2_; f3_ = t.f3_; f4_ = t.f4_; f5_ = t.f5_; f6_ = t.f6_; f7_ = t.f7_; return *this; } T0 f0_; T1 f1_; T2 f2_; T3 f3_; T4 f4_; T5 f5_; T6 f6_; T7 f7_; }; template class GTEST_9_TUPLE_(T) { public: template friend class gtest_internal::Get; tuple() : f0_(), f1_(), f2_(), f3_(), f4_(), f5_(), f6_(), f7_(), f8_() {} explicit tuple(GTEST_BY_REF_(T0) f0, GTEST_BY_REF_(T1) f1, GTEST_BY_REF_(T2) f2, GTEST_BY_REF_(T3) f3, GTEST_BY_REF_(T4) f4, GTEST_BY_REF_(T5) f5, GTEST_BY_REF_(T6) f6, GTEST_BY_REF_(T7) f7, GTEST_BY_REF_(T8) f8) : f0_(f0), f1_(f1), f2_(f2), f3_(f3), f4_(f4), f5_(f5), f6_(f6), f7_(f7), f8_(f8) {} tuple(const tuple& t) : f0_(t.f0_), f1_(t.f1_), f2_(t.f2_), f3_(t.f3_), f4_(t.f4_), f5_(t.f5_), f6_(t.f6_), f7_(t.f7_), f8_(t.f8_) {} template tuple(const GTEST_9_TUPLE_(U)& t) : f0_(t.f0_), f1_(t.f1_), f2_(t.f2_), f3_(t.f3_), f4_(t.f4_), f5_(t.f5_), f6_(t.f6_), f7_(t.f7_), f8_(t.f8_) {} tuple& operator=(const tuple& t) { return CopyFrom(t); } template tuple& operator=(const GTEST_9_TUPLE_(U)& t) { return CopyFrom(t); } GTEST_DECLARE_TUPLE_AS_FRIEND_ template tuple& CopyFrom(const GTEST_9_TUPLE_(U)& t) { f0_ = t.f0_; f1_ = t.f1_; f2_ = t.f2_; f3_ = t.f3_; f4_ = t.f4_; f5_ = t.f5_; f6_ = t.f6_; f7_ = t.f7_; f8_ = t.f8_; return *this; } T0 f0_; T1 f1_; T2 f2_; T3 f3_; T4 f4_; T5 f5_; T6 f6_; T7 f7_; T8 f8_; }; template class tuple { public: template friend class gtest_internal::Get; tuple() : f0_(), f1_(), f2_(), f3_(), f4_(), f5_(), f6_(), f7_(), f8_(), f9_() {} explicit tuple(GTEST_BY_REF_(T0) f0, GTEST_BY_REF_(T1) f1, GTEST_BY_REF_(T2) f2, GTEST_BY_REF_(T3) f3, GTEST_BY_REF_(T4) f4, GTEST_BY_REF_(T5) f5, GTEST_BY_REF_(T6) f6, GTEST_BY_REF_(T7) f7, GTEST_BY_REF_(T8) f8, GTEST_BY_REF_(T9) f9) : f0_(f0), f1_(f1), f2_(f2), f3_(f3), f4_(f4), f5_(f5), f6_(f6), f7_(f7), f8_(f8), f9_(f9) {} tuple(const tuple& t) : f0_(t.f0_), f1_(t.f1_), f2_(t.f2_), f3_(t.f3_), f4_(t.f4_), f5_(t.f5_), f6_(t.f6_), f7_(t.f7_), f8_(t.f8_), f9_(t.f9_) {} template tuple(const GTEST_10_TUPLE_(U)& t) : f0_(t.f0_), f1_(t.f1_), f2_(t.f2_), f3_(t.f3_), f4_(t.f4_), f5_(t.f5_), f6_(t.f6_), f7_(t.f7_), f8_(t.f8_), f9_(t.f9_) {} tuple& operator=(const tuple& t) { return CopyFrom(t); } template tuple& operator=(const GTEST_10_TUPLE_(U)& t) { return CopyFrom(t); } GTEST_DECLARE_TUPLE_AS_FRIEND_ template tuple& CopyFrom(const GTEST_10_TUPLE_(U)& t) { f0_ = t.f0_; f1_ = t.f1_; f2_ = t.f2_; f3_ = t.f3_; f4_ = t.f4_; f5_ = t.f5_; f6_ = t.f6_; f7_ = t.f7_; f8_ = t.f8_; f9_ = t.f9_; return *this; } T0 f0_; T1 f1_; T2 f2_; T3 f3_; T4 f4_; T5 f5_; T6 f6_; T7 f7_; T8 f8_; T9 f9_; }; // 6.1.3.2 Tuple creation functions. // Known limitations: we don't support passing an // std::tr1::reference_wrapper to make_tuple(). And we don't // implement tie(). inline tuple<> make_tuple() { return tuple<>(); } template inline GTEST_1_TUPLE_(T) make_tuple(const T0& f0) { return GTEST_1_TUPLE_(T)(f0); } template inline GTEST_2_TUPLE_(T) make_tuple(const T0& f0, const T1& f1) { return GTEST_2_TUPLE_(T)(f0, f1); } template inline GTEST_3_TUPLE_(T) make_tuple(const T0& f0, const T1& f1, const T2& f2) { return GTEST_3_TUPLE_(T)(f0, f1, f2); } template inline GTEST_4_TUPLE_(T) make_tuple(const T0& f0, const T1& f1, const T2& f2, const T3& f3) { return GTEST_4_TUPLE_(T)(f0, f1, f2, f3); } template inline GTEST_5_TUPLE_(T) make_tuple(const T0& f0, const T1& f1, const T2& f2, const T3& f3, const T4& f4) { return GTEST_5_TUPLE_(T)(f0, f1, f2, f3, f4); } template inline GTEST_6_TUPLE_(T) make_tuple(const T0& f0, const T1& f1, const T2& f2, const T3& f3, const T4& f4, const T5& f5) { return GTEST_6_TUPLE_(T)(f0, f1, f2, f3, f4, f5); } template inline GTEST_7_TUPLE_(T) make_tuple(const T0& f0, const T1& f1, const T2& f2, const T3& f3, const T4& f4, const T5& f5, const T6& f6) { return GTEST_7_TUPLE_(T)(f0, f1, f2, f3, f4, f5, f6); } template inline GTEST_8_TUPLE_(T) make_tuple(const T0& f0, const T1& f1, const T2& f2, const T3& f3, const T4& f4, const T5& f5, const T6& f6, const T7& f7) { return GTEST_8_TUPLE_(T)(f0, f1, f2, f3, f4, f5, f6, f7); } template inline GTEST_9_TUPLE_(T) make_tuple(const T0& f0, const T1& f1, const T2& f2, const T3& f3, const T4& f4, const T5& f5, const T6& f6, const T7& f7, const T8& f8) { return GTEST_9_TUPLE_(T)(f0, f1, f2, f3, f4, f5, f6, f7, f8); } template inline GTEST_10_TUPLE_(T) make_tuple(const T0& f0, const T1& f1, const T2& f2, const T3& f3, const T4& f4, const T5& f5, const T6& f6, const T7& f7, const T8& f8, const T9& f9) { return GTEST_10_TUPLE_(T)(f0, f1, f2, f3, f4, f5, f6, f7, f8, f9); } // 6.1.3.3 Tuple helper classes. template struct tuple_size; template struct tuple_size { static const int value = 0; }; template struct tuple_size { static const int value = 1; }; template struct tuple_size { static const int value = 2; }; template struct tuple_size { static const int value = 3; }; template struct tuple_size { static const int value = 4; }; template struct tuple_size { static const int value = 5; }; template struct tuple_size { static const int value = 6; }; template struct tuple_size { static const int value = 7; }; template struct tuple_size { static const int value = 8; }; template struct tuple_size { static const int value = 9; }; template struct tuple_size { static const int value = 10; }; template struct tuple_element { typedef typename gtest_internal::TupleElement< k < (tuple_size::value), k, Tuple>::type type; }; #define GTEST_TUPLE_ELEMENT_(k, Tuple) typename tuple_element::type // 6.1.3.4 Element access. namespace gtest_internal { template <> class Get<0> { public: template static GTEST_ADD_REF_(GTEST_TUPLE_ELEMENT_(0, Tuple)) Field(Tuple& t) { return t.f0_; } // NOLINT template static GTEST_BY_REF_(GTEST_TUPLE_ELEMENT_(0, Tuple)) ConstField(const Tuple& t) { return t.f0_; } }; template <> class Get<1> { public: template static GTEST_ADD_REF_(GTEST_TUPLE_ELEMENT_(1, Tuple)) Field(Tuple& t) { return t.f1_; } // NOLINT template static GTEST_BY_REF_(GTEST_TUPLE_ELEMENT_(1, Tuple)) ConstField(const Tuple& t) { return t.f1_; } }; template <> class Get<2> { public: template static GTEST_ADD_REF_(GTEST_TUPLE_ELEMENT_(2, Tuple)) Field(Tuple& t) { return t.f2_; } // NOLINT template static GTEST_BY_REF_(GTEST_TUPLE_ELEMENT_(2, Tuple)) ConstField(const Tuple& t) { return t.f2_; } }; template <> class Get<3> { public: template static GTEST_ADD_REF_(GTEST_TUPLE_ELEMENT_(3, Tuple)) Field(Tuple& t) { return t.f3_; } // NOLINT template static GTEST_BY_REF_(GTEST_TUPLE_ELEMENT_(3, Tuple)) ConstField(const Tuple& t) { return t.f3_; } }; template <> class Get<4> { public: template static GTEST_ADD_REF_(GTEST_TUPLE_ELEMENT_(4, Tuple)) Field(Tuple& t) { return t.f4_; } // NOLINT template static GTEST_BY_REF_(GTEST_TUPLE_ELEMENT_(4, Tuple)) ConstField(const Tuple& t) { return t.f4_; } }; template <> class Get<5> { public: template static GTEST_ADD_REF_(GTEST_TUPLE_ELEMENT_(5, Tuple)) Field(Tuple& t) { return t.f5_; } // NOLINT template static GTEST_BY_REF_(GTEST_TUPLE_ELEMENT_(5, Tuple)) ConstField(const Tuple& t) { return t.f5_; } }; template <> class Get<6> { public: template static GTEST_ADD_REF_(GTEST_TUPLE_ELEMENT_(6, Tuple)) Field(Tuple& t) { return t.f6_; } // NOLINT template static GTEST_BY_REF_(GTEST_TUPLE_ELEMENT_(6, Tuple)) ConstField(const Tuple& t) { return t.f6_; } }; template <> class Get<7> { public: template static GTEST_ADD_REF_(GTEST_TUPLE_ELEMENT_(7, Tuple)) Field(Tuple& t) { return t.f7_; } // NOLINT template static GTEST_BY_REF_(GTEST_TUPLE_ELEMENT_(7, Tuple)) ConstField(const Tuple& t) { return t.f7_; } }; template <> class Get<8> { public: template static GTEST_ADD_REF_(GTEST_TUPLE_ELEMENT_(8, Tuple)) Field(Tuple& t) { return t.f8_; } // NOLINT template static GTEST_BY_REF_(GTEST_TUPLE_ELEMENT_(8, Tuple)) ConstField(const Tuple& t) { return t.f8_; } }; template <> class Get<9> { public: template static GTEST_ADD_REF_(GTEST_TUPLE_ELEMENT_(9, Tuple)) Field(Tuple& t) { return t.f9_; } // NOLINT template static GTEST_BY_REF_(GTEST_TUPLE_ELEMENT_(9, Tuple)) ConstField(const Tuple& t) { return t.f9_; } }; } // namespace gtest_internal template GTEST_ADD_REF_(GTEST_TUPLE_ELEMENT_(k, GTEST_10_TUPLE_(T))) get(GTEST_10_TUPLE_(T)& t) { return gtest_internal::Get::Field(t); } template GTEST_BY_REF_(GTEST_TUPLE_ELEMENT_(k, GTEST_10_TUPLE_(T))) get(const GTEST_10_TUPLE_(T)& t) { return gtest_internal::Get::ConstField(t); } // 6.1.3.5 Relational operators // We only implement == and !=, as we don't have a need for the rest yet. namespace gtest_internal { // SameSizeTuplePrefixComparator::Eq(t1, t2) returns true if the // first k fields of t1 equals the first k fields of t2. // SameSizeTuplePrefixComparator(k1, k2) would be a compiler error if // k1 != k2. template struct SameSizeTuplePrefixComparator; template <> struct SameSizeTuplePrefixComparator<0, 0> { template static bool Eq(const Tuple1& /* t1 */, const Tuple2& /* t2 */) { return true; } }; template struct SameSizeTuplePrefixComparator { template static bool Eq(const Tuple1& t1, const Tuple2& t2) { return SameSizeTuplePrefixComparator::Eq(t1, t2) && ::std::tr1::get(t1) == ::std::tr1::get(t2); } }; } // namespace gtest_internal template inline bool operator==(const GTEST_10_TUPLE_(T)& t, const GTEST_10_TUPLE_(U)& u) { return gtest_internal::SameSizeTuplePrefixComparator< tuple_size::value, tuple_size::value>::Eq(t, u); } template inline bool operator!=(const GTEST_10_TUPLE_(T)& t, const GTEST_10_TUPLE_(U)& u) { return !(t == u); } // 6.1.4 Pairs. // Unimplemented. } // namespace tr1 } // namespace std #undef GTEST_0_TUPLE_ #undef GTEST_1_TUPLE_ #undef GTEST_2_TUPLE_ #undef GTEST_3_TUPLE_ #undef GTEST_4_TUPLE_ #undef GTEST_5_TUPLE_ #undef GTEST_6_TUPLE_ #undef GTEST_7_TUPLE_ #undef GTEST_8_TUPLE_ #undef GTEST_9_TUPLE_ #undef GTEST_10_TUPLE_ #undef GTEST_0_TYPENAMES_ #undef GTEST_1_TYPENAMES_ #undef GTEST_2_TYPENAMES_ #undef GTEST_3_TYPENAMES_ #undef GTEST_4_TYPENAMES_ #undef GTEST_5_TYPENAMES_ #undef GTEST_6_TYPENAMES_ #undef GTEST_7_TYPENAMES_ #undef GTEST_8_TYPENAMES_ #undef GTEST_9_TYPENAMES_ #undef GTEST_10_TYPENAMES_ #undef GTEST_DECLARE_TUPLE_AS_FRIEND_ #undef GTEST_BY_REF_ #undef GTEST_ADD_REF_ #undef GTEST_TUPLE_ELEMENT_ #endif // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_TUPLE_H_ ugene-1.9.8/src/libs_3rdparty/gtest/src/gtest/gtest.h0000644000175000017500000024102211651544307021233 0ustar ilyailya// Copyright 2005, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Author: wan@google.com (Zhanyong Wan) // // The Google C++ Testing Framework (Google Test) // // This header file defines the public API for Google Test. It should be // included by any test program that uses Google Test. // // IMPORTANT NOTE: Due to limitation of the C++ language, we have to // leave some internal implementation details in this header file. // They are clearly marked by comments like this: // // // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. // // Such code is NOT meant to be used by a user directly, and is subject // to CHANGE WITHOUT NOTICE. Therefore DO NOT DEPEND ON IT in a user // program! // // Acknowledgment: Google Test borrowed the idea of automatic test // registration from Barthelemy Dagenais' (barthelemy@prologique.com) // easyUnit framework. #ifndef GTEST_INCLUDE_GTEST_GTEST_H_ #define GTEST_INCLUDE_GTEST_GTEST_H_ #include #include #include "gtest/internal/gtest-internal.h" #include "gtest/internal/gtest-string.h" #include "gtest/gtest-death-test.h" #include "gtest/gtest-message.h" #include "gtest/gtest-param-test.h" #include "gtest/gtest-printers.h" #include "gtest/gtest_prod.h" #include "gtest/gtest-test-part.h" #include "gtest/gtest-typed-test.h" // Depending on the platform, different string classes are available. // On Linux, in addition to ::std::string, Google also makes use of // class ::string, which has the same interface as ::std::string, but // has a different implementation. // // The user can define GTEST_HAS_GLOBAL_STRING to 1 to indicate that // ::string is available AND is a distinct type to ::std::string, or // define it to 0 to indicate otherwise. // // If the user's ::std::string and ::string are the same class due to // aliasing, he should define GTEST_HAS_GLOBAL_STRING to 0. // // If the user doesn't define GTEST_HAS_GLOBAL_STRING, it is defined // heuristically. namespace testing { // Declares the flags. // This flag temporary enables the disabled tests. GTEST_DECLARE_bool_(also_run_disabled_tests); // This flag brings the debugger on an assertion failure. GTEST_DECLARE_bool_(break_on_failure); // This flag controls whether Google Test catches all test-thrown exceptions // and logs them as failures. GTEST_DECLARE_bool_(catch_exceptions); // This flag enables using colors in terminal output. Available values are // "yes" to enable colors, "no" (disable colors), or "auto" (the default) // to let Google Test decide. GTEST_DECLARE_string_(color); // This flag sets up the filter to select by name using a glob pattern // the tests to run. If the filter is not given all tests are executed. GTEST_DECLARE_string_(filter); // This flag causes the Google Test to list tests. None of the tests listed // are actually run if the flag is provided. GTEST_DECLARE_bool_(list_tests); // This flag controls whether Google Test emits a detailed XML report to a file // in addition to its normal textual output. GTEST_DECLARE_string_(output); // This flags control whether Google Test prints the elapsed time for each // test. GTEST_DECLARE_bool_(print_time); // This flag specifies the random number seed. GTEST_DECLARE_int32_(random_seed); // This flag sets how many times the tests are repeated. The default value // is 1. If the value is -1 the tests are repeating forever. GTEST_DECLARE_int32_(repeat); // This flag controls whether Google Test includes Google Test internal // stack frames in failure stack traces. GTEST_DECLARE_bool_(show_internal_stack_frames); // When this flag is specified, tests' order is randomized on every iteration. GTEST_DECLARE_bool_(shuffle); // This flag specifies the maximum number of stack frames to be // printed in a failure message. GTEST_DECLARE_int32_(stack_trace_depth); // When this flag is specified, a failed assertion will throw an // exception if exceptions are enabled, or exit the program with a // non-zero code otherwise. GTEST_DECLARE_bool_(throw_on_failure); // When this flag is set with a "host:port" string, on supported // platforms test results are streamed to the specified port on // the specified host machine. GTEST_DECLARE_string_(stream_result_to); // The upper limit for valid stack trace depths. const int kMaxStackTraceDepth = 100; namespace internal { class AssertHelper; class DefaultGlobalTestPartResultReporter; class ExecDeathTest; class NoExecDeathTest; class FinalSuccessChecker; class GTestFlagSaver; class TestResultAccessor; class TestEventListenersAccessor; class TestEventRepeater; class WindowsDeathTest; class UnitTestImpl* GetUnitTestImpl(); void ReportFailureInUnknownLocation(TestPartResult::Type result_type, const String& message); // Converts a streamable value to a String. A NULL pointer is // converted to "(null)". When the input value is a ::string, // ::std::string, ::wstring, or ::std::wstring object, each NUL // character in it is replaced with "\\0". // Declared in gtest-internal.h but defined here, so that it has access // to the definition of the Message class, required by the ARM // compiler. template String StreamableToString(const T& streamable) { return (Message() << streamable).GetString(); } } // namespace internal // The friend relationship of some of these classes is cyclic. // If we don't forward declare them the compiler might confuse the classes // in friendship clauses with same named classes on the scope. class Test; class TestCase; class TestInfo; class UnitTest; // A class for indicating whether an assertion was successful. When // the assertion wasn't successful, the AssertionResult object // remembers a non-empty message that describes how it failed. // // To create an instance of this class, use one of the factory functions // (AssertionSuccess() and AssertionFailure()). // // This class is useful for two purposes: // 1. Defining predicate functions to be used with Boolean test assertions // EXPECT_TRUE/EXPECT_FALSE and their ASSERT_ counterparts // 2. Defining predicate-format functions to be // used with predicate assertions (ASSERT_PRED_FORMAT*, etc). // // For example, if you define IsEven predicate: // // testing::AssertionResult IsEven(int n) { // if ((n % 2) == 0) // return testing::AssertionSuccess(); // else // return testing::AssertionFailure() << n << " is odd"; // } // // Then the failed expectation EXPECT_TRUE(IsEven(Fib(5))) // will print the message // // Value of: IsEven(Fib(5)) // Actual: false (5 is odd) // Expected: true // // instead of a more opaque // // Value of: IsEven(Fib(5)) // Actual: false // Expected: true // // in case IsEven is a simple Boolean predicate. // // If you expect your predicate to be reused and want to support informative // messages in EXPECT_FALSE and ASSERT_FALSE (negative assertions show up // about half as often as positive ones in our tests), supply messages for // both success and failure cases: // // testing::AssertionResult IsEven(int n) { // if ((n % 2) == 0) // return testing::AssertionSuccess() << n << " is even"; // else // return testing::AssertionFailure() << n << " is odd"; // } // // Then a statement EXPECT_FALSE(IsEven(Fib(6))) will print // // Value of: IsEven(Fib(6)) // Actual: true (8 is even) // Expected: false // // NB: Predicates that support negative Boolean assertions have reduced // performance in positive ones so be careful not to use them in tests // that have lots (tens of thousands) of positive Boolean assertions. // // To use this class with EXPECT_PRED_FORMAT assertions such as: // // // Verifies that Foo() returns an even number. // EXPECT_PRED_FORMAT1(IsEven, Foo()); // // you need to define: // // testing::AssertionResult IsEven(const char* expr, int n) { // if ((n % 2) == 0) // return testing::AssertionSuccess(); // else // return testing::AssertionFailure() // << "Expected: " << expr << " is even\n Actual: it's " << n; // } // // If Foo() returns 5, you will see the following message: // // Expected: Foo() is even // Actual: it's 5 // class GTEST_API_ AssertionResult { public: // Copy constructor. // Used in EXPECT_TRUE/FALSE(assertion_result). AssertionResult(const AssertionResult& other); // Used in the EXPECT_TRUE/FALSE(bool_expression). explicit AssertionResult(bool success) : success_(success) {} // Returns true iff the assertion succeeded. operator bool() const { return success_; } // NOLINT // Returns the assertion's negation. Used with EXPECT/ASSERT_FALSE. AssertionResult operator!() const; // Returns the text streamed into this AssertionResult. Test assertions // use it when they fail (i.e., the predicate's outcome doesn't match the // assertion's expectation). When nothing has been streamed into the // object, returns an empty string. const char* message() const { return message_.get() != NULL ? message_->c_str() : ""; } // TODO(vladl@google.com): Remove this after making sure no clients use it. // Deprecated; please use message() instead. const char* failure_message() const { return message(); } // Streams a custom failure message into this object. template AssertionResult& operator<<(const T& value) { AppendMessage(Message() << value); return *this; } // Allows streaming basic output manipulators such as endl or flush into // this object. AssertionResult& operator<<( ::std::ostream& (*basic_manipulator)(::std::ostream& stream)) { AppendMessage(Message() << basic_manipulator); return *this; } private: // Appends the contents of message to message_. void AppendMessage(const Message& a_message) { if (message_.get() == NULL) message_.reset(new ::std::string); message_->append(a_message.GetString().c_str()); } // Stores result of the assertion predicate. bool success_; // Stores the message describing the condition in case the expectation // construct is not satisfied with the predicate's outcome. // Referenced via a pointer to avoid taking too much stack frame space // with test assertions. internal::scoped_ptr< ::std::string> message_; GTEST_DISALLOW_ASSIGN_(AssertionResult); }; // Makes a successful assertion result. GTEST_API_ AssertionResult AssertionSuccess(); // Makes a failed assertion result. GTEST_API_ AssertionResult AssertionFailure(); // Makes a failed assertion result with the given failure message. // Deprecated; use AssertionFailure() << msg. GTEST_API_ AssertionResult AssertionFailure(const Message& msg); // The abstract class that all tests inherit from. // // In Google Test, a unit test program contains one or many TestCases, and // each TestCase contains one or many Tests. // // When you define a test using the TEST macro, you don't need to // explicitly derive from Test - the TEST macro automatically does // this for you. // // The only time you derive from Test is when defining a test fixture // to be used a TEST_F. For example: // // class FooTest : public testing::Test { // protected: // virtual void SetUp() { ... } // virtual void TearDown() { ... } // ... // }; // // TEST_F(FooTest, Bar) { ... } // TEST_F(FooTest, Baz) { ... } // // Test is not copyable. class GTEST_API_ Test { public: friend class TestInfo; // Defines types for pointers to functions that set up and tear down // a test case. typedef internal::SetUpTestCaseFunc SetUpTestCaseFunc; typedef internal::TearDownTestCaseFunc TearDownTestCaseFunc; // The d'tor is virtual as we intend to inherit from Test. virtual ~Test(); // Sets up the stuff shared by all tests in this test case. // // Google Test will call Foo::SetUpTestCase() before running the first // test in test case Foo. Hence a sub-class can define its own // SetUpTestCase() method to shadow the one defined in the super // class. static void SetUpTestCase() {} // Tears down the stuff shared by all tests in this test case. // // Google Test will call Foo::TearDownTestCase() after running the last // test in test case Foo. Hence a sub-class can define its own // TearDownTestCase() method to shadow the one defined in the super // class. static void TearDownTestCase() {} // Returns true iff the current test has a fatal failure. static bool HasFatalFailure(); // Returns true iff the current test has a non-fatal failure. static bool HasNonfatalFailure(); // Returns true iff the current test has a (either fatal or // non-fatal) failure. static bool HasFailure() { return HasFatalFailure() || HasNonfatalFailure(); } // Logs a property for the current test. Only the last value for a given // key is remembered. // These are public static so they can be called from utility functions // that are not members of the test fixture. // The arguments are const char* instead strings, as Google Test is used // on platforms where string doesn't compile. // // Note that a driving consideration for these RecordProperty methods // was to produce xml output suited to the Greenspan charting utility, // which at present will only chart values that fit in a 32-bit int. It // is the user's responsibility to restrict their values to 32-bit ints // if they intend them to be used with Greenspan. static void RecordProperty(const char* key, const char* value); static void RecordProperty(const char* key, int value); protected: // Creates a Test object. Test(); // Sets up the test fixture. virtual void SetUp(); // Tears down the test fixture. virtual void TearDown(); private: // Returns true iff the current test has the same fixture class as // the first test in the current test case. static bool HasSameFixtureClass(); // Runs the test after the test fixture has been set up. // // A sub-class must implement this to define the test logic. // // DO NOT OVERRIDE THIS FUNCTION DIRECTLY IN A USER PROGRAM. // Instead, use the TEST or TEST_F macro. virtual void TestBody() = 0; // Sets up, executes, and tears down the test. void Run(); // Deletes self. We deliberately pick an unusual name for this // internal method to avoid clashing with names used in user TESTs. void DeleteSelf_() { delete this; } // Uses a GTestFlagSaver to save and restore all Google Test flags. const internal::GTestFlagSaver* const gtest_flag_saver_; // Often a user mis-spells SetUp() as Setup() and spends a long time // wondering why it is never called by Google Test. The declaration of // the following method is solely for catching such an error at // compile time: // // - The return type is deliberately chosen to be not void, so it // will be a conflict if a user declares void Setup() in his test // fixture. // // - This method is private, so it will be another compiler error // if a user calls it from his test fixture. // // DO NOT OVERRIDE THIS FUNCTION. // // If you see an error about overriding the following function or // about it being private, you have mis-spelled SetUp() as Setup(). struct Setup_should_be_spelled_SetUp {}; virtual Setup_should_be_spelled_SetUp* Setup() { return NULL; } // We disallow copying Tests. GTEST_DISALLOW_COPY_AND_ASSIGN_(Test); }; typedef internal::TimeInMillis TimeInMillis; // A copyable object representing a user specified test property which can be // output as a key/value string pair. // // Don't inherit from TestProperty as its destructor is not virtual. class TestProperty { public: // C'tor. TestProperty does NOT have a default constructor. // Always use this constructor (with parameters) to create a // TestProperty object. TestProperty(const char* a_key, const char* a_value) : key_(a_key), value_(a_value) { } // Gets the user supplied key. const char* key() const { return key_.c_str(); } // Gets the user supplied value. const char* value() const { return value_.c_str(); } // Sets a new value, overriding the one supplied in the constructor. void SetValue(const char* new_value) { value_ = new_value; } private: // The key supplied by the user. internal::String key_; // The value supplied by the user. internal::String value_; }; // The result of a single Test. This includes a list of // TestPartResults, a list of TestProperties, a count of how many // death tests there are in the Test, and how much time it took to run // the Test. // // TestResult is not copyable. class GTEST_API_ TestResult { public: // Creates an empty TestResult. TestResult(); // D'tor. Do not inherit from TestResult. ~TestResult(); // Gets the number of all test parts. This is the sum of the number // of successful test parts and the number of failed test parts. int total_part_count() const; // Returns the number of the test properties. int test_property_count() const; // Returns true iff the test passed (i.e. no test part failed). bool Passed() const { return !Failed(); } // Returns true iff the test failed. bool Failed() const; // Returns true iff the test fatally failed. bool HasFatalFailure() const; // Returns true iff the test has a non-fatal failure. bool HasNonfatalFailure() const; // Returns the elapsed time, in milliseconds. TimeInMillis elapsed_time() const { return elapsed_time_; } // Returns the i-th test part result among all the results. i can range // from 0 to test_property_count() - 1. If i is not in that range, aborts // the program. const TestPartResult& GetTestPartResult(int i) const; // Returns the i-th test property. i can range from 0 to // test_property_count() - 1. If i is not in that range, aborts the // program. const TestProperty& GetTestProperty(int i) const; private: friend class TestInfo; friend class UnitTest; friend class internal::DefaultGlobalTestPartResultReporter; friend class internal::ExecDeathTest; friend class internal::TestResultAccessor; friend class internal::UnitTestImpl; friend class internal::WindowsDeathTest; // Gets the vector of TestPartResults. const std::vector& test_part_results() const { return test_part_results_; } // Gets the vector of TestProperties. const std::vector& test_properties() const { return test_properties_; } // Sets the elapsed time. void set_elapsed_time(TimeInMillis elapsed) { elapsed_time_ = elapsed; } // Adds a test property to the list. The property is validated and may add // a non-fatal failure if invalid (e.g., if it conflicts with reserved // key names). If a property is already recorded for the same key, the // value will be updated, rather than storing multiple values for the same // key. void RecordProperty(const TestProperty& test_property); // Adds a failure if the key is a reserved attribute of Google Test // testcase tags. Returns true if the property is valid. // TODO(russr): Validate attribute names are legal and human readable. static bool ValidateTestProperty(const TestProperty& test_property); // Adds a test part result to the list. void AddTestPartResult(const TestPartResult& test_part_result); // Returns the death test count. int death_test_count() const { return death_test_count_; } // Increments the death test count, returning the new count. int increment_death_test_count() { return ++death_test_count_; } // Clears the test part results. void ClearTestPartResults(); // Clears the object. void Clear(); // Protects mutable state of the property vector and of owned // properties, whose values may be updated. internal::Mutex test_properites_mutex_; // The vector of TestPartResults std::vector test_part_results_; // The vector of TestProperties std::vector test_properties_; // Running count of death tests. int death_test_count_; // The elapsed time, in milliseconds. TimeInMillis elapsed_time_; // We disallow copying TestResult. GTEST_DISALLOW_COPY_AND_ASSIGN_(TestResult); }; // class TestResult // A TestInfo object stores the following information about a test: // // Test case name // Test name // Whether the test should be run // A function pointer that creates the test object when invoked // Test result // // The constructor of TestInfo registers itself with the UnitTest // singleton such that the RUN_ALL_TESTS() macro knows which tests to // run. class GTEST_API_ TestInfo { public: // Destructs a TestInfo object. This function is not virtual, so // don't inherit from TestInfo. ~TestInfo(); // Returns the test case name. const char* test_case_name() const { return test_case_name_.c_str(); } // Returns the test name. const char* name() const { return name_.c_str(); } // Returns the name of the parameter type, or NULL if this is not a typed // or a type-parameterized test. const char* type_param() const { if (type_param_.get() != NULL) return type_param_->c_str(); return NULL; } // Returns the text representation of the value parameter, or NULL if this // is not a value-parameterized test. const char* value_param() const { if (value_param_.get() != NULL) return value_param_->c_str(); return NULL; } // Returns true if this test should run, that is if the test is not disabled // (or it is disabled but the also_run_disabled_tests flag has been specified) // and its full name matches the user-specified filter. // // Google Test allows the user to filter the tests by their full names. // The full name of a test Bar in test case Foo is defined as // "Foo.Bar". Only the tests that match the filter will run. // // A filter is a colon-separated list of glob (not regex) patterns, // optionally followed by a '-' and a colon-separated list of // negative patterns (tests to exclude). A test is run if it // matches one of the positive patterns and does not match any of // the negative patterns. // // For example, *A*:Foo.* is a filter that matches any string that // contains the character 'A' or starts with "Foo.". bool should_run() const { return should_run_; } // Returns the result of the test. const TestResult* result() const { return &result_; } private: #if GTEST_HAS_DEATH_TEST friend class internal::DefaultDeathTestFactory; #endif // GTEST_HAS_DEATH_TEST friend class Test; friend class TestCase; friend class internal::UnitTestImpl; friend TestInfo* internal::MakeAndRegisterTestInfo( const char* test_case_name, const char* name, const char* type_param, const char* value_param, internal::TypeId fixture_class_id, Test::SetUpTestCaseFunc set_up_tc, Test::TearDownTestCaseFunc tear_down_tc, internal::TestFactoryBase* factory); // Constructs a TestInfo object. The newly constructed instance assumes // ownership of the factory object. TestInfo(const char* test_case_name, const char* name, const char* a_type_param, const char* a_value_param, internal::TypeId fixture_class_id, internal::TestFactoryBase* factory); // Increments the number of death tests encountered in this test so // far. int increment_death_test_count() { return result_.increment_death_test_count(); } // Creates the test object, runs it, records its result, and then // deletes it. void Run(); static void ClearTestResult(TestInfo* test_info) { test_info->result_.Clear(); } // These fields are immutable properties of the test. const std::string test_case_name_; // Test case name const std::string name_; // Test name // Name of the parameter type, or NULL if this is not a typed or a // type-parameterized test. const internal::scoped_ptr type_param_; // Text representation of the value parameter, or NULL if this is not a // value-parameterized test. const internal::scoped_ptr value_param_; const internal::TypeId fixture_class_id_; // ID of the test fixture class bool should_run_; // True iff this test should run bool is_disabled_; // True iff this test is disabled bool matches_filter_; // True if this test matches the // user-specified filter. internal::TestFactoryBase* const factory_; // The factory that creates // the test object // This field is mutable and needs to be reset before running the // test for the second time. TestResult result_; GTEST_DISALLOW_COPY_AND_ASSIGN_(TestInfo); }; // A test case, which consists of a vector of TestInfos. // // TestCase is not copyable. class GTEST_API_ TestCase { public: // Creates a TestCase with the given name. // // TestCase does NOT have a default constructor. Always use this // constructor to create a TestCase object. // // Arguments: // // name: name of the test case // a_type_param: the name of the test's type parameter, or NULL if // this is not a type-parameterized test. // set_up_tc: pointer to the function that sets up the test case // tear_down_tc: pointer to the function that tears down the test case TestCase(const char* name, const char* a_type_param, Test::SetUpTestCaseFunc set_up_tc, Test::TearDownTestCaseFunc tear_down_tc); // Destructor of TestCase. virtual ~TestCase(); // Gets the name of the TestCase. const char* name() const { return name_.c_str(); } // Returns the name of the parameter type, or NULL if this is not a // type-parameterized test case. const char* type_param() const { if (type_param_.get() != NULL) return type_param_->c_str(); return NULL; } // Returns true if any test in this test case should run. bool should_run() const { return should_run_; } // Gets the number of successful tests in this test case. int successful_test_count() const; // Gets the number of failed tests in this test case. int failed_test_count() const; // Gets the number of disabled tests in this test case. int disabled_test_count() const; // Get the number of tests in this test case that should run. int test_to_run_count() const; // Gets the number of all tests in this test case. int total_test_count() const; // Returns true iff the test case passed. bool Passed() const { return !Failed(); } // Returns true iff the test case failed. bool Failed() const { return failed_test_count() > 0; } // Returns the elapsed time, in milliseconds. TimeInMillis elapsed_time() const { return elapsed_time_; } // Returns the i-th test among all the tests. i can range from 0 to // total_test_count() - 1. If i is not in that range, returns NULL. const TestInfo* GetTestInfo(int i) const; private: friend class Test; friend class internal::UnitTestImpl; // Gets the (mutable) vector of TestInfos in this TestCase. std::vector& test_info_list() { return test_info_list_; } // Gets the (immutable) vector of TestInfos in this TestCase. const std::vector& test_info_list() const { return test_info_list_; } // Returns the i-th test among all the tests. i can range from 0 to // total_test_count() - 1. If i is not in that range, returns NULL. TestInfo* GetMutableTestInfo(int i); // Sets the should_run member. void set_should_run(bool should) { should_run_ = should; } // Adds a TestInfo to this test case. Will delete the TestInfo upon // destruction of the TestCase object. void AddTestInfo(TestInfo * test_info); // Clears the results of all tests in this test case. void ClearResult(); // Clears the results of all tests in the given test case. static void ClearTestCaseResult(TestCase* test_case) { test_case->ClearResult(); } // Runs every test in this TestCase. void Run(); // Runs SetUpTestCase() for this TestCase. This wrapper is needed // for catching exceptions thrown from SetUpTestCase(). void RunSetUpTestCase() { (*set_up_tc_)(); } // Runs TearDownTestCase() for this TestCase. This wrapper is // needed for catching exceptions thrown from TearDownTestCase(). void RunTearDownTestCase() { (*tear_down_tc_)(); } // Returns true iff test passed. static bool TestPassed(const TestInfo* test_info) { return test_info->should_run() && test_info->result()->Passed(); } // Returns true iff test failed. static bool TestFailed(const TestInfo* test_info) { return test_info->should_run() && test_info->result()->Failed(); } // Returns true iff test is disabled. static bool TestDisabled(const TestInfo* test_info) { return test_info->is_disabled_; } // Returns true if the given test should run. static bool ShouldRunTest(const TestInfo* test_info) { return test_info->should_run(); } // Shuffles the tests in this test case. void ShuffleTests(internal::Random* random); // Restores the test order to before the first shuffle. void UnshuffleTests(); // Name of the test case. internal::String name_; // Name of the parameter type, or NULL if this is not a typed or a // type-parameterized test. const internal::scoped_ptr type_param_; // The vector of TestInfos in their original order. It owns the // elements in the vector. std::vector test_info_list_; // Provides a level of indirection for the test list to allow easy // shuffling and restoring the test order. The i-th element in this // vector is the index of the i-th test in the shuffled test list. std::vector test_indices_; // Pointer to the function that sets up the test case. Test::SetUpTestCaseFunc set_up_tc_; // Pointer to the function that tears down the test case. Test::TearDownTestCaseFunc tear_down_tc_; // True iff any test in this test case should run. bool should_run_; // Elapsed time, in milliseconds. TimeInMillis elapsed_time_; // We disallow copying TestCases. GTEST_DISALLOW_COPY_AND_ASSIGN_(TestCase); }; // An Environment object is capable of setting up and tearing down an // environment. The user should subclass this to define his own // environment(s). // // An Environment object does the set-up and tear-down in virtual // methods SetUp() and TearDown() instead of the constructor and the // destructor, as: // // 1. You cannot safely throw from a destructor. This is a problem // as in some cases Google Test is used where exceptions are enabled, and // we may want to implement ASSERT_* using exceptions where they are // available. // 2. You cannot use ASSERT_* directly in a constructor or // destructor. class Environment { public: // The d'tor is virtual as we need to subclass Environment. virtual ~Environment() {} // Override this to define how to set up the environment. virtual void SetUp() {} // Override this to define how to tear down the environment. virtual void TearDown() {} private: // If you see an error about overriding the following function or // about it being private, you have mis-spelled SetUp() as Setup(). struct Setup_should_be_spelled_SetUp {}; virtual Setup_should_be_spelled_SetUp* Setup() { return NULL; } }; // The interface for tracing execution of tests. The methods are organized in // the order the corresponding events are fired. class TestEventListener { public: virtual ~TestEventListener() {} // Fired before any test activity starts. virtual void OnTestProgramStart(const UnitTest& unit_test) = 0; // Fired before each iteration of tests starts. There may be more than // one iteration if GTEST_FLAG(repeat) is set. iteration is the iteration // index, starting from 0. virtual void OnTestIterationStart(const UnitTest& unit_test, int iteration) = 0; // Fired before environment set-up for each iteration of tests starts. virtual void OnEnvironmentsSetUpStart(const UnitTest& unit_test) = 0; // Fired after environment set-up for each iteration of tests ends. virtual void OnEnvironmentsSetUpEnd(const UnitTest& unit_test) = 0; // Fired before the test case starts. virtual void OnTestCaseStart(const TestCase& test_case) = 0; // Fired before the test starts. virtual void OnTestStart(const TestInfo& test_info) = 0; // Fired after a failed assertion or a SUCCEED() invocation. virtual void OnTestPartResult(const TestPartResult& test_part_result) = 0; // Fired after the test ends. virtual void OnTestEnd(const TestInfo& test_info) = 0; // Fired after the test case ends. virtual void OnTestCaseEnd(const TestCase& test_case) = 0; // Fired before environment tear-down for each iteration of tests starts. virtual void OnEnvironmentsTearDownStart(const UnitTest& unit_test) = 0; // Fired after environment tear-down for each iteration of tests ends. virtual void OnEnvironmentsTearDownEnd(const UnitTest& unit_test) = 0; // Fired after each iteration of tests finishes. virtual void OnTestIterationEnd(const UnitTest& unit_test, int iteration) = 0; // Fired after all test activities have ended. virtual void OnTestProgramEnd(const UnitTest& unit_test) = 0; }; // The convenience class for users who need to override just one or two // methods and are not concerned that a possible change to a signature of // the methods they override will not be caught during the build. For // comments about each method please see the definition of TestEventListener // above. class EmptyTestEventListener : public TestEventListener { public: virtual void OnTestProgramStart(const UnitTest& /*unit_test*/) {} virtual void OnTestIterationStart(const UnitTest& /*unit_test*/, int /*iteration*/) {} virtual void OnEnvironmentsSetUpStart(const UnitTest& /*unit_test*/) {} virtual void OnEnvironmentsSetUpEnd(const UnitTest& /*unit_test*/) {} virtual void OnTestCaseStart(const TestCase& /*test_case*/) {} virtual void OnTestStart(const TestInfo& /*test_info*/) {} virtual void OnTestPartResult(const TestPartResult& /*test_part_result*/) {} virtual void OnTestEnd(const TestInfo& /*test_info*/) {} virtual void OnTestCaseEnd(const TestCase& /*test_case*/) {} virtual void OnEnvironmentsTearDownStart(const UnitTest& /*unit_test*/) {} virtual void OnEnvironmentsTearDownEnd(const UnitTest& /*unit_test*/) {} virtual void OnTestIterationEnd(const UnitTest& /*unit_test*/, int /*iteration*/) {} virtual void OnTestProgramEnd(const UnitTest& /*unit_test*/) {} }; // TestEventListeners lets users add listeners to track events in Google Test. class GTEST_API_ TestEventListeners { public: TestEventListeners(); ~TestEventListeners(); // Appends an event listener to the end of the list. Google Test assumes // the ownership of the listener (i.e. it will delete the listener when // the test program finishes). void Append(TestEventListener* listener); // Removes the given event listener from the list and returns it. It then // becomes the caller's responsibility to delete the listener. Returns // NULL if the listener is not found in the list. TestEventListener* Release(TestEventListener* listener); // Returns the standard listener responsible for the default console // output. Can be removed from the listeners list to shut down default // console output. Note that removing this object from the listener list // with Release transfers its ownership to the caller and makes this // function return NULL the next time. TestEventListener* default_result_printer() const { return default_result_printer_; } // Returns the standard listener responsible for the default XML output // controlled by the --gtest_output=xml flag. Can be removed from the // listeners list by users who want to shut down the default XML output // controlled by this flag and substitute it with custom one. Note that // removing this object from the listener list with Release transfers its // ownership to the caller and makes this function return NULL the next // time. TestEventListener* default_xml_generator() const { return default_xml_generator_; } private: friend class TestCase; friend class TestInfo; friend class internal::DefaultGlobalTestPartResultReporter; friend class internal::NoExecDeathTest; friend class internal::TestEventListenersAccessor; friend class internal::UnitTestImpl; // Returns repeater that broadcasts the TestEventListener events to all // subscribers. TestEventListener* repeater(); // Sets the default_result_printer attribute to the provided listener. // The listener is also added to the listener list and previous // default_result_printer is removed from it and deleted. The listener can // also be NULL in which case it will not be added to the list. Does // nothing if the previous and the current listener objects are the same. void SetDefaultResultPrinter(TestEventListener* listener); // Sets the default_xml_generator attribute to the provided listener. The // listener is also added to the listener list and previous // default_xml_generator is removed from it and deleted. The listener can // also be NULL in which case it will not be added to the list. Does // nothing if the previous and the current listener objects are the same. void SetDefaultXmlGenerator(TestEventListener* listener); // Controls whether events will be forwarded by the repeater to the // listeners in the list. bool EventForwardingEnabled() const; void SuppressEventForwarding(); // The actual list of listeners. internal::TestEventRepeater* repeater_; // Listener responsible for the standard result output. TestEventListener* default_result_printer_; // Listener responsible for the creation of the XML output file. TestEventListener* default_xml_generator_; // We disallow copying TestEventListeners. GTEST_DISALLOW_COPY_AND_ASSIGN_(TestEventListeners); }; // A UnitTest consists of a vector of TestCases. // // This is a singleton class. The only instance of UnitTest is // created when UnitTest::GetInstance() is first called. This // instance is never deleted. // // UnitTest is not copyable. // // This class is thread-safe as long as the methods are called // according to their specification. class GTEST_API_ UnitTest { public: // Gets the singleton UnitTest object. The first time this method // is called, a UnitTest object is constructed and returned. // Consecutive calls will return the same object. static UnitTest* GetInstance(); // Runs all tests in this UnitTest object and prints the result. // Returns 0 if successful, or 1 otherwise. // // This method can only be called from the main thread. // // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. int Run() GTEST_MUST_USE_RESULT_; // Returns the working directory when the first TEST() or TEST_F() // was executed. The UnitTest object owns the string. const char* original_working_dir() const; // Returns the TestCase object for the test that's currently running, // or NULL if no test is running. const TestCase* current_test_case() const; // Returns the TestInfo object for the test that's currently running, // or NULL if no test is running. const TestInfo* current_test_info() const; // Returns the random seed used at the start of the current test run. int random_seed() const; #if GTEST_HAS_PARAM_TEST // Returns the ParameterizedTestCaseRegistry object used to keep track of // value-parameterized tests and instantiate and register them. // // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. internal::ParameterizedTestCaseRegistry& parameterized_test_registry(); #endif // GTEST_HAS_PARAM_TEST // Gets the number of successful test cases. int successful_test_case_count() const; // Gets the number of failed test cases. int failed_test_case_count() const; // Gets the number of all test cases. int total_test_case_count() const; // Gets the number of all test cases that contain at least one test // that should run. int test_case_to_run_count() const; // Gets the number of successful tests. int successful_test_count() const; // Gets the number of failed tests. int failed_test_count() const; // Gets the number of disabled tests. int disabled_test_count() const; // Gets the number of all tests. int total_test_count() const; // Gets the number of tests that should run. int test_to_run_count() const; // Gets the elapsed time, in milliseconds. TimeInMillis elapsed_time() const; // Returns true iff the unit test passed (i.e. all test cases passed). bool Passed() const; // Returns true iff the unit test failed (i.e. some test case failed // or something outside of all tests failed). bool Failed() const; // Gets the i-th test case among all the test cases. i can range from 0 to // total_test_case_count() - 1. If i is not in that range, returns NULL. const TestCase* GetTestCase(int i) const; // Returns the list of event listeners that can be used to track events // inside Google Test. TestEventListeners& listeners(); private: // Registers and returns a global test environment. When a test // program is run, all global test environments will be set-up in // the order they were registered. After all tests in the program // have finished, all global test environments will be torn-down in // the *reverse* order they were registered. // // The UnitTest object takes ownership of the given environment. // // This method can only be called from the main thread. Environment* AddEnvironment(Environment* env); // Adds a TestPartResult to the current TestResult object. All // Google Test assertion macros (e.g. ASSERT_TRUE, EXPECT_EQ, etc) // eventually call this to report their results. The user code // should use the assertion macros instead of calling this directly. void AddTestPartResult(TestPartResult::Type result_type, const char* file_name, int line_number, const internal::String& message, const internal::String& os_stack_trace); // Adds a TestProperty to the current TestResult object. If the result already // contains a property with the same key, the value will be updated. void RecordPropertyForCurrentTest(const char* key, const char* value); // Gets the i-th test case among all the test cases. i can range from 0 to // total_test_case_count() - 1. If i is not in that range, returns NULL. TestCase* GetMutableTestCase(int i); // Accessors for the implementation object. internal::UnitTestImpl* impl() { return impl_; } const internal::UnitTestImpl* impl() const { return impl_; } // These classes and funcions are friends as they need to access private // members of UnitTest. friend class Test; friend class internal::AssertHelper; friend class internal::ScopedTrace; friend Environment* AddGlobalTestEnvironment(Environment* env); friend internal::UnitTestImpl* internal::GetUnitTestImpl(); friend void internal::ReportFailureInUnknownLocation( TestPartResult::Type result_type, const internal::String& message); // Creates an empty UnitTest. UnitTest(); // D'tor virtual ~UnitTest(); // Pushes a trace defined by SCOPED_TRACE() on to the per-thread // Google Test trace stack. void PushGTestTrace(const internal::TraceInfo& trace); // Pops a trace from the per-thread Google Test trace stack. void PopGTestTrace(); // Protects mutable state in *impl_. This is mutable as some const // methods need to lock it too. mutable internal::Mutex mutex_; // Opaque implementation object. This field is never changed once // the object is constructed. We don't mark it as const here, as // doing so will cause a warning in the constructor of UnitTest. // Mutable state in *impl_ is protected by mutex_. internal::UnitTestImpl* impl_; // We disallow copying UnitTest. GTEST_DISALLOW_COPY_AND_ASSIGN_(UnitTest); }; // A convenient wrapper for adding an environment for the test // program. // // You should call this before RUN_ALL_TESTS() is called, probably in // main(). If you use gtest_main, you need to call this before main() // starts for it to take effect. For example, you can define a global // variable like this: // // testing::Environment* const foo_env = // testing::AddGlobalTestEnvironment(new FooEnvironment); // // However, we strongly recommend you to write your own main() and // call AddGlobalTestEnvironment() there, as relying on initialization // of global variables makes the code harder to read and may cause // problems when you register multiple environments from different // translation units and the environments have dependencies among them // (remember that the compiler doesn't guarantee the order in which // global variables from different translation units are initialized). inline Environment* AddGlobalTestEnvironment(Environment* env) { return UnitTest::GetInstance()->AddEnvironment(env); } // Initializes Google Test. This must be called before calling // RUN_ALL_TESTS(). In particular, it parses a command line for the // flags that Google Test recognizes. Whenever a Google Test flag is // seen, it is removed from argv, and *argc is decremented. // // No value is returned. Instead, the Google Test flag variables are // updated. // // Calling the function for the second time has no user-visible effect. GTEST_API_ void InitGoogleTest(int* argc, char** argv); // This overloaded version can be used in Windows programs compiled in // UNICODE mode. GTEST_API_ void InitGoogleTest(int* argc, wchar_t** argv); namespace internal { // Formats a comparison assertion (e.g. ASSERT_EQ, EXPECT_LT, and etc) // operand to be used in a failure message. The type (but not value) // of the other operand may affect the format. This allows us to // print a char* as a raw pointer when it is compared against another // char*, and print it as a C string when it is compared against an // std::string object, for example. // // The default implementation ignores the type of the other operand. // Some specialized versions are used to handle formatting wide or // narrow C strings. // // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. template String FormatForComparisonFailureMessage(const T1& value, const T2& /* other_operand */) { // C++Builder compiles this incorrectly if the namespace isn't explicitly // given. return ::testing::PrintToString(value); } // The helper function for {ASSERT|EXPECT}_EQ. template AssertionResult CmpHelperEQ(const char* expected_expression, const char* actual_expression, const T1& expected, const T2& actual) { #ifdef _MSC_VER # pragma warning(push) // Saves the current warning state. # pragma warning(disable:4389) // Temporarily disables warning on // signed/unsigned mismatch. #endif if (expected == actual) { return AssertionSuccess(); } #ifdef _MSC_VER # pragma warning(pop) // Restores the warning state. #endif return EqFailure(expected_expression, actual_expression, FormatForComparisonFailureMessage(expected, actual), FormatForComparisonFailureMessage(actual, expected), false); } // With this overloaded version, we allow anonymous enums to be used // in {ASSERT|EXPECT}_EQ when compiled with gcc 4, as anonymous enums // can be implicitly cast to BiggestInt. GTEST_API_ AssertionResult CmpHelperEQ(const char* expected_expression, const char* actual_expression, BiggestInt expected, BiggestInt actual); // The helper class for {ASSERT|EXPECT}_EQ. The template argument // lhs_is_null_literal is true iff the first argument to ASSERT_EQ() // is a null pointer literal. The following default implementation is // for lhs_is_null_literal being false. template class EqHelper { public: // This templatized version is for the general case. template static AssertionResult Compare(const char* expected_expression, const char* actual_expression, const T1& expected, const T2& actual) { return CmpHelperEQ(expected_expression, actual_expression, expected, actual); } // With this overloaded version, we allow anonymous enums to be used // in {ASSERT|EXPECT}_EQ when compiled with gcc 4, as anonymous // enums can be implicitly cast to BiggestInt. // // Even though its body looks the same as the above version, we // cannot merge the two, as it will make anonymous enums unhappy. static AssertionResult Compare(const char* expected_expression, const char* actual_expression, BiggestInt expected, BiggestInt actual) { return CmpHelperEQ(expected_expression, actual_expression, expected, actual); } }; // This specialization is used when the first argument to ASSERT_EQ() // is a null pointer literal, like NULL, false, or 0. template <> class EqHelper { public: // We define two overloaded versions of Compare(). The first // version will be picked when the second argument to ASSERT_EQ() is // NOT a pointer, e.g. ASSERT_EQ(0, AnIntFunction()) or // EXPECT_EQ(false, a_bool). template static AssertionResult Compare( const char* expected_expression, const char* actual_expression, const T1& expected, const T2& actual, // The following line prevents this overload from being considered if T2 // is not a pointer type. We need this because ASSERT_EQ(NULL, my_ptr) // expands to Compare("", "", NULL, my_ptr), which requires a conversion // to match the Secret* in the other overload, which would otherwise make // this template match better. typename EnableIf::value>::type* = 0) { return CmpHelperEQ(expected_expression, actual_expression, expected, actual); } // This version will be picked when the second argument to ASSERT_EQ() is a // pointer, e.g. ASSERT_EQ(NULL, a_pointer). template static AssertionResult Compare( const char* expected_expression, const char* actual_expression, // We used to have a second template parameter instead of Secret*. That // template parameter would deduce to 'long', making this a better match // than the first overload even without the first overload's EnableIf. // Unfortunately, gcc with -Wconversion-null warns when "passing NULL to // non-pointer argument" (even a deduced integral argument), so the old // implementation caused warnings in user code. Secret* /* expected (NULL) */, T* actual) { // We already know that 'expected' is a null pointer. return CmpHelperEQ(expected_expression, actual_expression, static_cast(NULL), actual); } }; // A macro for implementing the helper functions needed to implement // ASSERT_?? and EXPECT_??. It is here just to avoid copy-and-paste // of similar code. // // For each templatized helper function, we also define an overloaded // version for BiggestInt in order to reduce code bloat and allow // anonymous enums to be used with {ASSERT|EXPECT}_?? when compiled // with gcc 4. // // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. #define GTEST_IMPL_CMP_HELPER_(op_name, op)\ template \ AssertionResult CmpHelper##op_name(const char* expr1, const char* expr2, \ const T1& val1, const T2& val2) {\ if (val1 op val2) {\ return AssertionSuccess();\ } else {\ return AssertionFailure() \ << "Expected: (" << expr1 << ") " #op " (" << expr2\ << "), actual: " << FormatForComparisonFailureMessage(val1, val2)\ << " vs " << FormatForComparisonFailureMessage(val2, val1);\ }\ }\ GTEST_API_ AssertionResult CmpHelper##op_name(\ const char* expr1, const char* expr2, BiggestInt val1, BiggestInt val2) // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. // Implements the helper function for {ASSERT|EXPECT}_NE GTEST_IMPL_CMP_HELPER_(NE, !=); // Implements the helper function for {ASSERT|EXPECT}_LE GTEST_IMPL_CMP_HELPER_(LE, <=); // Implements the helper function for {ASSERT|EXPECT}_LT GTEST_IMPL_CMP_HELPER_(LT, < ); // Implements the helper function for {ASSERT|EXPECT}_GE GTEST_IMPL_CMP_HELPER_(GE, >=); // Implements the helper function for {ASSERT|EXPECT}_GT GTEST_IMPL_CMP_HELPER_(GT, > ); #undef GTEST_IMPL_CMP_HELPER_ // The helper function for {ASSERT|EXPECT}_STREQ. // // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. GTEST_API_ AssertionResult CmpHelperSTREQ(const char* expected_expression, const char* actual_expression, const char* expected, const char* actual); // The helper function for {ASSERT|EXPECT}_STRCASEEQ. // // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. GTEST_API_ AssertionResult CmpHelperSTRCASEEQ(const char* expected_expression, const char* actual_expression, const char* expected, const char* actual); // The helper function for {ASSERT|EXPECT}_STRNE. // // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. GTEST_API_ AssertionResult CmpHelperSTRNE(const char* s1_expression, const char* s2_expression, const char* s1, const char* s2); // The helper function for {ASSERT|EXPECT}_STRCASENE. // // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. GTEST_API_ AssertionResult CmpHelperSTRCASENE(const char* s1_expression, const char* s2_expression, const char* s1, const char* s2); // Helper function for *_STREQ on wide strings. // // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. GTEST_API_ AssertionResult CmpHelperSTREQ(const char* expected_expression, const char* actual_expression, const wchar_t* expected, const wchar_t* actual); // Helper function for *_STRNE on wide strings. // // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. GTEST_API_ AssertionResult CmpHelperSTRNE(const char* s1_expression, const char* s2_expression, const wchar_t* s1, const wchar_t* s2); } // namespace internal // IsSubstring() and IsNotSubstring() are intended to be used as the // first argument to {EXPECT,ASSERT}_PRED_FORMAT2(), not by // themselves. They check whether needle is a substring of haystack // (NULL is considered a substring of itself only), and return an // appropriate error message when they fail. // // The {needle,haystack}_expr arguments are the stringified // expressions that generated the two real arguments. GTEST_API_ AssertionResult IsSubstring( const char* needle_expr, const char* haystack_expr, const char* needle, const char* haystack); GTEST_API_ AssertionResult IsSubstring( const char* needle_expr, const char* haystack_expr, const wchar_t* needle, const wchar_t* haystack); GTEST_API_ AssertionResult IsNotSubstring( const char* needle_expr, const char* haystack_expr, const char* needle, const char* haystack); GTEST_API_ AssertionResult IsNotSubstring( const char* needle_expr, const char* haystack_expr, const wchar_t* needle, const wchar_t* haystack); GTEST_API_ AssertionResult IsSubstring( const char* needle_expr, const char* haystack_expr, const ::std::string& needle, const ::std::string& haystack); GTEST_API_ AssertionResult IsNotSubstring( const char* needle_expr, const char* haystack_expr, const ::std::string& needle, const ::std::string& haystack); #if GTEST_HAS_STD_WSTRING GTEST_API_ AssertionResult IsSubstring( const char* needle_expr, const char* haystack_expr, const ::std::wstring& needle, const ::std::wstring& haystack); GTEST_API_ AssertionResult IsNotSubstring( const char* needle_expr, const char* haystack_expr, const ::std::wstring& needle, const ::std::wstring& haystack); #endif // GTEST_HAS_STD_WSTRING namespace internal { // Helper template function for comparing floating-points. // // Template parameter: // // RawType: the raw floating-point type (either float or double) // // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. template AssertionResult CmpHelperFloatingPointEQ(const char* expected_expression, const char* actual_expression, RawType expected, RawType actual) { const FloatingPoint lhs(expected), rhs(actual); if (lhs.AlmostEquals(rhs)) { return AssertionSuccess(); } ::std::stringstream expected_ss; expected_ss << std::setprecision(std::numeric_limits::digits10 + 2) << expected; ::std::stringstream actual_ss; actual_ss << std::setprecision(std::numeric_limits::digits10 + 2) << actual; return EqFailure(expected_expression, actual_expression, StringStreamToString(&expected_ss), StringStreamToString(&actual_ss), false); } // Helper function for implementing ASSERT_NEAR. // // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. GTEST_API_ AssertionResult DoubleNearPredFormat(const char* expr1, const char* expr2, const char* abs_error_expr, double val1, double val2, double abs_error); // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE. // A class that enables one to stream messages to assertion macros class GTEST_API_ AssertHelper { public: // Constructor. AssertHelper(TestPartResult::Type type, const char* file, int line, const char* message); ~AssertHelper(); // Message assignment is a semantic trick to enable assertion // streaming; see the GTEST_MESSAGE_ macro below. void operator=(const Message& message) const; private: // We put our data in a struct so that the size of the AssertHelper class can // be as small as possible. This is important because gcc is incapable of // re-using stack space even for temporary variables, so every EXPECT_EQ // reserves stack space for another AssertHelper. struct AssertHelperData { AssertHelperData(TestPartResult::Type t, const char* srcfile, int line_num, const char* msg) : type(t), file(srcfile), line(line_num), message(msg) { } TestPartResult::Type const type; const char* const file; int const line; String const message; private: GTEST_DISALLOW_COPY_AND_ASSIGN_(AssertHelperData); }; AssertHelperData* const data_; GTEST_DISALLOW_COPY_AND_ASSIGN_(AssertHelper); }; } // namespace internal #if GTEST_HAS_PARAM_TEST // The pure interface class that all value-parameterized tests inherit from. // A value-parameterized class must inherit from both ::testing::Test and // ::testing::WithParamInterface. In most cases that just means inheriting // from ::testing::TestWithParam, but more complicated test hierarchies // may need to inherit from Test and WithParamInterface at different levels. // // This interface has support for accessing the test parameter value via // the GetParam() method. // // Use it with one of the parameter generator defining functions, like Range(), // Values(), ValuesIn(), Bool(), and Combine(). // // class FooTest : public ::testing::TestWithParam { // protected: // FooTest() { // // Can use GetParam() here. // } // virtual ~FooTest() { // // Can use GetParam() here. // } // virtual void SetUp() { // // Can use GetParam() here. // } // virtual void TearDown { // // Can use GetParam() here. // } // }; // TEST_P(FooTest, DoesBar) { // // Can use GetParam() method here. // Foo foo; // ASSERT_TRUE(foo.DoesBar(GetParam())); // } // INSTANTIATE_TEST_CASE_P(OneToTenRange, FooTest, ::testing::Range(1, 10)); template class WithParamInterface { public: typedef T ParamType; virtual ~WithParamInterface() {} // The current parameter value. Is also available in the test fixture's // constructor. This member function is non-static, even though it only // references static data, to reduce the opportunity for incorrect uses // like writing 'WithParamInterface::GetParam()' for a test that // uses a fixture whose parameter type is int. const ParamType& GetParam() const { return *parameter_; } private: // Sets parameter value. The caller is responsible for making sure the value // remains alive and unchanged throughout the current test. static void SetParam(const ParamType* parameter) { parameter_ = parameter; } // Static value used for accessing parameter during a test lifetime. static const ParamType* parameter_; // TestClass must be a subclass of WithParamInterface and Test. template friend class internal::ParameterizedTestFactory; }; template const T* WithParamInterface::parameter_ = NULL; // Most value-parameterized classes can ignore the existence of // WithParamInterface, and can just inherit from ::testing::TestWithParam. template class TestWithParam : public Test, public WithParamInterface { }; #endif // GTEST_HAS_PARAM_TEST // Macros for indicating success/failure in test code. // ADD_FAILURE unconditionally adds a failure to the current test. // SUCCEED generates a success - it doesn't automatically make the // current test successful, as a test is only successful when it has // no failure. // // EXPECT_* verifies that a certain condition is satisfied. If not, // it behaves like ADD_FAILURE. In particular: // // EXPECT_TRUE verifies that a Boolean condition is true. // EXPECT_FALSE verifies that a Boolean condition is false. // // FAIL and ASSERT_* are similar to ADD_FAILURE and EXPECT_*, except // that they will also abort the current function on failure. People // usually want the fail-fast behavior of FAIL and ASSERT_*, but those // writing data-driven tests often find themselves using ADD_FAILURE // and EXPECT_* more. // // Examples: // // EXPECT_TRUE(server.StatusIsOK()); // ASSERT_FALSE(server.HasPendingRequest(port)) // << "There are still pending requests " << "on port " << port; // Generates a nonfatal failure with a generic message. #define ADD_FAILURE() GTEST_NONFATAL_FAILURE_("Failed") // Generates a nonfatal failure at the given source file location with // a generic message. #define ADD_FAILURE_AT(file, line) \ GTEST_MESSAGE_AT_(file, line, "Failed", \ ::testing::TestPartResult::kNonFatalFailure) // Generates a fatal failure with a generic message. #define GTEST_FAIL() GTEST_FATAL_FAILURE_("Failed") // Define this macro to 1 to omit the definition of FAIL(), which is a // generic name and clashes with some other libraries. #if !GTEST_DONT_DEFINE_FAIL # define FAIL() GTEST_FAIL() #endif // Generates a success with a generic message. #define GTEST_SUCCEED() GTEST_SUCCESS_("Succeeded") // Define this macro to 1 to omit the definition of SUCCEED(), which // is a generic name and clashes with some other libraries. #if !GTEST_DONT_DEFINE_SUCCEED # define SUCCEED() GTEST_SUCCEED() #endif // Macros for testing exceptions. // // * {ASSERT|EXPECT}_THROW(statement, expected_exception): // Tests that the statement throws the expected exception. // * {ASSERT|EXPECT}_NO_THROW(statement): // Tests that the statement doesn't throw any exception. // * {ASSERT|EXPECT}_ANY_THROW(statement): // Tests that the statement throws an exception. #define EXPECT_THROW(statement, expected_exception) \ GTEST_TEST_THROW_(statement, expected_exception, GTEST_NONFATAL_FAILURE_) #define EXPECT_NO_THROW(statement) \ GTEST_TEST_NO_THROW_(statement, GTEST_NONFATAL_FAILURE_) #define EXPECT_ANY_THROW(statement) \ GTEST_TEST_ANY_THROW_(statement, GTEST_NONFATAL_FAILURE_) #define ASSERT_THROW(statement, expected_exception) \ GTEST_TEST_THROW_(statement, expected_exception, GTEST_FATAL_FAILURE_) #define ASSERT_NO_THROW(statement) \ GTEST_TEST_NO_THROW_(statement, GTEST_FATAL_FAILURE_) #define ASSERT_ANY_THROW(statement) \ GTEST_TEST_ANY_THROW_(statement, GTEST_FATAL_FAILURE_) // Boolean assertions. Condition can be either a Boolean expression or an // AssertionResult. For more information on how to use AssertionResult with // these macros see comments on that class. #define EXPECT_TRUE(condition) \ GTEST_TEST_BOOLEAN_(condition, #condition, false, true, \ GTEST_NONFATAL_FAILURE_) #define EXPECT_FALSE(condition) \ GTEST_TEST_BOOLEAN_(!(condition), #condition, true, false, \ GTEST_NONFATAL_FAILURE_) #define ASSERT_TRUE(condition) \ GTEST_TEST_BOOLEAN_(condition, #condition, false, true, \ GTEST_FATAL_FAILURE_) #define ASSERT_FALSE(condition) \ GTEST_TEST_BOOLEAN_(!(condition), #condition, true, false, \ GTEST_FATAL_FAILURE_) // Includes the auto-generated header that implements a family of // generic predicate assertion macros. #include "gtest/gtest_pred_impl.h" // Macros for testing equalities and inequalities. // // * {ASSERT|EXPECT}_EQ(expected, actual): Tests that expected == actual // * {ASSERT|EXPECT}_NE(v1, v2): Tests that v1 != v2 // * {ASSERT|EXPECT}_LT(v1, v2): Tests that v1 < v2 // * {ASSERT|EXPECT}_LE(v1, v2): Tests that v1 <= v2 // * {ASSERT|EXPECT}_GT(v1, v2): Tests that v1 > v2 // * {ASSERT|EXPECT}_GE(v1, v2): Tests that v1 >= v2 // // When they are not, Google Test prints both the tested expressions and // their actual values. The values must be compatible built-in types, // or you will get a compiler error. By "compatible" we mean that the // values can be compared by the respective operator. // // Note: // // 1. It is possible to make a user-defined type work with // {ASSERT|EXPECT}_??(), but that requires overloading the // comparison operators and is thus discouraged by the Google C++ // Usage Guide. Therefore, you are advised to use the // {ASSERT|EXPECT}_TRUE() macro to assert that two objects are // equal. // // 2. The {ASSERT|EXPECT}_??() macros do pointer comparisons on // pointers (in particular, C strings). Therefore, if you use it // with two C strings, you are testing how their locations in memory // are related, not how their content is related. To compare two C // strings by content, use {ASSERT|EXPECT}_STR*(). // // 3. {ASSERT|EXPECT}_EQ(expected, actual) is preferred to // {ASSERT|EXPECT}_TRUE(expected == actual), as the former tells you // what the actual value is when it fails, and similarly for the // other comparisons. // // 4. Do not depend on the order in which {ASSERT|EXPECT}_??() // evaluate their arguments, which is undefined. // // 5. These macros evaluate their arguments exactly once. // // Examples: // // EXPECT_NE(5, Foo()); // EXPECT_EQ(NULL, a_pointer); // ASSERT_LT(i, array_size); // ASSERT_GT(records.size(), 0) << "There is no record left."; #define EXPECT_EQ(expected, actual) \ EXPECT_PRED_FORMAT2(::testing::internal:: \ EqHelper::Compare, \ expected, actual) #define EXPECT_NE(expected, actual) \ EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperNE, expected, actual) #define EXPECT_LE(val1, val2) \ EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperLE, val1, val2) #define EXPECT_LT(val1, val2) \ EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperLT, val1, val2) #define EXPECT_GE(val1, val2) \ EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperGE, val1, val2) #define EXPECT_GT(val1, val2) \ EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperGT, val1, val2) #define GTEST_ASSERT_EQ(expected, actual) \ ASSERT_PRED_FORMAT2(::testing::internal:: \ EqHelper::Compare, \ expected, actual) #define GTEST_ASSERT_NE(val1, val2) \ ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperNE, val1, val2) #define GTEST_ASSERT_LE(val1, val2) \ ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperLE, val1, val2) #define GTEST_ASSERT_LT(val1, val2) \ ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperLT, val1, val2) #define GTEST_ASSERT_GE(val1, val2) \ ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperGE, val1, val2) #define GTEST_ASSERT_GT(val1, val2) \ ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperGT, val1, val2) // Define macro GTEST_DONT_DEFINE_ASSERT_XY to 1 to omit the definition of // ASSERT_XY(), which clashes with some users' own code. #if !GTEST_DONT_DEFINE_ASSERT_EQ # define ASSERT_EQ(val1, val2) GTEST_ASSERT_EQ(val1, val2) #endif #if !GTEST_DONT_DEFINE_ASSERT_NE # define ASSERT_NE(val1, val2) GTEST_ASSERT_NE(val1, val2) #endif #if !GTEST_DONT_DEFINE_ASSERT_LE # define ASSERT_LE(val1, val2) GTEST_ASSERT_LE(val1, val2) #endif #if !GTEST_DONT_DEFINE_ASSERT_LT # define ASSERT_LT(val1, val2) GTEST_ASSERT_LT(val1, val2) #endif #if !GTEST_DONT_DEFINE_ASSERT_GE # define ASSERT_GE(val1, val2) GTEST_ASSERT_GE(val1, val2) #endif #if !GTEST_DONT_DEFINE_ASSERT_GT # define ASSERT_GT(val1, val2) GTEST_ASSERT_GT(val1, val2) #endif // C String Comparisons. All tests treat NULL and any non-NULL string // as different. Two NULLs are equal. // // * {ASSERT|EXPECT}_STREQ(s1, s2): Tests that s1 == s2 // * {ASSERT|EXPECT}_STRNE(s1, s2): Tests that s1 != s2 // * {ASSERT|EXPECT}_STRCASEEQ(s1, s2): Tests that s1 == s2, ignoring case // * {ASSERT|EXPECT}_STRCASENE(s1, s2): Tests that s1 != s2, ignoring case // // For wide or narrow string objects, you can use the // {ASSERT|EXPECT}_??() macros. // // Don't depend on the order in which the arguments are evaluated, // which is undefined. // // These macros evaluate their arguments exactly once. #define EXPECT_STREQ(expected, actual) \ EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperSTREQ, expected, actual) #define EXPECT_STRNE(s1, s2) \ EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperSTRNE, s1, s2) #define EXPECT_STRCASEEQ(expected, actual) \ EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperSTRCASEEQ, expected, actual) #define EXPECT_STRCASENE(s1, s2)\ EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperSTRCASENE, s1, s2) #define ASSERT_STREQ(expected, actual) \ ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperSTREQ, expected, actual) #define ASSERT_STRNE(s1, s2) \ ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperSTRNE, s1, s2) #define ASSERT_STRCASEEQ(expected, actual) \ ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperSTRCASEEQ, expected, actual) #define ASSERT_STRCASENE(s1, s2)\ ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperSTRCASENE, s1, s2) // Macros for comparing floating-point numbers. // // * {ASSERT|EXPECT}_FLOAT_EQ(expected, actual): // Tests that two float values are almost equal. // * {ASSERT|EXPECT}_DOUBLE_EQ(expected, actual): // Tests that two double values are almost equal. // * {ASSERT|EXPECT}_NEAR(v1, v2, abs_error): // Tests that v1 and v2 are within the given distance to each other. // // Google Test uses ULP-based comparison to automatically pick a default // error bound that is appropriate for the operands. See the // FloatingPoint template class in gtest-internal.h if you are // interested in the implementation details. #define EXPECT_FLOAT_EQ(expected, actual)\ EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperFloatingPointEQ, \ expected, actual) #define EXPECT_DOUBLE_EQ(expected, actual)\ EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperFloatingPointEQ, \ expected, actual) #define ASSERT_FLOAT_EQ(expected, actual)\ ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperFloatingPointEQ, \ expected, actual) #define ASSERT_DOUBLE_EQ(expected, actual)\ ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperFloatingPointEQ, \ expected, actual) #define EXPECT_NEAR(val1, val2, abs_error)\ EXPECT_PRED_FORMAT3(::testing::internal::DoubleNearPredFormat, \ val1, val2, abs_error) #define ASSERT_NEAR(val1, val2, abs_error)\ ASSERT_PRED_FORMAT3(::testing::internal::DoubleNearPredFormat, \ val1, val2, abs_error) // These predicate format functions work on floating-point values, and // can be used in {ASSERT|EXPECT}_PRED_FORMAT2*(), e.g. // // EXPECT_PRED_FORMAT2(testing::DoubleLE, Foo(), 5.0); // Asserts that val1 is less than, or almost equal to, val2. Fails // otherwise. In particular, it fails if either val1 or val2 is NaN. GTEST_API_ AssertionResult FloatLE(const char* expr1, const char* expr2, float val1, float val2); GTEST_API_ AssertionResult DoubleLE(const char* expr1, const char* expr2, double val1, double val2); #if GTEST_OS_WINDOWS // Macros that test for HRESULT failure and success, these are only useful // on Windows, and rely on Windows SDK macros and APIs to compile. // // * {ASSERT|EXPECT}_HRESULT_{SUCCEEDED|FAILED}(expr) // // When expr unexpectedly fails or succeeds, Google Test prints the // expected result and the actual result with both a human-readable // string representation of the error, if available, as well as the // hex result code. # define EXPECT_HRESULT_SUCCEEDED(expr) \ EXPECT_PRED_FORMAT1(::testing::internal::IsHRESULTSuccess, (expr)) # define ASSERT_HRESULT_SUCCEEDED(expr) \ ASSERT_PRED_FORMAT1(::testing::internal::IsHRESULTSuccess, (expr)) # define EXPECT_HRESULT_FAILED(expr) \ EXPECT_PRED_FORMAT1(::testing::internal::IsHRESULTFailure, (expr)) # define ASSERT_HRESULT_FAILED(expr) \ ASSERT_PRED_FORMAT1(::testing::internal::IsHRESULTFailure, (expr)) #endif // GTEST_OS_WINDOWS // Macros that execute statement and check that it doesn't generate new fatal // failures in the current thread. // // * {ASSERT|EXPECT}_NO_FATAL_FAILURE(statement); // // Examples: // // EXPECT_NO_FATAL_FAILURE(Process()); // ASSERT_NO_FATAL_FAILURE(Process()) << "Process() failed"; // #define ASSERT_NO_FATAL_FAILURE(statement) \ GTEST_TEST_NO_FATAL_FAILURE_(statement, GTEST_FATAL_FAILURE_) #define EXPECT_NO_FATAL_FAILURE(statement) \ GTEST_TEST_NO_FATAL_FAILURE_(statement, GTEST_NONFATAL_FAILURE_) // Causes a trace (including the source file path, the current line // number, and the given message) to be included in every test failure // message generated by code in the current scope. The effect is // undone when the control leaves the current scope. // // The message argument can be anything streamable to std::ostream. // // In the implementation, we include the current line number as part // of the dummy variable name, thus allowing multiple SCOPED_TRACE()s // to appear in the same block - as long as they are on different // lines. #define SCOPED_TRACE(message) \ ::testing::internal::ScopedTrace GTEST_CONCAT_TOKEN_(gtest_trace_, __LINE__)(\ __FILE__, __LINE__, ::testing::Message() << (message)) // Compile-time assertion for type equality. // StaticAssertTypeEq() compiles iff type1 and type2 are // the same type. The value it returns is not interesting. // // Instead of making StaticAssertTypeEq a class template, we make it a // function template that invokes a helper class template. This // prevents a user from misusing StaticAssertTypeEq by // defining objects of that type. // // CAVEAT: // // When used inside a method of a class template, // StaticAssertTypeEq() is effective ONLY IF the method is // instantiated. For example, given: // // template class Foo { // public: // void Bar() { testing::StaticAssertTypeEq(); } // }; // // the code: // // void Test1() { Foo foo; } // // will NOT generate a compiler error, as Foo::Bar() is never // actually instantiated. Instead, you need: // // void Test2() { Foo foo; foo.Bar(); } // // to cause a compiler error. template bool StaticAssertTypeEq() { (void)internal::StaticAssertTypeEqHelper(); return true; } // Defines a test. // // The first parameter is the name of the test case, and the second // parameter is the name of the test within the test case. // // The convention is to end the test case name with "Test". For // example, a test case for the Foo class can be named FooTest. // // The user should put his test code between braces after using this // macro. Example: // // TEST(FooTest, InitializesCorrectly) { // Foo foo; // EXPECT_TRUE(foo.StatusIsOK()); // } // Note that we call GetTestTypeId() instead of GetTypeId< // ::testing::Test>() here to get the type ID of testing::Test. This // is to work around a suspected linker bug when using Google Test as // a framework on Mac OS X. The bug causes GetTypeId< // ::testing::Test>() to return different values depending on whether // the call is from the Google Test framework itself or from user test // code. GetTestTypeId() is guaranteed to always return the same // value, as it always calls GetTypeId<>() from the Google Test // framework. #define GTEST_TEST(test_case_name, test_name)\ GTEST_TEST_(test_case_name, test_name, \ ::testing::Test, ::testing::internal::GetTestTypeId()) // Define this macro to 1 to omit the definition of TEST(), which // is a generic name and clashes with some other libraries. #if !GTEST_DONT_DEFINE_TEST # define TEST(test_case_name, test_name) GTEST_TEST(test_case_name, test_name) #endif // Defines a test that uses a test fixture. // // The first parameter is the name of the test fixture class, which // also doubles as the test case name. The second parameter is the // name of the test within the test case. // // A test fixture class must be declared earlier. The user should put // his test code between braces after using this macro. Example: // // class FooTest : public testing::Test { // protected: // virtual void SetUp() { b_.AddElement(3); } // // Foo a_; // Foo b_; // }; // // TEST_F(FooTest, InitializesCorrectly) { // EXPECT_TRUE(a_.StatusIsOK()); // } // // TEST_F(FooTest, ReturnsElementCountCorrectly) { // EXPECT_EQ(0, a_.size()); // EXPECT_EQ(1, b_.size()); // } #define TEST_F(test_fixture, test_name)\ GTEST_TEST_(test_fixture, test_name, test_fixture, \ ::testing::internal::GetTypeId()) // Use this macro in main() to run all tests. It returns 0 if all // tests are successful, or 1 otherwise. // // RUN_ALL_TESTS() should be invoked after the command line has been // parsed by InitGoogleTest(). #define RUN_ALL_TESTS()\ (::testing::UnitTest::GetInstance()->Run()) } // namespace testing #endif // GTEST_INCLUDE_GTEST_GTEST_H_ ugene-1.9.8/src/libs_3rdparty/gtest/src/gtest/gtest-spi.h0000644000175000017500000002333711651544307022033 0ustar ilyailya// Copyright 2007, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Author: wan@google.com (Zhanyong Wan) // // Utilities for testing Google Test itself and code that uses Google Test // (e.g. frameworks built on top of Google Test). #ifndef GTEST_INCLUDE_GTEST_GTEST_SPI_H_ #define GTEST_INCLUDE_GTEST_GTEST_SPI_H_ #include "gtest/gtest.h" namespace testing { // This helper class can be used to mock out Google Test failure reporting // so that we can test Google Test or code that builds on Google Test. // // An object of this class appends a TestPartResult object to the // TestPartResultArray object given in the constructor whenever a Google Test // failure is reported. It can either intercept only failures that are // generated in the same thread that created this object or it can intercept // all generated failures. The scope of this mock object can be controlled with // the second argument to the two arguments constructor. class GTEST_API_ ScopedFakeTestPartResultReporter : public TestPartResultReporterInterface { public: // The two possible mocking modes of this object. enum InterceptMode { INTERCEPT_ONLY_CURRENT_THREAD, // Intercepts only thread local failures. INTERCEPT_ALL_THREADS // Intercepts all failures. }; // The c'tor sets this object as the test part result reporter used // by Google Test. The 'result' parameter specifies where to report the // results. This reporter will only catch failures generated in the current // thread. DEPRECATED explicit ScopedFakeTestPartResultReporter(TestPartResultArray* result); // Same as above, but you can choose the interception scope of this object. ScopedFakeTestPartResultReporter(InterceptMode intercept_mode, TestPartResultArray* result); // The d'tor restores the previous test part result reporter. virtual ~ScopedFakeTestPartResultReporter(); // Appends the TestPartResult object to the TestPartResultArray // received in the constructor. // // This method is from the TestPartResultReporterInterface // interface. virtual void ReportTestPartResult(const TestPartResult& result); private: void Init(); const InterceptMode intercept_mode_; TestPartResultReporterInterface* old_reporter_; TestPartResultArray* const result_; GTEST_DISALLOW_COPY_AND_ASSIGN_(ScopedFakeTestPartResultReporter); }; namespace internal { // A helper class for implementing EXPECT_FATAL_FAILURE() and // EXPECT_NONFATAL_FAILURE(). Its destructor verifies that the given // TestPartResultArray contains exactly one failure that has the given // type and contains the given substring. If that's not the case, a // non-fatal failure will be generated. class GTEST_API_ SingleFailureChecker { public: // The constructor remembers the arguments. SingleFailureChecker(const TestPartResultArray* results, TestPartResult::Type type, const string& substr); ~SingleFailureChecker(); private: const TestPartResultArray* const results_; const TestPartResult::Type type_; const string substr_; GTEST_DISALLOW_COPY_AND_ASSIGN_(SingleFailureChecker); }; } // namespace internal } // namespace testing // A set of macros for testing Google Test assertions or code that's expected // to generate Google Test fatal failures. It verifies that the given // statement will cause exactly one fatal Google Test failure with 'substr' // being part of the failure message. // // There are two different versions of this macro. EXPECT_FATAL_FAILURE only // affects and considers failures generated in the current thread and // EXPECT_FATAL_FAILURE_ON_ALL_THREADS does the same but for all threads. // // The verification of the assertion is done correctly even when the statement // throws an exception or aborts the current function. // // Known restrictions: // - 'statement' cannot reference local non-static variables or // non-static members of the current object. // - 'statement' cannot return a value. // - You cannot stream a failure message to this macro. // // Note that even though the implementations of the following two // macros are much alike, we cannot refactor them to use a common // helper macro, due to some peculiarity in how the preprocessor // works. The AcceptsMacroThatExpandsToUnprotectedComma test in // gtest_unittest.cc will fail to compile if we do that. #define EXPECT_FATAL_FAILURE(statement, substr) \ do { \ class GTestExpectFatalFailureHelper {\ public:\ static void Execute() { statement; }\ };\ ::testing::TestPartResultArray gtest_failures;\ ::testing::internal::SingleFailureChecker gtest_checker(\ >est_failures, ::testing::TestPartResult::kFatalFailure, (substr));\ {\ ::testing::ScopedFakeTestPartResultReporter gtest_reporter(\ ::testing::ScopedFakeTestPartResultReporter:: \ INTERCEPT_ONLY_CURRENT_THREAD, >est_failures);\ GTestExpectFatalFailureHelper::Execute();\ }\ } while (::testing::internal::AlwaysFalse()) #define EXPECT_FATAL_FAILURE_ON_ALL_THREADS(statement, substr) \ do { \ class GTestExpectFatalFailureHelper {\ public:\ static void Execute() { statement; }\ };\ ::testing::TestPartResultArray gtest_failures;\ ::testing::internal::SingleFailureChecker gtest_checker(\ >est_failures, ::testing::TestPartResult::kFatalFailure, (substr));\ {\ ::testing::ScopedFakeTestPartResultReporter gtest_reporter(\ ::testing::ScopedFakeTestPartResultReporter:: \ INTERCEPT_ALL_THREADS, >est_failures);\ GTestExpectFatalFailureHelper::Execute();\ }\ } while (::testing::internal::AlwaysFalse()) // A macro for testing Google Test assertions or code that's expected to // generate Google Test non-fatal failures. It asserts that the given // statement will cause exactly one non-fatal Google Test failure with 'substr' // being part of the failure message. // // There are two different versions of this macro. EXPECT_NONFATAL_FAILURE only // affects and considers failures generated in the current thread and // EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS does the same but for all threads. // // 'statement' is allowed to reference local variables and members of // the current object. // // The verification of the assertion is done correctly even when the statement // throws an exception or aborts the current function. // // Known restrictions: // - You cannot stream a failure message to this macro. // // Note that even though the implementations of the following two // macros are much alike, we cannot refactor them to use a common // helper macro, due to some peculiarity in how the preprocessor // works. If we do that, the code won't compile when the user gives // EXPECT_NONFATAL_FAILURE() a statement that contains a macro that // expands to code containing an unprotected comma. The // AcceptsMacroThatExpandsToUnprotectedComma test in gtest_unittest.cc // catches that. // // For the same reason, we have to write // if (::testing::internal::AlwaysTrue()) { statement; } // instead of // GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement) // to avoid an MSVC warning on unreachable code. #define EXPECT_NONFATAL_FAILURE(statement, substr) \ do {\ ::testing::TestPartResultArray gtest_failures;\ ::testing::internal::SingleFailureChecker gtest_checker(\ >est_failures, ::testing::TestPartResult::kNonFatalFailure, \ (substr));\ {\ ::testing::ScopedFakeTestPartResultReporter gtest_reporter(\ ::testing::ScopedFakeTestPartResultReporter:: \ INTERCEPT_ONLY_CURRENT_THREAD, >est_failures);\ if (::testing::internal::AlwaysTrue()) { statement; }\ }\ } while (::testing::internal::AlwaysFalse()) #define EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS(statement, substr) \ do {\ ::testing::TestPartResultArray gtest_failures;\ ::testing::internal::SingleFailureChecker gtest_checker(\ >est_failures, ::testing::TestPartResult::kNonFatalFailure, \ (substr));\ {\ ::testing::ScopedFakeTestPartResultReporter gtest_reporter(\ ::testing::ScopedFakeTestPartResultReporter::INTERCEPT_ALL_THREADS,\ >est_failures);\ if (::testing::internal::AlwaysTrue()) { statement; }\ }\ } while (::testing::internal::AlwaysFalse()) #endif // GTEST_INCLUDE_GTEST_GTEST_SPI_H_ ugene-1.9.8/src/libs_3rdparty/gtest/src/gtest/gtest-printers.h0000644000175000017500000007307111651544307023106 0ustar ilyailya// Copyright 2007, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Author: wan@google.com (Zhanyong Wan) // Google Test - The Google C++ Testing Framework // // This file implements a universal value printer that can print a // value of any type T: // // void ::testing::internal::UniversalPrinter::Print(value, ostream_ptr); // // A user can teach this function how to print a class type T by // defining either operator<<() or PrintTo() in the namespace that // defines T. More specifically, the FIRST defined function in the // following list will be used (assuming T is defined in namespace // foo): // // 1. foo::PrintTo(const T&, ostream*) // 2. operator<<(ostream&, const T&) defined in either foo or the // global namespace. // // If none of the above is defined, it will print the debug string of // the value if it is a protocol buffer, or print the raw bytes in the // value otherwise. // // To aid debugging: when T is a reference type, the address of the // value is also printed; when T is a (const) char pointer, both the // pointer value and the NUL-terminated string it points to are // printed. // // We also provide some convenient wrappers: // // // Prints a value to a string. For a (const or not) char // // pointer, the NUL-terminated string (but not the pointer) is // // printed. // std::string ::testing::PrintToString(const T& value); // // // Prints a value tersely: for a reference type, the referenced // // value (but not the address) is printed; for a (const or not) char // // pointer, the NUL-terminated string (but not the pointer) is // // printed. // void ::testing::internal::UniversalTersePrint(const T& value, ostream*); // // // Prints value using the type inferred by the compiler. The difference // // from UniversalTersePrint() is that this function prints both the // // pointer and the NUL-terminated string for a (const or not) char pointer. // void ::testing::internal::UniversalPrint(const T& value, ostream*); // // // Prints the fields of a tuple tersely to a string vector, one // // element for each field. Tuple support must be enabled in // // gtest-port.h. // std::vector UniversalTersePrintTupleFieldsToStrings( // const Tuple& value); // // Known limitation: // // The print primitives print the elements of an STL-style container // using the compiler-inferred type of *iter where iter is a // const_iterator of the container. When const_iterator is an input // iterator but not a forward iterator, this inferred type may not // match value_type, and the print output may be incorrect. In // practice, this is rarely a problem as for most containers // const_iterator is a forward iterator. We'll fix this if there's an // actual need for it. Note that this fix cannot rely on value_type // being defined as many user-defined container types don't have // value_type. #ifndef GTEST_INCLUDE_GTEST_GTEST_PRINTERS_H_ #define GTEST_INCLUDE_GTEST_GTEST_PRINTERS_H_ #include // NOLINT #include #include #include #include #include "gtest/internal/gtest-port.h" #include "gtest/internal/gtest-internal.h" namespace testing { // Definitions in the 'internal' and 'internal2' name spaces are // subject to change without notice. DO NOT USE THEM IN USER CODE! namespace internal2 { // Prints the given number of bytes in the given object to the given // ostream. GTEST_API_ void PrintBytesInObjectTo(const unsigned char* obj_bytes, size_t count, ::std::ostream* os); // For selecting which printer to use when a given type has neither << // nor PrintTo(). enum TypeKind { kProtobuf, // a protobuf type kConvertibleToInteger, // a type implicitly convertible to BiggestInt // (e.g. a named or unnamed enum type) kOtherType // anything else }; // TypeWithoutFormatter::PrintValue(value, os) is called // by the universal printer to print a value of type T when neither // operator<< nor PrintTo() is defined for T, where kTypeKind is the // "kind" of T as defined by enum TypeKind. template class TypeWithoutFormatter { public: // This default version is called when kTypeKind is kOtherType. static void PrintValue(const T& value, ::std::ostream* os) { PrintBytesInObjectTo(reinterpret_cast(&value), sizeof(value), os); } }; // We print a protobuf using its ShortDebugString() when the string // doesn't exceed this many characters; otherwise we print it using // DebugString() for better readability. const size_t kProtobufOneLinerMaxLength = 50; template class TypeWithoutFormatter { public: static void PrintValue(const T& value, ::std::ostream* os) { const ::testing::internal::string short_str = value.ShortDebugString(); const ::testing::internal::string pretty_str = short_str.length() <= kProtobufOneLinerMaxLength ? short_str : ("\n" + value.DebugString()); *os << ("<" + pretty_str + ">"); } }; template class TypeWithoutFormatter { public: // Since T has no << operator or PrintTo() but can be implicitly // converted to BiggestInt, we print it as a BiggestInt. // // Most likely T is an enum type (either named or unnamed), in which // case printing it as an integer is the desired behavior. In case // T is not an enum, printing it as an integer is the best we can do // given that it has no user-defined printer. static void PrintValue(const T& value, ::std::ostream* os) { const internal::BiggestInt kBigInt = value; *os << kBigInt; } }; // Prints the given value to the given ostream. If the value is a // protocol message, its debug string is printed; if it's an enum or // of a type implicitly convertible to BiggestInt, it's printed as an // integer; otherwise the bytes in the value are printed. This is // what UniversalPrinter::Print() does when it knows nothing about // type T and T has neither << operator nor PrintTo(). // // A user can override this behavior for a class type Foo by defining // a << operator in the namespace where Foo is defined. // // We put this operator in namespace 'internal2' instead of 'internal' // to simplify the implementation, as much code in 'internal' needs to // use << in STL, which would conflict with our own << were it defined // in 'internal'. // // Note that this operator<< takes a generic std::basic_ostream type instead of the more restricted std::ostream. If // we define it to take an std::ostream instead, we'll get an // "ambiguous overloads" compiler error when trying to print a type // Foo that supports streaming to std::basic_ostream, as the compiler cannot tell whether // operator<<(std::ostream&, const T&) or // operator<<(std::basic_stream, const Foo&) is more // specific. template ::std::basic_ostream& operator<<( ::std::basic_ostream& os, const T& x) { TypeWithoutFormatter::value ? kProtobuf : internal::ImplicitlyConvertible::value ? kConvertibleToInteger : kOtherType)>::PrintValue(x, &os); return os; } } // namespace internal2 } // namespace testing // This namespace MUST NOT BE NESTED IN ::testing, or the name look-up // magic needed for implementing UniversalPrinter won't work. namespace testing_internal { // Used to print a value that is not an STL-style container when the // user doesn't define PrintTo() for it. template void DefaultPrintNonContainerTo(const T& value, ::std::ostream* os) { // With the following statement, during unqualified name lookup, // testing::internal2::operator<< appears as if it was declared in // the nearest enclosing namespace that contains both // ::testing_internal and ::testing::internal2, i.e. the global // namespace. For more details, refer to the C++ Standard section // 7.3.4-1 [namespace.udir]. This allows us to fall back onto // testing::internal2::operator<< in case T doesn't come with a << // operator. // // We cannot write 'using ::testing::internal2::operator<<;', which // gcc 3.3 fails to compile due to a compiler bug. using namespace ::testing::internal2; // NOLINT // Assuming T is defined in namespace foo, in the next statement, // the compiler will consider all of: // // 1. foo::operator<< (thanks to Koenig look-up), // 2. ::operator<< (as the current namespace is enclosed in ::), // 3. testing::internal2::operator<< (thanks to the using statement above). // // The operator<< whose type matches T best will be picked. // // We deliberately allow #2 to be a candidate, as sometimes it's // impossible to define #1 (e.g. when foo is ::std, defining // anything in it is undefined behavior unless you are a compiler // vendor.). *os << value; } } // namespace testing_internal namespace testing { namespace internal { // UniversalPrinter::Print(value, ostream_ptr) prints the given // value to the given ostream. The caller must ensure that // 'ostream_ptr' is not NULL, or the behavior is undefined. // // We define UniversalPrinter as a class template (as opposed to a // function template), as we need to partially specialize it for // reference types, which cannot be done with function templates. template class UniversalPrinter; template void UniversalPrint(const T& value, ::std::ostream* os); // Used to print an STL-style container when the user doesn't define // a PrintTo() for it. template void DefaultPrintTo(IsContainer /* dummy */, false_type /* is not a pointer */, const C& container, ::std::ostream* os) { const size_t kMaxCount = 32; // The maximum number of elements to print. *os << '{'; size_t count = 0; for (typename C::const_iterator it = container.begin(); it != container.end(); ++it, ++count) { if (count > 0) { *os << ','; if (count == kMaxCount) { // Enough has been printed. *os << " ..."; break; } } *os << ' '; // We cannot call PrintTo(*it, os) here as PrintTo() doesn't // handle *it being a native array. internal::UniversalPrint(*it, os); } if (count > 0) { *os << ' '; } *os << '}'; } // Used to print a pointer that is neither a char pointer nor a member // pointer, when the user doesn't define PrintTo() for it. (A member // variable pointer or member function pointer doesn't really point to // a location in the address space. Their representation is // implementation-defined. Therefore they will be printed as raw // bytes.) template void DefaultPrintTo(IsNotContainer /* dummy */, true_type /* is a pointer */, T* p, ::std::ostream* os) { if (p == NULL) { *os << "NULL"; } else { // C++ doesn't allow casting from a function pointer to any object // pointer. // // IsTrue() silences warnings: "Condition is always true", // "unreachable code". if (IsTrue(ImplicitlyConvertible::value)) { // T is not a function type. We just call << to print p, // relying on ADL to pick up user-defined << for their pointer // types, if any. *os << p; } else { // T is a function type, so '*os << p' doesn't do what we want // (it just prints p as bool). We want to print p as a const // void*. However, we cannot cast it to const void* directly, // even using reinterpret_cast, as earlier versions of gcc // (e.g. 3.4.5) cannot compile the cast when p is a function // pointer. Casting to UInt64 first solves the problem. *os << reinterpret_cast( reinterpret_cast(p)); } } } // Used to print a non-container, non-pointer value when the user // doesn't define PrintTo() for it. template void DefaultPrintTo(IsNotContainer /* dummy */, false_type /* is not a pointer */, const T& value, ::std::ostream* os) { ::testing_internal::DefaultPrintNonContainerTo(value, os); } // Prints the given value using the << operator if it has one; // otherwise prints the bytes in it. This is what // UniversalPrinter::Print() does when PrintTo() is not specialized // or overloaded for type T. // // A user can override this behavior for a class type Foo by defining // an overload of PrintTo() in the namespace where Foo is defined. We // give the user this option as sometimes defining a << operator for // Foo is not desirable (e.g. the coding style may prevent doing it, // or there is already a << operator but it doesn't do what the user // wants). template void PrintTo(const T& value, ::std::ostream* os) { // DefaultPrintTo() is overloaded. The type of its first two // arguments determine which version will be picked. If T is an // STL-style container, the version for container will be called; if // T is a pointer, the pointer version will be called; otherwise the // generic version will be called. // // Note that we check for container types here, prior to we check // for protocol message types in our operator<<. The rationale is: // // For protocol messages, we want to give people a chance to // override Google Mock's format by defining a PrintTo() or // operator<<. For STL containers, other formats can be // incompatible with Google Mock's format for the container // elements; therefore we check for container types here to ensure // that our format is used. // // The second argument of DefaultPrintTo() is needed to bypass a bug // in Symbian's C++ compiler that prevents it from picking the right // overload between: // // PrintTo(const T& x, ...); // PrintTo(T* x, ...); DefaultPrintTo(IsContainerTest(0), is_pointer(), value, os); } // The following list of PrintTo() overloads tells // UniversalPrinter::Print() how to print standard types (built-in // types, strings, plain arrays, and pointers). // Overloads for various char types. GTEST_API_ void PrintTo(unsigned char c, ::std::ostream* os); GTEST_API_ void PrintTo(signed char c, ::std::ostream* os); inline void PrintTo(char c, ::std::ostream* os) { // When printing a plain char, we always treat it as unsigned. This // way, the output won't be affected by whether the compiler thinks // char is signed or not. PrintTo(static_cast(c), os); } // Overloads for other simple built-in types. inline void PrintTo(bool x, ::std::ostream* os) { *os << (x ? "true" : "false"); } // Overload for wchar_t type. // Prints a wchar_t as a symbol if it is printable or as its internal // code otherwise and also as its decimal code (except for L'\0'). // The L'\0' char is printed as "L'\\0'". The decimal code is printed // as signed integer when wchar_t is implemented by the compiler // as a signed type and is printed as an unsigned integer when wchar_t // is implemented as an unsigned type. GTEST_API_ void PrintTo(wchar_t wc, ::std::ostream* os); // Overloads for C strings. GTEST_API_ void PrintTo(const char* s, ::std::ostream* os); inline void PrintTo(char* s, ::std::ostream* os) { PrintTo(ImplicitCast_(s), os); } // signed/unsigned char is often used for representing binary data, so // we print pointers to it as void* to be safe. inline void PrintTo(const signed char* s, ::std::ostream* os) { PrintTo(ImplicitCast_(s), os); } inline void PrintTo(signed char* s, ::std::ostream* os) { PrintTo(ImplicitCast_(s), os); } inline void PrintTo(const unsigned char* s, ::std::ostream* os) { PrintTo(ImplicitCast_(s), os); } inline void PrintTo(unsigned char* s, ::std::ostream* os) { PrintTo(ImplicitCast_(s), os); } // MSVC can be configured to define wchar_t as a typedef of unsigned // short. It defines _NATIVE_WCHAR_T_DEFINED when wchar_t is a native // type. When wchar_t is a typedef, defining an overload for const // wchar_t* would cause unsigned short* be printed as a wide string, // possibly causing invalid memory accesses. #if !defined(_MSC_VER) || defined(_NATIVE_WCHAR_T_DEFINED) // Overloads for wide C strings GTEST_API_ void PrintTo(const wchar_t* s, ::std::ostream* os); inline void PrintTo(wchar_t* s, ::std::ostream* os) { PrintTo(ImplicitCast_(s), os); } #endif // Overload for C arrays. Multi-dimensional arrays are printed // properly. // Prints the given number of elements in an array, without printing // the curly braces. template void PrintRawArrayTo(const T a[], size_t count, ::std::ostream* os) { UniversalPrint(a[0], os); for (size_t i = 1; i != count; i++) { *os << ", "; UniversalPrint(a[i], os); } } // Overloads for ::string and ::std::string. #if GTEST_HAS_GLOBAL_STRING GTEST_API_ void PrintStringTo(const ::string&s, ::std::ostream* os); inline void PrintTo(const ::string& s, ::std::ostream* os) { PrintStringTo(s, os); } #endif // GTEST_HAS_GLOBAL_STRING GTEST_API_ void PrintStringTo(const ::std::string&s, ::std::ostream* os); inline void PrintTo(const ::std::string& s, ::std::ostream* os) { PrintStringTo(s, os); } // Overloads for ::wstring and ::std::wstring. #if GTEST_HAS_GLOBAL_WSTRING GTEST_API_ void PrintWideStringTo(const ::wstring&s, ::std::ostream* os); inline void PrintTo(const ::wstring& s, ::std::ostream* os) { PrintWideStringTo(s, os); } #endif // GTEST_HAS_GLOBAL_WSTRING #if GTEST_HAS_STD_WSTRING GTEST_API_ void PrintWideStringTo(const ::std::wstring&s, ::std::ostream* os); inline void PrintTo(const ::std::wstring& s, ::std::ostream* os) { PrintWideStringTo(s, os); } #endif // GTEST_HAS_STD_WSTRING #if GTEST_HAS_TR1_TUPLE // Overload for ::std::tr1::tuple. Needed for printing function arguments, // which are packed as tuples. // Helper function for printing a tuple. T must be instantiated with // a tuple type. template void PrintTupleTo(const T& t, ::std::ostream* os); // Overloaded PrintTo() for tuples of various arities. We support // tuples of up-to 10 fields. The following implementation works // regardless of whether tr1::tuple is implemented using the // non-standard variadic template feature or not. inline void PrintTo(const ::std::tr1::tuple<>& t, ::std::ostream* os) { PrintTupleTo(t, os); } template void PrintTo(const ::std::tr1::tuple& t, ::std::ostream* os) { PrintTupleTo(t, os); } template void PrintTo(const ::std::tr1::tuple& t, ::std::ostream* os) { PrintTupleTo(t, os); } template void PrintTo(const ::std::tr1::tuple& t, ::std::ostream* os) { PrintTupleTo(t, os); } template void PrintTo(const ::std::tr1::tuple& t, ::std::ostream* os) { PrintTupleTo(t, os); } template void PrintTo(const ::std::tr1::tuple& t, ::std::ostream* os) { PrintTupleTo(t, os); } template void PrintTo(const ::std::tr1::tuple& t, ::std::ostream* os) { PrintTupleTo(t, os); } template void PrintTo(const ::std::tr1::tuple& t, ::std::ostream* os) { PrintTupleTo(t, os); } template void PrintTo(const ::std::tr1::tuple& t, ::std::ostream* os) { PrintTupleTo(t, os); } template void PrintTo(const ::std::tr1::tuple& t, ::std::ostream* os) { PrintTupleTo(t, os); } template void PrintTo( const ::std::tr1::tuple& t, ::std::ostream* os) { PrintTupleTo(t, os); } #endif // GTEST_HAS_TR1_TUPLE // Overload for std::pair. template void PrintTo(const ::std::pair& value, ::std::ostream* os) { *os << '('; // We cannot use UniversalPrint(value.first, os) here, as T1 may be // a reference type. The same for printing value.second. UniversalPrinter::Print(value.first, os); *os << ", "; UniversalPrinter::Print(value.second, os); *os << ')'; } // Implements printing a non-reference type T by letting the compiler // pick the right overload of PrintTo() for T. template class UniversalPrinter { public: // MSVC warns about adding const to a function type, so we want to // disable the warning. #ifdef _MSC_VER # pragma warning(push) // Saves the current warning state. # pragma warning(disable:4180) // Temporarily disables warning 4180. #endif // _MSC_VER // Note: we deliberately don't call this PrintTo(), as that name // conflicts with ::testing::internal::PrintTo in the body of the // function. static void Print(const T& value, ::std::ostream* os) { // By default, ::testing::internal::PrintTo() is used for printing // the value. // // Thanks to Koenig look-up, if T is a class and has its own // PrintTo() function defined in its namespace, that function will // be visible here. Since it is more specific than the generic ones // in ::testing::internal, it will be picked by the compiler in the // following statement - exactly what we want. PrintTo(value, os); } #ifdef _MSC_VER # pragma warning(pop) // Restores the warning state. #endif // _MSC_VER }; // UniversalPrintArray(begin, len, os) prints an array of 'len' // elements, starting at address 'begin'. template void UniversalPrintArray(const T* begin, size_t len, ::std::ostream* os) { if (len == 0) { *os << "{}"; } else { *os << "{ "; const size_t kThreshold = 18; const size_t kChunkSize = 8; // If the array has more than kThreshold elements, we'll have to // omit some details by printing only the first and the last // kChunkSize elements. // TODO(wan@google.com): let the user control the threshold using a flag. if (len <= kThreshold) { PrintRawArrayTo(begin, len, os); } else { PrintRawArrayTo(begin, kChunkSize, os); *os << ", ..., "; PrintRawArrayTo(begin + len - kChunkSize, kChunkSize, os); } *os << " }"; } } // This overload prints a (const) char array compactly. GTEST_API_ void UniversalPrintArray(const char* begin, size_t len, ::std::ostream* os); // Implements printing an array type T[N]. template class UniversalPrinter { public: // Prints the given array, omitting some elements when there are too // many. static void Print(const T (&a)[N], ::std::ostream* os) { UniversalPrintArray(a, N, os); } }; // Implements printing a reference type T&. template class UniversalPrinter { public: // MSVC warns about adding const to a function type, so we want to // disable the warning. #ifdef _MSC_VER # pragma warning(push) // Saves the current warning state. # pragma warning(disable:4180) // Temporarily disables warning 4180. #endif // _MSC_VER static void Print(const T& value, ::std::ostream* os) { // Prints the address of the value. We use reinterpret_cast here // as static_cast doesn't compile when T is a function type. *os << "@" << reinterpret_cast(&value) << " "; // Then prints the value itself. UniversalPrint(value, os); } #ifdef _MSC_VER # pragma warning(pop) // Restores the warning state. #endif // _MSC_VER }; // Prints a value tersely: for a reference type, the referenced value // (but not the address) is printed; for a (const) char pointer, the // NUL-terminated string (but not the pointer) is printed. template void UniversalTersePrint(const T& value, ::std::ostream* os) { UniversalPrint(value, os); } inline void UniversalTersePrint(const char* str, ::std::ostream* os) { if (str == NULL) { *os << "NULL"; } else { UniversalPrint(string(str), os); } } inline void UniversalTersePrint(char* str, ::std::ostream* os) { UniversalTersePrint(static_cast(str), os); } // Prints a value using the type inferred by the compiler. The // difference between this and UniversalTersePrint() is that for a // (const) char pointer, this prints both the pointer and the // NUL-terminated string. template void UniversalPrint(const T& value, ::std::ostream* os) { UniversalPrinter::Print(value, os); } #if GTEST_HAS_TR1_TUPLE typedef ::std::vector Strings; // This helper template allows PrintTo() for tuples and // UniversalTersePrintTupleFieldsToStrings() to be defined by // induction on the number of tuple fields. The idea is that // TuplePrefixPrinter::PrintPrefixTo(t, os) prints the first N // fields in tuple t, and can be defined in terms of // TuplePrefixPrinter. // The inductive case. template struct TuplePrefixPrinter { // Prints the first N fields of a tuple. template static void PrintPrefixTo(const Tuple& t, ::std::ostream* os) { TuplePrefixPrinter::PrintPrefixTo(t, os); *os << ", "; UniversalPrinter::type> ::Print(::std::tr1::get(t), os); } // Tersely prints the first N fields of a tuple to a string vector, // one element for each field. template static void TersePrintPrefixToStrings(const Tuple& t, Strings* strings) { TuplePrefixPrinter::TersePrintPrefixToStrings(t, strings); ::std::stringstream ss; UniversalTersePrint(::std::tr1::get(t), &ss); strings->push_back(ss.str()); } }; // Base cases. template <> struct TuplePrefixPrinter<0> { template static void PrintPrefixTo(const Tuple&, ::std::ostream*) {} template static void TersePrintPrefixToStrings(const Tuple&, Strings*) {} }; // We have to specialize the entire TuplePrefixPrinter<> class // template here, even though the definition of // TersePrintPrefixToStrings() is the same as the generic version, as // Embarcadero (formerly CodeGear, formerly Borland) C++ doesn't // support specializing a method template of a class template. template <> struct TuplePrefixPrinter<1> { template static void PrintPrefixTo(const Tuple& t, ::std::ostream* os) { UniversalPrinter::type>:: Print(::std::tr1::get<0>(t), os); } template static void TersePrintPrefixToStrings(const Tuple& t, Strings* strings) { ::std::stringstream ss; UniversalTersePrint(::std::tr1::get<0>(t), &ss); strings->push_back(ss.str()); } }; // Helper function for printing a tuple. T must be instantiated with // a tuple type. template void PrintTupleTo(const T& t, ::std::ostream* os) { *os << "("; TuplePrefixPrinter< ::std::tr1::tuple_size::value>:: PrintPrefixTo(t, os); *os << ")"; } // Prints the fields of a tuple tersely to a string vector, one // element for each field. See the comment before // UniversalTersePrint() for how we define "tersely". template Strings UniversalTersePrintTupleFieldsToStrings(const Tuple& value) { Strings result; TuplePrefixPrinter< ::std::tr1::tuple_size::value>:: TersePrintPrefixToStrings(value, &result); return result; } #endif // GTEST_HAS_TR1_TUPLE } // namespace internal template ::std::string PrintToString(const T& value) { ::std::stringstream ss; internal::UniversalTersePrint(value, &ss); return ss.str(); } } // namespace testing #endif // GTEST_INCLUDE_GTEST_GTEST_PRINTERS_H_ ugene-1.9.8/src/libs_3rdparty/gtest/src/gtest/gtest_prod.h0000644000175000017500000000442411651544307022262 0ustar ilyailya// Copyright 2006, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Author: wan@google.com (Zhanyong Wan) // // Google C++ Testing Framework definitions useful in production code. #ifndef GTEST_INCLUDE_GTEST_GTEST_PROD_H_ #define GTEST_INCLUDE_GTEST_GTEST_PROD_H_ // When you need to test the private or protected members of a class, // use the FRIEND_TEST macro to declare your tests as friends of the // class. For example: // // class MyClass { // private: // void MyMethod(); // FRIEND_TEST(MyClassTest, MyMethod); // }; // // class MyClassTest : public testing::Test { // // ... // }; // // TEST_F(MyClassTest, MyMethod) { // // Can call MyClass::MyMethod() here. // } #define FRIEND_TEST(test_case_name, test_name)\ friend class test_case_name##_##test_name##_Test #endif // GTEST_INCLUDE_GTEST_GTEST_PROD_H_ ugene-1.9.8/src/libs_3rdparty/gtest/src/gtest/gtest-death-test.h0000644000175000017500000002554511651544307023305 0ustar ilyailya// Copyright 2005, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Author: wan@google.com (Zhanyong Wan) // // The Google C++ Testing Framework (Google Test) // // This header file defines the public API for death tests. It is // #included by gtest.h so a user doesn't need to include this // directly. #ifndef GTEST_INCLUDE_GTEST_GTEST_DEATH_TEST_H_ #define GTEST_INCLUDE_GTEST_GTEST_DEATH_TEST_H_ #include "gtest/internal/gtest-death-test-internal.h" namespace testing { // This flag controls the style of death tests. Valid values are "threadsafe", // meaning that the death test child process will re-execute the test binary // from the start, running only a single death test, or "fast", // meaning that the child process will execute the test logic immediately // after forking. GTEST_DECLARE_string_(death_test_style); #if GTEST_HAS_DEATH_TEST // The following macros are useful for writing death tests. // Here's what happens when an ASSERT_DEATH* or EXPECT_DEATH* is // executed: // // 1. It generates a warning if there is more than one active // thread. This is because it's safe to fork() or clone() only // when there is a single thread. // // 2. The parent process clone()s a sub-process and runs the death // test in it; the sub-process exits with code 0 at the end of the // death test, if it hasn't exited already. // // 3. The parent process waits for the sub-process to terminate. // // 4. The parent process checks the exit code and error message of // the sub-process. // // Examples: // // ASSERT_DEATH(server.SendMessage(56, "Hello"), "Invalid port number"); // for (int i = 0; i < 5; i++) { // EXPECT_DEATH(server.ProcessRequest(i), // "Invalid request .* in ProcessRequest()") // << "Failed to die on request " << i); // } // // ASSERT_EXIT(server.ExitNow(), ::testing::ExitedWithCode(0), "Exiting"); // // bool KilledBySIGHUP(int exit_code) { // return WIFSIGNALED(exit_code) && WTERMSIG(exit_code) == SIGHUP; // } // // ASSERT_EXIT(client.HangUpServer(), KilledBySIGHUP, "Hanging up!"); // // On the regular expressions used in death tests: // // On POSIX-compliant systems (*nix), we use the library, // which uses the POSIX extended regex syntax. // // On other platforms (e.g. Windows), we only support a simple regex // syntax implemented as part of Google Test. This limited // implementation should be enough most of the time when writing // death tests; though it lacks many features you can find in PCRE // or POSIX extended regex syntax. For example, we don't support // union ("x|y"), grouping ("(xy)"), brackets ("[xy]"), and // repetition count ("x{5,7}"), among others. // // Below is the syntax that we do support. We chose it to be a // subset of both PCRE and POSIX extended regex, so it's easy to // learn wherever you come from. In the following: 'A' denotes a // literal character, period (.), or a single \\ escape sequence; // 'x' and 'y' denote regular expressions; 'm' and 'n' are for // natural numbers. // // c matches any literal character c // \\d matches any decimal digit // \\D matches any character that's not a decimal digit // \\f matches \f // \\n matches \n // \\r matches \r // \\s matches any ASCII whitespace, including \n // \\S matches any character that's not a whitespace // \\t matches \t // \\v matches \v // \\w matches any letter, _, or decimal digit // \\W matches any character that \\w doesn't match // \\c matches any literal character c, which must be a punctuation // . matches any single character except \n // A? matches 0 or 1 occurrences of A // A* matches 0 or many occurrences of A // A+ matches 1 or many occurrences of A // ^ matches the beginning of a string (not that of each line) // $ matches the end of a string (not that of each line) // xy matches x followed by y // // If you accidentally use PCRE or POSIX extended regex features // not implemented by us, you will get a run-time failure. In that // case, please try to rewrite your regular expression within the // above syntax. // // This implementation is *not* meant to be as highly tuned or robust // as a compiled regex library, but should perform well enough for a // death test, which already incurs significant overhead by launching // a child process. // // Known caveats: // // A "threadsafe" style death test obtains the path to the test // program from argv[0] and re-executes it in the sub-process. For // simplicity, the current implementation doesn't search the PATH // when launching the sub-process. This means that the user must // invoke the test program via a path that contains at least one // path separator (e.g. path/to/foo_test and // /absolute/path/to/bar_test are fine, but foo_test is not). This // is rarely a problem as people usually don't put the test binary // directory in PATH. // // TODO(wan@google.com): make thread-safe death tests search the PATH. // Asserts that a given statement causes the program to exit, with an // integer exit status that satisfies predicate, and emitting error output // that matches regex. # define ASSERT_EXIT(statement, predicate, regex) \ GTEST_DEATH_TEST_(statement, predicate, regex, GTEST_FATAL_FAILURE_) // Like ASSERT_EXIT, but continues on to successive tests in the // test case, if any: # define EXPECT_EXIT(statement, predicate, regex) \ GTEST_DEATH_TEST_(statement, predicate, regex, GTEST_NONFATAL_FAILURE_) // Asserts that a given statement causes the program to exit, either by // explicitly exiting with a nonzero exit code or being killed by a // signal, and emitting error output that matches regex. # define ASSERT_DEATH(statement, regex) \ ASSERT_EXIT(statement, ::testing::internal::ExitedUnsuccessfully, regex) // Like ASSERT_DEATH, but continues on to successive tests in the // test case, if any: # define EXPECT_DEATH(statement, regex) \ EXPECT_EXIT(statement, ::testing::internal::ExitedUnsuccessfully, regex) // Two predicate classes that can be used in {ASSERT,EXPECT}_EXIT*: // Tests that an exit code describes a normal exit with a given exit code. class GTEST_API_ ExitedWithCode { public: explicit ExitedWithCode(int exit_code); bool operator()(int exit_status) const; private: // No implementation - assignment is unsupported. void operator=(const ExitedWithCode& other); const int exit_code_; }; # if !GTEST_OS_WINDOWS // Tests that an exit code describes an exit due to termination by a // given signal. class GTEST_API_ KilledBySignal { public: explicit KilledBySignal(int signum); bool operator()(int exit_status) const; private: const int signum_; }; # endif // !GTEST_OS_WINDOWS // EXPECT_DEBUG_DEATH asserts that the given statements die in debug mode. // The death testing framework causes this to have interesting semantics, // since the sideeffects of the call are only visible in opt mode, and not // in debug mode. // // In practice, this can be used to test functions that utilize the // LOG(DFATAL) macro using the following style: // // int DieInDebugOr12(int* sideeffect) { // if (sideeffect) { // *sideeffect = 12; // } // LOG(DFATAL) << "death"; // return 12; // } // // TEST(TestCase, TestDieOr12WorksInDgbAndOpt) { // int sideeffect = 0; // // Only asserts in dbg. // EXPECT_DEBUG_DEATH(DieInDebugOr12(&sideeffect), "death"); // // #ifdef NDEBUG // // opt-mode has sideeffect visible. // EXPECT_EQ(12, sideeffect); // #else // // dbg-mode no visible sideeffect. // EXPECT_EQ(0, sideeffect); // #endif // } // // This will assert that DieInDebugReturn12InOpt() crashes in debug // mode, usually due to a DCHECK or LOG(DFATAL), but returns the // appropriate fallback value (12 in this case) in opt mode. If you // need to test that a function has appropriate side-effects in opt // mode, include assertions against the side-effects. A general // pattern for this is: // // EXPECT_DEBUG_DEATH({ // // Side-effects here will have an effect after this statement in // // opt mode, but none in debug mode. // EXPECT_EQ(12, DieInDebugOr12(&sideeffect)); // }, "death"); // # ifdef NDEBUG # define EXPECT_DEBUG_DEATH(statement, regex) \ do { statement; } while (::testing::internal::AlwaysFalse()) # define ASSERT_DEBUG_DEATH(statement, regex) \ do { statement; } while (::testing::internal::AlwaysFalse()) # else # define EXPECT_DEBUG_DEATH(statement, regex) \ EXPECT_DEATH(statement, regex) # define ASSERT_DEBUG_DEATH(statement, regex) \ ASSERT_DEATH(statement, regex) # endif // NDEBUG for EXPECT_DEBUG_DEATH #endif // GTEST_HAS_DEATH_TEST // EXPECT_DEATH_IF_SUPPORTED(statement, regex) and // ASSERT_DEATH_IF_SUPPORTED(statement, regex) expand to real death tests if // death tests are supported; otherwise they just issue a warning. This is // useful when you are combining death test assertions with normal test // assertions in one test. #if GTEST_HAS_DEATH_TEST # define EXPECT_DEATH_IF_SUPPORTED(statement, regex) \ EXPECT_DEATH(statement, regex) # define ASSERT_DEATH_IF_SUPPORTED(statement, regex) \ ASSERT_DEATH(statement, regex) #else # define EXPECT_DEATH_IF_SUPPORTED(statement, regex) \ GTEST_UNSUPPORTED_DEATH_TEST_(statement, regex, ) # define ASSERT_DEATH_IF_SUPPORTED(statement, regex) \ GTEST_UNSUPPORTED_DEATH_TEST_(statement, regex, return) #endif } // namespace testing #endif // GTEST_INCLUDE_GTEST_GTEST_DEATH_TEST_H_ ugene-1.9.8/src/libs_3rdparty/gtest/src/src/0000755000175000017500000000000011651544307017374 5ustar ilyailyaugene-1.9.8/src/libs_3rdparty/gtest/src/src/gtest-test-part.cc0000644000175000017500000001014511651544307022753 0ustar ilyailya// Copyright 2008, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Author: mheule@google.com (Markus Heule) // // The Google C++ Testing Framework (Google Test) #include "gtest/gtest-test-part.h" // Indicates that this translation unit is part of Google Test's // implementation. It must come before gtest-internal-inl.h is // included, or there will be a compiler error. This trick is to // prevent a user from accidentally including gtest-internal-inl.h in // his code. #define GTEST_IMPLEMENTATION_ 1 #include "src/gtest-internal-inl.h" #undef GTEST_IMPLEMENTATION_ namespace testing { using internal::GetUnitTestImpl; // Gets the summary of the failure message by omitting the stack trace // in it. internal::String TestPartResult::ExtractSummary(const char* message) { const char* const stack_trace = strstr(message, internal::kStackTraceMarker); return stack_trace == NULL ? internal::String(message) : internal::String(message, stack_trace - message); } // Prints a TestPartResult object. std::ostream& operator<<(std::ostream& os, const TestPartResult& result) { return os << result.file_name() << ":" << result.line_number() << ": " << (result.type() == TestPartResult::kSuccess ? "Success" : result.type() == TestPartResult::kFatalFailure ? "Fatal failure" : "Non-fatal failure") << ":\n" << result.message() << std::endl; } // Appends a TestPartResult to the array. void TestPartResultArray::Append(const TestPartResult& result) { array_.push_back(result); } // Returns the TestPartResult at the given index (0-based). const TestPartResult& TestPartResultArray::GetTestPartResult(int index) const { if (index < 0 || index >= size()) { printf("\nInvalid index (%d) into TestPartResultArray.\n", index); internal::posix::Abort(); } return array_[index]; } // Returns the number of TestPartResult objects in the array. int TestPartResultArray::size() const { return static_cast(array_.size()); } namespace internal { HasNewFatalFailureHelper::HasNewFatalFailureHelper() : has_new_fatal_failure_(false), original_reporter_(GetUnitTestImpl()-> GetTestPartResultReporterForCurrentThread()) { GetUnitTestImpl()->SetTestPartResultReporterForCurrentThread(this); } HasNewFatalFailureHelper::~HasNewFatalFailureHelper() { GetUnitTestImpl()->SetTestPartResultReporterForCurrentThread( original_reporter_); } void HasNewFatalFailureHelper::ReportTestPartResult( const TestPartResult& result) { if (result.fatally_failed()) has_new_fatal_failure_ = true; original_reporter_->ReportTestPartResult(result); } } // namespace internal } // namespace testing ugene-1.9.8/src/libs_3rdparty/gtest/src/src/gtest-port.cc0000644000175000017500000006135011651544307022020 0ustar ilyailya// Copyright 2008, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Author: wan@google.com (Zhanyong Wan) #include "gtest/internal/gtest-port.h" #include #include #include #include #if GTEST_OS_WINDOWS_MOBILE # include // For TerminateProcess() #elif GTEST_OS_WINDOWS # include # include #else # include #endif // GTEST_OS_WINDOWS_MOBILE #if GTEST_OS_MAC # include # include # include #endif // GTEST_OS_MAC #include "gtest/gtest-spi.h" #include "gtest/gtest-message.h" #include "gtest/internal/gtest-internal.h" #include "gtest/internal/gtest-string.h" // Indicates that this translation unit is part of Google Test's // implementation. It must come before gtest-internal-inl.h is // included, or there will be a compiler error. This trick is to // prevent a user from accidentally including gtest-internal-inl.h in // his code. #define GTEST_IMPLEMENTATION_ 1 #include "src/gtest-internal-inl.h" #undef GTEST_IMPLEMENTATION_ namespace testing { namespace internal { #if defined(_MSC_VER) || defined(__BORLANDC__) // MSVC and C++Builder do not provide a definition of STDERR_FILENO. const int kStdOutFileno = 1; const int kStdErrFileno = 2; #else const int kStdOutFileno = STDOUT_FILENO; const int kStdErrFileno = STDERR_FILENO; #endif // _MSC_VER #if GTEST_OS_MAC // Returns the number of threads running in the process, or 0 to indicate that // we cannot detect it. size_t GetThreadCount() { const task_t task = mach_task_self(); mach_msg_type_number_t thread_count; thread_act_array_t thread_list; const kern_return_t status = task_threads(task, &thread_list, &thread_count); if (status == KERN_SUCCESS) { // task_threads allocates resources in thread_list and we need to free them // to avoid leaks. vm_deallocate(task, reinterpret_cast(thread_list), sizeof(thread_t) * thread_count); return static_cast(thread_count); } else { return 0; } } #else size_t GetThreadCount() { // There's no portable way to detect the number of threads, so we just // return 0 to indicate that we cannot detect it. return 0; } #endif // GTEST_OS_MAC #if GTEST_USES_POSIX_RE // Implements RE. Currently only needed for death tests. RE::~RE() { if (is_valid_) { // regfree'ing an invalid regex might crash because the content // of the regex is undefined. Since the regex's are essentially // the same, one cannot be valid (or invalid) without the other // being so too. regfree(&partial_regex_); regfree(&full_regex_); } free(const_cast(pattern_)); } // Returns true iff regular expression re matches the entire str. bool RE::FullMatch(const char* str, const RE& re) { if (!re.is_valid_) return false; regmatch_t match; return regexec(&re.full_regex_, str, 1, &match, 0) == 0; } // Returns true iff regular expression re matches a substring of str // (including str itself). bool RE::PartialMatch(const char* str, const RE& re) { if (!re.is_valid_) return false; regmatch_t match; return regexec(&re.partial_regex_, str, 1, &match, 0) == 0; } // Initializes an RE from its string representation. void RE::Init(const char* regex) { pattern_ = posix::StrDup(regex); // Reserves enough bytes to hold the regular expression used for a // full match. const size_t full_regex_len = strlen(regex) + 10; char* const full_pattern = new char[full_regex_len]; snprintf(full_pattern, full_regex_len, "^(%s)$", regex); is_valid_ = regcomp(&full_regex_, full_pattern, REG_EXTENDED) == 0; // We want to call regcomp(&partial_regex_, ...) even if the // previous expression returns false. Otherwise partial_regex_ may // not be properly initialized can may cause trouble when it's // freed. // // Some implementation of POSIX regex (e.g. on at least some // versions of Cygwin) doesn't accept the empty string as a valid // regex. We change it to an equivalent form "()" to be safe. if (is_valid_) { const char* const partial_regex = (*regex == '\0') ? "()" : regex; is_valid_ = regcomp(&partial_regex_, partial_regex, REG_EXTENDED) == 0; } EXPECT_TRUE(is_valid_) << "Regular expression \"" << regex << "\" is not a valid POSIX Extended regular expression."; delete[] full_pattern; } #elif GTEST_USES_SIMPLE_RE // Returns true iff ch appears anywhere in str (excluding the // terminating '\0' character). bool IsInSet(char ch, const char* str) { return ch != '\0' && strchr(str, ch) != NULL; } // Returns true iff ch belongs to the given classification. Unlike // similar functions in , these aren't affected by the // current locale. bool IsAsciiDigit(char ch) { return '0' <= ch && ch <= '9'; } bool IsAsciiPunct(char ch) { return IsInSet(ch, "^-!\"#$%&'()*+,./:;<=>?@[\\]_`{|}~"); } bool IsRepeat(char ch) { return IsInSet(ch, "?*+"); } bool IsAsciiWhiteSpace(char ch) { return IsInSet(ch, " \f\n\r\t\v"); } bool IsAsciiWordChar(char ch) { return ('a' <= ch && ch <= 'z') || ('A' <= ch && ch <= 'Z') || ('0' <= ch && ch <= '9') || ch == '_'; } // Returns true iff "\\c" is a supported escape sequence. bool IsValidEscape(char c) { return (IsAsciiPunct(c) || IsInSet(c, "dDfnrsStvwW")); } // Returns true iff the given atom (specified by escaped and pattern) // matches ch. The result is undefined if the atom is invalid. bool AtomMatchesChar(bool escaped, char pattern_char, char ch) { if (escaped) { // "\\p" where p is pattern_char. switch (pattern_char) { case 'd': return IsAsciiDigit(ch); case 'D': return !IsAsciiDigit(ch); case 'f': return ch == '\f'; case 'n': return ch == '\n'; case 'r': return ch == '\r'; case 's': return IsAsciiWhiteSpace(ch); case 'S': return !IsAsciiWhiteSpace(ch); case 't': return ch == '\t'; case 'v': return ch == '\v'; case 'w': return IsAsciiWordChar(ch); case 'W': return !IsAsciiWordChar(ch); } return IsAsciiPunct(pattern_char) && pattern_char == ch; } return (pattern_char == '.' && ch != '\n') || pattern_char == ch; } // Helper function used by ValidateRegex() to format error messages. String FormatRegexSyntaxError(const char* regex, int index) { return (Message() << "Syntax error at index " << index << " in simple regular expression \"" << regex << "\": ").GetString(); } // Generates non-fatal failures and returns false if regex is invalid; // otherwise returns true. bool ValidateRegex(const char* regex) { if (regex == NULL) { // TODO(wan@google.com): fix the source file location in the // assertion failures to match where the regex is used in user // code. ADD_FAILURE() << "NULL is not a valid simple regular expression."; return false; } bool is_valid = true; // True iff ?, *, or + can follow the previous atom. bool prev_repeatable = false; for (int i = 0; regex[i]; i++) { if (regex[i] == '\\') { // An escape sequence i++; if (regex[i] == '\0') { ADD_FAILURE() << FormatRegexSyntaxError(regex, i - 1) << "'\\' cannot appear at the end."; return false; } if (!IsValidEscape(regex[i])) { ADD_FAILURE() << FormatRegexSyntaxError(regex, i - 1) << "invalid escape sequence \"\\" << regex[i] << "\"."; is_valid = false; } prev_repeatable = true; } else { // Not an escape sequence. const char ch = regex[i]; if (ch == '^' && i > 0) { ADD_FAILURE() << FormatRegexSyntaxError(regex, i) << "'^' can only appear at the beginning."; is_valid = false; } else if (ch == '$' && regex[i + 1] != '\0') { ADD_FAILURE() << FormatRegexSyntaxError(regex, i) << "'$' can only appear at the end."; is_valid = false; } else if (IsInSet(ch, "()[]{}|")) { ADD_FAILURE() << FormatRegexSyntaxError(regex, i) << "'" << ch << "' is unsupported."; is_valid = false; } else if (IsRepeat(ch) && !prev_repeatable) { ADD_FAILURE() << FormatRegexSyntaxError(regex, i) << "'" << ch << "' can only follow a repeatable token."; is_valid = false; } prev_repeatable = !IsInSet(ch, "^$?*+"); } } return is_valid; } // Matches a repeated regex atom followed by a valid simple regular // expression. The regex atom is defined as c if escaped is false, // or \c otherwise. repeat is the repetition meta character (?, *, // or +). The behavior is undefined if str contains too many // characters to be indexable by size_t, in which case the test will // probably time out anyway. We are fine with this limitation as // std::string has it too. bool MatchRepetitionAndRegexAtHead( bool escaped, char c, char repeat, const char* regex, const char* str) { const size_t min_count = (repeat == '+') ? 1 : 0; const size_t max_count = (repeat == '?') ? 1 : static_cast(-1) - 1; // We cannot call numeric_limits::max() as it conflicts with the // max() macro on Windows. for (size_t i = 0; i <= max_count; ++i) { // We know that the atom matches each of the first i characters in str. if (i >= min_count && MatchRegexAtHead(regex, str + i)) { // We have enough matches at the head, and the tail matches too. // Since we only care about *whether* the pattern matches str // (as opposed to *how* it matches), there is no need to find a // greedy match. return true; } if (str[i] == '\0' || !AtomMatchesChar(escaped, c, str[i])) return false; } return false; } // Returns true iff regex matches a prefix of str. regex must be a // valid simple regular expression and not start with "^", or the // result is undefined. bool MatchRegexAtHead(const char* regex, const char* str) { if (*regex == '\0') // An empty regex matches a prefix of anything. return true; // "$" only matches the end of a string. Note that regex being // valid guarantees that there's nothing after "$" in it. if (*regex == '$') return *str == '\0'; // Is the first thing in regex an escape sequence? const bool escaped = *regex == '\\'; if (escaped) ++regex; if (IsRepeat(regex[1])) { // MatchRepetitionAndRegexAtHead() calls MatchRegexAtHead(), so // here's an indirect recursion. It terminates as the regex gets // shorter in each recursion. return MatchRepetitionAndRegexAtHead( escaped, regex[0], regex[1], regex + 2, str); } else { // regex isn't empty, isn't "$", and doesn't start with a // repetition. We match the first atom of regex with the first // character of str and recurse. return (*str != '\0') && AtomMatchesChar(escaped, *regex, *str) && MatchRegexAtHead(regex + 1, str + 1); } } // Returns true iff regex matches any substring of str. regex must be // a valid simple regular expression, or the result is undefined. // // The algorithm is recursive, but the recursion depth doesn't exceed // the regex length, so we won't need to worry about running out of // stack space normally. In rare cases the time complexity can be // exponential with respect to the regex length + the string length, // but usually it's must faster (often close to linear). bool MatchRegexAnywhere(const char* regex, const char* str) { if (regex == NULL || str == NULL) return false; if (*regex == '^') return MatchRegexAtHead(regex + 1, str); // A successful match can be anywhere in str. do { if (MatchRegexAtHead(regex, str)) return true; } while (*str++ != '\0'); return false; } // Implements the RE class. RE::~RE() { free(const_cast(pattern_)); free(const_cast(full_pattern_)); } // Returns true iff regular expression re matches the entire str. bool RE::FullMatch(const char* str, const RE& re) { return re.is_valid_ && MatchRegexAnywhere(re.full_pattern_, str); } // Returns true iff regular expression re matches a substring of str // (including str itself). bool RE::PartialMatch(const char* str, const RE& re) { return re.is_valid_ && MatchRegexAnywhere(re.pattern_, str); } // Initializes an RE from its string representation. void RE::Init(const char* regex) { pattern_ = full_pattern_ = NULL; if (regex != NULL) { pattern_ = posix::StrDup(regex); } is_valid_ = ValidateRegex(regex); if (!is_valid_) { // No need to calculate the full pattern when the regex is invalid. return; } const size_t len = strlen(regex); // Reserves enough bytes to hold the regular expression used for a // full match: we need space to prepend a '^', append a '$', and // terminate the string with '\0'. char* buffer = static_cast(malloc(len + 3)); full_pattern_ = buffer; if (*regex != '^') *buffer++ = '^'; // Makes sure full_pattern_ starts with '^'. // We don't use snprintf or strncpy, as they trigger a warning when // compiled with VC++ 8.0. memcpy(buffer, regex, len); buffer += len; if (len == 0 || regex[len - 1] != '$') *buffer++ = '$'; // Makes sure full_pattern_ ends with '$'. *buffer = '\0'; } #endif // GTEST_USES_POSIX_RE const char kUnknownFile[] = "unknown file"; // Formats a source file path and a line number as they would appear // in an error message from the compiler used to compile this code. GTEST_API_ ::std::string FormatFileLocation(const char* file, int line) { const char* const file_name = file == NULL ? kUnknownFile : file; if (line < 0) { return String::Format("%s:", file_name).c_str(); } #ifdef _MSC_VER return String::Format("%s(%d):", file_name, line).c_str(); #else return String::Format("%s:%d:", file_name, line).c_str(); #endif // _MSC_VER } // Formats a file location for compiler-independent XML output. // Although this function is not platform dependent, we put it next to // FormatFileLocation in order to contrast the two functions. // Note that FormatCompilerIndependentFileLocation() does NOT append colon // to the file location it produces, unlike FormatFileLocation(). GTEST_API_ ::std::string FormatCompilerIndependentFileLocation( const char* file, int line) { const char* const file_name = file == NULL ? kUnknownFile : file; if (line < 0) return file_name; else return String::Format("%s:%d", file_name, line).c_str(); } GTestLog::GTestLog(GTestLogSeverity severity, const char* file, int line) : severity_(severity) { const char* const marker = severity == GTEST_INFO ? "[ INFO ]" : severity == GTEST_WARNING ? "[WARNING]" : severity == GTEST_ERROR ? "[ ERROR ]" : "[ FATAL ]"; GetStream() << ::std::endl << marker << " " << FormatFileLocation(file, line).c_str() << ": "; } // Flushes the buffers and, if severity is GTEST_FATAL, aborts the program. GTestLog::~GTestLog() { GetStream() << ::std::endl; if (severity_ == GTEST_FATAL) { fflush(stderr); posix::Abort(); } } // Disable Microsoft deprecation warnings for POSIX functions called from // this class (creat, dup, dup2, and close) #ifdef _MSC_VER # pragma warning(push) # pragma warning(disable: 4996) #endif // _MSC_VER #if GTEST_HAS_STREAM_REDIRECTION // Object that captures an output stream (stdout/stderr). class CapturedStream { public: // The ctor redirects the stream to a temporary file. CapturedStream(int fd) : fd_(fd), uncaptured_fd_(dup(fd)) { # if GTEST_OS_WINDOWS char temp_dir_path[MAX_PATH + 1] = { '\0' }; // NOLINT char temp_file_path[MAX_PATH + 1] = { '\0' }; // NOLINT ::GetTempPathA(sizeof(temp_dir_path), temp_dir_path); const UINT success = ::GetTempFileNameA(temp_dir_path, "gtest_redir", 0, // Generate unique file name. temp_file_path); GTEST_CHECK_(success != 0) << "Unable to create a temporary file in " << temp_dir_path; const int captured_fd = creat(temp_file_path, _S_IREAD | _S_IWRITE); GTEST_CHECK_(captured_fd != -1) << "Unable to open temporary file " << temp_file_path; filename_ = temp_file_path; # else // There's no guarantee that a test has write access to the // current directory, so we create the temporary file in the /tmp // directory instead. char name_template[] = "/tmp/captured_stream.XXXXXX"; const int captured_fd = mkstemp(name_template); filename_ = name_template; # endif // GTEST_OS_WINDOWS fflush(NULL); dup2(captured_fd, fd_); close(captured_fd); } ~CapturedStream() { remove(filename_.c_str()); } String GetCapturedString() { if (uncaptured_fd_ != -1) { // Restores the original stream. fflush(NULL); dup2(uncaptured_fd_, fd_); close(uncaptured_fd_); uncaptured_fd_ = -1; } FILE* const file = posix::FOpen(filename_.c_str(), "r"); const String content = ReadEntireFile(file); posix::FClose(file); return content; } private: // Reads the entire content of a file as a String. static String ReadEntireFile(FILE* file); // Returns the size (in bytes) of a file. static size_t GetFileSize(FILE* file); const int fd_; // A stream to capture. int uncaptured_fd_; // Name of the temporary file holding the stderr output. ::std::string filename_; GTEST_DISALLOW_COPY_AND_ASSIGN_(CapturedStream); }; // Returns the size (in bytes) of a file. size_t CapturedStream::GetFileSize(FILE* file) { fseek(file, 0, SEEK_END); return static_cast(ftell(file)); } // Reads the entire content of a file as a string. String CapturedStream::ReadEntireFile(FILE* file) { const size_t file_size = GetFileSize(file); char* const buffer = new char[file_size]; size_t bytes_last_read = 0; // # of bytes read in the last fread() size_t bytes_read = 0; // # of bytes read so far fseek(file, 0, SEEK_SET); // Keeps reading the file until we cannot read further or the // pre-determined file size is reached. do { bytes_last_read = fread(buffer+bytes_read, 1, file_size-bytes_read, file); bytes_read += bytes_last_read; } while (bytes_last_read > 0 && bytes_read < file_size); const String content(buffer, bytes_read); delete[] buffer; return content; } # ifdef _MSC_VER # pragma warning(pop) # endif // _MSC_VER static CapturedStream* g_captured_stderr = NULL; static CapturedStream* g_captured_stdout = NULL; // Starts capturing an output stream (stdout/stderr). void CaptureStream(int fd, const char* stream_name, CapturedStream** stream) { if (*stream != NULL) { GTEST_LOG_(FATAL) << "Only one " << stream_name << " capturer can exist at a time."; } *stream = new CapturedStream(fd); } // Stops capturing the output stream and returns the captured string. String GetCapturedStream(CapturedStream** captured_stream) { const String content = (*captured_stream)->GetCapturedString(); delete *captured_stream; *captured_stream = NULL; return content; } // Starts capturing stdout. void CaptureStdout() { CaptureStream(kStdOutFileno, "stdout", &g_captured_stdout); } // Starts capturing stderr. void CaptureStderr() { CaptureStream(kStdErrFileno, "stderr", &g_captured_stderr); } // Stops capturing stdout and returns the captured string. String GetCapturedStdout() { return GetCapturedStream(&g_captured_stdout); } // Stops capturing stderr and returns the captured string. String GetCapturedStderr() { return GetCapturedStream(&g_captured_stderr); } #endif // GTEST_HAS_STREAM_REDIRECTION #if GTEST_HAS_DEATH_TEST // A copy of all command line arguments. Set by InitGoogleTest(). ::std::vector g_argvs; // Returns the command line as a vector of strings. const ::std::vector& GetArgvs() { return g_argvs; } #endif // GTEST_HAS_DEATH_TEST #if GTEST_OS_WINDOWS_MOBILE namespace posix { void Abort() { DebugBreak(); TerminateProcess(GetCurrentProcess(), 1); } } // namespace posix #endif // GTEST_OS_WINDOWS_MOBILE // Returns the name of the environment variable corresponding to the // given flag. For example, FlagToEnvVar("foo") will return // "GTEST_FOO" in the open-source version. static String FlagToEnvVar(const char* flag) { const String full_flag = (Message() << GTEST_FLAG_PREFIX_ << flag).GetString(); Message env_var; for (size_t i = 0; i != full_flag.length(); i++) { env_var << ToUpper(full_flag.c_str()[i]); } return env_var.GetString(); } // Parses 'str' for a 32-bit signed integer. If successful, writes // the result to *value and returns true; otherwise leaves *value // unchanged and returns false. bool ParseInt32(const Message& src_text, const char* str, Int32* value) { // Parses the environment variable as a decimal integer. char* end = NULL; const long long_value = strtol(str, &end, 10); // NOLINT // Has strtol() consumed all characters in the string? if (*end != '\0') { // No - an invalid character was encountered. Message msg; msg << "WARNING: " << src_text << " is expected to be a 32-bit integer, but actually" << " has value \"" << str << "\".\n"; printf("%s", msg.GetString().c_str()); fflush(stdout); return false; } // Is the parsed value in the range of an Int32? const Int32 result = static_cast(long_value); if (long_value == LONG_MAX || long_value == LONG_MIN || // The parsed value overflows as a long. (strtol() returns // LONG_MAX or LONG_MIN when the input overflows.) result != long_value // The parsed value overflows as an Int32. ) { Message msg; msg << "WARNING: " << src_text << " is expected to be a 32-bit integer, but actually" << " has value " << str << ", which overflows.\n"; printf("%s", msg.GetString().c_str()); fflush(stdout); return false; } *value = result; return true; } // Reads and returns the Boolean environment variable corresponding to // the given flag; if it's not set, returns default_value. // // The value is considered true iff it's not "0". bool BoolFromGTestEnv(const char* flag, bool default_value) { const String env_var = FlagToEnvVar(flag); const char* const string_value = posix::GetEnv(env_var.c_str()); return string_value == NULL ? default_value : strcmp(string_value, "0") != 0; } // Reads and returns a 32-bit integer stored in the environment // variable corresponding to the given flag; if it isn't set or // doesn't represent a valid 32-bit integer, returns default_value. Int32 Int32FromGTestEnv(const char* flag, Int32 default_value) { const String env_var = FlagToEnvVar(flag); const char* const string_value = posix::GetEnv(env_var.c_str()); if (string_value == NULL) { // The environment variable is not set. return default_value; } Int32 result = default_value; if (!ParseInt32(Message() << "Environment variable " << env_var, string_value, &result)) { printf("The default value %s is used.\n", (Message() << default_value).GetString().c_str()); fflush(stdout); return default_value; } return result; } // Reads and returns the string environment variable corresponding to // the given flag; if it's not set, returns default_value. const char* StringFromGTestEnv(const char* flag, const char* default_value) { const String env_var = FlagToEnvVar(flag); const char* const value = posix::GetEnv(env_var.c_str()); return value == NULL ? default_value : value; } } // namespace internal } // namespace testing ugene-1.9.8/src/libs_3rdparty/gtest/src/src/gtest-printers.cc0000644000175000017500000002741211651544307022703 0ustar ilyailya// Copyright 2007, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Author: wan@google.com (Zhanyong Wan) // Google Test - The Google C++ Testing Framework // // This file implements a universal value printer that can print a // value of any type T: // // void ::testing::internal::UniversalPrinter::Print(value, ostream_ptr); // // It uses the << operator when possible, and prints the bytes in the // object otherwise. A user can override its behavior for a class // type Foo by defining either operator<<(::std::ostream&, const Foo&) // or void PrintTo(const Foo&, ::std::ostream*) in the namespace that // defines Foo. #include "gtest/gtest-printers.h" #include #include #include // NOLINT #include #include "gtest/internal/gtest-port.h" namespace testing { namespace { using ::std::ostream; #if GTEST_OS_WINDOWS_MOBILE // Windows CE does not define _snprintf_s. # define snprintf _snprintf #elif _MSC_VER >= 1400 // VC 8.0 and later deprecate snprintf and _snprintf. # define snprintf _snprintf_s #elif _MSC_VER # define snprintf _snprintf #endif // GTEST_OS_WINDOWS_MOBILE // Prints a segment of bytes in the given object. void PrintByteSegmentInObjectTo(const unsigned char* obj_bytes, size_t start, size_t count, ostream* os) { char text[5] = ""; for (size_t i = 0; i != count; i++) { const size_t j = start + i; if (i != 0) { // Organizes the bytes into groups of 2 for easy parsing by // human. if ((j % 2) == 0) *os << ' '; else *os << '-'; } snprintf(text, sizeof(text), "%02X", obj_bytes[j]); *os << text; } } // Prints the bytes in the given value to the given ostream. void PrintBytesInObjectToImpl(const unsigned char* obj_bytes, size_t count, ostream* os) { // Tells the user how big the object is. *os << count << "-byte object <"; const size_t kThreshold = 132; const size_t kChunkSize = 64; // If the object size is bigger than kThreshold, we'll have to omit // some details by printing only the first and the last kChunkSize // bytes. // TODO(wan): let the user control the threshold using a flag. if (count < kThreshold) { PrintByteSegmentInObjectTo(obj_bytes, 0, count, os); } else { PrintByteSegmentInObjectTo(obj_bytes, 0, kChunkSize, os); *os << " ... "; // Rounds up to 2-byte boundary. const size_t resume_pos = (count - kChunkSize + 1)/2*2; PrintByteSegmentInObjectTo(obj_bytes, resume_pos, count - resume_pos, os); } *os << ">"; } } // namespace namespace internal2 { // Delegates to PrintBytesInObjectToImpl() to print the bytes in the // given object. The delegation simplifies the implementation, which // uses the << operator and thus is easier done outside of the // ::testing::internal namespace, which contains a << operator that // sometimes conflicts with the one in STL. void PrintBytesInObjectTo(const unsigned char* obj_bytes, size_t count, ostream* os) { PrintBytesInObjectToImpl(obj_bytes, count, os); } } // namespace internal2 namespace internal { // Depending on the value of a char (or wchar_t), we print it in one // of three formats: // - as is if it's a printable ASCII (e.g. 'a', '2', ' '), // - as a hexidecimal escape sequence (e.g. '\x7F'), or // - as a special escape sequence (e.g. '\r', '\n'). enum CharFormat { kAsIs, kHexEscape, kSpecialEscape }; // Returns true if c is a printable ASCII character. We test the // value of c directly instead of calling isprint(), which is buggy on // Windows Mobile. inline bool IsPrintableAscii(wchar_t c) { return 0x20 <= c && c <= 0x7E; } // Prints a wide or narrow char c as a character literal without the // quotes, escaping it when necessary; returns how c was formatted. // The template argument UnsignedChar is the unsigned version of Char, // which is the type of c. template static CharFormat PrintAsCharLiteralTo(Char c, ostream* os) { switch (static_cast(c)) { case L'\0': *os << "\\0"; break; case L'\'': *os << "\\'"; break; case L'\\': *os << "\\\\"; break; case L'\a': *os << "\\a"; break; case L'\b': *os << "\\b"; break; case L'\f': *os << "\\f"; break; case L'\n': *os << "\\n"; break; case L'\r': *os << "\\r"; break; case L'\t': *os << "\\t"; break; case L'\v': *os << "\\v"; break; default: if (IsPrintableAscii(c)) { *os << static_cast(c); return kAsIs; } else { *os << String::Format("\\x%X", static_cast(c)); return kHexEscape; } } return kSpecialEscape; } // Prints a char c as if it's part of a string literal, escaping it when // necessary; returns how c was formatted. static CharFormat PrintAsWideStringLiteralTo(wchar_t c, ostream* os) { switch (c) { case L'\'': *os << "'"; return kAsIs; case L'"': *os << "\\\""; return kSpecialEscape; default: return PrintAsCharLiteralTo(c, os); } } // Prints a char c as if it's part of a string literal, escaping it when // necessary; returns how c was formatted. static CharFormat PrintAsNarrowStringLiteralTo(char c, ostream* os) { return PrintAsWideStringLiteralTo(static_cast(c), os); } // Prints a wide or narrow character c and its code. '\0' is printed // as "'\\0'", other unprintable characters are also properly escaped // using the standard C++ escape sequence. The template argument // UnsignedChar is the unsigned version of Char, which is the type of c. template void PrintCharAndCodeTo(Char c, ostream* os) { // First, print c as a literal in the most readable form we can find. *os << ((sizeof(c) > 1) ? "L'" : "'"); const CharFormat format = PrintAsCharLiteralTo(c, os); *os << "'"; // To aid user debugging, we also print c's code in decimal, unless // it's 0 (in which case c was printed as '\\0', making the code // obvious). if (c == 0) return; *os << " (" << String::Format("%d", c).c_str(); // For more convenience, we print c's code again in hexidecimal, // unless c was already printed in the form '\x##' or the code is in // [1, 9]. if (format == kHexEscape || (1 <= c && c <= 9)) { // Do nothing. } else { *os << String::Format(", 0x%X", static_cast(c)).c_str(); } *os << ")"; } void PrintTo(unsigned char c, ::std::ostream* os) { PrintCharAndCodeTo(c, os); } void PrintTo(signed char c, ::std::ostream* os) { PrintCharAndCodeTo(c, os); } // Prints a wchar_t as a symbol if it is printable or as its internal // code otherwise and also as its code. L'\0' is printed as "L'\\0'". void PrintTo(wchar_t wc, ostream* os) { PrintCharAndCodeTo(wc, os); } // Prints the given array of characters to the ostream. // The array starts at *begin, the length is len, it may include '\0' characters // and may not be null-terminated. static void PrintCharsAsStringTo(const char* begin, size_t len, ostream* os) { *os << "\""; bool is_previous_hex = false; for (size_t index = 0; index < len; ++index) { const char cur = begin[index]; if (is_previous_hex && IsXDigit(cur)) { // Previous character is of '\x..' form and this character can be // interpreted as another hexadecimal digit in its number. Break string to // disambiguate. *os << "\" \""; } is_previous_hex = PrintAsNarrowStringLiteralTo(cur, os) == kHexEscape; } *os << "\""; } // Prints a (const) char array of 'len' elements, starting at address 'begin'. void UniversalPrintArray(const char* begin, size_t len, ostream* os) { PrintCharsAsStringTo(begin, len, os); } // Prints the given array of wide characters to the ostream. // The array starts at *begin, the length is len, it may include L'\0' // characters and may not be null-terminated. static void PrintWideCharsAsStringTo(const wchar_t* begin, size_t len, ostream* os) { *os << "L\""; bool is_previous_hex = false; for (size_t index = 0; index < len; ++index) { const wchar_t cur = begin[index]; if (is_previous_hex && isascii(cur) && IsXDigit(static_cast(cur))) { // Previous character is of '\x..' form and this character can be // interpreted as another hexadecimal digit in its number. Break string to // disambiguate. *os << "\" L\""; } is_previous_hex = PrintAsWideStringLiteralTo(cur, os) == kHexEscape; } *os << "\""; } // Prints the given C string to the ostream. void PrintTo(const char* s, ostream* os) { if (s == NULL) { *os << "NULL"; } else { *os << ImplicitCast_(s) << " pointing to "; PrintCharsAsStringTo(s, strlen(s), os); } } // MSVC compiler can be configured to define whar_t as a typedef // of unsigned short. Defining an overload for const wchar_t* in that case // would cause pointers to unsigned shorts be printed as wide strings, // possibly accessing more memory than intended and causing invalid // memory accesses. MSVC defines _NATIVE_WCHAR_T_DEFINED symbol when // wchar_t is implemented as a native type. #if !defined(_MSC_VER) || defined(_NATIVE_WCHAR_T_DEFINED) // Prints the given wide C string to the ostream. void PrintTo(const wchar_t* s, ostream* os) { if (s == NULL) { *os << "NULL"; } else { *os << ImplicitCast_(s) << " pointing to "; PrintWideCharsAsStringTo(s, wcslen(s), os); } } #endif // wchar_t is native // Prints a ::string object. #if GTEST_HAS_GLOBAL_STRING void PrintStringTo(const ::string& s, ostream* os) { PrintCharsAsStringTo(s.data(), s.size(), os); } #endif // GTEST_HAS_GLOBAL_STRING void PrintStringTo(const ::std::string& s, ostream* os) { PrintCharsAsStringTo(s.data(), s.size(), os); } // Prints a ::wstring object. #if GTEST_HAS_GLOBAL_WSTRING void PrintWideStringTo(const ::wstring& s, ostream* os) { PrintWideCharsAsStringTo(s.data(), s.size(), os); } #endif // GTEST_HAS_GLOBAL_WSTRING #if GTEST_HAS_STD_WSTRING void PrintWideStringTo(const ::std::wstring& s, ostream* os) { PrintWideCharsAsStringTo(s.data(), s.size(), os); } #endif // GTEST_HAS_STD_WSTRING } // namespace internal } // namespace testing ugene-1.9.8/src/libs_3rdparty/gtest/src/src/gtest.cc0000644000175000017500000053715611651544307021052 0ustar ilyailya// Copyright 2005, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Author: wan@google.com (Zhanyong Wan) // // The Google C++ Testing Framework (Google Test) #include "gtest/gtest.h" #include "gtest/gtest-spi.h" #include #include #include #include #include #include #include #include #include // NOLINT #include #include #if GTEST_OS_LINUX // TODO(kenton@google.com): Use autoconf to detect availability of // gettimeofday(). # define GTEST_HAS_GETTIMEOFDAY_ 1 # include // NOLINT # include // NOLINT # include // NOLINT // Declares vsnprintf(). This header is not available on Windows. # include // NOLINT # include // NOLINT # include // NOLINT # include // NOLINT # include #elif GTEST_OS_SYMBIAN # define GTEST_HAS_GETTIMEOFDAY_ 1 # include // NOLINT #elif GTEST_OS_ZOS # define GTEST_HAS_GETTIMEOFDAY_ 1 # include // NOLINT // On z/OS we additionally need strings.h for strcasecmp. # include // NOLINT #elif GTEST_OS_WINDOWS_MOBILE // We are on Windows CE. # include // NOLINT #elif GTEST_OS_WINDOWS // We are on Windows proper. # include // NOLINT # include // NOLINT # include // NOLINT # include // NOLINT # if GTEST_OS_WINDOWS_MINGW // MinGW has gettimeofday() but not _ftime64(). // TODO(kenton@google.com): Use autoconf to detect availability of // gettimeofday(). // TODO(kenton@google.com): There are other ways to get the time on // Windows, like GetTickCount() or GetSystemTimeAsFileTime(). MinGW // supports these. consider using them instead. # define GTEST_HAS_GETTIMEOFDAY_ 1 # include // NOLINT # endif // GTEST_OS_WINDOWS_MINGW // cpplint thinks that the header is already included, so we want to // silence it. # include // NOLINT #else // Assume other platforms have gettimeofday(). // TODO(kenton@google.com): Use autoconf to detect availability of // gettimeofday(). # define GTEST_HAS_GETTIMEOFDAY_ 1 // cpplint thinks that the header is already included, so we want to // silence it. # include // NOLINT # include // NOLINT #endif // GTEST_OS_LINUX #if GTEST_HAS_EXCEPTIONS # include #endif #if GTEST_CAN_STREAM_RESULTS_ # include // NOLINT # include // NOLINT #endif // Indicates that this translation unit is part of Google Test's // implementation. It must come before gtest-internal-inl.h is // included, or there will be a compiler error. This trick is to // prevent a user from accidentally including gtest-internal-inl.h in // his code. #define GTEST_IMPLEMENTATION_ 1 #include "src/gtest-internal-inl.h" #undef GTEST_IMPLEMENTATION_ #if GTEST_OS_WINDOWS # define vsnprintf _vsnprintf #endif // GTEST_OS_WINDOWS namespace testing { using internal::CountIf; using internal::ForEach; using internal::GetElementOr; using internal::Shuffle; // Constants. // A test whose test case name or test name matches this filter is // disabled and not run. static const char kDisableTestFilter[] = "DISABLED_*:*/DISABLED_*"; // A test case whose name matches this filter is considered a death // test case and will be run before test cases whose name doesn't // match this filter. static const char kDeathTestCaseFilter[] = "*DeathTest:*DeathTest/*"; // A test filter that matches everything. static const char kUniversalFilter[] = "*"; // The default output file for XML output. static const char kDefaultOutputFile[] = "test_detail.xml"; // The environment variable name for the test shard index. static const char kTestShardIndex[] = "GTEST_SHARD_INDEX"; // The environment variable name for the total number of test shards. static const char kTestTotalShards[] = "GTEST_TOTAL_SHARDS"; // The environment variable name for the test shard status file. static const char kTestShardStatusFile[] = "GTEST_SHARD_STATUS_FILE"; namespace internal { // The text used in failure messages to indicate the start of the // stack trace. const char kStackTraceMarker[] = "\nStack trace:\n"; // g_help_flag is true iff the --help flag or an equivalent form is // specified on the command line. bool g_help_flag = false; } // namespace internal GTEST_DEFINE_bool_( also_run_disabled_tests, internal::BoolFromGTestEnv("also_run_disabled_tests", false), "Run disabled tests too, in addition to the tests normally being run."); GTEST_DEFINE_bool_( break_on_failure, internal::BoolFromGTestEnv("break_on_failure", false), "True iff a failed assertion should be a debugger break-point."); GTEST_DEFINE_bool_( catch_exceptions, internal::BoolFromGTestEnv("catch_exceptions", true), "True iff " GTEST_NAME_ " should catch exceptions and treat them as test failures."); GTEST_DEFINE_string_( color, internal::StringFromGTestEnv("color", "auto"), "Whether to use colors in the output. Valid values: yes, no, " "and auto. 'auto' means to use colors if the output is " "being sent to a terminal and the TERM environment variable " "is set to xterm, xterm-color, xterm-256color, linux or cygwin."); GTEST_DEFINE_string_( filter, internal::StringFromGTestEnv("filter", kUniversalFilter), "A colon-separated list of glob (not regex) patterns " "for filtering the tests to run, optionally followed by a " "'-' and a : separated list of negative patterns (tests to " "exclude). A test is run if it matches one of the positive " "patterns and does not match any of the negative patterns."); GTEST_DEFINE_bool_(list_tests, false, "List all tests without running them."); GTEST_DEFINE_string_( output, internal::StringFromGTestEnv("output", ""), "A format (currently must be \"xml\"), optionally followed " "by a colon and an output file name or directory. A directory " "is indicated by a trailing pathname separator. " "Examples: \"xml:filename.xml\", \"xml::directoryname/\". " "If a directory is specified, output files will be created " "within that directory, with file-names based on the test " "executable's name and, if necessary, made unique by adding " "digits."); GTEST_DEFINE_bool_( print_time, internal::BoolFromGTestEnv("print_time", true), "True iff " GTEST_NAME_ " should display elapsed time in text output."); GTEST_DEFINE_int32_( random_seed, internal::Int32FromGTestEnv("random_seed", 0), "Random number seed to use when shuffling test orders. Must be in range " "[1, 99999], or 0 to use a seed based on the current time."); GTEST_DEFINE_int32_( repeat, internal::Int32FromGTestEnv("repeat", 1), "How many times to repeat each test. Specify a negative number " "for repeating forever. Useful for shaking out flaky tests."); GTEST_DEFINE_bool_( show_internal_stack_frames, false, "True iff " GTEST_NAME_ " should include internal stack frames when " "printing test failure stack traces."); GTEST_DEFINE_bool_( shuffle, internal::BoolFromGTestEnv("shuffle", false), "True iff " GTEST_NAME_ " should randomize tests' order on every run."); GTEST_DEFINE_int32_( stack_trace_depth, internal::Int32FromGTestEnv("stack_trace_depth", kMaxStackTraceDepth), "The maximum number of stack frames to print when an " "assertion fails. The valid range is 0 through 100, inclusive."); GTEST_DEFINE_string_( stream_result_to, internal::StringFromGTestEnv("stream_result_to", ""), "This flag specifies the host name and the port number on which to stream " "test results. Example: \"localhost:555\". The flag is effective only on " "Linux."); GTEST_DEFINE_bool_( throw_on_failure, internal::BoolFromGTestEnv("throw_on_failure", false), "When this flag is specified, a failed assertion will throw an exception " "if exceptions are enabled or exit the program with a non-zero code " "otherwise."); namespace internal { // Generates a random number from [0, range), using a Linear // Congruential Generator (LCG). Crashes if 'range' is 0 or greater // than kMaxRange. UInt32 Random::Generate(UInt32 range) { // These constants are the same as are used in glibc's rand(3). state_ = (1103515245U*state_ + 12345U) % kMaxRange; GTEST_CHECK_(range > 0) << "Cannot generate a number in the range [0, 0)."; GTEST_CHECK_(range <= kMaxRange) << "Generation of a number in [0, " << range << ") was requested, " << "but this can only generate numbers in [0, " << kMaxRange << ")."; // Converting via modulus introduces a bit of downward bias, but // it's simple, and a linear congruential generator isn't too good // to begin with. return state_ % range; } // GTestIsInitialized() returns true iff the user has initialized // Google Test. Useful for catching the user mistake of not initializing // Google Test before calling RUN_ALL_TESTS(). // // A user must call testing::InitGoogleTest() to initialize Google // Test. g_init_gtest_count is set to the number of times // InitGoogleTest() has been called. We don't protect this variable // under a mutex as it is only accessed in the main thread. int g_init_gtest_count = 0; static bool GTestIsInitialized() { return g_init_gtest_count != 0; } // Iterates over a vector of TestCases, keeping a running sum of the // results of calling a given int-returning method on each. // Returns the sum. static int SumOverTestCaseList(const std::vector& case_list, int (TestCase::*method)() const) { int sum = 0; for (size_t i = 0; i < case_list.size(); i++) { sum += (case_list[i]->*method)(); } return sum; } // Returns true iff the test case passed. static bool TestCasePassed(const TestCase* test_case) { return test_case->should_run() && test_case->Passed(); } // Returns true iff the test case failed. static bool TestCaseFailed(const TestCase* test_case) { return test_case->should_run() && test_case->Failed(); } // Returns true iff test_case contains at least one test that should // run. static bool ShouldRunTestCase(const TestCase* test_case) { return test_case->should_run(); } // AssertHelper constructor. AssertHelper::AssertHelper(TestPartResult::Type type, const char* file, int line, const char* message) : data_(new AssertHelperData(type, file, line, message)) { } AssertHelper::~AssertHelper() { delete data_; } // Message assignment, for assertion streaming support. void AssertHelper::operator=(const Message& message) const { UnitTest::GetInstance()-> AddTestPartResult(data_->type, data_->file, data_->line, AppendUserMessage(data_->message, message), UnitTest::GetInstance()->impl() ->CurrentOsStackTraceExceptTop(1) // Skips the stack frame for this function itself. ); // NOLINT } // Mutex for linked pointers. GTEST_DEFINE_STATIC_MUTEX_(g_linked_ptr_mutex); // Application pathname gotten in InitGoogleTest. String g_executable_path; // Returns the current application's name, removing directory path if that // is present. FilePath GetCurrentExecutableName() { FilePath result; #if GTEST_OS_WINDOWS result.Set(FilePath(g_executable_path).RemoveExtension("exe")); #else result.Set(FilePath(g_executable_path)); #endif // GTEST_OS_WINDOWS return result.RemoveDirectoryName(); } // Functions for processing the gtest_output flag. // Returns the output format, or "" for normal printed output. String UnitTestOptions::GetOutputFormat() { const char* const gtest_output_flag = GTEST_FLAG(output).c_str(); if (gtest_output_flag == NULL) return String(""); const char* const colon = strchr(gtest_output_flag, ':'); return (colon == NULL) ? String(gtest_output_flag) : String(gtest_output_flag, colon - gtest_output_flag); } // Returns the name of the requested output file, or the default if none // was explicitly specified. String UnitTestOptions::GetAbsolutePathToOutputFile() { const char* const gtest_output_flag = GTEST_FLAG(output).c_str(); if (gtest_output_flag == NULL) return String(""); const char* const colon = strchr(gtest_output_flag, ':'); if (colon == NULL) return String(internal::FilePath::ConcatPaths( internal::FilePath( UnitTest::GetInstance()->original_working_dir()), internal::FilePath(kDefaultOutputFile)).ToString() ); internal::FilePath output_name(colon + 1); if (!output_name.IsAbsolutePath()) // TODO(wan@google.com): on Windows \some\path is not an absolute // path (as its meaning depends on the current drive), yet the // following logic for turning it into an absolute path is wrong. // Fix it. output_name = internal::FilePath::ConcatPaths( internal::FilePath(UnitTest::GetInstance()->original_working_dir()), internal::FilePath(colon + 1)); if (!output_name.IsDirectory()) return output_name.ToString(); internal::FilePath result(internal::FilePath::GenerateUniqueFileName( output_name, internal::GetCurrentExecutableName(), GetOutputFormat().c_str())); return result.ToString(); } // Returns true iff the wildcard pattern matches the string. The // first ':' or '\0' character in pattern marks the end of it. // // This recursive algorithm isn't very efficient, but is clear and // works well enough for matching test names, which are short. bool UnitTestOptions::PatternMatchesString(const char *pattern, const char *str) { switch (*pattern) { case '\0': case ':': // Either ':' or '\0' marks the end of the pattern. return *str == '\0'; case '?': // Matches any single character. return *str != '\0' && PatternMatchesString(pattern + 1, str + 1); case '*': // Matches any string (possibly empty) of characters. return (*str != '\0' && PatternMatchesString(pattern, str + 1)) || PatternMatchesString(pattern + 1, str); default: // Non-special character. Matches itself. return *pattern == *str && PatternMatchesString(pattern + 1, str + 1); } } bool UnitTestOptions::MatchesFilter(const String& name, const char* filter) { const char *cur_pattern = filter; for (;;) { if (PatternMatchesString(cur_pattern, name.c_str())) { return true; } // Finds the next pattern in the filter. cur_pattern = strchr(cur_pattern, ':'); // Returns if no more pattern can be found. if (cur_pattern == NULL) { return false; } // Skips the pattern separater (the ':' character). cur_pattern++; } } // TODO(keithray): move String function implementations to gtest-string.cc. // Returns true iff the user-specified filter matches the test case // name and the test name. bool UnitTestOptions::FilterMatchesTest(const String &test_case_name, const String &test_name) { const String& full_name = String::Format("%s.%s", test_case_name.c_str(), test_name.c_str()); // Split --gtest_filter at '-', if there is one, to separate into // positive filter and negative filter portions const char* const p = GTEST_FLAG(filter).c_str(); const char* const dash = strchr(p, '-'); String positive; String negative; if (dash == NULL) { positive = GTEST_FLAG(filter).c_str(); // Whole string is a positive filter negative = String(""); } else { positive = String(p, dash - p); // Everything up to the dash negative = String(dash+1); // Everything after the dash if (positive.empty()) { // Treat '-test1' as the same as '*-test1' positive = kUniversalFilter; } } // A filter is a colon-separated list of patterns. It matches a // test if any pattern in it matches the test. return (MatchesFilter(full_name, positive.c_str()) && !MatchesFilter(full_name, negative.c_str())); } #if GTEST_HAS_SEH // Returns EXCEPTION_EXECUTE_HANDLER if Google Test should handle the // given SEH exception, or EXCEPTION_CONTINUE_SEARCH otherwise. // This function is useful as an __except condition. int UnitTestOptions::GTestShouldProcessSEH(DWORD exception_code) { // Google Test should handle a SEH exception if: // 1. the user wants it to, AND // 2. this is not a breakpoint exception, AND // 3. this is not a C++ exception (VC++ implements them via SEH, // apparently). // // SEH exception code for C++ exceptions. // (see http://support.microsoft.com/kb/185294 for more information). const DWORD kCxxExceptionCode = 0xe06d7363; bool should_handle = true; if (!GTEST_FLAG(catch_exceptions)) should_handle = false; else if (exception_code == EXCEPTION_BREAKPOINT) should_handle = false; else if (exception_code == kCxxExceptionCode) should_handle = false; return should_handle ? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH; } #endif // GTEST_HAS_SEH } // namespace internal // The c'tor sets this object as the test part result reporter used by // Google Test. The 'result' parameter specifies where to report the // results. Intercepts only failures from the current thread. ScopedFakeTestPartResultReporter::ScopedFakeTestPartResultReporter( TestPartResultArray* result) : intercept_mode_(INTERCEPT_ONLY_CURRENT_THREAD), result_(result) { Init(); } // The c'tor sets this object as the test part result reporter used by // Google Test. The 'result' parameter specifies where to report the // results. ScopedFakeTestPartResultReporter::ScopedFakeTestPartResultReporter( InterceptMode intercept_mode, TestPartResultArray* result) : intercept_mode_(intercept_mode), result_(result) { Init(); } void ScopedFakeTestPartResultReporter::Init() { internal::UnitTestImpl* const impl = internal::GetUnitTestImpl(); if (intercept_mode_ == INTERCEPT_ALL_THREADS) { old_reporter_ = impl->GetGlobalTestPartResultReporter(); impl->SetGlobalTestPartResultReporter(this); } else { old_reporter_ = impl->GetTestPartResultReporterForCurrentThread(); impl->SetTestPartResultReporterForCurrentThread(this); } } // The d'tor restores the test part result reporter used by Google Test // before. ScopedFakeTestPartResultReporter::~ScopedFakeTestPartResultReporter() { internal::UnitTestImpl* const impl = internal::GetUnitTestImpl(); if (intercept_mode_ == INTERCEPT_ALL_THREADS) { impl->SetGlobalTestPartResultReporter(old_reporter_); } else { impl->SetTestPartResultReporterForCurrentThread(old_reporter_); } } // Increments the test part result count and remembers the result. // This method is from the TestPartResultReporterInterface interface. void ScopedFakeTestPartResultReporter::ReportTestPartResult( const TestPartResult& result) { result_->Append(result); } namespace internal { // Returns the type ID of ::testing::Test. We should always call this // instead of GetTypeId< ::testing::Test>() to get the type ID of // testing::Test. This is to work around a suspected linker bug when // using Google Test as a framework on Mac OS X. The bug causes // GetTypeId< ::testing::Test>() to return different values depending // on whether the call is from the Google Test framework itself or // from user test code. GetTestTypeId() is guaranteed to always // return the same value, as it always calls GetTypeId<>() from the // gtest.cc, which is within the Google Test framework. TypeId GetTestTypeId() { return GetTypeId(); } // The value of GetTestTypeId() as seen from within the Google Test // library. This is solely for testing GetTestTypeId(). extern const TypeId kTestTypeIdInGoogleTest = GetTestTypeId(); // This predicate-formatter checks that 'results' contains a test part // failure of the given type and that the failure message contains the // given substring. AssertionResult HasOneFailure(const char* /* results_expr */, const char* /* type_expr */, const char* /* substr_expr */, const TestPartResultArray& results, TestPartResult::Type type, const string& substr) { const String expected(type == TestPartResult::kFatalFailure ? "1 fatal failure" : "1 non-fatal failure"); Message msg; if (results.size() != 1) { msg << "Expected: " << expected << "\n" << " Actual: " << results.size() << " failures"; for (int i = 0; i < results.size(); i++) { msg << "\n" << results.GetTestPartResult(i); } return AssertionFailure() << msg; } const TestPartResult& r = results.GetTestPartResult(0); if (r.type() != type) { return AssertionFailure() << "Expected: " << expected << "\n" << " Actual:\n" << r; } if (strstr(r.message(), substr.c_str()) == NULL) { return AssertionFailure() << "Expected: " << expected << " containing \"" << substr << "\"\n" << " Actual:\n" << r; } return AssertionSuccess(); } // The constructor of SingleFailureChecker remembers where to look up // test part results, what type of failure we expect, and what // substring the failure message should contain. SingleFailureChecker:: SingleFailureChecker( const TestPartResultArray* results, TestPartResult::Type type, const string& substr) : results_(results), type_(type), substr_(substr) {} // The destructor of SingleFailureChecker verifies that the given // TestPartResultArray contains exactly one failure that has the given // type and contains the given substring. If that's not the case, a // non-fatal failure will be generated. SingleFailureChecker::~SingleFailureChecker() { EXPECT_PRED_FORMAT3(HasOneFailure, *results_, type_, substr_); } DefaultGlobalTestPartResultReporter::DefaultGlobalTestPartResultReporter( UnitTestImpl* unit_test) : unit_test_(unit_test) {} void DefaultGlobalTestPartResultReporter::ReportTestPartResult( const TestPartResult& result) { unit_test_->current_test_result()->AddTestPartResult(result); unit_test_->listeners()->repeater()->OnTestPartResult(result); } DefaultPerThreadTestPartResultReporter::DefaultPerThreadTestPartResultReporter( UnitTestImpl* unit_test) : unit_test_(unit_test) {} void DefaultPerThreadTestPartResultReporter::ReportTestPartResult( const TestPartResult& result) { unit_test_->GetGlobalTestPartResultReporter()->ReportTestPartResult(result); } // Returns the global test part result reporter. TestPartResultReporterInterface* UnitTestImpl::GetGlobalTestPartResultReporter() { internal::MutexLock lock(&global_test_part_result_reporter_mutex_); return global_test_part_result_repoter_; } // Sets the global test part result reporter. void UnitTestImpl::SetGlobalTestPartResultReporter( TestPartResultReporterInterface* reporter) { internal::MutexLock lock(&global_test_part_result_reporter_mutex_); global_test_part_result_repoter_ = reporter; } // Returns the test part result reporter for the current thread. TestPartResultReporterInterface* UnitTestImpl::GetTestPartResultReporterForCurrentThread() { return per_thread_test_part_result_reporter_.get(); } // Sets the test part result reporter for the current thread. void UnitTestImpl::SetTestPartResultReporterForCurrentThread( TestPartResultReporterInterface* reporter) { per_thread_test_part_result_reporter_.set(reporter); } // Gets the number of successful test cases. int UnitTestImpl::successful_test_case_count() const { return CountIf(test_cases_, TestCasePassed); } // Gets the number of failed test cases. int UnitTestImpl::failed_test_case_count() const { return CountIf(test_cases_, TestCaseFailed); } // Gets the number of all test cases. int UnitTestImpl::total_test_case_count() const { return static_cast(test_cases_.size()); } // Gets the number of all test cases that contain at least one test // that should run. int UnitTestImpl::test_case_to_run_count() const { return CountIf(test_cases_, ShouldRunTestCase); } // Gets the number of successful tests. int UnitTestImpl::successful_test_count() const { return SumOverTestCaseList(test_cases_, &TestCase::successful_test_count); } // Gets the number of failed tests. int UnitTestImpl::failed_test_count() const { return SumOverTestCaseList(test_cases_, &TestCase::failed_test_count); } // Gets the number of disabled tests. int UnitTestImpl::disabled_test_count() const { return SumOverTestCaseList(test_cases_, &TestCase::disabled_test_count); } // Gets the number of all tests. int UnitTestImpl::total_test_count() const { return SumOverTestCaseList(test_cases_, &TestCase::total_test_count); } // Gets the number of tests that should run. int UnitTestImpl::test_to_run_count() const { return SumOverTestCaseList(test_cases_, &TestCase::test_to_run_count); } // Returns the current OS stack trace as a String. // // The maximum number of stack frames to be included is specified by // the gtest_stack_trace_depth flag. The skip_count parameter // specifies the number of top frames to be skipped, which doesn't // count against the number of frames to be included. // // For example, if Foo() calls Bar(), which in turn calls // CurrentOsStackTraceExceptTop(1), Foo() will be included in the // trace but Bar() and CurrentOsStackTraceExceptTop() won't. String UnitTestImpl::CurrentOsStackTraceExceptTop(int skip_count) { (void)skip_count; return String(""); } // Returns the current time in milliseconds. TimeInMillis GetTimeInMillis() { #if GTEST_OS_WINDOWS_MOBILE || defined(__BORLANDC__) // Difference between 1970-01-01 and 1601-01-01 in milliseconds. // http://analogous.blogspot.com/2005/04/epoch.html const TimeInMillis kJavaEpochToWinFileTimeDelta = static_cast(116444736UL) * 100000UL; const DWORD kTenthMicrosInMilliSecond = 10000; SYSTEMTIME now_systime; FILETIME now_filetime; ULARGE_INTEGER now_int64; // TODO(kenton@google.com): Shouldn't this just use // GetSystemTimeAsFileTime()? GetSystemTime(&now_systime); if (SystemTimeToFileTime(&now_systime, &now_filetime)) { now_int64.LowPart = now_filetime.dwLowDateTime; now_int64.HighPart = now_filetime.dwHighDateTime; now_int64.QuadPart = (now_int64.QuadPart / kTenthMicrosInMilliSecond) - kJavaEpochToWinFileTimeDelta; return now_int64.QuadPart; } return 0; #elif GTEST_OS_WINDOWS && !GTEST_HAS_GETTIMEOFDAY_ __timeb64 now; # ifdef _MSC_VER // MSVC 8 deprecates _ftime64(), so we want to suppress warning 4996 // (deprecated function) there. // TODO(kenton@google.com): Use GetTickCount()? Or use // SystemTimeToFileTime() # pragma warning(push) // Saves the current warning state. # pragma warning(disable:4996) // Temporarily disables warning 4996. _ftime64(&now); # pragma warning(pop) // Restores the warning state. # else _ftime64(&now); # endif // _MSC_VER return static_cast(now.time) * 1000 + now.millitm; #elif GTEST_HAS_GETTIMEOFDAY_ struct timeval now; gettimeofday(&now, NULL); return static_cast(now.tv_sec) * 1000 + now.tv_usec / 1000; #else # error "Don't know how to get the current time on your system." #endif } // Utilities // class String // Returns the input enclosed in double quotes if it's not NULL; // otherwise returns "(null)". For example, "\"Hello\"" is returned // for input "Hello". // // This is useful for printing a C string in the syntax of a literal. // // Known issue: escape sequences are not handled yet. String String::ShowCStringQuoted(const char* c_str) { return c_str ? String::Format("\"%s\"", c_str) : String("(null)"); } // Copies at most length characters from str into a newly-allocated // piece of memory of size length+1. The memory is allocated with new[]. // A terminating null byte is written to the memory, and a pointer to it // is returned. If str is NULL, NULL is returned. static char* CloneString(const char* str, size_t length) { if (str == NULL) { return NULL; } else { char* const clone = new char[length + 1]; posix::StrNCpy(clone, str, length); clone[length] = '\0'; return clone; } } // Clones a 0-terminated C string, allocating memory using new. The // caller is responsible for deleting[] the return value. Returns the // cloned string, or NULL if the input is NULL. const char * String::CloneCString(const char* c_str) { return (c_str == NULL) ? NULL : CloneString(c_str, strlen(c_str)); } #if GTEST_OS_WINDOWS_MOBILE // Creates a UTF-16 wide string from the given ANSI string, allocating // memory using new. The caller is responsible for deleting the return // value using delete[]. Returns the wide string, or NULL if the // input is NULL. LPCWSTR String::AnsiToUtf16(const char* ansi) { if (!ansi) return NULL; const int length = strlen(ansi); const int unicode_length = MultiByteToWideChar(CP_ACP, 0, ansi, length, NULL, 0); WCHAR* unicode = new WCHAR[unicode_length + 1]; MultiByteToWideChar(CP_ACP, 0, ansi, length, unicode, unicode_length); unicode[unicode_length] = 0; return unicode; } // Creates an ANSI string from the given wide string, allocating // memory using new. The caller is responsible for deleting the return // value using delete[]. Returns the ANSI string, or NULL if the // input is NULL. const char* String::Utf16ToAnsi(LPCWSTR utf16_str) { if (!utf16_str) return NULL; const int ansi_length = WideCharToMultiByte(CP_ACP, 0, utf16_str, -1, NULL, 0, NULL, NULL); char* ansi = new char[ansi_length + 1]; WideCharToMultiByte(CP_ACP, 0, utf16_str, -1, ansi, ansi_length, NULL, NULL); ansi[ansi_length] = 0; return ansi; } #endif // GTEST_OS_WINDOWS_MOBILE // Compares two C strings. Returns true iff they have the same content. // // Unlike strcmp(), this function can handle NULL argument(s). A NULL // C string is considered different to any non-NULL C string, // including the empty string. bool String::CStringEquals(const char * lhs, const char * rhs) { if ( lhs == NULL ) return rhs == NULL; if ( rhs == NULL ) return false; return strcmp(lhs, rhs) == 0; } #if GTEST_HAS_STD_WSTRING || GTEST_HAS_GLOBAL_WSTRING // Converts an array of wide chars to a narrow string using the UTF-8 // encoding, and streams the result to the given Message object. static void StreamWideCharsToMessage(const wchar_t* wstr, size_t length, Message* msg) { // TODO(wan): consider allowing a testing::String object to // contain '\0'. This will make it behave more like std::string, // and will allow ToUtf8String() to return the correct encoding // for '\0' s.t. we can get rid of the conditional here (and in // several other places). for (size_t i = 0; i != length; ) { // NOLINT if (wstr[i] != L'\0') { *msg << WideStringToUtf8(wstr + i, static_cast(length - i)); while (i != length && wstr[i] != L'\0') i++; } else { *msg << '\0'; i++; } } } #endif // GTEST_HAS_STD_WSTRING || GTEST_HAS_GLOBAL_WSTRING } // namespace internal #if GTEST_HAS_STD_WSTRING // Converts the given wide string to a narrow string using the UTF-8 // encoding, and streams the result to this Message object. Message& Message::operator <<(const ::std::wstring& wstr) { internal::StreamWideCharsToMessage(wstr.c_str(), wstr.length(), this); return *this; } #endif // GTEST_HAS_STD_WSTRING #if GTEST_HAS_GLOBAL_WSTRING // Converts the given wide string to a narrow string using the UTF-8 // encoding, and streams the result to this Message object. Message& Message::operator <<(const ::wstring& wstr) { internal::StreamWideCharsToMessage(wstr.c_str(), wstr.length(), this); return *this; } #endif // GTEST_HAS_GLOBAL_WSTRING // AssertionResult constructors. // Used in EXPECT_TRUE/FALSE(assertion_result). AssertionResult::AssertionResult(const AssertionResult& other) : success_(other.success_), message_(other.message_.get() != NULL ? new ::std::string(*other.message_) : static_cast< ::std::string*>(NULL)) { } // Returns the assertion's negation. Used with EXPECT/ASSERT_FALSE. AssertionResult AssertionResult::operator!() const { AssertionResult negation(!success_); if (message_.get() != NULL) negation << *message_; return negation; } // Makes a successful assertion result. AssertionResult AssertionSuccess() { return AssertionResult(true); } // Makes a failed assertion result. AssertionResult AssertionFailure() { return AssertionResult(false); } // Makes a failed assertion result with the given failure message. // Deprecated; use AssertionFailure() << message. AssertionResult AssertionFailure(const Message& message) { return AssertionFailure() << message; } namespace internal { // Constructs and returns the message for an equality assertion // (e.g. ASSERT_EQ, EXPECT_STREQ, etc) failure. // // The first four parameters are the expressions used in the assertion // and their values, as strings. For example, for ASSERT_EQ(foo, bar) // where foo is 5 and bar is 6, we have: // // expected_expression: "foo" // actual_expression: "bar" // expected_value: "5" // actual_value: "6" // // The ignoring_case parameter is true iff the assertion is a // *_STRCASEEQ*. When it's true, the string " (ignoring case)" will // be inserted into the message. AssertionResult EqFailure(const char* expected_expression, const char* actual_expression, const String& expected_value, const String& actual_value, bool ignoring_case) { Message msg; msg << "Value of: " << actual_expression; if (actual_value != actual_expression) { msg << "\n Actual: " << actual_value; } msg << "\nExpected: " << expected_expression; if (ignoring_case) { msg << " (ignoring case)"; } if (expected_value != expected_expression) { msg << "\nWhich is: " << expected_value; } return AssertionFailure() << msg; } // Constructs a failure message for Boolean assertions such as EXPECT_TRUE. String GetBoolAssertionFailureMessage(const AssertionResult& assertion_result, const char* expression_text, const char* actual_predicate_value, const char* expected_predicate_value) { const char* actual_message = assertion_result.message(); Message msg; msg << "Value of: " << expression_text << "\n Actual: " << actual_predicate_value; if (actual_message[0] != '\0') msg << " (" << actual_message << ")"; msg << "\nExpected: " << expected_predicate_value; return msg.GetString(); } // Helper function for implementing ASSERT_NEAR. AssertionResult DoubleNearPredFormat(const char* expr1, const char* expr2, const char* abs_error_expr, double val1, double val2, double abs_error) { const double diff = fabs(val1 - val2); if (diff <= abs_error) return AssertionSuccess(); // TODO(wan): do not print the value of an expression if it's // already a literal. return AssertionFailure() << "The difference between " << expr1 << " and " << expr2 << " is " << diff << ", which exceeds " << abs_error_expr << ", where\n" << expr1 << " evaluates to " << val1 << ",\n" << expr2 << " evaluates to " << val2 << ", and\n" << abs_error_expr << " evaluates to " << abs_error << "."; } // Helper template for implementing FloatLE() and DoubleLE(). template AssertionResult FloatingPointLE(const char* expr1, const char* expr2, RawType val1, RawType val2) { // Returns success if val1 is less than val2, if (val1 < val2) { return AssertionSuccess(); } // or if val1 is almost equal to val2. const FloatingPoint lhs(val1), rhs(val2); if (lhs.AlmostEquals(rhs)) { return AssertionSuccess(); } // Note that the above two checks will both fail if either val1 or // val2 is NaN, as the IEEE floating-point standard requires that // any predicate involving a NaN must return false. ::std::stringstream val1_ss; val1_ss << std::setprecision(std::numeric_limits::digits10 + 2) << val1; ::std::stringstream val2_ss; val2_ss << std::setprecision(std::numeric_limits::digits10 + 2) << val2; return AssertionFailure() << "Expected: (" << expr1 << ") <= (" << expr2 << ")\n" << " Actual: " << StringStreamToString(&val1_ss) << " vs " << StringStreamToString(&val2_ss); } } // namespace internal // Asserts that val1 is less than, or almost equal to, val2. Fails // otherwise. In particular, it fails if either val1 or val2 is NaN. AssertionResult FloatLE(const char* expr1, const char* expr2, float val1, float val2) { return internal::FloatingPointLE(expr1, expr2, val1, val2); } // Asserts that val1 is less than, or almost equal to, val2. Fails // otherwise. In particular, it fails if either val1 or val2 is NaN. AssertionResult DoubleLE(const char* expr1, const char* expr2, double val1, double val2) { return internal::FloatingPointLE(expr1, expr2, val1, val2); } namespace internal { // The helper function for {ASSERT|EXPECT}_EQ with int or enum // arguments. AssertionResult CmpHelperEQ(const char* expected_expression, const char* actual_expression, BiggestInt expected, BiggestInt actual) { if (expected == actual) { return AssertionSuccess(); } return EqFailure(expected_expression, actual_expression, FormatForComparisonFailureMessage(expected, actual), FormatForComparisonFailureMessage(actual, expected), false); } // A macro for implementing the helper functions needed to implement // ASSERT_?? and EXPECT_?? with integer or enum arguments. It is here // just to avoid copy-and-paste of similar code. #define GTEST_IMPL_CMP_HELPER_(op_name, op)\ AssertionResult CmpHelper##op_name(const char* expr1, const char* expr2, \ BiggestInt val1, BiggestInt val2) {\ if (val1 op val2) {\ return AssertionSuccess();\ } else {\ return AssertionFailure() \ << "Expected: (" << expr1 << ") " #op " (" << expr2\ << "), actual: " << FormatForComparisonFailureMessage(val1, val2)\ << " vs " << FormatForComparisonFailureMessage(val2, val1);\ }\ } // Implements the helper function for {ASSERT|EXPECT}_NE with int or // enum arguments. GTEST_IMPL_CMP_HELPER_(NE, !=) // Implements the helper function for {ASSERT|EXPECT}_LE with int or // enum arguments. GTEST_IMPL_CMP_HELPER_(LE, <=) // Implements the helper function for {ASSERT|EXPECT}_LT with int or // enum arguments. GTEST_IMPL_CMP_HELPER_(LT, < ) // Implements the helper function for {ASSERT|EXPECT}_GE with int or // enum arguments. GTEST_IMPL_CMP_HELPER_(GE, >=) // Implements the helper function for {ASSERT|EXPECT}_GT with int or // enum arguments. GTEST_IMPL_CMP_HELPER_(GT, > ) #undef GTEST_IMPL_CMP_HELPER_ // The helper function for {ASSERT|EXPECT}_STREQ. AssertionResult CmpHelperSTREQ(const char* expected_expression, const char* actual_expression, const char* expected, const char* actual) { if (String::CStringEquals(expected, actual)) { return AssertionSuccess(); } return EqFailure(expected_expression, actual_expression, String::ShowCStringQuoted(expected), String::ShowCStringQuoted(actual), false); } // The helper function for {ASSERT|EXPECT}_STRCASEEQ. AssertionResult CmpHelperSTRCASEEQ(const char* expected_expression, const char* actual_expression, const char* expected, const char* actual) { if (String::CaseInsensitiveCStringEquals(expected, actual)) { return AssertionSuccess(); } return EqFailure(expected_expression, actual_expression, String::ShowCStringQuoted(expected), String::ShowCStringQuoted(actual), true); } // The helper function for {ASSERT|EXPECT}_STRNE. AssertionResult CmpHelperSTRNE(const char* s1_expression, const char* s2_expression, const char* s1, const char* s2) { if (!String::CStringEquals(s1, s2)) { return AssertionSuccess(); } else { return AssertionFailure() << "Expected: (" << s1_expression << ") != (" << s2_expression << "), actual: \"" << s1 << "\" vs \"" << s2 << "\""; } } // The helper function for {ASSERT|EXPECT}_STRCASENE. AssertionResult CmpHelperSTRCASENE(const char* s1_expression, const char* s2_expression, const char* s1, const char* s2) { if (!String::CaseInsensitiveCStringEquals(s1, s2)) { return AssertionSuccess(); } else { return AssertionFailure() << "Expected: (" << s1_expression << ") != (" << s2_expression << ") (ignoring case), actual: \"" << s1 << "\" vs \"" << s2 << "\""; } } } // namespace internal namespace { // Helper functions for implementing IsSubString() and IsNotSubstring(). // This group of overloaded functions return true iff needle is a // substring of haystack. NULL is considered a substring of itself // only. bool IsSubstringPred(const char* needle, const char* haystack) { if (needle == NULL || haystack == NULL) return needle == haystack; return strstr(haystack, needle) != NULL; } bool IsSubstringPred(const wchar_t* needle, const wchar_t* haystack) { if (needle == NULL || haystack == NULL) return needle == haystack; return wcsstr(haystack, needle) != NULL; } // StringType here can be either ::std::string or ::std::wstring. template bool IsSubstringPred(const StringType& needle, const StringType& haystack) { return haystack.find(needle) != StringType::npos; } // This function implements either IsSubstring() or IsNotSubstring(), // depending on the value of the expected_to_be_substring parameter. // StringType here can be const char*, const wchar_t*, ::std::string, // or ::std::wstring. template AssertionResult IsSubstringImpl( bool expected_to_be_substring, const char* needle_expr, const char* haystack_expr, const StringType& needle, const StringType& haystack) { if (IsSubstringPred(needle, haystack) == expected_to_be_substring) return AssertionSuccess(); const bool is_wide_string = sizeof(needle[0]) > 1; const char* const begin_string_quote = is_wide_string ? "L\"" : "\""; return AssertionFailure() << "Value of: " << needle_expr << "\n" << " Actual: " << begin_string_quote << needle << "\"\n" << "Expected: " << (expected_to_be_substring ? "" : "not ") << "a substring of " << haystack_expr << "\n" << "Which is: " << begin_string_quote << haystack << "\""; } } // namespace // IsSubstring() and IsNotSubstring() check whether needle is a // substring of haystack (NULL is considered a substring of itself // only), and return an appropriate error message when they fail. AssertionResult IsSubstring( const char* needle_expr, const char* haystack_expr, const char* needle, const char* haystack) { return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack); } AssertionResult IsSubstring( const char* needle_expr, const char* haystack_expr, const wchar_t* needle, const wchar_t* haystack) { return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack); } AssertionResult IsNotSubstring( const char* needle_expr, const char* haystack_expr, const char* needle, const char* haystack) { return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack); } AssertionResult IsNotSubstring( const char* needle_expr, const char* haystack_expr, const wchar_t* needle, const wchar_t* haystack) { return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack); } AssertionResult IsSubstring( const char* needle_expr, const char* haystack_expr, const ::std::string& needle, const ::std::string& haystack) { return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack); } AssertionResult IsNotSubstring( const char* needle_expr, const char* haystack_expr, const ::std::string& needle, const ::std::string& haystack) { return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack); } #if GTEST_HAS_STD_WSTRING AssertionResult IsSubstring( const char* needle_expr, const char* haystack_expr, const ::std::wstring& needle, const ::std::wstring& haystack) { return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack); } AssertionResult IsNotSubstring( const char* needle_expr, const char* haystack_expr, const ::std::wstring& needle, const ::std::wstring& haystack) { return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack); } #endif // GTEST_HAS_STD_WSTRING namespace internal { #if GTEST_OS_WINDOWS namespace { // Helper function for IsHRESULT{SuccessFailure} predicates AssertionResult HRESULTFailureHelper(const char* expr, const char* expected, long hr) { // NOLINT # if GTEST_OS_WINDOWS_MOBILE // Windows CE doesn't support FormatMessage. const char error_text[] = ""; # else // Looks up the human-readable system message for the HRESULT code // and since we're not passing any params to FormatMessage, we don't // want inserts expanded. const DWORD kFlags = FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS; const DWORD kBufSize = 4096; // String::Format can't exceed this length. // Gets the system's human readable message string for this HRESULT. char error_text[kBufSize] = { '\0' }; DWORD message_length = ::FormatMessageA(kFlags, 0, // no source, we're asking system hr, // the error 0, // no line width restrictions error_text, // output buffer kBufSize, // buf size NULL); // no arguments for inserts // Trims tailing white space (FormatMessage leaves a trailing cr-lf) for (; message_length && IsSpace(error_text[message_length - 1]); --message_length) { error_text[message_length - 1] = '\0'; } # endif // GTEST_OS_WINDOWS_MOBILE const String error_hex(String::Format("0x%08X ", hr)); return ::testing::AssertionFailure() << "Expected: " << expr << " " << expected << ".\n" << " Actual: " << error_hex << error_text << "\n"; } } // namespace AssertionResult IsHRESULTSuccess(const char* expr, long hr) { // NOLINT if (SUCCEEDED(hr)) { return AssertionSuccess(); } return HRESULTFailureHelper(expr, "succeeds", hr); } AssertionResult IsHRESULTFailure(const char* expr, long hr) { // NOLINT if (FAILED(hr)) { return AssertionSuccess(); } return HRESULTFailureHelper(expr, "fails", hr); } #endif // GTEST_OS_WINDOWS // Utility functions for encoding Unicode text (wide strings) in // UTF-8. // A Unicode code-point can have upto 21 bits, and is encoded in UTF-8 // like this: // // Code-point length Encoding // 0 - 7 bits 0xxxxxxx // 8 - 11 bits 110xxxxx 10xxxxxx // 12 - 16 bits 1110xxxx 10xxxxxx 10xxxxxx // 17 - 21 bits 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx // The maximum code-point a one-byte UTF-8 sequence can represent. const UInt32 kMaxCodePoint1 = (static_cast(1) << 7) - 1; // The maximum code-point a two-byte UTF-8 sequence can represent. const UInt32 kMaxCodePoint2 = (static_cast(1) << (5 + 6)) - 1; // The maximum code-point a three-byte UTF-8 sequence can represent. const UInt32 kMaxCodePoint3 = (static_cast(1) << (4 + 2*6)) - 1; // The maximum code-point a four-byte UTF-8 sequence can represent. const UInt32 kMaxCodePoint4 = (static_cast(1) << (3 + 3*6)) - 1; // Chops off the n lowest bits from a bit pattern. Returns the n // lowest bits. As a side effect, the original bit pattern will be // shifted to the right by n bits. inline UInt32 ChopLowBits(UInt32* bits, int n) { const UInt32 low_bits = *bits & ((static_cast(1) << n) - 1); *bits >>= n; return low_bits; } // Converts a Unicode code point to a narrow string in UTF-8 encoding. // code_point parameter is of type UInt32 because wchar_t may not be // wide enough to contain a code point. // The output buffer str must containt at least 32 characters. // The function returns the address of the output buffer. // If the code_point is not a valid Unicode code point // (i.e. outside of Unicode range U+0 to U+10FFFF) it will be output // as '(Invalid Unicode 0xXXXXXXXX)'. char* CodePointToUtf8(UInt32 code_point, char* str) { if (code_point <= kMaxCodePoint1) { str[1] = '\0'; str[0] = static_cast(code_point); // 0xxxxxxx } else if (code_point <= kMaxCodePoint2) { str[2] = '\0'; str[1] = static_cast(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx str[0] = static_cast(0xC0 | code_point); // 110xxxxx } else if (code_point <= kMaxCodePoint3) { str[3] = '\0'; str[2] = static_cast(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx str[1] = static_cast(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx str[0] = static_cast(0xE0 | code_point); // 1110xxxx } else if (code_point <= kMaxCodePoint4) { str[4] = '\0'; str[3] = static_cast(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx str[2] = static_cast(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx str[1] = static_cast(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx str[0] = static_cast(0xF0 | code_point); // 11110xxx } else { // The longest string String::Format can produce when invoked // with these parameters is 28 character long (not including // the terminating nul character). We are asking for 32 character // buffer just in case. This is also enough for strncpy to // null-terminate the destination string. posix::StrNCpy( str, String::Format("(Invalid Unicode 0x%X)", code_point).c_str(), 32); str[31] = '\0'; // Makes sure no change in the format to strncpy leaves // the result unterminated. } return str; } // The following two functions only make sense if the the system // uses UTF-16 for wide string encoding. All supported systems // with 16 bit wchar_t (Windows, Cygwin, Symbian OS) do use UTF-16. // Determines if the arguments constitute UTF-16 surrogate pair // and thus should be combined into a single Unicode code point // using CreateCodePointFromUtf16SurrogatePair. inline bool IsUtf16SurrogatePair(wchar_t first, wchar_t second) { return sizeof(wchar_t) == 2 && (first & 0xFC00) == 0xD800 && (second & 0xFC00) == 0xDC00; } // Creates a Unicode code point from UTF16 surrogate pair. inline UInt32 CreateCodePointFromUtf16SurrogatePair(wchar_t first, wchar_t second) { const UInt32 mask = (1 << 10) - 1; return (sizeof(wchar_t) == 2) ? (((first & mask) << 10) | (second & mask)) + 0x10000 : // This function should not be called when the condition is // false, but we provide a sensible default in case it is. static_cast(first); } // Converts a wide string to a narrow string in UTF-8 encoding. // The wide string is assumed to have the following encoding: // UTF-16 if sizeof(wchar_t) == 2 (on Windows, Cygwin, Symbian OS) // UTF-32 if sizeof(wchar_t) == 4 (on Linux) // Parameter str points to a null-terminated wide string. // Parameter num_chars may additionally limit the number // of wchar_t characters processed. -1 is used when the entire string // should be processed. // If the string contains code points that are not valid Unicode code points // (i.e. outside of Unicode range U+0 to U+10FFFF) they will be output // as '(Invalid Unicode 0xXXXXXXXX)'. If the string is in UTF16 encoding // and contains invalid UTF-16 surrogate pairs, values in those pairs // will be encoded as individual Unicode characters from Basic Normal Plane. String WideStringToUtf8(const wchar_t* str, int num_chars) { if (num_chars == -1) num_chars = static_cast(wcslen(str)); ::std::stringstream stream; for (int i = 0; i < num_chars; ++i) { UInt32 unicode_code_point; if (str[i] == L'\0') { break; } else if (i + 1 < num_chars && IsUtf16SurrogatePair(str[i], str[i + 1])) { unicode_code_point = CreateCodePointFromUtf16SurrogatePair(str[i], str[i + 1]); i++; } else { unicode_code_point = static_cast(str[i]); } char buffer[32]; // CodePointToUtf8 requires a buffer this big. stream << CodePointToUtf8(unicode_code_point, buffer); } return StringStreamToString(&stream); } // Converts a wide C string to a String using the UTF-8 encoding. // NULL will be converted to "(null)". String String::ShowWideCString(const wchar_t * wide_c_str) { if (wide_c_str == NULL) return String("(null)"); return String(internal::WideStringToUtf8(wide_c_str, -1).c_str()); } // Similar to ShowWideCString(), except that this function encloses // the converted string in double quotes. String String::ShowWideCStringQuoted(const wchar_t* wide_c_str) { if (wide_c_str == NULL) return String("(null)"); return String::Format("L\"%s\"", String::ShowWideCString(wide_c_str).c_str()); } // Compares two wide C strings. Returns true iff they have the same // content. // // Unlike wcscmp(), this function can handle NULL argument(s). A NULL // C string is considered different to any non-NULL C string, // including the empty string. bool String::WideCStringEquals(const wchar_t * lhs, const wchar_t * rhs) { if (lhs == NULL) return rhs == NULL; if (rhs == NULL) return false; return wcscmp(lhs, rhs) == 0; } // Helper function for *_STREQ on wide strings. AssertionResult CmpHelperSTREQ(const char* expected_expression, const char* actual_expression, const wchar_t* expected, const wchar_t* actual) { if (String::WideCStringEquals(expected, actual)) { return AssertionSuccess(); } return EqFailure(expected_expression, actual_expression, String::ShowWideCStringQuoted(expected), String::ShowWideCStringQuoted(actual), false); } // Helper function for *_STRNE on wide strings. AssertionResult CmpHelperSTRNE(const char* s1_expression, const char* s2_expression, const wchar_t* s1, const wchar_t* s2) { if (!String::WideCStringEquals(s1, s2)) { return AssertionSuccess(); } return AssertionFailure() << "Expected: (" << s1_expression << ") != (" << s2_expression << "), actual: " << String::ShowWideCStringQuoted(s1) << " vs " << String::ShowWideCStringQuoted(s2); } // Compares two C strings, ignoring case. Returns true iff they have // the same content. // // Unlike strcasecmp(), this function can handle NULL argument(s). A // NULL C string is considered different to any non-NULL C string, // including the empty string. bool String::CaseInsensitiveCStringEquals(const char * lhs, const char * rhs) { if (lhs == NULL) return rhs == NULL; if (rhs == NULL) return false; return posix::StrCaseCmp(lhs, rhs) == 0; } // Compares two wide C strings, ignoring case. Returns true iff they // have the same content. // // Unlike wcscasecmp(), this function can handle NULL argument(s). // A NULL C string is considered different to any non-NULL wide C string, // including the empty string. // NB: The implementations on different platforms slightly differ. // On windows, this method uses _wcsicmp which compares according to LC_CTYPE // environment variable. On GNU platform this method uses wcscasecmp // which compares according to LC_CTYPE category of the current locale. // On MacOS X, it uses towlower, which also uses LC_CTYPE category of the // current locale. bool String::CaseInsensitiveWideCStringEquals(const wchar_t* lhs, const wchar_t* rhs) { if (lhs == NULL) return rhs == NULL; if (rhs == NULL) return false; #if GTEST_OS_WINDOWS return _wcsicmp(lhs, rhs) == 0; #elif GTEST_OS_LINUX && !GTEST_OS_LINUX_ANDROID return wcscasecmp(lhs, rhs) == 0; #else // Android, Mac OS X and Cygwin don't define wcscasecmp. // Other unknown OSes may not define it either. wint_t left, right; do { left = towlower(*lhs++); right = towlower(*rhs++); } while (left && left == right); return left == right; #endif // OS selector } // Compares this with another String. // Returns < 0 if this is less than rhs, 0 if this is equal to rhs, or > 0 // if this is greater than rhs. int String::Compare(const String & rhs) const { const char* const lhs_c_str = c_str(); const char* const rhs_c_str = rhs.c_str(); if (lhs_c_str == NULL) { return rhs_c_str == NULL ? 0 : -1; // NULL < anything except NULL } else if (rhs_c_str == NULL) { return 1; } const size_t shorter_str_len = length() <= rhs.length() ? length() : rhs.length(); for (size_t i = 0; i != shorter_str_len; i++) { if (lhs_c_str[i] < rhs_c_str[i]) { return -1; } else if (lhs_c_str[i] > rhs_c_str[i]) { return 1; } } return (length() < rhs.length()) ? -1 : (length() > rhs.length()) ? 1 : 0; } // Returns true iff this String ends with the given suffix. *Any* // String is considered to end with a NULL or empty suffix. bool String::EndsWith(const char* suffix) const { if (suffix == NULL || CStringEquals(suffix, "")) return true; if (c_str() == NULL) return false; const size_t this_len = strlen(c_str()); const size_t suffix_len = strlen(suffix); return (this_len >= suffix_len) && CStringEquals(c_str() + this_len - suffix_len, suffix); } // Returns true iff this String ends with the given suffix, ignoring case. // Any String is considered to end with a NULL or empty suffix. bool String::EndsWithCaseInsensitive(const char* suffix) const { if (suffix == NULL || CStringEquals(suffix, "")) return true; if (c_str() == NULL) return false; const size_t this_len = strlen(c_str()); const size_t suffix_len = strlen(suffix); return (this_len >= suffix_len) && CaseInsensitiveCStringEquals(c_str() + this_len - suffix_len, suffix); } // Formats a list of arguments to a String, using the same format // spec string as for printf. // // We do not use the StringPrintf class as it is not universally // available. // // The result is limited to 4096 characters (including the tailing 0). // If 4096 characters are not enough to format the input, or if // there's an error, "" is // returned. String String::Format(const char * format, ...) { va_list args; va_start(args, format); char buffer[4096]; const int kBufferSize = sizeof(buffer)/sizeof(buffer[0]); // MSVC 8 deprecates vsnprintf(), so we want to suppress warning // 4996 (deprecated function) there. #ifdef _MSC_VER // We are using MSVC. # pragma warning(push) // Saves the current warning state. # pragma warning(disable:4996) // Temporarily disables warning 4996. const int size = vsnprintf(buffer, kBufferSize, format, args); # pragma warning(pop) // Restores the warning state. #else // We are not using MSVC. const int size = vsnprintf(buffer, kBufferSize, format, args); #endif // _MSC_VER va_end(args); // vsnprintf()'s behavior is not portable. When the buffer is not // big enough, it returns a negative value in MSVC, and returns the // needed buffer size on Linux. When there is an output error, it // always returns a negative value. For simplicity, we lump the two // error cases together. if (size < 0 || size >= kBufferSize) { return String(""); } else { return String(buffer, size); } } // Converts the buffer in a stringstream to a String, converting NUL // bytes to "\\0" along the way. String StringStreamToString(::std::stringstream* ss) { const ::std::string& str = ss->str(); const char* const start = str.c_str(); const char* const end = start + str.length(); // We need to use a helper stringstream to do this transformation // because String doesn't support push_back(). ::std::stringstream helper; for (const char* ch = start; ch != end; ++ch) { if (*ch == '\0') { helper << "\\0"; // Replaces NUL with "\\0"; } else { helper.put(*ch); } } return String(helper.str().c_str()); } // Appends the user-supplied message to the Google-Test-generated message. String AppendUserMessage(const String& gtest_msg, const Message& user_msg) { // Appends the user message if it's non-empty. const String user_msg_string = user_msg.GetString(); if (user_msg_string.empty()) { return gtest_msg; } Message msg; msg << gtest_msg << "\n" << user_msg_string; return msg.GetString(); } } // namespace internal // class TestResult // Creates an empty TestResult. TestResult::TestResult() : death_test_count_(0), elapsed_time_(0) { } // D'tor. TestResult::~TestResult() { } // Returns the i-th test part result among all the results. i can // range from 0 to total_part_count() - 1. If i is not in that range, // aborts the program. const TestPartResult& TestResult::GetTestPartResult(int i) const { if (i < 0 || i >= total_part_count()) internal::posix::Abort(); return test_part_results_.at(i); } // Returns the i-th test property. i can range from 0 to // test_property_count() - 1. If i is not in that range, aborts the // program. const TestProperty& TestResult::GetTestProperty(int i) const { if (i < 0 || i >= test_property_count()) internal::posix::Abort(); return test_properties_.at(i); } // Clears the test part results. void TestResult::ClearTestPartResults() { test_part_results_.clear(); } // Adds a test part result to the list. void TestResult::AddTestPartResult(const TestPartResult& test_part_result) { test_part_results_.push_back(test_part_result); } // Adds a test property to the list. If a property with the same key as the // supplied property is already represented, the value of this test_property // replaces the old value for that key. void TestResult::RecordProperty(const TestProperty& test_property) { if (!ValidateTestProperty(test_property)) { return; } internal::MutexLock lock(&test_properites_mutex_); const std::vector::iterator property_with_matching_key = std::find_if(test_properties_.begin(), test_properties_.end(), internal::TestPropertyKeyIs(test_property.key())); if (property_with_matching_key == test_properties_.end()) { test_properties_.push_back(test_property); return; } property_with_matching_key->SetValue(test_property.value()); } // Adds a failure if the key is a reserved attribute of Google Test // testcase tags. Returns true if the property is valid. bool TestResult::ValidateTestProperty(const TestProperty& test_property) { internal::String key(test_property.key()); if (key == "name" || key == "status" || key == "time" || key == "classname") { ADD_FAILURE() << "Reserved key used in RecordProperty(): " << key << " ('name', 'status', 'time', and 'classname' are reserved by " << GTEST_NAME_ << ")"; return false; } return true; } // Clears the object. void TestResult::Clear() { test_part_results_.clear(); test_properties_.clear(); death_test_count_ = 0; elapsed_time_ = 0; } // Returns true iff the test failed. bool TestResult::Failed() const { for (int i = 0; i < total_part_count(); ++i) { if (GetTestPartResult(i).failed()) return true; } return false; } // Returns true iff the test part fatally failed. static bool TestPartFatallyFailed(const TestPartResult& result) { return result.fatally_failed(); } // Returns true iff the test fatally failed. bool TestResult::HasFatalFailure() const { return CountIf(test_part_results_, TestPartFatallyFailed) > 0; } // Returns true iff the test part non-fatally failed. static bool TestPartNonfatallyFailed(const TestPartResult& result) { return result.nonfatally_failed(); } // Returns true iff the test has a non-fatal failure. bool TestResult::HasNonfatalFailure() const { return CountIf(test_part_results_, TestPartNonfatallyFailed) > 0; } // Gets the number of all test parts. This is the sum of the number // of successful test parts and the number of failed test parts. int TestResult::total_part_count() const { return static_cast(test_part_results_.size()); } // Returns the number of the test properties. int TestResult::test_property_count() const { return static_cast(test_properties_.size()); } // class Test // Creates a Test object. // The c'tor saves the values of all Google Test flags. Test::Test() : gtest_flag_saver_(new internal::GTestFlagSaver) { } // The d'tor restores the values of all Google Test flags. Test::~Test() { delete gtest_flag_saver_; } // Sets up the test fixture. // // A sub-class may override this. void Test::SetUp() { } // Tears down the test fixture. // // A sub-class may override this. void Test::TearDown() { } // Allows user supplied key value pairs to be recorded for later output. void Test::RecordProperty(const char* key, const char* value) { UnitTest::GetInstance()->RecordPropertyForCurrentTest(key, value); } // Allows user supplied key value pairs to be recorded for later output. void Test::RecordProperty(const char* key, int value) { Message value_message; value_message << value; RecordProperty(key, value_message.GetString().c_str()); } namespace internal { void ReportFailureInUnknownLocation(TestPartResult::Type result_type, const String& message) { // This function is a friend of UnitTest and as such has access to // AddTestPartResult. UnitTest::GetInstance()->AddTestPartResult( result_type, NULL, // No info about the source file where the exception occurred. -1, // We have no info on which line caused the exception. message, String()); // No stack trace, either. } } // namespace internal // Google Test requires all tests in the same test case to use the same test // fixture class. This function checks if the current test has the // same fixture class as the first test in the current test case. If // yes, it returns true; otherwise it generates a Google Test failure and // returns false. bool Test::HasSameFixtureClass() { internal::UnitTestImpl* const impl = internal::GetUnitTestImpl(); const TestCase* const test_case = impl->current_test_case(); // Info about the first test in the current test case. const TestInfo* const first_test_info = test_case->test_info_list()[0]; const internal::TypeId first_fixture_id = first_test_info->fixture_class_id_; const char* const first_test_name = first_test_info->name(); // Info about the current test. const TestInfo* const this_test_info = impl->current_test_info(); const internal::TypeId this_fixture_id = this_test_info->fixture_class_id_; const char* const this_test_name = this_test_info->name(); if (this_fixture_id != first_fixture_id) { // Is the first test defined using TEST? const bool first_is_TEST = first_fixture_id == internal::GetTestTypeId(); // Is this test defined using TEST? const bool this_is_TEST = this_fixture_id == internal::GetTestTypeId(); if (first_is_TEST || this_is_TEST) { // The user mixed TEST and TEST_F in this test case - we'll tell // him/her how to fix it. // Gets the name of the TEST and the name of the TEST_F. Note // that first_is_TEST and this_is_TEST cannot both be true, as // the fixture IDs are different for the two tests. const char* const TEST_name = first_is_TEST ? first_test_name : this_test_name; const char* const TEST_F_name = first_is_TEST ? this_test_name : first_test_name; ADD_FAILURE() << "All tests in the same test case must use the same test fixture\n" << "class, so mixing TEST_F and TEST in the same test case is\n" << "illegal. In test case " << this_test_info->test_case_name() << ",\n" << "test " << TEST_F_name << " is defined using TEST_F but\n" << "test " << TEST_name << " is defined using TEST. You probably\n" << "want to change the TEST to TEST_F or move it to another test\n" << "case."; } else { // The user defined two fixture classes with the same name in // two namespaces - we'll tell him/her how to fix it. ADD_FAILURE() << "All tests in the same test case must use the same test fixture\n" << "class. However, in test case " << this_test_info->test_case_name() << ",\n" << "you defined test " << first_test_name << " and test " << this_test_name << "\n" << "using two different test fixture classes. This can happen if\n" << "the two classes are from different namespaces or translation\n" << "units and have the same name. You should probably rename one\n" << "of the classes to put the tests into different test cases."; } return false; } return true; } #if GTEST_HAS_SEH // Adds an "exception thrown" fatal failure to the current test. This // function returns its result via an output parameter pointer because VC++ // prohibits creation of objects with destructors on stack in functions // using __try (see error C2712). static internal::String* FormatSehExceptionMessage(DWORD exception_code, const char* location) { Message message; message << "SEH exception with code 0x" << std::setbase(16) << exception_code << std::setbase(10) << " thrown in " << location << "."; return new internal::String(message.GetString()); } #endif // GTEST_HAS_SEH #if GTEST_HAS_EXCEPTIONS // Adds an "exception thrown" fatal failure to the current test. static internal::String FormatCxxExceptionMessage(const char* description, const char* location) { Message message; if (description != NULL) { message << "C++ exception with description \"" << description << "\""; } else { message << "Unknown C++ exception"; } message << " thrown in " << location << "."; return message.GetString(); } static internal::String PrintTestPartResultToString( const TestPartResult& test_part_result); // A failed Google Test assertion will throw an exception of this type when // GTEST_FLAG(throw_on_failure) is true (if exceptions are enabled). We // derive it from std::runtime_error, which is for errors presumably // detectable only at run time. Since std::runtime_error inherits from // std::exception, many testing frameworks know how to extract and print the // message inside it. class GoogleTestFailureException : public ::std::runtime_error { public: explicit GoogleTestFailureException(const TestPartResult& failure) : ::std::runtime_error(PrintTestPartResultToString(failure).c_str()) {} }; #endif // GTEST_HAS_EXCEPTIONS namespace internal { // We put these helper functions in the internal namespace as IBM's xlC // compiler rejects the code if they were declared static. // Runs the given method and handles SEH exceptions it throws, when // SEH is supported; returns the 0-value for type Result in case of an // SEH exception. (Microsoft compilers cannot handle SEH and C++ // exceptions in the same function. Therefore, we provide a separate // wrapper function for handling SEH exceptions.) template Result HandleSehExceptionsInMethodIfSupported( T* object, Result (T::*method)(), const char* location) { #if GTEST_HAS_SEH __try { return (object->*method)(); } __except (internal::UnitTestOptions::GTestShouldProcessSEH( // NOLINT GetExceptionCode())) { // We create the exception message on the heap because VC++ prohibits // creation of objects with destructors on stack in functions using __try // (see error C2712). internal::String* exception_message = FormatSehExceptionMessage( GetExceptionCode(), location); internal::ReportFailureInUnknownLocation(TestPartResult::kFatalFailure, *exception_message); delete exception_message; return static_cast(0); } #else (void)location; return (object->*method)(); #endif // GTEST_HAS_SEH } // Runs the given method and catches and reports C++ and/or SEH-style // exceptions, if they are supported; returns the 0-value for type // Result in case of an SEH exception. template Result HandleExceptionsInMethodIfSupported( T* object, Result (T::*method)(), const char* location) { // NOTE: The user code can affect the way in which Google Test handles // exceptions by setting GTEST_FLAG(catch_exceptions), but only before // RUN_ALL_TESTS() starts. It is technically possible to check the flag // after the exception is caught and either report or re-throw the // exception based on the flag's value: // // try { // // Perform the test method. // } catch (...) { // if (GTEST_FLAG(catch_exceptions)) // // Report the exception as failure. // else // throw; // Re-throws the original exception. // } // // However, the purpose of this flag is to allow the program to drop into // the debugger when the exception is thrown. On most platforms, once the // control enters the catch block, the exception origin information is // lost and the debugger will stop the program at the point of the // re-throw in this function -- instead of at the point of the original // throw statement in the code under test. For this reason, we perform // the check early, sacrificing the ability to affect Google Test's // exception handling in the method where the exception is thrown. if (internal::GetUnitTestImpl()->catch_exceptions()) { #if GTEST_HAS_EXCEPTIONS try { return HandleSehExceptionsInMethodIfSupported(object, method, location); } catch (const GoogleTestFailureException&) { // NOLINT // This exception doesn't originate in code under test. It makes no // sense to report it as a test failure. throw; } catch (const std::exception& e) { // NOLINT internal::ReportFailureInUnknownLocation( TestPartResult::kFatalFailure, FormatCxxExceptionMessage(e.what(), location)); } catch (...) { // NOLINT internal::ReportFailureInUnknownLocation( TestPartResult::kFatalFailure, FormatCxxExceptionMessage(NULL, location)); } return static_cast(0); #else return HandleSehExceptionsInMethodIfSupported(object, method, location); #endif // GTEST_HAS_EXCEPTIONS } else { return (object->*method)(); } } } // namespace internal // Runs the test and updates the test result. void Test::Run() { if (!HasSameFixtureClass()) return; internal::UnitTestImpl* const impl = internal::GetUnitTestImpl(); impl->os_stack_trace_getter()->UponLeavingGTest(); internal::HandleExceptionsInMethodIfSupported(this, &Test::SetUp, "SetUp()"); // We will run the test only if SetUp() was successful. if (!HasFatalFailure()) { impl->os_stack_trace_getter()->UponLeavingGTest(); internal::HandleExceptionsInMethodIfSupported( this, &Test::TestBody, "the test body"); } // However, we want to clean up as much as possible. Hence we will // always call TearDown(), even if SetUp() or the test body has // failed. impl->os_stack_trace_getter()->UponLeavingGTest(); internal::HandleExceptionsInMethodIfSupported( this, &Test::TearDown, "TearDown()"); } // Returns true iff the current test has a fatal failure. bool Test::HasFatalFailure() { return internal::GetUnitTestImpl()->current_test_result()->HasFatalFailure(); } // Returns true iff the current test has a non-fatal failure. bool Test::HasNonfatalFailure() { return internal::GetUnitTestImpl()->current_test_result()-> HasNonfatalFailure(); } // class TestInfo // Constructs a TestInfo object. It assumes ownership of the test factory // object. // TODO(vladl@google.com): Make a_test_case_name and a_name const string&'s // to signify they cannot be NULLs. TestInfo::TestInfo(const char* a_test_case_name, const char* a_name, const char* a_type_param, const char* a_value_param, internal::TypeId fixture_class_id, internal::TestFactoryBase* factory) : test_case_name_(a_test_case_name), name_(a_name), type_param_(a_type_param ? new std::string(a_type_param) : NULL), value_param_(a_value_param ? new std::string(a_value_param) : NULL), fixture_class_id_(fixture_class_id), should_run_(false), is_disabled_(false), matches_filter_(false), factory_(factory), result_() {} // Destructs a TestInfo object. TestInfo::~TestInfo() { delete factory_; } namespace internal { // Creates a new TestInfo object and registers it with Google Test; // returns the created object. // // Arguments: // // test_case_name: name of the test case // name: name of the test // type_param: the name of the test's type parameter, or NULL if // this is not a typed or a type-parameterized test. // value_param: text representation of the test's value parameter, // or NULL if this is not a value-parameterized test. // fixture_class_id: ID of the test fixture class // set_up_tc: pointer to the function that sets up the test case // tear_down_tc: pointer to the function that tears down the test case // factory: pointer to the factory that creates a test object. // The newly created TestInfo instance will assume // ownership of the factory object. TestInfo* MakeAndRegisterTestInfo( const char* test_case_name, const char* name, const char* type_param, const char* value_param, TypeId fixture_class_id, SetUpTestCaseFunc set_up_tc, TearDownTestCaseFunc tear_down_tc, TestFactoryBase* factory) { TestInfo* const test_info = new TestInfo(test_case_name, name, type_param, value_param, fixture_class_id, factory); GetUnitTestImpl()->AddTestInfo(set_up_tc, tear_down_tc, test_info); return test_info; } #if GTEST_HAS_PARAM_TEST void ReportInvalidTestCaseType(const char* test_case_name, const char* file, int line) { Message errors; errors << "Attempted redefinition of test case " << test_case_name << ".\n" << "All tests in the same test case must use the same test fixture\n" << "class. However, in test case " << test_case_name << ", you tried\n" << "to define a test using a fixture class different from the one\n" << "used earlier. This can happen if the two fixture classes are\n" << "from different namespaces and have the same name. You should\n" << "probably rename one of the classes to put the tests into different\n" << "test cases."; fprintf(stderr, "%s %s", FormatFileLocation(file, line).c_str(), errors.GetString().c_str()); } #endif // GTEST_HAS_PARAM_TEST } // namespace internal namespace { // A predicate that checks the test name of a TestInfo against a known // value. // // This is used for implementation of the TestCase class only. We put // it in the anonymous namespace to prevent polluting the outer // namespace. // // TestNameIs is copyable. class TestNameIs { public: // Constructor. // // TestNameIs has NO default constructor. explicit TestNameIs(const char* name) : name_(name) {} // Returns true iff the test name of test_info matches name_. bool operator()(const TestInfo * test_info) const { return test_info && internal::String(test_info->name()).Compare(name_) == 0; } private: internal::String name_; }; } // namespace namespace internal { // This method expands all parameterized tests registered with macros TEST_P // and INSTANTIATE_TEST_CASE_P into regular tests and registers those. // This will be done just once during the program runtime. void UnitTestImpl::RegisterParameterizedTests() { #if GTEST_HAS_PARAM_TEST if (!parameterized_tests_registered_) { parameterized_test_registry_.RegisterTests(); parameterized_tests_registered_ = true; } #endif } } // namespace internal // Creates the test object, runs it, records its result, and then // deletes it. void TestInfo::Run() { if (!should_run_) return; // Tells UnitTest where to store test result. internal::UnitTestImpl* const impl = internal::GetUnitTestImpl(); impl->set_current_test_info(this); TestEventListener* repeater = UnitTest::GetInstance()->listeners().repeater(); // Notifies the unit test event listeners that a test is about to start. repeater->OnTestStart(*this); const TimeInMillis start = internal::GetTimeInMillis(); impl->os_stack_trace_getter()->UponLeavingGTest(); // Creates the test object. Test* const test = internal::HandleExceptionsInMethodIfSupported( factory_, &internal::TestFactoryBase::CreateTest, "the test fixture's constructor"); // Runs the test only if the test object was created and its // constructor didn't generate a fatal failure. if ((test != NULL) && !Test::HasFatalFailure()) { // This doesn't throw as all user code that can throw are wrapped into // exception handling code. test->Run(); } // Deletes the test object. impl->os_stack_trace_getter()->UponLeavingGTest(); internal::HandleExceptionsInMethodIfSupported( test, &Test::DeleteSelf_, "the test fixture's destructor"); result_.set_elapsed_time(internal::GetTimeInMillis() - start); // Notifies the unit test event listener that a test has just finished. repeater->OnTestEnd(*this); // Tells UnitTest to stop associating assertion results to this // test. impl->set_current_test_info(NULL); } // class TestCase // Gets the number of successful tests in this test case. int TestCase::successful_test_count() const { return CountIf(test_info_list_, TestPassed); } // Gets the number of failed tests in this test case. int TestCase::failed_test_count() const { return CountIf(test_info_list_, TestFailed); } int TestCase::disabled_test_count() const { return CountIf(test_info_list_, TestDisabled); } // Get the number of tests in this test case that should run. int TestCase::test_to_run_count() const { return CountIf(test_info_list_, ShouldRunTest); } // Gets the number of all tests. int TestCase::total_test_count() const { return static_cast(test_info_list_.size()); } // Creates a TestCase with the given name. // // Arguments: // // name: name of the test case // a_type_param: the name of the test case's type parameter, or NULL if // this is not a typed or a type-parameterized test case. // set_up_tc: pointer to the function that sets up the test case // tear_down_tc: pointer to the function that tears down the test case TestCase::TestCase(const char* a_name, const char* a_type_param, Test::SetUpTestCaseFunc set_up_tc, Test::TearDownTestCaseFunc tear_down_tc) : name_(a_name), type_param_(a_type_param ? new std::string(a_type_param) : NULL), set_up_tc_(set_up_tc), tear_down_tc_(tear_down_tc), should_run_(false), elapsed_time_(0) { } // Destructor of TestCase. TestCase::~TestCase() { // Deletes every Test in the collection. ForEach(test_info_list_, internal::Delete); } // Returns the i-th test among all the tests. i can range from 0 to // total_test_count() - 1. If i is not in that range, returns NULL. const TestInfo* TestCase::GetTestInfo(int i) const { const int index = GetElementOr(test_indices_, i, -1); return index < 0 ? NULL : test_info_list_[index]; } // Returns the i-th test among all the tests. i can range from 0 to // total_test_count() - 1. If i is not in that range, returns NULL. TestInfo* TestCase::GetMutableTestInfo(int i) { const int index = GetElementOr(test_indices_, i, -1); return index < 0 ? NULL : test_info_list_[index]; } // Adds a test to this test case. Will delete the test upon // destruction of the TestCase object. void TestCase::AddTestInfo(TestInfo * test_info) { test_info_list_.push_back(test_info); test_indices_.push_back(static_cast(test_indices_.size())); } // Runs every test in this TestCase. void TestCase::Run() { if (!should_run_) return; internal::UnitTestImpl* const impl = internal::GetUnitTestImpl(); impl->set_current_test_case(this); TestEventListener* repeater = UnitTest::GetInstance()->listeners().repeater(); repeater->OnTestCaseStart(*this); impl->os_stack_trace_getter()->UponLeavingGTest(); internal::HandleExceptionsInMethodIfSupported( this, &TestCase::RunSetUpTestCase, "SetUpTestCase()"); const internal::TimeInMillis start = internal::GetTimeInMillis(); for (int i = 0; i < total_test_count(); i++) { GetMutableTestInfo(i)->Run(); } elapsed_time_ = internal::GetTimeInMillis() - start; impl->os_stack_trace_getter()->UponLeavingGTest(); internal::HandleExceptionsInMethodIfSupported( this, &TestCase::RunTearDownTestCase, "TearDownTestCase()"); repeater->OnTestCaseEnd(*this); impl->set_current_test_case(NULL); } // Clears the results of all tests in this test case. void TestCase::ClearResult() { ForEach(test_info_list_, TestInfo::ClearTestResult); } // Shuffles the tests in this test case. void TestCase::ShuffleTests(internal::Random* random) { Shuffle(random, &test_indices_); } // Restores the test order to before the first shuffle. void TestCase::UnshuffleTests() { for (size_t i = 0; i < test_indices_.size(); i++) { test_indices_[i] = static_cast(i); } } // Formats a countable noun. Depending on its quantity, either the // singular form or the plural form is used. e.g. // // FormatCountableNoun(1, "formula", "formuli") returns "1 formula". // FormatCountableNoun(5, "book", "books") returns "5 books". static internal::String FormatCountableNoun(int count, const char * singular_form, const char * plural_form) { return internal::String::Format("%d %s", count, count == 1 ? singular_form : plural_form); } // Formats the count of tests. static internal::String FormatTestCount(int test_count) { return FormatCountableNoun(test_count, "test", "tests"); } // Formats the count of test cases. static internal::String FormatTestCaseCount(int test_case_count) { return FormatCountableNoun(test_case_count, "test case", "test cases"); } // Converts a TestPartResult::Type enum to human-friendly string // representation. Both kNonFatalFailure and kFatalFailure are translated // to "Failure", as the user usually doesn't care about the difference // between the two when viewing the test result. static const char * TestPartResultTypeToString(TestPartResult::Type type) { switch (type) { case TestPartResult::kSuccess: return "Success"; case TestPartResult::kNonFatalFailure: case TestPartResult::kFatalFailure: #ifdef _MSC_VER return "error: "; #else return "Failure\n"; #endif default: return "Unknown result type"; } } // Prints a TestPartResult to a String. static internal::String PrintTestPartResultToString( const TestPartResult& test_part_result) { return (Message() << internal::FormatFileLocation(test_part_result.file_name(), test_part_result.line_number()) << " " << TestPartResultTypeToString(test_part_result.type()) << test_part_result.message()).GetString(); } // Prints a TestPartResult. static void PrintTestPartResult(const TestPartResult& test_part_result) { const internal::String& result = PrintTestPartResultToString(test_part_result); printf("%s\n", result.c_str()); fflush(stdout); // If the test program runs in Visual Studio or a debugger, the // following statements add the test part result message to the Output // window such that the user can double-click on it to jump to the // corresponding source code location; otherwise they do nothing. #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE // We don't call OutputDebugString*() on Windows Mobile, as printing // to stdout is done by OutputDebugString() there already - we don't // want the same message printed twice. ::OutputDebugStringA(result.c_str()); ::OutputDebugStringA("\n"); #endif } // class PrettyUnitTestResultPrinter namespace internal { enum GTestColor { COLOR_DEFAULT, COLOR_RED, COLOR_GREEN, COLOR_YELLOW }; #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE // Returns the character attribute for the given color. WORD GetColorAttribute(GTestColor color) { switch (color) { case COLOR_RED: return FOREGROUND_RED; case COLOR_GREEN: return FOREGROUND_GREEN; case COLOR_YELLOW: return FOREGROUND_RED | FOREGROUND_GREEN; default: return 0; } } #else // Returns the ANSI color code for the given color. COLOR_DEFAULT is // an invalid input. const char* GetAnsiColorCode(GTestColor color) { switch (color) { case COLOR_RED: return "1"; case COLOR_GREEN: return "2"; case COLOR_YELLOW: return "3"; default: return NULL; }; } #endif // GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE // Returns true iff Google Test should use colors in the output. bool ShouldUseColor(bool stdout_is_tty) { const char* const gtest_color = GTEST_FLAG(color).c_str(); if (String::CaseInsensitiveCStringEquals(gtest_color, "auto")) { #if GTEST_OS_WINDOWS // On Windows the TERM variable is usually not set, but the // console there does support colors. return stdout_is_tty; #else // On non-Windows platforms, we rely on the TERM variable. const char* const term = posix::GetEnv("TERM"); const bool term_supports_color = String::CStringEquals(term, "xterm") || String::CStringEquals(term, "xterm-color") || String::CStringEquals(term, "xterm-256color") || String::CStringEquals(term, "screen") || String::CStringEquals(term, "linux") || String::CStringEquals(term, "cygwin"); return stdout_is_tty && term_supports_color; #endif // GTEST_OS_WINDOWS } return String::CaseInsensitiveCStringEquals(gtest_color, "yes") || String::CaseInsensitiveCStringEquals(gtest_color, "true") || String::CaseInsensitiveCStringEquals(gtest_color, "t") || String::CStringEquals(gtest_color, "1"); // We take "yes", "true", "t", and "1" as meaning "yes". If the // value is neither one of these nor "auto", we treat it as "no" to // be conservative. } // Helpers for printing colored strings to stdout. Note that on Windows, we // cannot simply emit special characters and have the terminal change colors. // This routine must actually emit the characters rather than return a string // that would be colored when printed, as can be done on Linux. void ColoredPrintf(GTestColor color, const char* fmt, ...) { va_list args; va_start(args, fmt); #if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_SYMBIAN || GTEST_OS_ZOS const bool use_color = false; #else static const bool in_color_mode = ShouldUseColor(posix::IsATTY(posix::FileNo(stdout)) != 0); const bool use_color = in_color_mode && (color != COLOR_DEFAULT); #endif // GTEST_OS_WINDOWS_MOBILE || GTEST_OS_SYMBIAN || GTEST_OS_ZOS // The '!= 0' comparison is necessary to satisfy MSVC 7.1. if (!use_color) { vprintf(fmt, args); va_end(args); return; } #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE const HANDLE stdout_handle = GetStdHandle(STD_OUTPUT_HANDLE); // Gets the current text color. CONSOLE_SCREEN_BUFFER_INFO buffer_info; GetConsoleScreenBufferInfo(stdout_handle, &buffer_info); const WORD old_color_attrs = buffer_info.wAttributes; // We need to flush the stream buffers into the console before each // SetConsoleTextAttribute call lest it affect the text that is already // printed but has not yet reached the console. fflush(stdout); SetConsoleTextAttribute(stdout_handle, GetColorAttribute(color) | FOREGROUND_INTENSITY); vprintf(fmt, args); fflush(stdout); // Restores the text color. SetConsoleTextAttribute(stdout_handle, old_color_attrs); #else printf("\033[0;3%sm", GetAnsiColorCode(color)); vprintf(fmt, args); printf("\033[m"); // Resets the terminal to default. #endif // GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE va_end(args); } void PrintFullTestCommentIfPresent(const TestInfo& test_info) { const char* const type_param = test_info.type_param(); const char* const value_param = test_info.value_param(); if (type_param != NULL || value_param != NULL) { printf(", where "); if (type_param != NULL) { printf("TypeParam = %s", type_param); if (value_param != NULL) printf(" and "); } if (value_param != NULL) { printf("GetParam() = %s", value_param); } } } // This class implements the TestEventListener interface. // // Class PrettyUnitTestResultPrinter is copyable. class PrettyUnitTestResultPrinter : public TestEventListener { public: PrettyUnitTestResultPrinter() {} static void PrintTestName(const char * test_case, const char * test) { printf("%s.%s", test_case, test); } // The following methods override what's in the TestEventListener class. virtual void OnTestProgramStart(const UnitTest& /*unit_test*/) {} virtual void OnTestIterationStart(const UnitTest& unit_test, int iteration); virtual void OnEnvironmentsSetUpStart(const UnitTest& unit_test); virtual void OnEnvironmentsSetUpEnd(const UnitTest& /*unit_test*/) {} virtual void OnTestCaseStart(const TestCase& test_case); virtual void OnTestStart(const TestInfo& test_info); virtual void OnTestPartResult(const TestPartResult& result); virtual void OnTestEnd(const TestInfo& test_info); virtual void OnTestCaseEnd(const TestCase& test_case); virtual void OnEnvironmentsTearDownStart(const UnitTest& unit_test); virtual void OnEnvironmentsTearDownEnd(const UnitTest& /*unit_test*/) {} virtual void OnTestIterationEnd(const UnitTest& unit_test, int iteration); virtual void OnTestProgramEnd(const UnitTest& /*unit_test*/) {} private: static void PrintFailedTests(const UnitTest& unit_test); internal::String test_case_name_; }; // Fired before each iteration of tests starts. void PrettyUnitTestResultPrinter::OnTestIterationStart( const UnitTest& unit_test, int iteration) { if (GTEST_FLAG(repeat) != 1) printf("\nRepeating all tests (iteration %d) . . .\n\n", iteration + 1); const char* const filter = GTEST_FLAG(filter).c_str(); // Prints the filter if it's not *. This reminds the user that some // tests may be skipped. if (!internal::String::CStringEquals(filter, kUniversalFilter)) { ColoredPrintf(COLOR_YELLOW, "Note: %s filter = %s\n", GTEST_NAME_, filter); } if (internal::ShouldShard(kTestTotalShards, kTestShardIndex, false)) { const Int32 shard_index = Int32FromEnvOrDie(kTestShardIndex, -1); ColoredPrintf(COLOR_YELLOW, "Note: This is test shard %d of %s.\n", static_cast(shard_index) + 1, internal::posix::GetEnv(kTestTotalShards)); } if (GTEST_FLAG(shuffle)) { ColoredPrintf(COLOR_YELLOW, "Note: Randomizing tests' orders with a seed of %d .\n", unit_test.random_seed()); } ColoredPrintf(COLOR_GREEN, "[==========] "); printf("Running %s from %s.\n", FormatTestCount(unit_test.test_to_run_count()).c_str(), FormatTestCaseCount(unit_test.test_case_to_run_count()).c_str()); fflush(stdout); } void PrettyUnitTestResultPrinter::OnEnvironmentsSetUpStart( const UnitTest& /*unit_test*/) { ColoredPrintf(COLOR_GREEN, "[----------] "); printf("Global test environment set-up.\n"); fflush(stdout); } void PrettyUnitTestResultPrinter::OnTestCaseStart(const TestCase& test_case) { test_case_name_ = test_case.name(); const internal::String counts = FormatCountableNoun(test_case.test_to_run_count(), "test", "tests"); ColoredPrintf(COLOR_GREEN, "[----------] "); printf("%s from %s", counts.c_str(), test_case_name_.c_str()); if (test_case.type_param() == NULL) { printf("\n"); } else { printf(", where TypeParam = %s\n", test_case.type_param()); } fflush(stdout); } void PrettyUnitTestResultPrinter::OnTestStart(const TestInfo& test_info) { ColoredPrintf(COLOR_GREEN, "[ RUN ] "); PrintTestName(test_case_name_.c_str(), test_info.name()); printf("\n"); fflush(stdout); } // Called after an assertion failure. void PrettyUnitTestResultPrinter::OnTestPartResult( const TestPartResult& result) { // If the test part succeeded, we don't need to do anything. if (result.type() == TestPartResult::kSuccess) return; // Print failure message from the assertion (e.g. expected this and got that). PrintTestPartResult(result); fflush(stdout); } void PrettyUnitTestResultPrinter::OnTestEnd(const TestInfo& test_info) { if (test_info.result()->Passed()) { ColoredPrintf(COLOR_GREEN, "[ OK ] "); } else { ColoredPrintf(COLOR_RED, "[ FAILED ] "); } PrintTestName(test_case_name_.c_str(), test_info.name()); if (test_info.result()->Failed()) PrintFullTestCommentIfPresent(test_info); if (GTEST_FLAG(print_time)) { printf(" (%s ms)\n", internal::StreamableToString( test_info.result()->elapsed_time()).c_str()); } else { printf("\n"); } fflush(stdout); } void PrettyUnitTestResultPrinter::OnTestCaseEnd(const TestCase& test_case) { if (!GTEST_FLAG(print_time)) return; test_case_name_ = test_case.name(); const internal::String counts = FormatCountableNoun(test_case.test_to_run_count(), "test", "tests"); ColoredPrintf(COLOR_GREEN, "[----------] "); printf("%s from %s (%s ms total)\n\n", counts.c_str(), test_case_name_.c_str(), internal::StreamableToString(test_case.elapsed_time()).c_str()); fflush(stdout); } void PrettyUnitTestResultPrinter::OnEnvironmentsTearDownStart( const UnitTest& /*unit_test*/) { ColoredPrintf(COLOR_GREEN, "[----------] "); printf("Global test environment tear-down\n"); fflush(stdout); } // Internal helper for printing the list of failed tests. void PrettyUnitTestResultPrinter::PrintFailedTests(const UnitTest& unit_test) { const int failed_test_count = unit_test.failed_test_count(); if (failed_test_count == 0) { return; } for (int i = 0; i < unit_test.total_test_case_count(); ++i) { const TestCase& test_case = *unit_test.GetTestCase(i); if (!test_case.should_run() || (test_case.failed_test_count() == 0)) { continue; } for (int j = 0; j < test_case.total_test_count(); ++j) { const TestInfo& test_info = *test_case.GetTestInfo(j); if (!test_info.should_run() || test_info.result()->Passed()) { continue; } ColoredPrintf(COLOR_RED, "[ FAILED ] "); printf("%s.%s", test_case.name(), test_info.name()); PrintFullTestCommentIfPresent(test_info); printf("\n"); } } } void PrettyUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test, int /*iteration*/) { ColoredPrintf(COLOR_GREEN, "[==========] "); printf("%s from %s ran.", FormatTestCount(unit_test.test_to_run_count()).c_str(), FormatTestCaseCount(unit_test.test_case_to_run_count()).c_str()); if (GTEST_FLAG(print_time)) { printf(" (%s ms total)", internal::StreamableToString(unit_test.elapsed_time()).c_str()); } printf("\n"); ColoredPrintf(COLOR_GREEN, "[ PASSED ] "); printf("%s.\n", FormatTestCount(unit_test.successful_test_count()).c_str()); int num_failures = unit_test.failed_test_count(); if (!unit_test.Passed()) { const int failed_test_count = unit_test.failed_test_count(); ColoredPrintf(COLOR_RED, "[ FAILED ] "); printf("%s, listed below:\n", FormatTestCount(failed_test_count).c_str()); PrintFailedTests(unit_test); printf("\n%2d FAILED %s\n", num_failures, num_failures == 1 ? "TEST" : "TESTS"); } int num_disabled = unit_test.disabled_test_count(); if (num_disabled && !GTEST_FLAG(also_run_disabled_tests)) { if (!num_failures) { printf("\n"); // Add a spacer if no FAILURE banner is displayed. } ColoredPrintf(COLOR_YELLOW, " YOU HAVE %d DISABLED %s\n\n", num_disabled, num_disabled == 1 ? "TEST" : "TESTS"); } // Ensure that Google Test output is printed before, e.g., heapchecker output. fflush(stdout); } // End PrettyUnitTestResultPrinter // class TestEventRepeater // // This class forwards events to other event listeners. class TestEventRepeater : public TestEventListener { public: TestEventRepeater() : forwarding_enabled_(true) {} virtual ~TestEventRepeater(); void Append(TestEventListener *listener); TestEventListener* Release(TestEventListener* listener); // Controls whether events will be forwarded to listeners_. Set to false // in death test child processes. bool forwarding_enabled() const { return forwarding_enabled_; } void set_forwarding_enabled(bool enable) { forwarding_enabled_ = enable; } virtual void OnTestProgramStart(const UnitTest& unit_test); virtual void OnTestIterationStart(const UnitTest& unit_test, int iteration); virtual void OnEnvironmentsSetUpStart(const UnitTest& unit_test); virtual void OnEnvironmentsSetUpEnd(const UnitTest& unit_test); virtual void OnTestCaseStart(const TestCase& test_case); virtual void OnTestStart(const TestInfo& test_info); virtual void OnTestPartResult(const TestPartResult& result); virtual void OnTestEnd(const TestInfo& test_info); virtual void OnTestCaseEnd(const TestCase& test_case); virtual void OnEnvironmentsTearDownStart(const UnitTest& unit_test); virtual void OnEnvironmentsTearDownEnd(const UnitTest& unit_test); virtual void OnTestIterationEnd(const UnitTest& unit_test, int iteration); virtual void OnTestProgramEnd(const UnitTest& unit_test); private: // Controls whether events will be forwarded to listeners_. Set to false // in death test child processes. bool forwarding_enabled_; // The list of listeners that receive events. std::vector listeners_; GTEST_DISALLOW_COPY_AND_ASSIGN_(TestEventRepeater); }; TestEventRepeater::~TestEventRepeater() { ForEach(listeners_, Delete); } void TestEventRepeater::Append(TestEventListener *listener) { listeners_.push_back(listener); } // TODO(vladl@google.com): Factor the search functionality into Vector::Find. TestEventListener* TestEventRepeater::Release(TestEventListener *listener) { for (size_t i = 0; i < listeners_.size(); ++i) { if (listeners_[i] == listener) { listeners_.erase(listeners_.begin() + i); return listener; } } return NULL; } // Since most methods are very similar, use macros to reduce boilerplate. // This defines a member that forwards the call to all listeners. #define GTEST_REPEATER_METHOD_(Name, Type) \ void TestEventRepeater::Name(const Type& parameter) { \ if (forwarding_enabled_) { \ for (size_t i = 0; i < listeners_.size(); i++) { \ listeners_[i]->Name(parameter); \ } \ } \ } // This defines a member that forwards the call to all listeners in reverse // order. #define GTEST_REVERSE_REPEATER_METHOD_(Name, Type) \ void TestEventRepeater::Name(const Type& parameter) { \ if (forwarding_enabled_) { \ for (int i = static_cast(listeners_.size()) - 1; i >= 0; i--) { \ listeners_[i]->Name(parameter); \ } \ } \ } GTEST_REPEATER_METHOD_(OnTestProgramStart, UnitTest) GTEST_REPEATER_METHOD_(OnEnvironmentsSetUpStart, UnitTest) GTEST_REPEATER_METHOD_(OnTestCaseStart, TestCase) GTEST_REPEATER_METHOD_(OnTestStart, TestInfo) GTEST_REPEATER_METHOD_(OnTestPartResult, TestPartResult) GTEST_REPEATER_METHOD_(OnEnvironmentsTearDownStart, UnitTest) GTEST_REVERSE_REPEATER_METHOD_(OnEnvironmentsSetUpEnd, UnitTest) GTEST_REVERSE_REPEATER_METHOD_(OnEnvironmentsTearDownEnd, UnitTest) GTEST_REVERSE_REPEATER_METHOD_(OnTestEnd, TestInfo) GTEST_REVERSE_REPEATER_METHOD_(OnTestCaseEnd, TestCase) GTEST_REVERSE_REPEATER_METHOD_(OnTestProgramEnd, UnitTest) #undef GTEST_REPEATER_METHOD_ #undef GTEST_REVERSE_REPEATER_METHOD_ void TestEventRepeater::OnTestIterationStart(const UnitTest& unit_test, int iteration) { if (forwarding_enabled_) { for (size_t i = 0; i < listeners_.size(); i++) { listeners_[i]->OnTestIterationStart(unit_test, iteration); } } } void TestEventRepeater::OnTestIterationEnd(const UnitTest& unit_test, int iteration) { if (forwarding_enabled_) { for (int i = static_cast(listeners_.size()) - 1; i >= 0; i--) { listeners_[i]->OnTestIterationEnd(unit_test, iteration); } } } // End TestEventRepeater // This class generates an XML output file. class XmlUnitTestResultPrinter : public EmptyTestEventListener { public: explicit XmlUnitTestResultPrinter(const char* output_file); virtual void OnTestIterationEnd(const UnitTest& unit_test, int iteration); private: // Is c a whitespace character that is normalized to a space character // when it appears in an XML attribute value? static bool IsNormalizableWhitespace(char c) { return c == 0x9 || c == 0xA || c == 0xD; } // May c appear in a well-formed XML document? static bool IsValidXmlCharacter(char c) { return IsNormalizableWhitespace(c) || c >= 0x20; } // Returns an XML-escaped copy of the input string str. If // is_attribute is true, the text is meant to appear as an attribute // value, and normalizable whitespace is preserved by replacing it // with character references. static String EscapeXml(const char* str, bool is_attribute); // Returns the given string with all characters invalid in XML removed. static string RemoveInvalidXmlCharacters(const string& str); // Convenience wrapper around EscapeXml when str is an attribute value. static String EscapeXmlAttribute(const char* str) { return EscapeXml(str, true); } // Convenience wrapper around EscapeXml when str is not an attribute value. static String EscapeXmlText(const char* str) { return EscapeXml(str, false); } // Streams an XML CDATA section, escaping invalid CDATA sequences as needed. static void OutputXmlCDataSection(::std::ostream* stream, const char* data); // Streams an XML representation of a TestInfo object. static void OutputXmlTestInfo(::std::ostream* stream, const char* test_case_name, const TestInfo& test_info); // Prints an XML representation of a TestCase object static void PrintXmlTestCase(FILE* out, const TestCase& test_case); // Prints an XML summary of unit_test to output stream out. static void PrintXmlUnitTest(FILE* out, const UnitTest& unit_test); // Produces a string representing the test properties in a result as space // delimited XML attributes based on the property key="value" pairs. // When the String is not empty, it includes a space at the beginning, // to delimit this attribute from prior attributes. static String TestPropertiesAsXmlAttributes(const TestResult& result); // The output file. const String output_file_; GTEST_DISALLOW_COPY_AND_ASSIGN_(XmlUnitTestResultPrinter); }; // Creates a new XmlUnitTestResultPrinter. XmlUnitTestResultPrinter::XmlUnitTestResultPrinter(const char* output_file) : output_file_(output_file) { if (output_file_.c_str() == NULL || output_file_.empty()) { fprintf(stderr, "XML output file may not be null\n"); fflush(stderr); exit(EXIT_FAILURE); } } // Called after the unit test ends. void XmlUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test, int /*iteration*/) { FILE* xmlout = NULL; FilePath output_file(output_file_); FilePath output_dir(output_file.RemoveFileName()); if (output_dir.CreateDirectoriesRecursively()) { xmlout = posix::FOpen(output_file_.c_str(), "w"); } if (xmlout == NULL) { // TODO(wan): report the reason of the failure. // // We don't do it for now as: // // 1. There is no urgent need for it. // 2. It's a bit involved to make the errno variable thread-safe on // all three operating systems (Linux, Windows, and Mac OS). // 3. To interpret the meaning of errno in a thread-safe way, // we need the strerror_r() function, which is not available on // Windows. fprintf(stderr, "Unable to open file \"%s\"\n", output_file_.c_str()); fflush(stderr); exit(EXIT_FAILURE); } PrintXmlUnitTest(xmlout, unit_test); fclose(xmlout); } // Returns an XML-escaped copy of the input string str. If is_attribute // is true, the text is meant to appear as an attribute value, and // normalizable whitespace is preserved by replacing it with character // references. // // Invalid XML characters in str, if any, are stripped from the output. // It is expected that most, if not all, of the text processed by this // module will consist of ordinary English text. // If this module is ever modified to produce version 1.1 XML output, // most invalid characters can be retained using character references. // TODO(wan): It might be nice to have a minimally invasive, human-readable // escaping scheme for invalid characters, rather than dropping them. String XmlUnitTestResultPrinter::EscapeXml(const char* str, bool is_attribute) { Message m; if (str != NULL) { for (const char* src = str; *src; ++src) { switch (*src) { case '<': m << "<"; break; case '>': m << ">"; break; case '&': m << "&"; break; case '\'': if (is_attribute) m << "'"; else m << '\''; break; case '"': if (is_attribute) m << """; else m << '"'; break; default: if (IsValidXmlCharacter(*src)) { if (is_attribute && IsNormalizableWhitespace(*src)) m << String::Format("&#x%02X;", unsigned(*src)); else m << *src; } break; } } } return m.GetString(); } // Returns the given string with all characters invalid in XML removed. // Currently invalid characters are dropped from the string. An // alternative is to replace them with certain characters such as . or ?. string XmlUnitTestResultPrinter::RemoveInvalidXmlCharacters(const string& str) { string output; output.reserve(str.size()); for (string::const_iterator it = str.begin(); it != str.end(); ++it) if (IsValidXmlCharacter(*it)) output.push_back(*it); return output; } // The following routines generate an XML representation of a UnitTest // object. // // This is how Google Test concepts map to the DTD: // // <-- corresponds to a UnitTest object // <-- corresponds to a TestCase object // <-- corresponds to a TestInfo object // ... // ... // ... // <-- individual assertion failures // // // // Formats the given time in milliseconds as seconds. std::string FormatTimeInMillisAsSeconds(TimeInMillis ms) { ::std::stringstream ss; ss << ms/1000.0; return ss.str(); } // Streams an XML CDATA section, escaping invalid CDATA sequences as needed. void XmlUnitTestResultPrinter::OutputXmlCDataSection(::std::ostream* stream, const char* data) { const char* segment = data; *stream << ""); if (next_segment != NULL) { stream->write( segment, static_cast(next_segment - segment)); *stream << "]]>]]>"); } else { *stream << segment; break; } } *stream << "]]>"; } // Prints an XML representation of a TestInfo object. // TODO(wan): There is also value in printing properties with the plain printer. void XmlUnitTestResultPrinter::OutputXmlTestInfo(::std::ostream* stream, const char* test_case_name, const TestInfo& test_info) { const TestResult& result = *test_info.result(); *stream << " \n"; *stream << " "; const string location = internal::FormatCompilerIndependentFileLocation( part.file_name(), part.line_number()); const string message = location + "\n" + part.message(); OutputXmlCDataSection(stream, RemoveInvalidXmlCharacters(message).c_str()); *stream << "\n"; } } if (failures == 0) *stream << " />\n"; else *stream << " \n"; } // Prints an XML representation of a TestCase object void XmlUnitTestResultPrinter::PrintXmlTestCase(FILE* out, const TestCase& test_case) { fprintf(out, " \n", FormatTimeInMillisAsSeconds(test_case.elapsed_time()).c_str()); for (int i = 0; i < test_case.total_test_count(); ++i) { ::std::stringstream stream; OutputXmlTestInfo(&stream, test_case.name(), *test_case.GetTestInfo(i)); fprintf(out, "%s", StringStreamToString(&stream).c_str()); } fprintf(out, " \n"); } // Prints an XML summary of unit_test to output stream out. void XmlUnitTestResultPrinter::PrintXmlUnitTest(FILE* out, const UnitTest& unit_test) { fprintf(out, "\n"); fprintf(out, "\n"); for (int i = 0; i < unit_test.total_test_case_count(); ++i) PrintXmlTestCase(out, *unit_test.GetTestCase(i)); fprintf(out, "\n"); } // Produces a string representing the test properties in a result as space // delimited XML attributes based on the property key="value" pairs. String XmlUnitTestResultPrinter::TestPropertiesAsXmlAttributes( const TestResult& result) { Message attributes; for (int i = 0; i < result.test_property_count(); ++i) { const TestProperty& property = result.GetTestProperty(i); attributes << " " << property.key() << "=" << "\"" << EscapeXmlAttribute(property.value()) << "\""; } return attributes.GetString(); } // End XmlUnitTestResultPrinter #if GTEST_CAN_STREAM_RESULTS_ // Streams test results to the given port on the given host machine. class StreamingListener : public EmptyTestEventListener { public: // Escapes '=', '&', '%', and '\n' characters in str as "%xx". static string UrlEncode(const char* str); StreamingListener(const string& host, const string& port) : sockfd_(-1), host_name_(host), port_num_(port) { MakeConnection(); Send("gtest_streaming_protocol_version=1.0\n"); } virtual ~StreamingListener() { if (sockfd_ != -1) CloseConnection(); } void OnTestProgramStart(const UnitTest& /* unit_test */) { Send("event=TestProgramStart\n"); } void OnTestProgramEnd(const UnitTest& unit_test) { // Note that Google Test current only report elapsed time for each // test iteration, not for the entire test program. Send(String::Format("event=TestProgramEnd&passed=%d\n", unit_test.Passed())); // Notify the streaming server to stop. CloseConnection(); } void OnTestIterationStart(const UnitTest& /* unit_test */, int iteration) { Send(String::Format("event=TestIterationStart&iteration=%d\n", iteration)); } void OnTestIterationEnd(const UnitTest& unit_test, int /* iteration */) { Send(String::Format("event=TestIterationEnd&passed=%d&elapsed_time=%sms\n", unit_test.Passed(), StreamableToString(unit_test.elapsed_time()).c_str())); } void OnTestCaseStart(const TestCase& test_case) { Send(String::Format("event=TestCaseStart&name=%s\n", test_case.name())); } void OnTestCaseEnd(const TestCase& test_case) { Send(String::Format("event=TestCaseEnd&passed=%d&elapsed_time=%sms\n", test_case.Passed(), StreamableToString(test_case.elapsed_time()).c_str())); } void OnTestStart(const TestInfo& test_info) { Send(String::Format("event=TestStart&name=%s\n", test_info.name())); } void OnTestEnd(const TestInfo& test_info) { Send(String::Format( "event=TestEnd&passed=%d&elapsed_time=%sms\n", (test_info.result())->Passed(), StreamableToString((test_info.result())->elapsed_time()).c_str())); } void OnTestPartResult(const TestPartResult& test_part_result) { const char* file_name = test_part_result.file_name(); if (file_name == NULL) file_name = ""; Send(String::Format("event=TestPartResult&file=%s&line=%d&message=", UrlEncode(file_name).c_str(), test_part_result.line_number())); Send(UrlEncode(test_part_result.message()) + "\n"); } private: // Creates a client socket and connects to the server. void MakeConnection(); // Closes the socket. void CloseConnection() { GTEST_CHECK_(sockfd_ != -1) << "CloseConnection() can be called only when there is a connection."; close(sockfd_); sockfd_ = -1; } // Sends a string to the socket. void Send(const string& message) { GTEST_CHECK_(sockfd_ != -1) << "Send() can be called only when there is a connection."; const int len = static_cast(message.length()); if (write(sockfd_, message.c_str(), len) != len) { GTEST_LOG_(WARNING) << "stream_result_to: failed to stream to " << host_name_ << ":" << port_num_; } } int sockfd_; // socket file descriptor const string host_name_; const string port_num_; GTEST_DISALLOW_COPY_AND_ASSIGN_(StreamingListener); }; // class StreamingListener // Checks if str contains '=', '&', '%' or '\n' characters. If yes, // replaces them by "%xx" where xx is their hexadecimal value. For // example, replaces "=" with "%3D". This algorithm is O(strlen(str)) // in both time and space -- important as the input str may contain an // arbitrarily long test failure message and stack trace. string StreamingListener::UrlEncode(const char* str) { string result; result.reserve(strlen(str) + 1); for (char ch = *str; ch != '\0'; ch = *++str) { switch (ch) { case '%': case '=': case '&': case '\n': result.append(String::Format("%%%02x", static_cast(ch))); break; default: result.push_back(ch); break; } } return result; } void StreamingListener::MakeConnection() { GTEST_CHECK_(sockfd_ == -1) << "MakeConnection() can't be called when there is already a connection."; addrinfo hints; memset(&hints, 0, sizeof(hints)); hints.ai_family = AF_UNSPEC; // To allow both IPv4 and IPv6 addresses. hints.ai_socktype = SOCK_STREAM; addrinfo* servinfo = NULL; // Use the getaddrinfo() to get a linked list of IP addresses for // the given host name. const int error_num = getaddrinfo( host_name_.c_str(), port_num_.c_str(), &hints, &servinfo); if (error_num != 0) { GTEST_LOG_(WARNING) << "stream_result_to: getaddrinfo() failed: " << gai_strerror(error_num); } // Loop through all the results and connect to the first we can. for (addrinfo* cur_addr = servinfo; sockfd_ == -1 && cur_addr != NULL; cur_addr = cur_addr->ai_next) { sockfd_ = socket( cur_addr->ai_family, cur_addr->ai_socktype, cur_addr->ai_protocol); if (sockfd_ != -1) { // Connect the client socket to the server socket. if (connect(sockfd_, cur_addr->ai_addr, cur_addr->ai_addrlen) == -1) { close(sockfd_); sockfd_ = -1; } } } freeaddrinfo(servinfo); // all done with this structure if (sockfd_ == -1) { GTEST_LOG_(WARNING) << "stream_result_to: failed to connect to " << host_name_ << ":" << port_num_; } } // End of class Streaming Listener #endif // GTEST_CAN_STREAM_RESULTS__ // Class ScopedTrace // Pushes the given source file location and message onto a per-thread // trace stack maintained by Google Test. // L < UnitTest::mutex_ ScopedTrace::ScopedTrace(const char* file, int line, const Message& message) { TraceInfo trace; trace.file = file; trace.line = line; trace.message = message.GetString(); UnitTest::GetInstance()->PushGTestTrace(trace); } // Pops the info pushed by the c'tor. // L < UnitTest::mutex_ ScopedTrace::~ScopedTrace() { UnitTest::GetInstance()->PopGTestTrace(); } // class OsStackTraceGetter // Returns the current OS stack trace as a String. Parameters: // // max_depth - the maximum number of stack frames to be included // in the trace. // skip_count - the number of top frames to be skipped; doesn't count // against max_depth. // // L < mutex_ // We use "L < mutex_" to denote that the function may acquire mutex_. String OsStackTraceGetter::CurrentStackTrace(int, int) { return String(""); } // L < mutex_ void OsStackTraceGetter::UponLeavingGTest() { } const char* const OsStackTraceGetter::kElidedFramesMarker = "... " GTEST_NAME_ " internal frames ..."; } // namespace internal // class TestEventListeners TestEventListeners::TestEventListeners() : repeater_(new internal::TestEventRepeater()), default_result_printer_(NULL), default_xml_generator_(NULL) { } TestEventListeners::~TestEventListeners() { delete repeater_; } // Returns the standard listener responsible for the default console // output. Can be removed from the listeners list to shut down default // console output. Note that removing this object from the listener list // with Release transfers its ownership to the user. void TestEventListeners::Append(TestEventListener* listener) { repeater_->Append(listener); } // Removes the given event listener from the list and returns it. It then // becomes the caller's responsibility to delete the listener. Returns // NULL if the listener is not found in the list. TestEventListener* TestEventListeners::Release(TestEventListener* listener) { if (listener == default_result_printer_) default_result_printer_ = NULL; else if (listener == default_xml_generator_) default_xml_generator_ = NULL; return repeater_->Release(listener); } // Returns repeater that broadcasts the TestEventListener events to all // subscribers. TestEventListener* TestEventListeners::repeater() { return repeater_; } // Sets the default_result_printer attribute to the provided listener. // The listener is also added to the listener list and previous // default_result_printer is removed from it and deleted. The listener can // also be NULL in which case it will not be added to the list. Does // nothing if the previous and the current listener objects are the same. void TestEventListeners::SetDefaultResultPrinter(TestEventListener* listener) { if (default_result_printer_ != listener) { // It is an error to pass this method a listener that is already in the // list. delete Release(default_result_printer_); default_result_printer_ = listener; if (listener != NULL) Append(listener); } } // Sets the default_xml_generator attribute to the provided listener. The // listener is also added to the listener list and previous // default_xml_generator is removed from it and deleted. The listener can // also be NULL in which case it will not be added to the list. Does // nothing if the previous and the current listener objects are the same. void TestEventListeners::SetDefaultXmlGenerator(TestEventListener* listener) { if (default_xml_generator_ != listener) { // It is an error to pass this method a listener that is already in the // list. delete Release(default_xml_generator_); default_xml_generator_ = listener; if (listener != NULL) Append(listener); } } // Controls whether events will be forwarded by the repeater to the // listeners in the list. bool TestEventListeners::EventForwardingEnabled() const { return repeater_->forwarding_enabled(); } void TestEventListeners::SuppressEventForwarding() { repeater_->set_forwarding_enabled(false); } // class UnitTest // Gets the singleton UnitTest object. The first time this method is // called, a UnitTest object is constructed and returned. Consecutive // calls will return the same object. // // We don't protect this under mutex_ as a user is not supposed to // call this before main() starts, from which point on the return // value will never change. UnitTest * UnitTest::GetInstance() { // When compiled with MSVC 7.1 in optimized mode, destroying the // UnitTest object upon exiting the program messes up the exit code, // causing successful tests to appear failed. We have to use a // different implementation in this case to bypass the compiler bug. // This implementation makes the compiler happy, at the cost of // leaking the UnitTest object. // CodeGear C++Builder insists on a public destructor for the // default implementation. Use this implementation to keep good OO // design with private destructor. #if (_MSC_VER == 1310 && !defined(_DEBUG)) || defined(__BORLANDC__) static UnitTest* const instance = new UnitTest; return instance; #else static UnitTest instance; return &instance; #endif // (_MSC_VER == 1310 && !defined(_DEBUG)) || defined(__BORLANDC__) } // Gets the number of successful test cases. int UnitTest::successful_test_case_count() const { return impl()->successful_test_case_count(); } // Gets the number of failed test cases. int UnitTest::failed_test_case_count() const { return impl()->failed_test_case_count(); } // Gets the number of all test cases. int UnitTest::total_test_case_count() const { return impl()->total_test_case_count(); } // Gets the number of all test cases that contain at least one test // that should run. int UnitTest::test_case_to_run_count() const { return impl()->test_case_to_run_count(); } // Gets the number of successful tests. int UnitTest::successful_test_count() const { return impl()->successful_test_count(); } // Gets the number of failed tests. int UnitTest::failed_test_count() const { return impl()->failed_test_count(); } // Gets the number of disabled tests. int UnitTest::disabled_test_count() const { return impl()->disabled_test_count(); } // Gets the number of all tests. int UnitTest::total_test_count() const { return impl()->total_test_count(); } // Gets the number of tests that should run. int UnitTest::test_to_run_count() const { return impl()->test_to_run_count(); } // Gets the elapsed time, in milliseconds. internal::TimeInMillis UnitTest::elapsed_time() const { return impl()->elapsed_time(); } // Returns true iff the unit test passed (i.e. all test cases passed). bool UnitTest::Passed() const { return impl()->Passed(); } // Returns true iff the unit test failed (i.e. some test case failed // or something outside of all tests failed). bool UnitTest::Failed() const { return impl()->Failed(); } // Gets the i-th test case among all the test cases. i can range from 0 to // total_test_case_count() - 1. If i is not in that range, returns NULL. const TestCase* UnitTest::GetTestCase(int i) const { return impl()->GetTestCase(i); } // Gets the i-th test case among all the test cases. i can range from 0 to // total_test_case_count() - 1. If i is not in that range, returns NULL. TestCase* UnitTest::GetMutableTestCase(int i) { return impl()->GetMutableTestCase(i); } // Returns the list of event listeners that can be used to track events // inside Google Test. TestEventListeners& UnitTest::listeners() { return *impl()->listeners(); } // Registers and returns a global test environment. When a test // program is run, all global test environments will be set-up in the // order they were registered. After all tests in the program have // finished, all global test environments will be torn-down in the // *reverse* order they were registered. // // The UnitTest object takes ownership of the given environment. // // We don't protect this under mutex_, as we only support calling it // from the main thread. Environment* UnitTest::AddEnvironment(Environment* env) { if (env == NULL) { return NULL; } impl_->environments().push_back(env); return env; } // Adds a TestPartResult to the current TestResult object. All Google Test // assertion macros (e.g. ASSERT_TRUE, EXPECT_EQ, etc) eventually call // this to report their results. The user code should use the // assertion macros instead of calling this directly. // L < mutex_ void UnitTest::AddTestPartResult(TestPartResult::Type result_type, const char* file_name, int line_number, const internal::String& message, const internal::String& os_stack_trace) { Message msg; msg << message; internal::MutexLock lock(&mutex_); if (impl_->gtest_trace_stack().size() > 0) { msg << "\n" << GTEST_NAME_ << " trace:"; for (int i = static_cast(impl_->gtest_trace_stack().size()); i > 0; --i) { const internal::TraceInfo& trace = impl_->gtest_trace_stack()[i - 1]; msg << "\n" << internal::FormatFileLocation(trace.file, trace.line) << " " << trace.message; } } if (os_stack_trace.c_str() != NULL && !os_stack_trace.empty()) { msg << internal::kStackTraceMarker << os_stack_trace; } const TestPartResult result = TestPartResult(result_type, file_name, line_number, msg.GetString().c_str()); impl_->GetTestPartResultReporterForCurrentThread()-> ReportTestPartResult(result); if (result_type != TestPartResult::kSuccess) { // gtest_break_on_failure takes precedence over // gtest_throw_on_failure. This allows a user to set the latter // in the code (perhaps in order to use Google Test assertions // with another testing framework) and specify the former on the // command line for debugging. if (GTEST_FLAG(break_on_failure)) { #if GTEST_OS_WINDOWS // Using DebugBreak on Windows allows gtest to still break into a debugger // when a failure happens and both the --gtest_break_on_failure and // the --gtest_catch_exceptions flags are specified. DebugBreak(); #else // Dereference NULL through a volatile pointer to prevent the compiler // from removing. We use this rather than abort() or __builtin_trap() for // portability: Symbian doesn't implement abort() well, and some debuggers // don't correctly trap abort(). *static_cast(NULL) = 1; #endif // GTEST_OS_WINDOWS } else if (GTEST_FLAG(throw_on_failure)) { #if GTEST_HAS_EXCEPTIONS throw GoogleTestFailureException(result); #else // We cannot call abort() as it generates a pop-up in debug mode // that cannot be suppressed in VC 7.1 or below. exit(1); #endif } } } // Creates and adds a property to the current TestResult. If a property matching // the supplied value already exists, updates its value instead. void UnitTest::RecordPropertyForCurrentTest(const char* key, const char* value) { const TestProperty test_property(key, value); impl_->current_test_result()->RecordProperty(test_property); } // Runs all tests in this UnitTest object and prints the result. // Returns 0 if successful, or 1 otherwise. // // We don't protect this under mutex_, as we only support calling it // from the main thread. int UnitTest::Run() { // Captures the value of GTEST_FLAG(catch_exceptions). This value will be // used for the duration of the program. impl()->set_catch_exceptions(GTEST_FLAG(catch_exceptions)); #if GTEST_HAS_SEH const bool in_death_test_child_process = internal::GTEST_FLAG(internal_run_death_test).length() > 0; // Either the user wants Google Test to catch exceptions thrown by the // tests or this is executing in the context of death test child // process. In either case the user does not want to see pop-up dialogs // about crashes - they are expected. if (impl()->catch_exceptions() || in_death_test_child_process) { # if !GTEST_OS_WINDOWS_MOBILE // SetErrorMode doesn't exist on CE. SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOALIGNMENTFAULTEXCEPT | SEM_NOGPFAULTERRORBOX | SEM_NOOPENFILEERRORBOX); # endif // !GTEST_OS_WINDOWS_MOBILE # if (defined(_MSC_VER) || GTEST_OS_WINDOWS_MINGW) && !GTEST_OS_WINDOWS_MOBILE // Death test children can be terminated with _abort(). On Windows, // _abort() can show a dialog with a warning message. This forces the // abort message to go to stderr instead. _set_error_mode(_OUT_TO_STDERR); # endif # if _MSC_VER >= 1400 && !GTEST_OS_WINDOWS_MOBILE // In the debug version, Visual Studio pops up a separate dialog // offering a choice to debug the aborted program. We need to suppress // this dialog or it will pop up for every EXPECT/ASSERT_DEATH statement // executed. Google Test will notify the user of any unexpected // failure via stderr. // // VC++ doesn't define _set_abort_behavior() prior to the version 8.0. // Users of prior VC versions shall suffer the agony and pain of // clicking through the countless debug dialogs. // TODO(vladl@google.com): find a way to suppress the abort dialog() in the // debug mode when compiled with VC 7.1 or lower. if (!GTEST_FLAG(break_on_failure)) _set_abort_behavior( 0x0, // Clear the following flags: _WRITE_ABORT_MSG | _CALL_REPORTFAULT); // pop-up window, core dump. # endif } #endif // GTEST_HAS_SEH return internal::HandleExceptionsInMethodIfSupported( impl(), &internal::UnitTestImpl::RunAllTests, "auxiliary test code (environments or event listeners)") ? 0 : 1; } // Returns the working directory when the first TEST() or TEST_F() was // executed. const char* UnitTest::original_working_dir() const { return impl_->original_working_dir_.c_str(); } // Returns the TestCase object for the test that's currently running, // or NULL if no test is running. // L < mutex_ const TestCase* UnitTest::current_test_case() const { internal::MutexLock lock(&mutex_); return impl_->current_test_case(); } // Returns the TestInfo object for the test that's currently running, // or NULL if no test is running. // L < mutex_ const TestInfo* UnitTest::current_test_info() const { internal::MutexLock lock(&mutex_); return impl_->current_test_info(); } // Returns the random seed used at the start of the current test run. int UnitTest::random_seed() const { return impl_->random_seed(); } #if GTEST_HAS_PARAM_TEST // Returns ParameterizedTestCaseRegistry object used to keep track of // value-parameterized tests and instantiate and register them. // L < mutex_ internal::ParameterizedTestCaseRegistry& UnitTest::parameterized_test_registry() { return impl_->parameterized_test_registry(); } #endif // GTEST_HAS_PARAM_TEST // Creates an empty UnitTest. UnitTest::UnitTest() { impl_ = new internal::UnitTestImpl(this); } // Destructor of UnitTest. UnitTest::~UnitTest() { delete impl_; } // Pushes a trace defined by SCOPED_TRACE() on to the per-thread // Google Test trace stack. // L < mutex_ void UnitTest::PushGTestTrace(const internal::TraceInfo& trace) { internal::MutexLock lock(&mutex_); impl_->gtest_trace_stack().push_back(trace); } // Pops a trace from the per-thread Google Test trace stack. // L < mutex_ void UnitTest::PopGTestTrace() { internal::MutexLock lock(&mutex_); impl_->gtest_trace_stack().pop_back(); } namespace internal { UnitTestImpl::UnitTestImpl(UnitTest* parent) : parent_(parent), #ifdef _MSC_VER # pragma warning(push) // Saves the current warning state. # pragma warning(disable:4355) // Temporarily disables warning 4355 // (using this in initializer). default_global_test_part_result_reporter_(this), default_per_thread_test_part_result_reporter_(this), # pragma warning(pop) // Restores the warning state again. #else default_global_test_part_result_reporter_(this), default_per_thread_test_part_result_reporter_(this), #endif // _MSC_VER global_test_part_result_repoter_( &default_global_test_part_result_reporter_), per_thread_test_part_result_reporter_( &default_per_thread_test_part_result_reporter_), #if GTEST_HAS_PARAM_TEST parameterized_test_registry_(), parameterized_tests_registered_(false), #endif // GTEST_HAS_PARAM_TEST last_death_test_case_(-1), current_test_case_(NULL), current_test_info_(NULL), ad_hoc_test_result_(), os_stack_trace_getter_(NULL), post_flag_parse_init_performed_(false), random_seed_(0), // Will be overridden by the flag before first use. random_(0), // Will be reseeded before first use. elapsed_time_(0), #if GTEST_HAS_DEATH_TEST internal_run_death_test_flag_(NULL), death_test_factory_(new DefaultDeathTestFactory), #endif // Will be overridden by the flag before first use. catch_exceptions_(false) { listeners()->SetDefaultResultPrinter(new PrettyUnitTestResultPrinter); } UnitTestImpl::~UnitTestImpl() { // Deletes every TestCase. ForEach(test_cases_, internal::Delete); // Deletes every Environment. ForEach(environments_, internal::Delete); delete os_stack_trace_getter_; } #if GTEST_HAS_DEATH_TEST // Disables event forwarding if the control is currently in a death test // subprocess. Must not be called before InitGoogleTest. void UnitTestImpl::SuppressTestEventsIfInSubprocess() { if (internal_run_death_test_flag_.get() != NULL) listeners()->SuppressEventForwarding(); } #endif // GTEST_HAS_DEATH_TEST // Initializes event listeners performing XML output as specified by // UnitTestOptions. Must not be called before InitGoogleTest. void UnitTestImpl::ConfigureXmlOutput() { const String& output_format = UnitTestOptions::GetOutputFormat(); if (output_format == "xml") { listeners()->SetDefaultXmlGenerator(new XmlUnitTestResultPrinter( UnitTestOptions::GetAbsolutePathToOutputFile().c_str())); } else if (output_format != "") { printf("WARNING: unrecognized output format \"%s\" ignored.\n", output_format.c_str()); fflush(stdout); } } #if GTEST_CAN_STREAM_RESULTS_ // Initializes event listeners for streaming test results in String form. // Must not be called before InitGoogleTest. void UnitTestImpl::ConfigureStreamingOutput() { const string& target = GTEST_FLAG(stream_result_to); if (!target.empty()) { const size_t pos = target.find(':'); if (pos != string::npos) { listeners()->Append(new StreamingListener(target.substr(0, pos), target.substr(pos+1))); } else { printf("WARNING: unrecognized streaming target \"%s\" ignored.\n", target.c_str()); fflush(stdout); } } } #endif // GTEST_CAN_STREAM_RESULTS_ // Performs initialization dependent upon flag values obtained in // ParseGoogleTestFlagsOnly. Is called from InitGoogleTest after the call to // ParseGoogleTestFlagsOnly. In case a user neglects to call InitGoogleTest // this function is also called from RunAllTests. Since this function can be // called more than once, it has to be idempotent. void UnitTestImpl::PostFlagParsingInit() { // Ensures that this function does not execute more than once. if (!post_flag_parse_init_performed_) { post_flag_parse_init_performed_ = true; #if GTEST_HAS_DEATH_TEST InitDeathTestSubprocessControlInfo(); SuppressTestEventsIfInSubprocess(); #endif // GTEST_HAS_DEATH_TEST // Registers parameterized tests. This makes parameterized tests // available to the UnitTest reflection API without running // RUN_ALL_TESTS. RegisterParameterizedTests(); // Configures listeners for XML output. This makes it possible for users // to shut down the default XML output before invoking RUN_ALL_TESTS. ConfigureXmlOutput(); #if GTEST_CAN_STREAM_RESULTS_ // Configures listeners for streaming test results to the specified server. ConfigureStreamingOutput(); #endif // GTEST_CAN_STREAM_RESULTS_ } } // A predicate that checks the name of a TestCase against a known // value. // // This is used for implementation of the UnitTest class only. We put // it in the anonymous namespace to prevent polluting the outer // namespace. // // TestCaseNameIs is copyable. class TestCaseNameIs { public: // Constructor. explicit TestCaseNameIs(const String& name) : name_(name) {} // Returns true iff the name of test_case matches name_. bool operator()(const TestCase* test_case) const { return test_case != NULL && strcmp(test_case->name(), name_.c_str()) == 0; } private: String name_; }; // Finds and returns a TestCase with the given name. If one doesn't // exist, creates one and returns it. It's the CALLER'S // RESPONSIBILITY to ensure that this function is only called WHEN THE // TESTS ARE NOT SHUFFLED. // // Arguments: // // test_case_name: name of the test case // type_param: the name of the test case's type parameter, or NULL if // this is not a typed or a type-parameterized test case. // set_up_tc: pointer to the function that sets up the test case // tear_down_tc: pointer to the function that tears down the test case TestCase* UnitTestImpl::GetTestCase(const char* test_case_name, const char* type_param, Test::SetUpTestCaseFunc set_up_tc, Test::TearDownTestCaseFunc tear_down_tc) { // Can we find a TestCase with the given name? const std::vector::const_iterator test_case = std::find_if(test_cases_.begin(), test_cases_.end(), TestCaseNameIs(test_case_name)); if (test_case != test_cases_.end()) return *test_case; // No. Let's create one. TestCase* const new_test_case = new TestCase(test_case_name, type_param, set_up_tc, tear_down_tc); // Is this a death test case? if (internal::UnitTestOptions::MatchesFilter(String(test_case_name), kDeathTestCaseFilter)) { // Yes. Inserts the test case after the last death test case // defined so far. This only works when the test cases haven't // been shuffled. Otherwise we may end up running a death test // after a non-death test. ++last_death_test_case_; test_cases_.insert(test_cases_.begin() + last_death_test_case_, new_test_case); } else { // No. Appends to the end of the list. test_cases_.push_back(new_test_case); } test_case_indices_.push_back(static_cast(test_case_indices_.size())); return new_test_case; } // Helpers for setting up / tearing down the given environment. They // are for use in the ForEach() function. static void SetUpEnvironment(Environment* env) { env->SetUp(); } static void TearDownEnvironment(Environment* env) { env->TearDown(); } // Runs all tests in this UnitTest object, prints the result, and // returns true if all tests are successful. If any exception is // thrown during a test, the test is considered to be failed, but the // rest of the tests will still be run. // // When parameterized tests are enabled, it expands and registers // parameterized tests first in RegisterParameterizedTests(). // All other functions called from RunAllTests() may safely assume that // parameterized tests are ready to be counted and run. bool UnitTestImpl::RunAllTests() { // Makes sure InitGoogleTest() was called. if (!GTestIsInitialized()) { printf("%s", "\nThis test program did NOT call ::testing::InitGoogleTest " "before calling RUN_ALL_TESTS(). Please fix it.\n"); return false; } // Do not run any test if the --help flag was specified. if (g_help_flag) return true; // Repeats the call to the post-flag parsing initialization in case the // user didn't call InitGoogleTest. PostFlagParsingInit(); // Even if sharding is not on, test runners may want to use the // GTEST_SHARD_STATUS_FILE to query whether the test supports the sharding // protocol. internal::WriteToShardStatusFileIfNeeded(); // True iff we are in a subprocess for running a thread-safe-style // death test. bool in_subprocess_for_death_test = false; #if GTEST_HAS_DEATH_TEST in_subprocess_for_death_test = (internal_run_death_test_flag_.get() != NULL); #endif // GTEST_HAS_DEATH_TEST const bool should_shard = ShouldShard(kTestTotalShards, kTestShardIndex, in_subprocess_for_death_test); // Compares the full test names with the filter to decide which // tests to run. const bool has_tests_to_run = FilterTests(should_shard ? HONOR_SHARDING_PROTOCOL : IGNORE_SHARDING_PROTOCOL) > 0; // Lists the tests and exits if the --gtest_list_tests flag was specified. if (GTEST_FLAG(list_tests)) { // This must be called *after* FilterTests() has been called. ListTestsMatchingFilter(); return true; } random_seed_ = GTEST_FLAG(shuffle) ? GetRandomSeedFromFlag(GTEST_FLAG(random_seed)) : 0; // True iff at least one test has failed. bool failed = false; TestEventListener* repeater = listeners()->repeater(); repeater->OnTestProgramStart(*parent_); // How many times to repeat the tests? We don't want to repeat them // when we are inside the subprocess of a death test. const int repeat = in_subprocess_for_death_test ? 1 : GTEST_FLAG(repeat); // Repeats forever if the repeat count is negative. const bool forever = repeat < 0; for (int i = 0; forever || i != repeat; i++) { // We want to preserve failures generated by ad-hoc test // assertions executed before RUN_ALL_TESTS(). ClearNonAdHocTestResult(); const TimeInMillis start = GetTimeInMillis(); // Shuffles test cases and tests if requested. if (has_tests_to_run && GTEST_FLAG(shuffle)) { random()->Reseed(random_seed_); // This should be done before calling OnTestIterationStart(), // such that a test event listener can see the actual test order // in the event. ShuffleTests(); } // Tells the unit test event listeners that the tests are about to start. repeater->OnTestIterationStart(*parent_, i); // Runs each test case if there is at least one test to run. if (has_tests_to_run) { // Sets up all environments beforehand. repeater->OnEnvironmentsSetUpStart(*parent_); ForEach(environments_, SetUpEnvironment); repeater->OnEnvironmentsSetUpEnd(*parent_); // Runs the tests only if there was no fatal failure during global // set-up. if (!Test::HasFatalFailure()) { for (int test_index = 0; test_index < total_test_case_count(); test_index++) { GetMutableTestCase(test_index)->Run(); } } // Tears down all environments in reverse order afterwards. repeater->OnEnvironmentsTearDownStart(*parent_); std::for_each(environments_.rbegin(), environments_.rend(), TearDownEnvironment); repeater->OnEnvironmentsTearDownEnd(*parent_); } elapsed_time_ = GetTimeInMillis() - start; // Tells the unit test event listener that the tests have just finished. repeater->OnTestIterationEnd(*parent_, i); // Gets the result and clears it. if (!Passed()) { failed = true; } // Restores the original test order after the iteration. This // allows the user to quickly repro a failure that happens in the // N-th iteration without repeating the first (N - 1) iterations. // This is not enclosed in "if (GTEST_FLAG(shuffle)) { ... }", in // case the user somehow changes the value of the flag somewhere // (it's always safe to unshuffle the tests). UnshuffleTests(); if (GTEST_FLAG(shuffle)) { // Picks a new random seed for each iteration. random_seed_ = GetNextRandomSeed(random_seed_); } } repeater->OnTestProgramEnd(*parent_); return !failed; } // Reads the GTEST_SHARD_STATUS_FILE environment variable, and creates the file // if the variable is present. If a file already exists at this location, this // function will write over it. If the variable is present, but the file cannot // be created, prints an error and exits. void WriteToShardStatusFileIfNeeded() { const char* const test_shard_file = posix::GetEnv(kTestShardStatusFile); if (test_shard_file != NULL) { FILE* const file = posix::FOpen(test_shard_file, "w"); if (file == NULL) { ColoredPrintf(COLOR_RED, "Could not write to the test shard status file \"%s\" " "specified by the %s environment variable.\n", test_shard_file, kTestShardStatusFile); fflush(stdout); exit(EXIT_FAILURE); } fclose(file); } } // Checks whether sharding is enabled by examining the relevant // environment variable values. If the variables are present, // but inconsistent (i.e., shard_index >= total_shards), prints // an error and exits. If in_subprocess_for_death_test, sharding is // disabled because it must only be applied to the original test // process. Otherwise, we could filter out death tests we intended to execute. bool ShouldShard(const char* total_shards_env, const char* shard_index_env, bool in_subprocess_for_death_test) { if (in_subprocess_for_death_test) { return false; } const Int32 total_shards = Int32FromEnvOrDie(total_shards_env, -1); const Int32 shard_index = Int32FromEnvOrDie(shard_index_env, -1); if (total_shards == -1 && shard_index == -1) { return false; } else if (total_shards == -1 && shard_index != -1) { const Message msg = Message() << "Invalid environment variables: you have " << kTestShardIndex << " = " << shard_index << ", but have left " << kTestTotalShards << " unset.\n"; ColoredPrintf(COLOR_RED, msg.GetString().c_str()); fflush(stdout); exit(EXIT_FAILURE); } else if (total_shards != -1 && shard_index == -1) { const Message msg = Message() << "Invalid environment variables: you have " << kTestTotalShards << " = " << total_shards << ", but have left " << kTestShardIndex << " unset.\n"; ColoredPrintf(COLOR_RED, msg.GetString().c_str()); fflush(stdout); exit(EXIT_FAILURE); } else if (shard_index < 0 || shard_index >= total_shards) { const Message msg = Message() << "Invalid environment variables: we require 0 <= " << kTestShardIndex << " < " << kTestTotalShards << ", but you have " << kTestShardIndex << "=" << shard_index << ", " << kTestTotalShards << "=" << total_shards << ".\n"; ColoredPrintf(COLOR_RED, msg.GetString().c_str()); fflush(stdout); exit(EXIT_FAILURE); } return total_shards > 1; } // Parses the environment variable var as an Int32. If it is unset, // returns default_val. If it is not an Int32, prints an error // and aborts. Int32 Int32FromEnvOrDie(const char* var, Int32 default_val) { const char* str_val = posix::GetEnv(var); if (str_val == NULL) { return default_val; } Int32 result; if (!ParseInt32(Message() << "The value of environment variable " << var, str_val, &result)) { exit(EXIT_FAILURE); } return result; } // Given the total number of shards, the shard index, and the test id, // returns true iff the test should be run on this shard. The test id is // some arbitrary but unique non-negative integer assigned to each test // method. Assumes that 0 <= shard_index < total_shards. bool ShouldRunTestOnShard(int total_shards, int shard_index, int test_id) { return (test_id % total_shards) == shard_index; } // Compares the name of each test with the user-specified filter to // decide whether the test should be run, then records the result in // each TestCase and TestInfo object. // If shard_tests == true, further filters tests based on sharding // variables in the environment - see // http://code.google.com/p/googletest/wiki/GoogleTestAdvancedGuide. // Returns the number of tests that should run. int UnitTestImpl::FilterTests(ReactionToSharding shard_tests) { const Int32 total_shards = shard_tests == HONOR_SHARDING_PROTOCOL ? Int32FromEnvOrDie(kTestTotalShards, -1) : -1; const Int32 shard_index = shard_tests == HONOR_SHARDING_PROTOCOL ? Int32FromEnvOrDie(kTestShardIndex, -1) : -1; // num_runnable_tests are the number of tests that will // run across all shards (i.e., match filter and are not disabled). // num_selected_tests are the number of tests to be run on // this shard. int num_runnable_tests = 0; int num_selected_tests = 0; for (size_t i = 0; i < test_cases_.size(); i++) { TestCase* const test_case = test_cases_[i]; const String &test_case_name = test_case->name(); test_case->set_should_run(false); for (size_t j = 0; j < test_case->test_info_list().size(); j++) { TestInfo* const test_info = test_case->test_info_list()[j]; const String test_name(test_info->name()); // A test is disabled if test case name or test name matches // kDisableTestFilter. const bool is_disabled = internal::UnitTestOptions::MatchesFilter(test_case_name, kDisableTestFilter) || internal::UnitTestOptions::MatchesFilter(test_name, kDisableTestFilter); test_info->is_disabled_ = is_disabled; const bool matches_filter = internal::UnitTestOptions::FilterMatchesTest(test_case_name, test_name); test_info->matches_filter_ = matches_filter; const bool is_runnable = (GTEST_FLAG(also_run_disabled_tests) || !is_disabled) && matches_filter; const bool is_selected = is_runnable && (shard_tests == IGNORE_SHARDING_PROTOCOL || ShouldRunTestOnShard(total_shards, shard_index, num_runnable_tests)); num_runnable_tests += is_runnable; num_selected_tests += is_selected; test_info->should_run_ = is_selected; test_case->set_should_run(test_case->should_run() || is_selected); } } return num_selected_tests; } // Prints the names of the tests matching the user-specified filter flag. void UnitTestImpl::ListTestsMatchingFilter() { for (size_t i = 0; i < test_cases_.size(); i++) { const TestCase* const test_case = test_cases_[i]; bool printed_test_case_name = false; for (size_t j = 0; j < test_case->test_info_list().size(); j++) { const TestInfo* const test_info = test_case->test_info_list()[j]; if (test_info->matches_filter_) { if (!printed_test_case_name) { printed_test_case_name = true; printf("%s.\n", test_case->name()); } printf(" %s\n", test_info->name()); } } } fflush(stdout); } // Sets the OS stack trace getter. // // Does nothing if the input and the current OS stack trace getter are // the same; otherwise, deletes the old getter and makes the input the // current getter. void UnitTestImpl::set_os_stack_trace_getter( OsStackTraceGetterInterface* getter) { if (os_stack_trace_getter_ != getter) { delete os_stack_trace_getter_; os_stack_trace_getter_ = getter; } } // Returns the current OS stack trace getter if it is not NULL; // otherwise, creates an OsStackTraceGetter, makes it the current // getter, and returns it. OsStackTraceGetterInterface* UnitTestImpl::os_stack_trace_getter() { if (os_stack_trace_getter_ == NULL) { os_stack_trace_getter_ = new OsStackTraceGetter; } return os_stack_trace_getter_; } // Returns the TestResult for the test that's currently running, or // the TestResult for the ad hoc test if no test is running. TestResult* UnitTestImpl::current_test_result() { return current_test_info_ ? &(current_test_info_->result_) : &ad_hoc_test_result_; } // Shuffles all test cases, and the tests within each test case, // making sure that death tests are still run first. void UnitTestImpl::ShuffleTests() { // Shuffles the death test cases. ShuffleRange(random(), 0, last_death_test_case_ + 1, &test_case_indices_); // Shuffles the non-death test cases. ShuffleRange(random(), last_death_test_case_ + 1, static_cast(test_cases_.size()), &test_case_indices_); // Shuffles the tests inside each test case. for (size_t i = 0; i < test_cases_.size(); i++) { test_cases_[i]->ShuffleTests(random()); } } // Restores the test cases and tests to their order before the first shuffle. void UnitTestImpl::UnshuffleTests() { for (size_t i = 0; i < test_cases_.size(); i++) { // Unshuffles the tests in each test case. test_cases_[i]->UnshuffleTests(); // Resets the index of each test case. test_case_indices_[i] = static_cast(i); } } // Returns the current OS stack trace as a String. // // The maximum number of stack frames to be included is specified by // the gtest_stack_trace_depth flag. The skip_count parameter // specifies the number of top frames to be skipped, which doesn't // count against the number of frames to be included. // // For example, if Foo() calls Bar(), which in turn calls // GetCurrentOsStackTraceExceptTop(..., 1), Foo() will be included in // the trace but Bar() and GetCurrentOsStackTraceExceptTop() won't. String GetCurrentOsStackTraceExceptTop(UnitTest* /*unit_test*/, int skip_count) { // We pass skip_count + 1 to skip this wrapper function in addition // to what the user really wants to skip. return GetUnitTestImpl()->CurrentOsStackTraceExceptTop(skip_count + 1); } // Used by the GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_ macro to // suppress unreachable code warnings. namespace { class ClassUniqueToAlwaysTrue {}; } bool IsTrue(bool condition) { return condition; } bool AlwaysTrue() { #if GTEST_HAS_EXCEPTIONS // This condition is always false so AlwaysTrue() never actually throws, // but it makes the compiler think that it may throw. if (IsTrue(false)) throw ClassUniqueToAlwaysTrue(); #endif // GTEST_HAS_EXCEPTIONS return true; } // If *pstr starts with the given prefix, modifies *pstr to be right // past the prefix and returns true; otherwise leaves *pstr unchanged // and returns false. None of pstr, *pstr, and prefix can be NULL. bool SkipPrefix(const char* prefix, const char** pstr) { const size_t prefix_len = strlen(prefix); if (strncmp(*pstr, prefix, prefix_len) == 0) { *pstr += prefix_len; return true; } return false; } // Parses a string as a command line flag. The string should have // the format "--flag=value". When def_optional is true, the "=value" // part can be omitted. // // Returns the value of the flag, or NULL if the parsing failed. const char* ParseFlagValue(const char* str, const char* flag, bool def_optional) { // str and flag must not be NULL. if (str == NULL || flag == NULL) return NULL; // The flag must start with "--" followed by GTEST_FLAG_PREFIX_. const String flag_str = String::Format("--%s%s", GTEST_FLAG_PREFIX_, flag); const size_t flag_len = flag_str.length(); if (strncmp(str, flag_str.c_str(), flag_len) != 0) return NULL; // Skips the flag name. const char* flag_end = str + flag_len; // When def_optional is true, it's OK to not have a "=value" part. if (def_optional && (flag_end[0] == '\0')) { return flag_end; } // If def_optional is true and there are more characters after the // flag name, or if def_optional is false, there must be a '=' after // the flag name. if (flag_end[0] != '=') return NULL; // Returns the string after "=". return flag_end + 1; } // Parses a string for a bool flag, in the form of either // "--flag=value" or "--flag". // // In the former case, the value is taken as true as long as it does // not start with '0', 'f', or 'F'. // // In the latter case, the value is taken as true. // // On success, stores the value of the flag in *value, and returns // true. On failure, returns false without changing *value. bool ParseBoolFlag(const char* str, const char* flag, bool* value) { // Gets the value of the flag as a string. const char* const value_str = ParseFlagValue(str, flag, true); // Aborts if the parsing failed. if (value_str == NULL) return false; // Converts the string value to a bool. *value = !(*value_str == '0' || *value_str == 'f' || *value_str == 'F'); return true; } // Parses a string for an Int32 flag, in the form of // "--flag=value". // // On success, stores the value of the flag in *value, and returns // true. On failure, returns false without changing *value. bool ParseInt32Flag(const char* str, const char* flag, Int32* value) { // Gets the value of the flag as a string. const char* const value_str = ParseFlagValue(str, flag, false); // Aborts if the parsing failed. if (value_str == NULL) return false; // Sets *value to the value of the flag. return ParseInt32(Message() << "The value of flag --" << flag, value_str, value); } // Parses a string for a string flag, in the form of // "--flag=value". // // On success, stores the value of the flag in *value, and returns // true. On failure, returns false without changing *value. bool ParseStringFlag(const char* str, const char* flag, String* value) { // Gets the value of the flag as a string. const char* const value_str = ParseFlagValue(str, flag, false); // Aborts if the parsing failed. if (value_str == NULL) return false; // Sets *value to the value of the flag. *value = value_str; return true; } // Determines whether a string has a prefix that Google Test uses for its // flags, i.e., starts with GTEST_FLAG_PREFIX_ or GTEST_FLAG_PREFIX_DASH_. // If Google Test detects that a command line flag has its prefix but is not // recognized, it will print its help message. Flags starting with // GTEST_INTERNAL_PREFIX_ followed by "internal_" are considered Google Test // internal flags and do not trigger the help message. static bool HasGoogleTestFlagPrefix(const char* str) { return (SkipPrefix("--", &str) || SkipPrefix("-", &str) || SkipPrefix("/", &str)) && !SkipPrefix(GTEST_FLAG_PREFIX_ "internal_", &str) && (SkipPrefix(GTEST_FLAG_PREFIX_, &str) || SkipPrefix(GTEST_FLAG_PREFIX_DASH_, &str)); } // Prints a string containing code-encoded text. The following escape // sequences can be used in the string to control the text color: // // @@ prints a single '@' character. // @R changes the color to red. // @G changes the color to green. // @Y changes the color to yellow. // @D changes to the default terminal text color. // // TODO(wan@google.com): Write tests for this once we add stdout // capturing to Google Test. static void PrintColorEncoded(const char* str) { GTestColor color = COLOR_DEFAULT; // The current color. // Conceptually, we split the string into segments divided by escape // sequences. Then we print one segment at a time. At the end of // each iteration, the str pointer advances to the beginning of the // next segment. for (;;) { const char* p = strchr(str, '@'); if (p == NULL) { ColoredPrintf(color, "%s", str); return; } ColoredPrintf(color, "%s", String(str, p - str).c_str()); const char ch = p[1]; str = p + 2; if (ch == '@') { ColoredPrintf(color, "@"); } else if (ch == 'D') { color = COLOR_DEFAULT; } else if (ch == 'R') { color = COLOR_RED; } else if (ch == 'G') { color = COLOR_GREEN; } else if (ch == 'Y') { color = COLOR_YELLOW; } else { --str; } } } static const char kColorEncodedHelpMessage[] = "This program contains tests written using " GTEST_NAME_ ". You can use the\n" "following command line flags to control its behavior:\n" "\n" "Test Selection:\n" " @G--" GTEST_FLAG_PREFIX_ "list_tests@D\n" " List the names of all tests instead of running them. The name of\n" " TEST(Foo, Bar) is \"Foo.Bar\".\n" " @G--" GTEST_FLAG_PREFIX_ "filter=@YPOSTIVE_PATTERNS" "[@G-@YNEGATIVE_PATTERNS]@D\n" " Run only the tests whose name matches one of the positive patterns but\n" " none of the negative patterns. '?' matches any single character; '*'\n" " matches any substring; ':' separates two patterns.\n" " @G--" GTEST_FLAG_PREFIX_ "also_run_disabled_tests@D\n" " Run all disabled tests too.\n" "\n" "Test Execution:\n" " @G--" GTEST_FLAG_PREFIX_ "repeat=@Y[COUNT]@D\n" " Run the tests repeatedly; use a negative count to repeat forever.\n" " @G--" GTEST_FLAG_PREFIX_ "shuffle@D\n" " Randomize tests' orders on every iteration.\n" " @G--" GTEST_FLAG_PREFIX_ "random_seed=@Y[NUMBER]@D\n" " Random number seed to use for shuffling test orders (between 1 and\n" " 99999, or 0 to use a seed based on the current time).\n" "\n" "Test Output:\n" " @G--" GTEST_FLAG_PREFIX_ "color=@Y(@Gyes@Y|@Gno@Y|@Gauto@Y)@D\n" " Enable/disable colored output. The default is @Gauto@D.\n" " -@G-" GTEST_FLAG_PREFIX_ "print_time=0@D\n" " Don't print the elapsed time of each test.\n" " @G--" GTEST_FLAG_PREFIX_ "output=xml@Y[@G:@YDIRECTORY_PATH@G" GTEST_PATH_SEP_ "@Y|@G:@YFILE_PATH]@D\n" " Generate an XML report in the given directory or with the given file\n" " name. @YFILE_PATH@D defaults to @Gtest_details.xml@D.\n" #if GTEST_CAN_STREAM_RESULTS_ " @G--" GTEST_FLAG_PREFIX_ "stream_result_to=@YHOST@G:@YPORT@D\n" " Stream test results to the given server.\n" #endif // GTEST_CAN_STREAM_RESULTS_ "\n" "Assertion Behavior:\n" #if GTEST_HAS_DEATH_TEST && !GTEST_OS_WINDOWS " @G--" GTEST_FLAG_PREFIX_ "death_test_style=@Y(@Gfast@Y|@Gthreadsafe@Y)@D\n" " Set the default death test style.\n" #endif // GTEST_HAS_DEATH_TEST && !GTEST_OS_WINDOWS " @G--" GTEST_FLAG_PREFIX_ "break_on_failure@D\n" " Turn assertion failures into debugger break-points.\n" " @G--" GTEST_FLAG_PREFIX_ "throw_on_failure@D\n" " Turn assertion failures into C++ exceptions.\n" " @G--" GTEST_FLAG_PREFIX_ "catch_exceptions=0@D\n" " Do not report exceptions as test failures. Instead, allow them\n" " to crash the program or throw a pop-up (on Windows).\n" "\n" "Except for @G--" GTEST_FLAG_PREFIX_ "list_tests@D, you can alternatively set " "the corresponding\n" "environment variable of a flag (all letters in upper-case). For example, to\n" "disable colored text output, you can either specify @G--" GTEST_FLAG_PREFIX_ "color=no@D or set\n" "the @G" GTEST_FLAG_PREFIX_UPPER_ "COLOR@D environment variable to @Gno@D.\n" "\n" "For more information, please read the " GTEST_NAME_ " documentation at\n" "@G" GTEST_PROJECT_URL_ "@D. If you find a bug in " GTEST_NAME_ "\n" "(not one in your own code or tests), please report it to\n" "@G<" GTEST_DEV_EMAIL_ ">@D.\n"; // Parses the command line for Google Test flags, without initializing // other parts of Google Test. The type parameter CharType can be // instantiated to either char or wchar_t. template void ParseGoogleTestFlagsOnlyImpl(int* argc, CharType** argv) { for (int i = 1; i < *argc; i++) { const String arg_string = StreamableToString(argv[i]); const char* const arg = arg_string.c_str(); using internal::ParseBoolFlag; using internal::ParseInt32Flag; using internal::ParseStringFlag; // Do we see a Google Test flag? if (ParseBoolFlag(arg, kAlsoRunDisabledTestsFlag, >EST_FLAG(also_run_disabled_tests)) || ParseBoolFlag(arg, kBreakOnFailureFlag, >EST_FLAG(break_on_failure)) || ParseBoolFlag(arg, kCatchExceptionsFlag, >EST_FLAG(catch_exceptions)) || ParseStringFlag(arg, kColorFlag, >EST_FLAG(color)) || ParseStringFlag(arg, kDeathTestStyleFlag, >EST_FLAG(death_test_style)) || ParseBoolFlag(arg, kDeathTestUseFork, >EST_FLAG(death_test_use_fork)) || ParseStringFlag(arg, kFilterFlag, >EST_FLAG(filter)) || ParseStringFlag(arg, kInternalRunDeathTestFlag, >EST_FLAG(internal_run_death_test)) || ParseBoolFlag(arg, kListTestsFlag, >EST_FLAG(list_tests)) || ParseStringFlag(arg, kOutputFlag, >EST_FLAG(output)) || ParseBoolFlag(arg, kPrintTimeFlag, >EST_FLAG(print_time)) || ParseInt32Flag(arg, kRandomSeedFlag, >EST_FLAG(random_seed)) || ParseInt32Flag(arg, kRepeatFlag, >EST_FLAG(repeat)) || ParseBoolFlag(arg, kShuffleFlag, >EST_FLAG(shuffle)) || ParseInt32Flag(arg, kStackTraceDepthFlag, >EST_FLAG(stack_trace_depth)) || ParseStringFlag(arg, kStreamResultToFlag, >EST_FLAG(stream_result_to)) || ParseBoolFlag(arg, kThrowOnFailureFlag, >EST_FLAG(throw_on_failure)) ) { // Yes. Shift the remainder of the argv list left by one. Note // that argv has (*argc + 1) elements, the last one always being // NULL. The following loop moves the trailing NULL element as // well. for (int j = i; j != *argc; j++) { argv[j] = argv[j + 1]; } // Decrements the argument count. (*argc)--; // We also need to decrement the iterator as we just removed // an element. i--; } else if (arg_string == "--help" || arg_string == "-h" || arg_string == "-?" || arg_string == "/?" || HasGoogleTestFlagPrefix(arg)) { // Both help flag and unrecognized Google Test flags (excluding // internal ones) trigger help display. g_help_flag = true; } } if (g_help_flag) { // We print the help here instead of in RUN_ALL_TESTS(), as the // latter may not be called at all if the user is using Google // Test with another testing framework. PrintColorEncoded(kColorEncodedHelpMessage); } } // Parses the command line for Google Test flags, without initializing // other parts of Google Test. void ParseGoogleTestFlagsOnly(int* argc, char** argv) { ParseGoogleTestFlagsOnlyImpl(argc, argv); } void ParseGoogleTestFlagsOnly(int* argc, wchar_t** argv) { ParseGoogleTestFlagsOnlyImpl(argc, argv); } // The internal implementation of InitGoogleTest(). // // The type parameter CharType can be instantiated to either char or // wchar_t. template void InitGoogleTestImpl(int* argc, CharType** argv) { g_init_gtest_count++; // We don't want to run the initialization code twice. if (g_init_gtest_count != 1) return; if (*argc <= 0) return; internal::g_executable_path = internal::StreamableToString(argv[0]); #if GTEST_HAS_DEATH_TEST g_argvs.clear(); for (int i = 0; i != *argc; i++) { g_argvs.push_back(StreamableToString(argv[i])); } #endif // GTEST_HAS_DEATH_TEST ParseGoogleTestFlagsOnly(argc, argv); GetUnitTestImpl()->PostFlagParsingInit(); } } // namespace internal // Initializes Google Test. This must be called before calling // RUN_ALL_TESTS(). In particular, it parses a command line for the // flags that Google Test recognizes. Whenever a Google Test flag is // seen, it is removed from argv, and *argc is decremented. // // No value is returned. Instead, the Google Test flag variables are // updated. // // Calling the function for the second time has no user-visible effect. void InitGoogleTest(int* argc, char** argv) { internal::InitGoogleTestImpl(argc, argv); } // This overloaded version can be used in Windows programs compiled in // UNICODE mode. void InitGoogleTest(int* argc, wchar_t** argv) { internal::InitGoogleTestImpl(argc, argv); } } // namespace testing ugene-1.9.8/src/libs_3rdparty/gtest/src/src/gtest-internal-inl.h0000644000175000017500000011654011651544307023274 0ustar ilyailya// Copyright 2005, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // Utility functions and classes used by the Google C++ testing framework. // // Author: wan@google.com (Zhanyong Wan) // // This file contains purely Google Test's internal implementation. Please // DO NOT #INCLUDE IT IN A USER PROGRAM. #ifndef GTEST_SRC_GTEST_INTERNAL_INL_H_ #define GTEST_SRC_GTEST_INTERNAL_INL_H_ // GTEST_IMPLEMENTATION_ is defined to 1 iff the current translation unit is // part of Google Test's implementation; otherwise it's undefined. #if !GTEST_IMPLEMENTATION_ // A user is trying to include this from his code - just say no. # error "gtest-internal-inl.h is part of Google Test's internal implementation." # error "It must not be included except by Google Test itself." #endif // GTEST_IMPLEMENTATION_ #ifndef _WIN32_WCE # include #endif // !_WIN32_WCE #include #include // For strtoll/_strtoul64/malloc/free. #include // For memmove. #include #include #include #include "gtest/internal/gtest-port.h" #if GTEST_OS_WINDOWS # include // NOLINT #endif // GTEST_OS_WINDOWS #include "gtest/gtest.h" // NOLINT #include "gtest/gtest-spi.h" namespace testing { // Declares the flags. // // We don't want the users to modify this flag in the code, but want // Google Test's own unit tests to be able to access it. Therefore we // declare it here as opposed to in gtest.h. GTEST_DECLARE_bool_(death_test_use_fork); namespace internal { // The value of GetTestTypeId() as seen from within the Google Test // library. This is solely for testing GetTestTypeId(). GTEST_API_ extern const TypeId kTestTypeIdInGoogleTest; // Names of the flags (needed for parsing Google Test flags). const char kAlsoRunDisabledTestsFlag[] = "also_run_disabled_tests"; const char kBreakOnFailureFlag[] = "break_on_failure"; const char kCatchExceptionsFlag[] = "catch_exceptions"; const char kColorFlag[] = "color"; const char kFilterFlag[] = "filter"; const char kListTestsFlag[] = "list_tests"; const char kOutputFlag[] = "output"; const char kPrintTimeFlag[] = "print_time"; const char kRandomSeedFlag[] = "random_seed"; const char kRepeatFlag[] = "repeat"; const char kShuffleFlag[] = "shuffle"; const char kStackTraceDepthFlag[] = "stack_trace_depth"; const char kStreamResultToFlag[] = "stream_result_to"; const char kThrowOnFailureFlag[] = "throw_on_failure"; // A valid random seed must be in [1, kMaxRandomSeed]. const int kMaxRandomSeed = 99999; // g_help_flag is true iff the --help flag or an equivalent form is // specified on the command line. GTEST_API_ extern bool g_help_flag; // Returns the current time in milliseconds. GTEST_API_ TimeInMillis GetTimeInMillis(); // Returns true iff Google Test should use colors in the output. GTEST_API_ bool ShouldUseColor(bool stdout_is_tty); // Formats the given time in milliseconds as seconds. GTEST_API_ std::string FormatTimeInMillisAsSeconds(TimeInMillis ms); // Parses a string for an Int32 flag, in the form of "--flag=value". // // On success, stores the value of the flag in *value, and returns // true. On failure, returns false without changing *value. GTEST_API_ bool ParseInt32Flag( const char* str, const char* flag, Int32* value); // Returns a random seed in range [1, kMaxRandomSeed] based on the // given --gtest_random_seed flag value. inline int GetRandomSeedFromFlag(Int32 random_seed_flag) { const unsigned int raw_seed = (random_seed_flag == 0) ? static_cast(GetTimeInMillis()) : static_cast(random_seed_flag); // Normalizes the actual seed to range [1, kMaxRandomSeed] such that // it's easy to type. const int normalized_seed = static_cast((raw_seed - 1U) % static_cast(kMaxRandomSeed)) + 1; return normalized_seed; } // Returns the first valid random seed after 'seed'. The behavior is // undefined if 'seed' is invalid. The seed after kMaxRandomSeed is // considered to be 1. inline int GetNextRandomSeed(int seed) { GTEST_CHECK_(1 <= seed && seed <= kMaxRandomSeed) << "Invalid random seed " << seed << " - must be in [1, " << kMaxRandomSeed << "]."; const int next_seed = seed + 1; return (next_seed > kMaxRandomSeed) ? 1 : next_seed; } // This class saves the values of all Google Test flags in its c'tor, and // restores them in its d'tor. class GTestFlagSaver { public: // The c'tor. GTestFlagSaver() { also_run_disabled_tests_ = GTEST_FLAG(also_run_disabled_tests); break_on_failure_ = GTEST_FLAG(break_on_failure); catch_exceptions_ = GTEST_FLAG(catch_exceptions); color_ = GTEST_FLAG(color); death_test_style_ = GTEST_FLAG(death_test_style); death_test_use_fork_ = GTEST_FLAG(death_test_use_fork); filter_ = GTEST_FLAG(filter); internal_run_death_test_ = GTEST_FLAG(internal_run_death_test); list_tests_ = GTEST_FLAG(list_tests); output_ = GTEST_FLAG(output); print_time_ = GTEST_FLAG(print_time); random_seed_ = GTEST_FLAG(random_seed); repeat_ = GTEST_FLAG(repeat); shuffle_ = GTEST_FLAG(shuffle); stack_trace_depth_ = GTEST_FLAG(stack_trace_depth); stream_result_to_ = GTEST_FLAG(stream_result_to); throw_on_failure_ = GTEST_FLAG(throw_on_failure); } // The d'tor is not virtual. DO NOT INHERIT FROM THIS CLASS. ~GTestFlagSaver() { GTEST_FLAG(also_run_disabled_tests) = also_run_disabled_tests_; GTEST_FLAG(break_on_failure) = break_on_failure_; GTEST_FLAG(catch_exceptions) = catch_exceptions_; GTEST_FLAG(color) = color_; GTEST_FLAG(death_test_style) = death_test_style_; GTEST_FLAG(death_test_use_fork) = death_test_use_fork_; GTEST_FLAG(filter) = filter_; GTEST_FLAG(internal_run_death_test) = internal_run_death_test_; GTEST_FLAG(list_tests) = list_tests_; GTEST_FLAG(output) = output_; GTEST_FLAG(print_time) = print_time_; GTEST_FLAG(random_seed) = random_seed_; GTEST_FLAG(repeat) = repeat_; GTEST_FLAG(shuffle) = shuffle_; GTEST_FLAG(stack_trace_depth) = stack_trace_depth_; GTEST_FLAG(stream_result_to) = stream_result_to_; GTEST_FLAG(throw_on_failure) = throw_on_failure_; } private: // Fields for saving the original values of flags. bool also_run_disabled_tests_; bool break_on_failure_; bool catch_exceptions_; String color_; String death_test_style_; bool death_test_use_fork_; String filter_; String internal_run_death_test_; bool list_tests_; String output_; bool print_time_; bool pretty_; internal::Int32 random_seed_; internal::Int32 repeat_; bool shuffle_; internal::Int32 stack_trace_depth_; String stream_result_to_; bool throw_on_failure_; } GTEST_ATTRIBUTE_UNUSED_; // Converts a Unicode code point to a narrow string in UTF-8 encoding. // code_point parameter is of type UInt32 because wchar_t may not be // wide enough to contain a code point. // The output buffer str must containt at least 32 characters. // The function returns the address of the output buffer. // If the code_point is not a valid Unicode code point // (i.e. outside of Unicode range U+0 to U+10FFFF) it will be output // as '(Invalid Unicode 0xXXXXXXXX)'. GTEST_API_ char* CodePointToUtf8(UInt32 code_point, char* str); // Converts a wide string to a narrow string in UTF-8 encoding. // The wide string is assumed to have the following encoding: // UTF-16 if sizeof(wchar_t) == 2 (on Windows, Cygwin, Symbian OS) // UTF-32 if sizeof(wchar_t) == 4 (on Linux) // Parameter str points to a null-terminated wide string. // Parameter num_chars may additionally limit the number // of wchar_t characters processed. -1 is used when the entire string // should be processed. // If the string contains code points that are not valid Unicode code points // (i.e. outside of Unicode range U+0 to U+10FFFF) they will be output // as '(Invalid Unicode 0xXXXXXXXX)'. If the string is in UTF16 encoding // and contains invalid UTF-16 surrogate pairs, values in those pairs // will be encoded as individual Unicode characters from Basic Normal Plane. GTEST_API_ String WideStringToUtf8(const wchar_t* str, int num_chars); // Reads the GTEST_SHARD_STATUS_FILE environment variable, and creates the file // if the variable is present. If a file already exists at this location, this // function will write over it. If the variable is present, but the file cannot // be created, prints an error and exits. void WriteToShardStatusFileIfNeeded(); // Checks whether sharding is enabled by examining the relevant // environment variable values. If the variables are present, // but inconsistent (e.g., shard_index >= total_shards), prints // an error and exits. If in_subprocess_for_death_test, sharding is // disabled because it must only be applied to the original test // process. Otherwise, we could filter out death tests we intended to execute. GTEST_API_ bool ShouldShard(const char* total_shards_str, const char* shard_index_str, bool in_subprocess_for_death_test); // Parses the environment variable var as an Int32. If it is unset, // returns default_val. If it is not an Int32, prints an error and // and aborts. GTEST_API_ Int32 Int32FromEnvOrDie(const char* env_var, Int32 default_val); // Given the total number of shards, the shard index, and the test id, // returns true iff the test should be run on this shard. The test id is // some arbitrary but unique non-negative integer assigned to each test // method. Assumes that 0 <= shard_index < total_shards. GTEST_API_ bool ShouldRunTestOnShard( int total_shards, int shard_index, int test_id); // STL container utilities. // Returns the number of elements in the given container that satisfy // the given predicate. template inline int CountIf(const Container& c, Predicate predicate) { // Implemented as an explicit loop since std::count_if() in libCstd on // Solaris has a non-standard signature. int count = 0; for (typename Container::const_iterator it = c.begin(); it != c.end(); ++it) { if (predicate(*it)) ++count; } return count; } // Applies a function/functor to each element in the container. template void ForEach(const Container& c, Functor functor) { std::for_each(c.begin(), c.end(), functor); } // Returns the i-th element of the vector, or default_value if i is not // in range [0, v.size()). template inline E GetElementOr(const std::vector& v, int i, E default_value) { return (i < 0 || i >= static_cast(v.size())) ? default_value : v[i]; } // Performs an in-place shuffle of a range of the vector's elements. // 'begin' and 'end' are element indices as an STL-style range; // i.e. [begin, end) are shuffled, where 'end' == size() means to // shuffle to the end of the vector. template void ShuffleRange(internal::Random* random, int begin, int end, std::vector* v) { const int size = static_cast(v->size()); GTEST_CHECK_(0 <= begin && begin <= size) << "Invalid shuffle range start " << begin << ": must be in range [0, " << size << "]."; GTEST_CHECK_(begin <= end && end <= size) << "Invalid shuffle range finish " << end << ": must be in range [" << begin << ", " << size << "]."; // Fisher-Yates shuffle, from // http://en.wikipedia.org/wiki/Fisher-Yates_shuffle for (int range_width = end - begin; range_width >= 2; range_width--) { const int last_in_range = begin + range_width - 1; const int selected = begin + random->Generate(range_width); std::swap((*v)[selected], (*v)[last_in_range]); } } // Performs an in-place shuffle of the vector's elements. template inline void Shuffle(internal::Random* random, std::vector* v) { ShuffleRange(random, 0, static_cast(v->size()), v); } // A function for deleting an object. Handy for being used as a // functor. template static void Delete(T* x) { delete x; } // A predicate that checks the key of a TestProperty against a known key. // // TestPropertyKeyIs is copyable. class TestPropertyKeyIs { public: // Constructor. // // TestPropertyKeyIs has NO default constructor. explicit TestPropertyKeyIs(const char* key) : key_(key) {} // Returns true iff the test name of test property matches on key_. bool operator()(const TestProperty& test_property) const { return String(test_property.key()).Compare(key_) == 0; } private: String key_; }; // Class UnitTestOptions. // // This class contains functions for processing options the user // specifies when running the tests. It has only static members. // // In most cases, the user can specify an option using either an // environment variable or a command line flag. E.g. you can set the // test filter using either GTEST_FILTER or --gtest_filter. If both // the variable and the flag are present, the latter overrides the // former. class GTEST_API_ UnitTestOptions { public: // Functions for processing the gtest_output flag. // Returns the output format, or "" for normal printed output. static String GetOutputFormat(); // Returns the absolute path of the requested output file, or the // default (test_detail.xml in the original working directory) if // none was explicitly specified. static String GetAbsolutePathToOutputFile(); // Functions for processing the gtest_filter flag. // Returns true iff the wildcard pattern matches the string. The // first ':' or '\0' character in pattern marks the end of it. // // This recursive algorithm isn't very efficient, but is clear and // works well enough for matching test names, which are short. static bool PatternMatchesString(const char *pattern, const char *str); // Returns true iff the user-specified filter matches the test case // name and the test name. static bool FilterMatchesTest(const String &test_case_name, const String &test_name); #if GTEST_OS_WINDOWS // Function for supporting the gtest_catch_exception flag. // Returns EXCEPTION_EXECUTE_HANDLER if Google Test should handle the // given SEH exception, or EXCEPTION_CONTINUE_SEARCH otherwise. // This function is useful as an __except condition. static int GTestShouldProcessSEH(DWORD exception_code); #endif // GTEST_OS_WINDOWS // Returns true if "name" matches the ':' separated list of glob-style // filters in "filter". static bool MatchesFilter(const String& name, const char* filter); }; // Returns the current application's name, removing directory path if that // is present. Used by UnitTestOptions::GetOutputFile. GTEST_API_ FilePath GetCurrentExecutableName(); // The role interface for getting the OS stack trace as a string. class OsStackTraceGetterInterface { public: OsStackTraceGetterInterface() {} virtual ~OsStackTraceGetterInterface() {} // Returns the current OS stack trace as a String. Parameters: // // max_depth - the maximum number of stack frames to be included // in the trace. // skip_count - the number of top frames to be skipped; doesn't count // against max_depth. virtual String CurrentStackTrace(int max_depth, int skip_count) = 0; // UponLeavingGTest() should be called immediately before Google Test calls // user code. It saves some information about the current stack that // CurrentStackTrace() will use to find and hide Google Test stack frames. virtual void UponLeavingGTest() = 0; private: GTEST_DISALLOW_COPY_AND_ASSIGN_(OsStackTraceGetterInterface); }; // A working implementation of the OsStackTraceGetterInterface interface. class OsStackTraceGetter : public OsStackTraceGetterInterface { public: OsStackTraceGetter() : caller_frame_(NULL) {} virtual String CurrentStackTrace(int max_depth, int skip_count); virtual void UponLeavingGTest(); // This string is inserted in place of stack frames that are part of // Google Test's implementation. static const char* const kElidedFramesMarker; private: Mutex mutex_; // protects all internal state // We save the stack frame below the frame that calls user code. // We do this because the address of the frame immediately below // the user code changes between the call to UponLeavingGTest() // and any calls to CurrentStackTrace() from within the user code. void* caller_frame_; GTEST_DISALLOW_COPY_AND_ASSIGN_(OsStackTraceGetter); }; // Information about a Google Test trace point. struct TraceInfo { const char* file; int line; String message; }; // This is the default global test part result reporter used in UnitTestImpl. // This class should only be used by UnitTestImpl. class DefaultGlobalTestPartResultReporter : public TestPartResultReporterInterface { public: explicit DefaultGlobalTestPartResultReporter(UnitTestImpl* unit_test); // Implements the TestPartResultReporterInterface. Reports the test part // result in the current test. virtual void ReportTestPartResult(const TestPartResult& result); private: UnitTestImpl* const unit_test_; GTEST_DISALLOW_COPY_AND_ASSIGN_(DefaultGlobalTestPartResultReporter); }; // This is the default per thread test part result reporter used in // UnitTestImpl. This class should only be used by UnitTestImpl. class DefaultPerThreadTestPartResultReporter : public TestPartResultReporterInterface { public: explicit DefaultPerThreadTestPartResultReporter(UnitTestImpl* unit_test); // Implements the TestPartResultReporterInterface. The implementation just // delegates to the current global test part result reporter of *unit_test_. virtual void ReportTestPartResult(const TestPartResult& result); private: UnitTestImpl* const unit_test_; GTEST_DISALLOW_COPY_AND_ASSIGN_(DefaultPerThreadTestPartResultReporter); }; // The private implementation of the UnitTest class. We don't protect // the methods under a mutex, as this class is not accessible by a // user and the UnitTest class that delegates work to this class does // proper locking. class GTEST_API_ UnitTestImpl { public: explicit UnitTestImpl(UnitTest* parent); virtual ~UnitTestImpl(); // There are two different ways to register your own TestPartResultReporter. // You can register your own repoter to listen either only for test results // from the current thread or for results from all threads. // By default, each per-thread test result repoter just passes a new // TestPartResult to the global test result reporter, which registers the // test part result for the currently running test. // Returns the global test part result reporter. TestPartResultReporterInterface* GetGlobalTestPartResultReporter(); // Sets the global test part result reporter. void SetGlobalTestPartResultReporter( TestPartResultReporterInterface* reporter); // Returns the test part result reporter for the current thread. TestPartResultReporterInterface* GetTestPartResultReporterForCurrentThread(); // Sets the test part result reporter for the current thread. void SetTestPartResultReporterForCurrentThread( TestPartResultReporterInterface* reporter); // Gets the number of successful test cases. int successful_test_case_count() const; // Gets the number of failed test cases. int failed_test_case_count() const; // Gets the number of all test cases. int total_test_case_count() const; // Gets the number of all test cases that contain at least one test // that should run. int test_case_to_run_count() const; // Gets the number of successful tests. int successful_test_count() const; // Gets the number of failed tests. int failed_test_count() const; // Gets the number of disabled tests. int disabled_test_count() const; // Gets the number of all tests. int total_test_count() const; // Gets the number of tests that should run. int test_to_run_count() const; // Gets the elapsed time, in milliseconds. TimeInMillis elapsed_time() const { return elapsed_time_; } // Returns true iff the unit test passed (i.e. all test cases passed). bool Passed() const { return !Failed(); } // Returns true iff the unit test failed (i.e. some test case failed // or something outside of all tests failed). bool Failed() const { return failed_test_case_count() > 0 || ad_hoc_test_result()->Failed(); } // Gets the i-th test case among all the test cases. i can range from 0 to // total_test_case_count() - 1. If i is not in that range, returns NULL. const TestCase* GetTestCase(int i) const { const int index = GetElementOr(test_case_indices_, i, -1); return index < 0 ? NULL : test_cases_[i]; } // Gets the i-th test case among all the test cases. i can range from 0 to // total_test_case_count() - 1. If i is not in that range, returns NULL. TestCase* GetMutableTestCase(int i) { const int index = GetElementOr(test_case_indices_, i, -1); return index < 0 ? NULL : test_cases_[index]; } // Provides access to the event listener list. TestEventListeners* listeners() { return &listeners_; } // Returns the TestResult for the test that's currently running, or // the TestResult for the ad hoc test if no test is running. TestResult* current_test_result(); // Returns the TestResult for the ad hoc test. const TestResult* ad_hoc_test_result() const { return &ad_hoc_test_result_; } // Sets the OS stack trace getter. // // Does nothing if the input and the current OS stack trace getter // are the same; otherwise, deletes the old getter and makes the // input the current getter. void set_os_stack_trace_getter(OsStackTraceGetterInterface* getter); // Returns the current OS stack trace getter if it is not NULL; // otherwise, creates an OsStackTraceGetter, makes it the current // getter, and returns it. OsStackTraceGetterInterface* os_stack_trace_getter(); // Returns the current OS stack trace as a String. // // The maximum number of stack frames to be included is specified by // the gtest_stack_trace_depth flag. The skip_count parameter // specifies the number of top frames to be skipped, which doesn't // count against the number of frames to be included. // // For example, if Foo() calls Bar(), which in turn calls // CurrentOsStackTraceExceptTop(1), Foo() will be included in the // trace but Bar() and CurrentOsStackTraceExceptTop() won't. String CurrentOsStackTraceExceptTop(int skip_count); // Finds and returns a TestCase with the given name. If one doesn't // exist, creates one and returns it. // // Arguments: // // test_case_name: name of the test case // type_param: the name of the test's type parameter, or NULL if // this is not a typed or a type-parameterized test. // set_up_tc: pointer to the function that sets up the test case // tear_down_tc: pointer to the function that tears down the test case TestCase* GetTestCase(const char* test_case_name, const char* type_param, Test::SetUpTestCaseFunc set_up_tc, Test::TearDownTestCaseFunc tear_down_tc); // Adds a TestInfo to the unit test. // // Arguments: // // set_up_tc: pointer to the function that sets up the test case // tear_down_tc: pointer to the function that tears down the test case // test_info: the TestInfo object void AddTestInfo(Test::SetUpTestCaseFunc set_up_tc, Test::TearDownTestCaseFunc tear_down_tc, TestInfo* test_info) { // In order to support thread-safe death tests, we need to // remember the original working directory when the test program // was first invoked. We cannot do this in RUN_ALL_TESTS(), as // the user may have changed the current directory before calling // RUN_ALL_TESTS(). Therefore we capture the current directory in // AddTestInfo(), which is called to register a TEST or TEST_F // before main() is reached. if (original_working_dir_.IsEmpty()) { original_working_dir_.Set(FilePath::GetCurrentDir()); GTEST_CHECK_(!original_working_dir_.IsEmpty()) << "Failed to get the current working directory."; } GetTestCase(test_info->test_case_name(), test_info->type_param(), set_up_tc, tear_down_tc)->AddTestInfo(test_info); } #if GTEST_HAS_PARAM_TEST // Returns ParameterizedTestCaseRegistry object used to keep track of // value-parameterized tests and instantiate and register them. internal::ParameterizedTestCaseRegistry& parameterized_test_registry() { return parameterized_test_registry_; } #endif // GTEST_HAS_PARAM_TEST // Sets the TestCase object for the test that's currently running. void set_current_test_case(TestCase* a_current_test_case) { current_test_case_ = a_current_test_case; } // Sets the TestInfo object for the test that's currently running. If // current_test_info is NULL, the assertion results will be stored in // ad_hoc_test_result_. void set_current_test_info(TestInfo* a_current_test_info) { current_test_info_ = a_current_test_info; } // Registers all parameterized tests defined using TEST_P and // INSTANTIATE_TEST_CASE_P, creating regular tests for each test/parameter // combination. This method can be called more then once; it has guards // protecting from registering the tests more then once. If // value-parameterized tests are disabled, RegisterParameterizedTests is // present but does nothing. void RegisterParameterizedTests(); // Runs all tests in this UnitTest object, prints the result, and // returns true if all tests are successful. If any exception is // thrown during a test, this test is considered to be failed, but // the rest of the tests will still be run. bool RunAllTests(); // Clears the results of all tests, except the ad hoc tests. void ClearNonAdHocTestResult() { ForEach(test_cases_, TestCase::ClearTestCaseResult); } // Clears the results of ad-hoc test assertions. void ClearAdHocTestResult() { ad_hoc_test_result_.Clear(); } enum ReactionToSharding { HONOR_SHARDING_PROTOCOL, IGNORE_SHARDING_PROTOCOL }; // Matches the full name of each test against the user-specified // filter to decide whether the test should run, then records the // result in each TestCase and TestInfo object. // If shard_tests == HONOR_SHARDING_PROTOCOL, further filters tests // based on sharding variables in the environment. // Returns the number of tests that should run. int FilterTests(ReactionToSharding shard_tests); // Prints the names of the tests matching the user-specified filter flag. void ListTestsMatchingFilter(); const TestCase* current_test_case() const { return current_test_case_; } TestInfo* current_test_info() { return current_test_info_; } const TestInfo* current_test_info() const { return current_test_info_; } // Returns the vector of environments that need to be set-up/torn-down // before/after the tests are run. std::vector& environments() { return environments_; } // Getters for the per-thread Google Test trace stack. std::vector& gtest_trace_stack() { return *(gtest_trace_stack_.pointer()); } const std::vector& gtest_trace_stack() const { return gtest_trace_stack_.get(); } #if GTEST_HAS_DEATH_TEST void InitDeathTestSubprocessControlInfo() { internal_run_death_test_flag_.reset(ParseInternalRunDeathTestFlag()); } // Returns a pointer to the parsed --gtest_internal_run_death_test // flag, or NULL if that flag was not specified. // This information is useful only in a death test child process. // Must not be called before a call to InitGoogleTest. const InternalRunDeathTestFlag* internal_run_death_test_flag() const { return internal_run_death_test_flag_.get(); } // Returns a pointer to the current death test factory. internal::DeathTestFactory* death_test_factory() { return death_test_factory_.get(); } void SuppressTestEventsIfInSubprocess(); friend class ReplaceDeathTestFactory; #endif // GTEST_HAS_DEATH_TEST // Initializes the event listener performing XML output as specified by // UnitTestOptions. Must not be called before InitGoogleTest. void ConfigureXmlOutput(); #if GTEST_CAN_STREAM_RESULTS_ // Initializes the event listener for streaming test results to a socket. // Must not be called before InitGoogleTest. void ConfigureStreamingOutput(); #endif // Performs initialization dependent upon flag values obtained in // ParseGoogleTestFlagsOnly. Is called from InitGoogleTest after the call to // ParseGoogleTestFlagsOnly. In case a user neglects to call InitGoogleTest // this function is also called from RunAllTests. Since this function can be // called more than once, it has to be idempotent. void PostFlagParsingInit(); // Gets the random seed used at the start of the current test iteration. int random_seed() const { return random_seed_; } // Gets the random number generator. internal::Random* random() { return &random_; } // Shuffles all test cases, and the tests within each test case, // making sure that death tests are still run first. void ShuffleTests(); // Restores the test cases and tests to their order before the first shuffle. void UnshuffleTests(); // Returns the value of GTEST_FLAG(catch_exceptions) at the moment // UnitTest::Run() starts. bool catch_exceptions() const { return catch_exceptions_; } private: friend class ::testing::UnitTest; // Used by UnitTest::Run() to capture the state of // GTEST_FLAG(catch_exceptions) at the moment it starts. void set_catch_exceptions(bool value) { catch_exceptions_ = value; } // The UnitTest object that owns this implementation object. UnitTest* const parent_; // The working directory when the first TEST() or TEST_F() was // executed. internal::FilePath original_working_dir_; // The default test part result reporters. DefaultGlobalTestPartResultReporter default_global_test_part_result_reporter_; DefaultPerThreadTestPartResultReporter default_per_thread_test_part_result_reporter_; // Points to (but doesn't own) the global test part result reporter. TestPartResultReporterInterface* global_test_part_result_repoter_; // Protects read and write access to global_test_part_result_reporter_. internal::Mutex global_test_part_result_reporter_mutex_; // Points to (but doesn't own) the per-thread test part result reporter. internal::ThreadLocal per_thread_test_part_result_reporter_; // The vector of environments that need to be set-up/torn-down // before/after the tests are run. std::vector environments_; // The vector of TestCases in their original order. It owns the // elements in the vector. std::vector test_cases_; // Provides a level of indirection for the test case list to allow // easy shuffling and restoring the test case order. The i-th // element of this vector is the index of the i-th test case in the // shuffled order. std::vector test_case_indices_; #if GTEST_HAS_PARAM_TEST // ParameterizedTestRegistry object used to register value-parameterized // tests. internal::ParameterizedTestCaseRegistry parameterized_test_registry_; // Indicates whether RegisterParameterizedTests() has been called already. bool parameterized_tests_registered_; #endif // GTEST_HAS_PARAM_TEST // Index of the last death test case registered. Initially -1. int last_death_test_case_; // This points to the TestCase for the currently running test. It // changes as Google Test goes through one test case after another. // When no test is running, this is set to NULL and Google Test // stores assertion results in ad_hoc_test_result_. Initially NULL. TestCase* current_test_case_; // This points to the TestInfo for the currently running test. It // changes as Google Test goes through one test after another. When // no test is running, this is set to NULL and Google Test stores // assertion results in ad_hoc_test_result_. Initially NULL. TestInfo* current_test_info_; // Normally, a user only writes assertions inside a TEST or TEST_F, // or inside a function called by a TEST or TEST_F. Since Google // Test keeps track of which test is current running, it can // associate such an assertion with the test it belongs to. // // If an assertion is encountered when no TEST or TEST_F is running, // Google Test attributes the assertion result to an imaginary "ad hoc" // test, and records the result in ad_hoc_test_result_. TestResult ad_hoc_test_result_; // The list of event listeners that can be used to track events inside // Google Test. TestEventListeners listeners_; // The OS stack trace getter. Will be deleted when the UnitTest // object is destructed. By default, an OsStackTraceGetter is used, // but the user can set this field to use a custom getter if that is // desired. OsStackTraceGetterInterface* os_stack_trace_getter_; // True iff PostFlagParsingInit() has been called. bool post_flag_parse_init_performed_; // The random number seed used at the beginning of the test run. int random_seed_; // Our random number generator. internal::Random random_; // How long the test took to run, in milliseconds. TimeInMillis elapsed_time_; #if GTEST_HAS_DEATH_TEST // The decomposed components of the gtest_internal_run_death_test flag, // parsed when RUN_ALL_TESTS is called. internal::scoped_ptr internal_run_death_test_flag_; internal::scoped_ptr death_test_factory_; #endif // GTEST_HAS_DEATH_TEST // A per-thread stack of traces created by the SCOPED_TRACE() macro. internal::ThreadLocal > gtest_trace_stack_; // The value of GTEST_FLAG(catch_exceptions) at the moment RunAllTests() // starts. bool catch_exceptions_; GTEST_DISALLOW_COPY_AND_ASSIGN_(UnitTestImpl); }; // class UnitTestImpl // Convenience function for accessing the global UnitTest // implementation object. inline UnitTestImpl* GetUnitTestImpl() { return UnitTest::GetInstance()->impl(); } #if GTEST_USES_SIMPLE_RE // Internal helper functions for implementing the simple regular // expression matcher. GTEST_API_ bool IsInSet(char ch, const char* str); GTEST_API_ bool IsAsciiDigit(char ch); GTEST_API_ bool IsAsciiPunct(char ch); GTEST_API_ bool IsRepeat(char ch); GTEST_API_ bool IsAsciiWhiteSpace(char ch); GTEST_API_ bool IsAsciiWordChar(char ch); GTEST_API_ bool IsValidEscape(char ch); GTEST_API_ bool AtomMatchesChar(bool escaped, char pattern, char ch); GTEST_API_ bool ValidateRegex(const char* regex); GTEST_API_ bool MatchRegexAtHead(const char* regex, const char* str); GTEST_API_ bool MatchRepetitionAndRegexAtHead( bool escaped, char ch, char repeat, const char* regex, const char* str); GTEST_API_ bool MatchRegexAnywhere(const char* regex, const char* str); #endif // GTEST_USES_SIMPLE_RE // Parses the command line for Google Test flags, without initializing // other parts of Google Test. GTEST_API_ void ParseGoogleTestFlagsOnly(int* argc, char** argv); GTEST_API_ void ParseGoogleTestFlagsOnly(int* argc, wchar_t** argv); #if GTEST_HAS_DEATH_TEST // Returns the message describing the last system error, regardless of the // platform. GTEST_API_ String GetLastErrnoDescription(); # if GTEST_OS_WINDOWS // Provides leak-safe Windows kernel handle ownership. class AutoHandle { public: AutoHandle() : handle_(INVALID_HANDLE_VALUE) {} explicit AutoHandle(HANDLE handle) : handle_(handle) {} ~AutoHandle() { Reset(); } HANDLE Get() const { return handle_; } void Reset() { Reset(INVALID_HANDLE_VALUE); } void Reset(HANDLE handle) { if (handle != handle_) { if (handle_ != INVALID_HANDLE_VALUE) ::CloseHandle(handle_); handle_ = handle; } } private: HANDLE handle_; GTEST_DISALLOW_COPY_AND_ASSIGN_(AutoHandle); }; # endif // GTEST_OS_WINDOWS // Attempts to parse a string into a positive integer pointed to by the // number parameter. Returns true if that is possible. // GTEST_HAS_DEATH_TEST implies that we have ::std::string, so we can use // it here. template bool ParseNaturalNumber(const ::std::string& str, Integer* number) { // Fail fast if the given string does not begin with a digit; // this bypasses strtoXXX's "optional leading whitespace and plus // or minus sign" semantics, which are undesirable here. if (str.empty() || !IsDigit(str[0])) { return false; } errno = 0; char* end; // BiggestConvertible is the largest integer type that system-provided // string-to-number conversion routines can return. # if GTEST_OS_WINDOWS && !defined(__GNUC__) // MSVC and C++ Builder define __int64 instead of the standard long long. typedef unsigned __int64 BiggestConvertible; const BiggestConvertible parsed = _strtoui64(str.c_str(), &end, 10); # else typedef unsigned long long BiggestConvertible; // NOLINT const BiggestConvertible parsed = strtoull(str.c_str(), &end, 10); # endif // GTEST_OS_WINDOWS && !defined(__GNUC__) const bool parse_success = *end == '\0' && errno == 0; // TODO(vladl@google.com): Convert this to compile time assertion when it is // available. GTEST_CHECK_(sizeof(Integer) <= sizeof(parsed)); const Integer result = static_cast(parsed); if (parse_success && static_cast(result) == parsed) { *number = result; return true; } return false; } #endif // GTEST_HAS_DEATH_TEST // TestResult contains some private methods that should be hidden from // Google Test user but are required for testing. This class allow our tests // to access them. // // This class is supplied only for the purpose of testing Google Test's own // constructs. Do not use it in user tests, either directly or indirectly. class TestResultAccessor { public: static void RecordProperty(TestResult* test_result, const TestProperty& property) { test_result->RecordProperty(property); } static void ClearTestPartResults(TestResult* test_result) { test_result->ClearTestPartResults(); } static const std::vector& test_part_results( const TestResult& test_result) { return test_result.test_part_results(); } }; } // namespace internal } // namespace testing #endif // GTEST_SRC_GTEST_INTERNAL_INL_H_ ugene-1.9.8/src/libs_3rdparty/gtest/src/src/gtest-typed-test.cc0000644000175000017500000000724311651544307023137 0ustar ilyailya// Copyright 2008 Google Inc. // All Rights Reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Author: wan@google.com (Zhanyong Wan) #include "gtest/gtest-typed-test.h" #include "gtest/gtest.h" namespace testing { namespace internal { #if GTEST_HAS_TYPED_TEST_P // Skips to the first non-space char in str. Returns an empty string if str // contains only whitespace characters. static const char* SkipSpaces(const char* str) { while (IsSpace(*str)) str++; return str; } // Verifies that registered_tests match the test names in // defined_test_names_; returns registered_tests if successful, or // aborts the program otherwise. const char* TypedTestCasePState::VerifyRegisteredTestNames( const char* file, int line, const char* registered_tests) { typedef ::std::set::const_iterator DefinedTestIter; registered_ = true; // Skip initial whitespace in registered_tests since some // preprocessors prefix stringizied literals with whitespace. registered_tests = SkipSpaces(registered_tests); Message errors; ::std::set tests; for (const char* names = registered_tests; names != NULL; names = SkipComma(names)) { const String name = GetPrefixUntilComma(names); if (tests.count(name) != 0) { errors << "Test " << name << " is listed more than once.\n"; continue; } bool found = false; for (DefinedTestIter it = defined_test_names_.begin(); it != defined_test_names_.end(); ++it) { if (name == *it) { found = true; break; } } if (found) { tests.insert(name); } else { errors << "No test named " << name << " can be found in this test case.\n"; } } for (DefinedTestIter it = defined_test_names_.begin(); it != defined_test_names_.end(); ++it) { if (tests.count(*it) == 0) { errors << "You forgot to list test " << *it << ".\n"; } } const String& errors_str = errors.GetString(); if (errors_str != "") { fprintf(stderr, "%s %s", FormatFileLocation(file, line).c_str(), errors_str.c_str()); fflush(stderr); posix::Abort(); } return registered_tests; } #endif // GTEST_HAS_TYPED_TEST_P } // namespace internal } // namespace testing ugene-1.9.8/src/libs_3rdparty/gtest/src/src/gtest-death-test.cc0000644000175000017500000013251511651544307023100 0ustar ilyailya// Copyright 2005, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Author: wan@google.com (Zhanyong Wan), vladl@google.com (Vlad Losev) // // This file implements death tests. #include "gtest/gtest-death-test.h" #include "gtest/internal/gtest-port.h" #if GTEST_HAS_DEATH_TEST # if GTEST_OS_MAC # include # endif // GTEST_OS_MAC # include # include # include # include # if GTEST_OS_WINDOWS # include # else # include # include # endif // GTEST_OS_WINDOWS #endif // GTEST_HAS_DEATH_TEST #include "gtest/gtest-message.h" #include "gtest/internal/gtest-string.h" // Indicates that this translation unit is part of Google Test's // implementation. It must come before gtest-internal-inl.h is // included, or there will be a compiler error. This trick is to // prevent a user from accidentally including gtest-internal-inl.h in // his code. #define GTEST_IMPLEMENTATION_ 1 #include "src/gtest-internal-inl.h" #undef GTEST_IMPLEMENTATION_ namespace testing { // Constants. // The default death test style. static const char kDefaultDeathTestStyle[] = "fast"; GTEST_DEFINE_string_( death_test_style, internal::StringFromGTestEnv("death_test_style", kDefaultDeathTestStyle), "Indicates how to run a death test in a forked child process: " "\"threadsafe\" (child process re-executes the test binary " "from the beginning, running only the specific death test) or " "\"fast\" (child process runs the death test immediately " "after forking)."); GTEST_DEFINE_bool_( death_test_use_fork, internal::BoolFromGTestEnv("death_test_use_fork", false), "Instructs to use fork()/_exit() instead of clone() in death tests. " "Ignored and always uses fork() on POSIX systems where clone() is not " "implemented. Useful when running under valgrind or similar tools if " "those do not support clone(). Valgrind 3.3.1 will just fail if " "it sees an unsupported combination of clone() flags. " "It is not recommended to use this flag w/o valgrind though it will " "work in 99% of the cases. Once valgrind is fixed, this flag will " "most likely be removed."); namespace internal { GTEST_DEFINE_string_( internal_run_death_test, "", "Indicates the file, line number, temporal index of " "the single death test to run, and a file descriptor to " "which a success code may be sent, all separated by " "colons. This flag is specified if and only if the current " "process is a sub-process launched for running a thread-safe " "death test. FOR INTERNAL USE ONLY."); } // namespace internal #if GTEST_HAS_DEATH_TEST // ExitedWithCode constructor. ExitedWithCode::ExitedWithCode(int exit_code) : exit_code_(exit_code) { } // ExitedWithCode function-call operator. bool ExitedWithCode::operator()(int exit_status) const { # if GTEST_OS_WINDOWS return exit_status == exit_code_; # else return WIFEXITED(exit_status) && WEXITSTATUS(exit_status) == exit_code_; # endif // GTEST_OS_WINDOWS } # if !GTEST_OS_WINDOWS // KilledBySignal constructor. KilledBySignal::KilledBySignal(int signum) : signum_(signum) { } // KilledBySignal function-call operator. bool KilledBySignal::operator()(int exit_status) const { return WIFSIGNALED(exit_status) && WTERMSIG(exit_status) == signum_; } # endif // !GTEST_OS_WINDOWS namespace internal { // Utilities needed for death tests. // Generates a textual description of a given exit code, in the format // specified by wait(2). static String ExitSummary(int exit_code) { Message m; # if GTEST_OS_WINDOWS m << "Exited with exit status " << exit_code; # else if (WIFEXITED(exit_code)) { m << "Exited with exit status " << WEXITSTATUS(exit_code); } else if (WIFSIGNALED(exit_code)) { m << "Terminated by signal " << WTERMSIG(exit_code); } # ifdef WCOREDUMP if (WCOREDUMP(exit_code)) { m << " (core dumped)"; } # endif # endif // GTEST_OS_WINDOWS return m.GetString(); } // Returns true if exit_status describes a process that was terminated // by a signal, or exited normally with a nonzero exit code. bool ExitedUnsuccessfully(int exit_status) { return !ExitedWithCode(0)(exit_status); } # if !GTEST_OS_WINDOWS // Generates a textual failure message when a death test finds more than // one thread running, or cannot determine the number of threads, prior // to executing the given statement. It is the responsibility of the // caller not to pass a thread_count of 1. static String DeathTestThreadWarning(size_t thread_count) { Message msg; msg << "Death tests use fork(), which is unsafe particularly" << " in a threaded context. For this test, " << GTEST_NAME_ << " "; if (thread_count == 0) msg << "couldn't detect the number of threads."; else msg << "detected " << thread_count << " threads."; return msg.GetString(); } # endif // !GTEST_OS_WINDOWS // Flag characters for reporting a death test that did not die. static const char kDeathTestLived = 'L'; static const char kDeathTestReturned = 'R'; static const char kDeathTestThrew = 'T'; static const char kDeathTestInternalError = 'I'; // An enumeration describing all of the possible ways that a death test can // conclude. DIED means that the process died while executing the test // code; LIVED means that process lived beyond the end of the test code; // RETURNED means that the test statement attempted to execute a return // statement, which is not allowed; THREW means that the test statement // returned control by throwing an exception. IN_PROGRESS means the test // has not yet concluded. // TODO(vladl@google.com): Unify names and possibly values for // AbortReason, DeathTestOutcome, and flag characters above. enum DeathTestOutcome { IN_PROGRESS, DIED, LIVED, RETURNED, THREW }; // Routine for aborting the program which is safe to call from an // exec-style death test child process, in which case the error // message is propagated back to the parent process. Otherwise, the // message is simply printed to stderr. In either case, the program // then exits with status 1. void DeathTestAbort(const String& message) { // On a POSIX system, this function may be called from a threadsafe-style // death test child process, which operates on a very small stack. Use // the heap for any additional non-minuscule memory requirements. const InternalRunDeathTestFlag* const flag = GetUnitTestImpl()->internal_run_death_test_flag(); if (flag != NULL) { FILE* parent = posix::FDOpen(flag->write_fd(), "w"); fputc(kDeathTestInternalError, parent); fprintf(parent, "%s", message.c_str()); fflush(parent); _exit(1); } else { fprintf(stderr, "%s", message.c_str()); fflush(stderr); posix::Abort(); } } // A replacement for CHECK that calls DeathTestAbort if the assertion // fails. # define GTEST_DEATH_TEST_CHECK_(expression) \ do { \ if (!::testing::internal::IsTrue(expression)) { \ DeathTestAbort(::testing::internal::String::Format( \ "CHECK failed: File %s, line %d: %s", \ __FILE__, __LINE__, #expression)); \ } \ } while (::testing::internal::AlwaysFalse()) // This macro is similar to GTEST_DEATH_TEST_CHECK_, but it is meant for // evaluating any system call that fulfills two conditions: it must return // -1 on failure, and set errno to EINTR when it is interrupted and // should be tried again. The macro expands to a loop that repeatedly // evaluates the expression as long as it evaluates to -1 and sets // errno to EINTR. If the expression evaluates to -1 but errno is // something other than EINTR, DeathTestAbort is called. # define GTEST_DEATH_TEST_CHECK_SYSCALL_(expression) \ do { \ int gtest_retval; \ do { \ gtest_retval = (expression); \ } while (gtest_retval == -1 && errno == EINTR); \ if (gtest_retval == -1) { \ DeathTestAbort(::testing::internal::String::Format( \ "CHECK failed: File %s, line %d: %s != -1", \ __FILE__, __LINE__, #expression)); \ } \ } while (::testing::internal::AlwaysFalse()) // Returns the message describing the last system error in errno. String GetLastErrnoDescription() { return String(errno == 0 ? "" : posix::StrError(errno)); } // This is called from a death test parent process to read a failure // message from the death test child process and log it with the FATAL // severity. On Windows, the message is read from a pipe handle. On other // platforms, it is read from a file descriptor. static void FailFromInternalError(int fd) { Message error; char buffer[256]; int num_read; do { while ((num_read = posix::Read(fd, buffer, 255)) > 0) { buffer[num_read] = '\0'; error << buffer; } } while (num_read == -1 && errno == EINTR); if (num_read == 0) { GTEST_LOG_(FATAL) << error.GetString(); } else { const int last_error = errno; GTEST_LOG_(FATAL) << "Error while reading death test internal: " << GetLastErrnoDescription() << " [" << last_error << "]"; } } // Death test constructor. Increments the running death test count // for the current test. DeathTest::DeathTest() { TestInfo* const info = GetUnitTestImpl()->current_test_info(); if (info == NULL) { DeathTestAbort("Cannot run a death test outside of a TEST or " "TEST_F construct"); } } // Creates and returns a death test by dispatching to the current // death test factory. bool DeathTest::Create(const char* statement, const RE* regex, const char* file, int line, DeathTest** test) { return GetUnitTestImpl()->death_test_factory()->Create( statement, regex, file, line, test); } const char* DeathTest::LastMessage() { return last_death_test_message_.c_str(); } void DeathTest::set_last_death_test_message(const String& message) { last_death_test_message_ = message; } String DeathTest::last_death_test_message_; // Provides cross platform implementation for some death functionality. class DeathTestImpl : public DeathTest { protected: DeathTestImpl(const char* a_statement, const RE* a_regex) : statement_(a_statement), regex_(a_regex), spawned_(false), status_(-1), outcome_(IN_PROGRESS), read_fd_(-1), write_fd_(-1) {} // read_fd_ is expected to be closed and cleared by a derived class. ~DeathTestImpl() { GTEST_DEATH_TEST_CHECK_(read_fd_ == -1); } void Abort(AbortReason reason); virtual bool Passed(bool status_ok); const char* statement() const { return statement_; } const RE* regex() const { return regex_; } bool spawned() const { return spawned_; } void set_spawned(bool is_spawned) { spawned_ = is_spawned; } int status() const { return status_; } void set_status(int a_status) { status_ = a_status; } DeathTestOutcome outcome() const { return outcome_; } void set_outcome(DeathTestOutcome an_outcome) { outcome_ = an_outcome; } int read_fd() const { return read_fd_; } void set_read_fd(int fd) { read_fd_ = fd; } int write_fd() const { return write_fd_; } void set_write_fd(int fd) { write_fd_ = fd; } // Called in the parent process only. Reads the result code of the death // test child process via a pipe, interprets it to set the outcome_ // member, and closes read_fd_. Outputs diagnostics and terminates in // case of unexpected codes. void ReadAndInterpretStatusByte(); private: // The textual content of the code this object is testing. This class // doesn't own this string and should not attempt to delete it. const char* const statement_; // The regular expression which test output must match. DeathTestImpl // doesn't own this object and should not attempt to delete it. const RE* const regex_; // True if the death test child process has been successfully spawned. bool spawned_; // The exit status of the child process. int status_; // How the death test concluded. DeathTestOutcome outcome_; // Descriptor to the read end of the pipe to the child process. It is // always -1 in the child process. The child keeps its write end of the // pipe in write_fd_. int read_fd_; // Descriptor to the child's write end of the pipe to the parent process. // It is always -1 in the parent process. The parent keeps its end of the // pipe in read_fd_. int write_fd_; }; // Called in the parent process only. Reads the result code of the death // test child process via a pipe, interprets it to set the outcome_ // member, and closes read_fd_. Outputs diagnostics and terminates in // case of unexpected codes. void DeathTestImpl::ReadAndInterpretStatusByte() { char flag; int bytes_read; // The read() here blocks until data is available (signifying the // failure of the death test) or until the pipe is closed (signifying // its success), so it's okay to call this in the parent before // the child process has exited. do { bytes_read = posix::Read(read_fd(), &flag, 1); } while (bytes_read == -1 && errno == EINTR); if (bytes_read == 0) { set_outcome(DIED); } else if (bytes_read == 1) { switch (flag) { case kDeathTestReturned: set_outcome(RETURNED); break; case kDeathTestThrew: set_outcome(THREW); break; case kDeathTestLived: set_outcome(LIVED); break; case kDeathTestInternalError: FailFromInternalError(read_fd()); // Does not return. break; default: GTEST_LOG_(FATAL) << "Death test child process reported " << "unexpected status byte (" << static_cast(flag) << ")"; } } else { GTEST_LOG_(FATAL) << "Read from death test child process failed: " << GetLastErrnoDescription(); } GTEST_DEATH_TEST_CHECK_SYSCALL_(posix::Close(read_fd())); set_read_fd(-1); } // Signals that the death test code which should have exited, didn't. // Should be called only in a death test child process. // Writes a status byte to the child's status file descriptor, then // calls _exit(1). void DeathTestImpl::Abort(AbortReason reason) { // The parent process considers the death test to be a failure if // it finds any data in our pipe. So, here we write a single flag byte // to the pipe, then exit. const char status_ch = reason == TEST_DID_NOT_DIE ? kDeathTestLived : reason == TEST_THREW_EXCEPTION ? kDeathTestThrew : kDeathTestReturned; GTEST_DEATH_TEST_CHECK_SYSCALL_(posix::Write(write_fd(), &status_ch, 1)); // We are leaking the descriptor here because on some platforms (i.e., // when built as Windows DLL), destructors of global objects will still // run after calling _exit(). On such systems, write_fd_ will be // indirectly closed from the destructor of UnitTestImpl, causing double // close if it is also closed here. On debug configurations, double close // may assert. As there are no in-process buffers to flush here, we are // relying on the OS to close the descriptor after the process terminates // when the destructors are not run. _exit(1); // Exits w/o any normal exit hooks (we were supposed to crash) } // Returns an indented copy of stderr output for a death test. // This makes distinguishing death test output lines from regular log lines // much easier. static ::std::string FormatDeathTestOutput(const ::std::string& output) { ::std::string ret; for (size_t at = 0; ; ) { const size_t line_end = output.find('\n', at); ret += "[ DEATH ] "; if (line_end == ::std::string::npos) { ret += output.substr(at); break; } ret += output.substr(at, line_end + 1 - at); at = line_end + 1; } return ret; } // Assesses the success or failure of a death test, using both private // members which have previously been set, and one argument: // // Private data members: // outcome: An enumeration describing how the death test // concluded: DIED, LIVED, THREW, or RETURNED. The death test // fails in the latter three cases. // status: The exit status of the child process. On *nix, it is in the // in the format specified by wait(2). On Windows, this is the // value supplied to the ExitProcess() API or a numeric code // of the exception that terminated the program. // regex: A regular expression object to be applied to // the test's captured standard error output; the death test // fails if it does not match. // // Argument: // status_ok: true if exit_status is acceptable in the context of // this particular death test, which fails if it is false // // Returns true iff all of the above conditions are met. Otherwise, the // first failing condition, in the order given above, is the one that is // reported. Also sets the last death test message string. bool DeathTestImpl::Passed(bool status_ok) { if (!spawned()) return false; const String error_message = GetCapturedStderr(); bool success = false; Message buffer; buffer << "Death test: " << statement() << "\n"; switch (outcome()) { case LIVED: buffer << " Result: failed to die.\n" << " Error msg:\n" << FormatDeathTestOutput(error_message); break; case THREW: buffer << " Result: threw an exception.\n" << " Error msg:\n" << FormatDeathTestOutput(error_message); break; case RETURNED: buffer << " Result: illegal return in test statement.\n" << " Error msg:\n" << FormatDeathTestOutput(error_message); break; case DIED: if (status_ok) { const bool matched = RE::PartialMatch(error_message.c_str(), *regex()); if (matched) { success = true; } else { buffer << " Result: died but not with expected error.\n" << " Expected: " << regex()->pattern() << "\n" << "Actual msg:\n" << FormatDeathTestOutput(error_message); } } else { buffer << " Result: died but not with expected exit code:\n" << " " << ExitSummary(status()) << "\n" << "Actual msg:\n" << FormatDeathTestOutput(error_message); } break; case IN_PROGRESS: default: GTEST_LOG_(FATAL) << "DeathTest::Passed somehow called before conclusion of test"; } DeathTest::set_last_death_test_message(buffer.GetString()); return success; } # if GTEST_OS_WINDOWS // WindowsDeathTest implements death tests on Windows. Due to the // specifics of starting new processes on Windows, death tests there are // always threadsafe, and Google Test considers the // --gtest_death_test_style=fast setting to be equivalent to // --gtest_death_test_style=threadsafe there. // // A few implementation notes: Like the Linux version, the Windows // implementation uses pipes for child-to-parent communication. But due to // the specifics of pipes on Windows, some extra steps are required: // // 1. The parent creates a communication pipe and stores handles to both // ends of it. // 2. The parent starts the child and provides it with the information // necessary to acquire the handle to the write end of the pipe. // 3. The child acquires the write end of the pipe and signals the parent // using a Windows event. // 4. Now the parent can release the write end of the pipe on its side. If // this is done before step 3, the object's reference count goes down to // 0 and it is destroyed, preventing the child from acquiring it. The // parent now has to release it, or read operations on the read end of // the pipe will not return when the child terminates. // 5. The parent reads child's output through the pipe (outcome code and // any possible error messages) from the pipe, and its stderr and then // determines whether to fail the test. // // Note: to distinguish Win32 API calls from the local method and function // calls, the former are explicitly resolved in the global namespace. // class WindowsDeathTest : public DeathTestImpl { public: WindowsDeathTest(const char* a_statement, const RE* a_regex, const char* file, int line) : DeathTestImpl(a_statement, a_regex), file_(file), line_(line) {} // All of these virtual functions are inherited from DeathTest. virtual int Wait(); virtual TestRole AssumeRole(); private: // The name of the file in which the death test is located. const char* const file_; // The line number on which the death test is located. const int line_; // Handle to the write end of the pipe to the child process. AutoHandle write_handle_; // Child process handle. AutoHandle child_handle_; // Event the child process uses to signal the parent that it has // acquired the handle to the write end of the pipe. After seeing this // event the parent can release its own handles to make sure its // ReadFile() calls return when the child terminates. AutoHandle event_handle_; }; // Waits for the child in a death test to exit, returning its exit // status, or 0 if no child process exists. As a side effect, sets the // outcome data member. int WindowsDeathTest::Wait() { if (!spawned()) return 0; // Wait until the child either signals that it has acquired the write end // of the pipe or it dies. const HANDLE wait_handles[2] = { child_handle_.Get(), event_handle_.Get() }; switch (::WaitForMultipleObjects(2, wait_handles, FALSE, // Waits for any of the handles. INFINITE)) { case WAIT_OBJECT_0: case WAIT_OBJECT_0 + 1: break; default: GTEST_DEATH_TEST_CHECK_(false); // Should not get here. } // The child has acquired the write end of the pipe or exited. // We release the handle on our side and continue. write_handle_.Reset(); event_handle_.Reset(); ReadAndInterpretStatusByte(); // Waits for the child process to exit if it haven't already. This // returns immediately if the child has already exited, regardless of // whether previous calls to WaitForMultipleObjects synchronized on this // handle or not. GTEST_DEATH_TEST_CHECK_( WAIT_OBJECT_0 == ::WaitForSingleObject(child_handle_.Get(), INFINITE)); DWORD status_code; GTEST_DEATH_TEST_CHECK_( ::GetExitCodeProcess(child_handle_.Get(), &status_code) != FALSE); child_handle_.Reset(); set_status(static_cast(status_code)); return status(); } // The AssumeRole process for a Windows death test. It creates a child // process with the same executable as the current process to run the // death test. The child process is given the --gtest_filter and // --gtest_internal_run_death_test flags such that it knows to run the // current death test only. DeathTest::TestRole WindowsDeathTest::AssumeRole() { const UnitTestImpl* const impl = GetUnitTestImpl(); const InternalRunDeathTestFlag* const flag = impl->internal_run_death_test_flag(); const TestInfo* const info = impl->current_test_info(); const int death_test_index = info->result()->death_test_count(); if (flag != NULL) { // ParseInternalRunDeathTestFlag() has performed all the necessary // processing. set_write_fd(flag->write_fd()); return EXECUTE_TEST; } // WindowsDeathTest uses an anonymous pipe to communicate results of // a death test. SECURITY_ATTRIBUTES handles_are_inheritable = { sizeof(SECURITY_ATTRIBUTES), NULL, TRUE }; HANDLE read_handle, write_handle; GTEST_DEATH_TEST_CHECK_( ::CreatePipe(&read_handle, &write_handle, &handles_are_inheritable, 0) // Default buffer size. != FALSE); set_read_fd(::_open_osfhandle(reinterpret_cast(read_handle), O_RDONLY)); write_handle_.Reset(write_handle); event_handle_.Reset(::CreateEvent( &handles_are_inheritable, TRUE, // The event will automatically reset to non-signaled state. FALSE, // The initial state is non-signalled. NULL)); // The even is unnamed. GTEST_DEATH_TEST_CHECK_(event_handle_.Get() != NULL); const String filter_flag = String::Format("--%s%s=%s.%s", GTEST_FLAG_PREFIX_, kFilterFlag, info->test_case_name(), info->name()); const String internal_flag = String::Format( "--%s%s=%s|%d|%d|%u|%Iu|%Iu", GTEST_FLAG_PREFIX_, kInternalRunDeathTestFlag, file_, line_, death_test_index, static_cast(::GetCurrentProcessId()), // size_t has the same with as pointers on both 32-bit and 64-bit // Windows platforms. // See http://msdn.microsoft.com/en-us/library/tcxf1dw6.aspx. reinterpret_cast(write_handle), reinterpret_cast(event_handle_.Get())); char executable_path[_MAX_PATH + 1]; // NOLINT GTEST_DEATH_TEST_CHECK_( _MAX_PATH + 1 != ::GetModuleFileNameA(NULL, executable_path, _MAX_PATH)); String command_line = String::Format("%s %s \"%s\"", ::GetCommandLineA(), filter_flag.c_str(), internal_flag.c_str()); DeathTest::set_last_death_test_message(""); CaptureStderr(); // Flush the log buffers since the log streams are shared with the child. FlushInfoLog(); // The child process will share the standard handles with the parent. STARTUPINFOA startup_info; memset(&startup_info, 0, sizeof(STARTUPINFO)); startup_info.dwFlags = STARTF_USESTDHANDLES; startup_info.hStdInput = ::GetStdHandle(STD_INPUT_HANDLE); startup_info.hStdOutput = ::GetStdHandle(STD_OUTPUT_HANDLE); startup_info.hStdError = ::GetStdHandle(STD_ERROR_HANDLE); PROCESS_INFORMATION process_info; GTEST_DEATH_TEST_CHECK_(::CreateProcessA( executable_path, const_cast(command_line.c_str()), NULL, // Retuned process handle is not inheritable. NULL, // Retuned thread handle is not inheritable. TRUE, // Child inherits all inheritable handles (for write_handle_). 0x0, // Default creation flags. NULL, // Inherit the parent's environment. UnitTest::GetInstance()->original_working_dir(), &startup_info, &process_info) != FALSE); child_handle_.Reset(process_info.hProcess); ::CloseHandle(process_info.hThread); set_spawned(true); return OVERSEE_TEST; } # else // We are not on Windows. // ForkingDeathTest provides implementations for most of the abstract // methods of the DeathTest interface. Only the AssumeRole method is // left undefined. class ForkingDeathTest : public DeathTestImpl { public: ForkingDeathTest(const char* statement, const RE* regex); // All of these virtual functions are inherited from DeathTest. virtual int Wait(); protected: void set_child_pid(pid_t child_pid) { child_pid_ = child_pid; } private: // PID of child process during death test; 0 in the child process itself. pid_t child_pid_; }; // Constructs a ForkingDeathTest. ForkingDeathTest::ForkingDeathTest(const char* a_statement, const RE* a_regex) : DeathTestImpl(a_statement, a_regex), child_pid_(-1) {} // Waits for the child in a death test to exit, returning its exit // status, or 0 if no child process exists. As a side effect, sets the // outcome data member. int ForkingDeathTest::Wait() { if (!spawned()) return 0; ReadAndInterpretStatusByte(); int status_value; GTEST_DEATH_TEST_CHECK_SYSCALL_(waitpid(child_pid_, &status_value, 0)); set_status(status_value); return status_value; } // A concrete death test class that forks, then immediately runs the test // in the child process. class NoExecDeathTest : public ForkingDeathTest { public: NoExecDeathTest(const char* a_statement, const RE* a_regex) : ForkingDeathTest(a_statement, a_regex) { } virtual TestRole AssumeRole(); }; // The AssumeRole process for a fork-and-run death test. It implements a // straightforward fork, with a simple pipe to transmit the status byte. DeathTest::TestRole NoExecDeathTest::AssumeRole() { const size_t thread_count = GetThreadCount(); if (thread_count != 1) { GTEST_LOG_(WARNING) << DeathTestThreadWarning(thread_count); } int pipe_fd[2]; GTEST_DEATH_TEST_CHECK_(pipe(pipe_fd) != -1); DeathTest::set_last_death_test_message(""); CaptureStderr(); // When we fork the process below, the log file buffers are copied, but the // file descriptors are shared. We flush all log files here so that closing // the file descriptors in the child process doesn't throw off the // synchronization between descriptors and buffers in the parent process. // This is as close to the fork as possible to avoid a race condition in case // there are multiple threads running before the death test, and another // thread writes to the log file. FlushInfoLog(); const pid_t child_pid = fork(); GTEST_DEATH_TEST_CHECK_(child_pid != -1); set_child_pid(child_pid); if (child_pid == 0) { GTEST_DEATH_TEST_CHECK_SYSCALL_(close(pipe_fd[0])); set_write_fd(pipe_fd[1]); // Redirects all logging to stderr in the child process to prevent // concurrent writes to the log files. We capture stderr in the parent // process and append the child process' output to a log. LogToStderr(); // Event forwarding to the listeners of event listener API mush be shut // down in death test subprocesses. GetUnitTestImpl()->listeners()->SuppressEventForwarding(); return EXECUTE_TEST; } else { GTEST_DEATH_TEST_CHECK_SYSCALL_(close(pipe_fd[1])); set_read_fd(pipe_fd[0]); set_spawned(true); return OVERSEE_TEST; } } // A concrete death test class that forks and re-executes the main // program from the beginning, with command-line flags set that cause // only this specific death test to be run. class ExecDeathTest : public ForkingDeathTest { public: ExecDeathTest(const char* a_statement, const RE* a_regex, const char* file, int line) : ForkingDeathTest(a_statement, a_regex), file_(file), line_(line) { } virtual TestRole AssumeRole(); private: // The name of the file in which the death test is located. const char* const file_; // The line number on which the death test is located. const int line_; }; // Utility class for accumulating command-line arguments. class Arguments { public: Arguments() { args_.push_back(NULL); } ~Arguments() { for (std::vector::iterator i = args_.begin(); i != args_.end(); ++i) { free(*i); } } void AddArgument(const char* argument) { args_.insert(args_.end() - 1, posix::StrDup(argument)); } template void AddArguments(const ::std::vector& arguments) { for (typename ::std::vector::const_iterator i = arguments.begin(); i != arguments.end(); ++i) { args_.insert(args_.end() - 1, posix::StrDup(i->c_str())); } } char* const* Argv() { return &args_[0]; } private: std::vector args_; }; // A struct that encompasses the arguments to the child process of a // threadsafe-style death test process. struct ExecDeathTestArgs { char* const* argv; // Command-line arguments for the child's call to exec int close_fd; // File descriptor to close; the read end of a pipe }; # if GTEST_OS_MAC inline char** GetEnviron() { // When Google Test is built as a framework on MacOS X, the environ variable // is unavailable. Apple's documentation (man environ) recommends using // _NSGetEnviron() instead. return *_NSGetEnviron(); } # else // Some POSIX platforms expect you to declare environ. extern "C" makes // it reside in the global namespace. extern "C" char** environ; inline char** GetEnviron() { return environ; } # endif // GTEST_OS_MAC // The main function for a threadsafe-style death test child process. // This function is called in a clone()-ed process and thus must avoid // any potentially unsafe operations like malloc or libc functions. static int ExecDeathTestChildMain(void* child_arg) { ExecDeathTestArgs* const args = static_cast(child_arg); GTEST_DEATH_TEST_CHECK_SYSCALL_(close(args->close_fd)); // We need to execute the test program in the same environment where // it was originally invoked. Therefore we change to the original // working directory first. const char* const original_dir = UnitTest::GetInstance()->original_working_dir(); // We can safely call chdir() as it's a direct system call. if (chdir(original_dir) != 0) { DeathTestAbort(String::Format("chdir(\"%s\") failed: %s", original_dir, GetLastErrnoDescription().c_str())); return EXIT_FAILURE; } // We can safely call execve() as it's a direct system call. We // cannot use execvp() as it's a libc function and thus potentially // unsafe. Since execve() doesn't search the PATH, the user must // invoke the test program via a valid path that contains at least // one path separator. execve(args->argv[0], args->argv, GetEnviron()); DeathTestAbort(String::Format("execve(%s, ...) in %s failed: %s", args->argv[0], original_dir, GetLastErrnoDescription().c_str())); return EXIT_FAILURE; } // Two utility routines that together determine the direction the stack // grows. // This could be accomplished more elegantly by a single recursive // function, but we want to guard against the unlikely possibility of // a smart compiler optimizing the recursion away. // // GTEST_NO_INLINE_ is required to prevent GCC 4.6 from inlining // StackLowerThanAddress into StackGrowsDown, which then doesn't give // correct answer. bool StackLowerThanAddress(const void* ptr) GTEST_NO_INLINE_; bool StackLowerThanAddress(const void* ptr) { int dummy; return &dummy < ptr; } bool StackGrowsDown() { int dummy; return StackLowerThanAddress(&dummy); } // A threadsafe implementation of fork(2) for threadsafe-style death tests // that uses clone(2). It dies with an error message if anything goes // wrong. static pid_t ExecDeathTestFork(char* const* argv, int close_fd) { ExecDeathTestArgs args = { argv, close_fd }; pid_t child_pid = -1; # if GTEST_HAS_CLONE const bool use_fork = GTEST_FLAG(death_test_use_fork); if (!use_fork) { static const bool stack_grows_down = StackGrowsDown(); const size_t stack_size = getpagesize(); // MMAP_ANONYMOUS is not defined on Mac, so we use MAP_ANON instead. void* const stack = mmap(NULL, stack_size, PROT_READ | PROT_WRITE, MAP_ANON | MAP_PRIVATE, -1, 0); GTEST_DEATH_TEST_CHECK_(stack != MAP_FAILED); void* const stack_top = static_cast(stack) + (stack_grows_down ? stack_size : 0); child_pid = clone(&ExecDeathTestChildMain, stack_top, SIGCHLD, &args); GTEST_DEATH_TEST_CHECK_(munmap(stack, stack_size) != -1); } # else const bool use_fork = true; # endif // GTEST_HAS_CLONE if (use_fork && (child_pid = fork()) == 0) { ExecDeathTestChildMain(&args); _exit(0); } GTEST_DEATH_TEST_CHECK_(child_pid != -1); return child_pid; } // The AssumeRole process for a fork-and-exec death test. It re-executes the // main program from the beginning, setting the --gtest_filter // and --gtest_internal_run_death_test flags to cause only the current // death test to be re-run. DeathTest::TestRole ExecDeathTest::AssumeRole() { const UnitTestImpl* const impl = GetUnitTestImpl(); const InternalRunDeathTestFlag* const flag = impl->internal_run_death_test_flag(); const TestInfo* const info = impl->current_test_info(); const int death_test_index = info->result()->death_test_count(); if (flag != NULL) { set_write_fd(flag->write_fd()); return EXECUTE_TEST; } int pipe_fd[2]; GTEST_DEATH_TEST_CHECK_(pipe(pipe_fd) != -1); // Clear the close-on-exec flag on the write end of the pipe, lest // it be closed when the child process does an exec: GTEST_DEATH_TEST_CHECK_(fcntl(pipe_fd[1], F_SETFD, 0) != -1); const String filter_flag = String::Format("--%s%s=%s.%s", GTEST_FLAG_PREFIX_, kFilterFlag, info->test_case_name(), info->name()); const String internal_flag = String::Format("--%s%s=%s|%d|%d|%d", GTEST_FLAG_PREFIX_, kInternalRunDeathTestFlag, file_, line_, death_test_index, pipe_fd[1]); Arguments args; args.AddArguments(GetArgvs()); args.AddArgument(filter_flag.c_str()); args.AddArgument(internal_flag.c_str()); DeathTest::set_last_death_test_message(""); CaptureStderr(); // See the comment in NoExecDeathTest::AssumeRole for why the next line // is necessary. FlushInfoLog(); const pid_t child_pid = ExecDeathTestFork(args.Argv(), pipe_fd[0]); GTEST_DEATH_TEST_CHECK_SYSCALL_(close(pipe_fd[1])); set_child_pid(child_pid); set_read_fd(pipe_fd[0]); set_spawned(true); return OVERSEE_TEST; } # endif // !GTEST_OS_WINDOWS // Creates a concrete DeathTest-derived class that depends on the // --gtest_death_test_style flag, and sets the pointer pointed to // by the "test" argument to its address. If the test should be // skipped, sets that pointer to NULL. Returns true, unless the // flag is set to an invalid value. bool DefaultDeathTestFactory::Create(const char* statement, const RE* regex, const char* file, int line, DeathTest** test) { UnitTestImpl* const impl = GetUnitTestImpl(); const InternalRunDeathTestFlag* const flag = impl->internal_run_death_test_flag(); const int death_test_index = impl->current_test_info() ->increment_death_test_count(); if (flag != NULL) { if (death_test_index > flag->index()) { DeathTest::set_last_death_test_message(String::Format( "Death test count (%d) somehow exceeded expected maximum (%d)", death_test_index, flag->index())); return false; } if (!(flag->file() == file && flag->line() == line && flag->index() == death_test_index)) { *test = NULL; return true; } } # if GTEST_OS_WINDOWS if (GTEST_FLAG(death_test_style) == "threadsafe" || GTEST_FLAG(death_test_style) == "fast") { *test = new WindowsDeathTest(statement, regex, file, line); } # else if (GTEST_FLAG(death_test_style) == "threadsafe") { *test = new ExecDeathTest(statement, regex, file, line); } else if (GTEST_FLAG(death_test_style) == "fast") { *test = new NoExecDeathTest(statement, regex); } # endif // GTEST_OS_WINDOWS else { // NOLINT - this is more readable than unbalanced brackets inside #if. DeathTest::set_last_death_test_message(String::Format( "Unknown death test style \"%s\" encountered", GTEST_FLAG(death_test_style).c_str())); return false; } return true; } // Splits a given string on a given delimiter, populating a given // vector with the fields. GTEST_HAS_DEATH_TEST implies that we have // ::std::string, so we can use it here. static void SplitString(const ::std::string& str, char delimiter, ::std::vector< ::std::string>* dest) { ::std::vector< ::std::string> parsed; ::std::string::size_type pos = 0; while (::testing::internal::AlwaysTrue()) { const ::std::string::size_type colon = str.find(delimiter, pos); if (colon == ::std::string::npos) { parsed.push_back(str.substr(pos)); break; } else { parsed.push_back(str.substr(pos, colon - pos)); pos = colon + 1; } } dest->swap(parsed); } # if GTEST_OS_WINDOWS // Recreates the pipe and event handles from the provided parameters, // signals the event, and returns a file descriptor wrapped around the pipe // handle. This function is called in the child process only. int GetStatusFileDescriptor(unsigned int parent_process_id, size_t write_handle_as_size_t, size_t event_handle_as_size_t) { AutoHandle parent_process_handle(::OpenProcess(PROCESS_DUP_HANDLE, FALSE, // Non-inheritable. parent_process_id)); if (parent_process_handle.Get() == INVALID_HANDLE_VALUE) { DeathTestAbort(String::Format("Unable to open parent process %u", parent_process_id)); } // TODO(vladl@google.com): Replace the following check with a // compile-time assertion when available. GTEST_CHECK_(sizeof(HANDLE) <= sizeof(size_t)); const HANDLE write_handle = reinterpret_cast(write_handle_as_size_t); HANDLE dup_write_handle; // The newly initialized handle is accessible only in in the parent // process. To obtain one accessible within the child, we need to use // DuplicateHandle. if (!::DuplicateHandle(parent_process_handle.Get(), write_handle, ::GetCurrentProcess(), &dup_write_handle, 0x0, // Requested privileges ignored since // DUPLICATE_SAME_ACCESS is used. FALSE, // Request non-inheritable handler. DUPLICATE_SAME_ACCESS)) { DeathTestAbort(String::Format( "Unable to duplicate the pipe handle %Iu from the parent process %u", write_handle_as_size_t, parent_process_id)); } const HANDLE event_handle = reinterpret_cast(event_handle_as_size_t); HANDLE dup_event_handle; if (!::DuplicateHandle(parent_process_handle.Get(), event_handle, ::GetCurrentProcess(), &dup_event_handle, 0x0, FALSE, DUPLICATE_SAME_ACCESS)) { DeathTestAbort(String::Format( "Unable to duplicate the event handle %Iu from the parent process %u", event_handle_as_size_t, parent_process_id)); } const int write_fd = ::_open_osfhandle(reinterpret_cast(dup_write_handle), O_APPEND); if (write_fd == -1) { DeathTestAbort(String::Format( "Unable to convert pipe handle %Iu to a file descriptor", write_handle_as_size_t)); } // Signals the parent that the write end of the pipe has been acquired // so the parent can release its own write end. ::SetEvent(dup_event_handle); return write_fd; } # endif // GTEST_OS_WINDOWS // Returns a newly created InternalRunDeathTestFlag object with fields // initialized from the GTEST_FLAG(internal_run_death_test) flag if // the flag is specified; otherwise returns NULL. InternalRunDeathTestFlag* ParseInternalRunDeathTestFlag() { if (GTEST_FLAG(internal_run_death_test) == "") return NULL; // GTEST_HAS_DEATH_TEST implies that we have ::std::string, so we // can use it here. int line = -1; int index = -1; ::std::vector< ::std::string> fields; SplitString(GTEST_FLAG(internal_run_death_test).c_str(), '|', &fields); int write_fd = -1; # if GTEST_OS_WINDOWS unsigned int parent_process_id = 0; size_t write_handle_as_size_t = 0; size_t event_handle_as_size_t = 0; if (fields.size() != 6 || !ParseNaturalNumber(fields[1], &line) || !ParseNaturalNumber(fields[2], &index) || !ParseNaturalNumber(fields[3], &parent_process_id) || !ParseNaturalNumber(fields[4], &write_handle_as_size_t) || !ParseNaturalNumber(fields[5], &event_handle_as_size_t)) { DeathTestAbort(String::Format( "Bad --gtest_internal_run_death_test flag: %s", GTEST_FLAG(internal_run_death_test).c_str())); } write_fd = GetStatusFileDescriptor(parent_process_id, write_handle_as_size_t, event_handle_as_size_t); # else if (fields.size() != 4 || !ParseNaturalNumber(fields[1], &line) || !ParseNaturalNumber(fields[2], &index) || !ParseNaturalNumber(fields[3], &write_fd)) { DeathTestAbort(String::Format( "Bad --gtest_internal_run_death_test flag: %s", GTEST_FLAG(internal_run_death_test).c_str())); } # endif // GTEST_OS_WINDOWS return new InternalRunDeathTestFlag(fields[0], line, index, write_fd); } } // namespace internal #endif // GTEST_HAS_DEATH_TEST } // namespace testing ugene-1.9.8/src/libs_3rdparty/gtest/src/src/gtest-filepath.cc0000644000175000017500000003365711651544307022641 0ustar ilyailya// Copyright 2008, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Authors: keith.ray@gmail.com (Keith Ray) #include "gtest/internal/gtest-filepath.h" #include "gtest/internal/gtest-port.h" #include #if GTEST_OS_WINDOWS_MOBILE # include #elif GTEST_OS_WINDOWS # include # include #elif GTEST_OS_SYMBIAN || GTEST_OS_NACL // Symbian OpenC and NaCl have PATH_MAX in sys/syslimits.h # include #else # include # include // Some Linux distributions define PATH_MAX here. #endif // GTEST_OS_WINDOWS_MOBILE #if GTEST_OS_WINDOWS # define GTEST_PATH_MAX_ _MAX_PATH #elif defined(PATH_MAX) # define GTEST_PATH_MAX_ PATH_MAX #elif defined(_XOPEN_PATH_MAX) # define GTEST_PATH_MAX_ _XOPEN_PATH_MAX #else # define GTEST_PATH_MAX_ _POSIX_PATH_MAX #endif // GTEST_OS_WINDOWS #include "gtest/internal/gtest-string.h" namespace testing { namespace internal { #if GTEST_OS_WINDOWS // On Windows, '\\' is the standard path separator, but many tools and the // Windows API also accept '/' as an alternate path separator. Unless otherwise // noted, a file path can contain either kind of path separators, or a mixture // of them. const char kPathSeparator = '\\'; const char kAlternatePathSeparator = '/'; const char kPathSeparatorString[] = "\\"; const char kAlternatePathSeparatorString[] = "/"; # if GTEST_OS_WINDOWS_MOBILE // Windows CE doesn't have a current directory. You should not use // the current directory in tests on Windows CE, but this at least // provides a reasonable fallback. const char kCurrentDirectoryString[] = "\\"; // Windows CE doesn't define INVALID_FILE_ATTRIBUTES const DWORD kInvalidFileAttributes = 0xffffffff; # else const char kCurrentDirectoryString[] = ".\\"; # endif // GTEST_OS_WINDOWS_MOBILE #else const char kPathSeparator = '/'; const char kPathSeparatorString[] = "/"; const char kCurrentDirectoryString[] = "./"; #endif // GTEST_OS_WINDOWS // Returns whether the given character is a valid path separator. static bool IsPathSeparator(char c) { #if GTEST_HAS_ALT_PATH_SEP_ return (c == kPathSeparator) || (c == kAlternatePathSeparator); #else return c == kPathSeparator; #endif } // Returns the current working directory, or "" if unsuccessful. FilePath FilePath::GetCurrentDir() { #if GTEST_OS_WINDOWS_MOBILE // Windows CE doesn't have a current directory, so we just return // something reasonable. return FilePath(kCurrentDirectoryString); #elif GTEST_OS_WINDOWS char cwd[GTEST_PATH_MAX_ + 1] = { '\0' }; return FilePath(_getcwd(cwd, sizeof(cwd)) == NULL ? "" : cwd); #else char cwd[GTEST_PATH_MAX_ + 1] = { '\0' }; return FilePath(getcwd(cwd, sizeof(cwd)) == NULL ? "" : cwd); #endif // GTEST_OS_WINDOWS_MOBILE } // Returns a copy of the FilePath with the case-insensitive extension removed. // Example: FilePath("dir/file.exe").RemoveExtension("EXE") returns // FilePath("dir/file"). If a case-insensitive extension is not // found, returns a copy of the original FilePath. FilePath FilePath::RemoveExtension(const char* extension) const { String dot_extension(String::Format(".%s", extension)); if (pathname_.EndsWithCaseInsensitive(dot_extension.c_str())) { return FilePath(String(pathname_.c_str(), pathname_.length() - 4)); } return *this; } // Returns a pointer to the last occurence of a valid path separator in // the FilePath. On Windows, for example, both '/' and '\' are valid path // separators. Returns NULL if no path separator was found. const char* FilePath::FindLastPathSeparator() const { const char* const last_sep = strrchr(c_str(), kPathSeparator); #if GTEST_HAS_ALT_PATH_SEP_ const char* const last_alt_sep = strrchr(c_str(), kAlternatePathSeparator); // Comparing two pointers of which only one is NULL is undefined. if (last_alt_sep != NULL && (last_sep == NULL || last_alt_sep > last_sep)) { return last_alt_sep; } #endif return last_sep; } // Returns a copy of the FilePath with the directory part removed. // Example: FilePath("path/to/file").RemoveDirectoryName() returns // FilePath("file"). If there is no directory part ("just_a_file"), it returns // the FilePath unmodified. If there is no file part ("just_a_dir/") it // returns an empty FilePath (""). // On Windows platform, '\' is the path separator, otherwise it is '/'. FilePath FilePath::RemoveDirectoryName() const { const char* const last_sep = FindLastPathSeparator(); return last_sep ? FilePath(String(last_sep + 1)) : *this; } // RemoveFileName returns the directory path with the filename removed. // Example: FilePath("path/to/file").RemoveFileName() returns "path/to/". // If the FilePath is "a_file" or "/a_file", RemoveFileName returns // FilePath("./") or, on Windows, FilePath(".\\"). If the filepath does // not have a file, like "just/a/dir/", it returns the FilePath unmodified. // On Windows platform, '\' is the path separator, otherwise it is '/'. FilePath FilePath::RemoveFileName() const { const char* const last_sep = FindLastPathSeparator(); String dir; if (last_sep) { dir = String(c_str(), last_sep + 1 - c_str()); } else { dir = kCurrentDirectoryString; } return FilePath(dir); } // Helper functions for naming files in a directory for xml output. // Given directory = "dir", base_name = "test", number = 0, // extension = "xml", returns "dir/test.xml". If number is greater // than zero (e.g., 12), returns "dir/test_12.xml". // On Windows platform, uses \ as the separator rather than /. FilePath FilePath::MakeFileName(const FilePath& directory, const FilePath& base_name, int number, const char* extension) { String file; if (number == 0) { file = String::Format("%s.%s", base_name.c_str(), extension); } else { file = String::Format("%s_%d.%s", base_name.c_str(), number, extension); } return ConcatPaths(directory, FilePath(file)); } // Given directory = "dir", relative_path = "test.xml", returns "dir/test.xml". // On Windows, uses \ as the separator rather than /. FilePath FilePath::ConcatPaths(const FilePath& directory, const FilePath& relative_path) { if (directory.IsEmpty()) return relative_path; const FilePath dir(directory.RemoveTrailingPathSeparator()); return FilePath(String::Format("%s%c%s", dir.c_str(), kPathSeparator, relative_path.c_str())); } // Returns true if pathname describes something findable in the file-system, // either a file, directory, or whatever. bool FilePath::FileOrDirectoryExists() const { #if GTEST_OS_WINDOWS_MOBILE LPCWSTR unicode = String::AnsiToUtf16(pathname_.c_str()); const DWORD attributes = GetFileAttributes(unicode); delete [] unicode; return attributes != kInvalidFileAttributes; #else posix::StatStruct file_stat; return posix::Stat(pathname_.c_str(), &file_stat) == 0; #endif // GTEST_OS_WINDOWS_MOBILE } // Returns true if pathname describes a directory in the file-system // that exists. bool FilePath::DirectoryExists() const { bool result = false; #if GTEST_OS_WINDOWS // Don't strip off trailing separator if path is a root directory on // Windows (like "C:\\"). const FilePath& path(IsRootDirectory() ? *this : RemoveTrailingPathSeparator()); #else const FilePath& path(*this); #endif #if GTEST_OS_WINDOWS_MOBILE LPCWSTR unicode = String::AnsiToUtf16(path.c_str()); const DWORD attributes = GetFileAttributes(unicode); delete [] unicode; if ((attributes != kInvalidFileAttributes) && (attributes & FILE_ATTRIBUTE_DIRECTORY)) { result = true; } #else posix::StatStruct file_stat; result = posix::Stat(path.c_str(), &file_stat) == 0 && posix::IsDir(file_stat); #endif // GTEST_OS_WINDOWS_MOBILE return result; } // Returns true if pathname describes a root directory. (Windows has one // root directory per disk drive.) bool FilePath::IsRootDirectory() const { #if GTEST_OS_WINDOWS // TODO(wan@google.com): on Windows a network share like // \\server\share can be a root directory, although it cannot be the // current directory. Handle this properly. return pathname_.length() == 3 && IsAbsolutePath(); #else return pathname_.length() == 1 && IsPathSeparator(pathname_.c_str()[0]); #endif } // Returns true if pathname describes an absolute path. bool FilePath::IsAbsolutePath() const { const char* const name = pathname_.c_str(); #if GTEST_OS_WINDOWS return pathname_.length() >= 3 && ((name[0] >= 'a' && name[0] <= 'z') || (name[0] >= 'A' && name[0] <= 'Z')) && name[1] == ':' && IsPathSeparator(name[2]); #else return IsPathSeparator(name[0]); #endif } // Returns a pathname for a file that does not currently exist. The pathname // will be directory/base_name.extension or // directory/base_name_.extension if directory/base_name.extension // already exists. The number will be incremented until a pathname is found // that does not already exist. // Examples: 'dir/foo_test.xml' or 'dir/foo_test_1.xml'. // There could be a race condition if two or more processes are calling this // function at the same time -- they could both pick the same filename. FilePath FilePath::GenerateUniqueFileName(const FilePath& directory, const FilePath& base_name, const char* extension) { FilePath full_pathname; int number = 0; do { full_pathname.Set(MakeFileName(directory, base_name, number++, extension)); } while (full_pathname.FileOrDirectoryExists()); return full_pathname; } // Returns true if FilePath ends with a path separator, which indicates that // it is intended to represent a directory. Returns false otherwise. // This does NOT check that a directory (or file) actually exists. bool FilePath::IsDirectory() const { return !pathname_.empty() && IsPathSeparator(pathname_.c_str()[pathname_.length() - 1]); } // Create directories so that path exists. Returns true if successful or if // the directories already exist; returns false if unable to create directories // for any reason. bool FilePath::CreateDirectoriesRecursively() const { if (!this->IsDirectory()) { return false; } if (pathname_.length() == 0 || this->DirectoryExists()) { return true; } const FilePath parent(this->RemoveTrailingPathSeparator().RemoveFileName()); return parent.CreateDirectoriesRecursively() && this->CreateFolder(); } // Create the directory so that path exists. Returns true if successful or // if the directory already exists; returns false if unable to create the // directory for any reason, including if the parent directory does not // exist. Not named "CreateDirectory" because that's a macro on Windows. bool FilePath::CreateFolder() const { #if GTEST_OS_WINDOWS_MOBILE FilePath removed_sep(this->RemoveTrailingPathSeparator()); LPCWSTR unicode = String::AnsiToUtf16(removed_sep.c_str()); int result = CreateDirectory(unicode, NULL) ? 0 : -1; delete [] unicode; #elif GTEST_OS_WINDOWS int result = _mkdir(pathname_.c_str()); #else int result = mkdir(pathname_.c_str(), 0777); #endif // GTEST_OS_WINDOWS_MOBILE if (result == -1) { return this->DirectoryExists(); // An error is OK if the directory exists. } return true; // No error. } // If input name has a trailing separator character, remove it and return the // name, otherwise return the name string unmodified. // On Windows platform, uses \ as the separator, other platforms use /. FilePath FilePath::RemoveTrailingPathSeparator() const { return IsDirectory() ? FilePath(String(pathname_.c_str(), pathname_.length() - 1)) : *this; } // Removes any redundant separators that might be in the pathname. // For example, "bar///foo" becomes "bar/foo". Does not eliminate other // redundancies that might be in a pathname involving "." or "..". // TODO(wan@google.com): handle Windows network shares (e.g. \\server\share). void FilePath::Normalize() { if (pathname_.c_str() == NULL) { pathname_ = ""; return; } const char* src = pathname_.c_str(); char* const dest = new char[pathname_.length() + 1]; char* dest_ptr = dest; memset(dest_ptr, 0, pathname_.length() + 1); while (*src != '\0') { *dest_ptr = *src; if (!IsPathSeparator(*src)) { src++; } else { #if GTEST_HAS_ALT_PATH_SEP_ if (*dest_ptr == kAlternatePathSeparator) { *dest_ptr = kPathSeparator; } #endif while (IsPathSeparator(*src)) src++; } dest_ptr++; } *dest_ptr = '\0'; pathname_ = dest; delete[] dest; } } // namespace internal } // namespace testing ugene-1.9.8/src/libs_3rdparty/gtest/src/gtest_unittest.cc0000644000175000017500000070705411651544307022216 0ustar ilyailya// Copyright 2005, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Author: wan@google.com (Zhanyong Wan) // // Tests for Google Test itself. This verifies that the basic constructs of // Google Test work. #include "gtest/gtest.h" #include #include // Verifies that the command line flag variables can be accessed // in code once has been #included. // Do not move it after other #includes. TEST(CommandLineFlagsTest, CanBeAccessedInCodeOnceGTestHIsIncluded) { bool dummy = testing::GTEST_FLAG(also_run_disabled_tests) || testing::GTEST_FLAG(break_on_failure) || testing::GTEST_FLAG(catch_exceptions) || testing::GTEST_FLAG(color) != "unknown" || testing::GTEST_FLAG(filter) != "unknown" || testing::GTEST_FLAG(list_tests) || testing::GTEST_FLAG(output) != "unknown" || testing::GTEST_FLAG(print_time) || testing::GTEST_FLAG(random_seed) || testing::GTEST_FLAG(repeat) > 0 || testing::GTEST_FLAG(show_internal_stack_frames) || testing::GTEST_FLAG(shuffle) || testing::GTEST_FLAG(stack_trace_depth) > 0 || testing::GTEST_FLAG(stream_result_to) != "unknown" || testing::GTEST_FLAG(throw_on_failure); EXPECT_TRUE(dummy || !dummy); // Suppresses warning that dummy is unused. } #include "gtest/gtest-spi.h" // Indicates that this translation unit is part of Google Test's // implementation. It must come before gtest-internal-inl.h is // included, or there will be a compiler error. This trick is to // prevent a user from accidentally including gtest-internal-inl.h in // his code. #define GTEST_IMPLEMENTATION_ 1 #include "src/gtest-internal-inl.h" #undef GTEST_IMPLEMENTATION_ #include // For INT_MAX. #include #include #include namespace testing { namespace internal { // Provides access to otherwise private parts of the TestEventListeners class // that are needed to test it. class TestEventListenersAccessor { public: static TestEventListener* GetRepeater(TestEventListeners* listeners) { return listeners->repeater(); } static void SetDefaultResultPrinter(TestEventListeners* listeners, TestEventListener* listener) { listeners->SetDefaultResultPrinter(listener); } static void SetDefaultXmlGenerator(TestEventListeners* listeners, TestEventListener* listener) { listeners->SetDefaultXmlGenerator(listener); } static bool EventForwardingEnabled(const TestEventListeners& listeners) { return listeners.EventForwardingEnabled(); } static void SuppressEventForwarding(TestEventListeners* listeners) { listeners->SuppressEventForwarding(); } }; } // namespace internal } // namespace testing using testing::AssertionFailure; using testing::AssertionResult; using testing::AssertionSuccess; using testing::DoubleLE; using testing::EmptyTestEventListener; using testing::FloatLE; using testing::GTEST_FLAG(also_run_disabled_tests); using testing::GTEST_FLAG(break_on_failure); using testing::GTEST_FLAG(catch_exceptions); using testing::GTEST_FLAG(color); using testing::GTEST_FLAG(death_test_use_fork); using testing::GTEST_FLAG(filter); using testing::GTEST_FLAG(list_tests); using testing::GTEST_FLAG(output); using testing::GTEST_FLAG(print_time); using testing::GTEST_FLAG(random_seed); using testing::GTEST_FLAG(repeat); using testing::GTEST_FLAG(show_internal_stack_frames); using testing::GTEST_FLAG(shuffle); using testing::GTEST_FLAG(stack_trace_depth); using testing::GTEST_FLAG(stream_result_to); using testing::GTEST_FLAG(throw_on_failure); using testing::IsNotSubstring; using testing::IsSubstring; using testing::Message; using testing::ScopedFakeTestPartResultReporter; using testing::StaticAssertTypeEq; using testing::Test; using testing::TestCase; using testing::TestEventListeners; using testing::TestPartResult; using testing::TestPartResultArray; using testing::TestProperty; using testing::TestResult; using testing::UnitTest; using testing::kMaxStackTraceDepth; using testing::internal::AddReference; using testing::internal::AlwaysFalse; using testing::internal::AlwaysTrue; using testing::internal::AppendUserMessage; using testing::internal::ArrayAwareFind; using testing::internal::ArrayEq; using testing::internal::CodePointToUtf8; using testing::internal::CompileAssertTypesEqual; using testing::internal::CopyArray; using testing::internal::CountIf; using testing::internal::EqFailure; using testing::internal::FloatingPoint; using testing::internal::ForEach; using testing::internal::FormatTimeInMillisAsSeconds; using testing::internal::GTestFlagSaver; using testing::internal::GetCurrentOsStackTraceExceptTop; using testing::internal::GetElementOr; using testing::internal::GetNextRandomSeed; using testing::internal::GetRandomSeedFromFlag; using testing::internal::GetTestTypeId; using testing::internal::GetTypeId; using testing::internal::GetUnitTestImpl; using testing::internal::ImplicitlyConvertible; using testing::internal::Int32; using testing::internal::Int32FromEnvOrDie; using testing::internal::IsAProtocolMessage; using testing::internal::IsContainer; using testing::internal::IsContainerTest; using testing::internal::IsNotContainer; using testing::internal::NativeArray; using testing::internal::ParseInt32Flag; using testing::internal::RemoveConst; using testing::internal::RemoveReference; using testing::internal::ShouldRunTestOnShard; using testing::internal::ShouldShard; using testing::internal::ShouldUseColor; using testing::internal::Shuffle; using testing::internal::ShuffleRange; using testing::internal::SkipPrefix; using testing::internal::StreamableToString; using testing::internal::String; using testing::internal::TestEventListenersAccessor; using testing::internal::TestResultAccessor; using testing::internal::UInt32; using testing::internal::WideStringToUtf8; using testing::internal::kCopy; using testing::internal::kMaxRandomSeed; using testing::internal::kReference; using testing::internal::kTestTypeIdInGoogleTest; using testing::internal::scoped_ptr; #if GTEST_HAS_STREAM_REDIRECTION using testing::internal::CaptureStdout; using testing::internal::GetCapturedStdout; #endif #if GTEST_IS_THREADSAFE using testing::internal::ThreadWithParam; #endif class TestingVector : public std::vector { }; ::std::ostream& operator<<(::std::ostream& os, const TestingVector& vector) { os << "{ "; for (size_t i = 0; i < vector.size(); i++) { os << vector[i] << " "; } os << "}"; return os; } // This line tests that we can define tests in an unnamed namespace. namespace { TEST(GetRandomSeedFromFlagTest, HandlesZero) { const int seed = GetRandomSeedFromFlag(0); EXPECT_LE(1, seed); EXPECT_LE(seed, static_cast(kMaxRandomSeed)); } TEST(GetRandomSeedFromFlagTest, PreservesValidSeed) { EXPECT_EQ(1, GetRandomSeedFromFlag(1)); EXPECT_EQ(2, GetRandomSeedFromFlag(2)); EXPECT_EQ(kMaxRandomSeed - 1, GetRandomSeedFromFlag(kMaxRandomSeed - 1)); EXPECT_EQ(static_cast(kMaxRandomSeed), GetRandomSeedFromFlag(kMaxRandomSeed)); } TEST(GetRandomSeedFromFlagTest, NormalizesInvalidSeed) { const int seed1 = GetRandomSeedFromFlag(-1); EXPECT_LE(1, seed1); EXPECT_LE(seed1, static_cast(kMaxRandomSeed)); const int seed2 = GetRandomSeedFromFlag(kMaxRandomSeed + 1); EXPECT_LE(1, seed2); EXPECT_LE(seed2, static_cast(kMaxRandomSeed)); } TEST(GetNextRandomSeedTest, WorksForValidInput) { EXPECT_EQ(2, GetNextRandomSeed(1)); EXPECT_EQ(3, GetNextRandomSeed(2)); EXPECT_EQ(static_cast(kMaxRandomSeed), GetNextRandomSeed(kMaxRandomSeed - 1)); EXPECT_EQ(1, GetNextRandomSeed(kMaxRandomSeed)); // We deliberately don't test GetNextRandomSeed() with invalid // inputs, as that requires death tests, which are expensive. This // is fine as GetNextRandomSeed() is internal and has a // straightforward definition. } static void ClearCurrentTestPartResults() { TestResultAccessor::ClearTestPartResults( GetUnitTestImpl()->current_test_result()); } // Tests GetTypeId. TEST(GetTypeIdTest, ReturnsSameValueForSameType) { EXPECT_EQ(GetTypeId(), GetTypeId()); EXPECT_EQ(GetTypeId(), GetTypeId()); } class SubClassOfTest : public Test {}; class AnotherSubClassOfTest : public Test {}; TEST(GetTypeIdTest, ReturnsDifferentValuesForDifferentTypes) { EXPECT_NE(GetTypeId(), GetTypeId()); EXPECT_NE(GetTypeId(), GetTypeId()); EXPECT_NE(GetTypeId(), GetTestTypeId()); EXPECT_NE(GetTypeId(), GetTestTypeId()); EXPECT_NE(GetTypeId(), GetTestTypeId()); EXPECT_NE(GetTypeId(), GetTypeId()); } // Verifies that GetTestTypeId() returns the same value, no matter it // is called from inside Google Test or outside of it. TEST(GetTestTypeIdTest, ReturnsTheSameValueInsideOrOutsideOfGoogleTest) { EXPECT_EQ(kTestTypeIdInGoogleTest, GetTestTypeId()); } // Tests FormatTimeInMillisAsSeconds(). TEST(FormatTimeInMillisAsSecondsTest, FormatsZero) { EXPECT_EQ("0", FormatTimeInMillisAsSeconds(0)); } TEST(FormatTimeInMillisAsSecondsTest, FormatsPositiveNumber) { EXPECT_EQ("0.003", FormatTimeInMillisAsSeconds(3)); EXPECT_EQ("0.01", FormatTimeInMillisAsSeconds(10)); EXPECT_EQ("0.2", FormatTimeInMillisAsSeconds(200)); EXPECT_EQ("1.2", FormatTimeInMillisAsSeconds(1200)); EXPECT_EQ("3", FormatTimeInMillisAsSeconds(3000)); } TEST(FormatTimeInMillisAsSecondsTest, FormatsNegativeNumber) { EXPECT_EQ("-0.003", FormatTimeInMillisAsSeconds(-3)); EXPECT_EQ("-0.01", FormatTimeInMillisAsSeconds(-10)); EXPECT_EQ("-0.2", FormatTimeInMillisAsSeconds(-200)); EXPECT_EQ("-1.2", FormatTimeInMillisAsSeconds(-1200)); EXPECT_EQ("-3", FormatTimeInMillisAsSeconds(-3000)); } #if GTEST_CAN_COMPARE_NULL # ifdef __BORLANDC__ // Silences warnings: "Condition is always true", "Unreachable code" # pragma option push -w-ccc -w-rch # endif // Tests that GTEST_IS_NULL_LITERAL_(x) is true when x is a null // pointer literal. TEST(NullLiteralTest, IsTrueForNullLiterals) { EXPECT_TRUE(GTEST_IS_NULL_LITERAL_(NULL)); EXPECT_TRUE(GTEST_IS_NULL_LITERAL_(0)); EXPECT_TRUE(GTEST_IS_NULL_LITERAL_(0U)); EXPECT_TRUE(GTEST_IS_NULL_LITERAL_(0L)); # ifndef __BORLANDC__ // Some compilers may fail to detect some null pointer literals; // as long as users of the framework don't use such literals, this // is harmless. EXPECT_TRUE(GTEST_IS_NULL_LITERAL_(1 - 1)); # endif } // Tests that GTEST_IS_NULL_LITERAL_(x) is false when x is not a null // pointer literal. TEST(NullLiteralTest, IsFalseForNonNullLiterals) { EXPECT_FALSE(GTEST_IS_NULL_LITERAL_(1)); EXPECT_FALSE(GTEST_IS_NULL_LITERAL_(0.0)); EXPECT_FALSE(GTEST_IS_NULL_LITERAL_('a')); EXPECT_FALSE(GTEST_IS_NULL_LITERAL_(static_cast(NULL))); } # ifdef __BORLANDC__ // Restores warnings after previous "#pragma option push" suppressed them. # pragma option pop # endif #endif // GTEST_CAN_COMPARE_NULL // // Tests CodePointToUtf8(). // Tests that the NUL character L'\0' is encoded correctly. TEST(CodePointToUtf8Test, CanEncodeNul) { char buffer[32]; EXPECT_STREQ("", CodePointToUtf8(L'\0', buffer)); } // Tests that ASCII characters are encoded correctly. TEST(CodePointToUtf8Test, CanEncodeAscii) { char buffer[32]; EXPECT_STREQ("a", CodePointToUtf8(L'a', buffer)); EXPECT_STREQ("Z", CodePointToUtf8(L'Z', buffer)); EXPECT_STREQ("&", CodePointToUtf8(L'&', buffer)); EXPECT_STREQ("\x7F", CodePointToUtf8(L'\x7F', buffer)); } // Tests that Unicode code-points that have 8 to 11 bits are encoded // as 110xxxxx 10xxxxxx. TEST(CodePointToUtf8Test, CanEncode8To11Bits) { char buffer[32]; // 000 1101 0011 => 110-00011 10-010011 EXPECT_STREQ("\xC3\x93", CodePointToUtf8(L'\xD3', buffer)); // 101 0111 0110 => 110-10101 10-110110 // Some compilers (e.g., GCC on MinGW) cannot handle non-ASCII codepoints // in wide strings and wide chars. In order to accomodate them, we have to // introduce such character constants as integers. EXPECT_STREQ("\xD5\xB6", CodePointToUtf8(static_cast(0x576), buffer)); } // Tests that Unicode code-points that have 12 to 16 bits are encoded // as 1110xxxx 10xxxxxx 10xxxxxx. TEST(CodePointToUtf8Test, CanEncode12To16Bits) { char buffer[32]; // 0000 1000 1101 0011 => 1110-0000 10-100011 10-010011 EXPECT_STREQ("\xE0\xA3\x93", CodePointToUtf8(static_cast(0x8D3), buffer)); // 1100 0111 0100 1101 => 1110-1100 10-011101 10-001101 EXPECT_STREQ("\xEC\x9D\x8D", CodePointToUtf8(static_cast(0xC74D), buffer)); } #if !GTEST_WIDE_STRING_USES_UTF16_ // Tests in this group require a wchar_t to hold > 16 bits, and thus // are skipped on Windows, Cygwin, and Symbian, where a wchar_t is // 16-bit wide. This code may not compile on those systems. // Tests that Unicode code-points that have 17 to 21 bits are encoded // as 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx. TEST(CodePointToUtf8Test, CanEncode17To21Bits) { char buffer[32]; // 0 0001 0000 1000 1101 0011 => 11110-000 10-010000 10-100011 10-010011 EXPECT_STREQ("\xF0\x90\xA3\x93", CodePointToUtf8(L'\x108D3', buffer)); // 0 0001 0000 0100 0000 0000 => 11110-000 10-010000 10-010000 10-000000 EXPECT_STREQ("\xF0\x90\x90\x80", CodePointToUtf8(L'\x10400', buffer)); // 1 0000 1000 0110 0011 0100 => 11110-100 10-001000 10-011000 10-110100 EXPECT_STREQ("\xF4\x88\x98\xB4", CodePointToUtf8(L'\x108634', buffer)); } // Tests that encoding an invalid code-point generates the expected result. TEST(CodePointToUtf8Test, CanEncodeInvalidCodePoint) { char buffer[32]; EXPECT_STREQ("(Invalid Unicode 0x1234ABCD)", CodePointToUtf8(L'\x1234ABCD', buffer)); } #endif // !GTEST_WIDE_STRING_USES_UTF16_ // Tests WideStringToUtf8(). // Tests that the NUL character L'\0' is encoded correctly. TEST(WideStringToUtf8Test, CanEncodeNul) { EXPECT_STREQ("", WideStringToUtf8(L"", 0).c_str()); EXPECT_STREQ("", WideStringToUtf8(L"", -1).c_str()); } // Tests that ASCII strings are encoded correctly. TEST(WideStringToUtf8Test, CanEncodeAscii) { EXPECT_STREQ("a", WideStringToUtf8(L"a", 1).c_str()); EXPECT_STREQ("ab", WideStringToUtf8(L"ab", 2).c_str()); EXPECT_STREQ("a", WideStringToUtf8(L"a", -1).c_str()); EXPECT_STREQ("ab", WideStringToUtf8(L"ab", -1).c_str()); } // Tests that Unicode code-points that have 8 to 11 bits are encoded // as 110xxxxx 10xxxxxx. TEST(WideStringToUtf8Test, CanEncode8To11Bits) { // 000 1101 0011 => 110-00011 10-010011 EXPECT_STREQ("\xC3\x93", WideStringToUtf8(L"\xD3", 1).c_str()); EXPECT_STREQ("\xC3\x93", WideStringToUtf8(L"\xD3", -1).c_str()); // 101 0111 0110 => 110-10101 10-110110 const wchar_t s[] = { 0x576, '\0' }; EXPECT_STREQ("\xD5\xB6", WideStringToUtf8(s, 1).c_str()); EXPECT_STREQ("\xD5\xB6", WideStringToUtf8(s, -1).c_str()); } // Tests that Unicode code-points that have 12 to 16 bits are encoded // as 1110xxxx 10xxxxxx 10xxxxxx. TEST(WideStringToUtf8Test, CanEncode12To16Bits) { // 0000 1000 1101 0011 => 1110-0000 10-100011 10-010011 const wchar_t s1[] = { 0x8D3, '\0' }; EXPECT_STREQ("\xE0\xA3\x93", WideStringToUtf8(s1, 1).c_str()); EXPECT_STREQ("\xE0\xA3\x93", WideStringToUtf8(s1, -1).c_str()); // 1100 0111 0100 1101 => 1110-1100 10-011101 10-001101 const wchar_t s2[] = { 0xC74D, '\0' }; EXPECT_STREQ("\xEC\x9D\x8D", WideStringToUtf8(s2, 1).c_str()); EXPECT_STREQ("\xEC\x9D\x8D", WideStringToUtf8(s2, -1).c_str()); } // Tests that the conversion stops when the function encounters \0 character. TEST(WideStringToUtf8Test, StopsOnNulCharacter) { EXPECT_STREQ("ABC", WideStringToUtf8(L"ABC\0XYZ", 100).c_str()); } // Tests that the conversion stops when the function reaches the limit // specified by the 'length' parameter. TEST(WideStringToUtf8Test, StopsWhenLengthLimitReached) { EXPECT_STREQ("ABC", WideStringToUtf8(L"ABCDEF", 3).c_str()); } #if !GTEST_WIDE_STRING_USES_UTF16_ // Tests that Unicode code-points that have 17 to 21 bits are encoded // as 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx. This code may not compile // on the systems using UTF-16 encoding. TEST(WideStringToUtf8Test, CanEncode17To21Bits) { // 0 0001 0000 1000 1101 0011 => 11110-000 10-010000 10-100011 10-010011 EXPECT_STREQ("\xF0\x90\xA3\x93", WideStringToUtf8(L"\x108D3", 1).c_str()); EXPECT_STREQ("\xF0\x90\xA3\x93", WideStringToUtf8(L"\x108D3", -1).c_str()); // 1 0000 1000 0110 0011 0100 => 11110-100 10-001000 10-011000 10-110100 EXPECT_STREQ("\xF4\x88\x98\xB4", WideStringToUtf8(L"\x108634", 1).c_str()); EXPECT_STREQ("\xF4\x88\x98\xB4", WideStringToUtf8(L"\x108634", -1).c_str()); } // Tests that encoding an invalid code-point generates the expected result. TEST(WideStringToUtf8Test, CanEncodeInvalidCodePoint) { EXPECT_STREQ("(Invalid Unicode 0xABCDFF)", WideStringToUtf8(L"\xABCDFF", -1).c_str()); } #else // !GTEST_WIDE_STRING_USES_UTF16_ // Tests that surrogate pairs are encoded correctly on the systems using // UTF-16 encoding in the wide strings. TEST(WideStringToUtf8Test, CanEncodeValidUtf16SUrrogatePairs) { const wchar_t s[] = { 0xD801, 0xDC00, '\0' }; EXPECT_STREQ("\xF0\x90\x90\x80", WideStringToUtf8(s, -1).c_str()); } // Tests that encoding an invalid UTF-16 surrogate pair // generates the expected result. TEST(WideStringToUtf8Test, CanEncodeInvalidUtf16SurrogatePair) { // Leading surrogate is at the end of the string. const wchar_t s1[] = { 0xD800, '\0' }; EXPECT_STREQ("\xED\xA0\x80", WideStringToUtf8(s1, -1).c_str()); // Leading surrogate is not followed by the trailing surrogate. const wchar_t s2[] = { 0xD800, 'M', '\0' }; EXPECT_STREQ("\xED\xA0\x80M", WideStringToUtf8(s2, -1).c_str()); // Trailing surrogate appearas without a leading surrogate. const wchar_t s3[] = { 0xDC00, 'P', 'Q', 'R', '\0' }; EXPECT_STREQ("\xED\xB0\x80PQR", WideStringToUtf8(s3, -1).c_str()); } #endif // !GTEST_WIDE_STRING_USES_UTF16_ // Tests that codepoint concatenation works correctly. #if !GTEST_WIDE_STRING_USES_UTF16_ TEST(WideStringToUtf8Test, ConcatenatesCodepointsCorrectly) { const wchar_t s[] = { 0x108634, 0xC74D, '\n', 0x576, 0x8D3, 0x108634, '\0'}; EXPECT_STREQ( "\xF4\x88\x98\xB4" "\xEC\x9D\x8D" "\n" "\xD5\xB6" "\xE0\xA3\x93" "\xF4\x88\x98\xB4", WideStringToUtf8(s, -1).c_str()); } #else TEST(WideStringToUtf8Test, ConcatenatesCodepointsCorrectly) { const wchar_t s[] = { 0xC74D, '\n', 0x576, 0x8D3, '\0'}; EXPECT_STREQ( "\xEC\x9D\x8D" "\n" "\xD5\xB6" "\xE0\xA3\x93", WideStringToUtf8(s, -1).c_str()); } #endif // !GTEST_WIDE_STRING_USES_UTF16_ // Tests the Random class. TEST(RandomDeathTest, GeneratesCrashesOnInvalidRange) { testing::internal::Random random(42); EXPECT_DEATH_IF_SUPPORTED( random.Generate(0), "Cannot generate a number in the range \\[0, 0\\)"); EXPECT_DEATH_IF_SUPPORTED( random.Generate(testing::internal::Random::kMaxRange + 1), "Generation of a number in \\[0, 2147483649\\) was requested, " "but this can only generate numbers in \\[0, 2147483648\\)"); } TEST(RandomTest, GeneratesNumbersWithinRange) { const UInt32 kRange = 10000; testing::internal::Random random(12345); for (int i = 0; i < 10; i++) { EXPECT_LT(random.Generate(kRange), kRange) << " for iteration " << i; } testing::internal::Random random2(testing::internal::Random::kMaxRange); for (int i = 0; i < 10; i++) { EXPECT_LT(random2.Generate(kRange), kRange) << " for iteration " << i; } } TEST(RandomTest, RepeatsWhenReseeded) { const int kSeed = 123; const int kArraySize = 10; const UInt32 kRange = 10000; UInt32 values[kArraySize]; testing::internal::Random random(kSeed); for (int i = 0; i < kArraySize; i++) { values[i] = random.Generate(kRange); } random.Reseed(kSeed); for (int i = 0; i < kArraySize; i++) { EXPECT_EQ(values[i], random.Generate(kRange)) << " for iteration " << i; } } // Tests STL container utilities. // Tests CountIf(). static bool IsPositive(int n) { return n > 0; } TEST(ContainerUtilityTest, CountIf) { std::vector v; EXPECT_EQ(0, CountIf(v, IsPositive)); // Works for an empty container. v.push_back(-1); v.push_back(0); EXPECT_EQ(0, CountIf(v, IsPositive)); // Works when no value satisfies. v.push_back(2); v.push_back(-10); v.push_back(10); EXPECT_EQ(2, CountIf(v, IsPositive)); } // Tests ForEach(). static int g_sum = 0; static void Accumulate(int n) { g_sum += n; } TEST(ContainerUtilityTest, ForEach) { std::vector v; g_sum = 0; ForEach(v, Accumulate); EXPECT_EQ(0, g_sum); // Works for an empty container; g_sum = 0; v.push_back(1); ForEach(v, Accumulate); EXPECT_EQ(1, g_sum); // Works for a container with one element. g_sum = 0; v.push_back(20); v.push_back(300); ForEach(v, Accumulate); EXPECT_EQ(321, g_sum); } // Tests GetElementOr(). TEST(ContainerUtilityTest, GetElementOr) { std::vector a; EXPECT_EQ('x', GetElementOr(a, 0, 'x')); a.push_back('a'); a.push_back('b'); EXPECT_EQ('a', GetElementOr(a, 0, 'x')); EXPECT_EQ('b', GetElementOr(a, 1, 'x')); EXPECT_EQ('x', GetElementOr(a, -2, 'x')); EXPECT_EQ('x', GetElementOr(a, 2, 'x')); } TEST(ContainerUtilityDeathTest, ShuffleRange) { std::vector a; a.push_back(0); a.push_back(1); a.push_back(2); testing::internal::Random random(1); EXPECT_DEATH_IF_SUPPORTED( ShuffleRange(&random, -1, 1, &a), "Invalid shuffle range start -1: must be in range \\[0, 3\\]"); EXPECT_DEATH_IF_SUPPORTED( ShuffleRange(&random, 4, 4, &a), "Invalid shuffle range start 4: must be in range \\[0, 3\\]"); EXPECT_DEATH_IF_SUPPORTED( ShuffleRange(&random, 3, 2, &a), "Invalid shuffle range finish 2: must be in range \\[3, 3\\]"); EXPECT_DEATH_IF_SUPPORTED( ShuffleRange(&random, 3, 4, &a), "Invalid shuffle range finish 4: must be in range \\[3, 3\\]"); } class VectorShuffleTest : public Test { protected: static const int kVectorSize = 20; VectorShuffleTest() : random_(1) { for (int i = 0; i < kVectorSize; i++) { vector_.push_back(i); } } static bool VectorIsCorrupt(const TestingVector& vector) { if (kVectorSize != static_cast(vector.size())) { return true; } bool found_in_vector[kVectorSize] = { false }; for (size_t i = 0; i < vector.size(); i++) { const int e = vector[i]; if (e < 0 || e >= kVectorSize || found_in_vector[e]) { return true; } found_in_vector[e] = true; } // Vector size is correct, elements' range is correct, no // duplicate elements. Therefore no corruption has occurred. return false; } static bool VectorIsNotCorrupt(const TestingVector& vector) { return !VectorIsCorrupt(vector); } static bool RangeIsShuffled(const TestingVector& vector, int begin, int end) { for (int i = begin; i < end; i++) { if (i != vector[i]) { return true; } } return false; } static bool RangeIsUnshuffled( const TestingVector& vector, int begin, int end) { return !RangeIsShuffled(vector, begin, end); } static bool VectorIsShuffled(const TestingVector& vector) { return RangeIsShuffled(vector, 0, static_cast(vector.size())); } static bool VectorIsUnshuffled(const TestingVector& vector) { return !VectorIsShuffled(vector); } testing::internal::Random random_; TestingVector vector_; }; // class VectorShuffleTest const int VectorShuffleTest::kVectorSize; TEST_F(VectorShuffleTest, HandlesEmptyRange) { // Tests an empty range at the beginning... ShuffleRange(&random_, 0, 0, &vector_); ASSERT_PRED1(VectorIsNotCorrupt, vector_); ASSERT_PRED1(VectorIsUnshuffled, vector_); // ...in the middle... ShuffleRange(&random_, kVectorSize/2, kVectorSize/2, &vector_); ASSERT_PRED1(VectorIsNotCorrupt, vector_); ASSERT_PRED1(VectorIsUnshuffled, vector_); // ...at the end... ShuffleRange(&random_, kVectorSize - 1, kVectorSize - 1, &vector_); ASSERT_PRED1(VectorIsNotCorrupt, vector_); ASSERT_PRED1(VectorIsUnshuffled, vector_); // ...and past the end. ShuffleRange(&random_, kVectorSize, kVectorSize, &vector_); ASSERT_PRED1(VectorIsNotCorrupt, vector_); ASSERT_PRED1(VectorIsUnshuffled, vector_); } TEST_F(VectorShuffleTest, HandlesRangeOfSizeOne) { // Tests a size one range at the beginning... ShuffleRange(&random_, 0, 1, &vector_); ASSERT_PRED1(VectorIsNotCorrupt, vector_); ASSERT_PRED1(VectorIsUnshuffled, vector_); // ...in the middle... ShuffleRange(&random_, kVectorSize/2, kVectorSize/2 + 1, &vector_); ASSERT_PRED1(VectorIsNotCorrupt, vector_); ASSERT_PRED1(VectorIsUnshuffled, vector_); // ...and at the end. ShuffleRange(&random_, kVectorSize - 1, kVectorSize, &vector_); ASSERT_PRED1(VectorIsNotCorrupt, vector_); ASSERT_PRED1(VectorIsUnshuffled, vector_); } // Because we use our own random number generator and a fixed seed, // we can guarantee that the following "random" tests will succeed. TEST_F(VectorShuffleTest, ShufflesEntireVector) { Shuffle(&random_, &vector_); ASSERT_PRED1(VectorIsNotCorrupt, vector_); EXPECT_FALSE(VectorIsUnshuffled(vector_)) << vector_; // Tests the first and last elements in particular to ensure that // there are no off-by-one problems in our shuffle algorithm. EXPECT_NE(0, vector_[0]); EXPECT_NE(kVectorSize - 1, vector_[kVectorSize - 1]); } TEST_F(VectorShuffleTest, ShufflesStartOfVector) { const int kRangeSize = kVectorSize/2; ShuffleRange(&random_, 0, kRangeSize, &vector_); ASSERT_PRED1(VectorIsNotCorrupt, vector_); EXPECT_PRED3(RangeIsShuffled, vector_, 0, kRangeSize); EXPECT_PRED3(RangeIsUnshuffled, vector_, kRangeSize, kVectorSize); } TEST_F(VectorShuffleTest, ShufflesEndOfVector) { const int kRangeSize = kVectorSize / 2; ShuffleRange(&random_, kRangeSize, kVectorSize, &vector_); ASSERT_PRED1(VectorIsNotCorrupt, vector_); EXPECT_PRED3(RangeIsUnshuffled, vector_, 0, kRangeSize); EXPECT_PRED3(RangeIsShuffled, vector_, kRangeSize, kVectorSize); } TEST_F(VectorShuffleTest, ShufflesMiddleOfVector) { int kRangeSize = kVectorSize/3; ShuffleRange(&random_, kRangeSize, 2*kRangeSize, &vector_); ASSERT_PRED1(VectorIsNotCorrupt, vector_); EXPECT_PRED3(RangeIsUnshuffled, vector_, 0, kRangeSize); EXPECT_PRED3(RangeIsShuffled, vector_, kRangeSize, 2*kRangeSize); EXPECT_PRED3(RangeIsUnshuffled, vector_, 2*kRangeSize, kVectorSize); } TEST_F(VectorShuffleTest, ShufflesRepeatably) { TestingVector vector2; for (int i = 0; i < kVectorSize; i++) { vector2.push_back(i); } random_.Reseed(1234); Shuffle(&random_, &vector_); random_.Reseed(1234); Shuffle(&random_, &vector2); ASSERT_PRED1(VectorIsNotCorrupt, vector_); ASSERT_PRED1(VectorIsNotCorrupt, vector2); for (int i = 0; i < kVectorSize; i++) { EXPECT_EQ(vector_[i], vector2[i]) << " where i is " << i; } } // Tests the size of the AssertHelper class. TEST(AssertHelperTest, AssertHelperIsSmall) { // To avoid breaking clients that use lots of assertions in one // function, we cannot grow the size of AssertHelper. EXPECT_LE(sizeof(testing::internal::AssertHelper), sizeof(void*)); } // Tests the String class. // Tests String's constructors. TEST(StringTest, Constructors) { // Default ctor. String s1; // We aren't using EXPECT_EQ(NULL, s1.c_str()) because comparing // pointers with NULL isn't supported on all platforms. EXPECT_EQ(0U, s1.length()); EXPECT_TRUE(NULL == s1.c_str()); // Implicitly constructs from a C-string. String s2 = "Hi"; EXPECT_EQ(2U, s2.length()); EXPECT_STREQ("Hi", s2.c_str()); // Constructs from a C-string and a length. String s3("hello", 3); EXPECT_EQ(3U, s3.length()); EXPECT_STREQ("hel", s3.c_str()); // The empty String should be created when String is constructed with // a NULL pointer and length 0. EXPECT_EQ(0U, String(NULL, 0).length()); EXPECT_FALSE(String(NULL, 0).c_str() == NULL); // Constructs a String that contains '\0'. String s4("a\0bcd", 4); EXPECT_EQ(4U, s4.length()); EXPECT_EQ('a', s4.c_str()[0]); EXPECT_EQ('\0', s4.c_str()[1]); EXPECT_EQ('b', s4.c_str()[2]); EXPECT_EQ('c', s4.c_str()[3]); // Copy ctor where the source is NULL. const String null_str; String s5 = null_str; EXPECT_TRUE(s5.c_str() == NULL); // Copy ctor where the source isn't NULL. String s6 = s3; EXPECT_EQ(3U, s6.length()); EXPECT_STREQ("hel", s6.c_str()); // Copy ctor where the source contains '\0'. String s7 = s4; EXPECT_EQ(4U, s7.length()); EXPECT_EQ('a', s7.c_str()[0]); EXPECT_EQ('\0', s7.c_str()[1]); EXPECT_EQ('b', s7.c_str()[2]); EXPECT_EQ('c', s7.c_str()[3]); } TEST(StringTest, ConvertsFromStdString) { // An empty std::string. const std::string src1(""); const String dest1 = src1; EXPECT_EQ(0U, dest1.length()); EXPECT_STREQ("", dest1.c_str()); // A normal std::string. const std::string src2("Hi"); const String dest2 = src2; EXPECT_EQ(2U, dest2.length()); EXPECT_STREQ("Hi", dest2.c_str()); // An std::string with an embedded NUL character. const char src3[] = "a\0b"; const String dest3 = std::string(src3, sizeof(src3)); EXPECT_EQ(sizeof(src3), dest3.length()); EXPECT_EQ('a', dest3.c_str()[0]); EXPECT_EQ('\0', dest3.c_str()[1]); EXPECT_EQ('b', dest3.c_str()[2]); } TEST(StringTest, ConvertsToStdString) { // An empty String. const String src1(""); const std::string dest1 = src1; EXPECT_EQ("", dest1); // A normal String. const String src2("Hi"); const std::string dest2 = src2; EXPECT_EQ("Hi", dest2); // A String containing a '\0'. const String src3("x\0y", 3); const std::string dest3 = src3; EXPECT_EQ(std::string("x\0y", 3), dest3); } #if GTEST_HAS_GLOBAL_STRING TEST(StringTest, ConvertsFromGlobalString) { // An empty ::string. const ::string src1(""); const String dest1 = src1; EXPECT_EQ(0U, dest1.length()); EXPECT_STREQ("", dest1.c_str()); // A normal ::string. const ::string src2("Hi"); const String dest2 = src2; EXPECT_EQ(2U, dest2.length()); EXPECT_STREQ("Hi", dest2.c_str()); // An ::string with an embedded NUL character. const char src3[] = "x\0y"; const String dest3 = ::string(src3, sizeof(src3)); EXPECT_EQ(sizeof(src3), dest3.length()); EXPECT_EQ('x', dest3.c_str()[0]); EXPECT_EQ('\0', dest3.c_str()[1]); EXPECT_EQ('y', dest3.c_str()[2]); } TEST(StringTest, ConvertsToGlobalString) { // An empty String. const String src1(""); const ::string dest1 = src1; EXPECT_EQ("", dest1); // A normal String. const String src2("Hi"); const ::string dest2 = src2; EXPECT_EQ("Hi", dest2); const String src3("x\0y", 3); const ::string dest3 = src3; EXPECT_EQ(::string("x\0y", 3), dest3); } #endif // GTEST_HAS_GLOBAL_STRING // Tests String::ShowCStringQuoted(). TEST(StringTest, ShowCStringQuoted) { EXPECT_STREQ("(null)", String::ShowCStringQuoted(NULL).c_str()); EXPECT_STREQ("\"\"", String::ShowCStringQuoted("").c_str()); EXPECT_STREQ("\"foo\"", String::ShowCStringQuoted("foo").c_str()); } // Tests String::empty(). TEST(StringTest, Empty) { EXPECT_TRUE(String("").empty()); EXPECT_FALSE(String().empty()); EXPECT_FALSE(String(NULL).empty()); EXPECT_FALSE(String("a").empty()); EXPECT_FALSE(String("\0", 1).empty()); } // Tests String::Compare(). TEST(StringTest, Compare) { // NULL vs NULL. EXPECT_EQ(0, String().Compare(String())); // NULL vs non-NULL. EXPECT_EQ(-1, String().Compare(String(""))); // Non-NULL vs NULL. EXPECT_EQ(1, String("").Compare(String())); // The following covers non-NULL vs non-NULL. // "" vs "". EXPECT_EQ(0, String("").Compare(String(""))); // "" vs non-"". EXPECT_EQ(-1, String("").Compare(String("\0", 1))); EXPECT_EQ(-1, String("").Compare(" ")); // Non-"" vs "". EXPECT_EQ(1, String("a").Compare(String(""))); // The following covers non-"" vs non-"". // Same length and equal. EXPECT_EQ(0, String("a").Compare(String("a"))); // Same length and different. EXPECT_EQ(-1, String("a\0b", 3).Compare(String("a\0c", 3))); EXPECT_EQ(1, String("b").Compare(String("a"))); // Different lengths. EXPECT_EQ(-1, String("a").Compare(String("ab"))); EXPECT_EQ(-1, String("a").Compare(String("a\0", 2))); EXPECT_EQ(1, String("abc").Compare(String("aacd"))); } // Tests String::operator==(). TEST(StringTest, Equals) { const String null(NULL); EXPECT_TRUE(null == NULL); // NOLINT EXPECT_FALSE(null == ""); // NOLINT EXPECT_FALSE(null == "bar"); // NOLINT const String empty(""); EXPECT_FALSE(empty == NULL); // NOLINT EXPECT_TRUE(empty == ""); // NOLINT EXPECT_FALSE(empty == "bar"); // NOLINT const String foo("foo"); EXPECT_FALSE(foo == NULL); // NOLINT EXPECT_FALSE(foo == ""); // NOLINT EXPECT_FALSE(foo == "bar"); // NOLINT EXPECT_TRUE(foo == "foo"); // NOLINT const String bar("x\0y", 3); EXPECT_FALSE(bar == "x"); } // Tests String::operator!=(). TEST(StringTest, NotEquals) { const String null(NULL); EXPECT_FALSE(null != NULL); // NOLINT EXPECT_TRUE(null != ""); // NOLINT EXPECT_TRUE(null != "bar"); // NOLINT const String empty(""); EXPECT_TRUE(empty != NULL); // NOLINT EXPECT_FALSE(empty != ""); // NOLINT EXPECT_TRUE(empty != "bar"); // NOLINT const String foo("foo"); EXPECT_TRUE(foo != NULL); // NOLINT EXPECT_TRUE(foo != ""); // NOLINT EXPECT_TRUE(foo != "bar"); // NOLINT EXPECT_FALSE(foo != "foo"); // NOLINT const String bar("x\0y", 3); EXPECT_TRUE(bar != "x"); } // Tests String::length(). TEST(StringTest, Length) { EXPECT_EQ(0U, String().length()); EXPECT_EQ(0U, String("").length()); EXPECT_EQ(2U, String("ab").length()); EXPECT_EQ(3U, String("a\0b", 3).length()); } // Tests String::EndsWith(). TEST(StringTest, EndsWith) { EXPECT_TRUE(String("foobar").EndsWith("bar")); EXPECT_TRUE(String("foobar").EndsWith("")); EXPECT_TRUE(String("").EndsWith("")); EXPECT_FALSE(String("foobar").EndsWith("foo")); EXPECT_FALSE(String("").EndsWith("foo")); } // Tests String::EndsWithCaseInsensitive(). TEST(StringTest, EndsWithCaseInsensitive) { EXPECT_TRUE(String("foobar").EndsWithCaseInsensitive("BAR")); EXPECT_TRUE(String("foobaR").EndsWithCaseInsensitive("bar")); EXPECT_TRUE(String("foobar").EndsWithCaseInsensitive("")); EXPECT_TRUE(String("").EndsWithCaseInsensitive("")); EXPECT_FALSE(String("Foobar").EndsWithCaseInsensitive("foo")); EXPECT_FALSE(String("foobar").EndsWithCaseInsensitive("Foo")); EXPECT_FALSE(String("").EndsWithCaseInsensitive("foo")); } // C++Builder's preprocessor is buggy; it fails to expand macros that // appear in macro parameters after wide char literals. Provide an alias // for NULL as a workaround. static const wchar_t* const kNull = NULL; // Tests String::CaseInsensitiveWideCStringEquals TEST(StringTest, CaseInsensitiveWideCStringEquals) { EXPECT_TRUE(String::CaseInsensitiveWideCStringEquals(NULL, NULL)); EXPECT_FALSE(String::CaseInsensitiveWideCStringEquals(kNull, L"")); EXPECT_FALSE(String::CaseInsensitiveWideCStringEquals(L"", kNull)); EXPECT_FALSE(String::CaseInsensitiveWideCStringEquals(kNull, L"foobar")); EXPECT_FALSE(String::CaseInsensitiveWideCStringEquals(L"foobar", kNull)); EXPECT_TRUE(String::CaseInsensitiveWideCStringEquals(L"foobar", L"foobar")); EXPECT_TRUE(String::CaseInsensitiveWideCStringEquals(L"foobar", L"FOOBAR")); EXPECT_TRUE(String::CaseInsensitiveWideCStringEquals(L"FOOBAR", L"foobar")); } // Tests that NULL can be assigned to a String. TEST(StringTest, CanBeAssignedNULL) { const String src(NULL); String dest; dest = src; EXPECT_STREQ(NULL, dest.c_str()); } // Tests that the empty string "" can be assigned to a String. TEST(StringTest, CanBeAssignedEmpty) { const String src(""); String dest; dest = src; EXPECT_STREQ("", dest.c_str()); } // Tests that a non-empty string can be assigned to a String. TEST(StringTest, CanBeAssignedNonEmpty) { const String src("hello"); String dest; dest = src; EXPECT_EQ(5U, dest.length()); EXPECT_STREQ("hello", dest.c_str()); const String src2("x\0y", 3); String dest2; dest2 = src2; EXPECT_EQ(3U, dest2.length()); EXPECT_EQ('x', dest2.c_str()[0]); EXPECT_EQ('\0', dest2.c_str()[1]); EXPECT_EQ('y', dest2.c_str()[2]); } // Tests that a String can be assigned to itself. TEST(StringTest, CanBeAssignedSelf) { String dest("hello"); // Use explicit function call notation here to suppress self-assign warning. dest.operator=(dest); EXPECT_STREQ("hello", dest.c_str()); } // Sun Studio < 12 incorrectly rejects this code due to an overloading // ambiguity. #if !(defined(__SUNPRO_CC) && __SUNPRO_CC < 0x590) // Tests streaming a String. TEST(StringTest, Streams) { EXPECT_EQ(StreamableToString(String()), "(null)"); EXPECT_EQ(StreamableToString(String("")), ""); EXPECT_EQ(StreamableToString(String("a\0b", 3)), "a\\0b"); } #endif // Tests that String::Format() works. TEST(StringTest, FormatWorks) { // Normal case: the format spec is valid, the arguments match the // spec, and the result is < 4095 characters. EXPECT_STREQ("Hello, 42", String::Format("%s, %d", "Hello", 42).c_str()); // Edge case: the result is 4095 characters. char buffer[4096]; const size_t kSize = sizeof(buffer); memset(buffer, 'a', kSize - 1); buffer[kSize - 1] = '\0'; EXPECT_STREQ(buffer, String::Format("%s", buffer).c_str()); // The result needs to be 4096 characters, exceeding Format()'s limit. EXPECT_STREQ("", String::Format("x%s", buffer).c_str()); #if GTEST_OS_LINUX // On Linux, invalid format spec should lead to an error message. // In other environment (e.g. MSVC on Windows), String::Format() may // simply ignore a bad format spec, so this assertion is run on // Linux only. EXPECT_STREQ("", String::Format("%").c_str()); #endif } #if GTEST_OS_WINDOWS // Tests String::ShowWideCString(). TEST(StringTest, ShowWideCString) { EXPECT_STREQ("(null)", String::ShowWideCString(NULL).c_str()); EXPECT_STREQ("", String::ShowWideCString(L"").c_str()); EXPECT_STREQ("foo", String::ShowWideCString(L"foo").c_str()); } // Tests String::ShowWideCStringQuoted(). TEST(StringTest, ShowWideCStringQuoted) { EXPECT_STREQ("(null)", String::ShowWideCStringQuoted(NULL).c_str()); EXPECT_STREQ("L\"\"", String::ShowWideCStringQuoted(L"").c_str()); EXPECT_STREQ("L\"foo\"", String::ShowWideCStringQuoted(L"foo").c_str()); } # if GTEST_OS_WINDOWS_MOBILE TEST(StringTest, AnsiAndUtf16Null) { EXPECT_EQ(NULL, String::AnsiToUtf16(NULL)); EXPECT_EQ(NULL, String::Utf16ToAnsi(NULL)); } TEST(StringTest, AnsiAndUtf16ConvertBasic) { const char* ansi = String::Utf16ToAnsi(L"str"); EXPECT_STREQ("str", ansi); delete [] ansi; const WCHAR* utf16 = String::AnsiToUtf16("str"); EXPECT_EQ(0, wcsncmp(L"str", utf16, 3)); delete [] utf16; } TEST(StringTest, AnsiAndUtf16ConvertPathChars) { const char* ansi = String::Utf16ToAnsi(L".:\\ \"*?"); EXPECT_STREQ(".:\\ \"*?", ansi); delete [] ansi; const WCHAR* utf16 = String::AnsiToUtf16(".:\\ \"*?"); EXPECT_EQ(0, wcsncmp(L".:\\ \"*?", utf16, 3)); delete [] utf16; } # endif // GTEST_OS_WINDOWS_MOBILE #endif // GTEST_OS_WINDOWS // Tests TestProperty construction. TEST(TestPropertyTest, StringValue) { TestProperty property("key", "1"); EXPECT_STREQ("key", property.key()); EXPECT_STREQ("1", property.value()); } // Tests TestProperty replacing a value. TEST(TestPropertyTest, ReplaceStringValue) { TestProperty property("key", "1"); EXPECT_STREQ("1", property.value()); property.SetValue("2"); EXPECT_STREQ("2", property.value()); } // AddFatalFailure() and AddNonfatalFailure() must be stand-alone // functions (i.e. their definitions cannot be inlined at the call // sites), or C++Builder won't compile the code. static void AddFatalFailure() { FAIL() << "Expected fatal failure."; } static void AddNonfatalFailure() { ADD_FAILURE() << "Expected non-fatal failure."; } class ScopedFakeTestPartResultReporterTest : public Test { public: // Must be public and not protected due to a bug in g++ 3.4.2. enum FailureMode { FATAL_FAILURE, NONFATAL_FAILURE }; static void AddFailure(FailureMode failure) { if (failure == FATAL_FAILURE) { AddFatalFailure(); } else { AddNonfatalFailure(); } } }; // Tests that ScopedFakeTestPartResultReporter intercepts test // failures. TEST_F(ScopedFakeTestPartResultReporterTest, InterceptsTestFailures) { TestPartResultArray results; { ScopedFakeTestPartResultReporter reporter( ScopedFakeTestPartResultReporter::INTERCEPT_ONLY_CURRENT_THREAD, &results); AddFailure(NONFATAL_FAILURE); AddFailure(FATAL_FAILURE); } EXPECT_EQ(2, results.size()); EXPECT_TRUE(results.GetTestPartResult(0).nonfatally_failed()); EXPECT_TRUE(results.GetTestPartResult(1).fatally_failed()); } TEST_F(ScopedFakeTestPartResultReporterTest, DeprecatedConstructor) { TestPartResultArray results; { // Tests, that the deprecated constructor still works. ScopedFakeTestPartResultReporter reporter(&results); AddFailure(NONFATAL_FAILURE); } EXPECT_EQ(1, results.size()); } #if GTEST_IS_THREADSAFE class ScopedFakeTestPartResultReporterWithThreadsTest : public ScopedFakeTestPartResultReporterTest { protected: static void AddFailureInOtherThread(FailureMode failure) { ThreadWithParam thread(&AddFailure, failure, NULL); thread.Join(); } }; TEST_F(ScopedFakeTestPartResultReporterWithThreadsTest, InterceptsTestFailuresInAllThreads) { TestPartResultArray results; { ScopedFakeTestPartResultReporter reporter( ScopedFakeTestPartResultReporter::INTERCEPT_ALL_THREADS, &results); AddFailure(NONFATAL_FAILURE); AddFailure(FATAL_FAILURE); AddFailureInOtherThread(NONFATAL_FAILURE); AddFailureInOtherThread(FATAL_FAILURE); } EXPECT_EQ(4, results.size()); EXPECT_TRUE(results.GetTestPartResult(0).nonfatally_failed()); EXPECT_TRUE(results.GetTestPartResult(1).fatally_failed()); EXPECT_TRUE(results.GetTestPartResult(2).nonfatally_failed()); EXPECT_TRUE(results.GetTestPartResult(3).fatally_failed()); } #endif // GTEST_IS_THREADSAFE // Tests EXPECT_FATAL_FAILURE{,ON_ALL_THREADS}. Makes sure that they // work even if the failure is generated in a called function rather than // the current context. typedef ScopedFakeTestPartResultReporterTest ExpectFatalFailureTest; TEST_F(ExpectFatalFailureTest, CatchesFatalFaliure) { EXPECT_FATAL_FAILURE(AddFatalFailure(), "Expected fatal failure."); } #if GTEST_HAS_GLOBAL_STRING TEST_F(ExpectFatalFailureTest, AcceptsStringObject) { EXPECT_FATAL_FAILURE(AddFatalFailure(), ::string("Expected fatal failure.")); } #endif TEST_F(ExpectFatalFailureTest, AcceptsStdStringObject) { EXPECT_FATAL_FAILURE(AddFatalFailure(), ::std::string("Expected fatal failure.")); } TEST_F(ExpectFatalFailureTest, CatchesFatalFailureOnAllThreads) { // We have another test below to verify that the macro catches fatal // failures generated on another thread. EXPECT_FATAL_FAILURE_ON_ALL_THREADS(AddFatalFailure(), "Expected fatal failure."); } #ifdef __BORLANDC__ // Silences warnings: "Condition is always true" # pragma option push -w-ccc #endif // Tests that EXPECT_FATAL_FAILURE() can be used in a non-void // function even when the statement in it contains ASSERT_*. int NonVoidFunction() { EXPECT_FATAL_FAILURE(ASSERT_TRUE(false), ""); EXPECT_FATAL_FAILURE_ON_ALL_THREADS(FAIL(), ""); return 0; } TEST_F(ExpectFatalFailureTest, CanBeUsedInNonVoidFunction) { NonVoidFunction(); } // Tests that EXPECT_FATAL_FAILURE(statement, ...) doesn't abort the // current function even though 'statement' generates a fatal failure. void DoesNotAbortHelper(bool* aborted) { EXPECT_FATAL_FAILURE(ASSERT_TRUE(false), ""); EXPECT_FATAL_FAILURE_ON_ALL_THREADS(FAIL(), ""); *aborted = false; } #ifdef __BORLANDC__ // Restores warnings after previous "#pragma option push" suppressed them. # pragma option pop #endif TEST_F(ExpectFatalFailureTest, DoesNotAbort) { bool aborted = true; DoesNotAbortHelper(&aborted); EXPECT_FALSE(aborted); } // Tests that the EXPECT_FATAL_FAILURE{,_ON_ALL_THREADS} accepts a // statement that contains a macro which expands to code containing an // unprotected comma. static int global_var = 0; #define GTEST_USE_UNPROTECTED_COMMA_ global_var++, global_var++ TEST_F(ExpectFatalFailureTest, AcceptsMacroThatExpandsToUnprotectedComma) { #ifndef __BORLANDC__ // ICE's in C++Builder. EXPECT_FATAL_FAILURE({ GTEST_USE_UNPROTECTED_COMMA_; AddFatalFailure(); }, ""); #endif EXPECT_FATAL_FAILURE_ON_ALL_THREADS({ GTEST_USE_UNPROTECTED_COMMA_; AddFatalFailure(); }, ""); } // Tests EXPECT_NONFATAL_FAILURE{,ON_ALL_THREADS}. typedef ScopedFakeTestPartResultReporterTest ExpectNonfatalFailureTest; TEST_F(ExpectNonfatalFailureTest, CatchesNonfatalFailure) { EXPECT_NONFATAL_FAILURE(AddNonfatalFailure(), "Expected non-fatal failure."); } #if GTEST_HAS_GLOBAL_STRING TEST_F(ExpectNonfatalFailureTest, AcceptsStringObject) { EXPECT_NONFATAL_FAILURE(AddNonfatalFailure(), ::string("Expected non-fatal failure.")); } #endif TEST_F(ExpectNonfatalFailureTest, AcceptsStdStringObject) { EXPECT_NONFATAL_FAILURE(AddNonfatalFailure(), ::std::string("Expected non-fatal failure.")); } TEST_F(ExpectNonfatalFailureTest, CatchesNonfatalFailureOnAllThreads) { // We have another test below to verify that the macro catches // non-fatal failures generated on another thread. EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS(AddNonfatalFailure(), "Expected non-fatal failure."); } // Tests that the EXPECT_NONFATAL_FAILURE{,_ON_ALL_THREADS} accepts a // statement that contains a macro which expands to code containing an // unprotected comma. TEST_F(ExpectNonfatalFailureTest, AcceptsMacroThatExpandsToUnprotectedComma) { EXPECT_NONFATAL_FAILURE({ GTEST_USE_UNPROTECTED_COMMA_; AddNonfatalFailure(); }, ""); EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS({ GTEST_USE_UNPROTECTED_COMMA_; AddNonfatalFailure(); }, ""); } #if GTEST_IS_THREADSAFE typedef ScopedFakeTestPartResultReporterWithThreadsTest ExpectFailureWithThreadsTest; TEST_F(ExpectFailureWithThreadsTest, ExpectFatalFailureOnAllThreads) { EXPECT_FATAL_FAILURE_ON_ALL_THREADS(AddFailureInOtherThread(FATAL_FAILURE), "Expected fatal failure."); } TEST_F(ExpectFailureWithThreadsTest, ExpectNonFatalFailureOnAllThreads) { EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS( AddFailureInOtherThread(NONFATAL_FAILURE), "Expected non-fatal failure."); } #endif // GTEST_IS_THREADSAFE // Tests the TestProperty class. TEST(TestPropertyTest, ConstructorWorks) { const TestProperty property("key", "value"); EXPECT_STREQ("key", property.key()); EXPECT_STREQ("value", property.value()); } TEST(TestPropertyTest, SetValue) { TestProperty property("key", "value_1"); EXPECT_STREQ("key", property.key()); property.SetValue("value_2"); EXPECT_STREQ("key", property.key()); EXPECT_STREQ("value_2", property.value()); } // Tests the TestResult class // The test fixture for testing TestResult. class TestResultTest : public Test { protected: typedef std::vector TPRVector; // We make use of 2 TestPartResult objects, TestPartResult * pr1, * pr2; // ... and 3 TestResult objects. TestResult * r0, * r1, * r2; virtual void SetUp() { // pr1 is for success. pr1 = new TestPartResult(TestPartResult::kSuccess, "foo/bar.cc", 10, "Success!"); // pr2 is for fatal failure. pr2 = new TestPartResult(TestPartResult::kFatalFailure, "foo/bar.cc", -1, // This line number means "unknown" "Failure!"); // Creates the TestResult objects. r0 = new TestResult(); r1 = new TestResult(); r2 = new TestResult(); // In order to test TestResult, we need to modify its internal // state, in particular the TestPartResult vector it holds. // test_part_results() returns a const reference to this vector. // We cast it to a non-const object s.t. it can be modified (yes, // this is a hack). TPRVector* results1 = const_cast( &TestResultAccessor::test_part_results(*r1)); TPRVector* results2 = const_cast( &TestResultAccessor::test_part_results(*r2)); // r0 is an empty TestResult. // r1 contains a single SUCCESS TestPartResult. results1->push_back(*pr1); // r2 contains a SUCCESS, and a FAILURE. results2->push_back(*pr1); results2->push_back(*pr2); } virtual void TearDown() { delete pr1; delete pr2; delete r0; delete r1; delete r2; } // Helper that compares two two TestPartResults. static void CompareTestPartResult(const TestPartResult& expected, const TestPartResult& actual) { EXPECT_EQ(expected.type(), actual.type()); EXPECT_STREQ(expected.file_name(), actual.file_name()); EXPECT_EQ(expected.line_number(), actual.line_number()); EXPECT_STREQ(expected.summary(), actual.summary()); EXPECT_STREQ(expected.message(), actual.message()); EXPECT_EQ(expected.passed(), actual.passed()); EXPECT_EQ(expected.failed(), actual.failed()); EXPECT_EQ(expected.nonfatally_failed(), actual.nonfatally_failed()); EXPECT_EQ(expected.fatally_failed(), actual.fatally_failed()); } }; // Tests TestResult::total_part_count(). TEST_F(TestResultTest, total_part_count) { ASSERT_EQ(0, r0->total_part_count()); ASSERT_EQ(1, r1->total_part_count()); ASSERT_EQ(2, r2->total_part_count()); } // Tests TestResult::Passed(). TEST_F(TestResultTest, Passed) { ASSERT_TRUE(r0->Passed()); ASSERT_TRUE(r1->Passed()); ASSERT_FALSE(r2->Passed()); } // Tests TestResult::Failed(). TEST_F(TestResultTest, Failed) { ASSERT_FALSE(r0->Failed()); ASSERT_FALSE(r1->Failed()); ASSERT_TRUE(r2->Failed()); } // Tests TestResult::GetTestPartResult(). typedef TestResultTest TestResultDeathTest; TEST_F(TestResultDeathTest, GetTestPartResult) { CompareTestPartResult(*pr1, r2->GetTestPartResult(0)); CompareTestPartResult(*pr2, r2->GetTestPartResult(1)); EXPECT_DEATH_IF_SUPPORTED(r2->GetTestPartResult(2), ""); EXPECT_DEATH_IF_SUPPORTED(r2->GetTestPartResult(-1), ""); } // Tests TestResult has no properties when none are added. TEST(TestResultPropertyTest, NoPropertiesFoundWhenNoneAreAdded) { TestResult test_result; ASSERT_EQ(0, test_result.test_property_count()); } // Tests TestResult has the expected property when added. TEST(TestResultPropertyTest, OnePropertyFoundWhenAdded) { TestResult test_result; TestProperty property("key_1", "1"); TestResultAccessor::RecordProperty(&test_result, property); ASSERT_EQ(1, test_result.test_property_count()); const TestProperty& actual_property = test_result.GetTestProperty(0); EXPECT_STREQ("key_1", actual_property.key()); EXPECT_STREQ("1", actual_property.value()); } // Tests TestResult has multiple properties when added. TEST(TestResultPropertyTest, MultiplePropertiesFoundWhenAdded) { TestResult test_result; TestProperty property_1("key_1", "1"); TestProperty property_2("key_2", "2"); TestResultAccessor::RecordProperty(&test_result, property_1); TestResultAccessor::RecordProperty(&test_result, property_2); ASSERT_EQ(2, test_result.test_property_count()); const TestProperty& actual_property_1 = test_result.GetTestProperty(0); EXPECT_STREQ("key_1", actual_property_1.key()); EXPECT_STREQ("1", actual_property_1.value()); const TestProperty& actual_property_2 = test_result.GetTestProperty(1); EXPECT_STREQ("key_2", actual_property_2.key()); EXPECT_STREQ("2", actual_property_2.value()); } // Tests TestResult::RecordProperty() overrides values for duplicate keys. TEST(TestResultPropertyTest, OverridesValuesForDuplicateKeys) { TestResult test_result; TestProperty property_1_1("key_1", "1"); TestProperty property_2_1("key_2", "2"); TestProperty property_1_2("key_1", "12"); TestProperty property_2_2("key_2", "22"); TestResultAccessor::RecordProperty(&test_result, property_1_1); TestResultAccessor::RecordProperty(&test_result, property_2_1); TestResultAccessor::RecordProperty(&test_result, property_1_2); TestResultAccessor::RecordProperty(&test_result, property_2_2); ASSERT_EQ(2, test_result.test_property_count()); const TestProperty& actual_property_1 = test_result.GetTestProperty(0); EXPECT_STREQ("key_1", actual_property_1.key()); EXPECT_STREQ("12", actual_property_1.value()); const TestProperty& actual_property_2 = test_result.GetTestProperty(1); EXPECT_STREQ("key_2", actual_property_2.key()); EXPECT_STREQ("22", actual_property_2.value()); } // Tests TestResult::GetTestProperty(). TEST(TestResultPropertyDeathTest, GetTestProperty) { TestResult test_result; TestProperty property_1("key_1", "1"); TestProperty property_2("key_2", "2"); TestProperty property_3("key_3", "3"); TestResultAccessor::RecordProperty(&test_result, property_1); TestResultAccessor::RecordProperty(&test_result, property_2); TestResultAccessor::RecordProperty(&test_result, property_3); const TestProperty& fetched_property_1 = test_result.GetTestProperty(0); const TestProperty& fetched_property_2 = test_result.GetTestProperty(1); const TestProperty& fetched_property_3 = test_result.GetTestProperty(2); EXPECT_STREQ("key_1", fetched_property_1.key()); EXPECT_STREQ("1", fetched_property_1.value()); EXPECT_STREQ("key_2", fetched_property_2.key()); EXPECT_STREQ("2", fetched_property_2.value()); EXPECT_STREQ("key_3", fetched_property_3.key()); EXPECT_STREQ("3", fetched_property_3.value()); EXPECT_DEATH_IF_SUPPORTED(test_result.GetTestProperty(3), ""); EXPECT_DEATH_IF_SUPPORTED(test_result.GetTestProperty(-1), ""); } // When a property using a reserved key is supplied to this function, it tests // that a non-fatal failure is added, a fatal failure is not added, and that the // property is not recorded. void ExpectNonFatalFailureRecordingPropertyWithReservedKey(const char* key) { TestResult test_result; TestProperty property(key, "1"); EXPECT_NONFATAL_FAILURE( TestResultAccessor::RecordProperty(&test_result, property), "Reserved key"); ASSERT_EQ(0, test_result.test_property_count()) << "Not recorded"; } // Attempting to recording a property with the Reserved literal "name" // should add a non-fatal failure and the property should not be recorded. TEST(TestResultPropertyTest, AddFailureWhenUsingReservedKeyCalledName) { ExpectNonFatalFailureRecordingPropertyWithReservedKey("name"); } // Attempting to recording a property with the Reserved literal "status" // should add a non-fatal failure and the property should not be recorded. TEST(TestResultPropertyTest, AddFailureWhenUsingReservedKeyCalledStatus) { ExpectNonFatalFailureRecordingPropertyWithReservedKey("status"); } // Attempting to recording a property with the Reserved literal "time" // should add a non-fatal failure and the property should not be recorded. TEST(TestResultPropertyTest, AddFailureWhenUsingReservedKeyCalledTime) { ExpectNonFatalFailureRecordingPropertyWithReservedKey("time"); } // Attempting to recording a property with the Reserved literal "classname" // should add a non-fatal failure and the property should not be recorded. TEST(TestResultPropertyTest, AddFailureWhenUsingReservedKeyCalledClassname) { ExpectNonFatalFailureRecordingPropertyWithReservedKey("classname"); } // Tests that GTestFlagSaver works on Windows and Mac. class GTestFlagSaverTest : public Test { protected: // Saves the Google Test flags such that we can restore them later, and // then sets them to their default values. This will be called // before the first test in this test case is run. static void SetUpTestCase() { saver_ = new GTestFlagSaver; GTEST_FLAG(also_run_disabled_tests) = false; GTEST_FLAG(break_on_failure) = false; GTEST_FLAG(catch_exceptions) = false; GTEST_FLAG(death_test_use_fork) = false; GTEST_FLAG(color) = "auto"; GTEST_FLAG(filter) = ""; GTEST_FLAG(list_tests) = false; GTEST_FLAG(output) = ""; GTEST_FLAG(print_time) = true; GTEST_FLAG(random_seed) = 0; GTEST_FLAG(repeat) = 1; GTEST_FLAG(shuffle) = false; GTEST_FLAG(stack_trace_depth) = kMaxStackTraceDepth; GTEST_FLAG(stream_result_to) = ""; GTEST_FLAG(throw_on_failure) = false; } // Restores the Google Test flags that the tests have modified. This will // be called after the last test in this test case is run. static void TearDownTestCase() { delete saver_; saver_ = NULL; } // Verifies that the Google Test flags have their default values, and then // modifies each of them. void VerifyAndModifyFlags() { EXPECT_FALSE(GTEST_FLAG(also_run_disabled_tests)); EXPECT_FALSE(GTEST_FLAG(break_on_failure)); EXPECT_FALSE(GTEST_FLAG(catch_exceptions)); EXPECT_STREQ("auto", GTEST_FLAG(color).c_str()); EXPECT_FALSE(GTEST_FLAG(death_test_use_fork)); EXPECT_STREQ("", GTEST_FLAG(filter).c_str()); EXPECT_FALSE(GTEST_FLAG(list_tests)); EXPECT_STREQ("", GTEST_FLAG(output).c_str()); EXPECT_TRUE(GTEST_FLAG(print_time)); EXPECT_EQ(0, GTEST_FLAG(random_seed)); EXPECT_EQ(1, GTEST_FLAG(repeat)); EXPECT_FALSE(GTEST_FLAG(shuffle)); EXPECT_EQ(kMaxStackTraceDepth, GTEST_FLAG(stack_trace_depth)); EXPECT_STREQ("", GTEST_FLAG(stream_result_to).c_str()); EXPECT_FALSE(GTEST_FLAG(throw_on_failure)); GTEST_FLAG(also_run_disabled_tests) = true; GTEST_FLAG(break_on_failure) = true; GTEST_FLAG(catch_exceptions) = true; GTEST_FLAG(color) = "no"; GTEST_FLAG(death_test_use_fork) = true; GTEST_FLAG(filter) = "abc"; GTEST_FLAG(list_tests) = true; GTEST_FLAG(output) = "xml:foo.xml"; GTEST_FLAG(print_time) = false; GTEST_FLAG(random_seed) = 1; GTEST_FLAG(repeat) = 100; GTEST_FLAG(shuffle) = true; GTEST_FLAG(stack_trace_depth) = 1; GTEST_FLAG(stream_result_to) = "localhost:1234"; GTEST_FLAG(throw_on_failure) = true; } private: // For saving Google Test flags during this test case. static GTestFlagSaver* saver_; }; GTestFlagSaver* GTestFlagSaverTest::saver_ = NULL; // Google Test doesn't guarantee the order of tests. The following two // tests are designed to work regardless of their order. // Modifies the Google Test flags in the test body. TEST_F(GTestFlagSaverTest, ModifyGTestFlags) { VerifyAndModifyFlags(); } // Verifies that the Google Test flags in the body of the previous test were // restored to their original values. TEST_F(GTestFlagSaverTest, VerifyGTestFlags) { VerifyAndModifyFlags(); } // Sets an environment variable with the given name to the given // value. If the value argument is "", unsets the environment // variable. The caller must ensure that both arguments are not NULL. static void SetEnv(const char* name, const char* value) { #if GTEST_OS_WINDOWS_MOBILE // Environment variables are not supported on Windows CE. return; #elif defined(__BORLANDC__) || defined(__SunOS_5_8) || defined(__SunOS_5_9) // C++Builder's putenv only stores a pointer to its parameter; we have to // ensure that the string remains valid as long as it might be needed. // We use an std::map to do so. static std::map added_env; // Because putenv stores a pointer to the string buffer, we can't delete the // previous string (if present) until after it's replaced. String *prev_env = NULL; if (added_env.find(name) != added_env.end()) { prev_env = added_env[name]; } added_env[name] = new String((Message() << name << "=" << value).GetString()); // The standard signature of putenv accepts a 'char*' argument. Other // implementations, like C++Builder's, accept a 'const char*'. // We cast away the 'const' since that would work for both variants. putenv(const_cast(added_env[name]->c_str())); delete prev_env; #elif GTEST_OS_WINDOWS // If we are on Windows proper. _putenv((Message() << name << "=" << value).GetString().c_str()); #else if (*value == '\0') { unsetenv(name); } else { setenv(name, value, 1); } #endif // GTEST_OS_WINDOWS_MOBILE } #if !GTEST_OS_WINDOWS_MOBILE // Environment variables are not supported on Windows CE. using testing::internal::Int32FromGTestEnv; // Tests Int32FromGTestEnv(). // Tests that Int32FromGTestEnv() returns the default value when the // environment variable is not set. TEST(Int32FromGTestEnvTest, ReturnsDefaultWhenVariableIsNotSet) { SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", ""); EXPECT_EQ(10, Int32FromGTestEnv("temp", 10)); } // Tests that Int32FromGTestEnv() returns the default value when the // environment variable overflows as an Int32. TEST(Int32FromGTestEnvTest, ReturnsDefaultWhenValueOverflows) { printf("(expecting 2 warnings)\n"); SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "12345678987654321"); EXPECT_EQ(20, Int32FromGTestEnv("temp", 20)); SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "-12345678987654321"); EXPECT_EQ(30, Int32FromGTestEnv("temp", 30)); } // Tests that Int32FromGTestEnv() returns the default value when the // environment variable does not represent a valid decimal integer. TEST(Int32FromGTestEnvTest, ReturnsDefaultWhenValueIsInvalid) { printf("(expecting 2 warnings)\n"); SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "A1"); EXPECT_EQ(40, Int32FromGTestEnv("temp", 40)); SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "12X"); EXPECT_EQ(50, Int32FromGTestEnv("temp", 50)); } // Tests that Int32FromGTestEnv() parses and returns the value of the // environment variable when it represents a valid decimal integer in // the range of an Int32. TEST(Int32FromGTestEnvTest, ParsesAndReturnsValidValue) { SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "123"); EXPECT_EQ(123, Int32FromGTestEnv("temp", 0)); SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "-321"); EXPECT_EQ(-321, Int32FromGTestEnv("temp", 0)); } #endif // !GTEST_OS_WINDOWS_MOBILE // Tests ParseInt32Flag(). // Tests that ParseInt32Flag() returns false and doesn't change the // output value when the flag has wrong format TEST(ParseInt32FlagTest, ReturnsFalseForInvalidFlag) { Int32 value = 123; EXPECT_FALSE(ParseInt32Flag("--a=100", "b", &value)); EXPECT_EQ(123, value); EXPECT_FALSE(ParseInt32Flag("a=100", "a", &value)); EXPECT_EQ(123, value); } // Tests that ParseInt32Flag() returns false and doesn't change the // output value when the flag overflows as an Int32. TEST(ParseInt32FlagTest, ReturnsDefaultWhenValueOverflows) { printf("(expecting 2 warnings)\n"); Int32 value = 123; EXPECT_FALSE(ParseInt32Flag("--abc=12345678987654321", "abc", &value)); EXPECT_EQ(123, value); EXPECT_FALSE(ParseInt32Flag("--abc=-12345678987654321", "abc", &value)); EXPECT_EQ(123, value); } // Tests that ParseInt32Flag() returns false and doesn't change the // output value when the flag does not represent a valid decimal // integer. TEST(ParseInt32FlagTest, ReturnsDefaultWhenValueIsInvalid) { printf("(expecting 2 warnings)\n"); Int32 value = 123; EXPECT_FALSE(ParseInt32Flag("--abc=A1", "abc", &value)); EXPECT_EQ(123, value); EXPECT_FALSE(ParseInt32Flag("--abc=12X", "abc", &value)); EXPECT_EQ(123, value); } // Tests that ParseInt32Flag() parses the value of the flag and // returns true when the flag represents a valid decimal integer in // the range of an Int32. TEST(ParseInt32FlagTest, ParsesAndReturnsValidValue) { Int32 value = 123; EXPECT_TRUE(ParseInt32Flag("--" GTEST_FLAG_PREFIX_ "abc=456", "abc", &value)); EXPECT_EQ(456, value); EXPECT_TRUE(ParseInt32Flag("--" GTEST_FLAG_PREFIX_ "abc=-789", "abc", &value)); EXPECT_EQ(-789, value); } // Tests that Int32FromEnvOrDie() parses the value of the var or // returns the correct default. // Environment variables are not supported on Windows CE. #if !GTEST_OS_WINDOWS_MOBILE TEST(Int32FromEnvOrDieTest, ParsesAndReturnsValidValue) { EXPECT_EQ(333, Int32FromEnvOrDie(GTEST_FLAG_PREFIX_UPPER_ "UnsetVar", 333)); SetEnv(GTEST_FLAG_PREFIX_UPPER_ "UnsetVar", "123"); EXPECT_EQ(123, Int32FromEnvOrDie(GTEST_FLAG_PREFIX_UPPER_ "UnsetVar", 333)); SetEnv(GTEST_FLAG_PREFIX_UPPER_ "UnsetVar", "-123"); EXPECT_EQ(-123, Int32FromEnvOrDie(GTEST_FLAG_PREFIX_UPPER_ "UnsetVar", 333)); } #endif // !GTEST_OS_WINDOWS_MOBILE // Tests that Int32FromEnvOrDie() aborts with an error message // if the variable is not an Int32. TEST(Int32FromEnvOrDieDeathTest, AbortsOnFailure) { SetEnv(GTEST_FLAG_PREFIX_UPPER_ "VAR", "xxx"); EXPECT_DEATH_IF_SUPPORTED( Int32FromEnvOrDie(GTEST_FLAG_PREFIX_UPPER_ "VAR", 123), ".*"); } // Tests that Int32FromEnvOrDie() aborts with an error message // if the variable cannot be represnted by an Int32. TEST(Int32FromEnvOrDieDeathTest, AbortsOnInt32Overflow) { SetEnv(GTEST_FLAG_PREFIX_UPPER_ "VAR", "1234567891234567891234"); EXPECT_DEATH_IF_SUPPORTED( Int32FromEnvOrDie(GTEST_FLAG_PREFIX_UPPER_ "VAR", 123), ".*"); } // Tests that ShouldRunTestOnShard() selects all tests // where there is 1 shard. TEST(ShouldRunTestOnShardTest, IsPartitionWhenThereIsOneShard) { EXPECT_TRUE(ShouldRunTestOnShard(1, 0, 0)); EXPECT_TRUE(ShouldRunTestOnShard(1, 0, 1)); EXPECT_TRUE(ShouldRunTestOnShard(1, 0, 2)); EXPECT_TRUE(ShouldRunTestOnShard(1, 0, 3)); EXPECT_TRUE(ShouldRunTestOnShard(1, 0, 4)); } class ShouldShardTest : public testing::Test { protected: virtual void SetUp() { index_var_ = GTEST_FLAG_PREFIX_UPPER_ "INDEX"; total_var_ = GTEST_FLAG_PREFIX_UPPER_ "TOTAL"; } virtual void TearDown() { SetEnv(index_var_, ""); SetEnv(total_var_, ""); } const char* index_var_; const char* total_var_; }; // Tests that sharding is disabled if neither of the environment variables // are set. TEST_F(ShouldShardTest, ReturnsFalseWhenNeitherEnvVarIsSet) { SetEnv(index_var_, ""); SetEnv(total_var_, ""); EXPECT_FALSE(ShouldShard(total_var_, index_var_, false)); EXPECT_FALSE(ShouldShard(total_var_, index_var_, true)); } // Tests that sharding is not enabled if total_shards == 1. TEST_F(ShouldShardTest, ReturnsFalseWhenTotalShardIsOne) { SetEnv(index_var_, "0"); SetEnv(total_var_, "1"); EXPECT_FALSE(ShouldShard(total_var_, index_var_, false)); EXPECT_FALSE(ShouldShard(total_var_, index_var_, true)); } // Tests that sharding is enabled if total_shards > 1 and // we are not in a death test subprocess. // Environment variables are not supported on Windows CE. #if !GTEST_OS_WINDOWS_MOBILE TEST_F(ShouldShardTest, WorksWhenShardEnvVarsAreValid) { SetEnv(index_var_, "4"); SetEnv(total_var_, "22"); EXPECT_TRUE(ShouldShard(total_var_, index_var_, false)); EXPECT_FALSE(ShouldShard(total_var_, index_var_, true)); SetEnv(index_var_, "8"); SetEnv(total_var_, "9"); EXPECT_TRUE(ShouldShard(total_var_, index_var_, false)); EXPECT_FALSE(ShouldShard(total_var_, index_var_, true)); SetEnv(index_var_, "0"); SetEnv(total_var_, "9"); EXPECT_TRUE(ShouldShard(total_var_, index_var_, false)); EXPECT_FALSE(ShouldShard(total_var_, index_var_, true)); } #endif // !GTEST_OS_WINDOWS_MOBILE // Tests that we exit in error if the sharding values are not valid. typedef ShouldShardTest ShouldShardDeathTest; TEST_F(ShouldShardDeathTest, AbortsWhenShardingEnvVarsAreInvalid) { SetEnv(index_var_, "4"); SetEnv(total_var_, "4"); EXPECT_DEATH_IF_SUPPORTED(ShouldShard(total_var_, index_var_, false), ".*"); SetEnv(index_var_, "4"); SetEnv(total_var_, "-2"); EXPECT_DEATH_IF_SUPPORTED(ShouldShard(total_var_, index_var_, false), ".*"); SetEnv(index_var_, "5"); SetEnv(total_var_, ""); EXPECT_DEATH_IF_SUPPORTED(ShouldShard(total_var_, index_var_, false), ".*"); SetEnv(index_var_, ""); SetEnv(total_var_, "5"); EXPECT_DEATH_IF_SUPPORTED(ShouldShard(total_var_, index_var_, false), ".*"); } // Tests that ShouldRunTestOnShard is a partition when 5 // shards are used. TEST(ShouldRunTestOnShardTest, IsPartitionWhenThereAreFiveShards) { // Choose an arbitrary number of tests and shards. const int num_tests = 17; const int num_shards = 5; // Check partitioning: each test should be on exactly 1 shard. for (int test_id = 0; test_id < num_tests; test_id++) { int prev_selected_shard_index = -1; for (int shard_index = 0; shard_index < num_shards; shard_index++) { if (ShouldRunTestOnShard(num_shards, shard_index, test_id)) { if (prev_selected_shard_index < 0) { prev_selected_shard_index = shard_index; } else { ADD_FAILURE() << "Shard " << prev_selected_shard_index << " and " << shard_index << " are both selected to run test " << test_id; } } } } // Check balance: This is not required by the sharding protocol, but is a // desirable property for performance. for (int shard_index = 0; shard_index < num_shards; shard_index++) { int num_tests_on_shard = 0; for (int test_id = 0; test_id < num_tests; test_id++) { num_tests_on_shard += ShouldRunTestOnShard(num_shards, shard_index, test_id); } EXPECT_GE(num_tests_on_shard, num_tests / num_shards); } } // For the same reason we are not explicitly testing everything in the // Test class, there are no separate tests for the following classes // (except for some trivial cases): // // TestCase, UnitTest, UnitTestResultPrinter. // // Similarly, there are no separate tests for the following macros: // // TEST, TEST_F, RUN_ALL_TESTS TEST(UnitTestTest, CanGetOriginalWorkingDir) { ASSERT_TRUE(UnitTest::GetInstance()->original_working_dir() != NULL); EXPECT_STRNE(UnitTest::GetInstance()->original_working_dir(), ""); } // This group of tests is for predicate assertions (ASSERT_PRED*, etc) // of various arities. They do not attempt to be exhaustive. Rather, // view them as smoke tests that can be easily reviewed and verified. // A more complete set of tests for predicate assertions can be found // in gtest_pred_impl_unittest.cc. // First, some predicates and predicate-formatters needed by the tests. // Returns true iff the argument is an even number. bool IsEven(int n) { return (n % 2) == 0; } // A functor that returns true iff the argument is an even number. struct IsEvenFunctor { bool operator()(int n) { return IsEven(n); } }; // A predicate-formatter function that asserts the argument is an even // number. AssertionResult AssertIsEven(const char* expr, int n) { if (IsEven(n)) { return AssertionSuccess(); } Message msg; msg << expr << " evaluates to " << n << ", which is not even."; return AssertionFailure(msg); } // A predicate function that returns AssertionResult for use in // EXPECT/ASSERT_TRUE/FALSE. AssertionResult ResultIsEven(int n) { if (IsEven(n)) return AssertionSuccess() << n << " is even"; else return AssertionFailure() << n << " is odd"; } // A predicate function that returns AssertionResult but gives no // explanation why it succeeds. Needed for testing that // EXPECT/ASSERT_FALSE handles such functions correctly. AssertionResult ResultIsEvenNoExplanation(int n) { if (IsEven(n)) return AssertionSuccess(); else return AssertionFailure() << n << " is odd"; } // A predicate-formatter functor that asserts the argument is an even // number. struct AssertIsEvenFunctor { AssertionResult operator()(const char* expr, int n) { return AssertIsEven(expr, n); } }; // Returns true iff the sum of the arguments is an even number. bool SumIsEven2(int n1, int n2) { return IsEven(n1 + n2); } // A functor that returns true iff the sum of the arguments is an even // number. struct SumIsEven3Functor { bool operator()(int n1, int n2, int n3) { return IsEven(n1 + n2 + n3); } }; // A predicate-formatter function that asserts the sum of the // arguments is an even number. AssertionResult AssertSumIsEven4( const char* e1, const char* e2, const char* e3, const char* e4, int n1, int n2, int n3, int n4) { const int sum = n1 + n2 + n3 + n4; if (IsEven(sum)) { return AssertionSuccess(); } Message msg; msg << e1 << " + " << e2 << " + " << e3 << " + " << e4 << " (" << n1 << " + " << n2 << " + " << n3 << " + " << n4 << ") evaluates to " << sum << ", which is not even."; return AssertionFailure(msg); } // A predicate-formatter functor that asserts the sum of the arguments // is an even number. struct AssertSumIsEven5Functor { AssertionResult operator()( const char* e1, const char* e2, const char* e3, const char* e4, const char* e5, int n1, int n2, int n3, int n4, int n5) { const int sum = n1 + n2 + n3 + n4 + n5; if (IsEven(sum)) { return AssertionSuccess(); } Message msg; msg << e1 << " + " << e2 << " + " << e3 << " + " << e4 << " + " << e5 << " (" << n1 << " + " << n2 << " + " << n3 << " + " << n4 << " + " << n5 << ") evaluates to " << sum << ", which is not even."; return AssertionFailure(msg); } }; // Tests unary predicate assertions. // Tests unary predicate assertions that don't use a custom formatter. TEST(Pred1Test, WithoutFormat) { // Success cases. EXPECT_PRED1(IsEvenFunctor(), 2) << "This failure is UNEXPECTED!"; ASSERT_PRED1(IsEven, 4); // Failure cases. EXPECT_NONFATAL_FAILURE({ // NOLINT EXPECT_PRED1(IsEven, 5) << "This failure is expected."; }, "This failure is expected."); EXPECT_FATAL_FAILURE(ASSERT_PRED1(IsEvenFunctor(), 5), "evaluates to false"); } // Tests unary predicate assertions that use a custom formatter. TEST(Pred1Test, WithFormat) { // Success cases. EXPECT_PRED_FORMAT1(AssertIsEven, 2); ASSERT_PRED_FORMAT1(AssertIsEvenFunctor(), 4) << "This failure is UNEXPECTED!"; // Failure cases. const int n = 5; EXPECT_NONFATAL_FAILURE(EXPECT_PRED_FORMAT1(AssertIsEvenFunctor(), n), "n evaluates to 5, which is not even."); EXPECT_FATAL_FAILURE({ // NOLINT ASSERT_PRED_FORMAT1(AssertIsEven, 5) << "This failure is expected."; }, "This failure is expected."); } // Tests that unary predicate assertions evaluates their arguments // exactly once. TEST(Pred1Test, SingleEvaluationOnFailure) { // A success case. static int n = 0; EXPECT_PRED1(IsEven, n++); EXPECT_EQ(1, n) << "The argument is not evaluated exactly once."; // A failure case. EXPECT_FATAL_FAILURE({ // NOLINT ASSERT_PRED_FORMAT1(AssertIsEvenFunctor(), n++) << "This failure is expected."; }, "This failure is expected."); EXPECT_EQ(2, n) << "The argument is not evaluated exactly once."; } // Tests predicate assertions whose arity is >= 2. // Tests predicate assertions that don't use a custom formatter. TEST(PredTest, WithoutFormat) { // Success cases. ASSERT_PRED2(SumIsEven2, 2, 4) << "This failure is UNEXPECTED!"; EXPECT_PRED3(SumIsEven3Functor(), 4, 6, 8); // Failure cases. const int n1 = 1; const int n2 = 2; EXPECT_NONFATAL_FAILURE({ // NOLINT EXPECT_PRED2(SumIsEven2, n1, n2) << "This failure is expected."; }, "This failure is expected."); EXPECT_FATAL_FAILURE({ // NOLINT ASSERT_PRED3(SumIsEven3Functor(), 1, 2, 4); }, "evaluates to false"); } // Tests predicate assertions that use a custom formatter. TEST(PredTest, WithFormat) { // Success cases. ASSERT_PRED_FORMAT4(AssertSumIsEven4, 4, 6, 8, 10) << "This failure is UNEXPECTED!"; EXPECT_PRED_FORMAT5(AssertSumIsEven5Functor(), 2, 4, 6, 8, 10); // Failure cases. const int n1 = 1; const int n2 = 2; const int n3 = 4; const int n4 = 6; EXPECT_NONFATAL_FAILURE({ // NOLINT EXPECT_PRED_FORMAT4(AssertSumIsEven4, n1, n2, n3, n4); }, "evaluates to 13, which is not even."); EXPECT_FATAL_FAILURE({ // NOLINT ASSERT_PRED_FORMAT5(AssertSumIsEven5Functor(), 1, 2, 4, 6, 8) << "This failure is expected."; }, "This failure is expected."); } // Tests that predicate assertions evaluates their arguments // exactly once. TEST(PredTest, SingleEvaluationOnFailure) { // A success case. int n1 = 0; int n2 = 0; EXPECT_PRED2(SumIsEven2, n1++, n2++); EXPECT_EQ(1, n1) << "Argument 1 is not evaluated exactly once."; EXPECT_EQ(1, n2) << "Argument 2 is not evaluated exactly once."; // Another success case. n1 = n2 = 0; int n3 = 0; int n4 = 0; int n5 = 0; ASSERT_PRED_FORMAT5(AssertSumIsEven5Functor(), n1++, n2++, n3++, n4++, n5++) << "This failure is UNEXPECTED!"; EXPECT_EQ(1, n1) << "Argument 1 is not evaluated exactly once."; EXPECT_EQ(1, n2) << "Argument 2 is not evaluated exactly once."; EXPECT_EQ(1, n3) << "Argument 3 is not evaluated exactly once."; EXPECT_EQ(1, n4) << "Argument 4 is not evaluated exactly once."; EXPECT_EQ(1, n5) << "Argument 5 is not evaluated exactly once."; // A failure case. n1 = n2 = n3 = 0; EXPECT_NONFATAL_FAILURE({ // NOLINT EXPECT_PRED3(SumIsEven3Functor(), ++n1, n2++, n3++) << "This failure is expected."; }, "This failure is expected."); EXPECT_EQ(1, n1) << "Argument 1 is not evaluated exactly once."; EXPECT_EQ(1, n2) << "Argument 2 is not evaluated exactly once."; EXPECT_EQ(1, n3) << "Argument 3 is not evaluated exactly once."; // Another failure case. n1 = n2 = n3 = n4 = 0; EXPECT_NONFATAL_FAILURE({ // NOLINT EXPECT_PRED_FORMAT4(AssertSumIsEven4, ++n1, n2++, n3++, n4++); }, "evaluates to 1, which is not even."); EXPECT_EQ(1, n1) << "Argument 1 is not evaluated exactly once."; EXPECT_EQ(1, n2) << "Argument 2 is not evaluated exactly once."; EXPECT_EQ(1, n3) << "Argument 3 is not evaluated exactly once."; EXPECT_EQ(1, n4) << "Argument 4 is not evaluated exactly once."; } // Some helper functions for testing using overloaded/template // functions with ASSERT_PREDn and EXPECT_PREDn. bool IsPositive(double x) { return x > 0; } template bool IsNegative(T x) { return x < 0; } template bool GreaterThan(T1 x1, T2 x2) { return x1 > x2; } // Tests that overloaded functions can be used in *_PRED* as long as // their types are explicitly specified. TEST(PredicateAssertionTest, AcceptsOverloadedFunction) { // C++Builder requires C-style casts rather than static_cast. EXPECT_PRED1((bool (*)(int))(IsPositive), 5); // NOLINT ASSERT_PRED1((bool (*)(double))(IsPositive), 6.0); // NOLINT } // Tests that template functions can be used in *_PRED* as long as // their types are explicitly specified. TEST(PredicateAssertionTest, AcceptsTemplateFunction) { EXPECT_PRED1(IsNegative, -5); // Makes sure that we can handle templates with more than one // parameter. ASSERT_PRED2((GreaterThan), 5, 0); } // Some helper functions for testing using overloaded/template // functions with ASSERT_PRED_FORMATn and EXPECT_PRED_FORMATn. AssertionResult IsPositiveFormat(const char* /* expr */, int n) { return n > 0 ? AssertionSuccess() : AssertionFailure(Message() << "Failure"); } AssertionResult IsPositiveFormat(const char* /* expr */, double x) { return x > 0 ? AssertionSuccess() : AssertionFailure(Message() << "Failure"); } template AssertionResult IsNegativeFormat(const char* /* expr */, T x) { return x < 0 ? AssertionSuccess() : AssertionFailure(Message() << "Failure"); } template AssertionResult EqualsFormat(const char* /* expr1 */, const char* /* expr2 */, const T1& x1, const T2& x2) { return x1 == x2 ? AssertionSuccess() : AssertionFailure(Message() << "Failure"); } // Tests that overloaded functions can be used in *_PRED_FORMAT* // without explicitly specifying their types. TEST(PredicateFormatAssertionTest, AcceptsOverloadedFunction) { EXPECT_PRED_FORMAT1(IsPositiveFormat, 5); ASSERT_PRED_FORMAT1(IsPositiveFormat, 6.0); } // Tests that template functions can be used in *_PRED_FORMAT* without // explicitly specifying their types. TEST(PredicateFormatAssertionTest, AcceptsTemplateFunction) { EXPECT_PRED_FORMAT1(IsNegativeFormat, -5); ASSERT_PRED_FORMAT2(EqualsFormat, 3, 3); } // Tests string assertions. // Tests ASSERT_STREQ with non-NULL arguments. TEST(StringAssertionTest, ASSERT_STREQ) { const char * const p1 = "good"; ASSERT_STREQ(p1, p1); // Let p2 have the same content as p1, but be at a different address. const char p2[] = "good"; ASSERT_STREQ(p1, p2); EXPECT_FATAL_FAILURE(ASSERT_STREQ("bad", "good"), "Expected: \"bad\""); } // Tests ASSERT_STREQ with NULL arguments. TEST(StringAssertionTest, ASSERT_STREQ_Null) { ASSERT_STREQ(static_cast(NULL), NULL); EXPECT_FATAL_FAILURE(ASSERT_STREQ(NULL, "non-null"), "non-null"); } // Tests ASSERT_STREQ with NULL arguments. TEST(StringAssertionTest, ASSERT_STREQ_Null2) { EXPECT_FATAL_FAILURE(ASSERT_STREQ("non-null", NULL), "non-null"); } // Tests ASSERT_STRNE. TEST(StringAssertionTest, ASSERT_STRNE) { ASSERT_STRNE("hi", "Hi"); ASSERT_STRNE("Hi", NULL); ASSERT_STRNE(NULL, "Hi"); ASSERT_STRNE("", NULL); ASSERT_STRNE(NULL, ""); ASSERT_STRNE("", "Hi"); ASSERT_STRNE("Hi", ""); EXPECT_FATAL_FAILURE(ASSERT_STRNE("Hi", "Hi"), "\"Hi\" vs \"Hi\""); } // Tests ASSERT_STRCASEEQ. TEST(StringAssertionTest, ASSERT_STRCASEEQ) { ASSERT_STRCASEEQ("hi", "Hi"); ASSERT_STRCASEEQ(static_cast(NULL), NULL); ASSERT_STRCASEEQ("", ""); EXPECT_FATAL_FAILURE(ASSERT_STRCASEEQ("Hi", "hi2"), "(ignoring case)"); } // Tests ASSERT_STRCASENE. TEST(StringAssertionTest, ASSERT_STRCASENE) { ASSERT_STRCASENE("hi1", "Hi2"); ASSERT_STRCASENE("Hi", NULL); ASSERT_STRCASENE(NULL, "Hi"); ASSERT_STRCASENE("", NULL); ASSERT_STRCASENE(NULL, ""); ASSERT_STRCASENE("", "Hi"); ASSERT_STRCASENE("Hi", ""); EXPECT_FATAL_FAILURE(ASSERT_STRCASENE("Hi", "hi"), "(ignoring case)"); } // Tests *_STREQ on wide strings. TEST(StringAssertionTest, STREQ_Wide) { // NULL strings. ASSERT_STREQ(static_cast(NULL), NULL); // Empty strings. ASSERT_STREQ(L"", L""); // Non-null vs NULL. EXPECT_NONFATAL_FAILURE(EXPECT_STREQ(L"non-null", NULL), "non-null"); // Equal strings. EXPECT_STREQ(L"Hi", L"Hi"); // Unequal strings. EXPECT_NONFATAL_FAILURE(EXPECT_STREQ(L"abc", L"Abc"), "Abc"); // Strings containing wide characters. EXPECT_NONFATAL_FAILURE(EXPECT_STREQ(L"abc\x8119", L"abc\x8120"), "abc"); } // Tests *_STRNE on wide strings. TEST(StringAssertionTest, STRNE_Wide) { // NULL strings. EXPECT_NONFATAL_FAILURE({ // NOLINT EXPECT_STRNE(static_cast(NULL), NULL); }, ""); // Empty strings. EXPECT_NONFATAL_FAILURE(EXPECT_STRNE(L"", L""), "L\"\""); // Non-null vs NULL. ASSERT_STRNE(L"non-null", NULL); // Equal strings. EXPECT_NONFATAL_FAILURE(EXPECT_STRNE(L"Hi", L"Hi"), "L\"Hi\""); // Unequal strings. EXPECT_STRNE(L"abc", L"Abc"); // Strings containing wide characters. EXPECT_NONFATAL_FAILURE(EXPECT_STRNE(L"abc\x8119", L"abc\x8119"), "abc"); } // Tests for ::testing::IsSubstring(). // Tests that IsSubstring() returns the correct result when the input // argument type is const char*. TEST(IsSubstringTest, ReturnsCorrectResultForCString) { EXPECT_FALSE(IsSubstring("", "", NULL, "a")); EXPECT_FALSE(IsSubstring("", "", "b", NULL)); EXPECT_FALSE(IsSubstring("", "", "needle", "haystack")); EXPECT_TRUE(IsSubstring("", "", static_cast(NULL), NULL)); EXPECT_TRUE(IsSubstring("", "", "needle", "two needles")); } // Tests that IsSubstring() returns the correct result when the input // argument type is const wchar_t*. TEST(IsSubstringTest, ReturnsCorrectResultForWideCString) { EXPECT_FALSE(IsSubstring("", "", kNull, L"a")); EXPECT_FALSE(IsSubstring("", "", L"b", kNull)); EXPECT_FALSE(IsSubstring("", "", L"needle", L"haystack")); EXPECT_TRUE(IsSubstring("", "", static_cast(NULL), NULL)); EXPECT_TRUE(IsSubstring("", "", L"needle", L"two needles")); } // Tests that IsSubstring() generates the correct message when the input // argument type is const char*. TEST(IsSubstringTest, GeneratesCorrectMessageForCString) { EXPECT_STREQ("Value of: needle_expr\n" " Actual: \"needle\"\n" "Expected: a substring of haystack_expr\n" "Which is: \"haystack\"", IsSubstring("needle_expr", "haystack_expr", "needle", "haystack").failure_message()); } // Tests that IsSubstring returns the correct result when the input // argument type is ::std::string. TEST(IsSubstringTest, ReturnsCorrectResultsForStdString) { EXPECT_TRUE(IsSubstring("", "", std::string("hello"), "ahellob")); EXPECT_FALSE(IsSubstring("", "", "hello", std::string("world"))); } #if GTEST_HAS_STD_WSTRING // Tests that IsSubstring returns the correct result when the input // argument type is ::std::wstring. TEST(IsSubstringTest, ReturnsCorrectResultForStdWstring) { EXPECT_TRUE(IsSubstring("", "", ::std::wstring(L"needle"), L"two needles")); EXPECT_FALSE(IsSubstring("", "", L"needle", ::std::wstring(L"haystack"))); } // Tests that IsSubstring() generates the correct message when the input // argument type is ::std::wstring. TEST(IsSubstringTest, GeneratesCorrectMessageForWstring) { EXPECT_STREQ("Value of: needle_expr\n" " Actual: L\"needle\"\n" "Expected: a substring of haystack_expr\n" "Which is: L\"haystack\"", IsSubstring( "needle_expr", "haystack_expr", ::std::wstring(L"needle"), L"haystack").failure_message()); } #endif // GTEST_HAS_STD_WSTRING // Tests for ::testing::IsNotSubstring(). // Tests that IsNotSubstring() returns the correct result when the input // argument type is const char*. TEST(IsNotSubstringTest, ReturnsCorrectResultForCString) { EXPECT_TRUE(IsNotSubstring("", "", "needle", "haystack")); EXPECT_FALSE(IsNotSubstring("", "", "needle", "two needles")); } // Tests that IsNotSubstring() returns the correct result when the input // argument type is const wchar_t*. TEST(IsNotSubstringTest, ReturnsCorrectResultForWideCString) { EXPECT_TRUE(IsNotSubstring("", "", L"needle", L"haystack")); EXPECT_FALSE(IsNotSubstring("", "", L"needle", L"two needles")); } // Tests that IsNotSubstring() generates the correct message when the input // argument type is const wchar_t*. TEST(IsNotSubstringTest, GeneratesCorrectMessageForWideCString) { EXPECT_STREQ("Value of: needle_expr\n" " Actual: L\"needle\"\n" "Expected: not a substring of haystack_expr\n" "Which is: L\"two needles\"", IsNotSubstring( "needle_expr", "haystack_expr", L"needle", L"two needles").failure_message()); } // Tests that IsNotSubstring returns the correct result when the input // argument type is ::std::string. TEST(IsNotSubstringTest, ReturnsCorrectResultsForStdString) { EXPECT_FALSE(IsNotSubstring("", "", std::string("hello"), "ahellob")); EXPECT_TRUE(IsNotSubstring("", "", "hello", std::string("world"))); } // Tests that IsNotSubstring() generates the correct message when the input // argument type is ::std::string. TEST(IsNotSubstringTest, GeneratesCorrectMessageForStdString) { EXPECT_STREQ("Value of: needle_expr\n" " Actual: \"needle\"\n" "Expected: not a substring of haystack_expr\n" "Which is: \"two needles\"", IsNotSubstring( "needle_expr", "haystack_expr", ::std::string("needle"), "two needles").failure_message()); } #if GTEST_HAS_STD_WSTRING // Tests that IsNotSubstring returns the correct result when the input // argument type is ::std::wstring. TEST(IsNotSubstringTest, ReturnsCorrectResultForStdWstring) { EXPECT_FALSE( IsNotSubstring("", "", ::std::wstring(L"needle"), L"two needles")); EXPECT_TRUE(IsNotSubstring("", "", L"needle", ::std::wstring(L"haystack"))); } #endif // GTEST_HAS_STD_WSTRING // Tests floating-point assertions. template class FloatingPointTest : public Test { protected: // Pre-calculated numbers to be used by the tests. struct TestValues { RawType close_to_positive_zero; RawType close_to_negative_zero; RawType further_from_negative_zero; RawType close_to_one; RawType further_from_one; RawType infinity; RawType close_to_infinity; RawType further_from_infinity; RawType nan1; RawType nan2; }; typedef typename testing::internal::FloatingPoint Floating; typedef typename Floating::Bits Bits; virtual void SetUp() { const size_t max_ulps = Floating::kMaxUlps; // The bits that represent 0.0. const Bits zero_bits = Floating(0).bits(); // Makes some numbers close to 0.0. values_.close_to_positive_zero = Floating::ReinterpretBits( zero_bits + max_ulps/2); values_.close_to_negative_zero = -Floating::ReinterpretBits( zero_bits + max_ulps - max_ulps/2); values_.further_from_negative_zero = -Floating::ReinterpretBits( zero_bits + max_ulps + 1 - max_ulps/2); // The bits that represent 1.0. const Bits one_bits = Floating(1).bits(); // Makes some numbers close to 1.0. values_.close_to_one = Floating::ReinterpretBits(one_bits + max_ulps); values_.further_from_one = Floating::ReinterpretBits( one_bits + max_ulps + 1); // +infinity. values_.infinity = Floating::Infinity(); // The bits that represent +infinity. const Bits infinity_bits = Floating(values_.infinity).bits(); // Makes some numbers close to infinity. values_.close_to_infinity = Floating::ReinterpretBits( infinity_bits - max_ulps); values_.further_from_infinity = Floating::ReinterpretBits( infinity_bits - max_ulps - 1); // Makes some NAN's. Sets the most significant bit of the fraction so that // our NaN's are quiet; trying to process a signaling NaN would raise an // exception if our environment enables floating point exceptions. values_.nan1 = Floating::ReinterpretBits(Floating::kExponentBitMask | (static_cast(1) << (Floating::kFractionBitCount - 1)) | 1); values_.nan2 = Floating::ReinterpretBits(Floating::kExponentBitMask | (static_cast(1) << (Floating::kFractionBitCount - 1)) | 200); } void TestSize() { EXPECT_EQ(sizeof(RawType), sizeof(Bits)); } static TestValues values_; }; template typename FloatingPointTest::TestValues FloatingPointTest::values_; // Instantiates FloatingPointTest for testing *_FLOAT_EQ. typedef FloatingPointTest FloatTest; // Tests that the size of Float::Bits matches the size of float. TEST_F(FloatTest, Size) { TestSize(); } // Tests comparing with +0 and -0. TEST_F(FloatTest, Zeros) { EXPECT_FLOAT_EQ(0.0, -0.0); EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(-0.0, 1.0), "1.0"); EXPECT_FATAL_FAILURE(ASSERT_FLOAT_EQ(0.0, 1.5), "1.5"); } // Tests comparing numbers close to 0. // // This ensures that *_FLOAT_EQ handles the sign correctly and no // overflow occurs when comparing numbers whose absolute value is very // small. TEST_F(FloatTest, AlmostZeros) { // In C++Builder, names within local classes (such as used by // EXPECT_FATAL_FAILURE) cannot be resolved against static members of the // scoping class. Use a static local alias as a workaround. // We use the assignment syntax since some compilers, like Sun Studio, // don't allow initializing references using construction syntax // (parentheses). static const FloatTest::TestValues& v = this->values_; EXPECT_FLOAT_EQ(0.0, v.close_to_positive_zero); EXPECT_FLOAT_EQ(-0.0, v.close_to_negative_zero); EXPECT_FLOAT_EQ(v.close_to_positive_zero, v.close_to_negative_zero); EXPECT_FATAL_FAILURE({ // NOLINT ASSERT_FLOAT_EQ(v.close_to_positive_zero, v.further_from_negative_zero); }, "v.further_from_negative_zero"); } // Tests comparing numbers close to each other. TEST_F(FloatTest, SmallDiff) { EXPECT_FLOAT_EQ(1.0, values_.close_to_one); EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(1.0, values_.further_from_one), "values_.further_from_one"); } // Tests comparing numbers far apart. TEST_F(FloatTest, LargeDiff) { EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(2.5, 3.0), "3.0"); } // Tests comparing with infinity. // // This ensures that no overflow occurs when comparing numbers whose // absolute value is very large. TEST_F(FloatTest, Infinity) { EXPECT_FLOAT_EQ(values_.infinity, values_.close_to_infinity); EXPECT_FLOAT_EQ(-values_.infinity, -values_.close_to_infinity); #if !GTEST_OS_SYMBIAN // Nokia's STLport crashes if we try to output infinity or NaN. EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(values_.infinity, -values_.infinity), "-values_.infinity"); // This is interesting as the representations of infinity and nan1 // are only 1 DLP apart. EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(values_.infinity, values_.nan1), "values_.nan1"); #endif // !GTEST_OS_SYMBIAN } // Tests that comparing with NAN always returns false. TEST_F(FloatTest, NaN) { #if !GTEST_OS_SYMBIAN // Nokia's STLport crashes if we try to output infinity or NaN. // In C++Builder, names within local classes (such as used by // EXPECT_FATAL_FAILURE) cannot be resolved against static members of the // scoping class. Use a static local alias as a workaround. // We use the assignment syntax since some compilers, like Sun Studio, // don't allow initializing references using construction syntax // (parentheses). static const FloatTest::TestValues& v = this->values_; EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(v.nan1, v.nan1), "v.nan1"); EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(v.nan1, v.nan2), "v.nan2"); EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(1.0, v.nan1), "v.nan1"); EXPECT_FATAL_FAILURE(ASSERT_FLOAT_EQ(v.nan1, v.infinity), "v.infinity"); #endif // !GTEST_OS_SYMBIAN } // Tests that *_FLOAT_EQ are reflexive. TEST_F(FloatTest, Reflexive) { EXPECT_FLOAT_EQ(0.0, 0.0); EXPECT_FLOAT_EQ(1.0, 1.0); ASSERT_FLOAT_EQ(values_.infinity, values_.infinity); } // Tests that *_FLOAT_EQ are commutative. TEST_F(FloatTest, Commutative) { // We already tested EXPECT_FLOAT_EQ(1.0, values_.close_to_one). EXPECT_FLOAT_EQ(values_.close_to_one, 1.0); // We already tested EXPECT_FLOAT_EQ(1.0, values_.further_from_one). EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(values_.further_from_one, 1.0), "1.0"); } // Tests EXPECT_NEAR. TEST_F(FloatTest, EXPECT_NEAR) { EXPECT_NEAR(-1.0f, -1.1f, 0.2f); EXPECT_NEAR(2.0f, 3.0f, 1.0f); EXPECT_NONFATAL_FAILURE(EXPECT_NEAR(1.0f,1.5f, 0.25f), // NOLINT "The difference between 1.0f and 1.5f is 0.5, " "which exceeds 0.25f"); // To work around a bug in gcc 2.95.0, there is intentionally no // space after the first comma in the previous line. } // Tests ASSERT_NEAR. TEST_F(FloatTest, ASSERT_NEAR) { ASSERT_NEAR(-1.0f, -1.1f, 0.2f); ASSERT_NEAR(2.0f, 3.0f, 1.0f); EXPECT_FATAL_FAILURE(ASSERT_NEAR(1.0f,1.5f, 0.25f), // NOLINT "The difference between 1.0f and 1.5f is 0.5, " "which exceeds 0.25f"); // To work around a bug in gcc 2.95.0, there is intentionally no // space after the first comma in the previous line. } // Tests the cases where FloatLE() should succeed. TEST_F(FloatTest, FloatLESucceeds) { EXPECT_PRED_FORMAT2(FloatLE, 1.0f, 2.0f); // When val1 < val2, ASSERT_PRED_FORMAT2(FloatLE, 1.0f, 1.0f); // val1 == val2, // or when val1 is greater than, but almost equals to, val2. EXPECT_PRED_FORMAT2(FloatLE, values_.close_to_positive_zero, 0.0f); } // Tests the cases where FloatLE() should fail. TEST_F(FloatTest, FloatLEFails) { // When val1 is greater than val2 by a large margin, EXPECT_NONFATAL_FAILURE(EXPECT_PRED_FORMAT2(FloatLE, 2.0f, 1.0f), "(2.0f) <= (1.0f)"); // or by a small yet non-negligible margin, EXPECT_NONFATAL_FAILURE({ // NOLINT EXPECT_PRED_FORMAT2(FloatLE, values_.further_from_one, 1.0f); }, "(values_.further_from_one) <= (1.0f)"); #if !GTEST_OS_SYMBIAN && !defined(__BORLANDC__) // Nokia's STLport crashes if we try to output infinity or NaN. // C++Builder gives bad results for ordered comparisons involving NaNs // due to compiler bugs. EXPECT_NONFATAL_FAILURE({ // NOLINT EXPECT_PRED_FORMAT2(FloatLE, values_.nan1, values_.infinity); }, "(values_.nan1) <= (values_.infinity)"); EXPECT_NONFATAL_FAILURE({ // NOLINT EXPECT_PRED_FORMAT2(FloatLE, -values_.infinity, values_.nan1); }, "(-values_.infinity) <= (values_.nan1)"); EXPECT_FATAL_FAILURE({ // NOLINT ASSERT_PRED_FORMAT2(FloatLE, values_.nan1, values_.nan1); }, "(values_.nan1) <= (values_.nan1)"); #endif // !GTEST_OS_SYMBIAN && !defined(__BORLANDC__) } // Instantiates FloatingPointTest for testing *_DOUBLE_EQ. typedef FloatingPointTest DoubleTest; // Tests that the size of Double::Bits matches the size of double. TEST_F(DoubleTest, Size) { TestSize(); } // Tests comparing with +0 and -0. TEST_F(DoubleTest, Zeros) { EXPECT_DOUBLE_EQ(0.0, -0.0); EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(-0.0, 1.0), "1.0"); EXPECT_FATAL_FAILURE(ASSERT_DOUBLE_EQ(0.0, 1.0), "1.0"); } // Tests comparing numbers close to 0. // // This ensures that *_DOUBLE_EQ handles the sign correctly and no // overflow occurs when comparing numbers whose absolute value is very // small. TEST_F(DoubleTest, AlmostZeros) { // In C++Builder, names within local classes (such as used by // EXPECT_FATAL_FAILURE) cannot be resolved against static members of the // scoping class. Use a static local alias as a workaround. // We use the assignment syntax since some compilers, like Sun Studio, // don't allow initializing references using construction syntax // (parentheses). static const DoubleTest::TestValues& v = this->values_; EXPECT_DOUBLE_EQ(0.0, v.close_to_positive_zero); EXPECT_DOUBLE_EQ(-0.0, v.close_to_negative_zero); EXPECT_DOUBLE_EQ(v.close_to_positive_zero, v.close_to_negative_zero); EXPECT_FATAL_FAILURE({ // NOLINT ASSERT_DOUBLE_EQ(v.close_to_positive_zero, v.further_from_negative_zero); }, "v.further_from_negative_zero"); } // Tests comparing numbers close to each other. TEST_F(DoubleTest, SmallDiff) { EXPECT_DOUBLE_EQ(1.0, values_.close_to_one); EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(1.0, values_.further_from_one), "values_.further_from_one"); } // Tests comparing numbers far apart. TEST_F(DoubleTest, LargeDiff) { EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(2.0, 3.0), "3.0"); } // Tests comparing with infinity. // // This ensures that no overflow occurs when comparing numbers whose // absolute value is very large. TEST_F(DoubleTest, Infinity) { EXPECT_DOUBLE_EQ(values_.infinity, values_.close_to_infinity); EXPECT_DOUBLE_EQ(-values_.infinity, -values_.close_to_infinity); #if !GTEST_OS_SYMBIAN // Nokia's STLport crashes if we try to output infinity or NaN. EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(values_.infinity, -values_.infinity), "-values_.infinity"); // This is interesting as the representations of infinity_ and nan1_ // are only 1 DLP apart. EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(values_.infinity, values_.nan1), "values_.nan1"); #endif // !GTEST_OS_SYMBIAN } // Tests that comparing with NAN always returns false. TEST_F(DoubleTest, NaN) { #if !GTEST_OS_SYMBIAN // In C++Builder, names within local classes (such as used by // EXPECT_FATAL_FAILURE) cannot be resolved against static members of the // scoping class. Use a static local alias as a workaround. // We use the assignment syntax since some compilers, like Sun Studio, // don't allow initializing references using construction syntax // (parentheses). static const DoubleTest::TestValues& v = this->values_; // Nokia's STLport crashes if we try to output infinity or NaN. EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(v.nan1, v.nan1), "v.nan1"); EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(v.nan1, v.nan2), "v.nan2"); EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(1.0, v.nan1), "v.nan1"); EXPECT_FATAL_FAILURE(ASSERT_DOUBLE_EQ(v.nan1, v.infinity), "v.infinity"); #endif // !GTEST_OS_SYMBIAN } // Tests that *_DOUBLE_EQ are reflexive. TEST_F(DoubleTest, Reflexive) { EXPECT_DOUBLE_EQ(0.0, 0.0); EXPECT_DOUBLE_EQ(1.0, 1.0); #if !GTEST_OS_SYMBIAN // Nokia's STLport crashes if we try to output infinity or NaN. ASSERT_DOUBLE_EQ(values_.infinity, values_.infinity); #endif // !GTEST_OS_SYMBIAN } // Tests that *_DOUBLE_EQ are commutative. TEST_F(DoubleTest, Commutative) { // We already tested EXPECT_DOUBLE_EQ(1.0, values_.close_to_one). EXPECT_DOUBLE_EQ(values_.close_to_one, 1.0); // We already tested EXPECT_DOUBLE_EQ(1.0, values_.further_from_one). EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(values_.further_from_one, 1.0), "1.0"); } // Tests EXPECT_NEAR. TEST_F(DoubleTest, EXPECT_NEAR) { EXPECT_NEAR(-1.0, -1.1, 0.2); EXPECT_NEAR(2.0, 3.0, 1.0); EXPECT_NONFATAL_FAILURE(EXPECT_NEAR(1.0, 1.5, 0.25), // NOLINT "The difference between 1.0 and 1.5 is 0.5, " "which exceeds 0.25"); // To work around a bug in gcc 2.95.0, there is intentionally no // space after the first comma in the previous statement. } // Tests ASSERT_NEAR. TEST_F(DoubleTest, ASSERT_NEAR) { ASSERT_NEAR(-1.0, -1.1, 0.2); ASSERT_NEAR(2.0, 3.0, 1.0); EXPECT_FATAL_FAILURE(ASSERT_NEAR(1.0, 1.5, 0.25), // NOLINT "The difference between 1.0 and 1.5 is 0.5, " "which exceeds 0.25"); // To work around a bug in gcc 2.95.0, there is intentionally no // space after the first comma in the previous statement. } // Tests the cases where DoubleLE() should succeed. TEST_F(DoubleTest, DoubleLESucceeds) { EXPECT_PRED_FORMAT2(DoubleLE, 1.0, 2.0); // When val1 < val2, ASSERT_PRED_FORMAT2(DoubleLE, 1.0, 1.0); // val1 == val2, // or when val1 is greater than, but almost equals to, val2. EXPECT_PRED_FORMAT2(DoubleLE, values_.close_to_positive_zero, 0.0); } // Tests the cases where DoubleLE() should fail. TEST_F(DoubleTest, DoubleLEFails) { // When val1 is greater than val2 by a large margin, EXPECT_NONFATAL_FAILURE(EXPECT_PRED_FORMAT2(DoubleLE, 2.0, 1.0), "(2.0) <= (1.0)"); // or by a small yet non-negligible margin, EXPECT_NONFATAL_FAILURE({ // NOLINT EXPECT_PRED_FORMAT2(DoubleLE, values_.further_from_one, 1.0); }, "(values_.further_from_one) <= (1.0)"); #if !GTEST_OS_SYMBIAN && !defined(__BORLANDC__) // Nokia's STLport crashes if we try to output infinity or NaN. // C++Builder gives bad results for ordered comparisons involving NaNs // due to compiler bugs. EXPECT_NONFATAL_FAILURE({ // NOLINT EXPECT_PRED_FORMAT2(DoubleLE, values_.nan1, values_.infinity); }, "(values_.nan1) <= (values_.infinity)"); EXPECT_NONFATAL_FAILURE({ // NOLINT EXPECT_PRED_FORMAT2(DoubleLE, -values_.infinity, values_.nan1); }, " (-values_.infinity) <= (values_.nan1)"); EXPECT_FATAL_FAILURE({ // NOLINT ASSERT_PRED_FORMAT2(DoubleLE, values_.nan1, values_.nan1); }, "(values_.nan1) <= (values_.nan1)"); #endif // !GTEST_OS_SYMBIAN && !defined(__BORLANDC__) } // Verifies that a test or test case whose name starts with DISABLED_ is // not run. // A test whose name starts with DISABLED_. // Should not run. TEST(DisabledTest, DISABLED_TestShouldNotRun) { FAIL() << "Unexpected failure: Disabled test should not be run."; } // A test whose name does not start with DISABLED_. // Should run. TEST(DisabledTest, NotDISABLED_TestShouldRun) { EXPECT_EQ(1, 1); } // A test case whose name starts with DISABLED_. // Should not run. TEST(DISABLED_TestCase, TestShouldNotRun) { FAIL() << "Unexpected failure: Test in disabled test case should not be run."; } // A test case and test whose names start with DISABLED_. // Should not run. TEST(DISABLED_TestCase, DISABLED_TestShouldNotRun) { FAIL() << "Unexpected failure: Test in disabled test case should not be run."; } // Check that when all tests in a test case are disabled, SetupTestCase() and // TearDownTestCase() are not called. class DisabledTestsTest : public Test { protected: static void SetUpTestCase() { FAIL() << "Unexpected failure: All tests disabled in test case. " "SetupTestCase() should not be called."; } static void TearDownTestCase() { FAIL() << "Unexpected failure: All tests disabled in test case. " "TearDownTestCase() should not be called."; } }; TEST_F(DisabledTestsTest, DISABLED_TestShouldNotRun_1) { FAIL() << "Unexpected failure: Disabled test should not be run."; } TEST_F(DisabledTestsTest, DISABLED_TestShouldNotRun_2) { FAIL() << "Unexpected failure: Disabled test should not be run."; } // Tests that disabled typed tests aren't run. #if GTEST_HAS_TYPED_TEST template class TypedTest : public Test { }; typedef testing::Types NumericTypes; TYPED_TEST_CASE(TypedTest, NumericTypes); TYPED_TEST(TypedTest, DISABLED_ShouldNotRun) { FAIL() << "Unexpected failure: Disabled typed test should not run."; } template class DISABLED_TypedTest : public Test { }; TYPED_TEST_CASE(DISABLED_TypedTest, NumericTypes); TYPED_TEST(DISABLED_TypedTest, ShouldNotRun) { FAIL() << "Unexpected failure: Disabled typed test should not run."; } #endif // GTEST_HAS_TYPED_TEST // Tests that disabled type-parameterized tests aren't run. #if GTEST_HAS_TYPED_TEST_P template class TypedTestP : public Test { }; TYPED_TEST_CASE_P(TypedTestP); TYPED_TEST_P(TypedTestP, DISABLED_ShouldNotRun) { FAIL() << "Unexpected failure: " << "Disabled type-parameterized test should not run."; } REGISTER_TYPED_TEST_CASE_P(TypedTestP, DISABLED_ShouldNotRun); INSTANTIATE_TYPED_TEST_CASE_P(My, TypedTestP, NumericTypes); template class DISABLED_TypedTestP : public Test { }; TYPED_TEST_CASE_P(DISABLED_TypedTestP); TYPED_TEST_P(DISABLED_TypedTestP, ShouldNotRun) { FAIL() << "Unexpected failure: " << "Disabled type-parameterized test should not run."; } REGISTER_TYPED_TEST_CASE_P(DISABLED_TypedTestP, ShouldNotRun); INSTANTIATE_TYPED_TEST_CASE_P(My, DISABLED_TypedTestP, NumericTypes); #endif // GTEST_HAS_TYPED_TEST_P // Tests that assertion macros evaluate their arguments exactly once. class SingleEvaluationTest : public Test { public: // Must be public and not protected due to a bug in g++ 3.4.2. // This helper function is needed by the FailedASSERT_STREQ test // below. It's public to work around C++Builder's bug with scoping local // classes. static void CompareAndIncrementCharPtrs() { ASSERT_STREQ(p1_++, p2_++); } // This helper function is needed by the FailedASSERT_NE test below. It's // public to work around C++Builder's bug with scoping local classes. static void CompareAndIncrementInts() { ASSERT_NE(a_++, b_++); } protected: SingleEvaluationTest() { p1_ = s1_; p2_ = s2_; a_ = 0; b_ = 0; } static const char* const s1_; static const char* const s2_; static const char* p1_; static const char* p2_; static int a_; static int b_; }; const char* const SingleEvaluationTest::s1_ = "01234"; const char* const SingleEvaluationTest::s2_ = "abcde"; const char* SingleEvaluationTest::p1_; const char* SingleEvaluationTest::p2_; int SingleEvaluationTest::a_; int SingleEvaluationTest::b_; // Tests that when ASSERT_STREQ fails, it evaluates its arguments // exactly once. TEST_F(SingleEvaluationTest, FailedASSERT_STREQ) { EXPECT_FATAL_FAILURE(SingleEvaluationTest::CompareAndIncrementCharPtrs(), "p2_++"); EXPECT_EQ(s1_ + 1, p1_); EXPECT_EQ(s2_ + 1, p2_); } // Tests that string assertion arguments are evaluated exactly once. TEST_F(SingleEvaluationTest, ASSERT_STR) { // successful EXPECT_STRNE EXPECT_STRNE(p1_++, p2_++); EXPECT_EQ(s1_ + 1, p1_); EXPECT_EQ(s2_ + 1, p2_); // failed EXPECT_STRCASEEQ EXPECT_NONFATAL_FAILURE(EXPECT_STRCASEEQ(p1_++, p2_++), "ignoring case"); EXPECT_EQ(s1_ + 2, p1_); EXPECT_EQ(s2_ + 2, p2_); } // Tests that when ASSERT_NE fails, it evaluates its arguments exactly // once. TEST_F(SingleEvaluationTest, FailedASSERT_NE) { EXPECT_FATAL_FAILURE(SingleEvaluationTest::CompareAndIncrementInts(), "(a_++) != (b_++)"); EXPECT_EQ(1, a_); EXPECT_EQ(1, b_); } // Tests that assertion arguments are evaluated exactly once. TEST_F(SingleEvaluationTest, OtherCases) { // successful EXPECT_TRUE EXPECT_TRUE(0 == a_++); // NOLINT EXPECT_EQ(1, a_); // failed EXPECT_TRUE EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(-1 == a_++), "-1 == a_++"); EXPECT_EQ(2, a_); // successful EXPECT_GT EXPECT_GT(a_++, b_++); EXPECT_EQ(3, a_); EXPECT_EQ(1, b_); // failed EXPECT_LT EXPECT_NONFATAL_FAILURE(EXPECT_LT(a_++, b_++), "(a_++) < (b_++)"); EXPECT_EQ(4, a_); EXPECT_EQ(2, b_); // successful ASSERT_TRUE ASSERT_TRUE(0 < a_++); // NOLINT EXPECT_EQ(5, a_); // successful ASSERT_GT ASSERT_GT(a_++, b_++); EXPECT_EQ(6, a_); EXPECT_EQ(3, b_); } #if GTEST_HAS_EXCEPTIONS void ThrowAnInteger() { throw 1; } // Tests that assertion arguments are evaluated exactly once. TEST_F(SingleEvaluationTest, ExceptionTests) { // successful EXPECT_THROW EXPECT_THROW({ // NOLINT a_++; ThrowAnInteger(); }, int); EXPECT_EQ(1, a_); // failed EXPECT_THROW, throws different EXPECT_NONFATAL_FAILURE(EXPECT_THROW({ // NOLINT a_++; ThrowAnInteger(); }, bool), "throws a different type"); EXPECT_EQ(2, a_); // failed EXPECT_THROW, throws nothing EXPECT_NONFATAL_FAILURE(EXPECT_THROW(a_++, bool), "throws nothing"); EXPECT_EQ(3, a_); // successful EXPECT_NO_THROW EXPECT_NO_THROW(a_++); EXPECT_EQ(4, a_); // failed EXPECT_NO_THROW EXPECT_NONFATAL_FAILURE(EXPECT_NO_THROW({ // NOLINT a_++; ThrowAnInteger(); }), "it throws"); EXPECT_EQ(5, a_); // successful EXPECT_ANY_THROW EXPECT_ANY_THROW({ // NOLINT a_++; ThrowAnInteger(); }); EXPECT_EQ(6, a_); // failed EXPECT_ANY_THROW EXPECT_NONFATAL_FAILURE(EXPECT_ANY_THROW(a_++), "it doesn't"); EXPECT_EQ(7, a_); } #endif // GTEST_HAS_EXCEPTIONS // Tests {ASSERT|EXPECT}_NO_FATAL_FAILURE. class NoFatalFailureTest : public Test { protected: void Succeeds() {} void FailsNonFatal() { ADD_FAILURE() << "some non-fatal failure"; } void Fails() { FAIL() << "some fatal failure"; } void DoAssertNoFatalFailureOnFails() { ASSERT_NO_FATAL_FAILURE(Fails()); ADD_FAILURE() << "shold not reach here."; } void DoExpectNoFatalFailureOnFails() { EXPECT_NO_FATAL_FAILURE(Fails()); ADD_FAILURE() << "other failure"; } }; TEST_F(NoFatalFailureTest, NoFailure) { EXPECT_NO_FATAL_FAILURE(Succeeds()); ASSERT_NO_FATAL_FAILURE(Succeeds()); } TEST_F(NoFatalFailureTest, NonFatalIsNoFailure) { EXPECT_NONFATAL_FAILURE( EXPECT_NO_FATAL_FAILURE(FailsNonFatal()), "some non-fatal failure"); EXPECT_NONFATAL_FAILURE( ASSERT_NO_FATAL_FAILURE(FailsNonFatal()), "some non-fatal failure"); } TEST_F(NoFatalFailureTest, AssertNoFatalFailureOnFatalFailure) { TestPartResultArray gtest_failures; { ScopedFakeTestPartResultReporter gtest_reporter(>est_failures); DoAssertNoFatalFailureOnFails(); } ASSERT_EQ(2, gtest_failures.size()); EXPECT_EQ(TestPartResult::kFatalFailure, gtest_failures.GetTestPartResult(0).type()); EXPECT_EQ(TestPartResult::kFatalFailure, gtest_failures.GetTestPartResult(1).type()); EXPECT_PRED_FORMAT2(testing::IsSubstring, "some fatal failure", gtest_failures.GetTestPartResult(0).message()); EXPECT_PRED_FORMAT2(testing::IsSubstring, "it does", gtest_failures.GetTestPartResult(1).message()); } TEST_F(NoFatalFailureTest, ExpectNoFatalFailureOnFatalFailure) { TestPartResultArray gtest_failures; { ScopedFakeTestPartResultReporter gtest_reporter(>est_failures); DoExpectNoFatalFailureOnFails(); } ASSERT_EQ(3, gtest_failures.size()); EXPECT_EQ(TestPartResult::kFatalFailure, gtest_failures.GetTestPartResult(0).type()); EXPECT_EQ(TestPartResult::kNonFatalFailure, gtest_failures.GetTestPartResult(1).type()); EXPECT_EQ(TestPartResult::kNonFatalFailure, gtest_failures.GetTestPartResult(2).type()); EXPECT_PRED_FORMAT2(testing::IsSubstring, "some fatal failure", gtest_failures.GetTestPartResult(0).message()); EXPECT_PRED_FORMAT2(testing::IsSubstring, "it does", gtest_failures.GetTestPartResult(1).message()); EXPECT_PRED_FORMAT2(testing::IsSubstring, "other failure", gtest_failures.GetTestPartResult(2).message()); } TEST_F(NoFatalFailureTest, MessageIsStreamable) { TestPartResultArray gtest_failures; { ScopedFakeTestPartResultReporter gtest_reporter(>est_failures); EXPECT_NO_FATAL_FAILURE(FAIL() << "foo") << "my message"; } ASSERT_EQ(2, gtest_failures.size()); EXPECT_EQ(TestPartResult::kNonFatalFailure, gtest_failures.GetTestPartResult(0).type()); EXPECT_EQ(TestPartResult::kNonFatalFailure, gtest_failures.GetTestPartResult(1).type()); EXPECT_PRED_FORMAT2(testing::IsSubstring, "foo", gtest_failures.GetTestPartResult(0).message()); EXPECT_PRED_FORMAT2(testing::IsSubstring, "my message", gtest_failures.GetTestPartResult(1).message()); } // Tests non-string assertions. // Tests EqFailure(), used for implementing *EQ* assertions. TEST(AssertionTest, EqFailure) { const String foo_val("5"), bar_val("6"); const String msg1( EqFailure("foo", "bar", foo_val, bar_val, false) .failure_message()); EXPECT_STREQ( "Value of: bar\n" " Actual: 6\n" "Expected: foo\n" "Which is: 5", msg1.c_str()); const String msg2( EqFailure("foo", "6", foo_val, bar_val, false) .failure_message()); EXPECT_STREQ( "Value of: 6\n" "Expected: foo\n" "Which is: 5", msg2.c_str()); const String msg3( EqFailure("5", "bar", foo_val, bar_val, false) .failure_message()); EXPECT_STREQ( "Value of: bar\n" " Actual: 6\n" "Expected: 5", msg3.c_str()); const String msg4( EqFailure("5", "6", foo_val, bar_val, false).failure_message()); EXPECT_STREQ( "Value of: 6\n" "Expected: 5", msg4.c_str()); const String msg5( EqFailure("foo", "bar", String("\"x\""), String("\"y\""), true).failure_message()); EXPECT_STREQ( "Value of: bar\n" " Actual: \"y\"\n" "Expected: foo (ignoring case)\n" "Which is: \"x\"", msg5.c_str()); } // Tests AppendUserMessage(), used for implementing the *EQ* macros. TEST(AssertionTest, AppendUserMessage) { const String foo("foo"); Message msg; EXPECT_STREQ("foo", AppendUserMessage(foo, msg).c_str()); msg << "bar"; EXPECT_STREQ("foo\nbar", AppendUserMessage(foo, msg).c_str()); } #ifdef __BORLANDC__ // Silences warnings: "Condition is always true", "Unreachable code" # pragma option push -w-ccc -w-rch #endif // Tests ASSERT_TRUE. TEST(AssertionTest, ASSERT_TRUE) { ASSERT_TRUE(2 > 1); // NOLINT EXPECT_FATAL_FAILURE(ASSERT_TRUE(2 < 1), "2 < 1"); } // Tests ASSERT_TRUE(predicate) for predicates returning AssertionResult. TEST(AssertionTest, AssertTrueWithAssertionResult) { ASSERT_TRUE(ResultIsEven(2)); #ifndef __BORLANDC__ // ICE's in C++Builder. EXPECT_FATAL_FAILURE(ASSERT_TRUE(ResultIsEven(3)), "Value of: ResultIsEven(3)\n" " Actual: false (3 is odd)\n" "Expected: true"); #endif ASSERT_TRUE(ResultIsEvenNoExplanation(2)); EXPECT_FATAL_FAILURE(ASSERT_TRUE(ResultIsEvenNoExplanation(3)), "Value of: ResultIsEvenNoExplanation(3)\n" " Actual: false (3 is odd)\n" "Expected: true"); } // Tests ASSERT_FALSE. TEST(AssertionTest, ASSERT_FALSE) { ASSERT_FALSE(2 < 1); // NOLINT EXPECT_FATAL_FAILURE(ASSERT_FALSE(2 > 1), "Value of: 2 > 1\n" " Actual: true\n" "Expected: false"); } // Tests ASSERT_FALSE(predicate) for predicates returning AssertionResult. TEST(AssertionTest, AssertFalseWithAssertionResult) { ASSERT_FALSE(ResultIsEven(3)); #ifndef __BORLANDC__ // ICE's in C++Builder. EXPECT_FATAL_FAILURE(ASSERT_FALSE(ResultIsEven(2)), "Value of: ResultIsEven(2)\n" " Actual: true (2 is even)\n" "Expected: false"); #endif ASSERT_FALSE(ResultIsEvenNoExplanation(3)); EXPECT_FATAL_FAILURE(ASSERT_FALSE(ResultIsEvenNoExplanation(2)), "Value of: ResultIsEvenNoExplanation(2)\n" " Actual: true\n" "Expected: false"); } #ifdef __BORLANDC__ // Restores warnings after previous "#pragma option push" supressed them # pragma option pop #endif // Tests using ASSERT_EQ on double values. The purpose is to make // sure that the specialization we did for integer and anonymous enums // isn't used for double arguments. TEST(ExpectTest, ASSERT_EQ_Double) { // A success. ASSERT_EQ(5.6, 5.6); // A failure. EXPECT_FATAL_FAILURE(ASSERT_EQ(5.1, 5.2), "5.1"); } // Tests ASSERT_EQ. TEST(AssertionTest, ASSERT_EQ) { ASSERT_EQ(5, 2 + 3); EXPECT_FATAL_FAILURE(ASSERT_EQ(5, 2*3), "Value of: 2*3\n" " Actual: 6\n" "Expected: 5"); } // Tests ASSERT_EQ(NULL, pointer). #if GTEST_CAN_COMPARE_NULL TEST(AssertionTest, ASSERT_EQ_NULL) { // A success. const char* p = NULL; // Some older GCC versions may issue a spurious waring in this or the next // assertion statement. This warning should not be suppressed with // static_cast since the test verifies the ability to use bare NULL as the // expected parameter to the macro. ASSERT_EQ(NULL, p); // A failure. static int n = 0; EXPECT_FATAL_FAILURE(ASSERT_EQ(NULL, &n), "Value of: &n\n"); } #endif // GTEST_CAN_COMPARE_NULL // Tests ASSERT_EQ(0, non_pointer). Since the literal 0 can be // treated as a null pointer by the compiler, we need to make sure // that ASSERT_EQ(0, non_pointer) isn't interpreted by Google Test as // ASSERT_EQ(static_cast(NULL), non_pointer). TEST(ExpectTest, ASSERT_EQ_0) { int n = 0; // A success. ASSERT_EQ(0, n); // A failure. EXPECT_FATAL_FAILURE(ASSERT_EQ(0, 5.6), "Expected: 0"); } // Tests ASSERT_NE. TEST(AssertionTest, ASSERT_NE) { ASSERT_NE(6, 7); EXPECT_FATAL_FAILURE(ASSERT_NE('a', 'a'), "Expected: ('a') != ('a'), " "actual: 'a' (97, 0x61) vs 'a' (97, 0x61)"); } // Tests ASSERT_LE. TEST(AssertionTest, ASSERT_LE) { ASSERT_LE(2, 3); ASSERT_LE(2, 2); EXPECT_FATAL_FAILURE(ASSERT_LE(2, 0), "Expected: (2) <= (0), actual: 2 vs 0"); } // Tests ASSERT_LT. TEST(AssertionTest, ASSERT_LT) { ASSERT_LT(2, 3); EXPECT_FATAL_FAILURE(ASSERT_LT(2, 2), "Expected: (2) < (2), actual: 2 vs 2"); } // Tests ASSERT_GE. TEST(AssertionTest, ASSERT_GE) { ASSERT_GE(2, 1); ASSERT_GE(2, 2); EXPECT_FATAL_FAILURE(ASSERT_GE(2, 3), "Expected: (2) >= (3), actual: 2 vs 3"); } // Tests ASSERT_GT. TEST(AssertionTest, ASSERT_GT) { ASSERT_GT(2, 1); EXPECT_FATAL_FAILURE(ASSERT_GT(2, 2), "Expected: (2) > (2), actual: 2 vs 2"); } #if GTEST_HAS_EXCEPTIONS void ThrowNothing() {} // Tests ASSERT_THROW. TEST(AssertionTest, ASSERT_THROW) { ASSERT_THROW(ThrowAnInteger(), int); # ifndef __BORLANDC__ // ICE's in C++Builder 2007 and 2009. EXPECT_FATAL_FAILURE( ASSERT_THROW(ThrowAnInteger(), bool), "Expected: ThrowAnInteger() throws an exception of type bool.\n" " Actual: it throws a different type."); # endif EXPECT_FATAL_FAILURE( ASSERT_THROW(ThrowNothing(), bool), "Expected: ThrowNothing() throws an exception of type bool.\n" " Actual: it throws nothing."); } // Tests ASSERT_NO_THROW. TEST(AssertionTest, ASSERT_NO_THROW) { ASSERT_NO_THROW(ThrowNothing()); EXPECT_FATAL_FAILURE(ASSERT_NO_THROW(ThrowAnInteger()), "Expected: ThrowAnInteger() doesn't throw an exception." "\n Actual: it throws."); } // Tests ASSERT_ANY_THROW. TEST(AssertionTest, ASSERT_ANY_THROW) { ASSERT_ANY_THROW(ThrowAnInteger()); EXPECT_FATAL_FAILURE( ASSERT_ANY_THROW(ThrowNothing()), "Expected: ThrowNothing() throws an exception.\n" " Actual: it doesn't."); } #endif // GTEST_HAS_EXCEPTIONS // Makes sure we deal with the precedence of <<. This test should // compile. TEST(AssertionTest, AssertPrecedence) { ASSERT_EQ(1 < 2, true); bool false_value = false; ASSERT_EQ(true && false_value, false); } // A subroutine used by the following test. void TestEq1(int x) { ASSERT_EQ(1, x); } // Tests calling a test subroutine that's not part of a fixture. TEST(AssertionTest, NonFixtureSubroutine) { EXPECT_FATAL_FAILURE(TestEq1(2), "Value of: x"); } // An uncopyable class. class Uncopyable { public: explicit Uncopyable(int a_value) : value_(a_value) {} int value() const { return value_; } bool operator==(const Uncopyable& rhs) const { return value() == rhs.value(); } private: // This constructor deliberately has no implementation, as we don't // want this class to be copyable. Uncopyable(const Uncopyable&); // NOLINT int value_; }; ::std::ostream& operator<<(::std::ostream& os, const Uncopyable& value) { return os << value.value(); } bool IsPositiveUncopyable(const Uncopyable& x) { return x.value() > 0; } // A subroutine used by the following test. void TestAssertNonPositive() { Uncopyable y(-1); ASSERT_PRED1(IsPositiveUncopyable, y); } // A subroutine used by the following test. void TestAssertEqualsUncopyable() { Uncopyable x(5); Uncopyable y(-1); ASSERT_EQ(x, y); } // Tests that uncopyable objects can be used in assertions. TEST(AssertionTest, AssertWorksWithUncopyableObject) { Uncopyable x(5); ASSERT_PRED1(IsPositiveUncopyable, x); ASSERT_EQ(x, x); EXPECT_FATAL_FAILURE(TestAssertNonPositive(), "IsPositiveUncopyable(y) evaluates to false, where\ny evaluates to -1"); EXPECT_FATAL_FAILURE(TestAssertEqualsUncopyable(), "Value of: y\n Actual: -1\nExpected: x\nWhich is: 5"); } // Tests that uncopyable objects can be used in expects. TEST(AssertionTest, ExpectWorksWithUncopyableObject) { Uncopyable x(5); EXPECT_PRED1(IsPositiveUncopyable, x); Uncopyable y(-1); EXPECT_NONFATAL_FAILURE(EXPECT_PRED1(IsPositiveUncopyable, y), "IsPositiveUncopyable(y) evaluates to false, where\ny evaluates to -1"); EXPECT_EQ(x, x); EXPECT_NONFATAL_FAILURE(EXPECT_EQ(x, y), "Value of: y\n Actual: -1\nExpected: x\nWhich is: 5"); } enum NamedEnum { kE1 = 0, kE2 = 1 }; TEST(AssertionTest, NamedEnum) { EXPECT_EQ(kE1, kE1); EXPECT_LT(kE1, kE2); EXPECT_NONFATAL_FAILURE(EXPECT_EQ(kE1, kE2), "Which is: 0"); EXPECT_NONFATAL_FAILURE(EXPECT_EQ(kE1, kE2), "Actual: 1"); } // The version of gcc used in XCode 2.2 has a bug and doesn't allow // anonymous enums in assertions. Therefore the following test is not // done on Mac. // Sun Studio and HP aCC also reject this code. #if !GTEST_OS_MAC && !defined(__SUNPRO_CC) && !defined(__HP_aCC) // Tests using assertions with anonymous enums. enum { kCaseA = -1, # if GTEST_OS_LINUX // We want to test the case where the size of the anonymous enum is // larger than sizeof(int), to make sure our implementation of the // assertions doesn't truncate the enums. However, MSVC // (incorrectly) doesn't allow an enum value to exceed the range of // an int, so this has to be conditionally compiled. // // On Linux, kCaseB and kCaseA have the same value when truncated to // int size. We want to test whether this will confuse the // assertions. kCaseB = testing::internal::kMaxBiggestInt, # else kCaseB = INT_MAX, # endif // GTEST_OS_LINUX kCaseC = 42 }; TEST(AssertionTest, AnonymousEnum) { # if GTEST_OS_LINUX EXPECT_EQ(static_cast(kCaseA), static_cast(kCaseB)); # endif // GTEST_OS_LINUX EXPECT_EQ(kCaseA, kCaseA); EXPECT_NE(kCaseA, kCaseB); EXPECT_LT(kCaseA, kCaseB); EXPECT_LE(kCaseA, kCaseB); EXPECT_GT(kCaseB, kCaseA); EXPECT_GE(kCaseA, kCaseA); EXPECT_NONFATAL_FAILURE(EXPECT_GE(kCaseA, kCaseB), "(kCaseA) >= (kCaseB)"); EXPECT_NONFATAL_FAILURE(EXPECT_GE(kCaseA, kCaseC), "-1 vs 42"); ASSERT_EQ(kCaseA, kCaseA); ASSERT_NE(kCaseA, kCaseB); ASSERT_LT(kCaseA, kCaseB); ASSERT_LE(kCaseA, kCaseB); ASSERT_GT(kCaseB, kCaseA); ASSERT_GE(kCaseA, kCaseA); # ifndef __BORLANDC__ // ICE's in C++Builder. EXPECT_FATAL_FAILURE(ASSERT_EQ(kCaseA, kCaseB), "Value of: kCaseB"); EXPECT_FATAL_FAILURE(ASSERT_EQ(kCaseA, kCaseC), "Actual: 42"); # endif EXPECT_FATAL_FAILURE(ASSERT_EQ(kCaseA, kCaseC), "Which is: -1"); } #endif // !GTEST_OS_MAC && !defined(__SUNPRO_CC) #if GTEST_OS_WINDOWS static HRESULT UnexpectedHRESULTFailure() { return E_UNEXPECTED; } static HRESULT OkHRESULTSuccess() { return S_OK; } static HRESULT FalseHRESULTSuccess() { return S_FALSE; } // HRESULT assertion tests test both zero and non-zero // success codes as well as failure message for each. // // Windows CE doesn't support message texts. TEST(HRESULTAssertionTest, EXPECT_HRESULT_SUCCEEDED) { EXPECT_HRESULT_SUCCEEDED(S_OK); EXPECT_HRESULT_SUCCEEDED(S_FALSE); EXPECT_NONFATAL_FAILURE(EXPECT_HRESULT_SUCCEEDED(UnexpectedHRESULTFailure()), "Expected: (UnexpectedHRESULTFailure()) succeeds.\n" " Actual: 0x8000FFFF"); } TEST(HRESULTAssertionTest, ASSERT_HRESULT_SUCCEEDED) { ASSERT_HRESULT_SUCCEEDED(S_OK); ASSERT_HRESULT_SUCCEEDED(S_FALSE); EXPECT_FATAL_FAILURE(ASSERT_HRESULT_SUCCEEDED(UnexpectedHRESULTFailure()), "Expected: (UnexpectedHRESULTFailure()) succeeds.\n" " Actual: 0x8000FFFF"); } TEST(HRESULTAssertionTest, EXPECT_HRESULT_FAILED) { EXPECT_HRESULT_FAILED(E_UNEXPECTED); EXPECT_NONFATAL_FAILURE(EXPECT_HRESULT_FAILED(OkHRESULTSuccess()), "Expected: (OkHRESULTSuccess()) fails.\n" " Actual: 0x00000000"); EXPECT_NONFATAL_FAILURE(EXPECT_HRESULT_FAILED(FalseHRESULTSuccess()), "Expected: (FalseHRESULTSuccess()) fails.\n" " Actual: 0x00000001"); } TEST(HRESULTAssertionTest, ASSERT_HRESULT_FAILED) { ASSERT_HRESULT_FAILED(E_UNEXPECTED); # ifndef __BORLANDC__ // ICE's in C++Builder 2007 and 2009. EXPECT_FATAL_FAILURE(ASSERT_HRESULT_FAILED(OkHRESULTSuccess()), "Expected: (OkHRESULTSuccess()) fails.\n" " Actual: 0x00000000"); # endif EXPECT_FATAL_FAILURE(ASSERT_HRESULT_FAILED(FalseHRESULTSuccess()), "Expected: (FalseHRESULTSuccess()) fails.\n" " Actual: 0x00000001"); } // Tests that streaming to the HRESULT macros works. TEST(HRESULTAssertionTest, Streaming) { EXPECT_HRESULT_SUCCEEDED(S_OK) << "unexpected failure"; ASSERT_HRESULT_SUCCEEDED(S_OK) << "unexpected failure"; EXPECT_HRESULT_FAILED(E_UNEXPECTED) << "unexpected failure"; ASSERT_HRESULT_FAILED(E_UNEXPECTED) << "unexpected failure"; EXPECT_NONFATAL_FAILURE( EXPECT_HRESULT_SUCCEEDED(E_UNEXPECTED) << "expected failure", "expected failure"); # ifndef __BORLANDC__ // ICE's in C++Builder 2007 and 2009. EXPECT_FATAL_FAILURE( ASSERT_HRESULT_SUCCEEDED(E_UNEXPECTED) << "expected failure", "expected failure"); # endif EXPECT_NONFATAL_FAILURE( EXPECT_HRESULT_FAILED(S_OK) << "expected failure", "expected failure"); EXPECT_FATAL_FAILURE( ASSERT_HRESULT_FAILED(S_OK) << "expected failure", "expected failure"); } #endif // GTEST_OS_WINDOWS #ifdef __BORLANDC__ // Silences warnings: "Condition is always true", "Unreachable code" # pragma option push -w-ccc -w-rch #endif // Tests that the assertion macros behave like single statements. TEST(AssertionSyntaxTest, BasicAssertionsBehavesLikeSingleStatement) { if (AlwaysFalse()) ASSERT_TRUE(false) << "This should never be executed; " "It's a compilation test only."; if (AlwaysTrue()) EXPECT_FALSE(false); else ; // NOLINT if (AlwaysFalse()) ASSERT_LT(1, 3); if (AlwaysFalse()) ; // NOLINT else EXPECT_GT(3, 2) << ""; } #if GTEST_HAS_EXCEPTIONS // Tests that the compiler will not complain about unreachable code in the // EXPECT_THROW/EXPECT_ANY_THROW/EXPECT_NO_THROW macros. TEST(ExpectThrowTest, DoesNotGenerateUnreachableCodeWarning) { int n = 0; EXPECT_THROW(throw 1, int); EXPECT_NONFATAL_FAILURE(EXPECT_THROW(n++, int), ""); EXPECT_NONFATAL_FAILURE(EXPECT_THROW(throw 1, const char*), ""); EXPECT_NO_THROW(n++); EXPECT_NONFATAL_FAILURE(EXPECT_NO_THROW(throw 1), ""); EXPECT_ANY_THROW(throw 1); EXPECT_NONFATAL_FAILURE(EXPECT_ANY_THROW(n++), ""); } TEST(AssertionSyntaxTest, ExceptionAssertionsBehavesLikeSingleStatement) { if (AlwaysFalse()) EXPECT_THROW(ThrowNothing(), bool); if (AlwaysTrue()) EXPECT_THROW(ThrowAnInteger(), int); else ; // NOLINT if (AlwaysFalse()) EXPECT_NO_THROW(ThrowAnInteger()); if (AlwaysTrue()) EXPECT_NO_THROW(ThrowNothing()); else ; // NOLINT if (AlwaysFalse()) EXPECT_ANY_THROW(ThrowNothing()); if (AlwaysTrue()) EXPECT_ANY_THROW(ThrowAnInteger()); else ; // NOLINT } #endif // GTEST_HAS_EXCEPTIONS TEST(AssertionSyntaxTest, NoFatalFailureAssertionsBehavesLikeSingleStatement) { if (AlwaysFalse()) EXPECT_NO_FATAL_FAILURE(FAIL()) << "This should never be executed. " << "It's a compilation test only."; else ; // NOLINT if (AlwaysFalse()) ASSERT_NO_FATAL_FAILURE(FAIL()) << ""; else ; // NOLINT if (AlwaysTrue()) EXPECT_NO_FATAL_FAILURE(SUCCEED()); else ; // NOLINT if (AlwaysFalse()) ; // NOLINT else ASSERT_NO_FATAL_FAILURE(SUCCEED()); } // Tests that the assertion macros work well with switch statements. TEST(AssertionSyntaxTest, WorksWithSwitch) { switch (0) { case 1: break; default: ASSERT_TRUE(true); } switch (0) case 0: EXPECT_FALSE(false) << "EXPECT_FALSE failed in switch case"; // Binary assertions are implemented using a different code path // than the Boolean assertions. Hence we test them separately. switch (0) { case 1: default: ASSERT_EQ(1, 1) << "ASSERT_EQ failed in default switch handler"; } switch (0) case 0: EXPECT_NE(1, 2); } #if GTEST_HAS_EXCEPTIONS void ThrowAString() { throw "String"; } // Test that the exception assertion macros compile and work with const // type qualifier. TEST(AssertionSyntaxTest, WorksWithConst) { ASSERT_THROW(ThrowAString(), const char*); EXPECT_THROW(ThrowAString(), const char*); } #endif // GTEST_HAS_EXCEPTIONS } // namespace namespace testing { // Tests that Google Test tracks SUCCEED*. TEST(SuccessfulAssertionTest, SUCCEED) { SUCCEED(); SUCCEED() << "OK"; EXPECT_EQ(2, GetUnitTestImpl()->current_test_result()->total_part_count()); } // Tests that Google Test doesn't track successful EXPECT_*. TEST(SuccessfulAssertionTest, EXPECT) { EXPECT_TRUE(true); EXPECT_EQ(0, GetUnitTestImpl()->current_test_result()->total_part_count()); } // Tests that Google Test doesn't track successful EXPECT_STR*. TEST(SuccessfulAssertionTest, EXPECT_STR) { EXPECT_STREQ("", ""); EXPECT_EQ(0, GetUnitTestImpl()->current_test_result()->total_part_count()); } // Tests that Google Test doesn't track successful ASSERT_*. TEST(SuccessfulAssertionTest, ASSERT) { ASSERT_TRUE(true); EXPECT_EQ(0, GetUnitTestImpl()->current_test_result()->total_part_count()); } // Tests that Google Test doesn't track successful ASSERT_STR*. TEST(SuccessfulAssertionTest, ASSERT_STR) { ASSERT_STREQ("", ""); EXPECT_EQ(0, GetUnitTestImpl()->current_test_result()->total_part_count()); } } // namespace testing namespace { // Tests EXPECT_TRUE. TEST(ExpectTest, EXPECT_TRUE) { EXPECT_TRUE(2 > 1); // NOLINT EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(2 < 1), "Value of: 2 < 1\n" " Actual: false\n" "Expected: true"); EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(2 > 3), "2 > 3"); } // Tests EXPECT_TRUE(predicate) for predicates returning AssertionResult. TEST(ExpectTest, ExpectTrueWithAssertionResult) { EXPECT_TRUE(ResultIsEven(2)); EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(ResultIsEven(3)), "Value of: ResultIsEven(3)\n" " Actual: false (3 is odd)\n" "Expected: true"); EXPECT_TRUE(ResultIsEvenNoExplanation(2)); EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(ResultIsEvenNoExplanation(3)), "Value of: ResultIsEvenNoExplanation(3)\n" " Actual: false (3 is odd)\n" "Expected: true"); } // Tests EXPECT_FALSE. TEST(ExpectTest, EXPECT_FALSE) { EXPECT_FALSE(2 < 1); // NOLINT EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(2 > 1), "Value of: 2 > 1\n" " Actual: true\n" "Expected: false"); EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(2 < 3), "2 < 3"); } // Tests EXPECT_FALSE(predicate) for predicates returning AssertionResult. TEST(ExpectTest, ExpectFalseWithAssertionResult) { EXPECT_FALSE(ResultIsEven(3)); EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(ResultIsEven(2)), "Value of: ResultIsEven(2)\n" " Actual: true (2 is even)\n" "Expected: false"); EXPECT_FALSE(ResultIsEvenNoExplanation(3)); EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(ResultIsEvenNoExplanation(2)), "Value of: ResultIsEvenNoExplanation(2)\n" " Actual: true\n" "Expected: false"); } #ifdef __BORLANDC__ // Restores warnings after previous "#pragma option push" supressed them # pragma option pop #endif // Tests EXPECT_EQ. TEST(ExpectTest, EXPECT_EQ) { EXPECT_EQ(5, 2 + 3); EXPECT_NONFATAL_FAILURE(EXPECT_EQ(5, 2*3), "Value of: 2*3\n" " Actual: 6\n" "Expected: 5"); EXPECT_NONFATAL_FAILURE(EXPECT_EQ(5, 2 - 3), "2 - 3"); } // Tests using EXPECT_EQ on double values. The purpose is to make // sure that the specialization we did for integer and anonymous enums // isn't used for double arguments. TEST(ExpectTest, EXPECT_EQ_Double) { // A success. EXPECT_EQ(5.6, 5.6); // A failure. EXPECT_NONFATAL_FAILURE(EXPECT_EQ(5.1, 5.2), "5.1"); } #if GTEST_CAN_COMPARE_NULL // Tests EXPECT_EQ(NULL, pointer). TEST(ExpectTest, EXPECT_EQ_NULL) { // A success. const char* p = NULL; // Some older GCC versions may issue a spurious warning in this or the next // assertion statement. This warning should not be suppressed with // static_cast since the test verifies the ability to use bare NULL as the // expected parameter to the macro. EXPECT_EQ(NULL, p); // A failure. int n = 0; EXPECT_NONFATAL_FAILURE(EXPECT_EQ(NULL, &n), "Value of: &n\n"); } #endif // GTEST_CAN_COMPARE_NULL // Tests EXPECT_EQ(0, non_pointer). Since the literal 0 can be // treated as a null pointer by the compiler, we need to make sure // that EXPECT_EQ(0, non_pointer) isn't interpreted by Google Test as // EXPECT_EQ(static_cast(NULL), non_pointer). TEST(ExpectTest, EXPECT_EQ_0) { int n = 0; // A success. EXPECT_EQ(0, n); // A failure. EXPECT_NONFATAL_FAILURE(EXPECT_EQ(0, 5.6), "Expected: 0"); } // Tests EXPECT_NE. TEST(ExpectTest, EXPECT_NE) { EXPECT_NE(6, 7); EXPECT_NONFATAL_FAILURE(EXPECT_NE('a', 'a'), "Expected: ('a') != ('a'), " "actual: 'a' (97, 0x61) vs 'a' (97, 0x61)"); EXPECT_NONFATAL_FAILURE(EXPECT_NE(2, 2), "2"); char* const p0 = NULL; EXPECT_NONFATAL_FAILURE(EXPECT_NE(p0, p0), "p0"); // Only way to get the Nokia compiler to compile the cast // is to have a separate void* variable first. Putting // the two casts on the same line doesn't work, neither does // a direct C-style to char*. void* pv1 = (void*)0x1234; // NOLINT char* const p1 = reinterpret_cast(pv1); EXPECT_NONFATAL_FAILURE(EXPECT_NE(p1, p1), "p1"); } // Tests EXPECT_LE. TEST(ExpectTest, EXPECT_LE) { EXPECT_LE(2, 3); EXPECT_LE(2, 2); EXPECT_NONFATAL_FAILURE(EXPECT_LE(2, 0), "Expected: (2) <= (0), actual: 2 vs 0"); EXPECT_NONFATAL_FAILURE(EXPECT_LE(1.1, 0.9), "(1.1) <= (0.9)"); } // Tests EXPECT_LT. TEST(ExpectTest, EXPECT_LT) { EXPECT_LT(2, 3); EXPECT_NONFATAL_FAILURE(EXPECT_LT(2, 2), "Expected: (2) < (2), actual: 2 vs 2"); EXPECT_NONFATAL_FAILURE(EXPECT_LT(2, 1), "(2) < (1)"); } // Tests EXPECT_GE. TEST(ExpectTest, EXPECT_GE) { EXPECT_GE(2, 1); EXPECT_GE(2, 2); EXPECT_NONFATAL_FAILURE(EXPECT_GE(2, 3), "Expected: (2) >= (3), actual: 2 vs 3"); EXPECT_NONFATAL_FAILURE(EXPECT_GE(0.9, 1.1), "(0.9) >= (1.1)"); } // Tests EXPECT_GT. TEST(ExpectTest, EXPECT_GT) { EXPECT_GT(2, 1); EXPECT_NONFATAL_FAILURE(EXPECT_GT(2, 2), "Expected: (2) > (2), actual: 2 vs 2"); EXPECT_NONFATAL_FAILURE(EXPECT_GT(2, 3), "(2) > (3)"); } #if GTEST_HAS_EXCEPTIONS // Tests EXPECT_THROW. TEST(ExpectTest, EXPECT_THROW) { EXPECT_THROW(ThrowAnInteger(), int); EXPECT_NONFATAL_FAILURE(EXPECT_THROW(ThrowAnInteger(), bool), "Expected: ThrowAnInteger() throws an exception of " "type bool.\n Actual: it throws a different type."); EXPECT_NONFATAL_FAILURE( EXPECT_THROW(ThrowNothing(), bool), "Expected: ThrowNothing() throws an exception of type bool.\n" " Actual: it throws nothing."); } // Tests EXPECT_NO_THROW. TEST(ExpectTest, EXPECT_NO_THROW) { EXPECT_NO_THROW(ThrowNothing()); EXPECT_NONFATAL_FAILURE(EXPECT_NO_THROW(ThrowAnInteger()), "Expected: ThrowAnInteger() doesn't throw an " "exception.\n Actual: it throws."); } // Tests EXPECT_ANY_THROW. TEST(ExpectTest, EXPECT_ANY_THROW) { EXPECT_ANY_THROW(ThrowAnInteger()); EXPECT_NONFATAL_FAILURE( EXPECT_ANY_THROW(ThrowNothing()), "Expected: ThrowNothing() throws an exception.\n" " Actual: it doesn't."); } #endif // GTEST_HAS_EXCEPTIONS // Make sure we deal with the precedence of <<. TEST(ExpectTest, ExpectPrecedence) { EXPECT_EQ(1 < 2, true); EXPECT_NONFATAL_FAILURE(EXPECT_EQ(true, true && false), "Value of: true && false"); } // Tests the StreamableToString() function. // Tests using StreamableToString() on a scalar. TEST(StreamableToStringTest, Scalar) { EXPECT_STREQ("5", StreamableToString(5).c_str()); } // Tests using StreamableToString() on a non-char pointer. TEST(StreamableToStringTest, Pointer) { int n = 0; int* p = &n; EXPECT_STRNE("(null)", StreamableToString(p).c_str()); } // Tests using StreamableToString() on a NULL non-char pointer. TEST(StreamableToStringTest, NullPointer) { int* p = NULL; EXPECT_STREQ("(null)", StreamableToString(p).c_str()); } // Tests using StreamableToString() on a C string. TEST(StreamableToStringTest, CString) { EXPECT_STREQ("Foo", StreamableToString("Foo").c_str()); } // Tests using StreamableToString() on a NULL C string. TEST(StreamableToStringTest, NullCString) { char* p = NULL; EXPECT_STREQ("(null)", StreamableToString(p).c_str()); } // Tests using streamable values as assertion messages. // Tests using std::string as an assertion message. TEST(StreamableTest, string) { static const std::string str( "This failure message is a std::string, and is expected."); EXPECT_FATAL_FAILURE(FAIL() << str, str.c_str()); } // Tests that we can output strings containing embedded NULs. // Limited to Linux because we can only do this with std::string's. TEST(StreamableTest, stringWithEmbeddedNUL) { static const char char_array_with_nul[] = "Here's a NUL\0 and some more string"; static const std::string string_with_nul(char_array_with_nul, sizeof(char_array_with_nul) - 1); // drops the trailing NUL EXPECT_FATAL_FAILURE(FAIL() << string_with_nul, "Here's a NUL\\0 and some more string"); } // Tests that we can output a NUL char. TEST(StreamableTest, NULChar) { EXPECT_FATAL_FAILURE({ // NOLINT FAIL() << "A NUL" << '\0' << " and some more string"; }, "A NUL\\0 and some more string"); } // Tests using int as an assertion message. TEST(StreamableTest, int) { EXPECT_FATAL_FAILURE(FAIL() << 900913, "900913"); } // Tests using NULL char pointer as an assertion message. // // In MSVC, streaming a NULL char * causes access violation. Google Test // implemented a workaround (substituting "(null)" for NULL). This // tests whether the workaround works. TEST(StreamableTest, NullCharPtr) { EXPECT_FATAL_FAILURE(FAIL() << static_cast(NULL), "(null)"); } // Tests that basic IO manipulators (endl, ends, and flush) can be // streamed to testing::Message. TEST(StreamableTest, BasicIoManip) { EXPECT_FATAL_FAILURE({ // NOLINT FAIL() << "Line 1." << std::endl << "A NUL char " << std::ends << std::flush << " in line 2."; }, "Line 1.\nA NUL char \\0 in line 2."); } // Tests the macros that haven't been covered so far. void AddFailureHelper(bool* aborted) { *aborted = true; ADD_FAILURE() << "Failure"; *aborted = false; } // Tests ADD_FAILURE. TEST(MacroTest, ADD_FAILURE) { bool aborted = true; EXPECT_NONFATAL_FAILURE(AddFailureHelper(&aborted), "Failure"); EXPECT_FALSE(aborted); } // Tests ADD_FAILURE_AT. TEST(MacroTest, ADD_FAILURE_AT) { // Verifies that ADD_FAILURE_AT does generate a nonfatal failure and // the failure message contains the user-streamed part. EXPECT_NONFATAL_FAILURE(ADD_FAILURE_AT("foo.cc", 42) << "Wrong!", "Wrong!"); // Verifies that the user-streamed part is optional. EXPECT_NONFATAL_FAILURE(ADD_FAILURE_AT("foo.cc", 42), "Failed"); // Unfortunately, we cannot verify that the failure message contains // the right file path and line number the same way, as // EXPECT_NONFATAL_FAILURE() doesn't get to see the file path and // line number. Instead, we do that in gtest_output_test_.cc. } // Tests FAIL. TEST(MacroTest, FAIL) { EXPECT_FATAL_FAILURE(FAIL(), "Failed"); EXPECT_FATAL_FAILURE(FAIL() << "Intentional failure.", "Intentional failure."); } // Tests SUCCEED TEST(MacroTest, SUCCEED) { SUCCEED(); SUCCEED() << "Explicit success."; } // Tests for EXPECT_EQ() and ASSERT_EQ(). // // These tests fail *intentionally*, s.t. the failure messages can be // generated and tested. // // We have different tests for different argument types. // Tests using bool values in {EXPECT|ASSERT}_EQ. TEST(EqAssertionTest, Bool) { EXPECT_EQ(true, true); EXPECT_FATAL_FAILURE({ bool false_value = false; ASSERT_EQ(false_value, true); }, "Value of: true"); } // Tests using int values in {EXPECT|ASSERT}_EQ. TEST(EqAssertionTest, Int) { ASSERT_EQ(32, 32); EXPECT_NONFATAL_FAILURE(EXPECT_EQ(32, 33), "33"); } // Tests using time_t values in {EXPECT|ASSERT}_EQ. TEST(EqAssertionTest, Time_T) { EXPECT_EQ(static_cast(0), static_cast(0)); EXPECT_FATAL_FAILURE(ASSERT_EQ(static_cast(0), static_cast(1234)), "1234"); } // Tests using char values in {EXPECT|ASSERT}_EQ. TEST(EqAssertionTest, Char) { ASSERT_EQ('z', 'z'); const char ch = 'b'; EXPECT_NONFATAL_FAILURE(EXPECT_EQ('\0', ch), "ch"); EXPECT_NONFATAL_FAILURE(EXPECT_EQ('a', ch), "ch"); } // Tests using wchar_t values in {EXPECT|ASSERT}_EQ. TEST(EqAssertionTest, WideChar) { EXPECT_EQ(L'b', L'b'); EXPECT_NONFATAL_FAILURE(EXPECT_EQ(L'\0', L'x'), "Value of: L'x'\n" " Actual: L'x' (120, 0x78)\n" "Expected: L'\0'\n" "Which is: L'\0' (0, 0x0)"); static wchar_t wchar; wchar = L'b'; EXPECT_NONFATAL_FAILURE(EXPECT_EQ(L'a', wchar), "wchar"); wchar = 0x8119; EXPECT_FATAL_FAILURE(ASSERT_EQ(static_cast(0x8120), wchar), "Value of: wchar"); } // Tests using ::std::string values in {EXPECT|ASSERT}_EQ. TEST(EqAssertionTest, StdString) { // Compares a const char* to an std::string that has identical // content. ASSERT_EQ("Test", ::std::string("Test")); // Compares two identical std::strings. static const ::std::string str1("A * in the middle"); static const ::std::string str2(str1); EXPECT_EQ(str1, str2); // Compares a const char* to an std::string that has different // content EXPECT_NONFATAL_FAILURE(EXPECT_EQ("Test", ::std::string("test")), "::std::string(\"test\")"); // Compares an std::string to a char* that has different content. char* const p1 = const_cast("foo"); EXPECT_NONFATAL_FAILURE(EXPECT_EQ(::std::string("bar"), p1), "p1"); // Compares two std::strings that have different contents, one of // which having a NUL character in the middle. This should fail. static ::std::string str3(str1); str3.at(2) = '\0'; EXPECT_FATAL_FAILURE(ASSERT_EQ(str1, str3), "Value of: str3\n" " Actual: \"A \\0 in the middle\""); } #if GTEST_HAS_STD_WSTRING // Tests using ::std::wstring values in {EXPECT|ASSERT}_EQ. TEST(EqAssertionTest, StdWideString) { // Compares two identical std::wstrings. const ::std::wstring wstr1(L"A * in the middle"); const ::std::wstring wstr2(wstr1); ASSERT_EQ(wstr1, wstr2); // Compares an std::wstring to a const wchar_t* that has identical // content. const wchar_t kTestX8119[] = { 'T', 'e', 's', 't', 0x8119, '\0' }; EXPECT_EQ(::std::wstring(kTestX8119), kTestX8119); // Compares an std::wstring to a const wchar_t* that has different // content. const wchar_t kTestX8120[] = { 'T', 'e', 's', 't', 0x8120, '\0' }; EXPECT_NONFATAL_FAILURE({ // NOLINT EXPECT_EQ(::std::wstring(kTestX8119), kTestX8120); }, "kTestX8120"); // Compares two std::wstrings that have different contents, one of // which having a NUL character in the middle. ::std::wstring wstr3(wstr1); wstr3.at(2) = L'\0'; EXPECT_NONFATAL_FAILURE(EXPECT_EQ(wstr1, wstr3), "wstr3"); // Compares a wchar_t* to an std::wstring that has different // content. EXPECT_FATAL_FAILURE({ // NOLINT ASSERT_EQ(const_cast(L"foo"), ::std::wstring(L"bar")); }, ""); } #endif // GTEST_HAS_STD_WSTRING #if GTEST_HAS_GLOBAL_STRING // Tests using ::string values in {EXPECT|ASSERT}_EQ. TEST(EqAssertionTest, GlobalString) { // Compares a const char* to a ::string that has identical content. EXPECT_EQ("Test", ::string("Test")); // Compares two identical ::strings. const ::string str1("A * in the middle"); const ::string str2(str1); ASSERT_EQ(str1, str2); // Compares a ::string to a const char* that has different content. EXPECT_NONFATAL_FAILURE(EXPECT_EQ(::string("Test"), "test"), "test"); // Compares two ::strings that have different contents, one of which // having a NUL character in the middle. ::string str3(str1); str3.at(2) = '\0'; EXPECT_NONFATAL_FAILURE(EXPECT_EQ(str1, str3), "str3"); // Compares a ::string to a char* that has different content. EXPECT_FATAL_FAILURE({ // NOLINT ASSERT_EQ(::string("bar"), const_cast("foo")); }, ""); } #endif // GTEST_HAS_GLOBAL_STRING #if GTEST_HAS_GLOBAL_WSTRING // Tests using ::wstring values in {EXPECT|ASSERT}_EQ. TEST(EqAssertionTest, GlobalWideString) { // Compares two identical ::wstrings. static const ::wstring wstr1(L"A * in the middle"); static const ::wstring wstr2(wstr1); EXPECT_EQ(wstr1, wstr2); // Compares a const wchar_t* to a ::wstring that has identical content. const wchar_t kTestX8119[] = { 'T', 'e', 's', 't', 0x8119, '\0' }; ASSERT_EQ(kTestX8119, ::wstring(kTestX8119)); // Compares a const wchar_t* to a ::wstring that has different // content. const wchar_t kTestX8120[] = { 'T', 'e', 's', 't', 0x8120, '\0' }; EXPECT_NONFATAL_FAILURE({ // NOLINT EXPECT_EQ(kTestX8120, ::wstring(kTestX8119)); }, "Test\\x8119"); // Compares a wchar_t* to a ::wstring that has different content. wchar_t* const p1 = const_cast(L"foo"); EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p1, ::wstring(L"bar")), "bar"); // Compares two ::wstrings that have different contents, one of which // having a NUL character in the middle. static ::wstring wstr3; wstr3 = wstr1; wstr3.at(2) = L'\0'; EXPECT_FATAL_FAILURE(ASSERT_EQ(wstr1, wstr3), "wstr3"); } #endif // GTEST_HAS_GLOBAL_WSTRING // Tests using char pointers in {EXPECT|ASSERT}_EQ. TEST(EqAssertionTest, CharPointer) { char* const p0 = NULL; // Only way to get the Nokia compiler to compile the cast // is to have a separate void* variable first. Putting // the two casts on the same line doesn't work, neither does // a direct C-style to char*. void* pv1 = (void*)0x1234; // NOLINT void* pv2 = (void*)0xABC0; // NOLINT char* const p1 = reinterpret_cast(pv1); char* const p2 = reinterpret_cast(pv2); ASSERT_EQ(p1, p1); EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p0, p2), "Value of: p2"); EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p1, p2), "p2"); EXPECT_FATAL_FAILURE(ASSERT_EQ(reinterpret_cast(0x1234), reinterpret_cast(0xABC0)), "ABC0"); } // Tests using wchar_t pointers in {EXPECT|ASSERT}_EQ. TEST(EqAssertionTest, WideCharPointer) { wchar_t* const p0 = NULL; // Only way to get the Nokia compiler to compile the cast // is to have a separate void* variable first. Putting // the two casts on the same line doesn't work, neither does // a direct C-style to char*. void* pv1 = (void*)0x1234; // NOLINT void* pv2 = (void*)0xABC0; // NOLINT wchar_t* const p1 = reinterpret_cast(pv1); wchar_t* const p2 = reinterpret_cast(pv2); EXPECT_EQ(p0, p0); EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p0, p2), "Value of: p2"); EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p1, p2), "p2"); void* pv3 = (void*)0x1234; // NOLINT void* pv4 = (void*)0xABC0; // NOLINT const wchar_t* p3 = reinterpret_cast(pv3); const wchar_t* p4 = reinterpret_cast(pv4); EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p3, p4), "p4"); } // Tests using other types of pointers in {EXPECT|ASSERT}_EQ. TEST(EqAssertionTest, OtherPointer) { ASSERT_EQ(static_cast(NULL), static_cast(NULL)); EXPECT_FATAL_FAILURE(ASSERT_EQ(static_cast(NULL), reinterpret_cast(0x1234)), "0x1234"); } // A class that supports binary comparison operators but not streaming. class UnprintableChar { public: explicit UnprintableChar(char ch) : char_(ch) {} bool operator==(const UnprintableChar& rhs) const { return char_ == rhs.char_; } bool operator!=(const UnprintableChar& rhs) const { return char_ != rhs.char_; } bool operator<(const UnprintableChar& rhs) const { return char_ < rhs.char_; } bool operator<=(const UnprintableChar& rhs) const { return char_ <= rhs.char_; } bool operator>(const UnprintableChar& rhs) const { return char_ > rhs.char_; } bool operator>=(const UnprintableChar& rhs) const { return char_ >= rhs.char_; } private: char char_; }; // Tests that ASSERT_EQ() and friends don't require the arguments to // be printable. TEST(ComparisonAssertionTest, AcceptsUnprintableArgs) { const UnprintableChar x('x'), y('y'); ASSERT_EQ(x, x); EXPECT_NE(x, y); ASSERT_LT(x, y); EXPECT_LE(x, y); ASSERT_GT(y, x); EXPECT_GE(x, x); EXPECT_NONFATAL_FAILURE(EXPECT_EQ(x, y), "1-byte object <78>"); EXPECT_NONFATAL_FAILURE(EXPECT_EQ(x, y), "1-byte object <79>"); EXPECT_NONFATAL_FAILURE(EXPECT_LT(y, y), "1-byte object <79>"); EXPECT_NONFATAL_FAILURE(EXPECT_GT(x, y), "1-byte object <78>"); EXPECT_NONFATAL_FAILURE(EXPECT_GT(x, y), "1-byte object <79>"); // Code tested by EXPECT_FATAL_FAILURE cannot reference local // variables, so we have to write UnprintableChar('x') instead of x. #ifndef __BORLANDC__ // ICE's in C++Builder. EXPECT_FATAL_FAILURE(ASSERT_NE(UnprintableChar('x'), UnprintableChar('x')), "1-byte object <78>"); EXPECT_FATAL_FAILURE(ASSERT_LE(UnprintableChar('y'), UnprintableChar('x')), "1-byte object <78>"); #endif EXPECT_FATAL_FAILURE(ASSERT_LE(UnprintableChar('y'), UnprintableChar('x')), "1-byte object <79>"); EXPECT_FATAL_FAILURE(ASSERT_GE(UnprintableChar('x'), UnprintableChar('y')), "1-byte object <78>"); EXPECT_FATAL_FAILURE(ASSERT_GE(UnprintableChar('x'), UnprintableChar('y')), "1-byte object <79>"); } // Tests the FRIEND_TEST macro. // This class has a private member we want to test. We will test it // both in a TEST and in a TEST_F. class Foo { public: Foo() {} private: int Bar() const { return 1; } // Declares the friend tests that can access the private member // Bar(). FRIEND_TEST(FRIEND_TEST_Test, TEST); FRIEND_TEST(FRIEND_TEST_Test2, TEST_F); }; // Tests that the FRIEND_TEST declaration allows a TEST to access a // class's private members. This should compile. TEST(FRIEND_TEST_Test, TEST) { ASSERT_EQ(1, Foo().Bar()); } // The fixture needed to test using FRIEND_TEST with TEST_F. class FRIEND_TEST_Test2 : public Test { protected: Foo foo; }; // Tests that the FRIEND_TEST declaration allows a TEST_F to access a // class's private members. This should compile. TEST_F(FRIEND_TEST_Test2, TEST_F) { ASSERT_EQ(1, foo.Bar()); } // Tests the life cycle of Test objects. // The test fixture for testing the life cycle of Test objects. // // This class counts the number of live test objects that uses this // fixture. class TestLifeCycleTest : public Test { protected: // Constructor. Increments the number of test objects that uses // this fixture. TestLifeCycleTest() { count_++; } // Destructor. Decrements the number of test objects that uses this // fixture. ~TestLifeCycleTest() { count_--; } // Returns the number of live test objects that uses this fixture. int count() const { return count_; } private: static int count_; }; int TestLifeCycleTest::count_ = 0; // Tests the life cycle of test objects. TEST_F(TestLifeCycleTest, Test1) { // There should be only one test object in this test case that's // currently alive. ASSERT_EQ(1, count()); } // Tests the life cycle of test objects. TEST_F(TestLifeCycleTest, Test2) { // After Test1 is done and Test2 is started, there should still be // only one live test object, as the object for Test1 should've been // deleted. ASSERT_EQ(1, count()); } } // namespace // Tests that the copy constructor works when it is NOT optimized away by // the compiler. TEST(AssertionResultTest, CopyConstructorWorksWhenNotOptimied) { // Checks that the copy constructor doesn't try to dereference NULL pointers // in the source object. AssertionResult r1 = AssertionSuccess(); AssertionResult r2 = r1; // The following line is added to prevent the compiler from optimizing // away the constructor call. r1 << "abc"; AssertionResult r3 = r1; EXPECT_EQ(static_cast(r3), static_cast(r1)); EXPECT_STREQ("abc", r1.message()); } // Tests that AssertionSuccess and AssertionFailure construct // AssertionResult objects as expected. TEST(AssertionResultTest, ConstructionWorks) { AssertionResult r1 = AssertionSuccess(); EXPECT_TRUE(r1); EXPECT_STREQ("", r1.message()); AssertionResult r2 = AssertionSuccess() << "abc"; EXPECT_TRUE(r2); EXPECT_STREQ("abc", r2.message()); AssertionResult r3 = AssertionFailure(); EXPECT_FALSE(r3); EXPECT_STREQ("", r3.message()); AssertionResult r4 = AssertionFailure() << "def"; EXPECT_FALSE(r4); EXPECT_STREQ("def", r4.message()); AssertionResult r5 = AssertionFailure(Message() << "ghi"); EXPECT_FALSE(r5); EXPECT_STREQ("ghi", r5.message()); } // Tests that the negation flips the predicate result but keeps the message. TEST(AssertionResultTest, NegationWorks) { AssertionResult r1 = AssertionSuccess() << "abc"; EXPECT_FALSE(!r1); EXPECT_STREQ("abc", (!r1).message()); AssertionResult r2 = AssertionFailure() << "def"; EXPECT_TRUE(!r2); EXPECT_STREQ("def", (!r2).message()); } TEST(AssertionResultTest, StreamingWorks) { AssertionResult r = AssertionSuccess(); r << "abc" << 'd' << 0 << true; EXPECT_STREQ("abcd0true", r.message()); } TEST(AssertionResultTest, CanStreamOstreamManipulators) { AssertionResult r = AssertionSuccess(); r << "Data" << std::endl << std::flush << std::ends << "Will be visible"; EXPECT_STREQ("Data\n\\0Will be visible", r.message()); } // Tests streaming a user type whose definition and operator << are // both in the global namespace. class Base { public: explicit Base(int an_x) : x_(an_x) {} int x() const { return x_; } private: int x_; }; std::ostream& operator<<(std::ostream& os, const Base& val) { return os << val.x(); } std::ostream& operator<<(std::ostream& os, const Base* pointer) { return os << "(" << pointer->x() << ")"; } TEST(MessageTest, CanStreamUserTypeInGlobalNameSpace) { Message msg; Base a(1); msg << a << &a; // Uses ::operator<<. EXPECT_STREQ("1(1)", msg.GetString().c_str()); } // Tests streaming a user type whose definition and operator<< are // both in an unnamed namespace. namespace { class MyTypeInUnnamedNameSpace : public Base { public: explicit MyTypeInUnnamedNameSpace(int an_x): Base(an_x) {} }; std::ostream& operator<<(std::ostream& os, const MyTypeInUnnamedNameSpace& val) { return os << val.x(); } std::ostream& operator<<(std::ostream& os, const MyTypeInUnnamedNameSpace* pointer) { return os << "(" << pointer->x() << ")"; } } // namespace TEST(MessageTest, CanStreamUserTypeInUnnamedNameSpace) { Message msg; MyTypeInUnnamedNameSpace a(1); msg << a << &a; // Uses ::operator<<. EXPECT_STREQ("1(1)", msg.GetString().c_str()); } // Tests streaming a user type whose definition and operator<< are // both in a user namespace. namespace namespace1 { class MyTypeInNameSpace1 : public Base { public: explicit MyTypeInNameSpace1(int an_x): Base(an_x) {} }; std::ostream& operator<<(std::ostream& os, const MyTypeInNameSpace1& val) { return os << val.x(); } std::ostream& operator<<(std::ostream& os, const MyTypeInNameSpace1* pointer) { return os << "(" << pointer->x() << ")"; } } // namespace namespace1 TEST(MessageTest, CanStreamUserTypeInUserNameSpace) { Message msg; namespace1::MyTypeInNameSpace1 a(1); msg << a << &a; // Uses namespace1::operator<<. EXPECT_STREQ("1(1)", msg.GetString().c_str()); } // Tests streaming a user type whose definition is in a user namespace // but whose operator<< is in the global namespace. namespace namespace2 { class MyTypeInNameSpace2 : public ::Base { public: explicit MyTypeInNameSpace2(int an_x): Base(an_x) {} }; } // namespace namespace2 std::ostream& operator<<(std::ostream& os, const namespace2::MyTypeInNameSpace2& val) { return os << val.x(); } std::ostream& operator<<(std::ostream& os, const namespace2::MyTypeInNameSpace2* pointer) { return os << "(" << pointer->x() << ")"; } TEST(MessageTest, CanStreamUserTypeInUserNameSpaceWithStreamOperatorInGlobal) { Message msg; namespace2::MyTypeInNameSpace2 a(1); msg << a << &a; // Uses ::operator<<. EXPECT_STREQ("1(1)", msg.GetString().c_str()); } // Tests streaming NULL pointers to testing::Message. TEST(MessageTest, NullPointers) { Message msg; char* const p1 = NULL; unsigned char* const p2 = NULL; int* p3 = NULL; double* p4 = NULL; bool* p5 = NULL; Message* p6 = NULL; msg << p1 << p2 << p3 << p4 << p5 << p6; ASSERT_STREQ("(null)(null)(null)(null)(null)(null)", msg.GetString().c_str()); } // Tests streaming wide strings to testing::Message. TEST(MessageTest, WideStrings) { // Streams a NULL of type const wchar_t*. const wchar_t* const_wstr = NULL; EXPECT_STREQ("(null)", (Message() << const_wstr).GetString().c_str()); // Streams a NULL of type wchar_t*. wchar_t* wstr = NULL; EXPECT_STREQ("(null)", (Message() << wstr).GetString().c_str()); // Streams a non-NULL of type const wchar_t*. const_wstr = L"abc\x8119"; EXPECT_STREQ("abc\xe8\x84\x99", (Message() << const_wstr).GetString().c_str()); // Streams a non-NULL of type wchar_t*. wstr = const_cast(const_wstr); EXPECT_STREQ("abc\xe8\x84\x99", (Message() << wstr).GetString().c_str()); } // This line tests that we can define tests in the testing namespace. namespace testing { // Tests the TestInfo class. class TestInfoTest : public Test { protected: static const TestInfo* GetTestInfo(const char* test_name) { const TestCase* const test_case = GetUnitTestImpl()-> GetTestCase("TestInfoTest", "", NULL, NULL); for (int i = 0; i < test_case->total_test_count(); ++i) { const TestInfo* const test_info = test_case->GetTestInfo(i); if (strcmp(test_name, test_info->name()) == 0) return test_info; } return NULL; } static const TestResult* GetTestResult( const TestInfo* test_info) { return test_info->result(); } }; // Tests TestInfo::test_case_name() and TestInfo::name(). TEST_F(TestInfoTest, Names) { const TestInfo* const test_info = GetTestInfo("Names"); ASSERT_STREQ("TestInfoTest", test_info->test_case_name()); ASSERT_STREQ("Names", test_info->name()); } // Tests TestInfo::result(). TEST_F(TestInfoTest, result) { const TestInfo* const test_info = GetTestInfo("result"); // Initially, there is no TestPartResult for this test. ASSERT_EQ(0, GetTestResult(test_info)->total_part_count()); // After the previous assertion, there is still none. ASSERT_EQ(0, GetTestResult(test_info)->total_part_count()); } // Tests setting up and tearing down a test case. class SetUpTestCaseTest : public Test { protected: // This will be called once before the first test in this test case // is run. static void SetUpTestCase() { printf("Setting up the test case . . .\n"); // Initializes some shared resource. In this simple example, we // just create a C string. More complex stuff can be done if // desired. shared_resource_ = "123"; // Increments the number of test cases that have been set up. counter_++; // SetUpTestCase() should be called only once. EXPECT_EQ(1, counter_); } // This will be called once after the last test in this test case is // run. static void TearDownTestCase() { printf("Tearing down the test case . . .\n"); // Decrements the number of test cases that have been set up. counter_--; // TearDownTestCase() should be called only once. EXPECT_EQ(0, counter_); // Cleans up the shared resource. shared_resource_ = NULL; } // This will be called before each test in this test case. virtual void SetUp() { // SetUpTestCase() should be called only once, so counter_ should // always be 1. EXPECT_EQ(1, counter_); } // Number of test cases that have been set up. static int counter_; // Some resource to be shared by all tests in this test case. static const char* shared_resource_; }; int SetUpTestCaseTest::counter_ = 0; const char* SetUpTestCaseTest::shared_resource_ = NULL; // A test that uses the shared resource. TEST_F(SetUpTestCaseTest, Test1) { EXPECT_STRNE(NULL, shared_resource_); } // Another test that uses the shared resource. TEST_F(SetUpTestCaseTest, Test2) { EXPECT_STREQ("123", shared_resource_); } // The InitGoogleTestTest test case tests testing::InitGoogleTest(). // The Flags struct stores a copy of all Google Test flags. struct Flags { // Constructs a Flags struct where each flag has its default value. Flags() : also_run_disabled_tests(false), break_on_failure(false), catch_exceptions(false), death_test_use_fork(false), filter(""), list_tests(false), output(""), print_time(true), random_seed(0), repeat(1), shuffle(false), stack_trace_depth(kMaxStackTraceDepth), stream_result_to(""), throw_on_failure(false) {} // Factory methods. // Creates a Flags struct where the gtest_also_run_disabled_tests flag has // the given value. static Flags AlsoRunDisabledTests(bool also_run_disabled_tests) { Flags flags; flags.also_run_disabled_tests = also_run_disabled_tests; return flags; } // Creates a Flags struct where the gtest_break_on_failure flag has // the given value. static Flags BreakOnFailure(bool break_on_failure) { Flags flags; flags.break_on_failure = break_on_failure; return flags; } // Creates a Flags struct where the gtest_catch_exceptions flag has // the given value. static Flags CatchExceptions(bool catch_exceptions) { Flags flags; flags.catch_exceptions = catch_exceptions; return flags; } // Creates a Flags struct where the gtest_death_test_use_fork flag has // the given value. static Flags DeathTestUseFork(bool death_test_use_fork) { Flags flags; flags.death_test_use_fork = death_test_use_fork; return flags; } // Creates a Flags struct where the gtest_filter flag has the given // value. static Flags Filter(const char* filter) { Flags flags; flags.filter = filter; return flags; } // Creates a Flags struct where the gtest_list_tests flag has the // given value. static Flags ListTests(bool list_tests) { Flags flags; flags.list_tests = list_tests; return flags; } // Creates a Flags struct where the gtest_output flag has the given // value. static Flags Output(const char* output) { Flags flags; flags.output = output; return flags; } // Creates a Flags struct where the gtest_print_time flag has the given // value. static Flags PrintTime(bool print_time) { Flags flags; flags.print_time = print_time; return flags; } // Creates a Flags struct where the gtest_random_seed flag has // the given value. static Flags RandomSeed(Int32 random_seed) { Flags flags; flags.random_seed = random_seed; return flags; } // Creates a Flags struct where the gtest_repeat flag has the given // value. static Flags Repeat(Int32 repeat) { Flags flags; flags.repeat = repeat; return flags; } // Creates a Flags struct where the gtest_shuffle flag has // the given value. static Flags Shuffle(bool shuffle) { Flags flags; flags.shuffle = shuffle; return flags; } // Creates a Flags struct where the GTEST_FLAG(stack_trace_depth) flag has // the given value. static Flags StackTraceDepth(Int32 stack_trace_depth) { Flags flags; flags.stack_trace_depth = stack_trace_depth; return flags; } // Creates a Flags struct where the GTEST_FLAG(stream_result_to) flag has // the given value. static Flags StreamResultTo(const char* stream_result_to) { Flags flags; flags.stream_result_to = stream_result_to; return flags; } // Creates a Flags struct where the gtest_throw_on_failure flag has // the given value. static Flags ThrowOnFailure(bool throw_on_failure) { Flags flags; flags.throw_on_failure = throw_on_failure; return flags; } // These fields store the flag values. bool also_run_disabled_tests; bool break_on_failure; bool catch_exceptions; bool death_test_use_fork; const char* filter; bool list_tests; const char* output; bool print_time; Int32 random_seed; Int32 repeat; bool shuffle; Int32 stack_trace_depth; const char* stream_result_to; bool throw_on_failure; }; // Fixture for testing InitGoogleTest(). class InitGoogleTestTest : public Test { protected: // Clears the flags before each test. virtual void SetUp() { GTEST_FLAG(also_run_disabled_tests) = false; GTEST_FLAG(break_on_failure) = false; GTEST_FLAG(catch_exceptions) = false; GTEST_FLAG(death_test_use_fork) = false; GTEST_FLAG(filter) = ""; GTEST_FLAG(list_tests) = false; GTEST_FLAG(output) = ""; GTEST_FLAG(print_time) = true; GTEST_FLAG(random_seed) = 0; GTEST_FLAG(repeat) = 1; GTEST_FLAG(shuffle) = false; GTEST_FLAG(stack_trace_depth) = kMaxStackTraceDepth; GTEST_FLAG(stream_result_to) = ""; GTEST_FLAG(throw_on_failure) = false; } // Asserts that two narrow or wide string arrays are equal. template static void AssertStringArrayEq(size_t size1, CharType** array1, size_t size2, CharType** array2) { ASSERT_EQ(size1, size2) << " Array sizes different."; for (size_t i = 0; i != size1; i++) { ASSERT_STREQ(array1[i], array2[i]) << " where i == " << i; } } // Verifies that the flag values match the expected values. static void CheckFlags(const Flags& expected) { EXPECT_EQ(expected.also_run_disabled_tests, GTEST_FLAG(also_run_disabled_tests)); EXPECT_EQ(expected.break_on_failure, GTEST_FLAG(break_on_failure)); EXPECT_EQ(expected.catch_exceptions, GTEST_FLAG(catch_exceptions)); EXPECT_EQ(expected.death_test_use_fork, GTEST_FLAG(death_test_use_fork)); EXPECT_STREQ(expected.filter, GTEST_FLAG(filter).c_str()); EXPECT_EQ(expected.list_tests, GTEST_FLAG(list_tests)); EXPECT_STREQ(expected.output, GTEST_FLAG(output).c_str()); EXPECT_EQ(expected.print_time, GTEST_FLAG(print_time)); EXPECT_EQ(expected.random_seed, GTEST_FLAG(random_seed)); EXPECT_EQ(expected.repeat, GTEST_FLAG(repeat)); EXPECT_EQ(expected.shuffle, GTEST_FLAG(shuffle)); EXPECT_EQ(expected.stack_trace_depth, GTEST_FLAG(stack_trace_depth)); EXPECT_STREQ(expected.stream_result_to, GTEST_FLAG(stream_result_to).c_str()); EXPECT_EQ(expected.throw_on_failure, GTEST_FLAG(throw_on_failure)); } // Parses a command line (specified by argc1 and argv1), then // verifies that the flag values are expected and that the // recognized flags are removed from the command line. template static void TestParsingFlags(int argc1, const CharType** argv1, int argc2, const CharType** argv2, const Flags& expected, bool should_print_help) { const bool saved_help_flag = ::testing::internal::g_help_flag; ::testing::internal::g_help_flag = false; #if GTEST_HAS_STREAM_REDIRECTION CaptureStdout(); #endif // Parses the command line. internal::ParseGoogleTestFlagsOnly(&argc1, const_cast(argv1)); #if GTEST_HAS_STREAM_REDIRECTION const String captured_stdout = GetCapturedStdout(); #endif // Verifies the flag values. CheckFlags(expected); // Verifies that the recognized flags are removed from the command // line. AssertStringArrayEq(argc1 + 1, argv1, argc2 + 1, argv2); // ParseGoogleTestFlagsOnly should neither set g_help_flag nor print the // help message for the flags it recognizes. EXPECT_EQ(should_print_help, ::testing::internal::g_help_flag); #if GTEST_HAS_STREAM_REDIRECTION const char* const expected_help_fragment = "This program contains tests written using"; if (should_print_help) { EXPECT_PRED_FORMAT2(IsSubstring, expected_help_fragment, captured_stdout); } else { EXPECT_PRED_FORMAT2(IsNotSubstring, expected_help_fragment, captured_stdout); } #endif // GTEST_HAS_STREAM_REDIRECTION ::testing::internal::g_help_flag = saved_help_flag; } // This macro wraps TestParsingFlags s.t. the user doesn't need // to specify the array sizes. #define GTEST_TEST_PARSING_FLAGS_(argv1, argv2, expected, should_print_help) \ TestParsingFlags(sizeof(argv1)/sizeof(*argv1) - 1, argv1, \ sizeof(argv2)/sizeof(*argv2) - 1, argv2, \ expected, should_print_help) }; // Tests parsing an empty command line. TEST_F(InitGoogleTestTest, Empty) { const char* argv[] = { NULL }; const char* argv2[] = { NULL }; GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags(), false); } // Tests parsing a command line that has no flag. TEST_F(InitGoogleTestTest, NoFlag) { const char* argv[] = { "foo.exe", NULL }; const char* argv2[] = { "foo.exe", NULL }; GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags(), false); } // Tests parsing a bad --gtest_filter flag. TEST_F(InitGoogleTestTest, FilterBad) { const char* argv[] = { "foo.exe", "--gtest_filter", NULL }; const char* argv2[] = { "foo.exe", "--gtest_filter", NULL }; GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Filter(""), true); } // Tests parsing an empty --gtest_filter flag. TEST_F(InitGoogleTestTest, FilterEmpty) { const char* argv[] = { "foo.exe", "--gtest_filter=", NULL }; const char* argv2[] = { "foo.exe", NULL }; GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Filter(""), false); } // Tests parsing a non-empty --gtest_filter flag. TEST_F(InitGoogleTestTest, FilterNonEmpty) { const char* argv[] = { "foo.exe", "--gtest_filter=abc", NULL }; const char* argv2[] = { "foo.exe", NULL }; GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Filter("abc"), false); } // Tests parsing --gtest_break_on_failure. TEST_F(InitGoogleTestTest, BreakOnFailureWithoutValue) { const char* argv[] = { "foo.exe", "--gtest_break_on_failure", NULL }; const char* argv2[] = { "foo.exe", NULL }; GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::BreakOnFailure(true), false); } // Tests parsing --gtest_break_on_failure=0. TEST_F(InitGoogleTestTest, BreakOnFailureFalse_0) { const char* argv[] = { "foo.exe", "--gtest_break_on_failure=0", NULL }; const char* argv2[] = { "foo.exe", NULL }; GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::BreakOnFailure(false), false); } // Tests parsing --gtest_break_on_failure=f. TEST_F(InitGoogleTestTest, BreakOnFailureFalse_f) { const char* argv[] = { "foo.exe", "--gtest_break_on_failure=f", NULL }; const char* argv2[] = { "foo.exe", NULL }; GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::BreakOnFailure(false), false); } // Tests parsing --gtest_break_on_failure=F. TEST_F(InitGoogleTestTest, BreakOnFailureFalse_F) { const char* argv[] = { "foo.exe", "--gtest_break_on_failure=F", NULL }; const char* argv2[] = { "foo.exe", NULL }; GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::BreakOnFailure(false), false); } // Tests parsing a --gtest_break_on_failure flag that has a "true" // definition. TEST_F(InitGoogleTestTest, BreakOnFailureTrue) { const char* argv[] = { "foo.exe", "--gtest_break_on_failure=1", NULL }; const char* argv2[] = { "foo.exe", NULL }; GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::BreakOnFailure(true), false); } // Tests parsing --gtest_catch_exceptions. TEST_F(InitGoogleTestTest, CatchExceptions) { const char* argv[] = { "foo.exe", "--gtest_catch_exceptions", NULL }; const char* argv2[] = { "foo.exe", NULL }; GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::CatchExceptions(true), false); } // Tests parsing --gtest_death_test_use_fork. TEST_F(InitGoogleTestTest, DeathTestUseFork) { const char* argv[] = { "foo.exe", "--gtest_death_test_use_fork", NULL }; const char* argv2[] = { "foo.exe", NULL }; GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::DeathTestUseFork(true), false); } // Tests having the same flag twice with different values. The // expected behavior is that the one coming last takes precedence. TEST_F(InitGoogleTestTest, DuplicatedFlags) { const char* argv[] = { "foo.exe", "--gtest_filter=a", "--gtest_filter=b", NULL }; const char* argv2[] = { "foo.exe", NULL }; GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Filter("b"), false); } // Tests having an unrecognized flag on the command line. TEST_F(InitGoogleTestTest, UnrecognizedFlag) { const char* argv[] = { "foo.exe", "--gtest_break_on_failure", "bar", // Unrecognized by Google Test. "--gtest_filter=b", NULL }; const char* argv2[] = { "foo.exe", "bar", NULL }; Flags flags; flags.break_on_failure = true; flags.filter = "b"; GTEST_TEST_PARSING_FLAGS_(argv, argv2, flags, false); } // Tests having a --gtest_list_tests flag TEST_F(InitGoogleTestTest, ListTestsFlag) { const char* argv[] = { "foo.exe", "--gtest_list_tests", NULL }; const char* argv2[] = { "foo.exe", NULL }; GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ListTests(true), false); } // Tests having a --gtest_list_tests flag with a "true" value TEST_F(InitGoogleTestTest, ListTestsTrue) { const char* argv[] = { "foo.exe", "--gtest_list_tests=1", NULL }; const char* argv2[] = { "foo.exe", NULL }; GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ListTests(true), false); } // Tests having a --gtest_list_tests flag with a "false" value TEST_F(InitGoogleTestTest, ListTestsFalse) { const char* argv[] = { "foo.exe", "--gtest_list_tests=0", NULL }; const char* argv2[] = { "foo.exe", NULL }; GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ListTests(false), false); } // Tests parsing --gtest_list_tests=f. TEST_F(InitGoogleTestTest, ListTestsFalse_f) { const char* argv[] = { "foo.exe", "--gtest_list_tests=f", NULL }; const char* argv2[] = { "foo.exe", NULL }; GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ListTests(false), false); } // Tests parsing --gtest_list_tests=F. TEST_F(InitGoogleTestTest, ListTestsFalse_F) { const char* argv[] = { "foo.exe", "--gtest_list_tests=F", NULL }; const char* argv2[] = { "foo.exe", NULL }; GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ListTests(false), false); } // Tests parsing --gtest_output (invalid). TEST_F(InitGoogleTestTest, OutputEmpty) { const char* argv[] = { "foo.exe", "--gtest_output", NULL }; const char* argv2[] = { "foo.exe", "--gtest_output", NULL }; GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags(), true); } // Tests parsing --gtest_output=xml TEST_F(InitGoogleTestTest, OutputXml) { const char* argv[] = { "foo.exe", "--gtest_output=xml", NULL }; const char* argv2[] = { "foo.exe", NULL }; GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Output("xml"), false); } // Tests parsing --gtest_output=xml:file TEST_F(InitGoogleTestTest, OutputXmlFile) { const char* argv[] = { "foo.exe", "--gtest_output=xml:file", NULL }; const char* argv2[] = { "foo.exe", NULL }; GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Output("xml:file"), false); } // Tests parsing --gtest_output=xml:directory/path/ TEST_F(InitGoogleTestTest, OutputXmlDirectory) { const char* argv[] = { "foo.exe", "--gtest_output=xml:directory/path/", NULL }; const char* argv2[] = { "foo.exe", NULL }; GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Output("xml:directory/path/"), false); } // Tests having a --gtest_print_time flag TEST_F(InitGoogleTestTest, PrintTimeFlag) { const char* argv[] = { "foo.exe", "--gtest_print_time", NULL }; const char* argv2[] = { "foo.exe", NULL }; GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::PrintTime(true), false); } // Tests having a --gtest_print_time flag with a "true" value TEST_F(InitGoogleTestTest, PrintTimeTrue) { const char* argv[] = { "foo.exe", "--gtest_print_time=1", NULL }; const char* argv2[] = { "foo.exe", NULL }; GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::PrintTime(true), false); } // Tests having a --gtest_print_time flag with a "false" value TEST_F(InitGoogleTestTest, PrintTimeFalse) { const char* argv[] = { "foo.exe", "--gtest_print_time=0", NULL }; const char* argv2[] = { "foo.exe", NULL }; GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::PrintTime(false), false); } // Tests parsing --gtest_print_time=f. TEST_F(InitGoogleTestTest, PrintTimeFalse_f) { const char* argv[] = { "foo.exe", "--gtest_print_time=f", NULL }; const char* argv2[] = { "foo.exe", NULL }; GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::PrintTime(false), false); } // Tests parsing --gtest_print_time=F. TEST_F(InitGoogleTestTest, PrintTimeFalse_F) { const char* argv[] = { "foo.exe", "--gtest_print_time=F", NULL }; const char* argv2[] = { "foo.exe", NULL }; GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::PrintTime(false), false); } // Tests parsing --gtest_random_seed=number TEST_F(InitGoogleTestTest, RandomSeed) { const char* argv[] = { "foo.exe", "--gtest_random_seed=1000", NULL }; const char* argv2[] = { "foo.exe", NULL }; GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::RandomSeed(1000), false); } // Tests parsing --gtest_repeat=number TEST_F(InitGoogleTestTest, Repeat) { const char* argv[] = { "foo.exe", "--gtest_repeat=1000", NULL }; const char* argv2[] = { "foo.exe", NULL }; GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Repeat(1000), false); } // Tests having a --gtest_also_run_disabled_tests flag TEST_F(InitGoogleTestTest, AlsoRunDisabledTestsFlag) { const char* argv[] = { "foo.exe", "--gtest_also_run_disabled_tests", NULL }; const char* argv2[] = { "foo.exe", NULL }; GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::AlsoRunDisabledTests(true), false); } // Tests having a --gtest_also_run_disabled_tests flag with a "true" value TEST_F(InitGoogleTestTest, AlsoRunDisabledTestsTrue) { const char* argv[] = { "foo.exe", "--gtest_also_run_disabled_tests=1", NULL }; const char* argv2[] = { "foo.exe", NULL }; GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::AlsoRunDisabledTests(true), false); } // Tests having a --gtest_also_run_disabled_tests flag with a "false" value TEST_F(InitGoogleTestTest, AlsoRunDisabledTestsFalse) { const char* argv[] = { "foo.exe", "--gtest_also_run_disabled_tests=0", NULL }; const char* argv2[] = { "foo.exe", NULL }; GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::AlsoRunDisabledTests(false), false); } // Tests parsing --gtest_shuffle. TEST_F(InitGoogleTestTest, ShuffleWithoutValue) { const char* argv[] = { "foo.exe", "--gtest_shuffle", NULL }; const char* argv2[] = { "foo.exe", NULL }; GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Shuffle(true), false); } // Tests parsing --gtest_shuffle=0. TEST_F(InitGoogleTestTest, ShuffleFalse_0) { const char* argv[] = { "foo.exe", "--gtest_shuffle=0", NULL }; const char* argv2[] = { "foo.exe", NULL }; GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Shuffle(false), false); } // Tests parsing a --gtest_shuffle flag that has a "true" // definition. TEST_F(InitGoogleTestTest, ShuffleTrue) { const char* argv[] = { "foo.exe", "--gtest_shuffle=1", NULL }; const char* argv2[] = { "foo.exe", NULL }; GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Shuffle(true), false); } // Tests parsing --gtest_stack_trace_depth=number. TEST_F(InitGoogleTestTest, StackTraceDepth) { const char* argv[] = { "foo.exe", "--gtest_stack_trace_depth=5", NULL }; const char* argv2[] = { "foo.exe", NULL }; GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::StackTraceDepth(5), false); } TEST_F(InitGoogleTestTest, StreamResultTo) { const char* argv[] = { "foo.exe", "--gtest_stream_result_to=localhost:1234", NULL }; const char* argv2[] = { "foo.exe", NULL }; GTEST_TEST_PARSING_FLAGS_( argv, argv2, Flags::StreamResultTo("localhost:1234"), false); } // Tests parsing --gtest_throw_on_failure. TEST_F(InitGoogleTestTest, ThrowOnFailureWithoutValue) { const char* argv[] = { "foo.exe", "--gtest_throw_on_failure", NULL }; const char* argv2[] = { "foo.exe", NULL }; GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ThrowOnFailure(true), false); } // Tests parsing --gtest_throw_on_failure=0. TEST_F(InitGoogleTestTest, ThrowOnFailureFalse_0) { const char* argv[] = { "foo.exe", "--gtest_throw_on_failure=0", NULL }; const char* argv2[] = { "foo.exe", NULL }; GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ThrowOnFailure(false), false); } // Tests parsing a --gtest_throw_on_failure flag that has a "true" // definition. TEST_F(InitGoogleTestTest, ThrowOnFailureTrue) { const char* argv[] = { "foo.exe", "--gtest_throw_on_failure=1", NULL }; const char* argv2[] = { "foo.exe", NULL }; GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ThrowOnFailure(true), false); } #if GTEST_OS_WINDOWS // Tests parsing wide strings. TEST_F(InitGoogleTestTest, WideStrings) { const wchar_t* argv[] = { L"foo.exe", L"--gtest_filter=Foo*", L"--gtest_list_tests=1", L"--gtest_break_on_failure", L"--non_gtest_flag", NULL }; const wchar_t* argv2[] = { L"foo.exe", L"--non_gtest_flag", NULL }; Flags expected_flags; expected_flags.break_on_failure = true; expected_flags.filter = "Foo*"; expected_flags.list_tests = true; GTEST_TEST_PARSING_FLAGS_(argv, argv2, expected_flags, false); } #endif // GTEST_OS_WINDOWS // Tests current_test_info() in UnitTest. class CurrentTestInfoTest : public Test { protected: // Tests that current_test_info() returns NULL before the first test in // the test case is run. static void SetUpTestCase() { // There should be no tests running at this point. const TestInfo* test_info = UnitTest::GetInstance()->current_test_info(); EXPECT_TRUE(test_info == NULL) << "There should be no tests running at this point."; } // Tests that current_test_info() returns NULL after the last test in // the test case has run. static void TearDownTestCase() { const TestInfo* test_info = UnitTest::GetInstance()->current_test_info(); EXPECT_TRUE(test_info == NULL) << "There should be no tests running at this point."; } }; // Tests that current_test_info() returns TestInfo for currently running // test by checking the expected test name against the actual one. TEST_F(CurrentTestInfoTest, WorksForFirstTestInATestCase) { const TestInfo* test_info = UnitTest::GetInstance()->current_test_info(); ASSERT_TRUE(NULL != test_info) << "There is a test running so we should have a valid TestInfo."; EXPECT_STREQ("CurrentTestInfoTest", test_info->test_case_name()) << "Expected the name of the currently running test case."; EXPECT_STREQ("WorksForFirstTestInATestCase", test_info->name()) << "Expected the name of the currently running test."; } // Tests that current_test_info() returns TestInfo for currently running // test by checking the expected test name against the actual one. We // use this test to see that the TestInfo object actually changed from // the previous invocation. TEST_F(CurrentTestInfoTest, WorksForSecondTestInATestCase) { const TestInfo* test_info = UnitTest::GetInstance()->current_test_info(); ASSERT_TRUE(NULL != test_info) << "There is a test running so we should have a valid TestInfo."; EXPECT_STREQ("CurrentTestInfoTest", test_info->test_case_name()) << "Expected the name of the currently running test case."; EXPECT_STREQ("WorksForSecondTestInATestCase", test_info->name()) << "Expected the name of the currently running test."; } } // namespace testing // These two lines test that we can define tests in a namespace that // has the name "testing" and is nested in another namespace. namespace my_namespace { namespace testing { // Makes sure that TEST knows to use ::testing::Test instead of // ::my_namespace::testing::Test. class Test {}; // Makes sure that an assertion knows to use ::testing::Message instead of // ::my_namespace::testing::Message. class Message {}; // Makes sure that an assertion knows to use // ::testing::AssertionResult instead of // ::my_namespace::testing::AssertionResult. class AssertionResult {}; // Tests that an assertion that should succeed works as expected. TEST(NestedTestingNamespaceTest, Success) { EXPECT_EQ(1, 1) << "This shouldn't fail."; } // Tests that an assertion that should fail works as expected. TEST(NestedTestingNamespaceTest, Failure) { EXPECT_FATAL_FAILURE(FAIL() << "This failure is expected.", "This failure is expected."); } } // namespace testing } // namespace my_namespace // Tests that one can call superclass SetUp and TearDown methods-- // that is, that they are not private. // No tests are based on this fixture; the test "passes" if it compiles // successfully. class ProtectedFixtureMethodsTest : public Test { protected: virtual void SetUp() { Test::SetUp(); } virtual void TearDown() { Test::TearDown(); } }; // StreamingAssertionsTest tests the streaming versions of a representative // sample of assertions. TEST(StreamingAssertionsTest, Unconditional) { SUCCEED() << "expected success"; EXPECT_NONFATAL_FAILURE(ADD_FAILURE() << "expected failure", "expected failure"); EXPECT_FATAL_FAILURE(FAIL() << "expected failure", "expected failure"); } #ifdef __BORLANDC__ // Silences warnings: "Condition is always true", "Unreachable code" # pragma option push -w-ccc -w-rch #endif TEST(StreamingAssertionsTest, Truth) { EXPECT_TRUE(true) << "unexpected failure"; ASSERT_TRUE(true) << "unexpected failure"; EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(false) << "expected failure", "expected failure"); EXPECT_FATAL_FAILURE(ASSERT_TRUE(false) << "expected failure", "expected failure"); } TEST(StreamingAssertionsTest, Truth2) { EXPECT_FALSE(false) << "unexpected failure"; ASSERT_FALSE(false) << "unexpected failure"; EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(true) << "expected failure", "expected failure"); EXPECT_FATAL_FAILURE(ASSERT_FALSE(true) << "expected failure", "expected failure"); } #ifdef __BORLANDC__ // Restores warnings after previous "#pragma option push" supressed them # pragma option pop #endif TEST(StreamingAssertionsTest, IntegerEquals) { EXPECT_EQ(1, 1) << "unexpected failure"; ASSERT_EQ(1, 1) << "unexpected failure"; EXPECT_NONFATAL_FAILURE(EXPECT_EQ(1, 2) << "expected failure", "expected failure"); EXPECT_FATAL_FAILURE(ASSERT_EQ(1, 2) << "expected failure", "expected failure"); } TEST(StreamingAssertionsTest, IntegerLessThan) { EXPECT_LT(1, 2) << "unexpected failure"; ASSERT_LT(1, 2) << "unexpected failure"; EXPECT_NONFATAL_FAILURE(EXPECT_LT(2, 1) << "expected failure", "expected failure"); EXPECT_FATAL_FAILURE(ASSERT_LT(2, 1) << "expected failure", "expected failure"); } TEST(StreamingAssertionsTest, StringsEqual) { EXPECT_STREQ("foo", "foo") << "unexpected failure"; ASSERT_STREQ("foo", "foo") << "unexpected failure"; EXPECT_NONFATAL_FAILURE(EXPECT_STREQ("foo", "bar") << "expected failure", "expected failure"); EXPECT_FATAL_FAILURE(ASSERT_STREQ("foo", "bar") << "expected failure", "expected failure"); } TEST(StreamingAssertionsTest, StringsNotEqual) { EXPECT_STRNE("foo", "bar") << "unexpected failure"; ASSERT_STRNE("foo", "bar") << "unexpected failure"; EXPECT_NONFATAL_FAILURE(EXPECT_STRNE("foo", "foo") << "expected failure", "expected failure"); EXPECT_FATAL_FAILURE(ASSERT_STRNE("foo", "foo") << "expected failure", "expected failure"); } TEST(StreamingAssertionsTest, StringsEqualIgnoringCase) { EXPECT_STRCASEEQ("foo", "FOO") << "unexpected failure"; ASSERT_STRCASEEQ("foo", "FOO") << "unexpected failure"; EXPECT_NONFATAL_FAILURE(EXPECT_STRCASEEQ("foo", "bar") << "expected failure", "expected failure"); EXPECT_FATAL_FAILURE(ASSERT_STRCASEEQ("foo", "bar") << "expected failure", "expected failure"); } TEST(StreamingAssertionsTest, StringNotEqualIgnoringCase) { EXPECT_STRCASENE("foo", "bar") << "unexpected failure"; ASSERT_STRCASENE("foo", "bar") << "unexpected failure"; EXPECT_NONFATAL_FAILURE(EXPECT_STRCASENE("foo", "FOO") << "expected failure", "expected failure"); EXPECT_FATAL_FAILURE(ASSERT_STRCASENE("bar", "BAR") << "expected failure", "expected failure"); } TEST(StreamingAssertionsTest, FloatingPointEquals) { EXPECT_FLOAT_EQ(1.0, 1.0) << "unexpected failure"; ASSERT_FLOAT_EQ(1.0, 1.0) << "unexpected failure"; EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(0.0, 1.0) << "expected failure", "expected failure"); EXPECT_FATAL_FAILURE(ASSERT_FLOAT_EQ(0.0, 1.0) << "expected failure", "expected failure"); } #if GTEST_HAS_EXCEPTIONS TEST(StreamingAssertionsTest, Throw) { EXPECT_THROW(ThrowAnInteger(), int) << "unexpected failure"; ASSERT_THROW(ThrowAnInteger(), int) << "unexpected failure"; EXPECT_NONFATAL_FAILURE(EXPECT_THROW(ThrowAnInteger(), bool) << "expected failure", "expected failure"); EXPECT_FATAL_FAILURE(ASSERT_THROW(ThrowAnInteger(), bool) << "expected failure", "expected failure"); } TEST(StreamingAssertionsTest, NoThrow) { EXPECT_NO_THROW(ThrowNothing()) << "unexpected failure"; ASSERT_NO_THROW(ThrowNothing()) << "unexpected failure"; EXPECT_NONFATAL_FAILURE(EXPECT_NO_THROW(ThrowAnInteger()) << "expected failure", "expected failure"); EXPECT_FATAL_FAILURE(ASSERT_NO_THROW(ThrowAnInteger()) << "expected failure", "expected failure"); } TEST(StreamingAssertionsTest, AnyThrow) { EXPECT_ANY_THROW(ThrowAnInteger()) << "unexpected failure"; ASSERT_ANY_THROW(ThrowAnInteger()) << "unexpected failure"; EXPECT_NONFATAL_FAILURE(EXPECT_ANY_THROW(ThrowNothing()) << "expected failure", "expected failure"); EXPECT_FATAL_FAILURE(ASSERT_ANY_THROW(ThrowNothing()) << "expected failure", "expected failure"); } #endif // GTEST_HAS_EXCEPTIONS // Tests that Google Test correctly decides whether to use colors in the output. TEST(ColoredOutputTest, UsesColorsWhenGTestColorFlagIsYes) { GTEST_FLAG(color) = "yes"; SetEnv("TERM", "xterm"); // TERM supports colors. EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY. EXPECT_TRUE(ShouldUseColor(false)); // Stdout is not a TTY. SetEnv("TERM", "dumb"); // TERM doesn't support colors. EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY. EXPECT_TRUE(ShouldUseColor(false)); // Stdout is not a TTY. } TEST(ColoredOutputTest, UsesColorsWhenGTestColorFlagIsAliasOfYes) { SetEnv("TERM", "dumb"); // TERM doesn't support colors. GTEST_FLAG(color) = "True"; EXPECT_TRUE(ShouldUseColor(false)); // Stdout is not a TTY. GTEST_FLAG(color) = "t"; EXPECT_TRUE(ShouldUseColor(false)); // Stdout is not a TTY. GTEST_FLAG(color) = "1"; EXPECT_TRUE(ShouldUseColor(false)); // Stdout is not a TTY. } TEST(ColoredOutputTest, UsesNoColorWhenGTestColorFlagIsNo) { GTEST_FLAG(color) = "no"; SetEnv("TERM", "xterm"); // TERM supports colors. EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY. EXPECT_FALSE(ShouldUseColor(false)); // Stdout is not a TTY. SetEnv("TERM", "dumb"); // TERM doesn't support colors. EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY. EXPECT_FALSE(ShouldUseColor(false)); // Stdout is not a TTY. } TEST(ColoredOutputTest, UsesNoColorWhenGTestColorFlagIsInvalid) { SetEnv("TERM", "xterm"); // TERM supports colors. GTEST_FLAG(color) = "F"; EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY. GTEST_FLAG(color) = "0"; EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY. GTEST_FLAG(color) = "unknown"; EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY. } TEST(ColoredOutputTest, UsesColorsWhenStdoutIsTty) { GTEST_FLAG(color) = "auto"; SetEnv("TERM", "xterm"); // TERM supports colors. EXPECT_FALSE(ShouldUseColor(false)); // Stdout is not a TTY. EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY. } TEST(ColoredOutputTest, UsesColorsWhenTermSupportsColors) { GTEST_FLAG(color) = "auto"; #if GTEST_OS_WINDOWS // On Windows, we ignore the TERM variable as it's usually not set. SetEnv("TERM", "dumb"); EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY. SetEnv("TERM", ""); EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY. SetEnv("TERM", "xterm"); EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY. #else // On non-Windows platforms, we rely on TERM to determine if the // terminal supports colors. SetEnv("TERM", "dumb"); // TERM doesn't support colors. EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY. SetEnv("TERM", "emacs"); // TERM doesn't support colors. EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY. SetEnv("TERM", "vt100"); // TERM doesn't support colors. EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY. SetEnv("TERM", "xterm-mono"); // TERM doesn't support colors. EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY. SetEnv("TERM", "xterm"); // TERM supports colors. EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY. SetEnv("TERM", "xterm-color"); // TERM supports colors. EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY. SetEnv("TERM", "xterm-256color"); // TERM supports colors. EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY. SetEnv("TERM", "screen"); // TERM supports colors. EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY. SetEnv("TERM", "linux"); // TERM supports colors. EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY. SetEnv("TERM", "cygwin"); // TERM supports colors. EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY. #endif // GTEST_OS_WINDOWS } // Verifies that StaticAssertTypeEq works in a namespace scope. static bool dummy1 GTEST_ATTRIBUTE_UNUSED_ = StaticAssertTypeEq(); static bool dummy2 GTEST_ATTRIBUTE_UNUSED_ = StaticAssertTypeEq(); // Verifies that StaticAssertTypeEq works in a class. template class StaticAssertTypeEqTestHelper { public: StaticAssertTypeEqTestHelper() { StaticAssertTypeEq(); } }; TEST(StaticAssertTypeEqTest, WorksInClass) { StaticAssertTypeEqTestHelper(); } // Verifies that StaticAssertTypeEq works inside a function. typedef int IntAlias; TEST(StaticAssertTypeEqTest, CompilesForEqualTypes) { StaticAssertTypeEq(); StaticAssertTypeEq(); } TEST(GetCurrentOsStackTraceExceptTopTest, ReturnsTheStackTrace) { testing::UnitTest* const unit_test = testing::UnitTest::GetInstance(); // We don't have a stack walker in Google Test yet. EXPECT_STREQ("", GetCurrentOsStackTraceExceptTop(unit_test, 0).c_str()); EXPECT_STREQ("", GetCurrentOsStackTraceExceptTop(unit_test, 1).c_str()); } TEST(HasNonfatalFailureTest, ReturnsFalseWhenThereIsNoFailure) { EXPECT_FALSE(HasNonfatalFailure()); } static void FailFatally() { FAIL(); } TEST(HasNonfatalFailureTest, ReturnsFalseWhenThereIsOnlyFatalFailure) { FailFatally(); const bool has_nonfatal_failure = HasNonfatalFailure(); ClearCurrentTestPartResults(); EXPECT_FALSE(has_nonfatal_failure); } TEST(HasNonfatalFailureTest, ReturnsTrueWhenThereIsNonfatalFailure) { ADD_FAILURE(); const bool has_nonfatal_failure = HasNonfatalFailure(); ClearCurrentTestPartResults(); EXPECT_TRUE(has_nonfatal_failure); } TEST(HasNonfatalFailureTest, ReturnsTrueWhenThereAreFatalAndNonfatalFailures) { FailFatally(); ADD_FAILURE(); const bool has_nonfatal_failure = HasNonfatalFailure(); ClearCurrentTestPartResults(); EXPECT_TRUE(has_nonfatal_failure); } // A wrapper for calling HasNonfatalFailure outside of a test body. static bool HasNonfatalFailureHelper() { return testing::Test::HasNonfatalFailure(); } TEST(HasNonfatalFailureTest, WorksOutsideOfTestBody) { EXPECT_FALSE(HasNonfatalFailureHelper()); } TEST(HasNonfatalFailureTest, WorksOutsideOfTestBody2) { ADD_FAILURE(); const bool has_nonfatal_failure = HasNonfatalFailureHelper(); ClearCurrentTestPartResults(); EXPECT_TRUE(has_nonfatal_failure); } TEST(HasFailureTest, ReturnsFalseWhenThereIsNoFailure) { EXPECT_FALSE(HasFailure()); } TEST(HasFailureTest, ReturnsTrueWhenThereIsFatalFailure) { FailFatally(); const bool has_failure = HasFailure(); ClearCurrentTestPartResults(); EXPECT_TRUE(has_failure); } TEST(HasFailureTest, ReturnsTrueWhenThereIsNonfatalFailure) { ADD_FAILURE(); const bool has_failure = HasFailure(); ClearCurrentTestPartResults(); EXPECT_TRUE(has_failure); } TEST(HasFailureTest, ReturnsTrueWhenThereAreFatalAndNonfatalFailures) { FailFatally(); ADD_FAILURE(); const bool has_failure = HasFailure(); ClearCurrentTestPartResults(); EXPECT_TRUE(has_failure); } // A wrapper for calling HasFailure outside of a test body. static bool HasFailureHelper() { return testing::Test::HasFailure(); } TEST(HasFailureTest, WorksOutsideOfTestBody) { EXPECT_FALSE(HasFailureHelper()); } TEST(HasFailureTest, WorksOutsideOfTestBody2) { ADD_FAILURE(); const bool has_failure = HasFailureHelper(); ClearCurrentTestPartResults(); EXPECT_TRUE(has_failure); } class TestListener : public EmptyTestEventListener { public: TestListener() : on_start_counter_(NULL), is_destroyed_(NULL) {} TestListener(int* on_start_counter, bool* is_destroyed) : on_start_counter_(on_start_counter), is_destroyed_(is_destroyed) {} virtual ~TestListener() { if (is_destroyed_) *is_destroyed_ = true; } protected: virtual void OnTestProgramStart(const UnitTest& /*unit_test*/) { if (on_start_counter_ != NULL) (*on_start_counter_)++; } private: int* on_start_counter_; bool* is_destroyed_; }; // Tests the constructor. TEST(TestEventListenersTest, ConstructionWorks) { TestEventListeners listeners; EXPECT_TRUE(TestEventListenersAccessor::GetRepeater(&listeners) != NULL); EXPECT_TRUE(listeners.default_result_printer() == NULL); EXPECT_TRUE(listeners.default_xml_generator() == NULL); } // Tests that the TestEventListeners destructor deletes all the listeners it // owns. TEST(TestEventListenersTest, DestructionWorks) { bool default_result_printer_is_destroyed = false; bool default_xml_printer_is_destroyed = false; bool extra_listener_is_destroyed = false; TestListener* default_result_printer = new TestListener( NULL, &default_result_printer_is_destroyed); TestListener* default_xml_printer = new TestListener( NULL, &default_xml_printer_is_destroyed); TestListener* extra_listener = new TestListener( NULL, &extra_listener_is_destroyed); { TestEventListeners listeners; TestEventListenersAccessor::SetDefaultResultPrinter(&listeners, default_result_printer); TestEventListenersAccessor::SetDefaultXmlGenerator(&listeners, default_xml_printer); listeners.Append(extra_listener); } EXPECT_TRUE(default_result_printer_is_destroyed); EXPECT_TRUE(default_xml_printer_is_destroyed); EXPECT_TRUE(extra_listener_is_destroyed); } // Tests that a listener Append'ed to a TestEventListeners list starts // receiving events. TEST(TestEventListenersTest, Append) { int on_start_counter = 0; bool is_destroyed = false; TestListener* listener = new TestListener(&on_start_counter, &is_destroyed); { TestEventListeners listeners; listeners.Append(listener); TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart( *UnitTest::GetInstance()); EXPECT_EQ(1, on_start_counter); } EXPECT_TRUE(is_destroyed); } // Tests that listeners receive events in the order they were appended to // the list, except for *End requests, which must be received in the reverse // order. class SequenceTestingListener : public EmptyTestEventListener { public: SequenceTestingListener(std::vector* vector, const char* id) : vector_(vector), id_(id) {} protected: virtual void OnTestProgramStart(const UnitTest& /*unit_test*/) { vector_->push_back(GetEventDescription("OnTestProgramStart")); } virtual void OnTestProgramEnd(const UnitTest& /*unit_test*/) { vector_->push_back(GetEventDescription("OnTestProgramEnd")); } virtual void OnTestIterationStart(const UnitTest& /*unit_test*/, int /*iteration*/) { vector_->push_back(GetEventDescription("OnTestIterationStart")); } virtual void OnTestIterationEnd(const UnitTest& /*unit_test*/, int /*iteration*/) { vector_->push_back(GetEventDescription("OnTestIterationEnd")); } private: String GetEventDescription(const char* method) { Message message; message << id_ << "." << method; return message.GetString(); } std::vector* vector_; const char* const id_; GTEST_DISALLOW_COPY_AND_ASSIGN_(SequenceTestingListener); }; TEST(EventListenerTest, AppendKeepsOrder) { std::vector vec; TestEventListeners listeners; listeners.Append(new SequenceTestingListener(&vec, "1st")); listeners.Append(new SequenceTestingListener(&vec, "2nd")); listeners.Append(new SequenceTestingListener(&vec, "3rd")); TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart( *UnitTest::GetInstance()); ASSERT_EQ(3U, vec.size()); EXPECT_STREQ("1st.OnTestProgramStart", vec[0].c_str()); EXPECT_STREQ("2nd.OnTestProgramStart", vec[1].c_str()); EXPECT_STREQ("3rd.OnTestProgramStart", vec[2].c_str()); vec.clear(); TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramEnd( *UnitTest::GetInstance()); ASSERT_EQ(3U, vec.size()); EXPECT_STREQ("3rd.OnTestProgramEnd", vec[0].c_str()); EXPECT_STREQ("2nd.OnTestProgramEnd", vec[1].c_str()); EXPECT_STREQ("1st.OnTestProgramEnd", vec[2].c_str()); vec.clear(); TestEventListenersAccessor::GetRepeater(&listeners)->OnTestIterationStart( *UnitTest::GetInstance(), 0); ASSERT_EQ(3U, vec.size()); EXPECT_STREQ("1st.OnTestIterationStart", vec[0].c_str()); EXPECT_STREQ("2nd.OnTestIterationStart", vec[1].c_str()); EXPECT_STREQ("3rd.OnTestIterationStart", vec[2].c_str()); vec.clear(); TestEventListenersAccessor::GetRepeater(&listeners)->OnTestIterationEnd( *UnitTest::GetInstance(), 0); ASSERT_EQ(3U, vec.size()); EXPECT_STREQ("3rd.OnTestIterationEnd", vec[0].c_str()); EXPECT_STREQ("2nd.OnTestIterationEnd", vec[1].c_str()); EXPECT_STREQ("1st.OnTestIterationEnd", vec[2].c_str()); } // Tests that a listener removed from a TestEventListeners list stops receiving // events and is not deleted when the list is destroyed. TEST(TestEventListenersTest, Release) { int on_start_counter = 0; bool is_destroyed = false; // Although Append passes the ownership of this object to the list, // the following calls release it, and we need to delete it before the // test ends. TestListener* listener = new TestListener(&on_start_counter, &is_destroyed); { TestEventListeners listeners; listeners.Append(listener); EXPECT_EQ(listener, listeners.Release(listener)); TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart( *UnitTest::GetInstance()); EXPECT_TRUE(listeners.Release(listener) == NULL); } EXPECT_EQ(0, on_start_counter); EXPECT_FALSE(is_destroyed); delete listener; } // Tests that no events are forwarded when event forwarding is disabled. TEST(EventListenerTest, SuppressEventForwarding) { int on_start_counter = 0; TestListener* listener = new TestListener(&on_start_counter, NULL); TestEventListeners listeners; listeners.Append(listener); ASSERT_TRUE(TestEventListenersAccessor::EventForwardingEnabled(listeners)); TestEventListenersAccessor::SuppressEventForwarding(&listeners); ASSERT_FALSE(TestEventListenersAccessor::EventForwardingEnabled(listeners)); TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart( *UnitTest::GetInstance()); EXPECT_EQ(0, on_start_counter); } // Tests that events generated by Google Test are not forwarded in // death test subprocesses. TEST(EventListenerDeathTest, EventsNotForwardedInDeathTestSubprecesses) { EXPECT_DEATH_IF_SUPPORTED({ GTEST_CHECK_(TestEventListenersAccessor::EventForwardingEnabled( *GetUnitTestImpl()->listeners())) << "expected failure";}, "expected failure"); } // Tests that a listener installed via SetDefaultResultPrinter() starts // receiving events and is returned via default_result_printer() and that // the previous default_result_printer is removed from the list and deleted. TEST(EventListenerTest, default_result_printer) { int on_start_counter = 0; bool is_destroyed = false; TestListener* listener = new TestListener(&on_start_counter, &is_destroyed); TestEventListeners listeners; TestEventListenersAccessor::SetDefaultResultPrinter(&listeners, listener); EXPECT_EQ(listener, listeners.default_result_printer()); TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart( *UnitTest::GetInstance()); EXPECT_EQ(1, on_start_counter); // Replacing default_result_printer with something else should remove it // from the list and destroy it. TestEventListenersAccessor::SetDefaultResultPrinter(&listeners, NULL); EXPECT_TRUE(listeners.default_result_printer() == NULL); EXPECT_TRUE(is_destroyed); // After broadcasting an event the counter is still the same, indicating // the listener is not in the list anymore. TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart( *UnitTest::GetInstance()); EXPECT_EQ(1, on_start_counter); } // Tests that the default_result_printer listener stops receiving events // when removed via Release and that is not owned by the list anymore. TEST(EventListenerTest, RemovingDefaultResultPrinterWorks) { int on_start_counter = 0; bool is_destroyed = false; // Although Append passes the ownership of this object to the list, // the following calls release it, and we need to delete it before the // test ends. TestListener* listener = new TestListener(&on_start_counter, &is_destroyed); { TestEventListeners listeners; TestEventListenersAccessor::SetDefaultResultPrinter(&listeners, listener); EXPECT_EQ(listener, listeners.Release(listener)); EXPECT_TRUE(listeners.default_result_printer() == NULL); EXPECT_FALSE(is_destroyed); // Broadcasting events now should not affect default_result_printer. TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart( *UnitTest::GetInstance()); EXPECT_EQ(0, on_start_counter); } // Destroying the list should not affect the listener now, too. EXPECT_FALSE(is_destroyed); delete listener; } // Tests that a listener installed via SetDefaultXmlGenerator() starts // receiving events and is returned via default_xml_generator() and that // the previous default_xml_generator is removed from the list and deleted. TEST(EventListenerTest, default_xml_generator) { int on_start_counter = 0; bool is_destroyed = false; TestListener* listener = new TestListener(&on_start_counter, &is_destroyed); TestEventListeners listeners; TestEventListenersAccessor::SetDefaultXmlGenerator(&listeners, listener); EXPECT_EQ(listener, listeners.default_xml_generator()); TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart( *UnitTest::GetInstance()); EXPECT_EQ(1, on_start_counter); // Replacing default_xml_generator with something else should remove it // from the list and destroy it. TestEventListenersAccessor::SetDefaultXmlGenerator(&listeners, NULL); EXPECT_TRUE(listeners.default_xml_generator() == NULL); EXPECT_TRUE(is_destroyed); // After broadcasting an event the counter is still the same, indicating // the listener is not in the list anymore. TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart( *UnitTest::GetInstance()); EXPECT_EQ(1, on_start_counter); } // Tests that the default_xml_generator listener stops receiving events // when removed via Release and that is not owned by the list anymore. TEST(EventListenerTest, RemovingDefaultXmlGeneratorWorks) { int on_start_counter = 0; bool is_destroyed = false; // Although Append passes the ownership of this object to the list, // the following calls release it, and we need to delete it before the // test ends. TestListener* listener = new TestListener(&on_start_counter, &is_destroyed); { TestEventListeners listeners; TestEventListenersAccessor::SetDefaultXmlGenerator(&listeners, listener); EXPECT_EQ(listener, listeners.Release(listener)); EXPECT_TRUE(listeners.default_xml_generator() == NULL); EXPECT_FALSE(is_destroyed); // Broadcasting events now should not affect default_xml_generator. TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart( *UnitTest::GetInstance()); EXPECT_EQ(0, on_start_counter); } // Destroying the list should not affect the listener now, too. EXPECT_FALSE(is_destroyed); delete listener; } // Sanity tests to ensure that the alternative, verbose spellings of // some of the macros work. We don't test them thoroughly as that // would be quite involved. Since their implementations are // straightforward, and they are rarely used, we'll just rely on the // users to tell us when they are broken. GTEST_TEST(AlternativeNameTest, Works) { // GTEST_TEST is the same as TEST. GTEST_SUCCEED() << "OK"; // GTEST_SUCCEED is the same as SUCCEED. // GTEST_FAIL is the same as FAIL. EXPECT_FATAL_FAILURE(GTEST_FAIL() << "An expected failure", "An expected failure"); // GTEST_ASSERT_XY is the same as ASSERT_XY. GTEST_ASSERT_EQ(0, 0); EXPECT_FATAL_FAILURE(GTEST_ASSERT_EQ(0, 1) << "An expected failure", "An expected failure"); EXPECT_FATAL_FAILURE(GTEST_ASSERT_EQ(1, 0) << "An expected failure", "An expected failure"); GTEST_ASSERT_NE(0, 1); GTEST_ASSERT_NE(1, 0); EXPECT_FATAL_FAILURE(GTEST_ASSERT_NE(0, 0) << "An expected failure", "An expected failure"); GTEST_ASSERT_LE(0, 0); GTEST_ASSERT_LE(0, 1); EXPECT_FATAL_FAILURE(GTEST_ASSERT_LE(1, 0) << "An expected failure", "An expected failure"); GTEST_ASSERT_LT(0, 1); EXPECT_FATAL_FAILURE(GTEST_ASSERT_LT(0, 0) << "An expected failure", "An expected failure"); EXPECT_FATAL_FAILURE(GTEST_ASSERT_LT(1, 0) << "An expected failure", "An expected failure"); GTEST_ASSERT_GE(0, 0); GTEST_ASSERT_GE(1, 0); EXPECT_FATAL_FAILURE(GTEST_ASSERT_GE(0, 1) << "An expected failure", "An expected failure"); GTEST_ASSERT_GT(1, 0); EXPECT_FATAL_FAILURE(GTEST_ASSERT_GT(0, 1) << "An expected failure", "An expected failure"); EXPECT_FATAL_FAILURE(GTEST_ASSERT_GT(1, 1) << "An expected failure", "An expected failure"); } // Tests for internal utilities necessary for implementation of the universal // printing. // TODO(vladl@google.com): Find a better home for them. class ConversionHelperBase {}; class ConversionHelperDerived : public ConversionHelperBase {}; // Tests that IsAProtocolMessage::value is a compile-time constant. TEST(IsAProtocolMessageTest, ValueIsCompileTimeConstant) { GTEST_COMPILE_ASSERT_(IsAProtocolMessage::value, const_true); GTEST_COMPILE_ASSERT_(!IsAProtocolMessage::value, const_false); } // Tests that IsAProtocolMessage::value is true when T is // proto2::Message or a sub-class of it. TEST(IsAProtocolMessageTest, ValueIsTrueWhenTypeIsAProtocolMessage) { EXPECT_TRUE(IsAProtocolMessage< ::proto2::Message>::value); EXPECT_TRUE(IsAProtocolMessage::value); } // Tests that IsAProtocolMessage::value is false when T is neither // ProtocolMessage nor a sub-class of it. TEST(IsAProtocolMessageTest, ValueIsFalseWhenTypeIsNotAProtocolMessage) { EXPECT_FALSE(IsAProtocolMessage::value); EXPECT_FALSE(IsAProtocolMessage::value); } // Tests that CompileAssertTypesEqual compiles when the type arguments are // equal. TEST(CompileAssertTypesEqual, CompilesWhenTypesAreEqual) { CompileAssertTypesEqual(); CompileAssertTypesEqual(); } // Tests that RemoveReference does not affect non-reference types. TEST(RemoveReferenceTest, DoesNotAffectNonReferenceType) { CompileAssertTypesEqual::type>(); CompileAssertTypesEqual::type>(); } // Tests that RemoveReference removes reference from reference types. TEST(RemoveReferenceTest, RemovesReference) { CompileAssertTypesEqual::type>(); CompileAssertTypesEqual::type>(); } // Tests GTEST_REMOVE_REFERENCE_. template void TestGTestRemoveReference() { CompileAssertTypesEqual(); } TEST(RemoveReferenceTest, MacroVersion) { TestGTestRemoveReference(); TestGTestRemoveReference(); } // Tests that RemoveConst does not affect non-const types. TEST(RemoveConstTest, DoesNotAffectNonConstType) { CompileAssertTypesEqual::type>(); CompileAssertTypesEqual::type>(); } // Tests that RemoveConst removes const from const types. TEST(RemoveConstTest, RemovesConst) { CompileAssertTypesEqual::type>(); CompileAssertTypesEqual::type>(); CompileAssertTypesEqual::type>(); } // Tests GTEST_REMOVE_CONST_. template void TestGTestRemoveConst() { CompileAssertTypesEqual(); } TEST(RemoveConstTest, MacroVersion) { TestGTestRemoveConst(); TestGTestRemoveConst(); TestGTestRemoveConst(); } // Tests GTEST_REMOVE_REFERENCE_AND_CONST_. template void TestGTestRemoveReferenceAndConst() { CompileAssertTypesEqual(); } TEST(RemoveReferenceToConstTest, Works) { TestGTestRemoveReferenceAndConst(); TestGTestRemoveReferenceAndConst(); TestGTestRemoveReferenceAndConst(); TestGTestRemoveReferenceAndConst(); TestGTestRemoveReferenceAndConst(); } // Tests that AddReference does not affect reference types. TEST(AddReferenceTest, DoesNotAffectReferenceType) { CompileAssertTypesEqual::type>(); CompileAssertTypesEqual::type>(); } // Tests that AddReference adds reference to non-reference types. TEST(AddReferenceTest, AddsReference) { CompileAssertTypesEqual::type>(); CompileAssertTypesEqual::type>(); } // Tests GTEST_ADD_REFERENCE_. template void TestGTestAddReference() { CompileAssertTypesEqual(); } TEST(AddReferenceTest, MacroVersion) { TestGTestAddReference(); TestGTestAddReference(); } // Tests GTEST_REFERENCE_TO_CONST_. template void TestGTestReferenceToConst() { CompileAssertTypesEqual(); } TEST(GTestReferenceToConstTest, Works) { TestGTestReferenceToConst(); TestGTestReferenceToConst(); TestGTestReferenceToConst(); TestGTestReferenceToConst(); } // Tests that ImplicitlyConvertible::value is a compile-time constant. TEST(ImplicitlyConvertibleTest, ValueIsCompileTimeConstant) { GTEST_COMPILE_ASSERT_((ImplicitlyConvertible::value), const_true); GTEST_COMPILE_ASSERT_((!ImplicitlyConvertible::value), const_false); } // Tests that ImplicitlyConvertible::value is true when T1 can // be implicitly converted to T2. TEST(ImplicitlyConvertibleTest, ValueIsTrueWhenConvertible) { EXPECT_TRUE((ImplicitlyConvertible::value)); EXPECT_TRUE((ImplicitlyConvertible::value)); EXPECT_TRUE((ImplicitlyConvertible::value)); EXPECT_TRUE((ImplicitlyConvertible::value)); EXPECT_TRUE((ImplicitlyConvertible::value)); EXPECT_TRUE((ImplicitlyConvertible::value)); } // Tests that ImplicitlyConvertible::value is false when T1 // cannot be implicitly converted to T2. TEST(ImplicitlyConvertibleTest, ValueIsFalseWhenNotConvertible) { EXPECT_FALSE((ImplicitlyConvertible::value)); EXPECT_FALSE((ImplicitlyConvertible::value)); EXPECT_FALSE((ImplicitlyConvertible::value)); EXPECT_FALSE((ImplicitlyConvertible::value)); } // Tests IsContainerTest. class NonContainer {}; TEST(IsContainerTestTest, WorksForNonContainer) { EXPECT_EQ(sizeof(IsNotContainer), sizeof(IsContainerTest(0))); EXPECT_EQ(sizeof(IsNotContainer), sizeof(IsContainerTest(0))); EXPECT_EQ(sizeof(IsNotContainer), sizeof(IsContainerTest(0))); } TEST(IsContainerTestTest, WorksForContainer) { EXPECT_EQ(sizeof(IsContainer), sizeof(IsContainerTest >(0))); EXPECT_EQ(sizeof(IsContainer), sizeof(IsContainerTest >(0))); } // Tests ArrayEq(). TEST(ArrayEqTest, WorksForDegeneratedArrays) { EXPECT_TRUE(ArrayEq(5, 5L)); EXPECT_FALSE(ArrayEq('a', 0)); } TEST(ArrayEqTest, WorksForOneDimensionalArrays) { const int a[] = { 0, 1 }; long b[] = { 0, 1 }; EXPECT_TRUE(ArrayEq(a, b)); EXPECT_TRUE(ArrayEq(a, 2, b)); b[0] = 2; EXPECT_FALSE(ArrayEq(a, b)); EXPECT_FALSE(ArrayEq(a, 1, b)); } TEST(ArrayEqTest, WorksForTwoDimensionalArrays) { const char a[][3] = { "hi", "lo" }; const char b[][3] = { "hi", "lo" }; const char c[][3] = { "hi", "li" }; EXPECT_TRUE(ArrayEq(a, b)); EXPECT_TRUE(ArrayEq(a, 2, b)); EXPECT_FALSE(ArrayEq(a, c)); EXPECT_FALSE(ArrayEq(a, 2, c)); } // Tests ArrayAwareFind(). TEST(ArrayAwareFindTest, WorksForOneDimensionalArray) { const char a[] = "hello"; EXPECT_EQ(a + 4, ArrayAwareFind(a, a + 5, 'o')); EXPECT_EQ(a + 5, ArrayAwareFind(a, a + 5, 'x')); } TEST(ArrayAwareFindTest, WorksForTwoDimensionalArray) { int a[][2] = { { 0, 1 }, { 2, 3 }, { 4, 5 } }; const int b[2] = { 2, 3 }; EXPECT_EQ(a + 1, ArrayAwareFind(a, a + 3, b)); const int c[2] = { 6, 7 }; EXPECT_EQ(a + 3, ArrayAwareFind(a, a + 3, c)); } // Tests CopyArray(). TEST(CopyArrayTest, WorksForDegeneratedArrays) { int n = 0; CopyArray('a', &n); EXPECT_EQ('a', n); } TEST(CopyArrayTest, WorksForOneDimensionalArrays) { const char a[3] = "hi"; int b[3]; #ifndef __BORLANDC__ // C++Builder cannot compile some array size deductions. CopyArray(a, &b); EXPECT_TRUE(ArrayEq(a, b)); #endif int c[3]; CopyArray(a, 3, c); EXPECT_TRUE(ArrayEq(a, c)); } TEST(CopyArrayTest, WorksForTwoDimensionalArrays) { const int a[2][3] = { { 0, 1, 2 }, { 3, 4, 5 } }; int b[2][3]; #ifndef __BORLANDC__ // C++Builder cannot compile some array size deductions. CopyArray(a, &b); EXPECT_TRUE(ArrayEq(a, b)); #endif int c[2][3]; CopyArray(a, 2, c); EXPECT_TRUE(ArrayEq(a, c)); } // Tests NativeArray. TEST(NativeArrayTest, ConstructorFromArrayWorks) { const int a[3] = { 0, 1, 2 }; NativeArray na(a, 3, kReference); EXPECT_EQ(3U, na.size()); EXPECT_EQ(a, na.begin()); } TEST(NativeArrayTest, CreatesAndDeletesCopyOfArrayWhenAskedTo) { typedef int Array[2]; Array* a = new Array[1]; (*a)[0] = 0; (*a)[1] = 1; NativeArray na(*a, 2, kCopy); EXPECT_NE(*a, na.begin()); delete[] a; EXPECT_EQ(0, na.begin()[0]); EXPECT_EQ(1, na.begin()[1]); // We rely on the heap checker to verify that na deletes the copy of // array. } TEST(NativeArrayTest, TypeMembersAreCorrect) { StaticAssertTypeEq::value_type>(); StaticAssertTypeEq::value_type>(); StaticAssertTypeEq::const_iterator>(); StaticAssertTypeEq::const_iterator>(); } TEST(NativeArrayTest, MethodsWork) { const int a[3] = { 0, 1, 2 }; NativeArray na(a, 3, kCopy); ASSERT_EQ(3U, na.size()); EXPECT_EQ(3, na.end() - na.begin()); NativeArray::const_iterator it = na.begin(); EXPECT_EQ(0, *it); ++it; EXPECT_EQ(1, *it); it++; EXPECT_EQ(2, *it); ++it; EXPECT_EQ(na.end(), it); EXPECT_TRUE(na == na); NativeArray na2(a, 3, kReference); EXPECT_TRUE(na == na2); const int b1[3] = { 0, 1, 1 }; const int b2[4] = { 0, 1, 2, 3 }; EXPECT_FALSE(na == NativeArray(b1, 3, kReference)); EXPECT_FALSE(na == NativeArray(b2, 4, kCopy)); } TEST(NativeArrayTest, WorksForTwoDimensionalArray) { const char a[2][3] = { "hi", "lo" }; NativeArray na(a, 2, kReference); ASSERT_EQ(2U, na.size()); EXPECT_EQ(a, na.begin()); } // Tests SkipPrefix(). TEST(SkipPrefixTest, SkipsWhenPrefixMatches) { const char* const str = "hello"; const char* p = str; EXPECT_TRUE(SkipPrefix("", &p)); EXPECT_EQ(str, p); p = str; EXPECT_TRUE(SkipPrefix("hell", &p)); EXPECT_EQ(str + 4, p); } TEST(SkipPrefixTest, DoesNotSkipWhenPrefixDoesNotMatch) { const char* const str = "world"; const char* p = str; EXPECT_FALSE(SkipPrefix("W", &p)); EXPECT_EQ(str, p); p = str; EXPECT_FALSE(SkipPrefix("world!", &p)); EXPECT_EQ(str, p); } ugene-1.9.8/src/libs_3rdparty/gtest/src/test/0000755000175000017500000000000011651544307017564 5ustar ilyailyaugene-1.9.8/src/libs_3rdparty/gtest/src/test/production.h0000644000175000017500000000417411651544307022131 0ustar ilyailya// Copyright 2006, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Author: wan@google.com (Zhanyong Wan) // // This is part of the unit test for include/gtest/gtest_prod.h. #ifndef GTEST_TEST_PRODUCTION_H_ #define GTEST_TEST_PRODUCTION_H_ #include "gtest/gtest_prod.h" class PrivateCode { public: // Declares a friend test that does not use a fixture. FRIEND_TEST(PrivateCodeTest, CanAccessPrivateMembers); // Declares a friend test that uses a fixture. FRIEND_TEST(PrivateCodeFixtureTest, CanAccessPrivateMembers); PrivateCode(); int x() const { return x_; } private: void set_x(int an_x) { x_ = an_x; } int x_; }; #endif // GTEST_TEST_PRODUCTION_H_ ugene-1.9.8/src/libs_3rdparty/gtest/src/test/production.cc0000644000175000017500000000330411651544307022261 0ustar ilyailya// Copyright 2006, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Author: wan@google.com (Zhanyong Wan) // // This is part of the unit test for include/gtest/gtest_prod.h. #include "production.h" PrivateCode::PrivateCode() : x_(0) {} ugene-1.9.8/src/libs_3rdparty/gtest/src/gtest_main.cc0000644000175000017500000000347611651544307021260 0ustar ilyailya// Copyright 2006, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include //#define GTEST_CREATE_SHARED_LIBRARY 1 //#define GTEST_LINKED_AS_SHARED_LIBRARY 1 #include "gtest/gtest.h" GTEST_API_ int main(int argc, char **argv) { std::cout << "Running main() from gtest_main.cc\n"; testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); } ugene-1.9.8/src/libs_3rdparty/gtest/gtest.pro0000644000175000017500000000267611651544307017701 0ustar ilyailyainclude (gtest.pri) # Input HEADERS += src/gtest/gtest-death-test.h \ src/gtest/gtest-message.h \ src/gtest/gtest-param-test.h \ src/gtest/gtest-printers.h \ src/gtest/gtest-spi.h \ src/gtest/gtest-test-part.h \ src/gtest/gtest-typed-test.h \ src/gtest/gtest.h \ src/gtest/gtest_pred_impl.h \ src/gtest/gtest_prod.h \ src/src/gtest-internal-inl.h \ src/test/production.h \ src/gtest/internal/gtest-death-test-internal.h \ src/gtest/internal/gtest-filepath.h \ src/gtest/internal/gtest-internal.h \ src/gtest/internal/gtest-linked_ptr.h \ src/gtest/internal/gtest-param-util-generated.h \ src/gtest/internal/gtest-param-util.h \ src/gtest/internal/gtest-port.h \ src/gtest/internal/gtest-string.h \ src/gtest/internal/gtest-tuple.h \ src/gtest/internal/gtest-type-util.h SOURCES += src/gtest-all.cc \ src/gtest_main.cc \ src/gtest_prod_test.cc \ src/gtest_unittest.cc \ src/src/gtest-death-test.cc \ src/src/gtest-filepath.cc \ src/src/gtest-port.cc \ src/src/gtest-printers.cc \ src/src/gtest-test-part.cc \ src/src/gtest-typed-test.cc \ src/src/gtest.cc \ src/test/production.cc ugene-1.9.8/src/libs_3rdparty/qscore/0000755000175000017500000000000011651544307016164 5ustar ilyailyaugene-1.9.8/src/libs_3rdparty/qscore/qscore.pro0000644000175000017500000000205611651544307020205 0ustar ilyailyainclude (qscore.pri) # Input HEADERS += src/QScoreAdapter.h \ src/qscore/msa.h \ src/qscore/qscore.h \ src/qscore/qscore_context.h \ src/qscore/sab_ids.h \ src/qscore/sab_ref2.h \ src/qscore/seq.h SOURCES += src/QScoreAdapter.cpp \ src/qscore/qscore_clineshift.cpp \ src/qscore/qscore_comparemap.cpp \ src/qscore/qscore_comparemsa.cpp \ src/qscore/qscore_comparepair.cpp \ src/qscore/qscore_context.cpp \ src/qscore/qscore_fasta.cpp \ src/qscore/qscore_fastq.cpp \ src/qscore/qscore_gapscore.cpp \ src/qscore/qscore_gapscore2.cpp \ src/qscore/qscore_msa_qscore.cpp \ src/qscore/qscore_options.cpp \ src/qscore/qscore_perseq.cpp \ src/qscore/qscore_qscore.cpp \ src/qscore/qscore_sab.cpp \ src/qscore/qscore_seq.cpp \ src/qscore/qscore_sumpairs.cpp \ src/qscore/qscore_tc.cpp \ src/qscore/qscore_utils.cpp ugene-1.9.8/src/libs_3rdparty/qscore/src/0000755000175000017500000000000011651544307016753 5ustar ilyailyaugene-1.9.8/src/libs_3rdparty/qscore/src/qscore/0000755000175000017500000000000011651544307020247 5ustar ilyailyaugene-1.9.8/src/libs_3rdparty/qscore/src/qscore/qscore_msa_qscore.cpp0000644000175000017500000001473411651544307024474 0ustar ilyailya#include "qscore.h" MSA_QScore::MSA_QScore() { m_uSeqCount = 0; m_uColCount = 0; m_uCacheSeqCount = 0; m_szSeqs = 0; //m_szNames = 0; m_SeqBuffer = 0; m_UngapMap = 0; m_GapMap = 0; m_SeqLengths = 0; } MSA_QScore::~MSA_QScore() { Free(); } void MSA_QScore::Free() { if (0 != m_UngapMap) for (unsigned n = 0; n < m_uSeqCount; ++n) delete[] m_UngapMap[n]; delete[] m_szSeqs; delete[] m_SeqBuffer; delete[] m_UngapMap; m_SeqNames.clear(); m_uSeqCount = 0; m_uColCount = 0; m_uCacheSeqCount = 0; m_SeqBuffer = 0; m_szSeqs = 0; } // Caller must allocate ptrSeq and ptrLabel as new char[n]. void MSA_QScore::AppendSeq(char *ptrSeq, unsigned uSeqLength, char *ptrLabel) { if (m_uSeqCount > m_uCacheSeqCount) Quit_Qscore("Internal error MSA::AppendSeq"); if (m_uSeqCount == m_uCacheSeqCount) ExpandCache(m_uSeqCount + 4, uSeqLength); m_szSeqs[m_uSeqCount] = ptrSeq; m_SeqNames.push_back(std::string(ptrLabel)); //m_szNames[m_uSeqCount] = ptrLabel; ++m_uSeqCount; } void MSA_QScore::ExpandCache(unsigned uSeqCount, unsigned uColCount) { if (m_uSeqCount > 0 && uColCount != m_uColCount) Quit_Qscore("Internal error MSA::ExpandCache, ColCount changed"); char **NewSeqs = new char *[uSeqCount]; char **NewNames = new char *[uSeqCount]; for (unsigned uSeqIndex = 0; uSeqIndex < m_uSeqCount; ++uSeqIndex) { NewSeqs[uSeqIndex] = m_szSeqs[uSeqIndex]; // NewNames[uSeqIndex] = m_szNames[uSeqIndex]; } for (unsigned uSeqIndex = m_uSeqCount; uSeqIndex < uSeqCount; ++uSeqIndex) { char *Seq = new char[uColCount]; NewSeqs[uSeqIndex] = Seq; #if DEBUG memset(Seq, '?', uColCount); #endif } delete[] m_szSeqs; //delete[] m_szNames; m_szSeqs = NewSeqs; //m_szNames = NewNames; m_uCacheSeqCount = uSeqCount; m_uColCount = uColCount; } bool MSA_QScore::GetSeqIndex(const char *ptrSeqName, unsigned *ptruSeqIndex) const { std::map::const_iterator p = m_SeqNameToIndex.find(ptrSeqName); if (p == m_SeqNameToIndex.end()) return false; *ptruSeqIndex = p->second; return true; } const char *MSA_QScore::GetSeqName(unsigned uSeqIndex) const { #if _DEBUG if (uSeqIndex >= m_uSeqCount) Quit_Qscore("MSA::GetSeqName(%u), count=%u", uSeqIndex, m_uSeqCount); #endif return m_SeqNames[uSeqIndex].c_str(); } /*** It is sometimes very convenient to represent a pairwise alignment as a "pair map", which works as follows. Let iPos1 be the index into ungapped sequence 1, similarly for iPos2. Then if a pair of letters (iPos1, iPos2) is aligned: iMap1[iPos1] = iPos2 and iMap2[iPos2] = iPos1. If iPos1 is not in an aligned column, or is aligned to a gap, then iMap1[iPos1] = -1, and similarly for iMap2. This overloads the meaning of the integer value, so is questionable software engineering practice; however it's a simple and convenient solution for small applications. ***/ void MSA_QScore::GetPairMap(unsigned uSeqIndex1, unsigned uSeqIndex2, int iMap1[], int iMap2[]) const { assert(uSeqIndex1 < GetSeqCount()); assert(uSeqIndex2 < GetSeqCount()); int iPos1 = 0; int iPos2 = 0; const unsigned uColCount = GetColCount(); for (unsigned uColIndex = 0; uColIndex < uColCount; ++uColIndex) { char c1 = GetChar(uSeqIndex1, uColIndex); char c2 = GetChar(uSeqIndex2, uColIndex); bool bIsGap1 = ::IsGap(c1); bool bIsGap2 = ::IsGap(c2); if (!bIsGap1 && !bIsGap2) { if (isupper(c1)) { if (!isupper(c2)) Quit_Qscore("Both upper and lower case letters (%c,%c) in ref alignment column %d", c1, c2, uColIndex); iMap1[iPos1] = iPos2; iMap2[iPos2] = iPos1; } else { iMap1[iPos1] = -1; iMap2[iPos2] = -1; } ++iPos1; ++iPos2; } else if (!bIsGap1 && bIsGap2) { iMap1[iPos1] = -1; ++iPos1; } else if (bIsGap1 && !bIsGap2) { iMap2[iPos2] = -1; ++iPos2; } } #if _DEBUG { int iLength1 = iPos1; int iLength2 = iPos2; for (int iPos1 = 0; iPos1 < iLength1; ++iPos1) { int iPos2 = iMap1[iPos1]; if (-1 == iPos2) continue; assert(iMap2[iPos2] == iPos1); } for (int iPos2 = 0; iPos2 < iLength2; ++iPos2) { int iPos1 = iMap2[iPos2]; if (-1 == iPos1) continue; assert(iMap1[iPos1] == iPos2); } } #endif } unsigned MSA_QScore::GetSeqLength(unsigned uSeqIndex) const { assert(uSeqIndex < GetSeqCount()); return m_SeqLengths[uSeqIndex]; } bool MSA_QScore::IsGap(unsigned uSeqIndex, unsigned uColIndex) const { return ::IsGap(GetChar(uSeqIndex, uColIndex)); } void MSA_QScore::SetChar(unsigned uSeqIndex, unsigned uIndex, char c) { #if _DEBUG if (uSeqIndex >= m_uSeqCount || uIndex >= m_uColCount) Quit_Qscore("MSA::GetLetter(%u/%u,%u/%u)", uSeqIndex, m_uSeqCount, uIndex, m_uColCount); #endif m_szSeqs[uSeqIndex][uIndex] = c; } void MSA_QScore::MakeUngapMap() { if (m_UngapMap != 0) return; m_UngapMap = new unsigned *[m_uSeqCount]; memset(m_UngapMap, 0, m_uSeqCount*sizeof(unsigned *)); for (unsigned uSeqIndex = 0; uSeqIndex < m_uSeqCount; ++uSeqIndex) MakeUngapMapSeq(uSeqIndex); } void MSA_QScore::MakeGapMap() { if (m_GapMap != 0) return; m_GapMap = new unsigned *[m_uSeqCount]; memset(m_GapMap, 0, m_uSeqCount*sizeof(unsigned *)); for (unsigned uSeqIndex = 0; uSeqIndex < m_uSeqCount; ++uSeqIndex) MakeGapMapSeq(uSeqIndex); } void MSA_QScore::MakeUngapMapSeq(unsigned uSeqIndex) { unsigned *ptrMap = new unsigned[m_uColCount]; memset(ptrMap, 0, m_uColCount*sizeof(unsigned)); unsigned uUngappedColIndex = 0; for (unsigned uGappedColIndex = 0; uGappedColIndex < m_uColCount; ++uGappedColIndex) { if (IsGap(uSeqIndex, uGappedColIndex)) ptrMap[uGappedColIndex] = uInsane; else { ptrMap[uGappedColIndex] = uUngappedColIndex; ++uUngappedColIndex; } } m_UngapMap[uSeqIndex] = ptrMap; } void MSA_QScore::MakeGapMapSeq(unsigned uSeqIndex) { unsigned *ptrMap = new unsigned[m_uColCount]; memset(ptrMap, 0, m_uColCount*sizeof(unsigned)); unsigned uUngappedColIndex = 0; for (unsigned uGappedColIndex = 0; uGappedColIndex < m_uColCount; ++uGappedColIndex) { if (!IsGap(uSeqIndex, uGappedColIndex)) { ptrMap[uUngappedColIndex] = uGappedColIndex; ++uUngappedColIndex; } } m_GapMap[uSeqIndex] = ptrMap; } unsigned MSA_QScore::GetUngappedColIndex(unsigned uSeqIndex, unsigned uColIndex) { assert(uSeqIndex < m_uSeqCount); assert(uColIndex < m_uColCount); return m_UngapMap[uSeqIndex][uColIndex]; } unsigned MSA_QScore::GetGappedColIndex(unsigned uSeqIndex, unsigned uUngappedColIndex) { assert(uSeqIndex < m_uSeqCount); assert(uUngappedColIndex < m_uColCount); return m_GapMap[uSeqIndex][uUngappedColIndex]; } ugene-1.9.8/src/libs_3rdparty/qscore/src/qscore/qscore_comparemsa.cpp0000644000175000017500000000402011651544307024452 0ustar ilyailya#include "qscore.h" void CompareMSA(const MSA_QScore &msaTest, const MSA_QScore &msaRef, double *ptrdSP, double *ptrdPS, double *ptrdCS) { const unsigned uRefSeqCount = msaRef.GetSeqCount(); double dTotalSP = 0.0; double dTotalPS = 0.0; double dTotalCS = 0.0; unsigned uPairCount = 0; //const QScoreContext *ctx = getQScoreContext(); const unsigned uTotalPairCount = (uRefSeqCount*(uRefSeqCount - 1))/2; for (unsigned uRefSeqIndexA = 0; uRefSeqIndexA < uRefSeqCount; ++uRefSeqIndexA) { const char *pstrSeqNameA = msaRef.GetSeqName(uRefSeqIndexA); unsigned uTestSeqIndexA; bool bFound = msaTest.GetSeqIndex(pstrSeqNameA, &uTestSeqIndexA); if (!bFound) { Quit_Qscore("Sequence '%s' not found in test alignment", pstrSeqNameA); continue; } for (unsigned uRefSeqIndexB = uRefSeqIndexA + 1; uRefSeqIndexB < uRefSeqCount; ++uRefSeqIndexB) { /*if (!ctx->g_Quiet && uPairCount%100 == 0) { double Pct = uPairCount*100.0/uTotalPairCount; k_printf( "%u seqs; %u of %u pairs (%.1f%%)\r", uRefSeqCount, uPairCount, uTotalPairCount, Pct); }*/ const char *pstrSeqNameB = msaRef.GetSeqName(uRefSeqIndexB); unsigned uTestSeqIndexB; bool bFound = msaTest.GetSeqIndex(pstrSeqNameB, &uTestSeqIndexB); if (!bFound) { Quit_Qscore("Sequence '%s' not found in test alignment", pstrSeqNameA); continue; } double dSP = dInsane; double dPS = dInsane; double dCS = dInsane; ComparePair(msaTest, uTestSeqIndexA, uTestSeqIndexB, msaRef, uRefSeqIndexA, uRefSeqIndexB, &dSP, &dPS, &dCS); dTotalSP += dSP; dTotalPS += dPS; dTotalCS += dCS; ++uPairCount; } } if (0 == uPairCount) { Quit_Qscore("No sequence pairs in common between test and reference alignment"); *ptrdSP = 0; *ptrdPS = 0; *ptrdCS = 0; return; } /*if (!ctx->g_Quiet) k_printf( "%u seqs; %u of %u pairs (100%%)\n", uRefSeqCount, uTotalPairCount, uTotalPairCount);*/ *ptrdSP = dTotalSP / uPairCount; *ptrdPS = dTotalPS / uPairCount; *ptrdCS = dTotalCS / uPairCount; } ugene-1.9.8/src/libs_3rdparty/qscore/src/qscore/qscore_perseq.cpp0000644000175000017500000000606411651544307023634 0ustar ilyailya#include "qscore.h" double QPair(const MSA_QScore &msaTest, unsigned uTestSeqIndexA, unsigned uTestSeqIndexB, const MSA_QScore &msaRef, unsigned uRefSeqIndexA, unsigned uRefSeqIndexB) { const int iLengthA = (int) msaTest.GetSeqLength(uTestSeqIndexA); const int iLengthB = (int) msaTest.GetSeqLength(uTestSeqIndexB); const int iLengthAr = (int) msaRef.GetSeqLength(uRefSeqIndexA); const int iLengthBr = (int) msaRef.GetSeqLength(uRefSeqIndexB); int *iRefMapA = new int[iLengthA]; int *iRefMapB = new int[iLengthB]; int *iTestMapA = new int[iLengthA]; int *iTestMapB = new int [iLengthB]; msaTest.GetPairMap(uTestSeqIndexA, uTestSeqIndexB, iTestMapA, iTestMapB); msaRef.GetPairMap(uRefSeqIndexA, uRefSeqIndexB, iRefMapA, iRefMapB); double Q = SumPairs(iRefMapA, iTestMapA, iLengthA); delete[] iRefMapA; delete[] iRefMapB; delete[] iTestMapA; delete[] iTestMapB; return Q; } double PerSeq(const MSA_QScore &msaTest, const MSA_QScore &msaRef) { const unsigned uRefSeqCount = msaRef.GetSeqCount(); const unsigned uTotalPairCount = (uRefSeqCount*(uRefSeqCount - 1))/2; unsigned uPairCount = 0; vector > QMx(uRefSeqCount); for (unsigned uRefSeqIndexA = 0; uRefSeqIndexA < uRefSeqCount; ++uRefSeqIndexA) QMx[uRefSeqIndexA].resize(uRefSeqCount); for (unsigned uRefSeqIndexA = 0; uRefSeqIndexA < uRefSeqCount; ++uRefSeqIndexA) { const char *pstrSeqNameA = msaRef.GetSeqName(uRefSeqIndexA); unsigned uTestSeqIndexA; bool bFound = msaTest.GetSeqIndex(pstrSeqNameA, &uTestSeqIndexA); if (!bFound) { Quit_Qscore("Sequence '%s' not found in test alignment", pstrSeqNameA); continue; } for (unsigned uRefSeqIndexB = uRefSeqIndexA + 1; uRefSeqIndexB < uRefSeqCount; ++uRefSeqIndexB) { /*if (!ctx->g_Quiet && uPairCount%100 == 0) { double Pct = uPairCount*100.0/uTotalPairCount; k_printf( "%u seqs; %u of %u pairs (%.1f%%)\r", uRefSeqCount, uPairCount, uTotalPairCount, Pct); }*/ const char *pstrSeqNameB = msaRef.GetSeqName(uRefSeqIndexB); unsigned uTestSeqIndexB; bool bFound = msaTest.GetSeqIndex(pstrSeqNameB, &uTestSeqIndexB); if (!bFound) { Quit_Qscore("Sequence '%s' not found in test alignment", pstrSeqNameA); continue; } double Q = QPair(msaTest, uTestSeqIndexA, uTestSeqIndexB, msaRef, uRefSeqIndexA, uRefSeqIndexB); QMx[uRefSeqIndexA][uRefSeqIndexB] = Q; QMx[uRefSeqIndexB][uRefSeqIndexA] = Q; } } double GrandSumQ = 0; for (unsigned uRefSeqIndexA = 0; uRefSeqIndexA < uRefSeqCount; ++uRefSeqIndexA) { double SumQ = 0; for (unsigned uRefSeqIndexB = 0; uRefSeqIndexB < uRefSeqCount; ++uRefSeqIndexB) { if (uRefSeqIndexB == uRefSeqIndexA) continue; SumQ += QMx[uRefSeqIndexA][uRefSeqIndexB]; } double Q = SumQ/(uRefSeqCount - 1); const char *pstrSeqName = msaRef.GetSeqName(uRefSeqIndexA); /*printf("Test=%s;Ref=%s;Seq=%s;Q=%.4f\n", g_TestFileName, g_RefFileName, pstrSeqName, Q);*/ GrandSumQ += Q; } double Q = GrandSumQ/uRefSeqCount; /* printf("Test=%s;Ref=%s;AvgQ=%.4f\n", g_TestFileName, g_RefFileName, Q);*/ return Q; } ugene-1.9.8/src/libs_3rdparty/qscore/src/qscore/sab_ids.h0000644000175000017500000001520511651544307022027 0ustar ilyailyachar *SAB_Ids[] = { "sf1", "sf10", "sf100", "sf101", "sf102", "sf103", "sf104", "sf105", "sf106", "sf107", "sf108", "sf109", "sf11", "sf110", "sf111", "sf112", "sf113", "sf114", "sf115", "sf116", "sf117", "sf118", "sf119", "sf12", "sf120", "sf121", "sf122", "sf123", "sf124", "sf125", "sf126", "sf127", "sf128", "sf129", "sf13", "sf130", "sf131", "sf132", "sf133", "sf134", "sf135", "sf136", "sf137", "sf138", "sf139", "sf14", "sf140", "sf141", "sf142", "sf143", "sf144", "sf145", "sf146", "sf147", "sf148", "sf149", "sf15", "sf150", "sf151", "sf152", "sf153", "sf154", "sf155", "sf156", "sf157", "sf158", "sf159", "sf16", "sf160", "sf161", "sf162", "sf163", "sf164", "sf165", "sf166", "sf167", "sf168", "sf169", "sf17", "sf170", "sf171", "sf172", "sf173", "sf174", "sf175", "sf176", "sf177", "sf178", "sf179", "sf18", "sf180", "sf181", "sf182", "sf183", "sf184", "sf185", "sf186", "sf187", "sf188", "sf189", "sf19", "sf190", "sf191", "sf192", "sf193", "sf194", "sf195", "sf196", "sf197", "sf198", "sf199", "sf2", "sf20", "sf200", "sf201", "sf202", "sf203", "sf204", "sf205", "sf206", "sf207", "sf208", "sf209", "sf21", "sf210", "sf211", "sf212", "sf213", "sf214", "sf215", "sf216", "sf217", "sf218", "sf219", "sf22", "sf220", "sf221", "sf222", "sf223", "sf224", "sf225", "sf226", "sf227", "sf228", "sf229", "sf23", "sf230", "sf231", "sf232", "sf233", "sf234", "sf235", "sf236", "sf237", "sf238", "sf239", "sf24", "sf240", "sf241", "sf242", "sf243", "sf244", "sf245", "sf246", "sf247", "sf248", "sf249", "sf25", "sf250", "sf251", "sf252", "sf253", "sf254", "sf255", "sf256", "sf257", "sf258", "sf259", "sf26", "sf260", "sf261", "sf262", "sf263", "sf264", "sf265", "sf266", "sf267", "sf268", "sf269", "sf27", "sf270", "sf271", "sf272", "sf273", "sf274", "sf275", "sf276", "sf277", "sf278", "sf279", "sf28", "sf280", "sf281", "sf282", "sf283", "sf284", "sf285", "sf286", "sf287", "sf288", "sf289", "sf29", "sf290", "sf291", "sf292", "sf293", "sf294", "sf295", "sf296", "sf297", "sf298", "sf299", "sf3", "sf30", "sf300", "sf301", "sf302", "sf303", "sf304", "sf305", "sf306", "sf307", "sf308", "sf309", "sf31", "sf310", "sf311", "sf312", "sf313", "sf314", "sf315", "sf316", "sf317", "sf318", "sf319", "sf32", "sf320", "sf321", "sf322", "sf323", "sf324", "sf325", "sf326", "sf327", "sf328", "sf329", "sf33", "sf330", "sf331", "sf332", "sf333", "sf334", "sf335", "sf336", "sf337", "sf338", "sf339", "sf34", "sf340", "sf341", "sf342", "sf343", "sf344", "sf345", "sf346", "sf347", "sf348", "sf349", "sf35", "sf350", "sf351", "sf352", "sf353", "sf354", "sf355", "sf356", "sf357", "sf358", "sf359", "sf36", "sf360", "sf361", "sf362", "sf363", "sf364", "sf365", "sf366", "sf367", "sf368", "sf369", "sf37", "sf370", "sf371", "sf372", "sf373", "sf374", "sf375", "sf376", "sf377", "sf378", "sf379", "sf38", "sf380", "sf381", "sf382", "sf383", "sf384", "sf385", "sf386", "sf387", "sf388", "sf389", "sf39", "sf390", "sf391", "sf392", "sf393", "sf394", "sf395", "sf396", "sf397", "sf398", "sf399", "sf4", "sf40", "sf400", "sf401", "sf402", "sf403", "sf404", "sf405", "sf406", "sf407", "sf408", "sf409", "sf41", "sf410", "sf411", "sf412", "sf413", "sf414", "sf415", "sf416", "sf417", "sf418", "sf419", "sf42", "sf420", "sf421", "sf422", "sf423", "sf424", "sf425", "sf426", "sf427", "sf428", "sf429", "sf43", "sf430", "sf431", "sf432", "sf433", "sf434", "sf435", "sf436", "sf437", "sf438", "sf439", "sf44", "sf440", "sf441", "sf442", "sf443", "sf444", "sf445", "sf446", "sf447", "sf448", "sf449", "sf45", "sf450", "sf451", "sf452", "sf453", "sf454", "sf455", "sf456", "sf457", "sf458", "sf459", "sf46", "sf460", "sf461", "sf462", "sf47", "sf48", "sf49", "sf5", "sf50", "sf51", "sf52", "sf53", "sf54", "sf55", "sf56", "sf57", "sf58", "sf59", "sf6", "sf60", "sf61", "sf62", "sf63", "sf64", "sf65", "sf66", "sf67", "sf68", "sf69", "sf7", "sf70", "sf71", "sf72", "sf73", "sf74", "sf75", "sf76", "sf77", "sf78", "sf79", "sf8", "sf80", "sf81", "sf82", "sf83", "sf84", "sf85", "sf86", "sf87", "sf88", "sf89", "sf9", "sf90", "sf91", "sf92", "sf93", "sf94", "sf95", "sf96", "sf97", "sf98", "sf99", "tw1", "tw10", "tw100", "tw101", "tw102", "tw103", "tw104", "tw105", "tw106", "tw107", "tw108", "tw109", "tw11", "tw110", "tw111", "tw112", "tw113", "tw114", "tw115", "tw116", "tw117", "tw118", "tw119", "tw12", "tw120", "tw121", "tw122", "tw123", "tw124", "tw125", "tw126", "tw127", "tw128", "tw129", "tw13", "tw130", "tw131", "tw132", "tw133", "tw134", "tw135", "tw136", "tw137", "tw138", "tw139", "tw14", "tw140", "tw141", "tw142", "tw143", "tw144", "tw145", "tw146", "tw147", "tw148", "tw149", "tw15", "tw150", "tw151", "tw152", "tw153", "tw154", "tw155", "tw156", "tw157", "tw158", "tw159", "tw16", "tw160", "tw161", "tw162", "tw163", "tw164", "tw165", "tw166", "tw167", "tw168", "tw169", "tw17", "tw170", "tw171", "tw172", "tw173", "tw174", "tw175", "tw176", "tw177", "tw178", "tw179", "tw18", "tw180", "tw181", "tw182", "tw183", "tw184", "tw185", "tw186", "tw187", "tw188", "tw189", "tw19", "tw190", "tw191", "tw192", "tw193", "tw194", "tw195", "tw196", "tw197", "tw198", "tw199", "tw2", "tw20", "tw200", "tw201", "tw202", "tw203", "tw204", "tw205", "tw206", "tw207", "tw208", "tw209", "tw21", "tw210", "tw211", "tw212", "tw213", "tw214", "tw215", "tw216", "tw217", "tw218", "tw219", "tw22", "tw220", "tw221", "tw222", "tw223", "tw224", "tw225", "tw226", "tw227", "tw228", "tw229", "tw23", "tw230", "tw231", "tw232", "tw233", "tw234", "tw235", "tw236", "tw24", "tw25", "tw26", "tw27", "tw28", "tw29", "tw3", "tw30", "tw31", "tw32", "tw33", "tw34", "tw35", "tw36", "tw37", "tw38", "tw39", "tw4", "tw40", "tw41", "tw42", "tw43", "tw44", "tw45", "tw46", "tw47", "tw48", "tw49", "tw5", "tw50", "tw51", "tw52", "tw53", "tw54", "tw55", "tw56", "tw57", "tw58", "tw59", "tw6", "tw60", "tw61", "tw62", "tw63", "tw64", "tw65", "tw66", "tw67", "tw68", "tw69", "tw7", "tw70", "tw71", "tw72", "tw73", "tw74", "tw75", "tw76", "tw77", "tw78", "tw79", "tw8", "tw80", "tw81", "tw82", "tw83", "tw84", "tw85", "tw86", "tw87", "tw88", "tw89", "tw9", "tw90", "tw91", "tw92", "tw93", "tw94", "tw95", "tw96", "tw97", "tw98", "tw99", }; ugene-1.9.8/src/libs_3rdparty/qscore/src/qscore/qscore_gapscore.cpp0000644000175000017500000000226411651544307024136 0ustar ilyailya#include "qscore.h" #define TRACE 0 using namespace std; void ComputeGapScore(const vector &TestSeqs, const vector &TestLabels, const vector &RefSeqs, const vector &RefLabels, double &GC, double &TC); void MSAToVecs(const MSA_QScore &msa, vector &Seqs, vector &Labels) { Seqs.clear(); Labels.clear(); const unsigned SeqCount = msa.GetSeqCount(); const unsigned ColCount = msa.GetColCount(); Seqs.resize(SeqCount); Labels.resize(SeqCount); for (unsigned SeqIndex = 0; SeqIndex < SeqCount; ++SeqIndex) { const char *Label = msa.GetSeqName(SeqIndex); Labels[SeqIndex] = Label; string &Seq = Seqs[SeqIndex]; Seq.resize(ColCount); for (unsigned ColIndex = 0; ColIndex < ColCount; ++ColIndex) { char c = msa.GetChar(SeqIndex, ColIndex); Seq[ColIndex] = c; } } } void ComputeGapScoreMSA(MSA_QScore &msaTest, MSA_QScore &msaRef, double &GC, double &TC) { vector TestSeqs; vector RefSeqs; vector TestLabels; vector RefLabels; MSAToVecs(msaTest, TestSeqs, TestLabels); MSAToVecs(msaRef, RefSeqs, RefLabels); ComputeGapScore(TestSeqs, TestLabels, RefSeqs, RefLabels, GC, TC); } ugene-1.9.8/src/libs_3rdparty/qscore/src/qscore/qscore_seq.cpp0000644000175000017500000001300311651544307023114 0ustar ilyailya#include "qscore.h" #if 0 const size_t MAX_FASTA_LINE = 4*4096; void Seq::SetName(const char *ptrName) { delete[] m_ptrName; size_t n = strlen(ptrName) + 1; m_ptrName = new char[n]; strcpy(m_ptrName, ptrName); } void Seq::ToFASTAFile(TextFile &File) const { File.PutFormat(">%s\n", m_ptrName); unsigned uColCount = Length(); for (unsigned n = 0; n < uColCount; ++n) { if (n > 0 && n%60 == 0) File.PutString("\n"); File.PutChar(at(n)); } File.PutString("\n"); } // Return true on end-of-file bool Seq::FromFASTAFile(TextFile &File) { Clear(); char szLine[MAX_FASTA_LINE]; bool bEof = File.GetLine(szLine, sizeof(szLine)); if (bEof) return true; if ('>' != szLine[0]) Quit_Qscore("Expecting '>' in FASTA file %s line %u", File.GetFileName(), File.GetLineNr()); // Truncate name at first blank // TODO: This is a hack because readseq does MSF -> FASTA // conversion in a very strange way with the annotation. //char *ptrBlank = strchr(szLine, ' '); //if (0 != ptrBlank) // *ptrBlank = 0; size_t n = strlen(szLine); if (1 == n) Quit_Qscore("Missing name following '>' in FASTA file %s line %u", File.GetFileName(), File.GetLineNr()); m_ptrName = new char[n]; strcpy(m_ptrName, szLine + 1); TEXTFILEPOS Pos = File.GetPos(); for (;;) { bEof = File.GetLine(szLine, sizeof(szLine)); if (bEof) { if (0 == size()) { Quit_Qscore("Empty sequence in FASTA file %s line %u", File.GetFileName(), File.GetLineNr()); return true; } return false; } if ('>' == szLine[0]) { if (0 == size()) Quit_Qscore("Empty sequence in FASTA file %s line %u", File.GetFileName(), File.GetLineNr()); // Rewind to beginning of this line, it's the start of the // next sequence. File.SetPos(Pos); return false; } const char *ptrChar = szLine; while (char c = *ptrChar++) push_back(c); Pos = File.GetPos(); } } void Seq::ExtractUngapped(MSA &msa) const { msa.Clear(); unsigned uColCount = Length(); msa.SetSize(1, 1); unsigned uUngappedPos = 0; for (unsigned n = 0; n < uColCount; ++n) { char c = at(n); if (!IsGap(c)) msa.SetChar(0, uUngappedPos++, c); } msa.SetSeqName(0, m_ptrName); } void Seq::Copy(const Seq &rhs) { clear(); const unsigned uLength = rhs.Length(); for (unsigned uColIndex = 0; uColIndex < uLength; ++uColIndex) push_back(rhs.at(uColIndex)); const char *ptrName = rhs.GetName(); size_t n = strlen(ptrName) + 1; m_ptrName = new char[n]; strcpy(m_ptrName, ptrName); } void Seq::CopyReversed(const Seq &rhs) { clear(); const unsigned uLength = rhs.Length(); const unsigned uBase = rhs.Length() - 1; for (unsigned uColIndex = 0; uColIndex < uLength; ++uColIndex) push_back(rhs.at(uBase - uColIndex)); const char *ptrName = rhs.GetName(); size_t n = strlen(ptrName) + 1; m_ptrName = new char[n]; strcpy(m_ptrName, ptrName); } void Seq::StripGaps() { for (CharVect::iterator p = begin(); p != end(); ) { char c = *p; if (IsGap(c)) erase(p); else ++p; } } void Seq::ToUpper() { for (CharVect::iterator p = begin(); p != end(); ++p) { char c = *p; if (islower(c)) *p = toupper(c); } } unsigned Seq::GetLetter(unsigned uIndex) const { assert(uIndex < Length()); char c = operator[](uIndex); return CharToLetterAmino(c); } bool Seq::EqIgnoreCase(const Seq &s) const { const unsigned n = Length(); if (n != s.Length()) { return false; } for (unsigned i = 0; i < n; ++i) { const char c1 = at(i); const char c2 = s.at(i); if (IsGap(c1)) { if (!IsGap(c2)) return false; } else { if (toupper(c1) != toupper(c2)) { return false; } } } return true; } bool Seq::EqIgnoreCaseAndGaps(const Seq &s) const { const unsigned uThisLength = Length(); const unsigned uOtherLength = s.Length(); unsigned uThisPos = 0; unsigned uOtherPos = 0; int cThis; int cOther; for (;;) { if (uThisPos == uThisLength && uOtherPos == uOtherLength) break; // Set cThis to next non-gap character in this string // or -1 if end-of-string. for (;;) { if (uThisPos == uThisLength) { cThis = -1; break; } else { cThis = at(uThisPos); ++uThisPos; if (!IsGap(cThis)) { cThis = toupper(cThis); break; } } } // Set cOther to next non-gap character in s // or -1 if end-of-string. for (;;) { if (uOtherPos == uOtherLength) { cOther = -1; break; } else { cOther = s.at(uOtherPos); ++uOtherPos; if (!IsGap(cOther)) { cOther = toupper(cOther); break; } } } // Compare characters are corresponding ungapped position if (cThis != cOther) return false; } return true; } unsigned Seq::GetUngappedLength() const { unsigned uUngappedLength = 0; for (CharVect::const_iterator p = begin(); p != end(); ++p) { char c = *p; if (!IsGap(c)) ++uUngappedLength; } return uUngappedLength; } void Seq::ListMe() const { List(">%s\n", m_ptrName); const unsigned n = Length(); for (unsigned i = 0; i < n; ++i) List("%c", at(i)); List("\n"); } void Seq::FromString(const char *pstrSeq, const char *pstrName) { clear(); const unsigned uLength = (unsigned) strlen(pstrSeq); for (unsigned uColIndex = 0; uColIndex < uLength; ++uColIndex) push_back(pstrSeq[uColIndex]); size_t n = strlen(pstrName) + 1; m_ptrName = new char[n]; strcpy(m_ptrName, pstrName); } bool Seq::HasGap() const { for (CharVect::const_iterator p = begin(); p != end(); ++p) { char c = *p; if (IsGap(c)) return true; } return false; } #endif ugene-1.9.8/src/libs_3rdparty/qscore/src/qscore/qscore_clineshift.cpp0000644000175000017500000000271011651544307024457 0ustar ilyailya#include "qscore.h" // Compute the Cline shift score [1] from two pair maps. // It is the relative simplicity of this code that motivates the use of pair maps. // [1] Cline, Hughey & Karplus (2002), Bioinformatics 18(2) p.306. double ClineShift(const int iTestMapA[], const int iRefMapA[], unsigned uLengthA, const int iTestMapB[], const int iRefMapB[], unsigned uLengthB, double dEpsilon) { unsigned uRefPairCount = 0; unsigned uTestPairCount = 0; double dTotal = 0.0; for (unsigned uPosA = 0; uPosA < uLengthA; ++uPosA) { int iRefPosB = iRefMapA[uPosA]; if (-1 == iRefPosB) continue; ++uRefPairCount; int iTestPosB = iTestMapA[uPosA]; if (-1 == iTestPosB) continue; int iShift = iabs(iRefPosB - iTestPosB); double dScore = (1 + dEpsilon)/(1 + iShift) - dEpsilon; assert(dScore >= -dEpsilon); assert(dScore <= 1.0); dTotal += dScore; } for (unsigned uPosB = 0; uPosB < uLengthB; ++uPosB) { int iTestPosA = iTestMapB[uPosB]; if (-1 == iTestPosA) continue; ++uTestPairCount; int iRefPosA = iRefMapB[uPosB]; if (-1 == iRefPosA) continue; int iShift = iabs(iRefPosA - iTestPosA); double dScore = (1 + dEpsilon)/(1 + iShift) - dEpsilon; assert(dScore >= -dEpsilon); assert(dScore <= 1.0); dTotal += dScore; } if (0 == uRefPairCount) { //DumpRefPair(); //Quit_Qscore("ClineShift: No aligned pair in ref alignment"); return 0.0; } return dTotal / (double) (uTestPairCount + uRefPairCount); } ugene-1.9.8/src/libs_3rdparty/qscore/src/qscore/sab_ref2.h0000644000175000017500000313672111651544307022120 0ustar ilyailyaconst char *SAB_Ref2Filenames[] = { "d12asa_.ent-d1atia2", "d12asa_.ent-d1b8aa2", "d12asa_.ent-d1bia_3", "d12asa_.ent-d1e1oa2", "d12asa_.ent-d1eova2", "d12asa_.ent-d1g51a3", "d12asa_.ent-d1h4vb2", "d12asa_.ent-d1hc7a2", "d12asa_.ent-d1jjca_", "d12asa_.ent-d1jjcb5", "d12asa_.ent-d1kmma2", "d12asa_.ent-d1qe0a2", "d12asa_.ent-d1qf6a4", "d12asa_.ent-d1seta2", "d153l__.ent-d1b9oa_", "d153l__.ent-d1chka_", "d153l__.ent-d1dxja_", "d153l__.ent-d1gd6a_", "d153l__.ent-d1k28a3", "d153l__.ent-d1qgia_", "d153l__.ent-d1qsaa2", "d153l__.ent-d1qusa_", "d153l__.ent-d217l__", "d153l__.ent-d2eql__", "d153l__.ent-d3lzt__", "d16pk__.ent-d1hdia_", "d16pk__.ent-d1php__.ent", "d19hca_.ent-d1aqe__.ent", "d19hca_.ent-d1dxrc_.ent", "d19hca_.ent-d1eysc_.ent", "d19hca_.ent-d1fgja_.ent", "d19hca_.ent-d1fs7a_.ent", "d19hca_.ent-d1ft5a_.ent", "d19hca_.ent-d1gu6a_.ent", "d19hca_.ent-d1gyoa_.ent", "d19hca_.ent-d1h21a_.ent", "d19hca_.ent-d1h29a_.ent", "d19hca_.ent-d1hh5a_.ent", "d19hca_.ent-d1kssa1.ent", "d19hca_.ent-d1m1qa_.ent", "d19hca_.ent-d1qo8a1.ent", "d19hca_.ent-d1wad__.ent", "d19hca_.ent-d2ctha_.ent", "d19hca_.ent-d2cy3__.ent", "d19hca_.ent-d3caoa_.ent", "d19hca_.ent-d3cyr__.ent", "d1a02n2.ent-d1a3qa2.ent", "d1a02n2.ent-d1amx__.ent", "d1a02n2.ent-d1aoha_.ent", "d1a02n2.ent-d1ayoa_.ent", "d1a02n2.ent-d1bg1a2.ent", "d1a02n2.ent-d1bvoa_.ent", "d1a02n2.ent-d1e2wa1.ent", "d1a02n2.ent-d1e5ba_.ent", "d1a02n2.ent-d1f0la1.ent", "d1a02n2.ent-d1h6fa_.ent", "d1a02n2.ent-d1i31a_.ent", "d1a02n2.ent-d1ikna2.ent", "d1a02n2.ent-d1imhc2.ent", "d1a02n2.ent-d1klfb1.ent", "d1a02n2.ent-d1klfb2.ent", "d1a02n2.ent-d1m2oa2.ent", "d1a02n2.ent-d1m2vb2.ent", "d1a02n2.ent-d1mnna_.ent", "d1a02n2.ent-d1nbca_.ent", "d1a02n2.ent-d1pdkb_.ent", "d1a02n2.ent-d1qba_2.ent", "d1a02n2.ent-d1tf4a2.ent", "d1a02n2.ent-d1ycsa_.ent", "d1a04a1.ent-d1fc3a_.ent", "d1a04a1.ent-d1fsea_.ent", "d1a04a1.ent-d1gxqa_.ent", "d1a04a1.ent-d1opc__.ent", "d1a04a2.ent-d1a2oa1.ent", "d1a04a2.ent-d1b00a_.ent", "d1a04a2.ent-d1c4ka1.ent", "d1a04a2.ent-d1dbwa_.ent", "d1a04a2.ent-d1dcfa_.ent", "d1a04a2.ent-d1dz3a_.ent", "d1a04a2.ent-d1m2fa_.ent", "d1a04a2.ent-d1mb3a_.ent", "d1a04a2.ent-d1mvoa_.ent", "d1a04a2.ent-d1nat__.ent", "d1a04a2.ent-d1ntr__.ent", "d1a04a2.ent-d1qo0d_.ent", "d1a04a2.ent-d1tmy__.ent", "d1a06__.ent-d1fgka_.ent", "d1a06__.ent-d1ia9a_.ent", "d1a06__.ent-d1iepa_.ent", "d1a06__.ent-d1jpaa_.ent", "d1a06__.ent-d1lufa_.ent", "d1a06__.ent-d1phk__.ent", "d1a09a_.ent-d1a81a1.ent", "d1a09a_.ent-d1a81a2.ent", "d1a09a_.ent-d1ayaa_.ent", "d1a09a_.ent-d1d4ta_.ent", "d1a09a_.ent-d1fu6a_.ent", "d1a09a_.ent-d1ju5a_.ent", "d1a09a_.ent-d1jwoa_.ent", "d1a09a_.ent-d1jyra_.ent", "d1a09a_.ent-d1lkka_.ent", "d1a09a_.ent-d1luia_.ent", "d1a09a_.ent-d1mil__.ent", "d1a09a_.ent-d1qada_.ent", "d1a09a_.ent-d2abl_2.ent", "d1a09a_.ent-d2cbla3.ent", "d1a09a_.ent-d2plda_.ent", "d1a09a_.ent-d2shpa3.ent", "d1a0aa_.ent-d1am9a_.ent", "d1a0aa_.ent-d1an4a_.ent", "d1a0aa_.ent-d1mdya_.ent", "d1a0aa_.ent-d1nkpa_.ent", "d1a0aa_.ent-d1nkpb_.ent", "d1a0aa_.ent-d1nlwa_.ent", "d1a0ca_.ent-d1muwa_.ent", "d1a0ca_.ent-d1qtwa_.ent", "d1a0fa1.ent-d1aw9_1.ent", "d1a0fa1.ent-d1axda1.ent", "d1a0fa1.ent-d1duga1.ent", "d1a0fa1.ent-d1e6ba1.ent", "d1a0fa1.ent-d1eema1.ent", "d1a0fa1.ent-d1f2ea1.ent", "d1a0fa1.ent-d1fw1a1.ent", "d1a0fa1.ent-d1g7oa1.ent", "d1a0fa1.ent-d1glqa1.ent", "d1a0fa1.ent-d1gnwa1.ent", "d1a0fa1.ent-d1gula1.ent", "d1a0fa1.ent-d1gwca1.ent", "d1a0fa1.ent-d1jlva1.ent", "d1a0fa1.ent-d1k0da1.ent", "d1a0fa1.ent-d1k0ma1.ent", "d1a0fa1.ent-d1k3ya1.ent", "d1a0fa1.ent-d1ljra1.ent", "d1a0fa1.ent-d1m0ua1.ent", "d1a0fa1.ent-d1pd211.ent", "d1a0fa1.ent-d1pmt_1.ent", "d1a0fa1.ent-d2gsq_1.ent", "d1a0fa1.ent-d2gsta1.ent", "d1a0i_2.ent-d1a9xa5.ent", "d1a0i_2.ent-d1b04a_.ent", "d1a0i_2.ent-d1ckma2.ent", "d1a0i_2.ent-d1dgsa3.ent", "d1a0i_2.ent-d1eucb2.ent", "d1a0i_2.ent-d1fvia2.ent", "d1a0i_2.ent-d1gsa_2.ent", "d1a0i_2.ent-d1gsoa3.ent", "d1a0i_2.ent-d1iow_2.ent", "d1a0i_2.ent-d1kbla3.ent", "d1a0i_2.ent-d1kjqa3.ent", "d1a0i_2.ent-d1m0wa2.ent", "d1a0la_.ent-d1agja_.ent", "d1a0la_.ent-d1azza_.ent", "d1a0la_.ent-d1bio__.ent", "d1a0la_.ent-d1bqya_.ent", "d1a0la_.ent-d1cgha_.ent", "d1a0la_.ent-d1eaxa_.ent", "d1a0la_.ent-d1ekbb_.ent", "d1a0la_.ent-d1elva1.ent", "d1a0la_.ent-d1fjsa_.ent", "d1a0la_.ent-d1gdna_.ent", "d1a0la_.ent-d1gpza1.ent", "d1a0la_.ent-d1gvkb_.ent", "d1a0la_.ent-d1gvza_.ent", "d1a0la_.ent-d1hj9a_.ent", "d1a0la_.ent-d1m9ua_.ent", "d1a0la_.ent-d1mzaa_.ent", "d1a0la_.ent-d1rfna_.ent", "d1a0la_.ent-d2hlca_.ent", "d1a0p_1.ent-d1a77_1.ent", "d1a0p_1.ent-d1b4fa_.ent", "d1a0p_1.ent-d1bgxt1.ent", "d1a0p_1.ent-d1bpya1.ent", "d1a0p_1.ent-d1cuk_2.ent", "d1a0p_1.ent-d1d8ba_.ent", "d1a0p_1.ent-d1dgsa1.ent", "d1a0p_1.ent-d1doqa_.ent", "d1a0p_1.ent-d1dxsa_.ent", "d1a0p_1.ent-d1f44a1.ent", "d1a0p_1.ent-d1floa1.ent", "d1a0p_1.ent-d1go3f_.ent", "d1a0p_1.ent-d1jmsa1.ent", "d1a0p_1.ent-d1jmsa3.ent", "d1a0p_1.ent-d1jyga_.ent", "d1a0p_1.ent-d1kfta_.ent", "d1a0p_1.ent-d1lb2b_.ent", "d1a0p_1.ent-d1tfr_1.ent", "d1a0p_2.ent-d1a41__.ent", "d1a0p_2.ent-d1aiha_.ent", "d1a0p_2.ent-d1f44a2.ent", "d1a0tp_.ent-d1by5a_.ent", "d1a0tp_.ent-d1hxxa_.ent", "d1a0tp_.ent-d1kmoa_.ent", "d1a0tp_.ent-d2mpra_.ent", "d1a0tp_.ent-d2por__.ent", "d1a0tp_.ent-d3prn__.ent", "d1a12a_.ent-d1c9la2.ent", "d1a12a_.ent-d1fwxa2.ent", "d1a12a_.ent-d1gxra_.ent", "d1a12a_.ent-d1jmxb_.ent", "d1a12a_.ent-d1jtdb_.ent", "d1a12a_.ent-d1k32a3.ent", "d1a12a_.ent-d1k8kc_.ent", "d1a12a_.ent-d1m1xa4.ent", "d1a12a_.ent-d2bbkh_.ent", "d1a17__.ent-d1elra_.ent", "d1a17__.ent-d1elwa_.ent", "d1a17__.ent-d1fcha_.ent", "d1a17__.ent-d1hh8a_.ent", "d1a17__.ent-d1hz4a_.ent", "d1a17__.ent-d1ihga1.ent", "d1a17__.ent-d1iyga_.ent", "d1a17__.ent-d1kt1a1.ent", "d1a17__.ent-d1qqea_.ent", "d1a1s_2.ent-d1duvg1.ent", "d1a1s_2.ent-d1duvg2.ent", "d1a1s_2.ent-d1ekxa2.ent", "d1a1s_2.ent-d1js1x1.ent", "d1a1s_2.ent-d1js1x2.ent", "d1a1s_2.ent-d1ml4a1.ent", "d1a1s_2.ent-d1ml4a2.ent", "d1a1s_2.ent-d1otha1.ent", "d1a1s_2.ent-d1otha2.ent", "d1a1w__.ent-d1d2za_.ent", "d1a1w__.ent-d1d2zb_.ent", "d1a1w__.ent-d1ddf__.ent", "d1a1w__.ent-d1dgna_.ent", "d1a1w__.ent-d1fada_.ent", "d1a1w__.ent-d1icha_.ent", "d1a1w__.ent-d1n3ka_.ent", "d1a1w__.ent-d1ngr__.ent", "d1a1w__.ent-d3crd__.ent", "d1a1w__.ent-d3ygsp_.ent", "d1a26_2.ent-d1f0la2.ent", "d1a26_2.ent-d1giqa1.ent", "d1a26_2.ent-d1giqa2.ent", "d1a26_2.ent-d1gxya_.ent", "d1a26_2.ent-d1ikpa2.ent", "d1a26_2.ent-d1j7na3.ent", "d1a26_2.ent-d1prta_.ent", "d1a26_2.ent-d1qs1a1.ent", "d1a26_2.ent-d1qs1a2.ent", "d1a28a_.ent-d1bsxa_.ent", "d1a28a_.ent-d1fcya_.ent", "d1a28a_.ent-d1g2na_.ent", "d1a28a_.ent-d1hg4a_.ent", "d1a28a_.ent-d1ie9a_.ent", "d1a28a_.ent-d1ilga_.ent", "d1a28a_.ent-d1kv6a_.ent", "d1a28a_.ent-d1lv2a_.ent", "d1a28a_.ent-d1mzna_.ent", "d1a28a_.ent-d1n83a_.ent", "d1a28a_.ent-d2prga_.ent", "d1a2oa1.ent-d1b00a_.ent", "d1a2oa1.ent-d1c4ka1.ent", "d1a2oa1.ent-d1dbwa_.ent", "d1a2oa1.ent-d1dcfa_.ent", "d1a2oa1.ent-d1dz3a_.ent", "d1a2oa1.ent-d1m2fa_.ent", "d1a2oa1.ent-d1mb3a_.ent", "d1a2oa1.ent-d1mvoa_.ent", "d1a2oa1.ent-d1nat__.ent", "d1a2oa1.ent-d1ntr__.ent", "d1a2oa1.ent-d1qo0d_.ent", "d1a2oa1.ent-d1tmy__.ent", "d1a2pa_.ent-d1aqza_.ent", "d1a2pa_.ent-d1i0va_.ent", "d1a2pa_.ent-d1lnia_.ent", "d1a2va2.ent-d1a2va3.ent", "d1a2va2.ent-d1cewi_.ent", "d1a2va2.ent-d1ea2a_.ent", "d1a2va2.ent-d1eeja2.ent", "d1a2va2.ent-d1gy7a_.ent", "d1a2va2.ent-d1ivwa2.ent", "d1a2va2.ent-d1ivwa3.ent", "d1a2va2.ent-d1jkgb_.ent", "d1a2va2.ent-d1ksia2.ent", "d1a2va2.ent-d1ksia3.ent", "d1a2va2.ent-d1kwia_.ent", "d1a2va2.ent-d1mola_.ent", "d1a2va2.ent-d1mwxa1.ent", "d1a2va2.ent-d1o7nb_.ent", "d1a2va2.ent-d1oaca2.ent", "d1a2va2.ent-d1oaca3.ent", "d1a2va2.ent-d1stfi_.ent", "d1a2va2.ent-d1ugia_.ent", "d1a2va2.ent-d3stda_.ent", "d1a2va3.ent-d1cewi_.ent", "d1a2va3.ent-d1ea2a_.ent", "d1a2va3.ent-d1eeja2.ent", "d1a2va3.ent-d1gy7a_.ent", "d1a2va3.ent-d1ivwa2.ent", "d1a2va3.ent-d1ivwa3.ent", "d1a2va3.ent-d1jkgb_.ent", "d1a2va3.ent-d1ksia2.ent", "d1a2va3.ent-d1ksia3.ent", "d1a2va3.ent-d1kwia_.ent", "d1a2va3.ent-d1mola_.ent", "d1a2va3.ent-d1mwxa1.ent", "d1a2va3.ent-d1o7nb_.ent", "d1a2va3.ent-d1oaca2.ent", "d1a2va3.ent-d1oaca3.ent", "d1a2va3.ent-d1stfi_.ent", "d1a2va3.ent-d1ugia_.ent", "d1a2va3.ent-d3stda_.ent", "d1a2yb_.ent-d1akjd_.ent", "d1a2yb_.ent-d1b88a_.ent", "d1a2yb_.ent-d1bec_1.ent", "d1a2yb_.ent-d1c5ch1.ent", "d1a2yb_.ent-d1dlfl_.ent", "d1a2yb_.ent-d1fo0a_.ent", "d1a2yb_.ent-d1gsma2.ent", "d1a2yb_.ent-d1h5ba_.ent", "d1a2yb_.ent-d1neu__.ent", "d1a2yb_.ent-d1nfdb1.ent", "d1a2yb_.ent-d1qfoa_.ent", "d1a2yb_.ent-d1tvda_.ent", "d1a2yb_.ent-d2rhe__.ent", "d1a2za_.ent-d1b8oa_.ent", "d1a2za_.ent-d1boub_.ent", "d1a2za_.ent-d1c8ba_.ent", "d1a2za_.ent-d1cfza_.ent", "d1a2za_.ent-d1je0a_.ent", "d1a2za_.ent-d1lam_2.ent", "d1a2za_.ent-d1lfwa1.ent", "d1a2za_.ent-d1loka_.ent", "d1a2za_.ent-d1m4la_.ent", "d1a2za_.ent-d2pth__.ent", "d1a32__.ent-d1ail__.ent", "d1a32__.ent-d1fyja_.ent", "d1a33__.ent-d1lopa_.ent", "d1a33__.ent-d2cpl__.ent", "d1a3aa_.ent-d1a6ja_.ent", "d1a3aa_.ent-d1hynp_.ent", "d1a3c__.ent-d1bd3a_.ent", "d1a3c__.ent-d1bzya_.ent", "d1a3c__.ent-d1dkra1.ent", "d1a3c__.ent-d1dkra2.ent", "d1a3c__.ent-d1dqna_.ent", "d1a3c__.ent-d1ecfa1.ent", "d1a3c__.ent-d1fsga_.ent", "d1a3c__.ent-d1g2qa_.ent", "d1a3c__.ent-d1g9sa_.ent", "d1a3c__.ent-d1gph11.ent", "d1a3c__.ent-d1hgxa_.ent", "d1a3c__.ent-d1i5ea_.ent", "d1a3c__.ent-d1l1qa_.ent", "d1a3c__.ent-d1lh0a_.ent", "d1a3c__.ent-d1nula_.ent", "d1a3c__.ent-d1qb7a_.ent", "d1a3c__.ent-d1tc1a_.ent", "d1a3qa2.ent-d1amx__.ent", "d1a3qa2.ent-d1aoha_.ent", "d1a3qa2.ent-d1ayoa_.ent", "d1a3qa2.ent-d1bg1a2.ent", "d1a3qa2.ent-d1bvoa_.ent", "d1a3qa2.ent-d1e2wa1.ent", "d1a3qa2.ent-d1e5ba_.ent", "d1a3qa2.ent-d1f0la1.ent", "d1a3qa2.ent-d1h6fa_.ent", "d1a3qa2.ent-d1i31a_.ent", "d1a3qa2.ent-d1ikna2.ent", "d1a3qa2.ent-d1imhc2.ent", "d1a3qa2.ent-d1klfb1.ent", "d1a3qa2.ent-d1klfb2.ent", "d1a3qa2.ent-d1m2oa2.ent", "d1a3qa2.ent-d1m2vb2.ent", "d1a3qa2.ent-d1mnna_.ent", "d1a3qa2.ent-d1nbca_.ent", "d1a3qa2.ent-d1pdkb_.ent", "d1a3qa2.ent-d1qba_2.ent", "d1a3qa2.ent-d1tf4a2.ent", "d1a3qa2.ent-d1ycsa_.ent", "d1a3wa1.ent-d1a49a1.ent", "d1a3wa1.ent-d1e0ta1.ent", "d1a3wa1.ent-d1g8fa1.ent", "d1a3wa1.ent-d1jhda1.ent", "d1a3wa1.ent-d1pkla1.ent", "d1a3wa3.ent-d1a49a3.ent", "d1a3wa3.ent-d1e0ta3.ent", "d1a3wa3.ent-d1pkla3.ent", "d1a41__.ent-d1aiha_.ent", "d1a41__.ent-d1f44a2.ent", "d1a49a1.ent-d1e0ta1.ent", "d1a49a1.ent-d1g8fa1.ent", "d1a49a1.ent-d1jhda1.ent", "d1a49a1.ent-d1pkla1.ent", "d1a49a3.ent-d1e0ta3.ent", "d1a49a3.ent-d1pkla3.ent", "d1a4ea_.ent-d1cf9a2.ent", "d1a4ea_.ent-d1dgfa_.ent", "d1a4ea_.ent-d1gwea_.ent", "d1a4ea_.ent-d1m7sa_.ent", "d1a4ia2.ent-d1b0aa2.ent", "d1a4ia2.ent-d1bgva2.ent", "d1a4ia2.ent-d1c1da2.ent", "d1a4ia2.ent-d1edza2.ent", "d1a4ia2.ent-d1gtma2.ent", "d1a4ia2.ent-d1hwxa2.ent", "d1a4ia2.ent-d1leha2.ent", "d1a4ia2.ent-d1lu9a2.ent", "d1a4ma_.ent-d1bf6a_.ent", "d1a4ma_.ent-d1i0da_.ent", "d1a4ma_.ent-d1itua_.ent", "d1a4ma_.ent-d1j5sa_.ent", "d1a4ma_.ent-d1k6wa2.ent", "d1a4ma_.ent-d1m7ja3.ent", "d1a4sa_.ent-d1ad3a_.ent", "d1a4sa_.ent-d1cw3a_.ent", "d1a4sa_.ent-d1euha_.ent", "d1a4sa_.ent-d1ez0a_.ent", "d1a4sa_.ent-d1ky8a_.ent", "d1a4ya_.ent-d1fqva2.ent", "d1a4ya_.ent-d1igra1.ent", "d1a4ya_.ent-d1io0a_.ent", "d1a4ya_.ent-d1koha1.ent", "d1a4ya_.ent-d1n8yc1.ent", "d1a4ya_.ent-d1yrga_.ent", "d1a53__.ent-d1dbta_.ent", "d1a53__.ent-d1dqwa_.ent", "d1a53__.ent-d1eixa_.ent", "d1a53__.ent-d1geqa_.ent", "d1a53__.ent-d1i4na_.ent", "d1a53__.ent-d1jvna1.ent", "d1a53__.ent-d1km3a_.ent", "d1a53__.ent-d1kv8a_.ent", "d1a53__.ent-d1nsj__.ent", "d1a53__.ent-d1pii_1.ent", "d1a53__.ent-d1pii_2.ent", "d1a53__.ent-d1qopa_.ent", "d1a53__.ent-d1rpxa_.ent", "d1a53__.ent-d1thfd_.ent", "d1a59__.ent-d1aj8a_.ent", "d1a59__.ent-d1csh__.ent", "d1a59__.ent-d1k3pa_.ent", "d1a59__.ent-d1o7xa_.ent", "d1a5r__.ent-d1bt0a_.ent", "d1a5r__.ent-d1c1yb_.ent", "d1a5r__.ent-d1e8xa3.ent", "d1a5r__.ent-d1euvb_.ent", "d1a5r__.ent-d1gg3a3.ent", "d1a5r__.ent-d1gnua_.ent", "d1a5r__.ent-d1h4ra3.ent", "d1a5r__.ent-d1h8ca_.ent", "d1a5r__.ent-d1i42a_.ent", "d1a5r__.ent-d1j8ca_.ent", "d1a5r__.ent-d1k8rb_.ent", "d1a5r__.ent-d1l7ya_.ent", "d1a5r__.ent-d1lfda_.ent", "d1a5r__.ent-d1lm8b_.ent", "d1a5r__.ent-d1m94a_.ent", "d1a5r__.ent-d1rlf__.ent", "d1a5z_2.ent-d1b8pa2.ent", "d1a5z_2.ent-d1ez4a2.ent", "d1a5z_2.ent-d1guya2.ent", "d1a5z_2.ent-d1hyea2.ent", "d1a5z_2.ent-d1hyha2.ent", "d1a5z_2.ent-d1i0za2.ent", "d1a5z_2.ent-d1ldg_2.ent", "d1a5z_2.ent-d1ldna2.ent", "d1a5z_2.ent-d1llda2.ent", "d1a5z_2.ent-d1o6za2.ent", "d1a5z_2.ent-d2cmd_2.ent", "d1a5z_2.ent-d5mdha2.ent", "d1a5z_2.ent-d7mdha2.ent", "d1a6bb_.ent-d1dsva_.ent", "d1a6bb_.ent-d1eska_.ent", "d1a6ca1.ent-d1a6ca2.ent", "d1a6ca1.ent-d1a6ca3.ent", "d1a6ca1.ent-d1cwpa_.ent", "d1a6ca1.ent-d1f15a_.ent", "d1a6ca1.ent-d2bpa2_.ent", "d1a6ca2.ent-d1a6ca3.ent", "d1a6ca2.ent-d1cwpa_.ent", "d1a6ca2.ent-d1f15a_.ent", "d1a6ca3.ent-d1cwpa_.ent", "d1a6ca3.ent-d1f15a_.ent", "d1a6da3.ent-d1a6db3.ent", "d1a6da3.ent-d1oela3.ent", "d1a6db3.ent-d1oela3.ent", "d1a6f__.ent-d1b63a1.ent", "d1a6f__.ent-d1d6ta_.ent", "d1a6f__.ent-d1dar_3.ent", "d1a6f__.ent-d1ei1a1.ent", "d1a6f__.ent-d1fjgi_.ent", "d1a6f__.ent-d1h72c1.ent", "d1a6f__.ent-d1kija1.ent", "d1a6f__.ent-d1kkha1.ent", "d1a6f__.ent-d1kvka1.ent", "d1a6f__.ent-d1mu5a2.ent", "d1a6f__.ent-d1n0ua3.ent", "d1a6f__.ent-d1pkp_1.ent", "d1a6ja_.ent-d1hynp_.ent", "d1a6m__.ent-d1ash__", "d1a6m__.ent-d1ash__.ent", "d1a6m__.ent-d1cg5a_", "d1a6m__.ent-d1cg5a_.ent", "d1a6m__.ent-d1cg5b_", "d1a6m__.ent-d1cg5b_.ent", "d1a6m__.ent-d1cqxa1", "d1a6m__.ent-d1cqxa1.ent", "d1a6m__.ent-d1dlwa_", "d1a6m__.ent-d1dlwa_.ent", "d1a6m__.ent-d1ew6a_", "d1a6m__.ent-d1ew6a_.ent", "d1a6m__.ent-d1gcva_", "d1a6m__.ent-d1gcva_.ent", "d1a6m__.ent-d1gtea1", "d1a6m__.ent-d1gtea1.ent", "d1a6m__.ent-d1gvha1", "d1a6m__.ent-d1gvha1.ent", "d1a6m__.ent-d1h97a_", "d1a6m__.ent-d1h97a_.ent", "d1a6m__.ent-d1irda_", "d1a6m__.ent-d1irda_.ent", "d1a6m__.ent-d1irdb_", "d1a6m__.ent-d1irdb_.ent", "d1a6m__.ent-d1it2a_", "d1a6m__.ent-d1it2a_.ent", "d1a6m__.ent-d1itha_", "d1a6m__.ent-d1itha_.ent", "d1a6m__.ent-d1jl7a_", "d1a6m__.ent-d1jl7a_.ent", "d1a6m__.ent-d1la6a_", "d1a6m__.ent-d1la6a_.ent", "d1a6m__.ent-d1mba__", "d1a6m__.ent-d1mba__.ent", "d1a6m__.ent-d1qlab1", "d1a6m__.ent-d1qlab1.ent", "d1a6m__.ent-d2gdm__", "d1a6m__.ent-d2gdm__.ent", "d1a6m__.ent-d2lhb__", "d1a6m__.ent-d2lhb__.ent", "d1a6m__.ent-d3sdha_", "d1a6m__.ent-d3sdha_.ent", "d1a6s__.ent-d1ecwa_.ent", "d1a6s__.ent-d1hiwa_.ent", "d1a6s__.ent-d1jvr__.ent", "d1a6s__.ent-d1mn8a_.ent", "d1a73a_.ent-d1e7la2.ent", "d1a73a_.ent-d1emvb_.ent", "d1a73a_.ent-d1ql0a_.ent", "d1a77_1.ent-d1b43a1.ent", "d1a77_1.ent-d1b4fa_.ent", "d1a77_1.ent-d1bgxt1.ent", "d1a77_1.ent-d1bpya1.ent", "d1a77_1.ent-d1cuk_2.ent", "d1a77_1.ent-d1d8ba_.ent", "d1a77_1.ent-d1dgsa1.ent", "d1a77_1.ent-d1doqa_.ent", "d1a77_1.ent-d1dxsa_.ent", "d1a77_1.ent-d1f44a1.ent", "d1a77_1.ent-d1floa1.ent", "d1a77_1.ent-d1go3f_.ent", "d1a77_1.ent-d1jmsa1.ent", "d1a77_1.ent-d1jmsa3.ent", "d1a77_1.ent-d1jyga_.ent", "d1a77_1.ent-d1kfta_.ent", "d1a77_1.ent-d1lb2b_.ent", "d1a77_1.ent-d1tfr_1.ent", "d1a77_1.ent-d1xo1a1.ent", "d1a77_2.ent-d1bgxt2.ent", "d1a77_2.ent-d1i6pa_.ent", "d1a77_2.ent-d1tfr_2.ent", "d1a77_2.ent-d1xo1a2.ent", "d1a77_2.ent-d2rsla_.ent", "d1a79a1.ent-d1avqa_.ent", "d1a79a1.ent-d1bam__.ent", "d1a79a1.ent-d1cfr__.ent", "d1a79a1.ent-d1ckqa_.ent", "d1a79a1.ent-d1d02a_.ent", "d1a79a1.ent-d1dc1a_.ent", "d1a79a1.ent-d1dmua_.ent", "d1a79a1.ent-d1dzfa1.ent", "d1a79a1.ent-d1ev7a_.ent", "d1a79a1.ent-d1f1za2.ent", "d1a79a1.ent-d1fiua_.ent", "d1a79a1.ent-d1gefa_.ent", "d1a79a1.ent-d1kc6a_.ent", "d1a79a1.ent-d1m0da_.ent", "d1a79a1.ent-d1vsra_.ent", "d1a79a1.ent-d2foka4.ent", "d1a79a1.ent-d3pvia_.ent", "d1a7i_2.ent-d1d4ua2.ent", "d1a7i_2.ent-d1dsza_.ent", "d1a7i_2.ent-d1fjgn_.ent", "d1a7i_2.ent-d1g47a1.ent", "d1a7i_2.ent-d1g47a2.ent", "d1a7i_2.ent-d1gnf__.ent", "d1a7i_2.ent-d1ibia2.ent", "d1a7i_2.ent-d1iml_2.ent", "d1a7i_2.ent-d1jj2t_.ent", "d1a7i_2.ent-d1k3xa3.ent", "d1a7i_2.ent-d1kb2a_.ent", "d1a7i_2.ent-d1l1za3.ent", "d1a7i_2.ent-d1lata_.ent", "d1a7i_2.ent-d1lv3a_.ent", "d1a7i_2.ent-d1zfo__.ent", "d1a7i_2.ent-d2nllb_.ent", "d1a7i_2.ent-d3gata_.ent", "d1a7i_2.ent-d7gata_.ent", "d1a7j__.ent-d1cr1a_.ent", "d1a7j__.ent-d1e69a_.ent", "d1a7j__.ent-d1f5na2.ent", "d1a7j__.ent-d1fnna2.ent", "d1a7j__.ent-d1g8ya_.ent", "d1a7j__.ent-d1gm5a3.ent", "d1a7j__.ent-d1lv7a_.ent", "d1a7j__.ent-d1m6na3.ent", "d1a7ta_.ent-d1e5da2.ent", "d1a7ta_.ent-d1jjea_.ent", "d1a7ta_.ent-d1k07a_.ent", "d1a7ta_.ent-d1qh5a_.ent", "d1a7ta_.ent-d1smla_.ent", "d1a81a1.ent-d1a81a2.ent", "d1a81a1.ent-d1ayaa_.ent", "d1a81a1.ent-d1d4ta_.ent", "d1a81a1.ent-d1fu6a_.ent", "d1a81a1.ent-d1ju5a_.ent", "d1a81a1.ent-d1jwoa_.ent", "d1a81a1.ent-d1jyra_.ent", "d1a81a1.ent-d1lkka_.ent", "d1a81a1.ent-d1luia_.ent", "d1a81a1.ent-d1mil__.ent", "d1a81a1.ent-d1qada_.ent", "d1a81a1.ent-d2abl_2.ent", "d1a81a1.ent-d2cbla3.ent", "d1a81a1.ent-d2plda_.ent", "d1a81a1.ent-d2shpa3.ent", "d1a81a2.ent-d1ayaa_.ent", "d1a81a2.ent-d1d4ta_.ent", "d1a81a2.ent-d1fu6a_.ent", "d1a81a2.ent-d1ju5a_.ent", "d1a81a2.ent-d1jwoa_.ent", "d1a81a2.ent-d1jyra_.ent", "d1a81a2.ent-d1lkka_.ent", "d1a81a2.ent-d1luia_.ent", "d1a81a2.ent-d1mil__.ent", "d1a81a2.ent-d1qada_.ent", "d1a81a2.ent-d2abl_2.ent", "d1a81a2.ent-d2cbla3.ent", "d1a81a2.ent-d2plda_.ent", "d1a81a2.ent-d2shpa3.ent", "d1a87__.ent-d1cii_1.ent", "d1a87__.ent-d1cola_.ent", "d1a8d_1.ent-d1ajka_.ent", "d1a8d_1.ent-d1c4ra_.ent", "d1a8d_1.ent-d1d2sa_.ent", "d1a8d_1.ent-d1dhkb_.ent", "d1a8d_1.ent-d1dyka1.ent", "d1a8d_1.ent-d1dyka2.ent", "d1a8d_1.ent-d1epwa1.ent", "d1a8d_1.ent-d1fx5a_.ent", "d1a8d_1.ent-d1gv9a_.ent", "d1a8d_1.ent-d1gzca_.ent", "d1a8d_1.ent-d1h30a1.ent", "d1a8d_1.ent-d1h30a2.ent", "d1a8d_1.ent-d1ikpa1.ent", "d1a8d_1.ent-d1is3a_.ent", "d1a8d_1.ent-d1jhna4.ent", "d1a8d_1.ent-d1kit_1.ent", "d1a8d_1.ent-d1kit_2.ent", "d1a8d_1.ent-d1kqra_.ent", "d1a8d_1.ent-d1n1ta1.ent", "d1a8d_1.ent-d1n3oa_.ent", "d1a8d_1.ent-d1nls__.ent", "d1a8d_1.ent-d1saca_.ent", "d1a8d_1.ent-d1xnb__.ent", "d1a8d_1.ent-d2ayh__.ent", "d1a8d_1.ent-d2nlra_.ent", "d1a8d_1.ent-d2pela_.ent", "d1a8d_1.ent-d2sli_1.ent", "d1a8d_1.ent-d3btaa1.ent", "d1a8d_2.ent-d1abrb1.ent", "d1a8d_2.ent-d1avac_.ent", "d1a8d_2.ent-d1avwb_.ent", "d1a8d_2.ent-d1bfg__.ent", "d1a8d_2.ent-d1dfca1.ent", "d1a8d_2.ent-d1dfca2.ent", "d1a8d_2.ent-d1dfca3.ent", "d1a8d_2.ent-d1dqga_.ent", "d1a8d_2.ent-d1epwa2.ent", "d1a8d_2.ent-d1eyla_.ent", "d1a8d_2.ent-d1hcd__.ent", "d1a8d_2.ent-d1jlxa1.ent", "d1a8d_2.ent-d1knma_.ent", "d1a8d_2.ent-d1l2ha_.ent", "d1a8d_2.ent-d1n4ka2.ent", "d1a8d_2.ent-d1wba__.ent", "d1a8d_2.ent-d3btaa2.ent", "d1a8e__.ent-d1a99a_.ent", "d1a8e__.ent-d1al3__.ent", "d1a8e__.ent-d1amf__.ent", "d1a8e__.ent-d1atg__.ent", "d1a8e__.ent-d1dpe__.ent", "d1a8e__.ent-d1eu8a_.ent", "d1a8e__.ent-d1h76a2.ent", "d1a8e__.ent-d1i6aa_.ent", "d1a8e__.ent-d1ii5a_.ent", "d1a8e__.ent-d1ixh__.ent", "d1a8e__.ent-d1jeta_.ent", "d1a8e__.ent-d1kwha_.ent", "d1a8e__.ent-d1lst__.ent", "d1a8e__.ent-d1m5ea_.ent", "d1a8e__.ent-d1mrp__.ent", "d1a8e__.ent-d1nh8a1.ent", "d1a8e__.ent-d1pda_1.ent", "d1a8e__.ent-d1pot__.ent", "d1a8e__.ent-d1sbp__.ent", "d1a8e__.ent-d1wdna_.ent", "d1a8e__.ent-d3mbp__.ent", "d1a8e__.ent-d3thia_.ent", "d1a8h_1.ent-d1f4la1.ent", "d1a8h_1.ent-d1f7ua1.ent", "d1a8h_1.ent-d1ffya1.ent", "d1a8h_1.ent-d1ile_1.ent", "d1a8h_1.ent-d1iq0a1.ent", "d1a8h_1.ent-d1ivsa2.ent", "d1a8h_1.ent-d1li5a1.ent", "d1a8h_2.ent-d1coza_.ent", "d1a8h_2.ent-d1ej2a_.ent", "d1a8h_2.ent-d1f4la2.ent", "d1a8h_2.ent-d1f7ua2.ent", "d1a8h_2.ent-d1ffya3.ent", "d1a8h_2.ent-d1g8fa2.ent", "d1a8h_2.ent-d1gtra2.ent", "d1a8h_2.ent-d1h3fa1.ent", "d1a8h_2.ent-d1h3na3.ent", "d1a8h_2.ent-d1ihoa_.ent", "d1a8h_2.ent-d1ile_3.ent", "d1a8h_2.ent-d1iq0a2.ent", "d1a8h_2.ent-d1irxa2.ent", "d1a8h_2.ent-d1ivsa4.ent", "d1a8h_2.ent-d1j09a2.ent", "d1a8h_2.ent-d1jhda2.ent", "d1a8h_2.ent-d1jila_.ent", "d1a8h_2.ent-d1k4ma_.ent", "d1a8h_2.ent-d1kama_.ent", "d1a8h_2.ent-d1kqna_.ent", "d1a8h_2.ent-d1li5a2.ent", "d1a8h_2.ent-d1n3la_.ent", "d1a8h_2.ent-d1qjca_.ent", "d1a8l_1.ent-d1a8l_2.ent", "d1a8l_1.ent-d1a8y_2.ent", "d1a8l_1.ent-d1a8y_3.ent", "d1a8l_1.ent-d1aba__.ent", "d1a8l_1.ent-d1aqwa2.ent", "d1a8l_1.ent-d1bed_2.ent", "d1a8l_1.ent-d1bjx__.ent", "d1a8l_1.ent-d1e6ba2.ent", "d1a8l_1.ent-d1ep7a_.ent", "d1a8l_1.ent-d1erv__.ent", "d1a8l_1.ent-d1f9ma_.ent", "d1a8l_1.ent-d1fb6a_.ent", "d1a8l_1.ent-d1fhe_2.ent", "d1a8l_1.ent-d1gh2a_.ent", "d1a8l_1.ent-d1hyua4.ent", "d1a8l_1.ent-d1iloa_.ent", "d1a8l_1.ent-d1k0ma2.ent", "d1a8l_1.ent-d1k3ya2.ent", "d1a8l_1.ent-d1kte__.ent", "d1a8l_1.ent-d1m2da_.ent", "d1a8l_1.ent-d1qmha1.ent", "d1a8l_1.ent-d1quwa_.ent", "d1a8l_1.ent-d1thx__.ent", "d1a8l_1.ent-d2trxa_.ent", "d1a8l_2.ent-d1a8y_2.ent", "d1a8l_2.ent-d1aba__.ent", "d1a8l_2.ent-d1aqwa2.ent", "d1a8l_2.ent-d1e6ba2.ent", "d1a8l_2.ent-d1erv__.ent", "d1a8l_2.ent-d1fb6a_.ent", "d1a8l_2.ent-d1fhe_2.ent", "d1a8l_2.ent-d1gh2a_.ent", "d1a8l_2.ent-d1hyua4.ent", "d1a8l_2.ent-d1iloa_.ent", "d1a8l_2.ent-d1k0ma2.ent", "d1a8l_2.ent-d1k3ya2.ent", "d1a8l_2.ent-d1kte__.ent", "d1a8l_2.ent-d1m2da_.ent", "d1a8l_2.ent-d1qmha1.ent", "d1a8l_2.ent-d1quwa_.ent", "d1a8p_1.ent-d1cqxa2.ent", "d1a8p_1.ent-d1dar_1.ent", "d1a8p_1.ent-d1ddga1.ent", "d1a8p_1.ent-d1ep3b1.ent", "d1a8p_1.ent-d1f20a1.ent", "d1a8p_1.ent-d1f60a1.ent", "d1a8p_1.ent-d1fdr_1.ent", "d1a8p_1.ent-d1fnc_1.ent", "d1a8p_1.ent-d1fuia1.ent", "d1a8p_1.ent-d1g7sa1.ent", "d1a8p_1.ent-d1g7sa2.ent", "d1a8p_1.ent-d1i7pa1.ent", "d1a8p_1.ent-d1i8da1.ent", "d1a8p_1.ent-d1i8da2.ent", "d1a8p_1.ent-d1ja1a1.ent", "d1a8p_1.ent-d1jb9a1.ent", "d1a8p_1.ent-d1jj2b_.ent", "d1a8p_1.ent-d1kk1a1.ent", "d1a8p_1.ent-d1krha1.ent", "d1a8p_1.ent-d1kzla1.ent", "d1a8p_1.ent-d1kzla2.ent", "d1a8p_1.ent-d1n08a_.ent", "d1a8p_1.ent-d1n0ua1.ent", "d1a8p_1.ent-d1qfja1.ent", "d1a8p_1.ent-d1que_1.ent", "d1a8p_1.ent-d2cnd_1.ent", "d1a8p_1.ent-d2pia_1.ent", "d1a8p_2.ent-d1cqxa3.ent", "d1a8p_2.ent-d1ddga2.ent", "d1a8p_2.ent-d1ep3b2.ent", "d1a8p_2.ent-d1f20a2.ent", "d1a8p_2.ent-d1fdr_2.ent", "d1a8p_2.ent-d1gvha3.ent", "d1a8p_2.ent-d1i7pa2.ent", "d1a8p_2.ent-d1ja1a3.ent", "d1a8p_2.ent-d1jb9a2.ent", "d1a8p_2.ent-d1krha2.ent", "d1a8p_2.ent-d1qfja2.ent", "d1a8p_2.ent-d1que_2.ent", "d1a8p_2.ent-d2cnd_2.ent", "d1a8p_2.ent-d2pia_2.ent", "d1a8ra_.ent-d1b66a_.ent", "d1a8ra_.ent-d1b9la_.ent", "d1a8ra_.ent-d1dhn__.ent", "d1a8ra_.ent-d1is8a_.ent", "d1a8ra_.ent-d1uox_1.ent", "d1a8ra_.ent-d1uox_2.ent", "d1a8y_1.ent-d1a8l_1.ent", "d1a8y_1.ent-d1a8l_2.ent", "d1a8y_1.ent-d1a8y_2.ent", "d1a8y_1.ent-d1a8y_3.ent", "d1a8y_1.ent-d1aba__.ent", "d1a8y_1.ent-d1aqwa2.ent", "d1a8y_1.ent-d1bed_2.ent", "d1a8y_1.ent-d1bjx__.ent", "d1a8y_1.ent-d1e6ba2.ent", "d1a8y_1.ent-d1ep7a_.ent", "d1a8y_1.ent-d1erv__.ent", "d1a8y_1.ent-d1f9ma_.ent", "d1a8y_1.ent-d1fb6a_.ent", "d1a8y_1.ent-d1fhe_2.ent", "d1a8y_1.ent-d1fvka2.ent", "d1a8y_1.ent-d1g7ea_.ent", "d1a8y_1.ent-d1gh2a_.ent", "d1a8y_1.ent-d1hyua4.ent", "d1a8y_1.ent-d1iloa_.ent", "d1a8y_1.ent-d1k0ma2.ent", "d1a8y_1.ent-d1k3ya2.ent", "d1a8y_1.ent-d1kte__.ent", "d1a8y_1.ent-d1m2da_.ent", "d1a8y_1.ent-d1mek__.ent", "d1a8y_1.ent-d1qmha1.ent", "d1a8y_1.ent-d1quwa_.ent", "d1a8y_1.ent-d1thx__.ent", "d1a8y_1.ent-d2trxa_.ent", "d1a8y_2.ent-d1aba__.ent", "d1a8y_2.ent-d1aqwa2.ent", "d1a8y_2.ent-d1e6ba2.ent", "d1a8y_2.ent-d1fhe_2.ent", "d1a8y_2.ent-d1hyua4.ent", "d1a8y_2.ent-d1iloa_.ent", "d1a8y_2.ent-d1k0ma2.ent", "d1a8y_2.ent-d1k3ya2.ent", "d1a8y_2.ent-d1m2da_.ent", "d1a8y_2.ent-d1qmha1.ent", "d1a8y_3.ent-d1a8l_2.ent", "d1a8y_3.ent-d1a8y_2.ent", "d1a8y_3.ent-d1aba__.ent", "d1a8y_3.ent-d1aqwa2.ent", "d1a8y_3.ent-d1bjx__.ent", "d1a8y_3.ent-d1e6ba2.ent", "d1a8y_3.ent-d1ep7a_.ent", "d1a8y_3.ent-d1erv__.ent", "d1a8y_3.ent-d1f9ma_.ent", "d1a8y_3.ent-d1fb6a_.ent", "d1a8y_3.ent-d1fhe_2.ent", "d1a8y_3.ent-d1gh2a_.ent", "d1a8y_3.ent-d1hyua4.ent", "d1a8y_3.ent-d1iloa_.ent", "d1a8y_3.ent-d1k0ma2.ent", "d1a8y_3.ent-d1k3ya2.ent", "d1a8y_3.ent-d1kte__.ent", "d1a8y_3.ent-d1m2da_.ent", "d1a8y_3.ent-d1qmha1.ent", "d1a8y_3.ent-d1quwa_.ent", "d1a8y_3.ent-d1thx__.ent", "d1a8y_3.ent-d2trxa_.ent", "d1a99a_.ent-d1al3__.ent", "d1a99a_.ent-d1amf__.ent", "d1a99a_.ent-d1atg__.ent", "d1a99a_.ent-d1dpe__.ent", "d1a99a_.ent-d1eu8a_.ent", "d1a99a_.ent-d1h76a2.ent", "d1a99a_.ent-d1i6aa_.ent", "d1a99a_.ent-d1ii5a_.ent", "d1a99a_.ent-d1ixh__.ent", "d1a99a_.ent-d1jeta_.ent", "d1a99a_.ent-d1kwha_.ent", "d1a99a_.ent-d1lst__.ent", "d1a99a_.ent-d1m5ea_.ent", "d1a99a_.ent-d1mrp__.ent", "d1a99a_.ent-d1nh8a1.ent", "d1a99a_.ent-d1pda_1.ent", "d1a99a_.ent-d1pot__.ent", "d1a99a_.ent-d1sbp__.ent", "d1a99a_.ent-d1wdna_.ent", "d1a99a_.ent-d3mbp__.ent", "d1a99a_.ent-d3thia_.ent", "d1a9na_.ent-d1dcea3.ent", "d1a9na_.ent-d1h6ta2.ent", "d1a9na_.ent-d1h6ua2.ent", "d1a9na_.ent-d1igra1.ent", "d1a9na_.ent-d1igra2.ent", "d1a9na_.ent-d1ivoa1.ent", "d1a9na_.ent-d1ivoa2.ent", "d1a9na_.ent-d1jl5a_.ent", "d1a9na_.ent-d1koha1.ent", "d1a9na_.ent-d1m0za_.ent", "d1a9na_.ent-d1m6ba1.ent", "d1a9na_.ent-d1m6ba2.ent", "d1a9na_.ent-d1n8yc1.ent", "d1a9na_.ent-d1n8yc2.ent", "d1a9xa3.ent-d1a9xa4.ent", "d1a9xa3.ent-d1b6ra2.ent", "d1a9xa3.ent-d1e4ea1.ent", "d1a9xa3.ent-d1ehia1.ent", "d1a9xa3.ent-d1gsa_1.ent", "d1a9xa3.ent-d1gsoa2.ent", "d1a9xa3.ent-d1iow_1.ent", "d1a9xa3.ent-d1kjqa2.ent", "d1a9xa3.ent-d1m0wa1.ent", "d1a9xa3.ent-d2hgsa1.ent", "d1a9xa4.ent-d1b6ra2.ent", "d1a9xa4.ent-d1e4ea1.ent", "d1a9xa4.ent-d1ehia1.ent", "d1a9xa4.ent-d1gsa_1.ent", "d1a9xa4.ent-d1gsoa2.ent", "d1a9xa4.ent-d1iow_1.ent", "d1a9xa4.ent-d1kjqa2.ent", "d1a9xa4.ent-d1m0wa1.ent", "d1a9xa4.ent-d2hgsa1.ent", "d1a9xa5.ent-d1a9xa6.ent", "d1a9xa5.ent-d1b04a_.ent", "d1a9xa5.ent-d1b6ra3.ent", "d1a9xa5.ent-d1ckma2.ent", "d1a9xa5.ent-d1dv1a3.ent", "d1a9xa5.ent-d1e4ea2.ent", "d1a9xa5.ent-d1ehia2.ent", "d1a9xa5.ent-d1eucb2.ent", "d1a9xa5.ent-d1fvia2.ent", "d1a9xa5.ent-d1gsa_2.ent", "d1a9xa5.ent-d1gsoa3.ent", "d1a9xa5.ent-d1iow_2.ent", "d1a9xa5.ent-d1jkjb2.ent", "d1a9xa5.ent-d1kbla3.ent", "d1a9xa5.ent-d1kjqa3.ent", "d1a9xa5.ent-d1m0wa2.ent", "d1a9xa5.ent-d2hgsa4.ent", "d1a9xa6.ent-d1b6ra3.ent", "d1a9xa6.ent-d1dv1a3.ent", "d1a9xa6.ent-d1e4ea2.ent", "d1a9xa6.ent-d1ehia2.ent", "d1a9xa6.ent-d1eucb2.ent", "d1a9xa6.ent-d1gsa_2.ent", "d1a9xa6.ent-d1gsoa3.ent", "d1a9xa6.ent-d1iow_2.ent", "d1a9xa6.ent-d1jkjb2.ent", "d1a9xa6.ent-d1kbla3.ent", "d1a9xa6.ent-d1kjqa3.ent", "d1a9xa6.ent-d1m0wa2.ent", "d1a9xa6.ent-d2hgsa4.ent", "d1a9xb1.ent-d1aco_1.ent", "d1a9xb1.ent-d1de4c2.ent", "d1a9xb1.ent-d1gmla_.ent", "d1a9xb1.ent-d1kbla2.ent", "d1a9xb1.ent-d1kid__.ent", "d1a9xb1.ent-d1l5ja2.ent", "d1a9xb1.ent-d1nbwa1.ent", "d1aa6_1.ent-d1bw3__.ent", "d1aa6_1.ent-d1cr5a1.ent", "d1aa6_1.ent-d1cz4a1.ent", "d1aa6_1.ent-d1e32a1.ent", "d1aa6_1.ent-d1eu1a1.ent", "d1aa6_1.ent-d1g8ka1.ent", "d1aa6_1.ent-d1h0ha1.ent", "d1aa6_1.ent-d1kqfa1.ent", "d1aa6_1.ent-d1n10a2.ent", "d1aa6_1.ent-d1tmo_1.ent", "d1aa6_1.ent-d2napa1.ent", "d1aac__.ent-d1e30a_.ent", "d1aac__.ent-d1gyca3.ent", "d1aac__.ent-d1hfua2.ent", "d1aac__.ent-d1ibya_.ent", "d1aac__.ent-d1ikop_.ent", "d1aac__.ent-d1jzga_.ent", "d1aac__.ent-d1kcw_1.ent", "d1aac__.ent-d1kcw_2.ent", "d1aac__.ent-d1kv7a1.ent", "d1aac__.ent-d1kv7a2.ent", "d1aac__.ent-d1kv7a3.ent", "d1aac__.ent-d1kzqa1.ent", "d1aac__.ent-d1l9qa1.ent", "d1aac__.ent-d1l9qa2.ent", "d1aac__.ent-d2cbp__.ent", "d1aac__.ent-d2cuaa_.ent", "d1aapa_.ent-d1bf0__.ent", "d1aapa_.ent-d1bik_1.ent", "d1aapa_.ent-d1bik_2.ent", "d1aapa_.ent-d1bunb_.ent", "d1aapa_.ent-d1d0da_.ent", "d1aapa_.ent-d1g6xa_.ent", "d1aapa_.ent-d1irha_.ent", "d1aapa_.ent-d1ktha_.ent", "d1aapa_.ent-d1tfxc_.ent", "d1aapa_.ent-d1tocr1.ent", "d1aapa_.ent-d1tocr2.ent", "d1aba__.ent-d1aqwa2.ent", "d1aba__.ent-d1e6ba2.ent", "d1aba__.ent-d1fhe_2.ent", "d1aba__.ent-d1iloa_.ent", "d1aba__.ent-d1k0ma2.ent", "d1aba__.ent-d1k3ya2.ent", "d1abra_.ent-d1ce7a_.ent", "d1abra_.ent-d1d6aa_.ent", "d1abra_.ent-d1dm0a_.ent", "d1abra_.ent-d1hwma_.ent", "d1abra_.ent-d1ift__.ent", "d1abra_.ent-d1mrj__.ent", "d1abra_.ent-d1qi7a_.ent", "d1abrb1.ent-d1abrb2.ent", "d1abrb1.ent-d1avwb_.ent", "d1abrb1.ent-d1bfg__.ent", "d1abrb1.ent-d1ce7b2.ent", "d1abrb1.ent-d1dfca1.ent", "d1abrb1.ent-d1dfca2.ent", "d1abrb1.ent-d1dfca3.ent", "d1abrb1.ent-d1dqga_.ent", "d1abrb1.ent-d1hcd__.ent", "d1abrb1.ent-d1hwmb1.ent", "d1abrb1.ent-d1hwmb2.ent", "d1abrb1.ent-d1jlxa1.ent", "d1abrb1.ent-d1knma_.ent", "d1abrb1.ent-d1l2ha_.ent", "d1abrb1.ent-d1n4ka2.ent", "d1abrb2.ent-d1ce7b2.ent", "d1abrb2.ent-d1dqga_.ent", "d1abrb2.ent-d1hwmb1.ent", "d1abrb2.ent-d1hwmb2.ent", "d1abrb2.ent-d1knma_.ent", "d1ac5__.ent-d1bu8a2.ent", "d1ac5__.ent-d1cpy__.ent", "d1ac5__.ent-d1cr6a2.ent", "d1ac5__.ent-d1cvl__.ent", "d1ac5__.ent-d1hlga_.ent", "d1ac5__.ent-d1ivya_.ent", "d1ac5__.ent-d1iz7a_.ent", "d1ac5__.ent-d1jjia_.ent", "d1ac5__.ent-d1jkma_.ent", "d1ac5__.ent-d1ju3a2.ent", "d1ac5__.ent-d1ku0a_.ent", "d1ac5__.ent-d1l7aa_.ent", "d1ac5__.ent-d1lnsa3.ent", "d1ac5__.ent-d1lzla_.ent", "d1ac5__.ent-d1qe3a_.ent", "d1ac5__.ent-d1qlwa_.ent", "d1ac5__.ent-d1qo7a_.ent", "d1ac5__.ent-d1qtra_.ent", "d1ac5__.ent-d1tca__.ent", "d1acf__.ent-d1pne__.ent", "d1acf__.ent-d1ypra_.ent", "d1aco_1.ent-d1de4c2.ent", "d1aco_1.ent-d1gmla_.ent", "d1aco_1.ent-d1kbla2.ent", "d1aco_1.ent-d1kid__.ent", "d1aco_1.ent-d1l5ja2.ent", "d1aco_1.ent-d1nbwa1.ent", "d1acz__.ent-d1cqya_.ent", "d1acz__.ent-d1pama2.ent", "d1acz__.ent-d1qhoa2.ent", "d1ad1a_.ent-d1aj2__.ent", "d1ad1a_.ent-d1eyea_.ent", "d1ad1a_.ent-d1f6ya_.ent", "d1ad3a_.ent-d1cw3a_.ent", "d1ad3a_.ent-d1euha_.ent", "d1ad3a_.ent-d1ez0a_.ent", "d1ad3a_.ent-d1ky8a_.ent", "d1adoa_.ent-d1d9ea_.ent", "d1adoa_.ent-d1dhpa_.ent", "d1adoa_.ent-d1dosa_.ent", "d1adoa_.ent-d1epxa_.ent", "d1adoa_.ent-d1euaa_.ent", "d1adoa_.ent-d1f74a_.ent", "d1adoa_.ent-d1gvfa_.ent", "d1adoa_.ent-d1gzga_.ent", "d1adoa_.ent-d1h7na_.ent", "d1adoa_.ent-d1hfba_.ent", "d1adoa_.ent-d1i2oa_.ent", "d1adoa_.ent-d1jcla_.ent", "d1adoa_.ent-d1jcxa_.ent", "d1adoa_.ent-d1l6wa_.ent", "d1adoa_.ent-d1mzha_.ent", "d1adoa_.ent-d1nal1_.ent", "d1adoa_.ent-d1o0ya_.ent", "d1adoa_.ent-d1qfea_.ent", "d1adr__.ent-d1b0na2.ent", "d1adr__.ent-d1d1la_.ent", "d1adr__.ent-d1e3oc2.ent", "d1adr__.ent-d1efaa1.ent", "d1adr__.ent-d1ic8a2.ent", "d1adr__.ent-d1lmb3_.ent", "d1adr__.ent-d1ner__.ent", "d1adr__.ent-d1r69__.ent", "d1adr__.ent-d1uxc__.ent", "d1adr__.ent-d1uxd__.ent", "d1adr__.ent-d1vpwa1.ent", "d1adr__.ent-d2cro__.ent", "d1ae7__.ent-d1buna_.ent", "d1ae7__.ent-d1faza_.ent", "d1ae7__.ent-d1g4ia_.ent", "d1ae7__.ent-d1kvoa_.ent", "d1ae7__.ent-d1le6a_.ent", "d1ae7__.ent-d1mc2a_.ent", "d1ae7__.ent-d1poc__.ent", "d1af7_2.ent-d1ej0a_.ent", "d1af7_2.ent-d1f3la_.ent", "d1af7_2.ent-d1fp2a2.ent", "d1af7_2.ent-d1g38a_.ent", "d1af7_2.ent-d1g60a_.ent", "d1af7_2.ent-d1hnna_.ent", "d1af7_2.ent-d1i4wa_.ent", "d1af7_2.ent-d1inla_.ent", "d1af7_2.ent-d1jg1a_.ent", "d1af7_2.ent-d1jqea_.ent", "d1af7_2.ent-d1jsxa_.ent", "d1af7_2.ent-d1khha_.ent", "d1af7_2.ent-d1vid__.ent", "d1af7_2.ent-d1xvaa_.ent", "d1af7_2.ent-d2dpma_.ent", "d1af7_2.ent-d3mag__.ent", "d1af8__.ent-d1dnya_.ent", "d1af8__.ent-d1dv5a_.ent", "d1af8__.ent-d1klpa_.ent", "d1af8__.ent-d1l0ia_.ent", "d1afj__.ent-d1aw0__.ent", "d1afj__.ent-d1cc8a_.ent", "d1afj__.ent-d1cpza_.ent", "d1afj__.ent-d1fe0a_.ent", "d1afj__.ent-d1fvqa_.ent", "d1afj__.ent-d1jwwa_.ent", "d1afj__.ent-d1k0va_.ent", "d1afj__.ent-d1mwza_.ent", "d1afra_.ent-d1dpsa_.ent", "d1afra_.ent-d1euma_.ent", "d1afra_.ent-d1h0oa_.ent", "d1afra_.ent-d1jgca_.ent", "d1afra_.ent-d1ji4a_.ent", "d1afra_.ent-d1jiga_.ent", "d1afra_.ent-d1jk0b_.ent", "d1afra_.ent-d1jkva_.ent", "d1afra_.ent-d1jqca_.ent", "d1afra_.ent-d1kgna_.ent", "d1afra_.ent-d1lkoa1.ent", "d1afra_.ent-d1mtyb_.ent", "d1afra_.ent-d1mtyd_.ent", "d1afra_.ent-d1qgha_.ent", "d1afra_.ent-d1rcd__.ent", "d1afwa1.ent-d1afwa2.ent", "d1afwa1.ent-d1bi5a2.ent", "d1afwa1.ent-d1e5ma1.ent", "d1afwa1.ent-d1e5ma2.ent", "d1afwa1.ent-d1ek4a1.ent", "d1afwa1.ent-d1ek4a2.ent", "d1afwa1.ent-d1hnja1.ent", "d1afwa1.ent-d1hnja2.ent", "d1afwa1.ent-d1hzpa1.ent", "d1afwa1.ent-d1hzpa2.ent", "d1afwa1.ent-d1kas_1.ent", "d1afwa1.ent-d1m3ka1.ent", "d1afwa1.ent-d1m3ka2.ent", "d1afwa1.ent-d1mzja1.ent", "d1afwa1.ent-d1mzja2.ent", "d1afwa2.ent-d1bi5a2.ent", "d1afwa2.ent-d1e5ma1.ent", "d1afwa2.ent-d1e5ma2.ent", "d1afwa2.ent-d1ek4a1.ent", "d1afwa2.ent-d1ek4a2.ent", "d1afwa2.ent-d1hnja1.ent", "d1afwa2.ent-d1hnja2.ent", "d1afwa2.ent-d1hzpa1.ent", "d1afwa2.ent-d1hzpa2.ent", "d1afwa2.ent-d1kas_1.ent", "d1afwa2.ent-d1m3ka1.ent", "d1afwa2.ent-d1m3ka2.ent", "d1afwa2.ent-d1mzja1.ent", "d1afwa2.ent-d1mzja2.ent", "d1ag9a_.ent-d1bvyf_.ent", "d1ag9a_.ent-d1d4aa_.ent", "d1ag9a_.ent-d1e5da1.ent", "d1ag9a_.ent-d1f4pa_.ent", "d1ag9a_.ent-d1fuea_.ent", "d1ag9a_.ent-d1ja1a2.ent", "d1ag9a_.ent-d1qr2a_.ent", "d1ag9a_.ent-d1rcf__.ent", "d1ag9a_.ent-d2fcr__.ent", "d1ag9a_.ent-d5nul__.ent", "d1agg__.ent-d1axh__.ent", "d1agg__.ent-d1b9wa1.ent", "d1agg__.ent-d1b9wa2.ent", "d1agg__.ent-d1c6wa_.ent", "d1agg__.ent-d1cixa_.ent", "d1agg__.ent-d1d1ha_.ent", "d1agg__.ent-d1dl0a_.ent", "d1agg__.ent-d1eit__.ent", "d1agg__.ent-d1emxa_.ent", "d1agg__.ent-d1flei_.ent", "d1agg__.ent-d1g9pa_.ent", "d1agg__.ent-d1gps__.ent", "d1agg__.ent-d1h59b_.ent", "d1agg__.ent-d1hyka_.ent", "d1agg__.ent-d1i25a_.ent", "d1agg__.ent-d1i26a_.ent", "d1agg__.ent-d1i2ua_.ent", "d1agg__.ent-d1imt_2.ent", "d1agg__.ent-d1jkza_.ent", "d1agg__.ent-d1koza_.ent", "d1agg__.ent-d1kqha_.ent", "d1agg__.ent-d1lpba2.ent", "d1agg__.ent-d1lqra_.ent", "d1agg__.ent-d1lupa_.ent", "d1agg__.ent-d1nixa_.ent", "d1agg__.ent-d1niya_.ent", "d1agg__.ent-d1qk6a_.ent", "d1agg__.ent-d1qk7a_.ent", "d1agg__.ent-d1vtx__.ent", "d1agi__.ent-d1gqva_.ent", "d1agi__.ent-d1rnfa_.ent", "d1agja_.ent-d1arb__.ent", "d1agja_.ent-d1azza_.ent", "d1agja_.ent-d1befa_.ent", "d1agja_.ent-d1bio__.ent", "d1agja_.ent-d1bqya_.ent", "d1agja_.ent-d1cgha_.ent", "d1agja_.ent-d1cqqa_.ent", "d1agja_.ent-d1eaxa_.ent", "d1agja_.ent-d1ekbb_.ent", "d1agja_.ent-d1elva1.ent", "d1agja_.ent-d1fjsa_.ent", "d1agja_.ent-d1gdna_.ent", "d1agja_.ent-d1gpza1.ent", "d1agja_.ent-d1gvkb_.ent", "d1agja_.ent-d1gvza_.ent", "d1agja_.ent-d1hava_.ent", "d1agja_.ent-d1hj9a_.ent", "d1agja_.ent-d1lcya2.ent", "d1agja_.ent-d1lvmb_.ent", "d1agja_.ent-d1lvoa_.ent", "d1agja_.ent-d1m9ua_.ent", "d1agja_.ent-d1mbma_.ent", "d1agja_.ent-d1mzaa_.ent", "d1agja_.ent-d1qq4a_.ent", "d1agja_.ent-d1rfna_.ent", "d1agja_.ent-d1svpa_.ent", "d1agja_.ent-d2hlca_.ent", "d1agja_.ent-d2hrva_.ent", "d1agqa_.ent-d1aoca_.ent", "d1agqa_.ent-d1bnda_.ent", "d1agqa_.ent-d1fl7b_.ent", "d1agqa_.ent-d1fltv_.ent", "d1agqa_.ent-d1hcna_.ent", "d1agqa_.ent-d1hcnb_.ent", "d1agqa_.ent-d1jpya_.ent", "d1agqa_.ent-d1m4ua_.ent", "d1agqa_.ent-d1m4ul_.ent", "d1agqa_.ent-d1pdga_.ent", "d1agqa_.ent-d2tgi__.ent", "d1agre_.ent-d1cmza_.ent", "d1agre_.ent-d1dk8a_.ent", "d1agre_.ent-d1iapa_.ent", "d1ah7__.ent-d1ak0__.ent", "d1ah7__.ent-d1ca1_1.ent", "d1aho__.ent-d1agg__.ent", "d1aho__.ent-d1apq__.ent", "d1aho__.ent-d1b9wa1.ent", "d1aho__.ent-d1b9wa2.ent", "d1aho__.ent-d1bcg__.ent", "d1aho__.ent-d1bmr__.ent", "d1aho__.ent-d1bx7__.ent", "d1aho__.ent-d1c2aa1.ent", "d1aho__.ent-d1c55a_.ent", "d1aho__.ent-d1cixa_.ent", "d1aho__.ent-d1cmr__.ent", "d1aho__.ent-d1e0fi_.ent", "d1aho__.ent-d1fjna_.ent", "d1aho__.ent-d1flei_.ent", "d1aho__.ent-d1g9pa_.ent", "d1aho__.ent-d1gps__.ent", "d1aho__.ent-d1h59b_.ent", "d1aho__.ent-d1hyka_.ent", "d1aho__.ent-d1i2ua_.ent", "d1aho__.ent-d1ica__.ent", "d1aho__.ent-d1ijqa2.ent", "d1aho__.ent-d1imt_2.ent", "d1aho__.ent-d1jkza_.ent", "d1aho__.ent-d1jxca_.ent", "d1aho__.ent-d1klil_.ent", "d1aho__.ent-d1klo_1.ent", "d1aho__.ent-d1klo_3.ent", "d1aho__.ent-d1lpba2.ent", "d1aho__.ent-d1myn__.ent", "d1aho__.ent-d1npia_.ent", "d1aho__.ent-d1nrb__.ent", "d1aho__.ent-d1qkya_.ent", "d1aho__.ent-d1sco__.ent", "d1aho__.ent-d1scy__.ent", "d1aho__.ent-d1sis__.ent", "d1aho__.ent-d1tsk__.ent", "d1aho__.ent-d2sn3__.ent", "d1aho__.ent-d4htci_.ent", "d1ahsa_.ent-d1bvp12.ent", "d1ahsa_.ent-d1flca1.ent", "d1ahsa_.ent-d1jsda_.ent", "d1ahsa_.ent-d1jsma_.ent", "d1ahsa_.ent-d1qhda2.ent", "d1ahsa_.ent-d2viua_.ent", "d1aiha_.ent-d1f44a2.ent", "d1ail__.ent-d1fyja_.ent", "d1aisa1.ent-d1aisa2.ent", "d1aisa1.ent-d1ko9a2.ent", "d1aisa1.ent-d1mpga2.ent", "d1aisa1.ent-d1ytba1.ent", "d1aisa1.ent-d1ytba2.ent", "d1aisa2.ent-d1ko9a2.ent", "d1aisa2.ent-d1mpga2.ent", "d1aisa2.ent-d1ytba1.ent", "d1aisa2.ent-d1ytba2.ent", "d1aisb1.ent-d1aisb2.ent", "d1aisb1.ent-d1bu2a1.ent", "d1aisb1.ent-d1bu2a2.ent", "d1aisb1.ent-d1f5qb1.ent", "d1aisb1.ent-d1f5qb2.ent", "d1aisb1.ent-d1g3nc1.ent", "d1aisb1.ent-d1g3nc2.ent", "d1aisb1.ent-d1guxa_.ent", "d1aisb1.ent-d1guxb_.ent", "d1aisb1.ent-d1h4ld_.ent", "d1aisb1.ent-d1jkw_1.ent", "d1aisb1.ent-d1jkw_2.ent", "d1aisb1.ent-d1vin_1.ent", "d1aisb1.ent-d1vin_2.ent", "d1aisb1.ent-d1vola1.ent", "d1aisb2.ent-d1bu2a1.ent", "d1aisb2.ent-d1bu2a2.ent", "d1aisb2.ent-d1f5qb1.ent", "d1aisb2.ent-d1f5qb2.ent", "d1aisb2.ent-d1g3nc1.ent", "d1aisb2.ent-d1g3nc2.ent", "d1aisb2.ent-d1guxa_.ent", "d1aisb2.ent-d1guxb_.ent", "d1aisb2.ent-d1h4ld_.ent", "d1aisb2.ent-d1jkw_1.ent", "d1aisb2.ent-d1jkw_2.ent", "d1aisb2.ent-d1vin_1.ent", "d1aisb2.ent-d1vin_2.ent", "d1aisb2.ent-d1vola1.ent", "d1aj2__.ent-d1eyea_.ent", "d1aj2__.ent-d1f6ya_.ent", "d1aj8a_.ent-d1csh__.ent", "d1aj8a_.ent-d1k3pa_.ent", "d1aj8a_.ent-d1o7xa_.ent", "d1ajj__.ent-d1d2la_.ent", "d1ajj__.ent-d1f5ya1.ent", "d1ajj__.ent-d1f5ya2.ent", "d1ajj__.ent-d1j8ea_.ent", "d1ajj__.ent-d1k7ba_.ent", "d1ajj__.ent-d1n7da6.ent", "d1ajj__.ent-d1n7da7.ent", "d1ajj__.ent-d1n7daa.ent", "d1ajka_.ent-d1c4ra_.ent", "d1ajka_.ent-d1d2sa_.ent", "d1ajka_.ent-d1dyka2.ent", "d1ajka_.ent-d1gv9a_.ent", "d1ajka_.ent-d1h30a2.ent", "d1ajka_.ent-d1ikpa1.ent", "d1ajka_.ent-d1is3a_.ent", "d1ajka_.ent-d1jhna4.ent", "d1ajka_.ent-d1kit_1.ent", "d1ajka_.ent-d1kqra_.ent", "d1ajka_.ent-d1n1ta1.ent", "d1ajka_.ent-d1nls__.ent", "d1ajka_.ent-d1saca_.ent", "d1ajka_.ent-d2nlra_.ent", "d1ajka_.ent-d2sli_1.ent", "d1ajsa_.ent-d1b9ha_.ent", "d1ajsa_.ent-d1bs0a_.ent", "d1ajsa_.ent-d1c4ka2.ent", "d1ajsa_.ent-d1c7na_.ent", "d1ajsa_.ent-d1e5ea_.ent", "d1ajsa_.ent-d1elua_.ent", "d1ajsa_.ent-d1gdea_.ent", "d1ajsa_.ent-d1j32a_.ent", "d1ajsa_.ent-d1jf9a_.ent", "d1ajsa_.ent-d1js3a_.ent", "d1ajsa_.ent-d1kl1a_.ent", "d1ajsa_.ent-d1lc5a_.ent", "d1ajsa_.ent-d1n8pa_.ent", "d1ajsa_.ent-d1qisa_.ent", "d1ajsa_.ent-d1qj5a_.ent", "d1ajsa_.ent-d1yaaa_.ent", "d1ajsa_.ent-d2ay1a_.ent", "d1ajsa_.ent-d2oata_.ent", "d1ajsa_.ent-d3tata_.ent", "d1ajsa_.ent-d7aata_.ent", "d1ak0__.ent-d1ca1_1.ent", "d1ak4c_.ent-d1em9a_.ent", "d1ak4c_.ent-d2eiaa2.ent", "d1ak7__.ent-d1cfya_.ent", "d1ak7__.ent-d1d0na3.ent", "d1ak7__.ent-d1d0na4.ent", "d1ak7__.ent-d1d0na5.ent", "d1ak7__.ent-d1d0na6.ent", "d1ak7__.ent-d1d4xg_.ent", "d1ak7__.ent-d1f7sa_.ent", "d1ak7__.ent-d1hqz1_.ent", "d1ak7__.ent-d1jhwa3.ent", "d1ak7__.ent-d1m4ja_.ent", "d1akjd_.ent-d1b88a_.ent", "d1akjd_.ent-d1bec_1.ent", "d1akjd_.ent-d1c5ch1.ent", "d1akjd_.ent-d1dlfl_.ent", "d1akjd_.ent-d1h5ba_.ent", "d1akjd_.ent-d1nfdb1.ent", "d1akjd_.ent-d2rhe__.ent", "d1ako__.ent-d1hd7a_.ent", "d1ako__.ent-d1i9za_.ent", "d1ako__.ent-d2dnja_.ent", "d1akp__.ent-d1noa__.ent", "d1akp__.ent-d2mcm__.ent", "d1aky_2.ent-d1d09b2.ent", "d1aky_2.ent-d1d0qa_.ent", "d1aky_2.ent-d1dxga_.ent", "d1aky_2.ent-d1f4la3.ent", "d1aky_2.ent-d1gh9a_.ent", "d1aky_2.ent-d1i50i1.ent", "d1aky_2.ent-d1i50i2.ent", "d1aky_2.ent-d1i50l_.ent", "d1aky_2.ent-d1jj22_.ent", "d1aky_2.ent-d1jj2y_.ent", "d1aky_2.ent-d1jj2z_.ent", "d1aky_2.ent-d1lkoa2.ent", "d1aky_2.ent-d1m2oa5.ent", "d1aky_2.ent-d1ocrf_.ent", "d1aky_2.ent-d1pft__.ent", "d1aky_2.ent-d1rb9__.ent", "d1aky_2.ent-d1tfi__.ent", "d1aky_2.ent-d1yua_1.ent", "d1aky_2.ent-d1yua_2.ent", "d1aky_2.ent-d1zaka2.ent", "d1aky_2.ent-d1zin_2.ent", "d1al3__.ent-d1amf__.ent", "d1al3__.ent-d1atg__.ent", "d1al3__.ent-d1dpe__.ent", "d1al3__.ent-d1eu8a_.ent", "d1al3__.ent-d1h76a2.ent", "d1al3__.ent-d1i6aa_.ent", "d1al3__.ent-d1ii5a_.ent", "d1al3__.ent-d1ixh__.ent", "d1al3__.ent-d1jeta_.ent", "d1al3__.ent-d1kwha_.ent", "d1al3__.ent-d1lst__.ent", "d1al3__.ent-d1m5ea_.ent", "d1al3__.ent-d1mrp__.ent", "d1al3__.ent-d1nh8a1.ent", "d1al3__.ent-d1pda_1.ent", "d1al3__.ent-d1pot__.ent", "d1al3__.ent-d1sbp__.ent", "d1al3__.ent-d1wdna_.ent", "d1al3__.ent-d3mbp__.ent", "d1al3__.ent-d3thia_.ent", "d1alla_.ent-d1a6m__", "d1alla_.ent-d1a6m__.ent", "d1alla_.ent-d1ash__", "d1alla_.ent-d1ash__.ent", "d1alla_.ent-d1cg5a_", "d1alla_.ent-d1cg5a_.ent", "d1alla_.ent-d1cg5b_", "d1alla_.ent-d1cg5b_.ent", "d1alla_.ent-d1cqxa1", "d1alla_.ent-d1cqxa1.ent", "d1alla_.ent-d1ew6a_", "d1alla_.ent-d1ew6a_.ent", "d1alla_.ent-d1gcva_", "d1alla_.ent-d1gcva_.ent", "d1alla_.ent-d1gvha1", "d1alla_.ent-d1gvha1.ent", "d1alla_.ent-d1h97a_", "d1alla_.ent-d1h97a_.ent", "d1alla_.ent-d1hlb__", "d1alla_.ent-d1hlb__.ent", "d1alla_.ent-d1irda_", "d1alla_.ent-d1irda_.ent", "d1alla_.ent-d1irdb_", "d1alla_.ent-d1irdb_.ent", "d1alla_.ent-d1it2a_", "d1alla_.ent-d1it2a_.ent", "d1alla_.ent-d1itha_", "d1alla_.ent-d1itha_.ent", "d1alla_.ent-d1jl7a_", "d1alla_.ent-d1jl7a_.ent", "d1alla_.ent-d1la6a_", "d1alla_.ent-d1la6a_.ent", "d1alla_.ent-d1mba__", "d1alla_.ent-d1mba__.ent", "d1alla_.ent-d2gdm__", "d1alla_.ent-d2gdm__.ent", "d1alla_.ent-d2lhb__", "d1alla_.ent-d2lhb__.ent", "d1alla_.ent-d3sdha_", "d1alla_.ent-d3sdha_.ent", "d1allb_.ent-d1a6m__", "d1allb_.ent-d1a6m__.ent", "d1allb_.ent-d1alla_", "d1allb_.ent-d1alla_.ent", "d1allb_.ent-d1ash__", "d1allb_.ent-d1ash__.ent", "d1allb_.ent-d1cg5a_", "d1allb_.ent-d1cg5a_.ent", "d1allb_.ent-d1cg5b_", "d1allb_.ent-d1cg5b_.ent", "d1allb_.ent-d1cqxa1", "d1allb_.ent-d1cqxa1.ent", "d1allb_.ent-d1ew6a_", "d1allb_.ent-d1ew6a_.ent", "d1allb_.ent-d1gcva_", "d1allb_.ent-d1gcva_.ent", "d1allb_.ent-d1gvha1", "d1allb_.ent-d1gvha1.ent", "d1allb_.ent-d1h97a_", "d1allb_.ent-d1h97a_.ent", "d1allb_.ent-d1hlb__", "d1allb_.ent-d1hlb__.ent", "d1allb_.ent-d1irda_", "d1allb_.ent-d1irda_.ent", "d1allb_.ent-d1irdb_", "d1allb_.ent-d1irdb_.ent", "d1allb_.ent-d1it2a_", "d1allb_.ent-d1it2a_.ent", "d1allb_.ent-d1itha_", "d1allb_.ent-d1itha_.ent", "d1allb_.ent-d1jl7a_", "d1allb_.ent-d1jl7a_.ent", "d1allb_.ent-d1la6a_", "d1allb_.ent-d1la6a_.ent", "d1allb_.ent-d1mba__", "d1allb_.ent-d1mba__.ent", "d1allb_.ent-d2gdm__", "d1allb_.ent-d2gdm__.ent", "d1allb_.ent-d2lhb__", "d1allb_.ent-d2lhb__.ent", "d1allb_.ent-d3sdha_", "d1allb_.ent-d3sdha_.ent", "d1aln_1.ent-d1aln_2.ent", "d1aln_1.ent-d1jtka_.ent", "d1aln_2.ent-d1jtka_.ent", "d1alu__.ent-d1au1a_.ent", "d1alu__.ent-d1ax8__.ent", "d1alu__.ent-d1b5l__.ent", "d1alu__.ent-d1bgc__.ent", "d1alu__.ent-d1cnt1_.ent", "d1alu__.ent-d1d9ca_.ent", "d1alu__.ent-d1eera_.ent", "d1alu__.ent-d1etea_.ent", "d1alu__.ent-d1evsa_.ent", "d1alu__.ent-d1f45b_.ent", "d1alu__.ent-d1f6fa_.ent", "d1alu__.ent-d1hula_.ent", "d1alu__.ent-d1huw__.ent", "d1alu__.ent-d1hzia_.ent", "d1alu__.ent-d1i1rb_.ent", "d1alu__.ent-d1jli__.ent", "d1alu__.ent-d1lki__.ent", "d1alu__.ent-d1lqsl_.ent", "d1alu__.ent-d1m47a_.ent", "d1alu__.ent-d1n1fa_.ent", "d1alu__.ent-d2gmfa_.ent", "d1alu__.ent-d2ilk__.ent", "d1alva_.ent-d1auib_.ent", "d1alva_.ent-d1eg3a1.ent", "d1alva_.ent-d1exra_.ent", "d1alva_.ent-d1ggwa_.ent", "d1alva_.ent-d1jfja_.ent", "d1alva_.ent-d1k94a_.ent", "d1alva_.ent-d1m31a_.ent", "d1alva_.ent-d1m45a_.ent", "d1alva_.ent-d1ncx__.ent", "d1alva_.ent-d1rro__.ent", "d1alva_.ent-d1sra__.ent", "d1alva_.ent-d1wdcb_.ent", "d1alva_.ent-d1wdcc_.ent", "d1alva_.ent-d2pvba_.ent", "d1alva_.ent-d5pal__.ent", "d1aly__.ent-d1dg6a_.ent", "d1aly__.ent-d1gr3a_.ent", "d1aly__.ent-d1kxga_.ent", "d1aly__.ent-d1tnra_.ent", "d1aly__.ent-d2tnfa_.ent", "d1am2__.ent-d1dq3a1.ent", "d1am2__.ent-d1gppa_.ent", "d1am9a_.ent-d1an4a_.ent", "d1am9a_.ent-d1mdya_.ent", "d1am9a_.ent-d1nkpa_.ent", "d1am9a_.ent-d1nkpb_.ent", "d1am9a_.ent-d1nlwa_.ent", "d1amf__.ent-d1atg__.ent", "d1amf__.ent-d1dpe__.ent", "d1amf__.ent-d1eu8a_.ent", "d1amf__.ent-d1h76a2.ent", "d1amf__.ent-d1i6aa_.ent", "d1amf__.ent-d1ii5a_.ent", "d1amf__.ent-d1ixh__.ent", "d1amf__.ent-d1jeta_.ent", "d1amf__.ent-d1kwha_.ent", "d1amf__.ent-d1lst__.ent", "d1amf__.ent-d1m5ea_.ent", "d1amf__.ent-d1mrp__.ent", "d1amf__.ent-d1nh8a1.ent", "d1amf__.ent-d1pda_1.ent", "d1amf__.ent-d1pot__.ent", "d1amf__.ent-d1sbp__.ent", "d1amf__.ent-d1wdna_.ent", "d1amf__.ent-d3mbp__.ent", "d1amf__.ent-d3thia_.ent", "d1amm_1.ent-d1amm_2.ent", "d1amm_1.ent-d1bhu__.ent", "d1amm_1.ent-d1c01a_.ent", "d1amm_1.ent-d1f53a_.ent", "d1amm_1.ent-d1g6ea_.ent", "d1amm_1.ent-d2bb2_1.ent", "d1amm_1.ent-d2bb2_2.ent", "d1amm_2.ent-d1bhu__.ent", "d1amm_2.ent-d1c01a_.ent", "d1amm_2.ent-d1f53a_.ent", "d1amm_2.ent-d1g6ea_.ent", "d1amm_2.ent-d2bb2_1.ent", "d1amm_2.ent-d2bb2_2.ent", "d1amua_.ent-d1lci__.ent", "d1amua_.ent-d1mdba_.ent", "d1amx__.ent-d1aoha_.ent", "d1amx__.ent-d1ayoa_.ent", "d1amx__.ent-d1bg1a2.ent", "d1amx__.ent-d1e2wa1.ent", "d1amx__.ent-d1e5ba_.ent", "d1amx__.ent-d1f0la1.ent", "d1amx__.ent-d1h6fa_.ent", "d1amx__.ent-d1i31a_.ent", "d1amx__.ent-d1klfb1.ent", "d1amx__.ent-d1klfb2.ent", "d1amx__.ent-d1m2oa2.ent", "d1amx__.ent-d1m2vb2.ent", "d1amx__.ent-d1mnna_.ent", "d1amx__.ent-d1nbca_.ent", "d1amx__.ent-d1pdkb_.ent", "d1amx__.ent-d1qba_2.ent", "d1amx__.ent-d1tf4a2.ent", "d1amx__.ent-d1ycsa_.ent", "d1an4a_.ent-d1mdya_.ent", "d1an4a_.ent-d1nkpa_.ent", "d1an4a_.ent-d1nkpb_.ent", "d1an4a_.ent-d1nlwa_.ent", "d1an8_1.ent-d1c4qa_.ent", "d1an8_1.ent-d1enfa1.ent", "d1an8_1.ent-d1esfa1.ent", "d1an8_1.ent-d1et9a1.ent", "d1an8_1.ent-d1eu3a1.ent", "d1an8_1.ent-d1fnua1.ent", "d1an8_1.ent-d1m4va1.ent", "d1an8_1.ent-d1prtb1.ent", "d1an8_1.ent-d1prtd_.ent", "d1an8_1.ent-d1prtf_.ent", "d1an8_1.ent-d1tiid_.ent", "d1an8_1.ent-d3chbd_.ent", "d1an8_1.ent-d3seb_1.ent", "d1an8_1.ent-d3tss_1.ent", "d1an8_2.ent-d1enfa2.ent", "d1an8_2.ent-d1esfa2.ent", "d1an8_2.ent-d1et9a2.ent", "d1an8_2.ent-d1eu3a2.ent", "d1an8_2.ent-d1m4va2.ent", "d1an8_2.ent-d3seb_2.ent", "d1an8_2.ent-d3tss_2.ent", "d1an9a1.ent-d1c0pa1.ent", "d1an9a1.ent-d1cjca2.ent", "d1an9a1.ent-d1gtea4.ent", "d1an9a1.ent-d1i8ta1.ent", "d1an9a1.ent-d1lqta2.ent", "d1an9a1.ent-d1o94a3.ent", "d1an9a2.ent-d1b5qa2.ent", "d1an9a2.ent-d1c0pa2.ent", "d1an9a2.ent-d1d5ta2.ent", "d1an9a2.ent-d1f8ra2.ent", "d1an9a2.ent-d1foha4.ent", "d1an9a2.ent-d1gosa2.ent", "d1an9a2.ent-d1gpea2.ent", "d1an9a2.ent-d1i8ta2.ent", "d1an9a2.ent-d1ju2a2.ent", "d1an9a2.ent-d1k0ia2.ent", "d1an9a2.ent-d1kdga2.ent", "d1an9a2.ent-d1l9ea2.ent", "d1an9a2.ent-d1mxta2.ent", "d1aoa_1.ent-d1aoa_2.ent", "d1aoa_1.ent-d1bhda_.ent", "d1aoa_1.ent-d1bkra_.ent", "d1aoa_1.ent-d1dxxa1.ent", "d1aoa_1.ent-d1h67a_.ent", "d1aoa_1.ent-d1lnsa1.ent", "d1aoa_2.ent-d1bhda_.ent", "d1aoa_2.ent-d1bkra_.ent", "d1aoa_2.ent-d1dxxa1.ent", "d1aoa_2.ent-d1h67a_.ent", "d1aoa_2.ent-d1lnsa1.ent", "d1aoca_.ent-d1bnda_.ent", "d1aoca_.ent-d1fl7b_.ent", "d1aoca_.ent-d1fltv_.ent", "d1aoca_.ent-d1hcna_.ent", "d1aoca_.ent-d1hcnb_.ent", "d1aoca_.ent-d1jpya_.ent", "d1aoca_.ent-d1m4ua_.ent", "d1aoca_.ent-d1m4ul_.ent", "d1aoca_.ent-d1pdga_.ent", "d1aoca_.ent-d2tgi__.ent", "d1aoea_.ent-d1d1ga_.ent", "d1aoea_.ent-d1df7a_.ent", "d1aoea_.ent-d1dyr__.ent", "d1aoea_.ent-d1ra9__.ent", "d1aoea_.ent-d1vdra_.ent", "d1aoea_.ent-d3dfr__.ent", "d1aoha_.ent-d1ayoa_.ent", "d1aoha_.ent-d1bg1a2.ent", "d1aoha_.ent-d1e2wa1.ent", "d1aoha_.ent-d1e5ba_.ent", "d1aoha_.ent-d1exh__.ent", "d1aoha_.ent-d1f0la1.ent", "d1aoha_.ent-d1g1ka_.ent", "d1aoha_.ent-d1g43a_.ent", "d1aoha_.ent-d1h6fa_.ent", "d1aoha_.ent-d1i31a_.ent", "d1aoha_.ent-d1klfb1.ent", "d1aoha_.ent-d1klfb2.ent", "d1aoha_.ent-d1m2oa2.ent", "d1aoha_.ent-d1m2vb2.ent", "d1aoha_.ent-d1mnna_.ent", "d1aoha_.ent-d1nbca_.ent", "d1aoha_.ent-d1pdkb_.ent", "d1aoha_.ent-d1qba_2.ent", "d1aoha_.ent-d1tf4a2.ent", "d1aoha_.ent-d1ycsa_.ent", "d1aono_.ent-d1e3ja1.ent", "d1aono_.ent-d1g31a_.ent", "d1aono_.ent-d1heta1.ent", "d1aono_.ent-d1jh2a_.ent", "d1aono_.ent-d1jqba1.ent", "d1aono_.ent-d1kola1.ent", "d1aono_.ent-d1qora1.ent", "d1aoza2.ent-d1cyx__.ent", "d1aoza2.ent-d1e30a_.ent", "d1aoza2.ent-d1gw0a1.ent", "d1aoza2.ent-d1gw0a2.ent", "d1aoza2.ent-d1hfua2.ent", "d1aoza2.ent-d1hfua3.ent", "d1aoza2.ent-d1ikop_.ent", "d1aoza2.ent-d1kbva1.ent", "d1aoza2.ent-d1kbva2.ent", "d1aoza2.ent-d1kcw_1.ent", "d1aoza2.ent-d1kcw_2.ent", "d1aoza2.ent-d1kcw_3.ent", "d1aoza2.ent-d1kcw_4.ent", "d1aoza2.ent-d1kcw_5.ent", "d1aoza2.ent-d1kcw_6.ent", "d1aoza2.ent-d1kv7a1.ent", "d1aoza2.ent-d1kv7a2.ent", "d1aoza2.ent-d1kv7a3.ent", "d1aoza2.ent-d1l9qa1.ent", "d1aoza2.ent-d1l9qa2.ent", "d1aoza2.ent-d1m56b1.ent", "d1aoza2.ent-d1qhqa_.ent", "d1aoza3.ent-d1aoza2.ent", "d1aoza3.ent-d1cyx__.ent", "d1aoza3.ent-d1e30a_.ent", "d1aoza3.ent-d1gw0a1.ent", "d1aoza3.ent-d1gw0a2.ent", "d1aoza3.ent-d1hfua2.ent", "d1aoza3.ent-d1hfua3.ent", "d1aoza3.ent-d1ikop_.ent", "d1aoza3.ent-d1kbva1.ent", "d1aoza3.ent-d1kbva2.ent", "d1aoza3.ent-d1kcw_1.ent", "d1aoza3.ent-d1kcw_2.ent", "d1aoza3.ent-d1kcw_3.ent", "d1aoza3.ent-d1kcw_4.ent", "d1aoza3.ent-d1kcw_5.ent", "d1aoza3.ent-d1kcw_6.ent", "d1aoza3.ent-d1kv7a1.ent", "d1aoza3.ent-d1kv7a2.ent", "d1aoza3.ent-d1kv7a3.ent", "d1aoza3.ent-d1l9qa1.ent", "d1aoza3.ent-d1l9qa2.ent", "d1aoza3.ent-d1m56b1.ent", "d1aoza3.ent-d1qhqa_.ent", "d1ap6a1.ent-d1b06a1.ent", "d1ap6a1.ent-d1bsma1.ent", "d1ap6a1.ent-d1coja1.ent", "d1ap6a1.ent-d1gv3a1.ent", "d1ap6a1.ent-d1isaa1.ent", "d1ap6a1.ent-d1ix9a1.ent", "d1apme_.ent-d1a06__.ent", "d1apme_.ent-d1b6cb_.ent", "d1apme_.ent-d1blxa_.ent", "d1apme_.ent-d1cjaa_.ent", "d1apme_.ent-d1csn__.ent", "d1apme_.ent-d1f3mc_.ent", "d1apme_.ent-d1fgka_.ent", "d1apme_.ent-d1fvra_.ent", "d1apme_.ent-d1ia9a_.ent", "d1apme_.ent-d1iepa_.ent", "d1apme_.ent-d1jksa_.ent", "d1apme_.ent-d1jpaa_.ent", "d1apme_.ent-d1jvpp_.ent", "d1apme_.ent-d1kwpa_.ent", "d1apme_.ent-d1lpua_.ent", "d1apme_.ent-d1lufa_.ent", "d1apme_.ent-d1m14a_.ent", "d1apme_.ent-d1phk__.ent", "d1apme_.ent-d1tkia_.ent", "d1apq__.ent-d1agg__.ent", "d1apq__.ent-d1b9wa1.ent", "d1apq__.ent-d1b9wa2.ent", "d1apq__.ent-d1bx7__.ent", "d1apq__.ent-d1ceja1.ent", "d1apq__.ent-d1ceja2.ent", "d1apq__.ent-d1cixa_.ent", "d1apq__.ent-d1cvua2.ent", "d1apq__.ent-d1dx5i1.ent", "d1apq__.ent-d1emo_1.ent", "d1apq__.ent-d1fjsl_.ent", "d1apq__.ent-d1flei_.ent", "d1apq__.ent-d1g9pa_.ent", "d1apq__.ent-d1gps__.ent", "d1apq__.ent-d1h59b_.ent", "d1apq__.ent-d1hyka_.ent", "d1apq__.ent-d1hz8a1.ent", "d1apq__.ent-d1hz8a2.ent", "d1apq__.ent-d1i2ua_.ent", "d1apq__.ent-d1ijqa2.ent", "d1apq__.ent-d1imt_2.ent", "d1apq__.ent-d1ioxa_.ent", "d1apq__.ent-d1jkza_.ent", "d1apq__.ent-d1jl9a_.ent", "d1apq__.ent-d1klo_3.ent", "d1apq__.ent-d1l3ya_.ent", "d1apq__.ent-d1lpba2.ent", "d1apq__.ent-d1m1xb5.ent", "d1apq__.ent-d1tpg_1.ent", "d1apq__.ent-d1urk_1.ent", "d1apq__.ent-d3tgf__.ent", "d1apxa_.ent-d1aru__.ent", "d1apxa_.ent-d1bgp__.ent", "d1apxa_.ent-d1cvua1.ent", "d1apxa_.ent-d1itka1.ent", "d1apxa_.ent-d1itka2.ent", "d1apxa_.ent-d1jdra_.ent", "d1apxa_.ent-d1llp__.ent", "d1apxa_.ent-d1mn2__.ent", "d1apxa_.ent-d1pa2a_.ent", "d1aqb__.ent-d1avgi_.ent", "d1aqb__.ent-d1b56__.ent", "d1aqb__.ent-d1bbpa_.ent", "d1aqb__.ent-d1beba_.ent", "d1aqb__.ent-d1bj7__.ent", "d1aqb__.ent-d1cbs__.ent", "d1aqb__.ent-d1dzka_.ent", "d1aqb__.ent-d1euoa_.ent", "d1aqb__.ent-d1ew3a_.ent", "d1aqb__.ent-d1exsa_.ent", "d1aqb__.ent-d1ftpa_.ent", "d1aqb__.ent-d1g85a_.ent", "d1aqb__.ent-d1ggla_.ent", "d1aqb__.ent-d1gkab_.ent", "d1aqb__.ent-d1hms__.ent", "d1aqb__.ent-d1i4ua_.ent", "d1aqb__.ent-d1ifc__.ent", "d1aqb__.ent-d1jv4a_.ent", "d1aqb__.ent-d1koia_.ent", "d1aqb__.ent-d1kqwa_.ent", "d1aqb__.ent-d1lf7a_.ent", "d1aqb__.ent-d1o1va_.ent", "d1aqb__.ent-d1qfta_.ent", "d1aqb__.ent-d1qqsa_.ent", "d1aqe__.ent-d1dxrc_.ent", "d1aqe__.ent-d1eysc_.ent", "d1aqe__.ent-d1fgja_.ent", "d1aqe__.ent-d1fs7a_.ent", "d1aqe__.ent-d1ft5a_.ent", "d1aqe__.ent-d1gu6a_.ent", "d1aqe__.ent-d1gyoa_.ent", "d1aqe__.ent-d1h21a_.ent", "d1aqe__.ent-d1h29a_.ent", "d1aqe__.ent-d1hh5a_.ent", "d1aqe__.ent-d1kssa1.ent", "d1aqe__.ent-d1m1qa_.ent", "d1aqe__.ent-d1qo8a1.ent", "d1aqe__.ent-d1wad__.ent", "d1aqe__.ent-d2ctha_.ent", "d1aqe__.ent-d2cy3__.ent", "d1aqe__.ent-d3caoa_.ent", "d1aqe__.ent-d3cyr__.ent", "d1aqt_1.ent-d1coja1.ent", "d1aqt_1.ent-d1cxzb_.ent", "d1aqt_1.ent-d1du2a_.ent", "d1aqt_1.ent-d1e52a_.ent", "d1aqt_1.ent-d1e79h1.ent", "d1aqt_1.ent-d1eiya1.ent", "d1aqt_1.ent-d1fpoa1.ent", "d1aqt_1.ent-d1fxkc_.ent", "d1aqt_1.ent-d1gh6a_.ent", "d1aqt_1.ent-d1grj_1.ent", "d1aqt_1.ent-d1hdj__.ent", "d1aqt_1.ent-d1ivsa1.ent", "d1aqt_1.ent-d1ix9a1.ent", "d1aqt_1.ent-d1jj2u_.ent", "d1aqt_1.ent-d1k4ta1.ent", "d1aqt_1.ent-d1lrza1.ent", "d1aqt_1.ent-d1seta1.ent", "d1aqua_.ent-d1a7j__.ent", "d1aqua_.ent-d1cr1a_.ent", "d1aqua_.ent-d1e69a_.ent", "d1aqua_.ent-d1f5na2.ent", "d1aqua_.ent-d1fnna2.ent", "d1aqua_.ent-d1g8ya_.ent", "d1aqua_.ent-d1gm5a3.ent", "d1aqua_.ent-d1jwyb_.ent", "d1aqua_.ent-d1lv7a_.ent", "d1aqua_.ent-d1m6na3.ent", "d1aqza_.ent-d1i0va_.ent", "d1aqza_.ent-d1lnia_.ent", "d1arb__.ent-d1a0la_.ent", "d1arb__.ent-d1agja_.ent", "d1arb__.ent-d1azza_.ent", "d1arb__.ent-d1befa_.ent", "d1arb__.ent-d1bio__.ent", "d1arb__.ent-d1bqya_.ent", "d1arb__.ent-d1cgha_.ent", "d1arb__.ent-d1cqqa_.ent", "d1arb__.ent-d1ddja_.ent", "d1arb__.ent-d1eaxa_.ent", "d1arb__.ent-d1ekbb_.ent", "d1arb__.ent-d1elva1.ent", "d1arb__.ent-d1fjsa_.ent", "d1arb__.ent-d1gdna_.ent", "d1arb__.ent-d1gpza1.ent", "d1arb__.ent-d1gvkb_.ent", "d1arb__.ent-d1gvza_.ent", "d1arb__.ent-d1hava_.ent", "d1arb__.ent-d1hj9a_.ent", "d1arb__.ent-d1klih_.ent", "d1arb__.ent-d1lcya2.ent", "d1arb__.ent-d1lvmb_.ent", "d1arb__.ent-d1lvoa_.ent", "d1arb__.ent-d1m9ua_.ent", "d1arb__.ent-d1mbma_.ent", "d1arb__.ent-d1mzaa_.ent", "d1arb__.ent-d1qq4a_.ent", "d1arb__.ent-d1qtfa_.ent", "d1arb__.ent-d1rfna_.ent", "d1arb__.ent-d1svpa_.ent", "d1arb__.ent-d2hlca_.ent", "d1arb__.ent-d2hrva_.ent", "d1aru__.ent-d1bgp__.ent", "d1aru__.ent-d1cvua1.ent", "d1aru__.ent-d1itka1.ent", "d1aru__.ent-d1itka2.ent", "d1aru__.ent-d1jdra_.ent", "d1aru__.ent-d1llp__.ent", "d1aru__.ent-d1mn2__.ent", "d1aru__.ent-d1pa2a_.ent", "d1ash__.ent-d1cg5a_", "d1ash__.ent-d1cg5a_.ent", "d1ash__.ent-d1cg5b_", "d1ash__.ent-d1cg5b_.ent", "d1ash__.ent-d1dlwa_", "d1ash__.ent-d1dlwa_.ent", "d1ash__.ent-d1ew6a_", "d1ash__.ent-d1ew6a_.ent", "d1ash__.ent-d1gcva_", "d1ash__.ent-d1gcva_.ent", "d1ash__.ent-d1gtea1", "d1ash__.ent-d1gtea1.ent", "d1ash__.ent-d1gvha1", "d1ash__.ent-d1gvha1.ent", "d1ash__.ent-d1h97a_", "d1ash__.ent-d1h97a_.ent", "d1ash__.ent-d1irda_", "d1ash__.ent-d1irda_.ent", "d1ash__.ent-d1irdb_", "d1ash__.ent-d1irdb_.ent", "d1ash__.ent-d1it2a_", "d1ash__.ent-d1it2a_.ent", "d1ash__.ent-d1itha_", "d1ash__.ent-d1itha_.ent", "d1ash__.ent-d1jl7a_", "d1ash__.ent-d1jl7a_.ent", "d1ash__.ent-d1la6a_", "d1ash__.ent-d1la6a_.ent", "d1ash__.ent-d1mba__", "d1ash__.ent-d1mba__.ent", "d1ash__.ent-d1qlab1", "d1ash__.ent-d1qlab1.ent", "d1ash__.ent-d2gdm__", "d1ash__.ent-d2gdm__.ent", "d1ash__.ent-d3sdha_", "d1ash__.ent-d3sdha_.ent", "d1ass__.ent-d1gmla_.ent", "d1ass__.ent-d1kid__.ent", "d1ast__.ent-d1atla_.ent", "d1ast__.ent-d1bkca_.ent", "d1ast__.ent-d1bqba_.ent", "d1ast__.ent-d1buda_.ent", "d1ast__.ent-d1c7ka_.ent", "d1ast__.ent-d1dmta_.ent", "d1ast__.ent-d1eb6a_.ent", "d1ast__.ent-d1epwa3.ent", "d1ast__.ent-d1ezm__.ent", "d1ast__.ent-d1g12a_.ent", "d1ast__.ent-d1gkda_.ent", "d1ast__.ent-d1gqia2.ent", "d1ast__.ent-d1hs6a3.ent", "d1ast__.ent-d1i1ip_.ent", "d1ast__.ent-d1j7na1.ent", "d1ast__.ent-d1j7na2.ent", "d1ast__.ent-d1jaka2.ent", "d1ast__.ent-d1jk3a_.ent", "d1ast__.ent-d1k7ia2.ent", "d1ast__.ent-d1k9xa_.ent", "d1ast__.ent-d1kapp2.ent", "d1ast__.ent-d1keia_.ent", "d1ast__.ent-d1kufa_.ent", "d1ast__.ent-d1lml__.ent", "d1ast__.ent-d1qba_4.ent", "d1ast__.ent-d3btaa3.ent", "d1at3a_.ent-d1fl1a_.ent", "d1at3a_.ent-d1iega_.ent", "d1at3a_.ent-d1o6ea_.ent", "d1atb__.ent-d1ccva_.ent", "d1atb__.ent-d1coua_.ent", "d1atb__.ent-d1eaic_.ent", "d1atb__.ent-d1hx2a_.ent", "d1atg__.ent-d1dpe__.ent", "d1atg__.ent-d1eu8a_.ent", "d1atg__.ent-d1h76a2.ent", "d1atg__.ent-d1i6aa_.ent", "d1atg__.ent-d1ii5a_.ent", "d1atg__.ent-d1ixh__.ent", "d1atg__.ent-d1jeta_.ent", "d1atg__.ent-d1kwha_.ent", "d1atg__.ent-d1lst__.ent", "d1atg__.ent-d1m5ea_.ent", "d1atg__.ent-d1mrp__.ent", "d1atg__.ent-d1nh8a1.ent", "d1atg__.ent-d1pda_1.ent", "d1atg__.ent-d1pot__.ent", "d1atg__.ent-d1sbp__.ent", "d1atg__.ent-d1wdna_.ent", "d1atg__.ent-d3mbp__.ent", "d1atg__.ent-d3thia_.ent", "d1atia1.ent-d1h4vb1.ent", "d1atia1.ent-d1hc7a1.ent", "d1atia1.ent-d1kmma1.ent", "d1atia1.ent-d1qe0a1.ent", "d1atia1.ent-d1qf6a1.ent", "d1atia2.ent-d1b8aa2.ent", "d1atia2.ent-d1bia_3.ent", "d1atia2.ent-d1e1oa2.ent", "d1atia2.ent-d1eova2.ent", "d1atia2.ent-d1g51a3.ent", "d1atia2.ent-d1h4vb2.ent", "d1atia2.ent-d1hc7a2.ent", "d1atia2.ent-d1jjca_.ent", "d1atia2.ent-d1jjcb5.ent", "d1atia2.ent-d1kmma2.ent", "d1atia2.ent-d1qe0a2.ent", "d1atia2.ent-d1qf6a4.ent", "d1atia2.ent-d1seta2.ent", "d1atla_.ent-d1bkca_.ent", "d1atla_.ent-d1bqba_.ent", "d1atla_.ent-d1buda_.ent", "d1atla_.ent-d1c7ka_.ent", "d1atla_.ent-d1dmta_.ent", "d1atla_.ent-d1eb6a_.ent", "d1atla_.ent-d1epwa3.ent", "d1atla_.ent-d1ezm__.ent", "d1atla_.ent-d1g12a_.ent", "d1atla_.ent-d1gkda_.ent", "d1atla_.ent-d1hs6a3.ent", "d1atla_.ent-d1i1ip_.ent", "d1atla_.ent-d1j7na1.ent", "d1atla_.ent-d1j7na2.ent", "d1atla_.ent-d1jk3a_.ent", "d1atla_.ent-d1k7ia2.ent", "d1atla_.ent-d1k9xa_.ent", "d1atla_.ent-d1kapp2.ent", "d1atla_.ent-d1keia_.ent", "d1atla_.ent-d1kufa_.ent", "d1atla_.ent-d1lml__.ent", "d1atla_.ent-d3btaa3.ent", "d1atx__.ent-d1b8wa_.ent", "d1atx__.ent-d1bnb__.ent", "d1atx__.ent-d1d6ba_.ent", "d1atx__.ent-d1dfna_.ent", "d1atx__.ent-d1e4ta_.ent", "d1atx__.ent-d1ewsa_.ent", "d1atx__.ent-d1fd3a_.ent", "d1atx__.ent-d1ijva_.ent", "d1atx__.ent-d1kj6a_.ent", "d1atx__.ent-d1sh1__.ent", "d1atx__.ent-d2bds__.ent", "d1atza_.ent-d1ijba_.ent", "d1atza_.ent-d1m1xb2.ent", "d1atza_.ent-d1m2oa3.ent", "d1atza_.ent-d1m2vb3.ent", "d1atza_.ent-d1mjna_.ent", "d1atza_.ent-d1n3ya_.ent", "d1atza_.ent-d1qc5a_.ent", "d1au1a_.ent-d1ax8__.ent", "d1au1a_.ent-d1b5l__.ent", "d1au1a_.ent-d1bgc__.ent", "d1au1a_.ent-d1cnt1_.ent", "d1au1a_.ent-d1d9ca_.ent", "d1au1a_.ent-d1eera_.ent", "d1au1a_.ent-d1etea_.ent", "d1au1a_.ent-d1evsa_.ent", "d1au1a_.ent-d1f45b_.ent", "d1au1a_.ent-d1f6fa_.ent", "d1au1a_.ent-d1hula_.ent", "d1au1a_.ent-d1huw__.ent", "d1au1a_.ent-d1hzia_.ent", "d1au1a_.ent-d1i1rb_.ent", "d1au1a_.ent-d1jli__.ent", "d1au1a_.ent-d1lki__.ent", "d1au1a_.ent-d1lqsl_.ent", "d1au1a_.ent-d1m47a_.ent", "d1au1a_.ent-d1n1fa_.ent", "d1au1a_.ent-d2gmfa_.ent", "d1au1a_.ent-d2ilk__.ent", "d1aua_1.ent-d1cuk_1.ent", "d1aua_1.ent-d1efub3.ent", "d1aua_1.ent-d1eija_.ent", "d1aua_1.ent-d1enwa_.ent", "d1aua_1.ent-d1f4ia_.ent", "d1aua_1.ent-d1ifya_.ent", "d1aua_1.ent-d1oaia_.ent", "d1auia_.ent-d1g5ba_.ent", "d1auia_.ent-d1ii7a_.ent", "d1auia_.ent-d1jk7a_.ent", "d1auia_.ent-d1nnwa_.ent", "d1auia_.ent-d1ush_2.ent", "d1auia_.ent-d1utea_.ent", "d1auia_.ent-d4kbpa2.ent", "d1auib_.ent-d1eg3a1.ent", "d1auib_.ent-d1exra_.ent", "d1auib_.ent-d1ggwa_.ent", "d1auib_.ent-d1jfja_.ent", "d1auib_.ent-d1k94a_.ent", "d1auib_.ent-d1m31a_.ent", "d1auib_.ent-d1m45a_.ent", "d1auib_.ent-d1ncx__.ent", "d1auib_.ent-d1rro__.ent", "d1auib_.ent-d1sra__.ent", "d1auib_.ent-d1wdcb_.ent", "d1auib_.ent-d1wdcc_.ent", "d1auib_.ent-d2pvba_.ent", "d1auib_.ent-d5pal__.ent", "d1auua_.ent-d1g31a_.ent", "d1auua_.ent-d1heta1.ent", "d1auua_.ent-d1jh2a_.ent", "d1avaa1.ent-d1bag_1.ent", "d1avaa1.ent-d1bf2_2.ent", "d1avaa1.ent-d1e43a1.ent", "d1avaa1.ent-d1ea9c2.ent", "d1avaa1.ent-d1eh9a2.ent", "d1avaa1.ent-d1g5aa1.ent", "d1avaa1.ent-d1g94a1.ent", "d1avaa1.ent-d1gcya1.ent", "d1avaa1.ent-d1gjwa1.ent", "d1avaa1.ent-d1hx0a1.ent", "d1avaa1.ent-d1iv8a1.ent", "d1avaa1.ent-d1j0ha2.ent", "d1avaa1.ent-d1jae_1.ent", "d1avaa1.ent-d1ji1a2.ent", "d1avaa1.ent-d1ji2a2.ent", "d1avaa1.ent-d1ktba1.ent", "d1avaa1.ent-d1kwga1.ent", "d1avaa1.ent-d1lwha1.ent", "d1avaa1.ent-d1m7xa2.ent", "d1avaa1.ent-d1qhoa3.ent", "d1avaa1.ent-d1uok_1.ent", "d1avaa1.ent-d7taa_1.ent", "d1avac_.ent-d1avwb_.ent", "d1avac_.ent-d1epwa2.ent", "d1avac_.ent-d1eyla_.ent", "d1avac_.ent-d1wba__.ent", "d1avac_.ent-d3btaa2.ent", "d1avc_2.ent-d1axn__.ent", "d1avc_2.ent-d1bo9a_.ent", "d1avc_2.ent-d1dk5a_.ent", "d1avc_2.ent-d1dm5a_.ent", "d1avc_2.ent-d1g5na_.ent", "d1avc_2.ent-d1hm6a_.ent", "d1avgi_.ent-d1b56__.ent", "d1avgi_.ent-d1bbpa_.ent", "d1avgi_.ent-d1beba_.ent", "d1avgi_.ent-d1bj7__.ent", "d1avgi_.ent-d1cbs__.ent", "d1avgi_.ent-d1dzka_.ent", "d1avgi_.ent-d1euoa_.ent", "d1avgi_.ent-d1ew3a_.ent", "d1avgi_.ent-d1exsa_.ent", "d1avgi_.ent-d1ftpa_.ent", "d1avgi_.ent-d1g85a_.ent", "d1avgi_.ent-d1ggla_.ent", "d1avgi_.ent-d1gkab_.ent", "d1avgi_.ent-d1hms__.ent", "d1avgi_.ent-d1i4ua_.ent", "d1avgi_.ent-d1ifc__.ent", "d1avgi_.ent-d1jv4a_.ent", "d1avgi_.ent-d1koia_.ent", "d1avgi_.ent-d1kqwa_.ent", "d1avgi_.ent-d1lf7a_.ent", "d1avgi_.ent-d1o1va_.ent", "d1avgi_.ent-d1qfta_.ent", "d1avgi_.ent-d1qqsa_.ent", "d1avpa_.ent-d1cmxa_.ent", "d1avpa_.ent-d1cv8__.ent", "d1avpa_.ent-d1deua_.ent", "d1avpa_.ent-d1dkia_.ent", "d1avpa_.ent-d1e2ta_.ent", "d1avpa_.ent-d1euva_.ent", "d1avpa_.ent-d1f13a4.ent", "d1avpa_.ent-d1fh0a_.ent", "d1avpa_.ent-d1g0da4.ent", "d1avpa_.ent-d1gmya_.ent", "d1avpa_.ent-d1gx3a_.ent", "d1avpa_.ent-d1iu4a_.ent", "d1avpa_.ent-d1kxra_.ent", "d1avpa_.ent-d1l9na4.ent", "d1avpa_.ent-d1me4a_.ent", "d1avpa_.ent-d1nbfa_.ent", "d1avpa_.ent-d1ppn__.ent", "d1avpa_.ent-d1qmya_.ent", "d1avpa_.ent-d1uch__.ent", "d1avpa_.ent-d2act__.ent", "d1avpa_.ent-d2cb5a_.ent", "d1avpa_.ent-d3gcb__.ent", "d1avpa_.ent-d7pcka_.ent", "d1avqa_.ent-d1bam__.ent", "d1avqa_.ent-d1cfr__.ent", "d1avqa_.ent-d1ckqa_.ent", "d1avqa_.ent-d1d02a_.ent", "d1avqa_.ent-d1dc1a_.ent", "d1avqa_.ent-d1dmua_.ent", "d1avqa_.ent-d1dzfa1.ent", "d1avqa_.ent-d1ev7a_.ent", "d1avqa_.ent-d1f1za2.ent", "d1avqa_.ent-d1fiua_.ent", "d1avqa_.ent-d1gefa_.ent", "d1avqa_.ent-d1hh1a_.ent", "d1avqa_.ent-d1kc6a_.ent", "d1avqa_.ent-d1knva_.ent", "d1avqa_.ent-d1m0da_.ent", "d1avqa_.ent-d1vsra_.ent", "d1avqa_.ent-d2foka4.ent", "d1avqa_.ent-d3pvia_.ent", "d1avwb_.ent-d1bfg__.ent", "d1avwb_.ent-d1dfca1.ent", "d1avwb_.ent-d1dfca2.ent", "d1avwb_.ent-d1dfca3.ent", "d1avwb_.ent-d1dqga_.ent", "d1avwb_.ent-d1epwa2.ent", "d1avwb_.ent-d1eyla_.ent", "d1avwb_.ent-d1hcd__.ent", "d1avwb_.ent-d1jlxa1.ent", "d1avwb_.ent-d1knma_.ent", "d1avwb_.ent-d1l2ha_.ent", "d1avwb_.ent-d1n4ka2.ent", "d1avwb_.ent-d1wba__.ent", "d1avwb_.ent-d3btaa2.ent", "d1aw0__.ent-d1cc8a_.ent", "d1aw0__.ent-d1cpza_.ent", "d1aw0__.ent-d1fe0a_.ent", "d1aw0__.ent-d1fvqa_.ent", "d1aw0__.ent-d1jwwa_.ent", "d1aw0__.ent-d1k0va_.ent", "d1aw0__.ent-d1mwza_.ent", "d1aw9_1.ent-d1axda1.ent", "d1aw9_1.ent-d1duga1.ent", "d1aw9_1.ent-d1e6ba1.ent", "d1aw9_1.ent-d1eema1.ent", "d1aw9_1.ent-d1f2ea1.ent", "d1aw9_1.ent-d1fw1a1.ent", "d1aw9_1.ent-d1g7oa1.ent", "d1aw9_1.ent-d1glqa1.ent", "d1aw9_1.ent-d1gnwa1.ent", "d1aw9_1.ent-d1gula1.ent", "d1aw9_1.ent-d1gwca1.ent", "d1aw9_1.ent-d1jlva1.ent", "d1aw9_1.ent-d1k0da1.ent", "d1aw9_1.ent-d1k0ma1.ent", "d1aw9_1.ent-d1k3ya1.ent", "d1aw9_1.ent-d1ljra1.ent", "d1aw9_1.ent-d1m0ua1.ent", "d1aw9_1.ent-d1pd211.ent", "d1aw9_1.ent-d1pmt_1.ent", "d1aw9_1.ent-d2gsq_1.ent", "d1aw9_1.ent-d2gsta1.ent", "d1awcb_.ent-d1bd8__.ent", "d1awcb_.ent-d1bi7b_.ent", "d1awcb_.ent-d1dcqa1.ent", "d1awcb_.ent-d1ihba_.ent", "d1awcb_.ent-d1k1aa_.ent", "d1awcb_.ent-d1k3zd_.ent", "d1awcb_.ent-d1myo__.ent", "d1awcb_.ent-d1n11a_.ent", "d1awcb_.ent-d1sw6a_.ent", "d1awcb_.ent-d1ycsb1.ent", "d1awj__.ent-d1bb9__.ent", "d1awj__.ent-d1bbza_.ent", "d1awj__.ent-d1fmk_1.ent", "d1awj__.ent-d1gcqa_.ent", "d1awj__.ent-d1gcqc_.ent", "d1awj__.ent-d1gl5a_.ent", "d1awj__.ent-d1gria1.ent", "d1awj__.ent-d1h92a_.ent", "d1awj__.ent-d1i07a_.ent", "d1awj__.ent-d1i1ja_.ent", "d1awj__.ent-d1jo8a_.ent", "d1awj__.ent-d1jqqa_.ent", "d1awj__.ent-d1k4us_.ent", "d1awj__.ent-d1kjwa1.ent", "d1awj__.ent-d1neb__.ent", "d1awj__.ent-d1pht__.ent", "d1awj__.ent-d1pwt__.ent", "d1awj__.ent-d1qcfa1.ent", "d1awj__.ent-d1ycsb2.ent", "d1awj__.ent-d2hsp__.ent", "d1ax8__.ent-d1b5l__.ent", "d1ax8__.ent-d1bgc__.ent", "d1ax8__.ent-d1cnt1_.ent", "d1ax8__.ent-d1d9ca_.ent", "d1ax8__.ent-d1eera_.ent", "d1ax8__.ent-d1etea_.ent", "d1ax8__.ent-d1evsa_.ent", "d1ax8__.ent-d1f45b_.ent", "d1ax8__.ent-d1f6fa_.ent", "d1ax8__.ent-d1hula_.ent", "d1ax8__.ent-d1huw__.ent", "d1ax8__.ent-d1hzia_.ent", "d1ax8__.ent-d1i1rb_.ent", "d1ax8__.ent-d1jli__.ent", "d1ax8__.ent-d1lki__.ent", "d1ax8__.ent-d1lqsl_.ent", "d1ax8__.ent-d1m47a_.ent", "d1ax8__.ent-d1n1fa_.ent", "d1ax8__.ent-d2gmfa_.ent", "d1ax8__.ent-d2ilk__.ent", "d1axca1.ent-d1axca2.ent", "d1axca1.ent-d1b77a1.ent", "d1axca1.ent-d1b77a2.ent", "d1axca1.ent-d1dmla1.ent", "d1axca1.ent-d1dmla2.ent", "d1axca1.ent-d1ge8a1.ent", "d1axca1.ent-d1ge8a2.ent", "d1axca1.ent-d1plq_1.ent", "d1axca1.ent-d1plq_2.ent", "d1axca1.ent-d2pola1.ent", "d1axca1.ent-d2pola2.ent", "d1axca1.ent-d2pola3.ent", "d1axca2.ent-d1b77a1.ent", "d1axca2.ent-d1b77a2.ent", "d1axca2.ent-d1dmla1.ent", "d1axca2.ent-d1dmla2.ent", "d1axca2.ent-d1ge8a1.ent", "d1axca2.ent-d1ge8a2.ent", "d1axca2.ent-d1plq_1.ent", "d1axca2.ent-d1plq_2.ent", "d1axca2.ent-d2pola1.ent", "d1axca2.ent-d2pola2.ent", "d1axca2.ent-d2pola3.ent", "d1axda1.ent-d1duga1.ent", "d1axda1.ent-d1e6ba1.ent", "d1axda1.ent-d1eema1.ent", "d1axda1.ent-d1f2ea1.ent", "d1axda1.ent-d1fw1a1.ent", "d1axda1.ent-d1g7oa1.ent", "d1axda1.ent-d1glqa1.ent", "d1axda1.ent-d1gnwa1.ent", "d1axda1.ent-d1gula1.ent", "d1axda1.ent-d1gwca1.ent", "d1axda1.ent-d1jlva1.ent", "d1axda1.ent-d1k0da1.ent", "d1axda1.ent-d1k0ma1.ent", "d1axda1.ent-d1k3ya1.ent", "d1axda1.ent-d1ljra1.ent", "d1axda1.ent-d1m0ua1.ent", "d1axda1.ent-d1pd211.ent", "d1axda1.ent-d1pmt_1.ent", "d1axda1.ent-d2gsq_1.ent", "d1axda1.ent-d2gsta1.ent", "d1axh__.ent-d1c6wa_.ent", "d1axh__.ent-d1cixa_.ent", "d1axh__.ent-d1d1ha_.ent", "d1axh__.ent-d1dl0a_.ent", "d1axh__.ent-d1eit__.ent", "d1axh__.ent-d1emxa_.ent", "d1axh__.ent-d1g9pa_.ent", "d1axh__.ent-d1i25a_.ent", "d1axh__.ent-d1i26a_.ent", "d1axh__.ent-d1koza_.ent", "d1axh__.ent-d1kqha_.ent", "d1axh__.ent-d1lqra_.ent", "d1axh__.ent-d1lupa_.ent", "d1axh__.ent-d1nixa_.ent", "d1axh__.ent-d1niya_.ent", "d1axh__.ent-d1qk6a_.ent", "d1axh__.ent-d1qk7a_.ent", "d1axh__.ent-d1vtx__.ent", "d1axib2.ent-d1bpv__.ent", "d1axib2.ent-d1cd9b2.ent", "d1axib2.ent-d1cfb_1.ent", "d1axib2.ent-d1cfb_2.ent", "d1axib2.ent-d1eerb2.ent", "d1axib2.ent-d1egja_.ent", "d1axib2.ent-d1f6fb1.ent", "d1axib2.ent-d1f6fb2.ent", "d1axib2.ent-d1fyhb1.ent", "d1axib2.ent-d1fyhb2.ent", "d1axib2.ent-d1gh7a1.ent", "d1axib2.ent-d1i1ra1.ent", "d1axib2.ent-d1lqsr1.ent", "d1axib2.ent-d1n26a2.ent", "d1axib2.ent-d1n26a3.ent", "d1axib2.ent-d1qg3a2.ent", "d1axib2.ent-d2hft_1.ent", "d1axib2.ent-d2hft_2.ent", "d1axn__.ent-d1bo9a_.ent", "d1axn__.ent-d1dk5a_.ent", "d1axn__.ent-d1dm5a_.ent", "d1axn__.ent-d1g5na_.ent", "d1axn__.ent-d1hm6a_.ent", "d1ayaa_.ent-d1d4ta_.ent", "d1ayaa_.ent-d1fu6a_.ent", "d1ayaa_.ent-d1ju5a_.ent", "d1ayaa_.ent-d1jwoa_.ent", "d1ayaa_.ent-d1jyra_.ent", "d1ayaa_.ent-d1lkka_.ent", "d1ayaa_.ent-d1luia_.ent", "d1ayaa_.ent-d1mil__.ent", "d1ayaa_.ent-d1qada_.ent", "d1ayaa_.ent-d2abl_2.ent", "d1ayaa_.ent-d2cbla3.ent", "d1ayaa_.ent-d2plda_.ent", "d1ayaa_.ent-d2shpa3.ent", "d1aye_2.ent-d1itpa_.ent", "d1aye_2.ent-d1jqga2.ent", "d1aye_2.ent-d1kn6a_.ent", "d1aye_2.ent-d1kwma2.ent", "d1aye_2.ent-d1scjb_.ent", "d1ayfa_.ent-d1b9ra_.ent", "d1ayfa_.ent-d1bmlc3.ent", "d1ayfa_.ent-d1c9fa_.ent", "d1ayfa_.ent-d1czpa_.ent", "d1ayfa_.ent-d1doi__.ent", "d1ayfa_.ent-d1e9ma_.ent", "d1ayfa_.ent-d1f52a1.ent", "d1ayfa_.ent-d1feha2.ent", "d1ayfa_.ent-d1fm0d_.ent", "d1ayfa_.ent-d1fo4a2.ent", "d1ayfa_.ent-d1h4ra3.ent", "d1ayfa_.ent-d1h8ca_.ent", "d1ayfa_.ent-d1hlra2.ent", "d1ayfa_.ent-d1i42a_.ent", "d1ayfa_.ent-d1i7ha_.ent", "d1ayfa_.ent-d1ip9a_.ent", "d1ayfa_.ent-d1jq4a_.ent", "d1ayfa_.ent-d1jroa2.ent", "d1ayfa_.ent-d1k8rb_.ent", "d1ayfa_.ent-d1kf6b2.ent", "d1ayfa_.ent-d1krha3.ent", "d1ayfa_.ent-d1l5pa_.ent", "d1ayfa_.ent-d1l7ya_.ent", "d1ayfa_.ent-d1lfda_.ent", "d1ayfa_.ent-d1n62a2.ent", "d1ayfa_.ent-d1nekb2.ent", "d1ayfa_.ent-d1put__.ent", "d1ayfa_.ent-d1qlab2.ent", "d1ayfa_.ent-d2pia_3.ent", "d1ayfa_.ent-d3tss_2.ent", "d1ayg__.ent-d1c52__.ent", "d1ayg__.ent-d1c75a_.ent", "d1ayg__.ent-d1cc5__.ent", "d1ayg__.ent-d1cnoa_.ent", "d1ayg__.ent-d1ctj__.ent", "d1ayg__.ent-d1diqc_.ent", "d1ayg__.ent-d1e29a_.ent", "d1ayg__.ent-d1ezvd1.ent", "d1ayg__.ent-d1fcdc2.ent", "d1ayg__.ent-d1gu2a_.ent", "d1ayg__.ent-d1h32a1.ent", "d1ayg__.ent-d1iqca1.ent", "d1ayg__.ent-d1iqca2.ent", "d1ayg__.ent-d1jmxa1.ent", "d1ayg__.ent-d1jmxa2.ent", "d1ayg__.ent-d1kb0a1.ent", "d1ayg__.ent-d1mg2d_.ent", "d1ayg__.ent-d1qksa1.ent", "d1ayl_1.ent-d1ii2a1.ent", "d1ayl_1.ent-d1khba1.ent", "d1ayl_1.ent-d1knxa2.ent", "d1ayl_1.ent-d1ko7a2.ent", "d1ayl_2.ent-d1ii2a2.ent", "d1ayl_2.ent-d1j3ba2.ent", "d1ayl_2.ent-d1khba2.ent", "d1aym1_.ent-d1aym2_.ent", "d1aym1_.ent-d1b35a_.ent", "d1aym1_.ent-d1b35b_.ent", "d1aym1_.ent-d1b35c_.ent", "d1aym1_.ent-d1bev1_.ent", "d1aym1_.ent-d1bev3_.ent", "d1aym1_.ent-d1d4m1_.ent", "d1aym1_.ent-d1k5ma_.ent", "d1aym1_.ent-d1pvc1_.ent", "d1aym1_.ent-d1tmf1_.ent", "d1aym1_.ent-d1vpsa_.ent", "d1aym1_.ent-d2mev1_.ent", "d1aym1_.ent-d2mev2_.ent", "d1aym2_.ent-d1bev3_.ent", "d1aym2_.ent-d2mev2_.ent", "d1ayoa_.ent-d1bg1a2.ent", "d1ayoa_.ent-d1e2wa1.ent", "d1ayoa_.ent-d1e5ba_.ent", "d1ayoa_.ent-d1f0la1.ent", "d1ayoa_.ent-d1h6fa_.ent", "d1ayoa_.ent-d1i31a_.ent", "d1ayoa_.ent-d1klfb1.ent", "d1ayoa_.ent-d1klfb2.ent", "d1ayoa_.ent-d1m2oa2.ent", "d1ayoa_.ent-d1m2vb2.ent", "d1ayoa_.ent-d1mnna_.ent", "d1ayoa_.ent-d1nbca_.ent", "d1ayoa_.ent-d1pdkb_.ent", "d1ayoa_.ent-d1qba_2.ent", "d1ayoa_.ent-d1tf4a2.ent", "d1ayoa_.ent-d1ycsa_.ent", "d1ayx__.ent-d1clc_1.ent", "d1ayx__.ent-d1faea_.ent", "d1ayx__.ent-d1fp3a_.ent", "d1ayx__.ent-d1gai__.ent", "d1ayx__.ent-d1h54a1.ent", "d1ayx__.ent-d1ia6a_.ent", "d1ayx__.ent-d1ks8a_.ent", "d1ayx__.ent-d1kwfa_.ent", "d1ayx__.ent-d1lf6a1.ent", "d1az9_1.ent-d1j54a_.ent", "d1az9_1.ent-d1mwma2.ent", "d1az9_1.ent-d1xwl_1.ent", "d1az9_2.ent-d1b6a_2.ent", "d1az9_2.ent-d1c22a_.ent", "d1az9_2.ent-d1chma2.ent", "d1az9_2.ent-d1o0xa_.ent", "d1az9_2.ent-d1xgsa2.ent", "d1azsa_.ent-d1azsb_.ent", "d1azsa_.ent-d1b3ta_.ent", "d1azsa_.ent-d1dj0a2.ent", "d1azsa_.ent-d1dqaa1.ent", "d1azsa_.ent-d1ekra_.ent", "d1azsa_.ent-d1eqoa_.ent", "d1azsa_.ent-d1f3va_.ent", "d1azsa_.ent-d1ftra1.ent", "d1azsa_.ent-d1ftra2.ent", "d1azsa_.ent-d1fx2a_.ent", "d1azsa_.ent-d1gpja3.ent", "d1azsa_.ent-d1h72c2.ent", "d1azsa_.ent-d1hbnb2.ent", "d1azsa_.ent-d1hlwa_.ent", "d1azsa_.ent-d1jnrb_.ent", "d1azsa_.ent-d1kvka2.ent", "d1azsa_.ent-d1qd1a1.ent", "d1azsa_.ent-d1qd1a2.ent", "d1azsa_.ent-d1regx_.ent", "d1azsb_.ent-d1fx2a_.ent", "d1azwa_.ent-d1bu8a2.ent", "d1azwa_.ent-d1dqza_.ent", "d1azwa_.ent-d1ei9a_.ent", "d1azwa_.ent-d1ex9a_.ent", "d1azwa_.ent-d1fj2a_.ent", "d1azwa_.ent-d1gkla_.ent", "d1azwa_.ent-d1hlga_.ent", "d1azwa_.ent-d1imja_.ent", "d1azwa_.ent-d1ispa_.ent", "d1azwa_.ent-d1jfra_.ent", "d1azwa_.ent-d1ju3a2.ent", "d1azwa_.ent-d1ku0a_.ent", "d1azwa_.ent-d1l7aa_.ent", "d1azwa_.ent-d1lzla_.ent", "d1azwa_.ent-d1mnaa_.ent", "d1azwa_.ent-d1n1ma2.ent", "d1azwa_.ent-d1qj4a_.ent", "d1azwa_.ent-d1qlwa_.ent", "d1azwa_.ent-d1qo7a_.ent", "d1azwa_.ent-d1tca__.ent", "d1azwa_.ent-d1thta_.ent", "d1azwa_.ent-d3tgl__.ent", "d1azza_.ent-d1cgha_.ent", "d1azza_.ent-d1gdna_.ent", "d1azza_.ent-d1hj9a_.ent", "d1b00a_.ent-d1c4ka1.ent", "d1b00a_.ent-d1dbwa_.ent", "d1b00a_.ent-d1dcfa_.ent", "d1b00a_.ent-d1dz3a_.ent", "d1b00a_.ent-d1m2fa_.ent", "d1b00a_.ent-d1mb3a_.ent", "d1b00a_.ent-d1mvoa_.ent", "d1b00a_.ent-d1nat__.ent", "d1b00a_.ent-d1ntr__.ent", "d1b00a_.ent-d1qo0d_.ent", "d1b00a_.ent-d1tmy__.ent", "d1b04a_.ent-d1ckma2.ent", "d1b04a_.ent-d1dgsa3.ent", "d1b04a_.ent-d1eucb2.ent", "d1b04a_.ent-d1fvia2.ent", "d1b04a_.ent-d1gsa_2.ent", "d1b04a_.ent-d1gsoa3.ent", "d1b04a_.ent-d1iow_2.ent", "d1b04a_.ent-d1kbla3.ent", "d1b04a_.ent-d1kjqa3.ent", "d1b04a_.ent-d1m0wa2.ent", "d1b06a1.ent-d1bsma1.ent", "d1b06a1.ent-d1coja1.ent", "d1b06a1.ent-d1gv3a1.ent", "d1b06a1.ent-d1isaa1.ent", "d1b06a1.ent-d1ix9a1.ent", "d1b06a2.ent-d1bsma2.ent", "d1b06a2.ent-d1coja2.ent", "d1b06a2.ent-d1gv3a2.ent", "d1b06a2.ent-d1isaa2.ent", "d1b06a2.ent-d1ix9a2.ent", "d1b06a2.ent-d1kkca2.ent", "d1b06a2.ent-d1ma1a2.ent", "d1b06a2.ent-d1qnna2.ent", "d1b08a1.ent-d1b6e__.ent", "d1b08a1.ent-d1cwva5.ent", "d1b08a1.ent-d1e87a_.ent", "d1b08a1.ent-d1f00i3.ent", "d1b08a1.ent-d1fvub_.ent", "d1b08a1.ent-d1g1ta1.ent", "d1b08a1.ent-d1h8ua_.ent", "d1b08a1.ent-d1li1a1.ent", "d1b08a1.ent-d1li1a2.ent", "d1b08a1.ent-d1prtb2.ent", "d1b08a1.ent-d1tsg__.ent", "d1b0aa2.ent-d1bgva2.ent", "d1b0aa2.ent-d1c1da2.ent", "d1b0aa2.ent-d1edza2.ent", "d1b0aa2.ent-d1gtma2.ent", "d1b0aa2.ent-d1hwxa2.ent", "d1b0aa2.ent-d1leha2.ent", "d1b0aa2.ent-d1lu9a2.ent", "d1b0na2.ent-d1d1la_.ent", "d1b0na2.ent-d1e3oc2.ent", "d1b0na2.ent-d1efaa1.ent", "d1b0na2.ent-d1ic8a2.ent", "d1b0na2.ent-d1lmb3_.ent", "d1b0na2.ent-d1ner__.ent", "d1b0na2.ent-d1r69__.ent", "d1b0na2.ent-d1uxc__.ent", "d1b0na2.ent-d1uxd__.ent", "d1b0na2.ent-d1vpwa1.ent", "d1b0na2.ent-d2cro__.ent", "d1b0xa_.ent-d1b4fa_.ent", "d1b0xa_.ent-d1bqv__.ent", "d1b0xa_.ent-d1dxsa_.ent", "d1b12a_.ent-d1f39a_.ent", "d1b12a_.ent-d1jhfa2.ent", "d1b2pa_.ent-d1jpc__.ent", "d1b2pa_.ent-d1kj1d_.ent", "d1b34a_.ent-d1b34b_.ent", "d1b34a_.ent-d1d3ba_.ent", "d1b34a_.ent-d1d3bb_.ent", "d1b34a_.ent-d1h641_.ent", "d1b34a_.ent-d1i8fa_.ent", "d1b34a_.ent-d1kq1a_.ent", "d1b34a_.ent-d1ljoa_.ent", "d1b34a_.ent-d1mgqa_.ent", "d1b34a_.ent-d1mxma1.ent", "d1b34a_.ent-d1n9ra_.ent", "d1b34b_.ent-d1d3ba_.ent", "d1b34b_.ent-d1d3bb_.ent", "d1b34b_.ent-d1h641_.ent", "d1b34b_.ent-d1i8fa_.ent", "d1b34b_.ent-d1kq1a_.ent", "d1b34b_.ent-d1ljoa_.ent", "d1b34b_.ent-d1mgqa_.ent", "d1b34b_.ent-d1mxma1.ent", "d1b34b_.ent-d1n9ra_.ent", "d1b35a_.ent-d1a6ca1.ent", "d1b35a_.ent-d1a6ca2.ent", "d1b35a_.ent-d1a6ca3.ent", "d1b35a_.ent-d1aym2_.ent", "d1b35a_.ent-d1b35b_.ent", "d1b35a_.ent-d1bev3_.ent", "d1b35a_.ent-d1bmv1_.ent", "d1b35a_.ent-d1c8na_.ent", "d1b35a_.ent-d1cwpa_.ent", "d1b35a_.ent-d1ddla_.ent", "d1b35a_.ent-d1f15a_.ent", "d1b35a_.ent-d1qqp1_.ent", "d1b35a_.ent-d1qqp2_.ent", "d1b35a_.ent-d1qqp3_.ent", "d1b35a_.ent-d2bpa2_.ent", "d1b35a_.ent-d2mev2_.ent", "d1b35a_.ent-d2stv__.ent", "d1b35b_.ent-d1a6ca1.ent", "d1b35b_.ent-d1a6ca2.ent", "d1b35b_.ent-d1a6ca3.ent", "d1b35b_.ent-d1aym2_.ent", "d1b35b_.ent-d1bev3_.ent", "d1b35b_.ent-d1bmv1_.ent", "d1b35b_.ent-d1c8na_.ent", "d1b35b_.ent-d1cwpa_.ent", "d1b35b_.ent-d1ddla_.ent", "d1b35b_.ent-d1f15a_.ent", "d1b35b_.ent-d1qqp1_.ent", "d1b35b_.ent-d1qqp2_.ent", "d1b35b_.ent-d1qqp3_.ent", "d1b35b_.ent-d2bpa2_.ent", "d1b35b_.ent-d2mev2_.ent", "d1b35b_.ent-d2stv__.ent", "d1b35c_.ent-d1a6ca1.ent", "d1b35c_.ent-d1a6ca2.ent", "d1b35c_.ent-d1a6ca3.ent", "d1b35c_.ent-d1aym2_.ent", "d1b35c_.ent-d1b35a_.ent", "d1b35c_.ent-d1b35b_.ent", "d1b35c_.ent-d1bev1_.ent", "d1b35c_.ent-d1bev3_.ent", "d1b35c_.ent-d1bmv1_.ent", "d1b35c_.ent-d1c8na_.ent", "d1b35c_.ent-d1cwpa_.ent", "d1b35c_.ent-d1ddla_.ent", "d1b35c_.ent-d1f15a_.ent", "d1b35c_.ent-d1pvc1_.ent", "d1b35c_.ent-d1qqp1_.ent", "d1b35c_.ent-d1qqp2_.ent", "d1b35c_.ent-d1qqp3_.ent", "d1b35c_.ent-d1tmf1_.ent", "d1b35c_.ent-d2bpa2_.ent", "d1b35c_.ent-d2mev1_.ent", "d1b35c_.ent-d2mev2_.ent", "d1b35c_.ent-d2stv__.ent", "d1b3aa_.ent-d1bf4a_.ent", "d1b3aa_.ent-d1doka_.ent", "d1b3aa_.ent-d1dz1a_.ent", "d1b3aa_.ent-d1e0ba_.ent", "d1b3aa_.ent-d1eiha_.ent", "d1b3aa_.ent-d1el0a_.ent", "d1b3aa_.ent-d1f2la_.ent", "d1b3aa_.ent-d1g2ta_.ent", "d1b3aa_.ent-d1j9oa_.ent", "d1b3aa_.ent-d1knaa_.ent", "d1b3aa_.ent-d1m8aa_.ent", "d1b3aa_.ent-d1qg7a_.ent", "d1b3aa_.ent-d1tvxa_.ent", "d1b3aa_.ent-d2hcc__.ent", "d1b3aa_.ent-d3il8__.ent", "d1b3qa1.ent-d1joya_.ent", "d1b3qa1.ent-d1nkd__.ent", "d1b3qa2.ent-d1fgua2.ent", "d1b3qa2.ent-d1fjgl_.ent", "d1b3qa2.ent-d1jb3a_.ent", "d1b3qa2.ent-d1jb7a2.ent", "d1b3qa2.ent-d1k28a1.ent", "d1b3qa2.ent-d1quqa_.ent", "d1b3qa2.ent-d3seb_1.ent", "d1b3ra2.ent-d1cex__.ent", "d1b3ra2.ent-d1cf9a1.ent", "d1b3ra2.ent-d1dxy_2.ent", "d1b3ra2.ent-d1e5da1.ent", "d1b3ra2.ent-d1es9a_.ent", "d1b3ra2.ent-d1euca2.ent", "d1b3ra2.ent-d1f2va_.ent", "d1b3ra2.ent-d1f4pa_.ent", "d1b3ra2.ent-d1f8ya_.ent", "d1b3ra2.ent-d1fjgb_.ent", "d1b3ra2.ent-d1fuea_.ent", "d1b3ra2.ent-d1fyea_.ent", "d1b3ra2.ent-d1g66a_.ent", "d1b3ra2.ent-d1gdha2.ent", "d1b3ra2.ent-d1h05a_.ent", "d1b3ra2.ent-d1iexa2.ent", "d1b3ra2.ent-d1j4aa2.ent", "d1b3ra2.ent-d1k7ca_.ent", "d1b3ra2.ent-d1kwga3.ent", "d1b3ra2.ent-d1l7da2.ent", "d1b3ra2.ent-d1mx3a2.ent", "d1b3ra2.ent-d1pjca2.ent", "d1b3ra2.ent-d1psda2.ent", "d1b3ra2.ent-d1qo0d_.ent", "d1b3ra2.ent-d2naca2.ent", "d1b3ra2.ent-d7reqb2.ent", "d1b3ta_.ent-d1by9__.ent", "d1b3ta_.ent-d1dqaa1.ent", "d1b3ta_.ent-d1ekra_.ent", "d1b3ta_.ent-d1gpja3.ent", "d1b3ta_.ent-d1h72c2.ent", "d1b3ta_.ent-d1qd1a2.ent", "d1b3ta_.ent-d1regx_.ent", "d1b3ta_.ent-d2bopa_.ent", "d1b3ua_.ent-d1bpoa1.ent", "d1b3ua_.ent-d1e8xa1.ent", "d1b3ua_.ent-d1ee4a_.ent", "d1b3ua_.ent-d1elka_.ent", "d1b3ua_.ent-d1h6ka1.ent", "d1b3ua_.ent-d1h6ka2.ent", "d1b3ua_.ent-d1h6ka3.ent", "d1b3ua_.ent-d1hf8a_.ent", "d1b3ua_.ent-d1hh8a_.ent", "d1b3ua_.ent-d1ho8a_.ent", "d1b3ua_.ent-d1hs6a1.ent", "d1b3ua_.ent-d1hz4a_.ent", "d1b3ua_.ent-d1iala_.ent", "d1b3ua_.ent-d1ihga1.ent", "d1b3ua_.ent-d1jdha_.ent", "d1b3ua_.ent-d1keya_.ent", "d1b3ua_.ent-d1kpsb_.ent", "d1b3ua_.ent-d1kx9a_.ent", "d1b3ua_.ent-d1l5ja1.ent", "d1b3ua_.ent-d1ld8a_.ent", "d1b3ua_.ent-d1ldja2.ent", "d1b3ua_.ent-d1lrv__.ent", "d1b3ua_.ent-d1lsha1.ent", "d1b3ua_.ent-d1n4ka1.ent", "d1b3ua_.ent-d1pbv__.ent", "d1b3ua_.ent-d1qjba_.ent", "d1b3ua_.ent-d1qqea_.ent", "d1b3ua_.ent-d1qsaa1.ent", "d1b43a1.ent-d1bgxt1.ent", "d1b43a1.ent-d1tfr_1.ent", "d1b43a1.ent-d1xo1a1.ent", "d1b4fa_.ent-d1bgxt1.ent", "d1b4fa_.ent-d1bpya1.ent", "d1b4fa_.ent-d1bqv__.ent", "d1b4fa_.ent-d1cuk_2.ent", "d1b4fa_.ent-d1d8ba_.ent", "d1b4fa_.ent-d1dgsa1.ent", "d1b4fa_.ent-d1doqa_.ent", "d1b4fa_.ent-d1dxsa_.ent", "d1b4fa_.ent-d1f44a1.ent", "d1b4fa_.ent-d1floa1.ent", "d1b4fa_.ent-d1go3f_.ent", "d1b4fa_.ent-d1jmsa1.ent", "d1b4fa_.ent-d1jmsa3.ent", "d1b4fa_.ent-d1jyga_.ent", "d1b4fa_.ent-d1kfta_.ent", "d1b4fa_.ent-d1lb2b_.ent", "d1b4fa_.ent-d1tfr_1.ent", "d1b56__.ent-d1bbpa_.ent", "d1b56__.ent-d1beba_.ent", "d1b56__.ent-d1bj7__.ent", "d1b56__.ent-d1cbs__.ent", "d1b56__.ent-d1dzka_.ent", "d1b56__.ent-d1euoa_.ent", "d1b56__.ent-d1ew3a_.ent", "d1b56__.ent-d1ftpa_.ent", "d1b56__.ent-d1g85a_.ent", "d1b56__.ent-d1ggla_.ent", "d1b56__.ent-d1gkab_.ent", "d1b56__.ent-d1hms__.ent", "d1b56__.ent-d1i4ua_.ent", "d1b56__.ent-d1ifc__.ent", "d1b56__.ent-d1jv4a_.ent", "d1b56__.ent-d1koia_.ent", "d1b56__.ent-d1kqwa_.ent", "d1b56__.ent-d1lf7a_.ent", "d1b56__.ent-d1o1va_.ent", "d1b56__.ent-d1qfta_.ent", "d1b56__.ent-d1qqsa_.ent", "d1b5ea_.ent-d1bkpa_.ent", "d1b5ea_.ent-d1f28a_.ent", "d1b5ea_.ent-d1tis__.ent", "d1b5l__.ent-d1bgc__.ent", "d1b5l__.ent-d1cnt1_.ent", "d1b5l__.ent-d1d9ca_.ent", "d1b5l__.ent-d1eera_.ent", "d1b5l__.ent-d1etea_.ent", "d1b5l__.ent-d1evsa_.ent", "d1b5l__.ent-d1f45b_.ent", "d1b5l__.ent-d1f6fa_.ent", "d1b5l__.ent-d1hula_.ent", "d1b5l__.ent-d1huw__.ent", "d1b5l__.ent-d1hzia_.ent", "d1b5l__.ent-d1i1rb_.ent", "d1b5l__.ent-d1jli__.ent", "d1b5l__.ent-d1lki__.ent", "d1b5l__.ent-d1lqsl_.ent", "d1b5l__.ent-d1m47a_.ent", "d1b5l__.ent-d1n1fa_.ent", "d1b5l__.ent-d2gmfa_.ent", "d1b5l__.ent-d2ilk__.ent", "d1b5qa1.ent-d1chua2.ent", "d1b5qa1.ent-d1cjca1.ent", "d1b5qa1.ent-d1d5ta1.ent", "d1b5qa1.ent-d1ebda1.ent", "d1b5qa1.ent-d1fcda1.ent", "d1b5qa1.ent-d1fcda2.ent", "d1b5qa1.ent-d1feca1.ent", "d1b5qa1.ent-d1fl2a2.ent", "d1b5qa1.ent-d1gtea3.ent", "d1b5qa1.ent-d1h6va1.ent", "d1b5qa1.ent-d1jeha1.ent", "d1b5qa1.ent-d1jnra2.ent", "d1b5qa1.ent-d1ju2a1.ent", "d1b5qa1.ent-d1k0ia1.ent", "d1b5qa1.ent-d1kf6a2.ent", "d1b5qa1.ent-d1kssa2.ent", "d1b5qa1.ent-d1l9ea1.ent", "d1b5qa1.ent-d1lqta1.ent", "d1b5qa1.ent-d1m6ia1.ent", "d1b5qa1.ent-d1m6ia2.ent", "d1b5qa1.ent-d1mo9a1.ent", "d1b5qa1.ent-d1neka2.ent", "d1b5qa1.ent-d1nhp_1.ent", "d1b5qa1.ent-d1nhp_2.ent", "d1b5qa1.ent-d1o94a2.ent", "d1b5qa1.ent-d1ojt_1.ent", "d1b5qa1.ent-d1qlaa2.ent", "d1b5qa1.ent-d1qo8a2.ent", "d1b5qa1.ent-d3grs_1.ent", "d1b5qa1.ent-d3grs_2.ent", "d1b5qa1.ent-d3lada1.ent", "d1b5qa2.ent-d1c0pa2.ent", "d1b5qa2.ent-d1d5ta2.ent", "d1b5qa2.ent-d1f8ra2.ent", "d1b5qa2.ent-d1foha4.ent", "d1b5qa2.ent-d1gosa2.ent", "d1b5qa2.ent-d1gpea2.ent", "d1b5qa2.ent-d1i8ta2.ent", "d1b5qa2.ent-d1ju2a2.ent", "d1b5qa2.ent-d1k0ia2.ent", "d1b5qa2.ent-d1kdga2.ent", "d1b5qa2.ent-d1l9ea2.ent", "d1b5qa2.ent-d1mxta2.ent", "d1b5sa_.ent-d1e2o__.ent", "d1b5sa_.ent-d1eaf__.ent", "d1b5sa_.ent-d1l5aa1.ent", "d1b5sa_.ent-d1l5aa2.ent", "d1b5sa_.ent-d1nocb_.ent", "d1b5sa_.ent-d3cla__.ent", "d1b63a1.ent-d1d6ta_.ent", "d1b63a1.ent-d1dar_3.ent", "d1b63a1.ent-d1ei1a1.ent", "d1b63a1.ent-d1fjgi_.ent", "d1b63a1.ent-d1h72c1.ent", "d1b63a1.ent-d1kija1.ent", "d1b63a1.ent-d1kkha1.ent", "d1b63a1.ent-d1kvka1.ent", "d1b63a1.ent-d1mu5a2.ent", "d1b63a1.ent-d1n0ua3.ent", "d1b63a1.ent-d1pkp_1.ent", "d1b63a2.ent-d1bxda_.ent", "d1b63a2.ent-d1byqa_.ent", "d1b63a2.ent-d1ei1a2.ent", "d1b63a2.ent-d1gkza2.ent", "d1b63a2.ent-d1i58a_.ent", "d1b63a2.ent-d1id0a_.ent", "d1b63a2.ent-d1jm6a2.ent", "d1b63a2.ent-d1kija2.ent", "d1b63a2.ent-d1l0oa_.ent", "d1b63a2.ent-d1mu5a3.ent", "d1b66a_.ent-d1b9la_.ent", "d1b66a_.ent-d1dhn__.ent", "d1b66a_.ent-d1is8a_.ent", "d1b66a_.ent-d1uox_1.ent", "d1b66a_.ent-d1uox_2.ent", "d1b67a_.ent-d1bh9a_.ent", "d1b67a_.ent-d1bh9b_.ent", "d1b67a_.ent-d1jfia_.ent", "d1b67a_.ent-d1jfib_.ent", "d1b67a_.ent-d1kx5a_.ent", "d1b67a_.ent-d1kx5b_.ent", "d1b67a_.ent-d1kx5c_.ent", "d1b67a_.ent-d1kx5d_.ent", "d1b67a_.ent-d1n1ja_.ent", "d1b67a_.ent-d1n1jb_.ent", "d1b6a_2.ent-d1c22a_.ent", "d1b6a_2.ent-d1chma2.ent", "d1b6a_2.ent-d1o0xa_.ent", "d1b6a_2.ent-d1xgsa2.ent", "d1b6cb_.ent-d1a06__.ent", "d1b6cb_.ent-d1blxa_.ent", "d1b6cb_.ent-d1csn__.ent", "d1b6cb_.ent-d1f3mc_.ent", "d1b6cb_.ent-d1fgka_.ent", "d1b6cb_.ent-d1fvra_.ent", "d1b6cb_.ent-d1ia9a_.ent", "d1b6cb_.ent-d1iepa_.ent", "d1b6cb_.ent-d1jksa_.ent", "d1b6cb_.ent-d1jpaa_.ent", "d1b6cb_.ent-d1jvpp_.ent", "d1b6cb_.ent-d1kwpa_.ent", "d1b6cb_.ent-d1lufa_.ent", "d1b6cb_.ent-d1m14a_.ent", "d1b6cb_.ent-d1phk__.ent", "d1b6cb_.ent-d1tkia_.ent", "d1b6e__.ent-d1cwva5.ent", "d1b6e__.ent-d1e87a_.ent", "d1b6e__.ent-d1f00i3.ent", "d1b6e__.ent-d1fvub_.ent", "d1b6e__.ent-d1g1ta1.ent", "d1b6e__.ent-d1h8ua_.ent", "d1b6e__.ent-d1li1a1.ent", "d1b6e__.ent-d1li1a2.ent", "d1b6e__.ent-d1prtb2.ent", "d1b6e__.ent-d1tsg__.ent", "d1b6ra1.ent-d1bdo__.ent", "d1b6ra1.ent-d1dv1a1.ent", "d1b6ra1.ent-d1e2wa2.ent", "d1b6ra1.ent-d1gpr__.ent", "d1b6ra1.ent-d1gsoa1.ent", "d1b6ra1.ent-d1hcz_2.ent", "d1b6ra1.ent-d1htp__.ent", "d1b6ra1.ent-d1k8ma_.ent", "d1b6ra1.ent-d1kjqa1.ent", "d1b6ra2.ent-d1e4ea1.ent", "d1b6ra2.ent-d1ehia1.ent", "d1b6ra2.ent-d1gsa_1.ent", "d1b6ra2.ent-d1gsoa2.ent", "d1b6ra2.ent-d1iow_1.ent", "d1b6ra2.ent-d1kjqa2.ent", "d1b6ra2.ent-d1m0wa1.ent", "d1b6ra2.ent-d2hgsa1.ent", "d1b6ra3.ent-d1dv1a3.ent", "d1b6ra3.ent-d1e4ea2.ent", "d1b6ra3.ent-d1ehia2.ent", "d1b6ra3.ent-d1eucb2.ent", "d1b6ra3.ent-d1gsa_2.ent", "d1b6ra3.ent-d1gsoa3.ent", "d1b6ra3.ent-d1iow_2.ent", "d1b6ra3.ent-d1jkjb2.ent", "d1b6ra3.ent-d1kbla3.ent", "d1b6ra3.ent-d1kjqa3.ent", "d1b6ra3.ent-d1m0wa2.ent", "d1b6ra3.ent-d2hgsa4.ent", "d1b72a_.ent-d1b8ia_.ent", "d1b72a_.ent-d1bl0a2.ent", "d1b72a_.ent-d1bw5__.ent", "d1b72a_.ent-d1d5ya2.ent", "d1b72a_.ent-d1e3oc1.ent", "d1b72a_.ent-d1fexa_.ent", "d1b72a_.ent-d1fjla_.ent", "d1b72a_.ent-d1g2ha_.ent", "d1b72a_.ent-d1hlva1.ent", "d1b72a_.ent-d1hlva2.ent", "d1b72a_.ent-d1ig7a_.ent", "d1b72a_.ent-d1irza_.ent", "d1b72a_.ent-d1iufa2.ent", "d1b72a_.ent-d1k61a_.ent", "d1b72a_.ent-d1k78a1.ent", "d1b72a_.ent-d1k78a2.ent", "d1b72a_.ent-d2tct_1.ent", "d1b72b_.ent-d1b72a_.ent", "d1b72b_.ent-d1b8ia_.ent", "d1b72b_.ent-d1bl0a2.ent", "d1b72b_.ent-d1bw5__.ent", "d1b72b_.ent-d1d5ya2.ent", "d1b72b_.ent-d1e3oc1.ent", "d1b72b_.ent-d1fexa_.ent", "d1b72b_.ent-d1fjla_.ent", "d1b72b_.ent-d1g2ha_.ent", "d1b72b_.ent-d1hlva1.ent", "d1b72b_.ent-d1hlva2.ent", "d1b72b_.ent-d1ig7a_.ent", "d1b72b_.ent-d1irza_.ent", "d1b72b_.ent-d1iufa2.ent", "d1b72b_.ent-d1jt6a1.ent", "d1b72b_.ent-d1k61a_.ent", "d1b72b_.ent-d1k78a1.ent", "d1b72b_.ent-d1k78a2.ent", "d1b72b_.ent-d2tct_1.ent", "d1b74a1.ent-d1b74a2.ent", "d1b74a1.ent-d1jfla1.ent", "d1b74a1.ent-d1jfla2.ent", "d1b74a2.ent-d1duvg1.ent", "d1b74a2.ent-d1duvg2.ent", "d1b74a2.ent-d1jfla1.ent", "d1b74a2.ent-d1jfla2.ent", "d1b74a2.ent-d1ml4a2.ent", "d1b77a1.ent-d1b77a2.ent", "d1b77a1.ent-d1dmla1.ent", "d1b77a1.ent-d1dmla2.ent", "d1b77a1.ent-d1ge8a1.ent", "d1b77a1.ent-d1ge8a2.ent", "d1b77a1.ent-d1plq_1.ent", "d1b77a1.ent-d1plq_2.ent", "d1b77a1.ent-d2pola1.ent", "d1b77a1.ent-d2pola2.ent", "d1b77a1.ent-d2pola3.ent", "d1b77a2.ent-d1dmla1.ent", "d1b77a2.ent-d1dmla2.ent", "d1b77a2.ent-d1ge8a1.ent", "d1b77a2.ent-d1ge8a2.ent", "d1b77a2.ent-d1plq_1.ent", "d1b77a2.ent-d1plq_2.ent", "d1b77a2.ent-d2pola1.ent", "d1b77a2.ent-d2pola2.ent", "d1b77a2.ent-d2pola3.ent", "d1b7ba_.ent-d1e19a_.ent", "d1b7ba_.ent-d1gs5a_.ent", "d1b7fa2.ent-d1cvja1.ent", "d1b7fa2.ent-d1cvja2.ent", "d1b7fa2.ent-d1fj7a_.ent", "d1b7fa2.ent-d1fjeb2.ent", "d1b7fa2.ent-d1fxla1.ent", "d1b7fa2.ent-d1fxla2.ent", "d1b7fa2.ent-d1h6kx_.ent", "d1b7fa2.ent-d1hd1a_.ent", "d1b7fa2.ent-d1iqta_.ent", "d1b7fa2.ent-d1jmta_.ent", "d1b7fa2.ent-d1koha2.ent", "d1b7fa2.ent-d1l3ka1.ent", "d1b7fa2.ent-d1l3ka2.ent", "d1b7fa2.ent-d1nu4a_.ent", "d1b7fa2.ent-d1qm9a1.ent", "d1b7fa2.ent-d1qm9a2.ent", "d1b7fa2.ent-d1u2fa_.ent", "d1b7fa2.ent-d2msta_.ent", "d1b7fa2.ent-d2u1a__.ent", "d1b7fa2.ent-d2u2fa_.ent", "d1b7go2.ent-d1cf2o2.ent", "d1b7go2.ent-d1dih_2.ent", "d1b7go2.ent-d1dpga2.ent", "d1b7go2.ent-d1e5qa2.ent", "d1b7go2.ent-d1ebfa2.ent", "d1b7go2.ent-d1f06a2.ent", "d1b7go2.ent-d1gr0a2.ent", "d1b7go2.ent-d1h6da2.ent", "d1b7go2.ent-d1j5pa3.ent", "d1b7go2.ent-d1jkia2.ent", "d1b7go2.ent-d1jn0a2.ent", "d1b7go2.ent-d1lc0a2.ent", "d1b7go2.ent-d1mb4a2.ent", "d1b7go2.ent-d1qkia2.ent", "d1b87a_.ent-d1bob__.ent", "d1b87a_.ent-d1cjwa_.ent", "d1b87a_.ent-d1fy7a_.ent", "d1b87a_.ent-d1i12a_.ent", "d1b87a_.ent-d1iica2.ent", "d1b87a_.ent-d1iyka1.ent", "d1b87a_.ent-d1iyka2.ent", "d1b87a_.ent-d1kzfa_.ent", "d1b87a_.ent-d1lrza2.ent", "d1b87a_.ent-d1lrza3.ent", "d1b87a_.ent-d1m4ia_.ent", "d1b87a_.ent-d1qsma_.ent", "d1b87a_.ent-d1qsta_.ent", "d1b88a_.ent-d1bec_1.ent", "d1b88a_.ent-d1c5ch1.ent", "d1b88a_.ent-d1dlfl_.ent", "d1b88a_.ent-d1h5ba_.ent", "d1b88a_.ent-d1nfdb1.ent", "d1b88a_.ent-d2rhe__.ent", "d1b8aa2.ent-d1bia_3.ent", "d1b8aa2.ent-d1e1oa2.ent", "d1b8aa2.ent-d1eova2.ent", "d1b8aa2.ent-d1g51a3.ent", "d1b8aa2.ent-d1h4vb2.ent", "d1b8aa2.ent-d1hc7a2.ent", "d1b8aa2.ent-d1jjca_.ent", "d1b8aa2.ent-d1jjcb5.ent", "d1b8aa2.ent-d1kmma2.ent", "d1b8aa2.ent-d1qe0a2.ent", "d1b8aa2.ent-d1qf6a4.ent", "d1b8aa2.ent-d1seta2.ent", "d1b8da_.ent-d1a6m__", "d1b8da_.ent-d1a6m__.ent", "d1b8da_.ent-d1alla_", "d1b8da_.ent-d1alla_.ent", "d1b8da_.ent-d1allb_", "d1b8da_.ent-d1allb_.ent", "d1b8da_.ent-d1ash__", "d1b8da_.ent-d1ash__.ent", "d1b8da_.ent-d1cg5a_", "d1b8da_.ent-d1cg5a_.ent", "d1b8da_.ent-d1cg5b_", "d1b8da_.ent-d1cg5b_.ent", "d1b8da_.ent-d1cqxa1", "d1b8da_.ent-d1cqxa1.ent", "d1b8da_.ent-d1ew6a_", "d1b8da_.ent-d1ew6a_.ent", "d1b8da_.ent-d1gcva_", "d1b8da_.ent-d1gcva_.ent", "d1b8da_.ent-d1gvha1", "d1b8da_.ent-d1gvha1.ent", "d1b8da_.ent-d1h97a_", "d1b8da_.ent-d1h97a_.ent", "d1b8da_.ent-d1hlb__", "d1b8da_.ent-d1hlb__.ent", "d1b8da_.ent-d1irda_", "d1b8da_.ent-d1irda_.ent", "d1b8da_.ent-d1irdb_", "d1b8da_.ent-d1irdb_.ent", "d1b8da_.ent-d1it2a_", "d1b8da_.ent-d1it2a_.ent", "d1b8da_.ent-d1itha_", "d1b8da_.ent-d1itha_.ent", "d1b8da_.ent-d1jl7a_", "d1b8da_.ent-d1jl7a_.ent", "d1b8da_.ent-d1la6a_", "d1b8da_.ent-d1la6a_.ent", "d1b8da_.ent-d1mba__", "d1b8da_.ent-d1mba__.ent", "d1b8da_.ent-d1phna_", "d1b8da_.ent-d1phna_.ent", "d1b8da_.ent-d2gdm__", "d1b8da_.ent-d2gdm__.ent", "d1b8da_.ent-d2lhb__", "d1b8da_.ent-d2lhb__.ent", "d1b8da_.ent-d3sdha_", "d1b8da_.ent-d3sdha_.ent", "d1b8ia_.ent-d1bl0a2.ent", "d1b8ia_.ent-d1e3oc1.ent", "d1b8ia_.ent-d1fexa_.ent", "d1b8ia_.ent-d1g2ha_.ent", "d1b8ia_.ent-d1ig7a_.ent", "d1b8ia_.ent-d1k61a_.ent", "d1b8ia_.ent-d1k78a2.ent", "d1b8oa_.ent-d1boub_.ent", "d1b8oa_.ent-d1c8ba_.ent", "d1b8oa_.ent-d1cb0a_.ent", "d1b8oa_.ent-d1cfza_.ent", "d1b8oa_.ent-d1g2oa_.ent", "d1b8oa_.ent-d1je0a_.ent", "d1b8oa_.ent-d1jysa_.ent", "d1b8oa_.ent-d1k9sa_.ent", "d1b8oa_.ent-d1lam_2.ent", "d1b8oa_.ent-d1lfwa1.ent", "d1b8oa_.ent-d1loka_.ent", "d1b8oa_.ent-d1m4la_.ent", "d1b8oa_.ent-d2pth__.ent", "d1b8pa2.ent-d1ez4a2.ent", "d1b8pa2.ent-d1guya2.ent", "d1b8pa2.ent-d1hyea2.ent", "d1b8pa2.ent-d1hyha2.ent", "d1b8pa2.ent-d1i0za2.ent", "d1b8pa2.ent-d1ldg_2.ent", "d1b8pa2.ent-d1ldna2.ent", "d1b8pa2.ent-d1llda2.ent", "d1b8pa2.ent-d1o6za2.ent", "d1b8pa2.ent-d2cmd_2.ent", "d1b8pa2.ent-d5mdha2.ent", "d1b8pa2.ent-d7mdha2.ent", "d1b8wa_.ent-d1bnb__.ent", "d1b8wa_.ent-d1d6ba_.ent", "d1b8wa_.ent-d1dfna_.ent", "d1b8wa_.ent-d1e4ta_.ent", "d1b8wa_.ent-d1ewsa_.ent", "d1b8wa_.ent-d1fd3a_.ent", "d1b8wa_.ent-d1ijva_.ent", "d1b8wa_.ent-d1kj6a_.ent", "d1b8wa_.ent-d1sh1__.ent", "d1b8wa_.ent-d2bds__.ent", "d1b8za_.ent-d1dp3a_.ent", "d1b8za_.ent-d1exea_.ent", "d1b8za_.ent-d1ihfa_.ent", "d1b8za_.ent-d1ihfb_.ent", "d1b9ha_.ent-d1bs0a_.ent", "d1b9ha_.ent-d1c4ka2.ent", "d1b9ha_.ent-d1elua_.ent", "d1b9ha_.ent-d1js3a_.ent", "d1b9ha_.ent-d1kl1a_.ent", "d1b9ha_.ent-d1lc5a_.ent", "d1b9ha_.ent-d1qj5a_.ent", "d1b9la_.ent-d1dhn__.ent", "d1b9la_.ent-d1is8a_.ent", "d1b9la_.ent-d1uox_1.ent", "d1b9la_.ent-d1uox_2.ent", "d1b9oa_.ent-d1chka_.ent", "d1b9oa_.ent-d1dxja_.ent", "d1b9oa_.ent-d1gd6a_.ent", "d1b9oa_.ent-d1k28a3.ent", "d1b9oa_.ent-d1qgia_.ent", "d1b9oa_.ent-d1qsaa2.ent", "d1b9oa_.ent-d1qusa_.ent", "d1b9oa_.ent-d217l__.ent", "d1b9oa_.ent-d2eql__.ent", "d1b9oa_.ent-d3lzt__.ent", "d1b9ra_.ent-d1czpa_.ent", "d1b9ra_.ent-d1doi__.ent", "d1b9ra_.ent-d1e9ma_.ent", "d1b9ra_.ent-d1feha2.ent", "d1b9ra_.ent-d1fo4a2.ent", "d1b9ra_.ent-d1hlra2.ent", "d1b9ra_.ent-d1i7ha_.ent", "d1b9ra_.ent-d1jq4a_.ent", "d1b9ra_.ent-d1jroa2.ent", "d1b9ra_.ent-d1kf6b2.ent", "d1b9ra_.ent-d1krha3.ent", "d1b9ra_.ent-d1l5pa_.ent", "d1b9ra_.ent-d1n62a2.ent", "d1b9ra_.ent-d1nekb2.ent", "d1b9ra_.ent-d1put__.ent", "d1b9ra_.ent-d1qlab2.ent", "d1b9ra_.ent-d2pia_3.ent", "d1b9wa1.ent-d1b9wa2.ent", "d1b9wa1.ent-d1ceja1.ent", "d1b9wa1.ent-d1cixa_.ent", "d1b9wa1.ent-d1cvua2.ent", "d1b9wa1.ent-d1dx5i1.ent", "d1b9wa1.ent-d1emo_1.ent", "d1b9wa1.ent-d1g9pa_.ent", "d1b9wa1.ent-d1h59b_.ent", "d1b9wa1.ent-d1hz8a1.ent", "d1b9wa1.ent-d1hz8a2.ent", "d1b9wa1.ent-d1i2ua_.ent", "d1b9wa1.ent-d1imt_2.ent", "d1b9wa1.ent-d1jl9a_.ent", "d1b9wa1.ent-d1l3ya_.ent", "d1b9wa1.ent-d1m1xb5.ent", "d1b9wa1.ent-d1tpg_1.ent", "d1b9wa1.ent-d1urk_1.ent", "d1b9wa2.ent-d1cixa_.ent", "d1b9wa2.ent-d1cvua2.ent", "d1b9wa2.ent-d1dx5i1.ent", "d1b9wa2.ent-d1emo_1.ent", "d1b9wa2.ent-d1hz8a1.ent", "d1b9wa2.ent-d1hz8a2.ent", "d1b9wa2.ent-d1i2ua_.ent", "d1b9wa2.ent-d1imt_2.ent", "d1b9wa2.ent-d1jl9a_.ent", "d1b9wa2.ent-d1l3ya_.ent", "d1b9wa2.ent-d1m1xb5.ent", "d1b9wa2.ent-d1tpg_1.ent", "d1b9wa2.ent-d1urk_1.ent", "d1b9za2.ent-d1cz1a_.ent", "d1b9za2.ent-d1e43a2.ent", "d1b9za2.ent-d1eh9a3.ent", "d1b9za2.ent-d1iexa1.ent", "d1b9za2.ent-d1j0ha3.ent", "d1b9za2.ent-d1kwga2.ent", "d1b9za2.ent-d1lwha2.ent", "d1b9za2.ent-d1pama4.ent", "d1b9za2.ent-d1qhoa4.ent", "d1b9za2.ent-d7taa_2.ent", "d1bag_1.ent-d1bf2_2.ent", "d1bag_1.ent-d1e43a1.ent", "d1bag_1.ent-d1ea9c2.ent", "d1bag_1.ent-d1eh9a2.ent", "d1bag_1.ent-d1g5aa1.ent", "d1bag_1.ent-d1g94a1.ent", "d1bag_1.ent-d1gcya1.ent", "d1bag_1.ent-d1gjwa1.ent", "d1bag_1.ent-d1hx0a1.ent", "d1bag_1.ent-d1iv8a1.ent", "d1bag_1.ent-d1j0ha2.ent", "d1bag_1.ent-d1jae_1.ent", "d1bag_1.ent-d1ji1a2.ent", "d1bag_1.ent-d1ji2a2.ent", "d1bag_1.ent-d1ktba1.ent", "d1bag_1.ent-d1kwga1.ent", "d1bag_1.ent-d1lwha1.ent", "d1bag_1.ent-d1m7xa2.ent", "d1bag_1.ent-d1qhoa3.ent", "d1bag_1.ent-d1uok_1.ent", "d1bag_1.ent-d7taa_1.ent", "d1bak__.ent-d1btka_.ent", "d1bak__.ent-d1btn__.ent", "d1bak__.ent-d1ddma_.ent", "d1bak__.ent-d1dro__.ent", "d1bak__.ent-d1dyna_.ent", "d1bak__.ent-d1eaza_.ent", "d1bak__.ent-d1evha_.ent", "d1bak__.ent-d1faoa_.ent", "d1bak__.ent-d1fhoa_.ent", "d1bak__.ent-d1gg3a2.ent", "d1bak__.ent-d1h4ra2.ent", "d1bak__.ent-d1k5db_.ent", "d1bak__.ent-d1ki1b2.ent", "d1bak__.ent-d1mai__.ent", "d1bak__.ent-d1mixa2.ent", "d1bak__.ent-d1mkea1.ent", "d1bak__.ent-d1pls__.ent", "d1bak__.ent-d1qqga1.ent", "d1bak__.ent-d1qqga2.ent", "d1bak__.ent-d1shca_.ent", "d1bam__.ent-d1cfr__.ent", "d1bam__.ent-d1ckqa_.ent", "d1bam__.ent-d1d02a_.ent", "d1bam__.ent-d1dc1a_.ent", "d1bam__.ent-d1dmua_.ent", "d1bam__.ent-d1dzfa1.ent", "d1bam__.ent-d1ev7a_.ent", "d1bam__.ent-d1f1za2.ent", "d1bam__.ent-d1fiua_.ent", "d1bam__.ent-d1gefa_.ent", "d1bam__.ent-d1hh1a_.ent", "d1bam__.ent-d1kc6a_.ent", "d1bam__.ent-d1knva_.ent", "d1bam__.ent-d1m0da_.ent", "d1bam__.ent-d1vsra_.ent", "d1bam__.ent-d2foka4.ent", "d1bam__.ent-d3pvia_.ent", "d1baza_.ent-d1cmba_.ent", "d1baza_.ent-d1irqa_.ent", "d1baza_.ent-d1mnta_.ent", "d1baza_.ent-d2cpga_.ent", "d1bb8__.ent-d1d9na_.ent", "d1bb8__.ent-d1gcca_.ent", "d1bb8__.ent-d1kjka_.ent", "d1bb8__.ent-d1qk9a_.ent", "d1bb9__.ent-d1bbza_.ent", "d1bb9__.ent-d1dj7b_.ent", "d1bb9__.ent-d1fmk_1.ent", "d1bb9__.ent-d1g3sa3.ent", "d1bb9__.ent-d1gcqa_.ent", "d1bb9__.ent-d1gcqc_.ent", "d1bb9__.ent-d1gl5a_.ent", "d1bb9__.ent-d1gria1.ent", "d1bb9__.ent-d1h92a_.ent", "d1bb9__.ent-d1i07a_.ent", "d1bb9__.ent-d1i1ja_.ent", "d1bb9__.ent-d1jb0e_.ent", "d1bb9__.ent-d1jo8a_.ent", "d1bb9__.ent-d1jqqa_.ent", "d1bb9__.ent-d1k4us_.ent", "d1bb9__.ent-d1khia1.ent", "d1bb9__.ent-d1kjwa1.ent", "d1bb9__.ent-d1m9sa2.ent", "d1bb9__.ent-d1neb__.ent", "d1bb9__.ent-d1pht__.ent", "d1bb9__.ent-d1pwt__.ent", "d1bb9__.ent-d1qcfa1.ent", "d1bb9__.ent-d1vie__.ent", "d1bb9__.ent-d1ycsb2.ent", "d1bb9__.ent-d2hsp__.ent", "d1bbha_.ent-d1cpq__.ent", "d1bbha_.ent-d1gqaa_.ent", "d1bbha_.ent-d1jafa_.ent", "d1bbha_.ent-d1mqva_.ent", "d1bbha_.ent-d256ba_.ent", "d1bbha_.ent-d2ccya_.ent", "d1bbpa_.ent-d1beba_.ent", "d1bbpa_.ent-d1bj7__.ent", "d1bbpa_.ent-d1cbs__.ent", "d1bbpa_.ent-d1dzka_.ent", "d1bbpa_.ent-d1euoa_.ent", "d1bbpa_.ent-d1ew3a_.ent", "d1bbpa_.ent-d1ftpa_.ent", "d1bbpa_.ent-d1g85a_.ent", "d1bbpa_.ent-d1ggla_.ent", "d1bbpa_.ent-d1gkab_.ent", "d1bbpa_.ent-d1hms__.ent", "d1bbpa_.ent-d1i4ua_.ent", "d1bbpa_.ent-d1ifc__.ent", "d1bbpa_.ent-d1jv4a_.ent", "d1bbpa_.ent-d1koia_.ent", "d1bbpa_.ent-d1kqwa_.ent", "d1bbpa_.ent-d1lf7a_.ent", "d1bbpa_.ent-d1o1va_.ent", "d1bbpa_.ent-d1qfta_.ent", "d1bbpa_.ent-d1qqsa_.ent", "d1bbza_.ent-d1fmk_1.ent", "d1bbza_.ent-d1gcqa_.ent", "d1bbza_.ent-d1gcqc_.ent", "d1bbza_.ent-d1gl5a_.ent", "d1bbza_.ent-d1gria1.ent", "d1bbza_.ent-d1h92a_.ent", "d1bbza_.ent-d1i07a_.ent", "d1bbza_.ent-d1i1ja_.ent", "d1bbza_.ent-d1jo8a_.ent", "d1bbza_.ent-d1jqqa_.ent", "d1bbza_.ent-d1k4us_.ent", "d1bbza_.ent-d1kjwa1.ent", "d1bbza_.ent-d1neb__.ent", "d1bbza_.ent-d1pht__.ent", "d1bbza_.ent-d1pwt__.ent", "d1bbza_.ent-d1qcfa1.ent", "d1bbza_.ent-d1ycsb2.ent", "d1bbza_.ent-d2hsp__.ent", "d1bcca1.ent-d1bcca2.ent", "d1bcca1.ent-d1bccb1.ent", "d1bcca1.ent-d1bccb2.ent", "d1bcca1.ent-d1ezva1.ent", "d1bcca1.ent-d1ezva2.ent", "d1bcca1.ent-d1ezvb1.ent", "d1bcca1.ent-d1ezvb2.ent", "d1bcca1.ent-d1hr6a1.ent", "d1bcca1.ent-d1hr6a2.ent", "d1bcca1.ent-d1hr6b1.ent", "d1bcca1.ent-d1hr6b2.ent", "d1bcca2.ent-d1bccb1.ent", "d1bcca2.ent-d1bccb2.ent", "d1bcca2.ent-d1ezva1.ent", "d1bcca2.ent-d1ezva2.ent", "d1bcca2.ent-d1ezvb1.ent", "d1bcca2.ent-d1ezvb2.ent", "d1bcca2.ent-d1hr6a1.ent", "d1bcca2.ent-d1hr6a2.ent", "d1bcca2.ent-d1hr6b1.ent", "d1bcca2.ent-d1hr6b2.ent", "d1bccb1.ent-d1bccb2.ent", "d1bccb1.ent-d1ezva1.ent", "d1bccb1.ent-d1ezva2.ent", "d1bccb1.ent-d1ezvb1.ent", "d1bccb1.ent-d1ezvb2.ent", "d1bccb1.ent-d1hr6a1.ent", "d1bccb1.ent-d1hr6a2.ent", "d1bccb1.ent-d1hr6b1.ent", "d1bccb1.ent-d1hr6b2.ent", "d1bccb2.ent-d1ezva1.ent", "d1bccb2.ent-d1ezva2.ent", "d1bccb2.ent-d1ezvb1.ent", "d1bccb2.ent-d1ezvb2.ent", "d1bccb2.ent-d1hr6a1.ent", "d1bccb2.ent-d1hr6a2.ent", "d1bccb2.ent-d1hr6b1.ent", "d1bccb2.ent-d1hr6b2.ent", "d1bccg_.ent-d1ehkc_.ent", "d1bccg_.ent-d1ezvd2.ent", "d1bccg_.ent-d1ezve2.ent", "d1bccg_.ent-d1ezvg_.ent", "d1bccg_.ent-d1ezvi_.ent", "d1bccg_.ent-d1jb0f_.ent", "d1bccg_.ent-d1jb0i_.ent", "d1bccg_.ent-d1jb0j_.ent", "d1bccg_.ent-d1jb0m_.ent", "d1bccg_.ent-d1kqfb2.ent", "d1bccg_.ent-d1l2pa_.ent", "d1bccg_.ent-d1m56d_.ent", "d1bccg_.ent-d1ocrd_.ent", "d1bccg_.ent-d1ocrg_.ent", "d1bccg_.ent-d1ocri_.ent", "d1bccg_.ent-d1ocrj_.ent", "d1bccg_.ent-d1ocrk_.ent", "d1bccg_.ent-d1ocrl_.ent", "d1bccg_.ent-d1ocrm_.ent", "d1bcg__.ent-d1bmr__.ent", "d1bcg__.ent-d1c55a_.ent", "d1bcg__.ent-d1cmr__.ent", "d1bcg__.ent-d1fjna_.ent", "d1bcg__.ent-d1gps__.ent", "d1bcg__.ent-d1i2ua_.ent", "d1bcg__.ent-d1ica__.ent", "d1bcg__.ent-d1jkza_.ent", "d1bcg__.ent-d1jxca_.ent", "d1bcg__.ent-d1myn__.ent", "d1bcg__.ent-d1npia_.ent", "d1bcg__.ent-d1nrb__.ent", "d1bcg__.ent-d1qkya_.ent", "d1bcg__.ent-d1sco__.ent", "d1bcg__.ent-d1scy__.ent", "d1bcg__.ent-d1sis__.ent", "d1bcg__.ent-d1tsk__.ent", "d1bcg__.ent-d2sn3__.ent", "d1bco_2.ent-d1az9_1.ent", "d1bco_2.ent-d1bupa1.ent", "d1bco_2.ent-d1bupa2.ent", "d1bco_2.ent-d1cxqa_.ent", "d1bco_2.ent-d1czan1.ent", "d1bco_2.ent-d1e4ft1.ent", "d1bco_2.ent-d1e4ft2.ent", "d1bco_2.ent-d1exqa_.ent", "d1bco_2.ent-d1fxxa_.ent", "d1bco_2.ent-d1hjra_.ent", "d1bco_2.ent-d1i39a_.ent", "d1bco_2.ent-d1ih7a1.ent", "d1bco_2.ent-d1io2a_.ent", "d1bco_2.ent-d1j54a_.ent", "d1bco_2.ent-d1jj2m_.ent", "d1bco_2.ent-d1jl1a_.ent", "d1bco_2.ent-d1kcfa2.ent", "d1bco_2.ent-d1kfsa1.ent", "d1bco_2.ent-d1musa_.ent", "d1bco_2.ent-d1mwma2.ent", "d1bco_2.ent-d1nbwa3.ent", "d1bco_2.ent-d1qtma1.ent", "d1bco_2.ent-d1t7pa1.ent", "d1bco_2.ent-d1tgoa1.ent", "d1bco_2.ent-d1vrta1.ent", "d1bco_2.ent-d1xwl_1.ent", "d1bd0a1.ent-d1e79a2.ent", "d1bd0a1.ent-d1e79d2.ent", "d1bd0a1.ent-d7odca1.ent", "d1bd3a_.ent-d1bzya_.ent", "d1bd3a_.ent-d1dkra1.ent", "d1bd3a_.ent-d1dkra2.ent", "d1bd3a_.ent-d1dqna_.ent", "d1bd3a_.ent-d1ecfa1.ent", "d1bd3a_.ent-d1fsga_.ent", "d1bd3a_.ent-d1g2qa_.ent", "d1bd3a_.ent-d1g9sa_.ent", "d1bd3a_.ent-d1gph11.ent", "d1bd3a_.ent-d1hgxa_.ent", "d1bd3a_.ent-d1i5ea_.ent", "d1bd3a_.ent-d1l1qa_.ent", "d1bd3a_.ent-d1lh0a_.ent", "d1bd3a_.ent-d1nula_.ent", "d1bd3a_.ent-d1qb7a_.ent", "d1bd3a_.ent-d1tc1a_.ent", "d1bd8__.ent-d1bi7b_.ent", "d1bd8__.ent-d1dcqa1.ent", "d1bd8__.ent-d1ihba_.ent", "d1bd8__.ent-d1k1aa_.ent", "d1bd8__.ent-d1k3zd_.ent", "d1bd8__.ent-d1lm5a_.ent", "d1bd8__.ent-d1myo__.ent", "d1bd8__.ent-d1n11a_.ent", "d1bd8__.ent-d1sw6a_.ent", "d1bd8__.ent-d1ycsb1.ent", "d1bdb__.ent-d1bgva1.ent", "d1bdb__.ent-d1e7wa_.ent", "d1bdb__.ent-d1gcoa_.ent", "d1bdb__.ent-d1h5qa_.ent", "d1bdb__.ent-d1ja9a_.ent", "d1bdb__.ent-d1oaa__.ent", "d1bdb__.ent-d1qsga_.ent", "d1bdb__.ent-d2ae2a_.ent", "d1bdfa1.ent-d1dcpa_.ent", "d1bdfa1.ent-d1g51a2.ent", "d1bdfa1.ent-d1i50c1.ent", "d1bdfa1.ent-d1i50k_.ent", "d1bdfa1.ent-d1iw7a1.ent", "d1bdfa1.ent-d1xxaa_.ent", "d1bdfa2.ent-d1i50c2.ent", "d1bdfa2.ent-d1iw7a2.ent", "d1bdg_1.ent-d1bdg_2.ent", "d1bdg_1.ent-d1bupa1.ent", "d1bdg_1.ent-d1bupa2.ent", "d1bdg_1.ent-d1czan1.ent", "d1bdg_1.ent-d1czan2.ent", "d1bdg_1.ent-d1czan3.ent", "d1bdg_1.ent-d1dkgd2.ent", "d1bdg_1.ent-d1e4ft1.ent", "d1bdg_1.ent-d1e4ft2.ent", "d1bdg_1.ent-d1g99a1.ent", "d1bdg_1.ent-d1g99a2.ent", "d1bdg_1.ent-d1glag1.ent", "d1bdg_1.ent-d1glag2.ent", "d1bdg_1.ent-d1huxa_.ent", "d1bdg_1.ent-d1ig8a1.ent", "d1bdg_1.ent-d1ig8a2.ent", "d1bdg_1.ent-d1j6za2.ent", "d1bdg_1.ent-d1jcfa1.ent", "d1bdg_1.ent-d1k8ka1.ent", "d1bdg_1.ent-d1mwma1.ent", "d1bdg_1.ent-d1mwma2.ent", "d1bdg_1.ent-d1nbwa2.ent", "d1bdg_1.ent-d1nbwa3.ent", "d1bdg_2.ent-d1bupa1.ent", "d1bdg_2.ent-d1bupa2.ent", "d1bdg_2.ent-d1czan1.ent", "d1bdg_2.ent-d1czan2.ent", "d1bdg_2.ent-d1czan3.ent", "d1bdg_2.ent-d1dkgd2.ent", "d1bdg_2.ent-d1e4ft1.ent", "d1bdg_2.ent-d1e4ft2.ent", "d1bdg_2.ent-d1g99a1.ent", "d1bdg_2.ent-d1g99a2.ent", "d1bdg_2.ent-d1glag1.ent", "d1bdg_2.ent-d1glag2.ent", "d1bdg_2.ent-d1huxa_.ent", "d1bdg_2.ent-d1ig8a1.ent", "d1bdg_2.ent-d1ig8a2.ent", "d1bdg_2.ent-d1j6za2.ent", "d1bdg_2.ent-d1jcfa1.ent", "d1bdg_2.ent-d1k8ka1.ent", "d1bdg_2.ent-d1mwma1.ent", "d1bdg_2.ent-d1mwma2.ent", "d1bdg_2.ent-d1nbwa2.ent", "d1bdg_2.ent-d1nbwa3.ent", "d1bdo__.ent-d1dd2a_.ent", "d1bdo__.ent-d1dv1a1.ent", "d1bdo__.ent-d1e2wa2.ent", "d1bdo__.ent-d1fyc__.ent", "d1bdo__.ent-d1ghk__.ent", "d1bdo__.ent-d1gpr__.ent", "d1bdo__.ent-d1gsoa1.ent", "d1bdo__.ent-d1htp__.ent", "d1bdo__.ent-d1k8ma_.ent", "d1bdo__.ent-d1kjqa1.ent", "d1bdo__.ent-d1lac__.ent", "d1bdo__.ent-d1qjoa_.ent", "d1bdya_.ent-d1d5ra1.ent", "d1bdya_.ent-d1dqva1.ent", "d1bdya_.ent-d1dsya_.ent", "d1bdya_.ent-d1e8xa2.ent", "d1bdya_.ent-d1gmia_.ent", "d1bdya_.ent-d1k5wa_.ent", "d1bdya_.ent-d1qasa2.ent", "d1bdya_.ent-d1rlw__.ent", "d1bdya_.ent-d1rsy__.ent", "d1bdya_.ent-d3rpba_.ent", "d1be9a_.ent-d1d5ga_.ent", "d1be9a_.ent-d1g9oa_.ent", "d1be9a_.ent-d1i16__.ent", "d1be9a_.ent-d1ihja_.ent", "d1be9a_.ent-d1k32a1.ent", "d1be9a_.ent-d1kwaa_.ent", "d1be9a_.ent-d1lcya1.ent", "d1be9a_.ent-d1m5za_.ent", "d1be9a_.ent-d1mfga_.ent", "d1be9a_.ent-d1qaua_.ent", "d1be9a_.ent-d1qava_.ent", "d1be9a_.ent-d1qlca_.ent", "d1bea__.ent-d1fk5a_.ent", "d1bea__.ent-d1hssa_.ent", "d1bea__.ent-d1hyp__.ent", "d1bea__.ent-d1l6ha_.ent", "d1beba_.ent-d1bj7__.ent", "d1beba_.ent-d1cbs__.ent", "d1beba_.ent-d1dzka_.ent", "d1beba_.ent-d1euoa_.ent", "d1beba_.ent-d1ew3a_.ent", "d1beba_.ent-d1ftpa_.ent", "d1beba_.ent-d1g85a_.ent", "d1beba_.ent-d1ggla_.ent", "d1beba_.ent-d1gkab_.ent", "d1beba_.ent-d1hms__.ent", "d1beba_.ent-d1i4ua_.ent", "d1beba_.ent-d1ifc__.ent", "d1beba_.ent-d1jv4a_.ent", "d1beba_.ent-d1koia_.ent", "d1beba_.ent-d1kqwa_.ent", "d1beba_.ent-d1lf7a_.ent", "d1beba_.ent-d1o1va_.ent", "d1beba_.ent-d1qfta_.ent", "d1beba_.ent-d1qqsa_.ent", "d1bec_1.ent-d1c5ch1.ent", "d1bec_1.ent-d1dlfl_.ent", "d1bec_1.ent-d1h5ba_.ent", "d1bec_1.ent-d1nfdb1.ent", "d1bed_2.ent-d1a8l_2.ent", "d1bed_2.ent-d1a8y_3.ent", "d1bed_2.ent-d1bjx__.ent", "d1bed_2.ent-d1ep7a_.ent", "d1bed_2.ent-d1erv__.ent", "d1bed_2.ent-d1f9ma_.ent", "d1bed_2.ent-d1fb6a_.ent", "d1bed_2.ent-d1gh2a_.ent", "d1bed_2.ent-d1kte__.ent", "d1bed_2.ent-d1quwa_.ent", "d1bed_2.ent-d1thx__.ent", "d1bed_2.ent-d2trxa_.ent", "d1befa_.ent-d1cqqa_.ent", "d1befa_.ent-d1gdna_.ent", "d1befa_.ent-d1hava_.ent", "d1befa_.ent-d1lcya2.ent", "d1befa_.ent-d1lvmb_.ent", "d1befa_.ent-d1lvoa_.ent", "d1befa_.ent-d1mbma_.ent", "d1befa_.ent-d1qq4a_.ent", "d1befa_.ent-d1svpa_.ent", "d1befa_.ent-d2hrva_.ent", "d1bev1_.ent-d1aym2_.ent", "d1bev1_.ent-d1b35a_.ent", "d1bev1_.ent-d1b35b_.ent", "d1bev1_.ent-d1bev3_.ent", "d1bev1_.ent-d2mev1_.ent", "d1bev1_.ent-d2mev2_.ent", "d1bf0__.ent-d1bik_1.ent", "d1bf0__.ent-d1bik_2.ent", "d1bf0__.ent-d1bunb_.ent", "d1bf0__.ent-d1d0da_.ent", "d1bf0__.ent-d1g6xa_.ent", "d1bf0__.ent-d1irha_.ent", "d1bf0__.ent-d1ktha_.ent", "d1bf0__.ent-d1tfxc_.ent", "d1bf0__.ent-d1tocr1.ent", "d1bf0__.ent-d1tocr2.ent", "d1bf2_1.ent-d1dqia_.ent", "d1bf2_1.ent-d1ea9c1.ent", "d1bf2_1.ent-d1eaja_.ent", "d1bf2_1.ent-d1edqa1.ent", "d1bf2_1.ent-d1ej8a_.ent", "d1bf2_1.ent-d1eut_1.ent", "d1bf2_1.ent-d1g0da1.ent", "d1bf2_1.ent-d1grwa_.ent", "d1bf2_1.ent-d1j0ha1.ent", "d1bf2_1.ent-d1ji1a1.ent", "d1bf2_1.ent-d1ji2a1.ent", "d1bf2_1.ent-d1jjua4.ent", "d1bf2_1.ent-d1jmxa4.ent", "d1bf2_1.ent-d1kgce2.ent", "d1bf2_1.ent-d1kmta_.ent", "d1bf2_1.ent-d1ktja_.ent", "d1bf2_1.ent-d1kv3a1.ent", "d1bf2_1.ent-d1kyfa1.ent", "d1bf2_1.ent-d1l9na1.ent", "d1bf2_1.ent-d1lmia_.ent", "d1bf2_1.ent-d1m1xa1.ent", "d1bf2_1.ent-d1m1xa2.ent", "d1bf2_1.ent-d1m1xb1.ent", "d1bf2_1.ent-d1m7xa1.ent", "d1bf2_1.ent-d1my7a_.ent", "d1bf2_1.ent-d1nepa_.ent", "d1bf2_1.ent-d1o75a1.ent", "d1bf2_1.ent-d1qba_1.ent", "d1bf2_1.ent-d1qfha1.ent", "d1bf2_1.ent-d1qfha2.ent", "d1bf2_1.ent-d1soxa1.ent", "d1bf2_1.ent-d1xsoa_.ent", "d1bf2_2.ent-d1e43a1.ent", "d1bf2_2.ent-d1ea9c2.ent", "d1bf2_2.ent-d1eh9a2.ent", "d1bf2_2.ent-d1g5aa1.ent", "d1bf2_2.ent-d1g94a1.ent", "d1bf2_2.ent-d1gcya1.ent", "d1bf2_2.ent-d1gjwa1.ent", "d1bf2_2.ent-d1hx0a1.ent", "d1bf2_2.ent-d1iv8a1.ent", "d1bf2_2.ent-d1j0ha2.ent", "d1bf2_2.ent-d1jae_1.ent", "d1bf2_2.ent-d1ji1a2.ent", "d1bf2_2.ent-d1ji2a2.ent", "d1bf2_2.ent-d1ktba1.ent", "d1bf2_2.ent-d1kwga1.ent", "d1bf2_2.ent-d1lwha1.ent", "d1bf2_2.ent-d1m7xa2.ent", "d1bf2_2.ent-d1qhoa3.ent", "d1bf2_2.ent-d1uok_1.ent", "d1bf2_2.ent-d7taa_1.ent", "d1bf2_3.ent-d1b9za2.ent", "d1bf2_3.ent-d1cz1a_.ent", "d1bf2_3.ent-d1e43a2.ent", "d1bf2_3.ent-d1e4ia_.ent", "d1bf2_3.ent-d1eh9a3.ent", "d1bf2_3.ent-d1iexa1.ent", "d1bf2_3.ent-d1j0ha3.ent", "d1bf2_3.ent-d1ji1a3.ent", "d1bf2_3.ent-d1kwga2.ent", "d1bf2_3.ent-d1lwha2.ent", "d1bf2_3.ent-d1pama4.ent", "d1bf2_3.ent-d1qba_3.ent", "d1bf2_3.ent-d1qhoa4.ent", "d1bf2_3.ent-d7taa_2.ent", "d1bf4a_.ent-d1dz1a_.ent", "d1bf4a_.ent-d1e0ba_.ent", "d1bf4a_.ent-d1g6za_.ent", "d1bf4a_.ent-d1knaa_.ent", "d1bf4a_.ent-d1tvxa_.ent", "d1bf6a_.ent-d1i0da_.ent", "d1bf6a_.ent-d1itua_.ent", "d1bf6a_.ent-d1j5sa_.ent", "d1bf6a_.ent-d1k6wa2.ent", "d1bf6a_.ent-d1m7ja3.ent", "d1bfd_1.ent-d1d4oa_.ent", "d1bfd_1.ent-d1dhs__.ent", "d1bfd_1.ent-d1efva2.ent", "d1bfd_1.ent-d1hzzc_.ent", "d1bfd_1.ent-d1icia_.ent", "d1bfd_1.ent-d1j8fa_.ent", "d1bfd_1.ent-d1jsca1.ent", "d1bfd_1.ent-d1ma3a_.ent", "d1bfd_1.ent-d1o97d2.ent", "d1bfd_1.ent-d1poxa1.ent", "d1bfd_1.ent-d1pvda1.ent", "d1bfd_1.ent-d1zpda1.ent", "d1bfd_2.ent-d1bfd_3.ent", "d1bfd_2.ent-d1dtwa_.ent", "d1bfd_2.ent-d1dtwb1.ent", "d1bfd_2.ent-d1gpua1.ent", "d1bfd_2.ent-d1gpua2.ent", "d1bfd_2.ent-d1ik6a1.ent", "d1bfd_2.ent-d1jsca2.ent", "d1bfd_2.ent-d1jsca3.ent", "d1bfd_2.ent-d1keka1.ent", "d1bfd_2.ent-d1keka2.ent", "d1bfd_2.ent-d1l8aa1.ent", "d1bfd_2.ent-d1l8aa2.ent", "d1bfd_2.ent-d1poxa2.ent", "d1bfd_2.ent-d1poxa3.ent", "d1bfd_2.ent-d1pvda2.ent", "d1bfd_2.ent-d1pvda3.ent", "d1bfd_2.ent-d1zpda2.ent", "d1bfd_2.ent-d1zpda3.ent", "d1bfd_3.ent-d1dtwa_.ent", "d1bfd_3.ent-d1dtwb1.ent", "d1bfd_3.ent-d1gpua1.ent", "d1bfd_3.ent-d1gpua2.ent", "d1bfd_3.ent-d1ik6a1.ent", "d1bfd_3.ent-d1jsca2.ent", "d1bfd_3.ent-d1jsca3.ent", "d1bfd_3.ent-d1keka1.ent", "d1bfd_3.ent-d1keka2.ent", "d1bfd_3.ent-d1l8aa1.ent", "d1bfd_3.ent-d1l8aa2.ent", "d1bfd_3.ent-d1poxa2.ent", "d1bfd_3.ent-d1poxa3.ent", "d1bfd_3.ent-d1pvda2.ent", "d1bfd_3.ent-d1pvda3.ent", "d1bfd_3.ent-d1zpda2.ent", "d1bfd_3.ent-d1zpda3.ent", "d1bfg__.ent-d1dfca1.ent", "d1bfg__.ent-d1dfca2.ent", "d1bfg__.ent-d1dfca3.ent", "d1bfg__.ent-d1dqga_.ent", "d1bfg__.ent-d1hcd__.ent", "d1bfg__.ent-d1ihka_.ent", "d1bfg__.ent-d1ijta_.ent", "d1bfg__.ent-d1ilr1_.ent", "d1bfg__.ent-d1jlxa1.ent", "d1bfg__.ent-d1knma_.ent", "d1bfg__.ent-d1l2ha_.ent", "d1bfg__.ent-d1n4ka2.ent", "d1bfg__.ent-d1nuna_.ent", "d1bfg__.ent-d1qqla_.ent", "d1bg1a1.ent-d1ez3a_.ent", "d1bg1a1.ent-d1fioa_.ent", "d1bg1a1.ent-d1hs7a_.ent", "d1bg1a1.ent-d1lvfa_.ent", "d1bg1a2.ent-d1bvoa_.ent", "d1bg1a2.ent-d1e2wa1.ent", "d1bg1a2.ent-d1e5ba_.ent", "d1bg1a2.ent-d1f0la1.ent", "d1bg1a2.ent-d1h6fa_.ent", "d1bg1a2.ent-d1i31a_.ent", "d1bg1a2.ent-d1ikna2.ent", "d1bg1a2.ent-d1imhc2.ent", "d1bg1a2.ent-d1klfb1.ent", "d1bg1a2.ent-d1klfb2.ent", "d1bg1a2.ent-d1m2oa2.ent", "d1bg1a2.ent-d1m2vb2.ent", "d1bg1a2.ent-d1mnna_.ent", "d1bg1a2.ent-d1nbca_.ent", "d1bg1a2.ent-d1pdkb_.ent", "d1bg1a2.ent-d1qba_2.ent", "d1bg1a2.ent-d1tf4a2.ent", "d1bg1a2.ent-d1ycsa_.ent", "d1bg2__.ent-d1e2ka_.ent", "d1bg2__.ent-d1f9va_.ent", "d1bg2__.ent-d1g8pa_.ent", "d1bg2__.ent-d1ksfx3.ent", "d1bg2__.ent-d1n0ua2.ent", "d1bg2__.ent-d1pjr_1.ent", "d1bg2__.ent-d1pjr_2.ent", "d1bg2__.ent-d1uaaa1.ent", "d1bg6_1.ent-d1dlja1.ent", "d1bg6_1.ent-d1f0ya1.ent", "d1bg6_1.ent-d1i36a1.ent", "d1bg6_1.ent-d1ks9a1.ent", "d1bg6_1.ent-d1m66a1.ent", "d1bg6_1.ent-d1pgja1.ent", "d1bg6_1.ent-d1qmga1.ent", "d1bg6_1.ent-d2pgd_1.ent", "d1bg6_2.ent-d1cf2o1.ent", "d1bg6_2.ent-d1dssg1.ent", "d1bg6_2.ent-d1e5qa1.ent", "d1bg6_2.ent-d1lc0a1.ent", "d1bg6_2.ent-d2pgd_2.ent", "d1bgc__.ent-d1cnt1_.ent", "d1bgc__.ent-d1d9ca_.ent", "d1bgc__.ent-d1eera_.ent", "d1bgc__.ent-d1etea_.ent", "d1bgc__.ent-d1evsa_.ent", "d1bgc__.ent-d1f45b_.ent", "d1bgc__.ent-d1f6fa_.ent", "d1bgc__.ent-d1hula_.ent", "d1bgc__.ent-d1huw__.ent", "d1bgc__.ent-d1hzia_.ent", "d1bgc__.ent-d1i1rb_.ent", "d1bgc__.ent-d1jli__.ent", "d1bgc__.ent-d1lki__.ent", "d1bgc__.ent-d1lqsl_.ent", "d1bgc__.ent-d1m47a_.ent", "d1bgc__.ent-d1n1fa_.ent", "d1bgc__.ent-d2gmfa_.ent", "d1bgc__.ent-d2ilk__.ent", "d1bgp__.ent-d1cvua1.ent", "d1bgp__.ent-d1itka1.ent", "d1bgp__.ent-d1itka2.ent", "d1bgp__.ent-d1jdra_.ent", "d1bgp__.ent-d1llp__.ent", "d1bgp__.ent-d1mn2__.ent", "d1bgp__.ent-d1pa2a_.ent", "d1bgva1.ent-d1bg6_2.ent", "d1bgva1.ent-d1c1da1.ent", "d1bgva1.ent-d1cf2o1.ent", "d1bgva1.ent-d1dlja2.ent", "d1bgva1.ent-d1dpga1.ent", "d1bgva1.ent-d1dssg1.ent", "d1bgva1.ent-d1e5qa1.ent", "d1bgva1.ent-d1f0ya2.ent", "d1bgva1.ent-d1gr0a1.ent", "d1bgva1.ent-d1hdoa_.ent", "d1bgva1.ent-d1hdr__.ent", "d1bgva1.ent-d1hxha_.ent", "d1bgva1.ent-d1jaya_.ent", "d1bgva1.ent-d1lc0a1.ent", "d1bgva1.ent-d1lu9a1.ent", "d1bgva1.ent-d1qmga2.ent", "d1bgva1.ent-d2naca1.ent", "d1bgva1.ent-d2pgd_2.ent", "d1bgva2.ent-d1c1da2.ent", "d1bgva2.ent-d1edza2.ent", "d1bgva2.ent-d1gtma2.ent", "d1bgva2.ent-d1hwxa2.ent", "d1bgva2.ent-d1leha2.ent", "d1bgva2.ent-d1lu9a2.ent", "d1bgxt1.ent-d1bpya1.ent", "d1bgxt1.ent-d1cuk_2.ent", "d1bgxt1.ent-d1d8ba_.ent", "d1bgxt1.ent-d1dgsa1.ent", "d1bgxt1.ent-d1doqa_.ent", "d1bgxt1.ent-d1dxsa_.ent", "d1bgxt1.ent-d1f44a1.ent", "d1bgxt1.ent-d1floa1.ent", "d1bgxt1.ent-d1go3f_.ent", "d1bgxt1.ent-d1jmsa1.ent", "d1bgxt1.ent-d1jmsa3.ent", "d1bgxt1.ent-d1jyga_.ent", "d1bgxt1.ent-d1kfta_.ent", "d1bgxt1.ent-d1lb2b_.ent", "d1bgxt1.ent-d1tfr_1.ent", "d1bgxt1.ent-d1xo1a1.ent", "d1bgxt2.ent-d1tfr_2.ent", "d1bgxt2.ent-d1xo1a2.ent", "d1bgxt2.ent-d2rsla_.ent", "d1bh9a_.ent-d1bh9b_.ent", "d1bh9a_.ent-d1jfia_.ent", "d1bh9a_.ent-d1jfib_.ent", "d1bh9a_.ent-d1kx5a_.ent", "d1bh9a_.ent-d1kx5b_.ent", "d1bh9a_.ent-d1kx5c_.ent", "d1bh9a_.ent-d1kx5d_.ent", "d1bh9a_.ent-d1n1ja_.ent", "d1bh9a_.ent-d1n1jb_.ent", "d1bh9b_.ent-d1jfia_.ent", "d1bh9b_.ent-d1jfib_.ent", "d1bh9b_.ent-d1kx5a_.ent", "d1bh9b_.ent-d1kx5b_.ent", "d1bh9b_.ent-d1kx5c_.ent", "d1bh9b_.ent-d1kx5d_.ent", "d1bh9b_.ent-d1n1ja_.ent", "d1bh9b_.ent-d1n1jb_.ent", "d1bhda_.ent-d1bkra_.ent", "d1bhda_.ent-d1dxxa1.ent", "d1bhda_.ent-d1h67a_.ent", "d1bhe__.ent-d1bn8a_.ent", "d1bhe__.ent-d1czfa_.ent", "d1bhe__.ent-d1daba_.ent", "d1bhe__.ent-d1dbga_.ent", "d1bhe__.ent-d1ee6a_.ent", "d1bhe__.ent-d1hg8a_.ent", "d1bhe__.ent-d1jtaa_.ent", "d1bhe__.ent-d1k5ca_.ent", "d1bhe__.ent-d1qcxa_.ent", "d1bhe__.ent-d1qjva_.ent", "d1bhe__.ent-d1qq1a_.ent", "d1bhe__.ent-d1rmg__.ent", "d1bhga1.ent-d1jz8a1.ent", "d1bhga1.ent-d1jz8a2.ent", "d1bhga2.ent-d1ciy_1.ent", "d1bhga2.ent-d1cx1a_.ent", "d1bhga2.ent-d1czsa_.ent", "d1bhga2.ent-d1d7pm_.ent", "d1bhga2.ent-d1dlc_1.ent", "d1bhga2.ent-d1eut_2.ent", "d1bhga2.ent-d1gmma_.ent", "d1bhga2.ent-d1gnya_.ent", "d1bhga2.ent-d1gqpa_.ent", "d1bhga2.ent-d1gu3a_.ent", "d1bhga2.ent-d1guia_.ent", "d1bhga2.ent-d1h6ya_.ent", "d1bhga2.ent-d1i5pa1.ent", "d1bhga2.ent-d1jhja_.ent", "d1bhga2.ent-d1ji6a1.ent", "d1bhga2.ent-d1ju3a1.ent", "d1bhga2.ent-d1jz8a3.ent", "d1bhga2.ent-d1k12a_.ent", "d1bhga2.ent-d1k3ia2.ent", "d1bhga2.ent-d1k42a_.ent", "d1bhga2.ent-d1kexa_.ent", "d1bhga2.ent-d1kgya_.ent", "d1bhga2.ent-d1l7la_.ent", "d1bhga2.ent-d1lnsa2.ent", "d1bhga2.ent-d1xnaa_.ent", "d1bhi__.ent-d1fu9a_.ent", "d1bhi__.ent-d1fv5a_.ent", "d1bhi__.ent-d1ncs__.ent", "d1bhi__.ent-d1paa__.ent", "d1bhi__.ent-d1rmd_1.ent", "d1bhi__.ent-d1tf3a1.ent", "d1bhi__.ent-d1tf3a2.ent", "d1bhi__.ent-d1tf3a3.ent", "d1bhi__.ent-d1tf6a4.ent", "d1bhi__.ent-d1ubdc3.ent", "d1bhi__.ent-d1yuja_.ent", "d1bhi__.ent-d1zfd__.ent", "d1bhi__.ent-d2drpa1.ent", "d1bhi__.ent-d2glia1.ent", "d1bhi__.ent-d2glia2.ent", "d1bhi__.ent-d2glia4.ent", "d1bhi__.ent-d5znf__.ent", "d1bhta1.ent-d1hkya_.ent", "d1bhta1.ent-d1i8na_.ent", "d1bhta2.ent-d1h8pa1.ent", "d1bhta2.ent-d1h8pa2.ent", "d1bhta2.ent-d1i71a_.ent", "d1bhta2.ent-d1kdu__.ent", "d1bhta2.ent-d1ki0a2.ent", "d1bhta2.ent-d1ki0a3.ent", "d1bhta2.ent-d1l6ja3.ent", "d1bhta2.ent-d1l6ja5.ent", "d1bhta2.ent-d1pmla_.ent", "d1bhta2.ent-d2hpqp_.ent", "d1bhta2.ent-d5hpga_.ent", "d1bhu__.ent-d1c01a_.ent", "d1bhu__.ent-d1f53a_.ent", "d1bhu__.ent-d1g6ea_.ent", "d1bhu__.ent-d2bb2_1.ent", "d1bhu__.ent-d2bb2_2.ent", "d1bi5a2.ent-d1e5ma1.ent", "d1bi5a2.ent-d1e5ma2.ent", "d1bi5a2.ent-d1ek4a1.ent", "d1bi5a2.ent-d1ek4a2.ent", "d1bi5a2.ent-d1hnja1.ent", "d1bi5a2.ent-d1hnja2.ent", "d1bi5a2.ent-d1hzpa1.ent", "d1bi5a2.ent-d1hzpa2.ent", "d1bi5a2.ent-d1kas_1.ent", "d1bi5a2.ent-d1m3ka1.ent", "d1bi5a2.ent-d1m3ka2.ent", "d1bi5a2.ent-d1mzja1.ent", "d1bi5a2.ent-d1mzja2.ent", "d1bi7b_.ent-d1dcqa1.ent", "d1bi7b_.ent-d1ihba_.ent", "d1bi7b_.ent-d1k1aa_.ent", "d1bi7b_.ent-d1k3zd_.ent", "d1bi7b_.ent-d1myo__.ent", "d1bi7b_.ent-d1n11a_.ent", "d1bi7b_.ent-d1sw6a_.ent", "d1bi7b_.ent-d1ycsb1.ent", "d1bia_2.ent-d1fx7a3.ent", "d1bia_2.ent-d1g3sa3.ent", "d1bia_2.ent-d1igqa_.ent", "d1bia_3.ent-d1e1oa2.ent", "d1bia_3.ent-d1eova2.ent", "d1bia_3.ent-d1g51a3.ent", "d1bia_3.ent-d1h4vb2.ent", "d1bia_3.ent-d1hc7a2.ent", "d1bia_3.ent-d1jjca_.ent", "d1bia_3.ent-d1jjcb5.ent", "d1bia_3.ent-d1kmma2.ent", "d1bia_3.ent-d1qe0a2.ent", "d1bia_3.ent-d1qf6a4.ent", "d1bia_3.ent-d1seta2.ent", "d1bif_2.ent-d1dkla_.ent", "d1bif_2.ent-d1e58a_.ent", "d1bif_2.ent-d1fzta_.ent", "d1bif_2.ent-d1h2ea_.ent", "d1bif_2.ent-d1ihp__.ent", "d1bif_2.ent-d1nd6a_.ent", "d1bif_2.ent-d1qfxa_.ent", "d1bif_2.ent-d3pgm__.ent", "d1bik_1.ent-d1bik_2.ent", "d1bik_1.ent-d1bunb_.ent", "d1bik_1.ent-d1d0da_.ent", "d1bik_1.ent-d1g6xa_.ent", "d1bik_1.ent-d1irha_.ent", "d1bik_1.ent-d1ktha_.ent", "d1bik_1.ent-d1tfxc_.ent", "d1bik_1.ent-d1tocr1.ent", "d1bik_1.ent-d1tocr2.ent", "d1bik_2.ent-d1bunb_.ent", "d1bik_2.ent-d1d0da_.ent", "d1bik_2.ent-d1g6xa_.ent", "d1bik_2.ent-d1irha_.ent", "d1bik_2.ent-d1ktha_.ent", "d1bik_2.ent-d1tfxc_.ent", "d1bik_2.ent-d1tocr1.ent", "d1bik_2.ent-d1tocr2.ent", "d1bio__.ent-d1azza_.ent", "d1bio__.ent-d1cgha_.ent", "d1bio__.ent-d1gdna_.ent", "d1bio__.ent-d1hj9a_.ent", "d1bj4a_.ent-d1ajsa_.ent", "d1bj4a_.ent-d1b9ha_.ent", "d1bj4a_.ent-d1bs0a_.ent", "d1bj4a_.ent-d1c4ka2.ent", "d1bj4a_.ent-d1c7na_.ent", "d1bj4a_.ent-d1e5ea_.ent", "d1bj4a_.ent-d1gdea_.ent", "d1bj4a_.ent-d1gtxa_.ent", "d1bj4a_.ent-d1j32a_.ent", "d1bj4a_.ent-d1jf9a_.ent", "d1bj4a_.ent-d1js3a_.ent", "d1bj4a_.ent-d1kl1a_.ent", "d1bj4a_.ent-d1m7ya_.ent", "d1bj4a_.ent-d1n8pa_.ent", "d1bj4a_.ent-d1qisa_.ent", "d1bj4a_.ent-d1qj5a_.ent", "d1bj4a_.ent-d1tpla_.ent", "d1bj4a_.ent-d1yaaa_.ent", "d1bj4a_.ent-d2ay1a_.ent", "d1bj4a_.ent-d2dkb__.ent", "d1bj4a_.ent-d2gsaa_.ent", "d1bj4a_.ent-d2oata_.ent", "d1bj4a_.ent-d3tata_.ent", "d1bj4a_.ent-d7aata_.ent", "d1bj7__.ent-d1cbs__.ent", "d1bj7__.ent-d1dzka_.ent", "d1bj7__.ent-d1euoa_.ent", "d1bj7__.ent-d1ew3a_.ent", "d1bj7__.ent-d1ftpa_.ent", "d1bj7__.ent-d1g85a_.ent", "d1bj7__.ent-d1ggla_.ent", "d1bj7__.ent-d1gkab_.ent", "d1bj7__.ent-d1hms__.ent", "d1bj7__.ent-d1i4ua_.ent", "d1bj7__.ent-d1ifc__.ent", "d1bj7__.ent-d1jv4a_.ent", "d1bj7__.ent-d1koia_.ent", "d1bj7__.ent-d1kqwa_.ent", "d1bj7__.ent-d1lf7a_.ent", "d1bj7__.ent-d1o1va_.ent", "d1bj7__.ent-d1qfta_.ent", "d1bj7__.ent-d1qqsa_.ent", "d1bjaa_.ent-d1d5va_.ent", "d1bjaa_.ent-d1e17a_.ent", "d1bjaa_.ent-d1fsha_.ent", "d1bjaa_.ent-d1ldja1.ent", "d1bjaa_.ent-d2foka3.ent", "d1bjx__.ent-d1a8l_2.ent", "d1bjx__.ent-d1erv__.ent", "d1bjx__.ent-d1fb6a_.ent", "d1bjx__.ent-d1gh2a_.ent", "d1bjx__.ent-d1kte__.ent", "d1bjx__.ent-d1quwa_.ent", "d1bjx__.ent-d1thx__.ent", "d1bjx__.ent-d2trxa_.ent", "d1bk7a_.ent-d1bola_.ent", "d1bk7a_.ent-d1dixa_.ent", "d1bk7a_.ent-d1iooa_.ent", "d1bk7a_.ent-d1iqqa_.ent", "d1bk7a_.ent-d1jy5a_.ent", "d1bkca_.ent-d1bqba_.ent", "d1bkca_.ent-d1buda_.ent", "d1bkca_.ent-d1c7ka_.ent", "d1bkca_.ent-d1dmta_.ent", "d1bkca_.ent-d1eb6a_.ent", "d1bkca_.ent-d1epwa3.ent", "d1bkca_.ent-d1ezm__.ent", "d1bkca_.ent-d1g12a_.ent", "d1bkca_.ent-d1gkda_.ent", "d1bkca_.ent-d1hs6a3.ent", "d1bkca_.ent-d1i1ip_.ent", "d1bkca_.ent-d1j7na1.ent", "d1bkca_.ent-d1j7na2.ent", "d1bkca_.ent-d1jk3a_.ent", "d1bkca_.ent-d1k7ia2.ent", "d1bkca_.ent-d1k9xa_.ent", "d1bkca_.ent-d1kapp2.ent", "d1bkca_.ent-d1keia_.ent", "d1bkca_.ent-d1kufa_.ent", "d1bkca_.ent-d1lml__.ent", "d1bkca_.ent-d3btaa3.ent", "d1bkf__.ent-d1edqa3.ent", "d1bkf__.ent-d1eq3a_.ent", "d1bkf__.ent-d1fd9a_.ent", "d1bkf__.ent-d1grj_2.ent", "d1bkf__.ent-d1hxva_.ent", "d1bkf__.ent-d1itxa2.ent", "d1bkf__.ent-d1j6ya_.ent", "d1bkf__.ent-d1jnda2.ent", "d1bkf__.ent-d1jvwa_.ent", "d1bkf__.ent-d1kt1a3.ent", "d1bkf__.ent-d1lg2a2.ent", "d1bkf__.ent-d1ll7a2.ent", "d1bkf__.ent-d1m5ya2.ent", "d1bkf__.ent-d1m5ya3.ent", "d1bkf__.ent-d1n1aa_.ent", "d1bkf__.ent-d1pbk__.ent", "d1bkf__.ent-d1pina2.ent", "d1bkf__.ent-d3eipa_.ent", "d1bkpa_.ent-d1f28a_.ent", "d1bkpa_.ent-d1tis__.ent", "d1bkra_.ent-d1dxxa1.ent", "d1bkra_.ent-d1h67a_.ent", "d1bkra_.ent-d1lnsa1.ent", "d1bl0a2.ent-d1e3oc1.ent", "d1bl0a2.ent-d1fexa_.ent", "d1bl0a2.ent-d1g2ha_.ent", "d1bl0a2.ent-d1ig7a_.ent", "d1bl0a2.ent-d1k61a_.ent", "d1bl0a2.ent-d1k78a2.ent", "d1blu__.ent-d1feha3.ent", "d1blu__.ent-d1fxd__.ent", "d1blu__.ent-d1fxra_.ent", "d1blu__.ent-d1gtea5.ent", "d1blu__.ent-d1h0hb_.ent", "d1blu__.ent-d1h98a_.ent", "d1blu__.ent-d1hfel2.ent", "d1blu__.ent-d1iqza_.ent", "d1blu__.ent-d1jb0c_.ent", "d1blu__.ent-d1jnrb_.ent", "d1blu__.ent-d1keka5.ent", "d1blu__.ent-d1kqfb1.ent", "d1blu__.ent-d2fdn__.ent", "d1blu__.ent-d7fd1a_.ent", "d1blxa_.ent-d1a06__.ent", "d1blxa_.ent-d1csn__.ent", "d1blxa_.ent-d1f3mc_.ent", "d1blxa_.ent-d1fgka_.ent", "d1blxa_.ent-d1fvra_.ent", "d1blxa_.ent-d1ia9a_.ent", "d1blxa_.ent-d1iepa_.ent", "d1blxa_.ent-d1jksa_.ent", "d1blxa_.ent-d1jpaa_.ent", "d1blxa_.ent-d1jvpp_.ent", "d1blxa_.ent-d1lufa_.ent", "d1blxa_.ent-d1phk__.ent", "d1bm9a_.ent-d1bjaa_.ent", "d1bm9a_.ent-d1d5va_.ent", "d1bm9a_.ent-d1e17a_.ent", "d1bm9a_.ent-d1f1za1.ent", "d1bm9a_.ent-d1fc3a_.ent", "d1bm9a_.ent-d1fnna1.ent", "d1bm9a_.ent-d1fp1d1.ent", "d1bm9a_.ent-d1fp2a1.ent", "d1bm9a_.ent-d1fsha_.ent", "d1bm9a_.ent-d1fzpb_.ent", "d1bm9a_.ent-d1hks__.ent", "d1bm9a_.ent-d1hsja1.ent", "d1bm9a_.ent-d1ig6a_.ent", "d1bm9a_.ent-d1igna2.ent", "d1bm9a_.ent-d1jhga_.ent", "d1bm9a_.ent-d1ka8a_.ent", "d1bm9a_.ent-d1ldja1.ent", "d1bm9a_.ent-d1opc__.ent", "d1bm9a_.ent-d1repc1.ent", "d1bm9a_.ent-d1repc2.ent", "d1bm9a_.ent-d1smta_.ent", "d1bm9a_.ent-d2ezl__.ent", "d1bm9a_.ent-d2foka3.ent", "d1bm9a_.ent-d2irfg_.ent", "d1bmlc3.ent-d1c9fa_.ent", "d1bmlc3.ent-d1fm0d_.ent", "d1bmlc3.ent-d1h4ra3.ent", "d1bmlc3.ent-d1h8ca_.ent", "d1bmlc3.ent-d1ip9a_.ent", "d1bmlc3.ent-d1k8rb_.ent", "d1bmlc3.ent-d1l4db_.ent", "d1bmlc3.ent-d1lfda_.ent", "d1bmlc3.ent-d1qqra_.ent", "d1bmlc3.ent-d2sak__.ent", "d1bmr__.ent-d1c55a_.ent", "d1bmr__.ent-d1cmr__.ent", "d1bmr__.ent-d1fjna_.ent", "d1bmr__.ent-d1gps__.ent", "d1bmr__.ent-d1i2ua_.ent", "d1bmr__.ent-d1ica__.ent", "d1bmr__.ent-d1jkza_.ent", "d1bmr__.ent-d1jxca_.ent", "d1bmr__.ent-d1myn__.ent", "d1bmr__.ent-d1npia_.ent", "d1bmr__.ent-d1nrb__.ent", "d1bmr__.ent-d1qkya_.ent", "d1bmr__.ent-d1sco__.ent", "d1bmr__.ent-d1scy__.ent", "d1bmr__.ent-d1sis__.ent", "d1bmr__.ent-d1tsk__.ent", "d1bmr__.ent-d2sn3__.ent", "d1bmta1.ent-d1brwa1.ent", "d1bmta1.ent-d1khda1.ent", "d1bmta2.ent-d1ccwa_.ent", "d1bmta2.ent-d7reqa2.ent", "d1bmta2.ent-d7reqb2.ent", "d1bmv1_.ent-d1a6ca1.ent", "d1bmv1_.ent-d1a6ca2.ent", "d1bmv1_.ent-d1a6ca3.ent", "d1bmv1_.ent-d1cwpa_.ent", "d1bmv1_.ent-d1f15a_.ent", "d1bmv1_.ent-d2bpa2_.ent", "d1bmv1_.ent-d2stv__.ent", "d1bmv2_.ent-d1a6ca1.ent", "d1bmv2_.ent-d1a6ca2.ent", "d1bmv2_.ent-d1a6ca3.ent", "d1bmv2_.ent-d1aym1_.ent", "d1bmv2_.ent-d1aym2_.ent", "d1bmv2_.ent-d1b35a_.ent", "d1bmv2_.ent-d1b35b_.ent", "d1bmv2_.ent-d1b35c_.ent", "d1bmv2_.ent-d1bev1_.ent", "d1bmv2_.ent-d1bev3_.ent", "d1bmv2_.ent-d1bmv1_.ent", "d1bmv2_.ent-d1c8na_.ent", "d1bmv2_.ent-d1cwpa_.ent", "d1bmv2_.ent-d1d4m1_.ent", "d1bmv2_.ent-d1ddla_.ent", "d1bmv2_.ent-d1f15a_.ent", "d1bmv2_.ent-d1k5ma_.ent", "d1bmv2_.ent-d1novc_.ent", "d1bmv2_.ent-d1pov0_.ent", "d1bmv2_.ent-d1pvc1_.ent", "d1bmv2_.ent-d1qqp1_.ent", "d1bmv2_.ent-d1qqp2_.ent", "d1bmv2_.ent-d1qqp3_.ent", "d1bmv2_.ent-d1sva1_.ent", "d1bmv2_.ent-d1tmf1_.ent", "d1bmv2_.ent-d1vpsa_.ent", "d1bmv2_.ent-d2bbva_.ent", "d1bmv2_.ent-d2bpa2_.ent", "d1bmv2_.ent-d2mev1_.ent", "d1bmv2_.ent-d2mev2_.ent", "d1bmv2_.ent-d2stv__.ent", "d1bn8a_.ent-d1czfa_.ent", "d1bn8a_.ent-d1daba_.ent", "d1bn8a_.ent-d1dbga_.ent", "d1bn8a_.ent-d1ee6a_.ent", "d1bn8a_.ent-d1hg8a_.ent", "d1bn8a_.ent-d1jtaa_.ent", "d1bn8a_.ent-d1k5ca_.ent", "d1bn8a_.ent-d1qcxa_.ent", "d1bn8a_.ent-d1qjva_.ent", "d1bn8a_.ent-d1qq1a_.ent", "d1bn8a_.ent-d1rmg__.ent", "d1bnb__.ent-d1d6ba_.ent", "d1bnb__.ent-d1dfna_.ent", "d1bnb__.ent-d1e4ta_.ent", "d1bnb__.ent-d1ewsa_.ent", "d1bnb__.ent-d1fd3a_.ent", "d1bnb__.ent-d1ijva_.ent", "d1bnb__.ent-d1kj6a_.ent", "d1bnb__.ent-d1sh1__.ent", "d1bnb__.ent-d2bds__.ent", "d1bnda_.ent-d1fl7b_.ent", "d1bnda_.ent-d1fltv_.ent", "d1bnda_.ent-d1hcna_.ent", "d1bnda_.ent-d1hcnb_.ent", "d1bnda_.ent-d1jpya_.ent", "d1bnda_.ent-d1m4ua_.ent", "d1bnda_.ent-d1m4ul_.ent", "d1bnda_.ent-d1pdga_.ent", "d1bnda_.ent-d2tgi__.ent", "d1bo9a_.ent-d1dk5a_.ent", "d1bo9a_.ent-d1dm5a_.ent", "d1bo9a_.ent-d1g5na_.ent", "d1bo9a_.ent-d1hm6a_.ent", "d1bob__.ent-d1cjwa_.ent", "d1bob__.ent-d1fy7a_.ent", "d1bob__.ent-d1i12a_.ent", "d1bob__.ent-d1iica2.ent", "d1bob__.ent-d1iyka1.ent", "d1bob__.ent-d1iyka2.ent", "d1bob__.ent-d1kzfa_.ent", "d1bob__.ent-d1lrza2.ent", "d1bob__.ent-d1lrza3.ent", "d1bob__.ent-d1m4ia_.ent", "d1bob__.ent-d1qsma_.ent", "d1bob__.ent-d1qsta_.ent", "d1bola_.ent-d1dixa_.ent", "d1bola_.ent-d1iooa_.ent", "d1bola_.ent-d1iqqa_.ent", "d1bola_.ent-d1jy5a_.ent", "d1booa_.ent-d1eg2a_.ent", "d1booa_.ent-d1fp1d2.ent", "d1booa_.ent-d1fp2a2.ent", "d1booa_.ent-d1g60a_.ent", "d1booa_.ent-d1hnna_.ent", "d1booa_.ent-d1i1na_.ent", "d1booa_.ent-d1i9ga_.ent", "d1booa_.ent-d1iy9a_.ent", "d1booa_.ent-d1jg1a_.ent", "d1booa_.ent-d1jqea_.ent", "d1booa_.ent-d1kywa2.ent", "d1booa_.ent-d1mjfa_.ent", "d1booa_.ent-d1qama_.ent", "d1booa_.ent-d1yub__.ent", "d1booa_.ent-d2dpma_.ent", "d1bor__.ent-d1chc__.ent", "d1bor__.ent-d1e4ua_.ent", "d1bor__.ent-d1fbva4.ent", "d1bor__.ent-d1g25a_.ent", "d1bor__.ent-d1jm7a_.ent", "d1bor__.ent-d1jm7b_.ent", "d1bor__.ent-d1ldjb_.ent", "d1bor__.ent-d1rmd_2.ent", "d1boub_.ent-d1c8ba_.ent", "d1boub_.ent-d1cfza_.ent", "d1boub_.ent-d1je0a_.ent", "d1boub_.ent-d1lam_2.ent", "d1boub_.ent-d1lfwa1.ent", "d1boub_.ent-d1loka_.ent", "d1boub_.ent-d1m4la_.ent", "d1boub_.ent-d2pth__.ent", "d1bowa_.ent-d1d5ya3.ent", "d1bowa_.ent-d1jyha_.ent", "d1bpoa1.ent-d1e8xa1.ent", "d1bpoa1.ent-d1ee4a_.ent", "d1bpoa1.ent-d1h6ka1.ent", "d1bpoa1.ent-d1h6ka2.ent", "d1bpoa1.ent-d1h6ka3.ent", "d1bpoa1.ent-d1ho8a_.ent", "d1bpoa1.ent-d1hs6a1.ent", "d1bpoa1.ent-d1iala_.ent", "d1bpoa1.ent-d1jdha_.ent", "d1bpoa1.ent-d1kx9a_.ent", "d1bpoa1.ent-d1lrv__.ent", "d1bpoa1.ent-d1n4ka1.ent", "d1bpv__.ent-d1cd9b2.ent", "d1bpv__.ent-d1cfb_1.ent", "d1bpv__.ent-d1eerb2.ent", "d1bpv__.ent-d1egja_.ent", "d1bpv__.ent-d1f6fb1.ent", "d1bpv__.ent-d1f6fb2.ent", "d1bpv__.ent-d1fyhb1.ent", "d1bpv__.ent-d1fyhb2.ent", "d1bpv__.ent-d1gh7a1.ent", "d1bpv__.ent-d1i1ra1.ent", "d1bpv__.ent-d1lqsr1.ent", "d1bpv__.ent-d1n26a2.ent", "d1bpv__.ent-d1n26a3.ent", "d1bpv__.ent-d1qg3a2.ent", "d1bpv__.ent-d2hft_1.ent", "d1bpv__.ent-d2hft_2.ent", "d1bpya1.ent-d1cuk_2.ent", "d1bpya1.ent-d1d8ba_.ent", "d1bpya1.ent-d1dgsa1.ent", "d1bpya1.ent-d1doqa_.ent", "d1bpya1.ent-d1dxsa_.ent", "d1bpya1.ent-d1f44a1.ent", "d1bpya1.ent-d1floa1.ent", "d1bpya1.ent-d1go3f_.ent", "d1bpya1.ent-d1jmsa1.ent", "d1bpya1.ent-d1jmsa3.ent", "d1bpya1.ent-d1jyga_.ent", "d1bpya1.ent-d1kfta_.ent", "d1bpya1.ent-d1lb2b_.ent", "d1bpya1.ent-d1tfr_1.ent", "d1bqba_.ent-d1buda_.ent", "d1bqba_.ent-d1c7ka_.ent", "d1bqba_.ent-d1dmta_.ent", "d1bqba_.ent-d1eb6a_.ent", "d1bqba_.ent-d1epwa3.ent", "d1bqba_.ent-d1ezm__.ent", "d1bqba_.ent-d1g12a_.ent", "d1bqba_.ent-d1gkda_.ent", "d1bqba_.ent-d1hs6a3.ent", "d1bqba_.ent-d1i1ip_.ent", "d1bqba_.ent-d1j7na1.ent", "d1bqba_.ent-d1j7na2.ent", "d1bqba_.ent-d1jk3a_.ent", "d1bqba_.ent-d1k7ia2.ent", "d1bqba_.ent-d1k9xa_.ent", "d1bqba_.ent-d1kapp2.ent", "d1bqba_.ent-d1keia_.ent", "d1bqba_.ent-d1kufa_.ent", "d1bqba_.ent-d1lml__.ent", "d1bqba_.ent-d3btaa3.ent", "d1bqhg_.ent-d1a2yb_.ent", "d1bqhg_.ent-d1akjd_.ent", "d1bqhg_.ent-d1b88a_.ent", "d1bqhg_.ent-d1bec_1.ent", "d1bqhg_.ent-d1c5ch1.ent", "d1bqhg_.ent-d1dlfh_.ent", "d1bqhg_.ent-d1dlfl_.ent", "d1bqhg_.ent-d1dqta_.ent", "d1bqhg_.ent-d1fo0a_.ent", "d1bqhg_.ent-d1gsma2.ent", "d1bqhg_.ent-d1h5ba_.ent", "d1bqhg_.ent-d1hxma1.ent", "d1bqhg_.ent-d1ktke1.ent", "d1bqhg_.ent-d1kxvc_.ent", "d1bqhg_.ent-d1neu__.ent", "d1bqhg_.ent-d1nfdb1.ent", "d1bqhg_.ent-d1qfoa_.ent", "d1bqhg_.ent-d1tvda_.ent", "d1bqhg_.ent-d2rhe__.ent", "d1bqua2.ent-d1axib2.ent", "d1bqua2.ent-d1bpv__.ent", "d1bqua2.ent-d1cd9b1.ent", "d1bqua2.ent-d1cd9b2.ent", "d1bqua2.ent-d1cfb_1.ent", "d1bqua2.ent-d1cfb_2.ent", "d1bqua2.ent-d1eerb1.ent", "d1bqua2.ent-d1eerb2.ent", "d1bqua2.ent-d1egja_.ent", "d1bqua2.ent-d1f6fb1.ent", "d1bqua2.ent-d1f6fb2.ent", "d1bqua2.ent-d1fyhb1.ent", "d1bqua2.ent-d1fyhb2.ent", "d1bqua2.ent-d1gh7a1.ent", "d1bqua2.ent-d1i1ra1.ent", "d1bqua2.ent-d1lqsr1.ent", "d1bqua2.ent-d1lqsr2.ent", "d1bqua2.ent-d1n26a2.ent", "d1bqua2.ent-d1n26a3.ent", "d1bqua2.ent-d1qg3a2.ent", "d1bqua2.ent-d2hft_1.ent", "d1bqua2.ent-d2hft_2.ent", "d1bqv__.ent-d1dxsa_.ent", "d1bqya_.ent-d1azza_.ent", "d1bqya_.ent-d1bio__.ent", "d1bqya_.ent-d1cgha_.ent", "d1bqya_.ent-d1fjsa_.ent", "d1bqya_.ent-d1gdna_.ent", "d1bqya_.ent-d1gpza1.ent", "d1bqya_.ent-d1hj9a_.ent", "d1bqya_.ent-d2hlca_.ent", "d1br2a1.ent-d1kk8a1.ent", "d1br2a1.ent-d1lvk_1.ent", "d1br2a2.ent-d1bg2__.ent", "d1br2a2.ent-d1c4oa1.ent", "d1br2a2.ent-d1dj3a_.ent", "d1br2a2.ent-d1e2ka_.ent", "d1br2a2.ent-d1e9ra_.ent", "d1br2a2.ent-d1eg7a_.ent", "d1br2a2.ent-d1f9va_.ent", "d1br2a2.ent-d1fmja_.ent", "d1br2a2.ent-d1g41a_.ent", "d1br2a2.ent-d1g8pa_.ent", "d1br2a2.ent-d1i6ia_.ent", "d1br2a2.ent-d1ii6a_.ent", "d1br2a2.ent-d1iwea_.ent", "d1br2a2.ent-d1ksfx3.ent", "d1br2a2.ent-d1n0ua2.ent", "d1br2a2.ent-d1pjr_1.ent", "d1br2a2.ent-d1pjr_2.ent", "d1br2a2.ent-d1qf5a_.ent", "d1br2a2.ent-d1uaaa1.ent", "d1br2a2.ent-d1uaaa2.ent", "d1br2a2.ent-d2ncda_.ent", "d1br9__.ent-d1b3qa2.ent", "d1br9__.ent-d1e1oa1.ent", "d1br9__.ent-d1eova1.ent", "d1br9__.ent-d1fgua2.ent", "d1br9__.ent-d1fjgl_.ent", "d1br9__.ent-d1fl0a_.ent", "d1br9__.ent-d1gm5a2.ent", "d1br9__.ent-d1go3e_.ent", "d1br9__.ent-d1i40a_.ent", "d1br9__.ent-d1i50h_.ent", "d1br9__.ent-d1iyjb5.ent", "d1br9__.ent-d1jb3a_.ent", "d1br9__.ent-d1jb7a1.ent", "d1br9__.ent-d1jb7a2.ent", "d1br9__.ent-d1jb7a3.ent", "d1br9__.ent-d1je5a_.ent", "d1br9__.ent-d1k28a1.ent", "d1br9__.ent-d1l1oc_.ent", "d1br9__.ent-d1quqa_.ent", "d1br9__.ent-d1sty__.ent", "d1br9__.ent-d1ueab_.ent", "d1br9__.ent-d3seb_1.ent", "d1brwa1.ent-d1khda1.ent", "d1brwa1.ent-d1o17a1.ent", "d1brwa1.ent-d2tpt_1.ent", "d1brwa2.ent-d1khda2.ent", "d1brwa2.ent-d1o17a2.ent", "d1brwa2.ent-d2tpt_2.ent", "d1brwa3.ent-d1fm0e_.ent", "d1brwa3.ent-d1jj2h_.ent", "d1brwa3.ent-d1n62b1.ent", "d1brwa3.ent-d1qpoa2.ent", "d1bs0a_.ent-d1c4ka2.ent", "d1bs0a_.ent-d1elua_.ent", "d1bs0a_.ent-d1js3a_.ent", "d1bs0a_.ent-d1kl1a_.ent", "d1bs0a_.ent-d1lc5a_.ent", "d1bs0a_.ent-d1qj5a_.ent", "d1bsg__.ent-d1buea_.ent", "d1bsg__.ent-d1ci9a_.ent", "d1bsg__.ent-d1e25a_.ent", "d1bsg__.ent-d1ei5a3.ent", "d1bsg__.ent-d1es5a_.ent", "d1bsg__.ent-d1g6aa_.ent", "d1bsg__.ent-d1ghpa_.ent", "d1bsg__.ent-d1iyoa_.ent", "d1bsg__.ent-d1l0ga_.ent", "d1bsg__.ent-d1m40a_.ent", "d1bsg__.ent-d1mfoa_.ent", "d1bsg__.ent-d1mwxa3.ent", "d1bsg__.ent-d1nj4a2.ent", "d1bsg__.ent-d1qmea4.ent", "d1bsg__.ent-d4blma_.ent", "d1bsma1.ent-d1coja1.ent", "d1bsma1.ent-d1gv3a1.ent", "d1bsma1.ent-d1isaa1.ent", "d1bsma1.ent-d1ix9a1.ent", "d1bsma2.ent-d1coja2.ent", "d1bsma2.ent-d1gv3a2.ent", "d1bsma2.ent-d1isaa2.ent", "d1bsma2.ent-d1ix9a2.ent", "d1bsma2.ent-d1kkca2.ent", "d1bsma2.ent-d1ma1a2.ent", "d1bsma2.ent-d1qnna2.ent", "d1bsxa_.ent-d1fcya_.ent", "d1bsxa_.ent-d1g2na_.ent", "d1bsxa_.ent-d1hg4a_.ent", "d1bsxa_.ent-d1ie9a_.ent", "d1bsxa_.ent-d1ilga_.ent", "d1bsxa_.ent-d1kv6a_.ent", "d1bsxa_.ent-d1lv2a_.ent", "d1bsxa_.ent-d1mzna_.ent", "d1bsxa_.ent-d1n83a_.ent", "d1bsxa_.ent-d2prga_.ent", "d1bt0a_.ent-d1c1yb_.ent", "d1bt0a_.ent-d1e8xa3.ent", "d1bt0a_.ent-d1euvb_.ent", "d1bt0a_.ent-d1gg3a3.ent", "d1bt0a_.ent-d1gnua_.ent", "d1bt0a_.ent-d1h4ra3.ent", "d1bt0a_.ent-d1h8ca_.ent", "d1bt0a_.ent-d1i42a_.ent", "d1bt0a_.ent-d1j8ca_.ent", "d1bt0a_.ent-d1k8rb_.ent", "d1bt0a_.ent-d1l7ya_.ent", "d1bt0a_.ent-d1lfda_.ent", "d1bt0a_.ent-d1lm8b_.ent", "d1bt0a_.ent-d1m94a_.ent", "d1bt0a_.ent-d1rlf__.ent", "d1bt3a_.ent-d1hc2_2.ent", "d1bt3a_.ent-d1js8a1.ent", "d1bt3a_.ent-d1lla_2.ent", "d1btka_.ent-d1btn__.ent", "d1btka_.ent-d1ddma_.ent", "d1btka_.ent-d1dro__.ent", "d1btka_.ent-d1dyna_.ent", "d1btka_.ent-d1eaza_.ent", "d1btka_.ent-d1evha_.ent", "d1btka_.ent-d1faoa_.ent", "d1btka_.ent-d1fhoa_.ent", "d1btka_.ent-d1gg3a2.ent", "d1btka_.ent-d1h4ra2.ent", "d1btka_.ent-d1k5db_.ent", "d1btka_.ent-d1ki1b2.ent", "d1btka_.ent-d1mai__.ent", "d1btka_.ent-d1mixa2.ent", "d1btka_.ent-d1mkea1.ent", "d1btka_.ent-d1pls__.ent", "d1btka_.ent-d1qqga1.ent", "d1btka_.ent-d1qqga2.ent", "d1btka_.ent-d1shca_.ent", "d1btn__.ent-d1ddma_.ent", "d1btn__.ent-d1dro__.ent", "d1btn__.ent-d1dyna_.ent", "d1btn__.ent-d1eaza_.ent", "d1btn__.ent-d1evha_.ent", "d1btn__.ent-d1faoa_.ent", "d1btn__.ent-d1fhoa_.ent", "d1btn__.ent-d1gg3a2.ent", "d1btn__.ent-d1h4ra2.ent", "d1btn__.ent-d1k5db_.ent", "d1btn__.ent-d1ki1b2.ent", "d1btn__.ent-d1mai__.ent", "d1btn__.ent-d1mixa2.ent", "d1btn__.ent-d1mkea1.ent", "d1btn__.ent-d1pls__.ent", "d1btn__.ent-d1qqga1.ent", "d1btn__.ent-d1qqga2.ent", "d1btn__.ent-d1shca_.ent", "d1bu2a1.ent-d1bu2a2.ent", "d1bu2a1.ent-d1f5qb1.ent", "d1bu2a1.ent-d1f5qb2.ent", "d1bu2a1.ent-d1g3nc1.ent", "d1bu2a1.ent-d1g3nc2.ent", "d1bu2a1.ent-d1guxa_.ent", "d1bu2a1.ent-d1guxb_.ent", "d1bu2a1.ent-d1h4ld_.ent", "d1bu2a1.ent-d1jkw_1.ent", "d1bu2a1.ent-d1jkw_2.ent", "d1bu2a1.ent-d1vin_1.ent", "d1bu2a1.ent-d1vin_2.ent", "d1bu2a1.ent-d1vola1.ent", "d1bu2a2.ent-d1f5qb1.ent", "d1bu2a2.ent-d1f5qb2.ent", "d1bu2a2.ent-d1g3nc1.ent", "d1bu2a2.ent-d1g3nc2.ent", "d1bu2a2.ent-d1guxa_.ent", "d1bu2a2.ent-d1guxb_.ent", "d1bu2a2.ent-d1h4ld_.ent", "d1bu2a2.ent-d1jkw_1.ent", "d1bu2a2.ent-d1jkw_2.ent", "d1bu2a2.ent-d1vin_1.ent", "d1bu2a2.ent-d1vin_2.ent", "d1bu2a2.ent-d1vola1.ent", "d1bu8a1.ent-d1ca1_2.ent", "d1bu8a1.ent-d1f8na2.ent", "d1bu8a1.ent-d1lox_2.ent", "d1bu8a2.ent-d1cr6a2.ent", "d1bu8a2.ent-d1cvl__.ent", "d1bu8a2.ent-d1dqza_.ent", "d1bu8a2.ent-d1ei9a_.ent", "d1bu8a2.ent-d1ex9a_.ent", "d1bu8a2.ent-d1fj2a_.ent", "d1bu8a2.ent-d1gkla_.ent", "d1bu8a2.ent-d1hlga_.ent", "d1bu8a2.ent-d1imja_.ent", "d1bu8a2.ent-d1ispa_.ent", "d1bu8a2.ent-d1iz7a_.ent", "d1bu8a2.ent-d1jfra_.ent", "d1bu8a2.ent-d1jjia_.ent", "d1bu8a2.ent-d1ju3a2.ent", "d1bu8a2.ent-d1ku0a_.ent", "d1bu8a2.ent-d1l7aa_.ent", "d1bu8a2.ent-d1lzla_.ent", "d1bu8a2.ent-d1mnaa_.ent", "d1bu8a2.ent-d1n1ma2.ent", "d1bu8a2.ent-d1qj4a_.ent", "d1bu8a2.ent-d1qlwa_.ent", "d1bu8a2.ent-d1qo7a_.ent", "d1bu8a2.ent-d1qtra_.ent", "d1bu8a2.ent-d1tca__.ent", "d1bu8a2.ent-d1thta_.ent", "d1bu8a2.ent-d3tgl__.ent", "d1buca2.ent-d1is2a3.ent", "d1buca2.ent-d1ivha2.ent", "d1buca2.ent-d1jqia2.ent", "d1buca2.ent-d3mdda2.ent", "d1buda_.ent-d1c7ka_.ent", "d1buda_.ent-d1dmta_.ent", "d1buda_.ent-d1eb6a_.ent", "d1buda_.ent-d1epwa3.ent", "d1buda_.ent-d1ezm__.ent", "d1buda_.ent-d1g12a_.ent", "d1buda_.ent-d1gkda_.ent", "d1buda_.ent-d1hs6a3.ent", "d1buda_.ent-d1i1ip_.ent", "d1buda_.ent-d1j7na1.ent", "d1buda_.ent-d1j7na2.ent", "d1buda_.ent-d1jk3a_.ent", "d1buda_.ent-d1k7ia2.ent", "d1buda_.ent-d1k9xa_.ent", "d1buda_.ent-d1kapp2.ent", "d1buda_.ent-d1keia_.ent", "d1buda_.ent-d1kufa_.ent", "d1buda_.ent-d1lml__.ent", "d1buda_.ent-d3btaa3.ent", "d1buea_.ent-d1ci9a_.ent", "d1buea_.ent-d1e25a_.ent", "d1buea_.ent-d1ei5a3.ent", "d1buea_.ent-d1es5a_.ent", "d1buea_.ent-d1g6aa_.ent", "d1buea_.ent-d1ghpa_.ent", "d1buea_.ent-d1iyoa_.ent", "d1buea_.ent-d1l0ga_.ent", "d1buea_.ent-d1m40a_.ent", "d1buea_.ent-d1mfoa_.ent", "d1buea_.ent-d1mwxa3.ent", "d1buea_.ent-d1nj4a2.ent", "d1buea_.ent-d1qmea4.ent", "d1buea_.ent-d4blma_.ent", "d1buna_.ent-d1faza_.ent", "d1buna_.ent-d1g4ia_.ent", "d1buna_.ent-d1kvoa_.ent", "d1buna_.ent-d1le6a_.ent", "d1buna_.ent-d1mc2a_.ent", "d1buna_.ent-d1poc__.ent", "d1bunb_.ent-d1d0da_.ent", "d1bunb_.ent-d1g6xa_.ent", "d1bunb_.ent-d1irha_.ent", "d1bunb_.ent-d1ktha_.ent", "d1bunb_.ent-d1tfxc_.ent", "d1bunb_.ent-d1tocr1.ent", "d1bunb_.ent-d1tocr2.ent", "d1buoa_.ent-d1fs1b2.ent", "d1buoa_.ent-d1hv2a_.ent", "d1buoa_.ent-d1lm8c_.ent", "d1buoa_.ent-d1t1da_.ent", "d1buoa_.ent-d3kvt__.ent", "d1bupa1.ent-d1az9_1.ent", "d1bupa1.ent-d1bupa2.ent", "d1bupa1.ent-d1czan1.ent", "d1bupa1.ent-d1czan2.ent", "d1bupa1.ent-d1czan3.ent", "d1bupa1.ent-d1dkgd2.ent", "d1bupa1.ent-d1e4ft1.ent", "d1bupa1.ent-d1e4ft2.ent", "d1bupa1.ent-d1g99a1.ent", "d1bupa1.ent-d1g99a2.ent", "d1bupa1.ent-d1glag1.ent", "d1bupa1.ent-d1glag2.ent", "d1bupa1.ent-d1huxa_.ent", "d1bupa1.ent-d1ig8a1.ent", "d1bupa1.ent-d1ig8a2.ent", "d1bupa1.ent-d1j54a_.ent", "d1bupa1.ent-d1j6za2.ent", "d1bupa1.ent-d1jcfa1.ent", "d1bupa1.ent-d1k8ka1.ent", "d1bupa1.ent-d1mwma1.ent", "d1bupa1.ent-d1mwma2.ent", "d1bupa1.ent-d1nbwa2.ent", "d1bupa1.ent-d1nbwa3.ent", "d1bupa1.ent-d1xwl_1.ent", "d1bupa2.ent-d1az9_1.ent", "d1bupa2.ent-d1bupa1.ent", "d1bupa2.ent-d1czan1.ent", "d1bupa2.ent-d1czan2.ent", "d1bupa2.ent-d1czan3.ent", "d1bupa2.ent-d1dkgd2.ent", "d1bupa2.ent-d1e4ft1.ent", "d1bupa2.ent-d1e4ft2.ent", "d1bupa2.ent-d1g99a1.ent", "d1bupa2.ent-d1g99a2.ent", "d1bupa2.ent-d1glag1.ent", "d1bupa2.ent-d1glag2.ent", "d1bupa2.ent-d1huxa_.ent", "d1bupa2.ent-d1ig8a1.ent", "d1bupa2.ent-d1ig8a2.ent", "d1bupa2.ent-d1j54a_.ent", "d1bupa2.ent-d1j6za2.ent", "d1bupa2.ent-d1jcfa1.ent", "d1bupa2.ent-d1jj2m_.ent", "d1bupa2.ent-d1k8ka1.ent", "d1bupa2.ent-d1mwma1.ent", "d1bupa2.ent-d1mwma2.ent", "d1bupa2.ent-d1nbwa2.ent", "d1bupa2.ent-d1nbwa3.ent", "d1bupa2.ent-d1xwl_1.ent", "d1bvoa_.ent-d1h6fa_.ent", "d1bvoa_.ent-d1ikna2.ent", "d1bvoa_.ent-d1imhc2.ent", "d1bvoa_.ent-d1mnna_.ent", "d1bvoa_.ent-d1ycsa_.ent", "d1bvp12.ent-d1flca1.ent", "d1bvp12.ent-d1jsda_.ent", "d1bvp12.ent-d1jsma_.ent", "d1bvp12.ent-d1qhda2.ent", "d1bvp12.ent-d2viua_.ent", "d1bvyf_.ent-d1d4aa_.ent", "d1bvyf_.ent-d1e5da1.ent", "d1bvyf_.ent-d1f4pa_.ent", "d1bvyf_.ent-d1fuea_.ent", "d1bvyf_.ent-d1ja1a2.ent", "d1bvyf_.ent-d1qr2a_.ent", "d1bvyf_.ent-d1rcf__.ent", "d1bvyf_.ent-d2fcr__.ent", "d1bvyf_.ent-d5nul__.ent", "d1bw3__.ent-d1cz4a1.ent", "d1bw3__.ent-d1e32a1.ent", "d1bw3__.ent-d1eu1a1.ent", "d1bw3__.ent-d1g8ka1.ent", "d1bw3__.ent-d1h0ha1.ent", "d1bw3__.ent-d1n10a2.ent", "d1bw5__.ent-d1b8ia_.ent", "d1bw5__.ent-d1bl0a2.ent", "d1bw5__.ent-d1d5ya2.ent", "d1bw5__.ent-d1e3oc1.ent", "d1bw5__.ent-d1fexa_.ent", "d1bw5__.ent-d1fjla_.ent", "d1bw5__.ent-d1g2ha_.ent", "d1bw5__.ent-d1hlva1.ent", "d1bw5__.ent-d1hlva2.ent", "d1bw5__.ent-d1ig7a_.ent", "d1bw5__.ent-d1irza_.ent", "d1bw5__.ent-d1iufa2.ent", "d1bw5__.ent-d1k61a_.ent", "d1bw5__.ent-d1k78a1.ent", "d1bw5__.ent-d1k78a2.ent", "d1bw5__.ent-d2tct_1.ent", "d1bwda_.ent-d1g61a_.ent", "d1bwda_.ent-d1g62a_.ent", "d1bwda_.ent-d1h70a_.ent", "d1bwda_.ent-d1jdw__.ent", "d1bwvs_.ent-d1gk8i_.ent", "d1bwvs_.ent-d1rblm_.ent", "d1bx4a_.ent-d1jxha_.ent", "d1bx4a_.ent-d1l2la_.ent", "d1bx4a_.ent-d1lhpa_.ent", "d1bx4a_.ent-d1liia_.ent", "d1bx4a_.ent-d1o14a_.ent", "d1bx4a_.ent-d1rkd__.ent", "d1bx7__.ent-d1agg__.ent", "d1bx7__.ent-d1b9wa1.ent", "d1bx7__.ent-d1b9wa2.ent", "d1bx7__.ent-d1cixa_.ent", "d1bx7__.ent-d1dec__.ent", "d1bx7__.ent-d1e0fi_.ent", "d1bx7__.ent-d1flei_.ent", "d1bx7__.ent-d1g9pa_.ent", "d1bx7__.ent-d1gps__.ent", "d1bx7__.ent-d1h59b_.ent", "d1bx7__.ent-d1hyka_.ent", "d1bx7__.ent-d1i2ua_.ent", "d1bx7__.ent-d1ijqa2.ent", "d1bx7__.ent-d1imt_2.ent", "d1bx7__.ent-d1jkza_.ent", "d1bx7__.ent-d1klo_3.ent", "d1bx7__.ent-d1lpba2.ent", "d1bx7__.ent-d1skz_1.ent", "d1bx7__.ent-d1skz_2.ent", "d1bx7__.ent-d4htci_.ent", "d1bxda_.ent-d1byqa_.ent", "d1bxda_.ent-d1ei1a2.ent", "d1bxda_.ent-d1gkza2.ent", "d1bxda_.ent-d1i58a_.ent", "d1bxda_.ent-d1id0a_.ent", "d1bxda_.ent-d1jm6a2.ent", "d1bxda_.ent-d1kija2.ent", "d1bxda_.ent-d1l0oa_.ent", "d1bxda_.ent-d1mu5a3.ent", "d1bxoa_.ent-d1dpja_.ent", "d1bxoa_.ent-d1fkna_.ent", "d1bxoa_.ent-d1fmb__.ent", "d1bxoa_.ent-d1idaa_.ent", "d1bxoa_.ent-d1j71a_.ent", "d1bxoa_.ent-d1kzka_.ent", "d1bxoa_.ent-d1lf2a_.ent", "d1bxoa_.ent-d1mpp__.ent", "d1bxoa_.ent-d1nsoa_.ent", "d1bxoa_.ent-d2apr__.ent", "d1bxoa_.ent-d2rspa_.ent", "d1bxoa_.ent-d3psg__.ent", "d1bxoa_.ent-d4fiv__.ent", "d1by1a_.ent-d1f5xa_.ent", "d1by1a_.ent-d1ki1b1.ent", "d1by5a_.ent-d1hxxa_.ent", "d1by5a_.ent-d1i78a_.ent", "d1by5a_.ent-d1k24a_.ent", "d1by5a_.ent-d1kmoa_.ent", "d1by5a_.ent-d1mm4a_.ent", "d1by5a_.ent-d1qj8a_.ent", "d1by5a_.ent-d1qjpa_.ent", "d1by5a_.ent-d2mpra_.ent", "d1by5a_.ent-d2por__.ent", "d1by5a_.ent-d3prn__.ent", "d1by7a_.ent-d1e05i_.ent", "d1by7a_.ent-d1imva_.ent", "d1by7a_.ent-d1jmja_.ent", "d1by7a_.ent-d1k9oi_.ent", "d1by7a_.ent-d1lj5a_.ent", "d1by7a_.ent-d1ovaa_.ent", "d1by7a_.ent-d1qlpa_.ent", "d1by9__.ent-d2bopa_.ent", "d1byfa_.ent-d1b08a1.ent", "d1byfa_.ent-d1b6e__.ent", "d1byfa_.ent-d1cwva5.ent", "d1byfa_.ent-d1e87a_.ent", "d1byfa_.ent-d1f00i3.ent", "d1byfa_.ent-d1fvub_.ent", "d1byfa_.ent-d1g1ta1.ent", "d1byfa_.ent-d1h8ua_.ent", "d1byfa_.ent-d1hq8a_.ent", "d1byfa_.ent-d1jwia_.ent", "d1byfa_.ent-d1jwib_.ent", "d1byfa_.ent-d1li1a1.ent", "d1byfa_.ent-d1li1a2.ent", "d1byfa_.ent-d1prtb2.ent", "d1byfa_.ent-d1tsg__.ent", "d1byka_.ent-d1dbqa_.ent", "d1byka_.ent-d1dp4a_.ent", "d1byka_.ent-d1ewka_.ent", "d1byka_.ent-d1gca__.ent", "d1byka_.ent-d1jdpa_.ent", "d1byka_.ent-d1jx6a_.ent", "d1byka_.ent-d1jyea_.ent", "d1byka_.ent-d1pea__.ent", "d1byka_.ent-d1rpja_.ent", "d1byka_.ent-d2dri__.ent", "d1byka_.ent-d2liv__.ent", "d1byka_.ent-d8abp__.ent", "d1byqa_.ent-d1ei1a2.ent", "d1byqa_.ent-d1gkza2.ent", "d1byqa_.ent-d1i58a_.ent", "d1byqa_.ent-d1id0a_.ent", "d1byqa_.ent-d1jm6a2.ent", "d1byqa_.ent-d1kija2.ent", "d1byqa_.ent-d1l0oa_.ent", "d1byqa_.ent-d1mu5a3.ent", "d1byra_.ent-d1f0ia1.ent", "d1byra_.ent-d1f0ia2.ent", "d1bywa_.ent-d1ew0a_.ent", "d1bywa_.ent-d1jnua_.ent", "d1bywa_.ent-d1ll8a_.ent", "d1bywa_.ent-d1lswa_.ent", "d1bywa_.ent-d1mzua_.ent", "d1bywa_.ent-d3pyp__.ent", "d1bzya_.ent-d1dkra1.ent", "d1bzya_.ent-d1dkra2.ent", "d1bzya_.ent-d1dqna_.ent", "d1bzya_.ent-d1ecfa1.ent", "d1bzya_.ent-d1fsga_.ent", "d1bzya_.ent-d1g2qa_.ent", "d1bzya_.ent-d1g9sa_.ent", "d1bzya_.ent-d1gph11.ent", "d1bzya_.ent-d1hgxa_.ent", "d1bzya_.ent-d1i5ea_.ent", "d1bzya_.ent-d1l1qa_.ent", "d1bzya_.ent-d1lh0a_.ent", "d1bzya_.ent-d1nula_.ent", "d1bzya_.ent-d1qb7a_.ent", "d1bzya_.ent-d1tc1a_.ent", "d1c01a_.ent-d1f53a_.ent", "d1c01a_.ent-d1g6ea_.ent", "d1c01a_.ent-d2bb2_1.ent", "d1c01a_.ent-d2bb2_2.ent", "d1c02a_.ent-d1dova_.ent", "d1c02a_.ent-d1ei7a_.ent", "d1c02a_.ent-d1f1ma_.ent", "d1c02a_.ent-d1fts_1.ent", "d1c02a_.ent-d1he1a_.ent", "d1c02a_.ent-d1jr8a_.ent", "d1c02a_.ent-d1k04a_.ent", "d1c02a_.ent-d1knya1.ent", "d1c02a_.ent-d1ls1a1.ent", "d1c02a_.ent-d1nfn__.ent", "d1c02a_.ent-d1nlxa_.ent", "d1c02a_.ent-d256ba_.ent", "d1c02a_.ent-d2a0b__.ent", "d1c02a_.ent-d2liga_.ent", "d1c02a_.ent-d2mhr__.ent", "d1c02a_.ent-d3fapb_.ent", "d1c0pa1.ent-d1cjca2.ent", "d1c0pa1.ent-d1gtea4.ent", "d1c0pa1.ent-d1i8ta1.ent", "d1c0pa1.ent-d1lqta2.ent", "d1c0pa1.ent-d1o94a3.ent", "d1c0pa2.ent-d1d5ta2.ent", "d1c0pa2.ent-d1f8ra2.ent", "d1c0pa2.ent-d1foha4.ent", "d1c0pa2.ent-d1gosa2.ent", "d1c0pa2.ent-d1gpea2.ent", "d1c0pa2.ent-d1i8ta2.ent", "d1c0pa2.ent-d1ju2a2.ent", "d1c0pa2.ent-d1k0ia2.ent", "d1c0pa2.ent-d1kdga2.ent", "d1c0pa2.ent-d1l9ea2.ent", "d1c0pa2.ent-d1mxta2.ent", "d1c0va_.ent-d1ehkb2.ent", "d1c0va_.ent-d1fftb2.ent", "d1c0va_.ent-d1ocrb2.ent", "d1c16a2.ent-d1cd1a2.ent", "d1c16a2.ent-d1de4a2.ent", "d1c16a2.ent-d1fnga2.ent", "d1c16a2.ent-d1fngb2.ent", "d1c16a2.ent-d1gzqa2.ent", "d1c16a2.ent-d1hdma2.ent", "d1c16a2.ent-d1hdmb2.ent", "d1c16a2.ent-d1hyrc2.ent", "d1c16a2.ent-d1iaka2.ent", "d1c16a2.ent-d1jfma_.ent", "d1c16a2.ent-d1k5na2.ent", "d1c16a2.ent-d1kcgc_.ent", "d1c16a2.ent-d1lqva_.ent", "d1c16a2.ent-d1zaga2.ent", "d1c16a2.ent-d3frua2.ent", "d1c1da1.ent-d1bg6_2.ent", "d1c1da1.ent-d1cf2o1.ent", "d1c1da1.ent-d1dlja2.ent", "d1c1da1.ent-d1dpga1.ent", "d1c1da1.ent-d1dssg1.ent", "d1c1da1.ent-d1e5qa1.ent", "d1c1da1.ent-d1f0ya2.ent", "d1c1da1.ent-d1lc0a1.ent", "d1c1da1.ent-d1lu9a1.ent", "d1c1da1.ent-d2naca1.ent", "d1c1da1.ent-d2pgd_2.ent", "d1c1da2.ent-d1edza2.ent", "d1c1da2.ent-d1gtma2.ent", "d1c1da2.ent-d1hwxa2.ent", "d1c1da2.ent-d1leha2.ent", "d1c1da2.ent-d1lu9a2.ent", "d1c1yb_.ent-d1e8xa3.ent", "d1c1yb_.ent-d1euvb_.ent", "d1c1yb_.ent-d1gg3a3.ent", "d1c1yb_.ent-d1gnua_.ent", "d1c1yb_.ent-d1h4ra3.ent", "d1c1yb_.ent-d1h8ca_.ent", "d1c1yb_.ent-d1i42a_.ent", "d1c1yb_.ent-d1j8ca_.ent", "d1c1yb_.ent-d1k8rb_.ent", "d1c1yb_.ent-d1l7ya_.ent", "d1c1yb_.ent-d1lfda_.ent", "d1c1yb_.ent-d1lm8b_.ent", "d1c1yb_.ent-d1m94a_.ent", "d1c1yb_.ent-d1rlf__.ent", "d1c20a_.ent-d1ig6a_.ent", "d1c20a_.ent-d1kkxa_.ent", "d1c22a_.ent-d1chma2.ent", "d1c22a_.ent-d1o0xa_.ent", "d1c22a_.ent-d1xgsa2.ent", "d1c2aa1.ent-d1agg__.ent", "d1c2aa1.ent-d1apq__.ent", "d1c2aa1.ent-d1b9wa1.ent", "d1c2aa1.ent-d1b9wa2.ent", "d1c2aa1.ent-d1bx7__.ent", "d1c2aa1.ent-d1cixa_.ent", "d1c2aa1.ent-d1e0fi_.ent", "d1c2aa1.ent-d1flei_.ent", "d1c2aa1.ent-d1g9pa_.ent", "d1c2aa1.ent-d1gps__.ent", "d1c2aa1.ent-d1h59b_.ent", "d1c2aa1.ent-d1hyka_.ent", "d1c2aa1.ent-d1i2ua_.ent", "d1c2aa1.ent-d1ijqa2.ent", "d1c2aa1.ent-d1imt_2.ent", "d1c2aa1.ent-d1jkza_.ent", "d1c2aa1.ent-d1klil_.ent", "d1c2aa1.ent-d1klo_1.ent", "d1c2aa1.ent-d1klo_3.ent", "d1c2aa1.ent-d1lpba2.ent", "d1c2aa1.ent-d4htci_.ent", "d1c2ya_.ent-d1c41a_.ent", "d1c2ya_.ent-d1di0a_.ent", "d1c2ya_.ent-d1ejba_.ent", "d1c2ya_.ent-d1hqka_.ent", "d1c2ya_.ent-d1kz1a_.ent", "d1c2ya_.ent-d1rvv1_.ent", "d1c3ca_.ent-d1dofa_.ent", "d1c3ca_.ent-d1fura_.ent", "d1c3ca_.ent-d1hy0a_.ent", "d1c3ca_.ent-d1jswa_.ent", "d1c3d__.ent-d1dceb_.ent", "d1c3d__.ent-d1dl2a_.ent", "d1c3d__.ent-d1faea_.ent", "d1c3d__.ent-d1fp3a_.ent", "d1c3d__.ent-d1gai__.ent", "d1c3d__.ent-d1gxma_.ent", "d1c3d__.ent-d1h54a1.ent", "d1c3d__.ent-d1ks8a_.ent", "d1c3d__.ent-d1kwfa_.ent", "d1c3d__.ent-d1ld8b_.ent", "d1c3d__.ent-d1lf6a1.ent", "d1c3d__.ent-d1n1ba1.ent", "d1c3d__.ent-d1n7oa1.ent", "d1c3d__.ent-d1qaza_.ent", "d1c3d__.ent-d2sqca1.ent", "d1c3d__.ent-d2sqca2.ent", "d1c3d__.ent-d5eau_1.ent", "d1c3pa_.ent-d1d3va_.ent", "d1c3pa_.ent-d1gq6a_.ent", "d1c3pa_.ent-d2ceva_.ent", "d1c3za_.ent-d1cpo_2.ent", "d1c3za_.ent-d1ctda_.ent", "d1c3za_.ent-d1dqea_.ent", "d1c3za_.ent-d1eg3a1.ent", "d1c3za_.ent-d1eg3a2.ent", "d1c3za_.ent-d1el4a_.ent", "d1c3za_.ent-d1fi6a_.ent", "d1c3za_.ent-d1h8ba_.ent", "d1c3za_.ent-d1iioa_.ent", "d1c3za_.ent-d1j7qa_.ent", "d1c3za_.ent-d1k94a_.ent", "d1c3za_.ent-d1m45a_.ent", "d1c3za_.ent-d1psra_.ent", "d1c3za_.ent-d1qasa1.ent", "d1c3za_.ent-d1rec__.ent", "d1c3za_.ent-d1sra__.ent", "d1c3za_.ent-d2cbla1.ent", "d1c3za_.ent-d2pvba_.ent", "d1c3za_.ent-d2sas__.ent", "d1c3za_.ent-d2scpa_.ent", "d1c41a_.ent-d1di0a_.ent", "d1c41a_.ent-d1ejba_.ent", "d1c41a_.ent-d1hqka_.ent", "d1c41a_.ent-d1kz1a_.ent", "d1c41a_.ent-d1rvv1_.ent", "d1c4ka1.ent-d1dbwa_.ent", "d1c4ka1.ent-d1dcfa_.ent", "d1c4ka1.ent-d1dz3a_.ent", "d1c4ka1.ent-d1m2fa_.ent", "d1c4ka1.ent-d1mb3a_.ent", "d1c4ka1.ent-d1mvoa_.ent", "d1c4ka1.ent-d1nat__.ent", "d1c4ka1.ent-d1ntr__.ent", "d1c4ka1.ent-d1qo0d_.ent", "d1c4ka1.ent-d1tmy__.ent", "d1c4ka2.ent-d1ajsa_.ent", "d1c4ka2.ent-d1b9ha_.ent", "d1c4ka2.ent-d1bs0a_.ent", "d1c4ka2.ent-d1c7na_.ent", "d1c4ka2.ent-d1e5ea_.ent", "d1c4ka2.ent-d1elua_.ent", "d1c4ka2.ent-d1gdea_.ent", "d1c4ka2.ent-d1gtxa_.ent", "d1c4ka2.ent-d1j32a_.ent", "d1c4ka2.ent-d1jf9a_.ent", "d1c4ka2.ent-d1js3a_.ent", "d1c4ka2.ent-d1kl1a_.ent", "d1c4ka2.ent-d1lc5a_.ent", "d1c4ka2.ent-d1m7ya_.ent", "d1c4ka2.ent-d1n8pa_.ent", "d1c4ka2.ent-d1qisa_.ent", "d1c4ka2.ent-d1qj5a_.ent", "d1c4ka2.ent-d1tpla_.ent", "d1c4ka2.ent-d1yaaa_.ent", "d1c4ka2.ent-d2ay1a_.ent", "d1c4ka2.ent-d2dkb__.ent", "d1c4ka2.ent-d2gsaa_.ent", "d1c4ka2.ent-d2oata_.ent", "d1c4ka2.ent-d3tata_.ent", "d1c4ka2.ent-d7aata_.ent", "d1c4oa1.ent-d1a7j__.ent", "d1c4oa1.ent-d1aqua_.ent", "d1c4oa1.ent-d1bg2__.ent", "d1c4oa1.ent-d1cr1a_.ent", "d1c4oa1.ent-d1e2ka_.ent", "d1c4oa1.ent-d1e69a_.ent", "d1c4oa1.ent-d1e79a3.ent", "d1c4oa1.ent-d1f5na2.ent", "d1c4oa1.ent-d1f9va_.ent", "d1c4oa1.ent-d1fnna2.ent", "d1c4oa1.ent-d1g8pa_.ent", "d1c4oa1.ent-d1g8ya_.ent", "d1c4oa1.ent-d1gm5a3.ent", "d1c4oa1.ent-d1ihua1.ent", "d1c4oa1.ent-d1jwyb_.ent", "d1c4oa1.ent-d1ksfx3.ent", "d1c4oa1.ent-d1lv7a_.ent", "d1c4oa1.ent-d1m6na3.ent", "d1c4oa1.ent-d1n0ua2.ent", "d1c4oa1.ent-d1nsta_.ent", "d1c4oa1.ent-d1pjr_1.ent", "d1c4oa1.ent-d1pjr_2.ent", "d1c4oa1.ent-d1uaaa1.ent", "d1c4oa1.ent-d1uaaa2.ent", "d1c4qa_.ent-d1enfa1.ent", "d1c4qa_.ent-d1esfa1.ent", "d1c4qa_.ent-d1et9a1.ent", "d1c4qa_.ent-d1eu3a1.ent", "d1c4qa_.ent-d1fnua1.ent", "d1c4qa_.ent-d1m4va1.ent", "d1c4qa_.ent-d1prtb1.ent", "d1c4qa_.ent-d1prtd_.ent", "d1c4qa_.ent-d1prtf_.ent", "d1c4qa_.ent-d1tiid_.ent", "d1c4qa_.ent-d3chbd_.ent", "d1c4qa_.ent-d3seb_1.ent", "d1c4qa_.ent-d3tss_1.ent", "d1c4ra_.ent-d1d2sa_.ent", "d1c4ra_.ent-d1dyka2.ent", "d1c4ra_.ent-d1gv9a_.ent", "d1c4ra_.ent-d1h30a2.ent", "d1c4ra_.ent-d1ikpa1.ent", "d1c4ra_.ent-d1is3a_.ent", "d1c4ra_.ent-d1jhna4.ent", "d1c4ra_.ent-d1kit_1.ent", "d1c4ra_.ent-d1kqra_.ent", "d1c4ra_.ent-d1n1ta1.ent", "d1c4ra_.ent-d1nls__.ent", "d1c4ra_.ent-d1saca_.ent", "d1c4ra_.ent-d2nlra_.ent", "d1c4ra_.ent-d2sli_1.ent", "d1c4zd_.ent-d1fzya_.ent", "d1c4zd_.ent-d1i7ka_.ent", "d1c4zd_.ent-d1j7da_.ent", "d1c4zd_.ent-d1jata_.ent", "d1c4zd_.ent-d1jatb_.ent", "d1c4zd_.ent-d1kppa_.ent", "d1c4zd_.ent-d1qcqa_.ent", "d1c4zd_.ent-d2aak__.ent", "d1c4zd_.ent-d2ucz__.ent", "d1c52__.ent-d1c75a_.ent", "d1c52__.ent-d1cc5__.ent", "d1c52__.ent-d1cnoa_.ent", "d1c52__.ent-d1co6a_.ent", "d1c52__.ent-d1cot__.ent", "d1c52__.ent-d1ctj__.ent", "d1c52__.ent-d1cxc__.ent", "d1c52__.ent-d1diqc_.ent", "d1c52__.ent-d1dw0a_.ent", "d1c52__.ent-d1e29a_.ent", "d1c52__.ent-d1etpa2.ent", "d1c52__.ent-d1ezvd1.ent", "d1c52__.ent-d1f1ca_.ent", "d1c52__.ent-d1fcdc2.ent", "d1c52__.ent-d1gu2a_.ent", "d1c52__.ent-d1h32a1.ent", "d1c52__.ent-d1hroa_.ent", "d1c52__.ent-d1iqca1.ent", "d1c52__.ent-d1iqca2.ent", "d1c52__.ent-d1jmxa1.ent", "d1c52__.ent-d1jmxa2.ent", "d1c52__.ent-d1kb0a1.ent", "d1c52__.ent-d1kv9a1.ent", "d1c52__.ent-d1mg2d_.ent", "d1c52__.ent-d1nira1.ent", "d1c52__.ent-d1qksa1.ent", "d1c52__.ent-d1ql3a_.ent", "d1c52__.ent-d1qn2a_.ent", "d1c52__.ent-d1ycc__.ent", "d1c52__.ent-d3c2c__.ent", "d1c55a_.ent-d1cmr__.ent", "d1c55a_.ent-d1fjna_.ent", "d1c55a_.ent-d1gps__.ent", "d1c55a_.ent-d1i2ua_.ent", "d1c55a_.ent-d1ica__.ent", "d1c55a_.ent-d1jkza_.ent", "d1c55a_.ent-d1jxca_.ent", "d1c55a_.ent-d1myn__.ent", "d1c55a_.ent-d1npia_.ent", "d1c55a_.ent-d1nrb__.ent", "d1c55a_.ent-d1qkya_.ent", "d1c55a_.ent-d1sco__.ent", "d1c55a_.ent-d1scy__.ent", "d1c55a_.ent-d1sis__.ent", "d1c55a_.ent-d1tsk__.ent", "d1c55a_.ent-d2sn3__.ent", "d1c5ea_.ent-d1euwa_.ent", "d1c5ea_.ent-d1g8la1.ent", "d1c5ea_.ent-d1h3ia2.ent", "d1c5ea_.ent-d1hg7a_.ent", "d1c5ea_.ent-d1mlva2.ent", "d1c5ea_.ent-d1n3ja_.ent", "d1c5ea_.ent-d1tul__.ent", "d1c5ea_.ent-d4ubpb_.ent", "d1c6wa_.ent-d1cixa_.ent", "d1c6wa_.ent-d1d1ha_.ent", "d1c6wa_.ent-d1dl0a_.ent", "d1c6wa_.ent-d1eit__.ent", "d1c6wa_.ent-d1emxa_.ent", "d1c6wa_.ent-d1g9pa_.ent", "d1c6wa_.ent-d1i25a_.ent", "d1c6wa_.ent-d1i26a_.ent", "d1c6wa_.ent-d1koza_.ent", "d1c6wa_.ent-d1kqha_.ent", "d1c6wa_.ent-d1lqra_.ent", "d1c6wa_.ent-d1lupa_.ent", "d1c6wa_.ent-d1nixa_.ent", "d1c6wa_.ent-d1niya_.ent", "d1c6wa_.ent-d1qk6a_.ent", "d1c6wa_.ent-d1qk7a_.ent", "d1c6wa_.ent-d1vtx__.ent", "d1c75a_.ent-d1cc5__.ent", "d1c75a_.ent-d1cnoa_.ent", "d1c75a_.ent-d1ctj__.ent", "d1c75a_.ent-d1diqc_.ent", "d1c75a_.ent-d1e29a_.ent", "d1c75a_.ent-d1ezvd1.ent", "d1c75a_.ent-d1fcdc2.ent", "d1c75a_.ent-d1gu2a_.ent", "d1c75a_.ent-d1h32a1.ent", "d1c75a_.ent-d1iqca1.ent", "d1c75a_.ent-d1iqca2.ent", "d1c75a_.ent-d1jmxa1.ent", "d1c75a_.ent-d1jmxa2.ent", "d1c75a_.ent-d1kb0a1.ent", "d1c75a_.ent-d1mg2d_.ent", "d1c75a_.ent-d1qksa1.ent", "d1c7ka_.ent-d1dmta_.ent", "d1c7ka_.ent-d1eb6a_.ent", "d1c7ka_.ent-d1epwa3.ent", "d1c7ka_.ent-d1ezm__.ent", "d1c7ka_.ent-d1g12a_.ent", "d1c7ka_.ent-d1gkda_.ent", "d1c7ka_.ent-d1gqia2.ent", "d1c7ka_.ent-d1hs6a3.ent", "d1c7ka_.ent-d1i1ip_.ent", "d1c7ka_.ent-d1j7na1.ent", "d1c7ka_.ent-d1j7na2.ent", "d1c7ka_.ent-d1jaka2.ent", "d1c7ka_.ent-d1jk3a_.ent", "d1c7ka_.ent-d1k7ia2.ent", "d1c7ka_.ent-d1k9xa_.ent", "d1c7ka_.ent-d1kapp2.ent", "d1c7ka_.ent-d1keia_.ent", "d1c7ka_.ent-d1kufa_.ent", "d1c7ka_.ent-d1lml__.ent", "d1c7ka_.ent-d1qba_4.ent", "d1c7ka_.ent-d3btaa3.ent", "d1c7na_.ent-d1b9ha_.ent", "d1c7na_.ent-d1bs0a_.ent", "d1c7na_.ent-d1e5ea_.ent", "d1c7na_.ent-d1gdea_.ent", "d1c7na_.ent-d1j32a_.ent", "d1c7na_.ent-d1n8pa_.ent", "d1c7na_.ent-d2ay1a_.ent", "d1c7qa_.ent-d1iata_.ent", "d1c7qa_.ent-d1m3sa_.ent", "d1c7qa_.ent-d1moq__.ent", "d1c8ba_.ent-d1cfza_.ent", "d1c8ba_.ent-d1je0a_.ent", "d1c8ba_.ent-d1lam_2.ent", "d1c8ba_.ent-d1lfwa1.ent", "d1c8ba_.ent-d1loka_.ent", "d1c8ba_.ent-d1m4la_.ent", "d1c8ba_.ent-d2pth__.ent", "d1c8da_.ent-d1a6ca1.ent", "d1c8da_.ent-d1a6ca2.ent", "d1c8da_.ent-d1a6ca3.ent", "d1c8da_.ent-d1aym1_.ent", "d1c8da_.ent-d1aym2_.ent", "d1c8da_.ent-d1b35a_.ent", "d1c8da_.ent-d1b35b_.ent", "d1c8da_.ent-d1b35c_.ent", "d1c8da_.ent-d1bev1_.ent", "d1c8da_.ent-d1bev3_.ent", "d1c8da_.ent-d1bmv1_.ent", "d1c8da_.ent-d1bmv2_.ent", "d1c8da_.ent-d1c8na_.ent", "d1c8da_.ent-d1cwpa_.ent", "d1c8da_.ent-d1d4m1_.ent", "d1c8da_.ent-d1ddla_.ent", "d1c8da_.ent-d1dnv__.ent", "d1c8da_.ent-d1dzla_.ent", "d1c8da_.ent-d1f15a_.ent", "d1c8da_.ent-d1ihma_.ent", "d1c8da_.ent-d1k5ma_.ent", "d1c8da_.ent-d1lp3a_.ent", "d1c8da_.ent-d1novc_.ent", "d1c8da_.ent-d1pov0_.ent", "d1c8da_.ent-d1pvc1_.ent", "d1c8da_.ent-d1qqp1_.ent", "d1c8da_.ent-d1qqp2_.ent", "d1c8da_.ent-d1qqp3_.ent", "d1c8da_.ent-d1sva1_.ent", "d1c8da_.ent-d1tmf1_.ent", "d1c8da_.ent-d1vpsa_.ent", "d1c8da_.ent-d2bbva_.ent", "d1c8da_.ent-d2bpa1_.ent", "d1c8da_.ent-d2bpa2_.ent", "d1c8da_.ent-d2mev1_.ent", "d1c8da_.ent-d2mev2_.ent", "d1c8da_.ent-d2stv__.ent", "d1c8na_.ent-d1a6ca1.ent", "d1c8na_.ent-d1a6ca2.ent", "d1c8na_.ent-d1a6ca3.ent", "d1c8na_.ent-d1bmv1_.ent", "d1c8na_.ent-d1cwpa_.ent", "d1c8na_.ent-d1ddla_.ent", "d1c8na_.ent-d1f15a_.ent", "d1c8na_.ent-d1qqp1_.ent", "d1c8na_.ent-d2bpa2_.ent", "d1c8na_.ent-d2stv__.ent", "d1c8ua1.ent-d1c8ua2.ent", "d1c8ua1.ent-d1iq6a_.ent", "d1c8ua1.ent-d1lo7a_.ent", "d1c8ua1.ent-d1mkaa_.ent", "d1c8ua2.ent-d1iq6a_.ent", "d1c8ua2.ent-d1lo7a_.ent", "d1c8ua2.ent-d1mkaa_.ent", "d1c9fa_.ent-d1d4ba_.ent", "d1c9fa_.ent-d1f2ri_.ent", "d1c9fa_.ent-d1fm0d_.ent", "d1c9fa_.ent-d1h4ra3.ent", "d1c9fa_.ent-d1h8ca_.ent", "d1c9fa_.ent-d1ip9a_.ent", "d1c9fa_.ent-d1k8rb_.ent", "d1c9fa_.ent-d1lfda_.ent", "d1c9la2.ent-d1fwxa2.ent", "d1c9la2.ent-d1gxra_.ent", "d1c9la2.ent-d1jmxb_.ent", "d1c9la2.ent-d1jtdb_.ent", "d1c9la2.ent-d1k32a3.ent", "d1c9la2.ent-d1k8kc_.ent", "d1c9la2.ent-d1m1xa4.ent", "d1c9la2.ent-d2bbkh_.ent", "d1ca1_2.ent-d1f8na2.ent", "d1ca1_2.ent-d1lox_2.ent", "d1cb0a_.ent-d1g2oa_.ent", "d1cb0a_.ent-d1je0a_.ent", "d1cb0a_.ent-d1jysa_.ent", "d1cb0a_.ent-d1k9sa_.ent", "d1cb8a1.ent-d1n7oa1.ent", "d1cb8a1.ent-d1qaza_.ent", "d1cb8a3.ent-d1h54a2.ent", "d1cb8a3.ent-d1jz8a4.ent", "d1cb8a3.ent-d1lf6a2.ent", "d1cb8a3.ent-d1n7oa3.ent", "d1cb8a3.ent-d1nsza_.ent", "d1cbg__.ent-d1b9za2.ent", "d1cbg__.ent-d1bf2_3.ent", "d1cbg__.ent-d1cz1a_.ent", "d1cbg__.ent-d1e43a2.ent", "d1cbg__.ent-d1e4ia_.ent", "d1cbg__.ent-d1eh9a3.ent", "d1cbg__.ent-d1hxja_.ent", "d1cbg__.ent-d1iexa1.ent", "d1cbg__.ent-d1j0ha3.ent", "d1cbg__.ent-d1ji1a3.ent", "d1cbg__.ent-d1kwga2.ent", "d1cbg__.ent-d1lwha2.ent", "d1cbg__.ent-d1pama4.ent", "d1cbg__.ent-d1qba_3.ent", "d1cbg__.ent-d1qhoa4.ent", "d1cbg__.ent-d1qvba_.ent", "d1cbg__.ent-d1uok_2.ent", "d1cbg__.ent-d7taa_2.ent", "d1cbs__.ent-d1dzka_.ent", "d1cbs__.ent-d1euoa_.ent", "d1cbs__.ent-d1ew3a_.ent", "d1cbs__.ent-d1ftpa_.ent", "d1cbs__.ent-d1g85a_.ent", "d1cbs__.ent-d1ggla_.ent", "d1cbs__.ent-d1gkab_.ent", "d1cbs__.ent-d1hms__.ent", "d1cbs__.ent-d1i4ua_.ent", "d1cbs__.ent-d1ifc__.ent", "d1cbs__.ent-d1jv4a_.ent", "d1cbs__.ent-d1koia_.ent", "d1cbs__.ent-d1kqwa_.ent", "d1cbs__.ent-d1lf7a_.ent", "d1cbs__.ent-d1o1va_.ent", "d1cbs__.ent-d1qfta_.ent", "d1cbs__.ent-d1qqsa_.ent", "d1cc5__.ent-d1cnoa_.ent", "d1cc5__.ent-d1ctj__.ent", "d1cc5__.ent-d1diqc_.ent", "d1cc5__.ent-d1e29a_.ent", "d1cc5__.ent-d1ezvd1.ent", "d1cc5__.ent-d1fcdc2.ent", "d1cc5__.ent-d1gu2a_.ent", "d1cc5__.ent-d1h32a1.ent", "d1cc5__.ent-d1iqca1.ent", "d1cc5__.ent-d1iqca2.ent", "d1cc5__.ent-d1jmxa1.ent", "d1cc5__.ent-d1jmxa2.ent", "d1cc5__.ent-d1kb0a1.ent", "d1cc5__.ent-d1mg2d_.ent", "d1cc5__.ent-d1qksa1.ent", "d1cc8a_.ent-d1cpza_.ent", "d1cc8a_.ent-d1fe0a_.ent", "d1cc8a_.ent-d1fvqa_.ent", "d1cc8a_.ent-d1jwwa_.ent", "d1cc8a_.ent-d1k0va_.ent", "d1cc8a_.ent-d1mwza_.ent", "d1ccva_.ent-d1coua_.ent", "d1ccva_.ent-d1eaic_.ent", "d1ccva_.ent-d1hx2a_.ent", "d1ccwa_.ent-d7reqa2.ent", "d1ccwa_.ent-d7reqb2.ent", "d1ccwb_.ent-d1cz1a_.ent", "d1ccwb_.ent-d1d3ga_.ent", "d1ccwb_.ent-d1edg__.ent", "d1ccwb_.ent-d1eexa_.ent", "d1ccwb_.ent-d1f8ma_.ent", "d1ccwb_.ent-d1gvoa_.ent", "d1ccwb_.ent-d1gw1a_.ent", "d1ccwb_.ent-d1iexa1.ent", "d1ccwb_.ent-d1itua_.ent", "d1ccwb_.ent-d1j5sa_.ent", "d1ccwb_.ent-d1k4ga_.ent", "d1ccwb_.ent-d1kbla1.ent", "d1ccwb_.ent-d1kwga2.ent", "d1ccwb_.ent-d1m7ja3.ent", "d1ccwb_.ent-d1muwa_.ent", "d1ccwb_.ent-d1ntha_.ent", "d1ccwb_.ent-d7reqa1.ent", "d1ccwb_.ent-d7reqb1.ent", "d1cd1a2.ent-d1de4a2.ent", "d1cd1a2.ent-d1fnga2.ent", "d1cd1a2.ent-d1fngb2.ent", "d1cd1a2.ent-d1gzqa2.ent", "d1cd1a2.ent-d1hdma2.ent", "d1cd1a2.ent-d1hdmb2.ent", "d1cd1a2.ent-d1hyrc2.ent", "d1cd1a2.ent-d1iaka2.ent", "d1cd1a2.ent-d1jfma_.ent", "d1cd1a2.ent-d1k5na2.ent", "d1cd1a2.ent-d1kcgc_.ent", "d1cd1a2.ent-d1lqva_.ent", "d1cd1a2.ent-d1zaga2.ent", "d1cd1a2.ent-d3frua2.ent", "d1cd9b1.ent-d1axib2.ent", "d1cd9b1.ent-d1bpv__.ent", "d1cd9b1.ent-d1cd9b2.ent", "d1cd9b1.ent-d1cfb_1.ent", "d1cd9b1.ent-d1cfb_2.ent", "d1cd9b1.ent-d1eerb2.ent", "d1cd9b1.ent-d1egja_.ent", "d1cd9b1.ent-d1f6fb1.ent", "d1cd9b1.ent-d1f6fb2.ent", "d1cd9b1.ent-d1fyhb1.ent", "d1cd9b1.ent-d1fyhb2.ent", "d1cd9b1.ent-d1gh7a1.ent", "d1cd9b1.ent-d1i1ra1.ent", "d1cd9b1.ent-d1lqsr1.ent", "d1cd9b1.ent-d1n26a2.ent", "d1cd9b1.ent-d1n26a3.ent", "d1cd9b1.ent-d1qg3a2.ent", "d1cd9b1.ent-d2hft_1.ent", "d1cd9b1.ent-d2hft_2.ent", "d1cd9b2.ent-d1f6fb1.ent", "d1cd9b2.ent-d1f6fb2.ent", "d1cd9b2.ent-d1fyhb1.ent", "d1cd9b2.ent-d1lqsr1.ent", "d1cdza_.ent-d1dgtb3.ent", "d1cdza_.ent-d1gzhb1.ent", "d1cdza_.ent-d1in1a_.ent", "d1cdza_.ent-d1l0ba1.ent", "d1cdza_.ent-d1l0ba2.ent", "d1ce3a_.ent-d1iw4a_.ent", "d1ce3a_.ent-d1ldtl_.ent", "d1ce3a_.ent-d1nuba3.ent", "d1ce3a_.ent-d1pce__.ent", "d1ce3a_.ent-d1sgpi_.ent", "d1ce3a_.ent-d1tbrr1.ent", "d1ce3a_.ent-d1tbrr2.ent", "d1ce3a_.ent-d1tgsi_.ent", "d1ce3a_.ent-d4sgbi_.ent", "d1ce7a_.ent-d1d6aa_.ent", "d1ce7a_.ent-d1dm0a_.ent", "d1ce7a_.ent-d1hwma_.ent", "d1ce7a_.ent-d1ift__.ent", "d1ce7a_.ent-d1mrj__.ent", "d1ce7a_.ent-d1qi7a_.ent", "d1ce7b2.ent-d1dqga_.ent", "d1ce7b2.ent-d1hwmb1.ent", "d1ce7b2.ent-d1hwmb2.ent", "d1ce7b2.ent-d1knma_.ent", "d1ceja1.ent-d1b9wa2.ent", "d1ceja1.ent-d1cvua2.ent", "d1ceja1.ent-d1dx5i1.ent", "d1ceja1.ent-d1emo_1.ent", "d1ceja1.ent-d1hz8a1.ent", "d1ceja1.ent-d1hz8a2.ent", "d1ceja1.ent-d1jl9a_.ent", "d1ceja1.ent-d1l3ya_.ent", "d1ceja1.ent-d1m1xb5.ent", "d1ceja1.ent-d1tpg_1.ent", "d1ceja1.ent-d1urk_1.ent", "d1ceja2.ent-d1b9wa1.ent", "d1ceja2.ent-d1b9wa2.ent", "d1ceja2.ent-d1ceja1.ent", "d1ceja2.ent-d1cvua2.ent", "d1ceja2.ent-d1dx5i1.ent", "d1ceja2.ent-d1emo_1.ent", "d1ceja2.ent-d1hz8a1.ent", "d1ceja2.ent-d1hz8a2.ent", "d1ceja2.ent-d1ijqa2.ent", "d1ceja2.ent-d1ioxa_.ent", "d1ceja2.ent-d1jl9a_.ent", "d1ceja2.ent-d1klo_3.ent", "d1ceja2.ent-d1l3ya_.ent", "d1ceja2.ent-d1m1xb5.ent", "d1ceja2.ent-d1tpg_1.ent", "d1ceja2.ent-d1urk_1.ent", "d1ceja2.ent-d3tgf__.ent", "d1cewi_.ent-d1ea2a_.ent", "d1cewi_.ent-d1eeja2.ent", "d1cewi_.ent-d1eqka_.ent", "d1cewi_.ent-d1g96a_.ent", "d1cewi_.ent-d1gy7a_.ent", "d1cewi_.ent-d1ivwa2.ent", "d1cewi_.ent-d1ivwa3.ent", "d1cewi_.ent-d1jkgb_.ent", "d1cewi_.ent-d1ksia2.ent", "d1cewi_.ent-d1ksia3.ent", "d1cewi_.ent-d1kwia_.ent", "d1cewi_.ent-d1mola_.ent", "d1cewi_.ent-d1mwxa1.ent", "d1cewi_.ent-d1o7nb_.ent", "d1cewi_.ent-d1oaca2.ent", "d1cewi_.ent-d1stfi_.ent", "d1cewi_.ent-d1ugia_.ent", "d1cewi_.ent-d3stda_.ent", "d1cex__.ent-d1cf9a1.ent", "d1cex__.ent-d1e5da1.ent", "d1cex__.ent-d1euca2.ent", "d1cex__.ent-d1f4pa_.ent", "d1cex__.ent-d1f8ya_.ent", "d1cex__.ent-d1fuea_.ent", "d1cex__.ent-d1h05a_.ent", "d1cex__.ent-d1kwga3.ent", "d1cex__.ent-d1l7da2.ent", "d1cex__.ent-d1qo0d_.ent", "d1cex__.ent-d2naca2.ent", "d1cex__.ent-d7reqb2.ent", "d1cf2o1.ent-d1dssg1.ent", "d1cf2o2.ent-d1dih_2.ent", "d1cf2o2.ent-d1dpga2.ent", "d1cf2o2.ent-d1e5qa2.ent", "d1cf2o2.ent-d1ebfa2.ent", "d1cf2o2.ent-d1f06a2.ent", "d1cf2o2.ent-d1gr0a2.ent", "d1cf2o2.ent-d1h6da2.ent", "d1cf2o2.ent-d1j5pa3.ent", "d1cf2o2.ent-d1jkia2.ent", "d1cf2o2.ent-d1jn0a2.ent", "d1cf2o2.ent-d1lc0a2.ent", "d1cf2o2.ent-d1mb4a2.ent", "d1cf2o2.ent-d1qkia2.ent", "d1cf9a1.ent-d1e5da1.ent", "d1cf9a1.ent-d1f4pa_.ent", "d1cf9a1.ent-d1f8ya_.ent", "d1cf9a1.ent-d1fyea_.ent", "d1cf9a1.ent-d1gpma2.ent", "d1cf9a1.ent-d1h05a_.ent", "d1cf9a1.ent-d1i7qb_.ent", "d1cf9a1.ent-d1k9vf_.ent", "d1cf9a1.ent-d1ka9h_.ent", "d1cf9a1.ent-d1kwga3.ent", "d1cf9a1.ent-d1l9xa_.ent", "d1cf9a1.ent-d1qdlb_.ent", "d1cf9a2.ent-d1dgfa_.ent", "d1cf9a2.ent-d1gwea_.ent", "d1cf9a2.ent-d1m7sa_.ent", "d1cfb_1.ent-d1cd9b2.ent", "d1cfb_1.ent-d1f6fb1.ent", "d1cfb_1.ent-d1f6fb2.ent", "d1cfb_1.ent-d1fyhb1.ent", "d1cfb_1.ent-d1i1ra1.ent", "d1cfb_1.ent-d1lqsr1.ent", "d1cfb_2.ent-d1bpv__.ent", "d1cfb_2.ent-d1cd9b2.ent", "d1cfb_2.ent-d1cfb_1.ent", "d1cfb_2.ent-d1eerb2.ent", "d1cfb_2.ent-d1egja_.ent", "d1cfb_2.ent-d1f6fb1.ent", "d1cfb_2.ent-d1f6fb2.ent", "d1cfb_2.ent-d1fyhb1.ent", "d1cfb_2.ent-d1fyhb2.ent", "d1cfb_2.ent-d1gh7a1.ent", "d1cfb_2.ent-d1i1ra1.ent", "d1cfb_2.ent-d1lqsr1.ent", "d1cfb_2.ent-d1n26a2.ent", "d1cfb_2.ent-d1n26a3.ent", "d1cfb_2.ent-d1qg3a2.ent", "d1cfb_2.ent-d2hft_1.ent", "d1cfb_2.ent-d2hft_2.ent", "d1cfr__.ent-d1ckqa_.ent", "d1cfr__.ent-d1d02a_.ent", "d1cfr__.ent-d1dc1a_.ent", "d1cfr__.ent-d1dmua_.ent", "d1cfr__.ent-d1dzfa1.ent", "d1cfr__.ent-d1ev7a_.ent", "d1cfr__.ent-d1f1za2.ent", "d1cfr__.ent-d1fiua_.ent", "d1cfr__.ent-d1gefa_.ent", "d1cfr__.ent-d1hh1a_.ent", "d1cfr__.ent-d1kc6a_.ent", "d1cfr__.ent-d1knva_.ent", "d1cfr__.ent-d1m0da_.ent", "d1cfr__.ent-d1vsra_.ent", "d1cfr__.ent-d2foka4.ent", "d1cfr__.ent-d3pvia_.ent", "d1cfya_.ent-d1d0na3.ent", "d1cfya_.ent-d1d0na4.ent", "d1cfya_.ent-d1d0na5.ent", "d1cfya_.ent-d1d0na6.ent", "d1cfya_.ent-d1d4xg_.ent", "d1cfya_.ent-d1f7sa_.ent", "d1cfya_.ent-d1hqz1_.ent", "d1cfya_.ent-d1jhwa3.ent", "d1cfya_.ent-d1m4ja_.ent", "d1cfza_.ent-d1je0a_.ent", "d1cfza_.ent-d1lam_2.ent", "d1cfza_.ent-d1lfwa1.ent", "d1cfza_.ent-d1loka_.ent", "d1cfza_.ent-d1m4la_.ent", "d1cfza_.ent-d2pth__.ent", "d1cg2a1.ent-d1de4c3.ent", "d1cg2a1.ent-d1gyta2.ent", "d1cg2a1.ent-d1h8la2.ent", "d1cg2a1.ent-d1jqga1.ent", "d1cg2a1.ent-d1kwma1.ent", "d1cg2a1.ent-d1lam_2.ent", "d1cg2a1.ent-d1lfwa1.ent", "d1cg2a1.ent-d1loka_.ent", "d1cg2a1.ent-d1m4la_.ent", "d1cg2a1.ent-d1obr__.ent", "d1cg5a_.ent-d1cg5b_", "d1cg5a_.ent-d1cg5b_.ent", "d1cg5a_.ent-d1ew6a_", "d1cg5a_.ent-d1ew6a_.ent", "d1cg5a_.ent-d1gcva_", "d1cg5a_.ent-d1gcva_.ent", "d1cg5a_.ent-d1irda_", "d1cg5a_.ent-d1irda_.ent", "d1cg5a_.ent-d1itha_", "d1cg5a_.ent-d1itha_.ent", "d1cg5b_.ent-d1ew6a_", "d1cg5b_.ent-d1ew6a_.ent", "d1cg5b_.ent-d1gcva_", "d1cg5b_.ent-d1gcva_.ent", "d1cg5b_.ent-d1irda_", "d1cg5b_.ent-d1irda_.ent", "d1cg5b_.ent-d1itha_", "d1cg5b_.ent-d1itha_.ent", "d1cgha_.ent-d1gdna_.ent", "d1cgha_.ent-d1hj9a_.ent", "d1cgme_.ent-d1ei7a_.ent", "d1cgme_.ent-d1rmva_.ent", "d1chc__.ent-d1e4ua_.ent", "d1chc__.ent-d1fbva4.ent", "d1chc__.ent-d1g25a_.ent", "d1chc__.ent-d1jm7a_.ent", "d1chc__.ent-d1jm7b_.ent", "d1chc__.ent-d1ldjb_.ent", "d1chc__.ent-d1rmd_2.ent", "d1chka_.ent-d1dxja_.ent", "d1chka_.ent-d1gd6a_.ent", "d1chka_.ent-d1k28a3.ent", "d1chka_.ent-d1qgia_.ent", "d1chka_.ent-d1qsaa2.ent", "d1chka_.ent-d1qusa_.ent", "d1chka_.ent-d217l__.ent", "d1chka_.ent-d2eql__.ent", "d1chka_.ent-d3lzt__.ent", "d1chma2.ent-d1o0xa_.ent", "d1chma2.ent-d1xgsa2.ent", "d1chua1.ent-d1e2aa_.ent", "d1chua1.ent-d1fjgt_.ent", "d1chua1.ent-d1g73a_.ent", "d1chua1.ent-d1hcia1.ent", "d1chua1.ent-d1hcia4.ent", "d1chua1.ent-d1hx1b_.ent", "d1chua1.ent-d1jnra1.ent", "d1chua1.ent-d1kf6a1.ent", "d1chua1.ent-d1m7ka_.ent", "d1chua1.ent-d1neka1.ent", "d1chua1.ent-d1qlaa1.ent", "d1chua1.ent-d1quua1.ent", "d1chua1.ent-d1quua2.ent", "d1chua1.ent-d2spca_.ent", "d1chua2.ent-d1cjca1.ent", "d1chua2.ent-d1ebda1.ent", "d1chua2.ent-d1feca1.ent", "d1chua2.ent-d1h6va1.ent", "d1chua2.ent-d1jeha1.ent", "d1chua2.ent-d1ojt_1.ent", "d1chua2.ent-d3lada1.ent", "d1chua3.ent-d1jnra3.ent", "d1chua3.ent-d1kf6a3.ent", "d1chua3.ent-d1kssa3.ent", "d1chua3.ent-d1neka3.ent", "d1chua3.ent-d1qlaa3.ent", "d1chua3.ent-d1qo8a3.ent", "d1ci0a_.ent-d1ejea_.ent", "d1ci0a_.ent-d1flma_.ent", "d1ci0a_.ent-d1i0ra_.ent", "d1ci0a_.ent-d1nrga_.ent", "d1ci9a_.ent-d1e25a_.ent", "d1ci9a_.ent-d1ei5a3.ent", "d1ci9a_.ent-d1es5a_.ent", "d1ci9a_.ent-d1g6aa_.ent", "d1ci9a_.ent-d1ghpa_.ent", "d1ci9a_.ent-d1iyoa_.ent", "d1ci9a_.ent-d1l0ga_.ent", "d1ci9a_.ent-d1m40a_.ent", "d1ci9a_.ent-d1mfoa_.ent", "d1ci9a_.ent-d1mwxa3.ent", "d1ci9a_.ent-d1nj4a2.ent", "d1ci9a_.ent-d1qmea4.ent", "d1ci9a_.ent-d4blma_.ent", "d1cii_1.ent-d1cola_.ent", "d1cixa_.ent-d1d1ha_.ent", "d1cixa_.ent-d1dl0a_.ent", "d1cixa_.ent-d1eit__.ent", "d1cixa_.ent-d1emxa_.ent", "d1cixa_.ent-d1g9pa_.ent", "d1cixa_.ent-d1i25a_.ent", "d1cixa_.ent-d1i26a_.ent", "d1cixa_.ent-d1i2ua_.ent", "d1cixa_.ent-d1imt_2.ent", "d1cixa_.ent-d1koza_.ent", "d1cixa_.ent-d1kqha_.ent", "d1cixa_.ent-d1lqra_.ent", "d1cixa_.ent-d1lupa_.ent", "d1cixa_.ent-d1nixa_.ent", "d1cixa_.ent-d1niya_.ent", "d1cixa_.ent-d1qk6a_.ent", "d1cixa_.ent-d1qk7a_.ent", "d1cixa_.ent-d1vtx__.ent", "d1ciy_1.ent-d1d7pm_.ent", "d1ciy_1.ent-d1dlc_1.ent", "d1ciy_1.ent-d1eut_2.ent", "d1ciy_1.ent-d1gmma_.ent", "d1ciy_1.ent-d1gnya_.ent", "d1ciy_1.ent-d1gu3a_.ent", "d1ciy_1.ent-d1guia_.ent", "d1ciy_1.ent-d1h6ya_.ent", "d1ciy_1.ent-d1i5pa1.ent", "d1ciy_1.ent-d1jhja_.ent", "d1ciy_1.ent-d1ju3a1.ent", "d1ciy_1.ent-d1jz8a3.ent", "d1ciy_1.ent-d1k12a_.ent", "d1ciy_1.ent-d1k3ia2.ent", "d1ciy_1.ent-d1kgya_.ent", "d1ciy_1.ent-d1l7la_.ent", "d1ciy_1.ent-d1lnsa2.ent", "d1ciy_1.ent-d1xnaa_.ent", "d1ciy_2.ent-d1i5pa2.ent", "d1ciy_2.ent-d1ji6a2.ent", "d1ciy_2.ent-d1vmoa_.ent", "d1ciy_3.ent-d1cola_.ent", "d1ciy_3.ent-d1ddba_.ent", "d1ciy_3.ent-d1f0la3.ent", "d1ciy_3.ent-d1i5pa3.ent", "d1ciy_3.ent-d1ikpa3.ent", "d1ciy_3.ent-d1ji6a3.ent", "d1ciy_3.ent-d1k3ka_.ent", "d1ciy_3.ent-d1maz__.ent", "d1cjaa_.ent-d1a06__.ent", "d1cjaa_.ent-d1b6cb_.ent", "d1cjaa_.ent-d1blxa_.ent", "d1cjaa_.ent-d1csn__.ent", "d1cjaa_.ent-d1e8xa4.ent", "d1cjaa_.ent-d1f3mc_.ent", "d1cjaa_.ent-d1fgka_.ent", "d1cjaa_.ent-d1fvra_.ent", "d1cjaa_.ent-d1ia9a_.ent", "d1cjaa_.ent-d1iepa_.ent", "d1cjaa_.ent-d1j7la_.ent", "d1cjaa_.ent-d1jksa_.ent", "d1cjaa_.ent-d1jpaa_.ent", "d1cjaa_.ent-d1jvpp_.ent", "d1cjaa_.ent-d1kwpa_.ent", "d1cjaa_.ent-d1lpua_.ent", "d1cjaa_.ent-d1lufa_.ent", "d1cjaa_.ent-d1m14a_.ent", "d1cjaa_.ent-d1phk__.ent", "d1cjaa_.ent-d1tkia_.ent", "d1cjca1.ent-d1ebda1.ent", "d1cjca2.ent-d1gtea4.ent", "d1cjca2.ent-d1i8ta1.ent", "d1cjca2.ent-d1lqta2.ent", "d1cjca2.ent-d1o94a3.ent", "d1cjwa_.ent-d1fy7a_.ent", "d1cjwa_.ent-d1i12a_.ent", "d1cjwa_.ent-d1iica2.ent", "d1cjwa_.ent-d1iyka1.ent", "d1cjwa_.ent-d1iyka2.ent", "d1cjwa_.ent-d1kzfa_.ent", "d1cjwa_.ent-d1lrza2.ent", "d1cjwa_.ent-d1lrza3.ent", "d1cjwa_.ent-d1m4ia_.ent", "d1cjwa_.ent-d1qsma_.ent", "d1cjwa_.ent-d1qsta_.ent", "d1cjxa1.ent-d1ecsa_.ent", "d1cjxa1.ent-d1f9za_.ent", "d1cjxa1.ent-d1kw3b1.ent", "d1cjxa1.ent-d1kw3b2.ent", "d1cjxa1.ent-d1lqpa_.ent", "d1cjxa1.ent-d1mpya1.ent", "d1cjxa1.ent-d1mpya2.ent", "d1cjxa1.ent-d1qipa_.ent", "d1cjxa1.ent-d1qtoa_.ent", "d1cjya2.ent-d1mla_1.ent", "d1cjya2.ent-d1nm2a1.ent", "d1ck9a_.ent-d1clia1.ent", "d1ck9a_.ent-d1dbfa_.ent", "d1ck9a_.ent-d1dt9a2.ent", "d1ck9a_.ent-d1e7ka_.ent", "d1ck9a_.ent-d1fsz_2.ent", "d1ck9a_.ent-d1ipaa2.ent", "d1ck9a_.ent-d1iv3a_.ent", "d1ck9a_.ent-d1jj2f_.ent", "d1ck9a_.ent-d1tuba2.ent", "d1ckla1.ent-d1ckla2.ent", "d1ckla1.ent-d1elva2.ent", "d1ckla1.ent-d1g40a1.ent", "d1ckla1.ent-d1g40a2.ent", "d1ckla1.ent-d1g40a3.ent", "d1ckla1.ent-d1g40a4.ent", "d1ckla1.ent-d1gkga2.ent", "d1ckla1.ent-d1gkna1.ent", "d1ckla1.ent-d1gkna2.ent", "d1ckla1.ent-d1gpza2.ent", "d1ckla1.ent-d1gpza3.ent", "d1ckla1.ent-d1hcc__.ent", "d1ckla1.ent-d1hfi__.ent", "d1ckla1.ent-d1ly2a1.ent", "d1ckla1.ent-d1ly2a2.ent", "d1ckla1.ent-d1quba1.ent", "d1ckla1.ent-d1quba2.ent", "d1ckla1.ent-d1quba3.ent", "d1ckla1.ent-d1quba4.ent", "d1ckla1.ent-d1quba5.ent", "d1ckla2.ent-d1elva2.ent", "d1ckla2.ent-d1g40a1.ent", "d1ckla2.ent-d1g40a2.ent", "d1ckla2.ent-d1g40a3.ent", "d1ckla2.ent-d1g40a4.ent", "d1ckla2.ent-d1gkga2.ent", "d1ckla2.ent-d1gkna1.ent", "d1ckla2.ent-d1gkna2.ent", "d1ckla2.ent-d1gpza2.ent", "d1ckla2.ent-d1gpza3.ent", "d1ckla2.ent-d1hcc__.ent", "d1ckla2.ent-d1hfi__.ent", "d1ckla2.ent-d1ly2a1.ent", "d1ckla2.ent-d1ly2a2.ent", "d1ckla2.ent-d1quba1.ent", "d1ckla2.ent-d1quba2.ent", "d1ckla2.ent-d1quba3.ent", "d1ckla2.ent-d1quba4.ent", "d1ckla2.ent-d1quba5.ent", "d1ckma2.ent-d1dgsa3.ent", "d1ckma2.ent-d1eucb2.ent", "d1ckma2.ent-d1fvia2.ent", "d1ckma2.ent-d1gsa_2.ent", "d1ckma2.ent-d1gsoa3.ent", "d1ckma2.ent-d1iow_2.ent", "d1ckma2.ent-d1kbla3.ent", "d1ckma2.ent-d1kjqa3.ent", "d1ckma2.ent-d1m0wa2.ent", "d1ckqa_.ent-d1d02a_.ent", "d1ckqa_.ent-d1dc1a_.ent", "d1ckqa_.ent-d1dmua_.ent", "d1ckqa_.ent-d1dzfa1.ent", "d1ckqa_.ent-d1ev7a_.ent", "d1ckqa_.ent-d1f1za2.ent", "d1ckqa_.ent-d1fiua_.ent", "d1ckqa_.ent-d1gefa_.ent", "d1ckqa_.ent-d1hh1a_.ent", "d1ckqa_.ent-d1kc6a_.ent", "d1ckqa_.ent-d1knva_.ent", "d1ckqa_.ent-d1m0da_.ent", "d1ckqa_.ent-d1vsra_.ent", "d1ckqa_.ent-d2foka4.ent", "d1ckqa_.ent-d3pvia_.ent", "d1ckta_.ent-d1hsm__.ent", "d1ckta_.ent-d1i11a_.ent", "d1ckta_.ent-d1k99a_.ent", "d1ckta_.ent-d1lwma_.ent", "d1ckta_.ent-d1qrva_.ent", "d1ckta_.ent-d2lefa_.ent", "d1ckv__.ent-d1g10a_.ent", "d1ckv__.ent-d1hqi__.ent", "d1clc_1.ent-d1faea_.ent", "d1clc_1.ent-d1fp3a_.ent", "d1clc_1.ent-d1gai__.ent", "d1clc_1.ent-d1h54a1.ent", "d1clc_1.ent-d1ia6a_.ent", "d1clc_1.ent-d1ks8a_.ent", "d1clc_1.ent-d1kwfa_.ent", "d1clc_1.ent-d1lf6a1.ent", "d1clia1.ent-d1dbfa_.ent", "d1clia1.ent-d1fsz_2.ent", "d1clia1.ent-d1ipaa2.ent", "d1clia1.ent-d1iv3a_.ent", "d1clia1.ent-d1jj2f_.ent", "d1clia1.ent-d1tuba2.ent", "d1cmba_.ent-d1irqa_.ent", "d1cmba_.ent-d1mnta_.ent", "d1cmba_.ent-d2cpga_.ent", "d1cmr__.ent-d1fjna_.ent", "d1cmr__.ent-d1gps__.ent", "d1cmr__.ent-d1i2ua_.ent", "d1cmr__.ent-d1ica__.ent", "d1cmr__.ent-d1jkza_.ent", "d1cmr__.ent-d1jxca_.ent", "d1cmr__.ent-d1myn__.ent", "d1cmr__.ent-d1npia_.ent", "d1cmr__.ent-d1nrb__.ent", "d1cmr__.ent-d1qkya_.ent", "d1cmr__.ent-d1sco__.ent", "d1cmr__.ent-d1scy__.ent", "d1cmr__.ent-d1sis__.ent", "d1cmr__.ent-d1tsk__.ent", "d1cmr__.ent-d2sn3__.ent", "d1cmxa_.ent-d1cv8__.ent", "d1cmxa_.ent-d1deua_.ent", "d1cmxa_.ent-d1dkia_.ent", "d1cmxa_.ent-d1e2ta_.ent", "d1cmxa_.ent-d1euva_.ent", "d1cmxa_.ent-d1f13a4.ent", "d1cmxa_.ent-d1fh0a_.ent", "d1cmxa_.ent-d1g0da4.ent", "d1cmxa_.ent-d1gmya_.ent", "d1cmxa_.ent-d1gx3a_.ent", "d1cmxa_.ent-d1iu4a_.ent", "d1cmxa_.ent-d1kxra_.ent", "d1cmxa_.ent-d1l9na4.ent", "d1cmxa_.ent-d1me4a_.ent", "d1cmxa_.ent-d1nbfa_.ent", "d1cmxa_.ent-d1ppn__.ent", "d1cmxa_.ent-d1qmya_.ent", "d1cmxa_.ent-d1uch__.ent", "d1cmxa_.ent-d2act__.ent", "d1cmxa_.ent-d2cb5a_.ent", "d1cmxa_.ent-d3gcb__.ent", "d1cmxa_.ent-d7pcka_.ent", "d1cmza_.ent-d1dk8a_.ent", "d1cmza_.ent-d1iapa_.ent", "d1cnoa_.ent-d1ctj__.ent", "d1cnoa_.ent-d1diqc_.ent", "d1cnoa_.ent-d1e29a_.ent", "d1cnoa_.ent-d1ezvd1.ent", "d1cnoa_.ent-d1fcdc2.ent", "d1cnoa_.ent-d1gu2a_.ent", "d1cnoa_.ent-d1h32a1.ent", "d1cnoa_.ent-d1iqca1.ent", "d1cnoa_.ent-d1iqca2.ent", "d1cnoa_.ent-d1jmxa1.ent", "d1cnoa_.ent-d1jmxa2.ent", "d1cnoa_.ent-d1kb0a1.ent", "d1cnoa_.ent-d1mg2d_.ent", "d1cnoa_.ent-d1qksa1.ent", "d1cnt1_.ent-d1d9ca_.ent", "d1cnt1_.ent-d1eera_.ent", "d1cnt1_.ent-d1etea_.ent", "d1cnt1_.ent-d1evsa_.ent", "d1cnt1_.ent-d1f45b_.ent", "d1cnt1_.ent-d1f6fa_.ent", "d1cnt1_.ent-d1hula_.ent", "d1cnt1_.ent-d1huw__.ent", "d1cnt1_.ent-d1hzia_.ent", "d1cnt1_.ent-d1i1rb_.ent", "d1cnt1_.ent-d1jli__.ent", "d1cnt1_.ent-d1lki__.ent", "d1cnt1_.ent-d1lqsl_.ent", "d1cnt1_.ent-d1m47a_.ent", "d1cnt1_.ent-d1n1fa_.ent", "d1cnt1_.ent-d2gmfa_.ent", "d1cnt1_.ent-d2ilk__.ent", "d1cnza_.ent-d1itwa_.ent", "d1cnza_.ent-d1lwda_.ent", "d1cnza_.ent-d1xaa__.ent", "d1co6a_.ent-d1etpa2.ent", "d1co6a_.ent-d1hroa_.ent", "d1co6a_.ent-d1kb0a1.ent", "d1co6a_.ent-d1kv9a1.ent", "d1co6a_.ent-d1ql3a_.ent", "d1co6a_.ent-d1qn2a_.ent", "d1coja1.ent-d1cxzb_.ent", "d1coja1.ent-d1du2a_.ent", "d1coja1.ent-d1e52a_.ent", "d1coja1.ent-d1e79h1.ent", "d1coja1.ent-d1eiya1.ent", "d1coja1.ent-d1fpoa1.ent", "d1coja1.ent-d1fxkc_.ent", "d1coja1.ent-d1gh6a_.ent", "d1coja1.ent-d1grj_1.ent", "d1coja1.ent-d1gv3a1.ent", "d1coja1.ent-d1hdj__.ent", "d1coja1.ent-d1isaa1.ent", "d1coja1.ent-d1ivsa1.ent", "d1coja1.ent-d1ix9a1.ent", "d1coja1.ent-d1jj2u_.ent", "d1coja1.ent-d1k4ta1.ent", "d1coja1.ent-d1lrza1.ent", "d1coja1.ent-d1seta1.ent", "d1coja2.ent-d1gv3a2.ent", "d1coja2.ent-d1isaa2.ent", "d1coja2.ent-d1ix9a2.ent", "d1coja2.ent-d1kkca2.ent", "d1coja2.ent-d1ma1a2.ent", "d1coja2.ent-d1qnna2.ent", "d1cola_.ent-d1ddba_.ent", "d1cola_.ent-d1f0la3.ent", "d1cola_.ent-d1ikpa3.ent", "d1cola_.ent-d1k3ka_.ent", "d1cola_.ent-d1maz__.ent", "d1cot__.ent-d1co6a_.ent", "d1cot__.ent-d1dw0a_.ent", "d1cot__.ent-d1etpa2.ent", "d1cot__.ent-d1hroa_.ent", "d1cot__.ent-d1kb0a1.ent", "d1cot__.ent-d1kv9a1.ent", "d1cot__.ent-d1nira1.ent", "d1cot__.ent-d1ql3a_.ent", "d1cot__.ent-d1qn2a_.ent", "d1cot__.ent-d1ycc__.ent", "d1cot__.ent-d3c2c__.ent", "d1coua_.ent-d1eaic_.ent", "d1coua_.ent-d1hx2a_.ent", "d1coza_.ent-d1ej2a_.ent", "d1coza_.ent-d1f4la2.ent", "d1coza_.ent-d1f7ua2.ent", "d1coza_.ent-d1ffya3.ent", "d1coza_.ent-d1g8fa2.ent", "d1coza_.ent-d1gtra2.ent", "d1coza_.ent-d1h3fa1.ent", "d1coza_.ent-d1h3na3.ent", "d1coza_.ent-d1ihoa_.ent", "d1coza_.ent-d1ile_3.ent", "d1coza_.ent-d1iq0a2.ent", "d1coza_.ent-d1irxa2.ent", "d1coza_.ent-d1ivsa4.ent", "d1coza_.ent-d1j09a2.ent", "d1coza_.ent-d1jhda2.ent", "d1coza_.ent-d1jila_.ent", "d1coza_.ent-d1k4ma_.ent", "d1coza_.ent-d1kama_.ent", "d1coza_.ent-d1kqna_.ent", "d1coza_.ent-d1li5a2.ent", "d1coza_.ent-d1n3la_.ent", "d1coza_.ent-d1qjca_.ent", "d1cp3a_.ent-d1cvra2.ent", "d1cp3a_.ent-d1jxqa_.ent", "d1cpo_2.ent-d1ctda_.ent", "d1cpo_2.ent-d1dqea_.ent", "d1cpo_2.ent-d1eg3a1.ent", "d1cpo_2.ent-d1eg3a2.ent", "d1cpo_2.ent-d1el4a_.ent", "d1cpo_2.ent-d1fi6a_.ent", "d1cpo_2.ent-d1h8ba_.ent", "d1cpo_2.ent-d1iioa_.ent", "d1cpo_2.ent-d1j7qa_.ent", "d1cpo_2.ent-d1k94a_.ent", "d1cpo_2.ent-d1m45a_.ent", "d1cpo_2.ent-d1psra_.ent", "d1cpo_2.ent-d1qasa1.ent", "d1cpo_2.ent-d1rec__.ent", "d1cpo_2.ent-d1sra__.ent", "d1cpo_2.ent-d2cbla1.ent", "d1cpo_2.ent-d2pvba_.ent", "d1cpo_2.ent-d2sas__.ent", "d1cpo_2.ent-d2scpa_.ent", "d1cpq__.ent-d1gqaa_.ent", "d1cpq__.ent-d1jafa_.ent", "d1cpq__.ent-d1mqva_.ent", "d1cpq__.ent-d256ba_.ent", "d1cpq__.ent-d2ccya_.ent", "d1cpt__.ent-d1dt6a_.ent", "d1cpt__.ent-d1dz4a_.ent", "d1cpt__.ent-d1e9xa_.ent", "d1cpt__.ent-d1io7a_.ent", "d1cpt__.ent-d1jfba_.ent", "d1cpt__.ent-d1jipa_.ent", "d1cpt__.ent-d1jpza_.ent", "d1cpt__.ent-d1lfka_.ent", "d1cpt__.ent-d1n97a_.ent", "d1cpy__.ent-d1bu8a2.ent", "d1cpy__.ent-d1cr6a2.ent", "d1cpy__.ent-d1cvl__.ent", "d1cpy__.ent-d1hlga_.ent", "d1cpy__.ent-d1iz7a_.ent", "d1cpy__.ent-d1jjia_.ent", "d1cpy__.ent-d1jkma_.ent", "d1cpy__.ent-d1ju3a2.ent", "d1cpy__.ent-d1ku0a_.ent", "d1cpy__.ent-d1l7aa_.ent", "d1cpy__.ent-d1lnsa3.ent", "d1cpy__.ent-d1lzla_.ent", "d1cpy__.ent-d1qlwa_.ent", "d1cpy__.ent-d1qo7a_.ent", "d1cpy__.ent-d1qtra_.ent", "d1cpy__.ent-d1tca__.ent", "d1cpza_.ent-d1fe0a_.ent", "d1cpza_.ent-d1fvqa_.ent", "d1cpza_.ent-d1jwwa_.ent", "d1cpza_.ent-d1k0va_.ent", "d1cpza_.ent-d1mwza_.ent", "d1cqqa_.ent-d1gdna_.ent", "d1cqqa_.ent-d1hava_.ent", "d1cqqa_.ent-d1lcya2.ent", "d1cqqa_.ent-d1lvmb_.ent", "d1cqqa_.ent-d1lvoa_.ent", "d1cqqa_.ent-d1mbma_.ent", "d1cqqa_.ent-d1qq4a_.ent", "d1cqqa_.ent-d1svpa_.ent", "d1cqqa_.ent-d2hrva_.ent", "d1cqxa1.ent-d1ash__", "d1cqxa1.ent-d1ash__.ent", "d1cqxa1.ent-d1cg5a_", "d1cqxa1.ent-d1cg5a_.ent", "d1cqxa1.ent-d1cg5b_", "d1cqxa1.ent-d1cg5b_.ent", "d1cqxa1.ent-d1ew6a_", "d1cqxa1.ent-d1ew6a_.ent", "d1cqxa1.ent-d1gcva_", "d1cqxa1.ent-d1gcva_.ent", "d1cqxa1.ent-d1gvha1", "d1cqxa1.ent-d1gvha1.ent", "d1cqxa1.ent-d1h97a_", "d1cqxa1.ent-d1h97a_.ent", "d1cqxa1.ent-d1irda_", "d1cqxa1.ent-d1irda_.ent", "d1cqxa1.ent-d1irdb_", "d1cqxa1.ent-d1irdb_.ent", "d1cqxa1.ent-d1it2a_", "d1cqxa1.ent-d1it2a_.ent", "d1cqxa1.ent-d1itha_", "d1cqxa1.ent-d1itha_.ent", "d1cqxa1.ent-d1jl7a_", "d1cqxa1.ent-d1jl7a_.ent", "d1cqxa1.ent-d1la6a_", "d1cqxa1.ent-d1la6a_.ent", "d1cqxa1.ent-d1mba__", "d1cqxa1.ent-d1mba__.ent", "d1cqxa1.ent-d2lhb__", "d1cqxa1.ent-d2lhb__.ent", "d1cqxa1.ent-d3sdha_", "d1cqxa1.ent-d3sdha_.ent", "d1cqxa2.ent-d1ddga1.ent", "d1cqxa2.ent-d1ep3b1.ent", "d1cqxa2.ent-d1f20a1.ent", "d1cqxa2.ent-d1fdr_1.ent", "d1cqxa2.ent-d1fnc_1.ent", "d1cqxa2.ent-d1i7pa1.ent", "d1cqxa2.ent-d1i8da1.ent", "d1cqxa2.ent-d1i8da2.ent", "d1cqxa2.ent-d1ja1a1.ent", "d1cqxa2.ent-d1jb9a1.ent", "d1cqxa2.ent-d1krha1.ent", "d1cqxa2.ent-d1kzla1.ent", "d1cqxa2.ent-d1kzla2.ent", "d1cqxa2.ent-d1qfja1.ent", "d1cqxa2.ent-d1que_1.ent", "d1cqxa2.ent-d2cnd_1.ent", "d1cqxa2.ent-d2pia_1.ent", "d1cqxa3.ent-d1ddga2.ent", "d1cqxa3.ent-d1ep3b2.ent", "d1cqxa3.ent-d1f20a2.ent", "d1cqxa3.ent-d1fdr_2.ent", "d1cqxa3.ent-d1gvha3.ent", "d1cqxa3.ent-d1i7pa2.ent", "d1cqxa3.ent-d1ja1a3.ent", "d1cqxa3.ent-d1jb9a2.ent", "d1cqxa3.ent-d1krha2.ent", "d1cqxa3.ent-d1qfja2.ent", "d1cqxa3.ent-d1que_2.ent", "d1cqxa3.ent-d2cnd_2.ent", "d1cqxa3.ent-d2pia_2.ent", "d1cqya_.ent-d1pama2.ent", "d1cqya_.ent-d1qhoa2.ent", "d1cr1a_.ent-d1g8ya_.ent", "d1cr5a1.ent-d1cz4a1.ent", "d1cr5a1.ent-d1e32a1.ent", "d1cr5a1.ent-d1eu1a1.ent", "d1cr5a1.ent-d1g8ka1.ent", "d1cr5a1.ent-d1h0ha1.ent", "d1cr5a1.ent-d1kqfa1.ent", "d1cr5a1.ent-d1tmo_1.ent", "d1cr5a1.ent-d2napa1.ent", "d1cr5a2.ent-d1cz4a2.ent", "d1cr5a2.ent-d1e32a3.ent", "d1cr6a1.ent-d1eula2.ent", "d1cr6a1.ent-d1feza_.ent", "d1cr6a1.ent-d1k1ea_.ent", "d1cr6a1.ent-d1l6ra_.ent", "d1cr6a1.ent-d1mh9a_.ent", "d1cr6a1.ent-d1qq5a_.ent", "d1cr6a1.ent-d1zrn__.ent", "d1cr6a2.ent-d1cvl__.ent", "d1cr6a2.ent-d1iz7a_.ent", "d1cr6a2.ent-d1jjia_.ent", "d1cr6a2.ent-d1l7aa_.ent", "d1cr6a2.ent-d1lzla_.ent", "d1cr6a2.ent-d1qlwa_.ent", "d1cr6a2.ent-d1qtra_.ent", "d1cr6a2.ent-d1tca__.ent", "d1crua_.ent-d1e1aa_.ent", "d1crua_.ent-d1e8ua_.ent", "d1crua_.ent-d1f8ea_.ent", "d1crua_.ent-d1h6la_.ent", "d1crua_.ent-d1ijqa1.ent", "d1crua_.ent-d1k32a2.ent", "d1crua_.ent-d1kit_3.ent", "d1crua_.ent-d3sil__.ent", "d1crza2.ent-d1eexb_.ent", "d1crza2.ent-d1ex2a_.ent", "d1crza2.ent-d1h4vb1.ent", "d1crza2.ent-d1hc7a1.ent", "d1crza2.ent-d1nbwb_.ent", "d1crza2.ent-d1qe0a1.ent", "d1csei_.ent-d1dwma_.ent", "d1csei_.ent-d1lw6i_.ent", "d1csh__.ent-d1k3pa_.ent", "d1csh__.ent-d1o7xa_.ent", "d1csn__.ent-d1a06__.ent", "d1csn__.ent-d1f3mc_.ent", "d1csn__.ent-d1fgka_.ent", "d1csn__.ent-d1ia9a_.ent", "d1csn__.ent-d1iepa_.ent", "d1csn__.ent-d1jksa_.ent", "d1csn__.ent-d1jpaa_.ent", "d1csn__.ent-d1jvpp_.ent", "d1csn__.ent-d1lufa_.ent", "d1csn__.ent-d1phk__.ent", "d1ct9a1.ent-d1efpa1.ent", "d1ct9a1.ent-d1efva1.ent", "d1ct9a1.ent-d1efvb_.ent", "d1ct9a1.ent-d1gpma1.ent", "d1ct9a1.ent-d1jgta1.ent", "d1ct9a1.ent-d1jmva_.ent", "d1ct9a1.ent-d1k92a1.ent", "d1ct9a1.ent-d1kora1.ent", "d1ct9a1.ent-d1kqpa_.ent", "d1ct9a1.ent-d1mjha_.ent", "d1ct9a1.ent-d1o97c_.ent", "d1ct9a1.ent-d1o97d1.ent", "d1ct9a1.ent-d1sur__.ent", "d1ctda_.ent-d1dqea_.ent", "d1ctda_.ent-d1eg3a1.ent", "d1ctda_.ent-d1eg3a2.ent", "d1ctda_.ent-d1el4a_.ent", "d1ctda_.ent-d1fi6a_.ent", "d1ctda_.ent-d1h8ba_.ent", "d1ctda_.ent-d1iioa_.ent", "d1ctda_.ent-d1j7qa_.ent", "d1ctda_.ent-d1k94a_.ent", "d1ctda_.ent-d1m45a_.ent", "d1ctda_.ent-d1psra_.ent", "d1ctda_.ent-d1qasa1.ent", "d1ctda_.ent-d1rec__.ent", "d1ctda_.ent-d1sra__.ent", "d1ctda_.ent-d2cbla1.ent", "d1ctda_.ent-d2pvba_.ent", "d1ctda_.ent-d2sas__.ent", "d1ctda_.ent-d2scpa_.ent", "d1ctj__.ent-d1diqc_.ent", "d1ctj__.ent-d1e29a_.ent", "d1ctj__.ent-d1ezvd1.ent", "d1ctj__.ent-d1fcdc2.ent", "d1ctj__.ent-d1gu2a_.ent", "d1ctj__.ent-d1h32a1.ent", "d1ctj__.ent-d1iqca1.ent", "d1ctj__.ent-d1iqca2.ent", "d1ctj__.ent-d1jmxa1.ent", "d1ctj__.ent-d1jmxa2.ent", "d1ctj__.ent-d1kb0a1.ent", "d1ctj__.ent-d1mg2d_.ent", "d1ctj__.ent-d1qksa1.ent", "d1cuk_1.ent-d1efub3.ent", "d1cuk_1.ent-d1eija_.ent", "d1cuk_1.ent-d1enwa_.ent", "d1cuk_1.ent-d1f4ia_.ent", "d1cuk_1.ent-d1ifya_.ent", "d1cuk_1.ent-d1oaia_.ent", "d1cuk_2.ent-d1d8ba_.ent", "d1cuk_2.ent-d1dgsa1.ent", "d1cuk_2.ent-d1doqa_.ent", "d1cuk_2.ent-d1dxsa_.ent", "d1cuk_2.ent-d1f44a1.ent", "d1cuk_2.ent-d1floa1.ent", "d1cuk_2.ent-d1go3f_.ent", "d1cuk_2.ent-d1ixra1.ent", "d1cuk_2.ent-d1jmsa1.ent", "d1cuk_2.ent-d1jmsa3.ent", "d1cuk_2.ent-d1jyga_.ent", "d1cuk_2.ent-d1kfta_.ent", "d1cuk_2.ent-d1lb2b_.ent", "d1cuk_2.ent-d1tfr_1.ent", "d1cuna1.ent-d1cuna2.ent", "d1cuna1.ent-d1hcia1.ent", "d1cuna1.ent-d1hcia4.ent", "d1cuna1.ent-d1quua1.ent", "d1cuna1.ent-d1quua2.ent", "d1cuna1.ent-d2spca_.ent", "d1cuna2.ent-d1hcia1.ent", "d1cuna2.ent-d1hcia4.ent", "d1cuna2.ent-d1quua1.ent", "d1cuna2.ent-d1quua2.ent", "d1cuna2.ent-d2spca_.ent", "d1cv8__.ent-d1deua_.ent", "d1cv8__.ent-d1dkia_.ent", "d1cv8__.ent-d1e2ta_.ent", "d1cv8__.ent-d1euva_.ent", "d1cv8__.ent-d1f13a4.ent", "d1cv8__.ent-d1fh0a_.ent", "d1cv8__.ent-d1g0da4.ent", "d1cv8__.ent-d1gmya_.ent", "d1cv8__.ent-d1gx3a_.ent", "d1cv8__.ent-d1iu4a_.ent", "d1cv8__.ent-d1kxra_.ent", "d1cv8__.ent-d1l9na4.ent", "d1cv8__.ent-d1me4a_.ent", "d1cv8__.ent-d1nbfa_.ent", "d1cv8__.ent-d1ppn__.ent", "d1cv8__.ent-d1qmya_.ent", "d1cv8__.ent-d1uch__.ent", "d1cv8__.ent-d2act__.ent", "d1cv8__.ent-d2cb5a_.ent", "d1cv8__.ent-d3gcb__.ent", "d1cv8__.ent-d7pcka_.ent", "d1cvja1.ent-d1cvja2.ent", "d1cvja1.ent-d1fj7a_.ent", "d1cvja1.ent-d1fjeb2.ent", "d1cvja1.ent-d1fxla1.ent", "d1cvja1.ent-d1fxla2.ent", "d1cvja1.ent-d1h6kx_.ent", "d1cvja1.ent-d1hd1a_.ent", "d1cvja1.ent-d1iqta_.ent", "d1cvja1.ent-d1jmta_.ent", "d1cvja1.ent-d1koha2.ent", "d1cvja1.ent-d1l3ka1.ent", "d1cvja1.ent-d1l3ka2.ent", "d1cvja1.ent-d1nu4a_.ent", "d1cvja1.ent-d1qm9a1.ent", "d1cvja1.ent-d1qm9a2.ent", "d1cvja1.ent-d1u2fa_.ent", "d1cvja1.ent-d2msta_.ent", "d1cvja1.ent-d2u1a__.ent", "d1cvja1.ent-d2u2fa_.ent", "d1cvja2.ent-d1fj7a_.ent", "d1cvja2.ent-d1fjeb2.ent", "d1cvja2.ent-d1fxla1.ent", "d1cvja2.ent-d1fxla2.ent", "d1cvja2.ent-d1h6kx_.ent", "d1cvja2.ent-d1hd1a_.ent", "d1cvja2.ent-d1iqta_.ent", "d1cvja2.ent-d1jmta_.ent", "d1cvja2.ent-d1koha2.ent", "d1cvja2.ent-d1l3ka1.ent", "d1cvja2.ent-d1l3ka2.ent", "d1cvja2.ent-d1nu4a_.ent", "d1cvja2.ent-d1qm9a1.ent", "d1cvja2.ent-d1qm9a2.ent", "d1cvja2.ent-d1u2fa_.ent", "d1cvja2.ent-d2msta_.ent", "d1cvja2.ent-d2u1a__.ent", "d1cvja2.ent-d2u2fa_.ent", "d1cvl__.ent-d1iz7a_.ent", "d1cvl__.ent-d1jjia_.ent", "d1cvl__.ent-d1qtra_.ent", "d1cvra2.ent-d1jxqa_.ent", "d1cvua1.ent-d1itka1.ent", "d1cvua1.ent-d1itka2.ent", "d1cvua1.ent-d1jdra_.ent", "d1cvua1.ent-d1llp__.ent", "d1cvua1.ent-d1mn2__.ent", "d1cvua1.ent-d1pa2a_.ent", "d1cvua2.ent-d1hz8a1.ent", "d1cvua2.ent-d1hz8a2.ent", "d1cvua2.ent-d1l3ya_.ent", "d1cvua2.ent-d1tpg_1.ent", "d1cw3a_.ent-d1euha_.ent", "d1cw3a_.ent-d1ez0a_.ent", "d1cw3a_.ent-d1ky8a_.ent", "d1cwva1.ent-d1cwva2.ent", "d1cwva1.ent-d1cwva3.ent", "d1cwva1.ent-d1cwva4.ent", "d1cwva1.ent-d1f00i1.ent", "d1cwva1.ent-d1f00i2.ent", "d1cwva2.ent-d1cwva3.ent", "d1cwva2.ent-d1cwva4.ent", "d1cwva2.ent-d1f00i1.ent", "d1cwva2.ent-d1f00i2.ent", "d1cwva3.ent-d1cwva4.ent", "d1cwva3.ent-d1f00i1.ent", "d1cwva3.ent-d1f00i2.ent", "d1cwva4.ent-d1f00i1.ent", "d1cwva4.ent-d1f00i2.ent", "d1cwva5.ent-d1f00i3.ent", "d1cwva5.ent-d1g1ta1.ent", "d1cwva5.ent-d1h8ua_.ent", "d1cwva5.ent-d1kg0c_.ent", "d1cwva5.ent-d1koe__.ent", "d1cwva5.ent-d1li1a1.ent", "d1cwva5.ent-d1prea1.ent", "d1cwva5.ent-d1prtb2.ent", "d1cwva5.ent-d1qdda_.ent", "d1cwva5.ent-d1tsg__.ent", "d1cx1a_.ent-d1ciy_1.ent", "d1cx1a_.ent-d1dlc_1.ent", "d1cx1a_.ent-d1eut_2.ent", "d1cx1a_.ent-d1gmma_.ent", "d1cx1a_.ent-d1gnya_.ent", "d1cx1a_.ent-d1gu3a_.ent", "d1cx1a_.ent-d1ji6a1.ent", "d1cx1a_.ent-d1xnaa_.ent", "d1cx4a1.ent-d1cx4a2.ent", "d1cx4a1.ent-d1dcs__.ent", "d1cx4a1.ent-d1dgwa_.ent", "d1cx4a1.ent-d1ds1a_.ent", "d1cx4a1.ent-d1e5sa_.ent", "d1cx4a1.ent-d1ep0a_.ent", "d1cx4a1.ent-d1eula1.ent", "d1cx4a1.ent-d1fi2a_.ent", "d1cx4a1.ent-d1ft9a2.ent", "d1cx4a1.ent-d1fxza1.ent", "d1cx4a1.ent-d1gp6a_.ent", "d1cx4a1.ent-d1gy9a_.ent", "d1cx4a1.ent-d1h2ka_.ent", "d1cx4a1.ent-d1hw5a2.ent", "d1cx4a1.ent-d1ig0a1.ent", "d1cx4a1.ent-d1jr7a_.ent", "d1cx4a1.ent-d1juha_.ent", "d1cx4a1.ent-d1lrha_.ent", "d1cx4a1.ent-d1m4oa_.ent", "d1cx4a1.ent-d1o7fa2.ent", "d1cx4a1.ent-d1o7fa3.ent", "d1cx4a1.ent-d1pmi__.ent", "d1cx4a1.ent-d1rgs_1.ent", "d1cx4a1.ent-d1rgs_2.ent", "d1cx4a1.ent-d1wapa_.ent", "d1cx4a1.ent-d2arca_.ent", "d1cx4a2.ent-d1ft9a2.ent", "d1cx4a2.ent-d1hw5a2.ent", "d1cx4a2.ent-d1o7fa2.ent", "d1cx4a2.ent-d1o7fa3.ent", "d1cx4a2.ent-d1rgs_1.ent", "d1cx4a2.ent-d1rgs_2.ent", "d1cxc__.ent-d1co6a_.ent", "d1cxc__.ent-d1cot__.ent", "d1cxc__.ent-d1dw0a_.ent", "d1cxc__.ent-d1etpa2.ent", "d1cxc__.ent-d1gu2a_.ent", "d1cxc__.ent-d1hroa_.ent", "d1cxc__.ent-d1kb0a1.ent", "d1cxc__.ent-d1kv9a1.ent", "d1cxc__.ent-d1nira1.ent", "d1cxc__.ent-d1ql3a_.ent", "d1cxc__.ent-d1qn2a_.ent", "d1cxc__.ent-d1ycc__.ent", "d1cxc__.ent-d3c2c__.ent", "d1cxqa_.ent-d1exqa_.ent", "d1cxqa_.ent-d1fxxa_.ent", "d1cxqa_.ent-d1hjra_.ent", "d1cxqa_.ent-d1i39a_.ent", "d1cxqa_.ent-d1ih7a1.ent", "d1cxqa_.ent-d1io2a_.ent", "d1cxqa_.ent-d1j54a_.ent", "d1cxqa_.ent-d1jl1a_.ent", "d1cxqa_.ent-d1kcfa2.ent", "d1cxqa_.ent-d1kfsa1.ent", "d1cxqa_.ent-d1musa_.ent", "d1cxqa_.ent-d1qtma1.ent", "d1cxqa_.ent-d1t7pa1.ent", "d1cxqa_.ent-d1tgoa1.ent", "d1cxqa_.ent-d1vrta1.ent", "d1cxqa_.ent-d1xwl_1.ent", "d1cxya_.ent-d1cyo__.ent", "d1cxya_.ent-d1kbia2.ent", "d1cxzb_.ent-d1du2a_.ent", "d1cxzb_.ent-d1e52a_.ent", "d1cxzb_.ent-d1e79h1.ent", "d1cxzb_.ent-d1eiya1.ent", "d1cxzb_.ent-d1fpoa1.ent", "d1cxzb_.ent-d1fxkc_.ent", "d1cxzb_.ent-d1gh6a_.ent", "d1cxzb_.ent-d1grj_1.ent", "d1cxzb_.ent-d1hdj__.ent", "d1cxzb_.ent-d1ivsa1.ent", "d1cxzb_.ent-d1ix9a1.ent", "d1cxzb_.ent-d1jj2u_.ent", "d1cxzb_.ent-d1k4ta1.ent", "d1cxzb_.ent-d1lrza1.ent", "d1cxzb_.ent-d1seta1.ent", "d1cy9a_.ent-d1gkub3.ent", "d1cy9a_.ent-d1i7da_.ent", "d1cyo__.ent-d1kbia2.ent", "d1cyx__.ent-d1e30a_.ent", "d1cyx__.ent-d1ikop_.ent", "d1cyx__.ent-d1kbva1.ent", "d1cyx__.ent-d1kbva2.ent", "d1cyx__.ent-d1kcw_2.ent", "d1cyx__.ent-d1kcw_4.ent", "d1cyx__.ent-d1kcw_6.ent", "d1cyx__.ent-d1kv7a1.ent", "d1cyx__.ent-d1kv7a3.ent", "d1cyx__.ent-d1qhqa_.ent", "d1cz1a_.ent-d1d3ga_.ent", "d1cz1a_.ent-d1e43a2.ent", "d1cz1a_.ent-d1edg__.ent", "d1cz1a_.ent-d1gvoa_.ent", "d1cz1a_.ent-d1gw1a_.ent", "d1cz1a_.ent-d1iexa1.ent", "d1cz1a_.ent-d1itua_.ent", "d1cz1a_.ent-d1j0ha3.ent", "d1cz1a_.ent-d1k4ga_.ent", "d1cz1a_.ent-d1kbla1.ent", "d1cz1a_.ent-d1kwga2.ent", "d1cz1a_.ent-d1lwha2.ent", "d1cz1a_.ent-d1m7ja3.ent", "d1cz1a_.ent-d1muwa_.ent", "d1cz1a_.ent-d7taa_2.ent", "d1cz4a1.ent-d1e32a1.ent", "d1cz4a1.ent-d1eu1a1.ent", "d1cz4a1.ent-d1g8ka1.ent", "d1cz4a1.ent-d1h0ha1.ent", "d1cz4a1.ent-d1kqfa1.ent", "d1cz4a1.ent-d1n10a2.ent", "d1cz4a1.ent-d1tmo_1.ent", "d1cz4a1.ent-d2napa1.ent", "d1cz4a2.ent-d1e32a3.ent", "d1czan1.ent-d1az9_1.ent", "d1czan1.ent-d1bupa1.ent", "d1czan1.ent-d1bupa2.ent", "d1czan1.ent-d1czan2.ent", "d1czan1.ent-d1czan3.ent", "d1czan1.ent-d1dkgd2.ent", "d1czan1.ent-d1e4ft1.ent", "d1czan1.ent-d1e4ft2.ent", "d1czan1.ent-d1g99a1.ent", "d1czan1.ent-d1g99a2.ent", "d1czan1.ent-d1glag1.ent", "d1czan1.ent-d1glag2.ent", "d1czan1.ent-d1huxa_.ent", "d1czan1.ent-d1ig8a1.ent", "d1czan1.ent-d1ig8a2.ent", "d1czan1.ent-d1j54a_.ent", "d1czan1.ent-d1j6za2.ent", "d1czan1.ent-d1jcfa1.ent", "d1czan1.ent-d1jj2m_.ent", "d1czan1.ent-d1k8ka1.ent", "d1czan1.ent-d1kcfa2.ent", "d1czan1.ent-d1mwma1.ent", "d1czan1.ent-d1mwma2.ent", "d1czan1.ent-d1nbwa2.ent", "d1czan1.ent-d1nbwa3.ent", "d1czan1.ent-d1t7pa1.ent", "d1czan1.ent-d1xwl_1.ent", "d1czan2.ent-d1az9_1.ent", "d1czan2.ent-d1bco_2.ent", "d1czan2.ent-d1bupa1.ent", "d1czan2.ent-d1bupa2.ent", "d1czan2.ent-d1czan1.ent", "d1czan2.ent-d1czan3.ent", "d1czan2.ent-d1dkgd2.ent", "d1czan2.ent-d1e4ft1.ent", "d1czan2.ent-d1e4ft2.ent", "d1czan2.ent-d1g99a1.ent", "d1czan2.ent-d1g99a2.ent", "d1czan2.ent-d1glag1.ent", "d1czan2.ent-d1glag2.ent", "d1czan2.ent-d1huxa_.ent", "d1czan2.ent-d1ig8a1.ent", "d1czan2.ent-d1ig8a2.ent", "d1czan2.ent-d1j54a_.ent", "d1czan2.ent-d1j6za2.ent", "d1czan2.ent-d1jcfa1.ent", "d1czan2.ent-d1jj2m_.ent", "d1czan2.ent-d1k8ka1.ent", "d1czan2.ent-d1kcfa2.ent", "d1czan2.ent-d1mwma1.ent", "d1czan2.ent-d1mwma2.ent", "d1czan2.ent-d1nbwa2.ent", "d1czan2.ent-d1nbwa3.ent", "d1czan2.ent-d1t7pa1.ent", "d1czan2.ent-d1xwl_1.ent", "d1czan3.ent-d1dkgd2.ent", "d1czan3.ent-d1e4ft1.ent", "d1czan3.ent-d1e4ft2.ent", "d1czan3.ent-d1g99a1.ent", "d1czan3.ent-d1g99a2.ent", "d1czan3.ent-d1glag1.ent", "d1czan3.ent-d1glag2.ent", "d1czan3.ent-d1huxa_.ent", "d1czan3.ent-d1ig8a1.ent", "d1czan3.ent-d1ig8a2.ent", "d1czan3.ent-d1j6za2.ent", "d1czan3.ent-d1jcfa1.ent", "d1czan3.ent-d1k8ka1.ent", "d1czan3.ent-d1mwma1.ent", "d1czan3.ent-d1mwma2.ent", "d1czan3.ent-d1nbwa2.ent", "d1czan3.ent-d1nbwa3.ent", "d1czfa_.ent-d1daba_.ent", "d1czfa_.ent-d1dbga_.ent", "d1czfa_.ent-d1ee6a_.ent", "d1czfa_.ent-d1hg8a_.ent", "d1czfa_.ent-d1jtaa_.ent", "d1czfa_.ent-d1k5ca_.ent", "d1czfa_.ent-d1qcxa_.ent", "d1czfa_.ent-d1qjva_.ent", "d1czfa_.ent-d1qq1a_.ent", "d1czfa_.ent-d1rmg__.ent", "d1czpa_.ent-d1bmlc3.ent", "d1czpa_.ent-d1c9fa_.ent", "d1czpa_.ent-d1doi__.ent", "d1czpa_.ent-d1e9ma_.ent", "d1czpa_.ent-d1feha2.ent", "d1czpa_.ent-d1fm0d_.ent", "d1czpa_.ent-d1fo4a2.ent", "d1czpa_.ent-d1h4ra3.ent", "d1czpa_.ent-d1h8ca_.ent", "d1czpa_.ent-d1hlra2.ent", "d1czpa_.ent-d1i42a_.ent", "d1czpa_.ent-d1i7ha_.ent", "d1czpa_.ent-d1ip9a_.ent", "d1czpa_.ent-d1jq4a_.ent", "d1czpa_.ent-d1jroa2.ent", "d1czpa_.ent-d1k8rb_.ent", "d1czpa_.ent-d1kf6b2.ent", "d1czpa_.ent-d1krha3.ent", "d1czpa_.ent-d1l5pa_.ent", "d1czpa_.ent-d1l7ya_.ent", "d1czpa_.ent-d1lfda_.ent", "d1czpa_.ent-d1n62a2.ent", "d1czpa_.ent-d1nekb2.ent", "d1czpa_.ent-d1put__.ent", "d1czpa_.ent-d1qlab2.ent", "d1czpa_.ent-d2pia_3.ent", "d1czsa_.ent-d1ciy_1.ent", "d1czsa_.ent-d1cx1a_.ent", "d1czsa_.ent-d1d7pm_.ent", "d1czsa_.ent-d1dlc_1.ent", "d1czsa_.ent-d1eut_2.ent", "d1czsa_.ent-d1gmma_.ent", "d1czsa_.ent-d1gnya_.ent", "d1czsa_.ent-d1gu3a_.ent", "d1czsa_.ent-d1guia_.ent", "d1czsa_.ent-d1h6ya_.ent", "d1czsa_.ent-d1ji6a1.ent", "d1czsa_.ent-d1k12a_.ent", "d1czsa_.ent-d1kexa_.ent", "d1czsa_.ent-d1xnaa_.ent", "d1czya1.ent-d1k2fa_.ent", "d1czya1.ent-d1lb6a_.ent", "d1d02a_.ent-d1dc1a_.ent", "d1d02a_.ent-d1dmua_.ent", "d1d02a_.ent-d1dzfa1.ent", "d1d02a_.ent-d1ev7a_.ent", "d1d02a_.ent-d1f1za2.ent", "d1d02a_.ent-d1fiua_.ent", "d1d02a_.ent-d1gefa_.ent", "d1d02a_.ent-d1hh1a_.ent", "d1d02a_.ent-d1kc6a_.ent", "d1d02a_.ent-d1knva_.ent", "d1d02a_.ent-d1m0da_.ent", "d1d02a_.ent-d1vsra_.ent", "d1d02a_.ent-d2foka4.ent", "d1d02a_.ent-d3pvia_.ent", "d1d09b2.ent-d1d0qa_.ent", "d1d09b2.ent-d1dxga_.ent", "d1d09b2.ent-d1f4la3.ent", "d1d09b2.ent-d1gh9a_.ent", "d1d09b2.ent-d1i50i1.ent", "d1d09b2.ent-d1i50i2.ent", "d1d09b2.ent-d1i50l_.ent", "d1d09b2.ent-d1jj22_.ent", "d1d09b2.ent-d1jj2y_.ent", "d1d09b2.ent-d1jj2z_.ent", "d1d09b2.ent-d1lkoa2.ent", "d1d09b2.ent-d1m2oa5.ent", "d1d09b2.ent-d1ocrf_.ent", "d1d09b2.ent-d1pft__.ent", "d1d09b2.ent-d1rb9__.ent", "d1d09b2.ent-d1tfi__.ent", "d1d09b2.ent-d1yua_1.ent", "d1d09b2.ent-d1yua_2.ent", "d1d09b2.ent-d1zaka2.ent", "d1d09b2.ent-d1zin_2.ent", "d1d0da_.ent-d1g6xa_.ent", "d1d0da_.ent-d1irha_.ent", "d1d0da_.ent-d1ktha_.ent", "d1d0da_.ent-d1tfxc_.ent", "d1d0da_.ent-d1tocr1.ent", "d1d0da_.ent-d1tocr2.ent", "d1d0na3.ent-d1d0na4.ent", "d1d0na3.ent-d1d0na5.ent", "d1d0na3.ent-d1d0na6.ent", "d1d0na3.ent-d1d4xg_.ent", "d1d0na3.ent-d1f7sa_.ent", "d1d0na3.ent-d1hqz1_.ent", "d1d0na3.ent-d1jhwa3.ent", "d1d0na3.ent-d1m2oa4.ent", "d1d0na3.ent-d1m2vb4.ent", "d1d0na3.ent-d1m4ja_.ent", "d1d0na4.ent-d1d0na5.ent", "d1d0na4.ent-d1d0na6.ent", "d1d0na4.ent-d1d4xg_.ent", "d1d0na4.ent-d1f7sa_.ent", "d1d0na4.ent-d1hqz1_.ent", "d1d0na4.ent-d1jhwa3.ent", "d1d0na4.ent-d1m4ja_.ent", "d1d0na5.ent-d1d0na6.ent", "d1d0na5.ent-d1d4xg_.ent", "d1d0na5.ent-d1f7sa_.ent", "d1d0na5.ent-d1hqz1_.ent", "d1d0na5.ent-d1jhwa3.ent", "d1d0na5.ent-d1m4ja_.ent", "d1d0na6.ent-d1d4xg_.ent", "d1d0na6.ent-d1f7sa_.ent", "d1d0na6.ent-d1hqz1_.ent", "d1d0na6.ent-d1jhwa3.ent", "d1d0na6.ent-d1m4ja_.ent", "d1d0qa_.ent-d1dl6a_.ent", "d1d0qa_.ent-d1dxga_.ent", "d1d0qa_.ent-d1f4la3.ent", "d1d0qa_.ent-d1gh9a_.ent", "d1d0qa_.ent-d1i50i1.ent", "d1d0qa_.ent-d1i50i2.ent", "d1d0qa_.ent-d1i50l_.ent", "d1d0qa_.ent-d1jj22_.ent", "d1d0qa_.ent-d1jj2y_.ent", "d1d0qa_.ent-d1jj2z_.ent", "d1d0qa_.ent-d1lkoa2.ent", "d1d0qa_.ent-d1m2oa5.ent", "d1d0qa_.ent-d1ocrf_.ent", "d1d0qa_.ent-d1pft__.ent", "d1d0qa_.ent-d1qyp__.ent", "d1d0qa_.ent-d1rb9__.ent", "d1d0qa_.ent-d1tfi__.ent", "d1d0qa_.ent-d1yua_1.ent", "d1d0qa_.ent-d1yua_2.ent", "d1d0qa_.ent-d1zaka2.ent", "d1d0qa_.ent-d1zin_2.ent", "d1d1da1.ent-d1dnya_.ent", "d1d1da1.ent-d1dv5a_.ent", "d1d1da1.ent-d1emva_.ent", "d1d1da1.ent-d1l0ia_.ent", "d1d1da1.ent-d1qrjb1.ent", "d1d1da1.ent-d2eiaa1.ent", "d1d1ga_.ent-d1df7a_.ent", "d1d1ga_.ent-d1dyr__.ent", "d1d1ga_.ent-d1ra9__.ent", "d1d1ga_.ent-d1vdra_.ent", "d1d1ga_.ent-d3dfr__.ent", "d1d1ha_.ent-d1dl0a_.ent", "d1d1ha_.ent-d1eit__.ent", "d1d1ha_.ent-d1emxa_.ent", "d1d1ha_.ent-d1g9pa_.ent", "d1d1ha_.ent-d1i25a_.ent", "d1d1ha_.ent-d1i26a_.ent", "d1d1ha_.ent-d1koza_.ent", "d1d1ha_.ent-d1kqha_.ent", "d1d1ha_.ent-d1lqra_.ent", "d1d1ha_.ent-d1lupa_.ent", "d1d1ha_.ent-d1nixa_.ent", "d1d1ha_.ent-d1niya_.ent", "d1d1ha_.ent-d1qk6a_.ent", "d1d1ha_.ent-d1qk7a_.ent", "d1d1ha_.ent-d1vtx__.ent", "d1d1la_.ent-d1e3oc2.ent", "d1d1la_.ent-d1efaa1.ent", "d1d1la_.ent-d1ic8a2.ent", "d1d1la_.ent-d1lmb3_.ent", "d1d1la_.ent-d1ner__.ent", "d1d1la_.ent-d1r69__.ent", "d1d1la_.ent-d1uxc__.ent", "d1d1la_.ent-d1uxd__.ent", "d1d1la_.ent-d1vpwa1.ent", "d1d1la_.ent-d2cro__.ent", "d1d1qa_.ent-d1iiba_.ent", "d1d1qa_.ent-d1jf8a_.ent", "d1d1qa_.ent-d1phr__.ent", "d1d2ea2.ent-d1exma2.ent", "d1d2ea2.ent-d1f60a2.ent", "d1d2ea2.ent-d1kk1a2.ent", "d1d2la_.ent-d1f5ya1.ent", "d1d2la_.ent-d1f5ya2.ent", "d1d2la_.ent-d1j8ea_.ent", "d1d2la_.ent-d1k7ba_.ent", "d1d2la_.ent-d1n7da6.ent", "d1d2la_.ent-d1n7da7.ent", "d1d2la_.ent-d1n7daa.ent", "d1d2oa1.ent-d1dmha_.ent", "d1d2oa1.ent-d1f86a_.ent", "d1d2oa1.ent-d1h8la1.ent", "d1d2oa1.ent-d1lm8v_.ent", "d1d2oa1.ent-d1qhoa2.ent", "d1d2sa_.ent-d1dyka2.ent", "d1d2sa_.ent-d1gv9a_.ent", "d1d2sa_.ent-d1h30a2.ent", "d1d2sa_.ent-d1ikpa1.ent", "d1d2sa_.ent-d1is3a_.ent", "d1d2sa_.ent-d1jhna4.ent", "d1d2sa_.ent-d1kit_1.ent", "d1d2sa_.ent-d1kqra_.ent", "d1d2sa_.ent-d1n1ta1.ent", "d1d2sa_.ent-d1nls__.ent", "d1d2sa_.ent-d1saca_.ent", "d1d2sa_.ent-d2nlra_.ent", "d1d2sa_.ent-d2sli_1.ent", "d1d2ta_.ent-d1qhba_.ent", "d1d2ta_.ent-d1qi9a_.ent", "d1d2ta_.ent-d1vns__.ent", "d1d2za_.ent-d1d2zb_.ent", "d1d2za_.ent-d1ddf__.ent", "d1d2za_.ent-d1dgna_.ent", "d1d2za_.ent-d1fada_.ent", "d1d2za_.ent-d1icha_.ent", "d1d2za_.ent-d1n3ka_.ent", "d1d2za_.ent-d1ngr__.ent", "d1d2za_.ent-d3crd__.ent", "d1d2za_.ent-d3ygsp_.ent", "d1d2zb_.ent-d1ddf__.ent", "d1d2zb_.ent-d1dgna_.ent", "d1d2zb_.ent-d1fada_.ent", "d1d2zb_.ent-d1icha_.ent", "d1d2zb_.ent-d1n3ka_.ent", "d1d2zb_.ent-d1ngr__.ent", "d1d2zb_.ent-d3crd__.ent", "d1d2zb_.ent-d3ygsp_.ent", "d1d3ba_.ent-d1d3bb_.ent", "d1d3ba_.ent-d1h641_.ent", "d1d3ba_.ent-d1i8fa_.ent", "d1d3ba_.ent-d1ib8a1.ent", "d1d3ba_.ent-d1kq1a_.ent", "d1d3ba_.ent-d1ljoa_.ent", "d1d3ba_.ent-d1mgqa_.ent", "d1d3ba_.ent-d1mxma1.ent", "d1d3ba_.ent-d1n9ra_.ent", "d1d3bb_.ent-d1h641_.ent", "d1d3bb_.ent-d1i8fa_.ent", "d1d3bb_.ent-d1kq1a_.ent", "d1d3bb_.ent-d1ljoa_.ent", "d1d3bb_.ent-d1mgqa_.ent", "d1d3bb_.ent-d1mxma1.ent", "d1d3bb_.ent-d1n9ra_.ent", "d1d3ga_.ent-d1ea0a2.ent", "d1d3ga_.ent-d1ep3a_.ent", "d1d3ga_.ent-d1gox__.ent", "d1d3ga_.ent-d1gtea2.ent", "d1d3ga_.ent-d1gvoa_.ent", "d1d3ga_.ent-d1huva_.ent", "d1d3ga_.ent-d1icpa_.ent", "d1d3ga_.ent-d1kbia1.ent", "d1d3ga_.ent-d1llwa2.ent", "d1d3ga_.ent-d1m7ja3.ent", "d1d3ga_.ent-d1o94a1.ent", "d1d3ga_.ent-d1oyb__.ent", "d1d3ga_.ent-d2dora_.ent", "d1d3va_.ent-d1gq6a_.ent", "d1d3va_.ent-d2ceva_.ent", "d1d4aa_.ent-d1b3ra2.ent", "d1d4aa_.ent-d1cex__.ent", "d1d4aa_.ent-d1cf9a1.ent", "d1d4aa_.ent-d1e5da1.ent", "d1d4aa_.ent-d1es9a_.ent", "d1d4aa_.ent-d1euca2.ent", "d1d4aa_.ent-d1f2va_.ent", "d1d4aa_.ent-d1f4pa_.ent", "d1d4aa_.ent-d1f8ya_.ent", "d1d4aa_.ent-d1fjgb_.ent", "d1d4aa_.ent-d1flca2.ent", "d1d4aa_.ent-d1fuea_.ent", "d1d4aa_.ent-d1fyea_.ent", "d1d4aa_.ent-d1g66a_.ent", "d1d4aa_.ent-d1h05a_.ent", "d1d4aa_.ent-d1iexa2.ent", "d1d4aa_.ent-d1ja1a2.ent", "d1d4aa_.ent-d1k7ca_.ent", "d1d4aa_.ent-d1kwga3.ent", "d1d4aa_.ent-d1l7da2.ent", "d1d4aa_.ent-d1qo0d_.ent", "d1d4aa_.ent-d1qr2a_.ent", "d1d4aa_.ent-d1rcf__.ent", "d1d4aa_.ent-d2fcr__.ent", "d1d4aa_.ent-d2naca2.ent", "d1d4aa_.ent-d5nul__.ent", "d1d4aa_.ent-d7reqb2.ent", "d1d4ba_.ent-d1ayfa_.ent", "d1d4ba_.ent-d1bmlc3.ent", "d1d4ba_.ent-d1c9fa_.ent", "d1d4ba_.ent-d1czpa_.ent", "d1d4ba_.ent-d1f2ri_.ent", "d1d4ba_.ent-d1f52a1.ent", "d1d4ba_.ent-d1fm0d_.ent", "d1d4ba_.ent-d1gnua_.ent", "d1d4ba_.ent-d1h4ra3.ent", "d1d4ba_.ent-d1h8ca_.ent", "d1d4ba_.ent-d1i42a_.ent", "d1d4ba_.ent-d1ip9a_.ent", "d1d4ba_.ent-d1k8rb_.ent", "d1d4ba_.ent-d1l4db_.ent", "d1d4ba_.ent-d1l5pa_.ent", "d1d4ba_.ent-d1l7ya_.ent", "d1d4ba_.ent-d1lfda_.ent", "d1d4ba_.ent-d1lm8b_.ent", "d1d4ba_.ent-d1qlab2.ent", "d1d4ba_.ent-d2sak__.ent", "d1d4ba_.ent-d3seb_2.ent", "d1d4ba_.ent-d3tss_2.ent", "d1d4m1_.ent-d1aym2_.ent", "d1d4m1_.ent-d1b35a_.ent", "d1d4m1_.ent-d1b35b_.ent", "d1d4m1_.ent-d1b35c_.ent", "d1d4m1_.ent-d1bev1_.ent", "d1d4m1_.ent-d1bev3_.ent", "d1d4m1_.ent-d1k5ma_.ent", "d1d4m1_.ent-d1pvc1_.ent", "d1d4m1_.ent-d1tmf1_.ent", "d1d4m1_.ent-d2mev1_.ent", "d1d4m1_.ent-d2mev2_.ent", "d1d4oa_.ent-d1dhs__.ent", "d1d4oa_.ent-d1efva2.ent", "d1d4oa_.ent-d1hzzc_.ent", "d1d4oa_.ent-d1icia_.ent", "d1d4oa_.ent-d1j8fa_.ent", "d1d4oa_.ent-d1jsca1.ent", "d1d4oa_.ent-d1ma3a_.ent", "d1d4oa_.ent-d1o97d2.ent", "d1d4oa_.ent-d1poxa1.ent", "d1d4oa_.ent-d1pvda1.ent", "d1d4oa_.ent-d1zpda1.ent", "d1d4ta_.ent-d1fu6a_.ent", "d1d4ta_.ent-d1ju5a_.ent", "d1d4ta_.ent-d1jwoa_.ent", "d1d4ta_.ent-d1jyra_.ent", "d1d4ta_.ent-d1lkka_.ent", "d1d4ta_.ent-d1luia_.ent", "d1d4ta_.ent-d1mil__.ent", "d1d4ta_.ent-d1qada_.ent", "d1d4ta_.ent-d2abl_2.ent", "d1d4ta_.ent-d2cbla3.ent", "d1d4ta_.ent-d2plda_.ent", "d1d4ta_.ent-d2shpa3.ent", "d1d4ua1.ent-d1exja1.ent", "d1d4ua1.ent-d1j9ia_.ent", "d1d4ua1.ent-d1jbga_.ent", "d1d4ua1.ent-d1jjcb1.ent", "d1d4ua1.ent-d1jjcb2.ent", "d1d4ua2.ent-d1dsza_.ent", "d1d4ua2.ent-d1fjgn_.ent", "d1d4ua2.ent-d1g47a1.ent", "d1d4ua2.ent-d1g47a2.ent", "d1d4ua2.ent-d1gnf__.ent", "d1d4ua2.ent-d1ibia2.ent", "d1d4ua2.ent-d1iml_2.ent", "d1d4ua2.ent-d1jj2t_.ent", "d1d4ua2.ent-d1k3xa3.ent", "d1d4ua2.ent-d1kb2a_.ent", "d1d4ua2.ent-d1l1za3.ent", "d1d4ua2.ent-d1lata_.ent", "d1d4ua2.ent-d1lv3a_.ent", "d1d4ua2.ent-d1zfo__.ent", "d1d4ua2.ent-d2nllb_.ent", "d1d4ua2.ent-d3gata_.ent", "d1d4ua2.ent-d7gata_.ent", "d1d4va1.ent-d1d4va2.ent", "d1d4va1.ent-d1d4va3.ent", "d1d4va1.ent-d1exta1.ent", "d1d4va1.ent-d1exta2.ent", "d1d4va1.ent-d1exta3.ent", "d1d4va1.ent-d1jmab1.ent", "d1d4va1.ent-d1jmab2.ent", "d1d4va2.ent-d1d4va3.ent", "d1d4va2.ent-d1exta1.ent", "d1d4va2.ent-d1exta2.ent", "d1d4va2.ent-d1exta3.ent", "d1d4va2.ent-d1jmab1.ent", "d1d4va2.ent-d1jmab2.ent", "d1d4va3.ent-d1exta1.ent", "d1d4va3.ent-d1exta2.ent", "d1d4va3.ent-d1exta3.ent", "d1d4va3.ent-d1jmab1.ent", "d1d4va3.ent-d1jmab2.ent", "d1d4xg_.ent-d1f7sa_.ent", "d1d4xg_.ent-d1hqz1_.ent", "d1d4xg_.ent-d1jhwa3.ent", "d1d4xg_.ent-d1m2oa4.ent", "d1d4xg_.ent-d1m2vb4.ent", "d1d4xg_.ent-d1m4ja_.ent", "d1d5ga_.ent-d1g9oa_.ent", "d1d5ga_.ent-d1i16__.ent", "d1d5ga_.ent-d1ihja_.ent", "d1d5ga_.ent-d1k32a1.ent", "d1d5ga_.ent-d1kwaa_.ent", "d1d5ga_.ent-d1lcya1.ent", "d1d5ga_.ent-d1m5za_.ent", "d1d5ga_.ent-d1mfga_.ent", "d1d5ga_.ent-d1qaua_.ent", "d1d5ga_.ent-d1qava_.ent", "d1d5ga_.ent-d1qlca_.ent", "d1d5ra1.ent-d1dcea2.ent", "d1d5ra1.ent-d1dqva1.ent", "d1d5ra1.ent-d1dsya_.ent", "d1d5ra1.ent-d1e8xa2.ent", "d1d5ra1.ent-d1gmia_.ent", "d1d5ra1.ent-d1k5wa_.ent", "d1d5ra1.ent-d1l4ia2.ent", "d1d5ra1.ent-d1qasa2.ent", "d1d5ra1.ent-d1rlw__.ent", "d1d5ra1.ent-d1rsy__.ent", "d1d5ra1.ent-d1who__.ent", "d1d5ra1.ent-d3rpba_.ent", "d1d5ra2.ent-d1eeoa_.ent", "d1d5ra2.ent-d1fpza_.ent", "d1d5ra2.ent-d1g4us2.ent", "d1d5ra2.ent-d1i9sa_.ent", "d1d5ra2.ent-d1ikza_.ent", "d1d5ra2.ent-d1jlna_.ent", "d1d5ra2.ent-d1lara1.ent", "d1d5ra2.ent-d1lara2.ent", "d1d5ra2.ent-d1lyva_.ent", "d1d5ra2.ent-d1mkp__.ent", "d1d5ra2.ent-d1vhra_.ent", "d1d5ra2.ent-d1yfoa_.ent", "d1d5ra2.ent-d2shpa1.ent", "d1d5ta1.ent-d1chua2.ent", "d1d5ta1.ent-d1cjca1.ent", "d1d5ta1.ent-d1ebda1.ent", "d1d5ta1.ent-d1fcda1.ent", "d1d5ta1.ent-d1fcda2.ent", "d1d5ta1.ent-d1feca1.ent", "d1d5ta1.ent-d1fl2a2.ent", "d1d5ta1.ent-d1gtea3.ent", "d1d5ta1.ent-d1h6va1.ent", "d1d5ta1.ent-d1jeha1.ent", "d1d5ta1.ent-d1jnra2.ent", "d1d5ta1.ent-d1ju2a1.ent", "d1d5ta1.ent-d1k0ia1.ent", "d1d5ta1.ent-d1kf6a2.ent", "d1d5ta1.ent-d1kssa2.ent", "d1d5ta1.ent-d1l9ea1.ent", "d1d5ta1.ent-d1lqta1.ent", "d1d5ta1.ent-d1m6ia1.ent", "d1d5ta1.ent-d1m6ia2.ent", "d1d5ta1.ent-d1mo9a1.ent", "d1d5ta1.ent-d1neka2.ent", "d1d5ta1.ent-d1nhp_1.ent", "d1d5ta1.ent-d1nhp_2.ent", "d1d5ta1.ent-d1o94a2.ent", "d1d5ta1.ent-d1ojt_1.ent", "d1d5ta1.ent-d1qlaa2.ent", "d1d5ta1.ent-d1qo8a2.ent", "d1d5ta1.ent-d3grs_1.ent", "d1d5ta1.ent-d3grs_2.ent", "d1d5ta1.ent-d3lada1.ent", "d1d5ta2.ent-d1f8ra2.ent", "d1d5ta2.ent-d1foha4.ent", "d1d5ta2.ent-d1gosa2.ent", "d1d5ta2.ent-d1gpea2.ent", "d1d5ta2.ent-d1i8ta2.ent", "d1d5ta2.ent-d1ju2a2.ent", "d1d5ta2.ent-d1k0ia2.ent", "d1d5ta2.ent-d1kdga2.ent", "d1d5ta2.ent-d1l9ea2.ent", "d1d5ta2.ent-d1mxta2.ent", "d1d5va_.ent-d1e17a_.ent", "d1d5va_.ent-d1fsha_.ent", "d1d5va_.ent-d1ldja1.ent", "d1d5ya2.ent-d1b8ia_.ent", "d1d5ya2.ent-d1bl0a2.ent", "d1d5ya2.ent-d1e3oc1.ent", "d1d5ya2.ent-d1fexa_.ent", "d1d5ya2.ent-d1fjla_.ent", "d1d5ya2.ent-d1g2ha_.ent", "d1d5ya2.ent-d1hlva2.ent", "d1d5ya2.ent-d1ig7a_.ent", "d1d5ya2.ent-d1irza_.ent", "d1d5ya2.ent-d1k61a_.ent", "d1d5ya2.ent-d1k78a1.ent", "d1d5ya2.ent-d1k78a2.ent", "d1d5ya3.ent-d1jyha_.ent", "d1d66a1.ent-d1hwtc1.ent", "d1d66a1.ent-d1pyia1.ent", "d1d66a1.ent-d1zmec1.ent", "d1d66a1.ent-d2alca_.ent", "d1d6aa_.ent-d1dm0a_.ent", "d1d6aa_.ent-d1hwma_.ent", "d1d6aa_.ent-d1ift__.ent", "d1d6aa_.ent-d1mrj__.ent", "d1d6aa_.ent-d1qi7a_.ent", "d1d6ba_.ent-d1dfna_.ent", "d1d6ba_.ent-d1e4ta_.ent", "d1d6ba_.ent-d1ewsa_.ent", "d1d6ba_.ent-d1fd3a_.ent", "d1d6ba_.ent-d1ijva_.ent", "d1d6ba_.ent-d1kj6a_.ent", "d1d6ba_.ent-d1sh1__.ent", "d1d6ba_.ent-d2bds__.ent", "d1d6ta_.ent-d1dar_3.ent", "d1d6ta_.ent-d1ei1a1.ent", "d1d6ta_.ent-d1fjgi_.ent", "d1d6ta_.ent-d1h72c1.ent", "d1d6ta_.ent-d1kija1.ent", "d1d6ta_.ent-d1kkha1.ent", "d1d6ta_.ent-d1kvka1.ent", "d1d6ta_.ent-d1mu5a2.ent", "d1d6ta_.ent-d1n0ua3.ent", "d1d6ta_.ent-d1pkp_1.ent", "d1d7pm_.ent-d1ciy_1.ent", "d1d7pm_.ent-d1cx1a_.ent", "d1d7pm_.ent-d1dlc_1.ent", "d1d7pm_.ent-d1eut_2.ent", "d1d7pm_.ent-d1gmma_.ent", "d1d7pm_.ent-d1gnya_.ent", "d1d7pm_.ent-d1gu3a_.ent", "d1d7pm_.ent-d1guia_.ent", "d1d7pm_.ent-d1h6ya_.ent", "d1d7pm_.ent-d1i5pa1.ent", "d1d7pm_.ent-d1jhja_.ent", "d1d7pm_.ent-d1ji6a1.ent", "d1d7pm_.ent-d1ju3a1.ent", "d1d7pm_.ent-d1jz8a3.ent", "d1d7pm_.ent-d1k12a_.ent", "d1d7pm_.ent-d1k3ia2.ent", "d1d7pm_.ent-d1kexa_.ent", "d1d7pm_.ent-d1kgya_.ent", "d1d7pm_.ent-d1l7la_.ent", "d1d7pm_.ent-d1lnsa2.ent", "d1d7pm_.ent-d1xnaa_.ent", "d1d7qa_.ent-d1e1oa1.ent", "d1d7qa_.ent-d1eova1.ent", "d1d7qa_.ent-d1ewia_.ent", "d1d7qa_.ent-d1fgua1.ent", "d1d7qa_.ent-d1fgua2.ent", "d1d7qa_.ent-d1fjgl_.ent", "d1d7qa_.ent-d1i50h_.ent", "d1d7qa_.ent-d1iyjb3.ent", "d1d7qa_.ent-d1iyjb5.ent", "d1d7qa_.ent-d1jb7a2.ent", "d1d7qa_.ent-d1jjcb3.ent", "d1d7qa_.ent-d1quqa_.ent", "d1d7qa_.ent-d1quqb_.ent", "d1d7ya3.ent-d1dxla3.ent", "d1d7ya3.ent-d1ebda3.ent", "d1d7ya3.ent-d1fcda3.ent", "d1d7ya3.ent-d1feca3.ent", "d1d7ya3.ent-d1h6va3.ent", "d1d7ya3.ent-d1lvl_3.ent", "d1d7ya3.ent-d1m6ia3.ent", "d1d7ya3.ent-d1mo9a3.ent", "d1d7ya3.ent-d1n62c1.ent", "d1d7ya3.ent-d1nhp_3.ent", "d1d7ya3.ent-d1ojt_3.ent", "d1d7ya3.ent-d3grs_3.ent", "d1d7ya3.ent-d3lada3.ent", "d1d8ba_.ent-d1dgsa1.ent", "d1d8ba_.ent-d1doqa_.ent", "d1d8ba_.ent-d1dxsa_.ent", "d1d8ba_.ent-d1f44a1.ent", "d1d8ba_.ent-d1floa1.ent", "d1d8ba_.ent-d1go3f_.ent", "d1d8ba_.ent-d1jmsa1.ent", "d1d8ba_.ent-d1jmsa3.ent", "d1d8ba_.ent-d1jyga_.ent", "d1d8ba_.ent-d1kfta_.ent", "d1d8ba_.ent-d1lb2b_.ent", "d1d8ba_.ent-d1tfr_1.ent", "d1d8ua_.ent-d1a6m__", "d1d8ua_.ent-d1a6m__.ent", "d1d8ua_.ent-d1alla_", "d1d8ua_.ent-d1alla_.ent", "d1d8ua_.ent-d1allb_", "d1d8ua_.ent-d1allb_.ent", "d1d8ua_.ent-d1ash__", "d1d8ua_.ent-d1ash__.ent", "d1d8ua_.ent-d1b8da_", "d1d8ua_.ent-d1b8da_.ent", "d1d8ua_.ent-d1cg5a_", "d1d8ua_.ent-d1cg5a_.ent", "d1d8ua_.ent-d1cg5b_", "d1d8ua_.ent-d1cg5b_.ent", "d1d8ua_.ent-d1cqxa1", "d1d8ua_.ent-d1cqxa1.ent", "d1d8ua_.ent-d1ew6a_", "d1d8ua_.ent-d1ew6a_.ent", "d1d8ua_.ent-d1gcva_", "d1d8ua_.ent-d1gcva_.ent", "d1d8ua_.ent-d1gvha1", "d1d8ua_.ent-d1gvha1.ent", "d1d8ua_.ent-d1h97a_", "d1d8ua_.ent-d1h97a_.ent", "d1d8ua_.ent-d1hlb__", "d1d8ua_.ent-d1hlb__.ent", "d1d8ua_.ent-d1irda_", "d1d8ua_.ent-d1irda_.ent", "d1d8ua_.ent-d1irdb_", "d1d8ua_.ent-d1irdb_.ent", "d1d8ua_.ent-d1it2a_", "d1d8ua_.ent-d1it2a_.ent", "d1d8ua_.ent-d1itha_", "d1d8ua_.ent-d1itha_.ent", "d1d8ua_.ent-d1jl7a_", "d1d8ua_.ent-d1jl7a_.ent", "d1d8ua_.ent-d1la6a_", "d1d8ua_.ent-d1la6a_.ent", "d1d8ua_.ent-d1mba__", "d1d8ua_.ent-d1mba__.ent", "d1d8ua_.ent-d1phna_", "d1d8ua_.ent-d1phna_.ent", "d1d8ua_.ent-d2gdm__", "d1d8ua_.ent-d2gdm__.ent", "d1d8ua_.ent-d2lhb__", "d1d8ua_.ent-d2lhb__.ent", "d1d8ua_.ent-d3sdha_", "d1d8ua_.ent-d3sdha_.ent", "d1d9ca_.ent-d1eera_.ent", "d1d9ca_.ent-d1etea_.ent", "d1d9ca_.ent-d1evsa_.ent", "d1d9ca_.ent-d1f45b_.ent", "d1d9ca_.ent-d1f6fa_.ent", "d1d9ca_.ent-d1hula_.ent", "d1d9ca_.ent-d1huw__.ent", "d1d9ca_.ent-d1hzia_.ent", "d1d9ca_.ent-d1i1rb_.ent", "d1d9ca_.ent-d1jli__.ent", "d1d9ca_.ent-d1lki__.ent", "d1d9ca_.ent-d1lqsl_.ent", "d1d9ca_.ent-d1m47a_.ent", "d1d9ca_.ent-d1n1fa_.ent", "d1d9ca_.ent-d2gmfa_.ent", "d1d9ca_.ent-d2ilk__.ent", "d1d9ea_.ent-d1dhpa_.ent", "d1d9ea_.ent-d1dosa_.ent", "d1d9ea_.ent-d1epxa_.ent", "d1d9ea_.ent-d1euaa_.ent", "d1d9ea_.ent-d1f74a_.ent", "d1d9ea_.ent-d1gvfa_.ent", "d1d9ea_.ent-d1gzga_.ent", "d1d9ea_.ent-d1h7na_.ent", "d1d9ea_.ent-d1hfba_.ent", "d1d9ea_.ent-d1i2oa_.ent", "d1d9ea_.ent-d1jcla_.ent", "d1d9ea_.ent-d1jcxa_.ent", "d1d9ea_.ent-d1l6wa_.ent", "d1d9ea_.ent-d1mzha_.ent", "d1d9ea_.ent-d1nal1_.ent", "d1d9ea_.ent-d1o0ya_.ent", "d1d9ea_.ent-d1qfea_.ent", "d1d9na_.ent-d1gcca_.ent", "d1d9na_.ent-d1kjka_.ent", "d1d9na_.ent-d1qk9a_.ent", "d1daaa_.ent-d1ekfa_.ent", "d1daaa_.ent-d1et0a_.ent", "d1daaa_.ent-d1i1ka_.ent", "d1daba_.ent-d1dbga_.ent", "d1daba_.ent-d1ee6a_.ent", "d1daba_.ent-d1ezga_.ent", "d1daba_.ent-d1hf2a1.ent", "d1daba_.ent-d1hg8a_.ent", "d1daba_.ent-d1jtaa_.ent", "d1daba_.ent-d1k4za_.ent", "d1daba_.ent-d1k5ca_.ent", "d1daba_.ent-d1llwa1.ent", "d1daba_.ent-d1qcxa_.ent", "d1daba_.ent-d1qjva_.ent", "d1daba_.ent-d1qq1a_.ent", "d1daba_.ent-d1rmg__.ent", "d1dar_1.ent-d1ep3b1.ent", "d1dar_1.ent-d1exma1.ent", "d1dar_1.ent-d1f20a1.ent", "d1dar_1.ent-d1f60a1.ent", "d1dar_1.ent-d1fuia1.ent", "d1dar_1.ent-d1g7sa1.ent", "d1dar_1.ent-d1g7sa2.ent", "d1dar_1.ent-d1i7pa1.ent", "d1dar_1.ent-d1jb9a1.ent", "d1dar_1.ent-d1jj2b_.ent", "d1dar_1.ent-d1kk1a1.ent", "d1dar_1.ent-d1krha1.ent", "d1dar_1.ent-d1kzla1.ent", "d1dar_1.ent-d1kzla2.ent", "d1dar_1.ent-d1n08a_.ent", "d1dar_1.ent-d1n0ua1.ent", "d1dar_1.ent-d1qfja1.ent", "d1dar_1.ent-d2pia_1.ent", "d1dar_3.ent-d1ei1a1.ent", "d1dar_3.ent-d1fjgi_.ent", "d1dar_3.ent-d1h72c1.ent", "d1dar_3.ent-d1kija1.ent", "d1dar_3.ent-d1kkha1.ent", "d1dar_3.ent-d1kvka1.ent", "d1dar_3.ent-d1mu5a2.ent", "d1dar_3.ent-d1n0ua3.ent", "d1dar_3.ent-d1pkp_1.ent", "d1dar_4.ent-d1fnma4.ent", "d1dar_4.ent-d1n0ua4.ent", "d1dar_4.ent-d1n0ua5.ent", "d1dbfa_.ent-d1fsz_2.ent", "d1dbfa_.ent-d1ipaa2.ent", "d1dbfa_.ent-d1iv3a_.ent", "d1dbfa_.ent-d1jd1a_.ent", "d1dbfa_.ent-d1jj2f_.ent", "d1dbfa_.ent-d1qd9a_.ent", "d1dbfa_.ent-d1tuba2.ent", "d1dbga_.ent-d1ee6a_.ent", "d1dbga_.ent-d1ezga_.ent", "d1dbga_.ent-d1hf2a1.ent", "d1dbga_.ent-d1hg8a_.ent", "d1dbga_.ent-d1jtaa_.ent", "d1dbga_.ent-d1k4za_.ent", "d1dbga_.ent-d1k5ca_.ent", "d1dbga_.ent-d1llwa1.ent", "d1dbga_.ent-d1qcxa_.ent", "d1dbga_.ent-d1qjva_.ent", "d1dbga_.ent-d1qq1a_.ent", "d1dbga_.ent-d1rmg__.ent", "d1dbqa_.ent-d1dp4a_.ent", "d1dbqa_.ent-d1ewka_.ent", "d1dbqa_.ent-d1gca__.ent", "d1dbqa_.ent-d1jdpa_.ent", "d1dbqa_.ent-d1jx6a_.ent", "d1dbqa_.ent-d1jyea_.ent", "d1dbqa_.ent-d1pea__.ent", "d1dbqa_.ent-d1rpja_.ent", "d1dbqa_.ent-d2dri__.ent", "d1dbqa_.ent-d2liv__.ent", "d1dbqa_.ent-d8abp__.ent", "d1dbta_.ent-d1dqwa_.ent", "d1dbta_.ent-d1eixa_.ent", "d1dbta_.ent-d1geqa_.ent", "d1dbta_.ent-d1i4na_.ent", "d1dbta_.ent-d1jvna1.ent", "d1dbta_.ent-d1km3a_.ent", "d1dbta_.ent-d1kv8a_.ent", "d1dbta_.ent-d1nsj__.ent", "d1dbta_.ent-d1pii_1.ent", "d1dbta_.ent-d1pii_2.ent", "d1dbta_.ent-d1qopa_.ent", "d1dbta_.ent-d1rpxa_.ent", "d1dbta_.ent-d1thfd_.ent", "d1dbwa_.ent-d1dcfa_.ent", "d1dbwa_.ent-d1dz3a_.ent", "d1dbwa_.ent-d1m2fa_.ent", "d1dbwa_.ent-d1mb3a_.ent", "d1dbwa_.ent-d1mvoa_.ent", "d1dbwa_.ent-d1nat__.ent", "d1dbwa_.ent-d1ntr__.ent", "d1dbwa_.ent-d1qo0d_.ent", "d1dbwa_.ent-d1tmy__.ent", "d1dc1a_.ent-d1dmua_.ent", "d1dc1a_.ent-d1dzfa1.ent", "d1dc1a_.ent-d1ev7a_.ent", "d1dc1a_.ent-d1f1za2.ent", "d1dc1a_.ent-d1fiua_.ent", "d1dc1a_.ent-d1gefa_.ent", "d1dc1a_.ent-d1hh1a_.ent", "d1dc1a_.ent-d1kc6a_.ent", "d1dc1a_.ent-d1knva_.ent", "d1dc1a_.ent-d1m0da_.ent", "d1dc1a_.ent-d1vsra_.ent", "d1dc1a_.ent-d2foka4.ent", "d1dc1a_.ent-d3pvia_.ent", "d1dcea2.ent-d1e8xa2.ent", "d1dcea2.ent-d1gmia_.ent", "d1dcea2.ent-d1l4ia2.ent", "d1dcea2.ent-d1rsy__.ent", "d1dcea2.ent-d1who__.ent", "d1dcea3.ent-d1h6ta2.ent", "d1dcea3.ent-d1h6ua2.ent", "d1dcea3.ent-d1igra1.ent", "d1dcea3.ent-d1igra2.ent", "d1dcea3.ent-d1ivoa1.ent", "d1dcea3.ent-d1ivoa2.ent", "d1dcea3.ent-d1jl5a_.ent", "d1dcea3.ent-d1koha1.ent", "d1dcea3.ent-d1m0za_.ent", "d1dcea3.ent-d1m6ba1.ent", "d1dcea3.ent-d1m6ba2.ent", "d1dcea3.ent-d1n8yc1.ent", "d1dcea3.ent-d1n8yc2.ent", "d1dceb_.ent-d1ld8b_.ent", "d1dceb_.ent-d1n1ba1.ent", "d1dceb_.ent-d2sqca1.ent", "d1dceb_.ent-d2sqca2.ent", "d1dceb_.ent-d5eau_1.ent", "d1dcfa_.ent-d1dz3a_.ent", "d1dcfa_.ent-d1m2fa_.ent", "d1dcfa_.ent-d1mb3a_.ent", "d1dcfa_.ent-d1mvoa_.ent", "d1dcfa_.ent-d1nat__.ent", "d1dcfa_.ent-d1ntr__.ent", "d1dcfa_.ent-d1qo0d_.ent", "d1dcfa_.ent-d1tmy__.ent", "d1dcia_.ent-d1ef8a_.ent", "d1dcia_.ent-d1hnua_.ent", "d1dcia_.ent-d1hzda_.ent", "d1dcia_.ent-d1k32a4.ent", "d1dcia_.ent-d1mj3a_.ent", "d1dcia_.ent-d1nzya_.ent", "d1dcia_.ent-d1o8ua_.ent", "d1dcia_.ent-d1tyfa_.ent", "d1dcja_.ent-d1g6sa_.ent", "d1dcja_.ent-d1h0xa_.ent", "d1dcja_.ent-d1hc7a3.ent", "d1dcja_.ent-d1jdqa_.ent", "d1dcja_.ent-d1je3a_.ent", "d1dcja_.ent-d1jo0a_.ent", "d1dcja_.ent-d1msza_.ent", "d1dcja_.ent-d1qmha2.ent", "d1dcja_.ent-d1tig__.ent", "d1dcpa_.ent-d1g51a2.ent", "d1dcpa_.ent-d1i50c1.ent", "d1dcpa_.ent-d1i50k_.ent", "d1dcpa_.ent-d1xxaa_.ent", "d1dcqa1.ent-d1ihba_.ent", "d1dcqa1.ent-d1k1aa_.ent", "d1dcqa1.ent-d1k3zd_.ent", "d1dcqa1.ent-d1lm5a_.ent", "d1dcqa1.ent-d1myo__.ent", "d1dcqa1.ent-d1n11a_.ent", "d1dcqa1.ent-d1sw6a_.ent", "d1dcqa1.ent-d1ycsb1.ent", "d1dcs__.ent-d1dgwa_.ent", "d1dcs__.ent-d1ds1a_.ent", "d1dcs__.ent-d1e5sa_.ent", "d1dcs__.ent-d1ep0a_.ent", "d1dcs__.ent-d1eula1.ent", "d1dcs__.ent-d1fi2a_.ent", "d1dcs__.ent-d1ft9a2.ent", "d1dcs__.ent-d1fxza1.ent", "d1dcs__.ent-d1gp6a_.ent", "d1dcs__.ent-d1gy9a_.ent", "d1dcs__.ent-d1h2ka_.ent", "d1dcs__.ent-d1hw5a2.ent", "d1dcs__.ent-d1ig0a1.ent", "d1dcs__.ent-d1jr7a_.ent", "d1dcs__.ent-d1juha_.ent", "d1dcs__.ent-d1lrha_.ent", "d1dcs__.ent-d1m4oa_.ent", "d1dcs__.ent-d1pmi__.ent", "d1dcs__.ent-d1qjea_.ent", "d1dcs__.ent-d1wapa_.ent", "d1dcs__.ent-d2arca_.ent", "d1dcta_.ent-d1booa_.ent", "d1dcta_.ent-d1eg2a_.ent", "d1dcta_.ent-d1f3la_.ent", "d1dcta_.ent-d1fp1d2.ent", "d1dcta_.ent-d1fp2a2.ent", "d1dcta_.ent-d1g60a_.ent", "d1dcta_.ent-d1hnna_.ent", "d1dcta_.ent-d1i1na_.ent", "d1dcta_.ent-d1i4wa_.ent", "d1dcta_.ent-d1i9ga_.ent", "d1dcta_.ent-d1inla_.ent", "d1dcta_.ent-d1iy9a_.ent", "d1dcta_.ent-d1jg1a_.ent", "d1dcta_.ent-d1jqea_.ent", "d1dcta_.ent-d1kywa2.ent", "d1dcta_.ent-d1mjfa_.ent", "d1dcta_.ent-d1qama_.ent", "d1dcta_.ent-d1xvaa_.ent", "d1dcta_.ent-d1yub__.ent", "d1dcta_.ent-d2dpma_.ent", "d1dcta_.ent-d3mag__.ent", "d1dcua_.ent-d1g0ha_.ent", "d1dcua_.ent-d1inp__.ent", "d1dcua_.ent-d1jp4a_.ent", "d1dcua_.ent-d1ka1a_.ent", "d1dcua_.ent-d1kz8a_.ent", "d1dcua_.ent-d1lbva_.ent", "d1dcua_.ent-d2hhma_.ent", "d1dd2a_.ent-d1fyc__.ent", "d1dd2a_.ent-d1ghk__.ent", "d1dd2a_.ent-d1htp__.ent", "d1dd2a_.ent-d1k8ma_.ent", "d1dd2a_.ent-d1lac__.ent", "d1dd2a_.ent-d1qjoa_.ent", "d1dd5a_.ent-d1eh1a_.ent", "d1dd5a_.ent-d1ek8a_.ent", "d1dd5a_.ent-d1ge9a_.ent", "d1ddba_.ent-d1f0la3.ent", "d1ddba_.ent-d1f16a_.ent", "d1ddba_.ent-d1ikpa3.ent", "d1ddba_.ent-d1k3ka_.ent", "d1ddba_.ent-d1maz__.ent", "d1ddf__.ent-d1dgna_.ent", "d1ddf__.ent-d1fada_.ent", "d1ddf__.ent-d1icha_.ent", "d1ddf__.ent-d1n3ka_.ent", "d1ddf__.ent-d1ngr__.ent", "d1ddf__.ent-d3crd__.ent", "d1ddf__.ent-d3ygsp_.ent", "d1ddga1.ent-d1ep3b1.ent", "d1ddga1.ent-d1f20a1.ent", "d1ddga1.ent-d1fdr_1.ent", "d1ddga1.ent-d1fnc_1.ent", "d1ddga1.ent-d1i7pa1.ent", "d1ddga1.ent-d1i8da1.ent", "d1ddga1.ent-d1i8da2.ent", "d1ddga1.ent-d1ja1a1.ent", "d1ddga1.ent-d1jb9a1.ent", "d1ddga1.ent-d1krha1.ent", "d1ddga1.ent-d1kzla1.ent", "d1ddga1.ent-d1kzla2.ent", "d1ddga1.ent-d1qfja1.ent", "d1ddga1.ent-d1que_1.ent", "d1ddga1.ent-d2cnd_1.ent", "d1ddga1.ent-d2pia_1.ent", "d1ddga2.ent-d1ep3b2.ent", "d1ddga2.ent-d1f20a2.ent", "d1ddga2.ent-d1fdr_2.ent", "d1ddga2.ent-d1gvha3.ent", "d1ddga2.ent-d1i7pa2.ent", "d1ddga2.ent-d1ja1a3.ent", "d1ddga2.ent-d1jb9a2.ent", "d1ddga2.ent-d1krha2.ent", "d1ddga2.ent-d1qfja2.ent", "d1ddga2.ent-d1que_2.ent", "d1ddga2.ent-d2cnd_2.ent", "d1ddga2.ent-d2pia_2.ent", "d1ddja_.ent-d1a0la_.ent", "d1ddja_.ent-d1agja_.ent", "d1ddja_.ent-d1azza_.ent", "d1ddja_.ent-d1bio__.ent", "d1ddja_.ent-d1bqya_.ent", "d1ddja_.ent-d1cgha_.ent", "d1ddja_.ent-d1eaxa_.ent", "d1ddja_.ent-d1ekbb_.ent", "d1ddja_.ent-d1elva1.ent", "d1ddja_.ent-d1fjsa_.ent", "d1ddja_.ent-d1gdna_.ent", "d1ddja_.ent-d1gpza1.ent", "d1ddja_.ent-d1gvkb_.ent", "d1ddja_.ent-d1gvza_.ent", "d1ddja_.ent-d1hj9a_.ent", "d1ddja_.ent-d1m9ua_.ent", "d1ddja_.ent-d1mzaa_.ent", "d1ddja_.ent-d1qtfa_.ent", "d1ddja_.ent-d1rfna_.ent", "d1ddja_.ent-d2hlca_.ent", "d1ddla_.ent-d1a6ca1.ent", "d1ddla_.ent-d1a6ca2.ent", "d1ddla_.ent-d1a6ca3.ent", "d1ddla_.ent-d1bmv1_.ent", "d1ddla_.ent-d1cwpa_.ent", "d1ddla_.ent-d1f15a_.ent", "d1ddla_.ent-d1qqp1_.ent", "d1ddla_.ent-d2bpa2_.ent", "d1ddla_.ent-d2stv__.ent", "d1ddma_.ent-d1dro__.ent", "d1ddma_.ent-d1dyna_.ent", "d1ddma_.ent-d1eaza_.ent", "d1ddma_.ent-d1evha_.ent", "d1ddma_.ent-d1faoa_.ent", "d1ddma_.ent-d1fhoa_.ent", "d1ddma_.ent-d1gg3a2.ent", "d1ddma_.ent-d1h4ra2.ent", "d1ddma_.ent-d1k5db_.ent", "d1ddma_.ent-d1ki1b2.ent", "d1ddma_.ent-d1mai__.ent", "d1ddma_.ent-d1mixa2.ent", "d1ddma_.ent-d1mkea1.ent", "d1ddma_.ent-d1pls__.ent", "d1ddma_.ent-d1qqga1.ent", "d1ddma_.ent-d1qqga2.ent", "d1ddma_.ent-d1shca_.ent", "d1ddza1.ent-d1ekja_.ent", "d1ddza1.ent-d1g5ca_.ent", "d1ddza1.ent-d1i6pa_.ent", "d1de4a2.ent-d1fnga2.ent", "d1de4a2.ent-d1fngb2.ent", "d1de4a2.ent-d1gzqa2.ent", "d1de4a2.ent-d1hdma2.ent", "d1de4a2.ent-d1hdmb2.ent", "d1de4a2.ent-d1hyrc2.ent", "d1de4a2.ent-d1iaka2.ent", "d1de4a2.ent-d1jfma_.ent", "d1de4a2.ent-d1k5na2.ent", "d1de4a2.ent-d1kcgc_.ent", "d1de4a2.ent-d1lqva_.ent", "d1de4a2.ent-d1zaga2.ent", "d1de4a2.ent-d3frua2.ent", "d1de4c1.ent-d1eo0a_.ent", "d1de4c1.ent-d2cbla2.ent", "d1de4c2.ent-d1gmla_.ent", "d1de4c2.ent-d1kbla2.ent", "d1de4c2.ent-d1kid__.ent", "d1de4c2.ent-d1l5ja2.ent", "d1de4c2.ent-d1nbwa1.ent", "d1de4c3.ent-d1gyta2.ent", "d1de4c3.ent-d1h8la2.ent", "d1de4c3.ent-d1jqga1.ent", "d1de4c3.ent-d1kwma1.ent", "d1de4c3.ent-d1lam_2.ent", "d1de4c3.ent-d1lfwa1.ent", "d1de4c3.ent-d1loka_.ent", "d1de4c3.ent-d1m4la_.ent", "d1de4c3.ent-d1obr__.ent", "d1dec__.ent-d1e0fi_.ent", "d1dec__.ent-d1skz_1.ent", "d1dec__.ent-d1skz_2.ent", "d1dec__.ent-d4htci_.ent", "d1deeg_.ent-d1gab__.ent", "d1deeg_.ent-d1gjta_.ent", "d1deua_.ent-d1dkia_.ent", "d1deua_.ent-d1e2ta_.ent", "d1deua_.ent-d1euva_.ent", "d1deua_.ent-d1f13a4.ent", "d1deua_.ent-d1fh0a_.ent", "d1deua_.ent-d1g0da4.ent", "d1deua_.ent-d1gmya_.ent", "d1deua_.ent-d1gx3a_.ent", "d1deua_.ent-d1iu4a_.ent", "d1deua_.ent-d1kxra_.ent", "d1deua_.ent-d1l9na4.ent", "d1deua_.ent-d1me4a_.ent", "d1deua_.ent-d1nbfa_.ent", "d1deua_.ent-d1ppn__.ent", "d1deua_.ent-d1qmya_.ent", "d1deua_.ent-d1uch__.ent", "d1deua_.ent-d2act__.ent", "d1deua_.ent-d2cb5a_.ent", "d1deua_.ent-d3gcb__.ent", "d1deua_.ent-d7pcka_.ent", "d1df0a1.ent-d1alva_.ent", "d1df0a1.ent-d1auib_.ent", "d1df0a1.ent-d1eg3a1.ent", "d1df0a1.ent-d1exra_.ent", "d1df0a1.ent-d1ggwa_.ent", "d1df0a1.ent-d1hqva_.ent", "d1df0a1.ent-d1jfja_.ent", "d1df0a1.ent-d1k94a_.ent", "d1df0a1.ent-d1m31a_.ent", "d1df0a1.ent-d1m45a_.ent", "d1df0a1.ent-d1ncx__.ent", "d1df0a1.ent-d1rro__.ent", "d1df0a1.ent-d1sra__.ent", "d1df0a1.ent-d1wdcb_.ent", "d1df0a1.ent-d1wdcc_.ent", "d1df0a1.ent-d2pvba_.ent", "d1df0a1.ent-d2scpa_.ent", "d1df0a1.ent-d5pal__.ent", "d1df7a_.ent-d1dyr__.ent", "d1df7a_.ent-d1ra9__.ent", "d1df7a_.ent-d1vdra_.ent", "d1df7a_.ent-d3dfr__.ent", "d1dfca1.ent-d1dfca2.ent", "d1dfca1.ent-d1dfca3.ent", "d1dfca1.ent-d1dfca4.ent", "d1dfca1.ent-d1dqga_.ent", "d1dfca1.ent-d1hcd__.ent", "d1dfca1.ent-d1jlxa1.ent", "d1dfca1.ent-d1knma_.ent", "d1dfca1.ent-d1l2ha_.ent", "d1dfca1.ent-d1n4ka2.ent", "d1dfca2.ent-d1dfca3.ent", "d1dfca2.ent-d1dfca4.ent", "d1dfca2.ent-d1dqga_.ent", "d1dfca2.ent-d1hcd__.ent", "d1dfca2.ent-d1jlxa1.ent", "d1dfca2.ent-d1knma_.ent", "d1dfca2.ent-d1l2ha_.ent", "d1dfca2.ent-d1n4ka2.ent", "d1dfca3.ent-d1dfca4.ent", "d1dfca3.ent-d1dqga_.ent", "d1dfca3.ent-d1hcd__.ent", "d1dfca3.ent-d1jlxa1.ent", "d1dfca3.ent-d1knma_.ent", "d1dfca3.ent-d1l2ha_.ent", "d1dfca3.ent-d1n4ka2.ent", "d1dfca4.ent-d1hcd__.ent", "d1dfna_.ent-d1e4ta_.ent", "d1dfna_.ent-d1ewsa_.ent", "d1dfna_.ent-d1fd3a_.ent", "d1dfna_.ent-d1ijva_.ent", "d1dfna_.ent-d1kj6a_.ent", "d1dfna_.ent-d1sh1__.ent", "d1dfna_.ent-d2bds__.ent", "d1dfsa_.ent-d1dmc__.ent", "d1dfsa_.ent-d1jjda_.ent", "d1dfsa_.ent-d1qjka_.ent", "d1dfsa_.ent-d4mt2__.ent", "d1dfup_.ent-d1feua_.ent", "d1dfup_.ent-d1gtra1.ent", "d1dg6a_.ent-d1gr3a_.ent", "d1dg6a_.ent-d1kxga_.ent", "d1dg6a_.ent-d1tnra_.ent", "d1dg6a_.ent-d2tnfa_.ent", "d1dgfa_.ent-d1gwea_.ent", "d1dgfa_.ent-d1m7sa_.ent", "d1dgna_.ent-d1fada_.ent", "d1dgna_.ent-d1icha_.ent", "d1dgna_.ent-d1n3ka_.ent", "d1dgna_.ent-d1ngr__.ent", "d1dgna_.ent-d3crd__.ent", "d1dgna_.ent-d3ygsp_.ent", "d1dgsa1.ent-d1doqa_.ent", "d1dgsa1.ent-d1dxsa_.ent", "d1dgsa1.ent-d1f44a1.ent", "d1dgsa1.ent-d1floa1.ent", "d1dgsa1.ent-d1go3f_.ent", "d1dgsa1.ent-d1ixra1.ent", "d1dgsa1.ent-d1jmsa1.ent", "d1dgsa1.ent-d1jmsa3.ent", "d1dgsa1.ent-d1jyga_.ent", "d1dgsa1.ent-d1kfta_.ent", "d1dgsa1.ent-d1lb2b_.ent", "d1dgsa1.ent-d1tfr_1.ent", "d1dgsa3.ent-d1fvia2.ent", "d1dgtb3.ent-d1gzhb1.ent", "d1dgtb3.ent-d1in1a_.ent", "d1dgtb3.ent-d1l0ba1.ent", "d1dgtb3.ent-d1l0ba2.ent", "d1dgua_.ent-d1alva_.ent", "d1dgua_.ent-d1auib_.ent", "d1dgua_.ent-d1df0a1.ent", "d1dgua_.ent-d1eg3a1.ent", "d1dgua_.ent-d1exra_.ent", "d1dgua_.ent-d1g8ia_.ent", "d1dgua_.ent-d1ggwa_.ent", "d1dgua_.ent-d1hqva_.ent", "d1dgua_.ent-d1jfja_.ent", "d1dgua_.ent-d1k94a_.ent", "d1dgua_.ent-d1m31a_.ent", "d1dgua_.ent-d1m45a_.ent", "d1dgua_.ent-d1ncx__.ent", "d1dgua_.ent-d1rro__.ent", "d1dgua_.ent-d1sra__.ent", "d1dgua_.ent-d1wdcb_.ent", "d1dgua_.ent-d1wdcc_.ent", "d1dgua_.ent-d2pvba_.ent", "d1dgua_.ent-d2scpa_.ent", "d1dgua_.ent-d5pal__.ent", "d1dgwa_.ent-d1ds1a_.ent", "d1dgwa_.ent-d1dzra_.ent", "d1dgwa_.ent-d1e5sa_.ent", "d1dgwa_.ent-d1ep0a_.ent", "d1dgwa_.ent-d1eula1.ent", "d1dgwa_.ent-d1fi2a_.ent", "d1dgwa_.ent-d1ft9a2.ent", "d1dgwa_.ent-d1fxza1.ent", "d1dgwa_.ent-d1fxza2.ent", "d1dgwa_.ent-d1gp6a_.ent", "d1dgwa_.ent-d1gy9a_.ent", "d1dgwa_.ent-d1h2ka_.ent", "d1dgwa_.ent-d1hw5a2.ent", "d1dgwa_.ent-d1ig0a1.ent", "d1dgwa_.ent-d1jr7a_.ent", "d1dgwa_.ent-d1juha_.ent", "d1dgwa_.ent-d1lrha_.ent", "d1dgwa_.ent-d1m4oa_.ent", "d1dgwa_.ent-d1pmi__.ent", "d1dgwa_.ent-d1wapa_.ent", "d1dgwa_.ent-d2arca_.ent", "d1dgwa_.ent-d2phla1.ent", "d1dgwa_.ent-d2phla2.ent", "d1dhkb_.ent-d1dyka1.ent", "d1dhkb_.ent-d1dyka2.ent", "d1dhkb_.ent-d1h30a1.ent", "d1dhkb_.ent-d1kit_1.ent", "d1dhkb_.ent-d1xnb__.ent", "d1dhn__.ent-d1is8a_.ent", "d1dhn__.ent-d1uox_1.ent", "d1dhn__.ent-d1uox_2.ent", "d1dhpa_.ent-d1dosa_.ent", "d1dhpa_.ent-d1epxa_.ent", "d1dhpa_.ent-d1euaa_.ent", "d1dhpa_.ent-d1f74a_.ent", "d1dhpa_.ent-d1gvfa_.ent", "d1dhpa_.ent-d1gzga_.ent", "d1dhpa_.ent-d1h7na_.ent", "d1dhpa_.ent-d1hfba_.ent", "d1dhpa_.ent-d1i2oa_.ent", "d1dhpa_.ent-d1jcla_.ent", "d1dhpa_.ent-d1jcxa_.ent", "d1dhpa_.ent-d1l6wa_.ent", "d1dhpa_.ent-d1mzha_.ent", "d1dhpa_.ent-d1nal1_.ent", "d1dhpa_.ent-d1o0ya_.ent", "d1dhpa_.ent-d1qfea_.ent", "d1dhs__.ent-d1efva2.ent", "d1dhs__.ent-d1hzzc_.ent", "d1dhs__.ent-d1icia_.ent", "d1dhs__.ent-d1j8fa_.ent", "d1dhs__.ent-d1jsca1.ent", "d1dhs__.ent-d1ma3a_.ent", "d1dhs__.ent-d1o97d2.ent", "d1dhs__.ent-d1poxa1.ent", "d1dhs__.ent-d1pvda1.ent", "d1dhs__.ent-d1zpda1.ent", "d1di0a_.ent-d1ejba_.ent", "d1di0a_.ent-d1hqka_.ent", "d1di0a_.ent-d1kz1a_.ent", "d1di0a_.ent-d1rvv1_.ent", "d1di1a_.ent-d1ezfa_.ent", "d1di1a_.ent-d1jfaa_.ent", "d1di1a_.ent-d1n1ba2.ent", "d1di1a_.ent-d1ps1a_.ent", "d1di1a_.ent-d1uby__.ent", "d1di1a_.ent-d5eau_2.ent", "d1di2a_.ent-d1dq3a2.ent", "d1di2a_.ent-d1fjge2.ent", "d1di2a_.ent-d1kn0a_.ent", "d1di2a_.ent-d1o0wa2.ent", "d1di2a_.ent-d1pda_2.ent", "d1di2a_.ent-d1pkp_2.ent", "d1di2a_.ent-d1qu6a1.ent", "d1di2a_.ent-d1qu6a2.ent", "d1di2a_.ent-d1stu__.ent", "d1di6a_.ent-d1g8la3.ent", "d1di6a_.ent-d1jlja_.ent", "d1dih_2.ent-d1dpga2.ent", "d1dih_2.ent-d1e5qa2.ent", "d1dih_2.ent-d1ebfa2.ent", "d1dih_2.ent-d1f06a2.ent", "d1dih_2.ent-d1gr0a2.ent", "d1dih_2.ent-d1h6da2.ent", "d1dih_2.ent-d1j5pa3.ent", "d1dih_2.ent-d1jkia2.ent", "d1dih_2.ent-d1jn0a2.ent", "d1dih_2.ent-d1lc0a2.ent", "d1dih_2.ent-d1mb4a2.ent", "d1dih_2.ent-d1qkia2.ent", "d1diqa1.ent-d1e8ga1.ent", "d1diqa1.ent-d1f0xa1.ent", "d1diqa1.ent-d1i19a1.ent", "d1diqa2.ent-d1e8ga2.ent", "d1diqa2.ent-d1f0xa2.ent", "d1diqa2.ent-d1fo4a6.ent", "d1diqa2.ent-d1hska1.ent", "d1diqa2.ent-d1i19a2.ent", "d1diqa2.ent-d1jroa4.ent", "d1diqa2.ent-d1n62c2.ent", "d1diqa2.ent-d1uxy_1.ent", "d1diqc_.ent-d1e29a_.ent", "d1diqc_.ent-d1ezvd1.ent", "d1diqc_.ent-d1fcdc2.ent", "d1diqc_.ent-d1gu2a_.ent", "d1diqc_.ent-d1h32a1.ent", "d1diqc_.ent-d1iqca1.ent", "d1diqc_.ent-d1iqca2.ent", "d1diqc_.ent-d1jmxa1.ent", "d1diqc_.ent-d1jmxa2.ent", "d1diqc_.ent-d1kb0a1.ent", "d1diqc_.ent-d1mg2d_.ent", "d1diqc_.ent-d1qksa1.ent", "d1dixa_.ent-d1iooa_.ent", "d1dixa_.ent-d1iqqa_.ent", "d1dixa_.ent-d1jy5a_.ent", "d1dj0a1.ent-d1dj0a2.ent", "d1dj0a1.ent-d1k8wa1.ent", "d1dj0a2.ent-d1b3ta_.ent", "d1dj0a2.ent-d1dqaa1.ent", "d1dj0a2.ent-d1ekra_.ent", "d1dj0a2.ent-d1ftra1.ent", "d1dj0a2.ent-d1ftra2.ent", "d1dj0a2.ent-d1gpja3.ent", "d1dj0a2.ent-d1h72c2.ent", "d1dj0a2.ent-d1hlwa_.ent", "d1dj0a2.ent-d1jnrb_.ent", "d1dj0a2.ent-d1k8wa1.ent", "d1dj0a2.ent-d1qd1a2.ent", "d1dj0a2.ent-d1regx_.ent", "d1dj3a_.ent-d1bg2__.ent", "d1dj3a_.ent-d1c4oa1.ent", "d1dj3a_.ent-d1e2ka_.ent", "d1dj3a_.ent-d1e9ra_.ent", "d1dj3a_.ent-d1f9va_.ent", "d1dj3a_.ent-d1fmja_.ent", "d1dj3a_.ent-d1g41a_.ent", "d1dj3a_.ent-d1g8pa_.ent", "d1dj3a_.ent-d1i6ia_.ent", "d1dj3a_.ent-d1ii6a_.ent", "d1dj3a_.ent-d1iwea_.ent", "d1dj3a_.ent-d1ksfx3.ent", "d1dj3a_.ent-d1n0ua2.ent", "d1dj3a_.ent-d1pjr_1.ent", "d1dj3a_.ent-d1pjr_2.ent", "d1dj3a_.ent-d1qf5a_.ent", "d1dj3a_.ent-d1uaaa1.ent", "d1dj3a_.ent-d1uaaa2.ent", "d1dj3a_.ent-d2ncda_.ent", "d1dj7b_.ent-d1gcqc_.ent", "d1dj7b_.ent-d1i07a_.ent", "d1dj7b_.ent-d1ireb_.ent", "d1dj7b_.ent-d1jb0e_.ent", "d1dj7b_.ent-d1jo8a_.ent", "d1dj7b_.ent-d1vie__.ent", "d1dj7b_.ent-d1ycsb2.ent", "d1dj7b_.ent-d2ahjb_.ent", "d1dk5a_.ent-d1dm5a_.ent", "d1dk5a_.ent-d1g5na_.ent", "d1dk5a_.ent-d1hm6a_.ent", "d1dk8a_.ent-d1iapa_.ent", "d1dkgd2.ent-d1e4ft1.ent", "d1dkgd2.ent-d1e4ft2.ent", "d1dkgd2.ent-d1g99a1.ent", "d1dkgd2.ent-d1g99a2.ent", "d1dkgd2.ent-d1glag1.ent", "d1dkgd2.ent-d1glag2.ent", "d1dkgd2.ent-d1huxa_.ent", "d1dkgd2.ent-d1ig8a1.ent", "d1dkgd2.ent-d1ig8a2.ent", "d1dkgd2.ent-d1j6za2.ent", "d1dkgd2.ent-d1jcfa1.ent", "d1dkgd2.ent-d1k8ka1.ent", "d1dkgd2.ent-d1mwma1.ent", "d1dkgd2.ent-d1mwma2.ent", "d1dkgd2.ent-d1nbwa2.ent", "d1dkgd2.ent-d1nbwa3.ent", "d1dkia_.ent-d1e2ta_.ent", "d1dkia_.ent-d1euva_.ent", "d1dkia_.ent-d1f13a4.ent", "d1dkia_.ent-d1fh0a_.ent", "d1dkia_.ent-d1g0da4.ent", "d1dkia_.ent-d1gmya_.ent", "d1dkia_.ent-d1gx3a_.ent", "d1dkia_.ent-d1iu4a_.ent", "d1dkia_.ent-d1kxra_.ent", "d1dkia_.ent-d1l9na4.ent", "d1dkia_.ent-d1me4a_.ent", "d1dkia_.ent-d1nbfa_.ent", "d1dkia_.ent-d1ppn__.ent", "d1dkia_.ent-d1qmya_.ent", "d1dkia_.ent-d1uch__.ent", "d1dkia_.ent-d2act__.ent", "d1dkia_.ent-d2cb5a_.ent", "d1dkia_.ent-d3gcb__.ent", "d1dkia_.ent-d7pcka_.ent", "d1dkla_.ent-d1e58a_.ent", "d1dkla_.ent-d1fzta_.ent", "d1dkla_.ent-d1h2ea_.ent", "d1dkla_.ent-d1ihp__.ent", "d1dkla_.ent-d1nd6a_.ent", "d1dkla_.ent-d1qfxa_.ent", "d1dkla_.ent-d3pgm__.ent", "d1dkra1.ent-d1dkra2.ent", "d1dkra1.ent-d1dqna_.ent", "d1dkra1.ent-d1ecfa1.ent", "d1dkra1.ent-d1fsga_.ent", "d1dkra1.ent-d1g2qa_.ent", "d1dkra1.ent-d1g9sa_.ent", "d1dkra1.ent-d1gph11.ent", "d1dkra1.ent-d1hgxa_.ent", "d1dkra1.ent-d1i5ea_.ent", "d1dkra1.ent-d1l1qa_.ent", "d1dkra1.ent-d1lh0a_.ent", "d1dkra1.ent-d1nula_.ent", "d1dkra1.ent-d1qb7a_.ent", "d1dkra1.ent-d1tc1a_.ent", "d1dkra2.ent-d1dqna_.ent", "d1dkra2.ent-d1ecfa1.ent", "d1dkra2.ent-d1fsga_.ent", "d1dkra2.ent-d1g2qa_.ent", "d1dkra2.ent-d1g9sa_.ent", "d1dkra2.ent-d1gph11.ent", "d1dkra2.ent-d1hgxa_.ent", "d1dkra2.ent-d1i5ea_.ent", "d1dkra2.ent-d1l1qa_.ent", "d1dkra2.ent-d1lh0a_.ent", "d1dkra2.ent-d1nula_.ent", "d1dkra2.ent-d1qb7a_.ent", "d1dkra2.ent-d1tc1a_.ent", "d1dl0a_.ent-d1eit__.ent", "d1dl0a_.ent-d1emxa_.ent", "d1dl0a_.ent-d1g9pa_.ent", "d1dl0a_.ent-d1i25a_.ent", "d1dl0a_.ent-d1i26a_.ent", "d1dl0a_.ent-d1koza_.ent", "d1dl0a_.ent-d1kqha_.ent", "d1dl0a_.ent-d1lqra_.ent", "d1dl0a_.ent-d1lupa_.ent", "d1dl0a_.ent-d1nixa_.ent", "d1dl0a_.ent-d1niya_.ent", "d1dl0a_.ent-d1qk6a_.ent", "d1dl0a_.ent-d1qk7a_.ent", "d1dl0a_.ent-d1vtx__.ent", "d1dl2a_.ent-d1faea_.ent", "d1dl2a_.ent-d1fo3a_.ent", "d1dl2a_.ent-d1fp3a_.ent", "d1dl2a_.ent-d1gai__.ent", "d1dl2a_.ent-d1gxma_.ent", "d1dl2a_.ent-d1h54a1.ent", "d1dl2a_.ent-d1krea_.ent", "d1dl2a_.ent-d1ks8a_.ent", "d1dl2a_.ent-d1kwfa_.ent", "d1dl2a_.ent-d1ld8b_.ent", "d1dl2a_.ent-d1lf6a1.ent", "d1dl2a_.ent-d1n1ba1.ent", "d1dl2a_.ent-d1n7oa1.ent", "d1dl2a_.ent-d1qaza_.ent", "d1dl2a_.ent-d2sqca1.ent", "d1dl2a_.ent-d2sqca2.ent", "d1dl6a_.ent-d1i50i1.ent", "d1dl6a_.ent-d1i50i2.ent", "d1dl6a_.ent-d1pft__.ent", "d1dl6a_.ent-d1qyp__.ent", "d1dl6a_.ent-d1tfi__.ent", "d1dl6a_.ent-d1yua_1.ent", "d1dl6a_.ent-d1yua_2.ent", "d1dlc_1.ent-d1eut_2.ent", "d1dlc_1.ent-d1gmma_.ent", "d1dlc_1.ent-d1gu3a_.ent", "d1dlea_.ent-d1a0la_.ent", "d1dlea_.ent-d1agja_.ent", "d1dlea_.ent-d1arb__.ent", "d1dlea_.ent-d1azza_.ent", "d1dlea_.ent-d1bio__.ent", "d1dlea_.ent-d1bqya_.ent", "d1dlea_.ent-d1cgha_.ent", "d1dlea_.ent-d1ddja_.ent", "d1dlea_.ent-d1eaxa_.ent", "d1dlea_.ent-d1ekbb_.ent", "d1dlea_.ent-d1elva1.ent", "d1dlea_.ent-d1fjsa_.ent", "d1dlea_.ent-d1gdna_.ent", "d1dlea_.ent-d1gpza1.ent", "d1dlea_.ent-d1gvkb_.ent", "d1dlea_.ent-d1gvza_.ent", "d1dlea_.ent-d1hj9a_.ent", "d1dlea_.ent-d1klih_.ent", "d1dlea_.ent-d1m9ua_.ent", "d1dlea_.ent-d1mzaa_.ent", "d1dlea_.ent-d1qtfa_.ent", "d1dlea_.ent-d1rfna_.ent", "d1dlea_.ent-d2hlca_.ent", "d1dlfh_.ent-d1a2yb_.ent", "d1dlfh_.ent-d1akjd_.ent", "d1dlfh_.ent-d1b88a_.ent", "d1dlfh_.ent-d1bec_1.ent", "d1dlfh_.ent-d1c5ch1.ent", "d1dlfh_.ent-d1dlfl_.ent", "d1dlfh_.ent-d1dqta_.ent", "d1dlfh_.ent-d1fo0a_.ent", "d1dlfh_.ent-d1gsma2.ent", "d1dlfh_.ent-d1h5ba_.ent", "d1dlfh_.ent-d1hxma1.ent", "d1dlfh_.ent-d1ktke1.ent", "d1dlfh_.ent-d1kxvc_.ent", "d1dlfh_.ent-d1neu__.ent", "d1dlfh_.ent-d1nfdb1.ent", "d1dlfh_.ent-d1qfoa_.ent", "d1dlfh_.ent-d1tvda_.ent", "d1dlfh_.ent-d2rhe__.ent", "d1dlfl_.ent-d1c5ch1.ent", "d1dlfl_.ent-d1h5ba_.ent", "d1dlfl_.ent-d1nfdb1.ent", "d1dlja1.ent-d1f0ya1.ent", "d1dlja1.ent-d1i36a1.ent", "d1dlja1.ent-d1ks9a1.ent", "d1dlja1.ent-d1m66a1.ent", "d1dlja1.ent-d1pgja1.ent", "d1dlja1.ent-d1qmga1.ent", "d1dlja1.ent-d2pgd_1.ent", "d1dlja2.ent-d1bg6_2.ent", "d1dlja2.ent-d1cf2o1.ent", "d1dlja2.ent-d1dpga1.ent", "d1dlja2.ent-d1dssg1.ent", "d1dlja2.ent-d1e5qa1.ent", "d1dlja2.ent-d1f0ya2.ent", "d1dlja2.ent-d1lc0a1.ent", "d1dlja2.ent-d1lu9a1.ent", "d1dlja2.ent-d2naca1.ent", "d1dlja2.ent-d2pgd_2.ent", "d1dlja3.ent-d1efva1.ent", "d1dlja3.ent-d1ej2a_.ent", "d1dlja3.ent-d1f4la2.ent", "d1dlja3.ent-d1f7ua2.ent", "d1dlja3.ent-d1gpma1.ent", "d1dlja3.ent-d1ihoa_.ent", "d1dlja3.ent-d1ile_3.ent", "d1dlja3.ent-d1irxa2.ent", "d1dlja3.ent-d1j09a2.ent", "d1dlja3.ent-d1jgta1.ent", "d1dlja3.ent-d1jhda2.ent", "d1dlja3.ent-d1jila_.ent", "d1dlja3.ent-d1jmva_.ent", "d1dlja3.ent-d1k4ma_.ent", "d1dlja3.ent-d1k92a1.ent", "d1dlja3.ent-d1kqna_.ent", "d1dlja3.ent-d1kqpa_.ent", "d1dlja3.ent-d1li5a2.ent", "d1dlja3.ent-d1mjha_.ent", "d1dlja3.ent-d1n3la_.ent", "d1dlja3.ent-d1o97c_.ent", "d1dlja3.ent-d1o97d1.ent", "d1dlja3.ent-d1qjca_.ent", "d1dlja3.ent-d1sur__.ent", "d1dlwa_.ent-d1ew6a_", "d1dlwa_.ent-d1ew6a_.ent", "d1dlwa_.ent-d1gtea1", "d1dlwa_.ent-d1gtea1.ent", "d1dlwa_.ent-d1gvha1", "d1dlwa_.ent-d1gvha1.ent", "d1dlwa_.ent-d1h97a_", "d1dlwa_.ent-d1h97a_.ent", "d1dlwa_.ent-d1irdb_", "d1dlwa_.ent-d1irdb_.ent", "d1dlwa_.ent-d1itha_", "d1dlwa_.ent-d1itha_.ent", "d1dlwa_.ent-d1qlab1", "d1dlwa_.ent-d1qlab1.ent", "d1dlwa_.ent-d2gdm__", "d1dlwa_.ent-d2gdm__.ent", "d1dm0a_.ent-d1hwma_.ent", "d1dm0a_.ent-d1ift__.ent", "d1dm0a_.ent-d1mrj__.ent", "d1dm0a_.ent-d1qi7a_.ent", "d1dm5a_.ent-d1g5na_.ent", "d1dm5a_.ent-d1hm6a_.ent", "d1dm9a_.ent-d1fjgd_.ent", "d1dm9a_.ent-d1h3fa2.ent", "d1dm9a_.ent-d1jh3a_.ent", "d1dmc__.ent-d1fmya_.ent", "d1dmc__.ent-d1ji9a_.ent", "d1dmc__.ent-d1jjda_.ent", "d1dmc__.ent-d1qjka_.ent", "d1dmc__.ent-d4mt2__.ent", "d1dmha_.ent-d1eo9a_.ent", "d1dmha_.ent-d1eo9b_.ent", "d1dmha_.ent-d1f86a_.ent", "d1dmha_.ent-d1h8la1.ent", "d1dmha_.ent-d1lm8v_.ent", "d1dmha_.ent-d1qhoa2.ent", "d1dmla1.ent-d1dmla2.ent", "d1dmla1.ent-d1ge8a1.ent", "d1dmla1.ent-d1ge8a2.ent", "d1dmla1.ent-d1plq_1.ent", "d1dmla1.ent-d1plq_2.ent", "d1dmla1.ent-d2pola1.ent", "d1dmla1.ent-d2pola2.ent", "d1dmla1.ent-d2pola3.ent", "d1dmla2.ent-d1ge8a1.ent", "d1dmla2.ent-d1ge8a2.ent", "d1dmla2.ent-d1plq_1.ent", "d1dmla2.ent-d1plq_2.ent", "d1dmla2.ent-d2pola1.ent", "d1dmla2.ent-d2pola2.ent", "d1dmla2.ent-d2pola3.ent", "d1dmta_.ent-d1eb6a_.ent", "d1dmta_.ent-d1epwa3.ent", "d1dmta_.ent-d1ezm__.ent", "d1dmta_.ent-d1g12a_.ent", "d1dmta_.ent-d1gkda_.ent", "d1dmta_.ent-d1gqia2.ent", "d1dmta_.ent-d1hs6a3.ent", "d1dmta_.ent-d1i1ip_.ent", "d1dmta_.ent-d1j7na1.ent", "d1dmta_.ent-d1j7na2.ent", "d1dmta_.ent-d1jaka2.ent", "d1dmta_.ent-d1jk3a_.ent", "d1dmta_.ent-d1k7ia2.ent", "d1dmta_.ent-d1k9xa_.ent", "d1dmta_.ent-d1kapp2.ent", "d1dmta_.ent-d1keia_.ent", "d1dmta_.ent-d1kufa_.ent", "d1dmta_.ent-d1lml__.ent", "d1dmta_.ent-d1qba_4.ent", "d1dmta_.ent-d3btaa3.ent", "d1dmua_.ent-d1dzfa1.ent", "d1dmua_.ent-d1ev7a_.ent", "d1dmua_.ent-d1f1za2.ent", "d1dmua_.ent-d1fiua_.ent", "d1dmua_.ent-d1gefa_.ent", "d1dmua_.ent-d1hh1a_.ent", "d1dmua_.ent-d1kc6a_.ent", "d1dmua_.ent-d1knva_.ent", "d1dmua_.ent-d1m0da_.ent", "d1dmua_.ent-d1vsra_.ent", "d1dmua_.ent-d2foka4.ent", "d1dmua_.ent-d3pvia_.ent", "d1dmza_.ent-d1g6ga_.ent", "d1dmza_.ent-d1gxca_.ent", "d1dmza_.ent-d1lgpa_.ent", "d1dmza_.ent-d1mjsa_.ent", "d1dmza_.ent-d1ygs__.ent", "d1dnpa1.ent-d1iqra1.ent", "d1dnpa1.ent-d1np7a1.ent", "d1dnpa1.ent-d1qnf_1.ent", "d1dnpa2.ent-d1iqra2.ent", "d1dnpa2.ent-d1np7a2.ent", "d1dnpa2.ent-d1qnf_2.ent", "d1dnv__.ent-d1a6ca1.ent", "d1dnv__.ent-d1a6ca2.ent", "d1dnv__.ent-d1a6ca3.ent", "d1dnv__.ent-d1aym1_.ent", "d1dnv__.ent-d1aym2_.ent", "d1dnv__.ent-d1b35a_.ent", "d1dnv__.ent-d1b35b_.ent", "d1dnv__.ent-d1b35c_.ent", "d1dnv__.ent-d1bev1_.ent", "d1dnv__.ent-d1bev3_.ent", "d1dnv__.ent-d1bmv1_.ent", "d1dnv__.ent-d1bmv2_.ent", "d1dnv__.ent-d1c8na_.ent", "d1dnv__.ent-d1cwpa_.ent", "d1dnv__.ent-d1d4m1_.ent", "d1dnv__.ent-d1ddla_.ent", "d1dnv__.ent-d1f15a_.ent", "d1dnv__.ent-d1k5ma_.ent", "d1dnv__.ent-d1novc_.ent", "d1dnv__.ent-d1pov0_.ent", "d1dnv__.ent-d1pvc1_.ent", "d1dnv__.ent-d1qqp1_.ent", "d1dnv__.ent-d1qqp2_.ent", "d1dnv__.ent-d1qqp3_.ent", "d1dnv__.ent-d1sva1_.ent", "d1dnv__.ent-d1tmf1_.ent", "d1dnv__.ent-d1vpsa_.ent", "d1dnv__.ent-d2bbva_.ent", "d1dnv__.ent-d2bpa2_.ent", "d1dnv__.ent-d2mev1_.ent", "d1dnv__.ent-d2mev2_.ent", "d1dnv__.ent-d2stv__.ent", "d1dnya_.ent-d1dv5a_.ent", "d1dnya_.ent-d1emva_.ent", "d1dnya_.ent-d1klpa_.ent", "d1dnya_.ent-d1l0ia_.ent", "d1do5a_.ent-d1ej8a_.ent", "d1do5a_.ent-d1eso__.ent", "d1do5a_.ent-d1xsoa_.ent", "d1do5a_.ent-d1yaia_.ent", "d1dofa_.ent-d1fura_.ent", "d1dofa_.ent-d1hy0a_.ent", "d1dofa_.ent-d1jswa_.ent", "d1doi__.ent-d1e9ma_.ent", "d1doi__.ent-d1feha2.ent", "d1doi__.ent-d1fo4a2.ent", "d1doi__.ent-d1hlra2.ent", "d1doi__.ent-d1i7ha_.ent", "d1doi__.ent-d1jq4a_.ent", "d1doi__.ent-d1jroa2.ent", "d1doi__.ent-d1kf6b2.ent", "d1doi__.ent-d1krha3.ent", "d1doi__.ent-d1l5pa_.ent", "d1doi__.ent-d1n62a2.ent", "d1doi__.ent-d1nekb2.ent", "d1doi__.ent-d1put__.ent", "d1doi__.ent-d1qlab2.ent", "d1doi__.ent-d2pia_3.ent", "d1doka_.ent-d1eiha_.ent", "d1doka_.ent-d1el0a_.ent", "d1doka_.ent-d1f2la_.ent", "d1doka_.ent-d1g2ta_.ent", "d1doka_.ent-d1j9oa_.ent", "d1doka_.ent-d1m8aa_.ent", "d1doka_.ent-d1qg7a_.ent", "d1doka_.ent-d1tvxa_.ent", "d1doka_.ent-d2hcc__.ent", "d1doka_.ent-d3il8__.ent", "d1doqa_.ent-d1dxsa_.ent", "d1doqa_.ent-d1f44a1.ent", "d1doqa_.ent-d1floa1.ent", "d1doqa_.ent-d1go3f_.ent", "d1doqa_.ent-d1jmsa1.ent", "d1doqa_.ent-d1jmsa3.ent", "d1doqa_.ent-d1jyga_.ent", "d1doqa_.ent-d1kfta_.ent", "d1doqa_.ent-d1lb2b_.ent", "d1doqa_.ent-d1tfr_1.ent", "d1dosa_.ent-d1epxa_.ent", "d1dosa_.ent-d1euaa_.ent", "d1dosa_.ent-d1f74a_.ent", "d1dosa_.ent-d1gvfa_.ent", "d1dosa_.ent-d1gzga_.ent", "d1dosa_.ent-d1h7na_.ent", "d1dosa_.ent-d1hfba_.ent", "d1dosa_.ent-d1i2oa_.ent", "d1dosa_.ent-d1jcla_.ent", "d1dosa_.ent-d1jcxa_.ent", "d1dosa_.ent-d1l6wa_.ent", "d1dosa_.ent-d1mzha_.ent", "d1dosa_.ent-d1nal1_.ent", "d1dosa_.ent-d1o0ya_.ent", "d1dosa_.ent-d1qfea_.ent", "d1dova_.ent-d1ei7a_.ent", "d1dova_.ent-d1f1ma_.ent", "d1dova_.ent-d1fts_1.ent", "d1dova_.ent-d1he1a_.ent", "d1dova_.ent-d1jr8a_.ent", "d1dova_.ent-d1k04a_.ent", "d1dova_.ent-d1knya1.ent", "d1dova_.ent-d1ls1a1.ent", "d1dova_.ent-d1nfn__.ent", "d1dova_.ent-d1nlxa_.ent", "d1dova_.ent-d256ba_.ent", "d1dova_.ent-d2a0b__.ent", "d1dova_.ent-d2liga_.ent", "d1dova_.ent-d2mhr__.ent", "d1dova_.ent-d3fapb_.ent", "d1doza_.ent-d1hrka_.ent", "d1doza_.ent-d1lbqa_.ent", "d1doza_.ent-d1m1na_.ent", "d1doza_.ent-d1m1nb_.ent", "d1doza_.ent-d1n2za_.ent", "d1doza_.ent-d1qgoa_.ent", "d1doza_.ent-d1toaa_.ent", "d1dp3a_.ent-d1exea_.ent", "d1dp3a_.ent-d1ihfa_.ent", "d1dp3a_.ent-d1ihfb_.ent", "d1dp4a_.ent-d1ewka_.ent", "d1dp4a_.ent-d1gca__.ent", "d1dp4a_.ent-d1jdpa_.ent", "d1dp4a_.ent-d1jx6a_.ent", "d1dp4a_.ent-d1jyea_.ent", "d1dp4a_.ent-d1pea__.ent", "d1dp4a_.ent-d1rpja_.ent", "d1dp4a_.ent-d2dri__.ent", "d1dp4a_.ent-d2liv__.ent", "d1dp4a_.ent-d8abp__.ent", "d1dpe__.ent-d1eu8a_.ent", "d1dpe__.ent-d1h76a2.ent", "d1dpe__.ent-d1i6aa_.ent", "d1dpe__.ent-d1ii5a_.ent", "d1dpe__.ent-d1ixh__.ent", "d1dpe__.ent-d1jeta_.ent", "d1dpe__.ent-d1kwha_.ent", "d1dpe__.ent-d1lst__.ent", "d1dpe__.ent-d1m5ea_.ent", "d1dpe__.ent-d1mrp__.ent", "d1dpe__.ent-d1nh8a1.ent", "d1dpe__.ent-d1pda_1.ent", "d1dpe__.ent-d1pot__.ent", "d1dpe__.ent-d1sbp__.ent", "d1dpe__.ent-d1wdna_.ent", "d1dpe__.ent-d3mbp__.ent", "d1dpe__.ent-d3thia_.ent", "d1dpga1.ent-d1bg6_2.ent", "d1dpga1.ent-d1cf2o1.ent", "d1dpga1.ent-d1dssg1.ent", "d1dpga1.ent-d1e5qa1.ent", "d1dpga1.ent-d1f0ya2.ent", "d1dpga1.ent-d1lc0a1.ent", "d1dpga1.ent-d1lu9a1.ent", "d1dpga1.ent-d2naca1.ent", "d1dpga1.ent-d2pgd_2.ent", "d1dpga2.ent-d1e5qa2.ent", "d1dpga2.ent-d1ebfa2.ent", "d1dpga2.ent-d1f06a2.ent", "d1dpga2.ent-d1gr0a2.ent", "d1dpga2.ent-d1h6da2.ent", "d1dpga2.ent-d1j5pa3.ent", "d1dpga2.ent-d1jkia2.ent", "d1dpga2.ent-d1jn0a2.ent", "d1dpga2.ent-d1lc0a2.ent", "d1dpga2.ent-d1mb4a2.ent", "d1dpga2.ent-d1qkia2.ent", "d1dpja_.ent-d1fkna_.ent", "d1dpja_.ent-d1fmb__.ent", "d1dpja_.ent-d1idaa_.ent", "d1dpja_.ent-d1j71a_.ent", "d1dpja_.ent-d1kzka_.ent", "d1dpja_.ent-d1lf2a_.ent", "d1dpja_.ent-d1mpp__.ent", "d1dpja_.ent-d1nsoa_.ent", "d1dpja_.ent-d2apr__.ent", "d1dpja_.ent-d2rspa_.ent", "d1dpja_.ent-d3psg__.ent", "d1dpja_.ent-d4fiv__.ent", "d1dpsa_.ent-d1euma_.ent", "d1dpsa_.ent-d1h0oa_.ent", "d1dpsa_.ent-d1jgca_.ent", "d1dpsa_.ent-d1ji4a_.ent", "d1dpsa_.ent-d1jiga_.ent", "d1dpsa_.ent-d1jk0b_.ent", "d1dpsa_.ent-d1jkva_.ent", "d1dpsa_.ent-d1jqca_.ent", "d1dpsa_.ent-d1kgna_.ent", "d1dpsa_.ent-d1lkoa1.ent", "d1dpsa_.ent-d1mtyb_.ent", "d1dpsa_.ent-d1mtyd_.ent", "d1dpsa_.ent-d1qgha_.ent", "d1dpsa_.ent-d1rcd__.ent", "d1dpta_.ent-d1gd0a_.ent", "d1dpta_.ent-d1gyxa_.ent", "d1dpta_.ent-d1hfoa_.ent", "d1dpta_.ent-d1otfa_.ent", "d1dpta_.ent-d1otga_.ent", "d1dq3a1.ent-d1gppa_.ent", "d1dq3a2.ent-d1kn0a_.ent", "d1dq3a2.ent-d1o0wa2.ent", "d1dq3a2.ent-d1pda_2.ent", "d1dq3a2.ent-d1pkp_2.ent", "d1dq3a2.ent-d1qu6a2.ent", "d1dq3a3.ent-d1dq3a4.ent", "d1dq3a3.ent-d1g9za_.ent", "d1dq3a3.ent-d1iba__.ent", "d1dq3a3.ent-d1jvaa2.ent", "d1dq3a3.ent-d1jvaa3.ent", "d1dq3a4.ent-d1g9za_.ent", "d1dq3a4.ent-d1iba__.ent", "d1dq3a4.ent-d1jvaa2.ent", "d1dq3a4.ent-d1jvaa3.ent", "d1dqea_.ent-d1eg3a1.ent", "d1dqea_.ent-d1eg3a2.ent", "d1dqea_.ent-d1el4a_.ent", "d1dqea_.ent-d1fi6a_.ent", "d1dqea_.ent-d1h8ba_.ent", "d1dqea_.ent-d1iioa_.ent", "d1dqea_.ent-d1j7qa_.ent", "d1dqea_.ent-d1k94a_.ent", "d1dqea_.ent-d1m45a_.ent", "d1dqea_.ent-d1psra_.ent", "d1dqea_.ent-d1qasa1.ent", "d1dqea_.ent-d1rec__.ent", "d1dqea_.ent-d1sra__.ent", "d1dqea_.ent-d2cbla1.ent", "d1dqea_.ent-d2pvba_.ent", "d1dqea_.ent-d2sas__.ent", "d1dqea_.ent-d2scpa_.ent", "d1dqga_.ent-d1hcd__.ent", "d1dqga_.ent-d1hwmb1.ent", "d1dqga_.ent-d1hwmb2.ent", "d1dqga_.ent-d1jlxa1.ent", "d1dqga_.ent-d1knma_.ent", "d1dqga_.ent-d1l2ha_.ent", "d1dqga_.ent-d1n4ka2.ent", "d1dqia_.ent-d1eaja_.ent", "d1dqia_.ent-d1grwa_.ent", "d1dqia_.ent-d1j0ha1.ent", "d1dqia_.ent-d1soxa1.ent", "d1dqna_.ent-d1ecfa1.ent", "d1dqna_.ent-d1fsga_.ent", "d1dqna_.ent-d1g2qa_.ent", "d1dqna_.ent-d1g9sa_.ent", "d1dqna_.ent-d1gph11.ent", "d1dqna_.ent-d1hgxa_.ent", "d1dqna_.ent-d1i5ea_.ent", "d1dqna_.ent-d1l1qa_.ent", "d1dqna_.ent-d1lh0a_.ent", "d1dqna_.ent-d1nula_.ent", "d1dqna_.ent-d1qb7a_.ent", "d1dqna_.ent-d1tc1a_.ent", "d1dqsa_.ent-d1j5ra_.ent", "d1dqsa_.ent-d1jq5a_.ent", "d1dqsa_.ent-d1kq3a_.ent", "d1dqta_.ent-d1a2yb_.ent", "d1dqta_.ent-d1akjd_.ent", "d1dqta_.ent-d1b88a_.ent", "d1dqta_.ent-d1bec_1.ent", "d1dqta_.ent-d1c5ch1.ent", "d1dqta_.ent-d1dlfl_.ent", "d1dqta_.ent-d1fo0a_.ent", "d1dqta_.ent-d1gsma2.ent", "d1dqta_.ent-d1h5ba_.ent", "d1dqta_.ent-d1neu__.ent", "d1dqta_.ent-d1nfdb1.ent", "d1dqta_.ent-d1qfoa_.ent", "d1dqta_.ent-d1tvda_.ent", "d1dqta_.ent-d2rhe__.ent", "d1dqua_.ent-d1dxea_.ent", "d1dqua_.ent-d1e0ta2.ent", "d1dqua_.ent-d1f8ma_.ent", "d1dqua_.ent-d1jqna_.ent", "d1dqua_.ent-d1jqoa_.ent", "d1dqua_.ent-d1kbla1.ent", "d1dqva1.ent-d1dsya_.ent", "d1dqva1.ent-d1e8xa2.ent", "d1dqva1.ent-d1gmia_.ent", "d1dqva1.ent-d1k5wa_.ent", "d1dqva1.ent-d1qasa2.ent", "d1dqva1.ent-d1rlw__.ent", "d1dqva1.ent-d1rsy__.ent", "d1dqva1.ent-d3rpba_.ent", "d1dqwa_.ent-d1eixa_.ent", "d1dqwa_.ent-d1geqa_.ent", "d1dqwa_.ent-d1i4na_.ent", "d1dqwa_.ent-d1jvna1.ent", "d1dqwa_.ent-d1km3a_.ent", "d1dqwa_.ent-d1kv8a_.ent", "d1dqwa_.ent-d1nsj__.ent", "d1dqwa_.ent-d1pii_1.ent", "d1dqwa_.ent-d1pii_2.ent", "d1dqwa_.ent-d1qopa_.ent", "d1dqwa_.ent-d1rpxa_.ent", "d1dqwa_.ent-d1thfd_.ent", "d1dqza_.ent-d1ei9a_.ent", "d1dqza_.ent-d1ex9a_.ent", "d1dqza_.ent-d1fj2a_.ent", "d1dqza_.ent-d1gkla_.ent", "d1dqza_.ent-d1hlga_.ent", "d1dqza_.ent-d1imja_.ent", "d1dqza_.ent-d1ispa_.ent", "d1dqza_.ent-d1jfra_.ent", "d1dqza_.ent-d1ju3a2.ent", "d1dqza_.ent-d1ku0a_.ent", "d1dqza_.ent-d1l7aa_.ent", "d1dqza_.ent-d1lzla_.ent", "d1dqza_.ent-d1mnaa_.ent", "d1dqza_.ent-d1n1ma2.ent", "d1dqza_.ent-d1qj4a_.ent", "d1dqza_.ent-d1qlwa_.ent", "d1dqza_.ent-d1qo7a_.ent", "d1dqza_.ent-d1tca__.ent", "d1dqza_.ent-d1thta_.ent", "d1dqza_.ent-d3tgl__.ent", "d1dro__.ent-d1dyna_.ent", "d1dro__.ent-d1eaza_.ent", "d1dro__.ent-d1evha_.ent", "d1dro__.ent-d1faoa_.ent", "d1dro__.ent-d1fhoa_.ent", "d1dro__.ent-d1gg3a2.ent", "d1dro__.ent-d1h4ra2.ent", "d1dro__.ent-d1k5db_.ent", "d1dro__.ent-d1ki1b2.ent", "d1dro__.ent-d1mai__.ent", "d1dro__.ent-d1mixa2.ent", "d1dro__.ent-d1mkea1.ent", "d1dro__.ent-d1pls__.ent", "d1dro__.ent-d1qqga1.ent", "d1dro__.ent-d1qqga2.ent", "d1dro__.ent-d1shca_.ent", "d1ds1a_.ent-d1e5sa_.ent", "d1ds1a_.ent-d1ep0a_.ent", "d1ds1a_.ent-d1eula1.ent", "d1ds1a_.ent-d1fi2a_.ent", "d1ds1a_.ent-d1ft9a2.ent", "d1ds1a_.ent-d1fxza1.ent", "d1ds1a_.ent-d1gp6a_.ent", "d1ds1a_.ent-d1gy9a_.ent", "d1ds1a_.ent-d1h2ka_.ent", "d1ds1a_.ent-d1hw5a2.ent", "d1ds1a_.ent-d1ig0a1.ent", "d1ds1a_.ent-d1jr7a_.ent", "d1ds1a_.ent-d1juha_.ent", "d1ds1a_.ent-d1lrha_.ent", "d1ds1a_.ent-d1m4oa_.ent", "d1ds1a_.ent-d1pmi__.ent", "d1ds1a_.ent-d1qjea_.ent", "d1ds1a_.ent-d1wapa_.ent", "d1ds1a_.ent-d2arca_.ent", "d1dsva_.ent-d1eska_.ent", "d1dsya_.ent-d1e8xa2.ent", "d1dsya_.ent-d1gmia_.ent", "d1dsya_.ent-d1k5wa_.ent", "d1dsya_.ent-d1qasa2.ent", "d1dsya_.ent-d1rlw__.ent", "d1dsya_.ent-d1rsy__.ent", "d1dsya_.ent-d3rpba_.ent", "d1dsza_.ent-d1fjgn_.ent", "d1dsza_.ent-d1g47a1.ent", "d1dsza_.ent-d1g47a2.ent", "d1dsza_.ent-d1gnf__.ent", "d1dsza_.ent-d1ibia2.ent", "d1dsza_.ent-d1iml_2.ent", "d1dsza_.ent-d1jj2t_.ent", "d1dsza_.ent-d1k3xa3.ent", "d1dsza_.ent-d1kb2a_.ent", "d1dsza_.ent-d1l1za3.ent", "d1dsza_.ent-d1lata_.ent", "d1dsza_.ent-d1lv3a_.ent", "d1dsza_.ent-d1zfo__.ent", "d1dsza_.ent-d2nllb_.ent", "d1dsza_.ent-d3gata_.ent", "d1dsza_.ent-d7gata_.ent", "d1dt6a_.ent-d1dz4a_.ent", "d1dt6a_.ent-d1e9xa_.ent", "d1dt6a_.ent-d1io7a_.ent", "d1dt6a_.ent-d1jfba_.ent", "d1dt6a_.ent-d1jipa_.ent", "d1dt6a_.ent-d1jpza_.ent", "d1dt6a_.ent-d1lfka_.ent", "d1dt6a_.ent-d1n97a_.ent", "d1dt9a1.ent-d1fjgk_.ent", "d1dt9a1.ent-d1ilya_.ent", "d1dt9a1.ent-d1jj2m_.ent", "d1dt9a2.ent-d1e7ka_.ent", "d1dt9a2.ent-d1ipaa2.ent", "d1dt9a2.ent-d1jj2f_.ent", "d1dtja_.ent-d1j4wa1.ent", "d1dtja_.ent-d1j4wa2.ent", "d1dtja_.ent-d1k1ga_.ent", "d1dtja_.ent-d1khma_.ent", "d1dtja_.ent-d1vig__.ent", "d1dtja_.ent-d2fmr__.ent", "d1dtwa_.ent-d1dtwb1.ent", "d1dtwa_.ent-d1gpua1.ent", "d1dtwa_.ent-d1gpua2.ent", "d1dtwa_.ent-d1ik6a1.ent", "d1dtwa_.ent-d1jsca2.ent", "d1dtwa_.ent-d1jsca3.ent", "d1dtwa_.ent-d1keka1.ent", "d1dtwa_.ent-d1keka2.ent", "d1dtwa_.ent-d1l8aa1.ent", "d1dtwa_.ent-d1l8aa2.ent", "d1dtwa_.ent-d1poxa2.ent", "d1dtwa_.ent-d1poxa3.ent", "d1dtwa_.ent-d1pvda2.ent", "d1dtwa_.ent-d1pvda3.ent", "d1dtwa_.ent-d1zpda2.ent", "d1dtwa_.ent-d1zpda3.ent", "d1dtwb1.ent-d1gpua1.ent", "d1dtwb1.ent-d1gpua2.ent", "d1dtwb1.ent-d1ik6a1.ent", "d1dtwb1.ent-d1jsca2.ent", "d1dtwb1.ent-d1jsca3.ent", "d1dtwb1.ent-d1keka1.ent", "d1dtwb1.ent-d1keka2.ent", "d1dtwb1.ent-d1l8aa1.ent", "d1dtwb1.ent-d1l8aa2.ent", "d1dtwb1.ent-d1poxa2.ent", "d1dtwb1.ent-d1poxa3.ent", "d1dtwb1.ent-d1pvda2.ent", "d1dtwb1.ent-d1pvda3.ent", "d1dtwb1.ent-d1zpda2.ent", "d1dtwb1.ent-d1zpda3.ent", "d1dtwb2.ent-d1gpua3.ent", "d1dtwb2.ent-d1ik6a2.ent", "d1dtwb2.ent-d1itza3.ent", "d1dtwb2.ent-d1keka3.ent", "d1dtwb2.ent-d1l8aa3.ent", "d1du2a_.ent-d1e52a_.ent", "d1du2a_.ent-d1e79h1.ent", "d1du2a_.ent-d1eiya1.ent", "d1du2a_.ent-d1fpoa1.ent", "d1du2a_.ent-d1fxkc_.ent", "d1du2a_.ent-d1gh6a_.ent", "d1du2a_.ent-d1grj_1.ent", "d1du2a_.ent-d1hdj__.ent", "d1du2a_.ent-d1ivsa1.ent", "d1du2a_.ent-d1ix9a1.ent", "d1du2a_.ent-d1jj2u_.ent", "d1du2a_.ent-d1k4ta1.ent", "d1du2a_.ent-d1lrza1.ent", "d1du2a_.ent-d1seta1.ent", "d1duga1.ent-d1e6ba1.ent", "d1duga1.ent-d1eema1.ent", "d1duga1.ent-d1f2ea1.ent", "d1duga1.ent-d1fw1a1.ent", "d1duga1.ent-d1g7oa1.ent", "d1duga1.ent-d1glqa1.ent", "d1duga1.ent-d1gnwa1.ent", "d1duga1.ent-d1gula1.ent", "d1duga1.ent-d1gwca1.ent", "d1duga1.ent-d1jlva1.ent", "d1duga1.ent-d1k0da1.ent", "d1duga1.ent-d1k0ma1.ent", "d1duga1.ent-d1k3ya1.ent", "d1duga1.ent-d1ljra1.ent", "d1duga1.ent-d1m0ua1.ent", "d1duga1.ent-d1pd211.ent", "d1duga1.ent-d1pmt_1.ent", "d1duga1.ent-d2gsq_1.ent", "d1duga1.ent-d2gsta1.ent", "d1dun__.ent-d1euwa_.ent", "d1dun__.ent-d1f7da_.ent", "d1dun__.ent-d1mq7a_.ent", "d1duvg1.ent-d1duvg2.ent", "d1duvg1.ent-d1ekxa2.ent", "d1duvg1.ent-d1jfla1.ent", "d1duvg1.ent-d1jfla2.ent", "d1duvg1.ent-d1js1x1.ent", "d1duvg1.ent-d1js1x2.ent", "d1duvg1.ent-d1ml4a1.ent", "d1duvg1.ent-d1ml4a2.ent", "d1duvg1.ent-d1otha1.ent", "d1duvg1.ent-d1otha2.ent", "d1duvg2.ent-d1ekxa2.ent", "d1duvg2.ent-d1jfla1.ent", "d1duvg2.ent-d1jfla2.ent", "d1duvg2.ent-d1js1x1.ent", "d1duvg2.ent-d1js1x2.ent", "d1duvg2.ent-d1ml4a1.ent", "d1duvg2.ent-d1ml4a2.ent", "d1duvg2.ent-d1otha1.ent", "d1duvg2.ent-d1otha2.ent", "d1dv1a1.ent-d1e2wa2.ent", "d1dv1a1.ent-d1gpr__.ent", "d1dv1a1.ent-d1gsoa1.ent", "d1dv1a1.ent-d1hcz_2.ent", "d1dv1a1.ent-d1htp__.ent", "d1dv1a1.ent-d1k8ma_.ent", "d1dv1a1.ent-d1kjqa1.ent", "d1dv1a3.ent-d1e4ea2.ent", "d1dv1a3.ent-d1ehia2.ent", "d1dv1a3.ent-d1eucb2.ent", "d1dv1a3.ent-d1gsa_2.ent", "d1dv1a3.ent-d1gsoa3.ent", "d1dv1a3.ent-d1iow_2.ent", "d1dv1a3.ent-d1jkjb2.ent", "d1dv1a3.ent-d1kbla3.ent", "d1dv1a3.ent-d1kjqa3.ent", "d1dv1a3.ent-d1m0wa2.ent", "d1dv1a3.ent-d2hgsa4.ent", "d1dv5a_.ent-d1emva_.ent", "d1dv5a_.ent-d1klpa_.ent", "d1dv5a_.ent-d1l0ia_.ent", "d1dv8a_.ent-d1b08a1.ent", "d1dv8a_.ent-d1b6e__.ent", "d1dv8a_.ent-d1byfa_.ent", "d1dv8a_.ent-d1cwva5.ent", "d1dv8a_.ent-d1e87a_.ent", "d1dv8a_.ent-d1f00i3.ent", "d1dv8a_.ent-d1fvub_.ent", "d1dv8a_.ent-d1g1ta1.ent", "d1dv8a_.ent-d1h8ua_.ent", "d1dv8a_.ent-d1hq8a_.ent", "d1dv8a_.ent-d1jwia_.ent", "d1dv8a_.ent-d1jwib_.ent", "d1dv8a_.ent-d1li1a1.ent", "d1dv8a_.ent-d1li1a2.ent", "d1dv8a_.ent-d1prtb2.ent", "d1dv8a_.ent-d1qo3c_.ent", "d1dv8a_.ent-d1tsg__.ent", "d1dvpa1.ent-d1elka_.ent", "d1dvpa1.ent-d1eyha_.ent", "d1dvpa2.ent-d1f62a_.ent", "d1dvpa2.ent-d1fp0a1.ent", "d1dvpa2.ent-d1joca1.ent", "d1dvpa2.ent-d1vfya_.ent", "d1dw0a_.ent-d1co6a_.ent", "d1dw0a_.ent-d1etpa2.ent", "d1dw0a_.ent-d1hroa_.ent", "d1dw0a_.ent-d1kb0a1.ent", "d1dw0a_.ent-d1kv9a1.ent", "d1dw0a_.ent-d1nira1.ent", "d1dw0a_.ent-d1ql3a_.ent", "d1dw0a_.ent-d1qn2a_.ent", "d1dw0a_.ent-d1ycc__.ent", "d1dw0a_.ent-d3c2c__.ent", "d1dwma_.ent-d1lw6i_.ent", "d1dwna_.ent-d1e6ta_.ent", "d1dwna_.ent-d1qbea_.ent", "d1dx4a_.ent-d1ac5__.ent", "d1dx4a_.ent-d1bu8a2.ent", "d1dx4a_.ent-d1cpy__.ent", "d1dx4a_.ent-d1cr6a2.ent", "d1dx4a_.ent-d1cvl__.ent", "d1dx4a_.ent-d1ea5a_.ent", "d1dx4a_.ent-d1hlga_.ent", "d1dx4a_.ent-d1ivya_.ent", "d1dx4a_.ent-d1iz7a_.ent", "d1dx4a_.ent-d1jjia_.ent", "d1dx4a_.ent-d1jkma_.ent", "d1dx4a_.ent-d1ju3a2.ent", "d1dx4a_.ent-d1k4ya_.ent", "d1dx4a_.ent-d1ku0a_.ent", "d1dx4a_.ent-d1l7aa_.ent", "d1dx4a_.ent-d1llfa_.ent", "d1dx4a_.ent-d1lnsa3.ent", "d1dx4a_.ent-d1lzla_.ent", "d1dx4a_.ent-d1qe3a_.ent", "d1dx4a_.ent-d1qlwa_.ent", "d1dx4a_.ent-d1qo7a_.ent", "d1dx4a_.ent-d1qtra_.ent", "d1dx4a_.ent-d1tca__.ent", "d1dx4a_.ent-d2bce__.ent", "d1dx5i1.ent-d1cvua2.ent", "d1dx5i1.ent-d1emo_1.ent", "d1dx5i1.ent-d1hz8a1.ent", "d1dx5i1.ent-d1hz8a2.ent", "d1dx5i1.ent-d1jl9a_.ent", "d1dx5i1.ent-d1l3ya_.ent", "d1dx5i1.ent-d1m1xb5.ent", "d1dx5i1.ent-d1tpg_1.ent", "d1dxea_.ent-d1e0ta2.ent", "d1dxea_.ent-d1f8ma_.ent", "d1dxea_.ent-d1jqna_.ent", "d1dxea_.ent-d1jqoa_.ent", "d1dxea_.ent-d1kbla1.ent", "d1dxga_.ent-d1f4la3.ent", "d1dxga_.ent-d1gh9a_.ent", "d1dxga_.ent-d1h7va_.ent", "d1dxga_.ent-d1i50i1.ent", "d1dxga_.ent-d1i50i2.ent", "d1dxga_.ent-d1i50l_.ent", "d1dxga_.ent-d1jj22_.ent", "d1dxga_.ent-d1jj2y_.ent", "d1dxga_.ent-d1jj2z_.ent", "d1dxga_.ent-d1lkoa2.ent", "d1dxga_.ent-d1m2oa5.ent", "d1dxga_.ent-d1ocrf_.ent", "d1dxga_.ent-d1pft__.ent", "d1dxga_.ent-d1rb9__.ent", "d1dxga_.ent-d1tfi__.ent", "d1dxga_.ent-d1yua_1.ent", "d1dxga_.ent-d1yua_2.ent", "d1dxga_.ent-d1zaka2.ent", "d1dxga_.ent-d1zin_2.ent", "d1dxja_.ent-d1gd6a_.ent", "d1dxja_.ent-d1k28a3.ent", "d1dxja_.ent-d1qgia_.ent", "d1dxja_.ent-d1qsaa2.ent", "d1dxja_.ent-d1qusa_.ent", "d1dxja_.ent-d217l__.ent", "d1dxja_.ent-d2eql__.ent", "d1dxja_.ent-d3lzt__.ent", "d1dxla3.ent-d1ebda3.ent", "d1dxla3.ent-d1fcda3.ent", "d1dxla3.ent-d1feca3.ent", "d1dxla3.ent-d1h6va3.ent", "d1dxla3.ent-d1lvl_3.ent", "d1dxla3.ent-d1m6ia3.ent", "d1dxla3.ent-d1mo9a3.ent", "d1dxla3.ent-d1nhp_3.ent", "d1dxla3.ent-d1ojt_3.ent", "d1dxla3.ent-d3grs_3.ent", "d1dxla3.ent-d3lada3.ent", "d1dxrc_.ent-d1eysc_.ent", "d1dxrc_.ent-d1fgja_.ent", "d1dxrc_.ent-d1fs7a_.ent", "d1dxrc_.ent-d1ft5a_.ent", "d1dxrc_.ent-d1gu6a_.ent", "d1dxrc_.ent-d1gyoa_.ent", "d1dxrc_.ent-d1h21a_.ent", "d1dxrc_.ent-d1h29a_.ent", "d1dxrc_.ent-d1hh5a_.ent", "d1dxrc_.ent-d1kssa1.ent", "d1dxrc_.ent-d1m1qa_.ent", "d1dxrc_.ent-d1qo8a1.ent", "d1dxrc_.ent-d1wad__.ent", "d1dxrc_.ent-d2ctha_.ent", "d1dxrc_.ent-d2cy3__.ent", "d1dxrc_.ent-d3caoa_.ent", "d1dxrc_.ent-d3cyr__.ent", "d1dxrm_.ent-d1qovl_.ent", "d1dxrm_.ent-d1qovm_.ent", "d1dxsa_.ent-d1f44a1.ent", "d1dxsa_.ent-d1floa1.ent", "d1dxsa_.ent-d1go3f_.ent", "d1dxsa_.ent-d1jmsa1.ent", "d1dxsa_.ent-d1jmsa3.ent", "d1dxsa_.ent-d1jyga_.ent", "d1dxsa_.ent-d1kfta_.ent", "d1dxsa_.ent-d1lb2b_.ent", "d1dxsa_.ent-d1tfr_1.ent", "d1dxxa1.ent-d1h67a_.ent", "d1dxy_2.ent-d1gdha2.ent", "d1dxy_2.ent-d1j4aa2.ent", "d1dxy_2.ent-d1l7da2.ent", "d1dxy_2.ent-d1mx3a2.ent", "d1dxy_2.ent-d1pjca2.ent", "d1dxy_2.ent-d1psda2.ent", "d1dxy_2.ent-d2naca2.ent", "d1dyka1.ent-d1dyka2.ent", "d1dyka1.ent-d1h30a1.ent", "d1dyka1.ent-d1xnb__.ent", "d1dyka2.ent-d1gv9a_.ent", "d1dyka2.ent-d1h30a2.ent", "d1dyka2.ent-d1ikpa1.ent", "d1dyka2.ent-d1is3a_.ent", "d1dyka2.ent-d1jhna4.ent", "d1dyka2.ent-d1kit_1.ent", "d1dyka2.ent-d1kqra_.ent", "d1dyka2.ent-d1n1ta1.ent", "d1dyka2.ent-d1nls__.ent", "d1dyka2.ent-d1saca_.ent", "d1dyka2.ent-d1xnb__.ent", "d1dyka2.ent-d2nlra_.ent", "d1dyka2.ent-d2sli_1.ent", "d1dyna_.ent-d1eaza_.ent", "d1dyna_.ent-d1evha_.ent", "d1dyna_.ent-d1faoa_.ent", "d1dyna_.ent-d1fhoa_.ent", "d1dyna_.ent-d1gg3a2.ent", "d1dyna_.ent-d1h4ra2.ent", "d1dyna_.ent-d1k5db_.ent", "d1dyna_.ent-d1ki1b2.ent", "d1dyna_.ent-d1mai__.ent", "d1dyna_.ent-d1mixa2.ent", "d1dyna_.ent-d1mkea1.ent", "d1dyna_.ent-d1pls__.ent", "d1dyna_.ent-d1qqga1.ent", "d1dyna_.ent-d1qqga2.ent", "d1dyna_.ent-d1shca_.ent", "d1dyr__.ent-d1ra9__.ent", "d1dyr__.ent-d1vdra_.ent", "d1dyr__.ent-d3dfr__.ent", "d1dysa_.ent-d1tml__.ent", "d1dysa_.ent-d2bvwa_.ent", "d1dz1a_.ent-d1e0ba_.ent", "d1dz1a_.ent-d1g6za_.ent", "d1dz1a_.ent-d1knaa_.ent", "d1dz1a_.ent-d1tvxa_.ent", "d1dz3a_.ent-d1m2fa_.ent", "d1dz3a_.ent-d1mb3a_.ent", "d1dz3a_.ent-d1mvoa_.ent", "d1dz3a_.ent-d1nat__.ent", "d1dz3a_.ent-d1ntr__.ent", "d1dz3a_.ent-d1qo0d_.ent", "d1dz3a_.ent-d1tmy__.ent", "d1dz4a_.ent-d1e9xa_.ent", "d1dz4a_.ent-d1io7a_.ent", "d1dz4a_.ent-d1jfba_.ent", "d1dz4a_.ent-d1jipa_.ent", "d1dz4a_.ent-d1jpza_.ent", "d1dz4a_.ent-d1lfka_.ent", "d1dz4a_.ent-d1n97a_.ent", "d1dzfa1.ent-d1ev7a_.ent", "d1dzfa1.ent-d1f1za2.ent", "d1dzfa1.ent-d1fiua_.ent", "d1dzfa1.ent-d1gefa_.ent", "d1dzfa1.ent-d1kc6a_.ent", "d1dzfa1.ent-d1m0da_.ent", "d1dzfa1.ent-d1vsra_.ent", "d1dzfa1.ent-d2foka4.ent", "d1dzfa1.ent-d3pvia_.ent", "d1dzfa2.ent-d1eika_.ent", "d1dzfa2.ent-d1i50f_.ent", "d1dzka_.ent-d1euoa_.ent", "d1dzka_.ent-d1ew3a_.ent", "d1dzka_.ent-d1exsa_.ent", "d1dzka_.ent-d1ftpa_.ent", "d1dzka_.ent-d1g85a_.ent", "d1dzka_.ent-d1ggla_.ent", "d1dzka_.ent-d1gkab_.ent", "d1dzka_.ent-d1hms__.ent", "d1dzka_.ent-d1i4ua_.ent", "d1dzka_.ent-d1ifc__.ent", "d1dzka_.ent-d1jv4a_.ent", "d1dzka_.ent-d1koia_.ent", "d1dzka_.ent-d1kqwa_.ent", "d1dzka_.ent-d1lf7a_.ent", "d1dzka_.ent-d1o1va_.ent", "d1dzka_.ent-d1qfta_.ent", "d1dzka_.ent-d1qqsa_.ent", "d1dzla_.ent-d1a6ca1.ent", "d1dzla_.ent-d1a6ca2.ent", "d1dzla_.ent-d1a6ca3.ent", "d1dzla_.ent-d1aym1_.ent", "d1dzla_.ent-d1aym2_.ent", "d1dzla_.ent-d1b35a_.ent", "d1dzla_.ent-d1b35b_.ent", "d1dzla_.ent-d1b35c_.ent", "d1dzla_.ent-d1bev1_.ent", "d1dzla_.ent-d1bev3_.ent", "d1dzla_.ent-d1bmv1_.ent", "d1dzla_.ent-d1bmv2_.ent", "d1dzla_.ent-d1c8na_.ent", "d1dzla_.ent-d1cwpa_.ent", "d1dzla_.ent-d1d4m1_.ent", "d1dzla_.ent-d1ddla_.ent", "d1dzla_.ent-d1dnv__.ent", "d1dzla_.ent-d1f15a_.ent", "d1dzla_.ent-d1k5ma_.ent", "d1dzla_.ent-d1novc_.ent", "d1dzla_.ent-d1pov0_.ent", "d1dzla_.ent-d1pvc1_.ent", "d1dzla_.ent-d1qqp1_.ent", "d1dzla_.ent-d1qqp2_.ent", "d1dzla_.ent-d1qqp3_.ent", "d1dzla_.ent-d1sva1_.ent", "d1dzla_.ent-d1tmf1_.ent", "d1dzla_.ent-d1vpsa_.ent", "d1dzla_.ent-d2bbva_.ent", "d1dzla_.ent-d2bpa1_.ent", "d1dzla_.ent-d2bpa2_.ent", "d1dzla_.ent-d2mev1_.ent", "d1dzla_.ent-d2mev2_.ent", "d1dzla_.ent-d2stv__.ent", "d1dzra_.ent-d1ep0a_.ent", "d1dzra_.ent-d1fi2a_.ent", "d1dzra_.ent-d1fxza1.ent", "d1dzra_.ent-d1fxza2.ent", "d1dzra_.ent-d1juha_.ent", "d1dzra_.ent-d1lrha_.ent", "d1dzra_.ent-d1m4oa_.ent", "d1dzra_.ent-d1pmi__.ent", "d1dzra_.ent-d2phla1.ent", "d1dzra_.ent-d2phla2.ent", "d1e05i_.ent-d1imva_.ent", "d1e05i_.ent-d1jmja_.ent", "d1e05i_.ent-d1k9oi_.ent", "d1e05i_.ent-d1lj5a_.ent", "d1e05i_.ent-d1ovaa_.ent", "d1e05i_.ent-d1qlpa_.ent", "d1e0ba_.ent-d1g6za_.ent", "d1e0ba_.ent-d1knaa_.ent", "d1e0ba_.ent-d1tvxa_.ent", "d1e0ca1.ent-d1hzma_.ent", "d1e0ca1.ent-d1rhs_1.ent", "d1e0fi_.ent-d1agg__.ent", "d1e0fi_.ent-d1apq__.ent", "d1e0fi_.ent-d1b9wa1.ent", "d1e0fi_.ent-d1b9wa2.ent", "d1e0fi_.ent-d1bx7__.ent", "d1e0fi_.ent-d1cixa_.ent", "d1e0fi_.ent-d1flei_.ent", "d1e0fi_.ent-d1g9pa_.ent", "d1e0fi_.ent-d1gps__.ent", "d1e0fi_.ent-d1h59b_.ent", "d1e0fi_.ent-d1hyka_.ent", "d1e0fi_.ent-d1i2ua_.ent", "d1e0fi_.ent-d1ijqa2.ent", "d1e0fi_.ent-d1imt_2.ent", "d1e0fi_.ent-d1jkza_.ent", "d1e0fi_.ent-d1klo_1.ent", "d1e0fi_.ent-d1klo_3.ent", "d1e0fi_.ent-d1lpba2.ent", "d1e0fi_.ent-d1skz_1.ent", "d1e0fi_.ent-d1skz_2.ent", "d1e0fi_.ent-d4htci_.ent", "d1e0ta1.ent-d1g8fa1.ent", "d1e0ta1.ent-d1jhda1.ent", "d1e0ta1.ent-d1pkla1.ent", "d1e0ta2.ent-d1f8ma_.ent", "d1e0ta2.ent-d1jqna_.ent", "d1e0ta2.ent-d1jqoa_.ent", "d1e0ta2.ent-d1kbla1.ent", "d1e0ta3.ent-d1pkla3.ent", "d1e12a_.ent-d1h2sa_.ent", "d1e12a_.ent-d1h2sb_.ent", "d1e12a_.ent-d1l9ha_.ent", "d1e12a_.ent-d1m0ka_.ent", "d1e17a_.ent-d1ldja1.ent", "d1e19a_.ent-d1gs5a_.ent", "d1e1aa_.ent-d1e8ua_.ent", "d1e1aa_.ent-d1f8ea_.ent", "d1e1aa_.ent-d1h6la_.ent", "d1e1aa_.ent-d1ijqa1.ent", "d1e1aa_.ent-d1k32a2.ent", "d1e1aa_.ent-d1kit_3.ent", "d1e1aa_.ent-d3sil__.ent", "d1e1oa1.ent-d1b3qa2.ent", "d1e1oa1.ent-d1eova1.ent", "d1e1oa1.ent-d1ewia_.ent", "d1e1oa1.ent-d1fgua1.ent", "d1e1oa1.ent-d1fgua2.ent", "d1e1oa1.ent-d1fjgl_.ent", "d1e1oa1.ent-d1i50h_.ent", "d1e1oa1.ent-d1iyjb3.ent", "d1e1oa1.ent-d1iyjb5.ent", "d1e1oa1.ent-d1jb3a_.ent", "d1e1oa1.ent-d1jb7a2.ent", "d1e1oa1.ent-d1jjcb3.ent", "d1e1oa1.ent-d1k28a1.ent", "d1e1oa1.ent-d1quqa_.ent", "d1e1oa1.ent-d1quqb_.ent", "d1e1oa1.ent-d1sty__.ent", "d1e1oa1.ent-d3seb_1.ent", "d1e1oa2.ent-d1eova2.ent", "d1e1oa2.ent-d1g51a3.ent", "d1e1oa2.ent-d1h4vb2.ent", "d1e1oa2.ent-d1hc7a2.ent", "d1e1oa2.ent-d1jjca_.ent", "d1e1oa2.ent-d1jjcb5.ent", "d1e1oa2.ent-d1kmma2.ent", "d1e1oa2.ent-d1qe0a2.ent", "d1e1oa2.ent-d1qf6a4.ent", "d1e1oa2.ent-d1seta2.ent", "d1e25a_.ent-d1ei5a3.ent", "d1e25a_.ent-d1es5a_.ent", "d1e25a_.ent-d1g6aa_.ent", "d1e25a_.ent-d1ghpa_.ent", "d1e25a_.ent-d1iyoa_.ent", "d1e25a_.ent-d1l0ga_.ent", "d1e25a_.ent-d1m40a_.ent", "d1e25a_.ent-d1mfoa_.ent", "d1e25a_.ent-d1mwxa3.ent", "d1e25a_.ent-d1nj4a2.ent", "d1e25a_.ent-d1qmea4.ent", "d1e25a_.ent-d4blma_.ent", "d1e29a_.ent-d1c52__.ent", "d1e29a_.ent-d1co6a_.ent", "d1e29a_.ent-d1cot__.ent", "d1e29a_.ent-d1cxc__.ent", "d1e29a_.ent-d1dw0a_.ent", "d1e29a_.ent-d1etpa2.ent", "d1e29a_.ent-d1ezvd1.ent", "d1e29a_.ent-d1f1ca_.ent", "d1e29a_.ent-d1fcdc2.ent", "d1e29a_.ent-d1gu2a_.ent", "d1e29a_.ent-d1h32a1.ent", "d1e29a_.ent-d1hroa_.ent", "d1e29a_.ent-d1iqca1.ent", "d1e29a_.ent-d1iqca2.ent", "d1e29a_.ent-d1jmxa1.ent", "d1e29a_.ent-d1jmxa2.ent", "d1e29a_.ent-d1kb0a1.ent", "d1e29a_.ent-d1kv9a1.ent", "d1e29a_.ent-d1mg2d_.ent", "d1e29a_.ent-d1nira1.ent", "d1e29a_.ent-d1qksa1.ent", "d1e29a_.ent-d1ql3a_.ent", "d1e29a_.ent-d1qn2a_.ent", "d1e29a_.ent-d1ycc__.ent", "d1e29a_.ent-d3c2c__.ent", "d1e2aa_.ent-d1fjgt_.ent", "d1e2aa_.ent-d1g73a_.ent", "d1e2aa_.ent-d1hcia1.ent", "d1e2aa_.ent-d1hcia4.ent", "d1e2aa_.ent-d1hx1b_.ent", "d1e2aa_.ent-d1jnra1.ent", "d1e2aa_.ent-d1m7ka_.ent", "d1e2aa_.ent-d1qlaa1.ent", "d1e2aa_.ent-d1quua1.ent", "d1e2aa_.ent-d1quua2.ent", "d1e2aa_.ent-d2spca_.ent", "d1e2ka_.ent-d1a7j__.ent", "d1e2ka_.ent-d1aqua_.ent", "d1e2ka_.ent-d1cr1a_.ent", "d1e2ka_.ent-d1e69a_.ent", "d1e2ka_.ent-d1e79a3.ent", "d1e2ka_.ent-d1f5na2.ent", "d1e2ka_.ent-d1fnna2.ent", "d1e2ka_.ent-d1g8ya_.ent", "d1e2ka_.ent-d1gm5a3.ent", "d1e2ka_.ent-d1ihua1.ent", "d1e2ka_.ent-d1jwyb_.ent", "d1e2ka_.ent-d1ksfx3.ent", "d1e2ka_.ent-d1lv7a_.ent", "d1e2ka_.ent-d1m6na3.ent", "d1e2ka_.ent-d1nsta_.ent", "d1e2ka_.ent-d1pjr_2.ent", "d1e2ka_.ent-d1uaaa1.ent", "d1e2o__.ent-d1eaf__.ent", "d1e2o__.ent-d1l5aa1.ent", "d1e2o__.ent-d1l5aa2.ent", "d1e2o__.ent-d1nocb_.ent", "d1e2o__.ent-d3cla__.ent", "d1e2ta_.ent-d1euva_.ent", "d1e2ta_.ent-d1f13a4.ent", "d1e2ta_.ent-d1fh0a_.ent", "d1e2ta_.ent-d1g0da4.ent", "d1e2ta_.ent-d1gmya_.ent", "d1e2ta_.ent-d1gx3a_.ent", "d1e2ta_.ent-d1iu4a_.ent", "d1e2ta_.ent-d1kxra_.ent", "d1e2ta_.ent-d1l9na4.ent", "d1e2ta_.ent-d1me4a_.ent", "d1e2ta_.ent-d1nbfa_.ent", "d1e2ta_.ent-d1ppn__.ent", "d1e2ta_.ent-d1qmya_.ent", "d1e2ta_.ent-d1uch__.ent", "d1e2ta_.ent-d2act__.ent", "d1e2ta_.ent-d2cb5a_.ent", "d1e2ta_.ent-d3gcb__.ent", "d1e2ta_.ent-d7pcka_.ent", "d1e2wa1.ent-d1e5ba_.ent", "d1e2wa1.ent-d1f0la1.ent", "d1e2wa1.ent-d1h6fa_.ent", "d1e2wa1.ent-d1i31a_.ent", "d1e2wa1.ent-d1klfb1.ent", "d1e2wa1.ent-d1klfb2.ent", "d1e2wa1.ent-d1m2oa2.ent", "d1e2wa1.ent-d1m2vb2.ent", "d1e2wa1.ent-d1mnna_.ent", "d1e2wa1.ent-d1nbca_.ent", "d1e2wa1.ent-d1pdkb_.ent", "d1e2wa1.ent-d1qba_2.ent", "d1e2wa1.ent-d1tf4a2.ent", "d1e2wa1.ent-d1ycsa_.ent", "d1e2wa2.ent-d1gpr__.ent", "d1e2wa2.ent-d1gsoa1.ent", "d1e2wa2.ent-d1hcz_2.ent", "d1e2wa2.ent-d1htp__.ent", "d1e2wa2.ent-d1k8ma_.ent", "d1e2wa2.ent-d1kjqa1.ent", "d1e30a_.ent-d1gyca3.ent", "d1e30a_.ent-d1hfua2.ent", "d1e30a_.ent-d1ibya_.ent", "d1e30a_.ent-d1ikop_.ent", "d1e30a_.ent-d1jzga_.ent", "d1e30a_.ent-d1kbva1.ent", "d1e30a_.ent-d1kbva2.ent", "d1e30a_.ent-d1kcw_1.ent", "d1e30a_.ent-d1kcw_2.ent", "d1e30a_.ent-d1kcw_4.ent", "d1e30a_.ent-d1kcw_6.ent", "d1e30a_.ent-d1kv7a1.ent", "d1e30a_.ent-d1kv7a2.ent", "d1e30a_.ent-d1kv7a3.ent", "d1e30a_.ent-d1kzqa1.ent", "d1e30a_.ent-d1l9qa1.ent", "d1e30a_.ent-d1l9qa2.ent", "d1e30a_.ent-d1qhqa_.ent", "d1e30a_.ent-d2cbp__.ent", "d1e30a_.ent-d2cuaa_.ent", "d1e31a_.ent-d1g73c_.ent", "d1e31a_.ent-d1i3oe_.ent", "d1e31a_.ent-d1jd5a_.ent", "d1e31a_.ent-d1qbha_.ent", "d1e32a1.ent-d1eu1a1.ent", "d1e32a1.ent-d1g8ka1.ent", "d1e32a1.ent-d1h0ha1.ent", "d1e32a1.ent-d1kqfa1.ent", "d1e32a1.ent-d1n10a2.ent", "d1e32a1.ent-d1tmo_1.ent", "d1e32a1.ent-d2napa1.ent", "d1e3ja1.ent-d1g31a_.ent", "d1e3ja1.ent-d1heta1.ent", "d1e3ja1.ent-d1jh2a_.ent", "d1e3ja1.ent-d1jqba1.ent", "d1e3ja1.ent-d1kola1.ent", "d1e3ja1.ent-d1qora1.ent", "d1e3oc2.ent-d1efaa1.ent", "d1e3oc2.ent-d1ic8a2.ent", "d1e3oc2.ent-d1lmb3_.ent", "d1e3oc2.ent-d1ner__.ent", "d1e3oc2.ent-d1r69__.ent", "d1e3oc2.ent-d1uxc__.ent", "d1e3oc2.ent-d1uxd__.ent", "d1e3oc2.ent-d1vpwa1.ent", "d1e3oc2.ent-d2cro__.ent", "d1e42a1.ent-d1gyva_.ent", "d1e42a1.ent-d1kyfa1.ent", "d1e43a1.ent-d1ea9c2.ent", "d1e43a1.ent-d1eh9a2.ent", "d1e43a1.ent-d1g5aa1.ent", "d1e43a1.ent-d1g94a1.ent", "d1e43a1.ent-d1gcya1.ent", "d1e43a1.ent-d1gjwa1.ent", "d1e43a1.ent-d1hx0a1.ent", "d1e43a1.ent-d1iv8a1.ent", "d1e43a1.ent-d1j0ha2.ent", "d1e43a1.ent-d1jae_1.ent", "d1e43a1.ent-d1ji1a2.ent", "d1e43a1.ent-d1ji2a2.ent", "d1e43a1.ent-d1ktba1.ent", "d1e43a1.ent-d1kwga1.ent", "d1e43a1.ent-d1lwha1.ent", "d1e43a1.ent-d1m7xa2.ent", "d1e43a1.ent-d1qhoa3.ent", "d1e43a1.ent-d1uok_1.ent", "d1e43a1.ent-d7taa_1.ent", "d1e43a2.ent-d1iexa1.ent", "d1e43a2.ent-d1j0ha3.ent", "d1e43a2.ent-d1kwga2.ent", "d1e43a2.ent-d1lwha2.ent", "d1e43a2.ent-d7taa_2.ent", "d1e4bp_.ent-d1gt7a_.ent", "d1e4bp_.ent-d1k0wa_.ent", "d1e4ea1.ent-d1ehia1.ent", "d1e4ea1.ent-d1gsa_1.ent", "d1e4ea1.ent-d1gsoa2.ent", "d1e4ea1.ent-d1iow_1.ent", "d1e4ea1.ent-d1kjqa2.ent", "d1e4ea1.ent-d1m0wa1.ent", "d1e4ea1.ent-d2hgsa1.ent", "d1e4ea2.ent-d1ehia2.ent", "d1e4ea2.ent-d1eucb2.ent", "d1e4ea2.ent-d1gsa_2.ent", "d1e4ea2.ent-d1gsoa3.ent", "d1e4ea2.ent-d1iow_2.ent", "d1e4ea2.ent-d1jkjb2.ent", "d1e4ea2.ent-d1kbla3.ent", "d1e4ea2.ent-d1kjqa3.ent", "d1e4ea2.ent-d1m0wa2.ent", "d1e4ea2.ent-d2hgsa4.ent", "d1e4ft1.ent-d1az9_1.ent", "d1e4ft1.ent-d1bupa1.ent", "d1e4ft1.ent-d1e4ft2.ent", "d1e4ft1.ent-d1g99a1.ent", "d1e4ft1.ent-d1g99a2.ent", "d1e4ft1.ent-d1glag1.ent", "d1e4ft1.ent-d1glag2.ent", "d1e4ft1.ent-d1huxa_.ent", "d1e4ft1.ent-d1ig8a1.ent", "d1e4ft1.ent-d1ig8a2.ent", "d1e4ft1.ent-d1j54a_.ent", "d1e4ft1.ent-d1j6za2.ent", "d1e4ft1.ent-d1jcfa1.ent", "d1e4ft1.ent-d1jj2m_.ent", "d1e4ft1.ent-d1k8ka1.ent", "d1e4ft1.ent-d1mwma1.ent", "d1e4ft1.ent-d1mwma2.ent", "d1e4ft1.ent-d1nbwa2.ent", "d1e4ft1.ent-d1nbwa3.ent", "d1e4ft1.ent-d1xwl_1.ent", "d1e4ft2.ent-d1az9_1.ent", "d1e4ft2.ent-d1g99a1.ent", "d1e4ft2.ent-d1g99a2.ent", "d1e4ft2.ent-d1glag1.ent", "d1e4ft2.ent-d1glag2.ent", "d1e4ft2.ent-d1huxa_.ent", "d1e4ft2.ent-d1ig8a1.ent", "d1e4ft2.ent-d1ig8a2.ent", "d1e4ft2.ent-d1j54a_.ent", "d1e4ft2.ent-d1j6za2.ent", "d1e4ft2.ent-d1jcfa1.ent", "d1e4ft2.ent-d1k8ka1.ent", "d1e4ft2.ent-d1mwma1.ent", "d1e4ft2.ent-d1mwma2.ent", "d1e4ft2.ent-d1nbwa2.ent", "d1e4ft2.ent-d1nbwa3.ent", "d1e4ft2.ent-d1xwl_1.ent", "d1e4ia_.ent-d1b9za2.ent", "d1e4ia_.ent-d1cz1a_.ent", "d1e4ia_.ent-d1e43a2.ent", "d1e4ia_.ent-d1eh9a3.ent", "d1e4ia_.ent-d1iexa1.ent", "d1e4ia_.ent-d1j0ha3.ent", "d1e4ia_.ent-d1ji1a3.ent", "d1e4ia_.ent-d1kwga2.ent", "d1e4ia_.ent-d1lwha2.ent", "d1e4ia_.ent-d1pama4.ent", "d1e4ia_.ent-d1qba_3.ent", "d1e4ia_.ent-d1qhoa4.ent", "d1e4ia_.ent-d7taa_2.ent", "d1e4mm_.ent-d1b9za2.ent", "d1e4mm_.ent-d1bf2_3.ent", "d1e4mm_.ent-d1cbg__.ent", "d1e4mm_.ent-d1ccwb_.ent", "d1e4mm_.ent-d1cz1a_.ent", "d1e4mm_.ent-d1d3ga_.ent", "d1e4mm_.ent-d1e43a2.ent", "d1e4mm_.ent-d1e4ia_.ent", "d1e4mm_.ent-d1edg__.ent", "d1e4mm_.ent-d1eh9a3.ent", "d1e4mm_.ent-d1f8ma_.ent", "d1e4mm_.ent-d1gvoa_.ent", "d1e4mm_.ent-d1gw1a_.ent", "d1e4mm_.ent-d1hxja_.ent", "d1e4mm_.ent-d1iexa1.ent", "d1e4mm_.ent-d1itua_.ent", "d1e4mm_.ent-d1j0ha3.ent", "d1e4mm_.ent-d1j5sa_.ent", "d1e4mm_.ent-d1ji1a3.ent", "d1e4mm_.ent-d1k4ga_.ent", "d1e4mm_.ent-d1kbla1.ent", "d1e4mm_.ent-d1kwga2.ent", "d1e4mm_.ent-d1lwha2.ent", "d1e4mm_.ent-d1m7ja3.ent", "d1e4mm_.ent-d1muwa_.ent", "d1e4mm_.ent-d1ntha_.ent", "d1e4mm_.ent-d1pama4.ent", "d1e4mm_.ent-d1qba_3.ent", "d1e4mm_.ent-d1qhoa4.ent", "d1e4mm_.ent-d1qvba_.ent", "d1e4mm_.ent-d1uok_2.ent", "d1e4mm_.ent-d7taa_2.ent", "d1e4ta_.ent-d1ewsa_.ent", "d1e4ta_.ent-d1fd3a_.ent", "d1e4ta_.ent-d1ijva_.ent", "d1e4ta_.ent-d1kj6a_.ent", "d1e4ta_.ent-d1sh1__.ent", "d1e4ta_.ent-d2bds__.ent", "d1e4ua_.ent-d1fbva4.ent", "d1e4ua_.ent-d1g25a_.ent", "d1e4ua_.ent-d1jm7a_.ent", "d1e4ua_.ent-d1jm7b_.ent", "d1e4ua_.ent-d1ldjb_.ent", "d1e4ua_.ent-d1rmd_2.ent", "d1e52a_.ent-d1e79h1.ent", "d1e52a_.ent-d1eiya1.ent", "d1e52a_.ent-d1fpoa1.ent", "d1e52a_.ent-d1fxkc_.ent", "d1e52a_.ent-d1gh6a_.ent", "d1e52a_.ent-d1grj_1.ent", "d1e52a_.ent-d1hdj__.ent", "d1e52a_.ent-d1ivsa1.ent", "d1e52a_.ent-d1ix9a1.ent", "d1e52a_.ent-d1jj2u_.ent", "d1e52a_.ent-d1k4ta1.ent", "d1e52a_.ent-d1lrza1.ent", "d1e52a_.ent-d1seta1.ent", "d1e53a_.ent-d1faq__.ent", "d1e53a_.ent-d1kbea_.ent", "d1e53a_.ent-d1ptq__.ent", "d1e58a_.ent-d1fzta_.ent", "d1e58a_.ent-d1h2ea_.ent", "d1e58a_.ent-d1ihp__.ent", "d1e58a_.ent-d1nd6a_.ent", "d1e58a_.ent-d1qfxa_.ent", "d1e58a_.ent-d3pgm__.ent", "d1e5ba_.ent-d1exh__.ent", "d1e5ba_.ent-d1f0la1.ent", "d1e5ba_.ent-d1g1ka_.ent", "d1e5ba_.ent-d1g43a_.ent", "d1e5ba_.ent-d1h6fa_.ent", "d1e5ba_.ent-d1i31a_.ent", "d1e5ba_.ent-d1klfb1.ent", "d1e5ba_.ent-d1klfb2.ent", "d1e5ba_.ent-d1m2oa2.ent", "d1e5ba_.ent-d1m2vb2.ent", "d1e5ba_.ent-d1mnna_.ent", "d1e5ba_.ent-d1nbca_.ent", "d1e5ba_.ent-d1pdkb_.ent", "d1e5ba_.ent-d1qba_2.ent", "d1e5ba_.ent-d1tf4a2.ent", "d1e5ba_.ent-d1ycsa_.ent", "d1e5da1.ent-d1f4pa_.ent", "d1e5da1.ent-d1fuea_.ent", "d1e5da1.ent-d1h05a_.ent", "d1e5da1.ent-d1ja1a2.ent", "d1e5da1.ent-d1qr2a_.ent", "d1e5da1.ent-d1rcf__.ent", "d1e5da1.ent-d2fcr__.ent", "d1e5da1.ent-d5nul__.ent", "d1e5da2.ent-d1jjea_.ent", "d1e5da2.ent-d1k07a_.ent", "d1e5da2.ent-d1qh5a_.ent", "d1e5da2.ent-d1smla_.ent", "d1e5ea_.ent-d1b9ha_.ent", "d1e5ea_.ent-d1bs0a_.ent", "d1e5ea_.ent-d1gdea_.ent", "d1e5ea_.ent-d1j32a_.ent", "d1e5ea_.ent-d1n8pa_.ent", "d1e5ea_.ent-d2ay1a_.ent", "d1e5ka_.ent-d1fo8a_.ent", "d1e5ka_.ent-d1fxoa_.ent", "d1e5ka_.ent-d1h7ea_.ent", "d1e5ka_.ent-d1hm9a2.ent", "d1e5ka_.ent-d1hv9a2.ent", "d1e5ka_.ent-d1i52a_.ent", "d1e5ka_.ent-d1jv1a_.ent", "d1e5ka_.ent-d1k4va_.ent", "d1e5ka_.ent-d1kwsa_.ent", "d1e5ka_.ent-d1ll2a_.ent", "d1e5ka_.ent-d1lzja_.ent", "d1e5ka_.ent-d1nf5b_.ent", "d1e5ka_.ent-d1qg8a_.ent", "d1e5ma1.ent-d1e5ma2.ent", "d1e5ma1.ent-d1ek4a1.ent", "d1e5ma1.ent-d1ek4a2.ent", "d1e5ma1.ent-d1hnja1.ent", "d1e5ma1.ent-d1hnja2.ent", "d1e5ma1.ent-d1hzpa1.ent", "d1e5ma1.ent-d1hzpa2.ent", "d1e5ma1.ent-d1kas_1.ent", "d1e5ma1.ent-d1m3ka1.ent", "d1e5ma1.ent-d1m3ka2.ent", "d1e5ma1.ent-d1mzja1.ent", "d1e5ma1.ent-d1mzja2.ent", "d1e5ma2.ent-d1ek4a1.ent", "d1e5ma2.ent-d1ek4a2.ent", "d1e5ma2.ent-d1hnja1.ent", "d1e5ma2.ent-d1hnja2.ent", "d1e5ma2.ent-d1hzpa1.ent", "d1e5ma2.ent-d1hzpa2.ent", "d1e5ma2.ent-d1kas_1.ent", "d1e5ma2.ent-d1m3ka1.ent", "d1e5ma2.ent-d1m3ka2.ent", "d1e5ma2.ent-d1mzja1.ent", "d1e5ma2.ent-d1mzja2.ent", "d1e5qa1.ent-d1cf2o1.ent", "d1e5qa1.ent-d1dssg1.ent", "d1e5qa1.ent-d1lc0a1.ent", "d1e5qa1.ent-d2pgd_2.ent", "d1e5qa2.ent-d1ebfa2.ent", "d1e5qa2.ent-d1f06a2.ent", "d1e5qa2.ent-d1gr0a2.ent", "d1e5qa2.ent-d1h6da2.ent", "d1e5qa2.ent-d1j5pa3.ent", "d1e5qa2.ent-d1jkia2.ent", "d1e5qa2.ent-d1jn0a2.ent", "d1e5qa2.ent-d1lc0a2.ent", "d1e5qa2.ent-d1mb4a2.ent", "d1e5qa2.ent-d1qkia2.ent", "d1e5sa_.ent-d1ep0a_.ent", "d1e5sa_.ent-d1eula1.ent", "d1e5sa_.ent-d1fi2a_.ent", "d1e5sa_.ent-d1ft9a2.ent", "d1e5sa_.ent-d1fxza1.ent", "d1e5sa_.ent-d1gp6a_.ent", "d1e5sa_.ent-d1gy9a_.ent", "d1e5sa_.ent-d1h2ka_.ent", "d1e5sa_.ent-d1hw5a2.ent", "d1e5sa_.ent-d1ig0a1.ent", "d1e5sa_.ent-d1jr7a_.ent", "d1e5sa_.ent-d1juha_.ent", "d1e5sa_.ent-d1lrha_.ent", "d1e5sa_.ent-d1m4oa_.ent", "d1e5sa_.ent-d1pmi__.ent", "d1e5sa_.ent-d1qjea_.ent", "d1e5sa_.ent-d1wapa_.ent", "d1e5sa_.ent-d2arca_.ent", "d1e68a_.ent-d1l9la_.ent", "d1e68a_.ent-d1n69a_.ent", "d1e69a_.ent-d1cr1a_.ent", "d1e69a_.ent-d1g8ya_.ent", "d1e69a_.ent-d1gm5a3.ent", "d1e69a_.ent-d1lv7a_.ent", "d1e6ba1.ent-d1eema1.ent", "d1e6ba1.ent-d1f2ea1.ent", "d1e6ba1.ent-d1fw1a1.ent", "d1e6ba1.ent-d1g7oa1.ent", "d1e6ba1.ent-d1glqa1.ent", "d1e6ba1.ent-d1gnwa1.ent", "d1e6ba1.ent-d1gula1.ent", "d1e6ba1.ent-d1gwca1.ent", "d1e6ba1.ent-d1jlva1.ent", "d1e6ba1.ent-d1k0da1.ent", "d1e6ba1.ent-d1k0ma1.ent", "d1e6ba1.ent-d1k3ya1.ent", "d1e6ba1.ent-d1ljra1.ent", "d1e6ba1.ent-d1m0ua1.ent", "d1e6ba1.ent-d1pd211.ent", "d1e6ba1.ent-d1pmt_1.ent", "d1e6ba1.ent-d2gsq_1.ent", "d1e6ba1.ent-d2gsta1.ent", "d1e6ba2.ent-d1aqwa2.ent", "d1e6ba2.ent-d1fhe_2.ent", "d1e6ba2.ent-d1iloa_.ent", "d1e6ba2.ent-d1k3ya2.ent", "d1e6ta_.ent-d1qbea_.ent", "d1e6ua_.ent-d1bdb__.ent", "d1e6ua_.ent-d1bg6_2.ent", "d1e6ua_.ent-d1bgva1.ent", "d1e6ua_.ent-d1c1da1.ent", "d1e6ua_.ent-d1cf2o1.ent", "d1e6ua_.ent-d1dlja2.ent", "d1e6ua_.ent-d1dpga1.ent", "d1e6ua_.ent-d1dssg1.ent", "d1e6ua_.ent-d1e5qa1.ent", "d1e6ua_.ent-d1e7wa_.ent", "d1e6ua_.ent-d1eno__.ent", "d1e6ua_.ent-d1eny__.ent", "d1e6ua_.ent-d1f0ya2.ent", "d1e6ua_.ent-d1fds__.ent", "d1e6ua_.ent-d1g0oa_.ent", "d1e6ua_.ent-d1gcoa_.ent", "d1e6ua_.ent-d1gr0a1.ent", "d1e6ua_.ent-d1h5qa_.ent", "d1e6ua_.ent-d1hdoa_.ent", "d1e6ua_.ent-d1hdr__.ent", "d1e6ua_.ent-d1hwxa1.ent", "d1e6ua_.ent-d1hxha_.ent", "d1e6ua_.ent-d1ja9a_.ent", "d1e6ua_.ent-d1jaya_.ent", "d1e6ua_.ent-d1lc0a1.ent", "d1e6ua_.ent-d1llqa1.ent", "d1e6ua_.ent-d1lu9a1.ent", "d1e6ua_.ent-d1n2sa_.ent", "d1e6ua_.ent-d1n5da_.ent", "d1e6ua_.ent-d1oaa__.ent", "d1e6ua_.ent-d1qmga2.ent", "d1e6ua_.ent-d1qsga_.ent", "d1e6ua_.ent-d2ae2a_.ent", "d1e6ua_.ent-d2naca1.ent", "d1e6ua_.ent-d2pgd_2.ent", "d1e6yb2.ent-d1hbnb2.ent", "d1e6yb2.ent-d1hbnc_.ent", "d1e79a1.ent-d1e79d1.ent", "d1e79a1.ent-d1fx0a1.ent", "d1e79a1.ent-d1skyb1.ent", "d1e79a2.ent-d1e79d2.ent", "d1e79a2.ent-d1fx0b2.ent", "d1e79a2.ent-d7odca1.ent", "d1e79a3.ent-d1a7j__.ent", "d1e79a3.ent-d1aqua_.ent", "d1e79a3.ent-d1cr1a_.ent", "d1e79a3.ent-d1e69a_.ent", "d1e79a3.ent-d1f5na2.ent", "d1e79a3.ent-d1fnna2.ent", "d1e79a3.ent-d1g8ya_.ent", "d1e79a3.ent-d1gm5a3.ent", "d1e79a3.ent-d1jwyb_.ent", "d1e79a3.ent-d1lv7a_.ent", "d1e79a3.ent-d1m6na3.ent", "d1e79a3.ent-d1nsta_.ent", "d1e79d1.ent-d1fx0a1.ent", "d1e79d1.ent-d1skyb1.ent", "d1e79d2.ent-d1fx0b2.ent", "d1e79d2.ent-d7odca1.ent", "d1e79h1.ent-d1eiya1.ent", "d1e79h1.ent-d1fpoa1.ent", "d1e79h1.ent-d1fxkc_.ent", "d1e79h1.ent-d1gh6a_.ent", "d1e79h1.ent-d1grj_1.ent", "d1e79h1.ent-d1hdj__.ent", "d1e79h1.ent-d1ivsa1.ent", "d1e79h1.ent-d1ix9a1.ent", "d1e79h1.ent-d1jj2u_.ent", "d1e79h1.ent-d1k4ta1.ent", "d1e79h1.ent-d1lrza1.ent", "d1e79h1.ent-d1seta1.ent", "d1e79i_.ent-d1g72b_.ent", "d1e79i_.ent-d1hfes_.ent", "d1e79i_.ent-d1jj21_.ent", "d1e79i_.ent-d1tbge_.ent", "d1e79i_.ent-d2prgc_.ent", "d1e7ka_.ent-d1ipaa2.ent", "d1e7ka_.ent-d1jj2f_.ent", "d1e7la1.ent-d1h1js_.ent", "d1e7la1.ent-d1h9ea_.ent", "d1e7la1.ent-d1h9fa_.ent", "d1e7la1.ent-d1jeqa1.ent", "d1e7la1.ent-d1kcfa1.ent", "d1e7la2.ent-d1emvb_.ent", "d1e7la2.ent-d1ql0a_.ent", "d1e7wa_.ent-d1bgva1.ent", "d1e7wa_.ent-d1gcoa_.ent", "d1e7wa_.ent-d1h5qa_.ent", "d1e7wa_.ent-d1ja9a_.ent", "d1e7wa_.ent-d1oaa__.ent", "d1e7wa_.ent-d1qsga_.ent", "d1e7wa_.ent-d2ae2a_.ent", "d1e87a_.ent-d1cwva5.ent", "d1e87a_.ent-d1f00i3.ent", "d1e87a_.ent-d1h8ua_.ent", "d1e87a_.ent-d1li1a1.ent", "d1e87a_.ent-d1li1a2.ent", "d1e87a_.ent-d1prtb2.ent", "d1e87a_.ent-d1tsg__.ent", "d1e88a3.ent-d1fbr_1.ent", "d1e88a3.ent-d1fbr_2.ent", "d1e88a3.ent-d1qgba1.ent", "d1e88a3.ent-d1qgba2.ent", "d1e88a3.ent-d1tpg_2.ent", "d1e8ga1.ent-d1azsa_.ent", "d1e8ga1.ent-d1b3ta_.ent", "d1e8ga1.ent-d1dj0a2.ent", "d1e8ga1.ent-d1dqaa1.ent", "d1e8ga1.ent-d1ekra_.ent", "d1e8ga1.ent-d1eqoa_.ent", "d1e8ga1.ent-d1f0xa1.ent", "d1e8ga1.ent-d1f3va_.ent", "d1e8ga1.ent-d1ftra1.ent", "d1e8ga1.ent-d1ftra2.ent", "d1e8ga1.ent-d1fx2a_.ent", "d1e8ga1.ent-d1gpja3.ent", "d1e8ga1.ent-d1h0hb_.ent", "d1e8ga1.ent-d1h72c2.ent", "d1e8ga1.ent-d1hbnb2.ent", "d1e8ga1.ent-d1hbnc_.ent", "d1e8ga1.ent-d1hlwa_.ent", "d1e8ga1.ent-d1i19a1.ent", "d1e8ga1.ent-d1jnrb_.ent", "d1e8ga1.ent-d1kvka2.ent", "d1e8ga1.ent-d1lfwa2.ent", "d1e8ga1.ent-d1qd1a1.ent", "d1e8ga1.ent-d1qd1a2.ent", "d1e8ga1.ent-d1regx_.ent", "d1e8ga2.ent-d1f0xa2.ent", "d1e8ga2.ent-d1fo4a6.ent", "d1e8ga2.ent-d1hska1.ent", "d1e8ga2.ent-d1i19a2.ent", "d1e8ga2.ent-d1jroa4.ent", "d1e8ga2.ent-d1n62c2.ent", "d1e8ga2.ent-d1uxy_1.ent", "d1e8ua_.ent-d1eur__.ent", "d1e8ua_.ent-d1f8ea_.ent", "d1e8ua_.ent-d1h6la_.ent", "d1e8ua_.ent-d1ijqa1.ent", "d1e8ua_.ent-d1k32a2.ent", "d1e8ua_.ent-d1kit_3.ent", "d1e8ua_.ent-d1n1ta2.ent", "d1e8ua_.ent-d1nsca_.ent", "d1e8ua_.ent-d2bat__.ent", "d1e8ua_.ent-d2sli_2.ent", "d1e8ua_.ent-d3sil__.ent", "d1e8xa1.ent-d1ee4a_.ent", "d1e8xa1.ent-d1elka_.ent", "d1e8xa1.ent-d1h6ka1.ent", "d1e8xa1.ent-d1h6ka2.ent", "d1e8xa1.ent-d1h6ka3.ent", "d1e8xa1.ent-d1ho8a_.ent", "d1e8xa1.ent-d1hs6a1.ent", "d1e8xa1.ent-d1iala_.ent", "d1e8xa1.ent-d1ihga1.ent", "d1e8xa1.ent-d1jdha_.ent", "d1e8xa1.ent-d1kpsb_.ent", "d1e8xa1.ent-d1kx9a_.ent", "d1e8xa1.ent-d1l5ja1.ent", "d1e8xa1.ent-d1lrv__.ent", "d1e8xa1.ent-d1n4ka1.ent", "d1e8xa2.ent-d1gmia_.ent", "d1e8xa2.ent-d1k5wa_.ent", "d1e8xa2.ent-d1l4ia2.ent", "d1e8xa2.ent-d1qasa2.ent", "d1e8xa2.ent-d1rlw__.ent", "d1e8xa2.ent-d1rsy__.ent", "d1e8xa2.ent-d1who__.ent", "d1e8xa2.ent-d3rpba_.ent", "d1e8xa3.ent-d1ayfa_.ent", "d1e8xa3.ent-d1bmlc3.ent", "d1e8xa3.ent-d1c9fa_.ent", "d1e8xa3.ent-d1czpa_.ent", "d1e8xa3.ent-d1d4ba_.ent", "d1e8xa3.ent-d1euvb_.ent", "d1e8xa3.ent-d1f52a1.ent", "d1e8xa3.ent-d1feha2.ent", "d1e8xa3.ent-d1fm0d_.ent", "d1e8xa3.ent-d1gg3a3.ent", "d1e8xa3.ent-d1gnua_.ent", "d1e8xa3.ent-d1h4ra3.ent", "d1e8xa3.ent-d1h8ca_.ent", "d1e8xa3.ent-d1i42a_.ent", "d1e8xa3.ent-d1ip9a_.ent", "d1e8xa3.ent-d1j8ca_.ent", "d1e8xa3.ent-d1k8rb_.ent", "d1e8xa3.ent-d1l4db_.ent", "d1e8xa3.ent-d1l5pa_.ent", "d1e8xa3.ent-d1l7ya_.ent", "d1e8xa3.ent-d1lfda_.ent", "d1e8xa3.ent-d1lm8b_.ent", "d1e8xa3.ent-d1m94a_.ent", "d1e8xa3.ent-d1qlab2.ent", "d1e8xa3.ent-d1qqra_.ent", "d1e8xa3.ent-d1rlf__.ent", "d1e8xa3.ent-d2sak__.ent", "d1e8xa3.ent-d3seb_2.ent", "d1e8xa3.ent-d3tss_2.ent", "d1e8xa4.ent-d1a06__.ent", "d1e8xa4.ent-d1apme_.ent", "d1e8xa4.ent-d1b6cb_.ent", "d1e8xa4.ent-d1blxa_.ent", "d1e8xa4.ent-d1cjaa_.ent", "d1e8xa4.ent-d1csn__.ent", "d1e8xa4.ent-d1f3mc_.ent", "d1e8xa4.ent-d1fgka_.ent", "d1e8xa4.ent-d1fvra_.ent", "d1e8xa4.ent-d1howa_.ent", "d1e8xa4.ent-d1ia9a_.ent", "d1e8xa4.ent-d1iepa_.ent", "d1e8xa4.ent-d1j7la_.ent", "d1e8xa4.ent-d1jksa_.ent", "d1e8xa4.ent-d1jnk__.ent", "d1e8xa4.ent-d1jpaa_.ent", "d1e8xa4.ent-d1jvpp_.ent", "d1e8xa4.ent-d1kwpa_.ent", "d1e8xa4.ent-d1lpua_.ent", "d1e8xa4.ent-d1lufa_.ent", "d1e8xa4.ent-d1m14a_.ent", "d1e8xa4.ent-d1p38__.ent", "d1e8xa4.ent-d1phk__.ent", "d1e8xa4.ent-d1tkia_.ent", "d1e9ga_.ent-d1i40a_.ent", "d1e9ga_.ent-d2prd__.ent", "d1e9ia1.ent-d1ec7a1.ent", "d1e9ia1.ent-d1fhua1.ent", "d1e9ia1.ent-d1jpdx1.ent", "d1e9ia1.ent-d1jpma1.ent", "d1e9ia1.ent-d1muca1.ent", "d1e9ia1.ent-d1onea1.ent", "d1e9ia1.ent-d2chr_1.ent", "d1e9ia1.ent-d2mnr_1.ent", "d1e9la2.ent-d1edqa3.ent", "d1e9la2.ent-d1goia3.ent", "d1e9la2.ent-d1itxa2.ent", "d1e9la2.ent-d1jnda2.ent", "d1e9la2.ent-d1kfwa2.ent", "d1e9la2.ent-d1lg2a2.ent", "d1e9la2.ent-d1ll7a2.ent", "d1e9ma_.ent-d1feha2.ent", "d1e9ma_.ent-d1fo4a2.ent", "d1e9ma_.ent-d1hlra2.ent", "d1e9ma_.ent-d1i7ha_.ent", "d1e9ma_.ent-d1jq4a_.ent", "d1e9ma_.ent-d1jroa2.ent", "d1e9ma_.ent-d1kf6b2.ent", "d1e9ma_.ent-d1krha3.ent", "d1e9ma_.ent-d1l5pa_.ent", "d1e9ma_.ent-d1n62a2.ent", "d1e9ma_.ent-d1nekb2.ent", "d1e9ma_.ent-d1put__.ent", "d1e9ma_.ent-d1qlab2.ent", "d1e9ma_.ent-d2pia_3.ent", "d1e9ra_.ent-d1a7j__.ent", "d1e9ra_.ent-d1aqua_.ent", "d1e9ra_.ent-d1bg2__.ent", "d1e9ra_.ent-d1c4oa1.ent", "d1e9ra_.ent-d1cr1a_.ent", "d1e9ra_.ent-d1e2ka_.ent", "d1e9ra_.ent-d1e69a_.ent", "d1e9ra_.ent-d1e79a3.ent", "d1e9ra_.ent-d1f5na2.ent", "d1e9ra_.ent-d1f9va_.ent", "d1e9ra_.ent-d1fmja_.ent", "d1e9ra_.ent-d1fnna2.ent", "d1e9ra_.ent-d1g41a_.ent", "d1e9ra_.ent-d1g8pa_.ent", "d1e9ra_.ent-d1g8ya_.ent", "d1e9ra_.ent-d1gm5a3.ent", "d1e9ra_.ent-d1i6ia_.ent", "d1e9ra_.ent-d1ihua1.ent", "d1e9ra_.ent-d1ii6a_.ent", "d1e9ra_.ent-d1jwyb_.ent", "d1e9ra_.ent-d1ksfx3.ent", "d1e9ra_.ent-d1lv7a_.ent", "d1e9ra_.ent-d1m6na3.ent", "d1e9ra_.ent-d1n0ua2.ent", "d1e9ra_.ent-d1nsta_.ent", "d1e9ra_.ent-d1pjr_1.ent", "d1e9ra_.ent-d1pjr_2.ent", "d1e9ra_.ent-d1uaaa1.ent", "d1e9ra_.ent-d1uaaa2.ent", "d1e9ra_.ent-d2ncda_.ent", "d1e9ta_.ent-d1hi7a_.ent", "d1e9ta_.ent-d2pspa2.ent", "d1e9xa_.ent-d1io7a_.ent", "d1e9xa_.ent-d1jfba_.ent", "d1e9xa_.ent-d1jipa_.ent", "d1e9xa_.ent-d1jpza_.ent", "d1e9xa_.ent-d1lfka_.ent", "d1e9xa_.ent-d1n97a_.ent", "d1e9ya1.ent-d1ejrb_.ent", "d1e9ya1.ent-d4ubpb_.ent", "d1ea0a2.ent-d1ep3a_.ent", "d1ea0a2.ent-d1gox__.ent", "d1ea0a2.ent-d1gtea2.ent", "d1ea0a2.ent-d1gvoa_.ent", "d1ea0a2.ent-d1huva_.ent", "d1ea0a2.ent-d1icpa_.ent", "d1ea0a2.ent-d1kbia1.ent", "d1ea0a2.ent-d1llwa2.ent", "d1ea0a2.ent-d1o94a1.ent", "d1ea0a2.ent-d1oyb__.ent", "d1ea0a2.ent-d2dora_.ent", "d1ea0a3.ent-d1ecfa2.ent", "d1ea0a3.ent-d1gdoa_.ent", "d1ea0a3.ent-d1gph12.ent", "d1ea0a3.ent-d1iru1_.ent", "d1ea0a3.ent-d1iru2_.ent", "d1ea0a3.ent-d1iruk_.ent", "d1ea0a3.ent-d1jgta2.ent", "d1ea0a3.ent-d1pma1_.ent", "d1ea0a3.ent-d1pmaa_.ent", "d1ea0a3.ent-d1ryp1_.ent", "d1ea0a3.ent-d1ryp2_.ent", "d1ea0a3.ent-d1rypa_.ent", "d1ea0a3.ent-d1rypb_.ent", "d1ea0a3.ent-d1rypc_.ent", "d1ea0a3.ent-d1rypd_.ent", "d1ea0a3.ent-d1rype_.ent", "d1ea0a3.ent-d1rypf_.ent", "d1ea0a3.ent-d1rypg_.ent", "d1ea0a3.ent-d1ryph_.ent", "d1ea0a3.ent-d1rypi_.ent", "d1ea0a3.ent-d1rypj_.ent", "d1ea0a3.ent-d1rypk_.ent", "d1ea0a3.ent-d1rypl_.ent", "d1ea2a_.ent-d1eeja2.ent", "d1ea2a_.ent-d1gy6a_.ent", "d1ea2a_.ent-d1gy7a_.ent", "d1ea2a_.ent-d1ivwa2.ent", "d1ea2a_.ent-d1ivwa3.ent", "d1ea2a_.ent-d1jkga_.ent", "d1ea2a_.ent-d1jkgb_.ent", "d1ea2a_.ent-d1ksia2.ent", "d1ea2a_.ent-d1ksia3.ent", "d1ea2a_.ent-d1kwia_.ent", "d1ea2a_.ent-d1m98a2.ent", "d1ea2a_.ent-d1mola_.ent", "d1ea2a_.ent-d1mwxa1.ent", "d1ea2a_.ent-d1o7nb_.ent", "d1ea2a_.ent-d1oaca2.ent", "d1ea2a_.ent-d1qjga_.ent", "d1ea2a_.ent-d1stfi_.ent", "d1ea2a_.ent-d1ugia_.ent", "d1ea2a_.ent-d3stda_.ent", "d1ea5a_.ent-d1ac5__.ent", "d1ea5a_.ent-d1bu8a2.ent", "d1ea5a_.ent-d1cpy__.ent", "d1ea5a_.ent-d1cr6a2.ent", "d1ea5a_.ent-d1cvl__.ent", "d1ea5a_.ent-d1hlga_.ent", "d1ea5a_.ent-d1ivya_.ent", "d1ea5a_.ent-d1iz7a_.ent", "d1ea5a_.ent-d1jjia_.ent", "d1ea5a_.ent-d1jkma_.ent", "d1ea5a_.ent-d1ju3a2.ent", "d1ea5a_.ent-d1k4ya_.ent", "d1ea5a_.ent-d1ku0a_.ent", "d1ea5a_.ent-d1l7aa_.ent", "d1ea5a_.ent-d1lnsa3.ent", "d1ea5a_.ent-d1lzla_.ent", "d1ea5a_.ent-d1qe3a_.ent", "d1ea5a_.ent-d1qlwa_.ent", "d1ea5a_.ent-d1qo7a_.ent", "d1ea5a_.ent-d1qtra_.ent", "d1ea5a_.ent-d1tca__.ent", "d1ea5a_.ent-d2bce__.ent", "d1ea7a_.ent-d1ga6a_.ent", "d1ea7a_.ent-d1gci__.ent", "d1ea7a_.ent-d1gt91_.ent", "d1ea7a_.ent-d1ic6a_.ent", "d1ea7a_.ent-d1thm__.ent", "d1ea9c1.ent-d1edqa1.ent", "d1ea9c1.ent-d1eut_1.ent", "d1ea9c1.ent-d1ji2a1.ent", "d1ea9c1.ent-d1kv3a1.ent", "d1ea9c1.ent-d1m7xa1.ent", "d1ea9c1.ent-d1my7a_.ent", "d1ea9c1.ent-d1qba_1.ent", "d1ea9c1.ent-d1qfha1.ent", "d1ea9c1.ent-d1qfha2.ent", "d1ea9c2.ent-d1eh9a2.ent", "d1ea9c2.ent-d1g5aa1.ent", "d1ea9c2.ent-d1g94a1.ent", "d1ea9c2.ent-d1gcya1.ent", "d1ea9c2.ent-d1gjwa1.ent", "d1ea9c2.ent-d1hx0a1.ent", "d1ea9c2.ent-d1iv8a1.ent", "d1ea9c2.ent-d1j0ha2.ent", "d1ea9c2.ent-d1jae_1.ent", "d1ea9c2.ent-d1ji1a2.ent", "d1ea9c2.ent-d1ji2a2.ent", "d1ea9c2.ent-d1ktba1.ent", "d1ea9c2.ent-d1kwga1.ent", "d1ea9c2.ent-d1lwha1.ent", "d1ea9c2.ent-d1m7xa2.ent", "d1ea9c2.ent-d1qhoa3.ent", "d1ea9c2.ent-d1uok_1.ent", "d1ea9c2.ent-d7taa_1.ent", "d1eaf__.ent-d1l5aa1.ent", "d1eaf__.ent-d1l5aa2.ent", "d1eaf__.ent-d1nocb_.ent", "d1eaf__.ent-d3cla__.ent", "d1eaic_.ent-d1hx2a_.ent", "d1eaja_.ent-d1a2yb_.ent", "d1eaja_.ent-d1akjd_.ent", "d1eaja_.ent-d1b88a_.ent", "d1eaja_.ent-d1bec_1.ent", "d1eaja_.ent-d1bqhg_.ent", "d1eaja_.ent-d1c5ch1.ent", "d1eaja_.ent-d1dlfh_.ent", "d1eaja_.ent-d1dlfl_.ent", "d1eaja_.ent-d1dqta_.ent", "d1eaja_.ent-d1fo0a_.ent", "d1eaja_.ent-d1grwa_.ent", "d1eaja_.ent-d1gsma2.ent", "d1eaja_.ent-d1h5ba_.ent", "d1eaja_.ent-d1hxma1.ent", "d1eaja_.ent-d1hxmb1.ent", "d1eaja_.ent-d1j0ha1.ent", "d1eaja_.ent-d1ktke1.ent", "d1eaja_.ent-d1kxvc_.ent", "d1eaja_.ent-d1neu__.ent", "d1eaja_.ent-d1nfdb1.ent", "d1eaja_.ent-d1qfoa_.ent", "d1eaja_.ent-d1soxa1.ent", "d1eaja_.ent-d1tvda_.ent", "d1eaja_.ent-d2rhe__.ent", "d1eaka1.ent-d1l6ja1.ent", "d1eaka1.ent-d1lbu_1.ent", "d1eaka1.ent-d1slm_1.ent", "d1eaxa_.ent-d1azza_.ent", "d1eaxa_.ent-d1bio__.ent", "d1eaxa_.ent-d1bqya_.ent", "d1eaxa_.ent-d1cgha_.ent", "d1eaxa_.ent-d1ekbb_.ent", "d1eaxa_.ent-d1elva1.ent", "d1eaxa_.ent-d1fjsa_.ent", "d1eaxa_.ent-d1gdna_.ent", "d1eaxa_.ent-d1gpza1.ent", "d1eaxa_.ent-d1gvkb_.ent", "d1eaxa_.ent-d1gvza_.ent", "d1eaxa_.ent-d1hj9a_.ent", "d1eaxa_.ent-d1m9ua_.ent", "d1eaxa_.ent-d1mzaa_.ent", "d1eaxa_.ent-d1rfna_.ent", "d1eaxa_.ent-d2hlca_.ent", "d1eaza_.ent-d1evha_.ent", "d1eaza_.ent-d1faoa_.ent", "d1eaza_.ent-d1fhoa_.ent", "d1eaza_.ent-d1gg3a2.ent", "d1eaza_.ent-d1h4ra2.ent", "d1eaza_.ent-d1k5db_.ent", "d1eaza_.ent-d1ki1b2.ent", "d1eaza_.ent-d1mai__.ent", "d1eaza_.ent-d1mixa2.ent", "d1eaza_.ent-d1mkea1.ent", "d1eaza_.ent-d1pls__.ent", "d1eaza_.ent-d1qqga1.ent", "d1eaza_.ent-d1qqga2.ent", "d1eaza_.ent-d1shca_.ent", "d1eb6a_.ent-d1epwa3.ent", "d1eb6a_.ent-d1ezm__.ent", "d1eb6a_.ent-d1g12a_.ent", "d1eb6a_.ent-d1gkda_.ent", "d1eb6a_.ent-d1gqia2.ent", "d1eb6a_.ent-d1hs6a3.ent", "d1eb6a_.ent-d1i1ip_.ent", "d1eb6a_.ent-d1j7na1.ent", "d1eb6a_.ent-d1j7na2.ent", "d1eb6a_.ent-d1jaka2.ent", "d1eb6a_.ent-d1jk3a_.ent", "d1eb6a_.ent-d1k7ia2.ent", "d1eb6a_.ent-d1k9xa_.ent", "d1eb6a_.ent-d1kapp2.ent", "d1eb6a_.ent-d1keia_.ent", "d1eb6a_.ent-d1kufa_.ent", "d1eb6a_.ent-d1lml__.ent", "d1eb6a_.ent-d1qba_4.ent", "d1eb6a_.ent-d3btaa3.ent", "d1eb7a1.ent-d1c52__.ent", "d1eb7a1.ent-d1co6a_.ent", "d1eb7a1.ent-d1cot__.ent", "d1eb7a1.ent-d1cxc__.ent", "d1eb7a1.ent-d1dw0a_.ent", "d1eb7a1.ent-d1e29a_.ent", "d1eb7a1.ent-d1eb7a2.ent", "d1eb7a1.ent-d1etpa2.ent", "d1eb7a1.ent-d1f1ca_.ent", "d1eb7a1.ent-d1gu2a_.ent", "d1eb7a1.ent-d1h32a1.ent", "d1eb7a1.ent-d1hroa_.ent", "d1eb7a1.ent-d1iqca1.ent", "d1eb7a1.ent-d1iqca2.ent", "d1eb7a1.ent-d1kb0a1.ent", "d1eb7a1.ent-d1kv9a1.ent", "d1eb7a1.ent-d1mg2d_.ent", "d1eb7a1.ent-d1nira1.ent", "d1eb7a1.ent-d1qksa1.ent", "d1eb7a1.ent-d1ql3a_.ent", "d1eb7a1.ent-d1qn2a_.ent", "d1eb7a1.ent-d1ycc__.ent", "d1eb7a1.ent-d3c2c__.ent", "d1eb7a2.ent-d1c52__.ent", "d1eb7a2.ent-d1co6a_.ent", "d1eb7a2.ent-d1cot__.ent", "d1eb7a2.ent-d1cxc__.ent", "d1eb7a2.ent-d1dw0a_.ent", "d1eb7a2.ent-d1e29a_.ent", "d1eb7a2.ent-d1etpa2.ent", "d1eb7a2.ent-d1f1ca_.ent", "d1eb7a2.ent-d1gu2a_.ent", "d1eb7a2.ent-d1h32a1.ent", "d1eb7a2.ent-d1hroa_.ent", "d1eb7a2.ent-d1iqca1.ent", "d1eb7a2.ent-d1kb0a1.ent", "d1eb7a2.ent-d1kv9a1.ent", "d1eb7a2.ent-d1mg2d_.ent", "d1eb7a2.ent-d1nira1.ent", "d1eb7a2.ent-d1qksa1.ent", "d1eb7a2.ent-d1ql3a_.ent", "d1eb7a2.ent-d1qn2a_.ent", "d1eb7a2.ent-d1ycc__.ent", "d1eb7a2.ent-d3c2c__.ent", "d1ebda3.ent-d1fcda3.ent", "d1ebda3.ent-d1feca3.ent", "d1ebda3.ent-d1h6va3.ent", "d1ebda3.ent-d1lvl_3.ent", "d1ebda3.ent-d1m6ia3.ent", "d1ebda3.ent-d1mo9a3.ent", "d1ebda3.ent-d1nhp_3.ent", "d1ebda3.ent-d1ojt_3.ent", "d1ebda3.ent-d3grs_3.ent", "d1ebda3.ent-d3lada3.ent", "d1ebfa2.ent-d1f06a2.ent", "d1ebfa2.ent-d1gr0a2.ent", "d1ebfa2.ent-d1h6da2.ent", "d1ebfa2.ent-d1j5pa3.ent", "d1ebfa2.ent-d1jkia2.ent", "d1ebfa2.ent-d1jn0a2.ent", "d1ebfa2.ent-d1lc0a2.ent", "d1ebfa2.ent-d1mb4a2.ent", "d1ebfa2.ent-d1qkia2.ent", "d1ec7a1.ent-d1fhua1.ent", "d1ec7a1.ent-d1jpdx1.ent", "d1ec7a1.ent-d1jpma1.ent", "d1ec7a1.ent-d1muca1.ent", "d1ec7a1.ent-d1onea1.ent", "d1ec7a1.ent-d2chr_1.ent", "d1ec7a1.ent-d2mnr_1.ent", "d1ec7a2.ent-d1fhua2.ent", "d1ec7a2.ent-d1jpdx2.ent", "d1ec7a2.ent-d1jpma2.ent", "d1ec7a2.ent-d1muca2.ent", "d1ec7a2.ent-d1onea2.ent", "d1ec7a2.ent-d2chr_2.ent", "d1ec7a2.ent-d2mnr_2.ent", "d1ecfa1.ent-d1fsga_.ent", "d1ecfa1.ent-d1g2qa_.ent", "d1ecfa1.ent-d1g9sa_.ent", "d1ecfa1.ent-d1gph11.ent", "d1ecfa1.ent-d1hgxa_.ent", "d1ecfa1.ent-d1i5ea_.ent", "d1ecfa1.ent-d1l1qa_.ent", "d1ecfa1.ent-d1lh0a_.ent", "d1ecfa1.ent-d1nula_.ent", "d1ecfa1.ent-d1qb7a_.ent", "d1ecfa1.ent-d1tc1a_.ent", "d1ecfa2.ent-d1gdoa_.ent", "d1ecfa2.ent-d1gph12.ent", "d1ecfa2.ent-d1iru1_.ent", "d1ecfa2.ent-d1iru2_.ent", "d1ecfa2.ent-d1iruk_.ent", "d1ecfa2.ent-d1jgta2.ent", "d1ecfa2.ent-d1pma1_.ent", "d1ecfa2.ent-d1pmaa_.ent", "d1ecfa2.ent-d1ryp1_.ent", "d1ecfa2.ent-d1ryp2_.ent", "d1ecfa2.ent-d1rypa_.ent", "d1ecfa2.ent-d1rypc_.ent", "d1ecfa2.ent-d1rypd_.ent", "d1ecfa2.ent-d1rype_.ent", "d1ecfa2.ent-d1rypf_.ent", "d1ecfa2.ent-d1rypg_.ent", "d1ecfa2.ent-d1ryph_.ent", "d1ecfa2.ent-d1rypi_.ent", "d1ecfa2.ent-d1rypj_.ent", "d1ecfa2.ent-d1rypk_.ent", "d1ecfa2.ent-d1rypl_.ent", "d1ecsa_.ent-d1f9za_.ent", "d1ecsa_.ent-d1kw3b1.ent", "d1ecsa_.ent-d1kw3b2.ent", "d1ecsa_.ent-d1lqpa_.ent", "d1ecsa_.ent-d1mpya1.ent", "d1ecsa_.ent-d1mpya2.ent", "d1ecsa_.ent-d1qipa_.ent", "d1ecsa_.ent-d1qtoa_.ent", "d1ecwa_.ent-d1hiwa_.ent", "d1ecwa_.ent-d1jvr__.ent", "d1ecwa_.ent-d1mn8a_.ent", "d1ed8a_.ent-d1eqja2.ent", "d1ed8a_.ent-d1ew2a_.ent", "d1ed8a_.ent-d1k7ha_.ent", "d1edg__.ent-d1d3ga_.ent", "d1edg__.ent-d1gvoa_.ent", "d1edg__.ent-d1gw1a_.ent", "d1edg__.ent-d1itua_.ent", "d1edg__.ent-d1k4ga_.ent", "d1edg__.ent-d1kbla1.ent", "d1edg__.ent-d1m7ja3.ent", "d1edha2.ent-d1l3wa3.ent", "d1edha2.ent-d1l3wa4.ent", "d1edha2.ent-d1l3wa5.ent", "d1edqa1.ent-d1eut_1.ent", "d1edqa1.ent-d1kv3a1.ent", "d1edqa1.ent-d1my7a_.ent", "d1edqa1.ent-d1qba_1.ent", "d1edqa1.ent-d1qfha1.ent", "d1edqa1.ent-d1qfha2.ent", "d1edqa3.ent-d1goia3.ent", "d1edqa3.ent-d1grj_2.ent", "d1edqa3.ent-d1hxva_.ent", "d1edqa3.ent-d1itxa2.ent", "d1edqa3.ent-d1jnda2.ent", "d1edqa3.ent-d1kfwa2.ent", "d1edqa3.ent-d1lg2a2.ent", "d1edqa3.ent-d1ll7a2.ent", "d1edqa3.ent-d1m5ya2.ent", "d1edqa3.ent-d1pina2.ent", "d1edqa3.ent-d3eipa_.ent", "d1edza2.ent-d1gtma2.ent", "d1edza2.ent-d1hwxa2.ent", "d1edza2.ent-d1leha2.ent", "d1edza2.ent-d1lu9a2.ent", "d1ee4a_.ent-d1h6ka1.ent", "d1ee4a_.ent-d1h6ka2.ent", "d1ee4a_.ent-d1h6ka3.ent", "d1ee4a_.ent-d1ho8a_.ent", "d1ee4a_.ent-d1hs6a1.ent", "d1ee4a_.ent-d1iala_.ent", "d1ee4a_.ent-d1jdha_.ent", "d1ee4a_.ent-d1kx9a_.ent", "d1ee4a_.ent-d1lrv__.ent", "d1ee4a_.ent-d1n4ka1.ent", "d1ee6a_.ent-d1ezga_.ent", "d1ee6a_.ent-d1hf2a1.ent", "d1ee6a_.ent-d1hg8a_.ent", "d1ee6a_.ent-d1jtaa_.ent", "d1ee6a_.ent-d1k4za_.ent", "d1ee6a_.ent-d1k5ca_.ent", "d1ee6a_.ent-d1llwa1.ent", "d1ee6a_.ent-d1qcxa_.ent", "d1ee6a_.ent-d1qjva_.ent", "d1ee6a_.ent-d1qq1a_.ent", "d1ee6a_.ent-d1rmg__.ent", "d1ee8a1.ent-d1fjgm_.ent", "d1ee8a1.ent-d1k3xa1.ent", "d1ee8a1.ent-d1k82a1.ent", "d1ee8a1.ent-d1l1za1.ent", "d1ee8a1.ent-d1mu5a1.ent", "d1ee8a1.ent-d1nnja1.ent", "d1ee8a2.ent-d1k3xa2.ent", "d1ee8a2.ent-d1k82a2.ent", "d1ee8a2.ent-d1l1za2.ent", "d1ee8a2.ent-d1nnja2.ent", "d1eeja1.ent-d1a8l_1.ent", "d1eeja1.ent-d1a8l_2.ent", "d1eeja1.ent-d1a8y_1.ent", "d1eeja1.ent-d1a8y_2.ent", "d1eeja1.ent-d1a8y_3.ent", "d1eeja1.ent-d1aba__.ent", "d1eeja1.ent-d1aqwa2.ent", "d1eeja1.ent-d1bed_2.ent", "d1eeja1.ent-d1bjx__.ent", "d1eeja1.ent-d1e6ba2.ent", "d1eeja1.ent-d1ep7a_.ent", "d1eeja1.ent-d1erv__.ent", "d1eeja1.ent-d1f9ma_.ent", "d1eeja1.ent-d1fb6a_.ent", "d1eeja1.ent-d1fhe_2.ent", "d1eeja1.ent-d1fvka2.ent", "d1eeja1.ent-d1g7ea_.ent", "d1eeja1.ent-d1gh2a_.ent", "d1eeja1.ent-d1hyua4.ent", "d1eeja1.ent-d1i5ga_.ent", "d1eeja1.ent-d1iloa_.ent", "d1eeja1.ent-d1k0ma2.ent", "d1eeja1.ent-d1k3ya2.ent", "d1eeja1.ent-d1knga_.ent", "d1eeja1.ent-d1kte__.ent", "d1eeja1.ent-d1m2da_.ent", "d1eeja1.ent-d1mek__.ent", "d1eeja1.ent-d1qmha1.ent", "d1eeja1.ent-d1quwa_.ent", "d1eeja1.ent-d1thx__.ent", "d1eeja1.ent-d2trxa_.ent", "d1eeja2.ent-d1gy7a_.ent", "d1eeja2.ent-d1ivwa2.ent", "d1eeja2.ent-d1ivwa3.ent", "d1eeja2.ent-d1jkgb_.ent", "d1eeja2.ent-d1ksia2.ent", "d1eeja2.ent-d1ksia3.ent", "d1eeja2.ent-d1kwia_.ent", "d1eeja2.ent-d1mola_.ent", "d1eeja2.ent-d1mwxa1.ent", "d1eeja2.ent-d1o7nb_.ent", "d1eeja2.ent-d1oaca2.ent", "d1eeja2.ent-d1stfi_.ent", "d1eeja2.ent-d1ugia_.ent", "d1eeja2.ent-d3stda_.ent", "d1eema1.ent-d1f2ea1.ent", "d1eema1.ent-d1fw1a1.ent", "d1eema1.ent-d1g7oa1.ent", "d1eema1.ent-d1glqa1.ent", "d1eema1.ent-d1gnwa1.ent", "d1eema1.ent-d1gula1.ent", "d1eema1.ent-d1gwca1.ent", "d1eema1.ent-d1jlva1.ent", "d1eema1.ent-d1k0da1.ent", "d1eema1.ent-d1k0ma1.ent", "d1eema1.ent-d1k3ya1.ent", "d1eema1.ent-d1ljra1.ent", "d1eema1.ent-d1m0ua1.ent", "d1eema1.ent-d1pd211.ent", "d1eema1.ent-d1pmt_1.ent", "d1eema1.ent-d2gsq_1.ent", "d1eema1.ent-d2gsta1.ent", "d1eeoa_.ent-d1fpza_.ent", "d1eeoa_.ent-d1g4us2.ent", "d1eeoa_.ent-d1i9sa_.ent", "d1eeoa_.ent-d1ikza_.ent", "d1eeoa_.ent-d1jlna_.ent", "d1eeoa_.ent-d1lara1.ent", "d1eeoa_.ent-d1lara2.ent", "d1eeoa_.ent-d1lyva_.ent", "d1eeoa_.ent-d1mkp__.ent", "d1eeoa_.ent-d1vhra_.ent", "d1eeoa_.ent-d1yfoa_.ent", "d1eeoa_.ent-d2shpa1.ent", "d1eera_.ent-d1etea_.ent", "d1eera_.ent-d1evsa_.ent", "d1eera_.ent-d1f45b_.ent", "d1eera_.ent-d1f6fa_.ent", "d1eera_.ent-d1hula_.ent", "d1eera_.ent-d1huw__.ent", "d1eera_.ent-d1hzia_.ent", "d1eera_.ent-d1i1rb_.ent", "d1eera_.ent-d1jli__.ent", "d1eera_.ent-d1lki__.ent", "d1eera_.ent-d1lqsl_.ent", "d1eera_.ent-d1m47a_.ent", "d1eera_.ent-d1n1fa_.ent", "d1eera_.ent-d2gmfa_.ent", "d1eera_.ent-d2ilk__.ent", "d1eerb1.ent-d1axib2.ent", "d1eerb1.ent-d1bpv__.ent", "d1eerb1.ent-d1cd9b1.ent", "d1eerb1.ent-d1cd9b2.ent", "d1eerb1.ent-d1cfb_1.ent", "d1eerb1.ent-d1cfb_2.ent", "d1eerb1.ent-d1eerb2.ent", "d1eerb1.ent-d1egja_.ent", "d1eerb1.ent-d1f6fb1.ent", "d1eerb1.ent-d1f6fb2.ent", "d1eerb1.ent-d1fyhb1.ent", "d1eerb1.ent-d1fyhb2.ent", "d1eerb1.ent-d1gh7a1.ent", "d1eerb1.ent-d1i1ra1.ent", "d1eerb1.ent-d1lqsr1.ent", "d1eerb1.ent-d1lqsr2.ent", "d1eerb1.ent-d1n26a2.ent", "d1eerb1.ent-d1n26a3.ent", "d1eerb1.ent-d1qg3a2.ent", "d1eerb1.ent-d2hft_1.ent", "d1eerb1.ent-d2hft_2.ent", "d1eerb2.ent-d1cd9b2.ent", "d1eerb2.ent-d1cfb_1.ent", "d1eerb2.ent-d1egja_.ent", "d1eerb2.ent-d1f6fb1.ent", "d1eerb2.ent-d1f6fb2.ent", "d1eerb2.ent-d1fyhb1.ent", "d1eerb2.ent-d1fyhb2.ent", "d1eerb2.ent-d1gh7a1.ent", "d1eerb2.ent-d1i1ra1.ent", "d1eerb2.ent-d1lqsr1.ent", "d1eerb2.ent-d1n26a2.ent", "d1eerb2.ent-d1n26a3.ent", "d1eerb2.ent-d1qg3a2.ent", "d1eerb2.ent-d2hft_1.ent", "d1eerb2.ent-d2hft_2.ent", "d1eexa_.ent-d1ccwb_.ent", "d1eexa_.ent-d1cz1a_.ent", "d1eexa_.ent-d1d3ga_.ent", "d1eexa_.ent-d1e4mm_.ent", "d1eexa_.ent-d1edg__.ent", "d1eexa_.ent-d1eswa_.ent", "d1eexa_.ent-d1f8ma_.ent", "d1eexa_.ent-d1gvoa_.ent", "d1eexa_.ent-d1gw1a_.ent", "d1eexa_.ent-d1iexa1.ent", "d1eexa_.ent-d1itua_.ent", "d1eexa_.ent-d1j5sa_.ent", "d1eexa_.ent-d1k4ga_.ent", "d1eexa_.ent-d1kbla1.ent", "d1eexa_.ent-d1kwga2.ent", "d1eexa_.ent-d1m7ja3.ent", "d1eexa_.ent-d1muwa_.ent", "d1eexa_.ent-d1ntha_.ent", "d1eexa_.ent-d7reqa1.ent", "d1eexa_.ent-d7reqb1.ent", "d1eexb_.ent-d1ex2a_.ent", "d1eexb_.ent-d1h4vb1.ent", "d1eexb_.ent-d1hc7a1.ent", "d1eexb_.ent-d1nbwb_.ent", "d1eexb_.ent-d1qe0a1.ent", "d1eexg_.ent-d1fpoa2.ent", "d1eexg_.ent-d1jw2a_.ent", "d1eexg_.ent-d1mtyg_.ent", "d1eexg_.ent-d1om2a_.ent", "d1ef8a_.ent-d1hnua_.ent", "d1ef8a_.ent-d1hzda_.ent", "d1ef8a_.ent-d1k32a4.ent", "d1ef8a_.ent-d1mj3a_.ent", "d1ef8a_.ent-d1nzya_.ent", "d1ef8a_.ent-d1o8ua_.ent", "d1ef8a_.ent-d1tyfa_.ent", "d1efaa1.ent-d1ic8a2.ent", "d1efaa1.ent-d1lmb3_.ent", "d1efaa1.ent-d1ner__.ent", "d1efaa1.ent-d1r69__.ent", "d1efaa1.ent-d1uxd__.ent", "d1efaa1.ent-d1vpwa1.ent", "d1efdn_.ent-d1m1na_.ent", "d1efdn_.ent-d1m1nb_.ent", "d1efdn_.ent-d1mioa_.ent", "d1efdn_.ent-d1miob_.ent", "d1efdn_.ent-d1n2za_.ent", "d1efdn_.ent-d1psza_.ent", "d1efdn_.ent-d1toaa_.ent", "d1efpa1.ent-d1efva1.ent", "d1efpa1.ent-d1efvb_.ent", "d1efpa1.ent-d1gpma1.ent", "d1efpa1.ent-d1jgta1.ent", "d1efpa1.ent-d1jmva_.ent", "d1efpa1.ent-d1k92a1.ent", "d1efpa1.ent-d1kora1.ent", "d1efpa1.ent-d1kqpa_.ent", "d1efpa1.ent-d1mjha_.ent", "d1efpa1.ent-d1o97c_.ent", "d1efpa1.ent-d1o97d1.ent", "d1efpa1.ent-d1sur__.ent", "d1efub2.ent-d1efub4.ent", "d1efub2.ent-d1tfe__.ent", "d1efub3.ent-d1eija_.ent", "d1efub3.ent-d1enwa_.ent", "d1efub3.ent-d1f4ia_.ent", "d1efub3.ent-d1ifya_.ent", "d1efub3.ent-d1oaia_.ent", "d1efub4.ent-d1tfe__.ent", "d1efva1.ent-d1efvb_.ent", "d1efva1.ent-d1ej2a_.ent", "d1efva1.ent-d1f4la2.ent", "d1efva1.ent-d1f7ua2.ent", "d1efva1.ent-d1gpma1.ent", "d1efva1.ent-d1ihoa_.ent", "d1efva1.ent-d1ile_3.ent", "d1efva1.ent-d1irxa2.ent", "d1efva1.ent-d1j09a2.ent", "d1efva1.ent-d1jgta1.ent", "d1efva1.ent-d1jhda2.ent", "d1efva1.ent-d1jila_.ent", "d1efva1.ent-d1jmva_.ent", "d1efva1.ent-d1k4ma_.ent", "d1efva1.ent-d1k92a1.ent", "d1efva1.ent-d1kora1.ent", "d1efva1.ent-d1kqna_.ent", "d1efva1.ent-d1kqpa_.ent", "d1efva1.ent-d1li5a2.ent", "d1efva1.ent-d1mjha_.ent", "d1efva1.ent-d1n3la_.ent", "d1efva1.ent-d1o97c_.ent", "d1efva1.ent-d1o97d1.ent", "d1efva1.ent-d1qjca_.ent", "d1efva1.ent-d1sur__.ent", "d1efva2.ent-d1hzzc_.ent", "d1efva2.ent-d1icia_.ent", "d1efva2.ent-d1j8fa_.ent", "d1efva2.ent-d1jsca1.ent", "d1efva2.ent-d1ma3a_.ent", "d1efva2.ent-d1o97d2.ent", "d1efva2.ent-d1poxa1.ent", "d1efva2.ent-d1pvda1.ent", "d1efva2.ent-d1zpda1.ent", "d1efvb_.ent-d1gpma1.ent", "d1efvb_.ent-d1jgta1.ent", "d1efvb_.ent-d1jmva_.ent", "d1efvb_.ent-d1k92a1.ent", "d1efvb_.ent-d1kora1.ent", "d1efvb_.ent-d1kqpa_.ent", "d1efvb_.ent-d1mjha_.ent", "d1efvb_.ent-d1o97c_.ent", "d1efvb_.ent-d1o97d1.ent", "d1efvb_.ent-d1sur__.ent", "d1eg2a_.ent-d1fp1d2.ent", "d1eg2a_.ent-d1fp2a2.ent", "d1eg2a_.ent-d1g60a_.ent", "d1eg2a_.ent-d1hnna_.ent", "d1eg2a_.ent-d1i1na_.ent", "d1eg2a_.ent-d1i9ga_.ent", "d1eg2a_.ent-d1jg1a_.ent", "d1eg2a_.ent-d1kywa2.ent", "d1eg2a_.ent-d1qama_.ent", "d1eg2a_.ent-d1yub__.ent", "d1eg2a_.ent-d2dpma_.ent", "d1eg3a1.ent-d1eg3a2.ent", "d1eg3a1.ent-d1el4a_.ent", "d1eg3a1.ent-d1fi6a_.ent", "d1eg3a1.ent-d1h8ba_.ent", "d1eg3a1.ent-d1iioa_.ent", "d1eg3a1.ent-d1j7qa_.ent", "d1eg3a1.ent-d1k94a_.ent", "d1eg3a1.ent-d1m31a_.ent", "d1eg3a1.ent-d1m45a_.ent", "d1eg3a1.ent-d1psra_.ent", "d1eg3a1.ent-d1qasa1.ent", "d1eg3a1.ent-d1rec__.ent", "d1eg3a1.ent-d1rro__.ent", "d1eg3a1.ent-d1sra__.ent", "d1eg3a1.ent-d2cbla1.ent", "d1eg3a1.ent-d2pvba_.ent", "d1eg3a1.ent-d2sas__.ent", "d1eg3a1.ent-d2scpa_.ent", "d1eg3a1.ent-d5pal__.ent", "d1eg3a2.ent-d1el4a_.ent", "d1eg3a2.ent-d1fi6a_.ent", "d1eg3a2.ent-d1h8ba_.ent", "d1eg3a2.ent-d1iioa_.ent", "d1eg3a2.ent-d1j7qa_.ent", "d1eg3a2.ent-d1k94a_.ent", "d1eg3a2.ent-d1m45a_.ent", "d1eg3a2.ent-d1psra_.ent", "d1eg3a2.ent-d1qasa1.ent", "d1eg3a2.ent-d1rec__.ent", "d1eg3a2.ent-d1sra__.ent", "d1eg3a2.ent-d2cbla1.ent", "d1eg3a2.ent-d2pvba_.ent", "d1eg3a2.ent-d2sas__.ent", "d1eg3a2.ent-d2scpa_.ent", "d1eg3a3.ent-d1goia1.ent", "d1eg3a3.ent-d1i5hw_.ent", "d1eg3a3.ent-d1jmqa_.ent", "d1eg3a3.ent-d1o6wa2.ent", "d1eg3a3.ent-d1pina1.ent", "d1eg7a_.ent-d1a7j__.ent", "d1eg7a_.ent-d1aqua_.ent", "d1eg7a_.ent-d1bg2__.ent", "d1eg7a_.ent-d1c4oa1.ent", "d1eg7a_.ent-d1cr1a_.ent", "d1eg7a_.ent-d1dj3a_.ent", "d1eg7a_.ent-d1e2ka_.ent", "d1eg7a_.ent-d1e69a_.ent", "d1eg7a_.ent-d1e79a3.ent", "d1eg7a_.ent-d1e9ra_.ent", "d1eg7a_.ent-d1f5na2.ent", "d1eg7a_.ent-d1f9va_.ent", "d1eg7a_.ent-d1fmja_.ent", "d1eg7a_.ent-d1fnna2.ent", "d1eg7a_.ent-d1g41a_.ent", "d1eg7a_.ent-d1g8pa_.ent", "d1eg7a_.ent-d1g8ya_.ent", "d1eg7a_.ent-d1gm5a3.ent", "d1eg7a_.ent-d1i6ia_.ent", "d1eg7a_.ent-d1ihua1.ent", "d1eg7a_.ent-d1ii6a_.ent", "d1eg7a_.ent-d1iwea_.ent", "d1eg7a_.ent-d1jwyb_.ent", "d1eg7a_.ent-d1ksfx3.ent", "d1eg7a_.ent-d1lv7a_.ent", "d1eg7a_.ent-d1m6na3.ent", "d1eg7a_.ent-d1n0ua2.ent", "d1eg7a_.ent-d1nsta_.ent", "d1eg7a_.ent-d1pjr_1.ent", "d1eg7a_.ent-d1pjr_2.ent", "d1eg7a_.ent-d1qf5a_.ent", "d1eg7a_.ent-d1uaaa1.ent", "d1eg7a_.ent-d1uaaa2.ent", "d1eg7a_.ent-d2ncda_.ent", "d1egaa2.ent-d1fjgc1.ent", "d1egaa2.ent-d1gpma3.ent", "d1egaa2.ent-d1hh2p2.ent", "d1egaa2.ent-d1ib8a2.ent", "d1egaa2.ent-d1iw5a_.ent", "d1egaa2.ent-d1k0ra2.ent", "d1egaa2.ent-d1k0ra3.ent", "d1egaa2.ent-d1mkya3.ent", "d1egaa2.ent-d3proc1.ent", "d1egaa2.ent-d3proc2.ent", "d1egia_.ent-d1b08a1.ent", "d1egia_.ent-d1b6e__.ent", "d1egia_.ent-d1byfa_.ent", "d1egia_.ent-d1cwva5.ent", "d1egia_.ent-d1dv8a_.ent", "d1egia_.ent-d1e87a_.ent", "d1egia_.ent-d1f00i3.ent", "d1egia_.ent-d1fvub_.ent", "d1egia_.ent-d1g1ta1.ent", "d1egia_.ent-d1h8ua_.ent", "d1egia_.ent-d1hq8a_.ent", "d1egia_.ent-d1jwia_.ent", "d1egia_.ent-d1jwib_.ent", "d1egia_.ent-d1li1a1.ent", "d1egia_.ent-d1li1a2.ent", "d1egia_.ent-d1prtb2.ent", "d1egia_.ent-d1qo3c_.ent", "d1egia_.ent-d1tsg__.ent", "d1egja_.ent-d1cd9b2.ent", "d1egja_.ent-d1cfb_1.ent", "d1egja_.ent-d1f6fb1.ent", "d1egja_.ent-d1f6fb2.ent", "d1egja_.ent-d1fyhb1.ent", "d1egja_.ent-d1i1ra1.ent", "d1egja_.ent-d1lqsr1.ent", "d1eh1a_.ent-d1ek8a_.ent", "d1eh1a_.ent-d1ge9a_.ent", "d1eh9a2.ent-d1g5aa1.ent", "d1eh9a2.ent-d1g94a1.ent", "d1eh9a2.ent-d1gcya1.ent", "d1eh9a2.ent-d1gjwa1.ent", "d1eh9a2.ent-d1hx0a1.ent", "d1eh9a2.ent-d1iv8a1.ent", "d1eh9a2.ent-d1j0ha2.ent", "d1eh9a2.ent-d1jae_1.ent", "d1eh9a2.ent-d1ji1a2.ent", "d1eh9a2.ent-d1ji2a2.ent", "d1eh9a2.ent-d1ktba1.ent", "d1eh9a2.ent-d1kwga1.ent", "d1eh9a2.ent-d1lwha1.ent", "d1eh9a2.ent-d1m7xa2.ent", "d1eh9a2.ent-d1qhoa3.ent", "d1eh9a2.ent-d1uok_1.ent", "d1eh9a2.ent-d7taa_1.ent", "d1eh9a3.ent-d1cz1a_.ent", "d1eh9a3.ent-d1e43a2.ent", "d1eh9a3.ent-d1iexa1.ent", "d1eh9a3.ent-d1j0ha3.ent", "d1eh9a3.ent-d1kwga2.ent", "d1eh9a3.ent-d1lwha2.ent", "d1eh9a3.ent-d7taa_2.ent", "d1ehia1.ent-d1gsa_1.ent", "d1ehia1.ent-d1gsoa2.ent", "d1ehia1.ent-d1iow_1.ent", "d1ehia1.ent-d1kjqa2.ent", "d1ehia1.ent-d1m0wa1.ent", "d1ehia1.ent-d2hgsa1.ent", "d1ehia2.ent-d1eucb2.ent", "d1ehia2.ent-d1gsa_2.ent", "d1ehia2.ent-d1gsoa3.ent", "d1ehia2.ent-d1iow_2.ent", "d1ehia2.ent-d1jkjb2.ent", "d1ehia2.ent-d1kbla3.ent", "d1ehia2.ent-d1kjqa3.ent", "d1ehia2.ent-d1m0wa2.ent", "d1ehia2.ent-d2hgsa4.ent", "d1ehka_.ent-d1ffta_.ent", "d1ehka_.ent-d1ocra_.ent", "d1ehkb2.ent-d1fftb2.ent", "d1ehkb2.ent-d1m56b2.ent", "d1ehkb2.ent-d1ocrb2.ent", "d1ehkc_.ent-d1ezvd2.ent", "d1ehkc_.ent-d1ezve2.ent", "d1ehkc_.ent-d1ezvg_.ent", "d1ehkc_.ent-d1ezvi_.ent", "d1ehkc_.ent-d1jb0f_.ent", "d1ehkc_.ent-d1jb0i_.ent", "d1ehkc_.ent-d1jb0j_.ent", "d1ehkc_.ent-d1jb0m_.ent", "d1ehkc_.ent-d1kqfb2.ent", "d1ehkc_.ent-d1l2pa_.ent", "d1ehkc_.ent-d1m56d_.ent", "d1ehkc_.ent-d1ocrd_.ent", "d1ehkc_.ent-d1ocrg_.ent", "d1ehkc_.ent-d1ocri_.ent", "d1ehkc_.ent-d1ocrj_.ent", "d1ehkc_.ent-d1ocrk_.ent", "d1ehkc_.ent-d1ocrl_.ent", "d1ehkc_.ent-d1ocrm_.ent", "d1ehwa_.ent-d1hlwa_.ent", "d1ehwa_.ent-d1k44a_.ent", "d1ehwa_.ent-d1nhkl_.ent", "d1ei1a1.ent-d1fjgi_.ent", "d1ei1a1.ent-d1h72c1.ent", "d1ei1a1.ent-d1kija1.ent", "d1ei1a1.ent-d1kkha1.ent", "d1ei1a1.ent-d1kvka1.ent", "d1ei1a1.ent-d1mu5a2.ent", "d1ei1a1.ent-d1n0ua3.ent", "d1ei1a1.ent-d1pkp_1.ent", "d1ei1a2.ent-d1gkza2.ent", "d1ei1a2.ent-d1i58a_.ent", "d1ei1a2.ent-d1id0a_.ent", "d1ei1a2.ent-d1jm6a2.ent", "d1ei1a2.ent-d1kija2.ent", "d1ei1a2.ent-d1l0oa_.ent", "d1ei1a2.ent-d1mu5a3.ent", "d1ei5a1.ent-d1ei5a2.ent", "d1ei5a1.ent-d1jiwi_.ent", "d1ei5a1.ent-d1jmxa5.ent", "d1ei5a1.ent-d1k3ba_.ent", "d1ei5a1.ent-d1swua_.ent", "d1ei5a2.ent-d1jiwi_.ent", "d1ei5a2.ent-d1jmxa5.ent", "d1ei5a2.ent-d1k3ba_.ent", "d1ei5a2.ent-d1swua_.ent", "d1ei5a3.ent-d1es5a_.ent", "d1ei5a3.ent-d1g6aa_.ent", "d1ei5a3.ent-d1ghpa_.ent", "d1ei5a3.ent-d1iyoa_.ent", "d1ei5a3.ent-d1l0ga_.ent", "d1ei5a3.ent-d1m40a_.ent", "d1ei5a3.ent-d1mfoa_.ent", "d1ei5a3.ent-d1mwxa3.ent", "d1ei5a3.ent-d1nj4a2.ent", "d1ei5a3.ent-d1qmea4.ent", "d1ei5a3.ent-d4blma_.ent", "d1ei7a_.ent-d1f1ma_.ent", "d1ei7a_.ent-d1fts_1.ent", "d1ei7a_.ent-d1he1a_.ent", "d1ei7a_.ent-d1jr8a_.ent", "d1ei7a_.ent-d1k04a_.ent", "d1ei7a_.ent-d1knya1.ent", "d1ei7a_.ent-d1ls1a1.ent", "d1ei7a_.ent-d1nfn__.ent", "d1ei7a_.ent-d1nlxa_.ent", "d1ei7a_.ent-d1rmva_.ent", "d1ei7a_.ent-d256ba_.ent", "d1ei7a_.ent-d2a0b__.ent", "d1ei7a_.ent-d2liga_.ent", "d1ei7a_.ent-d2mhr__.ent", "d1ei7a_.ent-d3fapb_.ent", "d1ei9a_.ent-d1ex9a_.ent", "d1ei9a_.ent-d1fj2a_.ent", "d1ei9a_.ent-d1gkla_.ent", "d1ei9a_.ent-d1hlga_.ent", "d1ei9a_.ent-d1imja_.ent", "d1ei9a_.ent-d1ispa_.ent", "d1ei9a_.ent-d1jfra_.ent", "d1ei9a_.ent-d1ju3a2.ent", "d1ei9a_.ent-d1ku0a_.ent", "d1ei9a_.ent-d1l7aa_.ent", "d1ei9a_.ent-d1lzla_.ent", "d1ei9a_.ent-d1mnaa_.ent", "d1ei9a_.ent-d1n1ma2.ent", "d1ei9a_.ent-d1qj4a_.ent", "d1ei9a_.ent-d1qlwa_.ent", "d1ei9a_.ent-d1qo7a_.ent", "d1ei9a_.ent-d1tca__.ent", "d1ei9a_.ent-d1thta_.ent", "d1ei9a_.ent-d3tgl__.ent", "d1eiha_.ent-d1el0a_.ent", "d1eiha_.ent-d1f2la_.ent", "d1eiha_.ent-d1g2ta_.ent", "d1eiha_.ent-d1j9oa_.ent", "d1eiha_.ent-d1m8aa_.ent", "d1eiha_.ent-d1qg7a_.ent", "d1eiha_.ent-d1tvxa_.ent", "d1eiha_.ent-d2hcc__.ent", "d1eiha_.ent-d3il8__.ent", "d1eija_.ent-d1enwa_.ent", "d1eija_.ent-d1f4ia_.ent", "d1eija_.ent-d1ifya_.ent", "d1eija_.ent-d1oaia_.ent", "d1eika_.ent-d1i50f_.ent", "d1eit__.ent-d1emxa_.ent", "d1eit__.ent-d1g9pa_.ent", "d1eit__.ent-d1i25a_.ent", "d1eit__.ent-d1i26a_.ent", "d1eit__.ent-d1koza_.ent", "d1eit__.ent-d1kqha_.ent", "d1eit__.ent-d1lqra_.ent", "d1eit__.ent-d1lupa_.ent", "d1eit__.ent-d1nixa_.ent", "d1eit__.ent-d1niya_.ent", "d1eit__.ent-d1qk6a_.ent", "d1eit__.ent-d1qk7a_.ent", "d1eit__.ent-d1vtx__.ent", "d1eixa_.ent-d1geqa_.ent", "d1eixa_.ent-d1i4na_.ent", "d1eixa_.ent-d1jvna1.ent", "d1eixa_.ent-d1km3a_.ent", "d1eixa_.ent-d1kv8a_.ent", "d1eixa_.ent-d1nsj__.ent", "d1eixa_.ent-d1pii_1.ent", "d1eixa_.ent-d1pii_2.ent", "d1eixa_.ent-d1qopa_.ent", "d1eixa_.ent-d1rpxa_.ent", "d1eixa_.ent-d1thfd_.ent", "d1eiya1.ent-d1fpoa1.ent", "d1eiya1.ent-d1fxkc_.ent", "d1eiya1.ent-d1gh6a_.ent", "d1eiya1.ent-d1grj_1.ent", "d1eiya1.ent-d1hdj__.ent", "d1eiya1.ent-d1ivsa1.ent", "d1eiya1.ent-d1ix9a1.ent", "d1eiya1.ent-d1jj2u_.ent", "d1eiya1.ent-d1k4ta1.ent", "d1eiya1.ent-d1lrza1.ent", "d1eiya1.ent-d1seta1.ent", "d1ej0a_.ent-d1f3la_.ent", "d1ej0a_.ent-d1fp2a2.ent", "d1ej0a_.ent-d1g38a_.ent", "d1ej0a_.ent-d1g60a_.ent", "d1ej0a_.ent-d1hnna_.ent", "d1ej0a_.ent-d1i4wa_.ent", "d1ej0a_.ent-d1inla_.ent", "d1ej0a_.ent-d1jg1a_.ent", "d1ej0a_.ent-d1jqea_.ent", "d1ej0a_.ent-d1jsxa_.ent", "d1ej0a_.ent-d1khha_.ent", "d1ej0a_.ent-d1vid__.ent", "d1ej0a_.ent-d1xvaa_.ent", "d1ej0a_.ent-d2dpma_.ent", "d1ej0a_.ent-d3mag__.ent", "d1ej2a_.ent-d1f4la2.ent", "d1ej2a_.ent-d1f7ua2.ent", "d1ej2a_.ent-d1ffya3.ent", "d1ej2a_.ent-d1g8fa2.ent", "d1ej2a_.ent-d1gpma1.ent", "d1ej2a_.ent-d1gtra2.ent", "d1ej2a_.ent-d1h3fa1.ent", "d1ej2a_.ent-d1h3na3.ent", "d1ej2a_.ent-d1ihoa_.ent", "d1ej2a_.ent-d1ile_3.ent", "d1ej2a_.ent-d1iq0a2.ent", "d1ej2a_.ent-d1irxa2.ent", "d1ej2a_.ent-d1ivsa4.ent", "d1ej2a_.ent-d1j09a2.ent", "d1ej2a_.ent-d1jgta1.ent", "d1ej2a_.ent-d1jhda2.ent", "d1ej2a_.ent-d1jila_.ent", "d1ej2a_.ent-d1jmva_.ent", "d1ej2a_.ent-d1k4ma_.ent", "d1ej2a_.ent-d1k92a1.ent", "d1ej2a_.ent-d1kama_.ent", "d1ej2a_.ent-d1kqna_.ent", "d1ej2a_.ent-d1kqpa_.ent", "d1ej2a_.ent-d1li5a2.ent", "d1ej2a_.ent-d1mjha_.ent", "d1ej2a_.ent-d1n3la_.ent", "d1ej2a_.ent-d1o97c_.ent", "d1ej2a_.ent-d1o97d1.ent", "d1ej2a_.ent-d1qjca_.ent", "d1ej2a_.ent-d1sur__.ent", "d1ej8a_.ent-d1dqia_.ent", "d1ej8a_.ent-d1eaja_.ent", "d1ej8a_.ent-d1eso__.ent", "d1ej8a_.ent-d1grwa_.ent", "d1ej8a_.ent-d1j0ha1.ent", "d1ej8a_.ent-d1jmxa4.ent", "d1ej8a_.ent-d1kgce2.ent", "d1ej8a_.ent-d1kmta_.ent", "d1ej8a_.ent-d1kyfa1.ent", "d1ej8a_.ent-d1l9na1.ent", "d1ej8a_.ent-d1lmia_.ent", "d1ej8a_.ent-d1m1xa2.ent", "d1ej8a_.ent-d1m1xb1.ent", "d1ej8a_.ent-d1nepa_.ent", "d1ej8a_.ent-d1o75a1.ent", "d1ej8a_.ent-d1soxa1.ent", "d1ej8a_.ent-d1xsoa_.ent", "d1ej8a_.ent-d1yaia_.ent", "d1ejba_.ent-d1hqka_.ent", "d1ejba_.ent-d1kz1a_.ent", "d1ejba_.ent-d1rvv1_.ent", "d1ejea_.ent-d1flma_.ent", "d1ejea_.ent-d1i0ra_.ent", "d1ejea_.ent-d1nrga_.ent", "d1ejfa_.ent-d1gmea_.ent", "d1ejfa_.ent-d1shsa_.ent", "d1ejrb_.ent-d4ubpb_.ent", "d1ek4a1.ent-d1ek4a2.ent", "d1ek4a1.ent-d1hnja1.ent", "d1ek4a1.ent-d1hnja2.ent", "d1ek4a1.ent-d1hzpa1.ent", "d1ek4a1.ent-d1hzpa2.ent", "d1ek4a1.ent-d1kas_1.ent", "d1ek4a1.ent-d1m3ka1.ent", "d1ek4a1.ent-d1m3ka2.ent", "d1ek4a1.ent-d1mzja1.ent", "d1ek4a1.ent-d1mzja2.ent", "d1ek4a2.ent-d1hnja1.ent", "d1ek4a2.ent-d1hnja2.ent", "d1ek4a2.ent-d1hzpa1.ent", "d1ek4a2.ent-d1hzpa2.ent", "d1ek4a2.ent-d1kas_1.ent", "d1ek4a2.ent-d1m3ka1.ent", "d1ek4a2.ent-d1m3ka2.ent", "d1ek4a2.ent-d1mzja1.ent", "d1ek4a2.ent-d1mzja2.ent", "d1ek6a_.ent-d1bdb__.ent", "d1ek6a_.ent-d1bgva1.ent", "d1ek6a_.ent-d1e6ua_.ent", "d1ek6a_.ent-d1e7wa_.ent", "d1ek6a_.ent-d1eno__.ent", "d1ek6a_.ent-d1eny__.ent", "d1ek6a_.ent-d1fds__.ent", "d1ek6a_.ent-d1g0oa_.ent", "d1ek6a_.ent-d1gcoa_.ent", "d1ek6a_.ent-d1h5qa_.ent", "d1ek6a_.ent-d1hwxa1.ent", "d1ek6a_.ent-d1ja9a_.ent", "d1ek6a_.ent-d1k6xa_.ent", "d1ek6a_.ent-d1kepa_.ent", "d1ek6a_.ent-d1llqa1.ent", "d1ek6a_.ent-d1n2sa_.ent", "d1ek6a_.ent-d1n5da_.ent", "d1ek6a_.ent-d1n7ha_.ent", "d1ek6a_.ent-d1oaa__.ent", "d1ek6a_.ent-d1qsga_.ent", "d1ek6a_.ent-d2ae2a_.ent", "d1ek8a_.ent-d1f7ua3.ent", "d1ek8a_.ent-d1ge9a_.ent", "d1ek8a_.ent-d1iq0a3.ent", "d1ek8a_.ent-d1qf6a3.ent", "d1ekbb_.ent-d1azza_.ent", "d1ekbb_.ent-d1bio__.ent", "d1ekbb_.ent-d1bqya_.ent", "d1ekbb_.ent-d1cgha_.ent", "d1ekbb_.ent-d1fjsa_.ent", "d1ekbb_.ent-d1gdna_.ent", "d1ekbb_.ent-d1gpza1.ent", "d1ekbb_.ent-d1hj9a_.ent", "d1ekbb_.ent-d1rfna_.ent", "d1ekbb_.ent-d2hlca_.ent", "d1ekfa_.ent-d1et0a_.ent", "d1ekfa_.ent-d1i1ka_.ent", "d1ekja_.ent-d1g5ca_.ent", "d1ekja_.ent-d1i6pa_.ent", "d1ekra_.ent-d1dqaa1.ent", "d1ekra_.ent-d1gpja3.ent", "d1ekra_.ent-d1h72c2.ent", "d1ekra_.ent-d1qd1a2.ent", "d1ekra_.ent-d1regx_.ent", "d1ekxa2.ent-d1js1x1.ent", "d1ekxa2.ent-d1js1x2.ent", "d1ekxa2.ent-d1ml4a1.ent", "d1ekxa2.ent-d1ml4a2.ent", "d1ekxa2.ent-d1otha1.ent", "d1ekxa2.ent-d1otha2.ent", "d1el0a_.ent-d1f2la_.ent", "d1el0a_.ent-d1g2ta_.ent", "d1el0a_.ent-d1j9oa_.ent", "d1el0a_.ent-d1m8aa_.ent", "d1el0a_.ent-d1qg7a_.ent", "d1el0a_.ent-d1tvxa_.ent", "d1el0a_.ent-d2hcc__.ent", "d1el0a_.ent-d3il8__.ent", "d1el4a_.ent-d1alva_.ent", "d1el4a_.ent-d1auib_.ent", "d1el4a_.ent-d1df0a1.ent", "d1el4a_.ent-d1dgua_.ent", "d1el4a_.ent-d1eg3a1.ent", "d1el4a_.ent-d1exra_.ent", "d1el4a_.ent-d1fi6a_.ent", "d1el4a_.ent-d1g8ia_.ent", "d1el4a_.ent-d1ggwa_.ent", "d1el4a_.ent-d1h8ba_.ent", "d1el4a_.ent-d1hqva_.ent", "d1el4a_.ent-d1iioa_.ent", "d1el4a_.ent-d1j7qa_.ent", "d1el4a_.ent-d1jbaa_.ent", "d1el4a_.ent-d1jfja_.ent", "d1el4a_.ent-d1k94a_.ent", "d1el4a_.ent-d1m31a_.ent", "d1el4a_.ent-d1m45a_.ent", "d1el4a_.ent-d1ncx__.ent", "d1el4a_.ent-d1psra_.ent", "d1el4a_.ent-d1qasa1.ent", "d1el4a_.ent-d1rec__.ent", "d1el4a_.ent-d1rro__.ent", "d1el4a_.ent-d1sra__.ent", "d1el4a_.ent-d1wdcb_.ent", "d1el4a_.ent-d1wdcc_.ent", "d1el4a_.ent-d2cbla1.ent", "d1el4a_.ent-d2pvba_.ent", "d1el4a_.ent-d2sas__.ent", "d1el4a_.ent-d2scpa_.ent", "d1el4a_.ent-d5pal__.ent", "d1elka_.ent-d1eyha_.ent", "d1elka_.ent-d1hs6a1.ent", "d1elka_.ent-d1n4ka1.ent", "d1elra_.ent-d1elwa_.ent", "d1elra_.ent-d1fcha_.ent", "d1elra_.ent-d1hh8a_.ent", "d1elra_.ent-d1hz4a_.ent", "d1elra_.ent-d1ihga1.ent", "d1elra_.ent-d1iyga_.ent", "d1elra_.ent-d1kt1a1.ent", "d1elra_.ent-d1qqea_.ent", "d1elua_.ent-d1js3a_.ent", "d1elua_.ent-d1kl1a_.ent", "d1elua_.ent-d1lc5a_.ent", "d1elua_.ent-d1qj5a_.ent", "d1elva1.ent-d1azza_.ent", "d1elva1.ent-d1bio__.ent", "d1elva1.ent-d1bqya_.ent", "d1elva1.ent-d1cgha_.ent", "d1elva1.ent-d1ekbb_.ent", "d1elva1.ent-d1fjsa_.ent", "d1elva1.ent-d1gdna_.ent", "d1elva1.ent-d1gpza1.ent", "d1elva1.ent-d1gvza_.ent", "d1elva1.ent-d1hj9a_.ent", "d1elva1.ent-d1rfna_.ent", "d1elva1.ent-d2hlca_.ent", "d1elva2.ent-d1g40a1.ent", "d1elva2.ent-d1g40a2.ent", "d1elva2.ent-d1g40a3.ent", "d1elva2.ent-d1g40a4.ent", "d1elva2.ent-d1gkga2.ent", "d1elva2.ent-d1gkna1.ent", "d1elva2.ent-d1gkna2.ent", "d1elva2.ent-d1gpza2.ent", "d1elva2.ent-d1gpza3.ent", "d1elva2.ent-d1hcc__.ent", "d1elva2.ent-d1hfi__.ent", "d1elva2.ent-d1ly2a1.ent", "d1elva2.ent-d1ly2a2.ent", "d1elva2.ent-d1quba1.ent", "d1elva2.ent-d1quba2.ent", "d1elva2.ent-d1quba3.ent", "d1elva2.ent-d1quba4.ent", "d1elva2.ent-d1quba5.ent", "d1elwa_.ent-d1fcha_.ent", "d1elwa_.ent-d1hh8a_.ent", "d1elwa_.ent-d1hz4a_.ent", "d1elwa_.ent-d1ihga1.ent", "d1elwa_.ent-d1iyga_.ent", "d1elwa_.ent-d1kt1a1.ent", "d1elwa_.ent-d1qqea_.ent", "d1em9a_.ent-d2eiaa2.ent", "d1emo_1.ent-d1cvua2.ent", "d1emo_1.ent-d1hz8a1.ent", "d1emo_1.ent-d1hz8a2.ent", "d1emo_1.ent-d1jl9a_.ent", "d1emo_1.ent-d1l3ya_.ent", "d1emo_1.ent-d1m1xb5.ent", "d1emo_1.ent-d1tpg_1.ent", "d1emsa1.ent-d1guqa1.ent", "d1emsa1.ent-d1guqa2.ent", "d1emsa1.ent-d1kpf__.ent", "d1emsa2.ent-d1erza_.ent", "d1emsa2.ent-d1f89a_.ent", "d1emva_.ent-d1l0ia_.ent", "d1emvb_.ent-d1ql0a_.ent", "d1emxa_.ent-d1g9pa_.ent", "d1emxa_.ent-d1i25a_.ent", "d1emxa_.ent-d1i26a_.ent", "d1emxa_.ent-d1koza_.ent", "d1emxa_.ent-d1kqha_.ent", "d1emxa_.ent-d1lqra_.ent", "d1emxa_.ent-d1lupa_.ent", "d1emxa_.ent-d1nixa_.ent", "d1emxa_.ent-d1niya_.ent", "d1emxa_.ent-d1qk6a_.ent", "d1emxa_.ent-d1qk7a_.ent", "d1emxa_.ent-d1vtx__.ent", "d1en2a2.ent-d1hev__.ent", "d1en2a2.ent-d1mmc__.ent", "d1en2a2.ent-d9wgaa2.ent", "d1enfa1.ent-d1esfa1.ent", "d1enfa1.ent-d1et9a1.ent", "d1enfa1.ent-d1eu3a1.ent", "d1enfa1.ent-d1fnua1.ent", "d1enfa1.ent-d1m4va1.ent", "d1enfa1.ent-d1prtb1.ent", "d1enfa1.ent-d1prtd_.ent", "d1enfa1.ent-d1prtf_.ent", "d1enfa1.ent-d1tiid_.ent", "d1enfa1.ent-d3chbd_.ent", "d1enfa1.ent-d3seb_1.ent", "d1enfa1.ent-d3tss_1.ent", "d1enfa2.ent-d1esfa2.ent", "d1enfa2.ent-d1et9a2.ent", "d1enfa2.ent-d1eu3a2.ent", "d1enfa2.ent-d1m4va2.ent", "d1enfa2.ent-d3seb_2.ent", "d1enfa2.ent-d3tss_2.ent", "d1eno__.ent-d1bdb__.ent", "d1eno__.ent-d1bgva1.ent", "d1eno__.ent-d1e7wa_.ent", "d1eno__.ent-d1eny__.ent", "d1eno__.ent-d1fds__.ent", "d1eno__.ent-d1g0oa_.ent", "d1eno__.ent-d1gcoa_.ent", "d1eno__.ent-d1h5qa_.ent", "d1eno__.ent-d1hwxa1.ent", "d1eno__.ent-d1ja9a_.ent", "d1eno__.ent-d1n5da_.ent", "d1eno__.ent-d1oaa__.ent", "d1eno__.ent-d1qsga_.ent", "d1eno__.ent-d2ae2a_.ent", "d1enwa_.ent-d1f4ia_.ent", "d1enwa_.ent-d1ifya_.ent", "d1enwa_.ent-d1oaia_.ent", "d1eny__.ent-d1bdb__.ent", "d1eny__.ent-d1bgva1.ent", "d1eny__.ent-d1e7wa_.ent", "d1eny__.ent-d1gcoa_.ent", "d1eny__.ent-d1h5qa_.ent", "d1eny__.ent-d1ja9a_.ent", "d1eny__.ent-d1oaa__.ent", "d1eny__.ent-d1qsga_.ent", "d1eny__.ent-d2ae2a_.ent", "d1eo0a_.ent-d2cbla2.ent", "d1eo9a_.ent-d1eo9b_.ent", "d1eova1.ent-d1b3qa2.ent", "d1eova1.ent-d1ewia_.ent", "d1eova1.ent-d1fgua1.ent", "d1eova1.ent-d1fgua2.ent", "d1eova1.ent-d1fjgl_.ent", "d1eova1.ent-d1i50h_.ent", "d1eova1.ent-d1iyjb3.ent", "d1eova1.ent-d1jb3a_.ent", "d1eova1.ent-d1jb7a2.ent", "d1eova1.ent-d1jjcb3.ent", "d1eova1.ent-d1k28a1.ent", "d1eova1.ent-d1quqa_.ent", "d1eova1.ent-d1quqb_.ent", "d1eova1.ent-d3seb_1.ent", "d1eova2.ent-d1g51a3.ent", "d1eova2.ent-d1h4vb2.ent", "d1eova2.ent-d1hc7a2.ent", "d1eova2.ent-d1jjca_.ent", "d1eova2.ent-d1jjcb5.ent", "d1eova2.ent-d1kmma2.ent", "d1eova2.ent-d1qe0a2.ent", "d1eova2.ent-d1qf6a4.ent", "d1eova2.ent-d1seta2.ent", "d1ep0a_.ent-d1eula1.ent", "d1ep0a_.ent-d1fi2a_.ent", "d1ep0a_.ent-d1ft9a2.ent", "d1ep0a_.ent-d1fxza1.ent", "d1ep0a_.ent-d1fxza2.ent", "d1ep0a_.ent-d1gp6a_.ent", "d1ep0a_.ent-d1gy9a_.ent", "d1ep0a_.ent-d1h2ka_.ent", "d1ep0a_.ent-d1hw5a2.ent", "d1ep0a_.ent-d1ig0a1.ent", "d1ep0a_.ent-d1jr7a_.ent", "d1ep0a_.ent-d1juha_.ent", "d1ep0a_.ent-d1lrha_.ent", "d1ep0a_.ent-d1m4oa_.ent", "d1ep0a_.ent-d1pmi__.ent", "d1ep0a_.ent-d1wapa_.ent", "d1ep0a_.ent-d2arca_.ent", "d1ep0a_.ent-d2phla1.ent", "d1ep0a_.ent-d2phla2.ent", "d1ep3a_.ent-d1gox__.ent", "d1ep3a_.ent-d1gtea2.ent", "d1ep3a_.ent-d1gvoa_.ent", "d1ep3a_.ent-d1huva_.ent", "d1ep3a_.ent-d1icpa_.ent", "d1ep3a_.ent-d1kbia1.ent", "d1ep3a_.ent-d1llwa2.ent", "d1ep3a_.ent-d1o94a1.ent", "d1ep3a_.ent-d1oyb__.ent", "d1ep3a_.ent-d2dora_.ent", "d1ep3b1.ent-d1f20a1.ent", "d1ep3b1.ent-d1f60a1.ent", "d1ep3b1.ent-d1fdr_1.ent", "d1ep3b1.ent-d1fnc_1.ent", "d1ep3b1.ent-d1fuia1.ent", "d1ep3b1.ent-d1g7sa1.ent", "d1ep3b1.ent-d1g7sa2.ent", "d1ep3b1.ent-d1i7pa1.ent", "d1ep3b1.ent-d1i8da1.ent", "d1ep3b1.ent-d1i8da2.ent", "d1ep3b1.ent-d1ja1a1.ent", "d1ep3b1.ent-d1jb9a1.ent", "d1ep3b1.ent-d1jj2b_.ent", "d1ep3b1.ent-d1kk1a1.ent", "d1ep3b1.ent-d1krha1.ent", "d1ep3b1.ent-d1kzla1.ent", "d1ep3b1.ent-d1kzla2.ent", "d1ep3b1.ent-d1n08a_.ent", "d1ep3b1.ent-d1n0ua1.ent", "d1ep3b1.ent-d1qfja1.ent", "d1ep3b1.ent-d1que_1.ent", "d1ep3b1.ent-d2cnd_1.ent", "d1ep3b1.ent-d2pia_1.ent", "d1ep3b2.ent-d1f20a2.ent", "d1ep3b2.ent-d1fdr_2.ent", "d1ep3b2.ent-d1gvha3.ent", "d1ep3b2.ent-d1i7pa2.ent", "d1ep3b2.ent-d1ja1a3.ent", "d1ep3b2.ent-d1jb9a2.ent", "d1ep3b2.ent-d1krha2.ent", "d1ep3b2.ent-d1qfja2.ent", "d1ep3b2.ent-d1que_2.ent", "d1ep3b2.ent-d2cnd_2.ent", "d1ep3b2.ent-d2pia_2.ent", "d1ep7a_.ent-d1a8l_2.ent", "d1ep7a_.ent-d1bjx__.ent", "d1ep7a_.ent-d1erv__.ent", "d1ep7a_.ent-d1f9ma_.ent", "d1ep7a_.ent-d1fb6a_.ent", "d1ep7a_.ent-d1gh2a_.ent", "d1ep7a_.ent-d1kte__.ent", "d1ep7a_.ent-d1quwa_.ent", "d1ep7a_.ent-d1thx__.ent", "d1ep7a_.ent-d2trxa_.ent", "d1epwa1.ent-d1dhkb_.ent", "d1epwa1.ent-d1dyka1.ent", "d1epwa1.ent-d1dyka2.ent", "d1epwa1.ent-d1h30a1.ent", "d1epwa1.ent-d1h30a2.ent", "d1epwa1.ent-d1kit_1.ent", "d1epwa1.ent-d1kit_2.ent", "d1epwa1.ent-d1saca_.ent", "d1epwa1.ent-d1xnb__.ent", "d1epwa1.ent-d2ayh__.ent", "d1epwa1.ent-d2sli_1.ent", "d1epwa1.ent-d3btaa1.ent", "d1epwa2.ent-d1eyla_.ent", "d1epwa2.ent-d1wba__.ent", "d1epwa2.ent-d3btaa2.ent", "d1epwa3.ent-d1ezm__.ent", "d1epwa3.ent-d1g12a_.ent", "d1epwa3.ent-d1gkda_.ent", "d1epwa3.ent-d1gqia2.ent", "d1epwa3.ent-d1hs6a3.ent", "d1epwa3.ent-d1i1ip_.ent", "d1epwa3.ent-d1j7na1.ent", "d1epwa3.ent-d1j7na2.ent", "d1epwa3.ent-d1jaka2.ent", "d1epwa3.ent-d1jk3a_.ent", "d1epwa3.ent-d1k7ia2.ent", "d1epwa3.ent-d1k9xa_.ent", "d1epwa3.ent-d1kapp2.ent", "d1epwa3.ent-d1keia_.ent", "d1epwa3.ent-d1kufa_.ent", "d1epwa3.ent-d1lml__.ent", "d1epwa3.ent-d1qba_4.ent", "d1epwa3.ent-d3btaa3.ent", "d1epxa_.ent-d1euaa_.ent", "d1epxa_.ent-d1f74a_.ent", "d1epxa_.ent-d1gvfa_.ent", "d1epxa_.ent-d1gzga_.ent", "d1epxa_.ent-d1h7na_.ent", "d1epxa_.ent-d1hfba_.ent", "d1epxa_.ent-d1i2oa_.ent", "d1epxa_.ent-d1jcla_.ent", "d1epxa_.ent-d1jcxa_.ent", "d1epxa_.ent-d1l6wa_.ent", "d1epxa_.ent-d1mzha_.ent", "d1epxa_.ent-d1nal1_.ent", "d1epxa_.ent-d1o0ya_.ent", "d1epxa_.ent-d1qfea_.ent", "d1eq3a_.ent-d1fd9a_.ent", "d1eq3a_.ent-d1grj_2.ent", "d1eq3a_.ent-d1hxva_.ent", "d1eq3a_.ent-d1j6ya_.ent", "d1eq3a_.ent-d1jvwa_.ent", "d1eq3a_.ent-d1kt1a3.ent", "d1eq3a_.ent-d1m5ya2.ent", "d1eq3a_.ent-d1m5ya3.ent", "d1eq3a_.ent-d1n1aa_.ent", "d1eq3a_.ent-d1pbk__.ent", "d1eq3a_.ent-d1pina2.ent", "d1eqfa1.ent-d1eqfa2.ent", "d1eqfa1.ent-d1f68a_.ent", "d1eqfa1.ent-d1jspb_.ent", "d1eqfa2.ent-d1f68a_.ent", "d1eqfa2.ent-d1jspb_.ent", "d1eqja2.ent-d1ew2a_.ent", "d1eqja2.ent-d1k7ha_.ent", "d1eqka_.ent-d1g96a_.ent", "d1eqka_.ent-d1kwia_.ent", "d1eqka_.ent-d1mola_.ent", "d1eqka_.ent-d1stfi_.ent", "d1eqoa_.ent-d1b3ta_.ent", "d1eqoa_.ent-d1dj0a2.ent", "d1eqoa_.ent-d1dqaa1.ent", "d1eqoa_.ent-d1ekra_.ent", "d1eqoa_.ent-d1f3va_.ent", "d1eqoa_.ent-d1ftra1.ent", "d1eqoa_.ent-d1ftra2.ent", "d1eqoa_.ent-d1gpja3.ent", "d1eqoa_.ent-d1h72c2.ent", "d1eqoa_.ent-d1hlwa_.ent", "d1eqoa_.ent-d1jnrb_.ent", "d1eqoa_.ent-d1qd1a2.ent", "d1eqoa_.ent-d1regx_.ent", "d1erd__.ent-d1erp__.ent", "d1erd__.ent-d1hd6a_.ent", "d1erd__.ent-d2erl__.ent", "d1erja_.ent-d1gxra_.ent", "d1erja_.ent-d1k8kc_.ent", "d1erja_.ent-d1tbga_.ent", "d1erp__.ent-d1hd6a_.ent", "d1erp__.ent-d2erl__.ent", "d1erv__.ent-d1fb6a_.ent", "d1erv__.ent-d1kte__.ent", "d1erv__.ent-d1quwa_.ent", "d1erza_.ent-d1f89a_.ent", "d1es5a_.ent-d1g6aa_.ent", "d1es5a_.ent-d1ghpa_.ent", "d1es5a_.ent-d1iyoa_.ent", "d1es5a_.ent-d1l0ga_.ent", "d1es5a_.ent-d1m40a_.ent", "d1es5a_.ent-d1mfoa_.ent", "d1es5a_.ent-d1mwxa3.ent", "d1es5a_.ent-d1nj4a2.ent", "d1es5a_.ent-d1qmea4.ent", "d1es5a_.ent-d4blma_.ent", "d1es7b_.ent-d1f94a_.ent", "d1es7b_.ent-d1fas__.ent", "d1es7b_.ent-d1hc9a_.ent", "d1es7b_.ent-d1jgka_.ent", "d1es7b_.ent-d1kbaa_.ent", "d1es7b_.ent-d1m9za_.ent", "d1es7b_.ent-d1tfs__.ent", "d1es7b_.ent-d1tgxa_.ent", "d1es7b_.ent-d3ebx__.ent", "d1es9a_.ent-d1cex__.ent", "d1es9a_.ent-d1cf9a1.ent", "d1es9a_.ent-d1e5da1.ent", "d1es9a_.ent-d1esc__.ent", "d1es9a_.ent-d1euca2.ent", "d1es9a_.ent-d1f2va_.ent", "d1es9a_.ent-d1f4pa_.ent", "d1es9a_.ent-d1f8ya_.ent", "d1es9a_.ent-d1flca2.ent", "d1es9a_.ent-d1fuea_.ent", "d1es9a_.ent-d1g66a_.ent", "d1es9a_.ent-d1h05a_.ent", "d1es9a_.ent-d1k7ca_.ent", "d1es9a_.ent-d1kwga3.ent", "d1es9a_.ent-d1l7da2.ent", "d1es9a_.ent-d1qo0d_.ent", "d1es9a_.ent-d2naca2.ent", "d1es9a_.ent-d7reqb2.ent", "d1esc__.ent-d1b3ra2.ent", "d1esc__.ent-d1cex__.ent", "d1esc__.ent-d1cf9a1.ent", "d1esc__.ent-d1d4aa_.ent", "d1esc__.ent-d1e5da1.ent", "d1esc__.ent-d1es9a_.ent", "d1esc__.ent-d1euca2.ent", "d1esc__.ent-d1f2va_.ent", "d1esc__.ent-d1f4pa_.ent", "d1esc__.ent-d1f8ya_.ent", "d1esc__.ent-d1fjgb_.ent", "d1esc__.ent-d1flca2.ent", "d1esc__.ent-d1fuea_.ent", "d1esc__.ent-d1fyea_.ent", "d1esc__.ent-d1g66a_.ent", "d1esc__.ent-d1h05a_.ent", "d1esc__.ent-d1iexa2.ent", "d1esc__.ent-d1k7ca_.ent", "d1esc__.ent-d1kwga3.ent", "d1esc__.ent-d1l7da2.ent", "d1esc__.ent-d1l9xa_.ent", "d1esc__.ent-d1qo0d_.ent", "d1esc__.ent-d2naca2.ent", "d1esc__.ent-d7reqb2.ent", "d1esfa1.ent-d1et9a1.ent", "d1esfa1.ent-d1eu3a1.ent", "d1esfa1.ent-d1fnua1.ent", "d1esfa1.ent-d1m4va1.ent", "d1esfa1.ent-d1prtb1.ent", "d1esfa1.ent-d1prtd_.ent", "d1esfa1.ent-d1prtf_.ent", "d1esfa1.ent-d1tiid_.ent", "d1esfa1.ent-d3chbd_.ent", "d1esfa1.ent-d3seb_1.ent", "d1esfa1.ent-d3tss_1.ent", "d1esfa2.ent-d1et9a2.ent", "d1esfa2.ent-d1eu3a2.ent", "d1esfa2.ent-d1m4va2.ent", "d1esfa2.ent-d3seb_2.ent", "d1esfa2.ent-d3tss_2.ent", "d1eso__.ent-d1xsoa_.ent", "d1eso__.ent-d1yaia_.ent", "d1eswa_.ent-d1b9za2.ent", "d1eswa_.ent-d1bf2_3.ent", "d1eswa_.ent-d1cbg__.ent", "d1eswa_.ent-d1ccwb_.ent", "d1eswa_.ent-d1cz1a_.ent", "d1eswa_.ent-d1d3ga_.ent", "d1eswa_.ent-d1e43a2.ent", "d1eswa_.ent-d1e4ia_.ent", "d1eswa_.ent-d1e4mm_.ent", "d1eswa_.ent-d1edg__.ent", "d1eswa_.ent-d1eh9a3.ent", "d1eswa_.ent-d1f8ma_.ent", "d1eswa_.ent-d1gvoa_.ent", "d1eswa_.ent-d1gw1a_.ent", "d1eswa_.ent-d1hxja_.ent", "d1eswa_.ent-d1iexa1.ent", "d1eswa_.ent-d1itua_.ent", "d1eswa_.ent-d1j0ha3.ent", "d1eswa_.ent-d1j5sa_.ent", "d1eswa_.ent-d1ji1a3.ent", "d1eswa_.ent-d1k4ga_.ent", "d1eswa_.ent-d1kbla1.ent", "d1eswa_.ent-d1kwga2.ent", "d1eswa_.ent-d1lwha2.ent", "d1eswa_.ent-d1m7ja3.ent", "d1eswa_.ent-d1muwa_.ent", "d1eswa_.ent-d1ntha_.ent", "d1eswa_.ent-d1pama4.ent", "d1eswa_.ent-d1qba_3.ent", "d1eswa_.ent-d1qhoa4.ent", "d1eswa_.ent-d1qvba_.ent", "d1eswa_.ent-d1uok_2.ent", "d1eswa_.ent-d7taa_2.ent", "d1et0a_.ent-d1i1ka_.ent", "d1et9a1.ent-d1eu3a1.ent", "d1et9a1.ent-d1fnua1.ent", "d1et9a1.ent-d1m4va1.ent", "d1et9a1.ent-d1prtb1.ent", "d1et9a1.ent-d1prtd_.ent", "d1et9a1.ent-d1prtf_.ent", "d1et9a1.ent-d1tiid_.ent", "d1et9a1.ent-d3chbd_.ent", "d1et9a1.ent-d3seb_1.ent", "d1et9a1.ent-d3tss_1.ent", "d1et9a2.ent-d1eu3a2.ent", "d1et9a2.ent-d1m4va2.ent", "d1et9a2.ent-d3seb_2.ent", "d1et9a2.ent-d3tss_2.ent", "d1etea_.ent-d1evsa_.ent", "d1etea_.ent-d1f45b_.ent", "d1etea_.ent-d1f6fa_.ent", "d1etea_.ent-d1hula_.ent", "d1etea_.ent-d1huw__.ent", "d1etea_.ent-d1hzia_.ent", "d1etea_.ent-d1i1rb_.ent", "d1etea_.ent-d1jli__.ent", "d1etea_.ent-d1lki__.ent", "d1etea_.ent-d1lqsl_.ent", "d1etea_.ent-d1m47a_.ent", "d1etea_.ent-d1n1fa_.ent", "d1etea_.ent-d2gmfa_.ent", "d1etea_.ent-d2ilk__.ent", "d1etpa2.ent-d1kb0a1.ent", "d1eu1a1.ent-d1g8ka1.ent", "d1eu1a1.ent-d1h0ha1.ent", "d1eu1a1.ent-d1kqfa1.ent", "d1eu1a1.ent-d1n10a2.ent", "d1eu1a1.ent-d1tmo_1.ent", "d1eu1a1.ent-d2napa1.ent", "d1eu3a1.ent-d1fnua1.ent", "d1eu3a1.ent-d1m4va1.ent", "d1eu3a1.ent-d1prtb1.ent", "d1eu3a1.ent-d1prtd_.ent", "d1eu3a1.ent-d1prtf_.ent", "d1eu3a1.ent-d1tiid_.ent", "d1eu3a1.ent-d3chbd_.ent", "d1eu3a1.ent-d3seb_1.ent", "d1eu3a1.ent-d3tss_1.ent", "d1eu3a2.ent-d1m4va2.ent", "d1eu3a2.ent-d3seb_2.ent", "d1eu3a2.ent-d3tss_2.ent", "d1eu8a_.ent-d1h76a2.ent", "d1eu8a_.ent-d1i6aa_.ent", "d1eu8a_.ent-d1ii5a_.ent", "d1eu8a_.ent-d1ixh__.ent", "d1eu8a_.ent-d1jeta_.ent", "d1eu8a_.ent-d1kwha_.ent", "d1eu8a_.ent-d1lst__.ent", "d1eu8a_.ent-d1m5ea_.ent", "d1eu8a_.ent-d1mrp__.ent", "d1eu8a_.ent-d1nh8a1.ent", "d1eu8a_.ent-d1pda_1.ent", "d1eu8a_.ent-d1pot__.ent", "d1eu8a_.ent-d1sbp__.ent", "d1eu8a_.ent-d1wdna_.ent", "d1eu8a_.ent-d3mbp__.ent", "d1eu8a_.ent-d3thia_.ent", "d1euaa_.ent-d1f74a_.ent", "d1euaa_.ent-d1gvfa_.ent", "d1euaa_.ent-d1gzga_.ent", "d1euaa_.ent-d1h7na_.ent", "d1euaa_.ent-d1hfba_.ent", "d1euaa_.ent-d1i2oa_.ent", "d1euaa_.ent-d1jcla_.ent", "d1euaa_.ent-d1jcxa_.ent", "d1euaa_.ent-d1l6wa_.ent", "d1euaa_.ent-d1mzha_.ent", "d1euaa_.ent-d1nal1_.ent", "d1euaa_.ent-d1o0ya_.ent", "d1euaa_.ent-d1qfea_.ent", "d1euca2.ent-d1cf9a1.ent", "d1euca2.ent-d1e5da1.ent", "d1euca2.ent-d1f4pa_.ent", "d1euca2.ent-d1f8ya_.ent", "d1euca2.ent-d1fuea_.ent", "d1euca2.ent-d1h05a_.ent", "d1euca2.ent-d7reqb2.ent", "d1eucb2.ent-d1fvia2.ent", "d1eucb2.ent-d1gsa_2.ent", "d1eucb2.ent-d1gsoa3.ent", "d1eucb2.ent-d1iow_2.ent", "d1eucb2.ent-d1jkjb2.ent", "d1eucb2.ent-d1kbla3.ent", "d1eucb2.ent-d1kjqa3.ent", "d1eucb2.ent-d1m0wa2.ent", "d1eucb2.ent-d2hgsa4.ent", "d1euha_.ent-d1ez0a_.ent", "d1euha_.ent-d1ky8a_.ent", "d1eula1.ent-d1fi2a_.ent", "d1eula1.ent-d1ft9a2.ent", "d1eula1.ent-d1fxza1.ent", "d1eula1.ent-d1gp6a_.ent", "d1eula1.ent-d1gy9a_.ent", "d1eula1.ent-d1h2ka_.ent", "d1eula1.ent-d1hw5a2.ent", "d1eula1.ent-d1ig0a1.ent", "d1eula1.ent-d1jr7a_.ent", "d1eula1.ent-d1juha_.ent", "d1eula1.ent-d1lrha_.ent", "d1eula1.ent-d1m4oa_.ent", "d1eula1.ent-d1pmi__.ent", "d1eula1.ent-d1wapa_.ent", "d1eula1.ent-d2arca_.ent", "d1eula2.ent-d1feza_.ent", "d1eula2.ent-d1k1ea_.ent", "d1eula2.ent-d1l6ra_.ent", "d1eula2.ent-d1mh9a_.ent", "d1eula2.ent-d1qq5a_.ent", "d1eula2.ent-d1zrn__.ent", "d1euma_.ent-d1h0oa_.ent", "d1euma_.ent-d1jgca_.ent", "d1euma_.ent-d1ji4a_.ent", "d1euma_.ent-d1jiga_.ent", "d1euma_.ent-d1jk0b_.ent", "d1euma_.ent-d1jkva_.ent", "d1euma_.ent-d1jqca_.ent", "d1euma_.ent-d1kgna_.ent", "d1euma_.ent-d1lkoa1.ent", "d1euma_.ent-d1mtyb_.ent", "d1euma_.ent-d1mtyd_.ent", "d1euma_.ent-d1qgha_.ent", "d1euma_.ent-d1rcd__.ent", "d1euoa_.ent-d1ew3a_.ent", "d1euoa_.ent-d1ftpa_.ent", "d1euoa_.ent-d1g85a_.ent", "d1euoa_.ent-d1ggla_.ent", "d1euoa_.ent-d1gkab_.ent", "d1euoa_.ent-d1hms__.ent", "d1euoa_.ent-d1i4ua_.ent", "d1euoa_.ent-d1ifc__.ent", "d1euoa_.ent-d1jv4a_.ent", "d1euoa_.ent-d1koia_.ent", "d1euoa_.ent-d1kqwa_.ent", "d1euoa_.ent-d1lf7a_.ent", "d1euoa_.ent-d1o1va_.ent", "d1euoa_.ent-d1qfta_.ent", "d1euoa_.ent-d1qqsa_.ent", "d1eur__.ent-d1f8ea_.ent", "d1eur__.ent-d1kit_3.ent", "d1eur__.ent-d1n1ta2.ent", "d1eur__.ent-d1nsca_.ent", "d1eur__.ent-d2bat__.ent", "d1eur__.ent-d2sli_2.ent", "d1eur__.ent-d3sil__.ent", "d1eut_2.ent-d1gmma_.ent", "d1eut_2.ent-d1gu3a_.ent", "d1euva_.ent-d1f13a4.ent", "d1euva_.ent-d1fh0a_.ent", "d1euva_.ent-d1g0da4.ent", "d1euva_.ent-d1gmya_.ent", "d1euva_.ent-d1gx3a_.ent", "d1euva_.ent-d1iu4a_.ent", "d1euva_.ent-d1kxra_.ent", "d1euva_.ent-d1l9na4.ent", "d1euva_.ent-d1me4a_.ent", "d1euva_.ent-d1nbfa_.ent", "d1euva_.ent-d1ppn__.ent", "d1euva_.ent-d1qmya_.ent", "d1euva_.ent-d1uch__.ent", "d1euva_.ent-d2act__.ent", "d1euva_.ent-d2cb5a_.ent", "d1euva_.ent-d3gcb__.ent", "d1euva_.ent-d7pcka_.ent", "d1euvb_.ent-d1gg3a3.ent", "d1euvb_.ent-d1gnua_.ent", "d1euvb_.ent-d1h4ra3.ent", "d1euvb_.ent-d1h8ca_.ent", "d1euvb_.ent-d1i42a_.ent", "d1euvb_.ent-d1j8ca_.ent", "d1euvb_.ent-d1k8rb_.ent", "d1euvb_.ent-d1l7ya_.ent", "d1euvb_.ent-d1lfda_.ent", "d1euvb_.ent-d1lm8b_.ent", "d1euvb_.ent-d1m94a_.ent", "d1euvb_.ent-d1rlf__.ent", "d1euwa_.ent-d1f7da_.ent", "d1euwa_.ent-d1g8la1.ent", "d1euwa_.ent-d1h3ia2.ent", "d1euwa_.ent-d1hg7a_.ent", "d1euwa_.ent-d1mlva2.ent", "d1euwa_.ent-d1mq7a_.ent", "d1euwa_.ent-d1n3ja_.ent", "d1euwa_.ent-d1tul__.ent", "d1euwa_.ent-d4ubpb_.ent", "d1ev7a_.ent-d1f1za2.ent", "d1ev7a_.ent-d1fiua_.ent", "d1ev7a_.ent-d1gefa_.ent", "d1ev7a_.ent-d1hh1a_.ent", "d1ev7a_.ent-d1kc6a_.ent", "d1ev7a_.ent-d1knva_.ent", "d1ev7a_.ent-d1m0da_.ent", "d1ev7a_.ent-d1vsra_.ent", "d1ev7a_.ent-d2foka4.ent", "d1ev7a_.ent-d3pvia_.ent", "d1evha_.ent-d1faoa_.ent", "d1evha_.ent-d1fhoa_.ent", "d1evha_.ent-d1gg3a2.ent", "d1evha_.ent-d1h4ra2.ent", "d1evha_.ent-d1k5db_.ent", "d1evha_.ent-d1ki1b2.ent", "d1evha_.ent-d1mai__.ent", "d1evha_.ent-d1mixa2.ent", "d1evha_.ent-d1mkea1.ent", "d1evha_.ent-d1pls__.ent", "d1evha_.ent-d1qqga1.ent", "d1evha_.ent-d1qqga2.ent", "d1evha_.ent-d1shca_.ent", "d1evsa_.ent-d1f45b_.ent", "d1evsa_.ent-d1f6fa_.ent", "d1evsa_.ent-d1hula_.ent", "d1evsa_.ent-d1huw__.ent", "d1evsa_.ent-d1hzia_.ent", "d1evsa_.ent-d1i1rb_.ent", "d1evsa_.ent-d1jli__.ent", "d1evsa_.ent-d1lki__.ent", "d1evsa_.ent-d1lqsl_.ent", "d1evsa_.ent-d1m47a_.ent", "d1evsa_.ent-d1n1fa_.ent", "d1evsa_.ent-d2gmfa_.ent", "d1evsa_.ent-d2ilk__.ent", "d1ew0a_.ent-d1f5ma_.ent", "d1ew0a_.ent-d1gw5m2.ent", "d1ew0a_.ent-d1h3qa_.ent", "d1ew0a_.ent-d1h8ma_.ent", "d1ew0a_.ent-d1jnua_.ent", "d1ew0a_.ent-d1ll8a_.ent", "d1ew0a_.ent-d1lswa_.ent", "d1ew0a_.ent-d1mc0a1.ent", "d1ew0a_.ent-d1mkma2.ent", "d1ew0a_.ent-d1mzua_.ent", "d1ew0a_.ent-d1pne__.ent", "d1ew0a_.ent-d3pyp__.ent", "d1ew2a_.ent-d1k7ha_.ent", "d1ew3a_.ent-d1ftpa_.ent", "d1ew3a_.ent-d1g85a_.ent", "d1ew3a_.ent-d1ggla_.ent", "d1ew3a_.ent-d1gkab_.ent", "d1ew3a_.ent-d1hms__.ent", "d1ew3a_.ent-d1i4ua_.ent", "d1ew3a_.ent-d1ifc__.ent", "d1ew3a_.ent-d1jv4a_.ent", "d1ew3a_.ent-d1koia_.ent", "d1ew3a_.ent-d1kqwa_.ent", "d1ew3a_.ent-d1lf7a_.ent", "d1ew3a_.ent-d1o1va_.ent", "d1ew3a_.ent-d1qfta_.ent", "d1ew3a_.ent-d1qqsa_.ent", "d1ew6a_.ent-d1gtea1", "d1ew6a_.ent-d1gtea1.ent", "d1ew6a_.ent-d1gvha1", "d1ew6a_.ent-d1gvha1.ent", "d1ew6a_.ent-d1h97a_", "d1ew6a_.ent-d1h97a_.ent", "d1ew6a_.ent-d1irdb_", "d1ew6a_.ent-d1irdb_.ent", "d1ew6a_.ent-d1itha_", "d1ew6a_.ent-d1itha_.ent", "d1ew6a_.ent-d1qlab1", "d1ew6a_.ent-d1qlab1.ent", "d1ew6a_.ent-d2gdm__", "d1ew6a_.ent-d2gdm__.ent", "d1ewia_.ent-d1jjcb3.ent", "d1ewia_.ent-d1quqb_.ent", "d1ewka_.ent-d1gca__.ent", "d1ewka_.ent-d1jdpa_.ent", "d1ewka_.ent-d1jx6a_.ent", "d1ewka_.ent-d1jyea_.ent", "d1ewka_.ent-d1pea__.ent", "d1ewka_.ent-d1rpja_.ent", "d1ewka_.ent-d2dri__.ent", "d1ewka_.ent-d2liv__.ent", "d1ewka_.ent-d8abp__.ent", "d1ewsa_.ent-d1fd3a_.ent", "d1ewsa_.ent-d1ijva_.ent", "d1ewsa_.ent-d1kj6a_.ent", "d1ewsa_.ent-d1sh1__.ent", "d1ewsa_.ent-d2bds__.ent", "d1ex2a_.ent-d1h4vb1.ent", "d1ex2a_.ent-d1hc7a1.ent", "d1ex2a_.ent-d1nbwb_.ent", "d1ex2a_.ent-d1qe0a1.ent", "d1ex9a_.ent-d1fj2a_.ent", "d1ex9a_.ent-d1gkla_.ent", "d1ex9a_.ent-d1hlga_.ent", "d1ex9a_.ent-d1imja_.ent", "d1ex9a_.ent-d1ispa_.ent", "d1ex9a_.ent-d1jfra_.ent", "d1ex9a_.ent-d1ju3a2.ent", "d1ex9a_.ent-d1ku0a_.ent", "d1ex9a_.ent-d1l7aa_.ent", "d1ex9a_.ent-d1lzla_.ent", "d1ex9a_.ent-d1mnaa_.ent", "d1ex9a_.ent-d1n1ma2.ent", "d1ex9a_.ent-d1qj4a_.ent", "d1ex9a_.ent-d1qlwa_.ent", "d1ex9a_.ent-d1qo7a_.ent", "d1ex9a_.ent-d1tca__.ent", "d1ex9a_.ent-d1thta_.ent", "d1ex9a_.ent-d3tgl__.ent", "d1exba_.ent-d1gvea_.ent", "d1exba_.ent-d1hqta_.ent", "d1exba_.ent-d1hw6a_.ent", "d1exba_.ent-d1j96a_.ent", "d1exba_.ent-d1jeza_.ent", "d1exea_.ent-d1ihfa_.ent", "d1exea_.ent-d1ihfb_.ent", "d1exh__.ent-d1g1ka_.ent", "d1exh__.ent-d1g43a_.ent", "d1exh__.ent-d1nbca_.ent", "d1exh__.ent-d1qba_2.ent", "d1exh__.ent-d1tf4a2.ent", "d1exja1.ent-d1j9ia_.ent", "d1exja1.ent-d1jbga_.ent", "d1exja1.ent-d1jjcb1.ent", "d1exja1.ent-d1jjcb2.ent", "d1exma1.ent-d1f60a1.ent", "d1exma1.ent-d1g7sa1.ent", "d1exma1.ent-d1g7sa2.ent", "d1exma1.ent-d1jj2b_.ent", "d1exma1.ent-d1kk1a1.ent", "d1exma1.ent-d1n0ua1.ent", "d1exma2.ent-d1f60a2.ent", "d1exma2.ent-d1kk1a2.ent", "d1exqa_.ent-d1fxxa_.ent", "d1exqa_.ent-d1hjra_.ent", "d1exqa_.ent-d1i39a_.ent", "d1exqa_.ent-d1ih7a1.ent", "d1exqa_.ent-d1io2a_.ent", "d1exqa_.ent-d1j54a_.ent", "d1exqa_.ent-d1jl1a_.ent", "d1exqa_.ent-d1kcfa2.ent", "d1exqa_.ent-d1kfsa1.ent", "d1exqa_.ent-d1musa_.ent", "d1exqa_.ent-d1qtma1.ent", "d1exqa_.ent-d1t7pa1.ent", "d1exqa_.ent-d1tgoa1.ent", "d1exqa_.ent-d1vrta1.ent", "d1exqa_.ent-d1xwl_1.ent", "d1exra_.ent-d1eg3a1.ent", "d1exra_.ent-d1ggwa_.ent", "d1exra_.ent-d1jfja_.ent", "d1exra_.ent-d1m31a_.ent", "d1exra_.ent-d1m45a_.ent", "d1exra_.ent-d1rro__.ent", "d1exra_.ent-d1wdcb_.ent", "d1exra_.ent-d2pvba_.ent", "d1exra_.ent-d5pal__.ent", "d1exsa_.ent-d1i4ua_.ent", "d1exsa_.ent-d1ifc__.ent", "d1exsa_.ent-d1koia_.ent", "d1exsa_.ent-d1lf7a_.ent", "d1exsa_.ent-d1qfta_.ent", "d1exsa_.ent-d1qqsa_.ent", "d1exta1.ent-d1exta2.ent", "d1exta1.ent-d1exta3.ent", "d1exta1.ent-d1jmab1.ent", "d1exta1.ent-d1jmab2.ent", "d1exta2.ent-d1exta3.ent", "d1exta2.ent-d1jmab1.ent", "d1exta2.ent-d1jmab2.ent", "d1exta3.ent-d1jmab1.ent", "d1exta3.ent-d1jmab2.ent", "d1eyea_.ent-d1f6ya_.ent", "d1eyla_.ent-d1wba__.ent", "d1eyla_.ent-d3btaa2.ent", "d1eysc_.ent-d1fgja_.ent", "d1eysc_.ent-d1fs7a_.ent", "d1eysc_.ent-d1ft5a_.ent", "d1eysc_.ent-d1gu6a_.ent", "d1eysc_.ent-d1gyoa_.ent", "d1eysc_.ent-d1h21a_.ent", "d1eysc_.ent-d1h29a_.ent", "d1eysc_.ent-d1hh5a_.ent", "d1eysc_.ent-d1kssa1.ent", "d1eysc_.ent-d1m1qa_.ent", "d1eysc_.ent-d1qo8a1.ent", "d1eysc_.ent-d1wad__.ent", "d1eysc_.ent-d2ctha_.ent", "d1eysc_.ent-d2cy3__.ent", "d1eysc_.ent-d3caoa_.ent", "d1eysc_.ent-d3cyr__.ent", "d1ez0a_.ent-d1ky8a_.ent", "d1ez3a_.ent-d1fioa_.ent", "d1ez3a_.ent-d1hs7a_.ent", "d1ez3a_.ent-d1lvfa_.ent", "d1ez4a2.ent-d1guya2.ent", "d1ez4a2.ent-d1hyea2.ent", "d1ez4a2.ent-d1hyha2.ent", "d1ez4a2.ent-d1i0za2.ent", "d1ez4a2.ent-d1ldg_2.ent", "d1ez4a2.ent-d1ldna2.ent", "d1ez4a2.ent-d1llda2.ent", "d1ez4a2.ent-d1o6za2.ent", "d1ez4a2.ent-d2cmd_2.ent", "d1ez4a2.ent-d5mdha2.ent", "d1ez4a2.ent-d7mdha2.ent", "d1ezfa_.ent-d1jfaa_.ent", "d1ezfa_.ent-d1n1ba2.ent", "d1ezfa_.ent-d1ps1a_.ent", "d1ezfa_.ent-d1uby__.ent", "d1ezfa_.ent-d5eau_2.ent", "d1ezga_.ent-d1hf2a1.ent", "d1ezga_.ent-d1k4za_.ent", "d1ezga_.ent-d1k5ca_.ent", "d1ezga_.ent-d1llwa1.ent", "d1ezga_.ent-d1qcxa_.ent", "d1ezga_.ent-d1qq1a_.ent", "d1ezm__.ent-d1g12a_.ent", "d1ezm__.ent-d1gkda_.ent", "d1ezm__.ent-d1gqia2.ent", "d1ezm__.ent-d1hs6a3.ent", "d1ezm__.ent-d1i1ip_.ent", "d1ezm__.ent-d1j7na1.ent", "d1ezm__.ent-d1j7na2.ent", "d1ezm__.ent-d1jaka2.ent", "d1ezm__.ent-d1jk3a_.ent", "d1ezm__.ent-d1k7ia2.ent", "d1ezm__.ent-d1k9xa_.ent", "d1ezm__.ent-d1kapp2.ent", "d1ezm__.ent-d1keia_.ent", "d1ezm__.ent-d1kufa_.ent", "d1ezm__.ent-d1lml__.ent", "d1ezm__.ent-d1qba_4.ent", "d1ezm__.ent-d3btaa3.ent", "d1ezva1.ent-d1ezva2.ent", "d1ezva1.ent-d1ezvb1.ent", "d1ezva1.ent-d1ezvb2.ent", "d1ezva1.ent-d1hr6a1.ent", "d1ezva1.ent-d1hr6a2.ent", "d1ezva1.ent-d1hr6b1.ent", "d1ezva1.ent-d1hr6b2.ent", "d1ezva2.ent-d1ezvb1.ent", "d1ezva2.ent-d1ezvb2.ent", "d1ezva2.ent-d1hr6a1.ent", "d1ezva2.ent-d1hr6a2.ent", "d1ezva2.ent-d1hr6b1.ent", "d1ezva2.ent-d1hr6b2.ent", "d1ezvb1.ent-d1ezvb2.ent", "d1ezvb1.ent-d1hr6a1.ent", "d1ezvb1.ent-d1hr6a2.ent", "d1ezvb1.ent-d1hr6b1.ent", "d1ezvb1.ent-d1hr6b2.ent", "d1ezvb2.ent-d1hr6a1.ent", "d1ezvb2.ent-d1hr6a2.ent", "d1ezvb2.ent-d1hr6b1.ent", "d1ezvb2.ent-d1hr6b2.ent", "d1ezvc3.ent-d1kf6c_.ent", "d1ezvc3.ent-d1kf6d_.ent", "d1ezvc3.ent-d1kqfc_.ent", "d1ezvc3.ent-d1nekc_.ent", "d1ezvc3.ent-d1nekd_.ent", "d1ezvc3.ent-d1qlac_.ent", "d1ezvd1.ent-d1c52__.ent", "d1ezvd1.ent-d1co6a_.ent", "d1ezvd1.ent-d1cot__.ent", "d1ezvd1.ent-d1cxc__.ent", "d1ezvd1.ent-d1dw0a_.ent", "d1ezvd1.ent-d1e29a_.ent", "d1ezvd1.ent-d1eb7a1.ent", "d1ezvd1.ent-d1eb7a2.ent", "d1ezvd1.ent-d1etpa2.ent", "d1ezvd1.ent-d1f1ca_.ent", "d1ezvd1.ent-d1fcdc2.ent", "d1ezvd1.ent-d1gu2a_.ent", "d1ezvd1.ent-d1h32a1.ent", "d1ezvd1.ent-d1hroa_.ent", "d1ezvd1.ent-d1iqca1.ent", "d1ezvd1.ent-d1iqca2.ent", "d1ezvd1.ent-d1jmxa1.ent", "d1ezvd1.ent-d1jmxa2.ent", "d1ezvd1.ent-d1kb0a1.ent", "d1ezvd1.ent-d1kv9a1.ent", "d1ezvd1.ent-d1mg2d_.ent", "d1ezvd1.ent-d1nira1.ent", "d1ezvd1.ent-d1qksa1.ent", "d1ezvd1.ent-d1ql3a_.ent", "d1ezvd1.ent-d1qn2a_.ent", "d1ezvd1.ent-d1ycc__.ent", "d1ezvd1.ent-d3c2c__.ent", "d1ezvd2.ent-d1ezve2.ent", "d1ezvd2.ent-d1ezvg_.ent", "d1ezvd2.ent-d1ezvi_.ent", "d1ezvd2.ent-d1jb0f_.ent", "d1ezvd2.ent-d1jb0i_.ent", "d1ezvd2.ent-d1jb0j_.ent", "d1ezvd2.ent-d1jb0m_.ent", "d1ezvd2.ent-d1kqfb2.ent", "d1ezvd2.ent-d1l2pa_.ent", "d1ezvd2.ent-d1m56d_.ent", "d1ezvd2.ent-d1ocrd_.ent", "d1ezvd2.ent-d1ocrg_.ent", "d1ezvd2.ent-d1ocri_.ent", "d1ezvd2.ent-d1ocrj_.ent", "d1ezvd2.ent-d1ocrk_.ent", "d1ezvd2.ent-d1ocrl_.ent", "d1ezvd2.ent-d1ocrm_.ent", "d1ezve2.ent-d1ezvg_.ent", "d1ezve2.ent-d1ezvi_.ent", "d1ezve2.ent-d1jb0f_.ent", "d1ezve2.ent-d1jb0i_.ent", "d1ezve2.ent-d1jb0j_.ent", "d1ezve2.ent-d1jb0m_.ent", "d1ezve2.ent-d1kqfb2.ent", "d1ezve2.ent-d1l2pa_.ent", "d1ezve2.ent-d1m56d_.ent", "d1ezve2.ent-d1ocrd_.ent", "d1ezve2.ent-d1ocrg_.ent", "d1ezve2.ent-d1ocri_.ent", "d1ezve2.ent-d1ocrj_.ent", "d1ezve2.ent-d1ocrk_.ent", "d1ezve2.ent-d1ocrl_.ent", "d1ezve2.ent-d1ocrm_.ent", "d1ezvg_.ent-d1ezvi_.ent", "d1ezvg_.ent-d1jb0f_.ent", "d1ezvg_.ent-d1jb0i_.ent", "d1ezvg_.ent-d1jb0j_.ent", "d1ezvg_.ent-d1jb0m_.ent", "d1ezvg_.ent-d1kqfb2.ent", "d1ezvg_.ent-d1l2pa_.ent", "d1ezvg_.ent-d1m56d_.ent", "d1ezvg_.ent-d1ocrd_.ent", "d1ezvg_.ent-d1ocrg_.ent", "d1ezvg_.ent-d1ocri_.ent", "d1ezvg_.ent-d1ocrj_.ent", "d1ezvg_.ent-d1ocrk_.ent", "d1ezvg_.ent-d1ocrl_.ent", "d1ezvg_.ent-d1ocrm_.ent", "d1ezvi_.ent-d1jb0f_.ent", "d1ezvi_.ent-d1jb0i_.ent", "d1ezvi_.ent-d1jb0j_.ent", "d1ezvi_.ent-d1jb0m_.ent", "d1ezvi_.ent-d1kqfb2.ent", "d1ezvi_.ent-d1l2pa_.ent", "d1ezvi_.ent-d1m56d_.ent", "d1ezvi_.ent-d1ocrd_.ent", "d1ezvi_.ent-d1ocrg_.ent", "d1ezvi_.ent-d1ocri_.ent", "d1ezvi_.ent-d1ocrj_.ent", "d1ezvi_.ent-d1ocrk_.ent", "d1ezvi_.ent-d1ocrl_.ent", "d1ezvi_.ent-d1ocrm_.ent", "d1ezwa_.ent-d1luca_.ent", "d1ezwa_.ent-d1lucb_.ent", "d1ezwa_.ent-d1m41a_.ent", "d1ezwa_.ent-d1nfp__.ent", "d1f00i1.ent-d1f00i2.ent", "d1f00i3.ent-d1g1ta1.ent", "d1f00i3.ent-d1h8ua_.ent", "d1f00i3.ent-d1kg0c_.ent", "d1f00i3.ent-d1koe__.ent", "d1f00i3.ent-d1li1a1.ent", "d1f00i3.ent-d1prea1.ent", "d1f00i3.ent-d1prtb2.ent", "d1f00i3.ent-d1qdda_.ent", "d1f00i3.ent-d1tsg__.ent", "d1f06a2.ent-d1gr0a2.ent", "d1f06a2.ent-d1h6da2.ent", "d1f06a2.ent-d1j5pa3.ent", "d1f06a2.ent-d1jkia2.ent", "d1f06a2.ent-d1jn0a2.ent", "d1f06a2.ent-d1lc0a2.ent", "d1f06a2.ent-d1mb4a2.ent", "d1f06a2.ent-d1qkia2.ent", "d1f08a_.ent-d1l2ma_.ent", "d1f08a_.ent-d1m55a_.ent", "d1f08a_.ent-d1tbd__.ent", "d1f0ia1.ent-d1f0ia2.ent", "d1f0ka_.ent-d1iira_.ent", "d1f0ka_.ent-d1jixa_.ent", "d1f0ka_.ent-d1l5wa_.ent", "d1f0la1.ent-d1h6fa_.ent", "d1f0la1.ent-d1i31a_.ent", "d1f0la1.ent-d1klfb1.ent", "d1f0la1.ent-d1klfb2.ent", "d1f0la1.ent-d1m2oa2.ent", "d1f0la1.ent-d1m2vb2.ent", "d1f0la1.ent-d1mnna_.ent", "d1f0la1.ent-d1nbca_.ent", "d1f0la1.ent-d1pdkb_.ent", "d1f0la1.ent-d1qba_2.ent", "d1f0la1.ent-d1tf4a2.ent", "d1f0la1.ent-d1ycsa_.ent", "d1f0la2.ent-d1giqa1.ent", "d1f0la2.ent-d1giqa2.ent", "d1f0la2.ent-d1gxya_.ent", "d1f0la2.ent-d1ikpa2.ent", "d1f0la2.ent-d1j7na3.ent", "d1f0la2.ent-d1prta_.ent", "d1f0la2.ent-d1qs1a1.ent", "d1f0la2.ent-d1qs1a2.ent", "d1f0la3.ent-d1ikpa3.ent", "d1f0la3.ent-d1k3ka_.ent", "d1f0la3.ent-d1maz__.ent", "d1f0xa1.ent-d1azsa_.ent", "d1f0xa1.ent-d1b3ta_.ent", "d1f0xa1.ent-d1dj0a2.ent", "d1f0xa1.ent-d1dqaa1.ent", "d1f0xa1.ent-d1ekra_.ent", "d1f0xa1.ent-d1eqoa_.ent", "d1f0xa1.ent-d1f3va_.ent", "d1f0xa1.ent-d1ftra1.ent", "d1f0xa1.ent-d1ftra2.ent", "d1f0xa1.ent-d1fx2a_.ent", "d1f0xa1.ent-d1gpja3.ent", "d1f0xa1.ent-d1h0hb_.ent", "d1f0xa1.ent-d1h72c2.ent", "d1f0xa1.ent-d1hbnb2.ent", "d1f0xa1.ent-d1hlwa_.ent", "d1f0xa1.ent-d1i19a1.ent", "d1f0xa1.ent-d1jnrb_.ent", "d1f0xa1.ent-d1kvka2.ent", "d1f0xa1.ent-d1lfwa2.ent", "d1f0xa1.ent-d1qd1a1.ent", "d1f0xa1.ent-d1qd1a2.ent", "d1f0xa1.ent-d1regx_.ent", "d1f0xa2.ent-d1fo4a6.ent", "d1f0xa2.ent-d1hska1.ent", "d1f0xa2.ent-d1i19a2.ent", "d1f0xa2.ent-d1jroa4.ent", "d1f0xa2.ent-d1n62c2.ent", "d1f0xa2.ent-d1uxy_1.ent", "d1f0ya1.ent-d1i36a1.ent", "d1f0ya1.ent-d1ks9a1.ent", "d1f0ya1.ent-d1m66a1.ent", "d1f0ya1.ent-d1pgja1.ent", "d1f0ya1.ent-d1qmga1.ent", "d1f0ya1.ent-d2pgd_1.ent", "d1f0ya2.ent-d1bg6_2.ent", "d1f0ya2.ent-d1cf2o1.ent", "d1f0ya2.ent-d1dssg1.ent", "d1f0ya2.ent-d1e5qa1.ent", "d1f0ya2.ent-d1lc0a1.ent", "d1f0ya2.ent-d1lu9a1.ent", "d1f0ya2.ent-d2naca1.ent", "d1f0ya2.ent-d2pgd_2.ent", "d1f0za_.ent-d1fm0d_.ent", "d1f0za_.ent-d1jsba_.ent", "d1f13a2.ent-d1f13a3.ent", "d1f13a2.ent-d1g0da2.ent", "d1f13a2.ent-d1g0da3.ent", "d1f13a2.ent-d1kv3a2.ent", "d1f13a2.ent-d1kv3a3.ent", "d1f13a2.ent-d1l9na2.ent", "d1f13a2.ent-d1l9na3.ent", "d1f13a3.ent-d1g0da2.ent", "d1f13a3.ent-d1g0da3.ent", "d1f13a3.ent-d1kv3a2.ent", "d1f13a3.ent-d1kv3a3.ent", "d1f13a3.ent-d1l9na2.ent", "d1f13a3.ent-d1l9na3.ent", "d1f13a4.ent-d1fh0a_.ent", "d1f13a4.ent-d1g0da4.ent", "d1f13a4.ent-d1gmya_.ent", "d1f13a4.ent-d1gx3a_.ent", "d1f13a4.ent-d1iu4a_.ent", "d1f13a4.ent-d1kxra_.ent", "d1f13a4.ent-d1l9na4.ent", "d1f13a4.ent-d1me4a_.ent", "d1f13a4.ent-d1nbfa_.ent", "d1f13a4.ent-d1ppn__.ent", "d1f13a4.ent-d1qmya_.ent", "d1f13a4.ent-d1uch__.ent", "d1f13a4.ent-d2act__.ent", "d1f13a4.ent-d2cb5a_.ent", "d1f13a4.ent-d3gcb__.ent", "d1f13a4.ent-d7pcka_.ent", "d1f15a_.ent-d1cwpa_.ent", "d1f16a_.ent-d1k3ka_.ent", "d1f16a_.ent-d1maz__.ent", "d1f1ca_.ent-d1co6a_.ent", "d1f1ca_.ent-d1cot__.ent", "d1f1ca_.ent-d1cxc__.ent", "d1f1ca_.ent-d1dw0a_.ent", "d1f1ca_.ent-d1etpa2.ent", "d1f1ca_.ent-d1gu2a_.ent", "d1f1ca_.ent-d1hroa_.ent", "d1f1ca_.ent-d1kb0a1.ent", "d1f1ca_.ent-d1kv9a1.ent", "d1f1ca_.ent-d1nira1.ent", "d1f1ca_.ent-d1qksa1.ent", "d1f1ca_.ent-d1ql3a_.ent", "d1f1ca_.ent-d1qn2a_.ent", "d1f1ca_.ent-d1ycc__.ent", "d1f1ca_.ent-d3c2c__.ent", "d1f1ma_.ent-d1fts_1.ent", "d1f1ma_.ent-d1he1a_.ent", "d1f1ma_.ent-d1jr8a_.ent", "d1f1ma_.ent-d1k04a_.ent", "d1f1ma_.ent-d1knya1.ent", "d1f1ma_.ent-d1ls1a1.ent", "d1f1ma_.ent-d1nfn__.ent", "d1f1ma_.ent-d1nlxa_.ent", "d1f1ma_.ent-d256ba_.ent", "d1f1ma_.ent-d2a0b__.ent", "d1f1ma_.ent-d2liga_.ent", "d1f1ma_.ent-d2mhr__.ent", "d1f1ma_.ent-d3fapb_.ent", "d1f1za1.ent-d1bjaa_.ent", "d1f1za1.ent-d1d5va_.ent", "d1f1za1.ent-d1e17a_.ent", "d1f1za1.ent-d1fsha_.ent", "d1f1za1.ent-d1ldja1.ent", "d1f1za1.ent-d1opc__.ent", "d1f1za1.ent-d1smta_.ent", "d1f1za1.ent-d2ezl__.ent", "d1f1za1.ent-d2foka3.ent", "d1f1za2.ent-d1fiua_.ent", "d1f1za2.ent-d1gefa_.ent", "d1f1za2.ent-d1hh1a_.ent", "d1f1za2.ent-d1kc6a_.ent", "d1f1za2.ent-d1knva_.ent", "d1f1za2.ent-d1m0da_.ent", "d1f1za2.ent-d1vsra_.ent", "d1f1za2.ent-d2foka4.ent", "d1f1za2.ent-d3pvia_.ent", "d1f20a1.ent-d1f60a1.ent", "d1f20a1.ent-d1fdr_1.ent", "d1f20a1.ent-d1fnc_1.ent", "d1f20a1.ent-d1fuia1.ent", "d1f20a1.ent-d1g7sa1.ent", "d1f20a1.ent-d1g7sa2.ent", "d1f20a1.ent-d1i7pa1.ent", "d1f20a1.ent-d1i8da1.ent", "d1f20a1.ent-d1i8da2.ent", "d1f20a1.ent-d1ja1a1.ent", "d1f20a1.ent-d1jb9a1.ent", "d1f20a1.ent-d1jj2b_.ent", "d1f20a1.ent-d1kk1a1.ent", "d1f20a1.ent-d1krha1.ent", "d1f20a1.ent-d1kzla1.ent", "d1f20a1.ent-d1kzla2.ent", "d1f20a1.ent-d1n08a_.ent", "d1f20a1.ent-d1n0ua1.ent", "d1f20a1.ent-d1qfja1.ent", "d1f20a1.ent-d1que_1.ent", "d1f20a1.ent-d2cnd_1.ent", "d1f20a1.ent-d2pia_1.ent", "d1f20a2.ent-d1fdr_2.ent", "d1f20a2.ent-d1gvha3.ent", "d1f20a2.ent-d1i7pa2.ent", "d1f20a2.ent-d1ja1a3.ent", "d1f20a2.ent-d1jb9a2.ent", "d1f20a2.ent-d1krha2.ent", "d1f20a2.ent-d1qfja2.ent", "d1f20a2.ent-d1que_2.ent", "d1f20a2.ent-d2cnd_2.ent", "d1f20a2.ent-d2pia_2.ent", "d1f28a_.ent-d1tis__.ent", "d1f2da_.ent-d1j6na_.ent", "d1f2da_.ent-d1jbqa_.ent", "d1f2da_.ent-d1qopb_.ent", "d1f2da_.ent-d1tdj_1.ent", "d1f2ea1.ent-d1fw1a1.ent", "d1f2ea1.ent-d1g7oa1.ent", "d1f2ea1.ent-d1glqa1.ent", "d1f2ea1.ent-d1gnwa1.ent", "d1f2ea1.ent-d1gula1.ent", "d1f2ea1.ent-d1gwca1.ent", "d1f2ea1.ent-d1jlva1.ent", "d1f2ea1.ent-d1k0da1.ent", "d1f2ea1.ent-d1k0ma1.ent", "d1f2ea1.ent-d1k3ya1.ent", "d1f2ea1.ent-d1ljra1.ent", "d1f2ea1.ent-d1m0ua1.ent", "d1f2ea1.ent-d1pd211.ent", "d1f2ea1.ent-d1pmt_1.ent", "d1f2ea1.ent-d2gsq_1.ent", "d1f2ea1.ent-d2gsta1.ent", "d1f2la_.ent-d1g2ta_.ent", "d1f2la_.ent-d1j9oa_.ent", "d1f2la_.ent-d1m8aa_.ent", "d1f2la_.ent-d1qg7a_.ent", "d1f2la_.ent-d1tvxa_.ent", "d1f2la_.ent-d2hcc__.ent", "d1f2la_.ent-d3il8__.ent", "d1f2ri_.ent-d1ip9a_.ent", "d1f2va_.ent-d1cex__.ent", "d1f2va_.ent-d1cf9a1.ent", "d1f2va_.ent-d1e5da1.ent", "d1f2va_.ent-d1euca2.ent", "d1f2va_.ent-d1f4pa_.ent", "d1f2va_.ent-d1f8ya_.ent", "d1f2va_.ent-d1fuea_.ent", "d1f2va_.ent-d1g66a_.ent", "d1f2va_.ent-d1h05a_.ent", "d1f2va_.ent-d1kwga3.ent", "d1f2va_.ent-d1l7da2.ent", "d1f2va_.ent-d1qo0d_.ent", "d1f2va_.ent-d2naca2.ent", "d1f2va_.ent-d7reqb2.ent", "d1f39a_.ent-d1jhfa2.ent", "d1f3la_.ent-d1booa_.ent", "d1f3la_.ent-d1eg2a_.ent", "d1f3la_.ent-d1fp1d2.ent", "d1f3la_.ent-d1fp2a2.ent", "d1f3la_.ent-d1g38a_.ent", "d1f3la_.ent-d1g60a_.ent", "d1f3la_.ent-d1hnna_.ent", "d1f3la_.ent-d1i1na_.ent", "d1f3la_.ent-d1i4wa_.ent", "d1f3la_.ent-d1i9ga_.ent", "d1f3la_.ent-d1inla_.ent", "d1f3la_.ent-d1iy9a_.ent", "d1f3la_.ent-d1jg1a_.ent", "d1f3la_.ent-d1jqea_.ent", "d1f3la_.ent-d1jsxa_.ent", "d1f3la_.ent-d1khha_.ent", "d1f3la_.ent-d1kywa2.ent", "d1f3la_.ent-d1mjfa_.ent", "d1f3la_.ent-d1qama_.ent", "d1f3la_.ent-d1vid__.ent", "d1f3la_.ent-d1xvaa_.ent", "d1f3la_.ent-d1yub__.ent", "d1f3la_.ent-d2dpma_.ent", "d1f3la_.ent-d3mag__.ent", "d1f3mc_.ent-d1a06__.ent", "d1f3mc_.ent-d1fgka_.ent", "d1f3mc_.ent-d1ia9a_.ent", "d1f3mc_.ent-d1iepa_.ent", "d1f3mc_.ent-d1jksa_.ent", "d1f3mc_.ent-d1jpaa_.ent", "d1f3mc_.ent-d1jvpp_.ent", "d1f3mc_.ent-d1lufa_.ent", "d1f3mc_.ent-d1phk__.ent", "d1f3va_.ent-d1b3ta_.ent", "d1f3va_.ent-d1dj0a2.ent", "d1f3va_.ent-d1dqaa1.ent", "d1f3va_.ent-d1ekra_.ent", "d1f3va_.ent-d1ftra1.ent", "d1f3va_.ent-d1ftra2.ent", "d1f3va_.ent-d1gpja3.ent", "d1f3va_.ent-d1h72c2.ent", "d1f3va_.ent-d1hlwa_.ent", "d1f3va_.ent-d1jnrb_.ent", "d1f3va_.ent-d1qd1a2.ent", "d1f3va_.ent-d1regx_.ent", "d1f42a2.ent-d1axib2.ent", "d1f42a2.ent-d1bpv__.ent", "d1f42a2.ent-d1bqua2.ent", "d1f42a2.ent-d1cd9b1.ent", "d1f42a2.ent-d1cd9b2.ent", "d1f42a2.ent-d1cfb_1.ent", "d1f42a2.ent-d1cfb_2.ent", "d1f42a2.ent-d1eerb1.ent", "d1f42a2.ent-d1eerb2.ent", "d1f42a2.ent-d1egja_.ent", "d1f42a2.ent-d1f6fb1.ent", "d1f42a2.ent-d1f6fb2.ent", "d1f42a2.ent-d1fyhb1.ent", "d1f42a2.ent-d1fyhb2.ent", "d1f42a2.ent-d1gh7a1.ent", "d1f42a2.ent-d1gh7a2.ent", "d1f42a2.ent-d1i1ra1.ent", "d1f42a2.ent-d1lqsr1.ent", "d1f42a2.ent-d1lqsr2.ent", "d1f42a2.ent-d1n26a2.ent", "d1f42a2.ent-d1n26a3.ent", "d1f42a2.ent-d1qg3a2.ent", "d1f42a2.ent-d2hft_1.ent", "d1f42a2.ent-d2hft_2.ent", "d1f44a1.ent-d1floa1.ent", "d1f44a1.ent-d1go3f_.ent", "d1f44a1.ent-d1jmsa1.ent", "d1f44a1.ent-d1jmsa3.ent", "d1f44a1.ent-d1jyga_.ent", "d1f44a1.ent-d1kfta_.ent", "d1f44a1.ent-d1lb2b_.ent", "d1f44a1.ent-d1tfr_1.ent", "d1f45b_.ent-d1f6fa_.ent", "d1f45b_.ent-d1hula_.ent", "d1f45b_.ent-d1huw__.ent", "d1f45b_.ent-d1hzia_.ent", "d1f45b_.ent-d1i1rb_.ent", "d1f45b_.ent-d1jli__.ent", "d1f45b_.ent-d1lki__.ent", "d1f45b_.ent-d1lqsl_.ent", "d1f45b_.ent-d1m47a_.ent", "d1f45b_.ent-d1n1fa_.ent", "d1f45b_.ent-d2gmfa_.ent", "d1f45b_.ent-d2ilk__.ent", "d1f46a_.ent-d1fm4a_.ent", "d1f46a_.ent-d1k2yx4.ent", "d1f46a_.ent-d1kcma_.ent", "d1f46a_.ent-d1ko9a2.ent", "d1f46a_.ent-d1ln1a_.ent", "d1f46a_.ent-d1mpga2.ent", "d1f46a_.ent-d1ytba1.ent", "d1f46a_.ent-d3pmga4.ent", "d1f4ia_.ent-d1ifya_.ent", "d1f4ia_.ent-d1oaia_.ent", "d1f4la1.ent-d1f7ua1.ent", "d1f4la1.ent-d1ffya1.ent", "d1f4la1.ent-d1ile_1.ent", "d1f4la1.ent-d1iq0a1.ent", "d1f4la1.ent-d1ivsa2.ent", "d1f4la1.ent-d1li5a1.ent", "d1f4la2.ent-d1f7ua2.ent", "d1f4la2.ent-d1ffya3.ent", "d1f4la2.ent-d1g8fa2.ent", "d1f4la2.ent-d1gpma1.ent", "d1f4la2.ent-d1gtra2.ent", "d1f4la2.ent-d1h3fa1.ent", "d1f4la2.ent-d1h3na3.ent", "d1f4la2.ent-d1ihoa_.ent", "d1f4la2.ent-d1ile_3.ent", "d1f4la2.ent-d1iq0a2.ent", "d1f4la2.ent-d1irxa2.ent", "d1f4la2.ent-d1ivsa4.ent", "d1f4la2.ent-d1j09a2.ent", "d1f4la2.ent-d1jgta1.ent", "d1f4la2.ent-d1jhda2.ent", "d1f4la2.ent-d1jila_.ent", "d1f4la2.ent-d1jmva_.ent", "d1f4la2.ent-d1k4ma_.ent", "d1f4la2.ent-d1k92a1.ent", "d1f4la2.ent-d1kama_.ent", "d1f4la2.ent-d1kqna_.ent", "d1f4la2.ent-d1kqpa_.ent", "d1f4la2.ent-d1li5a2.ent", "d1f4la2.ent-d1mjha_.ent", "d1f4la2.ent-d1n3la_.ent", "d1f4la2.ent-d1o97c_.ent", "d1f4la2.ent-d1o97d1.ent", "d1f4la2.ent-d1qjca_.ent", "d1f4la2.ent-d1sur__.ent", "d1f4la3.ent-d1gh9a_.ent", "d1f4la3.ent-d1i50i1.ent", "d1f4la3.ent-d1i50i2.ent", "d1f4la3.ent-d1i50l_.ent", "d1f4la3.ent-d1jj22_.ent", "d1f4la3.ent-d1jj2y_.ent", "d1f4la3.ent-d1jj2z_.ent", "d1f4la3.ent-d1lkoa2.ent", "d1f4la3.ent-d1m2oa5.ent", "d1f4la3.ent-d1ocrf_.ent", "d1f4la3.ent-d1pft__.ent", "d1f4la3.ent-d1rb9__.ent", "d1f4la3.ent-d1tfi__.ent", "d1f4la3.ent-d1yua_1.ent", "d1f4la3.ent-d1yua_2.ent", "d1f4la3.ent-d1zaka2.ent", "d1f4la3.ent-d1zin_2.ent", "d1f4pa_.ent-d1fuea_.ent", "d1f4pa_.ent-d1h05a_.ent", "d1f4pa_.ent-d1ja1a2.ent", "d1f4pa_.ent-d1qr2a_.ent", "d1f4pa_.ent-d1rcf__.ent", "d1f4pa_.ent-d2fcr__.ent", "d1f4pa_.ent-d5nul__.ent", "d1f52a1.ent-d1bmlc3.ent", "d1f52a1.ent-d1c9fa_.ent", "d1f52a1.ent-d1czpa_.ent", "d1f52a1.ent-d1fm0d_.ent", "d1f52a1.ent-d1h4ra3.ent", "d1f52a1.ent-d1h8ca_.ent", "d1f52a1.ent-d1i42a_.ent", "d1f52a1.ent-d1ip9a_.ent", "d1f52a1.ent-d1k8rb_.ent", "d1f52a1.ent-d1l5pa_.ent", "d1f52a1.ent-d1l7ya_.ent", "d1f52a1.ent-d1lfda_.ent", "d1f52a2.ent-d1m15a2.ent", "d1f52a2.ent-d1qh4a2.ent", "d1f53a_.ent-d1g6ea_.ent", "d1f53a_.ent-d2bb2_1.ent", "d1f53a_.ent-d2bb2_2.ent", "d1f5aa4.ent-d1fa0a4.ent", "d1f5aa4.ent-d1jaja_.ent", "d1f5aa4.ent-d1jmsa4.ent", "d1f5aa4.ent-d1jn3a2.ent", "d1f5aa4.ent-d1knya2.ent", "d1f5ma_.ent-d1gw5m2.ent", "d1f5ma_.ent-d1h3qa_.ent", "d1f5ma_.ent-d1h8ma_.ent", "d1f5ma_.ent-d1jnua_.ent", "d1f5ma_.ent-d1ll8a_.ent", "d1f5ma_.ent-d1mc0a1.ent", "d1f5ma_.ent-d1mc0a2.ent", "d1f5ma_.ent-d1mkma2.ent", "d1f5ma_.ent-d1pne__.ent", "d1f5ma_.ent-d3pyp__.ent", "d1f5na2.ent-d1cr1a_.ent", "d1f5na2.ent-d1e69a_.ent", "d1f5na2.ent-d1g8ya_.ent", "d1f5na2.ent-d1gm5a3.ent", "d1f5na2.ent-d1lv7a_.ent", "d1f5qb1.ent-d1f5qb2.ent", "d1f5qb1.ent-d1g3nc1.ent", "d1f5qb1.ent-d1g3nc2.ent", "d1f5qb1.ent-d1guxa_.ent", "d1f5qb1.ent-d1guxb_.ent", "d1f5qb1.ent-d1h4ld_.ent", "d1f5qb1.ent-d1jkw_1.ent", "d1f5qb1.ent-d1jkw_2.ent", "d1f5qb1.ent-d1vin_1.ent", "d1f5qb1.ent-d1vin_2.ent", "d1f5qb1.ent-d1vola1.ent", "d1f5qb2.ent-d1g3nc1.ent", "d1f5qb2.ent-d1g3nc2.ent", "d1f5qb2.ent-d1guxa_.ent", "d1f5qb2.ent-d1guxb_.ent", "d1f5qb2.ent-d1h4ld_.ent", "d1f5qb2.ent-d1jkw_1.ent", "d1f5qb2.ent-d1jkw_2.ent", "d1f5qb2.ent-d1vin_1.ent", "d1f5qb2.ent-d1vin_2.ent", "d1f5qb2.ent-d1vola1.ent", "d1f5va_.ent-d1icra_.ent", "d1f5va_.ent-d1nox__.ent", "d1f5va_.ent-d1vfra_.ent", "d1f5xa_.ent-d1ki1b1.ent", "d1f5ya1.ent-d1f5ya2.ent", "d1f5ya1.ent-d1j8ea_.ent", "d1f5ya1.ent-d1k7ba_.ent", "d1f5ya1.ent-d1n7da6.ent", "d1f5ya1.ent-d1n7da7.ent", "d1f5ya1.ent-d1n7daa.ent", "d1f5ya2.ent-d1j8ea_.ent", "d1f5ya2.ent-d1k7ba_.ent", "d1f5ya2.ent-d1n7da6.ent", "d1f5ya2.ent-d1n7da7.ent", "d1f5ya2.ent-d1n7daa.ent", "d1f60a1.ent-d1fuia1.ent", "d1f60a1.ent-d1g7sa1.ent", "d1f60a1.ent-d1g7sa2.ent", "d1f60a1.ent-d1i7pa1.ent", "d1f60a1.ent-d1jb9a1.ent", "d1f60a1.ent-d1jj2b_.ent", "d1f60a1.ent-d1kk1a1.ent", "d1f60a1.ent-d1krha1.ent", "d1f60a1.ent-d1kzla1.ent", "d1f60a1.ent-d1kzla2.ent", "d1f60a1.ent-d1n08a_.ent", "d1f60a1.ent-d1n0ua1.ent", "d1f60a1.ent-d1qfja1.ent", "d1f60a1.ent-d2pia_1.ent", "d1f60a2.ent-d1kk1a2.ent", "d1f62a_.ent-d1fp0a1.ent", "d1f62a_.ent-d1joca1.ent", "d1f62a_.ent-d1vfya_.ent", "d1f68a_.ent-d1jspb_.ent", "d1f6fa_.ent-d1hula_.ent", "d1f6fa_.ent-d1huw__.ent", "d1f6fa_.ent-d1hzia_.ent", "d1f6fa_.ent-d1i1rb_.ent", "d1f6fa_.ent-d1jli__.ent", "d1f6fa_.ent-d1lki__.ent", "d1f6fa_.ent-d1lqsl_.ent", "d1f6fa_.ent-d1m47a_.ent", "d1f6fa_.ent-d1n1fa_.ent", "d1f6fa_.ent-d2gmfa_.ent", "d1f6fa_.ent-d2ilk__.ent", "d1f6fb2.ent-d1f6fb1.ent", "d1f6fb2.ent-d1fyhb1.ent", "d1f6fb2.ent-d1lqsr1.ent", "d1f74a_.ent-d1gvfa_.ent", "d1f74a_.ent-d1gzga_.ent", "d1f74a_.ent-d1h7na_.ent", "d1f74a_.ent-d1hfba_.ent", "d1f74a_.ent-d1i2oa_.ent", "d1f74a_.ent-d1jcla_.ent", "d1f74a_.ent-d1jcxa_.ent", "d1f74a_.ent-d1l6wa_.ent", "d1f74a_.ent-d1mzha_.ent", "d1f74a_.ent-d1nal1_.ent", "d1f74a_.ent-d1o0ya_.ent", "d1f74a_.ent-d1qfea_.ent", "d1f7ca_.ent-d1pbwa_.ent", "d1f7ca_.ent-d1tx4a_.ent", "d1f7ca_.ent-d1wer__.ent", "d1f7da_.ent-d1mq7a_.ent", "d1f7la_.ent-d1ftha_.ent", "d1f7la_.ent-d1qr0a1.ent", "d1f7la_.ent-d1qr0a2.ent", "d1f7sa_.ent-d1hqz1_.ent", "d1f7sa_.ent-d1jhwa3.ent", "d1f7sa_.ent-d1m4ja_.ent", "d1f7ua1.ent-d1ffya1.ent", "d1f7ua1.ent-d1ile_1.ent", "d1f7ua1.ent-d1iq0a1.ent", "d1f7ua1.ent-d1ivsa2.ent", "d1f7ua1.ent-d1li5a1.ent", "d1f7ua2.ent-d1ffya3.ent", "d1f7ua2.ent-d1g8fa2.ent", "d1f7ua2.ent-d1gpma1.ent", "d1f7ua2.ent-d1gtra2.ent", "d1f7ua2.ent-d1h3fa1.ent", "d1f7ua2.ent-d1h3na3.ent", "d1f7ua2.ent-d1ihoa_.ent", "d1f7ua2.ent-d1ile_3.ent", "d1f7ua2.ent-d1iq0a2.ent", "d1f7ua2.ent-d1irxa2.ent", "d1f7ua2.ent-d1ivsa4.ent", "d1f7ua2.ent-d1j09a2.ent", "d1f7ua2.ent-d1jgta1.ent", "d1f7ua2.ent-d1jhda2.ent", "d1f7ua2.ent-d1jila_.ent", "d1f7ua2.ent-d1jmva_.ent", "d1f7ua2.ent-d1k4ma_.ent", "d1f7ua2.ent-d1k92a1.ent", "d1f7ua2.ent-d1kama_.ent", "d1f7ua2.ent-d1kqna_.ent", "d1f7ua2.ent-d1kqpa_.ent", "d1f7ua2.ent-d1li5a2.ent", "d1f7ua2.ent-d1mjha_.ent", "d1f7ua2.ent-d1n3la_.ent", "d1f7ua2.ent-d1o97c_.ent", "d1f7ua2.ent-d1o97d1.ent", "d1f7ua2.ent-d1qjca_.ent", "d1f7ua2.ent-d1sur__.ent", "d1f7ua3.ent-d1iq0a3.ent", "d1f7ua3.ent-d1qf6a3.ent", "d1f86a_.ent-d1h8la1.ent", "d1f86a_.ent-d1lm8v_.ent", "d1f86a_.ent-d1qhoa2.ent", "d1f8ea_.ent-d1h6la_.ent", "d1f8ea_.ent-d1ijqa1.ent", "d1f8ea_.ent-d1k32a2.ent", "d1f8ea_.ent-d1kit_3.ent", "d1f8ea_.ent-d1n1ta2.ent", "d1f8ea_.ent-d1nsca_.ent", "d1f8ea_.ent-d2bat__.ent", "d1f8ea_.ent-d2sli_2.ent", "d1f8ea_.ent-d3sil__.ent", "d1f8ma_.ent-d1cz1a_.ent", "d1f8ma_.ent-d1d3ga_.ent", "d1f8ma_.ent-d1edg__.ent", "d1f8ma_.ent-d1gvoa_.ent", "d1f8ma_.ent-d1gw1a_.ent", "d1f8ma_.ent-d1iexa1.ent", "d1f8ma_.ent-d1itua_.ent", "d1f8ma_.ent-d1jqna_.ent", "d1f8ma_.ent-d1jqoa_.ent", "d1f8ma_.ent-d1k4ga_.ent", "d1f8ma_.ent-d1kbla1.ent", "d1f8ma_.ent-d1kwga2.ent", "d1f8ma_.ent-d1m7ja3.ent", "d1f8ma_.ent-d1muwa_.ent", "d1f8na2.ent-d1lox_2.ent", "d1f8ra1.ent-d1b5qa1.ent", "d1f8ra1.ent-d1chua2.ent", "d1f8ra1.ent-d1cjca1.ent", "d1f8ra1.ent-d1d5ta1.ent", "d1f8ra1.ent-d1ebda1.ent", "d1f8ra1.ent-d1feca1.ent", "d1f8ra1.ent-d1foha5.ent", "d1f8ra1.ent-d1h6va1.ent", "d1f8ra1.ent-d1jeha1.ent", "d1f8ra1.ent-d1jnra2.ent", "d1f8ra1.ent-d1ju2a1.ent", "d1f8ra1.ent-d1k0ia1.ent", "d1f8ra1.ent-d1kdga1.ent", "d1f8ra1.ent-d1kf6a2.ent", "d1f8ra1.ent-d1kssa2.ent", "d1f8ra1.ent-d1l9ea1.ent", "d1f8ra1.ent-d1mo9a1.ent", "d1f8ra1.ent-d1neka2.ent", "d1f8ra1.ent-d1ojt_1.ent", "d1f8ra1.ent-d1qlaa2.ent", "d1f8ra1.ent-d1qo8a2.ent", "d1f8ra1.ent-d3lada1.ent", "d1f8ra2.ent-d1foha4.ent", "d1f8ra2.ent-d1gosa2.ent", "d1f8ra2.ent-d1gpea2.ent", "d1f8ra2.ent-d1i8ta2.ent", "d1f8ra2.ent-d1ju2a2.ent", "d1f8ra2.ent-d1k0ia2.ent", "d1f8ra2.ent-d1kdga2.ent", "d1f8ra2.ent-d1l9ea2.ent", "d1f8ra2.ent-d1mxta2.ent", "d1f8ya_.ent-d1e5da1.ent", "d1f8ya_.ent-d1f4pa_.ent", "d1f8ya_.ent-d1h05a_.ent", "d1f94a_.ent-d1fas__.ent", "d1f94a_.ent-d1hc9a_.ent", "d1f94a_.ent-d1jgka_.ent", "d1f94a_.ent-d1kbaa_.ent", "d1f94a_.ent-d1m9za_.ent", "d1f94a_.ent-d1tfs__.ent", "d1f94a_.ent-d1tgxa_.ent", "d1f94a_.ent-d3ebx__.ent", "d1f9ma_.ent-d1a8l_2.ent", "d1f9ma_.ent-d1bjx__.ent", "d1f9ma_.ent-d1erv__.ent", "d1f9ma_.ent-d1fb6a_.ent", "d1f9ma_.ent-d1gh2a_.ent", "d1f9ma_.ent-d1kte__.ent", "d1f9ma_.ent-d1quwa_.ent", "d1f9ma_.ent-d1thx__.ent", "d1f9ma_.ent-d2trxa_.ent", "d1f9va_.ent-d1a7j__.ent", "d1f9va_.ent-d1aqua_.ent", "d1f9va_.ent-d1cr1a_.ent", "d1f9va_.ent-d1e2ka_.ent", "d1f9va_.ent-d1e69a_.ent", "d1f9va_.ent-d1e79a3.ent", "d1f9va_.ent-d1f5na2.ent", "d1f9va_.ent-d1fnna2.ent", "d1f9va_.ent-d1g8ya_.ent", "d1f9va_.ent-d1gm5a3.ent", "d1f9va_.ent-d1ihua1.ent", "d1f9va_.ent-d1jwyb_.ent", "d1f9va_.ent-d1ksfx3.ent", "d1f9va_.ent-d1lv7a_.ent", "d1f9va_.ent-d1m6na3.ent", "d1f9va_.ent-d1nsta_.ent", "d1f9va_.ent-d1pjr_2.ent", "d1f9va_.ent-d1uaaa1.ent", "d1f9za_.ent-d1kw3b1.ent", "d1f9za_.ent-d1kw3b2.ent", "d1f9za_.ent-d1lqpa_.ent", "d1f9za_.ent-d1mpya1.ent", "d1f9za_.ent-d1mpya2.ent", "d1f9za_.ent-d1qipa_.ent", "d1f9za_.ent-d1qtoa_.ent", "d1fa0a4.ent-d1jaja_.ent", "d1fa0a4.ent-d1jmsa4.ent", "d1fa0a4.ent-d1jn3a2.ent", "d1fa0a4.ent-d1knya2.ent", "d1fada_.ent-d1icha_.ent", "d1fada_.ent-d1n3ka_.ent", "d1fada_.ent-d1ngr__.ent", "d1fada_.ent-d3crd__.ent", "d1fada_.ent-d3ygsp_.ent", "d1faea_.ent-d1fp3a_.ent", "d1faea_.ent-d1gai__.ent", "d1faea_.ent-d1gxma_.ent", "d1faea_.ent-d1h54a1.ent", "d1faea_.ent-d1ia6a_.ent", "d1faea_.ent-d1ks8a_.ent", "d1faea_.ent-d1kwfa_.ent", "d1faea_.ent-d1ld8b_.ent", "d1faea_.ent-d1lf6a1.ent", "d1faea_.ent-d1n1ba1.ent", "d1faea_.ent-d1n7oa1.ent", "d1faea_.ent-d1qaza_.ent", "d1faea_.ent-d2sqca1.ent", "d1faea_.ent-d2sqca2.ent", "d1fafa_.ent-d1fpoa1.ent", "d1fafa_.ent-d1gh6a_.ent", "d1fafa_.ent-d1hdj__.ent", "d1fafa_.ent-d1xbl__.ent", "d1faoa_.ent-d1fhoa_.ent", "d1faoa_.ent-d1gg3a2.ent", "d1faoa_.ent-d1h4ra2.ent", "d1faoa_.ent-d1k5db_.ent", "d1faoa_.ent-d1ki1b2.ent", "d1faoa_.ent-d1mai__.ent", "d1faoa_.ent-d1mixa2.ent", "d1faoa_.ent-d1mkea1.ent", "d1faoa_.ent-d1pls__.ent", "d1faoa_.ent-d1qqga1.ent", "d1faoa_.ent-d1qqga2.ent", "d1faoa_.ent-d1shca_.ent", "d1faq__.ent-d1kbea_.ent", "d1faq__.ent-d1ptq__.ent", "d1fas__.ent-d1hc9a_.ent", "d1fas__.ent-d1jgka_.ent", "d1fas__.ent-d1kbaa_.ent", "d1fas__.ent-d1m9za_.ent", "d1fas__.ent-d1tfs__.ent", "d1fas__.ent-d1tgxa_.ent", "d1fas__.ent-d3ebx__.ent", "d1faza_.ent-d1g4ia_.ent", "d1faza_.ent-d1kvoa_.ent", "d1faza_.ent-d1le6a_.ent", "d1faza_.ent-d1mc2a_.ent", "d1faza_.ent-d1poc__.ent", "d1fbl_1.ent-d1gen__.ent", "d1fbl_1.ent-d1itva_.ent", "d1fbl_1.ent-d1pex__.ent", "d1fbl_1.ent-d1qhua1.ent", "d1fbr_1.ent-d1fbr_2.ent", "d1fbr_1.ent-d1qgba1.ent", "d1fbr_1.ent-d1qgba2.ent", "d1fbr_2.ent-d1qgba1.ent", "d1fbr_2.ent-d1qgba2.ent", "d1fbr_2.ent-d1tpg_2.ent", "d1fbva4.ent-d1g25a_.ent", "d1fbva4.ent-d1jm7a_.ent", "d1fbva4.ent-d1jm7b_.ent", "d1fbva4.ent-d1ldjb_.ent", "d1fbva4.ent-d1rmd_2.ent", "d1fc3a_.ent-d1bjaa_.ent", "d1fc3a_.ent-d1d5va_.ent", "d1fc3a_.ent-d1f1za1.ent", "d1fc3a_.ent-d1fnna1.ent", "d1fc3a_.ent-d1fp1d1.ent", "d1fc3a_.ent-d1fp2a1.ent", "d1fc3a_.ent-d1fsea_.ent", "d1fc3a_.ent-d1gxqa_.ent", "d1fc3a_.ent-d1hsja1.ent", "d1fc3a_.ent-d1ig6a_.ent", "d1fc3a_.ent-d1igna2.ent", "d1fc3a_.ent-d1jhga_.ent", "d1fc3a_.ent-d1ka8a_.ent", "d1fc3a_.ent-d1opc__.ent", "d1fc3a_.ent-d1repc1.ent", "d1fc3a_.ent-d1repc2.ent", "d1fc3a_.ent-d1smta_.ent", "d1fc3a_.ent-d2ezl__.ent", "d1fc3a_.ent-d2foka3.ent", "d1fc3a_.ent-d2irfg_.ent", "d1fcda1.ent-d1fcda2.ent", "d1fcda1.ent-d1fl2a2.ent", "d1fcda1.ent-d1gtea3.ent", "d1fcda1.ent-d1jnra2.ent", "d1fcda1.ent-d1ju2a1.ent", "d1fcda1.ent-d1k0ia1.ent", "d1fcda1.ent-d1kssa2.ent", "d1fcda1.ent-d1l9ea1.ent", "d1fcda1.ent-d1lqta1.ent", "d1fcda1.ent-d1m6ia1.ent", "d1fcda1.ent-d1m6ia2.ent", "d1fcda1.ent-d1nhp_1.ent", "d1fcda1.ent-d1nhp_2.ent", "d1fcda1.ent-d1o94a2.ent", "d1fcda1.ent-d3grs_1.ent", "d1fcda1.ent-d3grs_2.ent", "d1fcda2.ent-d1fl2a2.ent", "d1fcda2.ent-d1gtea3.ent", "d1fcda2.ent-d1jnra2.ent", "d1fcda2.ent-d1ju2a1.ent", "d1fcda2.ent-d1k0ia1.ent", "d1fcda2.ent-d1kssa2.ent", "d1fcda2.ent-d1l9ea1.ent", "d1fcda2.ent-d1lqta1.ent", "d1fcda2.ent-d1m6ia1.ent", "d1fcda2.ent-d1m6ia2.ent", "d1fcda2.ent-d1nhp_1.ent", "d1fcda2.ent-d1nhp_2.ent", "d1fcda2.ent-d1o94a2.ent", "d1fcda2.ent-d3grs_1.ent", "d1fcda2.ent-d3grs_2.ent", "d1fcda3.ent-d1feca3.ent", "d1fcda3.ent-d1h6va3.ent", "d1fcda3.ent-d1lvl_3.ent", "d1fcda3.ent-d1m6ia3.ent", "d1fcda3.ent-d1mo9a3.ent", "d1fcda3.ent-d1n62c1.ent", "d1fcda3.ent-d1nhp_3.ent", "d1fcda3.ent-d1ojt_3.ent", "d1fcda3.ent-d3grs_3.ent", "d1fcda3.ent-d3lada3.ent", "d1fcdc2.ent-d1gu2a_.ent", "d1fcdc2.ent-d1h32a1.ent", "d1fcdc2.ent-d1iqca1.ent", "d1fcdc2.ent-d1iqca2.ent", "d1fcdc2.ent-d1jmxa1.ent", "d1fcdc2.ent-d1jmxa2.ent", "d1fcdc2.ent-d1kb0a1.ent", "d1fcdc2.ent-d1mg2d_.ent", "d1fcdc2.ent-d1qksa1.ent", "d1fcha_.ent-d1hh8a_.ent", "d1fcha_.ent-d1hz4a_.ent", "d1fcha_.ent-d1ihga1.ent", "d1fcha_.ent-d1iyga_.ent", "d1fcha_.ent-d1kt1a1.ent", "d1fcha_.ent-d1qqea_.ent", "d1fcya_.ent-d1g2na_.ent", "d1fcya_.ent-d1hg4a_.ent", "d1fcya_.ent-d1ie9a_.ent", "d1fcya_.ent-d1ilga_.ent", "d1fcya_.ent-d1kv6a_.ent", "d1fcya_.ent-d1lv2a_.ent", "d1fcya_.ent-d1mzna_.ent", "d1fcya_.ent-d1n83a_.ent", "d1fcya_.ent-d2prga_.ent", "d1fd3a_.ent-d1ijva_.ent", "d1fd3a_.ent-d1kj6a_.ent", "d1fd3a_.ent-d1sh1__.ent", "d1fd3a_.ent-d2bds__.ent", "d1fd9a_.ent-d1grj_2.ent", "d1fd9a_.ent-d1hxva_.ent", "d1fd9a_.ent-d1j6ya_.ent", "d1fd9a_.ent-d1jvwa_.ent", "d1fd9a_.ent-d1kt1a3.ent", "d1fd9a_.ent-d1m5ya2.ent", "d1fd9a_.ent-d1m5ya3.ent", "d1fd9a_.ent-d1n1aa_.ent", "d1fd9a_.ent-d1pbk__.ent", "d1fd9a_.ent-d1pina2.ent", "d1fdr_1.ent-d1fnc_1.ent", "d1fdr_1.ent-d1i7pa1.ent", "d1fdr_1.ent-d1i8da1.ent", "d1fdr_1.ent-d1i8da2.ent", "d1fdr_1.ent-d1ja1a1.ent", "d1fdr_1.ent-d1jb9a1.ent", "d1fdr_1.ent-d1krha1.ent", "d1fdr_1.ent-d1kzla1.ent", "d1fdr_1.ent-d1kzla2.ent", "d1fdr_1.ent-d1qfja1.ent", "d1fdr_1.ent-d1que_1.ent", "d1fdr_1.ent-d2cnd_1.ent", "d1fdr_1.ent-d2pia_1.ent", "d1fdr_2.ent-d1gvha3.ent", "d1fdr_2.ent-d1i7pa2.ent", "d1fdr_2.ent-d1ja1a3.ent", "d1fdr_2.ent-d1jb9a2.ent", "d1fdr_2.ent-d1krha2.ent", "d1fdr_2.ent-d1qfja2.ent", "d1fdr_2.ent-d1que_2.ent", "d1fdr_2.ent-d2cnd_2.ent", "d1fdr_2.ent-d2pia_2.ent", "d1fds__.ent-d1bdb__.ent", "d1fds__.ent-d1bgva1.ent", "d1fds__.ent-d1e7wa_.ent", "d1fds__.ent-d1eny__.ent", "d1fds__.ent-d1g0oa_.ent", "d1fds__.ent-d1gcoa_.ent", "d1fds__.ent-d1h5qa_.ent", "d1fds__.ent-d1ja9a_.ent", "d1fds__.ent-d1oaa__.ent", "d1fds__.ent-d1qsga_.ent", "d1fds__.ent-d2ae2a_.ent", "d1fe0a_.ent-d1fvqa_.ent", "d1fe0a_.ent-d1jwwa_.ent", "d1fe0a_.ent-d1k0va_.ent", "d1fe0a_.ent-d1mwza_.ent", "d1feca1.ent-d1cjca1.ent", "d1feca1.ent-d1ebda1.ent", "d1feca1.ent-d1h6va1.ent", "d1feca1.ent-d1jeha1.ent", "d1feca1.ent-d1ojt_1.ent", "d1feca1.ent-d3lada1.ent", "d1feca3.ent-d1h6va3.ent", "d1feca3.ent-d1lvl_3.ent", "d1feca3.ent-d1m6ia3.ent", "d1feca3.ent-d1mo9a3.ent", "d1feca3.ent-d1nhp_3.ent", "d1feca3.ent-d1ojt_3.ent", "d1feca3.ent-d3grs_3.ent", "d1feca3.ent-d3lada3.ent", "d1feha2.ent-d1ayfa_.ent", "d1feha2.ent-d1bmlc3.ent", "d1feha2.ent-d1c9fa_.ent", "d1feha2.ent-d1czpa_.ent", "d1feha2.ent-d1d4ba_.ent", "d1feha2.ent-d1f52a1.ent", "d1feha2.ent-d1fm0d_.ent", "d1feha2.ent-d1fo4a2.ent", "d1feha2.ent-d1gnua_.ent", "d1feha2.ent-d1h4ra3.ent", "d1feha2.ent-d1h8ca_.ent", "d1feha2.ent-d1hlra2.ent", "d1feha2.ent-d1i42a_.ent", "d1feha2.ent-d1i7ha_.ent", "d1feha2.ent-d1ip9a_.ent", "d1feha2.ent-d1jq4a_.ent", "d1feha2.ent-d1jroa2.ent", "d1feha2.ent-d1k8rb_.ent", "d1feha2.ent-d1kf6b2.ent", "d1feha2.ent-d1krha3.ent", "d1feha2.ent-d1l4db_.ent", "d1feha2.ent-d1l5pa_.ent", "d1feha2.ent-d1l7ya_.ent", "d1feha2.ent-d1lfda_.ent", "d1feha2.ent-d1lm8b_.ent", "d1feha2.ent-d1n62a2.ent", "d1feha2.ent-d1nekb2.ent", "d1feha2.ent-d1put__.ent", "d1feha2.ent-d1qlab2.ent", "d1feha2.ent-d2pia_3.ent", "d1feha2.ent-d2sak__.ent", "d1feha2.ent-d3seb_2.ent", "d1feha2.ent-d3tss_2.ent", "d1feha3.ent-d1fxd__.ent", "d1feha3.ent-d1fxra_.ent", "d1feha3.ent-d1gtea5.ent", "d1feha3.ent-d1h0hb_.ent", "d1feha3.ent-d1h98a_.ent", "d1feha3.ent-d1hfel2.ent", "d1feha3.ent-d1iqza_.ent", "d1feha3.ent-d1jb0c_.ent", "d1feha3.ent-d1jnrb_.ent", "d1feha3.ent-d1keka5.ent", "d1feha3.ent-d1kqfb1.ent", "d1feha3.ent-d2fdn__.ent", "d1feha3.ent-d7fd1a_.ent", "d1feua_.ent-d1gtra1.ent", "d1fexa_.ent-d1e3oc1.ent", "d1fexa_.ent-d1ig7a_.ent", "d1feza_.ent-d1k1ea_.ent", "d1feza_.ent-d1l6ra_.ent", "d1feza_.ent-d1mh9a_.ent", "d1feza_.ent-d1qq5a_.ent", "d1feza_.ent-d1zrn__.ent", "d1ffta_.ent-d1ocra_.ent", "d1fftb2.ent-d1m56b2.ent", "d1fftb2.ent-d1ocrb2.ent", "d1fftc_.ent-d1m56c_.ent", "d1fftc_.ent-d1ocrc_.ent", "d1ffya1.ent-d1ile_1.ent", "d1ffya1.ent-d1iq0a1.ent", "d1ffya1.ent-d1ivsa2.ent", "d1ffya1.ent-d1li5a1.ent", "d1ffya2.ent-d1h3na2.ent", "d1ffya2.ent-d1ile_2.ent", "d1ffya2.ent-d1ivsa3.ent", "d1ffya3.ent-d1g8fa2.ent", "d1ffya3.ent-d1gtra2.ent", "d1ffya3.ent-d1h3fa1.ent", "d1ffya3.ent-d1h3na3.ent", "d1ffya3.ent-d1ihoa_.ent", "d1ffya3.ent-d1ile_3.ent", "d1ffya3.ent-d1iq0a2.ent", "d1ffya3.ent-d1irxa2.ent", "d1ffya3.ent-d1ivsa4.ent", "d1ffya3.ent-d1j09a2.ent", "d1ffya3.ent-d1jhda2.ent", "d1ffya3.ent-d1jila_.ent", "d1ffya3.ent-d1k4ma_.ent", "d1ffya3.ent-d1kama_.ent", "d1ffya3.ent-d1kqna_.ent", "d1ffya3.ent-d1li5a2.ent", "d1ffya3.ent-d1n3la_.ent", "d1ffya3.ent-d1qjca_.ent", "d1fgja_.ent-d1fs7a_.ent", "d1fgja_.ent-d1ft5a_.ent", "d1fgja_.ent-d1gu6a_.ent", "d1fgja_.ent-d1gyoa_.ent", "d1fgja_.ent-d1h21a_.ent", "d1fgja_.ent-d1h29a_.ent", "d1fgja_.ent-d1hh5a_.ent", "d1fgja_.ent-d1kssa1.ent", "d1fgja_.ent-d1m1qa_.ent", "d1fgja_.ent-d1qo8a1.ent", "d1fgja_.ent-d1wad__.ent", "d1fgja_.ent-d2ctha_.ent", "d1fgja_.ent-d2cy3__.ent", "d1fgja_.ent-d3caoa_.ent", "d1fgja_.ent-d3cyr__.ent", "d1fgka_.ent-d1ia9a_.ent", "d1fgka_.ent-d1iepa_.ent", "d1fgka_.ent-d1jpaa_.ent", "d1fgka_.ent-d1lufa_.ent", "d1fgka_.ent-d1phk__.ent", "d1fgua1.ent-d1ewia_.ent", "d1fgua1.ent-d1iyjb3.ent", "d1fgua1.ent-d1jjcb3.ent", "d1fgua1.ent-d1quqb_.ent", "d1fgua2.ent-d1ewia_.ent", "d1fgua2.ent-d1fgua1.ent", "d1fgua2.ent-d1fjgl_.ent", "d1fgua2.ent-d1iyjb3.ent", "d1fgua2.ent-d1jb3a_.ent", "d1fgua2.ent-d1jb7a2.ent", "d1fgua2.ent-d1jjcb3.ent", "d1fgua2.ent-d1k28a1.ent", "d1fgua2.ent-d1quqa_.ent", "d1fgua2.ent-d1quqb_.ent", "d1fgua2.ent-d3seb_1.ent", "d1fh0a_.ent-d1g0da4.ent", "d1fh0a_.ent-d1gmya_.ent", "d1fh0a_.ent-d1gx3a_.ent", "d1fh0a_.ent-d1iu4a_.ent", "d1fh0a_.ent-d1kxra_.ent", "d1fh0a_.ent-d1l9na4.ent", "d1fh0a_.ent-d1me4a_.ent", "d1fh0a_.ent-d1nbfa_.ent", "d1fh0a_.ent-d1ppn__.ent", "d1fh0a_.ent-d1qmya_.ent", "d1fh0a_.ent-d1uch__.ent", "d1fh0a_.ent-d2act__.ent", "d1fh0a_.ent-d2cb5a_.ent", "d1fh0a_.ent-d3gcb__.ent", "d1fh0a_.ent-d7pcka_.ent", "d1fhe_2.ent-d1aqwa2.ent", "d1fhe_2.ent-d1iloa_.ent", "d1fhe_2.ent-d1k3ya2.ent", "d1fhoa_.ent-d1gg3a2.ent", "d1fhoa_.ent-d1h4ra2.ent", "d1fhoa_.ent-d1k5db_.ent", "d1fhoa_.ent-d1ki1b2.ent", "d1fhoa_.ent-d1mai__.ent", "d1fhoa_.ent-d1mixa2.ent", "d1fhoa_.ent-d1mkea1.ent", "d1fhoa_.ent-d1pls__.ent", "d1fhoa_.ent-d1qqga1.ent", "d1fhoa_.ent-d1qqga2.ent", "d1fhoa_.ent-d1shca_.ent", "d1fhua1.ent-d1jpdx1.ent", "d1fhua1.ent-d1jpma1.ent", "d1fhua1.ent-d1muca1.ent", "d1fhua1.ent-d1onea1.ent", "d1fhua1.ent-d2chr_1.ent", "d1fhua1.ent-d2mnr_1.ent", "d1fhua2.ent-d1jpdx2.ent", "d1fhua2.ent-d1jpma2.ent", "d1fhua2.ent-d1muca2.ent", "d1fhua2.ent-d1onea2.ent", "d1fhua2.ent-d2chr_2.ent", "d1fhua2.ent-d2mnr_2.ent", "d1fi2a_.ent-d1ft9a2.ent", "d1fi2a_.ent-d1fxza1.ent", "d1fi2a_.ent-d1fxza2.ent", "d1fi2a_.ent-d1gp6a_.ent", "d1fi2a_.ent-d1gy9a_.ent", "d1fi2a_.ent-d1h2ka_.ent", "d1fi2a_.ent-d1hw5a2.ent", "d1fi2a_.ent-d1ig0a1.ent", "d1fi2a_.ent-d1jr7a_.ent", "d1fi2a_.ent-d1juha_.ent", "d1fi2a_.ent-d1lrha_.ent", "d1fi2a_.ent-d1m4oa_.ent", "d1fi2a_.ent-d1pmi__.ent", "d1fi2a_.ent-d1wapa_.ent", "d1fi2a_.ent-d2arca_.ent", "d1fi2a_.ent-d2phla1.ent", "d1fi2a_.ent-d2phla2.ent", "d1fi6a_.ent-d1h8ba_.ent", "d1fi6a_.ent-d1iioa_.ent", "d1fi6a_.ent-d1j7qa_.ent", "d1fi6a_.ent-d1k94a_.ent", "d1fi6a_.ent-d1m45a_.ent", "d1fi6a_.ent-d1psra_.ent", "d1fi6a_.ent-d1qasa1.ent", "d1fi6a_.ent-d1rec__.ent", "d1fi6a_.ent-d1sra__.ent", "d1fi6a_.ent-d2cbla1.ent", "d1fi6a_.ent-d2pvba_.ent", "d1fi6a_.ent-d2sas__.ent", "d1fi6a_.ent-d2scpa_.ent", "d1fioa_.ent-d1hs7a_.ent", "d1fioa_.ent-d1lvfa_.ent", "d1fiua_.ent-d1gefa_.ent", "d1fiua_.ent-d1hh1a_.ent", "d1fiua_.ent-d1kc6a_.ent", "d1fiua_.ent-d1knva_.ent", "d1fiua_.ent-d1m0da_.ent", "d1fiua_.ent-d1vsra_.ent", "d1fiua_.ent-d2foka4.ent", "d1fiua_.ent-d3pvia_.ent", "d1fj2a_.ent-d1gkla_.ent", "d1fj2a_.ent-d1hlga_.ent", "d1fj2a_.ent-d1imja_.ent", "d1fj2a_.ent-d1ispa_.ent", "d1fj2a_.ent-d1jfra_.ent", "d1fj2a_.ent-d1ju3a2.ent", "d1fj2a_.ent-d1ku0a_.ent", "d1fj2a_.ent-d1l7aa_.ent", "d1fj2a_.ent-d1lzla_.ent", "d1fj2a_.ent-d1mnaa_.ent", "d1fj2a_.ent-d1n1ma2.ent", "d1fj2a_.ent-d1qj4a_.ent", "d1fj2a_.ent-d1qlwa_.ent", "d1fj2a_.ent-d1qo7a_.ent", "d1fj2a_.ent-d1tca__.ent", "d1fj2a_.ent-d1thta_.ent", "d1fj2a_.ent-d3tgl__.ent", "d1fj7a_.ent-d1fjeb2.ent", "d1fj7a_.ent-d1fxla1.ent", "d1fj7a_.ent-d1fxla2.ent", "d1fj7a_.ent-d1h6kx_.ent", "d1fj7a_.ent-d1hd1a_.ent", "d1fj7a_.ent-d1iqta_.ent", "d1fj7a_.ent-d1jmta_.ent", "d1fj7a_.ent-d1koha2.ent", "d1fj7a_.ent-d1l3ka1.ent", "d1fj7a_.ent-d1l3ka2.ent", "d1fj7a_.ent-d1nu4a_.ent", "d1fj7a_.ent-d1qm9a1.ent", "d1fj7a_.ent-d1qm9a2.ent", "d1fj7a_.ent-d1u2fa_.ent", "d1fj7a_.ent-d2msta_.ent", "d1fj7a_.ent-d2u1a__.ent", "d1fj7a_.ent-d2u2fa_.ent", "d1fjeb2.ent-d1fxla1.ent", "d1fjeb2.ent-d1fxla2.ent", "d1fjeb2.ent-d1h6kx_.ent", "d1fjeb2.ent-d1hd1a_.ent", "d1fjeb2.ent-d1iqta_.ent", "d1fjeb2.ent-d1jmta_.ent", "d1fjeb2.ent-d1koha2.ent", "d1fjeb2.ent-d1l3ka1.ent", "d1fjeb2.ent-d1l3ka2.ent", "d1fjeb2.ent-d1nu4a_.ent", "d1fjeb2.ent-d1qm9a1.ent", "d1fjeb2.ent-d1qm9a2.ent", "d1fjeb2.ent-d1u2fa_.ent", "d1fjeb2.ent-d2msta_.ent", "d1fjeb2.ent-d2u1a__.ent", "d1fjeb2.ent-d2u2fa_.ent", "d1fjgb_.ent-d1cex__.ent", "d1fjgb_.ent-d1cf9a1.ent", "d1fjgb_.ent-d1e5da1.ent", "d1fjgb_.ent-d1es9a_.ent", "d1fjgb_.ent-d1euca2.ent", "d1fjgb_.ent-d1f2va_.ent", "d1fjgb_.ent-d1f4pa_.ent", "d1fjgb_.ent-d1f8ya_.ent", "d1fjgb_.ent-d1fuea_.ent", "d1fjgb_.ent-d1fyea_.ent", "d1fjgb_.ent-d1g66a_.ent", "d1fjgb_.ent-d1h05a_.ent", "d1fjgb_.ent-d1iexa2.ent", "d1fjgb_.ent-d1k7ca_.ent", "d1fjgb_.ent-d1kwga3.ent", "d1fjgb_.ent-d1l7da2.ent", "d1fjgb_.ent-d1qo0d_.ent", "d1fjgb_.ent-d2naca2.ent", "d1fjgb_.ent-d7reqb2.ent", "d1fjgc1.ent-d1gpma3.ent", "d1fjgc1.ent-d1hh2p2.ent", "d1fjgc1.ent-d1ib8a2.ent", "d1fjgc1.ent-d1iw5a_.ent", "d1fjgc1.ent-d1k0ra2.ent", "d1fjgc1.ent-d1k0ra3.ent", "d1fjgc1.ent-d1mkya3.ent", "d1fjgc1.ent-d3proc1.ent", "d1fjgc1.ent-d3proc2.ent", "d1fjgd_.ent-d1h3fa2.ent", "d1fjgd_.ent-d1jh3a_.ent", "d1fjge2.ent-d1kn0a_.ent", "d1fjge2.ent-d1o0wa2.ent", "d1fjge2.ent-d1pkp_2.ent", "d1fjge2.ent-d1qu6a1.ent", "d1fjge2.ent-d1qu6a2.ent", "d1fjge2.ent-d1stu__.ent", "d1fjgi_.ent-d1h72c1.ent", "d1fjgi_.ent-d1kija1.ent", "d1fjgi_.ent-d1kkha1.ent", "d1fjgi_.ent-d1kvka1.ent", "d1fjgi_.ent-d1mu5a2.ent", "d1fjgi_.ent-d1n0ua3.ent", "d1fjgi_.ent-d1pkp_1.ent", "d1fjgk_.ent-d1ilya_.ent", "d1fjgk_.ent-d1jj2m_.ent", "d1fjgl_.ent-d1ewia_.ent", "d1fjgl_.ent-d1fgua1.ent", "d1fjgl_.ent-d1iyjb3.ent", "d1fjgl_.ent-d1jb7a2.ent", "d1fjgl_.ent-d1jjcb3.ent", "d1fjgl_.ent-d1k28a1.ent", "d1fjgl_.ent-d1quqa_.ent", "d1fjgl_.ent-d1quqb_.ent", "d1fjgl_.ent-d3seb_1.ent", "d1fjgm_.ent-d1k3xa1.ent", "d1fjgm_.ent-d1k82a1.ent", "d1fjgm_.ent-d1l1za1.ent", "d1fjgm_.ent-d1mu5a1.ent", "d1fjgm_.ent-d1nnja1.ent", "d1fjgn_.ent-d1g47a1.ent", "d1fjgn_.ent-d1g47a2.ent", "d1fjgn_.ent-d1gnf__.ent", "d1fjgn_.ent-d1ibia2.ent", "d1fjgn_.ent-d1iml_2.ent", "d1fjgn_.ent-d1jj2t_.ent", "d1fjgn_.ent-d1k3xa3.ent", "d1fjgn_.ent-d1kb2a_.ent", "d1fjgn_.ent-d1l1za3.ent", "d1fjgn_.ent-d1lata_.ent", "d1fjgn_.ent-d1lv3a_.ent", "d1fjgn_.ent-d1zfo__.ent", "d1fjgn_.ent-d2nllb_.ent", "d1fjgn_.ent-d3gata_.ent", "d1fjgn_.ent-d7gata_.ent", "d1fjgt_.ent-d1g73a_.ent", "d1fjgt_.ent-d1hcia1.ent", "d1fjgt_.ent-d1hcia4.ent", "d1fjgt_.ent-d1hx1b_.ent", "d1fjgt_.ent-d1jnra1.ent", "d1fjgt_.ent-d1m7ka_.ent", "d1fjgt_.ent-d1qlaa1.ent", "d1fjgt_.ent-d1quua1.ent", "d1fjgt_.ent-d1quua2.ent", "d1fjgt_.ent-d2spca_.ent", "d1fjla_.ent-d1b8ia_.ent", "d1fjla_.ent-d1bl0a2.ent", "d1fjla_.ent-d1e3oc1.ent", "d1fjla_.ent-d1fexa_.ent", "d1fjla_.ent-d1g2ha_.ent", "d1fjla_.ent-d1hlva2.ent", "d1fjla_.ent-d1ig7a_.ent", "d1fjla_.ent-d1irza_.ent", "d1fjla_.ent-d1k61a_.ent", "d1fjla_.ent-d1k78a1.ent", "d1fjla_.ent-d1k78a2.ent", "d1fjna_.ent-d1gps__.ent", "d1fjna_.ent-d1i2ua_.ent", "d1fjna_.ent-d1ica__.ent", "d1fjna_.ent-d1jkza_.ent", "d1fjna_.ent-d1jxca_.ent", "d1fjna_.ent-d1myn__.ent", "d1fjna_.ent-d1npia_.ent", "d1fjna_.ent-d1nrb__.ent", "d1fjna_.ent-d1qkya_.ent", "d1fjna_.ent-d1sco__.ent", "d1fjna_.ent-d1scy__.ent", "d1fjna_.ent-d1sis__.ent", "d1fjna_.ent-d1tsk__.ent", "d1fjna_.ent-d2sn3__.ent", "d1fjsa_.ent-d1azza_.ent", "d1fjsa_.ent-d1bio__.ent", "d1fjsa_.ent-d1cgha_.ent", "d1fjsa_.ent-d1gdna_.ent", "d1fjsa_.ent-d1gpza1.ent", "d1fjsa_.ent-d1hj9a_.ent", "d1fjsa_.ent-d2hlca_.ent", "d1fjsl_.ent-d1b9wa1.ent", "d1fjsl_.ent-d1b9wa2.ent", "d1fjsl_.ent-d1ceja1.ent", "d1fjsl_.ent-d1ceja2.ent", "d1fjsl_.ent-d1cvua2.ent", "d1fjsl_.ent-d1dx5i1.ent", "d1fjsl_.ent-d1emo_1.ent", "d1fjsl_.ent-d1hz8a1.ent", "d1fjsl_.ent-d1hz8a2.ent", "d1fjsl_.ent-d1ijqa2.ent", "d1fjsl_.ent-d1ioxa_.ent", "d1fjsl_.ent-d1jl9a_.ent", "d1fjsl_.ent-d1klo_3.ent", "d1fjsl_.ent-d1l3ya_.ent", "d1fjsl_.ent-d1m1xb5.ent", "d1fjsl_.ent-d1tpg_1.ent", "d1fjsl_.ent-d1urk_1.ent", "d1fjsl_.ent-d3tgf__.ent", "d1fk5a_.ent-d1hssa_.ent", "d1fk5a_.ent-d1hyp__.ent", "d1fk5a_.ent-d1l6ha_.ent", "d1fkna_.ent-d1fmb__.ent", "d1fkna_.ent-d1idaa_.ent", "d1fkna_.ent-d1j71a_.ent", "d1fkna_.ent-d1kzka_.ent", "d1fkna_.ent-d1lf2a_.ent", "d1fkna_.ent-d1mpp__.ent", "d1fkna_.ent-d1nsoa_.ent", "d1fkna_.ent-d2apr__.ent", "d1fkna_.ent-d2rspa_.ent", "d1fkna_.ent-d3psg__.ent", "d1fkna_.ent-d4fiv__.ent", "d1fl0a_.ent-d1b3qa2.ent", "d1fl0a_.ent-d1d7qa_.ent", "d1fl0a_.ent-d1e1oa1.ent", "d1fl0a_.ent-d1eova1.ent", "d1fl0a_.ent-d1ewia_.ent", "d1fl0a_.ent-d1fgua1.ent", "d1fl0a_.ent-d1fgua2.ent", "d1fl0a_.ent-d1fjgl_.ent", "d1fl0a_.ent-d1i50h_.ent", "d1fl0a_.ent-d1iyjb3.ent", "d1fl0a_.ent-d1iyjb5.ent", "d1fl0a_.ent-d1jb3a_.ent", "d1fl0a_.ent-d1jb7a2.ent", "d1fl0a_.ent-d1jjcb3.ent", "d1fl0a_.ent-d1k28a1.ent", "d1fl0a_.ent-d1quqa_.ent", "d1fl0a_.ent-d1quqb_.ent", "d1fl0a_.ent-d1qvca_.ent", "d1fl0a_.ent-d1sty__.ent", "d1fl0a_.ent-d3seb_1.ent", "d1fl1a_.ent-d1iega_.ent", "d1fl1a_.ent-d1o6ea_.ent", "d1fl2a2.ent-d1gtea3.ent", "d1fl2a2.ent-d1jnra2.ent", "d1fl2a2.ent-d1ju2a1.ent", "d1fl2a2.ent-d1k0ia1.ent", "d1fl2a2.ent-d1kssa2.ent", "d1fl2a2.ent-d1l9ea1.ent", "d1fl2a2.ent-d1lqta1.ent", "d1fl2a2.ent-d1m6ia1.ent", "d1fl2a2.ent-d1m6ia2.ent", "d1fl2a2.ent-d1nhp_1.ent", "d1fl2a2.ent-d1nhp_2.ent", "d1fl2a2.ent-d1o94a2.ent", "d1fl2a2.ent-d3grs_1.ent", "d1fl2a2.ent-d3grs_2.ent", "d1fl7b_.ent-d1fltv_.ent", "d1fl7b_.ent-d1hcna_.ent", "d1fl7b_.ent-d1hcnb_.ent", "d1fl7b_.ent-d1jpya_.ent", "d1fl7b_.ent-d1m4ua_.ent", "d1fl7b_.ent-d1m4ul_.ent", "d1fl7b_.ent-d1pdga_.ent", "d1fl7b_.ent-d2tgi__.ent", "d1flca1.ent-d1jsda_.ent", "d1flca1.ent-d1jsma_.ent", "d1flca1.ent-d1qhda2.ent", "d1flca1.ent-d2viua_.ent", "d1flca2.ent-d1b3ra2.ent", "d1flca2.ent-d1cex__.ent", "d1flca2.ent-d1cf9a1.ent", "d1flca2.ent-d1e5da1.ent", "d1flca2.ent-d1es9a_.ent", "d1flca2.ent-d1euca2.ent", "d1flca2.ent-d1f2va_.ent", "d1flca2.ent-d1f4pa_.ent", "d1flca2.ent-d1f8ya_.ent", "d1flca2.ent-d1fjgb_.ent", "d1flca2.ent-d1fuea_.ent", "d1flca2.ent-d1fyea_.ent", "d1flca2.ent-d1g66a_.ent", "d1flca2.ent-d1h05a_.ent", "d1flca2.ent-d1iexa2.ent", "d1flca2.ent-d1k7ca_.ent", "d1flca2.ent-d1kwga3.ent", "d1flca2.ent-d1l7da2.ent", "d1flca2.ent-d1qo0d_.ent", "d1flca2.ent-d2naca2.ent", "d1flca2.ent-d7reqb2.ent", "d1flei_.ent-d1b9wa1.ent", "d1flei_.ent-d1b9wa2.ent", "d1flei_.ent-d1cixa_.ent", "d1flei_.ent-d1g9pa_.ent", "d1flei_.ent-d1gps__.ent", "d1flei_.ent-d1h59b_.ent", "d1flei_.ent-d1hyka_.ent", "d1flei_.ent-d1i2ua_.ent", "d1flei_.ent-d1imt_2.ent", "d1flei_.ent-d1jkza_.ent", "d1flei_.ent-d1lpba2.ent", "d1flma_.ent-d1i0ra_.ent", "d1flma_.ent-d1nrga_.ent", "d1floa1.ent-d1go3f_.ent", "d1floa1.ent-d1jmsa1.ent", "d1floa1.ent-d1jmsa3.ent", "d1floa1.ent-d1jyga_.ent", "d1floa1.ent-d1kfta_.ent", "d1floa1.ent-d1lb2b_.ent", "d1floa1.ent-d1tfr_1.ent", "d1fltv_.ent-d1hcna_.ent", "d1fltv_.ent-d1hcnb_.ent", "d1fltv_.ent-d1jpya_.ent", "d1fltv_.ent-d1m4ua_.ent", "d1fltv_.ent-d1m4ul_.ent", "d1fltv_.ent-d1pdga_.ent", "d1fltv_.ent-d2tgi__.ent", "d1fm0d_.ent-d1jsba_.ent", "d1fm0e_.ent-d1jj2h_.ent", "d1fm0e_.ent-d1n62b1.ent", "d1fm0e_.ent-d1qpoa2.ent", "d1fm4a_.ent-d1icxa_.ent", "d1fm4a_.ent-d1jssa_.ent", "d1fm4a_.ent-d1k2yx4.ent", "d1fm4a_.ent-d1kcma_.ent", "d1fm4a_.ent-d1ko9a2.ent", "d1fm4a_.ent-d1ln1a_.ent", "d1fm4a_.ent-d1mpga2.ent", "d1fm4a_.ent-d1ytba1.ent", "d1fm4a_.ent-d3pmga4.ent", "d1fmb__.ent-d1idaa_.ent", "d1fmb__.ent-d1j71a_.ent", "d1fmb__.ent-d1kzka_.ent", "d1fmb__.ent-d1lf2a_.ent", "d1fmb__.ent-d1mpp__.ent", "d1fmb__.ent-d1nsoa_.ent", "d1fmb__.ent-d2apr__.ent", "d1fmb__.ent-d2rspa_.ent", "d1fmb__.ent-d3psg__.ent", "d1fmb__.ent-d4fiv__.ent", "d1fmja_.ent-d1bg2__.ent", "d1fmja_.ent-d1c4oa1.ent", "d1fmja_.ent-d1e2ka_.ent", "d1fmja_.ent-d1f9va_.ent", "d1fmja_.ent-d1g41a_.ent", "d1fmja_.ent-d1g8pa_.ent", "d1fmja_.ent-d1i6ia_.ent", "d1fmja_.ent-d1ii6a_.ent", "d1fmja_.ent-d1ksfx3.ent", "d1fmja_.ent-d1n0ua2.ent", "d1fmja_.ent-d1pjr_1.ent", "d1fmja_.ent-d1pjr_2.ent", "d1fmja_.ent-d1uaaa1.ent", "d1fmja_.ent-d1uaaa2.ent", "d1fmk_1.ent-d1gcqa_.ent", "d1fmk_1.ent-d1gcqc_.ent", "d1fmk_1.ent-d1gl5a_.ent", "d1fmk_1.ent-d1gria1.ent", "d1fmk_1.ent-d1h92a_.ent", "d1fmk_1.ent-d1i07a_.ent", "d1fmk_1.ent-d1i1ja_.ent", "d1fmk_1.ent-d1jo8a_.ent", "d1fmk_1.ent-d1jqqa_.ent", "d1fmk_1.ent-d1k4us_.ent", "d1fmk_1.ent-d1kjwa1.ent", "d1fmk_1.ent-d1neb__.ent", "d1fmk_1.ent-d1pht__.ent", "d1fmk_1.ent-d1pwt__.ent", "d1fmk_1.ent-d1qcfa1.ent", "d1fmk_1.ent-d1ycsb2.ent", "d1fmk_1.ent-d2hsp__.ent", "d1fmta2.ent-d1jkxa_.ent", "d1fmta2.ent-d1meoa_.ent", "d1fmya_.ent-d1ji9a_.ent", "d1fmya_.ent-d1jjda_.ent", "d1fmya_.ent-d1qjka_.ent", "d1fmya_.ent-d4mt2__.ent", "d1fnc_1.ent-d1i7pa1.ent", "d1fnc_1.ent-d1i8da1.ent", "d1fnc_1.ent-d1i8da2.ent", "d1fnc_1.ent-d1ja1a1.ent", "d1fnc_1.ent-d1jb9a1.ent", "d1fnc_1.ent-d1krha1.ent", "d1fnc_1.ent-d1kzla1.ent", "d1fnc_1.ent-d1kzla2.ent", "d1fnc_1.ent-d1qfja1.ent", "d1fnc_1.ent-d1que_1.ent", "d1fnc_1.ent-d2cnd_1.ent", "d1fnc_1.ent-d2pia_1.ent", "d1fnga2.ent-d1fngb2.ent", "d1fnga2.ent-d1gzqa2.ent", "d1fnga2.ent-d1hdma2.ent", "d1fnga2.ent-d1hdmb2.ent", "d1fnga2.ent-d1hyrc2.ent", "d1fnga2.ent-d1iaka2.ent", "d1fnga2.ent-d1jfma_.ent", "d1fnga2.ent-d1k5na2.ent", "d1fnga2.ent-d1kcgc_.ent", "d1fnga2.ent-d1lqva_.ent", "d1fnga2.ent-d1zaga2.ent", "d1fnga2.ent-d3frua2.ent", "d1fngb2.ent-d1gzqa2.ent", "d1fngb2.ent-d1hdma2.ent", "d1fngb2.ent-d1hdmb2.ent", "d1fngb2.ent-d1hyrc2.ent", "d1fngb2.ent-d1iaka2.ent", "d1fngb2.ent-d1jfma_.ent", "d1fngb2.ent-d1k5na2.ent", "d1fngb2.ent-d1kcgc_.ent", "d1fngb2.ent-d1lqva_.ent", "d1fngb2.ent-d1zaga2.ent", "d1fngb2.ent-d3frua2.ent", "d1fnma4.ent-d1n0ua4.ent", "d1fnma4.ent-d1n0ua5.ent", "d1fnna1.ent-d1bjaa_.ent", "d1fnna1.ent-d1d5va_.ent", "d1fnna1.ent-d1e17a_.ent", "d1fnna1.ent-d1f1za1.ent", "d1fnna1.ent-d1fp2a1.ent", "d1fnna1.ent-d1fsha_.ent", "d1fnna1.ent-d1igna2.ent", "d1fnna1.ent-d1jhga_.ent", "d1fnna1.ent-d1ka8a_.ent", "d1fnna1.ent-d1ldja1.ent", "d1fnna1.ent-d1opc__.ent", "d1fnna1.ent-d1repc2.ent", "d1fnna1.ent-d1smta_.ent", "d1fnna1.ent-d2ezl__.ent", "d1fnna1.ent-d2foka3.ent", "d1fnna2.ent-d1cr1a_.ent", "d1fnna2.ent-d1e69a_.ent", "d1fnna2.ent-d1f5na2.ent", "d1fnna2.ent-d1g8ya_.ent", "d1fnna2.ent-d1gm5a3.ent", "d1fnna2.ent-d1lv7a_.ent", "d1fnna2.ent-d1m6na3.ent", "d1fnua1.ent-d1m4va1.ent", "d1fnua1.ent-d1prtb1.ent", "d1fnua1.ent-d1prtd_.ent", "d1fnua1.ent-d1prtf_.ent", "d1fnua1.ent-d1tiid_.ent", "d1fnua1.ent-d3chbd_.ent", "d1fnua1.ent-d3seb_1.ent", "d1fnua1.ent-d3tss_1.ent", "d1fo0a_.ent-d1akjd_.ent", "d1fo0a_.ent-d1b88a_.ent", "d1fo0a_.ent-d1bec_1.ent", "d1fo0a_.ent-d1c5ch1.ent", "d1fo0a_.ent-d1dlfl_.ent", "d1fo0a_.ent-d1h5ba_.ent", "d1fo0a_.ent-d1neu__.ent", "d1fo0a_.ent-d1nfdb1.ent", "d1fo0a_.ent-d1qfoa_.ent", "d1fo0a_.ent-d2rhe__.ent", "d1fo3a_.ent-d1krea_.ent", "d1fo4a1.ent-d1hlra1.ent", "d1fo4a1.ent-d1n62a1.ent", "d1fo4a2.ent-d1hlra2.ent", "d1fo4a2.ent-d1i7ha_.ent", "d1fo4a2.ent-d1jq4a_.ent", "d1fo4a2.ent-d1jroa2.ent", "d1fo4a2.ent-d1kf6b2.ent", "d1fo4a2.ent-d1krha3.ent", "d1fo4a2.ent-d1l5pa_.ent", "d1fo4a2.ent-d1n62a2.ent", "d1fo4a2.ent-d1nekb2.ent", "d1fo4a2.ent-d1put__.ent", "d1fo4a2.ent-d1qlab2.ent", "d1fo4a2.ent-d2pia_3.ent", "d1fo4a3.ent-d1hlra3.ent", "d1fo4a3.ent-d1jrob1.ent", "d1fo4a3.ent-d1n62b1.ent", "d1fo4a4.ent-d1jroa3.ent", "d1fo4a4.ent-d1n62c1.ent", "d1fo4a5.ent-d1hlra4.ent", "d1fo4a5.ent-d1n62b2.ent", "d1fo4a6.ent-d1hska1.ent", "d1fo4a6.ent-d1i19a2.ent", "d1fo4a6.ent-d1jroa4.ent", "d1fo4a6.ent-d1n62c2.ent", "d1fo4a6.ent-d1uxy_1.ent", "d1fo8a_.ent-d1fxoa_.ent", "d1fo8a_.ent-d1h7ea_.ent", "d1fo8a_.ent-d1hm9a2.ent", "d1fo8a_.ent-d1hv9a2.ent", "d1fo8a_.ent-d1i52a_.ent", "d1fo8a_.ent-d1jv1a_.ent", "d1fo8a_.ent-d1k4va_.ent", "d1fo8a_.ent-d1kwsa_.ent", "d1fo8a_.ent-d1ll2a_.ent", "d1fo8a_.ent-d1lzja_.ent", "d1fo8a_.ent-d1nf5b_.ent", "d1fo8a_.ent-d1qg8a_.ent", "d1foha3.ent-d1a8l_1.ent", "d1foha3.ent-d1a8l_2.ent", "d1foha3.ent-d1a8y_1.ent", "d1foha3.ent-d1a8y_2.ent", "d1foha3.ent-d1a8y_3.ent", "d1foha3.ent-d1aba__.ent", "d1foha3.ent-d1aqwa2.ent", "d1foha3.ent-d1bed_2.ent", "d1foha3.ent-d1bjx__.ent", "d1foha3.ent-d1e6ba2.ent", "d1foha3.ent-d1eeja1.ent", "d1foha3.ent-d1ep7a_.ent", "d1foha3.ent-d1erv__.ent", "d1foha3.ent-d1f9ma_.ent", "d1foha3.ent-d1fb6a_.ent", "d1foha3.ent-d1fhe_2.ent", "d1foha3.ent-d1fvka2.ent", "d1foha3.ent-d1g7ea_.ent", "d1foha3.ent-d1gh2a_.ent", "d1foha3.ent-d1hd2a_.ent", "d1foha3.ent-d1hyua4.ent", "d1foha3.ent-d1i5ga_.ent", "d1foha3.ent-d1iloa_.ent", "d1foha3.ent-d1jfua_.ent", "d1foha3.ent-d1k0ma2.ent", "d1foha3.ent-d1k3ya2.ent", "d1foha3.ent-d1knga_.ent", "d1foha3.ent-d1kte__.ent", "d1foha3.ent-d1kyga_.ent", "d1foha3.ent-d1m2da_.ent", "d1foha3.ent-d1mek__.ent", "d1foha3.ent-d1qmha1.ent", "d1foha3.ent-d1quwa_.ent", "d1foha3.ent-d1thx__.ent", "d1foha3.ent-d2trxa_.ent", "d1foha4.ent-d1gosa2.ent", "d1foha4.ent-d1gpea2.ent", "d1foha4.ent-d1i8ta2.ent", "d1foha4.ent-d1ju2a2.ent", "d1foha4.ent-d1k0ia2.ent", "d1foha4.ent-d1kdga2.ent", "d1foha4.ent-d1l9ea2.ent", "d1foha4.ent-d1mxta2.ent", "d1foha5.ent-d1b5qa1.ent", "d1foha5.ent-d1chua2.ent", "d1foha5.ent-d1cjca1.ent", "d1foha5.ent-d1d5ta1.ent", "d1foha5.ent-d1ebda1.ent", "d1foha5.ent-d1feca1.ent", "d1foha5.ent-d1h6va1.ent", "d1foha5.ent-d1jeha1.ent", "d1foha5.ent-d1jnra2.ent", "d1foha5.ent-d1ju2a1.ent", "d1foha5.ent-d1k0ia1.ent", "d1foha5.ent-d1kdga1.ent", "d1foha5.ent-d1kf6a2.ent", "d1foha5.ent-d1kssa2.ent", "d1foha5.ent-d1l9ea1.ent", "d1foha5.ent-d1mo9a1.ent", "d1foha5.ent-d1neka2.ent", "d1foha5.ent-d1ojt_1.ent", "d1foha5.ent-d1qlaa2.ent", "d1foha5.ent-d1qo8a2.ent", "d1foha5.ent-d3lada1.ent", "d1fp0a1.ent-d1joca1.ent", "d1fp0a1.ent-d1vfya_.ent", "d1fp1d1.ent-d1bjaa_.ent", "d1fp1d1.ent-d1d5va_.ent", "d1fp1d1.ent-d1e17a_.ent", "d1fp1d1.ent-d1f1za1.ent", "d1fp1d1.ent-d1fnna1.ent", "d1fp1d1.ent-d1fp2a1.ent", "d1fp1d1.ent-d1fsha_.ent", "d1fp1d1.ent-d1fzpb_.ent", "d1fp1d1.ent-d1hks__.ent", "d1fp1d1.ent-d1ig6a_.ent", "d1fp1d1.ent-d1igna2.ent", "d1fp1d1.ent-d1jhga_.ent", "d1fp1d1.ent-d1ka8a_.ent", "d1fp1d1.ent-d1ldja1.ent", "d1fp1d1.ent-d1opc__.ent", "d1fp1d1.ent-d1repc2.ent", "d1fp1d1.ent-d1smta_.ent", "d1fp1d1.ent-d2ezl__.ent", "d1fp1d1.ent-d2foka3.ent", "d1fp1d1.ent-d2irfg_.ent", "d1fp1d2.ent-d1i1na_.ent", "d1fp1d2.ent-d1jg1a_.ent", "d1fp2a1.ent-d1bjaa_.ent", "d1fp2a1.ent-d1d5va_.ent", "d1fp2a1.ent-d1e17a_.ent", "d1fp2a1.ent-d1f1za1.ent", "d1fp2a1.ent-d1fsha_.ent", "d1fp2a1.ent-d1jhga_.ent", "d1fp2a1.ent-d1ka8a_.ent", "d1fp2a1.ent-d1ldja1.ent", "d1fp2a1.ent-d1opc__.ent", "d1fp2a1.ent-d1smta_.ent", "d1fp2a1.ent-d2ezl__.ent", "d1fp2a1.ent-d2foka3.ent", "d1fp2a2.ent-d1fp1d2.ent", "d1fp2a2.ent-d1g38a_.ent", "d1fp2a2.ent-d1g60a_.ent", "d1fp2a2.ent-d1hnna_.ent", "d1fp2a2.ent-d1i1na_.ent", "d1fp2a2.ent-d1i4wa_.ent", "d1fp2a2.ent-d1inla_.ent", "d1fp2a2.ent-d1jg1a_.ent", "d1fp2a2.ent-d1jqea_.ent", "d1fp2a2.ent-d1jsxa_.ent", "d1fp2a2.ent-d1khha_.ent", "d1fp2a2.ent-d1kywa2.ent", "d1fp2a2.ent-d1qama_.ent", "d1fp2a2.ent-d1vid__.ent", "d1fp2a2.ent-d1xvaa_.ent", "d1fp2a2.ent-d2dpma_.ent", "d1fp2a2.ent-d3mag__.ent", "d1fp3a_.ent-d1gai__.ent", "d1fp3a_.ent-d1gxma_.ent", "d1fp3a_.ent-d1h54a1.ent", "d1fp3a_.ent-d1ia6a_.ent", "d1fp3a_.ent-d1ks8a_.ent", "d1fp3a_.ent-d1kwfa_.ent", "d1fp3a_.ent-d1ld8b_.ent", "d1fp3a_.ent-d1lf6a1.ent", "d1fp3a_.ent-d1n1ba1.ent", "d1fp3a_.ent-d1n7oa1.ent", "d1fp3a_.ent-d1qaza_.ent", "d1fp3a_.ent-d2sqca1.ent", "d1fp3a_.ent-d2sqca2.ent", "d1fpoa1.ent-d1fxkc_.ent", "d1fpoa1.ent-d1gh6a_.ent", "d1fpoa1.ent-d1grj_1.ent", "d1fpoa1.ent-d1hdj__.ent", "d1fpoa1.ent-d1ivsa1.ent", "d1fpoa1.ent-d1ix9a1.ent", "d1fpoa1.ent-d1jj2u_.ent", "d1fpoa1.ent-d1k4ta1.ent", "d1fpoa1.ent-d1lrza1.ent", "d1fpoa1.ent-d1seta1.ent", "d1fpoa1.ent-d1xbl__.ent", "d1fpoa2.ent-d1jw2a_.ent", "d1fpoa2.ent-d1mtyg_.ent", "d1fpoa2.ent-d1om2a_.ent", "d1fpza_.ent-d1g4us2.ent", "d1fpza_.ent-d1i9sa_.ent", "d1fpza_.ent-d1ikza_.ent", "d1fpza_.ent-d1jlna_.ent", "d1fpza_.ent-d1lara1.ent", "d1fpza_.ent-d1lara2.ent", "d1fpza_.ent-d1lyva_.ent", "d1fpza_.ent-d1mkp__.ent", "d1fpza_.ent-d1vhra_.ent", "d1fpza_.ent-d1yfoa_.ent", "d1fpza_.ent-d2shpa1.ent", "d1fqta_.ent-d1g8kb_.ent", "d1fqta_.ent-d1jm1a_.ent", "d1fqta_.ent-d1o7na1.ent", "d1fqta_.ent-d1rfs__.ent", "d1fqta_.ent-d1rie__.ent", "d1fqva2.ent-d1igra1.ent", "d1fqva2.ent-d1io0a_.ent", "d1fqva2.ent-d1koha1.ent", "d1fqva2.ent-d1n8yc1.ent", "d1fqva2.ent-d1yrga_.ent", "d1fr3a_.ent-d1g2913.ent", "d1fr3a_.ent-d1g2914.ent", "d1fr3a_.ent-d1guta_.ent", "d1fr3a_.ent-d1h9ma1.ent", "d1fr3a_.ent-d1h9ma2.ent", "d1fr3a_.ent-d1h9ra1.ent", "d1fr3a_.ent-d1h9ra2.ent", "d1fs1b2.ent-d1hv2a_.ent", "d1fs1b2.ent-d1lm8c_.ent", "d1fs1b2.ent-d1t1da_.ent", "d1fs1b2.ent-d3kvt__.ent", "d1fs7a_.ent-d1ft5a_.ent", "d1fs7a_.ent-d1gu6a_.ent", "d1fs7a_.ent-d1gyoa_.ent", "d1fs7a_.ent-d1h21a_.ent", "d1fs7a_.ent-d1h29a_.ent", "d1fs7a_.ent-d1hh5a_.ent", "d1fs7a_.ent-d1kssa1.ent", "d1fs7a_.ent-d1m1qa_.ent", "d1fs7a_.ent-d1qo8a1.ent", "d1fs7a_.ent-d1wad__.ent", "d1fs7a_.ent-d2ctha_.ent", "d1fs7a_.ent-d2cy3__.ent", "d1fs7a_.ent-d3caoa_.ent", "d1fs7a_.ent-d3cyr__.ent", "d1fsea_.ent-d1gxqa_.ent", "d1fsea_.ent-d1opc__.ent", "d1fsga_.ent-d1g2qa_.ent", "d1fsga_.ent-d1g9sa_.ent", "d1fsga_.ent-d1gph11.ent", "d1fsga_.ent-d1hgxa_.ent", "d1fsga_.ent-d1i5ea_.ent", "d1fsga_.ent-d1l1qa_.ent", "d1fsga_.ent-d1lh0a_.ent", "d1fsga_.ent-d1nula_.ent", "d1fsga_.ent-d1qb7a_.ent", "d1fsga_.ent-d1tc1a_.ent", "d1fsha_.ent-d1e17a_.ent", "d1fsha_.ent-d1ldja1.ent", "d1fsz_1.ent-d1tuba1.ent", "d1fsz_1.ent-d1tubb1.ent", "d1fsz_2.ent-d1ipaa2.ent", "d1fsz_2.ent-d1iv3a_.ent", "d1fsz_2.ent-d1jj2f_.ent", "d1fsz_2.ent-d1tuba2.ent", "d1fsz_2.ent-d1tubb2.ent", "d1ft5a_.ent-d1gu6a_.ent", "d1ft5a_.ent-d1gyoa_.ent", "d1ft5a_.ent-d1h21a_.ent", "d1ft5a_.ent-d1h29a_.ent", "d1ft5a_.ent-d1hh5a_.ent", "d1ft5a_.ent-d1kssa1.ent", "d1ft5a_.ent-d1m1qa_.ent", "d1ft5a_.ent-d1qo8a1.ent", "d1ft5a_.ent-d1wad__.ent", "d1ft5a_.ent-d2ctha_.ent", "d1ft5a_.ent-d2cy3__.ent", "d1ft5a_.ent-d3caoa_.ent", "d1ft5a_.ent-d3cyr__.ent", "d1ft9a2.ent-d1fxza1.ent", "d1ft9a2.ent-d1gp6a_.ent", "d1ft9a2.ent-d1gy9a_.ent", "d1ft9a2.ent-d1h2ka_.ent", "d1ft9a2.ent-d1hw5a2.ent", "d1ft9a2.ent-d1ig0a1.ent", "d1ft9a2.ent-d1jr7a_.ent", "d1ft9a2.ent-d1juha_.ent", "d1ft9a2.ent-d1lrha_.ent", "d1ft9a2.ent-d1m4oa_.ent", "d1ft9a2.ent-d1o7fa2.ent", "d1ft9a2.ent-d1o7fa3.ent", "d1ft9a2.ent-d1pmi__.ent", "d1ft9a2.ent-d1rgs_1.ent", "d1ft9a2.ent-d1rgs_2.ent", "d1ft9a2.ent-d1wapa_.ent", "d1ft9a2.ent-d2arca_.ent", "d1ftha_.ent-d1qr0a1.ent", "d1ftha_.ent-d1qr0a2.ent", "d1ftpa_.ent-d1g85a_.ent", "d1ftpa_.ent-d1ggla_.ent", "d1ftpa_.ent-d1gkab_.ent", "d1ftpa_.ent-d1hms__.ent", "d1ftpa_.ent-d1i4ua_.ent", "d1ftpa_.ent-d1ifc__.ent", "d1ftpa_.ent-d1jv4a_.ent", "d1ftpa_.ent-d1koia_.ent", "d1ftpa_.ent-d1kqwa_.ent", "d1ftpa_.ent-d1lf7a_.ent", "d1ftpa_.ent-d1o1va_.ent", "d1ftpa_.ent-d1qfta_.ent", "d1ftpa_.ent-d1qqsa_.ent", "d1ftra1.ent-d1b3ta_.ent", "d1ftra1.ent-d1dqaa1.ent", "d1ftra1.ent-d1ekra_.ent", "d1ftra1.ent-d1ftra2.ent", "d1ftra1.ent-d1gpja3.ent", "d1ftra1.ent-d1h72c2.ent", "d1ftra1.ent-d1qd1a2.ent", "d1ftra1.ent-d1regx_.ent", "d1ftra2.ent-d1b3ta_.ent", "d1ftra2.ent-d1dqaa1.ent", "d1ftra2.ent-d1ekra_.ent", "d1ftra2.ent-d1gpja3.ent", "d1ftra2.ent-d1h72c2.ent", "d1ftra2.ent-d1qd1a2.ent", "d1ftra2.ent-d1regx_.ent", "d1fts_1.ent-d1he1a_.ent", "d1fts_1.ent-d1j8mf1.ent", "d1fts_1.ent-d1jr8a_.ent", "d1fts_1.ent-d1k04a_.ent", "d1fts_1.ent-d1knya1.ent", "d1fts_1.ent-d1ls1a1.ent", "d1fts_1.ent-d1nfn__.ent", "d1fts_1.ent-d1nlxa_.ent", "d1fts_1.ent-d256ba_.ent", "d1fts_1.ent-d2a0b__.ent", "d1fts_1.ent-d2liga_.ent", "d1fts_1.ent-d2mhr__.ent", "d1fts_1.ent-d3fapb_.ent", "d1fu6a_.ent-d1ju5a_.ent", "d1fu6a_.ent-d1jwoa_.ent", "d1fu6a_.ent-d1jyra_.ent", "d1fu6a_.ent-d1lkka_.ent", "d1fu6a_.ent-d1luia_.ent", "d1fu6a_.ent-d1mil__.ent", "d1fu6a_.ent-d1qada_.ent", "d1fu6a_.ent-d2abl_2.ent", "d1fu6a_.ent-d2cbla3.ent", "d1fu6a_.ent-d2plda_.ent", "d1fu6a_.ent-d2shpa3.ent", "d1fu9a_.ent-d1fv5a_.ent", "d1fu9a_.ent-d1ncs__.ent", "d1fu9a_.ent-d1paa__.ent", "d1fu9a_.ent-d1rmd_1.ent", "d1fu9a_.ent-d1tf3a1.ent", "d1fu9a_.ent-d1tf3a2.ent", "d1fu9a_.ent-d1tf3a3.ent", "d1fu9a_.ent-d1tf6a4.ent", "d1fu9a_.ent-d1ubdc3.ent", "d1fu9a_.ent-d1yuja_.ent", "d1fu9a_.ent-d1zfd__.ent", "d1fu9a_.ent-d2drpa1.ent", "d1fu9a_.ent-d2glia1.ent", "d1fu9a_.ent-d2glia2.ent", "d1fu9a_.ent-d2glia4.ent", "d1fu9a_.ent-d5znf__.ent", "d1fuea_.ent-d1cf9a1.ent", "d1fuea_.ent-d1e5da1.ent", "d1fuea_.ent-d1f4pa_.ent", "d1fuea_.ent-d1f8ya_.ent", "d1fuea_.ent-d1h05a_.ent", "d1fuea_.ent-d1ja1a2.ent", "d1fuea_.ent-d1qr2a_.ent", "d1fuea_.ent-d1rcf__.ent", "d1fuea_.ent-d2fcr__.ent", "d1fuea_.ent-d5nul__.ent", "d1fuea_.ent-d7reqb2.ent", "d1fuia1.ent-d1g7sa1.ent", "d1fuia1.ent-d1g7sa2.ent", "d1fuia1.ent-d1i7pa1.ent", "d1fuia1.ent-d1jb9a1.ent", "d1fuia1.ent-d1jj2b_.ent", "d1fuia1.ent-d1kk1a1.ent", "d1fuia1.ent-d1krha1.ent", "d1fuia1.ent-d1kzla1.ent", "d1fuia1.ent-d1kzla2.ent", "d1fuia1.ent-d1n08a_.ent", "d1fuia1.ent-d1n0ua1.ent", "d1fuia1.ent-d1qfja1.ent", "d1fuia1.ent-d2pia_1.ent", "d1fura_.ent-d1hy0a_.ent", "d1fura_.ent-d1jswa_.ent", "d1fv5a_.ent-d1ncs__.ent", "d1fv5a_.ent-d1paa__.ent", "d1fv5a_.ent-d1rmd_1.ent", "d1fv5a_.ent-d1tf3a1.ent", "d1fv5a_.ent-d1tf3a2.ent", "d1fv5a_.ent-d1tf3a3.ent", "d1fv5a_.ent-d1tf6a4.ent", "d1fv5a_.ent-d1ubdc3.ent", "d1fv5a_.ent-d1yuja_.ent", "d1fv5a_.ent-d1zfd__.ent", "d1fv5a_.ent-d2drpa1.ent", "d1fv5a_.ent-d2glia1.ent", "d1fv5a_.ent-d2glia2.ent", "d1fv5a_.ent-d2glia4.ent", "d1fv5a_.ent-d5znf__.ent", "d1fvia2.ent-d1gsa_2.ent", "d1fvia2.ent-d1gsoa3.ent", "d1fvia2.ent-d1iow_2.ent", "d1fvia2.ent-d1kbla3.ent", "d1fvia2.ent-d1kjqa3.ent", "d1fvia2.ent-d1m0wa2.ent", "d1fvka2.ent-d1a8l_1.ent", "d1fvka2.ent-d1a8l_2.ent", "d1fvka2.ent-d1a8y_2.ent", "d1fvka2.ent-d1a8y_3.ent", "d1fvka2.ent-d1aba__.ent", "d1fvka2.ent-d1aqwa2.ent", "d1fvka2.ent-d1bed_2.ent", "d1fvka2.ent-d1bjx__.ent", "d1fvka2.ent-d1e6ba2.ent", "d1fvka2.ent-d1ep7a_.ent", "d1fvka2.ent-d1erv__.ent", "d1fvka2.ent-d1f9ma_.ent", "d1fvka2.ent-d1fb6a_.ent", "d1fvka2.ent-d1fhe_2.ent", "d1fvka2.ent-d1g7ea_.ent", "d1fvka2.ent-d1gh2a_.ent", "d1fvka2.ent-d1hyua4.ent", "d1fvka2.ent-d1iloa_.ent", "d1fvka2.ent-d1k0ma2.ent", "d1fvka2.ent-d1k3ya2.ent", "d1fvka2.ent-d1kte__.ent", "d1fvka2.ent-d1m2da_.ent", "d1fvka2.ent-d1mek__.ent", "d1fvka2.ent-d1qmha1.ent", "d1fvka2.ent-d1quwa_.ent", "d1fvka2.ent-d1thx__.ent", "d1fvka2.ent-d2trxa_.ent", "d1fvqa_.ent-d1jwwa_.ent", "d1fvqa_.ent-d1k0va_.ent", "d1fvqa_.ent-d1mwza_.ent", "d1fvra_.ent-d1a06__.ent", "d1fvra_.ent-d1csn__.ent", "d1fvra_.ent-d1f3mc_.ent", "d1fvra_.ent-d1fgka_.ent", "d1fvra_.ent-d1ia9a_.ent", "d1fvra_.ent-d1iepa_.ent", "d1fvra_.ent-d1jksa_.ent", "d1fvra_.ent-d1jpaa_.ent", "d1fvra_.ent-d1jvpp_.ent", "d1fvra_.ent-d1lufa_.ent", "d1fvra_.ent-d1phk__.ent", "d1fvua_.ent-d1b08a1.ent", "d1fvua_.ent-d1b6e__.ent", "d1fvua_.ent-d1byfa_.ent", "d1fvua_.ent-d1cwva5.ent", "d1fvua_.ent-d1dv8a_.ent", "d1fvua_.ent-d1e87a_.ent", "d1fvua_.ent-d1egia_.ent", "d1fvua_.ent-d1f00i3.ent", "d1fvua_.ent-d1fvub_.ent", "d1fvua_.ent-d1g1ta1.ent", "d1fvua_.ent-d1h8ua_.ent", "d1fvua_.ent-d1hq8a_.ent", "d1fvua_.ent-d1jwia_.ent", "d1fvua_.ent-d1jwib_.ent", "d1fvua_.ent-d1k9ja_.ent", "d1fvua_.ent-d1li1a1.ent", "d1fvua_.ent-d1li1a2.ent", "d1fvua_.ent-d1prtb2.ent", "d1fvua_.ent-d1qo3c_.ent", "d1fvua_.ent-d1tsg__.ent", "d1fvub_.ent-d1cwva5.ent", "d1fvub_.ent-d1e87a_.ent", "d1fvub_.ent-d1f00i3.ent", "d1fvub_.ent-d1g1ta1.ent", "d1fvub_.ent-d1h8ua_.ent", "d1fvub_.ent-d1li1a1.ent", "d1fvub_.ent-d1li1a2.ent", "d1fvub_.ent-d1prtb2.ent", "d1fvub_.ent-d1tsg__.ent", "d1fw1a1.ent-d1g7oa1.ent", "d1fw1a1.ent-d1glqa1.ent", "d1fw1a1.ent-d1gnwa1.ent", "d1fw1a1.ent-d1gula1.ent", "d1fw1a1.ent-d1gwca1.ent", "d1fw1a1.ent-d1jlva1.ent", "d1fw1a1.ent-d1k0da1.ent", "d1fw1a1.ent-d1k0ma1.ent", "d1fw1a1.ent-d1k3ya1.ent", "d1fw1a1.ent-d1ljra1.ent", "d1fw1a1.ent-d1m0ua1.ent", "d1fw1a1.ent-d1pd211.ent", "d1fw1a1.ent-d1pmt_1.ent", "d1fw1a1.ent-d2gsq_1.ent", "d1fw1a1.ent-d2gsta1.ent", "d1fwxa2.ent-d1gxra_.ent", "d1fwxa2.ent-d1jmxb_.ent", "d1fwxa2.ent-d1jtdb_.ent", "d1fwxa2.ent-d1k32a3.ent", "d1fwxa2.ent-d1k8kc_.ent", "d1fwxa2.ent-d1m1xa4.ent", "d1fwxa2.ent-d2bbkh_.ent", "d1fx0a1.ent-d1skyb1.ent", "d1fx2a_.ent-d1azsa_.ent", "d1fx2a_.ent-d1b3ta_.ent", "d1fx2a_.ent-d1dj0a2.ent", "d1fx2a_.ent-d1dqaa1.ent", "d1fx2a_.ent-d1ekra_.ent", "d1fx2a_.ent-d1eqoa_.ent", "d1fx2a_.ent-d1f3va_.ent", "d1fx2a_.ent-d1ftra1.ent", "d1fx2a_.ent-d1ftra2.ent", "d1fx2a_.ent-d1gpja3.ent", "d1fx2a_.ent-d1h0hb_.ent", "d1fx2a_.ent-d1h72c2.ent", "d1fx2a_.ent-d1hbnb2.ent", "d1fx2a_.ent-d1hlwa_.ent", "d1fx2a_.ent-d1jnrb_.ent", "d1fx2a_.ent-d1kvka2.ent", "d1fx2a_.ent-d1lfwa2.ent", "d1fx2a_.ent-d1qd1a1.ent", "d1fx2a_.ent-d1qd1a2.ent", "d1fx2a_.ent-d1regx_.ent", "d1fx5a_.ent-d1dhkb_.ent", "d1fx5a_.ent-d1dyka1.ent", "d1fx5a_.ent-d1dyka2.ent", "d1fx5a_.ent-d1epwa1.ent", "d1fx5a_.ent-d1gv9a_.ent", "d1fx5a_.ent-d1gzca_.ent", "d1fx5a_.ent-d1h30a1.ent", "d1fx5a_.ent-d1h30a2.ent", "d1fx5a_.ent-d1jhna4.ent", "d1fx5a_.ent-d1kit_1.ent", "d1fx5a_.ent-d1kit_2.ent", "d1fx5a_.ent-d1n1ta1.ent", "d1fx5a_.ent-d1nls__.ent", "d1fx5a_.ent-d1saca_.ent", "d1fx5a_.ent-d1xnb__.ent", "d1fx5a_.ent-d2ayh__.ent", "d1fx5a_.ent-d2nlra_.ent", "d1fx5a_.ent-d2pela_.ent", "d1fx5a_.ent-d2sli_1.ent", "d1fx5a_.ent-d3btaa1.ent", "d1fx7a3.ent-d1bb9__.ent", "d1fx7a3.ent-d1dj7b_.ent", "d1fx7a3.ent-d1g3sa3.ent", "d1fx7a3.ent-d1gcqc_.ent", "d1fx7a3.ent-d1i07a_.ent", "d1fx7a3.ent-d1igqa_.ent", "d1fx7a3.ent-d1jb0e_.ent", "d1fx7a3.ent-d1jo8a_.ent", "d1fx7a3.ent-d1khia1.ent", "d1fx7a3.ent-d1m9sa2.ent", "d1fx7a3.ent-d1m9sa3.ent", "d1fx7a3.ent-d1pht__.ent", "d1fx7a3.ent-d1vie__.ent", "d1fx7a3.ent-d1ycsb2.ent", "d1fxd__.ent-d1fxra_.ent", "d1fxd__.ent-d1gtea5.ent", "d1fxd__.ent-d1h0hb_.ent", "d1fxd__.ent-d1h98a_.ent", "d1fxd__.ent-d1hfel2.ent", "d1fxd__.ent-d1iqza_.ent", "d1fxd__.ent-d1jb0c_.ent", "d1fxd__.ent-d1jnrb_.ent", "d1fxd__.ent-d1keka5.ent", "d1fxd__.ent-d1kqfb1.ent", "d1fxd__.ent-d2fdn__.ent", "d1fxd__.ent-d7fd1a_.ent", "d1fxkc_.ent-d1gh6a_.ent", "d1fxkc_.ent-d1grj_1.ent", "d1fxkc_.ent-d1hdj__.ent", "d1fxkc_.ent-d1ivsa1.ent", "d1fxkc_.ent-d1ix9a1.ent", "d1fxkc_.ent-d1jj2u_.ent", "d1fxkc_.ent-d1k4ta1.ent", "d1fxkc_.ent-d1lrza1.ent", "d1fxkc_.ent-d1seta1.ent", "d1fxla1.ent-d1fxla2.ent", "d1fxla1.ent-d1h6kx_.ent", "d1fxla1.ent-d1hd1a_.ent", "d1fxla1.ent-d1iqta_.ent", "d1fxla1.ent-d1jmta_.ent", "d1fxla1.ent-d1koha2.ent", "d1fxla1.ent-d1l3ka1.ent", "d1fxla1.ent-d1l3ka2.ent", "d1fxla1.ent-d1nu4a_.ent", "d1fxla1.ent-d1qm9a1.ent", "d1fxla1.ent-d1qm9a2.ent", "d1fxla1.ent-d1u2fa_.ent", "d1fxla1.ent-d2msta_.ent", "d1fxla1.ent-d2u1a__.ent", "d1fxla1.ent-d2u2fa_.ent", "d1fxla2.ent-d1h6kx_.ent", "d1fxla2.ent-d1hd1a_.ent", "d1fxla2.ent-d1iqta_.ent", "d1fxla2.ent-d1jmta_.ent", "d1fxla2.ent-d1koha2.ent", "d1fxla2.ent-d1l3ka1.ent", "d1fxla2.ent-d1l3ka2.ent", "d1fxla2.ent-d1nu4a_.ent", "d1fxla2.ent-d1qm9a1.ent", "d1fxla2.ent-d1qm9a2.ent", "d1fxla2.ent-d1u2fa_.ent", "d1fxla2.ent-d2msta_.ent", "d1fxla2.ent-d2u1a__.ent", "d1fxla2.ent-d2u2fa_.ent", "d1fxoa_.ent-d1h7ea_.ent", "d1fxoa_.ent-d1hm9a2.ent", "d1fxoa_.ent-d1hv9a2.ent", "d1fxoa_.ent-d1i52a_.ent", "d1fxoa_.ent-d1jv1a_.ent", "d1fxoa_.ent-d1k4va_.ent", "d1fxoa_.ent-d1kwsa_.ent", "d1fxoa_.ent-d1ll2a_.ent", "d1fxoa_.ent-d1lzja_.ent", "d1fxoa_.ent-d1nf5b_.ent", "d1fxoa_.ent-d1qg8a_.ent", "d1fxra_.ent-d1gtea5.ent", "d1fxra_.ent-d1h0hb_.ent", "d1fxra_.ent-d1h98a_.ent", "d1fxra_.ent-d1hfel2.ent", "d1fxra_.ent-d1iqza_.ent", "d1fxra_.ent-d1jb0c_.ent", "d1fxra_.ent-d1jnrb_.ent", "d1fxra_.ent-d1keka5.ent", "d1fxra_.ent-d1kqfb1.ent", "d1fxra_.ent-d2fdn__.ent", "d1fxra_.ent-d7fd1a_.ent", "d1fxxa_.ent-d1az9_1.ent", "d1fxxa_.ent-d1bco_2.ent", "d1fxxa_.ent-d1bupa1.ent", "d1fxxa_.ent-d1bupa2.ent", "d1fxxa_.ent-d1czan1.ent", "d1fxxa_.ent-d1czan2.ent", "d1fxxa_.ent-d1e4ft1.ent", "d1fxxa_.ent-d1e4ft2.ent", "d1fxxa_.ent-d1g99a2.ent", "d1fxxa_.ent-d1glag1.ent", "d1fxxa_.ent-d1glag2.ent", "d1fxxa_.ent-d1hjra_.ent", "d1fxxa_.ent-d1huxa_.ent", "d1fxxa_.ent-d1i39a_.ent", "d1fxxa_.ent-d1ih7a1.ent", "d1fxxa_.ent-d1io2a_.ent", "d1fxxa_.ent-d1j54a_.ent", "d1fxxa_.ent-d1j6za2.ent", "d1fxxa_.ent-d1jj2m_.ent", "d1fxxa_.ent-d1jl1a_.ent", "d1fxxa_.ent-d1kcfa2.ent", "d1fxxa_.ent-d1kfsa1.ent", "d1fxxa_.ent-d1musa_.ent", "d1fxxa_.ent-d1mwma2.ent", "d1fxxa_.ent-d1nbwa2.ent", "d1fxxa_.ent-d1nbwa3.ent", "d1fxxa_.ent-d1qtma1.ent", "d1fxxa_.ent-d1t7pa1.ent", "d1fxxa_.ent-d1tgoa1.ent", "d1fxxa_.ent-d1vrta1.ent", "d1fxxa_.ent-d1xwl_1.ent", "d1fxza1.ent-d1fxza2.ent", "d1fxza1.ent-d1gp6a_.ent", "d1fxza1.ent-d1gy9a_.ent", "d1fxza1.ent-d1h2ka_.ent", "d1fxza1.ent-d1hw5a2.ent", "d1fxza1.ent-d1ig0a1.ent", "d1fxza1.ent-d1jr7a_.ent", "d1fxza1.ent-d1juha_.ent", "d1fxza1.ent-d1lrha_.ent", "d1fxza1.ent-d1m4oa_.ent", "d1fxza1.ent-d1pmi__.ent", "d1fxza1.ent-d1wapa_.ent", "d1fxza1.ent-d2arca_.ent", "d1fxza1.ent-d2phla1.ent", "d1fxza1.ent-d2phla2.ent", "d1fxza2.ent-d1juha_.ent", "d1fxza2.ent-d1lrha_.ent", "d1fxza2.ent-d1m4oa_.ent", "d1fxza2.ent-d1pmi__.ent", "d1fxza2.ent-d2phla1.ent", "d1fxza2.ent-d2phla2.ent", "d1fy7a_.ent-d1i12a_.ent", "d1fy7a_.ent-d1iica2.ent", "d1fy7a_.ent-d1iyka1.ent", "d1fy7a_.ent-d1iyka2.ent", "d1fy7a_.ent-d1kzfa_.ent", "d1fy7a_.ent-d1lrza2.ent", "d1fy7a_.ent-d1lrza3.ent", "d1fy7a_.ent-d1m4ia_.ent", "d1fy7a_.ent-d1qsma_.ent", "d1fy7a_.ent-d1qsta_.ent", "d1fyc__.ent-d1ghk__.ent", "d1fyc__.ent-d1htp__.ent", "d1fyc__.ent-d1k8ma_.ent", "d1fyc__.ent-d1lac__.ent", "d1fyc__.ent-d1qjoa_.ent", "d1fyea_.ent-d1cex__.ent", "d1fyea_.ent-d1cf9a1.ent", "d1fyea_.ent-d1e5da1.ent", "d1fyea_.ent-d1es9a_.ent", "d1fyea_.ent-d1euca2.ent", "d1fyea_.ent-d1f2va_.ent", "d1fyea_.ent-d1f4pa_.ent", "d1fyea_.ent-d1f8ya_.ent", "d1fyea_.ent-d1fuea_.ent", "d1fyea_.ent-d1g66a_.ent", "d1fyea_.ent-d1gpma2.ent", "d1fyea_.ent-d1h05a_.ent", "d1fyea_.ent-d1i7qb_.ent", "d1fyea_.ent-d1iexa2.ent", "d1fyea_.ent-d1k9vf_.ent", "d1fyea_.ent-d1ka9h_.ent", "d1fyea_.ent-d1kwga3.ent", "d1fyea_.ent-d1l7da2.ent", "d1fyea_.ent-d1l9xa_.ent", "d1fyea_.ent-d1qdlb_.ent", "d1fyea_.ent-d1qo0d_.ent", "d1fyea_.ent-d2naca2.ent", "d1fyea_.ent-d7reqb2.ent", "d1fyhb1.ent-d1f6fb1.ent", "d1fyhb2.ent-d1cd9b2.ent", "d1fyhb2.ent-d1cfb_1.ent", "d1fyhb2.ent-d1egja_.ent", "d1fyhb2.ent-d1f6fb1.ent", "d1fyhb2.ent-d1f6fb2.ent", "d1fyhb2.ent-d1fyhb1.ent", "d1fyhb2.ent-d1gh7a1.ent", "d1fyhb2.ent-d1i1ra1.ent", "d1fyhb2.ent-d1lqsr1.ent", "d1fyhb2.ent-d1n26a2.ent", "d1fyhb2.ent-d1qg3a2.ent", "d1fyhb2.ent-d2hft_1.ent", "d1fyhb2.ent-d2hft_2.ent", "d1fzcb1.ent-d1fzda_.ent", "d1fzcb1.ent-d1jc9a_.ent", "d1fzda_.ent-d1jc9a_.ent", "d1fzpb_.ent-d1bjaa_.ent", "d1fzpb_.ent-d1d5va_.ent", "d1fzpb_.ent-d1e17a_.ent", "d1fzpb_.ent-d1f1za1.ent", "d1fzpb_.ent-d1fnna1.ent", "d1fzpb_.ent-d1fp2a1.ent", "d1fzpb_.ent-d1fsha_.ent", "d1fzpb_.ent-d1ka8a_.ent", "d1fzpb_.ent-d1ldja1.ent", "d1fzpb_.ent-d1repc2.ent", "d1fzpb_.ent-d1smta_.ent", "d1fzpb_.ent-d2foka3.ent", "d1fzta_.ent-d1h2ea_.ent", "d1fzta_.ent-d1ihp__.ent", "d1fzta_.ent-d1nd6a_.ent", "d1fzta_.ent-d1qfxa_.ent", "d1fzta_.ent-d3pgm__.ent", "d1fzya_.ent-d1i7ka_.ent", "d1fzya_.ent-d1j7da_.ent", "d1fzya_.ent-d1jata_.ent", "d1fzya_.ent-d1jatb_.ent", "d1fzya_.ent-d1kppa_.ent", "d1fzya_.ent-d1qcqa_.ent", "d1fzya_.ent-d2aak__.ent", "d1fzya_.ent-d2ucz__.ent", "d1g0da1.ent-d1ea9c1.ent", "d1g0da1.ent-d1edqa1.ent", "d1g0da1.ent-d1eut_1.ent", "d1g0da1.ent-d1j0ha1.ent", "d1g0da1.ent-d1ji1a1.ent", "d1g0da1.ent-d1ji2a1.ent", "d1g0da1.ent-d1jmxa4.ent", "d1g0da1.ent-d1ktja_.ent", "d1g0da1.ent-d1kv3a1.ent", "d1g0da1.ent-d1m7xa1.ent", "d1g0da1.ent-d1my7a_.ent", "d1g0da1.ent-d1nepa_.ent", "d1g0da1.ent-d1qba_1.ent", "d1g0da1.ent-d1qfha1.ent", "d1g0da1.ent-d1qfha2.ent", "d1g0da1.ent-d1soxa1.ent", "d1g0da2.ent-d1g0da3.ent", "d1g0da2.ent-d1kv3a2.ent", "d1g0da2.ent-d1kv3a3.ent", "d1g0da2.ent-d1l9na2.ent", "d1g0da2.ent-d1l9na3.ent", "d1g0da3.ent-d1kv3a2.ent", "d1g0da3.ent-d1kv3a3.ent", "d1g0da3.ent-d1l9na2.ent", "d1g0da3.ent-d1l9na3.ent", "d1g0da4.ent-d1gmya_.ent", "d1g0da4.ent-d1gx3a_.ent", "d1g0da4.ent-d1iu4a_.ent", "d1g0da4.ent-d1kxra_.ent", "d1g0da4.ent-d1l9na4.ent", "d1g0da4.ent-d1me4a_.ent", "d1g0da4.ent-d1nbfa_.ent", "d1g0da4.ent-d1ppn__.ent", "d1g0da4.ent-d1qmya_.ent", "d1g0da4.ent-d1uch__.ent", "d1g0da4.ent-d2act__.ent", "d1g0da4.ent-d2cb5a_.ent", "d1g0da4.ent-d3gcb__.ent", "d1g0da4.ent-d7pcka_.ent", "d1g0ha_.ent-d1inp__.ent", "d1g0ha_.ent-d1jp4a_.ent", "d1g0ha_.ent-d1ka1a_.ent", "d1g0ha_.ent-d1kz8a_.ent", "d1g0ha_.ent-d1lbva_.ent", "d1g0ha_.ent-d2hhma_.ent", "d1g0oa_.ent-d1bdb__.ent", "d1g0oa_.ent-d1bgva1.ent", "d1g0oa_.ent-d1e7wa_.ent", "d1g0oa_.ent-d1eny__.ent", "d1g0oa_.ent-d1gcoa_.ent", "d1g0oa_.ent-d1h5qa_.ent", "d1g0oa_.ent-d1ja9a_.ent", "d1g0oa_.ent-d1oaa__.ent", "d1g0oa_.ent-d1qsga_.ent", "d1g0oa_.ent-d2ae2a_.ent", "d1g0sa_.ent-d1hzta_.ent", "d1g0sa_.ent-d1jkna_.ent", "d1g0sa_.ent-d1k2ea_.ent", "d1g0sa_.ent-d1ktga_.ent", "d1g0sa_.ent-d1mut__.ent", "d1g10a_.ent-d1hqi__.ent", "d1g12a_.ent-d1gkda_.ent", "d1g12a_.ent-d1gqia2.ent", "d1g12a_.ent-d1hs6a3.ent", "d1g12a_.ent-d1i1ip_.ent", "d1g12a_.ent-d1j7na1.ent", "d1g12a_.ent-d1j7na2.ent", "d1g12a_.ent-d1jaka2.ent", "d1g12a_.ent-d1jk3a_.ent", "d1g12a_.ent-d1k7ia2.ent", "d1g12a_.ent-d1k9xa_.ent", "d1g12a_.ent-d1kapp2.ent", "d1g12a_.ent-d1keia_.ent", "d1g12a_.ent-d1kufa_.ent", "d1g12a_.ent-d1lml__.ent", "d1g12a_.ent-d1qba_4.ent", "d1g12a_.ent-d3btaa3.ent", "d1g1ka_.ent-d1g43a_.ent", "d1g1ka_.ent-d1nbca_.ent", "d1g1ka_.ent-d1qba_2.ent", "d1g1ka_.ent-d1tf4a2.ent", "d1g1ta1.ent-d1cwva5.ent", "d1g1ta1.ent-d1e87a_.ent", "d1g1ta1.ent-d1f00i3.ent", "d1g1ta1.ent-d1h8ua_.ent", "d1g1ta1.ent-d1kg0c_.ent", "d1g1ta1.ent-d1koe__.ent", "d1g1ta1.ent-d1li1a1.ent", "d1g1ta1.ent-d1li1a2.ent", "d1g1ta1.ent-d1prea1.ent", "d1g1ta1.ent-d1prtb2.ent", "d1g1ta1.ent-d1qdda_.ent", "d1g1ta1.ent-d1tsg__.ent", "d1g25a_.ent-d1jm7a_.ent", "d1g25a_.ent-d1jm7b_.ent", "d1g25a_.ent-d1ldjb_.ent", "d1g25a_.ent-d1rmd_2.ent", "d1g2913.ent-d1g2914.ent", "d1g2913.ent-d1guta_.ent", "d1g2913.ent-d1h9ma1.ent", "d1g2913.ent-d1h9ma2.ent", "d1g2913.ent-d1h9ra1.ent", "d1g2913.ent-d1h9ra2.ent", "d1g2914.ent-d1guta_.ent", "d1g2914.ent-d1h9ma1.ent", "d1g2914.ent-d1h9ma2.ent", "d1g2914.ent-d1h9ra1.ent", "d1g2914.ent-d1h9ra2.ent", "d1g2ha_.ent-d1e3oc1.ent", "d1g2ha_.ent-d1fexa_.ent", "d1g2ha_.ent-d1ig7a_.ent", "d1g2ha_.ent-d1k61a_.ent", "d1g2ha_.ent-d1k78a2.ent", "d1g2na_.ent-d1hg4a_.ent", "d1g2na_.ent-d1ie9a_.ent", "d1g2na_.ent-d1ilga_.ent", "d1g2na_.ent-d1kv6a_.ent", "d1g2na_.ent-d1lv2a_.ent", "d1g2na_.ent-d1mzna_.ent", "d1g2na_.ent-d1n83a_.ent", "d1g2na_.ent-d2prga_.ent", "d1g2oa_.ent-d1je0a_.ent", "d1g2oa_.ent-d1jysa_.ent", "d1g2oa_.ent-d1k9sa_.ent", "d1g2qa_.ent-d1g9sa_.ent", "d1g2qa_.ent-d1gph11.ent", "d1g2qa_.ent-d1hgxa_.ent", "d1g2qa_.ent-d1i5ea_.ent", "d1g2qa_.ent-d1l1qa_.ent", "d1g2qa_.ent-d1lh0a_.ent", "d1g2qa_.ent-d1nula_.ent", "d1g2qa_.ent-d1qb7a_.ent", "d1g2qa_.ent-d1tc1a_.ent", "d1g2ta_.ent-d1j9oa_.ent", "d1g2ta_.ent-d1m8aa_.ent", "d1g2ta_.ent-d1qg7a_.ent", "d1g2ta_.ent-d1tvxa_.ent", "d1g2ta_.ent-d2hcc__.ent", "d1g2ta_.ent-d3il8__.ent", "d1g31a_.ent-d1heta1.ent", "d1g31a_.ent-d1jh2a_.ent", "d1g31a_.ent-d1jqba1.ent", "d1g31a_.ent-d1kola1.ent", "d1g31a_.ent-d1qora1.ent", "d1g38a_.ent-d1booa_.ent", "d1g38a_.ent-d1dcta_.ent", "d1g38a_.ent-d1eg2a_.ent", "d1g38a_.ent-d1f3la_.ent", "d1g38a_.ent-d1fp1d2.ent", "d1g38a_.ent-d1fp2a2.ent", "d1g38a_.ent-d1g60a_.ent", "d1g38a_.ent-d1g6q1_.ent", "d1g38a_.ent-d1hnna_.ent", "d1g38a_.ent-d1i1na_.ent", "d1g38a_.ent-d1i4wa_.ent", "d1g38a_.ent-d1i9ga_.ent", "d1g38a_.ent-d1inla_.ent", "d1g38a_.ent-d1iy9a_.ent", "d1g38a_.ent-d1jg1a_.ent", "d1g38a_.ent-d1jqea_.ent", "d1g38a_.ent-d1jsxa_.ent", "d1g38a_.ent-d1khha_.ent", "d1g38a_.ent-d1kywa2.ent", "d1g38a_.ent-d1mjfa_.ent", "d1g38a_.ent-d1qama_.ent", "d1g38a_.ent-d1vid__.ent", "d1g38a_.ent-d1xvaa_.ent", "d1g38a_.ent-d1yub__.ent", "d1g38a_.ent-d2dpma_.ent", "d1g38a_.ent-d3mag__.ent", "d1g38a_.ent-d6mhta_.ent", "d1g3nc1.ent-d1g3nc2.ent", "d1g3nc1.ent-d1guxa_.ent", "d1g3nc1.ent-d1guxb_.ent", "d1g3nc1.ent-d1h4ld_.ent", "d1g3nc1.ent-d1jkw_1.ent", "d1g3nc1.ent-d1jkw_2.ent", "d1g3nc1.ent-d1vin_1.ent", "d1g3nc1.ent-d1vin_2.ent", "d1g3nc1.ent-d1vola1.ent", "d1g3nc2.ent-d1guxa_.ent", "d1g3nc2.ent-d1guxb_.ent", "d1g3nc2.ent-d1h4ld_.ent", "d1g3nc2.ent-d1jkw_1.ent", "d1g3nc2.ent-d1jkw_2.ent", "d1g3nc2.ent-d1vin_1.ent", "d1g3nc2.ent-d1vin_2.ent", "d1g3nc2.ent-d1vola1.ent", "d1g3sa3.ent-d1dj7b_.ent", "d1g3sa3.ent-d1gcqc_.ent", "d1g3sa3.ent-d1i07a_.ent", "d1g3sa3.ent-d1igqa_.ent", "d1g3sa3.ent-d1jb0e_.ent", "d1g3sa3.ent-d1jo8a_.ent", "d1g3sa3.ent-d1m9sa2.ent", "d1g3sa3.ent-d1vie__.ent", "d1g3sa3.ent-d1ycsb2.ent", "d1g40a1.ent-d1g40a2.ent", "d1g40a1.ent-d1g40a3.ent", "d1g40a1.ent-d1g40a4.ent", "d1g40a1.ent-d1gkga2.ent", "d1g40a1.ent-d1gkna1.ent", "d1g40a1.ent-d1gkna2.ent", "d1g40a1.ent-d1gpza2.ent", "d1g40a1.ent-d1gpza3.ent", "d1g40a1.ent-d1hcc__.ent", "d1g40a1.ent-d1hfi__.ent", "d1g40a1.ent-d1ly2a1.ent", "d1g40a1.ent-d1ly2a2.ent", "d1g40a1.ent-d1quba1.ent", "d1g40a1.ent-d1quba2.ent", "d1g40a1.ent-d1quba3.ent", "d1g40a1.ent-d1quba4.ent", "d1g40a1.ent-d1quba5.ent", "d1g40a2.ent-d1g40a3.ent", "d1g40a2.ent-d1g40a4.ent", "d1g40a2.ent-d1gkga2.ent", "d1g40a2.ent-d1gkna1.ent", "d1g40a2.ent-d1gkna2.ent", "d1g40a2.ent-d1gpza2.ent", "d1g40a2.ent-d1gpza3.ent", "d1g40a2.ent-d1hcc__.ent", "d1g40a2.ent-d1hfi__.ent", "d1g40a2.ent-d1ly2a1.ent", "d1g40a2.ent-d1ly2a2.ent", "d1g40a2.ent-d1quba1.ent", "d1g40a2.ent-d1quba2.ent", "d1g40a2.ent-d1quba3.ent", "d1g40a2.ent-d1quba4.ent", "d1g40a2.ent-d1quba5.ent", "d1g40a3.ent-d1g40a4.ent", "d1g40a3.ent-d1gkga2.ent", "d1g40a3.ent-d1gkna1.ent", "d1g40a3.ent-d1gkna2.ent", "d1g40a3.ent-d1gpza2.ent", "d1g40a3.ent-d1gpza3.ent", "d1g40a3.ent-d1hcc__.ent", "d1g40a3.ent-d1hfi__.ent", "d1g40a3.ent-d1ly2a1.ent", "d1g40a3.ent-d1ly2a2.ent", "d1g40a3.ent-d1quba1.ent", "d1g40a3.ent-d1quba2.ent", "d1g40a3.ent-d1quba3.ent", "d1g40a3.ent-d1quba4.ent", "d1g40a3.ent-d1quba5.ent", "d1g40a4.ent-d1gkga2.ent", "d1g40a4.ent-d1gkna1.ent", "d1g40a4.ent-d1gkna2.ent", "d1g40a4.ent-d1gpza2.ent", "d1g40a4.ent-d1gpza3.ent", "d1g40a4.ent-d1hcc__.ent", "d1g40a4.ent-d1hfi__.ent", "d1g40a4.ent-d1ly2a1.ent", "d1g40a4.ent-d1ly2a2.ent", "d1g40a4.ent-d1quba1.ent", "d1g40a4.ent-d1quba2.ent", "d1g40a4.ent-d1quba3.ent", "d1g40a4.ent-d1quba4.ent", "d1g40a4.ent-d1quba5.ent", "d1g41a_.ent-d1bg2__.ent", "d1g41a_.ent-d1c4oa1.ent", "d1g41a_.ent-d1e2ka_.ent", "d1g41a_.ent-d1f9va_.ent", "d1g41a_.ent-d1g8pa_.ent", "d1g41a_.ent-d1i6ia_.ent", "d1g41a_.ent-d1ksfx3.ent", "d1g41a_.ent-d1n0ua2.ent", "d1g41a_.ent-d1pjr_1.ent", "d1g41a_.ent-d1pjr_2.ent", "d1g41a_.ent-d1uaaa1.ent", "d1g41a_.ent-d1uaaa2.ent", "d1g43a_.ent-d1nbca_.ent", "d1g43a_.ent-d1qba_2.ent", "d1g43a_.ent-d1tf4a2.ent", "d1g47a1.ent-d1g47a2.ent", "d1g47a1.ent-d1gnf__.ent", "d1g47a1.ent-d1ibia2.ent", "d1g47a1.ent-d1iml_2.ent", "d1g47a1.ent-d1jj2t_.ent", "d1g47a1.ent-d1k3xa3.ent", "d1g47a1.ent-d1kb2a_.ent", "d1g47a1.ent-d1l1za3.ent", "d1g47a1.ent-d1lata_.ent", "d1g47a1.ent-d1lv3a_.ent", "d1g47a1.ent-d1zfo__.ent", "d1g47a1.ent-d2nllb_.ent", "d1g47a1.ent-d3gata_.ent", "d1g47a1.ent-d7gata_.ent", "d1g47a2.ent-d1gnf__.ent", "d1g47a2.ent-d1ibia2.ent", "d1g47a2.ent-d1iml_2.ent", "d1g47a2.ent-d1jj2t_.ent", "d1g47a2.ent-d1k3xa3.ent", "d1g47a2.ent-d1kb2a_.ent", "d1g47a2.ent-d1l1za3.ent", "d1g47a2.ent-d1lata_.ent", "d1g47a2.ent-d1lv3a_.ent", "d1g47a2.ent-d1zfo__.ent", "d1g47a2.ent-d2nllb_.ent", "d1g47a2.ent-d3gata_.ent", "d1g47a2.ent-d7gata_.ent", "d1g4ia_.ent-d1kvoa_.ent", "d1g4ia_.ent-d1le6a_.ent", "d1g4ia_.ent-d1mc2a_.ent", "d1g4ia_.ent-d1poc__.ent", "d1g4ma1.ent-d1bf2_1.ent", "d1g4ma1.ent-d1dqia_.ent", "d1g4ma1.ent-d1ea9c1.ent", "d1g4ma1.ent-d1eaja_.ent", "d1g4ma1.ent-d1edqa1.ent", "d1g4ma1.ent-d1ej8a_.ent", "d1g4ma1.ent-d1eut_1.ent", "d1g4ma1.ent-d1g0da1.ent", "d1g4ma1.ent-d1grwa_.ent", "d1g4ma1.ent-d1j0ha1.ent", "d1g4ma1.ent-d1ji1a1.ent", "d1g4ma1.ent-d1ji2a1.ent", "d1g4ma1.ent-d1jjua4.ent", "d1g4ma1.ent-d1jmxa4.ent", "d1g4ma1.ent-d1kgce2.ent", "d1g4ma1.ent-d1kmta_.ent", "d1g4ma1.ent-d1ktja_.ent", "d1g4ma1.ent-d1kv3a1.ent", "d1g4ma1.ent-d1kyfa1.ent", "d1g4ma1.ent-d1l9na1.ent", "d1g4ma1.ent-d1lmia_.ent", "d1g4ma1.ent-d1m1xa1.ent", "d1g4ma1.ent-d1m1xa2.ent", "d1g4ma1.ent-d1m1xb1.ent", "d1g4ma1.ent-d1m7xa1.ent", "d1g4ma1.ent-d1my7a_.ent", "d1g4ma1.ent-d1nepa_.ent", "d1g4ma1.ent-d1o75a1.ent", "d1g4ma1.ent-d1qba_1.ent", "d1g4ma1.ent-d1qfha1.ent", "d1g4ma1.ent-d1qfha2.ent", "d1g4ma1.ent-d1soxa1.ent", "d1g4ma1.ent-d1xsoa_.ent", "d1g4ma2.ent-d1bf2_1.ent", "d1g4ma2.ent-d1dqia_.ent", "d1g4ma2.ent-d1ea9c1.ent", "d1g4ma2.ent-d1eaja_.ent", "d1g4ma2.ent-d1edqa1.ent", "d1g4ma2.ent-d1ej8a_.ent", "d1g4ma2.ent-d1eut_1.ent", "d1g4ma2.ent-d1g0da1.ent", "d1g4ma2.ent-d1g4ma1.ent", "d1g4ma2.ent-d1grwa_.ent", "d1g4ma2.ent-d1j0ha1.ent", "d1g4ma2.ent-d1ji1a1.ent", "d1g4ma2.ent-d1ji2a1.ent", "d1g4ma2.ent-d1jjua4.ent", "d1g4ma2.ent-d1jmxa4.ent", "d1g4ma2.ent-d1kgce2.ent", "d1g4ma2.ent-d1kmta_.ent", "d1g4ma2.ent-d1ktja_.ent", "d1g4ma2.ent-d1kv3a1.ent", "d1g4ma2.ent-d1kyfa1.ent", "d1g4ma2.ent-d1l9na1.ent", "d1g4ma2.ent-d1lmia_.ent", "d1g4ma2.ent-d1m1xa1.ent", "d1g4ma2.ent-d1m1xa2.ent", "d1g4ma2.ent-d1m1xb1.ent", "d1g4ma2.ent-d1m7xa1.ent", "d1g4ma2.ent-d1my7a_.ent", "d1g4ma2.ent-d1nepa_.ent", "d1g4ma2.ent-d1o75a1.ent", "d1g4ma2.ent-d1qba_1.ent", "d1g4ma2.ent-d1qfha1.ent", "d1g4ma2.ent-d1qfha2.ent", "d1g4ma2.ent-d1soxa1.ent", "d1g4ma2.ent-d1xsoa_.ent", "d1g4us2.ent-d1i9sa_.ent", "d1g4us2.ent-d1ikza_.ent", "d1g4us2.ent-d1jlna_.ent", "d1g4us2.ent-d1lara1.ent", "d1g4us2.ent-d1lara2.ent", "d1g4us2.ent-d1lyva_.ent", "d1g4us2.ent-d1mkp__.ent", "d1g4us2.ent-d1vhra_.ent", "d1g4us2.ent-d1yfoa_.ent", "d1g4us2.ent-d2shpa1.ent", "d1g51a2.ent-d1i50c1.ent", "d1g51a2.ent-d1i50k_.ent", "d1g51a2.ent-d1xxaa_.ent", "d1g51a3.ent-d1h4vb2.ent", "d1g51a3.ent-d1hc7a2.ent", "d1g51a3.ent-d1jjca_.ent", "d1g51a3.ent-d1jjcb5.ent", "d1g51a3.ent-d1kmma2.ent", "d1g51a3.ent-d1qe0a2.ent", "d1g51a3.ent-d1qf6a4.ent", "d1g51a3.ent-d1seta2.ent", "d1g57a_.ent-d1jcua_.ent", "d1g57a_.ent-d1k4ia_.ent", "d1g5aa1.ent-d1g94a1.ent", "d1g5aa1.ent-d1gcya1.ent", "d1g5aa1.ent-d1gjwa1.ent", "d1g5aa1.ent-d1hx0a1.ent", "d1g5aa1.ent-d1iv8a1.ent", "d1g5aa1.ent-d1j0ha2.ent", "d1g5aa1.ent-d1jae_1.ent", "d1g5aa1.ent-d1ji1a2.ent", "d1g5aa1.ent-d1ji2a2.ent", "d1g5aa1.ent-d1ktba1.ent", "d1g5aa1.ent-d1kwga1.ent", "d1g5aa1.ent-d1lwha1.ent", "d1g5aa1.ent-d1m7xa2.ent", "d1g5aa1.ent-d1qhoa3.ent", "d1g5aa1.ent-d1uok_1.ent", "d1g5aa1.ent-d7taa_1.ent", "d1g5aa2.ent-d1b9za2.ent", "d1g5aa2.ent-d1bf2_3.ent", "d1g5aa2.ent-d1cbg__.ent", "d1g5aa2.ent-d1ccwb_.ent", "d1g5aa2.ent-d1cz1a_.ent", "d1g5aa2.ent-d1d3ga_.ent", "d1g5aa2.ent-d1e43a2.ent", "d1g5aa2.ent-d1e4ia_.ent", "d1g5aa2.ent-d1e4mm_.ent", "d1g5aa2.ent-d1edg__.ent", "d1g5aa2.ent-d1eexa_.ent", "d1g5aa2.ent-d1eh9a3.ent", "d1g5aa2.ent-d1eswa_.ent", "d1g5aa2.ent-d1f8ma_.ent", "d1g5aa2.ent-d1gvoa_.ent", "d1g5aa2.ent-d1gw1a_.ent", "d1g5aa2.ent-d1hxja_.ent", "d1g5aa2.ent-d1iexa1.ent", "d1g5aa2.ent-d1itua_.ent", "d1g5aa2.ent-d1j0ha3.ent", "d1g5aa2.ent-d1j5sa_.ent", "d1g5aa2.ent-d1ji1a3.ent", "d1g5aa2.ent-d1k4ga_.ent", "d1g5aa2.ent-d1k9da1.ent", "d1g5aa2.ent-d1kbla1.ent", "d1g5aa2.ent-d1kwga2.ent", "d1g5aa2.ent-d1lwha2.ent", "d1g5aa2.ent-d1m7ja3.ent", "d1g5aa2.ent-d1muwa_.ent", "d1g5aa2.ent-d1ntha_.ent", "d1g5aa2.ent-d1pama4.ent", "d1g5aa2.ent-d1qba_3.ent", "d1g5aa2.ent-d1qhoa4.ent", "d1g5aa2.ent-d1qvba_.ent", "d1g5aa2.ent-d1uok_2.ent", "d1g5aa2.ent-d7taa_2.ent", "d1g5ba_.ent-d1ii7a_.ent", "d1g5ba_.ent-d1jk7a_.ent", "d1g5ba_.ent-d1nnwa_.ent", "d1g5ba_.ent-d1ush_2.ent", "d1g5ba_.ent-d1utea_.ent", "d1g5ba_.ent-d4kbpa2.ent", "d1g5ca_.ent-d1i6pa_.ent", "d1g5na_.ent-d1hm6a_.ent", "d1g60a_.ent-d1fp1d2.ent", "d1g60a_.ent-d1hnna_.ent", "d1g60a_.ent-d1i1na_.ent", "d1g60a_.ent-d1i4wa_.ent", "d1g60a_.ent-d1inla_.ent", "d1g60a_.ent-d1jg1a_.ent", "d1g60a_.ent-d1jqea_.ent", "d1g60a_.ent-d1jsxa_.ent", "d1g60a_.ent-d1khha_.ent", "d1g60a_.ent-d1qama_.ent", "d1g60a_.ent-d1vid__.ent", "d1g60a_.ent-d1xvaa_.ent", "d1g60a_.ent-d2dpma_.ent", "d1g60a_.ent-d3mag__.ent", "d1g61a_.ent-d1g62a_.ent", "d1g61a_.ent-d1h70a_.ent", "d1g61a_.ent-d1jdw__.ent", "d1g62a_.ent-d1h70a_.ent", "d1g62a_.ent-d1jdw__.ent", "d1g66a_.ent-d1cex__.ent", "d1g66a_.ent-d1cf9a1.ent", "d1g66a_.ent-d1e5da1.ent", "d1g66a_.ent-d1euca2.ent", "d1g66a_.ent-d1f4pa_.ent", "d1g66a_.ent-d1f8ya_.ent", "d1g66a_.ent-d1fuea_.ent", "d1g66a_.ent-d1h05a_.ent", "d1g66a_.ent-d1kwga3.ent", "d1g66a_.ent-d1l7da2.ent", "d1g66a_.ent-d1qo0d_.ent", "d1g66a_.ent-d2naca2.ent", "d1g66a_.ent-d7reqb2.ent", "d1g6aa_.ent-d1ghpa_.ent", "d1g6aa_.ent-d1iyoa_.ent", "d1g6aa_.ent-d1l0ga_.ent", "d1g6aa_.ent-d1m40a_.ent", "d1g6aa_.ent-d1mfoa_.ent", "d1g6aa_.ent-d1mwxa3.ent", "d1g6aa_.ent-d1nj4a2.ent", "d1g6aa_.ent-d1qmea4.ent", "d1g6aa_.ent-d4blma_.ent", "d1g6ea_.ent-d2bb2_1.ent", "d1g6ea_.ent-d2bb2_2.ent", "d1g6ga_.ent-d1gxca_.ent", "d1g6ga_.ent-d1lgpa_.ent", "d1g6ga_.ent-d1mjsa_.ent", "d1g6ga_.ent-d1ygs__.ent", "d1g6q1_.ent-d1booa_.ent", "d1g6q1_.ent-d1dcta_.ent", "d1g6q1_.ent-d1eg2a_.ent", "d1g6q1_.ent-d1f3la_.ent", "d1g6q1_.ent-d1fp1d2.ent", "d1g6q1_.ent-d1fp2a2.ent", "d1g6q1_.ent-d1g60a_.ent", "d1g6q1_.ent-d1hnna_.ent", "d1g6q1_.ent-d1i1na_.ent", "d1g6q1_.ent-d1i4wa_.ent", "d1g6q1_.ent-d1i9ga_.ent", "d1g6q1_.ent-d1inla_.ent", "d1g6q1_.ent-d1iy9a_.ent", "d1g6q1_.ent-d1jg1a_.ent", "d1g6q1_.ent-d1jqea_.ent", "d1g6q1_.ent-d1kywa2.ent", "d1g6q1_.ent-d1mjfa_.ent", "d1g6q1_.ent-d1qama_.ent", "d1g6q1_.ent-d1xvaa_.ent", "d1g6q1_.ent-d1yub__.ent", "d1g6q1_.ent-d2dpma_.ent", "d1g6q1_.ent-d3mag__.ent", "d1g6q1_.ent-d6mhta_.ent", "d1g6sa_.ent-d1h0xa_.ent", "d1g6sa_.ent-d1hc7a3.ent", "d1g6sa_.ent-d1jo0a_.ent", "d1g6sa_.ent-d1msza_.ent", "d1g6sa_.ent-d1qmha2.ent", "d1g6sa_.ent-d1tig__.ent", "d1g6xa_.ent-d1irha_.ent", "d1g6xa_.ent-d1ktha_.ent", "d1g6xa_.ent-d1tfxc_.ent", "d1g6xa_.ent-d1tocr1.ent", "d1g6xa_.ent-d1tocr2.ent", "d1g6za_.ent-d1knaa_.ent", "d1g72b_.ent-d1hfes_.ent", "d1g72b_.ent-d1jj21_.ent", "d1g72b_.ent-d1tbge_.ent", "d1g72b_.ent-d2prgc_.ent", "d1g73a_.ent-d1hcia1.ent", "d1g73a_.ent-d1hcia4.ent", "d1g73a_.ent-d1hx1b_.ent", "d1g73a_.ent-d1jnra1.ent", "d1g73a_.ent-d1m7ka_.ent", "d1g73a_.ent-d1qlaa1.ent", "d1g73a_.ent-d1quua1.ent", "d1g73a_.ent-d1quua2.ent", "d1g73a_.ent-d2spca_.ent", "d1g73c_.ent-d1i3oe_.ent", "d1g73c_.ent-d1jd5a_.ent", "d1g73c_.ent-d1qbha_.ent", "d1g7da_.ent-d1m2oa1.ent", "d1g7da_.ent-d1m2vb1.ent", "d1g7ea_.ent-d1a8l_1.ent", "d1g7ea_.ent-d1a8l_2.ent", "d1g7ea_.ent-d1a8y_2.ent", "d1g7ea_.ent-d1a8y_3.ent", "d1g7ea_.ent-d1aba__.ent", "d1g7ea_.ent-d1aqwa2.ent", "d1g7ea_.ent-d1bed_2.ent", "d1g7ea_.ent-d1bjx__.ent", "d1g7ea_.ent-d1e6ba2.ent", "d1g7ea_.ent-d1ep7a_.ent", "d1g7ea_.ent-d1erv__.ent", "d1g7ea_.ent-d1f9ma_.ent", "d1g7ea_.ent-d1fb6a_.ent", "d1g7ea_.ent-d1fhe_2.ent", "d1g7ea_.ent-d1gh2a_.ent", "d1g7ea_.ent-d1hyua4.ent", "d1g7ea_.ent-d1iloa_.ent", "d1g7ea_.ent-d1k0ma2.ent", "d1g7ea_.ent-d1k3ya2.ent", "d1g7ea_.ent-d1kte__.ent", "d1g7ea_.ent-d1m2da_.ent", "d1g7ea_.ent-d1mek__.ent", "d1g7ea_.ent-d1qmha1.ent", "d1g7ea_.ent-d1quwa_.ent", "d1g7ea_.ent-d1thx__.ent", "d1g7ea_.ent-d2trxa_.ent", "d1g7oa1.ent-d1glqa1.ent", "d1g7oa1.ent-d1gnwa1.ent", "d1g7oa1.ent-d1gula1.ent", "d1g7oa1.ent-d1gwca1.ent", "d1g7oa1.ent-d1jlva1.ent", "d1g7oa1.ent-d1k0da1.ent", "d1g7oa1.ent-d1k0ma1.ent", "d1g7oa1.ent-d1k3ya1.ent", "d1g7oa1.ent-d1ljra1.ent", "d1g7oa1.ent-d1m0ua1.ent", "d1g7oa1.ent-d1pd211.ent", "d1g7oa1.ent-d1pmt_1.ent", "d1g7oa1.ent-d2gsq_1.ent", "d1g7oa1.ent-d2gsta1.ent", "d1g7sa1.ent-d1g7sa2.ent", "d1g7sa1.ent-d1i7pa1.ent", "d1g7sa1.ent-d1jb9a1.ent", "d1g7sa1.ent-d1jj2b_.ent", "d1g7sa1.ent-d1kk1a1.ent", "d1g7sa1.ent-d1krha1.ent", "d1g7sa1.ent-d1kzla1.ent", "d1g7sa1.ent-d1kzla2.ent", "d1g7sa1.ent-d1n08a_.ent", "d1g7sa1.ent-d1n0ua1.ent", "d1g7sa1.ent-d1qfja1.ent", "d1g7sa1.ent-d2pia_1.ent", "d1g7sa2.ent-d1i7pa1.ent", "d1g7sa2.ent-d1jb9a1.ent", "d1g7sa2.ent-d1jj2b_.ent", "d1g7sa2.ent-d1kk1a1.ent", "d1g7sa2.ent-d1krha1.ent", "d1g7sa2.ent-d1kzla1.ent", "d1g7sa2.ent-d1kzla2.ent", "d1g7sa2.ent-d1n08a_.ent", "d1g7sa2.ent-d1n0ua1.ent", "d1g7sa2.ent-d1qfja1.ent", "d1g7sa2.ent-d2pia_1.ent", "d1g7ya_.ent-d1a8d_1.ent", "d1g7ya_.ent-d1dhkb_.ent", "d1g7ya_.ent-d1dyka1.ent", "d1g7ya_.ent-d1dyka2.ent", "d1g7ya_.ent-d1epwa1.ent", "d1g7ya_.ent-d1fx5a_.ent", "d1g7ya_.ent-d1gv9a_.ent", "d1g7ya_.ent-d1gzca_.ent", "d1g7ya_.ent-d1h30a1.ent", "d1g7ya_.ent-d1h30a2.ent", "d1g7ya_.ent-d1ikpa1.ent", "d1g7ya_.ent-d1jhna4.ent", "d1g7ya_.ent-d1kit_1.ent", "d1g7ya_.ent-d1kit_2.ent", "d1g7ya_.ent-d1n1ta1.ent", "d1g7ya_.ent-d1n3oa_.ent", "d1g7ya_.ent-d1nls__.ent", "d1g7ya_.ent-d1saca_.ent", "d1g7ya_.ent-d1xnb__.ent", "d1g7ya_.ent-d2ayh__.ent", "d1g7ya_.ent-d2nlra_.ent", "d1g7ya_.ent-d2pela_.ent", "d1g7ya_.ent-d2sli_1.ent", "d1g7ya_.ent-d3btaa1.ent", "d1g85a_.ent-d1ggla_.ent", "d1g85a_.ent-d1gkab_.ent", "d1g85a_.ent-d1hms__.ent", "d1g85a_.ent-d1i4ua_.ent", "d1g85a_.ent-d1ifc__.ent", "d1g85a_.ent-d1jv4a_.ent", "d1g85a_.ent-d1koia_.ent", "d1g85a_.ent-d1kqwa_.ent", "d1g85a_.ent-d1lf7a_.ent", "d1g85a_.ent-d1o1va_.ent", "d1g85a_.ent-d1qfta_.ent", "d1g85a_.ent-d1qqsa_.ent", "d1g8fa1.ent-d1jhda1.ent", "d1g8fa1.ent-d1pkla1.ent", "d1g8fa2.ent-d1gtra2.ent", "d1g8fa2.ent-d1h3fa1.ent", "d1g8fa2.ent-d1h3na3.ent", "d1g8fa2.ent-d1ihoa_.ent", "d1g8fa2.ent-d1ile_3.ent", "d1g8fa2.ent-d1iq0a2.ent", "d1g8fa2.ent-d1irxa2.ent", "d1g8fa2.ent-d1ivsa4.ent", "d1g8fa2.ent-d1j09a2.ent", "d1g8fa2.ent-d1jhda2.ent", "d1g8fa2.ent-d1jila_.ent", "d1g8fa2.ent-d1k4ma_.ent", "d1g8fa2.ent-d1kama_.ent", "d1g8fa2.ent-d1kqna_.ent", "d1g8fa2.ent-d1li5a2.ent", "d1g8fa2.ent-d1n3la_.ent", "d1g8fa2.ent-d1qjca_.ent", "d1g8ia_.ent-d1alva_.ent", "d1g8ia_.ent-d1auib_.ent", "d1g8ia_.ent-d1df0a1.ent", "d1g8ia_.ent-d1eg3a1.ent", "d1g8ia_.ent-d1exra_.ent", "d1g8ia_.ent-d1ggwa_.ent", "d1g8ia_.ent-d1hqva_.ent", "d1g8ia_.ent-d1jfja_.ent", "d1g8ia_.ent-d1k94a_.ent", "d1g8ia_.ent-d1m31a_.ent", "d1g8ia_.ent-d1m45a_.ent", "d1g8ia_.ent-d1ncx__.ent", "d1g8ia_.ent-d1rro__.ent", "d1g8ia_.ent-d1sra__.ent", "d1g8ia_.ent-d1wdcb_.ent", "d1g8ia_.ent-d1wdcc_.ent", "d1g8ia_.ent-d2pvba_.ent", "d1g8ia_.ent-d2scpa_.ent", "d1g8ia_.ent-d5pal__.ent", "d1g8ka1.ent-d1h0ha1.ent", "d1g8ka1.ent-d1kqfa1.ent", "d1g8ka1.ent-d1n10a2.ent", "d1g8ka1.ent-d1tmo_1.ent", "d1g8ka1.ent-d2napa1.ent", "d1g8ka2.ent-d1tmo_2.ent", "d1g8ka2.ent-d2napa2.ent", "d1g8kb_.ent-d1jm1a_.ent", "d1g8kb_.ent-d1o7na1.ent", "d1g8kb_.ent-d1rfs__.ent", "d1g8kb_.ent-d1rie__.ent", "d1g8la1.ent-d1h3ia2.ent", "d1g8la1.ent-d1hg7a_.ent", "d1g8la1.ent-d1mlva2.ent", "d1g8la1.ent-d1n3ja_.ent", "d1g8la1.ent-d1tul__.ent", "d1g8la1.ent-d4ubpb_.ent", "d1g8la3.ent-d1jlja_.ent", "d1g8pa_.ent-d1a7j__.ent", "d1g8pa_.ent-d1aqua_.ent", "d1g8pa_.ent-d1cr1a_.ent", "d1g8pa_.ent-d1e2ka_.ent", "d1g8pa_.ent-d1e69a_.ent", "d1g8pa_.ent-d1e79a3.ent", "d1g8pa_.ent-d1f5na2.ent", "d1g8pa_.ent-d1f9va_.ent", "d1g8pa_.ent-d1fnna2.ent", "d1g8pa_.ent-d1g8ya_.ent", "d1g8pa_.ent-d1gm5a3.ent", "d1g8pa_.ent-d1ihua1.ent", "d1g8pa_.ent-d1jwyb_.ent", "d1g8pa_.ent-d1ksfx3.ent", "d1g8pa_.ent-d1lv7a_.ent", "d1g8pa_.ent-d1m6na3.ent", "d1g8pa_.ent-d1nsta_.ent", "d1g8pa_.ent-d1pjr_1.ent", "d1g8pa_.ent-d1pjr_2.ent", "d1g8pa_.ent-d1uaaa1.ent", "d1g94a1.ent-d1gcya1.ent", "d1g94a1.ent-d1gjwa1.ent", "d1g94a1.ent-d1hx0a1.ent", "d1g94a1.ent-d1iv8a1.ent", "d1g94a1.ent-d1j0ha2.ent", "d1g94a1.ent-d1jae_1.ent", "d1g94a1.ent-d1ji1a2.ent", "d1g94a1.ent-d1ji2a2.ent", "d1g94a1.ent-d1ktba1.ent", "d1g94a1.ent-d1kwga1.ent", "d1g94a1.ent-d1lwha1.ent", "d1g94a1.ent-d1m7xa2.ent", "d1g94a1.ent-d1qhoa3.ent", "d1g94a1.ent-d1uok_1.ent", "d1g94a1.ent-d7taa_1.ent", "d1g96a_.ent-d1kwia_.ent", "d1g96a_.ent-d1mola_.ent", "d1g96a_.ent-d1stfi_.ent", "d1g99a1.ent-d1g99a2.ent", "d1g99a1.ent-d1glag1.ent", "d1g99a1.ent-d1glag2.ent", "d1g99a1.ent-d1huxa_.ent", "d1g99a1.ent-d1ig8a1.ent", "d1g99a1.ent-d1ig8a2.ent", "d1g99a1.ent-d1j6za2.ent", "d1g99a1.ent-d1jcfa1.ent", "d1g99a1.ent-d1k8ka1.ent", "d1g99a1.ent-d1mwma1.ent", "d1g99a1.ent-d1mwma2.ent", "d1g99a1.ent-d1nbwa2.ent", "d1g99a1.ent-d1nbwa3.ent", "d1g99a2.ent-d1az9_1.ent", "d1g99a2.ent-d1bco_2.ent", "d1g99a2.ent-d1bupa1.ent", "d1g99a2.ent-d1bupa2.ent", "d1g99a2.ent-d1czan1.ent", "d1g99a2.ent-d1e4ft1.ent", "d1g99a2.ent-d1e4ft2.ent", "d1g99a2.ent-d1glag1.ent", "d1g99a2.ent-d1glag2.ent", "d1g99a2.ent-d1huxa_.ent", "d1g99a2.ent-d1ig8a1.ent", "d1g99a2.ent-d1ig8a2.ent", "d1g99a2.ent-d1j54a_.ent", "d1g99a2.ent-d1j6za2.ent", "d1g99a2.ent-d1jcfa1.ent", "d1g99a2.ent-d1jj2m_.ent", "d1g99a2.ent-d1k8ka1.ent", "d1g99a2.ent-d1kcfa2.ent", "d1g99a2.ent-d1mwma1.ent", "d1g99a2.ent-d1mwma2.ent", "d1g99a2.ent-d1nbwa2.ent", "d1g99a2.ent-d1nbwa3.ent", "d1g99a2.ent-d1t7pa1.ent", "d1g99a2.ent-d1xwl_1.ent", "d1g9la_.ent-d1i2ta_.ent", "d1g9la_.ent-d1ifwa_.ent", "d1g9mh1.ent-d1a2yb_.ent", "d1g9mh1.ent-d1akjd_.ent", "d1g9mh1.ent-d1b88a_.ent", "d1g9mh1.ent-d1bec_1.ent", "d1g9mh1.ent-d1bqhg_.ent", "d1g9mh1.ent-d1c5ch1.ent", "d1g9mh1.ent-d1dlfh_.ent", "d1g9mh1.ent-d1dlfl_.ent", "d1g9mh1.ent-d1dqta_.ent", "d1g9mh1.ent-d1eaja_.ent", "d1g9mh1.ent-d1fo0a_.ent", "d1g9mh1.ent-d1gsma2.ent", "d1g9mh1.ent-d1h5ba_.ent", "d1g9mh1.ent-d1hxma1.ent", "d1g9mh1.ent-d1hxmb1.ent", "d1g9mh1.ent-d1kgce2.ent", "d1g9mh1.ent-d1ktke1.ent", "d1g9mh1.ent-d1kxvc_.ent", "d1g9mh1.ent-d1neu__.ent", "d1g9mh1.ent-d1nfdb1.ent", "d1g9mh1.ent-d1qfoa_.ent", "d1g9mh1.ent-d1tvda_.ent", "d1g9mh1.ent-d2rhe__.ent", "d1g9oa_.ent-d1i16__.ent", "d1g9oa_.ent-d1ihja_.ent", "d1g9oa_.ent-d1k32a1.ent", "d1g9oa_.ent-d1kwaa_.ent", "d1g9oa_.ent-d1lcya1.ent", "d1g9oa_.ent-d1m5za_.ent", "d1g9oa_.ent-d1mfga_.ent", "d1g9oa_.ent-d1qaua_.ent", "d1g9oa_.ent-d1qava_.ent", "d1g9oa_.ent-d1qlca_.ent", "d1g9pa_.ent-d1b9wa2.ent", "d1g9pa_.ent-d1cixa_.ent", "d1g9pa_.ent-d1h59b_.ent", "d1g9pa_.ent-d1i25a_.ent", "d1g9pa_.ent-d1i26a_.ent", "d1g9pa_.ent-d1i2ua_.ent", "d1g9pa_.ent-d1imt_2.ent", "d1g9pa_.ent-d1koza_.ent", "d1g9pa_.ent-d1kqha_.ent", "d1g9pa_.ent-d1lqra_.ent", "d1g9pa_.ent-d1lupa_.ent", "d1g9pa_.ent-d1nixa_.ent", "d1g9pa_.ent-d1niya_.ent", "d1g9pa_.ent-d1qk6a_.ent", "d1g9pa_.ent-d1qk7a_.ent", "d1g9pa_.ent-d1vtx__.ent", "d1g9sa_.ent-d1gph11.ent", "d1g9sa_.ent-d1hgxa_.ent", "d1g9sa_.ent-d1i5ea_.ent", "d1g9sa_.ent-d1l1qa_.ent", "d1g9sa_.ent-d1lh0a_.ent", "d1g9sa_.ent-d1nula_.ent", "d1g9sa_.ent-d1qb7a_.ent", "d1g9sa_.ent-d1tc1a_.ent", "d1g9za_.ent-d1iba__.ent", "d1g9za_.ent-d1jvaa2.ent", "d1g9za_.ent-d1jvaa3.ent", "d1ga6a_.ent-d1gci__.ent", "d1ga6a_.ent-d1gt91_.ent", "d1ga6a_.ent-d1ic6a_.ent", "d1ga6a_.ent-d1thm__.ent", "d1gab__.ent-d1gjta_.ent", "d1gai__.ent-d1gxma_.ent", "d1gai__.ent-d1h54a1.ent", "d1gai__.ent-d1ia6a_.ent", "d1gai__.ent-d1ks8a_.ent", "d1gai__.ent-d1kwfa_.ent", "d1gai__.ent-d1ld8b_.ent", "d1gai__.ent-d1lf6a1.ent", "d1gai__.ent-d1n1ba1.ent", "d1gai__.ent-d1n7oa1.ent", "d1gai__.ent-d1qaza_.ent", "d1gai__.ent-d2sqca1.ent", "d1gai__.ent-d2sqca2.ent", "d1gca__.ent-d1jdpa_.ent", "d1gca__.ent-d1jx6a_.ent", "d1gca__.ent-d1jyea_.ent", "d1gca__.ent-d1pea__.ent", "d1gca__.ent-d1rpja_.ent", "d1gca__.ent-d2dri__.ent", "d1gca__.ent-d2liv__.ent", "d1gca__.ent-d8abp__.ent", "d1gcca_.ent-d1kjka_.ent", "d1gcca_.ent-d1qk9a_.ent", "d1gci__.ent-d1gt91_.ent", "d1gci__.ent-d1ic6a_.ent", "d1gci__.ent-d1thm__.ent", "d1gcoa_.ent-d1bgva1.ent", "d1gcoa_.ent-d1h5qa_.ent", "d1gcoa_.ent-d1ja9a_.ent", "d1gcoa_.ent-d1oaa__.ent", "d1gcoa_.ent-d1qsga_.ent", "d1gcoa_.ent-d2ae2a_.ent", "d1gcqa_.ent-d1gcqc_.ent", "d1gcqa_.ent-d1gl5a_.ent", "d1gcqa_.ent-d1gria1.ent", "d1gcqa_.ent-d1h92a_.ent", "d1gcqa_.ent-d1i07a_.ent", "d1gcqa_.ent-d1i1ja_.ent", "d1gcqa_.ent-d1jo8a_.ent", "d1gcqa_.ent-d1jqqa_.ent", "d1gcqa_.ent-d1k4us_.ent", "d1gcqa_.ent-d1kjwa1.ent", "d1gcqa_.ent-d1neb__.ent", "d1gcqa_.ent-d1pht__.ent", "d1gcqa_.ent-d1pwt__.ent", "d1gcqa_.ent-d1qcfa1.ent", "d1gcqa_.ent-d1ycsb2.ent", "d1gcqa_.ent-d2hsp__.ent", "d1gcqc_.ent-d1gl5a_.ent", "d1gcqc_.ent-d1gria1.ent", "d1gcqc_.ent-d1h92a_.ent", "d1gcqc_.ent-d1i07a_.ent", "d1gcqc_.ent-d1i1ja_.ent", "d1gcqc_.ent-d1jb0e_.ent", "d1gcqc_.ent-d1jo8a_.ent", "d1gcqc_.ent-d1jqqa_.ent", "d1gcqc_.ent-d1k4us_.ent", "d1gcqc_.ent-d1kjwa1.ent", "d1gcqc_.ent-d1neb__.ent", "d1gcqc_.ent-d1pht__.ent", "d1gcqc_.ent-d1pwt__.ent", "d1gcqc_.ent-d1qcfa1.ent", "d1gcqc_.ent-d1vie__.ent", "d1gcqc_.ent-d1ycsb2.ent", "d1gcqc_.ent-d2hsp__.ent", "d1gcva_.ent-d1ew6a_", "d1gcva_.ent-d1ew6a_.ent", "d1gcya1.ent-d1gjwa1.ent", "d1gcya1.ent-d1hx0a1.ent", "d1gcya1.ent-d1iv8a1.ent", "d1gcya1.ent-d1j0ha2.ent", "d1gcya1.ent-d1jae_1.ent", "d1gcya1.ent-d1ji1a2.ent", "d1gcya1.ent-d1ji2a2.ent", "d1gcya1.ent-d1ktba1.ent", "d1gcya1.ent-d1kwga1.ent", "d1gcya1.ent-d1lwha1.ent", "d1gcya1.ent-d1m7xa2.ent", "d1gcya1.ent-d1qhoa3.ent", "d1gcya1.ent-d1uok_1.ent", "d1gcya1.ent-d7taa_1.ent", "d1gd0a_.ent-d1gyxa_.ent", "d1gd0a_.ent-d1hfoa_.ent", "d1gd0a_.ent-d1otfa_.ent", "d1gd0a_.ent-d1otga_.ent", "d1gd6a_.ent-d1k28a3.ent", "d1gd6a_.ent-d1qgia_.ent", "d1gd6a_.ent-d1qsaa2.ent", "d1gd6a_.ent-d1qusa_.ent", "d1gd6a_.ent-d217l__.ent", "d1gd6a_.ent-d2eql__.ent", "d1gd6a_.ent-d3lzt__.ent", "d1gdea_.ent-d1b9ha_.ent", "d1gdea_.ent-d1bs0a_.ent", "d1gdea_.ent-d1j32a_.ent", "d1gdha2.ent-d1j4aa2.ent", "d1gdha2.ent-d1l7da2.ent", "d1gdha2.ent-d1mx3a2.ent", "d1gdha2.ent-d1pjca2.ent", "d1gdha2.ent-d1psda2.ent", "d1gdha2.ent-d2naca2.ent", "d1gdna_.ent-d1hava_.ent", "d1gdna_.ent-d1hj9a_.ent", "d1gdna_.ent-d1lcya2.ent", "d1gdna_.ent-d1lvmb_.ent", "d1gdna_.ent-d1lvoa_.ent", "d1gdna_.ent-d1mbma_.ent", "d1gdna_.ent-d1qq4a_.ent", "d1gdna_.ent-d1svpa_.ent", "d1gdna_.ent-d2hrva_.ent", "d1gdoa_.ent-d1gph12.ent", "d1gdoa_.ent-d1iru1_.ent", "d1gdoa_.ent-d1iru2_.ent", "d1gdoa_.ent-d1iruk_.ent", "d1gdoa_.ent-d1jgta2.ent", "d1gdoa_.ent-d1jjwa_.ent", "d1gdoa_.ent-d1kuua_.ent", "d1gdoa_.ent-d1llwa3.ent", "d1gdoa_.ent-d1pma1_.ent", "d1gdoa_.ent-d1pmaa_.ent", "d1gdoa_.ent-d1ryp1_.ent", "d1gdoa_.ent-d1ryp2_.ent", "d1gdoa_.ent-d1rypa_.ent", "d1gdoa_.ent-d1rypf_.ent", "d1gdoa_.ent-d1ryph_.ent", "d1gdoa_.ent-d1rypi_.ent", "d1gdoa_.ent-d1rypj_.ent", "d1gdoa_.ent-d1rypk_.ent", "d1gdoa_.ent-d1rypl_.ent", "d1ge8a1.ent-d1ge8a2.ent", "d1ge8a1.ent-d1plq_1.ent", "d1ge8a1.ent-d1plq_2.ent", "d1ge8a1.ent-d2pola1.ent", "d1ge8a1.ent-d2pola2.ent", "d1ge8a1.ent-d2pola3.ent", "d1ge8a2.ent-d1plq_1.ent", "d1ge8a2.ent-d1plq_2.ent", "d1ge8a2.ent-d2pola1.ent", "d1ge8a2.ent-d2pola2.ent", "d1ge8a2.ent-d2pola3.ent", "d1gefa_.ent-d1hh1a_.ent", "d1gefa_.ent-d1kc6a_.ent", "d1gefa_.ent-d1knva_.ent", "d1gefa_.ent-d1m0da_.ent", "d1gefa_.ent-d1vsra_.ent", "d1gefa_.ent-d2foka4.ent", "d1gefa_.ent-d3pvia_.ent", "d1gen__.ent-d1itva_.ent", "d1gen__.ent-d1pex__.ent", "d1gen__.ent-d1qhua1.ent", "d1geqa_.ent-d1i4na_.ent", "d1geqa_.ent-d1jvna1.ent", "d1geqa_.ent-d1km3a_.ent", "d1geqa_.ent-d1kv8a_.ent", "d1geqa_.ent-d1nsj__.ent", "d1geqa_.ent-d1pii_1.ent", "d1geqa_.ent-d1pii_2.ent", "d1geqa_.ent-d1qopa_.ent", "d1geqa_.ent-d1rpxa_.ent", "d1geqa_.ent-d1thfd_.ent", "d1gg3a1.ent-d1h4ra1.ent", "d1gg3a1.ent-d1hbka_.ent", "d1gg3a1.ent-d1mixa1.ent", "d1gg3a2.ent-d1h4ra2.ent", "d1gg3a2.ent-d1k5db_.ent", "d1gg3a2.ent-d1ki1b2.ent", "d1gg3a2.ent-d1mai__.ent", "d1gg3a2.ent-d1mixa2.ent", "d1gg3a2.ent-d1mkea1.ent", "d1gg3a2.ent-d1pls__.ent", "d1gg3a2.ent-d1qqga1.ent", "d1gg3a2.ent-d1qqga2.ent", "d1gg3a2.ent-d1shca_.ent", "d1gg3a3.ent-d1gnua_.ent", "d1gg3a3.ent-d1h4ra3.ent", "d1gg3a3.ent-d1h8ca_.ent", "d1gg3a3.ent-d1i42a_.ent", "d1gg3a3.ent-d1j8ca_.ent", "d1gg3a3.ent-d1k8rb_.ent", "d1gg3a3.ent-d1l7ya_.ent", "d1gg3a3.ent-d1lfda_.ent", "d1gg3a3.ent-d1lm8b_.ent", "d1gg3a3.ent-d1m94a_.ent", "d1gg3a3.ent-d1rlf__.ent", "d1ggla_.ent-d1gkab_.ent", "d1ggla_.ent-d1hms__.ent", "d1ggla_.ent-d1i4ua_.ent", "d1ggla_.ent-d1ifc__.ent", "d1ggla_.ent-d1jv4a_.ent", "d1ggla_.ent-d1koia_.ent", "d1ggla_.ent-d1kqwa_.ent", "d1ggla_.ent-d1lf7a_.ent", "d1ggla_.ent-d1o1va_.ent", "d1ggla_.ent-d1qfta_.ent", "d1ggla_.ent-d1qqsa_.ent", "d1ggwa_.ent-d1eg3a1.ent", "d1ggwa_.ent-d1jfja_.ent", "d1ggwa_.ent-d1m31a_.ent", "d1ggwa_.ent-d1rro__.ent", "d1ggwa_.ent-d2pvba_.ent", "d1ggwa_.ent-d5pal__.ent", "d1gh2a_.ent-d1a8y_2.ent", "d1gh2a_.ent-d1aba__.ent", "d1gh2a_.ent-d1aqwa2.ent", "d1gh2a_.ent-d1e6ba2.ent", "d1gh2a_.ent-d1erv__.ent", "d1gh2a_.ent-d1fb6a_.ent", "d1gh2a_.ent-d1fhe_2.ent", "d1gh2a_.ent-d1hyua4.ent", "d1gh2a_.ent-d1iloa_.ent", "d1gh2a_.ent-d1k0ma2.ent", "d1gh2a_.ent-d1k3ya2.ent", "d1gh2a_.ent-d1kte__.ent", "d1gh2a_.ent-d1m2da_.ent", "d1gh2a_.ent-d1qmha1.ent", "d1gh2a_.ent-d1quwa_.ent", "d1gh6a_.ent-d1grj_1.ent", "d1gh6a_.ent-d1hdj__.ent", "d1gh6a_.ent-d1ivsa1.ent", "d1gh6a_.ent-d1ix9a1.ent", "d1gh6a_.ent-d1jj2u_.ent", "d1gh6a_.ent-d1k4ta1.ent", "d1gh6a_.ent-d1lrza1.ent", "d1gh6a_.ent-d1seta1.ent", "d1gh6a_.ent-d1xbl__.ent", "d1gh7a1.ent-d1cd9b2.ent", "d1gh7a1.ent-d1cfb_1.ent", "d1gh7a1.ent-d1egja_.ent", "d1gh7a1.ent-d1f6fb1.ent", "d1gh7a1.ent-d1f6fb2.ent", "d1gh7a1.ent-d1fyhb1.ent", "d1gh7a1.ent-d1i1ra1.ent", "d1gh7a1.ent-d1lqsr1.ent", "d1gh7a1.ent-d1n26a2.ent", "d1gh7a1.ent-d1qg3a2.ent", "d1gh7a1.ent-d2hft_1.ent", "d1gh7a1.ent-d2hft_2.ent", "d1gh7a2.ent-d1axib2.ent", "d1gh7a2.ent-d1bpv__.ent", "d1gh7a2.ent-d1bqua2.ent", "d1gh7a2.ent-d1cd9b1.ent", "d1gh7a2.ent-d1cd9b2.ent", "d1gh7a2.ent-d1cfb_1.ent", "d1gh7a2.ent-d1cfb_2.ent", "d1gh7a2.ent-d1eerb1.ent", "d1gh7a2.ent-d1eerb2.ent", "d1gh7a2.ent-d1egja_.ent", "d1gh7a2.ent-d1f6fb1.ent", "d1gh7a2.ent-d1f6fb2.ent", "d1gh7a2.ent-d1fyhb1.ent", "d1gh7a2.ent-d1fyhb2.ent", "d1gh7a2.ent-d1gh7a1.ent", "d1gh7a2.ent-d1i1ra1.ent", "d1gh7a2.ent-d1lqsr1.ent", "d1gh7a2.ent-d1lqsr2.ent", "d1gh7a2.ent-d1n26a2.ent", "d1gh7a2.ent-d1n26a3.ent", "d1gh7a2.ent-d1qg3a2.ent", "d1gh7a2.ent-d2hft_1.ent", "d1gh7a2.ent-d2hft_2.ent", "d1gh9a_.ent-d1i50i1.ent", "d1gh9a_.ent-d1i50i2.ent", "d1gh9a_.ent-d1i50l_.ent", "d1gh9a_.ent-d1jj22_.ent", "d1gh9a_.ent-d1jj2y_.ent", "d1gh9a_.ent-d1jj2z_.ent", "d1gh9a_.ent-d1lkoa2.ent", "d1gh9a_.ent-d1m2oa5.ent", "d1gh9a_.ent-d1ocrf_.ent", "d1gh9a_.ent-d1pft__.ent", "d1gh9a_.ent-d1rb9__.ent", "d1gh9a_.ent-d1tfi__.ent", "d1gh9a_.ent-d1yua_1.ent", "d1gh9a_.ent-d1yua_2.ent", "d1gh9a_.ent-d1zaka2.ent", "d1gh9a_.ent-d1zin_2.ent", "d1ghk__.ent-d1htp__.ent", "d1ghk__.ent-d1k8ma_.ent", "d1ghk__.ent-d1lac__.ent", "d1ghk__.ent-d1qjoa_.ent", "d1ghpa_.ent-d1iyoa_.ent", "d1ghpa_.ent-d1l0ga_.ent", "d1ghpa_.ent-d1m40a_.ent", "d1ghpa_.ent-d1mfoa_.ent", "d1ghpa_.ent-d1mwxa3.ent", "d1ghpa_.ent-d1nj4a2.ent", "d1ghpa_.ent-d1qmea4.ent", "d1ghpa_.ent-d4blma_.ent", "d1giqa1.ent-d1giqa2.ent", "d1giqa1.ent-d1gxya_.ent", "d1giqa1.ent-d1ikpa2.ent", "d1giqa1.ent-d1j7na3.ent", "d1giqa1.ent-d1prta_.ent", "d1giqa1.ent-d1qs1a1.ent", "d1giqa1.ent-d1qs1a2.ent", "d1giqa2.ent-d1gxya_.ent", "d1giqa2.ent-d1ikpa2.ent", "d1giqa2.ent-d1j7na3.ent", "d1giqa2.ent-d1prta_.ent", "d1giqa2.ent-d1qs1a1.ent", "d1giqa2.ent-d1qs1a2.ent", "d1gjwa1.ent-d1hx0a1.ent", "d1gjwa1.ent-d1iv8a1.ent", "d1gjwa1.ent-d1j0ha2.ent", "d1gjwa1.ent-d1jae_1.ent", "d1gjwa1.ent-d1ji1a2.ent", "d1gjwa1.ent-d1ji2a2.ent", "d1gjwa1.ent-d1ktba1.ent", "d1gjwa1.ent-d1kwga1.ent", "d1gjwa1.ent-d1lwha1.ent", "d1gjwa1.ent-d1m7xa2.ent", "d1gjwa1.ent-d1qhoa3.ent", "d1gjwa1.ent-d1uok_1.ent", "d1gjwa1.ent-d7taa_1.ent", "d1gjwa2.ent-d1b9za2.ent", "d1gjwa2.ent-d1bf2_3.ent", "d1gjwa2.ent-d1cbg__.ent", "d1gjwa2.ent-d1ccwb_.ent", "d1gjwa2.ent-d1cz1a_.ent", "d1gjwa2.ent-d1d3ga_.ent", "d1gjwa2.ent-d1e43a2.ent", "d1gjwa2.ent-d1e4ia_.ent", "d1gjwa2.ent-d1e4mm_.ent", "d1gjwa2.ent-d1edg__.ent", "d1gjwa2.ent-d1eexa_.ent", "d1gjwa2.ent-d1eh9a3.ent", "d1gjwa2.ent-d1eswa_.ent", "d1gjwa2.ent-d1f8ma_.ent", "d1gjwa2.ent-d1g5aa2.ent", "d1gjwa2.ent-d1gqia1.ent", "d1gjwa2.ent-d1gvoa_.ent", "d1gjwa2.ent-d1gw1a_.ent", "d1gjwa2.ent-d1hxja_.ent", "d1gjwa2.ent-d1iexa1.ent", "d1gjwa2.ent-d1itua_.ent", "d1gjwa2.ent-d1j0ha3.ent", "d1gjwa2.ent-d1j5sa_.ent", "d1gjwa2.ent-d1ji1a3.ent", "d1gjwa2.ent-d1k4ga_.ent", "d1gjwa2.ent-d1k9da1.ent", "d1gjwa2.ent-d1kbla1.ent", "d1gjwa2.ent-d1kwga2.ent", "d1gjwa2.ent-d1lwha2.ent", "d1gjwa2.ent-d1m7ja3.ent", "d1gjwa2.ent-d1muwa_.ent", "d1gjwa2.ent-d1ntha_.ent", "d1gjwa2.ent-d1pama4.ent", "d1gjwa2.ent-d1qba_3.ent", "d1gjwa2.ent-d1qhoa4.ent", "d1gjwa2.ent-d1qvba_.ent", "d1gjwa2.ent-d1uok_2.ent", "d1gjwa2.ent-d7reqa1.ent", "d1gjwa2.ent-d7taa_2.ent", "d1gk8i_.ent-d1rblm_.ent", "d1gkab_.ent-d1hms__.ent", "d1gkab_.ent-d1i4ua_.ent", "d1gkab_.ent-d1ifc__.ent", "d1gkab_.ent-d1jv4a_.ent", "d1gkab_.ent-d1koia_.ent", "d1gkab_.ent-d1kqwa_.ent", "d1gkab_.ent-d1lf7a_.ent", "d1gkab_.ent-d1o1va_.ent", "d1gkab_.ent-d1qfta_.ent", "d1gkab_.ent-d1qqsa_.ent", "d1gkda_.ent-d1hs6a3.ent", "d1gkda_.ent-d1i1ip_.ent", "d1gkda_.ent-d1j7na1.ent", "d1gkda_.ent-d1j7na2.ent", "d1gkda_.ent-d1jk3a_.ent", "d1gkda_.ent-d1k7ia2.ent", "d1gkda_.ent-d1k9xa_.ent", "d1gkda_.ent-d1kapp2.ent", "d1gkda_.ent-d1keia_.ent", "d1gkda_.ent-d1kufa_.ent", "d1gkda_.ent-d1lml__.ent", "d1gkda_.ent-d3btaa3.ent", "d1gkga2.ent-d1gkna1.ent", "d1gkga2.ent-d1gkna2.ent", "d1gkga2.ent-d1gpza2.ent", "d1gkga2.ent-d1gpza3.ent", "d1gkga2.ent-d1hcc__.ent", "d1gkga2.ent-d1hfi__.ent", "d1gkga2.ent-d1ly2a1.ent", "d1gkga2.ent-d1ly2a2.ent", "d1gkga2.ent-d1quba1.ent", "d1gkga2.ent-d1quba2.ent", "d1gkga2.ent-d1quba3.ent", "d1gkga2.ent-d1quba4.ent", "d1gkga2.ent-d1quba5.ent", "d1gkla_.ent-d1hlga_.ent", "d1gkla_.ent-d1imja_.ent", "d1gkla_.ent-d1ispa_.ent", "d1gkla_.ent-d1jfra_.ent", "d1gkla_.ent-d1ju3a2.ent", "d1gkla_.ent-d1ku0a_.ent", "d1gkla_.ent-d1l7aa_.ent", "d1gkla_.ent-d1lzla_.ent", "d1gkla_.ent-d1mnaa_.ent", "d1gkla_.ent-d1n1ma2.ent", "d1gkla_.ent-d1qj4a_.ent", "d1gkla_.ent-d1qlwa_.ent", "d1gkla_.ent-d1qo7a_.ent", "d1gkla_.ent-d1tca__.ent", "d1gkla_.ent-d1thta_.ent", "d1gkla_.ent-d3tgl__.ent", "d1gkna1.ent-d1gkna2.ent", "d1gkna1.ent-d1gpza2.ent", "d1gkna1.ent-d1gpza3.ent", "d1gkna1.ent-d1hcc__.ent", "d1gkna1.ent-d1hfi__.ent", "d1gkna1.ent-d1ly2a1.ent", "d1gkna1.ent-d1ly2a2.ent", "d1gkna1.ent-d1quba1.ent", "d1gkna1.ent-d1quba2.ent", "d1gkna1.ent-d1quba3.ent", "d1gkna1.ent-d1quba4.ent", "d1gkna1.ent-d1quba5.ent", "d1gkna2.ent-d1gpza2.ent", "d1gkna2.ent-d1gpza3.ent", "d1gkna2.ent-d1hcc__.ent", "d1gkna2.ent-d1hfi__.ent", "d1gkna2.ent-d1ly2a1.ent", "d1gkna2.ent-d1ly2a2.ent", "d1gkna2.ent-d1quba1.ent", "d1gkna2.ent-d1quba2.ent", "d1gkna2.ent-d1quba3.ent", "d1gkna2.ent-d1quba4.ent", "d1gkna2.ent-d1quba5.ent", "d1gkpa1.ent-d1gkra1.ent", "d1gkpa1.ent-d1k1da1.ent", "d1gkpa1.ent-d1k6wa1.ent", "d1gkpa1.ent-d1m7ja1.ent", "d1gkpa1.ent-d1m7ja2.ent", "d1gkpa1.ent-d4ubpc1.ent", "d1gkra1.ent-d1k1da1.ent", "d1gkra1.ent-d1k6wa1.ent", "d1gkra1.ent-d1m7ja1.ent", "d1gkra1.ent-d1m7ja2.ent", "d1gkra1.ent-d4ubpc1.ent", "d1gkub3.ent-d1i7da_.ent", "d1gkza1.ent-d1gm5a1.ent", "d1gkza1.ent-d1is2a1.ent", "d1gkza1.ent-d1is2a2.ent", "d1gkza1.ent-d1jqia1.ent", "d1gkza2.ent-d1i58a_.ent", "d1gkza2.ent-d1id0a_.ent", "d1gkza2.ent-d1jm6a2.ent", "d1gkza2.ent-d1kija2.ent", "d1gkza2.ent-d1l0oa_.ent", "d1gkza2.ent-d1mu5a3.ent", "d1gl5a_.ent-d1gria1.ent", "d1gl5a_.ent-d1h92a_.ent", "d1gl5a_.ent-d1i07a_.ent", "d1gl5a_.ent-d1i1ja_.ent", "d1gl5a_.ent-d1jo8a_.ent", "d1gl5a_.ent-d1jqqa_.ent", "d1gl5a_.ent-d1k4us_.ent", "d1gl5a_.ent-d1kjwa1.ent", "d1gl5a_.ent-d1neb__.ent", "d1gl5a_.ent-d1pht__.ent", "d1gl5a_.ent-d1pwt__.ent", "d1gl5a_.ent-d1qcfa1.ent", "d1gl5a_.ent-d1ycsb2.ent", "d1gl5a_.ent-d2hsp__.ent", "d1glag1.ent-d1az9_1.ent", "d1glag1.ent-d1bco_2.ent", "d1glag1.ent-d1bupa1.ent", "d1glag1.ent-d1bupa2.ent", "d1glag1.ent-d1czan1.ent", "d1glag1.ent-d1e4ft1.ent", "d1glag1.ent-d1e4ft2.ent", "d1glag1.ent-d1g99a2.ent", "d1glag1.ent-d1glag2.ent", "d1glag1.ent-d1huxa_.ent", "d1glag1.ent-d1ig8a1.ent", "d1glag1.ent-d1ig8a2.ent", "d1glag1.ent-d1j54a_.ent", "d1glag1.ent-d1j6za2.ent", "d1glag1.ent-d1jcfa1.ent", "d1glag1.ent-d1jj2m_.ent", "d1glag1.ent-d1k8ka1.ent", "d1glag1.ent-d1kcfa2.ent", "d1glag1.ent-d1mwma1.ent", "d1glag1.ent-d1mwma2.ent", "d1glag1.ent-d1nbwa2.ent", "d1glag1.ent-d1nbwa3.ent", "d1glag1.ent-d1t7pa1.ent", "d1glag1.ent-d1xwl_1.ent", "d1glag2.ent-d1az9_1.ent", "d1glag2.ent-d1bco_2.ent", "d1glag2.ent-d1bupa1.ent", "d1glag2.ent-d1bupa2.ent", "d1glag2.ent-d1czan1.ent", "d1glag2.ent-d1czan2.ent", "d1glag2.ent-d1e4ft1.ent", "d1glag2.ent-d1e4ft2.ent", "d1glag2.ent-d1g99a2.ent", "d1glag2.ent-d1glag1.ent", "d1glag2.ent-d1huxa_.ent", "d1glag2.ent-d1ig8a1.ent", "d1glag2.ent-d1ig8a2.ent", "d1glag2.ent-d1j54a_.ent", "d1glag2.ent-d1j6za2.ent", "d1glag2.ent-d1jcfa1.ent", "d1glag2.ent-d1jj2m_.ent", "d1glag2.ent-d1k8ka1.ent", "d1glag2.ent-d1kcfa2.ent", "d1glag2.ent-d1mwma1.ent", "d1glag2.ent-d1mwma2.ent", "d1glag2.ent-d1nbwa2.ent", "d1glag2.ent-d1nbwa3.ent", "d1glag2.ent-d1t7pa1.ent", "d1glag2.ent-d1xwl_1.ent", "d1glqa1.ent-d1gnwa1.ent", "d1glqa1.ent-d1gula1.ent", "d1glqa1.ent-d1gwca1.ent", "d1glqa1.ent-d1jlva1.ent", "d1glqa1.ent-d1k0da1.ent", "d1glqa1.ent-d1k0ma1.ent", "d1glqa1.ent-d1k3ya1.ent", "d1glqa1.ent-d1ljra1.ent", "d1glqa1.ent-d1m0ua1.ent", "d1glqa1.ent-d1pd211.ent", "d1glqa1.ent-d1pmt_1.ent", "d1glqa1.ent-d2gsq_1.ent", "d1glqa1.ent-d2gsta1.ent", "d1gm5a1.ent-d1is2a1.ent", "d1gm5a1.ent-d1is2a2.ent", "d1gm5a1.ent-d1jqia1.ent", "d1gm5a2.ent-d1b3qa2.ent", "d1gm5a2.ent-d1d7qa_.ent", "d1gm5a2.ent-d1e1oa1.ent", "d1gm5a2.ent-d1eova1.ent", "d1gm5a2.ent-d1ewia_.ent", "d1gm5a2.ent-d1fgua1.ent", "d1gm5a2.ent-d1fgua2.ent", "d1gm5a2.ent-d1fjgl_.ent", "d1gm5a2.ent-d1fl0a_.ent", "d1gm5a2.ent-d1go3e_.ent", "d1gm5a2.ent-d1i40a_.ent", "d1gm5a2.ent-d1i50h_.ent", "d1gm5a2.ent-d1iyjb3.ent", "d1gm5a2.ent-d1iyjb5.ent", "d1gm5a2.ent-d1jb3a_.ent", "d1gm5a2.ent-d1jb7a1.ent", "d1gm5a2.ent-d1jb7a2.ent", "d1gm5a2.ent-d1jb7a3.ent", "d1gm5a2.ent-d1jjcb3.ent", "d1gm5a2.ent-d1k28a1.ent", "d1gm5a2.ent-d1l1oc_.ent", "d1gm5a2.ent-d1quqa_.ent", "d1gm5a2.ent-d1quqb_.ent", "d1gm5a2.ent-d1qvca_.ent", "d1gm5a2.ent-d1sty__.ent", "d1gm5a2.ent-d3seb_1.ent", "d1gm5a3.ent-d1cr1a_.ent", "d1gm5a3.ent-d1g8ya_.ent", "d1gm5a3.ent-d1lv7a_.ent", "d1gmea_.ent-d1shsa_.ent", "d1gmia_.ent-d1k5wa_.ent", "d1gmia_.ent-d1l4ia2.ent", "d1gmia_.ent-d1qasa2.ent", "d1gmia_.ent-d1rlw__.ent", "d1gmia_.ent-d1rsy__.ent", "d1gmia_.ent-d1who__.ent", "d1gmia_.ent-d3rpba_.ent", "d1gmla_.ent-d1kbla2.ent", "d1gmla_.ent-d1kid__.ent", "d1gmla_.ent-d1l5ja2.ent", "d1gmla_.ent-d1nbwa1.ent", "d1gmma_.ent-d1gnya_.ent", "d1gmma_.ent-d1gu3a_.ent", "d1gmma_.ent-d1guia_.ent", "d1gmma_.ent-d1h6ya_.ent", "d1gmma_.ent-d1i5pa1.ent", "d1gmma_.ent-d1jhja_.ent", "d1gmma_.ent-d1ju3a1.ent", "d1gmma_.ent-d1jz8a3.ent", "d1gmma_.ent-d1k12a_.ent", "d1gmma_.ent-d1k3ia2.ent", "d1gmma_.ent-d1kgya_.ent", "d1gmma_.ent-d1l7la_.ent", "d1gmma_.ent-d1lnsa2.ent", "d1gmma_.ent-d1xnaa_.ent", "d1gmya_.ent-d1gx3a_.ent", "d1gmya_.ent-d1iu4a_.ent", "d1gmya_.ent-d1kxra_.ent", "d1gmya_.ent-d1l9na4.ent", "d1gmya_.ent-d1me4a_.ent", "d1gmya_.ent-d1nbfa_.ent", "d1gmya_.ent-d1ppn__.ent", "d1gmya_.ent-d1qmya_.ent", "d1gmya_.ent-d1uch__.ent", "d1gmya_.ent-d2act__.ent", "d1gmya_.ent-d2cb5a_.ent", "d1gmya_.ent-d3gcb__.ent", "d1gmya_.ent-d7pcka_.ent", "d1gnf__.ent-d1ibia2.ent", "d1gnf__.ent-d1iml_2.ent", "d1gnf__.ent-d1jj2t_.ent", "d1gnf__.ent-d1k3xa3.ent", "d1gnf__.ent-d1kb2a_.ent", "d1gnf__.ent-d1l1za3.ent", "d1gnf__.ent-d1lata_.ent", "d1gnf__.ent-d1lv3a_.ent", "d1gnf__.ent-d1zfo__.ent", "d1gnf__.ent-d2nllb_.ent", "d1gnf__.ent-d3gata_.ent", "d1gnf__.ent-d7gata_.ent", "d1gnia1.ent-d1gnia2.ent", "d1gnia1.ent-d1gnia3.ent", "d1gnia1.ent-d1kxpd1.ent", "d1gnia1.ent-d1kxpd2.ent", "d1gnia1.ent-d1kxpd3.ent", "d1gnia2.ent-d1gnia3.ent", "d1gnia2.ent-d1kxpd1.ent", "d1gnia2.ent-d1kxpd2.ent", "d1gnia2.ent-d1kxpd3.ent", "d1gnia3.ent-d1kxpd1.ent", "d1gnia3.ent-d1kxpd2.ent", "d1gnia3.ent-d1kxpd3.ent", "d1gnla_.ent-d1jjya_.ent", "d1gnla_.ent-d1mjga_.ent", "d1gnla_.ent-d1mjgm_.ent", "d1gnua_.ent-d1ayfa_.ent", "d1gnua_.ent-d1bmlc3.ent", "d1gnua_.ent-d1c9fa_.ent", "d1gnua_.ent-d1czpa_.ent", "d1gnua_.ent-d1f52a1.ent", "d1gnua_.ent-d1fm0d_.ent", "d1gnua_.ent-d1h4ra3.ent", "d1gnua_.ent-d1h8ca_.ent", "d1gnua_.ent-d1i42a_.ent", "d1gnua_.ent-d1ip9a_.ent", "d1gnua_.ent-d1j8ca_.ent", "d1gnua_.ent-d1k8rb_.ent", "d1gnua_.ent-d1l4db_.ent", "d1gnua_.ent-d1l5pa_.ent", "d1gnua_.ent-d1l7ya_.ent", "d1gnua_.ent-d1lfda_.ent", "d1gnua_.ent-d1lm8b_.ent", "d1gnua_.ent-d1m94a_.ent", "d1gnua_.ent-d1qlab2.ent", "d1gnua_.ent-d1rlf__.ent", "d1gnua_.ent-d3seb_2.ent", "d1gnua_.ent-d3tss_2.ent", "d1gnwa1.ent-d1gula1.ent", "d1gnwa1.ent-d1gwca1.ent", "d1gnwa1.ent-d1jlva1.ent", "d1gnwa1.ent-d1k0da1.ent", "d1gnwa1.ent-d1k0ma1.ent", "d1gnwa1.ent-d1k3ya1.ent", "d1gnwa1.ent-d1ljra1.ent", "d1gnwa1.ent-d1m0ua1.ent", "d1gnwa1.ent-d1pd211.ent", "d1gnwa1.ent-d1pmt_1.ent", "d1gnwa1.ent-d2gsq_1.ent", "d1gnwa1.ent-d2gsta1.ent", "d1gnya_.ent-d1ciy_1.ent", "d1gnya_.ent-d1dlc_1.ent", "d1gnya_.ent-d1eut_2.ent", "d1gnya_.ent-d1gmma_.ent", "d1gnya_.ent-d1gu3a_.ent", "d1gnya_.ent-d1guia_.ent", "d1gnya_.ent-d1h6ya_.ent", "d1gnya_.ent-d1i5pa1.ent", "d1gnya_.ent-d1jhja_.ent", "d1gnya_.ent-d1ji6a1.ent", "d1gnya_.ent-d1ju3a1.ent", "d1gnya_.ent-d1jz8a3.ent", "d1gnya_.ent-d1k12a_.ent", "d1gnya_.ent-d1k3ia2.ent", "d1gnya_.ent-d1kgya_.ent", "d1gnya_.ent-d1l7la_.ent", "d1gnya_.ent-d1lnsa2.ent", "d1gnya_.ent-d1xnaa_.ent", "d1go3e_.ent-d1b3qa2.ent", "d1go3e_.ent-d1d7qa_.ent", "d1go3e_.ent-d1e1oa1.ent", "d1go3e_.ent-d1eova1.ent", "d1go3e_.ent-d1ewia_.ent", "d1go3e_.ent-d1fgua1.ent", "d1go3e_.ent-d1fgua2.ent", "d1go3e_.ent-d1fjgl_.ent", "d1go3e_.ent-d1fl0a_.ent", "d1go3e_.ent-d1i40a_.ent", "d1go3e_.ent-d1i50h_.ent", "d1go3e_.ent-d1iyjb3.ent", "d1go3e_.ent-d1iyjb5.ent", "d1go3e_.ent-d1jb3a_.ent", "d1go3e_.ent-d1jb7a1.ent", "d1go3e_.ent-d1jb7a2.ent", "d1go3e_.ent-d1jb7a3.ent", "d1go3e_.ent-d1jjcb3.ent", "d1go3e_.ent-d1k28a1.ent", "d1go3e_.ent-d1l1oc_.ent", "d1go3e_.ent-d1quqa_.ent", "d1go3e_.ent-d1quqb_.ent", "d1go3e_.ent-d1qvca_.ent", "d1go3e_.ent-d1sty__.ent", "d1go3e_.ent-d3seb_1.ent", "d1go3f_.ent-d1jmsa1.ent", "d1go3f_.ent-d1jmsa3.ent", "d1go3f_.ent-d1jyga_.ent", "d1go3f_.ent-d1kfta_.ent", "d1go3f_.ent-d1lb2b_.ent", "d1go3f_.ent-d1tfr_1.ent", "d1goia1.ent-d1o6wa2.ent", "d1goia1.ent-d1pina1.ent", "d1goia3.ent-d1itxa2.ent", "d1goia3.ent-d1jnda2.ent", "d1goia3.ent-d1kfwa2.ent", "d1goia3.ent-d1lg2a2.ent", "d1goia3.ent-d1ll7a2.ent", "d1gosa1.ent-d1b5qa1.ent", "d1gosa1.ent-d1chua2.ent", "d1gosa1.ent-d1cjca1.ent", "d1gosa1.ent-d1d5ta1.ent", "d1gosa1.ent-d1ebda1.ent", "d1gosa1.ent-d1f8ra1.ent", "d1gosa1.ent-d1feca1.ent", "d1gosa1.ent-d1foha5.ent", "d1gosa1.ent-d1h6va1.ent", "d1gosa1.ent-d1jeha1.ent", "d1gosa1.ent-d1jnra2.ent", "d1gosa1.ent-d1ju2a1.ent", "d1gosa1.ent-d1k0ia1.ent", "d1gosa1.ent-d1kdga1.ent", "d1gosa1.ent-d1kf6a2.ent", "d1gosa1.ent-d1kssa2.ent", "d1gosa1.ent-d1l9ea1.ent", "d1gosa1.ent-d1mo9a1.ent", "d1gosa1.ent-d1neka2.ent", "d1gosa1.ent-d1ojt_1.ent", "d1gosa1.ent-d1qlaa2.ent", "d1gosa1.ent-d1qo8a2.ent", "d1gosa1.ent-d3lada1.ent", "d1gosa2.ent-d1gpea2.ent", "d1gosa2.ent-d1i8ta2.ent", "d1gosa2.ent-d1ju2a2.ent", "d1gosa2.ent-d1k0ia2.ent", "d1gosa2.ent-d1kdga2.ent", "d1gosa2.ent-d1l9ea2.ent", "d1gosa2.ent-d1mxta2.ent", "d1gox__.ent-d1gtea2.ent", "d1gox__.ent-d1gvoa_.ent", "d1gox__.ent-d1huva_.ent", "d1gox__.ent-d1icpa_.ent", "d1gox__.ent-d1kbia1.ent", "d1gox__.ent-d1llwa2.ent", "d1gox__.ent-d1o94a1.ent", "d1gox__.ent-d1oyb__.ent", "d1gox__.ent-d2dora_.ent", "d1gp6a_.ent-d1gy9a_.ent", "d1gp6a_.ent-d1h2ka_.ent", "d1gp6a_.ent-d1hw5a2.ent", "d1gp6a_.ent-d1ig0a1.ent", "d1gp6a_.ent-d1jr7a_.ent", "d1gp6a_.ent-d1juha_.ent", "d1gp6a_.ent-d1lrha_.ent", "d1gp6a_.ent-d1m4oa_.ent", "d1gp6a_.ent-d1pmi__.ent", "d1gp6a_.ent-d1qjea_.ent", "d1gp6a_.ent-d1wapa_.ent", "d1gp6a_.ent-d2arca_.ent", "d1gpc__.ent-d1b3qa2.ent", "d1gpc__.ent-d1br9__.ent", "d1gpc__.ent-d1d7qa_.ent", "d1gpc__.ent-d1e1oa1.ent", "d1gpc__.ent-d1eova1.ent", "d1gpc__.ent-d1ewia_.ent", "d1gpc__.ent-d1fgua1.ent", "d1gpc__.ent-d1fgua2.ent", "d1gpc__.ent-d1fjgl_.ent", "d1gpc__.ent-d1fl0a_.ent", "d1gpc__.ent-d1gm5a2.ent", "d1gpc__.ent-d1go3e_.ent", "d1gpc__.ent-d1i40a_.ent", "d1gpc__.ent-d1i50h_.ent", "d1gpc__.ent-d1iyjb3.ent", "d1gpc__.ent-d1iyjb5.ent", "d1gpc__.ent-d1jb3a_.ent", "d1gpc__.ent-d1jb7a1.ent", "d1gpc__.ent-d1jb7a2.ent", "d1gpc__.ent-d1jb7a3.ent", "d1gpc__.ent-d1jb7b_.ent", "d1gpc__.ent-d1je5a_.ent", "d1gpc__.ent-d1jjcb3.ent", "d1gpc__.ent-d1k28a1.ent", "d1gpc__.ent-d1kxla_.ent", "d1gpc__.ent-d1l1oc_.ent", "d1gpc__.ent-d1quqa_.ent", "d1gpc__.ent-d1quqb_.ent", "d1gpc__.ent-d1qvca_.ent", "d1gpc__.ent-d1sty__.ent", "d1gpc__.ent-d3seb_1.ent", "d1gpea1.ent-d1b5qa1.ent", "d1gpea1.ent-d1chua2.ent", "d1gpea1.ent-d1cjca1.ent", "d1gpea1.ent-d1d5ta1.ent", "d1gpea1.ent-d1ebda1.ent", "d1gpea1.ent-d1f8ra1.ent", "d1gpea1.ent-d1feca1.ent", "d1gpea1.ent-d1foha5.ent", "d1gpea1.ent-d1gosa1.ent", "d1gpea1.ent-d1h6va1.ent", "d1gpea1.ent-d1jeha1.ent", "d1gpea1.ent-d1jnra2.ent", "d1gpea1.ent-d1ju2a1.ent", "d1gpea1.ent-d1k0ia1.ent", "d1gpea1.ent-d1kdga1.ent", "d1gpea1.ent-d1kf6a2.ent", "d1gpea1.ent-d1kssa2.ent", "d1gpea1.ent-d1l9ea1.ent", "d1gpea1.ent-d1mo9a1.ent", "d1gpea1.ent-d1neka2.ent", "d1gpea1.ent-d1ojt_1.ent", "d1gpea1.ent-d1qlaa2.ent", "d1gpea1.ent-d1qo8a2.ent", "d1gpea1.ent-d3lada1.ent", "d1gpea2.ent-d1i8ta2.ent", "d1gpea2.ent-d1ju2a2.ent", "d1gpea2.ent-d1k0ia2.ent", "d1gpea2.ent-d1kdga2.ent", "d1gpea2.ent-d1l9ea2.ent", "d1gpea2.ent-d1mxta2.ent", "d1gph11.ent-d1hgxa_.ent", "d1gph11.ent-d1i5ea_.ent", "d1gph11.ent-d1l1qa_.ent", "d1gph11.ent-d1lh0a_.ent", "d1gph11.ent-d1nula_.ent", "d1gph11.ent-d1qb7a_.ent", "d1gph11.ent-d1tc1a_.ent", "d1gph12.ent-d1iru1_.ent", "d1gph12.ent-d1iru2_.ent", "d1gph12.ent-d1iruk_.ent", "d1gph12.ent-d1jgta2.ent", "d1gph12.ent-d1pma1_.ent", "d1gph12.ent-d1pmaa_.ent", "d1gph12.ent-d1ryp1_.ent", "d1gph12.ent-d1ryp2_.ent", "d1gph12.ent-d1rypf_.ent", "d1gph12.ent-d1ryph_.ent", "d1gph12.ent-d1rypi_.ent", "d1gph12.ent-d1rypj_.ent", "d1gph12.ent-d1rypk_.ent", "d1gph12.ent-d1rypl_.ent", "d1gpja3.ent-d1dqaa1.ent", "d1gpja3.ent-d1h72c2.ent", "d1gpja3.ent-d1qd1a2.ent", "d1gpja3.ent-d1regx_.ent", "d1gpma1.ent-d1ihoa_.ent", "d1gpma1.ent-d1ile_3.ent", "d1gpma1.ent-d1irxa2.ent", "d1gpma1.ent-d1j09a2.ent", "d1gpma1.ent-d1jgta1.ent", "d1gpma1.ent-d1jhda2.ent", "d1gpma1.ent-d1jila_.ent", "d1gpma1.ent-d1jmva_.ent", "d1gpma1.ent-d1k4ma_.ent", "d1gpma1.ent-d1k92a1.ent", "d1gpma1.ent-d1kora1.ent", "d1gpma1.ent-d1kqna_.ent", "d1gpma1.ent-d1kqpa_.ent", "d1gpma1.ent-d1li5a2.ent", "d1gpma1.ent-d1mjha_.ent", "d1gpma1.ent-d1n3la_.ent", "d1gpma1.ent-d1o97c_.ent", "d1gpma1.ent-d1o97d1.ent", "d1gpma1.ent-d1qjca_.ent", "d1gpma1.ent-d1sur__.ent", "d1gpma2.ent-d1i7qb_.ent", "d1gpma2.ent-d1k9vf_.ent", "d1gpma2.ent-d1ka9h_.ent", "d1gpma2.ent-d1kwga3.ent", "d1gpma2.ent-d1l9xa_.ent", "d1gpma2.ent-d1qdlb_.ent", "d1gpma3.ent-d1ib8a2.ent", "d1gpma3.ent-d1iw5a_.ent", "d1gpma3.ent-d1k0ra2.ent", "d1gpma3.ent-d1k0ra3.ent", "d1gpma3.ent-d1mkya3.ent", "d1gpma3.ent-d3proc1.ent", "d1gpma3.ent-d3proc2.ent", "d1gpr__.ent-d1gsoa1.ent", "d1gpr__.ent-d1htp__.ent", "d1gpr__.ent-d1k8ma_.ent", "d1gpr__.ent-d1kjqa1.ent", "d1gpr__.ent-d2f3ga_.ent", "d1gpr__.ent-d2gpr__.ent", "d1gps__.ent-d1b9wa1.ent", "d1gps__.ent-d1b9wa2.ent", "d1gps__.ent-d1cixa_.ent", "d1gps__.ent-d1g9pa_.ent", "d1gps__.ent-d1h59b_.ent", "d1gps__.ent-d1hyka_.ent", "d1gps__.ent-d1i2ua_.ent", "d1gps__.ent-d1ica__.ent", "d1gps__.ent-d1imt_2.ent", "d1gps__.ent-d1jkza_.ent", "d1gps__.ent-d1jxca_.ent", "d1gps__.ent-d1lpba2.ent", "d1gps__.ent-d1myn__.ent", "d1gps__.ent-d1npia_.ent", "d1gps__.ent-d1nrb__.ent", "d1gps__.ent-d1qkya_.ent", "d1gps__.ent-d1sco__.ent", "d1gps__.ent-d1scy__.ent", "d1gps__.ent-d1sis__.ent", "d1gps__.ent-d1tsk__.ent", "d1gps__.ent-d2sn3__.ent", "d1gpua1.ent-d1gpua2.ent", "d1gpua1.ent-d1ik6a1.ent", "d1gpua1.ent-d1jsca2.ent", "d1gpua1.ent-d1jsca3.ent", "d1gpua1.ent-d1keka1.ent", "d1gpua1.ent-d1keka2.ent", "d1gpua1.ent-d1l8aa1.ent", "d1gpua1.ent-d1l8aa2.ent", "d1gpua1.ent-d1poxa2.ent", "d1gpua1.ent-d1poxa3.ent", "d1gpua1.ent-d1pvda2.ent", "d1gpua1.ent-d1pvda3.ent", "d1gpua1.ent-d1zpda2.ent", "d1gpua1.ent-d1zpda3.ent", "d1gpua2.ent-d1ik6a1.ent", "d1gpua2.ent-d1jsca2.ent", "d1gpua2.ent-d1jsca3.ent", "d1gpua2.ent-d1keka1.ent", "d1gpua2.ent-d1keka2.ent", "d1gpua2.ent-d1l8aa1.ent", "d1gpua2.ent-d1l8aa2.ent", "d1gpua2.ent-d1poxa2.ent", "d1gpua2.ent-d1poxa3.ent", "d1gpua2.ent-d1pvda2.ent", "d1gpua2.ent-d1pvda3.ent", "d1gpua2.ent-d1zpda2.ent", "d1gpua2.ent-d1zpda3.ent", "d1gpua3.ent-d1ik6a2.ent", "d1gpua3.ent-d1itza3.ent", "d1gpua3.ent-d1keka3.ent", "d1gpua3.ent-d1l8aa3.ent", "d1gpza1.ent-d1azza_.ent", "d1gpza1.ent-d1bio__.ent", "d1gpza1.ent-d1cgha_.ent", "d1gpza1.ent-d1gdna_.ent", "d1gpza1.ent-d1hj9a_.ent", "d1gpza1.ent-d2hlca_.ent", "d1gpza2.ent-d1gpza3.ent", "d1gpza2.ent-d1hcc__.ent", "d1gpza2.ent-d1hfi__.ent", "d1gpza2.ent-d1ly2a1.ent", "d1gpza2.ent-d1ly2a2.ent", "d1gpza2.ent-d1quba1.ent", "d1gpza2.ent-d1quba2.ent", "d1gpza2.ent-d1quba3.ent", "d1gpza2.ent-d1quba4.ent", "d1gpza2.ent-d1quba5.ent", "d1gpza3.ent-d1hcc__.ent", "d1gpza3.ent-d1hfi__.ent", "d1gpza3.ent-d1ly2a1.ent", "d1gpza3.ent-d1ly2a2.ent", "d1gpza3.ent-d1quba1.ent", "d1gpza3.ent-d1quba2.ent", "d1gpza3.ent-d1quba3.ent", "d1gpza3.ent-d1quba4.ent", "d1gpza3.ent-d1quba5.ent", "d1gq6a_.ent-d2ceva_.ent", "d1gqaa_.ent-d1jafa_.ent", "d1gqaa_.ent-d1mqva_.ent", "d1gqaa_.ent-d256ba_.ent", "d1gqaa_.ent-d2ccya_.ent", "d1gqia1.ent-d1b9za2.ent", "d1gqia1.ent-d1bf2_3.ent", "d1gqia1.ent-d1cbg__.ent", "d1gqia1.ent-d1ccwb_.ent", "d1gqia1.ent-d1cz1a_.ent", "d1gqia1.ent-d1d3ga_.ent", "d1gqia1.ent-d1e43a2.ent", "d1gqia1.ent-d1e4ia_.ent", "d1gqia1.ent-d1e4mm_.ent", "d1gqia1.ent-d1edg__.ent", "d1gqia1.ent-d1eexa_.ent", "d1gqia1.ent-d1eh9a3.ent", "d1gqia1.ent-d1eswa_.ent", "d1gqia1.ent-d1f8ma_.ent", "d1gqia1.ent-d1g5aa2.ent", "d1gqia1.ent-d1gvoa_.ent", "d1gqia1.ent-d1gw1a_.ent", "d1gqia1.ent-d1hxja_.ent", "d1gqia1.ent-d1iexa1.ent", "d1gqia1.ent-d1itua_.ent", "d1gqia1.ent-d1j0ha3.ent", "d1gqia1.ent-d1j5sa_.ent", "d1gqia1.ent-d1ji1a3.ent", "d1gqia1.ent-d1k4ga_.ent", "d1gqia1.ent-d1k9da1.ent", "d1gqia1.ent-d1kbla1.ent", "d1gqia1.ent-d1kwga2.ent", "d1gqia1.ent-d1lwha2.ent", "d1gqia1.ent-d1m7ja3.ent", "d1gqia1.ent-d1muwa_.ent", "d1gqia1.ent-d1ntha_.ent", "d1gqia1.ent-d1pama4.ent", "d1gqia1.ent-d1qba_3.ent", "d1gqia1.ent-d1qhoa4.ent", "d1gqia1.ent-d1qvba_.ent", "d1gqia1.ent-d1uok_2.ent", "d1gqia1.ent-d7reqa1.ent", "d1gqia1.ent-d7taa_2.ent", "d1gqia2.ent-d1hs6a3.ent", "d1gqia2.ent-d1i1ip_.ent", "d1gqia2.ent-d1j7na1.ent", "d1gqia2.ent-d1j7na2.ent", "d1gqia2.ent-d1jaka2.ent", "d1gqia2.ent-d1jk3a_.ent", "d1gqia2.ent-d1k9da2.ent", "d1gqia2.ent-d1k9xa_.ent", "d1gqia2.ent-d1kapp2.ent", "d1gqia2.ent-d1kufa_.ent", "d1gqia2.ent-d1lml__.ent", "d1gqia2.ent-d1qba_4.ent", "d1gqoa_.ent-d1gtza_.ent", "d1gqoa_.ent-d1h05a_.ent", "d1gqpa_.ent-d1ciy_1.ent", "d1gqpa_.ent-d1cx1a_.ent", "d1gqpa_.ent-d1czsa_.ent", "d1gqpa_.ent-d1d7pm_.ent", "d1gqpa_.ent-d1dlc_1.ent", "d1gqpa_.ent-d1eut_2.ent", "d1gqpa_.ent-d1gmma_.ent", "d1gqpa_.ent-d1gnya_.ent", "d1gqpa_.ent-d1gu3a_.ent", "d1gqpa_.ent-d1guia_.ent", "d1gqpa_.ent-d1h6ya_.ent", "d1gqpa_.ent-d1i5pa1.ent", "d1gqpa_.ent-d1jhja_.ent", "d1gqpa_.ent-d1ji6a1.ent", "d1gqpa_.ent-d1k12a_.ent", "d1gqpa_.ent-d1k3ia2.ent", "d1gqpa_.ent-d1k42a_.ent", "d1gqpa_.ent-d1kexa_.ent", "d1gqpa_.ent-d1xnaa_.ent", "d1gqva_.ent-d1rnfa_.ent", "d1gr0a1.ent-d1bg6_2.ent", "d1gr0a1.ent-d1c1da1.ent", "d1gr0a1.ent-d1cf2o1.ent", "d1gr0a1.ent-d1dlja2.ent", "d1gr0a1.ent-d1dpga1.ent", "d1gr0a1.ent-d1dssg1.ent", "d1gr0a1.ent-d1e5qa1.ent", "d1gr0a1.ent-d1f0ya2.ent", "d1gr0a1.ent-d1hdoa_.ent", "d1gr0a1.ent-d1hdr__.ent", "d1gr0a1.ent-d1jaya_.ent", "d1gr0a1.ent-d1lc0a1.ent", "d1gr0a1.ent-d1lu9a1.ent", "d1gr0a1.ent-d1qmga2.ent", "d1gr0a1.ent-d2naca1.ent", "d1gr0a1.ent-d2pgd_2.ent", "d1gr0a2.ent-d1h6da2.ent", "d1gr0a2.ent-d1j5pa3.ent", "d1gr0a2.ent-d1jkia2.ent", "d1gr0a2.ent-d1jn0a2.ent", "d1gr0a2.ent-d1lc0a2.ent", "d1gr0a2.ent-d1mb4a2.ent", "d1gr0a2.ent-d1qkia2.ent", "d1gr3a_.ent-d1kxga_.ent", "d1gr3a_.ent-d1tnra_.ent", "d1gr3a_.ent-d2tnfa_.ent", "d1gr8a_.ent-d1m22a_.ent", "d1gr8a_.ent-d1mt5a_.ent", "d1gria1.ent-d1h92a_.ent", "d1gria1.ent-d1i07a_.ent", "d1gria1.ent-d1i1ja_.ent", "d1gria1.ent-d1jo8a_.ent", "d1gria1.ent-d1jqqa_.ent", "d1gria1.ent-d1k4us_.ent", "d1gria1.ent-d1kjwa1.ent", "d1gria1.ent-d1neb__.ent", "d1gria1.ent-d1pht__.ent", "d1gria1.ent-d1pwt__.ent", "d1gria1.ent-d1qcfa1.ent", "d1gria1.ent-d1ycsb2.ent", "d1gria1.ent-d2hsp__.ent", "d1grj_1.ent-d1hdj__.ent", "d1grj_1.ent-d1ivsa1.ent", "d1grj_1.ent-d1ix9a1.ent", "d1grj_1.ent-d1jj2u_.ent", "d1grj_1.ent-d1k4ta1.ent", "d1grj_1.ent-d1lrza1.ent", "d1grj_1.ent-d1seta1.ent", "d1grj_2.ent-d1hxva_.ent", "d1grj_2.ent-d1itxa2.ent", "d1grj_2.ent-d1j6ya_.ent", "d1grj_2.ent-d1jnda2.ent", "d1grj_2.ent-d1jvwa_.ent", "d1grj_2.ent-d1kt1a3.ent", "d1grj_2.ent-d1lg2a2.ent", "d1grj_2.ent-d1ll7a2.ent", "d1grj_2.ent-d1m5ya2.ent", "d1grj_2.ent-d1m5ya3.ent", "d1grj_2.ent-d1n1aa_.ent", "d1grj_2.ent-d1pbk__.ent", "d1grj_2.ent-d1pina2.ent", "d1grj_2.ent-d3eipa_.ent", "d1grwa_.ent-d1j0ha1.ent", "d1grwa_.ent-d1l4ia1.ent", "d1grwa_.ent-d1qpxa1.ent", "d1grwa_.ent-d1soxa1.ent", "d1gsa_1.ent-d1gsoa2.ent", "d1gsa_1.ent-d1iow_1.ent", "d1gsa_1.ent-d1kjqa2.ent", "d1gsa_1.ent-d1m0wa1.ent", "d1gsa_1.ent-d2hgsa1.ent", "d1gsa_2.ent-d1gsoa3.ent", "d1gsa_2.ent-d1iow_2.ent", "d1gsa_2.ent-d1jkjb2.ent", "d1gsa_2.ent-d1kbla3.ent", "d1gsa_2.ent-d1kjqa3.ent", "d1gsa_2.ent-d1m0wa2.ent", "d1gsa_2.ent-d2hgsa4.ent", "d1gsma2.ent-d1akjd_.ent", "d1gsma2.ent-d1b88a_.ent", "d1gsma2.ent-d1bec_1.ent", "d1gsma2.ent-d1c5ch1.ent", "d1gsma2.ent-d1dlfl_.ent", "d1gsma2.ent-d1fo0a_.ent", "d1gsma2.ent-d1h5ba_.ent", "d1gsma2.ent-d1neu__.ent", "d1gsma2.ent-d1nfdb1.ent", "d1gsma2.ent-d1qfoa_.ent", "d1gsma2.ent-d1tvda_.ent", "d1gsma2.ent-d2rhe__.ent", "d1gsoa1.ent-d1hcz_2.ent", "d1gsoa1.ent-d1htp__.ent", "d1gsoa1.ent-d1k8ma_.ent", "d1gsoa1.ent-d1kjqa1.ent", "d1gsoa2.ent-d1iow_1.ent", "d1gsoa2.ent-d1kjqa2.ent", "d1gsoa2.ent-d1m0wa1.ent", "d1gsoa2.ent-d2hgsa1.ent", "d1gsoa3.ent-d1iow_2.ent", "d1gsoa3.ent-d1jkjb2.ent", "d1gsoa3.ent-d1kbla3.ent", "d1gsoa3.ent-d1kjqa3.ent", "d1gsoa3.ent-d1m0wa2.ent", "d1gsoa3.ent-d2hgsa4.ent", "d1gt7a_.ent-d1k0wa_.ent", "d1gt91_.ent-d1ic6a_.ent", "d1gt91_.ent-d1thm__.ent", "d1gtea1.ent-d1gvha1", "d1gtea1.ent-d1gvha1.ent", "d1gtea1.ent-d1h97a_", "d1gtea1.ent-d1h97a_.ent", "d1gtea1.ent-d1irdb_", "d1gtea1.ent-d1irdb_.ent", "d1gtea1.ent-d1itha_", "d1gtea1.ent-d1itha_.ent", "d1gtea1.ent-d1kf6b1.ent", "d1gtea1.ent-d1nekb1.ent", "d1gtea1.ent-d1qlab1", "d1gtea1.ent-d1qlab1.ent", "d1gtea1.ent-d2gdm__", "d1gtea1.ent-d2gdm__.ent", "d1gtea2.ent-d1gvoa_.ent", "d1gtea2.ent-d1huva_.ent", "d1gtea2.ent-d1icpa_.ent", "d1gtea2.ent-d1kbia1.ent", "d1gtea2.ent-d1llwa2.ent", "d1gtea2.ent-d1o94a1.ent", "d1gtea2.ent-d1oyb__.ent", "d1gtea2.ent-d2dora_.ent", "d1gtea3.ent-d1jnra2.ent", "d1gtea3.ent-d1ju2a1.ent", "d1gtea3.ent-d1k0ia1.ent", "d1gtea3.ent-d1kssa2.ent", "d1gtea3.ent-d1l9ea1.ent", "d1gtea3.ent-d1lqta1.ent", "d1gtea3.ent-d1m6ia1.ent", "d1gtea3.ent-d1m6ia2.ent", "d1gtea3.ent-d1nhp_1.ent", "d1gtea3.ent-d1nhp_2.ent", "d1gtea3.ent-d1o94a2.ent", "d1gtea3.ent-d3grs_1.ent", "d1gtea3.ent-d3grs_2.ent", "d1gtea4.ent-d1i8ta1.ent", "d1gtea4.ent-d1lqta2.ent", "d1gtea4.ent-d1o94a3.ent", "d1gtea5.ent-d1h0hb_.ent", "d1gtea5.ent-d1h98a_.ent", "d1gtea5.ent-d1hfel2.ent", "d1gtea5.ent-d1iqza_.ent", "d1gtea5.ent-d1jb0c_.ent", "d1gtea5.ent-d1jnrb_.ent", "d1gtea5.ent-d1keka5.ent", "d1gtea5.ent-d1kqfb1.ent", "d1gtea5.ent-d2fdn__.ent", "d1gtea5.ent-d7fd1a_.ent", "d1gtma2.ent-d1hwxa2.ent", "d1gtma2.ent-d1leha2.ent", "d1gtma2.ent-d1lu9a2.ent", "d1gtra2.ent-d1h3fa1.ent", "d1gtra2.ent-d1h3na3.ent", "d1gtra2.ent-d1ihoa_.ent", "d1gtra2.ent-d1ile_3.ent", "d1gtra2.ent-d1iq0a2.ent", "d1gtra2.ent-d1irxa2.ent", "d1gtra2.ent-d1ivsa4.ent", "d1gtra2.ent-d1j09a2.ent", "d1gtra2.ent-d1jhda2.ent", "d1gtra2.ent-d1jila_.ent", "d1gtra2.ent-d1k4ma_.ent", "d1gtra2.ent-d1kama_.ent", "d1gtra2.ent-d1kqna_.ent", "d1gtra2.ent-d1li5a2.ent", "d1gtra2.ent-d1n3la_.ent", "d1gtra2.ent-d1qjca_.ent", "d1gtxa_.ent-d1ajsa_.ent", "d1gtxa_.ent-d1b9ha_.ent", "d1gtxa_.ent-d1bs0a_.ent", "d1gtxa_.ent-d1c7na_.ent", "d1gtxa_.ent-d1e5ea_.ent", "d1gtxa_.ent-d1gdea_.ent", "d1gtxa_.ent-d1j32a_.ent", "d1gtxa_.ent-d1jf9a_.ent", "d1gtxa_.ent-d1kl1a_.ent", "d1gtxa_.ent-d1m7ya_.ent", "d1gtxa_.ent-d1n8pa_.ent", "d1gtxa_.ent-d1qisa_.ent", "d1gtxa_.ent-d1qj5a_.ent", "d1gtxa_.ent-d1tpla_.ent", "d1gtxa_.ent-d1yaaa_.ent", "d1gtxa_.ent-d2ay1a_.ent", "d1gtxa_.ent-d2dkb__.ent", "d1gtxa_.ent-d2gsaa_.ent", "d1gtxa_.ent-d2oata_.ent", "d1gtxa_.ent-d3tata_.ent", "d1gtxa_.ent-d7aata_.ent", "d1gtza_.ent-d1h05a_.ent", "d1gu2a_.ent-d1co6a_.ent", "d1gu2a_.ent-d1cot__.ent", "d1gu2a_.ent-d1dw0a_.ent", "d1gu2a_.ent-d1etpa2.ent", "d1gu2a_.ent-d1h32a1.ent", "d1gu2a_.ent-d1hroa_.ent", "d1gu2a_.ent-d1iqca1.ent", "d1gu2a_.ent-d1iqca2.ent", "d1gu2a_.ent-d1jmxa1.ent", "d1gu2a_.ent-d1jmxa2.ent", "d1gu2a_.ent-d1kb0a1.ent", "d1gu2a_.ent-d1kv9a1.ent", "d1gu2a_.ent-d1mg2d_.ent", "d1gu2a_.ent-d1nira1.ent", "d1gu2a_.ent-d1qksa1.ent", "d1gu2a_.ent-d1ql3a_.ent", "d1gu2a_.ent-d1qn2a_.ent", "d1gu2a_.ent-d1ycc__.ent", "d1gu2a_.ent-d3c2c__.ent", "d1gu3a_.ent-d1gmma_.ent", "d1gu3a_.ent-d1guia_.ent", "d1gu3a_.ent-d1h6ya_.ent", "d1gu3a_.ent-d1i5pa1.ent", "d1gu3a_.ent-d1jhja_.ent", "d1gu3a_.ent-d1ju3a1.ent", "d1gu3a_.ent-d1jz8a3.ent", "d1gu3a_.ent-d1k12a_.ent", "d1gu3a_.ent-d1k3ia2.ent", "d1gu3a_.ent-d1kgya_.ent", "d1gu3a_.ent-d1l7la_.ent", "d1gu3a_.ent-d1lnsa2.ent", "d1gu3a_.ent-d1xnaa_.ent", "d1gu6a_.ent-d1gyoa_.ent", "d1gu6a_.ent-d1h21a_.ent", "d1gu6a_.ent-d1h29a_.ent", "d1gu6a_.ent-d1hh5a_.ent", "d1gu6a_.ent-d1kssa1.ent", "d1gu6a_.ent-d1m1qa_.ent", "d1gu6a_.ent-d1qo8a1.ent", "d1gu6a_.ent-d1wad__.ent", "d1gu6a_.ent-d2ctha_.ent", "d1gu6a_.ent-d2cy3__.ent", "d1gu6a_.ent-d3caoa_.ent", "d1gu6a_.ent-d3cyr__.ent", "d1guia_.ent-d1ciy_1.ent", "d1guia_.ent-d1cx1a_.ent", "d1guia_.ent-d1dlc_1.ent", "d1guia_.ent-d1eut_2.ent", "d1guia_.ent-d1gmma_.ent", "d1guia_.ent-d1gnya_.ent", "d1guia_.ent-d1gu3a_.ent", "d1guia_.ent-d1h6ya_.ent", "d1guia_.ent-d1i5pa1.ent", "d1guia_.ent-d1jhja_.ent", "d1guia_.ent-d1ji6a1.ent", "d1guia_.ent-d1ju3a1.ent", "d1guia_.ent-d1jz8a3.ent", "d1guia_.ent-d1k12a_.ent", "d1guia_.ent-d1k3ia2.ent", "d1guia_.ent-d1kexa_.ent", "d1guia_.ent-d1kgya_.ent", "d1guia_.ent-d1l7la_.ent", "d1guia_.ent-d1lnsa2.ent", "d1guia_.ent-d1xnaa_.ent", "d1gula1.ent-d1gwca1.ent", "d1gula1.ent-d1jlva1.ent", "d1gula1.ent-d1k0da1.ent", "d1gula1.ent-d1k0ma1.ent", "d1gula1.ent-d1k3ya1.ent", "d1gula1.ent-d1ljra1.ent", "d1gula1.ent-d1m0ua1.ent", "d1gula1.ent-d1pd211.ent", "d1gula1.ent-d1pmt_1.ent", "d1gula1.ent-d2gsq_1.ent", "d1gula1.ent-d2gsta1.ent", "d1guqa1.ent-d1guqa2.ent", "d1guqa1.ent-d1kpf__.ent", "d1guqa1.ent-d1l9va1.ent", "d1guqa2.ent-d1kpf__.ent", "d1guqa2.ent-d1l9va1.ent", "d1guta_.ent-d1h9ma1.ent", "d1guta_.ent-d1h9ma2.ent", "d1guta_.ent-d1h9ra1.ent", "d1guta_.ent-d1h9ra2.ent", "d1guxa_.ent-d1guxb_.ent", "d1guxa_.ent-d1h4ld_.ent", "d1guxa_.ent-d1jkw_1.ent", "d1guxa_.ent-d1jkw_2.ent", "d1guxa_.ent-d1vin_1.ent", "d1guxa_.ent-d1vin_2.ent", "d1guxa_.ent-d1vola1.ent", "d1guxb_.ent-d1h4ld_.ent", "d1guxb_.ent-d1jkw_1.ent", "d1guxb_.ent-d1jkw_2.ent", "d1guxb_.ent-d1vin_1.ent", "d1guxb_.ent-d1vin_2.ent", "d1guxb_.ent-d1vola1.ent", "d1guya2.ent-d1hyea2.ent", "d1guya2.ent-d1hyha2.ent", "d1guya2.ent-d1i0za2.ent", "d1guya2.ent-d1ldg_2.ent", "d1guya2.ent-d1ldna2.ent", "d1guya2.ent-d1llda2.ent", "d1guya2.ent-d1o6za2.ent", "d1guya2.ent-d2cmd_2.ent", "d1guya2.ent-d5mdha2.ent", "d1guya2.ent-d7mdha2.ent", "d1gv3a1.ent-d1isaa1.ent", "d1gv3a1.ent-d1ix9a1.ent", "d1gv3a2.ent-d1isaa2.ent", "d1gv3a2.ent-d1ix9a2.ent", "d1gv3a2.ent-d1kkca2.ent", "d1gv3a2.ent-d1ma1a2.ent", "d1gv3a2.ent-d1qnna2.ent", "d1gv9a_.ent-d1dhkb_.ent", "d1gv9a_.ent-d1dyka1.ent", "d1gv9a_.ent-d1dyka2.ent", "d1gv9a_.ent-d1epwa1.ent", "d1gv9a_.ent-d1h30a1.ent", "d1gv9a_.ent-d1h30a2.ent", "d1gv9a_.ent-d1ikpa1.ent", "d1gv9a_.ent-d1is3a_.ent", "d1gv9a_.ent-d1jhna4.ent", "d1gv9a_.ent-d1kit_1.ent", "d1gv9a_.ent-d1kit_2.ent", "d1gv9a_.ent-d1kqra_.ent", "d1gv9a_.ent-d1n1ta1.ent", "d1gv9a_.ent-d1nls__.ent", "d1gv9a_.ent-d1saca_.ent", "d1gv9a_.ent-d1xnb__.ent", "d1gv9a_.ent-d2ayh__.ent", "d1gv9a_.ent-d2nlra_.ent", "d1gv9a_.ent-d2sli_1.ent", "d1gv9a_.ent-d3btaa1.ent", "d1gvea_.ent-d1hqta_.ent", "d1gvea_.ent-d1hw6a_.ent", "d1gvea_.ent-d1j96a_.ent", "d1gvea_.ent-d1jeza_.ent", "d1gvfa_.ent-d1gzga_.ent", "d1gvfa_.ent-d1h7na_.ent", "d1gvfa_.ent-d1hfba_.ent", "d1gvfa_.ent-d1i2oa_.ent", "d1gvfa_.ent-d1jcla_.ent", "d1gvfa_.ent-d1jcxa_.ent", "d1gvfa_.ent-d1l6wa_.ent", "d1gvfa_.ent-d1mzha_.ent", "d1gvfa_.ent-d1nal1_.ent", "d1gvfa_.ent-d1o0ya_.ent", "d1gvfa_.ent-d1qfea_.ent", "d1gvha1.ent-d1cg5a_", "d1gvha1.ent-d1cg5a_.ent", "d1gvha1.ent-d1cg5b_", "d1gvha1.ent-d1cg5b_.ent", "d1gvha1.ent-d1ew6a_", "d1gvha1.ent-d1ew6a_.ent", "d1gvha1.ent-d1gcva_", "d1gvha1.ent-d1gcva_.ent", "d1gvha1.ent-d1h97a_", "d1gvha1.ent-d1h97a_.ent", "d1gvha1.ent-d1irda_", "d1gvha1.ent-d1irda_.ent", "d1gvha1.ent-d1irdb_", "d1gvha1.ent-d1irdb_.ent", "d1gvha1.ent-d1it2a_", "d1gvha1.ent-d1it2a_.ent", "d1gvha1.ent-d1itha_", "d1gvha1.ent-d1itha_.ent", "d1gvha1.ent-d1la6a_", "d1gvha1.ent-d1la6a_.ent", "d1gvha1.ent-d1mba__", "d1gvha1.ent-d1mba__.ent", "d1gvha1.ent-d1qlab1", "d1gvha1.ent-d1qlab1.ent", "d1gvha1.ent-d2gdm__", "d1gvha1.ent-d2gdm__.ent", "d1gvha1.ent-d3sdha_", "d1gvha1.ent-d3sdha_.ent", "d1gvha3.ent-d1i7pa2.ent", "d1gvha3.ent-d1ja1a3.ent", "d1gvha3.ent-d1jb9a2.ent", "d1gvha3.ent-d1krha2.ent", "d1gvha3.ent-d1qfja2.ent", "d1gvha3.ent-d1que_2.ent", "d1gvha3.ent-d2cnd_2.ent", "d1gvha3.ent-d2pia_2.ent", "d1gvkb_.ent-d1azza_.ent", "d1gvkb_.ent-d1bio__.ent", "d1gvkb_.ent-d1bqya_.ent", "d1gvkb_.ent-d1cgha_.ent", "d1gvkb_.ent-d1ekbb_.ent", "d1gvkb_.ent-d1elva1.ent", "d1gvkb_.ent-d1fjsa_.ent", "d1gvkb_.ent-d1gdna_.ent", "d1gvkb_.ent-d1gpza1.ent", "d1gvkb_.ent-d1gvza_.ent", "d1gvkb_.ent-d1hj9a_.ent", "d1gvkb_.ent-d1mzaa_.ent", "d1gvkb_.ent-d1rfna_.ent", "d1gvkb_.ent-d2hlca_.ent", "d1gvoa_.ent-d1d3ga_.ent", "d1gvoa_.ent-d1huva_.ent", "d1gvoa_.ent-d1icpa_.ent", "d1gvoa_.ent-d1kbia1.ent", "d1gvoa_.ent-d1llwa2.ent", "d1gvoa_.ent-d1m7ja3.ent", "d1gvoa_.ent-d1o94a1.ent", "d1gvoa_.ent-d1oyb__.ent", "d1gvoa_.ent-d2dora_.ent", "d1gvza_.ent-d1azza_.ent", "d1gvza_.ent-d1bio__.ent", "d1gvza_.ent-d1bqya_.ent", "d1gvza_.ent-d1cgha_.ent", "d1gvza_.ent-d1ekbb_.ent", "d1gvza_.ent-d1fjsa_.ent", "d1gvza_.ent-d1gdna_.ent", "d1gvza_.ent-d1gpza1.ent", "d1gvza_.ent-d1hj9a_.ent", "d1gvza_.ent-d1rfna_.ent", "d1gvza_.ent-d2hlca_.ent", "d1gw0a1.ent-d1cyx__.ent", "d1gw0a1.ent-d1e30a_.ent", "d1gw0a1.ent-d1ikop_.ent", "d1gw0a1.ent-d1kbva1.ent", "d1gw0a1.ent-d1kbva2.ent", "d1gw0a1.ent-d1kcw_2.ent", "d1gw0a1.ent-d1kcw_4.ent", "d1gw0a1.ent-d1kcw_6.ent", "d1gw0a1.ent-d1kv7a1.ent", "d1gw0a1.ent-d1kv7a3.ent", "d1gw0a1.ent-d1m56b1.ent", "d1gw0a1.ent-d1qhqa_.ent", "d1gw0a2.ent-d1cyx__.ent", "d1gw0a2.ent-d1e30a_.ent", "d1gw0a2.ent-d1gw0a1.ent", "d1gw0a2.ent-d1hfua2.ent", "d1gw0a2.ent-d1ikop_.ent", "d1gw0a2.ent-d1kbva1.ent", "d1gw0a2.ent-d1kbva2.ent", "d1gw0a2.ent-d1kcw_2.ent", "d1gw0a2.ent-d1kcw_4.ent", "d1gw0a2.ent-d1kcw_5.ent", "d1gw0a2.ent-d1kcw_6.ent", "d1gw0a2.ent-d1kv7a1.ent", "d1gw0a2.ent-d1kv7a2.ent", "d1gw0a2.ent-d1kv7a3.ent", "d1gw0a2.ent-d1l9qa1.ent", "d1gw0a2.ent-d1l9qa2.ent", "d1gw0a2.ent-d1m56b1.ent", "d1gw0a2.ent-d1qhqa_.ent", "d1gw0a3.ent-d1aoza2.ent", "d1gw0a3.ent-d1aoza3.ent", "d1gw0a3.ent-d1cyx__.ent", "d1gw0a3.ent-d1e30a_.ent", "d1gw0a3.ent-d1gw0a1.ent", "d1gw0a3.ent-d1gw0a2.ent", "d1gw0a3.ent-d1hfua2.ent", "d1gw0a3.ent-d1hfua3.ent", "d1gw0a3.ent-d1ikop_.ent", "d1gw0a3.ent-d1kbva1.ent", "d1gw0a3.ent-d1kbva2.ent", "d1gw0a3.ent-d1kcw_1.ent", "d1gw0a3.ent-d1kcw_2.ent", "d1gw0a3.ent-d1kcw_3.ent", "d1gw0a3.ent-d1kcw_4.ent", "d1gw0a3.ent-d1kcw_5.ent", "d1gw0a3.ent-d1kcw_6.ent", "d1gw0a3.ent-d1kv7a1.ent", "d1gw0a3.ent-d1kv7a2.ent", "d1gw0a3.ent-d1kv7a3.ent", "d1gw0a3.ent-d1l9qa1.ent", "d1gw0a3.ent-d1l9qa2.ent", "d1gw0a3.ent-d1m56b1.ent", "d1gw0a3.ent-d1qhqa_.ent", "d1gw1a_.ent-d1d3ga_.ent", "d1gw1a_.ent-d1gvoa_.ent", "d1gw1a_.ent-d1itua_.ent", "d1gw1a_.ent-d1k4ga_.ent", "d1gw1a_.ent-d1kbla1.ent", "d1gw1a_.ent-d1m7ja3.ent", "d1gw5m2.ent-d1gw5s_.ent", "d1gw5m2.ent-d1h3qa_.ent", "d1gw5m2.ent-d1h8ma_.ent", "d1gw5m2.ent-d1jnua_.ent", "d1gw5m2.ent-d1ll8a_.ent", "d1gw5m2.ent-d1mc0a1.ent", "d1gw5m2.ent-d1mkma2.ent", "d1gw5m2.ent-d1pne__.ent", "d1gw5m2.ent-d3pyp__.ent", "d1gw5s_.ent-d1h3qa_.ent", "d1gw5s_.ent-d1h8ma_.ent", "d1gwca1.ent-d1jlva1.ent", "d1gwca1.ent-d1k0da1.ent", "d1gwca1.ent-d1k0ma1.ent", "d1gwca1.ent-d1k3ya1.ent", "d1gwca1.ent-d1ljra1.ent", "d1gwca1.ent-d1m0ua1.ent", "d1gwca1.ent-d1pd211.ent", "d1gwca1.ent-d1pmt_1.ent", "d1gwca1.ent-d2gsq_1.ent", "d1gwca1.ent-d2gsta1.ent", "d1gwea_.ent-d1m7sa_.ent", "d1gx3a_.ent-d1iu4a_.ent", "d1gx3a_.ent-d1kxra_.ent", "d1gx3a_.ent-d1l9na4.ent", "d1gx3a_.ent-d1me4a_.ent", "d1gx3a_.ent-d1nbfa_.ent", "d1gx3a_.ent-d1ppn__.ent", "d1gx3a_.ent-d1qmya_.ent", "d1gx3a_.ent-d1uch__.ent", "d1gx3a_.ent-d2act__.ent", "d1gx3a_.ent-d2cb5a_.ent", "d1gx3a_.ent-d3gcb__.ent", "d1gx3a_.ent-d7pcka_.ent", "d1gxca_.ent-d1lgpa_.ent", "d1gxca_.ent-d1mjsa_.ent", "d1gxca_.ent-d1ygs__.ent", "d1gxma_.ent-d1h54a1.ent", "d1gxma_.ent-d1ks8a_.ent", "d1gxma_.ent-d1kwfa_.ent", "d1gxma_.ent-d1ld8b_.ent", "d1gxma_.ent-d1lf6a1.ent", "d1gxma_.ent-d1n1ba1.ent", "d1gxma_.ent-d1n7oa1.ent", "d1gxma_.ent-d1qaza_.ent", "d1gxma_.ent-d2sqca1.ent", "d1gxma_.ent-d2sqca2.ent", "d1gxqa_.ent-d1opc__.ent", "d1gxra_.ent-d1jmxb_.ent", "d1gxra_.ent-d1jtdb_.ent", "d1gxra_.ent-d1k32a3.ent", "d1gxra_.ent-d1k8kc_.ent", "d1gxra_.ent-d1m1xa4.ent", "d1gxra_.ent-d1tbga_.ent", "d1gxra_.ent-d2bbkh_.ent", "d1gxya_.ent-d1ikpa2.ent", "d1gxya_.ent-d1j7na3.ent", "d1gxya_.ent-d1prta_.ent", "d1gxya_.ent-d1qs1a1.ent", "d1gxya_.ent-d1qs1a2.ent", "d1gy6a_.ent-d1gy7a_.ent", "d1gy6a_.ent-d1jkga_.ent", "d1gy6a_.ent-d1jkgb_.ent", "d1gy6a_.ent-d1m98a2.ent", "d1gy6a_.ent-d1mwxa1.ent", "d1gy6a_.ent-d1o7nb_.ent", "d1gy6a_.ent-d1qjga_.ent", "d1gy6a_.ent-d3stda_.ent", "d1gy7a_.ent-d1ivwa2.ent", "d1gy7a_.ent-d1ivwa3.ent", "d1gy7a_.ent-d1jkga_.ent", "d1gy7a_.ent-d1jkgb_.ent", "d1gy7a_.ent-d1ksia2.ent", "d1gy7a_.ent-d1ksia3.ent", "d1gy7a_.ent-d1kwia_.ent", "d1gy7a_.ent-d1m98a2.ent", "d1gy7a_.ent-d1mola_.ent", "d1gy7a_.ent-d1mwxa1.ent", "d1gy7a_.ent-d1o7nb_.ent", "d1gy7a_.ent-d1oaca2.ent", "d1gy7a_.ent-d1qjga_.ent", "d1gy7a_.ent-d1stfi_.ent", "d1gy7a_.ent-d1ugia_.ent", "d1gy7a_.ent-d3stda_.ent", "d1gy9a_.ent-d1h2ka_.ent", "d1gy9a_.ent-d1hw5a2.ent", "d1gy9a_.ent-d1ig0a1.ent", "d1gy9a_.ent-d1jr7a_.ent", "d1gy9a_.ent-d1juha_.ent", "d1gy9a_.ent-d1lrha_.ent", "d1gy9a_.ent-d1m4oa_.ent", "d1gy9a_.ent-d1pmi__.ent", "d1gy9a_.ent-d1qjea_.ent", "d1gy9a_.ent-d1wapa_.ent", "d1gy9a_.ent-d2arca_.ent", "d1gyca3.ent-d1hfua2.ent", "d1gyca3.ent-d1ibya_.ent", "d1gyca3.ent-d1ikop_.ent", "d1gyca3.ent-d1jzga_.ent", "d1gyca3.ent-d1kcw_1.ent", "d1gyca3.ent-d1kcw_2.ent", "d1gyca3.ent-d1kv7a1.ent", "d1gyca3.ent-d1kv7a2.ent", "d1gyca3.ent-d1kv7a3.ent", "d1gyca3.ent-d1kzqa1.ent", "d1gyca3.ent-d1l9qa1.ent", "d1gyca3.ent-d1l9qa2.ent", "d1gyca3.ent-d2cbp__.ent", "d1gyca3.ent-d2cuaa_.ent", "d1gyoa_.ent-d1h21a_.ent", "d1gyoa_.ent-d1h29a_.ent", "d1gyoa_.ent-d1hh5a_.ent", "d1gyoa_.ent-d1kssa1.ent", "d1gyoa_.ent-d1m1qa_.ent", "d1gyoa_.ent-d1qo8a1.ent", "d1gyoa_.ent-d1wad__.ent", "d1gyoa_.ent-d2ctha_.ent", "d1gyoa_.ent-d2cy3__.ent", "d1gyoa_.ent-d3caoa_.ent", "d1gyoa_.ent-d3cyr__.ent", "d1gyta2.ent-d1h8la2.ent", "d1gyta2.ent-d1jqga1.ent", "d1gyta2.ent-d1kwma1.ent", "d1gyta2.ent-d1lam_2.ent", "d1gyta2.ent-d1lfwa1.ent", "d1gyta2.ent-d1loka_.ent", "d1gyta2.ent-d1m4la_.ent", "d1gyta2.ent-d1obr__.ent", "d1gyva_.ent-d1kyfa1.ent", "d1gyxa_.ent-d1hfoa_.ent", "d1gyxa_.ent-d1otfa_.ent", "d1gyxa_.ent-d1otga_.ent", "d1gzca_.ent-d1dhkb_.ent", "d1gzca_.ent-d1dyka1.ent", "d1gzca_.ent-d1dyka2.ent", "d1gzca_.ent-d1epwa1.ent", "d1gzca_.ent-d1gv9a_.ent", "d1gzca_.ent-d1h30a1.ent", "d1gzca_.ent-d1h30a2.ent", "d1gzca_.ent-d1jhna4.ent", "d1gzca_.ent-d1kit_1.ent", "d1gzca_.ent-d1kit_2.ent", "d1gzca_.ent-d1n1ta1.ent", "d1gzca_.ent-d1nls__.ent", "d1gzca_.ent-d1saca_.ent", "d1gzca_.ent-d1xnb__.ent", "d1gzca_.ent-d2ayh__.ent", "d1gzca_.ent-d2nlra_.ent", "d1gzca_.ent-d2pela_.ent", "d1gzca_.ent-d2sli_1.ent", "d1gzca_.ent-d3btaa1.ent", "d1gzga_.ent-d1h7na_.ent", "d1gzga_.ent-d1hfba_.ent", "d1gzga_.ent-d1i2oa_.ent", "d1gzga_.ent-d1jcla_.ent", "d1gzga_.ent-d1jcxa_.ent", "d1gzga_.ent-d1l6wa_.ent", "d1gzga_.ent-d1mzha_.ent", "d1gzga_.ent-d1nal1_.ent", "d1gzga_.ent-d1o0ya_.ent", "d1gzga_.ent-d1qfea_.ent", "d1gzhb1.ent-d1in1a_.ent", "d1gzhb1.ent-d1l0ba1.ent", "d1gzhb1.ent-d1l0ba2.ent", "d1gzqa2.ent-d1hdma2.ent", "d1gzqa2.ent-d1hdmb2.ent", "d1gzqa2.ent-d1hyrc2.ent", "d1gzqa2.ent-d1iaka2.ent", "d1gzqa2.ent-d1jfma_.ent", "d1gzqa2.ent-d1k5na2.ent", "d1gzqa2.ent-d1kcgc_.ent", "d1gzqa2.ent-d1lqva_.ent", "d1gzqa2.ent-d1zaga2.ent", "d1gzqa2.ent-d3frua2.ent", "d1h0ha1.ent-d1kqfa1.ent", "d1h0ha1.ent-d1n10a2.ent", "d1h0ha1.ent-d1tmo_1.ent", "d1h0ha1.ent-d2napa1.ent", "d1h0hb_.ent-d1azsa_.ent", "d1h0hb_.ent-d1b3ta_.ent", "d1h0hb_.ent-d1dj0a2.ent", "d1h0hb_.ent-d1dqaa1.ent", "d1h0hb_.ent-d1ekra_.ent", "d1h0hb_.ent-d1eqoa_.ent", "d1h0hb_.ent-d1f3va_.ent", "d1h0hb_.ent-d1ftra1.ent", "d1h0hb_.ent-d1ftra2.ent", "d1h0hb_.ent-d1gpja3.ent", "d1h0hb_.ent-d1h72c2.ent", "d1h0hb_.ent-d1h98a_.ent", "d1h0hb_.ent-d1hbnb2.ent", "d1h0hb_.ent-d1hfel2.ent", "d1h0hb_.ent-d1hlwa_.ent", "d1h0hb_.ent-d1iqza_.ent", "d1h0hb_.ent-d1jb0c_.ent", "d1h0hb_.ent-d1jnrb_.ent", "d1h0hb_.ent-d1keka5.ent", "d1h0hb_.ent-d1kqfb1.ent", "d1h0hb_.ent-d1kvka2.ent", "d1h0hb_.ent-d1lfwa2.ent", "d1h0hb_.ent-d1qd1a1.ent", "d1h0hb_.ent-d1qd1a2.ent", "d1h0hb_.ent-d1regx_.ent", "d1h0hb_.ent-d2fdn__.ent", "d1h0hb_.ent-d7fd1a_.ent", "d1h0oa_.ent-d1jgca_.ent", "d1h0oa_.ent-d1ji4a_.ent", "d1h0oa_.ent-d1jiga_.ent", "d1h0oa_.ent-d1jk0b_.ent", "d1h0oa_.ent-d1jkva_.ent", "d1h0oa_.ent-d1jqca_.ent", "d1h0oa_.ent-d1kgna_.ent", "d1h0oa_.ent-d1lkoa1.ent", "d1h0oa_.ent-d1mtyb_.ent", "d1h0oa_.ent-d1mtyd_.ent", "d1h0oa_.ent-d1qgha_.ent", "d1h0oa_.ent-d1rcd__.ent", "d1h0xa_.ent-d1hc7a3.ent", "d1h0xa_.ent-d1jo0a_.ent", "d1h0xa_.ent-d1msza_.ent", "d1h0xa_.ent-d1qmha2.ent", "d1h0xa_.ent-d1tig__.ent", "d1h16a_.ent-d1h78a_.ent", "d1h16a_.ent-d1l1la_.ent", "d1h16a_.ent-d1rlr_2.ent", "d1h1js_.ent-d1h9ea_.ent", "d1h1js_.ent-d1h9fa_.ent", "d1h1js_.ent-d1jeqa1.ent", "d1h1js_.ent-d1kcfa1.ent", "d1h21a_.ent-d1h29a_.ent", "d1h21a_.ent-d1hh5a_.ent", "d1h21a_.ent-d1kssa1.ent", "d1h21a_.ent-d1m1qa_.ent", "d1h21a_.ent-d1qo8a1.ent", "d1h21a_.ent-d1wad__.ent", "d1h21a_.ent-d2ctha_.ent", "d1h21a_.ent-d2cy3__.ent", "d1h21a_.ent-d3caoa_.ent", "d1h21a_.ent-d3cyr__.ent", "d1h29a_.ent-d1hh5a_.ent", "d1h29a_.ent-d1kssa1.ent", "d1h29a_.ent-d1m1qa_.ent", "d1h29a_.ent-d1qo8a1.ent", "d1h29a_.ent-d1wad__.ent", "d1h29a_.ent-d2ctha_.ent", "d1h29a_.ent-d2cy3__.ent", "d1h29a_.ent-d3caoa_.ent", "d1h29a_.ent-d3cyr__.ent", "d1h2ea_.ent-d1ihp__.ent", "d1h2ea_.ent-d1nd6a_.ent", "d1h2ea_.ent-d1qfxa_.ent", "d1h2ea_.ent-d3pgm__.ent", "d1h2ka_.ent-d1hw5a2.ent", "d1h2ka_.ent-d1ig0a1.ent", "d1h2ka_.ent-d1jr7a_.ent", "d1h2ka_.ent-d1juha_.ent", "d1h2ka_.ent-d1lrha_.ent", "d1h2ka_.ent-d1m4oa_.ent", "d1h2ka_.ent-d1pmi__.ent", "d1h2ka_.ent-d1qjea_.ent", "d1h2ka_.ent-d1wapa_.ent", "d1h2ka_.ent-d2arca_.ent", "d1h2sa_.ent-d1h2sb_.ent", "d1h2sa_.ent-d1l9ha_.ent", "d1h2sa_.ent-d1m0ka_.ent", "d1h2sb_.ent-d1l9ha_.ent", "d1h2sb_.ent-d1m0ka_.ent", "d1h30a1.ent-d1dyka2.ent", "d1h30a1.ent-d1xnb__.ent", "d1h30a2.ent-d1dhkb_.ent", "d1h30a2.ent-d1dyka1.ent", "d1h30a2.ent-d1dyka2.ent", "d1h30a2.ent-d1h30a1.ent", "d1h30a2.ent-d1ikpa1.ent", "d1h30a2.ent-d1is3a_.ent", "d1h30a2.ent-d1jhna4.ent", "d1h30a2.ent-d1kit_1.ent", "d1h30a2.ent-d1kit_2.ent", "d1h30a2.ent-d1kqra_.ent", "d1h30a2.ent-d1n1ta1.ent", "d1h30a2.ent-d1nls__.ent", "d1h30a2.ent-d1saca_.ent", "d1h30a2.ent-d1xnb__.ent", "d1h30a2.ent-d2nlra_.ent", "d1h30a2.ent-d2sli_1.ent", "d1h32a1.ent-d1c52__.ent", "d1h32a1.ent-d1co6a_.ent", "d1h32a1.ent-d1cot__.ent", "d1h32a1.ent-d1cxc__.ent", "d1h32a1.ent-d1dw0a_.ent", "d1h32a1.ent-d1e29a_.ent", "d1h32a1.ent-d1etpa2.ent", "d1h32a1.ent-d1f1ca_.ent", "d1h32a1.ent-d1gu2a_.ent", "d1h32a1.ent-d1hroa_.ent", "d1h32a1.ent-d1iqca1.ent", "d1h32a1.ent-d1iqca2.ent", "d1h32a1.ent-d1jmxa1.ent", "d1h32a1.ent-d1jmxa2.ent", "d1h32a1.ent-d1kb0a1.ent", "d1h32a1.ent-d1kv9a1.ent", "d1h32a1.ent-d1mg2d_.ent", "d1h32a1.ent-d1nira1.ent", "d1h32a1.ent-d1qksa1.ent", "d1h32a1.ent-d1ql3a_.ent", "d1h32a1.ent-d1qn2a_.ent", "d1h32a1.ent-d1ycc__.ent", "d1h32a1.ent-d3c2c__.ent", "d1h3fa1.ent-d1h3na3.ent", "d1h3fa1.ent-d1ihoa_.ent", "d1h3fa1.ent-d1ile_3.ent", "d1h3fa1.ent-d1iq0a2.ent", "d1h3fa1.ent-d1irxa2.ent", "d1h3fa1.ent-d1ivsa4.ent", "d1h3fa1.ent-d1j09a2.ent", "d1h3fa1.ent-d1jhda2.ent", "d1h3fa1.ent-d1jila_.ent", "d1h3fa1.ent-d1k4ma_.ent", "d1h3fa1.ent-d1kama_.ent", "d1h3fa1.ent-d1kqna_.ent", "d1h3fa1.ent-d1li5a2.ent", "d1h3fa1.ent-d1n3la_.ent", "d1h3fa1.ent-d1qjca_.ent", "d1h3fa2.ent-d1jh3a_.ent", "d1h3ia2.ent-d1hg7a_.ent", "d1h3ia2.ent-d1mlva2.ent", "d1h3ia2.ent-d1mvha_.ent", "d1h3ia2.ent-d1n3ja_.ent", "d1h3ia2.ent-d1tul__.ent", "d1h3ia2.ent-d4ubpb_.ent", "d1h3la_.ent-d1iw7f_.ent", "d1h3la_.ent-d1ku3a_.ent", "d1h3la_.ent-d1l0oc_.ent", "d1h3la_.ent-d1sig__.ent", "d1h3na2.ent-d1ile_2.ent", "d1h3na2.ent-d1ivsa3.ent", "d1h3na3.ent-d1ihoa_.ent", "d1h3na3.ent-d1ile_3.ent", "d1h3na3.ent-d1iq0a2.ent", "d1h3na3.ent-d1irxa2.ent", "d1h3na3.ent-d1ivsa4.ent", "d1h3na3.ent-d1j09a2.ent", "d1h3na3.ent-d1jhda2.ent", "d1h3na3.ent-d1jila_.ent", "d1h3na3.ent-d1k4ma_.ent", "d1h3na3.ent-d1kama_.ent", "d1h3na3.ent-d1kqna_.ent", "d1h3na3.ent-d1li5a2.ent", "d1h3na3.ent-d1n3la_.ent", "d1h3na3.ent-d1qjca_.ent", "d1h3qa_.ent-d1h8ma_.ent", "d1h3qa_.ent-d1jnua_.ent", "d1h3qa_.ent-d1ll8a_.ent", "d1h3qa_.ent-d1mc0a1.ent", "d1h3qa_.ent-d1mkma2.ent", "d1h3qa_.ent-d1pne__.ent", "d1h3qa_.ent-d3pyp__.ent", "d1h4ld_.ent-d1jkw_1.ent", "d1h4ld_.ent-d1jkw_2.ent", "d1h4ld_.ent-d1vin_1.ent", "d1h4ld_.ent-d1vin_2.ent", "d1h4ld_.ent-d1vola1.ent", "d1h4ra1.ent-d1mixa1.ent", "d1h4ra2.ent-d1k5db_.ent", "d1h4ra2.ent-d1ki1b2.ent", "d1h4ra2.ent-d1mai__.ent", "d1h4ra2.ent-d1mixa2.ent", "d1h4ra2.ent-d1mkea1.ent", "d1h4ra2.ent-d1pls__.ent", "d1h4ra2.ent-d1qqga1.ent", "d1h4ra2.ent-d1qqga2.ent", "d1h4ra2.ent-d1shca_.ent", "d1h4ra3.ent-d1fm0d_.ent", "d1h4ra3.ent-d1h8ca_.ent", "d1h4ra3.ent-d1i42a_.ent", "d1h4ra3.ent-d1j8ca_.ent", "d1h4ra3.ent-d1k8rb_.ent", "d1h4ra3.ent-d1l7ya_.ent", "d1h4ra3.ent-d1lfda_.ent", "d1h4ra3.ent-d1lm8b_.ent", "d1h4ra3.ent-d1m94a_.ent", "d1h4ra3.ent-d1rlf__.ent", "d1h4vb1.ent-d1hc7a1.ent", "d1h4vb1.ent-d1kmma1.ent", "d1h4vb1.ent-d1nbwb_.ent", "d1h4vb1.ent-d1qe0a1.ent", "d1h4vb1.ent-d1qf6a1.ent", "d1h4vb2.ent-d1hc7a2.ent", "d1h4vb2.ent-d1jjca_.ent", "d1h4vb2.ent-d1jjcb5.ent", "d1h4vb2.ent-d1kmma2.ent", "d1h4vb2.ent-d1qe0a2.ent", "d1h4vb2.ent-d1qf6a4.ent", "d1h4vb2.ent-d1seta2.ent", "d1h54a1.ent-d1ia6a_.ent", "d1h54a1.ent-d1ks8a_.ent", "d1h54a1.ent-d1kwfa_.ent", "d1h54a1.ent-d1ld8b_.ent", "d1h54a1.ent-d1lf6a1.ent", "d1h54a1.ent-d1n1ba1.ent", "d1h54a1.ent-d1n7oa1.ent", "d1h54a1.ent-d1qaza_.ent", "d1h54a1.ent-d2sqca1.ent", "d1h54a1.ent-d2sqca2.ent", "d1h54a2.ent-d1jz8a4.ent", "d1h54a2.ent-d1lf6a2.ent", "d1h54a2.ent-d1n7oa3.ent", "d1h54a2.ent-d1nsza_.ent", "d1h59b_.ent-d1b9wa2.ent", "d1h59b_.ent-d1cixa_.ent", "d1h59b_.ent-d1i2ua_.ent", "d1h59b_.ent-d1igra3.ent", "d1h59b_.ent-d1imt_2.ent", "d1h59b_.ent-d1ivoa3.ent", "d1h59b_.ent-d1ivoa4.ent", "d1h59b_.ent-d1m6ba3.ent", "d1h59b_.ent-d1m6ba4.ent", "d1h59b_.ent-d1n8yc3.ent", "d1h59b_.ent-d1n8yc4.ent", "d1h5ba_.ent-d1c5ch1.ent", "d1h5ba_.ent-d1nfdb1.ent", "d1h5qa_.ent-d1bgva1.ent", "d1h5qa_.ent-d1ja9a_.ent", "d1h5qa_.ent-d1oaa__.ent", "d1h5qa_.ent-d1qsga_.ent", "d1h5qa_.ent-d2ae2a_.ent", "d1h641_.ent-d1i8fa_.ent", "d1h641_.ent-d1kq1a_.ent", "d1h641_.ent-d1ljoa_.ent", "d1h641_.ent-d1mgqa_.ent", "d1h641_.ent-d1mxma1.ent", "d1h641_.ent-d1n9ra_.ent", "d1h67a_.ent-d1lnsa1.ent", "d1h6da2.ent-d1j5pa3.ent", "d1h6da2.ent-d1jkia2.ent", "d1h6da2.ent-d1jn0a2.ent", "d1h6da2.ent-d1lc0a2.ent", "d1h6da2.ent-d1mb4a2.ent", "d1h6da2.ent-d1qkia2.ent", "d1h6fa_.ent-d1i31a_.ent", "d1h6fa_.ent-d1ikna2.ent", "d1h6fa_.ent-d1imhc2.ent", "d1h6fa_.ent-d1klfb1.ent", "d1h6fa_.ent-d1klfb2.ent", "d1h6fa_.ent-d1m2oa2.ent", "d1h6fa_.ent-d1m2vb2.ent", "d1h6fa_.ent-d1mnna_.ent", "d1h6fa_.ent-d1nbca_.ent", "d1h6fa_.ent-d1pdkb_.ent", "d1h6fa_.ent-d1qba_2.ent", "d1h6fa_.ent-d1tf4a2.ent", "d1h6fa_.ent-d1ycsa_.ent", "d1h6ka1.ent-d1e8xa1.ent", "d1h6ka1.ent-d1elka_.ent", "d1h6ka1.ent-d1h6ka2.ent", "d1h6ka1.ent-d1h6ka3.ent", "d1h6ka1.ent-d1hf8a_.ent", "d1h6ka1.ent-d1hh8a_.ent", "d1h6ka1.ent-d1ho8a_.ent", "d1h6ka1.ent-d1hs6a1.ent", "d1h6ka1.ent-d1iala_.ent", "d1h6ka1.ent-d1ihga1.ent", "d1h6ka1.ent-d1jdha_.ent", "d1h6ka1.ent-d1keya_.ent", "d1h6ka1.ent-d1kpsb_.ent", "d1h6ka1.ent-d1kx9a_.ent", "d1h6ka1.ent-d1l5ja1.ent", "d1h6ka1.ent-d1lrv__.ent", "d1h6ka1.ent-d1n4ka1.ent", "d1h6ka1.ent-d1pbv__.ent", "d1h6ka1.ent-d1qjba_.ent", "d1h6ka2.ent-d1e8xa1.ent", "d1h6ka2.ent-d1elka_.ent", "d1h6ka2.ent-d1h6ka3.ent", "d1h6ka2.ent-d1ho8a_.ent", "d1h6ka2.ent-d1hs6a1.ent", "d1h6ka2.ent-d1iala_.ent", "d1h6ka2.ent-d1ihga1.ent", "d1h6ka2.ent-d1jdha_.ent", "d1h6ka2.ent-d1kpsb_.ent", "d1h6ka2.ent-d1kx9a_.ent", "d1h6ka2.ent-d1l5ja1.ent", "d1h6ka2.ent-d1lrv__.ent", "d1h6ka2.ent-d1n4ka1.ent", "d1h6ka3.ent-d1e8xa1.ent", "d1h6ka3.ent-d1elka_.ent", "d1h6ka3.ent-d1h6ka1.ent", "d1h6ka3.ent-d1h6ka2.ent", "d1h6ka3.ent-d1hf8a_.ent", "d1h6ka3.ent-d1hh8a_.ent", "d1h6ka3.ent-d1ho8a_.ent", "d1h6ka3.ent-d1hs6a1.ent", "d1h6ka3.ent-d1iala_.ent", "d1h6ka3.ent-d1ihga1.ent", "d1h6ka3.ent-d1jdha_.ent", "d1h6ka3.ent-d1keya_.ent", "d1h6ka3.ent-d1kpsb_.ent", "d1h6ka3.ent-d1kx9a_.ent", "d1h6ka3.ent-d1l5ja1.ent", "d1h6ka3.ent-d1lrv__.ent", "d1h6ka3.ent-d1n4ka1.ent", "d1h6ka3.ent-d1pbv__.ent", "d1h6ka3.ent-d1qjba_.ent", "d1h6kx_.ent-d1hd1a_.ent", "d1h6kx_.ent-d1iqta_.ent", "d1h6kx_.ent-d1jmta_.ent", "d1h6kx_.ent-d1koha2.ent", "d1h6kx_.ent-d1l3ka1.ent", "d1h6kx_.ent-d1l3ka2.ent", "d1h6kx_.ent-d1nu4a_.ent", "d1h6kx_.ent-d1qm9a1.ent", "d1h6kx_.ent-d1qm9a2.ent", "d1h6kx_.ent-d1u2fa_.ent", "d1h6kx_.ent-d2msta_.ent", "d1h6kx_.ent-d2u1a__.ent", "d1h6kx_.ent-d2u2fa_.ent", "d1h6la_.ent-d1ijqa1.ent", "d1h6la_.ent-d1k32a2.ent", "d1h6la_.ent-d1kit_3.ent", "d1h6la_.ent-d3sil__.ent", "d1h6ta2.ent-d1h6ua2.ent", "d1h6ta2.ent-d1igra1.ent", "d1h6ta2.ent-d1igra2.ent", "d1h6ta2.ent-d1ivoa1.ent", "d1h6ta2.ent-d1ivoa2.ent", "d1h6ta2.ent-d1jl5a_.ent", "d1h6ta2.ent-d1koha1.ent", "d1h6ta2.ent-d1m0za_.ent", "d1h6ta2.ent-d1m6ba1.ent", "d1h6ta2.ent-d1m6ba2.ent", "d1h6ta2.ent-d1n8yc1.ent", "d1h6ta2.ent-d1n8yc2.ent", "d1h6ua2.ent-d1igra1.ent", "d1h6ua2.ent-d1igra2.ent", "d1h6ua2.ent-d1ivoa1.ent", "d1h6ua2.ent-d1ivoa2.ent", "d1h6ua2.ent-d1jl5a_.ent", "d1h6ua2.ent-d1koha1.ent", "d1h6ua2.ent-d1m0za_.ent", "d1h6ua2.ent-d1m6ba1.ent", "d1h6ua2.ent-d1m6ba2.ent", "d1h6ua2.ent-d1n8yc1.ent", "d1h6ua2.ent-d1n8yc2.ent", "d1h6va1.ent-d1cjca1.ent", "d1h6va1.ent-d1ebda1.ent", "d1h6va1.ent-d1jeha1.ent", "d1h6va1.ent-d1ojt_1.ent", "d1h6va1.ent-d3lada1.ent", "d1h6va3.ent-d1lvl_3.ent", "d1h6va3.ent-d1m6ia3.ent", "d1h6va3.ent-d1mo9a3.ent", "d1h6va3.ent-d1nhp_3.ent", "d1h6va3.ent-d1ojt_3.ent", "d1h6va3.ent-d3grs_3.ent", "d1h6va3.ent-d3lada3.ent", "d1h6ya_.ent-d1ciy_1.ent", "d1h6ya_.ent-d1cx1a_.ent", "d1h6ya_.ent-d1dlc_1.ent", "d1h6ya_.ent-d1eut_2.ent", "d1h6ya_.ent-d1gmma_.ent", "d1h6ya_.ent-d1gnya_.ent", "d1h6ya_.ent-d1gu3a_.ent", "d1h6ya_.ent-d1guia_.ent", "d1h6ya_.ent-d1i5pa1.ent", "d1h6ya_.ent-d1jhja_.ent", "d1h6ya_.ent-d1ji6a1.ent", "d1h6ya_.ent-d1ju3a1.ent", "d1h6ya_.ent-d1jz8a3.ent", "d1h6ya_.ent-d1k12a_.ent", "d1h6ya_.ent-d1k3ia2.ent", "d1h6ya_.ent-d1kexa_.ent", "d1h6ya_.ent-d1kgya_.ent", "d1h6ya_.ent-d1l7la_.ent", "d1h6ya_.ent-d1lnsa2.ent", "d1h6ya_.ent-d1xnaa_.ent", "d1h70a_.ent-d1jdw__.ent", "d1h72c1.ent-d1kija1.ent", "d1h72c1.ent-d1kkha1.ent", "d1h72c1.ent-d1kvka1.ent", "d1h72c1.ent-d1mu5a2.ent", "d1h72c1.ent-d1n0ua3.ent", "d1h72c1.ent-d1pkp_1.ent", "d1h72c2.ent-d1dqaa1.ent", "d1h72c2.ent-d1kkha2.ent", "d1h72c2.ent-d1kvka2.ent", "d1h72c2.ent-d1regx_.ent", "d1h76a2.ent-d1i6aa_.ent", "d1h76a2.ent-d1ii5a_.ent", "d1h76a2.ent-d1ixh__.ent", "d1h76a2.ent-d1jeta_.ent", "d1h76a2.ent-d1kwha_.ent", "d1h76a2.ent-d1lst__.ent", "d1h76a2.ent-d1m5ea_.ent", "d1h76a2.ent-d1mrp__.ent", "d1h76a2.ent-d1nh8a1.ent", "d1h76a2.ent-d1pda_1.ent", "d1h76a2.ent-d1pot__.ent", "d1h76a2.ent-d1sbp__.ent", "d1h76a2.ent-d1wdna_.ent", "d1h76a2.ent-d3mbp__.ent", "d1h76a2.ent-d3thia_.ent", "d1h78a_.ent-d1l1la_.ent", "d1h78a_.ent-d1rlr_2.ent", "d1h7ea_.ent-d1hm9a2.ent", "d1h7ea_.ent-d1hv9a2.ent", "d1h7ea_.ent-d1i52a_.ent", "d1h7ea_.ent-d1jv1a_.ent", "d1h7ea_.ent-d1k4va_.ent", "d1h7ea_.ent-d1kwsa_.ent", "d1h7ea_.ent-d1ll2a_.ent", "d1h7ea_.ent-d1lzja_.ent", "d1h7ea_.ent-d1nf5b_.ent", "d1h7ea_.ent-d1qg8a_.ent", "d1h7na_.ent-d1hfba_.ent", "d1h7na_.ent-d1i2oa_.ent", "d1h7na_.ent-d1jcla_.ent", "d1h7na_.ent-d1jcxa_.ent", "d1h7na_.ent-d1l6wa_.ent", "d1h7na_.ent-d1mzha_.ent", "d1h7na_.ent-d1nal1_.ent", "d1h7na_.ent-d1o0ya_.ent", "d1h7na_.ent-d1qfea_.ent", "d1h7va_.ent-d1lkoa2.ent", "d1h7va_.ent-d1ocrf_.ent", "d1h7va_.ent-d1rb9__.ent", "d1h7za_.ent-d1kaca_.ent", "d1h7za_.ent-d1kkea1.ent", "d1h7za_.ent-d1qhva_.ent", "d1h8ba_.ent-d1iioa_.ent", "d1h8ba_.ent-d1j7qa_.ent", "d1h8ba_.ent-d1k94a_.ent", "d1h8ba_.ent-d1m45a_.ent", "d1h8ba_.ent-d1psra_.ent", "d1h8ba_.ent-d1qasa1.ent", "d1h8ba_.ent-d1rec__.ent", "d1h8ba_.ent-d1sra__.ent", "d1h8ba_.ent-d2cbla1.ent", "d1h8ba_.ent-d2pvba_.ent", "d1h8ba_.ent-d2sas__.ent", "d1h8ba_.ent-d2scpa_.ent", "d1h8ca_.ent-d1fm0d_.ent", "d1h8ca_.ent-d1i42a_.ent", "d1h8ca_.ent-d1j8ca_.ent", "d1h8ca_.ent-d1k8rb_.ent", "d1h8ca_.ent-d1l7ya_.ent", "d1h8ca_.ent-d1lfda_.ent", "d1h8ca_.ent-d1lm8b_.ent", "d1h8ca_.ent-d1m94a_.ent", "d1h8ca_.ent-d1rlf__.ent", "d1h8la1.ent-d1lm8v_.ent", "d1h8la1.ent-d1qhoa2.ent", "d1h8la2.ent-d1jqga1.ent", "d1h8la2.ent-d1kwma1.ent", "d1h8la2.ent-d1lam_2.ent", "d1h8la2.ent-d1lfwa1.ent", "d1h8la2.ent-d1loka_.ent", "d1h8la2.ent-d1m4la_.ent", "d1h8la2.ent-d1obr__.ent", "d1h8ma_.ent-d1jnua_.ent", "d1h8ma_.ent-d1ll8a_.ent", "d1h8ma_.ent-d1mc0a1.ent", "d1h8ma_.ent-d1mkma2.ent", "d1h8ma_.ent-d1pne__.ent", "d1h8ma_.ent-d3pyp__.ent", "d1h8pa1.ent-d1h8pa2.ent", "d1h8pa1.ent-d1i71a_.ent", "d1h8pa1.ent-d1kdu__.ent", "d1h8pa1.ent-d1ki0a2.ent", "d1h8pa1.ent-d1ki0a3.ent", "d1h8pa1.ent-d1l6ja3.ent", "d1h8pa1.ent-d1l6ja4.ent", "d1h8pa1.ent-d1l6ja5.ent", "d1h8pa1.ent-d1pmla_.ent", "d1h8pa1.ent-d2hpqp_.ent", "d1h8pa1.ent-d5hpga_.ent", "d1h8pa2.ent-d1i71a_.ent", "d1h8pa2.ent-d1kdu__.ent", "d1h8pa2.ent-d1ki0a2.ent", "d1h8pa2.ent-d1ki0a3.ent", "d1h8pa2.ent-d1l6ja3.ent", "d1h8pa2.ent-d1l6ja5.ent", "d1h8pa2.ent-d1pmla_.ent", "d1h8pa2.ent-d2hpqp_.ent", "d1h8pa2.ent-d5hpga_.ent", "d1h8ua_.ent-d1cwva5.ent", "d1h8ua_.ent-d1f00i3.ent", "d1h8ua_.ent-d1kg0c_.ent", "d1h8ua_.ent-d1koe__.ent", "d1h8ua_.ent-d1li1a1.ent", "d1h8ua_.ent-d1li1a2.ent", "d1h8ua_.ent-d1prea1.ent", "d1h8ua_.ent-d1prtb2.ent", "d1h8ua_.ent-d1qdda_.ent", "d1h8ua_.ent-d1tsg__.ent", "d1h92a_.ent-d1i07a_.ent", "d1h92a_.ent-d1i1ja_.ent", "d1h92a_.ent-d1jo8a_.ent", "d1h92a_.ent-d1jqqa_.ent", "d1h92a_.ent-d1k4us_.ent", "d1h92a_.ent-d1kjwa1.ent", "d1h92a_.ent-d1neb__.ent", "d1h92a_.ent-d1pht__.ent", "d1h92a_.ent-d1pwt__.ent", "d1h92a_.ent-d1qcfa1.ent", "d1h92a_.ent-d1ycsb2.ent", "d1h92a_.ent-d2hsp__.ent", "d1h97a_.ent-d1cg5a_", "d1h97a_.ent-d1cg5a_.ent", "d1h97a_.ent-d1cg5b_", "d1h97a_.ent-d1cg5b_.ent", "d1h97a_.ent-d1ew6a_", "d1h97a_.ent-d1ew6a_.ent", "d1h97a_.ent-d1gcva_", "d1h97a_.ent-d1gcva_.ent", "d1h97a_.ent-d1gvha1", "d1h97a_.ent-d1gvha1.ent", "d1h97a_.ent-d1irda_", "d1h97a_.ent-d1irda_.ent", "d1h97a_.ent-d1irdb_", "d1h97a_.ent-d1irdb_.ent", "d1h97a_.ent-d1it2a_", "d1h97a_.ent-d1it2a_.ent", "d1h97a_.ent-d1itha_", "d1h97a_.ent-d1itha_.ent", "d1h97a_.ent-d1jl7a_", "d1h97a_.ent-d1jl7a_.ent", "d1h97a_.ent-d1la6a_", "d1h97a_.ent-d1mba__", "d1h97a_.ent-d1mba__.ent", "d1h97a_.ent-d1qlab1", "d1h97a_.ent-d1qlab1.ent", "d1h97a_.ent-d2gdm__", "d1h97a_.ent-d2gdm__.ent", "d1h97a_.ent-d3sdha_", "d1h97a_.ent-d3sdha_.ent", "d1h98a_.ent-d1hfel2.ent", "d1h98a_.ent-d1iqza_.ent", "d1h98a_.ent-d1jb0c_.ent", "d1h98a_.ent-d1jnrb_.ent", "d1h98a_.ent-d1keka5.ent", "d1h98a_.ent-d1kqfb1.ent", "d1h98a_.ent-d2fdn__.ent", "d1h98a_.ent-d7fd1a_.ent", "d1h9ea_.ent-d1h9fa_.ent", "d1h9ea_.ent-d1jeia_.ent", "d1h9ea_.ent-d1jeqa1.ent", "d1h9ea_.ent-d1kcfa1.ent", "d1h9fa_.ent-d1jeia_.ent", "d1h9fa_.ent-d1jeqa1.ent", "d1h9fa_.ent-d1kcfa1.ent", "d1h9ma1.ent-d1h9ma2.ent", "d1h9ma1.ent-d1h9ra1.ent", "d1h9ma1.ent-d1h9ra2.ent", "d1h9ma2.ent-d1h9ra1.ent", "d1h9ma2.ent-d1h9ra2.ent", "d1h9ra1.ent-d1h9ra2.ent", "d1hae__.ent-d1apq__.ent", "d1hae__.ent-d1b9wa1.ent", "d1hae__.ent-d1b9wa2.ent", "d1hae__.ent-d1ceja1.ent", "d1hae__.ent-d1ceja2.ent", "d1hae__.ent-d1cvua2.ent", "d1hae__.ent-d1dx5i1.ent", "d1hae__.ent-d1emo_1.ent", "d1hae__.ent-d1fjsl_.ent", "d1hae__.ent-d1hz8a1.ent", "d1hae__.ent-d1hz8a2.ent", "d1hae__.ent-d1ijqa2.ent", "d1hae__.ent-d1ioxa_.ent", "d1hae__.ent-d1jl9a_.ent", "d1hae__.ent-d1klil_.ent", "d1hae__.ent-d1klo_1.ent", "d1hae__.ent-d1klo_2.ent", "d1hae__.ent-d1klo_3.ent", "d1hae__.ent-d1l3ya_.ent", "d1hae__.ent-d1m1xb5.ent", "d1hae__.ent-d1rfnb_.ent", "d1hae__.ent-d1tpg_1.ent", "d1hae__.ent-d1urk_1.ent", "d1hae__.ent-d3tgf__.ent", "d1hava_.ent-d1lcya2.ent", "d1hava_.ent-d1lvmb_.ent", "d1hava_.ent-d1lvoa_.ent", "d1hava_.ent-d1mbma_.ent", "d1hava_.ent-d1qq4a_.ent", "d1hava_.ent-d1svpa_.ent", "d1hava_.ent-d2hrva_.ent", "d1hbka_.ent-d1mixa1.ent", "d1hbnb2.ent-d1b3ta_.ent", "d1hbnb2.ent-d1dj0a2.ent", "d1hbnb2.ent-d1dqaa1.ent", "d1hbnb2.ent-d1ekra_.ent", "d1hbnb2.ent-d1eqoa_.ent", "d1hbnb2.ent-d1f3va_.ent", "d1hbnb2.ent-d1ftra1.ent", "d1hbnb2.ent-d1ftra2.ent", "d1hbnb2.ent-d1gpja3.ent", "d1hbnb2.ent-d1h72c2.ent", "d1hbnb2.ent-d1hbnc_.ent", "d1hbnb2.ent-d1hlwa_.ent", "d1hbnb2.ent-d1jnrb_.ent", "d1hbnb2.ent-d1kvka2.ent", "d1hbnb2.ent-d1qd1a1.ent", "d1hbnb2.ent-d1qd1a2.ent", "d1hbnb2.ent-d1regx_.ent", "d1hbnc_.ent-d1azsa_.ent", "d1hbnc_.ent-d1b3ta_.ent", "d1hbnc_.ent-d1dj0a2.ent", "d1hbnc_.ent-d1dqaa1.ent", "d1hbnc_.ent-d1ekra_.ent", "d1hbnc_.ent-d1eqoa_.ent", "d1hbnc_.ent-d1f0xa1.ent", "d1hbnc_.ent-d1f3va_.ent", "d1hbnc_.ent-d1ftra1.ent", "d1hbnc_.ent-d1ftra2.ent", "d1hbnc_.ent-d1fx2a_.ent", "d1hbnc_.ent-d1gpja3.ent", "d1hbnc_.ent-d1h0hb_.ent", "d1hbnc_.ent-d1h72c2.ent", "d1hbnc_.ent-d1hbnb2.ent", "d1hbnc_.ent-d1hlwa_.ent", "d1hbnc_.ent-d1jnrb_.ent", "d1hbnc_.ent-d1kvka2.ent", "d1hbnc_.ent-d1lfwa2.ent", "d1hbnc_.ent-d1qd1a1.ent", "d1hbnc_.ent-d1qd1a2.ent", "d1hbnc_.ent-d1regx_.ent", "d1hc2_2.ent-d1js8a1.ent", "d1hc2_2.ent-d1lla_2.ent", "d1hc2_3.ent-d1bf2_1.ent", "d1hc2_3.ent-d1ea9c1.ent", "d1hc2_3.ent-d1edqa1.ent", "d1hc2_3.ent-d1eut_1.ent", "d1hc2_3.ent-d1g0da1.ent", "d1hc2_3.ent-d1g4ma1.ent", "d1hc2_3.ent-d1g4ma2.ent", "d1hc2_3.ent-d1j0ha1.ent", "d1hc2_3.ent-d1ji1a1.ent", "d1hc2_3.ent-d1ji2a1.ent", "d1hc2_3.ent-d1jjua4.ent", "d1hc2_3.ent-d1jmxa4.ent", "d1hc2_3.ent-d1kmta_.ent", "d1hc2_3.ent-d1ktja_.ent", "d1hc2_3.ent-d1kv3a1.ent", "d1hc2_3.ent-d1l9na1.ent", "d1hc2_3.ent-d1lla_3.ent", "d1hc2_3.ent-d1m7xa1.ent", "d1hc2_3.ent-d1my7a_.ent", "d1hc2_3.ent-d1nepa_.ent", "d1hc2_3.ent-d1qba_1.ent", "d1hc2_3.ent-d1qfha1.ent", "d1hc2_3.ent-d1qfha2.ent", "d1hc2_3.ent-d1soxa1.ent", "d1hc7a1.ent-d1kmma1.ent", "d1hc7a1.ent-d1nbwb_.ent", "d1hc7a1.ent-d1qe0a1.ent", "d1hc7a1.ent-d1qf6a1.ent", "d1hc7a2.ent-d1jjca_.ent", "d1hc7a2.ent-d1jjcb5.ent", "d1hc7a2.ent-d1kmma2.ent", "d1hc7a2.ent-d1qe0a2.ent", "d1hc7a2.ent-d1qf6a4.ent", "d1hc7a2.ent-d1seta2.ent", "d1hc7a3.ent-d1jo0a_.ent", "d1hc7a3.ent-d1msza_.ent", "d1hc7a3.ent-d1qmha2.ent", "d1hc7a3.ent-d1tig__.ent", "d1hc9a_.ent-d1jgka_.ent", "d1hc9a_.ent-d1kbaa_.ent", "d1hc9a_.ent-d1m9za_.ent", "d1hc9a_.ent-d1tfs__.ent", "d1hc9a_.ent-d1tgxa_.ent", "d1hc9a_.ent-d3ebx__.ent", "d1hcc__.ent-d1hfi__.ent", "d1hcc__.ent-d1ly2a1.ent", "d1hcc__.ent-d1ly2a2.ent", "d1hcc__.ent-d1quba1.ent", "d1hcc__.ent-d1quba2.ent", "d1hcc__.ent-d1quba3.ent", "d1hcc__.ent-d1quba4.ent", "d1hcc__.ent-d1quba5.ent", "d1hcd__.ent-d1jlxa1.ent", "d1hcd__.ent-d1knma_.ent", "d1hcd__.ent-d1l2ha_.ent", "d1hcd__.ent-d1n4ka2.ent", "d1hcia1.ent-d1hcia4.ent", "d1hcia1.ent-d1hx1b_.ent", "d1hcia1.ent-d1jnra1.ent", "d1hcia1.ent-d1m7ka_.ent", "d1hcia1.ent-d1qlaa1.ent", "d1hcia1.ent-d1quua1.ent", "d1hcia1.ent-d1quua2.ent", "d1hcia1.ent-d2spca_.ent", "d1hcia4.ent-d1hx1b_.ent", "d1hcia4.ent-d1jnra1.ent", "d1hcia4.ent-d1m7ka_.ent", "d1hcia4.ent-d1qlaa1.ent", "d1hcia4.ent-d1quua1.ent", "d1hcia4.ent-d1quua2.ent", "d1hcia4.ent-d2spca_.ent", "d1hcna_.ent-d1hcnb_.ent", "d1hcna_.ent-d1jpya_.ent", "d1hcna_.ent-d1m4ua_.ent", "d1hcna_.ent-d1m4ul_.ent", "d1hcna_.ent-d1pdga_.ent", "d1hcna_.ent-d2tgi__.ent", "d1hcnb_.ent-d1jpya_.ent", "d1hcnb_.ent-d1m4ua_.ent", "d1hcnb_.ent-d1m4ul_.ent", "d1hcnb_.ent-d1pdga_.ent", "d1hcnb_.ent-d2tgi__.ent", "d1hcz_2.ent-d1kjqa1.ent", "d1hd1a_.ent-d1iqta_.ent", "d1hd1a_.ent-d1jmta_.ent", "d1hd1a_.ent-d1koha2.ent", "d1hd1a_.ent-d1l3ka1.ent", "d1hd1a_.ent-d1l3ka2.ent", "d1hd1a_.ent-d1nu4a_.ent", "d1hd1a_.ent-d1qm9a1.ent", "d1hd1a_.ent-d1qm9a2.ent", "d1hd1a_.ent-d1u2fa_.ent", "d1hd1a_.ent-d2msta_.ent", "d1hd1a_.ent-d2u1a__.ent", "d1hd1a_.ent-d2u2fa_.ent", "d1hd2a_.ent-d1a8l_1.ent", "d1hd2a_.ent-d1a8l_2.ent", "d1hd2a_.ent-d1a8y_1.ent", "d1hd2a_.ent-d1a8y_2.ent", "d1hd2a_.ent-d1a8y_3.ent", "d1hd2a_.ent-d1aba__.ent", "d1hd2a_.ent-d1aqwa2.ent", "d1hd2a_.ent-d1bed_2.ent", "d1hd2a_.ent-d1bjx__.ent", "d1hd2a_.ent-d1e6ba2.ent", "d1hd2a_.ent-d1eeja1.ent", "d1hd2a_.ent-d1ep7a_.ent", "d1hd2a_.ent-d1erv__.ent", "d1hd2a_.ent-d1f9ma_.ent", "d1hd2a_.ent-d1fb6a_.ent", "d1hd2a_.ent-d1fhe_2.ent", "d1hd2a_.ent-d1fvka2.ent", "d1hd2a_.ent-d1g7ea_.ent", "d1hd2a_.ent-d1gh2a_.ent", "d1hd2a_.ent-d1hyua4.ent", "d1hd2a_.ent-d1i5ga_.ent", "d1hd2a_.ent-d1iloa_.ent", "d1hd2a_.ent-d1k0ma2.ent", "d1hd2a_.ent-d1k3ya2.ent", "d1hd2a_.ent-d1knga_.ent", "d1hd2a_.ent-d1kte__.ent", "d1hd2a_.ent-d1m2da_.ent", "d1hd2a_.ent-d1mek__.ent", "d1hd2a_.ent-d1qmha1.ent", "d1hd2a_.ent-d1quwa_.ent", "d1hd2a_.ent-d1thx__.ent", "d1hd2a_.ent-d2trxa_.ent", "d1hd6a_.ent-d2erl__.ent", "d1hd7a_.ent-d1i9za_.ent", "d1hd7a_.ent-d2dnja_.ent", "d1hdia_.ent-d1php__.ent", "d1hdj__.ent-d1ivsa1.ent", "d1hdj__.ent-d1ix9a1.ent", "d1hdj__.ent-d1jj2u_.ent", "d1hdj__.ent-d1k4ta1.ent", "d1hdj__.ent-d1lrza1.ent", "d1hdj__.ent-d1seta1.ent", "d1hdj__.ent-d1xbl__.ent", "d1hdma2.ent-d1hdmb2.ent", "d1hdma2.ent-d1hyrc2.ent", "d1hdma2.ent-d1iaka2.ent", "d1hdma2.ent-d1jfma_.ent", "d1hdma2.ent-d1k5na2.ent", "d1hdma2.ent-d1kcgc_.ent", "d1hdma2.ent-d1lqva_.ent", "d1hdma2.ent-d1zaga2.ent", "d1hdma2.ent-d3frua2.ent", "d1hdmb2.ent-d1hyrc2.ent", "d1hdmb2.ent-d1iaka2.ent", "d1hdmb2.ent-d1jfma_.ent", "d1hdmb2.ent-d1k5na2.ent", "d1hdmb2.ent-d1kcgc_.ent", "d1hdmb2.ent-d1lqva_.ent", "d1hdmb2.ent-d1zaga2.ent", "d1hdmb2.ent-d3frua2.ent", "d1hdoa_.ent-d1bg6_2.ent", "d1hdoa_.ent-d1c1da1.ent", "d1hdoa_.ent-d1cf2o1.ent", "d1hdoa_.ent-d1dlja2.ent", "d1hdoa_.ent-d1dpga1.ent", "d1hdoa_.ent-d1dssg1.ent", "d1hdoa_.ent-d1e5qa1.ent", "d1hdoa_.ent-d1f0ya2.ent", "d1hdoa_.ent-d1lc0a1.ent", "d1hdoa_.ent-d1lu9a1.ent", "d1hdoa_.ent-d2naca1.ent", "d1hdoa_.ent-d2pgd_2.ent", "d1hdr__.ent-d1bg6_2.ent", "d1hdr__.ent-d1c1da1.ent", "d1hdr__.ent-d1cf2o1.ent", "d1hdr__.ent-d1dlja2.ent", "d1hdr__.ent-d1dpga1.ent", "d1hdr__.ent-d1dssg1.ent", "d1hdr__.ent-d1e5qa1.ent", "d1hdr__.ent-d1f0ya2.ent", "d1hdr__.ent-d1hdoa_.ent", "d1hdr__.ent-d1jaya_.ent", "d1hdr__.ent-d1lc0a1.ent", "d1hdr__.ent-d1lu9a1.ent", "d1hdr__.ent-d1qmga2.ent", "d1hdr__.ent-d2naca1.ent", "d1hdr__.ent-d2pgd_2.ent", "d1he1a_.ent-d1jr8a_.ent", "d1he1a_.ent-d1k04a_.ent", "d1he1a_.ent-d1knya1.ent", "d1he1a_.ent-d1ls1a1.ent", "d1he1a_.ent-d1nfn__.ent", "d1he1a_.ent-d1nlxa_.ent", "d1he1a_.ent-d256ba_.ent", "d1he1a_.ent-d2a0b__.ent", "d1he1a_.ent-d2liga_.ent", "d1he1a_.ent-d2mhr__.ent", "d1he1a_.ent-d3fapb_.ent", "d1heta1.ent-d1jh2a_.ent", "d1heta1.ent-d1jqba1.ent", "d1heta1.ent-d1kola1.ent", "d1heta1.ent-d1qora1.ent", "d1hev__.ent-d1mmc__.ent", "d1hev__.ent-d9wgaa2.ent", "d1hf2a1.ent-d1k4za_.ent", "d1hf2a1.ent-d1k5ca_.ent", "d1hf2a1.ent-d1llwa1.ent", "d1hf2a1.ent-d1qcxa_.ent", "d1hf2a1.ent-d1qq1a_.ent", "d1hf8a_.ent-d1e8xa1.ent", "d1hf8a_.ent-d1elka_.ent", "d1hf8a_.ent-d1h6ka2.ent", "d1hf8a_.ent-d1hh8a_.ent", "d1hf8a_.ent-d1hs6a1.ent", "d1hf8a_.ent-d1ihga1.ent", "d1hf8a_.ent-d1keya_.ent", "d1hf8a_.ent-d1kpsb_.ent", "d1hf8a_.ent-d1l5ja1.ent", "d1hf8a_.ent-d1lrv__.ent", "d1hf8a_.ent-d1n4ka1.ent", "d1hf8a_.ent-d1pbv__.ent", "d1hf8a_.ent-d1qjba_.ent", "d1hfba_.ent-d1i2oa_.ent", "d1hfba_.ent-d1jcla_.ent", "d1hfba_.ent-d1jcxa_.ent", "d1hfba_.ent-d1l6wa_.ent", "d1hfba_.ent-d1mzha_.ent", "d1hfba_.ent-d1nal1_.ent", "d1hfba_.ent-d1o0ya_.ent", "d1hfba_.ent-d1qfea_.ent", "d1hfel2.ent-d1iqza_.ent", "d1hfel2.ent-d1jb0c_.ent", "d1hfel2.ent-d1jnrb_.ent", "d1hfel2.ent-d1keka5.ent", "d1hfel2.ent-d1kqfb1.ent", "d1hfel2.ent-d2fdn__.ent", "d1hfel2.ent-d7fd1a_.ent", "d1hfes_.ent-d1jj21_.ent", "d1hfes_.ent-d1tbge_.ent", "d1hfes_.ent-d2prgc_.ent", "d1hfi__.ent-d1ly2a1.ent", "d1hfi__.ent-d1ly2a2.ent", "d1hfi__.ent-d1quba1.ent", "d1hfi__.ent-d1quba2.ent", "d1hfi__.ent-d1quba3.ent", "d1hfi__.ent-d1quba4.ent", "d1hfi__.ent-d1quba5.ent", "d1hfoa_.ent-d1otfa_.ent", "d1hfoa_.ent-d1otga_.ent", "d1hfua2.ent-d1cyx__.ent", "d1hfua2.ent-d1e30a_.ent", "d1hfua2.ent-d1gw0a1.ent", "d1hfua2.ent-d1ibya_.ent", "d1hfua2.ent-d1ikop_.ent", "d1hfua2.ent-d1jzga_.ent", "d1hfua2.ent-d1kbva1.ent", "d1hfua2.ent-d1kbva2.ent", "d1hfua2.ent-d1kcw_1.ent", "d1hfua2.ent-d1kcw_2.ent", "d1hfua2.ent-d1kcw_4.ent", "d1hfua2.ent-d1kcw_6.ent", "d1hfua2.ent-d1kv7a1.ent", "d1hfua2.ent-d1kv7a2.ent", "d1hfua2.ent-d1kv7a3.ent", "d1hfua2.ent-d1kzqa1.ent", "d1hfua2.ent-d1l9qa1.ent", "d1hfua2.ent-d1l9qa2.ent", "d1hfua2.ent-d1m56b1.ent", "d1hfua2.ent-d1qhqa_.ent", "d1hfua2.ent-d2cbp__.ent", "d1hfua2.ent-d2cuaa_.ent", "d1hfua3.ent-d1cyx__.ent", "d1hfua3.ent-d1e30a_.ent", "d1hfua3.ent-d1gw0a1.ent", "d1hfua3.ent-d1gw0a2.ent", "d1hfua3.ent-d1hfua2.ent", "d1hfua3.ent-d1ikop_.ent", "d1hfua3.ent-d1kbva1.ent", "d1hfua3.ent-d1kbva2.ent", "d1hfua3.ent-d1kcw_1.ent", "d1hfua3.ent-d1kcw_2.ent", "d1hfua3.ent-d1kcw_3.ent", "d1hfua3.ent-d1kcw_4.ent", "d1hfua3.ent-d1kcw_5.ent", "d1hfua3.ent-d1kcw_6.ent", "d1hfua3.ent-d1kv7a1.ent", "d1hfua3.ent-d1kv7a2.ent", "d1hfua3.ent-d1kv7a3.ent", "d1hfua3.ent-d1l9qa1.ent", "d1hfua3.ent-d1l9qa2.ent", "d1hfua3.ent-d1m56b1.ent", "d1hfua3.ent-d1qhqa_.ent", "d1hg3a_.ent-d1lyxa_.ent", "d1hg3a_.ent-d1n55a_.ent", "d1hg3a_.ent-d1trea_.ent", "d1hg4a_.ent-d1ie9a_.ent", "d1hg4a_.ent-d1ilga_.ent", "d1hg4a_.ent-d1kv6a_.ent", "d1hg4a_.ent-d1lv2a_.ent", "d1hg4a_.ent-d1mzna_.ent", "d1hg4a_.ent-d1n83a_.ent", "d1hg4a_.ent-d2prga_.ent", "d1hg7a_.ent-d1mlva2.ent", "d1hg7a_.ent-d1n3ja_.ent", "d1hg7a_.ent-d1tul__.ent", "d1hg7a_.ent-d4ubpb_.ent", "d1hg8a_.ent-d1jtaa_.ent", "d1hg8a_.ent-d1k5ca_.ent", "d1hg8a_.ent-d1qcxa_.ent", "d1hg8a_.ent-d1qjva_.ent", "d1hg8a_.ent-d1qq1a_.ent", "d1hg8a_.ent-d1rmg__.ent", "d1hgxa_.ent-d1i5ea_.ent", "d1hgxa_.ent-d1l1qa_.ent", "d1hgxa_.ent-d1lh0a_.ent", "d1hgxa_.ent-d1nula_.ent", "d1hgxa_.ent-d1qb7a_.ent", "d1hgxa_.ent-d1tc1a_.ent", "d1hh1a_.ent-d1kc6a_.ent", "d1hh1a_.ent-d1knva_.ent", "d1hh1a_.ent-d1m0da_.ent", "d1hh1a_.ent-d1vsra_.ent", "d1hh1a_.ent-d2foka4.ent", "d1hh1a_.ent-d3pvia_.ent", "d1hh2p2.ent-d1k0ra2.ent", "d1hh2p2.ent-d1k0ra3.ent", "d1hh5a_.ent-d1kssa1.ent", "d1hh5a_.ent-d1m1qa_.ent", "d1hh5a_.ent-d1qo8a1.ent", "d1hh5a_.ent-d1wad__.ent", "d1hh5a_.ent-d2ctha_.ent", "d1hh5a_.ent-d2cy3__.ent", "d1hh5a_.ent-d3caoa_.ent", "d1hh5a_.ent-d3cyr__.ent", "d1hh8a_.ent-d1e8xa1.ent", "d1hh8a_.ent-d1elka_.ent", "d1hh8a_.ent-d1h6ka2.ent", "d1hh8a_.ent-d1hs6a1.ent", "d1hh8a_.ent-d1hz4a_.ent", "d1hh8a_.ent-d1ihga1.ent", "d1hh8a_.ent-d1iyga_.ent", "d1hh8a_.ent-d1kpsb_.ent", "d1hh8a_.ent-d1kt1a1.ent", "d1hh8a_.ent-d1l5ja1.ent", "d1hh8a_.ent-d1n4ka1.ent", "d1hh8a_.ent-d1qqea_.ent", "d1hhsa_.ent-d1ih7a2.ent", "d1hhsa_.ent-d1im4a_.ent", "d1hhsa_.ent-d1jiha_.ent", "d1hhsa_.ent-d1kfsa2.ent", "d1hhsa_.ent-d1khva_.ent", "d1hhsa_.ent-d1mml__.ent", "d1hhsa_.ent-d1mswd_.ent", "d1hhsa_.ent-d1muka_.ent", "d1hhsa_.ent-d1rdr__.ent", "d1hhsa_.ent-d1t7pa2.ent", "d1hhsa_.ent-d1tgoa2.ent", "d1hhsa_.ent-d1vrta2.ent", "d1hhsa_.ent-d1xwl_2.ent", "d1hi7a_.ent-d2pspa2.ent", "d1hiwa_.ent-d1jvr__.ent", "d1hiwa_.ent-d1mn8a_.ent", "d1hjra_.ent-d1i39a_.ent", "d1hjra_.ent-d1ih7a1.ent", "d1hjra_.ent-d1io2a_.ent", "d1hjra_.ent-d1j54a_.ent", "d1hjra_.ent-d1jl1a_.ent", "d1hjra_.ent-d1kcfa2.ent", "d1hjra_.ent-d1kfsa1.ent", "d1hjra_.ent-d1musa_.ent", "d1hjra_.ent-d1qtma1.ent", "d1hjra_.ent-d1t7pa1.ent", "d1hjra_.ent-d1tgoa1.ent", "d1hjra_.ent-d1vrta1.ent", "d1hjra_.ent-d1xwl_1.ent", "d1hks__.ent-d1bjaa_.ent", "d1hks__.ent-d1d5va_.ent", "d1hks__.ent-d1e17a_.ent", "d1hks__.ent-d1f1za1.ent", "d1hks__.ent-d1fnna1.ent", "d1hks__.ent-d1fp2a1.ent", "d1hks__.ent-d1fsha_.ent", "d1hks__.ent-d1fzpb_.ent", "d1hks__.ent-d1ka8a_.ent", "d1hks__.ent-d1ldja1.ent", "d1hks__.ent-d1repc2.ent", "d1hks__.ent-d1smta_.ent", "d1hks__.ent-d2foka3.ent", "d1hkya_.ent-d1i8na_.ent", "d1hlb__.ent-d1a6m__", "d1hlb__.ent-d1a6m__.ent", "d1hlb__.ent-d1ash__", "d1hlb__.ent-d1ash__.ent", "d1hlb__.ent-d1cg5a_", "d1hlb__.ent-d1cg5a_.ent", "d1hlb__.ent-d1cg5b_", "d1hlb__.ent-d1cg5b_.ent", "d1hlb__.ent-d1cqxa1", "d1hlb__.ent-d1cqxa1.ent", "d1hlb__.ent-d1ew6a_", "d1hlb__.ent-d1ew6a_.ent", "d1hlb__.ent-d1gcva_", "d1hlb__.ent-d1gcva_.ent", "d1hlb__.ent-d1gvha1", "d1hlb__.ent-d1gvha1.ent", "d1hlb__.ent-d1h97a_", "d1hlb__.ent-d1h97a_.ent", "d1hlb__.ent-d1irda_", "d1hlb__.ent-d1irda_.ent", "d1hlb__.ent-d1irdb_", "d1hlb__.ent-d1irdb_.ent", "d1hlb__.ent-d1it2a_", "d1hlb__.ent-d1it2a_.ent", "d1hlb__.ent-d1itha_", "d1hlb__.ent-d1itha_.ent", "d1hlb__.ent-d1jl7a_", "d1hlb__.ent-d1jl7a_.ent", "d1hlb__.ent-d1la6a_", "d1hlb__.ent-d1la6a_.ent", "d1hlb__.ent-d1mba__", "d1hlb__.ent-d1mba__.ent", "d1hlb__.ent-d2gdm__", "d1hlb__.ent-d2gdm__.ent", "d1hlb__.ent-d2lhb__", "d1hlb__.ent-d2lhb__.ent", "d1hlb__.ent-d3sdha_", "d1hlb__.ent-d3sdha_.ent", "d1hlga_.ent-d1bu8a2.ent", "d1hlga_.ent-d1cr6a2.ent", "d1hlga_.ent-d1cvl__.ent", "d1hlga_.ent-d1imja_.ent", "d1hlga_.ent-d1ispa_.ent", "d1hlga_.ent-d1iz7a_.ent", "d1hlga_.ent-d1jfra_.ent", "d1hlga_.ent-d1jjia_.ent", "d1hlga_.ent-d1jkma_.ent", "d1hlga_.ent-d1ju3a2.ent", "d1hlga_.ent-d1ku0a_.ent", "d1hlga_.ent-d1l7aa_.ent", "d1hlga_.ent-d1lzla_.ent", "d1hlga_.ent-d1mnaa_.ent", "d1hlga_.ent-d1n1ma2.ent", "d1hlga_.ent-d1qj4a_.ent", "d1hlga_.ent-d1qlwa_.ent", "d1hlga_.ent-d1qo7a_.ent", "d1hlga_.ent-d1qtra_.ent", "d1hlga_.ent-d1tca__.ent", "d1hlga_.ent-d1thta_.ent", "d1hlga_.ent-d3tgl__.ent", "d1hlra1.ent-d1n62a1.ent", "d1hlra2.ent-d1i7ha_.ent", "d1hlra2.ent-d1jq4a_.ent", "d1hlra2.ent-d1jroa2.ent", "d1hlra2.ent-d1kf6b2.ent", "d1hlra2.ent-d1krha3.ent", "d1hlra2.ent-d1l5pa_.ent", "d1hlra2.ent-d1n62a2.ent", "d1hlra2.ent-d1nekb2.ent", "d1hlra2.ent-d1put__.ent", "d1hlra2.ent-d1qlab2.ent", "d1hlra2.ent-d2pia_3.ent", "d1hlra3.ent-d1jrob1.ent", "d1hlra3.ent-d1n62b1.ent", "d1hlra4.ent-d1n62b2.ent", "d1hlva1.ent-d1b8ia_.ent", "d1hlva1.ent-d1bl0a2.ent", "d1hlva1.ent-d1d5ya2.ent", "d1hlva1.ent-d1e3oc1.ent", "d1hlva1.ent-d1fexa_.ent", "d1hlva1.ent-d1fjla_.ent", "d1hlva1.ent-d1g2ha_.ent", "d1hlva1.ent-d1hlva2.ent", "d1hlva1.ent-d1ig7a_.ent", "d1hlva1.ent-d1irza_.ent", "d1hlva1.ent-d1iufa2.ent", "d1hlva1.ent-d1k61a_.ent", "d1hlva1.ent-d1k78a1.ent", "d1hlva1.ent-d1k78a2.ent", "d1hlva1.ent-d2tct_1.ent", "d1hlva2.ent-d1b8ia_.ent", "d1hlva2.ent-d1bl0a2.ent", "d1hlva2.ent-d1e3oc1.ent", "d1hlva2.ent-d1fexa_.ent", "d1hlva2.ent-d1g2ha_.ent", "d1hlva2.ent-d1ig7a_.ent", "d1hlva2.ent-d1irza_.ent", "d1hlva2.ent-d1k61a_.ent", "d1hlva2.ent-d1k78a1.ent", "d1hlva2.ent-d1k78a2.ent", "d1hlwa_.ent-d1b3ta_.ent", "d1hlwa_.ent-d1dqaa1.ent", "d1hlwa_.ent-d1ekra_.ent", "d1hlwa_.ent-d1ftra1.ent", "d1hlwa_.ent-d1ftra2.ent", "d1hlwa_.ent-d1gpja3.ent", "d1hlwa_.ent-d1h72c2.ent", "d1hlwa_.ent-d1jnrb_.ent", "d1hlwa_.ent-d1k44a_.ent", "d1hlwa_.ent-d1nhkl_.ent", "d1hlwa_.ent-d1qd1a2.ent", "d1hlwa_.ent-d1regx_.ent", "d1hm9a1.ent-d1kk6a_.ent", "d1hm9a1.ent-d1krra_.ent", "d1hm9a1.ent-d1lxa__.ent", "d1hm9a1.ent-d1qrea_.ent", "d1hm9a1.ent-d1xat__.ent", "d1hm9a1.ent-d3tdt__.ent", "d1hm9a2.ent-d1hv9a2.ent", "d1hm9a2.ent-d1i52a_.ent", "d1hm9a2.ent-d1jv1a_.ent", "d1hm9a2.ent-d1k4va_.ent", "d1hm9a2.ent-d1kwsa_.ent", "d1hm9a2.ent-d1ll2a_.ent", "d1hm9a2.ent-d1lzja_.ent", "d1hm9a2.ent-d1nf5b_.ent", "d1hm9a2.ent-d1qg8a_.ent", "d1hms__.ent-d1i4ua_.ent", "d1hms__.ent-d1ifc__.ent", "d1hms__.ent-d1jv4a_.ent", "d1hms__.ent-d1koia_.ent", "d1hms__.ent-d1kqwa_.ent", "d1hms__.ent-d1lf7a_.ent", "d1hms__.ent-d1o1va_.ent", "d1hms__.ent-d1qfta_.ent", "d1hms__.ent-d1qqsa_.ent", "d1hnja1.ent-d1hnja2.ent", "d1hnja1.ent-d1hzpa1.ent", "d1hnja1.ent-d1hzpa2.ent", "d1hnja1.ent-d1kas_1.ent", "d1hnja1.ent-d1m3ka1.ent", "d1hnja1.ent-d1m3ka2.ent", "d1hnja1.ent-d1mzja1.ent", "d1hnja1.ent-d1mzja2.ent", "d1hnja2.ent-d1hzpa1.ent", "d1hnja2.ent-d1hzpa2.ent", "d1hnja2.ent-d1kas_1.ent", "d1hnja2.ent-d1m3ka1.ent", "d1hnja2.ent-d1m3ka2.ent", "d1hnja2.ent-d1mzja1.ent", "d1hnja2.ent-d1mzja2.ent", "d1hnna_.ent-d1fp1d2.ent", "d1hnna_.ent-d1fp2a2.ent", "d1hnna_.ent-d1g60a_.ent", "d1hnna_.ent-d1i1na_.ent", "d1hnna_.ent-d1i4wa_.ent", "d1hnna_.ent-d1inla_.ent", "d1hnna_.ent-d1jg1a_.ent", "d1hnna_.ent-d1jqea_.ent", "d1hnna_.ent-d1jsxa_.ent", "d1hnna_.ent-d1khha_.ent", "d1hnna_.ent-d1kywa2.ent", "d1hnna_.ent-d1qama_.ent", "d1hnna_.ent-d1vid__.ent", "d1hnna_.ent-d1xvaa_.ent", "d1hnna_.ent-d1yub__.ent", "d1hnna_.ent-d2dpma_.ent", "d1hnna_.ent-d3mag__.ent", "d1hnua_.ent-d1hzda_.ent", "d1hnua_.ent-d1k32a4.ent", "d1hnua_.ent-d1mj3a_.ent", "d1hnua_.ent-d1nzya_.ent", "d1hnua_.ent-d1o8ua_.ent", "d1hnua_.ent-d1tyfa_.ent", "d1ho8a_.ent-d1e8xa1.ent", "d1ho8a_.ent-d1elka_.ent", "d1ho8a_.ent-d1h6ka1.ent", "d1ho8a_.ent-d1h6ka2.ent", "d1ho8a_.ent-d1h6ka3.ent", "d1ho8a_.ent-d1hf8a_.ent", "d1ho8a_.ent-d1hh8a_.ent", "d1ho8a_.ent-d1hs6a1.ent", "d1ho8a_.ent-d1hz4a_.ent", "d1ho8a_.ent-d1iala_.ent", "d1ho8a_.ent-d1ihga1.ent", "d1ho8a_.ent-d1jdha_.ent", "d1ho8a_.ent-d1keya_.ent", "d1ho8a_.ent-d1kpsb_.ent", "d1ho8a_.ent-d1kx9a_.ent", "d1ho8a_.ent-d1l5ja1.ent", "d1ho8a_.ent-d1ld8a_.ent", "d1ho8a_.ent-d1ldja2.ent", "d1ho8a_.ent-d1lrv__.ent", "d1ho8a_.ent-d1lsha1.ent", "d1ho8a_.ent-d1n4ka1.ent", "d1ho8a_.ent-d1pbv__.ent", "d1ho8a_.ent-d1qjba_.ent", "d1ho8a_.ent-d1qqea_.ent", "d1howa_.ent-d1a06__.ent", "d1howa_.ent-d1apme_.ent", "d1howa_.ent-d1b6cb_.ent", "d1howa_.ent-d1blxa_.ent", "d1howa_.ent-d1cjaa_.ent", "d1howa_.ent-d1csn__.ent", "d1howa_.ent-d1f3mc_.ent", "d1howa_.ent-d1fgka_.ent", "d1howa_.ent-d1fvra_.ent", "d1howa_.ent-d1ia9a_.ent", "d1howa_.ent-d1iepa_.ent", "d1howa_.ent-d1jksa_.ent", "d1howa_.ent-d1jnk__.ent", "d1howa_.ent-d1jpaa_.ent", "d1howa_.ent-d1jvpp_.ent", "d1howa_.ent-d1kwpa_.ent", "d1howa_.ent-d1lpua_.ent", "d1howa_.ent-d1lufa_.ent", "d1howa_.ent-d1m14a_.ent", "d1howa_.ent-d1phk__.ent", "d1howa_.ent-d1tkia_.ent", "d1hpi__.ent-d1isua_.ent", "d1hpi__.ent-d1iuaa_.ent", "d1hpi__.ent-d2hipa_.ent", "d1hq8a_.ent-d1b08a1.ent", "d1hq8a_.ent-d1b6e__.ent", "d1hq8a_.ent-d1cwva5.ent", "d1hq8a_.ent-d1e87a_.ent", "d1hq8a_.ent-d1f00i3.ent", "d1hq8a_.ent-d1fvub_.ent", "d1hq8a_.ent-d1g1ta1.ent", "d1hq8a_.ent-d1h8ua_.ent", "d1hq8a_.ent-d1jwia_.ent", "d1hq8a_.ent-d1jwib_.ent", "d1hq8a_.ent-d1li1a1.ent", "d1hq8a_.ent-d1li1a2.ent", "d1hq8a_.ent-d1prtb2.ent", "d1hq8a_.ent-d1tsg__.ent", "d1hqka_.ent-d1kz1a_.ent", "d1hqka_.ent-d1rvv1_.ent", "d1hqta_.ent-d1hw6a_.ent", "d1hqta_.ent-d1j96a_.ent", "d1hqta_.ent-d1jeza_.ent", "d1hqva_.ent-d1alva_.ent", "d1hqva_.ent-d1auib_.ent", "d1hqva_.ent-d1eg3a1.ent", "d1hqva_.ent-d1exra_.ent", "d1hqva_.ent-d1ggwa_.ent", "d1hqva_.ent-d1jfja_.ent", "d1hqva_.ent-d1k94a_.ent", "d1hqva_.ent-d1m31a_.ent", "d1hqva_.ent-d1m45a_.ent", "d1hqva_.ent-d1ncx__.ent", "d1hqva_.ent-d1rro__.ent", "d1hqva_.ent-d1sra__.ent", "d1hqva_.ent-d1wdcb_.ent", "d1hqva_.ent-d1wdcc_.ent", "d1hqva_.ent-d2pvba_.ent", "d1hqva_.ent-d2scpa_.ent", "d1hqva_.ent-d5pal__.ent", "d1hqz1_.ent-d1jhwa3.ent", "d1hqz1_.ent-d1m2oa4.ent", "d1hqz1_.ent-d1m2vb4.ent", "d1hqz1_.ent-d1m4ja_.ent", "d1hr6a1.ent-d1hr6a2.ent", "d1hr6a1.ent-d1hr6b1.ent", "d1hr6a1.ent-d1hr6b2.ent", "d1hr6a2.ent-d1hr6b1.ent", "d1hr6a2.ent-d1hr6b2.ent", "d1hr6b1.ent-d1hr6b2.ent", "d1hrka_.ent-d1lbqa_.ent", "d1hrka_.ent-d1qgoa_.ent", "d1hroa_.ent-d1etpa2.ent", "d1hroa_.ent-d1kb0a1.ent", "d1hroa_.ent-d1kv9a1.ent", "d1hroa_.ent-d1ql3a_.ent", "d1hroa_.ent-d1qn2a_.ent", "d1hs6a1.ent-d1iala_.ent", "d1hs6a1.ent-d1jdha_.ent", "d1hs6a1.ent-d1kx9a_.ent", "d1hs6a1.ent-d1lrv__.ent", "d1hs6a1.ent-d1n4ka1.ent", "d1hs6a3.ent-d1i1ip_.ent", "d1hs6a3.ent-d1j7na1.ent", "d1hs6a3.ent-d1j7na2.ent", "d1hs6a3.ent-d1jaka2.ent", "d1hs6a3.ent-d1jk3a_.ent", "d1hs6a3.ent-d1k7ia2.ent", "d1hs6a3.ent-d1k9xa_.ent", "d1hs6a3.ent-d1kapp2.ent", "d1hs6a3.ent-d1keia_.ent", "d1hs6a3.ent-d1kufa_.ent", "d1hs6a3.ent-d1lml__.ent", "d1hs6a3.ent-d1qba_4.ent", "d1hs6a3.ent-d3btaa3.ent", "d1hs7a_.ent-d1lvfa_.ent", "d1hsja1.ent-d1bjaa_.ent", "d1hsja1.ent-d1d5va_.ent", "d1hsja1.ent-d1e17a_.ent", "d1hsja1.ent-d1f1za1.ent", "d1hsja1.ent-d1fnna1.ent", "d1hsja1.ent-d1fp1d1.ent", "d1hsja1.ent-d1fp2a1.ent", "d1hsja1.ent-d1fsha_.ent", "d1hsja1.ent-d1fzpb_.ent", "d1hsja1.ent-d1hks__.ent", "d1hsja1.ent-d1ig6a_.ent", "d1hsja1.ent-d1igna2.ent", "d1hsja1.ent-d1jhga_.ent", "d1hsja1.ent-d1ka8a_.ent", "d1hsja1.ent-d1ldja1.ent", "d1hsja1.ent-d1opc__.ent", "d1hsja1.ent-d1repc1.ent", "d1hsja1.ent-d1repc2.ent", "d1hsja1.ent-d1smta_.ent", "d1hsja1.ent-d2ezl__.ent", "d1hsja1.ent-d2foka3.ent", "d1hsja1.ent-d2irfg_.ent", "d1hska1.ent-d1i19a2.ent", "d1hska1.ent-d1jroa4.ent", "d1hska1.ent-d1n62c2.ent", "d1hska1.ent-d1uxy_1.ent", "d1hsm__.ent-d1i11a_.ent", "d1hsm__.ent-d1k99a_.ent", "d1hsm__.ent-d1lwma_.ent", "d1hsm__.ent-d1qrva_.ent", "d1hsm__.ent-d2lefa_.ent", "d1hssa_.ent-d1hyp__.ent", "d1hssa_.ent-d1l6ha_.ent", "d1htp__.ent-d1k8ma_.ent", "d1htp__.ent-d1kjqa1.ent", "d1htp__.ent-d1lac__.ent", "d1htp__.ent-d1qjoa_.ent", "d1hula_.ent-d1huw__.ent", "d1hula_.ent-d1hzia_.ent", "d1hula_.ent-d1i1rb_.ent", "d1hula_.ent-d1jli__.ent", "d1hula_.ent-d1lki__.ent", "d1hula_.ent-d1lqsl_.ent", "d1hula_.ent-d1m47a_.ent", "d1hula_.ent-d1n1fa_.ent", "d1hula_.ent-d2gmfa_.ent", "d1hula_.ent-d2ilk__.ent", "d1huva_.ent-d1icpa_.ent", "d1huva_.ent-d1kbia1.ent", "d1huva_.ent-d1llwa2.ent", "d1huva_.ent-d1o94a1.ent", "d1huva_.ent-d1oyb__.ent", "d1huva_.ent-d2dora_.ent", "d1huw__.ent-d1hzia_.ent", "d1huw__.ent-d1i1rb_.ent", "d1huw__.ent-d1jli__.ent", "d1huw__.ent-d1lki__.ent", "d1huw__.ent-d1lqsl_.ent", "d1huw__.ent-d1m47a_.ent", "d1huw__.ent-d1n1fa_.ent", "d1huw__.ent-d2gmfa_.ent", "d1huw__.ent-d2ilk__.ent", "d1huxa_.ent-d1az9_1.ent", "d1huxa_.ent-d1bco_2.ent", "d1huxa_.ent-d1bupa1.ent", "d1huxa_.ent-d1bupa2.ent", "d1huxa_.ent-d1czan1.ent", "d1huxa_.ent-d1czan2.ent", "d1huxa_.ent-d1e4ft1.ent", "d1huxa_.ent-d1e4ft2.ent", "d1huxa_.ent-d1g99a2.ent", "d1huxa_.ent-d1glag1.ent", "d1huxa_.ent-d1glag2.ent", "d1huxa_.ent-d1ig8a1.ent", "d1huxa_.ent-d1ig8a2.ent", "d1huxa_.ent-d1j54a_.ent", "d1huxa_.ent-d1j6za2.ent", "d1huxa_.ent-d1jcfa1.ent", "d1huxa_.ent-d1jj2m_.ent", "d1huxa_.ent-d1k8ka1.ent", "d1huxa_.ent-d1kcfa2.ent", "d1huxa_.ent-d1mwma1.ent", "d1huxa_.ent-d1mwma2.ent", "d1huxa_.ent-d1nbwa2.ent", "d1huxa_.ent-d1nbwa3.ent", "d1huxa_.ent-d1t7pa1.ent", "d1huxa_.ent-d1xwl_1.ent", "d1hv2a_.ent-d1lm8c_.ent", "d1hv2a_.ent-d1t1da_.ent", "d1hv2a_.ent-d3kvt__.ent", "d1hv9a2.ent-d1i52a_.ent", "d1hv9a2.ent-d1jv1a_.ent", "d1hv9a2.ent-d1k4va_.ent", "d1hv9a2.ent-d1kwsa_.ent", "d1hv9a2.ent-d1ll2a_.ent", "d1hv9a2.ent-d1lzja_.ent", "d1hv9a2.ent-d1nf5b_.ent", "d1hv9a2.ent-d1qg8a_.ent", "d1hw5a2.ent-d1ig0a1.ent", "d1hw5a2.ent-d1jr7a_.ent", "d1hw5a2.ent-d1juha_.ent", "d1hw5a2.ent-d1lrha_.ent", "d1hw5a2.ent-d1m4oa_.ent", "d1hw5a2.ent-d1o7fa2.ent", "d1hw5a2.ent-d1o7fa3.ent", "d1hw5a2.ent-d1pmi__.ent", "d1hw5a2.ent-d1rgs_1.ent", "d1hw5a2.ent-d1rgs_2.ent", "d1hw5a2.ent-d1wapa_.ent", "d1hw5a2.ent-d2arca_.ent", "d1hw6a_.ent-d1j96a_.ent", "d1hw6a_.ent-d1jeza_.ent", "d1hwma_.ent-d1ift__.ent", "d1hwma_.ent-d1mrj__.ent", "d1hwma_.ent-d1qi7a_.ent", "d1hwmb1.ent-d1hwmb2.ent", "d1hwmb1.ent-d1knma_.ent", "d1hwmb2.ent-d1knma_.ent", "d1hwtc1.ent-d1pyia1.ent", "d1hwtc1.ent-d1zmec1.ent", "d1hwtc1.ent-d2alca_.ent", "d1hwxa1.ent-d1bdb__.ent", "d1hwxa1.ent-d1bgva1.ent", "d1hwxa1.ent-d1e7wa_.ent", "d1hwxa1.ent-d1eny__.ent", "d1hwxa1.ent-d1fds__.ent", "d1hwxa1.ent-d1g0oa_.ent", "d1hwxa1.ent-d1gcoa_.ent", "d1hwxa1.ent-d1h5qa_.ent", "d1hwxa1.ent-d1ja9a_.ent", "d1hwxa1.ent-d1n5da_.ent", "d1hwxa1.ent-d1oaa__.ent", "d1hwxa1.ent-d1qsga_.ent", "d1hwxa1.ent-d2ae2a_.ent", "d1hwxa2.ent-d1leha2.ent", "d1hwxa2.ent-d1lu9a2.ent", "d1hx0a1.ent-d1iv8a1.ent", "d1hx0a1.ent-d1j0ha2.ent", "d1hx0a1.ent-d1jae_1.ent", "d1hx0a1.ent-d1ji1a2.ent", "d1hx0a1.ent-d1ji2a2.ent", "d1hx0a1.ent-d1ktba1.ent", "d1hx0a1.ent-d1kwga1.ent", "d1hx0a1.ent-d1lwha1.ent", "d1hx0a1.ent-d1m7xa2.ent", "d1hx0a1.ent-d1qhoa3.ent", "d1hx0a1.ent-d1uok_1.ent", "d1hx0a1.ent-d7taa_1.ent", "d1hx1b_.ent-d1jnra1.ent", "d1hx1b_.ent-d1m7ka_.ent", "d1hx1b_.ent-d1qlaa1.ent", "d1hx1b_.ent-d1quua1.ent", "d1hx1b_.ent-d1quua2.ent", "d1hx1b_.ent-d2spca_.ent", "d1hx6a1.ent-d1hx6a2.ent", "d1hx6a1.ent-d1k5ja_.ent", "d1hx6a1.ent-d1m3ya1.ent", "d1hx6a1.ent-d1m3ya2.ent", "d1hx6a1.ent-d1pgs_1.ent", "d1hx6a1.ent-d1pgs_2.ent", "d1hx6a1.ent-d1phm_1.ent", "d1hx6a1.ent-d1phm_2.ent", "d1hx6a1.ent-d1ruxa1.ent", "d1hx6a1.ent-d1ruxa2.ent", "d1hx6a2.ent-d1k5ja_.ent", "d1hx6a2.ent-d1m3ya1.ent", "d1hx6a2.ent-d1m3ya2.ent", "d1hx6a2.ent-d1pgs_1.ent", "d1hx6a2.ent-d1pgs_2.ent", "d1hx6a2.ent-d1phm_1.ent", "d1hx6a2.ent-d1phm_2.ent", "d1hx6a2.ent-d1ruxa1.ent", "d1hx6a2.ent-d1ruxa2.ent", "d1hxha_.ent-d1bg6_2.ent", "d1hxha_.ent-d1c1da1.ent", "d1hxha_.ent-d1cf2o1.ent", "d1hxha_.ent-d1dlja2.ent", "d1hxha_.ent-d1dpga1.ent", "d1hxha_.ent-d1dssg1.ent", "d1hxha_.ent-d1e5qa1.ent", "d1hxha_.ent-d1f0ya2.ent", "d1hxha_.ent-d1gr0a1.ent", "d1hxha_.ent-d1hdoa_.ent", "d1hxha_.ent-d1hdr__.ent", "d1hxha_.ent-d1jaya_.ent", "d1hxha_.ent-d1lc0a1.ent", "d1hxha_.ent-d1lu9a1.ent", "d1hxha_.ent-d1qmga2.ent", "d1hxha_.ent-d2naca1.ent", "d1hxha_.ent-d2pgd_2.ent", "d1hxja_.ent-d1b9za2.ent", "d1hxja_.ent-d1bf2_3.ent", "d1hxja_.ent-d1cz1a_.ent", "d1hxja_.ent-d1e43a2.ent", "d1hxja_.ent-d1e4ia_.ent", "d1hxja_.ent-d1eh9a3.ent", "d1hxja_.ent-d1iexa1.ent", "d1hxja_.ent-d1j0ha3.ent", "d1hxja_.ent-d1ji1a3.ent", "d1hxja_.ent-d1kwga2.ent", "d1hxja_.ent-d1lwha2.ent", "d1hxja_.ent-d1pama4.ent", "d1hxja_.ent-d1qba_3.ent", "d1hxja_.ent-d1qhoa4.ent", "d1hxja_.ent-d1qvba_.ent", "d1hxja_.ent-d1uok_2.ent", "d1hxja_.ent-d7taa_2.ent", "d1hxma1.ent-d1a2yb_.ent", "d1hxma1.ent-d1akjd_.ent", "d1hxma1.ent-d1b88a_.ent", "d1hxma1.ent-d1bec_1.ent", "d1hxma1.ent-d1c5ch1.ent", "d1hxma1.ent-d1dlfl_.ent", "d1hxma1.ent-d1dqta_.ent", "d1hxma1.ent-d1fo0a_.ent", "d1hxma1.ent-d1gsma2.ent", "d1hxma1.ent-d1h5ba_.ent", "d1hxma1.ent-d1ktke1.ent", "d1hxma1.ent-d1kxvc_.ent", "d1hxma1.ent-d1neu__.ent", "d1hxma1.ent-d1nfdb1.ent", "d1hxma1.ent-d1qfoa_.ent", "d1hxma1.ent-d1tvda_.ent", "d1hxma1.ent-d2rhe__.ent", "d1hxmb1.ent-d1a2yb_.ent", "d1hxmb1.ent-d1akjd_.ent", "d1hxmb1.ent-d1b88a_.ent", "d1hxmb1.ent-d1bec_1.ent", "d1hxmb1.ent-d1bqhg_.ent", "d1hxmb1.ent-d1c5ch1.ent", "d1hxmb1.ent-d1dlfh_.ent", "d1hxmb1.ent-d1dlfl_.ent", "d1hxmb1.ent-d1dqta_.ent", "d1hxmb1.ent-d1fo0a_.ent", "d1hxmb1.ent-d1gsma2.ent", "d1hxmb1.ent-d1h5ba_.ent", "d1hxmb1.ent-d1hxma1.ent", "d1hxmb1.ent-d1ktke1.ent", "d1hxmb1.ent-d1kxvc_.ent", "d1hxmb1.ent-d1neu__.ent", "d1hxmb1.ent-d1nfdb1.ent", "d1hxmb1.ent-d1qfoa_.ent", "d1hxmb1.ent-d1tvda_.ent", "d1hxmb1.ent-d2rhe__.ent", "d1hxva_.ent-d1itxa2.ent", "d1hxva_.ent-d1j6ya_.ent", "d1hxva_.ent-d1jnda2.ent", "d1hxva_.ent-d1jvwa_.ent", "d1hxva_.ent-d1kt1a3.ent", "d1hxva_.ent-d1lg2a2.ent", "d1hxva_.ent-d1ll7a2.ent", "d1hxva_.ent-d1m5ya2.ent", "d1hxva_.ent-d1m5ya3.ent", "d1hxva_.ent-d1n1aa_.ent", "d1hxva_.ent-d1pbk__.ent", "d1hxva_.ent-d1pina2.ent", "d1hxva_.ent-d3eipa_.ent", "d1hxxa_.ent-d1i78a_.ent", "d1hxxa_.ent-d1k24a_.ent", "d1hxxa_.ent-d1kmoa_.ent", "d1hxxa_.ent-d1mm4a_.ent", "d1hxxa_.ent-d1qj8a_.ent", "d1hxxa_.ent-d1qjpa_.ent", "d1hxxa_.ent-d2mpra_.ent", "d1hxxa_.ent-d2por__.ent", "d1hxxa_.ent-d3prn__.ent", "d1hy0a_.ent-d1jswa_.ent", "d1hyea2.ent-d1hyha2.ent", "d1hyea2.ent-d1i0za2.ent", "d1hyea2.ent-d1ldg_2.ent", "d1hyea2.ent-d1ldna2.ent", "d1hyea2.ent-d1llda2.ent", "d1hyea2.ent-d1o6za2.ent", "d1hyea2.ent-d2cmd_2.ent", "d1hyea2.ent-d5mdha2.ent", "d1hyea2.ent-d7mdha2.ent", "d1hyha2.ent-d1i0za2.ent", "d1hyha2.ent-d1ldg_2.ent", "d1hyha2.ent-d1ldna2.ent", "d1hyha2.ent-d1llda2.ent", "d1hyha2.ent-d1o6za2.ent", "d1hyha2.ent-d2cmd_2.ent", "d1hyha2.ent-d5mdha2.ent", "d1hyha2.ent-d7mdha2.ent", "d1hyka_.ent-d1b9wa1.ent", "d1hyka_.ent-d1b9wa2.ent", "d1hyka_.ent-d1cixa_.ent", "d1hyka_.ent-d1g9pa_.ent", "d1hyka_.ent-d1h59b_.ent", "d1hyka_.ent-d1i2ua_.ent", "d1hyka_.ent-d1imt_2.ent", "d1hyka_.ent-d1jkza_.ent", "d1hyka_.ent-d1lpba2.ent", "d1hyoa1.ent-d1bb9__.ent", "d1hyoa1.ent-d1dj7b_.ent", "d1hyoa1.ent-d1fx7a3.ent", "d1hyoa1.ent-d1g3sa3.ent", "d1hyoa1.ent-d1gcqc_.ent", "d1hyoa1.ent-d1i07a_.ent", "d1hyoa1.ent-d1i1ja_.ent", "d1hyoa1.ent-d1ixda_.ent", "d1hyoa1.ent-d1jb0e_.ent", "d1hyoa1.ent-d1jj2p_.ent", "d1hyoa1.ent-d1jo8a_.ent", "d1hyoa1.ent-d1khia1.ent", "d1hyoa1.ent-d1kjwa1.ent", "d1hyoa1.ent-d1lpla_.ent", "d1hyoa1.ent-d1m1fa_.ent", "d1hyoa1.ent-d1m9sa2.ent", "d1hyoa1.ent-d1m9sa3.ent", "d1hyoa1.ent-d1pht__.ent", "d1hyoa1.ent-d1vie__.ent", "d1hyoa1.ent-d1ycsb2.ent", "d1hyoa1.ent-d3vub__.ent", "d1hyoa2.ent-d1i7oa1.ent", "d1hyoa2.ent-d1i7oa2.ent", "d1hyp__.ent-d1l6ha_.ent", "d1hyrc2.ent-d1iaka2.ent", "d1hyrc2.ent-d1jfma_.ent", "d1hyrc2.ent-d1k5na2.ent", "d1hyrc2.ent-d1kcgc_.ent", "d1hyrc2.ent-d1lqva_.ent", "d1hyrc2.ent-d1zaga2.ent", "d1hyrc2.ent-d3frua2.ent", "d1hyua4.ent-d1aba__.ent", "d1hyua4.ent-d1aqwa2.ent", "d1hyua4.ent-d1e6ba2.ent", "d1hyua4.ent-d1fhe_2.ent", "d1hyua4.ent-d1iloa_.ent", "d1hyua4.ent-d1k0ma2.ent", "d1hyua4.ent-d1k3ya2.ent", "d1hyua4.ent-d1qmha1.ent", "d1hz4a_.ent-d1e8xa1.ent", "d1hz4a_.ent-d1elka_.ent", "d1hz4a_.ent-d1h6ka1.ent", "d1hz4a_.ent-d1h6ka2.ent", "d1hz4a_.ent-d1h6ka3.ent", "d1hz4a_.ent-d1hf8a_.ent", "d1hz4a_.ent-d1hh8a_.ent", "d1hz4a_.ent-d1hs6a1.ent", "d1hz4a_.ent-d1ihga1.ent", "d1hz4a_.ent-d1iyga_.ent", "d1hz4a_.ent-d1keya_.ent", "d1hz4a_.ent-d1kpsb_.ent", "d1hz4a_.ent-d1kt1a1.ent", "d1hz4a_.ent-d1l5ja1.ent", "d1hz4a_.ent-d1ld8a_.ent", "d1hz4a_.ent-d1ldja2.ent", "d1hz4a_.ent-d1lrv__.ent", "d1hz4a_.ent-d1lsha1.ent", "d1hz4a_.ent-d1n4ka1.ent", "d1hz4a_.ent-d1pbv__.ent", "d1hz4a_.ent-d1qjba_.ent", "d1hz4a_.ent-d1qqea_.ent", "d1hz8a1.ent-d1hz8a2.ent", "d1hz8a1.ent-d1l3ya_.ent", "d1hz8a1.ent-d1tpg_1.ent", "d1hz8a2.ent-d1l3ya_.ent", "d1hz8a2.ent-d1tpg_1.ent", "d1hzda_.ent-d1k32a4.ent", "d1hzda_.ent-d1mj3a_.ent", "d1hzda_.ent-d1nzya_.ent", "d1hzda_.ent-d1o8ua_.ent", "d1hzda_.ent-d1tyfa_.ent", "d1hzia_.ent-d1i1rb_.ent", "d1hzia_.ent-d1jli__.ent", "d1hzia_.ent-d1lki__.ent", "d1hzia_.ent-d1lqsl_.ent", "d1hzia_.ent-d1m47a_.ent", "d1hzia_.ent-d1n1fa_.ent", "d1hzia_.ent-d2gmfa_.ent", "d1hzia_.ent-d2ilk__.ent", "d1hzma_.ent-d1rhs_1.ent", "d1hzpa1.ent-d1hzpa2.ent", "d1hzpa1.ent-d1kas_1.ent", "d1hzpa1.ent-d1m3ka1.ent", "d1hzpa1.ent-d1m3ka2.ent", "d1hzpa1.ent-d1mzja1.ent", "d1hzpa1.ent-d1mzja2.ent", "d1hzpa2.ent-d1kas_1.ent", "d1hzpa2.ent-d1m3ka1.ent", "d1hzpa2.ent-d1m3ka2.ent", "d1hzpa2.ent-d1mzja1.ent", "d1hzpa2.ent-d1mzja2.ent", "d1hzta_.ent-d1jkna_.ent", "d1hzta_.ent-d1k2ea_.ent", "d1hzta_.ent-d1ktga_.ent", "d1hzta_.ent-d1mut__.ent", "d1hzzc_.ent-d1icia_.ent", "d1hzzc_.ent-d1j8fa_.ent", "d1hzzc_.ent-d1jsca1.ent", "d1hzzc_.ent-d1ma3a_.ent", "d1hzzc_.ent-d1o97d2.ent", "d1hzzc_.ent-d1poxa1.ent", "d1hzzc_.ent-d1pvda1.ent", "d1hzzc_.ent-d1zpda1.ent", "d1i07a_.ent-d1i1ja_.ent", "d1i07a_.ent-d1jo8a_.ent", "d1i07a_.ent-d1jqqa_.ent", "d1i07a_.ent-d1k4us_.ent", "d1i07a_.ent-d1kjwa1.ent", "d1i07a_.ent-d1neb__.ent", "d1i07a_.ent-d1pht__.ent", "d1i07a_.ent-d1pwt__.ent", "d1i07a_.ent-d1qcfa1.ent", "d1i07a_.ent-d1ycsb2.ent", "d1i07a_.ent-d2hsp__.ent", "d1i0da_.ent-d1itua_.ent", "d1i0da_.ent-d1j5sa_.ent", "d1i0da_.ent-d1k6wa2.ent", "d1i0da_.ent-d1m7ja3.ent", "d1i0ra_.ent-d1nrga_.ent", "d1i0va_.ent-d1lnia_.ent", "d1i0za2.ent-d1ldg_2.ent", "d1i0za2.ent-d1ldna2.ent", "d1i0za2.ent-d1llda2.ent", "d1i0za2.ent-d1o6za2.ent", "d1i0za2.ent-d2cmd_2.ent", "d1i0za2.ent-d5mdha2.ent", "d1i0za2.ent-d7mdha2.ent", "d1i11a_.ent-d1k99a_.ent", "d1i11a_.ent-d1lwma_.ent", "d1i11a_.ent-d1qrva_.ent", "d1i11a_.ent-d2lefa_.ent", "d1i12a_.ent-d1iica2.ent", "d1i12a_.ent-d1iyka1.ent", "d1i12a_.ent-d1iyka2.ent", "d1i12a_.ent-d1kzfa_.ent", "d1i12a_.ent-d1lrza2.ent", "d1i12a_.ent-d1lrza3.ent", "d1i12a_.ent-d1m4ia_.ent", "d1i12a_.ent-d1qsma_.ent", "d1i12a_.ent-d1qsta_.ent", "d1i16__.ent-d1ihja_.ent", "d1i16__.ent-d1k32a1.ent", "d1i16__.ent-d1kwaa_.ent", "d1i16__.ent-d1lcya1.ent", "d1i16__.ent-d1m5za_.ent", "d1i16__.ent-d1mfga_.ent", "d1i16__.ent-d1qaua_.ent", "d1i16__.ent-d1qava_.ent", "d1i16__.ent-d1qlca_.ent", "d1i19a1.ent-d1azsa_.ent", "d1i19a1.ent-d1b3ta_.ent", "d1i19a1.ent-d1dj0a2.ent", "d1i19a1.ent-d1dqaa1.ent", "d1i19a1.ent-d1e8ga1.ent", "d1i19a1.ent-d1ekra_.ent", "d1i19a1.ent-d1eqoa_.ent", "d1i19a1.ent-d1f0xa1.ent", "d1i19a1.ent-d1f3va_.ent", "d1i19a1.ent-d1ftra1.ent", "d1i19a1.ent-d1ftra2.ent", "d1i19a1.ent-d1fx2a_.ent", "d1i19a1.ent-d1gpja3.ent", "d1i19a1.ent-d1h0hb_.ent", "d1i19a1.ent-d1h72c2.ent", "d1i19a1.ent-d1hbnb2.ent", "d1i19a1.ent-d1hbnc_.ent", "d1i19a1.ent-d1hlwa_.ent", "d1i19a1.ent-d1jnrb_.ent", "d1i19a1.ent-d1kvka2.ent", "d1i19a1.ent-d1lfwa2.ent", "d1i19a1.ent-d1qd1a1.ent", "d1i19a1.ent-d1qd1a2.ent", "d1i19a1.ent-d1regx_.ent", "d1i19a2.ent-d1jroa4.ent", "d1i19a2.ent-d1n62c2.ent", "d1i19a2.ent-d1uxy_1.ent", "d1i1ip_.ent-d1j7na1.ent", "d1i1ip_.ent-d1j7na2.ent", "d1i1ip_.ent-d1jaka2.ent", "d1i1ip_.ent-d1jk3a_.ent", "d1i1ip_.ent-d1k7ia2.ent", "d1i1ip_.ent-d1k9xa_.ent", "d1i1ip_.ent-d1kapp2.ent", "d1i1ip_.ent-d1keia_.ent", "d1i1ip_.ent-d1kufa_.ent", "d1i1ip_.ent-d1lml__.ent", "d1i1ip_.ent-d1qba_4.ent", "d1i1ip_.ent-d3btaa3.ent", "d1i1ja_.ent-d1bb9__.ent", "d1i1ja_.ent-d1dj7b_.ent", "d1i1ja_.ent-d1fx7a3.ent", "d1i1ja_.ent-d1g3sa3.ent", "d1i1ja_.ent-d1gcqc_.ent", "d1i1ja_.ent-d1i07a_.ent", "d1i1ja_.ent-d1ixda_.ent", "d1i1ja_.ent-d1jb0e_.ent", "d1i1ja_.ent-d1jj2p_.ent", "d1i1ja_.ent-d1jo8a_.ent", "d1i1ja_.ent-d1jqqa_.ent", "d1i1ja_.ent-d1k4us_.ent", "d1i1ja_.ent-d1khia1.ent", "d1i1ja_.ent-d1kjwa1.ent", "d1i1ja_.ent-d1lpla_.ent", "d1i1ja_.ent-d1m9sa2.ent", "d1i1ja_.ent-d1m9sa3.ent", "d1i1ja_.ent-d1neb__.ent", "d1i1ja_.ent-d1pht__.ent", "d1i1ja_.ent-d1pwt__.ent", "d1i1ja_.ent-d1qcfa1.ent", "d1i1ja_.ent-d1vie__.ent", "d1i1ja_.ent-d1ycsb2.ent", "d1i1ja_.ent-d2hsp__.ent", "d1i1ja_.ent-d3vub__.ent", "d1i1na_.ent-d1jg1a_.ent", "d1i1ra1.ent-d1cd9b2.ent", "d1i1ra1.ent-d1f6fb1.ent", "d1i1ra1.ent-d1f6fb2.ent", "d1i1ra1.ent-d1fyhb1.ent", "d1i1ra1.ent-d1lqsr1.ent", "d1i1rb_.ent-d1jli__.ent", "d1i1rb_.ent-d1lki__.ent", "d1i1rb_.ent-d1lqsl_.ent", "d1i1rb_.ent-d1m47a_.ent", "d1i1rb_.ent-d1n1fa_.ent", "d1i1rb_.ent-d2gmfa_.ent", "d1i1rb_.ent-d2ilk__.ent", "d1i25a_.ent-d1i26a_.ent", "d1i25a_.ent-d1koza_.ent", "d1i25a_.ent-d1kqha_.ent", "d1i25a_.ent-d1lqra_.ent", "d1i25a_.ent-d1lupa_.ent", "d1i25a_.ent-d1nixa_.ent", "d1i25a_.ent-d1niya_.ent", "d1i25a_.ent-d1qk6a_.ent", "d1i25a_.ent-d1qk7a_.ent", "d1i25a_.ent-d1vtx__.ent", "d1i26a_.ent-d1koza_.ent", "d1i26a_.ent-d1kqha_.ent", "d1i26a_.ent-d1lqra_.ent", "d1i26a_.ent-d1lupa_.ent", "d1i26a_.ent-d1nixa_.ent", "d1i26a_.ent-d1niya_.ent", "d1i26a_.ent-d1qk6a_.ent", "d1i26a_.ent-d1qk7a_.ent", "d1i26a_.ent-d1vtx__.ent", "d1i2oa_.ent-d1jcla_.ent", "d1i2oa_.ent-d1jcxa_.ent", "d1i2oa_.ent-d1l6wa_.ent", "d1i2oa_.ent-d1mzha_.ent", "d1i2oa_.ent-d1nal1_.ent", "d1i2oa_.ent-d1o0ya_.ent", "d1i2oa_.ent-d1qfea_.ent", "d1i2ta_.ent-d1ifwa_.ent", "d1i2ua_.ent-d1ica__.ent", "d1i2ua_.ent-d1imt_2.ent", "d1i2ua_.ent-d1jkza_.ent", "d1i2ua_.ent-d1jxca_.ent", "d1i2ua_.ent-d1myn__.ent", "d1i2ua_.ent-d1npia_.ent", "d1i2ua_.ent-d1nrb__.ent", "d1i2ua_.ent-d1qkya_.ent", "d1i2ua_.ent-d1sco__.ent", "d1i2ua_.ent-d1scy__.ent", "d1i2ua_.ent-d1sis__.ent", "d1i2ua_.ent-d1tsk__.ent", "d1i2ua_.ent-d2sn3__.ent", "d1i31a_.ent-d1klfb1.ent", "d1i31a_.ent-d1klfb2.ent", "d1i31a_.ent-d1m2oa2.ent", "d1i31a_.ent-d1m2vb2.ent", "d1i31a_.ent-d1mnna_.ent", "d1i31a_.ent-d1nbca_.ent", "d1i31a_.ent-d1pdkb_.ent", "d1i31a_.ent-d1qba_2.ent", "d1i31a_.ent-d1tf4a2.ent", "d1i31a_.ent-d1ycsa_.ent", "d1i36a1.ent-d1ks9a1.ent", "d1i36a1.ent-d1m66a1.ent", "d1i36a1.ent-d1pgja1.ent", "d1i36a1.ent-d1qmga1.ent", "d1i36a1.ent-d2pgd_1.ent", "d1i39a_.ent-d1ih7a1.ent", "d1i39a_.ent-d1io2a_.ent", "d1i39a_.ent-d1j54a_.ent", "d1i39a_.ent-d1jl1a_.ent", "d1i39a_.ent-d1kcfa2.ent", "d1i39a_.ent-d1kfsa1.ent", "d1i39a_.ent-d1musa_.ent", "d1i39a_.ent-d1qtma1.ent", "d1i39a_.ent-d1t7pa1.ent", "d1i39a_.ent-d1tgoa1.ent", "d1i39a_.ent-d1vrta1.ent", "d1i39a_.ent-d1xwl_1.ent", "d1i3oe_.ent-d1jd5a_.ent", "d1i3oe_.ent-d1qbha_.ent", "d1i40a_.ent-d1b3qa2.ent", "d1i40a_.ent-d1e1oa1.ent", "d1i40a_.ent-d1eova1.ent", "d1i40a_.ent-d1fgua2.ent", "d1i40a_.ent-d1fjgl_.ent", "d1i40a_.ent-d1fl0a_.ent", "d1i40a_.ent-d1i50h_.ent", "d1i40a_.ent-d1iyjb5.ent", "d1i40a_.ent-d1jb3a_.ent", "d1i40a_.ent-d1jb7a1.ent", "d1i40a_.ent-d1jb7a2.ent", "d1i40a_.ent-d1jb7a3.ent", "d1i40a_.ent-d1k28a1.ent", "d1i40a_.ent-d1l1oc_.ent", "d1i40a_.ent-d1quqa_.ent", "d1i40a_.ent-d1sty__.ent", "d1i40a_.ent-d2prd__.ent", "d1i40a_.ent-d3seb_1.ent", "d1i42a_.ent-d1bmlc3.ent", "d1i42a_.ent-d1c9fa_.ent", "d1i42a_.ent-d1fm0d_.ent", "d1i42a_.ent-d1h4ra3.ent", "d1i42a_.ent-d1h8ca_.ent", "d1i42a_.ent-d1ip9a_.ent", "d1i42a_.ent-d1j8ca_.ent", "d1i42a_.ent-d1k8rb_.ent", "d1i42a_.ent-d1l7ya_.ent", "d1i42a_.ent-d1lfda_.ent", "d1i42a_.ent-d1lm8b_.ent", "d1i42a_.ent-d1m94a_.ent", "d1i42a_.ent-d1rlf__.ent", "d1i4na_.ent-d1jvna1.ent", "d1i4na_.ent-d1km3a_.ent", "d1i4na_.ent-d1kv8a_.ent", "d1i4na_.ent-d1nsj__.ent", "d1i4na_.ent-d1pii_1.ent", "d1i4na_.ent-d1pii_2.ent", "d1i4na_.ent-d1qopa_.ent", "d1i4na_.ent-d1rpxa_.ent", "d1i4na_.ent-d1thfd_.ent", "d1i4ua_.ent-d1ifc__.ent", "d1i4ua_.ent-d1jv4a_.ent", "d1i4ua_.ent-d1koia_.ent", "d1i4ua_.ent-d1kqwa_.ent", "d1i4ua_.ent-d1lf7a_.ent", "d1i4ua_.ent-d1o1va_.ent", "d1i4ua_.ent-d1qfta_.ent", "d1i4ua_.ent-d1qqsa_.ent", "d1i4wa_.ent-d1booa_.ent", "d1i4wa_.ent-d1eg2a_.ent", "d1i4wa_.ent-d1f3la_.ent", "d1i4wa_.ent-d1fp1d2.ent", "d1i4wa_.ent-d1fp2a2.ent", "d1i4wa_.ent-d1g60a_.ent", "d1i4wa_.ent-d1hnna_.ent", "d1i4wa_.ent-d1i1na_.ent", "d1i4wa_.ent-d1i9ga_.ent", "d1i4wa_.ent-d1inla_.ent", "d1i4wa_.ent-d1iy9a_.ent", "d1i4wa_.ent-d1jg1a_.ent", "d1i4wa_.ent-d1jqea_.ent", "d1i4wa_.ent-d1jsxa_.ent", "d1i4wa_.ent-d1khha_.ent", "d1i4wa_.ent-d1kywa2.ent", "d1i4wa_.ent-d1mjfa_.ent", "d1i4wa_.ent-d1qama_.ent", "d1i4wa_.ent-d1vid__.ent", "d1i4wa_.ent-d1xvaa_.ent", "d1i4wa_.ent-d1yub__.ent", "d1i4wa_.ent-d2dpma_.ent", "d1i4wa_.ent-d3mag__.ent", "d1i50a_.ent-d1i50b_.ent", "d1i50a_.ent-d1iw7c_.ent", "d1i50a_.ent-d1iw7d_.ent", "d1i50b_.ent-d1iw7c_.ent", "d1i50b_.ent-d1iw7d_.ent", "d1i50c1.ent-d1i50k_.ent", "d1i50c1.ent-d1iw7a1.ent", "d1i50c1.ent-d1xxaa_.ent", "d1i50c2.ent-d1iw7a2.ent", "d1i50h_.ent-d1b3qa2.ent", "d1i50h_.ent-d1ewia_.ent", "d1i50h_.ent-d1fgua1.ent", "d1i50h_.ent-d1fgua2.ent", "d1i50h_.ent-d1fjgl_.ent", "d1i50h_.ent-d1iyjb3.ent", "d1i50h_.ent-d1jb3a_.ent", "d1i50h_.ent-d1jb7a2.ent", "d1i50h_.ent-d1jjcb3.ent", "d1i50h_.ent-d1k28a1.ent", "d1i50h_.ent-d1quqa_.ent", "d1i50h_.ent-d1quqb_.ent", "d1i50h_.ent-d3seb_1.ent", "d1i50i1.ent-d1i50i2.ent", "d1i50i1.ent-d1i50l_.ent", "d1i50i1.ent-d1jj22_.ent", "d1i50i1.ent-d1jj2y_.ent", "d1i50i1.ent-d1jj2z_.ent", "d1i50i1.ent-d1lkoa2.ent", "d1i50i1.ent-d1m2oa5.ent", "d1i50i1.ent-d1ocrf_.ent", "d1i50i1.ent-d1pft__.ent", "d1i50i1.ent-d1qyp__.ent", "d1i50i1.ent-d1rb9__.ent", "d1i50i1.ent-d1tfi__.ent", "d1i50i1.ent-d1yua_1.ent", "d1i50i1.ent-d1yua_2.ent", "d1i50i1.ent-d1zaka2.ent", "d1i50i1.ent-d1zin_2.ent", "d1i50i2.ent-d1i50l_.ent", "d1i50i2.ent-d1jj22_.ent", "d1i50i2.ent-d1jj2y_.ent", "d1i50i2.ent-d1jj2z_.ent", "d1i50i2.ent-d1lkoa2.ent", "d1i50i2.ent-d1m2oa5.ent", "d1i50i2.ent-d1ocrf_.ent", "d1i50i2.ent-d1pft__.ent", "d1i50i2.ent-d1qyp__.ent", "d1i50i2.ent-d1rb9__.ent", "d1i50i2.ent-d1tfi__.ent", "d1i50i2.ent-d1yua_1.ent", "d1i50i2.ent-d1yua_2.ent", "d1i50i2.ent-d1zaka2.ent", "d1i50i2.ent-d1zin_2.ent", "d1i50k_.ent-d1iw7a1.ent", "d1i50k_.ent-d1xxaa_.ent", "d1i50l_.ent-d1jj22_.ent", "d1i50l_.ent-d1jj2y_.ent", "d1i50l_.ent-d1jj2z_.ent", "d1i50l_.ent-d1lkoa2.ent", "d1i50l_.ent-d1m2oa5.ent", "d1i50l_.ent-d1ocrf_.ent", "d1i50l_.ent-d1pft__.ent", "d1i50l_.ent-d1rb9__.ent", "d1i50l_.ent-d1tfi__.ent", "d1i50l_.ent-d1yua_1.ent", "d1i50l_.ent-d1yua_2.ent", "d1i50l_.ent-d1zaka2.ent", "d1i50l_.ent-d1zin_2.ent", "d1i52a_.ent-d1jv1a_.ent", "d1i52a_.ent-d1k4va_.ent", "d1i52a_.ent-d1kwsa_.ent", "d1i52a_.ent-d1ll2a_.ent", "d1i52a_.ent-d1lzja_.ent", "d1i52a_.ent-d1nf5b_.ent", "d1i52a_.ent-d1qg8a_.ent", "d1i58a_.ent-d1id0a_.ent", "d1i58a_.ent-d1jm6a2.ent", "d1i58a_.ent-d1kija2.ent", "d1i58a_.ent-d1l0oa_.ent", "d1i58a_.ent-d1mu5a3.ent", "d1i5ea_.ent-d1l1qa_.ent", "d1i5ea_.ent-d1lh0a_.ent", "d1i5ea_.ent-d1nula_.ent", "d1i5ea_.ent-d1qb7a_.ent", "d1i5ea_.ent-d1tc1a_.ent", "d1i5ga_.ent-d1a8l_1.ent", "d1i5ga_.ent-d1a8l_2.ent", "d1i5ga_.ent-d1a8y_1.ent", "d1i5ga_.ent-d1a8y_2.ent", "d1i5ga_.ent-d1a8y_3.ent", "d1i5ga_.ent-d1aba__.ent", "d1i5ga_.ent-d1aqwa2.ent", "d1i5ga_.ent-d1bed_2.ent", "d1i5ga_.ent-d1bjx__.ent", "d1i5ga_.ent-d1e6ba2.ent", "d1i5ga_.ent-d1ep7a_.ent", "d1i5ga_.ent-d1erv__.ent", "d1i5ga_.ent-d1f9ma_.ent", "d1i5ga_.ent-d1fb6a_.ent", "d1i5ga_.ent-d1fhe_2.ent", "d1i5ga_.ent-d1fvka2.ent", "d1i5ga_.ent-d1g7ea_.ent", "d1i5ga_.ent-d1gh2a_.ent", "d1i5ga_.ent-d1hyua4.ent", "d1i5ga_.ent-d1iloa_.ent", "d1i5ga_.ent-d1k0ma2.ent", "d1i5ga_.ent-d1k3ya2.ent", "d1i5ga_.ent-d1knga_.ent", "d1i5ga_.ent-d1kte__.ent", "d1i5ga_.ent-d1m2da_.ent", "d1i5ga_.ent-d1mek__.ent", "d1i5ga_.ent-d1qmha1.ent", "d1i5ga_.ent-d1quwa_.ent", "d1i5ga_.ent-d1thx__.ent", "d1i5ga_.ent-d2trxa_.ent", "d1i5hw_.ent-d1jmqa_.ent", "d1i5hw_.ent-d1o6wa2.ent", "d1i5hw_.ent-d1pina1.ent", "d1i5pa1.ent-d1ciy_1.ent", "d1i5pa1.ent-d1cx1a_.ent", "d1i5pa1.ent-d1czsa_.ent", "d1i5pa1.ent-d1d7pm_.ent", "d1i5pa1.ent-d1dlc_1.ent", "d1i5pa1.ent-d1eut_2.ent", "d1i5pa1.ent-d1gmma_.ent", "d1i5pa1.ent-d1gnya_.ent", "d1i5pa1.ent-d1gu3a_.ent", "d1i5pa1.ent-d1guia_.ent", "d1i5pa1.ent-d1h6ya_.ent", "d1i5pa1.ent-d1jhja_.ent", "d1i5pa1.ent-d1ji6a1.ent", "d1i5pa1.ent-d1ju3a1.ent", "d1i5pa1.ent-d1jz8a3.ent", "d1i5pa1.ent-d1k12a_.ent", "d1i5pa1.ent-d1k3ia2.ent", "d1i5pa1.ent-d1kexa_.ent", "d1i5pa1.ent-d1kgya_.ent", "d1i5pa1.ent-d1l7la_.ent", "d1i5pa1.ent-d1lnsa2.ent", "d1i5pa1.ent-d1xnaa_.ent", "d1i5pa2.ent-d1ji6a2.ent", "d1i5pa2.ent-d1vmoa_.ent", "d1i5pa3.ent-d1ji6a3.ent", "d1i6aa_.ent-d1ii5a_.ent", "d1i6aa_.ent-d1ixh__.ent", "d1i6aa_.ent-d1jeta_.ent", "d1i6aa_.ent-d1kwha_.ent", "d1i6aa_.ent-d1lst__.ent", "d1i6aa_.ent-d1m5ea_.ent", "d1i6aa_.ent-d1mrp__.ent", "d1i6aa_.ent-d1nh8a1.ent", "d1i6aa_.ent-d1pda_1.ent", "d1i6aa_.ent-d1pot__.ent", "d1i6aa_.ent-d1sbp__.ent", "d1i6aa_.ent-d1wdna_.ent", "d1i6aa_.ent-d3mbp__.ent", "d1i6aa_.ent-d3thia_.ent", "d1i6ia_.ent-d1bg2__.ent", "d1i6ia_.ent-d1c4oa1.ent", "d1i6ia_.ent-d1e2ka_.ent", "d1i6ia_.ent-d1f9va_.ent", "d1i6ia_.ent-d1g8pa_.ent", "d1i6ia_.ent-d1ksfx3.ent", "d1i6ia_.ent-d1n0ua2.ent", "d1i6ia_.ent-d1pjr_1.ent", "d1i6ia_.ent-d1pjr_2.ent", "d1i6ia_.ent-d1uaaa1.ent", "d1i6ia_.ent-d1uaaa2.ent", "d1i6pa_.ent-d1tfr_2.ent", "d1i6pa_.ent-d2rsla_.ent", "d1i71a_.ent-d1kdu__.ent", "d1i71a_.ent-d1ki0a2.ent", "d1i71a_.ent-d1ki0a3.ent", "d1i71a_.ent-d1l6ja3.ent", "d1i71a_.ent-d1l6ja4.ent", "d1i71a_.ent-d1l6ja5.ent", "d1i71a_.ent-d1pmla_.ent", "d1i71a_.ent-d2hpqp_.ent", "d1i71a_.ent-d5hpga_.ent", "d1i78a_.ent-d1k24a_.ent", "d1i78a_.ent-d1kmoa_.ent", "d1i78a_.ent-d1mm4a_.ent", "d1i78a_.ent-d1qj8a_.ent", "d1i78a_.ent-d1qjpa_.ent", "d1i78a_.ent-d2mpra_.ent", "d1i78a_.ent-d2por__.ent", "d1i7ha_.ent-d1jq4a_.ent", "d1i7ha_.ent-d1jroa2.ent", "d1i7ha_.ent-d1kf6b2.ent", "d1i7ha_.ent-d1krha3.ent", "d1i7ha_.ent-d1l5pa_.ent", "d1i7ha_.ent-d1n62a2.ent", "d1i7ha_.ent-d1nekb2.ent", "d1i7ha_.ent-d1put__.ent", "d1i7ha_.ent-d1qlab2.ent", "d1i7ha_.ent-d2pia_3.ent", "d1i7ka_.ent-d1j7da_.ent", "d1i7ka_.ent-d1jata_.ent", "d1i7ka_.ent-d1jatb_.ent", "d1i7ka_.ent-d1kppa_.ent", "d1i7ka_.ent-d1qcqa_.ent", "d1i7ka_.ent-d2aak__.ent", "d1i7ka_.ent-d2ucz__.ent", "d1i7oa1.ent-d1i7oa2.ent", "d1i7pa1.ent-d1i8da1.ent", "d1i7pa1.ent-d1i8da2.ent", "d1i7pa1.ent-d1ja1a1.ent", "d1i7pa1.ent-d1jb9a1.ent", "d1i7pa1.ent-d1jj2b_.ent", "d1i7pa1.ent-d1kk1a1.ent", "d1i7pa1.ent-d1krha1.ent", "d1i7pa1.ent-d1kzla1.ent", "d1i7pa1.ent-d1kzla2.ent", "d1i7pa1.ent-d1n08a_.ent", "d1i7pa1.ent-d1n0ua1.ent", "d1i7pa1.ent-d1qfja1.ent", "d1i7pa1.ent-d1que_1.ent", "d1i7pa1.ent-d2cnd_1.ent", "d1i7pa1.ent-d2pia_1.ent", "d1i7pa2.ent-d1ja1a3.ent", "d1i7pa2.ent-d1jb9a2.ent", "d1i7pa2.ent-d1krha2.ent", "d1i7pa2.ent-d1qfja2.ent", "d1i7pa2.ent-d1que_2.ent", "d1i7pa2.ent-d2cnd_2.ent", "d1i7pa2.ent-d2pia_2.ent", "d1i7qb_.ent-d1k9vf_.ent", "d1i7qb_.ent-d1ka9h_.ent", "d1i7qb_.ent-d1kwga3.ent", "d1i7qb_.ent-d1l9xa_.ent", "d1i7qb_.ent-d1qdlb_.ent", "d1i8aa_.ent-d1bf2_1.ent", "d1i8aa_.ent-d1dqia_.ent", "d1i8aa_.ent-d1eaja_.ent", "d1i8aa_.ent-d1ej8a_.ent", "d1i8aa_.ent-d1g4ma1.ent", "d1i8aa_.ent-d1g4ma2.ent", "d1i8aa_.ent-d1grwa_.ent", "d1i8aa_.ent-d1j0ha1.ent", "d1i8aa_.ent-d1jmxa4.ent", "d1i8aa_.ent-d1kgce2.ent", "d1i8aa_.ent-d1kmta_.ent", "d1i8aa_.ent-d1kyfa1.ent", "d1i8aa_.ent-d1l9na1.ent", "d1i8aa_.ent-d1lmia_.ent", "d1i8aa_.ent-d1m1xa1.ent", "d1i8aa_.ent-d1m1xa2.ent", "d1i8aa_.ent-d1m1xb1.ent", "d1i8aa_.ent-d1nepa_.ent", "d1i8aa_.ent-d1o75a1.ent", "d1i8aa_.ent-d1soxa1.ent", "d1i8aa_.ent-d1xsoa_.ent", "d1i8da1.ent-d1i8da2.ent", "d1i8da1.ent-d1ja1a1.ent", "d1i8da1.ent-d1jb9a1.ent", "d1i8da1.ent-d1krha1.ent", "d1i8da1.ent-d1kzla1.ent", "d1i8da1.ent-d1kzla2.ent", "d1i8da1.ent-d1qfja1.ent", "d1i8da1.ent-d1que_1.ent", "d1i8da1.ent-d2cnd_1.ent", "d1i8da1.ent-d2pia_1.ent", "d1i8da2.ent-d1ja1a1.ent", "d1i8da2.ent-d1jb9a1.ent", "d1i8da2.ent-d1krha1.ent", "d1i8da2.ent-d1kzla1.ent", "d1i8da2.ent-d1kzla2.ent", "d1i8da2.ent-d1qfja1.ent", "d1i8da2.ent-d1que_1.ent", "d1i8da2.ent-d2cnd_1.ent", "d1i8da2.ent-d2pia_1.ent", "d1i8fa_.ent-d1kq1a_.ent", "d1i8fa_.ent-d1ljoa_.ent", "d1i8fa_.ent-d1mgqa_.ent", "d1i8fa_.ent-d1mxma1.ent", "d1i8fa_.ent-d1n9ra_.ent", "d1i8ta1.ent-d1lqta2.ent", "d1i8ta1.ent-d1o94a3.ent", "d1i8ta2.ent-d1ju2a2.ent", "d1i8ta2.ent-d1k0ia2.ent", "d1i8ta2.ent-d1kdga2.ent", "d1i8ta2.ent-d1l9ea2.ent", "d1i8ta2.ent-d1mxta2.ent", "d1i9ga_.ent-d1fp1d2.ent", "d1i9ga_.ent-d1fp2a2.ent", "d1i9ga_.ent-d1g60a_.ent", "d1i9ga_.ent-d1hnna_.ent", "d1i9ga_.ent-d1i1na_.ent", "d1i9ga_.ent-d1jg1a_.ent", "d1i9ga_.ent-d1kywa2.ent", "d1i9ga_.ent-d1qama_.ent", "d1i9ga_.ent-d1yub__.ent", "d1i9ga_.ent-d2dpma_.ent", "d1i9sa_.ent-d1ikza_.ent", "d1i9sa_.ent-d1jlna_.ent", "d1i9sa_.ent-d1lara1.ent", "d1i9sa_.ent-d1lara2.ent", "d1i9sa_.ent-d1lyva_.ent", "d1i9sa_.ent-d1mkp__.ent", "d1i9sa_.ent-d1vhra_.ent", "d1i9sa_.ent-d1yfoa_.ent", "d1i9sa_.ent-d2shpa1.ent", "d1i9za_.ent-d2dnja_.ent", "d1ia6a_.ent-d1ks8a_.ent", "d1ia6a_.ent-d1kwfa_.ent", "d1ia6a_.ent-d1lf6a1.ent", "d1ia9a_.ent-d1iepa_.ent", "d1ia9a_.ent-d1j7la_.ent", "d1ia9a_.ent-d1jpaa_.ent", "d1ia9a_.ent-d1lufa_.ent", "d1iaka2.ent-d1jfma_.ent", "d1iaka2.ent-d1k5na2.ent", "d1iaka2.ent-d1kcgc_.ent", "d1iaka2.ent-d1lqva_.ent", "d1iaka2.ent-d1zaga2.ent", "d1iaka2.ent-d3frua2.ent", "d1iala_.ent-d1jdha_.ent", "d1iala_.ent-d1kx9a_.ent", "d1iala_.ent-d1lrv__.ent", "d1iala_.ent-d1n4ka1.ent", "d1iata_.ent-d1m3sa_.ent", "d1iata_.ent-d1moq__.ent", "d1ib8a1.ent-d1kq1a_.ent", "d1ib8a1.ent-d1mgqa_.ent", "d1ib8a1.ent-d1mxma1.ent", "d1ib8a2.ent-d1iw5a_.ent", "d1ib8a2.ent-d1k0ra2.ent", "d1ib8a2.ent-d1k0ra3.ent", "d1ib8a2.ent-d1mkya3.ent", "d1ib8a2.ent-d3proc1.ent", "d1ib8a2.ent-d3proc2.ent", "d1iba__.ent-d1jvaa2.ent", "d1iba__.ent-d1jvaa3.ent", "d1ibia2.ent-d1iml_2.ent", "d1ibia2.ent-d1jj2t_.ent", "d1ibia2.ent-d1k3xa3.ent", "d1ibia2.ent-d1kb2a_.ent", "d1ibia2.ent-d1l1za3.ent", "d1ibia2.ent-d1lata_.ent", "d1ibia2.ent-d1lv3a_.ent", "d1ibia2.ent-d1zfo__.ent", "d1ibia2.ent-d2nllb_.ent", "d1ibia2.ent-d3gata_.ent", "d1ibia2.ent-d7gata_.ent", "d1ibya_.ent-d1ikop_.ent", "d1ibya_.ent-d1jzga_.ent", "d1ibya_.ent-d1kcw_1.ent", "d1ibya_.ent-d1kcw_2.ent", "d1ibya_.ent-d1kv7a1.ent", "d1ibya_.ent-d1kv7a2.ent", "d1ibya_.ent-d1kv7a3.ent", "d1ibya_.ent-d1kzqa1.ent", "d1ibya_.ent-d1l9qa1.ent", "d1ibya_.ent-d1l9qa2.ent", "d1ibya_.ent-d2cbp__.ent", "d1ibya_.ent-d2cuaa_.ent", "d1ic6a_.ent-d1thm__.ent", "d1ic8a2.ent-d1lmb3_.ent", "d1ic8a2.ent-d1ner__.ent", "d1ic8a2.ent-d1r69__.ent", "d1ic8a2.ent-d1uxc__.ent", "d1ic8a2.ent-d1uxd__.ent", "d1ic8a2.ent-d1vpwa1.ent", "d1ic8a2.ent-d2cro__.ent", "d1ica__.ent-d1jkza_.ent", "d1ica__.ent-d1jxca_.ent", "d1ica__.ent-d1myn__.ent", "d1ica__.ent-d1npia_.ent", "d1ica__.ent-d1nrb__.ent", "d1ica__.ent-d1qkya_.ent", "d1ica__.ent-d1sco__.ent", "d1ica__.ent-d1scy__.ent", "d1ica__.ent-d1sis__.ent", "d1ica__.ent-d1tsk__.ent", "d1ica__.ent-d2sn3__.ent", "d1icha_.ent-d1n3ka_.ent", "d1icha_.ent-d1ngr__.ent", "d1icha_.ent-d3crd__.ent", "d1icha_.ent-d3ygsp_.ent", "d1icia_.ent-d1j8fa_.ent", "d1icia_.ent-d1jsca1.ent", "d1icia_.ent-d1ma3a_.ent", "d1icia_.ent-d1o97d2.ent", "d1icia_.ent-d1poxa1.ent", "d1icia_.ent-d1pvda1.ent", "d1icia_.ent-d1zpda1.ent", "d1icpa_.ent-d1kbia1.ent", "d1icpa_.ent-d1llwa2.ent", "d1icpa_.ent-d1o94a1.ent", "d1icpa_.ent-d1oyb__.ent", "d1icpa_.ent-d2dora_.ent", "d1icra_.ent-d1nox__.ent", "d1icra_.ent-d1vfra_.ent", "d1icxa_.ent-d1jssa_.ent", "d1icxa_.ent-d1kcma_.ent", "d1icxa_.ent-d1ln1a_.ent", "d1id0a_.ent-d1jm6a2.ent", "d1id0a_.ent-d1kija2.ent", "d1id0a_.ent-d1l0oa_.ent", "d1id0a_.ent-d1mu5a3.ent", "d1idaa_.ent-d1j71a_.ent", "d1idaa_.ent-d1kzka_.ent", "d1idaa_.ent-d1lf2a_.ent", "d1idaa_.ent-d1mpp__.ent", "d1idaa_.ent-d1nsoa_.ent", "d1idaa_.ent-d2apr__.ent", "d1idaa_.ent-d2rspa_.ent", "d1idaa_.ent-d3psg__.ent", "d1idaa_.ent-d4fiv__.ent", "d1ie9a_.ent-d1ilga_.ent", "d1ie9a_.ent-d1kv6a_.ent", "d1ie9a_.ent-d1lv2a_.ent", "d1ie9a_.ent-d1mzna_.ent", "d1ie9a_.ent-d1n83a_.ent", "d1ie9a_.ent-d2prga_.ent", "d1iega_.ent-d1o6ea_.ent", "d1iepa_.ent-d1jpaa_.ent", "d1iexa1.ent-d1d3ga_.ent", "d1iexa1.ent-d1edg__.ent", "d1iexa1.ent-d1gvoa_.ent", "d1iexa1.ent-d1gw1a_.ent", "d1iexa1.ent-d1itua_.ent", "d1iexa1.ent-d1j0ha3.ent", "d1iexa1.ent-d1k4ga_.ent", "d1iexa1.ent-d1kbla1.ent", "d1iexa1.ent-d1m7ja3.ent", "d1iexa1.ent-d1muwa_.ent", "d1iexa1.ent-d7taa_2.ent", "d1iexa2.ent-d1cex__.ent", "d1iexa2.ent-d1cf9a1.ent", "d1iexa2.ent-d1e5da1.ent", "d1iexa2.ent-d1es9a_.ent", "d1iexa2.ent-d1euca2.ent", "d1iexa2.ent-d1f2va_.ent", "d1iexa2.ent-d1f4pa_.ent", "d1iexa2.ent-d1f8ya_.ent", "d1iexa2.ent-d1fuea_.ent", "d1iexa2.ent-d1g66a_.ent", "d1iexa2.ent-d1h05a_.ent", "d1iexa2.ent-d1kwga3.ent", "d1iexa2.ent-d1l7da2.ent", "d1iexa2.ent-d1qo0d_.ent", "d1iexa2.ent-d2naca2.ent", "d1iexa2.ent-d7reqb2.ent", "d1ifc__.ent-d1jv4a_.ent", "d1ifc__.ent-d1koia_.ent", "d1ifc__.ent-d1kqwa_.ent", "d1ifc__.ent-d1lf7a_.ent", "d1ifc__.ent-d1o1va_.ent", "d1ifc__.ent-d1qfta_.ent", "d1ifc__.ent-d1qqsa_.ent", "d1ift__.ent-d1mrj__.ent", "d1ift__.ent-d1qi7a_.ent", "d1ifya_.ent-d1oaia_.ent", "d1ig0a1.ent-d1jr7a_.ent", "d1ig0a1.ent-d1juha_.ent", "d1ig0a1.ent-d1lrha_.ent", "d1ig0a1.ent-d1m4oa_.ent", "d1ig0a1.ent-d1pmi__.ent", "d1ig0a1.ent-d1wapa_.ent", "d1ig0a1.ent-d2arca_.ent", "d1ig6a_.ent-d1bjaa_.ent", "d1ig6a_.ent-d1d5va_.ent", "d1ig6a_.ent-d1f1za1.ent", "d1ig6a_.ent-d1fnna1.ent", "d1ig6a_.ent-d1fp2a1.ent", "d1ig6a_.ent-d1igna2.ent", "d1ig6a_.ent-d1jhga_.ent", "d1ig6a_.ent-d1ka8a_.ent", "d1ig6a_.ent-d1kkxa_.ent", "d1ig6a_.ent-d1opc__.ent", "d1ig6a_.ent-d1repc2.ent", "d1ig6a_.ent-d1smta_.ent", "d1ig6a_.ent-d2ezl__.ent", "d1ig6a_.ent-d2foka3.ent", "d1ig7a_.ent-d1e3oc1.ent", "d1ig8a1.ent-d1ig8a2.ent", "d1ig8a1.ent-d1j6za2.ent", "d1ig8a1.ent-d1jcfa1.ent", "d1ig8a1.ent-d1k8ka1.ent", "d1ig8a1.ent-d1mwma1.ent", "d1ig8a1.ent-d1mwma2.ent", "d1ig8a1.ent-d1nbwa2.ent", "d1ig8a1.ent-d1nbwa3.ent", "d1ig8a2.ent-d1j6za2.ent", "d1ig8a2.ent-d1jcfa1.ent", "d1ig8a2.ent-d1k8ka1.ent", "d1ig8a2.ent-d1mwma1.ent", "d1ig8a2.ent-d1mwma2.ent", "d1ig8a2.ent-d1nbwa2.ent", "d1ig8a2.ent-d1nbwa3.ent", "d1igna1.ent-d1b72a_.ent", "d1igna1.ent-d1b72b_.ent", "d1igna1.ent-d1b8ia_.ent", "d1igna1.ent-d1bl0a2.ent", "d1igna1.ent-d1bw5__.ent", "d1igna1.ent-d1d5ya2.ent", "d1igna1.ent-d1e3oc1.ent", "d1igna1.ent-d1fexa_.ent", "d1igna1.ent-d1fjla_.ent", "d1igna1.ent-d1g2ha_.ent", "d1igna1.ent-d1hlva1.ent", "d1igna1.ent-d1hlva2.ent", "d1igna1.ent-d1ig7a_.ent", "d1igna1.ent-d1irza_.ent", "d1igna1.ent-d1iufa1.ent", "d1igna1.ent-d1iufa2.ent", "d1igna1.ent-d1jt6a1.ent", "d1igna1.ent-d1k61a_.ent", "d1igna1.ent-d1k78a1.ent", "d1igna1.ent-d1k78a2.ent", "d1igna1.ent-d2ezi__.ent", "d1igna1.ent-d2tct_1.ent", "d1igna2.ent-d1b72a_.ent", "d1igna2.ent-d1b72b_.ent", "d1igna2.ent-d1b8ia_.ent", "d1igna2.ent-d1bjaa_.ent", "d1igna2.ent-d1bl0a2.ent", "d1igna2.ent-d1bw5__.ent", "d1igna2.ent-d1d5va_.ent", "d1igna2.ent-d1d5ya2.ent", "d1igna2.ent-d1e3oc1.ent", "d1igna2.ent-d1f1za1.ent", "d1igna2.ent-d1fexa_.ent", "d1igna2.ent-d1fjla_.ent", "d1igna2.ent-d1fp2a1.ent", "d1igna2.ent-d1g2ha_.ent", "d1igna2.ent-d1hlva1.ent", "d1igna2.ent-d1hlva2.ent", "d1igna2.ent-d1ig7a_.ent", "d1igna2.ent-d1igna1.ent", "d1igna2.ent-d1irza_.ent", "d1igna2.ent-d1iufa1.ent", "d1igna2.ent-d1iufa2.ent", "d1igna2.ent-d1jhga_.ent", "d1igna2.ent-d1jt6a1.ent", "d1igna2.ent-d1k61a_.ent", "d1igna2.ent-d1k78a1.ent", "d1igna2.ent-d1k78a2.ent", "d1igna2.ent-d1ka8a_.ent", "d1igna2.ent-d1opc__.ent", "d1igna2.ent-d1repc2.ent", "d1igna2.ent-d1smta_.ent", "d1igna2.ent-d2ezi__.ent", "d1igna2.ent-d2ezl__.ent", "d1igna2.ent-d2foka3.ent", "d1igna2.ent-d2tct_1.ent", "d1igra1.ent-d1igra2.ent", "d1igra1.ent-d1io0a_.ent", "d1igra1.ent-d1ivoa1.ent", "d1igra1.ent-d1ivoa2.ent", "d1igra1.ent-d1jl5a_.ent", "d1igra1.ent-d1koha1.ent", "d1igra1.ent-d1m0za_.ent", "d1igra1.ent-d1m6ba1.ent", "d1igra1.ent-d1m6ba2.ent", "d1igra1.ent-d1n8yc1.ent", "d1igra1.ent-d1n8yc2.ent", "d1igra2.ent-d1ivoa1.ent", "d1igra2.ent-d1ivoa2.ent", "d1igra2.ent-d1jl5a_.ent", "d1igra2.ent-d1koha1.ent", "d1igra2.ent-d1m0za_.ent", "d1igra2.ent-d1m6ba1.ent", "d1igra2.ent-d1m6ba2.ent", "d1igra2.ent-d1n8yc1.ent", "d1igra2.ent-d1n8yc2.ent", "d1igra3.ent-d1ivoa3.ent", "d1igra3.ent-d1ivoa4.ent", "d1igra3.ent-d1m6ba3.ent", "d1igra3.ent-d1m6ba4.ent", "d1igra3.ent-d1n8yc3.ent", "d1igra3.ent-d1n8yc4.ent", "d1ih7a1.ent-d1az9_1.ent", "d1ih7a1.ent-d1bco_2.ent", "d1ih7a1.ent-d1bupa1.ent", "d1ih7a1.ent-d1bupa2.ent", "d1ih7a1.ent-d1czan1.ent", "d1ih7a1.ent-d1czan2.ent", "d1ih7a1.ent-d1e4ft1.ent", "d1ih7a1.ent-d1e4ft2.ent", "d1ih7a1.ent-d1g99a2.ent", "d1ih7a1.ent-d1glag1.ent", "d1ih7a1.ent-d1glag2.ent", "d1ih7a1.ent-d1huxa_.ent", "d1ih7a1.ent-d1io2a_.ent", "d1ih7a1.ent-d1j54a_.ent", "d1ih7a1.ent-d1j6za2.ent", "d1ih7a1.ent-d1jj2m_.ent", "d1ih7a1.ent-d1jl1a_.ent", "d1ih7a1.ent-d1kcfa2.ent", "d1ih7a1.ent-d1kfsa1.ent", "d1ih7a1.ent-d1musa_.ent", "d1ih7a1.ent-d1mwma2.ent", "d1ih7a1.ent-d1nbwa2.ent", "d1ih7a1.ent-d1nbwa3.ent", "d1ih7a1.ent-d1qtma1.ent", "d1ih7a1.ent-d1t7pa1.ent", "d1ih7a1.ent-d1tgoa1.ent", "d1ih7a1.ent-d1vrta1.ent", "d1ih7a1.ent-d1xwl_1.ent", "d1ih7a2.ent-d1im4a_.ent", "d1ih7a2.ent-d1jiha_.ent", "d1ih7a2.ent-d1kfsa2.ent", "d1ih7a2.ent-d1khva_.ent", "d1ih7a2.ent-d1mml__.ent", "d1ih7a2.ent-d1mswd_.ent", "d1ih7a2.ent-d1muka_.ent", "d1ih7a2.ent-d1rdr__.ent", "d1ih7a2.ent-d1t7pa2.ent", "d1ih7a2.ent-d1tgoa2.ent", "d1ih7a2.ent-d1vrta2.ent", "d1ih7a2.ent-d1xwl_2.ent", "d1ihba_.ent-d1k1aa_.ent", "d1ihba_.ent-d1k3zd_.ent", "d1ihba_.ent-d1myo__.ent", "d1ihba_.ent-d1n11a_.ent", "d1ihba_.ent-d1sw6a_.ent", "d1ihba_.ent-d1ycsb1.ent", "d1ihfa_.ent-d1ihfb_.ent", "d1ihga1.ent-d1elka_.ent", "d1ihga1.ent-d1hs6a1.ent", "d1ihga1.ent-d1iyga_.ent", "d1ihga1.ent-d1kpsb_.ent", "d1ihga1.ent-d1kt1a1.ent", "d1ihga1.ent-d1l5ja1.ent", "d1ihga1.ent-d1n4ka1.ent", "d1ihga1.ent-d1qqea_.ent", "d1ihja_.ent-d1k32a1.ent", "d1ihja_.ent-d1kwaa_.ent", "d1ihja_.ent-d1lcya1.ent", "d1ihja_.ent-d1m5za_.ent", "d1ihja_.ent-d1mfga_.ent", "d1ihja_.ent-d1qaua_.ent", "d1ihja_.ent-d1qava_.ent", "d1ihja_.ent-d1qlca_.ent", "d1ihka_.ent-d1ijta_.ent", "d1ihka_.ent-d1ilr1_.ent", "d1ihka_.ent-d1l2ha_.ent", "d1ihka_.ent-d1nuna_.ent", "d1ihka_.ent-d1qqla_.ent", "d1ihma_.ent-d1aym1_.ent", "d1ihma_.ent-d1aym2_.ent", "d1ihma_.ent-d1b35a_.ent", "d1ihma_.ent-d1b35b_.ent", "d1ihma_.ent-d1b35c_.ent", "d1ihma_.ent-d1bev1_.ent", "d1ihma_.ent-d1bev3_.ent", "d1ihma_.ent-d1bmv2_.ent", "d1ihma_.ent-d1d4m1_.ent", "d1ihma_.ent-d1dnv__.ent", "d1ihma_.ent-d1dzla_.ent", "d1ihma_.ent-d1k5ma_.ent", "d1ihma_.ent-d1novc_.ent", "d1ihma_.ent-d1pov0_.ent", "d1ihma_.ent-d1pvc1_.ent", "d1ihma_.ent-d1sva1_.ent", "d1ihma_.ent-d1tmf1_.ent", "d1ihma_.ent-d1vpsa_.ent", "d1ihma_.ent-d2bbva_.ent", "d1ihma_.ent-d2bpa1_.ent", "d1ihma_.ent-d2mev1_.ent", "d1ihma_.ent-d2mev2_.ent", "d1ihoa_.ent-d1ile_3.ent", "d1ihoa_.ent-d1iq0a2.ent", "d1ihoa_.ent-d1irxa2.ent", "d1ihoa_.ent-d1ivsa4.ent", "d1ihoa_.ent-d1j09a2.ent", "d1ihoa_.ent-d1jgta1.ent", "d1ihoa_.ent-d1jhda2.ent", "d1ihoa_.ent-d1jila_.ent", "d1ihoa_.ent-d1jmva_.ent", "d1ihoa_.ent-d1k4ma_.ent", "d1ihoa_.ent-d1k92a1.ent", "d1ihoa_.ent-d1kama_.ent", "d1ihoa_.ent-d1kqna_.ent", "d1ihoa_.ent-d1kqpa_.ent", "d1ihoa_.ent-d1li5a2.ent", "d1ihoa_.ent-d1mjha_.ent", "d1ihoa_.ent-d1n3la_.ent", "d1ihoa_.ent-d1o97c_.ent", "d1ihoa_.ent-d1o97d1.ent", "d1ihoa_.ent-d1qjca_.ent", "d1ihoa_.ent-d1sur__.ent", "d1ihp__.ent-d1nd6a_.ent", "d1ihp__.ent-d1qfxa_.ent", "d1ihp__.ent-d3pgm__.ent", "d1ihua1.ent-d1a7j__.ent", "d1ihua1.ent-d1aqua_.ent", "d1ihua1.ent-d1cr1a_.ent", "d1ihua1.ent-d1e69a_.ent", "d1ihua1.ent-d1e79a3.ent", "d1ihua1.ent-d1f5na2.ent", "d1ihua1.ent-d1fnna2.ent", "d1ihua1.ent-d1g8ya_.ent", "d1ihua1.ent-d1gm5a3.ent", "d1ihua1.ent-d1jwyb_.ent", "d1ihua1.ent-d1lv7a_.ent", "d1ihua1.ent-d1m6na3.ent", "d1ihua1.ent-d1nsta_.ent", "d1ii2a1.ent-d1khba1.ent", "d1ii2a1.ent-d1knxa2.ent", "d1ii2a1.ent-d1ko7a2.ent", "d1ii2a2.ent-d1j3ba2.ent", "d1ii2a2.ent-d1khba2.ent", "d1ii5a_.ent-d1ixh__.ent", "d1ii5a_.ent-d1jeta_.ent", "d1ii5a_.ent-d1kwha_.ent", "d1ii5a_.ent-d1lst__.ent", "d1ii5a_.ent-d1m5ea_.ent", "d1ii5a_.ent-d1mrp__.ent", "d1ii5a_.ent-d1nh8a1.ent", "d1ii5a_.ent-d1pda_1.ent", "d1ii5a_.ent-d1pot__.ent", "d1ii5a_.ent-d1sbp__.ent", "d1ii5a_.ent-d1wdna_.ent", "d1ii5a_.ent-d3mbp__.ent", "d1ii5a_.ent-d3thia_.ent", "d1ii6a_.ent-d1bg2__.ent", "d1ii6a_.ent-d1c4oa1.ent", "d1ii6a_.ent-d1e2ka_.ent", "d1ii6a_.ent-d1f9va_.ent", "d1ii6a_.ent-d1g41a_.ent", "d1ii6a_.ent-d1g8pa_.ent", "d1ii6a_.ent-d1i6ia_.ent", "d1ii6a_.ent-d1ksfx3.ent", "d1ii6a_.ent-d1n0ua2.ent", "d1ii6a_.ent-d1pjr_1.ent", "d1ii6a_.ent-d1pjr_2.ent", "d1ii6a_.ent-d1uaaa1.ent", "d1ii6a_.ent-d1uaaa2.ent", "d1ii7a_.ent-d1jk7a_.ent", "d1ii7a_.ent-d1nnwa_.ent", "d1ii7a_.ent-d1ush_2.ent", "d1ii7a_.ent-d1utea_.ent", "d1ii7a_.ent-d4kbpa2.ent", "d1iiba_.ent-d1jf8a_.ent", "d1iica2.ent-d1iyka1.ent", "d1iica2.ent-d1iyka2.ent", "d1iica2.ent-d1kzfa_.ent", "d1iica2.ent-d1lrza2.ent", "d1iica2.ent-d1lrza3.ent", "d1iica2.ent-d1m4ia_.ent", "d1iica2.ent-d1qsma_.ent", "d1iica2.ent-d1qsta_.ent", "d1iioa_.ent-d1j7qa_.ent", "d1iioa_.ent-d1k94a_.ent", "d1iioa_.ent-d1m45a_.ent", "d1iioa_.ent-d1psra_.ent", "d1iioa_.ent-d1qasa1.ent", "d1iioa_.ent-d1rec__.ent", "d1iioa_.ent-d1sra__.ent", "d1iioa_.ent-d2cbla1.ent", "d1iioa_.ent-d2pvba_.ent", "d1iioa_.ent-d2sas__.ent", "d1iioa_.ent-d2scpa_.ent", "d1iira_.ent-d1jixa_.ent", "d1iira_.ent-d1l5wa_.ent", "d1ijba_.ent-d1m1xb2.ent", "d1ijba_.ent-d1m2oa3.ent", "d1ijba_.ent-d1m2vb3.ent", "d1ijba_.ent-d1mjna_.ent", "d1ijba_.ent-d1n3ya_.ent", "d1ijba_.ent-d1qc5a_.ent", "d1ijqa1.ent-d1k32a2.ent", "d1ijqa1.ent-d1kit_3.ent", "d1ijqa1.ent-d3sil__.ent", "d1ijqa2.ent-d1agg__.ent", "d1ijqa2.ent-d1b9wa1.ent", "d1ijqa2.ent-d1b9wa2.ent", "d1ijqa2.ent-d1ceja1.ent", "d1ijqa2.ent-d1cixa_.ent", "d1ijqa2.ent-d1cvua2.ent", "d1ijqa2.ent-d1dx5i1.ent", "d1ijqa2.ent-d1emo_1.ent", "d1ijqa2.ent-d1flei_.ent", "d1ijqa2.ent-d1g9pa_.ent", "d1ijqa2.ent-d1gps__.ent", "d1ijqa2.ent-d1h59b_.ent", "d1ijqa2.ent-d1hyka_.ent", "d1ijqa2.ent-d1hz8a1.ent", "d1ijqa2.ent-d1hz8a2.ent", "d1ijqa2.ent-d1i2ua_.ent", "d1ijqa2.ent-d1imt_2.ent", "d1ijqa2.ent-d1ioxa_.ent", "d1ijqa2.ent-d1jkza_.ent", "d1ijqa2.ent-d1jl9a_.ent", "d1ijqa2.ent-d1l3ya_.ent", "d1ijqa2.ent-d1lpba2.ent", "d1ijqa2.ent-d1m1xb5.ent", "d1ijqa2.ent-d1tpg_1.ent", "d1ijqa2.ent-d1urk_1.ent", "d1ijqa2.ent-d3tgf__.ent", "d1ijta_.ent-d1ilr1_.ent", "d1ijta_.ent-d1l2ha_.ent", "d1ijta_.ent-d1nuna_.ent", "d1ijta_.ent-d1qqla_.ent", "d1ijva_.ent-d1kj6a_.ent", "d1ijva_.ent-d1sh1__.ent", "d1ijva_.ent-d2bds__.ent", "d1ik6a1.ent-d1jsca2.ent", "d1ik6a1.ent-d1jsca3.ent", "d1ik6a1.ent-d1keka1.ent", "d1ik6a1.ent-d1keka2.ent", "d1ik6a1.ent-d1l8aa1.ent", "d1ik6a1.ent-d1l8aa2.ent", "d1ik6a1.ent-d1poxa2.ent", "d1ik6a1.ent-d1poxa3.ent", "d1ik6a1.ent-d1pvda2.ent", "d1ik6a1.ent-d1pvda3.ent", "d1ik6a1.ent-d1zpda2.ent", "d1ik6a1.ent-d1zpda3.ent", "d1ik6a2.ent-d1itza3.ent", "d1ik6a2.ent-d1keka3.ent", "d1ik6a2.ent-d1l8aa3.ent", "d1ikna2.ent-d1imhc2.ent", "d1ikna2.ent-d1mnna_.ent", "d1ikna2.ent-d1ycsa_.ent", "d1ikop_.ent-d1jzga_.ent", "d1ikop_.ent-d1kcw_1.ent", "d1ikop_.ent-d1kcw_2.ent", "d1ikop_.ent-d1kv7a1.ent", "d1ikop_.ent-d1kv7a2.ent", "d1ikop_.ent-d1kv7a3.ent", "d1ikop_.ent-d1kzqa1.ent", "d1ikop_.ent-d1l9qa1.ent", "d1ikop_.ent-d1l9qa2.ent", "d1ikop_.ent-d1qhqa_.ent", "d1ikop_.ent-d2cbp__.ent", "d1ikop_.ent-d2cuaa_.ent", "d1ikpa1.ent-d1dhkb_.ent", "d1ikpa1.ent-d1dyka1.ent", "d1ikpa1.ent-d1dyka2.ent", "d1ikpa1.ent-d1epwa1.ent", "d1ikpa1.ent-d1fx5a_.ent", "d1ikpa1.ent-d1gv9a_.ent", "d1ikpa1.ent-d1gzca_.ent", "d1ikpa1.ent-d1h30a1.ent", "d1ikpa1.ent-d1h30a2.ent", "d1ikpa1.ent-d1is3a_.ent", "d1ikpa1.ent-d1jhna4.ent", "d1ikpa1.ent-d1kit_1.ent", "d1ikpa1.ent-d1kit_2.ent", "d1ikpa1.ent-d1kqra_.ent", "d1ikpa1.ent-d1n1ta1.ent", "d1ikpa1.ent-d1n3oa_.ent", "d1ikpa1.ent-d1nls__.ent", "d1ikpa1.ent-d1saca_.ent", "d1ikpa1.ent-d1xnb__.ent", "d1ikpa1.ent-d2ayh__.ent", "d1ikpa1.ent-d2nlra_.ent", "d1ikpa1.ent-d2pela_.ent", "d1ikpa1.ent-d2sli_1.ent", "d1ikpa1.ent-d3btaa1.ent", "d1ikpa2.ent-d1j7na3.ent", "d1ikpa2.ent-d1prta_.ent", "d1ikpa2.ent-d1qs1a1.ent", "d1ikpa2.ent-d1qs1a2.ent", "d1ikpa3.ent-d1k3ka_.ent", "d1ikpa3.ent-d1maz__.ent", "d1ikza_.ent-d1jlna_.ent", "d1ikza_.ent-d1lara1.ent", "d1ikza_.ent-d1lara2.ent", "d1ikza_.ent-d1lyva_.ent", "d1ikza_.ent-d1mkp__.ent", "d1ikza_.ent-d1vhra_.ent", "d1ikza_.ent-d1yfoa_.ent", "d1ikza_.ent-d2shpa1.ent", "d1ile_1.ent-d1iq0a1.ent", "d1ile_1.ent-d1ivsa2.ent", "d1ile_1.ent-d1li5a1.ent", "d1ile_2.ent-d1ivsa3.ent", "d1ile_3.ent-d1iq0a2.ent", "d1ile_3.ent-d1irxa2.ent", "d1ile_3.ent-d1ivsa4.ent", "d1ile_3.ent-d1j09a2.ent", "d1ile_3.ent-d1jgta1.ent", "d1ile_3.ent-d1jhda2.ent", "d1ile_3.ent-d1jila_.ent", "d1ile_3.ent-d1jmva_.ent", "d1ile_3.ent-d1k4ma_.ent", "d1ile_3.ent-d1k92a1.ent", "d1ile_3.ent-d1kama_.ent", "d1ile_3.ent-d1kqna_.ent", "d1ile_3.ent-d1kqpa_.ent", "d1ile_3.ent-d1li5a2.ent", "d1ile_3.ent-d1mjha_.ent", "d1ile_3.ent-d1n3la_.ent", "d1ile_3.ent-d1o97c_.ent", "d1ile_3.ent-d1o97d1.ent", "d1ile_3.ent-d1qjca_.ent", "d1ile_3.ent-d1sur__.ent", "d1ilga_.ent-d1kv6a_.ent", "d1ilga_.ent-d1lv2a_.ent", "d1ilga_.ent-d1mzna_.ent", "d1ilga_.ent-d1n83a_.ent", "d1ilga_.ent-d2prga_.ent", "d1iloa_.ent-d1aqwa2.ent", "d1ilr1_.ent-d1l2ha_.ent", "d1ilr1_.ent-d1nuna_.ent", "d1ilr1_.ent-d1qqla_.ent", "d1ilya_.ent-d1jj2m_.ent", "d1im4a_.ent-d1jiha_.ent", "d1im4a_.ent-d1kfsa2.ent", "d1im4a_.ent-d1khva_.ent", "d1im4a_.ent-d1mml__.ent", "d1im4a_.ent-d1mswd_.ent", "d1im4a_.ent-d1muka_.ent", "d1im4a_.ent-d1rdr__.ent", "d1im4a_.ent-d1t7pa2.ent", "d1im4a_.ent-d1tgoa2.ent", "d1im4a_.ent-d1vrta2.ent", "d1im4a_.ent-d1xwl_2.ent", "d1im5a_.ent-d1nbaa_.ent", "d1im5a_.ent-d1yaca_.ent", "d1imhc2.ent-d1mnna_.ent", "d1imhc2.ent-d1ycsa_.ent", "d1imja_.ent-d1ispa_.ent", "d1imja_.ent-d1jfra_.ent", "d1imja_.ent-d1ju3a2.ent", "d1imja_.ent-d1ku0a_.ent", "d1imja_.ent-d1l7aa_.ent", "d1imja_.ent-d1lzla_.ent", "d1imja_.ent-d1mnaa_.ent", "d1imja_.ent-d1n1ma2.ent", "d1imja_.ent-d1qj4a_.ent", "d1imja_.ent-d1qlwa_.ent", "d1imja_.ent-d1qo7a_.ent", "d1imja_.ent-d1tca__.ent", "d1imja_.ent-d1thta_.ent", "d1imja_.ent-d3tgl__.ent", "d1iml_2.ent-d1jj2t_.ent", "d1iml_2.ent-d1k3xa3.ent", "d1iml_2.ent-d1kb2a_.ent", "d1iml_2.ent-d1l1za3.ent", "d1iml_2.ent-d1lata_.ent", "d1iml_2.ent-d1lv3a_.ent", "d1iml_2.ent-d1zfo__.ent", "d1iml_2.ent-d2nllb_.ent", "d1iml_2.ent-d3gata_.ent", "d1iml_2.ent-d7gata_.ent", "d1imt_1.ent-d1imt_2.ent", "d1imt_1.ent-d1lpba1.ent", "d1imt_1.ent-d1lpba2.ent", "d1imt_2.ent-d1lpba1.ent", "d1imt_2.ent-d1lpba2.ent", "d1imva_.ent-d1jmja_.ent", "d1imva_.ent-d1k9oi_.ent", "d1imva_.ent-d1lj5a_.ent", "d1imva_.ent-d1ovaa_.ent", "d1imva_.ent-d1qlpa_.ent", "d1in1a_.ent-d1l0ba1.ent", "d1in1a_.ent-d1l0ba2.ent", "d1inla_.ent-d1booa_.ent", "d1inla_.ent-d1eg2a_.ent", "d1inla_.ent-d1fp1d2.ent", "d1inla_.ent-d1fp2a2.ent", "d1inla_.ent-d1g60a_.ent", "d1inla_.ent-d1hnna_.ent", "d1inla_.ent-d1i1na_.ent", "d1inla_.ent-d1i9ga_.ent", "d1inla_.ent-d1iy9a_.ent", "d1inla_.ent-d1jg1a_.ent", "d1inla_.ent-d1jqea_.ent", "d1inla_.ent-d1jsxa_.ent", "d1inla_.ent-d1khha_.ent", "d1inla_.ent-d1kywa2.ent", "d1inla_.ent-d1mjfa_.ent", "d1inla_.ent-d1qama_.ent", "d1inla_.ent-d1vid__.ent", "d1inla_.ent-d1xvaa_.ent", "d1inla_.ent-d1yub__.ent", "d1inla_.ent-d2dpma_.ent", "d1inla_.ent-d3mag__.ent", "d1inp__.ent-d1jp4a_.ent", "d1inp__.ent-d1ka1a_.ent", "d1inp__.ent-d1kz8a_.ent", "d1inp__.ent-d1lbva_.ent", "d1inp__.ent-d2hhma_.ent", "d1io0a_.ent-d1koha1.ent", "d1io0a_.ent-d1n8yc1.ent", "d1io0a_.ent-d1yrga_.ent", "d1io2a_.ent-d1j54a_.ent", "d1io2a_.ent-d1jl1a_.ent", "d1io2a_.ent-d1kcfa2.ent", "d1io2a_.ent-d1kfsa1.ent", "d1io2a_.ent-d1musa_.ent", "d1io2a_.ent-d1qtma1.ent", "d1io2a_.ent-d1t7pa1.ent", "d1io2a_.ent-d1tgoa1.ent", "d1io2a_.ent-d1vrta1.ent", "d1io2a_.ent-d1xwl_1.ent", "d1io7a_.ent-d1jfba_.ent", "d1io7a_.ent-d1jipa_.ent", "d1io7a_.ent-d1jpza_.ent", "d1io7a_.ent-d1lfka_.ent", "d1io7a_.ent-d1n97a_.ent", "d1iooa_.ent-d1iqqa_.ent", "d1iooa_.ent-d1jy5a_.ent", "d1iow_1.ent-d1kjqa2.ent", "d1iow_1.ent-d1m0wa1.ent", "d1iow_1.ent-d2hgsa1.ent", "d1iow_2.ent-d1jkjb2.ent", "d1iow_2.ent-d1kbla3.ent", "d1iow_2.ent-d1kjqa3.ent", "d1iow_2.ent-d1m0wa2.ent", "d1iow_2.ent-d2hgsa4.ent", "d1ioxa_.ent-d1b9wa1.ent", "d1ioxa_.ent-d1b9wa2.ent", "d1ioxa_.ent-d1ceja1.ent", "d1ioxa_.ent-d1cvua2.ent", "d1ioxa_.ent-d1dx5i1.ent", "d1ioxa_.ent-d1emo_1.ent", "d1ioxa_.ent-d1hz8a1.ent", "d1ioxa_.ent-d1hz8a2.ent", "d1ioxa_.ent-d1jl9a_.ent", "d1ioxa_.ent-d1l3ya_.ent", "d1ioxa_.ent-d1m1xb5.ent", "d1ioxa_.ent-d1tpg_1.ent", "d1ioxa_.ent-d1urk_1.ent", "d1ioxa_.ent-d3tgf__.ent", "d1ip9a_.ent-d1fm0d_.ent", "d1ip9a_.ent-d1h4ra3.ent", "d1ip9a_.ent-d1h8ca_.ent", "d1ip9a_.ent-d1k8rb_.ent", "d1ipaa1.ent-d1k3ra2.ent", "d1ipaa1.ent-d1mxia_.ent", "d1ipaa2.ent-d1iv3a_.ent", "d1ipaa2.ent-d1jj2f_.ent", "d1ipaa2.ent-d1tuba2.ent", "d1iq0a1.ent-d1ivsa2.ent", "d1iq0a1.ent-d1li5a1.ent", "d1iq0a2.ent-d1irxa2.ent", "d1iq0a2.ent-d1ivsa4.ent", "d1iq0a2.ent-d1j09a2.ent", "d1iq0a2.ent-d1jhda2.ent", "d1iq0a2.ent-d1jila_.ent", "d1iq0a2.ent-d1k4ma_.ent", "d1iq0a2.ent-d1kama_.ent", "d1iq0a2.ent-d1kqna_.ent", "d1iq0a2.ent-d1li5a2.ent", "d1iq0a2.ent-d1n3la_.ent", "d1iq0a2.ent-d1qjca_.ent", "d1iq0a3.ent-d1qf6a3.ent", "d1iq6a_.ent-d1lo7a_.ent", "d1iq6a_.ent-d1mkaa_.ent", "d1iqca1.ent-d1c52__.ent", "d1iqca1.ent-d1co6a_.ent", "d1iqca1.ent-d1cot__.ent", "d1iqca1.ent-d1cxc__.ent", "d1iqca1.ent-d1dw0a_.ent", "d1iqca1.ent-d1e29a_.ent", "d1iqca1.ent-d1etpa2.ent", "d1iqca1.ent-d1f1ca_.ent", "d1iqca1.ent-d1gu2a_.ent", "d1iqca1.ent-d1hroa_.ent", "d1iqca1.ent-d1iqca2.ent", "d1iqca1.ent-d1jmxa1.ent", "d1iqca1.ent-d1jmxa2.ent", "d1iqca1.ent-d1kb0a1.ent", "d1iqca1.ent-d1kv9a1.ent", "d1iqca1.ent-d1mg2d_.ent", "d1iqca1.ent-d1nira1.ent", "d1iqca1.ent-d1qksa1.ent", "d1iqca1.ent-d1ql3a_.ent", "d1iqca1.ent-d1qn2a_.ent", "d1iqca1.ent-d1ycc__.ent", "d1iqca1.ent-d3c2c__.ent", "d1iqca2.ent-d1c52__.ent", "d1iqca2.ent-d1co6a_.ent", "d1iqca2.ent-d1cot__.ent", "d1iqca2.ent-d1cxc__.ent", "d1iqca2.ent-d1dw0a_.ent", "d1iqca2.ent-d1e29a_.ent", "d1iqca2.ent-d1eb7a2.ent", "d1iqca2.ent-d1etpa2.ent", "d1iqca2.ent-d1f1ca_.ent", "d1iqca2.ent-d1gu2a_.ent", "d1iqca2.ent-d1h32a1.ent", "d1iqca2.ent-d1hroa_.ent", "d1iqca2.ent-d1iqca1.ent", "d1iqca2.ent-d1jmxa1.ent", "d1iqca2.ent-d1jmxa2.ent", "d1iqca2.ent-d1kb0a1.ent", "d1iqca2.ent-d1kv9a1.ent", "d1iqca2.ent-d1mg2d_.ent", "d1iqca2.ent-d1nira1.ent", "d1iqca2.ent-d1qksa1.ent", "d1iqca2.ent-d1ql3a_.ent", "d1iqca2.ent-d1qn2a_.ent", "d1iqca2.ent-d1ycc__.ent", "d1iqca2.ent-d3c2c__.ent", "d1iqpa1.ent-d1jr3a1.ent", "d1iqpa1.ent-d1jr3d1.ent", "d1iqqa_.ent-d1jy5a_.ent", "d1iqra1.ent-d1np7a1.ent", "d1iqra1.ent-d1qnf_1.ent", "d1iqra2.ent-d1np7a2.ent", "d1iqra2.ent-d1qnf_2.ent", "d1iqta_.ent-d1jmta_.ent", "d1iqta_.ent-d1koha2.ent", "d1iqta_.ent-d1l3ka1.ent", "d1iqta_.ent-d1l3ka2.ent", "d1iqta_.ent-d1nu4a_.ent", "d1iqta_.ent-d1qm9a1.ent", "d1iqta_.ent-d1qm9a2.ent", "d1iqta_.ent-d1u2fa_.ent", "d1iqta_.ent-d2msta_.ent", "d1iqta_.ent-d2u1a__.ent", "d1iqta_.ent-d2u2fa_.ent", "d1iqza_.ent-d1jb0c_.ent", "d1iqza_.ent-d1jnrb_.ent", "d1iqza_.ent-d1keka5.ent", "d1iqza_.ent-d1kqfb1.ent", "d1iqza_.ent-d2fdn__.ent", "d1iqza_.ent-d7fd1a_.ent", "d1irda_.ent-d1ew6a_", "d1irda_.ent-d1ew6a_.ent", "d1irda_.ent-d1gcva_", "d1irda_.ent-d1gcva_.ent", "d1irda_.ent-d1itha_", "d1irda_.ent-d1itha_.ent", "d1irdb_.ent-d1cg5a_", "d1irdb_.ent-d1cg5a_.ent", "d1irdb_.ent-d1cg5b_", "d1irdb_.ent-d1cg5b_.ent", "d1irdb_.ent-d1ew6a_", "d1irdb_.ent-d1ew6a_.ent", "d1irdb_.ent-d1gcva_", "d1irdb_.ent-d1gcva_.ent", "d1irdb_.ent-d1irda_", "d1irdb_.ent-d1irda_.ent", "d1irdb_.ent-d1it2a_", "d1irdb_.ent-d1it2a_.ent", "d1irdb_.ent-d1itha_", "d1irdb_.ent-d1itha_.ent", "d1irdb_.ent-d1la6a_", "d1irdb_.ent-d1la6a_.ent", "d1irdb_.ent-d1mba__", "d1irdb_.ent-d1mba__.ent", "d1irdb_.ent-d1qlab1", "d1irdb_.ent-d1qlab1.ent", "d1irdb_.ent-d2gdm__", "d1irdb_.ent-d2gdm__.ent", "d1irdb_.ent-d3sdha_", "d1irdb_.ent-d3sdha_.ent", "d1ireb_.ent-d1jb0e_.ent", "d1ireb_.ent-d1vie__.ent", "d1ireb_.ent-d2ahjb_.ent", "d1irha_.ent-d1ktha_.ent", "d1irha_.ent-d1tfxc_.ent", "d1irha_.ent-d1tocr1.ent", "d1irha_.ent-d1tocr2.ent", "d1irqa_.ent-d1mnta_.ent", "d1irqa_.ent-d2cpga_.ent", "d1iru1_.ent-d1iruk_.ent", "d1iru1_.ent-d1jgta2.ent", "d1iru1_.ent-d1pma1_.ent", "d1iru1_.ent-d1ryph_.ent", "d1iru1_.ent-d1rypj_.ent", "d1iru1_.ent-d1rypk_.ent", "d1iru1_.ent-d1rypl_.ent", "d1iru2_.ent-d1iru1_.ent", "d1iru2_.ent-d1iruk_.ent", "d1iru2_.ent-d1jgta2.ent", "d1iru2_.ent-d1pma1_.ent", "d1iru2_.ent-d1ryph_.ent", "d1iru2_.ent-d1rypj_.ent", "d1iru2_.ent-d1rypk_.ent", "d1iru2_.ent-d1rypl_.ent", "d1iruk_.ent-d1rypk_.ent", "d1irxa2.ent-d1ivsa4.ent", "d1irxa2.ent-d1j09a2.ent", "d1irxa2.ent-d1jgta1.ent", "d1irxa2.ent-d1jhda2.ent", "d1irxa2.ent-d1jila_.ent", "d1irxa2.ent-d1jmva_.ent", "d1irxa2.ent-d1k4ma_.ent", "d1irxa2.ent-d1k92a1.ent", "d1irxa2.ent-d1kama_.ent", "d1irxa2.ent-d1kqna_.ent", "d1irxa2.ent-d1kqpa_.ent", "d1irxa2.ent-d1li5a2.ent", "d1irxa2.ent-d1mjha_.ent", "d1irxa2.ent-d1n3la_.ent", "d1irxa2.ent-d1o97c_.ent", "d1irxa2.ent-d1o97d1.ent", "d1irxa2.ent-d1qjca_.ent", "d1irxa2.ent-d1sur__.ent", "d1irza_.ent-d1b8ia_.ent", "d1irza_.ent-d1bl0a2.ent", "d1irza_.ent-d1e3oc1.ent", "d1irza_.ent-d1fexa_.ent", "d1irza_.ent-d1g2ha_.ent", "d1irza_.ent-d1ig7a_.ent", "d1irza_.ent-d1k61a_.ent", "d1irza_.ent-d1k78a1.ent", "d1irza_.ent-d1k78a2.ent", "d1is2a1.ent-d1is2a2.ent", "d1is2a1.ent-d1ivha1.ent", "d1is2a1.ent-d1jqia1.ent", "d1is2a1.ent-d3mdda1.ent", "d1is2a2.ent-d1ivha1.ent", "d1is2a2.ent-d1jqia1.ent", "d1is2a2.ent-d3mdda1.ent", "d1is2a3.ent-d1ivha2.ent", "d1is2a3.ent-d1jqia2.ent", "d1is2a3.ent-d3mdda2.ent", "d1is3a_.ent-d1jhna4.ent", "d1is3a_.ent-d1kit_1.ent", "d1is3a_.ent-d1kqra_.ent", "d1is3a_.ent-d1n1ta1.ent", "d1is3a_.ent-d1nls__.ent", "d1is3a_.ent-d1saca_.ent", "d1is3a_.ent-d2nlra_.ent", "d1is3a_.ent-d2sli_1.ent", "d1is8a_.ent-d1uox_1.ent", "d1is8a_.ent-d1uox_2.ent", "d1isaa1.ent-d1ix9a1.ent", "d1isaa2.ent-d1ix9a2.ent", "d1isaa2.ent-d1kkca2.ent", "d1isaa2.ent-d1ma1a2.ent", "d1isaa2.ent-d1qnna2.ent", "d1ispa_.ent-d1jfra_.ent", "d1ispa_.ent-d1ju3a2.ent", "d1ispa_.ent-d1ku0a_.ent", "d1ispa_.ent-d1l7aa_.ent", "d1ispa_.ent-d1lzla_.ent", "d1ispa_.ent-d1mnaa_.ent", "d1ispa_.ent-d1n1ma2.ent", "d1ispa_.ent-d1qj4a_.ent", "d1ispa_.ent-d1qlwa_.ent", "d1ispa_.ent-d1qo7a_.ent", "d1ispa_.ent-d1tca__.ent", "d1ispa_.ent-d1thta_.ent", "d1ispa_.ent-d3tgl__.ent", "d1isua_.ent-d1iuaa_.ent", "d1isua_.ent-d2hipa_.ent", "d1it2a_.ent-d1cg5a_", "d1it2a_.ent-d1cg5a_.ent", "d1it2a_.ent-d1cg5b_", "d1it2a_.ent-d1cg5b_.ent", "d1it2a_.ent-d1ew6a_", "d1it2a_.ent-d1ew6a_.ent", "d1it2a_.ent-d1gcva_", "d1it2a_.ent-d1gcva_.ent", "d1it2a_.ent-d1irda_", "d1it2a_.ent-d1irda_.ent", "d1it2a_.ent-d1itha_", "d1it2a_.ent-d1itha_.ent", "d1it2a_.ent-d1la6a_", "d1it2a_.ent-d1la6a_.ent", "d1it2a_.ent-d1mba__", "d1it2a_.ent-d1mba__.ent", "d1it2a_.ent-d3sdha_", "d1it2a_.ent-d3sdha_.ent", "d1itha_.ent-d1ew6a_", "d1itha_.ent-d1ew6a_.ent", "d1itha_.ent-d1gcva_", "d1itha_.ent-d1gcva_.ent", "d1itha_.ent-d1qlab1", "d1itha_.ent-d1qlab1.ent", "d1itha_.ent-d2gdm__", "d1itha_.ent-d2gdm__.ent", "d1itka1.ent-d1itka2.ent", "d1itka1.ent-d1jdra_.ent", "d1itka1.ent-d1llp__.ent", "d1itka1.ent-d1mn2__.ent", "d1itka1.ent-d1pa2a_.ent", "d1itka2.ent-d1jdra_.ent", "d1itka2.ent-d1llp__.ent", "d1itka2.ent-d1mn2__.ent", "d1itka2.ent-d1pa2a_.ent", "d1itpa_.ent-d1jqga2.ent", "d1itpa_.ent-d1kn6a_.ent", "d1itpa_.ent-d1kwma2.ent", "d1itpa_.ent-d1scjb_.ent", "d1itua_.ent-d1d3ga_.ent", "d1itua_.ent-d1gvoa_.ent", "d1itua_.ent-d1j5sa_.ent", "d1itua_.ent-d1k6wa2.ent", "d1itua_.ent-d1kbla1.ent", "d1itua_.ent-d1m7ja3.ent", "d1itva_.ent-d1pex__.ent", "d1itva_.ent-d1qhua1.ent", "d1itwa_.ent-d1lwda_.ent", "d1itwa_.ent-d1xaa__.ent", "d1itxa2.ent-d1jnda2.ent", "d1itxa2.ent-d1kfwa2.ent", "d1itxa2.ent-d1lg2a2.ent", "d1itxa2.ent-d1ll7a2.ent", "d1itxa2.ent-d1m5ya2.ent", "d1itxa2.ent-d1pina2.ent", "d1itxa2.ent-d3eipa_.ent", "d1itza3.ent-d1keka3.ent", "d1itza3.ent-d1l8aa3.ent", "d1iu4a_.ent-d1kxra_.ent", "d1iu4a_.ent-d1l9na4.ent", "d1iu4a_.ent-d1me4a_.ent", "d1iu4a_.ent-d1nbfa_.ent", "d1iu4a_.ent-d1ppn__.ent", "d1iu4a_.ent-d1qmya_.ent", "d1iu4a_.ent-d1uch__.ent", "d1iu4a_.ent-d2act__.ent", "d1iu4a_.ent-d2cb5a_.ent", "d1iu4a_.ent-d3gcb__.ent", "d1iu4a_.ent-d7pcka_.ent", "d1iuaa_.ent-d2hipa_.ent", "d1iufa1.ent-d1b72a_.ent", "d1iufa1.ent-d1b72b_.ent", "d1iufa1.ent-d1b8ia_.ent", "d1iufa1.ent-d1bl0a2.ent", "d1iufa1.ent-d1bw5__.ent", "d1iufa1.ent-d1d5ya2.ent", "d1iufa1.ent-d1e3oc1.ent", "d1iufa1.ent-d1fexa_.ent", "d1iufa1.ent-d1fjla_.ent", "d1iufa1.ent-d1g2ha_.ent", "d1iufa1.ent-d1hlva1.ent", "d1iufa1.ent-d1hlva2.ent", "d1iufa1.ent-d1ig7a_.ent", "d1iufa1.ent-d1irza_.ent", "d1iufa1.ent-d1iufa2.ent", "d1iufa1.ent-d1jt6a1.ent", "d1iufa1.ent-d1k61a_.ent", "d1iufa1.ent-d1k78a1.ent", "d1iufa1.ent-d1k78a2.ent", "d1iufa1.ent-d2ezi__.ent", "d1iufa1.ent-d2tct_1.ent", "d1iufa2.ent-d1b8ia_.ent", "d1iufa2.ent-d1bl0a2.ent", "d1iufa2.ent-d1d5ya2.ent", "d1iufa2.ent-d1e3oc1.ent", "d1iufa2.ent-d1fexa_.ent", "d1iufa2.ent-d1fjla_.ent", "d1iufa2.ent-d1g2ha_.ent", "d1iufa2.ent-d1hlva2.ent", "d1iufa2.ent-d1ig7a_.ent", "d1iufa2.ent-d1irza_.ent", "d1iufa2.ent-d1k61a_.ent", "d1iufa2.ent-d1k78a1.ent", "d1iufa2.ent-d1k78a2.ent", "d1iufa2.ent-d2tct_1.ent", "d1iv3a_.ent-d1jj2f_.ent", "d1iv3a_.ent-d1tuba2.ent", "d1iv8a1.ent-d1j0ha2.ent", "d1iv8a1.ent-d1jae_1.ent", "d1iv8a1.ent-d1ji1a2.ent", "d1iv8a1.ent-d1ji2a2.ent", "d1iv8a1.ent-d1ktba1.ent", "d1iv8a1.ent-d1kwga1.ent", "d1iv8a1.ent-d1lwha1.ent", "d1iv8a1.ent-d1m7xa2.ent", "d1iv8a1.ent-d1qhoa3.ent", "d1iv8a1.ent-d1uok_1.ent", "d1iv8a1.ent-d7taa_1.ent", "d1ivha1.ent-d1jqia1.ent", "d1ivha1.ent-d3mdda1.ent", "d1ivha2.ent-d1jqia2.ent", "d1ivha2.ent-d3mdda2.ent", "d1ivoa1.ent-d1ivoa2.ent", "d1ivoa1.ent-d1jl5a_.ent", "d1ivoa1.ent-d1koha1.ent", "d1ivoa1.ent-d1m0za_.ent", "d1ivoa1.ent-d1m6ba1.ent", "d1ivoa1.ent-d1m6ba2.ent", "d1ivoa1.ent-d1n8yc1.ent", "d1ivoa1.ent-d1n8yc2.ent", "d1ivoa2.ent-d1jl5a_.ent", "d1ivoa2.ent-d1koha1.ent", "d1ivoa2.ent-d1m0za_.ent", "d1ivoa2.ent-d1m6ba1.ent", "d1ivoa2.ent-d1m6ba2.ent", "d1ivoa2.ent-d1n8yc1.ent", "d1ivoa2.ent-d1n8yc2.ent", "d1ivoa3.ent-d1ivoa4.ent", "d1ivoa3.ent-d1m6ba3.ent", "d1ivoa3.ent-d1m6ba4.ent", "d1ivoa3.ent-d1n8yc3.ent", "d1ivoa3.ent-d1n8yc4.ent", "d1ivoa4.ent-d1m6ba3.ent", "d1ivoa4.ent-d1m6ba4.ent", "d1ivoa4.ent-d1n8yc3.ent", "d1ivoa4.ent-d1n8yc4.ent", "d1ivsa1.ent-d1ix9a1.ent", "d1ivsa1.ent-d1jj2u_.ent", "d1ivsa1.ent-d1k4ta1.ent", "d1ivsa1.ent-d1lrza1.ent", "d1ivsa1.ent-d1seta1.ent", "d1ivsa2.ent-d1li5a1.ent", "d1ivsa4.ent-d1j09a2.ent", "d1ivsa4.ent-d1jhda2.ent", "d1ivsa4.ent-d1jila_.ent", "d1ivsa4.ent-d1k4ma_.ent", "d1ivsa4.ent-d1kama_.ent", "d1ivsa4.ent-d1kqna_.ent", "d1ivsa4.ent-d1li5a2.ent", "d1ivsa4.ent-d1n3la_.ent", "d1ivsa4.ent-d1qjca_.ent", "d1ivwa2.ent-d1ivwa3.ent", "d1ivwa2.ent-d1jkgb_.ent", "d1ivwa2.ent-d1ksia2.ent", "d1ivwa2.ent-d1ksia3.ent", "d1ivwa2.ent-d1kwia_.ent", "d1ivwa2.ent-d1mola_.ent", "d1ivwa2.ent-d1mwxa1.ent", "d1ivwa2.ent-d1o7nb_.ent", "d1ivwa2.ent-d1oaca2.ent", "d1ivwa2.ent-d1oaca3.ent", "d1ivwa2.ent-d1stfi_.ent", "d1ivwa2.ent-d1ugia_.ent", "d1ivwa2.ent-d3stda_.ent", "d1ivwa3.ent-d1jkgb_.ent", "d1ivwa3.ent-d1ksia2.ent", "d1ivwa3.ent-d1ksia3.ent", "d1ivwa3.ent-d1kwia_.ent", "d1ivwa3.ent-d1mola_.ent", "d1ivwa3.ent-d1mwxa1.ent", "d1ivwa3.ent-d1o7nb_.ent", "d1ivwa3.ent-d1oaca2.ent", "d1ivwa3.ent-d1oaca3.ent", "d1ivwa3.ent-d1stfi_.ent", "d1ivwa3.ent-d1ugia_.ent", "d1ivwa3.ent-d3stda_.ent", "d1ivya_.ent-d1bu8a2.ent", "d1ivya_.ent-d1cpy__.ent", "d1ivya_.ent-d1cr6a2.ent", "d1ivya_.ent-d1cvl__.ent", "d1ivya_.ent-d1hlga_.ent", "d1ivya_.ent-d1iz7a_.ent", "d1ivya_.ent-d1jjia_.ent", "d1ivya_.ent-d1jkma_.ent", "d1ivya_.ent-d1ju3a2.ent", "d1ivya_.ent-d1ku0a_.ent", "d1ivya_.ent-d1l7aa_.ent", "d1ivya_.ent-d1lnsa3.ent", "d1ivya_.ent-d1lzla_.ent", "d1ivya_.ent-d1qlwa_.ent", "d1ivya_.ent-d1qo7a_.ent", "d1ivya_.ent-d1qtra_.ent", "d1ivya_.ent-d1tca__.ent", "d1iw4a_.ent-d1ldtl_.ent", "d1iw4a_.ent-d1nuba3.ent", "d1iw4a_.ent-d1pce__.ent", "d1iw4a_.ent-d1sgpi_.ent", "d1iw4a_.ent-d1tbrr1.ent", "d1iw4a_.ent-d1tbrr2.ent", "d1iw4a_.ent-d1tgsi_.ent", "d1iw4a_.ent-d4sgbi_.ent", "d1iw5a_.ent-d1k0ra2.ent", "d1iw5a_.ent-d1k0ra3.ent", "d1iw5a_.ent-d1mkya3.ent", "d1iw5a_.ent-d3proc1.ent", "d1iw5a_.ent-d3proc2.ent", "d1iw7c_.ent-d1iw7d_.ent", "d1iw7f_.ent-d1ku3a_.ent", "d1iw7f_.ent-d1l0oc_.ent", "d1iw7f_.ent-d1sig__.ent", "d1iwea_.ent-d1bg2__.ent", "d1iwea_.ent-d1c4oa1.ent", "d1iwea_.ent-d1e2ka_.ent", "d1iwea_.ent-d1e9ra_.ent", "d1iwea_.ent-d1f9va_.ent", "d1iwea_.ent-d1fmja_.ent", "d1iwea_.ent-d1g41a_.ent", "d1iwea_.ent-d1g8pa_.ent", "d1iwea_.ent-d1i6ia_.ent", "d1iwea_.ent-d1ii6a_.ent", "d1iwea_.ent-d1ksfx3.ent", "d1iwea_.ent-d1n0ua2.ent", "d1iwea_.ent-d1pjr_1.ent", "d1iwea_.ent-d1pjr_2.ent", "d1iwea_.ent-d1uaaa1.ent", "d1iwea_.ent-d1uaaa2.ent", "d1iwea_.ent-d2ncda_.ent", "d1iwga1.ent-d1iwga2.ent", "d1iwga1.ent-d1iwga3.ent", "d1iwga1.ent-d1iwga4.ent", "d1iwga2.ent-d1iwga3.ent", "d1iwga2.ent-d1iwga4.ent", "d1iwga3.ent-d1iwga4.ent", "d1ix9a1.ent-d1jj2u_.ent", "d1ix9a1.ent-d1k4ta1.ent", "d1ix9a1.ent-d1lrza1.ent", "d1ix9a1.ent-d1seta1.ent", "d1ix9a2.ent-d1kkca2.ent", "d1ix9a2.ent-d1ma1a2.ent", "d1ix9a2.ent-d1qnna2.ent", "d1ixda_.ent-d1bb9__.ent", "d1ixda_.ent-d1dj7b_.ent", "d1ixda_.ent-d1fx7a3.ent", "d1ixda_.ent-d1g3sa3.ent", "d1ixda_.ent-d1gcqc_.ent", "d1ixda_.ent-d1i07a_.ent", "d1ixda_.ent-d1jb0e_.ent", "d1ixda_.ent-d1jj2p_.ent", "d1ixda_.ent-d1jo8a_.ent", "d1ixda_.ent-d1khia1.ent", "d1ixda_.ent-d1kjwa1.ent", "d1ixda_.ent-d1lpla_.ent", "d1ixda_.ent-d1m9sa2.ent", "d1ixda_.ent-d1m9sa3.ent", "d1ixda_.ent-d1pht__.ent", "d1ixda_.ent-d1vie__.ent", "d1ixda_.ent-d1ycsb2.ent", "d1ixda_.ent-d3vub__.ent", "d1ixh__.ent-d1jeta_.ent", "d1ixh__.ent-d1kwha_.ent", "d1ixh__.ent-d1lst__.ent", "d1ixh__.ent-d1m5ea_.ent", "d1ixh__.ent-d1mrp__.ent", "d1ixh__.ent-d1nh8a1.ent", "d1ixh__.ent-d1pda_1.ent", "d1ixh__.ent-d1pot__.ent", "d1ixh__.ent-d1sbp__.ent", "d1ixh__.ent-d1wdna_.ent", "d1ixh__.ent-d3mbp__.ent", "d1ixh__.ent-d3thia_.ent", "d1ixra1.ent-d1kfta_.ent", "d1iy9a_.ent-d1eg2a_.ent", "d1iy9a_.ent-d1fp1d2.ent", "d1iy9a_.ent-d1fp2a2.ent", "d1iy9a_.ent-d1g60a_.ent", "d1iy9a_.ent-d1hnna_.ent", "d1iy9a_.ent-d1i1na_.ent", "d1iy9a_.ent-d1i9ga_.ent", "d1iy9a_.ent-d1jg1a_.ent", "d1iy9a_.ent-d1kywa2.ent", "d1iy9a_.ent-d1mjfa_.ent", "d1iy9a_.ent-d1qama_.ent", "d1iy9a_.ent-d1yub__.ent", "d1iy9a_.ent-d2dpma_.ent", "d1iyga_.ent-d1kt1a1.ent", "d1iyga_.ent-d1qqea_.ent", "d1iyjb3.ent-d1ewia_.ent", "d1iyjb3.ent-d1jjcb3.ent", "d1iyjb3.ent-d1quqb_.ent", "d1iyjb5.ent-d1b3qa2.ent", "d1iyjb5.ent-d1eova1.ent", "d1iyjb5.ent-d1ewia_.ent", "d1iyjb5.ent-d1fgua1.ent", "d1iyjb5.ent-d1fgua2.ent", "d1iyjb5.ent-d1fjgl_.ent", "d1iyjb5.ent-d1i50h_.ent", "d1iyjb5.ent-d1iyjb3.ent", "d1iyjb5.ent-d1jb3a_.ent", "d1iyjb5.ent-d1jb7a2.ent", "d1iyjb5.ent-d1jjcb3.ent", "d1iyjb5.ent-d1k28a1.ent", "d1iyjb5.ent-d1quqa_.ent", "d1iyjb5.ent-d1quqb_.ent", "d1iyjb5.ent-d1sty__.ent", "d1iyjb5.ent-d3seb_1.ent", "d1iyka1.ent-d1iyka2.ent", "d1iyka1.ent-d1kzfa_.ent", "d1iyka1.ent-d1lrza2.ent", "d1iyka1.ent-d1lrza3.ent", "d1iyka1.ent-d1m4ia_.ent", "d1iyka1.ent-d1qsma_.ent", "d1iyka1.ent-d1qsta_.ent", "d1iyka2.ent-d1kzfa_.ent", "d1iyka2.ent-d1lrza2.ent", "d1iyka2.ent-d1lrza3.ent", "d1iyka2.ent-d1m4ia_.ent", "d1iyka2.ent-d1qsma_.ent", "d1iyka2.ent-d1qsta_.ent", "d1iyoa_.ent-d1l0ga_.ent", "d1iyoa_.ent-d1m40a_.ent", "d1iyoa_.ent-d1mfoa_.ent", "d1iyoa_.ent-d1mwxa3.ent", "d1iyoa_.ent-d1nj4a2.ent", "d1iyoa_.ent-d1qmea4.ent", "d1iyoa_.ent-d4blma_.ent", "d1j09a2.ent-d1jgta1.ent", "d1j09a2.ent-d1jhda2.ent", "d1j09a2.ent-d1jila_.ent", "d1j09a2.ent-d1jmva_.ent", "d1j09a2.ent-d1k4ma_.ent", "d1j09a2.ent-d1k92a1.ent", "d1j09a2.ent-d1kama_.ent", "d1j09a2.ent-d1kqna_.ent", "d1j09a2.ent-d1kqpa_.ent", "d1j09a2.ent-d1li5a2.ent", "d1j09a2.ent-d1mjha_.ent", "d1j09a2.ent-d1n3la_.ent", "d1j09a2.ent-d1o97c_.ent", "d1j09a2.ent-d1o97d1.ent", "d1j09a2.ent-d1qjca_.ent", "d1j09a2.ent-d1sur__.ent", "d1j0ha1.ent-d1ea9c1.ent", "d1j0ha1.ent-d1edqa1.ent", "d1j0ha1.ent-d1eut_1.ent", "d1j0ha1.ent-d1ji1a1.ent", "d1j0ha1.ent-d1ji2a1.ent", "d1j0ha1.ent-d1kv3a1.ent", "d1j0ha1.ent-d1m7xa1.ent", "d1j0ha1.ent-d1my7a_.ent", "d1j0ha1.ent-d1qba_1.ent", "d1j0ha1.ent-d1qfha1.ent", "d1j0ha1.ent-d1qfha2.ent", "d1j0ha1.ent-d1soxa1.ent", "d1j0ha2.ent-d1jae_1.ent", "d1j0ha2.ent-d1ji1a2.ent", "d1j0ha2.ent-d1ji2a2.ent", "d1j0ha2.ent-d1ktba1.ent", "d1j0ha2.ent-d1kwga1.ent", "d1j0ha2.ent-d1lwha1.ent", "d1j0ha2.ent-d1m7xa2.ent", "d1j0ha2.ent-d1qhoa3.ent", "d1j0ha2.ent-d1uok_1.ent", "d1j0ha2.ent-d7taa_1.ent", "d1j0ha3.ent-d7taa_2.ent", "d1j32a_.ent-d1b9ha_.ent", "d1j32a_.ent-d1bs0a_.ent", "d1j3ba2.ent-d1khba2.ent", "d1j4aa2.ent-d1l7da2.ent", "d1j4aa2.ent-d1mx3a2.ent", "d1j4aa2.ent-d1pjca2.ent", "d1j4aa2.ent-d1psda2.ent", "d1j4aa2.ent-d2naca2.ent", "d1j4wa1.ent-d1j4wa2.ent", "d1j4wa1.ent-d1k1ga_.ent", "d1j4wa1.ent-d1khma_.ent", "d1j4wa1.ent-d1vig__.ent", "d1j4wa1.ent-d2fmr__.ent", "d1j4wa2.ent-d1k1ga_.ent", "d1j4wa2.ent-d1khma_.ent", "d1j4wa2.ent-d1vig__.ent", "d1j4wa2.ent-d2fmr__.ent", "d1j54a_.ent-d1jl1a_.ent", "d1j54a_.ent-d1kcfa2.ent", "d1j54a_.ent-d1kfsa1.ent", "d1j54a_.ent-d1musa_.ent", "d1j54a_.ent-d1mwma2.ent", "d1j54a_.ent-d1qtma1.ent", "d1j54a_.ent-d1t7pa1.ent", "d1j54a_.ent-d1tgoa1.ent", "d1j54a_.ent-d1vrta1.ent", "d1j54a_.ent-d1xwl_1.ent", "d1j5pa3.ent-d1jkia2.ent", "d1j5pa3.ent-d1jn0a2.ent", "d1j5pa3.ent-d1lc0a2.ent", "d1j5pa3.ent-d1mb4a2.ent", "d1j5pa3.ent-d1qkia2.ent", "d1j5ra_.ent-d1jq5a_.ent", "d1j5ra_.ent-d1kq3a_.ent", "d1j5sa_.ent-d1cz1a_.ent", "d1j5sa_.ent-d1d3ga_.ent", "d1j5sa_.ent-d1edg__.ent", "d1j5sa_.ent-d1f8ma_.ent", "d1j5sa_.ent-d1gvoa_.ent", "d1j5sa_.ent-d1gw1a_.ent", "d1j5sa_.ent-d1iexa1.ent", "d1j5sa_.ent-d1itua_.ent", "d1j5sa_.ent-d1k4ga_.ent", "d1j5sa_.ent-d1k6wa2.ent", "d1j5sa_.ent-d1kbla1.ent", "d1j5sa_.ent-d1kwga2.ent", "d1j5sa_.ent-d1m7ja3.ent", "d1j5sa_.ent-d1muwa_.ent", "d1j6na_.ent-d1jbqa_.ent", "d1j6na_.ent-d1qopb_.ent", "d1j6na_.ent-d1tdj_1.ent", "d1j6ya_.ent-d1jvwa_.ent", "d1j6ya_.ent-d1kt1a3.ent", "d1j6ya_.ent-d1m5ya2.ent", "d1j6ya_.ent-d1m5ya3.ent", "d1j6ya_.ent-d1n1aa_.ent", "d1j6ya_.ent-d1pbk__.ent", "d1j6ya_.ent-d1pina2.ent", "d1j6za2.ent-d1az9_1.ent", "d1j6za2.ent-d1bco_2.ent", "d1j6za2.ent-d1bupa1.ent", "d1j6za2.ent-d1bupa2.ent", "d1j6za2.ent-d1czan1.ent", "d1j6za2.ent-d1e4ft1.ent", "d1j6za2.ent-d1e4ft2.ent", "d1j6za2.ent-d1j54a_.ent", "d1j6za2.ent-d1jcfa1.ent", "d1j6za2.ent-d1jj2m_.ent", "d1j6za2.ent-d1k8ka1.ent", "d1j6za2.ent-d1kcfa2.ent", "d1j6za2.ent-d1mwma1.ent", "d1j6za2.ent-d1mwma2.ent", "d1j6za2.ent-d1nbwa2.ent", "d1j6za2.ent-d1nbwa3.ent", "d1j6za2.ent-d1t7pa1.ent", "d1j6za2.ent-d1xwl_1.ent", "d1j71a_.ent-d1kzka_.ent", "d1j71a_.ent-d1lf2a_.ent", "d1j71a_.ent-d1mpp__.ent", "d1j71a_.ent-d1nsoa_.ent", "d1j71a_.ent-d2apr__.ent", "d1j71a_.ent-d2rspa_.ent", "d1j71a_.ent-d3psg__.ent", "d1j71a_.ent-d4fiv__.ent", "d1j7da_.ent-d1jata_.ent", "d1j7da_.ent-d1jatb_.ent", "d1j7da_.ent-d1kppa_.ent", "d1j7da_.ent-d1qcqa_.ent", "d1j7da_.ent-d2aak__.ent", "d1j7da_.ent-d2ucz__.ent", "d1j7na1.ent-d1j7na2.ent", "d1j7na1.ent-d1jaka2.ent", "d1j7na1.ent-d1jk3a_.ent", "d1j7na1.ent-d1k7ia2.ent", "d1j7na1.ent-d1k9xa_.ent", "d1j7na1.ent-d1kapp2.ent", "d1j7na1.ent-d1keia_.ent", "d1j7na1.ent-d1kufa_.ent", "d1j7na1.ent-d1lml__.ent", "d1j7na1.ent-d1qba_4.ent", "d1j7na1.ent-d3btaa3.ent", "d1j7na2.ent-d1jaka2.ent", "d1j7na2.ent-d1jk3a_.ent", "d1j7na2.ent-d1k7ia2.ent", "d1j7na2.ent-d1k9xa_.ent", "d1j7na2.ent-d1kapp2.ent", "d1j7na2.ent-d1keia_.ent", "d1j7na2.ent-d1kufa_.ent", "d1j7na2.ent-d1lml__.ent", "d1j7na2.ent-d1qba_4.ent", "d1j7na2.ent-d3btaa3.ent", "d1j7na3.ent-d1prta_.ent", "d1j7na3.ent-d1qs1a1.ent", "d1j7na3.ent-d1qs1a2.ent", "d1j7qa_.ent-d1k94a_.ent", "d1j7qa_.ent-d1m45a_.ent", "d1j7qa_.ent-d1psra_.ent", "d1j7qa_.ent-d1qasa1.ent", "d1j7qa_.ent-d1rec__.ent", "d1j7qa_.ent-d1sra__.ent", "d1j7qa_.ent-d2cbla1.ent", "d1j7qa_.ent-d2pvba_.ent", "d1j7qa_.ent-d2sas__.ent", "d1j7qa_.ent-d2scpa_.ent", "d1j8ca_.ent-d1k8rb_.ent", "d1j8ca_.ent-d1l7ya_.ent", "d1j8ca_.ent-d1lfda_.ent", "d1j8ca_.ent-d1lm8b_.ent", "d1j8ca_.ent-d1m94a_.ent", "d1j8ca_.ent-d1rlf__.ent", "d1j8ea_.ent-d1k7ba_.ent", "d1j8ea_.ent-d1n7da6.ent", "d1j8ea_.ent-d1n7da7.ent", "d1j8ea_.ent-d1n7daa.ent", "d1j8fa_.ent-d1jsca1.ent", "d1j8fa_.ent-d1ma3a_.ent", "d1j8fa_.ent-d1o97d2.ent", "d1j8fa_.ent-d1poxa1.ent", "d1j8fa_.ent-d1pvda1.ent", "d1j8fa_.ent-d1zpda1.ent", "d1j8mf1.ent-d1ls1a1.ent", "d1j96a_.ent-d1jeza_.ent", "d1j9ia_.ent-d1jbga_.ent", "d1j9ia_.ent-d1jjcb1.ent", "d1j9ia_.ent-d1jjcb2.ent", "d1j9oa_.ent-d1m8aa_.ent", "d1j9oa_.ent-d1qg7a_.ent", "d1j9oa_.ent-d1tvxa_.ent", "d1j9oa_.ent-d2hcc__.ent", "d1j9oa_.ent-d3il8__.ent", "d1ja1a1.ent-d1jb9a1.ent", "d1ja1a1.ent-d1krha1.ent", "d1ja1a1.ent-d1kzla1.ent", "d1ja1a1.ent-d1kzla2.ent", "d1ja1a1.ent-d1qfja1.ent", "d1ja1a1.ent-d1que_1.ent", "d1ja1a1.ent-d2cnd_1.ent", "d1ja1a1.ent-d2pia_1.ent", "d1ja1a2.ent-d1qr2a_.ent", "d1ja1a2.ent-d1rcf__.ent", "d1ja1a2.ent-d2fcr__.ent", "d1ja1a2.ent-d5nul__.ent", "d1ja1a3.ent-d1jb9a2.ent", "d1ja1a3.ent-d1krha2.ent", "d1ja1a3.ent-d1qfja2.ent", "d1ja1a3.ent-d1que_2.ent", "d1ja1a3.ent-d2cnd_2.ent", "d1ja1a3.ent-d2pia_2.ent", "d1ja9a_.ent-d1bgva1.ent", "d1ja9a_.ent-d1oaa__.ent", "d1ja9a_.ent-d1qsga_.ent", "d1ja9a_.ent-d2ae2a_.ent", "d1jae_1.ent-d1ji1a2.ent", "d1jae_1.ent-d1ji2a2.ent", "d1jae_1.ent-d1ktba1.ent", "d1jae_1.ent-d1kwga1.ent", "d1jae_1.ent-d1lwha1.ent", "d1jae_1.ent-d1m7xa2.ent", "d1jae_1.ent-d1qhoa3.ent", "d1jae_1.ent-d1uok_1.ent", "d1jae_1.ent-d7taa_1.ent", "d1jafa_.ent-d1mqva_.ent", "d1jafa_.ent-d256ba_.ent", "d1jafa_.ent-d2ccya_.ent", "d1jaja_.ent-d1jmsa4.ent", "d1jaja_.ent-d1jn3a2.ent", "d1jaja_.ent-d1knya2.ent", "d1jaka2.ent-d1jk3a_.ent", "d1jaka2.ent-d1k9da2.ent", "d1jaka2.ent-d1k9xa_.ent", "d1jaka2.ent-d1kapp2.ent", "d1jaka2.ent-d1kufa_.ent", "d1jaka2.ent-d1lml__.ent", "d1jaka2.ent-d1qba_4.ent", "d1jata_.ent-d1jatb_.ent", "d1jata_.ent-d1kppa_.ent", "d1jata_.ent-d1qcqa_.ent", "d1jata_.ent-d2aak__.ent", "d1jata_.ent-d2ucz__.ent", "d1jatb_.ent-d1kppa_.ent", "d1jatb_.ent-d1qcqa_.ent", "d1jatb_.ent-d2aak__.ent", "d1jatb_.ent-d2ucz__.ent", "d1jaya_.ent-d1bg6_2.ent", "d1jaya_.ent-d1c1da1.ent", "d1jaya_.ent-d1cf2o1.ent", "d1jaya_.ent-d1dlja2.ent", "d1jaya_.ent-d1dpga1.ent", "d1jaya_.ent-d1dssg1.ent", "d1jaya_.ent-d1e5qa1.ent", "d1jaya_.ent-d1f0ya2.ent", "d1jaya_.ent-d1hdoa_.ent", "d1jaya_.ent-d1lc0a1.ent", "d1jaya_.ent-d1lu9a1.ent", "d1jaya_.ent-d2naca1.ent", "d1jaya_.ent-d2pgd_2.ent", "d1jb0c_.ent-d1jnrb_.ent", "d1jb0c_.ent-d1keka5.ent", "d1jb0c_.ent-d1kqfb1.ent", "d1jb0c_.ent-d2fdn__.ent", "d1jb0c_.ent-d7fd1a_.ent", "d1jb0e_.ent-d1i07a_.ent", "d1jb0e_.ent-d1jo8a_.ent", "d1jb0e_.ent-d1vie__.ent", "d1jb0e_.ent-d1ycsb2.ent", "d1jb0e_.ent-d2ahjb_.ent", "d1jb0f_.ent-d1jb0i_.ent", "d1jb0f_.ent-d1jb0j_.ent", "d1jb0f_.ent-d1jb0m_.ent", "d1jb0f_.ent-d1kqfb2.ent", "d1jb0f_.ent-d1l2pa_.ent", "d1jb0f_.ent-d1m56d_.ent", "d1jb0f_.ent-d1ocrd_.ent", "d1jb0f_.ent-d1ocrg_.ent", "d1jb0f_.ent-d1ocri_.ent", "d1jb0f_.ent-d1ocrj_.ent", "d1jb0f_.ent-d1ocrk_.ent", "d1jb0f_.ent-d1ocrl_.ent", "d1jb0f_.ent-d1ocrm_.ent", "d1jb0i_.ent-d1jb0j_.ent", "d1jb0i_.ent-d1jb0m_.ent", "d1jb0i_.ent-d1kqfb2.ent", "d1jb0i_.ent-d1l2pa_.ent", "d1jb0i_.ent-d1m56d_.ent", "d1jb0i_.ent-d1ocrd_.ent", "d1jb0i_.ent-d1ocrg_.ent", "d1jb0i_.ent-d1ocri_.ent", "d1jb0i_.ent-d1ocrj_.ent", "d1jb0i_.ent-d1ocrk_.ent", "d1jb0i_.ent-d1ocrl_.ent", "d1jb0i_.ent-d1ocrm_.ent", "d1jb0j_.ent-d1jb0m_.ent", "d1jb0j_.ent-d1kqfb2.ent", "d1jb0j_.ent-d1l2pa_.ent", "d1jb0j_.ent-d1m56d_.ent", "d1jb0j_.ent-d1ocrd_.ent", "d1jb0j_.ent-d1ocrg_.ent", "d1jb0j_.ent-d1ocri_.ent", "d1jb0j_.ent-d1ocrj_.ent", "d1jb0j_.ent-d1ocrk_.ent", "d1jb0j_.ent-d1ocrl_.ent", "d1jb0j_.ent-d1ocrm_.ent", "d1jb0m_.ent-d1kqfb2.ent", "d1jb0m_.ent-d1l2pa_.ent", "d1jb0m_.ent-d1m56d_.ent", "d1jb0m_.ent-d1ocrd_.ent", "d1jb0m_.ent-d1ocrg_.ent", "d1jb0m_.ent-d1ocri_.ent", "d1jb0m_.ent-d1ocrj_.ent", "d1jb0m_.ent-d1ocrk_.ent", "d1jb0m_.ent-d1ocrl_.ent", "d1jb0m_.ent-d1ocrm_.ent", "d1jb3a_.ent-d1fjgl_.ent", "d1jb3a_.ent-d1jb7a2.ent", "d1jb3a_.ent-d1k28a1.ent", "d1jb3a_.ent-d1quqa_.ent", "d1jb3a_.ent-d1ueab_.ent", "d1jb3a_.ent-d3seb_1.ent", "d1jb7a1.ent-d1b3qa2.ent", "d1jb7a1.ent-d1d7qa_.ent", "d1jb7a1.ent-d1e1oa1.ent", "d1jb7a1.ent-d1eova1.ent", "d1jb7a1.ent-d1ewia_.ent", "d1jb7a1.ent-d1fgua1.ent", "d1jb7a1.ent-d1fgua2.ent", "d1jb7a1.ent-d1fjgl_.ent", "d1jb7a1.ent-d1fl0a_.ent", "d1jb7a1.ent-d1i50h_.ent", "d1jb7a1.ent-d1iyjb3.ent", "d1jb7a1.ent-d1iyjb5.ent", "d1jb7a1.ent-d1jb3a_.ent", "d1jb7a1.ent-d1jb7a2.ent", "d1jb7a1.ent-d1jb7a3.ent", "d1jb7a1.ent-d1jjcb3.ent", "d1jb7a1.ent-d1k28a1.ent", "d1jb7a1.ent-d1quqa_.ent", "d1jb7a1.ent-d1quqb_.ent", "d1jb7a1.ent-d1qvca_.ent", "d1jb7a1.ent-d1sty__.ent", "d1jb7a1.ent-d3seb_1.ent", "d1jb7a2.ent-d1ewia_.ent", "d1jb7a2.ent-d1fgua1.ent", "d1jb7a2.ent-d1iyjb3.ent", "d1jb7a2.ent-d1jjcb3.ent", "d1jb7a2.ent-d1k28a1.ent", "d1jb7a2.ent-d1quqa_.ent", "d1jb7a2.ent-d1quqb_.ent", "d1jb7a2.ent-d3seb_1.ent", "d1jb7a3.ent-d1b3qa2.ent", "d1jb7a3.ent-d1d7qa_.ent", "d1jb7a3.ent-d1e1oa1.ent", "d1jb7a3.ent-d1eova1.ent", "d1jb7a3.ent-d1ewia_.ent", "d1jb7a3.ent-d1fgua1.ent", "d1jb7a3.ent-d1fgua2.ent", "d1jb7a3.ent-d1fjgl_.ent", "d1jb7a3.ent-d1fl0a_.ent", "d1jb7a3.ent-d1i50h_.ent", "d1jb7a3.ent-d1iyjb3.ent", "d1jb7a3.ent-d1iyjb5.ent", "d1jb7a3.ent-d1jb3a_.ent", "d1jb7a3.ent-d1jb7a2.ent", "d1jb7a3.ent-d1jjcb3.ent", "d1jb7a3.ent-d1k28a1.ent", "d1jb7a3.ent-d1quqa_.ent", "d1jb7a3.ent-d1quqb_.ent", "d1jb7a3.ent-d1qvca_.ent", "d1jb7a3.ent-d1sty__.ent", "d1jb7a3.ent-d3seb_1.ent", "d1jb7b_.ent-d1b3qa2.ent", "d1jb7b_.ent-d1br9__.ent", "d1jb7b_.ent-d1d7qa_.ent", "d1jb7b_.ent-d1e1oa1.ent", "d1jb7b_.ent-d1eova1.ent", "d1jb7b_.ent-d1ewia_.ent", "d1jb7b_.ent-d1fgua1.ent", "d1jb7b_.ent-d1fgua2.ent", "d1jb7b_.ent-d1fjgl_.ent", "d1jb7b_.ent-d1fl0a_.ent", "d1jb7b_.ent-d1gm5a2.ent", "d1jb7b_.ent-d1go3e_.ent", "d1jb7b_.ent-d1i40a_.ent", "d1jb7b_.ent-d1i50h_.ent", "d1jb7b_.ent-d1iyjb3.ent", "d1jb7b_.ent-d1iyjb5.ent", "d1jb7b_.ent-d1jb3a_.ent", "d1jb7b_.ent-d1jb7a1.ent", "d1jb7b_.ent-d1jb7a2.ent", "d1jb7b_.ent-d1jb7a3.ent", "d1jb7b_.ent-d1je5a_.ent", "d1jb7b_.ent-d1jjcb3.ent", "d1jb7b_.ent-d1k28a1.ent", "d1jb7b_.ent-d1kxla_.ent", "d1jb7b_.ent-d1l1oc_.ent", "d1jb7b_.ent-d1quqa_.ent", "d1jb7b_.ent-d1quqb_.ent", "d1jb7b_.ent-d1qvca_.ent", "d1jb7b_.ent-d1sty__.ent", "d1jb7b_.ent-d3seb_1.ent", "d1jb9a1.ent-d1jj2b_.ent", "d1jb9a1.ent-d1kk1a1.ent", "d1jb9a1.ent-d1krha1.ent", "d1jb9a1.ent-d1kzla1.ent", "d1jb9a1.ent-d1kzla2.ent", "d1jb9a1.ent-d1n08a_.ent", "d1jb9a1.ent-d1n0ua1.ent", "d1jb9a1.ent-d1qfja1.ent", "d1jb9a1.ent-d1que_1.ent", "d1jb9a1.ent-d2cnd_1.ent", "d1jb9a1.ent-d2pia_1.ent", "d1jb9a2.ent-d1krha2.ent", "d1jb9a2.ent-d1qfja2.ent", "d1jb9a2.ent-d1que_2.ent", "d1jb9a2.ent-d2cnd_2.ent", "d1jb9a2.ent-d2pia_2.ent", "d1jbaa_.ent-d1alva_.ent", "d1jbaa_.ent-d1auib_.ent", "d1jbaa_.ent-d1df0a1.ent", "d1jbaa_.ent-d1dgua_.ent", "d1jbaa_.ent-d1eg3a1.ent", "d1jbaa_.ent-d1exra_.ent", "d1jbaa_.ent-d1g8ia_.ent", "d1jbaa_.ent-d1ggwa_.ent", "d1jbaa_.ent-d1hqva_.ent", "d1jbaa_.ent-d1jfja_.ent", "d1jbaa_.ent-d1k94a_.ent", "d1jbaa_.ent-d1m31a_.ent", "d1jbaa_.ent-d1m45a_.ent", "d1jbaa_.ent-d1ncx__.ent", "d1jbaa_.ent-d1rec__.ent", "d1jbaa_.ent-d1rro__.ent", "d1jbaa_.ent-d1sra__.ent", "d1jbaa_.ent-d1wdcb_.ent", "d1jbaa_.ent-d1wdcc_.ent", "d1jbaa_.ent-d2pvba_.ent", "d1jbaa_.ent-d2sas__.ent", "d1jbaa_.ent-d2scpa_.ent", "d1jbaa_.ent-d5pal__.ent", "d1jbga_.ent-d1jjcb1.ent", "d1jbga_.ent-d1jjcb2.ent", "d1jbqa_.ent-d1qopb_.ent", "d1jbqa_.ent-d1tdj_1.ent", "d1jcfa1.ent-d1k8ka1.ent", "d1jcfa1.ent-d1mwma1.ent", "d1jcfa1.ent-d1mwma2.ent", "d1jcfa1.ent-d1nbwa2.ent", "d1jcfa1.ent-d1nbwa3.ent", "d1jcla_.ent-d1jcxa_.ent", "d1jcla_.ent-d1l6wa_.ent", "d1jcla_.ent-d1mzha_.ent", "d1jcla_.ent-d1nal1_.ent", "d1jcla_.ent-d1o0ya_.ent", "d1jcla_.ent-d1qfea_.ent", "d1jcua_.ent-d1k4ia_.ent", "d1jcxa_.ent-d1l6wa_.ent", "d1jcxa_.ent-d1mzha_.ent", "d1jcxa_.ent-d1nal1_.ent", "d1jcxa_.ent-d1o0ya_.ent", "d1jcxa_.ent-d1qfea_.ent", "d1jd0a_.ent-d1kopa_.ent", "d1jd0a_.ent-d1mooa_.ent", "d1jd0a_.ent-d2znc__.ent", "d1jd1a_.ent-d1qd9a_.ent", "d1jd5a_.ent-d1qbha_.ent", "d1jdha_.ent-d1e8xa1.ent", "d1jdha_.ent-d1elka_.ent", "d1jdha_.ent-d1h6ka1.ent", "d1jdha_.ent-d1h6ka2.ent", "d1jdha_.ent-d1h6ka3.ent", "d1jdha_.ent-d1hf8a_.ent", "d1jdha_.ent-d1hh8a_.ent", "d1jdha_.ent-d1ho8a_.ent", "d1jdha_.ent-d1hs6a1.ent", "d1jdha_.ent-d1hz4a_.ent", "d1jdha_.ent-d1ihga1.ent", "d1jdha_.ent-d1keya_.ent", "d1jdha_.ent-d1kpsb_.ent", "d1jdha_.ent-d1kx9a_.ent", "d1jdha_.ent-d1l5ja1.ent", "d1jdha_.ent-d1ld8a_.ent", "d1jdha_.ent-d1ldja2.ent", "d1jdha_.ent-d1lrv__.ent", "d1jdha_.ent-d1lsha1.ent", "d1jdha_.ent-d1n4ka1.ent", "d1jdha_.ent-d1pbv__.ent", "d1jdha_.ent-d1qjba_.ent", "d1jdha_.ent-d1qqea_.ent", "d1jdha_.ent-d1qsaa1.ent", "d1jdpa_.ent-d1jx6a_.ent", "d1jdpa_.ent-d1jyea_.ent", "d1jdpa_.ent-d1pea__.ent", "d1jdpa_.ent-d1rpja_.ent", "d1jdpa_.ent-d2dri__.ent", "d1jdpa_.ent-d2liv__.ent", "d1jdpa_.ent-d8abp__.ent", "d1jdqa_.ent-d1je3a_.ent", "d1jdra_.ent-d1llp__.ent", "d1jdra_.ent-d1mn2__.ent", "d1jdra_.ent-d1pa2a_.ent", "d1je0a_.ent-d1jysa_.ent", "d1je0a_.ent-d1k9sa_.ent", "d1je0a_.ent-d1lam_2.ent", "d1je0a_.ent-d1lfwa1.ent", "d1je0a_.ent-d1loka_.ent", "d1je0a_.ent-d1m4la_.ent", "d1je0a_.ent-d2pth__.ent", "d1je5a_.ent-d1b3qa2.ent", "d1je5a_.ent-d1d7qa_.ent", "d1je5a_.ent-d1e1oa1.ent", "d1je5a_.ent-d1eova1.ent", "d1je5a_.ent-d1ewia_.ent", "d1je5a_.ent-d1fgua1.ent", "d1je5a_.ent-d1fgua2.ent", "d1je5a_.ent-d1fjgl_.ent", "d1je5a_.ent-d1fl0a_.ent", "d1je5a_.ent-d1gm5a2.ent", "d1je5a_.ent-d1go3e_.ent", "d1je5a_.ent-d1i40a_.ent", "d1je5a_.ent-d1i50h_.ent", "d1je5a_.ent-d1iyjb3.ent", "d1je5a_.ent-d1iyjb5.ent", "d1je5a_.ent-d1jb3a_.ent", "d1je5a_.ent-d1jb7a1.ent", "d1je5a_.ent-d1jb7a2.ent", "d1je5a_.ent-d1jb7a3.ent", "d1je5a_.ent-d1jjcb3.ent", "d1je5a_.ent-d1k28a1.ent", "d1je5a_.ent-d1l1oc_.ent", "d1je5a_.ent-d1quqa_.ent", "d1je5a_.ent-d1quqb_.ent", "d1je5a_.ent-d1qvca_.ent", "d1je5a_.ent-d1sty__.ent", "d1je5a_.ent-d3seb_1.ent", "d1jeha1.ent-d1cjca1.ent", "d1jeha1.ent-d1ebda1.ent", "d1jeha1.ent-d1ojt_1.ent", "d1jeha1.ent-d3lada1.ent", "d1jeqa1.ent-d1kcfa1.ent", "d1jeta_.ent-d1kwha_.ent", "d1jeta_.ent-d1lst__.ent", "d1jeta_.ent-d1m5ea_.ent", "d1jeta_.ent-d1mrp__.ent", "d1jeta_.ent-d1nh8a1.ent", "d1jeta_.ent-d1pda_1.ent", "d1jeta_.ent-d1pot__.ent", "d1jeta_.ent-d1sbp__.ent", "d1jeta_.ent-d1wdna_.ent", "d1jeta_.ent-d3mbp__.ent", "d1jeta_.ent-d3thia_.ent", "d1jf8a_.ent-d1phr__.ent", "d1jf9a_.ent-d1b9ha_.ent", "d1jf9a_.ent-d1bs0a_.ent", "d1jf9a_.ent-d1c7na_.ent", "d1jf9a_.ent-d1e5ea_.ent", "d1jf9a_.ent-d1gdea_.ent", "d1jf9a_.ent-d1j32a_.ent", "d1jf9a_.ent-d1kl1a_.ent", "d1jf9a_.ent-d1n8pa_.ent", "d1jf9a_.ent-d1qisa_.ent", "d1jf9a_.ent-d2ay1a_.ent", "d1jf9a_.ent-d2oata_.ent", "d1jf9a_.ent-d3tata_.ent", "d1jf9a_.ent-d7aata_.ent", "d1jfaa_.ent-d1n1ba2.ent", "d1jfaa_.ent-d1ps1a_.ent", "d1jfaa_.ent-d1uby__.ent", "d1jfaa_.ent-d5eau_2.ent", "d1jfba_.ent-d1jipa_.ent", "d1jfba_.ent-d1jpza_.ent", "d1jfba_.ent-d1lfka_.ent", "d1jfba_.ent-d1n97a_.ent", "d1jfia_.ent-d1jfib_.ent", "d1jfia_.ent-d1kx5a_.ent", "d1jfia_.ent-d1kx5b_.ent", "d1jfia_.ent-d1kx5c_.ent", "d1jfia_.ent-d1kx5d_.ent", "d1jfia_.ent-d1n1ja_.ent", "d1jfia_.ent-d1n1jb_.ent", "d1jfib_.ent-d1kx5a_.ent", "d1jfib_.ent-d1kx5b_.ent", "d1jfib_.ent-d1kx5c_.ent", "d1jfib_.ent-d1kx5d_.ent", "d1jfib_.ent-d1n1ja_.ent", "d1jfib_.ent-d1n1jb_.ent", "d1jfja_.ent-d1eg3a1.ent", "d1jfja_.ent-d1m31a_.ent", "d1jfja_.ent-d1rro__.ent", "d1jfja_.ent-d2pvba_.ent", "d1jfja_.ent-d5pal__.ent", "d1jfla1.ent-d1jfla2.ent", "d1jfla1.ent-d1ml4a2.ent", "d1jfla2.ent-d1ml4a2.ent", "d1jfma_.ent-d1k5na2.ent", "d1jfma_.ent-d1kcgc_.ent", "d1jfma_.ent-d1lqva_.ent", "d1jfma_.ent-d1zaga2.ent", "d1jfma_.ent-d3frua2.ent", "d1jfra_.ent-d1ju3a2.ent", "d1jfra_.ent-d1ku0a_.ent", "d1jfra_.ent-d1l7aa_.ent", "d1jfra_.ent-d1lzla_.ent", "d1jfra_.ent-d1mnaa_.ent", "d1jfra_.ent-d1n1ma2.ent", "d1jfra_.ent-d1qj4a_.ent", "d1jfra_.ent-d1qlwa_.ent", "d1jfra_.ent-d1qo7a_.ent", "d1jfra_.ent-d1tca__.ent", "d1jfra_.ent-d1thta_.ent", "d1jfra_.ent-d3tgl__.ent", "d1jfua_.ent-d1a8l_1.ent", "d1jfua_.ent-d1a8l_2.ent", "d1jfua_.ent-d1a8y_1.ent", "d1jfua_.ent-d1a8y_3.ent", "d1jfua_.ent-d1bed_2.ent", "d1jfua_.ent-d1bjx__.ent", "d1jfua_.ent-d1eeja1.ent", "d1jfua_.ent-d1ep7a_.ent", "d1jfua_.ent-d1erv__.ent", "d1jfua_.ent-d1f9ma_.ent", "d1jfua_.ent-d1fb6a_.ent", "d1jfua_.ent-d1fvka2.ent", "d1jfua_.ent-d1g7ea_.ent", "d1jfua_.ent-d1gh2a_.ent", "d1jfua_.ent-d1hd2a_.ent", "d1jfua_.ent-d1i5ga_.ent", "d1jfua_.ent-d1knga_.ent", "d1jfua_.ent-d1kte__.ent", "d1jfua_.ent-d1kyga_.ent", "d1jfua_.ent-d1mek__.ent", "d1jfua_.ent-d1quwa_.ent", "d1jfua_.ent-d1thx__.ent", "d1jfua_.ent-d2trxa_.ent", "d1jg1a_.ent-d1jqea_.ent", "d1jg1a_.ent-d1jsxa_.ent", "d1jg1a_.ent-d1khha_.ent", "d1jg1a_.ent-d1vid__.ent", "d1jg1a_.ent-d1xvaa_.ent", "d1jg1a_.ent-d2dpma_.ent", "d1jg1a_.ent-d3mag__.ent", "d1jgca_.ent-d1ji4a_.ent", "d1jgca_.ent-d1jiga_.ent", "d1jgca_.ent-d1jk0b_.ent", "d1jgca_.ent-d1jkva_.ent", "d1jgca_.ent-d1jqca_.ent", "d1jgca_.ent-d1kgna_.ent", "d1jgca_.ent-d1lkoa1.ent", "d1jgca_.ent-d1mtyb_.ent", "d1jgca_.ent-d1mtyd_.ent", "d1jgca_.ent-d1qgha_.ent", "d1jgca_.ent-d1rcd__.ent", "d1jgka_.ent-d1kbaa_.ent", "d1jgka_.ent-d1m9za_.ent", "d1jgka_.ent-d1tfs__.ent", "d1jgka_.ent-d1tgxa_.ent", "d1jgka_.ent-d3ebx__.ent", "d1jgsa_.ent-d1bjaa_.ent", "d1jgsa_.ent-d1bm9a_.ent", "d1jgsa_.ent-d1d5va_.ent", "d1jgsa_.ent-d1e17a_.ent", "d1jgsa_.ent-d1f1za1.ent", "d1jgsa_.ent-d1fnna1.ent", "d1jgsa_.ent-d1fp1d1.ent", "d1jgsa_.ent-d1fp2a1.ent", "d1jgsa_.ent-d1fsha_.ent", "d1jgsa_.ent-d1fzpb_.ent", "d1jgsa_.ent-d1hks__.ent", "d1jgsa_.ent-d1hsja1.ent", "d1jgsa_.ent-d1ka8a_.ent", "d1jgsa_.ent-d1ldja1.ent", "d1jgsa_.ent-d1md0a_.ent", "d1jgsa_.ent-d1repc1.ent", "d1jgsa_.ent-d1repc2.ent", "d1jgsa_.ent-d1smta_.ent", "d1jgsa_.ent-d2foka1.ent", "d1jgsa_.ent-d2foka2.ent", "d1jgsa_.ent-d2foka3.ent", "d1jgsa_.ent-d2irfg_.ent", "d1jgta1.ent-d1jhda2.ent", "d1jgta1.ent-d1jila_.ent", "d1jgta1.ent-d1jmva_.ent", "d1jgta1.ent-d1k4ma_.ent", "d1jgta1.ent-d1k92a1.ent", "d1jgta1.ent-d1kora1.ent", "d1jgta1.ent-d1kqna_.ent", "d1jgta1.ent-d1kqpa_.ent", "d1jgta1.ent-d1li5a2.ent", "d1jgta1.ent-d1mjha_.ent", "d1jgta1.ent-d1n3la_.ent", "d1jgta1.ent-d1o97c_.ent", "d1jgta1.ent-d1o97d1.ent", "d1jgta1.ent-d1qjca_.ent", "d1jgta1.ent-d1sur__.ent", "d1jgta2.ent-d1iruk_.ent", "d1jgta2.ent-d1jjwa_.ent", "d1jgta2.ent-d1kuua_.ent", "d1jgta2.ent-d1llwa3.ent", "d1jgta2.ent-d1ryp1_.ent", "d1jgta2.ent-d1ryp2_.ent", "d1jgta2.ent-d1rypa_.ent", "d1jgta2.ent-d1rypk_.ent", "d1jgta2.ent-d1rypl_.ent", "d1jh2a_.ent-d1jqba1.ent", "d1jh2a_.ent-d1kola1.ent", "d1jh2a_.ent-d1qora1.ent", "d1jhda1.ent-d1pkla1.ent", "d1jhda2.ent-d1jila_.ent", "d1jhda2.ent-d1jmva_.ent", "d1jhda2.ent-d1k4ma_.ent", "d1jhda2.ent-d1k92a1.ent", "d1jhda2.ent-d1kama_.ent", "d1jhda2.ent-d1kqna_.ent", "d1jhda2.ent-d1kqpa_.ent", "d1jhda2.ent-d1li5a2.ent", "d1jhda2.ent-d1mjha_.ent", "d1jhda2.ent-d1n3la_.ent", "d1jhda2.ent-d1o97c_.ent", "d1jhda2.ent-d1o97d1.ent", "d1jhda2.ent-d1qjca_.ent", "d1jhda2.ent-d1sur__.ent", "d1jhga_.ent-d1bjaa_.ent", "d1jhga_.ent-d1d5va_.ent", "d1jhga_.ent-d1f1za1.ent", "d1jhga_.ent-d1ka8a_.ent", "d1jhga_.ent-d1opc__.ent", "d1jhga_.ent-d1smta_.ent", "d1jhga_.ent-d2ezl__.ent", "d1jhga_.ent-d2foka3.ent", "d1jhja_.ent-d1ciy_1.ent", "d1jhja_.ent-d1cx1a_.ent", "d1jhja_.ent-d1czsa_.ent", "d1jhja_.ent-d1d7pm_.ent", "d1jhja_.ent-d1dlc_1.ent", "d1jhja_.ent-d1eut_2.ent", "d1jhja_.ent-d1gmma_.ent", "d1jhja_.ent-d1gnya_.ent", "d1jhja_.ent-d1gu3a_.ent", "d1jhja_.ent-d1guia_.ent", "d1jhja_.ent-d1h6ya_.ent", "d1jhja_.ent-d1ji6a1.ent", "d1jhja_.ent-d1ju3a1.ent", "d1jhja_.ent-d1jz8a3.ent", "d1jhja_.ent-d1k12a_.ent", "d1jhja_.ent-d1k3ia2.ent", "d1jhja_.ent-d1kexa_.ent", "d1jhja_.ent-d1kgya_.ent", "d1jhja_.ent-d1l7la_.ent", "d1jhja_.ent-d1lnsa2.ent", "d1jhja_.ent-d1xnaa_.ent", "d1jhna4.ent-d1dhkb_.ent", "d1jhna4.ent-d1dyka1.ent", "d1jhna4.ent-d1dyka2.ent", "d1jhna4.ent-d1epwa1.ent", "d1jhna4.ent-d1gv9a_.ent", "d1jhna4.ent-d1h30a1.ent", "d1jhna4.ent-d1h30a2.ent", "d1jhna4.ent-d1kit_1.ent", "d1jhna4.ent-d1kit_2.ent", "d1jhna4.ent-d1kqra_.ent", "d1jhna4.ent-d1n1ta1.ent", "d1jhna4.ent-d1nls__.ent", "d1jhna4.ent-d1saca_.ent", "d1jhna4.ent-d1xnb__.ent", "d1jhna4.ent-d2ayh__.ent", "d1jhna4.ent-d2nlra_.ent", "d1jhna4.ent-d2pela_.ent", "d1jhna4.ent-d2sli_1.ent", "d1jhna4.ent-d3btaa1.ent", "d1jhwa3.ent-d1m4ja_.ent", "d1ji1a1.ent-d1ea9c1.ent", "d1ji1a1.ent-d1edqa1.ent", "d1ji1a1.ent-d1eut_1.ent", "d1ji1a1.ent-d1ji2a1.ent", "d1ji1a1.ent-d1kv3a1.ent", "d1ji1a1.ent-d1m7xa1.ent", "d1ji1a1.ent-d1my7a_.ent", "d1ji1a1.ent-d1qba_1.ent", "d1ji1a1.ent-d1qfha1.ent", "d1ji1a1.ent-d1qfha2.ent", "d1ji1a2.ent-d1ji2a2.ent", "d1ji1a2.ent-d1ktba1.ent", "d1ji1a2.ent-d1kwga1.ent", "d1ji1a2.ent-d1lwha1.ent", "d1ji1a2.ent-d1m7xa2.ent", "d1ji1a2.ent-d1qhoa3.ent", "d1ji1a2.ent-d1uok_1.ent", "d1ji1a2.ent-d7taa_1.ent", "d1ji1a3.ent-d1b9za2.ent", "d1ji1a3.ent-d1cz1a_.ent", "d1ji1a3.ent-d1e43a2.ent", "d1ji1a3.ent-d1eh9a3.ent", "d1ji1a3.ent-d1iexa1.ent", "d1ji1a3.ent-d1j0ha3.ent", "d1ji1a3.ent-d1kwga2.ent", "d1ji1a3.ent-d1lwha2.ent", "d1ji1a3.ent-d1pama4.ent", "d1ji1a3.ent-d1qhoa4.ent", "d1ji1a3.ent-d7taa_2.ent", "d1ji2a1.ent-d1edqa1.ent", "d1ji2a1.ent-d1eut_1.ent", "d1ji2a1.ent-d1kv3a1.ent", "d1ji2a1.ent-d1m7xa1.ent", "d1ji2a1.ent-d1my7a_.ent", "d1ji2a1.ent-d1qba_1.ent", "d1ji2a1.ent-d1qfha1.ent", "d1ji2a1.ent-d1qfha2.ent", "d1ji2a2.ent-d1ktba1.ent", "d1ji2a2.ent-d1kwga1.ent", "d1ji2a2.ent-d1lwha1.ent", "d1ji2a2.ent-d1m7xa2.ent", "d1ji2a2.ent-d1qhoa3.ent", "d1ji2a2.ent-d1uok_1.ent", "d1ji2a2.ent-d7taa_1.ent", "d1ji4a_.ent-d1jiga_.ent", "d1ji4a_.ent-d1jk0b_.ent", "d1ji4a_.ent-d1jkva_.ent", "d1ji4a_.ent-d1jqca_.ent", "d1ji4a_.ent-d1kgna_.ent", "d1ji4a_.ent-d1lkoa1.ent", "d1ji4a_.ent-d1mtyb_.ent", "d1ji4a_.ent-d1mtyd_.ent", "d1ji4a_.ent-d1qgha_.ent", "d1ji4a_.ent-d1rcd__.ent", "d1ji6a1.ent-d1ciy_1.ent", "d1ji6a1.ent-d1dlc_1.ent", "d1ji6a1.ent-d1eut_2.ent", "d1ji6a1.ent-d1gmma_.ent", "d1ji6a1.ent-d1gu3a_.ent", "d1ji9a_.ent-d1jjda_.ent", "d1ji9a_.ent-d1qjka_.ent", "d1ji9a_.ent-d4mt2__.ent", "d1jida_.ent-d1kvna_.ent", "d1jida_.ent-d1lnga_.ent", "d1jiga_.ent-d1jk0b_.ent", "d1jiga_.ent-d1jkva_.ent", "d1jiga_.ent-d1jqca_.ent", "d1jiga_.ent-d1kgna_.ent", "d1jiga_.ent-d1lkoa1.ent", "d1jiga_.ent-d1mtyb_.ent", "d1jiga_.ent-d1mtyd_.ent", "d1jiga_.ent-d1qgha_.ent", "d1jiga_.ent-d1rcd__.ent", "d1jiha_.ent-d1kfsa2.ent", "d1jiha_.ent-d1khva_.ent", "d1jiha_.ent-d1mml__.ent", "d1jiha_.ent-d1mswd_.ent", "d1jiha_.ent-d1muka_.ent", "d1jiha_.ent-d1rdr__.ent", "d1jiha_.ent-d1t7pa2.ent", "d1jiha_.ent-d1tgoa2.ent", "d1jiha_.ent-d1vrta2.ent", "d1jiha_.ent-d1xwl_2.ent", "d1jila_.ent-d1jmva_.ent", "d1jila_.ent-d1k4ma_.ent", "d1jila_.ent-d1k92a1.ent", "d1jila_.ent-d1kama_.ent", "d1jila_.ent-d1kqna_.ent", "d1jila_.ent-d1kqpa_.ent", "d1jila_.ent-d1li5a2.ent", "d1jila_.ent-d1mjha_.ent", "d1jila_.ent-d1n3la_.ent", "d1jila_.ent-d1o97c_.ent", "d1jila_.ent-d1o97d1.ent", "d1jila_.ent-d1qjca_.ent", "d1jila_.ent-d1sur__.ent", "d1jipa_.ent-d1jpza_.ent", "d1jipa_.ent-d1lfka_.ent", "d1jipa_.ent-d1n97a_.ent", "d1jiwi_.ent-d1jmxa5.ent", "d1jiwi_.ent-d1k3ba_.ent", "d1jiwi_.ent-d1swua_.ent", "d1jixa_.ent-d1l5wa_.ent", "d1jj21_.ent-d1tbge_.ent", "d1jj21_.ent-d2prgc_.ent", "d1jj22_.ent-d1jj2y_.ent", "d1jj22_.ent-d1jj2z_.ent", "d1jj22_.ent-d1lkoa2.ent", "d1jj22_.ent-d1m2oa5.ent", "d1jj22_.ent-d1ocrf_.ent", "d1jj22_.ent-d1pft__.ent", "d1jj22_.ent-d1rb9__.ent", "d1jj22_.ent-d1tfi__.ent", "d1jj22_.ent-d1yua_1.ent", "d1jj22_.ent-d1yua_2.ent", "d1jj22_.ent-d1zaka2.ent", "d1jj22_.ent-d1zin_2.ent", "d1jj2a1.ent-d1jj2p_.ent", "d1jj2a1.ent-d1jj2s_.ent", "d1jj2a1.ent-d1khia1.ent", "d1jj2a1.ent-d1m1ga2.ent", "d1jj2a1.ent-d2eifa1.ent", "d1jj2b_.ent-d1kk1a1.ent", "d1jj2b_.ent-d1krha1.ent", "d1jj2b_.ent-d1kzla1.ent", "d1jj2b_.ent-d1kzla2.ent", "d1jj2b_.ent-d1n08a_.ent", "d1jj2b_.ent-d1n0ua1.ent", "d1jj2b_.ent-d1qfja1.ent", "d1jj2b_.ent-d2pia_1.ent", "d1jj2e1.ent-d1jj2e2.ent", "d1jj2e1.ent-d1rl6a1.ent", "d1jj2e1.ent-d1rl6a2.ent", "d1jj2e2.ent-d1rl6a1.ent", "d1jj2e2.ent-d1rl6a2.ent", "d1jj2f_.ent-d1tuba2.ent", "d1jj2h_.ent-d1n62b1.ent", "d1jj2h_.ent-d1qpoa2.ent", "d1jj2m_.ent-d1az9_1.ent", "d1jj2m_.ent-d1bupa1.ent", "d1jj2m_.ent-d1e4ft2.ent", "d1jj2m_.ent-d1j54a_.ent", "d1jj2m_.ent-d1mwma2.ent", "d1jj2m_.ent-d1xwl_1.ent", "d1jj2p_.ent-d1bb9__.ent", "d1jj2p_.ent-d1dj7b_.ent", "d1jj2p_.ent-d1fx7a3.ent", "d1jj2p_.ent-d1g3sa3.ent", "d1jj2p_.ent-d1gcqc_.ent", "d1jj2p_.ent-d1i07a_.ent", "d1jj2p_.ent-d1jb0e_.ent", "d1jj2p_.ent-d1jj2s_.ent", "d1jj2p_.ent-d1jo8a_.ent", "d1jj2p_.ent-d1khia1.ent", "d1jj2p_.ent-d1kjwa1.ent", "d1jj2p_.ent-d1lpla_.ent", "d1jj2p_.ent-d1m1ga2.ent", "d1jj2p_.ent-d1m9sa2.ent", "d1jj2p_.ent-d1m9sa3.ent", "d1jj2p_.ent-d1pht__.ent", "d1jj2p_.ent-d1vie__.ent", "d1jj2p_.ent-d1ycsb2.ent", "d1jj2p_.ent-d2eifa1.ent", "d1jj2s_.ent-d1bb9__.ent", "d1jj2s_.ent-d1dj7b_.ent", "d1jj2s_.ent-d1fx7a3.ent", "d1jj2s_.ent-d1g3sa3.ent", "d1jj2s_.ent-d1gcqc_.ent", "d1jj2s_.ent-d1hyoa1.ent", "d1jj2s_.ent-d1i07a_.ent", "d1jj2s_.ent-d1i1ja_.ent", "d1jj2s_.ent-d1ixda_.ent", "d1jj2s_.ent-d1jb0e_.ent", "d1jj2s_.ent-d1jj2p_.ent", "d1jj2s_.ent-d1jo8a_.ent", "d1jj2s_.ent-d1khia1.ent", "d1jj2s_.ent-d1kjwa1.ent", "d1jj2s_.ent-d1lpla_.ent", "d1jj2s_.ent-d1m1fa_.ent", "d1jj2s_.ent-d1m1ga2.ent", "d1jj2s_.ent-d1m9sa2.ent", "d1jj2s_.ent-d1m9sa3.ent", "d1jj2s_.ent-d1pht__.ent", "d1jj2s_.ent-d1vie__.ent", "d1jj2s_.ent-d1ycsb2.ent", "d1jj2s_.ent-d2eifa1.ent", "d1jj2s_.ent-d3vub__.ent", "d1jj2t_.ent-d1k3xa3.ent", "d1jj2t_.ent-d1kb2a_.ent", "d1jj2t_.ent-d1l1za3.ent", "d1jj2t_.ent-d1lata_.ent", "d1jj2t_.ent-d1lv3a_.ent", "d1jj2t_.ent-d1zfo__.ent", "d1jj2t_.ent-d2nllb_.ent", "d1jj2t_.ent-d3gata_.ent", "d1jj2t_.ent-d7gata_.ent", "d1jj2u_.ent-d1k4ta1.ent", "d1jj2u_.ent-d1lrza1.ent", "d1jj2u_.ent-d1seta1.ent", "d1jj2y_.ent-d1jj2z_.ent", "d1jj2y_.ent-d1lkoa2.ent", "d1jj2y_.ent-d1m2oa5.ent", "d1jj2y_.ent-d1ocrf_.ent", "d1jj2y_.ent-d1pft__.ent", "d1jj2y_.ent-d1rb9__.ent", "d1jj2y_.ent-d1tfi__.ent", "d1jj2y_.ent-d1yua_1.ent", "d1jj2y_.ent-d1yua_2.ent", "d1jj2y_.ent-d1zaka2.ent", "d1jj2y_.ent-d1zin_2.ent", "d1jj2z_.ent-d1lkoa2.ent", "d1jj2z_.ent-d1m2oa5.ent", "d1jj2z_.ent-d1ocrf_.ent", "d1jj2z_.ent-d1pft__.ent", "d1jj2z_.ent-d1rb9__.ent", "d1jj2z_.ent-d1tfi__.ent", "d1jj2z_.ent-d1yua_1.ent", "d1jj2z_.ent-d1yua_2.ent", "d1jj2z_.ent-d1zaka2.ent", "d1jj2z_.ent-d1zin_2.ent", "d1jjca_.ent-d1jjcb5.ent", "d1jjca_.ent-d1kmma2.ent", "d1jjca_.ent-d1qe0a2.ent", "d1jjca_.ent-d1qf6a4.ent", "d1jjca_.ent-d1seta2.ent", "d1jjcb1.ent-d1jjcb2.ent", "d1jjcb5.ent-d1kmma2.ent", "d1jjcb5.ent-d1qe0a2.ent", "d1jjcb5.ent-d1qf6a4.ent", "d1jjcb5.ent-d1seta2.ent", "d1jjda_.ent-d1qjka_.ent", "d1jjda_.ent-d4mt2__.ent", "d1jjea_.ent-d1k07a_.ent", "d1jjea_.ent-d1qh5a_.ent", "d1jjea_.ent-d1smla_.ent", "d1jjia_.ent-d1iz7a_.ent", "d1jjua4.ent-d1ea9c1.ent", "d1jjua4.ent-d1edqa1.ent", "d1jjua4.ent-d1eut_1.ent", "d1jjua4.ent-d1g0da1.ent", "d1jjua4.ent-d1j0ha1.ent", "d1jjua4.ent-d1ji1a1.ent", "d1jjua4.ent-d1ji2a1.ent", "d1jjua4.ent-d1jmxa4.ent", "d1jjua4.ent-d1kmta_.ent", "d1jjua4.ent-d1ktja_.ent", "d1jjua4.ent-d1kv3a1.ent", "d1jjua4.ent-d1m7xa1.ent", "d1jjua4.ent-d1my7a_.ent", "d1jjua4.ent-d1nepa_.ent", "d1jjua4.ent-d1qba_1.ent", "d1jjua4.ent-d1qfha1.ent", "d1jjua4.ent-d1qfha2.ent", "d1jjua4.ent-d1soxa1.ent", "d1jjub_.ent-d1jmxb_.ent", "d1jjub_.ent-d2bbkh_.ent", "d1jjwa_.ent-d1kuua_.ent", "d1jjwa_.ent-d1llwa3.ent", "d1jjwa_.ent-d1ryp1_.ent", "d1jjwa_.ent-d1ryp2_.ent", "d1jjwa_.ent-d1rypa_.ent", "d1jjwa_.ent-d1rypl_.ent", "d1jjya_.ent-d1mjga_.ent", "d1jjya_.ent-d1mjgm_.ent", "d1jk0b_.ent-d1jkva_.ent", "d1jk0b_.ent-d1jqca_.ent", "d1jk0b_.ent-d1kgna_.ent", "d1jk0b_.ent-d1lkoa1.ent", "d1jk0b_.ent-d1mtyb_.ent", "d1jk0b_.ent-d1mtyd_.ent", "d1jk0b_.ent-d1qgha_.ent", "d1jk0b_.ent-d1rcd__.ent", "d1jk3a_.ent-d1k7ia2.ent", "d1jk3a_.ent-d1k9xa_.ent", "d1jk3a_.ent-d1kapp2.ent", "d1jk3a_.ent-d1keia_.ent", "d1jk3a_.ent-d1kufa_.ent", "d1jk3a_.ent-d1lml__.ent", "d1jk3a_.ent-d1qba_4.ent", "d1jk3a_.ent-d3btaa3.ent", "d1jk7a_.ent-d1nnwa_.ent", "d1jk7a_.ent-d1ush_2.ent", "d1jk7a_.ent-d1utea_.ent", "d1jk7a_.ent-d4kbpa2.ent", "d1jkga_.ent-d1jkgb_.ent", "d1jkga_.ent-d1m98a2.ent", "d1jkga_.ent-d1mwxa1.ent", "d1jkga_.ent-d1o7nb_.ent", "d1jkga_.ent-d1qjga_.ent", "d1jkga_.ent-d3stda_.ent", "d1jkgb_.ent-d1ksia2.ent", "d1jkgb_.ent-d1ksia3.ent", "d1jkgb_.ent-d1kwia_.ent", "d1jkgb_.ent-d1m98a2.ent", "d1jkgb_.ent-d1mola_.ent", "d1jkgb_.ent-d1mwxa1.ent", "d1jkgb_.ent-d1o7nb_.ent", "d1jkgb_.ent-d1oaca2.ent", "d1jkgb_.ent-d1qjga_.ent", "d1jkgb_.ent-d1stfi_.ent", "d1jkgb_.ent-d1ugia_.ent", "d1jkgb_.ent-d3stda_.ent", "d1jkia1.ent-d1bdb__.ent", "d1jkia1.ent-d1bg6_2.ent", "d1jkia1.ent-d1bgva1.ent", "d1jkia1.ent-d1c1da1.ent", "d1jkia1.ent-d1cf2o1.ent", "d1jkia1.ent-d1dlja2.ent", "d1jkia1.ent-d1dpga1.ent", "d1jkia1.ent-d1dssg1.ent", "d1jkia1.ent-d1e5qa1.ent", "d1jkia1.ent-d1e6ua_.ent", "d1jkia1.ent-d1e7wa_.ent", "d1jkia1.ent-d1ek6a_.ent", "d1jkia1.ent-d1eno__.ent", "d1jkia1.ent-d1eny__.ent", "d1jkia1.ent-d1f0ya2.ent", "d1jkia1.ent-d1fds__.ent", "d1jkia1.ent-d1g0oa_.ent", "d1jkia1.ent-d1gcoa_.ent", "d1jkia1.ent-d1gr0a1.ent", "d1jkia1.ent-d1h5qa_.ent", "d1jkia1.ent-d1hdoa_.ent", "d1jkia1.ent-d1hdr__.ent", "d1jkia1.ent-d1hwxa1.ent", "d1jkia1.ent-d1hxha_.ent", "d1jkia1.ent-d1ja9a_.ent", "d1jkia1.ent-d1jaya_.ent", "d1jkia1.ent-d1k6xa_.ent", "d1jkia1.ent-d1kepa_.ent", "d1jkia1.ent-d1kewa_.ent", "d1jkia1.ent-d1lc0a1.ent", "d1jkia1.ent-d1llqa1.ent", "d1jkia1.ent-d1lu9a1.ent", "d1jkia1.ent-d1n2sa_.ent", "d1jkia1.ent-d1n5da_.ent", "d1jkia1.ent-d1n7ha_.ent", "d1jkia1.ent-d1oaa__.ent", "d1jkia1.ent-d1qmga2.ent", "d1jkia1.ent-d1qrra_.ent", "d1jkia1.ent-d1qsga_.ent", "d1jkia1.ent-d2ae2a_.ent", "d1jkia1.ent-d2naca1.ent", "d1jkia1.ent-d2pgd_2.ent", "d1jkia2.ent-d1jn0a2.ent", "d1jkia2.ent-d1lc0a2.ent", "d1jkia2.ent-d1mb4a2.ent", "d1jkia2.ent-d1qkia2.ent", "d1jkjb2.ent-d1kbla3.ent", "d1jkjb2.ent-d1kjqa3.ent", "d1jkjb2.ent-d1m0wa2.ent", "d1jkjb2.ent-d2hgsa4.ent", "d1jkma_.ent-d1bu8a2.ent", "d1jkma_.ent-d1cr6a2.ent", "d1jkma_.ent-d1cvl__.ent", "d1jkma_.ent-d1iz7a_.ent", "d1jkma_.ent-d1jjia_.ent", "d1jkma_.ent-d1ju3a2.ent", "d1jkma_.ent-d1l7aa_.ent", "d1jkma_.ent-d1lzla_.ent", "d1jkma_.ent-d1qlwa_.ent", "d1jkma_.ent-d1qtra_.ent", "d1jkma_.ent-d1tca__.ent", "d1jkna_.ent-d1k2ea_.ent", "d1jkna_.ent-d1ktga_.ent", "d1jkna_.ent-d1mut__.ent", "d1jksa_.ent-d1a06__.ent", "d1jksa_.ent-d1fgka_.ent", "d1jksa_.ent-d1ia9a_.ent", "d1jksa_.ent-d1iepa_.ent", "d1jksa_.ent-d1jpaa_.ent", "d1jksa_.ent-d1lufa_.ent", "d1jksa_.ent-d1phk__.ent", "d1jkva_.ent-d1jqca_.ent", "d1jkva_.ent-d1kgna_.ent", "d1jkva_.ent-d1lkoa1.ent", "d1jkva_.ent-d1mtyb_.ent", "d1jkva_.ent-d1mtyd_.ent", "d1jkva_.ent-d1qgha_.ent", "d1jkva_.ent-d1rcd__.ent", "d1jkw_1.ent-d1jkw_2.ent", "d1jkw_1.ent-d1vin_1.ent", "d1jkw_1.ent-d1vin_2.ent", "d1jkw_1.ent-d1vola1.ent", "d1jkw_2.ent-d1vin_1.ent", "d1jkw_2.ent-d1vin_2.ent", "d1jkw_2.ent-d1vola1.ent", "d1jkxa_.ent-d1meoa_.ent", "d1jkza_.ent-d1b9wa1.ent", "d1jkza_.ent-d1b9wa2.ent", "d1jkza_.ent-d1cixa_.ent", "d1jkza_.ent-d1g9pa_.ent", "d1jkza_.ent-d1h59b_.ent", "d1jkza_.ent-d1i2ua_.ent", "d1jkza_.ent-d1imt_2.ent", "d1jkza_.ent-d1jxca_.ent", "d1jkza_.ent-d1lpba2.ent", "d1jkza_.ent-d1myn__.ent", "d1jkza_.ent-d1npia_.ent", "d1jkza_.ent-d1nrb__.ent", "d1jkza_.ent-d1qkya_.ent", "d1jkza_.ent-d1sco__.ent", "d1jkza_.ent-d1scy__.ent", "d1jkza_.ent-d1sis__.ent", "d1jkza_.ent-d1tsk__.ent", "d1jkza_.ent-d2sn3__.ent", "d1jl1a_.ent-d1kcfa2.ent", "d1jl1a_.ent-d1kfsa1.ent", "d1jl1a_.ent-d1musa_.ent", "d1jl1a_.ent-d1qtma1.ent", "d1jl1a_.ent-d1t7pa1.ent", "d1jl1a_.ent-d1tgoa1.ent", "d1jl1a_.ent-d1vrta1.ent", "d1jl1a_.ent-d1xwl_1.ent", "d1jl5a_.ent-d1koha1.ent", "d1jl5a_.ent-d1m0za_.ent", "d1jl5a_.ent-d1m6ba1.ent", "d1jl5a_.ent-d1m6ba2.ent", "d1jl5a_.ent-d1n8yc1.ent", "d1jl5a_.ent-d1n8yc2.ent", "d1jl7a_.ent-d1cg5a_", "d1jl7a_.ent-d1cg5a_.ent", "d1jl7a_.ent-d1cg5b_", "d1jl7a_.ent-d1cg5b_.ent", "d1jl7a_.ent-d1ew6a_", "d1jl7a_.ent-d1ew6a_.ent", "d1jl7a_.ent-d1gcva_", "d1jl7a_.ent-d1gcva_.ent", "d1jl7a_.ent-d1gvha1", "d1jl7a_.ent-d1gvha1.ent", "d1jl7a_.ent-d1irda_", "d1jl7a_.ent-d1irda_.ent", "d1jl7a_.ent-d1irdb_", "d1jl7a_.ent-d1irdb_.ent", "d1jl7a_.ent-d1it2a_", "d1jl7a_.ent-d1it2a_.ent", "d1jl7a_.ent-d1itha_", "d1jl7a_.ent-d1itha_.ent", "d1jl7a_.ent-d1la6a_", "d1jl7a_.ent-d1la6a_.ent", "d1jl7a_.ent-d1mba__", "d1jl7a_.ent-d1mba__.ent", "d1jl7a_.ent-d3sdha_", "d1jl7a_.ent-d3sdha_.ent", "d1jl9a_.ent-d1cvua2.ent", "d1jl9a_.ent-d1hz8a1.ent", "d1jl9a_.ent-d1hz8a2.ent", "d1jl9a_.ent-d1l3ya_.ent", "d1jl9a_.ent-d1tpg_1.ent", "d1jli__.ent-d1lki__.ent", "d1jli__.ent-d1lqsl_.ent", "d1jli__.ent-d1m47a_.ent", "d1jli__.ent-d1n1fa_.ent", "d1jli__.ent-d2gmfa_.ent", "d1jli__.ent-d2ilk__.ent", "d1jlna_.ent-d1lara1.ent", "d1jlna_.ent-d1lara2.ent", "d1jlna_.ent-d1lyva_.ent", "d1jlna_.ent-d1mkp__.ent", "d1jlna_.ent-d1vhra_.ent", "d1jlna_.ent-d1yfoa_.ent", "d1jlna_.ent-d2shpa1.ent", "d1jlva1.ent-d1k0da1.ent", "d1jlva1.ent-d1k0ma1.ent", "d1jlva1.ent-d1k3ya1.ent", "d1jlva1.ent-d1ljra1.ent", "d1jlva1.ent-d1m0ua1.ent", "d1jlva1.ent-d1pd211.ent", "d1jlva1.ent-d1pmt_1.ent", "d1jlva1.ent-d2gsq_1.ent", "d1jlva1.ent-d2gsta1.ent", "d1jlxa1.ent-d1knma_.ent", "d1jlxa1.ent-d1l2ha_.ent", "d1jlxa1.ent-d1n4ka2.ent", "d1jm1a_.ent-d1o7na1.ent", "d1jm1a_.ent-d1rfs__.ent", "d1jm1a_.ent-d1rie__.ent", "d1jm6a2.ent-d1kija2.ent", "d1jm6a2.ent-d1l0oa_.ent", "d1jm6a2.ent-d1mu5a3.ent", "d1jm7a_.ent-d1jm7b_.ent", "d1jm7a_.ent-d1ldjb_.ent", "d1jm7a_.ent-d1rmd_2.ent", "d1jm7b_.ent-d1ldjb_.ent", "d1jm7b_.ent-d1rmd_2.ent", "d1jmaa_.ent-d1a2yb_.ent", "d1jmaa_.ent-d1akjd_.ent", "d1jmaa_.ent-d1b88a_.ent", "d1jmaa_.ent-d1bec_1.ent", "d1jmaa_.ent-d1bf2_1.ent", "d1jmaa_.ent-d1bqhg_.ent", "d1jmaa_.ent-d1c5ch1.ent", "d1jmaa_.ent-d1dlfh_.ent", "d1jmaa_.ent-d1dlfl_.ent", "d1jmaa_.ent-d1dqia_.ent", "d1jmaa_.ent-d1dqta_.ent", "d1jmaa_.ent-d1eaja_.ent", "d1jmaa_.ent-d1ej8a_.ent", "d1jmaa_.ent-d1fo0a_.ent", "d1jmaa_.ent-d1g4ma1.ent", "d1jmaa_.ent-d1g4ma2.ent", "d1jmaa_.ent-d1g9mh1.ent", "d1jmaa_.ent-d1grwa_.ent", "d1jmaa_.ent-d1gsma2.ent", "d1jmaa_.ent-d1h5ba_.ent", "d1jmaa_.ent-d1hxma1.ent", "d1jmaa_.ent-d1hxmb1.ent", "d1jmaa_.ent-d1i8aa_.ent", "d1jmaa_.ent-d1j0ha1.ent", "d1jmaa_.ent-d1jmxa4.ent", "d1jmaa_.ent-d1kgce2.ent", "d1jmaa_.ent-d1kmta_.ent", "d1jmaa_.ent-d1ktke1.ent", "d1jmaa_.ent-d1kxvc_.ent", "d1jmaa_.ent-d1kyfa1.ent", "d1jmaa_.ent-d1l9na1.ent", "d1jmaa_.ent-d1lla_3.ent", "d1jmaa_.ent-d1lmia_.ent", "d1jmaa_.ent-d1m1xa1.ent", "d1jmaa_.ent-d1m1xa2.ent", "d1jmaa_.ent-d1m1xa3.ent", "d1jmaa_.ent-d1m1xb1.ent", "d1jmaa_.ent-d1nepa_.ent", "d1jmaa_.ent-d1neu__.ent", "d1jmaa_.ent-d1nfdb1.ent", "d1jmaa_.ent-d1o75a1.ent", "d1jmaa_.ent-d1qfoa_.ent", "d1jmaa_.ent-d1soxa1.ent", "d1jmaa_.ent-d1tvda_.ent", "d1jmaa_.ent-d1xsoa_.ent", "d1jmaa_.ent-d2rhe__.ent", "d1jmab1.ent-d1jmab2.ent", "d1jmja_.ent-d1k9oi_.ent", "d1jmja_.ent-d1lj5a_.ent", "d1jmja_.ent-d1ovaa_.ent", "d1jmja_.ent-d1qlpa_.ent", "d1jmqa_.ent-d1o6wa2.ent", "d1jmqa_.ent-d1pina1.ent", "d1jmsa1.ent-d1jmsa3.ent", "d1jmsa1.ent-d1jyga_.ent", "d1jmsa1.ent-d1kfta_.ent", "d1jmsa1.ent-d1lb2b_.ent", "d1jmsa1.ent-d1tfr_1.ent", "d1jmsa3.ent-d1jyga_.ent", "d1jmsa3.ent-d1kfta_.ent", "d1jmsa3.ent-d1lb2b_.ent", "d1jmsa3.ent-d1tfr_1.ent", "d1jmsa4.ent-d1jn3a2.ent", "d1jmsa4.ent-d1knya2.ent", "d1jmta_.ent-d1koha2.ent", "d1jmta_.ent-d1l3ka1.ent", "d1jmta_.ent-d1l3ka2.ent", "d1jmta_.ent-d1nu4a_.ent", "d1jmta_.ent-d1qm9a1.ent", "d1jmta_.ent-d1qm9a2.ent", "d1jmta_.ent-d1u2fa_.ent", "d1jmta_.ent-d2msta_.ent", "d1jmta_.ent-d2u1a__.ent", "d1jmta_.ent-d2u2fa_.ent", "d1jmva_.ent-d1k4ma_.ent", "d1jmva_.ent-d1k92a1.ent", "d1jmva_.ent-d1kora1.ent", "d1jmva_.ent-d1kqna_.ent", "d1jmva_.ent-d1kqpa_.ent", "d1jmva_.ent-d1li5a2.ent", "d1jmva_.ent-d1mjha_.ent", "d1jmva_.ent-d1n3la_.ent", "d1jmva_.ent-d1o97c_.ent", "d1jmva_.ent-d1o97d1.ent", "d1jmva_.ent-d1qjca_.ent", "d1jmva_.ent-d1sur__.ent", "d1jmxa1.ent-d1jmxa2.ent", "d1jmxa1.ent-d1kb0a1.ent", "d1jmxa1.ent-d1mg2d_.ent", "d1jmxa1.ent-d1qksa1.ent", "d1jmxa2.ent-d1kb0a1.ent", "d1jmxa2.ent-d1mg2d_.ent", "d1jmxa2.ent-d1qksa1.ent", "d1jmxa4.ent-d1dqia_.ent", "d1jmxa4.ent-d1ea9c1.ent", "d1jmxa4.ent-d1eaja_.ent", "d1jmxa4.ent-d1edqa1.ent", "d1jmxa4.ent-d1eut_1.ent", "d1jmxa4.ent-d1grwa_.ent", "d1jmxa4.ent-d1j0ha1.ent", "d1jmxa4.ent-d1ji1a1.ent", "d1jmxa4.ent-d1ji2a1.ent", "d1jmxa4.ent-d1kgce2.ent", "d1jmxa4.ent-d1ktja_.ent", "d1jmxa4.ent-d1kv3a1.ent", "d1jmxa4.ent-d1lmia_.ent", "d1jmxa4.ent-d1m7xa1.ent", "d1jmxa4.ent-d1my7a_.ent", "d1jmxa4.ent-d1nepa_.ent", "d1jmxa4.ent-d1o75a1.ent", "d1jmxa4.ent-d1qba_1.ent", "d1jmxa4.ent-d1qfha1.ent", "d1jmxa4.ent-d1qfha2.ent", "d1jmxa4.ent-d1soxa1.ent", "d1jmxa5.ent-d1k3ba_.ent", "d1jmxa5.ent-d1swua_.ent", "d1jmxb_.ent-d1jtdb_.ent", "d1jmxb_.ent-d1k32a3.ent", "d1jmxb_.ent-d1k8kc_.ent", "d1jmxb_.ent-d1m1xa4.ent", "d1jmxb_.ent-d2bbkh_.ent", "d1jn0a2.ent-d1lc0a2.ent", "d1jn0a2.ent-d1mb4a2.ent", "d1jn0a2.ent-d1qkia2.ent", "d1jn3a2.ent-d1knya2.ent", "d1jnda2.ent-d1kfwa2.ent", "d1jnda2.ent-d1lg2a2.ent", "d1jnda2.ent-d1ll7a2.ent", "d1jnda2.ent-d1m5ya2.ent", "d1jnda2.ent-d1pina2.ent", "d1jnda2.ent-d3eipa_.ent", "d1jnk__.ent-d1a06__.ent", "d1jnk__.ent-d1apme_.ent", "d1jnk__.ent-d1b6cb_.ent", "d1jnk__.ent-d1blxa_.ent", "d1jnk__.ent-d1cjaa_.ent", "d1jnk__.ent-d1csn__.ent", "d1jnk__.ent-d1f3mc_.ent", "d1jnk__.ent-d1fgka_.ent", "d1jnk__.ent-d1fvra_.ent", "d1jnk__.ent-d1ia9a_.ent", "d1jnk__.ent-d1iepa_.ent", "d1jnk__.ent-d1jksa_.ent", "d1jnk__.ent-d1jpaa_.ent", "d1jnk__.ent-d1jvpp_.ent", "d1jnk__.ent-d1kwpa_.ent", "d1jnk__.ent-d1lpua_.ent", "d1jnk__.ent-d1lufa_.ent", "d1jnk__.ent-d1m14a_.ent", "d1jnk__.ent-d1phk__.ent", "d1jnk__.ent-d1tkia_.ent", "d1jnra1.ent-d1kf6a1.ent", "d1jnra1.ent-d1m7ka_.ent", "d1jnra1.ent-d1neka1.ent", "d1jnra1.ent-d1qlaa1.ent", "d1jnra1.ent-d1quua1.ent", "d1jnra1.ent-d1quua2.ent", "d1jnra1.ent-d2spca_.ent", "d1jnra2.ent-d1b5qa1.ent", "d1jnra2.ent-d1chua2.ent", "d1jnra2.ent-d1cjca1.ent", "d1jnra2.ent-d1d5ta1.ent", "d1jnra2.ent-d1ebda1.ent", "d1jnra2.ent-d1feca1.ent", "d1jnra2.ent-d1h6va1.ent", "d1jnra2.ent-d1jeha1.ent", "d1jnra2.ent-d1ju2a1.ent", "d1jnra2.ent-d1k0ia1.ent", "d1jnra2.ent-d1kf6a2.ent", "d1jnra2.ent-d1kssa2.ent", "d1jnra2.ent-d1l9ea1.ent", "d1jnra2.ent-d1lqta1.ent", "d1jnra2.ent-d1m6ia1.ent", "d1jnra2.ent-d1m6ia2.ent", "d1jnra2.ent-d1mo9a1.ent", "d1jnra2.ent-d1neka2.ent", "d1jnra2.ent-d1nhp_1.ent", "d1jnra2.ent-d1nhp_2.ent", "d1jnra2.ent-d1o94a2.ent", "d1jnra2.ent-d1ojt_1.ent", "d1jnra2.ent-d1qlaa2.ent", "d1jnra2.ent-d1qo8a2.ent", "d1jnra2.ent-d3grs_1.ent", "d1jnra2.ent-d3grs_2.ent", "d1jnra2.ent-d3lada1.ent", "d1jnra3.ent-d1kf6a3.ent", "d1jnra3.ent-d1kssa3.ent", "d1jnra3.ent-d1neka3.ent", "d1jnra3.ent-d1qlaa3.ent", "d1jnra3.ent-d1qo8a3.ent", "d1jnrb_.ent-d1b3ta_.ent", "d1jnrb_.ent-d1dqaa1.ent", "d1jnrb_.ent-d1ekra_.ent", "d1jnrb_.ent-d1ftra1.ent", "d1jnrb_.ent-d1ftra2.ent", "d1jnrb_.ent-d1gpja3.ent", "d1jnrb_.ent-d1h72c2.ent", "d1jnrb_.ent-d1keka5.ent", "d1jnrb_.ent-d1kqfb1.ent", "d1jnrb_.ent-d1qd1a2.ent", "d1jnrb_.ent-d1regx_.ent", "d1jnrb_.ent-d2fdn__.ent", "d1jnrb_.ent-d7fd1a_.ent", "d1jnua_.ent-d1ll8a_.ent", "d1jnua_.ent-d1lswa_.ent", "d1jnua_.ent-d1mc0a1.ent", "d1jnua_.ent-d1mkma2.ent", "d1jnua_.ent-d1mzua_.ent", "d1jnua_.ent-d1pne__.ent", "d1jnua_.ent-d3pyp__.ent", "d1jo0a_.ent-d1msza_.ent", "d1jo0a_.ent-d1qmha2.ent", "d1jo0a_.ent-d1tig__.ent", "d1jo5a_.ent-d1lgha_.ent", "d1jo5a_.ent-d1lghb_.ent", "d1jo5a_.ent-d1nkzb_.ent", "d1jo8a_.ent-d1jqqa_.ent", "d1jo8a_.ent-d1k4us_.ent", "d1jo8a_.ent-d1kjwa1.ent", "d1jo8a_.ent-d1neb__.ent", "d1jo8a_.ent-d1pht__.ent", "d1jo8a_.ent-d1pwt__.ent", "d1jo8a_.ent-d1qcfa1.ent", "d1jo8a_.ent-d1ycsb2.ent", "d1jo8a_.ent-d2hsp__.ent", "d1joca1.ent-d1vfya_.ent", "d1joya_.ent-d1nkd__.ent", "d1jp4a_.ent-d1ka1a_.ent", "d1jp4a_.ent-d1kz8a_.ent", "d1jp4a_.ent-d1lbva_.ent", "d1jp4a_.ent-d2hhma_.ent", "d1jpc__.ent-d1kj1d_.ent", "d1jpdx1.ent-d1jpma1.ent", "d1jpdx1.ent-d1muca1.ent", "d1jpdx1.ent-d1onea1.ent", "d1jpdx1.ent-d2chr_1.ent", "d1jpdx1.ent-d2mnr_1.ent", "d1jpdx2.ent-d1jpma2.ent", "d1jpdx2.ent-d1muca2.ent", "d1jpdx2.ent-d1onea2.ent", "d1jpdx2.ent-d2chr_2.ent", "d1jpdx2.ent-d2mnr_2.ent", "d1jpma1.ent-d1muca1.ent", "d1jpma1.ent-d1onea1.ent", "d1jpma1.ent-d2chr_1.ent", "d1jpma1.ent-d2mnr_1.ent", "d1jpma2.ent-d1muca2.ent", "d1jpma2.ent-d1onea2.ent", "d1jpma2.ent-d2chr_2.ent", "d1jpma2.ent-d2mnr_2.ent", "d1jpya_.ent-d1m4ua_.ent", "d1jpya_.ent-d1m4ul_.ent", "d1jpya_.ent-d1pdga_.ent", "d1jpya_.ent-d2tgi__.ent", "d1jpza_.ent-d1lfka_.ent", "d1jpza_.ent-d1n97a_.ent", "d1jq4a_.ent-d1jroa2.ent", "d1jq4a_.ent-d1kf6b2.ent", "d1jq4a_.ent-d1krha3.ent", "d1jq4a_.ent-d1l5pa_.ent", "d1jq4a_.ent-d1n62a2.ent", "d1jq4a_.ent-d1nekb2.ent", "d1jq4a_.ent-d1put__.ent", "d1jq4a_.ent-d1qlab2.ent", "d1jq4a_.ent-d2pia_3.ent", "d1jq5a_.ent-d1kq3a_.ent", "d1jqba1.ent-d1kola1.ent", "d1jqba1.ent-d1qora1.ent", "d1jqca_.ent-d1kgna_.ent", "d1jqca_.ent-d1lkoa1.ent", "d1jqca_.ent-d1mtyb_.ent", "d1jqca_.ent-d1mtyd_.ent", "d1jqca_.ent-d1qgha_.ent", "d1jqca_.ent-d1rcd__.ent", "d1jqea_.ent-d1eg2a_.ent", "d1jqea_.ent-d1fp1d2.ent", "d1jqea_.ent-d1fp2a2.ent", "d1jqea_.ent-d1g60a_.ent", "d1jqea_.ent-d1hnna_.ent", "d1jqea_.ent-d1i1na_.ent", "d1jqea_.ent-d1i9ga_.ent", "d1jqea_.ent-d1iy9a_.ent", "d1jqea_.ent-d1jg1a_.ent", "d1jqea_.ent-d1jsxa_.ent", "d1jqea_.ent-d1khha_.ent", "d1jqea_.ent-d1kywa2.ent", "d1jqea_.ent-d1mjfa_.ent", "d1jqea_.ent-d1qama_.ent", "d1jqea_.ent-d1vid__.ent", "d1jqea_.ent-d1xvaa_.ent", "d1jqea_.ent-d1yub__.ent", "d1jqea_.ent-d2dpma_.ent", "d1jqea_.ent-d3mag__.ent", "d1jqga1.ent-d1kwma1.ent", "d1jqga1.ent-d1lam_2.ent", "d1jqga1.ent-d1lfwa1.ent", "d1jqga1.ent-d1loka_.ent", "d1jqga1.ent-d1m4la_.ent", "d1jqga1.ent-d1obr__.ent", "d1jqga2.ent-d1kn6a_.ent", "d1jqga2.ent-d1kwma2.ent", "d1jqga2.ent-d1scjb_.ent", "d1jqia1.ent-d3mdda1.ent", "d1jqia2.ent-d3mdda2.ent", "d1jqna_.ent-d1ccwb_.ent", "d1jqna_.ent-d1cz1a_.ent", "d1jqna_.ent-d1d3ga_.ent", "d1jqna_.ent-d1e4mm_.ent", "d1jqna_.ent-d1edg__.ent", "d1jqna_.ent-d1eexa_.ent", "d1jqna_.ent-d1eswa_.ent", "d1jqna_.ent-d1f8ma_.ent", "d1jqna_.ent-d1g5aa2.ent", "d1jqna_.ent-d1gjwa2.ent", "d1jqna_.ent-d1gqia1.ent", "d1jqna_.ent-d1gvoa_.ent", "d1jqna_.ent-d1gw1a_.ent", "d1jqna_.ent-d1iexa1.ent", "d1jqna_.ent-d1itua_.ent", "d1jqna_.ent-d1j5sa_.ent", "d1jqna_.ent-d1jqoa_.ent", "d1jqna_.ent-d1k4ga_.ent", "d1jqna_.ent-d1kbla1.ent", "d1jqna_.ent-d1kwga2.ent", "d1jqna_.ent-d1llwa2.ent", "d1jqna_.ent-d1m7ja3.ent", "d1jqna_.ent-d1muwa_.ent", "d1jqna_.ent-d1ntha_.ent", "d1jqna_.ent-d7reqa1.ent", "d1jqoa_.ent-d1kbla1.ent", "d1jqqa_.ent-d1k4us_.ent", "d1jqqa_.ent-d1kjwa1.ent", "d1jqqa_.ent-d1neb__.ent", "d1jqqa_.ent-d1pht__.ent", "d1jqqa_.ent-d1pwt__.ent", "d1jqqa_.ent-d1qcfa1.ent", "d1jqqa_.ent-d1ycsb2.ent", "d1jqqa_.ent-d2hsp__.ent", "d1jr3a1.ent-d1jr3d1.ent", "d1jr7a_.ent-d1juha_.ent", "d1jr7a_.ent-d1lrha_.ent", "d1jr7a_.ent-d1m4oa_.ent", "d1jr7a_.ent-d1pmi__.ent", "d1jr7a_.ent-d1qjea_.ent", "d1jr7a_.ent-d1wapa_.ent", "d1jr7a_.ent-d2arca_.ent", "d1jr8a_.ent-d1k04a_.ent", "d1jr8a_.ent-d1knya1.ent", "d1jr8a_.ent-d1ls1a1.ent", "d1jr8a_.ent-d1nfn__.ent", "d1jr8a_.ent-d1nlxa_.ent", "d1jr8a_.ent-d256ba_.ent", "d1jr8a_.ent-d2a0b__.ent", "d1jr8a_.ent-d2liga_.ent", "d1jr8a_.ent-d2mhr__.ent", "d1jr8a_.ent-d3fapb_.ent", "d1jroa2.ent-d1kf6b2.ent", "d1jroa2.ent-d1krha3.ent", "d1jroa2.ent-d1l5pa_.ent", "d1jroa2.ent-d1n62a2.ent", "d1jroa2.ent-d1nekb2.ent", "d1jroa2.ent-d1put__.ent", "d1jroa2.ent-d1qlab2.ent", "d1jroa2.ent-d2pia_3.ent", "d1jroa3.ent-d1n62c1.ent", "d1jroa4.ent-d1n62c2.ent", "d1jroa4.ent-d1uxy_1.ent", "d1jrob1.ent-d1n62b1.ent", "d1js1x1.ent-d1js1x2.ent", "d1js1x1.ent-d1ml4a1.ent", "d1js1x1.ent-d1ml4a2.ent", "d1js1x1.ent-d1otha1.ent", "d1js1x1.ent-d1otha2.ent", "d1js1x2.ent-d1ml4a1.ent", "d1js1x2.ent-d1ml4a2.ent", "d1js1x2.ent-d1otha1.ent", "d1js1x2.ent-d1otha2.ent", "d1js3a_.ent-d1ajsa_.ent", "d1js3a_.ent-d1b9ha_.ent", "d1js3a_.ent-d1bs0a_.ent", "d1js3a_.ent-d1c4ka2.ent", "d1js3a_.ent-d1c7na_.ent", "d1js3a_.ent-d1e5ea_.ent", "d1js3a_.ent-d1gdea_.ent", "d1js3a_.ent-d1gtxa_.ent", "d1js3a_.ent-d1j32a_.ent", "d1js3a_.ent-d1jf9a_.ent", "d1js3a_.ent-d1kl1a_.ent", "d1js3a_.ent-d1lc5a_.ent", "d1js3a_.ent-d1m7ya_.ent", "d1js3a_.ent-d1n8pa_.ent", "d1js3a_.ent-d1qisa_.ent", "d1js3a_.ent-d1qj5a_.ent", "d1js3a_.ent-d1tpla_.ent", "d1js3a_.ent-d1yaaa_.ent", "d1js3a_.ent-d2ay1a_.ent", "d1js3a_.ent-d2dkb__.ent", "d1js3a_.ent-d2gsaa_.ent", "d1js3a_.ent-d2oata_.ent", "d1js3a_.ent-d3tata_.ent", "d1js3a_.ent-d7aata_.ent", "d1js8a1.ent-d1lla_2.ent", "d1jsca1.ent-d1ma3a_.ent", "d1jsca1.ent-d1o97d2.ent", "d1jsca1.ent-d1poxa1.ent", "d1jsca1.ent-d1pvda1.ent", "d1jsca1.ent-d1zpda1.ent", "d1jsca2.ent-d1jsca3.ent", "d1jsca2.ent-d1keka1.ent", "d1jsca2.ent-d1keka2.ent", "d1jsca2.ent-d1l8aa1.ent", "d1jsca2.ent-d1l8aa2.ent", "d1jsca2.ent-d1poxa2.ent", "d1jsca2.ent-d1poxa3.ent", "d1jsca2.ent-d1pvda2.ent", "d1jsca2.ent-d1pvda3.ent", "d1jsca2.ent-d1zpda2.ent", "d1jsca2.ent-d1zpda3.ent", "d1jsca3.ent-d1keka1.ent", "d1jsca3.ent-d1keka2.ent", "d1jsca3.ent-d1l8aa1.ent", "d1jsca3.ent-d1l8aa2.ent", "d1jsca3.ent-d1poxa2.ent", "d1jsca3.ent-d1poxa3.ent", "d1jsca3.ent-d1pvda2.ent", "d1jsca3.ent-d1pvda3.ent", "d1jsca3.ent-d1zpda2.ent", "d1jsca3.ent-d1zpda3.ent", "d1jsda_.ent-d1jsma_.ent", "d1jsda_.ent-d1qhda2.ent", "d1jsda_.ent-d2viua_.ent", "d1jsma_.ent-d1qhda2.ent", "d1jsma_.ent-d2viua_.ent", "d1jssa_.ent-d1kcma_.ent", "d1jssa_.ent-d1ln1a_.ent", "d1jsxa_.ent-d1khha_.ent", "d1jsxa_.ent-d1vid__.ent", "d1jsxa_.ent-d1xvaa_.ent", "d1jsxa_.ent-d2dpma_.ent", "d1jsxa_.ent-d3mag__.ent", "d1jt6a1.ent-d1b72a_.ent", "d1jt6a1.ent-d1b8ia_.ent", "d1jt6a1.ent-d1bl0a2.ent", "d1jt6a1.ent-d1bw5__.ent", "d1jt6a1.ent-d1d5ya2.ent", "d1jt6a1.ent-d1e3oc1.ent", "d1jt6a1.ent-d1fexa_.ent", "d1jt6a1.ent-d1fjla_.ent", "d1jt6a1.ent-d1g2ha_.ent", "d1jt6a1.ent-d1hlva1.ent", "d1jt6a1.ent-d1hlva2.ent", "d1jt6a1.ent-d1ig7a_.ent", "d1jt6a1.ent-d1irza_.ent", "d1jt6a1.ent-d1iufa2.ent", "d1jt6a1.ent-d1k61a_.ent", "d1jt6a1.ent-d1k78a1.ent", "d1jt6a1.ent-d1k78a2.ent", "d1jt6a1.ent-d2tct_1.ent", "d1jtaa_.ent-d1k5ca_.ent", "d1jtaa_.ent-d1qcxa_.ent", "d1jtaa_.ent-d1qjva_.ent", "d1jtaa_.ent-d1qq1a_.ent", "d1jtaa_.ent-d1rmg__.ent", "d1jtdb_.ent-d1k32a3.ent", "d1jtdb_.ent-d1k8kc_.ent", "d1jtdb_.ent-d1m1xa4.ent", "d1jtdb_.ent-d2bbkh_.ent", "d1ju2a1.ent-d1b5qa1.ent", "d1ju2a1.ent-d1chua2.ent", "d1ju2a1.ent-d1cjca1.ent", "d1ju2a1.ent-d1d5ta1.ent", "d1ju2a1.ent-d1ebda1.ent", "d1ju2a1.ent-d1feca1.ent", "d1ju2a1.ent-d1h6va1.ent", "d1ju2a1.ent-d1jeha1.ent", "d1ju2a1.ent-d1k0ia1.ent", "d1ju2a1.ent-d1kf6a2.ent", "d1ju2a1.ent-d1kssa2.ent", "d1ju2a1.ent-d1l9ea1.ent", "d1ju2a1.ent-d1lqta1.ent", "d1ju2a1.ent-d1m6ia1.ent", "d1ju2a1.ent-d1m6ia2.ent", "d1ju2a1.ent-d1mo9a1.ent", "d1ju2a1.ent-d1neka2.ent", "d1ju2a1.ent-d1nhp_1.ent", "d1ju2a1.ent-d1nhp_2.ent", "d1ju2a1.ent-d1o94a2.ent", "d1ju2a1.ent-d1ojt_1.ent", "d1ju2a1.ent-d1qlaa2.ent", "d1ju2a1.ent-d1qo8a2.ent", "d1ju2a1.ent-d3grs_1.ent", "d1ju2a1.ent-d3grs_2.ent", "d1ju2a1.ent-d3lada1.ent", "d1ju2a2.ent-d1k0ia2.ent", "d1ju2a2.ent-d1kdga2.ent", "d1ju2a2.ent-d1l9ea2.ent", "d1ju2a2.ent-d1mxta2.ent", "d1ju3a1.ent-d1bhga2.ent", "d1ju3a1.ent-d1ciy_1.ent", "d1ju3a1.ent-d1cx1a_.ent", "d1ju3a1.ent-d1czsa_.ent", "d1ju3a1.ent-d1d7pm_.ent", "d1ju3a1.ent-d1dlc_1.ent", "d1ju3a1.ent-d1eut_2.ent", "d1ju3a1.ent-d1gmma_.ent", "d1ju3a1.ent-d1gnya_.ent", "d1ju3a1.ent-d1gqpa_.ent", "d1ju3a1.ent-d1gu3a_.ent", "d1ju3a1.ent-d1guia_.ent", "d1ju3a1.ent-d1h6ya_.ent", "d1ju3a1.ent-d1i5pa1.ent", "d1ju3a1.ent-d1jhja_.ent", "d1ju3a1.ent-d1ji6a1.ent", "d1ju3a1.ent-d1jz8a3.ent", "d1ju3a1.ent-d1k12a_.ent", "d1ju3a1.ent-d1k3ia2.ent", "d1ju3a1.ent-d1k42a_.ent", "d1ju3a1.ent-d1kexa_.ent", "d1ju3a1.ent-d1kgya_.ent", "d1ju3a1.ent-d1l7la_.ent", "d1ju3a1.ent-d1lnsa2.ent", "d1ju3a1.ent-d1xnaa_.ent", "d1ju3a2.ent-d1bu8a2.ent", "d1ju3a2.ent-d1cr6a2.ent", "d1ju3a2.ent-d1cvl__.ent", "d1ju3a2.ent-d1iz7a_.ent", "d1ju3a2.ent-d1jjia_.ent", "d1ju3a2.ent-d1ku0a_.ent", "d1ju3a2.ent-d1l7aa_.ent", "d1ju3a2.ent-d1lzla_.ent", "d1ju3a2.ent-d1mnaa_.ent", "d1ju3a2.ent-d1n1ma2.ent", "d1ju3a2.ent-d1qj4a_.ent", "d1ju3a2.ent-d1qlwa_.ent", "d1ju3a2.ent-d1qo7a_.ent", "d1ju3a2.ent-d1qtra_.ent", "d1ju3a2.ent-d1tca__.ent", "d1ju3a2.ent-d1thta_.ent", "d1ju3a2.ent-d3tgl__.ent", "d1ju5a_.ent-d1jwoa_.ent", "d1ju5a_.ent-d1jyra_.ent", "d1ju5a_.ent-d1lkka_.ent", "d1ju5a_.ent-d1luia_.ent", "d1ju5a_.ent-d1mil__.ent", "d1ju5a_.ent-d1qada_.ent", "d1ju5a_.ent-d2abl_2.ent", "d1ju5a_.ent-d2cbla3.ent", "d1ju5a_.ent-d2plda_.ent", "d1ju5a_.ent-d2shpa3.ent", "d1juha_.ent-d1lrha_.ent", "d1juha_.ent-d1m4oa_.ent", "d1juha_.ent-d1pmi__.ent", "d1juha_.ent-d1wapa_.ent", "d1juha_.ent-d2arca_.ent", "d1juha_.ent-d2phla1.ent", "d1juha_.ent-d2phla2.ent", "d1jv1a_.ent-d1k4va_.ent", "d1jv1a_.ent-d1kwsa_.ent", "d1jv1a_.ent-d1ll2a_.ent", "d1jv1a_.ent-d1lzja_.ent", "d1jv1a_.ent-d1nf5b_.ent", "d1jv1a_.ent-d1qg8a_.ent", "d1jv4a_.ent-d1koia_.ent", "d1jv4a_.ent-d1kqwa_.ent", "d1jv4a_.ent-d1lf7a_.ent", "d1jv4a_.ent-d1o1va_.ent", "d1jv4a_.ent-d1qfta_.ent", "d1jv4a_.ent-d1qqsa_.ent", "d1jvaa2.ent-d1jvaa3.ent", "d1jvna1.ent-d1km3a_.ent", "d1jvna1.ent-d1kv8a_.ent", "d1jvna1.ent-d1nsj__.ent", "d1jvna1.ent-d1pii_1.ent", "d1jvna1.ent-d1pii_2.ent", "d1jvna1.ent-d1qopa_.ent", "d1jvna1.ent-d1rpxa_.ent", "d1jvna1.ent-d1thfd_.ent", "d1jvpp_.ent-d1a06__.ent", "d1jvpp_.ent-d1fgka_.ent", "d1jvpp_.ent-d1ia9a_.ent", "d1jvpp_.ent-d1iepa_.ent", "d1jvpp_.ent-d1jksa_.ent", "d1jvpp_.ent-d1jpaa_.ent", "d1jvpp_.ent-d1lufa_.ent", "d1jvpp_.ent-d1phk__.ent", "d1jvr__.ent-d1mn8a_.ent", "d1jvwa_.ent-d1kt1a3.ent", "d1jvwa_.ent-d1m5ya2.ent", "d1jvwa_.ent-d1m5ya3.ent", "d1jvwa_.ent-d1n1aa_.ent", "d1jvwa_.ent-d1pbk__.ent", "d1jvwa_.ent-d1pina2.ent", "d1jw2a_.ent-d1mtyg_.ent", "d1jw2a_.ent-d1om2a_.ent", "d1jwia_.ent-d1b08a1.ent", "d1jwia_.ent-d1b6e__.ent", "d1jwia_.ent-d1cwva5.ent", "d1jwia_.ent-d1e87a_.ent", "d1jwia_.ent-d1f00i3.ent", "d1jwia_.ent-d1fvub_.ent", "d1jwia_.ent-d1g1ta1.ent", "d1jwia_.ent-d1h8ua_.ent", "d1jwia_.ent-d1li1a1.ent", "d1jwia_.ent-d1li1a2.ent", "d1jwia_.ent-d1prtb2.ent", "d1jwia_.ent-d1tsg__.ent", "d1jwib_.ent-d1b08a1.ent", "d1jwib_.ent-d1b6e__.ent", "d1jwib_.ent-d1cwva5.ent", "d1jwib_.ent-d1e87a_.ent", "d1jwib_.ent-d1f00i3.ent", "d1jwib_.ent-d1fvub_.ent", "d1jwib_.ent-d1g1ta1.ent", "d1jwib_.ent-d1h8ua_.ent", "d1jwib_.ent-d1jwia_.ent", "d1jwib_.ent-d1li1a1.ent", "d1jwib_.ent-d1li1a2.ent", "d1jwib_.ent-d1prtb2.ent", "d1jwib_.ent-d1tsg__.ent", "d1jwoa_.ent-d1jyra_.ent", "d1jwoa_.ent-d1lkka_.ent", "d1jwoa_.ent-d1luia_.ent", "d1jwoa_.ent-d1mil__.ent", "d1jwoa_.ent-d1qada_.ent", "d1jwoa_.ent-d2abl_2.ent", "d1jwoa_.ent-d2cbla3.ent", "d1jwoa_.ent-d2plda_.ent", "d1jwoa_.ent-d2shpa3.ent", "d1jwwa_.ent-d1k0va_.ent", "d1jwwa_.ent-d1mwza_.ent", "d1jwyb_.ent-d1a7j__.ent", "d1jwyb_.ent-d1cr1a_.ent", "d1jwyb_.ent-d1e69a_.ent", "d1jwyb_.ent-d1f5na2.ent", "d1jwyb_.ent-d1fnna2.ent", "d1jwyb_.ent-d1g8ya_.ent", "d1jwyb_.ent-d1gm5a3.ent", "d1jwyb_.ent-d1lv7a_.ent", "d1jwyb_.ent-d1m6na3.ent", "d1jx6a_.ent-d1jyea_.ent", "d1jx6a_.ent-d1pea__.ent", "d1jx6a_.ent-d1rpja_.ent", "d1jx6a_.ent-d2dri__.ent", "d1jx6a_.ent-d2liv__.ent", "d1jx6a_.ent-d8abp__.ent", "d1jxca_.ent-d1myn__.ent", "d1jxca_.ent-d1npia_.ent", "d1jxca_.ent-d1nrb__.ent", "d1jxca_.ent-d1qkya_.ent", "d1jxca_.ent-d1sco__.ent", "d1jxca_.ent-d1scy__.ent", "d1jxca_.ent-d1sis__.ent", "d1jxca_.ent-d1tsk__.ent", "d1jxca_.ent-d2sn3__.ent", "d1jxha_.ent-d1l2la_.ent", "d1jxha_.ent-d1lhpa_.ent", "d1jxha_.ent-d1liia_.ent", "d1jxha_.ent-d1o14a_.ent", "d1jxha_.ent-d1rkd__.ent", "d1jyea_.ent-d1pea__.ent", "d1jyea_.ent-d1rpja_.ent", "d1jyea_.ent-d2dri__.ent", "d1jyea_.ent-d2liv__.ent", "d1jyea_.ent-d8abp__.ent", "d1jyga_.ent-d1kfta_.ent", "d1jyga_.ent-d1lb2b_.ent", "d1jyga_.ent-d1tfr_1.ent", "d1jyoa_.ent-d1k3ea_.ent", "d1jyoa_.ent-d1k8kd1.ent", "d1jyoa_.ent-d1l2wi_.ent", "d1jyra_.ent-d1lkka_.ent", "d1jyra_.ent-d1luia_.ent", "d1jyra_.ent-d1mil__.ent", "d1jyra_.ent-d1qada_.ent", "d1jyra_.ent-d2abl_2.ent", "d1jyra_.ent-d2cbla3.ent", "d1jyra_.ent-d2plda_.ent", "d1jyra_.ent-d2shpa3.ent", "d1jysa_.ent-d1k9sa_.ent", "d1jz8a1.ent-d1jz8a2.ent", "d1jz8a3.ent-d1bhga2.ent", "d1jz8a3.ent-d1ciy_1.ent", "d1jz8a3.ent-d1cx1a_.ent", "d1jz8a3.ent-d1czsa_.ent", "d1jz8a3.ent-d1d7pm_.ent", "d1jz8a3.ent-d1dlc_1.ent", "d1jz8a3.ent-d1eut_2.ent", "d1jz8a3.ent-d1gmma_.ent", "d1jz8a3.ent-d1gnya_.ent", "d1jz8a3.ent-d1gqpa_.ent", "d1jz8a3.ent-d1gu3a_.ent", "d1jz8a3.ent-d1guia_.ent", "d1jz8a3.ent-d1h6ya_.ent", "d1jz8a3.ent-d1i5pa1.ent", "d1jz8a3.ent-d1jhja_.ent", "d1jz8a3.ent-d1ji6a1.ent", "d1jz8a3.ent-d1k12a_.ent", "d1jz8a3.ent-d1k3ia2.ent", "d1jz8a3.ent-d1k42a_.ent", "d1jz8a3.ent-d1kexa_.ent", "d1jz8a3.ent-d1kgya_.ent", "d1jz8a3.ent-d1l7la_.ent", "d1jz8a3.ent-d1lnsa2.ent", "d1jz8a3.ent-d1xnaa_.ent", "d1jz8a4.ent-d1lf6a2.ent", "d1jz8a4.ent-d1n7oa3.ent", "d1jz8a4.ent-d1nsza_.ent", "d1jzga_.ent-d1kcw_1.ent", "d1jzga_.ent-d1kcw_2.ent", "d1jzga_.ent-d1kv7a1.ent", "d1jzga_.ent-d1kv7a2.ent", "d1jzga_.ent-d1kv7a3.ent", "d1jzga_.ent-d1kzqa1.ent", "d1jzga_.ent-d1l9qa1.ent", "d1jzga_.ent-d1l9qa2.ent", "d1jzga_.ent-d2cbp__.ent", "d1jzga_.ent-d2cuaa_.ent", "d1k04a_.ent-d1knya1.ent", "d1k04a_.ent-d1ls1a1.ent", "d1k04a_.ent-d1nfn__.ent", "d1k04a_.ent-d1nlxa_.ent", "d1k04a_.ent-d256ba_.ent", "d1k04a_.ent-d2a0b__.ent", "d1k04a_.ent-d2liga_.ent", "d1k04a_.ent-d2mhr__.ent", "d1k04a_.ent-d3fapb_.ent", "d1k07a_.ent-d1qh5a_.ent", "d1k07a_.ent-d1smla_.ent", "d1k0da1.ent-d1k0ma1.ent", "d1k0da1.ent-d1k3ya1.ent", "d1k0da1.ent-d1ljra1.ent", "d1k0da1.ent-d1m0ua1.ent", "d1k0da1.ent-d1pd211.ent", "d1k0da1.ent-d1pmt_1.ent", "d1k0da1.ent-d2gsq_1.ent", "d1k0da1.ent-d2gsta1.ent", "d1k0ia1.ent-d1chua2.ent", "d1k0ia1.ent-d1cjca1.ent", "d1k0ia1.ent-d1ebda1.ent", "d1k0ia1.ent-d1feca1.ent", "d1k0ia1.ent-d1h6va1.ent", "d1k0ia1.ent-d1jeha1.ent", "d1k0ia1.ent-d1kssa2.ent", "d1k0ia1.ent-d1l9ea1.ent", "d1k0ia1.ent-d1lqta1.ent", "d1k0ia1.ent-d1m6ia1.ent", "d1k0ia1.ent-d1m6ia2.ent", "d1k0ia1.ent-d1mo9a1.ent", "d1k0ia1.ent-d1nhp_1.ent", "d1k0ia1.ent-d1nhp_2.ent", "d1k0ia1.ent-d1o94a2.ent", "d1k0ia1.ent-d1ojt_1.ent", "d1k0ia1.ent-d3grs_1.ent", "d1k0ia1.ent-d3grs_2.ent", "d1k0ia1.ent-d3lada1.ent", "d1k0ia2.ent-d1kdga2.ent", "d1k0ia2.ent-d1l9ea2.ent", "d1k0ia2.ent-d1mxta2.ent", "d1k0ma1.ent-d1k3ya1.ent", "d1k0ma1.ent-d1ljra1.ent", "d1k0ma1.ent-d1m0ua1.ent", "d1k0ma1.ent-d1pd211.ent", "d1k0ma1.ent-d1pmt_1.ent", "d1k0ma1.ent-d2gsq_1.ent", "d1k0ma1.ent-d2gsta1.ent", "d1k0ma2.ent-d1aqwa2.ent", "d1k0ma2.ent-d1e6ba2.ent", "d1k0ma2.ent-d1fhe_2.ent", "d1k0ma2.ent-d1iloa_.ent", "d1k0ma2.ent-d1k3ya2.ent", "d1k0ra2.ent-d1k0ra3.ent", "d1k0ra2.ent-d1mkya3.ent", "d1k0ra2.ent-d3proc1.ent", "d1k0ra2.ent-d3proc2.ent", "d1k0ra3.ent-d1mkya3.ent", "d1k0ra3.ent-d3proc1.ent", "d1k0ra3.ent-d3proc2.ent", "d1k0va_.ent-d1mwza_.ent", "d1k12a_.ent-d1ciy_1.ent", "d1k12a_.ent-d1cx1a_.ent", "d1k12a_.ent-d1dlc_1.ent", "d1k12a_.ent-d1eut_2.ent", "d1k12a_.ent-d1gmma_.ent", "d1k12a_.ent-d1gnya_.ent", "d1k12a_.ent-d1gu3a_.ent", "d1k12a_.ent-d1guia_.ent", "d1k12a_.ent-d1h6ya_.ent", "d1k12a_.ent-d1ji6a1.ent", "d1k12a_.ent-d1k3ia2.ent", "d1k12a_.ent-d1kexa_.ent", "d1k12a_.ent-d1kgya_.ent", "d1k12a_.ent-d1l7la_.ent", "d1k12a_.ent-d1lnsa2.ent", "d1k12a_.ent-d1xnaa_.ent", "d1k1aa_.ent-d1k3zd_.ent", "d1k1aa_.ent-d1myo__.ent", "d1k1aa_.ent-d1n11a_.ent", "d1k1aa_.ent-d1sw6a_.ent", "d1k1aa_.ent-d1ycsb1.ent", "d1k1ca_.ent-d1opd__.ent", "d1k1ca_.ent-d1pch__.ent", "d1k1ca_.ent-d1ptf__.ent", "d1k1da1.ent-d1k6wa1.ent", "d1k1da1.ent-d1m7ja1.ent", "d1k1da1.ent-d1m7ja2.ent", "d1k1da1.ent-d4ubpc1.ent", "d1k1ea_.ent-d1l6ra_.ent", "d1k1ea_.ent-d1mh9a_.ent", "d1k1ea_.ent-d1qq5a_.ent", "d1k1ea_.ent-d1zrn__.ent", "d1k1ga_.ent-d1khma_.ent", "d1k1ga_.ent-d1vig__.ent", "d1k1ga_.ent-d2fmr__.ent", "d1k24a_.ent-d1kmoa_.ent", "d1k24a_.ent-d1mm4a_.ent", "d1k24a_.ent-d1qj8a_.ent", "d1k24a_.ent-d1qjpa_.ent", "d1k24a_.ent-d2mpra_.ent", "d1k24a_.ent-d2por__.ent", "d1k28a1.ent-d1quqa_.ent", "d1k28a1.ent-d3seb_1.ent", "d1k28a3.ent-d1qgia_.ent", "d1k28a3.ent-d1qsaa2.ent", "d1k28a3.ent-d1qusa_.ent", "d1k28a3.ent-d217l__.ent", "d1k28a3.ent-d2eql__.ent", "d1k28a3.ent-d3lzt__.ent", "d1k2ea_.ent-d1ktga_.ent", "d1k2ea_.ent-d1mut__.ent", "d1k2fa_.ent-d1lb6a_.ent", "d1k2yx1.ent-d1k2yx2.ent", "d1k2yx1.ent-d1k2yx3.ent", "d1k2yx1.ent-d1kfia1.ent", "d1k2yx1.ent-d1kfia2.ent", "d1k2yx1.ent-d3pmga1.ent", "d1k2yx1.ent-d3pmga2.ent", "d1k2yx1.ent-d3pmga3.ent", "d1k2yx2.ent-d1k2yx3.ent", "d1k2yx2.ent-d1kfia1.ent", "d1k2yx2.ent-d1kfia2.ent", "d1k2yx2.ent-d3pmga1.ent", "d1k2yx2.ent-d3pmga2.ent", "d1k2yx2.ent-d3pmga3.ent", "d1k2yx3.ent-d1kfia1.ent", "d1k2yx3.ent-d1kfia2.ent", "d1k2yx3.ent-d3pmga1.ent", "d1k2yx3.ent-d3pmga2.ent", "d1k2yx3.ent-d3pmga3.ent", "d1k2yx4.ent-d1kcma_.ent", "d1k2yx4.ent-d1kfia4.ent", "d1k2yx4.ent-d1ko9a2.ent", "d1k2yx4.ent-d1ln1a_.ent", "d1k2yx4.ent-d1mpga2.ent", "d1k2yx4.ent-d1ytba1.ent", "d1k2yx4.ent-d3pmga4.ent", "d1k32a1.ent-d1kwaa_.ent", "d1k32a1.ent-d1lcya1.ent", "d1k32a1.ent-d1m5za_.ent", "d1k32a1.ent-d1mfga_.ent", "d1k32a1.ent-d1qaua_.ent", "d1k32a1.ent-d1qava_.ent", "d1k32a1.ent-d1qlca_.ent", "d1k32a2.ent-d1kit_3.ent", "d1k32a2.ent-d3sil__.ent", "d1k32a3.ent-d1k8kc_.ent", "d1k32a3.ent-d1m1xa4.ent", "d1k32a3.ent-d2bbkh_.ent", "d1k32a4.ent-d1mj3a_.ent", "d1k32a4.ent-d1nzya_.ent", "d1k32a4.ent-d1o8ua_.ent", "d1k32a4.ent-d1tyfa_.ent", "d1k3ba_.ent-d1swua_.ent", "d1k3ea_.ent-d1k8kd1.ent", "d1k3ea_.ent-d1l2wi_.ent", "d1k3ia2.ent-d1ciy_1.ent", "d1k3ia2.ent-d1cx1a_.ent", "d1k3ia2.ent-d1czsa_.ent", "d1k3ia2.ent-d1d7pm_.ent", "d1k3ia2.ent-d1dlc_1.ent", "d1k3ia2.ent-d1eut_2.ent", "d1k3ia2.ent-d1gmma_.ent", "d1k3ia2.ent-d1gnya_.ent", "d1k3ia2.ent-d1gu3a_.ent", "d1k3ia2.ent-d1guia_.ent", "d1k3ia2.ent-d1h6ya_.ent", "d1k3ia2.ent-d1i5pa1.ent", "d1k3ia2.ent-d1jhja_.ent", "d1k3ia2.ent-d1ji6a1.ent", "d1k3ia2.ent-d1k12a_.ent", "d1k3ia2.ent-d1kexa_.ent", "d1k3ia2.ent-d1kgya_.ent", "d1k3ia2.ent-d1l7la_.ent", "d1k3ia2.ent-d1lnsa2.ent", "d1k3ia2.ent-d1xnaa_.ent", "d1k3ka_.ent-d1maz__.ent", "d1k3pa_.ent-d1o7xa_.ent", "d1k3ra2.ent-d1mxia_.ent", "d1k3xa1.ent-d1k82a1.ent", "d1k3xa1.ent-d1l1za1.ent", "d1k3xa1.ent-d1mu5a1.ent", "d1k3xa1.ent-d1nnja1.ent", "d1k3xa2.ent-d1k82a2.ent", "d1k3xa2.ent-d1l1za2.ent", "d1k3xa2.ent-d1nnja2.ent", "d1k3xa3.ent-d1kb2a_.ent", "d1k3xa3.ent-d1l1za3.ent", "d1k3xa3.ent-d1lata_.ent", "d1k3xa3.ent-d1lv3a_.ent", "d1k3xa3.ent-d1zfo__.ent", "d1k3xa3.ent-d2nllb_.ent", "d1k3xa3.ent-d3gata_.ent", "d1k3xa3.ent-d7gata_.ent", "d1k3ya1.ent-d1ljra1.ent", "d1k3ya1.ent-d1m0ua1.ent", "d1k3ya1.ent-d1pd211.ent", "d1k3ya1.ent-d1pmt_1.ent", "d1k3ya1.ent-d2gsq_1.ent", "d1k3ya1.ent-d2gsta1.ent", "d1k3ya2.ent-d1aqwa2.ent", "d1k3ya2.ent-d1iloa_.ent", "d1k3zd_.ent-d1myo__.ent", "d1k3zd_.ent-d1n11a_.ent", "d1k3zd_.ent-d1sw6a_.ent", "d1k3zd_.ent-d1ycsb1.ent", "d1k42a_.ent-d1ciy_1.ent", "d1k42a_.ent-d1cx1a_.ent", "d1k42a_.ent-d1czsa_.ent", "d1k42a_.ent-d1d7pm_.ent", "d1k42a_.ent-d1dlc_1.ent", "d1k42a_.ent-d1eut_2.ent", "d1k42a_.ent-d1gmma_.ent", "d1k42a_.ent-d1gnya_.ent", "d1k42a_.ent-d1gu3a_.ent", "d1k42a_.ent-d1guia_.ent", "d1k42a_.ent-d1h6ya_.ent", "d1k42a_.ent-d1i5pa1.ent", "d1k42a_.ent-d1jhja_.ent", "d1k42a_.ent-d1ji6a1.ent", "d1k42a_.ent-d1k12a_.ent", "d1k42a_.ent-d1k3ia2.ent", "d1k42a_.ent-d1kexa_.ent", "d1k42a_.ent-d1xnaa_.ent", "d1k44a_.ent-d1nhkl_.ent", "d1k4ga_.ent-d1d3ga_.ent", "d1k4ga_.ent-d1gvoa_.ent", "d1k4ga_.ent-d1itua_.ent", "d1k4ga_.ent-d1kbla1.ent", "d1k4ga_.ent-d1m7ja3.ent", "d1k4ma_.ent-d1k92a1.ent", "d1k4ma_.ent-d1kama_.ent", "d1k4ma_.ent-d1kqna_.ent", "d1k4ma_.ent-d1kqpa_.ent", "d1k4ma_.ent-d1li5a2.ent", "d1k4ma_.ent-d1mjha_.ent", "d1k4ma_.ent-d1n3la_.ent", "d1k4ma_.ent-d1o97c_.ent", "d1k4ma_.ent-d1o97d1.ent", "d1k4ma_.ent-d1qjca_.ent", "d1k4ma_.ent-d1sur__.ent", "d1k4ta1.ent-d1lrza1.ent", "d1k4ta1.ent-d1seta1.ent", "d1k4us_.ent-d1kjwa1.ent", "d1k4us_.ent-d1neb__.ent", "d1k4us_.ent-d1pht__.ent", "d1k4us_.ent-d1pwt__.ent", "d1k4us_.ent-d1qcfa1.ent", "d1k4us_.ent-d1ycsb2.ent", "d1k4us_.ent-d2hsp__.ent", "d1k4va_.ent-d1kwsa_.ent", "d1k4va_.ent-d1ll2a_.ent", "d1k4va_.ent-d1lzja_.ent", "d1k4va_.ent-d1nf5b_.ent", "d1k4va_.ent-d1qg8a_.ent", "d1k4ya_.ent-d1ac5__.ent", "d1k4ya_.ent-d1bu8a2.ent", "d1k4ya_.ent-d1cpy__.ent", "d1k4ya_.ent-d1cr6a2.ent", "d1k4ya_.ent-d1cvl__.ent", "d1k4ya_.ent-d1hlga_.ent", "d1k4ya_.ent-d1ivya_.ent", "d1k4ya_.ent-d1iz7a_.ent", "d1k4ya_.ent-d1jjia_.ent", "d1k4ya_.ent-d1jkma_.ent", "d1k4ya_.ent-d1ju3a2.ent", "d1k4ya_.ent-d1ku0a_.ent", "d1k4ya_.ent-d1l7aa_.ent", "d1k4ya_.ent-d1lnsa3.ent", "d1k4ya_.ent-d1lzla_.ent", "d1k4ya_.ent-d1qe3a_.ent", "d1k4ya_.ent-d1qlwa_.ent", "d1k4ya_.ent-d1qo7a_.ent", "d1k4ya_.ent-d1qtra_.ent", "d1k4ya_.ent-d1tca__.ent", "d1k4za_.ent-d1k5ca_.ent", "d1k4za_.ent-d1llwa1.ent", "d1k4za_.ent-d1qcxa_.ent", "d1k4za_.ent-d1qq1a_.ent", "d1k5ca_.ent-d1llwa1.ent", "d1k5ca_.ent-d1qcxa_.ent", "d1k5ca_.ent-d1qjva_.ent", "d1k5ca_.ent-d1qq1a_.ent", "d1k5ca_.ent-d1rmg__.ent", "d1k5db_.ent-d1ki1b2.ent", "d1k5db_.ent-d1mai__.ent", "d1k5db_.ent-d1mixa2.ent", "d1k5db_.ent-d1mkea1.ent", "d1k5db_.ent-d1pls__.ent", "d1k5db_.ent-d1qqga1.ent", "d1k5db_.ent-d1qqga2.ent", "d1k5db_.ent-d1shca_.ent", "d1k5ja_.ent-d1m3ya1.ent", "d1k5ja_.ent-d1m3ya2.ent", "d1k5ja_.ent-d1pgs_1.ent", "d1k5ja_.ent-d1pgs_2.ent", "d1k5ja_.ent-d1phm_1.ent", "d1k5ja_.ent-d1phm_2.ent", "d1k5ja_.ent-d1ruxa1.ent", "d1k5ja_.ent-d1ruxa2.ent", "d1k5ma_.ent-d1aym2_.ent", "d1k5ma_.ent-d1b35a_.ent", "d1k5ma_.ent-d1b35b_.ent", "d1k5ma_.ent-d1b35c_.ent", "d1k5ma_.ent-d1bev1_.ent", "d1k5ma_.ent-d1bev3_.ent", "d1k5ma_.ent-d1pvc1_.ent", "d1k5ma_.ent-d1tmf1_.ent", "d1k5ma_.ent-d2mev1_.ent", "d1k5ma_.ent-d2mev2_.ent", "d1k5na2.ent-d1kcgc_.ent", "d1k5na2.ent-d1lqva_.ent", "d1k5na2.ent-d1zaga2.ent", "d1k5na2.ent-d3frua2.ent", "d1k5wa_.ent-d1qasa2.ent", "d1k5wa_.ent-d1rlw__.ent", "d1k5wa_.ent-d1rsy__.ent", "d1k5wa_.ent-d3rpba_.ent", "d1k61a_.ent-d1e3oc1.ent", "d1k61a_.ent-d1fexa_.ent", "d1k61a_.ent-d1ig7a_.ent", "d1k6da_.ent-d1poia_.ent", "d1k6da_.ent-d1poib_.ent", "d1k6wa1.ent-d1m7ja1.ent", "d1k6wa1.ent-d1m7ja2.ent", "d1k6wa1.ent-d4ubpc1.ent", "d1k6wa2.ent-d1m7ja3.ent", "d1k6xa_.ent-d1bdb__.ent", "d1k6xa_.ent-d1bg6_2.ent", "d1k6xa_.ent-d1bgva1.ent", "d1k6xa_.ent-d1c1da1.ent", "d1k6xa_.ent-d1cf2o1.ent", "d1k6xa_.ent-d1dlja2.ent", "d1k6xa_.ent-d1dpga1.ent", "d1k6xa_.ent-d1dssg1.ent", "d1k6xa_.ent-d1e5qa1.ent", "d1k6xa_.ent-d1e6ua_.ent", "d1k6xa_.ent-d1e7wa_.ent", "d1k6xa_.ent-d1eno__.ent", "d1k6xa_.ent-d1eny__.ent", "d1k6xa_.ent-d1f0ya2.ent", "d1k6xa_.ent-d1fds__.ent", "d1k6xa_.ent-d1g0oa_.ent", "d1k6xa_.ent-d1gcoa_.ent", "d1k6xa_.ent-d1gr0a1.ent", "d1k6xa_.ent-d1h5qa_.ent", "d1k6xa_.ent-d1hdoa_.ent", "d1k6xa_.ent-d1hdr__.ent", "d1k6xa_.ent-d1hwxa1.ent", "d1k6xa_.ent-d1hxha_.ent", "d1k6xa_.ent-d1ja9a_.ent", "d1k6xa_.ent-d1jaya_.ent", "d1k6xa_.ent-d1lc0a1.ent", "d1k6xa_.ent-d1llqa1.ent", "d1k6xa_.ent-d1lu9a1.ent", "d1k6xa_.ent-d1n2sa_.ent", "d1k6xa_.ent-d1n5da_.ent", "d1k6xa_.ent-d1oaa__.ent", "d1k6xa_.ent-d1qmga2.ent", "d1k6xa_.ent-d1qsga_.ent", "d1k6xa_.ent-d2ae2a_.ent", "d1k6xa_.ent-d2naca1.ent", "d1k6xa_.ent-d2pgd_2.ent", "d1k78a1.ent-d1b8ia_.ent", "d1k78a1.ent-d1bl0a2.ent", "d1k78a1.ent-d1e3oc1.ent", "d1k78a1.ent-d1fexa_.ent", "d1k78a1.ent-d1g2ha_.ent", "d1k78a1.ent-d1ig7a_.ent", "d1k78a1.ent-d1k61a_.ent", "d1k78a1.ent-d1k78a2.ent", "d1k78a2.ent-d1e3oc1.ent", "d1k78a2.ent-d1fexa_.ent", "d1k78a2.ent-d1ig7a_.ent", "d1k78a2.ent-d1k61a_.ent", "d1k7ba_.ent-d1n7da6.ent", "d1k7ba_.ent-d1n7da7.ent", "d1k7ba_.ent-d1n7daa.ent", "d1k7ca_.ent-d1cex__.ent", "d1k7ca_.ent-d1cf9a1.ent", "d1k7ca_.ent-d1e5da1.ent", "d1k7ca_.ent-d1es9a_.ent", "d1k7ca_.ent-d1euca2.ent", "d1k7ca_.ent-d1f2va_.ent", "d1k7ca_.ent-d1f4pa_.ent", "d1k7ca_.ent-d1f8ya_.ent", "d1k7ca_.ent-d1fuea_.ent", "d1k7ca_.ent-d1fyea_.ent", "d1k7ca_.ent-d1g66a_.ent", "d1k7ca_.ent-d1h05a_.ent", "d1k7ca_.ent-d1iexa2.ent", "d1k7ca_.ent-d1kwga3.ent", "d1k7ca_.ent-d1l7da2.ent", "d1k7ca_.ent-d1qo0d_.ent", "d1k7ca_.ent-d2naca2.ent", "d1k7ca_.ent-d7reqb2.ent", "d1k7ia2.ent-d1k9xa_.ent", "d1k7ia2.ent-d1kapp2.ent", "d1k7ia2.ent-d1keia_.ent", "d1k7ia2.ent-d1kufa_.ent", "d1k7ia2.ent-d1lml__.ent", "d1k7ia2.ent-d3btaa3.ent", "d1k82a1.ent-d1l1za1.ent", "d1k82a1.ent-d1mu5a1.ent", "d1k82a1.ent-d1nnja1.ent", "d1k82a2.ent-d1l1za2.ent", "d1k82a2.ent-d1nnja2.ent", "d1k8ka1.ent-d1mwma1.ent", "d1k8ka1.ent-d1mwma2.ent", "d1k8ka1.ent-d1nbwa2.ent", "d1k8ka1.ent-d1nbwa3.ent", "d1k8kc_.ent-d1m1xa4.ent", "d1k8kc_.ent-d1tbga_.ent", "d1k8kc_.ent-d2bbkh_.ent", "d1k8kd1.ent-d1l2wi_.ent", "d1k8ma_.ent-d1kjqa1.ent", "d1k8ma_.ent-d1lac__.ent", "d1k8ma_.ent-d1qjoa_.ent", "d1k8rb_.ent-d1fm0d_.ent", "d1k8rb_.ent-d1l7ya_.ent", "d1k8rb_.ent-d1lfda_.ent", "d1k8rb_.ent-d1lm8b_.ent", "d1k8rb_.ent-d1m94a_.ent", "d1k8rb_.ent-d1rlf__.ent", "d1k92a1.ent-d1kora1.ent", "d1k92a1.ent-d1kqna_.ent", "d1k92a1.ent-d1kqpa_.ent", "d1k92a1.ent-d1li5a2.ent", "d1k92a1.ent-d1mjha_.ent", "d1k92a1.ent-d1n3la_.ent", "d1k92a1.ent-d1o97c_.ent", "d1k92a1.ent-d1o97d1.ent", "d1k92a1.ent-d1qjca_.ent", "d1k92a1.ent-d1sur__.ent", "d1k94a_.ent-d1eg3a1.ent", "d1k94a_.ent-d1exra_.ent", "d1k94a_.ent-d1ggwa_.ent", "d1k94a_.ent-d1jfja_.ent", "d1k94a_.ent-d1m31a_.ent", "d1k94a_.ent-d1m45a_.ent", "d1k94a_.ent-d1ncx__.ent", "d1k94a_.ent-d1psra_.ent", "d1k94a_.ent-d1qasa1.ent", "d1k94a_.ent-d1rec__.ent", "d1k94a_.ent-d1rro__.ent", "d1k94a_.ent-d1sra__.ent", "d1k94a_.ent-d1wdcb_.ent", "d1k94a_.ent-d1wdcc_.ent", "d1k94a_.ent-d2cbla1.ent", "d1k94a_.ent-d2pvba_.ent", "d1k94a_.ent-d2sas__.ent", "d1k94a_.ent-d2scpa_.ent", "d1k94a_.ent-d5pal__.ent", "d1k99a_.ent-d1lwma_.ent", "d1k99a_.ent-d1qrva_.ent", "d1k99a_.ent-d2lefa_.ent", "d1k9da1.ent-d1b9za2.ent", "d1k9da1.ent-d1bf2_3.ent", "d1k9da1.ent-d1cbg__.ent", "d1k9da1.ent-d1cz1a_.ent", "d1k9da1.ent-d1e43a2.ent", "d1k9da1.ent-d1e4ia_.ent", "d1k9da1.ent-d1e4mm_.ent", "d1k9da1.ent-d1eh9a3.ent", "d1k9da1.ent-d1eswa_.ent", "d1k9da1.ent-d1hxja_.ent", "d1k9da1.ent-d1iexa1.ent", "d1k9da1.ent-d1j0ha3.ent", "d1k9da1.ent-d1ji1a3.ent", "d1k9da1.ent-d1kwga2.ent", "d1k9da1.ent-d1lwha2.ent", "d1k9da1.ent-d1pama4.ent", "d1k9da1.ent-d1qba_3.ent", "d1k9da1.ent-d1qhoa4.ent", "d1k9da1.ent-d1qvba_.ent", "d1k9da1.ent-d1uok_2.ent", "d1k9da1.ent-d7taa_2.ent", "d1k9da2.ent-d1qba_4.ent", "d1k9ja_.ent-d1b08a1.ent", "d1k9ja_.ent-d1b6e__.ent", "d1k9ja_.ent-d1byfa_.ent", "d1k9ja_.ent-d1cwva5.ent", "d1k9ja_.ent-d1dv8a_.ent", "d1k9ja_.ent-d1e87a_.ent", "d1k9ja_.ent-d1egia_.ent", "d1k9ja_.ent-d1f00i3.ent", "d1k9ja_.ent-d1fvub_.ent", "d1k9ja_.ent-d1g1ta1.ent", "d1k9ja_.ent-d1h8ua_.ent", "d1k9ja_.ent-d1hq8a_.ent", "d1k9ja_.ent-d1jwia_.ent", "d1k9ja_.ent-d1jwib_.ent", "d1k9ja_.ent-d1li1a1.ent", "d1k9ja_.ent-d1li1a2.ent", "d1k9ja_.ent-d1prtb2.ent", "d1k9ja_.ent-d1qo3c_.ent", "d1k9ja_.ent-d1tsg__.ent", "d1k9oi_.ent-d1lj5a_.ent", "d1k9oi_.ent-d1ovaa_.ent", "d1k9oi_.ent-d1qlpa_.ent", "d1k9vf_.ent-d1ka9h_.ent", "d1k9vf_.ent-d1kwga3.ent", "d1k9vf_.ent-d1l9xa_.ent", "d1k9vf_.ent-d1qdlb_.ent", "d1k9xa_.ent-d1kapp2.ent", "d1k9xa_.ent-d1keia_.ent", "d1k9xa_.ent-d1kufa_.ent", "d1k9xa_.ent-d1lml__.ent", "d1k9xa_.ent-d1qba_4.ent", "d1k9xa_.ent-d3btaa3.ent", "d1ka1a_.ent-d1kz8a_.ent", "d1ka1a_.ent-d1lbva_.ent", "d1ka1a_.ent-d2hhma_.ent", "d1ka8a_.ent-d1bjaa_.ent", "d1ka8a_.ent-d1d5va_.ent", "d1ka8a_.ent-d1e17a_.ent", "d1ka8a_.ent-d1f1za1.ent", "d1ka8a_.ent-d1fsha_.ent", "d1ka8a_.ent-d1ldja1.ent", "d1ka8a_.ent-d1opc__.ent", "d1ka8a_.ent-d1smta_.ent", "d1ka8a_.ent-d2ezl__.ent", "d1ka8a_.ent-d2foka3.ent", "d1ka9h_.ent-d1kwga3.ent", "d1ka9h_.ent-d1l9xa_.ent", "d1ka9h_.ent-d1qdlb_.ent", "d1kaca_.ent-d1kkea1.ent", "d1kaca_.ent-d1qhva_.ent", "d1kama_.ent-d1kqna_.ent", "d1kama_.ent-d1li5a2.ent", "d1kama_.ent-d1n3la_.ent", "d1kama_.ent-d1qjca_.ent", "d1kapp2.ent-d1keia_.ent", "d1kapp2.ent-d1kufa_.ent", "d1kapp2.ent-d1lml__.ent", "d1kapp2.ent-d1qba_4.ent", "d1kapp2.ent-d3btaa3.ent", "d1kas_1.ent-d1m3ka1.ent", "d1kas_1.ent-d1m3ka2.ent", "d1kas_1.ent-d1mzja1.ent", "d1kas_1.ent-d1mzja2.ent", "d1kb0a1.ent-d1mg2d_.ent", "d1kb0a1.ent-d1qksa1.ent", "d1kb2a_.ent-d1l1za3.ent", "d1kb2a_.ent-d1lata_.ent", "d1kb2a_.ent-d1lv3a_.ent", "d1kb2a_.ent-d1zfo__.ent", "d1kb2a_.ent-d2nllb_.ent", "d1kb2a_.ent-d3gata_.ent", "d1kb2a_.ent-d7gata_.ent", "d1kbaa_.ent-d1m9za_.ent", "d1kbaa_.ent-d1tfs__.ent", "d1kbaa_.ent-d1tgxa_.ent", "d1kbaa_.ent-d3ebx__.ent", "d1kbea_.ent-d1ptq__.ent", "d1kbia1.ent-d1llwa2.ent", "d1kbia1.ent-d1o94a1.ent", "d1kbia1.ent-d1oyb__.ent", "d1kbia1.ent-d2dora_.ent", "d1kbla1.ent-d1d3ga_.ent", "d1kbla1.ent-d1gvoa_.ent", "d1kbla1.ent-d1m7ja3.ent", "d1kbla2.ent-d1kid__.ent", "d1kbla2.ent-d1l5ja2.ent", "d1kbla2.ent-d1nbwa1.ent", "d1kbla3.ent-d1kjqa3.ent", "d1kbla3.ent-d1m0wa2.ent", "d1kbla3.ent-d2hgsa4.ent", "d1kbva1.ent-d1ikop_.ent", "d1kbva1.ent-d1kbva2.ent", "d1kbva1.ent-d1kcw_2.ent", "d1kbva1.ent-d1kcw_6.ent", "d1kbva1.ent-d1kv7a1.ent", "d1kbva1.ent-d1qhqa_.ent", "d1kbva2.ent-d1ikop_.ent", "d1kbva2.ent-d1kcw_2.ent", "d1kbva2.ent-d1kcw_6.ent", "d1kbva2.ent-d1kv7a1.ent", "d1kbva2.ent-d1qhqa_.ent", "d1kc6a_.ent-d1knva_.ent", "d1kc6a_.ent-d1m0da_.ent", "d1kc6a_.ent-d1vsra_.ent", "d1kc6a_.ent-d2foka4.ent", "d1kc6a_.ent-d3pvia_.ent", "d1kcfa2.ent-d1az9_1.ent", "d1kcfa2.ent-d1bupa1.ent", "d1kcfa2.ent-d1bupa2.ent", "d1kcfa2.ent-d1e4ft1.ent", "d1kcfa2.ent-d1e4ft2.ent", "d1kcfa2.ent-d1j54a_.ent", "d1kcfa2.ent-d1jj2m_.ent", "d1kcfa2.ent-d1kfsa1.ent", "d1kcfa2.ent-d1musa_.ent", "d1kcfa2.ent-d1mwma2.ent", "d1kcfa2.ent-d1nbwa3.ent", "d1kcfa2.ent-d1qtma1.ent", "d1kcfa2.ent-d1t7pa1.ent", "d1kcfa2.ent-d1tgoa1.ent", "d1kcfa2.ent-d1vrta1.ent", "d1kcfa2.ent-d1xwl_1.ent", "d1kcgc_.ent-d1lqva_.ent", "d1kcgc_.ent-d1zaga2.ent", "d1kcgc_.ent-d3frua2.ent", "d1kcma_.ent-d1ko9a2.ent", "d1kcma_.ent-d1ln1a_.ent", "d1kcma_.ent-d1mpga2.ent", "d1kcma_.ent-d1ytba1.ent", "d1kcma_.ent-d3pmga4.ent", "d1kcw_1.ent-d1cyx__.ent", "d1kcw_1.ent-d1e30a_.ent", "d1kcw_1.ent-d1gw0a1.ent", "d1kcw_1.ent-d1gw0a2.ent", "d1kcw_1.ent-d1hfua2.ent", "d1kcw_1.ent-d1ikop_.ent", "d1kcw_1.ent-d1kbva1.ent", "d1kcw_1.ent-d1kbva2.ent", "d1kcw_1.ent-d1kcw_2.ent", "d1kcw_1.ent-d1kcw_4.ent", "d1kcw_1.ent-d1kcw_5.ent", "d1kcw_1.ent-d1kcw_6.ent", "d1kcw_1.ent-d1kv7a1.ent", "d1kcw_1.ent-d1kv7a2.ent", "d1kcw_1.ent-d1kv7a3.ent", "d1kcw_1.ent-d1kzqa1.ent", "d1kcw_1.ent-d1l9qa1.ent", "d1kcw_1.ent-d1l9qa2.ent", "d1kcw_1.ent-d1m56b1.ent", "d1kcw_1.ent-d1qhqa_.ent", "d1kcw_1.ent-d2cbp__.ent", "d1kcw_1.ent-d2cuaa_.ent", "d1kcw_2.ent-d1ikop_.ent", "d1kcw_2.ent-d1kv7a1.ent", "d1kcw_2.ent-d1kv7a2.ent", "d1kcw_2.ent-d1kv7a3.ent", "d1kcw_2.ent-d1kzqa1.ent", "d1kcw_2.ent-d1l9qa1.ent", "d1kcw_2.ent-d1l9qa2.ent", "d1kcw_2.ent-d1qhqa_.ent", "d1kcw_2.ent-d2cbp__.ent", "d1kcw_2.ent-d2cuaa_.ent", "d1kcw_3.ent-d1cyx__.ent", "d1kcw_3.ent-d1e30a_.ent", "d1kcw_3.ent-d1gw0a1.ent", "d1kcw_3.ent-d1gw0a2.ent", "d1kcw_3.ent-d1hfua2.ent", "d1kcw_3.ent-d1ikop_.ent", "d1kcw_3.ent-d1kbva1.ent", "d1kcw_3.ent-d1kbva2.ent", "d1kcw_3.ent-d1kcw_1.ent", "d1kcw_3.ent-d1kcw_2.ent", "d1kcw_3.ent-d1kcw_4.ent", "d1kcw_3.ent-d1kcw_5.ent", "d1kcw_3.ent-d1kcw_6.ent", "d1kcw_3.ent-d1kv7a1.ent", "d1kcw_3.ent-d1kv7a2.ent", "d1kcw_3.ent-d1kv7a3.ent", "d1kcw_3.ent-d1l9qa1.ent", "d1kcw_3.ent-d1l9qa2.ent", "d1kcw_3.ent-d1m56b1.ent", "d1kcw_3.ent-d1qhqa_.ent", "d1kcw_4.ent-d1ikop_.ent", "d1kcw_4.ent-d1kbva1.ent", "d1kcw_4.ent-d1kbva2.ent", "d1kcw_4.ent-d1kcw_2.ent", "d1kcw_4.ent-d1kcw_6.ent", "d1kcw_4.ent-d1kv7a1.ent", "d1kcw_4.ent-d1qhqa_.ent", "d1kcw_5.ent-d1cyx__.ent", "d1kcw_5.ent-d1e30a_.ent", "d1kcw_5.ent-d1gw0a1.ent", "d1kcw_5.ent-d1hfua2.ent", "d1kcw_5.ent-d1ikop_.ent", "d1kcw_5.ent-d1kbva1.ent", "d1kcw_5.ent-d1kbva2.ent", "d1kcw_5.ent-d1kcw_2.ent", "d1kcw_5.ent-d1kcw_4.ent", "d1kcw_5.ent-d1kcw_6.ent", "d1kcw_5.ent-d1kv7a1.ent", "d1kcw_5.ent-d1kv7a2.ent", "d1kcw_5.ent-d1kv7a3.ent", "d1kcw_5.ent-d1l9qa1.ent", "d1kcw_5.ent-d1l9qa2.ent", "d1kcw_5.ent-d1m56b1.ent", "d1kcw_5.ent-d1qhqa_.ent", "d1kcw_6.ent-d1ikop_.ent", "d1kcw_6.ent-d1kcw_2.ent", "d1kcw_6.ent-d1kv7a1.ent", "d1kcw_6.ent-d1qhqa_.ent", "d1kdga1.ent-d1b5qa1.ent", "d1kdga1.ent-d1chua2.ent", "d1kdga1.ent-d1cjca1.ent", "d1kdga1.ent-d1d5ta1.ent", "d1kdga1.ent-d1ebda1.ent", "d1kdga1.ent-d1feca1.ent", "d1kdga1.ent-d1h6va1.ent", "d1kdga1.ent-d1jeha1.ent", "d1kdga1.ent-d1jnra2.ent", "d1kdga1.ent-d1ju2a1.ent", "d1kdga1.ent-d1k0ia1.ent", "d1kdga1.ent-d1kf6a2.ent", "d1kdga1.ent-d1kssa2.ent", "d1kdga1.ent-d1l9ea1.ent", "d1kdga1.ent-d1mo9a1.ent", "d1kdga1.ent-d1neka2.ent", "d1kdga1.ent-d1ojt_1.ent", "d1kdga1.ent-d1qlaa2.ent", "d1kdga1.ent-d1qo8a2.ent", "d1kdga1.ent-d3lada1.ent", "d1kdga2.ent-d1l9ea2.ent", "d1kdga2.ent-d1mxta2.ent", "d1kdu__.ent-d1ki0a2.ent", "d1kdu__.ent-d1ki0a3.ent", "d1kdu__.ent-d1l6ja3.ent", "d1kdu__.ent-d1l6ja5.ent", "d1kdu__.ent-d1pmla_.ent", "d1kdu__.ent-d2hpqp_.ent", "d1kdu__.ent-d5hpga_.ent", "d1keaa_.ent-d1ko9a1.ent", "d1keaa_.ent-d1lmza_.ent", "d1keaa_.ent-d1mpga1.ent", "d1keaa_.ent-d1mun__.ent", "d1keaa_.ent-d2abk__.ent", "d1keia_.ent-d1kufa_.ent", "d1keia_.ent-d1lml__.ent", "d1keia_.ent-d3btaa3.ent", "d1keka1.ent-d1keka2.ent", "d1keka1.ent-d1l8aa1.ent", "d1keka1.ent-d1l8aa2.ent", "d1keka1.ent-d1poxa2.ent", "d1keka1.ent-d1poxa3.ent", "d1keka1.ent-d1pvda2.ent", "d1keka1.ent-d1pvda3.ent", "d1keka1.ent-d1zpda2.ent", "d1keka1.ent-d1zpda3.ent", "d1keka2.ent-d1l8aa1.ent", "d1keka2.ent-d1l8aa2.ent", "d1keka2.ent-d1poxa2.ent", "d1keka2.ent-d1poxa3.ent", "d1keka2.ent-d1pvda2.ent", "d1keka2.ent-d1pvda3.ent", "d1keka2.ent-d1zpda2.ent", "d1keka2.ent-d1zpda3.ent", "d1keka3.ent-d1l8aa3.ent", "d1keka5.ent-d1kqfb1.ent", "d1keka5.ent-d2fdn__.ent", "d1keka5.ent-d7fd1a_.ent", "d1kepa_.ent-d1bdb__.ent", "d1kepa_.ent-d1bgva1.ent", "d1kepa_.ent-d1e6ua_.ent", "d1kepa_.ent-d1e7wa_.ent", "d1kepa_.ent-d1eno__.ent", "d1kepa_.ent-d1eny__.ent", "d1kepa_.ent-d1fds__.ent", "d1kepa_.ent-d1g0oa_.ent", "d1kepa_.ent-d1gcoa_.ent", "d1kepa_.ent-d1h5qa_.ent", "d1kepa_.ent-d1hwxa1.ent", "d1kepa_.ent-d1ja9a_.ent", "d1kepa_.ent-d1k6xa_.ent", "d1kepa_.ent-d1llqa1.ent", "d1kepa_.ent-d1n2sa_.ent", "d1kepa_.ent-d1n5da_.ent", "d1kepa_.ent-d1n7ha_.ent", "d1kepa_.ent-d1oaa__.ent", "d1kepa_.ent-d1qsga_.ent", "d1kepa_.ent-d2ae2a_.ent", "d1kewa_.ent-d1bdb__.ent", "d1kewa_.ent-d1bgva1.ent", "d1kewa_.ent-d1e6ua_.ent", "d1kewa_.ent-d1e7wa_.ent", "d1kewa_.ent-d1ek6a_.ent", "d1kewa_.ent-d1eno__.ent", "d1kewa_.ent-d1eny__.ent", "d1kewa_.ent-d1fds__.ent", "d1kewa_.ent-d1g0oa_.ent", "d1kewa_.ent-d1gcoa_.ent", "d1kewa_.ent-d1h5qa_.ent", "d1kewa_.ent-d1hwxa1.ent", "d1kewa_.ent-d1ja9a_.ent", "d1kewa_.ent-d1k6xa_.ent", "d1kewa_.ent-d1kepa_.ent", "d1kewa_.ent-d1llqa1.ent", "d1kewa_.ent-d1n2sa_.ent", "d1kewa_.ent-d1n5da_.ent", "d1kewa_.ent-d1n7ha_.ent", "d1kewa_.ent-d1oaa__.ent", "d1kewa_.ent-d1qsga_.ent", "d1kewa_.ent-d2ae2a_.ent", "d1kexa_.ent-d1ciy_1.ent", "d1kexa_.ent-d1cx1a_.ent", "d1kexa_.ent-d1dlc_1.ent", "d1kexa_.ent-d1eut_2.ent", "d1kexa_.ent-d1gmma_.ent", "d1kexa_.ent-d1gnya_.ent", "d1kexa_.ent-d1gu3a_.ent", "d1kexa_.ent-d1ji6a1.ent", "d1kexa_.ent-d1xnaa_.ent", "d1keya_.ent-d1e8xa1.ent", "d1keya_.ent-d1elka_.ent", "d1keya_.ent-d1h6ka2.ent", "d1keya_.ent-d1hh8a_.ent", "d1keya_.ent-d1hs6a1.ent", "d1keya_.ent-d1ihga1.ent", "d1keya_.ent-d1kpsb_.ent", "d1keya_.ent-d1l5ja1.ent", "d1keya_.ent-d1n4ka1.ent", "d1keya_.ent-d1pbv__.ent", "d1kf6a1.ent-d1neka1.ent", "d1kf6a1.ent-d1qlaa1.ent", "d1kf6a2.ent-d1chua2.ent", "d1kf6a2.ent-d1cjca1.ent", "d1kf6a2.ent-d1ebda1.ent", "d1kf6a2.ent-d1feca1.ent", "d1kf6a2.ent-d1h6va1.ent", "d1kf6a2.ent-d1jeha1.ent", "d1kf6a2.ent-d1k0ia1.ent", "d1kf6a2.ent-d1l9ea1.ent", "d1kf6a2.ent-d1mo9a1.ent", "d1kf6a2.ent-d1ojt_1.ent", "d1kf6a2.ent-d3lada1.ent", "d1kf6a3.ent-d1kssa3.ent", "d1kf6a3.ent-d1neka3.ent", "d1kf6a3.ent-d1qlaa3.ent", "d1kf6a3.ent-d1qo8a3.ent", "d1kf6b1.ent-d1nekb1.ent", "d1kf6b1.ent-d1qlab1.ent", "d1kf6b2.ent-d1krha3.ent", "d1kf6b2.ent-d1l5pa_.ent", "d1kf6b2.ent-d1n62a2.ent", "d1kf6b2.ent-d1nekb2.ent", "d1kf6b2.ent-d1put__.ent", "d1kf6b2.ent-d1qlab2.ent", "d1kf6b2.ent-d2pia_3.ent", "d1kf6c_.ent-d1kf6d_.ent", "d1kf6c_.ent-d1kqfc_.ent", "d1kf6c_.ent-d1nekc_.ent", "d1kf6c_.ent-d1nekd_.ent", "d1kf6c_.ent-d1qlac_.ent", "d1kf6d_.ent-d1kqfc_.ent", "d1kf6d_.ent-d1nekc_.ent", "d1kf6d_.ent-d1nekd_.ent", "d1kf6d_.ent-d1qlac_.ent", "d1kfia1.ent-d1kfia2.ent", "d1kfia1.ent-d3pmga1.ent", "d1kfia1.ent-d3pmga2.ent", "d1kfia1.ent-d3pmga3.ent", "d1kfia2.ent-d3pmga3.ent", "d1kfia4.ent-d3pmga4.ent", "d1kfsa1.ent-d1musa_.ent", "d1kfsa1.ent-d1qtma1.ent", "d1kfsa1.ent-d1t7pa1.ent", "d1kfsa1.ent-d1tgoa1.ent", "d1kfsa1.ent-d1vrta1.ent", "d1kfsa1.ent-d1xwl_1.ent", "d1kfsa2.ent-d1khva_.ent", "d1kfsa2.ent-d1mml__.ent", "d1kfsa2.ent-d1mswd_.ent", "d1kfsa2.ent-d1muka_.ent", "d1kfsa2.ent-d1rdr__.ent", "d1kfsa2.ent-d1t7pa2.ent", "d1kfsa2.ent-d1tgoa2.ent", "d1kfsa2.ent-d1vrta2.ent", "d1kfsa2.ent-d1xwl_2.ent", "d1kfta_.ent-d1lb2b_.ent", "d1kfta_.ent-d1tfr_1.ent", "d1kfwa2.ent-d1lg2a2.ent", "d1kfwa2.ent-d1ll7a2.ent", "d1kg0c_.ent-d1b08a1.ent", "d1kg0c_.ent-d1b6e__.ent", "d1kg0c_.ent-d1byfa_.ent", "d1kg0c_.ent-d1cwva5.ent", "d1kg0c_.ent-d1dv8a_.ent", "d1kg0c_.ent-d1e87a_.ent", "d1kg0c_.ent-d1egia_.ent", "d1kg0c_.ent-d1f00i3.ent", "d1kg0c_.ent-d1fvua_.ent", "d1kg0c_.ent-d1fvub_.ent", "d1kg0c_.ent-d1g1ta1.ent", "d1kg0c_.ent-d1h8ua_.ent", "d1kg0c_.ent-d1hq8a_.ent", "d1kg0c_.ent-d1jwia_.ent", "d1kg0c_.ent-d1jwib_.ent", "d1kg0c_.ent-d1k9ja_.ent", "d1kg0c_.ent-d1koe__.ent", "d1kg0c_.ent-d1li1a1.ent", "d1kg0c_.ent-d1li1a2.ent", "d1kg0c_.ent-d1prea1.ent", "d1kg0c_.ent-d1prtb2.ent", "d1kg0c_.ent-d1qdda_.ent", "d1kg0c_.ent-d1qo3c_.ent", "d1kg0c_.ent-d1tsg__.ent", "d1kgce2.ent-d1a2yb_.ent", "d1kgce2.ent-d1akjd_.ent", "d1kgce2.ent-d1b88a_.ent", "d1kgce2.ent-d1bec_1.ent", "d1kgce2.ent-d1bqhg_.ent", "d1kgce2.ent-d1c5ch1.ent", "d1kgce2.ent-d1dlfh_.ent", "d1kgce2.ent-d1dlfl_.ent", "d1kgce2.ent-d1dqia_.ent", "d1kgce2.ent-d1dqta_.ent", "d1kgce2.ent-d1eaja_.ent", "d1kgce2.ent-d1fo0a_.ent", "d1kgce2.ent-d1grwa_.ent", "d1kgce2.ent-d1gsma2.ent", "d1kgce2.ent-d1h5ba_.ent", "d1kgce2.ent-d1hxma1.ent", "d1kgce2.ent-d1hxmb1.ent", "d1kgce2.ent-d1j0ha1.ent", "d1kgce2.ent-d1ktke1.ent", "d1kgce2.ent-d1kxvc_.ent", "d1kgce2.ent-d1neu__.ent", "d1kgce2.ent-d1nfdb1.ent", "d1kgce2.ent-d1o75a1.ent", "d1kgce2.ent-d1qfoa_.ent", "d1kgce2.ent-d1soxa1.ent", "d1kgce2.ent-d1tvda_.ent", "d1kgce2.ent-d2rhe__.ent", "d1kgna_.ent-d1lkoa1.ent", "d1kgna_.ent-d1mtyb_.ent", "d1kgna_.ent-d1mtyd_.ent", "d1kgna_.ent-d1qgha_.ent", "d1kgna_.ent-d1rcd__.ent", "d1kgya_.ent-d1ciy_1.ent", "d1kgya_.ent-d1cx1a_.ent", "d1kgya_.ent-d1czsa_.ent", "d1kgya_.ent-d1d7pm_.ent", "d1kgya_.ent-d1dlc_1.ent", "d1kgya_.ent-d1eut_2.ent", "d1kgya_.ent-d1gmma_.ent", "d1kgya_.ent-d1gnya_.ent", "d1kgya_.ent-d1gqpa_.ent", "d1kgya_.ent-d1gu3a_.ent", "d1kgya_.ent-d1guia_.ent", "d1kgya_.ent-d1h6ya_.ent", "d1kgya_.ent-d1i5pa1.ent", "d1kgya_.ent-d1jhja_.ent", "d1kgya_.ent-d1ji6a1.ent", "d1kgya_.ent-d1k12a_.ent", "d1kgya_.ent-d1k3ia2.ent", "d1kgya_.ent-d1k42a_.ent", "d1kgya_.ent-d1kexa_.ent", "d1kgya_.ent-d1l7la_.ent", "d1kgya_.ent-d1lnsa2.ent", "d1kgya_.ent-d1xnaa_.ent", "d1khba1.ent-d1knxa2.ent", "d1khba1.ent-d1ko7a2.ent", "d1khda1.ent-d1o17a1.ent", "d1khda1.ent-d2tpt_1.ent", "d1khda2.ent-d1o17a2.ent", "d1khda2.ent-d2tpt_2.ent", "d1khha_.ent-d1vid__.ent", "d1khha_.ent-d1xvaa_.ent", "d1khha_.ent-d2dpma_.ent", "d1khha_.ent-d3mag__.ent", "d1khia1.ent-d1dj7b_.ent", "d1khia1.ent-d1g3sa3.ent", "d1khia1.ent-d1gcqc_.ent", "d1khia1.ent-d1i07a_.ent", "d1khia1.ent-d1jb0e_.ent", "d1khia1.ent-d1jo8a_.ent", "d1khia1.ent-d1m1ga2.ent", "d1khia1.ent-d1m9sa2.ent", "d1khia1.ent-d1vie__.ent", "d1khia1.ent-d1ycsb2.ent", "d1khia1.ent-d2eifa1.ent", "d1khma_.ent-d1vig__.ent", "d1khma_.ent-d2fmr__.ent", "d1khva_.ent-d1mml__.ent", "d1khva_.ent-d1mswd_.ent", "d1khva_.ent-d1muka_.ent", "d1khva_.ent-d1rdr__.ent", "d1khva_.ent-d1t7pa2.ent", "d1khva_.ent-d1tgoa2.ent", "d1khva_.ent-d1vrta2.ent", "d1khva_.ent-d1xwl_2.ent", "d1ki0a2.ent-d1ki0a3.ent", "d1ki0a2.ent-d1l6ja3.ent", "d1ki0a2.ent-d1l6ja5.ent", "d1ki0a2.ent-d1pmla_.ent", "d1ki0a2.ent-d2hpqp_.ent", "d1ki0a2.ent-d5hpga_.ent", "d1ki0a3.ent-d1l6ja3.ent", "d1ki0a3.ent-d1l6ja5.ent", "d1ki0a3.ent-d1pmla_.ent", "d1ki0a3.ent-d2hpqp_.ent", "d1ki0a3.ent-d5hpga_.ent", "d1ki1b2.ent-d1mai__.ent", "d1ki1b2.ent-d1mixa2.ent", "d1ki1b2.ent-d1mkea1.ent", "d1ki1b2.ent-d1pls__.ent", "d1ki1b2.ent-d1qqga1.ent", "d1ki1b2.ent-d1qqga2.ent", "d1ki1b2.ent-d1shca_.ent", "d1kid__.ent-d1l5ja2.ent", "d1kid__.ent-d1nbwa1.ent", "d1kija1.ent-d1kkha1.ent", "d1kija1.ent-d1kvka1.ent", "d1kija1.ent-d1mu5a2.ent", "d1kija1.ent-d1n0ua3.ent", "d1kija1.ent-d1pkp_1.ent", "d1kija2.ent-d1l0oa_.ent", "d1kija2.ent-d1mu5a3.ent", "d1kit_1.ent-d1dyka1.ent", "d1kit_1.ent-d1dyka2.ent", "d1kit_1.ent-d1h30a1.ent", "d1kit_1.ent-d1kqra_.ent", "d1kit_1.ent-d1n1ta1.ent", "d1kit_1.ent-d1nls__.ent", "d1kit_1.ent-d1saca_.ent", "d1kit_1.ent-d1xnb__.ent", "d1kit_1.ent-d2nlra_.ent", "d1kit_1.ent-d2sli_1.ent", "d1kit_2.ent-d1dhkb_.ent", "d1kit_2.ent-d1dyka1.ent", "d1kit_2.ent-d1dyka2.ent", "d1kit_2.ent-d1h30a1.ent", "d1kit_2.ent-d1kit_1.ent", "d1kit_2.ent-d1xnb__.ent", "d1kit_2.ent-d2sli_1.ent", "d1kit_3.ent-d1n1ta2.ent", "d1kit_3.ent-d1nsca_.ent", "d1kit_3.ent-d2bat__.ent", "d1kit_3.ent-d2sli_2.ent", "d1kit_3.ent-d3sil__.ent", "d1kj6a_.ent-d1sh1__.ent", "d1kj6a_.ent-d2bds__.ent", "d1kjka_.ent-d1qk9a_.ent", "d1kjqa2.ent-d1m0wa1.ent", "d1kjqa2.ent-d2hgsa1.ent", "d1kjqa3.ent-d1m0wa2.ent", "d1kjqa3.ent-d2hgsa4.ent", "d1kjwa1.ent-d1bb9__.ent", "d1kjwa1.ent-d1dj7b_.ent", "d1kjwa1.ent-d1fx7a3.ent", "d1kjwa1.ent-d1g3sa3.ent", "d1kjwa1.ent-d1gcqc_.ent", "d1kjwa1.ent-d1i07a_.ent", "d1kjwa1.ent-d1jb0e_.ent", "d1kjwa1.ent-d1jo8a_.ent", "d1kjwa1.ent-d1khia1.ent", "d1kjwa1.ent-d1m9sa2.ent", "d1kjwa1.ent-d1m9sa3.ent", "d1kjwa1.ent-d1neb__.ent", "d1kjwa1.ent-d1pht__.ent", "d1kjwa1.ent-d1pwt__.ent", "d1kjwa1.ent-d1qcfa1.ent", "d1kjwa1.ent-d1vie__.ent", "d1kjwa1.ent-d1ycsb2.ent", "d1kjwa1.ent-d2hsp__.ent", "d1kk1a1.ent-d1krha1.ent", "d1kk1a1.ent-d1kzla1.ent", "d1kk1a1.ent-d1kzla2.ent", "d1kk1a1.ent-d1n08a_.ent", "d1kk1a1.ent-d1n0ua1.ent", "d1kk1a1.ent-d1qfja1.ent", "d1kk1a1.ent-d2pia_1.ent", "d1kk6a_.ent-d1krra_.ent", "d1kk6a_.ent-d1lxa__.ent", "d1kk6a_.ent-d1qrea_.ent", "d1kk6a_.ent-d1xat__.ent", "d1kk6a_.ent-d3tdt__.ent", "d1kk8a1.ent-d1lvk_1.ent", "d1kk8a2.ent-d1bg2__.ent", "d1kk8a2.ent-d1br2a2.ent", "d1kk8a2.ent-d1c4oa1.ent", "d1kk8a2.ent-d1dj3a_.ent", "d1kk8a2.ent-d1e2ka_.ent", "d1kk8a2.ent-d1e9ra_.ent", "d1kk8a2.ent-d1eg7a_.ent", "d1kk8a2.ent-d1f9va_.ent", "d1kk8a2.ent-d1fmja_.ent", "d1kk8a2.ent-d1g41a_.ent", "d1kk8a2.ent-d1g8pa_.ent", "d1kk8a2.ent-d1i6ia_.ent", "d1kk8a2.ent-d1ii6a_.ent", "d1kk8a2.ent-d1iwea_.ent", "d1kk8a2.ent-d1ksfx3.ent", "d1kk8a2.ent-d1lkxa_.ent", "d1kk8a2.ent-d1lvk_2.ent", "d1kk8a2.ent-d1n0ua2.ent", "d1kk8a2.ent-d1pjr_1.ent", "d1kk8a2.ent-d1pjr_2.ent", "d1kk8a2.ent-d1qf5a_.ent", "d1kk8a2.ent-d1uaaa1.ent", "d1kk8a2.ent-d1uaaa2.ent", "d1kk8a2.ent-d2ncda_.ent", "d1kkca2.ent-d1ma1a2.ent", "d1kkca2.ent-d1qnna2.ent", "d1kkea1.ent-d1qhva_.ent", "d1kkha1.ent-d1kvka1.ent", "d1kkha1.ent-d1mu5a2.ent", "d1kkha1.ent-d1n0ua3.ent", "d1kkha1.ent-d1pkp_1.ent", "d1kkha2.ent-d1kvka2.ent", "d1kl1a_.ent-d1b9ha_.ent", "d1kl1a_.ent-d1bs0a_.ent", "d1kl1a_.ent-d1c7na_.ent", "d1kl1a_.ent-d1e5ea_.ent", "d1kl1a_.ent-d1gdea_.ent", "d1kl1a_.ent-d1j32a_.ent", "d1kl1a_.ent-d1lc5a_.ent", "d1kl1a_.ent-d1n8pa_.ent", "d1kl1a_.ent-d1qisa_.ent", "d1kl1a_.ent-d1qj5a_.ent", "d1kl1a_.ent-d2ay1a_.ent", "d1kl1a_.ent-d2oata_.ent", "d1kl1a_.ent-d3tata_.ent", "d1kl1a_.ent-d7aata_.ent", "d1klfb1.ent-d1klfb2.ent", "d1klfb1.ent-d1m2oa2.ent", "d1klfb1.ent-d1m2vb2.ent", "d1klfb1.ent-d1mnna_.ent", "d1klfb1.ent-d1nbca_.ent", "d1klfb1.ent-d1pdkb_.ent", "d1klfb1.ent-d1qba_2.ent", "d1klfb1.ent-d1tf4a2.ent", "d1klfb1.ent-d1ycsa_.ent", "d1klfb2.ent-d1m2oa2.ent", "d1klfb2.ent-d1m2vb2.ent", "d1klfb2.ent-d1mnna_.ent", "d1klfb2.ent-d1nbca_.ent", "d1klfb2.ent-d1pdkb_.ent", "d1klfb2.ent-d1qba_2.ent", "d1klfb2.ent-d1tf4a2.ent", "d1klfb2.ent-d1ycsa_.ent", "d1klih_.ent-d1a0la_.ent", "d1klih_.ent-d1agja_.ent", "d1klih_.ent-d1azza_.ent", "d1klih_.ent-d1bio__.ent", "d1klih_.ent-d1bqya_.ent", "d1klih_.ent-d1cgha_.ent", "d1klih_.ent-d1ddja_.ent", "d1klih_.ent-d1eaxa_.ent", "d1klih_.ent-d1ekbb_.ent", "d1klih_.ent-d1elva1.ent", "d1klih_.ent-d1fjsa_.ent", "d1klih_.ent-d1gdna_.ent", "d1klih_.ent-d1gpza1.ent", "d1klih_.ent-d1gvkb_.ent", "d1klih_.ent-d1gvza_.ent", "d1klih_.ent-d1hj9a_.ent", "d1klih_.ent-d1m9ua_.ent", "d1klih_.ent-d1mzaa_.ent", "d1klih_.ent-d1qtfa_.ent", "d1klih_.ent-d1rfna_.ent", "d1klih_.ent-d2hlca_.ent", "d1klil_.ent-d1agg__.ent", "d1klil_.ent-d1apq__.ent", "d1klil_.ent-d1b9wa1.ent", "d1klil_.ent-d1b9wa2.ent", "d1klil_.ent-d1bx7__.ent", "d1klil_.ent-d1ceja1.ent", "d1klil_.ent-d1ceja2.ent", "d1klil_.ent-d1cixa_.ent", "d1klil_.ent-d1cvua2.ent", "d1klil_.ent-d1dx5i1.ent", "d1klil_.ent-d1e0fi_.ent", "d1klil_.ent-d1emo_1.ent", "d1klil_.ent-d1fjsl_.ent", "d1klil_.ent-d1flei_.ent", "d1klil_.ent-d1g9pa_.ent", "d1klil_.ent-d1gps__.ent", "d1klil_.ent-d1h59b_.ent", "d1klil_.ent-d1hyka_.ent", "d1klil_.ent-d1hz8a1.ent", "d1klil_.ent-d1hz8a2.ent", "d1klil_.ent-d1i2ua_.ent", "d1klil_.ent-d1ijqa2.ent", "d1klil_.ent-d1imt_2.ent", "d1klil_.ent-d1ioxa_.ent", "d1klil_.ent-d1jkza_.ent", "d1klil_.ent-d1jl9a_.ent", "d1klil_.ent-d1klo_1.ent", "d1klil_.ent-d1klo_2.ent", "d1klil_.ent-d1klo_3.ent", "d1klil_.ent-d1l3ya_.ent", "d1klil_.ent-d1lpba2.ent", "d1klil_.ent-d1m1xb5.ent", "d1klil_.ent-d1rfnb_.ent", "d1klil_.ent-d1tpg_1.ent", "d1klil_.ent-d1urk_1.ent", "d1klil_.ent-d3tgf__.ent", "d1klil_.ent-d4htci_.ent", "d1klo_1.ent-d1agg__.ent", "d1klo_1.ent-d1apq__.ent", "d1klo_1.ent-d1b9wa1.ent", "d1klo_1.ent-d1b9wa2.ent", "d1klo_1.ent-d1bx7__.ent", "d1klo_1.ent-d1ceja1.ent", "d1klo_1.ent-d1ceja2.ent", "d1klo_1.ent-d1cixa_.ent", "d1klo_1.ent-d1cvua2.ent", "d1klo_1.ent-d1dx5i1.ent", "d1klo_1.ent-d1emo_1.ent", "d1klo_1.ent-d1fjsl_.ent", "d1klo_1.ent-d1flei_.ent", "d1klo_1.ent-d1g9pa_.ent", "d1klo_1.ent-d1gps__.ent", "d1klo_1.ent-d1h59b_.ent", "d1klo_1.ent-d1hyka_.ent", "d1klo_1.ent-d1hz8a1.ent", "d1klo_1.ent-d1hz8a2.ent", "d1klo_1.ent-d1i2ua_.ent", "d1klo_1.ent-d1ijqa2.ent", "d1klo_1.ent-d1imt_2.ent", "d1klo_1.ent-d1ioxa_.ent", "d1klo_1.ent-d1jkza_.ent", "d1klo_1.ent-d1jl9a_.ent", "d1klo_1.ent-d1klo_3.ent", "d1klo_1.ent-d1l3ya_.ent", "d1klo_1.ent-d1lpba2.ent", "d1klo_1.ent-d1m1xb5.ent", "d1klo_1.ent-d1tpg_1.ent", "d1klo_1.ent-d1urk_1.ent", "d1klo_1.ent-d3tgf__.ent", "d1klo_2.ent-d1apq__.ent", "d1klo_2.ent-d1b9wa1.ent", "d1klo_2.ent-d1b9wa2.ent", "d1klo_2.ent-d1ceja1.ent", "d1klo_2.ent-d1ceja2.ent", "d1klo_2.ent-d1cvua2.ent", "d1klo_2.ent-d1dx5i1.ent", "d1klo_2.ent-d1emo_1.ent", "d1klo_2.ent-d1fjsl_.ent", "d1klo_2.ent-d1hz8a1.ent", "d1klo_2.ent-d1hz8a2.ent", "d1klo_2.ent-d1ijqa2.ent", "d1klo_2.ent-d1ioxa_.ent", "d1klo_2.ent-d1jl9a_.ent", "d1klo_2.ent-d1klo_1.ent", "d1klo_2.ent-d1klo_3.ent", "d1klo_2.ent-d1l3ya_.ent", "d1klo_2.ent-d1m1xb5.ent", "d1klo_2.ent-d1tpg_1.ent", "d1klo_2.ent-d1urk_1.ent", "d1klo_2.ent-d3tgf__.ent", "d1klo_3.ent-d1agg__.ent", "d1klo_3.ent-d1b9wa1.ent", "d1klo_3.ent-d1b9wa2.ent", "d1klo_3.ent-d1ceja1.ent", "d1klo_3.ent-d1cixa_.ent", "d1klo_3.ent-d1cvua2.ent", "d1klo_3.ent-d1dx5i1.ent", "d1klo_3.ent-d1emo_1.ent", "d1klo_3.ent-d1flei_.ent", "d1klo_3.ent-d1g9pa_.ent", "d1klo_3.ent-d1gps__.ent", "d1klo_3.ent-d1h59b_.ent", "d1klo_3.ent-d1hyka_.ent", "d1klo_3.ent-d1hz8a1.ent", "d1klo_3.ent-d1hz8a2.ent", "d1klo_3.ent-d1i2ua_.ent", "d1klo_3.ent-d1ijqa2.ent", "d1klo_3.ent-d1imt_2.ent", "d1klo_3.ent-d1ioxa_.ent", "d1klo_3.ent-d1jkza_.ent", "d1klo_3.ent-d1jl9a_.ent", "d1klo_3.ent-d1l3ya_.ent", "d1klo_3.ent-d1lpba2.ent", "d1klo_3.ent-d1m1xb5.ent", "d1klo_3.ent-d1tpg_1.ent", "d1klo_3.ent-d1urk_1.ent", "d1klo_3.ent-d3tgf__.ent", "d1klpa_.ent-d1l0ia_.ent", "d1km3a_.ent-d1kv8a_.ent", "d1km3a_.ent-d1nsj__.ent", "d1km3a_.ent-d1pii_1.ent", "d1km3a_.ent-d1pii_2.ent", "d1km3a_.ent-d1qopa_.ent", "d1km3a_.ent-d1rpxa_.ent", "d1km3a_.ent-d1thfd_.ent", "d1kmma1.ent-d1qe0a1.ent", "d1kmma1.ent-d1qf6a1.ent", "d1kmma2.ent-d1qe0a2.ent", "d1kmma2.ent-d1qf6a4.ent", "d1kmma2.ent-d1seta2.ent", "d1kmoa_.ent-d1mm4a_.ent", "d1kmoa_.ent-d1qj8a_.ent", "d1kmoa_.ent-d1qjpa_.ent", "d1kmoa_.ent-d2mpra_.ent", "d1kmoa_.ent-d2por__.ent", "d1kmoa_.ent-d3prn__.ent", "d1kmta_.ent-d1dqia_.ent", "d1kmta_.ent-d1ea9c1.ent", "d1kmta_.ent-d1eaja_.ent", "d1kmta_.ent-d1edqa1.ent", "d1kmta_.ent-d1eut_1.ent", "d1kmta_.ent-d1g0da1.ent", "d1kmta_.ent-d1grwa_.ent", "d1kmta_.ent-d1j0ha1.ent", "d1kmta_.ent-d1ji1a1.ent", "d1kmta_.ent-d1ji2a1.ent", "d1kmta_.ent-d1jmxa4.ent", "d1kmta_.ent-d1kgce2.ent", "d1kmta_.ent-d1ktja_.ent", "d1kmta_.ent-d1kv3a1.ent", "d1kmta_.ent-d1kyfa1.ent", "d1kmta_.ent-d1lmia_.ent", "d1kmta_.ent-d1m1xb1.ent", "d1kmta_.ent-d1m7xa1.ent", "d1kmta_.ent-d1my7a_.ent", "d1kmta_.ent-d1nepa_.ent", "d1kmta_.ent-d1o75a1.ent", "d1kmta_.ent-d1qba_1.ent", "d1kmta_.ent-d1qfha1.ent", "d1kmta_.ent-d1qfha2.ent", "d1kmta_.ent-d1soxa1.ent", "d1kn0a_.ent-d1o0wa2.ent", "d1kn0a_.ent-d1pda_2.ent", "d1kn0a_.ent-d1pkp_2.ent", "d1kn0a_.ent-d1qu6a1.ent", "d1kn0a_.ent-d1qu6a2.ent", "d1kn0a_.ent-d1stu__.ent", "d1kn6a_.ent-d1kwma2.ent", "d1kn6a_.ent-d1scjb_.ent", "d1knaa_.ent-d1tvxa_.ent", "d1knga_.ent-d1a8l_1.ent", "d1knga_.ent-d1a8l_2.ent", "d1knga_.ent-d1a8y_1.ent", "d1knga_.ent-d1a8y_2.ent", "d1knga_.ent-d1a8y_3.ent", "d1knga_.ent-d1aba__.ent", "d1knga_.ent-d1aqwa2.ent", "d1knga_.ent-d1bed_2.ent", "d1knga_.ent-d1bjx__.ent", "d1knga_.ent-d1e6ba2.ent", "d1knga_.ent-d1ep7a_.ent", "d1knga_.ent-d1erv__.ent", "d1knga_.ent-d1f9ma_.ent", "d1knga_.ent-d1fb6a_.ent", "d1knga_.ent-d1fhe_2.ent", "d1knga_.ent-d1fvka2.ent", "d1knga_.ent-d1g7ea_.ent", "d1knga_.ent-d1gh2a_.ent", "d1knga_.ent-d1hyua4.ent", "d1knga_.ent-d1iloa_.ent", "d1knga_.ent-d1k0ma2.ent", "d1knga_.ent-d1k3ya2.ent", "d1knga_.ent-d1kte__.ent", "d1knga_.ent-d1m2da_.ent", "d1knga_.ent-d1mek__.ent", "d1knga_.ent-d1qmha1.ent", "d1knga_.ent-d1quwa_.ent", "d1knga_.ent-d1thx__.ent", "d1knga_.ent-d2trxa_.ent", "d1knma_.ent-d1l2ha_.ent", "d1knma_.ent-d1n4ka2.ent", "d1knva_.ent-d1m0da_.ent", "d1knva_.ent-d1vsra_.ent", "d1knva_.ent-d2foka4.ent", "d1knva_.ent-d3pvia_.ent", "d1knxa2.ent-d1ko7a2.ent", "d1knya1.ent-d1ls1a1.ent", "d1knya1.ent-d1nfn__.ent", "d1knya1.ent-d1nlxa_.ent", "d1knya1.ent-d256ba_.ent", "d1knya1.ent-d2a0b__.ent", "d1knya1.ent-d2liga_.ent", "d1knya1.ent-d2mhr__.ent", "d1knya1.ent-d3fapb_.ent", "d1ko9a1.ent-d1lmza_.ent", "d1ko9a1.ent-d1mpga1.ent", "d1ko9a1.ent-d1mun__.ent", "d1ko9a1.ent-d2abk__.ent", "d1ko9a2.ent-d1ln1a_.ent", "d1ko9a2.ent-d1mpga2.ent", "d1ko9a2.ent-d1ytba1.ent", "d1ko9a2.ent-d1ytba2.ent", "d1ko9a2.ent-d3pmga4.ent", "d1koba_.ent-d1a06__.ent", "d1koba_.ent-d1apme_.ent", "d1koba_.ent-d1b6cb_.ent", "d1koba_.ent-d1blxa_.ent", "d1koba_.ent-d1cjaa_.ent", "d1koba_.ent-d1csn__.ent", "d1koba_.ent-d1e8xa4.ent", "d1koba_.ent-d1f3mc_.ent", "d1koba_.ent-d1fgka_.ent", "d1koba_.ent-d1fvra_.ent", "d1koba_.ent-d1howa_.ent", "d1koba_.ent-d1ia9a_.ent", "d1koba_.ent-d1iepa_.ent", "d1koba_.ent-d1jksa_.ent", "d1koba_.ent-d1jnk__.ent", "d1koba_.ent-d1jpaa_.ent", "d1koba_.ent-d1jvpp_.ent", "d1koba_.ent-d1kwpa_.ent", "d1koba_.ent-d1lpua_.ent", "d1koba_.ent-d1lufa_.ent", "d1koba_.ent-d1m14a_.ent", "d1koba_.ent-d1p38__.ent", "d1koba_.ent-d1phk__.ent", "d1koba_.ent-d1tkia_.ent", "d1koe__.ent-d1b08a1.ent", "d1koe__.ent-d1b6e__.ent", "d1koe__.ent-d1byfa_.ent", "d1koe__.ent-d1cwva5.ent", "d1koe__.ent-d1dv8a_.ent", "d1koe__.ent-d1e87a_.ent", "d1koe__.ent-d1egia_.ent", "d1koe__.ent-d1f00i3.ent", "d1koe__.ent-d1fvua_.ent", "d1koe__.ent-d1fvub_.ent", "d1koe__.ent-d1g1ta1.ent", "d1koe__.ent-d1h8ua_.ent", "d1koe__.ent-d1hq8a_.ent", "d1koe__.ent-d1jwia_.ent", "d1koe__.ent-d1jwib_.ent", "d1koe__.ent-d1k9ja_.ent", "d1koe__.ent-d1kg0c_.ent", "d1koe__.ent-d1li1a1.ent", "d1koe__.ent-d1li1a2.ent", "d1koe__.ent-d1prea1.ent", "d1koe__.ent-d1prtb2.ent", "d1koe__.ent-d1qdda_.ent", "d1koe__.ent-d1qo3c_.ent", "d1koe__.ent-d1tn3__.ent", "d1koe__.ent-d1tsg__.ent", "d1koha1.ent-d1m0za_.ent", "d1koha1.ent-d1m6ba1.ent", "d1koha1.ent-d1m6ba2.ent", "d1koha1.ent-d1n8yc1.ent", "d1koha1.ent-d1n8yc2.ent", "d1koha2.ent-d1l3ka1.ent", "d1koha2.ent-d1l3ka2.ent", "d1koha2.ent-d1nu4a_.ent", "d1koha2.ent-d1qm9a1.ent", "d1koha2.ent-d1qm9a2.ent", "d1koha2.ent-d1u2fa_.ent", "d1koha2.ent-d2msta_.ent", "d1koha2.ent-d2u1a__.ent", "d1koha2.ent-d2u2fa_.ent", "d1koia_.ent-d1kqwa_.ent", "d1koia_.ent-d1lf7a_.ent", "d1koia_.ent-d1o1va_.ent", "d1koia_.ent-d1qfta_.ent", "d1koia_.ent-d1qqsa_.ent", "d1kola1.ent-d1qora1.ent", "d1kopa_.ent-d1mooa_.ent", "d1kopa_.ent-d2znc__.ent", "d1kora1.ent-d1kqpa_.ent", "d1kora1.ent-d1mjha_.ent", "d1kora1.ent-d1o97c_.ent", "d1kora1.ent-d1o97d1.ent", "d1kora1.ent-d1sur__.ent", "d1koza_.ent-d1kqha_.ent", "d1koza_.ent-d1lqra_.ent", "d1koza_.ent-d1lupa_.ent", "d1koza_.ent-d1nixa_.ent", "d1koza_.ent-d1niya_.ent", "d1koza_.ent-d1qk6a_.ent", "d1koza_.ent-d1qk7a_.ent", "d1koza_.ent-d1vtx__.ent", "d1kpf__.ent-d1l9va1.ent", "d1kppa_.ent-d1qcqa_.ent", "d1kppa_.ent-d2aak__.ent", "d1kppa_.ent-d2ucz__.ent", "d1kpsb_.ent-d1elka_.ent", "d1kpsb_.ent-d1hs6a1.ent", "d1kpsb_.ent-d1n4ka1.ent", "d1kq1a_.ent-d1ljoa_.ent", "d1kq1a_.ent-d1mgqa_.ent", "d1kq1a_.ent-d1mxma1.ent", "d1kq1a_.ent-d1n9ra_.ent", "d1kqfa1.ent-d1tmo_1.ent", "d1kqfa1.ent-d2napa1.ent", "d1kqfb1.ent-d2fdn__.ent", "d1kqfb1.ent-d7fd1a_.ent", "d1kqfb2.ent-d1l2pa_.ent", "d1kqfb2.ent-d1m56d_.ent", "d1kqfb2.ent-d1ocrd_.ent", "d1kqfb2.ent-d1ocrg_.ent", "d1kqfb2.ent-d1ocri_.ent", "d1kqfb2.ent-d1ocrj_.ent", "d1kqfb2.ent-d1ocrk_.ent", "d1kqfb2.ent-d1ocrl_.ent", "d1kqfb2.ent-d1ocrm_.ent", "d1kqfc_.ent-d1nekc_.ent", "d1kqfc_.ent-d1nekd_.ent", "d1kqfc_.ent-d1qlac_.ent", "d1kqha_.ent-d1lqra_.ent", "d1kqha_.ent-d1lupa_.ent", "d1kqha_.ent-d1nixa_.ent", "d1kqha_.ent-d1niya_.ent", "d1kqha_.ent-d1qk6a_.ent", "d1kqha_.ent-d1qk7a_.ent", "d1kqha_.ent-d1vtx__.ent", "d1kqna_.ent-d1kqpa_.ent", "d1kqna_.ent-d1li5a2.ent", "d1kqna_.ent-d1mjha_.ent", "d1kqna_.ent-d1n3la_.ent", "d1kqna_.ent-d1o97c_.ent", "d1kqna_.ent-d1o97d1.ent", "d1kqna_.ent-d1qjca_.ent", "d1kqna_.ent-d1sur__.ent", "d1kqpa_.ent-d1li5a2.ent", "d1kqpa_.ent-d1mjha_.ent", "d1kqpa_.ent-d1n3la_.ent", "d1kqpa_.ent-d1o97c_.ent", "d1kqpa_.ent-d1o97d1.ent", "d1kqpa_.ent-d1qjca_.ent", "d1kqpa_.ent-d1sur__.ent", "d1kqra_.ent-d1n1ta1.ent", "d1kqra_.ent-d1nls__.ent", "d1kqra_.ent-d1saca_.ent", "d1kqra_.ent-d2nlra_.ent", "d1kqra_.ent-d2sli_1.ent", "d1kqwa_.ent-d1lf7a_.ent", "d1kqwa_.ent-d1o1va_.ent", "d1kqwa_.ent-d1qfta_.ent", "d1kqwa_.ent-d1qqsa_.ent", "d1krha1.ent-d1kzla1.ent", "d1krha1.ent-d1kzla2.ent", "d1krha1.ent-d1n08a_.ent", "d1krha1.ent-d1n0ua1.ent", "d1krha1.ent-d1qfja1.ent", "d1krha1.ent-d1que_1.ent", "d1krha1.ent-d2cnd_1.ent", "d1krha1.ent-d2pia_1.ent", "d1krha2.ent-d1qfja2.ent", "d1krha2.ent-d1que_2.ent", "d1krha2.ent-d2cnd_2.ent", "d1krha2.ent-d2pia_2.ent", "d1krha3.ent-d1l5pa_.ent", "d1krha3.ent-d1n62a2.ent", "d1krha3.ent-d1nekb2.ent", "d1krha3.ent-d1put__.ent", "d1krha3.ent-d1qlab2.ent", "d1krha3.ent-d2pia_3.ent", "d1krra_.ent-d1lxa__.ent", "d1krra_.ent-d1qrea_.ent", "d1krra_.ent-d1xat__.ent", "d1krra_.ent-d3tdt__.ent", "d1ks8a_.ent-d1kwfa_.ent", "d1ks8a_.ent-d1ld8b_.ent", "d1ks8a_.ent-d1lf6a1.ent", "d1ks8a_.ent-d1n1ba1.ent", "d1ks8a_.ent-d1n7oa1.ent", "d1ks8a_.ent-d1qaza_.ent", "d1ks8a_.ent-d2sqca1.ent", "d1ks8a_.ent-d2sqca2.ent", "d1ks9a1.ent-d1m66a1.ent", "d1ks9a1.ent-d1pgja1.ent", "d1ks9a1.ent-d1qmga1.ent", "d1ks9a1.ent-d2pgd_1.ent", "d1ksfx3.ent-d1a7j__.ent", "d1ksfx3.ent-d1aqua_.ent", "d1ksfx3.ent-d1cr1a_.ent", "d1ksfx3.ent-d1e69a_.ent", "d1ksfx3.ent-d1e79a3.ent", "d1ksfx3.ent-d1f5na2.ent", "d1ksfx3.ent-d1fnna2.ent", "d1ksfx3.ent-d1g8ya_.ent", "d1ksfx3.ent-d1gm5a3.ent", "d1ksfx3.ent-d1ihua1.ent", "d1ksfx3.ent-d1jwyb_.ent", "d1ksfx3.ent-d1lv7a_.ent", "d1ksfx3.ent-d1m6na3.ent", "d1ksfx3.ent-d1nsta_.ent", "d1ksfx3.ent-d1uaaa1.ent", "d1ksia2.ent-d1ksia3.ent", "d1ksia2.ent-d1kwia_.ent", "d1ksia2.ent-d1mola_.ent", "d1ksia2.ent-d1mwxa1.ent", "d1ksia2.ent-d1o7nb_.ent", "d1ksia2.ent-d1oaca2.ent", "d1ksia2.ent-d1oaca3.ent", "d1ksia2.ent-d1stfi_.ent", "d1ksia2.ent-d1ugia_.ent", "d1ksia2.ent-d3stda_.ent", "d1ksia3.ent-d1kwia_.ent", "d1ksia3.ent-d1mola_.ent", "d1ksia3.ent-d1mwxa1.ent", "d1ksia3.ent-d1o7nb_.ent", "d1ksia3.ent-d1oaca2.ent", "d1ksia3.ent-d1oaca3.ent", "d1ksia3.ent-d1stfi_.ent", "d1ksia3.ent-d1ugia_.ent", "d1ksia3.ent-d3stda_.ent", "d1kssa1.ent-d1m1qa_.ent", "d1kssa1.ent-d1qo8a1.ent", "d1kssa1.ent-d1wad__.ent", "d1kssa1.ent-d2ctha_.ent", "d1kssa1.ent-d2cy3__.ent", "d1kssa1.ent-d3caoa_.ent", "d1kssa1.ent-d3cyr__.ent", "d1kssa2.ent-d1chua2.ent", "d1kssa2.ent-d1cjca1.ent", "d1kssa2.ent-d1ebda1.ent", "d1kssa2.ent-d1feca1.ent", "d1kssa2.ent-d1h6va1.ent", "d1kssa2.ent-d1jeha1.ent", "d1kssa2.ent-d1k0ia1.ent", "d1kssa2.ent-d1kf6a2.ent", "d1kssa2.ent-d1l9ea1.ent", "d1kssa2.ent-d1lqta1.ent", "d1kssa2.ent-d1m6ia1.ent", "d1kssa2.ent-d1m6ia2.ent", "d1kssa2.ent-d1mo9a1.ent", "d1kssa2.ent-d1nhp_1.ent", "d1kssa2.ent-d1nhp_2.ent", "d1kssa2.ent-d1o94a2.ent", "d1kssa2.ent-d1ojt_1.ent", "d1kssa2.ent-d1qo8a2.ent", "d1kssa2.ent-d3grs_1.ent", "d1kssa2.ent-d3grs_2.ent", "d1kssa2.ent-d3lada1.ent", "d1kssa3.ent-d1neka3.ent", "d1kssa3.ent-d1qlaa3.ent", "d1kssa3.ent-d1qo8a3.ent", "d1kt1a1.ent-d1qqea_.ent", "d1kt1a3.ent-d1m5ya2.ent", "d1kt1a3.ent-d1m5ya3.ent", "d1kt1a3.ent-d1n1aa_.ent", "d1kt1a3.ent-d1pbk__.ent", "d1kt1a3.ent-d1pina2.ent", "d1ktba1.ent-d1kwga1.ent", "d1ktba1.ent-d1lwha1.ent", "d1ktba1.ent-d1m7xa2.ent", "d1ktba1.ent-d1qhoa3.ent", "d1ktba1.ent-d1uok_1.ent", "d1ktba1.ent-d7taa_1.ent", "d1kte__.ent-d1a8y_2.ent", "d1kte__.ent-d1aba__.ent", "d1kte__.ent-d1aqwa2.ent", "d1kte__.ent-d1e6ba2.ent", "d1kte__.ent-d1fb6a_.ent", "d1kte__.ent-d1fhe_2.ent", "d1kte__.ent-d1hyua4.ent", "d1kte__.ent-d1iloa_.ent", "d1kte__.ent-d1k0ma2.ent", "d1kte__.ent-d1k3ya2.ent", "d1kte__.ent-d1m2da_.ent", "d1kte__.ent-d1qmha1.ent", "d1kte__.ent-d1quwa_.ent", "d1ktga_.ent-d1mut__.ent", "d1ktha_.ent-d1tfxc_.ent", "d1ktha_.ent-d1tocr1.ent", "d1ktha_.ent-d1tocr2.ent", "d1ktja_.ent-d1ea9c1.ent", "d1ktja_.ent-d1edqa1.ent", "d1ktja_.ent-d1eut_1.ent", "d1ktja_.ent-d1j0ha1.ent", "d1ktja_.ent-d1ji1a1.ent", "d1ktja_.ent-d1ji2a1.ent", "d1ktja_.ent-d1kv3a1.ent", "d1ktja_.ent-d1m7xa1.ent", "d1ktja_.ent-d1my7a_.ent", "d1ktja_.ent-d1qba_1.ent", "d1ktja_.ent-d1qfha1.ent", "d1ktja_.ent-d1qfha2.ent", "d1ktja_.ent-d1soxa1.ent", "d1ktke1.ent-d1a2yb_.ent", "d1ktke1.ent-d1akjd_.ent", "d1ktke1.ent-d1b88a_.ent", "d1ktke1.ent-d1bec_1.ent", "d1ktke1.ent-d1c5ch1.ent", "d1ktke1.ent-d1dlfl_.ent", "d1ktke1.ent-d1dqta_.ent", "d1ktke1.ent-d1fo0a_.ent", "d1ktke1.ent-d1gsma2.ent", "d1ktke1.ent-d1h5ba_.ent", "d1ktke1.ent-d1kxvc_.ent", "d1ktke1.ent-d1neu__.ent", "d1ktke1.ent-d1nfdb1.ent", "d1ktke1.ent-d1qfoa_.ent", "d1ktke1.ent-d1tvda_.ent", "d1ktke1.ent-d2rhe__.ent", "d1ku0a_.ent-d1bu8a2.ent", "d1ku0a_.ent-d1cr6a2.ent", "d1ku0a_.ent-d1cvl__.ent", "d1ku0a_.ent-d1hlga_.ent", "d1ku0a_.ent-d1iz7a_.ent", "d1ku0a_.ent-d1jjia_.ent", "d1ku0a_.ent-d1jkma_.ent", "d1ku0a_.ent-d1ju3a2.ent", "d1ku0a_.ent-d1l7aa_.ent", "d1ku0a_.ent-d1lzla_.ent", "d1ku0a_.ent-d1mnaa_.ent", "d1ku0a_.ent-d1n1ma2.ent", "d1ku0a_.ent-d1qj4a_.ent", "d1ku0a_.ent-d1qlwa_.ent", "d1ku0a_.ent-d1qo7a_.ent", "d1ku0a_.ent-d1qtra_.ent", "d1ku0a_.ent-d1tca__.ent", "d1ku0a_.ent-d1thta_.ent", "d1ku0a_.ent-d3tgl__.ent", "d1ku3a_.ent-d1l0oc_.ent", "d1ku3a_.ent-d1sig__.ent", "d1kufa_.ent-d1lml__.ent", "d1kufa_.ent-d1qba_4.ent", "d1kufa_.ent-d3btaa3.ent", "d1kuua_.ent-d1llwa3.ent", "d1kuua_.ent-d1ryp1_.ent", "d1kuua_.ent-d1ryp2_.ent", "d1kuua_.ent-d1rypa_.ent", "d1kuua_.ent-d1rypl_.ent", "d1kv3a1.ent-d1eut_1.ent", "d1kv3a1.ent-d1my7a_.ent", "d1kv3a1.ent-d1qba_1.ent", "d1kv3a1.ent-d1qfha1.ent", "d1kv3a1.ent-d1qfha2.ent", "d1kv3a2.ent-d1kv3a3.ent", "d1kv3a2.ent-d1l9na2.ent", "d1kv3a2.ent-d1l9na3.ent", "d1kv3a3.ent-d1l9na2.ent", "d1kv3a3.ent-d1l9na3.ent", "d1kv6a_.ent-d1lv2a_.ent", "d1kv6a_.ent-d1mzna_.ent", "d1kv6a_.ent-d1n83a_.ent", "d1kv6a_.ent-d2prga_.ent", "d1kv7a1.ent-d1kv7a2.ent", "d1kv7a1.ent-d1kv7a3.ent", "d1kv7a1.ent-d1kzqa1.ent", "d1kv7a1.ent-d1l9qa1.ent", "d1kv7a1.ent-d1l9qa2.ent", "d1kv7a1.ent-d1qhqa_.ent", "d1kv7a1.ent-d2cbp__.ent", "d1kv7a1.ent-d2cuaa_.ent", "d1kv7a2.ent-d1cyx__.ent", "d1kv7a2.ent-d1e30a_.ent", "d1kv7a2.ent-d1gw0a1.ent", "d1kv7a2.ent-d1ikop_.ent", "d1kv7a2.ent-d1kbva1.ent", "d1kv7a2.ent-d1kbva2.ent", "d1kv7a2.ent-d1kcw_2.ent", "d1kv7a2.ent-d1kcw_4.ent", "d1kv7a2.ent-d1kcw_6.ent", "d1kv7a2.ent-d1kv7a1.ent", "d1kv7a2.ent-d1kv7a3.ent", "d1kv7a2.ent-d1kzqa1.ent", "d1kv7a2.ent-d1l9qa1.ent", "d1kv7a2.ent-d1l9qa2.ent", "d1kv7a2.ent-d1m56b1.ent", "d1kv7a2.ent-d1qhqa_.ent", "d1kv7a2.ent-d2cbp__.ent", "d1kv7a2.ent-d2cuaa_.ent", "d1kv7a3.ent-d1e30a_.ent", "d1kv7a3.ent-d1ikop_.ent", "d1kv7a3.ent-d1kbva1.ent", "d1kv7a3.ent-d1kbva2.ent", "d1kv7a3.ent-d1kcw_2.ent", "d1kv7a3.ent-d1kcw_4.ent", "d1kv7a3.ent-d1kcw_6.ent", "d1kv7a3.ent-d1kv7a1.ent", "d1kv7a3.ent-d1kzqa1.ent", "d1kv7a3.ent-d1l9qa1.ent", "d1kv7a3.ent-d1l9qa2.ent", "d1kv7a3.ent-d1qhqa_.ent", "d1kv7a3.ent-d2cbp__.ent", "d1kv7a3.ent-d2cuaa_.ent", "d1kv8a_.ent-d1nsj__.ent", "d1kv8a_.ent-d1pii_1.ent", "d1kv8a_.ent-d1pii_2.ent", "d1kv8a_.ent-d1qopa_.ent", "d1kv8a_.ent-d1rpxa_.ent", "d1kv8a_.ent-d1thfd_.ent", "d1kv9a1.ent-d1etpa2.ent", "d1kv9a1.ent-d1kb0a1.ent", "d1kv9a1.ent-d1ql3a_.ent", "d1kv9a1.ent-d1qn2a_.ent", "d1kvka1.ent-d1mu5a2.ent", "d1kvka1.ent-d1n0ua3.ent", "d1kvka1.ent-d1pkp_1.ent", "d1kvka2.ent-d1b3ta_.ent", "d1kvka2.ent-d1dj0a2.ent", "d1kvka2.ent-d1dqaa1.ent", "d1kvka2.ent-d1ekra_.ent", "d1kvka2.ent-d1eqoa_.ent", "d1kvka2.ent-d1f3va_.ent", "d1kvka2.ent-d1ftra1.ent", "d1kvka2.ent-d1ftra2.ent", "d1kvka2.ent-d1gpja3.ent", "d1kvka2.ent-d1h72c2.ent", "d1kvka2.ent-d1hlwa_.ent", "d1kvka2.ent-d1jnrb_.ent", "d1kvka2.ent-d1qd1a2.ent", "d1kvka2.ent-d1regx_.ent", "d1kvna_.ent-d1lnga_.ent", "d1kvoa_.ent-d1le6a_.ent", "d1kvoa_.ent-d1mc2a_.ent", "d1kvoa_.ent-d1poc__.ent", "d1kw3b1.ent-d1kw3b2.ent", "d1kw3b1.ent-d1lqpa_.ent", "d1kw3b1.ent-d1mpya1.ent", "d1kw3b1.ent-d1mpya2.ent", "d1kw3b1.ent-d1qipa_.ent", "d1kw3b1.ent-d1qtoa_.ent", "d1kw3b2.ent-d1lqpa_.ent", "d1kw3b2.ent-d1mpya1.ent", "d1kw3b2.ent-d1mpya2.ent", "d1kw3b2.ent-d1qipa_.ent", "d1kw3b2.ent-d1qtoa_.ent", "d1kwaa_.ent-d1lcya1.ent", "d1kwaa_.ent-d1m5za_.ent", "d1kwaa_.ent-d1mfga_.ent", "d1kwaa_.ent-d1qaua_.ent", "d1kwaa_.ent-d1qava_.ent", "d1kwaa_.ent-d1qlca_.ent", "d1kwfa_.ent-d1ld8b_.ent", "d1kwfa_.ent-d1lf6a1.ent", "d1kwfa_.ent-d1n1ba1.ent", "d1kwfa_.ent-d1n7oa1.ent", "d1kwfa_.ent-d1qaza_.ent", "d1kwfa_.ent-d2sqca1.ent", "d1kwfa_.ent-d2sqca2.ent", "d1kwga1.ent-d1lwha1.ent", "d1kwga1.ent-d1m7xa2.ent", "d1kwga1.ent-d1qhoa3.ent", "d1kwga1.ent-d1uok_1.ent", "d1kwga1.ent-d7taa_1.ent", "d1kwga2.ent-d1d3ga_.ent", "d1kwga2.ent-d1edg__.ent", "d1kwga2.ent-d1gvoa_.ent", "d1kwga2.ent-d1gw1a_.ent", "d1kwga2.ent-d1iexa1.ent", "d1kwga2.ent-d1itua_.ent", "d1kwga2.ent-d1j0ha3.ent", "d1kwga2.ent-d1k4ga_.ent", "d1kwga2.ent-d1kbla1.ent", "d1kwga2.ent-d1lwha2.ent", "d1kwga2.ent-d1m7ja3.ent", "d1kwga2.ent-d1muwa_.ent", "d1kwga2.ent-d7taa_2.ent", "d1kwga3.ent-d1cf9a1.ent", "d1kwga3.ent-d1e5da1.ent", "d1kwga3.ent-d1euca2.ent", "d1kwga3.ent-d1f4pa_.ent", "d1kwga3.ent-d1f8ya_.ent", "d1kwga3.ent-d1fuea_.ent", "d1kwga3.ent-d1h05a_.ent", "d1kwga3.ent-d1l7da2.ent", "d1kwga3.ent-d1l9xa_.ent", "d1kwga3.ent-d1qdlb_.ent", "d1kwga3.ent-d1qo0d_.ent", "d1kwga3.ent-d2naca2.ent", "d1kwga3.ent-d7reqb2.ent", "d1kwha_.ent-d1lst__.ent", "d1kwha_.ent-d1m5ea_.ent", "d1kwha_.ent-d1mrp__.ent", "d1kwha_.ent-d1nh8a1.ent", "d1kwha_.ent-d1pda_1.ent", "d1kwha_.ent-d1pot__.ent", "d1kwha_.ent-d1sbp__.ent", "d1kwha_.ent-d1wdna_.ent", "d1kwha_.ent-d3mbp__.ent", "d1kwha_.ent-d3thia_.ent", "d1kwia_.ent-d1mola_.ent", "d1kwia_.ent-d1mwxa1.ent", "d1kwia_.ent-d1o7nb_.ent", "d1kwia_.ent-d1oaca2.ent", "d1kwia_.ent-d1stfi_.ent", "d1kwia_.ent-d1ugia_.ent", "d1kwia_.ent-d3stda_.ent", "d1kwma1.ent-d1lam_2.ent", "d1kwma1.ent-d1lfwa1.ent", "d1kwma1.ent-d1loka_.ent", "d1kwma1.ent-d1m4la_.ent", "d1kwma1.ent-d1obr__.ent", "d1kwma2.ent-d1scjb_.ent", "d1kwpa_.ent-d1a06__.ent", "d1kwpa_.ent-d1blxa_.ent", "d1kwpa_.ent-d1csn__.ent", "d1kwpa_.ent-d1f3mc_.ent", "d1kwpa_.ent-d1fgka_.ent", "d1kwpa_.ent-d1fvra_.ent", "d1kwpa_.ent-d1ia9a_.ent", "d1kwpa_.ent-d1iepa_.ent", "d1kwpa_.ent-d1jksa_.ent", "d1kwpa_.ent-d1jpaa_.ent", "d1kwpa_.ent-d1jvpp_.ent", "d1kwpa_.ent-d1lufa_.ent", "d1kwpa_.ent-d1m14a_.ent", "d1kwpa_.ent-d1phk__.ent", "d1kwsa_.ent-d1ll2a_.ent", "d1kwsa_.ent-d1lzja_.ent", "d1kwsa_.ent-d1nf5b_.ent", "d1kwsa_.ent-d1qg8a_.ent", "d1kx5a_.ent-d1kx5b_.ent", "d1kx5a_.ent-d1kx5c_.ent", "d1kx5a_.ent-d1kx5d_.ent", "d1kx5a_.ent-d1n1ja_.ent", "d1kx5a_.ent-d1n1jb_.ent", "d1kx5b_.ent-d1kx5c_.ent", "d1kx5b_.ent-d1kx5d_.ent", "d1kx5b_.ent-d1n1ja_.ent", "d1kx5b_.ent-d1n1jb_.ent", "d1kx5c_.ent-d1kx5d_.ent", "d1kx5c_.ent-d1n1ja_.ent", "d1kx5c_.ent-d1n1jb_.ent", "d1kx5d_.ent-d1n1ja_.ent", "d1kx5d_.ent-d1n1jb_.ent", "d1kx9a_.ent-d1lrv__.ent", "d1kx9a_.ent-d1n4ka1.ent", "d1kxga_.ent-d1tnra_.ent", "d1kxga_.ent-d2tnfa_.ent", "d1kxla_.ent-d1b3qa2.ent", "d1kxla_.ent-d1br9__.ent", "d1kxla_.ent-d1d7qa_.ent", "d1kxla_.ent-d1e1oa1.ent", "d1kxla_.ent-d1eova1.ent", "d1kxla_.ent-d1ewia_.ent", "d1kxla_.ent-d1fgua1.ent", "d1kxla_.ent-d1fgua2.ent", "d1kxla_.ent-d1fjgl_.ent", "d1kxla_.ent-d1fl0a_.ent", "d1kxla_.ent-d1gm5a2.ent", "d1kxla_.ent-d1go3e_.ent", "d1kxla_.ent-d1i40a_.ent", "d1kxla_.ent-d1i50h_.ent", "d1kxla_.ent-d1iyjb3.ent", "d1kxla_.ent-d1iyjb5.ent", "d1kxla_.ent-d1jb3a_.ent", "d1kxla_.ent-d1jb7a1.ent", "d1kxla_.ent-d1jb7a2.ent", "d1kxla_.ent-d1jb7a3.ent", "d1kxla_.ent-d1je5a_.ent", "d1kxla_.ent-d1jjcb3.ent", "d1kxla_.ent-d1k28a1.ent", "d1kxla_.ent-d1l1oc_.ent", "d1kxla_.ent-d1quqa_.ent", "d1kxla_.ent-d1quqb_.ent", "d1kxla_.ent-d1qvca_.ent", "d1kxla_.ent-d1sty__.ent", "d1kxla_.ent-d3seb_1.ent", "d1kxpd1.ent-d1kxpd2.ent", "d1kxpd1.ent-d1kxpd3.ent", "d1kxpd2.ent-d1kxpd3.ent", "d1kxra_.ent-d1l9na4.ent", "d1kxra_.ent-d1me4a_.ent", "d1kxra_.ent-d1nbfa_.ent", "d1kxra_.ent-d1ppn__.ent", "d1kxra_.ent-d1qmya_.ent", "d1kxra_.ent-d1uch__.ent", "d1kxra_.ent-d2act__.ent", "d1kxra_.ent-d2cb5a_.ent", "d1kxra_.ent-d3gcb__.ent", "d1kxra_.ent-d7pcka_.ent", "d1kxvc_.ent-d1a2yb_.ent", "d1kxvc_.ent-d1akjd_.ent", "d1kxvc_.ent-d1b88a_.ent", "d1kxvc_.ent-d1bec_1.ent", "d1kxvc_.ent-d1c5ch1.ent", "d1kxvc_.ent-d1dlfl_.ent", "d1kxvc_.ent-d1dqta_.ent", "d1kxvc_.ent-d1fo0a_.ent", "d1kxvc_.ent-d1gsma2.ent", "d1kxvc_.ent-d1h5ba_.ent", "d1kxvc_.ent-d1neu__.ent", "d1kxvc_.ent-d1nfdb1.ent", "d1kxvc_.ent-d1qfoa_.ent", "d1kxvc_.ent-d1tvda_.ent", "d1kxvc_.ent-d2rhe__.ent", "d1kyfa1.ent-d1dqia_.ent", "d1kyfa1.ent-d1eaja_.ent", "d1kyfa1.ent-d1grwa_.ent", "d1kyfa1.ent-d1j0ha1.ent", "d1kyfa1.ent-d1jmxa4.ent", "d1kyfa1.ent-d1kgce2.ent", "d1kyfa1.ent-d1lmia_.ent", "d1kyfa1.ent-d1m1xb1.ent", "d1kyfa1.ent-d1nepa_.ent", "d1kyfa1.ent-d1o75a1.ent", "d1kyfa1.ent-d1soxa1.ent", "d1kyga_.ent-d1a8l_1.ent", "d1kyga_.ent-d1a8l_2.ent", "d1kyga_.ent-d1a8y_1.ent", "d1kyga_.ent-d1a8y_3.ent", "d1kyga_.ent-d1bed_2.ent", "d1kyga_.ent-d1bjx__.ent", "d1kyga_.ent-d1eeja1.ent", "d1kyga_.ent-d1ep7a_.ent", "d1kyga_.ent-d1erv__.ent", "d1kyga_.ent-d1f9ma_.ent", "d1kyga_.ent-d1fb6a_.ent", "d1kyga_.ent-d1fvka2.ent", "d1kyga_.ent-d1g7ea_.ent", "d1kyga_.ent-d1gh2a_.ent", "d1kyga_.ent-d1hd2a_.ent", "d1kyga_.ent-d1i5ga_.ent", "d1kyga_.ent-d1knga_.ent", "d1kyga_.ent-d1kte__.ent", "d1kyga_.ent-d1mek__.ent", "d1kyga_.ent-d1quwa_.ent", "d1kyga_.ent-d1thx__.ent", "d1kyga_.ent-d2trxa_.ent", "d1kywa2.ent-d1fp1d2.ent", "d1kywa2.ent-d1g60a_.ent", "d1kywa2.ent-d1i1na_.ent", "d1kywa2.ent-d1jg1a_.ent", "d1kywa2.ent-d1qama_.ent", "d1kz1a_.ent-d1rvv1_.ent", "d1kz8a_.ent-d1lbva_.ent", "d1kz8a_.ent-d2hhma_.ent", "d1kzfa_.ent-d1lrza2.ent", "d1kzfa_.ent-d1lrza3.ent", "d1kzfa_.ent-d1m4ia_.ent", "d1kzfa_.ent-d1qsma_.ent", "d1kzfa_.ent-d1qsta_.ent", "d1kzka_.ent-d1lf2a_.ent", "d1kzka_.ent-d1mpp__.ent", "d1kzka_.ent-d1nsoa_.ent", "d1kzka_.ent-d2apr__.ent", "d1kzka_.ent-d2rspa_.ent", "d1kzka_.ent-d3psg__.ent", "d1kzka_.ent-d4fiv__.ent", "d1kzla1.ent-d1kzla2.ent", "d1kzla1.ent-d1n08a_.ent", "d1kzla1.ent-d1n0ua1.ent", "d1kzla1.ent-d1qfja1.ent", "d1kzla1.ent-d1que_1.ent", "d1kzla1.ent-d2cnd_1.ent", "d1kzla1.ent-d2pia_1.ent", "d1kzla2.ent-d1n08a_.ent", "d1kzla2.ent-d1n0ua1.ent", "d1kzla2.ent-d1qfja1.ent", "d1kzla2.ent-d1que_1.ent", "d1kzla2.ent-d2cnd_1.ent", "d1kzla2.ent-d2pia_1.ent", "d1kzqa1.ent-d1l9qa1.ent", "d1kzqa1.ent-d1l9qa2.ent", "d1kzqa1.ent-d2cbp__.ent", "d1kzqa1.ent-d2cuaa_.ent", "d1l0ba1.ent-d1l0ba2.ent", "d1l0ga_.ent-d1m40a_.ent", "d1l0ga_.ent-d1mfoa_.ent", "d1l0ga_.ent-d1mwxa3.ent", "d1l0ga_.ent-d1nj4a2.ent", "d1l0ga_.ent-d1qmea4.ent", "d1l0ga_.ent-d4blma_.ent", "d1l0oa_.ent-d1mu5a3.ent", "d1l0oc_.ent-d1sig__.ent", "d1l1la_.ent-d1rlr_2.ent", "d1l1oc_.ent-d1b3qa2.ent", "d1l1oc_.ent-d1d7qa_.ent", "d1l1oc_.ent-d1e1oa1.ent", "d1l1oc_.ent-d1eova1.ent", "d1l1oc_.ent-d1ewia_.ent", "d1l1oc_.ent-d1fgua1.ent", "d1l1oc_.ent-d1fgua2.ent", "d1l1oc_.ent-d1fjgl_.ent", "d1l1oc_.ent-d1fl0a_.ent", "d1l1oc_.ent-d1i50h_.ent", "d1l1oc_.ent-d1iyjb3.ent", "d1l1oc_.ent-d1iyjb5.ent", "d1l1oc_.ent-d1jb3a_.ent", "d1l1oc_.ent-d1jb7a1.ent", "d1l1oc_.ent-d1jb7a2.ent", "d1l1oc_.ent-d1jb7a3.ent", "d1l1oc_.ent-d1jjcb3.ent", "d1l1oc_.ent-d1k28a1.ent", "d1l1oc_.ent-d1quqa_.ent", "d1l1oc_.ent-d1quqb_.ent", "d1l1oc_.ent-d1qvca_.ent", "d1l1oc_.ent-d1sty__.ent", "d1l1oc_.ent-d3seb_1.ent", "d1l1qa_.ent-d1lh0a_.ent", "d1l1qa_.ent-d1nula_.ent", "d1l1qa_.ent-d1qb7a_.ent", "d1l1qa_.ent-d1tc1a_.ent", "d1l1za1.ent-d1mu5a1.ent", "d1l1za1.ent-d1nnja1.ent", "d1l1za2.ent-d1nnja2.ent", "d1l1za3.ent-d1lata_.ent", "d1l1za3.ent-d1lv3a_.ent", "d1l1za3.ent-d1zfo__.ent", "d1l1za3.ent-d2nllb_.ent", "d1l1za3.ent-d3gata_.ent", "d1l1za3.ent-d7gata_.ent", "d1l2ha_.ent-d1n4ka2.ent", "d1l2ha_.ent-d1nuna_.ent", "d1l2ha_.ent-d1qqla_.ent", "d1l2la_.ent-d1lhpa_.ent", "d1l2la_.ent-d1liia_.ent", "d1l2la_.ent-d1o14a_.ent", "d1l2la_.ent-d1rkd__.ent", "d1l2ma_.ent-d1m55a_.ent", "d1l2ma_.ent-d1tbd__.ent", "d1l2pa_.ent-d1m56d_.ent", "d1l2pa_.ent-d1ocrd_.ent", "d1l2pa_.ent-d1ocrg_.ent", "d1l2pa_.ent-d1ocri_.ent", "d1l2pa_.ent-d1ocrj_.ent", "d1l2pa_.ent-d1ocrk_.ent", "d1l2pa_.ent-d1ocrl_.ent", "d1l2pa_.ent-d1ocrm_.ent", "d1l3ka1.ent-d1l3ka2.ent", "d1l3ka1.ent-d1nu4a_.ent", "d1l3ka1.ent-d1qm9a1.ent", "d1l3ka1.ent-d1qm9a2.ent", "d1l3ka1.ent-d1u2fa_.ent", "d1l3ka1.ent-d2msta_.ent", "d1l3ka1.ent-d2u1a__.ent", "d1l3ka1.ent-d2u2fa_.ent", "d1l3ka2.ent-d1nu4a_.ent", "d1l3ka2.ent-d1qm9a1.ent", "d1l3ka2.ent-d1qm9a2.ent", "d1l3ka2.ent-d1u2fa_.ent", "d1l3ka2.ent-d2msta_.ent", "d1l3ka2.ent-d2u1a__.ent", "d1l3ka2.ent-d2u2fa_.ent", "d1l3wa3.ent-d1l3wa4.ent", "d1l3wa3.ent-d1l3wa5.ent", "d1l3wa4.ent-d1l3wa5.ent", "d1l3ya_.ent-d1tpg_1.ent", "d1l4db_.ent-d1ayfa_.ent", "d1l4db_.ent-d1bmlc3.ent", "d1l4db_.ent-d1c9fa_.ent", "d1l4db_.ent-d1czpa_.ent", "d1l4db_.ent-d1f52a1.ent", "d1l4db_.ent-d1fm0d_.ent", "d1l4db_.ent-d1h4ra3.ent", "d1l4db_.ent-d1h8ca_.ent", "d1l4db_.ent-d1i42a_.ent", "d1l4db_.ent-d1ip9a_.ent", "d1l4db_.ent-d1k8rb_.ent", "d1l4db_.ent-d1l5pa_.ent", "d1l4db_.ent-d1l7ya_.ent", "d1l4db_.ent-d1lfda_.ent", "d1l4db_.ent-d1lm8b_.ent", "d1l4db_.ent-d1qlab2.ent", "d1l4db_.ent-d1qqra_.ent", "d1l4db_.ent-d2sak__.ent", "d1l4db_.ent-d3tss_2.ent", "d1l4ia1.ent-d1qpxa1.ent", "d1l4ia2.ent-d1rsy__.ent", "d1l4ia2.ent-d1who__.ent", "d1l5aa1.ent-d1l5aa2.ent", "d1l5aa1.ent-d1nocb_.ent", "d1l5aa1.ent-d3cla__.ent", "d1l5aa2.ent-d1nocb_.ent", "d1l5aa2.ent-d3cla__.ent", "d1l5ja1.ent-d1elka_.ent", "d1l5ja1.ent-d1hs6a1.ent", "d1l5ja1.ent-d1kpsb_.ent", "d1l5ja1.ent-d1n4ka1.ent", "d1l5ja2.ent-d1nbwa1.ent", "d1l5pa_.ent-d1bmlc3.ent", "d1l5pa_.ent-d1c9fa_.ent", "d1l5pa_.ent-d1fm0d_.ent", "d1l5pa_.ent-d1h4ra3.ent", "d1l5pa_.ent-d1h8ca_.ent", "d1l5pa_.ent-d1i42a_.ent", "d1l5pa_.ent-d1ip9a_.ent", "d1l5pa_.ent-d1k8rb_.ent", "d1l5pa_.ent-d1lfda_.ent", "d1l5pa_.ent-d1n62a2.ent", "d1l5pa_.ent-d1nekb2.ent", "d1l5pa_.ent-d1put__.ent", "d1l5pa_.ent-d1qlab2.ent", "d1l5pa_.ent-d2pia_3.ent", "d1l6ja1.ent-d1lbu_1.ent", "d1l6ja1.ent-d1slm_1.ent", "d1l6ja3.ent-d1l6ja5.ent", "d1l6ja3.ent-d1pmla_.ent", "d1l6ja3.ent-d2hpqp_.ent", "d1l6ja3.ent-d5hpga_.ent", "d1l6ja5.ent-d1pmla_.ent", "d1l6ja5.ent-d2hpqp_.ent", "d1l6ja5.ent-d5hpga_.ent", "d1l6ra_.ent-d1mh9a_.ent", "d1l6ra_.ent-d1qq5a_.ent", "d1l6ra_.ent-d1zrn__.ent", "d1l6wa_.ent-d1mzha_.ent", "d1l6wa_.ent-d1nal1_.ent", "d1l6wa_.ent-d1o0ya_.ent", "d1l6wa_.ent-d1qfea_.ent", "d1l7aa_.ent-d1cvl__.ent", "d1l7aa_.ent-d1iz7a_.ent", "d1l7aa_.ent-d1jjia_.ent", "d1l7aa_.ent-d1lzla_.ent", "d1l7aa_.ent-d1mnaa_.ent", "d1l7aa_.ent-d1n1ma2.ent", "d1l7aa_.ent-d1qj4a_.ent", "d1l7aa_.ent-d1qlwa_.ent", "d1l7aa_.ent-d1qo7a_.ent", "d1l7aa_.ent-d1qtra_.ent", "d1l7aa_.ent-d1tca__.ent", "d1l7aa_.ent-d1thta_.ent", "d1l7aa_.ent-d3tgl__.ent", "d1l7da2.ent-d1cf9a1.ent", "d1l7da2.ent-d1e5da1.ent", "d1l7da2.ent-d1euca2.ent", "d1l7da2.ent-d1f4pa_.ent", "d1l7da2.ent-d1f8ya_.ent", "d1l7da2.ent-d1fuea_.ent", "d1l7da2.ent-d1h05a_.ent", "d1l7da2.ent-d1mx3a2.ent", "d1l7da2.ent-d1pjca2.ent", "d1l7da2.ent-d1psda2.ent", "d1l7da2.ent-d1qo0d_.ent", "d1l7da2.ent-d2naca2.ent", "d1l7da2.ent-d7reqb2.ent", "d1l7la_.ent-d1lnsa2.ent", "d1l7la_.ent-d1xnaa_.ent", "d1l7ya_.ent-d1bmlc3.ent", "d1l7ya_.ent-d1c9fa_.ent", "d1l7ya_.ent-d1fm0d_.ent", "d1l7ya_.ent-d1h4ra3.ent", "d1l7ya_.ent-d1h8ca_.ent", "d1l7ya_.ent-d1i42a_.ent", "d1l7ya_.ent-d1ip9a_.ent", "d1l7ya_.ent-d1k8rb_.ent", "d1l7ya_.ent-d1l5pa_.ent", "d1l7ya_.ent-d1lfda_.ent", "d1l7ya_.ent-d1lm8b_.ent", "d1l7ya_.ent-d1m94a_.ent", "d1l7ya_.ent-d1rlf__.ent", "d1l8aa1.ent-d1l8aa2.ent", "d1l8aa1.ent-d1poxa2.ent", "d1l8aa1.ent-d1poxa3.ent", "d1l8aa1.ent-d1pvda2.ent", "d1l8aa1.ent-d1pvda3.ent", "d1l8aa1.ent-d1zpda2.ent", "d1l8aa1.ent-d1zpda3.ent", "d1l8aa2.ent-d1poxa2.ent", "d1l8aa2.ent-d1poxa3.ent", "d1l8aa2.ent-d1pvda2.ent", "d1l8aa2.ent-d1pvda3.ent", "d1l8aa2.ent-d1zpda2.ent", "d1l8aa2.ent-d1zpda3.ent", "d1l9ea1.ent-d1chua2.ent", "d1l9ea1.ent-d1cjca1.ent", "d1l9ea1.ent-d1ebda1.ent", "d1l9ea1.ent-d1feca1.ent", "d1l9ea1.ent-d1h6va1.ent", "d1l9ea1.ent-d1jeha1.ent", "d1l9ea1.ent-d1lqta1.ent", "d1l9ea1.ent-d1m6ia1.ent", "d1l9ea1.ent-d1m6ia2.ent", "d1l9ea1.ent-d1mo9a1.ent", "d1l9ea1.ent-d1nhp_1.ent", "d1l9ea1.ent-d1nhp_2.ent", "d1l9ea1.ent-d1o94a2.ent", "d1l9ea1.ent-d1ojt_1.ent", "d1l9ea1.ent-d3grs_1.ent", "d1l9ea1.ent-d3grs_2.ent", "d1l9ea1.ent-d3lada1.ent", "d1l9ea2.ent-d1mxta2.ent", "d1l9ha_.ent-d1m0ka_.ent", "d1l9la_.ent-d1n69a_.ent", "d1l9la_.ent-d1nkl__.ent", "d1l9na1.ent-d1dqia_.ent", "d1l9na1.ent-d1ea9c1.ent", "d1l9na1.ent-d1eaja_.ent", "d1l9na1.ent-d1edqa1.ent", "d1l9na1.ent-d1eut_1.ent", "d1l9na1.ent-d1g0da1.ent", "d1l9na1.ent-d1grwa_.ent", "d1l9na1.ent-d1j0ha1.ent", "d1l9na1.ent-d1ji1a1.ent", "d1l9na1.ent-d1ji2a1.ent", "d1l9na1.ent-d1jjua4.ent", "d1l9na1.ent-d1jmxa4.ent", "d1l9na1.ent-d1kgce2.ent", "d1l9na1.ent-d1kmta_.ent", "d1l9na1.ent-d1ktja_.ent", "d1l9na1.ent-d1kv3a1.ent", "d1l9na1.ent-d1kyfa1.ent", "d1l9na1.ent-d1lmia_.ent", "d1l9na1.ent-d1m1xa2.ent", "d1l9na1.ent-d1m1xb1.ent", "d1l9na1.ent-d1m7xa1.ent", "d1l9na1.ent-d1my7a_.ent", "d1l9na1.ent-d1nepa_.ent", "d1l9na1.ent-d1o75a1.ent", "d1l9na1.ent-d1qba_1.ent", "d1l9na1.ent-d1qfha1.ent", "d1l9na1.ent-d1qfha2.ent", "d1l9na1.ent-d1soxa1.ent", "d1l9na2.ent-d1l9na3.ent", "d1l9na4.ent-d1me4a_.ent", "d1l9na4.ent-d1nbfa_.ent", "d1l9na4.ent-d1ppn__.ent", "d1l9na4.ent-d1qmya_.ent", "d1l9na4.ent-d1uch__.ent", "d1l9na4.ent-d2act__.ent", "d1l9na4.ent-d2cb5a_.ent", "d1l9na4.ent-d3gcb__.ent", "d1l9na4.ent-d7pcka_.ent", "d1l9qa1.ent-d1cyx__.ent", "d1l9qa1.ent-d1e30a_.ent", "d1l9qa1.ent-d1gw0a1.ent", "d1l9qa1.ent-d1ikop_.ent", "d1l9qa1.ent-d1kbva1.ent", "d1l9qa1.ent-d1kbva2.ent", "d1l9qa1.ent-d1kcw_2.ent", "d1l9qa1.ent-d1kcw_4.ent", "d1l9qa1.ent-d1kcw_6.ent", "d1l9qa1.ent-d1kv7a1.ent", "d1l9qa1.ent-d1kv7a3.ent", "d1l9qa1.ent-d1l9qa2.ent", "d1l9qa1.ent-d1m56b1.ent", "d1l9qa1.ent-d1qhqa_.ent", "d1l9qa1.ent-d2cbp__.ent", "d1l9qa1.ent-d2cuaa_.ent", "d1l9qa2.ent-d1cyx__.ent", "d1l9qa2.ent-d1e30a_.ent", "d1l9qa2.ent-d1gw0a1.ent", "d1l9qa2.ent-d1hfua2.ent", "d1l9qa2.ent-d1ikop_.ent", "d1l9qa2.ent-d1kbva1.ent", "d1l9qa2.ent-d1kbva2.ent", "d1l9qa2.ent-d1kcw_2.ent", "d1l9qa2.ent-d1kcw_4.ent", "d1l9qa2.ent-d1kcw_6.ent", "d1l9qa2.ent-d1kv7a1.ent", "d1l9qa2.ent-d1kv7a2.ent", "d1l9qa2.ent-d1kv7a3.ent", "d1l9qa2.ent-d1l9qa1.ent", "d1l9qa2.ent-d1m56b1.ent", "d1l9qa2.ent-d1qhqa_.ent", "d1l9qa2.ent-d2cbp__.ent", "d1l9qa2.ent-d2cuaa_.ent", "d1l9xa_.ent-d1b3ra2.ent", "d1l9xa_.ent-d1cex__.ent", "d1l9xa_.ent-d1cf9a1.ent", "d1l9xa_.ent-d1d4aa_.ent", "d1l9xa_.ent-d1e5da1.ent", "d1l9xa_.ent-d1es9a_.ent", "d1l9xa_.ent-d1euca2.ent", "d1l9xa_.ent-d1f2va_.ent", "d1l9xa_.ent-d1f4pa_.ent", "d1l9xa_.ent-d1f8ya_.ent", "d1l9xa_.ent-d1fjgb_.ent", "d1l9xa_.ent-d1flca2.ent", "d1l9xa_.ent-d1fuea_.ent", "d1l9xa_.ent-d1fyea_.ent", "d1l9xa_.ent-d1g66a_.ent", "d1l9xa_.ent-d1h05a_.ent", "d1l9xa_.ent-d1iexa2.ent", "d1l9xa_.ent-d1k7ca_.ent", "d1l9xa_.ent-d1kwga3.ent", "d1l9xa_.ent-d1l7da2.ent", "d1l9xa_.ent-d1qdlb_.ent", "d1l9xa_.ent-d1qo0d_.ent", "d1l9xa_.ent-d2naca2.ent", "d1l9xa_.ent-d7reqb2.ent", "d1la6a_.ent-d1cg5a_", "d1la6a_.ent-d1cg5a_.ent", "d1la6a_.ent-d1cg5b_", "d1la6a_.ent-d1cg5b_.ent", "d1la6a_.ent-d1ew6a_", "d1la6a_.ent-d1ew6a_.ent", "d1la6a_.ent-d1gcva_", "d1la6a_.ent-d1gcva_.ent", "d1la6a_.ent-d1irda_", "d1la6a_.ent-d1irda_.ent", "d1la6a_.ent-d1itha_", "d1la6a_.ent-d1itha_.ent", "d1lac__.ent-d1qjoa_.ent", "d1lam_2.ent-d1lfwa1.ent", "d1lam_2.ent-d1loka_.ent", "d1lam_2.ent-d1m4la_.ent", "d1lam_2.ent-d1obr__.ent", "d1lam_2.ent-d2pth__.ent", "d1lara1.ent-d1lara2.ent", "d1lara1.ent-d1lyva_.ent", "d1lara1.ent-d1mkp__.ent", "d1lara1.ent-d1vhra_.ent", "d1lara1.ent-d1yfoa_.ent", "d1lara1.ent-d2shpa1.ent", "d1lara2.ent-d1lyva_.ent", "d1lara2.ent-d1mkp__.ent", "d1lara2.ent-d1vhra_.ent", "d1lara2.ent-d1yfoa_.ent", "d1lara2.ent-d2shpa1.ent", "d1lata_.ent-d1lv3a_.ent", "d1lata_.ent-d1zfo__.ent", "d1lata_.ent-d2nllb_.ent", "d1lata_.ent-d3gata_.ent", "d1lata_.ent-d7gata_.ent", "d1laue_.ent-d1muga_.ent", "d1laue_.ent-d3euga_.ent", "d1lb2b_.ent-d1tfr_1.ent", "d1lbqa_.ent-d1qgoa_.ent", "d1lbu_1.ent-d1slm_1.ent", "d1lbva_.ent-d2hhma_.ent", "d1lc0a1.ent-d1cf2o1.ent", "d1lc0a1.ent-d1dssg1.ent", "d1lc0a2.ent-d1mb4a2.ent", "d1lc0a2.ent-d1qkia2.ent", "d1lc5a_.ent-d1qj5a_.ent", "d1lci__.ent-d1mdba_.ent", "d1lcya1.ent-d1m5za_.ent", "d1lcya1.ent-d1mfga_.ent", "d1lcya1.ent-d1qaua_.ent", "d1lcya1.ent-d1qava_.ent", "d1lcya1.ent-d1qlca_.ent", "d1lcya2.ent-d1lvmb_.ent", "d1lcya2.ent-d1lvoa_.ent", "d1lcya2.ent-d1mbma_.ent", "d1lcya2.ent-d1qq4a_.ent", "d1lcya2.ent-d1svpa_.ent", "d1lcya2.ent-d2hrva_.ent", "d1ld8a_.ent-d1e8xa1.ent", "d1ld8a_.ent-d1elka_.ent", "d1ld8a_.ent-d1h6ka1.ent", "d1ld8a_.ent-d1h6ka2.ent", "d1ld8a_.ent-d1h6ka3.ent", "d1ld8a_.ent-d1hf8a_.ent", "d1ld8a_.ent-d1hh8a_.ent", "d1ld8a_.ent-d1hs6a1.ent", "d1ld8a_.ent-d1ihga1.ent", "d1ld8a_.ent-d1keya_.ent", "d1ld8a_.ent-d1kpsb_.ent", "d1ld8a_.ent-d1l5ja1.ent", "d1ld8a_.ent-d1lrv__.ent", "d1ld8a_.ent-d1n4ka1.ent", "d1ld8a_.ent-d1pbv__.ent", "d1ld8a_.ent-d1qjba_.ent", "d1ld8a_.ent-d1qqea_.ent", "d1ld8b_.ent-d1lf6a1.ent", "d1ld8b_.ent-d1n1ba1.ent", "d1ld8b_.ent-d1n7oa1.ent", "d1ld8b_.ent-d1qaza_.ent", "d1ld8b_.ent-d2sqca1.ent", "d1ld8b_.ent-d2sqca2.ent", "d1ld8b_.ent-d5eau_1.ent", "d1ldg_2.ent-d1ldna2.ent", "d1ldg_2.ent-d1llda2.ent", "d1ldg_2.ent-d1o6za2.ent", "d1ldg_2.ent-d2cmd_2.ent", "d1ldg_2.ent-d5mdha2.ent", "d1ldg_2.ent-d7mdha2.ent", "d1ldja2.ent-d1e8xa1.ent", "d1ldja2.ent-d1elka_.ent", "d1ldja2.ent-d1h6ka1.ent", "d1ldja2.ent-d1h6ka2.ent", "d1ldja2.ent-d1h6ka3.ent", "d1ldja2.ent-d1hf8a_.ent", "d1ldja2.ent-d1hh8a_.ent", "d1ldja2.ent-d1hs6a1.ent", "d1ldja2.ent-d1ihga1.ent", "d1ldja2.ent-d1keya_.ent", "d1ldja2.ent-d1kpsb_.ent", "d1ldja2.ent-d1l5ja1.ent", "d1ldja2.ent-d1ld8a_.ent", "d1ldja2.ent-d1lrv__.ent", "d1ldja2.ent-d1lsha1.ent", "d1ldja2.ent-d1n4ka1.ent", "d1ldja2.ent-d1pbv__.ent", "d1ldja2.ent-d1qjba_.ent", "d1ldja2.ent-d1qqea_.ent", "d1ldjb_.ent-d1rmd_2.ent", "d1ldna2.ent-d1llda2.ent", "d1ldna2.ent-d1o6za2.ent", "d1ldna2.ent-d2cmd_2.ent", "d1ldna2.ent-d5mdha2.ent", "d1ldna2.ent-d7mdha2.ent", "d1ldtl_.ent-d1nuba3.ent", "d1ldtl_.ent-d1pce__.ent", "d1ldtl_.ent-d1sgpi_.ent", "d1ldtl_.ent-d1tbrr1.ent", "d1ldtl_.ent-d1tbrr2.ent", "d1ldtl_.ent-d1tgsi_.ent", "d1ldtl_.ent-d4sgbi_.ent", "d1le6a_.ent-d1mc2a_.ent", "d1le6a_.ent-d1poc__.ent", "d1leha2.ent-d1lu9a2.ent", "d1lf2a_.ent-d1mpp__.ent", "d1lf2a_.ent-d1nsoa_.ent", "d1lf2a_.ent-d2apr__.ent", "d1lf2a_.ent-d2rspa_.ent", "d1lf2a_.ent-d3psg__.ent", "d1lf2a_.ent-d4fiv__.ent", "d1lf6a1.ent-d1n1ba1.ent", "d1lf6a1.ent-d1n7oa1.ent", "d1lf6a1.ent-d1qaza_.ent", "d1lf6a1.ent-d2sqca1.ent", "d1lf6a1.ent-d2sqca2.ent", "d1lf6a2.ent-d1n7oa3.ent", "d1lf6a2.ent-d1nsza_.ent", "d1lf7a_.ent-d1o1va_.ent", "d1lf7a_.ent-d1qfta_.ent", "d1lf7a_.ent-d1qqsa_.ent", "d1lfda_.ent-d1fm0d_.ent", "d1lfda_.ent-d1h4ra3.ent", "d1lfda_.ent-d1h8ca_.ent", "d1lfda_.ent-d1ip9a_.ent", "d1lfda_.ent-d1k8rb_.ent", "d1lfda_.ent-d1lm8b_.ent", "d1lfda_.ent-d1m94a_.ent", "d1lfda_.ent-d1rlf__.ent", "d1lfka_.ent-d1n97a_.ent", "d1lfwa1.ent-d1loka_.ent", "d1lfwa1.ent-d1m4la_.ent", "d1lfwa1.ent-d1obr__.ent", "d1lfwa1.ent-d2pth__.ent", "d1lfwa2.ent-d1azsa_.ent", "d1lfwa2.ent-d1b3ta_.ent", "d1lfwa2.ent-d1dj0a2.ent", "d1lfwa2.ent-d1dqaa1.ent", "d1lfwa2.ent-d1ekra_.ent", "d1lfwa2.ent-d1eqoa_.ent", "d1lfwa2.ent-d1f3va_.ent", "d1lfwa2.ent-d1ftra1.ent", "d1lfwa2.ent-d1ftra2.ent", "d1lfwa2.ent-d1gpja3.ent", "d1lfwa2.ent-d1h72c2.ent", "d1lfwa2.ent-d1hbnb2.ent", "d1lfwa2.ent-d1hlwa_.ent", "d1lfwa2.ent-d1jnrb_.ent", "d1lfwa2.ent-d1kvka2.ent", "d1lfwa2.ent-d1qd1a1.ent", "d1lfwa2.ent-d1qd1a2.ent", "d1lfwa2.ent-d1regx_.ent", "d1lg2a2.ent-d1ll7a2.ent", "d1lg2a2.ent-d1m5ya2.ent", "d1lg2a2.ent-d1pina2.ent", "d1lg2a2.ent-d3eipa_.ent", "d1lgha_.ent-d1lghb_.ent", "d1lgha_.ent-d1nkzb_.ent", "d1lghb_.ent-d1nkzb_.ent", "d1lgpa_.ent-d1mjsa_.ent", "d1lgpa_.ent-d1ygs__.ent", "d1lh0a_.ent-d1nula_.ent", "d1lh0a_.ent-d1qb7a_.ent", "d1lh0a_.ent-d1tc1a_.ent", "d1lhpa_.ent-d1liia_.ent", "d1lhpa_.ent-d1o14a_.ent", "d1lhpa_.ent-d1rkd__.ent", "d1li1a1.ent-d1cwva5.ent", "d1li1a1.ent-d1f00i3.ent", "d1li1a1.ent-d1prea1.ent", "d1li1a1.ent-d1prtb2.ent", "d1li1a1.ent-d1qdda_.ent", "d1li1a1.ent-d1tsg__.ent", "d1li1a2.ent-d1cwva5.ent", "d1li1a2.ent-d1f00i3.ent", "d1li1a2.ent-d1li1a1.ent", "d1li1a2.ent-d1prtb2.ent", "d1li1a2.ent-d1tsg__.ent", "d1li5a2.ent-d1mjha_.ent", "d1li5a2.ent-d1n3la_.ent", "d1li5a2.ent-d1o97c_.ent", "d1li5a2.ent-d1o97d1.ent", "d1li5a2.ent-d1qjca_.ent", "d1li5a2.ent-d1sur__.ent", "d1liia_.ent-d1o14a_.ent", "d1liia_.ent-d1rkd__.ent", "d1lj5a_.ent-d1ovaa_.ent", "d1lj5a_.ent-d1qlpa_.ent", "d1lj9a_.ent-d1bjaa_.ent", "d1lj9a_.ent-d1bm9a_.ent", "d1lj9a_.ent-d1d5va_.ent", "d1lj9a_.ent-d1e17a_.ent", "d1lj9a_.ent-d1f1za1.ent", "d1lj9a_.ent-d1fc3a_.ent", "d1lj9a_.ent-d1fnna1.ent", "d1lj9a_.ent-d1fp1d1.ent", "d1lj9a_.ent-d1fp2a1.ent", "d1lj9a_.ent-d1fsha_.ent", "d1lj9a_.ent-d1fzpb_.ent", "d1lj9a_.ent-d1hks__.ent", "d1lj9a_.ent-d1hsja1.ent", "d1lj9a_.ent-d1ig6a_.ent", "d1lj9a_.ent-d1igna2.ent", "d1lj9a_.ent-d1jgsa_.ent", "d1lj9a_.ent-d1jhga_.ent", "d1lj9a_.ent-d1ka8a_.ent", "d1lj9a_.ent-d1ldja1.ent", "d1lj9a_.ent-d1md0a_.ent", "d1lj9a_.ent-d1o7fa1.ent", "d1lj9a_.ent-d1opc__.ent", "d1lj9a_.ent-d1repc1.ent", "d1lj9a_.ent-d1repc2.ent", "d1lj9a_.ent-d1smta_.ent", "d1lj9a_.ent-d2ezl__.ent", "d1lj9a_.ent-d2foka1.ent", "d1lj9a_.ent-d2foka2.ent", "d1lj9a_.ent-d2foka3.ent", "d1lj9a_.ent-d2irfg_.ent", "d1ljoa_.ent-d1mgqa_.ent", "d1ljoa_.ent-d1mxma1.ent", "d1ljoa_.ent-d1n9ra_.ent", "d1ljra1.ent-d1m0ua1.ent", "d1ljra1.ent-d1pd211.ent", "d1ljra1.ent-d1pmt_1.ent", "d1ljra1.ent-d2gsq_1.ent", "d1ljra1.ent-d2gsta1.ent", "d1lki__.ent-d1lqsl_.ent", "d1lki__.ent-d1m47a_.ent", "d1lki__.ent-d1n1fa_.ent", "d1lki__.ent-d2gmfa_.ent", "d1lki__.ent-d2ilk__.ent", "d1lkka_.ent-d1luia_.ent", "d1lkka_.ent-d1mil__.ent", "d1lkka_.ent-d1qada_.ent", "d1lkka_.ent-d2abl_2.ent", "d1lkka_.ent-d2cbla3.ent", "d1lkka_.ent-d2plda_.ent", "d1lkka_.ent-d2shpa3.ent", "d1lkoa1.ent-d1mtyb_.ent", "d1lkoa1.ent-d1mtyd_.ent", "d1lkoa1.ent-d1qgha_.ent", "d1lkoa1.ent-d1rcd__.ent", "d1lkoa2.ent-d1m2oa5.ent", "d1lkoa2.ent-d1ocrf_.ent", "d1lkoa2.ent-d1pft__.ent", "d1lkoa2.ent-d1rb9__.ent", "d1lkoa2.ent-d1tfi__.ent", "d1lkoa2.ent-d1yua_1.ent", "d1lkoa2.ent-d1yua_2.ent", "d1lkoa2.ent-d1zaka2.ent", "d1lkoa2.ent-d1zin_2.ent", "d1lkxa_.ent-d1bg2__.ent", "d1lkxa_.ent-d1br2a2.ent", "d1lkxa_.ent-d1c4oa1.ent", "d1lkxa_.ent-d1dj3a_.ent", "d1lkxa_.ent-d1e2ka_.ent", "d1lkxa_.ent-d1e9ra_.ent", "d1lkxa_.ent-d1eg7a_.ent", "d1lkxa_.ent-d1f9va_.ent", "d1lkxa_.ent-d1fmja_.ent", "d1lkxa_.ent-d1g41a_.ent", "d1lkxa_.ent-d1g8pa_.ent", "d1lkxa_.ent-d1i6ia_.ent", "d1lkxa_.ent-d1ii6a_.ent", "d1lkxa_.ent-d1iwea_.ent", "d1lkxa_.ent-d1ksfx3.ent", "d1lkxa_.ent-d1n0ua2.ent", "d1lkxa_.ent-d1pjr_1.ent", "d1lkxa_.ent-d1pjr_2.ent", "d1lkxa_.ent-d1qf5a_.ent", "d1lkxa_.ent-d1uaaa1.ent", "d1lkxa_.ent-d1uaaa2.ent", "d1lkxa_.ent-d2ncda_.ent", "d1ll2a_.ent-d1lzja_.ent", "d1ll2a_.ent-d1nf5b_.ent", "d1ll2a_.ent-d1qg8a_.ent", "d1ll7a2.ent-d1m5ya2.ent", "d1ll7a2.ent-d1pina2.ent", "d1ll7a2.ent-d3eipa_.ent", "d1ll8a_.ent-d1lswa_.ent", "d1ll8a_.ent-d1mc0a1.ent", "d1ll8a_.ent-d1mkma2.ent", "d1ll8a_.ent-d1mzua_.ent", "d1ll8a_.ent-d1pne__.ent", "d1ll8a_.ent-d3pyp__.ent", "d1lla_3.ent-d1bf2_1.ent", "d1lla_3.ent-d1dqia_.ent", "d1lla_3.ent-d1ea9c1.ent", "d1lla_3.ent-d1eaja_.ent", "d1lla_3.ent-d1edqa1.ent", "d1lla_3.ent-d1ej8a_.ent", "d1lla_3.ent-d1eut_1.ent", "d1lla_3.ent-d1g0da1.ent", "d1lla_3.ent-d1g4ma1.ent", "d1lla_3.ent-d1g4ma2.ent", "d1lla_3.ent-d1grwa_.ent", "d1lla_3.ent-d1i8aa_.ent", "d1lla_3.ent-d1j0ha1.ent", "d1lla_3.ent-d1ji1a1.ent", "d1lla_3.ent-d1ji2a1.ent", "d1lla_3.ent-d1jjua4.ent", "d1lla_3.ent-d1jmxa4.ent", "d1lla_3.ent-d1kgce2.ent", "d1lla_3.ent-d1kmta_.ent", "d1lla_3.ent-d1ktja_.ent", "d1lla_3.ent-d1kv3a1.ent", "d1lla_3.ent-d1kyfa1.ent", "d1lla_3.ent-d1l9na1.ent", "d1lla_3.ent-d1lmia_.ent", "d1lla_3.ent-d1m1xa1.ent", "d1lla_3.ent-d1m1xa2.ent", "d1lla_3.ent-d1m1xa3.ent", "d1lla_3.ent-d1m1xb1.ent", "d1lla_3.ent-d1m7xa1.ent", "d1lla_3.ent-d1my7a_.ent", "d1lla_3.ent-d1nepa_.ent", "d1lla_3.ent-d1o75a1.ent", "d1lla_3.ent-d1qba_1.ent", "d1lla_3.ent-d1qfha1.ent", "d1lla_3.ent-d1qfha2.ent", "d1lla_3.ent-d1soxa1.ent", "d1lla_3.ent-d1xsoa_.ent", "d1llda2.ent-d1o6za2.ent", "d1llda2.ent-d2cmd_2.ent", "d1llda2.ent-d5mdha2.ent", "d1llda2.ent-d7mdha2.ent", "d1llfa_.ent-d1ac5__.ent", "d1llfa_.ent-d1bu8a2.ent", "d1llfa_.ent-d1cpy__.ent", "d1llfa_.ent-d1cr6a2.ent", "d1llfa_.ent-d1cvl__.ent", "d1llfa_.ent-d1ea5a_.ent", "d1llfa_.ent-d1hlga_.ent", "d1llfa_.ent-d1ivya_.ent", "d1llfa_.ent-d1iz7a_.ent", "d1llfa_.ent-d1jjia_.ent", "d1llfa_.ent-d1jkma_.ent", "d1llfa_.ent-d1ju3a2.ent", "d1llfa_.ent-d1k4ya_.ent", "d1llfa_.ent-d1ku0a_.ent", "d1llfa_.ent-d1l7aa_.ent", "d1llfa_.ent-d1lnsa3.ent", "d1llfa_.ent-d1lzla_.ent", "d1llfa_.ent-d1qe3a_.ent", "d1llfa_.ent-d1qlwa_.ent", "d1llfa_.ent-d1qo7a_.ent", "d1llfa_.ent-d1qtra_.ent", "d1llfa_.ent-d1tca__.ent", "d1llfa_.ent-d2bce__.ent", "d1llp__.ent-d1mn2__.ent", "d1llp__.ent-d1pa2a_.ent", "d1llqa1.ent-d1bdb__.ent", "d1llqa1.ent-d1bgva1.ent", "d1llqa1.ent-d1e7wa_.ent", "d1llqa1.ent-d1eno__.ent", "d1llqa1.ent-d1eny__.ent", "d1llqa1.ent-d1fds__.ent", "d1llqa1.ent-d1g0oa_.ent", "d1llqa1.ent-d1gcoa_.ent", "d1llqa1.ent-d1h5qa_.ent", "d1llqa1.ent-d1hwxa1.ent", "d1llqa1.ent-d1ja9a_.ent", "d1llqa1.ent-d1n2sa_.ent", "d1llqa1.ent-d1n5da_.ent", "d1llqa1.ent-d1oaa__.ent", "d1llqa1.ent-d1qsga_.ent", "d1llqa1.ent-d2ae2a_.ent", "d1llwa1.ent-d1qcxa_.ent", "d1llwa1.ent-d1qq1a_.ent", "d1llwa2.ent-d1ccwb_.ent", "d1llwa2.ent-d1cz1a_.ent", "d1llwa2.ent-d1d3ga_.ent", "d1llwa2.ent-d1e4mm_.ent", "d1llwa2.ent-d1edg__.ent", "d1llwa2.ent-d1eexa_.ent", "d1llwa2.ent-d1eswa_.ent", "d1llwa2.ent-d1f8ma_.ent", "d1llwa2.ent-d1g5aa2.ent", "d1llwa2.ent-d1gjwa2.ent", "d1llwa2.ent-d1gqia1.ent", "d1llwa2.ent-d1gvoa_.ent", "d1llwa2.ent-d1gw1a_.ent", "d1llwa2.ent-d1iexa1.ent", "d1llwa2.ent-d1itua_.ent", "d1llwa2.ent-d1j5sa_.ent", "d1llwa2.ent-d1k4ga_.ent", "d1llwa2.ent-d1kbla1.ent", "d1llwa2.ent-d1kwga2.ent", "d1llwa2.ent-d1m7ja3.ent", "d1llwa2.ent-d1muwa_.ent", "d1llwa2.ent-d1ntha_.ent", "d1llwa2.ent-d1o94a1.ent", "d1llwa2.ent-d1oyb__.ent", "d1llwa2.ent-d2dora_.ent", "d1llwa2.ent-d7reqa1.ent", "d1llwa3.ent-d1ea0a3.ent", "d1llwa3.ent-d1ecfa2.ent", "d1llwa3.ent-d1gdoa_.ent", "d1llwa3.ent-d1gph12.ent", "d1llwa3.ent-d1iru1_.ent", "d1llwa3.ent-d1iru2_.ent", "d1llwa3.ent-d1iruk_.ent", "d1llwa3.ent-d1jgta2.ent", "d1llwa3.ent-d1pma1_.ent", "d1llwa3.ent-d1pmaa_.ent", "d1llwa3.ent-d1ryp1_.ent", "d1llwa3.ent-d1ryp2_.ent", "d1llwa3.ent-d1rypa_.ent", "d1llwa3.ent-d1rypb_.ent", "d1llwa3.ent-d1rypc_.ent", "d1llwa3.ent-d1rypd_.ent", "d1llwa3.ent-d1rype_.ent", "d1llwa3.ent-d1rypf_.ent", "d1llwa3.ent-d1rypg_.ent", "d1llwa3.ent-d1ryph_.ent", "d1llwa3.ent-d1rypi_.ent", "d1llwa3.ent-d1rypj_.ent", "d1llwa3.ent-d1rypk_.ent", "d1llwa3.ent-d1rypl_.ent", "d1lm5a_.ent-d1sw6a_.ent", "d1lm8b_.ent-d1ayfa_.ent", "d1lm8b_.ent-d1bmlc3.ent", "d1lm8b_.ent-d1c9fa_.ent", "d1lm8b_.ent-d1czpa_.ent", "d1lm8b_.ent-d1f52a1.ent", "d1lm8b_.ent-d1fm0d_.ent", "d1lm8b_.ent-d1h4ra3.ent", "d1lm8b_.ent-d1h8ca_.ent", "d1lm8b_.ent-d1i42a_.ent", "d1lm8b_.ent-d1ip9a_.ent", "d1lm8b_.ent-d1k8rb_.ent", "d1lm8b_.ent-d1l5pa_.ent", "d1lm8b_.ent-d1l7ya_.ent", "d1lm8b_.ent-d1lfda_.ent", "d1lm8b_.ent-d1m94a_.ent", "d1lm8b_.ent-d1qlab2.ent", "d1lm8b_.ent-d1rlf__.ent", "d1lm8b_.ent-d3tss_2.ent", "d1lm8c_.ent-d1t1da_.ent", "d1lm8c_.ent-d3kvt__.ent", "d1lm8v_.ent-d1qhoa2.ent", "d1lmb3_.ent-d1ner__.ent", "d1lmb3_.ent-d1r69__.ent", "d1lmb3_.ent-d1uxc__.ent", "d1lmb3_.ent-d1uxd__.ent", "d1lmb3_.ent-d1vpwa1.ent", "d1lmb3_.ent-d2cro__.ent", "d1lmia_.ent-d1dqia_.ent", "d1lmia_.ent-d1eaja_.ent", "d1lmia_.ent-d1grwa_.ent", "d1lmia_.ent-d1j0ha1.ent", "d1lmia_.ent-d1kgce2.ent", "d1lmia_.ent-d1nepa_.ent", "d1lmia_.ent-d1o75a1.ent", "d1lmia_.ent-d1soxa1.ent", "d1lml__.ent-d1qba_4.ent", "d1lml__.ent-d3btaa3.ent", "d1lmza_.ent-d1mpga1.ent", "d1lmza_.ent-d1mun__.ent", "d1lmza_.ent-d2abk__.ent", "d1ln1a_.ent-d1mpga2.ent", "d1ln1a_.ent-d1ytba1.ent", "d1ln1a_.ent-d3pmga4.ent", "d1lnsa2.ent-d1bhga2.ent", "d1lnsa2.ent-d1ciy_1.ent", "d1lnsa2.ent-d1cx1a_.ent", "d1lnsa2.ent-d1czsa_.ent", "d1lnsa2.ent-d1d7pm_.ent", "d1lnsa2.ent-d1dlc_1.ent", "d1lnsa2.ent-d1eut_2.ent", "d1lnsa2.ent-d1gmma_.ent", "d1lnsa2.ent-d1gnya_.ent", "d1lnsa2.ent-d1gqpa_.ent", "d1lnsa2.ent-d1gu3a_.ent", "d1lnsa2.ent-d1guia_.ent", "d1lnsa2.ent-d1h6ya_.ent", "d1lnsa2.ent-d1i5pa1.ent", "d1lnsa2.ent-d1jhja_.ent", "d1lnsa2.ent-d1ji6a1.ent", "d1lnsa2.ent-d1jz8a3.ent", "d1lnsa2.ent-d1k12a_.ent", "d1lnsa2.ent-d1k3ia2.ent", "d1lnsa2.ent-d1k42a_.ent", "d1lnsa2.ent-d1kexa_.ent", "d1lnsa2.ent-d1kgya_.ent", "d1lnsa2.ent-d1xnaa_.ent", "d1lnsa3.ent-d1bu8a2.ent", "d1lnsa3.ent-d1cr6a2.ent", "d1lnsa3.ent-d1cvl__.ent", "d1lnsa3.ent-d1hlga_.ent", "d1lnsa3.ent-d1iz7a_.ent", "d1lnsa3.ent-d1jjia_.ent", "d1lnsa3.ent-d1jkma_.ent", "d1lnsa3.ent-d1ju3a2.ent", "d1lnsa3.ent-d1ku0a_.ent", "d1lnsa3.ent-d1l7aa_.ent", "d1lnsa3.ent-d1lzla_.ent", "d1lnsa3.ent-d1qlwa_.ent", "d1lnsa3.ent-d1qo7a_.ent", "d1lnsa3.ent-d1qtra_.ent", "d1lnsa3.ent-d1tca__.ent", "d1lo7a_.ent-d1mkaa_.ent", "d1loka_.ent-d1m4la_.ent", "d1loka_.ent-d1obr__.ent", "d1loka_.ent-d2pth__.ent", "d1lopa_.ent-d2cpl__.ent", "d1lp3a_.ent-d1aym1_.ent", "d1lp3a_.ent-d1aym2_.ent", "d1lp3a_.ent-d1b35a_.ent", "d1lp3a_.ent-d1b35b_.ent", "d1lp3a_.ent-d1b35c_.ent", "d1lp3a_.ent-d1bev1_.ent", "d1lp3a_.ent-d1bev3_.ent", "d1lp3a_.ent-d1bmv2_.ent", "d1lp3a_.ent-d1d4m1_.ent", "d1lp3a_.ent-d1dnv__.ent", "d1lp3a_.ent-d1dzla_.ent", "d1lp3a_.ent-d1ihma_.ent", "d1lp3a_.ent-d1k5ma_.ent", "d1lp3a_.ent-d1novc_.ent", "d1lp3a_.ent-d1pov0_.ent", "d1lp3a_.ent-d1pvc1_.ent", "d1lp3a_.ent-d1sva1_.ent", "d1lp3a_.ent-d1tmf1_.ent", "d1lp3a_.ent-d1vpsa_.ent", "d1lp3a_.ent-d2bbva_.ent", "d1lp3a_.ent-d2bpa1_.ent", "d1lp3a_.ent-d2mev1_.ent", "d1lp3a_.ent-d2mev2_.ent", "d1lpba1.ent-d1lpba2.ent", "d1lpba2.ent-d1b9wa1.ent", "d1lpba2.ent-d1b9wa2.ent", "d1lpba2.ent-d1cixa_.ent", "d1lpba2.ent-d1g9pa_.ent", "d1lpba2.ent-d1h59b_.ent", "d1lpba2.ent-d1i2ua_.ent", "d1lpba2.ent-d1imt_2.ent", "d1lpla_.ent-d1bb9__.ent", "d1lpla_.ent-d1dj7b_.ent", "d1lpla_.ent-d1fx7a3.ent", "d1lpla_.ent-d1g3sa3.ent", "d1lpla_.ent-d1gcqc_.ent", "d1lpla_.ent-d1i07a_.ent", "d1lpla_.ent-d1jb0e_.ent", "d1lpla_.ent-d1jo8a_.ent", "d1lpla_.ent-d1khia1.ent", "d1lpla_.ent-d1kjwa1.ent", "d1lpla_.ent-d1m9sa2.ent", "d1lpla_.ent-d1m9sa3.ent", "d1lpla_.ent-d1pht__.ent", "d1lpla_.ent-d1vie__.ent", "d1lpla_.ent-d1ycsb2.ent", "d1lpua_.ent-d1a06__.ent", "d1lpua_.ent-d1b6cb_.ent", "d1lpua_.ent-d1blxa_.ent", "d1lpua_.ent-d1csn__.ent", "d1lpua_.ent-d1f3mc_.ent", "d1lpua_.ent-d1fgka_.ent", "d1lpua_.ent-d1fvra_.ent", "d1lpua_.ent-d1ia9a_.ent", "d1lpua_.ent-d1iepa_.ent", "d1lpua_.ent-d1jksa_.ent", "d1lpua_.ent-d1jpaa_.ent", "d1lpua_.ent-d1jvpp_.ent", "d1lpua_.ent-d1kwpa_.ent", "d1lpua_.ent-d1lufa_.ent", "d1lpua_.ent-d1m14a_.ent", "d1lpua_.ent-d1phk__.ent", "d1lpua_.ent-d1tkia_.ent", "d1lqpa_.ent-d1mpya1.ent", "d1lqpa_.ent-d1mpya2.ent", "d1lqpa_.ent-d1qipa_.ent", "d1lqpa_.ent-d1qtoa_.ent", "d1lqra_.ent-d1lupa_.ent", "d1lqra_.ent-d1nixa_.ent", "d1lqra_.ent-d1niya_.ent", "d1lqra_.ent-d1qk6a_.ent", "d1lqra_.ent-d1qk7a_.ent", "d1lqra_.ent-d1vtx__.ent", "d1lqsl_.ent-d1m47a_.ent", "d1lqsl_.ent-d1n1fa_.ent", "d1lqsl_.ent-d2gmfa_.ent", "d1lqsl_.ent-d2ilk__.ent", "d1lqsr1.ent-d1f6fb1.ent", "d1lqsr1.ent-d1fyhb1.ent", "d1lqsr2.ent-d1axib2.ent", "d1lqsr2.ent-d1bpv__.ent", "d1lqsr2.ent-d1cd9b1.ent", "d1lqsr2.ent-d1cd9b2.ent", "d1lqsr2.ent-d1cfb_1.ent", "d1lqsr2.ent-d1cfb_2.ent", "d1lqsr2.ent-d1eerb2.ent", "d1lqsr2.ent-d1egja_.ent", "d1lqsr2.ent-d1f6fb1.ent", "d1lqsr2.ent-d1f6fb2.ent", "d1lqsr2.ent-d1fyhb1.ent", "d1lqsr2.ent-d1fyhb2.ent", "d1lqsr2.ent-d1gh7a1.ent", "d1lqsr2.ent-d1i1ra1.ent", "d1lqsr2.ent-d1lqsr1.ent", "d1lqsr2.ent-d1n26a2.ent", "d1lqsr2.ent-d1n26a3.ent", "d1lqsr2.ent-d1qg3a2.ent", "d1lqsr2.ent-d2hft_1.ent", "d1lqsr2.ent-d2hft_2.ent", "d1lqta1.ent-d1m6ia1.ent", "d1lqta1.ent-d1m6ia2.ent", "d1lqta1.ent-d1nhp_1.ent", "d1lqta1.ent-d1nhp_2.ent", "d1lqta1.ent-d1o94a2.ent", "d1lqta1.ent-d3grs_1.ent", "d1lqta1.ent-d3grs_2.ent", "d1lqta2.ent-d1o94a3.ent", "d1lqva_.ent-d1zaga2.ent", "d1lqva_.ent-d3frua2.ent", "d1lrha_.ent-d1m4oa_.ent", "d1lrha_.ent-d1pmi__.ent", "d1lrha_.ent-d1wapa_.ent", "d1lrha_.ent-d2arca_.ent", "d1lrha_.ent-d2phla1.ent", "d1lrha_.ent-d2phla2.ent", "d1lrv__.ent-d1e8xa1.ent", "d1lrv__.ent-d1elka_.ent", "d1lrv__.ent-d1h6ka2.ent", "d1lrv__.ent-d1hh8a_.ent", "d1lrv__.ent-d1hs6a1.ent", "d1lrv__.ent-d1ihga1.ent", "d1lrv__.ent-d1keya_.ent", "d1lrv__.ent-d1kpsb_.ent", "d1lrv__.ent-d1l5ja1.ent", "d1lrv__.ent-d1n4ka1.ent", "d1lrv__.ent-d1pbv__.ent", "d1lrv__.ent-d1qjba_.ent", "d1lrza1.ent-d1seta1.ent", "d1lrza2.ent-d1lrza3.ent", "d1lrza2.ent-d1m4ia_.ent", "d1lrza2.ent-d1qsma_.ent", "d1lrza2.ent-d1qsta_.ent", "d1lrza3.ent-d1m4ia_.ent", "d1lrza3.ent-d1qsma_.ent", "d1lrza3.ent-d1qsta_.ent", "d1ls1a1.ent-d1nfn__.ent", "d1ls1a1.ent-d1nlxa_.ent", "d1ls1a1.ent-d256ba_.ent", "d1ls1a1.ent-d2a0b__.ent", "d1ls1a1.ent-d2liga_.ent", "d1ls1a1.ent-d2mhr__.ent", "d1ls1a1.ent-d3fapb_.ent", "d1lsha1.ent-d1e8xa1.ent", "d1lsha1.ent-d1elka_.ent", "d1lsha1.ent-d1h6ka1.ent", "d1lsha1.ent-d1h6ka2.ent", "d1lsha1.ent-d1h6ka3.ent", "d1lsha1.ent-d1hf8a_.ent", "d1lsha1.ent-d1hh8a_.ent", "d1lsha1.ent-d1hs6a1.ent", "d1lsha1.ent-d1ihga1.ent", "d1lsha1.ent-d1keya_.ent", "d1lsha1.ent-d1kpsb_.ent", "d1lsha1.ent-d1l5ja1.ent", "d1lsha1.ent-d1ld8a_.ent", "d1lsha1.ent-d1lrv__.ent", "d1lsha1.ent-d1n4ka1.ent", "d1lsha1.ent-d1pbv__.ent", "d1lsha1.ent-d1qjba_.ent", "d1lsha1.ent-d1qqea_.ent", "d1lst__.ent-d1m5ea_.ent", "d1lst__.ent-d1mrp__.ent", "d1lst__.ent-d1nh8a1.ent", "d1lst__.ent-d1pda_1.ent", "d1lst__.ent-d1pot__.ent", "d1lst__.ent-d1sbp__.ent", "d1lst__.ent-d1wdna_.ent", "d1lst__.ent-d3mbp__.ent", "d1lst__.ent-d3thia_.ent", "d1lswa_.ent-d1mzua_.ent", "d1lswa_.ent-d3pyp__.ent", "d1lu9a1.ent-d1bg6_2.ent", "d1lu9a1.ent-d1cf2o1.ent", "d1lu9a1.ent-d1dssg1.ent", "d1lu9a1.ent-d1e5qa1.ent", "d1lu9a1.ent-d1lc0a1.ent", "d1lu9a1.ent-d2naca1.ent", "d1lu9a1.ent-d2pgd_2.ent", "d1luca_.ent-d1lucb_.ent", "d1luca_.ent-d1m41a_.ent", "d1luca_.ent-d1nfp__.ent", "d1lucb_.ent-d1m41a_.ent", "d1lucb_.ent-d1nfp__.ent", "d1lufa_.ent-d1iepa_.ent", "d1lufa_.ent-d1jpaa_.ent", "d1luia_.ent-d1mil__.ent", "d1luia_.ent-d1qada_.ent", "d1luia_.ent-d2abl_2.ent", "d1luia_.ent-d2cbla3.ent", "d1luia_.ent-d2plda_.ent", "d1luia_.ent-d2shpa3.ent", "d1lupa_.ent-d1nixa_.ent", "d1lupa_.ent-d1niya_.ent", "d1lupa_.ent-d1qk6a_.ent", "d1lupa_.ent-d1qk7a_.ent", "d1lupa_.ent-d1vtx__.ent", "d1lv2a_.ent-d1mzna_.ent", "d1lv2a_.ent-d1n83a_.ent", "d1lv2a_.ent-d2prga_.ent", "d1lv3a_.ent-d1zfo__.ent", "d1lv3a_.ent-d2nllb_.ent", "d1lv3a_.ent-d3gata_.ent", "d1lv3a_.ent-d7gata_.ent", "d1lv7a_.ent-d1cr1a_.ent", "d1lv7a_.ent-d1g8ya_.ent", "d1lvk_2.ent-d1a7j__.ent", "d1lvk_2.ent-d1aqua_.ent", "d1lvk_2.ent-d1bg2__.ent", "d1lvk_2.ent-d1br2a2.ent", "d1lvk_2.ent-d1c4oa1.ent", "d1lvk_2.ent-d1cr1a_.ent", "d1lvk_2.ent-d1dj3a_.ent", "d1lvk_2.ent-d1e2ka_.ent", "d1lvk_2.ent-d1e69a_.ent", "d1lvk_2.ent-d1e79a3.ent", "d1lvk_2.ent-d1e9ra_.ent", "d1lvk_2.ent-d1eg7a_.ent", "d1lvk_2.ent-d1f5na2.ent", "d1lvk_2.ent-d1f9va_.ent", "d1lvk_2.ent-d1fmja_.ent", "d1lvk_2.ent-d1fnna2.ent", "d1lvk_2.ent-d1g41a_.ent", "d1lvk_2.ent-d1g8pa_.ent", "d1lvk_2.ent-d1g8ya_.ent", "d1lvk_2.ent-d1gm5a3.ent", "d1lvk_2.ent-d1i6ia_.ent", "d1lvk_2.ent-d1ihua1.ent", "d1lvk_2.ent-d1ii6a_.ent", "d1lvk_2.ent-d1iwea_.ent", "d1lvk_2.ent-d1jwyb_.ent", "d1lvk_2.ent-d1ksfx3.ent", "d1lvk_2.ent-d1lkxa_.ent", "d1lvk_2.ent-d1lv7a_.ent", "d1lvk_2.ent-d1m6na3.ent", "d1lvk_2.ent-d1n0ua2.ent", "d1lvk_2.ent-d1nsta_.ent", "d1lvk_2.ent-d1pjr_1.ent", "d1lvk_2.ent-d1pjr_2.ent", "d1lvk_2.ent-d1qf5a_.ent", "d1lvk_2.ent-d1uaaa1.ent", "d1lvk_2.ent-d1uaaa2.ent", "d1lvk_2.ent-d2ncda_.ent", "d1lvl_3.ent-d1m6ia3.ent", "d1lvl_3.ent-d1mo9a3.ent", "d1lvl_3.ent-d1nhp_3.ent", "d1lvl_3.ent-d1ojt_3.ent", "d1lvl_3.ent-d3grs_3.ent", "d1lvl_3.ent-d3lada3.ent", "d1lvmb_.ent-d1lvoa_.ent", "d1lvmb_.ent-d1mbma_.ent", "d1lvmb_.ent-d1qq4a_.ent", "d1lvmb_.ent-d1svpa_.ent", "d1lvmb_.ent-d2hrva_.ent", "d1lvoa_.ent-d1a0la_.ent", "d1lvoa_.ent-d1agja_.ent", "d1lvoa_.ent-d1arb__.ent", "d1lvoa_.ent-d1azza_.ent", "d1lvoa_.ent-d1bio__.ent", "d1lvoa_.ent-d1bqya_.ent", "d1lvoa_.ent-d1cgha_.ent", "d1lvoa_.ent-d1ddja_.ent", "d1lvoa_.ent-d1dlea_.ent", "d1lvoa_.ent-d1eaxa_.ent", "d1lvoa_.ent-d1ekbb_.ent", "d1lvoa_.ent-d1elva1.ent", "d1lvoa_.ent-d1fjsa_.ent", "d1lvoa_.ent-d1gdna_.ent", "d1lvoa_.ent-d1gpza1.ent", "d1lvoa_.ent-d1gvkb_.ent", "d1lvoa_.ent-d1gvza_.ent", "d1lvoa_.ent-d1hj9a_.ent", "d1lvoa_.ent-d1klih_.ent", "d1lvoa_.ent-d1m9ua_.ent", "d1lvoa_.ent-d1mbma_.ent", "d1lvoa_.ent-d1mzaa_.ent", "d1lvoa_.ent-d1qq4a_.ent", "d1lvoa_.ent-d1qtfa_.ent", "d1lvoa_.ent-d1rfna_.ent", "d1lvoa_.ent-d1svpa_.ent", "d1lvoa_.ent-d2hlca_.ent", "d1lvoa_.ent-d2hrva_.ent", "d1lwda_.ent-d1xaa__.ent", "d1lwha1.ent-d1m7xa2.ent", "d1lwha1.ent-d1qhoa3.ent", "d1lwha1.ent-d1uok_1.ent", "d1lwha1.ent-d7taa_1.ent", "d1lwha2.ent-d1iexa1.ent", "d1lwha2.ent-d1j0ha3.ent", "d1lwha2.ent-d7taa_2.ent", "d1lwma_.ent-d1qrva_.ent", "d1lwma_.ent-d2lefa_.ent", "d1lxa__.ent-d1qrea_.ent", "d1lxa__.ent-d1xat__.ent", "d1lxa__.ent-d3tdt__.ent", "d1ly2a1.ent-d1ly2a2.ent", "d1ly2a1.ent-d1quba1.ent", "d1ly2a1.ent-d1quba2.ent", "d1ly2a1.ent-d1quba3.ent", "d1ly2a1.ent-d1quba4.ent", "d1ly2a1.ent-d1quba5.ent", "d1ly2a2.ent-d1quba1.ent", "d1ly2a2.ent-d1quba2.ent", "d1ly2a2.ent-d1quba3.ent", "d1ly2a2.ent-d1quba4.ent", "d1ly2a2.ent-d1quba5.ent", "d1lyva_.ent-d1mkp__.ent", "d1lyva_.ent-d1vhra_.ent", "d1lyva_.ent-d1yfoa_.ent", "d1lyva_.ent-d2shpa1.ent", "d1lyxa_.ent-d1n55a_.ent", "d1lyxa_.ent-d1trea_.ent", "d1lzja_.ent-d1nf5b_.ent", "d1lzja_.ent-d1qg8a_.ent", "d1lzla_.ent-d1cvl__.ent", "d1lzla_.ent-d1iz7a_.ent", "d1lzla_.ent-d1jjia_.ent", "d1lzla_.ent-d1mnaa_.ent", "d1lzla_.ent-d1n1ma2.ent", "d1lzla_.ent-d1qj4a_.ent", "d1lzla_.ent-d1qlwa_.ent", "d1lzla_.ent-d1qo7a_.ent", "d1lzla_.ent-d1qtra_.ent", "d1lzla_.ent-d1tca__.ent", "d1lzla_.ent-d1thta_.ent", "d1lzla_.ent-d3tgl__.ent", "d1m0da_.ent-d1vsra_.ent", "d1m0da_.ent-d2foka4.ent", "d1m0da_.ent-d3pvia_.ent", "d1m0ua1.ent-d1pd211.ent", "d1m0ua1.ent-d1pmt_1.ent", "d1m0ua1.ent-d2gsq_1.ent", "d1m0ua1.ent-d2gsta1.ent", "d1m0wa1.ent-d2hgsa1.ent", "d1m0wa2.ent-d2hgsa4.ent", "d1m0za_.ent-d1m6ba1.ent", "d1m0za_.ent-d1m6ba2.ent", "d1m0za_.ent-d1n8yc1.ent", "d1m0za_.ent-d1n8yc2.ent", "d1m14a_.ent-d1a06__.ent", "d1m14a_.ent-d1blxa_.ent", "d1m14a_.ent-d1csn__.ent", "d1m14a_.ent-d1f3mc_.ent", "d1m14a_.ent-d1fgka_.ent", "d1m14a_.ent-d1fvra_.ent", "d1m14a_.ent-d1ia9a_.ent", "d1m14a_.ent-d1iepa_.ent", "d1m14a_.ent-d1jksa_.ent", "d1m14a_.ent-d1jpaa_.ent", "d1m14a_.ent-d1jvpp_.ent", "d1m14a_.ent-d1lufa_.ent", "d1m14a_.ent-d1phk__.ent", "d1m15a2.ent-d1qh4a2.ent", "d1m1fa_.ent-d1bb9__.ent", "d1m1fa_.ent-d1dj7b_.ent", "d1m1fa_.ent-d1fx7a3.ent", "d1m1fa_.ent-d1g3sa3.ent", "d1m1fa_.ent-d1gcqc_.ent", "d1m1fa_.ent-d1i07a_.ent", "d1m1fa_.ent-d1i1ja_.ent", "d1m1fa_.ent-d1ixda_.ent", "d1m1fa_.ent-d1jb0e_.ent", "d1m1fa_.ent-d1jj2p_.ent", "d1m1fa_.ent-d1jo8a_.ent", "d1m1fa_.ent-d1khia1.ent", "d1m1fa_.ent-d1kjwa1.ent", "d1m1fa_.ent-d1lpla_.ent", "d1m1fa_.ent-d1m9sa2.ent", "d1m1fa_.ent-d1m9sa3.ent", "d1m1fa_.ent-d1ne8a_.ent", "d1m1fa_.ent-d1pht__.ent", "d1m1fa_.ent-d1vie__.ent", "d1m1fa_.ent-d1ycsb2.ent", "d1m1fa_.ent-d3vub__.ent", "d1m1ga2.ent-d2eifa1.ent", "d1m1na_.ent-d1m1nb_.ent", "d1m1na_.ent-d1mioa_.ent", "d1m1na_.ent-d1miob_.ent", "d1m1na_.ent-d1n2za_.ent", "d1m1na_.ent-d1psza_.ent", "d1m1na_.ent-d1qgoa_.ent", "d1m1na_.ent-d1toaa_.ent", "d1m1nb_.ent-d1mioa_.ent", "d1m1nb_.ent-d1miob_.ent", "d1m1nb_.ent-d1n2za_.ent", "d1m1nb_.ent-d1psza_.ent", "d1m1nb_.ent-d1qgoa_.ent", "d1m1nb_.ent-d1toaa_.ent", "d1m1qa_.ent-d1qo8a1.ent", "d1m1qa_.ent-d1wad__.ent", "d1m1qa_.ent-d2ctha_.ent", "d1m1qa_.ent-d2cy3__.ent", "d1m1qa_.ent-d3caoa_.ent", "d1m1qa_.ent-d3cyr__.ent", "d1m1xa1.ent-d1dqia_.ent", "d1m1xa1.ent-d1eaja_.ent", "d1m1xa1.ent-d1ej8a_.ent", "d1m1xa1.ent-d1grwa_.ent", "d1m1xa1.ent-d1j0ha1.ent", "d1m1xa1.ent-d1jmxa4.ent", "d1m1xa1.ent-d1kgce2.ent", "d1m1xa1.ent-d1kmta_.ent", "d1m1xa1.ent-d1kyfa1.ent", "d1m1xa1.ent-d1l9na1.ent", "d1m1xa1.ent-d1lmia_.ent", "d1m1xa1.ent-d1m1xa2.ent", "d1m1xa1.ent-d1m1xa3.ent", "d1m1xa1.ent-d1m1xb1.ent", "d1m1xa1.ent-d1nepa_.ent", "d1m1xa1.ent-d1o75a1.ent", "d1m1xa1.ent-d1soxa1.ent", "d1m1xa1.ent-d1xsoa_.ent", "d1m1xa2.ent-d1dqia_.ent", "d1m1xa2.ent-d1eaja_.ent", "d1m1xa2.ent-d1grwa_.ent", "d1m1xa2.ent-d1j0ha1.ent", "d1m1xa2.ent-d1jmxa4.ent", "d1m1xa2.ent-d1kgce2.ent", "d1m1xa2.ent-d1kmta_.ent", "d1m1xa2.ent-d1kyfa1.ent", "d1m1xa2.ent-d1lmia_.ent", "d1m1xa2.ent-d1m1xa3.ent", "d1m1xa2.ent-d1m1xb1.ent", "d1m1xa2.ent-d1nepa_.ent", "d1m1xa2.ent-d1o75a1.ent", "d1m1xa2.ent-d1soxa1.ent", "d1m1xa3.ent-d1bf2_1.ent", "d1m1xa3.ent-d1dqia_.ent", "d1m1xa3.ent-d1eaja_.ent", "d1m1xa3.ent-d1ej8a_.ent", "d1m1xa3.ent-d1g4ma1.ent", "d1m1xa3.ent-d1g4ma2.ent", "d1m1xa3.ent-d1grwa_.ent", "d1m1xa3.ent-d1i8aa_.ent", "d1m1xa3.ent-d1j0ha1.ent", "d1m1xa3.ent-d1jmxa4.ent", "d1m1xa3.ent-d1kgce2.ent", "d1m1xa3.ent-d1kmta_.ent", "d1m1xa3.ent-d1kyfa1.ent", "d1m1xa3.ent-d1l9na1.ent", "d1m1xa3.ent-d1lmia_.ent", "d1m1xa3.ent-d1m1xa1.ent", "d1m1xa3.ent-d1m1xa2.ent", "d1m1xa3.ent-d1m1xb1.ent", "d1m1xa3.ent-d1nepa_.ent", "d1m1xa3.ent-d1o75a1.ent", "d1m1xa3.ent-d1soxa1.ent", "d1m1xa3.ent-d1xsoa_.ent", "d1m1xa4.ent-d2bbkh_.ent", "d1m1xb1.ent-d1dqia_.ent", "d1m1xb1.ent-d1eaja_.ent", "d1m1xb1.ent-d1grwa_.ent", "d1m1xb1.ent-d1j0ha1.ent", "d1m1xb1.ent-d1jmxa4.ent", "d1m1xb1.ent-d1kgce2.ent", "d1m1xb1.ent-d1lmia_.ent", "d1m1xb1.ent-d1nepa_.ent", "d1m1xb1.ent-d1o75a1.ent", "d1m1xb1.ent-d1soxa1.ent", "d1m1xb2.ent-d1m2oa3.ent", "d1m1xb2.ent-d1m2vb3.ent", "d1m1xb2.ent-d1mjna_.ent", "d1m1xb2.ent-d1n3ya_.ent", "d1m1xb2.ent-d1qc5a_.ent", "d1m1xb5.ent-d1cvua2.ent", "d1m1xb5.ent-d1hz8a1.ent", "d1m1xb5.ent-d1hz8a2.ent", "d1m1xb5.ent-d1jl9a_.ent", "d1m1xb5.ent-d1l3ya_.ent", "d1m1xb5.ent-d1tpg_1.ent", "d1m22a_.ent-d1mt5a_.ent", "d1m2da_.ent-d1aba__.ent", "d1m2da_.ent-d1aqwa2.ent", "d1m2da_.ent-d1e6ba2.ent", "d1m2da_.ent-d1fhe_2.ent", "d1m2da_.ent-d1hyua4.ent", "d1m2da_.ent-d1iloa_.ent", "d1m2da_.ent-d1k0ma2.ent", "d1m2da_.ent-d1k3ya2.ent", "d1m2da_.ent-d1qmha1.ent", "d1m2fa_.ent-d1mb3a_.ent", "d1m2fa_.ent-d1mvoa_.ent", "d1m2fa_.ent-d1nat__.ent", "d1m2fa_.ent-d1ntr__.ent", "d1m2fa_.ent-d1qo0d_.ent", "d1m2fa_.ent-d1tmy__.ent", "d1m2oa1.ent-d1m2vb1.ent", "d1m2oa2.ent-d1m2vb2.ent", "d1m2oa2.ent-d1mnna_.ent", "d1m2oa2.ent-d1nbca_.ent", "d1m2oa2.ent-d1pdkb_.ent", "d1m2oa2.ent-d1qba_2.ent", "d1m2oa2.ent-d1tf4a2.ent", "d1m2oa2.ent-d1ycsa_.ent", "d1m2oa3.ent-d1m2vb3.ent", "d1m2oa3.ent-d1mjna_.ent", "d1m2oa3.ent-d1n3ya_.ent", "d1m2oa3.ent-d1qc5a_.ent", "d1m2oa4.ent-d1m2vb4.ent", "d1m2oa4.ent-d1m4ja_.ent", "d1m2oa5.ent-d1ocrf_.ent", "d1m2oa5.ent-d1pft__.ent", "d1m2oa5.ent-d1rb9__.ent", "d1m2oa5.ent-d1tfi__.ent", "d1m2oa5.ent-d1yua_1.ent", "d1m2oa5.ent-d1yua_2.ent", "d1m2oa5.ent-d1zaka2.ent", "d1m2oa5.ent-d1zin_2.ent", "d1m2vb2.ent-d1mnna_.ent", "d1m2vb2.ent-d1nbca_.ent", "d1m2vb2.ent-d1pdkb_.ent", "d1m2vb2.ent-d1qba_2.ent", "d1m2vb2.ent-d1tf4a2.ent", "d1m2vb2.ent-d1ycsa_.ent", "d1m2vb3.ent-d1mjna_.ent", "d1m2vb3.ent-d1n3ya_.ent", "d1m2vb3.ent-d1qc5a_.ent", "d1m2vb4.ent-d1m4ja_.ent", "d1m3ka1.ent-d1m3ka2.ent", "d1m3ka1.ent-d1mzja1.ent", "d1m3ka1.ent-d1mzja2.ent", "d1m3ka2.ent-d1mzja1.ent", "d1m3ka2.ent-d1mzja2.ent", "d1m3sa_.ent-d1moq__.ent", "d1m3ya1.ent-d1m3ya2.ent", "d1m3ya1.ent-d1pgs_1.ent", "d1m3ya1.ent-d1pgs_2.ent", "d1m3ya1.ent-d1phm_1.ent", "d1m3ya1.ent-d1phm_2.ent", "d1m3ya1.ent-d1ruxa1.ent", "d1m3ya1.ent-d1ruxa2.ent", "d1m3ya2.ent-d1pgs_1.ent", "d1m3ya2.ent-d1pgs_2.ent", "d1m3ya2.ent-d1phm_1.ent", "d1m3ya2.ent-d1phm_2.ent", "d1m3ya2.ent-d1ruxa1.ent", "d1m3ya2.ent-d1ruxa2.ent", "d1m40a_.ent-d1mfoa_.ent", "d1m40a_.ent-d1mwxa3.ent", "d1m40a_.ent-d1nj4a2.ent", "d1m40a_.ent-d1qmea4.ent", "d1m40a_.ent-d4blma_.ent", "d1m41a_.ent-d1nfp__.ent", "d1m45a_.ent-d1eg3a1.ent", "d1m45a_.ent-d1ggwa_.ent", "d1m45a_.ent-d1jfja_.ent", "d1m45a_.ent-d1m31a_.ent", "d1m45a_.ent-d1psra_.ent", "d1m45a_.ent-d1qasa1.ent", "d1m45a_.ent-d1rec__.ent", "d1m45a_.ent-d1rro__.ent", "d1m45a_.ent-d1sra__.ent", "d1m45a_.ent-d1wdcb_.ent", "d1m45a_.ent-d2cbla1.ent", "d1m45a_.ent-d2pvba_.ent", "d1m45a_.ent-d2sas__.ent", "d1m45a_.ent-d2scpa_.ent", "d1m45a_.ent-d5pal__.ent", "d1m47a_.ent-d1n1fa_.ent", "d1m47a_.ent-d2gmfa_.ent", "d1m47a_.ent-d2ilk__.ent", "d1m4ia_.ent-d1qsma_.ent", "d1m4ia_.ent-d1qsta_.ent", "d1m4la_.ent-d1obr__.ent", "d1m4la_.ent-d2pth__.ent", "d1m4oa_.ent-d1pmi__.ent", "d1m4oa_.ent-d1wapa_.ent", "d1m4oa_.ent-d2arca_.ent", "d1m4oa_.ent-d2phla1.ent", "d1m4oa_.ent-d2phla2.ent", "d1m4ua_.ent-d1m4ul_.ent", "d1m4ua_.ent-d1pdga_.ent", "d1m4ua_.ent-d2tgi__.ent", "d1m4ul_.ent-d1pdga_.ent", "d1m4ul_.ent-d2tgi__.ent", "d1m4va1.ent-d1prtb1.ent", "d1m4va1.ent-d1prtd_.ent", "d1m4va1.ent-d1prtf_.ent", "d1m4va1.ent-d1tiid_.ent", "d1m4va1.ent-d3chbd_.ent", "d1m4va1.ent-d3seb_1.ent", "d1m4va1.ent-d3tss_1.ent", "d1m4va2.ent-d3seb_2.ent", "d1m4va2.ent-d3tss_2.ent", "d1m4za_.ent-d1bb9__.ent", "d1m4za_.ent-d1dj7b_.ent", "d1m4za_.ent-d1fx7a3.ent", "d1m4za_.ent-d1g3sa3.ent", "d1m4za_.ent-d1gcqc_.ent", "d1m4za_.ent-d1hyoa1.ent", "d1m4za_.ent-d1i07a_.ent", "d1m4za_.ent-d1i1ja_.ent", "d1m4za_.ent-d1ixda_.ent", "d1m4za_.ent-d1jb0e_.ent", "d1m4za_.ent-d1jj2p_.ent", "d1m4za_.ent-d1jj2s_.ent", "d1m4za_.ent-d1jo8a_.ent", "d1m4za_.ent-d1khia1.ent", "d1m4za_.ent-d1kjwa1.ent", "d1m4za_.ent-d1lpla_.ent", "d1m4za_.ent-d1m1fa_.ent", "d1m4za_.ent-d1m9sa2.ent", "d1m4za_.ent-d1m9sa3.ent", "d1m4za_.ent-d1pht__.ent", "d1m4za_.ent-d1vie__.ent", "d1m4za_.ent-d1ycsb2.ent", "d1m4za_.ent-d3vub__.ent", "d1m55a_.ent-d1tbd__.ent", "d1m56b1.ent-d1cyx__.ent", "d1m56b1.ent-d1e30a_.ent", "d1m56b1.ent-d1ikop_.ent", "d1m56b1.ent-d1kbva1.ent", "d1m56b1.ent-d1kbva2.ent", "d1m56b1.ent-d1kcw_2.ent", "d1m56b1.ent-d1kcw_4.ent", "d1m56b1.ent-d1kcw_6.ent", "d1m56b1.ent-d1kv7a1.ent", "d1m56b1.ent-d1kv7a3.ent", "d1m56b1.ent-d1qhqa_.ent", "d1m56b2.ent-d1ocrb2.ent", "d1m56c_.ent-d1ocrc_.ent", "d1m56d_.ent-d1ocrd_.ent", "d1m56d_.ent-d1ocrg_.ent", "d1m56d_.ent-d1ocri_.ent", "d1m56d_.ent-d1ocrj_.ent", "d1m56d_.ent-d1ocrk_.ent", "d1m56d_.ent-d1ocrl_.ent", "d1m56d_.ent-d1ocrm_.ent", "d1m5ea_.ent-d1mrp__.ent", "d1m5ea_.ent-d1nh8a1.ent", "d1m5ea_.ent-d1pda_1.ent", "d1m5ea_.ent-d1pot__.ent", "d1m5ea_.ent-d1sbp__.ent", "d1m5ea_.ent-d1wdna_.ent", "d1m5ea_.ent-d3mbp__.ent", "d1m5ea_.ent-d3thia_.ent", "d1m5ya2.ent-d1m5ya3.ent", "d1m5ya2.ent-d1n1aa_.ent", "d1m5ya2.ent-d1pbk__.ent", "d1m5ya2.ent-d1pina2.ent", "d1m5ya2.ent-d3eipa_.ent", "d1m5ya3.ent-d1n1aa_.ent", "d1m5ya3.ent-d1pbk__.ent", "d1m5ya3.ent-d1pina2.ent", "d1m5za_.ent-d1mfga_.ent", "d1m5za_.ent-d1qaua_.ent", "d1m5za_.ent-d1qava_.ent", "d1m5za_.ent-d1qlca_.ent", "d1m66a1.ent-d1pgja1.ent", "d1m66a1.ent-d1qmga1.ent", "d1m66a1.ent-d2pgd_1.ent", "d1m6ba1.ent-d1m6ba2.ent", "d1m6ba1.ent-d1n8yc1.ent", "d1m6ba1.ent-d1n8yc2.ent", "d1m6ba2.ent-d1n8yc1.ent", "d1m6ba2.ent-d1n8yc2.ent", "d1m6ba3.ent-d1m6ba4.ent", "d1m6ba3.ent-d1n8yc3.ent", "d1m6ba3.ent-d1n8yc4.ent", "d1m6ba4.ent-d1n8yc3.ent", "d1m6ba4.ent-d1n8yc4.ent", "d1m6ia1.ent-d1m6ia2.ent", "d1m6ia1.ent-d1nhp_1.ent", "d1m6ia1.ent-d1nhp_2.ent", "d1m6ia1.ent-d1o94a2.ent", "d1m6ia1.ent-d3grs_1.ent", "d1m6ia1.ent-d3grs_2.ent", "d1m6ia2.ent-d1nhp_1.ent", "d1m6ia2.ent-d1nhp_2.ent", "d1m6ia2.ent-d1o94a2.ent", "d1m6ia2.ent-d3grs_1.ent", "d1m6ia2.ent-d3grs_2.ent", "d1m6ia3.ent-d1mo9a3.ent", "d1m6ia3.ent-d1n62c1.ent", "d1m6ia3.ent-d1nhp_3.ent", "d1m6ia3.ent-d1ojt_3.ent", "d1m6ia3.ent-d3grs_3.ent", "d1m6ia3.ent-d3lada3.ent", "d1m6na3.ent-d1cr1a_.ent", "d1m6na3.ent-d1e69a_.ent", "d1m6na3.ent-d1f5na2.ent", "d1m6na3.ent-d1g8ya_.ent", "d1m6na3.ent-d1gm5a3.ent", "d1m6na3.ent-d1lv7a_.ent", "d1m7ja1.ent-d1m7ja2.ent", "d1m7ja1.ent-d4ubpc1.ent", "d1m7ja2.ent-d4ubpc1.ent", "d1m7ka_.ent-d1qlaa1.ent", "d1m7ka_.ent-d1quua1.ent", "d1m7ka_.ent-d1quua2.ent", "d1m7ka_.ent-d2spca_.ent", "d1m7xa1.ent-d1edqa1.ent", "d1m7xa1.ent-d1eut_1.ent", "d1m7xa1.ent-d1kv3a1.ent", "d1m7xa1.ent-d1my7a_.ent", "d1m7xa1.ent-d1qba_1.ent", "d1m7xa1.ent-d1qfha1.ent", "d1m7xa1.ent-d1qfha2.ent", "d1m7xa2.ent-d1qhoa3.ent", "d1m7xa2.ent-d1uok_1.ent", "d1m7xa2.ent-d7taa_1.ent", "d1m7ya_.ent-d1ajsa_.ent", "d1m7ya_.ent-d1b9ha_.ent", "d1m7ya_.ent-d1bs0a_.ent", "d1m7ya_.ent-d1c7na_.ent", "d1m7ya_.ent-d1e5ea_.ent", "d1m7ya_.ent-d1gdea_.ent", "d1m7ya_.ent-d1j32a_.ent", "d1m7ya_.ent-d1jf9a_.ent", "d1m7ya_.ent-d1kl1a_.ent", "d1m7ya_.ent-d1n8pa_.ent", "d1m7ya_.ent-d1qisa_.ent", "d1m7ya_.ent-d1yaaa_.ent", "d1m7ya_.ent-d2ay1a_.ent", "d1m7ya_.ent-d2oata_.ent", "d1m7ya_.ent-d3tata_.ent", "d1m7ya_.ent-d7aata_.ent", "d1m8aa_.ent-d1qg7a_.ent", "d1m8aa_.ent-d1tvxa_.ent", "d1m8aa_.ent-d2hcc__.ent", "d1m8aa_.ent-d3il8__.ent", "d1m94a_.ent-d1rlf__.ent", "d1m98a2.ent-d1mwxa1.ent", "d1m98a2.ent-d1o7nb_.ent", "d1m98a2.ent-d1qjga_.ent", "d1m98a2.ent-d3stda_.ent", "d1m9sa2.ent-d1dj7b_.ent", "d1m9sa2.ent-d1gcqc_.ent", "d1m9sa2.ent-d1i07a_.ent", "d1m9sa2.ent-d1jb0e_.ent", "d1m9sa2.ent-d1jo8a_.ent", "d1m9sa2.ent-d1m9sa3.ent", "d1m9sa2.ent-d1m9sa4.ent", "d1m9sa2.ent-d1vie__.ent", "d1m9sa2.ent-d1ycsb2.ent", "d1m9sa3.ent-d1bb9__.ent", "d1m9sa3.ent-d1dj7b_.ent", "d1m9sa3.ent-d1g3sa3.ent", "d1m9sa3.ent-d1gcqc_.ent", "d1m9sa3.ent-d1i07a_.ent", "d1m9sa3.ent-d1jb0e_.ent", "d1m9sa3.ent-d1jo8a_.ent", "d1m9sa3.ent-d1khia1.ent", "d1m9sa3.ent-d1m9sa2.ent", "d1m9sa3.ent-d1m9sa4.ent", "d1m9sa3.ent-d1pht__.ent", "d1m9sa3.ent-d1vie__.ent", "d1m9sa3.ent-d1ycsb2.ent", "d1m9ua_.ent-d1azza_.ent", "d1m9ua_.ent-d1bio__.ent", "d1m9ua_.ent-d1bqya_.ent", "d1m9ua_.ent-d1cgha_.ent", "d1m9ua_.ent-d1ekbb_.ent", "d1m9ua_.ent-d1elva1.ent", "d1m9ua_.ent-d1fjsa_.ent", "d1m9ua_.ent-d1gdna_.ent", "d1m9ua_.ent-d1gpza1.ent", "d1m9ua_.ent-d1gvkb_.ent", "d1m9ua_.ent-d1gvza_.ent", "d1m9ua_.ent-d1hj9a_.ent", "d1m9ua_.ent-d1mzaa_.ent", "d1m9ua_.ent-d1rfna_.ent", "d1m9ua_.ent-d2hlca_.ent", "d1m9za_.ent-d1tfs__.ent", "d1m9za_.ent-d1tgxa_.ent", "d1m9za_.ent-d3ebx__.ent", "d1ma1a2.ent-d1qnna2.ent", "d1ma3a_.ent-d1o97d2.ent", "d1ma3a_.ent-d1poxa1.ent", "d1ma3a_.ent-d1pvda1.ent", "d1ma3a_.ent-d1zpda1.ent", "d1mai__.ent-d1mixa2.ent", "d1mai__.ent-d1mkea1.ent", "d1mai__.ent-d1pls__.ent", "d1mai__.ent-d1qqga1.ent", "d1mai__.ent-d1qqga2.ent", "d1mai__.ent-d1shca_.ent", "d1mb3a_.ent-d1mvoa_.ent", "d1mb3a_.ent-d1nat__.ent", "d1mb3a_.ent-d1ntr__.ent", "d1mb3a_.ent-d1qo0d_.ent", "d1mb3a_.ent-d1tmy__.ent", "d1mb4a2.ent-d1qkia2.ent", "d1mba__.ent-d1cg5a_", "d1mba__.ent-d1cg5a_.ent", "d1mba__.ent-d1cg5b_", "d1mba__.ent-d1cg5b_.ent", "d1mba__.ent-d1ew6a_", "d1mba__.ent-d1ew6a_.ent", "d1mba__.ent-d1gcva_", "d1mba__.ent-d1gcva_.ent", "d1mba__.ent-d1irda_", "d1mba__.ent-d1irda_.ent", "d1mba__.ent-d1itha_", "d1mba__.ent-d1itha_.ent", "d1mba__.ent-d1la6a_", "d1mba__.ent-d1la6a_.ent", "d1mba__.ent-d3sdha_", "d1mba__.ent-d3sdha_.ent", "d1mbma_.ent-d1qq4a_.ent", "d1mbma_.ent-d1svpa_.ent", "d1mbma_.ent-d2hrva_.ent", "d1mc0a1.ent-d1mc0a2.ent", "d1mc0a1.ent-d1mkma2.ent", "d1mc0a1.ent-d1pne__.ent", "d1mc0a1.ent-d3pyp__.ent", "d1mc0a2.ent-d1mkma2.ent", "d1mc2a_.ent-d1poc__.ent", "d1md0a_.ent-d1bjaa_.ent", "d1md0a_.ent-d1bm9a_.ent", "d1md0a_.ent-d1d5va_.ent", "d1md0a_.ent-d1e17a_.ent", "d1md0a_.ent-d1f1za1.ent", "d1md0a_.ent-d1fc3a_.ent", "d1md0a_.ent-d1fnna1.ent", "d1md0a_.ent-d1fp1d1.ent", "d1md0a_.ent-d1fp2a1.ent", "d1md0a_.ent-d1fsha_.ent", "d1md0a_.ent-d1fzpb_.ent", "d1md0a_.ent-d1hks__.ent", "d1md0a_.ent-d1hsja1.ent", "d1md0a_.ent-d1ig6a_.ent", "d1md0a_.ent-d1igna2.ent", "d1md0a_.ent-d1jhga_.ent", "d1md0a_.ent-d1ka8a_.ent", "d1md0a_.ent-d1ldja1.ent", "d1md0a_.ent-d1opc__.ent", "d1md0a_.ent-d1repc1.ent", "d1md0a_.ent-d1repc2.ent", "d1md0a_.ent-d1smta_.ent", "d1md0a_.ent-d2ezl__.ent", "d1md0a_.ent-d2foka1.ent", "d1md0a_.ent-d2foka2.ent", "d1md0a_.ent-d2foka3.ent", "d1md0a_.ent-d2irfg_.ent", "d1mdya_.ent-d1nkpa_.ent", "d1mdya_.ent-d1nkpb_.ent", "d1mdya_.ent-d1nlwa_.ent", "d1me4a_.ent-d1nbfa_.ent", "d1me4a_.ent-d1ppn__.ent", "d1me4a_.ent-d1qmya_.ent", "d1me4a_.ent-d1uch__.ent", "d1me4a_.ent-d2act__.ent", "d1me4a_.ent-d2cb5a_.ent", "d1me4a_.ent-d3gcb__.ent", "d1me4a_.ent-d7pcka_.ent", "d1mek__.ent-d1a8l_1.ent", "d1mek__.ent-d1a8l_2.ent", "d1mek__.ent-d1a8y_3.ent", "d1mek__.ent-d1bed_2.ent", "d1mek__.ent-d1bjx__.ent", "d1mek__.ent-d1ep7a_.ent", "d1mek__.ent-d1erv__.ent", "d1mek__.ent-d1f9ma_.ent", "d1mek__.ent-d1fb6a_.ent", "d1mek__.ent-d1gh2a_.ent", "d1mek__.ent-d1kte__.ent", "d1mek__.ent-d1quwa_.ent", "d1mek__.ent-d1thx__.ent", "d1mek__.ent-d2trxa_.ent", "d1mfga_.ent-d1qaua_.ent", "d1mfga_.ent-d1qava_.ent", "d1mfga_.ent-d1qlca_.ent", "d1mfoa_.ent-d1mwxa3.ent", "d1mfoa_.ent-d1nj4a2.ent", "d1mfoa_.ent-d1qmea4.ent", "d1mfoa_.ent-d4blma_.ent", "d1mg2d_.ent-d1c52__.ent", "d1mg2d_.ent-d1co6a_.ent", "d1mg2d_.ent-d1cot__.ent", "d1mg2d_.ent-d1cxc__.ent", "d1mg2d_.ent-d1dw0a_.ent", "d1mg2d_.ent-d1e29a_.ent", "d1mg2d_.ent-d1etpa2.ent", "d1mg2d_.ent-d1f1ca_.ent", "d1mg2d_.ent-d1gu2a_.ent", "d1mg2d_.ent-d1hroa_.ent", "d1mg2d_.ent-d1kb0a1.ent", "d1mg2d_.ent-d1kv9a1.ent", "d1mg2d_.ent-d1nira1.ent", "d1mg2d_.ent-d1qksa1.ent", "d1mg2d_.ent-d1ql3a_.ent", "d1mg2d_.ent-d1qn2a_.ent", "d1mg2d_.ent-d1ycc__.ent", "d1mg2d_.ent-d3c2c__.ent", "d1mgqa_.ent-d1mxma1.ent", "d1mgqa_.ent-d1n9ra_.ent", "d1mgta2.ent-d1qnta2.ent", "d1mgta2.ent-d1sfe_2.ent", "d1mh9a_.ent-d1qq5a_.ent", "d1mh9a_.ent-d1zrn__.ent", "d1mil__.ent-d1qada_.ent", "d1mil__.ent-d2abl_2.ent", "d1mil__.ent-d2cbla3.ent", "d1mil__.ent-d2plda_.ent", "d1mil__.ent-d2shpa3.ent", "d1mioa_.ent-d1miob_.ent", "d1mioa_.ent-d1n2za_.ent", "d1mioa_.ent-d1psza_.ent", "d1mioa_.ent-d1toaa_.ent", "d1miob_.ent-d1n2za_.ent", "d1miob_.ent-d1psza_.ent", "d1miob_.ent-d1toaa_.ent", "d1mixa2.ent-d1mkea1.ent", "d1mixa2.ent-d1pls__.ent", "d1mixa2.ent-d1qqga1.ent", "d1mixa2.ent-d1qqga2.ent", "d1mixa2.ent-d1shca_.ent", "d1mj3a_.ent-d1nzya_.ent", "d1mj3a_.ent-d1o8ua_.ent", "d1mj3a_.ent-d1tyfa_.ent", "d1mjfa_.ent-d1eg2a_.ent", "d1mjfa_.ent-d1fp1d2.ent", "d1mjfa_.ent-d1fp2a2.ent", "d1mjfa_.ent-d1g60a_.ent", "d1mjfa_.ent-d1hnna_.ent", "d1mjfa_.ent-d1i1na_.ent", "d1mjfa_.ent-d1i9ga_.ent", "d1mjfa_.ent-d1jg1a_.ent", "d1mjfa_.ent-d1kywa2.ent", "d1mjfa_.ent-d1qama_.ent", "d1mjfa_.ent-d1yub__.ent", "d1mjfa_.ent-d2dpma_.ent", "d1mjga_.ent-d1mjgm_.ent", "d1mjha_.ent-d1n3la_.ent", "d1mjha_.ent-d1o97c_.ent", "d1mjha_.ent-d1o97d1.ent", "d1mjha_.ent-d1qjca_.ent", "d1mjha_.ent-d1sur__.ent", "d1mjna_.ent-d1n3ya_.ent", "d1mjna_.ent-d1qc5a_.ent", "d1mjsa_.ent-d1ygs__.ent", "d1mkea1.ent-d1pls__.ent", "d1mkea1.ent-d1qqga1.ent", "d1mkea1.ent-d1qqga2.ent", "d1mkea1.ent-d1shca_.ent", "d1mkma2.ent-d1pne__.ent", "d1mkma2.ent-d3pyp__.ent", "d1mkp__.ent-d1vhra_.ent", "d1mkp__.ent-d1yfoa_.ent", "d1mkp__.ent-d2shpa1.ent", "d1mkya3.ent-d3proc1.ent", "d1mkya3.ent-d3proc2.ent", "d1ml4a1.ent-d1ml4a2.ent", "d1ml4a1.ent-d1otha1.ent", "d1ml4a1.ent-d1otha2.ent", "d1ml4a2.ent-d1otha1.ent", "d1ml4a2.ent-d1otha2.ent", "d1mla_1.ent-d1nm2a1.ent", "d1mlva2.ent-d1mvha_.ent", "d1mlva2.ent-d1n3ja_.ent", "d1mlva2.ent-d1tul__.ent", "d1mlva2.ent-d4ubpb_.ent", "d1mm4a_.ent-d1qj8a_.ent", "d1mm4a_.ent-d1qjpa_.ent", "d1mm4a_.ent-d2mpra_.ent", "d1mm4a_.ent-d2por__.ent", "d1mmc__.ent-d9wgaa2.ent", "d1mml__.ent-d1mswd_.ent", "d1mml__.ent-d1muka_.ent", "d1mml__.ent-d1rdr__.ent", "d1mml__.ent-d1t7pa2.ent", "d1mml__.ent-d1tgoa2.ent", "d1mml__.ent-d1vrta2.ent", "d1mml__.ent-d1xwl_2.ent", "d1mn2__.ent-d1pa2a_.ent", "d1mnaa_.ent-d1n1ma2.ent", "d1mnaa_.ent-d1qj4a_.ent", "d1mnaa_.ent-d1qlwa_.ent", "d1mnaa_.ent-d1qo7a_.ent", "d1mnaa_.ent-d1tca__.ent", "d1mnaa_.ent-d1thta_.ent", "d1mnaa_.ent-d3tgl__.ent", "d1mnna_.ent-d1nbca_.ent", "d1mnna_.ent-d1pdkb_.ent", "d1mnna_.ent-d1qba_2.ent", "d1mnna_.ent-d1tf4a2.ent", "d1mnna_.ent-d1ycsa_.ent", "d1mnta_.ent-d2cpga_.ent", "d1mo9a1.ent-d1chua2.ent", "d1mo9a1.ent-d1cjca1.ent", "d1mo9a1.ent-d1ebda1.ent", "d1mo9a1.ent-d1feca1.ent", "d1mo9a1.ent-d1h6va1.ent", "d1mo9a1.ent-d1jeha1.ent", "d1mo9a1.ent-d1ojt_1.ent", "d1mo9a1.ent-d3lada1.ent", "d1mo9a3.ent-d1n62c1.ent", "d1mo9a3.ent-d1nhp_3.ent", "d1mo9a3.ent-d1ojt_3.ent", "d1mo9a3.ent-d3grs_3.ent", "d1mo9a3.ent-d3lada3.ent", "d1mola_.ent-d1mwxa1.ent", "d1mola_.ent-d1o7nb_.ent", "d1mola_.ent-d1oaca2.ent", "d1mola_.ent-d1stfi_.ent", "d1mola_.ent-d1ugia_.ent", "d1mola_.ent-d3stda_.ent", "d1mooa_.ent-d2znc__.ent", "d1mpga1.ent-d1mun__.ent", "d1mpga1.ent-d2abk__.ent", "d1mpga2.ent-d1ytba1.ent", "d1mpga2.ent-d1ytba2.ent", "d1mpga2.ent-d3pmga4.ent", "d1mpp__.ent-d1nsoa_.ent", "d1mpp__.ent-d2apr__.ent", "d1mpp__.ent-d2rspa_.ent", "d1mpp__.ent-d3psg__.ent", "d1mpp__.ent-d4fiv__.ent", "d1mpya1.ent-d1mpya2.ent", "d1mpya1.ent-d1qipa_.ent", "d1mpya1.ent-d1qtoa_.ent", "d1mpya2.ent-d1qipa_.ent", "d1mpya2.ent-d1qtoa_.ent", "d1mpza_.ent-d1n4ya_.ent", "d1mpza_.ent-d2ech__.ent", "d1mqva_.ent-d256ba_.ent", "d1mqva_.ent-d2ccya_.ent", "d1mrj__.ent-d1qi7a_.ent", "d1mrp__.ent-d1nh8a1.ent", "d1mrp__.ent-d1pda_1.ent", "d1mrp__.ent-d1pot__.ent", "d1mrp__.ent-d1sbp__.ent", "d1mrp__.ent-d1wdna_.ent", "d1mrp__.ent-d3mbp__.ent", "d1mrp__.ent-d3thia_.ent", "d1mswd_.ent-d1muka_.ent", "d1mswd_.ent-d1rdr__.ent", "d1mswd_.ent-d1t7pa2.ent", "d1mswd_.ent-d1tgoa2.ent", "d1mswd_.ent-d1vrta2.ent", "d1mswd_.ent-d1xwl_2.ent", "d1msza_.ent-d1qmha2.ent", "d1msza_.ent-d1tig__.ent", "d1mtyb_.ent-d1mtyd_.ent", "d1mtyb_.ent-d1qgha_.ent", "d1mtyb_.ent-d1rcd__.ent", "d1mtyd_.ent-d1qgha_.ent", "d1mtyd_.ent-d1rcd__.ent", "d1mtyg_.ent-d1om2a_.ent", "d1mu5a1.ent-d1nnja1.ent", "d1mu5a2.ent-d1n0ua3.ent", "d1mu5a2.ent-d1pkp_1.ent", "d1muca1.ent-d1onea1.ent", "d1muca1.ent-d2chr_1.ent", "d1muca1.ent-d2mnr_1.ent", "d1muca2.ent-d1onea2.ent", "d1muca2.ent-d2chr_2.ent", "d1muca2.ent-d2mnr_2.ent", "d1muga_.ent-d3euga_.ent", "d1muka_.ent-d1rdr__.ent", "d1muka_.ent-d1t7pa2.ent", "d1muka_.ent-d1tgoa2.ent", "d1muka_.ent-d1vrta2.ent", "d1muka_.ent-d1xwl_2.ent", "d1mun__.ent-d2abk__.ent", "d1musa_.ent-d1az9_1.ent", "d1musa_.ent-d1bco_2.ent", "d1musa_.ent-d1bupa1.ent", "d1musa_.ent-d1bupa2.ent", "d1musa_.ent-d1czan1.ent", "d1musa_.ent-d1czan2.ent", "d1musa_.ent-d1e4ft1.ent", "d1musa_.ent-d1e4ft2.ent", "d1musa_.ent-d1g99a2.ent", "d1musa_.ent-d1glag1.ent", "d1musa_.ent-d1glag2.ent", "d1musa_.ent-d1huxa_.ent", "d1musa_.ent-d1ih7a1.ent", "d1musa_.ent-d1j54a_.ent", "d1musa_.ent-d1j6za2.ent", "d1musa_.ent-d1jj2m_.ent", "d1musa_.ent-d1kcfa2.ent", "d1musa_.ent-d1mwma2.ent", "d1musa_.ent-d1nbwa2.ent", "d1musa_.ent-d1nbwa3.ent", "d1musa_.ent-d1qtma1.ent", "d1musa_.ent-d1t7pa1.ent", "d1musa_.ent-d1tgoa1.ent", "d1musa_.ent-d1vrta1.ent", "d1musa_.ent-d1xwl_1.ent", "d1muwa_.ent-d1d3ga_.ent", "d1muwa_.ent-d1edg__.ent", "d1muwa_.ent-d1gvoa_.ent", "d1muwa_.ent-d1gw1a_.ent", "d1muwa_.ent-d1itua_.ent", "d1muwa_.ent-d1k4ga_.ent", "d1muwa_.ent-d1kbla1.ent", "d1muwa_.ent-d1m7ja3.ent", "d1muwa_.ent-d1qtwa_.ent", "d1mvha_.ent-d1n3ja_.ent", "d1mvoa_.ent-d1nat__.ent", "d1mvoa_.ent-d1ntr__.ent", "d1mvoa_.ent-d1qo0d_.ent", "d1mvoa_.ent-d1tmy__.ent", "d1mwma1.ent-d1mwma2.ent", "d1mwma1.ent-d1nbwa2.ent", "d1mwma1.ent-d1nbwa3.ent", "d1mwma2.ent-d1nbwa2.ent", "d1mwma2.ent-d1nbwa3.ent", "d1mwxa1.ent-d1o7nb_.ent", "d1mwxa1.ent-d1oaca2.ent", "d1mwxa1.ent-d1qjga_.ent", "d1mwxa1.ent-d1stfi_.ent", "d1mwxa1.ent-d1ugia_.ent", "d1mwxa1.ent-d3stda_.ent", "d1mwxa3.ent-d1nj4a2.ent", "d1mwxa3.ent-d1qmea4.ent", "d1mwxa3.ent-d4blma_.ent", "d1mx3a2.ent-d1pjca2.ent", "d1mx3a2.ent-d1psda2.ent", "d1mx3a2.ent-d2naca2.ent", "d1mxa_2.ent-d1mxa_3.ent", "d1mxa_2.ent-d1qm4a2.ent", "d1mxa_3.ent-d1qm4a2.ent", "d1mxma1.ent-d1n9ra_.ent", "d1my7a_.ent-d1eut_1.ent", "d1my7a_.ent-d1qba_1.ent", "d1my7a_.ent-d1qfha1.ent", "d1myn__.ent-d1npia_.ent", "d1myn__.ent-d1nrb__.ent", "d1myn__.ent-d1qkya_.ent", "d1myn__.ent-d1sco__.ent", "d1myn__.ent-d1scy__.ent", "d1myn__.ent-d1sis__.ent", "d1myn__.ent-d1tsk__.ent", "d1myn__.ent-d2sn3__.ent", "d1myo__.ent-d1n11a_.ent", "d1myo__.ent-d1sw6a_.ent", "d1myo__.ent-d1ycsb1.ent", "d1mzaa_.ent-d1azza_.ent", "d1mzaa_.ent-d1bio__.ent", "d1mzaa_.ent-d1bqya_.ent", "d1mzaa_.ent-d1cgha_.ent", "d1mzaa_.ent-d1ekbb_.ent", "d1mzaa_.ent-d1elva1.ent", "d1mzaa_.ent-d1fjsa_.ent", "d1mzaa_.ent-d1gdna_.ent", "d1mzaa_.ent-d1gpza1.ent", "d1mzaa_.ent-d1gvza_.ent", "d1mzaa_.ent-d1hj9a_.ent", "d1mzaa_.ent-d1rfna_.ent", "d1mzaa_.ent-d2hlca_.ent", "d1mzha_.ent-d1nal1_.ent", "d1mzha_.ent-d1o0ya_.ent", "d1mzha_.ent-d1qfea_.ent", "d1mzja1.ent-d1mzja2.ent", "d1mzna_.ent-d1n83a_.ent", "d1mzna_.ent-d2prga_.ent", "d1mzua_.ent-d3pyp__.ent", "d1n08a_.ent-d1n0ua1.ent", "d1n08a_.ent-d1qfja1.ent", "d1n08a_.ent-d2pia_1.ent", "d1n0ua1.ent-d1qfja1.ent", "d1n0ua1.ent-d2pia_1.ent", "d1n0ua2.ent-d1e2ka_.ent", "d1n0ua2.ent-d1f9va_.ent", "d1n0ua2.ent-d1g8pa_.ent", "d1n0ua2.ent-d1ksfx3.ent", "d1n0ua2.ent-d1pjr_1.ent", "d1n0ua2.ent-d1pjr_2.ent", "d1n0ua2.ent-d1uaaa1.ent", "d1n0ua3.ent-d1pkp_1.ent", "d1n0ua4.ent-d1n0ua5.ent", "d1n11a_.ent-d1sw6a_.ent", "d1n11a_.ent-d1ycsb1.ent", "d1n1aa_.ent-d1pbk__.ent", "d1n1aa_.ent-d1pina2.ent", "d1n1ba1.ent-d1n7oa1.ent", "d1n1ba1.ent-d1qaza_.ent", "d1n1ba1.ent-d2sqca1.ent", "d1n1ba1.ent-d2sqca2.ent", "d1n1ba1.ent-d5eau_1.ent", "d1n1ba2.ent-d1ps1a_.ent", "d1n1ba2.ent-d1uby__.ent", "d1n1ba2.ent-d5eau_2.ent", "d1n1fa_.ent-d2gmfa_.ent", "d1n1fa_.ent-d2ilk__.ent", "d1n1ja_.ent-d1n1jb_.ent", "d1n1ma2.ent-d1qj4a_.ent", "d1n1ma2.ent-d1qlwa_.ent", "d1n1ma2.ent-d1qo7a_.ent", "d1n1ma2.ent-d1tca__.ent", "d1n1ma2.ent-d1thta_.ent", "d1n1ma2.ent-d3tgl__.ent", "d1n1ta1.ent-d1dhkb_.ent", "d1n1ta1.ent-d1dyka1.ent", "d1n1ta1.ent-d1dyka2.ent", "d1n1ta1.ent-d1epwa1.ent", "d1n1ta1.ent-d1h30a1.ent", "d1n1ta1.ent-d1h30a2.ent", "d1n1ta1.ent-d1kit_1.ent", "d1n1ta1.ent-d1kit_2.ent", "d1n1ta1.ent-d1nls__.ent", "d1n1ta1.ent-d1saca_.ent", "d1n1ta1.ent-d1xnb__.ent", "d1n1ta1.ent-d2ayh__.ent", "d1n1ta1.ent-d2nlra_.ent", "d1n1ta1.ent-d2sli_1.ent", "d1n1ta1.ent-d3btaa1.ent", "d1n1ta2.ent-d1nsca_.ent", "d1n1ta2.ent-d2bat__.ent", "d1n1ta2.ent-d2sli_2.ent", "d1n1ta2.ent-d3sil__.ent", "d1n26a2.ent-d1cd9b2.ent", "d1n26a2.ent-d1cfb_1.ent", "d1n26a2.ent-d1egja_.ent", "d1n26a2.ent-d1f6fb1.ent", "d1n26a2.ent-d1f6fb2.ent", "d1n26a2.ent-d1fyhb1.ent", "d1n26a2.ent-d1i1ra1.ent", "d1n26a2.ent-d1lqsr1.ent", "d1n26a2.ent-d2hft_1.ent", "d1n26a3.ent-d1cd9b2.ent", "d1n26a3.ent-d1cfb_1.ent", "d1n26a3.ent-d1egja_.ent", "d1n26a3.ent-d1f6fb1.ent", "d1n26a3.ent-d1f6fb2.ent", "d1n26a3.ent-d1fyhb1.ent", "d1n26a3.ent-d1fyhb2.ent", "d1n26a3.ent-d1gh7a1.ent", "d1n26a3.ent-d1i1ra1.ent", "d1n26a3.ent-d1lqsr1.ent", "d1n26a3.ent-d1n26a2.ent", "d1n26a3.ent-d1qg3a2.ent", "d1n26a3.ent-d2hft_1.ent", "d1n26a3.ent-d2hft_2.ent", "d1n2sa_.ent-d1bdb__.ent", "d1n2sa_.ent-d1bg6_2.ent", "d1n2sa_.ent-d1bgva1.ent", "d1n2sa_.ent-d1c1da1.ent", "d1n2sa_.ent-d1cf2o1.ent", "d1n2sa_.ent-d1dlja2.ent", "d1n2sa_.ent-d1dpga1.ent", "d1n2sa_.ent-d1dssg1.ent", "d1n2sa_.ent-d1e5qa1.ent", "d1n2sa_.ent-d1e7wa_.ent", "d1n2sa_.ent-d1eno__.ent", "d1n2sa_.ent-d1eny__.ent", "d1n2sa_.ent-d1f0ya2.ent", "d1n2sa_.ent-d1fds__.ent", "d1n2sa_.ent-d1g0oa_.ent", "d1n2sa_.ent-d1gcoa_.ent", "d1n2sa_.ent-d1gr0a1.ent", "d1n2sa_.ent-d1h5qa_.ent", "d1n2sa_.ent-d1hdoa_.ent", "d1n2sa_.ent-d1hdr__.ent", "d1n2sa_.ent-d1hwxa1.ent", "d1n2sa_.ent-d1hxha_.ent", "d1n2sa_.ent-d1ja9a_.ent", "d1n2sa_.ent-d1jaya_.ent", "d1n2sa_.ent-d1lc0a1.ent", "d1n2sa_.ent-d1lu9a1.ent", "d1n2sa_.ent-d1n5da_.ent", "d1n2sa_.ent-d1oaa__.ent", "d1n2sa_.ent-d1qmga2.ent", "d1n2sa_.ent-d1qsga_.ent", "d1n2sa_.ent-d2ae2a_.ent", "d1n2sa_.ent-d2naca1.ent", "d1n2sa_.ent-d2pgd_2.ent", "d1n2za_.ent-d1psza_.ent", "d1n2za_.ent-d1qgoa_.ent", "d1n2za_.ent-d1toaa_.ent", "d1n3ja_.ent-d1tul__.ent", "d1n3ja_.ent-d4ubpb_.ent", "d1n3ka_.ent-d1ngr__.ent", "d1n3ka_.ent-d3crd__.ent", "d1n3ka_.ent-d3ygsp_.ent", "d1n3la_.ent-d1o97c_.ent", "d1n3la_.ent-d1o97d1.ent", "d1n3la_.ent-d1qjca_.ent", "d1n3la_.ent-d1sur__.ent", "d1n3oa_.ent-d1dhkb_.ent", "d1n3oa_.ent-d1dyka1.ent", "d1n3oa_.ent-d1dyka2.ent", "d1n3oa_.ent-d1epwa1.ent", "d1n3oa_.ent-d1fx5a_.ent", "d1n3oa_.ent-d1gv9a_.ent", "d1n3oa_.ent-d1gzca_.ent", "d1n3oa_.ent-d1h30a1.ent", "d1n3oa_.ent-d1h30a2.ent", "d1n3oa_.ent-d1jhna4.ent", "d1n3oa_.ent-d1kit_1.ent", "d1n3oa_.ent-d1kit_2.ent", "d1n3oa_.ent-d1n1ta1.ent", "d1n3oa_.ent-d1nls__.ent", "d1n3oa_.ent-d1saca_.ent", "d1n3oa_.ent-d1xnb__.ent", "d1n3oa_.ent-d2ayh__.ent", "d1n3oa_.ent-d2nlra_.ent", "d1n3oa_.ent-d2pela_.ent", "d1n3oa_.ent-d2sli_1.ent", "d1n3oa_.ent-d3btaa1.ent", "d1n3ya_.ent-d1qc5a_.ent", "d1n4ya_.ent-d2ech__.ent", "d1n55a_.ent-d1trea_.ent", "d1n5da_.ent-d1bdb__.ent", "d1n5da_.ent-d1bgva1.ent", "d1n5da_.ent-d1e7wa_.ent", "d1n5da_.ent-d1eny__.ent", "d1n5da_.ent-d1fds__.ent", "d1n5da_.ent-d1g0oa_.ent", "d1n5da_.ent-d1gcoa_.ent", "d1n5da_.ent-d1h5qa_.ent", "d1n5da_.ent-d1ja9a_.ent", "d1n5da_.ent-d1oaa__.ent", "d1n5da_.ent-d1qsga_.ent", "d1n5da_.ent-d2ae2a_.ent", "d1n62a2.ent-d1nekb2.ent", "d1n62a2.ent-d1put__.ent", "d1n62a2.ent-d1qlab2.ent", "d1n62a2.ent-d2pia_3.ent", "d1n62b1.ent-d1qpoa2.ent", "d1n62c1.ent-d1nhp_3.ent", "d1n62c1.ent-d3grs_3.ent", "d1n62c2.ent-d1uxy_1.ent", "d1n69a_.ent-d1nkl__.ent", "d1n7da6.ent-d1n7da7.ent", "d1n7da6.ent-d1n7daa.ent", "d1n7da7.ent-d1n7daa.ent", "d1n7ha_.ent-d1bdb__.ent", "d1n7ha_.ent-d1bg6_2.ent", "d1n7ha_.ent-d1bgva1.ent", "d1n7ha_.ent-d1c1da1.ent", "d1n7ha_.ent-d1cf2o1.ent", "d1n7ha_.ent-d1dlja2.ent", "d1n7ha_.ent-d1dpga1.ent", "d1n7ha_.ent-d1dssg1.ent", "d1n7ha_.ent-d1e5qa1.ent", "d1n7ha_.ent-d1e6ua_.ent", "d1n7ha_.ent-d1e7wa_.ent", "d1n7ha_.ent-d1eno__.ent", "d1n7ha_.ent-d1eny__.ent", "d1n7ha_.ent-d1f0ya2.ent", "d1n7ha_.ent-d1fds__.ent", "d1n7ha_.ent-d1g0oa_.ent", "d1n7ha_.ent-d1gcoa_.ent", "d1n7ha_.ent-d1gr0a1.ent", "d1n7ha_.ent-d1h5qa_.ent", "d1n7ha_.ent-d1hdoa_.ent", "d1n7ha_.ent-d1hdr__.ent", "d1n7ha_.ent-d1hwxa1.ent", "d1n7ha_.ent-d1hxha_.ent", "d1n7ha_.ent-d1ja9a_.ent", "d1n7ha_.ent-d1jaya_.ent", "d1n7ha_.ent-d1k6xa_.ent", "d1n7ha_.ent-d1lc0a1.ent", "d1n7ha_.ent-d1llqa1.ent", "d1n7ha_.ent-d1lu9a1.ent", "d1n7ha_.ent-d1n2sa_.ent", "d1n7ha_.ent-d1n5da_.ent", "d1n7ha_.ent-d1oaa__.ent", "d1n7ha_.ent-d1qmga2.ent", "d1n7ha_.ent-d1qsga_.ent", "d1n7ha_.ent-d2ae2a_.ent", "d1n7ha_.ent-d2naca1.ent", "d1n7ha_.ent-d2pgd_2.ent", "d1n7oa1.ent-d1qaza_.ent", "d1n7oa1.ent-d2sqca1.ent", "d1n7oa1.ent-d2sqca2.ent", "d1n7oa3.ent-d1nsza_.ent", "d1n83a_.ent-d2prga_.ent", "d1n8pa_.ent-d1b9ha_.ent", "d1n8pa_.ent-d1bs0a_.ent", "d1n8pa_.ent-d1gdea_.ent", "d1n8pa_.ent-d1j32a_.ent", "d1n8yc1.ent-d1n8yc2.ent", "d1n8yc3.ent-d1agg__.ent", "d1n8yc3.ent-d1aho__.ent", "d1n8yc3.ent-d1apq__.ent", "d1n8yc3.ent-d1b9wa1.ent", "d1n8yc3.ent-d1b9wa2.ent", "d1n8yc3.ent-d1bx7__.ent", "d1n8yc3.ent-d1c2aa1.ent", "d1n8yc3.ent-d1cixa_.ent", "d1n8yc3.ent-d1e0fi_.ent", "d1n8yc3.ent-d1flei_.ent", "d1n8yc3.ent-d1g9pa_.ent", "d1n8yc3.ent-d1gps__.ent", "d1n8yc3.ent-d1h59b_.ent", "d1n8yc3.ent-d1hyka_.ent", "d1n8yc3.ent-d1i2ua_.ent", "d1n8yc3.ent-d1ijqa2.ent", "d1n8yc3.ent-d1imt_2.ent", "d1n8yc3.ent-d1jkza_.ent", "d1n8yc3.ent-d1klil_.ent", "d1n8yc3.ent-d1klo_1.ent", "d1n8yc3.ent-d1klo_3.ent", "d1n8yc3.ent-d1lpba2.ent", "d1n8yc3.ent-d1n8yc4.ent", "d1n8yc3.ent-d2sn3__.ent", "d1n8yc3.ent-d4htci_.ent", "d1nal1_.ent-d1o0ya_.ent", "d1nal1_.ent-d1qfea_.ent", "d1nat__.ent-d1ntr__.ent", "d1nat__.ent-d1qo0d_.ent", "d1nat__.ent-d1tmy__.ent", "d1nbaa_.ent-d1yaca_.ent", "d1nbca_.ent-d1pdkb_.ent", "d1nbca_.ent-d1qba_2.ent", "d1nbca_.ent-d1tf4a2.ent", "d1nbca_.ent-d1ycsa_.ent", "d1nbfa_.ent-d1ppn__.ent", "d1nbfa_.ent-d1qmya_.ent", "d1nbfa_.ent-d1uch__.ent", "d1nbfa_.ent-d2act__.ent", "d1nbfa_.ent-d2cb5a_.ent", "d1nbfa_.ent-d3gcb__.ent", "d1nbfa_.ent-d7pcka_.ent", "d1nbwa2.ent-d1az9_1.ent", "d1nbwa2.ent-d1bco_2.ent", "d1nbwa2.ent-d1bupa1.ent", "d1nbwa2.ent-d1bupa2.ent", "d1nbwa2.ent-d1czan1.ent", "d1nbwa2.ent-d1e4ft1.ent", "d1nbwa2.ent-d1e4ft2.ent", "d1nbwa2.ent-d1j54a_.ent", "d1nbwa2.ent-d1j6za2.ent", "d1nbwa2.ent-d1jj2m_.ent", "d1nbwa2.ent-d1kcfa2.ent", "d1nbwa2.ent-d1mwma2.ent", "d1nbwa2.ent-d1nbwa3.ent", "d1nbwa2.ent-d1t7pa1.ent", "d1nbwa2.ent-d1xwl_1.ent", "d1nbwa3.ent-d1az9_1.ent", "d1nbwa3.ent-d1bupa1.ent", "d1nbwa3.ent-d1bupa2.ent", "d1nbwa3.ent-d1e4ft1.ent", "d1nbwa3.ent-d1e4ft2.ent", "d1nbwa3.ent-d1j54a_.ent", "d1nbwa3.ent-d1jj2m_.ent", "d1nbwa3.ent-d1mwma2.ent", "d1nbwa3.ent-d1xwl_1.ent", "d1nbwb_.ent-d1qe0a1.ent", "d1ncs__.ent-d1paa__.ent", "d1ncs__.ent-d1rmd_1.ent", "d1ncs__.ent-d1tf3a1.ent", "d1ncs__.ent-d1tf3a2.ent", "d1ncs__.ent-d1tf3a3.ent", "d1ncs__.ent-d1tf6a4.ent", "d1ncs__.ent-d1ubdc3.ent", "d1ncs__.ent-d1yuja_.ent", "d1ncs__.ent-d1zfd__.ent", "d1ncs__.ent-d2drpa1.ent", "d1ncs__.ent-d2glia1.ent", "d1ncs__.ent-d2glia2.ent", "d1ncs__.ent-d2glia4.ent", "d1ncs__.ent-d5znf__.ent", "d1ncx__.ent-d1eg3a1.ent", "d1ncx__.ent-d1exra_.ent", "d1ncx__.ent-d1ggwa_.ent", "d1ncx__.ent-d1jfja_.ent", "d1ncx__.ent-d1m31a_.ent", "d1ncx__.ent-d1m45a_.ent", "d1ncx__.ent-d1rro__.ent", "d1ncx__.ent-d1sra__.ent", "d1ncx__.ent-d1wdcb_.ent", "d1ncx__.ent-d1wdcc_.ent", "d1ncx__.ent-d2pvba_.ent", "d1ncx__.ent-d5pal__.ent", "d1nd6a_.ent-d1qfxa_.ent", "d1nd6a_.ent-d3pgm__.ent", "d1ne8a_.ent-d3vub__.ent", "d1neb__.ent-d1pht__.ent", "d1neb__.ent-d1pwt__.ent", "d1neb__.ent-d1qcfa1.ent", "d1neb__.ent-d1ycsb2.ent", "d1neb__.ent-d2hsp__.ent", "d1neka1.ent-d1qlaa1.ent", "d1neka2.ent-d1chua2.ent", "d1neka2.ent-d1cjca1.ent", "d1neka2.ent-d1ebda1.ent", "d1neka2.ent-d1feca1.ent", "d1neka2.ent-d1h6va1.ent", "d1neka2.ent-d1jeha1.ent", "d1neka2.ent-d1k0ia1.ent", "d1neka2.ent-d1kf6a2.ent", "d1neka2.ent-d1kssa2.ent", "d1neka2.ent-d1l9ea1.ent", "d1neka2.ent-d1mo9a1.ent", "d1neka2.ent-d1ojt_1.ent", "d1neka2.ent-d1qo8a2.ent", "d1neka2.ent-d3lada1.ent", "d1neka3.ent-d1qlaa3.ent", "d1neka3.ent-d1qo8a3.ent", "d1nekb1.ent-d1qlab1.ent", "d1nekb2.ent-d1put__.ent", "d1nekb2.ent-d1qlab2.ent", "d1nekb2.ent-d2pia_3.ent", "d1nekc_.ent-d1nekd_.ent", "d1nekc_.ent-d1qlac_.ent", "d1nekd_.ent-d1qlac_.ent", "d1nepa_.ent-d1dqia_.ent", "d1nepa_.ent-d1ea9c1.ent", "d1nepa_.ent-d1eaja_.ent", "d1nepa_.ent-d1edqa1.ent", "d1nepa_.ent-d1eut_1.ent", "d1nepa_.ent-d1grwa_.ent", "d1nepa_.ent-d1j0ha1.ent", "d1nepa_.ent-d1ji1a1.ent", "d1nepa_.ent-d1ji2a1.ent", "d1nepa_.ent-d1kgce2.ent", "d1nepa_.ent-d1ktja_.ent", "d1nepa_.ent-d1kv3a1.ent", "d1nepa_.ent-d1m7xa1.ent", "d1nepa_.ent-d1my7a_.ent", "d1nepa_.ent-d1o75a1.ent", "d1nepa_.ent-d1qba_1.ent", "d1nepa_.ent-d1qfha1.ent", "d1nepa_.ent-d1qfha2.ent", "d1nepa_.ent-d1soxa1.ent", "d1ner__.ent-d1r69__.ent", "d1ner__.ent-d1uxc__.ent", "d1ner__.ent-d1uxd__.ent", "d1ner__.ent-d1vpwa1.ent", "d1ner__.ent-d2cro__.ent", "d1neu__.ent-d1akjd_.ent", "d1neu__.ent-d1b88a_.ent", "d1neu__.ent-d1bec_1.ent", "d1neu__.ent-d1c5ch1.ent", "d1neu__.ent-d1dlfl_.ent", "d1neu__.ent-d1h5ba_.ent", "d1neu__.ent-d1nfdb1.ent", "d1neu__.ent-d1qfoa_.ent", "d1neu__.ent-d2rhe__.ent", "d1nf5b_.ent-d1qg8a_.ent", "d1nfdb1.ent-d1c5ch1.ent", "d1nfn__.ent-d1nlxa_.ent", "d1nfn__.ent-d256ba_.ent", "d1nfn__.ent-d2a0b__.ent", "d1nfn__.ent-d2liga_.ent", "d1nfn__.ent-d2mhr__.ent", "d1nfn__.ent-d3fapb_.ent", "d1ngr__.ent-d3crd__.ent", "d1ngr__.ent-d3ygsp_.ent", "d1nh8a1.ent-d1pda_1.ent", "d1nh8a1.ent-d1pot__.ent", "d1nh8a1.ent-d1sbp__.ent", "d1nh8a1.ent-d1wdna_.ent", "d1nh8a1.ent-d3mbp__.ent", "d1nh8a1.ent-d3thia_.ent", "d1nhp_1.ent-d1nhp_2.ent", "d1nhp_1.ent-d1o94a2.ent", "d1nhp_1.ent-d3grs_1.ent", "d1nhp_1.ent-d3grs_2.ent", "d1nhp_2.ent-d1o94a2.ent", "d1nhp_2.ent-d3grs_1.ent", "d1nhp_2.ent-d3grs_2.ent", "d1nhp_3.ent-d1ojt_3.ent", "d1nhp_3.ent-d3grs_3.ent", "d1nhp_3.ent-d3lada3.ent", "d1nira1.ent-d1co6a_.ent", "d1nira1.ent-d1etpa2.ent", "d1nira1.ent-d1hroa_.ent", "d1nira1.ent-d1kb0a1.ent", "d1nira1.ent-d1kv9a1.ent", "d1nira1.ent-d1ql3a_.ent", "d1nira1.ent-d1qn2a_.ent", "d1nira1.ent-d1ycc__.ent", "d1nira1.ent-d3c2c__.ent", "d1nixa_.ent-d1niya_.ent", "d1nixa_.ent-d1qk6a_.ent", "d1nixa_.ent-d1qk7a_.ent", "d1nixa_.ent-d1vtx__.ent", "d1niya_.ent-d1qk6a_.ent", "d1niya_.ent-d1qk7a_.ent", "d1niya_.ent-d1vtx__.ent", "d1nj4a2.ent-d1qmea4.ent", "d1nj4a2.ent-d4blma_.ent", "d1nkpa_.ent-d1nkpb_.ent", "d1nkpa_.ent-d1nlwa_.ent", "d1nkpb_.ent-d1nlwa_.ent", "d1nls__.ent-d1dhkb_.ent", "d1nls__.ent-d1dyka1.ent", "d1nls__.ent-d1dyka2.ent", "d1nls__.ent-d1epwa1.ent", "d1nls__.ent-d1gv9a_.ent", "d1nls__.ent-d1h30a1.ent", "d1nls__.ent-d1h30a2.ent", "d1nls__.ent-d1kit_1.ent", "d1nls__.ent-d1kit_2.ent", "d1nls__.ent-d1n1ta1.ent", "d1nls__.ent-d1saca_.ent", "d1nls__.ent-d1xnb__.ent", "d1nls__.ent-d2ayh__.ent", "d1nls__.ent-d2nlra_.ent", "d1nls__.ent-d2pela_.ent", "d1nls__.ent-d2sli_1.ent", "d1nls__.ent-d3btaa1.ent", "d1nlxa_.ent-d256ba_.ent", "d1nlxa_.ent-d2a0b__.ent", "d1nlxa_.ent-d2liga_.ent", "d1nlxa_.ent-d2mhr__.ent", "d1nlxa_.ent-d3fapb_.ent", "d1nnwa_.ent-d1ush_2.ent", "d1nnwa_.ent-d1utea_.ent", "d1nnwa_.ent-d4kbpa2.ent", "d1noa__.ent-d2mcm__.ent", "d1nocb_.ent-d3cla__.ent", "d1novc_.ent-d1aym1_.ent", "d1novc_.ent-d1aym2_.ent", "d1novc_.ent-d1b35a_.ent", "d1novc_.ent-d1b35b_.ent", "d1novc_.ent-d1b35c_.ent", "d1novc_.ent-d1bev1_.ent", "d1novc_.ent-d1bev3_.ent", "d1novc_.ent-d1d4m1_.ent", "d1novc_.ent-d1k5ma_.ent", "d1novc_.ent-d1pov0_.ent", "d1novc_.ent-d1pvc1_.ent", "d1novc_.ent-d1tmf1_.ent", "d1novc_.ent-d1vpsa_.ent", "d1novc_.ent-d2bbva_.ent", "d1novc_.ent-d2mev1_.ent", "d1novc_.ent-d2mev2_.ent", "d1nox__.ent-d1vfra_.ent", "d1np7a1.ent-d1qnf_1.ent", "d1np7a2.ent-d1qnf_2.ent", "d1npia_.ent-d1nrb__.ent", "d1npia_.ent-d1qkya_.ent", "d1npia_.ent-d1sco__.ent", "d1npia_.ent-d1scy__.ent", "d1npia_.ent-d1sis__.ent", "d1npia_.ent-d1tsk__.ent", "d1npia_.ent-d2sn3__.ent", "d1nrb__.ent-d1qkya_.ent", "d1nrb__.ent-d1sco__.ent", "d1nrb__.ent-d1scy__.ent", "d1nrb__.ent-d1sis__.ent", "d1nrb__.ent-d1tsk__.ent", "d1nrb__.ent-d2sn3__.ent", "d1nsca_.ent-d2bat__.ent", "d1nsca_.ent-d2sli_2.ent", "d1nsca_.ent-d3sil__.ent", "d1nsj__.ent-d1pii_1.ent", "d1nsj__.ent-d1pii_2.ent", "d1nsj__.ent-d1qopa_.ent", "d1nsj__.ent-d1rpxa_.ent", "d1nsj__.ent-d1thfd_.ent", "d1nsoa_.ent-d2apr__.ent", "d1nsoa_.ent-d2rspa_.ent", "d1nsoa_.ent-d3psg__.ent", "d1nsoa_.ent-d4fiv__.ent", "d1nsta_.ent-d1a7j__.ent", "d1nsta_.ent-d1aqua_.ent", "d1nsta_.ent-d1cr1a_.ent", "d1nsta_.ent-d1e69a_.ent", "d1nsta_.ent-d1f5na2.ent", "d1nsta_.ent-d1fnna2.ent", "d1nsta_.ent-d1g8ya_.ent", "d1nsta_.ent-d1gm5a3.ent", "d1nsta_.ent-d1jwyb_.ent", "d1nsta_.ent-d1lv7a_.ent", "d1nsta_.ent-d1m6na3.ent", "d1ntha_.ent-d1cz1a_.ent", "d1ntha_.ent-d1d3ga_.ent", "d1ntha_.ent-d1edg__.ent", "d1ntha_.ent-d1f8ma_.ent", "d1ntha_.ent-d1gvoa_.ent", "d1ntha_.ent-d1gw1a_.ent", "d1ntha_.ent-d1iexa1.ent", "d1ntha_.ent-d1itua_.ent", "d1ntha_.ent-d1j5sa_.ent", "d1ntha_.ent-d1k4ga_.ent", "d1ntha_.ent-d1kbla1.ent", "d1ntha_.ent-d1kwga2.ent", "d1ntha_.ent-d1m7ja3.ent", "d1ntha_.ent-d1muwa_.ent", "d1ntr__.ent-d1qo0d_.ent", "d1ntr__.ent-d1tmy__.ent", "d1nu4a_.ent-d1qm9a1.ent", "d1nu4a_.ent-d1qm9a2.ent", "d1nu4a_.ent-d1u2fa_.ent", "d1nu4a_.ent-d2msta_.ent", "d1nu4a_.ent-d2u1a__.ent", "d1nu4a_.ent-d2u2fa_.ent", "d1nuba3.ent-d1pce__.ent", "d1nuba3.ent-d1sgpi_.ent", "d1nuba3.ent-d1tbrr1.ent", "d1nuba3.ent-d1tbrr2.ent", "d1nuba3.ent-d1tgsi_.ent", "d1nuba3.ent-d4sgbi_.ent", "d1nula_.ent-d1qb7a_.ent", "d1nula_.ent-d1tc1a_.ent", "d1nuna_.ent-d1qqla_.ent", "d1nzya_.ent-d1o8ua_.ent", "d1nzya_.ent-d1tyfa_.ent", "d1o0wa2.ent-d1pda_2.ent", "d1o0wa2.ent-d1pkp_2.ent", "d1o0wa2.ent-d1qu6a1.ent", "d1o0wa2.ent-d1qu6a2.ent", "d1o0wa2.ent-d1stu__.ent", "d1o0xa_.ent-d1xgsa2.ent", "d1o0ya_.ent-d1qfea_.ent", "d1o14a_.ent-d1rkd__.ent", "d1o17a1.ent-d2tpt_1.ent", "d1o17a2.ent-d2tpt_2.ent", "d1o1va_.ent-d1qfta_.ent", "d1o1va_.ent-d1qqsa_.ent", "d1o6wa2.ent-d1pina1.ent", "d1o6za2.ent-d2cmd_2.ent", "d1o6za2.ent-d5mdha2.ent", "d1o6za2.ent-d7mdha2.ent", "d1o75a1.ent-d1dqia_.ent", "d1o75a1.ent-d1eaja_.ent", "d1o75a1.ent-d1grwa_.ent", "d1o75a1.ent-d1j0ha1.ent", "d1o75a1.ent-d1soxa1.ent", "d1o7fa1.ent-d1bjaa_.ent", "d1o7fa1.ent-d1bm9a_.ent", "d1o7fa1.ent-d1d5va_.ent", "d1o7fa1.ent-d1e17a_.ent", "d1o7fa1.ent-d1f1za1.ent", "d1o7fa1.ent-d1fc3a_.ent", "d1o7fa1.ent-d1fnna1.ent", "d1o7fa1.ent-d1fp1d1.ent", "d1o7fa1.ent-d1fp2a1.ent", "d1o7fa1.ent-d1fsha_.ent", "d1o7fa1.ent-d1fzpb_.ent", "d1o7fa1.ent-d1hks__.ent", "d1o7fa1.ent-d1hsja1.ent", "d1o7fa1.ent-d1ig6a_.ent", "d1o7fa1.ent-d1igna2.ent", "d1o7fa1.ent-d1jgsa_.ent", "d1o7fa1.ent-d1jhga_.ent", "d1o7fa1.ent-d1ka8a_.ent", "d1o7fa1.ent-d1ldja1.ent", "d1o7fa1.ent-d1md0a_.ent", "d1o7fa1.ent-d1opc__.ent", "d1o7fa1.ent-d1repc1.ent", "d1o7fa1.ent-d1repc2.ent", "d1o7fa1.ent-d1smta_.ent", "d1o7fa1.ent-d2ezl__.ent", "d1o7fa1.ent-d2foka1.ent", "d1o7fa1.ent-d2foka2.ent", "d1o7fa1.ent-d2foka3.ent", "d1o7fa1.ent-d2irfg_.ent", "d1o7fa2.ent-d1o7fa3.ent", "d1o7fa2.ent-d1rgs_1.ent", "d1o7fa2.ent-d1rgs_2.ent", "d1o7fa3.ent-d1rgs_1.ent", "d1o7fa3.ent-d1rgs_2.ent", "d1o7ja_.ent-d1wsaa_.ent", "d1o7ja_.ent-d4pgaa_.ent", "d1o7na1.ent-d1rfs__.ent", "d1o7na1.ent-d1rie__.ent", "d1o7nb_.ent-d1oaca2.ent", "d1o7nb_.ent-d1qjga_.ent", "d1o7nb_.ent-d1stfi_.ent", "d1o7nb_.ent-d1ugia_.ent", "d1o7nb_.ent-d3stda_.ent", "d1o8ua_.ent-d1tyfa_.ent", "d1o94a1.ent-d1oyb__.ent", "d1o94a1.ent-d2dora_.ent", "d1o94a2.ent-d3grs_1.ent", "d1o94a2.ent-d3grs_2.ent", "d1o97c_.ent-d1o97d1.ent", "d1o97c_.ent-d1qjca_.ent", "d1o97c_.ent-d1sur__.ent", "d1o97d1.ent-d1qjca_.ent", "d1o97d1.ent-d1sur__.ent", "d1o97d2.ent-d1poxa1.ent", "d1o97d2.ent-d1pvda1.ent", "d1o97d2.ent-d1zpda1.ent", "d1oaa__.ent-d1bgva1.ent", "d1oaa__.ent-d1qsga_.ent", "d1oaa__.ent-d2ae2a_.ent", "d1oaca2.ent-d1oaca3.ent", "d1oaca2.ent-d1stfi_.ent", "d1oaca2.ent-d1ugia_.ent", "d1oaca2.ent-d3stda_.ent", "d1ocrd_.ent-d1ocrg_.ent", "d1ocrd_.ent-d1ocri_.ent", "d1ocrd_.ent-d1ocrj_.ent", "d1ocrd_.ent-d1ocrk_.ent", "d1ocrd_.ent-d1ocrl_.ent", "d1ocrd_.ent-d1ocrm_.ent", "d1ocrf_.ent-d1pft__.ent", "d1ocrf_.ent-d1rb9__.ent", "d1ocrf_.ent-d1tfi__.ent", "d1ocrf_.ent-d1yua_1.ent", "d1ocrf_.ent-d1yua_2.ent", "d1ocrf_.ent-d1zaka2.ent", "d1ocrf_.ent-d1zin_2.ent", "d1ocrg_.ent-d1ocri_.ent", "d1ocrg_.ent-d1ocrj_.ent", "d1ocrg_.ent-d1ocrk_.ent", "d1ocrg_.ent-d1ocrl_.ent", "d1ocrg_.ent-d1ocrm_.ent", "d1ocri_.ent-d1ocrj_.ent", "d1ocri_.ent-d1ocrk_.ent", "d1ocri_.ent-d1ocrl_.ent", "d1ocri_.ent-d1ocrm_.ent", "d1ocrj_.ent-d1ocrk_.ent", "d1ocrj_.ent-d1ocrl_.ent", "d1ocrj_.ent-d1ocrm_.ent", "d1ocrk_.ent-d1ocrl_.ent", "d1ocrk_.ent-d1ocrm_.ent", "d1ocrl_.ent-d1ocrm_.ent", "d1ojt_1.ent-d1cjca1.ent", "d1ojt_1.ent-d1ebda1.ent", "d1ojt_1.ent-d3lada1.ent", "d1ojt_3.ent-d3grs_3.ent", "d1ojt_3.ent-d3lada3.ent", "d1onea1.ent-d2chr_1.ent", "d1onea1.ent-d2mnr_1.ent", "d1onea2.ent-d2chr_2.ent", "d1onea2.ent-d2mnr_2.ent", "d1opc__.ent-d1bjaa_.ent", "d1opc__.ent-d1d5va_.ent", "d1opc__.ent-d1smta_.ent", "d1opc__.ent-d2ezl__.ent", "d1opc__.ent-d2foka3.ent", "d1opd__.ent-d1pch__.ent", "d1opd__.ent-d1ptf__.ent", "d1otfa_.ent-d1otga_.ent", "d1otha1.ent-d1otha2.ent", "d1ovaa_.ent-d1qlpa_.ent", "d1oyb__.ent-d2dora_.ent", "d1p38__.ent-d1a06__.ent", "d1p38__.ent-d1apme_.ent", "d1p38__.ent-d1b6cb_.ent", "d1p38__.ent-d1blxa_.ent", "d1p38__.ent-d1cjaa_.ent", "d1p38__.ent-d1csn__.ent", "d1p38__.ent-d1f3mc_.ent", "d1p38__.ent-d1fgka_.ent", "d1p38__.ent-d1fvra_.ent", "d1p38__.ent-d1howa_.ent", "d1p38__.ent-d1ia9a_.ent", "d1p38__.ent-d1iepa_.ent", "d1p38__.ent-d1jksa_.ent", "d1p38__.ent-d1jnk__.ent", "d1p38__.ent-d1jpaa_.ent", "d1p38__.ent-d1jvpp_.ent", "d1p38__.ent-d1kwpa_.ent", "d1p38__.ent-d1lpua_.ent", "d1p38__.ent-d1lufa_.ent", "d1p38__.ent-d1m14a_.ent", "d1p38__.ent-d1phk__.ent", "d1p38__.ent-d1tkia_.ent", "d1paa__.ent-d1rmd_1.ent", "d1paa__.ent-d1tf3a1.ent", "d1paa__.ent-d1tf3a2.ent", "d1paa__.ent-d1tf3a3.ent", "d1paa__.ent-d1tf6a4.ent", "d1paa__.ent-d1ubdc3.ent", "d1paa__.ent-d1yuja_.ent", "d1paa__.ent-d1zfd__.ent", "d1paa__.ent-d2drpa1.ent", "d1paa__.ent-d2glia1.ent", "d1paa__.ent-d2glia2.ent", "d1paa__.ent-d2glia4.ent", "d1paa__.ent-d5znf__.ent", "d1pama2.ent-d1qhoa2.ent", "d1pama4.ent-d1cz1a_.ent", "d1pama4.ent-d1e43a2.ent", "d1pama4.ent-d1eh9a3.ent", "d1pama4.ent-d1iexa1.ent", "d1pama4.ent-d1j0ha3.ent", "d1pama4.ent-d1kwga2.ent", "d1pama4.ent-d1lwha2.ent", "d1pama4.ent-d7taa_2.ent", "d1pbk__.ent-d1pina2.ent", "d1pbv__.ent-d1e8xa1.ent", "d1pbv__.ent-d1elka_.ent", "d1pbv__.ent-d1h6ka2.ent", "d1pbv__.ent-d1hh8a_.ent", "d1pbv__.ent-d1hs6a1.ent", "d1pbv__.ent-d1ihga1.ent", "d1pbv__.ent-d1kpsb_.ent", "d1pbv__.ent-d1l5ja1.ent", "d1pbv__.ent-d1n4ka1.ent", "d1pbwa_.ent-d1tx4a_.ent", "d1pbwa_.ent-d1wer__.ent", "d1pce__.ent-d1sgpi_.ent", "d1pce__.ent-d1tbrr1.ent", "d1pce__.ent-d1tbrr2.ent", "d1pce__.ent-d1tgsi_.ent", "d1pce__.ent-d4sgbi_.ent", "d1pch__.ent-d1ptf__.ent", "d1pd211.ent-d1pmt_1.ent", "d1pd211.ent-d2gsq_1.ent", "d1pd211.ent-d2gsta1.ent", "d1pda_1.ent-d1pot__.ent", "d1pda_1.ent-d1sbp__.ent", "d1pda_1.ent-d1wdna_.ent", "d1pda_1.ent-d3mbp__.ent", "d1pda_1.ent-d3thia_.ent", "d1pda_2.ent-d1pkp_2.ent", "d1pda_2.ent-d1qu6a2.ent", "d1pdga_.ent-d2tgi__.ent", "d1pdkb_.ent-d1qba_2.ent", "d1pdkb_.ent-d1tf4a2.ent", "d1pdkb_.ent-d1ycsa_.ent", "d1pea__.ent-d1rpja_.ent", "d1pea__.ent-d2dri__.ent", "d1pea__.ent-d2liv__.ent", "d1pea__.ent-d8abp__.ent", "d1pex__.ent-d1qhua1.ent", "d1pft__.ent-d1qyp__.ent", "d1pft__.ent-d1rb9__.ent", "d1pft__.ent-d1tfi__.ent", "d1pft__.ent-d1yua_1.ent", "d1pft__.ent-d1yua_2.ent", "d1pft__.ent-d1zaka2.ent", "d1pft__.ent-d1zin_2.ent", "d1pgja1.ent-d1qmga1.ent", "d1pgja1.ent-d2pgd_1.ent", "d1pgs_1.ent-d1pgs_2.ent", "d1pgs_1.ent-d1phm_1.ent", "d1pgs_1.ent-d1phm_2.ent", "d1pgs_1.ent-d1ruxa1.ent", "d1pgs_1.ent-d1ruxa2.ent", "d1pgs_2.ent-d1phm_1.ent", "d1pgs_2.ent-d1phm_2.ent", "d1pgs_2.ent-d1ruxa1.ent", "d1pgs_2.ent-d1ruxa2.ent", "d1phk__.ent-d1ia9a_.ent", "d1phk__.ent-d1iepa_.ent", "d1phk__.ent-d1jpaa_.ent", "d1phk__.ent-d1lufa_.ent", "d1phm_1.ent-d1phm_2.ent", "d1phm_1.ent-d1ruxa1.ent", "d1phm_1.ent-d1ruxa2.ent", "d1phm_2.ent-d1ruxa1.ent", "d1phm_2.ent-d1ruxa2.ent", "d1phna_.ent-d1a6m__", "d1phna_.ent-d1a6m__.ent", "d1phna_.ent-d1alla_", "d1phna_.ent-d1alla_.ent", "d1phna_.ent-d1allb_", "d1phna_.ent-d1allb_.ent", "d1phna_.ent-d1ash__", "d1phna_.ent-d1ash__.ent", "d1phna_.ent-d1cg5a_", "d1phna_.ent-d1cg5a_.ent", "d1phna_.ent-d1cg5b_", "d1phna_.ent-d1cg5b_.ent", "d1phna_.ent-d1cqxa1", "d1phna_.ent-d1cqxa1.ent", "d1phna_.ent-d1ew6a_", "d1phna_.ent-d1ew6a_.ent", "d1phna_.ent-d1gcva_", "d1phna_.ent-d1gcva_.ent", "d1phna_.ent-d1gvha1", "d1phna_.ent-d1gvha1.ent", "d1phna_.ent-d1h97a_", "d1phna_.ent-d1h97a_.ent", "d1phna_.ent-d1hlb__", "d1phna_.ent-d1hlb__.ent", "d1phna_.ent-d1irda_", "d1phna_.ent-d1irda_.ent", "d1phna_.ent-d1irdb_", "d1phna_.ent-d1irdb_.ent", "d1phna_.ent-d1it2a_", "d1phna_.ent-d1it2a_.ent", "d1phna_.ent-d1itha_", "d1phna_.ent-d1itha_.ent", "d1phna_.ent-d1jl7a_", "d1phna_.ent-d1jl7a_.ent", "d1phna_.ent-d1la6a_", "d1phna_.ent-d1la6a_.ent", "d1phna_.ent-d1mba__", "d1phna_.ent-d1mba__.ent", "d1phna_.ent-d2gdm__", "d1phna_.ent-d2gdm__.ent", "d1phna_.ent-d2lhb__", "d1phna_.ent-d2lhb__.ent", "d1phna_.ent-d3sdha_", "d1phna_.ent-d3sdha_.ent", "d1pht__.ent-d1dj7b_.ent", "d1pht__.ent-d1g3sa3.ent", "d1pht__.ent-d1gcqc_.ent", "d1pht__.ent-d1i07a_.ent", "d1pht__.ent-d1jb0e_.ent", "d1pht__.ent-d1jo8a_.ent", "d1pht__.ent-d1khia1.ent", "d1pht__.ent-d1m9sa2.ent", "d1pht__.ent-d1pwt__.ent", "d1pht__.ent-d1qcfa1.ent", "d1pht__.ent-d1vie__.ent", "d1pht__.ent-d1ycsb2.ent", "d1pht__.ent-d2hsp__.ent", "d1phza1.ent-d1psda3.ent", "d1phza1.ent-d1tdj_2.ent", "d1phza1.ent-d1tdj_3.ent", "d1pii_1.ent-d1pii_2.ent", "d1pii_1.ent-d1qopa_.ent", "d1pii_1.ent-d1rpxa_.ent", "d1pii_1.ent-d1thfd_.ent", "d1pii_2.ent-d1qopa_.ent", "d1pii_2.ent-d1rpxa_.ent", "d1pii_2.ent-d1thfd_.ent", "d1pina2.ent-d3eipa_.ent", "d1pjca2.ent-d1psda2.ent", "d1pjca2.ent-d2naca2.ent", "d1pjr_1.ent-d1a7j__.ent", "d1pjr_1.ent-d1aqua_.ent", "d1pjr_1.ent-d1cr1a_.ent", "d1pjr_1.ent-d1e2ka_.ent", "d1pjr_1.ent-d1e69a_.ent", "d1pjr_1.ent-d1e79a3.ent", "d1pjr_1.ent-d1f5na2.ent", "d1pjr_1.ent-d1f9va_.ent", "d1pjr_1.ent-d1fnna2.ent", "d1pjr_1.ent-d1g8ya_.ent", "d1pjr_1.ent-d1gm5a3.ent", "d1pjr_1.ent-d1ihua1.ent", "d1pjr_1.ent-d1jwyb_.ent", "d1pjr_1.ent-d1ksfx3.ent", "d1pjr_1.ent-d1lv7a_.ent", "d1pjr_1.ent-d1m6na3.ent", "d1pjr_1.ent-d1nsta_.ent", "d1pjr_1.ent-d1pjr_2.ent", "d1pjr_1.ent-d1uaaa1.ent", "d1pjr_2.ent-d1a7j__.ent", "d1pjr_2.ent-d1aqua_.ent", "d1pjr_2.ent-d1cr1a_.ent", "d1pjr_2.ent-d1e69a_.ent", "d1pjr_2.ent-d1e79a3.ent", "d1pjr_2.ent-d1f5na2.ent", "d1pjr_2.ent-d1fnna2.ent", "d1pjr_2.ent-d1g8ya_.ent", "d1pjr_2.ent-d1gm5a3.ent", "d1pjr_2.ent-d1ihua1.ent", "d1pjr_2.ent-d1jwyb_.ent", "d1pjr_2.ent-d1ksfx3.ent", "d1pjr_2.ent-d1lv7a_.ent", "d1pjr_2.ent-d1m6na3.ent", "d1pjr_2.ent-d1nsta_.ent", "d1pjr_2.ent-d1uaaa1.ent", "d1pkp_2.ent-d1qu6a1.ent", "d1pkp_2.ent-d1qu6a2.ent", "d1pkp_2.ent-d1stu__.ent", "d1plq_1.ent-d1plq_2.ent", "d1plq_1.ent-d2pola1.ent", "d1plq_1.ent-d2pola2.ent", "d1plq_1.ent-d2pola3.ent", "d1plq_2.ent-d2pola1.ent", "d1plq_2.ent-d2pola2.ent", "d1plq_2.ent-d2pola3.ent", "d1pls__.ent-d1qqga1.ent", "d1pls__.ent-d1qqga2.ent", "d1pls__.ent-d1shca_.ent", "d1pma1_.ent-d1iruk_.ent", "d1pma1_.ent-d1jgta2.ent", "d1pma1_.ent-d1rypk_.ent", "d1pmaa_.ent-d1iru1_.ent", "d1pmaa_.ent-d1iru2_.ent", "d1pmaa_.ent-d1iruk_.ent", "d1pmaa_.ent-d1jgta2.ent", "d1pmaa_.ent-d1pma1_.ent", "d1pmaa_.ent-d1ryph_.ent", "d1pmaa_.ent-d1rypj_.ent", "d1pmaa_.ent-d1rypk_.ent", "d1pmaa_.ent-d1rypl_.ent", "d1pmi__.ent-d1wapa_.ent", "d1pmi__.ent-d2arca_.ent", "d1pmi__.ent-d2phla1.ent", "d1pmi__.ent-d2phla2.ent", "d1pmla_.ent-d2hpqp_.ent", "d1pmla_.ent-d5hpga_.ent", "d1pmt_1.ent-d2gsq_1.ent", "d1pmt_1.ent-d2gsta1.ent", "d1pne__.ent-d1ypra_.ent", "d1pne__.ent-d3pyp__.ent", "d1poia_.ent-d1poib_.ent", "d1pot__.ent-d1sbp__.ent", "d1pot__.ent-d1wdna_.ent", "d1pot__.ent-d3mbp__.ent", "d1pot__.ent-d3thia_.ent", "d1pov0_.ent-d1aym1_.ent", "d1pov0_.ent-d1aym2_.ent", "d1pov0_.ent-d1b35a_.ent", "d1pov0_.ent-d1b35b_.ent", "d1pov0_.ent-d1b35c_.ent", "d1pov0_.ent-d1bev1_.ent", "d1pov0_.ent-d1bev3_.ent", "d1pov0_.ent-d1d4m1_.ent", "d1pov0_.ent-d1k5ma_.ent", "d1pov0_.ent-d1pvc1_.ent", "d1pov0_.ent-d1tmf1_.ent", "d1pov0_.ent-d1vpsa_.ent", "d1pov0_.ent-d2mev1_.ent", "d1pov0_.ent-d2mev2_.ent", "d1poxa1.ent-d1pvda1.ent", "d1poxa1.ent-d1zpda1.ent", "d1poxa2.ent-d1poxa3.ent", "d1poxa2.ent-d1pvda2.ent", "d1poxa2.ent-d1pvda3.ent", "d1poxa2.ent-d1zpda2.ent", "d1poxa2.ent-d1zpda3.ent", "d1poxa3.ent-d1pvda2.ent", "d1poxa3.ent-d1pvda3.ent", "d1poxa3.ent-d1zpda2.ent", "d1poxa3.ent-d1zpda3.ent", "d1ppn__.ent-d1qmya_.ent", "d1ppn__.ent-d1uch__.ent", "d1ppn__.ent-d2act__.ent", "d1ppn__.ent-d2cb5a_.ent", "d1ppn__.ent-d3gcb__.ent", "d1ppn__.ent-d7pcka_.ent", "d1prea1.ent-d1prtb2.ent", "d1prea1.ent-d1qdda_.ent", "d1prea1.ent-d1tsg__.ent", "d1prta_.ent-d1qs1a1.ent", "d1prta_.ent-d1qs1a2.ent", "d1prtb1.ent-d1prtd_.ent", "d1prtb1.ent-d1prtf_.ent", "d1prtb1.ent-d1tiid_.ent", "d1prtb1.ent-d3chbd_.ent", "d1prtb1.ent-d3seb_1.ent", "d1prtb1.ent-d3tss_1.ent", "d1prtb2.ent-d1qdda_.ent", "d1prtb2.ent-d1tsg__.ent", "d1prtd_.ent-d1prtf_.ent", "d1prtd_.ent-d1tiid_.ent", "d1prtd_.ent-d3chbd_.ent", "d1prtd_.ent-d3seb_1.ent", "d1prtd_.ent-d3tss_1.ent", "d1prtf_.ent-d1tiid_.ent", "d1prtf_.ent-d3chbd_.ent", "d1prtf_.ent-d3seb_1.ent", "d1prtf_.ent-d3tss_1.ent", "d1ps1a_.ent-d1uby__.ent", "d1ps1a_.ent-d5eau_2.ent", "d1psda2.ent-d2naca2.ent", "d1psda3.ent-d1tdj_2.ent", "d1psda3.ent-d1tdj_3.ent", "d1psra_.ent-d1qasa1.ent", "d1psra_.ent-d1rec__.ent", "d1psra_.ent-d1sra__.ent", "d1psra_.ent-d2cbla1.ent", "d1psra_.ent-d2pvba_.ent", "d1psra_.ent-d2sas__.ent", "d1psra_.ent-d2scpa_.ent", "d1psza_.ent-d1toaa_.ent", "d1put__.ent-d1qlab2.ent", "d1put__.ent-d2pia_3.ent", "d1pvc1_.ent-d1a6ca1.ent", "d1pvc1_.ent-d1a6ca2.ent", "d1pvc1_.ent-d1a6ca3.ent", "d1pvc1_.ent-d1aym2_.ent", "d1pvc1_.ent-d1b35a_.ent", "d1pvc1_.ent-d1b35b_.ent", "d1pvc1_.ent-d1bev1_.ent", "d1pvc1_.ent-d1bev3_.ent", "d1pvc1_.ent-d1bmv1_.ent", "d1pvc1_.ent-d1c8na_.ent", "d1pvc1_.ent-d1cwpa_.ent", "d1pvc1_.ent-d1ddla_.ent", "d1pvc1_.ent-d1f15a_.ent", "d1pvc1_.ent-d1qqp1_.ent", "d1pvc1_.ent-d1qqp2_.ent", "d1pvc1_.ent-d1qqp3_.ent", "d1pvc1_.ent-d1tmf1_.ent", "d1pvc1_.ent-d2bpa2_.ent", "d1pvc1_.ent-d2mev1_.ent", "d1pvc1_.ent-d2mev2_.ent", "d1pvc1_.ent-d2stv__.ent", "d1pvda1.ent-d1zpda1.ent", "d1pvda2.ent-d1pvda3.ent", "d1pvda2.ent-d1zpda2.ent", "d1pvda2.ent-d1zpda3.ent", "d1pvda3.ent-d1zpda2.ent", "d1pvda3.ent-d1zpda3.ent", "d1pwt__.ent-d1qcfa1.ent", "d1pwt__.ent-d1ycsb2.ent", "d1pwt__.ent-d2hsp__.ent", "d1pyia1.ent-d1zmec1.ent", "d1pyia1.ent-d2alca_.ent", "d1qada_.ent-d2abl_2.ent", "d1qada_.ent-d2cbla3.ent", "d1qada_.ent-d2plda_.ent", "d1qada_.ent-d2shpa3.ent", "d1qama_.ent-d1fp1d2.ent", "d1qama_.ent-d1i1na_.ent", "d1qama_.ent-d1jg1a_.ent", "d1qasa1.ent-d1rec__.ent", "d1qasa1.ent-d1sra__.ent", "d1qasa1.ent-d2cbla1.ent", "d1qasa1.ent-d2pvba_.ent", "d1qasa1.ent-d2sas__.ent", "d1qasa1.ent-d2scpa_.ent", "d1qasa2.ent-d1rlw__.ent", "d1qasa2.ent-d1rsy__.ent", "d1qasa2.ent-d3rpba_.ent", "d1qasa3.ent-d2plc__.ent", "d1qasa3.ent-d2ptd__.ent", "d1qaua_.ent-d1qava_.ent", "d1qaua_.ent-d1qlca_.ent", "d1qava_.ent-d1qlca_.ent", "d1qaza_.ent-d2sqca1.ent", "d1qaza_.ent-d2sqca2.ent", "d1qb7a_.ent-d1tc1a_.ent", "d1qba_1.ent-d1eut_1.ent", "d1qba_1.ent-d1qfha1.ent", "d1qba_2.ent-d1tf4a2.ent", "d1qba_2.ent-d1ycsa_.ent", "d1qba_3.ent-d1b9za2.ent", "d1qba_3.ent-d1cz1a_.ent", "d1qba_3.ent-d1e43a2.ent", "d1qba_3.ent-d1eh9a3.ent", "d1qba_3.ent-d1iexa1.ent", "d1qba_3.ent-d1j0ha3.ent", "d1qba_3.ent-d1ji1a3.ent", "d1qba_3.ent-d1kwga2.ent", "d1qba_3.ent-d1lwha2.ent", "d1qba_3.ent-d1pama4.ent", "d1qba_3.ent-d1qhoa4.ent", "d1qba_3.ent-d7taa_2.ent", "d1qcfa1.ent-d1ycsb2.ent", "d1qcfa1.ent-d2hsp__.ent", "d1qcqa_.ent-d2aak__.ent", "d1qcqa_.ent-d2ucz__.ent", "d1qcxa_.ent-d1qjva_.ent", "d1qcxa_.ent-d1qq1a_.ent", "d1qcxa_.ent-d1rmg__.ent", "d1qd1a1.ent-d1b3ta_.ent", "d1qd1a1.ent-d1dj0a2.ent", "d1qd1a1.ent-d1dqaa1.ent", "d1qd1a1.ent-d1ekra_.ent", "d1qd1a1.ent-d1eqoa_.ent", "d1qd1a1.ent-d1f3va_.ent", "d1qd1a1.ent-d1ftra1.ent", "d1qd1a1.ent-d1ftra2.ent", "d1qd1a1.ent-d1gpja3.ent", "d1qd1a1.ent-d1h72c2.ent", "d1qd1a1.ent-d1hlwa_.ent", "d1qd1a1.ent-d1jnrb_.ent", "d1qd1a1.ent-d1kvka2.ent", "d1qd1a1.ent-d1qd1a2.ent", "d1qd1a1.ent-d1regx_.ent", "d1qd1a2.ent-d1dqaa1.ent", "d1qd1a2.ent-d1h72c2.ent", "d1qd1a2.ent-d1regx_.ent", "d1qdda_.ent-d1b08a1.ent", "d1qdda_.ent-d1b6e__.ent", "d1qdda_.ent-d1byfa_.ent", "d1qdda_.ent-d1cwva5.ent", "d1qdda_.ent-d1dv8a_.ent", "d1qdda_.ent-d1e87a_.ent", "d1qdda_.ent-d1egia_.ent", "d1qdda_.ent-d1f00i3.ent", "d1qdda_.ent-d1fvua_.ent", "d1qdda_.ent-d1fvub_.ent", "d1qdda_.ent-d1g1ta1.ent", "d1qdda_.ent-d1h8ua_.ent", "d1qdda_.ent-d1hq8a_.ent", "d1qdda_.ent-d1jwia_.ent", "d1qdda_.ent-d1jwib_.ent", "d1qdda_.ent-d1k9ja_.ent", "d1qdda_.ent-d1kg0c_.ent", "d1qdda_.ent-d1li1a1.ent", "d1qdda_.ent-d1li1a2.ent", "d1qdda_.ent-d1prtb2.ent", "d1qdda_.ent-d1qo3c_.ent", "d1qdda_.ent-d1tn3__.ent", "d1qdda_.ent-d1tsg__.ent", "d1qe0a1.ent-d1qf6a1.ent", "d1qe0a2.ent-d1qf6a4.ent", "d1qe0a2.ent-d1seta2.ent", "d1qe3a_.ent-d1bu8a2.ent", "d1qe3a_.ent-d1cpy__.ent", "d1qe3a_.ent-d1cr6a2.ent", "d1qe3a_.ent-d1cvl__.ent", "d1qe3a_.ent-d1hlga_.ent", "d1qe3a_.ent-d1ivya_.ent", "d1qe3a_.ent-d1iz7a_.ent", "d1qe3a_.ent-d1jjia_.ent", "d1qe3a_.ent-d1jkma_.ent", "d1qe3a_.ent-d1ju3a2.ent", "d1qe3a_.ent-d1ku0a_.ent", "d1qe3a_.ent-d1l7aa_.ent", "d1qe3a_.ent-d1lnsa3.ent", "d1qe3a_.ent-d1lzla_.ent", "d1qe3a_.ent-d1qlwa_.ent", "d1qe3a_.ent-d1qo7a_.ent", "d1qe3a_.ent-d1qtra_.ent", "d1qe3a_.ent-d1tca__.ent", "d1qf5a_.ent-d1a7j__.ent", "d1qf5a_.ent-d1aqua_.ent", "d1qf5a_.ent-d1bg2__.ent", "d1qf5a_.ent-d1c4oa1.ent", "d1qf5a_.ent-d1cr1a_.ent", "d1qf5a_.ent-d1e2ka_.ent", "d1qf5a_.ent-d1e69a_.ent", "d1qf5a_.ent-d1e79a3.ent", "d1qf5a_.ent-d1e9ra_.ent", "d1qf5a_.ent-d1f5na2.ent", "d1qf5a_.ent-d1f9va_.ent", "d1qf5a_.ent-d1fmja_.ent", "d1qf5a_.ent-d1fnna2.ent", "d1qf5a_.ent-d1g41a_.ent", "d1qf5a_.ent-d1g8pa_.ent", "d1qf5a_.ent-d1g8ya_.ent", "d1qf5a_.ent-d1gm5a3.ent", "d1qf5a_.ent-d1i6ia_.ent", "d1qf5a_.ent-d1ihua1.ent", "d1qf5a_.ent-d1ii6a_.ent", "d1qf5a_.ent-d1iwea_.ent", "d1qf5a_.ent-d1jwyb_.ent", "d1qf5a_.ent-d1ksfx3.ent", "d1qf5a_.ent-d1lv7a_.ent", "d1qf5a_.ent-d1m6na3.ent", "d1qf5a_.ent-d1n0ua2.ent", "d1qf5a_.ent-d1nsta_.ent", "d1qf5a_.ent-d1pjr_1.ent", "d1qf5a_.ent-d1pjr_2.ent", "d1qf5a_.ent-d1uaaa1.ent", "d1qf5a_.ent-d1uaaa2.ent", "d1qf5a_.ent-d2ncda_.ent", "d1qf6a4.ent-d1seta2.ent", "d1qfha1.ent-d1eut_1.ent", "d1qfha2.ent-d1eut_1.ent", "d1qfha2.ent-d1my7a_.ent", "d1qfha2.ent-d1qba_1.ent", "d1qfha2.ent-d1qfha1.ent", "d1qfja1.ent-d1que_1.ent", "d1qfja1.ent-d2cnd_1.ent", "d1qfja1.ent-d2pia_1.ent", "d1qfja2.ent-d1que_2.ent", "d1qfja2.ent-d2cnd_2.ent", "d1qfja2.ent-d2pia_2.ent", "d1qfoa_.ent-d1akjd_.ent", "d1qfoa_.ent-d1b88a_.ent", "d1qfoa_.ent-d1bec_1.ent", "d1qfoa_.ent-d1c5ch1.ent", "d1qfoa_.ent-d1dlfl_.ent", "d1qfoa_.ent-d1h5ba_.ent", "d1qfoa_.ent-d1nfdb1.ent", "d1qfoa_.ent-d2rhe__.ent", "d1qfta_.ent-d1qqsa_.ent", "d1qfxa_.ent-d3pgm__.ent", "d1qg3a2.ent-d1cd9b2.ent", "d1qg3a2.ent-d1cfb_1.ent", "d1qg3a2.ent-d1egja_.ent", "d1qg3a2.ent-d1f6fb1.ent", "d1qg3a2.ent-d1f6fb2.ent", "d1qg3a2.ent-d1fyhb1.ent", "d1qg3a2.ent-d1i1ra1.ent", "d1qg3a2.ent-d1lqsr1.ent", "d1qg3a2.ent-d1n26a2.ent", "d1qg3a2.ent-d2hft_1.ent", "d1qg3a2.ent-d2hft_2.ent", "d1qg7a_.ent-d1tvxa_.ent", "d1qg7a_.ent-d2hcc__.ent", "d1qg7a_.ent-d3il8__.ent", "d1qgba1.ent-d1qgba2.ent", "d1qgba1.ent-d1tpg_2.ent", "d1qgba2.ent-d1tpg_2.ent", "d1qgha_.ent-d1rcd__.ent", "d1qgia_.ent-d1qsaa2.ent", "d1qgia_.ent-d1qusa_.ent", "d1qgia_.ent-d217l__.ent", "d1qgia_.ent-d2eql__.ent", "d1qgia_.ent-d3lzt__.ent", "d1qgoa_.ent-d1toaa_.ent", "d1qh5a_.ent-d1smla_.ent", "d1qhba_.ent-d1qi9a_.ent", "d1qhba_.ent-d1vns__.ent", "d1qhda2.ent-d2viua_.ent", "d1qhoa3.ent-d1uok_1.ent", "d1qhoa3.ent-d7taa_1.ent", "d1qhoa4.ent-d1cz1a_.ent", "d1qhoa4.ent-d1e43a2.ent", "d1qhoa4.ent-d1eh9a3.ent", "d1qhoa4.ent-d1iexa1.ent", "d1qhoa4.ent-d1j0ha3.ent", "d1qhoa4.ent-d1kwga2.ent", "d1qhoa4.ent-d1lwha2.ent", "d1qhoa4.ent-d1pama4.ent", "d1qhoa4.ent-d7taa_2.ent", "d1qi9a_.ent-d1vns__.ent", "d1qipa_.ent-d1qtoa_.ent", "d1qisa_.ent-d1b9ha_.ent", "d1qisa_.ent-d1bs0a_.ent", "d1qisa_.ent-d1c7na_.ent", "d1qisa_.ent-d1e5ea_.ent", "d1qisa_.ent-d1gdea_.ent", "d1qisa_.ent-d1j32a_.ent", "d1qisa_.ent-d1n8pa_.ent", "d1qisa_.ent-d2ay1a_.ent", "d1qj4a_.ent-d1qlwa_.ent", "d1qj4a_.ent-d1qo7a_.ent", "d1qj4a_.ent-d1tca__.ent", "d1qj4a_.ent-d1thta_.ent", "d1qj4a_.ent-d3tgl__.ent", "d1qj5a_.ent-d1ajsa_.ent", "d1qj5a_.ent-d1b9ha_.ent", "d1qj5a_.ent-d1bs0a_.ent", "d1qj5a_.ent-d1c7na_.ent", "d1qj5a_.ent-d1e5ea_.ent", "d1qj5a_.ent-d1gdea_.ent", "d1qj5a_.ent-d1j32a_.ent", "d1qj5a_.ent-d1jf9a_.ent", "d1qj5a_.ent-d1kl1a_.ent", "d1qj5a_.ent-d1m7ya_.ent", "d1qj5a_.ent-d1n8pa_.ent", "d1qj5a_.ent-d1qisa_.ent", "d1qj5a_.ent-d1tpla_.ent", "d1qj5a_.ent-d1yaaa_.ent", "d1qj5a_.ent-d2ay1a_.ent", "d1qj5a_.ent-d2gsaa_.ent", "d1qj5a_.ent-d2oata_.ent", "d1qj5a_.ent-d3tata_.ent", "d1qj5a_.ent-d7aata_.ent", "d1qj8a_.ent-d1qjpa_.ent", "d1qj8a_.ent-d2mpra_.ent", "d1qj8a_.ent-d2por__.ent", "d1qjba_.ent-d1e8xa1.ent", "d1qjba_.ent-d1elka_.ent", "d1qjba_.ent-d1h6ka2.ent", "d1qjba_.ent-d1hh8a_.ent", "d1qjba_.ent-d1hs6a1.ent", "d1qjba_.ent-d1ihga1.ent", "d1qjba_.ent-d1keya_.ent", "d1qjba_.ent-d1kpsb_.ent", "d1qjba_.ent-d1l5ja1.ent", "d1qjba_.ent-d1n4ka1.ent", "d1qjba_.ent-d1pbv__.ent", "d1qjca_.ent-d1sur__.ent", "d1qjga_.ent-d3stda_.ent", "d1qjka_.ent-d4mt2__.ent", "d1qjpa_.ent-d2mpra_.ent", "d1qjpa_.ent-d2por__.ent", "d1qjva_.ent-d1qq1a_.ent", "d1qjva_.ent-d1rmg__.ent", "d1qk6a_.ent-d1qk7a_.ent", "d1qk6a_.ent-d1vtx__.ent", "d1qk7a_.ent-d1vtx__.ent", "d1qksa1.ent-d1co6a_.ent", "d1qksa1.ent-d1cot__.ent", "d1qksa1.ent-d1cxc__.ent", "d1qksa1.ent-d1dw0a_.ent", "d1qksa1.ent-d1etpa2.ent", "d1qksa1.ent-d1gu2a_.ent", "d1qksa1.ent-d1hroa_.ent", "d1qksa1.ent-d1kb0a1.ent", "d1qksa1.ent-d1kv9a1.ent", "d1qksa1.ent-d1nira1.ent", "d1qksa1.ent-d1ql3a_.ent", "d1qksa1.ent-d1qn2a_.ent", "d1qksa1.ent-d1ycc__.ent", "d1qksa1.ent-d3c2c__.ent", "d1qkya_.ent-d1sco__.ent", "d1qkya_.ent-d1scy__.ent", "d1qkya_.ent-d1sis__.ent", "d1qkya_.ent-d1tsk__.ent", "d1qkya_.ent-d2sn3__.ent", "d1ql3a_.ent-d1etpa2.ent", "d1ql3a_.ent-d1kb0a1.ent", "d1ql3a_.ent-d1qn2a_.ent", "d1qlaa1.ent-d1quua1.ent", "d1qlaa1.ent-d1quua2.ent", "d1qlaa1.ent-d2spca_.ent", "d1qlaa2.ent-d1chua2.ent", "d1qlaa2.ent-d1cjca1.ent", "d1qlaa2.ent-d1ebda1.ent", "d1qlaa2.ent-d1feca1.ent", "d1qlaa2.ent-d1h6va1.ent", "d1qlaa2.ent-d1jeha1.ent", "d1qlaa2.ent-d1k0ia1.ent", "d1qlaa2.ent-d1kf6a2.ent", "d1qlaa2.ent-d1kssa2.ent", "d1qlaa2.ent-d1l9ea1.ent", "d1qlaa2.ent-d1mo9a1.ent", "d1qlaa2.ent-d1neka2.ent", "d1qlaa2.ent-d1ojt_1.ent", "d1qlaa2.ent-d1qo8a2.ent", "d1qlaa2.ent-d3lada1.ent", "d1qlaa3.ent-d1qo8a3.ent", "d1qlab1.ent-d2gdm__", "d1qlab1.ent-d2gdm__.ent", "d1qlab2.ent-d1ayfa_.ent", "d1qlab2.ent-d1bmlc3.ent", "d1qlab2.ent-d1c9fa_.ent", "d1qlab2.ent-d1czpa_.ent", "d1qlab2.ent-d1f52a1.ent", "d1qlab2.ent-d1fm0d_.ent", "d1qlab2.ent-d1h4ra3.ent", "d1qlab2.ent-d1h8ca_.ent", "d1qlab2.ent-d1i42a_.ent", "d1qlab2.ent-d1ip9a_.ent", "d1qlab2.ent-d1k8rb_.ent", "d1qlab2.ent-d1l5pa_.ent", "d1qlab2.ent-d1l7ya_.ent", "d1qlab2.ent-d1lfda_.ent", "d1qlab2.ent-d2pia_3.ent", "d1qlab2.ent-d3tss_2.ent", "d1qlwa_.ent-d1cvl__.ent", "d1qlwa_.ent-d1iz7a_.ent", "d1qlwa_.ent-d1jjia_.ent", "d1qlwa_.ent-d1lzla_.ent", "d1qlwa_.ent-d1qo7a_.ent", "d1qlwa_.ent-d1qtra_.ent", "d1qlwa_.ent-d1tca__.ent", "d1qlwa_.ent-d1thta_.ent", "d1qlwa_.ent-d3tgl__.ent", "d1qm9a1.ent-d1qm9a2.ent", "d1qm9a1.ent-d1u2fa_.ent", "d1qm9a1.ent-d2msta_.ent", "d1qm9a1.ent-d2u1a__.ent", "d1qm9a1.ent-d2u2fa_.ent", "d1qm9a2.ent-d1u2fa_.ent", "d1qm9a2.ent-d2msta_.ent", "d1qm9a2.ent-d2u1a__.ent", "d1qm9a2.ent-d2u2fa_.ent", "d1qmea4.ent-d4blma_.ent", "d1qmga1.ent-d2pgd_1.ent", "d1qmga2.ent-d1bg6_2.ent", "d1qmga2.ent-d1c1da1.ent", "d1qmga2.ent-d1cf2o1.ent", "d1qmga2.ent-d1dlja2.ent", "d1qmga2.ent-d1dpga1.ent", "d1qmga2.ent-d1dssg1.ent", "d1qmga2.ent-d1e5qa1.ent", "d1qmga2.ent-d1f0ya2.ent", "d1qmga2.ent-d1hdoa_.ent", "d1qmga2.ent-d1jaya_.ent", "d1qmga2.ent-d1lc0a1.ent", "d1qmga2.ent-d1lu9a1.ent", "d1qmga2.ent-d2naca1.ent", "d1qmga2.ent-d2pgd_2.ent", "d1qmha1.ent-d1aba__.ent", "d1qmha1.ent-d1aqwa2.ent", "d1qmha1.ent-d1e6ba2.ent", "d1qmha1.ent-d1fhe_2.ent", "d1qmha1.ent-d1iloa_.ent", "d1qmha1.ent-d1k0ma2.ent", "d1qmha1.ent-d1k3ya2.ent", "d1qmha2.ent-d1tig__.ent", "d1qmya_.ent-d1uch__.ent", "d1qmya_.ent-d2act__.ent", "d1qmya_.ent-d2cb5a_.ent", "d1qmya_.ent-d3gcb__.ent", "d1qmya_.ent-d7pcka_.ent", "d1qn2a_.ent-d1etpa2.ent", "d1qn2a_.ent-d1kb0a1.ent", "d1qnta2.ent-d1sfe_2.ent", "d1qo0d_.ent-d1cf9a1.ent", "d1qo0d_.ent-d1e5da1.ent", "d1qo0d_.ent-d1euca2.ent", "d1qo0d_.ent-d1f4pa_.ent", "d1qo0d_.ent-d1f8ya_.ent", "d1qo0d_.ent-d1fuea_.ent", "d1qo0d_.ent-d1h05a_.ent", "d1qo0d_.ent-d1tmy__.ent", "d1qo0d_.ent-d2naca2.ent", "d1qo0d_.ent-d7reqb2.ent", "d1qo3c_.ent-d1b08a1.ent", "d1qo3c_.ent-d1b6e__.ent", "d1qo3c_.ent-d1byfa_.ent", "d1qo3c_.ent-d1cwva5.ent", "d1qo3c_.ent-d1e87a_.ent", "d1qo3c_.ent-d1f00i3.ent", "d1qo3c_.ent-d1fvub_.ent", "d1qo3c_.ent-d1g1ta1.ent", "d1qo3c_.ent-d1h8ua_.ent", "d1qo3c_.ent-d1hq8a_.ent", "d1qo3c_.ent-d1jwia_.ent", "d1qo3c_.ent-d1jwib_.ent", "d1qo3c_.ent-d1li1a1.ent", "d1qo3c_.ent-d1li1a2.ent", "d1qo3c_.ent-d1prtb2.ent", "d1qo3c_.ent-d1tsg__.ent", "d1qo7a_.ent-d1bu8a2.ent", "d1qo7a_.ent-d1cr6a2.ent", "d1qo7a_.ent-d1cvl__.ent", "d1qo7a_.ent-d1hlga_.ent", "d1qo7a_.ent-d1iz7a_.ent", "d1qo7a_.ent-d1jjia_.ent", "d1qo7a_.ent-d1jkma_.ent", "d1qo7a_.ent-d1ju3a2.ent", "d1qo7a_.ent-d1l7aa_.ent", "d1qo7a_.ent-d1lzla_.ent", "d1qo7a_.ent-d1qlwa_.ent", "d1qo7a_.ent-d1qtra_.ent", "d1qo7a_.ent-d1tca__.ent", "d1qo7a_.ent-d1thta_.ent", "d1qo7a_.ent-d3tgl__.ent", "d1qo8a1.ent-d1wad__.ent", "d1qo8a1.ent-d2ctha_.ent", "d1qo8a1.ent-d2cy3__.ent", "d1qo8a1.ent-d3caoa_.ent", "d1qo8a1.ent-d3cyr__.ent", "d1qo8a2.ent-d1chua2.ent", "d1qo8a2.ent-d1cjca1.ent", "d1qo8a2.ent-d1ebda1.ent", "d1qo8a2.ent-d1feca1.ent", "d1qo8a2.ent-d1h6va1.ent", "d1qo8a2.ent-d1jeha1.ent", "d1qo8a2.ent-d1k0ia1.ent", "d1qo8a2.ent-d1kf6a2.ent", "d1qo8a2.ent-d1l9ea1.ent", "d1qo8a2.ent-d1mo9a1.ent", "d1qo8a2.ent-d1ojt_1.ent", "d1qo8a2.ent-d3lada1.ent", "d1qopa_.ent-d1rpxa_.ent", "d1qopa_.ent-d1thfd_.ent", "d1qopb_.ent-d1tdj_1.ent", "d1qovl_.ent-d1qovm_.ent", "d1qq1a_.ent-d1rmg__.ent", "d1qq4a_.ent-d1svpa_.ent", "d1qq4a_.ent-d2hrva_.ent", "d1qq5a_.ent-d1zrn__.ent", "d1qqea_.ent-d1e8xa1.ent", "d1qqea_.ent-d1elka_.ent", "d1qqea_.ent-d1h6ka1.ent", "d1qqea_.ent-d1h6ka2.ent", "d1qqea_.ent-d1h6ka3.ent", "d1qqea_.ent-d1hf8a_.ent", "d1qqea_.ent-d1hh8a_.ent", "d1qqea_.ent-d1hs6a1.ent", "d1qqea_.ent-d1ihga1.ent", "d1qqea_.ent-d1keya_.ent", "d1qqea_.ent-d1kpsb_.ent", "d1qqea_.ent-d1l5ja1.ent", "d1qqea_.ent-d1lrv__.ent", "d1qqea_.ent-d1n4ka1.ent", "d1qqea_.ent-d1pbv__.ent", "d1qqea_.ent-d1qjba_.ent", "d1qqga1.ent-d1qqga2.ent", "d1qqga1.ent-d1shca_.ent", "d1qqga2.ent-d1shca_.ent", "d1qqp1_.ent-d1a6ca1.ent", "d1qqp1_.ent-d1a6ca2.ent", "d1qqp1_.ent-d1a6ca3.ent", "d1qqp1_.ent-d1bmv1_.ent", "d1qqp1_.ent-d1cwpa_.ent", "d1qqp1_.ent-d1f15a_.ent", "d1qqp1_.ent-d2bpa2_.ent", "d1qqp1_.ent-d2stv__.ent", "d1qqp2_.ent-d1a6ca1.ent", "d1qqp2_.ent-d1a6ca2.ent", "d1qqp2_.ent-d1a6ca3.ent", "d1qqp2_.ent-d1bmv1_.ent", "d1qqp2_.ent-d1c8na_.ent", "d1qqp2_.ent-d1cwpa_.ent", "d1qqp2_.ent-d1ddla_.ent", "d1qqp2_.ent-d1f15a_.ent", "d1qqp2_.ent-d1qqp1_.ent", "d1qqp2_.ent-d2bpa2_.ent", "d1qqp2_.ent-d2stv__.ent", "d1qqp3_.ent-d1a6ca1.ent", "d1qqp3_.ent-d1a6ca2.ent", "d1qqp3_.ent-d1a6ca3.ent", "d1qqp3_.ent-d1bmv1_.ent", "d1qqp3_.ent-d1c8na_.ent", "d1qqp3_.ent-d1cwpa_.ent", "d1qqp3_.ent-d1ddla_.ent", "d1qqp3_.ent-d1f15a_.ent", "d1qqp3_.ent-d1qqp1_.ent", "d1qqp3_.ent-d1qqp2_.ent", "d1qqp3_.ent-d2bpa2_.ent", "d1qqp3_.ent-d2stv__.ent", "d1qqra_.ent-d1ayfa_.ent", "d1qqra_.ent-d1bmlc3.ent", "d1qqra_.ent-d1c9fa_.ent", "d1qqra_.ent-d1czpa_.ent", "d1qqra_.ent-d1d4ba_.ent", "d1qqra_.ent-d1f52a1.ent", "d1qqra_.ent-d1feha2.ent", "d1qqra_.ent-d1fm0d_.ent", "d1qqra_.ent-d1gnua_.ent", "d1qqra_.ent-d1h4ra3.ent", "d1qqra_.ent-d1h8ca_.ent", "d1qqra_.ent-d1i42a_.ent", "d1qqra_.ent-d1ip9a_.ent", "d1qqra_.ent-d1k8rb_.ent", "d1qqra_.ent-d1l4db_.ent", "d1qqra_.ent-d1l5pa_.ent", "d1qqra_.ent-d1l7ya_.ent", "d1qqra_.ent-d1lfda_.ent", "d1qqra_.ent-d1lm8b_.ent", "d1qqra_.ent-d1qlab2.ent", "d1qqra_.ent-d2sak__.ent", "d1qqra_.ent-d3seb_2.ent", "d1qqra_.ent-d3tss_2.ent", "d1qr0a1.ent-d1qr0a2.ent", "d1qr2a_.ent-d1rcf__.ent", "d1qr2a_.ent-d2fcr__.ent", "d1qr2a_.ent-d5nul__.ent", "d1qrea_.ent-d1xat__.ent", "d1qrea_.ent-d3tdt__.ent", "d1qrjb1.ent-d2eiaa1.ent", "d1qrra_.ent-d1bdb__.ent", "d1qrra_.ent-d1bg6_2.ent", "d1qrra_.ent-d1bgva1.ent", "d1qrra_.ent-d1c1da1.ent", "d1qrra_.ent-d1cf2o1.ent", "d1qrra_.ent-d1dlja2.ent", "d1qrra_.ent-d1dpga1.ent", "d1qrra_.ent-d1dssg1.ent", "d1qrra_.ent-d1e5qa1.ent", "d1qrra_.ent-d1e6ua_.ent", "d1qrra_.ent-d1e7wa_.ent", "d1qrra_.ent-d1ek6a_.ent", "d1qrra_.ent-d1eno__.ent", "d1qrra_.ent-d1eny__.ent", "d1qrra_.ent-d1f0ya2.ent", "d1qrra_.ent-d1fds__.ent", "d1qrra_.ent-d1g0oa_.ent", "d1qrra_.ent-d1gcoa_.ent", "d1qrra_.ent-d1gr0a1.ent", "d1qrra_.ent-d1h5qa_.ent", "d1qrra_.ent-d1hdoa_.ent", "d1qrra_.ent-d1hdr__.ent", "d1qrra_.ent-d1hwxa1.ent", "d1qrra_.ent-d1hxha_.ent", "d1qrra_.ent-d1ja9a_.ent", "d1qrra_.ent-d1jaya_.ent", "d1qrra_.ent-d1k6xa_.ent", "d1qrra_.ent-d1kepa_.ent", "d1qrra_.ent-d1kewa_.ent", "d1qrra_.ent-d1lc0a1.ent", "d1qrra_.ent-d1llqa1.ent", "d1qrra_.ent-d1lu9a1.ent", "d1qrra_.ent-d1n2sa_.ent", "d1qrra_.ent-d1n5da_.ent", "d1qrra_.ent-d1n7ha_.ent", "d1qrra_.ent-d1oaa__.ent", "d1qrra_.ent-d1qmga2.ent", "d1qrra_.ent-d1qsga_.ent", "d1qrra_.ent-d2ae2a_.ent", "d1qrra_.ent-d2naca1.ent", "d1qrra_.ent-d2pgd_2.ent", "d1qrva_.ent-d2lefa_.ent", "d1qs1a1.ent-d1qs1a2.ent", "d1qsaa1.ent-d1e8xa1.ent", "d1qsaa1.ent-d1elka_.ent", "d1qsaa1.ent-d1h6ka1.ent", "d1qsaa1.ent-d1h6ka2.ent", "d1qsaa1.ent-d1h6ka3.ent", "d1qsaa1.ent-d1hf8a_.ent", "d1qsaa1.ent-d1hh8a_.ent", "d1qsaa1.ent-d1ho8a_.ent", "d1qsaa1.ent-d1hs6a1.ent", "d1qsaa1.ent-d1hz4a_.ent", "d1qsaa1.ent-d1ihga1.ent", "d1qsaa1.ent-d1keya_.ent", "d1qsaa1.ent-d1kpsb_.ent", "d1qsaa1.ent-d1l5ja1.ent", "d1qsaa1.ent-d1ld8a_.ent", "d1qsaa1.ent-d1ldja2.ent", "d1qsaa1.ent-d1lrv__.ent", "d1qsaa1.ent-d1lsha1.ent", "d1qsaa1.ent-d1n4ka1.ent", "d1qsaa1.ent-d1pbv__.ent", "d1qsaa1.ent-d1qjba_.ent", "d1qsaa1.ent-d1qqea_.ent", "d1qsaa2.ent-d1qusa_.ent", "d1qsaa2.ent-d217l__.ent", "d1qsaa2.ent-d2eql__.ent", "d1qsaa2.ent-d3lzt__.ent", "d1qsga_.ent-d1bgva1.ent", "d1qsma_.ent-d1qsta_.ent", "d1qtfa_.ent-d1a0la_.ent", "d1qtfa_.ent-d1agja_.ent", "d1qtfa_.ent-d1azza_.ent", "d1qtfa_.ent-d1bio__.ent", "d1qtfa_.ent-d1bqya_.ent", "d1qtfa_.ent-d1cgha_.ent", "d1qtfa_.ent-d1eaxa_.ent", "d1qtfa_.ent-d1ekbb_.ent", "d1qtfa_.ent-d1elva1.ent", "d1qtfa_.ent-d1fjsa_.ent", "d1qtfa_.ent-d1gdna_.ent", "d1qtfa_.ent-d1gpza1.ent", "d1qtfa_.ent-d1gvkb_.ent", "d1qtfa_.ent-d1gvza_.ent", "d1qtfa_.ent-d1hj9a_.ent", "d1qtfa_.ent-d1m9ua_.ent", "d1qtfa_.ent-d1mzaa_.ent", "d1qtfa_.ent-d1rfna_.ent", "d1qtfa_.ent-d2hlca_.ent", "d1qtma1.ent-d1t7pa1.ent", "d1qtma1.ent-d1tgoa1.ent", "d1qtma1.ent-d1vrta1.ent", "d1qtma1.ent-d1xwl_1.ent", "d1qtra_.ent-d1iz7a_.ent", "d1qtra_.ent-d1jjia_.ent", "d1qu6a1.ent-d1qu6a2.ent", "d1qu6a1.ent-d1stu__.ent", "d1qu6a2.ent-d1stu__.ent", "d1quba1.ent-d1quba2.ent", "d1quba1.ent-d1quba3.ent", "d1quba1.ent-d1quba4.ent", "d1quba1.ent-d1quba5.ent", "d1quba2.ent-d1quba3.ent", "d1quba2.ent-d1quba4.ent", "d1quba2.ent-d1quba5.ent", "d1quba3.ent-d1quba4.ent", "d1quba3.ent-d1quba5.ent", "d1quba4.ent-d1quba5.ent", "d1que_1.ent-d2cnd_1.ent", "d1que_1.ent-d2pia_1.ent", "d1que_2.ent-d2cnd_2.ent", "d1que_2.ent-d2pia_2.ent", "d1quqa_.ent-d1ewia_.ent", "d1quqa_.ent-d1fgua1.ent", "d1quqa_.ent-d1iyjb3.ent", "d1quqa_.ent-d1jjcb3.ent", "d1quqa_.ent-d1quqb_.ent", "d1quqa_.ent-d3seb_1.ent", "d1quqb_.ent-d1jjcb3.ent", "d1qusa_.ent-d217l__.ent", "d1qusa_.ent-d2eql__.ent", "d1qusa_.ent-d3lzt__.ent", "d1quua1.ent-d1quua2.ent", "d1quua1.ent-d2spca_.ent", "d1quua2.ent-d2spca_.ent", "d1quwa_.ent-d1fb6a_.ent", "d1qvba_.ent-d1b9za2.ent", "d1qvba_.ent-d1bf2_3.ent", "d1qvba_.ent-d1cz1a_.ent", "d1qvba_.ent-d1e43a2.ent", "d1qvba_.ent-d1e4ia_.ent", "d1qvba_.ent-d1eh9a3.ent", "d1qvba_.ent-d1iexa1.ent", "d1qvba_.ent-d1j0ha3.ent", "d1qvba_.ent-d1ji1a3.ent", "d1qvba_.ent-d1kwga2.ent", "d1qvba_.ent-d1lwha2.ent", "d1qvba_.ent-d1pama4.ent", "d1qvba_.ent-d1qba_3.ent", "d1qvba_.ent-d1qhoa4.ent", "d1qvba_.ent-d1uok_2.ent", "d1qvba_.ent-d7taa_2.ent", "d1qvca_.ent-d1d7qa_.ent", "d1qvca_.ent-d1e1oa1.ent", "d1qvca_.ent-d1eova1.ent", "d1qvca_.ent-d1ewia_.ent", "d1qvca_.ent-d1fgua1.ent", "d1qvca_.ent-d1fgua2.ent", "d1qvca_.ent-d1fjgl_.ent", "d1qvca_.ent-d1i50h_.ent", "d1qvca_.ent-d1iyjb3.ent", "d1qvca_.ent-d1iyjb5.ent", "d1qvca_.ent-d1jb7a2.ent", "d1qvca_.ent-d1jjcb3.ent", "d1qvca_.ent-d1quqa_.ent", "d1qvca_.ent-d1quqb_.ent", "d1qyp__.ent-d1tfi__.ent", "d1qyp__.ent-d1yua_1.ent", "d1qyp__.ent-d1yua_2.ent", "d1r69__.ent-d1uxd__.ent", "d1r69__.ent-d1vpwa1.ent", "d1ra9__.ent-d1vdra_.ent", "d1ra9__.ent-d3dfr__.ent", "d1rb9__.ent-d1tfi__.ent", "d1rb9__.ent-d1yua_1.ent", "d1rb9__.ent-d1yua_2.ent", "d1rb9__.ent-d1zaka2.ent", "d1rb9__.ent-d1zin_2.ent", "d1rcf__.ent-d2fcr__.ent", "d1rcf__.ent-d5nul__.ent", "d1rdr__.ent-d1t7pa2.ent", "d1rdr__.ent-d1tgoa2.ent", "d1rdr__.ent-d1vrta2.ent", "d1rdr__.ent-d1xwl_2.ent", "d1rec__.ent-d1alva_.ent", "d1rec__.ent-d1auib_.ent", "d1rec__.ent-d1df0a1.ent", "d1rec__.ent-d1dgua_.ent", "d1rec__.ent-d1eg3a1.ent", "d1rec__.ent-d1exra_.ent", "d1rec__.ent-d1g8ia_.ent", "d1rec__.ent-d1ggwa_.ent", "d1rec__.ent-d1hqva_.ent", "d1rec__.ent-d1jfja_.ent", "d1rec__.ent-d1k94a_.ent", "d1rec__.ent-d1m31a_.ent", "d1rec__.ent-d1m45a_.ent", "d1rec__.ent-d1ncx__.ent", "d1rec__.ent-d1rro__.ent", "d1rec__.ent-d1sra__.ent", "d1rec__.ent-d1wdcb_.ent", "d1rec__.ent-d1wdcc_.ent", "d1rec__.ent-d2cbla1.ent", "d1rec__.ent-d2pvba_.ent", "d1rec__.ent-d2sas__.ent", "d1rec__.ent-d2scpa_.ent", "d1rec__.ent-d5pal__.ent", "d1regx_.ent-d1dqaa1.ent", "d1repc1.ent-d1bjaa_.ent", "d1repc1.ent-d1d5va_.ent", "d1repc1.ent-d1e17a_.ent", "d1repc1.ent-d1f1za1.ent", "d1repc1.ent-d1fnna1.ent", "d1repc1.ent-d1fp1d1.ent", "d1repc1.ent-d1fp2a1.ent", "d1repc1.ent-d1fsha_.ent", "d1repc1.ent-d1fzpb_.ent", "d1repc1.ent-d1hks__.ent", "d1repc1.ent-d1ig6a_.ent", "d1repc1.ent-d1igna2.ent", "d1repc1.ent-d1jhga_.ent", "d1repc1.ent-d1ka8a_.ent", "d1repc1.ent-d1ldja1.ent", "d1repc1.ent-d1opc__.ent", "d1repc1.ent-d1repc2.ent", "d1repc1.ent-d1smta_.ent", "d1repc1.ent-d2ezl__.ent", "d1repc1.ent-d2foka3.ent", "d1repc1.ent-d2irfg_.ent", "d1repc2.ent-d1bjaa_.ent", "d1repc2.ent-d1d5va_.ent", "d1repc2.ent-d1e17a_.ent", "d1repc2.ent-d1f1za1.ent", "d1repc2.ent-d1fp2a1.ent", "d1repc2.ent-d1fsha_.ent", "d1repc2.ent-d1jhga_.ent", "d1repc2.ent-d1ka8a_.ent", "d1repc2.ent-d1ldja1.ent", "d1repc2.ent-d1opc__.ent", "d1repc2.ent-d1smta_.ent", "d1repc2.ent-d2ezl__.ent", "d1repc2.ent-d2foka3.ent", "d1rfna_.ent-d1azza_.ent", "d1rfna_.ent-d1bio__.ent", "d1rfna_.ent-d1bqya_.ent", "d1rfna_.ent-d1cgha_.ent", "d1rfna_.ent-d1fjsa_.ent", "d1rfna_.ent-d1gdna_.ent", "d1rfna_.ent-d1gpza1.ent", "d1rfna_.ent-d1hj9a_.ent", "d1rfna_.ent-d2hlca_.ent", "d1rfnb_.ent-d1apq__.ent", "d1rfnb_.ent-d1b9wa1.ent", "d1rfnb_.ent-d1b9wa2.ent", "d1rfnb_.ent-d1ceja1.ent", "d1rfnb_.ent-d1ceja2.ent", "d1rfnb_.ent-d1cvua2.ent", "d1rfnb_.ent-d1dx5i1.ent", "d1rfnb_.ent-d1emo_1.ent", "d1rfnb_.ent-d1fjsl_.ent", "d1rfnb_.ent-d1hz8a1.ent", "d1rfnb_.ent-d1hz8a2.ent", "d1rfnb_.ent-d1ijqa2.ent", "d1rfnb_.ent-d1ioxa_.ent", "d1rfnb_.ent-d1jl9a_.ent", "d1rfnb_.ent-d1klo_1.ent", "d1rfnb_.ent-d1klo_2.ent", "d1rfnb_.ent-d1klo_3.ent", "d1rfnb_.ent-d1l3ya_.ent", "d1rfnb_.ent-d1m1xb5.ent", "d1rfnb_.ent-d1tpg_1.ent", "d1rfnb_.ent-d1urk_1.ent", "d1rfnb_.ent-d3tgf__.ent", "d1rfs__.ent-d1rie__.ent", "d1rgs_1.ent-d1rgs_2.ent", "d1rl6a1.ent-d1rl6a2.ent", "d1rlw__.ent-d1rsy__.ent", "d1rlw__.ent-d3rpba_.ent", "d1rmd_1.ent-d1tf3a1.ent", "d1rmd_1.ent-d1tf3a2.ent", "d1rmd_1.ent-d1tf3a3.ent", "d1rmd_1.ent-d1tf6a4.ent", "d1rmd_1.ent-d1ubdc3.ent", "d1rmd_1.ent-d1yuja_.ent", "d1rmd_1.ent-d1zfd__.ent", "d1rmd_1.ent-d2drpa1.ent", "d1rmd_1.ent-d2glia1.ent", "d1rmd_1.ent-d2glia2.ent", "d1rmd_1.ent-d2glia4.ent", "d1rmd_1.ent-d5znf__.ent", "d1rpja_.ent-d2dri__.ent", "d1rpja_.ent-d2liv__.ent", "d1rpja_.ent-d8abp__.ent", "d1rpxa_.ent-d1thfd_.ent", "d1rro__.ent-d1m31a_.ent", "d1rro__.ent-d2pvba_.ent", "d1rsy__.ent-d1who__.ent", "d1rsy__.ent-d3rpba_.ent", "d1ruxa1.ent-d1ruxa2.ent", "d1ryp1_.ent-d1iru1_.ent", "d1ryp1_.ent-d1iru2_.ent", "d1ryp1_.ent-d1iruk_.ent", "d1ryp1_.ent-d1jgta2.ent", "d1ryp1_.ent-d1pma1_.ent", "d1ryp1_.ent-d1pmaa_.ent", "d1ryp1_.ent-d1ryp2_.ent", "d1ryp1_.ent-d1rypa_.ent", "d1ryp1_.ent-d1ryph_.ent", "d1ryp1_.ent-d1rypi_.ent", "d1ryp1_.ent-d1rypj_.ent", "d1ryp1_.ent-d1rypk_.ent", "d1ryp1_.ent-d1rypl_.ent", "d1ryp2_.ent-d1iru1_.ent", "d1ryp2_.ent-d1iru2_.ent", "d1ryp2_.ent-d1iruk_.ent", "d1ryp2_.ent-d1jgta2.ent", "d1ryp2_.ent-d1pma1_.ent", "d1ryp2_.ent-d1pmaa_.ent", "d1ryp2_.ent-d1ryp1_.ent", "d1ryp2_.ent-d1rypa_.ent", "d1ryp2_.ent-d1rypf_.ent", "d1ryp2_.ent-d1ryph_.ent", "d1ryp2_.ent-d1rypi_.ent", "d1ryp2_.ent-d1rypj_.ent", "d1ryp2_.ent-d1rypk_.ent", "d1ryp2_.ent-d1rypl_.ent", "d1rypa_.ent-d1gdoa_.ent", "d1rypa_.ent-d1gph12.ent", "d1rypa_.ent-d1iru1_.ent", "d1rypa_.ent-d1iru2_.ent", "d1rypa_.ent-d1iruk_.ent", "d1rypa_.ent-d1jgta2.ent", "d1rypa_.ent-d1pma1_.ent", "d1rypa_.ent-d1pmaa_.ent", "d1rypa_.ent-d1ryp1_.ent", "d1rypa_.ent-d1ryp2_.ent", "d1rypa_.ent-d1rypd_.ent", "d1rypa_.ent-d1rype_.ent", "d1rypa_.ent-d1rypf_.ent", "d1rypa_.ent-d1ryph_.ent", "d1rypa_.ent-d1rypi_.ent", "d1rypa_.ent-d1rypj_.ent", "d1rypa_.ent-d1rypk_.ent", "d1rypa_.ent-d1rypl_.ent", "d1rypb_.ent-d1ecfa2.ent", "d1rypb_.ent-d1gdoa_.ent", "d1rypb_.ent-d1gph12.ent", "d1rypb_.ent-d1iru1_.ent", "d1rypb_.ent-d1iru2_.ent", "d1rypb_.ent-d1iruk_.ent", "d1rypb_.ent-d1jgta2.ent", "d1rypb_.ent-d1pma1_.ent", "d1rypb_.ent-d1pmaa_.ent", "d1rypb_.ent-d1ryp1_.ent", "d1rypb_.ent-d1ryp2_.ent", "d1rypb_.ent-d1rypa_.ent", "d1rypb_.ent-d1rypc_.ent", "d1rypb_.ent-d1rypd_.ent", "d1rypb_.ent-d1rype_.ent", "d1rypb_.ent-d1rypf_.ent", "d1rypb_.ent-d1rypg_.ent", "d1rypb_.ent-d1ryph_.ent", "d1rypb_.ent-d1rypi_.ent", "d1rypb_.ent-d1rypj_.ent", "d1rypb_.ent-d1rypk_.ent", "d1rypb_.ent-d1rypl_.ent", "d1rypc_.ent-d1gdoa_.ent", "d1rypc_.ent-d1gph12.ent", "d1rypc_.ent-d1iru1_.ent", "d1rypc_.ent-d1iru2_.ent", "d1rypc_.ent-d1iruk_.ent", "d1rypc_.ent-d1jgta2.ent", "d1rypc_.ent-d1pma1_.ent", "d1rypc_.ent-d1pmaa_.ent", "d1rypc_.ent-d1ryp1_.ent", "d1rypc_.ent-d1ryp2_.ent", "d1rypc_.ent-d1rypa_.ent", "d1rypc_.ent-d1rypd_.ent", "d1rypc_.ent-d1rype_.ent", "d1rypc_.ent-d1rypf_.ent", "d1rypc_.ent-d1rypg_.ent", "d1rypc_.ent-d1ryph_.ent", "d1rypc_.ent-d1rypi_.ent", "d1rypc_.ent-d1rypj_.ent", "d1rypc_.ent-d1rypk_.ent", "d1rypc_.ent-d1rypl_.ent", "d1rypd_.ent-d1gdoa_.ent", "d1rypd_.ent-d1gph12.ent", "d1rypd_.ent-d1iru1_.ent", "d1rypd_.ent-d1iru2_.ent", "d1rypd_.ent-d1iruk_.ent", "d1rypd_.ent-d1jgta2.ent", "d1rypd_.ent-d1pma1_.ent", "d1rypd_.ent-d1pmaa_.ent", "d1rypd_.ent-d1ryp1_.ent", "d1rypd_.ent-d1ryp2_.ent", "d1rypd_.ent-d1rypf_.ent", "d1rypd_.ent-d1ryph_.ent", "d1rypd_.ent-d1rypi_.ent", "d1rypd_.ent-d1rypj_.ent", "d1rypd_.ent-d1rypk_.ent", "d1rypd_.ent-d1rypl_.ent", "d1rype_.ent-d1gdoa_.ent", "d1rype_.ent-d1gph12.ent", "d1rype_.ent-d1iru1_.ent", "d1rype_.ent-d1iru2_.ent", "d1rype_.ent-d1iruk_.ent", "d1rype_.ent-d1jgta2.ent", "d1rype_.ent-d1pma1_.ent", "d1rype_.ent-d1pmaa_.ent", "d1rype_.ent-d1ryp1_.ent", "d1rype_.ent-d1ryp2_.ent", "d1rype_.ent-d1rypd_.ent", "d1rype_.ent-d1rypf_.ent", "d1rype_.ent-d1ryph_.ent", "d1rype_.ent-d1rypi_.ent", "d1rype_.ent-d1rypj_.ent", "d1rype_.ent-d1rypk_.ent", "d1rype_.ent-d1rypl_.ent", "d1rypf_.ent-d1iru1_.ent", "d1rypf_.ent-d1iru2_.ent", "d1rypf_.ent-d1iruk_.ent", "d1rypf_.ent-d1jgta2.ent", "d1rypf_.ent-d1pma1_.ent", "d1rypf_.ent-d1pmaa_.ent", "d1rypf_.ent-d1ryp1_.ent", "d1rypf_.ent-d1ryph_.ent", "d1rypf_.ent-d1rypi_.ent", "d1rypf_.ent-d1rypj_.ent", "d1rypf_.ent-d1rypk_.ent", "d1rypf_.ent-d1rypl_.ent", "d1rypg_.ent-d1gdoa_.ent", "d1rypg_.ent-d1gph12.ent", "d1rypg_.ent-d1iru1_.ent", "d1rypg_.ent-d1iru2_.ent", "d1rypg_.ent-d1iruk_.ent", "d1rypg_.ent-d1jgta2.ent", "d1rypg_.ent-d1pma1_.ent", "d1rypg_.ent-d1pmaa_.ent", "d1rypg_.ent-d1ryp1_.ent", "d1rypg_.ent-d1ryp2_.ent", "d1rypg_.ent-d1rypa_.ent", "d1rypg_.ent-d1rypd_.ent", "d1rypg_.ent-d1rype_.ent", "d1rypg_.ent-d1rypf_.ent", "d1rypg_.ent-d1ryph_.ent", "d1rypg_.ent-d1rypi_.ent", "d1rypg_.ent-d1rypj_.ent", "d1rypg_.ent-d1rypk_.ent", "d1rypg_.ent-d1rypl_.ent", "d1ryph_.ent-d1iruk_.ent", "d1ryph_.ent-d1jgta2.ent", "d1ryph_.ent-d1pma1_.ent", "d1ryph_.ent-d1rypj_.ent", "d1ryph_.ent-d1rypk_.ent", "d1rypi_.ent-d1iru1_.ent", "d1rypi_.ent-d1iru2_.ent", "d1rypi_.ent-d1iruk_.ent", "d1rypi_.ent-d1jgta2.ent", "d1rypi_.ent-d1pma1_.ent", "d1rypi_.ent-d1pmaa_.ent", "d1rypi_.ent-d1ryph_.ent", "d1rypi_.ent-d1rypj_.ent", "d1rypi_.ent-d1rypk_.ent", "d1rypi_.ent-d1rypl_.ent", "d1rypj_.ent-d1iruk_.ent", "d1rypj_.ent-d1jgta2.ent", "d1rypj_.ent-d1pma1_.ent", "d1rypj_.ent-d1rypk_.ent", "d1rypl_.ent-d1iruk_.ent", "d1rypl_.ent-d1jgta2.ent", "d1rypl_.ent-d1pma1_.ent", "d1rypl_.ent-d1ryph_.ent", "d1rypl_.ent-d1rypj_.ent", "d1rypl_.ent-d1rypk_.ent", "d1saca_.ent-d1dhkb_.ent", "d1saca_.ent-d1dyka1.ent", "d1saca_.ent-d1dyka2.ent", "d1saca_.ent-d1h30a1.ent", "d1saca_.ent-d1kit_1.ent", "d1saca_.ent-d1kit_2.ent", "d1saca_.ent-d1xnb__.ent", "d1saca_.ent-d2nlra_.ent", "d1saca_.ent-d2sli_1.ent", "d1sbp__.ent-d1wdna_.ent", "d1sbp__.ent-d3mbp__.ent", "d1sbp__.ent-d3thia_.ent", "d1sco__.ent-d1scy__.ent", "d1sco__.ent-d1sis__.ent", "d1sco__.ent-d1tsk__.ent", "d1sco__.ent-d2sn3__.ent", "d1scy__.ent-d1sis__.ent", "d1scy__.ent-d1tsk__.ent", "d1scy__.ent-d2sn3__.ent", "d1sgpi_.ent-d1tbrr1.ent", "d1sgpi_.ent-d1tbrr2.ent", "d1sgpi_.ent-d1tgsi_.ent", "d1sgpi_.ent-d4sgbi_.ent", "d1sh1__.ent-d2bds__.ent", "d1sis__.ent-d1tsk__.ent", "d1sis__.ent-d2sn3__.ent", "d1skz_1.ent-d1skz_2.ent", "d1skz_1.ent-d4htci_.ent", "d1skz_2.ent-d4htci_.ent", "d1smta_.ent-d1bjaa_.ent", "d1smta_.ent-d1d5va_.ent", "d1smta_.ent-d1e17a_.ent", "d1smta_.ent-d1fsha_.ent", "d1smta_.ent-d1ldja1.ent", "d1smta_.ent-d2foka3.ent", "d1soxa1.ent-d1ea9c1.ent", "d1soxa1.ent-d1edqa1.ent", "d1soxa1.ent-d1eut_1.ent", "d1soxa1.ent-d1ji1a1.ent", "d1soxa1.ent-d1ji2a1.ent", "d1soxa1.ent-d1kv3a1.ent", "d1soxa1.ent-d1m7xa1.ent", "d1soxa1.ent-d1my7a_.ent", "d1soxa1.ent-d1qba_1.ent", "d1soxa1.ent-d1qfha1.ent", "d1soxa1.ent-d1qfha2.ent", "d1sra__.ent-d1eg3a1.ent", "d1sra__.ent-d1exra_.ent", "d1sra__.ent-d1ggwa_.ent", "d1sra__.ent-d1jfja_.ent", "d1sra__.ent-d1m31a_.ent", "d1sra__.ent-d1m45a_.ent", "d1sra__.ent-d1rro__.ent", "d1sra__.ent-d1wdcb_.ent", "d1sra__.ent-d2cbla1.ent", "d1sra__.ent-d2pvba_.ent", "d1sra__.ent-d2sas__.ent", "d1sra__.ent-d2scpa_.ent", "d1sra__.ent-d5pal__.ent", "d1stfi_.ent-d1ugia_.ent", "d1stfi_.ent-d3stda_.ent", "d1sty__.ent-d1b3qa2.ent", "d1sty__.ent-d1eova1.ent", "d1sty__.ent-d1fgua2.ent", "d1sty__.ent-d1fjgl_.ent", "d1sty__.ent-d1i50h_.ent", "d1sty__.ent-d1jb3a_.ent", "d1sty__.ent-d1jb7a2.ent", "d1sty__.ent-d1k28a1.ent", "d1sty__.ent-d1quqa_.ent", "d1sty__.ent-d3seb_1.ent", "d1sva1_.ent-d1aym1_.ent", "d1sva1_.ent-d1aym2_.ent", "d1sva1_.ent-d1b35a_.ent", "d1sva1_.ent-d1b35b_.ent", "d1sva1_.ent-d1b35c_.ent", "d1sva1_.ent-d1bev1_.ent", "d1sva1_.ent-d1bev3_.ent", "d1sva1_.ent-d1d4m1_.ent", "d1sva1_.ent-d1k5ma_.ent", "d1sva1_.ent-d1novc_.ent", "d1sva1_.ent-d1pov0_.ent", "d1sva1_.ent-d1pvc1_.ent", "d1sva1_.ent-d1tmf1_.ent", "d1sva1_.ent-d1vpsa_.ent", "d1sva1_.ent-d2bbva_.ent", "d1sva1_.ent-d2mev1_.ent", "d1sva1_.ent-d2mev2_.ent", "d1svpa_.ent-d2hrva_.ent", "d1sw6a_.ent-d1ycsb1.ent", "d1t1da_.ent-d3kvt__.ent", "d1t7pa1.ent-d1az9_1.ent", "d1t7pa1.ent-d1bupa1.ent", "d1t7pa1.ent-d1bupa2.ent", "d1t7pa1.ent-d1e4ft1.ent", "d1t7pa1.ent-d1e4ft2.ent", "d1t7pa1.ent-d1j54a_.ent", "d1t7pa1.ent-d1jj2m_.ent", "d1t7pa1.ent-d1mwma2.ent", "d1t7pa1.ent-d1nbwa3.ent", "d1t7pa1.ent-d1tgoa1.ent", "d1t7pa1.ent-d1vrta1.ent", "d1t7pa1.ent-d1xwl_1.ent", "d1t7pa2.ent-d1tgoa2.ent", "d1t7pa2.ent-d1vrta2.ent", "d1t7pa2.ent-d1xwl_2.ent", "d1tbge_.ent-d2prgc_.ent", "d1tbrr1.ent-d1tbrr2.ent", "d1tbrr1.ent-d1tgsi_.ent", "d1tbrr1.ent-d4sgbi_.ent", "d1tbrr2.ent-d1tgsi_.ent", "d1tbrr2.ent-d4sgbi_.ent", "d1tca__.ent-d1cvl__.ent", "d1tca__.ent-d1iz7a_.ent", "d1tca__.ent-d1jjia_.ent", "d1tca__.ent-d1qtra_.ent", "d1tca__.ent-d1thta_.ent", "d1tca__.ent-d3tgl__.ent", "d1tdj_2.ent-d1tdj_3.ent", "d1tf3a1.ent-d1tf3a2.ent", "d1tf3a1.ent-d1tf3a3.ent", "d1tf3a1.ent-d1tf6a4.ent", "d1tf3a1.ent-d1ubdc3.ent", "d1tf3a1.ent-d1yuja_.ent", "d1tf3a1.ent-d1zfd__.ent", "d1tf3a1.ent-d2drpa1.ent", "d1tf3a1.ent-d2glia1.ent", "d1tf3a1.ent-d2glia2.ent", "d1tf3a1.ent-d2glia4.ent", "d1tf3a1.ent-d5znf__.ent", "d1tf3a2.ent-d1tf3a3.ent", "d1tf3a2.ent-d1tf6a4.ent", "d1tf3a2.ent-d1ubdc3.ent", "d1tf3a2.ent-d1yuja_.ent", "d1tf3a2.ent-d1zfd__.ent", "d1tf3a2.ent-d2drpa1.ent", "d1tf3a2.ent-d2glia1.ent", "d1tf3a2.ent-d2glia2.ent", "d1tf3a2.ent-d2glia4.ent", "d1tf3a2.ent-d5znf__.ent", "d1tf3a3.ent-d1tf6a4.ent", "d1tf3a3.ent-d1ubdc3.ent", "d1tf3a3.ent-d1yuja_.ent", "d1tf3a3.ent-d1zfd__.ent", "d1tf3a3.ent-d2drpa1.ent", "d1tf3a3.ent-d2glia1.ent", "d1tf3a3.ent-d2glia2.ent", "d1tf3a3.ent-d2glia4.ent", "d1tf3a3.ent-d5znf__.ent", "d1tf4a2.ent-d1ycsa_.ent", "d1tf6a4.ent-d1ubdc3.ent", "d1tf6a4.ent-d1yuja_.ent", "d1tf6a4.ent-d1zfd__.ent", "d1tf6a4.ent-d2drpa1.ent", "d1tf6a4.ent-d2glia1.ent", "d1tf6a4.ent-d2glia2.ent", "d1tf6a4.ent-d2glia4.ent", "d1tf6a4.ent-d5znf__.ent", "d1tfi__.ent-d1yua_1.ent", "d1tfi__.ent-d1yua_2.ent", "d1tfi__.ent-d1zaka2.ent", "d1tfi__.ent-d1zin_2.ent", "d1tfr_1.ent-d1xo1a1.ent", "d1tfr_2.ent-d1xo1a2.ent", "d1tfr_2.ent-d2rsla_.ent", "d1tfs__.ent-d1tgxa_.ent", "d1tfs__.ent-d3ebx__.ent", "d1tfxc_.ent-d1tocr1.ent", "d1tfxc_.ent-d1tocr2.ent", "d1tgoa1.ent-d1az9_1.ent", "d1tgoa1.ent-d1bco_2.ent", "d1tgoa1.ent-d1bupa1.ent", "d1tgoa1.ent-d1bupa2.ent", "d1tgoa1.ent-d1czan1.ent", "d1tgoa1.ent-d1czan2.ent", "d1tgoa1.ent-d1e4ft1.ent", "d1tgoa1.ent-d1e4ft2.ent", "d1tgoa1.ent-d1g99a2.ent", "d1tgoa1.ent-d1glag1.ent", "d1tgoa1.ent-d1glag2.ent", "d1tgoa1.ent-d1huxa_.ent", "d1tgoa1.ent-d1j54a_.ent", "d1tgoa1.ent-d1j6za2.ent", "d1tgoa1.ent-d1jj2m_.ent", "d1tgoa1.ent-d1kcfa2.ent", "d1tgoa1.ent-d1mwma2.ent", "d1tgoa1.ent-d1nbwa2.ent", "d1tgoa1.ent-d1nbwa3.ent", "d1tgoa1.ent-d1t7pa1.ent", "d1tgoa1.ent-d1vrta1.ent", "d1tgoa1.ent-d1xwl_1.ent", "d1tgoa2.ent-d1vrta2.ent", "d1tgoa2.ent-d1xwl_2.ent", "d1tgsi_.ent-d4sgbi_.ent", "d1tgxa_.ent-d3ebx__.ent", "d1thta_.ent-d3tgl__.ent", "d1thx__.ent-d1a8l_2.ent", "d1thx__.ent-d1a8y_2.ent", "d1thx__.ent-d1aba__.ent", "d1thx__.ent-d1aqwa2.ent", "d1thx__.ent-d1e6ba2.ent", "d1thx__.ent-d1erv__.ent", "d1thx__.ent-d1fb6a_.ent", "d1thx__.ent-d1fhe_2.ent", "d1thx__.ent-d1gh2a_.ent", "d1thx__.ent-d1hyua4.ent", "d1thx__.ent-d1iloa_.ent", "d1thx__.ent-d1k0ma2.ent", "d1thx__.ent-d1k3ya2.ent", "d1thx__.ent-d1kte__.ent", "d1thx__.ent-d1m2da_.ent", "d1thx__.ent-d1qmha1.ent", "d1thx__.ent-d1quwa_.ent", "d1thx__.ent-d2trxa_.ent", "d1tiid_.ent-d3chbd_.ent", "d1tiid_.ent-d3seb_1.ent", "d1tiid_.ent-d3tss_1.ent", "d1tkia_.ent-d1a06__.ent", "d1tkia_.ent-d1blxa_.ent", "d1tkia_.ent-d1csn__.ent", "d1tkia_.ent-d1f3mc_.ent", "d1tkia_.ent-d1fgka_.ent", "d1tkia_.ent-d1fvra_.ent", "d1tkia_.ent-d1ia9a_.ent", "d1tkia_.ent-d1iepa_.ent", "d1tkia_.ent-d1jksa_.ent", "d1tkia_.ent-d1jpaa_.ent", "d1tkia_.ent-d1jvpp_.ent", "d1tkia_.ent-d1kwpa_.ent", "d1tkia_.ent-d1lufa_.ent", "d1tkia_.ent-d1m14a_.ent", "d1tkia_.ent-d1phk__.ent", "d1tmf1_.ent-d1aym2_.ent", "d1tmf1_.ent-d1b35a_.ent", "d1tmf1_.ent-d1b35b_.ent", "d1tmf1_.ent-d1bev1_.ent", "d1tmf1_.ent-d1bev3_.ent", "d1tmf1_.ent-d2mev1_.ent", "d1tmf1_.ent-d2mev2_.ent", "d1tml__.ent-d2bvwa_.ent", "d1tmo_1.ent-d2napa1.ent", "d1tmo_2.ent-d2napa2.ent", "d1tn3__.ent-d1b08a1.ent", "d1tn3__.ent-d1b6e__.ent", "d1tn3__.ent-d1byfa_.ent", "d1tn3__.ent-d1cwva5.ent", "d1tn3__.ent-d1dv8a_.ent", "d1tn3__.ent-d1e87a_.ent", "d1tn3__.ent-d1egia_.ent", "d1tn3__.ent-d1f00i3.ent", "d1tn3__.ent-d1fvua_.ent", "d1tn3__.ent-d1fvub_.ent", "d1tn3__.ent-d1g1ta1.ent", "d1tn3__.ent-d1h8ua_.ent", "d1tn3__.ent-d1hq8a_.ent", "d1tn3__.ent-d1jwia_.ent", "d1tn3__.ent-d1jwib_.ent", "d1tn3__.ent-d1k9ja_.ent", "d1tn3__.ent-d1kg0c_.ent", "d1tn3__.ent-d1li1a1.ent", "d1tn3__.ent-d1li1a2.ent", "d1tn3__.ent-d1prtb2.ent", "d1tn3__.ent-d1qo3c_.ent", "d1tn3__.ent-d1tsg__.ent", "d1tnra_.ent-d2tnfa_.ent", "d1tocr1.ent-d1tocr2.ent", "d1tpla_.ent-d1ajsa_.ent", "d1tpla_.ent-d1b9ha_.ent", "d1tpla_.ent-d1bs0a_.ent", "d1tpla_.ent-d1c7na_.ent", "d1tpla_.ent-d1e5ea_.ent", "d1tpla_.ent-d1gdea_.ent", "d1tpla_.ent-d1j32a_.ent", "d1tpla_.ent-d1jf9a_.ent", "d1tpla_.ent-d1kl1a_.ent", "d1tpla_.ent-d1m7ya_.ent", "d1tpla_.ent-d1n8pa_.ent", "d1tpla_.ent-d1qisa_.ent", "d1tpla_.ent-d1yaaa_.ent", "d1tpla_.ent-d2ay1a_.ent", "d1tpla_.ent-d2oata_.ent", "d1tpla_.ent-d3tata_.ent", "d1tpla_.ent-d7aata_.ent", "d1tsg__.ent-d1prtb2.ent", "d1tsk__.ent-d2sn3__.ent", "d1tuba1.ent-d1tubb1.ent", "d1tuba2.ent-d1tubb2.ent", "d1tul__.ent-d4ubpb_.ent", "d1tvda_.ent-d1akjd_.ent", "d1tvda_.ent-d1b88a_.ent", "d1tvda_.ent-d1bec_1.ent", "d1tvda_.ent-d1c5ch1.ent", "d1tvda_.ent-d1dlfl_.ent", "d1tvda_.ent-d1fo0a_.ent", "d1tvda_.ent-d1h5ba_.ent", "d1tvda_.ent-d1neu__.ent", "d1tvda_.ent-d1nfdb1.ent", "d1tvda_.ent-d1qfoa_.ent", "d1tvda_.ent-d2rhe__.ent", "d1tvxa_.ent-d2hcc__.ent", "d1tvxa_.ent-d3il8__.ent", "d1tx4a_.ent-d1wer__.ent", "d1u2fa_.ent-d2msta_.ent", "d1u2fa_.ent-d2u1a__.ent", "d1u2fa_.ent-d2u2fa_.ent", "d1uaaa2.ent-d1bg2__.ent", "d1uaaa2.ent-d1e2ka_.ent", "d1uaaa2.ent-d1f9va_.ent", "d1uaaa2.ent-d1g8pa_.ent", "d1uaaa2.ent-d1ksfx3.ent", "d1uaaa2.ent-d1n0ua2.ent", "d1uaaa2.ent-d1pjr_1.ent", "d1uaaa2.ent-d1pjr_2.ent", "d1uaaa2.ent-d1uaaa1.ent", "d1ubdc3.ent-d1yuja_.ent", "d1ubdc3.ent-d1zfd__.ent", "d1ubdc3.ent-d2drpa1.ent", "d1ubdc3.ent-d2glia1.ent", "d1ubdc3.ent-d2glia2.ent", "d1ubdc3.ent-d2glia4.ent", "d1ubdc3.ent-d5znf__.ent", "d1uby__.ent-d5eau_2.ent", "d1uch__.ent-d2act__.ent", "d1uch__.ent-d2cb5a_.ent", "d1uch__.ent-d3gcb__.ent", "d1uch__.ent-d7pcka_.ent", "d1ugia_.ent-d3stda_.ent", "d1uok_1.ent-d7taa_1.ent", "d1uok_2.ent-d1b9za2.ent", "d1uok_2.ent-d1bf2_3.ent", "d1uok_2.ent-d1cz1a_.ent", "d1uok_2.ent-d1e43a2.ent", "d1uok_2.ent-d1e4ia_.ent", "d1uok_2.ent-d1eh9a3.ent", "d1uok_2.ent-d1iexa1.ent", "d1uok_2.ent-d1j0ha3.ent", "d1uok_2.ent-d1ji1a3.ent", "d1uok_2.ent-d1kwga2.ent", "d1uok_2.ent-d1lwha2.ent", "d1uok_2.ent-d1pama4.ent", "d1uok_2.ent-d1qba_3.ent", "d1uok_2.ent-d1qhoa4.ent", "d1uok_2.ent-d7taa_2.ent", "d1uox_1.ent-d1uox_2.ent", "d1urk_1.ent-d1cvua2.ent", "d1urk_1.ent-d1dx5i1.ent", "d1urk_1.ent-d1emo_1.ent", "d1urk_1.ent-d1hz8a1.ent", "d1urk_1.ent-d1hz8a2.ent", "d1urk_1.ent-d1jl9a_.ent", "d1urk_1.ent-d1l3ya_.ent", "d1urk_1.ent-d1m1xb5.ent", "d1urk_1.ent-d1tpg_1.ent", "d1ush_2.ent-d1utea_.ent", "d1ush_2.ent-d4kbpa2.ent", "d1utea_.ent-d4kbpa2.ent", "d1uxc__.ent-d1vpwa1.ent", "d1uxc__.ent-d2cro__.ent", "d1uxd__.ent-d1vpwa1.ent", "d1vdra_.ent-d3dfr__.ent", "d1vhra_.ent-d1yfoa_.ent", "d1vhra_.ent-d2shpa1.ent", "d1vid__.ent-d1xvaa_.ent", "d1vid__.ent-d2dpma_.ent", "d1vid__.ent-d3mag__.ent", "d1vie__.ent-d1i07a_.ent", "d1vie__.ent-d1jo8a_.ent", "d1vie__.ent-d2ahjb_.ent", "d1vig__.ent-d2fmr__.ent", "d1vin_1.ent-d1vin_2.ent", "d1vin_1.ent-d1vola1.ent", "d1vin_2.ent-d1vola1.ent", "d1vpsa_.ent-d1a6ca1.ent", "d1vpsa_.ent-d1a6ca2.ent", "d1vpsa_.ent-d1a6ca3.ent", "d1vpsa_.ent-d1aym2_.ent", "d1vpsa_.ent-d1b35a_.ent", "d1vpsa_.ent-d1b35b_.ent", "d1vpsa_.ent-d1b35c_.ent", "d1vpsa_.ent-d1bev1_.ent", "d1vpsa_.ent-d1bev3_.ent", "d1vpsa_.ent-d1bmv1_.ent", "d1vpsa_.ent-d1c8na_.ent", "d1vpsa_.ent-d1cwpa_.ent", "d1vpsa_.ent-d1d4m1_.ent", "d1vpsa_.ent-d1ddla_.ent", "d1vpsa_.ent-d1f15a_.ent", "d1vpsa_.ent-d1k5ma_.ent", "d1vpsa_.ent-d1pvc1_.ent", "d1vpsa_.ent-d1qqp1_.ent", "d1vpsa_.ent-d1qqp2_.ent", "d1vpsa_.ent-d1qqp3_.ent", "d1vpsa_.ent-d1tmf1_.ent", "d1vpsa_.ent-d2bpa2_.ent", "d1vpsa_.ent-d2mev1_.ent", "d1vpsa_.ent-d2mev2_.ent", "d1vpsa_.ent-d2stv__.ent", "d1vpwa1.ent-d2cro__.ent", "d1vrta1.ent-d1xwl_1.ent", "d1vrta2.ent-d1xwl_2.ent", "d1vsra_.ent-d2foka4.ent", "d1vsra_.ent-d3pvia_.ent", "d1wad__.ent-d2ctha_.ent", "d1wad__.ent-d2cy3__.ent", "d1wad__.ent-d3caoa_.ent", "d1wad__.ent-d3cyr__.ent", "d1wapa_.ent-d2arca_.ent", "d1wba__.ent-d3btaa2.ent", "d1wdcb_.ent-d1eg3a1.ent", "d1wdcb_.ent-d1ggwa_.ent", "d1wdcb_.ent-d1jfja_.ent", "d1wdcb_.ent-d1m31a_.ent", "d1wdcb_.ent-d1rro__.ent", "d1wdcb_.ent-d2pvba_.ent", "d1wdcb_.ent-d5pal__.ent", "d1wdcc_.ent-d1eg3a1.ent", "d1wdcc_.ent-d1exra_.ent", "d1wdcc_.ent-d1ggwa_.ent", "d1wdcc_.ent-d1jfja_.ent", "d1wdcc_.ent-d1m31a_.ent", "d1wdcc_.ent-d1m45a_.ent", "d1wdcc_.ent-d1rro__.ent", "d1wdcc_.ent-d1sra__.ent", "d1wdcc_.ent-d1wdcb_.ent", "d1wdcc_.ent-d2pvba_.ent", "d1wdcc_.ent-d5pal__.ent", "d1wdna_.ent-d3mbp__.ent", "d1wdna_.ent-d3thia_.ent", "d1wsaa_.ent-d4pgaa_.ent", "d1xat__.ent-d3tdt__.ent", "d1xnaa_.ent-d1ciy_1.ent", "d1xnaa_.ent-d1dlc_1.ent", "d1xnaa_.ent-d1eut_2.ent", "d1xnaa_.ent-d1gmma_.ent", "d1xnaa_.ent-d1gu3a_.ent", "d1xnaa_.ent-d1ji6a1.ent", "d1xo1a2.ent-d2rsla_.ent", "d1xsoa_.ent-d1dqia_.ent", "d1xsoa_.ent-d1eaja_.ent", "d1xsoa_.ent-d1ej8a_.ent", "d1xsoa_.ent-d1grwa_.ent", "d1xsoa_.ent-d1j0ha1.ent", "d1xsoa_.ent-d1jmxa4.ent", "d1xsoa_.ent-d1kgce2.ent", "d1xsoa_.ent-d1kmta_.ent", "d1xsoa_.ent-d1kyfa1.ent", "d1xsoa_.ent-d1l9na1.ent", "d1xsoa_.ent-d1lmia_.ent", "d1xsoa_.ent-d1m1xa2.ent", "d1xsoa_.ent-d1m1xb1.ent", "d1xsoa_.ent-d1nepa_.ent", "d1xsoa_.ent-d1o75a1.ent", "d1xsoa_.ent-d1soxa1.ent", "d1xsoa_.ent-d1yaia_.ent", "d1xvaa_.ent-d1booa_.ent", "d1xvaa_.ent-d1eg2a_.ent", "d1xvaa_.ent-d1fp1d2.ent", "d1xvaa_.ent-d1fp2a2.ent", "d1xvaa_.ent-d1g60a_.ent", "d1xvaa_.ent-d1hnna_.ent", "d1xvaa_.ent-d1i1na_.ent", "d1xvaa_.ent-d1i9ga_.ent", "d1xvaa_.ent-d1inla_.ent", "d1xvaa_.ent-d1iy9a_.ent", "d1xvaa_.ent-d1jg1a_.ent", "d1xvaa_.ent-d1jqea_.ent", "d1xvaa_.ent-d1kywa2.ent", "d1xvaa_.ent-d1mjfa_.ent", "d1xvaa_.ent-d1qama_.ent", "d1xvaa_.ent-d1yub__.ent", "d1xvaa_.ent-d2dpma_.ent", "d1xvaa_.ent-d3mag__.ent", "d1xwl_1.ent-d1mwma2.ent", "d1yaaa_.ent-d1b9ha_.ent", "d1yaaa_.ent-d1bs0a_.ent", "d1yaaa_.ent-d1c7na_.ent", "d1yaaa_.ent-d1e5ea_.ent", "d1yaaa_.ent-d1gdea_.ent", "d1yaaa_.ent-d1j32a_.ent", "d1yaaa_.ent-d1jf9a_.ent", "d1yaaa_.ent-d1kl1a_.ent", "d1yaaa_.ent-d1n8pa_.ent", "d1yaaa_.ent-d1qisa_.ent", "d1yaaa_.ent-d2ay1a_.ent", "d1yaaa_.ent-d2oata_.ent", "d1yaaa_.ent-d3tata_.ent", "d1yaaa_.ent-d7aata_.ent", "d1ycc__.ent-d1co6a_.ent", "d1ycc__.ent-d1etpa2.ent", "d1ycc__.ent-d1hroa_.ent", "d1ycc__.ent-d1kb0a1.ent", "d1ycc__.ent-d1kv9a1.ent", "d1ycc__.ent-d1ql3a_.ent", "d1ycc__.ent-d1qn2a_.ent", "d1ycsb2.ent-d1i07a_.ent", "d1ycsb2.ent-d1jo8a_.ent", "d1ycsb2.ent-d1vie__.ent", "d1ycsb2.ent-d2hsp__.ent", "d1yfoa_.ent-d2shpa1.ent", "d1ytba1.ent-d1ytba2.ent", "d1ytba1.ent-d3pmga4.ent", "d1yua_1.ent-d1yua_2.ent", "d1yua_1.ent-d1zaka2.ent", "d1yua_1.ent-d1zin_2.ent", "d1yua_2.ent-d1zaka2.ent", "d1yua_2.ent-d1zin_2.ent", "d1yub__.ent-d1fp1d2.ent", "d1yub__.ent-d1fp2a2.ent", "d1yub__.ent-d1g60a_.ent", "d1yub__.ent-d1i1na_.ent", "d1yub__.ent-d1jg1a_.ent", "d1yub__.ent-d1kywa2.ent", "d1yub__.ent-d1qama_.ent", "d1yuja_.ent-d1zfd__.ent", "d1yuja_.ent-d2drpa1.ent", "d1yuja_.ent-d2glia1.ent", "d1yuja_.ent-d2glia2.ent", "d1yuja_.ent-d2glia4.ent", "d1yuja_.ent-d5znf__.ent", "d1zaga2.ent-d3frua2.ent", "d1zaka2.ent-d1zin_2.ent", "d1zfd__.ent-d2drpa1.ent", "d1zfd__.ent-d2glia1.ent", "d1zfd__.ent-d2glia2.ent", "d1zfd__.ent-d2glia4.ent", "d1zfd__.ent-d5znf__.ent", "d1zfo__.ent-d2nllb_.ent", "d1zfo__.ent-d3gata_.ent", "d1zfo__.ent-d7gata_.ent", "d1zmec1.ent-d2alca_.ent", "d1zpda2.ent-d1zpda3.ent", "d217l__.ent-d2eql__.ent", "d217l__.ent-d3lzt__.ent", "d256ba_.ent-d2a0b__.ent", "d256ba_.ent-d2ccya_.ent", "d256ba_.ent-d2liga_.ent", "d256ba_.ent-d2mhr__.ent", "d256ba_.ent-d3fapb_.ent", "d2a0b__.ent-d2liga_.ent", "d2a0b__.ent-d2mhr__.ent", "d2a0b__.ent-d3fapb_.ent", "d2aak__.ent-d2ucz__.ent", "d2abl_2.ent-d2cbla3.ent", "d2abl_2.ent-d2plda_.ent", "d2abl_2.ent-d2shpa3.ent", "d2act__.ent-d2cb5a_.ent", "d2act__.ent-d3gcb__.ent", "d2act__.ent-d7pcka_.ent", "d2ae2a_.ent-d1bgva1.ent", "d2ae2a_.ent-d1qsga_.ent", "d2ahjb_.ent-d1bb9__.ent", "d2ahjb_.ent-d1dj7b_.ent", "d2ahjb_.ent-d1fx7a3.ent", "d2ahjb_.ent-d1g3sa3.ent", "d2ahjb_.ent-d1gcqc_.ent", "d2ahjb_.ent-d1hyoa1.ent", "d2ahjb_.ent-d1i07a_.ent", "d2ahjb_.ent-d1i1ja_.ent", "d2ahjb_.ent-d1ixda_.ent", "d2ahjb_.ent-d1jb0e_.ent", "d2ahjb_.ent-d1jj2p_.ent", "d2ahjb_.ent-d1jj2s_.ent", "d2ahjb_.ent-d1jo8a_.ent", "d2ahjb_.ent-d1khia1.ent", "d2ahjb_.ent-d1kjwa1.ent", "d2ahjb_.ent-d1lpla_.ent", "d2ahjb_.ent-d1m1fa_.ent", "d2ahjb_.ent-d1m4za_.ent", "d2ahjb_.ent-d1m9sa2.ent", "d2ahjb_.ent-d1m9sa3.ent", "d2ahjb_.ent-d1pht__.ent", "d2ahjb_.ent-d1vie__.ent", "d2ahjb_.ent-d1ycsb2.ent", "d2ahjb_.ent-d3vub__.ent", "d2apr__.ent-d2rspa_.ent", "d2apr__.ent-d3psg__.ent", "d2apr__.ent-d4fiv__.ent", "d2ay1a_.ent-d1b9ha_.ent", "d2ay1a_.ent-d1bs0a_.ent", "d2ay1a_.ent-d1gdea_.ent", "d2ay1a_.ent-d1j32a_.ent", "d2ay1a_.ent-d1n8pa_.ent", "d2ayh__.ent-d1dhkb_.ent", "d2ayh__.ent-d1dyka1.ent", "d2ayh__.ent-d1dyka2.ent", "d2ayh__.ent-d1h30a1.ent", "d2ayh__.ent-d1h30a2.ent", "d2ayh__.ent-d1kit_1.ent", "d2ayh__.ent-d1kit_2.ent", "d2ayh__.ent-d1saca_.ent", "d2ayh__.ent-d1xnb__.ent", "d2ayh__.ent-d2sli_1.ent", "d2ayh__.ent-d3btaa1.ent", "d2bat__.ent-d2sli_2.ent", "d2bat__.ent-d3sil__.ent", "d2bb2_1.ent-d2bb2_2.ent", "d2bbva_.ent-d1a6ca1.ent", "d2bbva_.ent-d1a6ca2.ent", "d2bbva_.ent-d1a6ca3.ent", "d2bbva_.ent-d1aym1_.ent", "d2bbva_.ent-d1aym2_.ent", "d2bbva_.ent-d1b35a_.ent", "d2bbva_.ent-d1b35b_.ent", "d2bbva_.ent-d1b35c_.ent", "d2bbva_.ent-d1bev1_.ent", "d2bbva_.ent-d1bev3_.ent", "d2bbva_.ent-d1bmv1_.ent", "d2bbva_.ent-d1c8na_.ent", "d2bbva_.ent-d1cwpa_.ent", "d2bbva_.ent-d1d4m1_.ent", "d2bbva_.ent-d1ddla_.ent", "d2bbva_.ent-d1f15a_.ent", "d2bbva_.ent-d1k5ma_.ent", "d2bbva_.ent-d1pov0_.ent", "d2bbva_.ent-d1pvc1_.ent", "d2bbva_.ent-d1qqp1_.ent", "d2bbva_.ent-d1qqp2_.ent", "d2bbva_.ent-d1qqp3_.ent", "d2bbva_.ent-d1tmf1_.ent", "d2bbva_.ent-d1vpsa_.ent", "d2bbva_.ent-d2bpa2_.ent", "d2bbva_.ent-d2mev1_.ent", "d2bbva_.ent-d2mev2_.ent", "d2bbva_.ent-d2stv__.ent", "d2bce__.ent-d1ac5__.ent", "d2bce__.ent-d1bu8a2.ent", "d2bce__.ent-d1cpy__.ent", "d2bce__.ent-d1cr6a2.ent", "d2bce__.ent-d1cvl__.ent", "d2bce__.ent-d1hlga_.ent", "d2bce__.ent-d1ivya_.ent", "d2bce__.ent-d1iz7a_.ent", "d2bce__.ent-d1jjia_.ent", "d2bce__.ent-d1jkma_.ent", "d2bce__.ent-d1ju3a2.ent", "d2bce__.ent-d1k4ya_.ent", "d2bce__.ent-d1ku0a_.ent", "d2bce__.ent-d1l7aa_.ent", "d2bce__.ent-d1lnsa3.ent", "d2bce__.ent-d1lzla_.ent", "d2bce__.ent-d1qe3a_.ent", "d2bce__.ent-d1qlwa_.ent", "d2bce__.ent-d1qo7a_.ent", "d2bce__.ent-d1qtra_.ent", "d2bce__.ent-d1tca__.ent", "d2bpa1_.ent-d1a6ca1.ent", "d2bpa1_.ent-d1a6ca2.ent", "d2bpa1_.ent-d1a6ca3.ent", "d2bpa1_.ent-d1aym1_.ent", "d2bpa1_.ent-d1aym2_.ent", "d2bpa1_.ent-d1b35a_.ent", "d2bpa1_.ent-d1b35b_.ent", "d2bpa1_.ent-d1b35c_.ent", "d2bpa1_.ent-d1bev1_.ent", "d2bpa1_.ent-d1bev3_.ent", "d2bpa1_.ent-d1bmv1_.ent", "d2bpa1_.ent-d1bmv2_.ent", "d2bpa1_.ent-d1c8na_.ent", "d2bpa1_.ent-d1cwpa_.ent", "d2bpa1_.ent-d1d4m1_.ent", "d2bpa1_.ent-d1ddla_.ent", "d2bpa1_.ent-d1dnv__.ent", "d2bpa1_.ent-d1f15a_.ent", "d2bpa1_.ent-d1k5ma_.ent", "d2bpa1_.ent-d1novc_.ent", "d2bpa1_.ent-d1pov0_.ent", "d2bpa1_.ent-d1pvc1_.ent", "d2bpa1_.ent-d1qqp1_.ent", "d2bpa1_.ent-d1qqp2_.ent", "d2bpa1_.ent-d1qqp3_.ent", "d2bpa1_.ent-d1sva1_.ent", "d2bpa1_.ent-d1tmf1_.ent", "d2bpa1_.ent-d1vpsa_.ent", "d2bpa1_.ent-d2bbva_.ent", "d2bpa1_.ent-d2bpa2_.ent", "d2bpa1_.ent-d2mev1_.ent", "d2bpa1_.ent-d2mev2_.ent", "d2bpa1_.ent-d2stv__.ent", "d2bpa2_.ent-d1a6ca2.ent", "d2bpa2_.ent-d1a6ca3.ent", "d2bpa2_.ent-d1cwpa_.ent", "d2bpa2_.ent-d1f15a_.ent", "d2cb5a_.ent-d3gcb__.ent", "d2cb5a_.ent-d7pcka_.ent", "d2cbla1.ent-d2pvba_.ent", "d2cbla1.ent-d2sas__.ent", "d2cbla1.ent-d2scpa_.ent", "d2cbla3.ent-d2plda_.ent", "d2cbla3.ent-d2shpa3.ent", "d2cbp__.ent-d2cuaa_.ent", "d2chr_1.ent-d2mnr_1.ent", "d2chr_2.ent-d2mnr_2.ent", "d2cmd_2.ent-d5mdha2.ent", "d2cmd_2.ent-d7mdha2.ent", "d2cnd_1.ent-d2pia_1.ent", "d2cnd_2.ent-d2pia_2.ent", "d2ctha_.ent-d2cy3__.ent", "d2ctha_.ent-d3caoa_.ent", "d2ctha_.ent-d3cyr__.ent", "d2cy3__.ent-d3caoa_.ent", "d2cy3__.ent-d3cyr__.ent", "d2dkb__.ent-d1ajsa_.ent", "d2dkb__.ent-d1b9ha_.ent", "d2dkb__.ent-d1bs0a_.ent", "d2dkb__.ent-d1c7na_.ent", "d2dkb__.ent-d1e5ea_.ent", "d2dkb__.ent-d1gdea_.ent", "d2dkb__.ent-d1j32a_.ent", "d2dkb__.ent-d1jf9a_.ent", "d2dkb__.ent-d1kl1a_.ent", "d2dkb__.ent-d1m7ya_.ent", "d2dkb__.ent-d1n8pa_.ent", "d2dkb__.ent-d1qisa_.ent", "d2dkb__.ent-d1qj5a_.ent", "d2dkb__.ent-d1tpla_.ent", "d2dkb__.ent-d1yaaa_.ent", "d2dkb__.ent-d2ay1a_.ent", "d2dkb__.ent-d2gsaa_.ent", "d2dkb__.ent-d2oata_.ent", "d2dkb__.ent-d3tata_.ent", "d2dkb__.ent-d7aata_.ent", "d2dpma_.ent-d1fp1d2.ent", "d2dpma_.ent-d1fp2a2.ent", "d2dpma_.ent-d1g60a_.ent", "d2dpma_.ent-d1i1na_.ent", "d2dpma_.ent-d1jg1a_.ent", "d2dpma_.ent-d1kywa2.ent", "d2dpma_.ent-d1qama_.ent", "d2dpma_.ent-d1yub__.ent", "d2dpma_.ent-d3mag__.ent", "d2dri__.ent-d2liv__.ent", "d2dri__.ent-d8abp__.ent", "d2drpa1.ent-d2glia1.ent", "d2drpa1.ent-d2glia2.ent", "d2drpa1.ent-d2glia4.ent", "d2drpa1.ent-d5znf__.ent", "d2eql__.ent-d3lzt__.ent", "d2ezi__.ent-d1b72a_.ent", "d2ezi__.ent-d1b72b_.ent", "d2ezi__.ent-d1b8ia_.ent", "d2ezi__.ent-d1bl0a2.ent", "d2ezi__.ent-d1bw5__.ent", "d2ezi__.ent-d1d5ya2.ent", "d2ezi__.ent-d1e3oc1.ent", "d2ezi__.ent-d1fexa_.ent", "d2ezi__.ent-d1fjla_.ent", "d2ezi__.ent-d1g2ha_.ent", "d2ezi__.ent-d1hlva1.ent", "d2ezi__.ent-d1hlva2.ent", "d2ezi__.ent-d1ig7a_.ent", "d2ezi__.ent-d1irza_.ent", "d2ezi__.ent-d1iufa2.ent", "d2ezi__.ent-d1jt6a1.ent", "d2ezi__.ent-d1k61a_.ent", "d2ezi__.ent-d1k78a1.ent", "d2ezi__.ent-d1k78a2.ent", "d2ezi__.ent-d2tct_1.ent", "d2ezl__.ent-d1b72a_.ent", "d2ezl__.ent-d1b72b_.ent", "d2ezl__.ent-d1b8ia_.ent", "d2ezl__.ent-d1bjaa_.ent", "d2ezl__.ent-d1bl0a2.ent", "d2ezl__.ent-d1bw5__.ent", "d2ezl__.ent-d1d5va_.ent", "d2ezl__.ent-d1d5ya2.ent", "d2ezl__.ent-d1e3oc1.ent", "d2ezl__.ent-d1fexa_.ent", "d2ezl__.ent-d1fjla_.ent", "d2ezl__.ent-d1g2ha_.ent", "d2ezl__.ent-d1hlva1.ent", "d2ezl__.ent-d1hlva2.ent", "d2ezl__.ent-d1ig7a_.ent", "d2ezl__.ent-d1igna1.ent", "d2ezl__.ent-d1irza_.ent", "d2ezl__.ent-d1iufa1.ent", "d2ezl__.ent-d1iufa2.ent", "d2ezl__.ent-d1jt6a1.ent", "d2ezl__.ent-d1k61a_.ent", "d2ezl__.ent-d1k78a1.ent", "d2ezl__.ent-d1k78a2.ent", "d2ezl__.ent-d1smta_.ent", "d2ezl__.ent-d2ezi__.ent", "d2ezl__.ent-d2foka3.ent", "d2ezl__.ent-d2tct_1.ent", "d2f3ga_.ent-d2gpr__.ent", "d2fcr__.ent-d5nul__.ent", "d2fdn__.ent-d7fd1a_.ent", "d2foka1.ent-d1bjaa_.ent", "d2foka1.ent-d1bm9a_.ent", "d2foka1.ent-d1d5va_.ent", "d2foka1.ent-d1e17a_.ent", "d2foka1.ent-d1f1za1.ent", "d2foka1.ent-d1fc3a_.ent", "d2foka1.ent-d1fnna1.ent", "d2foka1.ent-d1fp1d1.ent", "d2foka1.ent-d1fp2a1.ent", "d2foka1.ent-d1fsha_.ent", "d2foka1.ent-d1fzpb_.ent", "d2foka1.ent-d1hks__.ent", "d2foka1.ent-d1hsja1.ent", "d2foka1.ent-d1ig6a_.ent", "d2foka1.ent-d1igna2.ent", "d2foka1.ent-d1jhga_.ent", "d2foka1.ent-d1ka8a_.ent", "d2foka1.ent-d1ldja1.ent", "d2foka1.ent-d1opc__.ent", "d2foka1.ent-d1repc1.ent", "d2foka1.ent-d1repc2.ent", "d2foka1.ent-d1smta_.ent", "d2foka1.ent-d2ezl__.ent", "d2foka1.ent-d2foka3.ent", "d2foka1.ent-d2irfg_.ent", "d2foka2.ent-d1bjaa_.ent", "d2foka2.ent-d1bm9a_.ent", "d2foka2.ent-d1d5va_.ent", "d2foka2.ent-d1e17a_.ent", "d2foka2.ent-d1f1za1.ent", "d2foka2.ent-d1fc3a_.ent", "d2foka2.ent-d1fnna1.ent", "d2foka2.ent-d1fp1d1.ent", "d2foka2.ent-d1fp2a1.ent", "d2foka2.ent-d1fsha_.ent", "d2foka2.ent-d1fzpb_.ent", "d2foka2.ent-d1hks__.ent", "d2foka2.ent-d1hsja1.ent", "d2foka2.ent-d1ig6a_.ent", "d2foka2.ent-d1igna2.ent", "d2foka2.ent-d1jhga_.ent", "d2foka2.ent-d1ka8a_.ent", "d2foka2.ent-d1ldja1.ent", "d2foka2.ent-d1opc__.ent", "d2foka2.ent-d1repc1.ent", "d2foka2.ent-d1repc2.ent", "d2foka2.ent-d1smta_.ent", "d2foka2.ent-d2ezl__.ent", "d2foka2.ent-d2foka1.ent", "d2foka2.ent-d2foka3.ent", "d2foka2.ent-d2irfg_.ent", "d2foka3.ent-d1d5va_.ent", "d2foka3.ent-d1e17a_.ent", "d2foka3.ent-d1fsha_.ent", "d2foka3.ent-d1ldja1.ent", "d2foka4.ent-d3pvia_.ent", "d2gdm__.ent-d1a6m__", "d2gdm__.ent-d1a6m__.ent", "d2gdm__.ent-d1ash__", "d2gdm__.ent-d1ash__.ent", "d2gdm__.ent-d1cg5a_", "d2gdm__.ent-d1cg5a_.ent", "d2gdm__.ent-d1cg5b_", "d2gdm__.ent-d1cg5b_.ent", "d2gdm__.ent-d1cqxa1", "d2gdm__.ent-d1cqxa1.ent", "d2gdm__.ent-d1ew6a_", "d2gdm__.ent-d1ew6a_.ent", "d2gdm__.ent-d1gcva_", "d2gdm__.ent-d1gcva_.ent", "d2gdm__.ent-d1gvha1", "d2gdm__.ent-d1gvha1.ent", "d2gdm__.ent-d1h97a_", "d2gdm__.ent-d1h97a_.ent", "d2gdm__.ent-d1irda_", "d2gdm__.ent-d1irda_.ent", "d2gdm__.ent-d1irdb_", "d2gdm__.ent-d1irdb_.ent", "d2gdm__.ent-d1it2a_", "d2gdm__.ent-d1it2a_.ent", "d2gdm__.ent-d1itha_", "d2gdm__.ent-d1itha_.ent", "d2gdm__.ent-d1jl7a_", "d2gdm__.ent-d1jl7a_.ent", "d2gdm__.ent-d1la6a_", "d2gdm__.ent-d1la6a_.ent", "d2gdm__.ent-d1mba__", "d2gdm__.ent-d1mba__.ent", "d2gdm__.ent-d2lhb__", "d2gdm__.ent-d2lhb__.ent", "d2gdm__.ent-d3sdha_", "d2gdm__.ent-d3sdha_.ent", "d2glia1.ent-d2glia2.ent", "d2glia1.ent-d2glia4.ent", "d2glia1.ent-d5znf__.ent", "d2glia2.ent-d2glia4.ent", "d2glia2.ent-d5znf__.ent", "d2glia4.ent-d5znf__.ent", "d2gmfa_.ent-d2ilk__.ent", "d2gsaa_.ent-d1ajsa_.ent", "d2gsaa_.ent-d1b9ha_.ent", "d2gsaa_.ent-d1bs0a_.ent", "d2gsaa_.ent-d1c7na_.ent", "d2gsaa_.ent-d1e5ea_.ent", "d2gsaa_.ent-d1gdea_.ent", "d2gsaa_.ent-d1j32a_.ent", "d2gsaa_.ent-d1jf9a_.ent", "d2gsaa_.ent-d1kl1a_.ent", "d2gsaa_.ent-d1m7ya_.ent", "d2gsaa_.ent-d1n8pa_.ent", "d2gsaa_.ent-d1qisa_.ent", "d2gsaa_.ent-d1tpla_.ent", "d2gsaa_.ent-d1yaaa_.ent", "d2gsaa_.ent-d2ay1a_.ent", "d2gsaa_.ent-d2oata_.ent", "d2gsaa_.ent-d3tata_.ent", "d2gsaa_.ent-d7aata_.ent", "d2gsq_1.ent-d2gsta1.ent", "d2hcc__.ent-d3il8__.ent", "d2hft_1.ent-d1cd9b2.ent", "d2hft_1.ent-d1cfb_1.ent", "d2hft_1.ent-d1egja_.ent", "d2hft_1.ent-d1f6fb1.ent", "d2hft_1.ent-d1f6fb2.ent", "d2hft_1.ent-d1fyhb1.ent", "d2hft_1.ent-d1i1ra1.ent", "d2hft_1.ent-d1lqsr1.ent", "d2hft_2.ent-d1cd9b2.ent", "d2hft_2.ent-d1cfb_1.ent", "d2hft_2.ent-d1egja_.ent", "d2hft_2.ent-d1f6fb1.ent", "d2hft_2.ent-d1f6fb2.ent", "d2hft_2.ent-d1fyhb1.ent", "d2hft_2.ent-d1i1ra1.ent", "d2hft_2.ent-d1lqsr1.ent", "d2hft_2.ent-d1n26a2.ent", "d2hft_2.ent-d2hft_1.ent", "d2hlca_.ent-d1azza_.ent", "d2hlca_.ent-d1bio__.ent", "d2hlca_.ent-d1cgha_.ent", "d2hlca_.ent-d1gdna_.ent", "d2hlca_.ent-d1hj9a_.ent", "d2hpqp_.ent-d5hpga_.ent", "d2irfg_.ent-d1bjaa_.ent", "d2irfg_.ent-d1d5va_.ent", "d2irfg_.ent-d1e17a_.ent", "d2irfg_.ent-d1f1za1.ent", "d2irfg_.ent-d1fnna1.ent", "d2irfg_.ent-d1fp2a1.ent", "d2irfg_.ent-d1fsha_.ent", "d2irfg_.ent-d1fzpb_.ent", "d2irfg_.ent-d1hks__.ent", "d2irfg_.ent-d1ig6a_.ent", "d2irfg_.ent-d1igna2.ent", "d2irfg_.ent-d1jhga_.ent", "d2irfg_.ent-d1ka8a_.ent", "d2irfg_.ent-d1ldja1.ent", "d2irfg_.ent-d1opc__.ent", "d2irfg_.ent-d1repc2.ent", "d2irfg_.ent-d1smta_.ent", "d2irfg_.ent-d2ezl__.ent", "d2irfg_.ent-d2foka3.ent", "d2lhb__.ent-d1ash__", "d2lhb__.ent-d1ash__.ent", "d2lhb__.ent-d1cg5a_", "d2lhb__.ent-d1cg5a_.ent", "d2lhb__.ent-d1cg5b_", "d2lhb__.ent-d1cg5b_.ent", "d2lhb__.ent-d1ew6a_", "d2lhb__.ent-d1ew6a_.ent", "d2lhb__.ent-d1gcva_", "d2lhb__.ent-d1gcva_.ent", "d2lhb__.ent-d1gvha1", "d2lhb__.ent-d1gvha1.ent", "d2lhb__.ent-d1h97a_", "d2lhb__.ent-d1h97a_.ent", "d2lhb__.ent-d1irda_", "d2lhb__.ent-d1irda_.ent", "d2lhb__.ent-d1irdb_", "d2lhb__.ent-d1irdb_.ent", "d2lhb__.ent-d1it2a_", "d2lhb__.ent-d1it2a_.ent", "d2lhb__.ent-d1itha_", "d2lhb__.ent-d1itha_.ent", "d2lhb__.ent-d1jl7a_", "d2lhb__.ent-d1jl7a_.ent", "d2lhb__.ent-d1la6a_", "d2lhb__.ent-d1la6a_.ent", "d2lhb__.ent-d1mba__", "d2lhb__.ent-d1mba__.ent", "d2lhb__.ent-d3sdha_", "d2lhb__.ent-d3sdha_.ent", "d2liga_.ent-d2mhr__.ent", "d2liga_.ent-d3fapb_.ent", "d2liv__.ent-d8abp__.ent", "d2mev1_.ent-d1a6ca1.ent", "d2mev1_.ent-d1a6ca2.ent", "d2mev1_.ent-d1a6ca3.ent", "d2mev1_.ent-d1aym2_.ent", "d2mev1_.ent-d1b35a_.ent", "d2mev1_.ent-d1b35b_.ent", "d2mev1_.ent-d1bev3_.ent", "d2mev1_.ent-d1bmv1_.ent", "d2mev1_.ent-d1c8na_.ent", "d2mev1_.ent-d1cwpa_.ent", "d2mev1_.ent-d1ddla_.ent", "d2mev1_.ent-d1f15a_.ent", "d2mev1_.ent-d1qqp1_.ent", "d2mev1_.ent-d1qqp2_.ent", "d2mev1_.ent-d1qqp3_.ent", "d2mev1_.ent-d2bpa2_.ent", "d2mev1_.ent-d2mev2_.ent", "d2mev1_.ent-d2stv__.ent", "d2mev2_.ent-d1bev3_.ent", "d2mhr__.ent-d3fapb_.ent", "d2mpra_.ent-d2por__.ent", "d2mpra_.ent-d3prn__.ent", "d2msta_.ent-d2u1a__.ent", "d2msta_.ent-d2u2fa_.ent", "d2naca1.ent-d1bg6_2.ent", "d2naca1.ent-d1cf2o1.ent", "d2naca1.ent-d1dssg1.ent", "d2naca1.ent-d1e5qa1.ent", "d2naca1.ent-d1lc0a1.ent", "d2naca1.ent-d2pgd_2.ent", "d2naca2.ent-d1cf9a1.ent", "d2naca2.ent-d1e5da1.ent", "d2naca2.ent-d1euca2.ent", "d2naca2.ent-d1f4pa_.ent", "d2naca2.ent-d1f8ya_.ent", "d2naca2.ent-d1fuea_.ent", "d2naca2.ent-d1h05a_.ent", "d2naca2.ent-d7reqb2.ent", "d2ncda_.ent-d1bg2__.ent", "d2ncda_.ent-d1c4oa1.ent", "d2ncda_.ent-d1e2ka_.ent", "d2ncda_.ent-d1f9va_.ent", "d2ncda_.ent-d1fmja_.ent", "d2ncda_.ent-d1g41a_.ent", "d2ncda_.ent-d1g8pa_.ent", "d2ncda_.ent-d1i6ia_.ent", "d2ncda_.ent-d1ii6a_.ent", "d2ncda_.ent-d1ksfx3.ent", "d2ncda_.ent-d1n0ua2.ent", "d2ncda_.ent-d1pjr_1.ent", "d2ncda_.ent-d1pjr_2.ent", "d2ncda_.ent-d1uaaa1.ent", "d2ncda_.ent-d1uaaa2.ent", "d2nllb_.ent-d3gata_.ent", "d2nllb_.ent-d7gata_.ent", "d2nlra_.ent-d1dhkb_.ent", "d2nlra_.ent-d1dyka1.ent", "d2nlra_.ent-d1dyka2.ent", "d2nlra_.ent-d1epwa1.ent", "d2nlra_.ent-d1h30a1.ent", "d2nlra_.ent-d1h30a2.ent", "d2nlra_.ent-d1kit_1.ent", "d2nlra_.ent-d1kit_2.ent", "d2nlra_.ent-d1saca_.ent", "d2nlra_.ent-d1xnb__.ent", "d2nlra_.ent-d2ayh__.ent", "d2nlra_.ent-d2sli_1.ent", "d2nlra_.ent-d3btaa1.ent", "d2oata_.ent-d1b9ha_.ent", "d2oata_.ent-d1bs0a_.ent", "d2oata_.ent-d1c7na_.ent", "d2oata_.ent-d1e5ea_.ent", "d2oata_.ent-d1gdea_.ent", "d2oata_.ent-d1j32a_.ent", "d2oata_.ent-d1n8pa_.ent", "d2oata_.ent-d1qisa_.ent", "d2oata_.ent-d2ay1a_.ent", "d2oata_.ent-d3tata_.ent", "d2oata_.ent-d7aata_.ent", "d2pela_.ent-d1dhkb_.ent", "d2pela_.ent-d1dyka1.ent", "d2pela_.ent-d1dyka2.ent", "d2pela_.ent-d1epwa1.ent", "d2pela_.ent-d1gv9a_.ent", "d2pela_.ent-d1h30a1.ent", "d2pela_.ent-d1h30a2.ent", "d2pela_.ent-d1kit_1.ent", "d2pela_.ent-d1kit_2.ent", "d2pela_.ent-d1n1ta1.ent", "d2pela_.ent-d1saca_.ent", "d2pela_.ent-d1xnb__.ent", "d2pela_.ent-d2ayh__.ent", "d2pela_.ent-d2nlra_.ent", "d2pela_.ent-d2sli_1.ent", "d2pela_.ent-d3btaa1.ent", "d2pgd_2.ent-d1cf2o1.ent", "d2pgd_2.ent-d1dssg1.ent", "d2pgd_2.ent-d1lc0a1.ent", "d2phla1.ent-d2phla2.ent", "d2plc__.ent-d2ptd__.ent", "d2plda_.ent-d2shpa3.ent", "d2pola1.ent-d2pola2.ent", "d2pola1.ent-d2pola3.ent", "d2pola2.ent-d2pola3.ent", "d2por__.ent-d3prn__.ent", "d2pvba_.ent-d1m31a_.ent", "d2pvba_.ent-d2sas__.ent", "d2pvba_.ent-d2scpa_.ent", "d2rhe__.ent-d1bec_1.ent", "d2rhe__.ent-d1c5ch1.ent", "d2rhe__.ent-d1dlfl_.ent", "d2rhe__.ent-d1h5ba_.ent", "d2rhe__.ent-d1nfdb1.ent", "d2rspa_.ent-d3psg__.ent", "d2rspa_.ent-d4fiv__.ent", "d2sak__.ent-d1ayfa_.ent", "d2sak__.ent-d1bmlc3.ent", "d2sak__.ent-d1c9fa_.ent", "d2sak__.ent-d1czpa_.ent", "d2sak__.ent-d1f52a1.ent", "d2sak__.ent-d1fm0d_.ent", "d2sak__.ent-d1gnua_.ent", "d2sak__.ent-d1h4ra3.ent", "d2sak__.ent-d1h8ca_.ent", "d2sak__.ent-d1i42a_.ent", "d2sak__.ent-d1ip9a_.ent", "d2sak__.ent-d1k8rb_.ent", "d2sak__.ent-d1l4db_.ent", "d2sak__.ent-d1l5pa_.ent", "d2sak__.ent-d1l7ya_.ent", "d2sak__.ent-d1lfda_.ent", "d2sak__.ent-d1lm8b_.ent", "d2sak__.ent-d1qlab2.ent", "d2sak__.ent-d3seb_2.ent", "d2sak__.ent-d3tss_2.ent", "d2sas__.ent-d1alva_.ent", "d2sas__.ent-d1auib_.ent", "d2sas__.ent-d1df0a1.ent", "d2sas__.ent-d1dgua_.ent", "d2sas__.ent-d1eg3a1.ent", "d2sas__.ent-d1exra_.ent", "d2sas__.ent-d1g8ia_.ent", "d2sas__.ent-d1ggwa_.ent", "d2sas__.ent-d1hqva_.ent", "d2sas__.ent-d1jfja_.ent", "d2sas__.ent-d1k94a_.ent", "d2sas__.ent-d1m31a_.ent", "d2sas__.ent-d1m45a_.ent", "d2sas__.ent-d1ncx__.ent", "d2sas__.ent-d1rro__.ent", "d2sas__.ent-d1sra__.ent", "d2sas__.ent-d1wdcb_.ent", "d2sas__.ent-d1wdcc_.ent", "d2sas__.ent-d2pvba_.ent", "d2sas__.ent-d2scpa_.ent", "d2sas__.ent-d5pal__.ent", "d2scpa_.ent-d1alva_.ent", "d2scpa_.ent-d1auib_.ent", "d2scpa_.ent-d1eg3a1.ent", "d2scpa_.ent-d1exra_.ent", "d2scpa_.ent-d1ggwa_.ent", "d2scpa_.ent-d1jfja_.ent", "d2scpa_.ent-d1k94a_.ent", "d2scpa_.ent-d1m31a_.ent", "d2scpa_.ent-d1m45a_.ent", "d2scpa_.ent-d1ncx__.ent", "d2scpa_.ent-d1rro__.ent", "d2scpa_.ent-d1sra__.ent", "d2scpa_.ent-d1wdcb_.ent", "d2scpa_.ent-d1wdcc_.ent", "d2scpa_.ent-d2pvba_.ent", "d2scpa_.ent-d5pal__.ent", "d2sli_1.ent-d1dhkb_.ent", "d2sli_1.ent-d1dyka1.ent", "d2sli_1.ent-d1dyka2.ent", "d2sli_1.ent-d1h30a1.ent", "d2sli_1.ent-d1kit_1.ent", "d2sli_1.ent-d1xnb__.ent", "d2sli_2.ent-d3sil__.ent", "d2sn3__.ent-d1agg__.ent", "d2sn3__.ent-d1aho__.ent", "d2sn3__.ent-d1apq__.ent", "d2sn3__.ent-d1b9wa1.ent", "d2sn3__.ent-d1b9wa2.ent", "d2sn3__.ent-d1bx7__.ent", "d2sn3__.ent-d1c2aa1.ent", "d2sn3__.ent-d1cixa_.ent", "d2sn3__.ent-d1e0fi_.ent", "d2sn3__.ent-d1flei_.ent", "d2sn3__.ent-d1g9pa_.ent", "d2sn3__.ent-d1gps__.ent", "d2sn3__.ent-d1h59b_.ent", "d2sn3__.ent-d1hyka_.ent", "d2sn3__.ent-d1i2ua_.ent", "d2sn3__.ent-d1ijqa2.ent", "d2sn3__.ent-d1imt_2.ent", "d2sn3__.ent-d1jkza_.ent", "d2sn3__.ent-d1klil_.ent", "d2sn3__.ent-d1klo_1.ent", "d2sn3__.ent-d1klo_3.ent", "d2sn3__.ent-d1lpba2.ent", "d2sn3__.ent-d4htci_.ent", "d2sqca1.ent-d2sqca2.ent", "d2sqca1.ent-d5eau_1.ent", "d2sqca2.ent-d5eau_1.ent", "d2stv__.ent-d1a6ca1.ent", "d2stv__.ent-d1a6ca2.ent", "d2stv__.ent-d1a6ca3.ent", "d2stv__.ent-d1cwpa_.ent", "d2stv__.ent-d1f15a_.ent", "d2stv__.ent-d2bpa2_.ent", "d2tct_1.ent-d1b8ia_.ent", "d2tct_1.ent-d1bl0a2.ent", "d2tct_1.ent-d1d5ya2.ent", "d2tct_1.ent-d1e3oc1.ent", "d2tct_1.ent-d1fexa_.ent", "d2tct_1.ent-d1fjla_.ent", "d2tct_1.ent-d1g2ha_.ent", "d2tct_1.ent-d1hlva2.ent", "d2tct_1.ent-d1ig7a_.ent", "d2tct_1.ent-d1irza_.ent", "d2tct_1.ent-d1k61a_.ent", "d2tct_1.ent-d1k78a1.ent", "d2tct_1.ent-d1k78a2.ent", "d2trxa_.ent-d1a8l_2.ent", "d2trxa_.ent-d1erv__.ent", "d2trxa_.ent-d1fb6a_.ent", "d2trxa_.ent-d1gh2a_.ent", "d2trxa_.ent-d1kte__.ent", "d2trxa_.ent-d1quwa_.ent", "d2u1a__.ent-d2u2fa_.ent", "d3btaa1.ent-d1dhkb_.ent", "d3btaa1.ent-d1dyka1.ent", "d3btaa1.ent-d1dyka2.ent", "d3btaa1.ent-d1h30a1.ent", "d3btaa1.ent-d1h30a2.ent", "d3btaa1.ent-d1kit_1.ent", "d3btaa1.ent-d1kit_2.ent", "d3btaa1.ent-d1saca_.ent", "d3btaa1.ent-d1xnb__.ent", "d3btaa1.ent-d2sli_1.ent", "d3c2c__.ent-d1co6a_.ent", "d3c2c__.ent-d1etpa2.ent", "d3c2c__.ent-d1hroa_.ent", "d3c2c__.ent-d1kb0a1.ent", "d3c2c__.ent-d1kv9a1.ent", "d3c2c__.ent-d1ql3a_.ent", "d3c2c__.ent-d1qn2a_.ent", "d3c2c__.ent-d1ycc__.ent", "d3caoa_.ent-d3cyr__.ent", "d3chbd_.ent-d3seb_1.ent", "d3chbd_.ent-d3tss_1.ent", "d3crd__.ent-d3ygsp_.ent", "d3gata_.ent-d7gata_.ent", "d3gcb__.ent-d7pcka_.ent", "d3grs_1.ent-d3grs_2.ent", "d3grs_3.ent-d3lada3.ent", "d3lada1.ent-d1cjca1.ent", "d3lada1.ent-d1ebda1.ent", "d3mag__.ent-d1booa_.ent", "d3mag__.ent-d1eg2a_.ent", "d3mag__.ent-d1fp1d2.ent", "d3mag__.ent-d1fp2a2.ent", "d3mag__.ent-d1g60a_.ent", "d3mag__.ent-d1hnna_.ent", "d3mag__.ent-d1i1na_.ent", "d3mag__.ent-d1i9ga_.ent", "d3mag__.ent-d1inla_.ent", "d3mag__.ent-d1iy9a_.ent", "d3mag__.ent-d1jg1a_.ent", "d3mag__.ent-d1jqea_.ent", "d3mag__.ent-d1kywa2.ent", "d3mag__.ent-d1mjfa_.ent", "d3mag__.ent-d1qama_.ent", "d3mag__.ent-d1yub__.ent", "d3mag__.ent-d2dpma_.ent", "d3mbp__.ent-d3thia_.ent", "d3pmga1.ent-d3pmga2.ent", "d3pmga1.ent-d3pmga3.ent", "d3pmga2.ent-d3pmga3.ent", "d3proc1.ent-d3proc2.ent", "d3psg__.ent-d4fiv__.ent", "d3sdha_.ent-d1cg5a_", "d3sdha_.ent-d1cg5a_.ent", "d3sdha_.ent-d1cg5b_", "d3sdha_.ent-d1cg5b_.ent", "d3sdha_.ent-d1ew6a_", "d3sdha_.ent-d1ew6a_.ent", "d3sdha_.ent-d1gcva_", "d3sdha_.ent-d1gcva_.ent", "d3sdha_.ent-d1irda_", "d3sdha_.ent-d1irda_.ent", "d3sdha_.ent-d1itha_", "d3sdha_.ent-d1itha_.ent", "d3sdha_.ent-d1la6a_", "d3sdha_.ent-d1la6a_.ent", "d3seb_1.ent-d3tss_1.ent", "d3seb_2.ent-d1ayfa_.ent", "d3seb_2.ent-d1bmlc3.ent", "d3seb_2.ent-d1c9fa_.ent", "d3seb_2.ent-d1czpa_.ent", "d3seb_2.ent-d1f52a1.ent", "d3seb_2.ent-d1fm0d_.ent", "d3seb_2.ent-d1h4ra3.ent", "d3seb_2.ent-d1h8ca_.ent", "d3seb_2.ent-d1i42a_.ent", "d3seb_2.ent-d1ip9a_.ent", "d3seb_2.ent-d1k8rb_.ent", "d3seb_2.ent-d1l4db_.ent", "d3seb_2.ent-d1l5pa_.ent", "d3seb_2.ent-d1l7ya_.ent", "d3seb_2.ent-d1lfda_.ent", "d3seb_2.ent-d1lm8b_.ent", "d3seb_2.ent-d1qlab2.ent", "d3seb_2.ent-d3tss_2.ent", "d3tata_.ent-d1b9ha_.ent", "d3tata_.ent-d1bs0a_.ent", "d3tata_.ent-d1c7na_.ent", "d3tata_.ent-d1e5ea_.ent", "d3tata_.ent-d1gdea_.ent", "d3tata_.ent-d1j32a_.ent", "d3tata_.ent-d1n8pa_.ent", "d3tata_.ent-d1qisa_.ent", "d3tata_.ent-d2ay1a_.ent", "d3tgf__.ent-d1b9wa1.ent", "d3tgf__.ent-d1b9wa2.ent", "d3tgf__.ent-d1ceja1.ent", "d3tgf__.ent-d1cvua2.ent", "d3tgf__.ent-d1dx5i1.ent", "d3tgf__.ent-d1emo_1.ent", "d3tgf__.ent-d1hz8a1.ent", "d3tgf__.ent-d1hz8a2.ent", "d3tgf__.ent-d1jl9a_.ent", "d3tgf__.ent-d1l3ya_.ent", "d3tgf__.ent-d1m1xb5.ent", "d3tgf__.ent-d1tpg_1.ent", "d3tgf__.ent-d1urk_1.ent", "d3tss_2.ent-d1bmlc3.ent", "d3tss_2.ent-d1c9fa_.ent", "d3tss_2.ent-d1czpa_.ent", "d3tss_2.ent-d1f52a1.ent", "d3tss_2.ent-d1fm0d_.ent", "d3tss_2.ent-d1h4ra3.ent", "d3tss_2.ent-d1h8ca_.ent", "d3tss_2.ent-d1i42a_.ent", "d3tss_2.ent-d1ip9a_.ent", "d3tss_2.ent-d1k8rb_.ent", "d3tss_2.ent-d1l5pa_.ent", "d3tss_2.ent-d1l7ya_.ent", "d3tss_2.ent-d1lfda_.ent", "d3vub__.ent-d1bb9__.ent", "d3vub__.ent-d1dj7b_.ent", "d3vub__.ent-d1fx7a3.ent", "d3vub__.ent-d1g3sa3.ent", "d3vub__.ent-d1gcqc_.ent", "d3vub__.ent-d1i07a_.ent", "d3vub__.ent-d1jb0e_.ent", "d3vub__.ent-d1jj2p_.ent", "d3vub__.ent-d1jo8a_.ent", "d3vub__.ent-d1khia1.ent", "d3vub__.ent-d1kjwa1.ent", "d3vub__.ent-d1lpla_.ent", "d3vub__.ent-d1m9sa2.ent", "d3vub__.ent-d1m9sa3.ent", "d3vub__.ent-d1pht__.ent", "d3vub__.ent-d1vie__.ent", "d3vub__.ent-d1ycsb2.ent", "d4htci_.ent-d1agg__.ent", "d4htci_.ent-d1apq__.ent", "d4htci_.ent-d1b9wa1.ent", "d4htci_.ent-d1b9wa2.ent", "d4htci_.ent-d1bx7__.ent", "d4htci_.ent-d1cixa_.ent", "d4htci_.ent-d1e0fi_.ent", "d4htci_.ent-d1flei_.ent", "d4htci_.ent-d1g9pa_.ent", "d4htci_.ent-d1gps__.ent", "d4htci_.ent-d1h59b_.ent", "d4htci_.ent-d1hyka_.ent", "d4htci_.ent-d1i2ua_.ent", "d4htci_.ent-d1ijqa2.ent", "d4htci_.ent-d1imt_2.ent", "d4htci_.ent-d1jkza_.ent", "d4htci_.ent-d1klo_1.ent", "d4htci_.ent-d1klo_3.ent", "d4htci_.ent-d1lpba2.ent", "d5mdha2.ent-d7mdha2.ent", "d5pal__.ent-d1m31a_.ent", "d5pal__.ent-d1rro__.ent", "d5pal__.ent-d2pvba_.ent", "d6mhta_.ent-d1booa_.ent", "d6mhta_.ent-d1dcta_.ent", "d6mhta_.ent-d1eg2a_.ent", "d6mhta_.ent-d1f3la_.ent", "d6mhta_.ent-d1fp1d2.ent", "d6mhta_.ent-d1fp2a2.ent", "d6mhta_.ent-d1g60a_.ent", "d6mhta_.ent-d1hnna_.ent", "d6mhta_.ent-d1i1na_.ent", "d6mhta_.ent-d1i4wa_.ent", "d6mhta_.ent-d1i9ga_.ent", "d6mhta_.ent-d1inla_.ent", "d6mhta_.ent-d1iy9a_.ent", "d6mhta_.ent-d1jg1a_.ent", "d6mhta_.ent-d1jqea_.ent", "d6mhta_.ent-d1kywa2.ent", "d6mhta_.ent-d1mjfa_.ent", "d6mhta_.ent-d1qama_.ent", "d6mhta_.ent-d1xvaa_.ent", "d6mhta_.ent-d1yub__.ent", "d6mhta_.ent-d2dpma_.ent", "d6mhta_.ent-d3mag__.ent", "d7aata_.ent-d1b9ha_.ent", "d7aata_.ent-d1bs0a_.ent", "d7aata_.ent-d1c7na_.ent", "d7aata_.ent-d1e5ea_.ent", "d7aata_.ent-d1gdea_.ent", "d7aata_.ent-d1j32a_.ent", "d7aata_.ent-d1n8pa_.ent", "d7aata_.ent-d1qisa_.ent", "d7aata_.ent-d2ay1a_.ent", "d7aata_.ent-d3tata_.ent", "d7reqa1.ent-d1ccwb_.ent", "d7reqa1.ent-d1cz1a_.ent", "d7reqa1.ent-d1d3ga_.ent", "d7reqa1.ent-d1e4mm_.ent", "d7reqa1.ent-d1edg__.ent", "d7reqa1.ent-d1eexa_.ent", "d7reqa1.ent-d1eswa_.ent", "d7reqa1.ent-d1f8ma_.ent", "d7reqa1.ent-d1g5aa2.ent", "d7reqa1.ent-d1gvoa_.ent", "d7reqa1.ent-d1gw1a_.ent", "d7reqa1.ent-d1iexa1.ent", "d7reqa1.ent-d1itua_.ent", "d7reqa1.ent-d1j5sa_.ent", "d7reqa1.ent-d1k4ga_.ent", "d7reqa1.ent-d1kbla1.ent", "d7reqa1.ent-d1kwga2.ent", "d7reqa1.ent-d1m7ja3.ent", "d7reqa1.ent-d1muwa_.ent", "d7reqa1.ent-d1ntha_.ent", "d7reqa1.ent-d7reqb1.ent", "d7reqa2.ent-d7reqb2.ent", "d7reqb2.ent-d1cf9a1.ent", "d7reqb2.ent-d1e5da1.ent", "d7reqb2.ent-d1f4pa_.ent", "d7reqb2.ent-d1f8ya_.ent", "d7reqb2.ent-d1h05a_.ent", }; ugene-1.9.8/src/libs_3rdparty/qscore/src/qscore/seq.h0000644000175000017500000000322211651544307021207 0ustar ilyailya#ifndef Seq_h #define Seq_h #include class TextFile; class MSA_QScore; typedef std::vector CharVect; class Seq : public CharVect { public: Seq() { m_ptrName = 0; // Start with moderate size to avoid // thrashing the heap. reserve(200); } virtual ~Seq() { delete[] m_ptrName; } private: // Not implemented; prevent use of copy c'tor and assignment. Seq(const Seq &); Seq &operator=(const Seq &); public: void Clear() { clear(); delete[] m_ptrName; m_ptrName = 0; m_uId = uInsane; } const char *GetName() const { return m_ptrName; } unsigned GetId() const { if (uInsane == m_uId) Quit_Qscore("Seq::GetId, id not set"); return m_uId; } void SetId(unsigned uId) { m_uId = uId; } bool FromFASTAFile(TextFile &File); void ToFASTAFile(TextFile &File) const; void ExtractUngapped(MSA_QScore &msa) const; void FromString(const char *pstrSeq, const char *pstrName); void Copy(const Seq &rhs); void CopyReversed(const Seq &rhs); void StripGaps(); void ToUpper(); void SetName(const char *ptrName); unsigned GetLetter(unsigned uIndex) const; unsigned Length() const { return (unsigned) size(); } bool EqIgnoreCase(const Seq &s) const; bool EqIgnoreCaseAndGaps(const Seq &s) const; bool HasGap() const; unsigned GetUngappedLength() const; void ListMe() const; char GetChar(unsigned uIndex) const { return operator[](uIndex); } void SetChar(unsigned uIndex, char c) { operator[](uIndex) = c; } #ifndef _WIN32 reference at(size_type i) { return operator[](i); } const_reference at(size_type i) const { return operator[](i); } #endif private: char *m_ptrName; unsigned m_uId; }; #endif // Seq.h ugene-1.9.8/src/libs_3rdparty/qscore/src/qscore/qscore_sab.cpp0000644000175000017500000000412411651544307023075 0ustar ilyailya#include "qscore.h" #include "sab_ref2.h" #include "sab_ids.h" #ifdef _MSC_VER #include #undef chdir #define chdir _chdir #else #include #endif #define array_n(x) (sizeof(x)/sizeof(x[0])) const unsigned nrefs = array_n(SAB_Ref2Filenames); const unsigned nids = array_n(SAB_Ids); static map RefMSAs; MSA_QScore &GetRef(const string &Label1, const string &Label2) { string Name = Label1 + string("-") + Label2; map::iterator p = RefMSAs.find(Name); if (p != RefMSAs.end()) return *p->second; Name = Label2 + string("-") + Label1; p = RefMSAs.find(Name); if (p == RefMSAs.end()) Quit_Qscore("SAB ref %s not found", Name.c_str()); return *p->second; } static double SAB1(const char *FileName, MSA_QScore &TestMSA) { double SumQ = 0.0; unsigned PairCount = 0; const unsigned SeqCount = TestMSA.GetSeqCount(); for (unsigned i = 0; i < SeqCount; ++i) { const string Label1 = TestMSA.GetSeqName(i); for (unsigned j = i + 1; j < SeqCount; ++j) { const string Label2 = TestMSA.GetSeqName(j); MSA_QScore &RefMSA = GetRef(Label1, Label2); double Q; double TC; FastQ(TestMSA, RefMSA, Q, TC); SumQ += Q; ++PairCount; } } return PairCount == 0 ? 0 : SumQ/PairCount; } void SAB() { const char *TestDir = ValueOpt_QScore("sab_test"); const char *RefDir = ValueOpt_QScore("sab_ref"); chdir(RefDir); for (unsigned i = 0; i < nrefs; ++i) { //if (i%100 == 0) //k_printf( "Reading refs %u/%u\r", i, nrefs); MSA_QScore *msa = new MSA_QScore; const char *FileName = SAB_Ref2Filenames[i]; FILE *f = OpenStdioFile(FileName); msa->FromFASTAFile(f); fclose(f); RefMSAs[FileName] = msa; } //k_printf( "\n"); chdir(TestDir); double SumQ = 0.0; for (unsigned i = 0; i < nids; ++i) { const char *FileName = SAB_Ids[i]; FILE *f = OpenStdioFile(FileName); MSA_QScore TestMSA; TestMSA.FromFASTAFile(f); fclose(f); double Q = SAB1(FileName, TestMSA); //printf("Ref=SAB;Test=%s;Q=%.4f\n", FileName, Q); SumQ += Q; } //k_printf( "\n"); //k_printf( "Q=%7.4f %s\n", RefDir, SumQ/nids); } ugene-1.9.8/src/libs_3rdparty/qscore/src/qscore/qscore_fasta.cpp0000644000175000017500000000617711651544307023440 0ustar ilyailya#include "qscore.h" /*** Strip trailing whitespace from FASTA annotation and truncate at first whitespace or comma (-truncname option). ***/ static void FixLabel(std::string &Label) { // Truncate trailing whitespace const char *WhiteSpace = " \t\n\r"; size_t n = Label.find_last_of(WhiteSpace); if (n != std::string::npos) Label.erase(n); if (FlagOpt_QScore("truncname")) { n = Label.find_first_of(" \t\r\n,"); if (n != std::string::npos) Label.erase(n); } } static bool DoStrip(char c) { /*const QScoreContext *ctx = getQScoreContext(); c = toupper(c); if (ctx->g_StripX && c == 'X') return true; if (ctx->g_StripZ && c == 'Z') return true; if (ctx->g_StripB && c == 'B') return true;*/ return false; } #define APPEND_CHAR(c) \ { \ if (Pos >= BufferSize) \ Quit_Qscore("ReadMFA: buffer too small"); \ if (!DoStrip(c)) \ Buffer[Pos++] = (c); \ } #define APPEND_SEQ(Label, Start, Length, UngappedLength) \ { \ if (0 == m_uSeqCount) \ m_uColCount = Length; \ else if (Length != m_uColCount) \ Quit_Qscore("Sequence lengths differ %s=%d, %s=%d",\ Label.c_str(), m_uColCount, Label.c_str(), Length);\ if (m_uSeqCount >= m_uCacheSeqCount) \ { \ m_uCacheSeqCount += 128; \ char **Seqs = all(char *, m_uCacheSeqCount);\ unsigned *SeqLengths = all(unsigned, m_uCacheSeqCount);\ if (m_uSeqCount > 0) \ { \ memcpy(Seqs, m_szSeqs, m_uSeqCount*sizeof(char **));\ memcpy(SeqLengths, m_SeqLengths, m_uSeqCount*sizeof(unsigned));\ delete[] m_szSeqs; \ delete[] m_SeqLengths; \ } \ m_szSeqs = Seqs; \ m_SeqLengths = SeqLengths; \ } \ m_szSeqs[m_uSeqCount] = m_SeqBuffer + Start; \ FixLabel(Label); \ m_SeqNames.push_back(Label); \ m_SeqNameToIndex[Label] = m_uSeqCount; \ Label.clear(); \ m_SeqLengths[m_uSeqCount] = UngappedLength; \ ++m_uSeqCount; \ } void MSA_QScore::FromFASTAFile(FILE *f) { Clear(); rewind(f); int FileSize = GetFileSize(f); int BufferSize = FileSize; char *Buffer = all(char, BufferSize); m_SeqBuffer = Buffer; char prev_c = '\n'; bool InLabel = false; //int ContigFrom = 0; std::string Label; int UngappedSeqLength = 0; int Pos = 0; int ContigStart = 0; for (;;) { int c = fgetc(f); if (EOF == c) { if (feof(f)) break; Quit_Qscore("Stream error"); } if (InLabel) { if (c == '\r') continue; if ('\n' == c) { UngappedSeqLength = 0; InLabel = false; } else { Label.push_back(c); } } else { if ('>' == c && '\n' == prev_c) { unsigned ContigLength = Pos - ContigStart; if (ContigLength > 0) { APPEND_SEQ(Label, ContigStart, ContigLength, UngappedSeqLength) } ContigStart = Pos; InLabel = true; } else if (!isspace(c)) { APPEND_CHAR(c) if (!::IsGap(c)) ++UngappedSeqLength; } } prev_c = c; } unsigned ContigLength = Pos - ContigStart; if (ContigLength > 0) { APPEND_SEQ(Label, ContigStart, ContigLength, UngappedSeqLength); } MakeGapMap(); MakeUngapMap(); } ugene-1.9.8/src/libs_3rdparty/qscore/src/qscore/qscore_qscore.cpp0000644000175000017500000000546211651544307023632 0ustar ilyailya#include "qscore.h" //const char *g_TestFileName; //const char *g_RefFileName; //bool g_Quiet = false; //bool g_Slow = false; //bool g_Cline = false; //bool g_Modeler = false; //bool g_GC = false; //bool g_SeqDiffWarn = false; //bool g_Verbose = false; //bool g_StripX = false; //bool g_StripZ = false; //bool g_StripB = false; static void ToUpper(MSA_QScore &msa) { const int SeqCount = msa.GetSeqCount(); const int ColCount = msa.GetColCount(); for (int SeqIndex = 0; SeqIndex < SeqCount; ++SeqIndex) for (int ColIndex = 0; ColIndex < ColCount; ++ColIndex) { char c = msa.GetChar(SeqIndex, ColIndex); if (isalpha(c)) { c = toupper(c); msa.SetChar(SeqIndex, ColIndex, c); } } } double QScore(MSA_QScore* _msaTest, MSA_QScore* _msaRef) { /*g_TestFileName = RequiredValueOpt("test"); g_RefFileName = RequiredValueOpt("ref"); g_Slow = FlagOpt("slow"); g_Cline = FlagOpt("cline"); g_Modeler = FlagOpt("modeler"); g_Quiet = FlagOpt("quiet"); g_GC = FlagOpt("gapscore"); g_SeqDiffWarn = FlagOpt("seqdiffwarn"); g_Verbose = FlagOpt("verbose"); g_StripX = FlagOpt("stripx"); g_StripB = FlagOpt("stripb"); g_StripZ = FlagOpt("stripz");*/ MSA_QScore &msaTest = *_msaTest; MSA_QScore &msaRef = *_msaRef; /*FILE *fTest = OpenStdioFile(g_TestFileName); FILE *fRef = OpenStdioFile(g_RefFileName);*/ //msaTest.FromFASTAFile(fTest); //msaRef.FromFASTAFile(fRef); //fclose(fTest); //fclose(fRef); //if (FlagOpt("ignoretestcase")) ToUpper(msaTest); //if (FlagOpt("ignorerefcase")) ToUpper(msaRef); if (0 == msaTest.GetSeqCount()) Quit_Qscore("No seqs in test alignment"); if (0 == msaRef.GetSeqCount()) Quit_Qscore("No seqs in ref alignment"); //if (FlagOpt("perseq")) // PerSeq(msaTest, msaRef); double Q = dInsane; double TC = dInsane; double Modeler = dInsane; double SlowQ = dInsane; double SlowTC = dInsane; double SlowModeler = dInsane; double SlowCline = dInsane; double GC = dInsane; double CG = dInsane; double TGC = dInsane; double TCG = dInsane; FastQ(msaTest, msaRef, Q, TC); /*if (g_Modeler) { double NotUsedTC = dInsane; FastQ(msaRef, msaTest, Modeler, NotUsedTC, false); } if (g_Slow || g_Cline || g_Modeler) { CompareMSA(msaTest, msaRef, &SlowQ, &SlowModeler, &SlowCline); SlowTC = ComputeTC(msaTest, msaRef); } if (g_GC) { ComputeGapScoreMSA(msaTest, msaRef, GC, TGC); ComputeGapScoreMSA(msaRef, msaTest, CG, TCG); }*/ /*printf("Test=%s;Ref=%s;Q=%.3g;TC=%.3g", g_TestFileName, g_RefFileName, Q, TC);*/ return Q; //if (g_Cline) // printf(";Cline=%.3g", SlowCline); //if (g_Modeler) // printf(";Modeler=%.3g", Modeler); //if (g_Slow) // printf(";SlowQ=%.3g;SlowTC=%.3g;SlowModeler=%.3g", SlowQ, SlowTC, SlowModeler); //if (g_GC) // printf(";GC=%.3g;CG=%.3g;TGC=%.3g;TCG=%.3g", GC, CG, TGC, TCG); //printf("\n"); } ugene-1.9.8/src/libs_3rdparty/qscore/src/qscore/qscore_tc.cpp0000644000175000017500000001004711651544307022737 0ustar ilyailya#include "qscore.h" #ifdef _MSC_VER #pragma warning(disable: 4800) // int->bool #endif void SeqsDiffer(MSA_QScore &msaTest, unsigned uTestSeqIndex1, MSA_QScore &/*msaRef*/, unsigned /*uRefSeqIndex1*/, unsigned /*uRefColIndex*/) { Quit_Qscore("Test & ref sequences differ, label=%s", msaTest.GetSeqName(uTestSeqIndex1)); } bool IsAlignedColWithGaps(const MSA_QScore &msa, unsigned uColIndex) { const unsigned uSeqCount = msa.GetSeqCount(); bool AnyGaps = false; bool AnyUpper = false; for (unsigned uSeqIndex = 0; uSeqIndex < uSeqCount; ++uSeqIndex) { if (msa.IsGap(uSeqIndex, uColIndex)) { AnyGaps = true; continue; } char c = msa.GetChar(uSeqIndex, uColIndex); bool Upper = isupper(c); if (Upper) AnyUpper = true; else return false; if (Upper && AnyGaps) return true; } return AnyUpper && AnyGaps; } int IsAlignedCol(const MSA_QScore &msa, unsigned uColIndex) { const unsigned uSeqCount = msa.GetSeqCount(); for (unsigned uSeqIndex = 0; uSeqIndex < uSeqCount; ++uSeqIndex) { if (msa.IsGap(uSeqIndex, uColIndex)) continue; return isupper(msa.GetChar(uSeqIndex, uColIndex)); } return false; } double ComputeTC(MSA_QScore &msaTest, MSA_QScore &msaRef) { const unsigned uRefSeqCount = msaRef.GetSeqCount(); if (0 == uRefSeqCount) Quit_Qscore("No sequences in ref alignment"); unsigned *RefSeqIndexToTestSeqIndex = new unsigned[uRefSeqCount]; for (unsigned uRefSeqIndex = 0; uRefSeqIndex < uRefSeqCount; ++uRefSeqIndex) { const char *ptrName = msaRef.GetSeqName(uRefSeqIndex); unsigned uTestSeqIndex; bool bFound = msaTest.GetSeqIndex(ptrName, &uTestSeqIndex); if (bFound) RefSeqIndexToTestSeqIndex[uRefSeqIndex] = uTestSeqIndex; else RefSeqIndexToTestSeqIndex[uRefSeqIndex] = uInsane; } unsigned uRefAlignedColCount = 0; unsigned uCorrectlyAlignedColCount = 0; unsigned uRefColCount = msaRef.GetColCount(); for (unsigned uRefColIndex = 0; uRefColIndex < uRefColCount; ++uRefColIndex) { if (!IsAlignedCol(msaRef, uRefColIndex)) continue; bool bAllAlignedCorrectly = true; bool bAllGaps = true; // Iterate over all pairs for (unsigned uRefSeqIndex1 = 0; uRefSeqIndex1 < uRefSeqCount; ++uRefSeqIndex1) { unsigned uTestSeqIndex1 = RefSeqIndexToTestSeqIndex[uRefSeqIndex1]; if (uTestSeqIndex1 == uInsane) continue; char cRef1 = msaRef.GetChar(uRefSeqIndex1, uRefColIndex); if (IsGap(cRef1)) continue; if (!isupper(cRef1)) Quit_Qscore("Ref alignment col %d has both upper and lower-case letters", uRefColIndex); unsigned uRefUngappedColIndex1 = msaRef.GetUngappedColIndex(uRefSeqIndex1, uRefColIndex); unsigned uTestGappedColIndex1 = msaTest. GetGappedColIndex(uTestSeqIndex1, uRefUngappedColIndex1); char cTest1 = msaTest.GetChar(uTestSeqIndex1, uTestGappedColIndex1); if (cRef1 != toupper(cTest1)) SeqsDiffer(msaTest, uTestSeqIndex1, msaRef, uRefSeqIndex1, uRefColIndex); for (unsigned uRefSeqIndex2 = uRefSeqIndex1 + 1; uRefSeqIndex2 < uRefSeqCount; ++uRefSeqIndex2) { unsigned uTestSeqIndex2 = RefSeqIndexToTestSeqIndex[uRefSeqIndex2]; if (uTestSeqIndex2 == uInsane) continue; char cRef2 = msaRef.GetChar(uRefSeqIndex2, uRefColIndex); if (IsGap(cRef2)) continue; bAllGaps = false; assert(isupper(cRef2)); unsigned uRefUngappedColIndex2 = msaRef.GetUngappedColIndex(uRefSeqIndex2, uRefColIndex); unsigned uTestGappedColIndex2 = msaTest. GetGappedColIndex(uTestSeqIndex2, uRefUngappedColIndex2); char cTest2 = msaTest.GetChar(uTestSeqIndex2, uTestGappedColIndex2); if (!(isupper(cTest1) && isupper(cTest2) && uTestGappedColIndex1 == uTestGappedColIndex2)) { bAllAlignedCorrectly = false; goto NextCol; } } } NextCol: if (!bAllGaps) { ++uRefAlignedColCount; if (bAllAlignedCorrectly) ++uCorrectlyAlignedColCount; } } delete[] RefSeqIndexToTestSeqIndex; if (0 == uRefAlignedColCount) Quit_Qscore("No aligned columns (upper case) in ref alignment"); return (double) uCorrectlyAlignedColCount / (double) uRefAlignedColCount; } ugene-1.9.8/src/libs_3rdparty/qscore/src/qscore/qscore.h0000644000175000017500000000755211651544307021725 0ustar ilyailya// qscore.h #include #include #include #include #include #include #include #include #include #include #include #include #define UINT_MAX 0xffffffff #ifdef _MSC_VER #include typedef stdext::hash_map StrToInt; #else #include #define HASH_MAP struct HashStringToUnsigned { size_t operator()(const std::string &Key) const { size_t h = 0; size_t Bytes = Key.size(); for (size_t i = 0; i < Bytes; ++i) { unsigned char c = (unsigned char) Key[i]; h = c + (h << 6) + (h << 16) - h; } return h; } }; typedef __gnu_cxx::hash_map StrToInt; #endif using namespace std; // Allow different conventions: DEBUG or _DEBUG for debug mode, // NDEBUG for not debug mode. #ifdef _DEBUG #undef DEBUG #define DEBUG 1 #endif #ifdef DEBUG #undef _DEBUG #define _DEBUG 1 #endif #ifdef NDEBUG #undef DEBUG #undef _DEBUG #endif typedef vector IntVec; typedef vector BoolVec; #define all(t, n) (t *) allocmem((n)*sizeof(t)) #define reall(p, t, n) p = (t *) reallocmem(p, (n)*sizeof(t)) #define zero(p, t, n) memset(p, 0, (n)*sizeof(t)) void *allocmem(int bytes); void freemem(void *p); void *reallocmem(void *p, int bytes); static inline bool IsGap(char c) { return '-' == c || '~' == c || '.' == c || '+' == c || '#' == c; } static inline int iabs(int i) { return i >= 0 ? i : -i; } class MSA_QScore; const double dInsane = double(0xffffffff); const unsigned uInsane = 987654321; unsigned CharToLetter(char c); char LetterToChar(unsigned Letter); void ComparePair(const MSA_QScore &msaTest, unsigned uTestSeqIndexA, unsigned uTestSeqIndexB, const MSA_QScore &msaRef, unsigned uRefSeqIndexA, unsigned uRefSeqIndexB, double *ptrdSP, double *ptrdPS, double *ptrdCS); double ComparePairSP(const MSA_QScore &msaTest, unsigned uTestSeqIndexA, unsigned uTestSeqIndexB, const MSA_QScore &msaRef, unsigned uRefSeqIndexA, unsigned uRefSeqIndexB); void ComparePairMap(const int iTestMapA[], const int iTestMapB[], const int iRefMapA[], const int iRefMapB[], int iLengthA, int iLengthB, double *ptrdSP, double *ptrdPS, double *ptrdCS); double ComparePairMapSP(const int iTestMapA[], const int iTestMapB[], const int iRefMapA[], const int iRefMapB[], int iLengthA, int iLengthB); double SumPairs(const int iMapRef[], const int iMapTest[], unsigned uLength); double ClineShift(const int iTestMapA[], const int iRefMapA[], unsigned uLengthA, const int iTestMapB[], const int iRefMapB[], unsigned uLengthB, double dEpsilon = 0.2); void MakePairMaps(const MSA_QScore &msaTest, unsigned uTestSeqIndexA, unsigned uTestSeqIndexB, const MSA_QScore &msaRef, unsigned uRefSeqIndexA, unsigned uRefSeqIndexB, int **ptriTestMapAr, int **ptriTestMapBr, int **ptriRefMapAr, int **ptriRefMapBr); void Quit_Qscore(const char *Format, ...); //void Warning_Qscore(const char *Format, ...); FILE *OpenStdioFile(const char *FileName); int GetFileSize(FILE *f); //void ParseOptions(int argc, char *argv[]); bool FlagOpt_QScore(const char *Name); const char *ValueOpt_QScore(const char *Name); const char *RequiredValueOpt(const char *Name); void CompareMSA(const MSA_QScore &msaTest, const MSA_QScore &msaRef, double *ptrdSP, double *ptrdPS, double *ptrdCS); double ComputeTC(MSA_QScore &msaTest, MSA_QScore &msaRef); void FastQ(const MSA_QScore &msaTest, const MSA_QScore &msaRef, double &Q, double &TC, bool WarnIfNoRefAligned = true); void ComputeGapScoreMSA(MSA_QScore &msaTest, MSA_QScore &msaRef, double &GC, double &TC); //void Log(const char *Format, ...); double PerSeq(const MSA_QScore &msaTest, const MSA_QScore &msaRef); double QScore(MSA_QScore* _msaTest, MSA_QScore* _msaRef); void SAB(); #include "qscore/msa.h" #include "qscore/seq.h" #include "qscore/qscore_context.h" ugene-1.9.8/src/libs_3rdparty/qscore/src/qscore/qscore_fastq.cpp0000644000175000017500000001347411651544307023456 0ustar ilyailya#include "qscore.h" // O(NL) computation of PREFAB Q score and Balibase TC score. // Algorithm based on an idea due to Chuong (Tom) Do. // Each position in the reference alignment is annotated with // the column number C in the test alignment where the same // letter is found. A pair of identical Cs in the same reference // column indicates a correctly aligned pair of letters. void FastQ(const MSA_QScore &msaTest, const MSA_QScore &msaRef, double &Q, double &TC, bool WarnIfNoRefAligned) { unsigned CorrectPairCount = 0; unsigned RefAlignedPairCount = 0; const unsigned RefSeqCount = msaRef.GetSeqCount(); const unsigned TestSeqCount = msaTest.GetSeqCount(); const unsigned RefColCount = msaRef.GetColCount(); const unsigned TestColCount = msaTest.GetColCount(); StrToInt RefSeqNameToIndex; IntVec RefToTestSeqIndex(RefSeqCount); for (unsigned RefSeqIndex = 0; RefSeqIndex < RefSeqCount; ++RefSeqIndex) { const string SeqName = msaRef.GetSeqName(RefSeqIndex); RefToTestSeqIndex[RefSeqIndex] = UINT_MAX; RefSeqNameToIndex[SeqName] = RefSeqIndex; } for (unsigned TestSeqIndex = 0; TestSeqIndex < TestSeqCount; ++TestSeqIndex) { const string SeqName = msaTest.GetSeqName(TestSeqIndex); StrToInt::const_iterator p = RefSeqNameToIndex.find(SeqName); if (p != RefSeqNameToIndex.end()) { unsigned RefSeqIndex = p->second; if (RefSeqIndex == UINT_MAX) Quit_Qscore("UINT_MAX"); RefToTestSeqIndex[RefSeqIndex] = TestSeqIndex; } } #ifdef DEBUG if (!FlagOpt_QScore("ignoremissingseqs")) for (unsigned RefSeqIndex = 0; RefSeqIndex < RefSeqCount; ++RefSeqIndex) { unsigned TestSeqIndex = RefToTestSeqIndex[RefSeqIndex]; const char *RefSeqName = msaRef.GetSeqName(RefSeqIndex); if (TestSeqIndex == UINT_MAX) { //k_printf( "\n"); //k_printf( "RefSeqIndex RefSeqName\n"); //k_printf( "=========== ==========\n"); /*for (StrToInt::const_iterator p = RefSeqNameToIndex.begin(); p != RefSeqNameToIndex.end(); ++p) k_printf( "%11u %s\n", p->second, (p->first).c_str()); k_printf( "\n");*/ Quit_Qscore("Ref seq %u=%.16s not found in test alignment", RefSeqIndex, RefSeqName); } else { const char *TestSeqName = msaTest.GetSeqName(TestSeqIndex); assert(!strcmp(RefSeqName, TestSeqName)); } } #endif // TestColIndex[i] is the one-based (not zero-based!) test column index // of the letter found in the current column of the reference alignment // (or the most recent letter if the reference column is gapped, or zero // if no letter has yet been found). Here, seq index i is for msaRef. IntVec TestColIndex(TestSeqCount, 0); // TestColIndexCount[i] is the number of times that a letter from test // column i (one-based!) appears in the current reference column. IntVec TestColIndexCount(TestColCount+1, 0); // TestColIndexes[i] is the column index in the test alignment of // the i'th non-gapped position in the current reference column. IntVec TestColIndexes; unsigned RefAlignedColCount = 0; unsigned CorrectColCount = 0; for (unsigned RefColIndex = 0; RefColIndex < RefColCount; RefColIndex++) { TestColIndexes.clear(); TestColIndexes.reserve(RefSeqCount); // NonGappedCount is the number of non-gapped positions in the current // reference column. unsigned NonGappedCount = 0; unsigned FirstTestColIndex = UINT_MAX; bool RefColIsAligned = false; bool TestColAllCorrect = true; bool TestAllAligned = true; for (unsigned RefSeqIndex = 0; RefSeqIndex < RefSeqCount; RefSeqIndex++) { unsigned TestSeqIndex = RefToTestSeqIndex[RefSeqIndex]; if (TestSeqIndex == UINT_MAX) { if (FlagOpt_QScore("ignoremissingseqs")) continue; Quit_Qscore("Test seq %.16s missing", msaRef.GetSeqName(RefSeqIndex)); } char cRef = msaRef.GetChar(RefSeqIndex, RefColIndex); if (!IsGap(cRef)) { char cTest = 0; unsigned Col = TestColIndex[TestSeqIndex]; do cTest = msaTest.GetChar(TestSeqIndex, Col++); while (IsGap(cTest)); if (toupper(cRef) != toupper(cTest)) { //do nothing } if (isalpha(cRef) && isupper(cRef)) { RefColIsAligned = true; ++NonGappedCount; if (isupper(cTest)) { TestColIndexes.push_back(Col); ++(TestColIndexCount[Col]); if (FirstTestColIndex == UINT_MAX) FirstTestColIndex = Col; else { if (FirstTestColIndex != Col) TestColAllCorrect = false; } } else TestAllAligned = false; } else { if (RefColIsAligned) { /*k_printf( "\n"); k_printf( "Ref col: "); for (unsigned RefSeqIndex = 0; RefSeqIndex < RefSeqCount; RefSeqIndex++) k_printf( "%c", msaRef.GetChar(RefSeqIndex, RefColIndex)); k_printf( "\n");*/ Quit_Qscore("Ref col %u has both upper- and lower-case letters", RefColIndex); } } TestColIndex[TestSeqIndex] = Col; } } if (RefColIsAligned && NonGappedCount > 1) { ++RefAlignedColCount; if (TestColAllCorrect && TestAllAligned) ++CorrectColCount; } unsigned ColPairCount = 0; for (IntVec::const_iterator p = TestColIndexes.begin(); p != TestColIndexes.end(); ++p) { unsigned Col = *p; unsigned Count = TestColIndexCount[Col]; if (Count > 0) ColPairCount += Count*(Count - 1)/2; TestColIndexCount[Col] = 0; } CorrectPairCount += ColPairCount; RefAlignedPairCount += NonGappedCount*(NonGappedCount - 1)/2; } if (RefAlignedPairCount == 0) Q = 0; else Q = (double) CorrectPairCount / (double) RefAlignedPairCount; if (RefAlignedColCount == 0) { /*if (WarnIfNoRefAligned) k_printf( "Warning: reference alignment %s has no aligned (upper-case) columns\n", g_RefFileName);*/ TC = 0; } else TC = (double) CorrectColCount / (double) RefAlignedColCount; } ugene-1.9.8/src/libs_3rdparty/qscore/src/qscore/qscore_context.h0000644000175000017500000000130511651544307023457 0ustar ilyailya#ifndef _QSCORE_CONTEXT_ #define _QSCORE_CONTEXT_ class QScoreException { public: QScoreException() {} QScoreException(const char* str); char str[4096]; }; #endif //_QSCORE_CONTEXT_ // //struct QScoreContext { // const MSA_QScore *g_ptrmsaTest; // const MSA_QScore *g_ptrmsaRef; // unsigned g_TestSeqIndexA; // unsigned g_TestSeqIndexB; // unsigned g_RefSeqIndexA; // unsigned g_RefSeqIndexB; // bool g_Quiet; // bool g_Cline; // bool g_SeqDiffWarn; // bool g_Verbose; // bool g_StripX; // bool g_StripZ; // bool g_StripB; // bool g_Slow; // bool g_Modeler; // bool g_GC; // // //qscore_fastq.cpp // unsigned g_SeqDiffCount; // // QScoreContext(); //}; // //extern const QScoreContext* getQScoreContext();ugene-1.9.8/src/libs_3rdparty/qscore/src/qscore/qscore_comparemap.cpp0000644000175000017500000000433511651544307024460 0ustar ilyailya#include "qscore.h" #if _DEBUG static bool LocalEq(double x, double y) { double diff = fabs(x-y); return diff < 1e-3; } double ComparePairMapSP(const int iTestMapA[], const int iTestMapB[], const int iRefMapA[], const int iRefMapB[], int iLengthA, int iLengthB) #else double ComparePairMapSP(const int iTestMapA[], const int /*iTestMapB[]*/, const int iRefMapA[], const int /*iRefMapB[]*/, int iLengthA, int /*iLengthB*/) #endif { double dSP = SumPairs(iRefMapA, iTestMapA, iLengthA); #if _DEBUG { // Verify symmetry as a correctness check double dSP2 = SumPairs(iRefMapB, iTestMapB, iLengthB); if (!LocalEq(dSP, dSP2)) Quit_Qscore("ComparePairMapSP: dSP=%g dSP2=%g diff=%g", dSP, dSP2, fabs(dSP-dSP2)); } #endif return dSP; } void ComparePairMap(const int iTestMapA[], const int iTestMapB[], const int iRefMapA[], const int iRefMapB[], int iLengthA, int iLengthB, double *ptrdSP, double *ptrdPS, double *ptrdCS) { double dSP = SumPairs(iRefMapA, iTestMapA, iLengthA); double dPS = SumPairs(iTestMapA, iRefMapA, iLengthA); double dCS = -999.0; /*if (ctx->g_Cline) dCS = ClineShift(iTestMapA, iRefMapA, iLengthA, iTestMapB, iRefMapB, iLengthB);*/ #if _DEBUG { // Verify symmetries as a correctness check double dSP2 = SumPairs(iRefMapB, iTestMapB, iLengthB); double dPS2 = SumPairs(iTestMapB, iRefMapB, iLengthB); if (!LocalEq(dSP, dSP2)) Quit_Qscore("CompareSeqs: dSP=%g dSP2=%g diff=%g", dSP, dSP2, fabs(dSP-dSP2)); if (!LocalEq(dPS, dPS2)) Quit_Qscore("CompareSeqs: dPS=%g dPS2=%g diff=%g", dPS, dPS2, fabs(dPS-dPS2)); /*if (ctx->g_Cline) { double dCS2 = ClineShift(iTestMapB, iRefMapB, iLengthB, iTestMapA, iRefMapA, iLengthA); double dCS3 = ClineShift(iRefMapA, iTestMapA, iLengthA, iRefMapB, iTestMapB, iLengthB); double dCS4 = ClineShift(iRefMapB, iTestMapB, iLengthB, iRefMapA, iTestMapA, iLengthA); if (!LocalEq(dCS, dCS2)) Quit_Qscore("CompareSeqs: dCS=%g dCS2=%g diff=%g", dCS, dCS2, fabs(dCS-dCS2)); if (!LocalEq(dCS, dCS3)) Quit_Qscore("CompareSeqs: dCS=%g dCS3=%g diff=%g", dCS, dCS3, fabs(dCS-dCS3)); if (!LocalEq(dCS, dCS4)) Quit_Qscore("CompareSeqs: dCS=%g dCS4=%g diff=%g", dCS, dCS4, fabs(dCS-dCS4)); }*/ } #endif *ptrdSP = dSP; *ptrdPS = dPS; *ptrdCS = dCS; } ugene-1.9.8/src/libs_3rdparty/qscore/src/qscore/qscore_context.cpp0000644000175000017500000000100711651544307024011 0ustar ilyailya#include "qscore_context.h" // //QScoreContext::QScoreContext() { // MSA_QScore *g_ptrmsaTest = 0; // MSA_QScore *g_ptrmsaRef = 0; // g_TestSeqIndexA = UINT_MAX; // g_TestSeqIndexB = UINT_MAX; // g_RefSeqIndexA = UINT_MAX; // g_RefSeqIndexB = UINT_MAX; // g_Quiet = false; // g_Slow = false; // g_Cline = false; // g_Modeler = false; // g_GC = false; // g_SeqDiffWarn = false; // g_Verbose = false; // g_StripX = false; // g_StripZ = false; // g_StripB = false; //} // //const QScoreContext* getQScoreContext() { // //}ugene-1.9.8/src/libs_3rdparty/qscore/src/qscore/qscore_utils.cpp0000644000175000017500000000232411651544307023470 0ustar ilyailya#include "qscore.h" void Quit_Qscore(const char *szFormat, ...) { QScoreException e; va_list ArgList; va_start(ArgList, szFormat); vsprintf(e.str, szFormat, ArgList); throw e; // exit(EXIT_FatalError); } FILE *OpenStdioFile(const char *FileName) { FILE *f = fopen(FileName, "r"); if (0 == f) Quit_Qscore("Cannot open %s, %s [errno=%d]", FileName, strerror(errno), errno); return f; } int GetFileSize(FILE *f) { long CurrPos = ftell(f); if (CurrPos < 0) Quit_Qscore("FileSize: ftell<0 (CurrPos), errno=%d", errno); int Ok = fseek(f, 0, SEEK_END); if (Ok != 0) Quit_Qscore("FileSize fseek(END) != 0 errno=%d", errno); long Size = ftell(f); if (Size < 0) Quit_Qscore("FileSize: ftell<0 (size), errno=%d", errno); Ok = fseek(f, CurrPos, SEEK_SET); if (Ok != 0) Quit_Qscore("FileSize fseek(restore curr pos) != 0 errno=%d", errno); long NewPos = ftell(f); if (CurrPos < 0) Quit_Qscore("FileSize: ftell=%ld != CurrPos=%ld", CurrPos, NewPos); return (int) Size; } void *allocmem(int bytes) { char *p = (char *) malloc((size_t) (bytes)); if (0 == p) Quit_Qscore("Out of memory (%d)", bytes); return p; } void freemem(void *p) { if (0 == p) return; free(((char *) p)); } ugene-1.9.8/src/libs_3rdparty/qscore/src/qscore/qscore_sumpairs.cpp0000644000175000017500000000120711651544307024172 0ustar ilyailya#include "qscore.h" // Compute the sum of pairs score from two pair maps. // It is the simplicity of this code that motivates the use of pair maps. double SumPairs(const int iMapRef[], const int iMapTest[], unsigned uLength) { unsigned uPairCount = 0; unsigned uCorrectPairCount = 0; for (unsigned uPos = 0; uPos < uLength; ++uPos) { int iPosRef = iMapRef[uPos]; if (-1 == iPosRef) continue; ++uPairCount; int iPosTest = iMapTest[uPos]; if (-1 == iPosTest) continue; if (iPosRef == iPosTest) ++uCorrectPairCount; } if (0 == uPairCount) return 0.0; return (double) uCorrectPairCount / (double) uPairCount; } ugene-1.9.8/src/libs_3rdparty/qscore/src/qscore/qscore_comparepair.cpp0000644000175000017500000000266511651544307024642 0ustar ilyailya#include "qscore.h" //unsigned g_TestSeqIndexA = UINT_MAX; //unsigned g_TestSeqIndexB = UINT_MAX; //unsigned g_RefSeqIndexA = UINT_MAX; //unsigned g_RefSeqIndexB = UINT_MAX; void ComparePair(const MSA_QScore &msaTest, unsigned uTestSeqIndexA, unsigned uTestSeqIndexB, const MSA_QScore &msaRef, unsigned uRefSeqIndexA, unsigned uRefSeqIndexB, double *ptrdSP, double *ptrdPS, double *ptrdCS) { const int iLengthA = (int) msaTest.GetSeqLength(uTestSeqIndexA); const int iLengthB = (int) msaTest.GetSeqLength(uTestSeqIndexB); const int iLengthAr = (int) msaRef.GetSeqLength(uRefSeqIndexA); const int iLengthBr = (int) msaRef.GetSeqLength(uRefSeqIndexB); if (iLengthA != iLengthAr) Quit_Qscore("Seq %s has %u letters in test, %u letters in ref", msaTest.GetSeqName(uTestSeqIndexA), iLengthA, iLengthAr); if (iLengthB != iLengthBr) Quit_Qscore("Seq %s has %u letters in test, %u letters in ref", msaTest.GetSeqName(uTestSeqIndexB), iLengthB, iLengthBr); int *iRefMapA = new int[iLengthA]; int *iRefMapB = new int[iLengthB]; int *iTestMapA = new int[iLengthA]; int *iTestMapB = new int [iLengthB]; msaTest.GetPairMap(uTestSeqIndexA, uTestSeqIndexB, iTestMapA, iTestMapB); msaRef.GetPairMap(uRefSeqIndexA, uRefSeqIndexB, iRefMapA, iRefMapB); ComparePairMap(iTestMapA, iTestMapB, iRefMapA, iRefMapB, iLengthA, iLengthB, ptrdSP, ptrdPS, ptrdCS); delete[] iRefMapA; delete[] iRefMapB; delete[] iTestMapA; delete[] iTestMapB; } ugene-1.9.8/src/libs_3rdparty/qscore/src/qscore/qscore_gapscore2.cpp0000644000175000017500000001335111651544307024217 0ustar ilyailya#include "qscore.h" using namespace std; static bool IsGapChar(char c) { return c == '-' || c == '.' || c == '+' || c == '#'; } void MakeAlnColToSeqPosVec(const string &Seq, vector &PosVec) { const unsigned ColCount = (unsigned) Seq.size(); PosVec.resize(ColCount); unsigned Pos = 0; for (unsigned ColIndex = 0; ColIndex < ColCount; ++ColIndex) { char c = Seq[ColIndex]; PosVec[ColIndex] = Pos; if (!IsGapChar(c)) PosVec[ColIndex] = Pos++; } } void MakeSeqPosToAlnColVec(const string &Seq, vector &PosVec) { const unsigned ColCount = (unsigned) Seq.size(); PosVec.resize(ColCount); unsigned Pos = 0; for (unsigned ColIndex = 0; ColIndex < ColCount; ++ColIndex) { char c = Seq[ColIndex]; if (IsGapChar(c)) continue; PosVec[Pos++] = ColIndex; } } void MakeAlnColToSeqPosVecs(const vector &Seqs, vector > &PosVecs) { PosVecs.clear(); const unsigned SeqCount = (unsigned) Seqs.size(); PosVecs.resize(SeqCount); for (unsigned SeqIndex = 0; SeqIndex < SeqCount; ++SeqIndex) MakeAlnColToSeqPosVec(Seqs[SeqIndex], PosVecs[SeqIndex]); } void MakeSeqPosToAlnColVecs(const vector &Seqs, vector > &PosVecs) { PosVecs.clear(); const unsigned SeqCount = (unsigned) Seqs.size(); PosVecs.resize(SeqCount); for (unsigned SeqIndex = 0; SeqIndex < SeqCount; ++SeqIndex) MakeSeqPosToAlnColVec(Seqs[SeqIndex], PosVecs[SeqIndex]); } void ComputeGapScore(const vector &TestSeqs, const vector &TestLabels, const vector &RefSeqs, const vector &RefLabels, double &GC, double &TC) { const unsigned TestSeqCount = (unsigned) TestSeqs.size(); const unsigned RefSeqCount = (unsigned) RefSeqs.size(); if (RefSeqCount == 0) Quit_Qscore("No seqs in reference alignment"); if (TestSeqCount == 0) Quit_Qscore("No seqs in test alignment"); const unsigned RefColCount = (unsigned) RefSeqs[0].size(); if ((unsigned) TestLabels.size() != TestSeqCount) Quit_Qscore("ComputeGapScore, test label count"); if ((unsigned) RefLabels.size() != RefSeqCount) Quit_Qscore("ComputeGapScore, ref label count"); vector > TestSeqPosToAlnColVecs; vector > TestAlnColToSeqPosVecs; vector > RefAlnColToSeqPosVecs; MakeSeqPosToAlnColVecs(TestSeqs, TestSeqPosToAlnColVecs); MakeAlnColToSeqPosVecs(TestSeqs, TestAlnColToSeqPosVecs); MakeAlnColToSeqPosVecs(RefSeqs, RefAlnColToSeqPosVecs); vector RefSeqIndexToTestSeqIndex(RefSeqCount, UINT_MAX); for (unsigned RefSeqIndex = 0; RefSeqIndex < RefSeqCount; ++RefSeqIndex) { const string &RefLabel = RefLabels[RefSeqIndex]; bool Found = false; for (unsigned TestSeqIndex = 0; TestSeqIndex < TestSeqCount; ++TestSeqIndex) { const string &TestLabel = TestLabels[TestSeqIndex]; if (TestLabel == RefLabel) { Found = true; RefSeqIndexToTestSeqIndex[RefSeqIndex] = TestSeqIndex; break; } } if (!Found) Quit_Qscore("Ref seq '%s' not found in test alignment", RefLabel.c_str()); } unsigned AlignedColCount = 0; unsigned AlignedGapColCount = 0; unsigned CorrectColCount = 0; unsigned CorrectGapColCount = 0; for (unsigned RefColIndex = 0; RefColIndex < RefColCount; ++RefColIndex) { bool AnyGaps = false; bool AnyLetters = false; bool AllCorrect = true; bool AnyUpper = false; for (unsigned RefSeqIndex = 0; RefSeqIndex < RefSeqCount; ++RefSeqIndex) { const string &RefSeq = RefSeqs[RefSeqIndex]; char c = RefSeq[RefColIndex]; if (IsGapChar(c)) { AnyGaps = true; continue; } AnyLetters = true; if (!isupper(c)) { if (AnyUpper) Quit_Qscore("Mixed upper and lower case in ref alignment column"); continue; } AnyUpper = true; // We have a letter (X) in the reference sequence (S). // RefSeqPos is the (ungapped) position of X in the ref sequence. // TestSeqIndex is the sequence index in the test alignment of S. // TestColIndex is the (gapped) column in the test alignment of X. unsigned RefSeqPos = RefAlnColToSeqPosVecs[RefSeqIndex][RefColIndex]; unsigned TestSeqIndex = RefSeqIndexToTestSeqIndex[RefSeqIndex]; unsigned TestColIndex = TestSeqPosToAlnColVecs[TestSeqIndex][RefSeqPos]; // For every other sequence (S2) for (unsigned RefSeqIndex2 = 0; RefSeqIndex2 < RefSeqCount; ++RefSeqIndex2) { if (RefSeqIndex2 == RefSeqIndex) continue; const string &RefSeq2 = RefSeqs[RefSeqIndex2]; // TestSeqIndex2 is the sequence index in the test alignment of S2. unsigned TestSeqIndex2 = RefSeqIndexToTestSeqIndex[RefSeqIndex2]; char Refc2 = RefSeq2[RefColIndex]; if (IsGapChar(Refc2)) AnyGaps = true; char Testc2 = TestSeqs[TestSeqIndex2][TestColIndex]; // Must be the same letter or must both be gap. if (Refc2 != Testc2) { AllCorrect = false; break; } // If independent insertions, ambiguous where gap should be so skip next test. // if gap-gap. if (IsGapChar(Refc2) && IsGapChar(Testc2)) continue; unsigned RefSeqPos2 = RefAlnColToSeqPosVecs[RefSeqIndex2][RefColIndex]; unsigned TestSeqPos2 = TestAlnColToSeqPosVecs[TestSeqIndex2][TestColIndex]; if (RefSeqPos2 != TestSeqPos2) { AllCorrect = false; break; } } if (!AllCorrect) break; } if (AnyLetters && AnyUpper) { ++AlignedColCount; if (AllCorrect) ++CorrectColCount; if (AnyGaps) { ++AlignedGapColCount; if (AllCorrect) ++CorrectGapColCount; } } } if (AlignedColCount == 0) Quit_Qscore("No aligned cols in ref alignment"); else TC = (double) CorrectColCount / (double) AlignedColCount; if (AlignedGapColCount == 0) GC = 1.0; else GC = (double) CorrectGapColCount / (double) AlignedGapColCount; // Log("GC=%.3g;TC=%.3g\n", GC, TC); } ugene-1.9.8/src/libs_3rdparty/qscore/src/qscore/qscore_options.cpp0000644000175000017500000000407011651544307024023 0ustar ilyailya#include "qscore.h" struct VALUE_OPT { const char *m_pstrName; const char *m_pstrValue; }; struct FLAG_OPT { const char *m_pstrName; bool m_bSet; }; static VALUE_OPT ValueOpts[] = { { "test", 0, }, { "ref", 0, }, { "sab_test", 0, }, { "sab_ref", 0, }, }; static int ValueOptCount = sizeof(ValueOpts)/sizeof(ValueOpts[0]); static FLAG_OPT FlagOpts[] = { { "truncname", false, }, { "ignoretestcase", false, }, { "ignorerefcase", false, }, { "quiet", false, }, { "cline", false, }, { "modeler", false, }, { "slow", false, }, { "version", false, }, { "gapscore", false, }, { "seqdiffwarn", false, }, { "ignoremissingseqs", false, }, { "perseq", false, }, { "verbose", false, }, { "stripx", false, }, { "stripb", false, }, { "stripz", false, }, }; static int FlagOptCount = sizeof(FlagOpts)/sizeof(FlagOpts[0]); static bool TestSetFlagOpt(const char *Arg) { for (int i = 0; i < FlagOptCount; ++i) if (!strcmp(Arg, FlagOpts[i].m_pstrName)) { FlagOpts[i].m_bSet = true; return true; } return false; } static bool TestSetValueOpt(const char *Arg, const char *Value) { for (int i = 0; i < ValueOptCount; ++i) if (!strcmp(Arg, ValueOpts[i].m_pstrName)) { if (0 == Value) { //k_printf( "Option -%s must have value\n", Arg); Quit_Qscore("Option -%s must have value\n", Arg); } ValueOpts[i].m_pstrValue = strdup(Value); return true; } return false; } bool FlagOpt_QScore(const char *Name) { for (int i = 0; i < FlagOptCount; ++i) if (!strcmp(Name, FlagOpts[i].m_pstrName)) return FlagOpts[i].m_bSet; Quit_Qscore("FlagOpt(%s) invalid", Name); return false; } const char *ValueOpt_QScore(const char *Name) { for (int i = 0; i < ValueOptCount; ++i) if (!strcmp(Name, ValueOpts[i].m_pstrName)) return ValueOpts[i].m_pstrValue; Quit_Qscore("ValueOpt(%s) invalid", Name); return 0; } const char *RequiredValueOpt(const char *Name) { const char *s = ValueOpt_QScore(Name); if (0 == s) Quit_Qscore("Required option -%s not specified", Name); return s; } ugene-1.9.8/src/libs_3rdparty/qscore/src/qscore/msa.h0000644000175000017500000000436011651544307021203 0ustar ilyailya#ifndef MSA_h #define MSA_h #include #include #include extern void Quit_Qscore(const char szFormat[], ...); class MSA_QScore { #ifdef WIN32 friend void MSA_QScore::CopyReversed(); #endif public: MSA_QScore(); virtual ~MSA_QScore(); public: void FromFASTAFile(FILE *f); void SetSeqCount(unsigned uSeqCount); bool IsGap(unsigned uSeqIndex, unsigned uColIndex) const; void SetChar(unsigned uSeqIndex, unsigned uColIndex, char c); char GetChar(unsigned uSeqIndex, unsigned uIndex) const { #if _DEBUG if (uSeqIndex >= m_uSeqCount || uIndex >= m_uColCount) Quit_Qscore("MSA::GetChar(%u/%u,%u/%u)", uSeqIndex, m_uSeqCount, uIndex, m_uColCount); #endif char c = m_szSeqs[uSeqIndex][uIndex]; // assert(IsLegalChar(c)); return c; } void SetSeqName(unsigned uSeqIndex, const char szName[]); const char *GetSeqName(unsigned uSeqIndex) const; bool GetSeqIndex(const char *ptrSeqName, unsigned *ptruSeqIndex) const; unsigned GetCharCount(unsigned uSeqIndex, unsigned uColIndex) const; const char *GetSeqBuffer(unsigned uSeqIndex) const; unsigned GetSeqLength(unsigned uSeqIndex) const; void GetPairMap(unsigned uSeqIndex1, unsigned uSeqIndex2, int iMap1[], int iMap2[]) const; unsigned GetUngappedColIndex(unsigned uSeqIndex, unsigned uColIndex); unsigned GetGappedColIndex(unsigned uSeqIndex, unsigned uUngappedColIndex); void AppendSeq(char *ptrSeq, unsigned uSeqLength, char *ptrLabel); void ExpandCache(unsigned uSeqCount, unsigned uColCount); void Free(); void Clear() { Free(); } unsigned GetSeqCount() const { return m_uSeqCount; } unsigned GetColCount() const { return m_uColCount; } char LetterToChar(unsigned uLetter) const { return ::LetterToChar(uLetter); } char CharToLetter(char c) const { return ::CharToLetter(c); } private: void MakeGapMap(); void MakeGapMapSeq(unsigned uSeqIndex); void MakeUngapMap(); void MakeUngapMapSeq(unsigned uSeqIndex); private: unsigned m_uSeqCount; unsigned m_uColCount; unsigned m_uCacheSeqCount; char **m_szSeqs; //char **m_szNames; std::vector m_SeqNames; char *m_SeqBuffer; unsigned **m_UngapMap; unsigned **m_GapMap; unsigned *m_SeqLengths; std::map m_SeqNameToIndex; }; #endif // MSA_h ugene-1.9.8/src/libs_3rdparty/qscore/src/QScoreAdapter.h0000644000175000017500000000040411651544307021617 0ustar ilyailya#ifndef _U2_QSCORE_ADAPTER_H_ #define _U2_QSCORE_ADAPTER_H_ #include #include namespace U2 { extern double QScore(const MAlignment& maTest, const MAlignment& maRef, TaskStateInfo& ti); } #endif //_U2_QSCORE_ADAPTER_H_ ugene-1.9.8/src/libs_3rdparty/qscore/src/QScoreAdapter.cpp0000644000175000017500000000214311651544307022154 0ustar ilyailya#include "QScoreAdapter.h" #include "qscore/qscore.h" extern double QScore(MSA_QScore* _msaTest, MSA_QScore* _msaRef); namespace U2 { static void convertMAlignment2MSA(MSA_QScore& muscleMSA, const MAlignment& ma){ for (int i=0, n = ma.getNumRows(); iSRJuZNWc#di@% b_s Rۆ^t&:?!DmSQeJWeJÈqMT 'DB:RE_as3ȯC2Vz9W[9ŢwU*B4!B|zPJ fVcdEmZVw!Opřzp!MuS>x9f0Uއx8GHv=}uʡGBy=-Ka J8K+${?`vLЉ37ӿѯLjIENDB`ugene-1.9.8/src/ugenem/ugenem.rc0000644000175000017500000000271411651544337015204 0ustar ilyailya#include #define STRINGIFY(x) #x #define TOSTRING(x) STRINGIFY(x) #define UGENE_VERSION_STRING TOSTRING(UGENE_VERSION) #ifndef DEBUG #define VER_DEBUG 0 #else #define VER_DEBUG VS_FF_DEBUG #endif VS_VERSION_INFO VERSIONINFO FILEVERSION UGENE_VER_MAJOR,UGENE_VER_MINOR,UGENE_VER_BUILD,UGENE_VER_REVISION PRODUCTVERSION UGENE_VER_MAJOR,UGENE_VER_MINOR,UGENE_VER_BUILD FILEFLAGSMASK VS_FFI_FILEFLAGSMASK //FILEFLAGS (VER_PRIVATEBUILD|VER_PRERELEASE|VER_DEBUG) FILEFLAGS (VER_DEBUG) //FILEOS VOS__WINDOWS32 FILETYPE VFT_APP BEGIN BLOCK "StringFileInfo" BEGIN BLOCK "040904E4" BEGIN VALUE "CompanyName", "Unipro, Russia" VALUE "FileDescription", "Post-mortem reporter of UGENE" VALUE "FileVersion", TOSTRING(UGENE_VER_MAJOR.UGENE_VER_MINOR.UGENE_VER_BUILD.UGENE_VER_REVISION) //VALUE "InternalName", VER_INTERNALNAME_STR //VALUE "LegalCopyright", VER_LEGALCOPYRIGHT_STR //VALUE "LegalTrademarks1", VER_LEGALTRADEMARKS1_STR //VALUE "LegalTrademarks2", VER_LEGALTRADEMARKS2_STR VALUE "OriginalFilename", "ugenem" VALUE "ProductName", "Unipro UGENE" VALUE "ProductVersion", UGENE_VERSION_STRING VALUE "Comments", "UGENE is a free cross-platform genome analysis suite: http://ugene.unipro.ru/" END END END ugene-1.9.8/src/ugenem/src/0000755000175000017500000000000011651544337014161 5ustar ilyailyaugene-1.9.8/src/ugenem/src/SendReportDialog.cpp0000644000175000017500000001307111651544337020074 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "SendReportDialog.h" #include #include #define HOST_URL "http://ugene.unipro.ru" //#define HOST_URL "http://127.0.0.1" #define DESTINATION_URL_KEEPER_PAGE "/crash_reports_dest.html" void ReportSender::parse(const QString &htmlReport) { report = "Exception with code "; QStringList list = htmlReport.split("|"); if(list.size()== 7) { report += list.takeFirst() + " - "; report += list.takeFirst() + "\n\n"; report += "Operation system: "; report += getOSVersion() + "\n\n"; report += "UGENE version: "; report += list.takeFirst() + "\n\n"; report += "ActiveWindow: "; report += list.takeFirst() + "\n\n"; report += "Log:\n"; report += list.takeFirst() + "\n"; report += "Task tree:\n"; report += list.takeFirst() + "\n"; #if defined (Q_OS_WIN) report += list.takeLast(); #endif } else { foreach(const QString& str, list) { report += str + "\n"; } } QFile fp("/tmp/UGENEstacktrace.txt"); if(fp.open(QIODevice::ReadOnly)) { QByteArray stacktrace = fp.readAll(); report += "Stack trace:\n"; report += stacktrace.data(); if(stacktrace.isEmpty()) { QFile err("/tmp/UGENEerror"); if(err.open(QIODevice::ReadOnly)) { stacktrace = fp.readAll(); report += stacktrace.data(); err.close(); } } fp.close(); } } bool ReportSender::send(const QString &additionalInfo) { report += additionalInfo; SyncHTTP http(QUrl(HOST_URL).host()); QString reportsPath = http.syncGet( DESTINATION_URL_KEEPER_PAGE ); if( reportsPath.isEmpty() ) { return false; } if( QHttp::NoError != http.error() ) { return false; } SyncHTTP http2( QUrl(reportsPath).host() ); report.replace(' ', "_"); report.replace('\n', "|"); report.replace('\t', ""); report.replace("#", ""); report.replace("*", "

    "); report.replace("?", "-"); report.replace("~", "%7E"); report.replace("&", ""); QString fullPath = reportsPath; fullPath += "?data="; fullPath += report.toUtf8(); QString res = http2.syncGet(fullPath); if( QHttp::NoError != http.error() ) { return false; } return true; } SendReportDialog::SendReportDialog(const QString &report, QDialog *d): QDialog(d){ setupUi(this); sender.parse(report); errorEdit->setText(sender.getReport()); connect(additionalInfoTextEdit,SIGNAL(textChanged()), SLOT(sl_onMaximumMessageSizeReached())); connect(sendButton, SIGNAL(clicked()), SLOT(sl_onOKclicked())); connect(cancelButton, SIGNAL(clicked()), SLOT(reject())); } void SendReportDialog::sl_onMaximumMessageSizeReached(){ if(additionalInfoTextEdit->toPlainText().length() > 500 ){ QMessageBox msgBox; msgBox.setWindowTitle(tr("Warning")); msgBox.setText(tr("The \"Additional information\" message is too long.")); msgBox.setInformativeText(tr("You can also send the description of the problem to UGENE team" "by e-mail ugene@unipro.ru.")); msgBox.setStandardButtons(QMessageBox::Ok); msgBox.setDefaultButton(QMessageBox::Ok); msgBox.exec(); additionalInfoTextEdit->undo(); } } void SendReportDialog::sl_onOKclicked() { QString htmlReport = ""; if(!emailLineEdit->text().isEmpty()){ htmlReport += "\nUser email: "; htmlReport += emailLineEdit->text() + "\n"; } if(!additionalInfoTextEdit->toPlainText().isEmpty()){ htmlReport += "\nAdditional info: \n"; htmlReport += additionalInfoTextEdit->toPlainText() + "\n"; } if(sender.send(htmlReport)) { accept(); } } QString ReportSender::getOSVersion() { QString result; #if defined(Q_OS_WIN32) result = "Windows x86"; #elif defined(Q_OS_WIN64) result = "Windows x64"; #elif defined(Q_OS_LINUX) result = "Linux"; #elif defined(Q_OS_MAC) result = "MACOS"; #else result = "Unsupported OS"; #endif return result; } SyncHTTP::SyncHTTP(const QString& hostName, quint16 port, QObject* parent) : QHttp(hostName,port,parent), requestID(-1) { connect(this,SIGNAL(requestFinished(int,bool)),SLOT(finished(int,bool))); } QString SyncHTTP::syncGet(const QString& path) { QBuffer to; requestID = get(path, &to); loop.exec(); return QString(to.data()); } QString SyncHTTP::syncPost(const QString& path, const QByteArray& data) { QBuffer to; requestID = post(path, data, &to); loop.exec(); return QString(to.data()); } void SyncHTTP::finished(int, bool) { loop.exit(); } ugene-1.9.8/src/ugenem/src/main.cpp0000644000175000017500000000400711651544337015612 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include #include #include #include "SendReportDialog.h" #ifdef Q_OS_LINUX #include #endif int main(int argc, char *argv[]){ QString message; if(argc > 1) { message = QString::fromUtf8(QByteArray::fromBase64(argv[1])); } else { message = ""; } #ifdef Q_OS_LINUX if(XOpenDisplay(NULL) == NULL) { QCoreApplication a(argc, argv); QTextStream stream(stdin); QTextStream cout(stdout); printf("UGENE crashed. Would you like to send crash report to developer team? (y/n)\n"); QString str = stream.readLine(); printf("\n%s", str.toUtf8().data()); if(str == "y" || str == "Y") { ReportSender sender; sender.parse(message); sender.send(""); } } else { QApplication a(argc, argv); SendReportDialog dlg(message); dlg.setWindowIcon(QIcon(":ugenem/images/crash_icon.png")); dlg.exec(); } #else QApplication a(argc, argv); SendReportDialog dlg(message); dlg.setWindowIcon(QIcon(":ugenem/images/crash_icon.png")); dlg.exec(); #endif return 0; }ugene-1.9.8/src/ugenem/src/ui/0000755000175000017500000000000011651544337014576 5ustar ilyailyaugene-1.9.8/src/ugenem/src/ui/SendReportDialog.ui0000644000175000017500000000456211651544337020351 0ustar ilyailya Dialog 0 0 556 511 UGENE Crash Reporter ../crash_icon.png../crash_icon.png A fatal error has occurred during the program execution. Would you like to send the following crash report to UGENE team? true Additional information (optional) Enter your e-mail to stay in touch (optional) 200 Qt::Horizontal 40 20 Send Don't send ugene-1.9.8/src/ugenem/src/SendReportDialog.h0000644000175000017500000000400011651544337017531 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _SEND_REPORT_DIALOG_H_ #define _SEND_REPORT_DIALOG_H_ #include #include #include #include #include #include #include #include "../_tmp/ui/ui_SendReportDialog.h" class SyncHTTP : public QHttp { Q_OBJECT public: SyncHTTP(const QString& hostName, quint16 port=80, QObject* parent=0); QString syncGet(const QString& path); QString syncPost(const QString& path, const QByteArray &data); protected slots: virtual void finished(int idx, bool err); private: int requestID; QEventLoop loop; }; class ReportSender { public: ReportSender(): report("") {} void parse(const QString &str); bool send(const QString &additionalInfo); QString getOSVersion(); QString getReport() const {return report;} private: QString report; }; class SendReportDialog:public QDialog, public Ui_Dialog{ Q_OBJECT public: SendReportDialog(const QString &report, QDialog *d = NULL); private slots: void sl_onOKclicked(); void sl_onMaximumMessageSizeReached(); public: ReportSender sender; }; #endif ugene-1.9.8/src/ugenem/ugenem.qrc0000644000175000017500000000015211651544337015357 0ustar ilyailya images/crash_icon.png ugene-1.9.8/src/corelibs/0000755000175000017500000000000011651544334013711 5ustar ilyailyaugene-1.9.8/src/corelibs/U2Private/0000755000175000017500000000000011651544333015531 5ustar ilyailyaugene-1.9.8/src/corelibs/U2Private/U2Private.pri0000644000175000017500000000113511651544333020066 0ustar ilyailya# include (U2Private.pri) UGENE_RELATIVE_DESTDIR = '' MODULE_ID=U2Private include( ../../ugene_lib_common.pri ) QT += xml DEFINES+= QT_FATAL_ASSERT BUILDING_U2PRIVATE_DLL LIBS += -L../../_release -lU2Core -lU2Formats !debug_and_release|build_pass { CONFIG(debug, debug|release) { DESTDIR=../../_debug LIBS -= -L../../_release -lU2Core -lU2Formats LIBS += -L../../_debug -lU2Cored -lU2Formatsd } CONFIG(release, debug|release) { DESTDIR=../../_release } } unix { target.path = $$UGENE_INSTALL_DIR/$$UGENE_RELATIVE_DESTDIR INSTALLS += target } ugene-1.9.8/src/corelibs/U2Private/src/0000755000175000017500000000000011651544333016320 5ustar ilyailyaugene-1.9.8/src/corelibs/U2Private/src/PluginSupportImpl.h0000644000175000017500000000573411651544333022157 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_PLUGINSUPPORT_IMPL_ #define _U2_PLUGINSUPPORT_IMPL_ #include "private.h" #include #include #include #include #include "PluginDescriptor.h" #include namespace U2 { class ServiceRegistryImpl; class AddPluginTask; class RemovePluginTask; class PluginRef { public: PluginRef(Plugin* _plugin, QLibrary* _library, const PluginDesc& desc); ~PluginRef(); Plugin* plugin; QLibrary* library; PluginDesc pluginDesc; bool removeFlag; }; class U2PRIVATE_EXPORT PluginSupportImpl : public PluginSupport { Q_OBJECT friend class AddPluginTask; public: PluginSupportImpl(); ~PluginSupportImpl(); virtual const QList& getPlugins() {return plugins;} virtual Task* addPluginTask(const QString& pathToPlugin); //plugin will not be removed from the plugin list during the next app run virtual void setRemoveFlag(Plugin* p, bool v); virtual bool getRemoveFlag(Plugin* p) const; static bool isDefaultPluginsDir(const QString& url); static QDir getDefaultPluginsDir(); PluginRef* findRef(Plugin* p) const; PluginRef* findRefById(const QString& pluginId) const; virtual bool isAllPluginsLoaded() const; bool allLoaded; protected: void registerPlugin(PluginRef* ref); QString getPluginFileURL(Plugin* p) const; void updateSavedState(PluginRef* ref); private: QList plugRefs; QList plugins; }; class AddPluginTask : public Task { Q_OBJECT public: AddPluginTask(PluginSupportImpl* ps, const PluginDesc& desc); ReportResult report(); private: PluginSupportImpl* ps; PluginDesc desc; }; class LoadAllPluginsTask : public Task { Q_OBJECT public: LoadAllPluginsTask(PluginSupportImpl* ps,const QStringList& pluginFiles); void prepare(); ReportResult report(); private: void addToOrderingQueue(const QString& url); PluginSupportImpl* ps; QStringList pluginFiles; QList orderedPlugins; // plugins ordered by desc }; }//namespace #endif ugene-1.9.8/src/corelibs/U2Private/src/DocumentFormatRegistryImpl.cpp0000644000175000017500000001171411651544333024332 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "DocumentFormatRegistryImpl.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include namespace U2 { bool DocumentFormatRegistryImpl::registerFormat(DocumentFormat* f) { assert(getFormatById(f->getFormatId())==NULL); formats.push_back(f); emit si_documentFormatRegistered(f); if (f->getFormatDescription().isEmpty()) { coreLog.trace("Warn! Format has no description: " + f->getFormatName()); } return true; } QList DocumentFormatRegistryImpl::getRegisteredFormats() const { QList ids; foreach(DocumentFormat* df, formats) { ids.append(df->getFormatId()); } return ids; } DocumentFormat* DocumentFormatRegistryImpl::selectFormatByFileExtension(const QString& fileExt) const { foreach(DocumentFormat* df, formats) { if (df->getSupportedDocumentFileExtensions().contains(fileExt)) { return df; } } return NULL; } QList DocumentFormatRegistryImpl::selectFormats(const DocumentFormatConstraints& c) const { QList ids; foreach(DocumentFormat* df, formats) { if (df->checkConstraints(c)) { ids.append(df->getFormatId()); } } return ids; } bool DocumentFormatRegistryImpl::unregisterFormat(DocumentFormat* f) { int n = formats.removeAll(f); bool res = n > 0; if (res) { emit si_documentFormatUnregistered(f); } return res; } DocumentFormat* DocumentFormatRegistryImpl::getFormatById(DocumentFormatId id) const { foreach (DocumentFormat* f, formats) { if (f->getFormatId() == id) { return f; } } return NULL; } void DocumentFormatRegistryImpl::init() { PlainTextFormat* text = new PlainTextFormat(this); registerFormat(text); FastaFormat* fasta = new FastaFormat(this); registerFormat(fasta); GenbankPlainTextFormat* gb = new GenbankPlainTextFormat(this); registerFormat(gb); EMBLPlainTextFormat* em = new EMBLPlainTextFormat(this); registerFormat(em); SwissProtPlainTextFormat* sp = new SwissProtPlainTextFormat(this); registerFormat(sp); ABIFormat* abi = new ABIFormat(this); registerFormat(abi); SCFFormat* scf = new SCFFormat(this); registerFormat(scf); RawDNASequenceFormat* rsf = new RawDNASequenceFormat(this); registerFormat(rsf); ClustalWAlnFormat* aln = new ClustalWAlnFormat(this); registerFormat(aln); StockholmFormat* stf = new StockholmFormat(this); registerFormat(stf); NewickFormat* nwf = new NewickFormat(this); registerFormat(nwf); PDBFormat* pdb = new PDBFormat(this); registerFormat(pdb); FastqFormat* ftq = new FastqFormat(this); registerFormat(ftq); IndexFormat* indf = new IndexFormat(this); registerFormat(indf); ASNFormat* asn = new ASNFormat(this); registerFormat(asn); MSFFormat* msf = new MSFFormat(this); registerFormat(msf); GFFFormat *gff = new GFFFormat(this); registerFormat(gff); NEXUSFormat* nexus = new NEXUSFormat(this); registerFormat(nexus); SAMFormat *sam = new SAMFormat(this); sam->setNeverDetect(true); registerFormat(sam); MegaFormat *meg = new MegaFormat(this); registerFormat(meg); ACEFormat *ace = new ACEFormat(this); registerFormat(ace); PDWFormat *pdw = new PDWFormat(this); registerFormat(pdw); } }//namespace ugene-1.9.8/src/corelibs/U2Private/src/TaskSchedulerImpl.h0000644000175000017500000001177711651544333022071 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_TASK_SCHEDULER_IMPL_H_ #define _U2_TASK_SCHEDULER_IMPL_H_ #include "private.h" #include #include #include #include #include namespace U2 { class TaskInfo; class AppResourcePool; class AppResource; class TaskThread : public QThread { public: TaskThread(TaskInfo* _ti) : ti(_ti),finishEventListener(NULL) {} void run(); TaskInfo* ti; QObject* finishEventListener; }; class TaskInfo { public: TaskInfo(Task* t, TaskInfo* p) : task(t), parentTaskInfo(p), wasPrepared(false), subtasksWereCanceled(false), selfRunFinished(false), hasLockedPrepareResources(false), hasLockedRunResources(false), prevProgress(0), numPreparedSubtasks(0), numRunningSubtasks(0), numFinishedSubtasks(0), thread(NULL) {} virtual ~TaskInfo(); //true if task state >= RUN && thread is finished or not used at all Task* task; TaskInfo* parentTaskInfo; QList newSubtasks; bool wasPrepared; // 'true' if prepare() was called for the task bool subtasksWereCanceled; // 'true' if canceled task has called cancel() on its subtasks bool selfRunFinished; // indicates that the 'run' method of this task was finished bool hasLockedPrepareResources; //true if there were resource locks for 'prepare' stage bool hasLockedRunResources; //true if there were resource locks for 'run' stage int prevProgress; //used for TaskProgress_Manual QString prevDesc; int numPreparedSubtasks; int numRunningSubtasks; int numFinishedSubtasks; TaskThread* thread; inline int numActiveSubtasks() const { return numPreparedSubtasks+numRunningSubtasks; } }; class U2PRIVATE_EXPORT TaskSchedulerImpl : public TaskScheduler { Q_OBJECT public: TaskSchedulerImpl(AppResourcePool* rp); ~TaskSchedulerImpl(); virtual void registerTopLevelTask(Task* t); virtual void unregisterTopLevelTask(Task* t); const QList& getTopLevelTasks() const {return topLevelTasks;} Task * getTopLevelTaskById( qint64 id ) const; QDateTime estimatedFinishTime(Task*) const; virtual void cancelTask(Task* t); virtual void cancelAllTasks(); virtual QString getStateName(Task* t) const; void addThreadId(qint64 taskId, Qt::HANDLE id) {/*threadIds.insert(taskId, id);*/threadIds[taskId] = id;} void removeThreadId(qint64 taskId) {threadIds.remove(taskId);} qint64 getNameByThreadId(Qt::HANDLE id) const{return threadIds.key(id);} QList getMessages() {return schedulerLog->messages;} private slots: void update(); void sl_threadFinished(); private: bool processFinishedTasks(); void unregisterFinishedTopLevelTasks(); void processNewSubtasks(); void prepareNewTasks(); void runReady(); bool readyToFinish(TaskInfo* ti); bool addToPriorityQueue(Task* t, TaskInfo* parentInfo); //return true if added. Failure can be caused if a task requires resources void runThread(TaskInfo* pi); void stopTask(Task* t); void updateTaskProgressAndDesc(TaskInfo* ti); void promoteTask(TaskInfo* ti, Task::State newState); void deleteTask(Task* t); QString tryLockResources(Task* task, bool prepareStage, bool& hasLockedResourcesAfterCall); //returns error message void releaseResources(TaskInfo* ti, bool prepareStage); void propagateStateToParent(Task* t); void updateOldTasksPriority(); void checkSerialPromotion(TaskInfo* pti, Task* subtask); private: QTimer timer; QList topLevelTasks; QList priorityQueue; QList tasksWithNewSubtasks; QList newTasks; QStringList stateNames; QMap threadIds; AppResourcePool* resourcePool; AppResource* threadsResource; bool stateChangesObserved; LogCache* schedulerLog; }; } //namespace #endif ugene-1.9.8/src/corelibs/U2Private/src/SettingsImpl.cpp0000644000175000017500000001115111651544333021445 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "SettingsImpl.h" #include #include #include #include #include #include #include namespace U2 { #ifdef _DEBUG #define PRODUCT_NAME "UGENED" #else #define PRODUCT_NAME "UGENE" #endif static QString findKey(const QStringList& envList, const QString& key) { QString prefix = key + "="; QString result; foreach(const QString& var, envList) { if (var.startsWith(prefix)) { result = var.mid(prefix.length()); break; } } return result; } static QString preparePath(const QString& pathName) { QString result = pathName.trimmed().replace("//", "/").replace("\\", "/"); if (result.endsWith("/")) { result = result.left(result.length() - 1) ; } return result; } SettingsImpl::SettingsImpl(QSettings::Scope scope) { QString fileName; QStringList envList = QProcess::systemEnvironment(); static const QString configFileName = QString("%1.ini").arg(PRODUCT_NAME); if (scope == QSettings::UserScope) { // check for local cfg file -> portable UGENE bool localCfg = false; QDir dir(QDir::current()); QFileInfoList dirEntries = dir.entryInfoList(); foreach(const QFileInfo& entry, dirEntries) { if (entry.fileName() == configFileName) { fileName = entry.filePath(); localCfg = true; break; } } if (!localCfg) { fileName = AppContext::getCMDLineRegistry()->getParameterValue( CMDLineCoreOptions::INI_FILE ); if (fileName.isEmpty()) { fileName = findKey(envList, "UGENE_USER_INI"); } } } else { fileName = findKey(envList, "UGENE_SYSTEM_INI"); } if (fileName.isEmpty()) { #ifdef Q_WS_MAC QSettings::Format format = QSettings::NativeFormat; #else QSettings::Format format = QSettings::IniFormat; #endif settings = new QSettings(format, scope, "Unipro", PRODUCT_NAME, this); } else { settings = new QSettings(fileName, QSettings::IniFormat, this); } } SettingsImpl::~SettingsImpl() { settings->sync(); } bool SettingsImpl::contains(const QString& pathName) const { QMutexLocker lock(&threadSafityLock); QString key = preparePath(pathName); return settings->contains(key); } void SettingsImpl::remove(const QString& pathName) { QMutexLocker lock(&threadSafityLock); QString key = preparePath(pathName); settings->remove(key); } QVariant SettingsImpl::getValue(const QString& pathName, const QVariant& defaultValue) const { QMutexLocker lock(&threadSafityLock); QString path = pathName; QString key = preparePath(path); return settings->value(key, defaultValue); } void SettingsImpl::setValue(const QString& pathName, const QVariant& value) { QMutexLocker lock(&threadSafityLock); QString path = pathName; QString key = preparePath(path); settings->setValue(key, value); } QString SettingsImpl::toVersionKey(const QString& key) const { static QString VERSION_KEY_SUFFIX = "/" + Version::ugeneVersion().text; if (key.endsWith("/")) { return key + VERSION_KEY_SUFFIX + "/"; } return key + VERSION_KEY_SUFFIX; } QStringList SettingsImpl::getAllKeys(const QString& path) { QMutexLocker lock(&threadSafityLock); QString key = preparePath(path); settings->beginGroup(key); QStringList allKeys = settings->allKeys(); settings->endGroup(); return allKeys; } void SettingsImpl::sync() { QMutexLocker lock(&threadSafityLock); settings->sync(); } QString SettingsImpl::fileName() const { return settings->fileName(); } }//namespace ugene-1.9.8/src/corelibs/U2Private/src/StackWalker.cpp0000644000175000017500000011116011651544333021237 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ /********************************************************************** * LICENSE (http://www.opensource.org/licenses/bsd-license.php) * * Copyright (c) 2005-2011, Jochen Kalmbach * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Jochen Kalmbach nor the names of its contributors may be * used to endorse or promote products derived from this software without * specific prior written permission. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * **********************************************************************/ #if defined(USE_CRASHHANDLER) #include "StackWalker.h" #if defined (Q_OS_WIN) #pragma comment(lib, "version.lib") // for "VerQueryValue" #include #include #include #include #include #include #define USED_CONTEXT_FLAGS CONTEXT_ALL namespace U2 { class StackWalkerInternal { public: StackWalkerInternal(StackWalker *parent, HANDLE hProcess) { m_parent = parent; m_hDbhHelp = NULL; pSC = NULL; m_hProcess = hProcess; m_szSymPath = NULL; pSFTA = NULL; pSGLFA = NULL; pSGMB = NULL; pSGMI = NULL; pSGO = NULL; pSGSFA = NULL; pSI = NULL; pSLM = NULL; pSSO = NULL; pSW = NULL; pUDSN = NULL; pSGSP = NULL; } ~StackWalkerInternal() { if (pSC != NULL) { pSC(m_hProcess); // SymCleanup } if (m_hDbhHelp != NULL) { FreeLibrary(m_hDbhHelp); } m_hDbhHelp = NULL; m_parent = NULL; if(m_szSymPath != NULL) { free(m_szSymPath); } m_szSymPath = NULL; } BOOL Init(LPCSTR szSymPath) { if (m_parent == NULL) { return FALSE; } // Dynamically load the Entry-Points for dbghelp.dll: // First try to load the newest one from wchar_t szTemp[4096]; // But before we do this, we first check if the ".local" file exists if (GetModuleFileName(NULL, szTemp, 4096) > 0) { wcscat_s(szTemp, TEXT(".local")); if (GetFileAttributes(szTemp) == INVALID_FILE_ATTRIBUTES) { // ".local" file does not exist, so we can try to load the dbghelp.dll from the "Debugging Tools for Windows" if (GetEnvironmentVariable(TEXT("ProgramFiles"), szTemp, 4096) > 0) { wcscat_s(szTemp, TEXT("\\Debugging Tools for Windows\\dbghelp.dll")); // now check if the file exists: if (GetFileAttributes(szTemp) != INVALID_FILE_ATTRIBUTES){ m_hDbhHelp = LoadLibrary(szTemp); } } // Still not found? Then try to load the 64-Bit version: if ( (m_hDbhHelp == NULL) && (GetEnvironmentVariable(TEXT("ProgramFiles"), szTemp, 4096) > 0) ) { wcscat_s(szTemp, TEXT("\\Debugging Tools for Windows 64-Bit\\dbghelp.dll")); if (GetFileAttributes(szTemp) != INVALID_FILE_ATTRIBUTES){ m_hDbhHelp = LoadLibrary(szTemp); } } } } if (m_hDbhHelp == NULL) { // if not already loaded, try to load a default-one m_hDbhHelp = LoadLibrary( TEXT("dbghelp.dll") ); } if (m_hDbhHelp == NULL) { return FALSE; } pSI = (tSI) GetProcAddress(m_hDbhHelp, "SymInitialize" ); pSC = (tSC) GetProcAddress(m_hDbhHelp, "SymCleanup" ); pSW = (tSW) GetProcAddress(m_hDbhHelp, "StackWalk64" ); pSGO = (tSGO) GetProcAddress(m_hDbhHelp, "SymGetOptions" ); pSSO = (tSSO) GetProcAddress(m_hDbhHelp, "SymSetOptions" ); pSFTA = (tSFTA) GetProcAddress(m_hDbhHelp, "SymFunctionTableAccess64" ); pSGLFA = (tSGLFA) GetProcAddress(m_hDbhHelp, "SymGetLineFromAddr64" ); pSGMB = (tSGMB) GetProcAddress(m_hDbhHelp, "SymGetModuleBase64" ); pSGMI = (tSGMI) GetProcAddress(m_hDbhHelp, "SymGetModuleInfo64" ); //pSGMI_V3 = (tSGMI_V3) GetProcAddress(m_hDbhHelp, "SymGetModuleInfo64" ); pSGSFA = (tSGSFA) GetProcAddress(m_hDbhHelp, "SymGetSymFromAddr64" ); pUDSN = (tUDSN) GetProcAddress(m_hDbhHelp, "UnDecorateSymbolName" ); pSLM = (tSLM) GetProcAddress(m_hDbhHelp, "SymLoadModule64" ); pSGSP =(tSGSP) GetProcAddress(m_hDbhHelp, "SymGetSearchPath" ); if ( pSC == NULL || pSFTA == NULL || pSGMB == NULL || pSGMI == NULL || pSGO == NULL || pSGSFA == NULL || pSI == NULL || pSSO == NULL || pSW == NULL || pUDSN == NULL || pSLM == NULL ) { FreeLibrary(m_hDbhHelp); m_hDbhHelp = NULL; pSC = NULL; return FALSE; } // SymInitialize if (szSymPath != NULL) { m_szSymPath = _strdup(szSymPath); } if (this->pSI(m_hProcess, m_szSymPath, FALSE) == FALSE) { this->m_parent->OnDbgHelpErr("SymInitialize", GetLastError(), 0); } DWORD symOptions = this->pSGO(); // SymGetOptions symOptions |= SYMOPT_LOAD_LINES; symOptions |= SYMOPT_FAIL_CRITICAL_ERRORS; // SymSetOptions symOptions = this->pSSO(symOptions); char buf[StackWalker::STACKWALK_MAX_NAMELEN] = {0}; if (this->pSGSP != NULL) { if (this->pSGSP(m_hProcess, buf, StackWalker::STACKWALK_MAX_NAMELEN) == FALSE) { this->m_parent->OnDbgHelpErr("SymGetSearchPath", GetLastError(), 0); } } char szUserName[1024] = {0}; DWORD dwSize = 1024; GetUserNameA(szUserName, &dwSize); this->m_parent->OnSymInit(buf, symOptions, szUserName); return TRUE; } StackWalker *m_parent; HMODULE m_hDbhHelp; HANDLE m_hProcess; LPSTR m_szSymPath; typedef struct IMAGEHLP_MODULE64_V2 { DWORD SizeOfStruct; // set to sizeof(IMAGEHLP_MODULE64) DWORD64 BaseOfImage; // base load address of module DWORD ImageSize; // virtual size of the loaded module DWORD TimeDateStamp; // date/time stamp from pe header DWORD CheckSum; // checksum from the pe header DWORD NumSyms; // number of symbols in the symbol table SYM_TYPE SymType; // type of symbols loaded CHAR ModuleName[32]; // module name CHAR ImageName[256]; // image name CHAR LoadedImageName[256]; // symbol file name }; // SymCleanup() typedef BOOL (__stdcall *tSC)( IN HANDLE hProcess ); tSC pSC; // SymFunctionTableAccess64() typedef PVOID (__stdcall *tSFTA)( HANDLE hProcess, DWORD64 AddrBase ); tSFTA pSFTA; // SymGetLineFromAddr64() typedef BOOL (__stdcall *tSGLFA)( IN HANDLE hProcess, IN DWORD64 dwAddr, OUT PDWORD pdwDisplacement, OUT PIMAGEHLP_LINE64 Line ); tSGLFA pSGLFA; // SymGetModuleBase64() typedef DWORD64 (__stdcall *tSGMB)( IN HANDLE hProcess, IN DWORD64 dwAddr ); tSGMB pSGMB; // SymGetModuleInfo64() typedef BOOL (__stdcall *tSGMI)( IN HANDLE hProcess, IN DWORD64 dwAddr, OUT IMAGEHLP_MODULE64_V2 *ModuleInfo ); tSGMI pSGMI; // SymGetOptions() typedef DWORD (__stdcall *tSGO)( VOID ); tSGO pSGO; // SymGetSymFromAddr64() typedef BOOL (__stdcall *tSGSFA)( IN HANDLE hProcess, IN DWORD64 dwAddr, OUT PDWORD64 pdwDisplacement, OUT PIMAGEHLP_SYMBOL64 Symbol ); tSGSFA pSGSFA; // SymInitialize() typedef BOOL (__stdcall *tSI)( IN HANDLE hProcess, IN PSTR UserSearchPath, IN BOOL fInvadeProcess ); tSI pSI; // SymLoadModule64() typedef DWORD64 (__stdcall *tSLM)( IN HANDLE hProcess, IN HANDLE hFile, IN PSTR ImageName, IN PSTR ModuleName, IN DWORD64 BaseOfDll, IN DWORD SizeOfDll ); tSLM pSLM; // SymSetOptions() typedef DWORD (__stdcall *tSSO)( IN DWORD SymOptions ); tSSO pSSO; // StackWalk64() typedef BOOL (__stdcall *tSW)( DWORD MachineType, HANDLE hProcess, HANDLE hThread, LPSTACKFRAME64 StackFrame, PVOID ContextRecord, PREAD_PROCESS_MEMORY_ROUTINE64 ReadMemoryRoutine, PFUNCTION_TABLE_ACCESS_ROUTINE64 FunctionTableAccessRoutine, PGET_MODULE_BASE_ROUTINE64 GetModuleBaseRoutine, PTRANSLATE_ADDRESS_ROUTINE64 TranslateAddress ); tSW pSW; // UnDecorateSymbolName() typedef DWORD (__stdcall WINAPI *tUDSN)( PCSTR DecoratedName, PSTR UnDecoratedName, DWORD UndecoratedLength, DWORD Flags ); tUDSN pUDSN; typedef BOOL (__stdcall WINAPI *tSGSP)(HANDLE hProcess, PSTR SearchPath, DWORD SearchPathLength); tSGSP pSGSP; private: // **************************************** ToolHelp32 ************************ #define MAX_MODULE_NAME32 255 #define TH32CS_SNAPMODULE 0x00000008 #pragma pack( push, 8 ) typedef struct tagMODULEENTRY32 { DWORD dwSize; DWORD th32ModuleID; // This module DWORD th32ProcessID; // owning process DWORD GlblcntUsage; // Global usage count on the module DWORD ProccntUsage; // Module usage count in th32ProcessID's context BYTE * modBaseAddr; // Base address of module in th32ProcessID's context DWORD modBaseSize; // Size in bytes of module starting at modBaseAddr HMODULE hModule; // The hModule of this module in th32ProcessID's context char szModule[MAX_MODULE_NAME32 + 1]; char szExePath[MAX_PATH]; } MODULEENTRY32; typedef MODULEENTRY32 * PMODULEENTRY32; typedef MODULEENTRY32 * LPMODULEENTRY32; #pragma pack( pop ) BOOL GetModuleListTH32(HANDLE hProcess, DWORD pid) { // CreateToolhelp32Snapshot() typedef HANDLE (__stdcall *tCT32S)(DWORD dwFlags, DWORD th32ProcessID); // Module32First() typedef BOOL (__stdcall *tM32F)(HANDLE hSnapshot, LPMODULEENTRY32 lpme); // Module32Next() typedef BOOL (__stdcall *tM32N)(HANDLE hSnapshot, LPMODULEENTRY32 lpme); // try both dlls... const wchar_t *dllname[] = { TEXT("kernel32.dll"), TEXT("tlhelp32.dll") }; HINSTANCE hToolhelp = NULL; tCT32S pCT32S = NULL; tM32F pM32F = NULL; tM32N pM32N = NULL; HANDLE hSnap; MODULEENTRY32 me; me.dwSize = sizeof(me); BOOL keepGoing; size_t i; for (i = 0; i<(sizeof(dllname) / sizeof(dllname[0])); i++ ) { hToolhelp = LoadLibrary( dllname[i] ); if (hToolhelp == NULL) { continue; } pCT32S = (tCT32S) GetProcAddress(hToolhelp, "CreateToolhelp32Snapshot"); pM32F = (tM32F) GetProcAddress(hToolhelp, "Module32First"); pM32N = (tM32N) GetProcAddress(hToolhelp, "Module32Next"); if ( (pCT32S != NULL) && (pM32F != NULL) && (pM32N != NULL) ) { break; // found the functions! } FreeLibrary(hToolhelp); hToolhelp = NULL; } if (hToolhelp == NULL) { return FALSE; } hSnap = pCT32S( TH32CS_SNAPMODULE, pid ); if (hSnap == (HANDLE) -1) { return FALSE; } keepGoing = !!pM32F( hSnap, &me ); int cnt = 0; while (keepGoing){ this->LoadModule(hProcess, me.szExePath, me.szModule, (DWORD64) me.modBaseAddr, me.modBaseSize); cnt++; keepGoing = !!pM32N( hSnap, &me ); } CloseHandle(hSnap); FreeLibrary(hToolhelp); if (cnt <= 0) { return FALSE; } return TRUE; } // GetModuleListTH32 // **************************************** PSAPI ************************ typedef struct _MODULEINFO { LPVOID lpBaseOfDll; DWORD SizeOfImage; LPVOID EntryPoint; } MODULEINFO, *LPMODULEINFO; BOOL GetModuleListPSAPI(HANDLE hProcess) { // EnumProcessModules() typedef BOOL (__stdcall *tEPM)(HANDLE hProcess, HMODULE *lphModule, DWORD cb, LPDWORD lpcbNeeded ); // GetModuleFileNameEx() typedef DWORD (__stdcall *tGMFNE)(HANDLE hProcess, HMODULE hModule, LPSTR lpFilename, DWORD nSize ); // GetModuleBaseName() typedef DWORD (__stdcall *tGMBN)(HANDLE hProcess, HMODULE hModule, LPSTR lpFilename, DWORD nSize ); // GetModuleInformation() typedef BOOL (__stdcall *tGMI)(HANDLE hProcess, HMODULE hModule, LPMODULEINFO pmi, DWORD nSize ); HINSTANCE hPsapi; tEPM pEPM; tGMFNE pGMFNE; tGMBN pGMBN; tGMI pGMI; DWORD i; //ModuleEntry e; DWORD cbNeeded; MODULEINFO mi; HMODULE *hMods = 0; char *tt = NULL; char *tt2 = NULL; const SIZE_T TTBUFLEN = 8096; int cnt = 0; hPsapi = LoadLibrary( TEXT("psapi.dll") ); if (hPsapi == NULL) { return FALSE; } pEPM = (tEPM) GetProcAddress( hPsapi, "EnumProcessModules" ); pGMFNE = (tGMFNE) GetProcAddress( hPsapi, "GetModuleFileNameExA" ); pGMBN = (tGMFNE) GetProcAddress( hPsapi, "GetModuleBaseNameA" ); pGMI = (tGMI) GetProcAddress( hPsapi, "GetModuleInformation" ); if ( (pEPM == NULL) || (pGMFNE == NULL) || (pGMBN == NULL) || (pGMI == NULL) ) { // we couldn't find all functions FreeLibrary(hPsapi); return FALSE; } hMods = (HMODULE*) malloc(sizeof(HMODULE) * (TTBUFLEN / sizeof HMODULE)); tt = (char*) malloc(sizeof(char) * TTBUFLEN); tt2 = (char*) malloc(sizeof(char) * TTBUFLEN); if (!(((hMods == NULL) || (tt == NULL) || (tt2 == NULL)) || ! pEPM( hProcess, hMods, TTBUFLEN, &cbNeeded ) || cbNeeded > TTBUFLEN)) { for ( i = 0; i < cbNeeded / sizeof hMods[0]; i++ ){ // base address, size pGMI(hProcess, hMods[i], &mi, sizeof mi ); // image file name tt[0] = 0; pGMFNE(hProcess, hMods[i], tt, TTBUFLEN ); // module name tt2[0] = 0; pGMBN(hProcess, hMods[i], tt2, TTBUFLEN ); DWORD dwRes = this->LoadModule(hProcess, tt, tt2, (DWORD64) mi.lpBaseOfDll, mi.SizeOfImage); if (dwRes != ERROR_SUCCESS) this->m_parent->OnDbgHelpErr("LoadModule", dwRes, 0); cnt++; } } if (hPsapi != NULL) FreeLibrary(hPsapi); if (tt2 != NULL) free(tt2); if (tt != NULL) free(tt); if (hMods != NULL) free(hMods); return cnt != 0; } // GetModuleListPSAPI DWORD LoadModule(HANDLE hProcess, LPCSTR img, LPCSTR mod, DWORD64 baseAddr, DWORD size) { CHAR *szImg = _strdup(img); CHAR *szMod = _strdup(mod); DWORD result = ERROR_SUCCESS; if ( (szImg == NULL) || (szMod == NULL) ) result = ERROR_NOT_ENOUGH_MEMORY; else { if (pSLM(hProcess, 0, szImg, szMod, baseAddr, size) == 0) result = GetLastError(); } ULONGLONG fileVersion = 0; if ( (m_parent != NULL) && (szImg != NULL) ) { // try to retrive the file-version: if ( (this->m_parent->m_options & StackWalker::RetrieveFileVersion) != 0) { VS_FIXEDFILEINFO *fInfo = NULL; DWORD dwHandle; DWORD dwSize = GetFileVersionInfoSizeA(szImg, &dwHandle); if (dwSize > 0) { LPVOID vData = malloc(dwSize); if (vData != NULL) { if (GetFileVersionInfoA(szImg, dwHandle, dwSize, vData) != 0) { UINT len; TCHAR szSubBlock[] = TEXT("\\"); if (VerQueryValue(vData, szSubBlock, (LPVOID*) &fInfo, &len) == 0) fInfo = NULL; else { fileVersion = ((ULONGLONG)fInfo->dwFileVersionLS) + ((ULONGLONG)fInfo->dwFileVersionMS << 32); } } free(vData); } } } // Retrive some additional-infos about the module IMAGEHLP_MODULE64_V2 Module; const char *szSymType = "-unknown-"; if (this->GetModuleInfo(hProcess, baseAddr, &Module) != FALSE) { switch(Module.SymType) { case SymNone: szSymType = "-nosymbols-"; break; case SymCoff: szSymType = "COFF"; break; case SymCv: szSymType = "CV"; break; case SymPdb: szSymType = "PDB"; break; case SymExport: szSymType = "-exported-"; break; case SymDeferred: szSymType = "-deferred-"; break; case SymSym: szSymType = "SYM"; break; case 8: //SymVirtual: szSymType = "Virtual"; break; case 9: // SymDia: szSymType = "DIA"; break; } } this->m_parent->OnLoadModule(img, mod, baseAddr, size, result, szSymType, Module.LoadedImageName, fileVersion); } if (szImg != NULL) free(szImg); if (szMod != NULL) free(szMod); return result; } public: BOOL LoadModules(HANDLE hProcess, DWORD dwProcessId) { // first try toolhelp32 if (GetModuleListTH32(hProcess, dwProcessId)) { return true; } // then try psapi return GetModuleListPSAPI(hProcess); } bool GetModuleInfo(HANDLE hProcess, DWORD64 baseAddr, IMAGEHLP_MODULE64_V2 *pModuleInfo) { if(this->pSGMI == NULL){ SetLastError(ERROR_DLL_INIT_FAILED); return FALSE; } pModuleInfo->SizeOfStruct = sizeof(IMAGEHLP_MODULE64_V2); void *pData = malloc(4096); // reserve enough memory, so the bug in v6.3.5.1 does not lead to memory-overwrites... if (pData == NULL) { SetLastError(ERROR_NOT_ENOUGH_MEMORY); return FALSE; } memcpy(pData, pModuleInfo, sizeof(IMAGEHLP_MODULE64_V2)); if (this->pSGMI(hProcess, baseAddr, (IMAGEHLP_MODULE64_V2*) pData) != FALSE) { // only copy as much memory as is reserved... memcpy(pModuleInfo, pData, sizeof(IMAGEHLP_MODULE64_V2)); pModuleInfo->SizeOfStruct = sizeof(IMAGEHLP_MODULE64_V2); free(pData); return TRUE; } free(pData); SetLastError(ERROR_DLL_INIT_FAILED); return FALSE; } }; // ############################################################# StackWalker::StackWalker(DWORD dwProcessId, HANDLE hProcess) { this->m_options = OptionsAll; this->m_modulesLoaded = FALSE; this->m_hProcess = hProcess; this->m_sw = new StackWalkerInternal(this, this->m_hProcess); this->m_dwProcessId = dwProcessId; this->m_szSymPath = NULL; } StackWalker::StackWalker(int options, LPCSTR szSymPath, DWORD dwProcessId, HANDLE hProcess) { this->m_options = options; this->m_modulesLoaded = FALSE; this->m_hProcess = hProcess; this->m_sw = new StackWalkerInternal(this, this->m_hProcess); this->m_dwProcessId = dwProcessId; if (szSymPath != NULL) { this->m_szSymPath = _strdup(szSymPath); this->m_options |= SymBuildPath; } else { this->m_szSymPath = NULL; } } StackWalker::~StackWalker() { if (m_szSymPath != NULL) { free(m_szSymPath); } m_szSymPath = NULL; if (this->m_sw != NULL) { delete this->m_sw; } this->m_sw = NULL; } BOOL StackWalker::LoadModules() { if (this->m_sw == NULL) { SetLastError(ERROR_DLL_INIT_FAILED); return FALSE; } if (m_modulesLoaded != FALSE) { return TRUE; } // Build the sym-path: char *szSymPath = NULL; if ( (this->m_options & SymBuildPath) != 0) { const size_t nSymPathLen = 4096; szSymPath = (char*) malloc(nSymPathLen); if (szSymPath == NULL) { SetLastError(ERROR_NOT_ENOUGH_MEMORY); return FALSE; } szSymPath[0] = 0; // Now first add the (optional) provided sympath: if (this->m_szSymPath != NULL) { strcat_s(szSymPath, nSymPathLen, this->m_szSymPath); strcat_s(szSymPath, nSymPathLen, ";"); } strcat_s(szSymPath, nSymPathLen, ".;"); const size_t nTempLen = 1024; char szTemp[nTempLen]; // Now add the current directory: if (GetCurrentDirectoryA(nTempLen, szTemp) > 0) { szTemp[nTempLen-1] = 0; strcat_s(szSymPath, nSymPathLen, szTemp); strcat_s(szSymPath, nSymPathLen, ";"); } // Now add the path for the main-module: if (GetModuleFileNameA(NULL, szTemp, nTempLen) > 0) { szTemp[nTempLen-1] = 0; for (char *p = (szTemp+strlen(szTemp)-1); p >= szTemp; --p) { // locate the rightmost path separator if ( (*p == '\\') || (*p == '/') || (*p == ':') ) { *p = 0; break; } } // for (search for path separator...) if (strlen(szTemp) > 0){ strcat_s(szSymPath, nSymPathLen, szTemp); strcat_s(szSymPath, nSymPathLen, ";"); } } if (GetEnvironmentVariableA("_NT_SYMBOL_PATH", szTemp, nTempLen) > 0) { szTemp[nTempLen-1] = 0; strcat_s(szSymPath, nSymPathLen, szTemp); strcat_s(szSymPath, nSymPathLen, ";"); } if (GetEnvironmentVariableA("_NT_ALTERNATE_SYMBOL_PATH", szTemp, nTempLen) > 0) { szTemp[nTempLen-1] = 0; strcat_s(szSymPath, nSymPathLen, szTemp); strcat_s(szSymPath, nSymPathLen, ";"); } if (GetEnvironmentVariableA("SYSTEMROOT", szTemp, nTempLen) > 0) { szTemp[nTempLen-1] = 0; strcat_s(szSymPath, nSymPathLen, szTemp); strcat_s(szSymPath, nSymPathLen, ";"); // also add the "system32"-directory: strcat_s(szTemp, nTempLen, "\\system32"); strcat_s(szSymPath, nSymPathLen, szTemp); strcat_s(szSymPath, nSymPathLen, ";"); } if ( (this->m_options & SymBuildPath) != 0) { if (GetEnvironmentVariableA("SYSTEMDRIVE", szTemp, nTempLen) > 0) { szTemp[nTempLen-1] = 0; strcat_s(szSymPath, nSymPathLen, "SRV*"); strcat_s(szSymPath, nSymPathLen, szTemp); strcat_s(szSymPath, nSymPathLen, "\\websymbols"); strcat_s(szSymPath, nSymPathLen, "*http://msdl.microsoft.com/download/symbols;"); } else { strcat_s(szSymPath, nSymPathLen, "SRV*c:\\websymbols*http://msdl.microsoft.com/download/symbols;"); } } } // First Init the whole stuff... BOOL bRet = this->m_sw->Init(szSymPath); if (szSymPath != NULL) { free(szSymPath); } szSymPath = NULL; if (bRet == FALSE) { this->OnDbgHelpErr("Error while initializing dbghelp.dll", 0, 0); SetLastError(ERROR_DLL_INIT_FAILED); return FALSE; } bRet = this->m_sw->LoadModules(this->m_hProcess, this->m_dwProcessId); if (bRet != FALSE) { m_modulesLoaded = TRUE; } return bRet; } // The following is used to pass the "userData"-Pointer to the user-provided readMemoryFunction // This has to be done due to a problem with the "hProcess"-parameter in x64... // Because this class is in no case multi-threading-enabled (because of the limitations // of dbghelp.dll) it is "safe" to use a static-variable static StackWalker::PReadProcessMemoryRoutine s_readMemoryFunction = NULL; static LPVOID s_readMemoryFunction_UserData = NULL; bool StackWalker::ShowCallstack(HANDLE hThread, const CONTEXT *context, PReadProcessMemoryRoutine readMemoryFunction, LPVOID pUserData) { CONTEXT c; CallstackEntry csEntry; IMAGEHLP_SYMBOL64 *pSym = NULL; StackWalkerInternal::IMAGEHLP_MODULE64_V2 Module; IMAGEHLP_LINE64 Line; int frameNum; if (m_modulesLoaded == FALSE) this->LoadModules(); // ignore the result... if (this->m_sw->m_hDbhHelp == NULL) { SetLastError(ERROR_DLL_INIT_FAILED); return FALSE; } s_readMemoryFunction = readMemoryFunction; s_readMemoryFunction_UserData = pUserData; c = *context; // init STACKFRAME for first call STACKFRAME64 s; // in/out stackframe memset(&s, 0, sizeof(s)); DWORD imageType; #ifdef _M_IX86 // normally, call ImageNtHeader() and use machine info from PE header imageType = IMAGE_FILE_MACHINE_I386; s.AddrPC.Offset = c.Eip; s.AddrPC.Mode = AddrModeFlat; s.AddrFrame.Offset = c.Ebp; s.AddrFrame.Mode = AddrModeFlat; s.AddrStack.Offset = c.Esp; s.AddrStack.Mode = AddrModeFlat; #elif _M_X64 imageType = IMAGE_FILE_MACHINE_AMD64; s.AddrPC.Offset = c.Rip; s.AddrPC.Mode = AddrModeFlat; s.AddrFrame.Offset = c.Rsp; s.AddrFrame.Mode = AddrModeFlat; s.AddrStack.Offset = c.Rsp; s.AddrStack.Mode = AddrModeFlat; #elif _M_IA64 imageType = IMAGE_FILE_MACHINE_IA64; s.AddrPC.Offset = c.StIIP; s.AddrPC.Mode = AddrModeFlat; s.AddrFrame.Offset = c.IntSp; s.AddrFrame.Mode = AddrModeFlat; s.AddrBStore.Offset = c.RsBSP; s.AddrBStore.Mode = AddrModeFlat; s.AddrStack.Offset = c.IntSp; s.AddrStack.Mode = AddrModeFlat; #else #error "Platform not supported!" #endif pSym = (IMAGEHLP_SYMBOL64 *) malloc(sizeof(IMAGEHLP_SYMBOL64) + STACKWALK_MAX_NAMELEN); if (!pSym) goto cleanup; // not enough memory... memset(pSym, 0, sizeof(IMAGEHLP_SYMBOL64) + STACKWALK_MAX_NAMELEN); pSym->SizeOfStruct = sizeof(IMAGEHLP_SYMBOL64); pSym->MaxNameLength = STACKWALK_MAX_NAMELEN; memset(&Line, 0, sizeof(Line)); Line.SizeOfStruct = sizeof(Line); memset(&Module, 0, sizeof(Module)); Module.SizeOfStruct = sizeof(Module); for (frameNum = 0; ; ++frameNum ) { // get next stack frame (StackWalk64(), SymFunctionTableAccess64(), SymGetModuleBase64()) // if this returns ERROR_INVALID_ADDRESS (487) or ERROR_NOACCESS (998), you can // assume that either you are done, or that the stack is so hosed that the next // deeper frame could not be found. // CONTEXT need not to be suplied if imageTyp is IMAGE_FILE_MACHINE_I386! if ( ! this->m_sw->pSW(imageType, this->m_hProcess, hThread, &s, &c, myReadProcMem, this->m_sw->pSFTA, this->m_sw->pSGMB, NULL) ) { this->OnDbgHelpErr("StackWalk64", GetLastError(), s.AddrPC.Offset); break; } csEntry.offset = s.AddrPC.Offset; csEntry.name[0] = 0; csEntry.undName[0] = 0; csEntry.undFullName[0] = 0; csEntry.offsetFromSmybol = 0; csEntry.offsetFromLine = 0; csEntry.lineFileName[0] = 0; csEntry.lineNumber = 0; csEntry.loadedImageName[0] = 0; csEntry.moduleName[0] = 0; if (s.AddrPC.Offset == s.AddrReturn.Offset) { this->OnDbgHelpErr("StackWalk64-Endless-Callstack!", 0, s.AddrPC.Offset); break; } if (s.AddrPC.Offset != 0) { // we seem to have a valid PC // show procedure info (SymGetSymFromAddr64()) if (this->m_sw->pSGSFA(this->m_hProcess, s.AddrPC.Offset, &(csEntry.offsetFromSmybol), pSym) != FALSE) { // TODO: Mache dies sicher...! strcpy_s(csEntry.name, pSym->Name); // UnDecorateSymbolName() this->m_sw->pUDSN( pSym->Name, csEntry.undName, STACKWALK_MAX_NAMELEN, UNDNAME_NAME_ONLY ); this->m_sw->pUDSN( pSym->Name, csEntry.undFullName, STACKWALK_MAX_NAMELEN, UNDNAME_COMPLETE ); } else { this->OnDbgHelpErr("SymGetSymFromAddr64", GetLastError(), s.AddrPC.Offset); } // show line number info, NT5.0-method (SymGetLineFromAddr64()) if (this->m_sw->pSGLFA != NULL ) { // yes, we have SymGetLineFromAddr64() if (this->m_sw->pSGLFA(this->m_hProcess, s.AddrPC.Offset, &(csEntry.offsetFromLine), &Line) != FALSE) { csEntry.lineNumber = Line.LineNumber; // TODO: Mache dies sicher...! strcpy_s(csEntry.lineFileName, Line.FileName); } else { this->OnDbgHelpErr("SymGetLineFromAddr64", GetLastError(), s.AddrPC.Offset); } } // yes, we have SymGetLineFromAddr64() // show module info (SymGetModuleInfo64()) if (this->m_sw->GetModuleInfo(this->m_hProcess, s.AddrPC.Offset, &Module ) != FALSE) { // got module info OK switch ( Module.SymType ) { case SymNone: csEntry.symTypeString = "-nosymbols-"; break; case SymCoff: csEntry.symTypeString = "COFF"; break; case SymCv: csEntry.symTypeString = "CV"; break; case SymPdb: csEntry.symTypeString = "PDB"; break; case SymExport: csEntry.symTypeString = "-exported-"; break; case SymDeferred: csEntry.symTypeString = "-deferred-"; break; case SymSym: csEntry.symTypeString = "SYM"; break; #if API_VERSION_NUMBER >= 9 case SymDia: csEntry.symTypeString = "DIA"; break; #endif case 8: //SymVirtual: csEntry.symTypeString = "Virtual"; break; default: //_snprintf( ty, sizeof ty, "symtype=%ld", (long) Module.SymType ); csEntry.symTypeString = NULL; break; } // TODO: Mache dies sicher...! strcpy_s(csEntry.moduleName, Module.ModuleName); csEntry.baseOfImage = Module.BaseOfImage; strcpy_s(csEntry.loadedImageName, Module.LoadedImageName); } // got module info OK else { this->OnDbgHelpErr("SymGetModuleInfo64", GetLastError(), s.AddrPC.Offset); } } // we seem to have a valid PC CallstackEntryType et = nextEntry; if (frameNum == 0) et = firstEntry; this->OnCallstackEntry(et, csEntry); if (s.AddrReturn.Offset == 0) { this->OnCallstackEntry(lastEntry, csEntry); SetLastError(ERROR_SUCCESS); break; } } // for ( frameNum ) cleanup: if (pSym) free( pSym ); if (context == NULL) ResumeThread(hThread); return TRUE; } BOOL __stdcall StackWalker::myReadProcMem( HANDLE hProcess, DWORD64 qwBaseAddress, PVOID lpBuffer, DWORD nSize, LPDWORD lpNumberOfBytesRead ) { if (s_readMemoryFunction == NULL) { SIZE_T st; BOOL bRet = ReadProcessMemory(hProcess, (LPVOID) qwBaseAddress, lpBuffer, nSize, &st); *lpNumberOfBytesRead = (DWORD) st; return bRet; } else{ return s_readMemoryFunction(hProcess, qwBaseAddress, lpBuffer, nSize, lpNumberOfBytesRead, s_readMemoryFunction_UserData); } } void StackWalker::OnLoadModule(LPCSTR img, LPCSTR mod, DWORD64 baseAddr, DWORD size, DWORD result, LPCSTR symType, LPCSTR pdbName, ULONGLONG fileVersion) { libraries[(LPVOID)baseAddr] = QString(img); } void StackWalker::OnCallstackEntry(CallstackEntryType eType, CallstackEntry &entry) { QMap::iterator it = libraries.begin(); while(entry.offset > (DWORD)it.key() && it != libraries.end()) { it++; } it--; QString library = it.value(); DWORD libAddr = (DWORD)it.key(); QString binaryName = library.split("\\").last(); library.replace("dll", "map"); library.replace("exe", "map"); QFile file(library); if(!file.exists()) { QString str; buffer += str.sprintf("%p", entry.offset) + ": (" + binaryName + ") " + entry.name + "\n"; return; } file.open(QIODevice::ReadOnly); DWORD preferredAddress = 0x10000000; QString name; DWORD offset = 0; while(!file.readLine().contains("Rva+Base") && !file.atEnd()); file.readLine(); while(!file.atEnd()) { QString line = file.readLine(); QStringList list = line.split(" ",QString::SkipEmptyParts); if(list.size() > 3) { DWORD addr = list[2].toInt(NULL, 16); DWORD actualAddress = preferredAddress + entry.offset - libAddr; if(actualAddress < addr) { break; } name = list[1]; offset = actualAddress - addr; } } if(file.atEnd()) { name = "Some static function"; } file.close(); QString str; buffer += str.sprintf("%p", entry.offset) + ": (" + binaryName + ") " + name.replace("@", ":") + " + " + str.sprintf("%p", offset) + "\n"; } void StackWalker::OnDbgHelpErr(LPCSTR szFuncName, DWORD gle, DWORD64 addr) { //CHAR buffer[STACKWALK_MAX_NAMELEN]; //_snprintf_s(buffer, STACKWALK_MAX_NAMELEN, "ERROR: %s, GetLastError: %d (Address: %p)\n", szFuncName, gle, (LPVOID) addr); //OnOutput("--"); } void StackWalker::OnSymInit(LPCSTR szSearchPath, DWORD symOptions, LPCSTR szUserName) { CHAR buffer[STACKWALK_MAX_NAMELEN]; _snprintf_s(buffer, STACKWALK_MAX_NAMELEN, "SymInit: Symbol-SearchPath: '%s', symOptions: %d, UserName: '%s'\n", szSearchPath, symOptions, szUserName); // Also display the OS-version OSVERSIONINFOEXA ver; ZeroMemory(&ver, sizeof(OSVERSIONINFOEXA)); ver.dwOSVersionInfoSize = sizeof(ver); if (GetVersionExA( (OSVERSIONINFOA*) &ver) != FALSE) { _snprintf_s(buffer, STACKWALK_MAX_NAMELEN, "OS-Version: %d.%d.%d (%s) 0x%x-0x%x\n", ver.dwMajorVersion, ver.dwMinorVersion, ver.dwBuildNumber, ver.szCSDVersion, ver.wSuiteMask, ver.wProductType); OnOutput(buffer); } } void StackWalker::OnOutput(LPCSTR _buffer) { buffer.append(_buffer); } } #endif #endif ugene-1.9.8/src/corelibs/U2Private/src/CrashHandler.cpp0000644000175000017500000002611111651544333021363 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #if defined(USE_CRASHHANDLER) #include "CrashHandler.h" #include "TaskSchedulerImpl.h" #include #include namespace U2 { #if defined( Q_OS_WIN ) #include #include PVOID CrashHandler::handler = NULL; PVOID CrashHandler::handler2 = NULL; StackWalker CrashHandler::st; addExceptionHandler CrashHandler::addHandlerFunc = NULL; removeExceptionHandler CrashHandler::removeHandlerFunc = NULL; LONG CrashHandler::CrashHandlerFuncThird(PEXCEPTION_POINTERS pExceptionInfo ) { exit(1); } LONG CrashHandler::CrashHandlerFuncSecond(PEXCEPTION_POINTERS pExceptionInfo ) { if(removeHandlerFunc != NULL) { removeHandlerFunc(handler2); } if(addHandlerFunc != NULL) { addHandlerFunc(1, CrashHandlerFuncThird); } QString path = QCoreApplication::applicationDirPath() + "/ugenem.exe"; static QMutex mutex; QMutexLocker lock(&mutex); QProcess::startDetached(path, QStringList()); exit(1); } LONG CrashHandler::CrashHandlerFunc(PEXCEPTION_POINTERS pExceptionInfo ) { QString error; switch(pExceptionInfo->ExceptionRecord->ExceptionCode) { case EXCEPTION_ACCESS_VIOLATION: error = "Access violation"; break; case EXCEPTION_DATATYPE_MISALIGNMENT: error = "Data type misalignment"; break; case EXCEPTION_BREAKPOINT: error = "Break point"; break; case EXCEPTION_SINGLE_STEP: error = "Single step"; break; case EXCEPTION_ARRAY_BOUNDS_EXCEEDED: error = "Array bounds exceeded"; break; case EXCEPTION_FLT_DENORMAL_OPERAND: error = "Float denormal operand"; break; case EXCEPTION_FLT_DIVIDE_BY_ZERO: error = "Float divide by zero"; break; case EXCEPTION_FLT_INEXACT_RESULT: error = "Float inexact result"; break; case EXCEPTION_FLT_INVALID_OPERATION: error = "Float invalid operation"; break; case EXCEPTION_FLT_OVERFLOW: error = "Float overflow"; break; case EXCEPTION_FLT_STACK_CHECK: error = "Float check stack"; break; case EXCEPTION_FLT_UNDERFLOW: error = "Float underflow"; break; case EXCEPTION_INT_DIVIDE_BY_ZERO: error = "Int divide by zero"; break; case EXCEPTION_INT_OVERFLOW: error = "Int overflow"; break; case EXCEPTION_PRIV_INSTRUCTION: error = "Privileged instruction"; break; case EXCEPTION_IN_PAGE_ERROR: error = "In page error"; break; case EXCEPTION_ILLEGAL_INSTRUCTION: error = "Illegal instruction"; break; case EXCEPTION_NONCONTINUABLE_EXCEPTION: error = "Noncontinuable exception"; break; case EXCEPTION_STACK_OVERFLOW: break; case EXCEPTION_INVALID_DISPOSITION: error = "Invalid disposition"; break; case EXCEPTION_GUARD_PAGE: error = "Guard page violation"; break; case EXCEPTION_INVALID_HANDLE: error = "Invalid handle"; break; /*case EXCEPTION_POSSIBLE_DEADLOCK: error = "Possible deadlock"; break;*/ case CONTROL_C_EXIT: error = "Control C exit"; break; default: /*error = "Unknown exception";*/ return EXCEPTION_EXECUTE_HANDLER; } if(removeHandlerFunc != NULL) { removeHandlerFunc(handler); } //RemoveVectoredExceptionHandler(handler); //handler2 = AddVectoredExceptionHandler(1, CrashHandlerFuncSecond); if(pExceptionInfo->ExceptionRecord->ExceptionCode == EXCEPTION_STACK_OVERFLOW) { #if defined(Q_OS_WIN32) _asm add esp, 10240; //roll back stack and current frame pointer #endif /*WORD *sp = (WORD*)_AddressOfReturnAddress(); WORD newSp = *sp + 10240; __movsw(sp, &newSp, 1);*/ QString anotherError = QString::number(EXCEPTION_STACK_OVERFLOW, 16) + "|Stack overflow"; //previous error was dropped in the stack unwinding st.ShowCallstack(GetCurrentThread(), pExceptionInfo->ContextRecord); runMonitorProcess(anotherError); } st.ShowCallstack(GetCurrentThread(), pExceptionInfo->ContextRecord); runMonitorProcess(QString::number(pExceptionInfo->ExceptionRecord->ExceptionCode, 16) + "|" + error + "::" + QString::number((int)pExceptionInfo->ExceptionRecord->ExceptionAddress, 16)); return EXCEPTION_EXECUTE_HANDLER; } #else struct sigaction CrashHandler::sa; void CrashHandler::signalHandler(int signo, siginfo_t*, void*) { sigprocmask(SIG_UNBLOCK, &sa.sa_mask, NULL); QString exception; switch(signo) { case SIGBUS: exception = "Access to undefined portion of memory object"; break; case SIGFPE: exception = "Erroneous arithmetic operation"; break; case SIGILL: exception = "Illegal instruction"; break; case SIGSEGV: exception = "Segmentation fault"; break; case SIGSYS: exception = "Bad syscall"; break; case SIGXCPU: exception = "CPU time limit exceeded"; break; case SIGXFSZ: exception = "File size limit exceeded"; break; case SIGABRT: exception = "Program has been aborted"; break; default: return; } runMonitorProcess(QString::number(signo) + "|" + exception); } #endif char *CrashHandler::buffer = NULL; void CrashHandler::allocateReserve() { buffer = new char[1024*1024]; } void CrashHandler::releaseReserve() { delete []buffer; } void CrashHandler::setupHandler() { #if defined( Q_OS_WIN ) addHandlerFunc = NULL; removeHandlerFunc = NULL; HMODULE h = LoadLibrary(TEXT("kernel32.dll")); if(h != NULL) { FARPROC func = GetProcAddress(h, "AddVectoredExceptionHandler"); if(func != NULL) { addHandlerFunc = (addExceptionHandler)func; } func = GetProcAddress(h, "RemoveVectoredExceptionHandler"); if(func != NULL) { removeHandlerFunc = (removeExceptionHandler)func; } } if(addHandlerFunc != NULL) { addHandlerFunc(1, CrashHandlerFunc); } //handler = AddVectoredExceptionHandler(1, CrashHandlerFunc); #elif defined( Q_OS_MAC) return; //TODO: implement crash hander for MAC OS #else stack_t sigstk; sigstk.ss_sp = malloc(SIGSTKSZ); sigstk.ss_size = SIGSTKSZ; sigstk.ss_flags = 0; if (sigaltstack(&sigstk,0) < 0) { perror("sigaltstack"); } //struct sigaction sa; memset(&sa, 0, sizeof(sa)); sigemptyset(&sa.sa_mask); int kExceptionSignals[9] = {SIGBUS, SIGFPE, SIGILL, SIGSEGV, SIGSYS, SIGXCPU, SIGXFSZ, SIGABRT, -1}; for (unsigned i = 0; kExceptionSignals[i] != -1; ++i) { sigaddset(&sa.sa_mask, kExceptionSignals[i]); } sa.sa_sigaction = signalHandler; sa.sa_flags = SA_ONSTACK | SA_SIGINFO; for (unsigned i = 0; kExceptionSignals[i] != -1; ++i) { sigaction(kExceptionSignals[i], &sa, NULL); } #endif } void CrashHandler::runMonitorProcess(const QString &exceptionType) { QString path = QCoreApplication::applicationDirPath() + "/ugenem"; #ifndef Q_OS_WIN char pid_buf[30]; sprintf(pid_buf, "%d", getpid()); char name_buf[512]; name_buf[readlink(path.toAscii().data(), name_buf, 511)]=0; FILE *fp; fp = freopen ("/tmp/UGENEstacktrace.txt","w+",stdout); void * stackTrace[1024]; int frames = backtrace(stackTrace, 1024); backtrace_symbols_fd(stackTrace, frames, STDOUT_FILENO); fclose(fp); #endif QString message = exceptionType + "|"; message += Version::ugeneVersion().text; message += "|"; QString activeWindow = AppContext::getActiveWindowName(); if(activeWindow.isEmpty()) { message += "None|"; } else { message += activeWindow + "|"; } TaskScheduler *ts = AppContext::getTaskScheduler(); if (ts) { QList ms = ts->getMessages(); QString taskLog; QList::iterator it; int i; for(i = 0, it = --ms.end(); i <= 70 && it!= ms.begin(); i++, it--) { LogMessage* msg = *it; taskLog.prepend("[" + GTimer::createDateTime(msg->time).toString("hh:mm:ss.zzz") + "] " + "[" + msg->categories.first() + "] " + msg->text + "\n"); } taskLog += "|"; message += taskLog; QString taskList; QList topTasks = AppContext::getTaskScheduler()->getTopLevelTasks(); foreach(Task *t, topTasks) { if(t->getState() != Task::State_Finished) { QString state; if(t->getState() == Task::State_Running) { state = "(Running)"; } else if(t->getState() == Task::State_New) { state = "(New)"; } else if(t->getState() == Task::State_Prepared) { state = "(Preparing)"; } QString progress = QString::number(t->getStateInfo().progress); taskList.append(t->getTaskName() + "\t" + state + "\t" + progress + "\n"); foreach(Task *tt, t->getSubtasks()) { getSubTasks(tt, taskList, 1); } } } message += taskList; if(taskList.isEmpty()) { message += "None"; } } else { message += "None|None"; } #if defined (Q_OS_WIN) message += "|" + st.getBuffer(); #else message += "|None"; #endif static QMutex mutex; QMutexLocker lock(&mutex); QProcess::startDetached(path, QStringList() << message.toUtf8().toBase64()); exit(1); } void CrashHandler::getSubTasks(Task *t, QString& list, int lvl) { if(t->getState() != Task::State_Finished) { QString prefix; QString state; prefix.fill('-', lvl); if(t->getState() == Task::State_Running) { state = "(Running)"; } else if(t->getState() == Task::State_New) { state = "(New)"; } else if(t->getState() == Task::State_Prepared) { state = "(Preparing)"; } QString progress = QString::number(t->getStateInfo().progress); list.append(prefix + t->getTaskName() + "\t" + state + "\t" + progress + "\n"); foreach(Task *tt, t->getSubtasks()) { getSubTasks(tt, list, lvl + 1); } } } } #endif ugene-1.9.8/src/corelibs/U2Private/src/StackWalker.h0000644000175000017500000001446511651544333020716 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ /********************************************************************** * LICENSE (http://www.opensource.org/licenses/bsd-license.php) * * Copyright (c) 2005-2011, Jochen Kalmbach * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Jochen Kalmbach nor the names of its contributors may be * used to endorse or promote products derived from this software without * specific prior written permission. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * **********************************************************************/ #ifndef _STACK_WALKER_H_ #define _STACK_WALKER_H_ #include #if defined(USE_CRASHHANDLER) #if defined (Q_OS_WIN) #include #include #include #include namespace U2 { class StackWalkerInternal; // forward class StackWalker { public: enum StackWalkOptions { // No addition info will be retrived // (only the address is available) RetrieveNone = 0, // Try to get the symbol-name RetrieveSymbol = 1, // Try to get the line for this symbol RetrieveLine = 2, // Try to retrieve the module-infos RetrieveModuleInfo = 4, // Also retrieve the version for the DLL/EXE RetrieveFileVersion = 8, // Contains all the above RetrieveVerbose = 0xF, // Generate a "good" symbol-search-path SymBuildPath = 0x10, // Also use the public Microsoft-Symbol-Server SymUseSymSrv = 0x20, // Contains all the above "Sym"-options SymAll = 0x30, // Contains all options (default) OptionsAll = 0x3F }; StackWalker( int options = OptionsAll, // 'int' is by design, to combine the enum-flags LPCSTR szSymPath = NULL, DWORD dwProcessId = GetCurrentProcessId(), HANDLE hProcess = GetCurrentProcess() ); StackWalker(DWORD dwProcessId, HANDLE hProcess); virtual ~StackWalker(); typedef bool (__stdcall *PReadProcessMemoryRoutine)( HANDLE hProcess, DWORD64 qwBaseAddress, PVOID lpBuffer, DWORD nSize, LPDWORD lpNumberOfBytesRead, LPVOID pUserData // optional data, which was passed in "ShowCallstack" ); BOOL LoadModules(); bool ShowCallstack( HANDLE hThread = GetCurrentThread(), const CONTEXT *context = NULL, PReadProcessMemoryRoutine readMemoryFunction = NULL, LPVOID pUserData = NULL // optional to identify some data in the 'readMemoryFunction'-callback ); QString getBuffer() const {return buffer;} protected: enum { STACKWALK_MAX_NAMELEN = 1024 }; // max name length for found symbols protected: // Entry for each Callstack-Entry typedef struct CallstackEntry { DWORD64 offset; // if 0, we have no valid entry CHAR name[STACKWALK_MAX_NAMELEN]; CHAR undName[STACKWALK_MAX_NAMELEN]; CHAR undFullName[STACKWALK_MAX_NAMELEN]; DWORD64 offsetFromSmybol; DWORD offsetFromLine; DWORD lineNumber; CHAR lineFileName[STACKWALK_MAX_NAMELEN]; DWORD symType; LPCSTR symTypeString; CHAR moduleName[STACKWALK_MAX_NAMELEN]; DWORD64 baseOfImage; CHAR loadedImageName[STACKWALK_MAX_NAMELEN]; } CallstackEntry; typedef enum CallstackEntryType {firstEntry, nextEntry, lastEntry}; virtual void OnSymInit(LPCSTR szSearchPath, DWORD symOptions, LPCSTR szUserName); virtual void OnLoadModule(LPCSTR img, LPCSTR mod, DWORD64 baseAddr, DWORD size, DWORD result, LPCSTR symType, LPCSTR pdbName, ULONGLONG fileVersion); virtual void OnCallstackEntry(CallstackEntryType eType, CallstackEntry &entry); virtual void OnDbgHelpErr(LPCSTR szFuncName, DWORD gle, DWORD64 addr); virtual void OnOutput(LPCSTR szText); StackWalkerInternal *m_sw; HANDLE m_hProcess; DWORD m_dwProcessId; BOOL m_modulesLoaded; LPSTR m_szSymPath; int m_options; static BOOL __stdcall myReadProcMem(HANDLE hProcess, DWORD64 qwBaseAddress, PVOID lpBuffer, DWORD nSize, LPDWORD lpNumberOfBytesRead); QString buffer; QMap libraries; friend StackWalkerInternal; QString stackTrace; }; } #endif #endif #endif ugene-1.9.8/src/corelibs/U2Private/src/ServiceRegistryImpl.cpp0000644000175000017500000002520311651544333023001 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "ServiceRegistryImpl.h" #include #include #include #include namespace U2 { /* TRANSLATOR U2::ServiceRegistryImpl */ ServiceRegistryImpl::~ServiceRegistryImpl() { foreach(Service* s, services) { assert(s->isDisabled()); delete s; } assert(activeServiceTasks.isEmpty()); } QList ServiceRegistryImpl::findServices(ServiceType t ) const { QList res; foreach(Service* s, services) { if (s->getType() == t) { res.append(s); } } return res; } /// Returns 'true' if a service with the specified ServiceType is registered and enabled Task* ServiceRegistryImpl::registerServiceTask(Service* s) { return new RegisterServiceTask(this, s); } Task* ServiceRegistryImpl::unregisterServiceTask(Service* s) { return new UnregisterServiceTask(this, s); } Task* ServiceRegistryImpl::enableServiceTask(Service* s) { return new EnableServiceTask(this, s); } Task* ServiceRegistryImpl::disableServiceTask(Service* s) { return new DisableServiceTask(this, s, true); } void ServiceRegistryImpl::setServiceState(Service* s, ServiceState state) { if (s->getState() == state) { return; } _setServiceState(s, state); initiateServicesCheckTask(); } void ServiceRegistryImpl::initiateServicesCheckTask() { if (!timerIsActive) { timerIsActive = true; startTimer(100); } } void ServiceRegistryImpl::timerEvent(QTimerEvent *event) { if (!activeServiceTasks.empty()) { return; //wait until no active service tasks left } killTimer(event->timerId()); timerIsActive = false; Service* s = findServiceReadyToEnable(); if (s!=NULL) { AppContext::getTaskScheduler()->registerTopLevelTask(new EnableServiceTask(this, s)); } } Service* ServiceRegistryImpl::findServiceReadyToEnable() const { //TODO: recheck circular tasks too // look for new + parent_disabled services and check if a service can be run foreach(Service* s, services) { if (s->getState() == ServiceState_Disabled_New || s->getState() == ServiceState_Disabled_ParentDisabled) { bool allParentsEnabled = true; QList parentTypes = s->getParentServiceTypes(); foreach(ServiceType t, parentTypes) { QList parentServices = findServices(t); bool parentIsEnabled = false; foreach(Service* ps, parentServices) { if (ps->isEnabled()) { parentIsEnabled = true; break; } } if (!parentIsEnabled) { allParentsEnabled = false; break; } } if (allParentsEnabled) { return s; } } } return NULL; } ////////////////////////////////////////////////////////////////////////// // Tasks /// RegisterServiceTask RegisterServiceTask::RegisterServiceTask(ServiceRegistryImpl* _sr, Service* _s) : Task(tr("Register '%1' service").arg(_s->getName()), TaskFlag_NoRun), sr(_sr), s(_s) { assert(s->getState() == ServiceState_Disabled_New); assert(!sr->services.contains(s)); } void RegisterServiceTask::prepare() { if (sr->services.contains(s)) { stateInfo.setError( tr("Service is already registered '%1'").arg(s->getName()) ); return; } if (s->getState() != ServiceState_Disabled_New) { stateInfo.setError( tr("Illegal service state: %1").arg(s->getName()) ); return; } foreach(Service* rs, sr->services) { if (rs->getType() == s->getType() && (s->getFlags().testFlag(ServiceFlag_Singleton) || s->getFlags().testFlag(ServiceFlag_Singleton))) { stateInfo.setError(tr("Only one service of specified type is allowed: %1").arg(s->getType())); return; } } sr->services.append(s); emit sr->si_serviceRegistered(s); addSubTask(new EnableServiceTask(sr, s)); } ///EnableServiceTask EnableServiceTask::EnableServiceTask(ServiceRegistryImpl* _sr, Service* _s) : Task(tr("Enable '%1' service").arg(_s->getName()), TaskFlag_NoRun), sr(_sr), s(_s) { assert(s->isDisabled()); } static bool findCircular(ServiceRegistryImpl* sr, Service* s, int currentDepth =0); static bool checkAllParentsEnabled(ServiceRegistryImpl* sr, Service* s); void EnableServiceTask::prepare() { //TODO: improve messaging. The service name is already mentined in task name! sr->activeServiceTasks.push_back(this); if (s->isEnabled()) { stateInfo.setError(tr("Service is already enabled: %1").arg(s->getName())); return; } bool circular = findCircular(sr, s); if (circular) { sr->setServiceState(s, ServiceState_Disabled_CircularDependency); stateInfo.setError(tr("Circullar service dependency: %1").arg(s->getName())); return; } bool noparent = !checkAllParentsEnabled(sr, s); if (noparent) { sr->setServiceState(s, ServiceState_Disabled_ParentDisabled); stateInfo.setError(tr("Required service is not enabled: %1").arg(s->getName())); return; } Task* t = sr->createServiceEnablingTask(s); if (t != NULL) { addSubTask(t); } sr->initiateServicesCheckTask(); } Task::ReportResult EnableServiceTask::report() { sr->activeServiceTasks.removeAll(this); if (stateInfo.hasError() || s->isEnabled()) { return ReportResult_Finished; } bool success = !propagateSubtaskError(); sr->setServiceState(s, success ? ServiceState_Enabled : ServiceState_Disabled_FailedToStart); return ReportResult_Finished; } static bool findCircular(ServiceRegistryImpl* sr, Service* s, int currentDepth) { currentDepth++; if (currentDepth > sr->getServices().size()) { return true; } foreach(ServiceType st, s->getParentServiceTypes()) { QList parents = sr->findServices(st); foreach(Service* p, parents) { bool circular = findCircular(sr, p, currentDepth); if (circular) { return true; } } } return false; } static bool checkAllParentsEnabled(ServiceRegistryImpl* sr, Service* s) { foreach(ServiceType st, s->getParentServiceTypes()) { QList parents = sr->findServices(st); if (parents.isEmpty()) { return false; } foreach(Service* p, parents) { if (p->isDisabled()) { return false; } } } return true; } /// UnregisterServiceTask UnregisterServiceTask::UnregisterServiceTask(ServiceRegistryImpl* _sr, Service* _s) : Task(tr("Unregister '%1' service").arg(_s->getName()), TaskFlag_NoRun), sr(_sr), s(_s) { assert(sr->services.contains(s)); } void UnregisterServiceTask::prepare() { if (!sr->services.contains(s)) { stateInfo.setError( tr("Service is not registered: %1").arg(s->getName()) ); return; } if (s->isEnabled()) { addSubTask(new DisableServiceTask(sr, s, false)); } } Task::ReportResult UnregisterServiceTask::report() { if (stateInfo.hasError()) { return ReportResult_Finished; } if (s->isDisabled()) { assert(sr->services.count(s) == 1); sr->services.removeAll(s); emit sr->si_serviceUnregistered(s); delete s;//TODO: redesign real-time service registration/unregistration-> synchronize with plugin list } return ReportResult_Finished; } /// DisableServiceTask DisableServiceTask::DisableServiceTask(ServiceRegistryImpl* _sr, Service* _s, bool _manual) : Task(tr("Disable '%1' service").arg(_s->getName()), TaskFlags_NR_FOSCOE), sr(_sr), s(_s), manual(_manual) { assert(sr->services.contains(s) && s->isEnabled()); } static QList getDirectChilds(ServiceRegistryImpl* sr, ServiceType st); void DisableServiceTask::prepare() { sr->activeServiceTasks.push_back(this); const QList& activeTopTasks = AppContext::getTaskScheduler()->getTopLevelTasks(); int nTopLevelTasks = activeTopTasks.count(); if (nTopLevelTasks > 1) { foreach(Task* t, activeTopTasks) { coreLog.details(tr("Active top-level task name: %1").arg(t->getTaskName())); } stateInfo.setError( tr("Active task was found") ); return; } if (!sr->services.contains(s)) { stateInfo.setError( tr("Service is not registered: %1").arg(s->getName()) ); return; } if (!s->isEnabled()) { stateInfo.setError( tr("Service is not enabled: %1").arg(s->getName()) ); return; } bool stopChilds = sr->findServices(s->getType()).size() == 1; if (stopChilds) { QList childsToDisable = getDirectChilds(sr, s->getType()); foreach(Service* c, childsToDisable) { if (c->isEnabled()) { addSubTask(new DisableServiceTask(sr, c, false)); } } } Task* disablingTask = sr->createServiceDisablingTask(s); if (disablingTask!=NULL) { addSubTask(disablingTask); } } Task::ReportResult DisableServiceTask::report() { sr->activeServiceTasks.removeAll(this); if (stateInfo.hasError() || s->isDisabled()) { return ReportResult_Finished; } if (propagateSubtaskError()) { return ReportResult_Finished; } ServiceState newState = manual ? ServiceState_Disabled_Manually : ServiceState_Disabled_ParentDisabled; sr->setServiceState(s, newState); return ReportResult_Finished; } static QList getDirectChilds(ServiceRegistryImpl* sr, ServiceType st) { QList res; foreach(Service* s, sr->getServices()) { if (s->getParentServiceTypes().contains(st)) { res.append(s); } } return res; } }//namespace ugene-1.9.8/src/corelibs/U2Private/src/AppSettingsImpl.cpp0000644000175000017500000000254611651544333022116 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "AppSettingsImpl.h" #include #include #include #include namespace U2 { AppSettingsImpl::AppSettingsImpl() { nc = new NetworkConfiguration(); ri = new AppResourcePool(); userAppsSettings = new UserAppsSettings(); trs = new TestRunnerSettings(); } AppSettingsImpl::~AppSettingsImpl() { delete nc; delete ri; delete userAppsSettings; delete trs; } }//namespace ugene-1.9.8/src/corelibs/U2Private/src/LogSettings.h0000644000175000017500000000516011651544333020735 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_LOG_SETTINGS_H_ #define _U2_LOG_SETTINGS_H_ #include "private.h" #include #include #include namespace U2 { struct U2PRIVATE_EXPORT LoggerSettings { LoggerSettings() { qFill(activeLevelFlag, activeLevelFlag + LogLevel_NumLevels, 0); } bool operator==(const LoggerSettings& other) const { return categoryName == other.categoryName && activeLevelFlag == other.activeLevelFlag; } QString categoryName; bool activeLevelFlag[LogLevel_NumLevels]; }; class U2PRIVATE_EXPORT LogCategories : QObject { Q_OBJECT public: static void init(); static const QString getLocalizedLevelName(LogLevel l) { return localizedLevelNames[l]; } protected: static QString localizedLevelNames[LogLevel_NumLevels]; }; class U2PRIVATE_EXPORT LogSettings { public: LogSettings(); void removeCategory(const QString& name); void addCategory(const LoggerSettings& newcs); const LoggerSettings& getLoggerSettings(const QString& cName); const QHash getLoggerSettings() const {return categories;} bool operator==(const LogSettings& other) const; void save(); void reinitAll(); void reinitCategories(); QString levelColors[LogLevel_NumLevels]; bool activeLevelGlobalFlag[LogLevel_NumLevels]; QString logPattern; bool showDate; bool showLevel; bool showCategory; bool enableColor; //private: QHash categories; }; class U2PRIVATE_EXPORT LogSettingsHolder { public: const LogSettings& getSettings() const {return settings;} virtual void setSettings(const LogSettings& s); protected: mutable LogSettings settings; }; } //namespace #endif ugene-1.9.8/src/corelibs/U2Private/src/IOAdapterRegistryImpl.cpp0000644000175000017500000000362511651544333023215 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "IOAdapterRegistryImpl.h" #include #include #include namespace U2 { bool IOAdapterRegistryImpl::registerIOAdapter(IOAdapterFactory* io) { if (getIOAdapterFactoryById(io->getAdapterId())!=NULL) { return false; } adapters.push_back(io); return true; } bool IOAdapterRegistryImpl::unregisterIOAdapter(IOAdapterFactory* io) { int n = adapters.removeAll(io); return n > 0; } IOAdapterFactory* IOAdapterRegistryImpl::getIOAdapterFactoryById(IOAdapterId id) const { foreach (IOAdapterFactory* io, adapters) { if (io->getAdapterId() == id) { return io; } } return NULL; } void IOAdapterRegistryImpl::init() { registerIOAdapter(new LocalFileAdapterFactory(this)); registerIOAdapter(new GzippedLocalFileAdapterFactory(this)); registerIOAdapter( new HttpFileAdapterFactory(this) ); registerIOAdapter( new GzippedHttpFileAdapterFactory(this) ); registerIOAdapter( new VFSAdapterFactory(this) ); } }//namespace ugene-1.9.8/src/corelibs/U2Private/src/PluginDescriptor.cpp0000644000175000017500000002663611651544333022336 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "PluginDescriptor.h" #include #include #include namespace U2 { static PlatformName platformFromText(const QString& text) { QString trimmed = text.trimmed(); if (trimmed == "win") { return PlatformName_Win; } if (trimmed == "unix") { return PlatformName_UnixNotMac; } if (trimmed == "macx") { return PlatformName_Mac; } return PlatformName_Unknown; } static PlatformArch archFromText(const QString& text) { QString trimmed = text.trimmed(); if (trimmed == "32") { return PlatformArch_32; } if (trimmed == "64") { return PlatformArch_64; } return PlatformArch_Unknown; } static PluginMode modeFromText(const QString& text) { QString trimmed = text.trimmed().toLower(); QStringList tokens = trimmed.split(QRegExp("[\\s,]"), QString::SkipEmptyParts); PluginMode result; if (tokens.isEmpty()) { result|=PluginMode_Malformed; return result; } foreach(const QString& token, tokens) { if (token == "ui") { result|=PluginMode_UI; } else if (token == "console") { result|=PluginMode_Console; } else { result|=PluginMode_Malformed; return result; } } return result; } PluginDesc PluginDescriptorHelper::readPluginDescriptor(const QString& descUrl, QString& error) { PluginDesc result; PluginDesc failResult; //empty one, used if parsing is failed QFile f(descUrl); if (!f.open(QIODevice::ReadOnly)) { error = L10N::errorOpeningFileRead(descUrl); return failResult; } result.descriptorUrl = descUrl; QByteArray xmlData = f.readAll(); f.close(); QDomDocument doc; bool res = doc.setContent(xmlData); if (!res) { error = L10N::notValidFileFormat("XML", descUrl); return failResult; } QDomElement pluginElement = doc.documentElement(); QString pluginElementName = pluginElement.tagName(); if (pluginElementName != "ugene-plugin") { error = L10N::notValidFileFormat("UGENE plugin", descUrl); return failResult; } result.id = pluginElement.attribute("id"); if (result.id.isEmpty()) { error = tr("Required attribute not found %1").arg("id"); return failResult; } result.pluginVersion = Version::parseVersion(pluginElement.attribute("version")); if (result.pluginVersion.text.isEmpty()) { error = tr("Required attribute not found %1").arg("version"); return failResult; } result.ugeneVersion= Version::parseVersion(pluginElement.attribute("ugene-version")); if (result.ugeneVersion.text.isEmpty()) { error = tr("Required attribute not found %1").arg("ugene-version"); return failResult; } result.qtVersion = Version::parseVersion(pluginElement.attribute("qt-version")); if (result.qtVersion.text.isEmpty()) { error = tr("Required attribute not found %1").arg("qt-version"); return failResult; } QDomElement libraryElement = pluginElement.firstChildElement("library"); QString libraryUrlText = libraryElement.text(); if (!libraryUrlText.isEmpty() && QFileInfo(libraryUrlText).isRelative()) { //if path is relative, use descriptor dir as 'current folder' libraryUrlText = QFileInfo(descUrl).absoluteDir().canonicalPath() + "/" + libraryUrlText; } result.libraryUrl = libraryUrlText; if (result.libraryUrl.isEmpty()) { error = tr("Required element not found %1").arg("library"); return failResult; } result.name = pluginElement.firstChildElement("name").text(); if (result.name.isNull()) { error = tr("Required element not found %1").arg("name"); return failResult; } result.pluginVendor= pluginElement.firstChildElement("plugin-vendor").text(); if (result.pluginVendor.isNull()) { error = tr("Required element not found %1").arg("plugin-vendor"); return failResult; } QString pluginModeText = pluginElement.firstChildElement("plugin-mode").text(); result.mode = modeFromText(pluginModeText); if (result.mode.testFlag(PluginMode_Malformed)) { error = tr("Not valid value: '%1', plugin: %2").arg(pluginModeText).arg("plugin-mode"); return failResult; } QDomElement platformElement = pluginElement.firstChildElement("platform"); QString platformNameText = platformElement.attribute("name"); result.platform.name= platformFromText(platformNameText); if (result.platform.name == PlatformName_Unknown) { error = tr("Platform arch is unknown: %1").arg(platformNameText); return failResult; } QString platformArchText= platformElement.attribute("arch"); result.platform.arch = archFromText(platformArchText); if (result.platform.arch == PlatformArch_Unknown) { error = tr("Platform bits is unknown: %1").arg(platformArchText); return failResult; } QString debugText = pluginElement.firstChildElement("debug-build").text(); bool debug = debugText == "true" || debugText == "yes" || debugText.toInt() == 1; result.qtVersion.debug = result.ugeneVersion.debug = result.pluginVersion.debug = debug; QDomNodeList dependsElements = pluginElement.elementsByTagName("depends"); for(int i = 0; i < dependsElements.size(); i++) { QDomNode dn = dependsElements.item(i); if (!dn.isElement()) { continue; } QString dependsText = dn.toElement().text(); QStringList dependsTokes = dependsText.split(QChar(';'), QString::SkipEmptyParts); foreach (const QString& token, dependsTokes) { QStringList plugAndVersion = token.split(QChar(','), QString::KeepEmptyParts); if (plugAndVersion.size()!=2) { error = tr("Invalid depends token: %1").arg(token); return failResult; } DependsInfo di; di.id = plugAndVersion.at(0); di.version = Version::parseVersion(plugAndVersion.at(1)); result.dependsList.append(di); } } return result; } bool PluginDesc::operator == (const PluginDesc& pd) const { return id == pd.id && pluginVersion == pd.pluginVersion && ugeneVersion == pd.ugeneVersion && qtVersion == pd.qtVersion && libraryUrl == pd.libraryUrl && platform == pd.platform && mode == pd.mode; } ////////////////////////////////////////////////////////////////////////// // ordering //states set used for DFS graph traversal enum DepNodeState { DS_Clean, DS_InProcess, DS_Done }; class DepNode { public: DepNode() {state = DS_Clean; root = false;} QList parentNodes; //nodes this node depends on QList childNodes; //nodes that depends on this node PluginDesc desc; DepNodeState state; bool root; }; static void resetState(const QList& nodes) { foreach (DepNode* node, nodes) { node->state = DS_Clean; } } static void findParentNodes(DepNode* node, const PluginDesc& desc, QString & err, QList& result) { assert(node->state == DS_Clean); node->state = DS_InProcess; foreach (DepNode* childNode, node->childNodes) { if (childNode->state == DS_Done) { //check if node is already processed continue; } if (childNode->state == DS_InProcess) { // circular dependency between plugins err = PluginDescriptorHelper::tr("Plugin circular dependency detected: %1 <-> %2").arg(desc.id).arg(node->desc.id); return; } findParentNodes(node, desc, err, result); } foreach(const DependsInfo& di, desc.dependsList) { if ( di.id == node->desc.id && di.version <= node->desc.pluginVersion ) { result.append(node); break; } } node->state = DS_Done; } static void orderPostorder(DepNode* node, QList& result) { assert(node->state == DS_Clean); node->state = DS_InProcess; foreach (DepNode* childNode, node->childNodes) { if (childNode->state != DS_Clean) { continue; } orderPostorder(childNode, result); } if (!node->root) { result.append(node->desc); } node->state = DS_Done; } static void orderTopological(DepNode* node, QList& result) { orderPostorder(node, result); QList topologicalResult; QListIterator it(result); it.toBack(); while( it.hasPrevious()) { topologicalResult.append(it.previous()); } result = topologicalResult; } QList PluginDescriptorHelper::orderPlugins(const QList& unordered, QString& err) { // Sort plugin using dependency graph. // Root node has no dependencies. All child nodes depends on all parents. QList result; if (unordered.isEmpty()) { return unordered; } GAutoDeleteList allNodes; DepNode* rootNode = new DepNode(); rootNode->root = true; allNodes.qlist.append(rootNode); bool changed = false; QList queue = unordered; do { PluginDesc desc = queue.takeFirst(); QList nodes; int nDeps = desc.dependsList.size(); if (nDeps == 0) { nodes.append(rootNode); } else { resetState(allNodes.qlist); findParentNodes(rootNode, desc, err, nodes); } if (!err.isEmpty()) { return unordered; } if (nDeps == 0 || nodes.size() == nDeps) { DepNode* descNode = new DepNode(); allNodes.qlist.append(descNode); descNode->desc = desc; // now add this node as a child to all nodes it depends on foreach(DepNode* node, nodes) { node->childNodes.append(descNode); descNode->parentNodes.append(node); } changed = true; continue; } queue.append(desc); } while (changed && !queue.isEmpty()); if (!queue.isEmpty()) { err = tr("Can't satisfy dependencies for %1 !").arg(queue.first().id); return unordered; } //traverse graph and add nodes in topological (reverse postorder) mode resetState(allNodes.qlist); orderTopological(rootNode, result); #ifdef _DEBUG assert(result.size() == unordered.size()); foreach (const PluginDesc& desc, unordered) { int idx = result.indexOf(desc); assert(idx >= 0); } #endif return result; } } //namespace ugene-1.9.8/src/corelibs/U2Private/src/AppSettingsImpl.h0000644000175000017500000000215311651544333021555 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_APPSETTINGS_IMPL_H_ #define _U2_APPSETTINGS_IMPL_H_ #include "private.h" #include namespace U2 { class U2PRIVATE_EXPORT AppSettingsImpl : public AppSettings { public: AppSettingsImpl(); ~AppSettingsImpl(); }; }//namespace #endif ugene-1.9.8/src/corelibs/U2Private/src/PluginSupportImpl.cpp0000644000175000017500000003135011651544333022503 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "PluginSupportImpl.h" #include "ServiceRegistryImpl.h" #include #include #include #include #include #include #include #include #include #include #include namespace U2 { /* TRANSLATOR U2::PluginSupportImpl */ #define PLUGINS_LIST_SETTINGS QString("plugin_support/list/") #define SKIP_LIST_SETTINGS QString("plugin_support/skip_list/") static QStringList findAllPluginsInDefaultPluginsDir(); PluginRef::PluginRef(Plugin* _plugin, QLibrary* _library, const PluginDesc& desc) : plugin(_plugin), library(_library), pluginDesc(desc), removeFlag(false) { } PluginSupportImpl::PluginSupportImpl(): allLoaded(false) { //read plugin names from settings Settings* settings = AppContext::getSettings(); QString pluginListSettingsDir = settings->toVersionKey(PLUGINS_LIST_SETTINGS); QStringList allKeys = settings->getAllKeys(pluginListSettingsDir); QSet pluginFiles; foreach (QString pluginId, allKeys) { QString file = settings->getValue(pluginListSettingsDir + pluginId).toString(); pluginFiles.insert(file); } //read all plugins from the current folder and from ./plugins folder // use SKIP list to learn which plugin should not be loaded QStringList skipFiles = settings->getValue(settings->toVersionKey(SKIP_LIST_SETTINGS), QStringList()).toStringList(); pluginFiles.unite(findAllPluginsInDefaultPluginsDir().toSet()); pluginFiles.subtract(skipFiles.toSet()); Task* loadStartUpPlugins = new LoadAllPluginsTask(this, pluginFiles.toList()); AppContext::getTaskScheduler()->registerTopLevelTask(loadStartUpPlugins); } PluginSupportImpl::~PluginSupportImpl() { foreach(PluginRef* ref, plugRefs) { delete ref; } } bool PluginSupportImpl::isAllPluginsLoaded() const { return allLoaded; } LoadAllPluginsTask::LoadAllPluginsTask(PluginSupportImpl* _ps,const QStringList& _pluginFiles) : Task(tr("Loading start up plugins"), TaskFlag_NoRun), ps(_ps), pluginFiles(_pluginFiles) { coreLog.trace("List of the plugins to be loaded:"); foreach(const QString& path, pluginFiles) { coreLog.trace(path); } coreLog.trace("End of the list"); } void LoadAllPluginsTask::prepare() { foreach (const QString& url, pluginFiles) { addToOrderingQueue(url); } QString err; orderedPlugins = PluginDescriptorHelper::orderPlugins(orderedPlugins, err); if (!err.isEmpty()) { setError(err); return; } foreach(const PluginDesc& desc, orderedPlugins) { addSubTask(new AddPluginTask(ps, desc)); } } void LoadAllPluginsTask::addToOrderingQueue(const QString& url) { QFileInfo descFile(url); if (!descFile.exists()) { coreLog.trace( tr("File not found: %1").arg(url) ); return; } if (!descFile.isFile()) { coreLog.trace( tr("Invalid file format: %1").arg(url) ); return; } QString err; PluginDesc desc = PluginDescriptorHelper::readPluginDescriptor(url, err); if (!desc.isValid()) { assert(!err.isEmpty()); coreLog.trace(err); return; } // now check plugin compatibility bool isUIMode = AppContext::getMainWindow() != NULL; bool modeIsOk = false; if (isUIMode) { modeIsOk = desc.mode.testFlag(PluginMode_UI); } else { modeIsOk = desc.mode.testFlag(PluginMode_Console); } if (!modeIsOk) { coreLog.trace(QString("Plugin is inactive in the current mode: %1, skipping load").arg(desc.id)); return; } // check version Version ugeneVersion = Version::ugeneVersion(); Version qtVersion = Version::qtVersion(); if (ugeneVersion.debug != desc.pluginVersion.debug) { coreLog.trace(QString("Plugin debug/release mode is not matched with UGENE binaries: %1").arg(desc.id)); return; } if (qtVersion < desc.qtVersion) { coreLog.trace(QString("Plugin was built with higher QT version: %1").arg(desc.id)); return; } if (ugeneVersion < desc.ugeneVersion) { coreLog.trace(QString("Plugin was built with higher UGENE version: %1, %2 vs %3").arg(desc.id).arg(desc.ugeneVersion.text).arg(ugeneVersion.text)); return; } //check platform if (desc.platform.arch == PlatformArch_Unknown) { coreLog.trace(QString("Plugin platform arch is unknown: %1").arg(desc.id)); return; } if (desc.platform.arch == PlatformArch_32 && QT_POINTER_SIZE != 4) { coreLog.trace(QString("Plugin was built on 32-bit platform: %1").arg(desc.id)); return; } if (desc.platform.arch == PlatformArch_64 && QT_POINTER_SIZE != 8) { coreLog.trace(QString("Plugin was built on 64-bit platform: %1").arg(desc.id)); return; } if (desc.platform.name == PlatformName_Unknown) { coreLog.trace(QString("Plugin platform name is unknown: %1").arg(desc.id)); return; } #if defined(Q_OS_WIN) if (desc.platform.name != PlatformName_Win) { coreLog.trace(QString("Plugin platform is not Windows: %1").arg(desc.id)); return; } #elif defined(Q_OS_MAC) if (desc.platform.name != PlatformName_Mac) { coreLog.trace(QString("Plugin platform is not Mac: %1").arg(desc.id)); return; } #else if (desc.platform.name != PlatformName_UnixNotMac) { coreLog.trace(QString("Plugin platform is not Unix/Linux: %1").arg(desc.id)); return; } #endif orderedPlugins.append(desc); } Task::ReportResult LoadAllPluginsTask::report() { ps->allLoaded = true; emit ps->si_allStartUpPluginsLoaded(); return ReportResult_Finished; } static QStringList findAllPluginsInDefaultPluginsDir() { QDir d = PluginSupportImpl::getDefaultPluginsDir(); QStringList filter; filter << QString("*.") + PLUGIN_FILE_EXT; QStringList fileNames = d.entryList(filter, QDir::Readable | QDir::Files, QDir::NoSort); QStringList res; foreach(const QString& name, fileNames) { GUrl filePath(d.absolutePath() + "/" + name); QString path = filePath.getURLString(); res.append(path); coreLog.trace(QString("Found plugin candidate in default dir: %1").arg(path)); } return res; } PluginRef::~PluginRef() { assert(plugin!=NULL); delete plugin; plugin = NULL; } void PluginSupportImpl::registerPlugin(PluginRef* ref) { plugRefs.push_back(ref); plugins.push_back(ref->plugin); updateSavedState(ref); emit si_pluginAdded(ref->plugin); ServiceRegistry* sr = AppContext::getServiceRegistry(); foreach(Service* s, ref->plugin->getServices()) { AppContext::getTaskScheduler()->registerTopLevelTask(sr->registerServiceTask(s)); } } QString PluginSupportImpl::getPluginFileURL(Plugin* p) const { assert(plugins.size() == plugRefs.size()); foreach(PluginRef* ref, plugRefs) { if (ref->plugin == p) { if (ref->library == NULL) { return ""; } return ref->library->fileName(); } } return QString::null; } Task* PluginSupportImpl::addPluginTask(const QString& pathToPlugin) { QString err; PluginDesc desc = PluginDescriptorHelper::readPluginDescriptor(pathToPlugin, err); Task* res = new AddPluginTask(this, desc); if (!err.isEmpty()) { res->setError(err); } return res; } PluginRef* PluginSupportImpl::findRef(Plugin* p) const { foreach(PluginRef* r, plugRefs) { if (r->plugin == p) { return r; } } return NULL; } PluginRef* PluginSupportImpl::findRefById(const QString& pluginId) const { foreach(PluginRef* r, plugRefs) { if (r->pluginDesc.id == pluginId) { return r; } } return NULL; } //plugin will not be removed from the plugin list during the next app run void PluginSupportImpl::setRemoveFlag(Plugin* p, bool v) { PluginRef* r = findRef(p); assert(r!=NULL); if (r->removeFlag == v) { return; } r->removeFlag = v; updateSavedState(r); emit si_pluginRemoveFlagChanged(p); } bool PluginSupportImpl::getRemoveFlag(Plugin* p) const { PluginRef* r = findRef(p); return r->removeFlag; } void PluginSupportImpl::updateSavedState(PluginRef* ref) { if (ref->library == NULL) { // skip core plugin return; } Settings* settings = AppContext::getSettings(); QString pluginListSettingsDir = settings->toVersionKey(PLUGINS_LIST_SETTINGS); QString skipListSettingsDir = settings->toVersionKey(SKIP_LIST_SETTINGS); QString descUrl = ref->pluginDesc.descriptorUrl.getURLString(); QString pluginId = ref->pluginDesc.id; if (ref->removeFlag) { settings->remove(pluginListSettingsDir + pluginId); //add to skip-list if auto-loaded if (isDefaultPluginsDir(descUrl)) { QStringList skipFiles = settings->getValue(skipListSettingsDir, QStringList()).toStringList(); if (!skipFiles.contains(descUrl)) { skipFiles.append(descUrl); settings->setValue(skipListSettingsDir, skipFiles); } } } else { settings->setValue(pluginListSettingsDir + pluginId, descUrl); //remove from skip-list if present if (isDefaultPluginsDir(descUrl)) { QStringList skipFiles = settings->getValue(skipListSettingsDir, QStringList()).toStringList(); if (skipFiles.removeOne(descUrl)) { settings->setValue(skipListSettingsDir, skipFiles); } } } } QDir PluginSupportImpl::getDefaultPluginsDir() { return QDir(QCoreApplication::applicationDirPath() + "/plugins"); } bool PluginSupportImpl::isDefaultPluginsDir(const QString& url) { QDir urlAbsDir = QFileInfo(url).absoluteDir(); QDir plugsDir = getDefaultPluginsDir(); return urlAbsDir == plugsDir; } ////////////////////////////////////////////////////////////////////////// /// Tasks //todo: improve task naming AddPluginTask::AddPluginTask(PluginSupportImpl* _ps, const PluginDesc& _desc) : Task(tr("Add plugin task: %1").arg(_desc.id), TaskFlag_NoRun), ps(_ps), desc(_desc) { } Task::ReportResult AddPluginTask::report() { PluginRef* ref = ps->findRefById(desc.id); if (ref != NULL) { stateInfo.setError( tr("Plugin is already loaded: %1").arg(desc.id) ); return ReportResult_Finished; } //check that plugin we depends on is already loaded foreach (const DependsInfo& di, desc.dependsList) { PluginRef* ref = ps->findRefById(desc.id); if (ref == NULL) { stateInfo.setError( tr("Plugin %1 depends on %2 which is not loaded").arg(desc.id).arg(di.id) ); return ReportResult_Finished; } if (ref->pluginDesc.pluginVersion < di.version) { stateInfo.setError( tr("Plugin %1 depends on %2 which is available, but the version is too old").arg(desc.id).arg(di.id) ); return ReportResult_Finished; } } //load library QString libUrl = desc.libraryUrl.getURLString(); std::auto_ptr lib(new QLibrary(libUrl)); bool loadOk = lib->load(); if (!loadOk) { stateInfo.setError( tr("Plugin loading error: %1, Error string %2").arg(libUrl).arg(lib->errorString()) ); return ReportResult_Finished; } //instantiate plugin PLUG_INIT_FUNC init_fn = PLUG_INIT_FUNC((lib->resolve(U2_PLUGIN_INIT_FUNC_NAME))); if (!init_fn) { stateInfo.setError( tr("Plugin initialization routine was not found: %1").arg(libUrl) ); return ReportResult_Finished; } Plugin* p = init_fn(); if (p == NULL) { stateInfo.setError( tr("Plugin initialization failed: %1").arg(libUrl) ); return ReportResult_Finished; } ref = new PluginRef(p, lib.release(), desc); ps->registerPlugin(ref); return ReportResult_Finished; } }//namespace ugene-1.9.8/src/corelibs/U2Private/src/IOAdapterRegistryImpl.h0000644000175000017500000000301611651544333022654 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _IOADAPTER_REGISTRY_IMPL_H_ #define _IOADAPTER_REGISTRY_IMPL_H_ #include "private.h" #include namespace U2 { class U2PRIVATE_EXPORT IOAdapterRegistryImpl : public IOAdapterRegistry { public: IOAdapterRegistryImpl(QObject* p = NULL) : IOAdapterRegistry(p) {init();} virtual bool registerIOAdapter(IOAdapterFactory* io) ; virtual bool unregisterIOAdapter(IOAdapterFactory* io); virtual const QList& getRegisteredIOAdapters() const {return adapters;} virtual IOAdapterFactory* getIOAdapterFactoryById(IOAdapterId id) const; private: void init(); QList adapters; }; }//namespace #endif ugene-1.9.8/src/corelibs/U2Private/src/AppContextImpl.h0000644000175000017500000003760711651544333021415 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_APPCONTEXT_IMPL_ #define _U2_APPCONTEXT_IMPL_ #include "private.h" #include namespace U2 { class U2PRIVATE_EXPORT AppContextImpl : public AppContext { Q_OBJECT public: AppContextImpl() { ps = NULL; sr = NULL; pl = NULL; prj = NULL; prs = NULL; mw = NULL; pv = NULL; plv = NULL; ss = NULL; gs = NULL; dfr = NULL; io = NULL; dtr = NULL; dal = NULL; ovfr = NULL; ts = NULL; rt = NULL; dfc = NULL; asr = NULL; as = NULL; tf = NULL; dbxr = NULL; asg = NULL; smr = NULL; swar = NULL; msfr = NULL; swrfr = NULL; mcsr = NULL; secStructPredictRegistry = NULL; cgr = NULL; rdc = NULL; protocolInfoRegistry = NULL; remoteMachineMonitor = NULL; treeGeneratorRegistry = NULL; cmdLineRegistry = NULL; instance = this; msaConsensusAlgoRegistry = NULL; msaDistanceAlgoRegistry = NULL; pwmConversionAlgoRegistry = NULL; dnaAssemblyAlgRegistry = NULL; msaAlignAlgRegistry = NULL; virtualFileSystemRegistry = NULL; dataBaseRegistry = NULL; externalToolRegistry = NULL; aaSupport = NULL; dbiRegistry = NULL; rfr = NULL; qdafr = NULL; cdsfr = NULL; saar = NULL; guiMode = false; activeWindow = ""; tb = NULL; } ~AppContextImpl(); void setPluginSupport(PluginSupport* _ps) {assert(ps == NULL || _ps == NULL); ps = _ps;} void setServiceRegistry(ServiceRegistry* _sr) {assert(sr == NULL || _sr == NULL); sr = _sr;} void setProjectLoader(ProjectLoader* _pl) {assert(pl == NULL || _pl == NULL); pl = _pl;} void setProject(Project* _prj) {assert(prj == NULL || _prj == NULL); prj = _prj;} void setProjectService(ProjectService* _prs) {assert(prs == NULL || _prs == NULL); prs = _prs;} void setMainWindow(MainWindow* _mw) {assert(mw == NULL || _mw == NULL); mw = _mw;} void setProjectView(ProjectView* _pv) {assert(pv == NULL || _pv == NULL); pv = _pv;} void setPluginViewer(PluginViewer* _plv) {assert(plv == NULL || _plv == NULL); plv = _plv;} void setSettings(Settings* _ss) {assert(ss == NULL || _ss == NULL); ss= _ss;} void setGlobalSettings(Settings* _gs) {assert(gs == NULL || _gs == NULL); gs= _gs;} void setAppSettings( AppSettings* _as) { assert( as|| _as); as= _as; } void setAppSettingsGUI( AppSettingsGUI* _asg) { assert( asg == NULL || _asg == NULL ); asg= _asg; } void setDocumentFormatRegistry(DocumentFormatRegistry* _dfr) {assert(dfr == NULL || _dfr == NULL); dfr = _dfr;} void setIOAdapterRegistry(IOAdapterRegistry* _io) {assert(io == NULL || _io == NULL); io = _io;} void setDNATranslationRegistry(DNATranslationRegistry* _dtr) {assert(dtr == NULL || _dtr == NULL);dtr = _dtr;} void setDNAAlphabetRegistry(DNAAlphabetRegistry* _dal) {assert(dal == NULL || _dal == NULL);dal = _dal;} void setObjectViewFactoryRegistry(GObjectViewFactoryRegistry* _ovfr) {assert(ovfr == NULL || _ovfr == NULL); ovfr = _ovfr;} void setTaskScheduler(TaskScheduler* _ts) {assert(ts == NULL || _ts == NULL); ts = _ts;} void setResourceTracker(ResourceTracker* _rt) {assert(rt == NULL || _rt == NULL); rt = _rt;} void setDocumentFormatConfigurators(DocumentFormatConfigurators* _dfc) {assert(dfc == NULL || _dfc == NULL); dfc = _dfc;} void setAnnotationSettingsRegistry(AnnotationSettingsRegistry* _asr) {assert(asr == NULL || _asr == NULL); asr = _asr;} void setTestFramework( TestFramework* _tf) { assert( tf || _tf ); tf = _tf; } void setDBXRefRegistry( DBXRefRegistry* _dbxr) { assert( dbxr == NULL || _dbxr == NULL ); dbxr = _dbxr; } void setSubstMatrixRegistry(SubstMatrixRegistry* _smr) { assert( smr == NULL || _smr == NULL ); smr = _smr; } void setSmithWatermanTaskFactoryRegistry (SmithWatermanTaskFactoryRegistry* _swar) { assert( swar == NULL || _swar == NULL ); swar = _swar; } void setMolecularSurfaceFactoryRegistry (MolecularSurfaceFactoryRegistry* _msfr) { assert( msfr == NULL || _msfr == NULL ); msfr = _msfr; } void setSWResultFilterRegistry (SWResultFilterRegistry* _swrfr) { assert( swrfr == NULL || _swrfr == NULL ); swrfr = _swrfr; } void setMSAColorSchemeRegistry(MSAColorSchemeRegistry* _mcsr) {assert( mcsr == NULL || _mcsr == NULL ); mcsr = _mcsr;} void setSecStructPedictAlgRegistry(SecStructPredictAlgRegistry* _sspar) {assert( secStructPredictRegistry == NULL || _sspar == NULL ); secStructPredictRegistry = _sspar;} void setCudaGpuRegistry( CudaGpuRegistry * _cgr ) { assert( cgr == NULL || _cgr == NULL ); cgr = _cgr; } void setOpenCLGpuRegistry( OpenCLGpuRegistry* _oclgr ) { assert( oclgr == NULL || _oclgr == NULL ); oclgr = _oclgr; } void setRecentlyDownloadedCache( RecentlyDownloadedCache* _rdc) { assert( rdc == NULL || _rdc == NULL ); rdc = _rdc;} void setProtocolInfoRegistry( ProtocolInfoRegistry * pr ) { assert( NULL == protocolInfoRegistry || NULL == pr ); protocolInfoRegistry = pr; } void setRemoteMachineMonitor( RemoteMachineMonitor * rm ) { assert( NULL == remoteMachineMonitor || NULL == rm ); remoteMachineMonitor = rm; } void setPhyTreeGeneratorRegistry(PhyTreeGeneratorRegistry* genRegistry) { assert(NULL == treeGeneratorRegistry || NULL == genRegistry); treeGeneratorRegistry = genRegistry; } void setMSAConsensusAlgorithmRegistry(MSAConsensusAlgorithmRegistry* reg) { assert(reg == NULL || msaConsensusAlgoRegistry == NULL); msaConsensusAlgoRegistry = reg; } void setMSADistanceAlgorithmRegistry(MSADistanceAlgorithmRegistry* reg) { assert(reg == NULL || msaDistanceAlgoRegistry == NULL); msaDistanceAlgoRegistry = reg; } void setPWMConversionAlgorithmRegistry(PWMConversionAlgorithmRegistry* reg) { assert(reg == NULL || pwmConversionAlgoRegistry == NULL); pwmConversionAlgoRegistry = reg; } void setCMDLineRegistry(CMDLineRegistry* r) { assert(cmdLineRegistry == NULL || r == NULL); cmdLineRegistry = r; } void setVirtualFileSystemRegistry( VirtualFileSystemRegistry * r ) { assert( virtualFileSystemRegistry == NULL || r == NULL ); virtualFileSystemRegistry = r; } void setDnaAssemblyAlgRegistry( DnaAssemblyAlgRegistry * r ) { assert( dnaAssemblyAlgRegistry == NULL || r == NULL ); dnaAssemblyAlgRegistry = r; } void setMSAAlignAlgRegistry( MSAAlignAlgRegistry * r ) { assert( msaAlignAlgRegistry == NULL || r == NULL ); msaAlignAlgRegistry = r; } void setDataBaseRegistry( DataBaseRegistry *dbr) { assert (dataBaseRegistry == NULL || dbr == NULL ); dataBaseRegistry = dbr; } void setExternalToolRegistry( ExternalToolRegistry * _etr) { assert( externalToolRegistry == NULL || _etr == NULL ); externalToolRegistry = _etr; } void setRepeatFinderTaskFactoryRegistry (RepeatFinderTaskFactoryRegistry* _rfr) { assert( rfr == NULL || _rfr == NULL ); rfr = _rfr; } void setQDActorFactoryRegistry(QDActorPrototypeRegistry* _queryfactoryRegistry) { assert( qdafr == NULL || _queryfactoryRegistry == NULL ); qdafr = _queryfactoryRegistry; } void setAutoAnnotationsSupport(AutoAnnotationsSupport* _aaSupport) { assert( aaSupport == NULL || _aaSupport == NULL ); aaSupport = _aaSupport; } void setDbiRegistry(U2DbiRegistry *_dbiRegistry) { assert((NULL == dbiRegistry) || (NULL == _dbiRegistry)); dbiRegistry = _dbiRegistry; } void setCDSearchFactoryRegistry(CDSearchFactoryRegistry* _cdsfr) { assert((NULL == cdsfr) || (NULL == _cdsfr)); cdsfr= _cdsfr; } void setStructuralAlignmentAlgorithmRegistry(StructuralAlignmentAlgorithmRegistry *_saar) { assert(saar == NULL || _saar == NULL); saar = _saar; } void setGUIMode(bool v) { guiMode = v; } void _setActiveWindowName(const QString& name) { activeWindow = name; } void setGUITestBase(GUITestBase *_tb) {assert(tb == NULL || _tb == NULL); tb = _tb;} static AppContextImpl* getApplicationContext(); protected: virtual PluginSupport* _getPluginSupport() const {return ps;} virtual ServiceRegistry* _getServiceRegistry() const {return sr;} virtual ProjectLoader* _getProjectLoader() const {return pl;} virtual Project* _getProject() const {return prj;} virtual ProjectService* _getProjectService() const {return prs;} virtual MainWindow* _getMainWindow() const {return mw;} virtual ProjectView* _getProjectView() const {return pv;} virtual PluginViewer* _getPluginViewer() const {return plv;} virtual Settings* _getSettings() const {return ss;} virtual Settings* _getGlobalSettings() const {return gs;} virtual AppSettings* _getAppSettings() const{return as;}; virtual AppSettingsGUI* _getAppSettingsGUI() const{return asg;}; virtual DocumentFormatRegistry* _getDocumentFormatRegistry() const {return dfr;} virtual IOAdapterRegistry* _getIOAdapterRegistry() const {return io;} virtual DNATranslationRegistry* _getDNATranslationRegistry() const {return dtr;} virtual DNAAlphabetRegistry* _getDNAAlphabetRegistry() const {return dal;} virtual GObjectViewFactoryRegistry* _getObjectViewFactoryRegistry() const {return ovfr;} virtual TaskScheduler* _getTaskScheduler() const {return ts;} virtual ResourceTracker* _getResourceTracker() const {return rt;} virtual AnnotationSettingsRegistry* _getAnnotationsSettingsRegistry() const {return asr;} virtual TestFramework* _getTestFramework() const {return tf;} virtual DBXRefRegistry* _getDBXRefRegistry() const {return dbxr;} virtual SubstMatrixRegistry* _getSubstMatrixRegistry() const {return smr;} virtual SmithWatermanTaskFactoryRegistry* _getSmithWatermanTaskFactoryRegistry() const {return swar;} virtual PhyTreeGeneratorRegistry* _getPhyTreeGeneratorRegistry() const {return treeGeneratorRegistry;} virtual MolecularSurfaceFactoryRegistry* _getMolecularSurfaceFactoryRegistry() const {return msfr;} virtual SWResultFilterRegistry* _getSWResultFilterRegistry() const {return swrfr;} virtual MSAColorSchemeRegistry* _getMSAColorSchemeRegistry() const {return mcsr;} virtual SecStructPredictAlgRegistry* _getSecStructPredictAlgRegistry() const {return secStructPredictRegistry;} virtual CudaGpuRegistry * _getCudaGpuRegistry() const { return cgr; } virtual OpenCLGpuRegistry * _getOpenCLGpuRegistry() const { return oclgr; } virtual RecentlyDownloadedCache* _getRecentlyDownloadedCache() const {return rdc;} virtual DocumentFormatConfigurators* _getDocumentFormatConfigurators() const {return dfc;} virtual ProtocolInfoRegistry * _getProtocolInfoRegistry() const { return protocolInfoRegistry; } virtual RemoteMachineMonitor * _getRemoteMachineMonitor() const { return remoteMachineMonitor; } virtual CMDLineRegistry* _getCMDLineRegistry() const {return cmdLineRegistry;} virtual MSAConsensusAlgorithmRegistry* _getMSAConsensusAlgorithmRegistry() const {return msaConsensusAlgoRegistry;} virtual MSADistanceAlgorithmRegistry* _getMSADistanceAlgorithmRegistry() const {return msaDistanceAlgoRegistry;} virtual PWMConversionAlgorithmRegistry* _getPWMConversionAlgorithmRegistry() const {return pwmConversionAlgoRegistry;} virtual VirtualFileSystemRegistry * _getVirtualFileSystemRegistry() const { return virtualFileSystemRegistry; } virtual DnaAssemblyAlgRegistry* _getDnaAssemblyAlgRegistry() const {return dnaAssemblyAlgRegistry; } virtual MSAAlignAlgRegistry* _getMSAAlignAlgRegistry() const {return msaAlignAlgRegistry; } virtual DataBaseRegistry * _getDataBaseRegistry() const {return dataBaseRegistry;} virtual ExternalToolRegistry * _getExternalToolRegistry() const {return externalToolRegistry;} virtual RepeatFinderTaskFactoryRegistry* _getRepeatFinderTaskFactoryRegistry() const {return rfr;} virtual QDActorPrototypeRegistry* _getQDActorFactoryRegistry() const { return qdafr; } virtual StructuralAlignmentAlgorithmRegistry* _getStructuralAlignmentAlgorithmRegistry() const { return saar; } virtual AutoAnnotationsSupport* _getAutoAnnotationsSupport() const { return aaSupport; } virtual CDSearchFactoryRegistry* _getCDSFactoryRegistry() const { return cdsfr; } virtual U2DbiRegistry * _getDbiRegistry() const { return dbiRegistry; } virtual GUITestBase* _getGUITestBase() const {return tb;} virtual void _registerGlobalObject(AppGlobalObject* go); virtual void _unregisterGlobalObject(const QString& id); virtual AppGlobalObject* _getGlobalObjectById(const QString& id) const; virtual bool _isGUIMode() const {return guiMode;} virtual QString _getActiveWindowName() const {return activeWindow;} private: PluginSupport* ps; ServiceRegistry* sr; ProjectLoader* pl; Project* prj; ProjectService* prs; MainWindow* mw; ProjectView* pv; PluginViewer* plv; Settings* ss; Settings* gs; DocumentFormatRegistry* dfr; IOAdapterRegistry* io; DNATranslationRegistry* dtr; DNAAlphabetRegistry* dal; GObjectViewFactoryRegistry* ovfr; TaskScheduler* ts; ResourceTracker* rt; DocumentFormatConfigurators* dfc; AnnotationSettingsRegistry* asr; AppSettings * as; TestFramework* tf; DBXRefRegistry* dbxr; SubstMatrixRegistry* smr; SmithWatermanTaskFactoryRegistry* swar; MolecularSurfaceFactoryRegistry* msfr; SWResultFilterRegistry* swrfr; AppSettingsGUI* asg; MSAColorSchemeRegistry* mcsr; SecStructPredictAlgRegistry* secStructPredictRegistry; CudaGpuRegistry * cgr; OpenCLGpuRegistry * oclgr; RecentlyDownloadedCache* rdc; ProtocolInfoRegistry * protocolInfoRegistry; RemoteMachineMonitor * remoteMachineMonitor; PhyTreeGeneratorRegistry *treeGeneratorRegistry; CMDLineRegistry* cmdLineRegistry; MSAConsensusAlgorithmRegistry* msaConsensusAlgoRegistry; MSADistanceAlgorithmRegistry* msaDistanceAlgoRegistry; PWMConversionAlgorithmRegistry* pwmConversionAlgoRegistry; VirtualFileSystemRegistry * virtualFileSystemRegistry; DnaAssemblyAlgRegistry* dnaAssemblyAlgRegistry; MSAAlignAlgRegistry* msaAlignAlgRegistry; DataBaseRegistry* dataBaseRegistry; ExternalToolRegistry * externalToolRegistry; RepeatFinderTaskFactoryRegistry* rfr; QDActorPrototypeRegistry* qdafr; CDSearchFactoryRegistry* cdsfr; StructuralAlignmentAlgorithmRegistry* saar; AutoAnnotationsSupport* aaSupport; U2DbiRegistry *dbiRegistry; GUITestBase *tb; bool guiMode; QString activeWindow; QList appGlobalObjects; }; }//namespace #endif ugene-1.9.8/src/corelibs/U2Private/src/DocumentFormatRegistryImpl.h0000644000175000017500000000353411651544333024000 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _DOCUMENT_FORMAT_REGISTRY_IMPL_H_ #define _DOCUMENT_FORMAT_REGISTRY_IMPL_H_ #include "private.h" #include #include namespace U2 { class U2PRIVATE_EXPORT DocumentFormatRegistryImpl : public DocumentFormatRegistry { public: DocumentFormatRegistryImpl(QObject* p = NULL) : DocumentFormatRegistry(p) {init();} virtual bool registerFormat(DocumentFormat* dfs); virtual bool unregisterFormat(DocumentFormat* dfs); virtual QList getRegisteredFormats() const; virtual DocumentFormat* getFormatById(DocumentFormatId id) const; virtual DocumentFormat* selectFormatByFileExtension(const QString& fileExt) const; virtual QList selectFormats(const DocumentFormatConstraints& c) const; virtual DocumentImportersRegistry* getImportSupport() {return &importSupport;} private: void init(); QList formats; DocumentImportersRegistry importSupport; }; }//namespace #endif ugene-1.9.8/src/corelibs/U2Private/src/ServiceRegistryImpl.h0000644000175000017500000000663711651544333022460 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_SERVICE_REGISTRY_IMPL_ #define _U2_SERVICE_REGISTRY_IMPL_ #include "private.h" #include #include #include namespace U2 { class RegisterServiceTask; class EnableServiceTask; class UnregisterServiceTask; class DisableServiceTask; class U2PRIVATE_EXPORT ServiceRegistryImpl : public ServiceRegistry { Q_OBJECT friend class RegisterServiceTask; friend class EnableServiceTask; friend class UnregisterServiceTask; friend class DisableServiceTask; public: ServiceRegistryImpl() {timerIsActive = false;} ~ServiceRegistryImpl(); /// Returns list of all registered services virtual const QList& getServices() const {return services;} /// Finds service with the specified ServiceType virtual QList findServices(ServiceType t) const; virtual Task* registerServiceTask(Service* s); virtual Task* unregisterServiceTask(Service* s); virtual Task* enableServiceTask(Service* s); virtual Task* disableServiceTask(Service* s); void unregisterPluginServices(Plugin* p); private: void initiateServicesCheckTask(); Service* findServiceReadyToEnable() const; void setServiceState(Service* s, ServiceState state); Task* createServiceEnablingTask(Service* s) {return _createServiceEnablingTask(s);} Task* createServiceDisablingTask(Service* s) {return _createServiceDisablingTask(s);} protected: void timerEvent(QTimerEvent *event); private: QList services; bool timerIsActive; QList activeServiceTasks; }; class RegisterServiceTask : public Task { Q_OBJECT public: RegisterServiceTask(ServiceRegistryImpl* sr, Service* s); virtual void prepare(); private: ServiceRegistryImpl* sr; Service* s; }; class EnableServiceTask : public Task { Q_OBJECT public: EnableServiceTask(ServiceRegistryImpl* sr, Service* s); virtual void prepare(); virtual ReportResult report(); private: ServiceRegistryImpl* sr; Service* s; }; class UnregisterServiceTask : public Task { Q_OBJECT public: UnregisterServiceTask(ServiceRegistryImpl* sr, Service* s); virtual void prepare(); virtual ReportResult report(); private: ServiceRegistryImpl* sr; Service* s; }; class DisableServiceTask : public Task { Q_OBJECT public: DisableServiceTask(ServiceRegistryImpl* sr, Service* s, bool manual); virtual void prepare(); virtual ReportResult report(); private: ServiceRegistryImpl* sr; Service* s; bool manual; }; }//namespace #endif ugene-1.9.8/src/corelibs/U2Private/src/private.h0000644000175000017500000000027711651544333020151 0ustar ilyailya#ifndef _PRIVATE_DEFINES_H_ #define _PRIVATE_DEFINES_H_ #ifdef BUILDING_U2PRIVATE_DLL # define U2PRIVATE_EXPORT Q_DECL_EXPORT #else # define U2PRIVATE_EXPORT Q_DECL_IMPORT #endif #endifugene-1.9.8/src/corelibs/U2Private/src/AppContextImpl.cpp0000644000175000017500000000376711651544333021750 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "AppContextImpl.h" #include namespace U2 { static AppContextImpl appContext; AppContextImpl::~AppContextImpl() { for (int i=appGlobalObjects.size(); --i>=0; ) { //remove objects in reverse mode, so the last added deleted first AppGlobalObject* obj = appGlobalObjects[i]; delete obj; } } AppContextImpl* AppContextImpl::getApplicationContext() { return &appContext; } void AppContextImpl::_registerGlobalObject(AppGlobalObject* go) { const QString& id = go->getId(); assert(_getGlobalObjectById(id) == NULL); Q_UNUSED(id); appGlobalObjects.append(go); } void AppContextImpl::_unregisterGlobalObject(const QString& id) { for (int i=0, n = appGlobalObjects.size(); i < n; i++) { AppGlobalObject* obj = appGlobalObjects.at(i); if (obj->getId() == id) { appGlobalObjects.removeAt(i); break; } } } AppGlobalObject* AppContextImpl::_getGlobalObjectById(const QString& id) const { foreach(AppGlobalObject* obj, appGlobalObjects) { if (obj->getId() == id) { return obj; } } return NULL; } }//namespace ugene-1.9.8/src/corelibs/U2Private/src/TaskSchedulerImpl.cpp0000644000175000017500000007352611651544333022424 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "TaskSchedulerImpl.h" #include #include #include #include #include #include #include /* TRANSLATOR U2::TaskSchedulerImpl */ namespace U2 { #define UPDATE_TIMEOUT 100 TaskSchedulerImpl::TaskSchedulerImpl(AppResourcePool* rp) { resourcePool = rp; stateNames << tr("New") << tr("Prepared") << tr("Running") << tr("Finished"); connect(&timer, SIGNAL(timeout()), this, SLOT(update())); timer.start(UPDATE_TIMEOUT); stateChangesObserved = false; threadsResource = resourcePool->getResource(RESOURCE_THREAD); schedulerLog = new LogCache(); schedulerLog->filter.filters.append(LogFilterItem(ULOG_CAT_TASKS, LogLevel_TRACE)); schedulerLog->filter.filters.append(LogFilterItem(ULOG_CAT_CORE_SERVICES, LogLevel_TRACE)); schedulerLog->filter.filters.append(LogFilterItem(ULOG_CAT_IO, LogLevel_TRACE)); schedulerLog->filter.filters.append(LogFilterItem(ULOG_CAT_USER_INTERFACE, LogLevel_ERROR)); schedulerLog->filter.filters.append(LogFilterItem(ULOG_CAT_ALGORITHM, LogLevel_TRACE)); schedulerLog->filter.filters.append(LogFilterItem(ULOG_CAT_CONSOLE, LogLevel_ERROR)); } TaskSchedulerImpl::~TaskSchedulerImpl() { assert(topLevelTasks.empty()); assert(priorityQueue.isEmpty()); } void TaskSchedulerImpl::cancelTask(Task* task) { if (task->getState() < Task::State_Finished) { taskLog.info(tr("Canceling task: %1").arg(task->getTaskName())); getTaskStateInfo(task).cancelFlag = true; foreach(Task* t, task->getSubtasks()) { cancelTask(t); } } } void TaskSchedulerImpl::cancelAllTasks() { foreach(Task* t, topLevelTasks) { cancelTask(t); } } void TaskSchedulerImpl::propagateStateToParent(Task* task) { Task* parentTask = task->getParentTask(); if (parentTask == NULL) { return; } if (parentTask->hasError() || parentTask->isCanceled()) { return; } if (task->isCanceled() && parentTask->getFlags().testFlag(TaskFlag_FailOnSubtaskCancel)) { TaskStateInfo& tsi = getTaskStateInfo(parentTask); tsi.setError( tr("Subtask {%1} is canceled %2").arg(task->getTaskName()).arg(task->getError()) ); cancelTask(parentTask); } else if (task->hasError() && parentTask->getFlags().testFlag(TaskFlag_FailOnSubtaskError)) { TaskStateInfo& tsi = getTaskStateInfo(parentTask); if (parentTask->getFlags().testFlag(TaskFlag_MinimizeSubtaskErrorText)) { tsi.setError(task->getError()); } else { tsi.setError( tr("Subtask {%1} is failed: %2").arg(task->getTaskName()).arg(task->getError())); } } } bool TaskSchedulerImpl::processFinishedTasks() { bool hasFinished = false; for (int i = priorityQueue.size(); --i>=0;) { TaskInfo* ti = priorityQueue[i]; TaskInfo* pti = ti->parentTaskInfo; Task::State state = ti->task->getState(); assert(state != Task::State_Finished); if (ti->task->getTimeOut() > 0){ int secsPassed = GTimer::secsBetween(ti->task->getTimeInfo().startTime, GTimer::currentTimeMicros()); if(ti->task->getTimeOut() < secsPassed){ QString msg = QString("Timeout error, running %1 sec expected %2 sec.").arg(secsPassed).arg(ti->task->getTimeOut()); taskLog.error(QString("Task {%1} %2 Cancelling task...").arg(ti->task->getTaskName()).arg(msg)); ti->task->setError(msg); ti->task->cancel(); } } //if the task was canceled -> cancel subtasks too if (ti->task->isCanceled() && !ti->subtasksWereCanceled) { ti->subtasksWereCanceled = true; foreach(Task* t, ti->task->getSubtasks()) { cancelTask(t); } } if (state != Task::State_Running) { continue; } if (ti->selfRunFinished && ti->hasLockedRunResources) { releaseResources(ti, false); //release resources for RUN stage } //update state desc updateTaskProgressAndDesc(ti); if (!readyToFinish(ti)) { //the task can be finished only after all its subtasks finished and its run finished continue; } if (ti->wasPrepared) { Task::ReportResult res = ti->task->report(); if (res == Task::ReportResult_CallMeAgain) { continue; } } hasFinished = true; promoteTask(ti, Task::State_Finished); releaseResources(ti, true); //release resources for PREPARE stage Task* task = ti->task; priorityQueue.removeAt(i); delete ti; //task is removed from priority queue // notify parent that subtask finished, check if there are new subtasks from parent if (pti != NULL) { Task* parentTask = pti->task; SAFE_POINT(parentTask != NULL, "When notifying parentTask about finished task: parentTask is NULL", hasFinished); SAFE_POINT(task != NULL, "When notifying parentTask about finished task: task is NULL", hasFinished); propagateStateToParent(task); QList newSubTasks = onSubTaskFinished(parentTask, task); if (!newSubTasks.isEmpty() || !pti->newSubtasks.isEmpty()) { if (!tasksWithNewSubtasks.contains(pti)) { tasksWithNewSubtasks.append(pti); } } foreach(Task* newSub, newSubTasks) { if(newSub != NULL) { pti->newSubtasks.append(newSub); addSubTask(parentTask, newSub); } else { taskLog.error(QString("Calling onSubTaskFinished from task {%1} with subtask {%2} returned list containing NULL, skipping").arg(parentTask->getTaskName()).arg(task->getTaskName())); } } } } return hasFinished; } void TaskSchedulerImpl::unregisterFinishedTopLevelTasks() { QList tasksToDelete; foreach(Task* task, topLevelTasks) { if (task->getState() == Task::State_Finished) { tasksToDelete.append(task); } } foreach(Task* task, tasksToDelete) { unregisterTopLevelTask(task); } } void TaskSchedulerImpl::processNewSubtasks() { for (int i=0, n = tasksWithNewSubtasks.size();inewSubtasks.size() > 0); int nParallel = ti->task->getNumParallelSubtasks(); int nNew = ti->newSubtasks.size(); int nToRun = qMin(nParallel - ti->numActiveSubtasks(), nNew); int nRun = 0; for (int j=0; j < nToRun; j++) { Task* newSub = ti->newSubtasks[j]; bool ok = addToPriorityQueue(newSub, ti); if (ok) { ti->newSubtasks[j] = NULL; nRun++; } } if (nRun == nNew) { ti->newSubtasks.clear(); tasksWithNewSubtasks[i] = NULL; } else if (nRun > 0) { ti->newSubtasks.removeAll(NULL); } } tasksWithNewSubtasks.removeAll(NULL); } void TaskSchedulerImpl::runReady() { foreach(TaskInfo* ti, priorityQueue) { Task* task = ti->task; Task::State state = task->getState(); //Note: task is running if any of its subtasks is running assert(state == Task::State_Prepared || state == Task::State_Running); if (task->getFlags().testFlag(TaskFlag_NoRun) || task->isCanceled() || task->hasError()) { if (state == Task::State_Prepared) { promoteTask(ti, Task::State_Running); } if (ti->thread == NULL) { ti->selfRunFinished = true; } continue; } if (ti->thread!=NULL) { //task is already running in a separate thread assert(state == Task::State_Running); continue; } bool ready = task->hasFlags(TaskFlag_RunBeforeSubtasksFinished) || ti->numFinishedSubtasks == task->getSubtasks().size(); if (!ready) { continue; } QString noResMessage = tryLockResources(ti->task, false, ti->hasLockedRunResources); if (!noResMessage.isEmpty()) { setTaskStateDesc(ti->task, noResMessage); continue; } if (state == Task::State_Prepared) { promoteTask(ti, Task::State_Running); } setTaskStateDesc(ti->task, ""); runThread(ti); } } void TaskSchedulerImpl::runThread(TaskInfo* ti) { #ifdef _DEBUG assert(ti->task->getState() == Task::State_Running); assert(!ti->task->getFlags().testFlag(TaskFlag_NoRun)); assert(ti->task->hasFlags(TaskFlag_RunBeforeSubtasksFinished) || ti->numFinishedSubtasks == ti->task->getSubtasks().size()); assert(!ti->task->isCanceled()); assert(!ti->task->hasError()); assert(!ti->selfRunFinished); #endif ti->thread = new TaskThread(ti); connect(ti->thread, SIGNAL(finished()), SLOT(sl_threadFinished())); ti->thread->start(); } QString TaskSchedulerImpl::tryLockResources(Task* task, bool prepareStage, bool& hasLockedResourcesAfterCall) { if (prepareStage) { //task must be New SAFE_POINT(task->getState() == Task::State_New, "Attempt to lock prepare-stage resources for non-NEW task!", L10N::internalError()); } else { //task must be Prepared or Running. Task can be 'Running' if it has subtasks SAFE_POINT(task->getState() == Task::State_Running || task->getState() == Task::State_Prepared, QString("Attempt to lock run-stage for task in state: %1!").arg(task->getState()), L10N::internalError()); } if (!prepareStage && !threadsResource->isAvailable()) { return tr("Waiting for resource '%1', count: %2").arg(threadsResource->name).arg(1); } TaskResources& tres = getTaskResources(task); for (int i=0, n = tres.size(); igetResource(taskRes.resourceId); if (!appRes->isAvailable(taskRes.resourceUse)) { if (appRes->maxUse < taskRes.resourceUse) { task->setError(tr("Not enough resources for the task, resource name: '%1' max: %2%3 requested: %4%5") .arg(appRes->name).arg(appRes->maxUse).arg(appRes->suffix).arg(taskRes.resourceUse).arg(appRes->suffix)); } return tr("Waiting for resource '%1', count: %2%3").arg(appRes->name).arg(taskRes.resourceUse).arg(appRes->suffix); } } //ok there are all task resources available -> lock it int nLocked = 0; if (!prepareStage) { threadsResource->acquire(); taskLog.trace(QString("acquiring resource: '%1':%2, state: %3/%4").arg(threadsResource->name).arg(1).arg(threadsResource->currentUse).arg(threadsResource->maxUse)); nLocked++; } for (int i=0, n = tres.size(); igetResource(taskRes.resourceId); appRes->acquire(taskRes.resourceUse); taskRes.locked = true; nLocked++; taskLog.trace(QString("acquiring resource: '%1':%2, state: %3/%4").arg(appRes->name).arg(taskRes.resourceUse).arg(appRes->currentUse).arg(appRes->maxUse)); } hasLockedResourcesAfterCall = nLocked > 0; return QString::null; } void TaskSchedulerImpl::releaseResources(TaskInfo* ti, bool prepareStage) { SAFE_POINT(ti->task->getState() == (prepareStage ? Task::State_Finished : Task::State_Running), "Releasing task resources in illegal state!",); if (!(prepareStage ? ti->hasLockedPrepareResources : ti->hasLockedRunResources)) { return; } if (!prepareStage) { threadsResource->release(); } taskLog.trace(QString("releasing resource: '%1':%2, state: %3/%4").arg(threadsResource->name).arg(1).arg(threadsResource->currentUse).arg(threadsResource->maxUse)); TaskResources& tres = getTaskResources(ti->task); for (int i=0, n = tres.size(); igetResource(taskRes.resourceId); appRes->release(taskRes.resourceUse); taskRes.locked = false; taskLog.trace(QString("releasing resource: '%1':%2, state: %3/%4").arg(appRes->name).arg(taskRes.resourceUse).arg(appRes->currentUse).arg(appRes->maxUse)); } if (prepareStage) { ti->hasLockedPrepareResources = false; } else { ti->hasLockedRunResources = false; } } void TaskSchedulerImpl::update() { static bool recursion = false; if (recursion) { return; } recursion = true; stateChangesObserved = false; bool finishedFound = processFinishedTasks(); if (finishedFound) { unregisterFinishedTopLevelTasks(); } processNewSubtasks(); prepareNewTasks(); runReady(); updateOldTasksPriority(); if (stateChangesObserved) { stateChangesObserved = false; timer.setInterval(0); } else if (timer.interval()!=UPDATE_TIMEOUT){ timer.setInterval(UPDATE_TIMEOUT); } recursion = false; } void TaskSchedulerImpl::prepareNewTasks() { if (newTasks.empty()) { return; } QList newCopy = newTasks; newTasks.clear(); foreach(Task* task, newCopy) { if (task->hasError() || task->isCanceled()) {//check if its canceled or has errors propagateStateToParent(task); //forget about this task TaskInfo ti(task, 0); promoteTask(&ti, Task::State_Finished); if (task->isTopLevelTask()) { unregisterTopLevelTask(task); } continue; } bool ok = addToPriorityQueue(task, NULL); if (!ok) { newTasks.append(task); } } } void TaskSchedulerImpl::registerTopLevelTask(Task* task) { SAFE_POINT(task, QString("Trying to register NULL task"),); #ifdef _DEBUG QThread* appThread = QCoreApplication::instance()->thread(); QThread* thisThread = QThread::currentThread(); QThread* taskThread = task->thread(); assert(appThread == thisThread); assert(taskThread == thisThread); #endif SAFE_POINT(task->getState() == Task::State_New, QString("Trying to register task in not NEW state. State: %1").arg(task->getState()),); SAFE_POINT(!topLevelTasks.contains(task), QString("Task is already registered: %1").arg(task->getTaskName()),); taskLog.details(tr("Registering new task: %1").arg(task->getTaskName())); topLevelTasks.append(task); emit si_topLevelTaskRegistered(task); newTasks.append(task); } bool TaskSchedulerImpl::addToPriorityQueue(Task* task, TaskInfo* pti) { if (pti!=NULL && (pti->task->isCanceled() || pti->task->hasError())) { //canceled tasks are not processed task->cancel(); } //check if there are enough resources; bool runPrepare = !task->isCanceled() && !task->hasError(); bool lr = false; if (runPrepare) { QString noResMessage = tryLockResources(task, true, lr); if (!noResMessage.isEmpty()) { setTaskStateDesc(task, noResMessage); if (!task->hasError()) { return false; //call again } else { runPrepare = false; // resource lock error } } } TaskInfo* ti = new TaskInfo(task, pti); ti->hasLockedPrepareResources = lr; priorityQueue.append(ti); if (runPrepare) { setTaskInsidePrepare(task, true); task->prepare(); setTaskInsidePrepare(task, false); ti->wasPrepared = true; } promoteTask(ti, Task::State_Prepared); int nParallel = task->getNumParallelSubtasks(); const QList& subtasks = task->getSubtasks(); for (int i = 0, n = subtasks.size(); i < n; i++) { Task* sub = subtasks[i]; bool ok = i < nParallel && addToPriorityQueue(sub, ti); if (!ok && !sub->hasError()) { //if task got err on resource allocation -> its not new now, but failed ti->newSubtasks.append(sub); if( !tasksWithNewSubtasks.contains(ti) ){ tasksWithNewSubtasks.append(ti); } } } return true; } void TaskSchedulerImpl::unregisterTopLevelTask(Task* task) { SAFE_POINT(task != NULL, "Trying to unregister NULL task",); SAFE_POINT(topLevelTasks.contains(task), QString("Trying to unregister task that is not top-level"),); taskLog.trace(tr("Unregistering task: %1").arg(task->getTaskName())); stopTask(task); topLevelTasks.removeOne(task); emit si_topLevelTaskUnregistered(task); if (!task->hasFlags(TaskFlag_NoAutoDelete)) { deleteTask(task); } } void TaskSchedulerImpl::stopTask(Task* task) { foreach(Task* sub, task->getSubtasks()) { stopTask(sub); } foreach(TaskInfo* ti, priorityQueue) { //stop task if its running if (ti->task == task) { cancelTask(task); if (ti->thread!=NULL && !ti->thread->isFinished()) { ti->thread->wait();//TODO: try avoid blocking here } assert(readyToFinish(ti)); break; } } } bool TaskSchedulerImpl::readyToFinish(TaskInfo* ti) { if (ti->task->getState() == Task::State_Finished) { return true; } if (ti->task->getState() != Task::State_Running) { return false; } if (ti->numFinishedSubtasks < ti->task->getSubtasks().size()) { return false; } if (!ti->selfRunFinished) { return false; } #ifdef _DEBUG foreach(Task* sub, ti->task->getSubtasks()) { //must be true because of 'numFinishedSubtasks' check above assert(sub->getState() == Task::State_Finished); } assert(ti->newSubtasks.isEmpty()); #endif return true; } QString TaskSchedulerImpl::getStateName(Task* t) const { Task::State s = t->getState(); return stateNames[s]; } QDateTime TaskSchedulerImpl::estimatedFinishTime(Task* task) const { SAFE_POINT(task->getState() == Task::State_Running, "Method is valid for running tasks only", QDateTime()); const TaskTimeInfo& tti = task->getTimeInfo(); int secsPassed = GTimer::secsBetween(tti.startTime, GTimer::currentTimeMicros()); float percentInSecs = task->getProgress() / (float)secsPassed; int secsTotal = int(percentInSecs * 100); int secsLeft = secsTotal - secsPassed; QDateTime res = QDateTime::currentDateTime(); res.addSecs(secsLeft); return res; } static QString state2String(Task::State state) { switch(state) { case Task::State_New: return TaskSchedulerImpl::tr("New"); case Task::State_Prepared: return TaskSchedulerImpl::tr("Prepared"); case Task::State_Running: return TaskSchedulerImpl::tr("Running"); case Task::State_Finished: return TaskSchedulerImpl::tr("Finished"); default: assert(0); } return TaskSchedulerImpl::tr("Invalid name"); } void TaskSchedulerImpl::checkSerialPromotion(TaskInfo* pti, Task* subtask) { #ifdef _DEBUG assert(!subtask->isNew()); //must be promoted at this point -> check algorithm depends requirement Task* task = pti == NULL ? NULL : pti->task; if (task == NULL) { return; } int nParallel = task->getNumParallelSubtasks(); bool before = true; int numActive = 0; const QList& subs = task->getSubtasks(); for (int i=0, n = subs.size(); i < n; i++) { Task* sub = subs[i]; if (!sub->isNew() && !sub->isFinished()) { numActive++; assert(numActive <= nParallel); } if (sub == subtask) { before = false; } else if (before) { Task::State subState = sub->getState(); assert(subState!=Task::State_New); } } #else Q_UNUSED(pti); Q_UNUSED(subtask); #endif } static void checkFinishedState(TaskInfo* ti) { #ifdef _DEBUG foreach(Task* sub, ti->task->getSubtasks()) { assert(sub->getState() == Task::State_Finished); } assert(ti->newSubtasks.empty()); assert(ti->task->getSubtasks().size() == ti->numFinishedSubtasks); assert(ti->numRunningSubtasks == 0); assert(ti->numPreparedSubtasks == 0); #else Q_UNUSED(ti); # #endif } void TaskSchedulerImpl::promoteTask(TaskInfo* ti, Task::State newState) { stateChangesObserved = true; Task* task = ti->task; assert(newState > task->getState()); setTaskState(task, newState); //emits signals TaskStateInfo& tsi = getTaskStateInfo(task); TaskTimeInfo& tti = getTaskTimeInfo(task); TaskInfo* pti = ti->parentTaskInfo; if (!tsi.hasError()) { taskLog.trace(tr("promoting task {%1} to '%2'").arg(task->getTaskName()).arg(state2String(newState))); } else { taskLog.trace(tr("promoting task {%1} to '%2', error '%3'").arg(task->getTaskName()).arg(state2String(newState)).arg(tsi.getError())); } checkSerialPromotion(pti, ti->task); switch(newState) { case Task::State_Prepared: if (pti != NULL) { pti->numPreparedSubtasks++; } if (ti->task->isTopLevelTask() && ti->task->isVerboseLogMode()) { taskLog.info(tr("Starting {%1} task").arg(ti->task->getTaskName())); } break; case Task::State_Running: tti.startTime = GTimer::currentTimeMicros(); if (pti != NULL) { pti->numPreparedSubtasks--; pti->numRunningSubtasks++; if (pti->task->getState() < Task::State_Running) { assert(pti->task->getState() == Task::State_Prepared); promoteTask(pti, Task::State_Running); } } break; case Task::State_Finished: checkFinishedState(ti); tti.finishTime = GTimer::currentTimeMicros(); tsi.setDescription(QString()); if (pti != NULL) { pti->numRunningSubtasks--; assert(pti->numRunningSubtasks>=0); pti->numFinishedSubtasks++; assert(pti->numFinishedSubtasks <= pti->task->getSubtasks().size()); } if (ti->task->isTopLevelTask()) { if (tsi.hasError() && !tsi.cancelFlag) { taskLog.error(tr("Task {%1} finished with error: %2").arg(task->getTaskName()).arg(tsi.getError())); } else if (tsi.cancelFlag) { taskLog.info(tr("Task {%1} canceled").arg(ti->task->getTaskName())); } else if (ti->task->isVerboseLogMode()) { taskLog.info(tr("Task {%1} finished").arg(ti->task->getTaskName())); } } break; default: assert(0); } #ifdef _DEBUG Task* parentTask = task->getParentTask(); if (parentTask!=NULL){ int localPreparedSubs, localRunningSubs, localFinishedSubs, localNewSubs, localTotalSubs; localTotalSubs = localNewSubs = localPreparedSubs = localRunningSubs = localFinishedSubs = 0; foreach (Task* sub, parentTask->getSubtasks()){ switch (sub->getState()){ case Task::State_New: localNewSubs++; break; case Task::State_Prepared: localPreparedSubs++; break; case Task::State_Running: localRunningSubs++; break; case Task::State_Finished: localFinishedSubs++; break; } localTotalSubs++; } assert(localPreparedSubs == pti->numPreparedSubtasks); assert(localRunningSubs == pti->numRunningSubtasks); assert(localPreparedSubs+localRunningSubs == pti->numActiveSubtasks()); assert(localFinishedSubs == pti->numFinishedSubtasks); assert(localTotalSubs == localNewSubs+localPreparedSubs+localRunningSubs+localFinishedSubs); } #endif updateTaskProgressAndDesc(ti); } void TaskSchedulerImpl::updateTaskProgressAndDesc(TaskInfo* ti) { Task* task = ti->task; TaskStateInfo& tsi = getTaskStateInfo(task); //update desc if (ti->task->useDescriptionFromSubtask()) { const QList& subs = task->getSubtasks(); if (!subs.isEmpty()) { Task* sub = subs.last(); tsi.setDescription(sub->getStateInfo().getDescription()); } } QString currentDesc = tsi.getDescription(); if (currentDesc!= ti->prevDesc) { ti->prevDesc = currentDesc; emit_taskDescriptionChanged(task); } //update progress int newProgress = tsi.progress; bool updateProgress = false; if (task->isFinished()) { newProgress = 100; updateProgress = tsi.progress != newProgress; } else if (task->getProgressManagementType() == Task::Progress_Manual) { int prevProgress = ti->prevProgress; if (tsi.progress != prevProgress) { ti->prevProgress = tsi.progress; emit_taskProgressChanged(task); } } else { assert(task->getProgressManagementType() == Task::Progress_SubTasksBased); const QList& subs = task->getSubtasks(); int nsubs = subs.size(); if (nsubs > 0) { float sum = 0; float maxSum = 0.001F; foreach(Task* sub, subs) { float w = sub->getSubtaskProgressWeight(); sum += sub->getProgress() * w; maxSum += w; } if (maxSum > 1.0f) { newProgress = qRound(sum / maxSum); } else { newProgress = qRound(sum); } } updateProgress = tsi.progress != newProgress; } if (updateProgress) { tsi.progress = newProgress; emit_taskProgressChanged(task); } } void TaskSchedulerImpl::deleteTask(Task* task) { SAFE_POINT(task != NULL, "Trying to delete NULL task",); foreach(Task* sub, task->getSubtasks()) { //todo: check subtask autodelete ?? deleteTask(sub); } taskLog.trace(tr("Deleting task: %1").arg(task->getTaskName())); delete task; } #define MAX_SECS_TO_LOWER_PRIORITY 60 static QThread::Priority getThreadPriority(Task* t) { assert(t->isTopLevelTask()); assert(t->isRunning()); int secsPassed = GTimer::secsBetween(t->getTopLevelParentTask()->getTimeInfo().startTime, GTimer::currentTimeMicros()); if (secsPassed > MAX_SECS_TO_LOWER_PRIORITY) { return QThread::LowestPriority; } return QThread::LowPriority; } static void updateThreadPriority(TaskInfo* ti) { assert(ti->thread!=NULL); QThread::Priority tp = getThreadPriority(ti->task->getTopLevelParentTask()); if (ti->thread->priority() != tp && ti->thread->isRunning()) { ti->thread->setPriority(tp); } } void TaskSchedulerImpl::updateOldTasksPriority() { //work every N-th tick #define UPDATE_GRAN 10 static int n = UPDATE_GRAN; if (--n !=0) { return; } n = UPDATE_GRAN; foreach(TaskInfo* ti, priorityQueue) { if (!ti->task->isRunning() || ti->thread == NULL || !ti->thread->isRunning()) { continue; } updateThreadPriority(ti); } } void TaskSchedulerImpl::sl_threadFinished() { timer.setInterval(0); } Task * TaskSchedulerImpl::getTopLevelTaskById( qint64 id ) const { Task * ret = NULL; foreach( Task * task, topLevelTasks ) { assert( NULL != task ); if( id == task->getTaskId() ) { ret = task; break; } } return ret; } static QMutex lock; void TaskThread::run() { // try { Qt::HANDLE handle= QThread::currentThreadId(); lock.lock(); AppContext::getTaskScheduler()->addThreadId(ti->task->getTaskId(), handle); lock.unlock(); assert(!ti->selfRunFinished); assert(ti->task->getState()== Task::State_Running); updateThreadPriority(ti); ti->task->run(); assert(ti->task->getState()== Task::State_Running); ti->selfRunFinished = true; lock.lock(); AppContext::getTaskScheduler()->removeThreadId(ti->task->getTaskId()); lock.unlock(); //delete handle; /*} catch(...) { if(CrashHandler::buffer) { CrashHandler::releaseReserve(); } CrashHandler::runMonitorProcess("|Unhandled exception"); }*/ } TaskInfo::~TaskInfo() { if (thread!=NULL) { if (!thread->isFinished()) { taskLog.trace("TaskScheduler: Waiting for the thread before delete"); thread->wait(); taskLog.trace("TaskScheduler: Wait finished"); } delete thread; } } }//namespace ugene-1.9.8/src/corelibs/U2Private/src/SettingsImpl.h0000644000175000017500000000325111651544333021114 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_SETTINGS_IMPL #define _U2_SETTINGS_IMPL #include "private.h" #include #include #include namespace U2 { class U2PRIVATE_EXPORT SettingsImpl : public Settings { public: SettingsImpl(QSettings::Scope scope); ~SettingsImpl(); QStringList getAllKeys(const QString& path); virtual bool contains(const QString& key) const; virtual void remove(const QString& key); virtual QVariant getValue(const QString& key, const QVariant& defaultValue = QVariant()) const; virtual void setValue(const QString& key, const QVariant& value); virtual QString toVersionKey(const QString& key) const; virtual void sync(); virtual QString fileName() const; private: mutable QMutex threadSafityLock; QSettings* settings; }; }//namespace #endif ugene-1.9.8/src/corelibs/U2Private/src/CrashHandler.h0000644000175000017500000000522311651544333021031 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _CRASH_HANDLER_H_ #define _CRASH_HANDLER_H_ #if defined(USE_CRASHHANDLER) #include #include #include #include #include #include #include #include #include #include "private.h" #include "StackWalker.h" #if defined( Q_OS_WIN ) #include //LONG NTAPI CrashHandlerFunc(PEXCEPTION_POINTERS pExceptionInfo ); #else #include #include #include #include #include #include #include #endif namespace U2 { struct ExceptionInfo { QString errorType; }; #if defined( Q_OS_WIN ) typedef PVOID (__stdcall* addExceptionHandler)( __in ULONG, __in PVECTORED_EXCEPTION_HANDLER); typedef PVOID (__stdcall* removeExceptionHandler)(__in PVOID); #endif class U2PRIVATE_EXPORT CrashHandler { public: CrashHandler() {} static void setupHandler(); #if defined( Q_OS_WIN ) static LONG NTAPI CrashHandlerFunc(PEXCEPTION_POINTERS pExceptionInfo ); static LONG NTAPI CrashHandlerFuncSecond(PEXCEPTION_POINTERS pExceptionInfo ); static LONG NTAPI CrashHandlerFuncThird(PEXCEPTION_POINTERS pExceptionInfo ); static PVOID handler; static PVOID handler2; static addExceptionHandler addHandlerFunc; static removeExceptionHandler removeHandlerFunc; static StackWalker st; #else static void signalHandler(int signo, siginfo_t *info, void *context); static struct sigaction sa; #endif static void runMonitorProcess(const QString &exceptionType); static void getSubTasks(Task *t, QString& list, int lvl); static void allocateReserve(); static void releaseReserve(); static char *buffer; }; } #endif //crash handler flag #endif ugene-1.9.8/src/corelibs/U2Private/src/PluginDescriptor.h0000644000175000017500000000504511651544333021772 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include #include #include "private.h" namespace U2 { #define PLUGIN_FILE_EXT "plugin" enum PlatformName { PlatformName_Unknown, PlatformName_Win, PlatformName_UnixNotMac, PlatformName_Mac }; enum PlatformArch { PlatformArch_Unknown, PlatformArch_32, PlatformArch_64 }; enum PluginModeFlag { PluginMode_Malformed = 1, PluginMode_Console = 1 << 1, PluginMode_UI = 1 << 2 }; typedef QFlags PluginMode; class PlatformInfo { public: PlatformName name; PlatformArch arch; bool operator == (const PlatformInfo& p) const {return name == p.name && arch == p.arch;} }; class DependsInfo { public: QString id; Version version; }; class PluginDesc { public: QString id; QString name; Version pluginVersion; Version ugeneVersion; Version qtVersion; QString pluginVendor; GUrl descriptorUrl; GUrl libraryUrl; PlatformInfo platform; PluginMode mode; QList dependsList; bool isValid() const { return !id.isEmpty() && !pluginVersion.text.isEmpty() && !ugeneVersion.text.isEmpty() && !libraryUrl.isEmpty(); } bool operator == (const PluginDesc& pd) const ; }; class U2PRIVATE_EXPORT PluginDescriptorHelper: public QObject { Q_OBJECT private: PluginDescriptorHelper() {}; public: static PluginDesc readPluginDescriptor(const QString& url, QString& error); //orders plugins by loading order static QList orderPlugins(const QList& unordered, QString& err); }; } //namespace ugene-1.9.8/src/corelibs/U2Private/src/LogSettings.cpp0000644000175000017500000001237511651544333021276 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "LogSettings.h" #include #include #include #include #define SETTINGS_ROOT QString("log_settings/") namespace U2 { QString LogCategories::localizedLevelNames[LogLevel_NumLevels]; void LogCategories::init() { localizedLevelNames[LogLevel_TRACE] = tr("TRACE"); localizedLevelNames[LogLevel_DETAILS] = tr("DETAILS"); localizedLevelNames[LogLevel_INFO] = tr("INFO"); localizedLevelNames[LogLevel_ERROR] = tr("ERROR"); } LogSettings::LogSettings() { //created in not inited state } const LoggerSettings& LogSettings::getLoggerSettings(const QString& cName) { QHash::const_iterator it = categories.find(cName); if( it == categories.end()) { reinitCategories(); it = categories.find(cName); assert(it!=categories.end()); } const LoggerSettings& cs = it.value(); return cs; } void LogSettings::reinitAll() { Settings *s = AppContext::getSettings(); for (int i=0; i < LogLevel_NumLevels; i++) { if (i == LogLevel_TRACE) { levelColors[i] = QColor(Qt::darkGray).name(); } else if (i == LogLevel_INFO) { levelColors[i] = QColor(Qt::darkBlue).name(); } else if (i == LogLevel_ERROR) { levelColors[i] = QColor(Qt::darkRed).name(); } else { levelColors[i] = QColor(Qt::black).name(); } } showDate = s->getValue(SETTINGS_ROOT + "showDate", true).toBool(); showLevel = s->getValue(SETTINGS_ROOT + "showLevel", true).toBool(); showCategory = s->getValue(SETTINGS_ROOT + "showCategory", false).toBool(); logPattern = s->getValue(SETTINGS_ROOT + "datePattern", "hh:mm").toString(); enableColor = s->getValue(SETTINGS_ROOT + "enableColor", true).toBool(); reinitCategories(); } void LogSettings::reinitCategories() { LogCategories::init(); Settings *s = AppContext::getSettings(); for (int i=0; igetValue(SETTINGS_ROOT + "activeFlagLevel"+QString::number(i), i >= LogLevel_INFO).toBool(); } LogServer* ls = LogServer::getInstance(); const QStringList& categoryList = ls->getCategories(); foreach(const QString& name, categoryList) { if (!categories.contains(name)) { LoggerSettings cs; cs.categoryName = name; for (int i=0; igetValue(SETTINGS_ROOT + "categories/" + cs.categoryName + "/activeFlagLevel" + QString::number(i), activeLevelGlobalFlag[i]).toBool(); } categories[name] = cs; } } } void LogSettings::removeCategory(const QString& name) { int n = categories.remove(name); assert(n == 1); Q_UNUSED(n); } void LogSettings::addCategory(const LoggerSettings& newcs) { assert(!categories.contains(newcs.categoryName)); categories[newcs.categoryName] = newcs; } void LogSettings::save() { Settings *s = AppContext::getSettings(); foreach(const LoggerSettings& cs, categories.values()) { for (int i=0; i < LogLevel_NumLevels; i++) { s->setValue(SETTINGS_ROOT + "categories/" + cs.categoryName + "/activeFlagLevel" + QString::number(i), cs.activeLevelFlag[i]); } } for (int i=0; i < LogLevel_NumLevels; i++) { s->setValue(SETTINGS_ROOT + "color" + QString::number(i), levelColors[i]); s->setValue(SETTINGS_ROOT + "activeFlagLevel"+QString::number(i), activeLevelGlobalFlag[i]); } s->setValue(SETTINGS_ROOT + "showDate", showDate); s->setValue(SETTINGS_ROOT + "showLevel", showLevel); s->setValue(SETTINGS_ROOT + "showCategory", showCategory); s->setValue(SETTINGS_ROOT + "enableColor", enableColor); s->setValue(SETTINGS_ROOT + "datePattern", logPattern); } bool LogSettings::operator==(const LogSettings& other) const { bool res = levelColors == other.levelColors && activeLevelGlobalFlag == other.activeLevelGlobalFlag && showDate == other.showDate && showLevel == other.showLevel && showCategory == other.showCategory && categories == other.categories; return res; } void LogSettingsHolder::setSettings(const LogSettings& s) { if (settings == s) { return; } settings = s; settings.save(); } }//namespace ugene-1.9.8/src/corelibs/U2Private/U2Private.pro0000644000175000017500000000175011651544333020077 0ustar ilyailyainclude (U2Private.pri) # Input HEADERS += src/AppContextImpl.h \ src/AppSettingsImpl.h \ src/CrashHandler.h \ src/DocumentFormatRegistryImpl.h \ src/IOAdapterRegistryImpl.h \ src/LogSettings.h \ src/PluginDescriptor.h \ src/PluginSupportImpl.h \ src/private.h \ src/ServiceRegistryImpl.h \ src/SettingsImpl.h \ src/TaskSchedulerImpl.h \ src/StackWalker.h SOURCES += src/AppContextImpl.cpp \ src/AppSettingsImpl.cpp \ src/CrashHandler.cpp \ src/DocumentFormatRegistryImpl.cpp \ src/IOAdapterRegistryImpl.cpp \ src/LogSettings.cpp \ src/PluginDescriptor.cpp \ src/PluginSupportImpl.cpp \ src/ServiceRegistryImpl.cpp \ src/SettingsImpl.cpp \ src/TaskSchedulerImpl.cpp \ src/StackWalker.cpp TRANSLATIONS += transl/czech.ts transl/english.ts transl/russian.ts ugene-1.9.8/src/corelibs/U2Private/transl/0000755000175000017500000000000011651544333017034 5ustar ilyailyaugene-1.9.8/src/corelibs/U2Private/transl/russian.ts0000644000175000017500000003606511651544333021102 0ustar ilyailya U2::AddPluginTask Add plugin task: %1 Загрузка внешнего модуля: %1 plugin_file_not_found_%1 Не найден внешний модуль: %1 plugin_invalid_file_format_%1 Некорректный файл библиотеки: %1 Plugin is already loaded: %1 Модуль уже загружен: %1 Plugin %1 depends on %2 which is not loaded Модуль %1 зависит от модуля %2, который не был загружен Plugin %1 depends on %2 which is available, but the version is too old Модуль %1 зависит от модуля %2, который доступен, но версия которого устарела Plugin loading error: %1, Error string %2 Plugin loading error: %1 Ошибка инициализации модуля: %1 Plugin initialization routine was not found: %1 Не найдена входная функция библиотеки модуля: %1 Plugin initialization failed: %1 Ошибка инициализации модуля: %1 U2::DisableServiceTask Disable '%1' service Остановка сервиса: %1 Active top-level task name: %1 Активная задача: %1 Active task was found Имеются неоконченные задачи Service is not registered: %1 Сервис не зарегистрирован: %1 Service is not enabled: %1 Сервис не запущен: %1 U2::EnableServiceTask Service is already enabled: %1 Сервис запущен: %1 Circullar service dependency: %1 Циркулярная зависимость модуля: %1 Required service is not enabled: %1 Не запущен обеспечивающий зависимость сервис: %1 Enable '%1' service Запуск сервиса: %1 U2::LoadAllPluginsTask Loading start up plugins Загрузка подключаемых модулей File not found: %1 Не найден внешний модуль: %1 Invalid file format: %1 Некорректный файл библиотеки: %1 U2::LogCategories TRACE Трассировка DETAILS Детали INFO Информация ERROR Ошибки U2::PluginDescriptorHelper Required attribute not found %1 Required element not found %1 Not valid value: '%1', plugin: %2 Platform arch is unknown: %1 Platform bits is unknown: %1 Invalid depends token: %1 Plugin circular dependency detected: %1 <-> %2 Can't satisfy dependencies for %1 ! U2::RegisterServiceTask Register '%1' service Регистрация сервиса: %1 Service is already registered '%1' Сервис уже зарегистрирован: %1 Illegal service state: %1 Ошибка сервиса: %1 Only one service of specified type is allowed: %1 Разрешён только один экземпляр сервиса: %1 U2::TaskSchedulerImpl New Новая Prepared Инициализирована Running Выполняется Finished Завершена Canceling task: %1 Отменяется задача "%1" Subtask {%1} is canceled Подзадача {%1} отменена. Subtask {%1} is failed: %2 Подзадача {%1} завершена с ошибкой: %2 TimeOut Error. TimeOut = %1 sec. Waiting for resource '%1', count: %2 Ожидание ресурса "%1", требуется: %2 Not enough resources for the task, resource name: '%1' max: %2%3 requested: %4%5 Не достаточно ресурсов для выполнения задачи: '%1' макс: %2%3 запрошено: %4%5 Waiting for resource '%1', count: %2%3 Ожидание ресурса "%1", требуется: %2%3 Registering new task: %1 Добавлена задача "%1" Uregistering task: %1 Задача удаляется из списка: "%1" Invalid name Неизвестное состояние Deleting task: %1 Удаляется задача "%1" promoting task {%1} to '%2' Задача {%1} %2. promoting task {%1} to '%2', error '%3' Задача {%1} %2; ошибка: %3 Starting {%1} task Старт задачи {%1} Task {%1} finished with error: %2 Задача {%1} завершена с ошибкой: %2 Task {%1} canceled Отменяется задача {%1} Task {%1} finished Задача {%1} завершена U2::UnregisterServiceTask Service is not registered: %1 Сервис не зарегистрирован: %1 Unregister '%1' service Дерегистрация сервиса "%1" ugene-1.9.8/src/corelibs/U2Private/transl/czech.ts0000644000175000017500000004426611651544333020514 0ustar ilyailya U2::AddPluginTask add_plugin_task_url_%1 Přidat úkol pro přídavný modul: %1 plugin_file_not_found_%1 Soubor nenalezen: %1 plugin_invalid_file_format_%1 Neplatný souborový formát: %1 plugin_already_loaded_%1 Přídavný modul je již nahrán: %1 plugin_library_loading_error_%1 Chyba při nahrávání přídavného modulu: %1 plugin_init_function_not_found_%1 Obslužný postup pro spuštění přídavného modulu nebyl nalezen: %1 plugin_init_failed_%1 Spuštění přídavného modulu se nezdařilo: %1 Add plugin task: %1 Přidat úlohu přídavného modulu: %1 Plugin is already loaded: %1 Přídavný modul je již nahrán: %1 Plugin %1 depends on %2 which is not loaded Plugin %1 depends on %2 which is available, but the version is too old Plugin loading error: %1, Error string %2 Plugin initialization routine was not found: %1 Obslužná procedura inicializace přídavného modulu nebyla nalezena: %1 Plugin initialization failed: %1 Inicializace přídavného modulu se nezdařila: %1 U2::DisableServiceTask disable_service_task_%1 Zakázat '%1' službu Disable '%1' service Zakázat '%1' službu Active top-level task name: %1 Název činného úkolu nejvyšší úrovně: %1 Active task was found Činný úkol byl nalezen Service is not registered: %1 Služba není zapsána: %1 Service is not enabled: %1 Služba není povolena: %1 error_active_tasks_found Byl nalezen činný úkol service_is_not_registered_%1 Služba není zapsána: %1 service_is_not_enabled_%1 Služba není povolena: %1 U2::EnableServiceTask Enable '%1' service Povolit '%1' službu Service is already enabled: %1 Služba je povolena: %1 Circullar service dependency: %1 Kruhová závislost služby: %1 Required service is not enabled: %1 Požadovaná služba není povolena: %1 enable_service_task_%1 Povolit '%1' službu service_is_enabled_%1 Služba je již povolena: %1 service_circular_dependency_%1 Kruhová závislost služby: %1 service_parent_not_enabled_%1 Požadovaná služba není povolena: %1 U2::LoadAllPluginsTask Loading start up plugins Nahrávají se přídavné moduly při spuštění File not found: %1 Soubor nenalezen: %1 Invalid file format: %1 U2::LogCategories TRACE STOPA DETAILS PODROBNOSTI INFO INFORMACE ERROR CHYBA U2::PluginDescriptorHelper Required attribute not found %1 Required element not found %1 Not valid value: '%1', plugin: %2 Platform arch is unknown: %1 Platform bits is unknown: %1 Invalid depends token: %1 Plugin circular dependency detected: %1 <-> %2 Can't satisfy dependencies for %1 ! U2::RegisterServiceTask Register '%1' service Zapsat '%1' službu Service is already registered '%1' Služba je již zapsána '%1' Illegal service state: %1 Neplatný stav služby: %1 register_service_task_%1 Zapsat '%1' službu service_is_already_registered_%1 Služba je již zapsána '%1' illegal_service_state_%1 Neplatný stav služby: %1 Only one service of specified type is allowed: %1 Je povolena pouze jedna služba daného typu: %1 U2::TaskSchedulerImpl state_name_new Nový state_name_prepared Připravený state_name_running Běžící state_name_finished Dokončený canceling task: %1 Ruší se úkol: %1 New Nový Prepared Připraven Running Běží Finished Dokončen Canceling task: %1 Ruší se úkol: %1 Subtask {%1} is canceled Podúkol {%1} je zrušen Subtask {%1} is failed: %2 Podúkol {%1} se nezdařil: %2 TimeOut Error. TimeOut = %1 sec. Chyba překročení času. Překročení času = %1 sek. Waiting for resource '%1', count: %2 Čeká se na zdroj '%1', počet: %2 Not enough resources for the task, resource name: '%1' max: %2%3 requested: %4%5 Není dostatek zdrojů pro úkol. Názec zdroje: '%1' největší: %2%3 požadovaný: %4%5 Waiting for resource '%1', count: %2%3 Čeká se na zdroj '%1', počet: %2%3 Registering new task: %1 Zapisuje se nový úkol: %1 Uregistering task: %1 Ruší se zápis úkolu: %1 Invalid name Neplatný název Deleting task: %1 Maže se úkol: %1 registering new task %1 Zapisuje se nový úkol: %1 unregistering task %1 Ruší se zápis nového úkolu: %1 invalid state name Neplatný název pro stav promoting task {%1} to '%2' Postupuje se úkol {%1} do '%2' promoting task {%1} to '%2', error '%3' Postupuje se úkol {%1} do '%2'. Chyba '%3' Starting {%1} task Začíná se úkol {%1} Task {%1} finished with error: %2 Úkol {%1} dokončen s chybou: %2 Task {%1} canceled Úkol {%1} zrušen Task {%1} finished Úkol {%1} dokončen deleting task %1 Maže se úkol: %1 U2::UnregisterServiceTask Unregister '%1' service Zrušit zápis '%1' služby Service is not registered: %1 Služba není zapsána: %1 unregister_service_task_%1 Zrušit zápis '%1' služby service_is_not_registered_%1 Služba není zapsána: %1 ugene-1.9.8/src/corelibs/U2Private/transl/english.ts0000644000175000017500000003025311651544333021040 0ustar ilyailya U2::AddPluginTask Add plugin task: %1 Plugin is already loaded: %1 Plugin %1 depends on %2 which is not loaded Plugin %1 depends on %2 which is available, but the version is too old Plugin loading error: %1, Error string %2 Plugin initialization routine was not found: %1 Plugin initialization failed: %1 U2::DisableServiceTask Disable '%1' service Active top-level task name: %1 Active task was found Service is not registered: %1 Service is not enabled: %1 U2::EnableServiceTask Enable '%1' service Service is already enabled: %1 Circullar service dependency: %1 Required service is not enabled: %1 U2::LoadAllPluginsTask Loading start up plugins File not found: %1 Invalid file format: %1 U2::LogCategories TRACE DETAILS INFO ERROR U2::PluginDescriptorHelper Required attribute not found %1 Required element not found %1 Not valid value: '%1', plugin: %2 Platform arch is unknown: %1 Platform bits is unknown: %1 Invalid depends token: %1 Plugin circular dependency detected: %1 <-> %2 Can't satisfy dependencies for %1 ! U2::RegisterServiceTask Register '%1' service Service is already registered '%1' Illegal service state: %1 Only one service of specified type is allowed: %1 U2::TaskSchedulerImpl New Prepared Running Finished Canceling task: %1 Subtask {%1} is canceled Subtask {%1} is failed: %2 TimeOut Error. TimeOut = %1 sec. Waiting for resource '%1', count: %2 Not enough resources for the task, resource name: '%1' max: %2%3 requested: %4%5 Waiting for resource '%1', count: %2%3 Registering new task: %1 Uregistering task: %1 Invalid name promoting task {%1} to '%2' promoting task {%1} to '%2', error '%3' Starting {%1} task Task {%1} finished with error: %2 Task {%1} canceled Task {%1} finished Deleting task: %1 U2::UnregisterServiceTask Unregister '%1' service Service is not registered: %1 ugene-1.9.8/src/corelibs/U2Test/0000755000175000017500000000000011651544334015037 5ustar ilyailyaugene-1.9.8/src/corelibs/U2Test/U2Test.pri0000644000175000017500000000105711651544334016704 0ustar ilyailya# include (U2Test.pri) UGENE_RELATIVE_DESTDIR = '' MODULE_ID=U2Test include( ../../ugene_lib_common.pri ) QT += xml DEFINES+= QT_FATAL_ASSERT BUILDING_U2TEST_DLL LIBS += -L../../_release -lU2Core !debug_and_release|build_pass { CONFIG(debug, debug|release) { DESTDIR=../../_debug LIBS -= -L../../_release -lU2Core LIBS += -L../../_debug -lU2Cored } CONFIG(release, debug|release) { DESTDIR=../../_release } } unix { target.path = $$UGENE_INSTALL_DIR/$$UGENE_RELATIVE_DESTDIR INSTALLS += target } ugene-1.9.8/src/corelibs/U2Test/src/0000755000175000017500000000000011651544334015626 5ustar ilyailyaugene-1.9.8/src/corelibs/U2Test/src/GTest.cpp0000644000175000017500000002374111651544334017367 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include #include #include #include "GTest.h" namespace U2 { /* TRANSLATOR U2::GTest */ ////////////////////////////////////////////////////////////////////////// // GTest GTest::GTest(const QString& taskName, GTest* cp, const GTestEnvironment* _env, TaskFlags flags, const QList& subtasks) : Task(taskName, flags), contextProvider(cp), env(_env) { assert(env!=NULL); foreach(Task* t, subtasks) { addSubTask(t); } } QObject* GTest::getContext(const QString& name) const { assert(contextProvider != NULL); return contextProvider->subtestsContext.value(name); } void GTest::addContext(const QString& name, QObject* v) { assert(contextProvider != NULL); assert(!contextProvider->subtestsContext.contains(name)); contextProvider->subtestsContext[name] = v; } void GTest::removeContext(const QString& name) { assert(contextProvider != NULL); assert(contextProvider->subtestsContext.contains(name)); contextProvider->subtestsContext.remove(name); } void GTest::failMissingValue( const QString& name) { stateInfo.setError(QString("Mandatory attribute not set: %1").arg(name)); } ////////////////////////////////////////////////////////////////////////// // GTestSuite GTestSuite::~GTestSuite() { qDeleteAll(tests); qDeleteAll(excluded); } static QStringList findAllFiles(const QString& dirPath, const QString& ext, bool recursive, int rec) { QStringList res; if (rec > 100) { //symlink or other err //todo: report err? return res; } QDir dir(dirPath); //add files first QStringList files = ext.isEmpty() ? dir.entryList(QDir::Files) : dir.entryList(ext.split(":"), QDir::Files); foreach(const QString& file, files) { QFileInfo fi(dir.absolutePath() + "/" + file); res.append(fi.absoluteFilePath()); } //process subdirs if needed if (recursive) { QStringList subDirs = dir.entryList(QDir::Dirs | QDir::NoDotAndDotDot); foreach(QString sub, subDirs) { QString subDirPath = dirPath + "/" + sub; QStringList subRes = findAllFiles(subDirPath, ext, true, rec++); res+=subRes; } } return res; } static bool exclude(const QList& xlist, const QString& url) { foreach(const QRegExp& r, xlist) { if (r.exactMatch(url)) { return true; } } return false; } static QString addExcludeTests(const QString & fullTestDirPath, const QString & str, QList & xList) { QString err; if(str.isEmpty()) { return err; } foreach(const QString& s, str.split(",")) { QRegExp r(fullTestDirPath + "/" + s.trimmed(), Qt::CaseSensitive, QRegExp::Wildcard); if (!r.isValid()) { err = QString("Invalid exclude: %1").arg(s); break; } xList << r; } return err; } GTestSuite* GTestSuite::readTestSuite(const QString& url, QString& err) { QFile f(url); if (!f.open(QIODevice::ReadOnly)) { err = ("cant_open_file"); return NULL; } QByteArray xmlData = f.readAll(); f.close(); QDomDocument suiteDoc; bool res = suiteDoc.setContent(xmlData); if (!res) { err = ("not_an_xml_suite_file"); return NULL; } if (suiteDoc.doctype().name()!="UGENE_TEST_FRAMEWORK_SUITE") { err = ("not_a_test_suite_file"); return NULL; } QDomElement suiteEl = suiteDoc.documentElement(); if (suiteEl.tagName()!="suite") { err = ("suite_elem_not_found"); return NULL; } //Name QString suiteName = suiteEl.attribute("name"); if (suiteName.isEmpty()) { err = ("suite_name_is_empty"); return NULL; } //Test timeout QString testTimeout = suiteEl.attribute("test-timeout", "0"); //Env GTestEnvironment suiteEnv; QDomNodeList envNodes = suiteEl.elementsByTagName("env-var"); for(int i=0;i suiteTests; QList excluded; QDomNodeList testDirEls = suiteEl.elementsByTagName("test-dir"); for(int i=0;i xlist; err = addExcludeTests(fullTestDirPath, testDirEl.attribute("exclude"), xlist); if(!err.isEmpty()) { break; } if(sizeof(void*) == 8) { // means that it is 64 bit system err = addExcludeTests(fullTestDirPath, testDirEl.attribute("exclude_64"), xlist); if(!err.isEmpty()) { break; } } QString testFormatName = testDirEl.attribute("test-format"); bool recursive = testDirEl.attribute("recursive") != "false"; QString testExt = testDirEl.attribute("test-ext"); QStringList testURLs = findAllFiles(fullTestDirPath, testExt, recursive, 0); foreach(const QString& tUrl, testURLs) { int shortNameLen = tUrl.length() - fullTestDirPath.length() - 1; // minus '/' char assert(shortNameLen > 0); QString tShortName = tUrl.right(shortNameLen); GTestRef* tref = new GTestRef(tUrl, tShortName, testFormatName); if (exclude(xlist, tUrl)) { excluded << tref; } else { suiteTests << tref; } } } if (!err.isEmpty()) { qDeleteAll(suiteTests); qDeleteAll(excluded); return NULL; } GTestSuite* suite = new GTestSuite(); suite->url = suiteUrl.absoluteFilePath(); suite->name = suiteName; suite->env = suiteEnv; suite->tests = suiteTests; suite->excluded = excluded; // testTimeout format is unchecked, but it will fail to 0 it's ok suite->testTimeout = testTimeout.toInt(); suite->testTimeout = (suite->testTimeout == 0) ? -1 : suite->testTimeout; // -1 means timeout check disabled foreach( GTestRef * r, suiteTests ) { r->setSuite( suite ); } foreach( GTestRef * r, excluded ) { r->setSuite( suite ); } return suite; } QList GTestSuite::readTestSuiteList( const QString& url, QStringList& errs ) { QList result; QFile* suitListFile; suitListFile=new QFile(url); //QString dir = AppContext::getSettings()->getValue(SETTINGS_ROOT + "lastDir", QString()).toString(); QString dir = QFileInfo(url).dir().absolutePath(); if (suitListFile!=NULL){ suitListFile->open(QIODevice::ReadOnly | QIODevice::Text); QString suiteFileContent = suitListFile->readAll(); QStringList suiteNamesList = suiteFileContent.split(QRegExp("\\s+")); QString suiteName; foreach(suiteName,suiteNamesList){ suiteName = suiteName.trimmed(); if (suiteName.startsWith("#")) { //this is a comment line continue; } QFileInfo fifs(dir + "/" + suiteName); QString urlfs = fifs.absoluteFilePath(); QString errt; GTestSuite* ts = GTestSuite::readTestSuite(urlfs, errt); if (ts == NULL) { assert(!errt.isEmpty()); errs << errt; } else { result << ts; } } } return result; } ////////////////////////////////////////////////////////////////////////// // GTestState void GTestState::clearState() { if (state == TriState_Unknown) { assert(errMessage.isEmpty()); return; } errMessage.clear(); state = TriState_Unknown; emit si_stateChanged(this); } void GTestState::setFailed(const QString& err) { if (state == TriState_No) { assert(!errMessage.isEmpty()); return; } assert(!err.isEmpty()); assert(errMessage.isEmpty()); errMessage = err; state = TriState_No; emit si_stateChanged(this); } void GTestState::setPassed() { if (state == TriState_Yes) { assert(errMessage.isEmpty()); return; } errMessage.clear(); state = TriState_Yes; emit si_stateChanged(this); } }//namespace ugene-1.9.8/src/corelibs/U2Test/src/GTestFrameworkComponents.cpp0000644000175000017500000001120111651544334023277 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include #include #include #include #include #include #include "GTestFrameworkComponents.h" #include "xmltest/XMLTestFormat.h" namespace U2 { #define TR_SETTINGS_ROOT QString("test_runner/") GTestFormatRegistry::GTestFormatRegistry() { formats.append(new XMLTestFormat()); } GTestFormatRegistry::~GTestFormatRegistry() { foreach(GTestFormat* f, formats) { delete f; } } bool GTestFormatRegistry::registerTestFormat(GTestFormat* f) { if (formats.contains(f)) { return false; } formats.append(f); return true; } bool GTestFormatRegistry::unregisterTestFormat(GTestFormat* f) { if (!formats.contains(f)) { return false; } formats.removeOne(f); return true; } GTestFormat* GTestFormatRegistry::findFormat(const GTestFormatId& id) { foreach(GTestFormat* f, formats) { if (f->getFormatId() == id) { return f; } } return NULL; } const QString TestFramework::TEST_TIMEOUT_CMD_OPTION = "test-timeout"; bool TestFramework::helpRegistered = false; TestFramework::TestFramework() { if( !helpRegistered && Version::ugeneVersion().isDevVersion) { setTRHelpSections(); } setTestRunnerSettings(); } // all options connected with tests are registered here void TestFramework::setTRHelpSections() { assert( !helpRegistered ); helpRegistered = true; CMDLineRegistry * cmdLineRegistry = AppContext::getCMDLineRegistry(); assert( NULL != cmdLineRegistry ); CMDLineHelpProvider * testTimeoutSection = new CMDLineHelpProvider( TEST_TIMEOUT_CMD_OPTION, GTestFormatRegistry::tr( "Sets timeout for the tests." ), "", // No full description ""); CMDLineHelpProvider *testRunnerThreads = new CMDLineHelpProvider( CMDLineCoreOptions::TEST_THREADS, GTestFormatRegistry::tr( "Sets the number of threads." ), GTestFormatRegistry::tr( "Sets the number of threads in the Test Runner" " that can run at the same time.", "")); CMDLineHelpProvider *testReport = new CMDLineHelpProvider( CMDLineCoreOptions::TEST_REPORT, GTestFormatRegistry::tr("Sets the directory for the test report."), "", // No full description ""); CMDLineHelpProvider * suiteUrlSection = new CMDLineHelpProvider( CMDLineCoreOptions::SUITE_URLS, GTestFormatRegistry::tr( "Loads test suites and runs them." ), "", // No full description " [ ...]"); CMDLineHelpProvider * teamcityOutputSection = new CMDLineHelpProvider( CMDLineCoreOptions::TEAMCITY_OUTPUT, GTestFormatRegistry::tr( "Output a test's messages to the TeamCity system." ), ""); // No full description cmdLineRegistry->registerCMDLineHelpProvider( testRunnerThreads ); cmdLineRegistry->registerCMDLineHelpProvider( testTimeoutSection ); cmdLineRegistry->registerCMDLineHelpProvider( testReport ); cmdLineRegistry->registerCMDLineHelpProvider( suiteUrlSection ); cmdLineRegistry->registerCMDLineHelpProvider( teamcityOutputSection ); } void TestFramework::setTestRunnerSettings() { CMDLineRegistry * cmdLineRegistry = AppContext::getCMDLineRegistry(); assert( NULL != cmdLineRegistry ); Settings * settings = AppContext::getSettings(); assert( NULL != settings ); // TODO: make constants TIME_OUT_VAR and NUM_THREADS int timeOut = cmdLineRegistry->getParameterValue( TEST_TIMEOUT_CMD_OPTION ).toInt(); if (timeOut > 0) { settings->setValue( TR_SETTINGS_ROOT + "TIME_OUT_VAR", QString::number( timeOut ) ); } } }//namespace ugene-1.9.8/src/corelibs/U2Test/src/TestRunnerTask.cpp0000644000175000017500000002130711651544334021271 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "TestRunnerTask.h" #include #include #include #include #include #include namespace U2 { static Logger teamcityLog(ULOG_CAT_TEAMCITY); TestRunnerTask::TestRunnerTask(const QList& tests, const GTestEnvironment* _env, int testSizeToRun) : Task( tr("Test runner"), TaskFlag_NoRun), env(_env) { tpm = Task::Progress_Manual; setMaxParallelSubtasks(testSizeToRun); sizeToRun = testSizeToRun; finishedTests = 0; awaitingTests = tests; totalTests = tests.size(); foreach(GTestState *t,awaitingTests){ t->clearState(); } for (int i=0; !awaitingTests.isEmpty() && i < sizeToRun; i++){ GTestState *t=awaitingTests.takeFirst(); LoadTestTask* lt = new LoadTestTask(t); addSubTask(lt); } } QList TestRunnerTask::onSubTaskFinished(Task* subTask) { //update progress info: progress is a % of finished tests stateInfo.progress = 100 * finishedTests / totalTests; QList res; if(isCanceled()){ return res; } LoadTestTask* loader = qobject_cast(subTask); if (loader == NULL) { GTest* test = qobject_cast(subTask); assert(test); test->cleanup(); GTestState* testState = stateByTest.value(test); assert(testState!=NULL); assert(testState->isNew()); if (test->hasError()) { testState->setFailed(test->getStateInfo().getError()); teamcityLog.info(QString("##teamcity[testStarted name='%1 : %2']").arg(testState->getTestRef()->getSuite()->getName(),testState->getTestRef()->getShortName())); teamcityLog.info(QString("##teamcity[testFailed name='%1 : %2' message='%3' details='%3']").arg(testState->getTestRef()->getSuite()->getName(),testState->getTestRef()->getShortName(),QString(testState->getErrorMessage()).replace("'","|'").replace('\n',' '))); teamcityLog.info(QString("##teamcity[testFinished name='%1 : %2']").arg(testState->getTestRef()->getSuite()->getName(),testState->getTestRef()->getShortName())); } else { testState->setPassed(); teamcityLog.info(QString("##teamcity[testStarted name='%1 : %2']").arg(testState->getTestRef()->getSuite()->getName(),testState->getTestRef()->getShortName())); teamcityLog.info(QString("##teamcity[testFinished name='%1 : %2' duration='%3']").arg(testState->getTestRef()->getSuite()->getName(), testState->getTestRef()->getShortName(),QString::number(GTimer::millisBetween(test->getTimeInfo().startTime, test->getTimeInfo().finishTime)))); } if(!awaitingTests.isEmpty()){ GTestState *t=awaitingTests.takeFirst(); res.append(new LoadTestTask(t)); } } else { finishedTests++; GTestState* testState = loader->testState; if (loader->hasError()) { testState->setFailed(loader->getStateInfo().getError()); teamcityLog.info(QString("##teamcity[testStarted name='%1 : %2']").arg(testState->getTestRef()->getSuite()->getName(),testState->getTestRef()->getShortName())); teamcityLog.info(QString("##teamcity[testFailed name='%1 : %2' message='%3' details='%3']").arg(testState->getTestRef()->getSuite()->getName(),testState->getTestRef()->getShortName(),QString(testState->getErrorMessage()).replace("'","|'").replace('\n',' '))); teamcityLog.info(QString("##teamcity[testFinished name='%1 : %2']").arg(testState->getTestRef()->getSuite()->getName(),testState->getTestRef()->getShortName())); } else { GTestFormatId id = testState->getTestRef()->getFormatId(); GTestFormat* tf = AppContext::getTestFramework()->getTestFormatRegistry()->findFormat(id); if (tf == NULL) { testState->setFailed(tr("Test format not supported: %1").arg(id)); teamcityLog.info(QString("##teamcity[testStarted name='%1 : %2']").arg(testState->getTestRef()->getSuite()->getName(),testState->getTestRef()->getShortName())); teamcityLog.info(QString("##teamcity[testFailed name='%1 : %2' message='%3' details='%3']").arg(testState->getTestRef()->getSuite()->getName(),testState->getTestRef()->getShortName(),QString(testState->getErrorMessage()).replace("'","|'").replace('\n',' ').replace('\n',' '))); teamcityLog.info(QString("##teamcity[testFinished name='%1 : %2']").arg(testState->getTestRef()->getSuite()->getName(),testState->getTestRef()->getShortName())); } else { QString err; GTestEnvironment * newEnv = new GTestEnvironment(); //caching newly created environment. will be deleted in cleanup() mergedSuites.push_back( newEnv ); GTestEnvironment * testParentEnv = testState->getTestRef()->getSuite()->getEnv(); QMap parentVars = testParentEnv->getVars(); QList parentVarsNames = parentVars.keys(); foreach( const QString & parentVar, parentVarsNames ) { newEnv->setVar( parentVar, parentVars[parentVar] ); } //overriding existing variables with global ones QMap globalEnvVars = env->getVars(); foreach( QString var, globalEnvVars.keys() ) { newEnv->setVar( var, globalEnvVars[var] ); } const QString& suiteDir = QFileInfo(testState->getTestRef()->getSuite()->getURL()).absoluteDir().absolutePath(); if (newEnv->getVars().contains("COMMON_DATA_DIR")) { newEnv->setVar("COMMON_DATA_DIR", suiteDir + newEnv->getVar("COMMON_DATA_DIR")); } if (newEnv->getVars().contains("TEMP_DATA_DIR")) { newEnv->setVar("TEMP_DATA_DIR", suiteDir + newEnv->getVar("TEMP_DATA_DIR")); } GTest* test = tf->createTest(testState->getTestRef()->getShortName(), NULL, newEnv, loader->testData, err); int testTimeout = testState->getTestRef()->getSuite()->getTestTimeout(); test->setTimeOut(testTimeout); if (test == NULL) { testState->setFailed(err); teamcityLog.info(QString("##teamcity[testStarted name='%1 : %2']").arg(testState->getTestRef()->getSuite()->getName(),testState->getTestRef()->getShortName())); teamcityLog.info(QString("##teamcity[testFailed name='%1 : %2' message='%3' details='%3']").arg(testState->getTestRef()->getSuite()->getName(),testState->getTestRef()->getShortName(),QString(testState->getErrorMessage()).replace("'","|'").replace('\n',' '))); teamcityLog.info(QString("##teamcity[testFinished name='%1 : %2']").arg(testState->getTestRef()->getSuite()->getName(),testState->getTestRef()->getShortName())); } else { stateByTest[test] = testState; QString var = env->getVar(TIME_OUT_VAR); int timeout = var.toInt(); if (timeout > 0) { test->setTimeOut(timeout); } res.append(test); } } } } return res; } void TestRunnerTask::cleanup() { qDeleteAll( mergedSuites ); mergedSuites.clear(); Task::cleanup(); } LoadTestTask::LoadTestTask(GTestState* _testState) : Task( tr("TestLoader for %1").arg(_testState->getTestRef()->getShortName()), TaskFlag_None), testState(_testState) { } void LoadTestTask::run() { const QString& url = testState->getTestRef()->getURL(); QFile f(url); if (!f.open(QIODevice::ReadOnly)) { stateInfo.setError( tr("Cannot open file: %1").arg(url) ); return; } testData = f.readAll(); f.close(); } } //namespace ugene-1.9.8/src/corelibs/U2Test/src/TestRunnerSettings.h0000644000175000017500000000314011651544334021627 0ustar ilyailya#ifndef _U2_TEST_RUNNER_SETTINGS_H_ #define _U2_TEST_RUNNER_SETTINGS_H_ namespace U2 { class TestRunnerSettings { public: QString getVar(const QString& name) const { return registry.value(name); } void setVar(const QString& name, const QString& val) { registry[name] = val; } void removeVar(const QString& name) { registry.remove(name); } private: QMap registry; }; class APITestData { public: template T getValue(const QString& key) const { const QVariant& val = d.value(key); return qVariantValue(val); } template void addValue(const QString& key, const T& val) { assert(!key.isEmpty()); assert(!d.keys().contains(key)); const QVariant& var = qVariantFromValue(val); d[key] = var; } template QList getList(const QString& key) const { const QVariant& val = d.value(key); if (val.type() != QVariant::List) { return QList(); } const QVariantList& varList = val.toList(); QList list; foreach(const QVariant& var, varList) { list << qVariantValue(var); } return list; } template void addList(const QString& key, const QList& list) { assert(!key.isEmpty()); assert(!d.keys().contains(key)); QVariantList varList; foreach(const T& val, list) { varList << qVariantFromValue(val); } d[key] = varList; } private: QMap d; }; } //namespace #endif ugene-1.9.8/src/corelibs/U2Test/src/TestRunnerTask.h0000644000175000017500000000364411651544334020742 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_TEST_RUNNER_TASK_H_ #define _U2_TEST_RUNNER_TASK_H_ #include #include #include namespace U2 { class GTestEnvironment; class GTestState; class GTest; #define TIME_OUT_VAR "TIME_OUT_VAR" #define ULOG_CAT_TEAMCITY "Teamcity Integration" class U2TEST_EXPORT TestRunnerTask : public Task { Q_OBJECT public: TestRunnerTask(const QList& tests, const GTestEnvironment* env, int testSizeToRun=5); virtual void cleanup(); const QMap& getStateByTestMap() const {return stateByTest;} protected: virtual QList onSubTaskFinished(Task* subTask); QMap stateByTest; const GTestEnvironment* env; int sizeToRun; int finishedTests; int totalTests; QList awaitingTests; QList mergedSuites; }; class U2TEST_EXPORT LoadTestTask : public Task { Q_OBJECT public: LoadTestTask(GTestState* test); void run(); GTestState* testState; QByteArray testData; }; } //namespace #endif ugene-1.9.8/src/corelibs/U2Test/src/xmltest/0000755000175000017500000000000011651544334017326 5ustar ilyailyaugene-1.9.8/src/corelibs/U2Test/src/xmltest/XMLTestFormat.h0000644000175000017500000000401511651544334022150 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_XML_TEST_FORMAT_H_ #define _U2_XML_TEST_FORMAT_H_ #include "../GTest.h" namespace U2 { class XMLTestFormat; class U2TEST_EXPORT XMLTestFactory { public: XMLTestFactory(const QString& _tagName) : tagName(_tagName){} virtual ~XMLTestFactory(); virtual GTest* createTest(XMLTestFormat* tf, const QString& testName, GTest* cp, const GTestEnvironment* env, const QList& subtasks, const QDomElement& el) = 0; const QString& getTagName() const {return tagName;} private: QString tagName; }; class U2TEST_EXPORT XMLTestFormat : public GTestFormat { Q_OBJECT public: XMLTestFormat(); virtual ~XMLTestFormat(); virtual GTest* createTest(const QString& name, GTest* cp, const GTestEnvironment* env, const QByteArray& testData, QString& err); virtual GTest* createTest(const QString& name, GTest* cp, const GTestEnvironment* env, const QDomElement& el, QString& err); virtual bool registerTestFactory(XMLTestFactory* tf); virtual bool unregisterTestFactory(XMLTestFactory* tf); private: void registerBuiltInFactories(); QMap testFactories; }; }//namespace #endif ugene-1.9.8/src/corelibs/U2Test/src/xmltest/XMLTestFormat.cpp0000644000175000017500000000700511651544334022505 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "XMLTestFormat.h" #define TEST_FACTORIES_AUTO_CLEANUP #ifdef TEST_FACTORIES_AUTO_CLEANUP #include #include #endif #include namespace U2 { XMLTestFactory::~XMLTestFactory() { #ifdef TEST_FACTORIES_AUTO_CLEANUP GTestFormatRegistry* tfr = AppContext::getTestFramework()->getTestFormatRegistry(); if (tfr!=NULL) { XMLTestFormat *xmlTestFormat = qobject_cast(tfr->findFormat("XML")); if (xmlTestFormat!=NULL) { xmlTestFormat->unregisterTestFactory(this); } } #endif } XMLTestFormat::XMLTestFormat() : GTestFormat("XML") { registerBuiltInFactories(); } XMLTestFormat::~XMLTestFormat() { foreach(XMLTestFactory* f, testFactories.values()) { delete f; } } GTest* XMLTestFormat::createTest(const QString& name, GTest* cp, const GTestEnvironment* env, const QByteArray& testData, QString& err) { QDomDocument doc; int line = 0; int col = 0; bool res = doc.setContent(testData, &err, &line, &col); if (!res) { err = QString("error_reading_test: ") + err; err+=QString(" line: %1 col: %2").arg(QString::number(line)).arg(QString::number(col)); return NULL; } if (doc.doctype().name()!="UGENE_TEST_FRAMEWORK_TEST") { err = QString("not_a_test_file"); return NULL; } QDomElement testEl = doc.documentElement(); return createTest(name, cp, env, testEl, err); } GTest* XMLTestFormat::createTest(const QString& name, GTest* cp, const GTestEnvironment* env, const QDomElement& el, QString& err) { QString tagName = el.tagName(); XMLTestFactory* f = testFactories.value(tagName); if (f == NULL) { err = QString("XMLTestFactory not found '%1'").arg(tagName); return NULL; } QList subs; GTest* t = f->createTest(this, name, cp, env, subs, el); return t; } bool XMLTestFormat::registerTestFactory(XMLTestFactory* tf) { const QString& tagName = tf->getTagName(); if (testFactories.contains(tagName)) { return false; } testFactories[tagName] = tf; return true; } bool XMLTestFormat::unregisterTestFactory(XMLTestFactory* tf) { const QString& tagName = tf->getTagName(); if (!testFactories.contains(tagName)) { return false; } testFactories.remove(tagName); return true; } void XMLTestFormat::registerBuiltInFactories() { { // multitest QList fs = XMLTestUtils::createTestFactories(); foreach(XMLTestFactory* f, fs) { bool res = registerTestFactory(f); assert(res); Q_UNUSED(res); } } } }//namespace ugene-1.9.8/src/corelibs/U2Test/src/xmltest/XMLTestUtils.h0000644000175000017500000000572411651544334022030 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_XML_TEST_UTILS_ #define _U2_XML_TEST_UTILS_ #include #include "XMLTestFormat.h" namespace U2 { #define SIMPLE_XML_TEST_CONSTRUCT(ClassName, TFlags) \ ClassName(XMLTestFormat* _tf, const QString& _name, GTest* _cp, \ const GTestEnvironment* _env, const QList& _contexts, const QDomElement& _el) \ : GTest(_name, _cp, _env, TFlags, _contexts){init(_tf, _el);} \ #define SIMPLE_XML_TEST_BODY(ClassName, TFlags) \ public:\ SIMPLE_XML_TEST_CONSTRUCT(ClassName, TFlags) \ void init(XMLTestFormat *tf, const QDomElement& el); \ #define SIMPLE_XML_TEST_BODY_WITH_FACTORY_EXT(TestClass, TagName, TFlags) \ SIMPLE_XML_TEST_BODY(TestClass, TFlags) \ class TestClass##Factory : public XMLTestFactory { \ public: \ TestClass##Factory () : XMLTestFactory(TagName) {} \ \ virtual GTest* createTest(XMLTestFormat* tf, const QString& testName, GTest* cp, \ const GTestEnvironment* env, const QList& subtasks, const QDomElement& el) \ { \ return new TestClass(tf, testName, cp, env, subtasks, el); \ }\ };\ \ static XMLTestFactory* createFactory() {return new TestClass##Factory();}\ #define SIMPLE_XML_TEST_BODY_WITH_FACTORY(TestClass, TagName) \ SIMPLE_XML_TEST_BODY_WITH_FACTORY_EXT(TestClass, TagName, TaskFlags_NR_FOSCOE) \ class XMLTestUtils { public: static QList createTestFactories(); }; ////////////////////////////////////////////////////////////////////////// // utility tasks class XMLMultiTest : public GTest { Q_OBJECT public: SIMPLE_XML_TEST_BODY_WITH_FACTORY(XMLMultiTest, "multi-test"); ReportResult report(); }; class GTest_Fail : public GTest { Q_OBJECT public: SIMPLE_XML_TEST_BODY_WITH_FACTORY_EXT(GTest_Fail, "fail", TaskFlag_NoRun); ReportResult report(); private: QString msg; }; class GTest_DeleteTmpFile : public GTest { Q_OBJECT public: SIMPLE_XML_TEST_BODY_WITH_FACTORY_EXT(GTest_DeleteTmpFile, "delete", TaskFlag_NoRun); ReportResult report(); private: QString url; }; } //namespace #endif ugene-1.9.8/src/corelibs/U2Test/src/xmltest/XMLTestUtils.cpp0000644000175000017500000000547411651544334022365 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "XMLTestUtils.h" namespace U2 { QList XMLTestUtils::createTestFactories() { QList res; res.append(XMLMultiTest::createFactory()); res.append(GTest_DeleteTmpFile::createFactory()); res.append(GTest_Fail::createFactory()); return res; } void XMLMultiTest::init(XMLTestFormat *tf, const QDomElement& el) { QDomNodeList subtaskNodes = el.childNodes(); QList subs; for(int i=0;icreateTest(name, this, env, subEl, err); if (!err.isEmpty()) { stateInfo.setError(err); break; } assert(subTest); subs.append(subTest); } if (!hasError()) { foreach(Task* t, subs) { addSubTask(t); } } } Task::ReportResult XMLMultiTest::report() { if (!hasError()) { Task* t = getSubtaskWithErrors(); if (t!=NULL) { stateInfo.setError(t->getError()); } } return ReportResult_Finished; } void GTest_Fail::init(XMLTestFormat*, const QDomElement& el) { msg = el.attribute("msg"); } Task::ReportResult GTest_Fail::report() { stateInfo.setError(QString("Test failed: %1").arg(msg)); return ReportResult_Finished; } void GTest_DeleteTmpFile::init(XMLTestFormat*, const QDomElement& el) { url = el.attribute("file"); if (url.isEmpty()) { failMissingValue("url"); return; } url = env->getVar("TEMP_DATA_DIR") + "/" + url; } Task::ReportResult GTest_DeleteTmpFile::report() { if (!QFile::exists(url)) { stateInfo.setError(QString("TMP file not found: %1").arg(url)); } else if(!QFileInfo(url).isDir()) { QFile::remove(url); } return ReportResult_Finished; } }//namespace ugene-1.9.8/src/corelibs/U2Test/src/GTestFrameworkComponents.h0000644000175000017500000000343511651544334022756 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_TEST_FRAMWORK_COMPONENTS_ #define _U2_TEST_FRAMWORK_COMPONENTS_ #include "GTest.h" namespace U2 { class U2TEST_EXPORT GTestFormatRegistry : public QObject { Q_OBJECT public: GTestFormatRegistry(); ~GTestFormatRegistry(); bool registerTestFormat(GTestFormat* f); bool unregisterTestFormat(GTestFormat* f); QList getFormats() const {return formats;} GTestFormat* findFormat(const GTestFormatId& id); private: QList formats; }; class U2TEST_EXPORT TestFramework { public: static const int TEST_TIMEOUT_DEFAULT = 0; static const QString TEST_TIMEOUT_CMD_OPTION; private: static bool helpRegistered; static void setTRHelpSections(); public: TestFramework(); GTestFormatRegistry* getTestFormatRegistry() {return &formatRegistry;} private: void setTestRunnerSettings(); private: GTestFormatRegistry formatRegistry; }; }//namespace #endif ugene-1.9.8/src/corelibs/U2Test/src/gui_tests/0000755000175000017500000000000011651544334017634 5ustar ilyailyaugene-1.9.8/src/corelibs/U2Test/src/gui_tests/GUITestService.cpp0000644000175000017500000001605311651544334023152 0ustar ilyailya#include "GUITestService.h" #include "GUITestBase.h" #include #include #include #include #include #include namespace U2 { GUITestService::GUITestService(QObject *): Service(Service_GUITesting, tr("GUI test viewer"), tr("Service to support UGENE GUI testing")) { testLauncher = NULL; connect(AppContext::getPluginSupport(), SIGNAL(si_allStartUpPluginsLoaded()), SLOT(sl_registerSevice())); GUITestBase *tb = AppContext::getGUITestBase(); // TestProjectView *test1 = new TestProjectView("E:/Files/_1.003.fa", "E:/Files/_1.002.fa", "3INS chain 3 sequence", "Add object to view test"); // TestTaskView *test2 = new TestTaskView("E:/Files/ecoli.gbk", "Cancel task test"); // ComplexTest *test3 = new ComplexTest("E:/Files/_1.002.fa", "Lock-unlock test"); Test1AboutDialog* test1AboutDialog=new Test1AboutDialog("AboutDialog_test1"); Test2AboutDialog* test2AboutDialog=new Test2AboutDialog("AboutDialog_test2"); Test3AboutDialog* test3AboutDialog=new Test3AboutDialog("AboutDialog_test3"); Test4AboutDialog* test4AboutDialog=new Test4AboutDialog("AboutDialog_test4"); Test5AboutDialog* test5AboutDialog=new Test5AboutDialog("AboutDialog_test5"); /*tb->registerTest(test1); tb->registerTest(test2); tb->registerTest(test3);*/ tb->registerTest(test1AboutDialog); tb->registerTest(test2AboutDialog); tb->registerTest(test3AboutDialog); tb->registerTest(test4AboutDialog); tb->registerTest(test5AboutDialog); // tb->registerTest(new LongTest()); } void GUITestService::sl_registerSevice() { CMDLineRegistry* cmdLine = AppContext::getCMDLineRegistry(); if(cmdLine && cmdLine->hasParameter("gui-test")) { testLauncher = new TestLauncher(); GUITestBase *tb = AppContext::getGUITestBase(); GUITest *t = tb->findTestByName(cmdLine->getParameterValue("gui-test")); if(t) { LaunchTestTask *task = new LaunchTestTask(t); AppContext::getTaskScheduler()->registerTopLevelTask(task); } } else { AppContext::getTaskScheduler()->registerTopLevelTask(AppContext::getServiceRegistry()->registerServiceTask(this)); } } void GUITestService::serviceStateChangedCallback(ServiceState , bool enabledStateChanged) { if (!enabledStateChanged) { return; } if (isEnabled()) { testLauncher = NULL; runTestsAction = new QAction(tr("GUI testing"), this); runTestsAction->setObjectName("action_guitest"); connect(runTestsAction, SIGNAL(triggered()), SLOT(sl_registerTask())); AppContext::getMainWindow()->getTopLevelMenu(MWMENU_TOOLS)->addAction(runTestsAction); } else { assert(runTestsAction!=NULL); delete runTestsAction; runTestsAction = NULL; //delete testLauncher; testLauncher = NULL; } } void GUITestService::sl_registerTask() { testLauncher = new TestLauncher(); AppContext::getTaskScheduler()->registerTopLevelTask(testLauncher); } //Test examples void TestProjectView::execute() { openFile(path1); openFile(path2); if(!isWidgetExists(projectViewName)) { keyClick("left_dock_bar", Qt::Key_1, Qt::AltModifier); waitForWidget(projectViewName, true); } addObjectToView("[s] " + seqName); waitForWidget("ADV_single_sequence_widget_1", true); } void TestProjectView::checkResult() { // QWidget *w1 = findWidgetByName("ADV_single_sequence_widget_0", "_1 3INS chain 2 sequence"); // QWidget *w2 = findWidgetByName("ADV_single_sequence_widget_1", "_1 3INS chain 2 sequence"); /*ADVSingleSequenceWidget * sw1 = qobject_cast(w1); ADVSingleSequenceWidget * sw2 = qobject_cast(w2); QString str1 = sw1->getSequenceObject()->getGObjectName(); QString str2 = sw2->getSequenceObject()->getGObjectName(); if(!(str1 == "3INS chain 2 sequence" && str2 == "3INS chain 3 sequence")) { throw TestException(tr("Not expected result")); }*/ } void TestTaskView::execute() { OpenDocumentTest t(path, "tttt"); t.launch(); if(!isWidgetExists(taskViewWidgetName)) { keyClick("bottom_dock_bar", Qt::Key_2, Qt::AltModifier); waitForWidget("bottom_dock_bar", true); } waitForTreeItem("Open project/document", taskViewWidgetName, true); cancelTask("Open project/document"); waitForTreeItem("Open project/document", taskViewWidgetName, false); } void TestTaskView::checkResult() { if(isItemExists("Open project/document", taskViewWidgetName)) { throw TestException(tr("Not expected result")); } } void LockDocumentTest::execute(){ QPoint pos = getItemPosition(document, projectViewName); moveTo(projectViewName, pos); mouseClickOnItem(projectViewName, Qt::LeftButton, pos); contextMenuOnItem(projectViewName, pos); waitForMenuWithAction("Lock document for editing"); clickContextMenu("Lock document for editing"); sleep(50); } void LockDocumentTest::checkResult() { QTreeWidget * projectTree = static_cast(findWidgetByName(projectViewName)); QList items = projectTree->findItems(document, Qt::MatchRecursive | Qt::MatchExactly); if(!items.isEmpty()) { ProjViewDocumentItem *docItem = static_cast(items.first()); if(!docItem->doc->isStateLocked()) { throw TestException(tr("Document %1 not locked").arg(document)); } } else { throw TestException(tr("Not expected result")); } } void UnlockDocumentTest::execute(){ QPoint pos = getItemPosition(document, projectViewName); moveTo(projectViewName, pos); mouseClickOnItem(projectViewName, Qt::LeftButton, pos); contextMenuOnItem(projectViewName, pos); waitForMenuWithAction("Unlock document for editing"); clickContextMenu("Unlock document for editing"); sleep(50); } void UnlockDocumentTest::checkResult() { QTreeWidget * projectTree = static_cast(findWidgetByName(projectViewName)); QList items = projectTree->findItems(document, Qt::MatchRecursive | Qt::MatchExactly); if(!items.isEmpty()) { ProjViewDocumentItem *docItem = static_cast(items.first()); if(docItem->doc->isStateLocked()) { throw TestException(tr("Document %1 not locked").arg(document)); } } else { throw TestException(tr("Not expected result")); } } void ComplexTest::execute() { openFile(path); sleep(1000); if(!isWidgetExists(projectViewName)) { keyClick("left_dock_bar", Qt::Key_1, Qt::AltModifier); waitForWidget("left_dock_bar", true); } LockDocumentTest lock(path.split("/").last(), "lock"); UnlockDocumentTest unlock(path.split("/").last(), "unlock"); lock.launch(); unlock.launch(); } } ugene-1.9.8/src/corelibs/U2Test/src/gui_tests/GUITests.h0000644000175000017500000001254611651544334021464 0ustar ilyailya#ifndef _U2_GUI_TESTS_H_ #define _U2_GUI_TESTS_H_ #include #include #include #include #include //#include namespace U2 { class U2TEST_EXPORT TestStatus { public: TestStatus(): error(false), errorString("") {} bool hasError() const { return error; } QString getError() const { return errorString; } void setError(const QString &_error) { error = true; errorString = _error; } private: bool error; QString errorString; }; struct TestException { TestException(const QString &_msg = ""): msg(_msg) {} QString msg; }; class U2TEST_EXPORT GUITest: public QObject{ Q_OBJECT public: GUITest(const QString &_name): QObject(NULL), name(_name) { //parent must bu NULL to push object to main thread connect(this, SIGNAL(runTask(Task*)),this, SLOT(sl_runTask(Task*)), Qt::BlockingQueuedConnection); } void launch(); virtual void execute() = 0; virtual void checkResult() = 0; bool isSuccessful() const {return !ts.hasError();} QString getError() const {return ts.getError();} void setError(const QString &error) {ts.setError(error);} QString getName() const {return name;} protected: //mouse primitives void moveTo(const QString &widgetName, const QPoint &pos = QPoint()); void mouseClick(const QString &widgetName, Qt::MouseButton button, const QPoint &pos = QPoint()); void mouseDbClick(const QString &widgetName, const QPoint &pos = QPoint()); void mousePress(const QString &widgetName, Qt::MouseButton button,const QPoint &pos = QPoint()); void mouseRelease(const QString &widgetName, Qt::MouseButton button, const QPoint &pos = QPoint()); void mouseClick(QWidget *w, Qt::MouseButton button, const QPoint &pos = QPoint()); void mouseDbClick(QWidget *w, const QPoint &pos = QPoint()); void mousePress(QWidget *w, Qt::MouseButton button, const QPoint &pos = QPoint()); void mouseRelease(QWidget *w, Qt::MouseButton button, const QPoint &pos = QPoint()); //keyboard Qt::Key asciiToKey(char ascii); void keyPress(const QString &widgetName, int key, Qt::KeyboardModifiers modifiers = 0, const QString &text = ""); void keyRelease(const QString &widgetName, int key, Qt::KeyboardModifiers modifiers = 0); void keyClick(const QString &widgetName, int key, Qt::KeyboardModifiers modifiers = 0, const QString &text = ""); void keySequence(const QString &widgetName, const QString &sequence, Qt::KeyboardModifiers modifiers = 0); void keyPress(QWidget *w, int key, Qt::KeyboardModifiers modifiers = 0, const QString &text = ""); void keyRelease(QWidget *w, int key, Qt::KeyboardModifiers modifiers = 0); void keyClick(QWidget *w, int key, Qt::KeyboardModifiers modifiers = 0, const QString &text = ""); void keySequence(QWidget *w, const QString &sequence, Qt::KeyboardModifiers modifiers = 0); //menu void expandTopLevelMenu(const QString &menuName, const QString &parentMenu); void clickMenu(const QString &menuName, const QString &parentMenu); void clickContextMenu(const QString &menuName); void contextMenu(const QString &widgetName, const QPoint &pos = QPoint()); //tree model void mouseClickOnItem(const QString &widgetName, Qt::MouseButton button, const QPoint &pos = QPoint()); void mouseDbClickOnItem(const QString &widgetName, const QPoint &pos = QPoint()); void mousePressOnItem(const QString &widgetName, Qt::MouseButton button, const QPoint &pos = QPoint()); void mouseReleaseOnItem(const QString &widgetName, Qt::MouseButton button, const QPoint &pos = QPoint()); void contextMenuOnItem(const QString &widgetName, const QPoint &pos = QPoint()); QPoint getItemPosition(const QString &itemName, const QString &treeName); bool isItemExists(const QString &itemName, const QString &treeName); void expandTreeItem(const QString &itemName, const QString &treeName); QWidget *findWidgetByName(const QString &widgetName, const QString &parentName = "") const; QWidget *findWidgetByTitle(const QString &widgetTitle) const; bool isWidgetExists(const QString &widgetName) const; QMenu *getContextMenu() const {return static_cast(QApplication::activePopupWidget());} QDialog *getActiveDialog() const {return static_cast(QApplication::activeModalWidget());} QWidget *getWidgetInFocus() const {return QApplication::focusWidget();} void sendEvent(QObject *obj, QEvent *e); void sleep(int msec); //functions for wait result bool waitForWidget(const QString& widgetName, bool show); bool waitForTreeItem(const QString &itemName, const QString &treeName, bool show); bool waitForMenuWithAction(const QString &actionName); bool waitForTask(Task *t); protected: TestStatus ts; signals: void runTask(Task *t); private slots: void sl_runTask(Task *t); void sl_eventProcessed(QEvent *e) { if(e == sentEvent) { waitForEvent = true; } } private: QString name; bool waitForEvent; QEvent *sentEvent; class Waiter: public QThread { public: static void await(int mseconds) { msleep(mseconds); } }; }; } //U2 #endif ugene-1.9.8/src/corelibs/U2Test/src/gui_tests/GUITestLauncher.h0000644000175000017500000000162111651544334022753 0ustar ilyailya#ifndef _U2_GUI_TESTS_LAUNCHER_H_ #define _U2_GUI_TESTS_LAUNCHER_H_ #include #include #include #include #include #include "GUITests.h" #include "ProjectViewTests.h" namespace U2 { class LaunchTestTask: public Task { Q_OBJECT public: LaunchTestTask(GUITest* _t):Task(tr("Launch test"), TaskFlags_FOSCOE), t(_t) {} void prepare(); void run(); ReportResult report(); private: GUITest *t; }; class TestLauncher: public Task { Q_OBJECT public: TestLauncher(): Task("gui_test_launcher", TaskFlags(TaskFlag_ReportingIsSupported) | TaskFlag_ReportingIsEnabled), testToLaunch(NULL) {} void run(); QString generateReport() const; private: QList tests; GUITest* testToLaunch; QMap results; }; } #endif ugene-1.9.8/src/corelibs/U2Test/src/gui_tests/GUITestBase.h0000644000175000017500000000130111651544334022057 0ustar ilyailya#ifndef _U2_GUI_TEST_BASE_H_ #define _U2_GUI_TEST_BASE_H_ #include "GUITests.h" #include #include #include #include #include #include #include #include namespace U2 { class U2TEST_EXPORT GUITestBase { public: ~GUITestBase() { foreach(GUITest* t, tests.values()) { delete t; } } bool registerTest(GUITest *t); GUITest *findTestByName(const QString &name); QList getTests(); private: QMap tests; }; } #endif ugene-1.9.8/src/corelibs/U2Test/src/gui_tests/GUITests.cpp0000644000175000017500000005547711651544334022031 0ustar ilyailya#include "GUITests.h" #include namespace U2 { #define WAIT_TIMEOUT 2000 void GUITest::launch(){ moveToThread(QApplication::instance()->thread()); execute(); checkResult(); } QWidget* GUITest::findWidgetByName(const QString &widgetName, const QString &parentName) const { QMainWindow *mw = AppContext::getMainWindow()->getQMainWindow(); QWidget *w = NULL; if(parentName.isEmpty()) { w= mw->findChild(widgetName); } else { QWidget *parent = mw->findChild(parentName); if(parent) { w = parent->findChild(widgetName); } } if(!w) { TestException t(tr("Widget %1 not found").arg(widgetName)); throw t; } return w; } bool GUITest::isWidgetExists(const QString &widgetName) const { QMainWindow *mw = AppContext::getMainWindow()->getQMainWindow(); if(mw) { QWidget *w = mw->findChild(widgetName); return (w != NULL && w->isVisible()); } else { throw TestException(tr("No main window")); } } QWidget* GUITest::findWidgetByTitle(const QString &title) const { QMainWindow *mw = AppContext::getMainWindow()->getQMainWindow(); QListwList = mw->findChildren(); foreach(QWidget *w, wList) { QString t = w->windowTitle(); if(w->windowTitle() == title) { return w; } } throw TestException(tr("Widget %1 not found").arg(title)); } void GUITest::moveTo(const QString &widgetName, const QPoint &_pos) { QWidget * w = findWidgetByName(widgetName); assert(w != NULL); if(!w->isVisible()) { return; } QPoint pos = _pos; if(pos.isNull()) { pos = w->rect().center(); } QPoint begin = QCursor::pos(); QPoint end = w->mapToGlobal(pos); QCursor::setPos(end); return; float k = (float)(end.ry() - begin.ry())/(end.rx() - begin.rx()); float b = begin.ry() - k * begin.rx(); int x1 = begin.rx(); int x2 = end.rx(); if(x1 < x2) { for(int i = x1; i <= x2; i++) { int y = k*i + b; sleep(10); QCursor::setPos(i, y); } } else { for(int i = x1; i >= x2; i--) { int y = k*i + b; sleep(10); QCursor::setPos(i, y); } } } void GUITest::mousePress(const QString &widgetName, Qt::MouseButton button, const QPoint &_pos) { QWidget * w = findWidgetByName(widgetName); QPoint pos = _pos; if(pos.isNull()) { pos = w->rect().center(); } QMouseEvent *me = new QMouseEvent(QEvent::MouseButtonPress, pos, button, button, 0); sendEvent(w, me); } void GUITest::mouseRelease(const QString &widgetName, Qt::MouseButton button, const QPoint &_pos) { QWidget * w = findWidgetByName(widgetName); QPoint pos = _pos; if(pos.isNull()) { pos = w->rect().center(); } QMouseEvent *me = new QMouseEvent(QEvent::MouseButtonRelease, pos, button, button, 0); sendEvent(w, me); } void GUITest::mouseClick(const QString &widgetName, Qt::MouseButton button, const QPoint &_pos) { mousePress(widgetName, button, _pos); mouseRelease(widgetName, button, _pos); } void GUITest::mouseDbClick(const QString &widgetName, const QPoint &_pos) { QWidget * w = findWidgetByName(widgetName); QPoint pos = _pos; if(pos.isNull()) { pos = w->rect().center(); } QMouseEvent *me = new QMouseEvent(QEvent::MouseButtonDblClick, pos, Qt::LeftButton, Qt::LeftButton, 0); sendEvent(w, me); } void GUITest::keyPress(const QString &widgetName, int key, Qt::KeyboardModifiers modifiers, const QString &text) { QWidget *w = findWidgetByName(widgetName); QKeyEvent *ke = new QKeyEvent(QEvent::KeyPress, key, modifiers, text); sendEvent(w, ke); } void GUITest::keyRelease(const QString &widgetName, int key, Qt::KeyboardModifiers modifiers) { QWidget *w = findWidgetByName(widgetName); QKeyEvent *ke = new QKeyEvent(QEvent::KeyRelease, key, modifiers); sendEvent(w, ke); //QCoreApplication::postEvent(w, ke); //QCoreApplication::processEvents(); } void GUITest::keyClick(const QString &widgetName, int key, Qt::KeyboardModifiers modifiers, const QString &text) { keyPress(widgetName, key, modifiers, text); keyRelease(widgetName, key, modifiers); } void GUITest::mousePress(QWidget *w, Qt::MouseButton button, const QPoint &_pos) { if(w == NULL) { throw TestException(tr("widget is NULL")); } QPoint pos = _pos; if(pos.isNull()) { pos = w->rect().center(); } QMouseEvent *me = new QMouseEvent(QEvent::MouseButtonPress, pos, button, button, 0); sendEvent(w, me); } void GUITest::mouseRelease(QWidget *w, Qt::MouseButton button, const QPoint &_pos) { if(w == NULL) { throw TestException(tr("widget is NULL")); } QPoint pos = _pos; if(pos.isNull()) { pos = w->rect().center(); } QMouseEvent *me = new QMouseEvent(QEvent::MouseButtonRelease, pos, button, button, 0); sendEvent(w, me); } void GUITest::mouseClick(QWidget *w, Qt::MouseButton button, const QPoint &_pos) { mousePress(w, button, _pos); mouseRelease(w, button, _pos); } void GUITest::mouseDbClick(QWidget *w, const QPoint &_pos) { if(w == NULL) { throw TestException(tr("widget is NULL")); } QPoint pos = _pos; if(pos.isNull()) { pos = w->rect().center(); } QMouseEvent *me = new QMouseEvent(QEvent::MouseButtonDblClick, pos, Qt::LeftButton, Qt::LeftButton, 0); sendEvent(w, me); } void GUITest::keyPress(QWidget *w, int key, Qt::KeyboardModifiers modifiers, const QString &text) { if(w == NULL) { throw TestException(tr("widget is NULL")); } QKeyEvent *ke = new QKeyEvent(QEvent::KeyPress, key, modifiers, text); sendEvent(w, ke); /*QCoreApplication::postEvent(w, ke); QCoreApplication::processEvents();*/ } void GUITest::keyRelease(QWidget *w, int key, Qt::KeyboardModifiers modifiers) { if(w == NULL) { throw TestException(tr("widget is NULL")); } QKeyEvent *ke = new QKeyEvent(QEvent::KeyRelease, key, modifiers); sendEvent(w, ke); /*QCoreApplication::postEvent(w, ke); QCoreApplication::processEvents();*/ } void GUITest::keyClick(QWidget *w, int key, Qt::KeyboardModifiers modifiers, const QString &text) { keyPress(w, key, modifiers, text); keyRelease(w, key, modifiers); } Qt::Key GUITest::asciiToKey(char ascii) { // = asciiToKey(char ascii) from QTest switch ((unsigned char)ascii) { case 0x08: return Qt::Key_Backspace; case 0x09: return Qt::Key_Tab; case 0x0b: return Qt::Key_Backtab; case 0x0d: return Qt::Key_Return; case 0x1b: return Qt::Key_Escape; case 0x20: return Qt::Key_Space; case 0x21: return Qt::Key_Exclam; case 0x22: return Qt::Key_QuoteDbl; case 0x23: return Qt::Key_NumberSign; case 0x24: return Qt::Key_Dollar; case 0x25: return Qt::Key_Percent; case 0x26: return Qt::Key_Ampersand; case 0x27: return Qt::Key_Apostrophe; case 0x28: return Qt::Key_ParenLeft; case 0x29: return Qt::Key_ParenRight; case 0x2a: return Qt::Key_Asterisk; case 0x2b: return Qt::Key_Plus; case 0x2c: return Qt::Key_Comma; case 0x2d: return Qt::Key_Minus; case 0x2e: return Qt::Key_Period; case 0x2f: return Qt::Key_Slash; case 0x30: return Qt::Key_0; case 0x31: return Qt::Key_1; case 0x32: return Qt::Key_2; case 0x33: return Qt::Key_3; case 0x34: return Qt::Key_4; case 0x35: return Qt::Key_5; case 0x36: return Qt::Key_6; case 0x37: return Qt::Key_7; case 0x38: return Qt::Key_8; case 0x39: return Qt::Key_9; case 0x3a: return Qt::Key_Colon; case 0x3b: return Qt::Key_Semicolon; case 0x3c: return Qt::Key_Less; case 0x3d: return Qt::Key_Equal; case 0x3e: return Qt::Key_Greater; case 0x3f: return Qt::Key_Question; case 0x40: return Qt::Key_At; case 0x41: return Qt::Key_A; case 0x42: return Qt::Key_B; case 0x43: return Qt::Key_C; case 0x44: return Qt::Key_D; case 0x45: return Qt::Key_E; case 0x46: return Qt::Key_F; case 0x47: return Qt::Key_G; case 0x48: return Qt::Key_H; case 0x49: return Qt::Key_I; case 0x4a: return Qt::Key_J; case 0x4b: return Qt::Key_K; case 0x4c: return Qt::Key_L; case 0x4d: return Qt::Key_M; case 0x4e: return Qt::Key_N; case 0x4f: return Qt::Key_O; case 0x50: return Qt::Key_P; case 0x51: return Qt::Key_Q; case 0x52: return Qt::Key_R; case 0x53: return Qt::Key_S; case 0x54: return Qt::Key_T; case 0x55: return Qt::Key_U; case 0x56: return Qt::Key_V; case 0x57: return Qt::Key_W; case 0x58: return Qt::Key_X; case 0x59: return Qt::Key_Y; case 0x5a: return Qt::Key_Z; case 0x5b: return Qt::Key_BracketLeft; case 0x5c: return Qt::Key_Backslash; case 0x5d: return Qt::Key_BracketRight; case 0x5e: return Qt::Key_AsciiCircum; case 0x5f: return Qt::Key_Underscore; case 0x60: return Qt::Key_QuoteLeft; case 0x61: return Qt::Key_A; case 0x62: return Qt::Key_B; case 0x63: return Qt::Key_C; case 0x64: return Qt::Key_D; case 0x65: return Qt::Key_E; case 0x66: return Qt::Key_F; case 0x67: return Qt::Key_G; case 0x68: return Qt::Key_H; case 0x69: return Qt::Key_I; case 0x6a: return Qt::Key_J; case 0x6b: return Qt::Key_K; case 0x6c: return Qt::Key_L; case 0x6d: return Qt::Key_M; case 0x6e: return Qt::Key_N; case 0x6f: return Qt::Key_O; case 0x70: return Qt::Key_P; case 0x71: return Qt::Key_Q; case 0x72: return Qt::Key_R; case 0x73: return Qt::Key_S; case 0x74: return Qt::Key_T; case 0x75: return Qt::Key_U; case 0x76: return Qt::Key_V; case 0x77: return Qt::Key_W; case 0x78: return Qt::Key_X; case 0x79: return Qt::Key_Y; case 0x7a: return Qt::Key_Z; case 0x7b: return Qt::Key_BraceLeft; case 0x7c: return Qt::Key_Bar; case 0x7d: return Qt::Key_BraceRight; case 0x7e: return Qt::Key_AsciiTilde; // Latin 1 codes adapted from X: keysymdef.h,v 1.21 94/08/28 16:17:06 case 0xa0: return Qt::Key_nobreakspace; case 0xa1: return Qt::Key_exclamdown; case 0xa2: return Qt::Key_cent; case 0xa3: return Qt::Key_sterling; case 0xa4: return Qt::Key_currency; case 0xa5: return Qt::Key_yen; case 0xa6: return Qt::Key_brokenbar; case 0xa7: return Qt::Key_section; case 0xa8: return Qt::Key_diaeresis; case 0xa9: return Qt::Key_copyright; case 0xaa: return Qt::Key_ordfeminine; case 0xab: return Qt::Key_guillemotleft; case 0xac: return Qt::Key_notsign; case 0xad: return Qt::Key_hyphen; case 0xae: return Qt::Key_registered; case 0xaf: return Qt::Key_macron; case 0xb0: return Qt::Key_degree; case 0xb1: return Qt::Key_plusminus; case 0xb2: return Qt::Key_twosuperior; case 0xb3: return Qt::Key_threesuperior; case 0xb4: return Qt::Key_acute; case 0xb5: return Qt::Key_mu; case 0xb6: return Qt::Key_paragraph; case 0xb7: return Qt::Key_periodcentered; case 0xb8: return Qt::Key_cedilla; case 0xb9: return Qt::Key_onesuperior; case 0xba: return Qt::Key_masculine; case 0xbb: return Qt::Key_guillemotright; case 0xbc: return Qt::Key_onequarter; case 0xbd: return Qt::Key_onehalf; case 0xbe: return Qt::Key_threequarters; case 0xbf: return Qt::Key_questiondown; case 0xc0: return Qt::Key_Agrave; case 0xc1: return Qt::Key_Aacute; case 0xc2: return Qt::Key_Acircumflex; case 0xc3: return Qt::Key_Atilde; case 0xc4: return Qt::Key_Adiaeresis; case 0xc5: return Qt::Key_Aring; case 0xc6: return Qt::Key_AE; case 0xc7: return Qt::Key_Ccedilla; case 0xc8: return Qt::Key_Egrave; case 0xc9: return Qt::Key_Eacute; case 0xca: return Qt::Key_Ecircumflex; case 0xcb: return Qt::Key_Ediaeresis; case 0xcc: return Qt::Key_Igrave; case 0xcd: return Qt::Key_Iacute; case 0xce: return Qt::Key_Icircumflex; case 0xcf: return Qt::Key_Idiaeresis; case 0xd0: return Qt::Key_ETH; case 0xd1: return Qt::Key_Ntilde; case 0xd2: return Qt::Key_Ograve; case 0xd3: return Qt::Key_Oacute; case 0xd4: return Qt::Key_Ocircumflex; case 0xd5: return Qt::Key_Otilde; case 0xd6: return Qt::Key_Odiaeresis; case 0xd7: return Qt::Key_multiply; case 0xd8: return Qt::Key_Ooblique; case 0xd9: return Qt::Key_Ugrave; case 0xda: return Qt::Key_Uacute; case 0xdb: return Qt::Key_Ucircumflex; case 0xdc: return Qt::Key_Udiaeresis; case 0xdd: return Qt::Key_Yacute; case 0xde: return Qt::Key_THORN; case 0xdf: return Qt::Key_ssharp; case 0xe5: return Qt::Key_Aring; case 0xe6: return Qt::Key_AE; case 0xf7: return Qt::Key_division; case 0xf8: return Qt::Key_Ooblique; case 0xff: return Qt::Key_ydiaeresis; default: assert(false); return Qt::Key(0); } } void GUITest::keySequence(const QString &widgetName, const QString &sequence, Qt::KeyboardModifiers modifiers) { for(int i = 0; i< sequence.length();i++) { keyClick(widgetName, asciiToKey(sequence.at(i).toLatin1()), modifiers, QString(sequence.at(i).toLatin1())); } } void GUITest::keySequence(QWidget *w, const QString &sequence, Qt::KeyboardModifiers modifiers) { for(int i = 0; i< sequence.length();i++) { keyClick(w, asciiToKey(sequence.at(i).toLatin1()), modifiers, QString(sequence.at(i).toLatin1())); } } void GUITest::expandTopLevelMenu(const QString &menuName, const QString &parentMenu) { QMenuBar *parMenu = static_cast(findWidgetByName(parentMenu)); if(!parMenu->isVisible()) { return; } QMainWindow *mw = AppContext::getMainWindow()->getQMainWindow(); QAction *curAction = mw->findChild(menuName); /*QList actions = parMenu->actions(); QAction *curAction = NULL; foreach(QAction *a, actions) { if(a->text() == menuName) { curAction = a; break; } }*/ if(!curAction) { throw TestException(tr("Can't find action %1").arg(menuName)); } QPoint pos = parMenu->actionGeometry(curAction).center(); moveTo(parentMenu, pos); mouseClick(parentMenu, Qt::LeftButton, pos); } void GUITest::clickMenu(const QString &menuName, const QString &parentMenu) { QMenu* parMenu; parMenu = (QMenu*)findWidgetByName(parentMenu); if(parMenu == NULL) { throw TestException(tr("Menu %1 not found").arg(parentMenu)); } QMainWindow *mw = AppContext::getMainWindow()->getQMainWindow(); QAction *curAction = mw->findChild(menuName); /* QList actions = parMenu->actions(); QAction *curAction = NULL; foreach(QAction *a, actions) { if(a->text() == menuName) { curAction = a; break; } }*/ if(!curAction) { throw TestException(tr("Can't find action %1").arg(menuName)); } QPoint pos = parMenu->actionGeometry(curAction).center(); moveTo(parentMenu, pos); mouseClick(parentMenu, Qt::LeftButton, pos); } void GUITest::clickContextMenu(const QString &menuName) { QMenu* parMenu; parMenu = getContextMenu(); if(parMenu == NULL) { throw TestException(tr("Context menu not found")); } QList actions = parMenu->actions(); QAction *curAction = NULL; foreach(QAction *a, actions) { if(a->text() == menuName) { curAction = a; break; } } if(!curAction) { throw TestException(tr("Can't find action %1").arg(menuName)); } QPoint pos = parMenu->actionGeometry(curAction).center(); QCursor::setPos(parMenu->mapToGlobal(pos)); QMouseEvent *me = new QMouseEvent(QEvent::MouseButtonPress, pos, Qt::LeftButton, Qt::LeftButton, 0); sendEvent(parMenu, me); QMouseEvent *me1 = new QMouseEvent(QEvent::MouseButtonRelease, pos, Qt::LeftButton, Qt::LeftButton, 0); sendEvent(parMenu, me1); } void GUITest::contextMenu(const QString &widgetName, const QPoint &_pos) { QWidget * w = findWidgetByName(widgetName); QPoint pos = _pos; if(pos.isNull()) { pos = w->rect().center(); } QContextMenuEvent *cme = new QContextMenuEvent(QContextMenuEvent::Mouse, pos); //mousePress(widgetName, Qt::RightButton, pos); //Select item in tree sendEvent(w, cme); while(getContextMenu() == NULL) { sleep(1); } } void GUITest::sendEvent(QObject *obj, QEvent *e) { // if(res == ResultNone) { e->setAccepted(true); QCoreApplication::postEvent(obj, e); QCoreApplication::processEvents(); /*int count = 0; while(e->isAccepted() && count < WAIT_TIMEOUT) { sleep(1); count++; } if(count < WAIT_TIMEOUT) { coreLog.info("event processed"); }*/ /* } else { waitForEvent = false; sentEvent = e; connect(QApplication::instance(), SIGNAL(si_eventProcessed(QEvent*)), SLOT(sl_eventProcessed(QEvent*))); QCoreApplication::postEvent(obj, e); QCoreApplication::processEvents(); int counter = 0; while(!waitForEvent && counter < WAIT_TIMEOUT) { sleep(1); counter++; } disconnect(QApplication::instance(), SIGNAL(si_eventProcessed(QEvent*)), this, SLOT(sl_eventProcessed(QEvent*))); if(counter >= WAIT_TIMEOUT) { throw TestException(tr("Can't wait for result")); } }*/ } void GUITest::sleep( int msec ){ Waiter::await(msec); } void GUITest::mousePressOnItem(const QString &widgetName, Qt::MouseButton button, const QPoint &_pos) { QTreeView * w = static_cast(findWidgetByName(widgetName)); QPoint pos = _pos; if(pos.isNull()) { pos = w->rect().center(); } QMouseEvent *me = new QMouseEvent(QEvent::MouseButtonPress, pos, button, button, 0); sendEvent(w->viewport(), me); } void GUITest::mouseReleaseOnItem(const QString &widgetName, Qt::MouseButton button, const QPoint &_pos) { QTreeView * w = static_cast(findWidgetByName(widgetName)); QPoint pos = _pos; if(pos.isNull()) { pos = w->rect().center(); } QMouseEvent *me = new QMouseEvent(QEvent::MouseButtonRelease, pos, button, button, 0); sendEvent(w->viewport(), me); } void GUITest::mouseClickOnItem(const QString &widgetName, Qt::MouseButton button, const QPoint &_pos) { mousePressOnItem(widgetName, button, _pos); mouseReleaseOnItem(widgetName, button, _pos); } void GUITest::mouseDbClickOnItem(const QString &widgetName, const QPoint &_pos) { QTreeView * w = static_cast(findWidgetByName(widgetName)); QPoint pos = _pos; if(pos.isNull()) { pos = w->rect().center(); } QMouseEvent *me = new QMouseEvent(QEvent::MouseButtonDblClick, pos, Qt::LeftButton, Qt::LeftButton, 0); sendEvent(w->viewport(), me); } void GUITest::contextMenuOnItem(const QString &widgetName, const QPoint &_pos) { QTreeView * w = static_cast(findWidgetByName(widgetName)); QPoint pos = _pos; if(pos.isNull()) { pos = w->rect().center(); } QContextMenuEvent *cme = new QContextMenuEvent(QContextMenuEvent::Mouse, pos); //mousePressOnItem(widgetName, Qt::LeftButton, pos); //Select item in tree sendEvent(w->viewport(), cme); while(getContextMenu() == NULL) { sleep(1); } } QPoint GUITest::getItemPosition(const QString &itemName, const QString &treeName) { QTreeWidget *tree = static_cast(findWidgetByName(treeName)); if(tree->findItems(itemName, Qt::MatchExactly | Qt::MatchRecursive).isEmpty()) { throw TestException(tr("Item %1 not found").arg(itemName)); } QTreeWidgetItem *item = tree->findItems(itemName, Qt::MatchExactly | Qt::MatchRecursive).first(); if(!item) { return QPoint(); } return tree->visualItemRect(item).center(); } bool GUITest::isItemExists(const QString &itemName, const QString &treeName) { QTreeWidget *tree = static_cast(findWidgetByName(treeName)); if(tree->findItems(itemName, Qt::MatchExactly | Qt::MatchRecursive).isEmpty()) { return false; } return true; } void GUITest::sl_runTask(Task *t) { AppContext::getTaskScheduler()->registerTopLevelTask(t); } void GUITest::expandTreeItem( const QString &itemName, const QString &treeName){ QTreeWidget *tree = static_cast(findWidgetByName(treeName)); if(tree->findItems(itemName, Qt::MatchExactly | Qt::MatchRecursive).isEmpty()) { throw TestException(tr("Item %1 not found").arg(itemName)); } QTreeWidgetItem *item = tree->findItems(itemName, Qt::MatchExactly | Qt::MatchRecursive).first(); QPoint pos = tree->visualItemRect(item).topLeft(); moveTo(treeName, pos); mouseClickOnItem(treeName, Qt::LeftButton, pos); keyClick(tree->viewport()->objectName(), Qt::Key_Direction_R); } bool GUITest::waitForWidget( const QString& widgetName, bool show ){ int count = 0; bool visible = false; do { if(isWidgetExists(widgetName)) { visible = findWidgetByName(widgetName)->isVisible(); } else { visible = false; } sleep(1); count++; } while(/*isWidgetExists(widgetName) != show && */visible != show && count < WAIT_TIMEOUT); return count < WAIT_TIMEOUT; } bool GUITest::waitForTreeItem( const QString& itemName, const QString& treeName, bool show ){ int count = 0; do { sleep(1); count++; } while(isItemExists(itemName, treeName) != show && count < WAIT_TIMEOUT); return count < WAIT_TIMEOUT; } bool GUITest::waitForMenuWithAction(const QString &actionName) { int count = 0; bool fl = false; while(!fl && count < WAIT_TIMEOUT){ QMenu* menu = getContextMenu(); if(menu) { QList actions = menu->actions(); foreach(QAction *a, actions) { coreLog.info(a->text()); if(a->text() == actionName) { fl = true; break; } } } sleep(1); count++; } return count < WAIT_TIMEOUT; } bool GUITest::waitForTask( Task *t ){ int count = 0; while(!t->isRunning() && count < WAIT_TIMEOUT) { //count++; sleep(1); } return count < WAIT_TIMEOUT; } } ugene-1.9.8/src/corelibs/U2Test/src/gui_tests/GUITestBase.cpp0000644000175000017500000000103411651544334022415 0ustar ilyailya#include "GUITestBase.h" namespace U2 { bool GUITestBase::registerTest(GUITest *t) { if(!findTestByName(t->getName())) { tests.insert(t->getName(), t); return true; } return false; } GUITest *GUITestBase::findTestByName(const QString &name) { QMap::const_iterator i = tests.find(name); if(i == tests.end()) { return NULL; } else { return i.value(); } } QList GUITestBase::getTests() { return tests.values(); } } ugene-1.9.8/src/corelibs/U2Test/src/gui_tests/AboutDialogTests.h0000644000175000017500000000241011651544334023217 0ustar ilyailya#ifndef _ABOUT_DIALOG_TESTS_H_ #define _ABOUT_DIALOG_TESTS_H_ #include "GUITests.h" #include namespace U2 { class AboutDialogTests: public GUITest { public: AboutDialogTests(const QString &name): GUITest(name) {} void openDialogByMenu(); void openDialogByShortcut(); QPoint getButtonPos(const QString& buttonObjName); }; class Test1AboutDialog: public AboutDialogTests { public: Test1AboutDialog(const QString &name): AboutDialogTests(name){} void execute(); void checkResult(); }; class Test2AboutDialog: public AboutDialogTests { public: Test2AboutDialog(const QString &name): AboutDialogTests(name){} void execute(); void checkResult(); }; class Test3AboutDialog: public AboutDialogTests { public: Test3AboutDialog(const QString &name): AboutDialogTests(name){} void execute(); void checkResult(); }; class Test4AboutDialog: public AboutDialogTests { public: Test4AboutDialog(const QString &name): AboutDialogTests(name){} void execute(); void checkResult(); }; class Test5AboutDialog: public AboutDialogTests { public: Test5AboutDialog(const QString &name): AboutDialogTests(name){} void execute(); void checkResult(); }; } #endif ugene-1.9.8/src/corelibs/U2Test/src/gui_tests/ProjectViewTests.h0000644000175000017500000000144611651544334023276 0ustar ilyailya#ifndef _PROJECT_VIEW_TESTS_H_ #define _PROJECT_VIEW_TESTS_H_ #include "GUITests.h" #include namespace U2 { class ProjectViewTests: public GUITest { public: ProjectViewTests(const QString &name): GUITest(name) {} void openFile(const QString &path); void addObjectToView(const QString &objectName); void openDocumentInView(const QString &documentName); protected: static const QString projectViewName; }; class TaskViewTest: public GUITest { public: TaskViewTest(const QString &name): GUITest(name) {} QString getTaskProgress(const QString &taskName); QString getTaskState(const QString &taskName); void cancelTask(const QString &taskName); protected: static const QString taskViewWidgetName; }; } #endifugene-1.9.8/src/corelibs/U2Test/src/gui_tests/GUITestLauncher.cpp0000644000175000017500000000600611651544334023310 0ustar ilyailya#include "GUITestLauncher.h" #include "GUITestBase.h" #include #include #include #define TIMEOUT 60000 namespace U2 { void LaunchTestTask::run() { try { t->launch(); } catch(const TestException &ex) { t->setError(ex.msg); } } void LaunchTestTask::prepare() { if(!t) { printf("%s\n", tr("GUITesting:Empty test").toUtf8().data()); //coreLog.info(tr("GUITesting:Empty test")); exit(0); } } Task::ReportResult LaunchTestTask::report() { if(t->isSuccessful()) { printf("%s\n", tr("GUITesting:Success").toUtf8().data()); //coreLog.info(tr("GUITesting:Success")); } else { printf("%s\n", QString(tr("GUITesting:") + t->getError()).toUtf8().data()); //coreLog.info(QString(tr("GUITesting:") + t->getError()).toUtf8().data()); } exit(0); } void TestLauncher::run() { tests = AppContext::getGUITestBase()->getTests(); if(tests.isEmpty()) { setError(tr("No tests to run")); return; } QString path = QCoreApplication::applicationFilePath(); int finishedTest = 0; foreach(GUITest* t, tests) { if(isCanceled()) { return; } QProcess process; process.start(path, QStringList() << QString("--gui-test") + "=" + t->getName()); if(!process.waitForStarted()) { results[t->getName()] = tr("Can't start instance of UGENE"); continue; } if(!process.waitForFinished(TIMEOUT)) { process.kill(); results[t->getName()] = tr("Exit by timeout"); } else if(process.exitStatus() == QProcess::CrashExit) { results[t->getName()] = tr("UGENE crashed"); } else { QString msg = ""; QByteArray output = process.readAllStandardOutput(); QTextStream stream(&output, QIODevice::ReadOnly); while(!stream.atEnd() && msg.isEmpty()) { QString str = stream.readLine(); if(str.contains("GUITesting")) { msg = str.split(":").last(); } } results[t->getName()] = msg; finishedTest++; stateInfo.progress = finishedTest*100/tests.size(); emit si_progressChanged(); } } } QString TestLauncher::generateReport() const{ QString res; res += ""; res += QString("").arg(tr("Test name")).arg(tr("Status")); QMap::const_iterator i; for (i = results.begin(); i != results.end(); ++i) { QString color = "green"; if(!i.value().contains("Success")) { color = "red"; } res += QString("").arg(i.key()).arg(i.value()).arg(color); } res+="
    %1%2
    %1%2
    "; return res; } } ugene-1.9.8/src/corelibs/U2Test/src/gui_tests/AboutDialogTests.cpp0000644000175000017500000001205411651544334023557 0ustar ilyailya#include "AboutDialogTests.h" #include #include #include #include namespace U2 { /////////////////////////////////////////////////////////////////////////////// //util methods for testing AboutDialog void AboutDialogTests::openDialogByMenu() { expandTopLevelMenu(MWMENU_HELP,"mw_menu_bar"); waitForMenuWithAction("&About"); clickMenu(ACTION__ABOUT, MWMENU_HELP); waitForWidget("AboutDialog", true); } void AboutDialogTests::openDialogByShortcut() { keyClick("mw_menu_bar", Qt::Key_F1); waitForWidget("AboutDialog", true); } QPoint AboutDialogTests::getButtonPos(const QString& buttonObjName){ QDialog* dialog=getActiveDialog(); QPushButton* button=dialog->findChild(buttonObjName); return button->pos()+ button->rect().center(); } /////////////////////////////////////////////////////////////////////////////// //Tests of AboutDialog //Test 1: Open dialog with shortcut. Check Title and buttons. void Test1AboutDialog::execute(){ openDialogByShortcut(); } void Test1AboutDialog::checkResult(){ if(!isWidgetExists("AboutDialog")){ throw TestException(tr("Not found AboutDialog")); } QWidget* dialog = findWidgetByName("AboutDialog"); if(dialog->windowTitle() != "About UGENE"){ throw TestException(tr("Wrong AboutDialog title")); } if(dialog->findChild("close_button") == NULL){ throw TestException(tr("Not found close button")); } if(dialog->findChild("web_page_button") == NULL){ throw TestException(tr("Not found web page button")); } } //Test 2: Open dialog by menu. void Test2AboutDialog::execute(){ openDialogByMenu(); } void Test2AboutDialog::checkResult(){ if(!isWidgetExists("AboutDialog")){ throw TestException(tr("Not found AboutDialog")); } } //Test 3: Close with butoon "Close" void Test3AboutDialog::execute(){ openDialogByShortcut(); if(!isWidgetExists("AboutDialog")){ throw TestException(tr("Not found AboutDialog")); } QPoint pos=getButtonPos("close_button"); moveTo("AboutDialog",pos); mouseClick("close_button",Qt::LeftButton); waitForWidget("AboutDialog", false); } void Test3AboutDialog::checkResult(){ if(isWidgetExists("AboutDialog")){ throw TestException(tr("AboutDialog not closed. Close button not work")); } } //Test 4: Check that tetris game started/stoped by mouse click. Close with shortcut "Escape" void Test4AboutDialog::execute(){ openDialogByShortcut(); if(!isWidgetExists("AboutDialog")){ throw TestException(tr("Not found AboutDialog")); } QWidget* dialog=findWidgetByName("AboutDialog"); moveTo("AboutDialog"); waitForWidget("about_widget", true); mouseClick("about_widget",Qt::LeftButton); waitForWidget("tetris_widget", true); if(dialog->windowTitle() != "Have fun ;-)"){ throw TestException(tr("Wrong AboutDialog title")); } moveTo("tetris_widget"); mouseClick("tetris_widget",Qt::LeftButton);//"tetris_widget" waitForWidget("tetris_widget", false); if(dialog->windowTitle() != "About UGENE"){ throw TestException(tr("Wrong AboutDialog title")); } keyClick("AboutDialog",Qt::Key_Escape); waitForWidget("AboutDialog", false); } void Test4AboutDialog::checkResult(){ if(isWidgetExists("AboutDialog")){ throw TestException(tr("About Dialog not closed. 'Escape' shortcut not work")); } } //Test 5: Check that tetris game worked. Close with shortcut "Escape" void Test5AboutDialog::execute(){ openDialogByShortcut(); if(!isWidgetExists("AboutDialog")){ throw TestException(tr("Not found AboutDialog")); } QWidget* dialog = findWidgetByName("AboutDialog"); moveTo("AboutDialog"); keyClick("AboutDialog",Qt::Key_T); waitForWidget("tetris_widget", true); if(dialog->windowTitle() != "Have fun ;-)"){ throw TestException(tr("Wrong AboutDialog title")); } //TODO: check that tetris block moved keyClick("tetris_widget",Qt::Key_Space); //sleep(100); for(int i=0;i<10;i++){ keyClick("tetris_widget",Qt::Key_Up); //sleep(50); } for(int i=0;i<5;i++){ keyClick("tetris_widget",Qt::Key_Left); //sleep(50); } for(int i=0;i<10;i++){ keyClick("tetris_widget",Qt::Key_Down); //sleep(50); } for(int i=0;i<5;i++){ keyClick("tetris_widget",Qt::Key_Right); //sleep(50); } keyClick("AboutDialog",Qt::Key_T); coreLog.info("wait tetris begin"); waitForWidget("tetris_widget", false); coreLog.info("wait tetris"); if(dialog->windowTitle() != "About UGENE"){ throw TestException(tr("Wrong AboutDialog title")); } keyClick("AboutDialog",Qt::Key_Escape); coreLog.info("key click"); waitForWidget("AboutDialog", false); coreLog.info("wait about dialog"); } void Test5AboutDialog::checkResult(){ if(isWidgetExists("AboutDialog")){ throw TestException(tr("About Dialog not closed. 'Escape'' shortcut not work")); } } } //namespace ugene-1.9.8/src/corelibs/U2Test/src/gui_tests/GUITestService.h0000644000175000017500000000521711651544334022617 0ustar ilyailya#ifndef _U2_GUI_TESTS_VIEWER_H_ #define _U2_GUI_TESTS_VIEWER_H_ #include #include #include #include #include #include "GUITests.h" #include "GUITestLauncher.h" #include "ProjectViewTests.h" #include "AboutDialogTests.h" namespace U2 { class TestLauncher; class GUITestService; class U2TEST_EXPORT GUITestService: public Service { Q_OBJECT public: GUITestService(QObject *parent = NULL); void runTest(QList testsToRun); protected: virtual void serviceStateChangedCallback(ServiceState oldState, bool enabledStateChanged); public slots: void sl_registerSevice(); void sl_registerTask(); private: QAction *runTestsAction; TestLauncher *testLauncher; QList testsToRun; }; class TestProjectView: public ProjectViewTests { public: TestProjectView(const QString &_path1, const QString &_path2, const QString &_seqName, const QString &name): ProjectViewTests(name), path1(_path1), path2(_path2), seqName(_seqName) {} void execute(); void checkResult(); private: QString path1; QString path2; QString seqName; }; class LockDocumentTest: public ProjectViewTests { public: LockDocumentTest(const QString &_document, const QString &name): ProjectViewTests(name), document(_document) {} void execute(); void checkResult(); private: QString document; }; class UnlockDocumentTest: public ProjectViewTests { public: UnlockDocumentTest(const QString &_document, const QString &name): ProjectViewTests(name), document(_document) {} void execute(); void checkResult(); private: QString document; }; class ComplexTest: public ProjectViewTests { public: ComplexTest(const QString& _path, const QString &name): ProjectViewTests(name), path(_path) {} void execute(); void checkResult() {} private: QString path; }; class OpenDocumentTest: public ProjectViewTests { public: OpenDocumentTest(const QString &_path, const QString &name): ProjectViewTests(name), path(_path){} void execute() { openFile(path); } void checkResult() {} private: QString path; }; class TestTaskView: public TaskViewTest{ public: TestTaskView(const QString &_path, const QString &_name): TaskViewTest(_name), path(_path) {} void execute(); void checkResult(); private: QString path; }; class LongTest:public GUITest { public: LongTest(): GUITest("Long test") {} void execute() {while(true);} void checkResult() {} }; } #endif ugene-1.9.8/src/corelibs/U2Test/src/gui_tests/ProjectViewTests.cpp0000644000175000017500000000532311651544334023627 0ustar ilyailya#include "ProjectViewTests.h" #include #include #include #include namespace U2 { const QString ProjectViewTests::projectViewName = "documentTreeWidget"; void ProjectViewTests::openFile(const QString &path) { Task *t = AppContext::getProjectLoader()->openWithProjectTask(path); t->moveToThread(QApplication::instance()->thread()); emit runTask(t); //waitForTask(t); } void ProjectViewTests::addObjectToView(const QString &objectName) { //QTreeView *projectViewTree = static_cast(findWidgetByName(projectViewName)); QPoint pos = getItemPosition(objectName, projectViewName); moveTo(projectViewName, pos); mousePressOnItem(projectViewName, Qt::LeftButton, pos); contextMenuOnItem(projectViewName, pos); clickContextMenu("Add to view"); waitForMenuWithAction("Add to view: _1 3INS chain 2 sequence"); clickContextMenu("Add to view: _1 3INS chain 2 sequence"); } void ProjectViewTests::openDocumentInView(const QString &objectName) { //QTreeView *projectViewTree = static_cast(findWidgetByName(projectViewName)); QPoint pos = getItemPosition(objectName, projectViewName); moveTo(projectViewName, pos); mousePressOnItem(projectViewName, Qt::LeftButton, pos); contextMenuOnItem(projectViewName, pos); sleep(500); clickContextMenu("Open view"); sleep(500); clickContextMenu("Open new view: Sequence view"); sleep(2000); } QString TaskViewTest::getTaskProgress(const QString &taskName) { QTreeWidget * w = static_cast(findWidgetByName(taskViewWidgetName)); QListitems = w->findItems(taskName, Qt::MatchRecursive | Qt::MatchExactly); if(items.isEmpty()) { throw TestException(tr("Item %1 not found").arg(taskName)); } return items.first()->text(2); } void TaskViewTest::cancelTask(const QString &taskName) { QPoint pos = getItemPosition(taskName, taskViewWidgetName); moveTo(taskViewWidgetName, pos); mouseClickOnItem(taskViewWidgetName, Qt::LeftButton, pos); contextMenuOnItem(taskViewWidgetName, pos); //sleep(500); clickContextMenu("Cancel task"); } QString TaskViewTest::getTaskState(const QString &taskName){ QTreeWidget * w = static_cast(findWidgetByName(taskViewWidgetName)); QListitems = w->findItems(taskName, Qt::MatchRecursive | Qt::MatchExactly); if(items.isEmpty()) { throw TestException(tr("Item %1 not found").arg(taskName)); } return items.first()->text(1); } const QString TaskViewTest::taskViewWidgetName = "taskViewTree"; } ugene-1.9.8/src/corelibs/U2Test/src/GTest.h0000644000175000017500000001163011651544334017026 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_UGENE_TEST_FRAMEWORK_H_ #define _U2_UGENE_TEST_FRAMEWORK_H_ #include #include #include #include #include #include namespace U2 { class U2TEST_EXPORT GTestEnvironment { public: void setVar(const QString& varName, const QString& val) {vars[varName] = val;} QString getVar(const QString& varName) const {return vars.value(varName);} QMap getVars() const {return vars;} bool containsEmptyVars() const {return vars.values().contains(QString(""));} private: QMap vars; }; class U2TEST_EXPORT GTest : public Task { Q_OBJECT public: GTest(const QString& taskName, GTest* cp, const GTestEnvironment* env, TaskFlags flags, const QList& subtasks = QList()); QObject* getContext(const QString& name) const; void addContext(const QString& name, QObject* v); void removeContext(const QString& name); template static T* getContext(const GTest* test, const QString& name) { QObject* o = test->getContext(name); T* res = qobject_cast(o); return res; } const GTestEnvironment* getEnv() const {return env;} protected: GTest* getContextProvider() const {return contextProvider;} void failMissingValue(const QString&); GTest* contextProvider; const GTestEnvironment* env; QMap subtestsContext; }; class U2TEST_EXPORT GTestFormat : public QObject { public: GTestFormat(const QString& _formatId) : formatId(_formatId){}; const QString getFormatId() const {return formatId;} virtual GTest* createTest(const QString& name, GTest* cp, const GTestEnvironment* env, const QByteArray& testData, QString& err) = 0; protected: QString formatId; }; class GTestSuite; class U2TEST_EXPORT GTestRef { public: GTestRef(const QString& _url, const QString& sName, const GTestFormatId f) : url(_url), shortName(sName), formatId(f){} const QString& getURL() const {return url;} const QString& getShortName() const {return shortName;} const GTestFormatId getFormatId() {return formatId;} void setSuite( GTestSuite * _suite ) { suite = _suite; } GTestSuite * getSuite() const {return suite;} private: QString url; QString shortName; GTestFormatId formatId; GTestSuite * suite; }; class U2TEST_EXPORT GTestState : public QObject { Q_OBJECT public: GTestState(GTestRef* ref) : testRef(ref), state(TriState_Unknown) {} GTestRef* getTestRef() const {return testRef;} bool isPassed() const {return state == TriState_Yes;} bool isFailed() const {return state == TriState_No;} bool isNew() const {return state == TriState_Unknown;} const QString& getErrorMessage() const {return errMessage;} void clearState(); void setFailed(const QString& err); void setPassed(); signals: void si_stateChanged(GTestState* ts); private: GTestRef* testRef; TriState state; QString errMessage; }; class U2TEST_EXPORT GTestSuite : public QObject { Q_OBJECT public: virtual ~GTestSuite(); GTestEnvironment* getEnv() {return &env;} const QList& getTests() const {return tests;} const QList& getExcludedTests() const {return excluded;} const QString& getURL() const {return url;} const QString& getName() const {return name;} int getTestTimeout() const { return testTimeout; } static GTestSuite* readTestSuite(const QString& url, QString& err); static QList readTestSuiteList(const QString& url, QStringList& err); protected: GTestSuite() : url(), name(), tests(), excluded(), testTimeout(0), env() {} QString url; QString name; QList tests; QList excluded; /** Maximum run time for single test in sutie. timeout = 0 means this parameter unused */ int testTimeout; GTestEnvironment env; }; }//namespace #endif ugene-1.9.8/src/corelibs/U2Test/transl/0000755000175000017500000000000011651544334016342 5ustar ilyailyaugene-1.9.8/src/corelibs/U2Test/transl/russian.ts0000644000175000017500000000250511651544334020400 0ustar ilyailya U2::GTestFormatRegistry set timeout for tests U2::LoadTestTask TestLoader for %1 Cannot open file: %1 Не могу открыть файл: "%1" U2::TestRunnerTask Test runner Исполнение тестов Test format not supported: %1 Формат теста не поддерживается: %1 ugene-1.9.8/src/corelibs/U2Test/transl/czech.ts0000644000175000017500000000355611651544334020017 0ustar ilyailya U2::GTestFormatRegistry set timeout for tests Nastavit překročení času pro zkoušky U2::LoadTestTask test_loader_for_%1 TestLoader for %1 cant_open_file: %1 Can't open file: %1 TestLoader for %1 Zkušební nahrávač pro %1 Cannot open file: %1 Nelze otevřít soubor: %1 U2::TestRunnerTask test_runner Test runner test_format_not_supported_%1 Test format not supported: %1 Test runner Spouštěč zkoušky Test format not supported: %1 Formát zkoušky nepodporován: %1 ugene-1.9.8/src/corelibs/U2Test/transl/english.ts0000644000175000017500000000226511651544334020350 0ustar ilyailya U2::GTestFormatRegistry set timeout for tests U2::LoadTestTask TestLoader for %1 Cannot open file: %1 U2::TestRunnerTask Test runner Test format not supported: %1 ugene-1.9.8/src/corelibs/U2Test/U2Test.pro0000644000175000017500000000202311651544334016704 0ustar ilyailyainclude (U2Test.pri) # Input HEADERS += src/GTest.h \ src/GTestFrameworkComponents.h \ src/TestRunnerTask.h \ src/TestRunnerSettings.h \ src/xmltest/XMLTestFormat.h \ src/xmltest/XMLTestUtils.h \ src/gui_tests/AboutDialogTests.h \ src/gui_tests/GUITests.h \ src/gui_tests/GUITestService.h \ src/gui_tests/ProjectViewTests.h \ src/gui_tests/GUITestLauncher.h \ src/gui_tests/GUITestBase.h SOURCES += src/GTest.cpp \ src/GTestFrameworkComponents.cpp \ src/TestRunnerTask.cpp \ src/xmltest/XMLTestFormat.cpp \ src/xmltest/XMLTestUtils.cpp \ src/gui_tests/AboutDialogTests.cpp \ src/gui_tests/GUITests.cpp \ src/gui_tests/GUITestService.cpp \ src/gui_tests/ProjectViewTests.cpp \ src/gui_tests/GUITestLauncher.cpp \ src/gui_tests/GUITestBase.cpp TRANSLATIONS += transl/czech.ts transl/english.ts transl/russian.ts ugene-1.9.8/src/corelibs/U2View/0000755000175000017500000000000011651544334015032 5ustar ilyailyaugene-1.9.8/src/corelibs/U2View/U2View.pro0000644000175000017500000002662011651544334016703 0ustar ilyailyainclude (U2View.pri) # Input HEADERS += src/WebWindow.h \ src/phyltree/BranchSettingsDialog.h \ src/phyltree/ButtonSettingsDialog.h \ src/phyltree/CreatePhyTreeDialogController.h \ src/phyltree/CreatePhyTreeWidget.h \ src/phyltree/TextSettingsDialog.h \ src/phyltree/TreeSettingsDialog.h \ src/util_dna_assembly/BuildIndexDialog.h \ src/util_dna_assembly/ConvertAssemblyToSamDialog.h \ src/util_dna_assembly/DnaAssemblyDialog.h \ src/util_dna_assembly/DnaAssemblyGUIExtension.h \ src/util_dna_assembly/DnaAssemblyUtils.h \ src/util_find_dialog/FindDialog.h \ src/util_msa_align/MSAAlignDialog.h \ src/util_msa_align/MSAAlignGUIExtension.h \ src/util_ov_annotated_dna/ADVAnnotationCreation.h \ src/util_ov_annotated_dna/ADVClipboard.h \ src/util_ov_annotated_dna/ADVConstants.h \ src/util_ov_annotated_dna/ADVGraphModel.h \ src/util_ov_annotated_dna/ADVSequenceObjectContext.h \ src/util_ov_annotated_dna/ADVSequenceWidget.h \ src/util_ov_annotated_dna/ADVSingleSequenceWidget.h \ src/util_ov_annotated_dna/ADVSplitWidget.h \ src/util_ov_annotated_dna/ADVSyncViewManager.h \ src/util_ov_annotated_dna/ADVUtils.h \ src/util_ov_annotated_dna/AnnotatedDNAView.h \ src/util_ov_annotated_dna/AnnotatedDNAViewFactory.h \ src/util_ov_annotated_dna/AnnotatedDNAViewState.h \ src/util_ov_annotated_dna/AnnotatedDNAViewTasks.h \ src/util_ov_annotated_dna/AnnotationsTreeModel.h \ src/util_ov_annotated_dna/AnnotationsTreeView.h \ src/util_ov_annotated_dna/AnnotationsTreeViewL.h \ src/util_ov_annotated_dna/AutoAnnotationUtils.h \ src/util_ov_annotated_dna/CreateRulerDialogController.h \ src/util_ov_annotated_dna/DetView.h \ src/util_ov_annotated_dna/EditAnnotationDialogController.h \ src/util_ov_annotated_dna/GSequenceGraphView.h \ src/util_ov_annotated_dna/GSequenceLineView.h \ src/util_ov_annotated_dna/GSequenceLineViewAnnotated.h \ src/util_ov_annotated_dna/Overview.h \ src/util_ov_annotated_dna/PanView.h \ src/util_ov_annotated_dna/PanViewRows.h \ src/util_ov_annotated_dna/WindowStepSelectorWidget.h \ src/util_ov_indexview/CreateFileIndexDialog.h \ src/util_ov_indexview/UIndexExportToNewFileDialogImpl.h \ src/util_ov_indexview/UIndexSupport.h \ src/util_ov_indexview/UIndexViewer.h \ src/util_ov_indexview/UIndexViewerFactory.h \ src/util_ov_indexview/UIndexViewerTasks.h \ src/util_ov_indexview/UIndexViewHeaderItemWidgetImpl.h \ src/util_ov_indexview/UIndexViewWidgetImpl.h \ src/util_ov_indexview/UIndexViewWidgetKey.h \ src/util_ov_msaedit/AlignmentLogo.h \ src/util_ov_msaedit/ConsensusSelectorDialogController.h \ src/util_ov_msaedit/CreateSubalignimentDialogController.h \ src/util_ov_msaedit/DeleteGapsDialog.h \ src/util_ov_msaedit/MSAColorScheme.h \ src/util_ov_msaedit/MSAEditor.h \ src/util_ov_msaedit/MSAEditorBaseOffsetsCache.h \ src/util_ov_msaedit/MSAEditorConsensusArea.h \ src/util_ov_msaedit/MSAEditorConsensusCache.h \ src/util_ov_msaedit/MSAEditorFactory.h \ src/util_ov_msaedit/MSAEditorNameList.h \ src/util_ov_msaedit/MSAEditorOffsetsView.h \ src/util_ov_msaedit/MSAEditorSequenceArea.h \ src/util_ov_msaedit/MSAEditorState.h \ src/util_ov_msaedit/MSAEditorStatusBar.h \ src/util_ov_msaedit/MSAEditorTasks.h \ src/util_ov_msaedit/MSAEditorUndoFramework.h \ src/util_ov_phyltree/CreateBranchesTask.h \ src/util_ov_phyltree/CreateCircularBranchesTask.h \ src/util_ov_phyltree/CreateRectangularBranchesTask.h \ src/util_ov_phyltree/CreateUnrootedBranchesTask.h \ src/util_ov_phyltree/GraphicsBranchItem.h \ src/util_ov_phyltree/GraphicsButtonItem.h \ src/util_ov_phyltree/GraphicsCircularBranchItem.h \ src/util_ov_phyltree/GraphicsRectangularBranchItem.h \ src/util_ov_phyltree/GraphicsUnrootedBranchItem.h \ src/util_ov_phyltree/TreeViewer.h \ src/util_ov_phyltree/TreeViewerFactory.h \ src/util_ov_phyltree/TreeViewerState.h \ src/util_ov_phyltree/TreeViewerTasks.h \ src/util_ov_phyltree/TreeViewerUtils.h \ src/util_ov_textview/SimpleTextObjectView.h \ src/util_ov_textview/SimpleTextObjectViewTasks.h \ src/util_sec_struct_predict/SecStructDialog.h \ src/util_sec_struct_predict/SecStructPredictUtils.h \ src/util_smith_waterman/SmithWatermanDialog.h \ src/util_smith_waterman/SmithWatermanDialogImpl.h \ src/util_smith_waterman/SubstMatrixDialog.h FORMS += src/phyltree/ui/BranchSettingsDialog.ui \ src/phyltree/ui/ButtonSettingsDialog.ui \ src/phyltree/ui/CreatePhyTreeDialog.ui \ src/phyltree/ui/TextSettingsDialog.ui \ src/phyltree/ui/TreeSettingsDialog.ui \ src/util_dna_assembly/ui/AssemblyToRefDialog.ui \ src/util_dna_assembly/ui/AssemblyToSamDialog.ui \ src/util_dna_assembly/ui/BuildIndexFromRefDialog.ui \ src/util_find_dialog/ui/FindDialogUI.ui \ src/util_msa_align/ui/PerformAlignmentDialog.ui \ src/util_ov_annotated_dna/ui/CreateRulerDialog.ui \ src/util_ov_annotated_dna/ui/EditAnnotationDialog.ui \ src/util_ov_indexview/ui/CreateFileIndexDialog.ui \ src/util_ov_indexview/ui/UIndexExportToNewFileDialog.ui \ src/util_ov_indexview/ui/UIndexViewHeaderItemWidget.ui \ src/util_ov_indexview/ui/UIndexViewWidget.ui \ src/util_ov_msaedit/ui/ConsensusSelectorDialog.ui \ src/util_ov_msaedit/ui/CreateSubalignimentDialog.ui \ src/util_ov_msaedit/ui/DeleteGapsDialog.ui \ src/util_sec_struct_predict/ui/SecStructDialog.ui \ src/util_smith_waterman/ui/SmithWatermanDialogBase.ui \ src/util_smith_waterman/ui/SubstMatrixDialogBase.ui SOURCES += src/WebWindow.cpp \ src/phyltree/BranchSettingsDialog.cpp \ src/phyltree/ButtonSettingsDialog.cpp \ src/phyltree/CreatePhyTreeDialogController.cpp \ src/phyltree/CreatePhyTreeWidget.cpp \ src/phyltree/TextSettingsDialog.cpp \ src/phyltree/TreeSettingsDialog.cpp \ src/util_dna_assembly/BuildIndexDialog.cpp \ src/util_dna_assembly/ConvertAssemblyToSamDialog.cpp \ src/util_dna_assembly/DnaAssemblyDialog.cpp \ src/util_dna_assembly/DnaAssemblyUtils.cpp \ src/util_find_dialog/FindDialog.cpp \ src/util_msa_align/MSAAlignDialog.cpp \ src/util_ov_annotated_dna/ADVAnnotationCreation.cpp \ src/util_ov_annotated_dna/ADVClipboard.cpp \ src/util_ov_annotated_dna/ADVGraphModel.cpp \ src/util_ov_annotated_dna/ADVSequenceObjectContext.cpp \ src/util_ov_annotated_dna/ADVSequenceWidget.cpp \ src/util_ov_annotated_dna/ADVSingleSequenceWidget.cpp \ src/util_ov_annotated_dna/ADVSplitWidget.cpp \ src/util_ov_annotated_dna/ADVSyncViewManager.cpp \ src/util_ov_annotated_dna/ADVUtils.cpp \ src/util_ov_annotated_dna/AnnotatedDNAView.cpp \ src/util_ov_annotated_dna/AnnotatedDNAViewFactory.cpp \ src/util_ov_annotated_dna/AnnotatedDNAViewState.cpp \ src/util_ov_annotated_dna/AnnotatedDNAViewTasks.cpp \ src/util_ov_annotated_dna/AnnotationsTreeModel.cpp \ src/util_ov_annotated_dna/AnnotationsTreeView.cpp \ src/util_ov_annotated_dna/AnnotationsTreeViewL.cpp \ src/util_ov_annotated_dna/AutoAnnotationUtils.cpp \ src/util_ov_annotated_dna/CreateRulerDialogController.cpp \ src/util_ov_annotated_dna/DetView.cpp \ src/util_ov_annotated_dna/EditAnnotationDialogController.cpp \ src/util_ov_annotated_dna/GSequenceGraphView.cpp \ src/util_ov_annotated_dna/GSequenceLineView.cpp \ src/util_ov_annotated_dna/GSequenceLineViewAnnotated.cpp \ src/util_ov_annotated_dna/Overview.cpp \ src/util_ov_annotated_dna/PanView.cpp \ src/util_ov_annotated_dna/PanViewRows.cpp \ src/util_ov_annotated_dna/WindowStepSelectorWidget.cpp \ src/util_ov_indexview/UIndexExportToNewFileDialogImpl.cpp \ src/util_ov_indexview/UIndexSupport.cpp \ src/util_ov_indexview/UIndexViewer.cpp \ src/util_ov_indexview/UIndexViewerFactory.cpp \ src/util_ov_indexview/UIndexViewerTasks.cpp \ src/util_ov_indexview/UIndexViewHeaderItemWidgetImpl.cpp \ src/util_ov_indexview/UIndexViewWidgetImpl.cpp \ src/util_ov_indexview/UIndexViewWidgetKey.cpp \ src/util_ov_msaedit/AlignmentLogo.cpp \ src/util_ov_msaedit/ConsensusSelectorDialogController.cpp \ src/util_ov_msaedit/CreateSubalignimentDialogController.cpp \ src/util_ov_msaedit/DeleteGapsDialog.cpp \ src/util_ov_msaedit/MSAColorScheme.cpp \ src/util_ov_msaedit/MSAEditor.cpp \ src/util_ov_msaedit/MSAEditorBaseOffsetsCache.cpp \ src/util_ov_msaedit/MSAEditorConsensusArea.cpp \ src/util_ov_msaedit/MSAEditorConsensusCache.cpp \ src/util_ov_msaedit/MSAEditorFactory.cpp \ src/util_ov_msaedit/MSAEditorNameList.cpp \ src/util_ov_msaedit/MSAEditorOffsetsView.cpp \ src/util_ov_msaedit/MSAEditorSequenceArea.cpp \ src/util_ov_msaedit/MSAEditorState.cpp \ src/util_ov_msaedit/MSAEditorStatusBar.cpp \ src/util_ov_msaedit/MSAEditorTasks.cpp \ src/util_ov_msaedit/MSAEditorUndoFramework.cpp \ src/util_ov_phyltree/CreateCircularBranchesTask.cpp \ src/util_ov_phyltree/CreateRectangularBranchesTask.cpp \ src/util_ov_phyltree/CreateUnrootedBranchesTask.cpp \ src/util_ov_phyltree/GraphicsBranchItem.cpp \ src/util_ov_phyltree/GraphicsButtonItem.cpp \ src/util_ov_phyltree/GraphicsCircularBranchItem.cpp \ src/util_ov_phyltree/GraphicsRectangularBranchItem.cpp \ src/util_ov_phyltree/GraphicsUnrootedBranchItem.cpp \ src/util_ov_phyltree/TreeViewer.cpp \ src/util_ov_phyltree/TreeViewerFactory.cpp \ src/util_ov_phyltree/TreeViewerState.cpp \ src/util_ov_phyltree/TreeViewerTasks.cpp \ src/util_ov_phyltree/TreeViewerUtils.cpp \ src/util_ov_textview/SimpleTextObjectView.cpp \ src/util_ov_textview/SimpleTextObjectViewTasks.cpp \ src/util_sec_struct_predict/SecStructDialog.cpp \ src/util_sec_struct_predict/SecStructPredictUtils.cpp \ src/util_smith_waterman/SmithWatermanDialog.cpp \ src/util_smith_waterman/SubstMatrixDialog.cpp TRANSLATIONS += transl/czech.ts transl/english.ts transl/russian.ts ugene-1.9.8/src/corelibs/U2View/U2View.pri0000644000175000017500000000137111651544334016671 0ustar ilyailya# include (U2View.pri) UGENE_RELATIVE_DESTDIR = '' MODULE_ID=U2View include( ../../ugene_lib_common.pri ) QT += svg webkit DEFINES+= QT_FATAL_ASSERT BUILDING_U2VIEW_DLL LIBS += -L../../_release -lU2Core -lU2Algorithm -lU2Formats -lU2Remote -lU2Misc -lU2Lang -lU2Gui !debug_and_release|build_pass { CONFIG(debug, debug|release) { DESTDIR=../../_debug LIBS -= -L../../_release -lU2Core -lU2Algorithm -lU2Formats -lU2Remote -lU2Misc -lU2Lang -lU2Gui LIBS += -L../../_debug -lU2Cored -lU2Algorithmd -lU2Formatsd -lU2Remoted -lU2Miscd -lU2Langd -lU2Guid } CONFIG(release, debug|release) { DESTDIR=../../_release } } unix { target.path = $$UGENE_INSTALL_DIR/$$UGENE_RELATIVE_DESTDIR INSTALLS += target } ugene-1.9.8/src/corelibs/U2View/src/0000755000175000017500000000000011651544334015621 5ustar ilyailyaugene-1.9.8/src/corelibs/U2View/src/util_ov_phyltree/0000755000175000017500000000000011651544334021216 5ustar ilyailyaugene-1.9.8/src/corelibs/U2View/src/util_ov_phyltree/GraphicsCircularBranchItem.cpp0000644000175000017500000001044611651544334027111 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "GraphicsCircularBranchItem.h" #include "GraphicsRectangularBranchItem.h" #include "GraphicsButtonItem.h" #include "TreeViewerUtils.h" #include #include #include #include #include #include #include #include namespace U2 { #ifndef M_PI #define M_PI 3.14159265358979323846 #endif GraphicsCircularBranchItem::GraphicsCircularBranchItem(QGraphicsItem* parent, qreal h, GraphicsRectangularBranchItem* from) : GraphicsBranchItem(true), height(h), direction(from->getDirection()), visible(true) { setParentItem(parent); settings = from->settings; qreal w = from->getWidth(); setWidthW(w); setDist(from->getDist()); setPos(w, 0); QPointF p = mapFromScene(0, 0); setTransform(QTransform().translate(p.x(), p.y()).rotate((direction == GraphicsBranchItem::up ? -1 : 1) * h / M_PI * 180).translate(-p.x(), -p.y())); //QPen pen1; //pen1.setCosmetic(true); if (from->getNameText() != NULL) { nameText = new QGraphicsSimpleTextItem(from->getNameText()->text(), this); nameText->setFont(from->getNameText()->font()); QRectF rect = nameText->boundingRect(); qreal h = rect.height(); nameText->setPos(GraphicsBranchItem::TextSpace, -h * 0.5); if (nameText->scenePos().x() < 0.0) { QPointF p = rect.center(); nameText->setTransform(QTransform().translate(p.x(), p.y()).rotate(180).translate(-p.x(), -p.y())); } // pen1.setStyle(Qt::DotLine); // pen1.setColor(Qt::darkGray); nameText->setBrush(from->getNameText()->brush()); } if (from->getDistanceText() != NULL) { distanceText = new QGraphicsSimpleTextItem(from->getDistanceText()->text(), this); distanceText->setFont(from->getDistanceText()->font()); QRectF rect = distanceText->boundingRect(); if (distanceText->scenePos().x() < 0) { QPointF p(rect.center().x(), rect.height()); distanceText->setTransform(QTransform().translate(p.x(), p.y()).rotate(180).translate(-p.x(), -p.y())); } distanceText->setPos(-0.5 * (w + rect.width()), -rect.height()); distanceText->setBrush(from->getDistanceText()->brush()); } setPen(from->pen()); } QRectF GraphicsCircularBranchItem::boundingRect() const { QPointF p = scenePos(); qreal rad = qSqrt(p.x() * p.x() + p.y() * p.y()); qreal w = width + rad * (1 - qCos(height)); qreal h = rad * qSin(height); return QRectF(-w, direction == GraphicsBranchItem::up ? 0 : -h, w, h); } void GraphicsCircularBranchItem::paint(QPainter *painter, const QStyleOptionGraphicsItem*, QWidget*) { if (!visible) return; painter->setPen(pen()); QPointF p = scenePos(); qreal rad = qSqrt(p.x() * p.x() + p.y() * p.y()) - width; QRectF rect(-2 * rad - width, -rad, 2 * rad, 2 * rad); painter->drawArc(rect, 0, (direction == GraphicsBranchItem::up ? -1 : 1) * height * 16 * 180 / M_PI); painter->drawLine(0, 0, -width, 0); } QPainterPath GraphicsCircularBranchItem::shape() const { QPainterPath path; qreal rad = 30.0; // all hardcode will be deleted later during complete refactoring QRectF rect(-2 * rad - width, -rad, 2 * rad, 2 * rad); path.lineTo(width, 0); path.arcTo(rect, 0, (direction == GraphicsBranchItem::up ? -1 : 1) * height * 16 * 180 / M_PI); return path; } }//namespace ugene-1.9.8/src/corelibs/U2View/src/util_ov_phyltree/CreateCircularBranchesTask.h0000644000175000017500000000264511651544334026557 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_CREATE_CIRCULAR_BRANCHES_TASK_H_ #define _U2_CREATE_CIRCULAR_BRANCHES_TASK_H_ #include "CreateBranchesTask.h" namespace U2 { class PhyNode; class GraphicsRectangularBranchItem; class GraphicsCircularBranchItem; class CreateCircularBranchesTask: public CreateBranchesTask { Q_OBJECT qreal coef; GraphicsRectangularBranchItem* root1; GraphicsCircularBranchItem* getBranch(GraphicsRectangularBranchItem *r, GraphicsCircularBranchItem* parent); public: CreateCircularBranchesTask(GraphicsRectangularBranchItem *r); void run(); }; }//namespace; #endif ugene-1.9.8/src/corelibs/U2View/src/util_ov_phyltree/TreeViewerTasks.h0000644000175000017500000000443211651544334024461 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_TREE_VIEWER_TASKS_H_ #define _U2_TREE_VIEWER_TASKS_H_ #include #include namespace U2 { class PhyTreeObject; class UnloadedObject; class TreeViewer; class CreateRectangularBranchesTask; class OpenTreeViewerTask : public ObjectViewTask { Q_OBJECT public: OpenTreeViewerTask(PhyTreeObject* obj); OpenTreeViewerTask(UnloadedObject* obj); OpenTreeViewerTask(Document* doc); virtual void open(); static void updateTitle(TreeViewer* tv); private: QPointer phyObject; GObjectReference unloadedReference; }; class OpenSavedTreeViewerTask : public ObjectViewTask { Q_OBJECT public: OpenSavedTreeViewerTask(const QString& viewName, const QVariantMap& stateData); virtual void open(); static void updateRanges(const QVariantMap& stateData, TreeViewer* ctx); }; class UpdateTreeViewerTask : public ObjectViewTask { public: UpdateTreeViewerTask(GObjectView* v, const QString& stateName, const QVariantMap& stateData); virtual void update(); }; class CreateTreeViewerTask: public Task { QString viewName; QPointer phyObj; CreateRectangularBranchesTask* subTask; QVariantMap stateData; public: CreateTreeViewerTask(const QString& name, const QPointer& obj, const QVariantMap& stateData); virtual void prepare(); virtual ReportResult report(); }; } // namespace #endif ugene-1.9.8/src/corelibs/U2View/src/util_ov_phyltree/CreateBranchesTask.h0000644000175000017500000000237311651544334025070 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_CREATE_BRANCHES_TASK_H_ #define _U2_CREATE_BRANCHES_TASK_H_ #include namespace U2 { class GraphicsBranchItem; class CreateBranchesTask: public Task { Q_OBJECT protected: GraphicsBranchItem* root; public: CreateBranchesTask(): Task(QObject::tr("Generating tree view"), TaskFlag_None), root(NULL) {} GraphicsBranchItem* getResult() { return root; } }; }//namespace; #endif ugene-1.9.8/src/corelibs/U2View/src/util_ov_phyltree/TreeViewerTasks.cpp0000644000175000017500000001661011651544334025015 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "TreeViewerTasks.h" #include "TreeViewer.h" #include "TreeViewerFactory.h" #include "TreeViewerState.h" #include "CreateRectangularBranchesTask.h" #include "GraphicsRectangularBranchItem.h" #include #include #include #include #include #include #include #include #include namespace U2 { /* TRANSLATOR U2::TreeViewer */ /* TRANSLATOR U2::ObjectViewTask */ ////////////////////////////////////////////////////////////////////////// /// open new view OpenTreeViewerTask::OpenTreeViewerTask(PhyTreeObject* _obj) : ObjectViewTask(TreeViewerFactory::ID), phyObject(_obj) { assert(!phyObject.isNull()); } OpenTreeViewerTask::OpenTreeViewerTask(UnloadedObject* _obj) : ObjectViewTask(TreeViewerFactory::ID), unloadedReference(_obj) { assert(_obj->getLoadedObjectType() == GObjectTypes::PHYLOGENETIC_TREE); documentsToLoad.append(_obj->getDocument()); } OpenTreeViewerTask::OpenTreeViewerTask(Document* doc) : ObjectViewTask(TreeViewerFactory::ID), phyObject(NULL) { assert(!doc->isLoaded()); documentsToLoad.append(doc); } void OpenTreeViewerTask::open() { if (stateInfo.hasError() || (phyObject.isNull() && documentsToLoad.isEmpty())) { return; } if (phyObject.isNull()) { Document* doc = documentsToLoad.first(); QList objects; if (unloadedReference.isValid()) { GObject* obj = doc->findGObjectByName(unloadedReference.objName); if (obj != NULL && obj->getGObjectType() == GObjectTypes::PHYLOGENETIC_TREE) { phyObject = qobject_cast(obj); } } else { QList objects = doc->findGObjectByType(GObjectTypes::PHYLOGENETIC_TREE, UOF_LoadedAndUnloaded); phyObject = objects.isEmpty() ? NULL : qobject_cast(objects.first()); } if (phyObject.isNull()) { stateInfo.setError(tr("Phylogenetic tree object not found")); return; } } viewName = GObjectViewUtils::genUniqueViewName(phyObject->getDocument(), phyObject); uiLog.details(tr("Opening tree viewer for object %1").arg(phyObject->getGObjectName())); Task* createTask = new CreateTreeViewerTask(viewName, phyObject, stateData); TaskScheduler* scheduler = AppContext::getTaskScheduler(); scheduler->registerTopLevelTask(createTask); } void OpenTreeViewerTask::updateTitle(TreeViewer* tv) { const QString& oldViewName = tv->getName(); GObjectViewWindow* w = GObjectViewUtils::findViewByName(oldViewName); if (w != NULL) { PhyTreeObject* phyObj = tv->getPhyObject(); QString newViewName = GObjectViewUtils::genUniqueViewName(phyObj->getDocument(), phyObj); tv->setName(newViewName); w->setWindowTitle(newViewName); } } ////////////////////////////////////////////////////////////////////////// // open view from state OpenSavedTreeViewerTask::OpenSavedTreeViewerTask(const QString& viewName, const QVariantMap& stateData) : ObjectViewTask(TreeViewerFactory::ID, viewName, stateData) { TreeViewerState state(stateData); GObjectReference ref = state.getPhyObject(); Document* doc = AppContext::getProject()->findDocumentByURL(ref.docUrl); if (doc == NULL) { doc = createDocumentAndAddToProject(ref.docUrl, AppContext::getProject()); if (!doc) { stateIsIllegal = true; stateInfo.setError(L10N::errorDocumentNotFound(ref.docUrl)); return; } } if (!doc->isLoaded()) { documentsToLoad.append(doc); } } void OpenSavedTreeViewerTask::open() { if (stateInfo.hasError()) { return; } TreeViewerState state(stateData); GObjectReference ref = state.getPhyObject(); Document* doc = AppContext::getProject()->findDocumentByURL(ref.docUrl); if (doc == NULL) { stateIsIllegal = true; stateInfo.setError(L10N::errorDocumentNotFound(ref.docUrl)); return; } GObject* obj = doc->findGObjectByName(ref.objName); if (obj == NULL || obj->getGObjectType() != GObjectTypes::PHYLOGENETIC_TREE) { stateIsIllegal = true; stateInfo.setError(tr("DNA sequence object not found: %1").arg(ref.objName)); return; } PhyTreeObject* phyObject = qobject_cast(obj); assert(phyObject != NULL); Task* createTask = new CreateTreeViewerTask(viewName, phyObject, stateData); TaskScheduler* scheduler = AppContext::getTaskScheduler(); scheduler->registerTopLevelTask(createTask); } void OpenSavedTreeViewerTask::updateRanges(const QVariantMap& stateData, TreeViewer* ctx) { TreeViewerState state(stateData); QTransform m = state.getTransform(); if (m != QTransform()) { ctx->setTransform(m); } qreal zoom = state.getZoom(); ctx->setZoom(zoom); ctx->setSettingsState(stateData); } ////////////////////////////////////////////////////////////////////////// // update UpdateTreeViewerTask::UpdateTreeViewerTask(GObjectView* v, const QString& stateName, const QVariantMap& stateData) : ObjectViewTask(v, stateName, stateData) { } void UpdateTreeViewerTask::update() { if (view.isNull() || view->getFactoryId() != TreeViewerFactory::ID) { return; //view was closed; } TreeViewer* phyView = qobject_cast(view.data()); assert(phyView != NULL); OpenSavedTreeViewerTask::updateRanges(stateData, phyView); } ////////////////////////////////////////////////////////////////////////// /// create view CreateTreeViewerTask::CreateTreeViewerTask(const QString& name, const QPointer& obj, const QVariantMap& sData) : Task("Open tree viewer", TaskFlag_NoRun), viewName(name), phyObj(obj), subTask(NULL), stateData(sData) {} void CreateTreeViewerTask::prepare() { subTask = new CreateRectangularBranchesTask(phyObj->getTree()->rootNode); addSubTask(subTask); } Task::ReportResult CreateTreeViewerTask::report() { GraphicsRectangularBranchItem* root = dynamic_cast(subTask->getResult()); TreeViewer* v = new TreeViewer(viewName, phyObj, root, subTask->getScale()); GObjectViewWindow* w = new GObjectViewWindow(v, viewName, !stateData.isEmpty()); MWMDIManager* mdiManager = AppContext::getMainWindow()->getMDIManager(); mdiManager->addMDIWindow(w); if (!stateData.isEmpty()) { OpenSavedTreeViewerTask::updateRanges(stateData, v); } return Task::ReportResult_Finished; } } // namespace ugene-1.9.8/src/corelibs/U2View/src/util_ov_phyltree/GraphicsCircularBranchItem.h0000644000175000017500000000306411651544334026554 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_GRAPHICS_CIRCULAR_BRANCH_ITEM_H_ #define _U2_GRAPHICS_CIRCULAR_BRANCH_ITEM_H_ #include #include "GraphicsBranchItem.h" class QGraphicsItem; namespace U2 { class PhyNode; class GraphicsButtonItem; class GraphicsRectangularBranchItem; class GraphicsCircularBranchItem: public GraphicsBranchItem { qreal height; Direction direction; bool visible; public: GraphicsCircularBranchItem(QGraphicsItem* parent, qreal height, GraphicsRectangularBranchItem* from); QRectF boundingRect() const; QPainterPath shape() const; void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget); void setVisibleW(bool v) { visible = v; } }; }//namespace; #endif ugene-1.9.8/src/corelibs/U2View/src/util_ov_phyltree/TreeViewerFactory.cpp0000644000175000017500000001121711651544334025335 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "TreeViewerFactory.h" #include "TreeViewer.h" #include "TreeViewerTasks.h" #include "TreeViewerState.h" #include #include #include #include #include #include namespace U2 { /* TRANSLATOR U2::TreeViewer */ /* TRANSLATOR U2::ObjectViewTask */ const GObjectViewFactoryId TreeViewerFactory::ID("PhylTreeViewer"); TreeViewerFactory::TreeViewerFactory(): GObjectViewFactory(ID, tr("Phylogenetic tree viewer")) {} bool TreeViewerFactory::canCreateView(const MultiGSelection& multiSelection) { bool hasPhyDocuments = !SelectionUtils::findDocumentsWithObjects( GObjectTypes::PHYLOGENETIC_TREE, &multiSelection, UOF_LoadedAndUnloaded, true).isEmpty(); if (hasPhyDocuments) { return true; } return false; } #define MAX_VIEWS 10 Task* TreeViewerFactory::createViewTask(const MultiGSelection& multiSelection, bool single) { QList phyObjects = SelectionUtils::findObjects(GObjectTypes::PHYLOGENETIC_TREE, &multiSelection, UOF_LoadedAndUnloaded); QSet docsWithPhy = SelectionUtils::findDocumentsWithObjects(GObjectTypes::PHYLOGENETIC_TREE, &multiSelection, UOF_LoadedAndUnloaded, false); QList resTasks; foreach(Document* doc, docsWithPhy) { QList docObjs = doc->findGObjectByType(GObjectTypes::PHYLOGENETIC_TREE, UOF_LoadedAndUnloaded); if (!docObjs.isEmpty()) { foreach(GObject* obj, docObjs){ if(!phyObjects.contains(obj)){ phyObjects.append(obj); } } } else { resTasks.append(new OpenTreeViewerTask(doc)); if (resTasks.size() == MAX_VIEWS) { break; } } } if (!phyObjects.isEmpty()) { foreach(GObject* o, phyObjects) { if (resTasks.size() == MAX_VIEWS) { break; } if (o->getGObjectType() == GObjectTypes::UNLOADED) { resTasks.append(new OpenTreeViewerTask(qobject_cast(o))); } else { assert(o->getGObjectType() == GObjectTypes::PHYLOGENETIC_TREE); resTasks.append(new OpenTreeViewerTask(qobject_cast(o))); } } } if (resTasks.isEmpty()) { return NULL; } if (resTasks.size() == 1 || single) { return resTasks.first(); } Task* result = new Task(tr("Open multiple views"), TaskFlag_NoRun); foreach(Task* t, resTasks) { result->addSubTask(t); } return result; } bool TreeViewerFactory::isStateInSelection(const MultiGSelection& multiSelection, const QVariantMap& stateData) { TreeViewerState state(stateData); if (!state.isValid()) { return false; } GObjectReference ref = state.getPhyObject(); Document* doc = AppContext::getProject()->findDocumentByURL(ref.docUrl); if (doc == NULL) { //todo: accept to use invalid state removal routines of ObjectViewTask ??? return false; } //check that document is in selection QList selectedDocs = SelectionUtils::getSelectedDocs(multiSelection); if (selectedDocs.contains(doc)) { return true; } //check that object is in selection QList selectedObjects = SelectionUtils::getSelectedObjects(multiSelection); GObject* obj = doc->findGObjectByName(ref.objName); bool res = obj != NULL && selectedObjects.contains(obj); return res; } Task* TreeViewerFactory::createViewTask(const QString& viewName, const QVariantMap& stateData) { return new OpenSavedTreeViewerTask(viewName, stateData); } }//namespace ugene-1.9.8/src/corelibs/U2View/src/util_ov_phyltree/CreateRectangularBranchesTask.h0000644000175000017500000000263111651544334027255 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_CREATE_RECTANGULAR_BRANCHES_TASK_H_ #define _U2_CREATE_RECTANGULAR_BRANCHES_TASK_H_ #include "CreateBranchesTask.h" namespace U2 { class PhyNode; class GraphicsRectangularBranchItem; class CreateRectangularBranchesTask: public CreateBranchesTask { Q_OBJECT int size; int current; qreal scale; PhyNode* node; qreal minDistance, maxDistance; GraphicsRectangularBranchItem* getBranch(PhyNode *node); public: CreateRectangularBranchesTask(PhyNode *n); void run(); qreal getScale() { return scale; } }; }//namespace; #endif ugene-1.9.8/src/corelibs/U2View/src/util_ov_phyltree/CreateUnrootedBranchesTask.cpp0000644000175000017500000000350311651544334027137 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include #include "CreateUnrootedBranchesTask.h" #include "GraphicsUnrootedBranchItem.h" #include "GraphicsRectangularBranchItem.h" #include #include "TreeViewerUtils.h" namespace U2 { CreateUnrootedBranchesTask::CreateUnrootedBranchesTask(GraphicsRectangularBranchItem *r): root1(r) {} GraphicsUnrootedBranchItem* CreateUnrootedBranchesTask::getBranch(GraphicsRectangularBranchItem *from, GraphicsUnrootedBranchItem* parent) { GraphicsUnrootedBranchItem* res = new GraphicsUnrootedBranchItem(parent, coef * from->getHeight(), from); foreach (QGraphicsItem* item, from->childItems()) { GraphicsRectangularBranchItem* ri = dynamic_cast(item); if (ri != NULL) { getBranch(ri, res); } } res->setCorrespondingItem(from); return res; } void CreateUnrootedBranchesTask::run() { coef = 360.0 / root1->childrenBoundingRect().height(); root = getBranch(root1, NULL); } } ugene-1.9.8/src/corelibs/U2View/src/util_ov_phyltree/TreeViewerUtils.cpp0000644000175000017500000000476411651544334025037 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "TreeViewerUtils.h" #include #include #include #define IMAGE_DIR "image" namespace U2 { QFont* TreeViewerUtils::font = NULL; const char* TreeViewerUtils::IMAGE_FILTERS = "BMP - Windows Bitmap (*.bmp);;" "GIF - Graphic Interchange Format (*.gif);;" "JPG/JPEG format (*.jpg);;" "PBM - Portable Bitmap (*.pbm);;" "PNG - Portable Network Graphics (*.png);;" "PPM - Portable Pixmap (*.ppm);;" "TIFF - Tagged Image File format (*.tif);;" "XBM - X11 Bitmap (*.xbm);;" "XPM - X11 Pixmap (*.xpm)"; void TreeViewerUtils::saveImageDialog(const QString& filters, QString &fileName, QString &format) { LastOpenDirHelper lod(IMAGE_DIR); int i = fileName.lastIndexOf('.'); if (i != -1) { fileName = fileName.left(i); } QString initialPath = lod.dir + "/" + fileName; fileName = QFileDialog::getSaveFileName(NULL, QObject::tr("Save As"), initialPath, filters, &format); lod.url = fileName; if (fileName.isEmpty()) return; format = format.left(3).toLower(); if (!fileName.endsWith("." + format)) { fileName.append("." + format); if (QFile::exists(fileName)) { QMessageBox::StandardButtons b = QMessageBox::warning(0, QObject::tr("Replace file"), QObject::tr("%1 already exists.\nDo you want to replace it?").arg(fileName), QMessageBox::Yes | QMessageBox::No); if (QMessageBox::Yes != b) { return; } } } } const QFont& TreeViewerUtils::getFont() { if (font == NULL) { font = new QFont(); } return *font; } } ugene-1.9.8/src/corelibs/U2View/src/util_ov_phyltree/TreeViewerFactory.h0000644000175000017500000000311711651544334025002 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_TREE_VIEWER_FACTORY_H_ #define _U2_TREE_VIEWER_FACTORY_H_ #include namespace U2 { class MultiGSelection; class U2VIEW_EXPORT TreeViewerFactory : public GObjectViewFactory { Q_OBJECT public: TreeViewerFactory(); virtual bool canCreateView(const MultiGSelection& multiSelection); virtual Task* createViewTask(const MultiGSelection& multiSelection, bool single = false); virtual bool isStateInSelection(const MultiGSelection& multiSelection, const QVariantMap& stateData); virtual Task* createViewTask(const QString& viewName, const QVariantMap& stateData); virtual bool supportsSavedStates() const {return true;} static const GObjectViewFactoryId ID; }; } // namespace #endif ugene-1.9.8/src/corelibs/U2View/src/util_ov_phyltree/GraphicsRectangularBranchItem.cpp0000644000175000017500000002210711651544334027611 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "GraphicsRectangularBranchItem.h" #include "GraphicsButtonItem.h" #include "TreeViewerUtils.h" #include #include #include #include #include #include #include #include namespace U2 { const qreal GraphicsRectangularBranchItem::DEFAULT_WIDTH = 25.0; const qreal GraphicsRectangularBranchItem::MAXIMUM_WIDTH = 500.0; const int GraphicsRectangularBranchItem::DEFAULT_HEIGHT = 25; const qreal GraphicsRectangularBranchItem::EPSILON = 0.0000000001; void GraphicsRectangularBranchItem::collapse() { collapsed = !collapsed; QList items = childItems(); if (collapsed) { int xmin = 0; qreal ymin = items[0]->pos().y(), ymax = 0; for (int i = 0, s = items.size(); i < s; ++i) { if (!dynamic_cast(items[i])) continue; QPointF pos1 = items[i]->pos(); if (pos1.x() < xmin || xmin == 0) xmin = pos1.x(); if (pos1.y() < ymin) ymin = pos1.y(); if (pos1.y() > ymax) ymax = pos1.y(); if (items[i] != getDistanceText() && items[i] != getNameText()) { items[i]->hide(); } } if (xmin >= 2 * GraphicsRectangularBranchItem::DEFAULT_WIDTH) xmin /= 2; if (xmin < GraphicsRectangularBranchItem::DEFAULT_WIDTH) xmin = GraphicsRectangularBranchItem::DEFAULT_WIDTH; QPen pen1(QColor(0, 0, 0)); prepareGeometryChange(); pen1.setWidth(SelectedPenWidth); pen1.setCosmetic(true); const int defHeight = qMin((int)(ymax - ymin) / 2, 30); QGraphicsRectItem *r = new QGraphicsRectItem(0, -defHeight / 2, xmin, defHeight, this); r->setPen(pen1); } else { for (int i = 0, s = items.size(); i < s; ++i) { if (dynamic_cast(items[i])) { items[i]->setParentItem(NULL); scene()->removeItem(items[i]); } else { if (items[i] != getDistanceText() && items[i] != getNameText()) { items[i]->show(); } } } setSelectedRecurs(true,true); } scene()->update(); } GraphicsRectangularBranchItem::GraphicsRectangularBranchItem(const QString& name, GraphicsRectangularBranchItem* pitem) : GraphicsBranchItem(name), cur_height_coef(1), direction(GraphicsRectangularBranchItem::up) { setParentItem(pitem); setPos(0, 0); height = 0; phyBranch = NULL; } GraphicsRectangularBranchItem::GraphicsRectangularBranchItem(qreal x, qreal y, const QString& name) : GraphicsBranchItem(false), cur_height_coef(1), direction(GraphicsRectangularBranchItem::up) { new GraphicsRectangularBranchItem(name, this); setPos(x, y); phyBranch = NULL; } GraphicsRectangularBranchItem::GraphicsRectangularBranchItem(qreal x, qreal y, const QString& name, qreal d) : GraphicsBranchItem(d, false), cur_height_coef(1), direction(GraphicsRectangularBranchItem::up) { new GraphicsRectangularBranchItem(name, this); setPos(x, y); phyBranch = NULL; } GraphicsRectangularBranchItem::GraphicsRectangularBranchItem(qreal d) : GraphicsBranchItem(d), cur_height_coef(1), direction(GraphicsRectangularBranchItem::up), phyBranch(NULL) {} GraphicsRectangularBranchItem::GraphicsRectangularBranchItem() : cur_height_coef(1), direction(GraphicsRectangularBranchItem::up), phyBranch(NULL) {} void GraphicsRectangularBranchItem::setParentItem(QGraphicsItem *item) { prepareGeometryChange(); height = direction == up ? pos().y() - item->pos().y() : item->pos().y() - pos().y(); setPos(width, direction == up ? height : -height); QAbstractGraphicsShapeItem::setParentItem(item); } void GraphicsRectangularBranchItem::setDirection(Direction d) { prepareGeometryChange(); direction = d; } QRectF GraphicsRectangularBranchItem::boundingRect() const { return QRectF(- width - 0.5, direction == up ? -height: -0.5, width + 0.5, height + 0.5); } void GraphicsRectangularBranchItem::paint(QPainter *painter, const QStyleOptionGraphicsItem*, QWidget*) { painter->setPen(pen()); painter->drawLine(QPointF(0, 0), QPointF(-width, 0)); painter->drawLine(QPointF(-width, 0), QPointF(-width, direction == up ? -height : height)); } void GraphicsRectangularBranchItem::setHeight(qreal h) { if (height == h) { return; } if (direction == up) { setPos(pos().x(), pos().y() - height + h); }else{ setPos(pos().x(), pos().y() + height - h); } prepareGeometryChange(); height = h; } void GraphicsRectangularBranchItem::setHeightCoef(int coef){ if(coef == cur_height_coef){ return ; } qreal h = (height / (qreal)cur_height_coef) * coef; cur_height_coef = coef; setHeight(h); } void GraphicsRectangularBranchItem::swapSiblings() { if (!phyBranch) { return ; } PhyNode* nodeTo = phyBranch->node2; int branchCount = nodeTo->branches.count(); if (branchCount > 2) { nodeTo->branches.swap(0, 2); } } void GraphicsRectangularBranchItem::redrawBranches(int& current, qreal& minDistance, qreal& maxDistance, PhyNode* root){ assert(this); int branches = 0; PhyNode* node = NULL; if(phyBranch){ node = phyBranch->node2; }else if(root){ node = root; } if (node == NULL) { return ; } branches = node->branches.size(); if(branches > 1){ QList items; for (int i = 0; i < branches; ++i) { if (node->branches[i]->node2 != node) { GraphicsRectangularBranchItem *item = getChildItemByPhyBranch(node->branches[i]); item->redrawBranches(current, minDistance, maxDistance, NULL); items.append(item); } else { items.append(NULL); } } int size = items.size(); assert(size > 0); GraphicsRectangularBranchItem *item = this; { int xmin = 0, ymin = items[0] ? items[0]->pos().y() : items[1]->pos().y(), ymax = 0; for (int i = 0; i < size; ++i) { if (items[i] == NULL) { continue; } QPointF pos1 = items[i]->pos(); if (pos1.x() < xmin) xmin = pos1.x(); if (pos1.y() < ymin) ymin = pos1.y(); if (pos1.y() > ymax) ymax = pos1.y(); } xmin -= GraphicsRectangularBranchItem::DEFAULT_WIDTH; int y = (ymax + ymin) / 2; item->setPos(xmin, y); for (int i = 0; i < size; ++i) { if (items[i] == NULL) { continue; } qreal dist = qAbs(node->branches[i]->distance); if (minDistance > -1) { minDistance = qMin(minDistance, dist); } else { minDistance = dist; } maxDistance = qMax(maxDistance, dist); items[i]->setDirection(items[i]->pos().y() > y ? GraphicsRectangularBranchItem::up : GraphicsRectangularBranchItem::down); items[i]->setWidthW(dist); items[i]->setDist(dist); items[i]->setHeightCoefW(1); items[i]->setParentItem(item); QRectF rect = items[i]->getDistanceText()->boundingRect(); items[i]->getDistanceText()->setPos(-(items[i]->getWidth() + rect.width()) / 2, 0); } } }else{ int y = (current++ + 0.5) * GraphicsRectangularBranchItem::DEFAULT_HEIGHT; setPos(0,y); } } GraphicsRectangularBranchItem* GraphicsRectangularBranchItem::getChildItemByPhyBranch(const PhyBranch* branch){ foreach (QGraphicsItem* ci, this->childItems()) { GraphicsRectangularBranchItem* gbi = dynamic_cast(ci); if (gbi != NULL) { if(gbi->getPhyBranch() == branch){ return gbi; } } } return NULL; } }//namespace ugene-1.9.8/src/corelibs/U2View/src/util_ov_phyltree/TreeViewer.cpp0000644000175000017500000010773011651544334024013 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "TreeViewer.h" #include "TreeViewerFactory.h" #include "GraphicsBranchItem.h" #include "GraphicsButtonItem.h" #include "TreeViewerUtils.h" #include "CreateBranchesTask.h" #include "CreateCircularBranchesTask.h" #include "CreateUnrootedBranchesTask.h" #include "CreateRectangularBranchesTask.h" #include "GraphicsRectangularBranchItem.h" #include "TreeViewerTasks.h" #include "TreeViewerState.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include namespace U2 { TreeViewer::TreeViewer(const QString& viewName, GObject* obj, GraphicsRectangularBranchItem* _root, qreal s): GObjectView(TreeViewerFactory::ID, viewName), treeSettingsAction(NULL), layoutGroup(NULL), rectangularLayoutAction(NULL), circularLayoutAction(NULL), unrootedLayoutAction(NULL), branchesSettingsAction(NULL), nameLabelsAction(NULL), distanceLabelsAction(NULL), textSettingsAction(NULL), contAction(NULL), zoomToSelAction(NULL), zoomToAllAction(NULL), zoomOutAction(NULL), printAction(NULL), captureTreeAction(NULL), exportAction(NULL), ui(NULL), root(_root), scale(s) { phyObject = qobject_cast(obj); objects.append(phyObject); requiredObjects.append(phyObject); onObjectAdded(phyObject); } QTransform TreeViewer::getTransform() const { return ui->transform(); } void TreeViewer::setTransform(const QTransform& m) { ui->setTransform(m); } QVariantMap TreeViewer::saveState() { return TreeViewerState::saveState(this); } qreal TreeViewer::getZoom() const { return ui->getZoom(); } void TreeViewer::setZoom(qreal z) { ui->setZoom(z); } QVariantMap TreeViewer::getSettingsState() const { return ui->getSettingsState(); } void TreeViewer::setSettingsState(const QVariantMap& m) { ui->setSettingsState(m); } Task* TreeViewer::updateViewTask(const QString& stateName, const QVariantMap& stateData) { return new UpdateTreeViewerTask(this, stateName, stateData); } void TreeViewer::createActions() { // Tree Settings treeSettingsAction = new QAction(QIcon(":core/images/phylip.png"), tr("Tree Settings..."), ui); // Layout layoutGroup = new QActionGroup(ui); rectangularLayoutAction = new QAction(tr("Rectangular"), layoutGroup); rectangularLayoutAction->setCheckable(true); rectangularLayoutAction->setChecked(true); circularLayoutAction = new QAction(tr("Circular"), layoutGroup); circularLayoutAction->setCheckable(true); unrootedLayoutAction = new QAction(tr("Unrooted"), layoutGroup); unrootedLayoutAction->setCheckable(true); // Branch Settings branchesSettingsAction = new QAction(QIcon(":core/images/color_wheel.png"), tr("Branch Settings..."), ui); // Show Labels nameLabelsAction = new QAction(tr("Show Names"), ui); nameLabelsAction->setCheckable(true); nameLabelsAction->setChecked(true); distanceLabelsAction = new QAction(tr("Show Distances"), ui); distanceLabelsAction->setCheckable(true); distanceLabelsAction->setChecked(true); // Formatting textSettingsAction = new QAction(QIcon(":core/images/font.png"), tr("Formatting..."), ui); // Align Labels // Note: the icon is truncated to 15 px height to look properly in the main menu when it is checked contAction = new QAction(QIcon(":core/images/align_tree_labels.png"), tr("Align Labels"), ui); contAction->setCheckable(true); // Zooming zoomToSelAction = new QAction(QIcon(":core/images/zoom_in.png"), tr("Zoom In") , ui); zoomOutAction = new QAction(QIcon(":core/images/zoom_out.png"), tr("Zoom Out"), ui); zoomToAllAction = new QAction(QIcon(":core/images/zoom_whole.png"), tr("Reset Zooming"), ui); // Print Tree printAction = new QAction(QIcon(":/core/images/printer.png"), tr("Print Tree..."), ui); // Screen Capture captureTreeAction = new QAction(tr("Screen Capture..."), ui); exportAction = new QAction(tr("Whole Tree as SVG..."), ui); } void TreeViewer::setupLayoutSettingsMenu(QMenu* m) { m->addActions(layoutGroup->actions()); } void TreeViewer::setupShowLabelsMenu(QMenu* m) { m->addAction(nameLabelsAction); m->addAction(distanceLabelsAction); } void TreeViewer::setupCameraMenu(QMenu* m) { m->addAction(captureTreeAction); m->addAction(exportAction); } void TreeViewer::buildStaticToolbar(QToolBar* tb) { // Tree Settings tb->addAction(treeSettingsAction); // Layout QToolButton* layoutButton = new QToolButton(tb); QMenu* layoutMenu = new QMenu(tr("Layout"), ui); setupLayoutSettingsMenu(layoutMenu); layoutButton->setDefaultAction(layoutMenu->menuAction()); layoutButton->setPopupMode(QToolButton::InstantPopup); layoutButton->setIcon(QIcon(":core/images/tree_layout.png")); tb->addWidget(layoutButton); // Branch Settings tb->addAction(branchesSettingsAction); // Labels and Text Settings tb->addSeparator(); QToolButton* showLabelsButton = new QToolButton(); QMenu* showLabelsMenu = new QMenu(tr("Show Labels"), ui); setupShowLabelsMenu(showLabelsMenu); showLabelsButton->setDefaultAction(showLabelsMenu->menuAction()); showLabelsButton->setPopupMode(QToolButton::InstantPopup); showLabelsButton->setIcon(QIcon(":/core/images/text_ab.png")); tb->addWidget(showLabelsButton); tb->addAction(textSettingsAction); tb->addAction(contAction); // Zooming tb->addSeparator(); tb->addAction(zoomToSelAction); tb->addAction(zoomOutAction); tb->addAction(zoomToAllAction); // Print and Capture tb->addSeparator(); tb->addAction(printAction); QToolButton* cameraButton = new QToolButton(); QMenu* cameraMenu = new QMenu(tr("Export Tree Image"), ui); setupCameraMenu(cameraMenu); cameraButton->setDefaultAction(cameraMenu->menuAction()); cameraButton->setPopupMode(QToolButton::InstantPopup); cameraButton->setIcon(QIcon(":/core/images/cam2.png")); tb->addWidget(cameraButton); } void TreeViewer::buildStaticMenu(QMenu* m) { // Tree Settings m->addAction(treeSettingsAction); // Layout QMenu* layoutMenu = new QMenu(tr("Layout"), ui); setupLayoutSettingsMenu(layoutMenu); layoutMenu->setIcon(QIcon(":core/images/tree_layout.png")); m->addMenu(layoutMenu); // Branch Settings m->addAction(branchesSettingsAction); // Labels and Text Settings m->addSeparator(); QMenu* labelsMenu = new QMenu(tr("Show Labels"), ui); setupShowLabelsMenu(labelsMenu); labelsMenu->setIcon(QIcon(":/core/images/text_ab.png")); m->addMenu(labelsMenu); m->addAction(textSettingsAction); m->addAction(contAction); // Zooming m->addSeparator(); m->addAction(zoomToSelAction); m->addAction(zoomOutAction); m->addAction(zoomToAllAction); // Print and Capture m->addSeparator(); m->addAction(printAction); QMenu* cameraMenu = new QMenu(tr("Export Tree Image"), ui); setupCameraMenu(cameraMenu); cameraMenu->setIcon(QIcon(":/core/images/cam2.png")); m->addMenu(cameraMenu); m->addSeparator(); GObjectView::buildStaticMenu(m); GUIUtils::disableEmptySubmenus(m); } QWidget* TreeViewer::createWidget() { assert(ui == NULL); ui = new TreeViewerUI(this); return ui; } void TreeViewer::onObjectRenamed(GObject*, const QString&) { // update title OpenTreeViewerTask::updateTitle(this); } //////////////////////////// // TreeViewerUI const qreal TreeViewerUI::ZOOM_COEF = 1.2; const qreal TreeViewerUI::MINIMUM_ZOOM = 1.0; const qreal TreeViewerUI::MAXIMUM_ZOOM = 10.0; const int TreeViewerUI::MARGIN = 10; const qreal TreeViewerUI::SIZE_COEF = 0.1; TreeViewerUI::TreeViewerUI(TreeViewer* treeViewer): phyObject(treeViewer->getPhyObject()), root(treeViewer->getRoot()), rectRoot(treeViewer->getRoot()), layout(TreeLayout_Rectangular), curTreeViewer(NULL) { curTreeViewer = treeViewer; contEnabled = false; showDistanceLabels = true; showNameLabels = true; maxNameWidth = 0; zoom = 1.0; setWindowIcon(GObjectTypes::getTypeInfo(GObjectTypes::PHYLOGENETIC_TREE).icon); setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOn); setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn); setFrameShape(QFrame::NoFrame); setTransformationAnchor(QGraphicsView::AnchorUnderMouse); setScene(new QGraphicsScene()); scene()->addItem(root); setScale(treeViewer->getScale()); addLegend(treeViewer->getScale()); updateRect(); treeViewer->createActions(); connect(treeViewer->getNameLabelsAction(), SIGNAL(triggered(bool)), SLOT(sl_showNameLabelsTriggered(bool))); connect(treeViewer->getDistanceLabelsAction(), SIGNAL(triggered(bool)), SLOT(sl_showDistanceLabelsTriggered(bool))); connect(treeViewer->getPrintAction(), SIGNAL(triggered()), SLOT(sl_printTriggered())); connect(treeViewer->getCaptureTreeAction(), SIGNAL(triggered()), SLOT(sl_captureTreeTriggered())); connect(treeViewer->getExportAction(), SIGNAL(triggered()), SLOT(sl_exportTriggered())); connect(treeViewer->getContAction(), SIGNAL(triggered(bool)), SLOT(sl_contTriggered(bool))); connect(treeViewer->getRectangularLayoutAction(), SIGNAL(triggered(bool)), SLOT(sl_rectangularLayoutTriggered())); connect(treeViewer->getCircularLayoutAction(), SIGNAL(triggered(bool)), SLOT(sl_circularLayoutTriggered())); connect(treeViewer->getUnrootedLayoutAction(), SIGNAL(triggered(bool)), SLOT(sl_unrootedLayoutTriggered())); connect(treeViewer->getTextSettingsAction(), SIGNAL(triggered()), SLOT(sl_textSettingsTriggered())); connect(treeViewer->getTreeSettingsAction(), SIGNAL(triggered()), SLOT(sl_treeSettingsTriggered())); connect(treeViewer->getZoomToSelAction(), SIGNAL(triggered()), SLOT(sl_zoomToSel())); connect(treeViewer->getZoomOutAction(), SIGNAL(triggered()), SLOT(sl_zoomOut())); connect(treeViewer->getZoomToAllAction(), SIGNAL(triggered()), SLOT(sl_zoomToAll())); connect(treeViewer->getBranchesSettingsAction(), SIGNAL (triggered()), SLOT(sl_setSettingsTriggered())); zoomToAction = treeViewer->getZoomToSelAction(); zoomOutAction = treeViewer->getZoomOutAction(); zoomToAllAction = treeViewer->getZoomToAllAction(); setColorAction = treeViewer->getBranchesSettingsAction(); captureAction = treeViewer->getCaptureTreeAction(); exportAction = treeViewer->getExportAction(); buttonPopup = new QMenu(this); //chrootAction->setEnabled(false); //not implemented yet swapAction = buttonPopup->addAction(QObject::tr("Swap Siblings")); connect(swapAction, SIGNAL(triggered(bool)), SLOT(sl_swapTriggered())); buttonPopup->addAction(zoomToAction); collapseAction = buttonPopup->addAction(QObject::tr("Collapse")); connect(collapseAction, SIGNAL(triggered(bool)), SLOT(sl_collapseTriggered())); buttonPopup->addAction(setColorAction); QMenu* cameraMenu = new QMenu(tr("Export Tree Image"), this); cameraMenu->addAction(captureAction); cameraMenu->addAction(exportAction); cameraMenu->setIcon(QIcon(":/core/images/cam2.png")); buttonPopup->addMenu(cameraMenu); updateActionsState(); } TreeViewerUI::~TreeViewerUI() { delete scene(); } BranchSettings TreeViewerUI::getBranchSettings() const { return branchSettings; } ButtonSettings TreeViewerUI::getButtonSettings() const { return buttonSettings; } TextSettings TreeViewerUI::getTextSettings() const { return textSettings; } TreeSettings TreeViewerUI::getTreeSettings() const { return treeSettings; } void TreeViewerUI::updateSettings(const BranchSettings &settings) { branchSettings = settings; updateSettings(); } void TreeViewerUI::updateSettings(const ButtonSettings &settings) { buttonSettings = settings; updateSettings(); } void TreeViewerUI::updateSettings(const TextSettings &settings) { textSettings = settings; updateTextSettings(); } void TreeViewerUI::updateSettings(const TreeSettings &settings) { treeSettings = settings; if(layout!=TreeLayout_Rectangular){ updateLayout(); }else{ updateTreeSettings(); } } void TreeViewerUI::sl_setSettingsTriggered() { sl_branchSettings(); } void TreeViewerUI::sl_branchSettings() { BranchSettingsDialog d(this, getBranchSettings()); if (d.exec()) { updateSettings( d.getSettings() ); } } void TreeViewerUI::updateSettings() { QList updatingItems = this->scene()->selectedItems(); if(updatingItems.isEmpty()){ updatingItems = this->items(); QGraphicsLineItem* legendLine = dynamic_cast(legend); if(legendLine){ QPen legendPen; legendPen.setColor(branchSettings.branchColor); legendLine->setPen(legendPen); } } foreach (QGraphicsItem *graphItem, updatingItems) { GraphicsBranchItem *branchItem = dynamic_cast(graphItem); if (branchItem) { branchItem->updateSettings(branchSettings); if(branchItem->getCorrespondingItem()){ branchItem->getCorrespondingItem()->updateSettings(branchSettings); } } scene()->update(); } } void TreeViewerUI::updateTextSettings(){ QList updatingItems = this->scene()->selectedItems(); if(updatingItems.isEmpty()){ updatingItems = this->items(); QList legendChildItems = legend->children(); if(!legendChildItems.isEmpty()){ QGraphicsSimpleTextItem* legendText = dynamic_cast(legendChildItems.first()); if(legendText){ legendText->setBrush(textSettings.textColor); } } } foreach (QGraphicsItem *graphItem, updatingItems) { GraphicsBranchItem *branchItem = dynamic_cast(graphItem); if (branchItem) { branchItem->updateTextSettings(textSettings.textFont, textSettings.textColor); if(branchItem->getCorrespondingItem()){ branchItem->getCorrespondingItem()->updateTextSettings(textSettings.textFont, textSettings.textColor); } } //scene()->update(); } updateLayout(); updateTreeSettings(); } void TreeViewerUI::updateTreeSettings(){ qreal avgW = 0; if(treeSettings.type == TreeSettings::CLADOGRAM){ avgW = avgWidth(); legend->setVisible(false); }else{ legend->setVisible(true); } QStack stack; stack.push(rectRoot); while (!stack.empty()) { GraphicsBranchItem *item = stack.pop(); if(item!=rectRoot){ if(layout == TreeLayout_Rectangular){ GraphicsRectangularBranchItem *rectItem = dynamic_cast(item); if(rectItem){ rectItem->setHeightCoef(treeSettings.height_coef); } } qreal coef = qMax(1.0, TreeViewerUI::SIZE_COEF*treeSettings.width_coef); switch (treeSettings.type) { case TreeSettings::PHYLOGRAM: if(item->getDistanceText() != NULL){ if(item->getDistanceText()->text() == "0"){ item->setDistanceText(""); } } item->setWidth(qAbs(item->getDist()) * getScale()* coef); break; case TreeSettings::CLADOGRAM: if(item->getDistanceText() != NULL){ if(item->getDistanceText()->text() == ""){ item->setDistanceText("0"); } } item->setWidth(avgW * getScale()* coef); break; default: assert(false && "Unexpected tree type value"); break; } } foreach (QGraphicsItem* ci, item->childItems()) { GraphicsBranchItem* gbi = dynamic_cast(ci); if (gbi != NULL) { stack.push(gbi); } } } updateRect(); scene()->update(); if(contEnabled){ QStack stack; stack.push(root); if (root != rectRoot) { stack.push(rectRoot); } while (!stack.empty()) { GraphicsBranchItem* item = stack.pop(); if (item->getNameText() == NULL) { foreach (QGraphicsItem* citem, item->childItems()) { GraphicsBranchItem* gbi = dynamic_cast(citem); if (gbi != NULL) { stack.push(gbi); } } } else { item->setWidth(0); } } updateRect(); contEnabled = false; sl_contTriggered(true); } defaultZoom(); fitInView(scene()->sceneRect(), Qt::KeepAspectRatio); } #define BRANCH_COLOR QString("branch_color") #define BRANCH_THICKNESS QString("branch_thickness") QVariantMap TreeViewerUI::getSettingsState() const { QVariantMap m; int i=0; foreach (QGraphicsItem *graphItem, this->items()) { GraphicsBranchItem *branchItem = dynamic_cast(graphItem); if (branchItem) { m[BRANCH_COLOR + i] = branchItem->settings.branchColor; m[BRANCH_THICKNESS + i] = branchItem->settings.branchThickness; i++; } } return m; } void TreeViewerUI::setSettingsState(const QVariantMap& m) { int i=0; foreach (QGraphicsItem *graphItem, this->items()) { GraphicsBranchItem *branchItem = dynamic_cast(graphItem); if (branchItem) { BranchSettings branchSettings = branchItem->settings; QVariant vColor = m[BRANCH_COLOR + i]; if (vColor.type() == QVariant::Color) { branchSettings.branchColor = vColor.value(); } QVariant vThickness = m[BRANCH_THICKNESS + i]; if (vThickness.type() == QVariant::Int) { branchSettings.branchThickness = vThickness.toInt(); } branchItem->updateSettings(branchSettings); i++; } } } void TreeViewerUI::addLegend(qreal scale) { static const qreal WIDTH = 30.0; qreal d = WIDTH / scale; QString str = QString::number(d, 'f', 3); int i = str.length() - 1; for (; i >= 0 && str[i] == '0'; --i) ; if (str[i] == '.') --i; str.truncate(i + 1); legend = new QGraphicsLineItem(0, 0, WIDTH, 0); QGraphicsSimpleTextItem* text = new QGraphicsSimpleTextItem(str, legend); text->setFont(TreeViewerUtils::getFont()); QRectF rect = text->boundingRect(); text->setPos(0.5 * (WIDTH - rect.width()), -rect.height()); scene()->addItem(legend); } void TreeViewerUI::wheelEvent(QWheelEvent *we) { qreal zoom1 = pow(ZOOM_COEF, we->delta() / 120.0); zooming(zoom1); we->accept(); } void TreeViewerUI::zooming(qreal newzoom){ if(newzoom < 0){ return ; } newzoom = zoom * newzoom; newzoom = qMax(MINIMUM_ZOOM, newzoom); newzoom = qMin(MAXIMUM_ZOOM * qMax(treeSettings.width_coef*TreeViewerUI::SIZE_COEF, 1.0), newzoom); scale(newzoom / zoom, newzoom / zoom); zoom = newzoom; updateActionsState(); } void TreeViewerUI::mousePressEvent(QMouseEvent *e) { bool shiftPressed = e->modifiers() & Qt::ShiftModifier; bool leftButton = e->button() == Qt::LeftButton; if (leftButton) { setDragMode(QGraphicsView::ScrollHandDrag); } if (leftButton && !shiftPressed) { root->setSelectedRecurs(false, true); // clear selection } if (e->button() == Qt::RightButton) { updateActionsState(); buttonPopup->popup(e->globalPos()); e->accept(); return; } QGraphicsView::mousePressEvent(e); } void TreeViewerUI::mouseReleaseEvent(QMouseEvent *e) { bool leftButton = e->button() == Qt::LeftButton; if (leftButton) { setDragMode(QGraphicsView::NoDrag); } e->accept(); } void TreeViewerUI::resizeEvent(QResizeEvent *e) { QRectF rect = scene()->sceneRect(); rect.setWidth(rect.width() / zoom); rect.setHeight(rect.height() / zoom); rect.moveCenter(scene()->sceneRect().center()); fitInView(rect, Qt::KeepAspectRatio); QGraphicsView::resizeEvent(e); } // needed to export tree void TreeViewerUI::paint(QPainter &painter) { painter.setBrush(Qt::darkGray); painter.setFont(TreeViewerUtils::getFont()); scene()->render(&painter); } void TreeViewerUI::updateRect() { QRectF rect = root->mapToScene(root->childrenBoundingRect().united(root->boundingRect())).boundingRect(); rect.setLeft(rect.left() - MARGIN); rect.setRight(rect.right() - (showNameLabels ? 0 : maxNameWidth) + MARGIN); rect.setTop(rect.top() - MARGIN); rect.setBottom(rect.bottom() + legend->childrenBoundingRect().height() + MARGIN); legend->setPos(0, rect.bottom() - MARGIN); scene()->setSceneRect(rect); } void TreeViewerUI::sl_chrootTriggered() { //Q_ASSERT(0); } void TreeViewerUI::sl_swapTriggered() { foreach (QGraphicsItem *graphItem, this->items()) { GraphicsButtonItem *buttonItem = dynamic_cast(graphItem); if (buttonItem && buttonItem->isSelectedTop()) { buttonItem->swapSiblings(); break; } } redrawRectangularLayout(); updateLayout(); updateTreeSettings(); } void TreeViewerUI::collapseSelected() { foreach (QGraphicsItem *graphItem, this->items()) { GraphicsButtonItem *buttonItem = dynamic_cast(graphItem); if (buttonItem && buttonItem->isSelectedTop()) { buttonItem->collapse(); } } } bool TreeViewerUI::isSelectedCollapsed(){ foreach (QGraphicsItem *graphItem, this->items()) { GraphicsButtonItem *buttonItem = dynamic_cast(graphItem); if (buttonItem && buttonItem->isSelectedTop()) { return buttonItem->isCollapsed(); } } return false; } void TreeViewerUI::sl_collapseTriggered() { collapseSelected(); } void TreeViewerUI::sl_captureTreeTriggered() { this->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); this->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff); ExportImageDialog dialog(this,this->rect(),false,true,phyObject->getDocument()->getURL().baseFileName()); dialog.exec(); this->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOn); this->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn); } void TreeViewerUI::sl_exportTriggered() { QString fileName = phyObject->getDocument()->getName(); QString format = "SVG - Scalable Vector Graphics (*.svg)"; TreeViewerUtils::saveImageDialog(format, fileName, format); if (!fileName.isEmpty()) { QRect rect = scene()->sceneRect().toRect(); rect.moveTo(0, 0); QSvgGenerator generator; generator.setFileName(fileName); generator.setSize(rect.size()); generator.setViewBox(rect); QPainter painter; painter.begin(&generator); paint(painter); painter.end(); } } void TreeViewerUI::sl_contTriggered(bool on) { if (on != contEnabled) { contEnabled = on; QStack stack; stack.push(root); if (root != rectRoot) { stack.push(rectRoot); } while (!stack.empty()) { GraphicsBranchItem* item = stack.pop(); if (item->getNameText() == NULL) { foreach (QGraphicsItem* citem, item->childItems()) { GraphicsBranchItem* gbi = dynamic_cast(citem); if (gbi != NULL) { stack.push(gbi); } } } else { qreal nWidth = 0; if(on){ qreal scW = scene()->sceneRect().width(); qreal scL = scene()->sceneRect().left(); qreal textScPosX = item->getNameText()->scenePos().x(); nWidth = scW + scL - textScPosX; if (showNameLabels){ qreal textBRW = item->getNameText()->boundingRect().width(); nWidth -= textBRW + GraphicsBranchItem::TextSpace; } } // // //test // QGraphicsItem* pitem = item->parentItem(); // GraphicsBranchItem* grPItem = dynamic_cast(pitem); // if(grPItem){ // if(grPItem->getDistanceText()!= NULL && grPItem->getDistanceText()->text() == ""){ // nWidth+=8; // } // } // //test item->setWidth(nWidth); } } updateRect(); } } void TreeViewerUI::sl_rectangularLayoutTriggered() { if (layout != TreeLayout_Rectangular) { swapAction->setEnabled(true); root->setSelectedRecurs(false, true); // clear selection layout = TreeLayout_Rectangular; scene()->removeItem(root); if(!rectRoot){ redrawRectangularLayout(); } root = rectRoot; scene()->addItem(root); defaultZoom(); updateRect(); updateTreeSettings(); fitInView(scene()->sceneRect(), Qt::KeepAspectRatio); } } void TreeViewerUI::sl_circularLayoutTriggered() { if (layout != TreeLayout_Circular) { //swapAction->setEnabled(false); root->setSelectedRecurs(false, true); // clear selection layout = TreeLayout_Circular; updateTreeSettings(); layoutTask = new CreateCircularBranchesTask(rectRoot); connect(layoutTask, SIGNAL(si_stateChanged()), SLOT(sl_layoutRecomputed())); TaskScheduler* scheduler = AppContext::getTaskScheduler(); scheduler->registerTopLevelTask(layoutTask); } } void TreeViewerUI::sl_unrootedLayoutTriggered() { if (layout != TreeLayout_Unrooted) { // swapAction->setEnabled(false); root->setSelectedRecurs(false, true); // clear selection layout = TreeLayout_Unrooted; updateTreeSettings(); layoutTask = new CreateUnrootedBranchesTask(rectRoot); connect(layoutTask, SIGNAL(si_stateChanged()), SLOT(sl_layoutRecomputed())); TaskScheduler* scheduler = AppContext::getTaskScheduler(); scheduler->registerTopLevelTask(layoutTask); } } void TreeViewerUI::sl_layoutRecomputed() { if (layoutTask->getState() != Task::State_Finished || layoutTask->hasError()) { return; } scene()->removeItem(root); root = layoutTask->getResult(); scene()->addItem(root); defaultZoom(); updateRect(); if (!showNameLabels || !showDistanceLabels) { LabelTypes lt; if (!showDistanceLabels) { lt |= LabelType_Distance; } if (!showNameLabels) { lt |= LabelType_SequnceName; } showLabels(lt); } fitInView(scene()->sceneRect(), Qt::KeepAspectRatio); } void TreeViewerUI::showLabels(LabelTypes labelTypes) { QStack stack; stack.push(root); if (root != rectRoot) { stack.push(rectRoot); } while (!stack.isEmpty()) { GraphicsBranchItem *node = stack.pop(); if (labelTypes.testFlag(LabelType_SequnceName)) { if (node->getNameText() != NULL) { node->getNameText()->setVisible(showNameLabels); } } if (labelTypes.testFlag(LabelType_Distance)) { if (node->getDistanceText() != NULL) { node->getDistanceText()->setVisible(showDistanceLabels); } } foreach (QGraphicsItem* item, node->childItems()) { GraphicsBranchItem *bitem = dynamic_cast(item); if (bitem != NULL) { stack.push(bitem); } } } } void TreeViewerUI::sl_showNameLabelsTriggered(bool on) { if (on != showNameLabels) { QRectF rect = sceneRect(); rect.setWidth(rect.width() + (on ? 1 : -1) * maxNameWidth); scene()->setSceneRect(rect); showNameLabels = on; showLabels(LabelType_SequnceName); if(curTreeViewer){ curTreeViewer->getContAction()->setDisabled(!showNameLabels); if(!showNameLabels){ sl_contTriggered(false); }else{ if(curTreeViewer->getContAction()->isChecked()){ sl_contTriggered(true); } } }else{ if (contEnabled) { QStack stack; stack.push(root); if (root != rectRoot) { stack.push(rectRoot); } while (!stack.empty()) { GraphicsBranchItem* item = stack.pop(); if (item->getNameText() == NULL) { foreach (QGraphicsItem* citem, item->childItems()) { GraphicsBranchItem* gbi = dynamic_cast(citem); if (gbi != NULL) { stack.push(gbi); } } } else { item->setWidth(item->getWidth() + (on ? 1 : -1) * (maxNameWidth - item->getNameText()->boundingRect().width() - 2 * GraphicsBranchItem::TextSpace)); } } } } } } void TreeViewerUI::sl_showDistanceLabelsTriggered(bool on) { if (on != showDistanceLabels) { showDistanceLabels = on; showLabels(LabelType_Distance); } } void TreeViewerUI::sl_printTriggered() { QPrinter printer; QPrintDialog dialog(&printer, this); if (dialog.exec() != QDialog::Accepted) return; QPainter painter(&printer); paint(painter); } void TreeViewerUI::sl_textSettingsTriggered(){ TextSettingsDialog dialog(this, getTextSettings()); if(dialog.exec()){ updateSettings( dialog.getSettings() ); if(contEnabled){ QStack stack; stack.push(root); if (root != rectRoot) { stack.push(rectRoot); } while (!stack.empty()) { GraphicsBranchItem* item = stack.pop(); if (item->getNameText() == NULL) { foreach (QGraphicsItem* citem, item->childItems()) { GraphicsBranchItem* gbi = dynamic_cast(citem); if (gbi != NULL) { stack.push(gbi); } } } else { item->setWidth(0); } } updateRect(); contEnabled = false; sl_contTriggered(true); } } } void TreeViewerUI::sl_treeSettingsTriggered(){ TreeSettingsDialog dialog(this, getTreeSettings(), layout == TreeLayout_Rectangular); if(dialog.exec()){ updateSettings(dialog.getSettings()); } } void TreeViewerUI::sl_zoomToSel(){ QList selectedItems = this->scene()->selectedItems(); if(selectedItems.isEmpty()){ zooming(ZOOM_COEF); }else{ GraphicsButtonItem *topButton = NULL; foreach (QGraphicsItem *graphItem, selectedItems) { GraphicsButtonItem *buttonItem = dynamic_cast(graphItem); if (buttonItem && buttonItem->isSelectedTop()) { topButton = buttonItem; break; } } if(!topButton){ zooming(ZOOM_COEF); }else{ defaultZoom(); QGraphicsItem *topItem = topButton->parentItem(); QRectF rect = topItem->mapRectToScene(topItem->childrenBoundingRect()); QRectF rect1 = scene()->sceneRect(); qreal zoom1 = qMin(rect1.width() / rect.width(), rect1.height() / rect.height()); zooming(zoom1); centerOn(rect.center()); } } } void TreeViewerUI::sl_zoomOut(){ zooming(1.0/(float)ZOOM_COEF); } void TreeViewerUI::sl_zoomToAll(){ defaultZoom(); } void TreeViewerUI::defaultZoom(){ zooming(1.0/zoom); } void TreeViewerUI::redrawRectangularLayout(){ //if(layout == TreeLayout_Rectangular){ int current = 0; qreal minDistance = -2, maxDistance = 0; GraphicsRectangularBranchItem* item = rectRoot; item->redrawBranches(current, minDistance, maxDistance, phyObject->getTree()->rootNode); item->setWidthW(0); item->setDist(0); item->setHeightW(0); if(minDistance == 0){ minDistance = GraphicsRectangularBranchItem::EPSILON; } if(maxDistance == 0){ maxDistance = GraphicsRectangularBranchItem::EPSILON; } qreal minDistScale = GraphicsRectangularBranchItem::DEFAULT_WIDTH / (qreal)minDistance; qreal maxDistScale = GraphicsRectangularBranchItem::MAXIMUM_WIDTH / (qreal)maxDistance; qreal scale = qMin(minDistScale, maxDistScale); setScale(scale); //} } qreal TreeViewerUI::avgWidth(){ qreal sumW = 0; int count = 0; QList updatingItems = scene()->items(); foreach (QGraphicsItem *graphItem, updatingItems) { GraphicsBranchItem *branchItem = dynamic_cast(graphItem); if (branchItem) { sumW += qAbs(branchItem->getDist()); count++; } } return sumW/(qreal)count; } void TreeViewerUI::updateActionsState(){ zoomToAction->setEnabled(zoom < MAXIMUM_ZOOM* qMax(treeSettings.width_coef*TreeViewerUI::SIZE_COEF, 1.0)); zoomOutAction->setEnabled(zoom > MINIMUM_ZOOM); if(isSelectedCollapsed()){ collapseAction->setText(QObject::tr("Expand")); }else{ collapseAction->setText(QObject::tr("Collapse")); } QList updatingItems = this->scene()->selectedItems(); collapseAction->setEnabled(!updatingItems.isEmpty()); swapAction->setEnabled(!updatingItems.isEmpty()); } void TreeViewerUI::updateLayout() { TreeLayout tmpL = layout; layout = TreeLayout_Rectangular; switch(tmpL){ case TreeLayout_Circular: sl_circularLayoutTriggered(); break; case TreeLayout_Unrooted: sl_unrootedLayoutTriggered(); break; case TreeLayout_Rectangular: //here to please compiler break; } } }//namespace ugene-1.9.8/src/corelibs/U2View/src/util_ov_phyltree/GraphicsBranchItem.cpp0000644000175000017500000001543311651544334025425 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "GraphicsBranchItem.h" #include "GraphicsButtonItem.h" #include "TreeViewerUtils.h" #include #include #include namespace U2 { QColor BranchSettings::defaultColor = QColor(0, 0, 0); int BranchSettings::defaultThickness = 1; BranchSettings::BranchSettings() { branchColor = defaultColor; branchThickness = defaultThickness; } const int GraphicsBranchItem::TextSpace = 8; const int GraphicsBranchItem::SelectedPenWidth = 1; void GraphicsBranchItem::updateSettings(const BranchSettings& branchSettings) { settings = branchSettings; int penWidth = settings.branchThickness; if (isSelected()) { penWidth += SelectedPenWidth; } QPen currentPen = this->pen(); currentPen.setColor(settings.branchColor); currentPen.setWidth(penWidth); this->setPen(currentPen); } void GraphicsBranchItem::updateTextSettings(const QFont& font, const QColor& color){ if(distanceText){ distanceText->setFont(font); distanceText->setBrush(color); } if(nameText){ nameText->setFont(font); nameText->setBrush(color); } } void GraphicsBranchItem::collapse() { collapsed = !collapsed; QList items = childItems(); if (collapsed) { for (int i = 0, s = items.size(); i < s; ++i) { if (dynamic_cast(items[i])) { items[i]->hide(); } } int penWidth = settings.branchThickness; if (isSelected()) { penWidth += SelectedPenWidth; } QPen pen1(settings.branchColor); pen1.setWidth(penWidth); pen1.setCosmetic(true); QGraphicsRectItem *r = new QGraphicsRectItem(0, -4, 16, 8, this); r->setPen(pen1); } else { for (int i = 0, s = items.size(); i < s; ++i) { if (dynamic_cast(items[i])) { items[i]->setParentItem(NULL); scene()->removeItem(items[i]); } else { if (items[i] != getDistanceText() && items[i] != getNameText()) { items[i]->show(); } } } setSelectedRecurs(true,true); } } void GraphicsBranchItem::setSelectedRecurs(bool sel, bool recursively) { int penWidth = settings.branchThickness; if (sel) { penWidth = settings.branchThickness + SelectedPenWidth; } QPen thisPen = this->pen(); thisPen.setWidth(penWidth); setPen(thisPen); if (buttonItem) { buttonItem->setSelected(sel); } if (recursively) { foreach(QGraphicsItem* graphItem, this->childItems()) { GraphicsBranchItem *branchItem = dynamic_cast(graphItem); if (branchItem) { branchItem->setSelectedRecurs(sel, recursively); } } } this->setSelected(sel); scene()->update(); } void GraphicsBranchItem::initText(qreal d) { QString str = QString::number(d, 'f', 3); int i = str.length() - 1; for (; i >= 0 && str[i] == '0'; --i) ; if (str[i] == '.') --i; str.truncate(i + 1); //it doesn't show zeroes by default. only in cladogramm mode if(str == "0"){ str = ""; } //test distanceText = new QGraphicsSimpleTextItem(str); distanceText->setFont(TreeViewerUtils::getFont()); distanceText->setBrush(Qt::darkGray); QRectF rect = distanceText->boundingRect(); distanceText->setPos(-rect.width(), 0); distanceText->setParentItem(this); distanceText->setZValue(1); } GraphicsBranchItem::GraphicsBranchItem(bool withButton) : correspondingItem(NULL), buttonItem(NULL), distanceText(NULL), nameText(NULL), collapsed(false) { setFlag(QGraphicsItem::ItemIsSelectable); setAcceptHoverEvents(false); setAcceptedMouseButtons(Qt::NoButton); if (withButton) { buttonItem = new GraphicsButtonItem(); buttonItem->setParentItem(this); } setBrush(settings.branchColor); QPen pen1(settings.branchColor); pen1.setCosmetic(true); setPen(pen1); } GraphicsBranchItem::GraphicsBranchItem(const QString& name): correspondingItem(NULL), buttonItem(NULL), distanceText(NULL), collapsed(false) { setFlag(QGraphicsItem::ItemIsSelectable); setAcceptHoverEvents(false); setAcceptedMouseButtons(Qt::NoButton); QPen pen1(settings.branchColor); pen1.setStyle(Qt::DotLine); pen1.setCosmetic(true); setPen(pen1); width = 0; dist = 0; nameText = new QGraphicsSimpleTextItem(name); nameText->setFont(TreeViewerUtils::getFont()); nameText->setBrush(Qt::darkGray); QRectF rect = nameText->boundingRect(); nameText->setPos(GraphicsBranchItem::TextSpace, -rect.height() / 2); nameText->setParentItem(this); nameText->setZValue(1); } GraphicsBranchItem::GraphicsBranchItem(qreal d, bool withButton) : correspondingItem(NULL), buttonItem(NULL), distanceText(NULL), nameText(NULL), collapsed(false) { setFlag(QGraphicsItem::ItemIsSelectable); setAcceptHoverEvents(false); setAcceptedMouseButtons(Qt::NoButton); if (withButton) { buttonItem = new GraphicsButtonItem(); buttonItem->setParentItem(this); } initText(d); QPen pen1(settings.branchColor); pen1.setCosmetic(true); if (d < 0) { pen1.setStyle(Qt::DashLine); } setPen(pen1); setBrush(settings.branchColor); } void GraphicsBranchItem::setDistanceText(const QString& text){ if(distanceText){ distanceText->setText(text); } } void GraphicsBranchItem::setWidth(qreal w) { if (width == w) { return; } setPos(pos().x() - width + w, pos().y()); if (getDistanceText() != NULL) { QPointF pos = getDistanceText()->pos(); getDistanceText()->setPos(pos.x() + (width - w) * 0.5, pos.y()); } prepareGeometryChange(); width = w; } bool GraphicsBranchItem::isCollapsed(){ return collapsed; } } //namespace ugene-1.9.8/src/corelibs/U2View/src/util_ov_phyltree/CreateCircularBranchesTask.cpp0000644000175000017500000000366611651544334027116 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include #include "CreateCircularBranchesTask.h" #include "GraphicsCircularBranchItem.h" #include "GraphicsRectangularBranchItem.h" #include #include "TreeViewerUtils.h" namespace U2 { CreateCircularBranchesTask::CreateCircularBranchesTask(GraphicsRectangularBranchItem *r): root1(r) {} GraphicsCircularBranchItem* CreateCircularBranchesTask::getBranch(GraphicsRectangularBranchItem *from, GraphicsCircularBranchItem* parent) { GraphicsCircularBranchItem* res = new GraphicsCircularBranchItem(parent, coef * from->getHeight(), from); foreach (QGraphicsItem* item, from->childItems()) { GraphicsRectangularBranchItem* ri = dynamic_cast(item); if (ri != NULL) { getBranch(ri, res); } } res->setCorrespondingItem(from); return res; } void CreateCircularBranchesTask::run() { coef = 6.0 / root1->childrenBoundingRect().height(); root1->setWidthW(30); GraphicsCircularBranchItem* r = getBranch(root1, NULL); r->setVisibleW(false); root = r; root1->setWidthW(0); } } ugene-1.9.8/src/corelibs/U2View/src/util_ov_phyltree/GraphicsBranchItem.h0000644000175000017500000000524411651544334025071 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_GRAPHICS_BRANCH_ITEM_H_ #define _U2_GRAPHICS_BRANCH_ITEM_H_ #include namespace U2 { class PhyNode; class GraphicsButtonItem; class BranchSettings { public: BranchSettings(); QColor branchColor; int branchThickness; static QColor defaultColor; static int defaultThickness; }; class GraphicsBranchItem: public QAbstractGraphicsShapeItem { public: enum Direction { up, down }; static const int TextSpace; static const int SelectedPenWidth; BranchSettings settings; private: GraphicsBranchItem* correspondingItem; GraphicsButtonItem* buttonItem; void initText(qreal d); protected: QGraphicsSimpleTextItem* distanceText; QGraphicsSimpleTextItem* nameText; qreal width; qreal dist; bool collapsed; GraphicsBranchItem(const QString& name); GraphicsBranchItem(qreal d, bool withButton = true); public: GraphicsBranchItem(bool withButton = true); GraphicsButtonItem* getButton() const { return buttonItem; } QGraphicsSimpleTextItem* getDistanceText() const { return distanceText; } QGraphicsSimpleTextItem* getNameText() const { return nameText; } qreal getWidth() const { return width; } qreal getDist() const { return dist; } void setDistanceText(const QString& text); void setWidthW(qreal w) { width = w; } void setWidth(qreal w); void setDist (qreal d) { dist = d; } virtual void collapse(); void setSelectedRecurs(bool sel, bool recursively); bool isCollapsed(); void updateSettings(const BranchSettings& branchSettings); void updateTextSettings(const QFont& font, const QColor& color); GraphicsBranchItem* getCorrespondingItem() {return correspondingItem;} void setCorrespondingItem(GraphicsBranchItem* cItem) {correspondingItem = cItem;} }; }//namespace; #endif ugene-1.9.8/src/corelibs/U2View/src/util_ov_phyltree/GraphicsRectangularBranchItem.h0000644000175000017500000000503711651544334027261 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_GRAPHICS_RECTANGULAR_BRANCH_ITEM_H_ #define _U2_GRAPHICS_RECTANGULAR_BRANCH_ITEM_H_ #include #include "GraphicsBranchItem.h" namespace U2 { class PhyNode; class PhyBranch; class GraphicsButtonItem; class GraphicsRectangularBranchItem: public GraphicsBranchItem { public: static const qreal DEFAULT_WIDTH; static const qreal MAXIMUM_WIDTH; static const qreal EPSILON; static const int DEFAULT_HEIGHT; GraphicsRectangularBranchItem(); GraphicsRectangularBranchItem(const QString& name, GraphicsRectangularBranchItem* pitem); GraphicsRectangularBranchItem(qreal d); GraphicsRectangularBranchItem(qreal x, qreal y, const QString& name, qreal d); GraphicsRectangularBranchItem(qreal x, qreal y, const QString& name); QRectF boundingRect() const; void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget); void setParentItem(QGraphicsItem *item); Direction getDirection() const { return direction; } qreal getHeight() const { return height; } void setHeightW(qreal h) { height = h; } void setHeight(qreal h); void setHeightCoef(int coef); void setHeightCoefW(int coef) {cur_height_coef = coef;} void setDirection(Direction d); void collapse(); void swapSiblings(); void redrawBranches(int& current, qreal& minDistance, qreal& maxDistance, PhyNode* root); void setPhyBranch(PhyBranch* p) {phyBranch = p;} const PhyBranch* getPhyBranch() const {return phyBranch;} private: qreal height; int cur_height_coef; Direction direction; PhyBranch* phyBranch; GraphicsRectangularBranchItem* getChildItemByPhyBranch(const PhyBranch* branch); }; }//namespace; #endif ugene-1.9.8/src/corelibs/U2View/src/util_ov_phyltree/CreateRectangularBranchesTask.cpp0000644000175000017500000001274211651544334027614 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include #include "CreateRectangularBranchesTask.h" #include "GraphicsRectangularBranchItem.h" #include #include "TreeViewerUtils.h" namespace U2 { CreateRectangularBranchesTask::CreateRectangularBranchesTask(PhyNode *n): size(0), current(0), node(n) {} GraphicsRectangularBranchItem* CreateRectangularBranchesTask::getBranch(PhyNode *node) { if (isCanceled() || stateInfo.hasError()) return NULL; int branches = node->branches.size(); if (branches == 1 && (node->name=="" || node->name=="ROOT")) { assert(node != node->branches[0]->node2); return getBranch(node->branches[0]->node2); } if (branches > 1) { stateInfo.progress = 100 * ++size / 100; // <- number of sequences QList items; int ind = -1; for (int i = 0; i < branches; ++i) { if (node->branches[i]->node2 != node) { GraphicsRectangularBranchItem *item = getBranch(node->branches[i]->node2); items.append(item); } else { items.append(NULL); ind = i; } } GraphicsRectangularBranchItem *item; if (ind<0) { item = new GraphicsRectangularBranchItem(); } else { item = new GraphicsRectangularBranchItem(node->branches[ind]->distance); item->setPhyBranch(node->branches[ind]); } int size = items.size(); assert(size > 0); { int xmin = 0, ymin = items[0] ? items[0]->pos().y() : items[1]->pos().y(), ymax = 0; for (int i = 0; i < size; ++i) { if (items[i] == NULL) { continue; } QPointF pos1 = items[i]->pos(); if (pos1.x() < xmin) xmin = pos1.x(); if (pos1.y() < ymin) ymin = pos1.y(); if (pos1.y() > ymax) ymax = pos1.y(); } xmin -= GraphicsRectangularBranchItem::DEFAULT_WIDTH; int y = (ymax + ymin) / 2; item->setPos(xmin, y); for (int i = 0; i < size; ++i) { if (items[i] == NULL) { continue; } qreal dist = qAbs(node->branches[i]->distance); if (minDistance > -1) { minDistance = qMin(minDistance, dist); } else { minDistance = dist; } maxDistance = qMax(maxDistance, dist); items[i]->setDirection(items[i]->pos().y() > y ? GraphicsRectangularBranchItem::up : GraphicsRectangularBranchItem::down); items[i]->setWidthW(dist); items[i]->setDist(dist); items[i]->setParentItem(item); QRectF rect = items[i]->getDistanceText()->boundingRect(); items[i]->getDistanceText()->setPos(-(items[i]->getWidth() + rect.width()) / 2, 0); } } return item; } else { int y = (current++ + 0.5) * GraphicsRectangularBranchItem::DEFAULT_HEIGHT; GraphicsRectangularBranchItem *item = NULL; if(branches != 1){ item = new GraphicsRectangularBranchItem(0, y, node->name); }else{ item = new GraphicsRectangularBranchItem(0, y, node->name, node->branches[0]->distance); item->setPhyBranch(node->branches[0]); } return item; } } void CreateRectangularBranchesTask::run() { minDistance = -2; maxDistance = 0; GraphicsRectangularBranchItem* item = getBranch(node); // modifies minDistance and maxDistance item->setWidthW(0); item->setDist(0); item->setHeightW(0); root = item; if(minDistance == 0){ minDistance = GraphicsRectangularBranchItem::EPSILON; } if(maxDistance == 0){ maxDistance = GraphicsRectangularBranchItem::EPSILON; } qreal minDistScale = GraphicsRectangularBranchItem::DEFAULT_WIDTH / (qreal)minDistance; qreal maxDistScale = GraphicsRectangularBranchItem::MAXIMUM_WIDTH / (qreal)maxDistance; scale = qMin(minDistScale, maxDistScale); QStack stack; stack.push(item); while (!stack.empty()) { GraphicsRectangularBranchItem *item = stack.pop(); item->setWidth(item->getWidth() * scale); foreach (QGraphicsItem* ci, item->childItems()) { GraphicsRectangularBranchItem* gbi = dynamic_cast(ci); if (gbi != NULL) { stack.push(gbi); } } } } } ugene-1.9.8/src/corelibs/U2View/src/util_ov_phyltree/TreeViewer.h0000644000175000017500000002041111651544334023446 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_TREE_VIEWER_H_ #define _U2_TREE_VIEWER_H_ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include namespace U2 { class GObjectView; class TreeViewerUI; class GraphicsBranchItem; class GraphicsButtonItem; class GraphicsRectangularBranchItem; class CreateBranchesTask; class TreeViewer: public GObjectView { Q_OBJECT public: TreeViewer(const QString& viewName, GObject* obj, GraphicsRectangularBranchItem* root, qreal scale); //from GObjectView virtual void buildStaticToolbar(QToolBar* tb); virtual void buildStaticMenu(QMenu* m); void createActions(); virtual QVariantMap saveState(); virtual Task* updateViewTask(const QString& stateName, const QVariantMap& stateData); QAction* getPrintAction() const { return printAction; } QAction* getContAction() const { return contAction; } QAction* getNameLabelsAction() const { return nameLabelsAction; } QAction* getDistanceLabelsAction() const { return distanceLabelsAction; } QAction* getCaptureTreeAction() const { return captureTreeAction; } QAction* getExportAction() const { return exportAction; } QAction* getRectangularLayoutAction() const { return rectangularLayoutAction; } QAction* getCircularLayoutAction() const { return circularLayoutAction; } QAction* getUnrootedLayoutAction() const { return unrootedLayoutAction; } QAction* getTextSettingsAction() const { return textSettingsAction; } QAction* getTreeSettingsAction() const { return treeSettingsAction; } QAction* getBranchesSettingsAction() const { return branchesSettingsAction; } QAction* getZoomToSelAction() const { return zoomToSelAction; } QAction* getZoomOutAction() const { return zoomOutAction; } QAction* getZoomToAllAction() const { return zoomToAllAction; } PhyTreeObject* getPhyObject() const { return phyObject; } GraphicsRectangularBranchItem* getRoot() const { return root; } void setRoot(GraphicsRectangularBranchItem* rectRoot) { root = rectRoot;} qreal getScale() const {return scale;} void setScale(qreal scale) {this->scale = scale;} qreal getZoom() const; void setZoom(qreal z); QTransform getTransform() const; void setTransform(const QTransform& m); QVariantMap getSettingsState() const; void setSettingsState(const QVariantMap& m); protected: virtual QWidget* createWidget(); virtual void onObjectRenamed(GObject* obj, const QString& oldName); private: QAction* treeSettingsAction; QActionGroup* layoutGroup; QAction* rectangularLayoutAction; QAction* circularLayoutAction; QAction* unrootedLayoutAction; QAction* branchesSettingsAction; QAction* nameLabelsAction; QAction* distanceLabelsAction; QAction* textSettingsAction; QAction* contAction; QAction* zoomToSelAction; QAction* zoomToAllAction; QAction* zoomOutAction; QAction* printAction; QAction* captureTreeAction; QAction* exportAction; TreeViewerUI* ui; QByteArray state; PhyTreeObject* phyObject; GraphicsRectangularBranchItem* root; qreal scale; void setupLayoutSettingsMenu(QMenu* m); void setupShowLabelsMenu(QMenu* m); void setupCameraMenu(QMenu* m); }; class TreeViewerUI: public QGraphicsView { Q_OBJECT public: TreeViewerUI(TreeViewer* treeViewer); ~TreeViewerUI(); static const qreal ZOOM_COEF; static const qreal MINIMUM_ZOOM; static const qreal MAXIMUM_ZOOM; static const int MARGIN; static const qreal SIZE_COEF; BranchSettings getBranchSettings() const; ButtonSettings getButtonSettings() const; TextSettings getTextSettings() const; TreeSettings getTreeSettings() const; void updateSettings(const BranchSettings &settings); void updateSettings(const ButtonSettings &settings); void updateSettings(const TextSettings &settings); void updateSettings(const TreeSettings &settings); qreal getZoom() const {return zoom;} void setZoom(qreal z) {zoom = z;} QVariantMap getSettingsState() const; void setSettingsState(const QVariantMap& m); protected: virtual void wheelEvent(QWheelEvent *e); virtual void resizeEvent(QResizeEvent *e); virtual void mousePressEvent(QMouseEvent *e); virtual void mouseReleaseEvent(QMouseEvent *e); private slots: void sl_printTriggered(); void sl_captureTreeTriggered(); void sl_contTriggered(bool on); void sl_exportTriggered(); void sl_showNameLabelsTriggered(bool on); void sl_showDistanceLabelsTriggered(bool on); void sl_rectangularLayoutTriggered(); void sl_circularLayoutTriggered(); void sl_unrootedLayoutTriggered(); void sl_layoutRecomputed(); void sl_chrootTriggered(); void sl_swapTriggered(); void sl_collapseTriggered(); void sl_textSettingsTriggered(); void sl_treeSettingsTriggered(); void sl_setSettingsTriggered(); void sl_branchSettings(); void sl_zoomToSel(); void sl_zoomOut(); void sl_zoomToAll(); private: enum TreeLayout { TreeLayout_Rectangular, TreeLayout_Circular, TreeLayout_Unrooted, }; enum LabelType { LabelType_SequnceName = 1, LabelType_Distance = 2, }; typedef QFlags LabelTypes; void updateRect(); void paint(QPainter &painter); void showLabels(LabelTypes labelTypes); void addLegend(qreal scale); void collapseSelected(); void updateSettings(); void updateLayout(); void updateTextSettings(); void updateTreeSettings(); void redrawRectangularLayout(); bool isSelectedCollapsed(); void zooming(qreal newzoom); void defaultZoom(); void setScale(qreal s) { view_scale = s;} qreal getScale() {return view_scale;} void updateActionsState(); qreal avgWidth(); PhyTreeObject* phyObject; GraphicsBranchItem* root; GraphicsRectangularBranchItem* rectRoot; bool contEnabled; int maxNameWidth; bool showNameLabels; bool showDistanceLabels; qreal zoom; qreal view_scale; TreeLayout layout; CreateBranchesTask* layoutTask; QGraphicsItem* legend; QMenu* buttonPopup; const TreeViewer* curTreeViewer; QAction* swapAction; QAction* zoomToAction; QAction* zoomOutAction; QAction* zoomToAllAction; QAction* collapseAction; QAction* setColorAction; QAction* captureAction; QAction* exportAction; BranchSettings branchSettings; ButtonSettings buttonSettings; TextSettings textSettings; TreeSettings treeSettings; }; }//namespace #endif ugene-1.9.8/src/corelibs/U2View/src/util_ov_phyltree/GraphicsButtonItem.cpp0000644000175000017500000001061711651544334025502 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "GraphicsButtonItem.h" #include "GraphicsBranchItem.h" #include "GraphicsRectangularBranchItem.h" #include #include #include #include #include #include namespace U2 { const qreal GraphicsButtonItem::radiusMin = 2.0; const qreal GraphicsButtonItem::radiusMax = 5.0; GraphicsButtonItem::GraphicsButtonItem() { setPen(QColor(0, 0, 0)); setBrush(Qt::gray); setAcceptHoverEvents(true); setAcceptedMouseButtons(Qt::LeftButton); setZValue(2); setFlag(QGraphicsItem::ItemIsSelectable); } QRectF GraphicsButtonItem::boundingRect() const { return QRectF(-radiusMax, -radiusMax, 2 * radiusMax, 2 * radiusMax); } QPainterPath GraphicsButtonItem::shape() const { QPainterPath path; path.addEllipse(boundingRect()); return path; } void GraphicsButtonItem::paint(QPainter *painter, const QStyleOptionGraphicsItem*, QWidget*) { QBrush br(Qt::gray); int radius = radiusMin; bool mouseHovered = isUnderMouse(); bool itemSelected = isSelected(); if (mouseHovered || itemSelected) { radius = radiusMax; br = QBrush(QColor(0, 0, 255)); } painter->setPen(pen()); painter->setBrush(br); painter->drawEllipse(QPointF(0, 0), radius, radius); } void GraphicsButtonItem::mousePressEvent(QGraphicsSceneMouseEvent *e) { uiLog.trace("Tree button pressed"); bool shiftPressed = e->modifiers() & Qt::ShiftModifier; bool leftButton = e->button() == Qt::LeftButton; GraphicsBranchItem *p = dynamic_cast(parentItem()); if (leftButton && p!=NULL) { bool newSelection = true; if (shiftPressed) { newSelection = !isSelected(); } p->setSelectedRecurs(newSelection, true); e->accept(); update(); } } void GraphicsButtonItem::mouseDoubleClickEvent(QGraphicsSceneMouseEvent *e) { uiLog.trace("Tree button double-clicked"); collapse(); QAbstractGraphicsShapeItem::mouseDoubleClickEvent(e); } void GraphicsButtonItem::collapse() { GraphicsBranchItem *p = dynamic_cast(parentItem()); Q_ASSERT(p); if (p) { p->collapse(); } } void GraphicsButtonItem::swapSiblings() { uiLog.trace("Swapping siblings"); GraphicsBranchItem *branchItem = dynamic_cast(parentItem()); if (!branchItem) { return; } GraphicsRectangularBranchItem *rectBranchItem = dynamic_cast(branchItem); if(!rectBranchItem){ if(!branchItem->getCorrespondingItem()){ return; } rectBranchItem = dynamic_cast(branchItem->getCorrespondingItem()); if(!rectBranchItem){ return; } } rectBranchItem->swapSiblings(); } bool GraphicsButtonItem::isSelectedTop() { if (!isSelected()) { return false; } GraphicsBranchItem *branchItem = dynamic_cast(parentItem()); if (!branchItem) { return true; } GraphicsBranchItem *parentBranchItem = dynamic_cast(branchItem->parentItem()); if (!parentBranchItem) { return true; } bool parentBranchSelected = parentBranchItem->isSelected(); return !parentBranchSelected; } bool GraphicsButtonItem::isCollapsed(){ GraphicsBranchItem *p = dynamic_cast(parentItem()); Q_ASSERT(p); if (p) { return p->isCollapsed(); } return false; } }//namespace ugene-1.9.8/src/corelibs/U2View/src/util_ov_phyltree/TreeViewerState.h0000644000175000017500000000302211651544334024446 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_TREE_VIEWER_STATE_H_ #define _U2_TREE_VIEWER_STATE_H_ #include #include #include namespace U2 { class TreeViewer; class U2VIEW_EXPORT TreeViewerState { public: TreeViewerState(){} TreeViewerState(const QVariantMap& _stateData) : stateData(_stateData){} static QVariantMap saveState(TreeViewer* v); bool isValid() const; GObjectReference getPhyObject() const; void setPhyObject(const GObjectReference& ref); qreal getZoom() const; void setZoom(qreal s); QTransform getTransform() const; void setTransform(const QTransform& m); QVariantMap stateData; }; } // namespace #endif ugene-1.9.8/src/corelibs/U2View/src/util_ov_phyltree/CreateUnrootedBranchesTask.h0000644000175000017500000000264511651544334026612 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_CREATE_UNROOTED_BRANCHES_TASK_H_ #define _U2_CREATE_UNROOTED_BRANCHES_TASK_H_ #include "CreateBranchesTask.h" namespace U2 { class PhyNode; class GraphicsRectangularBranchItem; class GraphicsUnrootedBranchItem; class CreateUnrootedBranchesTask: public CreateBranchesTask { Q_OBJECT qreal coef; GraphicsRectangularBranchItem* root1; GraphicsUnrootedBranchItem* getBranch(GraphicsRectangularBranchItem *r, GraphicsUnrootedBranchItem* parent); public: CreateUnrootedBranchesTask(GraphicsRectangularBranchItem *r); void run(); }; }//namespace; #endif ugene-1.9.8/src/corelibs/U2View/src/util_ov_phyltree/GraphicsUnrootedBranchItem.h0000644000175000017500000000264711651544334026615 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_GRAPHICS_UNROOTED_BRANCH_ITEM_H_ #define _U2_GRAPHICS_UNROOTED_BRANCH_ITEM_H_ #include #include "GraphicsBranchItem.h" class QGraphicsItem; namespace U2 { class PhyNode; class GraphicsButtonItem; class GraphicsRectangularBranchItem; class GraphicsUnrootedBranchItem: public GraphicsBranchItem { public: GraphicsUnrootedBranchItem(QGraphicsItem* parent, qreal angle, GraphicsRectangularBranchItem* from); QRectF boundingRect() const; void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget); }; }//namespace; #endif ugene-1.9.8/src/corelibs/U2View/src/util_ov_phyltree/TreeViewerUtils.h0000644000175000017500000000224511651544334024474 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _TREE_VIEWER_UTILS_H_ #define _TREE_VIEWER_UTILS_H #include namespace U2 { class TreeViewerUtils { static QFont* font; public: static const char* IMAGE_FILTERS; static void saveImageDialog(const QString& filters, QString &fileName, QString &format); static const QFont& getFont(); }; } #endifugene-1.9.8/src/corelibs/U2View/src/util_ov_phyltree/TreeViewerState.cpp0000644000175000017500000000515011651544334025005 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "TreeViewerState.h" #include "TreeViewer.h" #include "TreeViewerFactory.h" #include #include #include #include namespace U2 { #define VIEW_ID QString("view_id") #define PHY_OBJ QString("phy_obj_ref") #define ZOOM QString("zoom") #define TRANSFORM QString("transform") bool TreeViewerState::isValid() const { return stateData.value(VIEW_ID) == TreeViewerFactory::ID; } GObjectReference TreeViewerState::getPhyObject() const { return stateData.contains(PHY_OBJ) ? stateData[PHY_OBJ].value() : GObjectReference(); } void TreeViewerState::setPhyObject(const GObjectReference& ref) { stateData[PHY_OBJ] = QVariant::fromValue(ref); } qreal TreeViewerState::getZoom() const { QVariant v = stateData.value(ZOOM); if (v.isValid()) { return v.value(); } else { return 1.0f; } } void TreeViewerState::setZoom(qreal s) { stateData[ZOOM] = s; } QTransform TreeViewerState::getTransform() const { QVariant v = stateData.value(TRANSFORM); if (v.type() == QVariant::Transform) { return v.value(); } QTransform t; return t; } void TreeViewerState::setTransform(const QTransform& m) { stateData[TRANSFORM] = m; } QVariantMap TreeViewerState::saveState(TreeViewer* v) { TreeViewerState ss; ss.stateData[VIEW_ID] = TreeViewerFactory::ID; PhyTreeObject* phyObj = v->getPhyObject(); if (phyObj) { ss.setPhyObject(GObjectReference(phyObj)); } ss.setZoom(v->getZoom()); ss.setTransform(v->getTransform()); ss.stateData.unite(v->getSettingsState()); return ss.stateData; } } // namespace ugene-1.9.8/src/corelibs/U2View/src/util_ov_phyltree/GraphicsUnrootedBranchItem.cpp0000644000175000017500000000701211651544334027137 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "GraphicsUnrootedBranchItem.h" #include "GraphicsRectangularBranchItem.h" #include "GraphicsButtonItem.h" #include "TreeViewerUtils.h" #include #include #include #include #include #include #include #include namespace U2 { GraphicsUnrootedBranchItem::GraphicsUnrootedBranchItem(QGraphicsItem* parent, qreal angle, GraphicsRectangularBranchItem* from): GraphicsBranchItem(true) { setParentItem(parent); qreal w = from->getWidth(); settings = from->settings; setWidthW(w); setDist(from->getDist()); setPos(w, 0); angle = from->getDirection() == GraphicsBranchItem::up ? angle : -angle; setTransform(QTransform().translate(-w, 0).rotate(angle).translate(w, 0)); // setTransformOriginPoint(-w, 0); // setRotation(angle); if (from->getNameText() != NULL) { nameText = new QGraphicsSimpleTextItem(from->getNameText()->text(), this); nameText->setFont(from->getNameText()->font()); QRectF rect = nameText->boundingRect(); qreal h = rect.height(); nameText->setPos(GraphicsBranchItem::TextSpace, -h * 0.5); if (nameText->scenePos().x() < 0.0) { QPointF p = rect.center(); nameText->setTransform(QTransform().translate(p.x(), p.y()).rotate(180).translate(-p.x(), -p.y())); // nameText->setTransformOriginPoint(rect.center()); // nameText->setRotation(180); } nameText->setBrush(from->getNameText()->brush()); } if (from->getDistanceText() != NULL) { distanceText = new QGraphicsSimpleTextItem(from->getDistanceText()->text(), this); distanceText->setFont(from->getDistanceText()->font()); QRectF rect = distanceText->boundingRect(); if (distanceText->scenePos().x() < 0) { QPointF p(rect.center().x(), rect.height()); distanceText->setTransform(QTransform().translate(p.x(), p.y()).rotate(180).translate(-p.x(), -p.y())); // distanceText->setTransformOriginPoint(rect.center().x(), rect.height()); // distanceText->setRotation(180); } distanceText->setPos(-0.5 * (w + rect.width()), -rect.height()); distanceText->setBrush(from->getDistanceText()->brush()); } setPen(from->pen()); } QRectF GraphicsUnrootedBranchItem::boundingRect() const { qreal penWidth = 1; return QRectF(-width, -penWidth * 0.5, width, penWidth); } void GraphicsUnrootedBranchItem::paint(QPainter *painter, const QStyleOptionGraphicsItem*, QWidget*) { painter->setPen(pen()); painter->drawLine(0, 0, -width, 0); } }//namespace ugene-1.9.8/src/corelibs/U2View/src/util_ov_phyltree/GraphicsButtonItem.h0000644000175000017500000000300611651544334025141 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_GRAPHICS_BUTTON_ITEM_H_ #define _U2_GRAPHICS_BUTTON_ITEM_H_ #include namespace U2 { class GraphicsButtonItem: public QAbstractGraphicsShapeItem { static const qreal radiusMin, radiusMax; protected: void mousePressEvent(QGraphicsSceneMouseEvent *e); void mouseDoubleClickEvent(QGraphicsSceneMouseEvent *e); public: GraphicsButtonItem(); QRectF boundingRect() const; QPainterPath shape() const; void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget); bool isSelectedTop(); void collapse(); void swapSiblings(); bool isCollapsed(); }; }//namespace; #endif ugene-1.9.8/src/corelibs/U2View/src/phyltree/0000755000175000017500000000000011651544334017455 5ustar ilyailyaugene-1.9.8/src/corelibs/U2View/src/phyltree/TextSettingsDialog.cpp0000644000175000017500000000556211651544334023756 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "TextSettingsDialog.h" #include "U2View/TreeViewerUtils.h" #include namespace U2 { QColor TextSettings::defaultColor = QColor(Qt::gray); QFont TextSettings::defaultFont = TreeViewerUtils::getFont(); TextSettings::TextSettings() { textColor = defaultColor; textFont = defaultFont; } TextSettingsDialog::TextSettingsDialog(QWidget *parent, const TextSettings &textSettings) : QDialog(parent), settings(textSettings), changedSettings(textSettings) { setupUi(this); updateColorButton(); fontComboBox->setCurrentFont(settings.textFont); sizeSpinBox->setValue(settings.textFont.pointSize()); boldToolButton->setChecked(settings.textFont.bold()); italicToolButton->setChecked(settings.textFont.italic()); underlineToolButton->setChecked(settings.textFont.underline()); overlineToolButton->setChecked(settings.textFont.overline()); overlineToolButton->setVisible(false); connect(colorButton, SIGNAL(clicked()), SLOT(sl_colorButton())); } void TextSettingsDialog::updateColorButton() { static const QString COLOR_STYLE("QPushButton { background-color : %1;}"); colorButton->setStyleSheet(COLOR_STYLE.arg(changedSettings.textColor.name())); } void TextSettingsDialog::sl_colorButton() { QColor newColor = QColorDialog::getColor(changedSettings.textColor, this); if (newColor.isValid()) { changedSettings.textColor = newColor; updateColorButton(); } } void TextSettingsDialog::accept() { changedSettings.textFont = fontComboBox->currentFont(); changedSettings.textFont.setPointSize(sizeSpinBox->value()); changedSettings.textFont.setBold(boldToolButton->isChecked()); changedSettings.textFont.setItalic(italicToolButton->isChecked()); changedSettings.textFont.setUnderline(underlineToolButton->isChecked()); changedSettings.textFont.setOverline(overlineToolButton->isChecked()); settings = changedSettings; QDialog::accept(); } TextSettings TextSettingsDialog::getSettings() const { return settings; } } //namespace ugene-1.9.8/src/corelibs/U2View/src/phyltree/ButtonSettingsDialog.cpp0000644000175000017500000000414511651544334024301 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "ButtonSettingsDialog.h" #include namespace U2 { QColor ButtonSettings::defaultColor = QColor(0, 0, 0); int ButtonSettings::defaultRadius = 2; ButtonSettings::ButtonSettings() { col = defaultColor; radius = defaultRadius; } ButtonSettingsDialog::ButtonSettingsDialog(QWidget *parent, const ButtonSettings &buttonSettings) : QDialog(parent), settings(buttonSettings), changedSettings(buttonSettings) { setupUi(this); radiusSpinBox->setValue(settings.radius); updateColorButton(); connect(colorButton, SIGNAL(clicked()), SLOT(sl_colorButton())); } void ButtonSettingsDialog::updateColorButton() { static const QString COLOR_STYLE("QPushButton { background-color : %1;}"); colorButton->setStyleSheet(COLOR_STYLE.arg(changedSettings.col.name())); } void ButtonSettingsDialog::sl_colorButton() { QColor newColor = QColorDialog::getColor(changedSettings.col, this); if (newColor.isValid()) { changedSettings.col = newColor; updateColorButton(); } } void ButtonSettingsDialog::accept() { changedSettings.radius = radiusSpinBox->value(); settings = changedSettings; QDialog::accept(); } ButtonSettings ButtonSettingsDialog::getSettings() const { return settings; } } //namespace ugene-1.9.8/src/corelibs/U2View/src/phyltree/TreeSettingsDialog.h0000644000175000017500000000303211651544334023364 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #pragma once #include #include namespace U2 { struct TreeSettings { public: TreeSettings(); enum TREE_TYPE { PHYLOGRAM, CLADOGRAM }; TREE_TYPE type; int width_coef; int height_coef; static int default_width_coef; static int default_height_coef; }; class TreeSettingsDialog : public QDialog, public Ui_TreeSettingsDialog{ Q_OBJECT public: TreeSettingsDialog(QWidget *parent, const TreeSettings &treeSettings, bool isRectLayout); virtual void accept(); TreeSettings getSettings() const; protected slots: // void sl_colorButton(); private: TreeSettings settings, changedSettings; }; } //namespace ugene-1.9.8/src/corelibs/U2View/src/phyltree/ui/0000755000175000017500000000000011651544334020072 5ustar ilyailyaugene-1.9.8/src/corelibs/U2View/src/phyltree/ui/CreatePhyTreeDialog.ui0000644000175000017500000000743511651544334024266 0ustar ilyailya CreatePhyTree 0 0 347 148 0 0 346 140 Build Phylogenetic Tree true Tree building method Save tree to ... Remember Settings Restore Default Qt::Horizontal 40 20 Qt::Horizontal 40 20 Build Cancel cancelButton clicked() CreatePhyTree reject() 177 117 172 69 ugene-1.9.8/src/corelibs/U2View/src/phyltree/ui/TextSettingsDialog.ui0000644000175000017500000001304011651544334024214 0ustar ilyailya TextSettingsDialog 0 0 276 173 Labels Formatting Color Size Qt::Horizontal 40 20 0 0 false false Font Attributes 75 true B true true I true true U true true S true Qt::Horizontal 40 20 OK Cancel cancelButton clicked() TextSettingsDialog reject() 352 189 199 105 okButton clicked() TextSettingsDialog accept() 271 189 199 105 ugene-1.9.8/src/corelibs/U2View/src/phyltree/ui/BranchSettingsDialog.ui0000644000175000017500000000740111651544334024471 0ustar ilyailya BranchSettingsDialog 0 0 261 115 Branch Settings Color Qt::Horizontal 40 20 0 0 false false Line Weight 1 Qt::Vertical 20 6 Qt::Horizontal 40 20 OK Cancel cancelButton clicked() BranchSettingsDialog reject() 352 189 199 105 okButton clicked() BranchSettingsDialog accept() 271 189 199 105 ugene-1.9.8/src/corelibs/U2View/src/phyltree/ui/ButtonSettingsDialog.ui0000644000175000017500000000735111651544334024553 0ustar ilyailya ButtonSettingsDialog 0 0 209 108 Button settings Color: Qt::Horizontal 40 20 0 0 false false Radius: Qt::Horizontal 40 20 OK Cancel cancelButton clicked() ButtonSettingsDialog reject() 352 189 199 105 okButton clicked() ButtonSettingsDialog accept() 271 189 199 105 10 10 true true true ugene-1.9.8/src/corelibs/U2View/src/phyltree/ui/TreeSettingsDialog.ui0000644000175000017500000001074311651544334024176 0ustar ilyailya TreeSettingsDialog 0 0 298 152 Tree Settings 10 50 Qt::Horizontal false false QSlider::TicksAbove 1 20 Qt::Horizontal QSlider::TicksAbove Width Height (Rectangular) Tree View Qt::Vertical QSizePolicy::Fixed 20 13 Qt::Horizontal 40 20 OK Cancel widthlSlider heightSlider treeViewCombo okButton cancelButton okButton clicked() TreeSettingsDialog accept() 115 143 59 106 cancelButton clicked() TreeSettingsDialog reject() 196 136 270 103 ugene-1.9.8/src/corelibs/U2View/src/phyltree/ButtonSettingsDialog.h0000644000175000017500000000306511651544334023746 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_PHYLTREE_BUTTON_SETTINGS_DIALOG_H_ #define _U2_PHYLTREE_BUTTON_SETTINGS_DIALOG_H_ #include #include namespace U2 { class ButtonSettings { public: ButtonSettings(); QColor col; int radius; static QColor defaultColor; static int defaultRadius; }; class ButtonSettingsDialog : public QDialog, public Ui_ButtonSettingsDialog{ Q_OBJECT public: ButtonSettingsDialog(QWidget *parent, const ButtonSettings& buttonSettings); virtual void accept(); ButtonSettings getSettings() const; protected slots: void sl_colorButton(); private: ButtonSettings settings, changedSettings; void updateColorButton(); }; } //namespace #endif ugene-1.9.8/src/corelibs/U2View/src/phyltree/CreatePhyTreeDialogController.cpp0000644000175000017500000001426111651544334026055 0ustar ilyailya#include "CreatePhyTreeDialogController.h" #include "ui/ui_CreatePhyTreeDialog.h" #include "CreatePhyTreeWidget.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include namespace U2{ CreatePhyTreeDialogController::CreatePhyTreeDialogController(QWidget* parent, const MAlignmentObject* mobj, CreatePhyTreeSettings& _settings) : QDialog(parent), msa(mobj->getMAlignment()), settings(_settings){ ui = new Ui_CreatePhyTree; ui->setupUi(this); ui->verticalLayout->getContentsMargins ( NULL, NULL, &rightMargin, NULL ); PhyTreeGeneratorRegistry* registry = AppContext::getPhyTreeGeneratorRegistry(); QStringList nameList = registry->getNameList(); for(int i=0; ialgorithmBox->addItem(nameList[i]); } const GUrl& msaURL = mobj->getDocument()->getURL(); GUrl url = GUrlUtils::rollFileName(msaURL.dirPath() + "/" + msaURL.baseFileName() + ".nwk", DocumentUtils::getNewDocFileNameExcludesHint()); connect(ui->okButton, SIGNAL(clicked()), SLOT(sl_okClicked())); connect(ui->browseButton, SIGNAL(clicked()), SLOT(sl_browseClicked())); connect(ui->storeSettings, SIGNAL(clicked()), SLOT(sl_onStoreSettings())); connect(ui->restoreSettings, SIGNAL(clicked()), SLOT(sl_onRestoreDefault())); ui->fileNameEdit->setText(url.getURLString()); PhyTreeGenerator* generator = registry->getGenerator(nameList.at(0)); generator->setupCreatePhyTreeUI(this, msa); ui->verticalLayout->activate(); QString algName = AppContext::getSettings()->getValue(CreatePhyTreeWidget::settingsPath + "/algorithm", ui->algorithmBox->itemText(0)).toString(); for(int i = 0; ialgorithmBox->count(); i++){ if(ui->algorithmBox->itemText(i) == algName){ ui->algorithmBox->setCurrentIndex(i); break; } } } void CreatePhyTreeDialogController::sl_okClicked(){ settings.algorithmId = ui->algorithmBox->currentText(); if (ui->fileNameEdit->text().isEmpty()) { QMessageBox::warning(this, tr("Warning"), tr("Please, input the file name.")); ui->fileNameEdit->setFocus(); return; } settings.fileUrl = ui->fileNameEdit->text(); foreach (CreatePhyTreeWidget* widget, childWidgets) { widget->fillSettings(settings); } if(settings.bootstrap){ if(!checkSeed(settings.seed)){ QMessageBox::warning(this, tr("Warning"), tr("The seed must be odd.")); return; } } qint64 memRequiredMB = 0; if(estimateResources(&memRequiredMB)){ QMessageBox mb(QMessageBox::Warning, tr("Warning"), tr("Probably, for that alignment there is no enough memory to run PHYLIP dnadist module. \ The module will require more than %1 MB in the estimation. \ \nIt could cause an error. Do you want to continue?").arg(memRequiredMB), QMessageBox::Ok|QMessageBox::Cancel); if(mb.exec() == QMessageBox::Ok){ QDialog::accept(); } }else{ QDialog::accept(); } } void CreatePhyTreeDialogController::insertContrWidget( int pos, CreatePhyTreeWidget* widget ) { ui->verticalLayout->insertWidget(pos, widget); childWidgets.append(widget); // adjust sizes setMinimumHeight(widget->minimumHeight() + minimumHeight()); if (minimumWidth() < widget->minimumWidth()) { setMinimumWidth(widget->minimumWidth() + rightMargin*2); }; widget->show(); } void CreatePhyTreeDialogController::sl_browseClicked() { GUrl oldUrl = ui->fileNameEdit->text(); QString path; LastOpenDirHelper lod; if (oldUrl.isEmpty()) { path = lod.dir; } else { path = oldUrl.getURLString(); } GUrl newUrl = QFileDialog::getSaveFileName(this, "Choose file name", path,"Newick format (*.nwk)"); if (newUrl.isEmpty()) { return; } ui->fileNameEdit->setText(newUrl.getURLString()); lod.url = newUrl.getURLString(); } CreatePhyTreeDialogController::~CreatePhyTreeDialogController() { delete ui; } bool CreatePhyTreeDialogController::estimateResources(qint64* memoryRequiredMB){ qint64 appMemMb = 0; qint64 minMemoryForDistanceMatrixMb = 0; AppResourcePool* s = AppContext::getAppSettings()->getAppResourcePool(); //AppResourcePool::getCurrentAppMemory(appMemMb); appMemMb = s->getMaxMemorySizeInMB(); //****description****** //dnadist_makevalues() // for (i = 0; i < spp; i++) { // nodep[i]->x = (phenotype)Malloc(endsite*sizeof(ratelike)); // for (j = 0; j < endsite; j++) // nodep[i]->x[j] = (ratelike)Malloc(rcategs*sizeof(sitelike)); // } //rcategs = 1 //sizeof(sitelike) = 32 //sizeof(ratelike) = 4 qint64 spp = msa.getNumRows(); qint64 endsite = msa.getLength(); qint64 ugeneLowestMemoryUsageMb = 50; minMemoryForDistanceMatrixMb = (qint64)(spp*endsite*32 + endsite*4)/(1024*1024); *memoryRequiredMB = minMemoryForDistanceMatrixMb; if(minMemoryForDistanceMatrixMb>appMemMb - ugeneLowestMemoryUsageMb){ return true; }else{ return false; } } #define SEED_MIN 0 #define SEED_MAX 32767 bool CreatePhyTreeDialogController::checkSeed(int seed){ return (seed > SEED_MIN) && (seed setValue(CreatePhyTreeWidget::settingsPath + "/algorithm", ui->algorithmBox->currentText()); foreach (CreatePhyTreeWidget* widget, childWidgets) { widget->storeSettings(); } } void CreatePhyTreeDialogController::sl_onRestoreDefault(){ AppContext::getSettings()->remove(CreatePhyTreeWidget::settingsPath + "/algorithm"); ui->algorithmBox->setCurrentIndex(0); foreach (CreatePhyTreeWidget* widget, childWidgets) { widget->restoreDefault(); } } } ugene-1.9.8/src/corelibs/U2View/src/phyltree/TextSettingsDialog.h0000644000175000017500000000310211651544334023407 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_PHYLTREE_TEXT_SETTINGS_DIALOG_H_ #define _U2_PHYLTREE_TEXT_SETTINGS_DIALOG_H_ #include #include #include namespace U2 { class TextSettings { public: TextSettings(); QColor textColor; QFont textFont; static QColor defaultColor; static QFont defaultFont; }; class TextSettingsDialog : public QDialog, public Ui_TextSettingsDialog{ Q_OBJECT public: TextSettingsDialog(QWidget *parent, const TextSettings &textSettings); virtual void accept(); TextSettings getSettings() const; protected slots: void sl_colorButton(); private: TextSettings settings, changedSettings; void updateColorButton(); }; } //namespace #endif ugene-1.9.8/src/corelibs/U2View/src/phyltree/TreeSettingsDialog.cpp0000644000175000017500000000511511651544334023723 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "TreeSettingsDialog.h" #include namespace U2 { int TreeSettings::default_width_coef = 1; int TreeSettings::default_height_coef = 1; TreeSettings::TreeSettings() { width_coef = default_width_coef; height_coef = default_height_coef; type = PHYLOGRAM; } TreeSettingsDialog::TreeSettingsDialog(QWidget *parent, const TreeSettings &treeSettings, bool isRectLayout) : QDialog(parent), settings(treeSettings), changedSettings(treeSettings) { setupUi(this); heightSlider->setValue(settings.height_coef); widthlSlider->setValue(settings.width_coef); heightSlider->setEnabled(isRectLayout); treeViewCombo->addItem(L10N::treePhylogram()); treeViewCombo->addItem(L10N::treeCladogram()); switch ( settings.type ) { case TreeSettings::PHYLOGRAM: treeViewCombo->setCurrentIndex(treeViewCombo->findText(L10N::treePhylogram())); break; case TreeSettings::CLADOGRAM: treeViewCombo->setCurrentIndex(treeViewCombo->findText(L10N::treeCladogram())); break; default: assert(false && "Unexpected tree type value."); break; } } void TreeSettingsDialog::accept() { changedSettings.height_coef = heightSlider->value(); changedSettings.width_coef = widthlSlider->value(); if (treeViewCombo->currentText() == L10N::treePhylogram()) { changedSettings.type = TreeSettings::PHYLOGRAM; } else if (treeViewCombo->currentText() == L10N::treeCladogram()) { changedSettings.type = TreeSettings::CLADOGRAM; } else { assert(false && "Unexpected tree type value"); } settings = changedSettings; QDialog::accept(); } TreeSettings TreeSettingsDialog::getSettings() const { return settings; } } //namespace ugene-1.9.8/src/corelibs/U2View/src/phyltree/BranchSettingsDialog.h0000644000175000017500000000271611651544334023672 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_PHYLTREE_BRANCH_SETTINGS_DIALOG_H_ #define _U2_PHYLTREE_BRANCH_SETTINGS_DIALOG_H_ #include #include #include namespace U2 { class BranchSettingsDialog : public QDialog, public Ui_BranchSettingsDialog{ Q_OBJECT public: BranchSettingsDialog(QWidget *parent, const BranchSettings& branchSettings); virtual void accept(); BranchSettings getSettings() const; protected slots: void sl_colorButton(); private: BranchSettings settings, changedSettings; void updateColorButton(); }; } //namespace #endif ugene-1.9.8/src/corelibs/U2View/src/phyltree/CreatePhyTreeWidget.cpp0000644000175000017500000000173011651544334024032 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "CreatePhyTreeWidget.h" namespace U2 { const QString CreatePhyTreeWidget::settingsPath = "phytree_dialog_settings"; } ugene-1.9.8/src/corelibs/U2View/src/phyltree/CreatePhyTreeDialogController.h0000644000175000017500000000200011651544334025506 0ustar ilyailya#ifndef _CREATEPHYTREEDIALOGCONTROLLER_H_ #define _CREATEPHYTREEDIALOGCONTROLLER_H_ #include #include #include class Ui_CreatePhyTree; class QWidget; namespace U2{ class MAlignmentObject; class MAlignment; class CreatePhyTreeWidget; class U2VIEW_EXPORT CreatePhyTreeDialogController : public QDialog { Q_OBJECT public: CreatePhyTreeDialogController(QWidget* parent, const MAlignmentObject* mobj, CreatePhyTreeSettings& settings); ~CreatePhyTreeDialogController(); void insertContrWidget(int pos, CreatePhyTreeWidget* widget); private slots: void sl_okClicked(); void sl_browseClicked(); void sl_onStoreSettings(); void sl_onRestoreDefault(); private: int rightMargin; const MAlignment& msa; CreatePhyTreeSettings& settings; QList childWidgets; Ui_CreatePhyTree* ui; bool estimateResources(qint64* memoryRequiredMB); bool checkSeed(int seed); }; } #endifugene-1.9.8/src/corelibs/U2View/src/phyltree/BranchSettingsDialog.cpp0000644000175000017500000000373311651544334024225 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "BranchSettingsDialog.h" #include namespace U2 { BranchSettingsDialog::BranchSettingsDialog(QWidget *parent, const BranchSettings &branchSettings) : QDialog(parent), settings(branchSettings), changedSettings(branchSettings) { setupUi(this); thicknessSpinBox->setValue(settings.branchThickness); updateColorButton(); connect(colorButton, SIGNAL(clicked()), SLOT(sl_colorButton())); } void BranchSettingsDialog::updateColorButton() { static const QString COLOR_STYLE("QPushButton { background-color : %1;}"); colorButton->setStyleSheet(COLOR_STYLE.arg(changedSettings.branchColor.name())); } void BranchSettingsDialog::sl_colorButton() { QColor newColor = QColorDialog::getColor(changedSettings.branchColor, this); if (newColor.isValid()) { changedSettings.branchColor = newColor; updateColorButton(); } } void BranchSettingsDialog::accept() { changedSettings.branchThickness = thicknessSpinBox->value(); settings = changedSettings; QDialog::accept(); } BranchSettings BranchSettingsDialog::getSettings() const { return settings; } } //namespace ugene-1.9.8/src/corelibs/U2View/src/phyltree/CreatePhyTreeWidget.h0000644000175000017500000000256111651544334023502 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _CREATEPHYTREEWIDGET_H_ #define _CREATEPHYTREEWIDGET_H_ #include #include #include namespace U2 { class U2VIEW_EXPORT CreatePhyTreeWidget : public QWidget { public: static const QString settingsPath; CreatePhyTreeWidget(QWidget* parent) : QWidget(parent) { } virtual void fillSettings(CreatePhyTreeSettings& settings) {Q_UNUSED(settings); } virtual void storeSettings() {;} virtual void restoreDefault() {;} }; } //namespace #endif ugene-1.9.8/src/corelibs/U2View/src/WebWindow.cpp0000644000175000017500000000233611651544334020236 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "WebWindow.h" #include #include namespace U2 { WebWindow::WebWindow(const QString& title, const QString& content) : MWMDIWindow(title) { QVBoxLayout* l = new QVBoxLayout(); l->setMargin(0); setLayout(l); QWebView* textEdit = new QWebView(this); textEdit->setHtml(content); l->addWidget(textEdit); } } //namespace ugene-1.9.8/src/corelibs/U2View/src/util_ov_indexview/0000755000175000017500000000000011651544334021364 5ustar ilyailyaugene-1.9.8/src/corelibs/U2View/src/util_ov_indexview/UIndexSupport.h0000644000175000017500000000232711651544334024332 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_UINDEX_SUPPORT_H_ #define _U2_UINDEX_SUPPORT_H_ #include #include namespace U2 { class U2VIEW_EXPORT UIndexSupport : public QObject { Q_OBJECT public: UIndexSupport(); private slots: void sl_showCreateFileIndexDialog(); void sl_creatingIndexTaskStateChanged(); }; } // U2 #endif // _U2_UINDEX_SUPPORT_H_ ugene-1.9.8/src/corelibs/U2View/src/util_ov_indexview/CreateFileIndexDialog.h0000644000175000017500000000316711651544334025657 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_CREATE_UINDEX_DLG_H_ #define _U2_CREATE_UINDEX_DLG_H_ #include #include namespace U2 { struct CreateFileIndexDialogModel { QStringList inputUrls; QString outputUrl; bool gzippedOutput; bool addToProject; }; // CreateFileIndexDialogModel class CreateFileIndexDialog : public QDialog, Ui_CreateFileIndexDialog { Q_OBJECT public: CreateFileIndexDialog(QWidget* p, bool enableAddToProjButton); CreateFileIndexDialogModel getModel() const; virtual void accept(); private: CreateFileIndexDialogModel model; private slots: void sl_openInputFile(); void sl_openOutputFile(); }; } // U2 #endif ugene-1.9.8/src/corelibs/U2View/src/util_ov_indexview/UIndexViewHeaderItemWidgetImpl.h0000644000175000017500000000541511651544334027507 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_UINDEX_VIEW_HEADER_ITEM_WIDGET_IMPL_H_ #define _U2_UINDEX_VIEW_HEADER_ITEM_WIDGET_IMPL_H_ #include #include #include #include #include "UIndexViewWidgetKey.h" namespace U2 { enum ValueDataType { NO_VALUE_TYPE, STR_TYPE, NUM_TYPE, NUM_NUM_TYPE }; // ValueDataType class UIndexViewHeaderItemWidgetImpl : public QWidget, public Ui::UIndexViewHeaderItemWidget { Q_OBJECT public: static QMap< UIndexKeySimpleRuleType, QString > ruleTypeMap; static QMap< UIndexKeySimpleRuleType, ValueDataType > ruleValueMap; static QAtomicInt rulesMapInitialized; static void initializeRulesMap(); public: UIndexViewHeaderItemWidgetImpl( QWidget* p, const QStringList& keyNamesList, const QList< UIndexKeyType >& keyTypesList,UIndexKey* key = NULL ); UIndexKey* getKey() { return key; } void setKey( UIndexKey* newKey ) { key = newKey; } private: void buildMenu(); void buildSubMenu( QMenu* sub, UIndexKeyType t ); QString getKeyName( QAction* action ); QString getData( const UIndexKeySimpleRuleType& keyType ); QString getString(); QString getNum(); QString getNumNum(); signals: void si_stateChanged( UIndexKey* newKey ); private slots: void sl_selectKeyButtonClicked(); void sl_noneKeySelected(); void sl_filterSelected(); private: UIndexKey* key; QStringList keyNamesList; QList< UIndexKeyType > keyTypesList; QMenu* selectKeyButtonMenu; QString SELECTED_KEY_LABEL_DEFAULT; QString INPUT_VALUES_TITLE; QString GREETING_STR_TYPE; QString GREETING_NUM_TYPE; QString GREETING1_NUM_MUM_TYPE; QString GREETING2_NUM_MUM_TYPE; }; // UIndexViewHeaderItemWidgetImpl } // U2 #endif // _U2_UINDEX_VIEW_HEADER_ITEM_WIDGET_IMPL_H_ ugene-1.9.8/src/corelibs/U2View/src/util_ov_indexview/UIndexViewHeaderItemWidgetImpl.cpp0000644000175000017500000001753611651544334030051 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include #include #include #include #include "UIndexViewHeaderItemWidgetImpl.h" namespace U2 { QMap< UIndexKeySimpleRuleType, QString > UIndexViewHeaderItemWidgetImpl::ruleTypeMap; QMap< UIndexKeySimpleRuleType, ValueDataType > UIndexViewHeaderItemWidgetImpl::ruleValueMap; QAtomicInt UIndexViewHeaderItemWidgetImpl::rulesMapInitialized; void UIndexViewHeaderItemWidgetImpl::initializeRulesMap() { ruleTypeMap[ALL_VALUES] = tr("[All values] filter"); ruleTypeMap[STARTS_WITH] = tr("[Starts with] filter "); ruleTypeMap[ENDS_WITH] = tr("[Ends with] filter"); ruleTypeMap[CONTAINS] = tr("[Contains] filter"); ruleTypeMap[EQUAL] = tr("[Equal] filter"); ruleTypeMap[NOT_EQUAL] = tr("[Not equal] filter"); ruleTypeMap[MORE_THAN] = tr("[Greater than] filter"); ruleTypeMap[LESS_THAN] = tr("[Lower than] filter"); ruleTypeMap[IN_RANGE] = tr("[In range] filter"); ruleValueMap[ALL_VALUES] = NO_VALUE_TYPE; ruleValueMap[STARTS_WITH] = STR_TYPE; ruleValueMap[ENDS_WITH] = STR_TYPE; ruleValueMap[CONTAINS] = STR_TYPE; ruleValueMap[EQUAL] = STR_TYPE; ruleValueMap[NOT_EQUAL] = STR_TYPE; ruleValueMap[MORE_THAN] = NUM_TYPE; ruleValueMap[LESS_THAN] = NUM_TYPE; ruleValueMap[IN_RANGE] = NUM_NUM_TYPE; } UIndexViewHeaderItemWidgetImpl::UIndexViewHeaderItemWidgetImpl(QWidget* p, const QStringList& nsl, const QList< UIndexKeyType >& ktl, UIndexKey* k ) : QWidget( p ), key( k ), keyNamesList(nsl), keyTypesList(ktl) { assert( !keyNamesList.isEmpty() ); setupUi( this ); SELECTED_KEY_LABEL_DEFAULT = tr( "Select new key" ); INPUT_VALUES_TITLE = tr( "Enter a filter value" ); GREETING_STR_TYPE = tr( "Enter a string value" ); GREETING_NUM_TYPE = tr( "Enter a number value" ); GREETING1_NUM_MUM_TYPE = tr( "Enter a lower bound" ); GREETING2_NUM_MUM_TYPE = tr( "Enter an upper bound" ); if( rulesMapInitialized.testAndSetAcquire( 0, 1 ) ) { UIndexViewHeaderItemWidgetImpl::initializeRulesMap(); } if( NULL == key ) { selectedKeyLabel->setText( SELECTED_KEY_LABEL_DEFAULT ); } else { assert( keyNamesList.contains( key->keyName ) ); selectedKeyLabel->setText( key->keyName ); } buildMenu(); connect( selectKeyButton, SIGNAL( clicked() ), SLOT( sl_selectKeyButtonClicked() ) ); } void UIndexViewHeaderItemWidgetImpl::buildMenu() { selectKeyButtonMenu = new QMenu( this ); QAction* noneAction = selectKeyButtonMenu->addAction( keyNamesList.first() ); connect( noneAction, SIGNAL( triggered() ), SLOT( sl_noneKeySelected() ) ); selectKeyButtonMenu->addSeparator(); int sz = keyNamesList.size(); for( int i = 1; i < sz; ++i ) { QMenu* sub = selectKeyButtonMenu->addMenu( keyNamesList.at( i ) ); buildSubMenu( sub, keyTypesList.at( i ) ); } } void UIndexViewHeaderItemWidgetImpl::buildSubMenu( QMenu* sub, UIndexKeyType t ) { assert( NULL != sub ); QMap< UIndexKeySimpleRuleType, QString >::const_iterator it = ruleTypeMap.constBegin(); while( ruleTypeMap.constEnd() != it ) { if( STR_TYPE == ruleValueMap[it.key()] || TYPE_NUM == t ) { QAction* curFilterAction = sub->addAction( it.value() ); connect( curFilterAction, SIGNAL( triggered() ), SLOT( sl_filterSelected() ) ); } ++it; } } void UIndexViewHeaderItemWidgetImpl::sl_noneKeySelected() { selectedKeyLabel->setText( SELECTED_KEY_LABEL_DEFAULT ); emit si_stateChanged( NULL ); } void UIndexViewHeaderItemWidgetImpl::sl_selectKeyButtonClicked() { selectKeyButtonMenu->exec( QCursor::pos() ); } void UIndexViewHeaderItemWidgetImpl::sl_filterSelected() { QAction* filterAction = qobject_cast< QAction* >( sender() ); QList< UIndexKeySimpleRuleType > typesList = ruleTypeMap.keys( filterAction->text() ); assert( !typesList.isEmpty() ); UIndexKeySimpleRuleType ruleType = typesList.first(); QString data = getData( ruleType ); if( data.isEmpty() ) { return; } QString keyName = getKeyName( filterAction ); assert( keyNamesList.contains( keyName ) ); selectedKeyLabel->setText( keyName ); UIndexKeyRule* rule = new UIndexKeyRule( new UIndexKeyRuleItem( ruleType, data, BAD_OP ) ); UIndexKeyType keyType = ( NULL == key )? TYPE_STR: key->type; UIndexKey* newKey = new UIndexKey( keyName, keyType, rule ); emit si_stateChanged( newKey ); } QString UIndexViewHeaderItemWidgetImpl::getKeyName( QAction* action ) { assert( NULL != action ); QMenu* parentMenu = qobject_cast< QMenu* >( action->parentWidget() ); assert( NULL != parentMenu ); return parentMenu->title(); } QString UIndexViewHeaderItemWidgetImpl::getData( const UIndexKeySimpleRuleType& keyType ) { QString ret; ValueDataType valueType = ruleValueMap[keyType]; switch( valueType ) { case NO_VALUE_TYPE: ret = " "; // not empty is important break; case STR_TYPE: ret = getString(); break; case NUM_TYPE: ret = getNum(); break; case NUM_NUM_TYPE: ret = getNumNum(); break; default: assert( 0 ); } return ret; } QString UIndexViewHeaderItemWidgetImpl::getString() { bool ok = false; QString ret; do { ret = QInputDialog::getText( this, INPUT_VALUES_TITLE, GREETING_STR_TYPE, QLineEdit::Normal, "", &ok ); if( ok && ret.isEmpty() ) { QMessageBox::critical( this, tr( "Error" ), tr( "The value can't be empty" ) ); continue; } break; }while( 1 ); if( !ok ) { ret.clear(); } return ret; } QString UIndexViewHeaderItemWidgetImpl::getNum() { bool ok = false; QString ret; int val = 0; val = QInputDialog::getInteger( this, INPUT_VALUES_TITLE, GREETING_NUM_TYPE, 0, -INT_MAX, INT_MAX, 1, &ok ); if( ok ) { ret = QString::number( val ); } return ret; } QString UIndexViewHeaderItemWidgetImpl::getNumNum() { bool ok = false; QString ret; int val1 = 0; int val2 = 0; do { ret.clear(); val1 = QInputDialog::getInteger( this, INPUT_VALUES_TITLE, GREETING1_NUM_MUM_TYPE, 0, -INT_MAX, INT_MAX, 1, &ok ); if( ok ) { ret = QString::number( val1 ) + " "; val2 = QInputDialog::getInteger( this, INPUT_VALUES_TITLE, GREETING2_NUM_MUM_TYPE, 0, -INT_MAX, INT_MAX, 1, &ok ); if( ok ) { if( val2 < val1 ) { QMessageBox::critical( this, tr( "Error!" ), tr( "Upper bound must be greater than lower" ) ); continue; } ret += QString::number( val2 ); } else { ret.clear(); break; } } break; }while( 1 ); return ret; } } // U2 ugene-1.9.8/src/corelibs/U2View/src/util_ov_indexview/UIndexViewerTasks.cpp0000644000175000017500000000557311651544334025466 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include #include #include #include #include "UIndexViewerFactory.h" #include "UIndexViewer.h" #include "UIndexViewerTasks.h" namespace U2 { /************************************************** ****************open new view task***************** */ OpenUIndexViewerTask::OpenUIndexViewerTask( UIndexObject* obj ) : ObjectViewTask( UIndexViewerFactory::ID ), uindObj( obj ) { if( uindObj.isNull() ) { stateInfo.setError(tr( "Index object is null" )); } } OpenUIndexViewerTask::OpenUIndexViewerTask( Document* doc ) : ObjectViewTask( UIndexViewerFactory::ID ), uindObj( NULL ) { if( NULL == doc || doc->isLoaded() ) { stateInfo.setError(tr( "Document is null or loaded" )); return; } documentsToLoad.append( doc ); } OpenUIndexViewerTask::OpenUIndexViewerTask( UnloadedObject* obj ) : ObjectViewTask( UIndexViewerFactory::ID ), unloadedReference( obj ) { assert( obj->getLoadedObjectType() == GObjectTypes::UINDEX ); documentsToLoad.append( obj->getDocument() ); } void OpenUIndexViewerTask::open() { if( stateInfo.hasError() ) { return; } if( uindObj.isNull() ) { Document* doc = documentsToLoad.first(); QList< GObject* > objs = doc->findGObjectByType( GObjectTypes::UINDEX ); if( objs.isEmpty() ) { return; } uindObj = qobject_cast< UIndexObject* >( objs.first() ); assert( !uindObj.isNull() ); } viewName = GObjectViewUtils::genUniqueViewName( uindObj->getDocument(), uindObj ); uiLog.info(tr("Opening index viewer for object %1" ).arg( uindObj->getGObjectName())); QString viewName = GObjectViewUtils::genUniqueViewName( uindObj->getDocument(), uindObj ); UIndexViewer* viewer = new UIndexViewer( viewName, uindObj ); GObjectViewWindow* window = new GObjectViewWindow( viewer, viewName, false ); MWMDIManager* mdiManager = AppContext::getMainWindow()->getMDIManager(); mdiManager->addMDIWindow( window ); } } // U2 ugene-1.9.8/src/corelibs/U2View/src/util_ov_indexview/ui/0000755000175000017500000000000011651544334022001 5ustar ilyailyaugene-1.9.8/src/corelibs/U2View/src/util_ov_indexview/ui/UIndexViewHeaderItemWidget.ui0000644000175000017500000000401211651544334027460 0ustar ilyailya UIndexViewHeaderItemWidget 0 0 194 44 0 0 Create annotation true 0 0 0 0 40 24 true ... :/core/images/uindexview_select_field.png:/core/images/uindexview_select_field.png ugene-1.9.8/src/corelibs/U2View/src/util_ov_indexview/ui/UIndexViewWidget.ui0000644000175000017500000000316711651544334025542 0ustar ilyailya UIndexViewWidget 0 0 423 367 0 0 Create annotation Manage columns Manage columns button > Qt::Vertical 20 328 ugene-1.9.8/src/corelibs/U2View/src/util_ov_indexview/ui/CreateFileIndexDialog.ui0000644000175000017500000001215611651544334026460 0ustar ilyailya CreateFileIndexDialog Qt::WindowModal 0 0 454 173 Create index file File(s) to index: File(s) to index separated by semicolon false ... File to store index: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> <html><head><meta name="qrichtext" content="1" /><style type="text/css"> p, li { white-space: pre-wrap; } </style></head><body style=" font-family:'MS Shell Dlg 2'; font-size:8.25pt; font-weight:400; font-style:normal;"> <p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-size:8pt;">Path to output index file</span></p></body></html> ... Compress true Add to project true Qt::Vertical 20 13 Qt::Horizontal 325 23 Ok true Cancel cancelButton clicked() CreateFileIndexDialog reject() 340 124 194 73 okButton clicked() CreateFileIndexDialog accept() 257 124 194 73 ugene-1.9.8/src/corelibs/U2View/src/util_ov_indexview/ui/UIndexExportToNewFileDialog.ui0000644000175000017500000000730711651544334027642 0ustar ilyailya UIndexExportToNewFileDialog 0 0 450 105 Export indexed document 0 0 Export file ... compress file true Qt::Horizontal 168 20 Qt::Vertical 20 1 Qt::Horizontal 40 20 Ok true Cancel cancelButton clicked() UIndexExportToNewFileDialog reject() 401 82 224 52 okButton clicked() UIndexExportToNewFileDialog accept() 318 82 224 52 ugene-1.9.8/src/corelibs/U2View/src/util_ov_indexview/UIndexViewerFactory.h0000644000175000017500000000316711651544334025452 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_UINDEX_VIEWER_FACTORY_H_ #define _U2_UINDEX_VIEWER_FACTORY_H_ #include namespace U2 { class MultiGSelection; class U2VIEW_EXPORT UIndexViewerFactory : public GObjectViewFactory { Q_OBJECT public: UIndexViewerFactory(); virtual bool canCreateView(const MultiGSelection& multiSelection); virtual bool isStateInSelection(const MultiGSelection& multiSelection, const QVariantMap& stateData); virtual Task* createViewTask(const MultiGSelection& multiSelection, bool single = false); virtual Task* createViewTask(const QString& viewName, const QVariantMap& stateData); bool supportsSavedStates() const; static const GObjectViewFactoryId ID; }; // UIndexViewerFactory } // U2 #endif // _U2_UINDEX_VIEWER_FACTORY_H_ ugene-1.9.8/src/corelibs/U2View/src/util_ov_indexview/UIndexExportToNewFileDialogImpl.h0000644000175000017500000000313311651544334027652 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_UINDEX_EXPORT_TO_NEW_DIALOG_IMPL_H_ #define _U2_UINDEX_EXPORT_TO_NEW_DIALOG_IMPL_H_ #include namespace U2 { struct UIndexExportToNewFileDialogModel { QString exportFilename; bool gzipExported; }; class UIndexExportToNewFileDialogImpl : public QDialog, public Ui::UIndexExportToNewFileDialog { Q_OBJECT public: static const QString SETTINGS_LAST_DIRECTORY; UIndexExportToNewFileDialogImpl(); UIndexExportToNewFileDialogModel getModel() const; virtual void accept(); private slots: void sl_openExportFile(); private: UIndexExportToNewFileDialogModel model; }; // UIndexExportToNewFileDialogImpl } // U2 #endif // _U2_UINDEX_EXPORT_TO_NEW_DIALOG_IMPL_H_ ugene-1.9.8/src/corelibs/U2View/src/util_ov_indexview/UIndexViewWidgetImpl.cpp0000644000175000017500000003525111651544334026113 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include #include #include #include #include "UIndexViewWidgetKey.h" #include "UIndexViewWidgetImpl.h" namespace U2 { const float UIndexViewWidgetImpl::SHOW_KEY_PERCENT_BORDER = 30.0f; UIndexViewWidgetImpl::UIndexViewWidgetImpl( QWidget* p, const UIndex& i ) : QWidget( p ), ind( i ) { VALUE_NOT_SELECTED = tr( "No filter selected" ); KEY_FORMAT = tr( "Document Format" ); KEY_URL = tr( "URL" ); KEY_NONE = tr( "None" ); COLUMN_MENU_ACTION_HIDE = tr( "Hide column" ); COLUMN_MENU_ACTION_DELETE = tr( "Remove column" ); NO_HIDDEN_COLUMNS = tr( "No hidden columns" ); SHOW_HIDDEN_COLS_STR = tr( "Show hidden columns:" ); SHOW_HIDDEN_COLS_BEGIN = tr( "column " ); ADD_LAST_EMPTY_COL = tr( "Add column" ); setupUi( this ); setContextMenuPolicy( Qt::CustomContextMenu ); uindexTable->horizontalHeader()->setHighlightSections( false ); uindexTable->horizontalHeader()->setClickable( true ); uindexTable->setEditTriggers( QAbstractItemView::NoEditTriggers ); uindexTable->setSelectionBehavior( QAbstractItemView::SelectRows ); connect( uindexTable->horizontalHeader(), SIGNAL( sectionClicked( int ) ), SLOT( sl_horHeaderSectionClicked( int ) ) ); // connect( manageColumsButton, SIGNAL( clicked() ), SLOT( sl_manageColumnsButtonClicked() ) ); manageColumsButton->setVisible(false); initKeyNamesList(); detectTypes(); uindexTable->setRowCount( ind.items.size() + 1 ); initTable(); execRules(); uindexTable->resizeColumnsToContents(); } UIndexViewWidgetImpl::~UIndexViewWidgetImpl() { foreach( UIndexViewHeaderItemWidgetImpl* headerIt, headerItems ) { assert( NULL != headerIt ); UIndexKey* key = headerIt->getKey(); delete key; } } void UIndexViewWidgetImpl::initKeyNamesList() { keyNamesList << KEY_NONE; keyNamesList << KEY_FORMAT; keyNamesList << KEY_URL; foreach( const UIndex::ItemSection& item, ind.items ) { QHash< QString, QString >::const_iterator it = item.keys.constBegin(); while( item.keys.constEnd() != it ) { if( !keyNamesList.contains( it.key() ) ) { keyNamesList << it.key(); } ++it; } } sortKeyNamesList(); } void UIndexViewWidgetImpl::sortKeyNamesList() { int i = 0; int sz = keyNamesList.size(); for( i = 0; i < sz; ++i ) { const QString& keyName = keyNamesList.at( i ); if( CreateFileIndexTask::KEY_ACCESSION == keyName || CreateFileIndexTask::KEY_NAME == keyName || CreateFileIndexTask::KEY_DESCRIPTION == keyName ) { keyNamesList.move( i, 1 ); } } } void UIndexViewWidgetImpl::detectTypes() { int i = 0; int sz = keyNamesList.size(); for( i = 0; i < sz; ++i ) { const QString& keyName = keyNamesList.at( i ); if( KEY_NONE == keyName || KEY_FORMAT == keyName || KEY_URL == keyName ) { keyTypesList << TYPE_STR; continue; } bool isNumber = true; foreach( const UIndex::ItemSection& item, ind.items ) { if( item.keys.contains( keyName ) ) { bool ok = false; const QString& val = item.keys.value( keyName ); val.toInt( &ok ); isNumber = isNumber && ok; if( !isNumber ) { break; } } } keyTypesList << ( ( isNumber )? TYPE_NUM: TYPE_STR ); } } void UIndexViewWidgetImpl::initTable() { int curCol = 0; int i = 0; int sz = keyNamesList.size(); for( i = 0; i < sz; ++i ) { const QString& keyName = keyNamesList.at( i ); if( KEY_NONE == keyName || KEY_FORMAT == keyName || KEY_URL == keyName ) { continue; } if( isSignificantKey( keyName ) ) { UIndexKeyRule* rule = new UIndexKeyRule( new UIndexKeyRuleItem() ); UIndexKey* key = new UIndexKey( keyName, TYPE_STR, rule ); UIndexViewHeaderItemWidgetImpl* header = new UIndexViewHeaderItemWidgetImpl( this, keyNamesList, keyTypesList, key ); insertHeaderItem( header ); addColumn( header ); setColumnVals( curCol ); curCol++; } } sl_addLastEmptyCol(); } bool UIndexViewWidgetImpl::isSignificantKey( const QString& keyName ) { float oneKeyPercent = ( 1.0f / ind.items.size() ) * 100.0f; float curPercentCount = 0.0f; bool res = false; foreach( const UIndex::ItemSection& it, ind.items ) { if( it.keys.contains( keyName ) ) { curPercentCount += oneKeyPercent; } if( SHOW_KEY_PERCENT_BORDER <= curPercentCount ) { res = true; break; } } return res; } void UIndexViewWidgetImpl::insertHeaderItem( UIndexViewHeaderItemWidgetImpl* headerIt ) { assert( NULL != headerIt ); headerItems << headerIt; connect( headerIt, SIGNAL( si_stateChanged( UIndexKey* ) ), SLOT( sl_headerWidgetStateChanged( UIndexKey* ) ) ); } void UIndexViewWidgetImpl::addColumn( UIndexViewHeaderItemWidgetImpl* headerIt ) { assert( NULL != headerIt ); int ind = uindexTable->columnCount(); uindexTable->insertColumn( ind ); QTableWidgetItem* colItem = new QTableWidgetItem(); uindexTable->setHorizontalHeaderItem( ind, colItem ); uindexTable->setCellWidget( HEADER_ITEMS_ROW, ind, headerIt ); setHorizontalHeaderLabel( ind ); } QString UIndexViewWidgetImpl::getRuleStrRepresent( const UIndexKeyRule* r ) const { assert( NULL != r ); QString ret; if( r->isSimple() ) { assert( NULL != r->root ); ret = UIndexViewHeaderItemWidgetImpl::ruleTypeMap[r->root->type] + ": " + r->root->data; } else { ret = tr( "Complex rule" ); } return ret; } void UIndexViewWidgetImpl::setHorizontalHeaderLabel( int col ) { assert( 0 <= col && uindexTable->columnCount() > col ); UIndexKey* key = headerItems.at( col )->getKey(); if( NULL == key || NULL == key->rule ) { uindexTable->horizontalHeaderItem( col )->setText( VALUE_NOT_SELECTED ); } else { QString name = getRuleStrRepresent( key->rule ); assert( !name.isEmpty() ); uindexTable->horizontalHeaderItem( col )->setText( name ); } } void UIndexViewWidgetImpl::setColumnVals( int col ) { assert( 0 <= col && uindexTable->columnCount() > col ); UIndexKey* key = headerItems.at( col )->getKey(); QList< UIndex::ItemSection > items = ind.items; int sz = items.size(); int i = 0; if( NULL == key ) { // init with empty items for( i = 0; i < sz; ++i ) { QTableWidgetItem* it = new QTableWidgetItem( "" ); uindexTable->setItem( i + 1, col, it ); } } else { QString keyName = key->keyName; QString val; for( i = 0; i < sz; ++i ) { UIndex::ItemSection curIt = items[i]; if( KEY_FORMAT == keyName ) { val = curIt.docFormat; } else if( KEY_URL == keyName ) { UIndex::IOSection curIO = ind.getIOSection( curIt.ioSectionId ); assert( !curIO.sectionId.isEmpty() && !curIO.url.isEmpty() ); val = curIO.url; } else { val = curIt.keys.value( keyName ); } QTableWidgetItem* it = new QTableWidgetItem( val ); uindexTable->setItem( i + 1, col, it ); } } } void UIndexViewWidgetImpl::sl_headerWidgetStateChanged( UIndexKey* newKey ) { UIndexViewHeaderItemWidgetImpl* headerItem = qobject_cast< UIndexViewHeaderItemWidgetImpl* >( sender() ); assert( NULL != headerItem ); int ind = headerItems.indexOf( headerItem ); UIndexKey* oldKey = headerItem->getKey(); delete oldKey; headerItem->setKey( newKey ); setHorizontalHeaderLabel( ind ); if( uindexTable->columnCount() - 1 == ind && NULL != newKey ) { UIndexViewHeaderItemWidgetImpl* newHeaderIt = new UIndexViewHeaderItemWidgetImpl( this, keyNamesList, keyTypesList, NULL ); insertHeaderItem( newHeaderIt ); addColumn( newHeaderIt ); } setColumnVals( ind ); execRules(); uindexTable->resizeColumnsToContents(); } bool UIndexViewWidgetImpl::execOneRule( int col, const QString& val ) { assert( 0 <= col && uindexTable->columnCount() > col ); if( val.isEmpty() ) { return false; } UIndexKey* key = headerItems.at( col )->getKey(); assert( NULL != key ); UIndexKeyRule* rule = key->rule; assert( NULL != rule ); return rule->exec( val ); } bool UIndexViewWidgetImpl::rulesPassed( int row ) { assert( 0 <= row && uindexTable->rowCount() > row ); int colSz = uindexTable->columnCount(); int i = 0; bool res = true; for( i = 0; i < colSz; ++i ) { if( isEmptyCol( i ) ) { continue; } QString val = uindexTable->item( row, i )->text(); res = res && execOneRule( i, val ); if( false == res ) { break; } } return res; } void UIndexViewWidgetImpl::execRules() { int rowCount = uindexTable->rowCount(); int i = 0; bool hasNotEmptyColumn = hasNotEmptyCol(); for( i = 1; i < rowCount; ++i ) { bool showThis = hasNotEmptyColumn && rulesPassed( i ); if( showThis ) { uindexTable->showRow( i ); } else { uindexTable->hideRow( i ); } } } bool UIndexViewWidgetImpl::isEmptyCol( int col ) const{ assert( 0 <= col && uindexTable->columnCount() > col ); UIndexViewHeaderItemWidgetImpl* headerIt = headerItems.at( col ); assert( NULL != headerIt ); return NULL == headerIt->getKey(); } bool UIndexViewWidgetImpl::hasNotEmptyCol() const { int colCount = uindexTable->columnCount(); int i = 0; bool res = false; for( i = 0; i < colCount; ++i ) { res = res || !isEmptyCol( i ); if( res ) { break; } } return res; } void UIndexViewWidgetImpl::sl_horHeaderSectionClicked( int col ) { QMenu columnMenu(this); QAction* delAction = NULL; QAction* hideAction = NULL; if (col!=0 && col + 1 != uindexTable->columnCount()) { delAction = columnMenu.addAction(tr("Remove column")); delAction->setParent(&columnMenu); } if (columnMenu.isEmpty()) { return; } QAction* selected = columnMenu.exec( QCursor::pos() ); if (selected == NULL) { return; } if( selected == hideAction) { uindexTable->hideColumn( col ); assert( !hiddenColumns.contains( col ) ); hiddenColumns << col; } else if( selected == delAction) { removeColumn( col ); execRules(); } } void UIndexViewWidgetImpl::removeColumn( int col ) { assert( 0 <= col && uindexTable->columnCount() > col ); uindexTable->removeColumn( col ); UIndexKey* key = headerItems.at( col )->getKey(); delete key; headerItems.removeAt( col ); } void UIndexViewWidgetImpl::sl_manageColumnsButtonClicked() { QMenu manageColsMenu; if( hiddenColumns.isEmpty() ) { manageColsMenu.addAction( NO_HIDDEN_COLUMNS )->setParent(&manageColsMenu); } else { manageColsMenu.addAction( SHOW_HIDDEN_COLS_STR )->setParent(&manageColsMenu); manageColsMenu.addSeparator(); foreach( int colNum, hiddenColumns ) { assert( 0 <= colNum && uindexTable->columnCount() > colNum ); UIndexViewHeaderItemWidgetImpl* head = headerItems.at( colNum ); UIndexKey* key = head->getKey(); QString keyName = ( NULL == key )? keyNamesList.first(): key->keyName; QString showColStr = SHOW_HIDDEN_COLS_BEGIN + QString::number( colNum ) + ":" + keyName; QAction* showColAction = manageColsMenu.addAction( showColStr ); showColAction->setParent(&manageColsMenu); connect( showColAction, SIGNAL( triggered() ), SLOT( sl_showHiddenColumn() ) ); } } int colCount = uindexTable->columnCount(); if( !colCount || !isEmptyCol( colCount - 1 ) ) { manageColsMenu.addSeparator(); QAction* addLastCol = manageColsMenu.addAction( ADD_LAST_EMPTY_COL ); addLastCol->setParent(&manageColsMenu); connect( addLastCol, SIGNAL( triggered() ), SLOT( sl_addLastEmptyCol() ) ); } manageColsMenu.exec( QCursor::pos() ); } void UIndexViewWidgetImpl::sl_addLastEmptyCol() { UIndexViewHeaderItemWidgetImpl* header = new UIndexViewHeaderItemWidgetImpl( this, keyNamesList, keyTypesList, NULL ); insertHeaderItem( header ); addColumn( header ); setColumnVals( uindexTable->columnCount() - 1 ); } void UIndexViewWidgetImpl::sl_showHiddenColumn() { QAction* showColAction = qobject_cast< QAction* >( sender() ); assert( NULL != showColAction ); QString txt = showColAction->text(); assert( !txt.isEmpty() ); int numStrEnd = txt.indexOf( ":" ); int numStrBegin = SHOW_HIDDEN_COLS_BEGIN.size() - 1; assert( numStrBegin < numStrEnd ); QString numStr = txt.mid( numStrBegin, numStrEnd - numStrBegin ); bool ok = false; int colNum = numStr.toInt( &ok ); assert( ok && 0 <= colNum && uindexTable->columnCount() > colNum ); assert( hiddenColumns.contains( colNum ) ); uindexTable->showColumn( colNum ); hiddenColumns.removeAll( colNum ); } UIndex UIndexViewWidgetImpl::getIndex() const { return ind; } QList< int > UIndexViewWidgetImpl::getSelectedDocNums() const { QList< QTableWidgetItem* > itemz = uindexTable->selectedItems(); QList< int > ret; foreach( QTableWidgetItem* it, itemz ) { int docNum = it->row() - 1; if( !ret.contains( docNum ) ) { ret << docNum; } } return ret; } } // U2 ugene-1.9.8/src/corelibs/U2View/src/util_ov_indexview/UIndexViewer.cpp0000644000175000017500000000747411651544334024462 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include #include #include #include #include #include #include "UIndexViewerFactory.h" #include "UIndexViewer.h" #include "UIndexExportToNewFileDialogImpl.h" namespace { using namespace U2; const QString GZIP_END = ".gz"; void updateModel( UIndexExportToNewFileDialogModel& model ) { if( model.gzipExported && !model.exportFilename.endsWith( GZIP_END ) ) { model.exportFilename.append( GZIP_END ); } } } // anonymous namespace namespace U2 { const QString UIndexViewer::EXPORT_MENU_NAME = "export_menu_name"; UIndexViewer::UIndexViewer( const QString& viewName, UIndexObject* o ) : GObjectView( UIndexViewerFactory::ID, viewName ), indexObject( o ), ui( NULL ) { objects.append( indexObject ); requiredObjects.append( indexObject ); } void UIndexViewer::buildStaticToolbar(QToolBar* tb) { GObjectView::buildStaticToolbar( tb ); } void UIndexViewer::buildStaticMenu( QMenu* m ) { if( NULL == m ) { return; } addExportMenu( m ); GObjectView::buildStaticMenu( m ); GUIUtils::disableEmptySubmenus( m ); } void UIndexViewer::addExportMenu( QMenu* m ) { assert( NULL != m ); QMenu* exMenu = m->addMenu( tr( "Export " ) ); exMenu->menuAction()->setObjectName( EXPORT_MENU_NAME ); QAction* exToNewDoc = exMenu->addAction(tr("Save selection to a new file")); connect( exToNewDoc, SIGNAL( triggered() ), SLOT( sl_exportToNewDoc() ) ); } Task* UIndexViewer::updateViewTask(const QVariantMap& stateData) { Q_UNUSED(stateData); return NULL; } QWidget* UIndexViewer::createWidget() { assert( NULL == ui ); ui = new UIndexViewWidgetImpl( NULL, indexObject->getIndex() ); connect( ui, SIGNAL( customContextMenuRequested (const QPoint& ) ), SLOT ( sl_onContextMenuRequested (const QPoint&) ) ); ui->setWindowIcon(GObjectTypes::getTypeInfo(GObjectTypes::UINDEX).icon); return ui; } void UIndexViewer::sl_onContextMenuRequested( const QPoint& pos ) { Q_UNUSED( pos ); QMenu menu; addExportMenu( &menu ); emit si_buildPopupMenu( this, &menu ); GUIUtils::disableEmptySubmenus( &menu ); menu.exec( QCursor::pos() ); } void UIndexViewer::sl_exportToNewDoc() { QList< int > docNums = ui->getSelectedDocNums(); if( docNums.isEmpty() ) { QMessageBox::critical( ui, tr( "Error" ), tr( "No items selected" ) ); return; } UIndex index = ui->getIndex(); //TODO: pass file ext? //TODO: support per-object export? UIndexExportToNewFileDialogImpl dlg; int rc = dlg.exec(); if (rc == QDialog::Rejected) { return; } UIndexExportToNewFileDialogModel model = dlg.getModel(); updateModel( model ); ExportToNewFileFromIndexTask* exportTask = new ExportToNewFileFromIndexTask( index, docNums, model.exportFilename ); AppContext::getTaskScheduler()->registerTopLevelTask( exportTask ); } } // U2 ugene-1.9.8/src/corelibs/U2View/src/util_ov_indexview/UIndexSupport.cpp0000644000175000017500000001516111651544334024665 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "UIndexSupport.h" #include "CreateFileIndexDialog.h" #include #include #include #include #include #include #include #include #include #include #include namespace U2 { const QString GZIP_END = ".gz"; const QString UIND_END = ".uind"; static void updateModel( CreateFileIndexDialogModel& m ) { if( m.gzippedOutput && !m.outputUrl.endsWith( GZIP_END ) ) { m.outputUrl.append( GZIP_END ); } int sz = m.outputUrl.size(); bool outIsGzip = m.outputUrl.endsWith( GZIP_END ); QString outRawName = ( outIsGzip )? m.outputUrl.left( sz - GZIP_END.size() ): m.outputUrl; if( !outRawName.endsWith( UIND_END ) ) { outRawName.append( UIND_END ); } m.outputUrl = ( outIsGzip )? outRawName + GZIP_END: outRawName; } /************************* * UIndexSupport *************************/ UIndexSupport::UIndexSupport() { QAction* showDlgAction = new QAction( tr("Index large file(s)..."), this ); showDlgAction->setIcon(QIcon(":core/images/table_add.png")); connect( showDlgAction, SIGNAL( triggered() ), SLOT( sl_showCreateFileIndexDialog() ) ); AppContext::getMainWindow()->getTopLevelMenu( MWMENU_TOOLS )->addAction( showDlgAction ); } void UIndexSupport::sl_showCreateFileIndexDialog() { CreateFileIndexDialogModel model; CreateFileIndexDialog dlg(QApplication::activeWindow(), AppContext::getProject() != NULL); int rc = dlg.exec(); if (rc == QDialog::Rejected) { return; } model = dlg.getModel(); updateModel( model ); IOAdapterFactory * outFactory = AppContext::getIOAdapterRegistry()-> getIOAdapterFactoryById(BaseIOAdapters::url2io( model.outputUrl )); if( outFactory == NULL ) { QMessageBox::critical(NULL, tr("Error!"), tr("Cannot write output file: unknown io adapter for %1").arg(model.outputUrl)); return; } QList inUrls = model.inputUrls; QList< IOAdapterFactory* > inFactories; for(int i = 0; i < inUrls.size(); ++i) { QString url = inUrls.at(i); IOAdapterFactory * factory = AppContext::getIOAdapterRegistry()->getIOAdapterFactoryById( BaseIOAdapters::url2io(url)); if(factory == NULL) { QMessageBox::critical(NULL, tr("Error!"), tr("Cannot read input file: unknown io adapter for %1").arg(url)); return; } inFactories.append(factory); } CreateFileIndexTask* t = new CreateFileIndexTask( inUrls, model.outputUrl, inFactories, outFactory ); AppContext::getTaskScheduler()->registerTopLevelTask(t); if(model.addToProject) { connect( t, SIGNAL(si_stateChanged()), SLOT(sl_creatingIndexTaskStateChanged()) ); } } void UIndexSupport::sl_creatingIndexTaskStateChanged() { CreateFileIndexTask * t = qobject_cast(sender()); assert(t != NULL); if( t->getState() != Task::State_Finished ) { return; } QString url = t->getOutputUrl(); assert(!url.isEmpty()); DocumentFormat * format = AppContext::getDocumentFormatRegistry()->getFormatById(BaseDocumentFormats::INDEX); assert(format != NULL); IOAdapterFactory * iof = AppContext::getIOAdapterRegistry()->getIOAdapterFactoryById(BaseIOAdapters::url2io(url)); assert(iof != NULL); Document * doc = new Document( format, iof, url, QList(), QVariantMap() ); AppContext::getTaskScheduler()->registerTopLevelTask(new AddDocumentTask(doc)); } /************************* * CreateFileIndexDialog *************************/ CreateFileIndexDialog::CreateFileIndexDialog(QWidget* p, bool enableAddToProjButton): QDialog(p) { setupUi( this ); connect( inputFileOpenButton, SIGNAL( clicked() ), SLOT( sl_openInputFile() ) ); connect( outputFileOpenButton, SIGNAL( clicked() ), SLOT( sl_openOutputFile() ) ); addToProjectCheckBox->setChecked(enableAddToProjButton); addToProjectCheckBox->setEnabled(enableAddToProjButton); } static const QString SEMICOLON = ";"; void CreateFileIndexDialog::sl_openInputFile() { LastOpenDirHelper helper; QStringList files = QFileDialog::getOpenFileNames(this, tr("Select files"), helper.dir); model.inputUrls = files; if( !files.isEmpty() ) { inputFileEdit->setText(files.join(SEMICOLON)); if( files.size() == 1 ) { outputFileEdit->setText(files.first() + UIND_END); } else { outputFileEdit->setText(QFileInfo(files.first()).absoluteDir().absolutePath() + "/index" + UIND_END); } helper.url = files.first(); } } void CreateFileIndexDialog::sl_openOutputFile() { LastOpenDirHelper h; h.url = QFileDialog::getSaveFileName( this, tr( "Select index file to create" ), h.dir ); if (!h.url.isEmpty()) { outputFileEdit->setText(h.url); } } void CreateFileIndexDialog::accept() { // input urls are set in sl_openInputFile model.outputUrl = outputFileEdit->text(); model.gzippedOutput = ( Qt::Checked == gzipOutputCheckBox->checkState() ); model.addToProject = Qt::Checked == addToProjectCheckBox->checkState(); model.inputUrls = inputFileEdit->text().split(SEMICOLON); if (model.inputUrls.isEmpty()) { QMessageBox::critical(this, tr("Error!"), tr("No input files supplied!")); inputFileEdit->setFocus(); return; } if (model.outputUrl.isEmpty()) { QMessageBox::critical(this, tr("Error!"), tr("Invalid output file name!")); outputFileEdit->setFocus(); return; } QDialog::accept(); } CreateFileIndexDialogModel CreateFileIndexDialog::getModel() const { return model; } } // U2 ugene-1.9.8/src/corelibs/U2View/src/util_ov_indexview/UIndexViewWidgetKey.h0000644000175000017500000000551711651544334025411 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_UINDEX_VIEW_WIDGET_FIELD_KEY_H_ #define _U2_UINDEX_VIEW_WIDGET_FIELD_KEY_H_ #include #include namespace U2 { enum UIndexKeySimpleRuleType { BAD_TYPE = -1, ALL_VALUES, STARTS_WITH, ENDS_WITH, CONTAINS, EQUAL, NOT_EQUAL, // REGEXP, MORE_THAN, LESS_THAN, IN_RANGE }; // UIndexKeyRuleType enum UIndexKeyRuleOperation { BAD_OP = -1, AND, OR, NOT }; // UIndexKeyRuleOperation struct UIndexKeyRuleItem { UIndexKeySimpleRuleType type; QString data; UIndexKeyRuleOperation op; QList< UIndexKeyRuleItem* > children; UIndexKeyRuleItem( const UIndexKeySimpleRuleType& t = ALL_VALUES, const QString& data = QString::null, const UIndexKeyRuleOperation& op = BAD_OP ); bool isOperationItem() const; }; // UIndexKeyRuleItem /* * A rule is represented as a tree of boolean operations ( AND, OR, NOT ) * and simple rules as a lists of that tree */ class UIndexKeyRule { public: UIndexKeyRule( UIndexKeyRuleItem* root = NULL ); ~UIndexKeyRule(); void delItem( UIndexKeyRuleItem* it ); bool isSimple() const { return NULL == root || root->children.isEmpty(); } bool exec( const QString& val ); private: UIndexKeyRule( const UIndexKeyRule& ); UIndexKeyRule& operator =( const UIndexKeyRule& ); bool execItem( UIndexKeyRuleItem* item, const QString& val ); bool execSimpleItem( UIndexKeyRuleItem* item, const QString& val ); public: UIndexKeyRuleItem* root; }; // UIndexKeyRule enum UIndexKeyType { TYPE_STR, TYPE_NUM }; // UIndexKeyType struct UIndexKey { QString keyName; UIndexKeyType type; UIndexKeyRule* rule; UIndexKey( const QString& name = QString::null, const UIndexKeyType& t = TYPE_STR, UIndexKeyRule* r = NULL ); ~UIndexKey(); bool isEmpty() const; }; // UIndexKey } // U2 #endif // _U2_UINDEX_VIEW_WIDGET_FIELD_KEY_H_ ugene-1.9.8/src/corelibs/U2View/src/util_ov_indexview/UIndexViewerFactory.cpp0000644000175000017500000000717411651544334026007 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include #include #include #include #include #include #include #include #include #include #include "UIndexViewerFactory.h" #include "UIndexViewerTasks.h" namespace U2 { const GObjectViewFactoryId UIndexViewerFactory::ID( "uindex_viewer" ); UIndexViewerFactory::UIndexViewerFactory() : GObjectViewFactory( ID, tr( "Index viewer" ) ) { } bool UIndexViewerFactory::canCreateView(const MultiGSelection& multiSelection) { bool hasUIndexDocs = !SelectionUtils::findDocumentsWithObjects( GObjectTypes::UINDEX, &multiSelection, UOF_LoadedAndUnloaded, true ).isEmpty(); return hasUIndexDocs; } bool UIndexViewerFactory::isStateInSelection(const MultiGSelection& mSelection, const QVariantMap& stData ) { Q_UNUSED(mSelection);Q_UNUSED(stData); return false; } // similar to MSAEditorFactory::createViewTask Task* UIndexViewerFactory::createViewTask(const MultiGSelection& mSel, bool single ) { QList indObjs = SelectionUtils::findObjects( GObjectTypes::UINDEX, &mSel, UOF_LoadedAndUnloaded ); QSet docsWithUInd = SelectionUtils::findDocumentsWithObjects( GObjectTypes::UINDEX, &mSel, UOF_LoadedAndUnloaded, false ); QList< OpenUIndexViewerTask* > resTasks; foreach(Document* doc, docsWithUInd ) { QList docObjs = doc->findGObjectByType( GObjectTypes::UINDEX, UOF_LoadedAndUnloaded ); if ( !docObjs.isEmpty() ) { indObjs += docObjs; } else { resTasks.append( new OpenUIndexViewerTask( doc ) ); } } if( !indObjs.isEmpty() ) { foreach( GObject* o, indObjs ) { if( o->getGObjectType() == GObjectTypes::UNLOADED ){ resTasks.append( new OpenUIndexViewerTask( qobject_cast< UnloadedObject* >( o ) ) ); } else { assert( o->getGObjectType() == GObjectTypes::UINDEX ); resTasks.append( new OpenUIndexViewerTask( qobject_cast< UIndexObject* >( o ) ) ); } } } if (resTasks.isEmpty()) { return NULL; } if( resTasks.size() == 1 || single ) { return resTasks.first(); } Task* result = new Task( tr( "Open multiple views" ), TaskFlag_NoRun ); foreach( Task* t, resTasks ) { result->addSubTask( t ); } return result; } Task* UIndexViewerFactory::createViewTask( const QString& viewName, const QVariantMap& stateData ) { Q_UNUSED(viewName);Q_UNUSED(stateData); return NULL; } bool UIndexViewerFactory::supportsSavedStates() const { return false; } } // U2 ugene-1.9.8/src/corelibs/U2View/src/util_ov_indexview/UIndexViewWidgetKey.cpp0000644000175000017500000001340211651544334025734 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include #include #include "UIndexViewWidgetKey.h" namespace { using namespace U2; bool booleanResStart( UIndexKeyRuleOperation op ) { if( AND == op ) { return true; } else if( OR == op ) { return false; } else { assert( 0 ); } return false; } bool booleanResContinue( bool& oldRes, bool newRes, UIndexKeyRuleOperation op ) { if( AND == op ) { oldRes = oldRes && newRes; if( true == oldRes ) { return true; } return false; } else if( OR == op ) { oldRes = oldRes || newRes; if( false == oldRes ) { return true; } return false; } else { assert( 0 ); } return false; } } // anonymous namespace namespace U2 { UIndexKeyRuleItem::UIndexKeyRuleItem( const UIndexKeySimpleRuleType& t, const QString& d, const UIndexKeyRuleOperation& o ) : type( t ), data( d ), op( o ) { } bool UIndexKeyRuleItem::isOperationItem() const { if( BAD_OP != op ) { assert( BAD_TYPE == type ); return true; } return false; } UIndexKeyRule::UIndexKeyRule( UIndexKeyRuleItem* r ) : root( r ) { } UIndexKeyRule::~UIndexKeyRule() { delItem( root ); } void UIndexKeyRule::delItem( UIndexKeyRuleItem* it ) { if( NULL == it ) { return; } foreach( UIndexKeyRuleItem* chld, it->children ) { delItem( chld ); } delete it; } bool UIndexKeyRule::exec( const QString& val ) { assert( !val.isEmpty() ); assert( NULL != root ); return execItem( root, val ); } bool UIndexKeyRule::execItem( UIndexKeyRuleItem* item, const QString& val ) { assert( NULL != item && !val.isEmpty() ); bool res = true; int chldSz = item->children.size(); if( item->isOperationItem() ) { switch( item->op ) { case AND: case OR: { assert( 0 != chldSz ); res = booleanResStart( item->op ); for( int i = 0; i < chldSz; ++i ) { bool chldRes = execItem( item->children.at( i ), val ); if( booleanResContinue( res, chldRes, item->op ) ) { continue; } break; } } break; case NOT: assert( 1 != chldSz ); res = !execItem( item->children.first(), val ); break; default: assert( 0 ); } } else { // simple items res = execSimpleItem( item, val ); } return res; } bool UIndexKeyRule::execSimpleItem( UIndexKeyRuleItem* item, const QString& val ) { assert( NULL != item && !val.isEmpty() ); UIndexKeySimpleRuleType t = item->type; assert( BAD_TYPE != t ); bool res = false; switch( t ) { case ALL_VALUES: res = true; break; case STARTS_WITH: res = val.startsWith( item->data, Qt::CaseInsensitive ); break; case ENDS_WITH: res = val.endsWith( item->data, Qt::CaseInsensitive ); break; case CONTAINS: res = val.contains( item->data, Qt::CaseInsensitive ); break; case EQUAL: res = val == item->data; break; case NOT_EQUAL: res = val != item->data; break; case MORE_THAN: { bool ok1 = false; bool ok2 = false; int intData = val.toInt( &ok1 ); int intVal = item->data.toInt( &ok2 ); res = ok1 && ok2 && ( intData >= intVal ); } break; case LESS_THAN: { bool ok1 = false; bool ok2 = false; int intData = val.toInt( &ok1 ); int intVal = item->data.toInt( &ok2 ); res = ok1 && ok2 && ( intData <= intVal ); } break; case IN_RANGE: { bool ok1 = false; bool ok2 = false; bool ok3 = false; QStringList numList = item->data.split( " ", QString::SkipEmptyParts ); if( 2 != numList.size() ) { res = false; break; } int intData = val.toInt( &ok1 ); int intValMin = numList.at( 0 ).toInt( &ok2 ); int intValMax = numList.at( 1 ).toInt( &ok3 ); res = ok1 && ok2 && ok3 && ( intValMin <= intData && intData <= intValMax ); } break; default: assert( 0 ); } return res; } UIndexKey::UIndexKey(const QString &name, const UIndexKeyType &t, UIndexKeyRule* r ) : keyName( name ), type( t ), rule( r ) { } UIndexKey::~UIndexKey() { delete rule; } bool UIndexKey::isEmpty() const { return keyName.isEmpty(); } } // U2 ugene-1.9.8/src/corelibs/U2View/src/util_ov_indexview/UIndexViewer.h0000644000175000017500000000354511651544334024122 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_UINDEX_VIEWER_H_ #define _U2_UINDEX_VIEWER_H_ #include #include #include "UIndexViewWidgetImpl.h" namespace U2 { class U2VIEW_EXPORT UIndexViewer : public GObjectView { Q_OBJECT public: UIndexViewer( const QString& viewName, UIndexObject* obj ); virtual void buildStaticToolbar(QToolBar* tb); virtual void buildStaticMenu(QMenu* n); virtual Task* updateViewTask(const QVariantMap& stateData); UIndexObject* getUindexObject() const { return indexObject; } const UIndexViewWidgetImpl* getUI() const { return ui; } protected slots: void sl_onContextMenuRequested( const QPoint& pos ); protected: virtual QWidget* createWidget(); private: static const QString EXPORT_MENU_NAME; void addExportMenu( QMenu* m ); UIndexObject* indexObject; UIndexViewWidgetImpl* ui; private slots: void sl_exportToNewDoc(); }; // UIndexViewer } // U2 #endif // _U2_UINDEX_VIEWER_H_ ugene-1.9.8/src/corelibs/U2View/src/util_ov_indexview/UIndexViewWidgetImpl.h0000644000175000017500000000605411651544334025557 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_UINDEX_VIEW_WIDGET_IMPL_H_ #define _U2_UINDEX_VIEW_WIDGET_IMPL_H_ #include #include "UIndexViewHeaderItemWidgetImpl.h" #include "UIndexViewWidgetKey.h" #include #include namespace U2 { class UIndexViewWidgetImpl : public QWidget, public Ui::UIndexViewWidget { Q_OBJECT public: UIndexViewWidgetImpl( QWidget* p, const UIndex& ind ); ~UIndexViewWidgetImpl(); QList< int > getSelectedDocNums() const; UIndex getIndex() const; private slots: void sl_headerWidgetStateChanged( UIndexKey* newKey ); void sl_horHeaderSectionClicked( int col ); void sl_manageColumnsButtonClicked(); void sl_showHiddenColumn(); void sl_addLastEmptyCol(); private: void initTable(); bool isSignificantKey( const QString& keyName ); void initKeyNamesList(); void sortKeyNamesList(); void insertHeaderItem( UIndexViewHeaderItemWidgetImpl* headerIt ); void setColumnVals( int col ); void addColumn( UIndexViewHeaderItemWidgetImpl* headerIt ); void removeColumn( int col ); void setHorizontalHeaderLabel( int col ); QString getRuleStrRepresent( const UIndexKeyRule* r ) const; void execRules(); bool rulesPassed( int row ); bool execOneRule( int col, const QString& val ); bool isEmptyCol( int col )const; bool hasNotEmptyCol() const; void detectTypes(); private: static const int HEADER_ITEMS_ROW = 0; static const int COL_DOC_FORMAT = 0; static const int COL_URL = 1; static const float SHOW_KEY_PERCENT_BORDER; QString COLUMN_MENU_ACTION_HIDE; QString COLUMN_MENU_ACTION_DELETE; QString NO_HIDDEN_COLUMNS; QString SHOW_HIDDEN_COLS_STR; QString SHOW_HIDDEN_COLS_BEGIN; QString ADD_LAST_EMPTY_COL; QString VALUE_NOT_SELECTED; QString KEY_FORMAT; QString KEY_URL; QString KEY_NONE; UIndex ind; QStringList keyNamesList; QList< UIndexKeyType > keyTypesList; QList< int > hiddenColumns; QList< UIndexViewHeaderItemWidgetImpl* > headerItems; }; // UindexViewWidgetImpl } // U2 #endif // _U2_UINDEX_VIEW_WIDGET_IMPL_H_ ugene-1.9.8/src/corelibs/U2View/src/util_ov_indexview/UIndexExportToNewFileDialogImpl.cpp0000644000175000017500000000372111651544334030210 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include #include #include #include #include "UIndexExportToNewFileDialogImpl.h" namespace U2 { UIndexExportToNewFileDialogImpl::UIndexExportToNewFileDialogImpl() { setupUi( this ); okButton->setDefault( true ); connect( exportFileOpenButton, SIGNAL( clicked() ), SLOT( sl_openExportFile() ) ); } UIndexExportToNewFileDialogModel UIndexExportToNewFileDialogImpl::getModel() const { return model; } void UIndexExportToNewFileDialogImpl::sl_openExportFile() { LastOpenDirHelper h; h.url = QFileDialog::getSaveFileName( this, tr( "Select file to export" ), h.dir ); if (!h.url.isEmpty()) { exportFileEdit->setText(h.url); } } void UIndexExportToNewFileDialogImpl::accept() { model.exportFilename = exportFileEdit->text(); model.gzipExported = ( Qt::Checked == gzipExportedCheck->checkState() ); if (model.exportFilename.isEmpty()) { QMessageBox::critical(this, tr("Error"), tr("Illegal file name")); exportFileEdit->setFocus(); return; } QDialog::accept(); } } // U2 ugene-1.9.8/src/corelibs/U2View/src/util_ov_indexview/UIndexViewerTasks.h0000644000175000017500000000267411651544334025132 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_UINDEX_VIEWER_TASKS_H_ #define _U2_UINDEX_VIEWER_TASKS_H_ #include #include #include namespace U2 { class UIndexViewer; class OpenUIndexViewerTask : public ObjectViewTask { Q_OBJECT public: OpenUIndexViewerTask( UIndexObject* indObj ); OpenUIndexViewerTask( Document* doc ); OpenUIndexViewerTask( UnloadedObject* obj ); virtual void open(); private: QPointer< UIndexObject > uindObj; GObjectReference unloadedReference; }; } // U2 #endif // _U2_UINDEX_VIEWER_TASKS_H_ ugene-1.9.8/src/corelibs/U2View/src/util_ov_annotated_dna/0000755000175000017500000000000011651544334022161 5ustar ilyailyaugene-1.9.8/src/corelibs/U2View/src/util_ov_annotated_dna/ADVSplitWidget.cpp0000644000175000017500000000000011651544334025445 0ustar ilyailyaugene-1.9.8/src/corelibs/U2View/src/util_ov_annotated_dna/PanViewRows.h0000644000175000017500000000374511651544334024567 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_PAN_VIEW_ROWS_H_ #define _U2_PAN_VIEW_ROWS_H_ #include #include #include #include namespace U2 { class Annotation; class PVRowData { public: PVRowData(const QString& _key) : key(_key){} bool fitToRow(const QVector& locations); QString key; //invariant: keep the ranges in ascending order QVector ranges; QList annotations; }; class PVRowsManager { public: PVRowsManager() {} ~PVRowsManager(); void clear(); void addAnnotation(Annotation* f, const QString& key); void removeAnnotation(Annotation* f); bool contains(const QString& key) const; int getNumRows() const {return rows.size();} PVRowData* getRow(int row) const; int getAnnotationRowIdx(Annotation* a) const; PVRowData* getAnnotationRow(Annotation* a) const {return rowByAnnotation.value(a, NULL);} const QString& getRowKey(int rowNum) const; int getNumAnnotationsInRow(int rowNum) const; private: QList rows; QMap rowByAnnotation; }; } // namespace #endif ugene-1.9.8/src/corelibs/U2View/src/util_ov_annotated_dna/WindowStepSelectorWidget.h0000644000175000017500000000442311651544334027305 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_WINDOW_STEP_SELECTOR_WIDGET_ #define _U2_WINDOW_STEP_SELECTOR_WIDGET_ #include #include #include #include #include namespace U2 { class U2VIEW_EXPORT WindowStepSelectorWidget : public QWidget { Q_OBJECT public: WindowStepSelectorWidget(QWidget* p, const U2Region& winRange, int win, int step); QString validate() const; int getWindow() const; int getStep() const; private: QSpinBox* windowEdit; QSpinBox* stepsPerWindowEdit; }; class U2VIEW_EXPORT MinMaxSelectorWidget : public QWidget { Q_OBJECT public: MinMaxSelectorWidget(QWidget* p, double min, double max, bool enabled); QString validate() const; double getMin() const; double getMax() const; bool getState() const; private: QGroupBox* minmaxGroup; QDoubleSpinBox* minBox; QDoubleSpinBox* maxBox; }; class U2VIEW_EXPORT WindowStepSelectorDialog : public QDialog { Q_OBJECT public: WindowStepSelectorDialog(QWidget* p, const U2Region& winRange, int win, int step, double min, double max, bool e); WindowStepSelectorWidget* getWindowStepSelector() const {return wss;} MinMaxSelectorWidget* getMinMaxSelector() const {return mms;} private slots: void sl_onCancelClicked(bool); void sl_onOkClicked(bool); private: WindowStepSelectorWidget* wss; MinMaxSelectorWidget* mms; }; } // namespace #endif ugene-1.9.8/src/corelibs/U2View/src/util_ov_annotated_dna/AnnotationsTreeViewL.h0000644000175000017500000002555611651544334026433 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_ANNOTATIONS_TREE_VIEW_ #define _U2_ANNOTATIONS_TREE_VIEW_ #include #include #include #include #include #include #include #include #include #include #include #include "AnnotationsTreeModel.h" namespace U2 { class Annotation; class AnnotationGroup; class U2Qualifier; class AnnotationTableObject; class AVItemL; class AVGroupItemL; class AVAnnotationItemL; class AVQualifierItemL; class AnnotatedDNAView; class AnnotationSelection; class AnnotationGroupSelection; class AnnotationModification; class GObjectView; class LazyTreeView; class AnnotationsTreeViewL; class CustomSlider: public QScrollBar { public: CustomSlider(QWidget *parent = NULL); void setMaxVal(int _maxVal); int getMaxVal() const; void setPosition(int pos); void setCustomPageStep(int ps); int sliderCustomPosition() const; void setRowHeight(int height); int numToScroll() const; void resetNumToScroll(); protected: virtual void sliderChange(SliderChange sc); void paintEvent(QPaintEvent *); void mouseMoveEvent(QMouseEvent *me); void mousePressEvent(QMouseEvent *me); void mouseReleaseEvent(QMouseEvent *me); private: int minVal; int maxVal; int sliderPos; //int pageStep; int rowHeight; QStyleOptionSlider options; int dif; bool sliderPressed; }; class U2VIEW_EXPORT LazyTreeView: public QTreeView { Q_OBJECT public: LazyTreeView(QWidget * parent = 0 ); QList selectedItems() ; QTreeWidgetItem* currentItem() ; void scrollToItem(QTreeWidgetItem *item, ScrollHint hint = EnsureVisible) ; void setCurrentItem(QTreeWidgetItem *item) ; int topLevelItemCount() const ; QTreeWidgetItem * topLevelItem(int i) ; void setColumnCount(int nCol); void setHeaderLabels(QStringList headers); QTreeWidgetItem *itemAt(const QPoint pos); int getMaxItem() const {return numOnScreen;} int getPositionInTree(QTreeWidgetItem *item); AVItemL *getNextItemDown(AVItemL * bottom); AVItemL *getNextItemUp(); AVItemL *getLastItemInSubtree(AnnotationGroup *gr, AnnotationsTreeViewL *view); int getExpandedNumber(AVItemL *item); int getExpandedNumber(AnnotationGroup *gr); void updateItem(QTreeWidgetItem *item); void setLineHeight(int height); QModelIndex guessIndex(QTreeWidgetItem *item); protected: virtual void selectionChanged ( const QItemSelection & selected, const QItemSelection & deselected ); virtual void mouseDoubleClickEvent ( QMouseEvent * event ); virtual void mousePressEvent(QMouseEvent *event); virtual void resizeEvent(QResizeEvent *event); virtual void scrollContentsBy ( int dx, int dy ); int scrollOneItemDown(); int scrollOneItemUp(); private: void resizeModel(); void insertItem(int row, QTreeWidgetItem *item, bool removeLast = true); void insertItemBehindView(int row, QTreeWidgetItem *item); void removeItem(QTreeWidgetItem *item, bool removeAll = false); void calculateIndex(AnnotationTableObject *obj); void updateSlider(); private slots: void sl_expanded(const QModelIndex &index) ; void sl_collapsed(const QModelIndex &index); void sl_entered(const QModelIndex &index); signals: void itemSelectionChanged(); void itemDoubleClicked(QTreeWidgetItem*, int); void itemClicked(QTreeWidgetItem*, int); void itemExpanded(QTreeWidgetItem*); void itemCollapsed(QTreeWidgetItem*); void itemEntered(QTreeWidgetItem*, int); private: QList onScreen; int numOnScreen; int realNumberOfItems; bool flag; bool emptyExpand; int lineHeight; TreeIndex *treeWalker; friend class AnnotationsTreeViewL; }; class U2VIEW_EXPORT AnnotationsTreeViewL : public QWidget { Q_OBJECT public: AnnotationsTreeViewL(AnnotatedDNAView* ctx); void saveWidgetState(); void restoreWidgetState(); void adjustStaticMenu(QMenu *m) const {adjustMenu(m);} QTreeView* getTreeWidget() const {return tree;} QStringList getQualifierColumnNames() const {return qColumns;} void addQualifierColumn(const QString& q); void removeQualifierColumn(const QString& q); void saveState(QVariantMap& map) const; void updateState(const QVariantMap& map); void setSortingEnabled(bool v); AVItemL* currentItem(); private slots: void sl_onAnnotationObjectAdded(AnnotationTableObject* obj); void sl_onAnnotationObjectRemoved(AnnotationTableObject* obj); void sl_onAnnotationsAdded(const QList&); void sl_onAnnotationsRemoved(const QList&); void sl_onAnnotationsInGroupRemoved(const QList& as, AnnotationGroup* group); void sl_onAnnotationModified(const AnnotationModification& md); void sl_onAnnotationObjectModifiedStateChanged(); void sl_onAnnotationObjectRenamed(const QString& oldName); void sl_onGroupCreated(AnnotationGroup*); void sl_onGroupRemoved(AnnotationGroup* parent, AnnotationGroup* removed); void sl_onGroupRenamed(AnnotationGroup*, const QString& oldName); /* void sl_onAnnotationSettingsChanged(const QStringList& changedSettings);*/ void sl_onAnnotationSelectionChanged(AnnotationSelection*, const QList&, const QList&); void sl_onAnnotationGroupSelectionChanged(AnnotationGroupSelection*, const QList&, const QList&); void sl_onItemSelectionChanged(); void sl_onAddAnnotationObjectToView(); void sl_removeObjectFromView(); void sl_removeAnnsAndQs(); void sl_onBuildPopupMenu(GObjectView* thiz, QMenu* menu); void sl_onCopyQualifierValue(); void sl_onCopyQualifierURL(); void sl_onToggleQualifierColumn(); void sl_onRemoveColumnByHeaderClick(); void sl_onCopyColumnText(); void sl_onCopyColumnURL(); void sl_rename(); void sl_edit(); void sl_addQualifier(); // void sl_cutAnnotations(); // void sl_copyAnnotations(); // void sl_pasteAnnotations(); void sl_itemEntered(QTreeWidgetItem * i, int column); void sl_itemClicked( QTreeWidgetItem * item, int column); void sl_itemDoubleClicked (QTreeWidgetItem * item, int column); void sl_itemExpanded(QTreeWidgetItem*); void sl_itemCollapsed(QTreeWidgetItem*); //TODO: deal with style()->styleHint(QStyle::SH_ItemView_ActivateItemOnSingleClick) correctly // void sl_itemActivated(QTreeWidgetItem*, int) {sl_edit();} //void sl_sortTree(); protected: bool eventFilter(QObject* o, QEvent* e); private: void renameItem(AVItemL* i); void editItem(AVItemL* i); QString renameDialogHelper(AVItemL* i, const QString& defText, const QString& title); bool editQualifierDialogHelper(AVQualifierItemL* i, bool ro, U2Qualifier& res); void moveDialogToItem(QTreeWidgetItem* item, QDialog& d); void adjustMenu(QMenu* m_) const; AVGroupItemL* createGroupItem(AVGroupItemL* parentGroup, AnnotationGroup* g); AVAnnotationItemL* createAnnotationItem(AVGroupItemL* parentGroup, Annotation* a, bool removeLast = true); void updateAllAnnotations(ATVAnnUpdateFlags flags); void destroyTree(QTreeWidgetItem* qi); void focusOnItem(Annotation* a); AVGroupItemL* findGroupItem(const AnnotationGroup* g) const; AVAnnotationItemL* findAnnotationItem(const AnnotationGroup* g, const Annotation* a) const; AVAnnotationItemL* findAnnotationItem(const AVGroupItemL* gi, const Annotation* a) const; // searches for annotation items that has not-null document added to the view QList findAnnotationItems(const Annotation* a) const; void connectAnnotationSelection(); void connectAnnotationGroupSelection(); void updateState(); void updateColumnContextActions(AVItemL* item, int col); void resetDragAndDropData(); bool initiateDragAndDrop(QMouseEvent* me); void finishDragAndDrop(Qt::DropAction dndAction); LazyTreeView* tree; AnnotatedDNAView* ctx; QAction* addAnnotationObjectAction; QAction* removeObjectsFromViewAction; QAction* removeAnnsAndQsAction; QAction* copyQualifierAction; QAction* copyQualifierURLAction; QAction* toggleQualifierColumnAction; QAction* removeColumnByHeaderClickAction; QAction* copyColumnTextAction; QAction* copyColumnURLAction; // QAction* cutAnnotationsAction; // QAction* copyAnnotationsAction; // QAction* pasteAnnotationsAction; QAction* renameAction; // action to rename active group/qualifier/annotation only QAction* editAction; // action to edit active item -> only for non-readonly QAction* viewAction; // action to view active item -> could be used both for readonly and not readonly QAction* addQualifierAction; // action to create qualifier. Editable annotation or editable qualifier must be selected Qt::MouseButton lastMB; QStringList headerLabels; QStringList qColumns; int lastClickedColumn; QIcon addColumnIcon; QIcon removeColumnIcon; QTimer sortTimer; QPoint dragStartPos; // drag&drop related data bool isDragging; bool dndCopyOnly; bool renameFlag; QList dndSelItems; AVGroupItemL* dropDestination; static const QString annotationMimeType; friend class LazyTreeView; }; }//namespace #endif ugene-1.9.8/src/corelibs/U2View/src/util_ov_annotated_dna/ADVConstants.h0000644000175000017500000000152211651544334024641 0ustar ilyailya#ifndef _U2_ADV_CONSTANTS_H_ #define _U2_ADV_CONSTANTS_H_ namespace U2 { #define ADV_MENU_ANALYSE "ADV_MENU_ANALYSE" #define ADV_MENU_COPY "ADV_MENU_COPY" #define ADV_MENU_SELECT "ADV_MENU_SELECT" #define ADV_MENU_ADD "ADV_MENU_ADD" #define ADV_MENU_REMOVE "ADV_MENU_REMOVE" #define ADV_MENU_ZOOM "ADV_MENU_ZOOM" #define ADV_MENU_ALIGN "ADV_MENU_ALIGN" #define ADV_MENU_EXPORT "ADV_MENU_EXPORT" #define ADV_GOTO_ACTION "ADV_GOTO_ACTION" #define ADV_MENU_SECTION1_SEP "ADV_MENU_SEC1_SEP" #define ADV_MENU_SECTION2_SEP "ADV_MENU_SEC2_SEP" #define ADV_MENU_EDIT "ADV_MENU_EDIT" #define ANNOTATED_DNA_VIEW_FACTORY_ID "AnnotatedDNAView" } //namespace #endif ugene-1.9.8/src/corelibs/U2View/src/util_ov_annotated_dna/ADVSequenceObjectContext.h0000644000175000017500000000760511651544334027141 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_ADV_SEQUENCE_OBJECT_CONTEXT_H_ #define _U2_ADV_SEQUENCE_OBJECT_CONTEXT_H_ #include #include #include #include namespace U2 { class AnnotatedDNAView; class DNASequenceObject; class DNAAlphabet; class DNATranslation; class DNASequenceSelection; class ADVSequenceWidget; class AnnotationTableObject; class AnnotationSelection; class GObject; class Annotation; class U2VIEW_EXPORT ADVSequenceObjectContext : public QObject { Q_OBJECT public: ADVSequenceObjectContext(AnnotatedDNAView* v, DNASequenceObject* obj); AnnotatedDNAView* getAnnotatedDNAView() const {return view;} DNATranslation* getComplementTT() const {return complTT;} DNATranslation* getAminoTT() const {return aminoTT;} DNASequenceObject* getSequenceObject() const {return seqObj;} GObject* getSequenceGObject() const; const QByteArray& getSequenceData() const; int getSequenceLen() const; DNAAlphabet* getAlphabet() const; DNASequenceSelection* getSequenceSelection() const {return selection;} QSet getAnnotationObjects(bool includeAutoAnnotations = false) const; QSet getAutoAnnotationObjects() const { return autoAnnotations; } QList getAnnotationGObjects() const; QMenu* createTranslationsMenu(); void setAminoTranslation(const QString& tid); void addAnnotationObject(AnnotationTableObject* obj); void addAutoAnnotationObject(AnnotationTableObject* obj); void removeAnnotationObject(AnnotationTableObject* obj); AnnotationSelection* getAnnotationsSelection() const; const QList& getSequenceWidgets() const {return seqWidgets;} void addSequenceWidget(ADVSequenceWidget* w); void removeSequenceWidget(ADVSequenceWidget* w); QList selectRelatedAnnotations(const QList& alist) const; QVector getTranslationRowsVisibleStatus(); void setTranslationsVisible(bool enable); private slots: void sl_setAminoTranslation(); void sl_toggleTranslations(); void sl_showDirectOnly(); void sl_showComplOnly(); void sl_showShowAll(); signals: void si_aminoTranslationChanged(); void si_annotationObjectAdded(AnnotationTableObject* obj); void si_annotationObjectRemoved(AnnotationTableObject* obj); void si_translationRowsChanged(); private: void guessAminoTT(AnnotationTableObject* ao); AnnotatedDNAView* view; DNASequenceObject* seqObj; DNATranslation* aminoTT; DNATranslation* complTT; DNASequenceSelection* selection; QActionGroup* translations; QActionGroup* visibleFrames; QVector translationRowsStatus; QList seqWidgets; QSet annotations; QSet autoAnnotations; bool clarifyAminoTT; }; } //namespace #endif ugene-1.9.8/src/corelibs/U2View/src/util_ov_annotated_dna/DetView.h0000644000175000017500000000717511651544334023713 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_DET_VIEW_H_ #define _U2_DET_VIEW_H_ #include "GSequenceLineViewAnnotated.h" #include #include #include class QActionGroup; namespace U2 { class DNATranslation; class U2VIEW_EXPORT DetView : public GSequenceLineViewAnnotated { Q_OBJECT public: DetView(QWidget* p, ADVSequenceObjectContext* ctx); bool isOneLineMode() {return getComplementTT() == NULL && getAminoTT() == NULL;} bool hasTranslations() {return getAminoTT() != NULL;} bool hasComplementaryStrand() {return getComplementTT() != NULL;} DNATranslation* getComplementTT() const; DNATranslation* getAminoTT() const; void setShowComplement(bool t); void setShowTranslation(bool t); QAction* getShowComplementAction() const {return showComplementAction;} QAction* getShowTranslationAction() const {return showTranslationAction;} protected slots: virtual void sl_sequenceChanged(); void sl_onAminoTTChanged(); void sl_showComplementToggle(bool v) {setShowComplement(v);} void sl_showTranslationToggle(bool v); void sl_translationRowsChanged(); protected: void showEvent(QShowEvent * e); void hideEvent(QHideEvent * e); void mouseReleaseEvent(QMouseEvent* me); void updateActions(); void resizeEvent(QResizeEvent *e); void updateSize(); QAction* showComplementAction; QAction* showTranslationAction; }; class DetViewRenderArea : public GSequenceLineViewAnnotatedRenderArea { public: DetViewRenderArea(DetView* d); virtual int coordToPos(int x) const; virtual float posToCoordF(int x, bool useVirtualSpace = false) const; virtual float getCurrentScale() const; DetView* getDetView() const {return static_cast(view);} virtual U2Region getAnnotationYRange(Annotation* a, int region, const AnnotationSettings* as) const; void updateSize(); bool isOnTranslationsLine(int y) const; protected: virtual void drawAll(QPaintDevice* pd); private: int getLineY(int line) const {return 2 + line * lineHeight;} int getTextY(int line) const {return getLineY(line) + lineHeight - yCharOffset;} void updateLines(); void drawDirect(QPainter& p); void drawComplement(QPainter& p); void drawTranslations(QPainter& p); void drawSequenceSelection(QPainter& p); void drawRuler(QPainter& p); void highlight(QPainter& p, const U2Region& r, int line); int posToComplTransLine(int p) const; int posToDirectTransLine(int p) const; bool deriveTranslationCharColor(int pos, U2Strand strand, QList annotationsInRange, QColor& result); int numLines; int rulerLine; int baseLine; int complementLine; int firstDirectTransLine; int firstComplTransLine; }; }//namespace; #endif ugene-1.9.8/src/corelibs/U2View/src/util_ov_annotated_dna/AnnotatedDNAViewTasks.h0000644000175000017500000000356211651544334026441 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_ANNOTATED_DNA_VIEW_TASKS_H_ #define _U2_ANNOTATED_DNA_VIEW_TASKS_H_ #include #include namespace U2 { class DNASequenceObject; class AnnotatedDNAView; class OpenAnnotatedDNAViewTask : public ObjectViewTask { Q_OBJECT public: //opens a single view for all sequence object in the list of sequence objects related to the objects in the list OpenAnnotatedDNAViewTask(const QList& objects); virtual void open(); static void updateTitle(AnnotatedDNAView* v); private: QList sequenceObjectRefs; }; class OpenSavedAnnotatedDNAViewTask : public ObjectViewTask { Q_OBJECT public: OpenSavedAnnotatedDNAViewTask(const QString& viewName, const QVariantMap& stateData); virtual void open(); }; class UpdateAnnotatedDNAViewTask : public ObjectViewTask { public: UpdateAnnotatedDNAViewTask(AnnotatedDNAView* v, const QString& stateName, const QVariantMap& stateData); virtual void update(); }; } // namespace #endif ugene-1.9.8/src/corelibs/U2View/src/util_ov_annotated_dna/ADVSingleSequenceWidget.h0000644000175000017500000001557211651544334026755 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_ADV_SINGLE_SEQ_WIDGET_H_ #define _U2_ADV_SINGLE_SEQ_WIDGET_H_ #include "ADVSequenceWidget.h" #include #include #include "PanView.h" #include #include #include #include #include #include #ifdef Q_OS_LINUX #include #endif // Q_OS_LINUX namespace U2 { class AnnotatedDNAView; class DNASequenceObject; class GSequenceLineView; class DetView; class PanView; class Overview; class GSingleSeqBlockState; class DNATranslation; class ADVSequenceObjectContext; class ADVSingleSequenceHeaderWidget; class Annotation; class AnnotationSelection; class DNAAlphabet; class U2VIEW_EXPORT ADVSingleSequenceWidget : public ADVSequenceWidget { Q_OBJECT public: ADVSingleSequenceWidget(ADVSequenceObjectContext* seqCtx, AnnotatedDNAView* ctx); ~ADVSingleSequenceWidget(); const QList& getLineViews() const {return lineViews;} GSequenceLineView* getPanGSLView() const; GSequenceLineView* getDetGSLView() const; PanView* getPanView() const {return panView;} DetView* getDetView() const {return detView;} virtual void centerPosition(int pos, QWidget* skipView = NULL); ADVSequenceObjectContext* getActiveSequenceContext() const {return (seqContexts.isEmpty()) ? NULL : seqContexts.first();} ADVSequenceObjectContext* getSequenceContext() const {return getActiveSequenceContext();} DNATranslation* getComplementTT() const; DNATranslation* getAminoTT() const; DNASequenceSelection* getSequenceSelection() const; int getSequenceLen() const; virtual void addSequenceView(GSequenceLineView* v, QWidget* after = NULL); virtual void removeSequenceView(GSequenceLineView* v, bool deleteView = true); DNASequenceObject* getSequenceObject() const; virtual void buildPopupMenu(QMenu& m); virtual bool isWidgetOnlyObject(GObject* o) const; virtual void addADVSequenceWidgetAction(ADVSequenceWidgetAction* action); void setViewCollapsed(bool v); bool isViewCollapsed() const; void setPanViewCollapsed(bool v); bool isPanViewCollapsed() const; void setDetViewCollapsed(bool v); bool isDetViewCollapsed() const; void setOverviewCollapsed(bool v); bool isOverviewCollapsed() const; virtual void updateState(const QVariantMap& m); virtual void updateSelectionActions(); QVector getSelectedAnnotationRegions(int max); virtual void saveState(QVariantMap& m); void closeView(); virtual U2Region getVisibleRange() const; virtual void setVisibleRange(const U2Region& r); virtual int getNumBasesVisible() const; virtual void setNumBasesVisible(int n); QAction* getSelectRangeAction() const {return selectRangeAction1;} virtual void onSequenceObjectRenamed(const QString& oldName); protected slots: void sl_onViewDestroyed(QObject*); void sl_toggleView(); void sl_togglePanView(); void sl_toggleDetView() {setDetViewCollapsed(!isDetViewCollapsed());} void sl_toggleOverview() {setOverviewCollapsed(!isOverviewCollapsed());} void sl_onSelectRange(); void sl_onSelectInRange(); void sl_onSelectOutRange(); void sl_zoomToRange(); void sl_onLocalCenteringRequest(int pos); void sl_createCustomRuler(); void sl_removeCustomRuler(); void sl_onAnnotationSelectionChanged(AnnotationSelection* thiz, const QList& added, const QList& removed); // QT 4.5.0 bug workaround public slots: void sl_closeView(); private slots: void sl_saveScreenshot(); protected: void init(); bool eventFilter(QObject* o, QEvent* e); private: virtual void updateMinMaxHeight(); void addStateActions(QMenu& m); void addRulersMenu(QMenu& m); void addSelectMenu(QMenu& m); virtual GSequenceLineView* findSequenceViewByPos(const QPoint& globalPos) const; virtual void addZoomMenu(const QPoint& globalPos, QMenu* m); DetView* detView; PanView* panView; Overview* overview; QList lineViews; QVBoxLayout* linesLayout; ADVSingleSequenceHeaderWidget *headerWidget; QAction* toggleViewAction; QAction* togglePanViewAction; QAction* toggleDetViewAction; QAction* toggleOverviewAction; QAction* selectRangeAction1; QAction* selectRangeAction2; QAction* selectInAnnotationRangeAction; QAction* selectOutAnnotationRangeAction; QAction* zoomToRangeAction; QAction* createNewRulerAction; QAction* shotScreenAction; QList tbMenues; QToolButton* ttButton; GAutoDeleteList rulerActions; PanView::ZoomUseObject zoomUseObject; friend class ADVSingleSequenceHeaderWidget; }; class U2VIEW_EXPORT ADVSingleSequenceHeaderWidget : public QWidget { Q_OBJECT public: ADVSingleSequenceHeaderWidget(ADVSingleSequenceWidget* p); QToolBar* getToolBar() const { return toolBar;} void setTitle(const QString & title) {nameLabel->setText(title);} void updateTitle(); protected: virtual void mouseDoubleClickEvent(QMouseEvent *e); virtual void paintEvent(QPaintEvent *e); virtual bool eventFilter (QObject *o, QEvent *e); protected slots: void sl_advFocusChanged(ADVSequenceWidget* prevFocus, ADVSequenceWidget* newFocus); void sl_actionTriggered(QAction* a); void sl_showStateMenu(); void sl_closeView(); private: void populateToolBars(); void updateActiveState(); QString getShortAlphabetName(DNAAlphabet* al); ADVSingleSequenceWidget* ctx; QToolBar* toolBar; QToolBar* closeBar; QLabel* pixLabel; QLabel* nameLabel; QAction* closeViewAction; QToolButton* widgetStateMenuButton; }; }//namespace #endif ugene-1.9.8/src/corelibs/U2View/src/util_ov_annotated_dna/ADVSyncViewManager.h0000644000175000017500000001032211651544334025725 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_ADV_SYNC_VIEW_MANAGER_H_ #define _U2_ADV_SYNC_VIEW_MANAGER_H_ #include #include #include #include #include #include namespace U2 { class AnnotatedDNAView; class ADVSequenceWidget; class ADVSingleSequenceWidget; class LRegionsSelection; //Support for synchronous operation for ADVSingleSequenceViews: sync& lock scale, toggle visibility class ADVSyncViewManager : public QObject { Q_OBJECT public: ADVSyncViewManager(AnnotatedDNAView* v); ~ADVSyncViewManager(); void updateAutoAnnotationActions(); void updateToolbar1(QToolBar* tb); void updateToolbar2(QToolBar* tb); private slots: void sl_rangeChanged(); void sl_onSelectionChanged(LRegionsSelection* thiz, const QVector& added, const QVector& removed); void sl_sequenceWidgetAdded(ADVSequenceWidget* w); void sl_sequenceWidgetRemoved(ADVSequenceWidget* w); void sl_lock(); void sl_sync(); void sl_toggleVisualMode(); void sl_toggleAutoAnnotaionsHighlighting(); void sl_updateAutoAnnotationsMenu(); void sl_updateVisualMode(); private: enum SyncMode { SyncMode_Start, SyncMode_SeqSel, SyncMode_AnnSel }; void sync(bool lock, SyncMode mode); int offsetBySeqSel(ADVSingleSequenceWidget* w) const; int offsetByAnnSel(ADVSingleSequenceWidget* w) const; SyncMode detectSyncMode() const; int findSelectedAnnotationPos(ADVSingleSequenceWidget* w) const; void unlock(); void updateEnabledState(); void toggleCheckedAction(SyncMode mode); QList getViewsFromADV() const; AnnotatedDNAView* adv; QAction* lockByStartPosAction; QAction* lockBySeqSelAction; QAction* lockByAnnSelAction; QAction* syncByStartPosAction; QAction* syncBySeqSelAction; QAction* syncByAnnSelAction; QActionGroup* lockActionGroup; QToolButton* syncButton; QToolButton* lockButton; QMenu* syncMenu; QMenu* lockMenu; QAction* syncButtonTBAction; QAction* lockButtonTBAction; bool selectionRecursion; bool recursion; QList views; // auto annotation highlighting QMap aaActionMap; QAction* toggleAutoAnnotationsAction; QMenu* toggleAutoAnnotationsMenu; QToolButton* toggleAutoAnnotationsButton; // visual mode vars QAction* toggleViewButtonAction; QToolButton* toggleViewButton; QMenu* toggleViewButtonMenu; QAction* toggleAllAction; QAction* toggleOveAction; QAction* togglePanAction; QAction* toggleDetAction; }; } //namespace #endif ugene-1.9.8/src/corelibs/U2View/src/util_ov_annotated_dna/ADVClipboard.h0000644000175000017500000000565211651544334024574 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_ANNOTATED_DNA_VIEW_CLIPBOARD_H_ #define _U2_ANNOTATED_DNA_VIEW_CLIPBOARD_H_ #include #include #include namespace U2 { class AnnotatedDNAView; class LRegionsSelection; class Annotation; class AnnotationSelection; class ADVSequenceObjectContext; class ADVSequenceWidget; class U2VIEW_EXPORT ADVClipboard: public QObject { Q_OBJECT public: ADVClipboard(AnnotatedDNAView* ctx); QAction* getCopySequenceAction() const {return copySequenceAction;} QAction* getCopyTranslationAction() const {return copyTranslationAction;} QAction* getCopyComplementAction() const {return copyComplementSequenceAction;} QAction* getCopyComplementTranslationAction() const {return copyComplementTranslationAction;} QAction* getCopyAnnotationSequenceAction() const {return copyAnnotationSequenceAction;} QAction* getCopyAnnotationSequenceTranslationAction() const {return copyAnnotationSequenceTranslationAction;} void addCopyMenu(QMenu* m); public slots: void sl_onDNASelectionChanged(LRegionsSelection* s, const QVector& added, const QVector& removed); void sl_onAnnotationSelectionChanged(AnnotationSelection* s, const QList& added, const QList& removed); void sl_onFocusedSequenceWidgetChanged(ADVSequenceWidget*, ADVSequenceWidget*); void sl_copySequence(); void sl_copyTranslation(); void sl_copyComplementSequence(); void sl_copyComplementTranslation(); void sl_copyAnnotationSequence(); void sl_copyAnnotationSequenceTranslation(); ADVSequenceObjectContext* getSequenceContext() const; private: void connectSequence(ADVSequenceObjectContext* s); void updateActions(); void copySequenceSelection(bool complement, bool amino); AnnotatedDNAView* ctx; QAction* copySequenceAction; QAction* copyTranslationAction; QAction* copyComplementSequenceAction; QAction* copyComplementTranslationAction; QAction* copyAnnotationSequenceAction; QAction* copyAnnotationSequenceTranslationAction; }; }//namespace #endif ugene-1.9.8/src/corelibs/U2View/src/util_ov_annotated_dna/CreateRulerDialogController.cpp0000644000175000017500000000543011651544334030270 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "CreateRulerDialogController.h" #include #include #include #include #include #include #include namespace U2 { CreateRulerDialogController::CreateRulerDialogController(const QSet& namesToFilter, const U2Region& seqRange, int defaultOffset, QWidget* p) : QDialog(p) { setupUi(this); setMaximumHeight(layout()->minimumSize().height()); filter = namesToFilter; sampleLabel->setAutoFillBackground(true); nameEdit->setText(TextUtils::variate(tr("New ruler"), "_", filter)); spinBox->setMinimum(INT_MIN); spinBox->setMaximum(INT_MAX); spinBox->setValue(seqRange.contains(defaultOffset+1) ? defaultOffset + 1 : spinBox->minimum()); color = Qt::darkBlue; updateColorSample(); connect(colorButton, SIGNAL(clicked()), SLOT(sl_colorButtonClicked())); setWindowIcon(QIcon(":/ugene/images/ugene_16.png")); } void CreateRulerDialogController::updateColorSample() { QPalette lPal; lPal.setColor(QPalette::Window, Qt::white); lPal.setColor(QPalette::WindowText, color); sampleLabel->setPalette(lPal); } void CreateRulerDialogController::sl_colorButtonClicked() { QColor c = QColorDialog::getColor(color, this); if (!c.isValid()) { return; } color = c; updateColorSample(); } void CreateRulerDialogController::accept() { QString n = nameEdit->text(); if (n.isEmpty()) { QMessageBox::critical(NULL, tr("Error"), tr("Ruler name is empty!")); nameEdit->setFocus(); return; } if (filter.contains(n)) { QMessageBox::critical(NULL, tr("Error"), tr("Ruler with the same name is already exists!")); nameEdit->setFocus(); return; } name = n; offset = spinBox->value() - 1; QDialog::accept(); } }//namespace ugene-1.9.8/src/corelibs/U2View/src/util_ov_annotated_dna/AnnotationsTreeModel.cpp0000644000175000017500000006222111651544334026766 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "AnnotationsTreeModel.h" #include "AnnotationsTreeViewL.h" #include #include #include namespace U2 { LazyAnnotationTreeViewModel::LazyAnnotationTreeViewModel(QObject * parent): QAbstractItemModel(parent) { rootItem = new AVItemL(NULL, AVItemType_Group); nCol = 1; headers = QStringList() << "Name" << "Value"; currentInModel = 0; debugFlag = false; } AVItemL * LazyAnnotationTreeViewModel::getItem(const QModelIndex &index) const { AVItemL *item = rootItem; if (index.isValid()) { item = static_cast(index.internalPointer()); assert(item); } return item; } QVariant LazyAnnotationTreeViewModel::data ( const QModelIndex & index, int role) const { AVItemL *item = getItem(index); return item->data(index.column(), role); } int LazyAnnotationTreeViewModel::columnCount ( const QModelIndex &) const { return nCol; } int LazyAnnotationTreeViewModel::rowCount ( const QModelIndex & parent) const { AVItemL *parentItem = getItem(parent); return parentItem->childCount(); } QModelIndex LazyAnnotationTreeViewModel::parent ( const QModelIndex & index ) const { if (!index.isValid()) return QModelIndex(); AVItemL *childItem = getItem(index); AVItemL *parentItem = static_cast(childItem->parent()); if (parentItem == rootItem) return QModelIndex(); return createIndex(parentItem->childNumber(), 0, parentItem); } Qt::ItemFlags LazyAnnotationTreeViewModel::flags ( const QModelIndex &) const { return Qt::ItemIsSelectable | Qt::ItemIsEnabled; } QModelIndex LazyAnnotationTreeViewModel::index ( int row, int column, const QModelIndex & parent) const { if (parent.isValid() && parent.column() != 0) return QModelIndex(); AVItemL *parentItem = getItem(parent); AVItemL *childItem = static_cast(parentItem->child(row)); if (childItem) { return createIndex(row, column, childItem); } else { return QModelIndex(); } } QVariant LazyAnnotationTreeViewModel::headerData ( int section, Qt::Orientation orientation, int role) const { if(orientation == Qt::Horizontal && role == Qt::DisplayRole) { return headers[section]; } else { return QVariant(); } } bool LazyAnnotationTreeViewModel::removeRows(int position, int rows, const QModelIndex &parent){ assert(debugFlag); debugFlag = false; AVItemL *parentItem = getItem(parent); bool success = true; beginRemoveRows(parent, position, position + rows - 1); success = parentItem->removeChildren(position, rows); endRemoveRows(); currentInModel -= rows; return success; } bool LazyAnnotationTreeViewModel::insertRows(int position, int rows, const QModelIndex &parent){ assert(debugFlag); debugFlag = false; assert(nextToAdd); AVItemL *parentItem = getItem(parent); bool success = true; beginInsertRows(parent, position, position + rows - 1); success = parentItem->addChildren(position, rows, nextToAdd); endInsertRows(); nextToAdd = NULL; currentInModel += rows; return success; } QModelIndex LazyAnnotationTreeViewModel::guessIndex(QTreeWidgetItem* item) { AVItemL * av = static_cast(item); if(av->parent()) { int row = av->parent()->indexOfChild(av); int column = 0; QModelIndex index = createIndex(row, column, item); return index; } else { return QModelIndex(); } } void LazyAnnotationTreeViewModel::setColumnCount(int _nCol) { nCol = _nCol; } void LazyAnnotationTreeViewModel::setHeaderLabels(QStringList _headers) { headers = _headers; } bool LazyAnnotationTreeViewModel::hasChildren ( const QModelIndex & parent) const { AVItemL *item = getItem(parent); if(item->type == AVItemType_Group && item->parent()) { AVGroupItemL *ann = static_cast(item); return (!ann->getAnnotationGroup()->getSubgroups().isEmpty() || !ann->getAnnotationGroup()->getAnnotations().isEmpty()); } if(item->type == AVItemType_Annotation) { AVAnnotationItemL *ann = static_cast(item); return (!ann->annotation->getQualifiers().isEmpty()); } else { return (item->childCount() > 0); } } bool LazyAnnotationTreeViewModel::insertColumns( int position, int columns, const QModelIndex &parent /*= QModelIndex()*/ ) { beginInsertColumns(parent, position, position + columns - 1); //success = rootItem->insertColumns(position, columns); nCol += columns; endInsertColumns(); return true; } bool LazyAnnotationTreeViewModel::removeColumns( int position, int columns, const QModelIndex &parent /*= QModelIndex()*/ ) { beginRemoveColumns(parent, position, position + columns - 1); //success = rootItem->removeColumns(position, columns); nCol -= columns; endRemoveColumns(); if(nCol >= 2) { return true; } else { return false; } } //Tree Index TreeIndex::TreeIndex() { } TreeIndex::~TreeIndex() { } bool TreeIndex::isExpanded(AVItemL *item) { switch(item->type) { case AVItemType_Group: { AVGroupItemL *gr = static_cast(item); return isExpanded(gr->getAnnotationGroup()); } break; case AVItemType_Annotation: { AVGroupItemL *gr = static_cast(item->parent()); AVAnnotationItemL * ann = static_cast(item); return isExpanded(ann->annotation, gr->getAnnotationGroup()); } break; default: return 0; } } bool TreeIndex::isExpanded(Annotation *a, AnnotationGroup *gr) { int ind = findPosition(gr) + gr->getAnnotations().indexOf(a) + 1; return (itemMap[getRootGroupName(gr->getGObject())][ind] == 1); } bool TreeIndex::isExpanded(AnnotationGroup *gr) { if(gr->getParentGroup() == NULL) { return (itemMap[getRootGroupName(gr->getGObject())][0] == 1); } int ind = findPosition(gr); return (itemMap[getRootGroupName(gr->getGObject())][ind] == 1); } void TreeIndex::expand(QTreeWidgetItem *item) { QList indexes; QList groups; AVItemL *av = static_cast(item); QString objName; if(av->type == AVItemType_Group) { AnnotationGroup *topGroup = (static_cast(av))->getAnnotationGroup(); int ind = findPosition(topGroup); //itemMap[topGroup->getGObject()->getDocument()->getURLString()][ind] = 1; itemMap[getRootGroupName(topGroup->getGObject())][ind] = 1; } else if(av->type == AVItemType_Annotation) { Annotation *a = (static_cast(av))->annotation; AnnotationGroup *topGroup = (static_cast(av->parent()))->getAnnotationGroup(); int offset = topGroup->getAnnotations().indexOf(a); int ind = findPosition(topGroup) + offset + 1; itemMap[getRootGroupName(topGroup->getGObject())][ind] = 1; } } int TreeIndex::getChildNumber(AnnotationGroup *gr, int index) { int res = 1; for(int i = 0; i < index; i++) { res += getChildNumber(gr->getSubgroups()[i]); } res += gr->getAnnotations().size(); return res; } int TreeIndex::getChildNumber(AnnotationGroup *gr) { int res = 1; for(int i = 0; i < gr->getSubgroups().size(); i++) { res += getChildNumber(gr->getSubgroups()[i]); } res += gr->getAnnotations().size(); return res; } int TreeIndex::findPosition(AnnotationGroup *gr) { QList indexes; QList groups; int res = 0; /*------------------------------------------*/ /*-----Array of indexes in tree------------*/ /*------------------------------------------*/ AnnotationGroup *parGroup = gr->getParentGroup(); groups.append(parGroup); if(parGroup != NULL) { indexes << parGroup->getSubgroups().indexOf(gr); while(parGroup->getParentGroup()) { indexes.prepend(parGroup->getParentGroup()->getSubgroups().indexOf(parGroup)); parGroup = parGroup->getParentGroup(); groups.prepend(parGroup); } } else { return 0; } for(int i = 0; i < groups.size(); i++) { res += getChildNumber(groups[i], indexes[i]); //if(i > 0) { parGroup = groups[i]; //} } return res; } void TreeIndex::collapse(QTreeWidgetItem *item) { QList indexes; QList groups; AVItemL *av = static_cast(item); QString objName; if(av->type == AVItemType_Group) { AnnotationGroup *topGroup = (static_cast(av))->getAnnotationGroup(); int ind = findPosition(topGroup); itemMap[getRootGroupName(topGroup->getGObject())][ind] = 0; } else if(av->type == AVItemType_Annotation) { AnnotationGroup *topGroup = (static_cast(av->parent()))->getAnnotationGroup(); int offset = topGroup->getAnnotations().indexOf((static_cast(av))->annotation); int ind = findPosition(topGroup) + offset + 1; itemMap[getRootGroupName(topGroup->getGObject())][ind] = 0; } } void TreeIndex::recalculate( AnnotationTableObject * obj ){ std::vector items = std::vector(getChildNumber(obj), 0); itemMap.insert(getRootGroupName(obj), items); } int TreeIndex::getChildNumber( AnnotationTableObject * obj ){ AnnotationGroup *rootGroup = obj->getRootGroup(); int res = 1; foreach(AnnotationGroup *gr, rootGroup->getSubgroups()) { res += getChildNumber(gr); } return res; } void TreeIndex::deleteItem(Annotation *a, AnnotationGroup *gr) { int offset = gr->getAnnotations().indexOf(a); int ind = findPosition(gr) + offset + 1; itemMap[getRootGroupName(gr->getGObject())].erase(itemMap[getRootGroupName(gr->getGObject())].begin() + ind); if(gr->getAnnotations().isEmpty()) { ind = findPosition(gr); itemMap[getRootGroupName(gr->getGObject())][ind] = 0; } } void TreeIndex::deleteItem(AnnotationGroup *gr) { int ind = findPosition(gr); QString name = gr->getGObject() ? getRootGroupName(gr->getGObject()) : getRootGroupName(gr->getParentGroup()->getGObject()); itemMap[name].erase(itemMap[name].begin() + ind); if(gr->getParentGroup()->getSubgroups().isEmpty()) { ind = findPosition(gr->getParentGroup()); itemMap[name][ind] = 0; } } void TreeIndex::addItem(Annotation *a, AnnotationGroup *gr) { int ind; if(gr->getAnnotations().indexOf(a) != 0) { int offset = gr->getAnnotations().indexOf(a); ind = findPosition(gr) + offset; } else { while(gr->getParentGroup()) { int i = gr->getParentGroup()->getSubgroups().indexOf(gr); if(i != 0) { gr = gr->getParentGroup()->getSubgroups()[i - 1]; break; } gr = gr->getParentGroup(); } ind = findPosition(gr); } itemMap[getRootGroupName(gr->getGObject())].insert(itemMap[getRootGroupName(gr->getGObject())].begin() + ind, 1, 0); } void TreeIndex::addItem(AnnotationGroup *gr) { int ind; while(gr->getParentGroup()) { int i = gr->getParentGroup()->getSubgroups().indexOf(gr); if(i != 0) { gr = gr->getParentGroup()->getSubgroups()[i - 1]; break; } gr = gr->getParentGroup(); } ind = findPosition(gr); itemMap[getRootGroupName(gr->getGObject())].insert(itemMap[getRootGroupName(gr->getGObject())].begin() + ind, 1, 0); } QString TreeIndex::getRootGroupName(AnnotationTableObject* aobj) const{ AnnotationGroup *gr = aobj->getRootGroup(); QString text = aobj->getGObjectName(); if (aobj->getDocument() != NULL ) { QString docShortName = aobj->getDocument()->getName(); assert(!docShortName.isEmpty()); text = gr->getGObject()->getGObjectName() + " ["+docShortName+"]"; } return text; } ////////////////////////////////////////////////////////////////////////// /// Tree model bool AVItemL::processLinks(const QString& qName, const QString& qValue, int col) { bool linked = false; if (qName == "db_xref") { QStringList l = qValue.split(":"); QString dbName = l[0]; QString dbId = l.size() > 1 ? l[1] : ""; DBXRefInfo info = AppContext::getDBXRefRegistry()->getRefByKey(dbName); linked = !info.url.isEmpty(); setToolTip(col, info.comment); if (linked) { setData(col, Qt::UserRole, true); } } if (linked) { QFont f = font(col); f.setUnderline(true); setFont(col, f); setForeground(col, Qt::blue); } return linked; } bool AVItemL::removeChildren(int position, int count) { for (int row = 0; row < count; ++row) { delete takeChild(position); } return true; } bool AVItemL::addChildren(int position, int count, AVItemL *item) { for (int row = 0; row < count; ++row) { if(indexOfChild(item) != -1) { takeChild(indexOfChild(item)); } insertChild(position, item); } return true; } bool AVItemL::isColumnLinked(int col) const { return data(col, Qt::UserRole).type() == QVariant::Bool; } QString AVItemL::buildLinkURL(int col) const { assert(isColumnLinked(col)); QString qValue = text(col); QStringList split = qValue.split(":"); QString type = split.first(); QString id = split.size() < 2 ? QString("") : split[1]; QString url = AppContext::getDBXRefRegistry()->getRefByKey(type).url.arg(id); return url; } QString AVItemL::getFileUrl(int col) const { assert(isColumnLinked(col)); QStringList split = text(col).split(":"); QString type = split.first(); QString fileUrl = AppContext::getDBXRefRegistry()->getRefByKey(type).fileUrl; if (!fileUrl.isEmpty()) { QString id = split.size() < 2 ? QString("") : split[1]; return fileUrl.arg(id); } return fileUrl; } AVGroupItemL::AVGroupItemL(AnnotationsTreeViewL* _atv, AVGroupItemL* parent, AnnotationGroup* g) : AVItemL(parent, AVItemType_Group), group(g), atv(_atv) { updateVisual(); } AVGroupItemL::~AVGroupItemL() { group = NULL; } const QIcon& AVGroupItemL::getGroupIcon() { static QIcon groupIcon(":/core/images/group_green_active.png"); return groupIcon; } const QIcon& AVGroupItemL::getDocumentIcon() { static QIcon groupIcon(":/core/images/gobject.png"); return groupIcon; } void AVGroupItemL::updateVisual() { if (parent() == NULL || parent()->parent() == NULL) { // document item AnnotationTableObject* aobj = group->getGObject(); Document* doc = aobj->getDocument(); QString text = aobj->getGObjectName(); if (doc != NULL ) { QString docShortName = aobj->getDocument()->getName(); assert(!docShortName.isEmpty()); text = group->getGObject()->getGObjectName() + " ["+docShortName+"]"; if (aobj->isTreeItemModified()) { text+=" *"; } } setText(0, text); setIcon(0, getDocumentIcon()); GUIUtils::setMutedLnF(this, aobj->getAnnotations().count() == 0, false); } else { // usual groups with annotations int na = group->getAnnotations().size(); int ng = group->getSubgroups().size(); QString nameString = group->getGroupName() + " " + QString("(%1, %2)").arg(ng).arg(na); setText(0, nameString); setIcon(0, getGroupIcon()); // if all child items are muted -> mute this group too bool showDisabled = childCount() > 0; //empty group is not disabled for (int i = 0; i < childCount(); i++) { QTreeWidgetItem* childItem = child(i); if (!GUIUtils::isMutedLnF(childItem)) { showDisabled = false; break; } } GUIUtils::setMutedLnF(this, showDisabled, false); } } void AVGroupItemL::updateAnnotations(const QString& nameFilter, ATVAnnUpdateFlags f) { bool noFilter = nameFilter.isEmpty(); for (int j = 0; j < childCount(); j++) { AVItemL* item = static_cast(child(j)); if (item->type == AVItemType_Group) { AVGroupItemL* level1 = static_cast(item); if (noFilter || level1->group->getGroupName() == nameFilter) { level1->updateAnnotations(nameFilter, f); } } else { assert(item->type == AVItemType_Annotation); AVAnnotationItemL* aItem= static_cast(item); if (noFilter || aItem->annotation->getAnnotationName() == nameFilter) { aItem->updateVisual(f); } } } } bool AVGroupItemL::isReadonly() const { //documents names are not editable return group->getParentGroup() == NULL ? true: group->getGObject()->isStateLocked(); } void AVGroupItemL::findAnnotationItems(QList& result, Annotation* a) const { for (int i = 0, n = childCount(); i < n; i++) { AVItemL* item = static_cast(child(i)); if (item->type == AVItemType_Group) { AVGroupItemL* gi = static_cast(item); gi->findAnnotationItems(result, a); } else if (item->type == AVItemType_Annotation) { AVAnnotationItemL* ai = static_cast(item); if (ai->annotation == a) { result.append(ai); } } } } AnnotationTableObject* AVGroupItemL::getAnnotationTableObject() const { return group->getGObject(); } AnnotationGroup* AVGroupItemL::getAnnotationGroup() const { return group; } int AVGroupItemL::childNumber() const{ if(parent()) { if(parent()->parent() == NULL) {//root item const QTreeWidgetItem *root = parent(); for(int i = 0; i < root->childCount();i++) { if(root->child(i) == this) { return i; } } return 0; } return parent()->indexOfChild((QTreeWidgetItem*)this); } else { return 0; } } AVAnnotationItemL::AVAnnotationItemL(AVGroupItemL* parent, Annotation* a) : AVItemL(parent, AVItemType_Annotation), annotation(a) { updateVisual(ATVAnnUpdateFlags(ATVAnnUpdateFlag_BaseColumns) | ATVAnnUpdateFlag_QualColumns); hasNumericQColumns = false; } AVAnnotationItemL::~AVAnnotationItemL() { annotation = NULL; } #define MAX_ICONS_CACHE_SIZE 500 QMap& AVAnnotationItemL::getIconsCache() { static QMap iconsCache; return iconsCache; } void AVAnnotationItemL::updateVisual(ATVAnnUpdateFlags f) { const QString& name = annotation->getAnnotationName(); const AnnotationSettings* as = AppContext::getAnnotationsSettingsRegistry()->getAnnotationSettings(name); if (f.testFlag(ATVAnnUpdateFlag_BaseColumns)) { QMap& cache = getIconsCache(); QIcon icon = cache.value(name); if (icon.isNull()) { QColor iconColor = as->visible ? as->color : Qt::lightGray; icon = GUIUtils::createSquareIcon(iconColor, 9); if (cache.size() > MAX_ICONS_CACHE_SIZE) { cache.clear(); } cache[name] = icon; } assert(!icon.isNull()); setIcon(0, icon); setText(0, annotation->getAnnotationName()); locationString = Genbank::LocationParser::buildLocationString(annotation->data()); setText(1, locationString); } if (f.testFlag(ATVAnnUpdateFlag_QualColumns)) { //setup custom qualifiers columns AnnotationsTreeViewL* atv = getAnnotationTreeView(); assert(atv!=NULL); const QStringList& colNames = atv->getQualifierColumnNames(); hasNumericQColumns = false; for (int i=0, n = colNames.size(); i < n ;i++) { int col = 2+i; QString colName = colNames[i]; QString colText = annotation->findFirstQualifierValue(colName); setText(2+i, colText); bool linked = processLinks(colName, colText, col); if (!linked) { bool ok = false; double d = colText.toDouble(&ok); if (ok) { setData(col, Qt::UserRole, d); hasNumericQColumns = true; } } } } GUIUtils::setMutedLnF(this, !as->visible, true); } QVariant AVAnnotationItemL::data( int col, int role ) const { if (col == 1 && role == Qt::DisplayRole) { if (locationString.isEmpty()) { locationString = Genbank::LocationParser::buildLocationString(annotation->data()); } return locationString; } return QTreeWidgetItem::data(col, role); } int AVAnnotationItemL::childNumber() const { return parent()->indexOfChild((QTreeWidgetItem*)this); } bool AVAnnotationItemL::operator<(const QTreeWidgetItem & other) const { int col = treeWidget()->sortColumn(); const AVItemL& avItem = (const AVItemL&)other; if (avItem.type != AVItemType_Annotation) { return text(col) < other.text(col); } const AVAnnotationItemL& ai = (const AVAnnotationItemL&)other; if (col == 0) { QString name1 = annotation->getAnnotationName(); QString name2 = ai.annotation->getAnnotationName(); if (name1 == name2) { // for annotations with equal names we compare locations // this allows to avoid resorting on lazy qualifier loading return annotation->getLocation()->regions[0] < ai.annotation->getLocation()->regions[0]; } return name1 < name2; } if (col == 1 || (isColumnNumeric(col) && ai.isColumnNumeric(col))) { double oval = ai.getNumericVal(col); double mval = getNumericVal(col); return mval < oval; } return text(col) < other.text(col); } bool AVAnnotationItemL::isColumnNumeric(int col) const { if (col == 0) { return false; } if (col == 1) { return true; } if (!hasNumericQColumns) { return false; } return data(col, Qt::UserRole).type() == QVariant::Double; } double AVAnnotationItemL::getNumericVal(int col) const { if (col == 1) { const U2Region& r = annotation->getLocation()->regions[0]; return r.startPos; } bool ok = false; double d = data(col, Qt::UserRole).toDouble(&ok); assert(ok); return d; } void AVAnnotationItemL::removeQualifier(const U2Qualifier& q) { for(int i=0, n = childCount(); i < n; i++) { AVQualifierItemL* qi = static_cast(child(i)); if (qi->qName == q.name && qi->qValue == q.value) { delete qi; break; } } updateVisual(ATVAnnUpdateFlag_QualColumns); } void AVAnnotationItemL::addQualifier(const U2Qualifier& q) { AVQualifierItemL* qi = new AVQualifierItemL(this, q); Q_UNUSED(qi); updateVisual(ATVAnnUpdateFlag_QualColumns); } AVQualifierItemL* AVAnnotationItemL::findQualifierItem(const QString& name, const QString& val) const { for(int i=0, n = childCount(); i < n; i++) { AVQualifierItemL* qi = static_cast(child(i)); if (qi->qName == name && qi->qValue == val) { return qi; } } return NULL; } AVQualifierItemL::AVQualifierItemL(AVAnnotationItemL* parent, const U2Qualifier& q) : AVItemL(parent, AVItemType_Qualifier), qName(q.name), qValue(q.value) { setText(0, qName); setText(1, qValue); processLinks(qName, qValue, 1); } int AVQualifierItemL::childNumber() const { return parent()->indexOfChild((QTreeWidgetItem*)this); } }ugene-1.9.8/src/corelibs/U2View/src/util_ov_annotated_dna/ADVSequenceObjectContext.cpp0000644000175000017500000002537311651544334027476 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "ADVSequenceObjectContext.h" #include #include #include #include #include #include #include #include #include #include "AnnotatedDNAView.h" namespace U2 { ADVSequenceObjectContext::ADVSequenceObjectContext(AnnotatedDNAView* v, DNASequenceObject* obj) : QObject(v), view(v), seqObj(obj), aminoTT(NULL), complTT(NULL), selection(NULL), translations(NULL), visibleFrames(NULL) { selection = new DNASequenceSelection(seqObj, this); clarifyAminoTT = false; DNAAlphabet* al = getAlphabet(); if (al->isNucleic()) { DNATranslationRegistry* tr = AppContext::getDNATranslationRegistry(); complTT = GObjectUtils::findComplementTT(seqObj); aminoTT = GObjectUtils::findAminoTT(seqObj, true); clarifyAminoTT = aminoTT == NULL; QList aminoTs = tr->lookupTranslation(al, DNATranslationType_NUCL_2_AMINO); if (!aminoTs.empty()) { aminoTT = aminoTT == NULL ? aminoTs.first() : aminoTT; translations = new QActionGroup(this); foreach(DNATranslation* t, aminoTs) { QAction* a = translations->addAction(t->getTranslationName()); a->setCheckable(true); a->setChecked(aminoTT == t); a->setData(QVariant(t->getTranslationId())); connect(a, SIGNAL(triggered()), SLOT(sl_setAminoTranslation())); } visibleFrames = new QActionGroup(this); visibleFrames->setExclusive(false); for(int i = 0; i < 6; i++){ QAction* a; if(i < 3){ a = visibleFrames->addAction(QString("%1 direct translation frame").arg(i+1)); }else{ a = visibleFrames->addAction(QString("%1 complementary translation frame").arg(i+1-3)); } a->setCheckable(true); a->setChecked(true); //set row id a->setData(i); //save status translationRowsStatus.append(a); connect(a, SIGNAL(triggered()), SLOT(sl_toggleTranslations())); } } } } void ADVSequenceObjectContext::guessAminoTT(AnnotationTableObject* ao) { DNAAlphabet* al = getAlphabet(); assert(al->isNucleic()); DNATranslation* res = NULL; DNATranslationRegistry* tr = AppContext::getDNATranslationRegistry(); // try to guess relevant translation from a CDS feature (if any) foreach(Annotation* ann, ao->getAnnotations()) { if (ann->getAnnotationName() == "CDS") { QVector ql; ann->findQualifiers("transl_table", ql); if (ql.size() > 0) { QString guess = "NCBI-GenBank #"+ql.first().value; res = tr->lookupTranslation(al, DNATranslationType_NUCL_2_AMINO, guess); if (res !=NULL) { break; } } } } if (res != NULL) { clarifyAminoTT = false; setAminoTranslation(res->getTranslationId()); } } const QByteArray& ADVSequenceObjectContext::getSequenceData() const { return seqObj->getSequence(); } int ADVSequenceObjectContext::getSequenceLen() const { return seqObj->getSequenceLen(); } DNAAlphabet* ADVSequenceObjectContext::getAlphabet() const { return seqObj->getAlphabet(); } QList ADVSequenceObjectContext::getAnnotationGObjects() const { QList res; foreach(AnnotationTableObject* ao, annotations) { res.append(ao); } return res; } void ADVSequenceObjectContext::sl_showDirectOnly(){ bool needUpdate = false; QList actionList = visibleFrames->actions(); translationRowsStatus.clear(); int i = 0; for(; i < 3; i++){ QAction *a = actionList[i]; if(!a->isChecked()){ needUpdate = true; a->setChecked(true); translationRowsStatus.append(a); } } for(; i < 6; i++){ QAction *a = actionList[i]; if(a->isChecked()){ needUpdate = true; a->setChecked(false); } } if(needUpdate){ emit si_translationRowsChanged(); } } void ADVSequenceObjectContext::sl_showComplOnly(){ bool needUpdate = false; QList actionList = visibleFrames->actions(); translationRowsStatus.clear(); int i = 0; for(; i < 3; i++){ QAction *a = actionList[i]; if(a->isChecked()){ needUpdate = true; a->setChecked(false); } } for(; i < 6; i++){ QAction *a = actionList[i]; if(!a->isChecked()){ needUpdate = true; a->setChecked(true); translationRowsStatus.append(a); } } if(needUpdate){ emit si_translationRowsChanged(); } } void ADVSequenceObjectContext::sl_showShowAll(){ bool needUpdate = false; translationRowsStatus.clear(); foreach(QAction* a, visibleFrames->actions()){ if(!a->isChecked()) { needUpdate = true; a->setChecked(true); translationRowsStatus.append(a); } } if(needUpdate){ emit si_translationRowsChanged(); } } QMenu* ADVSequenceObjectContext::createTranslationsMenu() { QMenu* m = NULL, *frames = NULL; if (translations) { m = new QMenu(tr("Amino translation")); frames = new QMenu(tr("Translation frames")); foreach(QAction* a, visibleFrames->actions()) { frames->addAction(a); } frames->addSeparator(); connect(frames->addAction(QString("Show direct only")), SIGNAL(triggered()), SLOT(sl_showDirectOnly())); connect(frames->addAction(QString("Show complementary only")), SIGNAL(triggered()), SLOT(sl_showComplOnly())); connect(frames->addAction(QString("Show all")), SIGNAL(triggered()), SLOT(sl_showShowAll())); m->addMenu(frames); m->addSeparator(); m->setIcon(QIcon(":core/images/tt_switch.png")); foreach(QAction* a, translations->actions()) { m->addAction(a); } } return m; } void ADVSequenceObjectContext::setAminoTranslation(const QString& tid) { DNAAlphabet* al = getAlphabet(); DNATranslation* aTT = AppContext::getDNATranslationRegistry()->lookupTranslation(al, DNATranslationType_NUCL_2_AMINO, tid); assert(aTT!=NULL); if (aTT == aminoTT) { return; } aminoTT = aTT; foreach(QAction* a, translations->actions()) { if (a->data().toString() == tid) { a->setChecked(true); break; } } seqObj->getGHints()->set(AMINO_TT_GOBJECT_HINT, tid); emit si_aminoTranslationChanged(); } void ADVSequenceObjectContext::sl_setAminoTranslation() { QAction* a = qobject_cast(sender()); QString tid = a->data().toString(); setAminoTranslation(tid); } AnnotationSelection* ADVSequenceObjectContext::getAnnotationsSelection() const { return view->getAnnotationsSelection(); } void ADVSequenceObjectContext::removeSequenceWidget(ADVSequenceWidget* w) { assert(seqWidgets.contains(w)); seqWidgets.removeOne(w); } void ADVSequenceObjectContext::addSequenceWidget(ADVSequenceWidget* w) { assert(!seqWidgets.contains(w)); seqWidgets.append(w); } void ADVSequenceObjectContext::addAnnotationObject(AnnotationTableObject* obj) { assert(!annotations.contains(obj)); assert(obj->hasObjectRelation(seqObj, GObjectRelationRole::SEQUENCE)); annotations.insert(obj); emit si_annotationObjectAdded(obj); if (clarifyAminoTT) { guessAminoTT(obj); } } void ADVSequenceObjectContext::removeAnnotationObject(AnnotationTableObject* obj) { assert(annotations.contains(obj)); annotations.remove(obj); emit si_annotationObjectRemoved(obj); } QList ADVSequenceObjectContext::selectRelatedAnnotations(const QList& alist) const { QList res; foreach(Annotation* a, alist) { AnnotationTableObject* o = a->getGObject(); if (annotations.contains(o) || autoAnnotations.contains(o)) { res.append(a); } } return res; } GObject* ADVSequenceObjectContext::getSequenceGObject() const { return seqObj; } void ADVSequenceObjectContext::addAutoAnnotationObject( AnnotationTableObject* obj ){ autoAnnotations.insert(obj); emit si_annotationObjectAdded(obj); } QSet ADVSequenceObjectContext::getAnnotationObjects(bool includeAutoAnnotations) const { QSet result = annotations; if (includeAutoAnnotations) { result += autoAnnotations; } return result; } void ADVSequenceObjectContext::sl_toggleTranslations(){ translationRowsStatus.clear(); emit si_translationRowsChanged(); } QVector ADVSequenceObjectContext::getTranslationRowsVisibleStatus(){ QVector result; if (visibleFrames != NULL) { foreach(QAction* a, visibleFrames->actions()) { result.append(a->isChecked()); } } return result; } void ADVSequenceObjectContext::setTranslationsVisible(bool enable){ bool needUpdate = false; if(!enable){ translationRowsStatus.clear(); } foreach(QAction* a, visibleFrames->actions()){ if(!enable){//hide if(a->isChecked()) { needUpdate = true; a->setChecked(false); translationRowsStatus.append(a); } }else{//show if(!a->isChecked() && (translationRowsStatus.contains(a) || translationRowsStatus.isEmpty())) { needUpdate = true; a->setChecked(true); } } } if(needUpdate){ emit si_translationRowsChanged(); } } }//namespace ugene-1.9.8/src/corelibs/U2View/src/util_ov_annotated_dna/ui/0000755000175000017500000000000011651544334022576 5ustar ilyailyaugene-1.9.8/src/corelibs/U2View/src/util_ov_annotated_dna/ui/EditAnnotationDialog.ui0000644000175000017500000000732211651544334027201 0ustar ilyailya EditAnnotationDialog 0 0 354 124 Edit annotation Annotation name Location Qt::RichText ... :/core/images/do_complement.png:/core/images/do_complement.png ... :/core/images/predefined_annotation_groups.png:/core/images/predefined_annotation_groups.png Qt::Horizontal 40 20 OK Cancel OKButton clicked() EditAnnotationDialog accept() 222 100 176 61 CancelButton clicked() EditAnnotationDialog reject() 305 100 176 61 ugene-1.9.8/src/corelibs/U2View/src/util_ov_annotated_dna/ui/CreateRulerDialog.ui0000644000175000017500000001076511651544334026503 0ustar ilyailya CreateRulerDialog 0 0 222 130 Create new ruler 0 0 Ruler name 50 0 0 Ruler start Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter 0 0 Ruler color Sample Text false Qt::AlignCenter ... Qt::Vertical 20 4 Qt::Horizontal 40 20 Create true Cancel cancelButton clicked() CreateRulerDialog reject() 337 261 199 149 createButton clicked() CreateRulerDialog accept() 237 261 199 149 ugene-1.9.8/src/corelibs/U2View/src/util_ov_annotated_dna/PanView.cpp0000644000175000017500000011124111651544334024236 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "PanView.h" #include "ADVSequenceObjectContext.h" #include "ADVSingleSequenceWidget.h" #include "PanViewRows.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include namespace U2 { #define RULER_NOTCH_SIZE 2 PanView::ZoomUseObject::ZoomUseObject() : usingZoom(false), panView(NULL) {} PanView::ZoomUseObject::ZoomUseObject(PanView *pv) : usingZoom(false) { setPanView(pv); } PanView::ZoomUseObject::~ZoomUseObject(){ releaseZoom(); } void PanView::ZoomUseObject::setPanView(PanView *pv) { releaseZoom(); Q_ASSERT(pv); panView = pv; useZoom(); } void PanView::ZoomUseObject::useZoom() { if (usingZoom || !panView) { return; } usingZoom = true; panView->useZoom(); } void PanView::ZoomUseObject::releaseZoom() { if (!usingZoom || !panView) { return; } usingZoom = false; panView->releaseZoom(); } PanView::PanView(QWidget* p, ADVSequenceObjectContext* ctx) : GSequenceLineViewAnnotated(p, ctx) { rowBar = new QScrollBar(this); rowsManager = new PVRowsManager(); renderArea = new PanViewRenderArea(this); visibleRange.length = seqLen; minNuclsPerScreen = qMin(seqLen, qint64(0)); zoomUsing = 0; zoomInAction = new QAction(QIcon(":/core/images/zoom_in.png"), tr("Zoom In"), this); connect(zoomInAction, SIGNAL(triggered()), SLOT(sl_zoomInAction())); zoomOutAction = new QAction(QIcon(":/core/images/zoom_out.png"), tr("Zoom Out"), this); connect(zoomOutAction, SIGNAL(triggered()), SLOT(sl_zoomOutAction())); zoomToSelectionAction= new QAction(QIcon(":/core/images/zoom_sel.png"), tr("Zoom to Selection"), this); connect(zoomToSelectionAction, SIGNAL(triggered()), SLOT(sl_zoomToSelection())); zoomToSequenceAction = new QAction(QIcon(":/core/images/zoom_whole.png"), tr("Zoom to Whole Sequence"), this); connect(zoomToSequenceAction, SIGNAL(triggered()), SLOT(sl_zoomToSequence())); panViewToolButton = new QToolButton(); QMenu *menu = new QMenu(); showAllAnnotations = new QAction(tr("Show All Rows"), menu); showAllAnnotations->setCheckable(true); connect(showAllAnnotations, SIGNAL(triggered(bool)), renderArea, SLOT(sl_maxLines(bool))); increasePanViewHeight = new QAction(tr("+1 Row"), menu); connect(increasePanViewHeight, SIGNAL(triggered()), renderArea, SLOT(sl_increaseLines())); decreasePanViewHeight = new QAction(tr("-1 Row"), menu); connect(decreasePanViewHeight, SIGNAL(triggered()), renderArea, SLOT(sl_decreaseLines())); increase5PanViewHeight = new QAction(tr("+5 Rows"), menu); connect(increase5PanViewHeight, SIGNAL(triggered()), renderArea, SLOT(sl_increase5Lines())); decrease5PanViewHeight = new QAction(tr("-5 Rows"), menu); connect(decrease5PanViewHeight, SIGNAL(triggered()), renderArea, SLOT(sl_decrease5Lines())); resetAnnotations = new QAction(tr("Reset Rows Number"), menu); connect(resetAnnotations, SIGNAL(triggered()), renderArea, SLOT(sl_resetToDefault())); menu->addAction(showAllAnnotations); menu->addAction(increase5PanViewHeight); menu->addAction(increasePanViewHeight); menu->addAction(decreasePanViewHeight); menu->addAction(decrease5PanViewHeight); menu->addAction(resetAnnotations); panViewToolButton->setPopupMode(QToolButton::InstantPopup); panViewToolButton->setMenu(menu); panViewToolButton->setIcon(QIcon(":/core/images/zoom_rows.png")); panViewToolButton->setToolTip(tr("Manage Rows in Zoom View")); toggleMainRulerAction = new QAction(tr("Show Main Ruler"), this); toggleMainRulerAction->setCheckable(true); toggleMainRulerAction->setChecked(getRenderArea()->showMainRuler); connect(toggleMainRulerAction, SIGNAL(triggered(bool)), SLOT(sl_toggleMainRulerVisibility(bool))); toggleCustomRulersAction = new QAction(tr("Show Custom Rulers"), this); toggleCustomRulersAction->setCheckable(true); toggleCustomRulersAction->setChecked(getRenderArea()->showCustomRulers); toggleCustomRulersAction->setEnabled(!getRenderArea()->customRulers.isEmpty()); connect(toggleCustomRulersAction, SIGNAL(triggered(bool)), SLOT(sl_toggleCustomRulersVisibility(bool))); drawSettings.drawAnnotationArrows = true; drawSettings.drawAnnotationNames = true; drawSettings.drawCutSites = false; syncOffset = 0; //can't move to the GSequenceLineViewAnnotated -> virtual calls does not work in constructor foreach(AnnotationTableObject* obj, ctx->getAnnotationObjects(true)) { registerAnnotations(obj->getAnnotations()); } connect(ctx->getSequenceGObject(), SIGNAL(si_sequenceChanged()), this, SLOT(sl_sequenceChanged())); connect(this, SIGNAL(si_updateRows()), SLOT(sl_updateRows())); updateActions(); updateRowBar(); pack(); } void PanView::pack() { assert(layout() == NULL); QGridLayout* layout = new QGridLayout(); layout->setMargin(0); layout->setSpacing(0); layout->addWidget(renderArea, 0, 0, 1, 1); layout->addWidget(rowBar, 0, 1, 2, 1); layout->addWidget(scrollBar, 1, 0, 1, 1); setLayout(layout); setFixedHeight(layout->minimumSize().height()); } PanView::~PanView() { delete rowsManager; } void PanView::registerAnnotations(const QList& l) { GTIMER(c1,t1,"PanView::registerAnnotations"); AnnotationSettingsRegistry* asr = AppContext::getAnnotationsSettingsRegistry(); foreach(Annotation* a, l) { AnnotationSettings* as = asr->getAnnotationSettings(a); if (as->visible) { rowsManager->addAnnotation(a, a->getAnnotationName()); } } updateRows(); } void PanView::unregisterAnnotations(const QList& l) { AnnotationSettingsRegistry* asr = AppContext::getAnnotationsSettingsRegistry(); foreach(Annotation* a, l) { AnnotationSettings* as = asr->getAnnotationSettings(a); if (as->visible) { rowsManager->removeAnnotation(a); } } emit si_updateRows(); //updateRows(); } void PanView::updateRows() { updateRAHeight(); int maxSteps = calculateNumRowBarSteps(); if (qAbs(rowBar->maximum() - rowBar->minimum())!=maxSteps) { updateRowBar(); } updateActions(); } void PanView::updateRAHeight() { PanViewRenderArea* ra = getRenderArea(); bool heightChanged = ra->updateNumVisibleRows(); if (heightChanged) { QLayout* lt = layout(); if (lt != NULL) { setFixedHeight(lt->minimumSize().height()); } } } int PanView::calculateNumRowBarSteps() const { PanViewRenderArea* ra = getRenderArea(); int visibleRows = ra->getNumVisibleRows(); int numRows = rowsManager->getNumRows(); int res = qMax(0, numRows - visibleRows); return res; } void PanView::updateRowBar() { rowBar->disconnect(this); PanViewRenderArea* ra = getRenderArea(); int visibleRows = ra->getNumVisibleRows(); int maxSteps = calculateNumRowBarSteps(); rowBar->setMinimum(-maxSteps); //inverted appearance rowBar->setMaximum(0); rowBar->setSingleStep(1); rowBar->setPageStep(visibleRows - 1); int rowsOffset = qMin(maxSteps, ra->getRowLinesOffset()); ra->setRowLinesOffset(rowsOffset); rowBar->setSliderPosition(-rowsOffset); rowBar->setEnabled(maxSteps > 0); connect(rowBar, SIGNAL(valueChanged(int)), SLOT(sl_onRowBarMoved(int))); } void PanView::sl_onRowBarMoved(int v) { PanViewRenderArea* ra = getRenderArea(); ra->setRowLinesOffset(-v); // '-' because of inverted appearance addUpdateFlags(GSLV_UF_NeedCompleteRedraw); update(); } void PanView::sl_onAnnotationsModified(const AnnotationModification& md) { QList modified; modified << md.annotation; unregisterAnnotations(modified); registerAnnotations(modified); GSequenceLineViewAnnotated::sl_onAnnotationsModified(md); } void PanView::sl_onAnnotationSettingsChanged(const QStringList& changedSettings) { AnnotationSettingsRegistry* asr = AppContext::getAnnotationsSettingsRegistry(); foreach (const QString& name, changedSettings) { AnnotationSettings* as =asr->getAnnotationSettings(name); bool hasRow = rowsManager->contains(name); if (as->visible == hasRow) { continue; } QList changed; foreach(AnnotationTableObject* ao, ctx->getAnnotationObjects(true)) { ao->selectAnnotationsByName(name, changed); } if (changed.isEmpty()) { continue; } foreach(Annotation* a, changed) { if (as->visible) { rowsManager->addAnnotation(a, a->getAnnotationName()); } else { rowsManager->removeAnnotation(a); } } } updateRows(); GSequenceLineViewAnnotated::sl_onAnnotationSettingsChanged(changedSettings); } void PanView::setSelection(const U2Region& r) { ctx->getSequenceSelection()->clear(); if (r.length!=0) { ctx->getSequenceSelection()->addRegion(r); } } void PanView::onVisibleRangeChanged(bool signal) { updateActions(); GSequenceLineView::onVisibleRangeChanged(signal); } void PanView::useZoom() { zoomUsing++; updateActions(); } void PanView::releaseZoom() { if (zoomUsing) { zoomUsing--; updateActions(); } Q_ASSERT(zoomUsing >= 0); } void PanView::updateActions() { if (!zoomUsing) { zoomInAction->setDisabled(true); zoomOutAction->setDisabled(true); zoomToSelectionAction->setDisabled(true); zoomToSequenceAction->setDisabled(true); return; } zoomInAction->setEnabled(visibleRange.length > minNuclsPerScreen); zoomOutAction->setEnabled(visibleRange.length < seqLen); const QVector& sel = ctx->getSequenceSelection()->getSelectedRegions(); if (!sel.isEmpty() && sel.first().length >= minNuclsPerScreen) { zoomToSelectionAction->setEnabled(true); } else { zoomToSelectionAction->setEnabled(false); } zoomToSequenceAction->setEnabled(visibleRange.startPos != 0 || visibleRange.endPos() != seqLen); increasePanViewHeight->setEnabled(((PanViewRenderArea*)renderArea)->canIncreaseLines()); decreasePanViewHeight->setEnabled(((PanViewRenderArea*)renderArea)->canDecreaseLines()); increase5PanViewHeight->setEnabled(((PanViewRenderArea*)renderArea)->canIncreaseLines()); decrease5PanViewHeight->setEnabled(((PanViewRenderArea*)renderArea)->canDecreaseLines()); resetAnnotations->setEnabled(!((PanViewRenderArea*)renderArea)->isDefaultSize()); //showAllAnnotations->setEnabled(!((PanViewRenderArea*)renderArea)->isAllLinesShown()); panViewToolButton->setEnabled(isVisible() && (increasePanViewHeight->isEnabled() || decreasePanViewHeight->isEnabled() || increase5PanViewHeight->isEnabled() || decrease5PanViewHeight->isEnabled() || resetAnnotations->isEnabled())); } void PanView::sl_zoomInAction() { assert(visibleRange.length >= minNuclsPerScreen); DNASequenceSelection* sel = getSequenceContext()->getSequenceSelection(); if (!sel->isEmpty()) { const U2Region& selRange = sel->getSelectedRegions().first(); if (selRange.length >= minNuclsPerScreen && visibleRange.contains(selRange) && visibleRange != selRange) { sl_zoomToSelection(); return; } } U2Region newVisibleRange = visibleRange; newVisibleRange.length = qMax(int(visibleRange.length + 1) / 2, minNuclsPerScreen); if (newVisibleRange.length!=visibleRange.length) { newVisibleRange.startPos = visibleRange.startPos + (visibleRange.length - newVisibleRange.length)/2; setVisibleRange(newVisibleRange); } } void PanView::sl_zoomOutAction() { assert(visibleRange.length <= seqLen); U2Region newVisibleRange = visibleRange; newVisibleRange.length = qMin(visibleRange.length * 2, seqLen); if (newVisibleRange.length != visibleRange.length) { newVisibleRange.startPos = qBound(qint64(0), visibleRange.startPos - (newVisibleRange.length - visibleRange.length)/2, seqLen-newVisibleRange.length); assert(newVisibleRange.startPos >=0 && newVisibleRange.endPos() <= seqLen); //todo: move to setVisibleRange setVisibleRange(newVisibleRange); } } void PanView::sl_onDNASelectionChanged(LRegionsSelection* s, const QVector& added, const QVector& removed) { GSequenceLineView::sl_onDNASelectionChanged(s, added, removed); updateActions(); } void PanView::sl_zoomToSelection() { const QVector& sel = ctx->getSequenceSelection()->getSelectedRegions(); if (sel.isEmpty()) { return; } U2Region selRegion = sel.first(); if (selRegion.length < minNuclsPerScreen) { return; } if (visibleRange==selRegion) { return; } assert(ctx->getSequenceObject()->getSequenceRange().contains(selRegion)); visibleRange = selRegion; onVisibleRangeChanged(); } void PanView::sl_zoomToSequence() { U2Region wholeRange(0, seqLen); assert(visibleRange != wholeRange); visibleRange = wholeRange; onVisibleRangeChanged(); } void PanView::setVisibleRange(const U2Region& newRange, bool signal) { assert(newRange.startPos >=0 && newRange.endPos() <= seqLen); if (newRange.length < minNuclsPerScreen) { minNuclsPerScreen = newRange.length; } GSequenceLineView::setVisibleRange(newRange, signal); } void PanView::ensureVisible(Annotation* a, int locationIdx) { AnnotationSettingsRegistry* asr = AppContext::getAnnotationsSettingsRegistry(); AnnotationSettings* as = asr->getAnnotationSettings(a); if (as->visible) { int row = rowsManager->getAnnotationRowIdx(a); PanViewRenderArea* pr = getRenderArea(); if (!pr->isRowVisible(row)) { centerRow(row); } } GSequenceLineViewAnnotated::ensureVisible(a, locationIdx); } void PanView::centerRow(int row) { PanViewRenderArea* pr = getRenderArea(); int targetFirstRowLine = qMax(0, row - pr->getNumVisibleRows() / 2); int rowOnTheFirstLine = pr->getRowLinesOffset(); if (targetFirstRowLine == rowOnTheFirstLine) { return; } int dPos = targetFirstRowLine - rowOnTheFirstLine; int sliderPos = qBound(rowBar->minimum(), rowBar->value() - dPos, rowBar->maximum()); rowBar->setSliderPosition(sliderPos); } void PanView::sl_onRangeChangeRequest(int start, int end) { uiLog.trace(tr("range change request: [%1, %2]").arg(start).arg(end)); setVisibleRange(U2Region(start-1, end)); } void PanView::setNumBasesVisible(int n) { int nBases = qBound(minNuclsPerScreen, n, (int)seqLen); int center = visibleRange.startPos + visibleRange.length / 2; int newStart = qMax(0, center - nBases / 2); assert(newStart + nBases <= seqLen); setVisibleRange(U2Region(newStart, nBases)); } PanViewRenderArea* PanView::getRenderArea() const { return static_cast(renderArea); } QList PanView::getCustomRulers() const { return getRenderArea()->customRulers; } void PanView::addCustomRuler(const RulerInfo& r) { PanViewRenderArea* ra = getRenderArea(); ra->customRulers.append(r); if (ra->showCustomRulers) { updateRAHeight(); addUpdateFlags(GSLV_UF_NeedCompleteRedraw); update(); } toggleCustomRulersAction->setEnabled(true); } void PanView::removeCustomRuler(const QString& name) { PanViewRenderArea* ra = getRenderArea(); for (int i=0, n = ra->customRulers.count(); i < n; i++) { if (ra->customRulers[i].name == name) { ra->customRulers.removeAt(i); break; } } toggleCustomRulersAction->setEnabled(!ra->customRulers.isEmpty()); if (ra->showCustomRulers) { updateRAHeight(); addUpdateFlags(GSLV_UF_NeedCompleteRedraw); update(); } } void PanView::removeAllCustomRulers() { toggleCustomRulersAction->setEnabled(false); if (!getRenderArea()->customRulers.isEmpty()) { getRenderArea()->customRulers.clear(); updateRAHeight(); addUpdateFlags(GSLV_UF_NeedCompleteRedraw); update(); } } void PanView::sl_toggleMainRulerVisibility(bool visible) { getRenderArea()->showMainRuler = visible; updateRAHeight(); addUpdateFlags(GSLV_UF_NeedCompleteRedraw); update(); } void PanView::sl_toggleCustomRulersVisibility(bool visible) { getRenderArea()->showCustomRulers = visible; updateRAHeight(); addUpdateFlags(GSLV_UF_NeedCompleteRedraw); update(); } void PanView::setSyncOffset(int o) { if (o == syncOffset) { return; } syncOffset = o; addUpdateFlags(GSLV_UF_NeedCompleteRedraw); update(); } void PanView::sl_sequenceChanged(){ seqLen = ctx->getSequenceLen(); U2Region curSource(0, ctx->getSequenceLen()), newRange(0,0); if(!curSource.contains(visibleRange)){ if (curSource.length > visibleRange.length){ newRange.startPos = visibleRange.startPos - (visibleRange.endPos() - curSource.endPos()); newRange.length = visibleRange.length; }else{ newRange = curSource; } setVisibleRange(newRange); } GSequenceLineView::sl_sequenceChanged(); } void PanView::hideEvent( QHideEvent *ev ){ zoomInAction->setDisabled(true); zoomOutAction->setDisabled(true); zoomToSelectionAction->setDisabled(true); zoomToSequenceAction->setDisabled(true); panViewToolButton->setDisabled(true); QWidget::hideEvent(ev); } void PanView::showEvent( QShowEvent *ev ){ QWidget::showEvent(ev); updateActions(); } void PanView::sl_updateRows(){ updateRows(); } ////////////////////////////////////////////////////////////////////////// /// render PanViewRenderArea::PanViewRenderArea(PanView* d) : GSequenceLineViewAnnotatedRenderArea(d, false), panView(d) { showMainRuler = true; showCustomRulers = true; fromActions = false; showAllLines = false; defaultRows = true; numLines = 0; rowLinesOffset = 0; updateNumVisibleRows(); } void PanViewRenderArea::drawAll(QPaintDevice* pd) { GTIMER(c2,t2,"PanViewRenderArea::drawAll"); GSLV_UpdateFlags uf = view->getUpdateFlags(); bool completeRedraw = uf.testFlag(GSLV_UF_NeedCompleteRedraw) || uf.testFlag(GSLV_UF_ViewResized) || uf.testFlag(GSLV_UF_VisibleRangeChanged) || uf.testFlag(GSLV_UF_AnnotationsChanged); QPainter p(pd); if (completeRedraw) { QPainter pCached(cachedView); pCached.fillRect(0, 0, pd->width(), pd->height(), Qt::white); pCached.setPen(Qt::black); GraphUtils::RulerConfig c; PanView* panview = qobject_cast(view); const U2Region& visibleRange = view->getVisibleRange(); float halfChar = getCurrentScale() / 2; int firstCharCenter = qRound(posToCoordF(visibleRange.startPos) + halfChar); int lastCharCenter = qRound(posToCoordF(visibleRange.endPos()-1) + halfChar); int firstLastWidth = lastCharCenter - firstCharCenter; if (qRound(halfChar) == 0) { int w = width(); assert(firstLastWidth == w); Q_UNUSED(w); firstLastWidth--; // make the end of the ruler visible } c.notchSize = RULER_NOTCH_SIZE; int chunk = GraphUtils::calculateChunk(visibleRange.startPos+1, visibleRange.endPos(), panView->width(), p); foreach(const RulerInfo& ri, customRulers) { chunk = qMax(chunk, GraphUtils::calculateChunk(visibleRange.startPos+1-ri.offset, visibleRange.endPos()-ri.offset, panView->width(), p)); } c.predefinedChunk = chunk; drawRuler(c, pCached, visibleRange, firstCharCenter, firstLastWidth); drawCustomRulers(c, pCached, visibleRange, firstCharCenter); drawAnnotations(pCached); pCached.end(); } p.drawPixmap(0, 0, *cachedView); PanView* panview = qobject_cast(view); ADVSingleSequenceWidget* ssw = qobject_cast(panview->parentWidget()); assert(ssw); if(!ssw->isOverviewCollapsed()) { drawFrame(p); } drawSequence(p); drawAnnotationsSelection(p); drawSequenceSelection(p); if (view->hasFocus()) { drawFocus(p); } } void PanViewRenderArea::drawRuler(GraphUtils::RulerConfig c, QPainter& p, const U2Region &visibleRange, int firstCharCenter, int firstLastWidth){ if (!showMainRuler) { return; } int y = getLineY(getRulerLine()) + c.notchSize; GraphUtils::drawRuler(p, QPoint(firstCharCenter, y), firstLastWidth, visibleRange.startPos+1, visibleRange.endPos(), rulerFont, c); } #define LINE_TEXT_OFFSET 10 void PanViewRenderArea::drawCustomRulers(GraphUtils::RulerConfig c, QPainter& p, const U2Region &visibleRange, int firstCharCenter) { if (!showCustomRulers || customRulers.isEmpty()) { return; } float pixelsPerChar = getCurrentScale(); float halfChar = pixelsPerChar / 2; int lastCharCenter = qRound(posToCoordF(visibleRange.endPos()-1) + halfChar); QFont crf = rulerFont; crf.setBold(true); QFontMetrics fm(crf); int w = width(); int maxRulerTextWidth = 0; foreach(const RulerInfo& ri, customRulers) { int w = fm.width(ri.name); maxRulerTextWidth = qMax(maxRulerTextWidth, w); } for (int i=0, n = customRulers.count(); i= w) { continue; } int startPos = visibleRange.startPos + 1 - ri.offset; int endPos = visibleRange.endPos() - ri.offset; int x = firstCharCenter; if (firstCharCenter <= rulerStartOffset) { int deltaPixels = rulerStartOffset - firstCharCenter; int nChars = qMax(1, qRound(deltaPixels / pixelsPerChar)); int deltaPixels2 = nChars * pixelsPerChar; startPos+=nChars; x+=deltaPixels2; } int rulerWidth = lastCharCenter - x; if (qRound(halfChar) == 0) { assert(firstCharCenter == 0 && lastCharCenter == w); rulerWidth--; // make the end of the ruler visible } int offsetToFirstNotch = c.predefinedChunk - visibleRange.startPos%c.predefinedChunk; int mainRuler = visibleRange.startPos + offsetToFirstNotch; int newStartPos = visibleRange.startPos - ri.offset + offsetToFirstNotch; int lim = startPos + ri.offset; for(; mainRuler < lim; mainRuler += c.predefinedChunk, newStartPos += c.predefinedChunk); c.correction = newStartPos; GraphUtils::drawRuler(p, QPoint(x, y), rulerWidth, startPos, endPos, rulerFont, c); } } U2Region PanViewRenderArea::getAnnotationYRange(Annotation* a, int, const AnnotationSettings* as) const { if (!as->visible) { return U2Region(-1, 0); } int row = getPanView()->getRowsManager()->getAnnotationRowIdx(a); int line = getRowLine(row); return U2Region(getLineY(line) + 2, lineHeight - 4); } void PanViewRenderArea::drawAnnotations(QPainter& p) { GTIMER(c2,t2,"PanViewRenderArea::drawAnnotations"); QPen dotty(Qt::lightGray, 1, Qt::DotLine); p.setPen(dotty); p.setFont(*afSmall); int w = width(); //draw row names PVRowsManager* rm = getPanView()->getRowsManager(); int maxVisibleRows = getNumVisibleRows(); for (int i = 0; i < maxVisibleRows; i++) { int row = i + rowLinesOffset; int rowLine = getRowLine(row); int lineY = getLineY(rowLine); p.drawLine(0, lineY, cachedView->width(), lineY); PVRowData* rData = rm->getRow(row); QString text; if (rData == NULL) { text = U2::PanView::tr("empty"); } else { text = rData->key + " (" + QString::number(rData->annotations.size()) + ")"; } QRect textRect(LINE_TEXT_OFFSET, lineY + 1, w, lineHeight - 2); p.drawText(textRect, text); if (rData != NULL) { AnnotationSettingsRegistry* asr = AppContext::getAnnotationsSettingsRegistry(); AnnotationSettings* as = asr->getAnnotationSettings(rData->key); if (as->visible) { QPen pen1(Qt::SolidLine); pen1.setWidth(1); U2Region yr(lineY + 2, lineHeight - 4); foreach(Annotation* a, rData->annotations) { drawAnnotation(p, DrawAnnotationPass_DrawFill, a, pen1, false, as, yr); drawAnnotation(p, DrawAnnotationPass_DrawBorder, a, pen1, false, as, yr); } //restore pen p.setPen(dotty); p.setFont(*afSmall); } } } int firstRowLine = getRowLine(0); int lineY = getLineY(firstRowLine) + lineHeight; p.drawLine(0, lineY, cachedView->width(), lineY); } bool PanViewRenderArea::isSequenceCharsVisible() const { return getCurrentScale() >= smallCharWidth; } void PanViewRenderArea::drawSequence(QPainter& p) { if (!isSequenceCharsVisible()) { return; } p.setPen(Qt::black); float halfCharByScale = getCurrentScale() / 2; float halfCharByFont = 0.0f; if (getCurrentScale() >= charWidth) { p.setFont(sequenceFont); halfCharByFont = charWidth / 2.0f; } else { p.setFont(smallSequenceFont); halfCharByFont = smallCharWidth / 2.0f; } const QByteArray& seq = view->getSequenceContext()->getSequenceData(); const U2Region& visibleRange = view->getVisibleRange(); int y = getLineY(getSelectionLine()) + lineHeight - yCharOffset; for (int i = visibleRange.startPos; i < visibleRange.endPos(); i++) { char c = seq[i]; int x = qRound(posToCoordF(i) + halfCharByScale - halfCharByFont); p.drawText(x, y, QString(c)); } } #define ARROW_DY 5 #define ARROW_DX 5 void PanViewRenderArea::drawSequenceSelection(QPainter& p) { const QVector& selection = panView->getSequenceContext()->getSequenceSelection()->getSelectedRegions(); bool showSequenceMode = isSequenceCharsVisible(); if (selection.isEmpty()) { return; } const U2Region& visibleRange = view->getVisibleRange(); QPen pen1(Qt::darkGray, 1, Qt::SolidLine); QPen pen2(QColor("#007DE3"), 2, Qt::SolidLine); p.setFont(rulerFont); QFontMetrics rfm(rulerFont); int lineY = getLineY(getSelectionLine()); int ly = lineY + lineHeight/2; //ruler line bool drawRect = showSequenceMode; bool drawGraphics = true; if (showSequenceMode) { ly = lineY - lineHeight + RULER_NOTCH_SIZE; drawGraphics = ly > 0; } int halfNum = rfm.boundingRect('1').height() / 2; int rty = ly + halfNum; DNAAlphabet* alphabet = panView->getSequenceObject()->getAlphabet(); QString unitType; if (alphabet->isAmino()) { unitType = "aa"; } else { unitType = "bp"; } QString rangePattern = " "+tr("[%1 %2]")+" "; foreach(const U2Region& r, selection) { if (!visibleRange.intersects(r)) { continue; } int x1 = qMax(0, posToCoord(r.startPos, true)); int x2 = qMin(cachedView->width(), posToCoord(r.endPos(), true)); p.setPen(pen1); if (visibleRange.contains(r.startPos)) { p.drawLine(x1, 0, x1, ly); } if (visibleRange.contains(r.endPos()-1)) { p.drawLine(x2, 0, x2, ly); } if (drawRect) { p.setPen(Qt::black); p.drawRect(x1, lineY+1, x2 - x1, lineHeight-2); } if (drawGraphics) { //draw line p.setPen(pen2); p.drawLine(x1, ly, x2, ly); int dArrow = 2 * ARROW_DX; QString t1 = QString::number(r.startPos+1); QString t2 = QString::number(r.endPos()); int tOffs = ARROW_DX-1; QRect t1Rect = rfm.boundingRect(t1); t1Rect.translate(x1 - t1Rect.width() - tOffs, rty); QRect t2Rect = rfm.boundingRect(t2).translated(x2 + tOffs, rty); // define range text coords QString rangeText = rangePattern.arg(r.length).arg(unitType); QRect rtRect = rfm.boundingRect(rangeText); int rulerWidth = x2 - x1; bool rangeTextInTheMiddle = rulerWidth - dArrow > rtRect.width(); if (rangeTextInTheMiddle) { int rtx = x1 + (rulerWidth - rtRect.width())/2 + 1; assert(rtx - x1 >= ARROW_DX); rtRect.translate(rtx, rty); p.fillRect(rtRect, Qt::white); p.drawText(rtRect, Qt::AlignCenter, rangeText); } else if (!rangeTextInTheMiddle) { //if range text is not in the middle glue it to one of the boundary texts QString newT2 = t2 + rangeText; QRect newT2Rect = rfm.boundingRect(newT2).translated(x2 + tOffs, rty); if (newT2Rect.right() < width()) { t2Rect = newT2Rect; t2 = newT2; } else { QString newT1 = rangeText + t1; QRect newT1Rect = rfm.boundingRect(newT1); newT1Rect.translate(x1 - newT1Rect.width() - tOffs, rty); if (newT1Rect.left() >=0) { t1 = newT1; t1Rect = newT1Rect; } } } //check if regions overlap int interWidth = t2Rect.left() - t1Rect.right(); if (interWidth < dArrow) { int deltaW = interWidth > 0 ? dArrow : qAbs(interWidth) + dArrow; if (t1Rect.x() - deltaW > 0) { t1Rect.translate(-deltaW, 0); } else if (t2Rect.right() + deltaW < width()) { t2Rect.translate(deltaW, 0); } } //draw regions p.fillRect(t1Rect, Qt::white); p.fillRect(t2Rect, Qt::white); p.drawText(t1Rect, Qt::AlignCenter, t1); p.drawText(t2Rect, Qt::AlignCenter, t2); //draw arrows (after the text -> can overlap with text rect boundaries) if (visibleRange.contains(r.startPos)) { p.drawLine(x1, ly, x1 + ARROW_DX, ly + ARROW_DY); p.drawLine(x1, ly, x1 + ARROW_DX, ly - ARROW_DY); } if (visibleRange.contains(r.endPos()-1)) { p.drawLine(x2, ly, x2 - ARROW_DX, ly + ARROW_DY); p.drawLine(x2, ly, x2 - ARROW_DX, ly - ARROW_DY); } } } } int PanViewRenderArea::getRowLine(int i) const { int line = getFirstRowLine() - i + rowLinesOffset; if (line < 0 || line > getFirstRowLine()) { return -1; } return line; } #define MIN_VISIBLE_ROWS 1 #define EXTRA_EMPTY_ROWS 0 #define MAX_VISIBLE_ROWS 20 void PanViewRenderArea::setRowLinesOffset(int r) { int maxRows = getPanView()->getRowsManager()->getNumRows(); int visibleRows = getNumVisibleRows(); assert(r <= maxRows - (visibleRows - MIN_VISIBLE_ROWS)) ; Q_UNUSED(maxRows); Q_UNUSED(visibleRows); if (r!=rowLinesOffset) { rowLinesOffset = r; update(); } } bool PanViewRenderArea::updateNumVisibleRows() { if(showAllLines) { int additionalLines = 1 + (showMainRuler ? 1 : 0) + (showCustomRulers ? customRulers.size() : 0); numLines = getPanView()->getRowsManager()->getNumRows() + additionalLines; } else if(defaultRows) { int annotationRows = getPanView()->getRowsManager()->getNumRows(); int expectedRowsToShow = annotationRows + EXTRA_EMPTY_ROWS; int actualAnnotationsRowsToShow = qBound(MIN_VISIBLE_ROWS, expectedRowsToShow, MAX_VISIBLE_ROWS); int newNumLines = actualAnnotationsRowsToShow + 1 + (showMainRuler ? 1 : 0) + (showCustomRulers ? customRulers.size() : 0); if (newNumLines == numLines) { return false; //height was not changed } numLines = newNumLines; } else { fromActions = false; } setFixedHeight(numLines * lineHeight); view->addUpdateFlags(GSLV_UF_ViewResized); view->update(); return true; } void PanViewRenderArea::sl_increaseLines(){ int additionalLines = 1 + (showMainRuler ? 1 : 0) + (showCustomRulers ? customRulers.size() : 0); if(numLines < getPanView()->getRowsManager()->getNumRows() + additionalLines) { numLines++; fromActions = true; defaultRows = false; panView->updateRows(); } } void PanViewRenderArea::sl_decreaseLines(){ int additionalLines = 1 + (showMainRuler ? 1 : 0) + (showCustomRulers ? customRulers.size() : 0); if(numLines > 1 + additionalLines) { numLines--; panView->showAllAnnotations->setChecked(false); showAllLines = false; fromActions = true; defaultRows = false; panView->updateRows(); } } void PanViewRenderArea::sl_increase5Lines(){ int additionalLines = 1 + (showMainRuler ? 1 : 0) + (showCustomRulers ? customRulers.size() : 0); if(numLines < getPanView()->getRowsManager()->getNumRows() + additionalLines) { numLines += qMin(5, getPanView()->getRowsManager()->getNumRows() + additionalLines - numLines); fromActions = true; defaultRows = false; panView->updateRows(); } } void PanViewRenderArea::sl_decrease5Lines(){ int additionalLines = 1 + (showMainRuler ? 1 : 0) + (showCustomRulers ? customRulers.size() : 0); if(numLines > 1 + additionalLines) { numLines -= 5; if(numLines < 1 + additionalLines) { numLines = 1 + additionalLines; } panView->showAllAnnotations->setChecked(false); showAllLines = false; fromActions = true; defaultRows = false; panView->updateRows(); } } void PanViewRenderArea::sl_maxLines(bool checked){ if(checked) { showAllLines = true; int additionalLines = 1 + (showMainRuler ? 1 : 0) + (showCustomRulers ? customRulers.size() : 0); numLines = getPanView()->getRowsManager()->getNumRows() + additionalLines; fromActions = true; defaultRows = false; panView->updateRows(); } else { showAllLines = false; } } void PanViewRenderArea::sl_resetToDefault() { int additionalLines = 1 + (showMainRuler ? 1 : 0) + (showCustomRulers ? customRulers.size() : 0); numLines = qMin(MAX_VISIBLE_ROWS + additionalLines, getPanView()->getRowsManager()->getNumRows() + additionalLines); panView->showAllAnnotations->setChecked(false); showAllLines = false; fromActions = true; defaultRows = false; panView->updateRows(); } bool PanViewRenderArea::canIncreaseLines() { int additionalLines = 1 + (showMainRuler ? 1 : 0) + (showCustomRulers ? customRulers.size() : 0); return numLines < (getPanView()->getRowsManager()->getNumRows() + additionalLines); } bool PanViewRenderArea::canDecreaseLines() { int additionalLines = 1 + (showMainRuler ? 1 : 0) + (showCustomRulers ? customRulers.size() : 0); return numLines > (1 +additionalLines); } bool PanViewRenderArea::isAllLinesShown() { int additionalLines = 1 + (showMainRuler ? 1 : 0) + (showCustomRulers ? customRulers.size() : 0); return numLines == (getPanView()->getRowsManager()->getNumRows() + additionalLines); } bool PanViewRenderArea::isDefaultSize() { int additionalLines = 1 + (showMainRuler ? 1 : 0) + (showCustomRulers ? customRulers.size() : 0); return numLines == (MAX_VISIBLE_ROWS + additionalLines); } }//namespace ugene-1.9.8/src/corelibs/U2View/src/util_ov_annotated_dna/AnnotatedDNAViewTasks.cpp0000644000175000017500000002311711651544334026772 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "AnnotatedDNAViewTasks.h" #include "AnnotatedDNAView.h" #include "AnnotatedDNAViewFactory.h" #include "AnnotatedDNAViewState.h" #include "GSequenceLineView.h" #include #include #include #include #include #include #include #include #include #include #include namespace U2 { /* TRANSLATOR U2::AnnotatedDNAView */ /* TRANSLATOR U2::ObjectViewTask */ ////////////////////////////////////////////////////////////////////////// /// open new view //opens a single view for all sequence object in the list of sequence objects related to the objects in the list OpenAnnotatedDNAViewTask::OpenAnnotatedDNAViewTask(const QList& objects) : ObjectViewTask(AnnotatedDNAViewFactory::ID) { // remember only sequence objects -> other added automatically // load all objects QList docsToLoadSet; QSet refsAdded; QList allSequenceObjects = GObjectUtils::findAllObjects(UOF_LoadedAndUnloaded, GObjectTypes::SEQUENCE); foreach(GObject* obj, objects) { uiLog.trace("Object to open sequence view: '" + obj->getGObjectName()+"'"); Document* doc = obj->getDocument(); if (!doc->isLoaded()) { docsToLoadSet.append(doc); } if (GObjectUtils::hasType(obj, GObjectTypes::SEQUENCE)) { sequenceObjectRefs.append(GObjectReference(doc->getURLString(), obj->getGObjectName(), GObjectTypes::SEQUENCE)); refsAdded.insert(obj); continue; } //look for sequence object using relations QList objWithSeqRelation = GObjectUtils::selectRelations(obj, GObjectTypes::SEQUENCE, GObjectRelationRole::SEQUENCE, allSequenceObjects, UOF_LoadedAndUnloaded); foreach(GObject* robj, objWithSeqRelation) { if (!GObjectUtils::hasType(robj, GObjectTypes::SEQUENCE)) { continue; } if (refsAdded.contains(robj)) { continue; } Document* rdoc = robj->getDocument(); if (!rdoc->isLoaded()) { docsToLoadSet.append(rdoc); } refsAdded.insert(robj); sequenceObjectRefs.append(GObjectReference(rdoc->getURLString(), robj->getGObjectName(), GObjectTypes::SEQUENCE)); } } foreach(Document* doc, docsToLoadSet) { uiLog.trace("Document to load: '" + doc->getURLString()+"'"); documentsToLoad.append(doc); } } #define MAX_SEQ_OBJS_PER_VIEW 50 static QString deriveViewName(const QList& seqObjects) { QString viewName; if (seqObjects.size() > 1) { bool singleDocument = true; Document* doc = seqObjects.first()->getDocument(); foreach(GObject* obj, seqObjects) { if (doc != obj->getDocument()) { singleDocument = false; break; } } if (singleDocument) { viewName = GObjectViewUtils::genUniqueViewName(doc->getName()); } else { viewName = GObjectViewUtils::genUniqueViewName(OpenAnnotatedDNAViewTask::tr("Sequences")); } } else { GObject* obj = seqObjects.first(); viewName = GObjectViewUtils::genUniqueViewName(obj->getDocument(), obj); } return viewName; } void OpenAnnotatedDNAViewTask::open() { if (stateInfo.hasError() || sequenceObjectRefs.isEmpty()) { return; } QList seqObjects; QList allSequenceObjects = GObjectUtils::findAllObjects(UOF_LoadedOnly, GObjectTypes::SEQUENCE); foreach(const GObjectReference& r, sequenceObjectRefs) { GObject* obj = GObjectUtils::selectObjectByReference(r, allSequenceObjects, UOF_LoadedOnly); DNASequenceObject* seqObj = qobject_cast(obj); if (seqObj!=NULL) { seqObjects.append(seqObj); if (seqObjects.size() > MAX_SEQ_OBJS_PER_VIEW) { uiLog.details(tr("Maximum number of objects per view reached: %1").arg(MAX_SEQ_OBJS_PER_VIEW)); break; } } else { uiLog.details(tr("Sequence object not available! URL %1, name %2").arg(r.docUrl).arg(r.objName)); } } if (seqObjects.isEmpty()) { //object was removed asynchronously with the task stateInfo.setError(tr("No sequence objects found")); return; } QString viewName = deriveViewName(seqObjects); AnnotatedDNAView* v = new AnnotatedDNAView(viewName, seqObjects); GObjectViewWindow* w = new GObjectViewWindow(v, viewName, false); MWMDIManager* mdiManager = AppContext::getMainWindow()->getMDIManager(); mdiManager->addMDIWindow(w); } void OpenAnnotatedDNAViewTask::updateTitle(AnnotatedDNAView* v) { const QString& oldViewName = v->getName(); GObjectViewWindow* w = GObjectViewUtils::findViewByName(oldViewName); if (w != NULL) { QString newViewName = deriveViewName(v->getSequenceObjectsWithContexts()); v->setName(newViewName); w->setWindowTitle(newViewName); } } ////////////////////////////////////////////////////////////////////////// // open view from state static QSet selectDocuments(Project* p, const QList& refs) { QSet res; foreach(const GObjectReference& r, refs) { Document* doc = p->findDocumentByURL(r.docUrl); if (doc!=NULL) { res.insert(doc); } else { doc = ObjectViewTask::createDocumentAndAddToProject(r.docUrl, p); if (doc) { res.insert(doc); } } } return res; } OpenSavedAnnotatedDNAViewTask::OpenSavedAnnotatedDNAViewTask(const QString& viewName, const QVariantMap& stateData) : ObjectViewTask(AnnotatedDNAViewFactory::ID, viewName, stateData) { AnnotatedDNAViewState state(stateData); QList refs = state.getSequenceObjects(); if (refs.isEmpty()) { stateIsIllegal = true; stateInfo.setError(ObjectViewTask::tr("No sequence info found!")); return; } foreach(const GObjectReference& ref, refs) { Document* doc = AppContext::getProject()->findDocumentByURL(ref.docUrl); if (doc == NULL) { doc = createDocumentAndAddToProject(ref.docUrl, AppContext::getProject()); if (!doc) { stateIsIllegal = true; stateInfo.setError(L10N::errorDocumentNotFound(ref.docUrl)); return; } } if (!doc->isLoaded()) { documentsToLoad.append(doc); } } QSet adocs = selectDocuments(AppContext::getProject(), state.getAnnotationObjects()); foreach(Document* adoc, adocs) { if (!adoc->isLoaded()) { documentsToLoad.append(adoc); } } } void OpenSavedAnnotatedDNAViewTask::open() { if (stateInfo.hasError()) { return; } AnnotatedDNAViewState state(stateData); QList sequenceObjects; foreach(const GObjectReference& ref, state.getSequenceObjects()) { Document* doc = AppContext::getProject()->findDocumentByURL(ref.docUrl); if (doc == NULL) { stateIsIllegal = true; stateInfo.setError(L10N::errorDocumentNotFound(ref.docUrl)); return; } GObject* obj = doc->findGObjectByName(ref.objName); if (obj == NULL || obj->getGObjectType() != GObjectTypes::SEQUENCE) { stateIsIllegal = true; stateInfo.setError(tr("DNA sequence object not found: %1").arg(ref.objName)); return; } DNASequenceObject* dnaObj= qobject_cast(obj); sequenceObjects.append(dnaObj); } AnnotatedDNAView* v = new AnnotatedDNAView(viewName, sequenceObjects); GObjectViewWindow* w = new GObjectViewWindow(v, viewName, true); MWMDIManager* mdiManager = AppContext::getMainWindow()->getMDIManager(); mdiManager->addMDIWindow(w); v->updateState(state); } ////////////////////////////////////////////////////////////////////////// // update UpdateAnnotatedDNAViewTask::UpdateAnnotatedDNAViewTask(AnnotatedDNAView* v, const QString& stateName, const QVariantMap& stateData) : ObjectViewTask(v, stateName, stateData) { } void UpdateAnnotatedDNAViewTask::update() { if (view.isNull()) { return; //view was closed; } AnnotatedDNAView* aview = qobject_cast(view.data()); assert(aview!=NULL); AnnotatedDNAViewState state(stateData); aview->updateState(state); } } // namespace ugene-1.9.8/src/corelibs/U2View/src/util_ov_annotated_dna/GSequenceLineView.cpp0000644000175000017500000004352311651544334026216 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "GSequenceLineView.h" #include "ADVSequenceObjectContext.h" #include #include #include #include #include #include #include #include namespace U2 { GSequenceLineView::GSequenceLineView(QWidget* p, ADVSequenceObjectContext* _ctx) : QWidget(p), ctx(_ctx), renderArea(NULL), scrollBar(NULL), lastPressPos(-1), lastUpdateFlags(GSLV_UF_ViewResized), featureFlags(GSLV_FF_SupportsCustomRange), frameView(NULL), coherentRangeView(NULL), ignoreMouseSelectionEvents(false) { seqLen = ctx->getSequenceLen(); setFocusPolicy(Qt::WheelFocus); scrollBar = new GScrollBar(Qt::Horizontal, this); connect(ctx->getSequenceSelection(), SIGNAL(si_selectionChanged(LRegionsSelection*, const QVector&, const QVector&)), SLOT(sl_onDNASelectionChanged(LRegionsSelection*, const QVector& , const QVector&))); } void GSequenceLineView::pack() { assert(layout() == NULL); QVBoxLayout *layout = new QVBoxLayout(); layout->setMargin(0); layout->setSpacing(0); layout->addWidget(renderArea); layout->addWidget(scrollBar); setLayout(layout); setFixedHeight(layout->minimumSize().height()); } void GSequenceLineView::resizeEvent(QResizeEvent *e) { updateScrollBar(); addUpdateFlags(GSLV_UF_ViewResized); QWidget::resizeEvent(e); } void GSequenceLineView::updateScrollBar() { scrollBar->disconnect(this); scrollBar->setMinimum(0); scrollBar->setMaximum(seqLen - visibleRange.length); scrollBar->setSliderPosition(visibleRange.startPos); //todo: int singleStep = getSingleStep(); int pageStep = getPageStep(); scrollBar->setSingleStep(singleStep); scrollBar->setPageStep(pageStep); scrollBar->setDisabled(visibleRange.length == seqLen); connect(scrollBar, SIGNAL(valueChanged(int)), SLOT(sl_onScrollBarMoved(int))); } int GSequenceLineView::getSingleStep() const { if (coherentRangeView !=NULL) { return coherentRangeView->getSingleStep(); } return 1; } int GSequenceLineView::getPageStep() const { if (coherentRangeView !=NULL) { return coherentRangeView->getPageStep(); } return visibleRange.length; } void GSequenceLineView::sl_onScrollBarMoved(int pos) { if (coherentRangeView!=NULL) { coherentRangeView->sl_onScrollBarMoved(pos); return; } setStartPos(pos); if (lastPressPos!=-1) { QAbstractSlider::SliderAction aAction = scrollBar->getRepeatAction(); if (aAction == QAbstractSlider::SliderSingleStepAdd) { int selStart = qMin(lastPressPos, visibleRange.endPos()); int selEnd = qMax(lastPressPos, visibleRange.endPos()); setSelection(U2Region(selStart, selEnd - selStart)); } else if (aAction == QAbstractSlider::SliderSingleStepSub) { int selStart = qMin(lastPressPos, visibleRange.startPos); int selEnd = qMax(lastPressPos, visibleRange.startPos); setSelection(U2Region(selStart, selEnd - selStart)); } } } void GSequenceLineView::setSelection(const U2Region& r) { SAFE_POINT(r.startPos >=0 && r.endPos() <= seqLen, QString("Selection is out of range! [%2, len: %3]").arg(r.startPos).arg(r.length),); ctx->getSequenceSelection()->clear(); if (r.length!=0) { ctx->getSequenceSelection()->addRegion(r); } } void GSequenceLineView::addSelection(const U2Region& r) { SAFE_POINT(r.startPos >=0 && r.endPos() <= seqLen, QString("Selection is out of range! [%2, len: %3]").arg(r.startPos).arg(r.length),); if (r.length!=0) { ctx->getSequenceSelection()->addRegion(r); } } void GSequenceLineView::removeSelection(const U2Region& r) { SAFE_POINT(r.startPos >=0 && r.endPos() <= seqLen, QString("Selection is out of range! [%2, len: %3]").arg(r.startPos).arg(r.length),); if (r.length!=0) { ctx->getSequenceSelection()->removeRegion(r); } } void GSequenceLineView::mousePressEvent(QMouseEvent* me) { setFocus(); if (me->button() == Qt::RightButton) { QWidget::mousePressEvent(me); return; } QPoint renderAreaPos = toRenderAreaPoint(me->pos()); if (!renderArea->rect().contains(renderAreaPos)) { scrollBar->setupRepeatAction(QAbstractSlider::SliderNoAction); lastPressPos = -1; QWidget::mousePressEvent(me); return; } lastPressPos = renderArea->coordToPos(renderAreaPos.x()); SAFE_POINT(lastPressPos >= visibleRange.startPos && lastPressPos <= visibleRange.endPos(), "Last mouse press position is out of visible range!",); if (!ignoreMouseSelectionEvents) { ctx->getSequenceSelection()->clear(); } QWidget::mousePressEvent(me); } void GSequenceLineView::mouseReleaseEvent(QMouseEvent* me) { setFocus(); if (!ignoreMouseSelectionEvents) { //click with 'alt' selects a single base Qt::KeyboardModifiers km = QApplication::keyboardModifiers(); bool singleBaseSelectionMode = km.testFlag(Qt::AltModifier); if (me->button() == Qt::LeftButton && singleBaseSelectionMode) { QPoint areaPoint = toRenderAreaPoint(me->pos()); int pos = renderArea->coordToPos(areaPoint.x()); if (pos == lastPressPos) { U2Region rgn(pos, 1); if (rgn.startPos >=0 && rgn.endPos() <= seqLen) { setSelection(rgn); } } } } scrollBar->setupRepeatAction(QAbstractSlider::SliderNoAction); lastPressPos = -1; QWidget::mouseReleaseEvent(me); } void GSequenceLineView::mouseMoveEvent(QMouseEvent* me) { if (lastPressPos == -1) { QWidget::mouseMoveEvent(me); return; } if (me->buttons() & Qt::LeftButton) { QPoint areaPoint = toRenderAreaPoint(me->pos()); // manage scrollbar auto-scrolling if (areaPoint.x() > width()) { scrollBar->setupRepeatAction(QAbstractSlider::SliderSingleStepAdd); } else if (areaPoint.x() <= 0) { scrollBar->setupRepeatAction(QAbstractSlider::SliderSingleStepSub); } else { scrollBar->setupRepeatAction(QAbstractSlider::SliderNoAction); } // compute selection qint64 pos = renderArea->coordToPos(areaPoint.x()); qint64 selStart = qMin(lastPressPos, pos); qint64 selLen = qAbs(pos - lastPressPos); if (selStart<0) { selLen+=selStart; selStart=0; } else if (selStart + selLen > seqLen) { selLen = seqLen - selStart; } setSelection(U2Region(selStart, selLen)); } QWidget::mouseMoveEvent(me); } void GSequenceLineView::mouseDoubleClickEvent(QMouseEvent* me) { QPoint areaPoint = toRenderAreaPoint(me->pos()); if (renderArea->rect().contains(areaPoint)) { int pos = renderArea->coordToPos(areaPoint.x()); emit si_centerPosition(pos); } QWidget::mouseDoubleClickEvent(me); } void GSequenceLineView::keyPressEvent(QKeyEvent *e) { int key = e->key(); bool accepted = false; GSequenceLineView* view = coherentRangeView == NULL ? this : coherentRangeView; switch(key) { case Qt::Key_Left: case Qt::Key_Up: view->setStartPos(qMax(qint64(0), visibleRange.startPos - 1)); accepted = true; break; case Qt::Key_Right: case Qt::Key_Down: view->setStartPos(qMin(seqLen-1, visibleRange.startPos + 1)); accepted = true; break; case Qt::Key_Home: view->setStartPos(0); accepted = true; break; case Qt::Key_End: view->setStartPos(seqLen-1); accepted = true; break; case Qt::Key_PageUp: view->scrollBar->triggerAction(QAbstractSlider::SliderPageStepSub); accepted = true; break; case Qt::Key_PageDown: view->scrollBar->triggerAction(QAbstractSlider::SliderPageStepAdd); accepted = true; break; } if (accepted) { e->accept(); } else { QWidget::keyPressEvent(e); } } void GSequenceLineView::setCenterPos(int centerPos) { SAFE_POINT(centerPos <= seqLen && centerPos >= 0, QString("Center pos is out of sequence range! value: %1").arg(centerPos),); int newPos = qMax(qint64(0), centerPos - visibleRange.length/2); setStartPos(newPos); } void GSequenceLineView::setStartPos(int newPos) { if (newPos + visibleRange.length > seqLen) { newPos = seqLen - visibleRange.length; } if (newPos < 0) { newPos = 0; } if (visibleRange.startPos != newPos) { visibleRange.startPos = newPos; onVisibleRangeChanged(); } } void GSequenceLineView::onVisibleRangeChanged(bool signal) { addUpdateFlags(GSLV_UF_VisibleRangeChanged); updateScrollBar(); if (signal) { emit si_visibleRangeChanged(); } update(); } QPoint GSequenceLineView::toRenderAreaPoint(const QPoint& p) { assert(renderArea); return p - renderArea->pos(); } void GSequenceLineView::wheelEvent(QWheelEvent *we) { bool renderAreaWheel = QRect(renderArea->x(), renderArea->y(), renderArea->width(), renderArea->height()).contains(we->pos()); if (!renderAreaWheel) { QWidget::wheelEvent(we); return; } setFocus(); bool toMin = we->delta() > 0; if (we->modifiers() == 0) { scrollBar->triggerAction(toMin ? QAbstractSlider::SliderSingleStepSub : QAbstractSlider::SliderSingleStepAdd); } else if (we->modifiers() & Qt::SHIFT) { GSequenceLineView* moveView = coherentRangeView == NULL ? this : coherentRangeView; if (toMin && visibleRange.startPos > 0) { moveView->setStartPos(visibleRange.startPos-1); } else if (!toMin && visibleRange.endPos() < seqLen) { moveView->setStartPos(visibleRange.startPos+1); } } else if (we->modifiers() & Qt::ALT) { QAction* zoomAction = toMin ? getZoomInAction() : getZoomOutAction(); if (zoomAction != NULL) { zoomAction->activate(QAction::Trigger); } } } void GSequenceLineView::sl_onDNASelectionChanged(LRegionsSelection*, const QVector& added, const QVector& removed) { if (visibleRange.intersects(added) || visibleRange.intersects(removed)) { addUpdateFlags(GSLV_UF_SelectionChanged); update(); } } void GSequenceLineView::focusInEvent(QFocusEvent* fe) { addUpdateFlags(GSLV_UF_FocusChanged); QWidget::focusInEvent(fe); } void GSequenceLineView::focusOutEvent(QFocusEvent* fe) { addUpdateFlags(GSLV_UF_FocusChanged); QWidget::focusOutEvent(fe); } bool GSequenceLineView::eventFilter(QObject *object, QEvent *event) { if (object == frameView) { // show-hide frame on frameView show/hide event if ((isVisible() && event->type() == QEvent::Show) || event->type() == QEvent::Hide) { if (visibleRange.contains(frameView->getVisibleRange())) { addUpdateFlags(GSLV_UF_FrameChanged); update(); } } } return false; } void GSequenceLineView::setFrameView(GSequenceLineView* _frameView) { SAFE_POINT((frameView == NULL) != (_frameView==NULL), "Failed to set frame view!",); if (_frameView == NULL) { frameView->disconnect(this); frameView->removeEventFilter(this); frameView = NULL; return; } frameView = _frameView; frameView->installEventFilter(this); connect(frameView, SIGNAL(si_visibleRangeChanged()), SLOT(sl_onFrameRangeChanged())); } void GSequenceLineView::setCoherentRangeView(GSequenceLineView* _rangeView) { SAFE_POINT((coherentRangeView == NULL) != (_rangeView==NULL), "Failed to set coherent view!",); if (_rangeView == NULL) { coherentRangeView->disconnect(this); coherentRangeView = NULL; return; } coherentRangeView = _rangeView; setVisibleRange(coherentRangeView->getVisibleRange()); connect(coherentRangeView, SIGNAL(si_visibleRangeChanged()), SLOT(sl_onCoherentRangeViewRangeChanged())); } void GSequenceLineView::sl_onFrameRangeChanged() { //todo: optimize and do not redraw frame if visual coords of the frame are not changed! #ifdef _DEBUG const U2Region& newRange = frameView->getVisibleRange(); assert(newRange.startPos >= 0 && newRange.endPos() <= ctx->getSequenceObject()->getSequenceLen() && newRange.length >= 0); #endif addUpdateFlags(GSLV_UF_FrameChanged); update(); } void GSequenceLineView::sl_onCoherentRangeViewRangeChanged() { const U2Region& newRange = coherentRangeView->getVisibleRange(); if (newRange == visibleRange) { return; } setVisibleRange(newRange); } void GSequenceLineView::setVisibleRange(const U2Region& newRange, bool signal) { SAFE_POINT(newRange.startPos >=0 && newRange.endPos() <= seqLen, "Failed to update visible range. Range is out of the sequence range!",); if (newRange == visibleRange) { return; } if (featureFlags.testFlag(GSLV_FF_SupportsCustomRange)) { visibleRange = newRange; onVisibleRangeChanged(signal); } else if (newRange.startPos != visibleRange.startPos) { setStartPos(newRange.startPos); } } DNASequenceObject* GSequenceLineView::getSequenceObject() const { return ctx->getSequenceObject(); } void GSequenceLineView::completeUpdate(){ addUpdateFlags(GSLV_UF_NeedCompleteRedraw); update(); } void GSequenceLineView::sl_sequenceChanged(){ updateScrollBar(); completeUpdate(); } const U2Region& GSequenceLineView::getSequenceRange() const { return ctx->getSequenceObject()->getSequenceRange(); } ////////////////////////////////////////////////////////////////////////// /// GSequenceLineViewRenderArea GSequenceLineViewRenderArea::GSequenceLineViewRenderArea(GSequenceLineView* v) : QWidget(v) { view = v; cachedView = new QPixmap(); sequenceFont.setFamily("Courier New"); sequenceFont.setPointSize(12); smallSequenceFont.setFamily("Courier New"); smallSequenceFont.setPointSize(8); rulerFont.setFamily("Arial"); rulerFont.setPointSize(8); updateFontMetrics(); } GSequenceLineViewRenderArea::~GSequenceLineViewRenderArea() { delete cachedView; } void GSequenceLineViewRenderArea::updateFontMetrics() { QFontMetrics fm(sequenceFont); yCharOffset = 4; lineHeight = fm.boundingRect('W').height() + 2 * yCharOffset; xCharOffset = 1; charWidth = fm.boundingRect('W').width() + 2 * xCharOffset; QFontMetrics fms(smallSequenceFont); smallCharWidth = fms.boundingRect('W').width(); } void GSequenceLineViewRenderArea::drawFocus(QPainter& p) { p.setPen(QPen(Qt::black, 1, Qt::DotLine)); p.drawRect(0, 0, width()-1, height()-1); } void GSequenceLineViewRenderArea::drawFrame(QPainter& p) { GSequenceLineView* frameView = view->getFrameView(); if (frameView == NULL || !frameView->isVisible()) { return; } const U2Region& frameRange = frameView->getVisibleRange(); if (frameRange.length == 0) { return; } const U2Region& visibleRange = view->getVisibleRange(); U2Region visibleFrameRange = visibleRange.intersect(frameRange); if (visibleFrameRange.isEmpty()) { return; } float scale = getCurrentScale(); int xStart = (int) ( scale * (visibleFrameRange.startPos - visibleRange.startPos) ); int xLen = qMax((int)(scale * visibleFrameRange.length), 4); QPen pen(Qt::lightGray, 2, Qt::DashLine); p.setPen(pen); p.drawRect(xStart, 0, xLen, height()); } void GSequenceLineViewRenderArea::paintEvent(QPaintEvent *e) { QSize cachedViewSize = cachedView->size(); QSize currentSize = size(); if (cachedViewSize != currentSize) { assert(view->getUpdateFlags().testFlag(GSLV_UF_ViewResized)==true); delete cachedView; cachedView = new QPixmap(currentSize); } drawAll(this); view->clearUpdateFlags(); QWidget::paintEvent(e); } float GSequenceLineViewRenderArea::getCurrentScale() const { return float(width()) / view->getVisibleRange().length; } int GSequenceLineViewRenderArea::coordToPos(int _x) const { int x = qBound(0, _x, width()); const U2Region& vr = view->getVisibleRange(); float scale = getCurrentScale(); int pos = vr.startPos + int(x/scale+0.5f); assert(pos >= vr.startPos && pos <= vr.endPos()); return pos; } float GSequenceLineViewRenderArea::posToCoordF(int p, bool useVirtualSpace) const { const U2Region& visibleRange = view->getVisibleRange(); if (!useVirtualSpace && !visibleRange.contains(p) && p!=visibleRange.endPos()) { return -1; } float res = ((p - visibleRange.startPos) * getCurrentScale()); int w = width(); assert(useVirtualSpace || qRound(res) <= w); Q_UNUSED(w); return res; } int GSequenceLineViewRenderArea::posToCoord(int p, bool useVirtualSpace) const { return qRound(posToCoordF(p, useVirtualSpace)); } } //namespace ugene-1.9.8/src/corelibs/U2View/src/util_ov_annotated_dna/WindowStepSelectorWidget.cpp0000644000175000017500000001320011651544334027631 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "WindowStepSelectorWidget.h" #include #include #include #include namespace U2 { ////////////////////////////////////////////////////////////////////////// // WindowStepSelectorWidget WindowStepSelectorWidget::WindowStepSelectorWidget(QWidget* p, const U2Region& winRange, int win, int step) : QWidget(p) { assert(win >= step); windowEdit = new QSpinBox(this); windowEdit->setRange(winRange.startPos, winRange.endPos()); windowEdit->setValue(win); windowEdit->setAlignment(Qt::AlignRight); stepsPerWindowEdit = new QSpinBox(this); stepsPerWindowEdit->setRange(1, winRange.endPos()); assert(win % step == 0); stepsPerWindowEdit->setValue(win/step); stepsPerWindowEdit->setAlignment(Qt::AlignRight); QFormLayout* l = new QFormLayout(this); l->addRow(tr("Window:"), windowEdit); l->addRow(tr("Steps per window:"), stepsPerWindowEdit); setLayout(l); } int WindowStepSelectorWidget::getWindow() const { assert(validate().isEmpty()); return windowEdit->value(); } int WindowStepSelectorWidget::getStep() const { assert(validate().isEmpty()); return windowEdit->value() / stepsPerWindowEdit->value(); } QString WindowStepSelectorWidget::validate() const { int win = windowEdit->value(); int stepsPerWindow = stepsPerWindowEdit->value(); if (win % stepsPerWindow !=0) { stepsPerWindowEdit->setFocus(Qt::NoFocusReason); return tr("Illegal step value"); } int step = win / stepsPerWindow; if (step > win) { stepsPerWindowEdit->setFocus(Qt::NoFocusReason); return tr("Invalid step value"); } return QString(); } ////////////////////////////////////////////////////////////////////////// /// MinMaxSelectorWidget::MinMaxSelectorWidget(QWidget* p, double min, double max, bool enabled) { Q_UNUSED(p); minmaxGroup = new QGroupBox(QString(tr("Cutoff for minimum and maximum values")), this); minmaxGroup->setCheckable(true); minmaxGroup->setChecked(enabled); //for range use min max of type minBox = new QDoubleSpinBox; minBox->setRange(INT_MIN,INT_MAX ); minBox->setValue(min); minBox->setDecimals(2); minBox->setAlignment(Qt::AlignRight); maxBox = new QDoubleSpinBox; maxBox->setRange(INT_MIN,INT_MAX); maxBox->setValue(max); maxBox->setDecimals(2); maxBox->setAlignment(Qt::AlignRight); QFormLayout* l = new QFormLayout; l->addRow(tr("Minimum:"), minBox); l->addRow(tr("Maximum:"), maxBox); minmaxGroup->setLayout(l); QVBoxLayout* mainLayout = new QVBoxLayout; mainLayout->addWidget(minmaxGroup); setLayout(mainLayout); } double MinMaxSelectorWidget::getMin() const { assert(validate().isEmpty()); return minBox->value(); } double MinMaxSelectorWidget::getMax() const { assert(validate().isEmpty()); return maxBox->value(); } bool MinMaxSelectorWidget::getState() const { assert(validate().isEmpty()); return minmaxGroup->isChecked(); } QString MinMaxSelectorWidget::validate() const { if (!minmaxGroup->isChecked()) return QString(); double min = minBox->value(); double max = maxBox->value(); if (min >= max) { minBox->setFocus(Qt::NoFocusReason); return tr("Invalid cutoff values"); } return QString(); } ////////////////////////////////////////////////////////////////////////// /// Dialog WindowStepSelectorDialog::WindowStepSelectorDialog(QWidget* p, const U2Region& winRange, int win, int step, double min, double max, bool e) : QDialog(p) { wss = new WindowStepSelectorWidget(this, winRange, win, step); mms = new MinMaxSelectorWidget(this, min, max, e); QVBoxLayout* l = new QVBoxLayout(); QHBoxLayout* buttonsLayout = new QHBoxLayout(); buttonsLayout->addStretch(10); QPushButton* cancelButton = new QPushButton(tr("Cancel"), this); QPushButton* okButton = new QPushButton(tr("Ok"), this); buttonsLayout->addWidget(okButton); buttonsLayout->addWidget(cancelButton); l->addWidget(wss); l->addWidget(mms); l->addLayout(buttonsLayout); setLayout(l); setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Minimum); setMinimumWidth(200); connect(cancelButton, SIGNAL(clicked(bool)), SLOT(sl_onCancelClicked(bool))); connect(okButton, SIGNAL(clicked(bool)), SLOT(sl_onOkClicked(bool))); okButton->setDefault(true); } void WindowStepSelectorDialog::sl_onCancelClicked(bool v) { Q_UNUSED(v); reject(); } void WindowStepSelectorDialog::sl_onOkClicked(bool v) { Q_UNUSED(v); QString err = wss->validate(); QString mmerr = mms->validate(); if (err.isEmpty() && mmerr.isEmpty()) { accept(); return; } QMessageBox::critical(this, tr("Error!"), err.append(' ').append(mmerr)); } } //namespace ugene-1.9.8/src/corelibs/U2View/src/util_ov_annotated_dna/AutoAnnotationUtils.cpp0000644000175000017500000001657611651544334026670 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include #include #include #include #include #include "ADVSequenceObjectContext.h" #include "AutoAnnotationUtils.h" namespace U2 { const QString AutoAnnotationsADVAction::ACTION_NAME("AutoAnnotationUpdateAction"); #define AUTO_ANNOTATION_GROUP_NAME "AutoAnnotatationGroupName" AutoAnnotationsADVAction::AutoAnnotationsADVAction(ADVSequenceWidget* v, AutoAnnotationObject* obj) : ADVSequenceWidgetAction(ACTION_NAME, tr("Automatic Annotations Highlighting")), aaObj(obj), updatesCount(0) { seqWidget = v; addToBar = true; menu = new QMenu(); setIcon(QIcon(":core/images/predefined_annotation_groups.png")); setMenu(menu); connect(aaObj, SIGNAL(si_updateStarted()), SLOT(sl_autoAnnotationUpdateStarted())); connect(aaObj, SIGNAL(si_updateFinshed()), SLOT(sl_autoAnnotationUpdateFinished())); updateMenu(); aaObj->update(); } void AutoAnnotationsADVAction::updateMenu() { AutoAnnotationConstraints constraints; if (seqWidget->getSequenceContexts().count() > 0) { constraints.alphabet = seqWidget->getSequenceContexts().first()->getAlphabet(); } if(seqWidget->getSequenceObjects().count() > 0){ constraints.hints = seqWidget->getSequenceObjects().first()->getGHints(); } QList updaters = AppContext::getAutoAnnotationsSupport()->getAutoAnnotationUpdaters(); if (updaters.count() == 0 ) { setEnabled(false); return; } foreach (AutoAnnotationsUpdater* updater, updaters) { QAction* toggleAction = new QAction(updater->getName(), this); toggleAction->setProperty(AUTO_ANNOTATION_GROUP_NAME, updater->getGroupName()); bool enabled = updater->checkConstraints(constraints); toggleAction->setEnabled(enabled); toggleAction->setCheckable(true); bool checked = updater->isCheckedByDefault(); toggleAction->setChecked(checked); aaObj->setGroupEnabled(updater->getGroupName(), checked); connect( toggleAction, SIGNAL(toggled(bool)), SLOT(sl_toggle(bool)) ); menu->addAction(toggleAction); } menu->update(); } void AutoAnnotationsADVAction::sl_toggle( bool toggled ) { QAction* action = qobject_cast(sender()); if (action == NULL) { return; } AutoAnnotationsUpdater* updater = AppContext::getAutoAnnotationsSupport()->findUpdaterByName(action->text()); if (updater != NULL) { QString groupName = updater->getGroupName(); aaObj->setGroupEnabled(groupName, toggled); aaObj->updateGroup(groupName); updater->setCheckedByDefault(toggled); } } AutoAnnotationsADVAction::~AutoAnnotationsADVAction() { menu->clear(); delete menu; menu = NULL; } QList AutoAnnotationsADVAction::getToggleActions() { return menu->actions(); } QAction* AutoAnnotationsADVAction::findToggleAction( const QString& groupName ) { QList toggleActions = menu->actions(); foreach(QAction* tAction, toggleActions) { if (tAction->property(AUTO_ANNOTATION_GROUP_NAME) == groupName) { return tAction; } } return NULL; } void AutoAnnotationsADVAction::addUpdaterToMenu(AutoAnnotationsUpdater* updater){ AutoAnnotationConstraints constraints; if (seqWidget->getSequenceContexts().count() > 0) { constraints.alphabet = seqWidget->getSequenceContexts().first()->getAlphabet(); } if(seqWidget->getSequenceObjects().count() > 0){ constraints.hints = seqWidget->getSequenceObjects().first()->getGHints(); } QAction* toggleAction = new QAction(updater->getName(), this); toggleAction->setProperty(AUTO_ANNOTATION_GROUP_NAME, updater->getGroupName()); bool enabled = updater->checkConstraints(constraints); toggleAction->setEnabled(enabled); toggleAction->setCheckable(true); bool checked = updater->isCheckedByDefault(); toggleAction->setChecked(checked); aaObj->setGroupEnabled(updater->getGroupName(), checked); connect( toggleAction, SIGNAL(toggled(bool)), SLOT(sl_toggle(bool)) ); menu->addAction(toggleAction); menu->update(); } void AutoAnnotationsADVAction::sl_autoAnnotationUpdateStarted() { setEnabled(false); updatesCount++; } void AutoAnnotationsADVAction::sl_autoAnnotationUpdateFinished() { updatesCount--; if (updatesCount == 0) { setEnabled(true); } } QAction* AutoAnnotationUtils::findAutoAnnotationsToggleAction( ADVSequenceObjectContext* ctx, const QString& groupName ) { foreach(ADVSequenceWidget* w, ctx->getSequenceWidgets()) { ADVSequenceWidgetAction* advAction = w->getADVSequenceWidgetAction(AutoAnnotationsADVAction::ACTION_NAME); if (advAction == NULL) { continue; } AutoAnnotationsADVAction* aaAction = qobject_cast (advAction); assert(aaAction != NULL); QList toggleActions = aaAction->getToggleActions(); foreach(QAction* tAction, toggleActions) { if (tAction->property(AUTO_ANNOTATION_GROUP_NAME) == groupName) { return tAction; } } } return NULL; } void AutoAnnotationUtils::triggerAutoAnnotationsUpdate( ADVSequenceObjectContext* ctx, const QString& aaGroupName ) { AutoAnnotationsADVAction* aaAction = findAutoAnnotationADVAction( ctx ); if (!aaAction->isEnabled()) { return; } assert(aaAction != NULL); if (aaAction) { QAction* updateAction = aaAction->findToggleAction(aaGroupName); assert (updateAction != NULL); if (!updateAction) { return; } if (!updateAction->isChecked()) { updateAction->trigger(); } else { AutoAnnotationsUpdater* updater = AppContext::getAutoAnnotationsSupport()->findUpdaterByGroupName(aaGroupName); if (updater != NULL) { aaAction->getAAObj()->updateGroup(aaGroupName); } } } } AutoAnnotationsADVAction* AutoAnnotationUtils::findAutoAnnotationADVAction( ADVSequenceObjectContext* ctx ) { foreach(ADVSequenceWidget* w, ctx->getSequenceWidgets()) { ADVSequenceWidgetAction* advAction = w->getADVSequenceWidgetAction(AutoAnnotationsADVAction::ACTION_NAME); if (advAction == NULL) { continue; } else { return qobject_cast(advAction); } } return NULL; } } //namespace ugene-1.9.8/src/corelibs/U2View/src/util_ov_annotated_dna/GSequenceGraphView.cpp0000644000175000017500000001406511651544334026367 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "GSequenceGraphView.h" #include "ADVSequenceObjectContext.h" #include "ADVSingleSequenceWidget.h" #include #include #include namespace U2 { /* TRANSLATOR U2::GSequenceGraphView */ GSequenceGraphView::GSequenceGraphView(QWidget* p, ADVSequenceObjectContext* ctx, GSequenceLineView* _baseView, const QString& _vName) : GSequenceLineView(p, ctx), baseView(_baseView), vName(_vName), graphDrawer(NULL) { assert(baseView); visualPropertiesAction = new QAction(tr("Graph settings"), this); visualPropertiesAction->setObjectName("visual_properties_action"); connect(visualPropertiesAction, SIGNAL(triggered(bool)), SLOT(sl_onShowVisualProperties(bool))); scrollBar->setDisabled(true); renderArea = new GSequenceGraphViewRA(this); visibleRange = baseView->getVisibleRange(); setCoherentRangeView(baseView); setFrameView(baseView->getFrameView()); //process double clicks as centering requests ADVSingleSequenceWidget* ssw = baseView == NULL ? NULL : qobject_cast(baseView->parentWidget()); if (ssw != NULL) { connect(this, SIGNAL(si_centerPosition(int)), ssw, SLOT(sl_onLocalCenteringRequest(int))); } pack(); } void GSequenceGraphView::setGraphDrawer(GSequenceGraphDrawer* gd) { graphDrawer = gd; update(); } void GSequenceGraphView::pack() { assert(layout() == NULL); QVBoxLayout *vLayout = new QVBoxLayout(); vLayout->setMargin(0); vLayout->setSpacing(0); vLayout->addWidget(renderArea); // use extra layout with scrollbar to have synchronized width with pan-view // in future fake-scroll-bar can be replaced with graph specific toolbar QHBoxLayout *hLayout = new QHBoxLayout(); hLayout->setMargin(0); hLayout->setSpacing(0); QScrollBar* fakeBar = new QScrollBar(Qt::Vertical, this); fakeBar->setDisabled(true); hLayout->addLayout(vLayout); hLayout->addWidget(fakeBar); setLayout(hLayout); scrollBar->setHidden(true); //todo: support mode without scrollbar at all?? setFixedHeight(140); } GSequenceGraphView::~GSequenceGraphView() { foreach(GSequenceGraphData* g, graphs) { delete g; } } void GSequenceGraphView::addGraphData(GSequenceGraphData* g) { assert(!graphs.contains(g)); graphs.append(g); } void GSequenceGraphView::buildPopupMenu(QMenu& m) { QPoint cpos = renderArea->mapFromGlobal(QCursor::pos()); if (!renderArea->rect().contains(cpos)) { return; } m.addAction(visualPropertiesAction); } void GSequenceGraphView::sl_onShowVisualProperties(bool) { graphDrawer->showSettingsDialog(); } ////////////////////////////////////////////////////////////////////////// // RA GSequenceGraphViewRA::GSequenceGraphViewRA(GSequenceGraphView* g) : GSequenceLineViewRenderArea(g) { headerFont= new QFont("Courier", 10); headerHeight = 20; } GSequenceGraphViewRA::~GSequenceGraphViewRA() { delete headerFont; } void GSequenceGraphViewRA::drawAll(QPaintDevice* pd) { //todo: use cached view here!! QPainter p(pd); p.fillRect(0, 0, pd->width(), pd->height(), Qt::white); p.setPen(Qt::black); graphRect = QRect(1, headerHeight+1, pd->width()-2, pd->height()-headerHeight-2); if (view->hasFocus()) { drawFocus(p); } gd = getGraphView()->getGSequenceGraphDrawer(); assert(gd!=NULL); drawHeader(p); const QList& graphs = getGraphView()->getGraphs(); foreach(GSequenceGraphData* d, graphs) { gd->draw(p, d, graphRect); } drawFrame(p); drawSelection(p); } void GSequenceGraphViewRA::drawHeader(QPainter& p) { p.setFont(*headerFont); const GSequenceGraphWindowData& wd = gd->getWindowData(); const U2Region& visibleRange = view->getVisibleRange(); QString text = GSequenceGraphView::tr("%1 [%2, %3], Window: %4, Step %5").arg(getGraphView()->getGraphViewName()) .arg(QString::number(visibleRange.startPos+1)).arg(QString::number(visibleRange.endPos())).arg(QString::number(wd.window)).arg(QString::number(wd.step)); QRect rect(1, 1, cachedView->width() - 2, headerHeight - 2); p.drawText(rect, Qt::AlignLeft, text); } float GSequenceGraphViewRA::getCurrentScale() const { return float(graphRect.width()) / view->getVisibleRange().length; } void GSequenceGraphViewRA::drawSelection(QPainter& p) { const QVector& selection = view->getSequenceContext()->getSequenceSelection()->getSelectedRegions(); if (selection.isEmpty()) { return; } const U2Region& visibleRange = view->getVisibleRange(); QPen pen1(Qt::darkGray, 1, Qt::SolidLine); foreach(const U2Region& r, selection) { if (!visibleRange.intersects(r)) { continue; } int x1 = graphRect.left() + qMax(0, posToCoord(r.startPos, true)); int x2 = graphRect.left() + qMin(cachedView->width(), posToCoord(r.endPos(), true)); p.setPen(pen1); if (visibleRange.contains(r.startPos)) { p.drawLine(x1, graphRect.top(), x1, graphRect.bottom()); } if (visibleRange.contains(r.endPos())) { p.drawLine(x2, graphRect.top(), x2, graphRect.bottom()); } } } } // namespace ugene-1.9.8/src/corelibs/U2View/src/util_ov_annotated_dna/AnnotatedDNAViewState.h0000644000175000017500000000325511651544334026433 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_ANNOTATED_DNA_VIEW_STATE_H_ #define _U2_ANNOTATED_DNA_VIEW_STATE_H_ #include #include #include namespace U2 { class AnnotatedDNAView; class U2VIEW_EXPORT AnnotatedDNAViewState { public: AnnotatedDNAViewState(); AnnotatedDNAViewState(const QVariantMap& _stateData) : stateData(_stateData){} static QVariantMap saveState(AnnotatedDNAView* v); bool isValid() const; void setSequenceObjects(const QList& objs, const QVector& selections); QList getSequenceObjects() const; QVector getSequenceSelections() const; QList getAnnotationObjects() const; void setAnnotationObjects(const QList& objs); QVariantMap stateData; }; } // namespace #endif ugene-1.9.8/src/corelibs/U2View/src/util_ov_annotated_dna/PanView.h0000644000175000017500000001743511651544334023715 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_PAN_VIEW_H_ #define _U2_PAN_VIEW_H_ #include "GSequenceLineViewAnnotated.h" #include "U2Misc/GraphUtils.h" #include #include #include #include namespace U2 { class PanViewRenderArea; class GScrollBar; class GObjectView; class PVRowsManager; class AnnotationTableObject; class Annotation; class RulerInfo { public: RulerInfo(): offset(0){} RulerInfo(const QString& _name, int _offset, const QColor& _color) : name(_name), offset(_offset), color(_color) {} QString name; int offset; QColor color; }; class U2VIEW_EXPORT PanView : public GSequenceLineViewAnnotated { Q_OBJECT public: class U2VIEW_EXPORT ZoomUseObject { public: ZoomUseObject(); ZoomUseObject(PanView *pv); virtual ~ZoomUseObject(); void useZoom(); void releaseZoom(); void setPanView(PanView *pv); private: bool usingZoom; PanView *panView; }; PanView(QWidget* p, ADVSequenceObjectContext* ctx); ~PanView(); const U2Region& getFrameRange() const {return frameView->getVisibleRange();} virtual QAction* getZoomInAction() const {return zoomInAction;} virtual QAction* getZoomOutAction() const {return zoomOutAction;} virtual QAction* getZoomToSelectionAction() const {return zoomToSelectionAction;} virtual QAction* getZoomToSequenceAction() const {return zoomToSequenceAction;} QToolButton* getPanViewActions() const {return panViewToolButton;} // [0..seqLen) virtual void setVisibleRange(const U2Region& reg, bool signal = true); int getSeqLen() const {return seqLen;} PVRowsManager* getRowsManager() const {return rowsManager;} virtual void setNumBasesVisible(int n); void setSyncOffset(int o); int getSyncOffset() const {return syncOffset;} QList getCustomRulers() const; void addCustomRuler(const RulerInfo& r); void removeCustomRuler(const QString& name); void removeAllCustomRulers(); QAction* getToggleMainRulerAction() const {return toggleMainRulerAction;} QAction* getToggleCustomRulersAction() const {return toggleCustomRulersAction;} void hideEvent(QHideEvent *ev); void showEvent(QShowEvent *ev); protected: virtual int getSingleStep() const {return qMax(1, int(visibleRange.length) / 10);} virtual int getPageStep() const {return qMax(1, int(visibleRange.length) / 5);} virtual void onVisibleRangeChanged(bool signal = true); virtual void pack(); virtual void registerAnnotations(const QList& l); virtual void unregisterAnnotations(const QList& l); virtual void ensureVisible(Annotation* a, int locationIdx); protected slots: virtual void sl_sequenceChanged(); void sl_onAnnotationsModified(const AnnotationModification& md); private slots: void sl_zoomInAction(); void sl_zoomOutAction(); void sl_zoomToSelection(); void sl_zoomToSequence(); void sl_onRowBarMoved(int); void sl_onRangeChangeRequest(int start, int end); virtual void sl_onDNASelectionChanged(LRegionsSelection* s, const QVector& added, const QVector& removed); virtual void sl_onAnnotationSettingsChanged(const QStringList& changedSettings); void sl_toggleMainRulerVisibility(bool visible); void sl_toggleCustomRulersVisibility(bool visible); void sl_updateRows(); signals: void si_updateRows(); public: void setSelection(const U2Region& r); void centerRow(int row); int calculateNumRowBarSteps() const; void updateActions(); void updateRows(); void updateRowBar(); void updateRAHeight(); void useZoom(); void releaseZoom(); PanViewRenderArea* getRenderArea() const; U2Region frameRange; int minNuclsPerScreen; QAction* zoomInAction; QAction* zoomOutAction; QAction* zoomToSelectionAction; QAction* zoomToSequenceAction; QAction* toggleMainRulerAction; QAction* toggleCustomRulersAction; QAction* increasePanViewHeight; QAction* decreasePanViewHeight; QAction* increase5PanViewHeight; QAction* decrease5PanViewHeight; QAction* resetAnnotations; QAction* showAllAnnotations; QToolButton* panViewToolButton; PVRowsManager* rowsManager; QScrollBar* rowBar; int syncOffset; //used by ADVSyncViewManager only int zoomUsing; }; class PanViewRenderArea : public GSequenceLineViewAnnotatedRenderArea { friend class PanView; Q_OBJECT public: PanViewRenderArea(PanView* d); bool isRowVisible(int row) const { return getRowLine(row) >= 0; } int getRowLine(int i) const; int getNumVisibleRows() const {return getFirstRowLine() + 1;} int getRowLinesOffset() const {return rowLinesOffset;} void setRowLinesOffset(int r); virtual U2Region getAnnotationYRange(Annotation* a, int region, const AnnotationSettings* as) const; bool updateNumVisibleRows(); bool canIncreaseLines(); bool canDecreaseLines(); bool isAllLinesShown(); bool isDefaultSize(); protected: virtual void drawAll(QPaintDevice* pd); virtual void drawAnnotations(QPainter& p); virtual void drawSequence(QPainter& p); private slots: void sl_increaseLines(); void sl_decreaseLines(); void sl_increase5Lines(); void sl_decrease5Lines(); void sl_resetToDefault(); void sl_maxLines(bool); private: int getSelectionLine() const {return numLines - 1;} int getRulerLine() const { assert(showMainRuler); return numLines - 2; } int getCustomRulerLine(int n) const { assert(showCustomRulers); assert(n >= 0 && n < customRulers.count()); return numLines - (showMainRuler ? 3 : 2) - n; } int getFirstRowLine()const {return numLines - 2 - (showMainRuler ? 1 : 0) - (showCustomRulers ? customRulers.count() : 0 );} bool isSequenceCharsVisible() const; PanView* getPanView() const {return (PanView*)view;} int getLineY(int line) const { return cachedView->height() - ((numLines - line) * lineHeight); } void drawRuler(GraphUtils::RulerConfig c, QPainter& p, const U2Region &visibleRange, int firstCharCenter, int firstLastWidth); void drawCustomRulers(GraphUtils::RulerConfig c, QPainter& p, const U2Region &visibleRange, int firstCharCenter); void drawSequenceSelection(QPainter& p); PanView* panView; int numLines; // number of visible lines int rowLinesOffset; // row number on the first row line bool showAllLines; bool showMainRuler; bool showCustomRulers; bool fromActions; bool defaultRows; QList customRulers; }; }//namespace; #endif ugene-1.9.8/src/corelibs/U2View/src/util_ov_annotated_dna/AnnotationsTreeView.cpp0000644000175000017500000024332011651544334026641 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "AnnotationsTreeView.h" #include "AnnotatedDNAView.h" #include "ADVConstants.h" #include "ADVSequenceObjectContext.h" #include "EditAnnotationDialogController.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include /* TRANSLATOR U2::AnnotationsTreeView */ namespace U2 { class TreeSorter { public: TreeSorter(AnnotationsTreeView* t) : w(t) { w->setSortingEnabled(false); } virtual ~TreeSorter() { w->setSortingEnabled(true); } AnnotationsTreeView* w; }; #define SETTINGS_ROOT QString("view_adv/annotations_tree_view/") #define COLUMN_SIZES QString("columnSizes") const QString AnnotationsTreeView::annotationMimeType = "application/x-annotations-and-groups"; AnnotationsTreeView::AnnotationsTreeView(AnnotatedDNAView* _ctx) : ctx(_ctx){ lastMB = Qt::NoButton; lastClickedColumn = 0; tree = new QTreeWidget(this); tree->setObjectName("annotations_tree_widget"); tree->setSortingEnabled(true); tree->sortItems(0, Qt::AscendingOrder); tree->setColumnCount(2); headerLabels << tr("Name") << tr("Value"); tree->setHeaderLabels(headerLabels); tree->setUniformRowHeights(true); tree->setSelectionMode(QAbstractItemView::ExtendedSelection); tree->viewport()->installEventFilter(this); tree->setMouseTracking(true); tree->setAutoScroll(false); connect(tree, SIGNAL(itemEntered(QTreeWidgetItem*, int)), SLOT(sl_itemEntered(QTreeWidgetItem*, int))); connect(tree, SIGNAL(itemClicked(QTreeWidgetItem*, int)), SLOT(sl_itemClicked(QTreeWidgetItem*, int))); connect(tree, SIGNAL(itemDoubleClicked(QTreeWidgetItem*, int)), SLOT(sl_itemDoubleClicked(QTreeWidgetItem*, int))); connect(tree, SIGNAL(itemExpanded(QTreeWidgetItem*)), SLOT(sl_itemExpanded(QTreeWidgetItem*))); //connect(tree, SIGNAL(itemActivated(QTreeWidgetItem*, int)), SLOT(sl_itemActivated(QTreeWidgetItem*, int))); QVBoxLayout *layout = new QVBoxLayout(); layout->setMargin(0); layout->addWidget(tree); setLayout(layout); restoreWidgetState(); connect(ctx, SIGNAL(si_buildPopupMenu(GObjectView*, QMenu*)), SLOT(sl_onBuildPopupMenu(GObjectView*, QMenu*))); connect(ctx, SIGNAL(si_annotationObjectAdded(AnnotationTableObject*)), SLOT(sl_onAnnotationObjectAdded(AnnotationTableObject*))); connect(ctx, SIGNAL(si_annotationObjectRemoved(AnnotationTableObject*)), SLOT(sl_onAnnotationObjectRemoved(AnnotationTableObject*))); QList aObjs = ctx->getAnnotationObjects(true); foreach(AnnotationTableObject* obj, aObjs) { sl_onAnnotationObjectAdded(obj); } connectAnnotationSelection(); connectAnnotationGroupSelection(); connect(tree, SIGNAL(itemSelectionChanged()), SLOT(sl_onItemSelectionChanged())); connect(AppContext::getAnnotationsSettingsRegistry(), SIGNAL(si_annotationSettingsChanged(const QStringList&)), SLOT(sl_onAnnotationSettingsChanged(const QStringList&))); #define SORT_INTERVAL 500 sortTimer.setInterval(SORT_INTERVAL); sortTimer.setSingleShot(true); connect(&sortTimer, SIGNAL(timeout()), SLOT(sl_sortTree())); addColumnIcon = QIcon(":core/images/add_column.png"); removeColumnIcon = QIcon(":core/images/remove_column.png"); addAnnotationObjectAction = new QAction(tr("Objects with annotations..."), this); connect(addAnnotationObjectAction, SIGNAL(triggered()), SLOT(sl_onAddAnnotationObjectToView())); removeObjectsFromViewAction = new QAction(tr("Selected objects with annotations from view"), this); removeObjectsFromViewAction->setShortcut(QKeySequence(Qt::SHIFT| Qt::Key_Delete)); removeObjectsFromViewAction->setShortcutContext(Qt::WidgetShortcut); connect(removeObjectsFromViewAction, SIGNAL(triggered()), SLOT(sl_removeObjectFromView())); tree->addAction(removeObjectsFromViewAction); removeAnnsAndQsAction = new QAction(tr("Selected annotations and qualifiers"), this); removeAnnsAndQsAction->setShortcut(QKeySequence(Qt::Key_Delete)); removeAnnsAndQsAction->setShortcutContext(Qt::WindowShortcut); connect(removeAnnsAndQsAction, SIGNAL(triggered()), SLOT(sl_removeAnnsAndQs())); tree->addAction(removeAnnsAndQsAction); copyQualifierAction = new QAction(tr("Copy qualifier text"), this); connect(copyQualifierAction, SIGNAL(triggered()), SLOT(sl_onCopyQualifierValue())); copyQualifierURLAction = new QAction(tr("Copy qualifier URL"), this); connect(copyQualifierURLAction, SIGNAL(triggered()), SLOT(sl_onCopyQualifierURL())); toggleQualifierColumnAction = new QAction(tr("Toggle column"), this); connect(toggleQualifierColumnAction, SIGNAL(triggered()), SLOT(sl_onToggleQualifierColumn())); removeColumnByHeaderClickAction = new QAction(tr("Hide column"), this); removeColumnByHeaderClickAction->setIcon(removeColumnIcon); connect(removeColumnByHeaderClickAction, SIGNAL(triggered()), SLOT(sl_onRemoveColumnByHeaderClick())); copyColumnTextAction = new QAction(tr("Copy column text"), this); connect(copyColumnTextAction, SIGNAL(triggered()), SLOT(sl_onCopyColumnText())); copyColumnURLAction = new QAction(tr("copy column URL"), this); connect(copyColumnURLAction, SIGNAL(triggered()), SLOT(sl_onCopyColumnURL())); renameAction = new QAction(tr("Edit item"), this); renameAction->setShortcut(QKeySequence(Qt::Key_F2)); renameAction->setShortcutContext(Qt::WidgetShortcut); connect(renameAction, SIGNAL(triggered()), SLOT(sl_rename())); tree->addAction(renameAction); editAction = new QAction(tr("Edit qualifier"), this); editAction->setShortcut(QKeySequence(Qt::Key_F4)); editAction->setShortcutContext(Qt::WidgetShortcut); connect(editAction, SIGNAL(triggered()), SLOT(sl_edit())); tree->addAction(editAction); viewAction = new QAction(tr("View qualifier"), this); viewAction->setShortcut(QKeySequence(Qt::Key_F3)); viewAction->setShortcutContext(Qt::WidgetShortcut); connect(viewAction, SIGNAL(triggered()), SLOT(sl_edit())); tree->addAction(viewAction); addQualifierAction = new QAction(tr("Qualifier..."), this); addQualifierAction->setShortcut(QKeySequence(Qt::Key_Insert)); addQualifierAction->setShortcutContext(Qt::WindowShortcut); connect(addQualifierAction, SIGNAL(triggered()), SLOT(sl_addQualifier())); tree->addAction(addQualifierAction); /* cutAnnotationsAction = new QAction(tr("cut_annotations"), this); // cutAnnotationsAction->setShortcut(QKeySequence(Qt::K)); connect(cutAnnotationsAction, SIGNAL(triggered()), SLOT(sl_cutAnnotations)); tree->addAction(cutAnnotationsAction); copyAnnotationsAction = new QAction(tr("copy_annotations"), this); // copyAnnotationsAction->setShortcut(QKeySequence(Qt::K)); connect(copyAnnotationsAction, SIGNAL(triggered()), SLOT(sl_copyAnnotations)); tree->addAction(copyAnnotationsAction); pasteAnnotationsAction = new QAction(tr("paste_annotations"), this); // pasteAnnotationsAction->setShortcut(QKeySequence(Qt::K)); connect(pasteAnnotationsAction, SIGNAL(triggered()), SLOT(sl_pasteAnnotations)); tree->addAction(pasteAnnotationsAction);*/ updateState(); isDragging = false; resetDragAndDropData(); tree->setAcceptDrops(true); } void AnnotationsTreeView::restoreWidgetState() { QStringList geom = AppContext::getSettings()->getValue(SETTINGS_ROOT + COLUMN_SIZES, QStringList()).toStringList(); if (geom.isEmpty()) { tree->setColumnWidth(0, 300); tree->setColumnWidth(1, 300); } else { for (int i=0;isetColumnWidth(i, width); } } } } void AnnotationsTreeView::saveWidgetState() { QStringList geom; for (int i=0; i < tree->columnCount(); i++) { QString s = QString::number(tree->columnWidth(i)); geom.append(s); } AppContext::getSettings()->setValue(SETTINGS_ROOT+COLUMN_SIZES, geom); } AVGroupItem* AnnotationsTreeView::findGroupItem(const AnnotationGroup* g) const { GTIMER(c2,t2,"AnnotationsTreeView::findGroupItem"); if (g->getParentGroup() == NULL) { for (int i=0, n = tree->topLevelItemCount(); i(tree->topLevelItem(i)); assert(item->type == AVItemType_Group); AVGroupItem* groupItem = static_cast(item); if (groupItem->group == g) { return groupItem; } } } else { AVGroupItem* parentGroupItem = findGroupItem(g->getParentGroup()); if (parentGroupItem != NULL) { for(int i = 0, n = parentGroupItem->childCount(); i < n; i++) { AVItem* item = static_cast(parentGroupItem->child(i)); if (item->type != AVItemType_Group) { continue; } AVGroupItem* gItem = static_cast(item); if (gItem->group == g) { return gItem; } } } } return NULL; } AVAnnotationItem* AnnotationsTreeView::findAnnotationItem(const AVGroupItem* groupItem, const Annotation* a) const { GTIMER(c2,t2,"AnnotationsTreeView::findAnnotationItem"); for(int i = 0, n = groupItem->childCount(); i < n; i++) { AVItem* item = static_cast(groupItem->child(i)); if (item->type != AVItemType_Annotation) { continue; } AVAnnotationItem* aItem = static_cast(item); if (aItem->annotation == a) { return aItem; } } return NULL; } AVAnnotationItem* AnnotationsTreeView::findAnnotationItem(const AnnotationGroup* g, const Annotation* a) const { AVGroupItem* groupItem = findGroupItem(g); if (groupItem == NULL) { return NULL; } return findAnnotationItem(groupItem, a); } /** This method is optimized to use annotation groups. So can only be used for annotations that belongs to some object */ QList AnnotationsTreeView::findAnnotationItems(const Annotation* a) const { assert(a->getGObject() != NULL && ctx->getAnnotationObjects(true).contains(a->getGObject())); QList res; foreach(AnnotationGroup* g, a->getGroups()) { AVGroupItem* gItem = findGroupItem(g); AVAnnotationItem* aItem = findAnnotationItem(gItem, a); res.append(aItem); } return res; } void AnnotationsTreeView::connectAnnotationSelection() { connect(ctx->getAnnotationsSelection(), SIGNAL(si_selectionChanged(AnnotationSelection*, const QList&, const QList& )), SLOT(sl_onAnnotationSelectionChanged(AnnotationSelection*, const QList&, const QList&))); } void AnnotationsTreeView::connectAnnotationGroupSelection() { connect(ctx->getAnnotationsGroupSelection(), SIGNAL(si_selectionChanged(AnnotationGroupSelection*, const QList&, const QList& )), SLOT(sl_onAnnotationGroupSelectionChanged(AnnotationGroupSelection*, const QList&, const QList&))); } void AnnotationsTreeView::sl_onItemSelectionChanged() { AnnotationSelection* as = ctx->getAnnotationsSelection(); as->disconnect(this); as->clear(); AnnotationGroupSelection* ags = ctx->getAnnotationsGroupSelection(); ags->disconnect(this); ags->clear(); QList items = tree->selectedItems(); foreach(QTreeWidgetItem* i, items) { AVItem* item = static_cast(i); if (item->type == AVItemType_Annotation) { AVAnnotationItem* aItem = static_cast(item); assert(aItem->annotation!=NULL); assert(aItem->annotation->getGObject()!=NULL); as->addToSelection(aItem->annotation); } else if (item->type == AVItemType_Group) { AVGroupItem* gItem = static_cast(item); assert(gItem->group!=NULL); ags->addToSelection(gItem->group); } } connectAnnotationSelection(); connectAnnotationGroupSelection(); updateState(); } void AnnotationsTreeView::sl_onAnnotationSelectionChanged(AnnotationSelection*, const QList& added, const QList& removed) { tree->disconnect(this, SIGNAL(sl_onItemSelectionChanged())); foreach(Annotation* a, removed) { foreach(AnnotationGroup* g, a->getGroups()) { AVAnnotationItem* item = findAnnotationItem(g, a); if (item == NULL) { continue; } if (item->isSelected()) { item->setSelected(false); } } } AVAnnotationItem* toVisible = NULL; QList selectedItems; foreach(Annotation* a, added) { foreach(AnnotationGroup* g, a->getGroups()) { AVAnnotationItem* item = findAnnotationItem(g, a); if (item == NULL) { continue; } if (!item->isSelected()) { item->setSelected(true); selectedItems.append(item); for (QTreeWidgetItem* p = item->parent(); p!=NULL; p = p->parent()) { if (!p->isExpanded()) { p->setExpanded(true); } } } toVisible = item; } } if( !selectedItems.isEmpty() ) { tree->setCurrentItem(selectedItems.first()); } connect(tree, SIGNAL(itemSelectionChanged()), SLOT(sl_onItemSelectionChanged ())); //make item visible if special conditions are met if (toVisible != NULL && added.size() == 1) { tree->scrollToItem(toVisible, QAbstractItemView::EnsureVisible); } updateState(); } void AnnotationsTreeView::sl_onAnnotationGroupSelectionChanged(AnnotationGroupSelection* s, const QList& added, const QList& removed) { Q_UNUSED(s); foreach(AnnotationGroup* g, removed) { AVGroupItem* item = findGroupItem(g); if (item->isSelected()) { item->setSelected(false); } } foreach(AnnotationGroup* g, added) { AVGroupItem* item = findGroupItem(g); if (!item->isSelected()) { item->setSelected(true); } } if (added.size() == 1) { AVGroupItem* item = findGroupItem(added.first()); tree->scrollToItem(item, QAbstractItemView::EnsureVisible); } } void AnnotationsTreeView::sl_onAnnotationObjectAdded(AnnotationTableObject* obj) { GTIMER(c2,t2,"AnnotationsTreeView::sl_onAnnotationObjectAdded"); TreeSorter ts(this); assert(findGroupItem(obj->getRootGroup()) == NULL); AVGroupItem* groupItem = buildGroupTree(NULL, obj->getRootGroup()); SAFE_POINT(groupItem != NULL, "creating AVGroupItem failed",); tree->addTopLevelItem(groupItem); connect(obj, SIGNAL(si_onAnnotationsAdded(const QList&)), SLOT(sl_onAnnotationsAdded(const QList&))); connect(obj, SIGNAL(si_onAnnotationsRemoved(const QList&)), SLOT(sl_onAnnotationsRemoved(const QList&))); connect(obj, SIGNAL(si_onAnnotationsInGroupRemoved(const QList&, AnnotationGroup*)), SLOT(sl_onAnnotationsInGroupRemoved(const QList&, AnnotationGroup*))); connect(obj, SIGNAL(si_onAnnotationModified(const AnnotationModification&)), SLOT(sl_onAnnotationModified(const AnnotationModification&))); connect(obj, SIGNAL(si_onGroupCreated(AnnotationGroup*)), SLOT(sl_onGroupCreated(AnnotationGroup*))); connect(obj, SIGNAL(si_onGroupRemoved(AnnotationGroup*, AnnotationGroup*)), SLOT(sl_onGroupRemoved(AnnotationGroup*, AnnotationGroup*))); connect(obj, SIGNAL(si_onGroupRenamed(AnnotationGroup*, const QString& )), SLOT(sl_onGroupRenamed(AnnotationGroup*, const QString& ))); connect(obj, SIGNAL(si_modifiedStateChanged()), SLOT(sl_annotationObjectModifiedStateChanged())); connect(obj, SIGNAL(si_nameChanged(const QString&)), SLOT(sl_onAnnotationObjectRenamed(const QString&))); } void AnnotationsTreeView::sl_onAnnotationObjectRemoved(AnnotationTableObject* obj) { TreeSorter ts(this); AVGroupItem* groupItem = findGroupItem(obj->getRootGroup()); // it's safe to delete NULL pointer delete groupItem; obj->disconnect(this); } void AnnotationsTreeView::sl_onAnnotationObjectRenamed(const QString&) { AnnotationTableObject* ao = qobject_cast(sender()); AVGroupItem* gi = findGroupItem(ao->getRootGroup()); SAFE_POINT(gi!=NULL, "Failed to find annotations object on rename!",); gi->updateVisual(); } void AnnotationsTreeView::sl_onAnnotationsAdded(const QList& as) { GTIMER(c1,t1,"AnnotationsTreeView::sl_onAnnotationsAdded"); TreeSorter ts(this); QSet toUpdate; foreach(Annotation* a, as) { foreach(AnnotationGroup* ag, a->getGroups()) { AVGroupItem* gi = findGroupItem(ag); if (gi!=NULL) { //if (findAnnotationItem(gi, a)== NULL) { buildAnnotationTree(gi, a); } } else { AnnotationGroup* childGroup = ag; while(true) { gi = findGroupItem(childGroup->getParentGroup()); if (gi != NULL) { break; } childGroup = childGroup->getParentGroup(); } SAFE_POINT(gi!=NULL && childGroup!=NULL, "AnnotationsTreeView::sl_onAnnotationsAdded: childGroup not found",); buildGroupTree(gi, childGroup); } assert(gi!=NULL); toUpdate.insert(gi); } } GTIMER(c2,t2,"AnnotationsTreeView::sl_onAnnotationsAdded [updateVisual]"); while (!toUpdate.isEmpty()) { AVGroupItem* i= *toUpdate.begin(); toUpdate.remove(i); i->updateVisual(); AVGroupItem* p = (AVGroupItem*)(i->parent()); if (p != NULL) { toUpdate.insert(p); } } } void AnnotationsTreeView::sl_onAnnotationsRemoved(const QList& as) { TreeSorter ts(this); tree->disconnect(this, SIGNAL(sl_onItemSelectionChanged())); AnnotationTableObject* aObj = qobject_cast(sender()); assert(aObj != NULL); AVGroupItem* groupItem = findGroupItem(aObj->getRootGroup()); QSet groupsToUpdate; foreach(Annotation* a, as) { assert(a->getGObject() == NULL); QList aItems; groupItem->findAnnotationItems(aItems, a); assert(!aItems.isEmpty()); foreach(AVAnnotationItem* ai, aItems) { groupsToUpdate.insert(static_cast(ai->parent())); delete ai; } } foreach(AVGroupItem* g, groupsToUpdate) { g->updateVisual(); } connect(tree, SIGNAL(itemSelectionChanged()), SLOT(sl_onItemSelectionChanged ())); sl_onItemSelectionChanged(); } void AnnotationsTreeView::sl_onAnnotationsInGroupRemoved(const QList& as, AnnotationGroup* group) { AnnotationTableObject* aObj = qobject_cast(sender()); RemoveItemsTask *task = new RemoveItemsTask(this, aObj, as, group); AppContext::getTaskScheduler()->registerTopLevelTask(task); } void RemoveItemsTask::prepare() { TreeSorter ts(treeView); treeView->tree->disconnect(treeView, SLOT(sl_onItemSelectionChanged())); parentGroupItem = treeView->findGroupItem(parentGroup); parentGroupItem->setExpanded(false); parentGroupItem->setDisabled(true); parentGroupItem->setFlags(parentGroupItem->flags() ^ (Qt::ItemIsSelectable | Qt::ItemIsEditable)); //flags = parentGroupItem->flags(); //parentGroupItem->setFlags(0); //AnnotationTableObject* aObj = qobject_cast(sender()); assert(aObj != NULL); } void RemoveItemsTask::run() { //AVGroupItem* groupItem = treeView->findGroupItem(aObj->getRootGroup()); qDeleteAll(parentGroupItem->takeChildren()); //delete parentGroupItem; /*foreach(Annotation* a, as) { assert(a->getGObject() == NULL); QList aItems; groupItem->findAnnotationItems(aItems, a); assert(!aItems.isEmpty()); itemsToDelete.append(aItems); }*/ } Task::ReportResult RemoveItemsTask::report() { //parentGroupItem->setFlags(flags); /*foreach(AVAnnotationItem * aItem, itemsToDelete) { (static_cast(aItem->parent()))->updateVisual(); delete aItem; }*/ /* foreach(AVGroupItem* g, groupsToUpdate) { g->updateVisual(); }*/ AVGroupItem* groupItem = treeView->findGroupItem(aObj->getRootGroup()); groupItem->updateVisual(); connect(treeView->tree, SIGNAL(itemSelectionChanged()), treeView, SLOT(sl_onItemSelectionChanged ())); treeView->sl_onItemSelectionChanged(); aObj->releaseLocker(); return ReportResult_Finished; } void AnnotationsTreeView::sl_onAnnotationModified(const AnnotationModification& md) { switch(md.type) { case AnnotationModification_NameChanged: case AnnotationModification_LocationChanged: { QList aItems = findAnnotationItems(md.annotation); assert(!aItems.isEmpty()); foreach(AVAnnotationItem* ai, aItems) { ai->updateVisual(ATVAnnUpdateFlag_BaseColumns); } } break; case AnnotationModification_QualifierRemoved: { const QualifierModification& qm = (const QualifierModification&)md; QList aItems = findAnnotationItems(qm.annotation); foreach(AVAnnotationItem* ai, aItems) { ai->removeQualifier(qm.qualifier); } } break; case AnnotationModification_QualifierAdded: { const QualifierModification& qm = (const QualifierModification&)md; QList aItems = findAnnotationItems(qm.annotation); foreach(AVAnnotationItem* ai, aItems) { if (ai->isExpanded() || ai->childCount() > 1) { //if item was expanded - add real qualifier items ai->addQualifier(qm.qualifier); } else { ai->setChildIndicatorPolicy(QTreeWidgetItem::ShowIndicator); //otherwise process indicator only } } } break; case AnnotationModification_AddedToGroup: { const AnnotationGroupModification& gmd = (const AnnotationGroupModification&)md; AVGroupItem* gi = findGroupItem(gmd.group); assert(gi!=NULL); buildAnnotationTree(gi, gmd.annotation); gi->updateVisual(); } break; case AnnotationModification_RemovedFromGroup: { const AnnotationGroupModification& gmd = (const AnnotationGroupModification&)md; AVAnnotationItem* ai = findAnnotationItem(gmd.group, gmd.annotation); AVGroupItem* gi = dynamic_cast(ai->parent()); assert(ai!=NULL); delete ai; gi->updateVisual(); } break; } } void AnnotationsTreeView::sl_onGroupCreated(AnnotationGroup* g) { AVGroupItem* pg = g->getParentGroup()== NULL ? NULL : findGroupItem(g->getParentGroup()); buildGroupTree(pg, g); pg->updateVisual(); } void AnnotationsTreeView::sl_onGroupRemoved(AnnotationGroup* parent, AnnotationGroup* g) { AVGroupItem* pg = findGroupItem(parent); if(pg == NULL) { return; } assert(parent!=NULL && pg!=NULL); for(int i = 0, n = pg->childCount(); i < n; i++) { AVItem* item = static_cast(pg->child(i)); if (item->type == AVItemType_Group && (static_cast(item))->group == g) { if (item->parent() != NULL) { item->parent()->removeChild(item); } delete item; break; } } pg->updateVisual(); } void AnnotationsTreeView::sl_onGroupRenamed(AnnotationGroup* g, const QString& oldName) { Q_UNUSED(oldName); AVGroupItem* gi = findGroupItem(g); assert(gi!=NULL); gi->updateVisual(); } AVGroupItem* AnnotationsTreeView::buildGroupTree(AVGroupItem* parentGroupItem, AnnotationGroup* g) { SAFE_POINT(g != NULL, "in AnnotationsTreeView::buildGroupTree: AnnotationGroup argument is NULL", NULL); AVGroupItem* groupItem = new AVGroupItem(this, parentGroupItem, g); const QList& subgroups = g->getSubgroups(); foreach(AnnotationGroup* subgroup, subgroups) { buildGroupTree(groupItem, subgroup); } const QList& annotations = g->getAnnotations(); foreach(Annotation* a, annotations) { buildAnnotationTree(groupItem, a); } groupItem->updateVisual(); return groupItem; } AVAnnotationItem* AnnotationsTreeView::buildAnnotationTree(AVGroupItem* parentGroup, Annotation* a) { AVAnnotationItem* annotationItem = new AVAnnotationItem(parentGroup, a); const QVector& qualifiers = a->getQualifiers(); if (!qualifiers.isEmpty()) { annotationItem->setChildIndicatorPolicy(QTreeWidgetItem::ShowIndicator); } return annotationItem; } void AnnotationsTreeView::populateAnnotationQualifiers(AVAnnotationItem* ai){ assert(ai->childIndicatorPolicy() == QTreeWidgetItem::ShowIndicator); assert(ai->childCount() == 0); const QVector& qualifiers = ai->annotation->getQualifiers(); foreach(const U2Qualifier& q, qualifiers) { AVQualifierItem* curQualifierItem = new AVQualifierItem(ai, q); Q_UNUSED(curQualifierItem); } ai->setChildIndicatorPolicy(QTreeWidgetItem::DontShowIndicatorWhenChildless); } class SettingsUpdater : public TreeWidgetVisitor { public: SettingsUpdater(const QStringList& cs) : changedSettings(cs) {} bool isChildVisitRequired(QTreeWidgetItem* ti) { AVItem* item = static_cast(ti); assert(item->type != AVItemType_Qualifier); return item->type == AVItemType_Group; //visit children only for group items } void visit(QTreeWidgetItem* ti) { AVItem* item = static_cast(ti); if (item->type == AVItemType_Group) { AVGroupItem* gi = static_cast(item); gi->updateVisual(); } else if (item->type == AVItemType_Annotation) { AVAnnotationItem* ai = static_cast(item); QString name = ai->annotation->getAnnotationName(); if (changedSettings.contains(name)) { ai->updateVisual(ATVAnnUpdateFlag_BaseColumns); } } } private: QStringList changedSettings; }; void AnnotationsTreeView::sl_onAnnotationSettingsChanged(const QStringList& changedSettings) { // first clear colors cache for changed annotations QMap& cache = AVAnnotationItem::getIconsCache(); foreach (const QString& name, changedSettings) { cache.remove(name); } // second -> update all annotations SettingsUpdater su(changedSettings); TreeWidgetUtils::visitDFS(tree, &su); } void AnnotationsTreeView::updateColumnContextActions(AVItem* item, int col) { copyColumnTextAction->setEnabled(item!=NULL && (col >= 2 || (item->type == AVItemType_Annotation && col == 1)) && !item->text(col).isEmpty()); copyColumnURLAction->setEnabled(item!=NULL && col >= 2 && item->isColumnLinked(col)); if (!copyColumnTextAction->isEnabled()) { copyColumnTextAction->setText(tr("Copy column text")); } else { QString colName; if (col >= 2) { assert(qColumns.size() > col - 2); colName = qColumns[col - 2]; copyColumnTextAction->setText(tr("Copy column '%1' text").arg(colName)); } else { AVAnnotationItem* ai = static_cast(item); copyColumnTextAction->setText(tr("Copy '%1' annotation location").arg(ai->annotation->getAnnotationName())); } } if (!copyColumnURLAction->isEnabled()) { copyColumnURLAction->setText(tr("copy column URL")); } else { assert(qColumns.size() > col - 2); QString colName = qColumns[col - 2]; copyColumnURLAction->setText(tr("Copy column '%1' URL").arg(colName)); } } void AnnotationsTreeView::sl_onBuildPopupMenu(GObjectView*, QMenu* m) { // Add actions that not depends on the point popup is called adjustMenu(m); QPoint globalPos = QCursor::pos(); QPoint treePos = tree->mapFromGlobal(globalPos); if (!tree->rect().contains(treePos)) { return; } // Check is popup is called for column header QHeaderView* header = tree->header(); QPoint headerPoint = header->mapFromGlobal(globalPos); if (header->rect().contains(headerPoint)) { int idx = header->logicalIndexAt(headerPoint); if (idx >= 2) { assert(idx - 2 < qColumns.size()); lastClickedColumn = idx; removeColumnByHeaderClickAction->setText(tr("Hide '%1' column").arg(qColumns[lastClickedColumn-2])); QAction* first = m->actions().first(); m->insertAction(first, removeColumnByHeaderClickAction); m->insertSeparator(first); } return; } //Ensure that item clicked is in the tree selection. Do not destroy multi-selection if present QList selItems = tree->selectedItems(); QPoint viewportPos = tree->viewport()->mapFromGlobal(globalPos); if (selItems.size() <= 1) { QTreeWidgetItem* item = tree->itemAt(viewportPos); if (item!=NULL) { if (selItems.size() == 1 && selItems.first()!=item) { tree->setItemSelected(selItems.first(), false); } tree->setItemSelected(item, true); } } //Update column sensitive actions that appears only in context menu selItems = tree->selectedItems(); lastClickedColumn = tree->columnAt(viewportPos.x()); updateColumnContextActions(selItems.size() == 1 ? static_cast(selItems.first()) : static_cast(NULL), lastClickedColumn); //Add active context actions to the top level menu QList contextActions; contextActions << copyQualifierAction << copyQualifierURLAction << toggleQualifierColumnAction << copyColumnTextAction << copyColumnURLAction << editAction ;// << cutAnnotationsAction << copyAnnotationsAction << pasteAnnotationsAction; QMenu* copyMenu = GUIUtils::findSubMenu(m, ADV_MENU_COPY); foreach(QAction* a, contextActions) { if (a->isEnabled()) { copyMenu->addAction(a); } } int nActive = 0; QAction* first = m->actions().first(); foreach(QAction* a, contextActions) { if (a->isEnabled()) { nActive++; m->insertAction(first, a); } } if (nActive > 0) { m->insertSeparator(first); } } void AnnotationsTreeView::adjustMenu(QMenu* m) const { QMenu* addMenu = GUIUtils::findSubMenu(m, ADV_MENU_ADD); assert(addMenu!=NULL); addMenu->addAction(addAnnotationObjectAction); addMenu->addAction(addQualifierAction); QMenu* removeMenu = GUIUtils::findSubMenu(m, ADV_MENU_REMOVE); assert(removeMenu!=NULL); removeMenu->addAction(removeObjectsFromViewAction); removeMenu->addAction(removeAnnsAndQsAction); bool enabled = false; foreach (QAction* action, removeMenu->actions()) { if (action->isEnabled()) { enabled = true; break; } } removeMenu->setEnabled(enabled); } void AnnotationsTreeView::sl_onAddAnnotationObjectToView() { ProjectTreeControllerModeSettings s; s.objectTypesToShow.append(GObjectTypes::ANNOTATION_TABLE); s.groupMode = ProjectTreeGroupMode_Flat; foreach(GObject* o, ctx->getObjects()) { s.excludeObjectList.append(o); } QList objs = ProjectTreeItemSelectorDialog::selectObjects(s, this); foreach(GObject* obj, objs) { assert(obj->getGObjectType() == GObjectTypes::ANNOTATION_TABLE); ctx->tryAddObject(obj); } } static QList selectGroupItems(const QList& items, TriState readOnly, TriState rootOnly) { QList res; foreach(QTreeWidgetItem* i, items) { AVItem* item = static_cast(i); if (item->type == AVItemType_Group) { AVGroupItem* gItem = static_cast(item); if (rootOnly != TriState_Unknown) { bool groupIsRoot = gItem->parent() == NULL; if ( (rootOnly == TriState_Yes && !groupIsRoot) || (rootOnly==TriState_No && groupIsRoot)) { continue; } } if (readOnly != TriState_Unknown) { bool groupReadOnly = gItem->isReadonly(); if ( (readOnly == TriState_Yes && !groupReadOnly) || (readOnly==TriState_No && groupReadOnly)) { continue; } } res.append(gItem); } } return res; } static QList selectAnnotationItems(const QList& items, TriState readOnly) { QList res; foreach(QTreeWidgetItem* i, items) { AVItem* item = static_cast(i); if (item->type == AVItemType_Annotation) { AVAnnotationItem* aItem = static_cast(item); if (readOnly != TriState_Unknown) { bool aReadOnly= aItem->isReadonly(); if ( (readOnly == TriState_Yes && !aReadOnly) || (readOnly==TriState_No && aReadOnly)) { continue; } } res.append(aItem); } } return res; } static QList selectQualifierItems(const QList& items, TriState readOnly) { QList res; foreach(QTreeWidgetItem* i, items) { AVItem* item = static_cast(i); if (item->type == AVItemType_Qualifier) { AVQualifierItem* qItem = static_cast(item); if (readOnly != TriState_Unknown) { bool qReadOnly= qItem->isReadonly(); if ( (readOnly == TriState_Yes && !qReadOnly) || (readOnly==TriState_No && qReadOnly)) { continue; } } res.append(qItem); } } return res; } void AnnotationsTreeView::sl_removeObjectFromView() { QList topLevelGroups = selectGroupItems(tree->selectedItems(), TriState_Unknown, TriState_Yes); QList objects; foreach(AVGroupItem* gItem, topLevelGroups) { objects.append(gItem->group->getGObject()); } foreach(GObject* obj, objects) { assert(obj->getGObjectType() == GObjectTypes::ANNOTATION_TABLE); if (AutoAnnotationsSupport::isAutoAnnotation(obj)) { continue; } ctx->removeObject(obj); } } static bool groupDepthInverseComparator(const AVGroupItem* i1, const AVGroupItem* i2) { int depth1 = i1->group->getGroupDepth(); int depth2 = i2->group->getGroupDepth(); return depth1 > depth2; } void AnnotationsTreeView::sl_removeAnnsAndQs() { //remove selected qualifiers first (cache them, since different qualifier items with equal name/val are not distinguished) QList qualifierItemsToRemove = selectQualifierItems(tree->selectedItems(), TriState_No); QVector qualsToRemove(qualifierItemsToRemove.size()); QVector qualAnnotations(qualifierItemsToRemove.size()); for(int i=0, n = qualifierItemsToRemove.size(); i(qi->parent()); qualAnnotations[i] = ai->annotation; qualsToRemove[i] = U2Qualifier(qi->qName, qi->qValue); } for(int i=0, n = qualifierItemsToRemove.size(); iremoveQualifier(q); } //remove selected annotations now QList annotationItemsToRemove = selectAnnotationItems(tree->selectedItems(), TriState_No); QMultiMap annotationsByGroup; foreach(AVAnnotationItem* aItem, annotationItemsToRemove) { assert(!aItem->annotation->getGObject()->isStateLocked()); AnnotationGroup* ag = (static_cast(aItem->parent())->group); annotationsByGroup.insert(ag, aItem->annotation); } QList agroups = annotationsByGroup.uniqueKeys(); foreach(AnnotationGroup* ag, agroups) { QList annotations = annotationsByGroup.values(ag); ag->removeAnnotations(annotations); } //now remove selected groups QList groupItemsToRemove = selectGroupItems(tree->selectedItems(), TriState_No, TriState_No); qSort(groupItemsToRemove.begin(), groupItemsToRemove.end(), groupDepthInverseComparator); //now remove all groups foreach(AVGroupItem* gi, groupItemsToRemove) { AnnotationGroup* pg = gi->group->getParentGroup(); pg->removeSubgroup(gi->group); } } void AnnotationsTreeView::updateState() { QList items = tree->selectedItems(); QList topLevelGroups = selectGroupItems(items, TriState_Unknown, TriState_Yes); bool hasAutoAnnotationObjects = false; foreach (AVGroupItem* item, topLevelGroups) { AnnotationTableObject* aObj = item->getAnnotationTableObject(); if (AutoAnnotationsSupport::isAutoAnnotation(aObj)) { hasAutoAnnotationObjects = true; break; } } removeObjectsFromViewAction->setEnabled(!topLevelGroups.isEmpty() && !hasAutoAnnotationObjects); QList nonRootModGroups = selectGroupItems(items, TriState_No, TriState_No); QList modAnnotations = selectAnnotationItems(items, TriState_No); QList modQualifiers = selectQualifierItems(items, TriState_No); removeAnnsAndQsAction->setEnabled(!nonRootModGroups.isEmpty() || !modAnnotations.isEmpty() || !modQualifiers.isEmpty()); bool hasOnly1QualifierSelected = items.size() == 1 && (static_cast(items.first()))->type == AVItemType_Qualifier; QString qName = hasOnly1QualifierSelected ? (static_cast(items.first()))->qName : QString(""); copyQualifierAction->setEnabled(hasOnly1QualifierSelected); copyQualifierAction->setText(hasOnly1QualifierSelected ? tr("Copy qualifier '%1' value").arg(qName) : tr("Copy qualifier text")); bool hasOnly1QualifierSelectedWithURL = hasOnly1QualifierSelected && (static_cast(items.first()))->isColumnLinked(1); copyQualifierURLAction->setEnabled(hasOnly1QualifierSelectedWithURL); copyQualifierURLAction->setText(hasOnly1QualifierSelectedWithURL ? tr("Copy qualifier '%1' URL").arg(qName) : tr("Copy qualifier URL")); toggleQualifierColumnAction->setEnabled(hasOnly1QualifierSelected); bool hasColumn = qColumns.contains(qName); toggleQualifierColumnAction->setText(!hasOnly1QualifierSelected ? tr("Toggle column") : (qColumns.contains(qName) ? tr("Hide '%1' column"): tr("Add '%1' column")).arg(qName)); toggleQualifierColumnAction->setIcon(hasOnly1QualifierSelected ? (hasColumn ? removeColumnIcon : addColumnIcon) : QIcon()); QTreeWidgetItem * ciBase = tree->currentItem(); AVItem* ci = static_cast(ciBase); bool editableItemSelected = items.size() == 1 && ci!=NULL && ci == items.first() && !ci->isReadonly(); renameAction->setEnabled(editableItemSelected); editAction->setEnabled(hasOnly1QualifierSelected && editableItemSelected); viewAction->setEnabled(hasOnly1QualifierSelected); bool hasEditableAnnotationContext = editableItemSelected && (ci->type == AVItemType_Annotation || ci->type == AVItemType_Qualifier); addQualifierAction->setEnabled(hasEditableAnnotationContext); } static bool isReadOnly(QTreeWidgetItem *item) { for (; item; item = item->parent()) { AVItem *itemi = dynamic_cast(item); AnnotationTableObject *obj; switch (itemi->type) { case AVItemType_Group: obj = dynamic_cast(itemi)->group->getGObject(); break; case AVItemType_Annotation: obj = dynamic_cast(itemi)->annotation->getGObject(); break; default: continue; } if (obj->isStateLocked()) return true; } return false; } void AnnotationsTreeView::resetDragAndDropData() { dndCopyOnly = false; dndSelItems.clear(); dropDestination = NULL; } bool AnnotationsTreeView::eventFilter(QObject* o, QEvent* e) { if (o != tree->viewport()) { return false; } QEvent::Type etype = e->type(); switch (etype) { case QEvent::ToolTip: { QHelpEvent* he = (QHelpEvent*)e; QPoint globalPos = he->globalPos(); QPoint viewportPos = tree->viewport()->mapFromGlobal(globalPos); QTreeWidgetItem* item = tree->itemAt(viewportPos); if (item != NULL) { AVItem* avi = static_cast(item); if (avi->type == AVItemType_Annotation) { AVAnnotationItem* ai = static_cast(avi); ADVSequenceObjectContext* sc = ctx->getSequenceContext(ai->getAnnotationTableObject()); QString tip = ai->annotation->getQualifiersTip(15, sc?sc->getSequenceObject():NULL, sc?sc->getComplementTT():NULL); if (!tip.isEmpty()) { QToolTip::showText(he->globalPos(), tip); return true; } } } return false; } case QEvent::MouseButtonRelease: lastMB = ((QMouseEvent*)e)->button(); isDragging = false; return false; case QEvent::MouseButtonPress: { QMouseEvent *me = dynamic_cast(e); if (me->modifiers() == Qt::NoModifier && me->button() == Qt::LeftButton) { QTreeWidgetItem *item = tree->itemAt(dragStartPos = me->pos()); if (item != NULL) { AVItemType type = dynamic_cast(item)->type; if (type == AVItemType_Annotation || type == AVItemType_Group) { if (!tree->selectedItems().contains(item)) { tree->setCurrentItem(item); } isDragging = true; return false; } } } isDragging = false; return false; } case QEvent::MouseMove: { QMouseEvent *me = dynamic_cast(e); if (!(me->buttons() & Qt::LeftButton) || !isDragging) { return false; } if ((me->pos() - dragStartPos).manhattanLength() < QApplication::startDragDistance()) { return true; } initiateDragAndDrop(me); return true; } case QEvent::DragEnter: { QDragEnterEvent *de = dynamic_cast(e); if (de->mimeData()->hasFormat(annotationMimeType)) { de->acceptProposedAction(); uiLog.trace("Drag enter event in Annotations view : format is OK"); return true; } uiLog.trace("Drag enter event in Annotations view : unsupported mime format!"); return false; } case QEvent::DragMove: { // update current D&D state QDragMoveEvent *de = dynamic_cast(e); if (de->mimeData()->hasFormat(annotationMimeType)) { QTreeWidgetItem *item = tree->itemAt(de->pos()); if (item == NULL) { de->ignore(); uiLog.trace("Drag event in Annotations view : invalid destination"); return true; } if (isReadOnly(item)) { de->ignore(); uiLog.trace(QString("Drag event in Annotations view : destination is read-only: %1").arg(item->text(0))); return true; } Qt::DropAction dndAction = (de->keyboardModifiers() & Qt::ShiftModifier) ? Qt::CopyAction : Qt::MoveAction; if (dndAction == Qt::MoveAction && dndCopyOnly) { de->ignore(); uiLog.trace("Drag event in Annotations view : source is read-only, can't move"); return true; } for (AVItem *itemi = dynamic_cast(item); itemi != NULL; itemi = dynamic_cast(itemi->parent())) { if (itemi->type == AVItemType_Group) { for (int i = 0, s = dndSelItems.size(); i < s; ++i) { AVItem* dndItem = dndSelItems[i]; if (dndItem == itemi) { // do not allow drop group into itself de->ignore(); uiLog.trace("Drag event in Annotations view : can't move group into itself!"); return true; } } } } if (item->parent() == NULL) { //destination is root item for (int i = 0, s = dndSelItems.size(); i < s; ++i) { AVItem* dndItem = dndSelItems[i]; if (dndItem->type == AVItemType_Annotation) { de->ignore(); // root group can't have annotations -> problem with store/load invariant.. uiLog.trace("Drag event in Annotations view : can't move annotations, destination group is not found!"); return true; } } } de->setDropAction(dndAction); de->accept(); uiLog.trace(QString("Drag event in Annotations view, status: OK, type: %1").arg(dndAction == Qt::MoveAction? "Move" : "Copy")); return true; } return false; } case QEvent::Drop: { uiLog.trace("Drop event in Annotations view"); QDropEvent *de = dynamic_cast(e); const QMimeData *mime = de->mimeData(); if (mime->hasFormat(annotationMimeType)) { QTreeWidgetItem *item = tree->itemAt(de->pos()); if (item != NULL) { AVItem *avItem= dynamic_cast(item); while (avItem != NULL && avItem->type != AVItemType_Group) { avItem = dynamic_cast(avItem->parent()); } if (avItem != NULL) { dropDestination = static_cast(avItem); if (de->keyboardModifiers() & Qt::ShiftModifier) { de->setDropAction(Qt::CopyAction); } else { de->setDropAction(Qt::MoveAction); } de->accept(); uiLog.trace(QString("Drop event in Annotations view : destination group %1").arg(dropDestination->group->getGroupPath())); } else { uiLog.trace("Drop event in Annotations view : something weird, can't derive destination group!"); } return true; } else { uiLog.trace("Drop event in Annotations view : invalid destination"); } } else { uiLog.trace("Drop event in Annotations view : unknown MIME format"); return false; } de->ignore(); return true; } default: return false; } } bool AnnotationsTreeView::initiateDragAndDrop(QMouseEvent* ) { uiLog.trace("Starting drag & drop in annotations view"); resetDragAndDropData(); // Now filter selection: keep only parent items in the items list, remove qualifiers, check if 'move' is allowed QList initialSelItems = tree->selectedItems(); // whole selection will be moved dndCopyOnly = false; // allow 'move' by default first for (int i = 0, n = initialSelItems.size(); i < n; i++) { AVItem *itemi = dynamic_cast(initialSelItems[i]); if (!dndCopyOnly && isReadOnly(itemi)) { dndCopyOnly = true; } if (itemi->type == AVItemType_Annotation) { // if annotation group is in the selection -> remove annotation from the list, it will be moved/copied automatically with group bool addItem = true; for (QTreeWidgetItem *cur = itemi->parent(); cur != NULL; cur = cur->parent()) { if (initialSelItems.contains(cur)) { addItem = false; break; } } if (addItem) { dndSelItems.append(itemi); } } else if (itemi->type == AVItemType_Qualifier) { // remove qualifiers from selection dndSelItems[i]->setSelected(false); } else { assert(itemi->type == AVItemType_Group); if (itemi->parent() == NULL) { // object level group -> add all subgroups for (int j = 0, m = itemi->childCount(); j < m; j++) { AVItem* citem = dynamic_cast(itemi->child(j)); assert(citem->type == AVItemType_Group || citem->type == AVItemType_Annotation); dndSelItems.append(citem); } } else { dndSelItems.append(itemi); } } } if (dndSelItems.isEmpty()) { resetDragAndDropData(); uiLog.trace("No items to drag & drop"); return false; } // serialize selected items : // TODO: actually we do not need it today, so skipping this step //QStringList annotationsAndGroupsRefs; QByteArray serializedReferences; serializedReferences.append(serializedReferences); // initiate dragging QMimeData* mimeData = new QMimeData(); mimeData->setData(annotationMimeType, serializedReferences); QDrag *drag = new QDrag(this); drag->setMimeData(mimeData); Qt::DropAction dndAction = drag->exec(Qt::MoveAction | Qt::CopyAction, Qt::CopyAction); if (dndAction == Qt::MoveAction || dndAction == Qt::CopyAction) { finishDragAndDrop(dndAction); } else { uiLog.trace("Drag & drop in Annotations view was ignored"); } resetDragAndDropData(); return true; } typedef QPair GroupChangeInfo; typedef QPair AnnotationDnDInfo; static void collectAnnotationDnDInfo(AnnotationGroup* ag, const QString& destGroupPath, QList& annotationsToProcess) { foreach(Annotation* a, ag->getAnnotations()) { annotationsToProcess << AnnotationDnDInfo(GroupChangeInfo(ag, destGroupPath), a); } QString newDestGroupPath = destGroupPath + "/" + ag->getGroupName(); foreach(AnnotationGroup* sag, ag->getSubgroups()) { collectAnnotationDnDInfo(sag, newDestGroupPath, annotationsToProcess); } } void AnnotationsTreeView::finishDragAndDrop(Qt::DropAction dndAction) { AnnotationTableObject* dstObject = dropDestination->getAnnotationTableObject(); QString destGroupPath = dropDestination->group->getGroupPath(); QList affectedGroups; QList affectedAnnotations; QStringList manualCreationGroups; for (int i = 0, n = dndSelItems.size(); i < n; ++i) { AVItem* selItem = dndSelItems.at(i); assert(selItem->parent()!= NULL); // we never have no top-level object items in dndSelItems if (selItem->type == AVItemType_Annotation) { AVGroupItem* fromGroupItem = dynamic_cast(selItem->parent()); AVAnnotationItem* ai = dynamic_cast(selItem); affectedAnnotations << AnnotationDnDInfo(GroupChangeInfo(fromGroupItem->group, destGroupPath), ai->annotation); } else { AVGroupItem* movedGroupItem = dynamic_cast(selItem); if (movedGroupItem->group->getParentGroup() == dropDestination->group) { continue; // can't drop group into itself } QString toGroupPath = destGroupPath + (destGroupPath.isEmpty() ? "" : "/") + movedGroupItem->group->getGroupName(); if (movedGroupItem->group->getAnnotations().isEmpty()) { //this group will not be created as part of annotation move process -> create it manually manualCreationGroups.append(toGroupPath); } collectAnnotationDnDInfo(movedGroupItem->group, toGroupPath, affectedAnnotations); affectedGroups.append(movedGroupItem->group); } } uiLog.trace(QString("Finishing drag & drop in Annotations view, affected groups: %1 , top-level annotations: %2").arg(affectedGroups.size()).arg(affectedAnnotations.size())); // Move or Copy annotation reference inside of the object foreach(const AnnotationDnDInfo& adnd, affectedAnnotations) { const QString& toGroupPath = adnd.first.second; AnnotationGroup* dstGroup = dstObject->getRootGroup()->getSubgroup(toGroupPath, true); if (dstGroup == dstObject->getRootGroup()) { // root group can't have annotations -> problem with store/load invariant.. continue; } AnnotationGroup* srcGroup = adnd.first.first; Annotation *srcAnnotation = adnd.second; Annotation* dstAnnotation = (dstObject == srcAnnotation->getGObject()) ? srcAnnotation : new Annotation(srcAnnotation->data()); bool doAdd = !dstGroup->getAnnotations().contains(dstAnnotation); bool doRemove = dndAction == Qt::MoveAction && doAdd; if (doAdd) { dstGroup->addAnnotation(dstAnnotation); } if (doRemove) { srcGroup->removeAnnotation(srcAnnotation); } } // Process groups if (dndAction == Qt::MoveAction) { foreach(AnnotationGroup* ag, affectedGroups) { ag->getParentGroup()->removeSubgroup(ag); } } // manually create empty group items foreach(const QString& path, manualCreationGroups) { dstObject->getRootGroup()->getSubgroup(path, true); } } void AnnotationsTreeView::sl_itemEntered(QTreeWidgetItem * i, int column) { AVItem* item = static_cast(i); Qt::CursorShape newShape = Qt::ArrowCursor; Qt::CursorShape currentShape = tree->cursor().shape(); if (item != NULL) { if (item->isColumnLinked(column)) { newShape = Qt::PointingHandCursor; } } if (newShape == Qt::PointingHandCursor || ((newShape == Qt::ArrowCursor && currentShape == Qt::PointingHandCursor))) { tree->setCursor(newShape); } } void AnnotationsTreeView::sl_itemDoubleClicked(QTreeWidgetItem *i, int) { AVItem* item = static_cast(i); if (item->type == AVItemType_Qualifier) { editItem(item); } } void AnnotationsTreeView::sl_itemClicked(QTreeWidgetItem * i, int column) { AVItem* item = static_cast(i); if (lastMB != Qt::LeftButton || item==NULL || !item->isColumnLinked(column)) { return; } QString fileUrl = item->getFileUrl(column); if (!fileUrl.isEmpty()) { Task* task = new LoadRemoteDocumentAndOpenViewTask(fileUrl); AppContext::getTaskScheduler()->registerTopLevelTask(task); } else { GUIUtils::runWebBrowser(item->buildLinkURL(column)); } } void AnnotationsTreeView::sl_itemExpanded(QTreeWidgetItem* qi) { AVItem* i = static_cast(qi); if (i->type != AVItemType_Annotation) { return; } AVAnnotationItem* ai = static_cast(i); if (ai->childCount() == 0 && !ai->annotation->getQualifiers().isEmpty()) { assert(ai->childIndicatorPolicy() == QTreeWidgetItem::ShowIndicator); populateAnnotationQualifiers(ai); ai->updateVisual( ATVAnnUpdateFlag_BaseColumns); } else { assert(ai->childIndicatorPolicy() == QTreeWidgetItem::DontShowIndicatorWhenChildless); } } void AnnotationsTreeView::sl_onCopyQualifierValue() { QList items = tree->selectedItems(); assert(items.size() == 1); AVItem* item = static_cast(items.first()); assert(item->type == AVItemType_Qualifier); AVQualifierItem* qi = static_cast(item); QApplication::clipboard()->setText(qi->qValue); } void AnnotationsTreeView::sl_onCopyQualifierURL() { QList items = tree->selectedItems(); assert(items.size() == 1); AVItem* item = static_cast(items.first()); if (item->isColumnLinked(1)) { QApplication::clipboard()->setText(item->buildLinkURL(1)); } } void AnnotationsTreeView::sl_onCopyColumnText() { QList items = tree->selectedItems(); assert(items.size() == 1); AVItem* item = static_cast(items.first()); QApplication::clipboard()->setText(item->text(lastClickedColumn)); } void AnnotationsTreeView::sl_onCopyColumnURL() { QList items = tree->selectedItems(); assert(items.size() == 1); AVItem* item = static_cast(items.first()); QApplication::clipboard()->setText(item->buildLinkURL(lastClickedColumn)); } void AnnotationsTreeView::sl_onToggleQualifierColumn() { QList items = tree->selectedItems(); assert(items.size() == 1); AVItem* item = static_cast(items.first()); assert(item->type == AVItemType_Qualifier); AVQualifierItem* qi = static_cast(item); if (qColumns.contains(qi->qName)) { removeQualifierColumn(qi->qName); } else { addQualifierColumn(qi->qName); } } void AnnotationsTreeView::sl_onRemoveColumnByHeaderClick() { assert(lastClickedColumn >= 2); assert(lastClickedColumn-2 <= qColumns.size()); removeQualifierColumn(qColumns[lastClickedColumn-2]); } void AnnotationsTreeView::updateAllAnnotations(ATVAnnUpdateFlags flags) { QString emptyFilter; for(int i=0; itopLevelItemCount(); i++) { AVGroupItem* gi = static_cast(tree->topLevelItem(i)); gi->updateAnnotations(emptyFilter, flags); } } void AnnotationsTreeView::addQualifierColumn(const QString& q) { TreeSorter ts(this); qColumns.append(q); int nColumns = headerLabels.size() + qColumns.size(); tree->setColumnCount(nColumns); tree->setHeaderLabels(headerLabels + qColumns); tree->setColumnWidth(nColumns-2, nColumns - 2 == 1 ? 200 : 100); updateAllAnnotations(ATVAnnUpdateFlag_QualColumns); updateState(); } void AnnotationsTreeView::removeQualifierColumn(const QString& q) { bool ok = qColumns.removeOne(q); if (!ok) { return; } TreeSorter ts(this); tree->setColumnCount(headerLabels.size() + qColumns.size()); tree->setHeaderLabels(headerLabels + qColumns); updateAllAnnotations(ATVAnnUpdateFlag_QualColumns); updateState(); } #define COLUMN_NAMES "ATV_COLUMNS" void AnnotationsTreeView::saveState(QVariantMap& map) const { map.insert(COLUMN_NAMES, QVariant(qColumns)); QStringList columns = map.value(COLUMN_NAMES).toStringList(); assert(columns == qColumns); } void AnnotationsTreeView::updateState(const QVariantMap& map) { QStringList columns = map.value(COLUMN_NAMES).toStringList(); //QByteArray geom = map.value(COLUMNS_GEOM).toByteArray(); if (columns != qColumns && !columns.isEmpty()) { TreeSorter ts(this); foreach(QString q, qColumns) { removeQualifierColumn(q); } foreach(QString q, columns) { addQualifierColumn(q); } } /*if (columns == qColumns && !geom.isEmpty()) { tree->header()->restoreState(geom); }*/ } void AnnotationsTreeView::setSortingEnabled(bool v) { if (sortTimer.isActive()) { sortTimer.stop(); } if (v) { sortTimer.start(); } else { tree->setSortingEnabled(false); } } void AnnotationsTreeView::sl_sortTree() { tree->setSortingEnabled(true); } void AnnotationsTreeView::sl_rename() { AVItem* item = static_cast(tree->currentItem()); renameItem(item); } void AnnotationsTreeView::sl_edit() { AVItem* item = static_cast(tree->currentItem()); if (item != NULL) { editItem(item); } } void AnnotationsTreeView::editItem(AVItem* item) { //warn: item could be readonly here -> used just for viewing advanced context if (item->type == AVItemType_Qualifier) { AVQualifierItem* qi = static_cast(item); AVAnnotationItem* ai = static_cast(qi->parent()); U2Qualifier q; bool ro = qi->isReadonly(); bool ok = editQualifierDialogHelper(qi, ro, q); if (!ro && ok && (q.name !=qi->qName || q.value != qi->qValue)) { Annotation* a = (static_cast(qi->parent()))->annotation; a->removeQualifier(qi->qName, qi->qValue); a->addQualifier(q); AVQualifierItem* qi = ai->findQualifierItem(q.name, q.value); tree->setCurrentItem(qi); tree->scrollToItem(qi); } } } void AnnotationsTreeView::moveDialogToItem(QTreeWidgetItem* item, QDialog& d) { if (item == NULL) { return; } tree->scrollToItem(item); //try place dialog right below or right above the item d.layout()->update(); QRect itemRect = tree->visualItemRect(item).translated(tree->viewport()->mapToGlobal(QPoint(0, 0))); QSize dialogSize = d.layout()->minimumSize(); QRect dialogRect(0, 0, dialogSize.width(), dialogSize.height() + 35); //+35 -> estimation for a title bar QRect widgetRect = rect().translated(mapToGlobal(QPoint(0, 0))); QRect finalDialogRect = dialogRect.translated(itemRect.bottomLeft()); if (!widgetRect.contains(finalDialogRect)) { finalDialogRect = dialogRect.translated(itemRect.topLeft()).translated(QPoint(0, -dialogRect.height())); } if (widgetRect.contains(finalDialogRect)) { d.move(finalDialogRect.topLeft()); } } QString AnnotationsTreeView::renameDialogHelper(AVItem* i, const QString& defText, const QString& title) { QDialog d(this); d.setWindowTitle(title); QVBoxLayout* l = new QVBoxLayout(); d.setLayout(l); QLineEdit* edit = new QLineEdit(&d); edit->setText(defText); edit->setSelection(0, defText.length()); connect(edit, SIGNAL(returnPressed()), &d, SLOT(accept())); l->addWidget(edit); moveDialogToItem(i, d); int rc = d.exec(); if (rc == QDialog::Rejected) { return defText; } return edit->text(); } bool AnnotationsTreeView::editQualifierDialogHelper(AVQualifierItem* i, bool ro, U2Qualifier& q) { EditQualifierDialog d(this, U2Qualifier(i == NULL ? "new_qualifier" : i->qName , i == NULL ? "" : i->qValue), ro, i != NULL); moveDialogToItem(i == NULL ? tree->currentItem() : i, d); int rc = d.exec(); q = d.getModifiedQualifier(); return rc == QDialog::Accepted; } void AnnotationsTreeView::renameItem(AVItem* item) { if (item->isReadonly()) { return; } if (item->type == AVItemType_Group) { AVGroupItem* gi = static_cast(item); assert(gi->group->getParentGroup()!=NULL); //not a root group QString oldName = gi->group->getGroupName(); QString newName = renameDialogHelper(item, oldName, tr("Rename group")); if (newName != oldName && AnnotationGroup::isValidGroupName(newName, false) && gi->group->getParentGroup()->getSubgroup(newName, false) == NULL) { gi->group->setGroupName(newName); gi->group->getGObject()->setModified(true); gi->updateVisual(); } } else if (item->type == AVItemType_Annotation) { AVAnnotationItem* ai = static_cast(item); QVector l = ai->annotation->getRegions(); QList soList = ctx->findRelatedSequenceContexts(ai->annotation->getGObject()); assert(soList.size() == 1); ADVSequenceObjectContext* so = soList.first(); U2Region seqRange = so->getSequenceObject()->getSequenceRange(); EditAnnotationDialogController dialog(ai->annotation, seqRange, this); moveDialogToItem(ai, dialog); int result = dialog.exec(); if(result == QDialog::Accepted){ QString newName = dialog.getName(); if (newName!=ai->annotation->getAnnotationName()) { ai->annotation->setAnnotationName(newName); QList ais = findAnnotationItems(ai->annotation); foreach(AVAnnotationItem* a, ais) { a->updateVisual(ATVAnnUpdateFlag_BaseColumns); } } U2Location location = dialog.getLocation(); if( !location->regions.isEmpty() && l != location->regions){ ai->annotation->replaceRegions(location->regions); } ai->annotation->setLocationOperator(location->op); ai->annotation->setStrand(location->strand); ai->annotation->getGObject()->setModified(true); } } else { assert(item->type == AVItemType_Qualifier); AVQualifierItem* qi = static_cast(item); AVAnnotationItem* ai = static_cast(qi->parent()); QString newName = renameDialogHelper(item, qi->qName, tr("Rename qualifier")); if (newName != qi->qName) { Annotation* a = (static_cast(qi->parent()))->annotation; QString val = qi->qValue; a->removeQualifier(qi->qName, val); a->addQualifier(newName, val); a->getGObject()->setModified(true); AVQualifierItem* qi = ai->findQualifierItem(newName, val); tree->setCurrentItem(qi); tree->scrollToItem(qi); } } } void AnnotationsTreeView::sl_addQualifier() { AVItem* item = static_cast(tree->currentItem()); if (item->isReadonly() || item->type == AVItemType_Group) { return; } U2Qualifier q; bool ok = editQualifierDialogHelper(NULL, false, q); if (ok) { assert(!q.name.isEmpty()); AVAnnotationItem* ai = item->type == AVItemType_Annotation ? static_cast(item) : static_cast(item->parent()); Annotation* a = ai->annotation; a->addQualifier(q); ai->setExpanded(true); AVQualifierItem* qi = ai->findQualifierItem(q.name, q.value); tree->setCurrentItem(qi); tree->scrollToItem(qi); } } /*void AnnotationsTreeView::sl_cutAnnotations() { QByteArray itemData; QDataStream dataStream(&itemData, QIODevice::WriteOnly); QList selItems = tree->selectedItems(); int s = selItems.size(); dataStream << true; dataStream << s; for (int i = 0; i < s; ++i) { AVItem *itemi = dynamic_cast(selItems[i]); dataStream << (itemi->type == AVItemType_Group); if (itemi->type == AVItemType_Annotation) dataStream << *dynamic_cast(itemi)->annotation->data(); else dataStream << *dynamic_cast(itemi)->group; } QMimeData *mimeData = new QMimeData; mimeData->setData(annotationMimeType, itemData); QClipboard *clipboard = QApplication::clipboard(); clipboard->setMimeData(mimeData); } void AnnotationsTreeView::sl_copyAnnotations() { QByteArray itemData; QDataStream dataStream(&itemData, QIODevice::WriteOnly); QList selItems = tree->selectedItems(); int s = selItems.size(); dataStream << false; dataStream << s; for (int i = 0; i < s; ++i) { AVItem *itemi = dynamic_cast(selItems[i]); dataStream << (itemi->type == AVItemType_Group); if (itemi->type == AVItemType_Annotation) dataStream << *dynamic_cast(itemi)->annotation->data(); else dataStream << *dynamic_cast(itemi)->group; } QMimeData *mimeData = new QMimeData; mimeData->setData(annotationMimeType, itemData); QClipboard *clipboard = QApplication::clipboard(); clipboard->setMimeData(mimeData); } void AnnotationsTreeView::sl_pasteAnnotations() { }*/ void AnnotationsTreeView::sl_annotationObjectModifiedStateChanged() { AnnotationTableObject* ao = qobject_cast(sender()); assert(ao!=NULL); AVGroupItem* gi = findGroupItem(ao->getRootGroup()); assert(gi!=NULL); gi->updateVisual(); } AVItem* AnnotationsTreeView::currentItem(){ return static_cast(tree->currentItem()); } ////////////////////////////////////////////////////////////////////////// /// Tree model bool AVItem::processLinks(const QString& qName, const QString& qValue, int col) { bool linked = false; if (qName == "db_xref") { QStringList l = qValue.split(":"); QString dbName = l[0]; QString dbId = l.size() > 1 ? l[1] : ""; DBXRefInfo info = AppContext::getDBXRefRegistry()->getRefByKey(dbName); linked = !info.url.isEmpty(); setToolTip(col, info.comment); if (linked) { setData(col, Qt::UserRole, true); } } if (linked) { QFont f = font(col); f.setUnderline(true); setFont(col, f); setForeground(col, Qt::blue); } return linked; } bool AVItem::isColumnLinked(int col) const { return data(col, Qt::UserRole).type() == QVariant::Bool; } QString AVItem::buildLinkURL(int col) const { assert(isColumnLinked(col)); QString qValue = text(col); QStringList split = qValue.split(":"); QString type = split.first(); QString id = split.size() < 2 ? QString("") : split[1]; QString url = AppContext::getDBXRefRegistry()->getRefByKey(type).url.arg(id); return url; } QString AVItem::getFileUrl(int col) const { assert(isColumnLinked(col)); QStringList split = text(col).split(":"); QString type = split.first(); QString fileUrl = AppContext::getDBXRefRegistry()->getRefByKey(type).fileUrl; if (!fileUrl.isEmpty()) { QString id = split.size() < 2 ? QString("") : split[1]; return fileUrl.arg(id); } return fileUrl; } AVGroupItem::AVGroupItem(AnnotationsTreeView* _atv, AVGroupItem* parent, AnnotationGroup* g) : AVItem(parent, AVItemType_Group), group(g), atv(_atv) { updateVisual(); } AVGroupItem::~AVGroupItem() { group = NULL; } const QIcon& AVGroupItem::getGroupIcon() { static QIcon groupIcon(":/core/images/group_green_active.png"); return groupIcon; } const QIcon& AVGroupItem::getDocumentIcon() { static QIcon groupIcon(":/core/images/gobject.png"); return groupIcon; } void AVGroupItem::updateVisual() { SAFE_POINT(group != NULL, "AVGroupItem created with NULL AnnotationGroup argument",); if (parent() == NULL) { // document item AnnotationTableObject* aobj = group->getGObject(); Document* doc = aobj->getDocument(); QString text = aobj->getGObjectName(); if (doc != NULL ) { QString docShortName = aobj->getDocument()->getName(); assert(!docShortName.isEmpty()); text = group->getGObject()->getGObjectName() + " ["+docShortName+"]"; if (aobj->isTreeItemModified()) { text+=" *"; } } setText(0, text); setIcon(0, getDocumentIcon()); GUIUtils::setMutedLnF(this, aobj->getAnnotations().count() == 0, false); } else { // usual groups with annotations int na = group->getAnnotations().size(); int ng = group->getSubgroups().size(); QString nameString = group->getGroupName() + " " + QString("(%1, %2)").arg(ng).arg(na); setText(0, nameString); setIcon(0, getGroupIcon()); // if all child items are muted -> mute this group too bool showDisabled = childCount() > 0; //empty group is not disabled for (int i = 0; i < childCount(); i++) { QTreeWidgetItem* childItem = child(i); if (!GUIUtils::isMutedLnF(childItem)) { showDisabled = false; break; } } GUIUtils::setMutedLnF(this, showDisabled, false); } } void AVGroupItem::updateAnnotations(const QString& nameFilter, ATVAnnUpdateFlags f) { bool noFilter = nameFilter.isEmpty(); for (int j = 0; j < childCount(); j++) { AVItem* item = static_cast(child(j)); if (item->type == AVItemType_Group) { AVGroupItem* level1 = static_cast(item); if (noFilter || level1->group->getGroupName() == nameFilter) { level1->updateAnnotations(nameFilter, f); } } else { assert(item->type == AVItemType_Annotation); AVAnnotationItem* aItem= static_cast(item); if (noFilter || aItem->annotation->getAnnotationName() == nameFilter) { aItem->updateVisual(f); } } } } bool AVGroupItem::isReadonly() const { //documents names are not editable GObject* obj = group->getGObject(); bool readOnly = obj->isStateLocked() || AutoAnnotationsSupport::isAutoAnnotation(obj); return group->getParentGroup() == NULL ? true : readOnly; } void AVGroupItem::findAnnotationItems(QList& result, Annotation* a) const { for (int i = 0, n = childCount(); i < n; i++) { AVItem* item = static_cast(child(i)); if (item->type == AVItemType_Group) { AVGroupItem* gi = static_cast(item); gi->findAnnotationItems(result, a); } else if (item->type == AVItemType_Annotation) { AVAnnotationItem* ai = static_cast(item); if (ai->annotation == a) { result.append(ai); } } } } AnnotationTableObject* AVGroupItem::getAnnotationTableObject() const { return group->getGObject(); } AnnotationGroup* AVGroupItem::getAnnotationGroup() const { return group; } AVAnnotationItem::AVAnnotationItem(AVGroupItem* parent, Annotation* a) : AVItem(parent, AVItemType_Annotation), annotation(a) { updateVisual(ATVAnnUpdateFlags(ATVAnnUpdateFlag_BaseColumns) | ATVAnnUpdateFlag_QualColumns); hasNumericQColumns = false; } AVAnnotationItem::~AVAnnotationItem() { annotation = NULL; } #define MAX_ICONS_CACHE_SIZE 500 QMap& AVAnnotationItem::getIconsCache() { static QMap iconsCache; return iconsCache; } void AVAnnotationItem::updateVisual(ATVAnnUpdateFlags f) { const QString& name = annotation->getAnnotationName(); const AnnotationSettings* as = AppContext::getAnnotationsSettingsRegistry()->getAnnotationSettings(name); if (f.testFlag(ATVAnnUpdateFlag_BaseColumns)) { QMap& cache = getIconsCache(); QIcon icon = cache.value(name); if (icon.isNull()) { QColor iconColor = as->visible ? as->color : Qt::lightGray; icon = GUIUtils::createSquareIcon(iconColor, 9); if (cache.size() > MAX_ICONS_CACHE_SIZE) { cache.clear(); } cache[name] = icon; } assert(!icon.isNull()); setIcon(0, icon); setText(0, annotation->getAnnotationName()); locationString = Genbank::LocationParser::buildLocationString(annotation->data()); setText(1, locationString); } if (f.testFlag(ATVAnnUpdateFlag_QualColumns)) { //setup custom qualifiers columns AnnotationsTreeView* atv = getAnnotationTreeView(); assert(atv!=NULL); const QStringList& colNames = atv->getQualifierColumnNames(); hasNumericQColumns = false; for (int i=0, n = colNames.size(); i < n ;i++) { int col = 2+i; QString colName = colNames[i]; QString colText = annotation->findFirstQualifierValue(colName); setText(2+i, colText); bool linked = processLinks(colName, colText, col); if (!linked) { bool ok = false; double d = colText.toDouble(&ok); if (ok) { setData(col, Qt::UserRole, d); hasNumericQColumns = true; } } } } GUIUtils::setMutedLnF(this, !as->visible, true); } QVariant AVAnnotationItem::data( int col, int role ) const { if (col == 1 && role == Qt::DisplayRole) { if (locationString.isEmpty()) { locationString = Genbank::LocationParser::buildLocationString(annotation->data()); } return locationString; } return QTreeWidgetItem::data(col, role); } bool AVAnnotationItem::operator<(const QTreeWidgetItem & other) const { int col = treeWidget()->sortColumn(); const AVItem& avItem = (const AVItem&)other; if (avItem.type != AVItemType_Annotation) { return text(col) < other.text(col); } const AVAnnotationItem& ai = (const AVAnnotationItem&)other; if (col == 0) { QString name1 = annotation->getAnnotationName(); QString name2 = ai.annotation->getAnnotationName(); if (name1 == name2) { // for annotations with equal names we compare locations // this allows to avoid resorting on lazy qualifier loading return annotation->getLocation()->regions[0] < ai.annotation->getLocation()->regions[0]; } return name1 < name2; } if (col == 1 || (isColumnNumeric(col) && ai.isColumnNumeric(col))) { double oval = ai.getNumericVal(col); double mval = getNumericVal(col); return mval < oval; } return text(col) < other.text(col); } bool AVAnnotationItem::isColumnNumeric(int col) const { if (col == 0) { return false; } if (col == 1) { return true; } if (!hasNumericQColumns) { return false; } return data(col, Qt::UserRole).type() == QVariant::Double; } double AVAnnotationItem::getNumericVal(int col) const { if (col == 1) { const U2Region& r = annotation->getLocation()->regions[0]; return r.startPos; } bool ok = false; double d = data(col, Qt::UserRole).toDouble(&ok); assert(ok); return d; } void AVAnnotationItem::removeQualifier(const U2Qualifier& q) { for(int i=0, n = childCount(); i < n; i++) { AVQualifierItem* qi = static_cast(child(i)); if (qi->qName == q.name && qi->qValue == q.value) { delete qi; break; } } updateVisual(ATVAnnUpdateFlag_QualColumns); } void AVAnnotationItem::addQualifier(const U2Qualifier& q) { AVQualifierItem* qi = new AVQualifierItem(this, q); Q_UNUSED(qi); updateVisual(ATVAnnUpdateFlag_QualColumns); } AVQualifierItem* AVAnnotationItem::findQualifierItem(const QString& name, const QString& val) const { for(int i=0, n = childCount(); i < n; i++) { AVQualifierItem* qi = static_cast(child(i)); if (qi->qName == name && qi->qValue == val) { return qi; } } return NULL; } AVQualifierItem::AVQualifierItem(AVAnnotationItem* parent, const U2Qualifier& q) : AVItem(parent, AVItemType_Qualifier), qName(q.name), qValue(q.value) { setText(0, qName); setText(1, qValue); processLinks(qName, qValue, 1); } }//namespace ugene-1.9.8/src/corelibs/U2View/src/util_ov_annotated_dna/AutoAnnotationUtils.h0000644000175000017500000000416411651544334026323 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_AUTO_ANNOTATION_UTILS_H_ #define _U2_AUTO_ANNOTATION_UTILS_H_ #include "ADVSingleSequenceWidget.h" namespace U2 { class MWMDIWindow; class AutoAnnotationObject; class AutoAnnotationsUpdater; class AutoAnnotationsADVAction : public ADVSequenceWidgetAction { Q_OBJECT public: AutoAnnotationsADVAction(ADVSequenceWidget* widget, AutoAnnotationObject* aaObj); ~AutoAnnotationsADVAction(); QList getToggleActions(); AutoAnnotationObject* getAAObj() {return aaObj; } QAction* findToggleAction(const QString& groupName); void addUpdaterToMenu(AutoAnnotationsUpdater* updater); static const QString ACTION_NAME; private slots: void sl_toggle(bool toggled); void sl_autoAnnotationUpdateStarted(); void sl_autoAnnotationUpdateFinished(); private: void updateMenu(); AutoAnnotationObject* aaObj; QMenu* menu; int updatesCount; }; class U2VIEW_EXPORT AutoAnnotationUtils { public: static AutoAnnotationsADVAction* findAutoAnnotationADVAction(ADVSequenceObjectContext* ctx); static QAction* findAutoAnnotationsToggleAction(ADVSequenceObjectContext* ctx, const QString& name); static void triggerAutoAnnotationsUpdate(ADVSequenceObjectContext* ctx, const QString& aaGroupName); }; } #endif // _U2_AUTO_ANNOTATION_UTILS_H_ ugene-1.9.8/src/corelibs/U2View/src/util_ov_annotated_dna/AnnotatedDNAView.h0000644000175000017500000001725111651544334025433 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_ANNOTATED_DNA_VIEW_H_ #define _U2_ANNOTATED_DNA_VIEW_H_ #include #include #include #include class QScrollArea; class QVBoxLayout; namespace U2 { class AnnotatedDNAView; class AnnotatedDNAViewState; class DNASequenceObject; class AnnotationTableObject; class GSequenceLineView; class AnnotationsTreeView; class AnnotationSelection; class AnnotationGroupSelection; class DNASequenceSelection; class Task; class ADVClipboard; class ADVSequenceWidget; class ADVSplitWidget; class ADVSequenceObjectContext; class PositionSelector; class GObjectReference; class ADVSyncViewManager; class ADVObjectHandler; class ADVGlobalAction; class AutoAnnotationObject; class AutoAnnotationsUpdater; class U2VIEW_EXPORT AnnotatedDNAView : public GObjectView { Q_OBJECT public: AnnotatedDNAView(const QString& viewName, const QList& dnaObjects); ~AnnotatedDNAView(); virtual void buildStaticToolbar(QToolBar* tb); virtual void buildStaticMenu(QMenu* n); virtual Task* updateViewTask(const QString& stateName, const QVariantMap& stateData); virtual QVariantMap saveState(); // view content const QList& getSequenceContexts() const {return seqContexts;} QList getSequenceObjectsWithContexts() const; QList getSequenceGObjectsWithContexts() const; QList getAnnotationObjects( bool includeAutoAnnotations = false) const; AnnotationSelection* getAnnotationsSelection() const {return annotationSelection;} AnnotationGroupSelection* getAnnotationsGroupSelection() const {return annotationGroupSelection;} const QList getSequenceWidgets() const {return seqViews;} virtual bool canAddObject(GObject* obj); void addSequenceWidget(ADVSequenceWidget* v); void removeSequenceWidget(ADVSequenceWidget* v); void insertWidgetIntoSplitter(ADVSplitWidget* widget); void unregisterSplitWidget(ADVSplitWidget* widget); virtual QString addObject(GObject* o); void saveWidgetState(); ADVSequenceObjectContext* getSequenceContext(AnnotationTableObject* obj) const; ADVSequenceObjectContext* getSequenceContext(DNASequenceObject*) const; ADVSequenceObjectContext* getSequenceContext(const GObjectReference& r) const; QWidget* getScrolledWidget() const {return scrolledWidget;} ADVSequenceWidget* getSequenceWidgetInFocus() const {return focusedWidget;} ADVSequenceObjectContext* getSequenceInFocus() const; QList getAllSeqContextsInFocus() const; QList findRelatedSequenceContexts(GObject* obj) const; void setFocusedSequenceWidget(ADVSequenceWidget* v); void updateState(const AnnotatedDNAViewState& s); QAction* getCreateAnnotationAction() const {return createAnnotationAction;} void addADVAction(ADVGlobalAction* a); void removeADVAction(ADVGlobalAction* a) {advActions.removeAll(a);} AnnotationsTreeView* getAnnotationsView() {return annotationsView;} void updateAutoAnnotations(); void addAutoAnnotationsUpdated(AutoAnnotationsUpdater* updater); // Tries to add object to the view. Uses GUI functions to ask user if some data if needed // Returns error message if failed. // If object is unloaded - intitiates async object loading QString tryAddObject(GObject* obj); protected: virtual QWidget* createWidget(); virtual bool onObjectRemoved(GObject* o); virtual void onObjectRenamed(GObject* obj, const QString& oldName); virtual bool eventFilter(QObject*, QEvent*); virtual void timerEvent(QTimerEvent *e); virtual bool isChildWidgetObject(GObject* o) const; virtual void addAnalyseMenu(QMenu* m); virtual void addAddMenu(QMenu* m); virtual void addExportMenu(QMenu* m); virtual void addAlignMenu(QMenu* m); virtual void addRemoveMenu(QMenu* m); virtual void addEditMenu(QMenu* m); virtual ADVSequenceWidget* findSequenceWidgetByPos(const QPoint& globalPos) const; signals: void si_sequenceAdded(ADVSequenceObjectContext* c); void si_sequenceRemoved(ADVSequenceObjectContext* c); void si_annotationObjectAdded(AnnotationTableObject* obj); void si_annotationObjectRemoved(AnnotationTableObject* obj); void si_sequenceWidgetAdded(ADVSequenceWidget* w); void si_sequenceWidgetRemoved(ADVSequenceWidget* w); void si_focusChanged(ADVSequenceWidget*, ADVSequenceWidget*); private slots: void sl_onContextMenuRequested(const QPoint & pos); void sl_onFindDialog(); void sl_onAnnotationSettings(); void sl_onPosChangeRequest(int pos); void sl_onShowPosSelectorRequest(); void sl_toggleHL(); void sl_splitterMoved(int, int); void sl_addSequencePart(); void sl_removeSequencePart(); void sl_replaceSequencePart(); void sl_sequenceModifyTaskStateChanged(); void sl_reverseSequence(); virtual void sl_onDocumentAdded(Document*); virtual void sl_onDocumentLoadedStateChanged(); virtual void sl_removeSelectedSequenceObject(); private: void updateScrollAreaHeight(); void updateMultiViewActions(); void addRelatedAnnotations(ADVSequenceObjectContext* seqCtx); void addAutoAnnotations(ADVSequenceObjectContext* seqCtx); void importDocAnnotations(Document* doc); QSplitter* mainSplitter; QScrollArea* scrollArea; QWidget* scrolledWidget; QVBoxLayout* scrolledWidgetLayout; QAction* createAnnotationAction; QAction* findDialogAction; QAction* annotationSettingsAction; QAction* posSelectorAction; QAction* toggleHLAction; QAction* posSelectorWidgetAction; QAction* addSequencePart; QAction* removeSequencePart; QAction* replaceSequencePart; QAction* removeSequenceObjectAction; QAction* reverseSequenceAction; PositionSelector* posSelector; QList seqContexts; QList annotations; QList handlers; QList advActions; QMap autoAnnotationsMap; AnnotationsTreeView* annotationsView; QList seqViews; QList splitWidgets; AnnotationSelection * annotationSelection; AnnotationGroupSelection * annotationGroupSelection; ADVClipboard* clipb; ADVSyncViewManager* syncViewManager; ADVSequenceWidget* focusedWidget; int timerId; }; }//namespace; #endif ugene-1.9.8/src/corelibs/U2View/src/util_ov_annotated_dna/AnnotationsTreeModel.h0000644000175000017500000001674511651544334026445 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _ANNOTATIONS_TREE_MODEL_H_ #define _ANNOTATIONS_TREE_MODEL_H_ //#include "AnnotationsTreeViewL.h" #include #include #include #include #include #include #include #include #include #include #include namespace U2 { ////////////////////////////////////////////////////////////////////////// /// Tree model enum AVItemTypeL { AVItemType_Group, AVItemType_Annotation, AVItemType_Qualifier }; enum ATVAnnUpdateFlag { ATVAnnUpdateFlag_BaseColumns = 0x1, ATVAnnUpdateFlag_QualColumns = 0x2 }; typedef QFlags ATVAnnUpdateFlags; class AnnotationsTreeViewL; class AVAnnotationItemL; class AVQualifierItemL; class AVItemL : public QTreeWidgetItem { public: AVItemL(QTreeWidgetItem* parent, AVItemTypeL _type) : QTreeWidgetItem(parent), type(_type) { } virtual ~AVItemL() {} const AVItemTypeL type; bool processLinks(const QString& qname, const QString& qval, int col); bool isColumnLinked(int col) const; QString buildLinkURL(int col) const; QString getFileUrl(int col) const; virtual bool isReadonly() const {assert(parent()!=NULL); return (static_cast(parent())->isReadonly());} virtual int childNumber() const {return childCount();} bool removeChildren(int position, int count); bool addChildren(int position, int count, AVItemL *item); virtual AnnotationsTreeViewL* getAnnotationTreeView() const {assert(parent()!=NULL); return (static_cast(parent())->getAnnotationTreeView());} virtual AnnotationTableObject* getAnnotationTableObject() const {assert(parent()!=NULL); return (static_cast(parent())->getAnnotationTableObject());} virtual AnnotationGroup* getAnnotationGroup() const {assert(parent()!=NULL); return (static_cast(parent())->getAnnotationGroup());} }; class AVGroupItemL : public AVItemL { public: AVGroupItemL(AnnotationsTreeViewL* atv, AVGroupItemL* parent, AnnotationGroup* g); ~AVGroupItemL(); void updateVisual(); void updateAnnotations(const QString& nameFilter, ATVAnnUpdateFlags flags); void findAnnotationItems(QList& result, Annotation* a) const; static const QIcon& getGroupIcon(); static const QIcon& getDocumentIcon(); virtual AnnotationsTreeViewL* getAnnotationTreeView() const {return atv;} virtual bool isReadonly() const; virtual AnnotationTableObject* getAnnotationTableObject() const; virtual AnnotationGroup* getAnnotationGroup() const; virtual int childNumber() const; //void changeIndexes(int i); AnnotationGroup* group; AnnotationsTreeViewL* atv; }; class AVAnnotationItemL : public AVItemL { public: AVAnnotationItemL(AVGroupItemL* parent, Annotation* a); ~AVAnnotationItemL(); Annotation* annotation; mutable QString locationString; virtual QVariant data ( int column, int role ) const; void updateVisual(ATVAnnUpdateFlags flags); virtual bool operator< ( const QTreeWidgetItem & other ) const; bool isColumnNumeric(int col) const; double getNumericVal(int col) const; virtual int childNumber() const; void removeQualifier(const U2Qualifier& q); void addQualifier(const U2Qualifier& q); AVQualifierItemL* findQualifierItem(const QString& name, const QString& val) const; static QMap& getIconsCache(); bool hasNumericQColumns; }; class AVQualifierItemL: public AVItemL { public: virtual int childNumber() const ; AVQualifierItemL(AVAnnotationItemL* parent, const U2Qualifier& q); const QString qName; const QString qValue; }; class TreeIndex { public: TreeIndex(); ~TreeIndex(); bool isExpanded(AVItemL *item); bool isExpanded(Annotation *a, AnnotationGroup *gr); bool isExpanded(AnnotationGroup *gr); void expand(QTreeWidgetItem *i); void collapse(QTreeWidgetItem *i); int getChildNumber(AnnotationTableObject * obj); void recalculate( AnnotationTableObject * obj ); int getChildNumber(AnnotationGroup *gr, int index); int getChildNumber(AnnotationGroup *gr); int findPosition(AnnotationGroup *gr); void deleteItem(Annotation *a, AnnotationGroup *gr); void deleteItem(AnnotationGroup *gr); void addItem(Annotation *a, AnnotationGroup *gr); void addItem(AnnotationGroup *gr); QString getRootGroupName(AnnotationTableObject *aobj) const; //bool *items; //std::vector items; short *indexes; int num; QMap > itemMap; }; class U2VIEW_EXPORT LazyAnnotationTreeViewModel: public QAbstractItemModel { public: LazyAnnotationTreeViewModel(QObject * parent = 0); virtual ~LazyAnnotationTreeViewModel() { delete rootItem; } virtual QVariant data ( const QModelIndex & index, int role = Qt::DisplayRole ) const; virtual int columnCount ( const QModelIndex & parent = QModelIndex() ) const; virtual int rowCount ( const QModelIndex & parent = QModelIndex() ) const; virtual QModelIndex parent ( const QModelIndex & index ) const; virtual bool removeRows ( int row, int count, const QModelIndex & parent = QModelIndex() ); virtual bool insertRows ( int row, int count, const QModelIndex & parent = QModelIndex() ); virtual bool insertColumns(int position, int columns, const QModelIndex &parent = QModelIndex()); virtual bool removeColumns(int position, int columns, const QModelIndex &parent = QModelIndex()); virtual Qt::ItemFlags flags ( const QModelIndex & index ) const; virtual bool hasChildren ( const QModelIndex & parent = QModelIndex() ) const; QModelIndex index ( int row, int column, const QModelIndex & parent = QModelIndex() ) const; QVariant headerData ( int section, Qt::Orientation orientation, int role = Qt::DisplayRole ) const; AVItemL *getItem(const QModelIndex &index) const; QModelIndex guessIndex(QTreeWidgetItem *item); int getCurrentItemInModel() const {return currentInModel;} void setColumnCount(int nCol); void setHeaderLabels(QStringList headers); //void insertToplevelItem (AVItemL *item); AVItemL *nextToAdd; bool debugFlag; private: int nCol; QStringList headers; int currentInModel; int top, bottom; int scroll; AVItemL *rootItem; QModelIndex topIndex; QModelIndex bottomIndex; }; } #endif ugene-1.9.8/src/corelibs/U2View/src/util_ov_annotated_dna/DetView.cpp0000644000175000017500000005760111651544334024245 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "DetView.h" #include "ADVSequenceObjectContext.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include namespace U2 { DetView::DetView(QWidget* p, ADVSequenceObjectContext* ctx) : GSequenceLineViewAnnotated(p, ctx) { showComplementAction = new QAction(tr("Show complement strand"), this); showComplementAction->setIcon(QIcon(":core/images/show_compl.png")); showTranslationAction = new QAction(tr("Show amino translations"), this); showTranslationAction->setIcon(QIcon(":core/images/show_trans.png")); showComplementAction->setCheckable(true); showTranslationAction->setCheckable(true); bool hasComplement = ctx->getComplementTT()!=NULL; showComplementAction->setChecked(hasComplement); bool hasAmino = ctx->getAminoTT()!=NULL; showTranslationAction->setChecked(hasAmino); connect(showComplementAction, SIGNAL(triggered(bool)), SLOT(sl_showComplementToggle(bool))); connect(showTranslationAction, SIGNAL(triggered(bool)), SLOT(sl_showTranslationToggle(bool))); assert(ctx->getSequenceObject()!=NULL); featureFlags&=!GSLV_FF_SupportsCustomRange; renderArea = new DetViewRenderArea(this); renderArea->setObjectName("render_area"); connect(ctx, SIGNAL(si_aminoTranslationChanged()), SLOT(sl_onAminoTTChanged())); connect(ctx, SIGNAL(si_translationRowsChanged()), SLOT(sl_translationRowsChanged())); connect(ctx->getSequenceGObject(), SIGNAL(si_sequenceChanged()), this, SLOT(sl_sequenceChanged())); pack(); updateActions(); } void DetView::updateSize() { DetViewRenderArea* detArea = (static_cast(renderArea)); detArea->updateSize(); setFixedHeight(layout()->minimumSize().height()); } void DetView::resizeEvent(QResizeEvent *e) { int w = width(); int charWidth = renderArea->getCharWidth(); int visibleSymbolsCount = w / charWidth; if (visibleSymbolsCount > seqLen) { visibleRange.startPos = 0; visibleRange.length = seqLen; } else { visibleRange.length = visibleSymbolsCount; if (visibleRange.endPos() > seqLen) { visibleRange.startPos = seqLen - visibleSymbolsCount; } } Q_ASSERT(visibleRange.startPos >= 0 && visibleRange.endPos()<=seqLen); GSequenceLineView::resizeEvent(e); onVisibleRangeChanged(); } void DetView::updateActions() { bool visible = isVisible(); bool hasComplement = ctx->getComplementTT()!=NULL; showComplementAction->setEnabled(hasComplement && visible); bool hasAmino = ctx->getAminoTT()!=NULL; showTranslationAction->setEnabled(hasAmino && visible); } void DetView::showEvent(QShowEvent * e) { updateActions(); GSequenceLineViewAnnotated::showEvent(e); } void DetView::hideEvent(QHideEvent * e) { updateActions(); GSequenceLineViewAnnotated::hideEvent(e); } void DetView::sl_onAminoTTChanged() { lastUpdateFlags|=GSLV_UF_NeedCompleteRedraw; update(); } DNATranslation* DetView::getComplementTT() const { return showComplementAction->isChecked() ? ctx->getComplementTT() : NULL; } DNATranslation* DetView::getAminoTT() const { return showTranslationAction->isChecked() ? ctx->getAminoTT() : NULL; } void DetView::setShowComplement(bool t) { showComplementAction->disconnect(this); showComplementAction->setChecked(t); connect(showComplementAction, SIGNAL(triggered(bool)), SLOT(sl_showComplementToggle(bool))); updateSize(); } void DetView::setShowTranslation(bool t) { showTranslationAction->disconnect(this); showTranslationAction->setChecked(t); if(!t){ getSequenceContext()->setTranslationsVisible(t); } connect(showTranslationAction, SIGNAL(triggered(bool)), SLOT(sl_showTranslationToggle(bool))); updateSize(); } void DetView::mouseReleaseEvent(QMouseEvent* me) { //click with 'alt' shift selects single base in GSingleSeqWidget; //here we adjust this behavior -> if click was done in translation line -> select 3 bases Qt::KeyboardModifiers km = QApplication::keyboardModifiers(); bool singleBaseSelectionMode = km.testFlag(Qt::AltModifier); if (me->button() == Qt::LeftButton && singleBaseSelectionMode) { QPoint areaPoint = toRenderAreaPoint(me->pos()); if ((static_cast(renderArea))->isOnTranslationsLine(areaPoint.y())) { int pos = renderArea->coordToPos(areaPoint.x()); if (pos == lastPressPos) { U2Region rgn(pos-1, 3); if (rgn.startPos >=0 && rgn.endPos() <= seqLen) { setSelection(rgn); lastPressPos=-1; } } } } GSequenceLineViewAnnotated::mouseReleaseEvent(me); } void DetView::sl_sequenceChanged(){ seqLen = ctx->getSequenceLen(); int w = width(); int charWidth = renderArea->getCharWidth(); int visibleSymbolsCount = w / charWidth; if(seqLen > visibleSymbolsCount){ if((visibleRange.length != visibleSymbolsCount) || (visibleRange.endPos() > seqLen)){ visibleRange.length = visibleSymbolsCount; if(visibleRange.endPos() > visibleSymbolsCount){ visibleRange.startPos = seqLen - visibleSymbolsCount; } onVisibleRangeChanged(true); } }else{ visibleRange.length = seqLen; onVisibleRangeChanged(true); } GSequenceLineView::sl_sequenceChanged(); } void DetView::sl_translationRowsChanged(){ QVector visibleRows = getSequenceContext()->getTranslationRowsVisibleStatus(); bool anyFrame = false; foreach(bool b, visibleRows){ anyFrame = anyFrame || b; } if(!anyFrame){ if(showTranslationAction->isChecked()){ sl_showTranslationToggle(false); } return; } if(!showTranslationAction->isChecked()){ sl_showTranslationToggle(true); } updateScrollBar(); updateSize(); completeUpdate(); } void DetView::sl_showTranslationToggle( bool v ){ showTranslationAction->setChecked(v); getSequenceContext()->setTranslationsVisible(v); updateSize(); //setShowTranslation(v); } ////////////////////////////////////////////////////////////////////////// /// render DetViewRenderArea::DetViewRenderArea(DetView* v) : GSequenceLineViewAnnotatedRenderArea(v, true) { updateSize(); } void DetViewRenderArea::updateLines() { numLines = -1; rulerLine = -1; baseLine = -1; complementLine = -1; firstDirectTransLine = -1; firstComplTransLine = -1; DetView* detView = getDetView(); if (detView->isOneLineMode()) { baseLine = 0; rulerLine = 1; numLines = 2; } else if (detView->hasComplementaryStrand() && detView->hasTranslations()) { firstDirectTransLine = 0; baseLine = 3; rulerLine = 4; complementLine = 5; firstComplTransLine = 6; numLines = 9; } else if (detView->hasComplementaryStrand()) { assert(!detView->hasTranslations()); baseLine = 0; rulerLine = 1; complementLine = 2; numLines = 3; } else { assert(!detView->hasComplementaryStrand() && detView->hasTranslations()); firstDirectTransLine = 0; baseLine = 3; rulerLine = 4; numLines = 5; } assert(numLines > 0); } U2Region DetViewRenderArea::getAnnotationYRange(Annotation* a, int region, const AnnotationSettings* as) const { bool complement = a->getStrand().isCompementary() && getDetView()->hasComplementaryStrand(); TriState aminoState = TriState_Unknown; //a->getAminoFrame(); if (aminoState == TriState_Unknown) { aminoState = as->amino ? TriState_Yes : TriState_No; } bool transl = getDetView()->hasTranslations() && aminoState == TriState_Yes; int frame = U2AnnotationUtils::getRegionFrame(view->getSequenceLen(), a->getStrand(), a->isOrder(), region, a->getRegions()); int line = -1; if (complement) { if (transl) { line = firstComplTransLine + frame; } else { line = complementLine; } } else { if (transl) { line = firstDirectTransLine + frame; } else { line = baseLine; } } assert(line!=-1); int y = getLineY(line); return U2Region(y, lineHeight); } bool DetViewRenderArea::isOnTranslationsLine(int y) const { if (firstDirectTransLine != -1) { U2Region dtr(getLineY(firstDirectTransLine), 3*lineHeight); if (dtr.contains(y)) { return true; } } if (firstComplTransLine !=-1) { U2Region ctr(getLineY(firstComplTransLine), 3*lineHeight); if (ctr.contains(y)) { return true; } } return false; } void DetViewRenderArea::drawAll(QPaintDevice* pd) { GSLV_UpdateFlags uf = view->getUpdateFlags(); bool completeRedraw = uf.testFlag(GSLV_UF_NeedCompleteRedraw) || uf.testFlag(GSLV_UF_ViewResized) || uf.testFlag(GSLV_UF_VisibleRangeChanged) || uf.testFlag(GSLV_UF_AnnotationsChanged); bool hasSelectedAnnotationInRange = isAnnotationSelectionInVisibleRange(); if (completeRedraw) { QPainter pCached(cachedView); pCached.fillRect(0, 0, pd->width(), pd->height(), Qt::white); pCached.setPen(Qt::black); drawAnnotations(pCached); drawDirect(pCached); drawComplement(pCached); drawTranslations(pCached); drawRuler(pCached); pCached.end(); } QPainter p(pd); p.drawPixmap(0, 0, *cachedView); drawAnnotationsSelection(p); if (hasSelectedAnnotationInRange) { drawDirect(p); drawComplement(p); drawTranslations(p); } drawSequenceSelection(p); if (view->hasFocus()) { drawFocus(p); } } void DetViewRenderArea::drawDirect(QPainter& p) { p.setFont(sequenceFont); p.setPen(Qt::black); const U2Region visibleRange = view->getVisibleRange(); assert(visibleRange.length * charWidth <= width()); const QByteArray& sequence = view->getSequenceContext()->getSequenceData(); const char* seq = sequence.data() + visibleRange.startPos; /// draw base line; int y = getTextY(baseLine); for(int i = 0; i < visibleRange.length; i++) { char nucl = seq[i]; p.drawText(i*charWidth + xCharOffset, y, QString(nucl)); } } void DetViewRenderArea::drawComplement(QPainter& p) { p.setFont(sequenceFont); p.setPen(Qt::black); DetView* detView = getDetView(); if (complementLine > 0) { const U2Region visibleRange = detView->getVisibleRange(); const QByteArray& sequence = detView->getSequenceContext()->getSequenceData(); const char* seq = sequence.data() + detView->getVisibleRange().startPos; DNATranslation* complTrans = detView->getComplementTT(); QByteArray map = complTrans->getOne2OneMapper(); int y = getTextY(complementLine); for(int i=0;i< visibleRange.length; i++) { char nucl = seq[i]; char complNucl = map.at(nucl); p.drawText(i*charWidth + xCharOffset, y, QString(complNucl)); } } } static QByteArray translate(DNATranslation* t, const char* seq, int seqLen) { QByteArray res(seqLen / 3, 0); int n = t->translate(seq, seqLen, res.data(), res.length()); assert(n == res.length()); Q_UNUSED(n); return res; } void DetViewRenderArea::drawTranslations(QPainter& p) { p.setFont(sequenceFont); if (firstDirectTransLine < 0 && firstComplTransLine < 0) { return; } DetView* detView = getDetView(); DNATranslation3to1Impl* aminoTable = (DNATranslation3to1Impl*)detView->getAminoTT(); assert(aminoTable!=NULL && aminoTable->isThree2One()); const QByteArray& sequence = detView->getSequenceContext()->getSequenceData(); const U2Region& visibleRange = detView->getVisibleRange(); qint64 maxUsablePos = qMin(visibleRange.endPos() + 1, qint64(sequence.length())); qint64 minUsablePos = qMax(visibleRange.startPos - 1, qint64(0)); QColor startC(0,0x99,0); QColor stopC(0x99,0,0); QFont fontB = sequenceFont; fontB.setBold(true); QFont fontI = sequenceFont; fontI.setItalic(true); QFont sequenceFontSmall = sequenceFont; sequenceFontSmall.setPointSize(sequenceFont.pointSize()-1); QFont fontBS = sequenceFontSmall; fontBS.setBold(true); QFont fontIS = sequenceFontSmall; fontIS.setItalic(true); QList annotationsInRange = detView->findAnnotationsInRange(visibleRange); {//direct translations for(int i = 0; i < 3; i++) { int indent = (visibleRange.startPos + i) % 3; int dnaStartPos = visibleRange.startPos + indent - 3; if (dnaStartPos < minUsablePos) { dnaStartPos+=3; } int dnaLen = maxUsablePos - dnaStartPos; const char* seqStart = sequence.data(); const char* dnaSeq = sequence.data() + dnaStartPos; QByteArray amino = translate(aminoTable, dnaSeq, dnaLen); int line = dnaStartPos % 3; int y = getTextY(firstDirectTransLine + line); int dx = dnaStartPos - visibleRange.startPos; for(int j = 0, n = amino.length(); j < n ; j++, dnaSeq += 3) { char amin = amino[j]; int xpos = 3 * j + 1 + dx; assert(xpos >= 0 && xpos < visibleRange.length); int x = xpos * charWidth + xCharOffset; QColor charColor; bool inAnnotation = deriveTranslationCharColor(dnaSeq - seqStart, U2Strand::Direct, annotationsInRange, charColor); if (aminoTable->isStartCodon(dnaSeq)) { p.setPen(inAnnotation ? charColor : startC); p.setFont(inAnnotation ? fontB : fontBS); } else if (aminoTable->isCodon(DNATranslationRole_Start_Alternative, dnaSeq)) { p.setPen(inAnnotation ? charColor : startC); p.setFont(inAnnotation ? fontI: fontIS); } else if (aminoTable->isStopCodon(dnaSeq)) { p.setPen(inAnnotation ? charColor : stopC); p.setFont(inAnnotation ? fontB : fontBS); } else { p.setPen(charColor); p.setFont(inAnnotation ? sequenceFont : sequenceFontSmall); } p.drawText(x, y, QString(amin)); } } } if (detView->hasComplementaryStrand()) {//reverse translations DNATranslation* complTable = detView->getComplementTT(); assert(complTable!=NULL); int seqLen = sequence.length(); int usableSize = maxUsablePos - minUsablePos; QByteArray revComplDna(usableSize, 0); complTable->translate(sequence.data() + minUsablePos, usableSize, revComplDna.data(), usableSize); TextUtils::reverse(revComplDna.data(), revComplDna.size()); for(int i = 0; i < 3; i++) { int indent = (seqLen - visibleRange.endPos() + i) % 3; int revComplStartPos = visibleRange.endPos() - indent + 3; //start of the reverse complement sequence in direct coords if (revComplStartPos > maxUsablePos) { revComplStartPos-=3; } int revComplDnaOffset = maxUsablePos - revComplStartPos; assert(revComplDnaOffset >= 0); const char* revComplData = revComplDna.constData(); const char* dnaSeq = revComplData + revComplDnaOffset; int dnaLen = revComplStartPos - minUsablePos; QByteArray amino = translate(aminoTable, dnaSeq, dnaLen); int line = (seqLen - revComplStartPos) % 3; int y = getTextY(firstComplTransLine + line); int dx = visibleRange.endPos() - revComplStartPos; for(int j = 0, n = amino.length(); j < n ; j++, dnaSeq +=3) { char amin = amino[j]; int xpos = visibleRange.length - (3 * j + 2 + dx); assert(xpos >= 0 && xpos < visibleRange.length); int x = xpos * charWidth + xCharOffset; QColor charColor; bool inAnnotation = deriveTranslationCharColor(maxUsablePos - (dnaSeq - revComplDna.constData()), U2Strand::Complementary, annotationsInRange, charColor); if (aminoTable->isStartCodon(dnaSeq)) { p.setPen(inAnnotation ? charColor : startC); p.setFont(inAnnotation ? fontB : fontBS); } else if (aminoTable->isCodon(DNATranslationRole_Start_Alternative, dnaSeq)) { p.setPen(inAnnotation ? charColor : startC); p.setFont(inAnnotation ? fontI : fontIS); } else if (aminoTable->isStopCodon(dnaSeq)) { p.setPen(inAnnotation ? charColor : stopC); p.setFont(inAnnotation ? fontB : fontBS); } else { p.setPen(charColor); p.setFont(inAnnotation ? sequenceFont : sequenceFontSmall); } p.drawText(x, y, QString(amin)); } } } p.setPen(Qt::black); p.setFont(sequenceFont); } bool DetViewRenderArea::deriveTranslationCharColor(int pos, U2Strand strand, QList annotationsInRange, QColor& result) { // logic: // no annotations found -> grey // found annotation that is on translation -> black // 1 annotation found on nucleic -> darker(annotation color) // 2+ annotations found on nucleic -> black int nAnnotations = 0; U2Region tripletRange = strand == U2Strand::Complementary ? U2Region(pos - 2, 2) : U2Region(pos, 2); AnnotationSettings* as = NULL; int sequenceLen = view->getSequenceLen(); foreach (Annotation* a, annotationsInRange) { if (a->getStrand() != strand) { continue; } bool annotationOk = false; AnnotationSettings *tas = NULL; bool order = a->isOrder(); const QVector& location = a->getRegions(); for (int i = 0, n = location.size(); i < n; i++) { const U2Region& r = location.at(i); if (!r.contains(tripletRange)) { continue; } int regionFrame = U2AnnotationUtils::getRegionFrame(sequenceLen, strand, order, i, location); int posFrame = strand == U2Strand::Complementary ? (sequenceLen - pos) % 3 : (pos % 3); if (regionFrame == posFrame) { tas = AppContext::getAnnotationsSettingsRegistry()->getAnnotationSettings(a); if (tas->visible){ annotationOk = true; break; } } } if (annotationOk) { nAnnotations++; as = tas; if (nAnnotations > 1) { break; } } } if (nAnnotations == 0) { result = Qt::gray; return false; } if (nAnnotations > 1) { result == Qt::black; return true; } TriState aminoState = TriState_Unknown; //annotation->getAminoFrame(); if (aminoState == TriState_Unknown) { aminoState = as->amino ? TriState_Yes : TriState_No; } bool aminoOverlap = aminoState == TriState_Yes; // annotation is drawn on amino strand -> use black color for letters if (aminoOverlap) { result = Qt::black; } else { result = as->color.darker(300); } return true; } void DetViewRenderArea::drawSequenceSelection(QPainter& p) { DetView* detView = getDetView(); DNASequenceSelection* sel = detView->getSequenceContext()->getSequenceSelection(); if (sel->isEmpty()) { return; } QPen pen1(Qt::black, 1, Qt::DashLine); p.setPen(pen1); foreach(const U2Region& r, sel->getSelectedRegions()) { highlight(p, r, baseLine); if (detView->hasComplementaryStrand()) { highlight(p, r, complementLine); } if (detView->hasTranslations()) { int translLine = posToDirectTransLine(r.startPos); highlight(p, r, translLine); if (detView->hasComplementaryStrand()) { int complTransLine = posToComplTransLine(r.endPos()); highlight(p, r, complTransLine); } } } } void DetViewRenderArea::drawRuler(QPainter& p) { int y = getLineY(rulerLine) + 2; const U2Region& visibleRange = view->getVisibleRange(); int firstCharStart = posToCoord(visibleRange.startPos); int lastCharStart = posToCoord(visibleRange.endPos()-1); int firstCharCenter = firstCharStart + charWidth / 2; int firstLastLen = lastCharStart - firstCharStart; GraphUtils::RulerConfig c; GraphUtils::drawRuler(p, QPoint(firstCharCenter, y), firstLastLen, visibleRange.startPos + 1, visibleRange.endPos(), rulerFont, c); } int DetViewRenderArea::posToDirectTransLine(int p) const { assert(firstDirectTransLine >= 0); return firstDirectTransLine + p % 3; } int DetViewRenderArea::posToComplTransLine(int p) const { assert(firstComplTransLine >= 0); return firstComplTransLine + (view->getSequenceLen() - p) % 3; } void DetViewRenderArea::highlight(QPainter& p, const U2Region& r, int line) { const U2Region& visibleRange = view->getVisibleRange(); if (!visibleRange.intersects(r)) { return; } U2Region visibleRegion = visibleRange.intersect(r); int x = posToCoord(visibleRegion.startPos); int width = posToCoord(visibleRegion.endPos()) - x; int ymargin = yCharOffset / 2; int y = getLineY(line) + ymargin; int height = lineHeight - 2 * ymargin; p.drawRect(x, y, width, height); } int DetViewRenderArea::coordToPos(int x) const { U2Region visibleRange = view->getVisibleRange(); int pos = visibleRange.startPos + int(x / (float)charWidth + 0.5f); if (pos > visibleRange.endPos()) { pos = visibleRange.endPos(); } return pos; } float DetViewRenderArea::posToCoordF(int x, bool useVirtualSpace) const { const U2Region& visible = view->getVisibleRange(); if (!useVirtualSpace && !visible.contains(x) && visible.endPos()!=x) { return -1; } float res = (float)(x - visible.startPos) * charWidth; assert(useVirtualSpace || (res >=0 && res <= width())); return res; } float DetViewRenderArea::getCurrentScale() const { assert(0); //TODO: must never be called. Not tested if called return (float)charWidth; } void DetViewRenderArea::updateSize() { updateLines(); int h = numLines * lineHeight + 5; setFixedHeight(h); //todo: remove +5 and fix ruler drawing to fit its line } }//namespace ugene-1.9.8/src/corelibs/U2View/src/util_ov_annotated_dna/AnnotationsTreeView.h0000644000175000017500000002544511651544334026314 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_ANNOTATIONS_TREE_VIEW_ #define _U2_ANNOTATIONS_TREE_VIEW_ #include #include #include #include #include #include #include namespace U2 { class Annotation; class AnnotationGroup; class U2Qualifier; class AnnotationTableObject; class AVItem; class AVGroupItem; class AVAnnotationItem; class AVQualifierItem; class AnnotatedDNAView; class AnnotationSelection; class AnnotationGroupSelection; class AnnotationModification; class GObjectView; class RemoveItemsTask; enum ATVAnnUpdateFlag { ATVAnnUpdateFlag_BaseColumns = 0x1, ATVAnnUpdateFlag_QualColumns = 0x2 }; typedef QFlags ATVAnnUpdateFlags; class U2VIEW_EXPORT AnnotationsTreeView : public QWidget { Q_OBJECT public: AnnotationsTreeView(AnnotatedDNAView* ctx); void saveWidgetState(); void restoreWidgetState(); void adjustStaticMenu(QMenu *m) const {adjustMenu(m);} QTreeWidget* getTreeWidget() const {return tree;} QStringList getQualifierColumnNames() const {return qColumns;} void addQualifierColumn(const QString& q); void removeQualifierColumn(const QString& q); void saveState(QVariantMap& map) const; void updateState(const QVariantMap& map); void setSortingEnabled(bool v); AVItem* currentItem(); private slots: void sl_onAnnotationObjectAdded(AnnotationTableObject* obj); void sl_onAnnotationObjectRemoved(AnnotationTableObject* obj); void sl_onAnnotationObjectRenamed(const QString &oldName); void sl_onAnnotationsAdded(const QList&); void sl_onAnnotationsRemoved(const QList&); void sl_onAnnotationsInGroupRemoved(const QList&, AnnotationGroup*); void sl_onAnnotationModified(const AnnotationModification& md); void sl_annotationObjectModifiedStateChanged(); void sl_onGroupCreated(AnnotationGroup*); void sl_onGroupRemoved(AnnotationGroup* parent, AnnotationGroup* removed); void sl_onGroupRenamed(AnnotationGroup*, const QString& oldName); void sl_onAnnotationSettingsChanged(const QStringList& changedSettings); void sl_onAnnotationSelectionChanged(AnnotationSelection*, const QList&, const QList&); void sl_onAnnotationGroupSelectionChanged(AnnotationGroupSelection*, const QList&, const QList&); void sl_onItemSelectionChanged(); void sl_onAddAnnotationObjectToView(); void sl_removeObjectFromView(); void sl_removeAnnsAndQs(); void sl_onBuildPopupMenu(GObjectView* thiz, QMenu* menu); void sl_onCopyQualifierValue(); void sl_onCopyQualifierURL(); void sl_onToggleQualifierColumn(); void sl_onRemoveColumnByHeaderClick(); void sl_onCopyColumnText(); void sl_onCopyColumnURL(); void sl_rename(); void sl_edit(); void sl_addQualifier(); // void sl_cutAnnotations(); // void sl_copyAnnotations(); // void sl_pasteAnnotations(); void sl_itemEntered(QTreeWidgetItem * i, int column); void sl_itemClicked( QTreeWidgetItem * item, int column); void sl_itemDoubleClicked (QTreeWidgetItem * item, int column); void sl_itemExpanded(QTreeWidgetItem*); //TODO: deal with style()->styleHint(QStyle::SH_ItemView_ActivateItemOnSingleClick) correctly // void sl_itemActivated(QTreeWidgetItem*, int) {sl_edit();} void sl_sortTree(); protected: bool eventFilter(QObject* o, QEvent* e); private: void renameItem(AVItem* i); void editItem(AVItem* i); QString renameDialogHelper(AVItem* i, const QString& defText, const QString& title); bool editQualifierDialogHelper(AVQualifierItem* i, bool ro, U2Qualifier& res); void moveDialogToItem(QTreeWidgetItem* item, QDialog& d); void adjustMenu(QMenu* m_) const; AVGroupItem* buildGroupTree(AVGroupItem* parentGroup, AnnotationGroup* g); AVAnnotationItem* buildAnnotationTree(AVGroupItem* parentGroup, Annotation* a); void populateAnnotationQualifiers(AVAnnotationItem* ai); void updateAllAnnotations(ATVAnnUpdateFlags flags); AVGroupItem* findGroupItem(const AnnotationGroup* g) const; AVAnnotationItem* findAnnotationItem(const AnnotationGroup* g, const Annotation* a) const; AVAnnotationItem* findAnnotationItem(const AVGroupItem* gi, const Annotation* a) const; // searches for annotation items that has not-null document added to the view QList findAnnotationItems(const Annotation* a) const; void connectAnnotationSelection(); void connectAnnotationGroupSelection(); void updateState(); void updateColumnContextActions(AVItem* item, int col); void resetDragAndDropData(); bool initiateDragAndDrop(QMouseEvent* me); void finishDragAndDrop(Qt::DropAction dndAction); QTreeWidget* tree; AnnotatedDNAView* ctx; QAction* addAnnotationObjectAction; QAction* removeObjectsFromViewAction; QAction* removeAnnsAndQsAction; QAction* copyQualifierAction; QAction* copyQualifierURLAction; QAction* toggleQualifierColumnAction; QAction* removeColumnByHeaderClickAction; QAction* copyColumnTextAction; QAction* copyColumnURLAction; // QAction* cutAnnotationsAction; // QAction* copyAnnotationsAction; // QAction* pasteAnnotationsAction; QAction* renameAction; // action to rename active group/qualifier/annotation only QAction* editAction; // action to edit active item -> only for non-readonly QAction* viewAction; // action to view active item -> could be used both for readonly and not readonly QAction* addQualifierAction; // action to create qualifier. Editable annotation or editable qualifier must be selected Qt::MouseButton lastMB; QStringList headerLabels; QStringList qColumns; int lastClickedColumn; QIcon addColumnIcon; QIcon removeColumnIcon; QTimer sortTimer; QPoint dragStartPos; // drag&drop related data bool isDragging; bool dndCopyOnly; QList dndSelItems; AVGroupItem* dropDestination; static const QString annotationMimeType; friend class RemoveItemsTask; }; ////////////////////////////////////////////////////////////////////////// /// Tree model //TODO: create qualifiers subtrees only when qualifier node is opened (usually qualifiers get ~ 90% of memory) enum AVItemType { AVItemType_Group, AVItemType_Annotation, AVItemType_Qualifier }; class AVItem : public QTreeWidgetItem { public: AVItem(QTreeWidgetItem* parent, AVItemType _type) : QTreeWidgetItem(parent), type(_type) {} const AVItemType type; bool processLinks(const QString& qname, const QString& qval, int col); bool isColumnLinked(int col) const; QString buildLinkURL(int col) const; QString getFileUrl(int col) const; virtual bool isReadonly() const {assert(parent()!=NULL); return (static_cast(parent())->isReadonly());} virtual AnnotationsTreeView* getAnnotationTreeView() const {assert(parent()!=NULL); return (static_cast(parent())->getAnnotationTreeView());} virtual AnnotationTableObject* getAnnotationTableObject() const {assert(parent()!=NULL); return (static_cast(parent())->getAnnotationTableObject());} virtual AnnotationGroup* getAnnotationGroup() const {assert(parent()!=NULL); return (static_cast(parent())->getAnnotationGroup());} }; class AVGroupItem : public AVItem { public: AVGroupItem(AnnotationsTreeView* atv, AVGroupItem* parent, AnnotationGroup* g); ~AVGroupItem(); void updateVisual(); void updateAnnotations(const QString& nameFilter, ATVAnnUpdateFlags flags); void findAnnotationItems(QList& result, Annotation* a) const; static const QIcon& getGroupIcon(); static const QIcon& getDocumentIcon(); virtual AnnotationsTreeView* getAnnotationTreeView() const {return atv;} virtual bool isReadonly() const; virtual AnnotationTableObject* getAnnotationTableObject() const; virtual AnnotationGroup* getAnnotationGroup() const; AnnotationGroup* group; AnnotationsTreeView* atv; }; class AVAnnotationItem : public AVItem { public: AVAnnotationItem(AVGroupItem* parent, Annotation* a); ~AVAnnotationItem(); Annotation* annotation; mutable QString locationString; virtual QVariant data ( int column, int role ) const; void updateVisual(ATVAnnUpdateFlags flags); virtual bool operator< ( const QTreeWidgetItem & other ) const; bool isColumnNumeric(int col) const; double getNumericVal(int col) const; void removeQualifier(const U2Qualifier& q); void addQualifier(const U2Qualifier& q); AVQualifierItem* findQualifierItem(const QString& name, const QString& val) const; static QMap& getIconsCache(); bool hasNumericQColumns; }; class AVQualifierItem: public AVItem { public: AVQualifierItem(AVAnnotationItem* parent, const U2Qualifier& q); //TODO: keep values in U2Qualifier struct const QString qName; const QString qValue; }; class RemoveItemsTask: public Task { public: RemoveItemsTask(AnnotationsTreeView *_treeView, AnnotationTableObject *_aObj, const QList& list, AnnotationGroup *gr): Task("Remove items", TaskFlag_None), treeView(_treeView), aObj(_aObj), as(list), parentGroup(gr) {} void prepare(); void run(); Task::ReportResult report(); private: AnnotationsTreeView *treeView; AnnotationTableObject* aObj; QList as; AnnotationGroup *parentGroup; QSet groupsToUpdate; AVGroupItem* parentGroupItem; Qt::ItemFlags flags; QList itemsToDelete; }; }//namespace #endif ugene-1.9.8/src/corelibs/U2View/src/util_ov_annotated_dna/Overview.h0000644000175000017500000000651311651544334024145 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_OVERVIEW_H_ #define _U2_OVERVIEW_H_ #include "GSequenceLineView.h" #include "ADVSequenceObjectContext.h" #include namespace U2 { class PanView; class DetView; class OverviewRenderArea; class AnnotationModification; class AnnotationGroup; class Overview : public GSequenceLineView { Q_OBJECT public: Overview(QWidget* p, ADVSequenceObjectContext* ctx); protected slots: void sl_visibleRangeChanged(); void sl_tbToggled(); void sl_annotationsAdded(const QList& a); void sl_annotationsRemoved(const QList& a); void sl_onAnnotationsInGroupRemoved(const QList&, AnnotationGroup*); void sl_annotationModified(const AnnotationModification& md); void sl_onAnnotationSettingsChanged(const QStringList& changedSettings); void sl_annotationObjectAdded(AnnotationTableObject* obj); void sl_annotationObjectRemoved(AnnotationTableObject* obj); void sl_sequenceChanged(); protected: void pack(); virtual bool event(QEvent* e); void mousePressEvent(QMouseEvent *me); void mouseMoveEvent(QMouseEvent* me); void mouseDoubleClickEvent(QMouseEvent* me); void mouseReleaseEvent(QMouseEvent* me); void wheelEvent(QWheelEvent* we); QString createToolTip(QHelpEvent* he); PanView* getPan() const {return panView;}; DetView* getDet() const {return detView;}; bool panSliderClicked; bool detSliderClicked; bool panSliderMovedRight; bool panSliderMovedLeft; int offset; private: PanView* panView; DetView* detView; QPoint mousePosToSlider; QToolButton* tb; friend class OverviewRenderArea; }; class OverviewRenderArea : public GSequenceLineViewRenderArea { Q_OBJECT public: OverviewRenderArea(Overview* p); const QRectF getPanSlider() const {return panSlider;}; const QRectF getDetSlider() const {return detSlider;}; int getAnnotationDensity(int pos) const; bool showGraph; protected: void drawAll(QPaintDevice* pd); private: void drawRuler(QPainter& p); void drawSelection(QPainter& p); void drawSlider(QPainter& p, QRectF rect, QColor col); void drawArrow(QPainter& p, QRectF rect, QColor col); void setAnnotationsOnPos(); void drawGraph(QPainter& p); QColor getUnitColor(int count); QRectF panSlider; QRectF detSlider; QBrush gradientMaskBrush; QVector annotationsOnPos; }; }//namespace #endif ugene-1.9.8/src/corelibs/U2View/src/util_ov_annotated_dna/PanViewRows.cpp0000644000175000017500000001032011651544334025105 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "PanViewRows.h" #include #include namespace U2 { PVRowsManager::~PVRowsManager() { clear(); } void PVRowsManager::clear() { qDeleteAll(rows); rows.clear(); rowByAnnotation.clear(); } typedef QVector::const_iterator LRIter; bool PVRowData::fitToRow(const QVector& location) { //assume locations are always in ascending order //usually annotations come in sorted by location //first check the most frequent way { const U2Region& l = location.first(); const U2Region& r = ranges.last(); if (l.startPos > r.endPos()) { ranges << location; return true; } else if (l.startPos >= r.startPos || l.endPos() >= r.startPos) { //got intersection return false; } } //bad luck, full search required QVarLengthArray pos; LRIter zero = ranges.constBegin(); LRIter end = ranges.constEnd(); foreach(const U2Region& l, location) { LRIter it = qLowerBound(ranges, l); if (it != end && (it->startPos <= l.endPos() || (it != zero && (it-1)->endPos() >= l.startPos)) ) { //got intersection return false; } pos.append(it-zero); } //ok this feature can be added to row; //keep the ranges in ascending order for(int i = location.size()-1; i>=0; i--) { ranges.insert(pos[i], location.at(i)); } return true; } inline bool compare_rows(PVRowData* x, PVRowData* y) { return x->key.compare(y->key) > 0; } void PVRowsManager::addAnnotation(Annotation* a, const QString& key) { assert(!rowByAnnotation.contains(a)); QVector location = a->getRegions(); foreach(PVRowData* row, rows) { if (row->key == key && row->fitToRow(location)) { row->annotations.append(a); rowByAnnotation[a] = row; return; } } PVRowData* row = new PVRowData(key); row->ranges << location; row->annotations.append(a); rowByAnnotation[a] = row; rows.push_back(row); qStableSort(rows.begin(), rows.end(), compare_rows); } void PVRowsManager::removeAnnotation(Annotation* a) { PVRowData* row = rowByAnnotation.value(a, NULL); assert(row != NULL); rowByAnnotation.remove(a); row->annotations.removeOne(a); U2Region::removeAll(row->ranges, a->getRegions()); if (row->annotations.empty()) { rows.removeOne(row); delete row; } } int PVRowsManager::getAnnotationRowIdx(Annotation* a) const { PVRowData* row = rowByAnnotation.value(a, NULL); assert(row != NULL); return rows.indexOf(row); } const QString& PVRowsManager::getRowKey(int rowNum) const { assert(rowNum >= 0 && rowNum < rows.size()); PVRowData* r = rows[rowNum]; return r->key; } int PVRowsManager::getNumAnnotationsInRow(int rowNum) const { assert(rowNum >= 0 && rowNum < rows.size()); PVRowData* r = rows[rowNum]; return r->annotations.size(); } bool PVRowsManager::contains(const QString& key) const { foreach(PVRowData* r, rows) { if (r->key == key) { return true; } } return false; } PVRowData* PVRowsManager::getRow( int row ) const { if (row>= 0 && row * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "AnnotatedDNAViewState.h" #include "AnnotatedDNAView.h" #include "AnnotatedDNAViewFactory.h" #include "ADVSequenceObjectContext.h" #include #include #include #include #include #include namespace U2 { #define VIEW_ID QString("view_id") #define SEQUENCE_OBJECTS QString("dna_obj_ref") #define ANNOTATION_OBJECTS QString("ann_obj_ref") #define SEQUENCE_SELECTION QString("dna_obj_sel") AnnotatedDNAViewState::AnnotatedDNAViewState() { } bool AnnotatedDNAViewState::isValid() const { bool idOK = stateData.value(VIEW_ID) == AnnotatedDNAViewFactory::ID; return idOK && !getSequenceObjects().isEmpty(); } QList AnnotatedDNAViewState::getSequenceObjects() const { QList res = stateData.value(SEQUENCE_OBJECTS).value >(); return res; } void AnnotatedDNAViewState::setSequenceObjects(const QList& objs, const QVector& selections) { assert(objs.size() == selections.size()); stateData[SEQUENCE_OBJECTS] = QVariant::fromValue >(objs); stateData[SEQUENCE_SELECTION]= QVariant::fromValue >(selections); } QVector AnnotatedDNAViewState::getSequenceSelections() const { QVector res = stateData.value(SEQUENCE_SELECTION).value >(); return res; } QList AnnotatedDNAViewState::getAnnotationObjects() const { QList res = stateData.value(ANNOTATION_OBJECTS).value >(); return res; } void AnnotatedDNAViewState::setAnnotationObjects(const QList& objs) { stateData[ANNOTATION_OBJECTS] = QVariant::fromValue >(objs); } QVariantMap AnnotatedDNAViewState::saveState(AnnotatedDNAView* v) { AnnotatedDNAViewState s; s.stateData[VIEW_ID] = AnnotatedDNAViewFactory::ID; QList seqRefs; QVector seqSels; foreach(const ADVSequenceObjectContext * ctx, v->getSequenceContexts()) { seqRefs.append(ctx->getSequenceObject()); DNASequenceSelection* sel = ctx->getSequenceSelection(); seqSels.append(sel->isEmpty()? U2Region() : sel->getSelectedRegions().first()); } QList anRefs; foreach(GObject* ao, v->getAnnotationObjects()) { anRefs.append(ao); } s.setSequenceObjects(seqRefs, seqSels); s.setAnnotationObjects(anRefs); return s.stateData; } } // namespace ugene-1.9.8/src/corelibs/U2View/src/util_ov_annotated_dna/EditAnnotationDialogController.cpp0000644000175000017500000001166311651544334031000 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "EditAnnotationDialogController.h" #include #include #include #include /* TRANSLATOR U2::EditAnnotationDialogController */ namespace U2 { EditAnnotationDialogController::EditAnnotationDialogController( Annotation* a, U2Region _seqRange, QWidget* p) : QDialog(p), seqRange(_seqRange) { setupUi(this); nameEdit->setText(a->getAnnotationName()); locationEdit->setText(Genbank::LocationParser::buildLocationString(a->data())); location = a->getLocation(); QMenu* menu = EditAnnotationDialogController::createAnnotationNamesMenu(this, this); showNameGroupsButton->setMenu(menu); showNameGroupsButton->setPopupMode(QToolButton::InstantPopup); connect(locationEdit, SIGNAL(textChanged(const QString&)), SLOT(sl_onTextChanged(const QString&))); connect(complementButton, SIGNAL(clicked()), SLOT(sl_complementLocation())); connect(locationEdit, SIGNAL(returnPressed()), SLOT(accept())); connect(nameEdit, SIGNAL(returnPressed()), SLOT(accept())); } void EditAnnotationDialogController::sl_onTextChanged(const QString& changedText){ QByteArray locEditText = changedText.toAscii(); Genbank::LocationParser::parseLocation(locEditText.constData(), changedText.length(), location); if (location->isEmpty()) { if(changedText.isEmpty()){ statusLabel->setText("" + tr("Location is empty!") + ""); }else{ statusLabel->setText("" + tr("Invalid location!") + ""); } }else{ statusLabel->setText(""); } } void EditAnnotationDialogController::accept(){ QByteArray locEditText = locationEdit->text().toAscii(); Genbank::LocationParser::parseLocation(locEditText.constData(), locationEdit->text().length(), location); U2Region cRegion = U2Region::containingRegion(location->regions); bool validRegions = seqRange.contains(cRegion); if ( location->isEmpty() || (nameEdit->text()).isEmpty() ) { QDialog::reject(); }else if (!Annotation::isValidAnnotationName(nameEdit->text())) { QMessageBox::critical( this, tr( "Error!" ), tr( "Wrong annotation name!" ) ); }else if (!validRegions){ QMessageBox::critical( this, tr( "Error!" ), tr( "New annotation locations is out of sequence bounds!" ) ); }else{ currentName = nameEdit->text(); QDialog::accept(); } } static bool caseInsensitiveLessThan(const QString &s1, const QString &s2) { return s1.toLower() < s2.toLower(); } QMenu* EditAnnotationDialogController::createAnnotationNamesMenu( QWidget* p, QObject* receiver ) { assert(p!=NULL && receiver!=NULL); QMenu* m = new QMenu(p); const QMultiMap& nameGroups = GBFeatureUtils::getKeyGroups(); QStringList groupNames = nameGroups.uniqueKeys(); qSort(groupNames.begin(), groupNames.end(), caseInsensitiveLessThan); foreach(const QString& groupName, groupNames) { QMenu* groupMenu = m->addMenu(groupName); QList keys = nameGroups.values(groupName); QStringList names; foreach(GBFeatureKey k, keys) { names.append(GBFeatureUtils::getKeyInfo(k).text); } qSort(names.begin(), names.end(), caseInsensitiveLessThan); foreach(const QString& name, names) { QAction* a = new QAction(name, groupMenu); connect(a, SIGNAL(triggered()), receiver, SLOT(sl_setPredefinedAnnotationName())); groupMenu->addAction(a); } } return m; } void EditAnnotationDialogController::sl_setPredefinedAnnotationName() { QAction* a = qobject_cast(sender()); QString text = a->text(); nameEdit->setText(text); } void EditAnnotationDialogController::sl_complementLocation() { QString text = locationEdit->text(); if (text.startsWith("complement(") && text.endsWith(")")) { locationEdit->setText(text.mid(11, text.length()-12)); } else { locationEdit->setText("complement(" + text + ")"); } } }// ns ugene-1.9.8/src/corelibs/U2View/src/util_ov_annotated_dna/Overview.cpp0000644000175000017500000005337611651544334024511 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "Overview.h" #include "ADVSingleSequenceWidget.h" #include "PanView.h" #include "DetView.h" #include #include #include #include #include #include #include #include namespace U2 { Overview::Overview(QWidget *p, ADVSequenceObjectContext *ctx) : GSequenceLineView(p, ctx) { renderArea = new OverviewRenderArea(this); visibleRange = U2Region(0, ctx->getSequenceLen()); renderArea->setMouseTracking(true); ADVSingleSequenceWidget* ssw = qobject_cast(p); panView = ssw->getPanView(); detView = ssw->getDetView(); tb = new QToolButton(this); tb->setFixedWidth(16); tb->setFixedHeight(20); tb->setCheckable(true); tb->setIcon(QIcon(":core/images/sum.png")); tb->setToolTip(tr("Toggle annotation density graph")); connect(panView, SIGNAL(si_visibleRangeChanged()), SLOT(sl_visibleRangeChanged())); connect(detView, SIGNAL(si_visibleRangeChanged()), SLOT(sl_visibleRangeChanged())); connect(tb, SIGNAL(pressed()), SLOT(sl_tbToggled())); connect(ctx, SIGNAL(si_annotationObjectAdded(AnnotationTableObject*)), SLOT(sl_annotationObjectAdded(AnnotationTableObject*))); connect(ctx, SIGNAL(si_annotationObjectRemoved(AnnotationTableObject*)), SLOT(sl_annotationObjectRemoved(AnnotationTableObject*))); foreach(AnnotationTableObject* at, ctx->getAnnotationObjects(true)) { connect(at, SIGNAL(si_onAnnotationsAdded(const QList&)), SLOT(sl_annotationsAdded(const QList&))); connect(at, SIGNAL(si_onAnnotationsRemoved(const QList&)), SLOT(sl_annotationsRemoved(const QList&))); connect(at, SIGNAL(si_onAnnotationsInGroupRemoved(const QList&, AnnotationGroup*)), SLOT(sl_onAnnotationsInGroupRemoved(const QList&, AnnotationGroup*))); connect(at, SIGNAL(si_onAnnotationModified(const AnnotationModification&)), SLOT(sl_annotationModified(const AnnotationModification&))); connect(AppContext::getAnnotationsSettingsRegistry(), SIGNAL(si_annotationSettingsChanged(const QStringList&)), SLOT(sl_onAnnotationSettingsChanged(const QStringList&))); } connect(ctx->getSequenceGObject(), SIGNAL(si_sequenceChanged()), SLOT(sl_sequenceChanged())); sl_visibleRangeChanged(); pack(); } void Overview::sl_annotationObjectAdded(AnnotationTableObject* obj) { connect(obj, SIGNAL(si_onAnnotationsAdded(const QList&)), SLOT(sl_annotationsAdded(const QList&))); connect(obj, SIGNAL(si_onAnnotationsRemoved(const QList&)), SLOT(sl_annotationsRemoved(const QList&))); connect(obj, SIGNAL(si_onAnnotationModified(const AnnotationModification&)), SLOT(sl_annotationModified(const AnnotationModification&))); addUpdateFlags(GSLV_UF_AnnotationsChanged); update(); } void Overview::sl_annotationObjectRemoved(AnnotationTableObject* obj) { Q_UNUSED(obj); addUpdateFlags(GSLV_UF_AnnotationsChanged); update(); } void Overview::sl_annotationsAdded(const QList& a) { Q_UNUSED(a); addUpdateFlags(GSLV_UF_AnnotationsChanged); update(); } void Overview::sl_annotationsRemoved(const QList& a) { Q_UNUSED(a); addUpdateFlags(GSLV_UF_AnnotationsChanged); update(); } void Overview::sl_onAnnotationsInGroupRemoved(const QList&, AnnotationGroup*) { addUpdateFlags(GSLV_UF_AnnotationsChanged); update(); AnnotationTableObject *aobj = static_cast(sender()); aobj->releaseLocker(); } void Overview::sl_annotationModified(const AnnotationModification& md) { if (md.type==AnnotationModification_LocationChanged) { addUpdateFlags(GSLV_UF_AnnotationsChanged); update(); } } void Overview::sl_onAnnotationSettingsChanged(const QStringList& changedSettings) { Q_UNUSED(changedSettings); addUpdateFlags(GSLV_UF_AnnotationsChanged); update(); } void Overview::sl_sequenceChanged() { addUpdateFlags(GSLV_UF_NeedCompleteRedraw); update(); } void Overview::pack() { assert(layout() == NULL); QHBoxLayout *layout = new QHBoxLayout(); layout->setMargin(0); layout->setSpacing(0); layout->addWidget(renderArea); layout->addWidget(tb); setLayout(layout); scrollBar->setHidden(true); setFixedHeight(renderArea->height()); } void Overview::sl_tbToggled() { OverviewRenderArea* ra = qobject_cast(renderArea); ra->showGraph = !ra->showGraph; addUpdateFlags(GSLV_UF_NeedCompleteRedraw); update(); } void Overview::sl_visibleRangeChanged() { renderArea->update(); } void Overview::mousePressEvent(QMouseEvent *me) { if (me->buttons() & Qt::LeftButton) { OverviewRenderArea* ra = static_cast(renderArea); QPoint renderAreaPos = toRenderAreaPoint(me->pos()); //make selection if shift was pressed if(me->modifiers().testFlag(Qt::ShiftModifier)) { lastPressPos=ra->coordToPos(renderAreaPos.x()); QWidget::mousePressEvent(me); return; } QRectF panSlider(ra->getPanSlider()); QRectF detSlider(ra->getDetSlider()); panSliderClicked = panSlider.contains(renderAreaPos); panSliderMovedRight = (panSlider.topRight().x() - renderAreaPos.x() < 10) && panSliderClicked; panSliderMovedLeft = (renderAreaPos.x() - panSlider.topLeft().x() < 10) && panSliderClicked; offset = renderArea->coordToPos(me->pos().x()) - renderArea->coordToPos(panSlider.left()); //don't process detSlider when details view is collapsed ADVSingleSequenceWidget* parent = qobject_cast(parentWidget()); assert(parent); if(parent->isDetViewCollapsed()) { detSliderClicked = false; } else { detSliderClicked = detSlider.contains(renderAreaPos); } //int panW = panSlider.width(); //int raW = ra->width(); if(panSliderClicked&&detSliderClicked) { /*panSliderClicked = panSlider.width()getSequenceLen(); int panVisLen = panView->getVisibleRange().length; int detVisLen = detView->getVisibleRange().length; int panPos = renderArea->coordToPos(renderAreaPos.x() - panSlider.width()/2); panPos = qBound(0, panPos, seqLen-panVisLen); panView->setVisibleRange(U2Region(panPos, panVisLen)); int detPos = renderArea->coordToPos(renderAreaPos.x()); detPos = qBound(0, detPos, seqLen-detVisLen); detView->setVisibleRange(U2Region(detPos, detVisLen)); } } QWidget::mousePressEvent(me); } void Overview::mouseReleaseEvent(QMouseEvent* me) { lastPressPos=-1; panSliderMovedRight = false; panSliderMovedLeft = false; QWidget::mouseReleaseEvent(me); } void Overview::mouseMoveEvent(QMouseEvent *me) { QPoint renderAreaPos = toRenderAreaPoint(me->pos()); OverviewRenderArea* ra = static_cast(renderArea); QRectF panSlider(ra->getPanSlider()); if(((panSlider.topRight().x() - renderAreaPos.x() < 10 && panSlider.topRight().x() - renderAreaPos.x() > -5) || (renderAreaPos.x() - panSlider.topLeft().x()> -5 && renderAreaPos.x() - panSlider.topLeft().x() < 10)) && panView->isVisible()) { setCursor(QCursor(Qt::SizeHorCursor)); } else { setCursor(QCursor(Qt::ArrowCursor)); } if (me->buttons() & Qt::LeftButton) { int pos = renderArea->coordToPos(renderAreaPos.x() - mousePosToSlider.x()); if(lastPressPos!=-1) {//make selection U2Region selection; int mousePos = renderArea->coordToPos(renderAreaPos.x()); int selLen = mousePos-lastPressPos; if(selLen>0) { selection.startPos=lastPressPos; selection.length=selLen; } else { selection.startPos=mousePos; selection.length=-selLen; } setSelection(selection); QWidget::mouseMoveEvent(me); return; } if(panView->isVisible()) { if(panSliderMovedRight) { OverviewRenderArea* ra = static_cast(renderArea); QRectF panSlider(ra->getPanSlider()); qreal length = me->pos().x() - panSlider.right(); int panVisLen = renderArea->coordToPos(qAbs(length)); if(length < 0) { panVisLen *= -1; } panVisLen = panView->getVisibleRange().length + panVisLen; pos = renderArea->coordToPos(panSlider.left()) ; if(panVisLen > 0 && panView->getSeqLen() >= (panVisLen + pos)) { panView->setVisibleRange(U2Region(pos, panVisLen)); } } else if(panSliderMovedLeft) { OverviewRenderArea* ra = static_cast(renderArea); QRectF panSlider(ra->getPanSlider()); int length = panSlider.left() - me->pos().x(); int panVisLen = renderArea->coordToPos(qAbs(length)); if(length < 0) { panVisLen *= -1; } panVisLen = panView->getVisibleRange().length + panVisLen + offset; pos = panView->getVisibleRange().endPos() - panVisLen; if(panVisLen > 0 && pos > 0 && (panVisLen + pos) <= ctx->getSequenceLen()) { panView->setVisibleRange(U2Region(pos, panVisLen)); } } else if(panSliderClicked) { int panVisLen = panView->getVisibleRange().length; pos = qBound(0, pos, ctx->getSequenceLen() - panVisLen); panView->setVisibleRange(U2Region(pos, panVisLen)); } } if (detSliderClicked) { int detVisLen = detView->getVisibleRange().length; pos = qBound(0, pos, ctx->getSequenceLen() - detVisLen); detView->setVisibleRange(U2Region(pos, detVisLen)); } } QWidget::mouseMoveEvent(me); } void Overview::mouseDoubleClickEvent(QMouseEvent* me) { if(me->buttons() & Qt::LeftButton) { OverviewRenderArea* ra = static_cast(renderArea); QRectF panSlider(ra->getPanSlider()); int panVisLen = panView->getVisibleRange().length; QPoint renderAreaPos = toRenderAreaPoint(me->pos()); int panPos = ra->coordToPos(renderAreaPos.x() - panSlider.width()/2); panPos = qBound(0, panPos, ctx->getSequenceLen() - panVisLen); panView->setVisibleRange(U2Region(panPos, panVisLen)); //don't process detSlider when details view is collapsed ADVSingleSequenceWidget* parent = qobject_cast(parentWidget()); assert(parent); if(!parent->isDetViewCollapsed()) { QRectF detSlider(ra->getDetSlider()); int detVisLen = detView->getVisibleRange().length; int detPos = ra->coordToPos(renderAreaPos.x()); detPos = qBound(0, detPos, ctx->getSequenceLen() - detVisLen); detView->setVisibleRange(U2Region(detPos, detVisLen)); } panSliderClicked=false; detSliderClicked=false; panSliderMovedRight = false; panSliderMovedLeft = false; } QWidget::mouseDoubleClickEvent(me); } void Overview::wheelEvent(QWheelEvent *we) { bool renderAreaWheel = QRect(renderArea->x(), renderArea->y(), renderArea->width(), renderArea->height()).contains(we->pos()); if (!renderAreaWheel) { QWidget::wheelEvent(we); return; } setFocus(); bool toMin = we->delta() > 0; QAction* zoomAction = toMin ? panView->getZoomInAction() : panView->getZoomOutAction(); if (zoomAction != NULL) { zoomAction->activate(QAction::Trigger); } } bool Overview::event(QEvent* e) { if (e->type() == QEvent::ToolTip) { QHelpEvent* he = static_cast(e); QString tip = createToolTip(he); if (!tip.isEmpty()) { QToolTip::showText(he->globalPos(), tip); } } return GSequenceLineView::event(e); } QString Overview::createToolTip(QHelpEvent *he) { OverviewRenderArea* ra = qobject_cast(renderArea); QPoint renderAreaPos = toRenderAreaPoint(he->pos()); int halfChar = ra->getCurrentScale()/2; int pos = ra->coordToPos(renderAreaPos.x() + halfChar); int pos2 = ra->coordToPos(renderAreaPos.x() + halfChar +1); int delta=0; if(pos2-1>pos) { delta=pos2-pos-1; } QString tip = tr("Position ")+QString::number(pos); if(delta!=0) { tip+=".."+QString::number(pos+delta); } if(ra->showGraph) { int density = ra->getAnnotationDensity(pos); for (int i=pos;i<=pos+delta;++i) { int nextPosDensity = ra->getAnnotationDensity(i); density=qMax(density, nextPosDensity); } tip+="\n"+tr("Annotation density ")+QString::number(density); } return tip; } ////////////////////////////////////////////////////////////////////////// /// GlobalViewRenderArea #define ANNOTATION_GRAPH_HEIGHT 4 #define RULER_NOTCH_SIZE 2 #define SLIDER_MIN_WIDTH 3 #define ARROW_WIDTH 12 #define ARROW_HEIGHT 10 #define ARROW_TOP_PAD ANNOTATION_GRAPH_HEIGHT + 2*RULER_NOTCH_SIZE #define PEN_WIDTH 1 #define RENDER_AREA_HEIGHT lineHeight + ANNOTATION_GRAPH_HEIGHT OverviewRenderArea::OverviewRenderArea(Overview *p) : GSequenceLineViewRenderArea(p) { setFixedHeight(RENDER_AREA_HEIGHT); QLinearGradient gradient(0, 0, 0, 1); //vertical gradient.setCoordinateMode(QGradient::ObjectBoundingMode); gradient.setColorAt(0.00, QColor(255, 255, 255, 120)); gradient.setColorAt(0.50, QColor( 0, 0, 0, 0)); gradient.setColorAt(0.70, QColor( 0, 0, 0, 0)); gradient.setColorAt(1.00, QColor( 0, 0, 0, 70)); gradientMaskBrush = QBrush(gradient); showGraph=false; } //pos [1, seqLen]; annotationsOnPos [0, seqLen) int OverviewRenderArea::getAnnotationDensity (int pos) const { if(pos<1 || pos>annotationsOnPos.size()) { return 0; } return annotationsOnPos.at(pos-1); } void OverviewRenderArea::setAnnotationsOnPos() { annotationsOnPos.clear(); ADVSequenceObjectContext* ctx = view->getSequenceContext(); int len = ctx->getSequenceLen(); annotationsOnPos.resize(len); const U2Region& sequenceRange = ctx->getSequenceObject()->getSequenceRange(); AnnotationSettingsRegistry* asr = AppContext::getAnnotationsSettingsRegistry(); QSet aObjs = ctx->getAnnotationObjects(true); foreach(AnnotationTableObject* at, aObjs) { foreach(Annotation* a, at->getAnnotations()) { AnnotationSettings* as = asr->getAnnotationSettings(a->getAnnotationName()); if(as->visible) { foreach(const U2Region& r, a->getRegions()) { U2Region innerRegion = r.intersect(sequenceRange); for(int i = innerRegion.startPos;i < innerRegion.endPos(); i++) { annotationsOnPos[i]++; } } } } } } void OverviewRenderArea::drawAll(QPaintDevice *pd) { QPen pen(Qt::SolidLine); pen.setWidth(PEN_WIDTH); GSLV_UpdateFlags uf = view->getUpdateFlags(); bool completeRedraw = uf.testFlag(GSLV_UF_NeedCompleteRedraw) || uf.testFlag(GSLV_UF_AnnotationsChanged) || uf.testFlag(GSLV_UF_ViewResized); if(completeRedraw) { QPainter pCached(cachedView); pCached.fillRect(0, 0, pd->width(), pd->height(), Qt::white); if(showGraph) { setAnnotationsOnPos(); drawGraph(pCached); } pCached.end(); } QPainter p(pd); p.drawPixmap(0,0,*cachedView); Overview* gv = static_cast(view); int panX = posToCoord(gv->getPan()->getVisibleRange().startPos); int panW = qMax(posToCoord(gv->getPan()->getVisibleRange().length), SLIDER_MIN_WIDTH); int detX = posToCoord(gv->getDet()->getVisibleRange().startPos) - int(ARROW_WIDTH/2); int panSliderHeight = pd->height()-PEN_WIDTH; int panSliderTop=0; if(showGraph) { panSliderHeight-=ANNOTATION_GRAPH_HEIGHT; panSliderTop+=ANNOTATION_GRAPH_HEIGHT; } panSlider.setRect(panX, panSliderTop, panW-PEN_WIDTH, panSliderHeight); detSlider.setRect(detX,ARROW_TOP_PAD, ARROW_WIDTH, ARROW_HEIGHT); pen.setColor(Qt::darkGray); p.setPen(pen); //don't show arrow when det view collapsed Overview* overview = qobject_cast(view); ADVSingleSequenceWidget* ssw = qobject_cast(overview->parentWidget()); assert(ssw); if(!ssw->isPanViewCollapsed()) { drawSlider(p, panSlider, QColor(230, 230, 230)); } if (!ssw->isDetViewCollapsed()) { drawArrow(p, detSlider, QColor(255, 187, 0)); } drawRuler(p); drawSelection(p); } void OverviewRenderArea::drawSlider(QPainter& p, QRectF rect, QColor col) { QPainterPath path; path.addRect(rect); path.setFillRule(Qt::WindingFill); p.fillPath(path, col); p.fillPath(path, gradientMaskBrush); p.drawPath(path); } void OverviewRenderArea::drawArrow(QPainter& p, QRectF rect, QColor col) { QPainterPath arrPath; arrPath.moveTo(rect.bottomLeft()); arrPath.lineTo(rect.center().x(), rect.center().y()-rect.width()/2); arrPath.lineTo(rect.bottomRight()); arrPath.closeSubpath(); arrPath.setFillRule(Qt::WindingFill); p.fillPath(arrPath, col); p.fillPath(arrPath, gradientMaskBrush); p.drawPath(arrPath); } void OverviewRenderArea::drawRuler(QPainter &p) { p.save(); QPen pen(Qt::black); pen.setWidth(PEN_WIDTH); p.setPen(pen); Overview* gv = static_cast(view); int seqLen = gv->ctx->getSequenceLen(); U2Region visibleRange = gv->getVisibleRange(); float halfChar = getCurrentScale() / 2; int firstCharCenter = qRound(posToCoordF(visibleRange.startPos) + halfChar); int lastCharCenter = qRound(posToCoordF(visibleRange.endPos() - 1) + halfChar); int firstLastWidth = lastCharCenter - firstCharCenter; if (qRound(halfChar) == 0) { firstLastWidth--; // make the end of the ruler visible } GraphUtils::RulerConfig c; if(showGraph) { c.singleSideNotches=true; } c.notchSize = RULER_NOTCH_SIZE; GraphUtils::drawRuler(p, QPoint(firstCharCenter, ANNOTATION_GRAPH_HEIGHT), firstLastWidth, 1, seqLen, rulerFont, c); p.restore(); } #define SELECTION_LINE_WIDTH 3 void OverviewRenderArea::drawSelection(QPainter& p) { QPen pen(QColor("#007DE3")); pen.setWidth(SELECTION_LINE_WIDTH); p.setPen(pen); Overview* gv = qobject_cast(view); DNASequenceSelection* sel = gv->ctx->getSequenceSelection(); foreach(const U2Region& r, sel->getSelectedRegions()) { int x1 = posToCoord(r.startPos); int x2 = posToCoord(r.endPos()); p.drawLine(x1, ANNOTATION_GRAPH_HEIGHT, x2, ANNOTATION_GRAPH_HEIGHT); } } void OverviewRenderArea::drawGraph(QPainter& p) { p.save(); QPen graphPen; graphPen.setWidth(1); p.fillRect(0,0,width()-PEN_WIDTH, ANNOTATION_GRAPH_HEIGHT-PEN_WIDTH, Qt::white); int halfChar = getCurrentScale()/2; for(int i = 0; i < width(); i++) { int count; int pos1 = coordToPos(i+halfChar); if(pos1<1 || pos1>annotationsOnPos.size()+1) { continue; } if(coordToPos(i+1)>pos1) { count=annotationsOnPos.at(pos1-1); } else { int pos2 = coordToPos(i) - 1; count = annotationsOnPos.at(pos1-1); for (int pos = pos1; pos < pos2; pos++) { int nextCount = annotationsOnPos.at(pos-1); count = qMax(count, nextCount); } } QColor col = getUnitColor(count); graphPen.setColor(col); p.setPen(graphPen); p.drawLine(i,0,i,ANNOTATION_GRAPH_HEIGHT); } p.restore(); } QColor OverviewRenderArea::getUnitColor(int count) { switch(count) { case 0: return QColor(0xFF, 0xFF, 0xFF); case 1: return QColor(0xCC, 0xCC, 0xCC); case 2: case 3: return QColor(0x66, 0x66, 0x66); default: return QColor(0x00, 0x00, 0x00); } } }//namespace ugene-1.9.8/src/corelibs/U2View/src/util_ov_annotated_dna/AnnotatedDNAViewFactory.cpp0000644000175000017500000001566611651544334027326 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "AnnotatedDNAViewFactory.h" #include "AnnotatedDNAView.h" #include "AnnotatedDNAViewTasks.h" #include "AnnotatedDNAViewState.h" #include "ADVConstants.h" #include #include #include #include #include #include #include #include #include #include namespace U2 { /* TRANSLATOR U2::AnnotatedDNAView */ const GObjectViewFactoryId AnnotatedDNAViewFactory::ID(ANNOTATED_DNA_VIEW_FACTORY_ID); AnnotatedDNAViewFactory::AnnotatedDNAViewFactory() : GObjectViewFactory(ID, tr("Sequence view")) { } bool AnnotatedDNAViewFactory::canCreateView(const MultiGSelection& multiSelection) { //return true if //1. selection has loaded of unloaded DNA sequence object //2. selection has any object with SEQUENCE relation to DNA sequence object that is in the project //3. selection has document that have sequence object or object assosiated with sequence //1. QList selectedObjects = SelectionUtils::findObjects("", &multiSelection, UOF_LoadedAndUnloaded); QList selectedSequences = GObjectUtils::select(selectedObjects, GObjectTypes::SEQUENCE, UOF_LoadedAndUnloaded); if (!selectedSequences.isEmpty()) { return true; } //2. QList objectsWithSeqRelation = GObjectUtils::selectObjectsWithRelation(selectedObjects, GObjectTypes::SEQUENCE, GObjectRelationRole::SEQUENCE, UOF_LoadedAndUnloaded, true); if (!objectsWithSeqRelation.isEmpty()) { return true; } //3. const DocumentSelection* ds = qobject_cast(multiSelection.findSelectionByType(GSelectionTypes::DOCUMENTS)); if (ds == NULL) { return false; } foreach(Document* doc, ds->getSelectedDocuments()) { if (!doc->findGObjectByType(GObjectTypes::SEQUENCE, UOF_LoadedAndUnloaded).isEmpty()) { return true; } objectsWithSeqRelation = GObjectUtils::selectObjectsWithRelation(doc->getObjects(), GObjectTypes::SEQUENCE, GObjectRelationRole::SEQUENCE, UOF_LoadedAndUnloaded, true); if (!objectsWithSeqRelation.isEmpty()) { return true; } } return false; } Task* AnnotatedDNAViewFactory::createViewTask(const MultiGSelection& multiSelection, bool single /*=false*/) { Q_UNUSED(single); QList objectsToOpen = SelectionUtils::findObjects(GObjectTypes::SEQUENCE, &multiSelection, UOF_LoadedAndUnloaded); QList selectedObjects = SelectionUtils::findObjects("", &multiSelection, UOF_LoadedAndUnloaded); QList objectsWithSequenceRelation = GObjectUtils::selectObjectsWithRelation(selectedObjects, GObjectTypes::SEQUENCE, GObjectRelationRole::SEQUENCE, UOF_LoadedAndUnloaded, true); foreach(GObject* obj, objectsWithSequenceRelation) { if(!objectsToOpen.contains(obj)) { objectsToOpen.append(obj); } } //objectsToOpen.append(objectsWithSequenceRelation); const DocumentSelection* ds = qobject_cast(multiSelection.findSelectionByType(GSelectionTypes::DOCUMENTS)); if (ds != NULL) { foreach(Document* doc, ds->getSelectedDocuments()) { /*objectsToOpen.append(doc->findGObjectByType(GObjectTypes::SEQUENCE, UOF_LoadedAndUnloaded)); objectsToOpen.append(GObjectUtils::selectObjectsWithRelation(doc->getObjects(), GObjectTypes::SEQUENCE, GObjectRelationRole::SEQUENCE, UOF_LoadedAndUnloaded, true));*/ foreach(GObject* obj, doc->findGObjectByType(GObjectTypes::SEQUENCE, UOF_LoadedAndUnloaded)) { if(!objectsToOpen.contains(obj)) { objectsToOpen.append(obj); } } foreach(GObject* obj, GObjectUtils::selectObjectsWithRelation(doc->getObjects(), GObjectTypes::SEQUENCE, GObjectRelationRole::SEQUENCE, UOF_LoadedAndUnloaded, true)) { if(!objectsToOpen.contains(obj)) { objectsToOpen.append(obj); } } } } OpenAnnotatedDNAViewTask* task = new OpenAnnotatedDNAViewTask(objectsToOpen); return task; } bool AnnotatedDNAViewFactory::isStateInSelection(const MultiGSelection& multiSelection, const QVariantMap& stateData) { AnnotatedDNAViewState state(stateData); if (!state.isValid()) { return false; } QList refs = state.getSequenceObjects(); assert(!refs.isEmpty()); foreach (const GObjectReference& ref, refs) { Document* doc = AppContext::getProject()->findDocumentByURL(ref.docUrl); if (doc == NULL) { //todo: accept to use invalid state removal routines of ObjectViewTask ??? return false; } //check that document is in selection QList selectedDocs = SelectionUtils::getSelectedDocs(multiSelection); bool docIsSelected = selectedDocs.contains(doc); //check that object is in selection QList selectedObjects = SelectionUtils::getSelectedObjects(multiSelection); GObject* obj = doc->findGObjectByName(ref.objName); bool objIsSelected = obj!=NULL && selectedObjects.contains(obj); //check that object associated with sequence object is in selection bool refIsSelected = false; foreach (const GObject* selObject, selectedObjects) { GObjectReference selRef(selObject); if (ref == selRef) { refIsSelected = true; break; } } if (!docIsSelected && !objIsSelected && !refIsSelected) { return false; } } return true; } Task* AnnotatedDNAViewFactory::createViewTask(const QString& viewName, const QVariantMap& stateData) { return new OpenSavedAnnotatedDNAViewTask(viewName, stateData); } } // namespace ugene-1.9.8/src/corelibs/U2View/src/util_ov_annotated_dna/ADVSyncViewManager.cpp0000644000175000017500000005045411651544334026272 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "ADVSyncViewManager.h" #include "AnnotatedDNAView.h" #include "ADVSingleSequenceWidget.h" #include "ADVSequenceObjectContext.h" #include "AutoAnnotationUtils.h" #include "PanView.h" #include #include namespace U2 { ADVSyncViewManager::ADVSyncViewManager(AnnotatedDNAView* v) : QObject(v), adv(v) { assert(v->getSequenceContexts().isEmpty()); recursion = false; selectionRecursion = false; lockByStartPosAction = new QAction(tr("Lock scales: visible range start"), this); connect(lockByStartPosAction, SIGNAL(triggered()), SLOT(sl_lock())); lockByStartPosAction->setCheckable(true); lockBySeqSelAction = new QAction(tr("Lock scales: selected sequence"), this); connect(lockBySeqSelAction, SIGNAL(triggered()), SLOT(sl_lock())); lockBySeqSelAction->setCheckable(true); lockByAnnSelAction = new QAction(tr("Lock scales: selected annotation"), this); connect(lockByAnnSelAction, SIGNAL(triggered()), SLOT(sl_lock())); lockByAnnSelAction->setCheckable(true); lockActionGroup = new QActionGroup(this); lockActionGroup->addAction(lockByStartPosAction); lockActionGroup->addAction(lockBySeqSelAction); lockActionGroup->addAction(lockByAnnSelAction); lockActionGroup->setExclusive(true); syncByStartPosAction = new QAction(tr("Adjust scales: visible range start"), this); connect(syncByStartPosAction, SIGNAL(triggered()), SLOT(sl_sync())); syncBySeqSelAction = new QAction(tr("Adjust scales: selected sequence"), this); connect(syncBySeqSelAction, SIGNAL(triggered()), SLOT(sl_sync())); syncByAnnSelAction = new QAction(tr("Adjust scales: selected annotation"), this); connect(syncByAnnSelAction, SIGNAL(triggered()), SLOT(sl_sync())); lockMenu = new QMenu(tr("Lock scales")); lockMenu->setIcon(QIcon(":core/images/lock_scales.png")); lockMenu->addActions(lockActionGroup->actions()); syncMenu = new QMenu(tr("Adjust scales")); syncMenu->setIcon(QIcon(":core/images/sync_scales.png")); syncMenu->addAction(syncByStartPosAction); syncMenu->addAction(syncBySeqSelAction); syncMenu->addAction(syncByAnnSelAction); lockButton = new QToolButton(); lockButton->setCheckable(true); connect(lockButton, SIGNAL(clicked()), SLOT(sl_lock())); lockButton->setDefaultAction(lockMenu->menuAction()); lockButton->setCheckable(true); syncButton = new QToolButton(); connect(syncButton, SIGNAL(clicked()), SLOT(sl_sync())); syncButton->setDefaultAction(syncMenu->menuAction()); lockButtonTBAction = NULL; syncButtonTBAction = NULL; // auto-annotations highlighting ops toggleAutoAnnotationsMenu = new QMenu("Global automatic annotation highlighting"); toggleAutoAnnotationsMenu->setIcon(QIcon(":core/images/predefined_annotation_groups.png")); connect( toggleAutoAnnotationsMenu, SIGNAL(aboutToShow()), SLOT(sl_updateAutoAnnotationsMenu()) ); toggleAutoAnnotationsButton = new QToolButton(); toggleAutoAnnotationsButton->setDefaultAction(toggleAutoAnnotationsMenu->menuAction()); toggleAutoAnnotationsButton->setPopupMode(QToolButton::InstantPopup); toggleAutoAnnotationsAction = NULL; // visual mode ops toggleAllAction = new QAction("Toggle All sequence views", this); connect(toggleAllAction, SIGNAL(triggered()), SLOT(sl_toggleVisualMode())); toggleOveAction = new QAction("Toggle Overview", this); connect(toggleOveAction, SIGNAL(triggered()), SLOT(sl_toggleVisualMode())); togglePanAction = new QAction("Toggle Zoom view", this); connect(togglePanAction, SIGNAL(triggered()), SLOT(sl_toggleVisualMode())); toggleDetAction = new QAction("Toggle Details view", this); connect(toggleDetAction, SIGNAL(triggered()), SLOT(sl_toggleVisualMode())); toggleViewButtonAction = NULL; toggleViewButtonMenu = new QMenu(tr("Toggle views")); toggleViewButtonMenu->setIcon(QIcon(":core/images/adv_widget_menu.png")); toggleViewButtonMenu->addAction(toggleAllAction); //-> behavior can be not clear to user toggleViewButtonMenu->addAction(toggleOveAction); toggleViewButtonMenu->addAction(togglePanAction); toggleViewButtonMenu->addAction(toggleDetAction); connect(toggleViewButtonMenu, SIGNAL(aboutToShow()), SLOT(sl_updateVisualMode())); toggleViewButton = new QToolButton(); toggleViewButton->setDefaultAction(toggleViewButtonMenu->menuAction()); toggleViewButton->setPopupMode(QToolButton::InstantPopup); updateEnabledState(); connect(adv, SIGNAL(si_sequenceWidgetAdded(ADVSequenceWidget*)), SLOT(sl_sequenceWidgetAdded(ADVSequenceWidget*))); connect(adv, SIGNAL(si_sequenceWidgetRemoved(ADVSequenceWidget*)), SLOT(sl_sequenceWidgetRemoved(ADVSequenceWidget*))); } ADVSyncViewManager::~ADVSyncViewManager() { delete lockButton; delete syncButton; delete syncMenu; delete lockMenu; delete toggleAutoAnnotationsButton; delete toggleAutoAnnotationsMenu; delete toggleViewButton; delete toggleViewButtonMenu; } void ADVSyncViewManager::updateToolbar1(QToolBar* tb) { if (lockButtonTBAction == NULL) { lockButtonTBAction = tb->addWidget(lockButton); syncButtonTBAction = tb->addWidget(syncButton); } else { tb->addAction(lockButtonTBAction); tb->addAction(syncButtonTBAction); } } void ADVSyncViewManager::updateToolbar2(QToolBar* tb) { if (toggleAutoAnnotationsAction == NULL ) { updateAutoAnnotationActions(); toggleAutoAnnotationsAction = tb->addWidget(toggleAutoAnnotationsButton); } else { tb->addAction(toggleAutoAnnotationsAction); } if (toggleViewButtonAction == NULL) { toggleViewButtonAction = tb->addWidget(toggleViewButton); } else { tb->addAction(toggleViewButtonAction); } } void ADVSyncViewManager::updateEnabledState() { bool enabled = getViewsFromADV().size() > 1; syncButton->setEnabled(enabled); lockButton->setEnabled(enabled); } void ADVSyncViewManager::sl_sequenceWidgetAdded(ADVSequenceWidget* w) { ADVSingleSequenceWidget* sw = qobject_cast(w); if (sw == NULL) { return; } unlock(); if (toggleAutoAnnotationsAction != NULL) { updateAutoAnnotationActions(); } } void ADVSyncViewManager::sl_sequenceWidgetRemoved(ADVSequenceWidget* w) { ADVSingleSequenceWidget* sw = qobject_cast(w); if (sw == NULL) { return; } unlock(); updateAutoAnnotationActions(); } void ADVSyncViewManager::unlock() { foreach(ADVSingleSequenceWidget* sw, views) { sw->getPanView()->disconnect(this); sw->getSequenceSelection()->disconnect(this); } views.clear(); updateEnabledState(); } QList ADVSyncViewManager::getViewsFromADV() const { QList res; foreach(ADVSequenceWidget* w, adv->getSequenceWidgets()) { ADVSingleSequenceWidget* sw = qobject_cast(w); if (sw != NULL) { res.append(sw); } } return res; } void ADVSyncViewManager::sl_rangeChanged() { if (recursion) { return; } recursion = true; PanView* activePan = qobject_cast(sender()); const U2Region& activeRange = activePan->getVisibleRange(); int activeOffset = activePan->getSyncOffset(); foreach(ADVSingleSequenceWidget* sw, views) { PanView* pan = sw->getPanView(); if (pan == activePan) { continue; } int panOffset = pan->getSyncOffset(); int resultOffset = panOffset - activeOffset; qint64 seqLen = pan->getSeqLen(); qint64 newStart = qBound(qint64(0), activeRange.startPos + resultOffset, seqLen); qint64 nVisible = qMin(activeRange.length, seqLen); if (newStart + nVisible > seqLen) { newStart = seqLen - nVisible; } assert(newStart >= 0 && newStart + nVisible <= seqLen); pan->setVisibleRange(U2Region(newStart, nVisible)); } recursion = false; } void ADVSyncViewManager::sl_lock() { QObject* s = sender(); bool buttonClicked = (s == lockButton); SyncMode m = SyncMode_Start; if (lockButton->isChecked()) { unlock(); } else { if (s == lockBySeqSelAction) { m = SyncMode_SeqSel; } else if (s == lockByAnnSelAction) { m = SyncMode_AnnSel; } else if (s == lockButton) { m = detectSyncMode(); } sync(true, m); } if (buttonClicked) { QAction* checkedAction = lockActionGroup->checkedAction(); if (NULL == checkedAction) { toggleCheckedAction(m); } else { checkedAction->toggle(); } lockButton->toggle(); } else { lockButton->setChecked(lockActionGroup->checkedAction() != NULL); } } void ADVSyncViewManager::sl_sync() { QObject* s = sender(); SyncMode m = SyncMode_Start; if (s == syncBySeqSelAction) { m = SyncMode_SeqSel; } else if (s == syncByAnnSelAction) { m = SyncMode_AnnSel; } else if (s == syncButton) { m = detectSyncMode(); } sync(false, m); } void ADVSyncViewManager::sync(bool lock, SyncMode m) { ADVSingleSequenceWidget* focusedW = qobject_cast(adv->getSequenceWidgetInFocus()); if (focusedW == NULL) { return; } QList seqs = getViewsFromADV(); QVector offsets(seqs.size()); //offset here ==> new panview start pos //dOffset is used to keep focused sequence unchanged U2Region focusedRange; int dOffset = 0; for (int i=0; i< seqs.size(); i++ ){ int offset = 0; ADVSingleSequenceWidget* seqW = seqs[i]; switch(m) { case SyncMode_Start: offset = seqW->getVisibleRange().startPos; break; case SyncMode_SeqSel: offset = offsetBySeqSel(seqW);break; case SyncMode_AnnSel: offset = offsetByAnnSel(seqW);break; } offsets[i] = offset; if (seqW == focusedW) { focusedRange = focusedW->getVisibleRange(); dOffset = offset - focusedRange.startPos; } } assert(!focusedRange.isEmpty()); for (int i=0; i< seqs.size(); i++ ){ ADVSingleSequenceWidget* seqW = seqs[i]; int offset = offsets[i] - dOffset; PanView* pan = seqW->getPanView(); if (seqW != focusedW) { pan->setNumBasesVisible(focusedRange.length); pan->setStartPos(offset); } if (lock) { DNASequenceSelection* selection = seqW->getSequenceContext()->getSequenceSelection(); connect(selection, SIGNAL(si_selectionChanged(LRegionsSelection*, const QVector&, const QVector& )), SLOT(sl_onSelectionChanged(LRegionsSelection*, const QVector&, const QVector& )) ); pan->setSyncOffset(offset); connect(pan, SIGNAL(si_visibleRangeChanged()), SLOT(sl_rangeChanged())); views.append(seqW); } } } int ADVSyncViewManager::offsetBySeqSel(ADVSingleSequenceWidget* w) const { DNASequenceSelection* seqSel = w->getSequenceContext()->getSequenceSelection(); if (seqSel->isEmpty()) { return w->getVisibleRange().startPos; } return seqSel->getSelectedRegions().first().startPos; } int ADVSyncViewManager::offsetByAnnSel(ADVSingleSequenceWidget* w) const { int pos = findSelectedAnnotationPos(w); if (pos == -1) { return w->getVisibleRange().startPos; } return pos; } int ADVSyncViewManager::findSelectedAnnotationPos(ADVSingleSequenceWidget* w) const { AnnotationSelection* as = w->getSequenceContext()->getAnnotationsSelection(); const QSet& objs = w->getSequenceContext()->getAnnotationObjects(true); foreach(const AnnotationSelectionData& d , as->getSelection()) { AnnotationTableObject* obj = d.annotation->getGObject(); if (objs.contains(obj)) { return d.annotation->getStrand().isCompementary() ? d.getSelectedRegions().last().endPos() : d.getSelectedRegions().first().startPos; } } return -1; } ADVSyncViewManager::SyncMode ADVSyncViewManager::detectSyncMode() const { ADVSingleSequenceWidget* focusedW = qobject_cast(adv->getSequenceWidgetInFocus()); assert(focusedW != NULL); QList seqs = getViewsFromADV(); //if current sequence + any other sequence have annotation selection -> sync by annotation if (findSelectedAnnotationPos(focusedW) != -1) { foreach(ADVSingleSequenceWidget* sw, seqs) { if (sw != focusedW && findSelectedAnnotationPos(sw) != -1) { return SyncMode_AnnSel; } } } //if current sequence + any other sequence have sequence selection -> sync by annotation if (!focusedW->getSequenceContext()->getSequenceSelection()->isEmpty()) { foreach(ADVSingleSequenceWidget* sw, seqs) { if (sw != focusedW && !sw->getSequenceContext()->getSequenceSelection()->isEmpty()) { return SyncMode_SeqSel; } } } // else sync by start pos return SyncMode_Start; } void ADVSyncViewManager::sl_updateVisualMode() { //if have at least 1 visible -> hide all bool haveVisiblePan = false; bool haveVisibleDet = false; bool haveVisibleView = false; bool haveVisibleOve = false; foreach(ADVSingleSequenceWidget* sw, getViewsFromADV()) { haveVisiblePan = haveVisiblePan || !sw->isPanViewCollapsed(); haveVisibleDet = haveVisibleDet || !sw->isDetViewCollapsed(); haveVisibleView = haveVisibleView || !sw->isViewCollapsed(); haveVisibleOve = haveVisibleOve || !sw->isOverviewCollapsed(); } toggleAllAction->setText(haveVisibleView ? tr("Hide all sequences") : tr("Show all sequences")); togglePanAction->setText(haveVisiblePan ? tr("Hide all zoom views") : tr("Show all zoom views")); toggleDetAction->setText(haveVisibleDet ? tr("Hide all details") : tr("Show all details")); toggleOveAction->setText(haveVisibleOve ? tr("Hide all overviews") : tr("Show all overviews")); } void ADVSyncViewManager::sl_toggleVisualMode() { //if have at least 1 visible -> hide all bool haveVisibleNav= false; bool haveVisiblePan = false; bool haveVisibleDet = false; bool haveVisibleView = false; QList views = getViewsFromADV(); foreach(ADVSingleSequenceWidget* sw, views) { haveVisibleDet = haveVisibleDet || !sw->isDetViewCollapsed(); haveVisibleView = haveVisibleView || !sw->isViewCollapsed(); haveVisiblePan = haveVisiblePan || !sw->isPanViewCollapsed(); haveVisibleNav = haveVisibleNav || !sw->isOverviewCollapsed(); } QObject* s = sender(); foreach(ADVSingleSequenceWidget* sw, views) { if (s == toggleOveAction) { sw->setOverviewCollapsed(haveVisibleNav); } else if (s == togglePanAction) { sw->setPanViewCollapsed(haveVisiblePan); } else if (s == toggleDetAction) { sw->setDetViewCollapsed(haveVisibleDet); } else { sw->setViewCollapsed(haveVisibleView); } } } void ADVSyncViewManager::sl_onSelectionChanged( LRegionsSelection* sel, const QVector& added, const QVector& ) { Q_UNUSED(sel); if (selectionRecursion) { return; } selectionRecursion = true; ADVSingleSequenceWidget* focusedW = qobject_cast(adv->getSequenceWidgetInFocus()); if (focusedW == NULL) { return; } for( int i = 0; i < views.size(); ++i ) { ADVSingleSequenceWidget* w = views[i]; if (w == focusedW) { continue; } int offset = focusedW->getVisibleRange().startPos - w->getVisibleRange().startPos; DNASequenceSelection* selection = w->getSequenceSelection(); selection->clear(); foreach(U2Region r, added) { r.startPos -= offset; if (r.startPos < 0) { r.startPos = 0; } if (r.endPos() > w->getSequenceLen()) { r.length = w->getSequenceLen() - r.startPos; } if(r.length > 0) { selection->addRegion(r); } } } selectionRecursion = false; } void ADVSyncViewManager::toggleCheckedAction( SyncMode mode ) { switch (mode) { case SyncMode_AnnSel: lockByAnnSelAction->toggle(); break; case SyncMode_SeqSel: lockBySeqSelAction->toggle(); break; default: lockByStartPosAction->toggle(); } } void ADVSyncViewManager::updateAutoAnnotationActions() { aaActionMap.clear(); toggleAutoAnnotationsMenu->clear(); foreach (ADVSequenceWidget* w, adv->getSequenceWidgets()) { QList actions = w->getADVSequenceWidgetActions(); foreach (ADVSequenceWidgetAction* action, actions) { AutoAnnotationsADVAction* aaAction = qobject_cast(action); if (aaAction != NULL) { QList aaToggleActions = aaAction->getToggleActions(); foreach( QAction* toggleAction, aaToggleActions) { if (toggleAction->isEnabled()) { aaActionMap.insertMulti(toggleAction->text(), toggleAction); } } } } } toggleAutoAnnotationsButton->setEnabled(!aaActionMap.isEmpty()); QSet actionNames = aaActionMap.keys().toSet(); foreach (const QString& aName, actionNames) { QAction* action = new QAction(toggleAutoAnnotationsMenu); action->setObjectName(aName); connect(action, SIGNAL(triggered()), SLOT(sl_toggleAutoAnnotaionsHighlighting())); toggleAutoAnnotationsMenu->addAction(action); } } #define HAVE_ENABLED_AUTOANNOTATIONS "have_enabled_autoannotations" void ADVSyncViewManager::sl_toggleAutoAnnotaionsHighlighting() { QAction* menuAction = qobject_cast( sender() ); if (menuAction == NULL) { return; } QVariant val = menuAction->property(HAVE_ENABLED_AUTOANNOTATIONS); assert(val.isValid()); bool haveEnabledAutoAnnotations = val.toBool(); QList aaActions = aaActionMap.values(menuAction->objectName()); foreach (QAction* aaAction, aaActions ) { aaAction->setChecked(!haveEnabledAutoAnnotations); } } void ADVSyncViewManager::sl_updateAutoAnnotationsMenu() { QList menuActions = toggleAutoAnnotationsMenu->actions(); foreach (QAction* menuAction, menuActions) { QString aName = menuAction->objectName(); bool haveEnabledAutoAnnotations = false; //if have at least 1 checked -> uncheck all QList aaActions = aaActionMap.values(aName); foreach(QAction* aaAction, aaActions ) { if (aaAction->isChecked()) { haveEnabledAutoAnnotations = true; break; } } if (haveEnabledAutoAnnotations) { menuAction->setText(tr("Hide %1").arg(aName)); } else { menuAction->setText(tr("Show %1").arg(aName)); } menuAction->setProperty(HAVE_ENABLED_AUTOANNOTATIONS,haveEnabledAutoAnnotations); } } }//namespace ugene-1.9.8/src/corelibs/U2View/src/util_ov_annotated_dna/EditAnnotationDialogController.h0000644000175000017500000000342611651544334030443 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_EDIT_ANNOTATION_DIALOG_CONTROLLER_H_ #define _U2_EDIT_ANNOTATION_DIALOG_CONTROLLER_H_ #include "ui/ui_EditAnnotationDialog.h" #include #include namespace U2{ class U2VIEW_EXPORT EditAnnotationDialogController : public QDialog, public Ui_EditAnnotationDialog { Q_OBJECT public: EditAnnotationDialogController(Annotation* a, U2Region _seqRange, QWidget* p = NULL); virtual void accept (); QString getName() const {return currentName;} U2Location getLocation() const {return location;} private slots: void sl_onTextChanged(const QString&); void sl_setPredefinedAnnotationName(); void sl_complementLocation(); private: QMenu* createAnnotationNamesMenu(QWidget* p, QObject* receiver); U2Region seqRange; U2Location location; QString currentName; }; }//ns #endif //_U2_EDIT_ANNOTATION_DIALOG_CONTROLLER_H_ ugene-1.9.8/src/corelibs/U2View/src/util_ov_annotated_dna/ADVUtils.h0000644000175000017500000000427411651544334023774 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_ADV_UTILS_H_ #define _U2_ADV_UTILS_H_ #include #include #include #include namespace U2 { class ADVSequenceWidget; class AnnotatedDNAView; enum ADVGlobalActionFlag { ADVGlobalActionFlag_AddToToolbar = 1 << 1, ADVGlobalActionFlag_AddToAnalyseMenu = 1 << 2, ADVGlobalActionFlag_SingleSequenceOnly = 1 << 3 }; typedef QFlags ADVGlobalActionFlags; class U2VIEW_EXPORT ADVGlobalAction: public GObjectViewAction { Q_OBJECT public: ADVGlobalAction(AnnotatedDNAView* v, const QIcon& icon, const QString& text, int pos = 1000*1000, ADVGlobalActionFlags flags = ADVGlobalActionFlags(ADVGlobalActionFlag_AddToToolbar) | ADVGlobalActionFlag_AddToAnalyseMenu | ADVGlobalActionFlag_SingleSequenceOnly); void addAlphabetFilter(DNAAlphabetType t) {alphabetFilter.insert(t); updateState();}; ADVGlobalActionFlags getFlags() const {return flags;} int getPosition() const {return pos;} private slots: void sl_focusChanged(ADVSequenceWidget*, ADVSequenceWidget*); private: void updateState(); QSet alphabetFilter; int pos; ADVGlobalActionFlags flags; }; } //namespace #endif ugene-1.9.8/src/corelibs/U2View/src/util_ov_annotated_dna/GSequenceLineViewAnnotated.cpp0000644000175000017500000007073011651544334030054 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "GSequenceLineViewAnnotated.h" #include "ADVSequenceObjectContext.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include namespace U2 { #define MIN_ANNOTATION_WIDTH 3 #define MIN_ANNOTATION_TEXT_WIDTH 5 #define MIN_SELECTED_ANNOTATION_WIDTH 4 #define MIN_WIDTH_TO_DRAW_EXTRA_FEATURES 10 GSequenceLineViewAnnotated::GSequenceLineViewAnnotated(QWidget* p, ADVSequenceObjectContext* ctx) : GSequenceLineView(p, ctx) { const QSet aObjs = ctx->getAnnotationObjects(true); foreach(AnnotationTableObject* ao, aObjs) { connectAnnotationObject(ao); } connect(ctx->getAnnotationsSelection(), SIGNAL(si_selectionChanged(AnnotationSelection*, const QList&, const QList& )), SLOT(sl_onAnnotationSelectionChanged(AnnotationSelection*, const QList&, const QList&))); connect(ctx, SIGNAL(si_annotationObjectAdded(AnnotationTableObject*)), SLOT(sl_onAnnotationObjectAdded(AnnotationTableObject*))); connect(ctx, SIGNAL(si_annotationObjectRemoved(AnnotationTableObject*)), SLOT(sl_onAnnotationObjectRemoved(AnnotationTableObject*))); connect(AppContext::getAnnotationsSettingsRegistry(), SIGNAL(si_annotationSettingsChanged(const QStringList&)), SLOT(sl_onAnnotationSettingsChanged(const QStringList&))); } void GSequenceLineViewAnnotated::connectAnnotationObject(AnnotationTableObject* ao) { connect(ao, SIGNAL(si_onAnnotationsAdded(const QList&)), SLOT(sl_onAnnotationsAdded(const QList&))); connect(ao, SIGNAL(si_onAnnotationsRemoved(const QList&)), SLOT(sl_onAnnotationsRemoved(const QList&))); connect(ao, SIGNAL(si_onAnnotationsInGroupRemoved(const QList&, AnnotationGroup*)), SLOT(sl_onAnnotationsInGroupRemoved(const QList&, AnnotationGroup*))); connect(ao, SIGNAL(si_onAnnotationModified(const AnnotationModification&)), SLOT(sl_onAnnotationsModified(const AnnotationModification&))); } void GSequenceLineViewAnnotated::sl_onAnnotationSettingsChanged(const QStringList&) { addUpdateFlags(GSLV_UF_AnnotationsChanged); update(); } void GSequenceLineViewAnnotated::sl_onAnnotationObjectAdded(AnnotationTableObject* o) { connectAnnotationObject(o); sl_onAnnotationsAdded(o->getAnnotations()); } void GSequenceLineViewAnnotated::sl_onAnnotationObjectRemoved(AnnotationTableObject* o) { o->disconnect(this); sl_onAnnotationsRemoved(o->getAnnotations()); } void GSequenceLineViewAnnotated::sl_onAnnotationsAdded(const QList& l) { GTIMER(c2,t2,"GSequenceLineViewAnnotated::sl_onAnnotationsAdded"); registerAnnotations(l); addUpdateFlags(GSLV_UF_AnnotationsChanged); update(); } void GSequenceLineViewAnnotated::sl_onAnnotationsRemoved(const QList& l) { unregisterAnnotations(l); addUpdateFlags(GSLV_UF_AnnotationsChanged); update(); } void GSequenceLineViewAnnotated::sl_onAnnotationsInGroupRemoved(const QList& l, AnnotationGroup*) { /*unregisterAnnotations(l); addUpdateFlags(GSLV_UF_AnnotationsChanged); update();*/ AnnotationTableObject *aobj = static_cast(sender()); // aobj->releaseLocker(); ClearAnnotationsTask *task = new ClearAnnotationsTask(l, aobj, this); AppContext::getTaskScheduler()->registerTopLevelTask(task); } void ClearAnnotationsTask::run() { view->unregisterAnnotations(l); } Task::ReportResult ClearAnnotationsTask::report() { view->addUpdateFlags(GSLV_UF_AnnotationsChanged); view->update(); aobj->releaseLocker(); return ReportResult_Finished; } void GSequenceLineViewAnnotated::sl_onAnnotationSelectionChanged(AnnotationSelection* as, const QList& _added, const QList& _removed) { const QSet aos = ctx->getAnnotationObjects(true); bool changed = false; QList added = ctx->selectRelatedAnnotations(_added); QList removed = ctx->selectRelatedAnnotations(_removed); if (added.size() == 1) { Annotation* a = added.first(); if (aos.contains(a->getGObject())) { const AnnotationSelectionData* asd = as->getAnnotationData(a); ensureVisible(a, asd->locationIdx); changed = true; } } if (!changed) { foreach(Annotation* a, added) { if (aos.contains(a->getGObject()) && isAnnotationVisible(a)) { changed = true; break; } } if (!changed) { foreach(Annotation* a, removed) { if (aos.contains(a->getGObject()) && isAnnotationVisible(a)) { changed = true; break; } } } } if (changed) { addUpdateFlags(GSLV_UF_SelectionChanged); update(); } } bool GSequenceLineViewAnnotated::isAnnotationVisible(Annotation* a) const { foreach(const U2Region& r, a->getRegions()) { if (visibleRange.intersects(r)) { return true; } } return false; } QList GSequenceLineViewAnnotated::selectAnnotationByCoord(const QPoint& p) const { QList res; GSequenceLineViewAnnotatedRenderArea* ra = (GSequenceLineViewAnnotatedRenderArea*)renderArea; AnnotationSettingsRegistry* asr = AppContext::getAnnotationsSettingsRegistry(); int pos = ra->coordToPos(p.x()); int dPos = 0; if (visibleRange.length > renderArea->width()) { float scale = renderArea->getCurrentScale(); dPos = (int) ( 1 / (scale) ); assert(dPos < seqLen); } U2Region reg(pos-dPos, 1 + 2*dPos); const QSet aObjs = ctx->getAnnotationObjects(true); foreach(AnnotationTableObject* ao, aObjs ) { foreach(Annotation* a, ao->getAnnotations()) { QVector location = a->getRegions(); for (int i = 0, n = location.size(); i < n; i++) { const U2Region& l = location[i]; if (l.intersects(reg) || l.endPos() == reg.startPos) { bool ok = true; if (l.endPos() == pos || pos == l.startPos) {//now check pixel precise coords for boundaries int x1 = ra->posToCoord(l.startPos, true); int x2 = ra->posToCoord(l.endPos(), true); ok = p.x() <= x2 && p.x() >= x1; } if (ok) { AnnotationSettings* as = asr->getAnnotationSettings(a); if (as->visible) { U2Region ry = ra->getAnnotationYRange(a, i, as); if (ry.contains(p.y())) { res.append(AnnotationSelectionData(a, i)); } } } } } } } return res; } void GSequenceLineViewAnnotated::mousePressEvent(QMouseEvent * me) { setFocus(); QPoint p = toRenderAreaPoint(me->pos()); Qt::KeyboardModifiers km = QApplication::keyboardModifiers(); bool singleBaseSelectionMode = km.testFlag(Qt::AltModifier); bool annotationEvent = false; // true if mouse pressed in some annotation area if (renderArea->rect().contains(p) && me->button()== Qt::LeftButton && !singleBaseSelectionMode) { bool expandAnnotationSelectionToSequence = me->modifiers().testFlag(Qt::ControlModifier); if (!me->modifiers().testFlag(Qt::ShiftModifier)) { ctx->getAnnotationsSelection()->clear(); } QList selected = selectAnnotationByCoord(p); annotationEvent = !selected.isEmpty(); if (annotationEvent) { AnnotationSelectionData* asd = &selected.first(); if (selected.size() > 1) { AnnotationSettingsRegistry* asr = AppContext::getAnnotationsSettingsRegistry(); QMenu popup; foreach(const AnnotationSelectionData& as, selected) { QVector location = as.annotation->getRegions(); const U2Region& r = location[qMax(0, as.locationIdx)]; QString text = as.annotation->getAnnotationName() + QString(" [%1, %2]").arg(QString::number(r.startPos+1)).arg(QString::number(r.endPos())); AnnotationSettings* asettings = asr->getAnnotationSettings(as.annotation->getAnnotationName()); QIcon icon = GUIUtils::createSquareIcon(asettings->color, 10); popup.addAction(icon, text); } QAction* a = popup.exec(QCursor::pos()); if (a == NULL) { asd = NULL; } else { int idx = popup.actions().indexOf(a); asd = &selected[idx]; } } if (asd != NULL) { //add to annotation selection AnnotationSelection* asel = ctx->getAnnotationsSelection(); if (asel->contains(asd->annotation, asd->locationIdx)) { ctx->getAnnotationsSelection()->removeFromSelection(asd->annotation, asd->locationIdx); } else { ctx->getAnnotationsSelection()->addToSelection(asd->annotation, asd->locationIdx); } //select region if (expandAnnotationSelectionToSequence) { ctx->getSequenceSelection()->clear(); U2Region regionToSelect; foreach(const AnnotationSelectionData& asd, asel->getSelection()) { AnnotationTableObject* aobj = asd.annotation->getGObject(); const QSet aObjs = ctx->getAnnotationObjects(true); if (!aObjs.contains(aobj)) { continue; } U2Region aregion; if (asd.locationIdx == -1) { aregion = U2Region::containingRegion(asd.annotation->getRegions()); } else { aregion = asd.annotation->getRegions().at(asd.locationIdx); } regionToSelect = regionToSelect.length == 0 ? aregion : U2Region::containingRegion(regionToSelect, aregion); } ctx->getSequenceSelection()->addRegion(regionToSelect); } } } } // a hint to parent class: if mouse action leads to annotation selection -> skip selection handling for mouse press ignoreMouseSelectionEvents = annotationEvent; GSequenceLineView::mousePressEvent(me); ignoreMouseSelectionEvents = false; } QString GSequenceLineViewAnnotated::prepareAnnotationText(const Annotation* a, const AnnotationSettings* as) { if (as->nameQuals.isEmpty()) { return a->getAnnotationName(); } QVector qs; foreach(const QString& qn, as->nameQuals) { qs.clear(); a->findQualifiers(qn, qs); if (!qs.isEmpty()) { QString res = qs[0].value; return res; } } return a->getAnnotationName(); } QList GSequenceLineViewAnnotated::findAnnotationsInRange(const U2Region& range) { QList result; const QSet aObjs = ctx->getAnnotationObjects(true); foreach(AnnotationTableObject* ao, aObjs) { foreach (Annotation* a, ao->getAnnotations()) { if (range.intersects(a->getRegions())) { result.append(a); } } } return result; } ////////////////////////////////////////////////////////////////////////// /// Renderer GSequenceLineViewAnnotatedRenderArea::GSequenceLineViewAnnotatedRenderArea(GSequenceLineViewAnnotated* d, bool overlap) : GSequenceLineViewRenderArea(d) { annotationsCanOverlap = overlap; afNormal = new QFont("Courier", 10); afSmall = new QFont("Arial", 8); afmNormal = new QFontMetrics(*afNormal); afmSmall = new QFontMetrics(*afSmall); afNormalCharWidth = afmNormal->width('w'); afSmallCharWidth = afmSmall->width('w'); QLinearGradient gradient(0, 0, 0, 1); //vertical gradient.setCoordinateMode(QGradient::ObjectBoundingMode); gradient.setColorAt(0.00, QColor(255, 255, 255, 120)); gradient.setColorAt(0.50, QColor( 0, 0, 0, 0)); gradient.setColorAt(0.70, QColor( 0, 0, 0, 0)); gradient.setColorAt(1.00, QColor( 0, 0, 0, 70)); gradientMaskBrush = QBrush(gradient); } GSequenceLineViewAnnotatedRenderArea::~GSequenceLineViewAnnotatedRenderArea() { delete afmNormal; delete afNormal; delete afmSmall; delete afSmall; } void GSequenceLineViewAnnotatedRenderArea::drawAnnotations(QPainter& p) { GTIMER(c2,t2,"GSequenceLineViewAnnotatedRenderArea::drawAnnotations"); ADVSequenceObjectContext* ctx = view->getSequenceContext(); QPen pen1(Qt::SolidLine); pen1.setWidth(1); foreach(AnnotationTableObject* ao, ctx->getAnnotationObjects(true)) { foreach(Annotation* a, ao->getAnnotations()) { AnnotationSettingsRegistry* asr = AppContext::getAnnotationsSettingsRegistry(); AnnotationSettings* as = asr->getAnnotationSettings(a->getAnnotationName()); drawAnnotation(p, DrawAnnotationPass_DrawFill, a, pen1, false, as); drawAnnotation(p, DrawAnnotationPass_DrawBorder, a, pen1, false, as); } } } #define FEATURE_ARROW_HLEN 3 #define FEATURE_ARROW_VLEN 3 void static addArrowPath(QPainterPath& path, const QRect& rect, bool leftArrow) { if (rect.width() <= FEATURE_ARROW_HLEN || rect.height() <= 0) { return; } int x = leftArrow ? rect.left() : rect.right(); int dx = leftArrow ? -FEATURE_ARROW_HLEN : FEATURE_ARROW_HLEN; QPolygon arr; arr << QPoint(x - dx, rect.top() - FEATURE_ARROW_VLEN); arr << QPoint(x + dx, rect.top() + rect.height() / 2); arr << QPoint(x - dx, rect.bottom() + FEATURE_ARROW_VLEN); arr << QPoint(x - dx, rect.top() - FEATURE_ARROW_VLEN); QPainterPath arrowPath; arrowPath.addPolygon(arr); QPainterPath dRectPath; dRectPath.addRect(leftArrow ? x : x - (FEATURE_ARROW_HLEN - 1), rect.top(), FEATURE_ARROW_HLEN, rect.height()); path = path.subtracted(dRectPath); path = path.united(arrowPath); } /*#define FEATURE_TRIM_HLEN 5 void static addTrimPath(QPainterPath& path, const QRect& rect, bool leftTrim) { //TODO: normalize line line by 4 if (rect.width() <= FEATURE_TRIM_HLEN || rect.height() <= 0) { return; } int x = leftTrim ? rect.left() - 1: rect.right() + 1; int dx = leftTrim ? -FEATURE_TRIM_HLEN : FEATURE_TRIM_HLEN; float dy = rect.height() / 4.0f; QPolygon arr; arr << QPoint(x , rect.top()-1); arr << QPoint(x - dx, rect.top()-1); arr << QPoint(x , qRound(rect.top() + dy)); arr << QPoint(x - dx, qRound(rect.top() + dy * 2)); arr << QPoint(x , qRound(rect.top() + dy * 3)); arr << QPoint(x - dx, rect.bottom()+1); arr << QPoint(x , rect.bottom()+1); arr << QPoint(x , rect.top()); QPainterPath trimPath; trimPath.addPolygon(arr); path = path.subtracted(trimPath); }*/ void GSequenceLineViewAnnotatedRenderArea::drawAnnotation(QPainter& p, DrawAnnotationPass pass, Annotation* a, const QPen& borderPen, bool selected, const AnnotationSettings* as, U2Region predefinedy) { if (as == NULL) { AnnotationSettingsRegistry* asr = AppContext::getAnnotationsSettingsRegistry(); as = asr->getAnnotationSettings(a->getAnnotationName()); } if (!as->visible && (pass == DrawAnnotationPass_DrawFill || !selected)) { return; } const GSequenceLineViewAnnotated::DrawSettings& drawSettings = getGSequenceLineViewAnnotated()->getDrawSettings(); const U2Region& vr = view->getVisibleRange(); QVector location = a->getRegions(); bool simple = location.size() == 1; for (int ri = 0, ln = location.size(); ri < ln; ri++) { const U2Region& r = location.at(ri); if (!r.intersects(vr) || predefinedy.startPos < 0) { continue; } U2Region visibleLocation = r.intersect(vr); U2Region y = predefinedy.isEmpty() ? getAnnotationYRange(a, ri, as) : predefinedy; if (y.startPos < 0){ continue; } float x1f = posToCoordF(visibleLocation.startPos); float x2f = posToCoordF(visibleLocation.endPos()); assert(x2f >= x1f); int rw = qMax(selected ? MIN_SELECTED_ANNOTATION_WIDTH : MIN_ANNOTATION_WIDTH, qRound(x2f - x1f)); int x1 = qRound(x1f); QRect annotationRect(x1, y.startPos, rw, y.length); QPainterPath rectPath; rectPath.addRect(x1, y.startPos, rw, y.length); bool leftTrim = visibleLocation.startPos != r.startPos; bool rightTrim = visibleLocation.endPos()!= r.endPos(); bool drawArrow = a->getStrand().isCompementary() ? !leftTrim : !rightTrim; if (drawSettings.drawAnnotationArrows && drawArrow ) { addArrowPath(rectPath, annotationRect, a->getStrand().isCompementary()); } /* else { if (leftTrim) { addTrimPath(rectPath, annotationRect, true); } if (rightTrim) { addTrimPath(rectPath, annotationRect, false); } } */ if (pass == DrawAnnotationPass_DrawFill) { rectPath.setFillRule(Qt::WindingFill); p.fillPath(rectPath, as->color); p.fillPath(rectPath, gradientMaskBrush); } else { assert(pass == DrawAnnotationPass_DrawBorder); p.setPen(borderPen); if (rw > MIN_ANNOTATION_WIDTH) { p.drawPath(rectPath); if (drawSettings.drawAnnotationNames && annotationRect.width() >= MIN_ANNOTATION_TEXT_WIDTH) { QString aText = GSequenceLineViewAnnotated::prepareAnnotationText(a, as); drawBoundedText(p, annotationRect, aText); } if (simple && annotationRect.width() > MIN_WIDTH_TO_DRAW_EXTRA_FEATURES) { if (drawSettings.drawCutSites) { QString cutStr = a->findFirstQualifierValue(GBFeatureUtils::QUALIFIER_CUT); bool hasD = false, hasC = false; int cutD = 0, cutC = 0; if (!cutStr.isEmpty()) { int complSplit = cutStr.indexOf('/'); if (complSplit != -1) { cutD = cutStr.left(complSplit).toInt(&hasD); cutC = cutStr.mid(qMin(cutStr.length(), complSplit+1)).toInt(&hasC); } else { cutD = cutStr.toInt(&hasD); cutC = cutD; hasC = hasD; } } if (hasD) { drawCutSite(p, annotationRect, r.startPos + cutD, true); } if (hasC) { drawCutSite(p, annotationRect, r.endPos() - cutC, false); } } } } drawAnnotationConnections(p, a, as); } } } void GSequenceLineViewAnnotatedRenderArea::drawAnnotationsSelection(QPainter& p) { ADVSequenceObjectContext* ctx = view->getSequenceContext(); QPen pen1(Qt::SolidLine); pen1.setWidth(1); QPen pen2(Qt::SolidLine); pen2.setWidth(2); foreach(const AnnotationSelectionData& asd, ctx->getAnnotationsSelection()->getSelection()) { AnnotationTableObject* o = asd.annotation->getGObject(); if (ctx->getAnnotationObjects(true).contains(o)) { if (annotationsCanOverlap) { drawAnnotation(p, DrawAnnotationPass_DrawFill, asd.annotation, pen1, true); } drawAnnotation(p, DrawAnnotationPass_DrawBorder, asd.annotation, pen2, true); } } } void GSequenceLineViewAnnotatedRenderArea::drawBoundedText(QPainter& p, const QRect& r, const QString& text) const { if (afSmallCharWidth > r.width()) { return; } QFont *font = afNormal; QFontMetrics* fm = afmNormal; if (fm->width(text) > r.width()) { font = afSmall; fm = afmSmall; } p.setFont(*font); int len = text.length(); int textWidth = 0, prefixLen = 0; do { int cw = fm->width(text[prefixLen]); if (textWidth + cw > r.width()) { break; } textWidth+=cw; } while (++prefixLen < len); if (prefixLen == 0) { return; } p.drawText(r, Qt::TextSingleLine | Qt::AlignCenter, text.left(prefixLen)); } #define CUT_SITE_HALF_WIDTH 4 #define CUT_SITE_HALF_HEIGHT 2 void GSequenceLineViewAnnotatedRenderArea::drawCutSite(QPainter& p, const QRect& rect, int pos, bool direct) { int xCenter = posToCoord(pos, true); if (xCenter < rect.left() || xCenter > rect.right()) { return; // drawing cut sites out of the annotation region is not supported } int xLeft = xCenter - CUT_SITE_HALF_WIDTH; int xRight= xCenter + CUT_SITE_HALF_WIDTH; int yFlat = direct ? rect.top() - CUT_SITE_HALF_HEIGHT : rect.bottom() + CUT_SITE_HALF_HEIGHT; int yPeak = direct ? rect.top() + CUT_SITE_HALF_HEIGHT : rect.bottom() - CUT_SITE_HALF_HEIGHT; p.drawLine(xLeft, yFlat, xRight, yFlat); p.drawLine(xLeft, yFlat, xCenter, yPeak); p.drawLine(xRight, yFlat, xCenter, yPeak); } #define MAX_VIRTUAL_RANGE 10000 void GSequenceLineViewAnnotatedRenderArea::drawAnnotationConnections(QPainter& p, Annotation* a, const AnnotationSettings* as) { if (a->getLocation()->isSingleRegion()) { return; } if (U2AnnotationUtils::isSplitted(a->getLocation(), getGSequenceLineViewAnnotated()->getSequenceRange())) { return; } const GSequenceLineViewAnnotated::DrawSettings& drawSettings = getGSequenceLineViewAnnotated()->getDrawSettings(); const U2Region& visibleRange = view->getVisibleRange(); int dx1 = 0; int dx2 = 0; if (drawSettings.drawAnnotationArrows) { if (a->getStrand().isCompementary()) { dx2 = - FEATURE_ARROW_HLEN; } else { dx1 = FEATURE_ARROW_HLEN; } } QVector location = a->getRegions(); for (int ri = 0, ln = location.size(); ri < ln; ri++) { const U2Region& r = location.at(ri); //U2Region y = getAnnotationYRange(a, ri, as); if (ri > 0) { U2Region prev = location.at(ri - 1); int prevPos = prev.endPos(); int pos = r.startPos; int min = qMin(prevPos, pos); int max = qMax(prevPos, pos); if (visibleRange.intersects(U2Region(min, max-min))) { int x1 = posToCoord(prevPos, true) + dx1; int x2 = posToCoord(pos, true) + dx2; if (qAbs(x2-x1) > 1) { x1 = qBound(-MAX_VIRTUAL_RANGE, x1, MAX_VIRTUAL_RANGE); //qt4.4 crashes in line clipping alg for extremely large X values x2 = qBound(-MAX_VIRTUAL_RANGE, x2, MAX_VIRTUAL_RANGE); int midX = (x1 + x2) / 2; U2Region pyr = getAnnotationYRange(a, ri - 1, as); U2Region yr = getAnnotationYRange(a, ri, as); int y1 = pyr.startPos; int dy1 = pyr.length/2; int y2 = yr.startPos; int dy2 = yr.length/2; int midY = qMin(y1, y2); p.drawLine(x1, y1+dy1, midX, midY); p.drawLine(midX, midY, x2, y2+dy2); } } } } } void GSequenceLineViewAnnotated::ensureVisible(Annotation* a, int locationIdx) { QVector location = a->getRegions(); assert(locationIdx < location.size()); if (locationIdx == -1) { foreach(const U2Region& r, location) { if (visibleRange.intersects(r)) { return; } } } const U2Region& region = location[qMax(0, locationIdx)]; if (!visibleRange.intersects(region)) { qint64 pos = a->getStrand().isCompementary() ? region.endPos() : region.startPos; setCenterPos(qBound(qint64(0), pos, seqLen-1)); } } bool GSequenceLineViewAnnotated::event(QEvent* e) { if (e->type() == QEvent::ToolTip) { QHelpEvent* he = static_cast(e); QString tip = createToolTip(he); if (!tip.isEmpty()) { QToolTip::showText(he->globalPos(), tip); } return true; } return GSequenceLineView::event(e); } QString GSequenceLineViewAnnotated::createToolTip(QHelpEvent* e) { const int ROWS_LIMIT = 25; QList la = selectAnnotationByCoord(e->pos()); if (la.isEmpty()) return QString(); QString tip = ""; int rows = 0; if (la.size() > 1) { foreach(AnnotationSelectionData ad, la) { rows += ad.annotation->getQualifiers().size() + 1; } } bool skipDetails = rows > ROWS_LIMIT; rows = 0; foreach(AnnotationSelectionData ad, la) { if (++rows > ROWS_LIMIT) break; QString aname = ad.annotation->getAnnotationName(); QColor acl = AppContext::getAnnotationsSettingsRegistry()->getAnnotationSettings(aname)->color; tip += ""; //if (ad.annotation->getQualifiers().size() !=0) { if (skipDetails) { tip += ""; rows++; } else { tip += ""; tip += ""; rows += ad.annotation->getQualifiers().size(); } } } tip += "
    "+aname+"
    ...
    Location = " + Genbank::LocationParser::buildLocationString(ad.annotation->data()) + "
    "; tip += ad.annotation->getQualifiersTip(ROWS_LIMIT - rows, getSequenceObject(), ctx->getComplementTT(), ctx->getAminoTT()); tip += "
    "; if (rows > ROWS_LIMIT) { tip += "


    "+tr("etc ...")+"
    "; } return tip; } void GSequenceLineViewAnnotated::sl_onAnnotationsModified( const AnnotationModification& md ) { if (md.type == AnnotationModification_LocationChanged || md.type == AnnotationModification_NameChanged ) { addUpdateFlags(GSLV_UF_AnnotationsChanged); update(); } } bool GSequenceLineViewAnnotatedRenderArea::isAnnotationSelectionInVisibleRange() const { const QSet aos = view->getSequenceContext()->getAnnotationObjects(true); AnnotationSelection* as = view->getSequenceContext()->getAnnotationsSelection(); foreach(const AnnotationSelectionData& asd, as->getSelection()) { if (!aos.contains(asd.annotation->getGObject())) { continue; } if (getGSequenceLineViewAnnotated()->isAnnotationVisible(asd.annotation)) { return true; } } return false; } } // namespace ugene-1.9.8/src/corelibs/U2View/src/util_ov_annotated_dna/ADVAnnotationCreation.cpp0000644000175000017500000001115011651544334027015 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "ADVAnnotationCreation.h" #include "AnnotatedDNAView.h" #include "ADVSequenceObjectContext.h" #include "AnnotationsTreeView.h" #include #include //for CreateAnnotationModel #include #include #include #include #include #include #include #include #include #include namespace U2 { ADVCreateAnnotationsTask::ADVCreateAnnotationsTask(AnnotatedDNAView* _ctx, const GObjectReference& aobjRef, const QString& group, const QList& data) : Task(tr("Create annotations task"), TaskFlags_NR_FOSCOE), ctx(_ctx) { LoadUnloadedDocumentTask::addLoadingSubtask(this, LoadDocumentTaskConfig(true, aobjRef, new LDTObjectFactory(this))); t = new CreateAnnotationsTask(aobjRef, group, data); addSubTask(t); } Task::ReportResult ADVCreateAnnotationsTask::report() { if (!hasError() && !ctx.isNull()) { Annotation* a = t->getAnnotations().first(); assert(a!=NULL); AnnotationTableObject* ao = a->getGObject(); if (!ctx->getAnnotationObjects().contains(ao)) { //for documents loaded during annotation creation object is added here QString err = ctx->addObject(ao); if (!err.isEmpty()) { setError(err); } } if (!hasError()) { ctx->getAnnotationsSelection()->clear(); ctx->getAnnotationsSelection()->addToSelection(a); } } return ReportResult_Finished; } ////////////////////////////////////////////////////////////////////////// /// ADVAnnotationCreation ADVAnnotationCreation::ADVAnnotationCreation(AnnotatedDNAView* c) : QObject(c) { ctx = c; createAction = new QAction(QIcon(":core/images/create_annotation_icon.png"), tr("New annotation..."), this); createAction->setObjectName("create_annotation_action"); createAction->setShortcut(QKeySequence(Qt::CTRL | Qt::Key_N)); createAction->setShortcutContext(Qt::WindowShortcut); connect(createAction, SIGNAL(triggered()), SLOT(sl_createAnnotation())); } void ADVAnnotationCreation::sl_createAnnotation() { ADVSequenceObjectContext* seqCtx = ctx->getSequenceInFocus(); assert(seqCtx!=NULL); CreateAnnotationModel m; m.useUnloadedObjects = true; m.sequenceObjectRef = GObjectReference(seqCtx->getSequenceObject()); m.sequenceLen = seqCtx->getSequenceObject()->getSequenceLen(); if (!seqCtx->getSequenceSelection()->isEmpty()) { m.data->location->regions << seqCtx->getSequenceSelection()->getSelectedRegions(); } //setup default object and group if possible from AnnotationsTreeView AnnotationsTreeView* tv = ctx->getAnnotationsView(); AVItem* ai = tv->currentItem(); if (ai!=NULL && !ai->isReadonly()) { AnnotationTableObject* aobj = ai->getAnnotationTableObject(); if (seqCtx->getAnnotationGObjects().contains(aobj)) { m.annotationObjectRef = aobj; AnnotationGroup* ag = ai->getAnnotationGroup(); if (ag!=aobj->getRootGroup()) { m.groupName = ag->getGroupPath(); } } } CreateAnnotationDialog d(ctx->getWidget(), m); int rc = d.exec(); if (rc != QDialog::Accepted) { return; } QList data; data << m.data; ADVCreateAnnotationsTask* t = new ADVCreateAnnotationsTask(ctx, m.annotationObjectRef, m.groupName, data); AppContext::getTaskScheduler()->registerTopLevelTask(t); } } // namespace ugene-1.9.8/src/corelibs/U2View/src/util_ov_annotated_dna/AnnotatedDNAViewFactory.h0000644000175000017500000000314611651544334026761 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_ANNOTATED_DNA_VIEW_FACTORY_H_ #define _U2_ANNOTATED_DNA_VIEW_FACTORY_H_ #include namespace U2 { class MultiGSelection; class U2VIEW_EXPORT AnnotatedDNAViewFactory : public GObjectViewFactory { Q_OBJECT public: AnnotatedDNAViewFactory(); virtual bool canCreateView(const MultiGSelection& multiSelection); virtual Task* createViewTask(const MultiGSelection& multiSelection, bool single = false); virtual bool isStateInSelection(const MultiGSelection& multiSelection, const QVariantMap& stateData); virtual Task* createViewTask(const QString& viewName, const QVariantMap& stateData); virtual bool supportsSavedStates() const {return true;} static const GObjectViewFactoryId ID; }; } // namespace #endif ugene-1.9.8/src/corelibs/U2View/src/util_ov_annotated_dna/ADVSequenceWidget.h0000644000175000017500000000645211651544334025610 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_ADV_SEQUENCE_WIDGET_H_ #define _U2_ADV_SEQUENCE_WIDGET_H_ #include #include #include #include namespace U2 { class AnnotatedDNAView; class DNASequenceObject; class DNASequenceSelection; class ADVSequenceWidgetAction; class ADVSequenceObjectContext; class GObject; class U2VIEW_EXPORT ADVSequenceWidget : public QWidget { Q_OBJECT public: ADVSequenceWidget(AnnotatedDNAView* ctx); AnnotatedDNAView* getAnnotatedDNAView() const {return ctx;} virtual QList getSequenceObjects() const; virtual QList getSequenceContexts() const {return seqContexts;} /** actions associated with this block. Automatically deleted with block*/ virtual void addADVSequenceWidgetAction(ADVSequenceWidgetAction* action); ADVSequenceWidgetAction* getADVSequenceWidgetAction(const QString& objName) const; QList getADVSequenceWidgetActions() const { return wActions; } virtual ADVSequenceObjectContext* getActiveSequenceContext() const = 0; virtual void centerPosition(int pos, QWidget* skipView = NULL) = 0; virtual void buildPopupMenu(QMenu& m); //TODO: replace with GObjectViewObjectHandler virtual bool isWidgetOnlyObject(GObject* o) const { Q_UNUSED(o); return false;} virtual void updateState(const QVariantMap& m) {Q_UNUSED(m);} virtual void saveState(QVariantMap& m) {Q_UNUSED(m);} virtual U2Region getVisibleRange() const = 0; virtual void setVisibleRange(const U2Region& r) = 0; virtual int getNumBasesVisible() const = 0; virtual void setNumBasesVisible(int n) = 0; virtual void onSequenceObjectRenamed(const QString& oldName) = 0; signals: void si_sequenceObjectAdded(DNASequenceObject*); void si_sequenceObjectRemoved(DNASequenceObject* ); protected: AnnotatedDNAView* ctx; QList seqContexts; QList wActions; }; class U2VIEW_EXPORT ADVSequenceWidgetAction : public QAction { Q_OBJECT public: ADVSequenceWidgetAction(const QString& objName, const QString& text) : QAction(text, NULL), addToBar(false), addToMenu(false), seqWidget(NULL) { setObjectName(objName); } bool addToBar; bool addToMenu; QString afterMenu; ADVSequenceWidget* seqWidget; }; }//namespace #endif ugene-1.9.8/src/corelibs/U2View/src/util_ov_annotated_dna/CreateRulerDialogController.h0000644000175000017500000000307111651544334027734 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_CREATE_RULER_DIALOG_CONTROLLER_H_ #define _U2_CREATE_RULER_DIALOG_CONTROLLER_H_ #include #include #include #include namespace U2 { class U2VIEW_EXPORT CreateRulerDialogController : public QDialog, public Ui_CreateRulerDialog { Q_OBJECT public: CreateRulerDialogController(const QSet& namesToFilter, const U2Region& range, int offset = -1, QWidget* p=NULL); virtual void accept (); private slots: void sl_colorButtonClicked(); private: void updateColorSample(); public: QString name; int offset; QColor color; QSet filter; }; }// namespace #endif ugene-1.9.8/src/corelibs/U2View/src/util_ov_annotated_dna/ADVAnnotationCreation.h0000644000175000017500000000351511651544334026470 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_ADVANNOTATION_CREATION_H_ #define _U2_ADVANNOTATION_CREATION_H_ #include #include #include #include namespace U2 { class CreateAnnotationsTask; class AnnotatedDNAView; class DNASequenceObject; class U2VIEW_EXPORT ADVAnnotationCreation : public QObject { Q_OBJECT public: ADVAnnotationCreation(AnnotatedDNAView* v); QAction* getCreateAnnotationAction() const {return createAction;} private slots: void sl_createAnnotation(); private: AnnotatedDNAView* ctx; QAction* createAction; }; class U2VIEW_EXPORT ADVCreateAnnotationsTask : public Task { Q_OBJECT public: ADVCreateAnnotationsTask(AnnotatedDNAView* _ctx, const GObjectReference& aobjRef, const QString& group, const QList& data); ReportResult report(); private: QPointer ctx; CreateAnnotationsTask* t; }; } // namespace #endif ugene-1.9.8/src/corelibs/U2View/src/util_ov_annotated_dna/ADVGraphModel.h0000644000175000017500000001043211651544334024707 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_AVD_GRAPH_MODEL_H_ #define _U2_AVD_GRAPH_MODEL_H_ #include #include #include #include namespace U2 { class DNASequenceObject; class GSequenceGraphData; class GSequenceGraphWindowData; class GSequenceGraphView; //BUG:402: refactor to remove cross references in structures! class U2VIEW_EXPORT GSequenceGraphAlgorithm { public: virtual ~GSequenceGraphAlgorithm(){} virtual void calculate(QVector& res, DNASequenceObject* o, const U2Region& r, const GSequenceGraphWindowData* d) = 0; }; class U2VIEW_EXPORT GSequenceGraphWindowData { public: GSequenceGraphWindowData() : step(0), window(0){} GSequenceGraphWindowData(int _step, int w) : step(_step), window(w){} virtual ~GSequenceGraphWindowData(){}; int step; int window; }; class U2VIEW_EXPORT GSequenceGraphMinMaxCutOffData { public: GSequenceGraphMinMaxCutOffData() : min(0.0), max(0.0), enableCuttoff(false) {} GSequenceGraphMinMaxCutOffData(double _min, double _max, bool _enableCuttoff) : min(_min), max(_max), enableCuttoff(_enableCuttoff){} virtual ~GSequenceGraphMinMaxCutOffData(){}; double min; double max; bool enableCuttoff; }; struct PairVector { QVector firstPoints; //max if use both QVector secondPoints; bool useIntervals; }; class U2VIEW_EXPORT GSequenceGraphDrawer : public QObject{ Q_OBJECT public: GSequenceGraphDrawer(GSequenceGraphView* v, const GSequenceGraphWindowData& wd); virtual ~GSequenceGraphDrawer(); virtual void draw(QPainter& p, GSequenceGraphData* d, const QRect& rect); virtual void showSettingsDialog(); const GSequenceGraphWindowData& getWindowData() {return wdata;} const GSequenceGraphMinMaxCutOffData& getCutOffData() {return commdata;} protected: void calculatePoints(GSequenceGraphData* d, PairVector& points, float& min, float& max, int numPoints); // calculates points (> visual area size) and fits the result into visual size void calculateWithFit(GSequenceGraphData* d, PairVector& points, int alignedStart, int alignedEnd); // calculates points (< visual area size) and expands points to fill all visual area size void calculateWithExpand(GSequenceGraphData* d, PairVector& points, int alignedStart, int alignedEnd); protected: GSequenceGraphView* view; QFont* defFont; GSequenceGraphWindowData wdata; GSequenceGraphMinMaxCutOffData commdata; }; class U2VIEW_EXPORT GSequenceGraphData { public: GSequenceGraphData(const QString& _graphName); virtual ~GSequenceGraphData(); QString graphName; GSequenceGraphAlgorithm* ga; int cachedFrom, cachedLen, cachedW, cachedS; int alignedFC, alignedLC; PairVector cachedData; }; class U2VIEW_EXPORT GSequenceGraphUtils { public: static int getNumSteps(const U2Region& range, int w, int s); static void fitToScreen(const QVector& data, int dataStartBase, int dataEndBase, QVector& results, int resultStartBase, int resultEndBase, int screenWidth, float unknownVal); static float calculateAverage(const QVector& data, float start, float range); static void calculateMinMax(const QVector& data, float& min, float& max); }; } // namespace #endif ugene-1.9.8/src/corelibs/U2View/src/util_ov_annotated_dna/AnnotationsTreeViewL.cpp0000644000175000017500000033070411651544334026760 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "AnnotationsTreeViewL.h" #include "AnnotatedDNAView.h" #include "ADVConstants.h" #include "ADVSequenceObjectContext.h" #include "EditAnnotationDialogController.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include /* TRANSLATOR U2::AnnotationsTreeView */ namespace U2 { class TreeSorter { public: TreeSorter(AnnotationsTreeViewL* t) : w(t) { w->setSortingEnabled(false); } virtual ~TreeSorter() { w->setSortingEnabled(true); } AnnotationsTreeViewL* w; }; #define SETTINGS_ROOT QString("view_adv/annotations_tree_view/") #define COLUMN_SIZES QString("columnSizes") const QString AnnotationsTreeViewL::annotationMimeType = "application/x-annotations-and-groups"; AnnotationsTreeViewL::AnnotationsTreeViewL(AnnotatedDNAView* _ctx) : ctx(_ctx){ lastMB = Qt::NoButton; lastClickedColumn = 0; tree = new LazyTreeView(this); LazyAnnotationTreeViewModel *model = new LazyAnnotationTreeViewModel(); tree->setObjectName("tree_widget"); tree->setModel(model); //tree->setSortingEnabled(true); //tree->sortItems(0, Qt::AscendingOrder); tree->setColumnCount(2); headerLabels << tr("Name") << tr("Value"); tree->setHeaderLabels(headerLabels); tree->setHeaderHidden(false); //tree->header()->setStretchLastSection(true); tree->setUniformRowHeights(true); tree->setSelectionMode(QAbstractItemView::ExtendedSelection); tree->viewport()->installEventFilter(this); tree->setMouseTracking(true); tree->setAutoScroll(false); //tree->setNumberOfItems(); connect(tree, SIGNAL(itemEntered(QTreeWidgetItem*, int)), SLOT(sl_itemEntered(QTreeWidgetItem*, int))); connect(tree, SIGNAL(itemClicked(QTreeWidgetItem*, int)), SLOT(sl_itemClicked(QTreeWidgetItem*, int))); connect(tree, SIGNAL(itemDoubleClicked(QTreeWidgetItem*, int)), SLOT(sl_itemDoubleClicked(QTreeWidgetItem*, int))); connect(tree, SIGNAL(itemExpanded(QTreeWidgetItem*)), SLOT(sl_itemExpanded(QTreeWidgetItem*))); connect(tree, SIGNAL(itemCollapsed(QTreeWidgetItem*)), SLOT(sl_itemCollapsed(QTreeWidgetItem*))); //connect(tree, SIGNAL(itemActivated(QTreeWidgetItem*, int)), SLOT(sl_itemActivated(QTreeWidgetItem*, int))); QVBoxLayout *layout = new QVBoxLayout(); layout->setMargin(0); layout->addWidget(tree); setLayout(layout); restoreWidgetState(); connect(ctx, SIGNAL(si_buildPopupMenu(GObjectView*, QMenu*)), SLOT(sl_onBuildPopupMenu(GObjectView*, QMenu*))); connect(ctx, SIGNAL(si_annotationObjectAdded(AnnotationTableObject*)), SLOT(sl_onAnnotationObjectAdded(AnnotationTableObject*))); connect(ctx, SIGNAL(si_annotationObjectRemoved(AnnotationTableObject*)), SLOT(sl_onAnnotationObjectRemoved(AnnotationTableObject*))); foreach(AnnotationTableObject* obj, ctx->getAnnotationObjects()) { sl_onAnnotationObjectAdded(obj); } connectAnnotationSelection(); connectAnnotationGroupSelection(); connect(tree, SIGNAL(itemSelectionChanged()), SLOT(sl_onItemSelectionChanged())); connect(AppContext::getAnnotationsSettingsRegistry(), SIGNAL(si_annotationSettingsChanged(const QStringList&)), SLOT(sl_onAnnotationSettingsChanged(const QStringList&))); #define SORT_INTERVAL 500 sortTimer.setInterval(SORT_INTERVAL); sortTimer.setSingleShot(true); connect(&sortTimer, SIGNAL(timeout()), SLOT(sl_sortTree())); addColumnIcon = QIcon(":core/images/add_column.png"); removeColumnIcon = QIcon(":core/images/remove_column.png"); addAnnotationObjectAction = new QAction(tr("Objects with annotations..."), this); connect(addAnnotationObjectAction, SIGNAL(triggered()), SLOT(sl_onAddAnnotationObjectToView())); removeObjectsFromViewAction = new QAction(tr("Selected objects with annotations from view"), this); removeObjectsFromViewAction->setShortcut(QKeySequence(Qt::SHIFT| Qt::Key_Delete)); removeObjectsFromViewAction->setShortcutContext(Qt::WidgetShortcut); connect(removeObjectsFromViewAction, SIGNAL(triggered()), SLOT(sl_removeObjectFromView())); tree->addAction(removeObjectsFromViewAction); removeAnnsAndQsAction = new QAction(tr("Selected annotations and qualifiers"), this); removeAnnsAndQsAction->setShortcut(QKeySequence(Qt::Key_Delete)); removeAnnsAndQsAction->setShortcutContext(Qt::WindowShortcut); connect(removeAnnsAndQsAction, SIGNAL(triggered()), SLOT(sl_removeAnnsAndQs())); tree->addAction(removeAnnsAndQsAction); copyQualifierAction = new QAction(tr("Copy qualifier text"), this); connect(copyQualifierAction, SIGNAL(triggered()), SLOT(sl_onCopyQualifierValue())); copyQualifierURLAction = new QAction(tr("Copy qualifier URL"), this); connect(copyQualifierURLAction, SIGNAL(triggered()), SLOT(sl_onCopyQualifierURL())); toggleQualifierColumnAction = new QAction(tr("Toggle column"), this); connect(toggleQualifierColumnAction, SIGNAL(triggered()), SLOT(sl_onToggleQualifierColumn())); removeColumnByHeaderClickAction = new QAction(tr("Hide column"), this); removeColumnByHeaderClickAction->setIcon(removeColumnIcon); connect(removeColumnByHeaderClickAction, SIGNAL(triggered()), SLOT(sl_onRemoveColumnByHeaderClick())); copyColumnTextAction = new QAction(tr("Copy column text"), this); connect(copyColumnTextAction, SIGNAL(triggered()), SLOT(sl_onCopyColumnText())); copyColumnURLAction = new QAction(tr("copy column URL"), this); connect(copyColumnURLAction, SIGNAL(triggered()), SLOT(sl_onCopyColumnURL())); renameAction = new QAction(tr("Edit item"), this); renameAction->setShortcut(QKeySequence(Qt::Key_F2)); renameAction->setShortcutContext(Qt::WidgetShortcut); connect(renameAction, SIGNAL(triggered()), SLOT(sl_rename())); tree->addAction(renameAction); editAction = new QAction(tr("Edit qualifier"), this); editAction->setShortcut(QKeySequence(Qt::Key_F4)); editAction->setShortcutContext(Qt::WidgetShortcut); connect(editAction, SIGNAL(triggered()), SLOT(sl_edit())); tree->addAction(editAction); viewAction = new QAction(tr("View qualifier"), this); viewAction->setShortcut(QKeySequence(Qt::Key_F3)); viewAction->setShortcutContext(Qt::WidgetShortcut); connect(viewAction, SIGNAL(triggered()), SLOT(sl_edit())); tree->addAction(viewAction); addQualifierAction = new QAction(tr("U2Qualifier..."), this); addQualifierAction->setShortcut(QKeySequence(Qt::Key_Insert)); addQualifierAction->setShortcutContext(Qt::WindowShortcut); connect(addQualifierAction, SIGNAL(triggered()), SLOT(sl_addQualifier())); tree->addAction(addQualifierAction); /* cutAnnotationsAction = new QAction(tr("cut_annotations"), this); // cutAnnotationsAction->setShortcut(QKeySequence(Qt::K)); connect(cutAnnotationsAction, SIGNAL(triggered()), SLOT(sl_cutAnnotations)); tree->addAction(cutAnnotationsAction); copyAnnotationsAction = new QAction(tr("copy_annotations"), this); // copyAnnotationsAction->setShortcut(QKeySequence(Qt::K)); connect(copyAnnotationsAction, SIGNAL(triggered()), SLOT(sl_copyAnnotations)); tree->addAction(copyAnnotationsAction); pasteAnnotationsAction = new QAction(tr("paste_annotations"), this); // pasteAnnotationsAction->setShortcut(QKeySequence(Qt::K)); connect(pasteAnnotationsAction, SIGNAL(triggered()), SLOT(sl_pasteAnnotations)); tree->addAction(pasteAnnotationsAction);*/ updateState(); isDragging = false; resetDragAndDropData(); tree->setAcceptDrops(true); renameFlag = false; } void AnnotationsTreeViewL::restoreWidgetState() { QStringList geom = AppContext::getSettings()->getValue(SETTINGS_ROOT + COLUMN_SIZES, QStringList()).toStringList(); if (geom.isEmpty()) { tree->setColumnWidth(0, 300); tree->setColumnWidth(1, 300); } else { for (int i=0;isetColumnWidth(i, width); } } } } void AnnotationsTreeViewL::saveWidgetState() { QStringList geom; for (int i=0; i < tree->model()->columnCount(); i++) { QString s = QString::number(tree->columnWidth(i)); geom.append(s); } AppContext::getSettings()->setValue(SETTINGS_ROOT+COLUMN_SIZES, geom); } AVGroupItemL* AnnotationsTreeViewL::findGroupItem(const AnnotationGroup* g) const { GTIMER(c2,t2,"AnnotationsTreeView::findGroupItem"); if (g->getParentGroup() == NULL) { LazyAnnotationTreeViewModel *model = static_cast(tree->model()); AVItemL *root = model->getItem(QModelIndex()); for(int i = 0; i < root->childCount(); i++) { AVGroupItemL* item = static_cast(root->child(i)); if(item->group == g) { return item; } } } else { AVGroupItemL* parentGroupItem = findGroupItem(g->getParentGroup()); if (parentGroupItem != NULL) { for(int i = 0, n = parentGroupItem->childCount(); i < n; i++) { AVItemL* item = static_cast(parentGroupItem->child(i)); if (item->type != AVItemType_Group) { continue; } AVGroupItemL* gItem = static_cast(item); if (gItem->group == g) { return gItem; } } } } return NULL; } AVAnnotationItemL* AnnotationsTreeViewL::findAnnotationItem(const AVGroupItemL* groupItem, const Annotation* a) const { GTIMER(c2,t2,"AnnotationsTreeView::findAnnotationItem"); for(int i = 0, n = groupItem->childCount(); i < n; i++) { AVItemL* item = static_cast(groupItem->child(i)); if (item->type != AVItemType_Annotation) { continue; } AVAnnotationItemL* aItem = static_cast(item); if (aItem->annotation == a) { return aItem; } } return NULL; } AVAnnotationItemL* AnnotationsTreeViewL::findAnnotationItem(const AnnotationGroup* g, const Annotation* a) const { AVGroupItemL* groupItem = findGroupItem(g); if (groupItem == NULL) { return NULL; } return findAnnotationItem(groupItem, a); } /** This method is optimized to use annotation groups. So can only be used for annotations that belongs to some object */ QList AnnotationsTreeViewL::findAnnotationItems(const Annotation* a) const { assert(a->getGObject() != NULL && ctx->getAnnotationObjects().contains(a->getGObject())); QList res; foreach(AnnotationGroup* g, a->getGroups()) { AVGroupItemL* gItem = findGroupItem(g); if(gItem == NULL) { return QList(); } AVAnnotationItemL* aItem = findAnnotationItem(gItem, a); res.append(aItem); } return res; } void AnnotationsTreeViewL::connectAnnotationSelection() { connect(ctx->getAnnotationsSelection(), SIGNAL(si_selectionChanged(AnnotationSelection*, const QList&, const QList& )), SLOT(sl_onAnnotationSelectionChanged(AnnotationSelection*, const QList&, const QList&))); } void AnnotationsTreeViewL::connectAnnotationGroupSelection() { connect(ctx->getAnnotationsGroupSelection(), SIGNAL(si_selectionChanged(AnnotationGroupSelection*, const QList&, const QList& )), SLOT(sl_onAnnotationGroupSelectionChanged(AnnotationGroupSelection*, const QList&, const QList&))); } void AnnotationsTreeViewL::sl_onItemSelectionChanged() { AnnotationSelection* as = ctx->getAnnotationsSelection(); as->disconnect(this); as->clear(); AnnotationGroupSelection* ags = ctx->getAnnotationsGroupSelection(); ags->disconnect(this); ags->clear(); QList items = tree->selectedItems(); foreach(QTreeWidgetItem* i, items) { AVItemL* item = static_cast(i); if (item->type == AVItemType_Annotation) { AVAnnotationItemL* aItem = static_cast(item); assert(aItem->annotation!=NULL); assert(aItem->annotation->getGObject()!=NULL); as->addToSelection(aItem->annotation); } else if (item->type == AVItemType_Group) { AVGroupItemL* gItem = static_cast(item); assert(gItem->group!=NULL); ags->addToSelection(gItem->group); } } connectAnnotationSelection(); connectAnnotationGroupSelection(); updateState(); } void AnnotationsTreeViewL::sl_onAnnotationSelectionChanged(AnnotationSelection*, const QList& added, const QList& removed) { tree->disconnect(this, SIGNAL(sl_onItemSelectionChanged())); foreach(Annotation* a, removed) { foreach(AnnotationGroup* g, a->getGroups()) { AVAnnotationItemL* item = findAnnotationItem(g, a); if (item && item->isSelected()) { item->setSelected(false); } } } AVAnnotationItemL* toVisible = NULL; QList selectedItems; if(added.size() > 0 && !findAnnotationItem(added.first()->getGroups().first(), added.first())) { focusOnItem(added.first()); } foreach(Annotation* a, added) { foreach(AnnotationGroup* g, a->getGroups()) { AVAnnotationItemL* item = findAnnotationItem(g, a); if (!item->isSelected()) { item->setSelected(true); selectedItems.append(item); /*for (QTreeWidgetItem* p = item->parent(); p!=NULL; p = p->parent()) { if (!p->isExpanded()) { p->setExpanded(true); } }*/ } toVisible = item; } } if( !selectedItems.isEmpty() ) { tree->setCurrentItem(selectedItems.first()); } connect(tree, SIGNAL(itemSelectionChanged()), SLOT(sl_onItemSelectionChanged ())); //make item visible if special conditions are met if (toVisible != NULL && added.size() == 1) { tree->scrollToItem(toVisible, QAbstractItemView::EnsureVisible); } updateState(); } void AnnotationsTreeViewL::sl_onAnnotationGroupSelectionChanged(AnnotationGroupSelection* s, const QList& added, const QList& removed) { Q_UNUSED(s); foreach(AnnotationGroup* g, removed) { AVGroupItemL* item = findGroupItem(g); if (item->isSelected()) { item->setSelected(false); } } foreach(AnnotationGroup* g, added) { AVGroupItemL* item = findGroupItem(g); if (!item->isSelected()) { item->setSelected(true); } } if (added.size() == 1) { AVGroupItemL* item = findGroupItem(added.first()); tree->scrollToItem(item, QAbstractItemView::EnsureVisible); } } void AnnotationsTreeViewL::sl_onAnnotationObjectAdded(AnnotationTableObject* obj) { GTIMER(c2,t2,"AnnotationsTreeView::sl_onAnnotationObjectAdded"); TreeSorter ts(this); assert(findGroupItem(obj->getRootGroup()) == NULL); LazyAnnotationTreeViewModel *model = static_cast(tree->model()); AVGroupItemL *root = (AVGroupItemL*)model->getItem(QModelIndex()); AVGroupItemL* groupItem = createGroupItem(root, obj->getRootGroup()); if(tree->lineHeight == 1) { //tree->lineHeight = tree->rowHeight(model->guessIndex(groupItem)); tree->setLineHeight(tree->rowHeight(tree->guessIndex(groupItem))); } tree->calculateIndex(obj); tree->realNumberOfItems++; tree->updateSlider(); connect(obj, SIGNAL(si_onAnnotationsAdded(const QList&)), SLOT(sl_onAnnotationsAdded(const QList&))); connect(obj, SIGNAL(si_onAnnotationsRemoved(const QList&)), SLOT(sl_onAnnotationsRemoved(const QList&))); connect(obj, SIGNAL(si_onAnnotationModified(const AnnotationModification&)), SLOT(sl_onAnnotationModified(const AnnotationModification&))); connect(obj, SIGNAL(si_onAnnotationsInGroupRemoved(const QList&, AnnotationGroup*)), SLOT(sl_onAnnotationsInGroupRemoved(const QList&, AnnotationGroup*))); connect(obj, SIGNAL(si_onGroupCreated(AnnotationGroup*)), SLOT(sl_onGroupCreated(AnnotationGroup*))); connect(obj, SIGNAL(si_onGroupRemoved(AnnotationGroup*, AnnotationGroup*)), SLOT(sl_onGroupRemoved(AnnotationGroup*, AnnotationGroup*))); connect(obj, SIGNAL(si_onGroupRenamed(AnnotationGroup*, const QString& )), SLOT(sl_onGroupRenamed(AnnotationGroup*, const QString& ))); connect(obj, SIGNAL(si_modifiedStateChanged()), SLOT(sl_onAnnotationObjectModifiedStateChanged())); connect(obj, SIGNAL(si_nameChanged(const QString&)), SLOT(sl_onAnnotationObjectRenamed(const QString& ))); } void AnnotationsTreeViewL::sl_onAnnotationObjectRemoved(AnnotationTableObject* obj) { TreeSorter ts(this); AVGroupItemL* groupItem = findGroupItem(obj->getRootGroup()); if (groupItem) { destroyTree(groupItem); tree->removeItem(groupItem, true); } obj->disconnect(this); } void AnnotationsTreeViewL::sl_onAnnotationsInGroupRemoved(const QList&, AnnotationGroup* group) { AVGroupItemL *parentGroupItem = findGroupItem(group); if(parentGroupItem != NULL) { tree->realNumberOfItems -= tree->getExpandedNumber(group); destroyTree(parentGroupItem); tree->removeItem(parentGroupItem); } group->getGObject()->releaseLocker(); } void AnnotationsTreeViewL::sl_onAnnotationsAdded(const QList& as) { GTIMER(c1,t1,"AnnotationsTreeView::sl_onAnnotationsAdded"); TreeSorter ts(this); QSet toUpdate; foreach(Annotation* a, as) { foreach(AnnotationGroup* ag, a->getGroups()) { AVGroupItemL* gi = findGroupItem(ag); if(!gi) { AnnotationGroup* childGroup = ag; while(true) { gi = findGroupItem(childGroup->getParentGroup()); if (gi != NULL) { break; } childGroup = childGroup->getParentGroup(); } } toUpdate.insert(gi); //tree->realNumberOfItems++; tree->treeWalker->addItem(a, ag); } } GTIMER(c2,t2,"AnnotationsTreeView::sl_onAnnotationsAdded [updateVisual]"); while (!toUpdate.isEmpty()) { AVGroupItemL* i= *toUpdate.begin(); toUpdate.remove(i); i->updateVisual(); AVGroupItemL* p = (AVGroupItemL*)(i->parent()); if (p != NULL && p->parent() != NULL) { toUpdate.insert(p); } } } void AnnotationsTreeViewL::sl_onAnnotationsRemoved(const QList& as) { TreeSorter ts(this); tree->disconnect(this, SIGNAL(sl_onItemSelectionChanged())); AnnotationTableObject* aObj = qobject_cast(sender()); assert(aObj != NULL); AVGroupItemL* groupItem = findGroupItem(aObj->getRootGroup()); QSet groupsToUpdate; foreach(Annotation* a, as) { assert(a->getGObject() == NULL); QList aItems; groupItem->findAnnotationItems(aItems, a); foreach(AnnotationGroup *gr, a->getGroups()) { if(tree->treeWalker->isExpanded(gr)) { tree->realNumberOfItems--; tree->updateSlider(); } } //assert(!aItems.isEmpty()); foreach(AVAnnotationItemL* ai, aItems) { tree->treeWalker->deleteItem(a, (static_cast(ai->parent())->getAnnotationGroup())); AVGroupItemL * parentGroup = static_cast(ai->parent()); groupsToUpdate.insert(parentGroup); tree->removeItem(ai); } } foreach(AVGroupItemL* g, groupsToUpdate) { g->updateVisual(); } connect(tree, SIGNAL(itemSelectionChanged()), SLOT(sl_onItemSelectionChanged ())); sl_onItemSelectionChanged(); } void AnnotationsTreeViewL::sl_onAnnotationModified(const AnnotationModification& md) { switch(md.type) { case AnnotationModification_NameChanged: case AnnotationModification_LocationChanged: { QList aItems = findAnnotationItems(md.annotation); //assert(!aItems.isEmpty()); foreach(AVAnnotationItemL* ai, aItems) { ai->updateVisual(ATVAnnUpdateFlag_BaseColumns); } } break; case AnnotationModification_QualifierRemoved: { const QualifierModification& qm = (const QualifierModification&)md; QList aItems = findAnnotationItems(qm.annotation); foreach(AVAnnotationItemL* ai, aItems) { for(int i=0, n = ai->childCount(); i < n; i++) { AVQualifierItemL* qi = static_cast(ai->child(i)); if (qi->qName == qm.qualifier.name && qi->qValue == qm.qualifier.value) { tree->removeItem(qi); tree->realNumberOfItems--; tree->updateSlider(); break; } } ai->updateVisual(ATVAnnUpdateFlag_QualColumns); } } break; case AnnotationModification_QualifierAdded: { const QualifierModification& qm = (const QualifierModification&)md; QList aItems = findAnnotationItems(qm.annotation); foreach(AVAnnotationItemL* ai, aItems) { if (ai->isExpanded() || ai->childCount() > 0 || renameFlag) { //if item was expanded - add real qualifier items AVQualifierItemL* qi = new AVQualifierItemL(ai, qm.qualifier); tree->insertItem(ai->childCount() - 1, qi, false); tree->realNumberOfItems++; tree->updateSlider(); tree->emptyExpand = true; renameFlag = false; tree->expand(tree->guessIndex(qi->parent())); tree->emptyExpand = false; } else { ai->setChildIndicatorPolicy(QTreeWidgetItem::ShowIndicator); //otherwise process indicator only } } } break; case AnnotationModification_AddedToGroup: { const AnnotationGroupModification& gmd = (const AnnotationGroupModification&)md; AVGroupItemL* gi = findGroupItem(gmd.group); assert(gi!=NULL); createAnnotationItem(gi, gmd.annotation); gi->updateVisual(); } break; case AnnotationModification_RemovedFromGroup: { const AnnotationGroupModification& gmd = (const AnnotationGroupModification&)md; AVAnnotationItemL* ai = findAnnotationItem(gmd.group, gmd.annotation); AVGroupItemL* gi = dynamic_cast(ai->parent()); assert(ai!=NULL); tree->removeItem(ai); gi->updateVisual(); } break; } } void AnnotationsTreeViewL::sl_onGroupCreated(AnnotationGroup* g) { LazyAnnotationTreeViewModel *model = static_cast(tree->model()); AVGroupItemL* pg = g->getParentGroup()== NULL ? static_cast(model->getItem(QModelIndex())) : findGroupItem(g->getParentGroup()); tree->treeWalker->addItem(g); /*if(pg && pg->childCount() == 0) { tree->insertItem(pg->parent()->indexOfChild(pg), pg); }*/ if(pg != NULL) { tree->updateItem(pg); pg->updateVisual(); } } void AnnotationsTreeViewL::sl_onGroupRemoved(AnnotationGroup*, AnnotationGroup* g) { AVGroupItemL *gr = findGroupItem(g); if (gr != NULL) { destroyTree(gr); tree->treeWalker->deleteItem(g); tree->realNumberOfItems -= tree->getExpandedNumber(gr) + 1; tree->removeItem(gr); } } void AnnotationsTreeViewL::sl_onGroupRenamed(AnnotationGroup* g, const QString&) { AVGroupItemL* gi = findGroupItem(g); if (gi != NULL) { gi->updateVisual(); } } AVGroupItemL* AnnotationsTreeViewL::createGroupItem(AVGroupItemL* parentGroupItem, AnnotationGroup* g) { AVGroupItemL* groupItem = new AVGroupItemL(this, parentGroupItem, g); tree->insertItem(parentGroupItem->childCount() - 1, groupItem); if(!g->getAnnotations().isEmpty() || ! g->getSubgroups().isEmpty()) { groupItem->setChildIndicatorPolicy(QTreeWidgetItem::ShowIndicator); } groupItem->updateVisual(); return groupItem; } AVAnnotationItemL* AnnotationsTreeViewL::createAnnotationItem(AVGroupItemL* parentGroup, Annotation* a, bool removeLast) { AVAnnotationItemL* annotationItem = new AVAnnotationItemL(parentGroup, a); tree->insertItem(parentGroup->childCount() - 1, annotationItem, removeLast); const QVector& qualifiers = a->getQualifiers(); if (!qualifiers.isEmpty()) { annotationItem->setChildIndicatorPolicy(QTreeWidgetItem::ShowIndicator); } return annotationItem; } class SettingsUpdater : public TreeWidgetVisitor { public: SettingsUpdater(const QStringList& cs) : changedSettings(cs) {} bool isChildVisitRequired(QTreeWidgetItem* ti) { AVItemL* item = static_cast(ti); assert(item->type != AVItemType_Qualifier); return item->type == AVItemType_Group; //visit children only for group items } void visit(QTreeWidgetItem* ti) { AVItemL* item = static_cast(ti); if (item->type == AVItemType_Group) { AVGroupItemL* gi = static_cast(item); gi->updateVisual(); } else if (item->type == AVItemType_Annotation) { AVAnnotationItemL* ai = static_cast(item); QString name = ai->annotation->getAnnotationName(); if (changedSettings.contains(name)) { ai->updateVisual(ATVAnnUpdateFlag_BaseColumns); } } } private: QStringList changedSettings; }; /* void AnnotationsTreeViewL::sl_onAnnotationSettingsChanged(const QStringList& changedSettings) { // first clear colors cache for changed annotations QMap& cache = AVAnnotationItemL::getIconsCache(); foreach (const QString& name, changedSettings) { cache.remove(name); } // second -> update all annotations SettingsUpdater su(changedSettings); TreeWidgetUtils::visitDFS(tree, &su); }*/ void AnnotationsTreeViewL::updateColumnContextActions(AVItemL* item, int col) { copyColumnTextAction->setEnabled(item!=NULL && (col >= 2 || (item->type == AVItemType_Annotation && col == 1)) && !item->text(col).isEmpty()); copyColumnURLAction->setEnabled(item!=NULL && col >= 2 && item->isColumnLinked(col)); if (!copyColumnTextAction->isEnabled()) { copyColumnTextAction->setText(tr("Copy column text")); } else { QString colName; if (col >= 2) { assert(qColumns.size() > col - 2); colName = qColumns[col - 2]; copyColumnTextAction->setText(tr("Copy column '%1' text").arg(colName)); } else { AVAnnotationItemL* ai = static_cast(item); copyColumnTextAction->setText(tr("Copy '%1' annotation location").arg(ai->annotation->getAnnotationName())); } } if (!copyColumnURLAction->isEnabled()) { copyColumnURLAction->setText(tr("copy column URL")); } else { assert(qColumns.size() > col - 2); QString colName = qColumns[col - 2]; copyColumnURLAction->setText(tr("Copy column '%1' URL").arg(colName)); } } void AnnotationsTreeViewL::sl_onBuildPopupMenu(GObjectView*, QMenu* m) { // Add actions that not depends on the point popup is called adjustMenu(m); QPoint globalPos = QCursor::pos(); QPoint treePos = tree->mapFromGlobal(globalPos); if (!tree->rect().contains(treePos)) { return; } // Check is popup is called for column header QHeaderView* header = tree->header(); QPoint headerPoint = header->mapFromGlobal(globalPos); if (header->rect().contains(headerPoint)) { int idx = header->logicalIndexAt(headerPoint); if (idx >= 2) { assert(idx - 2 < qColumns.size()); lastClickedColumn = idx; removeColumnByHeaderClickAction->setText(tr("Hide '%1' column").arg(qColumns[lastClickedColumn-2])); QAction* first = m->actions().first(); m->insertAction(first, removeColumnByHeaderClickAction); m->insertSeparator(first); } return; } //Ensure that item clicked is in the tree selection. Do not destroy multi-selection if present QList selItems = tree->selectedItems(); QPoint viewportPos = tree->viewport()->mapFromGlobal(globalPos); if (selItems.size() <= 1) { QTreeWidgetItem* item = tree->itemAt(viewportPos); if (item!=NULL) { if (selItems.size() == 1 && selItems.first()!=item) { //tree->setItemSelected(selItems.first(), false); selItems.first()->setSelected(false); } if(!selItems.isEmpty()) { selItems.first()->setSelected(true); } //tree->setItemSelected(item, true); } } //Update column sensitive actions that appears only in context menu selItems = tree->selectedItems(); lastClickedColumn = tree->columnAt(viewportPos.x()); updateColumnContextActions(selItems.size() == 1 ? static_cast(selItems.first()) : static_cast(NULL), lastClickedColumn); //Add active context actions to the top level menu QList contextActions; contextActions << copyQualifierAction << copyQualifierURLAction << toggleQualifierColumnAction << copyColumnTextAction << copyColumnURLAction << editAction ;// << cutAnnotationsAction << copyAnnotationsAction << pasteAnnotationsAction; QMenu* copyMenu = GUIUtils::findSubMenu(m, ADV_MENU_COPY); foreach(QAction* a, contextActions) { if (a->isEnabled()) { copyMenu->addAction(a); } } int nActive = 0; QAction* first = m->actions().first(); foreach(QAction* a, contextActions) { if (a->isEnabled()) { nActive++; m->insertAction(first, a); } } if (nActive > 0) { m->insertSeparator(first); } } void AnnotationsTreeViewL::adjustMenu(QMenu* m) const { QMenu* addMenu = GUIUtils::findSubMenu(m, ADV_MENU_ADD); assert(addMenu!=NULL); addMenu->addAction(addAnnotationObjectAction); addMenu->addAction(addQualifierAction); QMenu* removeMenu = GUIUtils::findSubMenu(m, ADV_MENU_REMOVE); assert(removeMenu!=NULL); removeMenu->addAction(removeObjectsFromViewAction); removeMenu->addAction(removeAnnsAndQsAction); } void AnnotationsTreeViewL::sl_onAddAnnotationObjectToView() { ProjectTreeControllerModeSettings s; s.objectTypesToShow.append(GObjectTypes::ANNOTATION_TABLE); s.groupMode = ProjectTreeGroupMode_Flat; foreach(GObject* o, ctx->getObjects()) { s.excludeObjectList.append(o); } QList objs = ProjectTreeItemSelectorDialog::selectObjects(s, this); foreach(GObject* obj, objs) { assert(obj->getGObjectType() == GObjectTypes::ANNOTATION_TABLE); ctx->tryAddObject(obj); } } static QList selectGroupItems(const QList& items, TriState readOnly, TriState rootOnly) { QList res; foreach(QTreeWidgetItem* i, items) { AVItemL* item = static_cast(i); if (item->type == AVItemType_Group) { AVGroupItemL* gItem = static_cast(item); if (rootOnly != TriState_Unknown) { bool groupIsRoot = gItem->parent()->parent() == NULL; if ( (rootOnly == TriState_Yes && !groupIsRoot) || (rootOnly==TriState_No && groupIsRoot)) { continue; } } if (readOnly != TriState_Unknown) { bool groupReadOnly = gItem->isReadonly(); if ( (readOnly == TriState_Yes && !groupReadOnly) || (readOnly==TriState_No && groupReadOnly)) { continue; } } res.append(gItem); } } return res; } static QList selectAnnotationItems(const QList& items, TriState readOnly) { QList res; foreach(QTreeWidgetItem* i, items) { AVItemL* item = static_cast(i); if (item->type == AVItemType_Annotation) { AVAnnotationItemL* aItem = static_cast(item); if (readOnly != TriState_Unknown) { bool aReadOnly= aItem->isReadonly(); if ( (readOnly == TriState_Yes && !aReadOnly) || (readOnly==TriState_No && aReadOnly)) { continue; } } res.append(aItem); } } return res; } static QList selectQualifierItems(const QList& items, TriState readOnly) { QList res; foreach(QTreeWidgetItem* i, items) { AVItemL* item = static_cast(i); if (item->type == AVItemType_Qualifier) { AVQualifierItemL* qItem = static_cast(item); if (readOnly != TriState_Unknown) { bool qReadOnly= qItem->isReadonly(); if ( (readOnly == TriState_Yes && !qReadOnly) || (readOnly==TriState_No && qReadOnly)) { continue; } } res.append(qItem); } } return res; } void AnnotationsTreeViewL::sl_removeObjectFromView() { QList topLevelGroups = selectGroupItems(tree->selectedItems(), TriState_Unknown, TriState_Yes); QList objects; foreach(AVGroupItemL* gItem, topLevelGroups) { objects.append(gItem->group->getGObject()); } foreach(GObject* obj, objects) { assert(obj->getGObjectType() == GObjectTypes::ANNOTATION_TABLE); ctx->removeObject(obj); } } static bool groupDepthInverseComparator(const AVGroupItemL* i1, const AVGroupItemL* i2) { int depth1 = i1->group->getGroupDepth(); int depth2 = i2->group->getGroupDepth(); return depth1 > depth2; } void AnnotationsTreeViewL::sl_removeAnnsAndQs() { //remove selected qualifiers first (cache them, since different qualifier items with equal name/val are not distinguished) QList qualifierItemsToRemove = selectQualifierItems(tree->selectedItems(), TriState_No); QVector qualsToRemove(qualifierItemsToRemove.size()); QVector qualAnnotations(qualifierItemsToRemove.size()); for(int i=0, n = qualifierItemsToRemove.size(); i(qi->parent()); qualAnnotations[i] = ai->annotation; qualsToRemove[i] = U2Qualifier(qi->qName, qi->qValue); } for(int i=0, n = qualifierItemsToRemove.size(); iremoveQualifier(q); } //remove selected annotations now QList annotationItemsToRemove = selectAnnotationItems(tree->selectedItems(), TriState_No); QMultiMap annotationsByGroup; foreach(AVAnnotationItemL* aItem, annotationItemsToRemove) { assert(!aItem->annotation->getGObject()->isStateLocked()); AnnotationGroup* ag = (static_cast(aItem->parent())->group); annotationsByGroup.insert(ag, aItem->annotation); } QList agroups = annotationsByGroup.uniqueKeys(); foreach(AnnotationGroup* ag, agroups) { QList annotations = annotationsByGroup.values(ag); ag->removeAnnotations(annotations); } //now remove selected groups QList groupItemsToRemove = selectGroupItems(tree->selectedItems(), TriState_No, TriState_No); qSort(groupItemsToRemove.begin(), groupItemsToRemove.end(), groupDepthInverseComparator); //now remove all groups foreach(AVGroupItemL* gi, groupItemsToRemove) { AnnotationGroup* pg = gi->group->getParentGroup(); pg->removeSubgroup(gi->group); } } void AnnotationsTreeViewL::updateState() { QList items = tree->selectedItems(); QList topLevelGroups = selectGroupItems(items, TriState_Unknown, TriState_Yes); foreach (AVGroupItemL* item, topLevelGroups) { AnnotationTableObject* aObj = item->getAnnotationTableObject(); if (AutoAnnotationsSupport::isAutoAnnotation(aObj)) { break; } } removeObjectsFromViewAction->setEnabled(!topLevelGroups.isEmpty()); QList nonRootModGroups = selectGroupItems(items, TriState_No, TriState_No); QList modAnnotations = selectAnnotationItems(items, TriState_No); QList modQualifiers = selectQualifierItems(items, TriState_No); removeAnnsAndQsAction->setEnabled(!nonRootModGroups.isEmpty() || !modAnnotations.isEmpty() || !modQualifiers.isEmpty()); bool hasOnly1QualifierSelected = items.size() == 1 && (static_cast(items.first()))->type == AVItemType_Qualifier; QString qName = hasOnly1QualifierSelected ? (static_cast(items.first()))->qName : QString(""); copyQualifierAction->setEnabled(hasOnly1QualifierSelected); copyQualifierAction->setText(hasOnly1QualifierSelected ? tr("Copy qualifier '%1' value").arg(qName) : tr("Copy qualifier text")); bool hasOnly1QualifierSelectedWithURL = hasOnly1QualifierSelected && (static_cast(items.first()))->isColumnLinked(1); copyQualifierURLAction->setEnabled(hasOnly1QualifierSelectedWithURL); copyQualifierURLAction->setText(hasOnly1QualifierSelectedWithURL ? tr("Copy qualifier '%1' URL").arg(qName) : tr("Copy qualifier URL")); toggleQualifierColumnAction->setEnabled(hasOnly1QualifierSelected); bool hasColumn = qColumns.contains(qName); toggleQualifierColumnAction->setText(!hasOnly1QualifierSelected ? tr("Toggle column") : (qColumns.contains(qName) ? tr("Hide '%1' column"): tr("Add '%1' column")).arg(qName)); toggleQualifierColumnAction->setIcon(hasOnly1QualifierSelected ? (hasColumn ? removeColumnIcon : addColumnIcon) : QIcon()); QTreeWidgetItem * ciBase = tree->currentItem(); AVItemL* ci = static_cast(ciBase); bool editableItemSelected = items.size() == 1 && ci!=NULL && ci == items.first() && !ci->isReadonly(); renameAction->setEnabled(editableItemSelected); editAction->setEnabled(hasOnly1QualifierSelected && editableItemSelected); viewAction->setEnabled(hasOnly1QualifierSelected); bool hasEditableAnnotationContext = editableItemSelected && (ci->type == AVItemType_Annotation || ci->type == AVItemType_Qualifier); addQualifierAction->setEnabled(hasEditableAnnotationContext); } static bool isReadOnly(QTreeWidgetItem *item) { for (; item; item = item->parent()) { if(item->parent() == NULL) { continue; } AVItemL *itemi = dynamic_cast(item); AnnotationTableObject *obj; switch (itemi->type) { case AVItemType_Group: obj = dynamic_cast(itemi)->group->getGObject(); break; case AVItemType_Annotation: obj = dynamic_cast(itemi)->annotation->getGObject(); break; default: continue; } if (obj->isStateLocked()) return true; } return false; } void AnnotationsTreeViewL::resetDragAndDropData() { dndCopyOnly = false; dndSelItems.clear(); dropDestination = NULL; } bool AnnotationsTreeViewL::eventFilter(QObject* o, QEvent* e) { if (o != tree->viewport()) { return false; } QEvent::Type etype = e->type(); switch (etype) { case QEvent::ToolTip: { QHelpEvent* he = (QHelpEvent*)e; QPoint globalPos = he->globalPos(); QPoint viewportPos = tree->viewport()->mapFromGlobal(globalPos); QTreeWidgetItem* item = tree->itemAt(viewportPos); if (item != NULL) { AVItemL* avi = static_cast(item); if (avi->type == AVItemType_Annotation) { AVAnnotationItemL* ai = static_cast(avi); ADVSequenceObjectContext* sc = ctx->getSequenceContext(ai->getAnnotationTableObject()); QString tip = ai->annotation->getQualifiersTip(15, sc?sc->getSequenceObject():NULL, sc?sc->getComplementTT():NULL); if (!tip.isEmpty()) { QToolTip::showText(he->globalPos(), tip); return true; } } } return false; } case QEvent::MouseButtonRelease: lastMB = ((QMouseEvent*)e)->button(); isDragging = false; return false; case QEvent::MouseButtonPress: { QMouseEvent *me = dynamic_cast(e); if (me->modifiers() == Qt::NoModifier && me->button() == Qt::LeftButton) { QTreeWidgetItem *item = tree->itemAt(dragStartPos = me->pos()); if (item != NULL) { AVItemTypeL type = dynamic_cast(item)->type; if (type == AVItemType_Annotation || type == AVItemType_Group) { if (!tree->selectedItems().contains(item)) { tree->setCurrentItem(item); } isDragging = true; return false; } } } isDragging = false; return false; } case QEvent::MouseMove: { QMouseEvent *me = dynamic_cast(e); if (!(me->buttons() & Qt::LeftButton) || !isDragging) { return false; } if ((me->pos() - dragStartPos).manhattanLength() < QApplication::startDragDistance()) { return true; } initiateDragAndDrop(me); return true; } case QEvent::DragEnter: { QDragEnterEvent *de = dynamic_cast(e); if (de->mimeData()->hasFormat(annotationMimeType)) { de->acceptProposedAction(); uiLog.trace("Drag enter event in Annotations view : format is OK"); return true; } uiLog.trace("Drag enter event in Annotations view : unsupported mime format!"); return false; } case QEvent::DragMove: { // update current D&D state QDragMoveEvent *de = dynamic_cast(e); if (de->mimeData()->hasFormat(annotationMimeType)) { QTreeWidgetItem *item = tree->itemAt(de->pos()); if (item == NULL) { de->ignore(); uiLog.trace("Drag event in Annotations view : invalid destination"); return true; } if (isReadOnly(item)) { de->ignore(); uiLog.trace(QString("Drag event in Annotations view : destination is read-only: %1").arg(item->text(0))); return true; } Qt::DropAction dndAction = (de->keyboardModifiers() & Qt::ShiftModifier) ? Qt::CopyAction : Qt::MoveAction; if (dndAction == Qt::MoveAction && dndCopyOnly) { de->ignore(); uiLog.trace("Drag event in Annotations view : source is read-only, can't move"); return true; } for (AVItemL *itemi = dynamic_cast(item); itemi != NULL; itemi = dynamic_cast(itemi->parent())) { if (itemi->type == AVItemType_Group) { for (int i = 0, s = dndSelItems.size(); i < s; ++i) { AVItemL* dndItem = dndSelItems[i]; if (dndItem == itemi) { // do not allow drop group into itself de->ignore(); uiLog.trace("Drag event in Annotations view : can't move group into itself!"); return true; } } } } if (item->parent() == NULL) { //destination is root item for (int i = 0, s = dndSelItems.size(); i < s; ++i) { AVItemL* dndItem = dndSelItems[i]; if (dndItem->type == AVItemType_Annotation) { de->ignore(); // root group can't have annotations -> problem with store/load invariant.. uiLog.trace("Drag event in Annotations view : can't move annotations, destination group is not found!"); return true; } } } de->setDropAction(dndAction); de->accept(); uiLog.trace(QString("Drag event in Annotations view, status: OK, type: %1").arg(dndAction == Qt::MoveAction? "Move" : "Copy")); return true; } return false; } case QEvent::Drop: { uiLog.trace("Drop event in Annotations view"); QDropEvent *de = dynamic_cast(e); const QMimeData *mime = de->mimeData(); if (mime->hasFormat(annotationMimeType)) { QTreeWidgetItem *item = tree->itemAt(de->pos()); if (item != NULL) { AVItemL *avItem= dynamic_cast(item); while (avItem != NULL && avItem->type != AVItemType_Group) { avItem = dynamic_cast(avItem->parent()); } if (avItem != NULL) { dropDestination = static_cast(avItem); if (de->keyboardModifiers() & Qt::ShiftModifier) { de->setDropAction(Qt::CopyAction); } else { de->setDropAction(Qt::MoveAction); } de->accept(); uiLog.trace(QString("Drop event in Annotations view : destination group %1").arg(dropDestination->group->getGroupPath())); } else { uiLog.trace("Drop event in Annotations view : something weird, can't derive destination group!"); } return true; } else { uiLog.trace("Drop event in Annotations view : invalid destination"); } } else { uiLog.trace("Drop event in Annotations view : unknown MIME format"); return false; } de->ignore(); return true; } default: return false; } } bool AnnotationsTreeViewL::initiateDragAndDrop(QMouseEvent*) { uiLog.trace("Starting drag & drop in annotations view"); resetDragAndDropData(); // Now filter selection: keep only parent items in the items list, remove qualifiers, check if 'move' is allowed QList initialSelItems = tree->selectedItems(); // whole selection will be moved dndCopyOnly = false; // allow 'move' by default first for (int i = 0, n = initialSelItems.size(); i < n; i++) { AVItemL *itemi = dynamic_cast(initialSelItems[i]); if (itemi->parent() && !dndCopyOnly && isReadOnly(itemi)) { dndCopyOnly = true; } if (itemi->type == AVItemType_Annotation) { // if annotation group is in the selection -> remove annotation from the list, it will be moved/copied automatically with group bool addItem = true; for (QTreeWidgetItem *cur = itemi->parent(); cur != NULL; cur = cur->parent()) { if (initialSelItems.contains(cur)) { addItem = false; break; } } if (addItem) { dndSelItems.append(itemi); } } else if (itemi->type == AVItemType_Qualifier) { // remove qualifiers from selection dndSelItems[i]->setSelected(false); } else { assert(itemi->type == AVItemType_Group); if (itemi->parent() == NULL) { // object level group -> add all subgroups for (int j = 0, m = itemi->childCount(); j < m; j++) { AVItemL* citem = dynamic_cast(itemi->child(j)); assert(citem->type == AVItemType_Group || citem->type == AVItemType_Annotation); dndSelItems.append(citem); } } else { dndSelItems.append(itemi); } } } if (dndSelItems.isEmpty()) { resetDragAndDropData(); uiLog.trace("No items to drag & drop"); return false; } // serialize selected items : // TODO: actually we do not need it today, so skipping this step //QStringList annotationsAndGroupsRefs; QByteArray serializedReferences; serializedReferences.append(serializedReferences); // initiate dragging QMimeData* mimeData = new QMimeData(); mimeData->setData(annotationMimeType, serializedReferences); QDrag *drag = new QDrag(this); drag->setMimeData(mimeData); Qt::DropAction dndAction = drag->exec(Qt::MoveAction | Qt::CopyAction, Qt::CopyAction); if (dndAction == Qt::MoveAction || dndAction == Qt::CopyAction) { finishDragAndDrop(dndAction); } else { uiLog.trace("Drag & drop in Annotations view was ignored"); } resetDragAndDropData(); return true; } typedef QPair GroupChangeInfo; typedef QPair AnnotationDnDInfo; static void collectAnnotationDnDInfo(AnnotationGroup* ag, const QString& destGroupPath, QList& annotationsToProcess) { foreach(Annotation* a, ag->getAnnotations()) { annotationsToProcess << AnnotationDnDInfo(GroupChangeInfo(ag, destGroupPath), a); } QString newDestGroupPath = destGroupPath + "/" + ag->getGroupName(); foreach(AnnotationGroup* sag, ag->getSubgroups()) { collectAnnotationDnDInfo(sag, newDestGroupPath, annotationsToProcess); } } void AnnotationsTreeViewL::finishDragAndDrop(Qt::DropAction dndAction) { AnnotationTableObject* dstObject = dropDestination->getAnnotationTableObject(); QString destGroupPath = dropDestination->group->getGroupPath(); QList affectedGroups; QList affectedAnnotations; QStringList manualCreationGroups; for (int i = 0, n = dndSelItems.size(); i < n; ++i) { AVItemL* selItem = dndSelItems.at(i); assert(selItem->parent()!= NULL); // we never have no top-level object items in dndSelItems if (selItem->type == AVItemType_Annotation) { AVGroupItemL* fromGroupItem = dynamic_cast(selItem->parent()); AVAnnotationItemL* ai = dynamic_cast(selItem); affectedAnnotations << AnnotationDnDInfo(GroupChangeInfo(fromGroupItem->group, destGroupPath), ai->annotation); } else { AVGroupItemL* movedGroupItem = dynamic_cast(selItem); if (movedGroupItem->group->getParentGroup() == dropDestination->group) { continue; // can't drop group into itself } QString toGroupPath = destGroupPath + (destGroupPath.isEmpty() ? "" : "/") + movedGroupItem->group->getGroupName(); if (movedGroupItem->group->getAnnotations().isEmpty()) { //this group will not be created as part of annotation move process -> create it manually manualCreationGroups.append(toGroupPath); } collectAnnotationDnDInfo(movedGroupItem->group, toGroupPath, affectedAnnotations); affectedGroups.append(movedGroupItem->group); } } uiLog.trace(QString("Finishing drag & drop in Annotations view, affected groups: %1 , top-level annotations: %2").arg(affectedGroups.size()).arg(affectedAnnotations.size())); // Move or Copy annotation reference inside of the object foreach(const AnnotationDnDInfo& adnd, affectedAnnotations) { const QString& toGroupPath = adnd.first.second; AnnotationGroup* dstGroup = dstObject->getRootGroup()->getSubgroup(toGroupPath, true); if (dstGroup == dstObject->getRootGroup()) { // root group can't have annotations -> problem with store/load invariant.. continue; } AnnotationGroup* srcGroup = adnd.first.first; Annotation *srcAnnotation = adnd.second; Annotation* dstAnnotation = (dstObject == srcAnnotation->getGObject()) ? srcAnnotation : new Annotation(srcAnnotation->data()); bool doAdd = !dstGroup->getAnnotations().contains(dstAnnotation); bool doRemove = dndAction == Qt::MoveAction && doAdd; if (doAdd) { dstGroup->addAnnotation(dstAnnotation); } if (doRemove) { srcGroup->removeAnnotation(srcAnnotation); } } // Process groups if (dndAction == Qt::MoveAction) { foreach(AnnotationGroup* ag, affectedGroups) { ag->getParentGroup()->removeSubgroup(ag); } } // manually create empty group items foreach(const QString& path, manualCreationGroups) { dstObject->getRootGroup()->getSubgroup(path, true); } } void AnnotationsTreeViewL::sl_itemEntered(QTreeWidgetItem * i, int column) { AVItemL* item = static_cast(i); Qt::CursorShape newShape = Qt::ArrowCursor; Qt::CursorShape currentShape = tree->cursor().shape(); if (item != NULL) { if (item->isColumnLinked(column)) { newShape = Qt::PointingHandCursor; } } if (newShape == Qt::PointingHandCursor || ((newShape == Qt::ArrowCursor && currentShape == Qt::PointingHandCursor))) { tree->setCursor(newShape); } } void AnnotationsTreeViewL::sl_itemDoubleClicked(QTreeWidgetItem *i, int) { AVItemL* item = static_cast(i); if (item->type == AVItemType_Qualifier) { editItem(item); } } void AnnotationsTreeViewL::sl_itemClicked(QTreeWidgetItem * i, int column) { AVItemL* item = static_cast(i); if (lastMB != Qt::LeftButton || item==NULL || !item->isColumnLinked(column)) { return; } QString fileUrl = item->getFileUrl(column); if (!fileUrl.isEmpty()) { Task* task = new LoadRemoteDocumentAndOpenViewTask(fileUrl); AppContext::getTaskScheduler()->registerTopLevelTask(task); } else { GUIUtils::runWebBrowser(item->buildLinkURL(column)); } } void AnnotationsTreeViewL::sl_itemExpanded(QTreeWidgetItem* qi) { int current = tree->onScreen.size(); int lim = tree->getMaxItem(); int itemsToAdd; AVItemL* i = static_cast(qi); if(qi->childCount() != 0) { return; } itemsToAdd = tree->getExpandedNumber(i); int acceptable = lim - current; int j = 0; for(;j < acceptable && j < itemsToAdd; j++) { //Add while there is space on viewport i = tree->getNextItemDown(i); tree->insertItem(i->parent()->childCount() - 1, i, false); if(tree->treeWalker->isExpanded(i)) { tree->emptyExpand = true; tree->expand(tree->guessIndex(i)); tree->emptyExpand = false; } } QTreeWidgetItem *bottomItem = tree->onScreen.last(); QTreeWidgetItem *lastInserted = i; for(; j< itemsToAdd;j++) { if(lastInserted == bottomItem) { break; } i = tree->getNextItemDown(i); tree->insertItem(i->parent()->childCount() - 1, i); if(tree->treeWalker->isExpanded(i)) { tree->emptyExpand = true; tree->expand(tree->guessIndex(i)); tree->emptyExpand = false; } tree->removeItem(bottomItem); bottomItem = tree->onScreen.last(); lastInserted = i; } } void AnnotationsTreeViewL::sl_itemCollapsed(QTreeWidgetItem* qi) { destroyTree(qi); qi->setChildIndicatorPolicy(QTreeWidgetItem::ShowIndicator); int current = tree->onScreen.size(); int lim = tree->getMaxItem(); int acceptable = lim - current; AVItemL *item = NULL; if(acceptable > 0) { item = tree->getNextItemDown(static_cast(tree->onScreen.last())); } while(item && acceptable > 0) { tree->insertItem(item->parent()->childCount() - 1, item, false); if(tree->treeWalker->isExpanded(item)) { tree->expand(tree->guessIndex(item)); } acceptable--; if(acceptable > 0) { item = tree->getNextItemDown(static_cast(tree->onScreen.last())); } } if(acceptable > 0) { item = tree->getNextItemUp(); } while(item && acceptable > 0) { QTreeWidgetItem *last = tree->onScreen.first(); if(item == last->parent() || item->parent()->parent() == NULL) { tree->onScreen.insert(0, item); } else { tree->insertItem(0, item); } acceptable--; if(acceptable > 0) { item = tree->getNextItemUp(); } } } void AnnotationsTreeViewL::destroyTree(QTreeWidgetItem* qi) { while(qi->childCount() > 0) { destroyTree(qi->child(0)); tree->removeItem(qi->child(0)); } } void AnnotationsTreeViewL::sl_onCopyQualifierValue() { QList items = tree->selectedItems(); assert(items.size() == 1); AVItemL* item = static_cast(items.first()); assert(item->type == AVItemType_Qualifier); AVQualifierItemL* qi = static_cast(item); QApplication::clipboard()->setText(qi->qValue); } void AnnotationsTreeViewL::sl_onCopyQualifierURL() { QList items = tree->selectedItems(); assert(items.size() == 1); AVItemL* item = static_cast(items.first()); if (item->isColumnLinked(1)) { QApplication::clipboard()->setText(item->buildLinkURL(1)); } } void AnnotationsTreeViewL::sl_onCopyColumnText() { QList items = tree->selectedItems(); assert(items.size() == 1); AVItemL* item = static_cast(items.first()); QApplication::clipboard()->setText(item->text(lastClickedColumn)); } void AnnotationsTreeViewL::sl_onCopyColumnURL() { QList items = tree->selectedItems(); assert(items.size() == 1); AVItemL* item = static_cast(items.first()); QApplication::clipboard()->setText(item->buildLinkURL(lastClickedColumn)); } void AnnotationsTreeViewL::sl_onToggleQualifierColumn() { QList items = tree->selectedItems(); assert(items.size() == 1); AVItemL* item = static_cast(items.first()); assert(item->type == AVItemType_Qualifier); AVQualifierItemL* qi = static_cast(item); if (qColumns.contains(qi->qName)) { removeQualifierColumn(qi->qName); } else { addQualifierColumn(qi->qName); } } void AnnotationsTreeViewL::sl_onRemoveColumnByHeaderClick() { assert(lastClickedColumn >= 2); assert(lastClickedColumn-2 <= qColumns.size()); removeQualifierColumn(qColumns[lastClickedColumn-2]); } void AnnotationsTreeViewL::updateAllAnnotations(ATVAnnUpdateFlags flags) { QString emptyFilter; for(int i=0; itopLevelItemCount(); i++) { AVGroupItemL* gi = static_cast(tree->topLevelItem(i)); gi->updateAnnotations(emptyFilter, flags); } } void AnnotationsTreeViewL::addQualifierColumn(const QString& q) { TreeSorter ts(this); qColumns.append(q); int nColumns = headerLabels.size() + qColumns.size(); //tree->setColumnCount(nColumns); LazyAnnotationTreeViewModel *lm = static_cast(tree->model()); tree->setHeaderLabels(headerLabels + qColumns); lm->insertColumn(nColumns); tree->setColumnWidth(nColumns-2, nColumns - 2 == 1 ? 200 : 100); updateAllAnnotations(ATVAnnUpdateFlag_QualColumns); updateState(); } void AnnotationsTreeViewL::removeQualifierColumn(const QString& q) { int ind = qColumns.indexOf(q); bool ok = qColumns.removeOne(q); if (!ok) { return; } TreeSorter ts(this); //tree->setColumnCount(headerLabels.size() + qColumns.size()); LazyAnnotationTreeViewModel *lm = static_cast(tree->model()); tree->setHeaderLabels(headerLabels + qColumns); lm->removeColumn(ind); updateAllAnnotations(ATVAnnUpdateFlag_QualColumns); updateState(); } #define COLUMN_NAMES "ATV_COLUMNS" void AnnotationsTreeViewL::saveState(QVariantMap& map) const { map.insert(COLUMN_NAMES, QVariant(qColumns)); QStringList columns = map.value(COLUMN_NAMES).toStringList(); assert(columns == qColumns); } void AnnotationsTreeViewL::updateState(const QVariantMap& map) { QStringList columns = map.value(COLUMN_NAMES).toStringList(); //QByteArray geom = map.value(COLUMNS_GEOM).toByteArray(); if (columns != qColumns && !columns.isEmpty()) { TreeSorter ts(this); foreach(QString q, qColumns) { removeQualifierColumn(q); } foreach(QString q, columns) { addQualifierColumn(q); } } /*if (columns == qColumns && !geom.isEmpty()) { tree->header()->restoreState(geom); }*/ } void AnnotationsTreeViewL::setSortingEnabled(bool v) { if (sortTimer.isActive()) { sortTimer.stop(); } if (v) { sortTimer.start(); } else { tree->setSortingEnabled(false); } } /* void AnnotationsTreeView::sl_sortTree() { tree->setSortingEnabled(true); }*/ void AnnotationsTreeViewL::sl_rename() { AVItemL* item = static_cast(tree->currentItem()); renameItem(item); } void AnnotationsTreeViewL::sl_edit() { AVItemL* item = static_cast(tree->currentItem()); if (item != NULL) { editItem(item); } } void AnnotationsTreeViewL::editItem(AVItemL* item) { //warn: item could be readonly here -> used just for viewing advanced context if (item->type == AVItemType_Qualifier) { AVQualifierItemL* qi = static_cast(item); AVAnnotationItemL* ai = static_cast(qi->parent()); U2Qualifier q; bool ro = qi->isReadonly(); bool ok = editQualifierDialogHelper(qi, ro, q); if (!ro && ok && (q.name!=qi->qName || q.value!=qi->qValue)) { Annotation* a = (static_cast(qi->parent()))->annotation; renameFlag = true; a->removeQualifier(qi->qName, qi->qValue); a->addQualifier(q); AVQualifierItemL* qi = ai->findQualifierItem(q.name, q.value); tree->setCurrentItem(qi); tree->scrollToItem(qi); } } } void AnnotationsTreeViewL::moveDialogToItem(QTreeWidgetItem* item, QDialog& d) { if (item == NULL) { return; } tree->scrollToItem(item); //try place dialog right below or right above the item d.layout()->update(); /*QRect itemRect = tree->visualItemRect(item).translated(tree->viewport()->mapToGlobal(QPoint(0, 0))); QSize dialogSize = d.layout()->minimumSize(); QRect dialogRect(0, 0, dialogSize.width(), dialogSize.height() + 35); //+35 -> estimation for a title bar QRect widgetRect = rect().translated(mapToGlobal(QPoint(0, 0))); QRect finalDialogRect = dialogRect.translated(itemRect.bottomLeft()); if (!widgetRect.contains(finalDialogRect)) { finalDialogRect = dialogRect.translated(itemRect.topLeft()).translated(QPoint(0, -dialogRect.height())); } if (widgetRect.contains(finalDialogRect)) { d.move(finalDialogRect.topLeft()); }*/ } QString AnnotationsTreeViewL::renameDialogHelper(AVItemL* i, const QString& defText, const QString& title) { QDialog d(this); d.setWindowTitle(title); QVBoxLayout* l = new QVBoxLayout(); d.setLayout(l); QLineEdit* edit = new QLineEdit(&d); edit->setText(defText); edit->setSelection(0, defText.length()); connect(edit, SIGNAL(returnPressed()), &d, SLOT(accept())); l->addWidget(edit); moveDialogToItem(i, d); int rc = d.exec(); if (rc == QDialog::Rejected) { return defText; } return edit->text(); } bool AnnotationsTreeViewL::editQualifierDialogHelper(AVQualifierItemL* i, bool ro, U2Qualifier& q) { EditQualifierDialog d(this, U2Qualifier(i == NULL ? "new_qualifier" : i->qName , i == NULL ? "" : i->qValue), ro, i != NULL); moveDialogToItem(i == NULL ? tree->currentItem() : i, d); int rc = d.exec(); q = d.getModifiedQualifier(); return rc == QDialog::Accepted; } void AnnotationsTreeViewL::renameItem(AVItemL* item) { if (item->isReadonly()) { return; } if (item->type == AVItemType_Group) { AVGroupItemL* gi = static_cast(item); assert(gi->group->getParentGroup()!=NULL); //not a root group QString oldName = gi->group->getGroupName(); QString newName = renameDialogHelper(item, oldName, tr("Rename group")); if (newName != oldName && AnnotationGroup::isValidGroupName(newName, false) && gi->group->getParentGroup()->getSubgroup(newName, false) == NULL) { gi->group->setGroupName(newName); gi->updateVisual(); } } else if (item->type == AVItemType_Annotation) { AVAnnotationItemL* ai = static_cast(item); QVector l = ai->annotation->getRegions(); QList soList = ctx->findRelatedSequenceContexts(ai->annotation->getGObject()); assert(soList.size() == 1); ADVSequenceObjectContext* so = soList.first(); U2Region seqRange = so->getSequenceObject()->getSequenceRange(); EditAnnotationDialogController dialog(ai->annotation, seqRange, this); moveDialogToItem(ai, dialog); int result = dialog.exec(); if(result == QDialog::Accepted){ QString newName = dialog.getName(); if (newName!=ai->annotation->getAnnotationName()) { ai->annotation->setAnnotationName(newName); QList ais = findAnnotationItems(ai->annotation); foreach(AVAnnotationItemL* a, ais) { a->updateVisual(ATVAnnUpdateFlag_BaseColumns); } } U2Location location = dialog.getLocation(); if( !location->regions.isEmpty() && l != location->regions){ ai->annotation->replaceRegions(location->regions); } ai->annotation->setLocationOperator(location->op); ai->annotation->setStrand(location->strand); ai->annotation->getGObject()->setModified(true); } } else { assert(item->type == AVItemType_Qualifier); AVQualifierItemL* qi = static_cast(item); AVAnnotationItemL* ai = static_cast(qi->parent()); QString newName = renameDialogHelper(item, qi->qName, tr("Rename qualifier")); if (newName != qi->qName) { Annotation* a = (static_cast(qi->parent()))->annotation; QString val = qi->qValue; renameFlag = true; a->removeQualifier(qi->qName, val); a->addQualifier(newName, val); AVQualifierItemL* qi = ai->findQualifierItem(newName, val); tree->setCurrentItem(qi); tree->scrollToItem(qi); } } } void AnnotationsTreeViewL::sl_addQualifier() { AVItemL* item = static_cast(tree->currentItem()); if (item->isReadonly() || item->type == AVItemType_Group) { return; } U2Qualifier q; bool ok = editQualifierDialogHelper(NULL, false, q); if (ok) { assert(!q.name.isEmpty()); AVAnnotationItemL* ai = item->type == AVItemType_Annotation ? static_cast(item) : static_cast(item->parent()); Annotation* a = ai->annotation; a->addQualifier(q); //ai->setExpanded(true); AVQualifierItemL* qi = new AVQualifierItemL(ai, q); //sl_itemExpanded(ai); tree->expand(tree->guessIndex(qi->parent())); //AVQualifierItemL* qi = ai->findQualifierItem(q.name, q.value); tree->setCurrentItem(qi); tree->scrollToItem(qi); } } /*void AnnotationsTreeView::sl_cutAnnotations() { QByteArray itemData; QDataStream dataStream(&itemData, QIODevice::WriteOnly); QList selItems = tree->selectedItems(); int s = selItems.size(); dataStream << true; dataStream << s; for (int i = 0; i < s; ++i) { AVItemL *itemi = dynamic_cast(selItems[i]); dataStream << (itemi->type == AVItemType_Group); if (itemi->type == AVItemType_Annotation) dataStream << *dynamic_cast(itemi)->annotation->data(); else dataStream << *dynamic_cast(itemi)->group; } QMimeData *mimeData = new QMimeData; mimeData->setData(annotationMimeType, itemData); QClipboard *clipboard = QApplication::clipboard(); clipboard->setMimeData(mimeData); } void AnnotationsTreeView::sl_copyAnnotations() { QByteArray itemData; QDataStream dataStream(&itemData, QIODevice::WriteOnly); QList selItems = tree->selectedItems(); int s = selItems.size(); dataStream << false; dataStream << s; for (int i = 0; i < s; ++i) { AVItemL *itemi = dynamic_cast(selItems[i]); dataStream << (itemi->type == AVItemType_Group); if (itemi->type == AVItemType_Annotation) dataStream << *dynamic_cast(itemi)->annotation->data(); else dataStream << *dynamic_cast(itemi)->group; } QMimeData *mimeData = new QMimeData; mimeData->setData(annotationMimeType, itemData); QClipboard *clipboard = QApplication::clipboard(); clipboard->setMimeData(mimeData); } void AnnotationsTreeView::sl_pasteAnnotations() { }*/ void AnnotationsTreeViewL::sl_onAnnotationObjectModifiedStateChanged() { AnnotationTableObject* ao = qobject_cast(sender()); assert(ao!=NULL); AVGroupItemL* gi = findGroupItem(ao->getRootGroup()); assert(gi!=NULL); gi->updateVisual(); } void AnnotationsTreeViewL::sl_onAnnotationObjectRenamed(const QString&) { AnnotationTableObject* ao = qobject_cast(sender()); AVGroupItemL* gi = findGroupItem(ao->getRootGroup()); if (gi != NULL) { gi->updateVisual(); tree->updateItem(gi); //TODO: why manual update is required? } } AVItemL* AnnotationsTreeViewL::currentItem(){ return static_cast(tree->currentItem()); } QList LazyTreeView::selectedItems() { QList list; LazyAnnotationTreeViewModel *modell = static_cast(model()); foreach(const QModelIndex &index, selectedIndexes()) { QTreeWidgetItem* item = (QTreeWidgetItem*)modell->getItem(index); if(!list.contains(item)) { list << item; } } return list; } QTreeWidgetItem* LazyTreeView::currentItem() { QModelIndex index = currentIndex(); if(index.isValid()) { LazyAnnotationTreeViewModel *modell = static_cast(model()); QTreeWidgetItem*item = (QTreeWidgetItem*)modell->getItem(index); return item; } else { return NULL; } } void LazyTreeView::scrollToItem(QTreeWidgetItem *item, ScrollHint hint) { QModelIndex index = guessIndex(item); scrollTo(index, hint); } void LazyTreeView::setCurrentItem(QTreeWidgetItem *item) { QModelIndex index = guessIndex(item); setCurrentIndex (index); } int LazyTreeView::topLevelItemCount() const { LazyAnnotationTreeViewModel *modell = static_cast(model()); return modell->getItem(QModelIndex())->childCount(); } QTreeWidgetItem * LazyTreeView::topLevelItem(int i) { LazyAnnotationTreeViewModel *modell = static_cast(model()); AVItemL *root = modell->getItem(QModelIndex()); return (QTreeWidgetItem *)(root->child(i)); } void LazyTreeView::setColumnCount(int nCol) { LazyAnnotationTreeViewModel *modell = static_cast(model()); modell->setColumnCount(nCol); } void LazyTreeView::setHeaderLabels(QStringList headers) { LazyAnnotationTreeViewModel *modell = static_cast(model()); modell->setHeaderLabels(headers); } QTreeWidgetItem *LazyTreeView::itemAt(const QPoint pos) { QModelIndex index = indexAt(pos); LazyAnnotationTreeViewModel *modell = static_cast(model()); return (QTreeWidgetItem*)(modell->getItem(index)); } void LazyTreeView::scrollContentsBy ( int, int dy ) { int numToScroll = qAbs(dy); if(flag) { flag = false; return; } CustomSlider *slider = static_cast(verticalScrollBar()); if(slider->numToScroll() != 0) { numToScroll = qBound(0, slider->numToScroll(), slider->getMaxVal()); slider->resetNumToScroll(); } int pos = slider->sliderCustomPosition(); coreLog.trace("old position was: " + QString::number(pos)); coreLog.trace("numToScroll was: " + QString::number(numToScroll)); if(dy < 0) { int res = 1; while(numToScroll > 0 && res) { res = scrollOneItemDown(); numToScroll -= res; pos += res; } } else { int res = 1; while(numToScroll > 0 && res) { res = scrollOneItemUp(); numToScroll -= res; pos -= res; } } if(indexAt(QPoint(0,0)) != guessIndex(onScreen.first())) { flag = true; emptyExpand = true; //expand(guessIndex(onScreen.first()->parent())); //if don't expand parent, qtreeview itself will expand it and resize scroll bar //emptyExpand = false; scrollTo(guessIndex(onScreen.first()), QAbstractItemView::PositionAtTop); emptyExpand = false; } slider->setPosition(pos); coreLog.trace("new position was set to: " + QString::number(pos)); slider->update(); viewport()->update(); } int LazyTreeView::scrollOneItemUp() { AVItemL *item = getNextItemUp(); assert(item != NULL); QTreeWidgetItem *last = onScreen.first(); QTreeWidgetItem *toDelete = onScreen.last(); if(item == last->parent() || item->parent()->parent() == NULL) { onScreen.insert(0, item); } else { insertItem(0, item); } removeItem(toDelete); return 1; } int LazyTreeView::scrollOneItemDown() { AVItemL *item = getNextItemDown(static_cast(onScreen.last())); if(item) { QTreeWidgetItem *toDelete = onScreen.first(); insertItem(item->parent()->childCount() - 1, item, false); if(treeWalker->isExpanded(item)) { emptyExpand = true; expand(guessIndex(item)); emptyExpand = false; } QTreeWidgetItem *parentToDelete = toDelete->parent(); if(toDelete->childCount() == 0) { removeItem(toDelete); } while(parentToDelete->childCount() == 0) { toDelete = parentToDelete; parentToDelete = parentToDelete->parent(); removeItem(toDelete); } return 1; } else { return 0; } } int LazyTreeView::getExpandedNumber(AnnotationGroup *gr) { int num = 0; num += gr->getSubgroups().size() + gr->getAnnotations().size(); foreach(AnnotationGroup *g, gr->getSubgroups()) { if(treeWalker->isExpanded(g)) { num += getExpandedNumber(g); } } foreach(Annotation *a, gr->getAnnotations()) { if(treeWalker->isExpanded(a, gr)) { num += a->getQualifiers().size(); } } return num; } int LazyTreeView::getExpandedNumber(AVItemL *item) { int num = 0; AVGroupItemL *groupItem; AVAnnotationItemL *annItem; switch(item->type) { case AVItemType_Group: groupItem = static_cast(item); num += groupItem->getAnnotationGroup()->getSubgroups().size() + groupItem->getAnnotationGroup()->getAnnotations().size(); foreach(AnnotationGroup *gr, groupItem->getAnnotationGroup()->getSubgroups()) { if(treeWalker->isExpanded(gr)) { num += getExpandedNumber(gr); } } foreach(Annotation *a, groupItem->getAnnotationGroup()->getAnnotations()) { if(treeWalker->isExpanded(a, groupItem->getAnnotationGroup())) { num += a->getQualifiers().size(); } } break; case AVItemType_Annotation: annItem = static_cast(item); num += annItem->annotation->getQualifiers().size(); break; default: assert(0); } return num; } void LazyTreeView::sl_expanded(const QModelIndex &index) { if(emptyExpand) { emptyExpand = false; return; } LazyAnnotationTreeViewModel *modell = static_cast(model()); QTreeWidgetItem *item = (QTreeWidgetItem *)modell->getItem(index); treeWalker->expand(modell->getItem(index)); emit itemExpanded(item); realNumberOfItems += getExpandedNumber((AVItemL*)item); updateSlider(); } void LazyTreeView::sl_collapsed(const QModelIndex &index) { LazyAnnotationTreeViewModel *modell = static_cast(model()); QTreeWidgetItem *item = (QTreeWidgetItem *)modell->getItem(index); treeWalker->collapse(modell->getItem(index)); realNumberOfItems -= getExpandedNumber((AVItemL*)item); updateSlider(); emit itemCollapsed(item); } void LazyTreeView::insertItemBehindView(int row, QTreeWidgetItem *item) { QTreeWidgetItem *parent = item->parent(); LazyAnnotationTreeViewModel *lm = static_cast(model()); lm->nextToAdd = (AVItemL*)item; lm->debugFlag = true; lm->insertRow(row, guessIndex(parent)); } void LazyTreeView::insertItem(int row, QTreeWidgetItem *item, bool removeLast) { QTreeWidgetItem *parent = item->parent(); LazyAnnotationTreeViewModel *lm = static_cast(model()); lm->nextToAdd = (AVItemL*)item; lm->debugFlag = true; lm->insertRow(row, guessIndex(parent)); int ind; if(onScreen.indexOf(parent) != -1) { if(row > 0) { QTreeWidgetItem* prevChild = parent->child(row - 1); while(prevChild->childCount() > 0) { prevChild = prevChild->child(prevChild->childCount() -1); } ind = onScreen.indexOf(prevChild) + 1; } else { ind = onScreen.indexOf(parent) + 1; } } else if(row > 0){ ind = numOnScreen; } else { ind = 0; } onScreen.insert(ind, item); if(onScreen.size() > numOnScreen) { if(removeLast) { onScreen.removeLast(); } else { onScreen.removeFirst(); } } } void LazyTreeView::removeItem(QTreeWidgetItem *item, bool removeAll) { QTreeWidgetItem *parent = item->parent(); LazyAnnotationTreeViewModel *lm = static_cast(model()); onScreen.removeOne(item); if(item->parent()->parent() != NULL || removeAll) { lm->debugFlag = true; if(currentItem() == item) { setCurrentIndex(QModelIndex()); } lm->removeRow(parent->indexOfChild(item), guessIndex(parent)); } } AVItemL * LazyTreeView::getNextItemDown(AVItemL *bottom){ //Get item next down from bottom SAFE_POINT(bottom != NULL, "NULL current item", NULL); AVItemL *nextItem = NULL; AVQualifierItemL *currentQual = NULL; AVAnnotationItemL *currentAnn = NULL; AVGroupItemL *currentGroup = NULL; AVGroupItemL *parentGroup = NULL; U2Qualifier qual; int index; switch(bottom->type) { case AVItemType_Qualifier: //Current item is qualifier currentQual = static_cast(bottom); currentAnn = static_cast(currentQual->parent()); qual = U2Qualifier(currentQual->qName, currentQual->qValue); index = currentAnn->annotation->getQualifiers().indexOf(qual); if(index < currentAnn->annotation->getQualifiers().size() - 1) { //Next item is nearby qualifier nextItem = new AVQualifierItemL(currentAnn, currentAnn->annotation->getQualifiers()[index + 1]); return nextItem; } //If not go to higher level case AVItemType_Annotation: if(currentAnn == NULL) { currentAnn = static_cast(bottom); parentGroup = static_cast(currentAnn->parent()); bool f = treeWalker->isExpanded(currentAnn->annotation, parentGroup->getAnnotationGroup()); if(f) { //If item is expanded, get first child nextItem = new AVQualifierItemL(currentAnn, currentAnn->annotation->getQualifiers()[0]); return nextItem; } } currentGroup = static_cast(currentAnn->parent()); index = currentGroup->getAnnotationGroup()->getAnnotations().indexOf(currentAnn->annotation);//next item is annotation if(index < currentGroup->getAnnotationGroup()->getAnnotations().size() - 1) { nextItem = new AVAnnotationItemL(currentGroup, currentGroup->getAnnotationGroup()->getAnnotations()[index + 1]); return nextItem; } //If not go to higher level case AVItemType_Group: if(currentGroup == NULL) { currentGroup = static_cast(bottom); if(treeWalker->isExpanded(currentGroup->getAnnotationGroup())) {//If item is expanded get first child if(currentGroup->getAnnotationGroup()->getAnnotations().isEmpty()) { if(!currentGroup->getAnnotationGroup()->getSubgroups().isEmpty()) { nextItem = new AVGroupItemL(currentGroup->getAnnotationTreeView(), currentGroup, currentGroup->getAnnotationGroup()->getSubgroups()[0]); } else { return NULL; } } else { nextItem = new AVAnnotationItemL(currentGroup, currentGroup->getAnnotationGroup()->getAnnotations()[0]); } return nextItem; } } //Or find next group parentGroup = static_cast(currentGroup->parent()); //Need custom case when currentGroup is top-level item while(parentGroup->parent()) { index = parentGroup->getAnnotationGroup()->getSubgroups().indexOf(currentGroup->getAnnotationGroup()); if(index < parentGroup->getAnnotationGroup()->getSubgroups().size() - 1) { nextItem = new AVGroupItemL(parentGroup->getAnnotationTreeView(), parentGroup, parentGroup->getAnnotationGroup()->getSubgroups()[index + 1]); return nextItem; } currentGroup = parentGroup; parentGroup = static_cast(currentGroup->parent()); } index = parentGroup->indexOfChild(currentGroup); // Reach root item if(++index < parentGroup->childCount()) { return static_cast(parentGroup->child(index)); } break; default: assert(false); } return NULL; //reached end of tree } AVItemL * LazyTreeView::getLastItemInSubtree(AnnotationGroup *gr, AnnotationsTreeViewL *view) { if(gr->getSubgroups().isEmpty()) { Annotation *a = gr->getAnnotations().last(); if(treeWalker->isExpanded(a, gr)) { AVAnnotationItemL *annItem = view->findAnnotationItem(gr, a); AVGroupItemL *upperGroup = view->findGroupItem(gr); if(upperGroup == NULL) { AVGroupItemL *pGroup = view->findGroupItem(gr->getParentGroup()); assert(pGroup); upperGroup = new AVGroupItemL(view, pGroup, gr); insertItemBehindView(0, upperGroup); } if(annItem == NULL) { annItem = new AVAnnotationItemL(upperGroup, a); insertItemBehindView(upperGroup->childCount() - 1, annItem); if(treeWalker->isExpanded(a, gr)) { emptyExpand = true; expand(guessIndex(annItem)); emptyExpand = true; expand(guessIndex(upperGroup)); emptyExpand = false; } } return new AVQualifierItemL(annItem, a->getQualifiers().last()); } else { AVGroupItemL *parentGroup = view->findGroupItem(gr); AVGroupItemL *upperGroup = view->findGroupItem(gr->getParentGroup()); if(parentGroup == NULL) { parentGroup = new AVGroupItemL(view, upperGroup, gr); insertItemBehindView(/*upperGroup->childCount() - 1*/0, parentGroup); if(treeWalker->isExpanded(gr)) { emptyExpand = true; expand(guessIndex(parentGroup)); emptyExpand = false; } } return new AVAnnotationItemL(parentGroup, a); } } else { AnnotationGroup *childGroup = gr->getSubgroups().last(); if(treeWalker->isExpanded(childGroup)) { return getLastItemInSubtree(childGroup, view); } else { AVGroupItemL *parentGroup = view->findGroupItem(gr); //FIXME: what if group don't exist AVGroupItemL *upperGroup = view->findGroupItem(gr->getParentGroup()); if(parentGroup == NULL) { parentGroup = new AVGroupItemL(view, upperGroup, gr); insertItemBehindView(/*upperGroup->childCount() - 1 */0, parentGroup); if(treeWalker->isExpanded(gr)) { emptyExpand = true; expand(guessIndex(parentGroup)); emptyExpand = false; } } return new AVGroupItemL(view, parentGroup, childGroup); } } } AVItemL * LazyTreeView::getNextItemUp(){ //Get item upper than first on screen AVItemL *bottom = static_cast(onScreen.first()); AVItemL *nextItem = NULL; AVQualifierItemL *currentQual = NULL; AVAnnotationItemL *currentAnn = NULL; AVGroupItemL *currentGroup = NULL; AVGroupItemL *parentGroup = NULL; U2Qualifier qual; int index; switch(bottom->type) { case AVItemType_Qualifier: //If top item is qualifier currentQual = static_cast(bottom); currentAnn = static_cast(currentQual->parent()); qual = U2Qualifier(currentQual->qName, currentQual->qValue); index = currentAnn->annotation->getQualifiers().indexOf(qual); if(index == 0) { //Next item parent annotation return currentAnn; } else { //Or nearby qualifier if current qualifier not first nextItem = new AVQualifierItemL(currentAnn, currentAnn->annotation->getQualifiers()[index - 1]); return nextItem; } break; case AVItemType_Annotation: //If top item is annotation currentAnn = static_cast(bottom); currentGroup = static_cast(currentAnn->parent()); index = currentGroup->getAnnotationGroup()->getAnnotations().indexOf(currentAnn->annotation); if(index == 0) { //Next item is parent group return currentGroup; } else { //If not //If previous annotation is expanded if(treeWalker->isExpanded(currentGroup->getAnnotationGroup()->getAnnotations()[index - 1], currentGroup->getAnnotationGroup())) { AVAnnotationItemL * annItem = currentGroup->getAnnotationTreeView()->findAnnotationItem(currentGroup->getAnnotationGroup(), currentGroup->getAnnotationGroup()->getAnnotations()[index - 1]); //Previous annotation in group if(!annItem) { //If annotation not in tree, insert it in tree annItem = new AVAnnotationItemL(currentGroup, currentGroup->getAnnotationGroup()->getAnnotations()[index - 1]); insertItemBehindView(0, annItem); if(treeWalker->isExpanded(currentGroup->getAnnotationGroup()->getAnnotations()[index - 1], currentGroup->getAnnotationGroup())) { emptyExpand = true; expand(guessIndex(annItem)); emptyExpand = false; } } //Last qualifier of previous annotation nextItem = new AVQualifierItemL(annItem, annItem->annotation->getQualifiers().last()); return nextItem; } //Or annotation itself nextItem = new AVAnnotationItemL(currentGroup, currentGroup->getAnnotationGroup()->getAnnotations()[index - 1]); return nextItem; } break; case AVItemType_Group: //If top item is group currentGroup = static_cast(bottom); parentGroup = static_cast(currentGroup->parent()); if(parentGroup->parent() == NULL) { //If it top group index = parentGroup->indexOfChild(currentGroup); if(index == 0) { return NULL; //reached top of tree } else { AVGroupItemL *rootGroup = static_cast(parentGroup->child(index - 1)); //Another top group if(treeWalker->isExpanded(rootGroup->getAnnotationGroup())) {//If top group is expanded, get last item in it return getLastItemInSubtree(rootGroup->getAnnotationGroup(), rootGroup->getAnnotationTreeView()); } else { //or return top group return rootGroup; } } } index = parentGroup->getAnnotationGroup()->getSubgroups().indexOf(currentGroup->getAnnotationGroup()); if(index == 0) { return parentGroup; } else { if(treeWalker->isExpanded(parentGroup->getAnnotationGroup()->getSubgroups()[index - 1])) { return getLastItemInSubtree(parentGroup->getAnnotationGroup()->getSubgroups()[index - 1], parentGroup->getAnnotationTreeView()); } nextItem = new AVGroupItemL(parentGroup->getAnnotationTreeView(), parentGroup, parentGroup->getAnnotationGroup()->getSubgroups()[index - 1]); return nextItem; } break; default: assert(0); } return NULL; } void LazyTreeView::resizeModel(){ int dif = onScreen.size() - numOnScreen; if(dif == 0 || onScreen.isEmpty()) { return; } if(dif < 0) { //Expand view AVItemL *item = getNextItemDown(static_cast(onScreen.last())); while(item && dif < 0) { //Add items to bottom if(item->parent()->parent() == NULL) { insertItem(item->parent()->indexOfChild(item), item, false); } else { insertItem(item->parent()->childCount() - 1, item, false); } if(++dif < 0) { item = getNextItemDown(static_cast(onScreen.last())); } } if(dif < 0) { item = getNextItemUp(); } while(item && dif < 0) { //Add items to top flag = true; QTreeWidgetItem *last = onScreen.first(); if(item == last->parent()) { onScreen.insert(0, item); } else { insertItem(0, item); } if(++dif < 0) { item = getNextItemUp(); } } } else { //Narrow view while(dif > 0) { QTreeWidgetItem *item = onScreen.takeLast(); //delete all excess annotations removeItem(item); dif--; } } if(indexAt(QPoint(0,0)) != guessIndex(onScreen.first())) { flag = true; emptyExpand = true; scrollTo(guessIndex(onScreen.first()), QAbstractItemView::PositionAtTop); emptyExpand = false; } updateSlider(); } void LazyTreeView::calculateIndex( AnnotationTableObject *obj ){ treeWalker->recalculate(obj); } void LazyTreeView::updateSlider() { int maxVal; if(realNumberOfItems - numOnScreen < 0) { maxVal = 0; } else { maxVal = realNumberOfItems - numOnScreen; } CustomSlider *slider = static_cast(verticalScrollBar()); slider->setCustomPageStep(numOnScreen); slider->setPageStep(numOnScreen); slider->setMaxVal(maxVal); slider->setMaximum(slider->getMaxVal()); } int LazyTreeView::getPositionInTree(QTreeWidgetItem *item) { QList indexes; while(item->parent()) { indexes.prepend(item->parent()->indexOfChild(item)); item = item->parent(); } int pos = 0; foreach(int i, indexes) { for(int j = 0; j < i; j++) { pos += getExpandedNumber((AVItemL*)item->child(j)); } item = item->child(i); } return pos + indexes.last(); } LazyTreeView::LazyTreeView( QWidget * parent /*= 0 */ ) : QTreeView(parent) { connect(this, SIGNAL(expanded(const QModelIndex &)), SLOT(sl_expanded(const QModelIndex &))); connect(this, SIGNAL(entered(const QModelIndex &)), SLOT(sl_entered(const QModelIndex &))); connect(this, SIGNAL(collapsed(const QModelIndex&)), SLOT(sl_collapsed(const QModelIndex&))); //connect(verticalScrollBar(), SIGNAL(rangeChanged ( int, int)), SLOT(sl_rangeChanged(int, int))); numOnScreen = 14; setVerticalScrollBar(new CustomSlider(this)); verticalScrollBar()->setMouseTracking(true); flag = false; treeWalker = new TreeIndex(); realNumberOfItems = 0; emptyExpand = false; lineHeight = 1; } void LazyTreeView::selectionChanged( const QItemSelection & selected, const QItemSelection & deselected ) { QTreeView::selectionChanged(selected, deselected); emit itemSelectionChanged(); } void LazyTreeView::mouseDoubleClickEvent( QMouseEvent * event ) { LazyAnnotationTreeViewModel *modell = static_cast(model()); QPoint pos = event->pos(); QModelIndex index = indexAt(pos); QTreeWidgetItem *item = (QTreeWidgetItem *)modell->getItem(index); //selectionModel()->select(index, QItemSelectionModel::Select); QTreeView::mouseDoubleClickEvent(event); emit itemDoubleClicked(item, index.column()); } void LazyTreeView::mousePressEvent( QMouseEvent *event ) { LazyAnnotationTreeViewModel *modell = static_cast(model()); QPoint pos = event->pos(); QModelIndex index = indexAt(pos); QTreeWidgetItem *item = (QTreeWidgetItem *)modell->getItem(index); QTreeView::mousePressEvent(event); emit itemClicked(item, index.column()); } void LazyTreeView::resizeEvent( QResizeEvent *event ) { QTreeView::resizeEvent(event); numOnScreen = viewport()->height() / lineHeight; if(numOnScreen == 0) { numOnScreen = 1; } resizeModel(); } void LazyTreeView::sl_entered( const QModelIndex &index ) { LazyAnnotationTreeViewModel *modell = static_cast(model()); QTreeWidgetItem *item = (QTreeWidgetItem *)modell->getItem(index); emit itemEntered(item, index.column()); } void LazyTreeView::updateItem( QTreeWidgetItem *item ) { update(guessIndex(item)); setDirtyRegion(QRegion(visualRect(guessIndex(item)))); viewport()->repaint(); } void LazyTreeView::setLineHeight( int height ) { lineHeight = height; CustomSlider * slider = static_cast(verticalScrollBar()); slider->setRowHeight(height); } QModelIndex LazyTreeView::guessIndex( QTreeWidgetItem *item ) { LazyAnnotationTreeViewModel *lm = static_cast(model()); return lm->guessIndex(item); } void AnnotationsTreeViewL::focusOnItem(Annotation *a) { QList indexes; AnnotationGroup *topGroup = a->getGroups().first(); indexes << topGroup->getAnnotations().indexOf(a); /************************************************************************/ /*Create indexes of items from annotation to top group */ /************************************************************************/ while(topGroup->getParentGroup()) { indexes.insert(0, topGroup->getParentGroup()->getSubgroups().indexOf(topGroup)); topGroup = topGroup->getParentGroup(); } AVGroupItemL *topGroupItem = /*NULL*/findGroupItem(topGroup); LazyAnnotationTreeViewModel *lm = static_cast(tree->model()); AVItemL *root = lm->getItem(QModelIndex()); /************************************************************************/ /*Destroy old tree */ /************************************************************************/ assert(topGroupItem); for(int i = 0; i< root->childCount(); i++) { destroyTree(root->child(i)); } /************************************************************************/ /*Create all parent groups for given annotation */ /************************************************************************/ for(int i = 0; i < indexes.size() - 1; i++) { if(!findGroupItem(topGroupItem->group->getSubgroups()[indexes[i]])) { topGroupItem = createGroupItem(topGroupItem, topGroupItem->group->getSubgroups()[indexes[i]]); } else { topGroupItem = findGroupItem(topGroupItem->group->getSubgroups()[indexes[i]]); tree->onScreen.insert(0, topGroupItem); } } int num = tree->numOnScreen; QList oldList = tree->onScreen; tree->onScreen.clear(); int index = indexes.last(); createAnnotationItem(topGroupItem, topGroupItem->group->getAnnotations()[index], false); num--; AVItemL *item = tree->getNextItemDown(static_cast(tree->onScreen.last())); while(num > 0 && item) { tree->insertItem(item->parent()->childCount() - 1, item, false); num--; if(num > 0) { item = tree->getNextItemDown(static_cast(tree->onScreen.last())); } } if(num > 0) { item = tree->getNextItemUp(); } while(num > 0 && item) { if(!oldList.contains(item)) { tree->insertItem(0, item, false); if(tree->treeWalker->isExpanded(item)) { tree->expand(tree->guessIndex(item)); } } else { tree->onScreen.insert(0, item); } num--; if(num > 0) { item = tree->getNextItemUp(); } } /************************************************************************ Scroll to upper item on screen ************************************************************************/ if(tree->indexAt(QPoint(0,0)) != tree->guessIndex(tree->onScreen.first())) { tree->flag = true; CustomSlider *slider = static_cast(tree->verticalScrollBar()); slider->setPosition(tree->getPositionInTree(tree->onScreen.first())); tree->scrollTo(tree->guessIndex(tree->onScreen.first()), QAbstractItemView::PositionAtTop); } } CustomSlider::CustomSlider( QWidget *parent /*= NULL*/ ) : QScrollBar(parent), minVal(0), maxVal(0), sliderPos(0), rowHeight(1), dif(0){ setPageStep(14); //random value, will be changed by tree view setMouseTracking(true); sliderPressed = false; } void CustomSlider::setMaxVal( int _maxVal ){ maxVal = _maxVal; } int CustomSlider::getMaxVal() const { return maxVal; } void CustomSlider::setPosition( int pos ) { sliderPos = qBound(minVal,pos, maxVal); } void CustomSlider::setCustomPageStep( int /*ps*/ ) { //pageStep = ps; } void CustomSlider::sliderChange( SliderChange sc ) { if(sc == QAbstractSlider::SliderRangeChange) { if(!(maximum() == maxVal /*&& minimum() == minVal*/)) { setMaximum(maxVal); setMinimum(minVal); return; } } QScrollBar::sliderChange(sc); } void CustomSlider::paintEvent( QPaintEvent * ) { //QStyleOptionSlider options; options.initFrom(this); options.sliderPosition = sliderPos; options.maximum = maxVal; options.minimum = minVal; options.singleStep = 1; options.pageStep = pageStep(); options.orientation = Qt::Vertical; options.sliderValue = sliderPos; options.upsideDown = false; options.state = QStyle::State_Sunken | QStyle::State_Enabled; QPainter painter(this); style()->drawComplexControl(QStyle::CC_ScrollBar, &options, &painter); } int CustomSlider::sliderCustomPosition() const { return sliderPos; } void CustomSlider::mouseMoveEvent( QMouseEvent *me ) { if(me->buttons() & Qt::LeftButton && sliderPressed) { int newPos = QStyle::sliderValueFromPosition(minVal, maxVal, me->pos().y(), height()); int sDif = newPos - sliderPos; dif = qAbs(sDif); setSliderPosition(sliderPosition() + sDif); } } void CustomSlider::mousePressEvent(QMouseEvent *me) { if(me->button() == Qt::LeftButton) { QRect sliderRect = style()->subControlRect(QStyle::CC_ScrollBar, &options, QStyle::SC_ScrollBarSlider, this); //Slider QRect grooveRect = style()->subControlRect(QStyle::CC_ScrollBar, &options, QStyle::SC_ScrollBarGroove, this); //Free space where slider can move if(sliderRect.contains(me->pos())) { //mouse was pressed on slider -> scroll according to mouse move sliderPressed = true; } else if(grooveRect.contains(me->pos())) { //mouse was pressed on free space of scroll bar -> scroll on page step if(me->pos().y() < sliderRect.topLeft().y()) { dif = pageStep(); setSliderPosition(sliderPosition() - pageStep()); } else if(me->pos().y() > sliderRect.bottomLeft().y()) { dif = pageStep(); setSliderPosition(sliderPosition() + pageStep()); } } else{ //mouse was pressed on arrows if(me->pos().y() < sliderRect.topLeft().y()) { dif = 1; setSliderPosition(sliderPosition() - 1); } else if(me->pos().y() > sliderRect.bottomLeft().y()) { dif = 1; setSliderPosition(sliderPosition() + 1); } } return; } QScrollBar::mousePressEvent(me); //mouse was pressed on arrows or right button was pressed } void CustomSlider::mouseReleaseEvent(QMouseEvent *me) { if(me->button() == Qt::LeftButton) { sliderPressed = false; } } void CustomSlider::setRowHeight( int height ) { rowHeight = height; } int CustomSlider::numToScroll() const { return dif; } void CustomSlider::resetNumToScroll() { dif = 0; } }//namespace ugene-1.9.8/src/corelibs/U2View/src/util_ov_annotated_dna/ADVSingleSequenceWidget.cpp0000644000175000017500000010147411651544334027305 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "ADVSingleSequenceWidget.h" #include "ADVSequenceObjectContext.h" #include "AnnotatedDNAView.h" #include "ADVConstants.h" #include "DetView.h" #include "Overview.h" #include "CreateRulerDialogController.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include namespace U2 { #define ADV_HEADER_HEIGHT 24 #define IMAGE_DIR "image" ADVSingleSequenceWidget::ADVSingleSequenceWidget(ADVSequenceObjectContext* seqCtx, AnnotatedDNAView* ctx) : ADVSequenceWidget(ctx) { seqContexts.append(seqCtx); toggleViewAction = new QAction(this); connect(toggleViewAction, SIGNAL(triggered()), SLOT(sl_toggleView())); togglePanViewAction = new QAction(this); connect(togglePanViewAction, SIGNAL(triggered()), SLOT(sl_togglePanView())); toggleDetViewAction = new QAction(this); connect(toggleDetViewAction, SIGNAL(triggered()), SLOT(sl_toggleDetView())); toggleOverviewAction = new QAction(this); connect(toggleOverviewAction, SIGNAL(triggered()), SLOT(sl_toggleOverview())); connect(seqCtx->getAnnotatedDNAView()->getAnnotationsSelection(), SIGNAL(si_selectionChanged(AnnotationSelection* , const QList&, const QList&)), SLOT(sl_onAnnotationSelectionChanged(AnnotationSelection* , const QList&, const QList&))); selectRangeAction1 = new QAction(QIcon(":/core/images/select_region.png"), tr("Select sequence region..."), this); selectRangeAction1->setShortcut(QKeySequence(Qt::CTRL | Qt::Key_A)); selectRangeAction1->setObjectName("select_range_action"); selectRangeAction1->setShortcutContext(Qt::WidgetShortcut); connect(selectRangeAction1, SIGNAL(triggered()), SLOT(sl_onSelectRange())); selectRangeAction2 = new QAction(QIcon(":/core/images/select_region.png"), tr("Sequence region..."), this); connect(selectRangeAction2, SIGNAL(triggered()), SLOT(sl_onSelectRange())); selectInAnnotationRangeAction= new QAction(tr("Sequence between selected annotations"), this); connect(selectInAnnotationRangeAction, SIGNAL(triggered()), SLOT(sl_onSelectInRange())); selectOutAnnotationRangeAction= new QAction(tr("Sequence around selected annotations"), this); connect(selectOutAnnotationRangeAction, SIGNAL(triggered()), SLOT(sl_onSelectOutRange())); zoomToRangeAction = new QAction(QIcon(":/core/images/zoom_reg.png"), tr("Zoom to range.."), this); connect(zoomToRangeAction, SIGNAL(triggered()), SLOT(sl_zoomToRange())); createNewRulerAction = new QAction(tr("Create new ruler..."), this); connect(createNewRulerAction, SIGNAL(triggered()), SLOT(sl_createCustomRuler())); linesLayout = new QVBoxLayout(); linesLayout->setMargin(0); linesLayout->setSpacing(0); setLayout(linesLayout); headerWidget = new ADVSingleSequenceHeaderWidget(this); headerWidget->installEventFilter(this); linesLayout->addWidget(headerWidget); init(); } void ADVSingleSequenceWidget::init() { ADVSequenceObjectContext* seqCtx = getSequenceContext(); detView = new DetView(this, seqCtx); detView->setObjectName("det_view"); addSequenceView(detView); panView = new PanView(this, seqCtx); panView->setObjectName("pan_view"); connect(panView, SIGNAL(si_centerPosition(int)), SLOT(sl_onLocalCenteringRequest(int))); zoomUseObject.setPanView(panView); addSequenceView(panView, headerWidget); panView->setFrameView(detView); overview = new Overview(this, seqCtx); overview->setObjectName("overview"); overview->setMouseTracking(true); addSequenceView(overview, headerWidget); setFixedHeight(linesLayout->minimumSize().height()); QToolBar* hBar = headerWidget->getToolBar(); hBar->addAction(selectRangeAction1); hBar->addSeparator(); if (seqCtx->getComplementTT() != NULL) { QAction* showComplementAction = detView->getShowComplementAction(); hBar->addAction(showComplementAction); } if (seqCtx->getAminoTT() != NULL) { QAction* showTranslationAction = detView->getShowTranslationAction(); hBar->addAction(showTranslationAction); } if (seqCtx->getAminoTT() != NULL) { ttButton = new QToolButton(hBar); QMenu* ttMenu = seqCtx->createTranslationsMenu(); ttButton->setDefaultAction(ttMenu->menuAction()); ttButton->setPopupMode(QToolButton::InstantPopup); hBar->addWidget(ttButton); tbMenues.append(ttMenu); hBar->addSeparator(); } else { ttButton = NULL; } QAction* shotScreenAction = new QAction(QIcon(":/core/images/cam2.png"), tr("Capture screen"), this); shotScreenAction->setObjectName("capture_screen"); connect(shotScreenAction, SIGNAL(triggered()), this, SLOT(sl_saveScreenshot())); hBar->addAction(shotScreenAction); hBar->addAction(panView->getZoomInAction()); hBar->addAction(panView->getZoomOutAction()); //hBar->addAction(panView->getZoomToSelectionAction()); hBar->addAction(zoomToRangeAction); hBar->addAction(panView->getZoomToSequenceAction()); hBar->addWidget(panView->getPanViewActions()); updateSelectionActions(); #define MIN_SEQUENCE_LEN_TO_USE_FULL_MODE 100 if (seqCtx->getSequenceLen() < MIN_SEQUENCE_LEN_TO_USE_FULL_MODE) { //sequence is rather small -> show panview only by default setOverviewCollapsed(true); setDetViewCollapsed(true); } } ADVSingleSequenceWidget::~ADVSingleSequenceWidget() { foreach(QMenu* m, tbMenues) { delete m; } } bool ADVSingleSequenceWidget::isPanViewCollapsed() const { return panView->isHidden(); } bool ADVSingleSequenceWidget::isDetViewCollapsed() const { return detView->isHidden(); } bool ADVSingleSequenceWidget::isOverviewCollapsed() const { return overview->isHidden(); } bool ADVSingleSequenceWidget::isViewCollapsed() const { bool collapsed = true; foreach(GSequenceLineView* seqView, lineViews) { if (seqView->isVisible()) { collapsed = false; break; } } return collapsed; } void ADVSingleSequenceWidget::setViewCollapsed(bool v) { foreach(GSequenceLineView* seqView, lineViews) { seqView->setHidden(v); } updateMinMaxHeight(); } void ADVSingleSequenceWidget::setPanViewCollapsed(bool v) { panView->setHidden(v); updateMinMaxHeight(); if (isPanViewCollapsed()) { zoomUseObject.releaseZoom(); } else { zoomUseObject.useZoom(); } zoomToRangeAction->setDisabled( isPanViewCollapsed() ); } void ADVSingleSequenceWidget::setDetViewCollapsed(bool v) { detView->setHidden(v); if (ttButton != NULL) { ttButton->setDisabled(v); } updateMinMaxHeight(); } void ADVSingleSequenceWidget::setOverviewCollapsed(bool v) { overview->setHidden(v); updateMinMaxHeight(); } void ADVSingleSequenceWidget::addSequenceView(GSequenceLineView* v, QWidget* after) { assert(!lineViews.contains(v)); lineViews.append(v); if (after==NULL) { if(lineViews.size()>1) { linesLayout->insertWidget(2, v); } else { linesLayout->insertWidget(1, v); } } else { int after_ = linesLayout->indexOf(after); assert(after_!=-1); linesLayout->insertWidget(after_+1, v); } v->setVisible(true); v->installEventFilter(this); updateMinMaxHeight(); connect(v, SIGNAL(destroyed(QObject*)), SLOT(sl_onViewDestroyed(QObject*))); } void ADVSingleSequenceWidget::removeSequenceView(GSequenceLineView* v, bool deleteView) { assert(lineViews.contains(v)); lineViews.removeOne(v); linesLayout->removeWidget(v); v->setVisible(false); v->disconnect(this); v->removeEventFilter(this); if (deleteView) { delete v; } updateMinMaxHeight(); } U2Region ADVSingleSequenceWidget::getVisibleRange() const { return panView->getVisibleRange(); } void ADVSingleSequenceWidget::setVisibleRange(const U2Region& r) { return panView->setVisibleRange(r); } int ADVSingleSequenceWidget::getNumBasesVisible() const { return panView->getVisibleRange().length; } void ADVSingleSequenceWidget::setNumBasesVisible(int n) { panView->setNumBasesVisible(n); } void ADVSingleSequenceWidget::sl_onViewDestroyed(QObject* o) { GSequenceLineView* v = static_cast(o); bool r = lineViews.removeOne(v); linesLayout->removeWidget(v);//need here for updateMinMaxHeight assert(r); Q_UNUSED(r); updateMinMaxHeight(); } void ADVSingleSequenceWidget::centerPosition(int pos, QWidget* skipView) { foreach(GSequenceLineView* v, lineViews) { if (v == skipView) { continue; } v->setCenterPos(pos); } } void ADVSingleSequenceWidget::updateMinMaxHeight() { int height = linesLayout->minimumSize().height(); setFixedHeight(height); } void ADVSingleSequenceWidget::addZoomMenu(const QPoint& globalPos, QMenu* m) { GSequenceLineView* lineView = findSequenceViewByPos(globalPos); if (lineView == NULL) { return; } QAction* first = m->actions().isEmpty() ? NULL : m->actions().first(); QAction * zoomInAction = lineView->getZoomInAction(); QAction * zoomOutAction = lineView->getZoomOutAction(); QAction * zoomToSelection = lineView->getZoomToSelectionAction(); QAction * zoomToSequence = lineView->getZoomToSequenceAction(); if (zoomInAction == NULL && zoomOutAction == NULL && zoomToSelection == NULL && zoomToSequence == NULL) { return; } QMenu* zm = m->addMenu(tr("Zoom")); if (zoomInAction!=NULL) { zm->insertAction(first, zoomInAction); } if (zoomOutAction!=NULL) { zm->insertAction(first, zoomOutAction); } if (zoomToSelection!=NULL) { zm->insertAction(first, zoomToSelection); } if (lineView == panView || lineView->getConherentRangeView() == panView) { zm->insertAction(first, zoomToRangeAction); } if (zoomToSequence!=NULL) { zm->insertAction(first, zoomToSequence); } zm->menuAction()->setObjectName(ADV_MENU_ZOOM); m->addSeparator(); } GSequenceLineView* ADVSingleSequenceWidget::findSequenceViewByPos(const QPoint& globalPos) const { Q_UNUSED(globalPos); assert(0); return NULL; } int ADVSingleSequenceWidget::getSequenceLen() const { return getSequenceContext()->getSequenceLen(); } DNATranslation* ADVSingleSequenceWidget::getComplementTT() const { ADVSequenceObjectContext* seqCtx = getSequenceContext(); return seqCtx->getComplementTT(); } DNATranslation* ADVSingleSequenceWidget::getAminoTT() const { ADVSequenceObjectContext* seqCtx = getSequenceContext(); return seqCtx->getAminoTT(); } DNASequenceSelection* ADVSingleSequenceWidget::getSequenceSelection() const { ADVSequenceObjectContext* seqCtx = getSequenceContext(); return seqCtx->getSequenceSelection(); } DNASequenceObject* ADVSingleSequenceWidget::getSequenceObject() const { ADVSequenceObjectContext* seqCtx = getSequenceContext(); return seqCtx->getSequenceObject(); } GSequenceLineView* ADVSingleSequenceWidget::getPanGSLView() const { return panView; } GSequenceLineView* ADVSingleSequenceWidget::getDetGSLView() const { return detView; } void ADVSingleSequenceWidget::buildPopupMenu(QMenu& m) { m.insertAction(GUIUtils::findActionAfter(m.actions(), ADV_GOTO_ACTION), getAnnotatedDNAView()->getCreateAnnotationAction()); m.insertAction(GUIUtils::findActionAfter(m.actions(), ADV_GOTO_ACTION), selectRangeAction1); addSelectMenu(m); if (panView->isVisible()) { addRulersMenu(m); } ADVSequenceWidget::buildPopupMenu(m); foreach(GSequenceLineView* v, lineViews) { v->buildPopupMenu(m); } } void ADVSingleSequenceWidget::addSelectMenu(QMenu& m) { QMenu* selectMenu = new QMenu(tr("Select"), &m); selectMenu->addAction(selectRangeAction2); selectMenu->addAction(selectInAnnotationRangeAction); selectMenu->addAction(selectOutAnnotationRangeAction); QAction* aBefore = GUIUtils::findActionAfter(m.actions(), ADV_MENU_COPY); m.insertMenu(aBefore, selectMenu); } void ADVSingleSequenceWidget::addRulersMenu(QMenu& m) { qDeleteAll(rulerActions.qlist); rulerActions.qlist.clear(); QMenu* rulersM = new QMenu(tr("Rulers..."), &m); rulersM->setIcon(QIcon(":core/images/ruler.png")); rulersM->addAction(createNewRulerAction); rulersM->addSeparator(); rulersM->addAction(panView->getToggleMainRulerAction()); rulersM->addAction(panView->getToggleCustomRulersAction()); rulersM->addSeparator(); foreach(const RulerInfo& ri, panView->getCustomRulers()) { QAction* rulerAction = new QAction(tr("Remove '%1'").arg(ri.name), this); rulerAction->setData(ri.name); connect(rulerAction, SIGNAL(triggered()), SLOT(sl_removeCustomRuler())); rulerActions.qlist.append(rulerAction); } rulersM->addActions(rulerActions.qlist); QAction* aBefore = GUIUtils::findActionAfter(m.actions(), ADV_MENU_SECTION2_SEP); m.insertMenu(aBefore, rulersM); m.insertSeparator(aBefore)->setObjectName("SECOND_SEP"); } bool ADVSingleSequenceWidget::isWidgetOnlyObject(GObject* o) const { foreach(GSequenceLineView* v, lineViews) { ADVSequenceObjectContext *ctx = v->getSequenceContext(); if(ctx->getSequenceGObject() == o) { return true; } } return false; } bool ADVSingleSequenceWidget::eventFilter(QObject* o, QEvent* e) { QEvent::Type t = e->type(); if (t == QEvent::Resize) { GSequenceLineView* v = qobject_cast(o); if (lineViews.contains(v)) { updateMinMaxHeight(); } } else if (t == QEvent::FocusIn || t == QEvent::MouseButtonPress || t == QEvent::MouseButtonRelease) { ctx->setFocusedSequenceWidget(this); } return false; } void ADVSingleSequenceWidget::sl_onLocalCenteringRequest(int pos) { detView->setCenterPos(pos); } void ADVSingleSequenceWidget::addADVSequenceWidgetAction(ADVSequenceWidgetAction* a) { ADVSequenceWidget::addADVSequenceWidgetAction(a); if (a->addToBar) { QToolBar* tb = headerWidget->getToolBar(); if (a->menu()!=NULL) { QToolButton* tt = new QToolButton(tb); tt->setDefaultAction(a); tt->setPopupMode(QToolButton::InstantPopup); tb->insertWidget(tb->actions().first(), tt); } else { tb->insertAction(tb->actions().first(), a); } } } void ADVSingleSequenceWidget::sl_onSelectRange() { QDialog dlg(this); dlg.setModal(true); dlg.setWindowTitle(tr("Select range")); ADVSequenceObjectContext* ctx = getSequenceContext(); DNASequenceSelection* selection=ctx->getSequenceSelection(); RangeSelector* rs; if(selection->isEmpty()){ rs=new RangeSelector(&dlg, 1, ctx->getSequenceLen(), ctx->getSequenceLen(), true); }else{ rs=new RangeSelector(&dlg, selection->getSelectedRegions().first().startPos + 1, selection->getSelectedRegions().first().endPos(), ctx->getSequenceLen(), true); } int rc = dlg.exec(); if (rc == QDialog::Accepted) { U2Region r(rs->getStart() - 1, rs->getEnd() - rs->getStart() + 1); ctx->getSequenceSelection()->clear(); getSequenceSelection()->addRegion(r); if (!detView->getVisibleRange().intersects(r)) { detView->setCenterPos(r.startPos); } } delete rs; } QVector ADVSingleSequenceWidget::getSelectedAnnotationRegions(int max) { ADVSequenceObjectContext* seqCtx = getSequenceContext(); const QList selection = seqCtx->getAnnotatedDNAView()->getAnnotationsSelection()->getSelection(); const QSet myAnns = seqCtx->getAnnotationObjects(true); QVector res; foreach(const AnnotationSelectionData& sd, selection) { AnnotationTableObject* aObj = sd.annotation->getGObject(); if (myAnns.contains(aObj)) { res << sd.getSelectedRegions(); if (max > 0 && res.size() >= max) { break; } } } return res; } void ADVSingleSequenceWidget::sl_onSelectInRange() { QVector selRegs = getSelectedAnnotationRegions(3); assert(selRegs.size() == 2); const U2Region& r1 = selRegs.at(0); const U2Region& r2 = selRegs.at(1); assert(!r1.intersects(r2)); U2Region r; r.startPos = qMin(r1.endPos(), r2.endPos()); r.length = qMax(r1.startPos, r2.startPos) - r.startPos; getSequenceContext()->getSequenceSelection()->clear(); getSequenceContext()->getSequenceSelection()->addRegion(r); } void ADVSingleSequenceWidget::sl_onSelectOutRange() { QVector selRegs = getSelectedAnnotationRegions(0); assert(!selRegs.isEmpty()); U2Region r = U2Region::containingRegion(selRegs); getSequenceContext()->getSequenceSelection()->clear(); getSequenceContext()->getSequenceSelection()->addRegion(r); } void ADVSingleSequenceWidget::sl_zoomToRange() { QDialog dlg(this); dlg.setModal(true); dlg.setWindowTitle(tr("Zoom to range")); DNASequenceSelection* sel = getSequenceSelection(); int start=getVisibleRange().startPos + 1, end=getVisibleRange().endPos(); if (!sel->isEmpty()) { const QVector& regions = sel->getSelectedRegions(); start=regions.first().startPos+1; end=regions.first().endPos(); } RangeSelector* rs = new RangeSelector(&dlg, start, end, getSequenceLen(), true); int rc = dlg.exec(); if (rc == QDialog::Accepted) { U2Region r(rs->getStart() - 1, rs->getEnd() - rs->getStart() + 1); panView->setVisibleRange(r); detView->setStartPos(r.startPos); } delete rs; } #define SPLITTER_STATE_MAP_NAME "ADVSI_MAP" #define PAN_REG_NAME "PAN_REG" #define DET_POS_NAME "DET_POS" #define OVERVIEW_VISIBLE "OVERVIEW_VISIBLE" #define PAN_VISIBLE "PAN_VISIBLE" #define DET_VISIBLE "DET_VISIBLE" #define MAIN_RULER_VISIBLE "MAINR_VISIBLE" #define CUSTOM_RULERS_VISIBLE "CUSTOMR_VISIBLE" #define CUSTOM_R_NAMES "CUSTOMR_NAMES" #define CUSTOM_R_COLORS "CUSTOMR_COLORS" #define CUSTOM_R_OFFSETS "CUSTOMR_OFFSETS" void ADVSingleSequenceWidget::updateState(const QVariantMap& m) { QVariantMap map = m.value(SPLITTER_STATE_MAP_NAME).toMap(); QString sequenceInProjectId = getActiveSequenceContext()->getSequenceObject()->getGHints()->get(GObjectHint_InProjectId).toString(); QVariantMap myData = map.value(sequenceInProjectId).toMap(); U2Region panReg = myData.value(PAN_REG_NAME).value(); int detPos = myData.value(DET_POS_NAME).toInt(); U2Region seqRange(0, getActiveSequenceContext()->getSequenceLen()); if (seqRange.contains(detPos)) { detView->setStartPos(detPos); } if (!panReg.isEmpty() && seqRange.contains(panReg)) { panView->setVisibleRange(panReg); } bool overIsVisible = myData.value(OVERVIEW_VISIBLE, true).toBool(); setOverviewCollapsed(!overIsVisible); bool panIsVisible = myData.value(PAN_VISIBLE, true).toBool(); setPanViewCollapsed(!panIsVisible); bool detIsVisible = myData.value(DET_VISIBLE, true).toBool(); setDetViewCollapsed(!detIsVisible); bool mainRulerVisible = myData.value(MAIN_RULER_VISIBLE, true).toBool(); panView->getToggleMainRulerAction()->setChecked(mainRulerVisible); bool customRulersVisible = myData.value(CUSTOM_RULERS_VISIBLE, true).toBool(); panView->getToggleCustomRulersAction()->setChecked(customRulersVisible); QStringList rnames = myData[CUSTOM_R_NAMES].toStringList(); QList rcolors = myData[CUSTOM_R_COLORS].toList(); QList roffsets = myData[CUSTOM_R_OFFSETS].toList(); if (rnames.count() == rcolors.count() && rnames.count() == roffsets.count()) { panView->removeAllCustomRulers(); for (int i=0; i< rnames.count(); i++) { QString name = rnames[i]; int offset = roffsets[i].toInt(); QColor color = rcolors[i].value(); panView->addCustomRuler(RulerInfo(name, offset, color)); } } } void ADVSingleSequenceWidget::saveState(QVariantMap& m) { QVariantMap map = m.value(SPLITTER_STATE_MAP_NAME).toMap(); QVariantMap myData; myData[PAN_REG_NAME] = QVariant::fromValue(panView->getVisibleRange()); myData[DET_POS_NAME] = QVariant::fromValue(detView->getVisibleRange().startPos); myData[OVERVIEW_VISIBLE] = !isOverviewCollapsed(); myData[PAN_VISIBLE] = !isPanViewCollapsed(); myData[DET_VISIBLE] = !isDetViewCollapsed(); myData[MAIN_RULER_VISIBLE] = panView->getToggleMainRulerAction()->isChecked(); myData[CUSTOM_RULERS_VISIBLE] = panView->getToggleCustomRulersAction()->isChecked(); QStringList rnames; QList roffsets; QList rcolors; foreach(const RulerInfo& ri, panView->getCustomRulers()) { rnames.append(ri.name); roffsets.append(ri.offset); rcolors.append(ri.color); } myData[CUSTOM_R_NAMES] = rnames; myData[CUSTOM_R_OFFSETS] = roffsets; myData[CUSTOM_R_COLORS] = rcolors; QString sequenceInProjectId = getActiveSequenceContext()->getSequenceObject()->getGHints()->get(GObjectHint_InProjectId).toString(); map[sequenceInProjectId] = myData; m[SPLITTER_STATE_MAP_NAME] = map; } // QT 4.5.0 bug workaround void ADVSingleSequenceWidget::sl_closeView() { closeView(); } void ADVSingleSequenceWidget::sl_saveScreenshot() { QRect screenRect = QRect(linesLayout->itemAt(1)->geometry().topLeft().x(), linesLayout->itemAt(1)->geometry().topLeft().y(), this->geometry().bottomRight().x(), this->geometry().bottomRight().y()); ExportImageDialog dialog(this, screenRect); dialog.exec(); } void ADVSingleSequenceWidget::closeView() { DNASequenceObject* dnaObj = getSequenceObject(); AnnotatedDNAView* v = getAnnotatedDNAView(); v->removeObject(dnaObj); } void ADVSingleSequenceWidget::sl_createCustomRuler() { QSet namesToFilter; foreach(const RulerInfo& ri, panView->getCustomRulers()) { namesToFilter.insert(ri.name); } int offset = panView->getVisibleRange().center(); AnnotationSelection * annSelection = getDetGSLView()->getSequenceContext()->getAnnotationsSelection(); DNASequenceObject * seqObj = getSequenceObject(); int annOffset = INT_MAX; foreach(const AnnotationSelectionData & selectionData, annSelection->getSelection()) { Annotation * ann = selectionData.annotation; AnnotationTableObject * annObj = ann->getGObject(); if( !annObj->hasObjectRelation(seqObj, GObjectRelationRole::SEQUENCE) ) { continue; } // find minimum of start positions of selected annotations foreach( const U2Region & region, selectionData.getSelectedRegions() ) { annOffset = annOffset > region.startPos ? region.startPos : annOffset; } } if( annOffset != INT_MAX ) { offset = annOffset; } QVector selection = getSequenceSelection()->getSelectedRegions(); if(!selection.isEmpty()) { offset = selection.first().startPos; } CreateRulerDialogController d(namesToFilter, getSequenceObject()->getSequenceRange(), offset); int rc = d.exec(); if (rc != QDialog::Accepted) { return; } RulerInfo ri(d.name, d.offset, d.color); panView->addCustomRuler(ri); } void ADVSingleSequenceWidget::sl_removeCustomRuler() { QString rulerName = qobject_cast(sender())->data().toString(); panView->removeCustomRuler(rulerName); } void ADVSingleSequenceWidget::sl_onAnnotationSelectionChanged(AnnotationSelection* s, const QList&, const QList&) { // make sequence selection to match external annotation bounds QVector annotatedRegions = s->getSelectedLocations(getSequenceContext()->getAnnotationObjects(true)); if (!annotatedRegions.isEmpty()) { QVector joinedRegions = U2Region::join(annotatedRegions); getSequenceContext()->getSequenceSelection()->setSelectedRegions(joinedRegions); } updateSelectionActions(); } void ADVSingleSequenceWidget::updateSelectionActions() { QVector selRegs = getSelectedAnnotationRegions(3); selectInAnnotationRangeAction->setEnabled(selRegs.size() == 2 && !selRegs[0].intersects(selRegs[1])); selectOutAnnotationRangeAction->setEnabled(!selRegs.isEmpty()); } void ADVSingleSequenceWidget::addStateActions( QMenu& m ) { toggleViewAction->setText(isViewCollapsed() ? tr("Show all views") : tr("Hide all views")); togglePanViewAction->setText(isPanViewCollapsed() ? tr("Show zoom view") : tr("Hide zoom view")); toggleDetViewAction->setText(isDetViewCollapsed() ? tr("Show details view") : tr("Hide details view")); toggleOverviewAction->setText(isOverviewCollapsed() ? tr("Show overview") : tr("Hide overview")); m.addAction(toggleViewAction); m.addAction(toggleDetViewAction); m.addAction(togglePanViewAction); m.addAction(toggleOverviewAction); } void ADVSingleSequenceWidget::sl_toggleView(){ bool newStateCollapsed = !isViewCollapsed(); setViewCollapsed(newStateCollapsed); } void ADVSingleSequenceWidget::sl_togglePanView(){ setPanViewCollapsed(!isPanViewCollapsed()); } void ADVSingleSequenceWidget::onSequenceObjectRenamed(const QString&) { headerWidget->updateTitle(); } ////////////////////////////////////////////////////////////////////////// // header ADVSingleSequenceHeaderWidget::ADVSingleSequenceHeaderWidget(ADVSingleSequenceWidget* p) : QWidget(p), ctx(p) { setFixedHeight(ADV_HEADER_HEIGHT); setBackgroundRole(QPalette::Window); setAutoFillBackground(true); connect(ctx->getAnnotatedDNAView(), SIGNAL(si_focusChanged(ADVSequenceWidget*, ADVSequenceWidget*)), SLOT(sl_advFocusChanged(ADVSequenceWidget*, ADVSequenceWidget*))); //TODO: track focus events (mouse clicks) on toolbar in disabled state and on disabled buttons !!! QHBoxLayout* l = new QHBoxLayout(); l->setSpacing(4); l->setContentsMargins(5, 1, 0, 2); DNASequenceObject* seqObj = ctx->getSequenceObject(); QString objName = seqObj->getGObjectName(); pixLabel= new QLabel(this); QFont f = pixLabel->font(); if (f.pixelSize() > ADV_HEADER_HEIGHT) { f.setPixelSize(ADV_HEADER_HEIGHT-8); } QIcon objIcon(":/core/images/gobject.png"); QPixmap pix = objIcon.pixmap(QSize(16, 16), QIcon::Active); pixLabel->setPixmap(pix); pixLabel->setFont(f); QString objInfoTip = "" + objName + "" + "
    " + tr("Alphabet: %1").arg(seqObj->getAlphabet()->getName()) + "
    " + tr(" Sequence size: %1").arg(seqObj->getSequenceLen()) + "
    " + tr(" File: %1").arg(seqObj->getDocument()->getURLString()); pixLabel->setToolTip(objInfoTip); pixLabel->installEventFilter(this); int labelWidth = 50; QFontMetrics fm(f); nameLabel = new QLabel("", this); updateTitle(); nameLabel->setAlignment(Qt::AlignLeft | Qt::AlignVCenter); nameLabel->setMinimumWidth(labelWidth); nameLabel->setMaximumWidth(fm.width(nameLabel->text())); nameLabel->setFont(f); nameLabel->setToolTip(objInfoTip); nameLabel->setTextInteractionFlags(Qt::TextSelectableByMouse); toolBar = new HBar(this); toolBar->layout()->setSpacing(0); toolBar->layout()->setMargin(0); /// close bar closeBar = new HBar(this); closeBar->layout()->setSpacing(0); closeBar->layout()->setMargin(0); setLayout(l); l->addWidget(pixLabel); l->addWidget(nameLabel); l->addStretch(); l->addWidget(toolBar); l->addWidget(closeBar); connect(toolBar, SIGNAL(actionTriggered(QAction*)), SLOT(sl_actionTriggered(QAction*))); connect(closeBar, SIGNAL(actionTriggered(QAction*)), SLOT(sl_actionTriggered(QAction*))); populateToolBars(); updateActiveState(); } void ADVSingleSequenceHeaderWidget::updateTitle() { DNASequenceObject* seqObj = ctx->getSequenceObject(); QString newTitle = seqObj->getGObjectName() + " [" + getShortAlphabetName(seqObj->getAlphabet()) +"]"; setTitle(newTitle); } void ADVSingleSequenceHeaderWidget::populateToolBars() { // close bar widgetStateMenuButton = new QToolButton(this); widgetStateMenuButton->setIcon(QIcon(":core/images/adv_widget_menu.png")); widgetStateMenuButton->setFixedWidth(20); widgetStateMenuButton->setToolTip(tr("Toggle view")); connect(widgetStateMenuButton, SIGNAL(pressed()), SLOT(sl_showStateMenu())); closeViewAction = new QAction(tr("Remove sequence"), ctx); connect(closeViewAction, SIGNAL(triggered()), SLOT(sl_closeView())); closeBar->addWidget(widgetStateMenuButton); } bool ADVSingleSequenceHeaderWidget::eventFilter(QObject *o, QEvent *e) { if (o == pixLabel && e->type() == QEvent::MouseButtonPress) { sl_showStateMenu(); return true; } return false; } void ADVSingleSequenceHeaderWidget::sl_actionTriggered(QAction* a){ Q_UNUSED(a); ctx->getAnnotatedDNAView()->setFocusedSequenceWidget(ctx); } void ADVSingleSequenceHeaderWidget::sl_advFocusChanged(ADVSequenceWidget* prevFocus, ADVSequenceWidget* newFocus) { if (prevFocus == ctx || newFocus == ctx) { update(); updateActiveState(); } } void ADVSingleSequenceHeaderWidget::updateActiveState() { bool focused = ctx->getAnnotatedDNAView()->getSequenceWidgetInFocus() == ctx; nameLabel->setEnabled(focused); pixLabel->setEnabled(focused); ctx->getSelectRangeAction()->setShortcutContext(focused ? Qt::WindowShortcut : Qt::WidgetShortcut); //toolBar->setEnabled(focused); TODO: click on disabled buttons does not switch focus! } void ADVSingleSequenceHeaderWidget::sl_showStateMenu() { QPointer widgetStateMenuButtonPtr(widgetStateMenuButton); QMenu m; ctx->addStateActions(m); m.addAction(closeViewAction); m.exec(QCursor::pos()); if (!widgetStateMenuButtonPtr.isNull()) { //if not self closed widgetStateMenuButtonPtr->setDown(false); } } void ADVSingleSequenceHeaderWidget::sl_closeView() { #ifdef Q_OS_LINUX if(QString("4.5.0") == qVersion()) { QTimer::singleShot(0,ctx,SLOT(sl_closeView())); } else { #endif // Q_OS_LINUX ctx->closeView(); #ifdef Q_OS_LINUX } #endif // Q_OS_LINUX } void ADVSingleSequenceHeaderWidget::mouseDoubleClickEvent(QMouseEvent *e) { ctx->toggleViewAction->trigger(); QWidget::mouseDoubleClickEvent(e); } void ADVSingleSequenceHeaderWidget::paintEvent(QPaintEvent *e) { QWidget::paintEvent(e); QPainter p(this); p.setPen(QApplication::palette().color(QPalette::Dark)); p.drawLine(0, height()-1, width(), height()-1); } QString ADVSingleSequenceHeaderWidget::getShortAlphabetName(DNAAlphabet* al) { DNAAlphabetType type = al->getType(); if (type == DNAAlphabet_RAW) { return tr("raw"); } if (type == DNAAlphabet_AMINO) { return tr("amino"); } assert(type == DNAAlphabet_NUCL); QString id = al->getId(); if (id == BaseDNAAlphabetIds::NUCL_DNA_DEFAULT()) { return tr("dna"); } else if (id == BaseDNAAlphabetIds::NUCL_DNA_EXTENDED()) { return tr("dna ext"); } else if (id == BaseDNAAlphabetIds::NUCL_RNA_DEFAULT()) { return tr("rna"); } else if (id == BaseDNAAlphabetIds::NUCL_RNA_EXTENDED()) { return tr("rna ext"); } return "?"; } }//namespace ugene-1.9.8/src/corelibs/U2View/src/util_ov_annotated_dna/GSequenceLineViewAnnotated.h0000644000175000017500000001175111651544334027517 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_GSEQUENCE_LINE_VIEW_ANNOTATED_H_ #define _U2_GSEQUENCE_LINE_VIEW_ANNOTATED_H_ #include "GSequenceLineView.h" #include #include namespace U2 { class AnnotationTableObject; class AnnotationSettings; class AnnotationModification; class ClearAnnotationsTask; class U2VIEW_EXPORT GSequenceLineViewAnnotated : public GSequenceLineView { Q_OBJECT public: class DrawSettings { public: DrawSettings() : drawAnnotationNames(false), drawAnnotationArrows(false), drawCutSites(true){} bool drawAnnotationNames; bool drawAnnotationArrows; bool drawCutSites; }; GSequenceLineViewAnnotated(QWidget* p, ADVSequenceObjectContext* ctx); bool isAnnotationVisible(Annotation* a) const; const DrawSettings& getDrawSettings() const {return drawSettings;} virtual QList selectAnnotationByCoord(const QPoint& coord) const; static QString prepareAnnotationText(const Annotation* a, const AnnotationSettings* as); QList findAnnotationsInRange(const U2Region& range); protected: void mousePressEvent(QMouseEvent * e); virtual bool event(QEvent* e); virtual QString createToolTip(QHelpEvent* e); virtual void registerAnnotations(const QList& l){ Q_UNUSED(l); } virtual void unregisterAnnotations(const QList& l){ Q_UNUSED(l); } virtual void ensureVisible(Annotation* a, int locationIdx); protected slots: virtual void sl_onAnnotationSettingsChanged(const QStringList& changedSettings); void sl_onAnnotationObjectAdded(AnnotationTableObject*); void sl_onAnnotationObjectRemoved(AnnotationTableObject*); void sl_onAnnotationsInGroupRemoved(const QList&, AnnotationGroup*); void sl_onAnnotationsAdded(const QList&); void sl_onAnnotationsRemoved(const QList&); virtual void sl_onAnnotationsModified(const AnnotationModification& md); virtual void sl_onAnnotationSelectionChanged(AnnotationSelection*, const QList& added, const QList& removed); private: void connectAnnotationObject(AnnotationTableObject* ao); protected: DrawSettings drawSettings; friend class ClearAnnotationsTask; }; class U2VIEW_EXPORT GSequenceLineViewAnnotatedRenderArea : public GSequenceLineViewRenderArea { public: GSequenceLineViewAnnotatedRenderArea(GSequenceLineViewAnnotated* d, bool annotationsCanOverlap); ~GSequenceLineViewAnnotatedRenderArea(); virtual U2Region getAnnotationYRange(Annotation* a, int region, const AnnotationSettings* as) const = 0; GSequenceLineViewAnnotated* getGSequenceLineViewAnnotated() const {return (GSequenceLineViewAnnotated*)view;} protected: virtual void drawAnnotations(QPainter& p); virtual void drawBoundedText(QPainter& p, const QRect& r, const QString& text) const; virtual void drawAnnotationConnections(QPainter& p, Annotation* a, const AnnotationSettings* as); virtual void drawAnnotationsSelection(QPainter& p); virtual void drawCutSite(QPainter& p, const QRect& r, int pos, bool direct); bool isAnnotationSelectionInVisibleRange() const; enum DrawAnnotationPass { DrawAnnotationPass_DrawFill, DrawAnnotationPass_DrawBorder }; void drawAnnotation(QPainter& p, DrawAnnotationPass pass, Annotation* a, const QPen& borderPen, bool selected = false, const AnnotationSettings* as = NULL, U2Region y = U2Region()); protected: bool annotationsCanOverlap; //af* == annotation font QFont* afNormal; QFont* afSmall; QFontMetrics* afmNormal; QFontMetrics* afmSmall; int afNormalCharWidth; int afSmallCharWidth; QBrush gradientMaskBrush; }; class ClearAnnotationsTask:public Task { public: ClearAnnotationsTask(const QList& _list, AnnotationTableObject *_aobj, GSequenceLineViewAnnotated *_view): Task("Clear annotations", TaskFlag_None), l(_list), aobj(_aobj), view(_view) {} void run(); Task::ReportResult report(); private: QList l; AnnotationTableObject *aobj; GSequenceLineViewAnnotated *view; }; } // namespace #endif ugene-1.9.8/src/corelibs/U2View/src/util_ov_annotated_dna/AnnotatedDNAView.cpp0000644000175000017500000011241411651544334025763 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "AnnotatedDNAView.h" #include "AnnotatedDNAViewState.h" #include "AnnotatedDNAViewFactory.h" #include "AnnotatedDNAViewTasks.h" #include "ADVUtils.h" #include "AnnotationsTreeView.h" #include "ADVAnnotationCreation.h" #include "ADVClipboard.h" #include "ADVConstants.h" #include "ADVSequenceObjectContext.h" #include "ADVSingleSequenceWidget.h" #include "ADVSplitWidget.h" #include "ADVSyncViewManager.h" #include "AutoAnnotationUtils.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include //BUG:423: move to plugins!? #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include namespace U2 { /* TRANSLATOR U2::AnnotatedDNAView */ AnnotatedDNAView::AnnotatedDNAView(const QString& viewName, const QList& dnaObjects) : GObjectView(AnnotatedDNAViewFactory::ID, viewName) { timerId = 0; annotationSelection = new AnnotationSelection(this); annotationGroupSelection = new AnnotationGroupSelection(this); clipb = NULL; mainSplitter = NULL; scrollArea = NULL; posSelector = NULL; posSelectorWidgetAction = NULL; annotationsView = NULL; focusedWidget = NULL; createAnnotationAction = (new ADVAnnotationCreation(this))->getCreateAnnotationAction(); annotationSettingsAction = new QAction(QIcon(":core/images/annotation_settings.png"), tr("Annotations highlighting..."), this); connect(annotationSettingsAction, SIGNAL(triggered()), SLOT(sl_onAnnotationSettings())); posSelectorAction = new QAction(QIcon(":core/images/goto.png"), tr("Go to position..."), this); posSelectorAction->setShortcut(QKeySequence(Qt::CTRL | Qt::Key_G)); posSelectorAction->setShortcutContext(Qt::WindowShortcut); posSelectorAction->setObjectName(ADV_GOTO_ACTION); connect(posSelectorAction, SIGNAL(triggered()), SLOT(sl_onShowPosSelectorRequest())); toggleHLAction = new QAction("", this); connect(toggleHLAction, SIGNAL(triggered()), SLOT(sl_toggleHL())); syncViewManager = new ADVSyncViewManager(this); foreach(DNASequenceObject* dnaObj, dnaObjects) { addObject(dnaObj); } findDialogAction = new ADVGlobalAction(this, QIcon(":core/images/find_dialog.png"), tr("Find pattern..."), 10); findDialogAction->setShortcut(QKeySequence(Qt::CTRL | Qt::Key_F)); findDialogAction->setShortcutContext(Qt::WindowShortcut); connect(findDialogAction, SIGNAL(triggered()), SLOT(sl_onFindDialog())); addSequencePart = new QAction(tr("Insert subsequence..."), this); connect(addSequencePart, SIGNAL(triggered()), this, SLOT(sl_addSequencePart())); removeSequencePart = new QAction(tr("Remove subsequence..."), this); connect(removeSequencePart, SIGNAL(triggered()), this, SLOT(sl_removeSequencePart())); replaceSequencePart = new QAction(tr("Replace subsequence..."), this); connect(replaceSequencePart, SIGNAL(triggered()), this, SLOT(sl_replaceSequencePart())); removeSequenceObjectAction = new QAction(tr("Selected sequence from view"), this); connect(removeSequenceObjectAction, SIGNAL(triggered()), SLOT(sl_removeSelectedSequenceObject())); reverseSequenceAction = new QAction(tr("Reverse complement sequence"), this); connect(reverseSequenceAction, SIGNAL(triggered()), SLOT(sl_reverseSequence())); SecStructPredictViewAction::createAction(this); } QWidget* AnnotatedDNAView::createWidget() { GTIMER(c1,t1,"AnnotatedDNAView::createWidget"); assert(scrollArea == NULL); mainSplitter = new QSplitter(Qt::Vertical); mainSplitter->setObjectName("annotated_DNA_splitter"); //mainSplitter->setOpaqueResize(false); mainSplitter->setMaximumHeight(200); connect(mainSplitter, SIGNAL(splitterMoved(int, int)), SLOT(sl_splitterMoved(int, int))); mainSplitter->setContextMenuPolicy(Qt::CustomContextMenu); connect(mainSplitter, SIGNAL(customContextMenuRequested(const QPoint &)), SLOT(sl_onContextMenuRequested(const QPoint &))); scrollArea = new QScrollArea(); scrollArea->setObjectName("annotated_DNA_scrollarea"); scrollArea->setWidgetResizable(true); mainSplitter->addWidget(scrollArea); mainSplitter->setCollapsible(mainSplitter->indexOf(scrollArea), false); mainSplitter->setStretchFactor(mainSplitter->count()-1, 5); scrolledWidget = new QWidget(scrollArea); scrolledWidgetLayout = new QVBoxLayout(); scrolledWidgetLayout->setContentsMargins(0, 0, 0, 0); scrolledWidgetLayout->setSpacing(0); scrolledWidget->setBackgroundRole(QPalette::Light); annotationsView = new AnnotationsTreeView(this); annotationsView->setObjectName("annotations_tree_view"); for (int i = seqContexts.size(); --i>=0;) { //use reverse mode -> so sequence widget for a lower index will be on top ADVSequenceObjectContext* seqCtx = seqContexts[i]; ADVSingleSequenceWidget* block = new ADVSingleSequenceWidget(seqCtx, this); block->setObjectName("ADV_single_sequence_widget_"+QString::number(i)); addSequenceWidget(block); } mainSplitter->addWidget(annotationsView); mainSplitter->setCollapsible(mainSplitter->indexOf(annotationsView), false); mainSplitter->setStretchFactor(mainSplitter->count()-1, 1); scrolledWidget->setLayout(scrolledWidgetLayout); scrolledWidget->setObjectName("scrolled_widget_layout"); //TODO: scroll area does not restore focus for last active child widget after Alt-Tab... scrollArea->setWidget(scrolledWidget); scrollArea->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn); clipb = new ADVClipboard(this); mainSplitter->installEventFilter(this); mainSplitter->setAcceptDrops(true); if (!seqViews.isEmpty()) { setFocusedSequenceWidget(seqViews.last()); } //add view global shortcuts mainSplitter->addAction(toggleHLAction); mainSplitter->addAction(removeSequenceObjectAction); mainSplitter->setWindowIcon(GObjectTypes::getTypeInfo(GObjectTypes::SEQUENCE).icon); return mainSplitter; } void AnnotatedDNAView::sl_splitterMoved(int, int) { // WORKAROUND: looks like a QT bug: // ADVSequenceWidgets get paint events as needed, but scrolledWidget is over-painted by splitter's handle // to reproduce it open any complex (like 3d structure) view and pull the splitter handle upward slowly // -> workaround: update geometry for scrollArea or repaint main splitter's ares (todo: recheck effect) mainSplitter->repaint(scrollArea->geometry()); /*if (timerId!=0) { killTimer(timerId); } timerId = startTimer(100);*/ } void AnnotatedDNAView::timerEvent(QTimerEvent*) { //see comment for sl_splitterMoved() assert(timerId!=0); killTimer(timerId); timerId = 0; QWidget* w = scrollArea; QRect orig = w->geometry(); QRect tmp = orig; tmp.adjust(0, 0, 1, 1); w->setGeometry(tmp); w->setGeometry(orig); } void AnnotatedDNAView::updateScrollAreaHeight() { if (!scrolledWidget->isVisible()) { return; } int fw = scrollArea->frameWidth(); int mh = fw * 2; foreach(ADVSequenceWidget* v, seqViews) { mh+=v->height(); } scrollArea->setMaximumHeight(mh); scrolledWidgetLayout->activate(); } AnnotatedDNAView::~AnnotatedDNAView() { delete posSelector; } bool AnnotatedDNAView::eventFilter(QObject* o, QEvent* e) { if (o == mainSplitter) { if (e->type() == QEvent::DragEnter || e->type() == QEvent::Drop) { QDropEvent* de = (QDropEvent*)e; const QMimeData* md = de->mimeData(); const GObjectMimeData* gomd = qobject_cast(md); if (gomd != NULL) { if (e->type() == QEvent::DragEnter) { de->acceptProposedAction(); } else { GObject* obj = gomd->objPtr.data(); if (obj!=NULL) { QString err = tryAddObject(obj); if (!err.isEmpty()) { QMessageBox::critical(NULL, tr("Error!"), err); } } } } } } else if (e->type() == QEvent::Resize) { ADVSequenceWidget* v = qobject_cast(o); if ( v!=NULL ) { updateScrollAreaHeight(); } } return false; } void AnnotatedDNAView::setFocusedSequenceWidget(ADVSequenceWidget* v) { if (v == focusedWidget) { return; } ADVSequenceWidget* prevFocus = focusedWidget; focusedWidget = v; updateMultiViewActions(); emit si_focusChanged(prevFocus, focusedWidget); } bool AnnotatedDNAView::onObjectRemoved(GObject* o) { if (o->getGObjectType() == GObjectTypes::ANNOTATION_TABLE) { AnnotationTableObject* ao = qobject_cast(o); annotationSelection->removeObjectAnnotations(ao); foreach(ADVSequenceObjectContext* seqCtx, seqContexts) { if (seqCtx->getAnnotationObjects().contains(ao)) { seqCtx->removeAnnotationObject(ao); break; } } annotations.removeOne(ao); emit si_annotationObjectRemoved(ao); } else if (o->getGObjectType() == GObjectTypes::SEQUENCE) { DNASequenceObject* seqObj = qobject_cast(o); ADVSequenceObjectContext* seqCtx = getSequenceContext(seqObj); if (seqCtx!=NULL) { foreach(ADVSequenceWidget* w, seqCtx->getSequenceWidgets()) { removeSequenceWidget(w); } QSet aObjs = seqCtx->getAnnotationObjects(); foreach(AnnotationTableObject* ao, aObjs) { removeObject(ao); } seqContexts.removeOne(seqCtx); AutoAnnotationObject* aa = autoAnnotationsMap.take(seqCtx); emit si_annotationObjectRemoved(aa->getAnnotationObject()); delete aa; delete seqCtx; } } GObjectView::onObjectRemoved(o); return seqContexts.isEmpty(); } void AnnotatedDNAView::addADVAction(ADVGlobalAction* a1) { for (int i=0; igetPosition(); int p2 = a2->getPosition(); if (p1 < p2 || (p1 == p2 && a1->text() < a2->text())) { advActions.insert(i, a1); return; } } advActions.append(a1); } void AnnotatedDNAView::buildStaticToolbar(QToolBar* tb) { tb->addAction(createAnnotationAction); tb->addAction(annotationSettingsAction); tb->addSeparator(); tb->addAction(clipb->getCopySequenceAction()); tb->addAction(clipb->getCopyComplementAction()); tb->addAction(clipb->getCopyTranslationAction()); tb->addAction(clipb->getCopyComplementTranslationAction()); tb->addAction(clipb->getCopyAnnotationSequenceAction()); tb->addAction(clipb->getCopyAnnotationSequenceTranslationAction()); tb->addSeparator(); if (posSelector == NULL && !seqContexts.isEmpty()) { int len = seqContexts.first()->getSequenceLen(); posSelector = new PositionSelector(tb, 1, len); connect(posSelector, SIGNAL(si_positionChanged(int)), SLOT(sl_onPosChangeRequest(int))); posSelectorWidgetAction = tb->addWidget(posSelector); } else { tb->addAction(posSelectorWidgetAction); } tb->addSeparator(); syncViewManager->updateToolbar1(tb); tb->addSeparator(); foreach(ADVGlobalAction* a, advActions) { if (a->getFlags().testFlag(ADVGlobalActionFlag_AddToToolbar)) { tb->addAction(a); } } GObjectView::buildStaticToolbar(tb); tb->addSeparator(); syncViewManager->updateToolbar2(tb); } void AnnotatedDNAView::buildStaticMenu(QMenu* m) { m->addAction(posSelectorAction); clipb->addCopyMenu(m); m->addSeparator(); addAddMenu(m); addAnalyseMenu(m); addAlignMenu(m); addExportMenu(m); addRemoveMenu(m); addEditMenu(m); m->addSeparator(); m->addAction(annotationSettingsAction); annotationsView->adjustStaticMenu(m); GObjectView::buildStaticMenu(m); } ADVSequenceWidget* AnnotatedDNAView::findSequenceWidgetByPos(const QPoint& globalPos) const { foreach(ADVSequenceWidget* slv, seqViews) { const QRect& rect = slv->rect(); QPoint localPos = slv->mapFromGlobal(globalPos); if (rect.contains(localPos)) { return slv; } } return NULL; } void AnnotatedDNAView::addAnalyseMenu(QMenu* m) { QMenu* am = m->addMenu(tr("Analyze")); am->menuAction()->setObjectName(ADV_MENU_ANALYSE); foreach(ADVGlobalAction* a, advActions) { if (a->getFlags().testFlag(ADVGlobalActionFlag_AddToAnalyseMenu)) { am->addAction(a); } } } void AnnotatedDNAView::addAddMenu(QMenu* m) { QMenu* am = m->addMenu(tr("Add")); am->menuAction()->setObjectName(ADV_MENU_ADD); am->addAction(createAnnotationAction); } void AnnotatedDNAView::addExportMenu(QMenu* m) { QMenu* em = m->addMenu(tr("Export")); em->menuAction()->setObjectName(ADV_MENU_EXPORT); } void AnnotatedDNAView::addAlignMenu(QMenu* m) { QMenu* am = m->addMenu(tr("Align")); am->menuAction()->setObjectName(ADV_MENU_ALIGN); } void AnnotatedDNAView::addRemoveMenu(QMenu* m) { QMenu* rm = m->addMenu(tr("Remove")); rm->menuAction()->setObjectName(ADV_MENU_REMOVE); rm->addAction(removeSequenceObjectAction); } void AnnotatedDNAView::addEditMenu(QMenu* m) { ADVSequenceObjectContext* seqCtx = getSequenceInFocus(); DNASequenceObject *seqObj = seqCtx->getSequenceObject(); Document *curDoc = seqObj->getDocument(); QMenu* rm = m->addMenu(tr("Edit sequence")); if(curDoc->findGObjectByType(GObjectTypes::SEQUENCE).isEmpty() || curDoc->isStateLocked()){ rm->setDisabled(true); }else{ rm->setEnabled(true); }; rm->menuAction()->setObjectName(ADV_MENU_EDIT); if (seqCtx->getSequenceSelection()->isEmpty()) { rm->addAction(addSequencePart); } else { rm->addAction(replaceSequencePart); } rm->addAction(removeSequencePart); if (seqCtx->getComplementTT() != NULL) { reverseSequenceAction->setText(tr("Reverse complement sequence")); } else { reverseSequenceAction->setText(tr("Reverse sequence")); } rm->addAction(reverseSequenceAction); } Task* AnnotatedDNAView::updateViewTask(const QString& stateName, const QVariantMap& stateData) { return new UpdateAnnotatedDNAViewTask(this, stateName, stateData); } QVariantMap AnnotatedDNAView::saveState() { if (closing) { return QVariantMap(); } QVariantMap state = AnnotatedDNAViewState::saveState(this); foreach(ADVSequenceWidget* sw, seqViews) { sw->saveState(state); } foreach(ADVSplitWidget* w, splitWidgets) { w->saveState(state); } annotationsView->saveState(state); return state; } void AnnotatedDNAView::saveWidgetState() { annotationsView->saveWidgetState(); } bool AnnotatedDNAView::canAddObject(GObject* obj) { if (GObjectView::canAddObject(obj)) { return true; } if (isChildWidgetObject(obj)) { return true; } if (obj->getGObjectType() == GObjectTypes::SEQUENCE) { return true; } if (obj->getGObjectType()!=GObjectTypes::ANNOTATION_TABLE) { return false; } //todo: add annotations related to sequence object not in view (sobj) and add 'sobj' too the view ? bool hasRelation = false; foreach(ADVSequenceObjectContext* soc, seqContexts) { if (obj->hasObjectRelation(soc->getSequenceObject(), GObjectRelationRole::SEQUENCE)) { hasRelation = true; break; } } return hasRelation; } bool AnnotatedDNAView::isChildWidgetObject(GObject* obj) const { foreach(ADVSequenceWidget* lv, seqViews) { if (lv->isWidgetOnlyObject(obj)) { return true; } } foreach(ADVSplitWidget* sw, splitWidgets) { if (sw->acceptsGObject(obj)) { return true; } } return false; } void AnnotatedDNAView::addSequenceWidget(ADVSequenceWidget* v) { assert(!seqViews.contains(v)); seqViews.append(v); QList contexts = v->getSequenceContexts(); foreach(ADVSequenceObjectContext* c, contexts) { c->addSequenceWidget(v); addAutoAnnotations(c); } scrolledWidgetLayout->insertWidget(0, v); v->setVisible(true); v->installEventFilter(this); updateScrollAreaHeight(); updateMultiViewActions(); emit si_sequenceWidgetAdded(v); } void AnnotatedDNAView::removeSequenceWidget(ADVSequenceWidget* v) { assert(seqViews.contains(v)); int idx = seqViews.indexOf(v); assert(idx>=0); //fix focus if (focusedWidget == v) { if (idx + 1 < seqViews.size()) { setFocusedSequenceWidget(seqViews[idx+1]); } else if (idx -1 >= 0) { setFocusedSequenceWidget(seqViews[idx-1]); } else { setFocusedSequenceWidget(NULL); } } //remove widget seqViews.removeOne(v); v->hide(); QList contexts = v->getSequenceContexts(); foreach(ADVSequenceObjectContext* c, contexts) { c->removeSequenceWidget(v); } updateMultiViewActions(); emit si_sequenceWidgetRemoved(v); scrolledWidgetLayout->removeWidget(v); delete v; //v->deleteLater(); //problem: updates for 'v' after seqCtx is destroyed updateScrollAreaHeight(); } void AnnotatedDNAView::updateMultiViewActions() { bool canRemoveFocusedSequence = seqViews.size() > 1 && focusedWidget != NULL && focusedWidget->getActiveSequenceContext() != NULL; removeSequenceObjectAction->setEnabled(canRemoveFocusedSequence); } void AnnotatedDNAView::sl_onContextMenuRequested(const QPoint & scrollAreaPos) { Q_UNUSED(scrollAreaPos); QMenu m; m.addAction(posSelectorAction); m.addSeparator()->setObjectName("FIRST_SEP"); clipb->addCopyMenu(&m); m.addSeparator()->setObjectName(ADV_MENU_SECTION1_SEP); addAddMenu(&m); addAnalyseMenu(&m); addAlignMenu(&m); addExportMenu(&m); addEditMenu(&m); addRemoveMenu(&m); m.addSeparator()->setObjectName(ADV_MENU_SECTION2_SEP); if (annotationSelection->getSelection().size() == 1) { Annotation* a = annotationSelection->getSelection().first().annotation; QString name = a->getAnnotationName(); AnnotationSettings* as = AppContext::getAnnotationsSettingsRegistry()->getAnnotationSettings(name); if (as->visible) { toggleHLAction->setText(tr("Disable '%1' highlighting").arg(a->getAnnotationName())); } else { toggleHLAction->setText(tr("Enable '%1' highlighting").arg(a->getAnnotationName())); } AnnotationSettings* asettings = AppContext::getAnnotationsSettingsRegistry()->getAnnotationSettings(a); QIcon icon = GUIUtils::createSquareIcon(asettings->color, 10); toggleHLAction->setIcon(icon); toggleHLAction->setObjectName("toggle_HL_action"); m.addAction(toggleHLAction); } annotationSettingsAction->setObjectName("annotation_settings_action"); m.addAction(annotationSettingsAction); if (focusedWidget!=NULL) { focusedWidget->buildPopupMenu(m); } emit si_buildPopupMenu(this, &m); m.exec(QCursor::pos()); } void AnnotatedDNAView::sl_onFindDialog() { ADVSequenceObjectContext* c = getSequenceInFocus(); if (c != NULL) { FindDialog::runDialog(c); } } void AnnotatedDNAView::sl_onAnnotationSettings() { AnnotationSettingsDialogController::run(scrollArea); } void AnnotatedDNAView::sl_toggleHL() { if (annotationSelection->isEmpty()) { return; } QString name = annotationSelection->getSelection().first().annotation->getAnnotationName(); AnnotationSettings* as = AppContext::getAnnotationsSettingsRegistry()->getAnnotationSettings(name); as->visible = !as->visible; AppContext::getAnnotationsSettingsRegistry()->changeSettings(QList()<getGObjectType() == GObjectTypes::UNLOADED) { AppContext::getTaskScheduler()->registerTopLevelTask(new AddToViewTask(this, o)); return ""; } QList rCtx; if (o->getGObjectType() == GObjectTypes::ANNOTATION_TABLE) { rCtx = findRelatedSequenceContexts(o); if (rCtx.isEmpty()) { //ask user if to create new association CreateObjectRelationDialogController d(o, getSequenceGObjectsWithContexts(), GObjectRelationRole::SEQUENCE, true, tr("Select sequence to associate annotations with:")); d.exec(); rCtx = findRelatedSequenceContexts(o); if (rCtx.isEmpty()) { return ""; } } } return addObject(o); } QString AnnotatedDNAView::addObject(GObject* o) { QList rCtx; if (o->getGObjectType() == GObjectTypes::ANNOTATION_TABLE) { rCtx = findRelatedSequenceContexts(o); if (rCtx.isEmpty()) { return tr("No sequence object found for annotations"); } } QString res = GObjectView::addObject(o); if (!res.isEmpty()) { return res; } bool internalViewObject = isChildWidgetObject(o); if (internalViewObject) { return ""; } if (o->getGObjectType() == GObjectTypes::SEQUENCE) { DNASequenceObject* dnaObj = qobject_cast(o); ADVSequenceObjectContext* sc = new ADVSequenceObjectContext(this, dnaObj); seqContexts.append(sc); //if mainSplitter==NULL -> its view initialization and widgets will be added later if (mainSplitter!=NULL && !isChildWidgetObject(dnaObj)) { ADVSingleSequenceWidget* block = new ADVSingleSequenceWidget(sc, this); block->setObjectName("ADV_single_sequence_widget_" + QString::number(seqViews.count())); addSequenceWidget(block); } addRelatedAnnotations(sc); emit si_sequenceAdded(sc); } else if (o->getGObjectType() == GObjectTypes::ANNOTATION_TABLE) { AnnotationTableObject* ao = qobject_cast(o); assert(ao!=NULL); annotations.append(ao); foreach(ADVSequenceObjectContext* sc, rCtx) { sc->addAnnotationObject(ao); } emit si_annotationObjectAdded(ao); } return ""; } QList AnnotatedDNAView::findRelatedSequenceContexts(GObject* obj) const { QList relatedObjects = GObjectUtils::selectRelations(obj, GObjectTypes::SEQUENCE, GObjectRelationRole::SEQUENCE, objects, UOF_LoadedOnly); QList res; foreach(GObject* seqObj, relatedObjects) { DNASequenceObject* dnaObj = qobject_cast(seqObj); ADVSequenceObjectContext* ctx = getSequenceContext(dnaObj); res.append(ctx); } return res; } void AnnotatedDNAView::sl_onPosChangeRequest(int pos) { uiLog.trace(QString("ADV: center change request: %1").arg(pos)); ADVSequenceWidget* seqBlock = getSequenceWidgetInFocus(); assert(seqBlock!=NULL); seqBlock->centerPosition(pos-1); } void AnnotatedDNAView::sl_onShowPosSelectorRequest() { ADVSequenceObjectContext* seqCtx = getSequenceInFocus(); assert(seqCtx!=NULL); QDialog dlg(getWidget()); dlg.setModal(true); dlg.setWindowTitle(tr("Go To")); std::auto_ptr ps(new PositionSelector(&dlg, 1, seqCtx->getSequenceLen(), true)); connect(ps.get(), SIGNAL(si_positionChanged(int)), SLOT(sl_onPosChangeRequest(int))); dlg.exec(); } void AnnotatedDNAView::insertWidgetIntoSplitter(ADVSplitWidget* splitWidget) { assert(mainSplitter!=NULL); mainSplitter->insertWidget(0, splitWidget); mainSplitter->setStretchFactor(0, 1); splitWidgets.append(splitWidget); } void AnnotatedDNAView::unregisterSplitWidget(ADVSplitWidget* splitWidget) { splitWidgets.removeOne(splitWidget); } ADVSequenceObjectContext* AnnotatedDNAView::getSequenceContext(AnnotationTableObject* obj) const { assert(getAnnotationObjects(true).contains(obj)); foreach(ADVSequenceObjectContext* seqCtx, seqContexts) { QSet aObjs = seqCtx->getAnnotationObjects(true); if(aObjs.contains(obj)) { return seqCtx; } } return NULL; } ADVSequenceObjectContext* AnnotatedDNAView::getSequenceInFocus() const { ADVSequenceWidget* w = getSequenceWidgetInFocus(); return w == NULL ? NULL : w->getActiveSequenceContext(); } QList AnnotatedDNAView::getAllSeqContextsInFocus() const { return getSequenceWidgetInFocus()->getSequenceContexts(); } ADVSequenceObjectContext* AnnotatedDNAView::getSequenceContext(DNASequenceObject* obj) const { foreach(ADVSequenceObjectContext* seqCtx, seqContexts) { if(seqCtx->getSequenceObject() == obj) { return seqCtx; } } return NULL; } ADVSequenceObjectContext* AnnotatedDNAView::getSequenceContext(const GObjectReference& r) const { foreach(ADVSequenceObjectContext* seqCtx, seqContexts) { GObjectReference ref(seqCtx->getSequenceObject()); if (ref == r) { return seqCtx; } } return NULL; } void AnnotatedDNAView::addRelatedAnnotations(ADVSequenceObjectContext* seqCtx) { QList allLoadedAnnotations = GObjectUtils::findAllObjects(UOF_LoadedOnly, GObjectTypes::ANNOTATION_TABLE); QList annotations = GObjectUtils::findObjectsRelatedToObjectByRole(seqCtx->getSequenceObject(), GObjectTypes::ANNOTATION_TABLE, GObjectRelationRole::SEQUENCE, allLoadedAnnotations, UOF_LoadedOnly); foreach(GObject* ao, annotations) { if (objects.contains(ao)) { seqCtx->addAnnotationObject(qobject_cast(ao)); } else { addObject(ao); } } } void AnnotatedDNAView::addAutoAnnotations( ADVSequenceObjectContext* seqCtx ) { AutoAnnotationObject* aa = new AutoAnnotationObject(seqCtx->getSequenceObject()); seqCtx->addAutoAnnotationObject(aa->getAnnotationObject()); autoAnnotationsMap.insert(seqCtx, aa); emit si_annotationObjectAdded(aa->getAnnotationObject()); foreach(ADVSequenceWidget* w, seqCtx->getSequenceWidgets()) { AutoAnnotationsADVAction* aaAction = new AutoAnnotationsADVAction(w, aa); w->addADVSequenceWidgetAction( aaAction ); } } void AnnotatedDNAView::sl_onDocumentAdded(Document* d) { GObjectView::sl_onDocumentAdded(d); importDocAnnotations(d); } void AnnotatedDNAView::importDocAnnotations(Document* doc) { QList docObjects = doc->getObjects(); foreach(GObject* o, docObjects) { if (o->getGObjectType() != GObjectTypes::ANNOTATION_TABLE) { continue; } QList cList = findRelatedSequenceContexts(o); if (cList.isEmpty()) { continue; } addObject(o); } } void AnnotatedDNAView::sl_onDocumentLoadedStateChanged() { Document* d = qobject_cast(sender()); importDocAnnotations(d); GObjectView::sl_onDocumentLoadedStateChanged(); } QList AnnotatedDNAView::getSequenceObjectsWithContexts() const { QList res; foreach(ADVSequenceObjectContext* cx, seqContexts) { res.append(cx->getSequenceObject()); } return res; } QList AnnotatedDNAView::getSequenceGObjectsWithContexts() const { QList res; foreach(ADVSequenceObjectContext* cx, seqContexts) { res.append(cx->getSequenceObject()); } return res; } void AnnotatedDNAView::updateState(const AnnotatedDNAViewState& s) { if (!s.isValid()) { return; } QList objs = s.getSequenceObjects(); QVector regs = s.getSequenceSelections(); assert(objs.size() == regs.size()); //TODO: sync seq object lists //TODO: sync annotation object lists for (int i=0; i < objs.size(); i++) { const GObjectReference& ref = objs[i]; const U2Region& reg = regs[i]; ADVSequenceObjectContext* seqCtx = getSequenceContext(ref); if (seqCtx == NULL) { continue; } U2Region wholeSeq(0, seqCtx->getSequenceLen()); U2Region finalSel = reg.intersect(wholeSeq); seqCtx->getSequenceSelection()->clear(); if (!finalSel.isEmpty()) { seqCtx->getSequenceSelection()->addRegion(finalSel); } } foreach(ADVSequenceWidget* sw, seqViews) { sw->updateState(s.stateData); } foreach (ADVSplitWidget* w, splitWidgets) { w->updateState(s.stateData); } annotationsView->updateState(s.stateData); } void AnnotatedDNAView::sl_addSequencePart(){ ADVSequenceObjectContext* seqCtx = getSequenceInFocus(); DNASequenceObject *seqObj = seqCtx->getSequenceObject(); EditSequencDialogConfig cfg; cfg.mode = EditSequenceMode_Insert; cfg.source = U2Region(0, seqObj->getSequenceLen()); cfg.alphabet = seqObj->getAlphabet(); EditSequenceDialogController dialog(cfg, getSequenceWidgetInFocus()); int result = dialog.exec(); if(result == QDialog::Accepted){ Task *t = new AddPartToSequenceTask(dialog.getDocumentFormatId(), seqObj, dialog.getPosToInsert(), dialog.getNewSequence(), dialog.getAnnotationStrategy(), dialog.getDocumentPath(), dialog.mergeAnnotations()); connect(t, SIGNAL(si_stateChanged()), SLOT(sl_sequenceModifyTaskStateChanged())); AppContext::getTaskScheduler()->registerTopLevelTask(t); } } void AnnotatedDNAView::sl_removeSequencePart(){ ADVSequenceObjectContext* seqCtx = getSequenceInFocus(); DNASequenceObject *seqObj = seqCtx->getSequenceObject(); Document *curDoc = seqObj->getDocument(); QString filter = DialogUtils::prepareDocumentsFileFilter(curDoc->getDocumentFormat()->getFormatId(), false); U2Region source(0, seqObj->getSequenceLen()); U2Region selection = source; if( seqCtx->getSequenceSelection()->getSelectedRegions().size() > 0){ selection = seqCtx->getSequenceSelection()->getSelectedRegions().first(); } RemovePartFromSequenceDialogController dialog(selection, source, curDoc->getURLString(), getSequenceWidgetInFocus()); int result = dialog.exec(); if (result != QDialog::Accepted) { return; } Task *t; if(dialog.modifyCurrentDocument()){ t = new RemovePartFromSequenceTask(dialog.getDocumentFormatId(), seqObj, dialog.getRegionToDelete(), dialog.getStrategy(), seqObj->getDocument()->getURL()); connect(t, SIGNAL(si_stateChanged()), SLOT(sl_sequenceModifyTaskStateChanged())); }else{ t = new RemovePartFromSequenceTask(dialog.getDocumentFormatId(), seqObj, dialog.getRegionToDelete(), dialog.getStrategy(), dialog.getNewDocumentPath(), dialog.mergeAnnotations()); } AppContext::getTaskScheduler()->registerTopLevelTask(t); seqCtx->getSequenceSelection()->clear(); } void AnnotatedDNAView::sl_replaceSequencePart() { ADVSequenceObjectContext* seqCtx = getSequenceInFocus(); DNASequenceObject *seqObj = seqCtx->getSequenceObject(); EditSequencDialogConfig cfg; cfg.mode = EditSequenceMode_Replace; cfg.source = U2Region(0, seqObj->getSequenceLen()); cfg.alphabet = seqObj->getAlphabet(); U2Region selection = seqCtx->getSequenceSelection()->getSelectedRegions().first(); cfg.initialText = seqObj->getSequence().mid(selection.startPos, selection.length); EditSequenceDialogController dlg(cfg, getSequenceWidgetInFocus()); int result = dlg.exec(); if (result != QDialog::Accepted){ return; } Task *t = new ReplacePartOfSequenceTask(dlg.getDocumentFormatId(), seqObj, selection, dlg.getNewSequence(), dlg.getAnnotationStrategy(), dlg.getDocumentPath(), dlg.mergeAnnotations()); connect(t, SIGNAL(si_stateChanged()), SLOT(sl_sequenceModifyTaskStateChanged())); AppContext::getTaskScheduler()->registerTopLevelTask(t); seqCtx->getSequenceSelection()->clear(); } void AnnotatedDNAView::sl_removeSelectedSequenceObject() { ADVSequenceWidget* sw = getSequenceWidgetInFocus(); ADVSequenceObjectContext* soc = sw->getActiveSequenceContext(); DNASequenceObject* so = soc->getSequenceObject(); removeObject(so); } QList AnnotatedDNAView::getAnnotationObjects( bool includeAutoAnnotations /* = false*/ ) const { QList result = annotations; if (includeAutoAnnotations) { foreach (AutoAnnotationObject* aa, autoAnnotationsMap.values()) { result += aa->getAnnotationObject(); } } return result; } void AnnotatedDNAView::updateAutoAnnotations() { QList autoAnnotations = autoAnnotationsMap.values(); foreach (AutoAnnotationObject* aa, autoAnnotations) { aa->update(); } } void AnnotatedDNAView::addAutoAnnotationsUpdated(AutoAnnotationsUpdater* updater){ foreach(ADVSequenceObjectContext* advContext, seqContexts){ AutoAnnotationsADVAction* autoAnnotAction = AutoAnnotationUtils::findAutoAnnotationADVAction(advContext); if(autoAnnotAction){ autoAnnotAction->addUpdaterToMenu(updater); } } } void AnnotatedDNAView::sl_sequenceModifyTaskStateChanged() { Task* t = qobject_cast (sender()); if (t == NULL) { return; } if (t->getState() == Task::State_Finished && !(t->hasError() || t->isCanceled()) ) { updateAutoAnnotations(); // TODO: there must be better way to do this ReverseSequenceTask* reverseTask = qobject_cast(t); ADVSequenceObjectContext* seqCtx = getSequenceInFocus(); if (reverseTask != NULL && seqCtx != NULL) { QVector regions = seqCtx->getSequenceSelection()->getSelectedRegions(); if (regions.count() == 1) { U2Region r = regions.first(); foreach (ADVSequenceWidget* w, seqCtx->getSequenceWidgets()) { w->centerPosition(r.startPos); } } } } } void AnnotatedDNAView::onObjectRenamed(GObject* obj, const QString& oldName) { // 1. update title OpenAnnotatedDNAViewTask::updateTitle(this); // 2. update components if (obj->getGObjectType() == GObjectTypes::SEQUENCE) { DNASequenceObject* seqObj = qobject_cast(obj); ADVSequenceObjectContext* ctx = getSequenceContext(seqObj); foreach(ADVSequenceWidget* w, ctx->getSequenceWidgets()) { w->onSequenceObjectRenamed(oldName); } } } void AnnotatedDNAView::sl_reverseSequence() { ADVSequenceObjectContext* seqCtx = getSequenceInFocus(); DNASequenceObject *seqObj = seqCtx->getSequenceObject(); QList annotations = seqCtx->getAnnotationObjects(false).toList(); DNATranslation* complTr = NULL; if (seqObj->getAlphabet()->isNucleic()) { complTr = seqCtx->getComplementTT(); } Task* t = new ReverseSequenceTask(seqObj,annotations, seqCtx->getSequenceSelection(), complTr); AppContext::getTaskScheduler()->registerTopLevelTask(t); connect(t, SIGNAL(si_stateChanged()), SLOT(sl_sequenceModifyTaskStateChanged())); } }//namespace ugene-1.9.8/src/corelibs/U2View/src/util_ov_annotated_dna/GSequenceGraphView.h0000644000175000017500000000520211651544334026025 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_GSEQUENCE_GRAPH_VIEW_H_ #define _U2_GSEQUENCE_GRAPH_VIEW_H_ #include "GSequenceLineView.h" #include "ADVGraphModel.h" #include namespace U2 { class GSequenceGraphWindowData; class GSequenceGraphView; class GObjectView; ////////////////////////////////////////////////////////////////////////// /// View class U2VIEW_EXPORT GSequenceGraphView : public GSequenceLineView { Q_OBJECT public: GSequenceGraphView(QWidget* p, ADVSequenceObjectContext* ctx, GSequenceLineView* baseView, const QString& vName); ~GSequenceGraphView(); const QString& getGraphViewName() const {return vName;} void addGraphData(GSequenceGraphData* g); void setGraphDrawer(GSequenceGraphDrawer* gd); const QList& getGraphs() const {return graphs;} GSequenceGraphDrawer* getGSequenceGraphDrawer() const {return graphDrawer;} void buildPopupMenu(QMenu& m); protected: virtual void pack(); private slots: void sl_onShowVisualProperties(bool); private: GSequenceLineView* baseView; QString vName; QList graphs; GSequenceGraphDrawer* graphDrawer; QAction* visualPropertiesAction; }; class U2VIEW_EXPORT GSequenceGraphViewRA : public GSequenceLineViewRenderArea { public: GSequenceGraphViewRA(GSequenceGraphView* g); ~GSequenceGraphViewRA(); virtual GSequenceGraphView* getGraphView() const {return static_cast(view);} float getCurrentScale() const; protected: virtual void drawAll(QPaintDevice* pd); virtual void drawHeader(QPainter& p); void drawSelection(QPainter& p); private: QFont *headerFont; int headerHeight; QRect graphRect; GSequenceGraphDrawer* gd; }; } // namespace #endif ugene-1.9.8/src/corelibs/U2View/src/util_ov_annotated_dna/ADVSplitWidget.h0000644000175000017500000000272711651544334025134 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_ADV_SPLIT_WIDGET_H_ #define _U2_ADV_SPLIT_WIDGET_H_ #include #include namespace U2 { class AnnotatedDNAView; class GObject; class U2VIEW_EXPORT ADVSplitWidget : public QWidget { Q_OBJECT public: ADVSplitWidget(AnnotatedDNAView* view) : dnaView(view) { } AnnotatedDNAView* getAnnotatedDNAView() const {return dnaView;} virtual bool acceptsGObject(GObject* objects) = 0; virtual void updateState(const QVariantMap& m) = 0; virtual void saveState(QVariantMap& m) = 0; protected: AnnotatedDNAView* dnaView; }; }//namespace #endif //_U2_ADV_SPLIT_WIDGET_H_ ugene-1.9.8/src/corelibs/U2View/src/util_ov_annotated_dna/ADVSequenceWidget.cpp0000644000175000017500000000366011651544334026141 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "ADVSequenceWidget.h" #include "ADVSequenceObjectContext.h" #include "AnnotatedDNAView.h" namespace U2 { ADVSequenceWidget::ADVSequenceWidget(AnnotatedDNAView* _ctx) :QWidget(_ctx->getScrolledWidget()), ctx(_ctx) { } void ADVSequenceWidget::addADVSequenceWidgetAction(ADVSequenceWidgetAction* action) { assert(!action->objectName().isEmpty()); assert(getADVSequenceWidgetAction(action->objectName()) == NULL); action->setParent(this); action->seqWidget = this; wActions.append(action); } ADVSequenceWidgetAction* ADVSequenceWidget::getADVSequenceWidgetAction(const QString& objName) const { foreach(ADVSequenceWidgetAction* action, wActions) { if (action->objectName() == objName) { return action; } } return NULL; } QList ADVSequenceWidget::getSequenceObjects() const { QList res; foreach(ADVSequenceObjectContext* ctx, seqContexts) { res.append(ctx->getSequenceObject()); } return res; } void ADVSequenceWidget::buildPopupMenu(QMenu& m) { Q_UNUSED(m); } }//namespace ugene-1.9.8/src/corelibs/U2View/src/util_ov_annotated_dna/ADVGraphModel.cpp0000644000175000017500000004730111651544334025247 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "ADVGraphModel.h" #include "GSequenceGraphView.h" #include "WindowStepSelectorWidget.h" #include namespace U2 { GSequenceGraphData::GSequenceGraphData(const QString& _graphName) : graphName(_graphName), ga(NULL) { cachedFrom = cachedLen = cachedW = cachedS = 0;; } GSequenceGraphData::~GSequenceGraphData() { delete ga; } void GSequenceGraphUtils::calculateMinMax(const QVector& data, float& min, float& max) { assert(data.size() > 0); min = max = data.first(); const float* d = data.constData(); for (int i=1, n = data.size() ; i val) { min = val; } else if (max < val) { max = val; } } } #define ACCEPTABLE_FLOAT_PRESISION_LOSS 0.0001 float GSequenceGraphUtils::calculateAverage(const QVector& data, float start, float range) { float result; if (int(start)!=int(start+range)) { //result constructed from 3 parts: ave[start, startIdx] + ave[startIdx, endIdx] + ave[endIdx, end] float part1 = 0; float part2 = 0; float part3 = 0; int startIdx = int(floor(start)); float startDiff = 1 - (start - startIdx); float end = start + range; int endIdx = int(end); float endDiff = end - endIdx; assert(qAbs(startDiff + (endIdx-(startIdx+1)) + endDiff - range) / range <= ACCEPTABLE_FLOAT_PRESISION_LOSS); //calculating part1 if (startDiff > ACCEPTABLE_FLOAT_PRESISION_LOSS) { float v1 = data[startIdx]; float v2 = data[startIdx+1]; float k = v2-v1; float valInStart = v2 - k*startDiff; part1 = startDiff * (valInStart + v2) / 2; } int firstIdxInRange = int(ceil(start)); //calculating part2 for(int i =firstIdxInRange; i < endIdx; i++) { part2+=data[i]; } //calculating part3 if (endDiff > ACCEPTABLE_FLOAT_PRESISION_LOSS && endIdx+1 < (int)data.size()) { float v1 = data[endIdx]; float v2 = data[endIdx+1]; float k = v2-v1; float valInEnd= v1+k*endDiff; part3 = endDiff * (v1 + valInEnd) / 2; } //sum result = (part1 + part2 + part3 ) / range; } else { //result constructed from 1 part: ave[start, end], no data points between int startIdx = int(start); float startDiff = start - float(startIdx); float endDiff = startDiff + range; assert(endDiff < 1); float v1 = data[startIdx]; float v2 = data[startIdx+1]; float k = v2-v1; float valInStart = v1 + k*startDiff; float valInEnd = v1 + k*endDiff; result = (valInEnd+valInStart)/2; } return result; } void GSequenceGraphUtils::fitToScreen(const QVector& data, int dataStartBase, int dataEndBase, QVector& results, int resultStartBase, int resultEndBase, int screenWidth, float unknownVal) { //BUG:422: use intervals and max/min values instead of average! float basesPerPixel = (resultEndBase - resultStartBase) / (float) screenWidth; float basesInDataPerIndex = (dataEndBase - dataStartBase) / (float) (data.size() - 1); float currentBase = resultStartBase; results.reserve(results.size() + screenWidth); for (int i=0; i < screenWidth; i++, currentBase+=basesPerPixel) { float dataStartIdx = (currentBase - basesPerPixel / 2 - dataStartBase) / basesInDataPerIndex; float dataEndIdx = (currentBase + basesPerPixel / 2 - dataStartBase) / basesInDataPerIndex; dataStartIdx = qMax((float)0, dataStartIdx); dataEndIdx = qMin((float)data.size()-1, dataEndIdx); float nDataPointsToAverage = dataEndIdx - dataStartIdx; float val = unknownVal; if (nDataPointsToAverage >= ACCEPTABLE_FLOAT_PRESISION_LOSS) { val = calculateAverage(data, dataStartIdx, nDataPointsToAverage); } results.append(val); } } int GSequenceGraphUtils::getNumSteps(const U2Region& range, int w, int s) { assert(range.length >= w); int steps = (range.length - w) / s + 1; return steps; } ////////////////////////////////////////////////////////////////////////// //drawer GSequenceGraphDrawer::GSequenceGraphDrawer(GSequenceGraphView* v, const GSequenceGraphWindowData& wd) : QObject(v), view(v), wdata(wd) { defFont = new QFont("Arial", 8); } GSequenceGraphDrawer::~GSequenceGraphDrawer() { delete defFont; } //TODO: #define UNKNOWN_VAL -1 void GSequenceGraphDrawer::draw(QPainter& p, GSequenceGraphData* d, const QRect& rect) { float min=0; float max=0; PairVector points; int nPoints = rect.width(); calculatePoints(d, points, min, max, nPoints); assert(points.firstPoints.size() == nPoints); double comin = commdata.min, comax = commdata.max; QString minprefix, maxprefix; if (commdata.enableCuttoff){ min = comin; max = comax; minprefix = "<="; maxprefix = ">="; } { //draw min/max QPen minMaxPen(Qt::DashDotDotLine); minMaxPen.setWidth(1); p.setPen(minMaxPen); p.setFont(*defFont); //max p.drawLine(rect.topLeft(), rect.topRight()); QRect maxTextRect(rect.x(), rect.y(), rect.width(), 12); p.drawText(maxTextRect, Qt::AlignRight, maxprefix + QString::number((double) max, 'g', 4)); //min p.drawLine(rect.bottomLeft(), rect.bottomRight()); QRect minTextRect(rect.x(), rect.bottom()-12, rect.width(), 12); p.drawText(minTextRect, Qt::AlignRight, minprefix + QString::number((double) min, 'g', 4)); } QPen graphPen(Qt::SolidLine); graphPen.setWidth(1); p.setPen(graphPen); int graphHeight = rect.bottom() - rect.top() - 2; float kh = (min == max) ? 1 : graphHeight / (max - min); int prevY = -1; int prevX = -1; if (!commdata.enableCuttoff) { ////////cutoff off for (int i = 0, n = nPoints; i < n; i++) { float fy1 = points.firstPoints[i]; if (fy1 == UNKNOWN_VAL) { continue; } int dy1 = qRound((fy1 - min) * kh); assert(dy1 <= graphHeight); int y1 = rect.bottom() - 1 - dy1; int x = rect.left() + i; assert(y1 > rect.top() && y1 < rect.bottom()); if (prevX != -1) { p.drawLine(prevX, prevY , x, y1); } prevY = y1; prevX = x; if (points.useIntervals) { float fy2 = points.secondPoints[i]; if (fy2 == UNKNOWN_VAL) { continue; } int dy2 = qRound((fy2 - min) * kh); assert(dy2 <= graphHeight); int y2 = rect.bottom() - 1 - dy2; assert(y2 > rect.top() && y2 < rect.bottom()); if (prevX != -1){ p.drawLine(prevX, prevY , x, y2); } prevY = y2; prevX = x; } } } else { ////////cutoff on float fymin = comin; float fymax = comax; float fymid = (comin + comax)/2; float fy; int prevFY = -1; bool rp = false, lp = false; int ymid = rect.bottom() - 1 - qRound((fymid - min) * kh); if (points.useIntervals){ for (int i=0, n = nPoints; i < n; i++) { fy = points.firstPoints[i]; if (fy == UNKNOWN_VAL) { continue; } if (fy >= fymax) { fy = fymax; } else { if (fy <= fymin) fy = fymin; else fy = fymid; } int dy = qRound((fy - min) * kh); assert(dy <= graphHeight); int y = rect.bottom() - 1 - dy; int x = rect.left() + i; assert(y > rect.top() && y < rect.bottom()); p.drawLine(x, ymid , x, y); } for (int i=0, n = points.secondPoints.size(); i < n; i++) { fy = points.secondPoints[i]; if (fy == UNKNOWN_VAL) { continue; } if (fy >= fymax) { fy = fymax; } else { if (fy <= fymin) fy = fymin; else fy = fymid; } int dy = qRound((fy - min) * kh); assert(dy <= graphHeight); int y = rect.bottom() - 1 - dy; int x = rect.left() + i; assert(y > rect.top() && y < rect.bottom()); p.drawLine(x, ymid , x, y); } } else { for (int i=0, n = points.firstPoints.size(); i < n; i++) { fy = points.firstPoints[i]; rp = false; lp = false; if (fy == UNKNOWN_VAL) { continue; } if (fy >= fymax) { fy = fymax; if (prevFY == int(fymid)) lp=true; } else { fy = fymid; if (prevFY == int(fymax)) rp=true; } int dy = qRound((fy - min) * kh); assert(dy <= graphHeight); int y = rect.bottom() - 1 - dy; int x = rect.left() + i; if (lp) { p.drawLine(prevX, prevY, x, prevY); prevX = x; } if (rp) { p.drawLine(prevX,prevY,prevX,y); prevY = y; } assert(y > rect.top() && y < rect.bottom()); if (prevX!=-1){ p.drawLine(prevX, prevY , x, y); } prevY = y; prevX = x; prevFY = (int) fy; } prevY = -1; prevX = -1; prevFY = -1; for (int i=0, n = points.firstPoints.size(); i < n; i++) { fy = points.firstPoints[i]; rp = false; lp = false; if (fy == UNKNOWN_VAL) { continue; } if (fy <= fymin) { fy = fymin; if (prevFY == int(fymid)) lp=true; } else { fy = fymid; if (prevFY == int(fymin)) rp=true; } int dy = qRound((fy - min) * kh); assert(dy <= graphHeight); int y = rect.bottom() - 1 - dy; int x = rect.left() + i; if (lp) { p.drawLine(prevX, prevY, x, prevY); prevX = x; } if (rp) { p.drawLine(prevX,prevY,prevX,y); prevY = y; } assert(y > rect.top() && y < rect.bottom()); if (prevX!=-1){ p.drawLine(prevX, prevY , x, y); } prevY = y; prevX = x; prevFY = (int) fy; } } } } static void align(int start, int end, int win, int step, int seqLen, int& alignedFirst, int& alignedLast) { int win2 = (win + 1) / 2; int notAlignedFirst = start - win2; alignedFirst = qMax(0, notAlignedFirst - notAlignedFirst % step); int notAlignedLast = end + win + step; alignedLast = notAlignedLast - notAlignedLast % step; while (alignedLast + win2 >= end + step) { alignedLast-=step; } while (alignedLast > seqLen - win) { alignedLast-=step; } assert(alignedLast % step == 0); assert(alignedFirst % step == 0); assert(alignedLast < end); } void GSequenceGraphDrawer::calculatePoints(GSequenceGraphData* d, PairVector& points, float& min, float& max, int numPoints) { const U2Region& vr = view->getVisibleRange(); int step = wdata.step; int win = wdata.window; int seqLen = view->getSequenceLen(); points.firstPoints.resize(numPoints); points.firstPoints.fill(UNKNOWN_VAL); points.secondPoints.resize(numPoints); points.secondPoints.fill(UNKNOWN_VAL); min = UNKNOWN_VAL; max = UNKNOWN_VAL; if (vr.length < win) { return; } int alignedFirst = 0; //start point for the first window int alignedLast = 0; //start point for the last window align(vr.startPos, vr.endPos(), win, step, seqLen, alignedFirst, alignedLast); int nSteps = (alignedLast - alignedFirst) / step; bool winStepNotChanged = win == d->cachedW && step == d->cachedS ; bool numPointsNotChanged = numPoints == d->cachedData.firstPoints.size(); bool useCached = vr.length == d->cachedLen && vr.startPos == d->cachedFrom && winStepNotChanged && numPointsNotChanged; if (useCached) { points = d->cachedData; } else if (nSteps > numPoints) { points.useIntervals = true; int stepsPerPoint = nSteps / points.firstPoints.size(); int basesPerPoint = stepsPerPoint * step; //<=step because of boundary conditions -> number of steps can be changed if alignedLast+w2 == end bool offsetIsTooSmall = qAbs((d->alignedLC - d->alignedFC) - (alignedLast - alignedFirst)) <= step && (qAbs(alignedFirst - d->alignedFC) < basesPerPoint); if (offsetIsTooSmall && winStepNotChanged && numPointsNotChanged && vr.length == d->cachedLen ) { useCached = true; points = d->cachedData; } else { calculateWithFit(d, points, alignedFirst, alignedLast); } } else { points.useIntervals = false; calculateWithExpand(d, points, alignedFirst, alignedLast); } // Calculate min-max values, ignore unknown values bool inited = false; min = 0; max = 0; foreach(float p, points.firstPoints) { if (p == UNKNOWN_VAL) { continue; } if (!inited) { inited = true; min = p; max = p; } else { min = qMin(p, min); max = qMax(p, max); } } // If interval based graph -> adjust min-max values with second graph data if (points.useIntervals) { foreach(float p, points.secondPoints) { if (p == UNKNOWN_VAL) { continue; } min = qMin(p, min); max = qMax(p, max); } } if (useCached) { return; } // cache this result d->cachedData = points; d->cachedFrom = vr.startPos; d->cachedLen = vr.length; d->cachedW = win; d->cachedS = step; d->alignedFC = alignedFirst; d->alignedLC = alignedLast; } void GSequenceGraphDrawer::calculateWithFit(GSequenceGraphData* d, PairVector& points, int alignedFirst, int alignedLast) { int nPoints = points.firstPoints.size(); float basesPerPoint = (alignedLast - alignedFirst) / float(nPoints); assert(int(basesPerPoint) >= wdata.step); //ensure that every point is associated with some step data QVector pointData; DNASequenceObject* o = view->getSequenceObject(); int len = qMax(int(basesPerPoint), wdata.window); #ifdef DEBUG int lastBase = alignedLast + wdata.window; #endif // DEBUG for (int i = 0; i < nPoints; i++) { pointData.clear(); int startPos = alignedFirst + int(i * basesPerPoint); U2Region r(startPos, len); #ifdef DEBUG assert(r.endPos() <= lastBase); #endif d->ga->calculate(pointData, o, r, &wdata); float min, max; GSequenceGraphUtils::calculateMinMax(pointData, min, max); points.firstPoints[i] = max; //BUG:422: support interval based graph!!! points.secondPoints[i] = min; } } void GSequenceGraphDrawer::calculateWithExpand(GSequenceGraphData* d, PairVector& points, int alignedFirst, int alignedLast) { int win = wdata.window; int win2 = (win+1)/2; int step = wdata.step; assert((alignedLast - alignedFirst) % step == 0); U2Region r(alignedFirst, alignedLast - alignedFirst + win); DNASequenceObject* o = view->getSequenceObject(); QVector res; d->ga->calculate(res, o, r, &wdata); const U2Region& vr = view->getVisibleRange(); assert(alignedFirst + win2 + step >= vr.startPos); //0 or 1 step is before the visible range assert(alignedLast + win2 - step <= vr.endPos()); //0 or 1 step is after the the visible range bool hasBeforeStep = alignedFirst + win2 < vr.startPos; bool hasAfterStep = alignedLast + win2 >= vr.endPos(); int firstBaseOffset = hasBeforeStep ? (step - (vr.startPos - (alignedFirst + win2))) : (alignedFirst + win2 - vr.startPos); int lastBaseOffset = hasAfterStep ? (step - (alignedLast + win2 - vr.endPos())) //extra step on the right is available : (vr.endPos() - (alignedLast + win2)); // no extra step available -> end of the sequence assert(firstBaseOffset >= 0 && lastBaseOffset >= 0); assert(hasBeforeStep ? (firstBaseOffset < step && firstBaseOffset!=0): firstBaseOffset <= win2); assert(hasAfterStep ? (lastBaseOffset <= step && lastBaseOffset !=0) : lastBaseOffset < win2 + step); float base2point = points.firstPoints.size() / (float)vr.length; int ri = hasBeforeStep ? 1 : 0; int rn = hasAfterStep ? res.size()-1 : res.size(); for (int i=0; ri < rn; ri++, i++) { int b = firstBaseOffset + i * step; int px = int(b * base2point); assert(px < points.firstPoints.size()); points.firstPoints[px] = res[ri]; } //restore boundary points if possible if (hasBeforeStep && res[0]!=UNKNOWN_VAL && res[1]!=UNKNOWN_VAL) { assert(firstBaseOffset > 0); float k = firstBaseOffset / (float)step; float val = res[1] + (res[0]-res[1])*k; points.firstPoints[0] = val; } if (hasAfterStep && res[rn-1]!=UNKNOWN_VAL && res[rn]!=UNKNOWN_VAL) { assert(lastBaseOffset > 0); float k = lastBaseOffset / (float)step; float val = res[rn-1] + (res[rn]-res[rn-1])*k; points.firstPoints[points.firstPoints.size()-1] = val; } } void GSequenceGraphDrawer::showSettingsDialog() { WindowStepSelectorDialog d(view, U2Region(1, view->getSequenceLen()-1), wdata.window, wdata.step, commdata.min, commdata.max, commdata.enableCuttoff); int res = d.exec(); if (res == QDialog::Accepted) { wdata.window = d.getWindowStepSelector()->getWindow(); wdata.step = d.getWindowStepSelector()->getStep(); commdata.enableCuttoff = d.getMinMaxSelector()->getState(); commdata.min = d.getMinMaxSelector()->getMin(); commdata.max = d.getMinMaxSelector()->getMax(); view->update(); } } } // namespace ugene-1.9.8/src/corelibs/U2View/src/util_ov_annotated_dna/GSequenceLineView.h0000644000175000017500000001525011651544334025657 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_GSEQUENCE_LINE_VIEW_H_ #define _U2_GSEQUENCE_LINE_VIEW_H_ #include #include #include #include #include #include #include #include namespace U2 { class GSequenceLineViewRenderArea; class DNASequenceObject; class DNASequenceSelection; class LRegionsSelection; class GScrollBar; class ADVSequenceObjectContext; class GObjectViewOpConstraints; class GObject; enum GSLV_UpdateFlag { GSLV_UF_NeedCompleteRedraw = 1<<0, GSLV_UF_ViewResized = 1<<1, GSLV_UF_VisibleRangeChanged = 1<<2, GSLV_UF_SelectionChanged = 1<<3, GSLV_UF_FocusChanged = 1<<4, GSLV_UF_FrameChanged = 1<<5, GSLV_UF_AnnotationsChanged = 1<<6 }; enum GSLV_FeatureFlag { GSLV_FF_SupportsCustomRange = 0x1 }; typedef QFlags GSLV_UpdateFlags; typedef QFlags GSLV_FeatureFlags; //single-line sequence view class U2VIEW_EXPORT GSequenceLineView : public QWidget { Q_OBJECT public: GSequenceLineView(QWidget* p, ADVSequenceObjectContext* ctx); const U2Region& getVisibleRange() const {return visibleRange;} ADVSequenceObjectContext* getSequenceContext() const {return ctx;} const U2Region& getSequenceRange() const; virtual void setStartPos(int pos); virtual void setCenterPos(int pos); int getSequenceLen() const {return seqLen;} virtual void addUpdateFlags(GSLV_UpdateFlags newFlags) {lastUpdateFlags|=newFlags;} virtual void clearUpdateFlags() {lastUpdateFlags = 0;} GSLV_UpdateFlags getUpdateFlags() const {return lastUpdateFlags;} virtual void setFrameView(GSequenceLineView* frameView); virtual GSequenceLineView* getFrameView() const {return frameView;} virtual void setCoherentRangeView(GSequenceLineView* rangeView); virtual GSequenceLineView* getConherentRangeView() const {return coherentRangeView;} // [0..seqLen) virtual void setVisibleRange(const U2Region& reg, bool signal = true); virtual QAction* getZoomInAction() const {return coherentRangeView == NULL ? NULL : coherentRangeView->getZoomInAction();} virtual QAction* getZoomOutAction() const {return coherentRangeView == NULL ? NULL : coherentRangeView->getZoomOutAction();} virtual QAction* getZoomToSelectionAction() const {return coherentRangeView == NULL ? NULL : coherentRangeView->getZoomToSelectionAction();} virtual QAction* getZoomToSequenceAction() const {return coherentRangeView == NULL ? NULL : coherentRangeView->getZoomToSequenceAction();} virtual DNASequenceObject* getSequenceObject() const; virtual void buildPopupMenu(QMenu& m){ Q_UNUSED(m); } virtual bool isWidgetOnlyObject(GObject* o) const { Q_UNUSED(o); return false;} virtual bool eventFilter (QObject * watched, QEvent * event); signals: void si_visibleRangeChanged(); void si_centerPosition(int pos); protected: void resizeEvent(QResizeEvent* e); void mouseDoubleClickEvent(QMouseEvent* me); void mousePressEvent(QMouseEvent* me); void mouseReleaseEvent(QMouseEvent* me); void mouseMoveEvent(QMouseEvent* me); void wheelEvent(QWheelEvent* we); void focusInEvent(QFocusEvent* fe); void focusOutEvent(QFocusEvent* fe); void keyPressEvent(QKeyEvent *e); virtual void onVisibleRangeChanged(bool signal = true); public slots: void sl_centerPosition(int pos) {setCenterPos(pos);} protected slots: virtual void sl_onScrollBarMoved(int pos); virtual void sl_onDNASelectionChanged(LRegionsSelection* thiz, const QVector& added, const QVector& removed); virtual void sl_sequenceChanged(); void sl_onFrameRangeChanged(); void sl_onCoherentRangeViewRangeChanged(); void completeUpdate(); protected: QPoint toRenderAreaPoint(const QPoint& p); void updateScrollBar(); void setSelection(const U2Region& r); void addSelection(const U2Region& r); void removeSelection(const U2Region& r); virtual void pack(); virtual int getSingleStep() const; virtual int getPageStep() const; ADVSequenceObjectContext* ctx; GSequenceLineViewRenderArea* renderArea; U2Region visibleRange; GScrollBar* scrollBar; qint64 lastPressPos; qint64 seqLen; GSLV_UpdateFlags lastUpdateFlags; GSLV_FeatureFlags featureFlags; GSequenceLineView* frameView; GSequenceLineView* coherentRangeView; // special flag setup by child classes that tells to this class do or skip // any changes to selection on mouse ops bool ignoreMouseSelectionEvents; }; class U2VIEW_EXPORT GSequenceLineViewRenderArea : public QWidget { public: GSequenceLineViewRenderArea(GSequenceLineView* p); ~GSequenceLineViewRenderArea(); virtual int coordToPos(int x) const; virtual int posToCoord(int p, bool useVirtualSpace = false) const; virtual float posToCoordF(int p, bool useVirtualSpace = false) const; //number of pixels per base virtual float getCurrentScale() const; //char width, derived from current 'font' int getCharWidth() const {return charWidth;} protected: virtual void paintEvent(QPaintEvent *e); virtual void drawAll(QPaintDevice* pd) = 0; void drawFrame(QPainter& p); virtual void drawFocus(QPainter& p); void updateFontMetrics(); GSequenceLineView* view; QPixmap* cachedView; QPixmap* tmpView; //per char and per line metrics QFont sequenceFont; QFont smallSequenceFont; QFont rulerFont; int charWidth; int smallCharWidth; int lineHeight; int yCharOffset; int xCharOffset; }; } //namespace #endif ugene-1.9.8/src/corelibs/U2View/src/util_ov_annotated_dna/ADVClipboard.cpp0000644000175000017500000002500711651544334025123 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "ADVClipboard.h" #include "AnnotatedDNAView.h" #include "ADVSequenceObjectContext.h" #include "ADVConstants.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include namespace U2 { ADVClipboard::ADVClipboard(AnnotatedDNAView* c) : QObject(c) { ctx = c; //TODO: listen seqadded/seqremoved!! connect(ctx, SIGNAL(si_focusChanged(ADVSequenceWidget*, ADVSequenceWidget*)), SLOT(sl_onFocusedSequenceWidgetChanged(ADVSequenceWidget*, ADVSequenceWidget*))); foreach(ADVSequenceObjectContext* sCtx, ctx->getSequenceContexts()) { connectSequence(sCtx); } copySequenceAction = new QAction(QIcon(":/core/images/copy_sequence.png"), tr("Copy sequence"), this); copySequenceAction->setShortcut(QKeySequence(Qt::CTRL | Qt::Key_C)); copyTranslationAction = new QAction(QIcon(":/core/images/copy_translation.png"), tr("Copy translation"), this); copyTranslationAction->setShortcut(QKeySequence(Qt::CTRL | Qt::Key_T)); copyComplementSequenceAction = new QAction(QIcon(":/core/images/copy_complement_sequence.png"), tr("Copy reverse complement sequence"), this); copyComplementSequenceAction->setShortcut(QKeySequence(Qt::CTRL | Qt::SHIFT | Qt::Key_C)); copyComplementTranslationAction = new QAction(QIcon(":/core/images/copy_complement_translation.png"), tr("Copy reverse complement translation"), this); copyComplementTranslationAction->setShortcut(QKeySequence(Qt::CTRL | Qt::SHIFT | Qt::Key_T)); copyAnnotationSequenceAction = new QAction(QIcon(":/core/images/copy_annotation_sequence.png"), tr("Copy annotation sequence"), this); copyAnnotationSequenceTranslationAction = new QAction(QIcon(":/core/images/copy_annotation_translation.png"), tr("Copy annotation sequence translation"), this); connect(copySequenceAction, SIGNAL(triggered()), SLOT(sl_copySequence())); connect(copyTranslationAction, SIGNAL(triggered()), SLOT(sl_copyTranslation())); connect(copyComplementSequenceAction, SIGNAL(triggered()), SLOT(sl_copyComplementSequence())); connect(copyComplementTranslationAction, SIGNAL(triggered()), SLOT(sl_copyComplementTranslation())); connect(copyAnnotationSequenceAction, SIGNAL(triggered()), SLOT(sl_copyAnnotationSequence())); connect(copyAnnotationSequenceTranslationAction, SIGNAL(triggered()), SLOT(sl_copyAnnotationSequenceTranslation())); updateActions(); } void ADVClipboard::connectSequence(ADVSequenceObjectContext* sCtx) { connect(sCtx->getSequenceSelection(), SIGNAL(si_selectionChanged(LRegionsSelection*, const QVector&, const QVector&)), SLOT(sl_onDNASelectionChanged(LRegionsSelection*, const QVector& , const QVector&))); connect(sCtx->getAnnotatedDNAView()->getAnnotationsSelection(), SIGNAL(si_selectionChanged(AnnotationSelection* , const QList&, const QList&)), SLOT(sl_onAnnotationSelectionChanged(AnnotationSelection* , const QList&, const QList&))); } void ADVClipboard::sl_onDNASelectionChanged(LRegionsSelection*, const QVector&, const QVector&) { updateActions(); } void ADVClipboard::sl_onAnnotationSelectionChanged(AnnotationSelection*, const QList&, const QList&) { updateActions(); } void ADVClipboard::copySequenceSelection(bool complement, bool amino) { ADVSequenceObjectContext* seqCtx = getSequenceContext(); if (seqCtx == NULL) { QMessageBox::critical(NULL, tr("Error!"), "No sequence selected!"); return; } QString res; QVector regions = seqCtx->getSequenceSelection()->getSelectedRegions(); if (!regions.isEmpty()) { DNASequenceObject* seqObj = seqCtx->getSequenceObject(); DNATranslation* complTT = complement ? seqCtx->getComplementTT() : NULL; DNATranslation* aminoTT = amino ? seqCtx->getAminoTT() : NULL; QList seqParts = SequenceUtils::extractSequence(seqObj->getSequence(), regions, complTT, aminoTT, false, seqObj->isCircular()); res = SequenceUtils::joinRegions(seqParts); } QApplication::clipboard()->setText(res); } void ADVClipboard::sl_copySequence() { copySequenceSelection(false, false); } void ADVClipboard::sl_copyTranslation() { copySequenceSelection(false, true); } void ADVClipboard::sl_copyComplementSequence() { copySequenceSelection(true, false); } void ADVClipboard::sl_copyComplementTranslation() { copySequenceSelection(true, true); } void ADVClipboard::sl_copyAnnotationSequence() { QByteArray res; const QList& as = ctx->getAnnotationsSelection()->getSelection(); //BUG528: add alphabet symbol role: insertion mark char gapSym = '-'; for (int i=0, n = as.size(); i < n; i++) { const AnnotationSelectionData& sd = as.at(i); if (i!=0) { res.append('\n'); } ADVSequenceObjectContext* seqCtx = ctx->getSequenceContext(sd.annotation->getGObject()); if (seqCtx == NULL) { res.append(gapSym);//?? generate sequence with len == region-len using default sym? continue; } const QByteArray& sequence = seqCtx->getSequenceData(); DNATranslation* complTT = sd.annotation->getStrand().isCompementary() ? seqCtx->getComplementTT() : NULL; AnnotationSelection::getAnnotationSequence(res, sd, gapSym, sequence, complTT, NULL); } QApplication::clipboard()->setText(res); } void ADVClipboard::sl_copyAnnotationSequenceTranslation() { QByteArray res; const QList& as = ctx->getAnnotationsSelection()->getSelection(); //BUG528: add alphabet symbol role: insertion mark //TODO: reuse AnnotationSelection utils char gapSym = '-'; for (int i=0, n = as.size(); i < n; i++) { const AnnotationSelectionData& sd = as.at(i); if (i!=0) { res.append('\n'); } ADVSequenceObjectContext* seqCtx = ctx->getSequenceContext(sd.annotation->getGObject()); if (seqCtx == NULL) { res.append(gapSym);//?? generate sequence with len == region-len using default sym? continue; } const QByteArray& sequence = seqCtx->getSequenceData(); DNATranslation* complTT = sd.annotation->getStrand().isCompementary() ? seqCtx->getComplementTT() : NULL; DNATranslation* aminoTT = seqCtx->getAminoTT(); if (aminoTT == NULL) { continue; } QList nuclParts = SequenceUtils::extractRegions(sequence, sd.annotation->getRegions(), complTT); QList aminoParts = SequenceUtils::translateRegions(nuclParts, aminoTT, sd.annotation->isJoin()); res = SequenceUtils::joinRegions(aminoParts); } QApplication::clipboard()->setText(res); } void ADVClipboard::updateActions() { ADVSequenceObjectContext* seqCtx = getSequenceContext(); DNASequenceSelection* sel = seqCtx == NULL ? NULL : seqCtx->getSequenceSelection(); bool hasSequence = sel != NULL; bool hasComplement = hasSequence && seqCtx->getComplementTT()!=NULL; bool hasTranslation = hasSequence && seqCtx->getAminoTT()!=NULL; bool selectionIsNotEmpty = hasSequence && !sel->getSelectedRegions().isEmpty(); copySequenceAction->setEnabled(selectionIsNotEmpty); copyTranslationAction->setEnabled(selectionIsNotEmpty && hasTranslation); copyComplementSequenceAction->setEnabled(selectionIsNotEmpty && hasComplement); copyComplementTranslationAction->setEnabled(selectionIsNotEmpty && hasComplement && hasTranslation); bool hasAnnotationSelection = !ctx->getAnnotationsSelection()->isEmpty(); bool hasSequenceForAnnotations = false; bool hasTranslationForAnnotations = false; if (hasAnnotationSelection) { const QList& as = ctx->getAnnotationsSelection()->getSelection(); foreach(const AnnotationSelectionData& sd, as) { ADVSequenceObjectContext* asCtx = ctx->getSequenceContext(sd.annotation->getGObject()); if (asCtx == NULL) { continue; } hasSequenceForAnnotations = true; hasTranslationForAnnotations = hasTranslationForAnnotations || asCtx->getAminoTT()!=NULL; if (hasTranslationForAnnotations) { break; } } } copyAnnotationSequenceAction->setEnabled(hasAnnotationSelection && hasSequenceForAnnotations); copyAnnotationSequenceTranslationAction->setEnabled(hasAnnotationSelection && hasTranslationForAnnotations); } void ADVClipboard::addCopyMenu(QMenu* m) { QMenu* copyMenu = new QMenu(tr("Copy"), m); copyMenu->menuAction()->setObjectName(ADV_MENU_COPY); copyMenu->addAction(copySequenceAction); copyMenu->addAction(copyComplementSequenceAction); copyMenu->addAction(copyTranslationAction); copyMenu->addAction(copyComplementTranslationAction); copyMenu->addAction(copyAnnotationSequenceAction); copyMenu->addAction(copyAnnotationSequenceTranslationAction); m->addMenu(copyMenu); } ADVSequenceObjectContext* ADVClipboard::getSequenceContext() const { return ctx->getSequenceInFocus(); } void ADVClipboard::sl_onFocusedSequenceWidgetChanged(ADVSequenceWidget* oldW, ADVSequenceWidget* newW) { Q_UNUSED(oldW); Q_UNUSED(newW); updateActions(); } }//namespace ugene-1.9.8/src/corelibs/U2View/src/util_ov_annotated_dna/ADVUtils.cpp0000644000175000017500000000412311651544334024320 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "ADVUtils.h" #include "AnnotatedDNAView.h" #include "ADVSingleSequenceWidget.h" #include "ADVSequenceObjectContext.h" namespace U2 { ADVGlobalAction::ADVGlobalAction(AnnotatedDNAView* v, const QIcon& icon, const QString& text, int ps, ADVGlobalActionFlags fl) : GObjectViewAction(v, v, text), pos(ps), flags(fl) { setIcon(icon); connect(v, SIGNAL(si_focusChanged(ADVSequenceWidget*, ADVSequenceWidget*)), SLOT(sl_focusChanged(ADVSequenceWidget*, ADVSequenceWidget*))); updateState(); v->addADVAction(this); } void ADVGlobalAction::sl_focusChanged(ADVSequenceWidget* fromW, ADVSequenceWidget* toW) { Q_UNUSED(fromW); Q_UNUSED(toW); updateState(); } void ADVGlobalAction::updateState() { AnnotatedDNAView* av = qobject_cast(getObjectView()); ADVSequenceWidget* w = av->getSequenceWidgetInFocus(); bool enabled = w!=NULL; if (enabled && flags.testFlag(ADVGlobalActionFlag_SingleSequenceOnly) && qobject_cast(w) == NULL) { enabled = false; } if (enabled && !alphabetFilter.isEmpty()) { DNAAlphabetType t = w->getActiveSequenceContext()->getAlphabet()->getType(); enabled = alphabetFilter.contains(t); } setEnabled(enabled); } } //namespace ugene-1.9.8/src/corelibs/U2View/src/util_ov_textview/0000755000175000017500000000000011651544334021241 5ustar ilyailyaugene-1.9.8/src/corelibs/U2View/src/util_ov_textview/SimpleTextObjectView.cpp0000644000175000017500000001503011651544334026024 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "SimpleTextObjectView.h" #include "SimpleTextObjectViewTasks.h" #include #include #include #include #include #include #include #include namespace U2 { /* TRANSLATOR U2::SimpleTextObjectViewFactory */ ////////////////////////////////////////////////////////////////////////// /// Factory const GObjectViewFactoryId SimpleTextObjectViewFactory::ID(GObjectViewFactory::SIMPLE_TEXT_FACTORY); SimpleTextObjectViewFactory::SimpleTextObjectViewFactory(QObject* p) : GObjectViewFactory(ID, tr("Text editor"), p) { } bool SimpleTextObjectViewFactory::canCreateView(const MultiGSelection& multiSelection) { bool hasTextDocuments = !SelectionUtils::findDocumentsWithObjects(GObjectTypes::TEXT, &multiSelection, UOF_LoadedAndUnloaded, true).isEmpty(); return hasTextDocuments; } bool SimpleTextObjectViewFactory::isStateInSelection(const MultiGSelection& multiSelection, const QVariantMap& stateData) { QString documentURL = SimpleTextObjectView::getDocumentUrl(stateData); QSet documents = SelectionUtils::findDocumentsWithObjects(GObjectTypes::TEXT, &multiSelection, UOF_LoadedAndUnloaded, true); foreach(Document* doc, documents) { if (doc->getURL() == documentURL) { return true; } } return false; } Task* SimpleTextObjectViewFactory::createViewTask(const MultiGSelection& multiSelection, bool single) { QSet documents = SelectionUtils::findDocumentsWithObjects(GObjectTypes::TEXT, &multiSelection, UOF_LoadedAndUnloaded, true); if (documents.size() == 0) { return NULL; } Task* result = (single || documents.size() == 1) ? NULL : new Task(tr("Open multiple views task"), TaskFlag_NoRun); foreach(Document* d, documents) { Task* t = new OpenSimpleTextObjectViewTask(d); if (result == NULL) { return t; } //todo: limit number of views? result->addSubTask(t); } return result; } Task* SimpleTextObjectViewFactory::createViewTask(const QString& viewName, const QVariantMap& state) { return new OpenSavedTextObjectViewTask(viewName, state); } ////////////////////////////////////////////////////////////////////////// /// Simple Text View SimpleTextObjectView::SimpleTextObjectView(const QString& name, TextObject* to, const QVariantMap& _state) : GObjectView(SimpleTextObjectViewFactory::ID, name), textObject(to), openState(_state), selection(to) { textEdit = NULL; firstShow = true; assert(to); objects.append(to); requiredObjects.append(to); } QWidget* SimpleTextObjectView::createWidget() { assert(textEdit == NULL); textEdit = new QPlainTextEdit(); textEdit->setLineWrapMode(QPlainTextEdit::NoWrap); textEdit->setWordWrapMode(QTextOption::NoWrap); textEdit->setPlainText(textObject->getText()); if (textObject->isStateLocked()) { textEdit->setReadOnly(true); } connect(textEdit, SIGNAL(textChanged()), SLOT(sl_onTextEditTextChanged())); connect(textObject, SIGNAL(si_lockedStateChanged()), SLOT(sl_onTextObjStateLockChanged())); textEdit->installEventFilter(this); textEdit->setWindowIcon(GObjectTypes::getTypeInfo(GObjectTypes::TEXT).icon); return textEdit; } bool SimpleTextObjectView::eventFilter(QObject* o, QEvent *e) { if (firstShow && o == textEdit && e->type() == QEvent::ShowToParent) { firstShow = false; updateView(openState); } return false; } void SimpleTextObjectView::sl_onTextEditTextChanged() { textObject->setText(textEdit->toPlainText()); } void SimpleTextObjectView::sl_onTextObjStateLockChanged() { textEdit->setReadOnly(textObject->isStateLocked()); } Task* SimpleTextObjectView::updateViewTask(const QString& stateName, const QVariantMap& state) { return new UpdateSimpleTextObjectViewTask(this, stateName, state); } bool SimpleTextObjectView::checkAddToView(const MultiGSelection& s) { Q_UNUSED(s); return false; } Task* SimpleTextObjectView::addToViewTask(const MultiGSelection& s) { Q_UNUSED(s); assert(0); return NULL; } #define URL_KEY "url" #define OBJ_KEY "obj" #define CURS_POS_KEY "cursor_pos" #define HBAR_POS_KEY "hbar_pos" #define VBAR_POS_KEY "vbar_pos" void SimpleTextObjectView::updateView(const QVariantMap& data) { int cursPos= data.value(CURS_POS_KEY, 0).toInt(); int hScrollPos = data.value(HBAR_POS_KEY, 0).toInt(); int vScrollPos = data.value(VBAR_POS_KEY, 0).toInt(); QTextCursor c = textEdit->textCursor(); c.setPosition(cursPos);//, QTextCursor::KeepAnchor textEdit->setTextCursor(c); textEdit->verticalScrollBar()->setSliderPosition(vScrollPos); textEdit->horizontalScrollBar()->setSliderPosition(hScrollPos); } QVariantMap SimpleTextObjectView::saveState() { QVariantMap data; //Content: //file url data[URL_KEY] = textObject->getDocument()->getURLString(); data[OBJ_KEY] = textObject->getGObjectName(); //GUI: //start vis pos data[CURS_POS_KEY] = textEdit->textCursor().position(); data[HBAR_POS_KEY] = textEdit->horizontalScrollBar()->sliderPosition(); data[VBAR_POS_KEY] = textEdit->verticalScrollBar()->sliderPosition(); return data; } QString SimpleTextObjectView::getDocumentUrl(const QVariantMap& savedState) { return savedState.value(URL_KEY).toString(); } void SimpleTextObjectView::setDocumentUrl(QVariantMap& savedState, const QString& url) { savedState[URL_KEY] = url; } QString SimpleTextObjectView::getObjectName( const QVariantMap& savedState ) { return savedState.value(OBJ_KEY).toString(); } }//namespace ugene-1.9.8/src/corelibs/U2View/src/util_ov_textview/SimpleTextObjectViewTasks.cpp0000644000175000017500000000776611651544334027053 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "SimpleTextObjectViewTasks.h" #include "SimpleTextObjectView.h" #include #include #include #include #include #include namespace U2 { ////////////////////////////////////////////////////////////////////////// //open view task OpenSimpleTextObjectViewTask::OpenSimpleTextObjectViewTask(Document* _doc) : ObjectViewTask(SimpleTextObjectViewFactory::ID), doc(_doc) { if (!doc->isLoaded()) { documentsToLoad.append(doc); } } OpenSavedTextObjectViewTask::OpenSavedTextObjectViewTask(const QString& vname, const QVariantMap& stateData) : ObjectViewTask(SimpleTextObjectViewFactory::ID, vname, stateData), doc(NULL) { QString documentUrl = SimpleTextObjectView::getDocumentUrl(stateData); doc = AppContext::getProject()->findDocumentByURL(documentUrl); if (doc.isNull()) { doc = createDocumentAndAddToProject(documentUrl, AppContext::getProject()); if (!doc) { stateIsIllegal = true; stateInfo.setError(L10N::errorDocumentNotFound(documentUrl)); return; } } if (!doc->isLoaded()) { documentsToLoad.append(doc); } } void OpenSavedTextObjectViewTask::open() { if (stateInfo.hasError() || doc.isNull()) { return; } assert(doc->isLoaded()); QString objName = SimpleTextObjectView::getObjectName(stateData); GObject* obj = doc->findGObjectByName(objName); TextObject* to = qobject_cast(obj); if (!to) { stateInfo.setError(tr("Text object '%1' is not found").arg(objName)); stateIsIllegal = true; return; } SimpleTextObjectView* v = new SimpleTextObjectView(viewName, to, stateData); GObjectViewWindow* w = new GObjectViewWindow(v, viewName, !stateData.isEmpty()); MWMDIManager* mdiManager = AppContext::getMainWindow()->getMDIManager(); mdiManager->addMDIWindow(w); } void OpenSimpleTextObjectViewTask::open() { if (stateInfo.hasError() || doc.isNull()) { return; } assert(doc->isLoaded()); foreach(GObject* obj, doc->findGObjectByType(GObjectTypes::TEXT)) { TextObject* to = qobject_cast(obj); assert(to); QString viewName = GObjectViewUtils::genUniqueViewName(doc, to); SimpleTextObjectView* v = new SimpleTextObjectView(viewName, to, stateData); GObjectViewWindow* w = new GObjectViewWindow(v, viewName, !stateData.isEmpty()); MWMDIManager* mdiManager = AppContext::getMainWindow()->getMDIManager(); mdiManager->addMDIWindow(w); } } ////////////////////////////////////////////////////////////////////////// // update view task UpdateSimpleTextObjectViewTask::UpdateSimpleTextObjectViewTask(GObjectView* v, const QString& stateName, const QVariantMap& stateData) : ObjectViewTask(v, stateName, stateData) { } void UpdateSimpleTextObjectViewTask::update() { if (view.isNull()) { return; } SimpleTextObjectView* tv = qobject_cast(view); if (tv == NULL) { return; } tv->updateView(stateData); } } // namespace ugene-1.9.8/src/corelibs/U2View/src/util_ov_textview/SimpleTextObjectViewTasks.h0000644000175000017500000000320311651544334026476 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_SIMPLE_TEXT_OBJECT_VIEW_TASKS_H_ #define _U2_SIMPLE_TEXT_OBJECT_VIEW_TASKS_H_ #include namespace U2 { class OpenSimpleTextObjectViewTask : public ObjectViewTask { Q_OBJECT public: OpenSimpleTextObjectViewTask(Document* doc); virtual void open(); private: QPointer doc; }; class OpenSavedTextObjectViewTask : public ObjectViewTask { Q_OBJECT public: OpenSavedTextObjectViewTask(const QString& viewName, const QVariantMap& stateData); virtual void open(); private: QPointer doc; }; class UpdateSimpleTextObjectViewTask : public ObjectViewTask { public: UpdateSimpleTextObjectViewTask(GObjectView* v, const QString& stateName, const QVariantMap& stateData); virtual void update(); }; } // namespace #endif ugene-1.9.8/src/corelibs/U2View/src/util_ov_textview/SimpleTextObjectView.h0000644000175000017500000000570011651544334025474 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_SIMPLE_TEXT_VIEW_H_ #define _U2_SIMPLE_TEXT_VIEW_H_ #include #include #include #include namespace U2 { class OpenSimpleTextObjectViewTask; class U2VIEW_EXPORT SimpleTextObjectViewFactory : public GObjectViewFactory { Q_OBJECT public: SimpleTextObjectViewFactory(QObject* p = NULL); static const GObjectViewFactoryId ID; virtual bool canCreateView(const MultiGSelection& multiSelection); virtual bool isStateInSelection(const MultiGSelection& multiSelection, const QVariantMap& stateData); virtual Task* createViewTask(const MultiGSelection& multiSelection, bool single = false); virtual Task* createViewTask(const QString& viewName, const QVariantMap& state); virtual bool supportsSavedStates() const {return true;} }; class U2VIEW_EXPORT SimpleTextObjectView: public GObjectView { Q_OBJECT friend class SimpleTextObjectViewFactory; public: SimpleTextObjectView(const QString& name, TextObject* to, const QVariantMap& state); virtual QVariantMap saveState(); virtual Task* updateViewTask(const QString& stateName, const QVariantMap& stateData); virtual bool checkAddToView(const MultiGSelection& multiSelection); virtual Task* addToViewTask(const MultiGSelection& multiSelection); virtual const TextSelection& getSelectedText() {return selection;} virtual QWidget* createWidget(); void updateView(const QVariantMap& stateData); // saved state accessors -> todo: extract into separate model class static QString getDocumentUrl(const QVariantMap& savedState); static QString getObjectName(const QVariantMap& savedState); static void setDocumentUrl(QVariantMap& savedState, const QString& url); protected: bool eventFilter(QObject *obj, QEvent *event); private slots: void sl_onTextEditTextChanged(); void sl_onTextObjStateLockChanged(); private: TextObject* textObject; QVariantMap openState; TextSelection selection; QPlainTextEdit* textEdit; bool firstShow; }; }//namespace #endif ugene-1.9.8/src/corelibs/U2View/src/util_ov_msaedit/0000755000175000017500000000000011651544334021010 5ustar ilyailyaugene-1.9.8/src/corelibs/U2View/src/util_ov_msaedit/ConsensusSelectorDialogController.cpp0000644000175000017500000001127611651544334030370 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "ConsensusSelectorDialogController.h" #include #include #include namespace U2 { ConsensusSelectorDialogController::ConsensusSelectorDialogController(const QString& _selectedAlgorithmId, ConsensusAlgorithmFlags flags, QWidget* p) : QDialog(p) { setupUi(this); MSAConsensusAlgorithmRegistry* reg = AppContext::getMSAConsensusAlgorithmRegistry(); QList algos = reg->getAlgorithmFactories(flags); //TODO: sort algos by name foreach(const MSAConsensusAlgorithmFactory* algo, algos) { consensusCombo->addItem(QIcon(), algo->getName(), algo->getId()); } selectedAlgorithmId = _selectedAlgorithmId; int indexToSelect = qMax(0, consensusCombo->findData(selectedAlgorithmId)); consensusCombo->setCurrentIndex(indexToSelect); disableThresholdSelector(); updateSelectedAlgorithmDesc(); connect(consensusCombo, SIGNAL(currentIndexChanged(int)), SLOT(sl_algorithmSelectionChanged(int))); connect(thresholdSlider, SIGNAL(valueChanged(int)), SLOT(sl_thresholdSliderChanged(int))); connect(thresholdSpin, SIGNAL(valueChanged(int)), SLOT(sl_thresholdSpinChanged(int))); connect(thresholdDefaultButton, SIGNAL(clicked(bool)), SLOT(sl_resetThresholdClicked(bool))); GCOUNTER(cvar,tvar, "ConsensusSelectorDialog"); } void ConsensusSelectorDialogController::sl_algorithmSelectionChanged(int i) { selectedAlgorithmId = consensusCombo->itemData(i).toString(); updateSelectedAlgorithmDesc(); emit si_algorithmChanged(selectedAlgorithmId); } void ConsensusSelectorDialogController::updateSelectedAlgorithmDesc() { MSAConsensusAlgorithmRegistry* reg = AppContext::getMSAConsensusAlgorithmRegistry(); MSAConsensusAlgorithmFactory* algo = reg->getAlgorithmFactory(selectedAlgorithmId); QString description = algo->getDescription(); descriptionEdit->setText(description); } void ConsensusSelectorDialogController::enableThresholdSelector(int minVal, int maxVal, int value, const QString& suffix) { thresholdLabel->setEnabled(true); thresholdSlider->setEnabled(true); thresholdSpin->setEnabled(true); thresholdDefaultButton->setEnabled(true); thresholdSlider->setRange(minVal, maxVal); thresholdSpin->setRange(minVal, maxVal); thresholdSpin->setSuffix(suffix); thresholdSpin->setValue(qBound(minVal, value, maxVal)); //triggers slider update too } void ConsensusSelectorDialogController::disableThresholdSelector() { thresholdLabel->setEnabled(false); thresholdSlider->setEnabled(false); thresholdSpin->setEnabled(false); thresholdDefaultButton->setEnabled(false); thresholdSlider->setRange(0, 0); thresholdSpin->setRange(0, 0); thresholdSpin->setSuffix(QString()); thresholdSpin->setValue(0); //triggers slider update too } int ConsensusSelectorDialogController::getThresholdValue() const { assert(thresholdSpin->isEnabled()); return thresholdSpin->value(); } void ConsensusSelectorDialogController::sl_thresholdSliderChanged(int val) { thresholdSpin->disconnect(this); thresholdSpin->setValue(val); connect(thresholdSpin, SIGNAL(valueChanged(int)), SLOT(sl_thresholdSpinChanged(int))); emit si_thresholdChanged(val); } void ConsensusSelectorDialogController::sl_thresholdSpinChanged(int val) { thresholdSlider->disconnect(this); thresholdSlider->setValue(val); connect(thresholdSlider, SIGNAL(valueChanged(int)), SLOT(sl_thresholdSliderChanged(int))); emit si_thresholdChanged(val); } void ConsensusSelectorDialogController::sl_resetThresholdClicked(bool) { MSAConsensusAlgorithmFactory* factory = AppContext::getMSAConsensusAlgorithmRegistry()->getAlgorithmFactory(selectedAlgorithmId); int defaultVal = factory->getDefaultThreshold(); thresholdSpin->setValue(defaultVal); } }; ugene-1.9.8/src/corelibs/U2View/src/util_ov_msaedit/MSAEditorConsensusArea.cpp0000644000175000017500000004544711651544334026013 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "MSAEditorConsensusArea.h" #include "MSAEditor.h" #include "MSAEditorSequenceArea.h" #include "MSAEditorConsensusCache.h" #include "ConsensusSelectorDialogController.h" #include #include #include #include #include #include #include #include #include #include #include #include #include namespace U2 { #define SETTINGS_ROOT QString("msaeditor/") MSAEditorConsensusArea::MSAEditorConsensusArea(MSAEditorUI* _ui) : editor(_ui->editor), ui(_ui) { assert(editor->getMSAObject()); consensusDialog = NULL; completeRedraw = true; curPos = -1; scribbling = false; cachedView = new QPixmap(); connect(ui->seqArea, SIGNAL(si_startChanged(const QPoint&, const QPoint&)), SLOT(sl_startChanged(const QPoint&, const QPoint&))); connect(ui->seqArea, SIGNAL(si_selectionChanged(const MSAEditorSelection&, const MSAEditorSelection&) ), SLOT(sl_selectionChanged(const MSAEditorSelection&, const MSAEditorSelection&)) ); connect(ui->editor, SIGNAL(si_zoomOperationPerformed(bool)), SLOT(sl_zoomOperationPerformed(bool))); connect(ui->seqArea->getHBar(), SIGNAL(actionTriggered(int)), SLOT(sl_onScrollBarActionTriggered(int))); connect(editor->getMSAObject(), SIGNAL(si_alignmentChanged(const MAlignment&, const MAlignmentModInfo&)), SLOT(sl_alignmentChanged(const MAlignment&, const MAlignmentModInfo&))); connect(editor, SIGNAL(si_buildStaticMenu(GObjectView*, QMenu*)), SLOT(sl_buildStaticMenu(GObjectView*, QMenu*))); connect(editor, SIGNAL(si_buildPopupMenu(GObjectView* , QMenu*)), SLOT(sl_buildContextMenu(GObjectView*, QMenu*))); copyConsensusAction = new QAction(tr("Copy consensus"), this); connect(copyConsensusAction, SIGNAL(triggered()), SLOT(sl_copyConsensusSequence())); copyConsensusWithGapsAction = new QAction(tr("Copy consensus with gaps"), this); connect(copyConsensusWithGapsAction, SIGNAL(triggered()), SLOT(sl_copyConsensusSequenceWithGaps())); configureConsensusAction = new QAction(tr("Consensus mode..."), this); connect(configureConsensusAction, SIGNAL(triggered()), SLOT(sl_configureConsensusAction())); setupFontAndHeight(); setMouseTracking(true); QString lastUsedAlgoKey = getLastUsedAlgoSettingsKey(); QString lastUsedAlgo = AppContext::getSettings()->getValue(lastUsedAlgoKey).toString(); MSAConsensusAlgorithmFactory* algo = AppContext::getMSAConsensusAlgorithmRegistry()->getAlgorithmFactory(lastUsedAlgo); const DNAAlphabet* al = editor->getMSAObject()->getAlphabet(); ConsensusAlgorithmFlags alphaFlags = MSAConsensusAlgorithmFactory::getAphabetFlags(al); if (algo == NULL || (algo->getFlags() & alphaFlags) != alphaFlags) { algo = AppContext::getMSAConsensusAlgorithmRegistry()->getAlgorithmFactory(BuiltInConsensusAlgorithms::DEFAULT_ALGO); AppContext::getSettings()->setValue(lastUsedAlgoKey, BuiltInConsensusAlgorithms::DEFAULT_ALGO); } consensusCache = new MSAEditorConsensusCache(this, editor->getMSAObject(), algo); connect(consensusCache->getConsensusAlgorithm(), SIGNAL(si_thresholdChanged(int)), SLOT(sl_onConsensusThresholdChanged(int))); restoreLastUsedConsensusThreshold(); } MSAEditorConsensusArea::~MSAEditorConsensusArea() { delete cachedView; } bool MSAEditorConsensusArea::event(QEvent* e) { if (e->type() == QEvent::ToolTip) { QHelpEvent* he = static_cast(e); QString tip = createToolTip(he); if (!tip.isEmpty()) { QToolTip::showText(he->globalPos(), tip); } return true; } return QWidget::event(e); } QString MSAEditorConsensusArea::createToolTip(QHelpEvent* he) const { int x = he->pos().x(); int pos = ui->seqArea->coordToPos(x); QString result; if (pos >= 0) { assert(editor->getMSAObject()); const MAlignment& ma = editor->getMSAObject()->getMAlignment(); result = MSAConsensusUtils::getConsensusPercentTip(ma, pos, 0, 4); } return result; } void MSAEditorConsensusArea::resizeEvent(QResizeEvent *e) { completeRedraw = true; QWidget::resizeEvent(e); } void MSAEditorConsensusArea::paintEvent(QPaintEvent *e) { QSize s = size(); QSize sas = ui->seqArea->size(); Q_UNUSED(sas); if (sas.width() != s.width()) { //this can happen due to the manual layouting performed by MSAEditor -> just wait for the next resize+paint return; } assert(s.width() == sas.width()); if (cachedView->size() != s) { assert(completeRedraw); delete cachedView; cachedView = new QPixmap(s); } if (completeRedraw) { QPainter pCached(cachedView); pCached.fillRect(cachedView->rect(), Qt::white); drawConsensus(pCached); drawRuler(pCached); drawHistogram(pCached); completeRedraw = false; } QPainter p(this); p.drawPixmap(0, 0, *cachedView); drawSelection(p); QWidget::paintEvent(e); } void MSAEditorConsensusArea::drawSelection(QPainter& p) { QFont f = ui->editor->getFont(); f.setWeight(QFont::DemiBold); p.setFont(f); MSAEditorSelection selection = ui->seqArea->getSelection(); if (selection.width() == editor->getAlignmentLen() ) { // small optimization? return; } int startPos = qMax(selection.x(), 0); int endPos = qMin(selection.x() + selection.width() - 1, ui->editor->getAlignmentLen() - 1); assert(endPos < ui->editor->getAlignmentLen()); for ( int pos = startPos; pos <= endPos; ++pos) { drawConsensusChar(p, pos, true); } } void MSAEditorConsensusArea::drawConsensus(QPainter& p) { //draw consensus p.setPen(Qt::black); QFont f = ui->editor->getFont(); f.setWeight(QFont::DemiBold); p.setFont(f); int startPos = ui->seqArea->getFirstVisibleBase(); int lastPos = ui->seqArea->getLastVisibleBase(true); for (int pos = startPos; pos <= lastPos; pos++) { drawConsensusChar(p, pos, false); } } void MSAEditorConsensusArea::drawConsensusChar(QPainter& p, int pos, bool selected) { U2Region yRange = getYRange(MSAEditorConsElement_CONSENSUS_TEXT); U2Region xRange= ui->seqArea->getBaseXRange(pos, false); QRect cr(xRange.startPos, yRange.startPos, xRange.length + 1, yRange.length); int w = width(), h = height(); assert(xRange.endPos() <= w && yRange.endPos() <= h); Q_UNUSED(w); Q_UNUSED(h); if (selected) { QColor color(Qt::lightGray); color = color.lighter(115); p.fillRect(cr, color); } if (editor->getResizeMode() == MSAEditor::ResizeMode_FontAndContent) { char c = consensusCache->getConsensusChar(pos); p.drawText(cr, Qt::AlignVCenter | Qt::AlignHCenter, QString(c)); } } #define RULER_NOTCH_SIZE 3 void MSAEditorConsensusArea::drawRuler(QPainter& p) { //draw ruler p.setPen(Qt::darkGray); int w = width(); int startPos = ui->seqArea->getFirstVisibleBase(); int lastPos = ui->seqArea->getLastVisibleBase(true); QFontMetrics rfm(rulerFont); U2Region rr = getYRange(MSAEditorConsElement_RULER); U2Region rrP = getYRange(MSAEditorConsElement_CONSENSUS_TEXT); int dy = rr.startPos - rrP.endPos(); rr.length+=dy; rr.startPos-=dy; U2Region firstBaseXReg = ui->seqArea->getBaseXRange(startPos, false); U2Region lastBaseXReg = ui->seqArea->getBaseXRange(lastPos, false); int firstLastLen = lastBaseXReg.startPos - firstBaseXReg.startPos; int firstXCenter = firstBaseXReg.startPos + firstBaseXReg.length / 2; QPoint startPoint(firstXCenter, rr.startPos); GraphUtils::RulerConfig c; c.singleSideNotches = true; c.notchSize = RULER_NOTCH_SIZE; c.textOffset = (rr.length - rfm.ascent()) /2; c.extraAxisLenBefore = startPoint.x(); c.extraAxisLenAfter = w - (startPoint.x() + firstLastLen); c.textBorderStart = -firstBaseXReg.length / 2; c.textBorderEnd = -firstBaseXReg.length / 2; GraphUtils::drawRuler(p, startPoint, firstLastLen, startPos + 1, lastPos + 1, rulerFont, c); startPoint.setY(rr.endPos()); c.drawNumbers = false; c.textPosition = GraphUtils::LEFT; GraphUtils::drawRuler(p, startPoint, firstLastLen, startPos + 1, lastPos + 1, rulerFont, c); } void MSAEditorConsensusArea::drawHistogram(QPainter& p) { QColor c("#255060"); p.setPen(c); U2Region yr = getYRange(MSAEditorConsElement_HISTOGRAM); yr.startPos++; yr.length-=2; //keep borders QBrush brush(c, Qt::Dense4Pattern); QVector counts(256, 0); for (int pos = ui->seqArea->getFirstVisibleBase(), lastPos = ui->seqArea->getLastVisibleBase(true); pos <= lastPos; pos++) { U2Region xr = ui->seqArea->getBaseXRange(pos, true); int percent = consensusCache->getConsensusCharPercent(pos); assert(percent >= 0 && percent <= 100); int h = qRound(percent * yr.length / 100.0); QRect hr(xr.startPos + 1, yr.endPos() - h, xr.length - 2, h); p.drawRect(hr); p.fillRect(hr, brush); } } U2Region MSAEditorConsensusArea::getYRange(MSAEditorConsElement e) const { U2Region res; switch(e) { case MSAEditorConsElement_HISTOGRAM: res = U2Region(0, 50); break; case MSAEditorConsElement_CONSENSUS_TEXT: res = U2Region(0, editor->getRowHeight()); res.startPos += getYRange(MSAEditorConsElement(e-1)).endPos(); break; case MSAEditorConsElement_RULER: res = U2Region(0, rulerFontHeight + 2 * RULER_NOTCH_SIZE + 4); res.startPos += getYRange(MSAEditorConsElement(e-1)).endPos(); break; } return res; } void MSAEditorConsensusArea::sl_startChanged(const QPoint& p, const QPoint& prev) { if (p.x() == prev.x()) { return; } completeRedraw = true; update(); } void MSAEditorConsensusArea::sl_alignmentChanged(const MAlignment&, const MAlignmentModInfo&) { completeRedraw = true; update(); } void MSAEditorConsensusArea::setupFontAndHeight() { rulerFont.setFamily("Arial"); rulerFont.setPointSize(qMax(8, int(ui->editor->getFont().pointSize() * 0.7))); rulerFontHeight = QFontMetrics(rulerFont).height(); setFixedHeight( getYRange(MSAEditorConsElement_RULER).endPos() + 1); } void MSAEditorConsensusArea::sl_zoomOperationPerformed( bool resizeModeChanged ) { if (editor->getResizeMode() == MSAEditor::ResizeMode_OnlyContent || resizeModeChanged) { completeRedraw = true; update(); } else { setupFontAndHeight(); } } void MSAEditorConsensusArea::sl_selectionChanged(const MSAEditorSelection& current, const MSAEditorSelection& prev) { // TODO: return if only height of selection changes? Q_UNUSED(current); Q_UNUSED(prev); update(); } void MSAEditorConsensusArea::sl_buildStaticMenu(GObjectView* v, QMenu* m) { Q_UNUSED(v); buildMenu(m); } void MSAEditorConsensusArea::sl_buildContextMenu(GObjectView* v, QMenu* m) { Q_UNUSED(v); buildMenu(m); } void MSAEditorConsensusArea::buildMenu(QMenu* m) { QMenu* copyMenu = GUIUtils::findSubMenu(m, MSAE_MENU_COPY); assert(copyMenu!=NULL); copyMenu->addAction(copyConsensusAction); copyMenu->addAction(copyConsensusWithGapsAction); m->addAction(configureConsensusAction); } void MSAEditorConsensusArea::sl_copyConsensusSequence() { QApplication::clipboard()->setText(consensusCache->getConsensusLine(false)); } void MSAEditorConsensusArea::sl_copyConsensusSequenceWithGaps() { QApplication::clipboard()->setText(consensusCache->getConsensusLine(true)); } void MSAEditorConsensusArea::sl_configureConsensusAction() { assert(consensusDialog == NULL); MSAConsensusAlgorithmFactory* algoFactory = consensusCache->getConsensusAlgorithm()->getFactory(); const DNAAlphabet* al = editor->getMSAObject()->getAlphabet(); ConsensusSelectorDialogController cd(algoFactory->getId(), MSAConsensusAlgorithmFactory::getAphabetFlags(al), this); consensusDialog = &cd; updateThresholdInfoInConsensusDialog(); connect(&cd, SIGNAL(si_algorithmChanged(const QString&)), SLOT(sl_changeConsensusAlgorithm(const QString&))); connect(&cd, SIGNAL(si_thresholdChanged(int)), SLOT(sl_changeConsensusThreshold(int))); int rc = cd.exec(); consensusDialog = NULL; if (rc == QDialog::Accepted) { //do nothing -> algo was set up in signal listener } else { //restore original one setConsensusAlgorithm(algoFactory); } } void MSAEditorConsensusArea::updateThresholdInfoInConsensusDialog() { const MSAConsensusAlgorithm* algo = getConsensusAlgorithm(); if (algo->supportsThreshold()) { consensusDialog->enableThresholdSelector(algo->getMinThreshold(), algo->getMaxThreshold(), algo->getThreshold(), algo->getThresholdSuffix()); } else { consensusDialog->disableThresholdSelector(); } } void MSAEditorConsensusArea::sl_changeConsensusAlgorithm(const QString& algoId) { assert(consensusDialog!=NULL); MSAConsensusAlgorithmFactory* algoFactory = AppContext::getMSAConsensusAlgorithmRegistry()->getAlgorithmFactory(algoId); if (getConsensusAlgorithm()->getFactory() != algoFactory) { assert(algoFactory!=NULL); setConsensusAlgorithm(algoFactory); } updateThresholdInfoInConsensusDialog(); } QString MSAEditorConsensusArea::getLastUsedAlgoSettingsKey() const { const DNAAlphabet* al = editor->getMSAObject()->getAlphabet(); const char* suffix = al->isAmino() ? "_protein" : al->isNucleic() ? "_nucleic" : "_raw"; return SETTINGS_ROOT + "_consensus_algorithm_"+ suffix; } QString MSAEditorConsensusArea::getThresholdSettingsKey(const QString& factoryId) const { return getLastUsedAlgoSettingsKey() + "_" + factoryId + "_threshold"; } void MSAEditorConsensusArea::setConsensusAlgorithm(MSAConsensusAlgorithmFactory* algoFactory) { MSAConsensusAlgorithm* oldAlgo = getConsensusAlgorithm(); if (oldAlgo!=NULL && algoFactory == oldAlgo->getFactory()) { return; } //store threshold for the active algo if (oldAlgo!=NULL && oldAlgo->supportsThreshold()) { AppContext::getSettings()->setValue(getThresholdSettingsKey(oldAlgo->getId()), oldAlgo->getThreshold()); } //store current algorithm selection AppContext::getSettings()->setValue(getLastUsedAlgoSettingsKey(), algoFactory->getId()); consensusCache->setConsensusAlgorithm(algoFactory); connect(consensusCache->getConsensusAlgorithm(), SIGNAL(si_thresholdChanged(int)), SLOT(sl_onConsensusThresholdChanged(int))); restoreLastUsedConsensusThreshold(); completeRedraw = true; update(); } void MSAEditorConsensusArea::setConsensusAlgorithmConsensusThreshold(int val) { MSAConsensusAlgorithm* algo = getConsensusAlgorithm(); if (algo->getThreshold() == val) { return; } //store threshold as the last value AppContext::getSettings()->setValue(getThresholdSettingsKey(algo->getId()), algo->getThreshold()); algo->setThreshold(val); } void MSAEditorConsensusArea::sl_onConsensusThresholdChanged(int newValue) { Q_UNUSED(newValue); completeRedraw = true; update(); } void MSAEditorConsensusArea::restoreLastUsedConsensusThreshold() { //restore last used threshold for new algorithm type if found MSAConsensusAlgorithm* algo = getConsensusAlgorithm(); int threshold = AppContext::getSettings()->getValue(getThresholdSettingsKey(algo->getId()), algo->getDefaultThreshold()).toInt(); getConsensusAlgorithm()->setThreshold(threshold); } MSAConsensusAlgorithm* MSAEditorConsensusArea::getConsensusAlgorithm() const { return consensusCache->getConsensusAlgorithm(); } void MSAEditorConsensusArea::sl_changeConsensusThreshold(int val) { setConsensusAlgorithmConsensusThreshold(val); } void MSAEditorConsensusArea::mousePressEvent(QMouseEvent *e) { int x = e->x(); curPos = ui->seqArea->getColumnNumByX(x); if ((curPos !=-1) && (e->buttons() & Qt::LeftButton)) { int height = editor->getNumSequences(); // select current column MSAEditorSelection selection(curPos, 0, 1, height); ui->seqArea->setSelection(selection); scribbling = true; } QWidget::mousePressEvent(e); } void MSAEditorConsensusArea::mouseMoveEvent( QMouseEvent *e ) { if ((e->buttons() & Qt::LeftButton) && scribbling) { int newPos = ui->seqArea->getColumnNumByX(e->x()); if ( ui->seqArea->isPosInRange(newPos)) { ui->seqArea->updateHBarPosition(newPos); } updateSelection(newPos); } QWidget::mouseMoveEvent(e); } void MSAEditorConsensusArea::mouseReleaseEvent( QMouseEvent *e ) { if (e->button() == Qt::LeftButton) { int newPos = ui->seqArea->getColumnNumByX(e->x()); updateSelection(newPos); curPos = newPos; scribbling = false; } ui->seqArea->getHBar()->setupRepeatAction(QAbstractSlider::SliderNoAction); QWidget::mouseReleaseEvent(e); } void MSAEditorConsensusArea::updateSelection(int newPos) { if (newPos == curPos) { return; } if (newPos != -1) { int height = editor->getNumSequences(); int startPos = qMin(curPos,newPos); int width = qAbs(newPos - curPos) + 1; MSAEditorSelection selection(startPos, 0, width, height ); ui->seqArea->setSelection(selection); } } void MSAEditorConsensusArea::sl_onScrollBarActionTriggered( int scrollAction ) { if (scrollAction == QAbstractSlider::SliderSingleStepAdd || scrollAction == QAbstractSlider::SliderSingleStepSub) { if (scribbling) { QPoint coord = mapFromGlobal(QCursor::pos()); int newPos = ui->seqArea->getColumnNumByX(coord.x()); updateSelection(newPos); } } } }//namespace ugene-1.9.8/src/corelibs/U2View/src/util_ov_msaedit/MSAEditorFactory.h0000644000175000017500000000315211651544334024301 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_MSA_EDITOR_FACTORY_H_ #define _U2_MSA_EDITOR_FACTORY_H_ #include namespace U2 { class MultiGSelection; class MSAColorSchemeRegistry; class U2VIEW_EXPORT MSAEditorFactory : public GObjectViewFactory { Q_OBJECT public: MSAEditorFactory(); virtual bool canCreateView(const MultiGSelection& multiSelection); virtual Task* createViewTask(const MultiGSelection& multiSelection, bool single = false); virtual bool isStateInSelection(const MultiGSelection& multiSelection, const QVariantMap& stateData); virtual Task* createViewTask(const QString& viewName, const QVariantMap& stateData); virtual bool supportsSavedStates() const {return true;} static const GObjectViewFactoryId ID; }; } // namespace #endif ugene-1.9.8/src/corelibs/U2View/src/util_ov_msaedit/MSAEditorConsensusArea.h0000644000175000017500000001010711651544334025441 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_MSA_EDITOR_CONSENSUS_AREA_H_ #define _U2_MSA_EDITOR_CONSENSUS_AREA_H_ #include #include #include #include #include namespace U2 { class MSAEditor; class MSAEditorUI; class GObjectView; class MSAEditorConsensusCache; class MAlignment; class MAlignmentModInfo; class MSAEditorSelection; class MSAConsensusAlgorithm; class MSAConsensusAlgorithmFactory; class ConsensusSelectorDialogController; enum MSAEditorConsElement { MSAEditorConsElement_HISTOGRAM, MSAEditorConsElement_CONSENSUS_TEXT, MSAEditorConsElement_RULER }; class U2VIEW_EXPORT MSAEditorConsensusArea : public QWidget { Q_OBJECT public: MSAEditorConsensusArea(MSAEditorUI* ui); ~MSAEditorConsensusArea(); U2Region getRullerLineYRange() const; void setConsensusAlgorithm(MSAConsensusAlgorithmFactory* algo); void setConsensusAlgorithmConsensusThreshold(int val); MSAConsensusAlgorithm* getConsensusAlgorithm() const; protected: virtual bool event(QEvent* e); void paintEvent(QPaintEvent*); void resizeEvent(QResizeEvent*); void mousePressEvent(QMouseEvent *e); void mouseMoveEvent(QMouseEvent *e); void mouseReleaseEvent(QMouseEvent *e); private slots: void sl_startChanged(const QPoint&, const QPoint&); void sl_selectionChanged(const MSAEditorSelection& current, const MSAEditorSelection& prev); void sl_alignmentChanged(const MAlignment&, const MAlignmentModInfo&); void sl_changeConsensusAlgorithm(const QString& algoId); void sl_changeConsensusThreshold(int val); void sl_onScrollBarActionTriggered( int scrollAction ); void sl_onConsensusThresholdChanged(int newValue); void sl_buildStaticMenu(GObjectView* v, QMenu* m); void sl_buildContextMenu(GObjectView* v, QMenu* m); void sl_copyConsensusSequence(); void sl_copyConsensusSequenceWithGaps(); void sl_configureConsensusAction(); void sl_zoomOperationPerformed(bool resizeModeChanged); private: QString createToolTip(QHelpEvent* he) const; void updateThresholdInfoInConsensusDialog(); void restoreLastUsedConsensusThreshold(); QString getLastUsedAlgoSettingsKey() const; QString getThresholdSettingsKey(const QString& factoryId) const; void buildMenu(QMenu* m); void setupFontAndHeight(); void updateSelection(int newPos); void drawConsensus(QPainter& p); void drawConsensusChar(QPainter& p, int pos, bool selected); void drawRuler(QPainter& p); void drawHistogram(QPainter& p); void drawSelection(QPainter& p); U2Region getYRange(MSAEditorConsElement e) const; MSAEditor* editor; const MSAEditorUI* ui; QFont rulerFont; int rulerFontHeight; QAction* copyConsensusAction; QAction* copyConsensusWithGapsAction; QAction* configureConsensusAction; int curPos; bool scribbling; MSAEditorConsensusCache* consensusCache; bool completeRedraw; QPixmap* cachedView; //works in interactive mode with the view -> so we need to cache it ConsensusSelectorDialogController* consensusDialog; }; }//namespace #endif ugene-1.9.8/src/corelibs/U2View/src/util_ov_msaedit/CreateSubalignimentDialogController.cpp0000644000175000017500000001702611651544334030633 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "CreateSubalignimentDialogController.h" #include #include #include #include #include #include #include #include #include #include #include namespace U2{ CreateSubalignimentDialogController::CreateSubalignimentDialogController(MAlignmentObject *_mobj, const QRect& selection, QWidget *p) : QDialog(p), mobj(_mobj){ setupUi(this); connect(browseButton, SIGNAL(clicked()), SLOT(sl_browseButtonClicked())); connect(allButton, SIGNAL(clicked()), SLOT(sl_allButtonClicked())); connect(noneButton, SIGNAL(clicked()), SLOT(sl_noneButtonClicked())); connect(invertButton, SIGNAL(clicked()), SLOT(sl_invertButtonClicked())); int rowNumber = mobj->getMAlignment().getNumRows(); int alignLength = mobj->getMAlignment().getLength(); sequencesTableWidget->clearContents(); sequencesTableWidget->setRowCount(rowNumber); sequencesTableWidget->setColumnCount(1); sequencesTableWidget->verticalHeader()->setHidden( true ); sequencesTableWidget->horizontalHeader()->setHidden( true ); sequencesTableWidget->setShowGrid(false); sequencesTableWidget->horizontalHeader()->setResizeMode( 0, QHeaderView::Stretch ); int startSeq = -1; int endSeq = -1; int startPos = -1; int endPos = -1; if (selection.isNull()) { startPos = 1; endPos = alignLength; startSeq = 0; endSeq = rowNumber -1; } else { startSeq = selection.y(); endSeq = selection.y() + selection.height() - 1; startPos = selection.x() + 1; endPos = selection.x() + selection.width(); } startPosBox->setMaximum(alignLength); endPosBox->setMaximum(alignLength); startPosBox->setValue(startPos); endPosBox->setValue(endPos); for (int i=0; igetMAlignment().getRow(i).getName(), this); cb->setSizePolicy( QSizePolicy::Expanding, QSizePolicy::Expanding ); if ( (i >= startSeq) && (i <= endSeq)) { cb->setChecked(true); } sequencesTableWidget->setCellWidget(i, 0, cb); sequencesTableWidget->setRowHeight(i, 15); } QList dfIdList = AppContext::getDocumentFormatRegistry()->getRegisteredFormats(), supportedFormats; //CRITICAL: do not create doc here -> add the way to learn about constraints without doc! foreach(DocumentFormatId dfId, dfIdList){ DocumentFormat *df = AppContext::getDocumentFormatRegistry()->getFormatById(dfId); IOAdapterFactory* iof = AppContext::getIOAdapterRegistry()->getIOAdapterFactoryById(BaseIOAdapters::VFS_FILE); Document *d = df->createNewDocument(iof, GUrl("fake", GUrl_VFSFile)); bool supported = df->isObjectOpSupported(d, DocumentFormat::DocObjectOp_Add, GObjectTypes::MULTIPLE_ALIGNMENT); if(supported){ foreach(QString ext, df->getSupportedDocumentFileExtensions()){ filter.append("*." + ext + " "); } } } } void CreateSubalignimentDialogController::sl_browseButtonClicked(){ LastOpenDirHelper h; QString newPath = QFileDialog::getSaveFileName(this, tr("Select file to save..."), h.dir, filter ); filepathEdit->setText(newPath); } void CreateSubalignimentDialogController::sl_allButtonClicked(){ for (int i=0; irowCount(); i++) { QCheckBox *cb = qobject_cast(sequencesTableWidget->cellWidget(i, 0)); cb->setChecked(true); } } void CreateSubalignimentDialogController::sl_invertButtonClicked(){ for (int i=0; irowCount(); i++) { QCheckBox *cb = qobject_cast(sequencesTableWidget->cellWidget(i, 0)); cb->setChecked(!cb->isChecked()); } } void CreateSubalignimentDialogController::sl_noneButtonClicked(){ for (int i=0; irowCount(); i++) { QCheckBox *cb = qobject_cast(sequencesTableWidget->cellWidget(i, 0)); cb->setChecked(false); } } void CreateSubalignimentDialogController::accept(){ QFileInfo fi(filepathEdit->text()); QDir dirToSave(fi.dir()); if (!dirToSave.exists()){ QMessageBox::critical(this, this->windowTitle(), tr("Directory to save is not exists")); return; } if(filepathEdit->text().isEmpty()){ QMessageBox::critical(this, this->windowTitle(), tr("No path specified")); return; } if(fi.baseName().isEmpty()){ QMessageBox::critical(this, this->windowTitle(), tr("Filename to save is empty")); return; } // '-1' because in memory positions start from 0 not 1 int start = startPosBox->value() - 1; int end = endPosBox->value() - 1; int seqLen = mobj->getMAlignment().getLength(); if( start > end ) { QMessageBox::critical(this, windowTitle(), tr("Start position must be greater than end position")); return; } U2Region region(start, end - start + 1), sequence(0, seqLen); if(!sequence.contains(region)){ QMessageBox::critical(this, this->windowTitle(), tr("Entered region not contained in current sequence")); return; } selectSeqNames(); if(selectedNames.size() == 0){ QMessageBox::critical(this, this->windowTitle(), tr("You must select at least one sequence")); return; } window = region; this->close(); QDialog::accept(); } void CreateSubalignimentDialogController::selectSeqNames(){ QStringList names; for (int i=0; irowCount(); i++) { QCheckBox *cb = qobject_cast(sequencesTableWidget->cellWidget(i, 0)); if(cb->isChecked()){ names.append(cb->text()); } } selectedNames = names; } CreateSubalignmentAndOpenViewTask::CreateSubalignmentAndOpenViewTask( MAlignmentObject* maObj, const CreateSubalignmentSettings& settings ) :Task("CreateSubalignmentAndOpenViewTask", TaskFlags_NR_FOSCOE) { csTask = new CreateSubalignmentTask(maObj, settings); addSubTask(csTask); setMaxParallelSubtasks(1); } QList CreateSubalignmentAndOpenViewTask::onSubTaskFinished( Task* subTask ) { QList res; propagateSubtaskError(); if (hasError() || isCanceled()) { return res; } if ( (subTask == csTask) && csTask->getSettings().addToProject ) { Document* doc = csTask->takeDocument(); assert(doc != NULL); res.append(new AddDocumentAndOpenViewTask(doc)); } return res; } }; ugene-1.9.8/src/corelibs/U2View/src/util_ov_msaedit/MSAColorScheme.h0000644000175000017500000001444311651544334023733 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_MSA_COLOR_SCHEME_H_ #define _U2_MSA_COLOR_SCHEME_H_ #include #include #include namespace U2 { class MAlignmentObject; class MSAColorScheme; class MAlignment; class MAlignmentModInfo; ////////////////////////////////////////////////////////////////////////// // factories class U2VIEW_EXPORT MSAColorSchemeFactory : public QObject { Q_OBJECT public: MSAColorSchemeFactory(QObject* p, const QString& id, const QString& name, DNAAlphabetType atype); virtual MSAColorScheme* create(QObject* p, MAlignmentObject* obj) = 0; const QString& getId() const {return id;} const QString& getName() const {return name;} DNAAlphabetType getAlphabetType() const {return aType;} private: QString id; QString name; DNAAlphabetType aType; }; class U2VIEW_EXPORT MSAColorSchemeStaticFactory : public MSAColorSchemeFactory { Q_OBJECT public: MSAColorSchemeStaticFactory(QObject* p, const QString& id, const QString& name, DNAAlphabetType atype, const QVector& colorsPerChar); virtual MSAColorScheme* create(QObject* p, MAlignmentObject* obj); private: QVector colorsPerChar; }; class MSAColorSchemePercIdentFactory : public MSAColorSchemeFactory { Q_OBJECT public: MSAColorSchemePercIdentFactory(QObject* p, const QString& id, const QString& name, DNAAlphabetType atype); virtual MSAColorScheme* create(QObject* p, MAlignmentObject* obj); }; class MSAColorSchemeClustalXFactory : public MSAColorSchemeFactory { Q_OBJECT public: MSAColorSchemeClustalXFactory(QObject* p, const QString& id, const QString& name, DNAAlphabetType atype); virtual MSAColorScheme* create(QObject* p, MAlignmentObject* obj); }; ////////////////////////////////////////////////////////////////////////// // schemes class U2VIEW_EXPORT MSAColorScheme : public QObject { Q_OBJECT public: MSAColorScheme(QObject* p, MSAColorSchemeFactory* f, MAlignmentObject* o); virtual QColor getColor(int seq, int pos) = 0; MSAColorSchemeFactory* getFactory() const {return factory;} static QString EMPTY_NUCL; static QString UGENE_NUCL; static QString JALVIEW_NUCL; static QString IDENTPERC_NUCL; static QString EMPTY_AMINO; static QString UGENE_AMINO; static QString ZAPPO_AMINO; static QString TAILOR_AMINO; static QString HYDRO_AMINO; static QString HELIX_AMINO; static QString STRAND_AMINO; static QString TURN_AMINO; static QString BURIED_AMINO; static QString IDENTPERC_AMINO; static QString CLUSTALX_AMINO; protected: MSAColorSchemeFactory* factory; MAlignmentObject* maObj; }; class U2VIEW_EXPORT MSAColorSchemeStatic : public MSAColorScheme { Q_OBJECT public: MSAColorSchemeStatic(QObject* p, MSAColorSchemeFactory* f, MAlignmentObject* o, const QVector& colorsPerChar); virtual QColor getColor(int seq, int pos); const QColor& getColor(char c) const {return colorsPerChar[(quint8)c];} private: QVector colorsPerChar; }; //PERCENT class U2VIEW_EXPORT MSAColorSchemePercIdent : public MSAColorScheme { Q_OBJECT public: MSAColorSchemePercIdent(QObject* p, MSAColorSchemeFactory* f, MAlignmentObject* o); virtual QColor getColor(int seq, int pos); private slots: void sl_alignmentChanged(const MAlignment&, const MAlignmentModInfo&) {objVersion++;} protected: void updateCache(); QVector indentCache; int cacheVersion; int objVersion; QColor colorsByRange[4]; int mask4[4]; char tmpChars[4]; int tmpRanges[4]; }; //CLUSTALX // 0.5 * alisize mem use, slow update class U2VIEW_EXPORT MSAColorSchemeClustalX: public MSAColorScheme { Q_OBJECT public: MSAColorSchemeClustalX(QObject* p, MSAColorSchemeFactory* f, MAlignmentObject* o); virtual QColor getColor(int seq, int pos); private slots: void sl_alignmentChanged(const MAlignment&, const MAlignmentModInfo&) {objVersion++;} protected: void updateCache(); int getCacheIdx(int seq, int pos, bool& low) const { assert(objVersion == cacheVersion); int res = seq * aliLen + pos; low = !(res & 0x1); return res / 2; } int getColorIdx(int seq, int pos); void setColorIdx(int seq, int pos, int cidx); enum ClustalColor { ClustalColor_NO_COLOR, ClustalColor_BLUE, ClustalColor_RED, ClustalColor_GREEN, ClustalColor_PINK, ClustalColor_MAGENTA, ClustalColor_ORANGE, ClustalColor_CYAN, ClustalColor_YELLOW, ClustalColor_NUM_COLORS }; int objVersion; int cacheVersion; int aliLen; QVector colorsCache; QColor colorByIdx[ClustalColor_NUM_COLORS]; }; ////////////////////////////////////////////////////////////////////////// // registry class U2VIEW_EXPORT MSAColorSchemeRegistry : public QObject { Q_OBJECT public: MSAColorSchemeRegistry(); const QList& getMSAColorSchemes() const {return colorers;} QList getMSAColorSchemes(DNAAlphabetType atype) const; MSAColorSchemeFactory* getMSAColorSchemeFactoryById(const QString& id) const; void addMSAColorSchemeFactory(MSAColorSchemeFactory* cs); private: void initBuiltInSchemes(); QList colorers; }; }//namespace #endif ugene-1.9.8/src/corelibs/U2View/src/util_ov_msaedit/MSAEditorSequenceArea.cpp0000644000175000017500000013347611651544334025603 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "MSAEditorSequenceArea.h" #include "MSAEditor.h" #include "MSAColorScheme.h" #include "CreateSubalignimentDialogController.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include namespace U2 { /* TRANSLATOR U2::MSAEditor */ #define SETTINGS_ROOT QString("msaeditor/") #define SETTINGS_COLOR_NUCL "color_nucl" #define SETTINGS_COLOR_AMINO "color_amino" MSAEditorSequenceArea::MSAEditorSequenceArea(MSAEditorUI* _ui, GScrollBar* hb, GScrollBar* vb) : editor(_ui->editor), ui(_ui), shBar(hb), svBar(vb) { setFocusPolicy(Qt::WheelFocus); cachedView = new QPixmap(); completeRedraw = true; setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::MinimumExpanding); setMinimumSize(100, 100); startPos = 0; startSeq = 0; highlightSelection = false; scribbling = false; delSelectionAction = new QAction(tr("Remove selection"), this); delSelectionAction->setShortcut(QKeySequence(Qt::Key_Delete)); delSelectionAction->setShortcutContext(Qt::WidgetShortcut); connect(delSelectionAction, SIGNAL(triggered()), SLOT(sl_delCurrentSelection())); copySelectionAction = new QAction(tr("Copy selection"), this); copySelectionAction->setShortcut(QKeySequence::Copy); copySelectionAction->setShortcutContext(Qt::WidgetShortcut); copySelectionAction->setToolTip(QString("%1 (%2)").arg(copySelectionAction->text()) .arg(copySelectionAction->shortcut().toString())); connect(copySelectionAction, SIGNAL(triggered()), SLOT(sl_copyCurrentSelection())); addAction(copySelectionAction); delColAction = new QAction(QIcon(":core/images/msaed_remove_columns_with_gaps.png"), tr("Remove columns of gaps..."), this); delColAction->setShortcut(QKeySequence(Qt::SHIFT| Qt::Key_Delete)); delColAction->setShortcutContext(Qt::WidgetShortcut); connect(delColAction, SIGNAL(triggered()), SLOT(sl_delCol())); insSymAction = new QAction(tr("Fill selection with gaps"), this); insSymAction->setShortcut(QKeySequence(Qt::Key_Space)); insSymAction->setShortcutContext(Qt::WidgetShortcut); connect(insSymAction, SIGNAL(triggered()), SLOT(sl_fillCurrentSelectionWithGaps())); addAction(insSymAction); createSubaligniment = new QAction(tr("Save subalignment"), this); createSubaligniment->setShortcutContext(Qt::WidgetShortcut); connect(createSubaligniment, SIGNAL(triggered()), SLOT(sl_createSubaligniment())); insColAction = new QAction(tr("Insert column of gaps"), this); insColAction->setShortcut(QKeySequence(Qt::SHIFT| Qt::Key_Space)); insColAction->setShortcutContext(Qt::WidgetShortcut); connect(insColAction, SIGNAL(triggered()), SLOT(sl_insCol())); gotoAction = new QAction(QIcon(":core/images/goto.png"), tr("Go to position..."), this); gotoAction->setShortcut(QKeySequence(Qt::CTRL | Qt::Key_G)); gotoAction->setShortcutContext(Qt::WindowShortcut); gotoAction->setToolTip(QString("%1 (%2)").arg(gotoAction->text()).arg(gotoAction->shortcut().toString())); connect(gotoAction, SIGNAL(triggered()), SLOT(sl_goto())); removeAllGapsAction = new QAction(QIcon(":core/images/msaed_remove_all_gaps.png"), tr("Remove all gaps"), this); connect(removeAllGapsAction, SIGNAL(triggered()), SLOT(sl_removeAllGaps())); addSeqFromFileAction = new QAction(tr("Sequence from file..."), this); connect(addSeqFromFileAction, SIGNAL(triggered()), SLOT(sl_addSeqFromFile())); addSeqFromProjectAction = new QAction(tr("Sequence from current project..."), this); connect(addSeqFromProjectAction, SIGNAL(triggered()), SLOT(sl_addSeqFromProject())); sortByNameAction = new QAction(tr("Sort sequences by name"), this); connect(sortByNameAction, SIGNAL(triggered()), SLOT(sl_sortByName())); reverseComplementAction = new QAction(tr("Replace selected rows with reverse-complement"), this); connect(reverseComplementAction, SIGNAL(triggered()), SLOT(sl_reverseComplementCurrentSelection())); connect(editor->getMSAObject(), SIGNAL(si_alignmentChanged(const MAlignment&, const MAlignmentModInfo&)), SLOT(sl_alignmentChanged(const MAlignment&, const MAlignmentModInfo&))); connect(editor->getMSAObject(), SIGNAL(si_lockedStateChanged()), SLOT(sl_lockedStateChanged())); connect(editor, SIGNAL(si_buildStaticMenu(GObjectView*, QMenu*)), SLOT(sl_buildStaticMenu(GObjectView*, QMenu*))); connect(editor, SIGNAL(si_buildStaticToolbar(GObjectView*, QToolBar*)), SLOT(sl_buildStaticToolbar(GObjectView*, QToolBar*))); connect(editor, SIGNAL(si_buildPopupMenu(GObjectView* , QMenu*)), SLOT(sl_buildContextMenu(GObjectView*, QMenu*))); connect(editor, SIGNAL(si_zoomOperationPerformed(bool)), SLOT(sl_zoomOperationPerformed(bool))); addAction(ui->getUndoAction()); addAction(ui->getRedoAction()); prepareColorSchemeMenuActions(); updateActions(); } MSAEditorSequenceArea::~MSAEditorSequenceArea() { delete cachedView; } void MSAEditorSequenceArea::prepareColorSchemeMenuActions() { Settings* s = AppContext::getSettings(); MAlignmentObject* maObj = editor->getMSAObject(); if (maObj == NULL) return; DNAAlphabetType atype = maObj->getMAlignment().getAlphabet()->getType(); MSAColorSchemeRegistry* csr = AppContext::getMSAColorSchemeRegistry(); QString csid = atype == DNAAlphabet_AMINO ? s->getValue(SETTINGS_ROOT + SETTINGS_COLOR_AMINO, MSAColorScheme::UGENE_AMINO).toString() : s->getValue(SETTINGS_ROOT + SETTINGS_COLOR_NUCL, MSAColorScheme::UGENE_NUCL).toString(); MSAColorSchemeFactory* csf = csr->getMSAColorSchemeFactoryById(csid); if (csf == NULL) { csf = csr->getMSAColorSchemeFactoryById(atype == DNAAlphabet_AMINO ? MSAColorScheme::UGENE_AMINO : MSAColorScheme::UGENE_NUCL); } assert(csf!=NULL); colorScheme = csf->create(this, maObj); QList factories= csr->getMSAColorSchemes(atype); foreach(MSAColorSchemeFactory* f, factories) { QAction* action = new QAction(f->getName(), this); action->setCheckable(true); action->setChecked(f == csf); action->setData(f->getId()); connect(action, SIGNAL(triggered()), SLOT(sl_changeColorScheme())); colorSchemeMenuActions.append(action); } } void MSAEditorSequenceArea::sl_changeColorScheme() { QAction* a = qobject_cast(sender()); QString id = a->data().toString(); MSAColorSchemeFactory* f = AppContext::getMSAColorSchemeRegistry()->getMSAColorSchemeFactoryById(id); delete colorScheme; if (ui->editor->getMSAObject() == NULL) return; colorScheme = f->create(this, ui->editor->getMSAObject()); foreach(QAction* action, colorSchemeMenuActions) { action->setChecked(action == a); } if (f->getAlphabetType() == DNAAlphabet_AMINO) { AppContext::getSettings()->setValue(SETTINGS_ROOT + SETTINGS_COLOR_AMINO, id); } else { AppContext::getSettings()->setValue(SETTINGS_ROOT + SETTINGS_COLOR_NUCL, id); } completeRedraw = true; update(); } void MSAEditorSequenceArea::updateActions() { MAlignmentObject* maObj = editor->getMSAObject(); assert(maObj != NULL); bool readOnly = maObj->isStateLocked(); delSelectionAction->setEnabled(!readOnly); delColAction->setEnabled(!readOnly); insColAction->setEnabled(!readOnly); insSymAction->setEnabled(!readOnly); createSubaligniment->setEnabled(!readOnly); removeAllGapsAction->setEnabled(!readOnly); addSeqFromProjectAction->setEnabled(!readOnly); addSeqFromFileAction->setEnabled(!readOnly); sortByNameAction->setEnabled(!readOnly); reverseComplementAction->setEnabled(!readOnly && maObj->getAlphabet()->isNucleic()); assert(checkState()); } void MSAEditorSequenceArea::paintEvent(QPaintEvent *e) { drawAll(); QWidget::paintEvent(e); } void MSAEditorSequenceArea::drawAll() { QSize s = size(); if (cachedView->size() != s) { assert(completeRedraw); delete cachedView; cachedView = new QPixmap(s); } if (completeRedraw) { QPainter pCached(cachedView); drawContent(pCached); completeRedraw = false; } QPainter p(this); p.drawPixmap(0, 0, *cachedView); //drawCursor(p); drawSelection(p); drawFocus(p); } void MSAEditorSequenceArea::drawContent(QPainter& p) { MAlignmentObject* maObj = editor->getMSAObject(); assert(maObj!=NULL); p.fillRect(cachedView->rect(), Qt::white); p.setFont(editor->getFont()); //for every sequence in msa starting from first visible //draw it starting from startPos int firstVisibleSeq = getFirstVisibleSequence(); int lastVisibleSeq = getLastVisibleSequence(true); int lastPos = getLastVisibleBase(true); int w = width(); int h = height(); const MAlignment& msa = maObj->getMAlignment(); for (int seq = firstVisibleSeq; seq <= lastVisibleSeq; seq++) { U2Region baseYRange = getSequenceYRange(seq, true); //draw horizontal grid //p.drawLine(0, r.startPos, width(), r.startPos); p.drawLine(0, r.endPos(), width(), r.endPos()); for (int pos = startPos; pos <= lastPos; pos++) { U2Region baseXRange = getBaseXRange(pos, true); QRect cr(baseXRange.startPos, baseYRange.startPos, baseXRange.length+1, baseYRange.length); assert(cr.left() < w && cr.top() < h); Q_UNUSED(w); Q_UNUSED(h); char c = msa.charAt(seq, pos); QColor color = colorScheme->getColor(seq, pos); if (color.isValid()) { p.fillRect(cr, color); } if (editor->getResizeMode() == MSAEditor::ResizeMode_FontAndContent) { p.drawText(cr, Qt::AlignCenter, QString(c)); } } } } void MSAEditorSequenceArea::drawSelection( QPainter &p ) { int x = selection.x(); int y = selection.y(); U2Region xRange = getBaseXRange(x, true); U2Region yRange = getSequenceYRange(y, true); QPen pen(highlightSelection || hasFocus()? Qt::black : Qt::gray); pen.setStyle(Qt::DashLine); pen.setWidth(highlightSelection ? 2 : 1); p.setPen(pen); p.drawRect(xRange.startPos, yRange.startPos, xRange.length*selection.width(), yRange.length*selection.height()); } void MSAEditorSequenceArea::drawCursor(QPainter& p) { if (!isVisible(cursorPos, true)) { return; } U2Region xRange = getBaseXRange(cursorPos.x(), true); U2Region yRange = getSequenceYRange(cursorPos.y(), true); QPen pen(highlightSelection || hasFocus()? Qt::black : Qt::gray); pen.setStyle(Qt::DashLine); pen.setWidth(highlightSelection ? 2 : 1); p.setPen(pen); p.drawRect(xRange.startPos, yRange.startPos, xRange.length, yRange.length); } void MSAEditorSequenceArea::drawFocus(QPainter& p) { if (hasFocus()) { p.setPen(QPen(Qt::black, 1, Qt::DotLine)); p.drawRect(0, 0, width()-1, height()-1); } } bool MSAEditorSequenceArea::isPosInRange(int p) const { return p >= 0 && p < editor->getAlignmentLen(); } bool MSAEditorSequenceArea::isSeqInRange(int s) const { return s >= 0 && s < editor->getNumSequences(); } bool MSAEditorSequenceArea::isPosVisible(int pos, bool countClipped) const { if (pos < getFirstVisibleBase() || pos > getLastVisibleBase(countClipped)) { return false; } return true; } bool MSAEditorSequenceArea::isSeqVisible(int seq, bool countClipped) const { if (seq < getFirstVisibleSequence() || seq > getLastVisibleSequence(countClipped)) { return false; } return true; } void MSAEditorSequenceArea::setFirstVisibleBase(int pos) { Q_ASSERT(isPosInRange(pos)); if (pos == startPos) { return; } QPoint prev(startPos, startSeq); int aliLen = editor->getAlignmentLen(); int effectiveFirst = qMin(aliLen - countWidthForBases(false), pos); startPos = qMax(0, effectiveFirst); updateHScrollBar(); QPoint p(startPos, startSeq); emit si_startChanged(p, prev); completeRedraw = true; update(); } void MSAEditorSequenceArea::setFirstVisibleSequence(int seq) { Q_ASSERT(isSeqInRange(seq)); if (seq == startSeq) { return; } QPoint prev(startPos, startSeq); int nSeq = editor->getNumSequences(); int effectiveFirst = qMin(nSeq - countHeightForSequences(false), seq); startSeq = qMax(0, effectiveFirst); updateVScrollBar(); QPoint p(startPos, startSeq); emit si_startChanged(p, prev); completeRedraw = true; update(); } void MSAEditorSequenceArea::resizeEvent(QResizeEvent *e) { completeRedraw = true; validateRanges(); QWidget::resizeEvent(e); } void MSAEditorSequenceArea::validateRanges() { //check x dimension int aliLen = editor->getAlignmentLen(); int visibleBaseCount = countWidthForBases(false); if (visibleBaseCount > aliLen) { setFirstVisibleBase(0); } else if (startPos + visibleBaseCount > aliLen) { setFirstVisibleBase(aliLen - visibleBaseCount); } assert(startPos >= 0); assert((aliLen >= startPos + visibleBaseCount) || aliLen < visibleBaseCount); updateHScrollBar(); //check y dimension int nSeqs = editor->getNumSequences(); int visibleSequenceCount = countHeightForSequences(false); if (visibleSequenceCount > nSeqs) { setFirstVisibleSequence(0); } else if (startSeq + visibleSequenceCount > nSeqs) { setFirstVisibleSequence(nSeqs - visibleSequenceCount); } assert(startSeq >= 0); assert((nSeqs >= startSeq + visibleSequenceCount) || nSeqs < visibleSequenceCount); updateVScrollBar(); } void MSAEditorSequenceArea::sl_onHScrollMoved(int pos) { assert(pos >=0 && pos <= editor->getAlignmentLen() - getNumVisibleBases(false)); setFirstVisibleBase(pos); } void MSAEditorSequenceArea::sl_onVScrollMoved(int seq) { assert(seq >=0 && seq <= editor->getNumSequences() - getNumVisibleSequences(false)); setFirstVisibleSequence(seq); } void MSAEditorSequenceArea::updateHScrollBar() { shBar->disconnect(this); int numVisibleBases = getNumVisibleBases(false); int alignmentLen = editor->getAlignmentLen(); Q_ASSERT(numVisibleBases <= alignmentLen); shBar->setMinimum(0); shBar->setMaximum(alignmentLen - numVisibleBases); shBar->setSliderPosition(getFirstVisibleBase()); shBar->setSingleStep(1); shBar->setPageStep(numVisibleBases); shBar->setDisabled(numVisibleBases == alignmentLen); connect(shBar, SIGNAL(valueChanged(int)), SLOT(sl_onHScrollMoved(int))); connect(shBar, SIGNAL(actionTriggered(int)), SLOT(sl_onScrollBarActionTriggered(int))); } void MSAEditorSequenceArea::updateVScrollBar() { svBar->disconnect(this); int numVisibleSequences = getNumVisibleSequences(false); int nSeqs = editor->getNumSequences(); Q_ASSERT(numVisibleSequences <= nSeqs); svBar->setMinimum(0); svBar->setMaximum(nSeqs - numVisibleSequences); svBar->setSliderPosition(getFirstVisibleSequence()); svBar->setSingleStep(1); svBar->setPageStep(numVisibleSequences); svBar->setDisabled(numVisibleSequences == nSeqs); connect(svBar, SIGNAL(valueChanged(int)), SLOT(sl_onVScrollMoved(int))); connect(svBar, SIGNAL(actionTriggered(int)), SLOT(sl_onScrollBarActionTriggered(int))); } int MSAEditorSequenceArea::countWidthForBases(bool countClipped, bool forOffset) const { int seqAreaWidth = width(); int colWidth = editor->getColumnWidth(); int nVisible = seqAreaWidth / colWidth; if(countClipped) { bool colIsVisible = ((float)(seqAreaWidth % colWidth) / colWidth < 0.5) ? 0 : 1; colIsVisible |= !forOffset; nVisible += colIsVisible && (seqAreaWidth % colWidth != 0); } //int nVisible = seqAreaWidth / editor->getColumnWidth() + (countClipped && (seqAreaWidth % editor->getColumnWidth() != 0) ? 1 : 0); return nVisible; } int MSAEditorSequenceArea::countHeightForSequences(bool countClipped) const { int seqAreaHeight = height(); int nVisible = seqAreaHeight / editor->getRowHeight() + (countClipped && (seqAreaHeight % editor->getRowHeight() != 0) ? 1 : 0); return nVisible; } int MSAEditorSequenceArea::getNumVisibleBases(bool countClipped, bool forOffset) const { int lastVisible = getLastVisibleBase(countClipped, forOffset); assert(lastVisible >= startPos || (!countClipped && lastVisible + 1 == startPos /*1 symbol is visible & clipped*/)); assert(lastVisible < editor->getAlignmentLen()); int res = lastVisible - startPos + 1; return res; } int MSAEditorSequenceArea::getLastVisibleBase(bool countClipped, bool forOffset) const { int nVisible = countWidthForBases(countClipped, forOffset); int alignLen = editor->getAlignmentLen(); int res = qBound(0, startPos + nVisible - 1, alignLen - 1); return res; } int MSAEditorSequenceArea::getLastVisibleSequence(bool countClipped) const { int nVisible = countHeightForSequences(countClipped); int numSeqs = editor->getNumSequences(); int res = qBound(0, startSeq + nVisible - 1, numSeqs - 1); return res; } int MSAEditorSequenceArea::getNumVisibleSequences(bool countClipped) const { int lastVisible = getLastVisibleSequence(countClipped); assert(lastVisible >= startSeq); assert(lastVisible < editor->getNumSequences()); int res = lastVisible - startSeq + 1; return res; } int MSAEditorSequenceArea::getColumnNumByX(int x) const { int colOffs = x / editor->getColumnWidth(); int pos = startPos + colOffs; if ((pos >= editor->getAlignmentLen()) || (pos < 0)) { return -1; } return pos; } int MSAEditorSequenceArea::getSequenceNumByY(int y) const { int seqOffs = y / editor->getRowHeight(); int seq = startSeq + seqOffs; if ((seq >= editor->getNumSequences()) || (seq < 0)) { return -1; } return seq; } U2Region MSAEditorSequenceArea::getBaseXRange(int pos, bool useVirtualCoords) const { U2Region res(editor->getColumnWidth() * (pos - startPos), editor->getColumnWidth()); if (!useVirtualCoords) { int w = width(); res = res.intersect(U2Region(0, w)); } return res; } U2Region MSAEditorSequenceArea::getSequenceYRange(int seq, bool useVirtualCoords) const { U2Region res(editor->getRowHeight()* (seq - startSeq), editor->getRowHeight()); if (!useVirtualCoords) { int h = height(); res = res.intersect(U2Region(0, h)); } return res; } #define SCROLL_STEP 1 void MSAEditorSequenceArea::updateSelection( const QPoint& newPos) { if (!isInRange(newPos)) { return; } int width = qAbs(newPos.x() - cursorPos.x()) + 1; int height = qAbs(newPos.y() - cursorPos.y()) + 1; // find top left int left = qMin(newPos.x(), cursorPos.x()); int top = qMin(newPos.y(), cursorPos.y()); MSAEditorSelection s(left, top, width, height); if (newPos.x()!=-1 && newPos.y()!=-1) { setSelection(s); } } void MSAEditorSequenceArea::mouseMoveEvent( QMouseEvent* e ) { if ((e->buttons() & Qt::LeftButton) && scribbling) { QPoint absPos = coordToAbsolutePos(e->pos()); if ( isInRange(absPos) ) { updateHBarPosition(absPos.x()); updateVBarPosition(absPos.y()); } updateSelection(absPos); } QWidget::mouseMoveEvent(e); } void MSAEditorSequenceArea::mouseReleaseEvent(QMouseEvent *e) { if (e->button() == Qt::LeftButton) { QPoint pos = coordToAbsolutePos(e->pos()); updateSelection(pos); scribbling = false; } shBar->setupRepeatAction(QAbstractSlider::SliderNoAction); svBar->setupRepeatAction(QAbstractSlider::SliderNoAction); QWidget::mouseReleaseEvent(e); } void MSAEditorSequenceArea::mousePressEvent(QMouseEvent *e) { if (!hasFocus()) { setFocus(); } if (e->button() == Qt::LeftButton) { QPoint p = coordToPos(e->pos()); if (p.x()!=-1 && p.y()!=-1) { setCursorPos(p); setSelection(MSAEditorSelection(p,1,1)); } scribbling = true; } mousePos = e->pos(); QWidget::mousePressEvent(e); } void MSAEditorSequenceArea::keyPressEvent(QKeyEvent *e) { if (!hasFocus()) { return; } int key = e->key(); bool shift = e->modifiers().testFlag(Qt::ShiftModifier); bool ctrl = e->modifiers().testFlag(Qt::ControlModifier); if (ctrl && (key == Qt::Key_Left || key == Qt::Key_Right || key == Qt::Key_Up || key == Qt::Key_Down)) { //remap to page_up/page_down shift = key == Qt::Key_Up || key == Qt::Key_Down; key = (key == Qt::Key_Up || key == Qt::Key_Left) ? Qt::Key_PageUp : Qt::Key_PageDown; } //part of these keys are assigned to actions -> so them never passed to keyPressEvent (action handling has higher priority) switch(key) { case Qt::Key_Escape: cancelSelection(); break; case Qt::Key_Left: //moveCursor(-1, 0); moveSelection(-1,0); break; case Qt::Key_Right: //moveCursor(1, 0); moveSelection(1,0); break; case Qt::Key_Up: //moveCursor(0, -1); moveSelection(0,-1); break; case Qt::Key_Down: //moveCursor(0, 1); moveSelection(0,1); break; case Qt::Key_Home: cancelSelection(); if (shift) { //scroll namelist setFirstVisibleSequence(0); setCursorPos(QPoint(cursorPos.x(), 0)); } else { //scroll sequence cancelSelection(); setFirstVisibleBase(0); setCursorPos(QPoint(0, cursorPos.y())); } break; case Qt::Key_End: cancelSelection(); if (shift) { //scroll namelist int n = editor->getNumSequences() - 1; setFirstVisibleSequence(n); setCursorPos(QPoint(cursorPos.x(), n)); } else { //scroll sequence int n = editor->getAlignmentLen() - 1; setFirstVisibleBase(n); setCursorPos(QPoint(n, cursorPos.y())); } break; case Qt::Key_PageUp: cancelSelection(); if (shift) { //scroll namelist int nVis = getNumVisibleSequences(false); int fp = qMax(0, getFirstVisibleSequence() - nVis); int cp = qMax(0, cursorPos.y() - nVis); setFirstVisibleSequence(fp); setCursorPos(QPoint(cursorPos.x(), cp)); } else { //scroll sequence int nVis = getNumVisibleBases(false); int fp = qMax(0, getFirstVisibleBase() - nVis); int cp = qMax(0, cursorPos.x() - nVis); setFirstVisibleBase(fp); setCursorPos(QPoint(cp, cursorPos.y())); } break; case Qt::Key_PageDown: cancelSelection(); if (shift) { //scroll namelist int nVis = getNumVisibleSequences(false); int nSeq = editor->getNumSequences(); int fp = qMin(nSeq-1, getFirstVisibleSequence() + nVis); int cp = qMin(nSeq-1, cursorPos.y() + nVis); setFirstVisibleSequence(fp); setCursorPos(QPoint(cursorPos.x(), cp)); } else { //scroll sequence int nVis = getNumVisibleBases(false); int len = editor->getAlignmentLen(); int fp = qMin(len-1, getFirstVisibleBase() + nVis); int cp = qMin(len-1, cursorPos.x() + nVis); setFirstVisibleBase(fp); setCursorPos(QPoint(cp, cursorPos.y())); } break; case Qt::Key_Delete: if (shift) { sl_delCol(); } else { deleteCurrentSelection(); } break; case Qt::Key_Backspace: // Cursor mode emulation: selection is of size one if ( (selection.width() == 1) && (selection.height() == 1) ) { QPoint pos = selection.topLeft(); if (pos.x() > 0) { del(QPoint(pos.x()-1, pos.y()), shift); } } break; case Qt::Key_Insert: fillSelectionWithGaps(); break; } QWidget::keyPressEvent(e); } void MSAEditorSequenceArea::focusInEvent(QFocusEvent* fe) { QWidget::focusInEvent(fe); update(); } void MSAEditorSequenceArea::focusOutEvent(QFocusEvent* fe) { QWidget::focusOutEvent(fe); update(); } void MSAEditorSequenceArea::moveSelection( int dx, int dy ) { int leftX = selection.x(); int topY = selection.y(); int bottomY = selection.y() + selection.height() - 1; int rightX = selection.x() + selection.width() - 1; QPoint baseTopLeft(leftX, topY); QPoint baseBottomRight(rightX,bottomY); QPoint newTopLeft = baseTopLeft + QPoint(dx,dy); QPoint newBottomRight = baseBottomRight + QPoint(dx,dy); if ((!isInRange(newTopLeft)) || (!isInRange(newBottomRight)) ) { return; } if (!isVisible(newTopLeft, false)) { if (isVisible(newTopLeft, true)) { if (dx != 0) { setFirstVisibleBase(startPos + dx); } if (dy!=0) { setFirstVisibleSequence(getFirstVisibleSequence()+dy); } } else { if (dx != 0) { setFirstVisibleBase(newTopLeft.x()); } if (dy !=0 ) { setFirstVisibleSequence(newTopLeft.y()); } } } MSAEditorSelection newSelection(newTopLeft, selection.width(), selection.height()); setSelection(newSelection); } void MSAEditorSequenceArea::moveCursor(int dx, int dy) { QPoint p = cursorPos + QPoint(dx, dy); if (!isInRange(p)) { return; } // Move only one cell selection? // TODO: consider selection movement int sz = selection.width()*selection.height(); if (sz != 1) { return; } if (!isVisible(p, false)) { if (isVisible(cursorPos, true)) { if (dx != 0) { setFirstVisibleBase(startPos + dx); } if (dy!=0) { setFirstVisibleSequence(getFirstVisibleSequence()+dy); } } else { setFirstVisibleBase(p.x()); setFirstVisibleSequence(p.y()); } } setCursorPos(p); //setSelection(MSAEditorSelection(p, 1,1)); } int MSAEditorSequenceArea::coordToPos(int x) const { int y = getSequenceYRange(getFirstVisibleSequence(), false).startPos; return coordToPos(QPoint(x, y)).x(); } QPoint MSAEditorSequenceArea::coordToAbsolutePos(const QPoint& coord) const { int column = getColumnNumByX(coord.x()); int row = getSequenceNumByY(coord.y()); return QPoint(column, row); } QPoint MSAEditorSequenceArea::coordToPos(const QPoint& coord) const { QPoint res(-1, -1); //Y: row for (int i=getFirstVisibleSequence(), n = getLastVisibleSequence(true); i<=n; i++) { U2Region r = getSequenceYRange(i, false); if (r.contains(coord.y())) { res.setY(i); break; } } //X: position in sequence for (int i=getFirstVisibleBase(), n = getLastVisibleBase(true); i<=n; i++) { U2Region r = getBaseXRange(i, false); if (r.contains(coord.x())) { res.setX(i); break; } } return res; } void MSAEditorSequenceArea::setSelection(const MSAEditorSelection& s) { // TODO: assert(isInRange(s)); if (s == selection) { return; } MSAEditorSelection prevSelection = selection; selection = s; int selEndPos = s.x() + s.width() - 1; int ofRange = selEndPos - editor->getAlignmentLen(); if(ofRange>=0) { selection = MSAEditorSelection(s.topLeft(), s.width() - ofRange - 1, s.height()); } emit si_selectionChanged(selection, prevSelection); QPoint current = prevSelection.topLeft(), prev = prevSelection.topLeft(); emit si_cursorMoved(current, prev); update(); } void MSAEditorSequenceArea::setCursorPos(const QPoint& p) { assert(isInRange(p)); if (p == cursorPos) { return; } QPoint prev = cursorPos; cursorPos = p; emit si_cursorMoved(cursorPos, prev); //if (up) { // update(); //} highlightSelection = false; updateActions(); } void MSAEditorSequenceArea::ins(const QPoint& p, bool columnMode) { assert(isInRange(p)); MAlignmentObject* maObj = editor->getMSAObject(); if (maObj == NULL || maObj->isStateLocked()) { return; } if (columnMode) { maObj->insertGap(p.x(), 1); } else { maObj->insertGap(p.y(), p.x(), 1); } } void MSAEditorSequenceArea::del(const QPoint& p, bool columnMode) { assert(isInRange(p)); MAlignmentObject* maObj = editor->getMSAObject(); if (maObj == NULL || maObj->isStateLocked()) { return; } if (columnMode) { maObj->deleteGap(p.x(), 1); } else { maObj->deleteGap(p.y(), p.x(), 1); } } void MSAEditorSequenceArea::sl_alignmentChanged(const MAlignment&, const MAlignmentModInfo&) { int aliLen = editor->getAlignmentLen(); int nSeq = editor->getNumSequences(); //todo: set in one method! setFirstVisibleBase(qBound(0, startPos, aliLen-countWidthForBases(false))); setFirstVisibleSequence(qBound(0, startSeq, nSeq - countHeightForSequences(false))); setCursorPos(qMin(cursorPos.x(), aliLen-1), qMin(cursorPos.y(), nSeq-1)); QPoint selTopLeft( qMin(selection.x(), aliLen - 1), qMin(selection.y(), nSeq - 1) ); QPoint selBottomRight( qMin(selection.x() + selection.width() - 1, aliLen - 1), qMin(selection.y() + selection.height() - 1, nSeq -1 ) ); MSAEditorSelection newSelection(selTopLeft, selBottomRight); // we don't emit "selection changed" signal to avoid redrawing selection = newSelection; updateHScrollBar(); updateVScrollBar(); completeRedraw = true; update(); } void MSAEditorSequenceArea::sl_buildStaticToolbar(GObjectView*, QToolBar* t) { t->addAction(ui->getUndoAction()); t->addAction(ui->getRedoAction()); t->addAction(gotoAction); t->addAction(removeAllGapsAction); } void MSAEditorSequenceArea::sl_buildStaticMenu(GObjectView*, QMenu* m) { buildMenu(m); } void MSAEditorSequenceArea::sl_buildContextMenu(GObjectView*, QMenu* m) { buildMenu(m); QMenu* editMenu = GUIUtils::findSubMenu(m, MSAE_MENU_EDIT); assert(editMenu!=NULL); QList actions; actions << delSelectionAction << delColAction << insSymAction << reverseComplementAction; QMenu* copyMenu = GUIUtils::findSubMenu(m, MSAE_MENU_COPY); assert(copyMenu != NULL); if (rect().contains( mapFromGlobal(QCursor::pos()) ) ) { editMenu->addActions(actions); copyMenu->addAction(copySelectionAction); } } void MSAEditorSequenceArea::buildMenu(QMenu* m) { QAction* copyMenuAction = GUIUtils::findAction(m->actions(), MSAE_MENU_LOAD); m->insertAction(copyMenuAction, gotoAction); QMenu* loadSeqMenu = GUIUtils::findSubMenu(m, MSAE_MENU_LOAD); assert(loadSeqMenu!=NULL); loadSeqMenu->addAction(addSeqFromProjectAction); loadSeqMenu->addAction(addSeqFromFileAction); QMenu* editMenu = GUIUtils::findSubMenu(m, MSAE_MENU_EDIT); assert(editMenu!=NULL); QList actions; actions << removeAllGapsAction; editMenu->insertActions(editMenu->isEmpty() ? NULL : editMenu->actions().first(), actions); QMenu * exportMenu = GUIUtils::findSubMenu(m, MSAE_MENU_EXPORT); assert(exportMenu != NULL); exportMenu->addAction(createSubaligniment); QMenu* copyMenu = GUIUtils::findSubMenu(m, MSAE_MENU_COPY); copyMenu->addAction(copySelectionAction); QMenu* viewMenu = GUIUtils::findSubMenu(m, MSAE_MENU_VIEW); assert(viewMenu!=NULL); viewMenu->addAction(sortByNameAction); QMenu* colorsSchemeMenu = new QMenu(tr("Colors"), m); colorsSchemeMenu->setIcon(QIcon(":core/images/color_wheel.png")); foreach(QAction* a, colorSchemeMenuActions) { colorsSchemeMenu->addAction(a); } m->insertMenu(GUIUtils::findAction(m->actions(), MSAE_MENU_EDIT), colorsSchemeMenu); } void MSAEditorSequenceArea::sl_delSym() { del(cursorPos, false); } void MSAEditorSequenceArea::sl_delCol() { DeleteGapsDialog dlg(this, editor->getMSAObject()->getMAlignment().getNumRows()); if(dlg.exec() == QDialog::Accepted) { DeleteMode deleteMode = dlg.getDeleteMode(); int value = dlg.getValue(); MAlignmentObject* msaObj = editor->getMSAObject(); switch(deleteMode) { case DeleteByAbsoluteVal: msaObj->deleteGapsByAbsoluteVal(value); break; case DeleteByRelativeVal: msaObj->deleteGapsByAbsoluteVal( ( msaObj->getMAlignment().getNumRows()*value ) / 100 ); break; case DeleteAll: msaObj->deleteAllGapColumn(); break; default: assert(0); } } //del(cursorPos, true); } void MSAEditorSequenceArea::sl_fillCurrentSelectionWithGaps() { fillSelectionWithGaps(); } void MSAEditorSequenceArea::sl_insCol() { ins(cursorPos, true); } void MSAEditorSequenceArea::sl_goto() { QDialog dlg; dlg.setModal(true); dlg.setWindowTitle(tr("Go To")); int aliLen = editor->getAlignmentLen(); PositionSelector* ps = new PositionSelector(&dlg, 1, aliLen, true); connect(ps, SIGNAL(si_positionChanged(int)), SLOT(sl_onPosChangeRequest(int))); dlg.exec(); delete ps; } void MSAEditorSequenceArea::sl_onPosChangeRequest(int pos) { centerPos(pos-1); setSelection(MSAEditorSelection(pos-1,selection.y(),1,1)); } void MSAEditorSequenceArea::sl_lockedStateChanged() { updateActions(); } void MSAEditorSequenceArea::centerPos(const QPoint& pos) { assert(isInRange(pos)); int newStartPos = qMax(0, pos.x() - getNumVisibleBases(false)/2); setFirstVisibleBase(newStartPos); int newStartSeq = qMax(0, pos.y() - getNumVisibleSequences(false)/2); setFirstVisibleSequence(newStartSeq); } void MSAEditorSequenceArea::centerPos(int pos) { centerPos(QPoint(pos, cursorPos.y())); } void MSAEditorSequenceArea::wheelEvent (QWheelEvent * we) { bool toMin = we->delta() > 0; if (we->modifiers() == 0) { shBar->triggerAction(toMin ? QAbstractSlider::SliderSingleStepSub : QAbstractSlider::SliderSingleStepAdd); } else if (we->modifiers() & Qt::SHIFT) { svBar->triggerAction(toMin ? QAbstractSlider::SliderSingleStepSub : QAbstractSlider::SliderSingleStepAdd); } QWidget::wheelEvent(we); } void MSAEditorSequenceArea::sl_removeAllGaps() { QBitArray gapMap(256); gapMap[MAlignment_GapChar] = true; MAlignmentObject* msa = editor->getMSAObject(); assert(!msa->isStateLocked()); MAlignment ma = msa->getMAlignment(); bool changed = ma.simplify(); if (changed) { msa->setMAlignment(ma); setFirstVisibleBase(0); setFirstVisibleSequence(0); } } bool MSAEditorSequenceArea::checkState() const { #ifdef _DEBUG MAlignmentObject* maObj = editor->getMSAObject(); int aliLen = maObj->getMAlignment().getLength(); int nSeqs = maObj->getMAlignment().getNumRows(); assert(startPos >=0 && startSeq >=0); int lastPos = getLastVisibleBase(true); int lastSeq = getLastVisibleSequence(true); assert(lastPos < aliLen && lastSeq < nSeqs); int cx = cursorPos.x(); int cy = cursorPos.y(); assert(cx >= 0 && cy >= 0); assert(cx < aliLen && cy < nSeqs); #endif return true; } void MSAEditorSequenceArea::sl_zoomOperationPerformed( bool resizeModeChanged ) { Q_UNUSED(resizeModeChanged); completeRedraw = true; validateRanges(); updateActions(); update(); } void MSAEditorSequenceArea::sl_createSubaligniment(){ CreateSubalignimentDialogController dialog(editor->getMSAObject(), selection.getRect(), this); dialog.exec(); if(dialog.result() == QDialog::Accepted){ U2Region window = dialog.getRegion(); bool addToProject = dialog.getAddToProjFlag(); QString path = dialog.getSavePath(); QStringList seqNames = dialog.getSelectedSeqNames(); Task* csTask = new CreateSubalignmentAndOpenViewTask(editor->getMSAObject(), CreateSubalignmentSettings(window, seqNames, path, true, addToProject) ); AppContext::getTaskScheduler()->registerTopLevelTask(csTask); } } void MSAEditorSequenceArea::cancelSelection() { MSAEditorSelection emptySelection; setSelection(emptySelection); } void MSAEditorSequenceArea::sl_onScrollBarActionTriggered( int scrollAction ) { QScrollBar* sbar = qobject_cast( QObject::sender() ); if (sbar == NULL) { return; } if (scrollAction == QAbstractSlider::SliderSingleStepAdd || scrollAction == QAbstractSlider::SliderSingleStepSub) { if (scribbling) { QPoint coord = mapFromGlobal(QCursor::pos()); QPoint pos = coordToAbsolutePos(coord); if ( (scrollAction == QAbstractSlider::SliderSingleStepSub) && (sbar == shBar) ) { pos.setX(pos.x() - 1); } else if ( (scrollAction == QAbstractSlider::SliderSingleStepSub) && (sbar == svBar) ) { pos.setY(pos.y() - 1); } updateSelection(pos); } } } void MSAEditorSequenceArea::updateHBarPosition( int base ) { if (base <= getFirstVisibleBase() ) { shBar->setupRepeatAction(QAbstractSlider::SliderSingleStepSub, 50, 10); } else if (base >= getLastVisibleBase(true)) { shBar->setupRepeatAction(QAbstractSlider::SliderSingleStepAdd, 50, 10); } else { shBar->setupRepeatAction(QAbstractSlider::SliderNoAction); } } void MSAEditorSequenceArea::updateVBarPosition( int seq ) { if (seq <= getFirstVisibleSequence()) { svBar->setupRepeatAction(QAbstractSlider::SliderSingleStepSub, 50, 10); } else if (seq >= getLastVisibleSequence(true)) { svBar->setupRepeatAction(QAbstractSlider::SliderSingleStepAdd, 50, 10); } else { svBar->setupRepeatAction(QAbstractSlider::SliderNoAction); } } void MSAEditorSequenceArea::sl_delCurrentSelection() { deleteCurrentSelection(); } void MSAEditorSequenceArea::sl_copyCurrentSelection() { // TODO: probably better solution would be to export selection??? assert(isInRange(selection.topLeft())); assert(isInRange( QPoint(selection.x() + selection.width() - 1, selection.y() + selection.height() - 1) ) ); MAlignmentObject* maObj = editor->getMSAObject(); if ( selection.isNull() ) { return; } const MAlignment& msa = maObj->getMAlignment(); int startSeq = selection.y(); int endSeq = startSeq + selection.height(); QString selText; for (int i = startSeq; i < endSeq; ++i) { const MAlignmentRow& row = msa.getRow(i); int len = selection.width(); QByteArray seqPart = row.mid(selection.x(), len).toByteArray(len); selText.append(seqPart); if (i + 1 != endSeq) { // do not add line break into the last line selText.append("\n"); } } QApplication::clipboard()->setText(selText); } void MSAEditorSequenceArea::deleteCurrentSelection() { if (selection.isNull()) { return; } assert(isInRange(selection.topLeft())); assert(isInRange( QPoint(selection.x() + selection.width() - 1, selection.y() + selection.height() - 1) ) ); MAlignmentObject* maObj = editor->getMSAObject(); if (maObj == NULL || maObj->isStateLocked()) { return; } if ( !selection.isNull() ) { const MAlignment& msa = maObj->getMAlignment(); if (selection.width() == msa.getLength() && selection.height() == msa.getNumRows()) { return; } maObj->removeRegion(selection.x(), selection.y(), selection.width(), selection.height(), true); } if (selection.height() == 1 && selection.width() == 1) { if (isInRange(selection.topLeft())) { return; } } cancelSelection(); } void MSAEditorSequenceArea::sl_addSeqFromFile() { MAlignmentObject* msaObject = editor->getMSAObject(); if (msaObject->isStateLocked()) { return; } QString filter = DialogUtils::prepareDocumentsFileFilterByObjType(GObjectTypes::SEQUENCE, true); LastOpenDirHelper lod; QStringList urls = QFileDialog::getOpenFileNames(this, tr("Open file with sequences"), lod.dir, filter); if (!urls.isEmpty()) { lod.url = urls.first(); cancelSelection(); AddSequencesToAlignmentTask * task = new AddSequencesToAlignmentTask(msaObject, urls); AppContext::getTaskScheduler()->registerTopLevelTask(task); } } void MSAEditorSequenceArea::sl_addSeqFromProject() { MAlignmentObject* msaObject = editor->getMSAObject(); if (msaObject->isStateLocked()) { return; } ProjectTreeControllerModeSettings settings; settings.objectTypesToShow.append(GObjectTypes::SEQUENCE); std::auto_ptr seqConstraints(new DNASequenceObjectConstraints()); seqConstraints->alphabetType = msaObject->getAlphabet()->getType(); settings.objectConstraints.append(seqConstraints.get()); QList objects = ProjectTreeItemSelectorDialog::selectObjects(settings,this); if (!objects.isEmpty()) { foreach(GObject* obj, objects) { if (obj->isUnloaded()) { continue; } DNASequenceObject* seqObj = qobject_cast(obj); if (seqObj) { msaObject->addRow(seqObj->getDNASequence(), 0); cancelSelection(); } } } } void MSAEditorSequenceArea::sl_sortByName() { MAlignmentObject* msaObject = editor->getMSAObject(); if (msaObject->isStateLocked()) { return; } MAlignment ma = msaObject->getMAlignment(); ma.sortRowsByName(); QStringList rowNames = ma.getRowNames(); if (rowNames != msaObject->getMAlignment().getRowNames()) { msaObject->setMAlignment(ma); } } void MSAEditorSequenceArea::fillSelectionWithGaps( ) { if (selection.isNull()) { return; } assert(isInRange(selection.topLeft())); assert(isInRange( QPoint(selection.x() + selection.width() - 1, selection.y() + selection.height() - 1) ) ); MAlignmentObject* maObj = editor->getMSAObject(); if (maObj == NULL || maObj->isStateLocked()) { return; } const MAlignment& msa = maObj->getMAlignment(); if (selection.width() == msa.getLength() && selection.height() == msa.getNumRows()) { return; } U2Region sequences(selection.y(), selection.height()); maObj->insertGap(sequences, selection.x() , selection.width()); if (selection.height() > 1 && selection.width() > 1) { cancelSelection(); } } void MSAEditorSequenceArea::sl_reverseComplementCurrentSelection() { MAlignmentObject* maObj = editor->getMSAObject(); if (maObj == NULL || maObj->isStateLocked()) { return; } if (!maObj->getAlphabet()->isNucleic()) { return; } if (selection.height() == 0) { return; } assert(isInRange(selection.topLeft())); assert(isInRange( QPoint(selection.x() + selection.width() - 1, selection.y() + selection.height() - 1) ) ); if ( !selection.isNull() ) { MAlignment ma = maObj->getMAlignment(); DNATranslation* trans = AppContext::getDNATranslationRegistry()->lookupComplementTranslation(ma.getAlphabet()); if (trans == NULL || !trans->isOne2One()) { return; } for (int i = selection.y(); i < selection.y() + selection.height(); i++) { QByteArray curr = ma.getRow(i).toByteArray(ma.getLength()); trans->translate(curr.data(), curr.length()); TextUtils::reverse(curr.data(), curr.length()); QString name = ma.getRow(i).getName(); if (name.endsWith("|revcompl")) { name.resize(name.length() - QString("|revcompl").length()); } else { name.append("|revcompl"); } DNASequence seq(name, curr, maObj->getAlphabet()); maObj->removeRow(i); maObj->addRow(seq, i); } } } }//namespace ugene-1.9.8/src/corelibs/U2View/src/util_ov_msaedit/MSAEditor.cpp0000644000175000017500000005050211651544334023305 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "MSAEditor.h" #include "MSAEditorTasks.h" #include "MSAEditorFactory.h" #include "MSAEditorState.h" #include "MSAEditorConsensusArea.h" #include "MSAEditorOffsetsView.h" #include "MSAEditorSequenceArea.h" #include "MSAEditorNameList.h" #include "MSAEditorStatusBar.h" #include "MSAEditorUndoFramework.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include namespace U2 { #define MIN_FONT_SIZE 8 #define MAX_FONT_SIZE 18 #define MIN_COLUMN_WIDTH 1 #define SETTINGS_ROOT QString("msaeditor/") #define SETTINGS_FONT_FAMILY "font_family" #define SETTINGS_FONT_SIZE "font_size" #define SETTINGS_FONT_ITALIC "font_italic" #define SETTINGS_FONT_BOLD "font_bold" #define SETTINGS_ZOOM_FACTOR "zoom_factor" #define DEFAULT_FONT_FAMILY "Verdana" #define DEFAULT_FONT_SIZE 10 #define DEFAULT_ZOOM_FACTOR 1.0f /* TRANSLATOR U2::MSAEditor */ const float MSAEditor::zoomMult = 1.25; MSAEditor::MSAEditor(const QString& viewName, GObject* obj) : GObjectView(MSAEditorFactory::ID, viewName), ui(NULL) { msaObject = qobject_cast(obj); objects.append(msaObject); onObjectAdded(msaObject); requiredObjects.append(msaObject); GCOUNTER(cvar,tvar,"MSAEditor"); zoomInAction = new QAction(QIcon(":core/images/zoom_in.png"), tr("Zoom In"), this); connect(zoomInAction, SIGNAL(triggered()), SLOT(sl_zoomIn())); zoomOutAction = new QAction(QIcon(":core/images/zoom_out.png"), tr("Zoom Out"), this); connect(zoomOutAction, SIGNAL(triggered()), SLOT(sl_zoomOut())); zoomToSelectionAction = new QAction(QIcon(":core/images/zoom_reg.png"), tr("Zoom To Selection"), this); connect(zoomToSelectionAction, SIGNAL(triggered()), SLOT(sl_zoomToSelection())); resetFontAction = new QAction(QIcon(":core/images/zoom_whole.png"), tr("Reset Zoom"), this); connect(resetFontAction, SIGNAL(triggered()), SLOT(sl_resetZoom())); changeFontAction = new QAction(QIcon(":core/images/font.png"), tr("Change Font"), this); connect(changeFontAction, SIGNAL(triggered()), SLOT(sl_changeFont())); buildTreeAction = new QAction(QIcon(":/core/images/phylip.png"), tr("Build Tree"), this); connect(buildTreeAction, SIGNAL(triggered()), SLOT(sl_buildTree())); Settings* s = AppContext::getSettings(); zoomFactor = DEFAULT_ZOOM_FACTOR; font.setFamily(s->getValue(SETTINGS_ROOT + SETTINGS_FONT_FAMILY, DEFAULT_FONT_FAMILY).toString()); font.setPointSize(s->getValue(SETTINGS_ROOT + SETTINGS_FONT_SIZE, DEFAULT_FONT_SIZE).toInt()); font.setItalic(s->getValue(SETTINGS_ROOT + SETTINGS_FONT_ITALIC, false).toBool()); font.setBold(s->getValue(SETTINGS_ROOT + SETTINGS_FONT_BOLD, false).toBool()); calcFontPixelToPointSizeCoef(); updateActions(); if ( (font.pointSize() == MIN_FONT_SIZE) && (zoomFactor < 1.0f) ) { resizeMode = ResizeMode_OnlyContent; } else { resizeMode = ResizeMode_FontAndContent; } } int MSAEditor::getRowHeight() const { QFontMetrics fm(font); return fm.height() * zoomMult; } int MSAEditor::getColumnWidth() const { QFontMetrics fm(font); int width = fm.width('W') * zoomMult; width = (int)(width * zoomFactor); width = qMax(width, MIN_COLUMN_WIDTH); return width; } void MSAEditor::sl_zoomIn() { int pSize = font.pointSize(); if (resizeMode == ResizeMode_OnlyContent) { zoomFactor *= zoomMult; } else if ( (pSize < MAX_FONT_SIZE) && (resizeMode == ResizeMode_FontAndContent) ) { font.setPointSize(pSize+1); setFont(font); } bool resizeModeChanged = false; if (zoomFactor >= 1) { resizeMode = ResizeMode_FontAndContent; zoomFactor = 1; resizeModeChanged = true; } updateActions(); emit si_zoomOperationPerformed(resizeModeChanged); } void MSAEditor::sl_zoomOut() { int pSize = font.pointSize(); bool resizeModeChanged = false; if (pSize > MIN_FONT_SIZE) { font.setPointSize(pSize-1); setFont(font); } else { Q_ASSERT(zoomMult > 0); zoomFactor /= zoomMult; resizeMode = ResizeMode_OnlyContent; resizeModeChanged = true; } updateActions(); emit si_zoomOperationPerformed(resizeModeChanged); } void MSAEditor::sl_zoomToSelection() { ResizeMode oldMode = resizeMode; int seqAreaWidth = ui->seqArea->width(); MSAEditorSelection selection = ui->seqArea->getSelection(); if (selection.isNull()) { return; } int selectionWidth = selection.width(); float pixelsPerBase = (seqAreaWidth / float(selectionWidth)) * zoomMult; int fontPointSize = int(pixelsPerBase / fontPixelToPointSize); if (fontPointSize >= MIN_FONT_SIZE) { if (fontPointSize > MAX_FONT_SIZE) { fontPointSize = MAX_FONT_SIZE; } font.setPointSize(fontPointSize); setFont(font); resizeMode = ResizeMode_FontAndContent; zoomFactor = 1; } else { if (font.pointSize() != MIN_FONT_SIZE) { font.setPointSize(MIN_FONT_SIZE); setFont(font); } zoomFactor = pixelsPerBase / (MIN_FONT_SIZE * fontPixelToPointSize); resizeMode = ResizeMode_OnlyContent; } ui->seqArea->setFirstVisibleBase(selection.x()); ui->seqArea->setFirstVisibleSequence(selection.y()); updateActions(); emit si_zoomOperationPerformed(oldMode == resizeMode); } void MSAEditor::sl_buildTree() { PhyTreeGeneratorRegistry* registry = AppContext::getPhyTreeGeneratorRegistry(); QStringList list = registry->getNameList(); if (list.size() == 0){ QMessageBox::information(ui, tr("Calculate phy tree"), tr("No algorithms for building phylogenetic tree are available.") ); return; } CreatePhyTreeDialogController dlg(widget, msaObject, settings); int rc = dlg.exec(); if (rc != QDialog::Accepted) { return; } treeGeneratorTask = new PhyTreeGeneratorTask(msaObject->getMAlignment(), settings); connect(treeGeneratorTask, SIGNAL(si_stateChanged()), SLOT(sl_openTree())); TaskScheduler* scheduler = AppContext::getTaskScheduler(); scheduler->registerTopLevelTask(treeGeneratorTask); } void MSAEditor::sl_openTree() { if (treeGeneratorTask->getState() != Task::State_Finished || treeGeneratorTask->hasError()) { return; } const GUrl& msaURL = msaObject->getDocument()->getURL(); assert(!msaURL.isEmpty()); if (msaURL.isEmpty()) { return; } Project* p = AppContext::getProject(); QString treeFileName = settings.fileUrl.getURLString(); if (treeFileName.isEmpty()) { treeFileName = GUrlUtils::rollFileName(msaURL.dirPath() + "/" + msaURL.baseFileName() + ".nwk", DocumentUtils::getNewDocFileNameExcludesHint()); } PhyTreeObject *newObj = new PhyTreeObject(treeGeneratorTask->getResult(), "Tree"); DocumentFormat* df = AppContext::getDocumentFormatRegistry()->getFormatById(BaseDocumentFormats::NEWICK); IOAdapterFactory *iof = AppContext::getIOAdapterRegistry()->getIOAdapterFactoryById(BaseIOAdapters::LOCAL_FILE); Document *d = new Document(df, iof, treeFileName, QList()<addDocument(d); Task* saveTask = new SaveDocumentTask(d); Task* task = new OpenTreeViewerTask(newObj); TaskScheduler* scheduler = AppContext::getTaskScheduler(); scheduler->registerTopLevelTask(saveTask); scheduler->registerTopLevelTask(task); } void MSAEditor::onObjectRenamed(GObject*, const QString&) { // update title OpenMSAEditorTask::updateTitle(this); } static void saveFont(const QFont& f) { Settings* s = AppContext::getSettings(); s->setValue(SETTINGS_ROOT + SETTINGS_FONT_FAMILY, f.family()); s->setValue(SETTINGS_ROOT + SETTINGS_FONT_SIZE, f.pointSize()); s->setValue(SETTINGS_ROOT + SETTINGS_FONT_ITALIC, f.italic()); s->setValue(SETTINGS_ROOT + SETTINGS_FONT_BOLD, f.bold()); } void MSAEditor::setFont(const QFont& f) { int pSize = f.pointSize(); font = f; calcFontPixelToPointSizeCoef(); font.setPointSize(qBound(MIN_FONT_SIZE, pSize, MAX_FONT_SIZE)); emit si_fontChanged(f); saveFont(font); } void MSAEditor::setFirstVisibleBase(int firstPos) { if (ui->seqArea->isPosInRange(firstPos)) { ui->seqArea->setFirstVisibleBase(firstPos); } } int MSAEditor::getFirstVisibleBase() const { return ui->seqArea->getFirstVisibleBase(); } void MSAEditor::sl_changeFont() { bool ok = false; QFont f = QFontDialog::getFont(&ok, font, widget, tr("Select font for alignment")); if (!ok) { return; } setFont(f); updateActions(); } void MSAEditor::sl_resetZoom() { QFont f(DEFAULT_FONT_FAMILY, DEFAULT_FONT_SIZE); setFont(f); zoomFactor = DEFAULT_ZOOM_FACTOR; ResizeMode oldMode = resizeMode; resizeMode = ResizeMode_FontAndContent; emit si_zoomOperationPerformed(resizeMode == oldMode); updateActions(); } MSAEditor::~MSAEditor() { } void MSAEditor::buildStaticToolbar(QToolBar* tb) { tb->addAction(zoomInAction); tb->addAction(zoomOutAction); tb->addAction(zoomToSelectionAction); tb->addAction(resetFontAction); tb->addAction(changeFontAction); tb->addAction(buildTreeAction); tb->addAction(saveScreenshotAction); GObjectView::buildStaticToolbar(tb); } void MSAEditor::buildStaticMenu(QMenu* m) { addLoadMenu(m); addCopyMenu(m); addEditMenu(m); addAlignMenu(m); addTreeMenu(m); addStatisticsMenu(m); addViewMenu(m); addExportMenu(m); addAdvancedMenu(m); GObjectView::buildStaticMenu(m); GUIUtils::disableEmptySubmenus(m); } void MSAEditor::addCopyMenu(QMenu* m) { QMenu* cm = m->addMenu(tr("Copy")); cm->menuAction()->setObjectName(MSAE_MENU_COPY); } void MSAEditor::addEditMenu(QMenu* m) { QMenu* em = m->addMenu(tr("Edit")); em->menuAction()->setObjectName(MSAE_MENU_EDIT); } void MSAEditor::addExportMenu(QMenu* m) { QMenu* em = m->addMenu(tr("Export")); em->menuAction()->setObjectName(MSAE_MENU_EXPORT); } void MSAEditor::addViewMenu(QMenu* m) { QMenu* em = m->addMenu(tr("View")); em->menuAction()->setObjectName(MSAE_MENU_VIEW); if (ui->offsetsView != NULL) { em->addAction(ui->offsetsView->getToggleColumnsViewAction()); } } void MSAEditor::addAlignMenu(QMenu* m) { QMenu* em = m->addMenu(tr("Align")); em->setIcon(QIcon(":core/images/align.png")); em->menuAction()->setObjectName(MSAE_MENU_ALIGN); } void MSAEditor::addTreeMenu(QMenu* m) { QMenu* em = m->addMenu(tr("Tree")); //em->setIcon(QIcon(":core/images/tree.png")); em->menuAction()->setObjectName(MSAE_MENU_TREES); em->addAction(buildTreeAction); } void MSAEditor::addAdvancedMenu(QMenu* m) { QMenu* em = m->addMenu(tr("Advanced")); em->menuAction()->setObjectName(MSAE_MENU_ADVANCED); } void MSAEditor::addStatisticsMenu(QMenu* m) { QMenu* em = m->addMenu(tr("Statistics")); em->setIcon(QIcon(":core/images/chart_bar.png")); em->menuAction()->setObjectName(MSAE_MENU_STATISTICS); } void MSAEditor::addLoadMenu( QMenu* m ) { QMenu* lsm = m->addMenu(tr("Add")); lsm->menuAction()->setObjectName(MSAE_MENU_LOAD); } Task* MSAEditor::updateViewTask(const QString& stateName, const QVariantMap& stateData) { return new UpdateMSAEditorTask(this, stateName, stateData); } QVariantMap MSAEditor::saveState() { return MSAEditorState::saveState(this); } QWidget* MSAEditor::createWidget() { assert(ui == NULL); ui = new MSAEditorUI(this); connect(ui , SIGNAL(customContextMenuRequested(const QPoint &)), SLOT(sl_onContextMenuRequested(const QPoint &))); saveScreenshotAction = new QAction(QIcon(":/core/images/cam2.png"), tr("Export as image"), this); connect(saveScreenshotAction, SIGNAL(triggered()), ui, SLOT(sl_saveScreenshot())); initDragAndDropSupport(); return ui; } int MSAEditor::getAlignmentLen() const { return msaObject->getMAlignment().getLength(); } int MSAEditor::getNumSequences() const { return msaObject->getMAlignment().getNumRows(); } void MSAEditor::sl_onContextMenuRequested(const QPoint & pos) { Q_UNUSED(pos); QMenu m; addLoadMenu(&m); addCopyMenu(&m); addEditMenu(&m); addAlignMenu(&m); addTreeMenu(&m); addStatisticsMenu(&m); addViewMenu(&m); addExportMenu(&m); addAdvancedMenu(&m); emit si_buildPopupMenu(this, &m); GUIUtils::disableEmptySubmenus(&m); m.exec(QCursor::pos()); } const QRect& MSAEditor::getCurrentSelection() const { return ui->seqArea->getSelection().getRect(); } void MSAEditor::updateActions() { zoomInAction->setEnabled(font.pointSize() < MAX_FONT_SIZE); zoomOutAction->setEnabled( getColumnWidth() > MIN_COLUMN_WIDTH ); zoomToSelectionAction->setEnabled( font.pointSize() < MAX_FONT_SIZE); changeFontAction->setEnabled( resizeMode == ResizeMode_FontAndContent); } void MSAEditor::calcFontPixelToPointSizeCoef() { QFontInfo info(font); fontPixelToPointSize = (float) info.pixelSize() / (float) info.pointSize(); } bool MSAEditor::eventFilter(QObject*, QEvent* e) { if (e->type() == QEvent::DragEnter || e->type() == QEvent::Drop) { QDropEvent* de = (QDropEvent*)e; const QMimeData* md = de->mimeData(); const GObjectMimeData* gomd = qobject_cast(md); if (gomd != NULL) { if (msaObject->isStateLocked()) { return false; } DNASequenceObject* dnaObj = qobject_cast (gomd->objPtr.data()); if (dnaObj != NULL ) { if (DNAAlphabet::deriveCommonAlphabet(dnaObj->getAlphabet(), msaObject->getAlphabet()) == NULL) { return false; } if (e->type() == QEvent::DragEnter) { de->acceptProposedAction(); } else { msaObject->addRow(dnaObj->getDNASequence()); } } } } return false; } void MSAEditor::initDragAndDropSupport() { assert(ui!= NULL); ui->setAcceptDrops(true); ui->installEventFilter(this); } ////////////////////////////////////////////////////////////////////////// MSAEditorUI::MSAEditorUI(MSAEditor* _editor): editor(_editor), seqArea(NULL), offsetsView(NULL), statusWidget(NULL) { undoFWK = new MSAEditorUndoFramework(this, editor->getMSAObject()); setContextMenuPolicy(Qt::CustomContextMenu); setMinimumSize(300, 200); setWindowIcon(GObjectTypes::getTypeInfo(GObjectTypes::MULTIPLE_ALIGNMENT).icon); QWidget *seqAreaContainer, *nameAreaContainer, *label; GScrollBar* shBar = new GScrollBar(Qt::Horizontal); QScrollBar* nhBar = new QScrollBar(Qt::Horizontal); GScrollBar* cvBar = new GScrollBar(Qt::Vertical); seqArea = new MSAEditorSequenceArea(this, shBar, cvBar); nameList = new MSAEditorNameList(this, nhBar); consArea = new MSAEditorConsensusArea(this); offsetsView = new MSAEditorOffsetsViewController(this, editor, seqArea); statusWidget = new MSAEditorStatusWidget(editor->getMSAObject(), seqArea); QWidget* label1 = createLabelWidget(); QWidget* label2 = createLabelWidget(); label1->setMinimumHeight(consArea->height()); label2->setMinimumHeight(consArea->height()); offsetsView->getLeftWidget()->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::MinimumExpanding); offsetsView->getRightWidget()->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::MinimumExpanding); QGridLayout* seqAreaLayout = new QGridLayout(); seqAreaLayout->setMargin(0); seqAreaLayout->setSpacing(0); seqAreaLayout->addWidget(consArea, 0, 1); seqAreaLayout->addWidget(label1, 0, 0); seqAreaLayout->addWidget(offsetsView->getLeftWidget(), 1, 0, 2, 1); seqAreaLayout->addWidget(seqArea, 1, 1); seqAreaLayout->addWidget(label2, 0, 2); seqAreaLayout->addWidget(offsetsView->getRightWidget(), 1, 2, 2, 1); seqAreaLayout->addWidget(shBar, 2, 1, 1, 1); seqAreaContainer = new QWidget(); seqAreaContainer->setLayout(seqAreaLayout); label = createLabelWidget(tr("Consensus")); label->setMinimumHeight(consArea->height()); nameList->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::MinimumExpanding); QVBoxLayout* nameAreaLayout = new QVBoxLayout(); nameAreaLayout->setMargin(0); nameAreaLayout->setSpacing(0); nameAreaLayout->addWidget(label); nameAreaLayout->addWidget(nameList); nameAreaLayout->addWidget(nhBar); nameAreaContainer = new QWidget(); nameAreaContainer->setLayout(nameAreaLayout); splitter = new QSplitter(Qt::Horizontal); splitter->addWidget(nameAreaContainer); splitter->addWidget(seqAreaContainer); splitter->setStretchFactor(0, 0); splitter->setStretchFactor(1, 0); splitter->setStretchFactor(2, 1); //TODO: make initial namelist size depend on font int baseSize = splitter->width(); int nameListSize = baseSize / 5; splitter->setSizes(QList()<< nameListSize << baseSize - nameListSize); splitter->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::MinimumExpanding); label = createLabelWidget(); label->setMinimumHeight(consArea->height()); cvBar->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::MinimumExpanding); QGridLayout *mainLayout = new QGridLayout(); mainLayout->setMargin(0); mainLayout->setSpacing(0); mainLayout->addWidget(splitter, 0, 0, 2, 1); mainLayout->addWidget(cvBar, 1, 1); mainLayout->addWidget(label, 0, 1); mainLayout->addWidget(statusWidget, 2, 0, 1, 2); QWidget *mainWidget = new QWidget(); mainWidget->setLayout(mainLayout); setLayout(mainLayout); } QWidget* MSAEditorUI::createLabelWidget(const QString& text, Qt::Alignment ali) const { return new MSALabelWidget(this, text, ali); } QAction* MSAEditorUI::getUndoAction() const { return undoFWK->getUndoAction(); } QAction* MSAEditorUI::getRedoAction() const { return undoFWK->getRedoAction(); } void MSAEditorUI::sl_saveScreenshot(){ ExportImageDialog dialog(this); dialog.exec(); } MSALabelWidget::MSALabelWidget(const MSAEditorUI* _ui, const QString & _t, Qt::Alignment _a) : ui(_ui), text(_t), ali(_a) { connect(ui->getEditor(), SIGNAL(si_fontChanged(const QFont&)), SLOT(sl_fontChanged())); } void MSALabelWidget::paintEvent(QPaintEvent *) { QPainter p(this); p.fillRect(rect(), Qt::white); if (!text.isEmpty()) { p.setFont(ui->getEditor()->getFont()); p.drawText(rect(), text, ali); } } void MSALabelWidget::sl_fontChanged() { update(); setMinimumHeight(ui->consArea->height()); } void MSALabelWidget::mousePressEvent( QMouseEvent *e ) { ui->seqArea->cancelSelection(); } }//namespace ugene-1.9.8/src/corelibs/U2View/src/util_ov_msaedit/MSAEditorNameList.h0000644000175000017500000000637311651544334024416 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_MSA_EDITOR_NAME_LIST_H_ #define _U2_MSA_EDITOR_NAME_LIST_H_ #include #include #include #include #include namespace U2 { class MSAEditor; class MSAEditorUI; class GObjectView; class MAlignment; class MAlignmentModInfo; class MSAEditorSelection; class MSAEditorNameList: public QWidget { Q_OBJECT public: MSAEditorNameList(MSAEditorUI* ui, QScrollBar* nhBar); ~MSAEditorNameList(); private slots: void sl_buildStaticMenu(GObjectView* v, QMenu* m); void sl_buildContextMenu(GObjectView* v, QMenu* m); void sl_copyCurrentSequence(); void sl_editSequenceName(); void sl_lockedStateChanged(); void sl_removeCurrentSequence(); void sl_alignmentChanged(const MAlignment&, const MAlignmentModInfo&); void sl_onScrollBarActionTriggered( int scrollAction ); void sl_startChanged(const QPoint& p, const QPoint& prev); void sl_selectionChanged(const MSAEditorSelection& current, const MSAEditorSelection& prev); void sl_nameBarMoved(int n); void sl_fontChanged(); protected: void resizeEvent(QResizeEvent* e); void paintEvent(QPaintEvent* e); void keyPressEvent (QKeyEvent *e); void mousePressEvent(QMouseEvent *e); void mouseMoveEvent(QMouseEvent* e); void mouseReleaseEvent(QMouseEvent *e); void mouseDoubleClickEvent(QMouseEvent *e); void focusOutEvent(QFocusEvent* fe); void focusInEvent(QFocusEvent* fe); void wheelEvent (QWheelEvent * we); //todo context menu? private: bool isRowInSelection(int row); void updateActions(); void buildMenu(QMenu* m); void updateScrollBar(); void updateSelection(int newSeqNum); void moveSelectedRegion( int shift ); void drawAll(); void drawContent(QPainter& p); void drawSelection(QPainter& p); void drawSequenceItem(QPainter& p, int n, bool selected); void drawFocus(QPainter& p); MSAEditor* editor; MSAEditorUI* ui; QScrollBar* nhBar; int curSeq; QPoint origin; bool scribbling,shifting; QRubberBand* rubberBand; QAction* editSequenceNameAction; QAction* copyCurrentSequenceAction; QAction* removeCurrentSequenceAction; QPixmap* cachedView; bool completeRedraw; }; }//namespace #endif ugene-1.9.8/src/corelibs/U2View/src/util_ov_msaedit/MSAEditorStatusBar.cpp0000644000175000017500000001673211651544334025145 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "MSAEditorStatusBar.h" #include "MSAEditorSequenceArea.h" #include #include #include #include #include namespace U2 { MSAEditorStatusWidget::MSAEditorStatusWidget(MAlignmentObject* mobj, MSAEditorSequenceArea* sa) : aliObj(mobj), seqArea(sa), lockedIcon(":core/images/lock.png"), unlockedIcon(":core/images/lock_open.png") { setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::Minimum); QLabel* findLabel = new QLabel(); findLabel->setText(tr("Find:")); prevButton = new QPushButton(); prevButton->setToolTip(tr("Find backward (SHIFT + Enter)")); prevButton->setIcon(QIcon(":core/images/msa_find_prev.png")); prevButton->setFlat(true); nextButton = new QPushButton(); nextButton->setToolTip(tr("Find forward (Enter)")); nextButton->setIcon(QIcon(":core/images/msa_find_next.png")); nextButton->setFlat(true); searchEdit = new QLineEdit(); //searchEdit->setMinimumWidth(200); searchEdit->installEventFilter(this); searchEdit->setMaxLength(1000); findLabel->setBuddy(searchEdit); linesLabel = new QLabel(); linesLabel->setAlignment(Qt::AlignCenter); colsLabel = new QLabel(); colsLabel->setAlignment(Qt::AlignCenter); lockLabel = new QLabel(); QHBoxLayout* l = new QHBoxLayout(); l->setMargin(2); l->addStretch(1); l->addWidget(findLabel); l->addWidget(prevButton); l->addWidget(searchEdit); l->addWidget(nextButton); // l->addStretch(1); l->addWidget(linesLabel); l->addWidget(colsLabel); l->addWidget(lockLabel); setLayout(l); connect(seqArea, SIGNAL(si_cursorMoved(const QPoint&,const QPoint&)), SLOT(sl_cursorMoved(const QPoint&,const QPoint&))); connect(mobj, SIGNAL(si_alignmentChanged(const MAlignment&, const MAlignmentModInfo&)), SLOT(sl_alignmentChanged(const MAlignment&, const MAlignmentModInfo&))); connect(mobj, SIGNAL(si_lockedStateChanged()), SLOT(sl_lockStateChanged())); connect(prevButton, SIGNAL(clicked()), SLOT(sl_findPrev())); connect(nextButton, SIGNAL(clicked()), SLOT(sl_findNext())); findAction = new QAction(tr("Find in alignment"), this);//this action is used only to enable shortcut to change focus today findAction->setShortcut(QKeySequence(Qt::CTRL | Qt::Key_F)); findAction->setShortcutContext(Qt::WindowShortcut); connect(findAction, SIGNAL(triggered()), SLOT(sl_findFocus())); addAction(findAction); updateCoords(); updateLock(); } void MSAEditorStatusWidget::updateLock() { bool locked = aliObj->isStateLocked(); lockLabel->setPixmap(locked ? lockedIcon : unlockedIcon); lockLabel->setToolTip(locked ? tr("Alignment object is locked") : tr("Alignment object is not locked")); } void MSAEditorStatusWidget::updateCoords() { const QPoint& pos = seqArea->getSelection().topLeft(); int aliLen = aliObj->getMAlignment().getLength(); int nSeq = aliObj->getMAlignment().getNumRows(); QFontMetrics fm(linesLabel->font()); QString lpattern = QString(tr("Ln %1 / %2")); QString ltext = lpattern.arg(pos.y() + 1).arg(nSeq); linesLabel->setText(ltext); linesLabel->setToolTip(tr("Line %1 of %2").arg(pos.y() + 1).arg(nSeq)); linesLabel->setMinimumWidth(10 + fm.width(lpattern.arg(nSeq).arg(nSeq))); QString cpattern = QString(tr("Col %1 / %2")); QString ctext = cpattern.arg(pos.x() + 1).arg(aliLen); colsLabel->setText(ctext); colsLabel->setToolTip(tr("Column %1 of %2").arg(pos.x() + 1).arg(aliLen)); colsLabel->setMinimumWidth(10 + fm.width(cpattern.arg(aliLen).arg(aliLen))); } bool MSAEditorStatusWidget::eventFilter(QObject*, QEvent* ev) { if (ev->type() == QEvent::KeyPress) { QKeyEvent* kev = (QKeyEvent*)ev; if (kev->key() == Qt::Key_Enter || kev->key() == Qt::Key_Return) { if (kev->modifiers() == Qt::SHIFT) { prevButton->click(); } else { nextButton->click(); } } else if (kev->key() == Qt::Key_Escape) { seqArea->setFocus(); } } return false; } void MSAEditorStatusWidget::sl_findNext() { QByteArray pat = searchEdit->text().toLocal8Bit(); if (pat.isEmpty()) { return; } const MAlignment& ma = aliObj->getMAlignment(); if (!ma.getAlphabet()->isCaseSensitive()) { pat = pat.toUpper(); } int aliLen = ma.getLength(); int nSeq = ma.getNumRows(); QPoint pos = seqArea->getSelection().topLeft(); if (pos == lastSearchPos) { pos.setX(pos.x() + 1); } for (int s = pos.y(); s < nSeq; s++) { const MAlignmentRow& row = ma.getRow(s); // if s == pos.y -> search from the current base, otherwise search from the seq start int p = (s == pos.y()) ? pos.x() : 0; for (; p < (aliLen - pat.length() + 1); p++) { char c = row.chatAt(p); if (c != MAlignment_GapChar && MSAUtils::equalsIgnoreGaps(row, p, pat)) { // select the result now MSAEditorSelection sel(p,s, pat.length(), 1); seqArea->setSelection(sel); seqArea->highlightCurrentSelection(); seqArea->centerPos(sel.topLeft()); lastSearchPos = seqArea->getSelection().topLeft(); return; } } } } void MSAEditorStatusWidget::sl_findPrev() { QByteArray pat = searchEdit->text().toLocal8Bit(); if (pat.isEmpty()) { return; } const MAlignment& ma = aliObj->getMAlignment(); if (!ma.getAlphabet()->isCaseSensitive()) { pat = pat.toUpper(); } int aliLen = ma.getLength(); QPoint pos = seqArea->getSelection().topLeft(); if (pos == lastSearchPos) { pos.setX(pos.x() - 1); } for (int s = pos.y(); s >= 0; s--) { const MAlignmentRow& row = ma.getRow(s); //if s == pos.y -> search from the current base, otherwise search from the seq end int p = (s == pos.y() ? pos.x() : (aliLen - pat.length() + 1)); while (p >=0) { if (row.chatAt(p) != MAlignment_GapChar && MSAUtils::equalsIgnoreGaps(row, p, pat)) { // select the result now MSAEditorSelection sel(p,s, pat.length(), 1); seqArea->setSelection(sel); seqArea->highlightCurrentSelection(); seqArea->centerPos(sel.topLeft()); lastSearchPos = seqArea->getSelection().topLeft(); return; } p--; } } } void MSAEditorStatusWidget::sl_findFocus() { searchEdit->setFocus(); } }//namespace ugene-1.9.8/src/corelibs/U2View/src/util_ov_msaedit/DeleteGapsDialog.h0000644000175000017500000000263511651544334024324 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _DELETE_GAPS_DIALOG_ #define _DELETE_GAPS_DIALOG_ #include "ui/ui_DeleteGapsDialog.h" namespace U2 { enum DeleteMode { DeleteByAbsoluteVal, DeleteByRelativeVal, DeleteAll }; class DeleteGapsDialog: public QDialog, public Ui_DeleteGapsDialog { Q_OBJECT public: DeleteGapsDialog(QWidget* parent, int alignmentLen); DeleteMode getDeleteMode() const {return deleteMode;} int getValue() const {return value;} private slots: void sl_onOkClicked(); void sl_onCancelClicked(); private: DeleteMode deleteMode; int value; }; } #endifugene-1.9.8/src/corelibs/U2View/src/util_ov_msaedit/ui/0000755000175000017500000000000011651544334021425 5ustar ilyailyaugene-1.9.8/src/corelibs/U2View/src/util_ov_msaedit/ui/ConsensusSelectorDialog.ui0000644000175000017500000001201111651544334026560 0ustar ilyailya ConsensusSelectorDialog 0 0 455 275 Consensus representation Select consensus representation scheme Select consensus representation scheme true true Consensus type 0 0 false Threshold false true Qt::Horizontal QSlider::NoTicks 10 false 80 0 Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter QAbstractSpinBox::UpDownArrows false Reset to default value Reset :/core/images/arrow_rotate_clockwise.png:/core/images/arrow_rotate_clockwise.png true Qt::Horizontal 40 20 OK Cancel cancelButton clicked() ConsensusSelectorDialog reject() 338 173 192 97 okButton clicked() ConsensusSelectorDialog accept() 257 173 192 97 ugene-1.9.8/src/corelibs/U2View/src/util_ov_msaedit/ui/DeleteGapsDialog.ui0000644000175000017500000000467011651544334025130 0ustar ilyailya DeleteGapsDialog 0 0 363 120 Remove columns of gaps Remove columns with number of gaps Remove columns with percentage of gaps % 10 100 Remove all columns of gaps Qt::Horizontal 40 20 Remove Cancel ugene-1.9.8/src/corelibs/U2View/src/util_ov_msaedit/ui/CreateSubalignimentDialog.ui0000644000175000017500000001433011651544334027032 0ustar ilyailya CreateSubalignimentDialog 0 0 350 345 Extract selected as MSA From 0 0 Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter 1 500000 to 0 0 Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter 1 Selected sequences 100 Qt::Horizontal 40 20 Invert selection Select all Clear selection File name ... Qt::Horizontal 40 20 Add to project true Qt::Vertical 20 1 Qt::Horizontal 40 20 Extract true Cancel okButton clicked() CreateSubalignimentDialog accept() 181 374 155 198 cancelButton clicked() CreateSubalignimentDialog reject() 264 374 155 198 ugene-1.9.8/src/corelibs/U2View/src/util_ov_msaedit/DeleteGapsDialog.cpp0000644000175000017500000000334511651544334024656 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "DeleteGapsDialog.h" namespace U2 { DeleteGapsDialog::DeleteGapsDialog(QWidget* parent, int rowNum): QDialog(parent) { setupUi(this); allRadioButton->setChecked(true); absoluteSpinBox->setMinimum(1); absoluteSpinBox->setMaximum(rowNum); connect(deleteButton, SIGNAL(clicked()), SLOT(sl_onOkClicked())); connect(cancelButton, SIGNAL(clicked()), SLOT(sl_onCancelClicked())); } void DeleteGapsDialog::sl_onOkClicked() { deleteMode = allRadioButton->isChecked() ? DeleteAll : (relativeRadioButton->isChecked() ? DeleteByRelativeVal : DeleteByAbsoluteVal); switch(deleteMode) { case DeleteByAbsoluteVal: value = absoluteSpinBox->value(); break; case DeleteByRelativeVal: value = relativeSpinBox->value(); break; default: value = 0; } accept(); } void DeleteGapsDialog::sl_onCancelClicked() { reject(); } }ugene-1.9.8/src/corelibs/U2View/src/util_ov_msaedit/MSAColorScheme.cpp0000644000175000017500000006061611651544334024271 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "MSAColorScheme.h" #include "MSAEditorFactory.h" #include #include #include namespace U2 { ////////////////////////////////////////////////////////////////////////// // factories MSAColorSchemeFactory::MSAColorSchemeFactory(QObject* p, const QString& _id, const QString& _name, DNAAlphabetType _at) : QObject(p), id(_id), name(_name), aType(_at) { } MSAColorSchemeStaticFactory::MSAColorSchemeStaticFactory(QObject* p, const QString& _id, const QString& _name, DNAAlphabetType _atype, const QVector& _colorsPerChar) : MSAColorSchemeFactory(p, _id, _name, _atype), colorsPerChar(_colorsPerChar) { } MSAColorScheme* MSAColorSchemeStaticFactory::create(QObject* p, MAlignmentObject* o) { return new MSAColorSchemeStatic(p, this, o, colorsPerChar); } MSAColorSchemePercIdentFactory::MSAColorSchemePercIdentFactory(QObject* p, const QString& _id, const QString& _name, DNAAlphabetType _atype) : MSAColorSchemeFactory(p, _id, _name, _atype) { } MSAColorScheme* MSAColorSchemePercIdentFactory::create(QObject* p, MAlignmentObject* o) { return new MSAColorSchemePercIdent(p, this, o); } MSAColorSchemeClustalXFactory::MSAColorSchemeClustalXFactory(QObject* p, const QString& _id, const QString& _name, DNAAlphabetType _atype) : MSAColorSchemeFactory(p, _id, _name, _atype) { } MSAColorScheme* MSAColorSchemeClustalXFactory::create(QObject* p, MAlignmentObject* o) { return new MSAColorSchemeClustalX(p, this, o); } ////////////////////////////////////////////////////////////////////////// // schemes MSAColorScheme::MSAColorScheme(QObject* p, MSAColorSchemeFactory* f, MAlignmentObject* o) : QObject(p), factory(f), maObj(o) { } MSAColorSchemeStatic::MSAColorSchemeStatic(QObject* p, MSAColorSchemeFactory* f, MAlignmentObject* o, const QVector& _cp) : MSAColorScheme(p, f, o), colorsPerChar(_cp) { } QColor MSAColorSchemeStatic::getColor(int seq, int pos) { char c = maObj->getMAlignment().charAt(seq, pos); return getColor(c); } /// PERCENT MSAColorSchemePercIdent::MSAColorSchemePercIdent(QObject* p, MSAColorSchemeFactory* f, MAlignmentObject* o) : MSAColorScheme(p, f, o) { cacheVersion = 0; objVersion = 1; mask4[0]=81; mask4[1]=61; mask4[2]=41; mask4[3]=25; colorsByRange[0] = QColor("#6464FF"); colorsByRange[1] = QColor("#9999FF"); colorsByRange[2] = QColor("#CCCCFF"); colorsByRange[3] = QColor(); connect(maObj, SIGNAL(si_alignmentChanged(const MAlignment&, const MAlignmentModInfo&)), SLOT(sl_alignmentChanged(const MAlignment&, const MAlignmentModInfo&))); } QColor MSAColorSchemePercIdent::getColor(int seq, int pos) { updateCache(); char c = maObj->getMAlignment().charAt(seq, pos); if (c == MAlignment_GapChar) { return QColor(); } quint32 packedVal = indentCache[pos]; MSAConsensusUtils::unpackConsensusCharsFromInt(packedVal, tmpChars, tmpRanges); for (int i=0; i < 4; i++) { if (c == tmpChars[i]) { int range = tmpRanges[i]; return colorsByRange[range]; } } return QColor(); } void MSAColorSchemePercIdent::updateCache() { if (cacheVersion == objVersion) { return; } const MAlignment& ma = maObj->getMAlignment(); int aliLen = ma.getLength(); indentCache.resize(aliLen); for (int i=0; i < aliLen; i++) { indentCache[i] = MSAConsensusUtils::packConsensusCharsToInt(ma, i, mask4, true); } cacheVersion = objVersion; } /// CLUSTAL MSAColorSchemeClustalX::MSAColorSchemeClustalX(QObject* p, MSAColorSchemeFactory* f, MAlignmentObject* maObj) : MSAColorScheme(p, f, maObj) { objVersion = 1; cacheVersion = 0; aliLen = maObj->getMAlignment().getLength(); colorByIdx[ClustalColor_BLUE] = "#80a0f0"; colorByIdx[ClustalColor_RED] = "#f01505"; colorByIdx[ClustalColor_GREEN] = "#15c015"; colorByIdx[ClustalColor_PINK] = "#f08080"; colorByIdx[ClustalColor_MAGENTA] = "#c048c0"; colorByIdx[ClustalColor_ORANGE] = "#f09048"; colorByIdx[ClustalColor_CYAN] = "#15a4a4"; colorByIdx[ClustalColor_YELLOW] = "#c0c000"; connect(maObj, SIGNAL(si_alignmentChanged(const MAlignment&, const MAlignmentModInfo&)), SLOT(sl_alignmentChanged(const MAlignment&, const MAlignmentModInfo&))); } QColor MSAColorSchemeClustalX::getColor(int seq, int pos) { if (cacheVersion!=objVersion) { updateCache(); } int idx = getColorIdx(seq, pos); assert(idx >=0 && idx < ClustalColor_NUM_COLORS); return colorByIdx[idx]; } int MSAColorSchemeClustalX::getColorIdx(int seq, int pos) { bool low = false; int cacheIdx = getCacheIdx(seq, pos, low); quint8 val = colorsCache[cacheIdx]; int colorIdx = low ? val & 0x0F : (val & 0xF0) >> 4; assert(colorIdx >=0 && colorIdx < ClustalColor_NUM_COLORS); return colorIdx; } void MSAColorSchemeClustalX::setColorIdx(int seq, int pos, int colorIdx) { assert(colorIdx >=0 && colorIdx < ClustalColor_NUM_COLORS); bool low = false; int cacheIdx = getCacheIdx(seq, pos, low); quint8 val = colorsCache[cacheIdx]; if (low) { val = (val & 0xF0) | colorIdx; } else { val = (val & 0x0F) | (colorIdx << 4); } colorsCache[cacheIdx] = val; } static int basesContent(const int* freqs, const char* str, int len) { int res = 0; for (int i=0; i < len; i++) { uchar c = str[i]; res +=freqs[c]; } return res; } void MSAColorSchemeClustalX::updateCache() { if (cacheVersion == objVersion) { return; } // compute colors for whole ali // use 4 bits per color const MAlignment& ma = maObj->getMAlignment(); int nSeq = ma.getNumRows(); aliLen = maObj->getMAlignment().getLength(); cacheVersion = objVersion; bool stub = false; int cacheSize = getCacheIdx(nSeq, aliLen, stub) + 1; colorsCache.resize(cacheSize); /* source: http://ekhidna.biocenter.helsinki.fi/pfam2/clustal_colours BLUE (W,L,V,I,M,F): {50%, P}{60%, WLVIMAFCYHP} (A): {50%, P}{60%, WLVIMAFCYHP}{85%, T,S,G} (C): {50%, P}{60%, WLVIMAFCYHP}{85%, S} RED (K,R): {60%, KR}{85%, Q} GREEN (T): {50%, TS}{60%, WLVIMAFCYHP} (S): {50%, TS}{80%, WLVIMAFCYHP} (N): {50%, N}{85%, D} (Q): {50%, QE}{60%, KR} PINK (C): {85%, C} MAGENTA (D): {50%, DE,N} (E): {50%, DE,QE} ORANGE (G): {ALWAYS} CYAN (H,Y): {50%, P}{60%, WLVIMAFCYHP} YELLOW (P): {ALWAYS} WARN: do not count gaps in percents! */ QVector freqsByChar(256); const int* freqs = freqsByChar.data(); for (int pos = 0; pos < aliLen; pos++) { int nonGapChars = 0; MSAConsensusUtils::getColumnFreqs(ma, pos, freqsByChar, nonGapChars); int content50 = int(nonGapChars * 50.0 / 100); int content60 = int(nonGapChars * 60.0 / 100); int content80 = int(nonGapChars * 80.0 / 100); int content85 = int(nonGapChars * 85.0 / 100); for (int seq = 0; seq < nSeq; seq++) { char c = ma.charAt(seq, pos); int colorIdx = ClustalColor_NO_COLOR; switch(c) { case 'W': //(W,L,V,I,M,F): {50%, P}{60%, WLVIMAFCYHP} -> BLUE case 'L': case 'V': case 'I': case 'M': case 'F': if (freqs['P'] > content50 || basesContent(freqs, "WLVIMAFCYHP", 11) > content60) { colorIdx = ClustalColor_BLUE; } break; case 'A': // {50%, P}{60%, WLVIMAFCYHP}{85%, T,S,G} -> BLUE if (freqs['P'] > content50 || basesContent(freqs, "WLVIMAFCYHP", 11) > content60) { colorIdx = ClustalColor_BLUE; } else if (freqs['T'] > content85 || freqs['S'] > content85 || freqs['G']>85) { colorIdx = ClustalColor_BLUE; } break; case 'K': //{60%, KR}{85%, Q} -> RED case 'R': if ((freqs['K'] + freqs['R'] > content60) || freqs['Q'] > content85) { colorIdx = ClustalColor_RED; } break; case 'T': // {50%, TS}{60%, WLVIMAFCYHP} -> GREEN if ((freqs['T'] + freqs['S'] > content50) || basesContent(freqs, "WLVIMAFCYHP", 11) > content60) { colorIdx = ClustalColor_GREEN; } break; case 'S': // {50%, TS}{80%, WLVIMAFCYHP} -> GREEN if ((freqs['T'] + freqs['S'] > content50) || basesContent(freqs, "WLVIMAFCYHP", 11) > content80) { colorIdx = ClustalColor_GREEN; } break; case 'N': // {50%, N}{85%, D} -> GREEN if (freqs['N'] > content50 || freqs['D'] > content85) { colorIdx = ClustalColor_GREEN; } break; case 'Q': // {50%, QE}{60%, KR} -> GREEN if ((freqs['Q'] + freqs['E']) > content50 || (freqs['K'] + freqs['R']) > content60) { colorIdx = ClustalColor_GREEN; } break; case 'C': //{85%, C} -> PINK //{50%, P}{60%, WLVIMAFCYHP}{85%, S} -> BLUE if (freqs['C'] > content85) { colorIdx = ClustalColor_PINK; } else if (freqs['P'] > content50 || basesContent(freqs, "WLVIMAFCYHP", 11) > content60 || freqs['S'] > content85) { colorIdx = ClustalColor_BLUE; } break; case 'D': //{50%, DE,N} -> MAGENTA if ((freqs['D'] + freqs['E']) > content50 || freqs['N'] > content50) { colorIdx = ClustalColor_MAGENTA; } break; case 'E': //{50%, DE,QE} -> MAGENTA if ((freqs['D'] + freqs['E']) > content50 || (freqs['Q'] + freqs['E']) > content50) { colorIdx = ClustalColor_MAGENTA; } break; case 'G': //{ALWAYS} -> ORANGE colorIdx = ClustalColor_ORANGE; break; case 'H': // {50%, P}{60%, WLVIMAFCYHP} -> CYAN case 'Y': if (freqs['P'] > content50 || basesContent(freqs, "WLVIMAFCYHP", 11) > content60) { colorIdx = ClustalColor_CYAN; } break; case 'P': //{ALWAYS} -> YELLOW colorIdx = ClustalColor_YELLOW; break; default: break; } setColorIdx(seq, pos, colorIdx); } } } ////////////////////////////////////////////////////////////////////////// // registry MSAColorSchemeRegistry::MSAColorSchemeRegistry() { initBuiltInSchemes(); } QList MSAColorSchemeRegistry::getMSAColorSchemes(DNAAlphabetType atype) const { QList res; foreach(MSAColorSchemeFactory* f, colorers) { if (f->getAlphabetType() == atype) { res.append(f); } } return res; } MSAColorSchemeFactory* MSAColorSchemeRegistry::getMSAColorSchemeFactoryById(const QString& id) const { foreach(MSAColorSchemeFactory* csf, colorers) { if(csf->getId() == id) { return csf; } } return NULL; } static bool compareNames(const MSAColorSchemeFactory* a1, const MSAColorSchemeFactory* a2) { if (a1->getId() == MSAColorScheme::EMPTY_NUCL) { return true; } if (a2->getId() == MSAColorScheme::EMPTY_NUCL) { return false; } if (a1->getId() == MSAColorScheme::EMPTY_AMINO) { return true; } if (a2->getId() == MSAColorScheme::EMPTY_AMINO) { return false; } return a1->getName() < a2->getName(); } void MSAColorSchemeRegistry::addMSAColorSchemeFactory(MSAColorSchemeFactory* csf) { assert(getMSAColorSchemeFactoryById(csf->getId()) == NULL); colorers.append(csf); qStableSort(colorers.begin(), colorers.end(), compareNames); } static void fillEmptyCS(QVector& colorsPerChar) { colorsPerChar.fill(QColor(), 256); } static void fillLightColorsCS(QVector& colorsPerChar) { for (int i = 0; i < 256; i++) { colorsPerChar[i] = FeatureColors::genLightColor(QString((char)i)); } colorsPerChar[MAlignment_GapChar] = QColor(); //invalid color -> no color at all } #define SET_C(ch, cl) colorsPerChar[ch]=colorsPerChar[ch+('a'-'A')]=cl static void addUGENEAmino(QVector& colorsPerChar) { //amino groups: "KRH", "GPST", "FWY", "ILM" QColor krh("#FFEE00"); SET_C('K', krh); SET_C('R', krh.darker(120)); SET_C('H', krh.lighter(120)); QColor gpst("#FF5082"); SET_C('G', gpst); SET_C('P', gpst.darker(120)); SET_C('S', gpst.lighter(120)); SET_C('T', gpst.lighter(150)); QColor fwy("#3DF490"); SET_C('F', fwy); SET_C('W', fwy.darker(120)); SET_C('Y', fwy.lighter(120)); QColor ilm("#00ABED"); SET_C('I', ilm); SET_C('L', ilm.darker(120)); SET_C('M', ilm.lighter(120)); //fix some color overlaps: //e looks like q by default SET_C('E', "#C0BDBB"); //gray SET_C('X', "#FCFCFC"); } static void addUGENENucl(QVector& colorsPerChar) { SET_C('A', "#FCFF92"); // yellow SET_C('C', "#70F970"); // green SET_C('T', "#FF99B1"); // light red SET_C('G', "#4EADE1"); // light blue SET_C('U', colorsPerChar['T'].lighter(120)); SET_C('N', "#FCFCFC"); } //TODO: check extended AMINO chars!!! (O/B/U?) static void addZappoAmino(QVector& colorsPerChar) { //Aliphatic/hydrophobic: ILVAM #ffafaf SET_C('I', "#ffafaf"); SET_C('L', "#ffafaf"); SET_C('V', "#ffafaf"); SET_C('A', "#ffafaf"); SET_C('M', "#ffafaf"); //Aromatic: FWY #ffc800 SET_C('F', "#ffc800"); SET_C('W', "#ffc800"); SET_C('Y', "#ffc800"); //Positive KRH #6464ff SET_C('K', "#6464ff"); SET_C('R', "#6464ff"); SET_C('H', "#6464ff"); //Negative DE #ff0000 SET_C('D', "#ff0000"); SET_C('E', "#ff0000"); //Hydrophil STNQ #00ff00 SET_C('S', "#00ff00"); SET_C('T', "#00ff00"); SET_C('N', "#00ff00"); SET_C('Q', "#00ff00"); //conformat PG #ff00ff SET_C('P', "#ff00ff"); SET_C('G', "#ff00ff"); //Cysteine C #ffff00 SET_C('C', "#ffff00"); } static void addTailorAmino(QVector& colorsPerChar) { SET_C('A', "#ccff00"); SET_C('V', "#99ff00"); SET_C('I', "#66ff00"); SET_C('L', "#33ff00"); SET_C('M', "#00ff00"); SET_C('F', "#00ff66"); SET_C('Y', "#00ffcc"); SET_C('W', "#00ccff"); SET_C('H', "#0066ff"); SET_C('R', "#0000ff"); SET_C('K', "#6600ff"); SET_C('N', "#cc00ff"); SET_C('Q', "#ff00cc"); SET_C('E', "#ff0066"); SET_C('D', "#ff0000"); SET_C('S', "#ff3300"); SET_C('T', "#ff6600"); SET_C('G', "#ff9900"); SET_C('P', "#ffcc00"); SET_C('C', "#ffff00"); } static void addHydroAmino(QVector& colorsPerChar) { //The most hydrophobic residues according to this table are colored red and the most hydrophilic ones are colored blue. SET_C('I', "#ff0000"); SET_C('V', "#f60009"); SET_C('L', "#ea0015"); SET_C('F', "#cb0034"); SET_C('C', "#c2003d"); SET_C('M', "#b0004f"); SET_C('A', "#ad0052"); SET_C('G', "#6a0095"); SET_C('X', "#680097"); SET_C('T', "#61009e"); SET_C('S', "#5e00a1"); SET_C('W', "#5b00a4"); SET_C('Y', "#4f00b0"); SET_C('P', "#4600b9"); SET_C('H', "#1500ea"); SET_C('E', "#0c00f3"); SET_C('Z', "#0c00f3"); SET_C('Q', "#0c00f3"); SET_C('D', "#0c00f3"); SET_C('B', "#0c00f3"); SET_C('N', "#0c00f3"); SET_C('K', "#0000ff"); SET_C('R', "#0000ff"); } static void addHelixAmino(QVector& colorsPerChar) { SET_C('E', "#ff00ff"); SET_C('M', "#ef10ef"); SET_C('A', "#e718e7"); SET_C('Z', "#c936c9"); SET_C('L', "#ae51ae"); SET_C('K', "#a05fa0"); SET_C('F', "#986798"); SET_C('Q', "#926d92"); SET_C('I', "#8a758a"); SET_C('W', "#8a758a"); SET_C('V', "#857a85"); SET_C('D', "#778877"); SET_C('X', "#758a75"); SET_C('H', "#758a75"); SET_C('R', "#6f906f"); SET_C('B', "#49b649"); SET_C('T', "#47b847"); SET_C('S', "#36c936"); SET_C('C', "#23dc23"); SET_C('Y', "#21de21"); SET_C('N', "#1be41b"); SET_C('G', "#00ff00"); SET_C('P', "#00ff00"); } static void addStrandAmino(QVector& colorsPerChar) { SET_C('V', "#ffff00"); SET_C('I', "#ecec13"); SET_C('Y', "#d3d32c"); SET_C('F', "#c2c23d"); SET_C('W', "#c0c03f"); SET_C('L', "#b2b24d"); SET_C('T', "#9d9d62"); SET_C('C', "#9d9d62"); SET_C('Q', "#8c8c73"); SET_C('M', "#82827d"); SET_C('X', "#797986"); SET_C('R', "#6b6b94"); SET_C('N', "#64649b"); SET_C('H', "#60609f"); SET_C('A', "#5858a7"); SET_C('S', "#4949b6"); SET_C('G', "#4949b6"); SET_C('Z', "#4747b8"); SET_C('K', "#4747b8"); SET_C('B', "#4343bc"); SET_C('P', "#2323dc"); SET_C('D', "#2121de"); SET_C('E', "#0000ff"); } static void addTurnAmino(QVector& colorsPerChar) { SET_C('N', "#ff0000"); SET_C('G', "#ff0000"); SET_C('P', "#f60909"); SET_C('B', "#f30c0c"); SET_C('D', "#e81717"); SET_C('S', "#e11e1e"); SET_C('C', "#a85757"); SET_C('Y', "#9d6262"); SET_C('K', "#7e8181"); SET_C('X', "#7c8383"); SET_C('Q', "#778888"); SET_C('W', "#738c8c"); SET_C('T', "#738c8c"); SET_C('R', "#708f8f"); SET_C('H', "#708f8f"); SET_C('Z', "#5ba4a4"); SET_C('E', "#3fc0c0"); SET_C('A', "#2cd3d3"); SET_C('F', "#1ee1e1"); SET_C('M', "#1ee1e1"); SET_C('L', "#1ce3e3"); SET_C('V', "#07f8f8"); SET_C('I', "#00ffff"); } static void addBuriedAmino(QVector& colorsPerChar) { SET_C('C', "#0000ff"); SET_C('I', "#0054ab"); SET_C('V', "#005fa0"); SET_C('L', "#007b84"); SET_C('F', "#008778"); SET_C('M', "#009768"); SET_C('G', "#009d62"); SET_C('A', "#00a35c"); SET_C('W', "#00a857"); SET_C('X', "#00b649"); SET_C('S', "#00d52a"); SET_C('H', "#00d52a"); SET_C('T', "#00db24"); SET_C('P', "#00e01f"); SET_C('Y', "#00e619"); SET_C('N', "#00eb14"); SET_C('B', "#00eb14"); SET_C('D', "#00eb14"); SET_C('Q', "#00f10e"); SET_C('Z', "#00f10e"); SET_C('E', "#00f10e"); SET_C('R', "#00fc03"); SET_C('K', "#00ff00"); } static void addJalviewNucl(QVector& colorsPerChar) { SET_C('A', "#64F73F"); SET_C('C', "#FFB340"); SET_C('G', "#EB413C"); SET_C('T', "#3C88EE"); SET_C('U', colorsPerChar['T'].lighter(105)); } //SET_C('', "#"); QString MSAColorScheme::EMPTY_NUCL = "COLOR_SCHEME_EMPTY_NUCL"; QString MSAColorScheme::UGENE_NUCL = "COLOR_SCHEME_UGENE_NUCL"; QString MSAColorScheme::JALVIEW_NUCL = "COLOR_SCHEME_JALVIEW_NUCL"; QString MSAColorScheme::IDENTPERC_NUCL = "COLOR_SCHEME_IDENTPERC_NUCL"; QString MSAColorScheme::EMPTY_AMINO = "COLOR_SCHEME_EMPTY_AMINO"; QString MSAColorScheme::UGENE_AMINO = "COLOR_SCHEME_UGENE_AMINO"; QString MSAColorScheme::ZAPPO_AMINO = "COLOR_SCHEME_ZAPPO_AMINO"; QString MSAColorScheme::TAILOR_AMINO = "COLOR_SCHEME_TAILOR_AMINO"; QString MSAColorScheme::HYDRO_AMINO = "COLOR_SCHEME_HYDRO_AMINO"; QString MSAColorScheme::HELIX_AMINO = "COLOR_SCHEME_HELIX_AMINO"; QString MSAColorScheme::STRAND_AMINO = "COLOR_SCHEME_STRAND_AMINO"; QString MSAColorScheme::TURN_AMINO = "COLOR_SCHEME_TURN_AMINO"; QString MSAColorScheme::BURIED_AMINO = "COLOR_SCHEME_BURIED_AMINO"; QString MSAColorScheme::IDENTPERC_AMINO = "COLOR_SCHEME_IDENTPERC_AMINO"; QString MSAColorScheme::CLUSTALX_AMINO = "COLOR_SCHEME_CLUSTALX_AMINO"; void MSAColorSchemeRegistry::initBuiltInSchemes() { QVector colorsPerChar; //nucleic fillEmptyCS(colorsPerChar); addMSAColorSchemeFactory(new MSAColorSchemeStaticFactory(this, MSAColorScheme::EMPTY_NUCL, tr("No colors"), DNAAlphabet_NUCL, colorsPerChar)); fillLightColorsCS(colorsPerChar); addUGENENucl(colorsPerChar); addMSAColorSchemeFactory(new MSAColorSchemeStaticFactory(this, MSAColorScheme::UGENE_NUCL, tr("UGENE"), DNAAlphabet_NUCL, colorsPerChar)); fillEmptyCS(colorsPerChar); addJalviewNucl(colorsPerChar); addMSAColorSchemeFactory(new MSAColorSchemeStaticFactory(this, MSAColorScheme::JALVIEW_NUCL, tr("Jalview"), DNAAlphabet_NUCL, colorsPerChar)); addMSAColorSchemeFactory(new MSAColorSchemePercIdentFactory(this, MSAColorScheme::IDENTPERC_NUCL, tr("Percentage Identity"), DNAAlphabet_NUCL)); //amino fillEmptyCS(colorsPerChar); addMSAColorSchemeFactory(new MSAColorSchemeStaticFactory(this, MSAColorScheme::EMPTY_AMINO, tr("No colors"), DNAAlphabet_AMINO, colorsPerChar)); fillLightColorsCS(colorsPerChar); addUGENEAmino(colorsPerChar); addMSAColorSchemeFactory(new MSAColorSchemeStaticFactory(this, MSAColorScheme::UGENE_AMINO, tr("UGENE"), DNAAlphabet_AMINO, colorsPerChar)); fillEmptyCS(colorsPerChar); addZappoAmino(colorsPerChar); addMSAColorSchemeFactory(new MSAColorSchemeStaticFactory(this, MSAColorScheme::ZAPPO_AMINO, tr("Zappo"), DNAAlphabet_AMINO, colorsPerChar)); fillEmptyCS(colorsPerChar); addTailorAmino(colorsPerChar); addMSAColorSchemeFactory(new MSAColorSchemeStaticFactory(this, MSAColorScheme::TAILOR_AMINO, tr("Tailor"), DNAAlphabet_AMINO, colorsPerChar)); fillEmptyCS(colorsPerChar); addHydroAmino(colorsPerChar); addMSAColorSchemeFactory(new MSAColorSchemeStaticFactory(this, MSAColorScheme::HYDRO_AMINO, tr("Hydrophobicity"), DNAAlphabet_AMINO, colorsPerChar)); fillEmptyCS(colorsPerChar); addHelixAmino(colorsPerChar); addMSAColorSchemeFactory(new MSAColorSchemeStaticFactory(this, MSAColorScheme::HELIX_AMINO, tr("Helix propensity"), DNAAlphabet_AMINO, colorsPerChar)); fillEmptyCS(colorsPerChar); addStrandAmino(colorsPerChar); addMSAColorSchemeFactory(new MSAColorSchemeStaticFactory(this, MSAColorScheme::STRAND_AMINO, tr("Strand propensity"), DNAAlphabet_AMINO, colorsPerChar)); fillEmptyCS(colorsPerChar); addTurnAmino(colorsPerChar); addMSAColorSchemeFactory(new MSAColorSchemeStaticFactory(this, MSAColorScheme::TURN_AMINO, tr("Turn propensity"), DNAAlphabet_AMINO, colorsPerChar)); fillEmptyCS(colorsPerChar); addBuriedAmino(colorsPerChar); addMSAColorSchemeFactory(new MSAColorSchemeStaticFactory(this, MSAColorScheme::BURIED_AMINO, tr("Buried index"), DNAAlphabet_AMINO, colorsPerChar)); addMSAColorSchemeFactory(new MSAColorSchemePercIdentFactory(this, MSAColorScheme::IDENTPERC_AMINO, tr("Percentage Identity"), DNAAlphabet_AMINO)); addMSAColorSchemeFactory(new MSAColorSchemeClustalXFactory(this, MSAColorScheme::CLUSTALX_AMINO, tr("Clustal X"), DNAAlphabet_AMINO)); } }//namespace ugene-1.9.8/src/corelibs/U2View/src/util_ov_msaedit/MSAEditorFactory.cpp0000644000175000017500000001113011651544334024627 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "MSAEditorFactory.h" #include "MSAEditor.h" #include "MSAEditorTasks.h" #include "MSAEditorState.h" #include #include #include #include #include #include namespace U2 { /* TRANSLATOR U2::MSAEditor */ /* TRANSLATOR U2::ObjectViewTask */ const GObjectViewFactoryId MSAEditorFactory::ID("MSAEditor"); MSAEditorFactory::MSAEditorFactory() : GObjectViewFactory(ID, tr("Alignment editor")) { } bool MSAEditorFactory::canCreateView(const MultiGSelection& multiSelection) { bool hasMSADocuments = !SelectionUtils::findDocumentsWithObjects( GObjectTypes::MULTIPLE_ALIGNMENT, &multiSelection, UOF_LoadedAndUnloaded, true).isEmpty(); if (hasMSADocuments) { return true; } return false; } #define MAX_VIEWS 10 Task* MSAEditorFactory::createViewTask(const MultiGSelection& multiSelection, bool single) { QList msaObjects = SelectionUtils::findObjects(GObjectTypes::MULTIPLE_ALIGNMENT, &multiSelection, UOF_LoadedAndUnloaded); QSet docsWithMSA = SelectionUtils::findDocumentsWithObjects(GObjectTypes::MULTIPLE_ALIGNMENT, &multiSelection, UOF_LoadedAndUnloaded, false); QList resTasks; foreach(Document* doc, docsWithMSA) { QList docObjs = doc->findGObjectByType(GObjectTypes::MULTIPLE_ALIGNMENT, UOF_LoadedAndUnloaded); if (!docObjs.isEmpty()) { foreach(GObject* obj, docObjs){ if(!msaObjects.contains(obj)){ msaObjects.append(obj); } } } else { resTasks.append(new OpenMSAEditorTask(doc)); if (resTasks.size() == MAX_VIEWS) { break; } } } if (!msaObjects.isEmpty()) { foreach(GObject* o, msaObjects) { if (resTasks.size() == MAX_VIEWS) { break; } if (o->getGObjectType() == GObjectTypes::UNLOADED) { resTasks.append(new OpenMSAEditorTask(qobject_cast(o))); } else { assert(o->getGObjectType() == GObjectTypes::MULTIPLE_ALIGNMENT); resTasks.append(new OpenMSAEditorTask(qobject_cast(o))); } } } if (resTasks.isEmpty()) { return NULL; } if (resTasks.size() == 1 || single) { return resTasks.first(); } Task* result = new Task(tr("Open multiple views"), TaskFlag_NoRun); foreach(Task* t, resTasks) { result->addSubTask(t); } return result; } bool MSAEditorFactory::isStateInSelection(const MultiGSelection& multiSelection, const QVariantMap& stateData) { MSAEditorState state(stateData); if (!state.isValid()) { return false; } GObjectReference ref = state.getMSAObjectRef(); Document* doc = AppContext::getProject()->findDocumentByURL(ref.docUrl); if (doc == NULL) { //todo: accept to use invalid state removal routines of ObjectViewTask ??? return false; } //check that document is in selection QList selectedDocs = SelectionUtils::getSelectedDocs(multiSelection); if (selectedDocs.contains(doc)) { return true; } //check that object is in selection QList selectedObjects = SelectionUtils::getSelectedObjects(multiSelection); GObject* obj = doc->findGObjectByName(ref.objName); bool res = obj!=NULL && selectedObjects.contains(obj); return res; } Task* MSAEditorFactory::createViewTask(const QString& viewName, const QVariantMap& stateData) { return new OpenSavedMSAEditorTask(viewName, stateData); } }//namespace ugene-1.9.8/src/corelibs/U2View/src/util_ov_msaedit/MSAEditorBaseOffsetsCache.h0000644000175000017500000000373211651544334026026 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_MSA_EDITOR_BASEOFFSET_CACHE_H_ #define _U2_MSA_EDITOR_BASEOFFSET_CACHE_H_ #include #include namespace U2 { class MAlignmentObject; class MAlignment; class MAlignmentModInfo; //TODO: optimize this cache example -> use sparse cache for 1 of 100 positions in every sequence class MSAEditorBaseOffsetCache : public QObject { Q_OBJECT public: MSAEditorBaseOffsetCache(QObject* p, MAlignmentObject* aliObj); int getBaseCounts(int seqNum, int aliPos, bool inclAliPos); MAlignmentObject* getMSAObject() const {return aliObj;} private slots: void sl_alignmentChanged(const MAlignment&, const MAlignmentModInfo&); private: void updateCacheSize(); void updateCacheRow(int seqNum); int _getBaseCounts(int seqNum, int aliPos, int& cachedEndPos); class RowCache { public: RowCache() : cacheVersion(0){} int cacheVersion; QVector rowOffsets; }; MAlignmentObject* aliObj; QVector cache; int objVersion; int globVersion; }; }//namespace; #endif ugene-1.9.8/src/corelibs/U2View/src/util_ov_msaedit/MSAEditorConsensusCache.h0000644000175000017500000000422211651544334025575 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_MSA_EDITOR_CONSENSUS_CACHE_H_ #define _U2_MSA_EDITOR_CONSENSUS_CACHE_H_ #include #include namespace U2 { class MAlignmentObject; class MAlignment; class MAlignmentModInfo; class MSAConsensusAlgorithm; class MSAConsensusAlgorithmFactory; class MSAEditorConsensusCache : public QObject { Q_OBJECT public: MSAEditorConsensusCache(QObject* p, MAlignmentObject* aliObj, MSAConsensusAlgorithmFactory* algo); ~MSAEditorConsensusCache(); char getConsensusChar(int pos); int getConsensusCharPercent(int pos); void setConsensusAlgorithm(MSAConsensusAlgorithmFactory* algo); MSAConsensusAlgorithm* getConsensusAlgorithm() const {return algorithm;} QByteArray getConsensusLine(bool withGaps); private slots: void sl_alignmentChanged(const MAlignment&, const MAlignmentModInfo&); void sl_thresholdChanged(int newValue); private: struct CacheItem { CacheItem(int v = 0, char c = '-', int tc = 0) : version(v), topChar(c), topPercent(tc){} int version; char topChar; char topPercent; }; void updateCacheItem(int pos); int currentVersion; QVector cache; MAlignmentObject* aliObj; MSAConsensusAlgorithm* algorithm; }; }//namespace; #endif ugene-1.9.8/src/corelibs/U2View/src/util_ov_msaedit/MSAEditorTasks.h0000644000175000017500000000373111651544334023762 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_MSA_EDITOR_TASKS_H_ #define _U2_MSA_EDITOR_TASKS_H_ #include #include namespace U2 { class MAlignmentObject; class UnloadedObject; class MSAEditor; class OpenMSAEditorTask : public ObjectViewTask { Q_OBJECT public: OpenMSAEditorTask(MAlignmentObject* obj); OpenMSAEditorTask(UnloadedObject* obj); OpenMSAEditorTask(Document* doc); virtual void open(); static void updateTitle(MSAEditor* msaEd); private: QPointer msaObject; GObjectReference unloadedReference; }; class OpenSavedMSAEditorTask : public ObjectViewTask { Q_OBJECT public: OpenSavedMSAEditorTask(const QString& viewName, const QVariantMap& stateData); virtual void open(); static void updateRanges(const QVariantMap& stateData, MSAEditor* ctx); static void addAnnotations(const QVariantMap& stateData, MSAEditor* ctx); }; class UpdateMSAEditorTask : public ObjectViewTask { public: UpdateMSAEditorTask(GObjectView* v, const QString& stateName, const QVariantMap& stateData); virtual void update(); }; } // namespace #endif ugene-1.9.8/src/corelibs/U2View/src/util_ov_msaedit/MSAEditorConsensusCache.cpp0000644000175000017500000000656411651544334026143 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "MSAEditorConsensusCache.h" #include #include namespace U2 { MSAEditorConsensusCache::MSAEditorConsensusCache(QObject* p, MAlignmentObject* o, MSAConsensusAlgorithmFactory* factory) : QObject(p), currentVersion(1), aliObj(o), algorithm(NULL) { setConsensusAlgorithm(factory); connect(aliObj, SIGNAL(si_alignmentChanged(const MAlignment&, const MAlignmentModInfo&)), SLOT(sl_alignmentChanged(const MAlignment&, const MAlignmentModInfo&))); cache.resize(aliObj->getMAlignment().getLength()); } MSAEditorConsensusCache::~MSAEditorConsensusCache() { delete algorithm; algorithm = NULL; } void MSAEditorConsensusCache::setConsensusAlgorithm(MSAConsensusAlgorithmFactory* factory) { delete algorithm; algorithm = NULL; algorithm = factory->createAlgorithm(aliObj->getMAlignment()); connect(algorithm, SIGNAL(si_thresholdChanged(int)), SLOT(sl_thresholdChanged(int))); currentVersion++; } void MSAEditorConsensusCache::sl_alignmentChanged(const MAlignment&, const MAlignmentModInfo&) { cache.resize(aliObj->getMAlignment().getLength()); currentVersion++; } void MSAEditorConsensusCache::updateCacheItem(int pos) { const MAlignment& ma = aliObj->getMAlignment(); assert(pos >= 0 && pos < ma.getLength()); assert(pos < cache.size() && cache.size() == ma.getLength()); const CacheItem& cci = cache[pos]; if (cci.version == currentVersion) { return; } CacheItem& ci = cache[pos]; int count = 0; int nSeq = ma.getNumRows(); ci.topChar = algorithm->getConsensusCharAndScore(ma, pos, count); ci.topPercent = (char)qRound(count * 100 / nSeq); assert(ci.topPercent >=0 && ci.topPercent<=100); ci.version = currentVersion; } char MSAEditorConsensusCache::getConsensusChar(int pos) { updateCacheItem(pos); const CacheItem& ci = cache[pos]; return ci.topChar; } int MSAEditorConsensusCache::getConsensusCharPercent(int pos) { updateCacheItem(pos); const CacheItem& ci = cache[pos]; return ci.topPercent; } QByteArray MSAEditorConsensusCache::getConsensusLine(bool withGaps) { QByteArray res; const MAlignment& ma = aliObj->getMAlignment(); for (int i=0, n = ma.getLength(); i * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_MSA_EDITOR_OFFSETS_VIEW_H_ #define _U2_MSA_EDITOR_OFFSETS_VIEW_H_ #include #include #include #include namespace U2 { class MSAEditor; class MAlignmentObject; class MAlignment; class MAlignmentModInfo; class MSAEditorSequenceArea; class MSAEditorBaseOffsetCache; class MSAEditorOffsetsViewWidget; class MSAEditorOffsetsViewController : public QObject { Q_OBJECT public: MSAEditorOffsetsViewController(QObject* p, MSAEditor* editor, MSAEditorSequenceArea* seqArea); MSAEditorOffsetsViewWidget* getLeftWidget() const {return lw;} MSAEditorOffsetsViewWidget* getRightWidget() const {return rw;} QAction* getToggleColumnsViewAction() const {return viewAction;} bool eventFilter(QObject* o, QEvent* e); private slots: void sl_alignmentChanged(const MAlignment&, const MAlignmentModInfo&){updateOffsets();} void sl_startChanged(const QPoint& , const QPoint& ) {updateOffsets();} void sl_fontChanged() {updateOffsets();} void sl_showOffsets(bool); private: void updateOffsets(); MSAEditorSequenceArea* seqArea; MSAEditor* editor; MSAEditorOffsetsViewWidget* lw; MSAEditorOffsetsViewWidget* rw; QAction* viewAction; }; class MSAEditorOffsetsViewWidget : public QWidget { friend class MSAEditorOffsetsViewController; public: MSAEditorOffsetsViewWidget(MSAEditor* editor, MSAEditorSequenceArea* seqArea, MSAEditorBaseOffsetCache* cache, bool showStartPos); ~MSAEditorOffsetsViewWidget(); protected: void paintEvent(QPaintEvent* e); void updateView(); void drawAll(QPainter& p); QFont getOffsetsFont(); private: MSAEditorSequenceArea* seqArea; MSAEditor* editor; MSAEditorBaseOffsetCache* cache; bool showStartPos; bool completeRedraw; QPixmap* cachedView; }; }//namespace; #endif ugene-1.9.8/src/corelibs/U2View/src/util_ov_msaedit/MSAEditorNameList.cpp0000644000175000017500000004335211651544334024747 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "MSAEditorNameList.h" #include "MSAEditor.h" #include "MSAEditorSequenceArea.h" #include #include #include #include #include #include #include #include namespace U2 { MSAEditorNameList::MSAEditorNameList(MSAEditorUI* _ui, QScrollBar* _nhBar) : editor(_ui->editor), ui(_ui), nhBar(_nhBar) { setFocusPolicy(Qt::WheelFocus); cachedView = new QPixmap(); completeRedraw = true; scribbling = false; shifting = false; curSeq = -1; rubberBand = new QRubberBand(QRubberBand::Rectangle, this); connect(editor, SIGNAL(si_buildStaticMenu(GObjectView*, QMenu*)), SLOT(sl_buildStaticMenu(GObjectView*, QMenu*))); editSequenceNameAction = new QAction(tr("Edit sequence name"), this); connect(editSequenceNameAction, SIGNAL(triggered()), SLOT(sl_editSequenceName())); copyCurrentSequenceAction = new QAction(tr("Copy current sequence"), this); connect(copyCurrentSequenceAction, SIGNAL(triggered()), SLOT(sl_copyCurrentSequence())); removeCurrentSequenceAction = new QAction("Remove current sequence", this); connect(removeCurrentSequenceAction, SIGNAL(triggered()), SLOT(sl_removeCurrentSequence())); connect(editor, SIGNAL(si_buildPopupMenu(GObjectView* , QMenu*)), SLOT(sl_buildContextMenu(GObjectView*, QMenu*))); if (editor->getMSAObject()) { connect(editor->getMSAObject(), SIGNAL(si_alignmentChanged(const MAlignment&, const MAlignmentModInfo&)), SLOT(sl_alignmentChanged(const MAlignment&, const MAlignmentModInfo&))); connect(editor->getMSAObject(), SIGNAL(si_lockedStateChanged()), SLOT(sl_lockedStateChanged())); } if (ui->seqArea) { connect(ui->seqArea, SIGNAL(si_startChanged(const QPoint& , const QPoint& )), SLOT(sl_startChanged(const QPoint& , const QPoint&))); connect(ui->seqArea, SIGNAL(si_selectionChanged(const MSAEditorSelection&, const MSAEditorSelection&)), SLOT(sl_selectionChanged(const MSAEditorSelection& , const MSAEditorSelection& ))); connect(ui->editor, SIGNAL(si_fontChanged(const QFont&)), SLOT(sl_fontChanged())); connect(ui->seqArea->getVBar(), SIGNAL(actionTriggered(int)), SLOT(sl_onScrollBarActionTriggered(int))); } nhBar->setEnabled(false); updateActions(); } MSAEditorNameList::~MSAEditorNameList() { delete cachedView; } void MSAEditorNameList::updateActions() { copyCurrentSequenceAction->setEnabled(true); MAlignmentObject* maObj = editor->getMSAObject(); if (maObj){ removeCurrentSequenceAction->setEnabled(!maObj->isStateLocked() && maObj->getMAlignment().getNumRows() > 1); editSequenceNameAction->setEnabled(!maObj->isStateLocked()); } } #define MARGIN_TEXT_LEFT 5 #define MARGIN_TEXT_TOP 2 #define MARGIN_TEXT_BOTTOM 2 void MSAEditorNameList::updateScrollBar() { nhBar->disconnect(this); QFont f = ui->editor->getFont(); f.setItalic(true); QFontMetrics fm(f); int maxNameWidth = 0; MAlignmentObject* maObj = editor->getMSAObject(); foreach(const MAlignmentRow& row, maObj->getMAlignment().getRows()) { maxNameWidth = qMax(fm.width(row.getName()), maxNameWidth); } int availableWidth = width() - MARGIN_TEXT_LEFT; int nSteps = 1; int stepSize = fm.width('W'); if (availableWidth < maxNameWidth) { int dw = maxNameWidth - availableWidth; nSteps += dw / stepSize + (dw % stepSize != 0 ? 1 : 0); } nhBar->setMinimum(0); nhBar->setMaximum(nSteps - 1); nhBar->setValue(0); nhBar->setEnabled(nSteps > 1); connect(nhBar, SIGNAL(valueChanged(int)), SLOT(sl_nameBarMoved(int))); } void MSAEditorNameList::sl_buildStaticMenu(GObjectView* v, QMenu* m) { Q_UNUSED(v); buildMenu(m); } void MSAEditorNameList::sl_buildContextMenu(GObjectView* v, QMenu* m) { Q_UNUSED(v); buildMenu(m); } void MSAEditorNameList::buildMenu(QMenu* m) { if ( !rect().contains( mapFromGlobal(QCursor::pos()) ) ) { return; } QMenu* copyMenu = GUIUtils::findSubMenu(m, MSAE_MENU_COPY); assert(copyMenu!=NULL); copyMenu->addAction(copyCurrentSequenceAction); QMenu* editMenu = GUIUtils::findSubMenu(m, MSAE_MENU_EDIT); assert(editMenu!=NULL); editMenu->addAction(removeCurrentSequenceAction); editMenu->insertAction(editMenu->actions().first(), editSequenceNameAction); } void MSAEditorNameList::sl_copyCurrentSequence() { const MSAEditorSelection& selection = ui->seqArea->getSelection(); if (selection.height() == 0) { return; } int n = selection.y(); MAlignmentObject* maObj = editor->getMSAObject(); if (maObj) { const MAlignmentRow& row = maObj->getMAlignment().getRow(n); //TODO: trim large sequence? QApplication::clipboard()->setText(row.toByteArray(maObj->getLength())); } } void MSAEditorNameList::sl_alignmentChanged(const MAlignment&, const MAlignmentModInfo& mi) { if (mi.sequenceListChanged) { completeRedraw = true; updateScrollBar(); update(); } } void MSAEditorNameList::sl_nameBarMoved(int) { completeRedraw = true; update(); } void MSAEditorNameList::sl_removeCurrentSequence() { const MSAEditorSelection& selection = ui->seqArea->getSelection(); if (selection.height() == 0) { return; } int n = selection.y(); MAlignmentObject* maObj = editor->getMSAObject(); if (maObj) { assert(!maObj->isStateLocked()); maObj->removeRow(n); //MAlignment ma = maObj->getMAlignment(); //assert(ma.getNumSequences() > 1); //ma.alignedSeqs.removeAt(n); //maObj->setMAlignment(ma); } } void MSAEditorNameList::sl_lockedStateChanged() { updateActions(); } void MSAEditorNameList::resizeEvent(QResizeEvent* e) { completeRedraw = true; updateScrollBar(); QWidget::resizeEvent(e); } void MSAEditorNameList::paintEvent(QPaintEvent*) { drawAll(); } void MSAEditorNameList::keyPressEvent (QKeyEvent *e) { int key = e->key(); switch(key) { case Qt::Key_Delete: ui->seqArea->deleteCurrentSelection(); break; case Qt::Key_Up: ui->seqArea->moveSelection(0, -1); break; case Qt::Key_Down: ui->seqArea->moveSelection(0, 1); break; case Qt::Key_Left: nhBar->triggerAction(QAbstractSlider::SliderSingleStepSub); break; case Qt::Key_Right: nhBar->triggerAction(QAbstractSlider::SliderSingleStepAdd); break; case Qt::Key_Home: ui->seqArea->setFirstVisibleSequence(0); ui->seqArea->cancelSelection(); //TODO: select first sequence? break; case Qt::Key_End: { int s = editor->getNumSequences() - 1; ui->seqArea->setFirstVisibleSequence(s); ui->seqArea->cancelSelection(); //TODO: select last sequence? } break; case Qt::Key_PageUp: { int nVis = ui->seqArea->getNumVisibleSequences(false); int fp = qMax(0, ui->seqArea->getFirstVisibleSequence() - nVis); //int cp = qMax(0, ui->seqArea->getCursorPos().y() - nVis); ui->seqArea->setFirstVisibleSequence(fp); ui->seqArea->cancelSelection(); } break; case Qt::Key_PageDown: { int nVis = ui->seqArea->getNumVisibleSequences(false); int nSeq = editor->getNumSequences(); int fp = qMin(nSeq-1, ui->seqArea->getFirstVisibleSequence() + nVis); //int cp = qMin(nSeq-1, ui->seqArea->getCursorPos().y() + nVis); ui->seqArea->setFirstVisibleSequence(fp); ui->seqArea->cancelSelection(); } break; } QWidget::keyPressEvent(e); } void MSAEditorNameList::mousePressEvent(QMouseEvent *e) { if ((e->button() == Qt::LeftButton)){ origin = e->pos(); curSeq = ui->seqArea->getSequenceNumByY(e->y()); MSAEditorSelection s = ui->seqArea->getSelection(); if ( s.getRect().contains(0,curSeq) ){ shifting = true; } else { rubberBand->setGeometry(QRect(origin, QSize())); rubberBand->show(); ui->seqArea->cancelSelection(); } if ( ui->seqArea->isSeqInRange(curSeq) ) { scribbling = true; } } QWidget::mousePressEvent(e); } void MSAEditorNameList::mouseMoveEvent( QMouseEvent* e ) { if ( (e->buttons() & Qt::LeftButton) && scribbling ) { int newSeqNum = ui->seqArea->getSequenceNumByY(e->pos().y()); if (ui->seqArea->isSeqInRange(newSeqNum)) { ui->seqArea->updateVBarPosition(newSeqNum); } if (shifting) { moveSelectedRegion(newSeqNum - curSeq); } else { rubberBand->setGeometry(QRect(origin, e->pos()).normalized()); } } QWidget::mouseMoveEvent(e); } void MSAEditorNameList::mouseReleaseEvent( QMouseEvent *e ) { rubberBand->hide(); if (scribbling) { int newSeq = ui->seqArea->getSequenceNumByY(e->y()); if (!ui->seqArea->isSeqInRange(newSeq) ) { if (e->y() < origin.y()) { newSeq = 0; } else { newSeq = ui->editor->getNumSequences() - 1; } } if (e->pos() == origin) { // special case: click but don't drag shifting = false; } if (shifting) { int shift = 0; int numSeq = ui->editor->getNumSequences(); int selectionStart = ui->seqArea->getSelection().y(); int selectionSize = ui->seqArea->getSelection().height(); if (newSeq == 0) { shift = -selectionStart; } else if (newSeq == numSeq - 1) { shift = numSeq - (selectionStart + selectionSize); } else { shift = newSeq - curSeq; } moveSelectedRegion(shift); shifting = false; } else { updateSelection(newSeq); } scribbling = false; } ui->seqArea->getVBar()->setupRepeatAction(QAbstractSlider::SliderNoAction); QWidget::mouseReleaseEvent(e); } void MSAEditorNameList::updateSelection( int newSeq ) { if (newSeq != -1) { int startSeq = qMin(curSeq,newSeq); int width = editor->getAlignmentLen(); int height = qAbs(newSeq - curSeq) + 1; MSAEditorSelection selection(0, startSeq, width, height ); ui->seqArea->setSelection(selection); } } void MSAEditorNameList::wheelEvent (QWheelEvent * we) { bool toMin = we->delta() > 0; ui->seqArea->getVBar()->triggerAction(toMin ? QAbstractSlider::SliderSingleStepSub : QAbstractSlider::SliderSingleStepAdd); QWidget::wheelEvent(we); } void MSAEditorNameList::sl_startChanged(const QPoint& p, const QPoint& prev) { if (p.y() == prev.y()) { return; } completeRedraw = true; update(); } void MSAEditorNameList::sl_selectionChanged( const MSAEditorSelection& current, const MSAEditorSelection& prev ) { Q_UNUSED(current); Q_UNUSED(prev); if (current.y() == prev.y() && current.height() == prev.height() ) { return; } completeRedraw = true; update(); } void MSAEditorNameList::focusInEvent(QFocusEvent* fe) { QWidget::focusInEvent(fe); update(); } void MSAEditorNameList::focusOutEvent(QFocusEvent* fe) { QWidget::focusOutEvent(fe); update(); } void MSAEditorNameList::sl_fontChanged() { completeRedraw = true; updateScrollBar(); update(); } ////////////////////////////////////////////////////////////////////////// // draw methods void MSAEditorNameList::drawAll() { QSize s = size(); if (cachedView->size() != s) { assert(completeRedraw); delete cachedView; cachedView = new QPixmap(s); } if (completeRedraw) { QPainter pCached(cachedView); drawContent(pCached); completeRedraw = false; } QPainter p(this); p.drawPixmap(0, 0, *cachedView); drawSelection(p); //drawFocus(p); } void MSAEditorNameList::drawContent(QPainter& p) { p.fillRect(cachedView->rect(), Qt::white); int startSeq = ui->seqArea->getFirstVisibleSequence(); int lastSeq = ui->seqArea->getLastVisibleSequence(true); for (int s = startSeq; s <= lastSeq; s++) { bool isSelected = isRowInSelection(s); drawSequenceItem(p, s, isSelected); } } void MSAEditorNameList::drawSequenceItem(QPainter& p, int s, bool selected) { QFont f = ui->editor->getFont(); f.setItalic(true); if (selected) { f.setBold(true); } p.setFont(f); QFontMetrics fm(f); int w = width(); U2Region yRange = ui->seqArea->getSequenceYRange(s, true); QRect itemRect(0, yRange.startPos, w-1, yRange.length-1); int textX = MARGIN_TEXT_LEFT; int textW = w - MARGIN_TEXT_LEFT; int textY = yRange.startPos + MARGIN_TEXT_TOP; int textH = yRange.length - MARGIN_TEXT_TOP - MARGIN_TEXT_BOTTOM; MAlignmentObject* maObj = editor->getMSAObject(); if (maObj == NULL) return; const MAlignment& ma = maObj->getMAlignment(); const MAlignmentRow& row = ma.getRow(s); QRect textRect(textX, textY, textW, textH); if (nhBar->isEnabled()) { int stepSize = fm.width('W'); int dx = stepSize * nhBar->value(); textRect = textRect.adjusted(-dx, 0, 0, 0); } p.setPen(Qt::black); p.drawText(textRect, Qt::AlignVCenter | Qt::AlignLeft, row.getName()); } void MSAEditorNameList::drawSelection(QPainter& p) { MSAEditorSelection sel = ui->seqArea->getSelection(); if ((sel.height() == editor->getNumSequences()) || (sel.height() == 0)) { return; } int startPos = sel.y(); int w = width(); U2Region yRange = ui->seqArea->getSequenceYRange(startPos, true); QRect itemsRect(0, yRange.startPos, w - 1, sel.height()*yRange.length -1 ); p.setPen(QPen(Qt::gray, 1, Qt::DashLine)); p.drawRect(itemsRect); } void MSAEditorNameList::drawFocus(QPainter& p) { if (hasFocus()) { p.setPen(QPen(Qt::black, 1, Qt::DotLine)); p.drawRect(0, 0, width()-1, height()-1); } } void MSAEditorNameList::sl_onScrollBarActionTriggered( int scrollAction ) { if (scrollAction == QAbstractSlider::SliderSingleStepAdd || scrollAction == QAbstractSlider::SliderSingleStepSub) { if (scribbling) { // TODO: sync origin point /*int y = origin.y(); int step = ui->seqArea->getVBar()->singleStep(); if (scrollAction == QAbstractSlider::SliderSingleStepAdd) { origin.setY(y - step); } else { origin.setY(y + step); }*/ } } } void MSAEditorNameList::sl_editSequenceName() { const MSAEditorSelection& selection = ui->seqArea->getSelection(); if (selection.height() == 0) { return; } MAlignmentObject* maObj = editor->getMSAObject(); if (maObj->isStateLocked()) { return; } int seqIdx = selection.y(); bool ok = false; const MAlignmentRow& row = maObj->getMAlignment().getRow(curSeq); QString curName = row.getName(); QString newName = QInputDialog::getText(this, tr("Rename"), tr("New sequence name:"), QLineEdit::Normal, curName, &ok); if (ok && !newName.isEmpty()) { maObj->renameRow(seqIdx,newName); } } void MSAEditorNameList::mouseDoubleClickEvent( QMouseEvent *e ) { Q_UNUSED(e); sl_editSequenceName(); } void MSAEditorNameList::moveSelectedRegion( int shift ) { if (shift == 0) { return; } int numRowsInSelection = ui->seqArea->getSelection().height(); int firstRowInSelection = ui->seqArea->getSelection().y(); int lastRowInSelection = firstRowInSelection + numRowsInSelection - 1; // "out-of-range" checks if ( (shift > 0 && lastRowInSelection + shift >= editor->getNumSequences() ) || (shift < 0 && firstRowInSelection + shift < 0 ) || (shift < 0 && firstRowInSelection + qAbs(shift) > editor->getNumSequences()) ) { return; } MAlignmentObject* maObj = editor->getMSAObject(); if ( !maObj->isStateLocked() ) { maObj->moveRowsBlock(firstRowInSelection, numRowsInSelection, shift); curSeq += shift; int selectionStart = firstRowInSelection + shift; MSAEditorSelection selection(0, selectionStart, editor->getAlignmentLen(), numRowsInSelection ); ui->seqArea->setSelection(selection); } } bool MSAEditorNameList::isRowInSelection( int seqnum ) { MSAEditorSelection s = ui->seqArea->getSelection(); int endPos = s.y() + s.height() - 1; return seqnum >= s.y() && seqnum <= endPos; } }//namespace ugene-1.9.8/src/corelibs/U2View/src/util_ov_msaedit/MSAEditorOffsetsView.cpp0000644000175000017500000001477111651544334025502 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "MSAEditorOffsetsView.h" #include "MSAEditorBaseOffsetsCache.h" #include "MSAEditorSequenceArea.h" #include "MSAEditor.h" #include #include #include #include #include namespace U2 { #define SETTINGS_ROOT QString("msaeditor/") #define SETTINGS_SHOW_OFFSETS "show_offsets" #define MIN_LENGTH_TO_SHOW_OFFSETS 3000 MSAEditorOffsetsViewController::MSAEditorOffsetsViewController(QObject* p, MSAEditor* ed, MSAEditorSequenceArea* sa) : QObject(p) { seqArea = sa; editor = ed; MAlignmentObject *mobj = editor->getMSAObject(); assert(mobj); MSAEditorBaseOffsetCache* cache = new MSAEditorBaseOffsetCache(this, mobj); lw = new MSAEditorOffsetsViewWidget(ed, seqArea, cache, true); rw = new MSAEditorOffsetsViewWidget(ed, seqArea, cache, false); connect(seqArea, SIGNAL(si_startChanged(const QPoint&,const QPoint&)), SLOT(sl_startChanged(const QPoint&,const QPoint&))); connect(editor, SIGNAL(si_fontChanged(const QFont&)), SLOT(sl_fontChanged())); connect(mobj, SIGNAL(si_alignmentChanged(const MAlignment&, const MAlignmentModInfo&)), SLOT(sl_alignmentChanged(const MAlignment&, const MAlignmentModInfo&))); sa->installEventFilter(this); Settings* s = AppContext::getSettings(); bool showOffsets = s->getValue(SETTINGS_ROOT + SETTINGS_SHOW_OFFSETS, true).toBool(); viewAction = new QAction(tr("Show offsets"), this); viewAction->setCheckable(true); viewAction->setChecked(showOffsets); connect(viewAction, SIGNAL(triggered(bool)), SLOT(sl_showOffsets(bool))); updateOffsets(); } bool MSAEditorOffsetsViewController::eventFilter(QObject* o, QEvent* e) { if (o == seqArea) { if (e->type() == QEvent::Resize || e->type() == QEvent::Show) { updateOffsets(); } } return false; } void MSAEditorOffsetsViewController::sl_showOffsets(bool show) { updateOffsets(); Settings* s = AppContext::getSettings(); s->setValue(SETTINGS_ROOT + SETTINGS_SHOW_OFFSETS, show); } void MSAEditorOffsetsViewController::updateOffsets() { bool enableOffsets = editor->getAlignmentLen() < MIN_LENGTH_TO_SHOW_OFFSETS; viewAction->setEnabled(enableOffsets); if (lw->parentWidget()!=NULL) { bool vis = viewAction->isChecked() & enableOffsets; lw->setVisible(vis); rw->setVisible(vis); } lw->updateView(); rw->updateView(); } MSAEditorOffsetsViewWidget::MSAEditorOffsetsViewWidget(MSAEditor *ed, MSAEditorSequenceArea* sa, MSAEditorBaseOffsetCache* c, bool sp) :seqArea(sa), editor(ed), cache(c), showStartPos(sp), completeRedraw(true) { cachedView = new QPixmap(); } MSAEditorOffsetsViewWidget::~MSAEditorOffsetsViewWidget() { delete cachedView; } #define OFFS_WIDGET_BORDER 3 void MSAEditorOffsetsViewWidget::updateView() { int aliLen = cache->getMSAObject()->getMAlignment().getLength(); QFont f = getOffsetsFont(); QFontMetrics fm(f); int aliLenStrLen = int(log10((double)aliLen)) + 1; int w = OFFS_WIDGET_BORDER + fm.width('X') * aliLenStrLen + OFFS_WIDGET_BORDER; w += (showStartPos ? fm.width('[') : fm.width(']')); setFixedWidth(w); completeRedraw = true; update(); } void MSAEditorOffsetsViewWidget::paintEvent(QPaintEvent*) { assert(isVisible()); QSize s = size(); if (s != cachedView->size()) { delete cachedView; cachedView = new QPixmap(s); completeRedraw = true; } if (completeRedraw) { QPainter pCached(cachedView); drawAll(pCached); completeRedraw = false; } QPainter p(this); p.drawPixmap(0, 0, *cachedView); } QFont MSAEditorOffsetsViewWidget::getOffsetsFont() { QFont f = editor->getFont(); f.setPointSize(qMax(f.pointSize()-1, 6)); return f; } void MSAEditorOffsetsViewWidget::drawAll(QPainter& p) { QLinearGradient gradient(0, 0, width(), 0); QColor lg(0xDA, 0xDA, 0xDA); QColor dg(0x4A, 0x4A, 0x4A); gradient.setColorAt(0.00, lg); gradient.setColorAt(0.25, Qt::white); gradient.setColorAt(0.75, Qt::white); gradient.setColorAt(1.00, lg); p.fillRect(rect(), QBrush(gradient)); int w = width(); QFont f = getOffsetsFont(); QFontMetrics fm(f); p.setFont(f); int nSeqVisible = seqArea->getNumVisibleSequences(true); int startSeq = seqArea->getFirstVisibleSequence(); int aliLen = cache->getMSAObject()->getMAlignment().getLength(); int lbw = fm.width('['); int rbw = fm.width(']'); int pos = showStartPos ? seqArea->getFirstVisibleBase() : seqArea->getLastVisibleBase(true, true); for(int i=0; i< nSeqVisible; i++) { U2Region yRange = seqArea->getSequenceYRange(startSeq + i, true); int offs = cache->getBaseCounts(startSeq + i, pos, !showStartPos); int seqSize = cache->getBaseCounts(startSeq + i, aliLen - 1, true); QString offset = QString::number(offs+1); if (showStartPos && offs == 0) { p.setPen(Qt::black); QRect lbr(OFFS_WIDGET_BORDER, yRange.startPos, lbw, yRange.length); p.drawText(lbr, Qt::AlignCenter, "["); } else if (!showStartPos && offs == seqSize) { p.setPen(Qt::black); QRect rbr(w - OFFS_WIDGET_BORDER - rbw, yRange.startPos, rbw, yRange.length); p.drawText(rbr, Qt::AlignCenter, "]"); offset = QString::number(offs); } else { p.setPen(dg); } QRect tr(OFFS_WIDGET_BORDER + (showStartPos ? lbw : 0), yRange.startPos, w - 2 * OFFS_WIDGET_BORDER - (showStartPos ? lbw : rbw), yRange.length); p.drawText(tr, Qt::AlignRight | Qt::AlignVCenter, offset); } } }//namespace ugene-1.9.8/src/corelibs/U2View/src/util_ov_msaedit/MSAEditorTasks.cpp0000644000175000017500000001474511651544334024324 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "MSAEditorTasks.h" #include "MSAEditor.h" #include "MSAEditorFactory.h" #include "MSAEditorState.h" #include #include #include #include #include #include #include #include #include namespace U2 { /* TRANSLATOR U2::MSAEditor */ /* TRANSLATOR U2::ObjectViewTask */ ////////////////////////////////////////////////////////////////////////// /// open new view OpenMSAEditorTask::OpenMSAEditorTask(MAlignmentObject* _obj) : ObjectViewTask(MSAEditorFactory::ID), msaObject(_obj) { assert(!msaObject.isNull()); } OpenMSAEditorTask::OpenMSAEditorTask(UnloadedObject* _obj) : ObjectViewTask(MSAEditorFactory::ID), unloadedReference(_obj) { assert(_obj->getLoadedObjectType() == GObjectTypes::MULTIPLE_ALIGNMENT); documentsToLoad.append(_obj->getDocument()); } OpenMSAEditorTask::OpenMSAEditorTask(Document* doc) : ObjectViewTask(MSAEditorFactory::ID), msaObject(NULL) { assert(!doc->isLoaded()); documentsToLoad.append(doc); } void OpenMSAEditorTask::open() { if (stateInfo.hasError() || (msaObject.isNull() && documentsToLoad.isEmpty())) { return; } if (msaObject.isNull()) { Document* doc = documentsToLoad.first(); QList objects; if (unloadedReference.isValid()) { GObject* obj = doc->findGObjectByName(unloadedReference.objName); if (obj!=NULL && obj->getGObjectType() == GObjectTypes::MULTIPLE_ALIGNMENT) { msaObject = qobject_cast(obj); } } else { QList objects = doc->findGObjectByType(GObjectTypes::MULTIPLE_ALIGNMENT, UOF_LoadedAndUnloaded); msaObject = objects.isEmpty() ? NULL : qobject_cast(objects.first()); } if (msaObject.isNull()) { stateInfo.setError(tr("Multiple alignment object not found")); return; } } viewName = GObjectViewUtils::genUniqueViewName(msaObject->getDocument(), msaObject); uiLog.details(tr("Opening MSA editor for object: %1").arg(msaObject->getGObjectName())); MSAEditor* v = new MSAEditor(viewName, msaObject); GObjectViewWindow* w = new GObjectViewWindow(v, viewName, false); MWMDIManager* mdiManager = AppContext::getMainWindow()->getMDIManager(); mdiManager->addMDIWindow(w); } void OpenMSAEditorTask::updateTitle(MSAEditor* msaEd) { const QString& oldViewName = msaEd->getName(); GObjectViewWindow* w = GObjectViewUtils::findViewByName(oldViewName); if (w != NULL) { MAlignmentObject* msaObject = msaEd->getMSAObject(); QString newViewName = GObjectViewUtils::genUniqueViewName(msaObject->getDocument(), msaObject); msaEd->setName(newViewName); w->setWindowTitle(newViewName); } } ////////////////////////////////////////////////////////////////////////// // open view from state OpenSavedMSAEditorTask::OpenSavedMSAEditorTask(const QString& viewName, const QVariantMap& stateData) : ObjectViewTask(MSAEditorFactory::ID, viewName, stateData) { MSAEditorState state(stateData); GObjectReference ref = state.getMSAObjectRef(); Document* doc = AppContext::getProject()->findDocumentByURL(ref.docUrl); if (doc == NULL) { doc = createDocumentAndAddToProject(ref.docUrl, AppContext::getProject()); if (!doc) { stateIsIllegal = true; stateInfo.setError(L10N::errorDocumentNotFound(ref.docUrl)); return; } } if (!doc->isLoaded()) { documentsToLoad.append(doc); } } void OpenSavedMSAEditorTask::open() { if (stateInfo.hasError()) { return; } MSAEditorState state(stateData); GObjectReference ref = state.getMSAObjectRef(); Document* doc = AppContext::getProject()->findDocumentByURL(ref.docUrl); if (doc == NULL) { stateIsIllegal = true; stateInfo.setError(L10N::errorDocumentNotFound(ref.docUrl)); return; } GObject* obj = doc->findGObjectByName(ref.objName); if (obj == NULL || obj->getGObjectType() != GObjectTypes::MULTIPLE_ALIGNMENT) { stateIsIllegal = true; stateInfo.setError(tr("Alignment object not found: %1").arg(ref.objName)); return; } MAlignmentObject* msaObject = qobject_cast(obj); assert(msaObject!=NULL); MSAEditor* v = new MSAEditor(viewName, msaObject); GObjectViewWindow* w = new GObjectViewWindow(v, viewName, true); MWMDIManager* mdiManager = AppContext::getMainWindow()->getMDIManager(); mdiManager->addMDIWindow(w); updateRanges(stateData, v); } void OpenSavedMSAEditorTask::updateRanges(const QVariantMap& stateData, MSAEditor* ctx) { Q_UNUSED(ctx); MSAEditorState state(stateData); QFont f = state.getFont(); if (!f.isCopyOf(QFont())) { ctx->setFont(f); } int firstPos = state.getFirstPos(); ctx->setFirstVisibleBase(firstPos); float zoomFactor = state.getZoomFactor(); ctx->setZoomFactor(zoomFactor); } ////////////////////////////////////////////////////////////////////////// // update UpdateMSAEditorTask::UpdateMSAEditorTask(GObjectView* v, const QString& stateName, const QVariantMap& stateData) : ObjectViewTask(v, stateName, stateData) { } void UpdateMSAEditorTask::update() { if (view.isNull() || view->getFactoryId() != MSAEditorFactory::ID) { return; //view was closed; } MSAEditor* msaView = qobject_cast(view.data()); assert(msaView!=NULL); OpenSavedMSAEditorTask::updateRanges(stateData, msaView); } } // namespace ugene-1.9.8/src/corelibs/U2View/src/util_ov_msaedit/MSAEditorSequenceArea.h0000644000175000017500000002102711651544334025234 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_MSA_EDITOR_SEQUENCE_AREA_H_ #define _U2_MSA_EDITOR_SEQUENCE_AREA_H_ #include "DeleteGapsDialog.h" #include #include #include #include #include #include namespace U2 { class MSAEditor; class MSAEditorUI; class GObjectView; class MSAColorScheme; class MAlignment; class MAlignmentModInfo; class U2VIEW_EXPORT MSAEditorSelection { public: MSAEditorSelection() { } MSAEditorSelection(int left, int top, int width, int height) : selArea(left,top,width,height) { } MSAEditorSelection(const QPoint& topLeft, const QPoint& bottomRight) : selArea(topLeft, bottomRight) { } MSAEditorSelection(const QPoint& topLeft, int width, int height) : selArea(topLeft, QSize(width,height)) { } // consider that selection may consist of several unconnected areas bool isContiniuous() const { return true; } bool isNull() const {return selArea.isNull(); } QPoint topLeft() const { return selArea.topLeft(); } const QRect& getRect() const {return selArea; } int x() const { return selArea.x(); } int y() const { return selArea.y(); } int width() const { return selArea.width(); } int height() const { return selArea.height(); } bool operator==(const MSAEditorSelection& other) const { return selArea == other.selArea; } MSAEditorSelection translated (int dx, int dy) const; MSAEditorSelection intersected (const MSAEditorSelection& selection) const { QRect r = selArea.intersected(selection.selArea); return MSAEditorSelection(r); } private: explicit MSAEditorSelection(QRect& rect) : selArea(rect) { } QRect selArea; }; class U2VIEW_EXPORT MSAEditorSequenceArea : public QWidget { Q_OBJECT public: MSAEditorSequenceArea(MSAEditorUI* ui, GScrollBar* hb, GScrollBar* vb); ~MSAEditorSequenceArea(); // x dimension -> positions int countWidthForBases(bool countClipped, bool forOffset = false) const; int getFirstVisibleBase() const {return startPos;} int getLastVisibleBase(bool countClipped, bool forOffset = false) const; int getNumVisibleBases(bool countClipped, bool forOffset = false) const; U2Region getBaseXRange(int pos, bool useVirtualCoords) const; int getColumnNumByX(int x) const; void setFirstVisibleBase(int pos); // y dimension -> sequences int countHeightForSequences(bool countClipped) const; int getFirstVisibleSequence() const {return startSeq;} int getLastVisibleSequence(bool countClipped) const; int getNumVisibleSequences(bool countClipped) const; U2Region getSequenceYRange(int seqNum, bool useVirtualCoords) const; int getSequenceNumByY(int y) const; void setFirstVisibleSequence(int seq); bool isPosInRange(int p) const; bool isSeqInRange(int s) const; bool isInRange(const QPoint& p) const {return isPosInRange(p.x()) && isSeqInRange(p.y());} bool isVisible(const QPoint& p, bool countClipped) const {return isPosVisible(p.x(), countClipped) && isSeqVisible(p.y(), countClipped);} bool isPosVisible(int pos, bool countClipped) const; bool isSeqVisible(int seq, bool countClipped) const; int coordToPos(int x) const; // returns valid position only for visible area QPoint coordToPos(const QPoint& coord) const; // returns valid position if coords are out of visible area QPoint coordToAbsolutePos(const QPoint& coord) const; const MSAEditorSelection& getSelection() const { assert(checkState()); return selection; } void updateSelection(const QPoint& newMousePos); void setSelection(const MSAEditorSelection& sel); void moveSelection(int dx, int dy); void cancelSelection(); void highlightCurrentSelection() { highlightSelection = true; update(); } void deleteCurrentSelection(); private: const QPoint& getCursorPos() const {assert(checkState()); return cursorPos;} void setCursorPos(const QPoint& p); void setCursorPos(int x, int y) { setCursorPos(QPoint(x, y)); }; void setCursorPos(int pos) { setCursorPos(QPoint(pos, cursorPos.y())); } void moveCursor(int dx, int dy); void highlightCurrentCursorPos() { highlightSelection = true; update();} public: void centerPos(const QPoint& pos); void centerPos(int pos); void setFont(const QFont& f); GScrollBar* getVBar() const {return svBar;} GScrollBar* getHBar() const {return shBar;} void updateHBarPosition(int base); void updateVBarPosition(int seq); signals: void si_startChanged(const QPoint& p, const QPoint& prev); void si_cursorMoved(const QPoint& p, const QPoint& prev); void si_selectionChanged(const MSAEditorSelection& current, const MSAEditorSelection& prev); protected: void resizeEvent(QResizeEvent *); void paintEvent(QPaintEvent *); void mousePressEvent(QMouseEvent *); void mouseReleaseEvent(QMouseEvent*); void mouseMoveEvent(QMouseEvent*); void keyPressEvent(QKeyEvent *); void focusOutEvent(QFocusEvent* fe); void focusInEvent(QFocusEvent* fe); private slots: void sl_onHScrollMoved(int pos); void sl_onVScrollMoved(int pos); void sl_alignmentChanged(const MAlignment&, const MAlignmentModInfo&); void sl_onScrollBarActionTriggered(int scrollAction); void sl_buildStaticMenu(GObjectView* v, QMenu* m); void sl_buildStaticToolbar(GObjectView* v, QToolBar* t); void sl_buildContextMenu(GObjectView* v, QMenu* m); void sl_lockedStateChanged(); void sl_addSeqFromFile(); void sl_addSeqFromProject(); void sl_delCurrentSelection(); void sl_copyCurrentSelection(); void sl_fillCurrentSelectionWithGaps(); void sl_delSym(); void sl_delCol(); void sl_insCol(); void sl_goto(); void sl_removeAllGaps(); void sl_sortByName(); void sl_reverseComplementCurrentSelection(); void sl_onPosChangeRequest(int pos); void sl_createSubaligniment(); void sl_changeColorScheme(); void sl_zoomOperationPerformed(bool resizeModeChanged); protected: virtual void wheelEvent (QWheelEvent * event); private: void buildMenu(QMenu* m); void prepareColorSchemeMenuActions(); void updateActions(); void updateHScrollBar(); void updateVScrollBar(); void drawAll(); void drawContent(QPainter& p); void drawCursor(QPainter& p); void drawFocus(QPainter& p); void drawSelection(QPainter &p); void ins(const QPoint& p, bool columnMode); void fillSelectionWithGaps(); void del(const QPoint& p, bool columnMode); bool checkState() const; void validateRanges(); //called on resize/refont like events MSAEditor* editor; MSAEditorUI* ui; GScrollBar* shBar; GScrollBar* svBar; int startPos; //first visible x pos int startSeq; //first visible y pos bool scribbling; QPoint cursorPos; QPoint mousePos; MSAEditorSelection selection; QAction* copySelectionAction; QAction* delSelectionAction; QAction* delColAction; QAction* insSymAction; QAction* insColAction; QAction* removeAllGapsAction; QAction* gotoAction; QAction* createSubaligniment; QAction* addSeqFromFileAction; QAction* addSeqFromProjectAction; QAction* sortByNameAction; QAction* reverseComplementAction; QPixmap* cachedView; bool completeRedraw; MSAColorScheme* colorScheme; bool highlightSelection; QList colorSchemeMenuActions; }; }//namespace #endif ugene-1.9.8/src/corelibs/U2View/src/util_ov_msaedit/AlignmentLogo.h0000644000175000017500000001325011651544334023721 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_ALIGNMENT_LOGO_H_ #define _U2_ALIGNMENT_LOGO_H_ #include #include #include #include #include #include namespace U2 { class MSAEditor; enum SequenceType {Auto, NA, AA}; /************************************************************************/ /* Settings */ /************************************************************************/ class U2VIEW_EXPORT AlignmentLogoSettings { public: AlignmentLogoSettings(const MAlignment& _ma) : ma(_ma) { for (int i = 0; i < 256; i++) { colorScheme[i] = Qt::black; } if (ma.getAlphabet()->isNucleic()) { sequenceType = NA; colorScheme['G'] = QColor(255, 128, 0); colorScheme['T'] = Qt::red; colorScheme['C'] = Qt::blue; colorScheme['A'] = Qt::green; colorScheme['U'] = Qt::red; } else if (ma.getAlphabet()->isAmino()) { sequenceType = AA; } else { sequenceType = Auto; } if (!ma.getAlphabet()->isNucleic()) { colorScheme['G'] = Qt::green; colorScheme['S'] = Qt::green; colorScheme['T'] = Qt::green; colorScheme['Y'] = Qt::green; colorScheme['C'] = Qt::green; colorScheme['N'] = QColor(192, 0, 192); colorScheme['Q'] = QColor(192, 0, 192); colorScheme['K'] = Qt::blue; colorScheme['R'] = Qt::blue; colorScheme['H'] = Qt::blue; colorScheme['D'] = Qt::red; colorScheme['E'] = Qt::red; colorScheme['P'] = Qt::black; colorScheme['A'] = Qt::black; colorScheme['W'] = Qt::black; colorScheme['F'] = Qt::black; colorScheme['L'] = Qt::black; colorScheme['I'] = Qt::black; colorScheme['M'] = Qt::black; colorScheme['V'] = Qt::black; } startPos = 0; len = ma.getLength(); /*colorScheme.insert('S', Qt::green); colorScheme.insert('G', Qt::green); colorScheme.insert('H', Qt::green); colorScheme.insert('T', Qt::green); colorScheme.insert('A', Qt::green); colorScheme.insert('P', Qt::green); colorScheme.insert('Y', Qt::blue); colorScheme.insert('V', Qt::blue); colorScheme.insert('M', Qt::blue); colorScheme.insert('C', Qt::blue); colorScheme.insert('L', Qt::blue); colorScheme.insert('F', Qt::blue); colorScheme.insert('I', Qt::blue); colorScheme.insert('W', Qt::blue);*/ } MAlignment ma; SequenceType sequenceType; int startPos; int len; QColor colorScheme[256]; }; /************************************************************************/ /* LogoRenderArea */ /************************************************************************/ class U2VIEW_EXPORT AlignmentLogoRenderArea : public QWidget { public: AlignmentLogoRenderArea(const AlignmentLogoSettings& s, QWidget* p); void replaceSettings(const AlignmentLogoSettings& s); protected: virtual void paintEvent(QPaintEvent* e); virtual void resizeEvent(QResizeEvent* e); void evaluateHeights(); void sortCharsByHeight(); qreal getH(int pos); private: AlignmentLogoSettings settings; qreal s;//4||20 qreal error; QVector* acceptableChars; QVector bases; QVector aminoacids; QVector > columns; //frequency and height of a particular char at position QVector frequencies[256]; QVector heights[256]; int bitWidth; int bitHeight; }; /************************************************************************/ /* LogoItem */ /************************************************************************/ class AlignmentLogoItem : public QGraphicsItem { public: AlignmentLogoItem(char _ch, QPointF _baseline, int _charWidth, int _charHeight, QFont _font, QColor _color=Qt::black); QRectF boundingRect() const; void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget /* = 0 */); private: char ch; QPointF baseline; int charWidth; int charHeight; QFont font; QColor color; QPainterPath path; }; }//namespace #endif ugene-1.9.8/src/corelibs/U2View/src/util_ov_msaedit/MSAEditorUndoFramework.cpp0000644000175000017500000001005111651544334026004 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "MSAEditorUndoFramework.h" #include #include namespace U2 { MSAEditorUndoFramework::MSAEditorUndoFramework(QObject* p, MAlignmentObject* ma) : QUndoStack(p), maObj(ma), lastSavedObjectVersion(0), maxMemUse(20*1024*1024) { if (maObj!=NULL) { connect(maObj, SIGNAL(si_alignmentChanged(const MAlignment&, const MAlignmentModInfo&)), SLOT(sl_alignmentChanged(const MAlignment&, const MAlignmentModInfo&))); connect(maObj, SIGNAL(si_lockedStateChanged()), SLOT(sl_lockedStateChanged())); } setUndoLimit(100); uAction = createUndoAction(this); uAction->setIcon(QIcon(":core/images/undo.png")); uAction->setShortcut(QKeySequence::Undo); uAction->setToolTip(QString("%1 (%2)").arg(uAction->text()).arg(uAction->shortcut().toString())); rAction = createRedoAction(this); rAction->setIcon(QIcon(":core/images/redo.png")); rAction->setShortcut(QKeySequence::Redo); rAction->setToolTip(QString("%1 (%2)").arg(rAction->text()).arg(rAction->shortcut().toString())); sl_lockedStateChanged();//updates action state } void MSAEditorUndoFramework::sl_lockedStateChanged() { bool active = maObj ? !maObj->isStateLocked() : false; setActive(active); int activeIdx = index(); int cnt = count(); uAction->setEnabled(active && activeIdx > 0); rAction->setEnabled(active && activeIdx + 1 < cnt); } void MSAEditorUndoFramework::applyUndoRedoAction(const MAlignment& ma) { if (maObj) { assert(!maObj->isStateLocked()); lastSavedObjectVersion = maObj->getModificationVersion()+1; maObj->setMAlignment(ma); } } void MSAEditorUndoFramework::sl_alignmentChanged(const MAlignment& maBefore, const MAlignmentModInfo& ) { if (maObj == NULL || lastSavedObjectVersion == maObj->getModificationVersion() || maBefore.getRows() == maObj->getMAlignment().getRows()) { return; } lastSavedObjectVersion = maObj->getModificationVersion(); const MAlignment& maAfter = maObj->getMAlignment(); int memUseBefore = 0; int cntBefore = count(); for (int i=0; i < cntBefore;i++) { memUseBefore+=(static_cast(command(i)))->getMemUsage(); } MSAEditorUndoWholeAliCommand* cmd = new MSAEditorUndoWholeAliCommand(maBefore, maAfter); cmd->fwk = this; int cmdMemUse = cmd->getMemUsage(); int undoL = undoLimit(); if (memUseBefore + cmdMemUse < maxMemUse && cntBefore == undoL) { setUndoLimit(undoL+1); } push(cmd); int newMemUse = memUseBefore + cmdMemUse; if (newMemUse > maxMemUse) { int itemsToRemove = 0; int dMem = 0; int cnt = count(); for (; itemsToRemove < cnt; itemsToRemove++) { dMem+=(static_cast(command(itemsToRemove)))->getMemUsage(); if (newMemUse - dMem <= maxMemUse) { break; } } int newLimit = cnt - itemsToRemove; setUndoLimit(newLimit); } } void MSAEditorUndoWholeAliCommand::redo() { fwk->applyUndoRedoAction(maAfter); } void MSAEditorUndoWholeAliCommand::undo() { fwk->applyUndoRedoAction(maBefore); } } //namespace ugene-1.9.8/src/corelibs/U2View/src/util_ov_msaedit/MSAEditor.h0000644000175000017500000001424611651544334022757 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_MSA_EDITOR_H_ #define _U2_MSA_EDITOR_H_ #include #include #include #include #include #include namespace U2 { class MAlignmentObject; class PhyTreeObject; class MSAEditorUI; class MSAEditorSequenceArea; class MSAEditorConsensusArea; class MSAEditorNameList; class MSAEditorOffsetsViewController; class MSAEditorStatusWidget; class MSAEditorUndoFramework; class PhyTreeGeneratorTask; class MSAEditorTreeViewer; #define MSAE_MENU_COPY "MSAE_MENU_COPY" #define MSAE_MENU_EDIT "MSAE_MENU_EDIT" #define MSAE_MENU_EXPORT "MSAE_MENU_EXPORT" #define MSAE_MENU_VIEW "MSAE_MENU_VIEW" #define MSAE_MENU_ALIGN "MSAE_MENU_ALIGN" #define MSAE_MENU_TREES "MSAE_MENU_TREES" #define MSAE_MENU_STATISTICS "MSAE_MENU_STATISTICS" #define MSAE_MENU_ADVANCED "MSAE_MENU_ADVANCED" #define MSAE_MENU_LOAD "MSAE_MENU_LOAD_SEQ" class U2VIEW_EXPORT MSAEditor : public GObjectView { Q_OBJECT friend class OpenSavedMSAEditorTask; public: MSAEditor(const QString& viewName, GObject* obj); ~MSAEditor(); virtual void buildStaticToolbar(QToolBar* tb); virtual void buildStaticMenu(QMenu* m); virtual Task* updateViewTask(const QString& stateName, const QVariantMap& stateData); virtual QVariantMap saveState(); MAlignmentObject* getMSAObject() const {return msaObject;} const MSAEditorUI* getUI() const {return ui;} int getAlignmentLen() const; int getNumSequences() const; const QRect& getCurrentSelection() const; const QFont& getFont() const {return font;} int getFirstVisibleBase() const; float getZoomFactor() const {return zoomFactor;} enum ResizeMode { ResizeMode_FontAndContent, ResizeMode_OnlyContent }; ResizeMode getResizeMode() const { return resizeMode; } int getRowHeight() const; int getColumnWidth() const; static const float zoomMult; signals: void si_fontChanged(const QFont& f); void si_zoomOperationPerformed(bool resizeModeChanged); protected slots: void sl_onContextMenuRequested(const QPoint & pos); void sl_zoomIn(); void sl_zoomOut(); void sl_zoomToSelection(); void sl_changeFont(); void sl_resetZoom(); void sl_buildTree(); void sl_openTree(); protected: virtual QWidget* createWidget(); bool eventFilter(QObject* o, QEvent* e); virtual void onObjectRenamed(GObject* obj, const QString& oldName); private: void addCopyMenu(QMenu* m); void addEditMenu(QMenu* m); void addExportMenu(QMenu* m); void addViewMenu(QMenu* m); void addAlignMenu(QMenu* m); void addTreeMenu(QMenu* m); void addAdvancedMenu(QMenu* m); void addStatisticsMenu(QMenu* m); void addLoadMenu(QMenu* m); void setFont(const QFont& f); void calcFontPixelToPointSizeCoef(); void updateActions(); void setFirstVisibleBase(int firstPos); void setZoomFactor(float newZoomFactor) {zoomFactor = newZoomFactor;} void initDragAndDropSupport(); MAlignmentObject* msaObject; MSAEditorUI* ui; QFont font; ResizeMode resizeMode; float zoomFactor; float fontPixelToPointSize; QAction* zoomInAction; QAction* zoomOutAction; QAction* zoomToSelectionAction; QAction* changeFontAction; QAction* resetFontAction; QAction* buildTreeAction; QAction* saveScreenshotAction; CreatePhyTreeSettings settings; PhyTreeGeneratorTask* treeGeneratorTask; }; class MSAEditorUI : public QWidget { Q_OBJECT //todo: make public accessors: friend class MSALabelWidget; friend class MSAEditorSequenceArea; friend class MSAEditorConsensusArea; friend class MSAEditorNameList; friend class MSAEditorTreeViewer; friend class MSAEditor; public: MSAEditorUI(MSAEditor* editor); QWidget* createLabelWidget(const QString& text = QString(), Qt::Alignment ali = Qt::AlignCenter) const; MSAEditor* getEditor() const {return editor;} QAction* getUndoAction() const; QAction* getRedoAction() const; public slots: void sl_saveScreenshot(); private: MSAEditor* editor; MSAEditorNameList* nameList; MSAEditorSequenceArea* seqArea; MSAEditorConsensusArea* consArea; MSAEditorOffsetsViewController* offsetsView; MSAEditorStatusWidget* statusWidget; MSAEditorTreeViewer* treeViewer; QSplitter* splitter; QList nameAreaWidgets; QList lw1Widgets; QList seqAreaWidgets; QList lw2Widgets; QList treeAreaWidgets; MSAEditorUndoFramework* undoFWK; }; class MSALabelWidget : public QWidget { Q_OBJECT public: MSALabelWidget(const MSAEditorUI* _ui, const QString & _t, Qt::Alignment _a); const MSAEditorUI* ui; QString text; Qt::Alignment ali; protected slots: void sl_fontChanged(); protected: void paintEvent(QPaintEvent *e); void mousePressEvent(QMouseEvent *e); }; }//namespace; #endif ugene-1.9.8/src/corelibs/U2View/src/util_ov_msaedit/MSAEditorBaseOffsetsCache.cpp0000644000175000017500000000705711651544334026365 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "MSAEditorBaseOffsetsCache.h" #include namespace U2 { //one of 256 positions contains offset info #define CACHE_FREQ 256 MSAEditorBaseOffsetCache::MSAEditorBaseOffsetCache(QObject* p, MAlignmentObject* obj) : QObject(p), aliObj(obj) { connect(aliObj, SIGNAL(si_alignmentChanged(const MAlignment&, const MAlignmentModInfo&)), SLOT(sl_alignmentChanged(const MAlignment&, const MAlignmentModInfo&))); objVersion = 1; globVersion = 0; } void MSAEditorBaseOffsetCache::sl_alignmentChanged(const MAlignment&, const MAlignmentModInfo& modInfo) { if (modInfo.sequenceContentChanged) { objVersion++; } } int MSAEditorBaseOffsetCache::getBaseCounts(int seqNum, int aliPos, bool inclAliPos) { const MAlignment& ma = aliObj->getMAlignment(); const MAlignmentRow& row = ma.getRow(seqNum); int endPos = inclAliPos ? aliPos + 1 : aliPos; if (endPos < row.getCoreStart()) { return 0; } int i = 0; int cnt = _getBaseCounts(seqNum, aliPos, i); for (; i < endPos; i++) { if (row.chatAt(i) != MAlignment_GapChar) { cnt++; } } return cnt; } int MSAEditorBaseOffsetCache::_getBaseCounts(int seqNum, int aliPos, int& cachedEndPos) { updateCacheSize(); updateCacheRow(seqNum); const RowCache& r = cache[seqNum]; assert(globVersion = objVersion); assert(r.cacheVersion == objVersion); int cacheIdx = aliPos / CACHE_FREQ - 1; if (cacheIdx < 0) { cachedEndPos = 0; return 0; } cachedEndPos = (cacheIdx + 1) * CACHE_FREQ; int res = r.rowOffsets[cacheIdx]; return res; } void MSAEditorBaseOffsetCache::updateCacheSize() { if (objVersion == globVersion) { return; } int nSeq = aliObj->getMAlignment().getNumRows(); cache.resize(nSeq); globVersion = objVersion; } void MSAEditorBaseOffsetCache::updateCacheRow(int seqNum) { assert(globVersion == objVersion); RowCache& r = cache[seqNum]; if (r.cacheVersion == objVersion) { return; } const MAlignment& ma = aliObj->getMAlignment(); int aliLen = ma.getLength(); int nPoints = aliLen / CACHE_FREQ; r.rowOffsets.resize(nPoints); const MAlignmentRow& row = ma.getRow(seqNum); const char* seq = row.getCore().constData(); int firstCharOffset = row.getCoreStart(); int lastCharOffset = row.getCoreEnd(); for (int i = 0, cnt = 0; i < aliLen; i++) { if (i != 0 && i % CACHE_FREQ == 0) { r.rowOffsets[i / CACHE_FREQ - 1] = cnt; } if (i < firstCharOffset || i >= lastCharOffset || seq[i - firstCharOffset] != MAlignment_GapChar) { cnt++; } } r.cacheVersion = objVersion; } }//namespace ugene-1.9.8/src/corelibs/U2View/src/util_ov_msaedit/CreateSubalignimentDialogController.h0000644000175000017500000000433311651544334030275 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_CREATE_SUBALIGNIMENT_DIALOG_CONTROLLER_H_ #define _U2_CREATE_SUBALIGNIMENT_DIALOG_CONTROLLER_H_ #include "ui/ui_CreateSubalignimentDialog.h" #include #include #include namespace U2{ class U2VIEW_EXPORT CreateSubalignimentDialogController : public QDialog, Ui_CreateSubalignimentDialog { Q_OBJECT public: CreateSubalignimentDialogController( MAlignmentObject *_mobj, const QRect& selection, QWidget *p = NULL); void accept(); bool getAddToProjFlag(){return addToProjBox->isChecked();}; QString getSavePath(){return filepathEdit->text();}; U2Region getRegion(){return window;}; QStringList getSelectedSeqNames(){return selectedNames;}; private slots: void sl_browseButtonClicked(); void sl_allButtonClicked(); void sl_invertButtonClicked(); void sl_noneButtonClicked(); private: void selectSeqNames(); QString filter; MAlignmentObject *mobj; U2Region window; QStringList selectedNames; }; class CreateSubalignmentTask; class CreateSubalignmentSettings; class U2VIEW_EXPORT CreateSubalignmentAndOpenViewTask : public Task { Q_OBJECT public: CreateSubalignmentAndOpenViewTask(MAlignmentObject* mobj, const CreateSubalignmentSettings& settings); QList onSubTaskFinished(Task* subTask); private: CreateSubalignmentTask* csTask; }; } #endif ugene-1.9.8/src/corelibs/U2View/src/util_ov_msaedit/AlignmentLogo.cpp0000644000175000017500000001765511651544334024271 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "AlignmentLogo.h" #include #include #include #include "U2Core/MAlignment.h" #include "U2Core/DNAAlphabet.h" #include namespace U2 { /************************************************************************/ /* LogoRenderArea */ /************************************************************************/ AlignmentLogoRenderArea::AlignmentLogoRenderArea(const AlignmentLogoSettings& _s, QWidget* p) : QWidget(p), settings(_s) { QHBoxLayout* layout = new QHBoxLayout(); layout->addWidget(this); p->setLayout(layout); bases<<'A'<<'G'<<'C'<<'T'<<'U'; /*aminoacids<<'A'<<'C'<<'D'<<'E'<<'F'<<'G'<<'H' <<'I'<<'K'<<'L'<<'M'<<'N'<<'P'<<'Q'<<'R' <<'S'<<'T'<<'V'<<'W'<<'Y';*/ acceptableChars = new QVector(); switch (settings.sequenceType) { case NA: acceptableChars = &bases; s = 4.0; break; default: QByteArray chars = settings.ma.getAlphabet()->getAlphabetChars(); foreach(char ch, chars) { if(ch!=MAlignment_GapChar) acceptableChars->append(ch); } s = 20.0; acceptableChars = &aminoacids; break; } evaluateHeights(); sortCharsByHeight(); } void AlignmentLogoRenderArea::replaceSettings(const AlignmentLogoSettings& _s) { settings = _s; acceptableChars = new QVector(); switch (settings.sequenceType) { case NA: acceptableChars = &bases; s = 4.0; break; default: QByteArray chars = settings.ma.getAlphabet()->getAlphabetChars(); foreach(char ch, chars) { if(ch!=MAlignment_GapChar) acceptableChars->append(ch); } s = 20.0; acceptableChars = &aminoacids; break; } columns.clear(); for (int i = 0; i < 256; i++) { frequencies[i].clear(); heights[i].clear(); } evaluateHeights(); sortCharsByHeight(); } #define SPACER 1 #define MIN_WIDTH 8 void AlignmentLogoRenderArea::paintEvent(QPaintEvent* e) { QPainter p(this); p.fillRect(0,0,width(),height(),Qt::white); QFont charFont("Helvetica"); charFont.setPixelSize(bitHeight); charFont.setBold(true); for(int pos=0; pos < settings.len; pos++) { assert(pos < columns.size()); const QVector& charsAt = columns.at(pos); int yLevel = height(); foreach(char ch, charsAt) { QPointF baseline(pos * (bitWidth + SPACER), yLevel); int charHeight = heights[(int)uchar(ch)][pos] * bitHeight; QColor charColor = settings.colorScheme[(int)uchar(ch)]; AlignmentLogoItem* logoItem = new AlignmentLogoItem(ch, baseline, bitWidth, charHeight, charFont, charColor); logoItem->paint(&p, NULL, this); yLevel -= charHeight + SPACER; } } QWidget::paintEvent(e); } void AlignmentLogoRenderArea::resizeEvent(QResizeEvent* e) { bitWidth = qMax(width() / settings.ma.getLength() - SPACER, MIN_WIDTH); bitHeight = (height() - s) * log(2.0) / log(s); QWidget::resizeEvent(e); } void AlignmentLogoRenderArea::evaluateHeights() { const MAlignment& ma = settings.ma; int numRows = ma.getNumRows(); error = (s - 1)/(2*log(2.0)*numRows); foreach (char ch, *acceptableChars) { QVector freqs(settings.len); QVector hts(settings.len); frequencies[(int)uchar(ch)] = freqs; heights[(int)uchar(ch)] = hts; } columns.resize(settings.len); for (int pos = settings.startPos; pos < settings.len + settings.startPos; pos++) { for (int idx = 0; idx < numRows; idx++) { const MAlignmentRow& row = ma.getRow(idx); assert(pos < ma.getLength()); char ch = row.chatAt(pos); if(acceptableChars->contains(ch)) { int arrIdx = pos - settings.startPos; assert(arrIdx >= 0); assert(arrIdx < frequencies[(int)uchar(ch)].size()); frequencies[(int)uchar(ch)][arrIdx]+=1.0; if (!columns[arrIdx].contains(ch)) { columns[arrIdx].append(ch); } } } } int rows = settings.ma.getNumRows(); for(int pos=0; pos < settings.len; pos++) { qreal h = getH(pos); foreach(char c, columns[pos]) { qreal freq = frequencies[(int)uchar(c)][pos] / rows; heights[(int)uchar(c)][pos] = freq * ( log(s) / log(2.0) - ( h + error ) ); } } } qreal AlignmentLogoRenderArea::getH(int pos) { qreal h = 0.0; int rows = settings.ma.getNumRows(); foreach(char ch, columns.at(pos)) { qreal freq = frequencies[(int)uchar(ch)][pos] / rows; h += -freq * log(freq) / log(2.0); } assert (h >= 0.0); return h; } void AlignmentLogoRenderArea::sortCharsByHeight() { for(int pos = 0; pos < columns.size(); pos++) { QVector& chars = columns[pos]; char temp; int count = chars.size(); for(int j = 0; j < chars.size() - 1; j++) { for(int i = 0; i < count - 1; i++) { temp = chars[i]; qreal tempFreq = frequencies[(int)uchar(temp)][pos]; qreal nextFreq = frequencies[(int)uchar(chars[i+1])][pos]; if (tempFreq>nextFreq) { chars[i] = chars[i+1]; chars[i+1] = temp; } else { temp = chars[i+1]; } } --count; } } } /************************************************************************/ /* Logo item */ /************************************************************************/ AlignmentLogoItem::AlignmentLogoItem(char _ch, QPointF _baseline, int _charWidth, int _charHeight, QFont _font, QColor _color) : ch(_ch), baseline(_baseline), charWidth(_charWidth), charHeight(_charHeight), font(_font), color(_color) {} QRectF AlignmentLogoItem::boundingRect() const { return path.boundingRect(); } void AlignmentLogoItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget ) { Q_UNUSED(option); Q_UNUSED(widget); painter->save(); QString chStr(ch); path.addText(baseline, font, chStr); //adjust item's height QRectF bound = path.boundingRect(); //epsilon value needed to avoid division by extremely small values and raising exception in qt gui qreal eps = 1e-3; qreal sx = qMax(charWidth / bound.width(), eps); qreal sy = qMax(charHeight / bound.height(), eps); painter->scale(sx, sy); //map baseline position to scaled coordinates qreal offsetx = baseline.x() * (1/sx - 1); qreal offsety = baseline.y() * (1/sy - 1); painter->translate(offsetx, offsety); painter->fillPath(path, color); painter->restore(); } }//namespace ugene-1.9.8/src/corelibs/U2View/src/util_ov_msaedit/MSAEditorState.h0000644000175000017500000000312311651544334023750 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_MSA_EDITOR_STATE_H_ #define _U2_MSA_EDITOR_STATE_H_ #include #include #include namespace U2 { class MSAEditor; class U2VIEW_EXPORT MSAEditorState { public: MSAEditorState(){} MSAEditorState(const QVariantMap& _stateData) : stateData(_stateData){} static QVariantMap saveState(MSAEditor* v); bool isValid() const; GObjectReference getMSAObjectRef() const; void setMSAObjectRef(const GObjectReference& ref); QFont getFont() const; void setFont(const QFont &f); int getFirstPos() const; void setFirstPos(int y); float getZoomFactor() const; void setZoomFactor(float zoomFactor); QVariantMap stateData; }; } // namespace #endif ugene-1.9.8/src/corelibs/U2View/src/util_ov_msaedit/MSAEditorUndoFramework.h0000644000175000017500000000463711651544334025466 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_MSA_EDITOR_UNDO_FRAMEWOFK_H_ #define _U2_MSA_EDITOR_UNDO_FRAMEWOFK_H_ #include #include #include namespace U2 { class MAlignmentObject; class MAlignmentModInfo; class U2VIEW_EXPORT MSAEditorUndoFramework : protected QUndoStack { Q_OBJECT public: MSAEditorUndoFramework(QObject* p, MAlignmentObject* ma); void applyUndoRedoAction(const MAlignment& ma); QAction* getUndoAction() const {return uAction;} QAction* getRedoAction() const {return rAction;} public slots: void sl_alignmentChanged(const MAlignment& aliBefore, const MAlignmentModInfo& modInfo); void sl_lockedStateChanged(); private: MAlignmentObject* maObj; int lastSavedObjectVersion; int maxMemUse;//in bytes; QAction* uAction; QAction* rAction; }; class MSAEditorUndoCommand : public QUndoCommand { friend class MSAEditorUndoFramework; public: MSAEditorUndoCommand() : fwk (NULL) {} virtual int getMemUsage() const {return 0;} //in bytes, report non-0 if > 100k; protected: MSAEditorUndoFramework* fwk; }; class MSAEditorUndoWholeAliCommand : public MSAEditorUndoCommand { public: MSAEditorUndoWholeAliCommand(const MAlignment& _maBefore, const MAlignment& _maAfter) : maBefore(_maBefore), maAfter(_maAfter){} virtual int getMemUsage() const {return maBefore.estimateMemorySize();} virtual void redo(); virtual void undo(); protected: MAlignment maBefore; MAlignment maAfter; }; } // namespace #endif ugene-1.9.8/src/corelibs/U2View/src/util_ov_msaedit/ConsensusSelectorDialogController.h0000644000175000017500000000415211651544334030030 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_CONSENSUS_SELECTOR_DIALOG_CONTROLLER_H_ #define _U2_CONSENSUS_SELECTOR_DIALOG_CONTROLLER_H_ #include "ui/ui_ConsensusSelectorDialog.h" #include #include namespace U2{ class U2VIEW_EXPORT ConsensusSelectorDialogController : public QDialog, Ui_ConsensusSelectorDialog { Q_OBJECT public: ConsensusSelectorDialogController(const QString& selectedAlgorithmId, ConsensusAlgorithmFlags flags, QWidget *p = NULL); const QString& getSelectedAlgorithmId() const {return selectedAlgorithmId;} // enables threshold selector group, sets threshold range to 'r' // and current value for slider and spin box to 'value' void enableThresholdSelector(int minVal, int maxVal, int value, const QString& suffix); // disables threshold selector group void disableThresholdSelector(); int getThresholdValue() const; signals: void si_algorithmChanged(const QString& algoId); void si_thresholdChanged(int val); private slots: void sl_algorithmSelectionChanged(int); void sl_thresholdSliderChanged(int); void sl_thresholdSpinChanged(int); void sl_resetThresholdClicked(bool); private: void updateSelectedAlgorithmDesc(); QString selectedAlgorithmId; }; } #endif ugene-1.9.8/src/corelibs/U2View/src/util_ov_msaedit/MSAEditorState.cpp0000644000175000017500000000551411651544334024311 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "MSAEditorState.h" #include "MSAEditor.h" #include "MSAEditorFactory.h" #include #include #include #include namespace U2 { #define VIEW_ID QString("view_id") #define MSA_OBJ QString("msa_obj_ref") #define FONT QString("font") #define FIRST_POS QString("first_pos") #define ZOOM_FACTOR QString("zoom_factor") bool MSAEditorState::isValid() const { return stateData.value(VIEW_ID) == MSAEditorFactory::ID; } GObjectReference MSAEditorState::getMSAObjectRef() const { return stateData.contains(MSA_OBJ) ? stateData[MSA_OBJ].value() : GObjectReference(); } void MSAEditorState::setMSAObjectRef(const GObjectReference& ref) { stateData[MSA_OBJ] = QVariant::fromValue(ref); } QFont MSAEditorState::getFont() const { QVariant v = stateData.value(FONT); if (v.type() == QVariant::Font) { return v.value(); } return QFont(); } void MSAEditorState::setFont(const QFont &f) { stateData[FONT] = f; } int MSAEditorState::getFirstPos() const { QVariant v = stateData.value(FIRST_POS); if (v.type() == QVariant::Int) { return v.toInt(); } return -1; } void MSAEditorState::setFirstPos(int y) { stateData[FIRST_POS] = y; } float MSAEditorState::getZoomFactor() const { QVariant v = stateData.value(ZOOM_FACTOR); if (v.type() == QVariant::Double) { return v.toDouble(); } return 1.0; } void MSAEditorState::setZoomFactor(float zoomFactor) { stateData[ZOOM_FACTOR] = zoomFactor; } QVariantMap MSAEditorState::saveState(MSAEditor* v) { MSAEditorState ss; ss.stateData[VIEW_ID]=MSAEditorFactory::ID; MAlignmentObject* msaObj = v->getMSAObject(); if (msaObj) { ss.setMSAObjectRef(GObjectReference(msaObj)); } ss.setFont(v->getFont()); ss.setFirstPos(v->getFirstVisibleBase()); return ss.stateData; } } // namespace ugene-1.9.8/src/corelibs/U2View/src/util_ov_msaedit/MSAEditorStatusBar.h0000644000175000017500000000441611651544334024606 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_MSA_EDITOR_STATUS_BAR_H_ #define _U2_MSA_EDITOR_STATUS_BAR_H_ #include #include #include #include #include #include namespace U2 { class MAlignmentObject; class MAlignment; class MAlignmentModInfo; class MSAEditorSequenceArea; class MSAEditorStatusWidget : public QWidget { Q_OBJECT public: MSAEditorStatusWidget(MAlignmentObject* mobj, MSAEditorSequenceArea* seqArea); bool eventFilter(QObject* obj, QEvent* ev); private slots: void sl_alignmentChanged(const MAlignment&, const MAlignmentModInfo&) {updateCoords();} void sl_lockStateChanged() {updateLock();} void sl_cursorMoved(const QPoint& , const QPoint& ) {updateCoords();} void sl_findNext(); void sl_findPrev(); void sl_findFocus(); private: void updateCoords(); void updateLock(); MAlignmentObject* aliObj; MSAEditorSequenceArea* seqArea; QPixmap lockedIcon; QPixmap unlockedIcon; QPushButton* prevButton; QPushButton* nextButton; QLineEdit* searchEdit; QLabel* linesLabel; QLabel* colsLabel; QLabel* lockLabel; QPoint lastSearchPos; QAction* findAction; }; }//namespace; #endif ugene-1.9.8/src/corelibs/U2View/src/util_find_dialog/0000755000175000017500000000000011651544334021115 5ustar ilyailyaugene-1.9.8/src/corelibs/U2View/src/util_find_dialog/FindDialog.h0000644000175000017500000000604711651544334023275 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_FINDDIALOG_H_ #define _U2_FINDDIALOG_H_ #include #include #include #include #include #include #include #include namespace U2 { class ADVSequenceObjectContext; class DNASequenceObject; class FindAlgorithmTask; class Task; class FRListItem; class U2VIEW_EXPORT FindDialog : public QDialog, public Ui_FindDialogBase { Q_OBJECT friend class FindAlgorithmTask; public: static bool runDialog(ADVSequenceObjectContext* ctx); public slots: virtual void reject(); protected: bool eventFilter(QObject *obj, QEvent *ev); private: FindDialog(ADVSequenceObjectContext* c); private slots: //buttons: void sl_onSaveAnnotations(); void sl_onClearList(); void sl_onFindNext(); void sl_onFindAll(); void sl_onClose(); //line ed void sl_onSearchPatternChanged(const QString&); // groups void sl_onSequenceTypeChanged(); void sl_onStrandChanged(); void sl_onAlgorithmChanged(); //spin box void sl_onMatchPercentChanged(int); void sl_onTaskFinished(Task*); void sl_onTimer(); //range void sl_onRangeStartChanged(int); void sl_onCurrentPosChanged(int); void sl_onRangeEndChanged(int); void sl_onResultActivated(QListWidgetItem* i, bool setPos = true); void sl_currentResultChanged(QListWidgetItem*, QListWidgetItem*); void sl_onRangeToSelection(); void sl_onRangeToSequence(); void sl_onRemoveOverlaps(); private: void connectGUI(); void updateState(); void updateStatus(); void tunePercentBox(); bool checkState(bool forSingleShot); bool checkPrevSettings(); void savePrevSettings(); void runTask(bool singleShot); void importResults(); int getMaxErr() const; U2Region getCompleteSearchRegion() const; private: ADVSequenceObjectContext* ctx; DNASequenceObject* sequence; QString prevSearchString; int prevAlgorithm; //0 - 100%, 1-mismatch, 2-insdel int prevMatch; FindAlgorithmTask* task; QTimer* timer; U2Region initialSelection; }; }//namespace #endif ugene-1.9.8/src/corelibs/U2View/src/util_find_dialog/FindDialog.cpp0000644000175000017500000005141211651544334023624 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "FindDialog.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include namespace U2 { /* TRANSLATOR U2::FindDialog */ class FRListItem : public QListWidgetItem { public: FRListItem(const FindAlgorithmResult& r); FindAlgorithmResult res; virtual bool operator< ( const QListWidgetItem & other ) const; }; static FRListItem* findItem(const FindAlgorithmResult& r, QListWidget* lv) { for (int i=0, n = lv->count(); i(lv->item(i)); if (r == item->res) { return item; } } return NULL; } bool FindDialog::runDialog(ADVSequenceObjectContext* ctx) { FindDialog d(ctx); d.exec(); return true; } FindDialog::FindDialog(ADVSequenceObjectContext* context): QDialog(context->getAnnotatedDNAView()->getWidget()) { setupUi(this); ctx = context; prevAlgorithm = 0; prevMatch = 100; task = NULL; QVector selection = ctx->getSequenceSelection()->getSelectedRegions(); if(!selection.isEmpty()) { initialSelection = selection.first(); } connectGUI(); updateState(); if (context->getComplementTT() == NULL) { rbDirect->setChecked(true); } sbMatch->setMinimum(30); int seqLen = context->getSequenceLen(); sbRangeStart->setMinimum(1); sbRangeStart->setMaximum(seqLen); sbCurrentPos->setMinimum(1); sbCurrentPos->setMaximum(seqLen); sbRangeEnd->setMinimum(1); sbRangeEnd->setMaximum(seqLen); sbRangeStart->setValue(initialSelection.isEmpty() ? 1 : initialSelection.startPos + 1); sbRangeEnd->setValue(initialSelection.isEmpty() ? seqLen : initialSelection.endPos()); leFind->setFocus(); lbResult->setSortingEnabled(true); DNAAlphabet* al = ctx->getSequenceObject()->getAlphabet(); useAmbiguousBasesBox->setEnabled(al->isNucleic()); timer = new QTimer(this); connect(AppContext::getTaskScheduler(), SIGNAL(si_stateChanged(Task*)), SLOT(sl_onTaskFinished(Task*))); connect(timer, SIGNAL(timeout()), SLOT(sl_onTimer())); } void FindDialog::connectGUI() { //buttons connect(pbSaveAnnotations, SIGNAL(clicked()), SLOT(sl_onSaveAnnotations())); connect(pbClearList, SIGNAL(clicked()), SLOT(sl_onClearList())); connect(pbRemoveOverlaps, SIGNAL(clicked()), SLOT(sl_onRemoveOverlaps())); connect(pbFind, SIGNAL(clicked()), SLOT(sl_onFindNext())); connect(pbFindAll, SIGNAL(clicked()), SLOT(sl_onFindAll())); connect(pbClose, SIGNAL(clicked()), SLOT(sl_onClose())); //search line edit connect(leFind, SIGNAL(textEdited(const QString&)), SLOT(sl_onSearchPatternChanged(const QString&))); //radio button groups connect(rbSequence, SIGNAL(clicked()), SLOT(sl_onSequenceTypeChanged())); connect(rbTranslation, SIGNAL(clicked()), SLOT(sl_onSequenceTypeChanged())); connect(rbBoth, SIGNAL(clicked()), SLOT(sl_onStrandChanged())); connect(rbDirect, SIGNAL(clicked()), SLOT(sl_onStrandChanged())); connect(rbComplement, SIGNAL(clicked()), SLOT(sl_onStrandChanged())); connect(rbMismatchAlg, SIGNAL(clicked()), SLOT(sl_onAlgorithmChanged())); connect(rbInsDelAlg, SIGNAL(clicked()), SLOT(sl_onAlgorithmChanged())); //match percent spin connect(sbMatch, SIGNAL(valueChanged(int)), SLOT(sl_onMatchPercentChanged(int))); //connect position selectors connect(sbRangeStart, SIGNAL(valueChanged(int)), SLOT(sl_onRangeStartChanged(int))); connect(sbCurrentPos, SIGNAL(valueChanged(int)), SLOT(sl_onCurrentPosChanged(int))); connect(sbRangeEnd, SIGNAL(valueChanged(int)), SLOT(sl_onRangeEndChanged(int))); //results list connect(lbResult, SIGNAL(itemActivated(QListWidgetItem*)), SLOT(sl_onResultActivated(QListWidgetItem*))); connect(lbResult, SIGNAL(currentItemChanged(QListWidgetItem*, QListWidgetItem*)), SLOT(sl_currentResultChanged(QListWidgetItem*, QListWidgetItem*))); //range buttons connect(pbRangeToSelection, SIGNAL(clicked()), SLOT(sl_onRangeToSelection())); connect(pbRangeToSeq, SIGNAL(clicked()), SLOT(sl_onRangeToSequence())); lbResult->installEventFilter(this); } void FindDialog::updateState() { bool hasInitialSelection = initialSelection.length > 0; bool hasActiveTask = task!=NULL; bool hasAmino = ctx->getAminoTT()!=NULL; bool hasCompl = ctx->getComplementTT()!=NULL; bool hasResults = lbResult->count() > 0; bool hasPattern = !leFind->text().isEmpty(); sbMatch->setEnabled(hasPattern); pbFind->setEnabled(hasPattern); pbFindAll->setEnabled(hasPattern); leFind->setEnabled(!hasActiveTask); pbFind->setEnabled(!hasActiveTask); pbFindAll->setEnabled(!hasActiveTask); pbSaveAnnotations->setEnabled(!hasActiveTask && hasResults); pbClearList->setEnabled(!hasActiveTask && hasResults); pbRemoveOverlaps->setEnabled(lbResult->count() > 2); pbClose->setText(hasActiveTask ? tr("Cancel") : tr("Close")); rbSequence->setEnabled(!hasActiveTask); rbTranslation->setEnabled(!hasActiveTask && hasAmino); rbBoth->setEnabled(!hasActiveTask && hasCompl); rbDirect->setEnabled(!hasActiveTask); rbComplement->setEnabled(!hasActiveTask && hasCompl); rbMismatchAlg->setEnabled(!hasActiveTask); rbInsDelAlg->setEnabled(!hasActiveTask); sbRangeStart->setEnabled(!hasActiveTask); sbCurrentPos->setEnabled(!hasActiveTask); sbRangeEnd->setEnabled(!hasActiveTask); pbRangeToSelection->setEnabled(!hasActiveTask && hasInitialSelection); pbRangeToSeq->setEnabled(!hasActiveTask); updateStatus(); } void FindDialog::updateStatus() { QString message; if (task != NULL) { message = tr("Progress %1%. Current position %2 ").arg(task->getProgress()).arg(task->getCurrentPos()); } message += tr("Results found %1").arg(lbResult->count()); statusBar->setText(message); } bool FindDialog::eventFilter(QObject *obj, QEvent *ev) { if (obj == lbResult && ev->type() == QEvent::KeyPress) { QKeyEvent* ke = (QKeyEvent*)ev; if (ke->key() == Qt::Key_Space) { FRListItem* item = static_cast(lbResult->currentItem()); if (item != NULL) { sl_onResultActivated(item); } } } return false; } void FindDialog::sl_onSaveAnnotations() { if (lbResult->count() == 0) { return; } CreateAnnotationModel m; m.sequenceObjectRef = ctx->getSequenceObject(); m.hideLocation = true; m.sequenceLen = ctx->getSequenceObject()->getSequenceLen(); CreateAnnotationDialog d(this, m); int rc = d.exec(); if (rc != QDialog::Accepted) { return; } AnnotationTableObject* aobj = m.getAnnotationObject(); assert(aobj!=NULL); const QString& name = m.data->name; QList list; for (int i=0, n = lbResult->count(); i(lbResult->item(i)); list.append(item->res.toAnnotation(name)); } CreateAnnotationsTask* t = new CreateAnnotationsTask(aobj, m.groupName, list); AppContext::getTaskScheduler()->registerTopLevelTask(t); } void FindDialog::sl_onClearList() { lbResult->clear(); updateState(); } void FindDialog::sl_onFindNext() { //TODO: check if the same search params are used after find-all -> use cached results? bool ok = checkState(true); if (!ok) { return; } if (sbCurrentPos->value() >= sbRangeEnd->value()) { int res = QMessageBox::question(this, tr("Question?"), tr("The end of the search region is reached. Restart?"), QMessageBox::Yes, QMessageBox::No); if (res != QMessageBox::Yes) { return; } sbCurrentPos->setValue(sbRangeStart->value()); } savePrevSettings(); runTask(true); } void FindDialog::sl_onFindAll() { //TODO: check if the same search params are used after find-all -> use cached results? bool ok = checkState(false); if (!ok) { return; } sbCurrentPos->setValue(sbRangeStart->value()); savePrevSettings(); runTask(false); } void FindDialog::reject() { if (task!=NULL) { task->cancel(); return; } QDialog::reject(); } void FindDialog::sl_onRangeStartChanged(int v) { if (v > sbCurrentPos->value()) { sbCurrentPos->setValue(v); } } void FindDialog::sl_onCurrentPosChanged(int v) { if (v > sbRangeEnd->value()) { sbRangeEnd->setValue(v); } if (v < sbRangeStart->value()) { sbRangeStart->setValue(v); } } void FindDialog::sl_onRangeEndChanged(int v) { if (v < sbCurrentPos->value()) { sbCurrentPos->setValue(v); } } void FindDialog::sl_onClose() { reject(); } void FindDialog::tunePercentBox() { int patternLen = qMax(1, leFind->text().length()); int p = sbMatch->value(); int step = qMax(1, 100 / patternLen); sbMatch->setSingleStep(step); int diff = p % step; if (diff == 0 || p == 100) { return; } int newVal = p; if (diff > step /2) { newVal=qMin(100, newVal + (step - diff)); } else { newVal-= diff; } if (newVal < sbMatch->minimum()) { newVal+= step; } assert(newVal <= 100); sbMatch->setValue(newVal); } //line ed void FindDialog::sl_onSearchPatternChanged(const QString&) { if (leFind->text().length() > getCompleteSearchRegion().length) { sl_onRangeToSequence(); } tunePercentBox(); updateState(); } // groups void FindDialog::sl_onSequenceTypeChanged() { } void FindDialog::sl_onStrandChanged() { } void FindDialog::sl_onAlgorithmChanged() { } //spin box void FindDialog::sl_onMatchPercentChanged(int) { tunePercentBox(); } bool FindDialog::checkState(bool forSingleShot) { QString pattern = leFind->text(); if (pattern.isEmpty()) { QMessageBox::critical(this, tr("Error!"), tr("Search pattern is empty")); return false; } int maxErr = getMaxErr(); int minMatch = pattern.length() - maxErr; assert(minMatch > 0); if (minMatch > getCompleteSearchRegion().length) { QMessageBox::critical(this, tr("Error!"), tr("Pattern length is greater than search range")); return false; } //check pattern's alphabet DNAAlphabet* al = ctx->getAlphabet(); if (!al->isCaseSensitive()) { QString oldPattern = pattern; pattern = pattern.toUpper(); if (pattern!=oldPattern) { // make visible the logic we use to user leFind->setText(pattern); } } bool isTranslation = rbTranslation->isChecked(); if (isTranslation) { DNATranslation* t = ctx->getAminoTT(); assert(t!=NULL); al = t->getDstAlphabet(); } bool alphabetIsOk = TextUtils::fits(al->getMap(), pattern.toLocal8Bit().data(), pattern.size()) || useAmbiguousBasesBox->isChecked(); if (!alphabetIsOk) { int res = QMessageBox::warning(this, tr("Warning!"), tr("Search pattern contains symbols that are out of the active alphabet range. Continue anyway?"), QMessageBox::Yes, QMessageBox::No); if (res == QMessageBox::No) { return false; } } if (lbResult->count() > 0) { if (forSingleShot) { bool settingsTheSame = checkPrevSettings(); if (!settingsTheSame) { int res = QMessageBox::warning(this, tr("Warning!"), tr("The seach settings were changed from the last search. Clean old results?"), QMessageBox::Yes, QMessageBox::No, QMessageBox::Cancel); if (res == QMessageBox::Cancel) { return false; } if (res == QMessageBox::Yes) { lbResult->clear(); sbCurrentPos->setValue(sbRangeStart->value()); } } } else { int res = QMessageBox::warning(this, tr("Warning!"), tr("Results list contains results from the previous search. Clear?"), QMessageBox::Yes, QMessageBox::No, QMessageBox::Cancel); if (res == QMessageBox::Cancel) { return false; } if (res == QMessageBox::Yes) { lbResult->clear(); } } } return true; } bool FindDialog::checkPrevSettings() { if (prevSearchString != leFind->text()) { return false; } int match = sbMatch->value(); if (match != prevMatch) { return false; } int alg = match == 100 ? 0 : rbMismatchAlg->isChecked() ? 1 : 2; if (prevAlgorithm != alg) { return false; } return true; } void FindDialog::savePrevSettings() { prevSearchString = leFind->text(); prevMatch = sbMatch->value(); prevAlgorithm = prevMatch == 100 ? 0 : rbMismatchAlg->isChecked() ? 1 : 2; } int FindDialog::getMaxErr() const { return int((float)(1 - float(sbMatch->value()) / 100) * leFind->text().length()); } U2Region FindDialog::getCompleteSearchRegion() const { return U2Region(sbRangeStart->value()-1, sbRangeEnd->value() - sbRangeStart->value() + 1); } void FindDialog::runTask(bool singleShot) { assert(task == NULL); FindAlgorithmTaskSettings s; s.sequence = ctx->getSequenceData(); s.pattern = leFind->text().toLocal8Bit(); s.strand = rbBoth->isChecked() ? FindAlgorithmStrand_Both : (rbDirect->isChecked() ? FindAlgorithmStrand_Direct : FindAlgorithmStrand_Complement); s.complementTT = ctx->getComplementTT(); if (s.complementTT == NULL && s.strand!=FindAlgorithmStrand_Direct) { assert(0); s.strand = FindAlgorithmStrand_Both; } s.proteinTT = rbTranslation->isChecked() ? ctx->getAminoTT() : NULL; s.singleShot = singleShot; s.maxErr = getMaxErr(); s.insDelAlg = rbInsDelAlg->isChecked(); s.useAmbiguousBases = useAmbiguousBasesBox->isChecked(); //setup search region s.searchRegion = getCompleteSearchRegion(); if (singleShot) { //TODO: loosing complementary strand here! int newStartPos = sbCurrentPos->value() - 1; //visual val is +1 to the last used current s.searchRegion.length-=(newStartPos - s.searchRegion.startPos); s.searchRegion.startPos = newStartPos; } task = new FindAlgorithmTask(s); AppContext::getTaskScheduler()->registerTopLevelTask(task); updateState(); timer->start(400); } void FindDialog::sl_onTaskFinished(Task* t) { if (t != task || t->getState()!= Task::State_Finished) { return; } //todo: show message if task was canceled? importResults(); task = NULL; //TODO: show report window if not a singlShot? updateState(); timer->stop(); } void FindDialog::sl_onTimer() { importResults(); } void FindDialog::importResults() { if (task == NULL) { return; } int currentPos = task->getCurrentPos(); sbCurrentPos->setValue(currentPos + 1); QList newResults = task->popResults(); if (!newResults.empty()) { FRListItem* item = NULL; foreach(const FindAlgorithmResult& r, newResults) { item = findItem(r, lbResult); if (item==NULL) { item = new FRListItem(r); lbResult->addItem(item); } } if (task->getSettings().singleShot) { item->setSelected(true); lbResult->scrollToItem(item); sl_onResultActivated(item,false); } lbResult->setFocus(); } updateStatus(); } void FindDialog::sl_onResultActivated(QListWidgetItem* i, bool setCurPos) { assert(i); FRListItem* item = static_cast(i); DNASequenceSelection* sel = ctx->getSequenceSelection(); sel->clear(); sel->addRegion(item->res.region); if (setCurPos) { sbCurrentPos->setValue(item->res.region.startPos + 1); } ADVSingleSequenceWidget* sw = qobject_cast(ctx->getAnnotatedDNAView()->getSequenceWidgetInFocus()); if (sw!=NULL && sw->getSequenceContext() == ctx) { if (item->res.strand == U2Strand::Complementary) { sw->centerPosition(item->res.region.endPos()); } else { sw->centerPosition(item->res.region.startPos); } } //TODO: add complement info to selection!! } void FindDialog::sl_currentResultChanged(QListWidgetItem* current, QListWidgetItem* prev) { if (current==NULL || prev==NULL) { return; } FRListItem* item = static_cast(current); sbCurrentPos->setValue(item->res.region.startPos + 1); } void FindDialog::sl_onRangeToSelection() { assert(initialSelection.length!=0); sbRangeStart->setValue(initialSelection.startPos + 1); sbCurrentPos->setValue(sbRangeStart->value()); sbRangeEnd->setValue(initialSelection.endPos()); } void FindDialog::sl_onRangeToSequence() { sbRangeStart->setValue(1); sbCurrentPos->setValue(sbRangeStart->value()); sbRangeEnd->setValue(ctx->getSequenceLen()); } #define MAX_OVERLAP_K 0.5F void FindDialog::sl_onRemoveOverlaps() { int nBefore = lbResult->count(); for (int i = 0, n = lbResult->count(); i < n; i++) { FRListItem* ri = static_cast(lbResult->item(i)); for (int j=i+1; j < n; j++) { FRListItem* rj = static_cast(lbResult->item(j)); assert(rj->res.region.startPos >= ri->res.region.startPos); if (rj->res.strand != ri->res.strand) { continue; } if (rj->res.translation != ri->res.translation) { continue; } if (rj->res.translation) { U2Strand strand = rj->res.strand ; int framej = strand == U2Strand::Complementary ? rj->res.region.endPos() % 3 : rj->res.region.startPos % 3; int framei = strand == U2Strand::Complementary ? ri->res.region.endPos() % 3 : ri->res.region.startPos % 3; if (framei != framej) { continue; } } U2Region r = rj->res.region.intersect(ri->res.region); if (r.length > 0 && r.length >= MAX_OVERLAP_K * ri->res.region.length) { if (ri->res.err > ri->res.err) { delete ri; i--; break; } else { j--; delete rj; } n--; } else { break; } } } int removed = nBefore - lbResult->count(); QString message= tr("%1 overlaps filtered, %2 results left.").arg(removed).arg(lbResult->count()); statusBar->setText(message); } ////////////////////////////////////////////////////////////////////////// /// list FRListItem::FRListItem(const FindAlgorithmResult& r) : res(r) { QString yes = FindDialog::tr("yes"); QString no = FindDialog::tr("no"); setText(FindDialog::tr("[%1 %2] translation: %3 complement: %4") .arg(res.region.startPos+1) //user sees sequence from [1, end] .arg(res.region.endPos()) .arg(res.translation ? yes : no) .arg(res.strand == U2Strand::Complementary ? yes : no)); } bool FRListItem::operator< ( const QListWidgetItem & other ) const { const FRListItem& o = (const FRListItem &)other; if (o.res.region.startPos == res.region.startPos) { if (o.res.region.endPos() == res.region.endPos()) { return this > &other; } return o.res.region.endPos() > res.region.endPos(); } return o.res.region.startPos > res.region.startPos; } }//namespace ugene-1.9.8/src/corelibs/U2View/src/util_find_dialog/ui/0000755000175000017500000000000011651544334021532 5ustar ilyailyaugene-1.9.8/src/corelibs/U2View/src/util_find_dialog/ui/FindDialogUI.ui0000644000175000017500000005222111651544334024331 0ustar ilyailya FindDialogBase 0 0 703 450 0 0 0 0 32767 32767 false Find in sequence Find text pattern in sequence true 0 0 50 0 Pattern false leFind 0 0 450 0 A text pattern to find 0 0 Search in Search pattern in sequence Sequence true Search pattern in translation Translation Qt::Vertical 20 25 0 0 Strand Both true Search pattern in direct strand only Direct false Search pattern in complement strand only Complement Qt::Vertical 20 0 0 0 Algorithm true Match percent: false sbMatch true 0 0 A minimal percent to match pattern % 1 100 100 Allow mismatches only Allow mismatches only Substitute true Allow insertions and deletions Allow insertions and deletions InsDel When this option is used insertions and deletions are not supported. Search with ambiguous bases Qt::Vertical 20 0 Qt::Vertical QSizePolicy::MinimumExpanding 20 1 false 0 0 Find next result Find next true false 0 0 Find all results Find All false 0 0 Close Close Qt::Vertical QSizePolicy::MinimumExpanding 20 1 Save results as annotations Save results as annotations Save as annotations Remove overlaps 0 0 Clear results Qt::Horizontal QSizePolicy::Expanding 211 31 true 0 4 0 140 Clear results Range start: 100 0 Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter true Position: 100 0 Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter true Range end: 100 0 Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter true 99 Qt::Horizontal 1 22 Selection range Sequence range 0 0 QFrame::Panel QFrame::Sunken false leFind pbFind pbFindAll pbClose rbSequence rbTranslation rbBoth rbDirect rbComplement sbMatch rbMismatchAlg pbSaveAnnotations pbClearList lbResult sbRangeStart sbCurrentPos sbRangeEnd pbRangeToSelection pbRangeToSeq useAmbiguousBasesBox toggled(bool) rbInsDelAlg setDisabled(bool) 433 124 476 99 useAmbiguousBasesBox toggled(bool) rbMismatchAlg setDisabled(bool) 433 124 390 99 useAmbiguousBasesBox toggled(bool) rbMismatchAlg setChecked(bool) 433 124 390 99 ugene-1.9.8/src/corelibs/U2View/src/util_dna_assembly/0000755000175000017500000000000011651544334021317 5ustar ilyailyaugene-1.9.8/src/corelibs/U2View/src/util_dna_assembly/DnaAssemblyDialog.cpp0000644000175000017500000002577111651544334025361 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include #include #include #include #include #include #include #include #include #include #include "DnaAssemblyDialog.h" #include "DnaAssemblyGUIExtension.h" namespace U2 { QStringList DnaAssemblyDialog::lastShortReadsUrls; QString DnaAssemblyDialog::lastRefSeqUrl; QString DnaAssemblyDialog::methodName; bool DnaAssemblyDialog::prebuiltIndex = false; bool DnaAssemblyDialog::samOutput = false; DnaAssemblyDialog::DnaAssemblyDialog(QWidget* p, const QStringList& shortReadsUrls, const QString& refSeqUrl) : QDialog(p), assemblyRegistry(AppContext::getDnaAssemblyAlgRegistry()), customGUI(NULL) { setupUi(this); QStringList names = assemblyRegistry->getRegisteredAlgorithmIds(); methodNamesBox->addItems(names); // TODO: change the way default method is set if (names.size() > 0) { int res = -1; if (!methodName.isEmpty()) { res = methodNamesBox->findText(methodName); } if (-1 == res) { methodNamesBox->setCurrentIndex(names.size() - 1); } else { methodNamesBox->setCurrentIndex(res); } } shortReadsList->installEventFilter(this); prebuiltIndexCheckBox->setChecked(prebuiltIndex); sl_onAlgorithmChanged(methodNamesBox->currentText()); sl_onPrebuiltIndexBoxClicked(); connect(addShortreadsButton, SIGNAL(clicked()), SLOT(sl_onAddShortReadsButtonClicked()) ); connect(removeShortReadsButton, SIGNAL(clicked()), SLOT(sl_onRemoveShortReadsButtonClicked())); connect(setResultFileNameButton, SIGNAL(clicked()), SLOT(sl_onSetResultFileNameButtonClicked())); connect(addRefButton, SIGNAL(clicked()), SLOT(sl_onAddRefButtonClicked()) ); connect(methodNamesBox, SIGNAL(currentIndexChanged(const QString &)), SLOT(sl_onAlgorithmChanged(const QString &))); connect(prebuiltIndexCheckBox, SIGNAL(clicked()), SLOT(sl_onPrebuiltIndexBoxClicked())); connect(samBox, SIGNAL(clicked()), SLOT(sl_onSamBoxClicked())); QString activeRefSeqUrl = refSeqUrl.isEmpty() ? lastRefSeqUrl : refSeqUrl; if (!activeRefSeqUrl.isEmpty()) { refSeqEdit->setText(activeRefSeqUrl); buildResultUrl(activeRefSeqUrl); if (NULL != customGUI) { QString error; customGUI->buildIndexUrl(lastRefSeqUrl, prebuiltIndex, error); //todo: process error! } } QStringList activeShortReadsUrl = shortReadsUrls.isEmpty() ? lastShortReadsUrls : shortReadsUrls; foreach(const QString& read, activeShortReadsUrl) { shortReadsList->addItem(read); } } void DnaAssemblyDialog::updateState() { addGuiExtension(); } void DnaAssemblyDialog::sl_onAddShortReadsButtonClicked() { LastOpenDirHelper lod; QStringList fileNames = QFileDialog::getOpenFileNames(this, tr("Add short reads"), lod.dir); if (fileNames.isEmpty()) { return; } lod.url = fileNames.at(fileNames.count() - 1); foreach(const QString& f, fileNames) { shortReadsList->addItem(f); } } void DnaAssemblyDialog::sl_onAddRefButtonClicked() { LastOpenDirHelper lod; QString filter; lod.url = QFileDialog::getOpenFileName(this, tr("Open reference sequence"), lod.dir, filter); if (lod.url.isEmpty()) { return; } refSeqEdit->setText(lod.url); buildResultUrl(lod.url); if (NULL != customGUI) { QString error; if (!customGUI->buildIndexUrl(lod.url, prebuiltIndex, error)) { QMessageBox::information(this, "DNA Assembly", error); } } } void DnaAssemblyDialog::accept() { if (NULL != customGUI) { QString error; if (!customGUI->isParametersOk(error)) { QMessageBox::information(this, tr("DNA Assembly"), error); return; } if (!customGUI->isIndexOk(error, refSeqEdit->text())) { if (!prebuiltIndex) { QMessageBox::StandardButton res = QMessageBox::warning(this, tr("DNA Assembly"), error, QMessageBox::Ok | QMessageBox::Cancel); if (QMessageBox::Cancel == res) { return; } } else { QMessageBox::information(this, tr("DNA Assembly"), error); return; } } } if (refSeqEdit->text().isEmpty()) { QMessageBox::information(this, tr("DNA Assembly"), tr("Reference sequence url is not set!") ); } else if (resultFileNameEdit->text().isEmpty() ) { QMessageBox::information(this, tr("DNA Assembly"), tr("Result alignment file name is not set!") ); } else if (shortReadsList->count() == 0 ) { QMessageBox::information(this, tr("DNA Assembly"), tr("Short reads list is empty!") ); } else { lastRefSeqUrl.clear(); lastShortReadsUrls.clear(); lastRefSeqUrl = refSeqEdit->text(); int numItems = shortReadsList->count(); for( int i =0; i < numItems; ++i) { lastShortReadsUrls.append(shortReadsList->item(i)->text()); } QDialog::accept(); } } const GUrl DnaAssemblyDialog::getRefSeqUrl() { return refSeqEdit->text(); } const QList DnaAssemblyDialog::getShortReadUrls() { QList urls; int numItems = shortReadsList->count(); for( int i =0; i < numItems; ++i) { urls.append(shortReadsList->item(i)->text()); } return urls; } const QString DnaAssemblyDialog::getAlgorithmName() { return methodNamesBox->currentText(); } void DnaAssemblyDialog::sl_onRemoveShortReadsButtonClicked() { int currentRow = shortReadsList->currentRow(); shortReadsList->takeItem(currentRow); } void DnaAssemblyDialog::sl_onSetResultFileNameButtonClicked() { LastOpenDirHelper lod; lod.url = QFileDialog::getSaveFileName(this, tr("Set result alignment file name"), lod.dir); if (!lod.url.isEmpty()) { GUrl result = lod.url; buildResultUrl(result); } } void DnaAssemblyDialog::sl_onAlgorithmChanged(const QString &text) { methodName = text; updateState(); } void DnaAssemblyDialog::sl_onPrebuiltIndexBoxClicked() { prebuiltIndex = prebuiltIndexCheckBox->isChecked(); if (customGUI != NULL) { customGUI->prebuiltIndex(prebuiltIndex); if (refSeqEdit->text().isEmpty()) { return; } QString error; if (!customGUI->buildIndexUrl(refSeqEdit->text(), prebuiltIndex, error)) { QMessageBox::information(this, "DNA Assembly", error); } } } void DnaAssemblyDialog::sl_onSamBoxClicked() { samOutput = samBox->isChecked(); if (!refSeqEdit->text().isEmpty()) { buildResultUrl(refSeqEdit->text()); } } const QString DnaAssemblyDialog::getResultFileName() { return resultFileNameEdit->text(); } bool DnaAssemblyDialog::isPrebuiltIndex() const { return prebuiltIndexCheckBox->isChecked(); } bool DnaAssemblyDialog::isSamOutput() const { return samBox->isChecked(); } QMap DnaAssemblyDialog::getCustomSettings() { if (customGUI != NULL) { return customGUI->getDnaAssemblyCustomSettings(); } else { return QMap(); } } void DnaAssemblyDialog::addGuiExtension() { static const int insertPos = verticalLayout->count() - 2; // cleanup previous extension if (customGUI != NULL) { layout()->removeWidget(customGUI); setMinimumHeight(minimumHeight() - customGUI->minimumHeight()); delete customGUI; customGUI = NULL; } // insert new extension widget DnaAssemblyAlgorithmEnv* env = assemblyRegistry->getAlgorithm(methodNamesBox->currentText()); if (NULL == env) { adjustSize(); return; } if (!env->isDbiSupported()) { samBox->setChecked(true); samBox->setEnabled(false); if (!samOutput) { samOutput = true; sl_onSamBoxClicked(); } } else { samBox->setEnabled(true); } DnaAssemblyGUIExtensionsFactory* gui = env->getGUIExtFactory(); if (gui!=NULL && gui->hasMainWidget()) { customGUI = gui->createMainWidget(this); int extensionMinWidth = customGUI->sizeHint().width(); int extensionMinHeight = customGUI->sizeHint().height(); customGUI->setMinimumWidth(extensionMinWidth); customGUI->setMinimumHeight(extensionMinHeight); verticalLayout->insertWidget(insertPos, customGUI); // adjust sizes setMinimumHeight(customGUI->minimumHeight() + minimumHeight()); if (minimumWidth() < customGUI->minimumWidth()) { setMinimumWidth(customGUI->minimumWidth()); }; if (!refSeqEdit->text().isEmpty()) { QString error; customGUI->buildIndexUrl(refSeqEdit->text(), prebuiltIndex, error); } customGUI->show(); } else { adjustSize(); } } void DnaAssemblyDialog::buildResultUrl(const GUrl& refUrl ) { QByteArray extension; if (samOutput) { extension = "sam"; } else { extension = "ugenedb"; } QString tmpUrl = QString(refUrl.dirPath() + "/" + refUrl.baseFileName()+ ".%1").arg(extension.constData()); GUrl url = GUrlUtils::rollFileName(tmpUrl, DocumentUtils::getNewDocFileNameExcludesHint()); resultFileNameEdit->setText(url.getURLString()); } bool DnaAssemblyDialog::eventFilter( QObject * obj, QEvent * event ) { if (obj == shortReadsList) { if (event->type() == QEvent::KeyPress) { QKeyEvent *keyEvent = static_cast(event); if (keyEvent->key() == Qt::Key_Delete) { sl_onRemoveShortReadsButtonClicked(); } return true; } else { return false; } } else { // pass the event on to the parent class return QDialog::eventFilter(obj, event); } } void DnaAssemblyGUIUtils::runAssembly2ReferenceDialog(const QStringList& shortReadUrls, const QString& refSeqUrl) { DnaAssemblyDialog d(QApplication::activeWindow(), shortReadUrls, refSeqUrl); d.exec(); } } // U2 ugene-1.9.8/src/corelibs/U2View/src/util_dna_assembly/BuildIndexDialog.cpp0000644000175000017500000001316511651544334025200 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "BuildIndexDialog.h" #include "DnaAssemblyGUIExtension.h" #include #include #include #include #include #include namespace U2 { QString BuildIndexDialog::genomePath; BuildIndexDialog::BuildIndexDialog(const DnaAssemblyAlgRegistry* registry, QWidget* p) : QDialog(p), assemblyRegistry(registry), customGUI(NULL) { setupUi(this); QStringList names = registry->getRegisteredAlgorithmsWithIndexFileSupport(); methodNamesBox->addItems(names); // TODO: change the way default method is set if (names.size() > 0) { methodNamesBox->setCurrentIndex(names.size() - 1); } sl_onAlgorithmChanged(methodNamesBox->currentText()); connect(setIndexFileNameButton, SIGNAL(clicked()), SLOT(sl_onSetIndexFileNameButtonClicked())); connect(addRefButton, SIGNAL(clicked()), SLOT(sl_onAddRefButtonClicked()) ); connect(methodNamesBox, SIGNAL(currentIndexChanged(const QString &)), SLOT(sl_onAlgorithmChanged(const QString &))); if (!genomePath.isEmpty()) { refSeqEdit->setText(genomePath); buildIndexUrl(genomePath); } } void BuildIndexDialog::sl_onAddRefButtonClicked() { LastOpenDirHelper lod; QString filter; lod.url = QFileDialog::getOpenFileName(this, tr("Open reference sequence"), lod.dir, filter); if (lod.url.isEmpty()) { return; } refSeqEdit->setText(lod.url); buildIndexUrl(lod.url); } void BuildIndexDialog::sl_onSetIndexFileNameButtonClicked() { LastOpenDirHelper lod; lod.url = QFileDialog::getSaveFileName(this, tr("Set index file name"), lod.dir); if (!lod.url.isEmpty()) { GUrl index = lod.url; if (index.lastFileSuffix().isEmpty() && customGUI != NULL) { QString extension = customGUI->getIndexFileExtension(); if (extension.isEmpty()) { index = QString( "%1" ).arg( index.getURLString() ); } else { index = QString( "%1.%2" ).arg( index.getURLString() ).arg(extension); } } indexFileNameEdit->setText(index.getURLString()); } } void BuildIndexDialog::sl_onAlgorithmChanged(const QString &) { updateState(); } void BuildIndexDialog::updateState() { addGuiExtension(); } void BuildIndexDialog::addGuiExtension() { int insertPos = verticalLayout->count() - 2; // cleanup previous extension if (customGUI != NULL) { layout()->removeWidget(customGUI); setMinimumHeight(minimumHeight() - customGUI->minimumHeight()); delete customGUI; customGUI = NULL; } // insert new extension widget DnaAssemblyAlgorithmEnv* env = assemblyRegistry->getAlgorithm(methodNamesBox->currentText()); if (NULL == env) { adjustSize(); return; } DnaAssemblyGUIExtensionsFactory* gui = env->getGUIExtFactory(); if (gui!=NULL && gui->hasBuildIndexWidget()) { customGUI = gui->createBuildIndexWidget(this); int extensionMinWidth = customGUI->sizeHint().width(); int extensionMinHeight = customGUI->sizeHint().height(); customGUI->setMinimumWidth(extensionMinWidth); customGUI->setMinimumHeight(extensionMinHeight); verticalLayout->insertWidget(insertPos, customGUI); // adjust sizes setMinimumHeight(customGUI->minimumHeight() + minimumHeight()); if (minimumWidth() < customGUI->minimumWidth()) { setMinimumWidth(customGUI->minimumWidth()); } if (!refSeqEdit->text().isEmpty()) { buildIndexUrl(refSeqEdit->text()); } customGUI->show(); } else { adjustSize(); } } void BuildIndexDialog::buildIndexUrl(const GUrl& refUrl ) { QString extension(""); if (NULL != customGUI) { extension = customGUI->getIndexFileExtension(); customGUI->buildIndexUrl(refUrl); } GUrl url; if (extension.isEmpty()) { url = GUrlUtils::rollFileName(refUrl.dirPath() + "/" + refUrl.baseFileName(), DocumentUtils::getNewDocFileNameExcludesHint()); } else { url = GUrlUtils::rollFileName(refUrl.dirPath() + "/" + refUrl.baseFileName()+ "." + extension, DocumentUtils::getNewDocFileNameExcludesHint()); } indexFileNameEdit->setText(url.getURLString()); } void BuildIndexDialog::accept() { if (refSeqEdit->text().isEmpty()) { QMessageBox::information(this, tr("Build index"), tr("Reference sequence url is not set!") ); } else if (indexFileNameEdit->text().isEmpty() ) { QMessageBox::information(this, tr("Build index"), tr("Index file name is not set!") ); } else { genomePath.clear(); genomePath = refSeqEdit->text(); QDialog::accept(); } } const GUrl BuildIndexDialog::getRefSeqUrl() { return refSeqEdit->text(); } const QString BuildIndexDialog::getAlgorithmName() { return methodNamesBox->currentText(); } const QString BuildIndexDialog::getIndexFileName() { return indexFileNameEdit->text(); } QMap BuildIndexDialog::getCustomSettings() { if (customGUI != NULL) { return customGUI->getBuildIndexCustomSettings(); } else { return QMap(); } } }//namespace ugene-1.9.8/src/corelibs/U2View/src/util_dna_assembly/DnaAssemblyGUIExtension.h0000644000175000017500000000474311651544334026144 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_DNA_ASSEMBLEY_GUI_EXTENSION_H_ #define _U2_DNA_ASSEMBLEY_GUI_EXTENSION_H_ #include #include #include #include namespace U2 { // These classes are intended for extending standard Dna Assembly dialog GUI // with options specific to the assembly algorithm class DnaAssemblyAlgorithmMainWidget : public QWidget { public: DnaAssemblyAlgorithmMainWidget(QWidget* parent) : QWidget(parent) {} virtual QMap getDnaAssemblyCustomSettings() = 0; virtual bool isParametersOk(QString &error) = 0; virtual bool buildIndexUrl(const GUrl&, bool, QString &) {return true;}; virtual void prebuiltIndex(bool) {}; virtual bool isIndexOk(QString &, GUrl) {return true;}; }; class DnaAssemblyAlgorithmBuildIndexWidget : public QWidget { public: DnaAssemblyAlgorithmBuildIndexWidget(QWidget* parent) : QWidget(parent) {} virtual QMap getBuildIndexCustomSettings() = 0; virtual QString getIndexFileExtension() = 0; virtual void buildIndexUrl(const GUrl& url) = 0; }; class DnaAssemblyGUIExtensionsFactory { public: virtual DnaAssemblyAlgorithmMainWidget* createMainWidget(QWidget* parent) = 0; virtual DnaAssemblyAlgorithmBuildIndexWidget* createBuildIndexWidget(QWidget* parent) = 0; virtual bool hasMainWidget() = 0; virtual bool hasBuildIndexWidget() = 0; }; class U2VIEW_EXPORT DnaAssemblyGUIUtils : public QObject { public: static void runAssembly2ReferenceDialog(const QStringList& shortReadUrls = QStringList(), const QString& refSeqUrl = QString()); }; } // U2 #endif // _U2_DNA_ASSEMBLEY_GUI_EXTENSION_H_ ugene-1.9.8/src/corelibs/U2View/src/util_dna_assembly/ui/0000755000175000017500000000000011651544334021734 5ustar ilyailyaugene-1.9.8/src/corelibs/U2View/src/util_dna_assembly/ui/AssemblyToSamDialog.ui0000644000175000017500000000531311651544334026140 0ustar ilyailya AssemblyToSamDialog Qt::NonModal 0 0 430 100 430 100 430 100 Convert UGENE assembly data base to SAM format Assembly data base: ... Result SAM file: ... Qt::Horizontal 40 20 Convert Cancel ugene-1.9.8/src/corelibs/U2View/src/util_dna_assembly/ui/AssemblyToRefDialog.ui0000644000175000017500000001653111651544334026140 0ustar ilyailya AssemblyToRefDialog 0 0 430 350 430 350 Align short reads Select a method to align short reads. Align short reads method Select required align short reads method Qt::Vertical QSizePolicy::Fixed 20 15 Select a DNA sequence to align short reads to. This parameter is <b>required</b>. Reference sequence false ... Select the file in SAM format to write the result of alignment into. This parameter is <b>required</b>. Result file name true ... Use an index file instead of a source reference sequence. Prebuilt index Qt::Horizontal 40 20 SAM output Add short reads here. <b>At least one read</b> should be presented. Short reads 0 0 Add short reads here. <b>At least one read</b> should be presented. Qt::Horizontal 40 20 Add Remove Qt::Vertical QSizePolicy::Fixed 20 15 Qt::Horizontal 40 20 Start Cancel cancelButton clicked() AssemblyToRefDialog reject() 473 470 229 186 assembleyButton clicked() AssemblyToRefDialog accept() 390 470 229 186 ugene-1.9.8/src/corelibs/U2View/src/util_dna_assembly/ui/BuildIndexFromRefDialog.ui0000644000175000017500000001324511651544334026730 0ustar ilyailya BuildIndexFromRefDialog 0 0 498 170 430 170 16777215 170 Build index Select a method that would be used to align short reads. Align short reads method Select a method that would be used to align short reads. Qt::Vertical 409 15 Select a DNA sequence that would be used to align short reads to. This parameter is <b>required</b>. Reference sequence Select a DNA sequence that would be used to align short reads to. This parameter is <b>required</b>. false ... Specify the index to build for the reference sequence. This parameter is <b>required</b>. Index file name Specify the index to build for the reference sequence. This parameter is <b>required</b>. true ... Qt::Vertical 409 15 Qt::Horizontal 40 20 Start Cancel buildButton clicked() BuildIndexFromRefDialog accept() 437 164 35 129 cancelButton clicked() BuildIndexFromRefDialog reject() 518 164 245 153 ugene-1.9.8/src/corelibs/U2View/src/util_dna_assembly/BuildIndexDialog.h0000644000175000017500000000351711651544334024645 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_BUILD_INDEX_DIALOG_H_ #define _U2_BUILD_INDEX_DIALOG_H_ #include #include #include namespace U2 { class DnaAssemblyAlgRegistry; class DnaAssemblyAlgorithmBuildIndexWidget; class BuildIndexDialog : public QDialog, private Ui::BuildIndexFromRefDialog { Q_OBJECT public: BuildIndexDialog(const DnaAssemblyAlgRegistry* registry, QWidget* p = NULL); const GUrl getRefSeqUrl(); const QString getAlgorithmName(); const QString getIndexFileName(); QMap getCustomSettings(); private: const DnaAssemblyAlgRegistry *assemblyRegistry; DnaAssemblyAlgorithmBuildIndexWidget *customGUI; static QString genomePath; void buildIndexUrl(const GUrl& url); void updateState(); void addGuiExtension(); void accept(); private slots: void sl_onAddRefButtonClicked(); void sl_onSetIndexFileNameButtonClicked(); void sl_onAlgorithmChanged(const QString &text); }; } // namespace #endif // _U2_BUILD_INDEX_DIALOG_H_ ugene-1.9.8/src/corelibs/U2View/src/util_dna_assembly/ConvertAssemblyToSamDialog.cpp0000644000175000017500000000753211651544334027236 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include #include #include #include #include #include #include "ConvertAssemblyToSamDialog.h" namespace U2 { GUrl ConvertAssemblyToSamDialog::dbFileUrl; ConvertAssemblyToSamDialog::ConvertAssemblyToSamDialog(QWidget* parent, QString dbPath) : QDialog(parent) { ui = new Ui_AssemblyToSamDialog; ui->setupUi(this); connect(ui->setDbPathButton, SIGNAL(clicked()), SLOT(sl_onSetDbPathButtonClicked())); connect(ui->setSamPathButton, SIGNAL(clicked()), SLOT(sl_onSetSamPathButtonClicked())); connect(ui->convertButton, SIGNAL(clicked()), SLOT(accept())); connect(ui->cancelButton, SIGNAL(clicked()), SLOT(reject())); if ("" != dbPath) { ui->dbPathEdit->setText(dbPath); ui->dbPathEdit->setReadOnly(true); ui->setDbPathButton->setEnabled(false); buildSamUrl(dbPath); return; } if (!dbFileUrl.isEmpty()) { ui->dbPathEdit->setText(dbFileUrl.getURLString()); buildSamUrl(dbFileUrl); } } void ConvertAssemblyToSamDialog::accept() { if (ui->dbPathEdit->text().isEmpty()) { QMessageBox::information(this, tr("Data base to SAM converter"), tr("Data base file url is not set!") ); } else if (ui->samPathEdit->text().isEmpty()) { QMessageBox::information(this, tr("Data base to SAM converter"), tr("SAM file url is not set!") ); } else { if (ui->setDbPathButton->isEnabled()) { dbFileUrl = getDbFileUrl(); } QDialog::accept(); } } void ConvertAssemblyToSamDialog::reject() { if (ui->setDbPathButton->isEnabled() && !ui->dbPathEdit->text().isEmpty()) { dbFileUrl = getDbFileUrl(); } QDialog::reject(); } void ConvertAssemblyToSamDialog::buildSamUrl(const GUrl &dbUrl) { GUrl url = GUrlUtils::rollFileName(dbUrl.dirPath() + "/" + dbUrl.baseFileName()+ ".sam", DocumentUtils::getNewDocFileNameExcludesHint()); ui->samPathEdit->setText(url.getURLString()); } void ConvertAssemblyToSamDialog::sl_onSetDbPathButtonClicked() { LastOpenDirHelper lod; QString filter; lod.url = QFileDialog::getOpenFileName(this, tr("Open an assembly data base file"), lod.dir, filter); if (lod.url.isEmpty()) { return; } ui->dbPathEdit->setText(lod.url); buildSamUrl(lod.url); } void ConvertAssemblyToSamDialog::sl_onSetSamPathButtonClicked() { LastOpenDirHelper lod; lod.url = QFileDialog::getSaveFileName(this, tr("Set a result SAM file name"), lod.dir); if (!lod.url.isEmpty()) { GUrl result = lod.url; if (result.lastFileSuffix().isEmpty()) { result = QString( "%1.sam" ).arg( result.getURLString() ); } ui->samPathEdit->setText(result.getURLString()); } } const GUrl ConvertAssemblyToSamDialog::getDbFileUrl() { return ui->dbPathEdit->text(); } const GUrl ConvertAssemblyToSamDialog::getSamFileUrl() { return ui->samPathEdit->text(); } } // U2 ugene-1.9.8/src/corelibs/U2View/src/util_dna_assembly/DnaAssemblyUtils.cpp0000644000175000017500000001211211651544334025243 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "DnaAssemblyUtils.h" #include "DnaAssemblyDialog.h" #include "BuildIndexDialog.h" #include "ConvertAssemblyToSamDialog.h" namespace U2 { DnaAssemblySupport::DnaAssemblySupport() { QMenu *toolsMenu = AppContext::getMainWindow()->getTopLevelMenu( MWMENU_TOOLS ); QMenu *dnaAssemblySub = toolsMenu->addMenu(QIcon( ":core/images/align.png" ), tr("DNA assembly")); dnaAssemblySub->setObjectName(MWMENU_TOOLS_ASSEMBLY); QAction* dnaAssemblyAction = new QAction( tr("Align short reads..."), this ); dnaAssemblyAction->setIcon(QIcon(":core/images/align.png")); connect( dnaAssemblyAction, SIGNAL( triggered() ), SLOT( sl_showDnaAssemblyDialog() ) ); dnaAssemblySub->addAction( dnaAssemblyAction ); QAction* buildIndexAction = new QAction( tr("Build index..."), this ); buildIndexAction->setIcon(QIcon(":core/images/align.png")); connect( buildIndexAction, SIGNAL( triggered() ), SLOT( sl_showBuildIndexDialog() ) ); dnaAssemblySub->addAction( buildIndexAction ); QAction* convertAssemblyToSamAction = new QAction( tr("Convert UGENE Assembly data base to SAM format..."), this ); convertAssemblyToSamAction->setIcon(QIcon(":core/images/align.png")); connect( convertAssemblyToSamAction, SIGNAL( triggered() ), SLOT( sl_showConvertToSamDialog() ) ); dnaAssemblySub->addAction( convertAssemblyToSamAction ); } void DnaAssemblySupport::sl_showDnaAssemblyDialog() { DnaAssemblyAlgRegistry* registry = AppContext::getDnaAssemblyAlgRegistry(); if (registry->getRegisteredAlgorithmIds().isEmpty()) { QMessageBox::information(QApplication::activeWindow(), tr("DNA Assembly"), tr("There are no algorithms for DNA assembly available.\nPlease, check your plugin list.") ); return; } DnaAssemblyDialog dlg(QApplication::activeWindow()); if (dlg.exec()) { DnaAssemblyToRefTaskSettings s; s.samOutput = dlg.isSamOutput(); s.refSeqUrl = dlg.getRefSeqUrl(); s.algName = dlg.getAlgorithmName(); s.resultFileName = dlg.getResultFileName(); s.setCustomSettings( dlg.getCustomSettings() ); s.shortReadUrls = dlg.getShortReadUrls(); s.prebuiltIndex = dlg.isPrebuiltIndex(); s.openView = true; Task* assemblyTask = new DnaAssemblyMultiTask(s, true); AppContext::getTaskScheduler()->registerTopLevelTask(assemblyTask); } } void DnaAssemblySupport::sl_showBuildIndexDialog() { DnaAssemblyAlgRegistry* registry = AppContext::getDnaAssemblyAlgRegistry(); if (registry->getRegisteredAlgorithmIds().isEmpty()) { QMessageBox::information(QApplication::activeWindow(), tr("DNA Assembly"), tr("There are no algorithms for DNA assembly available.\nPlease, check your plugin list.") ); return; } BuildIndexDialog dlg(registry, QApplication::activeWindow()); if (dlg.exec()) { DnaAssemblyToRefTaskSettings s; s.refSeqUrl = dlg.getRefSeqUrl(); s.algName = dlg.getAlgorithmName(); s.resultFileName = dlg.getIndexFileName(); s.indexFileName = dlg.getIndexFileName(); s.setCustomSettings( dlg.getCustomSettings() ); s.openView = false; s.prebuiltIndex = false; Task* assemblyTask = new DnaAssemblyMultiTask(s, false, true); AppContext::getTaskScheduler()->registerTopLevelTask(assemblyTask); } } void DnaAssemblySupport::sl_showConvertToSamDialog() { ConvertAssemblyToSamDialog dlg(QApplication::activeWindow()); if (dlg.exec()) { Task *convertTask = new ConvertAssemblyToSamTask(dlg.getDbFileUrl(), dlg.getSamFileUrl()); AppContext::getTaskScheduler()->registerTopLevelTask(convertTask); } } } // U2 ugene-1.9.8/src/corelibs/U2View/src/util_dna_assembly/DnaAssemblyDialog.h0000644000175000017500000000475211651544334025022 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_DNA_ASSEMBLEY_DIALOG_H_ #define _U2_DNA_ASSEMBLEY_DIALOG_H_ #include #include #include #include namespace U2 { class DnaAssemblyAlgRegistry; class DnaAssemblyAlgorithmMainWidget; class DnaAssemblyDialog : public QDialog, private Ui::AssemblyToRefDialog { Q_OBJECT public: DnaAssemblyDialog(QWidget* p = NULL, const QStringList& shortReadsUrls = QStringList(), const QString& refSeqUrl = QString()); const GUrl getRefSeqUrl(); const QList getShortReadUrls(); const QString getAlgorithmName(); const QString getResultFileName(); bool isPrebuiltIndex() const; bool isSamOutput() const; QMap getCustomSettings(); protected: bool eventFilter(QObject *, QEvent *); private slots: void sl_onAddRefButtonClicked(); void sl_onAddShortReadsButtonClicked(); void sl_onRemoveShortReadsButtonClicked(); void sl_onSetResultFileNameButtonClicked(); void sl_onAlgorithmChanged(const QString &text); void sl_onPrebuiltIndexBoxClicked(); void sl_onSamBoxClicked(); private: void updateState(); void addGuiExtension(); void buildResultUrl(const GUrl& url); void accept(); const DnaAssemblyAlgRegistry* assemblyRegistry; DnaAssemblyAlgorithmMainWidget* customGUI; static QString lastRefSeqUrl; static QStringList lastShortReadsUrls; static QString methodName; static bool prebuiltIndex; static bool samOutput; }; } // namespace #endif // _U2_DNA_ASSEMBLEY_DIALOG_H_ ugene-1.9.8/src/corelibs/U2View/src/util_dna_assembly/DnaAssemblyUtils.h0000644000175000017500000000327511651544334024722 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_DNA_ASSEMBLEY_UTILS_H_ #define _U2_DNA_ASSEMBLEY_UTILS_H_ #include namespace U2 { class DnaAssemblyToRefTaskSettings; class U2VIEW_EXPORT DnaAssemblySupport : public QObject { Q_OBJECT public: DnaAssemblySupport(); private slots: void sl_showDnaAssemblyDialog(); void sl_showBuildIndexDialog(); void sl_showConvertToSamDialog(); }; // class DnaAssemblyLoadShortReadsTask : public Task { // Q_OBJECT // public: // DnaAssemblyLoadShortReadsTask(DnaAssemblyToRefTaskSettings& settings, const QList& shortReads); // virtual void prepare(); // QList onSubTaskFinished(Task* subTask); // QList& shortReads; // }; } // U2 #endif // _U2_DNA_ASSEMBLEY_TASK_H_ ugene-1.9.8/src/corelibs/U2View/src/util_dna_assembly/ConvertAssemblyToSamDialog.h0000644000175000017500000000305611651544334026700 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_CONVERT_ASSEMBLY_TO_SAM_DIALOG_H_ #define _U2_CONVERT_ASSEMBLY_TO_SAM_DIALOG_H_ #include #include class Ui_AssemblyToSamDialog; namespace U2 { class U2VIEW_EXPORT ConvertAssemblyToSamDialog : public QDialog { Q_OBJECT public: ConvertAssemblyToSamDialog(QWidget* parent = NULL, QString dbPath = ""); const GUrl getDbFileUrl(); const GUrl getSamFileUrl(); private slots: void sl_onSetDbPathButtonClicked(); void sl_onSetSamPathButtonClicked(); void accept(); void reject(); private: Ui_AssemblyToSamDialog *ui; void buildSamUrl(const GUrl &dbUrl); static GUrl dbFileUrl; }; } // U2 #endif // _U2_CONVERT_ASSEMBLY_TO_SAM_DIALOG_H_ ugene-1.9.8/src/corelibs/U2View/src/util_sec_struct_predict/0000755000175000017500000000000011651544334022546 5ustar ilyailyaugene-1.9.8/src/corelibs/U2View/src/util_sec_struct_predict/SecStructPredictUtils.cpp0000644000175000017500000001013011651544334027520 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include #include #include #include #include #include #include #include "SecStructDialog.h" #include "SecStructPredictUtils.h" namespace U2 { SecStructPredictViewAction::SecStructPredictViewAction(AnnotatedDNAView* v) : ADVGlobalAction(v, QIcon(":core//images//ssp_logo.png"), tr("Predict secondary structure...") ) { connect(this, SIGNAL(triggered()), SLOT(sl_execute())); addAlphabetFilter(DNAAlphabet_AMINO); } void SecStructPredictViewAction::sl_execute() { QAction* a = (QAction*)sender(); GObjectViewAction* viewAction = qobject_cast(a); AnnotatedDNAView* av = qobject_cast(viewAction->getObjectView()); Q_ASSERT(av); ADVSequenceObjectContext* seqCtx = av->getSequenceInFocus(); Q_ASSERT(seqCtx->getAlphabet()->isAmino()); //TODO: if no analysis algorithm is available? SecStructDialog secStructDialog(seqCtx, av->getWidget()); secStructDialog.exec(); } ADVGlobalAction* SecStructPredictViewAction::createAction( AnnotatedDNAView* av ) { ADVGlobalAction* action = new SecStructPredictViewAction(av); return action; } SecStructPredictViewAction::~SecStructPredictViewAction() { } QString SecStructPredictUtils::getStructNameForCharTag( char tag ) { SecondaryStructure::Type type = SecondaryStructure::Type_None; switch(tag) { case 'H': type = SecondaryStructure::Type_AlphaHelix; break; case 'G': type = SecondaryStructure::Type_310Helix; break; case 'I': type = SecondaryStructure::Type_PiHelix; break; case 'B': type = SecondaryStructure::Type_BetaBridge; break; case 'E': type = SecondaryStructure::Type_BetaStrand; break; case 'T': type = SecondaryStructure::Type_Turn; break; case 'S': type = SecondaryStructure::Type_BendRegion; break; default: Q_ASSERT(0); } return BioStruct3D::getSecStructTypeName(type); } QList SecStructPredictUtils::saveAlgorithmResultsAsAnnotations( const QByteArray& predicted, const QString& annotationName ) { char emptyCoil = 'C'; int numAcronyms = predicted.length(); QList predictedStructures; char prevChar = predicted.at(0); int lastRecordedPos = 0; for (int i = 1; i < numAcronyms; ++i) { char curChar = predicted.at(i); if ( (curChar != prevChar) || (i == numAcronyms - 1)) { if ( prevChar != emptyCoil ) { SharedAnnotationData sd( new AnnotationData); sd->name = annotationName; sd->location->regions.append(U2Region(lastRecordedPos, i - lastRecordedPos)); sd->qualifiers.append(U2Qualifier(BioStruct3D::SecStructTypeQualifierName, getStructNameForCharTag(prevChar))); predictedStructures.append(sd); } lastRecordedPos = i; } prevChar = curChar; } return predictedStructures; } } //namespace ugene-1.9.8/src/corelibs/U2View/src/util_sec_struct_predict/SecStructPredictUtils.h0000644000175000017500000000313211651544334027171 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_SEC_STRUCT_PREDICT_UTILS_H_ #define _U2_SEC_STRUCT_PREDICT_UTILS_H_ #include #include namespace U2 { class AnnotatedDNAView; class SecStructPredictViewAction: public ADVGlobalAction { Q_OBJECT public: SecStructPredictViewAction(AnnotatedDNAView* v); ~SecStructPredictViewAction(); static ADVGlobalAction* createAction(AnnotatedDNAView* view); protected slots: void sl_execute(); }; class U2VIEW_EXPORT SecStructPredictUtils { public: static QString getStructNameForCharTag(char tag); static QList saveAlgorithmResultsAsAnnotations(const QByteArray& predicted, const QString& annotationName); }; } //namespace #endif // _U2_SEC_STRUCT_PREDICT_UTILS_H_ ugene-1.9.8/src/corelibs/U2View/src/util_sec_struct_predict/ui/0000755000175000017500000000000011651544334023163 5ustar ilyailyaugene-1.9.8/src/corelibs/U2View/src/util_sec_struct_predict/ui/SecStructDialog.ui0000644000175000017500000001132111651544334026557 0ustar ilyailya SecStructDialog 0 0 439 480 Secondary Structure Prediction Algorithm Range Start: Qt::Horizontal 40 20 Range End: Qt::Horizontal 40 20 Results: Qt::Horizontal 40 20 QAbstractItemView::NoEditTriggers 0 Total predicted: 0 Qt::Horizontal 40 20 Start prediction Qt::WheelFocus Save As Annotation... Close cancelButton clicked() SecStructDialog reject() 403 544 244 283 ugene-1.9.8/src/corelibs/U2View/src/util_sec_struct_predict/SecStructDialog.cpp0000644000175000017500000001411511651544334026313 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "SecStructDialog.h" #include #include #include #include #include #include #include #include #include #include #include #include namespace U2 { SecStructDialog::SecStructDialog( ADVSequenceObjectContext* _ctx, QWidget *p ) : QDialog(p), rangeStart(0), rangeEnd(0), ctx(_ctx), task(NULL) { setupUi(this); sspr = AppContext::getSecStructPredictAlgRegistry(); algorithmComboBox->addItems(sspr->getAlgNameList()); saveAnnotationButton->setDisabled(true); U2Region initialSelection = ctx->getSequenceSelection()->isEmpty() ? U2Region() : ctx->getSequenceSelection()->getSelectedRegions().first(); int seqLen = ctx->getSequenceLen(); rangeStartSpinBox->setMinimum(1); rangeStartSpinBox->setMaximum(seqLen); rangeEndSpinBox->setMinimum(1); rangeEndSpinBox->setMaximum(seqLen); rangeStartSpinBox->setValue(initialSelection.isEmpty() ? 1 : initialSelection.startPos + 1); rangeEndSpinBox->setValue(initialSelection.isEmpty() ? seqLen : initialSelection.endPos()); resultsTable->setColumnCount(2); QStringList headerNames; headerNames.append(tr("Region")); headerNames.append(tr("Structure Type")); resultsTable->setHorizontalHeaderLabels(headerNames); resultsTable->horizontalHeader()->setStretchLastSection(true); connect(AppContext::getTaskScheduler(), SIGNAL(si_stateChanged(Task*)), SLOT(sl_onTaskFinished(Task*))); connectGUI(); } void SecStructDialog::connectGUI() { connect(rangeStartSpinBox, SIGNAL(valueChanged(int)), this, SLOT(sl_spinRangeStartChanged(int))); connect(rangeEndSpinBox, SIGNAL(valueChanged(int)), this, SLOT(sl_spinRangeEndChanged(int))); connect(startButton, SIGNAL(clicked()), this, SLOT(sl_onStartPredictionClicked())); connect(saveAnnotationButton, SIGNAL(clicked()), this, SLOT(sl_onSaveAnnotations())); } void SecStructDialog::sl_spinRangeStartChanged( int val ) { if (val > rangeEndSpinBox->value()) { rangeEndSpinBox->setValue(val); } } void SecStructDialog::sl_spinRangeEndChanged( int val ) { if (val < rangeStartSpinBox->value()) { rangeStartSpinBox->setValue(val); } } void SecStructDialog::updateState() { bool haveActiveTask = task!=NULL; bool haveResults = !results.isEmpty(); algorithmComboBox->setEnabled(!haveActiveTask); startButton->setEnabled(!haveActiveTask); cancelButton->setEnabled(!haveActiveTask); saveAnnotationButton->setEnabled(haveResults); totalPredictedStatus->setText( QString("%1").arg(results.size())); showResults(); } void SecStructDialog::sl_onStartPredictionClicked() { assert(task == NULL); SecStructPredictTaskFactory* factory = sspr->getAlgorithm(algorithmComboBox->currentText()); //prepare target sequence const QByteArray & seq = ctx->getSequenceData(); rangeStart = rangeStartSpinBox->value(); rangeEnd = rangeEndSpinBox->value(); assert(rangeStart <= rangeEnd); assert(rangeStart >= 0 && rangeEnd <= seq.size() ); task = factory->createTaskInstance(seq.mid(rangeStart, rangeEnd - rangeStart)); AppContext::getTaskScheduler()->registerTopLevelTask(task); results.clear(); updateState(); } void SecStructDialog::sl_onTaskFinished( Task* t ) { if (t != task || t->getState()!= Task::State_Finished) { return; } results = task->getResults(); //shifting results according to startPos for(QMutableListIterator it_ad(results); it_ad.hasNext(); ) { AnnotationData * ad = it_ad.next().data(); U2Region::shift(rangeStart, ad->location->regions); } task = NULL; rangeStart = 0; rangeEnd = 0; updateState(); } void SecStructDialog::showResults() { int rowIndex = 0; resultsTable->setRowCount(results.size()); foreach(SharedAnnotationData data, results) { U2Region annRegion = data->getRegions().first(); QTableWidgetItem *locItem = new QTableWidgetItem( QString("[%1..%2]").arg(annRegion.startPos). arg(annRegion.endPos()) ); resultsTable->setItem(rowIndex, 0, locItem); QTableWidgetItem* nameItem = new QTableWidgetItem( QString(data->name)); resultsTable->setItem(rowIndex, 1, nameItem); ++rowIndex; } } #define SEC_STRUCT_ANNOTATION_GROUP_NAME "predicted" void SecStructDialog::sl_onSaveAnnotations() { CreateAnnotationModel m; m.sequenceObjectRef = ctx->getSequenceObject(); m.hideLocation = true; m.hideAnnotationName = true; m.data->name = SEC_STRUCT_ANNOTATION_GROUP_NAME; m.sequenceLen = ctx->getSequenceObject()->getSequenceLen(); CreateAnnotationDialog d(this, m); int rc = d.exec(); if (rc != QDialog::Accepted) { return; } CreateAnnotationsTask* t = new CreateAnnotationsTask(m.getAnnotationObject(), m.groupName, results); AppContext::getTaskScheduler()->registerTopLevelTask(t); QDialog::accept(); } } // namespace ugene-1.9.8/src/corelibs/U2View/src/util_sec_struct_predict/SecStructDialog.h0000644000175000017500000000347611651544334025770 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_EXPORT_SEC_STRUCT_DIALOG_H_ #define _U2_EXPORT_SEC_STRUCT_DIALOG_H_ #include #include namespace U2 { class ADVSequenceObjectContext; class SecStructPredictTask; class SecStructPredictAlgRegistry; class Task; class U2VIEW_EXPORT SecStructDialog : public QDialog, private Ui::SecStructDialog { Q_OBJECT public: SecStructDialog(ADVSequenceObjectContext* ctx, QWidget *p = NULL); private slots: void sl_spinRangeStartChanged(int val); void sl_spinRangeEndChanged(int val); void sl_onStartPredictionClicked(); void sl_onTaskFinished(Task*); void sl_onSaveAnnotations(); private: int rangeStart; int rangeEnd; QList results; ADVSequenceObjectContext* ctx; SecStructPredictTask* task; SecStructPredictAlgRegistry* sspr; void connectGUI(); void updateState(); void showResults(); }; } // namespace #endif // _U2_EXPORT_SEC_STRUCT_DIALOG_H_ ugene-1.9.8/src/corelibs/U2View/src/WebWindow.h0000644000175000017500000000216411651544334017702 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_WEB_WINDOW_H_ #define _U2_WEB_WINDOW_H_ #include #include namespace U2 { class U2VIEW_EXPORT WebWindow : public MWMDIWindow { Q_OBJECT public: WebWindow(const QString& title, const QString& content); }; }//namespace #endif ugene-1.9.8/src/corelibs/U2View/src/util_msa_align/0000755000175000017500000000000011651544334020610 5ustar ilyailyaugene-1.9.8/src/corelibs/U2View/src/util_msa_align/MSAAlignDialog.cpp0000644000175000017500000001045211651544334024031 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include #include #include #include #include #include #include #include #include #include #include "MSAAlignDialog.h" #include #include "MSAAlignGUIExtension.h" namespace U2 { MSAAlignDialog::MSAAlignDialog(const QString& _algorithmName, bool useFileMenu ,QWidget* p) : QDialog(p), algorithmName(_algorithmName), customGUI(NULL), algoEnv(NULL), openFileMode(useFileMenu) { ui = new Ui_performAlignmentDialog; ui->setupUi(this); if (!useFileMenu) { ui->inputLabel->setVisible(false); ui->fileNameEdit->setVisible(false); ui->browseButton->setVisible(false); } addGuiExtension(); connect(ui->browseButton, SIGNAL(clicked()), SLOT(sl_onFileNameButtonClicked())); } void MSAAlignDialog::sl_onFileNameButtonClicked() { LastOpenDirHelper lod; lod.url = QFileDialog::getOpenFileName(this, tr("Set result alignment file name"), lod.dir, DialogUtils::prepareDocumentsFileFilterByObjType(GObjectTypes::MULTIPLE_ALIGNMENT, true)); if (!lod.url.isEmpty()) { ui->fileNameEdit->setText(lod.url); } } const QString MSAAlignDialog::getAlgorithmName() { return algorithmName; } QMap MSAAlignDialog::getCustomSettings() { if (customGUI != NULL) { return customGUI->getMSAAlignCustomSettings(); } else { return QMap(); } } void MSAAlignDialog::addGuiExtension() { static const int insertPos = 1; // cleanup previous extension if (customGUI != NULL) { layout()->removeWidget(customGUI); setMinimumHeight(minimumHeight() - customGUI->minimumHeight()); delete customGUI; customGUI = NULL; } MSAAlignAlgRegistry* registry = AppContext::getMSAAlignAlgRegistry(); // insert new extension widget MSAAlignAlgorithmEnv* env = registry->getAlgorithm(algorithmName); if (env == NULL) { adjustSize(); return; } MSAAlignGUIExtensionsFactory* gui = env->getGUIExtFactory(); if (gui!=NULL && gui->hasMainWidget()) { customGUI = gui->createMainWidget(this); int extensionMinWidth = customGUI->sizeHint().width(); int extensionMinHeight = customGUI->sizeHint().height(); customGUI->setMinimumWidth(extensionMinWidth); customGUI->setMinimumHeight(extensionMinHeight); ui->globalLayout->insertWidget(insertPos, customGUI); // adjust sizes setMinimumHeight(customGUI->minimumHeight() + minimumHeight()); if (minimumWidth() < customGUI->minimumWidth()) { QMargins margins = layout()->contentsMargins(); setMinimumWidth(customGUI->minimumWidth() + margins.left() + margins.right()); }; if (!customGUI->windowTitle().isEmpty()) { setWindowTitle(customGUI->windowTitle()); } customGUI->show(); } adjustSize(); } void MSAAlignDialog::accept() { if ( openFileMode && ui->fileNameEdit->text().isEmpty() ) { QMessageBox::warning(this, windowTitle(), tr("The input file url is empty.\nPlease select file to align.")); return; } QDialog::accept(); } const QString MSAAlignDialog::getFileName() { return ui->fileNameEdit->text(); } } // U2 ugene-1.9.8/src/corelibs/U2View/src/util_msa_align/ui/0000755000175000017500000000000011651544334021225 5ustar ilyailyaugene-1.9.8/src/corelibs/U2View/src/util_msa_align/ui/PerformAlignmentDialog.ui0000644000175000017500000000742311651544334026163 0ustar ilyailya performAlignmentDialog 0 0 485 177 430 100 Align Base options Select input file: ... <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> <html><head><meta name="qrichtext" content="1" /><style type="text/css"> p, li { white-space: pre-wrap; } </style></head><body style=" font-family:'MS Shell Dlg 2'; font-size:8.25pt; font-weight:400; font-style:normal;"> <p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-size:8pt;">Translating alignment to amino allows to avoid errors of inserting gaps within codon boundaries.</span></p></body></html> Translate to amino when aligning Qt::Vertical 20 40 Qt::Horizontal QDialogButtonBox::Cancel|QDialogButtonBox::Ok buttonBox accepted() performAlignmentDialog accept() 248 254 157 274 buttonBox rejected() performAlignmentDialog reject() 316 260 286 274 ugene-1.9.8/src/corelibs/U2View/src/util_msa_align/MSAAlignDialog.h0000644000175000017500000000335211651544334023477 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_MSA_ALIGN_DIALOG_H_ #define _U2_MSA_ALIGN_DIALOG_H_ #include #include class Ui_performAlignmentDialog; namespace U2 { class MSAAlignAlgRegistry; class MSAAlignAlgorithmMainWidget; class MSAAlignAlgorithmEnv; class U2VIEW_EXPORT MSAAlignDialog: public QDialog { Q_OBJECT public: MSAAlignDialog(const QString& algorithmName, bool useFileMenu, QWidget* p = NULL); const QString getAlgorithmName(); QMap getCustomSettings(); const QString getFileName(); private slots: void sl_onFileNameButtonClicked(); private: Ui_performAlignmentDialog* ui; const QString& algorithmName; MSAAlignAlgorithmMainWidget* customGUI; MSAAlignAlgorithmEnv* algoEnv; static QString alignmentPath; bool openFileMode; void addGuiExtension(); void accept(); }; } // namespace #endif // _U2_MSA_ALIGN_DIALOG_H_ ugene-1.9.8/src/corelibs/U2View/src/util_msa_align/MSAAlignGUIExtension.h0000644000175000017500000000307511651544334024623 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_MSA_ALIGN_GUI_EXTENSION_H_ #define _U2_MSA_ALIGN_GUI_EXTENSION_H_ #include #include #include #include namespace U2 { // These classes are intended for extending standard MSA Align dialog GUI // with options specific to the align algorithm class MSAAlignAlgorithmMainWidget : public QWidget { public: MSAAlignAlgorithmMainWidget(QWidget* parent) : QWidget(parent) {} virtual QMap getMSAAlignCustomSettings() = 0; }; class MSAAlignGUIExtensionsFactory { public: virtual MSAAlignAlgorithmMainWidget* createMainWidget(QWidget* parent) = 0; virtual bool hasMainWidget() = 0; }; } // U2 #endif // _U2_MSA_ALIGN_GUI_EXTENSION_H_ ugene-1.9.8/src/corelibs/U2View/src/util_smith_waterman/0000755000175000017500000000000011651544334021700 5ustar ilyailyaugene-1.9.8/src/corelibs/U2View/src/util_smith_waterman/SubstMatrixDialog.cpp0000644000175000017500000001247511651544334026022 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "SubstMatrixDialog.h" #include #include #include namespace U2 { SubstMatrixDialog::SubstMatrixDialog(const SMatrix& _m, QWidget* p) : QDialog(p), hlBorderColumn(-1), hlBorderRow(-1), hlInnerColumn(-1), hlInnerRow(-1), m(_m) { assert(!m.isEmpty()); setupUi(this); setWindowTitle(tr("Scoring matrix: %1").arg(m.getName())); setModal(true); QString info; info+="" + tr("min score:")+" " + QString::number(m.getMinScore()) + ", "; info+="" + tr("max score:")+" " + QString::number(m.getMaxScore()) + "
    "; info+="
    " + m.getDescription() + "
    "; infoEdit->setHtml(info); connectGUI(); prepareTable(); } void SubstMatrixDialog::sl_closeWindow() { close(); } void SubstMatrixDialog::connectGUI() { connect(bttnClose, SIGNAL(clicked()), SLOT(sl_closeWindow())); connect(tableMatrix, SIGNAL(cellEntered(int, int)), SLOT(sl_mouseOnCell(int, int))); } #define CELL_WIDTH 25 #define DEFAULT_BORDER_CELL_COLOR QColor(200, 200, 200) #define HIGHLIGHT_BORDER_CELL_COLOR QColor(200, 230, 200) #define DEFAULT_INNER_CELL_COLOR QColor(255, 255, 255) #define HIGHLIGHT_INNER_CELL_COLOR QColor(200, 230, 200) void SubstMatrixDialog::prepareTable() { tableMatrix->horizontalHeader()->setHidden(true); tableMatrix->verticalHeader()->setHidden(true); QByteArray alphaChars = m.getAlphabet()->getAlphabetChars(); int n = alphaChars.size(); tableMatrix->setRowCount(n + 1); tableMatrix->setColumnCount(n + 1); QTableWidgetItem* ptwi = new QTableWidgetItem(""); Qt::ItemFlags flags = ptwi->flags(); flags &= (~Qt::ItemIsEditable); ptwi->setFlags(flags); tableMatrix->setItem(0, 0, ptwi); for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { char ch_i = alphaChars.at(i); char ch_j = alphaChars.at(j); float score = m.getScore(ch_i, ch_j); ptwi = new QTableWidgetItem(QString::number(score)); ptwi->setBackgroundColor(DEFAULT_INNER_CELL_COLOR); ptwi->setTextAlignment(Qt::AlignRight | Qt::AlignVCenter); ptwi->setFlags(flags); tableMatrix->setItem(i + 1, j + 1, ptwi); } } for (int i = 0; i < n; i++) { char ch = alphaChars.at(i); QString title(ch); ptwi = new QTableWidgetItem(title); ptwi->setBackgroundColor(DEFAULT_BORDER_CELL_COLOR); ptwi->setFlags(flags); ptwi->setTextAlignment(Qt::AlignCenter); tableMatrix->setItem(i+1, 0, ptwi); ptwi = new QTableWidgetItem(title); ptwi->setFlags(flags); ptwi->setTextAlignment(Qt::AlignCenter); ptwi->setBackgroundColor(DEFAULT_BORDER_CELL_COLOR); tableMatrix->setItem(0, i+1, ptwi); } tableMatrix->verticalHeader()->setResizeMode(QHeaderView::Stretch); tableMatrix->horizontalHeader()->setResizeMode(QHeaderView::Stretch); tableMatrix->setMinimumSize(CELL_WIDTH * (n + 1) + 20, CELL_WIDTH * (n + 1) + 20); //+20 is for borders } void SubstMatrixDialog::sl_mouseOnCell(int row, int column) { //update mid-cell if (row != 0 && column != 0 && !(column == hlInnerColumn && row == hlInnerRow)) { QTableWidgetItem* prevItem = tableMatrix->item(hlInnerRow, hlInnerColumn); if (prevItem != NULL) { prevItem->setBackgroundColor(DEFAULT_INNER_CELL_COLOR); } QTableWidgetItem* newItem = tableMatrix->item(row, column); if (newItem != NULL) { newItem->setBackgroundColor(HIGHLIGHT_INNER_CELL_COLOR); } hlInnerColumn = column; hlInnerRow = row; } //update row header if (row != hlBorderRow && row != 0) { QTableWidgetItem* pw = tableMatrix->item(row, 0); if (pw!=NULL) { pw->setBackgroundColor(HIGHLIGHT_BORDER_CELL_COLOR); } pw = tableMatrix->item(hlBorderRow, 0); if (pw!=NULL) { pw->setBackgroundColor(DEFAULT_BORDER_CELL_COLOR); } hlBorderRow = row; } //update column header if (column != hlBorderColumn && column != 0) { QTableWidgetItem* pw = tableMatrix->item(0, column); if (pw!=NULL) { pw->setBackgroundColor(HIGHLIGHT_BORDER_CELL_COLOR); } pw = tableMatrix->item(0, hlBorderColumn); if (pw != NULL) { pw->setBackgroundColor(DEFAULT_BORDER_CELL_COLOR); } hlBorderColumn = column; } } } // namespace ugene-1.9.8/src/corelibs/U2View/src/util_smith_waterman/SubstMatrixDialog.h0000644000175000017500000000275511651544334025467 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_SUBST_MATRIX_DIALOG_H_ #define _U2_SUBST_MATRIX_DIALOG_H_ #include "ui_SubstMatrixDialogBase.h" #include #include #include namespace U2 { class U2VIEW_EXPORT SubstMatrixDialog: public QDialog, public Ui::SubstMatrixDialogBase { Q_OBJECT public: SubstMatrixDialog(const SMatrix& m, QWidget* parent); private slots: void sl_closeWindow(); void sl_mouseOnCell(int row, int column); private: void connectGUI(); void prepareTable(); int hlBorderColumn; int hlBorderRow; int hlInnerColumn; int hlInnerRow; SMatrix m; }; } // namespace #endif ugene-1.9.8/src/corelibs/U2View/src/util_smith_waterman/ui/0000755000175000017500000000000011651544334022315 5ustar ilyailyaugene-1.9.8/src/corelibs/U2View/src/util_smith_waterman/ui/SmithWatermanDialogBase.ui0000644000175000017500000005302611651544334027360 0ustar ilyailya SmithWatermanDialogBase 0 0 718 435 0 0 0 0 10000 10000 Smith-Waterman Search 0 Smith-Waterman parameters Pattern 0 0 0 0 100000 500 0 0 1000 1000 Search in Qt::AlignLeading|Qt::AlignLeft|Qt::AlignVCenter false false Sequence true false true false Translation Qt::Vertical 20 2 0 0 1000 1000 Strand false Both false Direct false Complement 0 0 Range Whole sequence true Selected range Custom range false 100 0 Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter true 1 1 - false 100 0 Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter true 1 1 Smith-Waterman algorithm parameters Algorithm version 0 0 120 0 1000 1000 Qt::Horizontal 48 20 false 75 23 Advanced.. 1000 1000 Scoring matrix 0 0 120 0 1000 1000 Qt::Horizontal 47 20 false 75 23 View.. false Gap scores Gap open Gap extension -4096.000000000000000 -0.010000000000000 -4096.000000000000000 -0.010000000000000 Results filtering strategy Minimal score Qt::Horizontal 40 20 0 0 % 1 100 90 Report results 0 0 Qt::Vertical 20 95 Input and output 0 0 0 0 Qt::Vertical 20 182 verticalSpacer_2 annotationsWidget Qt::Horizontal 40 20 true Remote run... true Search Cancel radioTranslation radioComplement bttnRun bttnCancel comboMatrix bttnViewMatrix spinScorePercent bttnCancel clicked() SmithWatermanDialogBase close() 549 533 544 111 ugene-1.9.8/src/corelibs/U2View/src/util_smith_waterman/ui/SubstMatrixDialogBase.ui0000644000175000017500000000524611651544334027063 0ustar ilyailya SubstMatrixDialogBase Qt::WindowModal 0 0 519 449 0 0 0 0 0 0 Qt::Vertical false 0 100 true true 0 0 500 200 true Qt::Horizontal 40 20 Close bttnClose ugene-1.9.8/src/corelibs/U2View/src/util_smith_waterman/SmithWatermanDialogImpl.h0000644000175000017500000000533311651544334026602 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_SMITH_WATERMAN_DIALOG_IMPL_H_ #define _U2_SMITH_WATERMAN_DIALOG_IMPL_H_ #include "SmithWatermanDialog.h" #include #include #include #include #include #include #include #include namespace U2 { class SmithWatermanDialog: public QDialog, public Ui::SmithWatermanDialogBase { Q_OBJECT public: SmithWatermanDialog(QWidget* p, ADVSequenceObjectContext* ctx, SWDialogConfig* dialogConfig); private slots: void sl_bttnViewMatrix(); void sl_bttnRun(); void sl_spinRangeStartChanged(int val); void sl_spinRangeEndChanged(int val); void sl_translationToggled(bool toggled); void sl_wholeSequenceToggled(bool toggled); void sl_selectedRangeToggled(bool toggled); void sl_customRangeToggled(bool toggled); //void sl_remoteRunButtonClicked(); void sl_patternChanged(); private: void clearAll(); void loadDialogConfig(); void saveDialogConfig(); bool readParameters(); void updateVisualState(); bool readPattern(DNATranslation* aminoTT); bool readRegion(); bool readRealization(); bool readSubstMatrix(); bool readResultFilter(); bool readGapModel(); void setParameters(); void connectGUI(); void addAnnotationWidget(); SubstMatrixRegistry* substMatrixRegistry; SWResultFilterRegistry* swResultFilterRegistry; SmithWatermanTaskFactoryRegistry* swTaskFactoryRegistry; SWDialogConfig* dialogConfig; SmithWatermanSettings config; SmithWatermanTaskFactory* realization; ADVSequenceObjectContext* ctxSeq; CreateAnnotationWidgetController* ac; }; } // namespace #endif ugene-1.9.8/src/corelibs/U2View/src/util_smith_waterman/SmithWatermanDialog.cpp0000644000175000017500000004700011651544334026310 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "SmithWatermanDialog.h" #include "SmithWatermanDialogImpl.h" #include #include #include #include #include #include #include #include #include #include #include #include "SubstMatrixDialog.h" namespace U2 { SmithWatermanDialog::SmithWatermanDialog(QWidget* w, ADVSequenceObjectContext* ctx, SWDialogConfig* _dialogConfig): QDialog(w), substMatrixRegistry(0), swTaskFactoryRegistry(0) { ctxSeq = ctx; dialogConfig = _dialogConfig; setupUi(this); substMatrixRegistry = AppContext::getSubstMatrixRegistry(); if (0 == substMatrixRegistry) { coreLog.error(tr("No substitution matrices found.")); QMessageBox::critical(this, windowTitle(), tr("No substitution matrices found.")); QDialog::done(-1); return; } swResultFilterRegistry = AppContext::getSWResultFilterRegistry(); if (0 == swResultFilterRegistry) { coreLog.error(tr("No filter registry found.")); //FIXME should be optional? QDialog::done(-1); //No. return; } swTaskFactoryRegistry = AppContext::getSmithWatermanTaskFactoryRegistry(); if (0 == swTaskFactoryRegistry) { coreLog.error(tr("No algorithm registry found.")); QDialog::done(-1); return; } setParameters(); addAnnotationWidget(); connectGUI(); clearAll(); loadDialogConfig(); updateVisualState(); teditPattern->setFocus(); //! FIXME: remoteRunPushButton->setVisible(false); } void SmithWatermanDialog::connectGUI() { connect(bttnViewMatrix, SIGNAL(clicked()), SLOT(sl_bttnViewMatrix())); connect(bttnRun, SIGNAL(clicked()), SLOT(sl_bttnRun())); connect(spinRangeStart, SIGNAL(valueChanged(int)), SLOT(sl_spinRangeStartChanged(int))); connect(spinRangeEnd, SIGNAL(valueChanged(int)), SLOT(sl_spinRangeEndChanged(int))); connect(radioTranslation, SIGNAL(toggled(bool)), SLOT(sl_translationToggled(bool))); connect(radioWholeSequence, SIGNAL(toggled(bool)), SLOT(sl_wholeSequenceToggled(bool))); connect(radioSelectedRange, SIGNAL(toggled(bool)), SLOT(sl_selectedRangeToggled(bool))); connect(radioCustomRange, SIGNAL(toggled(bool)), SLOT(sl_customRangeToggled(bool))); //connect( remoteRunPushButton, SIGNAL( clicked() ), SLOT( sl_remoteRunButtonClicked() ) ); connect(teditPattern, SIGNAL(textChanged()), SLOT(sl_patternChanged())); } void SmithWatermanDialog::sl_patternChanged() { updateVisualState(); } void SmithWatermanDialog::updateVisualState() { int patternLen = teditPattern->toPlainText().length(); if (patternLen == 0) { lblPattern->setText(tr("Enter pattern here")); } else { lblPattern->setText(tr("Pattern length: %1").arg(patternLen)); } } void SmithWatermanDialog::addAnnotationWidget() { DNASequenceObject *dnaso = qobject_cast(ctxSeq->getSequenceGObject()); CreateAnnotationModel acm; acm.sequenceObjectRef = GObjectReference(dnaso); acm.hideAnnotationName = false; acm.hideLocation = true; acm.sequenceLen = dnaso->getSequenceLen(); ac = new CreateAnnotationWidgetController(acm, this); QWidget* caw = ac->getWidget(); QVBoxLayout* l = new QVBoxLayout(); l->setMargin(0); l->addWidget(caw); annotationsWidget->setLayout(l); annotationsWidget->setMinimumSize(caw->layout()->minimumSize()); } void SmithWatermanDialog::setParameters() { DNAAlphabet* alphabet = ctxSeq->getAlphabet(); QStringList matrixList = substMatrixRegistry->selectMatrixNamesByAlphabet(alphabet); if (!matrixList.isEmpty()) { bttnViewMatrix->setEnabled(true); } comboMatrix->addItems(matrixList); QStringList alg_lst = swTaskFactoryRegistry->getListFactoryNames(); comboRealization->addItems(alg_lst); QStringList filterIds = swResultFilterRegistry->getFiltersIds(); //TODO: use localized names! comboResultFilter->addItems(filterIds); int defaultFilterIndex = filterIds.indexOf(swResultFilterRegistry->getDefaultFilterId()); comboResultFilter->setCurrentIndex(defaultFilterIndex); radioSequence->setEnabled(true); radioSequence->setChecked(true); if (0 != ctxSeq->getAminoTT()) { radioTranslation->setEnabled(true); } radioDirect->setEnabled(true); if (ctxSeq->getComplementTT() != NULL) { radioComplement->setEnabled(true); radioBoth->setEnabled(true); radioBoth->setChecked(true); } else { radioDirect->setChecked(true); } spinScorePercent->setValue(DEF_PERCENT_OF_SCORE); dblSpinGapOpen->setValue(DEF_GAP_OPEN_SCORE); dblSpinGapExtd->setValue(DEF_GAP_EXTD_SCORE); bool hasSelection = !ctxSeq->getSequenceSelection()->isEmpty(); radioSelectedRange->setEnabled(hasSelection); radioSelectedRange->setChecked(hasSelection); int seqLen = ctxSeq->getSequenceLen(); spinRangeStart->setMinimum(1); spinRangeStart->setMaximum(seqLen); spinRangeStart->setValue(1); spinRangeEnd->setMinimum(1); spinRangeEnd->setMaximum(seqLen); spinRangeEnd->setValue(seqLen); } void SmithWatermanDialog::sl_bttnViewMatrix() { QString strSelectedMatrix = comboMatrix->currentText(); SMatrix mtx = substMatrixRegistry->getMatrix(strSelectedMatrix); if (mtx.isEmpty()) { QMessageBox::critical(this, windowTitle(), tr("Matrix not found.")); return; } SubstMatrixDialog smDialog(mtx, this); smDialog.exec(); } void SmithWatermanDialog::sl_spinRangeStartChanged(int curr_val) { if (curr_val > spinRangeEnd->value()) { spinRangeEnd->setValue(curr_val); } } void SmithWatermanDialog::sl_spinRangeEndChanged(int curr_val) { if (curr_val < spinRangeStart->value()) { spinRangeStart->setValue(curr_val); } } void SmithWatermanDialog::sl_translationToggled(bool checked) { DNAAlphabet* alphabet = 0; if (checked) { DNATranslation* aminoTT = ctxSeq->getAminoTT(); alphabet = aminoTT->getDstAlphabet(); } else { alphabet = ctxSeq->getAlphabet(); } QStringList matrixList = substMatrixRegistry->selectMatrixNamesByAlphabet(alphabet); if (matrixList.isEmpty()) { bttnViewMatrix->setEnabled(false); } else { bttnViewMatrix->setEnabled(true); } comboMatrix->clear(); comboMatrix->addItems(matrixList); } void SmithWatermanDialog::sl_wholeSequenceToggled(bool) { spinRangeEnd->setEnabled(false); spinRangeStart->setEnabled(false); } void SmithWatermanDialog::sl_selectedRangeToggled(bool) { spinRangeEnd->setEnabled(false); spinRangeStart->setEnabled(false); } void SmithWatermanDialog::sl_customRangeToggled(bool) { spinRangeEnd->setEnabled(true); spinRangeStart->setEnabled(true); } void SmithWatermanDialog::sl_bttnRun() { QString err = ac->validate(); if (!err.isEmpty()) { QMessageBox::critical(this, tr("Error!"), err); return; } if (readParameters()) { ac->prepareAnnotationObject(); const CreateAnnotationModel& m = ac->getModel(); AnnotationTableObject* obj = m.getAnnotationObject(); QString annotationName = m.data->name; QString annotationGroup = m.groupName; config.resultListener = new SmithWatermanResultListener; config.resultCallback = new SmithWatermanReportCallbackImpl( obj, annotationName, annotationGroup ); Task* task = realization->getTaskInstance(config, tr("SmithWatermanTask") ); AppContext::getTaskScheduler()->registerTopLevelTask(task); saveDialogConfig(); QDialog::accept(); } else { clearAll(); } } bool SmithWatermanDialog::readParameters() { clearAll(); config.sqnc = ctxSeq->getSequenceData(); DNATranslation* aminoTT = 0; bool isTranslation = radioTranslation->isChecked(); if (isTranslation) { aminoTT = ctxSeq->getAminoTT(); } else { aminoTT = 0; } if (!readSubstMatrix()) { return false; } if (!readPattern(aminoTT)) { return false; } config.aminoTT = aminoTT; if (!readRegion() || !readGapModel() || !readResultFilter() || !readRealization() ) { return false; } if (radioDirect->isChecked()) { config.strand = StrandOption_DirectOnly; } else if (radioComplement->isChecked()) { config.strand = StrandOption_ComplementOnly; } else if (radioBoth->isChecked()) { config.strand = StrandOption_Both; } else { assert(0); } config.complTT = ctxSeq->getComplementTT(); if (0 == config.complTT && isComplement(config.strand)) { QMessageBox::critical(this, windowTitle(), tr("Complement translation is not found.")); return false; } return true; } bool SmithWatermanDialog::readRealization() { QString strSelectedRealization = comboRealization->currentText(); SmithWatermanTaskFactory* rlz = swTaskFactoryRegistry->getFactory(strSelectedRealization); if (0 == rlz) { QMessageBox::critical(this, windowTitle(), tr("Algorithm is not found.")); return false; } realization = rlz; return true; } bool SmithWatermanDialog::readSubstMatrix() { QString strSelectedMatrix = comboMatrix->currentText(); SMatrix mtx = substMatrixRegistry->getMatrix(strSelectedMatrix); if (mtx.isEmpty()) { QMessageBox::critical(this, windowTitle(), tr("Matrix %1 is not found.").arg(strSelectedMatrix)); return false; } config.pSm = mtx; return true; } bool SmithWatermanDialog::readRegion() { U2Region range; int sqncLen = ctxSeq->getSequenceLen(); if (radioWholeSequence->isChecked()) { range = U2Region(0, sqncLen); } else if ( radioSelectedRange->isChecked() && !ctxSeq->getSequenceSelection()->getSelectedRegions().isEmpty()) { range = ctxSeq->getSequenceSelection()->getSelectedRegions().first(); } else { int startPos = spinRangeStart->value() - 1; // start with 0 int endPos = spinRangeEnd->value(); // int regionLen = endPos - startPos; range = U2Region(startPos, regionLen); } config.globalRegion = range; return true; } bool SmithWatermanDialog::readGapModel() { float scoreGapOpen = dblSpinGapOpen->value(); config.gapModel.scoreGapOpen = scoreGapOpen; float scoreGapExtd = dblSpinGapExtd->value(); config.gapModel.scoreGapExtd = scoreGapExtd; return true; } bool SmithWatermanDialog::readResultFilter() { int percentOfScore = spinScorePercent->value(); config.percentOfScore = percentOfScore; QString strSelectedFilter = comboResultFilter->currentText(); SmithWatermanResultFilter* filter = swResultFilterRegistry->getFilter(strSelectedFilter); if (0 == filter) { QMessageBox::critical(this, windowTitle(), tr("Filter is not found.")); return false; } config.resultFilter = filter; return true; } bool SmithWatermanDialog::readPattern(DNATranslation* aminoTT) { DNAAlphabet* al = 0; if (0 == aminoTT) { assert(config.pSm.getAlphabet() != NULL); al = config.pSm.getAlphabet(); } else { al = aminoTT->getDstAlphabet(); } if (0 == al) { QMessageBox::critical(this, windowTitle(), tr("Internal error")); return false; } QString inputPattern = teditPattern->toPlainText(); if (inputPattern.isEmpty()) { QMessageBox::critical(this, windowTitle(), tr("Pattern is empty")); return false; } QByteArray pattern; if (!al->isCaseSensitive()) { QString upperPattern = inputPattern.toUpper(); pattern = upperPattern.toLocal8Bit(); } else { pattern = inputPattern.toLocal8Bit(); } if (!TextUtils::fits(al->getMap(), pattern.constData(), pattern.length())) { QMessageBox::critical(this, windowTitle(), tr("Pattern contains unknown symbol")); return false; } config.ptrn = pattern; return true; } void SmithWatermanDialog::clearAll() { config.sqnc = QByteArray(); config.ptrn = QByteArray(); config.globalRegion = U2Region(0, 0); config.gapModel.scoreGapOpen = 0; config.gapModel.scoreGapExtd = 0; config.pSm = SMatrix(); config.percentOfScore = 0; config.resultCallback = 0; config.resultFilter = 0; config.resultListener = 0; config.strand = StrandOption_DirectOnly; config.complTT = 0; config.aminoTT = 0; realization = 0; } void SmithWatermanDialog::loadDialogConfig() { const SmithWatermanSearchType searchType = dialogConfig->searchType; switch (searchType) { case (SmithWatermanSearchType_inSequence): radioSequence->setChecked(true); break; case (SmithWatermanSearchType_inTranslation): radioTranslation->setChecked(true); break; default: break; } const StrandOption strand = dialogConfig->strand; switch (strand) { case (StrandOption_DirectOnly): radioDirect->setChecked(true); break; case (StrandOption_ComplementOnly): radioComplement->setChecked(true); break; case (StrandOption_Both): radioBoth->setChecked(true); break; default: break; } const SmithWatermanRangeType rangeType = dialogConfig->rangeType; switch (rangeType) { case (SmithWatermanRangeType_wholeSequence): radioWholeSequence->setChecked(true); break; case (SmithWatermanRangeType_selectedRange): radioSelectedRange->setChecked(true); break; case (SmithWatermanRangeType_customRange): radioCustomRange->setChecked(true); break; default: break; } const QByteArray& prevPattern = dialogConfig->ptrn; if (!prevPattern.isEmpty()) { teditPattern->setText(prevPattern); } const QString& prevAlgVersion = dialogConfig->algVersion; if (swTaskFactoryRegistry->hadRegistered(prevAlgVersion)) { int algIndex = comboRealization->findText(prevAlgVersion); assert(-1 != algIndex); comboRealization->setCurrentIndex(algIndex); } const QString& prevScoringMatrix = dialogConfig->scoringMatrix; if (!substMatrixRegistry->getMatrix(prevScoringMatrix).isEmpty()) { int mtxIndex = comboMatrix->findText(prevScoringMatrix); if( -1 != mtxIndex ) { comboMatrix->setCurrentIndex(mtxIndex); } } const float scoreGapOpen = dialogConfig->gm.scoreGapOpen; dblSpinGapOpen->setValue(scoreGapOpen); const float scoreGapExtd = dialogConfig->gm.scoreGapExtd; dblSpinGapExtd->setValue(scoreGapExtd); const QString& prevResultFilter = dialogConfig->resultFilter; if (swResultFilterRegistry->isRegistered(prevResultFilter)) { int filterIndex = comboResultFilter->findText(prevResultFilter); assert(-1 != filterIndex); comboResultFilter->setCurrentIndex(filterIndex); } const float minScoreInPercent = dialogConfig->minScoreInPercent; spinScorePercent->setValue(minScoreInPercent); return; } void SmithWatermanDialog::saveDialogConfig() { dialogConfig->ptrn = teditPattern->toPlainText().toAscii(); dialogConfig->algVersion = comboRealization->currentText(); dialogConfig->scoringMatrix = comboMatrix->currentText(); dialogConfig->gm.scoreGapOpen = (float)dblSpinGapOpen->value(); dialogConfig->gm.scoreGapExtd = (float)dblSpinGapExtd->value(); dialogConfig->resultFilter = comboResultFilter->currentText(); dialogConfig->minScoreInPercent = spinScorePercent->value(); dialogConfig->searchType = (radioSequence->isChecked()) ? (SmithWatermanSearchType_inSequence): (SmithWatermanSearchType_inTranslation); dialogConfig->strand = (radioDirect->isChecked()) ? (StrandOption_DirectOnly): (dialogConfig->strand); dialogConfig->strand = (radioComplement->isChecked()) ? (StrandOption_ComplementOnly): (dialogConfig->strand); dialogConfig->strand = (radioBoth->isChecked()) ? (StrandOption_Both): (dialogConfig->strand); dialogConfig->rangeType = (radioWholeSequence->isChecked()) ? (SmithWatermanRangeType_wholeSequence): (dialogConfig->rangeType); dialogConfig->rangeType = (radioSelectedRange->isChecked()) ? (SmithWatermanRangeType_selectedRange): (dialogConfig->rangeType); dialogConfig->rangeType = (radioCustomRange->isChecked()) ? (SmithWatermanRangeType_customRange): (dialogConfig->rangeType); return; } //void SmithWatermanDialog::sl_remoteRunButtonClicked() { // // validate annotations controller first // QString err = ac->validate(); // if( !err.isEmpty() ) { // QMessageBox::critical( this, tr( "Error!" ), err ); // return; // } // if( !readParameters() ) { // clearAll(); // return; // } // // RemoteMachineMonitor * rmm = AppContext::getRemoteMachineMonitor(); // assert(rmm); // RemoteMachineSettings *rms = RemoteMachineMonitorDialogController::selectRemoteMachine(rmm, true); // if (!rms) { // return; // } // assert(rms->getMachineType() == RemoteMachineType_RemoteService); // // ac->prepareAnnotationObject(); // const CreateAnnotationModel &m = ac->getModel(); // // Task *t = new SmithWatermanSchemaRemoteTask(rms, config, m.getAnnotationObject(), m.data->name, m.groupName); // Task *t = new SmithWatermanSchemaTask(config, m.getAnnotationObject(), m.data->name, m.groupName); // for local run // AppContext::getTaskScheduler()->registerTopLevelTask(t); // // saveDialogConfig(); // QDialog::accept(); //} void SmithWatermanDialogController::run( QWidget* p, ADVSequenceObjectContext* ctx, SWDialogConfig* dialogConfig ) { SmithWatermanDialog smv(p, ctx, dialogConfig); smv.exec(); } } // namespace ugene-1.9.8/src/corelibs/U2View/src/util_smith_waterman/SmithWatermanDialog.h0000644000175000017500000000477611651544334025772 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_SMITH_WATERMAN_DIALOG_H_ #define _U2_SMITH_WATERMAN_DIALOG_H_ #include namespace U2 { class ADVSequenceObjectContext; class CreateAnnotationWidgetController; #define DEF_PERCENT_OF_SCORE 90 #define DEF_GAP_OPEN_SCORE (-10.0f) #define DEF_GAP_EXTD_SCORE (-1.0f) enum SmithWatermanRangeType { SmithWatermanRangeType_noRange, SmithWatermanRangeType_wholeSequence, SmithWatermanRangeType_selectedRange, SmithWatermanRangeType_customRange }; enum SmithWatermanSearchType { SmithWatermanSearchType_noSearch, SmithWatermanSearchType_inSequence, SmithWatermanSearchType_inTranslation }; struct SWDialogConfig { SWDialogConfig() { ptrn = QByteArray(); algVersion = QString(""); scoringMatrix = QString(""); gm.scoreGapOpen = DEF_GAP_OPEN_SCORE; gm.scoreGapExtd = DEF_GAP_EXTD_SCORE; resultFilter = QString(""); minScoreInPercent = DEF_PERCENT_OF_SCORE; searchType = SmithWatermanSearchType_noSearch; strand = StrandOption_DirectOnly; rangeType = SmithWatermanRangeType_noRange; } QByteArray ptrn; QString algVersion; QString scoringMatrix; GapModel gm; QString resultFilter; int minScoreInPercent; // c {0, 1, ..., 100} SmithWatermanSearchType searchType; StrandOption strand; SmithWatermanRangeType rangeType; }; class U2VIEW_EXPORT SmithWatermanDialogController { public: static void run(QWidget* p, ADVSequenceObjectContext* ctx, SWDialogConfig* dialogConfig); }; } // namespace #endif ugene-1.9.8/src/corelibs/U2View/transl/0000755000175000017500000000000011651544334016335 5ustar ilyailyaugene-1.9.8/src/corelibs/U2View/transl/russian.ts0000644000175000017500000052426211651544334020404 0ustar ilyailya AssemblyToRefDialog Assembly To Referenece Сборка Контигов по Последовательности Assembly method: Метод сборки: Reference sequence: Референсная последовательность: Result file name: Имя результата: ... ... Align short reads Выравнивание на геном Short reads: Считываемые последовательности: Add Добавить Remove Удалить Start Собрать Cancel Отмена Align short reads method Метод выравнивания Select a method to align short reads. Выберите метод выраввнивания. Select required align short reads method Выберите требуемый метод выравнивания Select a DNA sequence to align short reads to. This parameter is <b>required</b>. Выберите референтную последовательность. Reference sequence Референтная последовательность Select the file in SAM format to write the result of alignment into. This parameter is <b>required</b>. Результат сборки контигов в формате SAM. Result file name Имя выходного файла Use an index file instead of a source reference sequence. Prebuilt index SAM output Add short reads here. <b>At least one read</b> should be presented. Здесь показаны риды, которые будут выравнены на референтную последовательность. Short reads Короткие риды AssemblyToSamDialog Convert UGENE assembly data base to SAM format Assembly data base: ... ... Result SAM file: Convert Cancel BranchSettingsDialog Branch Settings Настройки ветвей дерева Color Цвет Line Weight Толщина линий OK Готово Cancel Отмена BuildIndexFromRefDialog Build index Построить индекс Select a method that would be used to align short reads. Выберите метод выравнивания. Align short reads method Метод выравнивания Select a DNA sequence that would be used to align short reads to. This parameter is <b>required</b>. Выберните последовательность на которую будут выравнены ваш риды. Reference sequence Референтная последовательность Specify the index to build for the reference sequence. This parameter is <b>required</b>. Индеск для референтной последовательности. Index file name Имя индекс файла Start Собрать ... ... Cancel Отмена ButtonSettingsDialog Button settings Color: Цвет: Radius: Радиус: OK Cancel Отмена ConsensusSelectorDialog Consensus representation Представление консенсуса Select consensus representation scheme Выберите схему представления консенсуса Consensus type Тип консенсуса Threshold Порог Reset to default value Восстановить значение по умолчанию Reset Сбросить OK OK Cancel Отмена CreateFileIndexDialog File(s) to index: Файл(ы) для индексирования: File(s) to index separated by semicolon Файл(ы) для индексирования, разделённые точкой с запятой ... File to store index: Файл индекса: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> <html><head><meta name="qrichtext" content="1" /><style type="text/css"> p, li { white-space: pre-wrap; } </style></head><body style=" font-family:'MS Shell Dlg 2'; font-size:8.25pt; font-weight:400; font-style:normal;"> <p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-size:8pt;">Path to output index file</span></p></body></html> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> <html><head><meta name="qrichtext" content="1" /><style type="text/css"> p, li { white-space: pre-wrap; } </style></head><body style=" font-family:'MS Shell Dlg 2'; font-size:8.25pt; font-weight:400; font-style:normal;"> <p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-size:8pt;">Путь к создаваемому файлу индекса</span></p></body></html> Ok Готово Cancel Отмена Create index file Создание индекса File to index Файл для индексирования File to store index Файл индекса Compress Сжать индекс Add to project Добавить в проект CreatePhyTree Build Phylogenetic Tree Построение филогенетического дерева Tree building method Метод построения Save tree to Сохранить дерево в ... ... Remember Settings Сохранить настройки Restore Default Восстановить настройки Build Построить Cancel Отмена CreateRulerDialog Create new ruler Создать новую шкалу Ruler name Имя шкалы Ruler offset Сдвиг шкалы Ruler color Цвет шкалы Sample Text образец ... Create Создать Cancel Отмена CreateSubalignimentDialog Extract selected as MSA Извлечь выделенное Selected sequences Выбранные последовательности From От to до Invert selection Инвертировать выбор Select all Выбрать всё Clear selection Снять выделение File name Имя файла ... ... Add to project Добавить в проект Extract Извлечь Cancel Отмена DeleteGapsDialog Remove columns of gaps Удаление Пропусков Remove columns with number of gaps more than Удалить столбцы с числом пропусков Remove columns with number of gaps Remove columns with percentage of gaps Удалить столбцы с числом пропусков в процентах % % Remove all columns of gaps Удалить все столбцы пропусков Remove Удалить Cancel Отмена EditAnnotationDialog Edit annotation Редактирование аннотации Annotation name Имя аннотации Location Позиция ... OK Готово Cancel Отмена FindDialogBase Find in sequence Поиск подстрок в последовательности Find text pattern in sequence Поиск подстрок в последовательности по алгоритму Смита-Ватермана Pattern Паттерн A text pattern to find Паттерн для поиска в последовательности Search in Искать в последовательности Search pattern in sequence Искать совпадения в исходной нуклеотидной последовательности Sequence нуклеотидной Search pattern in translation Искать совпадения в транслированной аминокислотной последовательности Translation аминокислотной Strand Направление поиска Both Оба Search pattern in direct strand only Искать только в прямой последовательности Direct Прямой Search pattern in complement strand only Искать только в комплементированной последовательности Complement Комплементарный Algorithm Алгоритм Match percent: Строгость совпадения: A minimal percent to match pattern Минимально допустимый процент совпадения с паттерном % Allow mismatches only Допускать только замены Substitute Замены Allow insertions and deletions Допускать инсерции и делеции InsDel Инсерции/делеции When this option is used insertions and deletions are not supported. Search with ambiguous bases Find next result Искать одно ближайшее совпадение Find next Искать Find all results Найти все возможные совпадения Find All Найти все Close Закрыть Save results as annotations Сохранить найденные совпадения как аннотации Save as annotations Сохранить как аннотации Remove overlaps Исключить перекрытия Clear results Очистить Range start: Начало региона: Position: Текущая позиция: Range end: Конец региона: Selection range Селектированный регион Sequence range Вся последовательность ObjectViewTask No sequence info found! Информация о последовательности не найдена! QObject Generating tree view Swap Siblings Поменять ветви местами Expand Раскрыть Collapse Скрыть Save As Сохранить как Replace file Заменить файл %1 already exists. Do you want to replace it? %1 уже существует. Вы уверены, что хотите заменить его? SecStructDialog Secondary Structure Prediction Предсказание вторичной структуры Algorithm Алгоритм Range Start: Начало региона: Range End: Конец региона: Results: Результаты: Total predicted: Всего предсказано: 0 Start prediction Предсказать Save As Annotation... Сохранить как аннотации... Close Закрыть SmithWatermanDialogBase - Smith-Waterman Search Поиск Смита-Ватермана Input and output Ввод и вывод Smith-Waterman parameters Параметры алгоритма Смита-Ватермана Pattern Паттерн Smith-Waterman algorithm parameters Параметры поиска Algorithm version Версия алгоритма Advanced.. Дополнительно.. Scoring matrix Матрица весов View.. Смотреть.. Gap scores Веса пропусков Gap open Открытие Gap extension Продление Results filtering strategy Фильтрация результатов Minimal score Минимальная оценка % Report results Фильтровать Search in Искать в Sequence Последовательности Translation Трансляции Strand Направление Both Оба Direct Прямое Complement Комплементарное Range Регион Whole sequence Вся последовательность Selected range Выбранный Custom range Указанный Remote run... Удаленный запуск... Search Искать Cancel Отменить SubstMatrixDialogBase Alphabet Алфавит New Создать Save Сохранить Close Закрыть TextSettingsDialog Labels Formatting Форматирование надписей Color Цвет Size Размер Font Шрифт Attributes Аттрибуты B I U S OK Готово Cancel Отмена TreeSettingsDialog Tree Settings Настройки дерева Width Ширина Height (Rectangular) Высота (для прямоугольного) Tree View Тип дерева OK Готово Cancel Отмена U2::ADVAnnotationCreation New annotation... Создать аннотацию... U2::ADVClipboard Copy sequence Копировать последовательность Copy translation Копировать трансляцию Copy complement sequence Копировать комплeментарную последовательность Copy complement translation Копировать комплeментарную трансляцию Copy Копировать Copy annotation sequence Копировать аннотированную последовательность Copy annotation sequence translation Копировать трансляцию аннотированной последовательности Error! Ошибка! No sequence selected Не выбрана последовательность U2::ADVCreateAnnotationsTask Create annotations task Создание аннотации U2::ADVSequenceObjectContext Amino translation Таблицы Трансляции U2::ADVSingleSequenceHeaderWidget Toggle view Переключить обзор Remove sequence Удалить последовательность Alphabet: <b>%1</b> Sequence size: <b>%1</b> File:&nbsp;<b>%1</b> raw amino dna dna ext rna ext rna U2::ADVSingleSequenceWidget Zoom to range.. Приблизить регион ... Zoom Масштаб Select range Выбор региона Zoom to range Выбор масштаба Create new ruler... Создать новую шкалу... Rulers... Шкала обзора... Remove '%1' Удалить "%1" Select sequence region... Выберите регион... Sequence region... Регион последовательности... Sequence between selected annotations Последовательность между выбранными аннотациями Sequence around selected annotations Последовательность под выбранными аннотациями Select Селектировать Replace file Заменить файл %1 already exists. Do you want to replace it? %1 уже существует. Вы уверены, что хотите заменить его? Show all views Показать всё Hide all views Скрыть всё Show zoom view Показать масштабируемое представление Hide zoom view Скрыть масштабируемое представление Show details view Показать детали Hide details view Скрыть детали Show all Показать все Hide all Скрыть все Show overview Показать панораму Hide overview Скрыть панораму Show details Показывать детали Hide details Скрыть детали Capture screen Сохранить изображение Save As Сохранить как U2::ADVSyncViewManager Hide all sequences Скрыть все последовательности Show all sequences Показать все последовательности Hide all zoom views Скрыть все масштабируемые представления Show all zoom views Показать все масштабируемый представления Hide all overviews Скрыть все панорамы Show all overviews Показать все панорамы Hide all details Скрыть все детали Show all details Показать все детали Lock scales: visible range start Связать шкалы: по началу видимого региона Lock scales: selected sequence Связать шкалы: по выбранному региону Lock scales: selected annotation Связать шкалы: по выбранной аннотации Adjust scales: visible range start Синхронизировать шкалы: по началу видимого региона Adjust scales: selected sequence Синхронизировать шкалы: по выбранному региону Adjust scales: selected annotation Синхронизировать шкалы: по выбранной аннотации Lock scales Связать шкалы Adjust scales Синхронизировать шкалы Toggle views Переключить обзор Hide %1 Show %1 U2::AnnotatedDNAView Find pattern... Поиск подстрок... Annotations highlighting... Маркировка аннотаций... Go to position... Перейти Insert subsequence... Вставить подпоследовательность... Remove subsequence... Удалить подпоследовательность... Replace subsequence... Selected sequence from view Error! Ошибка! Analyze Анализировать Add Добавить Export Экспорт Align Выровнять Remove Удалить Edit sequence Редактировать последовательность Select sequence to associate annotations with: Установить связь аннотаций с последовательностью: No sequence object found for annotations Не найдена связанная с аннотациями последовательность center change request: %1 запрос на центрирование: %1 Toggle '%1' highlight Переключить подсветку "%1" Disable '%1' highlighting Не использовать подсветку для '%1' Enable '%1' highlighting Задействовать подсветку для '%1' Go To Выбор позиции U2::AnnotatedDNAViewFactory Sequence view Последовательность U2::AnnotationsTreeView Name Имя Value Значение Existing object with annotations... Существующие аннотации... Selected objects with annotations from view Copy qualifier text Копировать значение квалификатора Copy qualifier URL Копировать ссылку Toggle column Переключить столбец Hide column Убрать столбец Copy column text Копировать значение copy column URL Копировать ссылку Selected object from view Выбранный объект из окна Objects with annotations... Selected annotations and qualifiers Выбранные аннотации и квалификаторы Edit item Редактировать Edit qualifier Редактировать квалификатор View qualifier Редактировать квалификатор Qualifier... Квалификатор... Copy column '%1' text Копировать значение "%1" Copy '%1' annotation location Копировать позицию аннотации "%1" Copy column '%1' URL Копировать ссылку "%1" Hide '%1' column Скрыть столбец "%1" Copy qualifier '%1' value Копировать значение "%1" Copy qualifier '%1' URL Копировать ссылку "%1" Add '%1' column Добавить столбец "%1" Rename group Переименовать группу Rename qualifier Переименовать квалификатор U2::AnnotationsTreeViewL Name Имя Value Значение Objects with annotations... Selected objects with annotations from view Selected annotations and qualifiers Выбранные аннотации и квалификаторы Copy qualifier text Копировать значение квалификатора Copy qualifier URL Копировать ссылку Toggle column Переключить столбец Hide column Copy column text Копировать значение copy column URL Копировать ссылку Edit item Редактировать Edit qualifier Редактировать квалификатор View qualifier Редактировать квалификатор U2Qualifier... Copy column '%1' text Копировать значение "%1" Copy '%1' annotation location Копировать позицию аннотации "%1" Copy column '%1' URL Копировать ссылку "%1" Hide '%1' column Скрыть столбец "%1" Copy qualifier '%1' value Копировать значение "%1" Copy qualifier '%1' URL Копировать ссылку "%1" Add '%1' column Добавить столбец "%1" Rename group Переименовать группу Rename qualifier Переименовать квалификатор U2::AutoAnnotationsADVAction Automatic Annotations Highlighting Автомаркировка аннотаций U2::BuildIndexDialog Open reference sequence Выбрать реферируемый геном Set index file name Build index Построить индекс Reference sequence url is not set! Путь к геному не указан! Index file name is not set! U2::ConvertAssemblyToSamDialog Data base to SAM converter Data base file url is not set! SAM file url is not set! Open an assembly data base file Set a result SAM file name U2::CreateFileIndexDialog Open file Выбор файла для индексирования Select files Выберите файлы Select index file to create Выбор файла индекса Error! Ошибка! No input files supplied! Не обеспечен входными файлами! Invalid input file name! Не указан входной файл Invalid output file name! Не указан файл индекса! U2::CreatePhyTreeDialogController Warning Внимание Please, input the file name. Пожалуйста, введите имя файла. The seed must be odd. Затравка должна быть нечетной. Probably, for that alignment there is no enough memory to run PHYLIP dnadist module. The module will require more than %1 MB in the estimation. It could cause an error. Do you want to continue? Возможно, для этого выравнивания недостаточно памяти, чтобы запустить модуль PHYLIP - dnadist. Модуль, ориентировочно, потребует %1 Мб. Это может вызвать ошибку. Вы хотите продолжить? There is insufficient memory to run PHYLIP dnadist for the alignment. It may cause an error. Do you want to continue? На вашей системе недостаточно памяти, чтобы выполнить PHYLIP dnadist для данного множественного выравнивания. В случае продолжения может возникнуть ошибка. Продолжить? File name is empty Имя файла пусто U2::CreateRulerDialogController New ruler Новая шкала Error Ошибка Ruler name is empty! Необходимо указать название шкалы Ruler with the same name is already exists! Шкала с таким названием уже есть! U2::CreateSubalignimentDialogController Select file to save... Сохранение файла Directory to save is not exists Директория не существует No path specified Не задан путь Filename to save is empty Имя сохраняемого файла пусто Entered save filepath is empty Не задан путь Filename is empty Не задано имя файла Start position must be greater than end position Начальная позиция должна быть больше конечной позиции Start position must be integer Начальная позиция должна выражаться целым числом End position must be integer Конечная позиция должна выражаться целым числом Entered region not contained in current sequence Указанный регион не содержит последовательности You must select at least one sequence Выберите хотябы одну последовательность U2::CreateSubalignimentTask Create subaligniment task Создание подмножества выравнивания Document is locked Документ заблокирован Unable to detect format by file extension Невозможно определить тип документа по расширению Unable to create subalignment, because there are gaps only Не удалось создать подмножество выравнивания, неверные рамки Save document and open view Сохранинение документа и открытие U2::DetView Show complement strand Показывать комплeментарную последовательность Show amino translations Показывать транслированную последовательность U2::DnaAssemblyDialog Add short reads Добавить выравниваемые последовательности Open reference sequence Выбрать реферируемый геном DNA Assembly Сборка контигов Reference sequence url is not set! Путь к геному не указан! Result alignment file name is not set! Имя для результирующего выравнивания не указано! Short reads list is empty! Список выравниваемых последовательностей пуст! Set result alignment file name Укажите имя для результата U2::DnaAssemblySupport DNA assembly Сборка контигов Align short reads... Выравнинвание на геном... Build index... Построение индекса... Convert UGENE Assembly data base to SAM format... DNA Assembly Сборка контигов There are no algorithms for DNA assembly available. Please, check your plugin list. Нет доступных алгоритмов для сборки контигов. Проверьте список подключенных модулей. U2::EditAnnotationDialogController Location empty! Не задана позиция! Location is empty! Регион пуст! Invalid location! Неверная позиция! Error! Ошибка! Wrong annotation name! Нелегальные символы в имени аннотации. Допустимы только цифры, буквы и подчёркивания New annotation locations is out of sequence bounds! Набор (список) аннотированных регионов биологической последовательности. U2::FindDialog Cancel Отменить Close Закрыть Progress %1%. Current position %2 Прогресс %1. Текущая позиция %2. Results found %1 Найдено совпадений: %1 Question? Подтверждение The end of the search region is reached. Restart? Достигнут конец региона. Начать с начала? Error! Ошибка Search pattern is empty Не указан паттерн Pattern length is greater than search range Слишком длинный паттерн Warning! Внимание Search pattern contains symbols that are out of the active alphabet range. Continue anyway? Паттерн содержит символы не входящие в алфавит последовательности. Продолжать? The seach settings were changed from the last search. Clean old results? Опции поиска изменены, удалить старые результаты? Results list contains results from the previous search. Clear? Удалить старые результаты? yes Да no Нет [%1 %2] translation: %3 complement: %4 [%1 %2] трансляция: %3 комплeментарная: %4 %1 overlaps filtered, %2 results left. %1 перекрытий удалено, осталось %2 результатов. U2::GSequenceGraphView Graph settings Опции графика %1 [%2, %3], Window: %4, Step %5 %1 [%2, %3] окно: %4 шаг: %5 U2::GSequenceLineViewAnnotated etc ... Прочие ... U2::MSAAlignDialog ... ... Align Выровнять Set result alignment file name Укажите имя для результата The input file url is empty. Please select file to align. Result alignment file name is not set! Имя для результирующего выравнивания не указано! U2::MSAColorSchemeRegistry No colors Без цвета UGENE Раскраска UGENE Jalview Раскраска Jalview Percentage Identity По процентному соотношению Zappo Tailor Hydrophobicity Helix propensity Strand propensity Turn propensity Buried index Clustal X U2::MSAEditor Zoom In Приблизить Zoom Out Отдалить Zoom To Selection Приблизить выбранный регион Reset Zoom Вернуться к приближению "по умолчанию" Export as image Экспорт изображения Copy Копировать Edit Редактировать Export Экспорт Align Выровнять Tree Дерево Advanced Дополнительные операции Add Добавить Export alignment image Экспорт изображения выравнивания error Ошибка View Вид Increase Font Увеличить шрифт Decrease Font Уменьшить шрифт Change Font Изменить шрифт Reset Font Сбросить шрифт Build Tree Построить дерево Calculate phy tree Построение филогенетического дерева No algorithms for building phylogenetic tree are available. Нет доступных алгоритмов для построения дерева. Select font for alignment Выбрать шрифт Statistics Статистика U2::MSAEditorConsensusArea copy_consensus Копировать строку консенсуса Copy consensus Копировать консенсус Copy consensus with gaps Копировать консенсунс с пропусками Consensus mode... Выбрать режим консенсуса... U2::MSAEditorFactory Open multiple views Открытие нескольких окон Alignment editor Редактор выравниваний U2::MSAEditorNameList Edit sequence name Изменить имя последовательности Copy current sequence Копировать текущую последовательность Rename Переименовать New sequence name: Новое имя: U2::MSAEditorOffsetsViewController Show offsets Показывать смещение U2::MSAEditorSequenceArea del_sym Удалить пропуск Remove selection Удалить выделение Copy selection Скопировать выделение: Remove columns of gaps... Удалить столбцы пропусков... Insert gap Вставить пропуск Create subaligniment Создать подмножество Insert column of gaps Вставить столбец пропусков Go to position.. Перейти ... Remove columns with gaps Удалить столбцы пропусков Extract selected as MSA... Извлечь выравнивание... Go to position... Перейти к позиции... Remove all gaps Удалить все пропуски Sequence from file... Последовательность из файла... Sequence from current project... Последовательность из проекта... Sort sequences by name Сортировать последовательности по имени Replace selected rows with reverse-complement Заменить выделенные строки обратно-комплементарными Open file with sequences Открыть Go To Выбор позиции Fill selection with gaps Заполнить пропусками Save subalignment Сохранить подмножество Colors Раскраска U2::MSAEditorStatusWidget Find: Поиск: Find backward <b>(SHIFT + Enter)</b> Искать назад <b>(SHIFT + Ввод)</b> Find forward <b>(Enter)</b> Искать вперёд <b>(Ввод)</b> Find in alignment Искать в выравнивании Alignment object is locked Объект выравнивания заблокирован Alignment object is not locked Объект выравнивания рвзблокирован Ln %1 / %2 Стр %1 / %2 Line %1 of %2 Строка %1 из %2 Col %1 / %2 Стб %1 / %2 Column %1 of %2 Столбец %1 из %2 U2::MSAEditorUI Tree view Дерево Consensus Консенсус U2::MinMaxSelectorWidget Cutoff for minimum and maximum values Диапазон значений Minimum: Минимум: Maximum: Максимум: Invalid cutoff values Некорректный диапазон: мин больше макс U2::ObjectViewTask No sequence info found! Информация о последовательности не найдена! U2::OpenAnnotatedDNAViewTask Sequences Последовательности Maximum number of objects per view reached: %1 Достигнут предел по кол-ву объектов на окно: %1 Sequence object not available! URL %1, name %2 Последовательность не найдена: %2 из %1 No sequence objects found Последовательностей не найдено U2::OpenMSAEditorTask Multiple alignment object not found Объект выравнивания не найден Opening MSA editor for object: %1 Открывается редактор выравниваний для "%1" U2::OpenSavedAnnotatedDNAViewTask DNA sequence object not found: %1 Последовательность не найдена: "%1" U2::OpenSavedMSAEditorTask DNA sequence object not found: %1 Последовательность не найдена: "%1" U2::OpenSavedTextObjectViewTask Text object '%1' is not found Объект текста не найден: "%1" U2::OpenSavedTreeViewerTask DNA sequence object not found: %1 Последовательность не найдена: "%1" U2::OpenTreeViewerTask Opening tree viewer for object %1 Открытие визуализатора филогенетических деревьев Phylogenetic tree object not found Филогенетическое дерево не найдено U2::OpenUIndexViewerTask Index object is null Document is null or loaded Opening index viewer for object %1 Openining index viewer for object %1 Открытие окна индекса: %1 U2::Overview Toggle annotation density graph Показать диаграмму плотности аннотаций Position Позиция Annotation density Плотность аннотаций U2::PanView Zoom In Приблизить Zoom Out Отдалить Zoom to Selection Масштабировать по выделению Zoom to Whole Sequence Масштабировать ко всей последовательности Show All Rows Показывать все ряды +1 Row +1 ряд -1 Row -1 ряд +5 Rows +5 рядов -5 Rows -5 рядов Reset Rows Number Восстановить количество рядов Manage Rows in Zoom View Управление рядами в масштабируемом представлении Show Main Ruler Показывать основную шкалу Show Custom Rulers Показывать дополнительные шкалы range change request: [%1, %2] Изменён видимый диапазон: [%1, %2] empty <пусто> U2::PanViewRenderArea [%1 %2] U2::SecStructDialog Region Регион Structure Type Тип структуры U2::SecStructPredictViewAction Predict secondary structure... Предсказание вторичной структуры... U2::SimpleTextObjectViewFactory Open multiple views task Открытие нескольких окон Text editor Текстовый редактор U2::SmithWatermanDialog Error! Ошибка! No matrix registry. Отсутствует реестр матриц. No substitution matrices found. Не найдены матрицы подстановки. No filter registry. Не найден реестр фильтров. No algorithm registry. Не найден реестр алгоритмов. No filter registry found. No algorithm registry found. Enter pattern here Введите паттерн Pattern length: %1 Длина паттерна: %1 Matrix not found. Не найдена матрица подстановки. SmithWatermanTask Поиск алгоритмом Смита-Ватермана Algorithm is not found. Алгоритм не найден. Matrix %1 is not found. Матрица %1 не найдена. Filter is not found. Фильтр не найден. Internal error Внутренняя ошибка Pattern is empty Не указан паттерн Pattern contains unknown symbol Паттерн содержит символы не входящие в алфавит последовательности Selecting machines error! Ошибка выбора удаленных машин! You didn't select a machine to run remote task! Не выбрана машина для удаленного запуска! Distributed run on many machines is not supported yet. Select 1 machine Распределенный запуск на нескольких машинах в данный пока не поддерживается. Выберите одну машину Complement translation is not found. Комплементарная трансляция не найдена. U2::SmithWatermanSchemaTask SmithWatermanSchemaTask Выполнение алгоритма Смита-Ватермана Unable to create temporary files Невозможно создать временные файлы U2::SubstMatrixDialog Scoring matrix: %1 min score: max score: U2::TreeViewer Tree Settings... Настройки дерева... Rectangular Прямоугольное Circular Круговое Unrooted Неукорененное Branch Settings... Настройки ветвей дерева... Show Names Показывать имена Show Distances Показывать расстояния Formatting... Форматирование... Align Labels Выровнять надписи Zoom In Приблизить Zoom Out Отдалить Reset Zooming Восстановить размер по умолчанию Print Tree... Печатать дерево... Screen Capture... Снимок экрана... Whole Tree as SVG... Все дерево в SVG... As SVG... В SVG формате... Layout Представление дерева Show Labels Показывать надписи Export Tree Image Экспортировать изображение дерева U2::TreeViewerFactory Phylogenetic tree viewer Визуализатор филогенетических деревьев Open multiple views Открыть несколько окон U2::UIndexExportToNewFileDialogImpl Select file to export Выбор файла экспорта Error Ошибка Illegal file name Не указан файл для экспорта U2::UIndexSupport Index large file(s)... Индексировать файл(ы)... error Ошибка Create index file Индексировать файл данных Error! Ошибка! Cannot write output file: unknown io adapter for %1 Не могу записать в выходной файл: неизвестный адаптер ввода/вывода для "%1" Cannot read input file: unknown io adapter for %1 Не могу прочитать входной файл: неизвестный адаптер ввода/вывода для "%1" Unknown protocol Неизвестный протокол U2::UIndexViewHeaderItemWidgetImpl [All values] filter [Starts with] filter [Ends with] filter [Contains] filter [Equal] filter [Not equal] filter [Greater than] filter [Lower than] filter [In range] filter Select new key Enter a filter value Enter a string value Enter a number value Enter a lower bound Enter an upper bound Error Ошибка The value can't be empty Error! Ошибка! Upper bound must be greater than lower U2::UIndexViewWidgetImpl column столбец No filter selected Фильтр не выбран Document Format Формат файла URL Путь до файла None Ключ не выбран Hide column Спрятать столбеу Remove column Удалить столбец No hidden columns Нет спрятанных столбцов Show hidden columns: Показать спрятанные столбцы: Add column Добавить столбец Complex rule Сложное правило U2::UIndexViewer Export Экспорт Save selection to a new file Сохранить выделенные в новый файл Error Ошибка No items selected Ничего не выделено U2::UIndexViewerFactory Index viewer Индекс Open multiple views Открыть несколько окон U2::WindowStepSelectorDialog Cancel Отмена Ok Готово Error! Ошибка U2::WindowStepSelectorWidget Window: Окно Invalid step value Недопустимая величина шага Steps per window: Шаг окна Illegal step value Некорректная величина шага UIndexExportToNewFileDialog ... Ok Готово Cancel Отменить Export indexed document Экспорт документа Export file Файл compress file сжать UIndexViewHeaderItemWidget Create annotation ... UIndexViewWidget Create annotation Создание аннотации Manage columns Упраление столбцами Manage columns button Кнопка управления столбцами > performAlignmentDialog Align Выровнять Base options Select input file: ... ... <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> <html><head><meta name="qrichtext" content="1" /><style type="text/css"> p, li { white-space: pre-wrap; } </style></head><body style=" font-family:'MS Shell Dlg 2'; font-size:8.25pt; font-weight:400; font-style:normal;"> <p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-size:8pt;">Translating alignment to amino allows to avoid errors of inserting gaps within codon boundaries.</span></p></body></html> Translate to amino when aligning ugene-1.9.8/src/corelibs/U2View/transl/czech.ts0000644000175000017500000047024511651544334020015 0ustar ilyailya AssemblyToRefDialog ... Align short reads Add Přidat Remove Odstranit Start Začít Cancel Zrušit Align short reads method Select a method to align short reads. Select required align short reads method Select a DNA sequence to align short reads to. This parameter is <b>required</b>. Reference sequence Srovnávací sekvence: Select the file in SAM format to write the result of alignment into. This parameter is <b>required</b>. Result file name Název výsledného souboru Add short reads here. <b>At least one read</b> should be presented. Short reads Krátká čtení BranchSettingsDialog Branch Settings Color Line Weight OK OK Cancel Cancel BuildIndexFromRefDialog Build index Select a method that would be used to align short reads. Align short reads method Select a DNA sequence that would be used to align short reads to. This parameter is <b>required</b>. Reference sequence Srovnávací sekvence: Specify the index to build for the reference sequence. This parameter is <b>required</b>. Index file name Start Začít ... Cancel Cancel ButtonSettingsDialog Button settings Color: Radius: OK OK Cancel Cancel ConsensusSelectorDialog Consensus representation Znázornění shody Select consensus representation scheme Vyberte schéma názornění shody Consensus type Typ shody Threshold Prahová hodnota Reset to default value Nastavit znovu na výchozí hodnotu Reset Nastavit znovu OK OK Cancel Zrušit CreateFileIndexDialog File(s) to index: Umístění dokument(y) File(s) to index separated by semicolon ... File to store index: Umístění rejstříku <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> <html><head><meta name="qrichtext" content="1" /><style type="text/css"> p, li { white-space: pre-wrap; } </style></head><body style=" font-family:'MS Shell Dlg 2'; font-size:8.25pt; font-weight:400; font-style:normal;"> <p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-size:8pt;">Path to output index file</span></p></body></html> Compress Zhustit Add to project Přidat do projektu Ok OK Cancel Zrušit Create index file Vytvořit soubor rejstříku File to index Document location File to store index Index location compress index Compress CreatePhyTree Create Phylogenetic Tree Vytvořit fylogenetický strom Choose algorithm: Vybrat algoritmus: Path to file: Cesta k souboru: Build Phylogenetic Tree Tree building method Save tree to ... Build OK OK Cancel Zrušit CreateRulerDialog Create new ruler Vytvořit nové pravítko Ruler name Název pravítka Ruler offset Posun pravítka Ruler color Barva pravítka Sample Text Ukázkový text ... Create Vytvořit Cancel Zrušit CreateSubalignimentDialog Extract selected as MSA Selected sequences Vybrané sekvence From to Invert selection Obrátit výběr Select all Vybrat vše Clear selection Smazat výběr File name ... Add to project Přidat do projektu Extract Extract Cancel Zrušit DeleteGapsDialog Remove columns of gaps Remove columns with number of gaps Remove columns with percentage of gaps % % % Remove all columns of gaps Remove Remove Cancel Cancel EditAnnotationDialog Edit annotation Upravit poznámku Annotation name Název poznámky Location Umístění ... OK OK Cancel Zrušit FindDialogBase find_dialog_caption Find in sequence find_dialog_wit Find text pattern in sequence find_label Pattern search_edit_wit A text pattern to find find_in_group Search in find_in_seq_wit Search pattern in sequence find_in_seq_label Sequence find_in_transl_wit Search pattern in translation find_in_transl_label Translation strand_group Strand strand_both Both strand_direct_wit Search pattern in direct strand only strand_direct_label Direct strand_complement_wit Search pattern in complement strand only strand_complement_label Complement algorithm_group Algorithm match_label Match percent: match_wit A minimal percent to match pattern Find in sequence Najít v sekvenci Find text pattern in sequence Najít v sekvenci textový vzor Pattern Vzor A text pattern to find Textový vzor, který se má najít Search in Hledat v Search pattern in sequence Hledat vzor v sekvenci Sequence Sekvence Search pattern in translation Hledat vzor v překladu Translation Překlad Strand Řetězec Both Oba Search pattern in direct strand only Hledat vzor pouze v přímém řetězci Direct Přímý Search pattern in complement strand only Hledat vzor pouze v doplňkovém řetězci Complement Doplněk Algorithm Algoritmus Match percent: Procento shody: A minimal percent to match pattern Nejmenší procento pro shodující se vzor % % Allow mismatches only Povolit pouze neodpovídající si Substitute Zaměnit Allow insertions and deletions Povolit vložení a smazání InsDel VložSmaž Find next result Najít další výsledek Find next Najít další Find all results Najít všechny výsledky Find All Najít vše Close Zavřít Save results as annotations Uložit výsledky jako poznámky Save as annotations Uložit jako poznámky Remove overlaps Odstranit překrytí Clear results Smazat výsledky Range start: Začátek rozsahu: Position: Poloha: Range end: Konec rozsahu: Selection range Rozsah výběru Sequence range Rozsah sekvence mismatches_tt Allow mismatches only mismatches_wit Allow mismatches only mismatches_only Substitute insertions_deletions_tt Allow insertions and deletions insertions_deletions_wit Allow insertions and deletions insertions_deletions InsDel find_next_wit Find next result find_next_button Find next find_all_wit Find all results find_all_button Find All hide_button_wit Close close_button Close save_as_features_tt Save results as annotations save_as_features_wit Save results as annotations save_as_annotations_button Save as annotations clear_list_button Clear results matches_area_wit Clear results rstart_label Range start: cpos_label Position: rend_label Range end: sel_button Selection range wh_seq_button Sequence range remove_overlaps Remove overlaps ObjectViewTask No sequence info found! QObject Generating tree view Swap Siblings Expand Collapse Save As Uložit jako Replace file Nahradit soubor %1 already exists. Do you want to replace it? Soubor %1 již existuje. Chcete jej nahradit? SecStructDialog Secondary Structure Prediction Předpověď druhotné stavby Algorithm Algoritmus Range Start: Začátek rozsahu: Range End: Konec rozsahu: Results: Výsledky: Total predicted: Celkem předpověděno: 0 Start prediction Spustit předpověď Save As Annotation... Uložit jako poznámku... Close Zavřít SmithWatermanDialogBase - - Smith-Waterman Search Hledání Smith-Waterman Smith-Waterman parameters Parametry Smith-Waterman Pattern Vzor Smith-Waterman algorithm parameters Parametry algoritmu Smith-Waterman Algorithm version Verze algoritmu Advanced.. Pokročilé... Scoring matrix Výsledková matice View.. Pohled... Gap scores Zápisy mezer Gap open Otevřená mezera Gap extension Prodloužení mezery Results filtering strategy Strategie filtrování výsledků Minimal score Nejmenší výsledek % % Report results Oznámit výsledky Search in Hledat v Sequence Sekvence Translation Překlad Strand Řetězec Both Obojí Direct Přímý Complement Doplňkový Range Rozsah Whole sequence Celá sekvence Selected range Vybraný rozsah Custom range Vlastní rozsah Input and output Remote run... Vzdálené spuštění... Search Hledat Cancel Zrušit SubstMatrixDialogBase Close Zavřít TextSettingsDialog Labels Formatting Color Size Font Attributes B I U S OK OK Cancel Cancel TreeSettingsDialog Tree Settings Width Height (Rectangular) Tree View OK OK Cancel U2::ADVAnnotationCreation New annotation... Nová poznámka... U2::ADVClipboard Copy sequence Kopírovat sekvenci Copy translation Kopírovat překlad Copy complement sequence Kopírovat doplňkovou sekvenci Copy complement translation Kopírovat doplňkový překlad Copy annotation sequence Kopírovat poznámkovou sekvenci Copy annotation sequence translation Kopírovat překlad poznámkové sekvence Error! Chyba No sequence selected Nebyla vybrána žádná sekvence Copy Kopírovat U2::ADVCreateAnnotationsTask adv_create_annotation_task Create annotations task Create annotations task Vytvořit úlohu poznámky U2::ADVSequenceObjectContext amino_translations_menu Amino translation Amino translation Přepis amino U2::ADVSingleSequenceHeaderWidget Toggle view Přepnout pohled Remove sequence Odstranit sekvenci Alphabet: <b>%1</b> Sequence size: <b>%1</b> File:&nbsp;<b>%1</b> raw amino dna dna ext. rna rna ext. U2::ADVSingleSequenceWidget range_zoom Zoom to range.. zoom_menu Zoom selection_range_title Select range visible_range_title Zoom to range Create new ruler... Vytvořit nové pravítko... Rulers... Pravítka... Remove '%1' Odstranit '%1' Select sequence region... Vybrat oblast sekvence... Sequence region... Oblast sekvence... Sequence between selected annotations Sekvence mezi vybranými poznámkami Sequence around selected annotations Sekvence okolo vybraných poznámek Zoom to range.. Přiblížit na rozsah... Zoom Zvětšení Select Vybrat Select range Vybrat rozsah Zoom to range Přiblížit na rozsah... Replace file Nahradit soubor %1 already exists. Do you want to replace it? Soubor %1 již existuje. Chcete jej nahradit? Show all views Ukázat všechny pohledy Hide all views Skrýt všechny pohledy Show zoom view Ukázat pohled se zvětšením Hide zoom view Skrýt pohled se zvětšením Show details view Ukázat pohled s podrobnostmi Hide details view Skrýt pohled s podrobnostmi Show overview Ukázat přehled Hide overview Skrýt přehled Capture screen Zachytit obrazovku Save As Uložit jako U2::ADVSyncViewManager Hide all sequences Skrýt všechny sekvence Show all sequences Ukázat všechny sekvence Hide all zoom views Skrýt všechny pohledy se zvětšením Show all zoom views Ukázat všechny pohledy se zvětšením Hide all overviews Skrýt všechny přehledy Show all overviews Ukázat všechny přehledy Hide all details Skrýt všechny podrobnosti Show all details Ukázat všechny podrobnosti Lock scales: visible range start Zamknout stupnice: začátek viditelného rozsahu Lock scales: selected sequence Zamknout stupnice: vybraná sekvence Lock scales: selected annotation Zamknout stupnice: vybraná poznámka Adjust scales: visible range start Přizpůsobit stupnice: začátek viditelného rozsahu Adjust scales: selected sequence Přizpůsobit stupnice: vybraná sekvence Adjust scales: selected annotation Přizpůsobit stupnice: vybraná poznámka Lock scales Zamknout stupnice Adjust scales Přizpůsobit stupnice Toggle views Přepnout pohledy Hide %1 Show %1 U2::AnnotatedDNAView Find pattern... Najít vzor Annotations highlighting... Zvýraznění poznámek... Go to position... Jít na... Insert subsequence Insert subsequence Remove subsequence... Odstranit podsekvence Replace subsequence... Selected sequence from view Error! Chyba! Analyze Provést rozbor Add Přidat Export Vyvést Align Zarovnat Remove Odstranit Edit sequence Upravit sekvenci Select sequence to associate annotations with: Vybrat sekvenci, se kterou se mají poznámky spojit: No sequence object found for annotations Pro poznámky nebyl nalezen žádný předmět sekvence Disable '%1' highlighting Insert subsequence... Přidat podsekvenci Enable '%1' highlighting Go To Jít na U2::AnnotatedDNAViewFactory Sequence view Pohled na sekvenci U2::AnnotationsTreeView Name Název Value Hodnota Objects with annotations... Selected objects with annotations from view Vybraný předmět z pohledu Selected annotations and qualifiers Copy qualifier text Kopírovat text modifikátoru Copy qualifier URL Kopírovat adresu (URL) modifikátoru Toggle column Přepnout sloupec modifikátoru Hide column Skrýt sloupec modifikátoru Copy column text Kopírovat text sloupce copy column URL Kopírovat adresu (URL) sloupce Edit item Přidat položku Edit qualifier Upravit modifikátor View qualifier Zobrazit modifikátor Qualifier... Modifikátor... Copy column '%1' text Kopírovat text sloupce '%1' Copy '%1' annotation location Kopírovat umístění poznámky '%1' Copy column '%1' URL Kopírovat adresu (URL) sloupce '%1' Hide '%1' column Skrýt sloupec '%1' Copy qualifier '%1' value Kopírovat text modifikátoru '%1' Copy qualifier '%1' URL Kopírovat adresu (URL) modifikátoru '%1' Add '%1' column Přidat sloupec '%1' Rename group Přejmenovat skupinu Rename qualifier Přejmenovat modifikátor U2::AutoAnnotationsADVAction Automatic Annotations Highlighting U2::BuildIndexDialog Open reference sequence Otevřít srovnávací sekvenci Set index file name Build index Reference sequence url is not set! Adresa (URL) srovnávací sekvence není nastavena! Index file name is not set! U2::CreateFileIndexDialog Select files Otevřít soubor Select index file to create Vybrat soubor rejstříku k vytvoření Error! Chyba! No input files supplied! Neplatný název vstupního souboru! Invalid output file name! Neplatný název výstupního souboru! U2::CreatePhyTreeDialogController Warning Varování Please, input the file name. The seed must be odd. There is insufficient memory to run PHYLIP dnadist for the alignment. It may cause an error. Do you want to continue? File name is empty Název souboru je prázdný U2::CreateRulerDialogController New ruler Nové pravítko Error Chyba Ruler name is empty! Název pravítka je prázdný! Ruler with the same name is already exists! Pravítko se stejným názvem již existuje! U2::CreateSubalignimentDialogController Select file to save... Vybrat soubor pro uložení... Directory to save is not exists Cílový adresář neexistuje No path specified Nezadána žádná cesta Start position must be greater than end position Entered save filepath is empty No path specified Filename to save is empty Název souboru pro uložení je prázdný Start position must be integer Start position must be integer Entered region not contained in current sequence Zadaná oblast není obsažena v nynější sekvenci You must select at least one sequence Musíte vybrat alespoň jednu sekvenci U2::CreateSubalignimentTask Document is locked Dokument je uzamknut Unable to detect format by file extension Podle souborové přípony formát zjistit nelze Save document and open view Uložit dokument a otevřít zobrazení U2::DetView show_complement Show complement strand show_translation Show amino translations Show complement strand Ukázat doplňkový řetězec Show amino translations Ukázat amino přepis U2::DnaAssemblyDialog Add short reads Přidat krátká čtení Open reference sequence Otevřít srovnávací sekvenci DNA Assembly Shromáždění DNA Reference sequence url is not set! Adresa (URL) srovnávací sekvence není nastavena! Result alignment file name is not set! Název souboru pro výsledné zarovnání není nastaven! Short reads list is empty! Seznam krátkých čtení je prázdný! Set result alignment file name Nastavit název souboru pro výsledné zarovnání U2::DnaAssemblySupport DNA assembly Shromáždění DNA Align short reads... Build index... DNA Assembly Shromáždění DNA There are no algorithms for DNA assembly available. Please, check your plugin list. Nejsou dostupné žádné algoritmy pro shromáždění DNA. Prověřte, prosím, váš seznam s přídavnými moduly. U2::EditAnnotationDialogController Location empty! Location is empty! Location invalid! Invalid location! Location is empty! Umístění je prázdné! Invalid location! Umístění je neplatné! Error! Chyba! Wrong annotation name! Chybný název poznámky! New annotation locations is out of sequence bounds! Cílová oblast je mimo hranice sekvence! U2::FindDialog cancel_button Cancel close_button Close progress_%1%_current_pos_%2_ Progress %1%. Current position %2 %1_results_found. Results found %1 question_caption Question? restart_q The end of the search region is reached. Restart? error Error! search_pattern_is_empty_text Search pattern is empty pattern_is_too_long Pattern length is greater than search range warning Warning! search_pattern_alphabet_error_continue_q Search pattern contains symbols that are out of the active alphabet range. Continue anyway? settings_changed_clean_res_q The seach settings were changed from the last search. Clean old results? results_list_not_empty_ask_clear Results list contains results from the previous search. Clear? Cancel Zrušit Close Zavřít Progress %1%. Current position %2 Postup %1%. Současná %2 Results found %1 Nalezené výsledky %1 Question? Otázka? The end of the search region is reached. Restart? Dosaženo konce prohledávané oblasti. Začít znovu? Error! Chyba! Search pattern is empty Vzor pro hledání je prázdný Pattern length is greater than search range Délka vzoru je větší než prohledávaný rozsah Warning! Varování! Search pattern contains symbols that are out of the active alphabet range. Continue anyway? Vzor pro hledání obsahuje symboly, které jsou mimo činný abecední rozsah. Přesto pokračovat? The seach settings were changed from the last search. Clean old results? nastavení pro hledání bylo od posledního hledání změněno. Smazat staré výsledky? Results list contains results from the previous search. Clear? Seznam s výsledky obsahuje výsledky z předchozího hledání. Smazat? yes Ano no Ne [%1 %2] translation: %3 complement: %4 [%1 %2] překlad: %3 doplněk: %4 [%1 %2] translation:%3 complement:%4 [%1 %2] translation: %3 complement: %4 %1 overlaps filtered, %2 results left. %1překrytí filtrováno, %2 zbývajících výsledků. U2::GSequenceGraphView visual_properties Graph settings graph_header_%1_pos_%2_%3_window_%4_step_%5 %1 [%2, %3], Window: %4, Step %5 Graph settings Nastavení grafu %1 [%2, %3], Window: %4, Step %5 %1 [%2, %3], Okno: %4, Krok %5 U2::GSequenceLineViewAnnotated etc ... a tak dále... U2::MSAAlignDialog Align Zarovnat Set result alignment file name Nastavit název souboru pro výsledné zarovnání The input file url is empty. Please select file to align. Result alignment file name is not set! Název souboru pro výsledné zarovnání není nastaven! U2::MSAColorSchemeRegistry No colors Žádné barvy UGENE Jalview Percentage Identity Procentní identická rovnost Zappo Tailor Hydrophobicity Nesmáčivost Helix propensity Sklon šroubovice Strand propensity Sklon řetězce Turn propensity Sklon otočení Buried index Schovaný rejstřík Clustal X U2::MSAEditor Zoom In Přiblížit Zoom Out Oddálit Zoom To Selection Přiblížit na výběr Reset Zoom Nastavit zvětšení znovu Export as image Vyvést jako obrázek copy_menu Copy edit_menu Edit align_menu Align advanced_menu Advanced Add Přidat Export alignment image Vyvést obrázek se zarovnáním error Error! View Pohled Change Font Změnit písmo Build Tree Postavit strom Calculate phy tree Vypočítat fylogenetický strom No algorithms for building phylogenetic tree are available. Nejsou dostupné žádné algoritmy pro postavení fylogenetického stromu. Select font for alignment Vybrat písmo pro zarovnání Copy Kopírovat Edit Upravit Export Vyvést Align Zarovnat Tree Strom Advanced Pokročilé Statistics Statistika U2::MSAEditorConsensusArea copy_consensus Copy consensus line Copy consensus Kopírovat shodu Copy consensus with gaps Consensus mode... Režim shody... U2::MSAEditorFactory open_multiple_views Open multiple views Alignment editor Editor zarovnání Open multiple views Otevřít více pohledů U2::MSAEditorNameList Edit sequence name Upravit název sekvence copy_current_sequence Copy current sequence Copy current sequence Kopírovat nynější sekvenci Rename Přejmenovat New sequence name: Nový název sekvence: U2::MSAEditorOffsetsViewController Show offsets Ukázat posuny U2::MSAEditorSequenceArea del_sym Delete gap Remove selection Smazat výběr Copy selection Kopírovat výběr del_col Remove columns of gaps... Remove columns of gaps... ins_sym Insert gap ins_col Insert column of gaps goto_pos Go to position.. Go to position... Jít na místo... Remove all gaps Odstranit všechny mezery Sequence from file... Sekvence ze souboru... Sequence from current project... Sekvence z nynějšího projektu... Sort sequences by name Třídit sekvence podle názvu Replace selected rows with reverse-complement Open file with sequences Otevřít soubor se sekvencemi Go To Jít na Remove columns of gaps... Smazat sloupce z mezer... Fill selection with gaps Vložit mezeru Save subalignment Insert column of gaps Vložit sloupec z mezer Colors Barvy U2::MSAEditorStatusWidget Find: Hledat: Find backward <b>(SHIFT + Enter)</b> Hledat zpět <b>(SHIFT + Enter)</b> Find forward <b>(Enter)</b> Hledat vpřed <b>(Enter)</b> Find in alignment Najít v zarovnání Alignment object is locked Předmět zarovnání je zamčen Alignment object is not locked Předmět zarovnání není zamčen Ln %1 / %2 Řádek %1 / %2 Line %1 of %2 Řádek %1 z %2 Col %1 / %2 Sloupec %1 z %2 Column %1 of %2 Sloupec %1 z %2 U2::MSAEditorUI Consensus Shoda U2::MinMaxSelectorWidget minmax_cutoff Cutoff for minimum and maximum values min_cutoff Minimum: max_cutoff Maximum: invalid_min_max_value Invalid cutoff values Cutoff for minimum and maximum values Nejzazší hranice pro nejnižší a nejvyšší hodnoty Minimum: Maximum: Invalid cutoff values Neplatné nejnižší a nejvyšší hodnoty U2::OpenAnnotatedDNAViewTask Sequences Maximum number of objects per view reached: %1 Byl dosažen největší možný počet předmětů na pohled: %1 Sequence object not available! URL %1, name %2 Není dostupný předmět se sekvencí! Adresa (URL) %1, název %2 No sequence objects found Nebyly nalezeny žádné předměty se sekvencemi U2::OpenMSAEditorTask Multiple alignment object not found Předmět s více zarovnáními nebyl nalezen Opening MSA editor for object: %1 Otevírá se editor MSA pro předmět: %1 openining_msa_editor_for_object_%1 Opening MSA editor for object: %1 U2::OpenSavedAnnotatedDNAViewTask DNA sequence object not found: %1 Předmět se sekvencí DNA nebyl nalezen %1 dna_object_not_found_%1 DNA sequence object not found: %1 U2::OpenSavedMSAEditorTask DNA sequence object not found: %1 Předmět se sekvencí DNA nebyl nalezen %1 dna_object_not_found_%1 DNA sequence object not found: %1 U2::OpenSavedTextObjectViewTask Text object '%1' is not found Předmět s textem '%1' nenalezen U2::OpenSavedTreeViewerTask dna_object_not_found_%1 DNA sequence object not found: %1 DNA sequence object not found: %1 Předmět se sekvencí DNA nebyl nalezen: %1 U2::OpenTreeViewerTask Phylogenetic tree object not found Předmět s fylogenetickým stromem nebyl nalezen Opening tree viewer for object %1 Otevírá se prohlížeč stromu pro předmět: %1 U2::OpenUIndexViewerTask Index object is null Předmět rejstříku je nulový Document is null or loaded Dokument je nulový nebo nahraný Opening index viewer for object %1 Otevírá se prohlížeč rejstříku pro předmět: %1 U2::Overview Toggle annotation density graph Přepnout nákres hustoty poznámek Position Poloha Annotation density Hustota poznámek U2::PanView Zoom In Přiblížit Zoom Out Oddálit Zoom to Selection Přiblížit na výběr Zoom to Whole Sequence Oddálit na celou sekvenci Show All Rows +1 Row -1 Row +5 Rows -5 Rows Reset Rows Number Manage Rows in Zoom View Show Main Ruler Ukázat hlavní pravítko Show Custom Rulers Ukázat vlastní pravítka range change request: [%1, %2] Požadavek na změnu rozsahu: [%1, %2] empty prázdný U2::PanViewRenderArea [%1 %2] U2::SecStructDialog Region Oblast Structure Type Typ stavby U2::SecStructPredictViewAction Predict secondary structure... Předpovědět druhotnou stavbu... U2::SimpleTextObjectViewFactory open_multiple_views Open multiple views task Text editor Textový editor Open multiple views task Úkol otevření více pohledů U2::SmithWatermanDialog Error! Chyba! No matrix registry. No matrix registry. No substitution matrices found. Nenalezeny žádné nahrazovací matice. No filter registry. No filter registry. No algorithm registry. No algorithm registry. No filter registry found. Žádný zápis filtru. No algorithm registry found. Žádný zápis algoritmu. Enter pattern here Zde zadejte vzor Pattern length: %1 Délka vzoru: %1 Matrix not found. Matice nenalezena. SmithWatermanTask Úkol Smith-Waterman Algorithm is not found. Algoritmus nenalezen. Matrix %1 is not found. Matice %1 nenalezena. Filter is not found. Filtr nenalezen. Internal error Vnitřní chyba Pattern is empty Vzor je prázdný Pattern contains unknown symbol Vzor obsahuje neznámý symbol Selecting machines error! Selecting machines error! You didn't select a machine to run remote task! You didn't select a machine to run remote task! Distributed run on many machines is not supported yet. Select 1 machine Distributed run on many machines is not supported yet. Select 1 machine Complement translation is not found. Doplňkový překlad nenalezen. U2::SubstMatrixDialog Scoring matrix: %1 Výsledková matice: %1 min score: Nejmenší výsledek: max score: Největší výsledek: U2::TreeViewer Show sequence names Ukázat názvy sekvencí Show distance labels Ukázat štítky vzdáleností Print tree Vytisknout strom Capture tree Zachytit strom Export tree in SVG Vyvést strom jako SVG Align name labels Zarovnat štítky s názvy Rectangular layout Obdélníkové rozvržení Circular layout Kruhové rozvržení Unrooted layout Vytržené rozvržení Zoom in Přiblížit Zoom out Oddálit Tree Settings... Rectangular Circular Unrooted Branch Settings... Show Names Show Distances Formatting... Align Labels Zoom In Přiblížit Zoom Out Oddálit Reset Zooming Print Tree... Screen Capture... As SVG... Layout Rozvržení Show Labels Export Tree Image U2::TreeViewerFactory Phylogenetic tree viewer Prohlížeč fylogenetického stromu Open multiple views Otevřít více pohledů U2::UIndexExportToNewFileDialogImpl Select file to export Vybrat soubor k vyvedení Error Chyba Illegal file name Neplatný název souboru U2::UIndexSupport Index large file(s)... Error! Chyba! Cannot write output file: unknown io adapter for %1 Cannot read input file: unknown io adapter for %1 error Error! U2::UIndexViewHeaderItemWidgetImpl [All values] filter Filtr [Všechny hodnoty] [Starts with] filter Filtr [Začíná] [Ends with] filter Filtr [Končí] [Contains] filter Filtr [Obsahuje] [Equal] filter Filtr [Rovná se] [Not equal] filter Filtr [Nerovná se] [Greater than] filter Filtr [Větší než] [Lower than] filter Filtr [Menší než] [In range] filter Filtr [V rozsahu] Select new key Vybrat nový klíč Enter a filter value Zadat hodnotu filtru Enter a string value Zadat hodnotu řetězce Enter a number value Zadat hodnotu čísla Enter a lower bound Zadat spodní hranici Enter an upper bound Zadat horní hranici Error Chyba The value can't be empty Hodnota nemůže být prázdná Error! Chyba! Upper bound must be greater than lower Horní hranice musí být větší než spodní hranice U2::UIndexViewWidgetImpl column sloupec No filter selected Nevybrán žádný filtr Document Format Formát dokumentu URL Adresa (URL) None Žádná Hide column Skrýt sloupec Remove column Odstranit sloupec No hidden columns Žádné skryté sloupce Show hidden columns: Ukázat skryté sloupce: Add column Přidat sloupec Complex rule Složené pravidlo U2::UIndexViewer Export Vyvést Save selection to a new file Uložit výběr do souboru Error Chyba No items selected Nevybrány žádné položky U2::UIndexViewerFactory Index viewer Prohlížeč rejstříku Open multiple views Otevřít více pohledů U2::WindowStepSelectorDialog cancel_button Cancel ok_button Ok error_title Error! Cancel Zrušit Ok OK Error! Chyba! U2::WindowStepSelectorWidget window_label Window: invalid_step_value Invalid step value steps_per_window_label Steps per window: step_calculate_fail Illegal step value Window: Okno: Steps per window: Kroků na okno: Illegal step value Selhání ve výpočtu kroku Invalid step value Neplatná hodnota kroku UIndexExportToNewFileDialog ... Ok OK Cancel Zrušit Export indexed document Vyvést rejstříkovaný dokument Export file Vyvést soubor compress file Zhustit soubor UIndexViewHeaderItemWidget Form Create annotation Create annotation Vytvořit poznámky ... UIndexViewWidget Form Create annotation Create annotation Vytvořit poznámky Manage columns Spravovat sloupce Manage columns button Tlačítko Spravovat sloupce > performAlignmentDialog Align Zarovnat Base options Select input file: ... <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> <html><head><meta name="qrichtext" content="1" /><style type="text/css"> p, li { white-space: pre-wrap; } </style></head><body style=" font-family:'MS Shell Dlg 2'; font-size:8.25pt; font-weight:400; font-style:normal;"> <p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-size:8pt;">Translating alignment to amino allows to avoid errors of inserting gaps within codon boundaries.</span></p></body></html> Translate to amino when aligning ugene-1.9.8/src/corelibs/U2View/transl/english.ts0000644000175000017500000042107011651544334020342 0ustar ilyailya AssemblyToRefDialog Align short reads ... Add Remove Start Cancel Align short reads method Select a method to align short reads. Select required align short reads method Select a DNA sequence to align short reads to. This parameter is <b>required</b>. Reference sequence Select the file in SAM format to write the result of alignment into. This parameter is <b>required</b>. Result file name Use an index file instead of a source reference sequence. Prebuilt index SAM output Add short reads here. <b>At least one read</b> should be presented. Short reads AssemblyToSamDialog Convert UGENE assembly data base to SAM format Assembly data base: ... Result SAM file: Convert Cancel BranchSettingsDialog Branch Settings Color Line Weight OK Cancel BuildIndexFromRefDialog Build index Select a method that would be used to align short reads. Align short reads method Select a DNA sequence that would be used to align short reads to. This parameter is <b>required</b>. Reference sequence Specify the index to build for the reference sequence. This parameter is <b>required</b>. Index file name Start ... Cancel ButtonSettingsDialog Button settings Color: Radius: OK Cancel ConsensusSelectorDialog Consensus representation Select consensus representation scheme Consensus type Threshold Reset to default value Reset OK Cancel CreateFileIndexDialog Create index file ... File(s) to index: File(s) to index separated by semicolon File to store index: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> <html><head><meta name="qrichtext" content="1" /><style type="text/css"> p, li { white-space: pre-wrap; } </style></head><body style=" font-family:'MS Shell Dlg 2'; font-size:8.25pt; font-weight:400; font-style:normal;"> <p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-size:8pt;">Path to output index file</span></p></body></html> Compress Add to project Ok Cancel CreatePhyTree Build Phylogenetic Tree Tree building method Save tree to ... Remember Settings Restore Default Build Cancel CreateRulerDialog Create new ruler Ruler name Ruler offset Ruler color Sample Text ... Create Cancel CreateSubalignimentDialog Extract selected as MSA Selected sequences Select all Clear selection From to Invert selection File name ... Add to project Extract Cancel DeleteGapsDialog Remove columns of gaps Remove columns with number of gaps Remove columns with percentage of gaps % % Remove all columns of gaps Remove Cancel EditAnnotationDialog Edit annotation Annotation name Location ... OK Cancel FindDialogBase Find in sequence Find text pattern in sequence Pattern A text pattern to find Search in Search pattern in sequence Sequence Search pattern in translation Translation Strand Both Search pattern in direct strand only Direct Search pattern in complement strand only Complement Algorithm Match percent: A minimal percent to match pattern % Allow mismatches only Substitute Allow insertions and deletions InsDel When this option is used insertions and deletions are not supported. Search with ambiguous bases Find next result Find next Find all results Find All Close Save results as annotations Save as annotations Remove overlaps Clear results Range start: Position: Range end: Selection range Sequence range ObjectViewTask No sequence info found! QObject Generating tree view Swap Siblings Expand Collapse Save As Replace file %1 already exists. Do you want to replace it? SecStructDialog Secondary Structure Prediction Algorithm Range Start: Range End: Results: Total predicted: 0 Start prediction Save As Annotation... Close SmithWatermanDialogBase Smith-Waterman Search Input and output Smith-Waterman parameters Pattern Search in Sequence Translation Strand Both Direct Complement Range Whole sequence Selected range Custom range - Smith-Waterman algorithm parameters Algorithm version Advanced.. Scoring matrix View.. Gap scores Gap open Gap extension Results filtering strategy Minimal score % Report results Remote run... Search Cancel SubstMatrixDialogBase Close TextSettingsDialog Labels Formatting Color Size Font Attributes B I U S OK Cancel TreeSettingsDialog Tree Settings Width Height (Rectangular) Tree View OK Cancel U2::ADVAnnotationCreation New annotation... U2::ADVClipboard Copy sequence Copy translation Copy complement sequence Copy complement translation Copy annotation sequence Copy annotation sequence translation Error! Copy U2::ADVCreateAnnotationsTask Create annotations task U2::ADVSequenceObjectContext Amino translation U2::ADVSingleSequenceHeaderWidget Toggle view Remove sequence Alphabet: <b>%1</b> Sequence size: <b>%1</b> File:&nbsp;<b>%1</b> raw amino dna dna ext rna ext rna U2::ADVSingleSequenceWidget Select sequence region... Sequence region... Sequence between selected annotations Sequence around selected annotations Zoom to range.. Create new ruler... Capture screen Zoom Select Rulers... Remove '%1' Select range Zoom to range Show all views Hide all views Show zoom view Hide zoom view Show details view Hide details view Show overview Hide overview U2::ADVSyncViewManager Lock scales: visible range start Lock scales: selected sequence Lock scales: selected annotation Adjust scales: visible range start Adjust scales: selected sequence Adjust scales: selected annotation Lock scales Adjust scales Toggle views Hide all sequences Show all sequences Hide all zoom views Show all zoom views Hide all details Show all details Hide all overviews Show all overviews Hide %1 Show %1 U2::AnnotatedDNAView Annotations highlighting... Go to position... Find pattern... Insert subsequence... Remove subsequence... Replace subsequence... Selected sequence from view Error! Analyze Add Export Align Remove Edit sequence Disable '%1' highlighting Enable '%1' highlighting Select sequence to associate annotations with: No sequence object found for annotations Go To U2::AnnotatedDNAViewFactory Sequence view U2::AnnotationsTreeView Name Value Objects with annotations... Selected objects with annotations from view Selected annotations and qualifiers Copy qualifier text Copy qualifier URL Toggle column Hide column Copy column text copy column URL Edit item Edit qualifier View qualifier Qualifier... Copy column '%1' text Copy '%1' annotation location Copy column '%1' URL Hide '%1' column Copy qualifier '%1' value Copy qualifier '%1' URL Add '%1' column Rename group Rename qualifier U2::AnnotationsTreeViewL Name Value Objects with annotations... Selected objects with annotations from view Selected annotations and qualifiers Copy qualifier text Copy qualifier URL Toggle column Hide column Copy column text copy column URL Edit item Edit qualifier View qualifier U2Qualifier... Copy column '%1' text Copy '%1' annotation location Copy column '%1' URL Hide '%1' column Copy qualifier '%1' value Copy qualifier '%1' URL Add '%1' column Rename group Rename qualifier U2::AutoAnnotationsADVAction Automatic Annotations Highlighting U2::BuildIndexDialog Open reference sequence Set index file name Build index Reference sequence url is not set! Index file name is not set! U2::ConvertAssemblyToSamDialog Data base to SAM converter Data base file url is not set! SAM file url is not set! Open an assembly data base file Set a result SAM file name U2::CreateFileIndexDialog Select files Select index file to create Error! No input files supplied! Invalid output file name! U2::CreatePhyTreeDialogController Warning Please, input the file name. The seed must be odd. Probably, for that alignment there is no enough memory to run PHYLIP dnadist module. The module will require more than %1 MB in the estimation. It could cause an error. Do you want to continue? U2::CreateRulerDialogController New ruler Error Ruler name is empty! Ruler with the same name is already exists! U2::CreateSubalignimentDialogController Select file to save... Directory to save is not exists No path specified Filename to save is empty Start position must be greater than end position Entered region not contained in current sequence You must select at least one sequence U2::DetView Show complement strand Show amino translations U2::DnaAssemblyDialog Add short reads Open reference sequence DNA Assembly Reference sequence url is not set! Result alignment file name is not set! Short reads list is empty! Set result alignment file name U2::DnaAssemblySupport DNA assembly Align short reads... Build index... Convert UGENE Assembly data base to SAM format... DNA Assembly DNA assembly There are no algorithms for DNA assembly available. Please, check your plugin list. U2::EditAnnotationDialogController Location is empty! Invalid location! Error! Wrong annotation name! New annotation locations is out of sequence bounds! U2::FindDialog Cancel Close Progress %1%. Current position %2 Results found %1 Question? The end of the search region is reached. Restart? Error! Search pattern is empty Pattern length is greater than search range Warning! Search pattern contains symbols that are out of the active alphabet range. Continue anyway? The seach settings were changed from the last search. Clean old results? Results list contains results from the previous search. Clear? %1 overlaps filtered, %2 results left. yes no [%1 %2] translation: %3 complement: %4 U2::GSequenceGraphView Graph settings %1 [%2, %3], Window: %4, Step %5 U2::GSequenceLineViewAnnotated etc ... U2::MSAAlignDialog Set result alignment file name The input file url is empty. Please select file to align. U2::MSAColorSchemeRegistry No colors UGENE Jalview Percentage Identity Zappo Tailor Hydrophobicity Helix propensity Strand propensity Turn propensity Buried index Clustal X U2::MSAEditor Zoom In Zoom Out Zoom To Selection Reset Zoom Change Font Build Tree Export as image Calculate phy tree No algorithms for building phylogenetic tree are available. Select font for alignment Copy Edit Export View Align Tree Advanced Statistics Add U2::MSAEditorConsensusArea Copy consensus Copy consensus with gaps Consensus mode... U2::MSAEditorFactory Alignment editor Open multiple views U2::MSAEditorNameList Edit sequence name Copy current sequence Rename New sequence name: U2::MSAEditorOffsetsViewController Show offsets U2::MSAEditorSequenceArea Remove selection Copy selection Remove columns of gaps... Fill selection with gaps Save subalignment Insert column of gaps Go to position... Remove all gaps Sequence from file... Sequence from current project... Sort sequences by name Replace selected rows with reverse-complement Colors Go To Open file with sequences U2::MSAEditorStatusWidget Find: Find backward <b>(SHIFT + Enter)</b> Find forward <b>(Enter)</b> Find in alignment Alignment object is locked Alignment object is not locked Ln %1 / %2 Line %1 of %2 Col %1 / %2 Column %1 of %2 U2::MSAEditorUI Consensus U2::MinMaxSelectorWidget Cutoff for minimum and maximum values Minimum: Maximum: Invalid cutoff values U2::OpenAnnotatedDNAViewTask Sequences Maximum number of objects per view reached: %1 Sequence object not available! URL %1, name %2 No sequence objects found U2::OpenMSAEditorTask Multiple alignment object not found Opening MSA editor for object: %1 U2::OpenSavedAnnotatedDNAViewTask DNA sequence object not found: %1 U2::OpenSavedMSAEditorTask DNA sequence object not found: %1 U2::OpenSavedTextObjectViewTask Text object '%1' is not found U2::OpenSavedTreeViewerTask DNA sequence object not found: %1 U2::OpenTreeViewerTask Opening tree viewer for object %1 Phylogenetic tree object not found U2::OpenUIndexViewerTask Index object is null Document is null or loaded Opening index viewer for object %1 U2::Overview Toggle annotation density graph Position Annotation density U2::PanView Zoom In Zoom Out Zoom to Selection Zoom to Whole Sequence Show All Rows +1 Row -1 Row +5 Rows -5 Rows Reset Rows Number Manage Rows in Zoom View Show Main Ruler Show Custom Rulers range change request: [%1, %2] empty U2::PanViewRenderArea [%1 %2] U2::SecStructDialog Region Structure Type U2::SecStructPredictViewAction Predict secondary structure... U2::SimpleTextObjectViewFactory Text editor Open multiple views task U2::SmithWatermanDialog No substitution matrices found. No filter registry found. No algorithm registry found. Enter pattern here Pattern length: %1 Matrix not found. Error! SmithWatermanTask Complement translation is not found. Algorithm is not found. Matrix %1 is not found. Filter is not found. Internal error Pattern is empty Pattern contains unknown symbol U2::SubstMatrixDialog Scoring matrix: %1 min score: max score: U2::TreeViewer Tree Settings... Rectangular Circular Unrooted Branch Settings... Show Names Show Distances Formatting... Align Labels Zoom In Zoom Out Reset Zooming Print Tree... Screen Capture... Whole Tree as SVG... Layout Show Labels Export Tree Image U2::TreeViewerFactory Phylogenetic tree viewer Open multiple views U2::UIndexExportToNewFileDialogImpl Select file to export Error Illegal file name U2::UIndexSupport Index large file(s)... Error! Cannot write output file: unknown io adapter for %1 Cannot read input file: unknown io adapter for %1 U2::UIndexViewHeaderItemWidgetImpl [All values] filter [Starts with] filter [Ends with] filter [Contains] filter [Equal] filter [Not equal] filter [Greater than] filter [Lower than] filter [In range] filter Select new key Enter a filter value Enter a string value Enter a number value Enter a lower bound Enter an upper bound Error The value can't be empty Error! Upper bound must be greater than lower U2::UIndexViewWidgetImpl No filter selected Document Format URL None Hide column Remove column No hidden columns Show hidden columns: column Add column Complex rule U2::UIndexViewer Export Save selection to a new file Error No items selected U2::UIndexViewerFactory Index viewer Open multiple views U2::WindowStepSelectorDialog Cancel Ok Error! U2::WindowStepSelectorWidget Window: Steps per window: Illegal step value Invalid step value UIndexExportToNewFileDialog Export indexed document Export file ... compress file Ok Cancel UIndexViewHeaderItemWidget Create annotation ... UIndexViewWidget Create annotation Manage columns Manage columns button > performAlignmentDialog Align Base options Select input file: ... <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> <html><head><meta name="qrichtext" content="1" /><style type="text/css"> p, li { white-space: pre-wrap; } </style></head><body style=" font-family:'MS Shell Dlg 2'; font-size:8.25pt; font-weight:400; font-style:normal;"> <p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-size:8pt;">Translating alignment to amino allows to avoid errors of inserting gaps within codon boundaries.</span></p></body></html> Translate to amino when aligning ugene-1.9.8/src/corelibs/U2Remote/0000755000175000017500000000000011651544334015353 5ustar ilyailyaugene-1.9.8/src/corelibs/U2Remote/U2Remote.pro0000644000175000017500000000301211651544333017532 0ustar ilyailyainclude (U2Remote.pri) # Input HEADERS += src/DistributedComputingUtil.h \ src/PingTask.h \ src/ProtocolInfo.h \ src/ProtocolUI.h \ src/RemoteMachine.h \ src/RemoteMachineMonitor.h \ src/RemoteMachineMonitorDialogController.h \ src/RemoteMachineMonitorDialogImpl.h \ src/RemoteMachineScanDialogImpl.h \ src/RemoteMachineScanner.h \ src/RemoteMachineSettingsDialog.h \ src/RemoteMachineTasks.h \ src/RemoteWorkflowRunTask.h \ src/Serializable.h \ src/SerializeUtils.h \ src/SynchHttp.h \ src/TaskDistributor.h FORMS += src/ui/RemoteMachineMonitorDialog.ui \ src/ui/RemoteMachineScanDialog.ui \ src/ui/RemoteMachineSettingsDialog.ui SOURCES += src/DistributedComputingUtil.cpp \ src/PingTask.cpp \ src/ProtocolInfo.cpp \ src/ProtocolUI.cpp \ src/RemoteMachine.cpp \ src/RemoteMachineMonitor.cpp \ src/RemoteMachineMonitorDialogController.cpp \ src/RemoteMachineMonitorDialogImpl.cpp \ src/RemoteMachineScanDialogImpl.cpp \ src/RemoteMachineScanner.cpp \ src/RemoteMachineSettingsDialog.cpp \ src/RemoteMachineTasks.cpp \ src/RemoteWorkflowRunTask.cpp \ src/Serializable.cpp \ src/SerializeUtils.cpp \ src/SynchHttp.cpp TRANSLATIONS += transl/czech.ts transl/english.ts transl/russian.ts ugene-1.9.8/src/corelibs/U2Remote/U2Remote.pri0000644000175000017500000000132011651544333017524 0ustar ilyailya# include (U2Remote.pri) UGENE_RELATIVE_DESTDIR = '' MODULE_ID=U2Remote include( ../../ugene_lib_common.pri ) QT += network DEFINES+= QT_FATAL_ASSERT BUILDING_U2REMOTE_DLL INCLUDEPATH += ../U2Private/src LIBS += -L../../_release -lU2Core -lU2Misc -lU2Lang -lU2Gui -lU2Private !debug_and_release|build_pass { CONFIG(debug, debug|release) { DESTDIR=../../_debug LIBS -= -L../../_release -lU2Core -lU2Misc -lU2Lang -lU2Gui -lU2Private LIBS += -L../../_debug -lU2Cored -lU2Miscd -lU2Langd -lU2Guid -lU2Privated } CONFIG(release, debug|release) { DESTDIR=../../_release } } unix { target.path = $$UGENE_INSTALL_DIR/$$UGENE_RELATIVE_DESTDIR INSTALLS += target } ugene-1.9.8/src/corelibs/U2Remote/src/0000755000175000017500000000000011651544334016142 5ustar ilyailyaugene-1.9.8/src/corelibs/U2Remote/src/SerializeUtils.h0000644000175000017500000002601711651544334021271 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_SERIALIZE_UTILS_H_ #define _U2_SERIALIZE_UTILS_H_ #include #include #include #include #include #include #include #include //for calloc namespace U2 { class U2REMOTE_EXPORT SerializeUtils { private: static const int SERIALIZED_DNASEQUENCE_LIST_SZ = 3; static const int SERIALIZED_MALIGNMENT_LIST_SZ = 4; static const QString REMOTE_MACHINE_VERSION_1_0; public: template static QVariant serializeValue( const T & t ) { return qVariantFromValue( t ); } template static bool deserializeValue( const QVariant & data, T * val ) { if( NULL == val ) { return false; } if( !data.canConvert() ) { return false; } *val = data.value(); return true; } template static QVariant serializeArray( T * arr, int sz ) { if( NULL == arr ) { return 0; } assert( 0 <= sz ); QVariantList res; for( int i = 0; i < sz; ++i ) { res << serializeValue( arr[i] ); } return res; } /* the arr array must be allocated by caller */ template static bool deserializeArray( const QVariant & data, T * arr, int sz ) { if( data.canConvert( QVariant::Int ) && 0 == data.toInt() ) { return true; } if( 0 >= sz ) { return false; } if( !data.canConvert( QVariant::List ) ) { return false; } QVariantList args = data.toList(); if( args.size() != sz ) { return false; } for( int i = 0; i < sz; ++i ) { if( !deserializeValue( args[i], arr + i ) ) { return false; } } return true; } /* serialization of RemoteMachineSettings: human-readable QString instead of binary QVariant 4 deserialization functions need for tests */ static QString serializeRemoteMachineSettings( RemoteMachineSettings * machine ); static bool deserializeRemoteMachineSettings( const QString & data, RemoteMachineSettings ** settings, QString * protoId = NULL ); static bool deserializeRemoteMachineSettings( const QString & data, RemoteMachine ** machine ); static bool deserializeRemoteMachineSettingsFromFile( const QString & machinePath, RemoteMachine ** machine ); static bool deserializeRemoteMachineSettingsFromFile( const QString & machinePath, RemoteMachineSettings ** machine ); }; // SerializeUtils // serializeValue/deserializeValue template realizations: TODO: is it good to make them inline? template<> inline QVariant SerializeUtils::serializeValue( char * const& str ) { QVariantList res; if( NULL == str ) { res << serializeValue( -1 ); res << QVariant(); } else { int len = strlen( str ); res << serializeValue( len ); res << serializeArray( str, len ); } return res; } template<> inline bool SerializeUtils::deserializeValue( const QVariant & data, char ** str ) { if( NULL == str ) { return false; } *str = NULL; if( !data.canConvert( QVariant::List ) ) { return false; } QVariantList args = data.toList(); if( 2 != args.size() ) { return false; } int sz = 0; if( !deserializeValue( args[0], &sz ) ) { return false; } if( -1 == sz ) { return true; } assert( 0 <= sz ); *str = (char*)calloc( sz + 1, sizeof( char ) ); assert( NULL != str ); if( !deserializeArray( args[1], *str, sz ) ) { return false; } (*str)[sz] = '\0'; return true; } template<> inline QVariant SerializeUtils::serializeValue( DNAAlphabet * const& al ) { QVariantList res; if( NULL != al ) { res << serializeValue( true ); res << serializeValue( al->getId() ); } else { res << serializeValue( false ); res << serializeValue( "" ); } return res; } template<> inline bool SerializeUtils::deserializeValue( const QVariant & data, DNAAlphabet ** al ) { if( NULL == al ) { return false; } *al = NULL; if( !data.canConvert( QVariant::List ) ) { return false; } QVariantList args = data.toList(); if( 2 != args.size() ) { return false; } bool notNullAl = false; QString alId; if( !deserializeValue( args[0], ¬NullAl ) ) { return false; } if( !deserializeValue( args[1], &alId ) ) { return false; } if( notNullAl ) { DNAAlphabetRegistry * alReg = AppContext::getDNAAlphabetRegistry(); assert( NULL != alReg ); *al = alReg->findById( alId ); } return true; } template<> inline QVariant SerializeUtils::serializeValue( const DNASequence & sequence ) { assert( !sequence.isNull() && NULL != sequence.alphabet ); QVariantList res; res << serializeValue( sequence.info ); res << serializeValue( sequence.seq ); res << serializeValue( sequence.alphabet ); return res; } template<> inline bool SerializeUtils::deserializeValue( const QVariant & data, DNASequence * seq ) { if( NULL == seq ) { return false; } if( !data.canConvert( QVariant::List ) ) { return false; } QVariantList args = data.toList(); if( SERIALIZED_DNASEQUENCE_LIST_SZ != args.size() ) { return false; } if( !deserializeValue( args[0], &seq->info ) ) { return false; } if( !deserializeValue( args[1], &seq->seq ) ) { return false; } if( !deserializeValue( args[2], &seq->alphabet ) ) { return false; } assert( NULL != seq->alphabet ); return true; } template<> inline QVariant SerializeUtils::serializeValue( const MAlignmentRow & row) { QVariantList res; res << serializeValue( row.getName() ); res << serializeValue( row.getCore() ); res << serializeValue( row.getCoreLength() ); return res; } template<> inline QVariant SerializeUtils::serializeValue< QList >( const QList< MAlignmentRow> & items ) { QVariantList res; foreach( const MAlignmentRow & item, items ) { res << serializeValue( item ); } return res; } template<> inline bool SerializeUtils::deserializeValue( const QVariant & data, MAlignmentRow* row ) { if( !data.canConvert( QVariant::List ) ) { return false; } QVariantList args = data.toList(); if( 3 != args.size() ) { return false; } QString name; if ( !deserializeValue( args[0], &name) ) { return false; } QByteArray array; if ( !deserializeValue( args[1], &array) ) { return false; } int offset = 0; if ( !deserializeValue( args[2], &offset) ) { return false; } *row= MAlignmentRow(name, array, offset); return true; } template<> inline bool SerializeUtils::deserializeValue< QList >( const QVariant & data, QList< MAlignmentRow > * itemList ) { if( !data.canConvert( QVariant::List ) ) { return false; } QVariantList args = data.toList(); foreach( const QVariant & arg, args ) { MAlignmentRow item; if( !deserializeValue( arg, &item ) ) { return false; } itemList->append( item ); } return true; } template<> inline QVariant SerializeUtils::serializeValue( const MAlignment & ma ) { QVariantList res; res << serializeValue( ma.getAlphabet()); res << serializeValue< QList >( ma.getRows() ); res << serializeValue( ma.getLength() ); res << serializeValue( ma.getInfo() ); return res; } template<> inline bool SerializeUtils::deserializeValue( const QVariant & data, MAlignment * ma ) { if( NULL == ma ) { return false; } if( !data.canConvert( QVariant::List ) ) { return false; } QVariantList args = data.toList(); if( SERIALIZED_MALIGNMENT_LIST_SZ != args.size() ) { return false; } DNAAlphabet* al = NULL; if( !deserializeValue( args[0], &al) ) { return false; } QList rows; if( !deserializeValue< QList >( args[1], &rows) ) { return false; } int len = 0; if( !deserializeValue( args[2], &len) ) { return false; } QVariantMap info; if( !deserializeValue( args[3], &info ) ) { return false; } *ma = MAlignment(MA_OBJECT_NAME, al, rows); ma->setInfo(info); return true; } template<> inline QVariant SerializeUtils::serializeValue( const VirtualFileSystem & vfs ) { QVariantList res; res << serializeValue( vfs.getId() ); QVariantMap resMap; QStringList filenames = vfs.getAllFilenames(); foreach( const QString & filename, filenames ) { QByteArray file = vfs.getFileByName( filename ); resMap.insert( filename, serializeValue( file ) ); } res << serializeValue( resMap ); return res; } template<> inline bool SerializeUtils::deserializeValue( const QVariant & data, VirtualFileSystem * val ) { if( NULL == val ) { return false; } if( !data.canConvert( QVariant::List ) ) { return false; } QVariantList args = data.toList(); if( 2 != args.size() ) { return false; } QString id; if( !deserializeValue( args[0], &id ) ) { return false; } val->setId( id ); QVariantMap filesMap; if( !deserializeValue( args[1], &filesMap ) ) { return false; } foreach( const QString & filename, filesMap.keys() ) { QByteArray fileData; if( !deserializeValue( filesMap[filename], &fileData ) ) { val->removeAllFiles(); return false; } val->createFile( filename, fileData ); } return true; } } // U2 #endif // _U2_SERIALIZE_UTILS_H_ ugene-1.9.8/src/corelibs/U2Remote/src/Serializable.cpp0000644000175000017500000000217311651544334021257 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "Serializable.h" namespace U2 { /***************************** * Serializable *****************************/ Serializable::~Serializable() { } /***************************** * HumanSerializable *****************************/ HumanSerializable::~HumanSerializable() { } } // U2 ugene-1.9.8/src/corelibs/U2Remote/src/ProtocolUI.h0000644000175000017500000000340711651544333020355 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_PROTOCOL_UI_H_ #define _U2_PROTOCOL_UI_H_ #include #include #include #include "RemoteMachine.h" namespace U2 { /* * Base class for GUI form with remote machine info */ class U2REMOTE_EXPORT ProtocolUI : public QWidget { public: ProtocolUI(); virtual ~ProtocolUI(); // after user clicks 'ok', creates remote machine settings based on the info in the form. Caller should delete it virtual RemoteMachineSettings * createMachine() const = 0; virtual void initializeWidget( const RemoteMachineSettings *settings ) = 0; virtual void clearWidget() = 0; virtual QString validate() const = 0; virtual QDialog* createUserTasksDialog(const RemoteMachineSettings* settings, QWidget* parent) = 0; private: ProtocolUI( const ProtocolUI & ); ProtocolUI & operator=( const ProtocolUI & ); }; // ProtocolUI } // U2 #endif // _U2_PROTOCOL_UI_H ugene-1.9.8/src/corelibs/U2Remote/src/PingTask.cpp0000644000175000017500000000307711651544333020374 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include #include #include #include #include #include #include "PingTask.h" namespace U2 { /************************************ * PingTask ***********************************/ PingTask::PingTask(RemoteMachine* m) : Task( tr( "PingTask" ), TaskFlag_None), machine(m) { assert(machine!=NULL); GCOUNTER( cvar, tvar, "PingTask" ); } void PingTask::run() { rsLog.details(tr("Starting remote service ping task, task-id: %1" ).arg( QString::number( getTaskId() ) ) ); machine->ping(stateInfo); rsLog.details(tr("Remote service ping task finished, task-id: %1").arg( QString::number( getTaskId() ) ) ); } } // U2 ugene-1.9.8/src/corelibs/U2Remote/src/PingTask.h0000644000175000017500000000224611651544333020036 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_PING_TASK_H_ #define _U2_PING_TASK_H_ #include namespace U2 { class RemoteMachine; class U2REMOTE_EXPORT PingTask : public Task { Q_OBJECT public: PingTask(RemoteMachine* m); virtual void run(); private: RemoteMachine* machine; }; // PingTask } // U2 #endif // _U2_PING_TASK_H_ ugene-1.9.8/src/corelibs/U2Remote/src/SynchHttp.h0000644000175000017500000000260311651544334020240 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef __SYNC_HTTP_H__ #define __SYNC_HTTP_H__ #include #include #include #include namespace U2 { class U2REMOTE_EXPORT SyncHTTP : public QHttp { Q_OBJECT public: SyncHTTP(const QString& hostName, quint16 port=80, QObject* parent=0); QString syncGet(const QString& path); QString syncPost(const QString & path, QIODevice * data); protected slots: virtual void finished(int idx, bool err); private: int requestID; QEventLoop loop; }; } // U2 #endif ugene-1.9.8/src/corelibs/U2Remote/src/RemoteWorkflowRunTask.h0000644000175000017500000000454511651544334022621 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_REMOTE_WORKFLOW_RUN_TASK_H_ #define _U2_REMOTE_WORKFLOW_RUN_TASK_H_ #include #include #include #include #include namespace U2 { using namespace Workflow; class U2REMOTE_EXPORT RemoteWorkflowRunTask : public Task { Q_OBJECT public: RemoteWorkflowRunTask( RemoteMachineSettings *m, const Schema & sc, const QList & its ); RemoteWorkflowRunTask( RemoteMachineSettings *m, qint64 remoteTaskId); ~RemoteWorkflowRunTask(); static const int TIMER_UPDATE_TIME = 2000; /* 2 seconds */ static const int REMOTE_TASK_TIMEOUT = 30000; virtual void prepare(); virtual void run(); QString generateReport() const; virtual ReportResult report(); qint64 getRemoteTaskId() { return taskId; } private: void preprocessSchema(); static void dumpSchema(const QString& fileName, const QByteArray& schema); private slots: void sl_remoteTaskTimerUpdate(); private: RemoteMachineSettings* machineSettings; RemoteMachine * machine; Schema schema; QList iterations; qint64 taskId; QEventLoop* eventLoop; QStringList outputUrls; QVariantMap taskSettings; // Task is running or enqueued on remote machine already bool taskIsActive; }; // RemoteWorkflowRunTask } // U2 #endif // _U2_REMOTE_WORKFLOW_RUN_TASK_H_ ugene-1.9.8/src/corelibs/U2Remote/src/RemoteMachine.cpp0000644000175000017500000000317711651544333021375 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "RemoteMachine.h" namespace U2 { RemoteMachine::~RemoteMachine() { } RemoteMachineSettings::RemoteMachineSettings( ProtocolInfo * proto, RemoteMachineType type ) : credentials(NULL), machineType(type) { assert( NULL != proto ); protoId = proto->getId(); } RemoteMachineSettings::~RemoteMachineSettings() { flushCredentials(); } void RemoteMachineSettings::flushCredentials() { delete credentials; credentials = NULL; } void RemoteMachineSettings::setupCredentials( const QString& userName, const QString& passwd, bool permanent ) { flushCredentials(); credentials = new UserCredentials; credentials->name = userName; credentials->passwd = passwd; credentials->permanent = permanent; } RemoteMachineFactory::~RemoteMachineFactory() { } } // U2 ugene-1.9.8/src/corelibs/U2Remote/src/ui/0000755000175000017500000000000011651544334016557 5ustar ilyailyaugene-1.9.8/src/corelibs/U2Remote/src/ui/RemoteMachineScanDialog.ui0000644000175000017500000000334111651544334023564 0ustar ilyailya RemoteMachineScanDialog 0 0 425 318 Scan remote machine Add Host Protocol Qt::Horizontal 40 20 Add selected Cancel ugene-1.9.8/src/corelibs/U2Remote/src/ui/RemoteMachineSettingsDialog.ui0000644000175000017500000000333111651544334024477 0ustar ilyailya RemoteMachineSettingsDialog 0 0 332 90 0 0 Remote machine configuration Qt::Vertical 20 36 Qt::Horizontal 40 20 OK Cancel ugene-1.9.8/src/corelibs/U2Remote/src/ui/RemoteMachineMonitorDialog.ui0000644000175000017500000001767611651544334024347 0ustar ilyailya RemoteMachineMonitorDialog 0 0 654 319 Remote machine monitor Remote machine list <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> <html><head><meta name="qrichtext" content="1" /><style type="text/css"> p, li { white-space: pre-wrap; } </style></head><body style=" font-family:'MS Shell Dlg 2'; font-size:8.25pt; font-weight:400; font-style:normal;"> <p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-size:8pt;">The list contains information about available UGENE remote service machines: the web-url, server name, ping and authentification status. </span></p> <p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-size:8pt;">The green </span><a name="result_box"></a><span style=" font-size:8pt;">t</span><span style=" font-size:8pt;">ick in the status means succes, red cross - fail. The question sign means that the connection with these service has not been tested yet. </span></p></body></html> Url Server Name Ping Auth Add new UGENE remote service machine Add new UGENE remote service machine Add... false Remove UGENE remote service machine from list Remove UGENE remote service machine from list Remove false Modify settings of existing UGENE remote service machine Modify settings of existing UGENE remote service machine Modify... false Test connection with selected remote machine <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> <html><head><meta name="qrichtext" content="1" /><style type="text/css"> p, li { white-space: pre-wrap; } </style></head><body style=" font-family:'MS Shell Dlg 2'; font-size:8.25pt; font-weight:400; font-style:normal;"> <p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-size:8pt;">The connection is tested in two steps.</span></p> <p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-size:8pt;">First a PING command is sent to remote service, then an authentification information is sent (AUTH command) and active session is started. </span></p></body></html> Test Connection false Show user remote tasks statistics Activate User Tasks dialog, to check finished and ongoing tasks status, retrieve results or delete remote tasks. Show User Tasks Qt::Vertical 20 40 Add available public machines to the list Add available public machines to the list Get Public Machines Qt::Horizontal 40 20 OK Cancel 0 80 Events log ugene-1.9.8/src/corelibs/U2Remote/src/RemoteMachineSettingsDialog.cpp0000644000175000017500000000620711651544334024234 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include #include #include #include "RemoteMachineSettingsDialog.h" namespace U2 { RemoteMachineSettingsDialog::RemoteMachineSettingsDialog(QWidget* parent, RemoteMachineSettings* settings) : QDialog(parent), machineSettings( settings ), currentUi( NULL ) { setupUi( this ); ProtocolInfoRegistry * pir = AppContext::getProtocolInfoRegistry(); assert( NULL != pir ); QList< ProtocolInfo* > protoInfos = pir->getProtocolInfos(); assert(protoInfos.size() > 0); ProtocolInfo* pi = protoInfos.first(); currentUi = pi->getProtocolUI(); QVBoxLayout * topLayout = qobject_cast< QVBoxLayout* >( layout() ); topLayout->insertWidget( 0, currentUi ); protoId = pi->getId(); if (machineSettings != NULL) { currentUi->initializeWidget(machineSettings); } connect( cancelPushButton, SIGNAL( clicked() ), SLOT( reject() ) ); connect( okPushButton, SIGNAL( clicked() ), SLOT( sl_okPushButtonClicked() ) ); } RemoteMachineSettingsDialog::~RemoteMachineSettingsDialog() { if( NULL != currentUi ) { QVBoxLayout * topLayout = qobject_cast< QVBoxLayout* >( layout() ); assert( NULL != topLayout ); Q_UNUSED(topLayout); currentUi->setParent( NULL ); } } RemoteMachineSettings * RemoteMachineSettingsDialog::getMachineSettings() const { return machineSettings; } void RemoteMachineSettingsDialog::sl_okPushButtonClicked() { QString error = currentUi->validate(); if( !error.isEmpty() ) { QMessageBox::critical( this, tr( "Error!" ), error ); return; } createMachineSettings(); QDialog::accept(); } void RemoteMachineSettingsDialog::showErrorLabel( const QString& msg ) { assert( !msg.isEmpty() ); QLabel * errorLabel = new QLabel( msg, this ); QVBoxLayout * topLayout = qobject_cast< QVBoxLayout* >( layout() ); assert( NULL != topLayout ); topLayout->insertWidget( 0, errorLabel ); } void RemoteMachineSettingsDialog::createMachineSettings() { assert( !protoId.isEmpty() ); machineSettings = currentUi->createMachine(); if( NULL == machineSettings ) { QMessageBox::critical( this, tr( "Error!" ), tr( "Sorry! Cannot create remote machine" ) ); } } } // U2 ugene-1.9.8/src/corelibs/U2Remote/src/RemoteWorkflowRunTask.cpp0000644000175000017500000002402011651544334023142 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include #include #include #include #include #include #include #include #include #include #include #include #include #include "RemoteWorkflowRunTask.h" namespace U2 { #define TASK_OUTPUT_DIR "out/" #define TASK_INPUT_DIR "in/" /*************************************** * RemoteWorkflowRunTask ***************************************/ RemoteWorkflowRunTask::RemoteWorkflowRunTask( RemoteMachineSettings * m, const Schema & sc, const QList & its ) : Task( tr( "Workflow run task on the cloud" ), TaskFlags_FOSCOE | TaskFlag_ReportingIsSupported | TaskFlag_ReportingIsEnabled ), machineSettings( m ), machine( NULL ), schema( sc ), iterations( its ), taskId(0), eventLoop(NULL),taskIsActive(false) { GCOUNTER(cvar, tvar, "WorkflowOnTheCloud"); if( NULL == machineSettings ) { setError( tr("Bad remote machine settings")); return; } tpm = Progress_Manual; } RemoteWorkflowRunTask::RemoteWorkflowRunTask( RemoteMachineSettings *m, qint64 remoteTaskId ) : Task( tr( "Workflow run task on the cloud" ), TaskFlags_FOSCOE | TaskFlag_ReportingIsSupported | TaskFlag_ReportingIsEnabled), machineSettings( m ), machine( NULL ), taskId(remoteTaskId), eventLoop(NULL), taskIsActive(true) { GCOUNTER(cvar, tvar, "WorkflowOnTheCloud"); if( NULL == machineSettings ) { setError( tr("Bad remote machine settings")); return; } tpm = Progress_Manual; } void RemoteWorkflowRunTask::preprocessSchema() { foreach( Actor * actor, schema.getProcesses() ) { assert( NULL != actor ); if( actor->getParameter( BaseAttributes::URL_IN_ATTRIBUTE().getId() ) != NULL && actor->getParameter( BaseAttributes::URL_LOCATION_ATTRIBUTE().getId()) == NULL ) { actor->addParameter( BaseAttributes::URL_LOCATION_ATTRIBUTE().getId(), new Attribute( BaseAttributes::URL_LOCATION_ATTRIBUTE(), BaseTypes::BOOL_TYPE(), false, true ) ); } QList::iterator it = iterations.begin(); ActorId id = actor->getId(); while( it != iterations.end() ) { QList parameterNames = actor->getParameters().keys(); foreach( const QString & paramName, parameterNames ) { if( !it->cfg[id].contains( paramName ) ) { it->cfg[id][paramName] = actor->getParameter( paramName )->getAttributePureValue(); } } ++it; } } } void RemoteWorkflowRunTask::dumpSchema(const QString& fileName, const QByteArray& schema) { QFile file(fileName); file.open(QIODevice::WriteOnly); file.write(schema); file.close(); } void RemoteWorkflowRunTask::prepare() { if( hasError() || isCanceled() ) { return; } rsLog.trace(tr("Started remote workflow task")); machine = AppContext::getProtocolInfoRegistry()->getProtocolInfo( machineSettings->getProtocolId() ) ->getRemoteMachineFactory()->createInstance( machineSettings ); if( NULL == machine ) { setError( tr( "Cannot create remote machine from remote machine settings: %1" ).arg( machineSettings->getName()) ); return; } stateInfo.progress = 0; if (taskIsActive) { return; } preprocessSchema(); QStringList inputUrls; foreach( Actor * actor, schema.getProcesses() ) { assert( NULL != actor ); ActorId actorId = actor->getId(); Attribute * urlInAttr = actor->getParameter( BaseAttributes::URL_IN_ATTRIBUTE().getId() ); if( NULL != urlInAttr ) { QList::iterator it = iterations.begin(); while( it != iterations.end() ) { if( it->cfg[actorId].value( BaseAttributes::URL_LOCATION_ATTRIBUTE().getId() ).value() ) { // file located on this computer QString urlpath = it->cfg[actorId].value( BaseAttributes::URL_IN_ATTRIBUTE().getId() ).value(); // multiple urls are in the same string // TODO: folder contents handling QStringList urls = urlpath.split(';', QString::SkipEmptyParts); QStringList newPathes; foreach (const GUrl& filePath, urls) { QString path = TASK_INPUT_DIR + filePath.fileName(); inputUrls.append(filePath.getURLString()); newPathes.append(path); } // skip first semicolon QString newPath = newPathes.join(";"); it->cfg[actorId][BaseAttributes::URL_IN_ATTRIBUTE().getId()] = newPath; } ++it; } } Attribute * urlOutAttr = actor->getParameter( BaseAttributes::URL_OUT_ATTRIBUTE().getId() ); if( NULL != urlOutAttr ) { assert( NULL == actor->getParameter( BaseAttributes::URL_LOCATION_ATTRIBUTE().getId() ) ); QList::iterator it = iterations.begin(); while( it != iterations.end() ) { QVariantMap cfg = it->getParameters( actorId ); GUrl filePath = cfg.value( BaseAttributes::URL_OUT_ATTRIBUTE().getId() ).value(); QString newPath = TASK_OUTPUT_DIR + filePath.fileName(); outputUrls.append(filePath.getURLString()); it->cfg[actorId][BaseAttributes::URL_OUT_ATTRIBUTE().getId()] = newPath; ++it; } } } schema.getIterations() = iterations; QByteArray rawData = HRSchemaSerializer::schema2String(schema, NULL).toUtf8(); taskSettings.insert(CoreLibConstants::WORKFLOW_SCHEMA_ATTR, rawData); taskSettings.insert(CoreLibConstants::DATA_IN_ATTR, inputUrls); taskSettings.insert(CoreLibConstants::DATA_OUT_ATTR, outputUrls); rsLog.trace("Schema is preprocessed for sending to remote service"); #ifdef _DEBUG assert(!WorkflowUtils::WD_FILE_EXTENSIONS.isEmpty()); dumpSchema("dump." + WorkflowUtils::WD_FILE_EXTENSIONS.first(), rawData); #endif } void RemoteWorkflowRunTask::run() { if (!taskIsActive) { taskId = machine->runTask(stateInfo, CoreLibConstants::WORKFLOW_ON_CLOUD_TASK_ID, taskSettings); if (hasError()) { return; } } eventLoop = new QEventLoop(this); QTimer::singleShot(RemoteWorkflowRunTask::TIMER_UPDATE_TIME, this, SLOT(sl_remoteTaskTimerUpdate())); eventLoop->exec(QEventLoop::ExcludeUserInputEvents); delete eventLoop; eventLoop = NULL; } void RemoteWorkflowRunTask::sl_remoteTaskTimerUpdate() { assert( eventLoop != NULL ); if (isCanceled()) { machine->cancelTask(stateInfo, taskId); eventLoop->exit(); return; } State state = State_Running; state = machine->getTaskState(stateInfo, taskId); if (hasError()) { eventLoop->exit(); return; } if (state == State_Finished) { rsLog.trace("Workflow task finished on remote host."); if (!outputUrls.isEmpty()) { machine->getTaskResult(stateInfo, taskId, outputUrls, TASK_OUTPUT_DIR); if (hasError()) { eventLoop->exit(); return; } rsLog.trace("Retrieved result data from remote host."); } eventLoop->exit(); return; } int progress = machine->getTaskProgress(stateInfo, taskId); if (hasError()) { eventLoop->exit(); return; } stateInfo.progress = progress; QTimer::singleShot( RemoteWorkflowRunTask::TIMER_UPDATE_TIME, this, SLOT( sl_remoteTaskTimerUpdate() ) ); } QString RemoteWorkflowRunTask::generateReport() const { QString res; res+=""; res+=QString("").arg(tr("Task")).arg(tr("Status")).arg(tr("Details")); QString name = Qt::escape(getTaskName()); QString status = hasError() ? tr("Failed") : isCanceled() ? tr("Canceled") : tr("Finished"); QString error = Qt::escape(getError()).replace("\n", "
    "); if (hasError()) { name = ""+name+""; status = ""+status+""; } else if (isCanceled()) { status = ""+status+""; } else { status = ""+status+""; } res+=QString("").arg(name).arg(status).arg(error); res += QString("").arg(tr("Output files:")); foreach(QString url, outputUrls) { if(QFile::exists(url)) { res += QString("").arg(url).arg(url); } } res+=""; res+="
    %1%2%3
    %1%2%3
    %1
    %2
    "; return res; } Task::ReportResult RemoteWorkflowRunTask::report() { if (!hasError() && !isCanceled()) { rsLog.details("Remote task finished successfully"); } return ReportResult_Finished; } RemoteWorkflowRunTask::~RemoteWorkflowRunTask() { delete machine; } } // ~ U2 ugene-1.9.8/src/corelibs/U2Remote/src/RemoteMachine.h0000644000175000017500000001027011651544333021032 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_REMOTE_MACHINE_H_ #define _U2_REMOTE_MACHINE_H_ #include "ProtocolInfo.h" #include "Serializable.h" #include namespace U2 { class RemoteMachineSettings; /* * Base class for RemoteMachines. Should be implemented for each transport protocol. * Stores all required remote machine info, performs remote requests. */ class U2REMOTE_EXPORT RemoteMachine { public: virtual ~RemoteMachine(); // Runs task on remote machine. Returns remote taskId virtual qint64 runTask( TaskStateInfo& si, const QString & taskFactoryId, const QVariant & settings) = 0; // Cancels remote task virtual void cancelTask(TaskStateInfo& si, qint64 taskId ) = 0; // Retrieves remote task state virtual Task::State getTaskState(TaskStateInfo& si, qint64 taskId) = 0; // Retrieves remote task progress [0..100%] virtual int getTaskProgress(TaskStateInfo& si, qint64 taskId) = 0; // Retrieves remote task result virtual void getTaskResult(TaskStateInfo& si, qint64 taskId, const QStringList& resultUrls, const QString& urlPrefix ) = 0; // Retrieves remote task error message virtual QString getTaskErrorMessage(TaskStateInfo& si, qint64 taskId) = 0; // Returns remote machine server name. TODO: refactor virtual QString getServerName(TaskStateInfo& si) = 0; // Lists active tasks ids on remote machine virtual QList getActiveTasks(TaskStateInfo& si) = 0; // Pings remote machine virtual void ping(TaskStateInfo& si) = 0; virtual const RemoteMachineSettings* getSettings() const = 0; }; // RemoteMachine /* * The type determines how to treat remote machine. * In case of remote service the remote tasks are launched via UGENE remote service protocol. */ enum RemoteMachineType { RemoteMachineType_SimpleMachine, RemoteMachineType_RemoteService }; /* * Authentication information */ struct U2REMOTE_EXPORT UserCredentials { QString name; QString passwd; bool permanent; }; /* * Base class for remote machine settings */ class U2REMOTE_EXPORT RemoteMachineSettings : public HumanSerializable { public: RemoteMachineSettings( ProtocolInfo * proto, RemoteMachineType type ); virtual ~RemoteMachineSettings(); RemoteMachineType getMachineType() const { return machineType; } const QString& getProtocolId() const {return protoId;} void flushCredentials(); void setupCredentials(const QString& userName, const QString& passwd, bool permanent ); UserCredentials* getUserCredentials() const { return credentials; } virtual QString serialize() const = 0; virtual QString getName() const = 0; virtual bool usesGuestAccount() const = 0; virtual bool operator==( const RemoteMachineSettings& ) const = 0; protected: UserCredentials* credentials; QString protoId; RemoteMachineType machineType; }; // RemoteMachineSettings /* * Base class for RemoteMachinesFactories */ class U2REMOTE_EXPORT RemoteMachineFactory { public: virtual ~RemoteMachineFactory(); virtual RemoteMachine * createInstance( const QString & serializedSettings ) const = 0; virtual RemoteMachine * createInstance( RemoteMachineSettings * settings ) const = 0; virtual RemoteMachineSettings * createSettings( const QString & serializedSettings ) const = 0; }; // RemoteMachineFactory } // U2 #endif // U2_REMOTE_MACHINE_H_ ugene-1.9.8/src/corelibs/U2Remote/src/RemoteMachineScanDialogImpl.h0000644000175000017500000000435711651544334023613 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_REMOTE_MACHINE_SCAN_DIALOG_IMPL_H_ #define _U2_REMOTE_MACHINE_SCAN_DIALOG_IMPL_H_ #include #include #include #include namespace U2 { typedef QList< RemoteMachineSettings * > RemoteMachineScanDialogModel; class RemoteMachineScanDialogImpl : public QDialog, public Ui::RemoteMachineScanDialog { Q_OBJECT public: static const int SCAN_UPDATE_TIME = 500; /* 0.5 seconds */ public: RemoteMachineScanDialogImpl(); ~RemoteMachineScanDialogImpl(); RemoteMachineScanDialogModel getModel() const; private: void addMachines( const QList< RemoteMachineSettings* > newMachines ); void addMachine( RemoteMachineSettings * machine ); void addNextMachineToTable( RemoteMachineSettings * ); void cleanup(); bool hasSameMachineInTheList( RemoteMachineSettings* ) const; void resizeTable(); private slots: void sl_cancelPushButtonClicked(); void sl_okPushButtonClicked(); void sl_startScan( const QString & protoId ); void sl_updatePushButtonClicked(); private: RemoteMachineScanDialogModel model; /* machines by order as in the table */ QList< RemoteMachineScanner * > runningScanners; QTimer updateTimer; }; // RemoteMachineScanDialogImpl } // U2 #endif // _U2_REMOTE_MACHINE_SCAN_DIALOG_IMPL_H_ ugene-1.9.8/src/corelibs/U2Remote/src/ProtocolInfo.h0000644000175000017500000000426611651544333020737 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_PROTOCOL_INFO_H_ #define _U2_PROTOCOL_INFO_H_ #include #include #include #include namespace U2 { class RemoteTaskServer; class ProtocolUI; class RemoteMachineFactory; class RemoteMachineScanner; class U2REMOTE_EXPORT ProtocolInfo { public: ProtocolInfo( const QString &id, ProtocolUI *protocolUI, RemoteMachineFactory *remoteMachineFactory); ProtocolUI *getProtocolUI() const; RemoteMachineFactory *getRemoteMachineFactory() const; // TODO: do we need version? QString getId() const; private: RemoteMachineScanner *getRemoteMachineScanner() const; RemoteTaskServer *getRemoteTaskServer() const; private: RemoteTaskServer *server; ProtocolUI *protocolUI; RemoteMachineFactory *remoteMachineFactory; RemoteMachineScanner *scanner; QString id; }; // ProtocolInfo class U2REMOTE_EXPORT ProtocolInfoRegistry { public: void registerProtocolInfo( ProtocolInfo *info ); bool unregisterProtocolInfo( const QString &id ); bool isProtocolInfoRegistered( const QString &id ) const; ProtocolInfo *getProtocolInfo( const QString &id ) const; QList< ProtocolInfo * > getProtocolInfos() const; private: QMap< QString, ProtocolInfo * > protocolInfos; }; // ProtcolInfoRegistry } // U2 #endif // _U2_PROTOCOL_INFO_H_ ugene-1.9.8/src/corelibs/U2Remote/src/RemoteMachineMonitorDialogController.h0000644000175000017500000000236611651544333025575 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_REMOTE_MACHINE_MONITOR_DIALOG_CTRL_H_ #define _U2_REMOTE_MACHINE_MONITOR_DIALOG_CTRL_H_ #include #include namespace U2 { class U2REMOTE_EXPORT RemoteMachineMonitorDialogController { public: static RemoteMachineSettings* selectRemoteMachine(RemoteMachineMonitor* monitor, bool runTaskMode = false ); }; } // U2 #endif ugene-1.9.8/src/corelibs/U2Remote/src/RemoteMachineMonitorDialogImpl.h0000644000175000017500000001016211651544334024345 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_REMOTE_MACHINE_MONITOR_DIALOG_IMPL_H_ #define _U2_REMOTE_MACHINE_MONITOR_DIALOG_IMPL_H_ #include #include #include #include #include namespace U2 { class RemoteTask; class RetrievePublicMachinesTask; class UpdateActiveTasks; class RemoteMachinesMonitor; struct RemoteMachineItemInfo { RemoteMachineSettings * settings; QString hostname; bool isSelected; RemoteMachineItemInfo( RemoteMachineSettings * s) : settings( s ) { assert( NULL != settings ); } RemoteMachineItemInfo() : settings( NULL ), isSelected(false) { } }; // RemoteMachineMonitorItemInfo class RemoteMachineMonitorDialogImpl : public QDialog, Ui::RemoteMachineMonitorDialog { Q_OBJECT private: static const QString OK_BUTTON_RUN; static const int CHECKBOX_SIZE_HINT_MAGIC_NUMBER = 2; static const QString SAVE_SETTINGS_FILE_DOMAIN; public: RemoteMachineMonitorDialogImpl( QWidget * p, RemoteMachineMonitor* monitor, bool runTaskMode = false ); QList< RemoteMachineItemInfo > getModel() const; RemoteMachineSettings* getSelectedMachine() const; private: bool addMachine( RemoteMachineSettings * machine, bool ping ); QTreeWidgetItem * addItemToTheView( RemoteMachineItemInfo & item ); int topLevelItemsSelectedNum() const; int getSelectedTopLevelRow() const; bool hasSameMachineInTheView( RemoteMachineSettings * machine ) const; void enableItem( QTreeWidgetItem * item, bool enable ); bool removeDialogItemAt( int row ); /* returns if item was successfully removed */ bool checkCredentials(RemoteMachineSettings* settings); void checkBoxStateChanged( QCheckBox * cb, bool enable ); RemoteMachineItemInfo& getItemInfo(QTreeWidgetItem* item); void pingMachine( RemoteMachineSettings * settings, QTreeWidgetItem * item ); void resizeTreeWidget(); void initMachineActionsMenu(); void updateState(); private slots: void sl_okPushButtonClicked(); void sl_cancelPushButtonClicked(); void sl_addPushButtonClicked(); void sl_removePushButtonClicked(); void sl_modifyPushButtonClicked(); void sl_selectionChanged(); void sl_retrieveInfoTaskStateChanged(); void sl_pingPushButtonClicked(); void sl_getPublicMachinesButtonClicked(); void sl_getPublicMachinesTaskStateChanged(); void sl_machinesTreeMenuRequested(const QPoint&); void sl_showUserTasksButtonClicked(); void sl_saveMachine(); private: QMenu* machineActionsMenu; int currentlySelectedItemIndex; QList< RemoteMachineItemInfo > machinesItemsByOrder; QMap< RemoteMachineSettings *, QTreeWidgetItem * > pingingItems; /* ping sent to machines with this items */ /* not static because QApplication must be constructed before any graphical object */ const QPixmap PING_YES; const QPixmap PING_NO; const QPixmap PING_WAIT_FOR_RESPONSE; const QPixmap PING_QUESTION; RemoteMachineMonitor* rmm; RetrievePublicMachinesTask * getPublicMachinesTask; }; // RemoteMachineMonitorDialogImpl } // U2 #endif // _U2_REMOTE_MACHINE_MONITOR_DIALOG_IMPL_H_ ugene-1.9.8/src/corelibs/U2Remote/src/DistributedComputingUtil.h0000644000175000017500000000416011651544333023321 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_DISTRIBUTED_COMPUTING_UTIL_H #define _U2_DISTRIBUTED_COMPUTING_UTIL_H #include #include #include namespace U2 { class PingTask; class U2REMOTE_EXPORT DistributedComputingUtil : public QObject { Q_OBJECT public: DistributedComputingUtil(); ~DistributedComputingUtil(); /* remote machines has some services that are only for internal usage. this function filters them */ static QStringList filterRemoteMachineServices( const QStringList & services ); private slots: void sl_showRemoteMachinesMonitor(); private: /* pointers here to manage object creation order */ ProtocolInfoRegistry * pir; RemoteMachineMonitor * rmm; }; // DistributedComputingUtil /* Checks for active tasks and adds them to TaskScheduler */ class UpdateActiveTasks : public Task { Q_OBJECT public: UpdateActiveTasks( RemoteMachineSettings* s); ~UpdateActiveTasks(); virtual void run(); RemoteMachineSettings* getSettings() { return settings; } private: RemoteMachineSettings* settings; RemoteMachine* machine; void addTaskToScheduler(qint64 taskid); }; // UpdateActiveTasks } // U2 #endif // _U2_DISTRIBUTED_COMPUTING_UTIL_H ugene-1.9.8/src/corelibs/U2Remote/src/RemoteMachineScanner.h0000644000175000017500000000327011651544334022347 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_REMOTE_MACHINE_SCANNER_H_ #define _U2_REMOTE_MACHINE_SCANNER_H_ #include #include "RemoteMachine.h" namespace U2 { /* * Base class. Each transport protocol that can scan remote machines should implement this */ class U2REMOTE_EXPORT RemoteMachineScanner : public QObject { public: RemoteMachineScanner( bool filter = true ); virtual ~RemoteMachineScanner(); virtual void startScan() = 0; /* creates new allocated list of machine settings. caller should delete them. returned machines - newly scanned since startScan() */ virtual QList< RemoteMachineSettings * > takeScanned() = 0; virtual void setFilterLocalHost( bool filter ); virtual bool getFilterLocalHost() const; protected: bool filterLocalHost; }; // RemoteMachineScanner } // U2 #endif // _U2_REMOTE_MACHINE_SCANNER_H_ ugene-1.9.8/src/corelibs/U2Remote/src/RemoteMachineMonitor.cpp0000644000175000017500000001315211651544333022737 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include #include #include "SerializeUtils.h" #include "RemoteMachineMonitor.h" namespace U2 { const QString RemoteMachineMonitor::REMOTE_MACHINE_MONITOR_SETTINGS_TAG = "rservice/machines"; RemoteMachineMonitor::RemoteMachineMonitor() : initialized( false ) { } void RemoteMachineMonitor::ensureInitialized() { if (!initialized) { initialize(); } } void RemoteMachineMonitor::initialize() { assert(!initialized); initialized = true; Settings * settings = AppContext::getSettings(); assert( NULL != settings ); if( !deserializeMachines( settings->getValue( REMOTE_MACHINE_MONITOR_SETTINGS_TAG ) ) ) { qDeleteAll( getMachinesList() ); items.clear(); return; } } RemoteMachineMonitor::~RemoteMachineMonitor() { if (!initialized) { return; } saveSettings(); qDeleteAll( getMachinesList() ); } void RemoteMachineMonitor::saveSettings() { if (!initialized) { return; } Settings * settings = AppContext::getSettings(); assert( NULL != settings ); QVariant serializedMachines = serializeMachines(); assert( serializedMachines.isValid() ); settings->setValue( REMOTE_MACHINE_MONITOR_SETTINGS_TAG, serializedMachines ); } QVariant RemoteMachineMonitor::serializeMachines() const { QVariantList res; foreach( const RemoteMachineMonitorItem & item, items ) { QVariantList itemRes; itemRes << QVariant( SerializeUtils::serializeRemoteMachineSettings( item.machine ) ); itemRes << QVariant( item.selected ); res << QVariant( itemRes ); } return res; } bool RemoteMachineMonitor::deserializeMachines( const QVariant & data ) { if( !data.canConvert( QVariant::List ) ) { return false; } QVariantList args = data.toList(); foreach( QVariant arg, args ) { if( !arg.canConvert( QVariant::List ) ) { return false; } QVariantList itemArgs = arg.toList(); if( 2 != itemArgs.size() ) { return false; } RemoteMachineMonitorItem item; if( !SerializeUtils::deserializeRemoteMachineSettings( itemArgs[0].toString(), &item.machine ) ) { assert( NULL == item.machine ); return false; } if( !SerializeUtils::deserializeValue( itemArgs[1], &item.selected ) ) { return false; } items << item; } return true; } bool RemoteMachineMonitor::addMachine( RemoteMachineSettings * machine, bool selected ) { ensureInitialized(); if( NULL == machine || hasMachineInMonitor( machine ) ) { return false; } items.append( RemoteMachineMonitorItem( machine, selected ) ); return true; } void RemoteMachineMonitor::setSelected( RemoteMachineSettings * machine, bool selected ) { if( NULL == machine ) { return; } int sz = items.size(); for( int i = 0; i < sz; ++i ) { RemoteMachineMonitorItem & item = items[i]; if( item.machine == machine ) { item.selected = selected; break; } } } bool RemoteMachineMonitor::hasMachineInMonitor( RemoteMachineSettings * machine ) const { assert( NULL != machine ); foreach( const RemoteMachineMonitorItem & item, items ) { if( item.machine == machine ) { return true; } } return false; } void RemoteMachineMonitor::removeMachine( RemoteMachineSettings * machine ) { ensureInitialized(); if( NULL == machine || !hasMachineInMonitor( machine ) ) { return; } int at = -1; int sz = items.size(); for( int i = 0; i < sz; ++i ) { if( items.at( i ).machine == machine ) { at = i; break; } } assert( -1 != at ); delete items.at( at ).machine; items.removeAt( at ); } QList< RemoteMachineSettings * > RemoteMachineMonitor::getMachinesList() { ensureInitialized(); QList< RemoteMachineSettings* > ret; foreach( const RemoteMachineMonitorItem & item, items ) { ret << item.machine; } return ret; } QList< RemoteMachineMonitorItem > RemoteMachineMonitor::getRemoteMachineMonitorItems() { ensureInitialized(); return items; } QList< RemoteMachineSettings* > RemoteMachineMonitor::getSelectedMachines() { ensureInitialized(); QList< RemoteMachineSettings* > res; foreach( const RemoteMachineMonitorItem & item, items ) { if( item.selected ) { res << item.machine; } } return res; } RemoteMachineSettings* RemoteMachineMonitor::findMachine( const QString& id ) const { foreach ( const RemoteMachineMonitorItem& item, items) { if (item.machine->serialize() == id ) { return item.machine; } } return NULL; } } // U2 ugene-1.9.8/src/corelibs/U2Remote/src/RemoteMachineTasks.cpp0000644000175000017500000001613311651544334022400 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "RemoteMachineTasks.h" #include "PingTask.h" #include "SynchHttp.h" #include #include #include #include #include #include #include "SerializeUtils.h" #include #include namespace U2 { /******************************************* * RetrieveRemoteMachineInfoTask *******************************************/ RetrieveRemoteMachineInfoTask::RetrieveRemoteMachineInfoTask( RemoteMachineSettings* s ) : Task( tr( "Retrieve remote machine info task" ), TaskFlags_FOSCOE ), pingTask(NULL), pingOK(false), machine( NULL ), settings(s) { setVerboseLogMode(true); setErrorNotificationSuppression(true); } RetrieveRemoteMachineInfoTask::~RetrieveRemoteMachineInfoTask() { delete machine; machine = NULL; } void RetrieveRemoteMachineInfoTask::prepare() { rsLog.details(tr("Retrieving remomote machine info..." )); ProtocolInfo* pi = AppContext::getProtocolInfoRegistry()->getProtocolInfo( settings->getProtocolId() ); machine = pi->getRemoteMachineFactory()->createInstance(settings); if( NULL == machine ) { setError( tr( "Cannot create remote machine from remote machine settings: %1" ).arg( settings->getName() ) ); return; } pingTask = new PingTask(machine); addSubTask( pingTask ); } void RetrieveRemoteMachineInfoTask::run() { if( hasError() || isCanceled() ) { return; } assert( NULL != machine ); if( isCanceled() ) { return; } hostname = machine->getServerName(stateInfo); } Task::ReportResult RetrieveRemoteMachineInfoTask::report() { if( pingTask->isCanceled() ) { pingTask->setError( tr( "Ping task is canceled by user" ) ); } if( pingTask->hasError() ) { setError( tr( "Ping task finished with error: " ) + pingTask->getError() ); pingOK = false; return ReportResult_Finished; } pingOK = true; if( isCanceled() ) { setError( tr( "Task is canceled by user" ) ); return ReportResult_Finished; } return ReportResult_Finished; } QStringList RetrieveRemoteMachineInfoTask::getServicesList() const { return services; } QString RetrieveRemoteMachineInfoTask::getHostName() const { return hostname; } bool RetrieveRemoteMachineInfoTask::isPingOk() const { return pingOK; } /******************************************* * RetrievePublicMachinesTask *******************************************/ const QString RetrievePublicMachinesTask::PUBLIC_MACHINES_KEEPER_SERVER = "http://ugene.unipro.ru"; const QString RetrievePublicMachinesTask::PUBLIC_MACHINES_KEEPER_PAGE = "/public_machines.html"; const QString RetrievePublicMachinesTask::PUBLIC_MACHINES_STR_SEPARATOR = "
    "; RetrievePublicMachinesTask::RetrievePublicMachinesTask() : Task( "Retrieve public remote machines", TaskFlag_None ) { setVerboseLogMode(true); setErrorNotificationSuppression(true); } RetrievePublicMachinesTask::~RetrievePublicMachinesTask() { qDeleteAll( publicMachines ); } void RetrievePublicMachinesTask::run() { rsLog.details(tr("Retrieving public machines...")); SyncHTTP http( QUrl( PUBLIC_MACHINES_KEEPER_SERVER ).host() ); NetworkConfiguration * nc = AppContext::getAppSettings()->getNetworkConfiguration(); assert( NULL != nc ); bool proxyUsed = nc->isProxyUsed( QNetworkProxy::HttpProxy ); bool srvIsException = nc->getExceptionsList().contains( QUrl( PUBLIC_MACHINES_KEEPER_SERVER ).host() ); if( proxyUsed && !srvIsException ) { http.setProxy( nc->getProxy( QNetworkProxy::HttpProxy ) ); } processEncodedMachines( http.syncGet( PUBLIC_MACHINES_KEEPER_PAGE ) ); if (hasError()) { rsLog.error(tr("Failed to retrieve public machines, error: %1").arg(getError())); } else { rsLog.info(tr("Found %1 public machines").arg(publicMachines.size())); } } void RetrievePublicMachinesTask::processEncodedMachines( const QString & encodedMachinesStr ) { QStringList encodedMachines = encodedMachinesStr.split( PUBLIC_MACHINES_STR_SEPARATOR, QString::SkipEmptyParts ); foreach( const QString & encodedMachine, encodedMachines ) { RemoteMachineSettings * settings = NULL; if (!SerializeUtils::deserializeRemoteMachineSettings( encodedMachine.trimmed(), &settings )) { assert( NULL == settings ); setError( tr( "Illegal server response" ) ); break; } publicMachines << settings; } } QList< RemoteMachineSettings* > RetrievePublicMachinesTask::getPublicMachines() const { return publicMachines; } QList< RemoteMachineSettings* > RetrievePublicMachinesTask::takePublicMachines() { QList< RemoteMachineSettings* > res = publicMachines; publicMachines.clear(); return res; } /******************************************* * SaveRemoteMachineSettings *******************************************/ SaveRemoteMachineSettings::SaveRemoteMachineSettings(RemoteMachineSettings * machineSettings, const QString& file) : Task(tr("Save remote machine settings task"), TaskFlag_None), filename(file) { if(filename.isEmpty()) { setError(tr("Output file not set")); return; } if( machineSettings == NULL ) { setError(tr("Nothing to write: empty remote machine settings")); return; } data = SerializeUtils::serializeRemoteMachineSettings(machineSettings).toAscii(); } void SaveRemoteMachineSettings::run() { if(hasError() || isCanceled()) { return; } QFile out(filename); if( !out.open(QIODevice::WriteOnly) ) { setError(tr("Cannot open %1 file").arg(filename)); return; } out.write(data); out.close(); } } // U2 ugene-1.9.8/src/corelibs/U2Remote/src/RemoteMachineMonitor.h0000644000175000017500000000556111651544333022411 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_REMOTE_MACHINE_MONITOR_H_ #define _U2_REMOTE_MACHINE_MONITOR_H_ #include #include #include #include "RemoteMachine.h" namespace U2 { struct RemoteMachineMonitorItem { RemoteMachineSettings * machine; bool selected; RemoteMachineMonitorItem( RemoteMachineSettings * s, bool se ) : machine( s ), selected( se ) { assert( NULL != machine ); } RemoteMachineMonitorItem() : machine( NULL ), selected( false ) { } }; // RemoteMachineMonitorItem /* * Stores info about all remote machines registered in system * Can be accessed by AppContext::getRemoteMachineMonitor() */ class U2REMOTE_EXPORT RemoteMachineMonitor { public: static const QString REMOTE_MACHINE_MONITOR_SETTINGS_TAG; public: RemoteMachineMonitor(); ~RemoteMachineMonitor(); /* RemoteMachineMonitor takes ownership of this machine */ bool addMachine( RemoteMachineSettings * machine, bool selected ); void removeMachine( RemoteMachineSettings * machine ); void setSelected( RemoteMachineSettings * machine, bool selected ); RemoteMachineSettings* findMachine(const QString& serializedSettings) const; QList< RemoteMachineSettings * > getMachinesList(); /* function not const because we can call initialize() here */ QList< RemoteMachineMonitorItem > getRemoteMachineMonitorItems(); QList< RemoteMachineSettings* > getSelectedMachines(); void saveSettings(); private: RemoteMachineMonitor( const RemoteMachineMonitor & ); RemoteMachineMonitor & operator=( const RemoteMachineMonitor & ); QVariant serializeMachines() const; bool deserializeMachines( const QVariant & data ); void ensureInitialized(); void initialize(); bool hasMachineInMonitor( RemoteMachineSettings * machine ) const; private: QList< RemoteMachineMonitorItem > items; bool initialized; }; // RemoteMachineMonitor } // U2 #endif // _U2_REMOTE_MACHINE_MONITOR_H_ ugene-1.9.8/src/corelibs/U2Remote/src/TaskDistributor.h0000644000175000017500000000544611651544334021461 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_TASK_DISTRIBUTOR_H_ #define _U2_TASK_DISTRIBUTOR_H_ #include #include "LocalTask.h" namespace U2 { /* * Base class. Each algorithm needs its own distributor */ class U2REMOTE_EXPORT TaskDistributor { public: virtual ~TaskDistributor(){} /*scatters task settings to some number of parts returns new allocated settings */ virtual QList scatter( const LocalTaskSettings * settings)const = 0; /* returns new allocated results */ virtual LocalTaskResult * gather(const QList &results)const = 0; }; // TaskDistributor /* * Template to TaskDistributor. Makes it easier to write own TaskDistributor implementation. */ template class U2REMOTE_EXPORT TaskDistributorTemplate : public TaskDistributor { public: virtual QList scatter( LocalTaskSettings * settings)const { SettingsT *castedSettings = dynamic_cast(settings); if(NULL == castedSettings) { return QList(); } QList settingsList; foreach(SettingsT *settings, scatter(castedSettings)) { settingsList.append(settings); } return settingsList; } virtual LocalTaskResult *gather(const QList &results)const { QList castedResults; foreach(LocalTaskResult *result, results) { ResultT *castedResult = dynamic_cast(result); if(NULL == castedResult) { return NULL; } castedResults.append(castedResult); } return gather(castedResults); } virtual QList scatter(const SettingsT *settings)const = 0; virtual ResultT *gather(const QList &results)const = 0; }; // TaskDistributorTemplate } // U2 #endif // _U2_TASK_DISTRIBUTOR_H_ ugene-1.9.8/src/corelibs/U2Remote/src/SerializeUtils.cpp0000644000175000017500000000750211651544334021622 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include #include #include #include #include "RemoteMachine.h" #include "SerializeUtils.h" #include namespace U2 { // remote machine settings #define HEADER_COMMENT "# UGENE remote machine settings" QString SerializeUtils::serializeRemoteMachineSettings( RemoteMachineSettings * machine ) { assert( NULL != machine ); return HEADER_COMMENT "\n" + machine->serialize(); } bool SerializeUtils::deserializeRemoteMachineSettingsFromFile( const QString & machinePath, RemoteMachine ** machine ) { QFile file( machinePath ); if( !file.open( QIODevice::ReadOnly ) ) { return NULL; } QString data; while (!file.atEnd()) { QString line = file.readLine(); if (!line.startsWith("#")) { data.append(line); } } if( !deserializeRemoteMachineSettings( data, machine ) || NULL == machine ) { return false; } return true; } bool SerializeUtils::deserializeRemoteMachineSettingsFromFile( const QString & machinePath, RemoteMachineSettings ** settings ) { QFile file( machinePath ); if( !file.open( QIODevice::ReadOnly ) ) { return NULL; } QString data; while (!file.atEnd()) { QString line = file.readLine(); if (!line.startsWith("#")) { data.append(line); } } if( !deserializeRemoteMachineSettings( data, settings ) || NULL == settings ) { return false; } return true; } static QString getDefaultProtocolId( ) { QString res; QList< ProtocolInfo* > infos = AppContext::getProtocolInfoRegistry()->getProtocolInfos(); if (infos.count() > 0) { res = infos.first()->getId(); } return res; } bool SerializeUtils::deserializeRemoteMachineSettings( const QString & data, RemoteMachineSettings ** ret, QString * retProtoId ) { if( NULL == ret ) { return false; } *ret = NULL; QString protoId = getDefaultProtocolId(); ProtocolInfo * protoInfo = AppContext::getProtocolInfoRegistry()->getProtocolInfo( protoId ); if( NULL == protoInfo ) { return false; } *ret = protoInfo->getRemoteMachineFactory()->createSettings( data ); if( NULL != retProtoId ) { *retProtoId = protoId; } return NULL == *ret ? false : true; } bool SerializeUtils::deserializeRemoteMachineSettings( const QString & data, RemoteMachine ** machine ) { if( NULL == machine ) { return false; } *machine = NULL; RemoteMachineSettings * settings = NULL; QString protoId; if( !deserializeRemoteMachineSettings( data, &settings, &protoId ) ) { assert( NULL == settings ); return false; } assert( NULL != settings ); *machine = AppContext::getProtocolInfoRegistry()->getProtocolInfo( protoId )->getRemoteMachineFactory()->createInstance( settings ); delete settings; return NULL == *machine ? false : true; } } // U2 ugene-1.9.8/src/corelibs/U2Remote/src/RemoteMachineSettingsDialog.h0000644000175000017500000000340411651544334023675 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_REMOTE_MACHINE_SETTINGS_DIALOG_H_ #define _U2_REMOTE_MACHINE_SETTINGS_DIALOG_H_ #include #include #include #include namespace U2 { class RemoteMachineSettingsDialog : public QDialog, public Ui::RemoteMachineSettingsDialog { Q_OBJECT public: RemoteMachineSettingsDialog(QWidget* parent, RemoteMachineSettings* settings = NULL); ~RemoteMachineSettingsDialog(); RemoteMachineSettings * getMachineSettings() const; private slots: void sl_okPushButtonClicked(); private: void showErrorLabel(const QString& error); void createMachineSettings(); RemoteMachineSettings * machineSettings; QString protoId; ProtocolUI * currentUi; }; // RemoteMachineSettingsDialog } // U2 #endif // _U2_REMOTE_MACHINE_SETTINGS_DIALOG_H_ ugene-1.9.8/src/corelibs/U2Remote/src/RemoteMachineTasks.h0000644000175000017500000000621311651544334022043 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_DISTRIBUTED_COMPUTING_UTIL_H #define _U2_DISTRIBUTED_COMPUTING_UTIL_H #include #include "RemoteMachine.h" namespace U2 { class PingTask; /* RemoteMachine functions are blocking, so this task can be useful, * because it waits for remote machine responses in separate thread */ class RetrieveRemoteMachineInfoTask : public Task { Q_OBJECT public: RetrieveRemoteMachineInfoTask( RemoteMachineSettings* s); ~RetrieveRemoteMachineInfoTask(); virtual void prepare(); virtual void run(); virtual ReportResult report(); QStringList getServicesList() const; //QUuid getUuid() const; QString getHostName() const; bool isPingOk() const; RemoteMachineSettings* getMachineSettings() const {return settings;} private: QStringList services; QString hostname; PingTask* pingTask; bool pingOK; RemoteMachine * machine; RemoteMachineSettings* settings; }; // RetrieveRemoteMachineInfoTask /* Retrieves public RemoteMachines settings from hard-coded ugene websites */ class RetrievePublicMachinesTask : public Task { Q_OBJECT public: static const QString PUBLIC_MACHINES_KEEPER_SERVER; static const QString PUBLIC_MACHINES_KEEPER_PAGE; static const QString PUBLIC_MACHINES_STR_SEPARATOR; public: RetrievePublicMachinesTask(); ~RetrievePublicMachinesTask(); virtual void run(); QList< RemoteMachineSettings* > getPublicMachines() const; QList< RemoteMachineSettings* > takePublicMachines(); private: void processEncodedMachines( const QString & encodedMachines ); private: QList< RemoteMachineSettings* > publicMachines; }; // RetrievePublicMachinesTask /* Save remote machine settings to file */ class SaveRemoteMachineSettings : public Task { Q_OBJECT public: SaveRemoteMachineSettings(RemoteMachineSettings * machineSettings, const QString& filename); virtual void run(); private: QByteArray data; QString filename; }; // SaveRemoteMachineSettings } // U2 #endif // _U2_DISTRIBUTED_COMPUTING_UTIL_H ugene-1.9.8/src/corelibs/U2Remote/src/RemoteMachineMonitorDialogImpl.cpp0000644000175000017500000004262311651544334024707 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "RemoteMachineScanDialogImpl.h" #include "RemoteMachineSettingsDialog.h" #include "RemoteMachineMonitorDialogImpl.h" #include #include #include #include #include #include #include #include #include #include #include #include #include namespace U2 { const QString RemoteMachineMonitorDialogImpl::OK_BUTTON_RUN = RemoteMachineMonitorDialogImpl::tr( "Run" ); const QString RemoteMachineMonitorDialogImpl::SAVE_SETTINGS_FILE_DOMAIN = "rservice"; static LogFilter prepareLogFilter() { LogFilter res; res.filters.append(LogFilterItem(ULOG_CAT_REMOTE_SERVICE, LogLevel_DETAILS)); return res; } RemoteMachineMonitorDialogImpl::RemoteMachineMonitorDialogImpl( QWidget * p, RemoteMachineMonitor* monitor, bool runTaskMode ) : QDialog( p ), PING_YES( ":core/images/remote_machine_ping_yes.png" ), PING_NO( ":core/images/remote_machine_ping_no.png" ), PING_WAIT_FOR_RESPONSE( ":core/images/remote_machine_ping_waiting_response.png" ), PING_QUESTION(":core/images/question.png"), rmm(monitor), getPublicMachinesTask( NULL ) { setupUi( this ); // add log-view widget QVBoxLayout* logLayout = new QVBoxLayout(); logViewHolder->setLayout(logLayout); LogViewWidget* logView = new LogViewWidget(prepareLogFilter()); logView->setSearchBoxMode(LogViewSearchBox_Hidden); logLayout->addWidget(logView); currentlySelectedItemIndex = -1; assert(rmm != NULL); QList< RemoteMachineMonitorItem > monitorItems = rmm->getRemoteMachineMonitorItems(); int sz = monitorItems.size(); for( int i = 0; i < sz; ++i ) { RemoteMachineMonitorItem item = monitorItems.at( i ); addMachine( item.machine, false ); } rsLog.details(tr("Found %1 remote machine records").arg(sz)); connect( okPushButton, SIGNAL( clicked() ), SLOT( sl_okPushButtonClicked() ) ); connect( cancelPushButton, SIGNAL( clicked() ), SLOT( sl_cancelPushButtonClicked() ) ); connect( addPushButton, SIGNAL( clicked() ), SLOT( sl_addPushButtonClicked() ) ); connect( removePushButton, SIGNAL( clicked() ), SLOT( sl_removePushButtonClicked() ) ); connect( modifyPushButton, SIGNAL( clicked() ), SLOT( sl_modifyPushButtonClicked() ) ); connect( showTasksButton, SIGNAL(clicked()), SLOT(sl_showUserTasksButtonClicked()) ); connect( machinesTreeWidget, SIGNAL( itemSelectionChanged() ), SLOT( sl_selectionChanged() ) ); connect( pingPushButton, SIGNAL( clicked() ), SLOT( sl_pingPushButtonClicked() ) ); connect( getPublicMachinesButton, SIGNAL( clicked() ), SLOT( sl_getPublicMachinesButtonClicked() ) ); okPushButton->setDefault( true ); QHeaderView * header = machinesTreeWidget->header(); header->setClickable( false ); header->setStretchLastSection( false ); header->setResizeMode( 1, QHeaderView::Stretch ); if( runTaskMode ) { okPushButton->setText( OK_BUTTON_RUN ); } initMachineActionsMenu(); updateState(); } void RemoteMachineMonitorDialogImpl::initMachineActionsMenu() { machinesTreeWidget->setContextMenuPolicy(Qt::CustomContextMenu); connect(machinesTreeWidget, SIGNAL(customContextMenuRequested(const QPoint &)), SLOT(sl_machinesTreeMenuRequested(const QPoint&))); machineActionsMenu = new QMenu(this); QAction * removeMachineAction = machineActionsMenu->addAction(removePushButton->text()); connect(removeMachineAction, SIGNAL(triggered()), SLOT(sl_removePushButtonClicked())); QAction * modifyMachineAction = machineActionsMenu->addAction(modifyPushButton->text()); connect(modifyMachineAction, SIGNAL(triggered()), SLOT(sl_modifyPushButtonClicked())); QAction * pingMachineAction = machineActionsMenu->addAction(pingPushButton->text()); connect(pingMachineAction, SIGNAL(triggered()), SLOT(sl_pingPushButtonClicked())); QAction * saveMachineAction = machineActionsMenu->addAction(tr("Save machine..."));; connect(saveMachineAction, SIGNAL(triggered()), SLOT(sl_saveMachine())); } bool RemoteMachineMonitorDialogImpl::addMachine( RemoteMachineSettings * settings, bool ping ) { assert( NULL != settings ); if( hasSameMachineInTheView( settings ) ) { rsLog.error(tr( "Can't add %1 machine. The machine is already registered" ).arg( settings->getName() ) ); return false; } RemoteMachineItemInfo item( settings); machinesItemsByOrder << item; QTreeWidgetItem * widgetItem = addItemToTheView( item ); assert( NULL != widgetItem ); if (ping) { pingMachine( settings, widgetItem ); } else { widgetItem->setIcon(2, PING_QUESTION); widgetItem->setIcon(3, PING_QUESTION); } rmm->addMachine(settings, false); return true; } QTreeWidgetItem * RemoteMachineMonitorDialogImpl::addItemToTheView( RemoteMachineItemInfo & itemInfo ) { assert( NULL != itemInfo.settings ); QStringList strings; QTreeWidgetItem * widgetItem = new QTreeWidgetItem( machinesTreeWidget ); widgetItem->setText(0, itemInfo.settings->getName()); widgetItem->setText(1, itemInfo.settings->getProtocolId()); widgetItem->setTextAlignment(2, Qt::AlignCenter); machinesTreeWidget->addTopLevelItem( widgetItem ); resizeTreeWidget(); return widgetItem; } bool RemoteMachineMonitorDialogImpl::hasSameMachineInTheView( RemoteMachineSettings * suspect ) const { int sz = machinesItemsByOrder.size(); int i = 0; for( ; i < sz; ++i ) { RemoteMachineItemInfo item = machinesItemsByOrder.at( i ); if( *item.settings == *suspect ) { return true; } } return false; } QList< RemoteMachineItemInfo > RemoteMachineMonitorDialogImpl::getModel() const { return machinesItemsByOrder; } void RemoteMachineMonitorDialogImpl::sl_okPushButtonClicked() { if (okPushButton->text() == OK_BUTTON_RUN) { RemoteMachineSettings* s = getSelectedMachine(); checkCredentials(s); } accept(); } void RemoteMachineMonitorDialogImpl::sl_cancelPushButtonClicked() { reject(); } void RemoteMachineMonitorDialogImpl::sl_addPushButtonClicked() { RemoteMachineSettingsDialog settingsDlg(this); QList< ProtocolInfo* > protoInfos = AppContext::getProtocolInfoRegistry()->getProtocolInfos(); if (protoInfos.size() < 1) { QMessageBox::information(this, tr("Add remote macnine"), tr("No protocols for distributed computing are found.\nPlease check your plugin list.")); return; } int rc = settingsDlg.exec(); if( QDialog::Rejected == rc ) { return; } assert( QDialog::Accepted == rc ); RemoteMachineSettings * newMachine = settingsDlg.getMachineSettings(); if( NULL == newMachine ) { return; } if( !addMachine( newMachine, true ) ) { delete newMachine; } } void RemoteMachineMonitorDialogImpl::sl_modifyPushButtonClicked() { assert( 1 == topLevelItemsSelectedNum() ); int row = getSelectedTopLevelRow(); assert( 0 <= row && row < machinesItemsByOrder.size() ); RemoteMachineSettingsDialog settingsDlg( this, machinesItemsByOrder.at( row ).settings ); int rc = settingsDlg.exec(); if( QDialog::Rejected == rc ) { return; } RemoteMachineSettings * newMachine = settingsDlg.getMachineSettings(); if( NULL == newMachine ) { return; } removeDialogItemAt( row ); addMachine( newMachine, true ); } void RemoteMachineMonitorDialogImpl::sl_removePushButtonClicked() { assert( 1 == topLevelItemsSelectedNum() ); bool ok = removeDialogItemAt( getSelectedTopLevelRow() ); if( !ok ) { QString msg = tr( "Cannot delete machine that is waiting for response" ); rsLog.error(msg); QMessageBox::critical( this, tr( "Error!" ), msg ); return; } } bool RemoteMachineMonitorDialogImpl::removeDialogItemAt( int row ) { assert( 0 <= row && row < machinesItemsByOrder.size() ); RemoteMachineItemInfo & itemToRemove = machinesItemsByOrder[row]; std::auto_ptr treeItemToRemove ( machinesTreeWidget->takeTopLevelItem( row ) ); rmm->removeMachine(itemToRemove.settings); machinesItemsByOrder.removeAt( row ); return true; } void RemoteMachineMonitorDialogImpl::sl_selectionChanged() { if (machinesTreeWidget->currentItem() != NULL ) { currentlySelectedItemIndex = getSelectedTopLevelRow(); } else { currentlySelectedItemIndex = -1; } updateState(); } int RemoteMachineMonitorDialogImpl::topLevelItemsSelectedNum() const { return machinesTreeWidget->selectedItems().size(); } int RemoteMachineMonitorDialogImpl::getSelectedTopLevelRow() const { assert( 1 == topLevelItemsSelectedNum() ); QList< QTreeWidgetItem* > selection = machinesTreeWidget->selectedItems(); assert( !selection.isEmpty() ); return machinesTreeWidget->indexOfTopLevelItem( selection.first() ); } void RemoteMachineMonitorDialogImpl::enableItem( QTreeWidgetItem * item, bool enable ) { assert( NULL != item ); GUIUtils::setMutedLnF(item, !enable, true); } void RemoteMachineMonitorDialogImpl::sl_retrieveInfoTaskStateChanged() { RetrieveRemoteMachineInfoTask * retrieveInfoTask = qobject_cast< RetrieveRemoteMachineInfoTask* >( sender() ); assert( NULL != retrieveInfoTask ); if( Task::State_Finished != retrieveInfoTask->getState() ) { return; } RemoteMachineSettings* machineSettings = retrieveInfoTask->getMachineSettings(); assert( NULL != machineSettings ); QTreeWidgetItem * treeItem = pingingItems.value( machineSettings ); pingingItems.remove( machineSettings ); int row = machinesTreeWidget->indexOfTopLevelItem( treeItem ); if( -1 == row ) { return; /* item was deleted from the table */ } RemoteMachineItemInfo & itemInfo = machinesItemsByOrder[row]; bool pingOk = retrieveInfoTask->isPingOk(); bool authOk = !retrieveInfoTask->hasError(); treeItem->setIcon( 2, pingOk ? PING_YES : PING_NO); treeItem->setIcon( 3, authOk ? PING_YES : PING_NO); if ( !authOk ) { rsLog.error( tr( "Test connection for machine %1 finished with error: '%2'" ). arg( itemInfo.settings->getName() ).arg( retrieveInfoTask->getError() ) ); } itemInfo.hostname = retrieveInfoTask->getHostName(); treeItem->setText(1, itemInfo.hostname ); resizeTreeWidget(); enableItem(treeItem, authOk); updateState(); } void RemoteMachineMonitorDialogImpl::sl_pingPushButtonClicked() { assert( 1 == topLevelItemsSelectedNum() ); int row = getSelectedTopLevelRow(); pingMachine( machinesItemsByOrder.at( row ).settings, machinesTreeWidget->topLevelItem( row ) ); updateState(); } void RemoteMachineMonitorDialogImpl::pingMachine( RemoteMachineSettings * settings, QTreeWidgetItem * item ) { assert( NULL != settings && NULL != item ); if (!checkCredentials(settings)) { return; } if( pingingItems.values().contains( item ) ) { rsLog.info(tr("Ping task is already active for machine: %1" ).arg(item->text(0))); return; } pingingItems.insert( settings, item ); item->setIcon(2, PING_WAIT_FOR_RESPONSE); item->setIcon(3, PING_WAIT_FOR_RESPONSE); RetrieveRemoteMachineInfoTask * retrieveInfoTask = new RetrieveRemoteMachineInfoTask( settings ); connect( retrieveInfoTask, SIGNAL( si_stateChanged() ), SLOT( sl_retrieveInfoTaskStateChanged() ) ); AppContext::getTaskScheduler()->registerTopLevelTask( retrieveInfoTask ); } void RemoteMachineMonitorDialogImpl::resizeTreeWidget() { QHeaderView * header = machinesTreeWidget->header(); header->resizeSections( QHeaderView::ResizeToContents ); } void RemoteMachineMonitorDialogImpl::sl_getPublicMachinesButtonClicked() { if( NULL != getPublicMachinesTask ) { rsLog.details(tr("Public machines request is already sent" ) ); return; } getPublicMachinesTask = new RetrievePublicMachinesTask(); connect( getPublicMachinesTask, SIGNAL( si_stateChanged() ), SLOT( sl_getPublicMachinesTaskStateChanged() ) ); AppContext::getTaskScheduler()->registerTopLevelTask( getPublicMachinesTask ); getPublicMachinesButton->setEnabled(false); } void RemoteMachineMonitorDialogImpl::sl_getPublicMachinesTaskStateChanged() { assert( NULL != getPublicMachinesTask && getPublicMachinesTask == sender() ); if( Task::State_Finished != getPublicMachinesTask->getState() ) { return; } QList< RemoteMachineSettings* > newMachines = getPublicMachinesTask->takePublicMachines(); if( getPublicMachinesTask->hasError()) { QMessageBox::critical(this, tr("Info"), tr("Error during remote machines request: %1").arg(getPublicMachinesTask->getError())); } else if ( newMachines.isEmpty() ) { QMessageBox::information(this, tr("Info"), tr("No public machines found")); } else { foreach( RemoteMachineSettings * machine, newMachines ) { if( !addMachine( machine, false ) ) { delete machine; /* it already exists in the monitor list */ } } } getPublicMachinesTask = NULL; getPublicMachinesButton->setEnabled(true); } void RemoteMachineMonitorDialogImpl::sl_machinesTreeMenuRequested(const QPoint& p) { QTreeWidgetItem * item = machinesTreeWidget->itemAt(p); if( item == NULL || item->parent() != NULL ) { return; } machineActionsMenu->exec(QCursor::pos()); } void RemoteMachineMonitorDialogImpl::sl_saveMachine() { assert(topLevelItemsSelectedNum() == 1); RemoteMachineItemInfo & item = machinesItemsByOrder[getSelectedTopLevelRow()]; QString filename; LastOpenDirHelper dirHelper(SAVE_SETTINGS_FILE_DOMAIN); dirHelper.url = filename = QFileDialog::getSaveFileName( this, tr("Select a file to save"), dirHelper.dir); AppContext::getTaskScheduler()->registerTopLevelTask(new SaveRemoteMachineSettings(item.settings, filename)); } void RemoteMachineMonitorDialogImpl::updateState() { if (okPushButton->text() == OK_BUTTON_RUN) { okPushButton->setEnabled(topLevelItemsSelectedNum() > 0); } bool itemSelected = machinesTreeWidget->selectedItems().size() > 0; bool pinging = false; foreach(QTreeWidgetItem* item, pingingItems.values()) { if (item->isSelected()) { pinging = true; break; } } bool available = !pinging && itemSelected; pingPushButton->setEnabled(available); removePushButton->setEnabled(available ); modifyPushButton->setEnabled(available ); showTasksButton->setEnabled(available); foreach (QAction* action, machineActionsMenu->actions()) { action->setEnabled(available); } } RemoteMachineSettings* RemoteMachineMonitorDialogImpl::getSelectedMachine() const { if ( currentlySelectedItemIndex < 0 || currentlySelectedItemIndex >= machinesItemsByOrder.size() ) { return NULL; } const RemoteMachineItemInfo& info = machinesItemsByOrder.at(currentlySelectedItemIndex); return info.settings; } void RemoteMachineMonitorDialogImpl::sl_showUserTasksButtonClicked() { ProtocolInfoRegistry * pir = AppContext::getProtocolInfoRegistry(); assert( NULL != pir ); QList< ProtocolInfo* > protoInfos = pir->getProtocolInfos(); assert(protoInfos.size() > 0); ProtocolInfo* pi = protoInfos.first(); int row = getSelectedTopLevelRow(); RemoteMachineSettings* settings = machinesItemsByOrder.at(row).settings; if (!checkCredentials(settings)) { return; } if (settings->usesGuestAccount()) { QMessageBox::warning(this, tr("User Tasks"), tr("
    Unable to show user task statistics for guest account. \
    Please register on ugene-service.com")); return; } std::auto_ptr dlg(pi->getProtocolUI()->createUserTasksDialog(settings, this)); dlg->exec(); } bool RemoteMachineMonitorDialogImpl::checkCredentials( RemoteMachineSettings* settings ) { UserCredentials* credentials = settings->getUserCredentials(); if (credentials == NULL) { AuthDialog dlg(this); int rc = dlg.exec(); if ( QDialog::Rejected == rc ) { return false; } settings->setupCredentials(dlg.getUserName(), dlg.getPasswd(), dlg.rememberAuthData()); } return true; } } // U2 ugene-1.9.8/src/corelibs/U2Remote/src/RemoteMachineMonitorDialogController.cpp0000644000175000017500000000336211651544333026125 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "RemoteMachineMonitorDialogController.h" #include "RemoteMachineMonitorDialogImpl.h" #include /* TRANSLATOR U2::RemoteMachineMonitorDialogImpl */ namespace U2 { RemoteMachineSettings* RemoteMachineMonitorDialogController::selectRemoteMachine( RemoteMachineMonitor* monitor, bool runTaskMode /*= false */ ) { RemoteMachineMonitorDialogImpl dlg( QApplication::activeWindow(), monitor, runTaskMode); int ret = dlg.exec(); if(ret == QDialog::Rejected) { return NULL; } assert(ret == QDialog::Accepted); RemoteMachineSettings *rms = dlg.getSelectedMachine(); if (runTaskMode && !rms) { QMessageBox::critical(QApplication::activeWindow(), RemoteMachineMonitorDialogImpl::tr("Selecting machines error!"), RemoteMachineMonitorDialogImpl::tr("You didn't select a machine to run remote task!")); } return rms; } }//nsugene-1.9.8/src/corelibs/U2Remote/src/Serializable.h0000644000175000017500000000274611651544334020732 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_SERIALIZABLE_H_ #define _U2_SERIALIZABLE_H_ #include namespace U2 { class U2REMOTE_EXPORT Serializable { public: virtual ~Serializable(); virtual QVariant serialize()const = 0; virtual bool deserialize( const QVariant & data ) = 0; }; // Serializable /* * this interface is same as Serializable, but it must provide human-readable serialization */ class U2REMOTE_EXPORT HumanSerializable { public: virtual ~HumanSerializable(); virtual QString serialize() const = 0; virtual bool deserialize( const QString & data ) = 0; }; // HumanSerializable } // U2 #endif // _U2_SERIALIZABLE_H_ ugene-1.9.8/src/corelibs/U2Remote/src/RemoteMachineScanner.cpp0000644000175000017500000000232711651544334022704 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "RemoteMachineScanner.h" namespace U2 { RemoteMachineScanner::RemoteMachineScanner( bool filter ) : filterLocalHost( filter ) { } RemoteMachineScanner::~RemoteMachineScanner() { } void RemoteMachineScanner::setFilterLocalHost( bool filter ) { filterLocalHost = filter; } bool RemoteMachineScanner::getFilterLocalHost() const { return filterLocalHost; } } // U2 ugene-1.9.8/src/corelibs/U2Remote/src/DistributedComputingUtil.cpp0000644000175000017500000001116411651544333023656 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "DistributedComputingUtil.h" #include #include #include #include #include #include #include #include #include #include #include #include #include "RemoteMachineMonitorDialogImpl.h" #include #include #include #include namespace U2 { /******************************************* * DistributedComputingUtil *******************************************/ DistributedComputingUtil::DistributedComputingUtil() { AppContextImpl * appContext = AppContextImpl::getApplicationContext(); assert( NULL != appContext ); pir = new ProtocolInfoRegistry(); appContext->setProtocolInfoRegistry( pir ); rmm = new RemoteMachineMonitor(); appContext->setRemoteMachineMonitor( rmm ); if( NULL != AppContext::getMainWindow() ) { /* if not congene */ QAction * showRemoteMachinesMonitor = new QAction( QIcon( ":core/images/remote_machine_monitor.png" ), tr( "Remote machines monitor..." ), this ); connect( showRemoteMachinesMonitor, SIGNAL( triggered() ), SLOT( sl_showRemoteMachinesMonitor() ) ); AppContext::getMainWindow()->getTopLevelMenu( MWMENU_SETTINGS )->addAction( showRemoteMachinesMonitor ); } } DistributedComputingUtil::~DistributedComputingUtil() { delete rmm; delete pir; } void DistributedComputingUtil::sl_showRemoteMachinesMonitor() { RemoteMachineMonitorDialogImpl dlg( QApplication::activeWindow(), rmm ); int ret = dlg.exec(); if( QDialog::Rejected == ret ) { return; } assert( QDialog::Accepted == ret ); } QStringList DistributedComputingUtil::filterRemoteMachineServices( const QStringList & services ) { QStringList res = services; return res; } /******************************************* * UpdateActiveTasks *******************************************/ UpdateActiveTasks::UpdateActiveTasks(RemoteMachineSettings* s) : Task("UpdateActiveTasks", TaskFlags_FOSCOE), settings(s), machine(NULL) { rsLog.details(tr("Updating active tasks...")); ProtocolInfo* pi = AppContext::getProtocolInfoRegistry()->getProtocolInfo( settings->getProtocolId() ); machine = pi->getRemoteMachineFactory()->createInstance( settings ); if( NULL == machine ) { setError( tr( "Cannot create remote machine from remote machine settings: %1" ).arg( settings->getName() ) ); } } UpdateActiveTasks::~UpdateActiveTasks() { delete machine; machine = NULL; } void UpdateActiveTasks::run() { if (hasError() || isCanceled()) { return; } QList taskIds; taskIds = machine->getActiveTasks(stateInfo); if (hasError()) { return; } foreach(qint64 taskId, taskIds) { rsLog.details(tr("Found active task: %1").arg(taskId)); addTaskToScheduler(taskId); } rsLog.details(tr("Active tasks update finished!")); } void UpdateActiveTasks::addTaskToScheduler( qint64 taskid ) { TaskScheduler* scheduler = AppContext::getTaskScheduler(); QList activeIds; QList topLevelTasks = scheduler->getTopLevelTasks(); foreach(Task* task, topLevelTasks) { RemoteWorkflowRunTask* workflowTask = qobject_cast (task); if (workflowTask == NULL) { continue; } activeIds.append(workflowTask->getRemoteTaskId()); } if (!activeIds.contains(taskid)) { Task* newTask = new RemoteWorkflowRunTask(settings, taskid); scheduler->registerTopLevelTask(newTask); } } } // U2 ugene-1.9.8/src/corelibs/U2Remote/src/ProtocolInfo.cpp0000644000175000017500000000476311651544333021274 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "ProtocolInfo.h" namespace U2 { /*********************************************** * ProtocolInfo ***********************************************/ ProtocolInfo::ProtocolInfo( const QString &id, ProtocolUI *protocolUI, RemoteMachineFactory *remoteMachineFactory ) : server(NULL), protocolUI(protocolUI), remoteMachineFactory(remoteMachineFactory), scanner(NULL), id(id) { } RemoteTaskServer * ProtocolInfo::getRemoteTaskServer() const { return server; } ProtocolUI * ProtocolInfo::getProtocolUI() const { return protocolUI; } RemoteMachineFactory * ProtocolInfo::getRemoteMachineFactory() const { return remoteMachineFactory; } RemoteMachineScanner * ProtocolInfo::getRemoteMachineScanner() const { return scanner; } QString ProtocolInfo::getId() const { return id; } /*********************************************** * ProtocolInfoRegistry ***********************************************/ void ProtocolInfoRegistry::registerProtocolInfo( ProtocolInfo *info ) { protocolInfos.insert( info->getId(), info ); } bool ProtocolInfoRegistry::unregisterProtocolInfo( const QString &id ) { if( !protocolInfos.contains( id ) ) { return false; } protocolInfos.remove( id ); return true; } bool ProtocolInfoRegistry::isProtocolInfoRegistered( const QString &id ) const { return protocolInfos.contains( id ); } ProtocolInfo *ProtocolInfoRegistry::getProtocolInfo( const QString &id ) const { if( !protocolInfos.contains( id ) ) { return NULL; } return protocolInfos.value( id ); } QList< ProtocolInfo *> ProtocolInfoRegistry::getProtocolInfos() const { return protocolInfos.values(); } } // U2 ugene-1.9.8/src/corelibs/U2Remote/src/SynchHttp.cpp0000644000175000017500000000311211651544334020567 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "SynchHttp.h" namespace U2 { SyncHTTP::SyncHTTP(const QString& hostName, quint16 port, QObject* parent) : QHttp(hostName,port,parent), requestID(-1) { connect(this,SIGNAL(requestFinished(int,bool)),SLOT(finished(int,bool))); } QString SyncHTTP::syncGet(const QString& path) { assert(requestID == -1); QBuffer to; requestID = get(path, &to); loop.exec(); return QString(to.data()); } QString SyncHTTP::syncPost(const QString & path, QIODevice * data) { assert(requestID == -1); QBuffer to; requestID = post(path, data, &to); loop.exec(); return QString(to.data()); } void SyncHTTP::finished(int idx, bool err) { assert(idx = requestID);Q_UNUSED(err); Q_UNUSED(idx); loop.exit(); } } // U2 ugene-1.9.8/src/corelibs/U2Remote/src/RemoteMachineScanDialogImpl.cpp0000644000175000017500000001404411651544334024140 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include #include #include #include #include #include #include #include "RemoteMachineScanDialogImpl.h" namespace U2 { RemoteMachineScanDialogImpl::RemoteMachineScanDialogImpl() { setupUi( this ); ProtocolInfoRegistry * pir = AppContext::getProtocolInfoRegistry(); assert( NULL != pir ); QList< ProtocolInfo * > protocolInfos = pir->getProtocolInfos(); foreach( ProtocolInfo * pi, protocolInfos ) { Q_UNUSED(pi); assert( NULL != pi ); // if( NULL != pi->getRemoteMachineScanner() ) { // protocolComboBox->addItem( pi->getId() ); // } } connect( cancelPushButton, SIGNAL( clicked() ), SLOT( sl_cancelPushButtonClicked() ) ); connect( okPushButton, SIGNAL( clicked() ), SLOT( sl_okPushButtonClicked() ) ); if( 0 == protocolComboBox->count() ) { okPushButton->setEnabled( false ); QLabel * errorLable = new QLabel( tr( "No protocols that supports scanning found!" ), this ); QVBoxLayout * topLayout = qobject_cast< QVBoxLayout* >( layout() ); assert( NULL != topLayout ); topLayout->insertWidget( 1, errorLable ); return; } connect( protocolComboBox, SIGNAL( activated( const QString & ) ), SLOT( sl_startScan( const QString & ) ) ); connect( &updateTimer, SIGNAL( timeout() ), SLOT( sl_updatePushButtonClicked() ) ); updateTimer.start( SCAN_UPDATE_TIME ); machinesTableWidget->horizontalHeader()->setHighlightSections( false ); machinesTableWidget->horizontalHeader()->setClickable( false ); machinesTableWidget->verticalHeader()->setClickable( false ); machinesTableWidget->setSelectionMode( QAbstractItemView::NoSelection ); machinesTableWidget->setEditTriggers( QAbstractItemView::NoEditTriggers ); resizeTable(); sl_startScan( protocolComboBox->currentText() ); } RemoteMachineScanDialogImpl::~RemoteMachineScanDialogImpl() { } void RemoteMachineScanDialogImpl::cleanup() { qDeleteAll( model ); model.clear(); } void RemoteMachineScanDialogImpl::sl_cancelPushButtonClicked() { cleanup(); reject(); } void RemoteMachineScanDialogImpl::sl_okPushButtonClicked() { int sz = machinesTableWidget->rowCount(); QList< int > delIndexes; for( int i = 0; i < sz; ++i ) { QCheckBox * checkBox = qobject_cast( machinesTableWidget->cellWidget( i, 0 ) ); assert( NULL != checkBox ); if( !checkBox->isChecked() ) { delIndexes << i; } } qSort( delIndexes.begin(), delIndexes.end(), qGreater() ); sz = delIndexes.size(); for( int i = 0; i < sz; ++i ) { delete model.takeAt( delIndexes.at( i ) ); } accept(); } void RemoteMachineScanDialogImpl::sl_startScan( const QString & /*protoId*/ ) { // RemoteMachineScanner * scanner = AppContext::getProtocolInfoRegistry()->getProtocolInfo( protoId )->getRemoteMachineScanner(); // assert( NULL != scanner ); // scanner->startScan(); // if( !runningScanners.contains( scanner ) ) { // runningScanners << scanner; // } } void RemoteMachineScanDialogImpl::addMachines( const QList< RemoteMachineSettings* > newMachines ) { foreach( RemoteMachineSettings * machine, newMachines ) { addMachine( machine ); } } void RemoteMachineScanDialogImpl::addMachine( RemoteMachineSettings * machine ) { assert( NULL != machine ); if( hasSameMachineInTheList( machine ) ) { delete machine; } else { model.append( machine ); addNextMachineToTable( machine ); } resizeTable(); } void RemoteMachineScanDialogImpl::addNextMachineToTable( RemoteMachineSettings * settings ) { assert( NULL != settings ); int sz = machinesTableWidget->rowCount(); machinesTableWidget->insertRow( sz ); QCheckBox * checkBox = new QCheckBox(); checkBox->setCheckState( Qt::Checked ); machinesTableWidget->setCellWidget( sz, 0, checkBox ); machinesTableWidget->setItem( sz, 1, new QTableWidgetItem( settings->getName() ) ); machinesTableWidget->setItem( sz, 2, new QTableWidgetItem( settings->getProtocolId() ) ); machinesTableWidget->resizeColumnToContents( 2 ); } void RemoteMachineScanDialogImpl::sl_updatePushButtonClicked() { foreach( RemoteMachineScanner * scanner, runningScanners ) { assert( NULL != scanner ); QList< RemoteMachineSettings* > newScanned = scanner->takeScanned(); addMachines( newScanned ); } } bool RemoteMachineScanDialogImpl::hasSameMachineInTheList( RemoteMachineSettings* suspect ) const { assert( NULL != suspect ); foreach( RemoteMachineSettings * machine, model ) { assert( NULL != machine ); if( *machine == *suspect ) { return true; } } return false; } RemoteMachineScanDialogModel RemoteMachineScanDialogImpl::getModel() const { return model; } void RemoteMachineScanDialogImpl::resizeTable() { machinesTableWidget->horizontalHeader()->setResizeMode( 1, QHeaderView::Stretch ); machinesTableWidget->horizontalHeader()->resizeSections( QHeaderView::ResizeToContents ); } } // U2 ugene-1.9.8/src/corelibs/U2Remote/src/ProtocolUI.cpp0000644000175000017500000000170511651544333020707 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "ProtocolUI.h" namespace U2 { ProtocolUI::ProtocolUI() { } ProtocolUI::~ProtocolUI() { } } // U2 ugene-1.9.8/src/corelibs/U2Remote/transl/0000755000175000017500000000000011651544334016656 5ustar ilyailyaugene-1.9.8/src/corelibs/U2Remote/transl/russian.ts0000644000175000017500000007003611651544334020720 0ustar ilyailya RemoteMachineMonitorDialog Remote machine monitor Диспетчер удаленных машин Host Адрес Protocol Протокол Remote machine list <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> <html><head><meta name="qrichtext" content="1" /><style type="text/css"> p, li { white-space: pre-wrap; } </style></head><body style=" font-family:'MS Shell Dlg 2'; font-size:8.25pt; font-weight:400; font-style:normal;"> <p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-size:8pt;">The list contains information about available UGENE remote service machines: the web-url, server name, ping and authentification status. </span></p> <p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-size:8pt;">The green </span><a name="result_box"></a><span style=" font-size:8pt;">t</span><span style=" font-size:8pt;">ick in the status means succes, red cross - fail. The question sign means that the connection with these service has not been tested yet. </span></p></body></html> Url Server Name Ping Пинг Auth Add new UGENE remote service machine Add... Добавить... Remove UGENE remote service machine from list Remove Удалить Modify settings of existing UGENE remote service machine Modify... Изменить... Test connection with selected remote machine <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> <html><head><meta name="qrichtext" content="1" /><style type="text/css"> p, li { white-space: pre-wrap; } </style></head><body style=" font-family:'MS Shell Dlg 2'; font-size:8.25pt; font-weight:400; font-style:normal;"> <p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-size:8pt;">The connection is tested in two steps.</span></p> <p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-size:8pt;">First a PING command is sent to remote service, then an authentification information is sent (AUTH command) and active session is started. </span></p></body></html> Test Connection Show user remote tasks statistics Activate User Tasks dialog, to check finished and ongoing tasks status, retrieve results or delete remote tasks. Show User Tasks Add available public machines to the list Get Public Machines OK Events log Scan... Сканировать... Get public machines Найти публичные машины Ok Готово Cancel Отмена RemoteMachineScanDialog Scan remote machine Сканировать удаленные машины Add Добавить Host Адрес Protocol Протокол Add selected Добавить выбранные Cancel Отмена RemoteMachineSettingsDialog Remote machine configuration Конфигурация удалённой машины OK Cancel Отмена U2::DistributedComputingUtil Remote machines monitor Диспетчер удаленных машин Remote machines monitor... Диспетчер удаленных машин ... U2::PingTask Ping task Задача пинг PingTask Задача пинг Starting remote service ping task, task-id: %1 Remote service ping task finished, task-id: %1 Ping task with %1 id created Задача пинг с идентификатором %1 создана Ping task with %1 id is finished Задача пинг с идентификатором %1 завершена Ping task with %1 id preparing Задача пинг с идентификатором %1 подготовлена Ping task with %1 id running Задача пинг с идентификатором %1 исполнена Ping task with %1 id reporting Задача пинг с идентификатором %1 завершена Ping task with %1 id destroyed Задача пинг с идентификатором %1 удалена U2::RemoteMachineMonitorDialogImpl Run Found %1 remote machine records Save machine... Сохранить удалённую машину... Can't add %1 machine. The machine is already registered Add remote macnine No protocols for distributed computing are found. Please check your plugin list. Ping task is already active for machine: %1 Public machines request is already sent Error during remote machines request: %1 No public machines found tried to add %1 machine to view. it already exists in the view попытка добавления удаленной машины %1, которая уже добавлена в таблицу Error! Ошибка! Cannot modify machine that is waiting for response Нельзя изменять машину, которая ждет удаленного ответа Cannot delete machine that is waiting for response Нельзя удалять машину, которая ждет удаленного ответа Retrieve info task for machine %1 finished with error: '%2' Задача получения информации о удаленной машине %1 завершилась с ошибкой %2 Test connection for machine %1 finished with error: '%2' tried to ping machine that is pinging now Попытка пинга машины, к которой уже отправлен пинг and и seems to be the same machines. видимо являются одной и той же машиной. request to public machines already sent запрос на получение публичных машин уже послан Retrieve public machines failed with error:%1 Запрос на получение списка публичных машин завершился с ошибкой: %1 Info Select a file to save Выберите файл для сохранения Selecting machines error! You didn't select a machine to run remote task! U2::RemoteMachineScanDialogImpl No protocols that supports scanning found! Не найдено ни одного сетевого протокола, поддерживающего сканирование сети! U2::RemoteMachineSettingsDialog Error! Ошибка! Sorry! Cannot create remote machine U2::RemoteWorkflowRunTask Workflow run task on the cloud Исполнение вычислительной схемы на облаке Bad remote machine settings Некорректные настройки удалённой машины Started remote workflow task Cannot create remote machine from remote machine settings: %1 Не удалось создать удаленную машину на основе следующих настроек:%1 U2::RetrievePublicMachinesTask Bad machine found on server Запрос к удаленным машинам: Не удалось распознать удаленную машину Retrieving public machines... Failed to retrieve public machines, error: %1 Found %1 public machines Illegal server response U2::RetrieveRemoteMachineInfoTask Retrieve remote machine info task Задача получения информации о удаленной машине Bad remote machine given Удаленная машина не задана Retrieve remote machine info task started Задача получения информации об удаленной машине создана Started retrieve machine info task Задача получения информации об удаленной машине создана Cannot create remote machine from remote machine settings: %1 Не удалось создать удаленную машину на основе следующих настроек:%1 Retrieved uuid Получена информация: uuid Retrieved services list Получена информация: список сервисов Failed to get server name Ошибка получения имени сервера Retrieved hostname Получена информация: имя удаленной машины Ping task is canceled by user Задача пинга отменена пользователем Ping task finished with error: Задача пинг завершилась с ошибкой: Task is canceled by user Задача отменена пользователем Retrieving remomote machine info... U2::SaveRemoteMachineSettings Save remote machine settings task Сохранение настроек удалённой машины Output file not set Выходной файл не указан Nothing to write: empty remote machine settings Невозможно записать: пустые настройки удалённой машины Cannot open %1 file Невозможно открыть файл "%1" U2::UpdateActiveTasks Updating active tasks... Found active task: %1 Active tasks update finished! Started updating active tasks... Начато обновление активных задач... Cannot create remote machine from remote machine settings: %1 Не удалось создать удаленную машину на основе следующих настроек:%1 Failed to retrieve active tasks %1 Не удалось получить активные задания "%1" Finished updating active tasks Обновление активных задач завершено ugene-1.9.8/src/corelibs/U2Remote/transl/czech.ts0000644000175000017500000006166011651544334020333 0ustar ilyailya RemoteMachineMonitorDialog Remote machine monitor Sledování vzdáleného stroje Host Host Protocol Protocol Remote machine list <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> <html><head><meta name="qrichtext" content="1" /><style type="text/css"> p, li { white-space: pre-wrap; } </style></head><body style=" font-family:'MS Shell Dlg 2'; font-size:8.25pt; font-weight:400; font-style:normal;"> <p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-size:8pt;">The list contains information about available UGENE remote service machines: the web-url, server name, ping and authentification status. </span></p> <p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-size:8pt;">The green </span><a name="result_box"></a><span style=" font-size:8pt;">t</span><span style=" font-size:8pt;">ick in the status means succes, red cross - fail. The question sign means that the connection with these service has not been tested yet. </span></p></body></html> Url Server Name Ping Zazvonit Auth Add new UGENE remote service machine Add... Přidat... Remove UGENE remote service machine from list Remove Odstranit Modify settings of existing UGENE remote service machine Modify... Upravit... Test connection with selected remote machine <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> <html><head><meta name="qrichtext" content="1" /><style type="text/css"> p, li { white-space: pre-wrap; } </style></head><body style=" font-family:'MS Shell Dlg 2'; font-size:8.25pt; font-weight:400; font-style:normal;"> <p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-size:8pt;">The connection is tested in two steps.</span></p> <p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-size:8pt;">First a PING command is sent to remote service, then an authentification information is sent (AUTH command) and active session is started. </span></p></body></html> Test Connection Show user remote tasks statistics Activate User Tasks dialog, to check finished and ongoing tasks status, retrieve results or delete remote tasks. Show User Tasks Add available public machines to the list Get Public Machines OK Events log Scan... Scan... Get public machines Get public machines Ok Ok Cancel Zrušit RemoteMachineScanDialog Scan remote machine Prohledat vzdálený stroj Add Přidat Host Hostitelský počítač Protocol Protokol Add selected Přidat vybrané Cancel Zrušit RemoteMachineSettingsDialog Remote machine configuration Upravit vzdálený stroj OK Cancel Zrušit U2::DistributedComputingUtil Remote machines monitor Remote machines monitor Remote machines monitor... Sledování vzdálených strojů... U2::PingTask Ping task Ping task Ping task with %1 id created Ping task with %1 id created Ping task with %1 id preparing Ping task with %1 id preparing Ping task with %1 id running Ping task with %1 id running Ping task with %1 id reporting Ping task with %1 id reporting Ping task with %1 id destroyed Ping task with %1 id destroyed PingTask Úkol zazvonění Starting remote service ping task, task-id: %1 Remote service ping task finished, task-id: %1 U2::RemoteMachineMonitorDialogImpl Run Run Found %1 remote machine records Save machine... Uložit stroj... Can't add %1 machine. The machine is already registered Byl učiněn pokus o přidání %1 stroje do pohledu. Již v pohledu je Add remote macnine No protocols for distributed computing are found. Please check your plugin list. Test connection for machine %1 finished with error: '%2' Ping task is already active for machine: %1 Public machines request is already sent Info Error during remote machines request: %1 No public machines found tried to add %1 machine to view. it already exists in the view tried to add %1 machine to view. it already exists in the view Error! Error! Cannot modify machine that is waiting for response Cannot modify machine that is waiting for response Cannot delete machine that is waiting for response Cannot delete machine that is waiting for response Retrieve info task for machine %1 finished with error: '%2' Retrieve info task for machine %1 finished with error: '%2' tried to ping machine that is pinging now tried to ping machine that is pinging now and and seems to be the same machines. seems to be the same machines. request to public machines already sent request to public machines already sent Retrieve public machines failed with error:%1 Retrieve public machines failed with error:%1 Select a file to save Vybrat soubor k uložení Selecting machines error! You didn't select a machine to run remote task! U2::RemoteMachineScanDialogImpl No protocols that supports scanning found! Nebyly nalezeny žádné protokoly, které by podporovaly prohlížení! U2::RemoteMachineSettingsDialog Error! Chyba! Sorry! Cannot create remote machine Promiňte. Nelze vytvořit vzdálený stroj U2::RemoteWorkflowRunTask Workflow run task on the cloud Bad remote machine settings Started remote workflow task Cannot create remote machine from remote machine settings: %1 U2::RetrievePublicMachinesTask Bad machine found on server Retrieve public machines: cannot recognise remote machine Retrieving public machines... Failed to retrieve public machines, error: %1 Found %1 public machines Illegal server response U2::RetrieveRemoteMachineInfoTask Retrieve remote machine info task Úkol získání informace o vzdáleném stroji Bad remote machine given Bad remote machine given Retrieve remote machine info task started Retrieve remote machine info task started Retrieved uuid Retrieved uuid Retrieved services list Retrieved services list Retrieved hostname Retrieved hostname Cannot create remote machine for ping task Cannot create remote machine for ping task Ping task is canceled by user Úkol zazvonění je zrušen uživatelem Ping task finished with error: Úkol zazvonění skončil s chybou: Task is canceled by user Úkol je zrušen uživatelem Retrieving remomote machine info... Cannot create remote machine from remote machine settings: %1 U2::SaveRemoteMachineSettings Save remote machine settings task Úkol uložení nastavení vzdáleného stroje Output file not set Výstupní soubor nenastaven Nothing to write: empty remote machine settings Není co zapsat: prázdné nastavení vzdáleného stroje Cannot open %1 file Nelze otevřít %1 soubor U2::UpdateActiveTasks Updating active tasks... Cannot create remote machine from remote machine settings: %1 Found active task: %1 Active tasks update finished! ugene-1.9.8/src/corelibs/U2Remote/transl/english.ts0000644000175000017500000004772411651544334020675 0ustar ilyailya RemoteMachineMonitorDialog Remote machine monitor Remote machine list <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> <html><head><meta name="qrichtext" content="1" /><style type="text/css"> p, li { white-space: pre-wrap; } </style></head><body style=" font-family:'MS Shell Dlg 2'; font-size:8.25pt; font-weight:400; font-style:normal;"> <p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-size:8pt;">The list contains information about available UGENE remote service machines: the web-url, server name, ping and authentification status. </span></p> <p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-size:8pt;">The green </span><a name="result_box"></a><span style=" font-size:8pt;">t</span><span style=" font-size:8pt;">ick in the status means succes, red cross - fail. The question sign means that the connection with these service has not been tested yet. </span></p></body></html> Url Server Name Ping Auth Add new UGENE remote service machine Add... Remove UGENE remote service machine from list Remove Modify settings of existing UGENE remote service machine Modify... Test connection with selected remote machine <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> <html><head><meta name="qrichtext" content="1" /><style type="text/css"> p, li { white-space: pre-wrap; } </style></head><body style=" font-family:'MS Shell Dlg 2'; font-size:8.25pt; font-weight:400; font-style:normal;"> <p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-size:8pt;">The connection is tested in two steps.</span></p> <p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-size:8pt;">First a PING command is sent to remote service, then an authentification information is sent (AUTH command) and active session is started. </span></p></body></html> Test Connection Show user remote tasks statistics Activate User Tasks dialog, to check finished and ongoing tasks status, retrieve results or delete remote tasks. Show User Tasks Add available public machines to the list Get Public Machines OK Cancel Events log RemoteMachineScanDialog Scan remote machine Add Host Protocol Add selected Cancel RemoteMachineSettingsDialog Remote machine configuration OK Cancel U2::DistributedComputingUtil Remote machines monitor... U2::PingTask PingTask Starting remote service ping task, task-id: %1 Remote service ping task finished, task-id: %1 U2::RemoteMachineMonitorDialogImpl Found %1 remote machine records Save machine... Can't add %1 machine. The machine is already registered Add remote macnine No protocols for distributed computing are found. Please check your plugin list. Error! Ping task is already active for machine: %1 Public machines request is already sent Error during remote machines request: %1 No public machines found Cannot delete machine that is waiting for response Run Test connection for machine %1 finished with error: '%2' Info Select a file to save Selecting machines error! You didn't select a machine to run remote task! U2::RemoteMachineScanDialogImpl No protocols that supports scanning found! U2::RemoteMachineSettingsDialog Error! Sorry! Cannot create remote machine U2::RemoteWorkflowRunTask Workflow run task on the cloud Bad remote machine settings Started remote workflow task Cannot create remote machine from remote machine settings: %1 U2::RetrievePublicMachinesTask Retrieving public machines... Failed to retrieve public machines, error: %1 Found %1 public machines Illegal server response U2::RetrieveRemoteMachineInfoTask Retrieve remote machine info task Cannot create remote machine from remote machine settings: %1 Ping task is canceled by user Ping task finished with error: Task is canceled by user Retrieving remomote machine info... U2::SaveRemoteMachineSettings Save remote machine settings task Output file not set Nothing to write: empty remote machine settings Cannot open %1 file U2::UpdateActiveTasks Updating active tasks... Found active task: %1 Active tasks update finished! Cannot create remote machine from remote machine settings: %1 ugene-1.9.8/src/corelibs/U2Core/0000755000175000017500000000000011651544332015006 5ustar ilyailyaugene-1.9.8/src/corelibs/U2Core/src/0000755000175000017500000000000011651544332015575 5ustar ilyailyaugene-1.9.8/src/corelibs/U2Core/src/util_text/0000755000175000017500000000000011651544332017616 5ustar ilyailyaugene-1.9.8/src/corelibs/U2Core/src/util_text/FormatUtils.cpp0000644000175000017500000000656511651544332022607 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "FormatUtils.h" namespace U2 { QString FormatUtils::splitThousands(int num) { QString prefix = ""; QString numStr = QString::number(num); QString result = ""; int j = 0; for (int i = numStr.length(); --i >= 0; j++) { result = numStr.mid(i, 1) + (j > 0 && j % 3 == 0?" " : "") + result; } return result; } QString FormatUtils::formatNumber(int num) { int rem; if (num >= 1000 * 1000 * 1000) { if ((rem = num % (1000 * 1000 * 1000)) == 0) { return QString::number(rem) + QString("G"); } if (num % (100 * 1000 * 1000) == 0) { return QString::number(num / (double) (1000 * 1000 * 100), 'f', 1) + QString("G"); } } if (num >= 1000 * 1000) { if (num % (1000 * 1000) == 0) { return QString::number(num / (1000 * 1000)) + QString("m"); } if (num % (100 * 1000) == 0) { return QString::number(num / (double) (1000 * 1000), 'f', 1) + QString("m"); } } if (num >= 1000) { if (num % 1000 == 0) { return QString::number(num / 1000) + QString("k"); } if (num % 100 == 0) { return QString::number(num / (double) 1000, 'f', 1) + QString("k"); } } return QString::number(num); } // 6031769.1k -> 6 031 769.1k static QString insertSpaceSeparators(QString str) { for(int i = str.length()-3; i > 0; i-=3) { if(str.at(i).isDigit() && i > 0 && str.at(i-1).isDigit()) { str.insert(i, " "); } } return str; } QString FormatUtils::formatNumberWithSeparators(int num) { return insertSpaceSeparators(formatNumber(num)); } QString FormatUtils::insertSeparators(int num) { return insertSpaceSeparators(QString::number(num)); } QString FormatUtils::getShortMonthName( int num ) { switch (num) { case 1: return QString("JAN"); case 2: return QString("FEB"); case 3: return QString("MAR"); case 4: return QString("APR"); case 5: return QString("MAY"); case 6: return QString("JUN"); case 7: return QString("JUL"); case 8: return QString("AUG"); case 9: return QString("SEP"); case 10: return QString("OCT"); case 11: return QString("NOV"); case 12: return QString("DEC"); default: return QString(); } } } ugene-1.9.8/src/corelibs/U2Core/src/util_text/TextUtils.cpp0000644000175000017500000001171411651544332022273 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "TextUtils.h" #include namespace U2 { static QBitArray getAlphas(); static QBitArray getAlphaNums(); static QBitArray getNums(); static QBitArray getWhites(); static QBitArray getLines(); static QBitArray getBinary(); static QByteArray getUpperCaseMap(); static QByteArray getLowerCaseMap(); static QByteArray getSpaceLine(); static QBitArray getLessThan(); static QBitArray getGrearThan(); static QBitArray getQualNameAllowedSymbols(); const QBitArray TextUtils::ALPHAS = getAlphas(); const QBitArray TextUtils::ALPHA_NUMS = getAlphaNums(); const QBitArray TextUtils::NUMS = getNums(); const QBitArray TextUtils::WHITES = getWhites(); const QBitArray TextUtils::LINE_BREAKS = getLines(); const QBitArray TextUtils::BINARY = getBinary(); const QByteArray TextUtils::UPPER_CASE_MAP = getUpperCaseMap(); const QByteArray TextUtils::LOWER_CASE_MAP = getLowerCaseMap(); const QByteArray TextUtils::SPACE_LINE = getSpaceLine(); const QBitArray TextUtils::LESS_THAN = getLessThan(); const QBitArray TextUtils::GREATER_THAN = getGrearThan(); const QBitArray TextUtils::QUALIFIER_NAME_CHARS = getAlphas() | getNums() | getQualNameAllowedSymbols(); const QBitArray TextUtils::ANNOTATIONS_NAME_CHARS = TextUtils::QUALIFIER_NAME_CHARS; //TODO: optimize shared data structs access! -> replace it with arrays with bounds checking in debug static QBitArray getEmptyBitMap() { return QBitArray(256); } static QBitArray getQualNameAllowedSymbols(){ QBitArray res = getEmptyBitMap(); res['-']=res['\'']=res['_']=res['*']=true; return res; } static QBitArray getBinary() { QBitArray res = getEmptyBitMap(); res.fill(true, 0, 31); res &= ~getWhites(); return res; } static QBitArray getAlphaNums() { QBitArray res = getAlphas(); res|= getNums(); return res; } static QBitArray getAlphas() { QBitArray res = getEmptyBitMap(); res.fill(true, 'A', 'Z'+1); res.fill(true, 'a', 'z'+1); return res; } static QBitArray getNums() { QBitArray res = getEmptyBitMap(); res.fill(true, '0', '9'+1); return res; } static QBitArray getWhites() { //'\t', '\n', '\v', '\f', '\r', and ' ' QBitArray res = getEmptyBitMap(); res['\t']=res['\n']=res['\v']=res['\f']=res['\r']=res[' ']=true; return res; } QBitArray getLines() { QBitArray res = getEmptyBitMap(); res['\r'] = res['\n'] = true; return res; } QBitArray getLessThan() { QBitArray res = getEmptyBitMap(); res['<'] = true; return res; } QBitArray getGrearThan() { QBitArray res = getEmptyBitMap(); res['>'] = true; return res; } QBitArray TextUtils::createBitMap(char c1) { QBitArray res = getEmptyBitMap(); res[quint8(c1)] = true; return res; } QBitArray TextUtils::createBitMap(const QByteArray& chars, bool val) { QBitArray res = getEmptyBitMap(); for (int i = 0, n = chars.size(); i < n ; i++) { char c = chars[i]; res[quint8(c)] = val; } return res; } QByteArray TextUtils::createMap(const QBitArray& bits, char defaultChar) { assert(bits.size() == 256); QByteArray res(256, 0); for(int i=0;i<256; i++) { res[i] = bits[i] ? (char)i : defaultChar; } return res; } static QByteArray getUpperCaseMap() { QByteArray b(256, 0); for(int i=0;i= 'a' && c<='z') { c-='a'-'A'; } b[i] = c; } return b; } static QByteArray getLowerCaseMap() { QByteArray b(256, 0); for(int i=0;i= 'A' && c<='Z') { c+='a'-'A'; } b[i] = c; } return b; } static QByteArray getSpaceLine() { QByteArray res(4096, ' '); res[4096]='\0'; return res; } QString TextUtils::variate(const QString& prefix, const QString& sep, const QSet& filter, bool mustHaveSuffix, int startSeed) { int seed = startSeed; QString res = prefix; if (!mustHaveSuffix && !filter.contains(res) && !res.isEmpty()) { return res; } do { res = prefix + sep + QString::number(seed++); } while (filter.contains(res)); return res; } }//namespace ugene-1.9.8/src/corelibs/U2Core/src/util_text/TextUtils.h0000644000175000017500000002214711651544332021742 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_TEXT_UTILS_H_ #define _U2_TEXT_UTILS_H_ #include #include #include #include #include #include namespace U2 { class U2CORE_EXPORT TextUtils { public: static const QBitArray ALPHAS; static const QBitArray ALPHA_NUMS; static const QBitArray NUMS; static const QBitArray WHITES; static const QBitArray LINE_BREAKS; static const QBitArray BINARY; static const QBitArray LESS_THAN; static const QBitArray GREATER_THAN; static const QByteArray UPPER_CASE_MAP; static const QByteArray LOWER_CASE_MAP; static const QByteArray SPACE_LINE; static const QBitArray QUALIFIER_NAME_CHARS; static const QBitArray ANNOTATIONS_NAME_CHARS; inline static const char* getLineOfSpaces(int nspaces); inline static bool fits(const QBitArray& map, const char* str, int len); inline static bool contains(const QBitArray& map, const char* str, int len); static QBitArray createBitMap(char c1); static QBitArray createBitMap(const QByteArray& chars, bool val = true); static QByteArray createMap(const QBitArray& bits, char defaultChar); inline static int skip(const QBitArray& map, const char* seq, int len); inline static int keep(const char* srcSeq, int len, char* dstSeq, const QBitArray& keepMap); inline static int keep(char* srcSeq, int len, const QBitArray& keepMap) {return keep(srcSeq, len, srcSeq, keepMap);} inline static int remove(const char* srcSeq, int len, char* dstSeq, const QBitArray& removeMap); inline static int remove(char* srcSeq, int len, const QBitArray& removeMap) {return remove(srcSeq, len, srcSeq, removeMap);} inline static void replace(char* seq, int len, const QBitArray& fromMap, char to); inline static void applyMap(const QBitArray& map, const char* srcSeq, int len, char* dstSeq); inline static void applyMap(const QBitArray& map, char* seq, int len) { applyMap(map, seq, len, seq);} inline static void translate(const QByteArray& map, char* seq, int len) { translate(map, seq, len, seq);} inline static void translate(const QByteArray& map, const char* src, int len, char* dst); inline static void reverse(const char* srcSeq, char* dstSeq, int len); inline static void reverse(char* seq, int len); inline static bool equals(const char* str1, const char* str2, int n); inline static bool isQuoted(const char* str, int len, int qChar); static QString variate(const QString& prefix, const QString& sep, const QSet& filter, bool mustHaveSuffix = false, int startSeed = 0); inline static void charBounds(const char* data, int dataSize, char& minChar, char& maxChar); //todo: move this method to another class inline static QByteArray selectIdx256(const QBitArray& map, bool sign); // Returns first index of the character not equal to 'c'. Returns -1 if not found inline static int firstIndexOfNotEqualChar(const char* seq, int size, char c); // Returns last index of the character not equal to 'c'. Returns -1 if not found inline static int lastIndexOfNotEqualChar(const char* seq, int size, char c); // Wraps input string for valid output to CSV following RFC 4180 inline static void wrapForCSV(QString& str); }; template inline void reverseVector(QVector&); inline const char* TextUtils::getLineOfSpaces(int nspaces) { assert(nspaces >=0 && nspaces <= SPACE_LINE.size()); return SPACE_LINE.data() + SPACE_LINE.size() - 1 - nspaces; } inline bool TextUtils::fits(const QBitArray& map, const char* str, int len) { for(int i=0; i len); for (int i = 0, j = len-1; i < len; i++, j--) { char c = srcSeq[i]; dstSeq[j] = c; } } inline void TextUtils::reverse(char* seq, int len) { for (int i = 0, j = len-1; i < j; i++, j--) { char c = seq[j]; seq[j] = seq[i]; seq[i] = c; } } template inline void reverseVector(QVector& seq) { const int len = seq.size(); for (int i = 0, j = len-1; i < j; i++, j--) { T t = seq[j]; seq[j] = seq[i]; seq[i] = t; } } inline bool TextUtils::equals(const char* str1, const char* str2, int n) { assert(n>0); if (str1[0] != str2[0]) { return false; } for(int i=1; i=0); if (len < 2 || str[0]!=qChar || str[len-1]!=qChar) { return false; } int nquotes = 2; for(int i=1, n=len-1; i 0); maxChar = minChar = data[0]; for (int i=1; i < dataSize; i++) { char c = data[i]; minChar = qMin(minChar, c); maxChar = qMax(maxChar, c); } } // returns first index of the character not equal to 'c' inline int TextUtils::firstIndexOfNotEqualChar(const char* seq, int size, char c) { for (int i = 0; i < size; i++) { char ci = seq[i]; if (ci != c) { return i; } } return -1; } // returns last index of the character not equal to 'c' inline int TextUtils::lastIndexOfNotEqualChar(const char* seq, int size, char c) { for (int i = size - 1; i >= 0; i--) { char ci = seq[i]; if (ci != c) { return i; } } return -1; } // Wraps input string for valid output to CSV following RFC 4180 inline void TextUtils::wrapForCSV(QString& str) { if (!str.contains(",")) { return; } str.replace("\"", "\"\""); str.prepend("\""); str.append("\""); } } //namespace #endif ugene-1.9.8/src/corelibs/U2Core/src/util_text/FormatUtils.h0000644000175000017500000000270311651544332022242 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_FORMAT_UTILS_H_ #define _U2_FORMAT_UTILS_H_ #include #include namespace U2 { class U2CORE_EXPORT FormatUtils { public: static QString splitThousands(int num); static QString formatNumber(int num); static QString formatNumberWithSeparators(int num); static QString insertSeparators(int num); // QDate::getShortMonthName() returns date in local translation // This is English version of this function, required by EMBL and Genbank // for correct date formatting static QString getShortMonthName(int num); }; }//namespace #endif ugene-1.9.8/src/corelibs/U2Core/src/selection/0000755000175000017500000000000011651544332017562 5ustar ilyailyaugene-1.9.8/src/corelibs/U2Core/src/selection/DNASequenceSelection.h0000644000175000017500000000256611651544332023705 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_DNASEQUENCE_SELECTION_H_ #define _U2_DNASEQUENCE_SELECTION_H_ #include "LRegionsSelection.h" #include "SelectionTypes.h" namespace U2 { class DNASequenceObject; class U2CORE_EXPORT DNASequenceSelection : public LRegionsSelection { Q_OBJECT public: DNASequenceSelection(DNASequenceObject* _obj, QObject* p = NULL) : LRegionsSelection(GSelectionTypes::DNASEQUENCE, p), obj(_obj) {} const DNASequenceObject* getSequenceObject() const { return obj; } private: DNASequenceObject* obj; }; }//namespace #endif ugene-1.9.8/src/corelibs/U2Core/src/selection/SelectionTypes.cpp0000644000175000017500000000301111651544332023233 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "SelectionTypes.h" // These are included to export symbols #include "TextSelection.h" #include "DNASequenceSelection.h" namespace U2 { const GSelectionType GSelectionTypes::DOCUMENTS("selection_documents"); const GSelectionType GSelectionTypes::GOBJECTS("selection_gobjects"); const GSelectionType GSelectionTypes::GOBJECT_VIEWS("selection_gobject_views"); const GSelectionType GSelectionTypes::TEXT("selection_text"); const GSelectionType GSelectionTypes::DNASEQUENCE("selection_dnasequence"); const GSelectionType GSelectionTypes::ANNOTATIONS("selection_annotations"); const GSelectionType GSelectionTypes::ANNOTATION_GROUPS("selection_annotation_groups"); }//namespace ugene-1.9.8/src/corelibs/U2Core/src/selection/DocumentSelection.cpp0000644000175000017500000000610311651544332023712 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "DocumentSelection.h" #include #include namespace U2 { static QList emptyDocs; void DocumentSelection::clear() { QList tmpRemoved = selectedDocs; selectedDocs.clear(); if (!tmpRemoved.isEmpty()) { emit si_selectionChanged(this, emptyDocs, tmpRemoved); } } void DocumentSelection::setSelection(const QList& docs) { if (docs.isEmpty()) { clear(); return; } if (isEmpty()) { addToSelection(docs); return; } QList tmpAdded; QList tmpRemoved; foreach(Document* d, docs) { if (!selectedDocs.contains(d)) { tmpAdded.push_back(d); } } foreach(Document* d, selectedDocs) { if (!docs.contains(d)) { tmpRemoved.push_back(d); } } foreach(Document* d, tmpRemoved) { selectedDocs.removeAll(d); } foreach(Document* d, tmpAdded) { selectedDocs.push_back(d); } emit si_selectionChanged(this, tmpAdded, tmpRemoved); } void DocumentSelection::addToSelection(const QList& docs) { QList tmpAdded; int sBefore = selectedDocs.size(); foreach(Document* d, docs) { if (!selectedDocs.contains(d)) { tmpAdded.push_back(d); selectedDocs.push_back(d); } } if (selectedDocs.size()!=sBefore) { emit si_selectionChanged(this, tmpAdded, emptyDocs); } } void DocumentSelection::removeFromSelection(const QList& docs) { QList tmpRemoved; int sBefore = selectedDocs.size(); foreach(Document* d, docs) { if (selectedDocs.removeAll(d)!=0) { tmpRemoved.push_back(d); } } if (selectedDocs.size()!=sBefore) { emit si_selectionChanged(this, emptyDocs, tmpRemoved); } } /* ProjectDocumentSelection::ProjectDocumentSelection(QObject* parent) : DocumentSelection(parent) { Project* p = AppContext::getProject(); connect(p, SIGNAL(si_documentRemoved(Document*)), SLOT(sl_onDocumentRemoved(Document*))); } void ProjectDocumentSelection::sl_onDocumentRemoved(Document* d) { removeFromSelection(QList()< * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_ANNOTATION_SELECTION_H_ #define _U2_ANNOTATION_SELECTION_H_ #include "SelectionTypes.h" #include namespace U2 { class Annotation; class AnnotationGroup; class AnnotationTableObject; class DNATranslation; class U2CORE_EXPORT AnnotationSelectionData { public: AnnotationSelectionData(Annotation* a, int lIdx) : annotation(a), locationIdx(lIdx){} // the annotation selected Annotation* annotation; //location idx that is preferable for visualization // -1 == not specified, 0..N == idx of U2Region in 'location' field //BUG:404: do we need a separate class for this feature? int locationIdx; bool operator==(const AnnotationSelectionData& d) const {return d.annotation == annotation && d.locationIdx == locationIdx;} int getSelectedRegionsLen() const; // Returns all regions from selected annotations locations without any modification QVector getSelectedRegions() const; }; class U2CORE_EXPORT AnnotationSelection : public GSelection { Q_OBJECT public: AnnotationSelection(QObject* p = NULL) : GSelection(GSelectionTypes::ANNOTATIONS, p) {} const QList& getSelection() const {return selection;} const AnnotationSelectionData* getAnnotationData(const Annotation*) const; // adds annotation to selection. // if annotation is already in selection and have a different locationIdx -> removes the old annotaiton selection data // and adds the annotation again with updated locationIdx void addToSelection(Annotation* a, int locationIdx = -1); void removeFromSelection(Annotation* a, int locationIdx = -1); virtual bool isEmpty() const {return selection.isEmpty();} virtual void clear(); virtual void removeObjectAnnotations(AnnotationTableObject* obj); bool contains(const Annotation* a) const {return getAnnotationData(a)!=NULL;} bool contains(const Annotation* a, int locationIdx) const; static void getAnnotationSequence(QByteArray& res, const AnnotationSelectionData& sd, char gapSym, const QByteArray& seq, DNATranslation* complTT, DNATranslation* aminoTT); // Returns list of locations of all selected annotations that belongs to the objects in list QVector getSelectedLocations(const QSet& objects) const; signals: void si_selectionChanged( AnnotationSelection* thiz, const QList& added, const QList& removed); private: QList selection; }; ////////////////////////////////////////////////////////////////////////// // AnnotationGroupSelection class U2CORE_EXPORT AnnotationGroupSelection : public GSelection { Q_OBJECT public: AnnotationGroupSelection(QObject* p = NULL) : GSelection(GSelectionTypes::ANNOTATION_GROUPS, p) {} const QList& getSelection() const {return selection;} void addToSelection(AnnotationGroup* g); void removeFromSelection(AnnotationGroup* g); virtual bool isEmpty() const {return selection.isEmpty();} virtual void clear(); virtual void removeObjectGroups(AnnotationTableObject* obj); bool contains(AnnotationGroup* g) const {return selection.contains(g);} signals: void si_selectionChanged( AnnotationGroupSelection* thiz, const QList& added, const QList& removed); private: QList selection; }; }//namespace #endif ugene-1.9.8/src/corelibs/U2Core/src/selection/AnnotationSelection.cpp0000644000175000017500000002220011651544332024242 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "AnnotationSelection.h" #include #include #include #include namespace U2 { static QList emptyAnnotations; QVector AnnotationSelectionData::getSelectedRegions() const { QVector res; if (locationIdx != -1) { res << annotation->getRegions()[locationIdx]; } else { res << annotation->getRegions(); } return res; } int AnnotationSelectionData::getSelectedRegionsLen() const { if (locationIdx != -1) { return annotation->getRegions()[locationIdx].length; } int len = 0; foreach(const U2Region& r, annotation->getRegions()) { len+=r.length; } return len; } void AnnotationSelection::clear() { if (selection.isEmpty()) { return; } QList tmpRemoved; foreach(const AnnotationSelectionData& asd, selection) { tmpRemoved.push_back(asd.annotation); } selection.clear(); emit si_selectionChanged(this, emptyAnnotations, tmpRemoved); } void AnnotationSelection::removeObjectAnnotations(AnnotationTableObject* obj) { QList removed; foreach(Annotation* a, obj->getAnnotations()) { for(int i=0, n = selection.size(); i=-1 && locationIdx < a->getRegions().size(), "Invalid location index!",); int nRegionsBefore = 0; foreach(const AnnotationSelectionData& asd, selection) { if (asd.annotation == a) { nRegionsBefore++; if (asd.locationIdx == locationIdx || asd.locationIdx == -1) { return; //nothing changed } } } int nRegionsTotal = a->getRegions().size(); assert(nRegionsBefore < nRegionsTotal); //remove old regions if needed bool removeFromSelection = nRegionsBefore > 0 && ((nRegionsBefore == nRegionsTotal - 1) || locationIdx == -1); if (removeFromSelection) { QList newSelection; foreach(const AnnotationSelectionData& asd, selection) { if (asd.annotation != a) { newSelection.append(asd); } } selection = newSelection; } int updatedLocationIdx = nRegionsBefore == nRegionsTotal - 1 ? -1 : locationIdx; selection.append(AnnotationSelectionData(a, updatedLocationIdx)); QList tmp; tmp.append(a); emit si_selectionChanged(this, tmp, emptyAnnotations); } void AnnotationSelection::removeFromSelection(Annotation* a, int locationIdx) { bool inSel = false; bool inSelPartial = false; int nRegionsSelected = 0; int nRegionsTotal = a->getRegions().size(); foreach(const AnnotationSelectionData& asd, selection) { if (asd.annotation == a) { inSel = true; inSelPartial = asd.locationIdx != -1; nRegionsSelected++; } } if (!inSel) { return; } bool leftInSelection = false; if (locationIdx == -1) { // remove all regions from selection QList newSelection; foreach(const AnnotationSelectionData& asd, selection) { if (asd.annotation != a) { newSelection.append(asd); } } selection = newSelection; } else if (inSelPartial) { //remove 1 region from set of regions for (int i = 0, n = selection.size(); i 0; } else { // selection contains whole annotation, only 1 region is removed -> split assert(!inSelPartial && locationIdx!=-1); for (int i = 0, n = selection.size(); igetRegions().size(); i 1; } QList tmp; tmp << a; emit si_selectionChanged(this, leftInSelection ? tmp : emptyAnnotations, tmp); } const AnnotationSelectionData* AnnotationSelection::getAnnotationData(const Annotation* a) const { foreach(const AnnotationSelectionData& asd, selection) { if (asd.annotation == a) { return &asd; } } return NULL; } void AnnotationSelection::getAnnotationSequence(QByteArray& res, const AnnotationSelectionData& sd, char gapSym, const QByteArray& sequence, DNATranslation* complTT, DNATranslation* aminoTT) { int start = sd.locationIdx == -1 ? 0 : sd.locationIdx; QVector r = sd.annotation->getRegions(); int nLocations = sd.locationIdx == -1 ? r.size() : 1; U2Region sequenceRange(0, sequence.size()); for (int j = start, last = start + nLocations; j < last; j++) { if (j!=start) { res.append(gapSym); } U2Region reg = r.at(j).intersect(sequenceRange); QByteArray partSeq(sequence.constData() + reg.startPos, reg.length); if (complTT!=NULL) { TextUtils::translate(complTT->getOne2OneMapper(), partSeq.data(), partSeq.size()); TextUtils::reverse(partSeq.data(), partSeq.size()); } if (aminoTT!=NULL) { aminoTT->translate(partSeq.data(), reg.length, partSeq.data(), reg.length); partSeq.resize(partSeq.size()/3); } res.append(partSeq); } } bool AnnotationSelection::contains(const Annotation* a, int locationIdx) const { foreach(const AnnotationSelectionData& asd, selection) { if (asd.annotation == a && (asd.locationIdx == -1 || asd.locationIdx == locationIdx)) { return true; } } return false; } ////////////////////////////////////////////////////////////////////////// // Annotation group selection static QList emptyGroups; void AnnotationGroupSelection::clear() { if (selection.isEmpty()) { return; } QList tmpRemoved = selection; selection.clear(); emit si_selectionChanged(this, emptyGroups, tmpRemoved); } void AnnotationGroupSelection::removeObjectGroups(AnnotationTableObject* obj) { QList tmpRemoved; foreach(AnnotationGroup* g, selection) { if (g->getGObject() == obj) { tmpRemoved.append(g); } } foreach(AnnotationGroup* g, tmpRemoved) { selection.removeOne(g); } emit si_selectionChanged(this, emptyGroups, tmpRemoved); } void AnnotationGroupSelection::addToSelection(AnnotationGroup* g) { if (selection.contains(g)) { return; } selection.append(g); QList tmpAdded; tmpAdded.append(g); emit si_selectionChanged(this, tmpAdded, emptyGroups); } void AnnotationGroupSelection::removeFromSelection(AnnotationGroup* g) { bool found = selection.removeOne(g); if (found) { QList tmpRemoved; tmpRemoved.append(g); emit si_selectionChanged(this, emptyGroups, tmpRemoved); } } // Returns list of locations of all selected annotations QVector AnnotationSelection::getSelectedLocations(const QSet& objects) const { QVector result; if (objects.isEmpty()) { return result; } foreach(const AnnotationSelectionData& d, selection) { if (objects.contains(d.annotation->getGObject())) { result << d.getSelectedRegions(); } } return result; } }//namespace ugene-1.9.8/src/corelibs/U2Core/src/selection/SelectionTypes.h0000644000175000017500000000251011651544332022703 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_SELECTION_TYPES_H_ #define _U2_SELECTION_TYPES_H_ #include namespace U2 { class U2CORE_EXPORT GSelectionTypes { public: static const GSelectionType DOCUMENTS; static const GSelectionType GOBJECTS; static const GSelectionType GOBJECT_VIEWS; static const GSelectionType TEXT; static const GSelectionType DNASEQUENCE; static const GSelectionType ANNOTATIONS; static const GSelectionType ANNOTATION_GROUPS; }; }//namespace #endif ugene-1.9.8/src/corelibs/U2Core/src/selection/SelectionModel.h0000644000175000017500000000361211651544332022643 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_SELECTION_MODEL_H_ #define _U2_SELECTION_MODEL_H_ #include namespace U2 { typedef QString GSelectionType; class U2CORE_EXPORT GSelection : public QObject { Q_OBJECT public: GSelection(GSelectionType _type, QObject* p = NULL) : QObject(p), type(_type) {} GSelectionType getSelectionType() const {return type;} virtual bool isEmpty() const = 0; virtual void clear() = 0; signals: void si_onSelectionChanged(GSelection*); private: GSelectionType type; }; typedef QList GSelections; class U2CORE_EXPORT MultiGSelection { public: MultiGSelection(){} //TODO: deallocation! -> use shared data void addSelection(const GSelection* s); void removeSelection(const GSelection* s); bool contains(GSelectionType t) const {return findSelectionByType(t) !=NULL;} const GSelection* findSelectionByType(GSelectionType t) const; const QList& getSelections() const {return selections;} private: QList selections; }; }//namespace #endif ugene-1.9.8/src/corelibs/U2Core/src/selection/GObjectSelection.cpp0000644000175000017500000000707311651544332023460 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "GObjectSelection.h" namespace U2 { static QList emptyObjs; void GObjectSelection::clear() { QList tmpRemoved = selectedObjects; selectedObjects.clear(); if (!tmpRemoved.isEmpty()) { emit si_selectionChanged(this, emptyObjs, tmpRemoved); } } void GObjectSelection::setSelection(const QList& objs) { if (objs.isEmpty()) { clear(); return; } if (isEmpty()) { addToSelection(objs); return; } QList tmpAdded; QList tmpRemoved; foreach(GObject* o, objs) { if (!selectedObjects.contains(o)) { tmpAdded.append(o); } } foreach(GObject* o, selectedObjects) { if (!objs.contains(o)) { tmpRemoved.append(o); } } foreach(GObject* o, tmpRemoved) { selectedObjects.removeAll(o); } foreach(GObject* o, tmpAdded) { selectedObjects.append(o); } emit si_selectionChanged(this, tmpAdded, tmpRemoved); } void GObjectSelection::addToSelection(GObject* obj) { QList objs; objs.append(obj); addToSelection(objs); } void GObjectSelection::addToSelection(const QList& obj) { QList tmpAdded; int sBefore = selectedObjects.size(); foreach(GObject* o, obj) { if (!selectedObjects.contains(o)) { tmpAdded.append(o); selectedObjects.append(o); } } if (selectedObjects.size() != sBefore) { emit si_selectionChanged(this, tmpAdded, emptyObjs); } } void GObjectSelection::removeFromSelection(GObject* obj) { QList l; l.append(obj); removeFromSelection(l); } void GObjectSelection::removeFromSelection(const QList& obj) { QList tmpRemoved; int sBefore = selectedObjects.size(); foreach(GObject* o, obj) { if (selectedObjects.removeAll(o)!=0) { tmpRemoved.push_back(o); } } if (selectedObjects.size() != sBefore) { emit si_selectionChanged(this, emptyObjs, tmpRemoved); } } /* ////////////////////////////////////////////////////////////////////////// /// GDocumentObjectSelection void GDocumentObjectSelection::_append(GObject* o) { Document* d = o->getDocument(); assert(d!=NULL); connect(d, SIGNAL(si_objectRemoved(GObject*)), SLOT(void sl_onObjectRemoved(GObject*))); GObjectSelection::_append(o); } void GDocumentObjectSelection::_remove(GObject* o) { o->disconnect(this); GObjectSelection::_remove(o); } void GDocumentObjectSelection::sl_onObjectRemoved(GObject* o) { removeFromSelection(o); } ////////////////////////////////////////////////////////////////////////// /// GProjectObjectSelection */ }//namespace ugene-1.9.8/src/corelibs/U2Core/src/selection/SelectionUtils.cpp0000644000175000017500000001623611651544332023244 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "SelectionUtils.h" #include "DocumentSelection.h" #include "GObjectSelection.h" #include "SelectionTypes.h" #include #include #include #include #include #include namespace U2 { //Warn: works only for pointer type template static void removeDuplicatesPointersFromList(QList& list) { QSet tracked; for(int i=0, n = list.size(); i < n ; i++) { const T* val = list.at(i); if (tracked.contains(val)) { list[i] = NULL; } else { tracked.insert(val); } } list.removeAll(NULL); } QList SelectionUtils::findObjects(GObjectType t, const MultiGSelection* ms, UnloadedObjectFilter f) { QList res; foreach(const GSelection* s, ms->getSelections()) { QList tmp = findObjects(t, s, f); res+=tmp; } return res; } QList SelectionUtils::findObjectsKeepOrder(GObjectType t, const MultiGSelection* ms, UnloadedObjectFilter f) { QList res; foreach(const GSelection* s, ms->getSelections()) { QList tmp = findObjectsKeepOrder(t, s, f); res+=tmp; } //now remove duplicates from list removeDuplicatesPointersFromList(res); return res; } QList SelectionUtils::findObjects(GObjectType t, const GSelection* s, UnloadedObjectFilter f) { QList res = findObjectsKeepOrder(t, s, f); return res; } QList SelectionUtils::findObjectsKeepOrder(GObjectType t, const GSelection* s, UnloadedObjectFilter f) { QList res; GSelectionType stype = s->getSelectionType(); if (stype == GSelectionTypes::DOCUMENTS) { const DocumentSelection* ds = qobject_cast(s); foreach(Document* d, ds->getSelectedDocuments()) { const QList& objs= d->getObjects(); QList tmp = GObjectUtils::select(objs, t, f); res+=tmp; } } else if (stype == GSelectionTypes::GOBJECTS) { const GObjectSelection* os = qobject_cast(s); const QList& objs= os->getSelectedObjects(); res = GObjectUtils::select(objs, t, f); } return res; } QSet SelectionUtils::findDocumentsWithObjects(GObjectType t, const MultiGSelection* ms, UnloadedObjectFilter f, bool deriveDocsFromObjectSelection) { QSet res; foreach(const GSelection* s, ms->getSelections()) { res+=findDocumentsWithObjects(t, s, f, deriveDocsFromObjectSelection); } return res; } QSet SelectionUtils::findDocumentsWithObjects(GObjectType t, const GSelection* s, UnloadedObjectFilter f, bool deriveDocsFromObjectSelection) { QSet res; GSelectionType st = s->getSelectionType(); if (st == GSelectionTypes::DOCUMENTS) { DocumentFormatConstraints c; c.supportedObjectTypes += t; const DocumentSelection* ds = qobject_cast(s); const QList& docs = ds->getSelectedDocuments(); foreach(Document* d, docs) { if (!d->getObjects().isEmpty()) { QList objs = d->findGObjectByType(t, f); if (!objs.isEmpty()) { res+=d; } } else if (f == UOF_LoadedAndUnloaded && !d->isLoaded()) { //document is unloaded DocumentFormat* df = d->getDocumentFormat(); if (df->checkConstraints(c)) { res+=d; } } } } else if (st == GSelectionTypes::GOBJECTS && deriveDocsFromObjectSelection) { QList objects = findObjects(t, s, f); foreach(GObject* o, objects) { res+=o->getDocument(); } } return res; } bool SelectionUtils::isDocumentInSelection(const Document* doc, const MultiGSelection& ms, bool deriveDocsFromObjectSelection) { foreach(const GSelection* s, ms.getSelections()) { GSelectionType st = s->getSelectionType(); if (st == GSelectionTypes::DOCUMENTS) { const DocumentSelection* ds = qobject_cast(s); const QList& docs = ds->getSelectedDocuments(); if (docs.contains((Document* const &)doc)) {//TODO? why cast return true; } } else if (st == GSelectionTypes::GOBJECTS && deriveDocsFromObjectSelection) { const GObjectSelection* os = qobject_cast(s); const QList& objects = os->getSelectedObjects(); foreach(GObject* o, objects) { if (o->getDocument() == doc) { return true; } } } } return false; } QList SelectionUtils::getSelectedDocs(const MultiGSelection& ms) { foreach(const GSelection* s, ms.getSelections()) { GSelectionType st = s->getSelectionType(); if (st == GSelectionTypes::DOCUMENTS) { const DocumentSelection* ds = qobject_cast(s); return ds->getSelectedDocuments(); } } return QList(); } QList SelectionUtils::getSelectedObjects(const MultiGSelection& ms) { foreach(const GSelection* s, ms.getSelections()) { GSelectionType st = s->getSelectionType(); if (st == GSelectionTypes::GOBJECTS) { const GObjectSelection* os = qobject_cast(s); return os->getSelectedObjects(); } } return QList(); } U2Region SelectionUtils::normalizeRegionBy3(U2Region reg, int seqLen, bool direct) { assert(reg.length > 0); if ( seqLen < 3 ){ return reg; } int d = reg.length % 3; if (d == 1) { if (direct) { reg.length-=1; } else { reg.startPos+=1; reg.length-=1; } } else if (d == 2) { if (direct) { reg.length+=(reg.length+1 < seqLen) ? +1 : -2; } else { int prevStart = reg.startPos; reg.startPos+=(reg.startPos > 0) ? -1 : +2; reg.length+=prevStart - reg.startPos; } } return reg; } }//namespace ugene-1.9.8/src/corelibs/U2Core/src/selection/GObjectSelection.h0000644000175000017500000000503211651544332023116 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_GOBJECT_SELECTION_H_ #define _U2_GOBJECT_SELECTION_H_ #include "SelectionTypes.h" #include namespace U2 { class GObject; class U2CORE_EXPORT GObjectSelection : public GSelection { Q_OBJECT public: GObjectSelection(QObject* p = NULL) : GSelection(GSelectionTypes::GOBJECTS, p) {} const QList& getSelectedObjects() const {return selectedObjects;} virtual bool isEmpty() const {return selectedObjects.isEmpty();} virtual void clear(); void setSelection(const QList& objs); void addToSelection(const QList& obj); void addToSelection(GObject* obj); void removeFromSelection(GObject* obj); void removeFromSelection(const QList& obj); bool contains(GObject* obj) const {return selectedObjects.contains(obj);} signals: void si_selectionChanged(GObjectSelection* thiz, const QList& objectsAdded, const QList& objectsRemoved); protected: virtual void _append(GObject* o) {selectedObjects.append(o);} virtual void _remove(GObject* o) {selectedObjects.removeAll(o);}; private: QList selectedObjects; }; /* class Document; class GDocumentObjectSelection : public GObjectSelection { Q_OBJECT public: GDocumentObjectSelection(QObject* p = NULL) : GObjectSelection(p){}; protected: virtual void _append(GObject* o); virtual void _remove(GObject* o); private slots: void sl_onObjectRemoved(Document* d, GObject* o); }; class GProjectObjectSelection : public GObjectSelection { Q_OBJECT public: GProjectObjectSelection(QObject* p = NULL); private slots: void sl_onDocumentRemoved(Document* d); }; */ } //namespace #endif ugene-1.9.8/src/corelibs/U2Core/src/selection/LRegionsSelection.h0000644000175000017500000000322211651544332023322 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_LREGION_SELECTION_H_ #define _U2_LREGION_SELECTION_H_ #include #include namespace U2 { class U2CORE_EXPORT LRegionsSelection : public GSelection { Q_OBJECT public: LRegionsSelection(GSelectionType type, QObject* p = NULL) : GSelection(type, p) {} const QVector& getSelectedRegions() const {return regions;} void setSelectedRegions(const QVector& newSelection); void addRegion(const U2Region& r); void removeRegion(const U2Region& r); virtual bool isEmpty() const {return regions.isEmpty();} virtual void clear(); signals: void si_selectionChanged(LRegionsSelection* thiz, const QVector& added, const QVector& removed); public: QVector regions; }; }//namespace #endif ugene-1.9.8/src/corelibs/U2Core/src/selection/SelectionUtils.h0000644000175000017500000000444711651544332022712 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_SELECTION_UTILS_H_ #define _U2_SELECTION_UTILS_H_ #include #include namespace U2 { class GObject; class Document; class MultiGSelection; class GSelection; class U2CORE_EXPORT SelectionUtils { public: static QList findObjects(GObjectType t, const MultiGSelection* s, UnloadedObjectFilter f); static QList findObjectsKeepOrder(GObjectType t, const MultiGSelection* s, UnloadedObjectFilter f); static QList findObjects(GObjectType t, const GSelection* s, UnloadedObjectFilter f); static QList findObjectsKeepOrder(GObjectType t, const GSelection* s, UnloadedObjectFilter f); static QSet findDocumentsWithObjects(GObjectType t, const MultiGSelection* s, UnloadedObjectFilter f, bool deriveDocsFromObjectSelection); static QSet findDocumentsWithObjects(GObjectType t, const GSelection* s, UnloadedObjectFilter f, bool deriveDocsFromObjectSelection); static bool isDocumentInSelection(const Document* doc, const MultiGSelection& ms, bool deriveDocsFromObjectSelection); static QList getSelectedDocs(const MultiGSelection& ms); static QList getSelectedObjects(const MultiGSelection& ms); //todo: find a better place: like DNAUtils.. static U2Region normalizeRegionBy3(U2Region reg, int seqLen, bool direct); }; }//namespace #endif ugene-1.9.8/src/corelibs/U2Core/src/selection/DocumentSelection.h0000644000175000017500000000375211651544332023366 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_DOCUMENT_SELECTION_H_ #define _U2_DOCUMENT_SELECTION_H_ #include "SelectionTypes.h" #include namespace U2 { class Document; class U2CORE_EXPORT DocumentSelection : public GSelection { Q_OBJECT public: DocumentSelection(QObject* p = NULL) : GSelection(GSelectionTypes::DOCUMENTS, p) {} const QList& getSelectedDocuments() const {return selectedDocs;} virtual bool isEmpty() const {return selectedDocs.isEmpty();} virtual void clear(); void setSelection(const QList& docs); void addToSelection(const QList& docs); void removeFromSelection(const QList& docs); bool contains(Document* doc) const {return selectedDocs.contains(doc);} signals: void si_selectionChanged(DocumentSelection* thiz, const QList& docsAdded, const QList& docsRemoved); private: QList selectedDocs; }; /* class ProjectDocumentSelection : public DocumentSelection { Q_OBJECT public: ProjectDocumentSelection(QObject* parent = NULL); private slots: void sl_onDocumentRemoved(Document*); }; */ }//namespace #endif ugene-1.9.8/src/corelibs/U2Core/src/selection/SelectionModel.cpp0000644000175000017500000000257011651544332023200 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "SelectionModel.h" namespace U2 { void MultiGSelection::addSelection(const GSelection* s) { assert(!selections.contains(s)); selections.push_back(s); } void MultiGSelection::removeSelection(const GSelection* s) { assert(selections.contains(s)); selections.removeAll(s); } const GSelection* MultiGSelection::findSelectionByType(GSelectionType t) const { foreach(const GSelection* s, selections) { if (s->getSelectionType() == t) { return s; } } return NULL; } }//namespace ugene-1.9.8/src/corelibs/U2Core/src/selection/LRegionsSelection.cpp0000644000175000017500000000363011651544332023660 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "LRegionsSelection.h" namespace U2 { static QVector emptyLRegions; void LRegionsSelection::clear() { QVector tmpRemoved = regions; regions.clear(); if (!tmpRemoved.isEmpty()) { emit si_selectionChanged(this, emptyLRegions, tmpRemoved); } } void LRegionsSelection::addRegion(const U2Region& r) { assert(r.length > 0); if (regions.contains(r)) { return; } regions.append(r); QVector tmpAdded; tmpAdded.append(r); emit si_selectionChanged(this, tmpAdded, emptyLRegions); } void LRegionsSelection::removeRegion(const U2Region& r) { int idx = regions.indexOf(r); if (idx == -1) { return; } regions.remove(idx); QVector tmpRemoved; tmpRemoved.append(r); emit si_selectionChanged(this, emptyLRegions, tmpRemoved); } void LRegionsSelection::setSelectedRegions(const QVector& newSelection) { QVector tmpRemoved = regions; regions = newSelection; emit si_selectionChanged(this, newSelection, tmpRemoved); } } //namespace ugene-1.9.8/src/corelibs/U2Core/src/selection/TextSelection.h0000644000175000017500000000234511651544332022531 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_TEXT_SELECTION_H_ #define _U2_TEXT_SELECTION_H_ #include "LRegionsSelection.h" #include "SelectionTypes.h" namespace U2 { class TextObject; class U2CORE_EXPORT TextSelection : public LRegionsSelection { public: TextSelection(TextObject* _obj, QObject* p = NULL) : LRegionsSelection(GSelectionTypes::TEXT, p), obj(_obj) {} private: TextObject* obj; }; }//namespace #endif ugene-1.9.8/src/corelibs/U2Core/src/util_algorithm/0000755000175000017500000000000011651544332020620 5ustar ilyailyaugene-1.9.8/src/corelibs/U2Core/src/util_algorithm/U2AttributeUtils.cpp0000644000175000017500000000662111651544332024524 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include #include #include namespace U2 { qint64 U2AttributeUtils::findIntegerAttribute(U2AttributeDbi* adbi, const U2DataId& objectId, const QString& name, qint64 defaultVal, U2OpStatus& os) { QList attributeIds = adbi->getObjectAttributes(objectId, name, os); if (attributeIds.isEmpty() || os.hasError()) { return defaultVal; } U2Dbi* dbi = adbi->getRootDbi(); foreach(const U2DataId& id, attributeIds) { if (dbi->getEntityTypeById(id) == U2Type::AttributeInteger) { U2IntegerAttribute ia = adbi->getIntegerAttribute(id, os); return ia.value; } } return defaultVal; } double U2AttributeUtils::findRealAttribute(U2AttributeDbi* adbi, const U2DataId& objectId, const QString& name, double defaultVal, U2OpStatus& os) { QList attributeIds = adbi->getObjectAttributes(objectId, name, os); if (attributeIds.isEmpty() || os.hasError()) { return defaultVal; } U2Dbi* dbi = adbi->getRootDbi(); foreach(const U2DataId& id, attributeIds) { if (dbi->getEntityTypeById(id) == U2Type::AttributeReal) { U2RealAttribute ra = adbi->getRealAttribute(id, os); return ra.value; } } return defaultVal; } QByteArray U2AttributeUtils::findByteArrayAttribute(U2AttributeDbi* adbi, const U2DataId& objectId, const QString& name, const QByteArray& defaultVal, U2OpStatus& os) { QList attributeIds = adbi->getObjectAttributes(objectId, name, os); if (attributeIds.isEmpty() || os.hasError()) { return defaultVal; } U2Dbi* dbi = adbi->getRootDbi(); foreach(const U2DataId& id, attributeIds) { if (dbi->getEntityTypeById(id) == U2Type::AttributeByteArray) { U2ByteArrayAttribute aa = adbi->getByteArrayAttribute(id, os); return aa.value; } } return defaultVal; } QString U2AttributeUtils::findStringAttribute(U2AttributeDbi* adbi, const U2DataId& objectId, const QString& name, const QString& defaultVal, U2OpStatus& os) { QList attributeIds = adbi->getObjectAttributes(objectId, name, os); if (attributeIds.isEmpty() || os.hasError()) { return defaultVal; } U2Dbi* dbi = adbi->getRootDbi(); foreach(const U2DataId& id, attributeIds) { if (dbi->getEntityTypeById(id) == U2Type::AttributeInteger) { U2StringAttribute sa = adbi->getStringAttribute(id, os); return sa.value; } } return defaultVal; } } //namespace ugene-1.9.8/src/corelibs/U2Core/src/util_algorithm/SequenceUtils.cpp0000644000175000017500000001745211651544332024126 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "SequenceUtils.h" #include #include #include #include #include #include namespace U2 { QList SequenceUtils::extractRegions(const QByteArray& seq, const QVector& regions, DNATranslation* complTT) { QVector safeLocation = regions; U2Region::bound(0, seq.length(), safeLocation); QList resParts; for (int i = 0, n = safeLocation.size(); i < n; i++) { const U2Region& oReg = safeLocation.at(i); if (complTT == NULL) { resParts.append(seq.mid(oReg.startPos, oReg.length)); } else { QByteArray arr = seq.mid(oReg.startPos, oReg.length); TextUtils::reverse(arr.data(), arr.length()); complTT->translate(arr.data(), arr.length()); resParts.prepend(arr); } } return resParts; } QByteArray SequenceUtils::joinRegions(const QList& parts) { if (parts.size() == 1) { return parts.first(); } QByteArray res; foreach(const QByteArray& p, parts) { res.append(p); } return res; } QList SequenceUtils::translateRegions(const QList& origParts, DNATranslation* aminoTT, bool join) { QList resParts; assert(aminoTT != NULL); if (join) { resParts.append(SequenceUtils::joinRegions(origParts)); } else { resParts.append(origParts); } for (int i = 0, n = resParts.length(); i < n; i++) { const QByteArray& d = resParts[i]; int translatedLen = d.size() / 3; QByteArray translated(translatedLen, '?'); aminoTT->translate(d.constData(), d.length(), translated.data(), translatedLen); resParts[i] = translated; } return resParts; } QList SequenceUtils::extractSequence(const QByteArray& seq, const QVector& origLocation, DNATranslation* complTT, DNATranslation* aminoTT, bool join, bool circular) { QList resParts = extractRegions(seq, origLocation, complTT); if (circular && resParts.size() > 1) { const U2Region& firstL = origLocation.first(); const U2Region& lastL = origLocation.last(); if (firstL.startPos == 0 && lastL.endPos() == seq.length()) { QByteArray lastS = resParts.last(); QByteArray firstS = resParts.first(); resParts.removeLast(); resParts[0] = lastS.append(firstS); } } if (aminoTT != NULL) { resParts = translateRegions(resParts, aminoTT, join); } else if (join) { QByteArray joined = joinRegions(resParts); resParts.clear(); resParts.append(joined); } return resParts; } QVector SequenceUtils::toJoinedRegions(const QList& seqParts) { QVector res; int prevEnd = 0; foreach(const QByteArray& seq, seqParts) { res.append(U2Region(prevEnd, seq.size())); prevEnd += seq.size(); } return res; } Document* SequenceUtils::mergeSequences(const Document* doc, int mergeGap, U2OpStatus& os) { // prepare annotation object -> sequence object mapping first // and precompute resulted sequence size and alphabet int mergedSize = 0; QHash< QString, QList > annotationsBySequenceObjectName; QList seqObjects; QString docUrl = doc->getURLString(); DNAAlphabet* al = NULL; foreach(GObject* obj, doc->getObjects()) { AnnotationTableObject* annObj = qobject_cast(obj); if (annObj == NULL) { DNASequenceObject* seqObj = qobject_cast(obj); if (seqObj != NULL) { seqObjects << seqObj; mergedSize += mergedSize == 0 ? 0 : mergeGap; mergedSize += seqObj->getSequenceLen(); DNAAlphabet* seqAl = seqObj->getAlphabet(); al = (al == NULL) ? seqAl : DNAAlphabet::deriveCommonAlphabet(al, seqAl); if (al == NULL) { os.setError(tr("Failed to derive common alphabet!")); break; } } continue; } QList seqRelations = annObj->findRelatedObjectsByRole(GObjectRelationRole::SEQUENCE); foreach(const GObjectRelation& rel, seqRelations) { const QString& relDocUrl = rel.getDocURL(); if (relDocUrl == docUrl) { QList& annObjs = annotationsBySequenceObjectName[rel.ref.objName]; if (!annObjs.contains(annObj)) { annObjs << annObj; } } } } if (os.hasError()) { return NULL; } if (seqObjects.isEmpty()) { return NULL; } if (mergedSize > 1000*1000*1000) { //2Gb (max qbytearray size) / 2 os.setError(tr("Not enough memory to complete operation!")); return NULL; } DNASequence seq(doc->getURL().fileName(), QByteArray(), al); seq.seq.reserve(mergedSize); //TODO: check if memory op succeed!!! AnnotationTableObject* annObj = new AnnotationTableObject(seq.getName() + " annotations"); QByteArray delim(mergeGap, al->getDefaultSymbol()); foreach(DNASequenceObject* seqObj, seqObjects) { if (!seq.seq.isEmpty()) { seq.seq.append(delim); } U2Region contigReg(seq.seq.length(), seqObj->getSequenceLen()); seq.seq.append(seqObj->getSequence()); SharedAnnotationData ad(new AnnotationData()); ad->name = "contig"; ad->location->regions << contigReg; annObj->addAnnotation(new Annotation(ad)); // now convert all annotations; QList annObjects = annotationsBySequenceObjectName.value(seqObj->getGObjectName()); foreach(AnnotationTableObject* annObj, annObjects) { foreach(Annotation* a, annObj->getAnnotations()) { Annotation* newAnnotation = new Annotation(a->data()); U2Location newLocation = newAnnotation->getLocation(); U2Region::shift(contigReg.startPos, newLocation->regions); newAnnotation->setLocation(newLocation); QStringList groupNames; foreach(AnnotationGroup* g, a->getGroups()) { groupNames << g->getGroupName(); } annObj->addAnnotation(newAnnotation, groupNames); } } } DNASequenceObject* seqObj = new DNASequenceObject(seq.getName(), seq); QList objects; objects << seqObj << annObj; QVariantMap hints; Document* resultDoc = new Document(doc->getDocumentFormat(), doc->getIOAdapterFactory(), doc->getURL(), objects, hints, tr("File content was merged")); doc->propagateModLocks(resultDoc); return resultDoc; } }//namespace ugene-1.9.8/src/corelibs/U2Core/src/util_algorithm/U2AssemblyUtils.cpp0000644000175000017500000001002011651544332024324 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include #include #include #include namespace U2 { U2CigarOp U2AssemblyUtils::char2Cigar(char c, QString& err) { char cu = TextUtils::UPPER_CASE_MAP[c]; switch (cu) { case 'D': return U2CigarOp_D; // deleted case 'I': return U2CigarOp_I; // inserted case 'H': return U2CigarOp_H; // hard-clipped case 'M': return U2CigarOp_M; // matched case 'N': return U2CigarOp_N; // skipped case 'P': return U2CigarOp_P; // padded case 'S': return U2CigarOp_S; // soft-clipped case '=': return U2CigarOp_EQ; // sequence match case 'X': return U2CigarOp_X; // sequence mismatch } err = tr("Invalid CIGAR op: '%1'!").arg(c); return U2CigarOp_Invalid; } char U2AssemblyUtils::cigar2Char(U2CigarOp op) { char c; switch(op) { case U2CigarOp_D: c = 'D'; break; case U2CigarOp_I: c = 'I'; break; case U2CigarOp_H: c = 'H'; break; case U2CigarOp_M: c = 'M'; break; case U2CigarOp_N: c = 'N'; break; case U2CigarOp_P: c = 'P'; break; case U2CigarOp_S: c = 'S'; break; case U2CigarOp_EQ:c = '='; break; case U2CigarOp_X: c = 'X'; break; default: assert(0); c = '?'; } return c; } QList U2AssemblyUtils::parseCigar(const QByteArray& cigarString, QString& err) { QList result; int pos = 0, len = cigarString.length(); const char* cigar = cigarString.constData(); int count = 0; // count numbers while (pos < len ) { char c = cigar[pos++]; if (c >= '0' && c <= '9') { int n = c - '0'; count = count * 10 + n; continue; } U2CigarOp op = char2Cigar(c, err); if (!err.isEmpty()) { break; } result.append(U2CigarToken(op, count)); count = 0; } return result; } QByteArray U2AssemblyUtils::cigar2String(const QList& cigar) { QByteArray res; foreach(const U2CigarToken& t, cigar) { if (t.op != U2CigarOp_Invalid) { res = res + QByteArray::number(t.count) + cigar2Char(t.op); } } return res; } qint64 U2AssemblyUtils::getEffectiveReadLength(const U2AssemblyRead& read) { return read->readSequence.length() + getCigarExtraLength(read->cigar); } qint64 U2AssemblyUtils::getCigarExtraLength(const QList& cigar) { qint64 res = 0; foreach(const U2CigarToken& t, cigar) { switch(t.op) { case U2CigarOp_I: case U2CigarOp_S: res-=t.count; break; case U2CigarOp_D: case U2CigarOp_N: res+=t.count; break; default:; } } return res; } static QByteArray prepareCigarChars() { return QByteArray("0123456789DIHMNPS=X"); } QByteArray U2AssemblyUtils::getCigarAlphabetChars() { static QByteArray res = prepareCigarChars(); return res; } } //namespace ugene-1.9.8/src/corelibs/U2Core/src/util_algorithm/MSAUtils.cpp0000644000175000017500000001032511651544332022766 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "MSAUtils.h" #include #include #include #include #include #include namespace U2 { bool MSAUtils::equalsIgnoreGaps(const MAlignmentRow& row, int startPos, const QByteArray& pat) { int sLen = row.getCoreEnd(); int pLen = pat.size(); for (int i = startPos, j = 0; i < sLen && j < pLen; i++, j++) { char c1 = row.chatAt(i); char c2 = pat[j]; while(c1 == MAlignment_GapChar && ++i < sLen) { c1 = row.chatAt(i); } if (c1 != c2) { return false; } } return true; } MAlignment MSAUtils::seq2ma( const QList& list, U2OpStatus& os) { MAlignment ma(MA_OBJECT_NAME); foreach(GObject* obj, list) { DNASequenceObject* dnaObj = qobject_cast(obj); if (dnaObj == NULL) { continue; } const DNASequence& seq = dnaObj->getDNASequence(); DNAAlphabet* al = ma.getAlphabet(); if (al == NULL) { al = dnaObj->getAlphabet(); } else { al = DNAAlphabet::deriveCommonAlphabet(al, dnaObj->getAlphabet()); if (al == NULL) { if(ma.getAlphabet()->getType() == DNAAlphabet_AMINO && dnaObj->getAlphabet()->getType() == DNAAlphabet_NUCL ) { al = ma.getAlphabet(); } else if(ma.getAlphabet()->getId() == "NUCL_DNA_EXTENDED_ALPHABET") { al = dnaObj->getAlphabet(); } else { os.setError(tr("Sequences have different alphabets.")); break; } } } ma.setAlphabet(al); //TODO: handle memory overflow MAlignmentRow row(dnaObj->getGObjectName(), seq.seq, 0); ma.addRow(row); } if (os.hasError()) { ma.clear(); } return ma; } QList MSAUtils::ma2seq(const MAlignment& ma, bool trimGaps) { QList lst; QBitArray gapCharMap = TextUtils::createBitMap(MAlignment_GapChar); int len = ma.getLength(); DNAAlphabet* al = ma.getAlphabet(); foreach(const MAlignmentRow& row, ma.getRows()) { DNASequence s(row.getName(), row.toByteArray(len), al); if (trimGaps) { int newLen = TextUtils::remove(s.seq.data(), s.length(), gapCharMap); s.seq.resize(newLen); } lst << s; } return lst; } bool MSAUtils::checkPackedModelSymmetry(MAlignment& ali, TaskStateInfo& ti) { if (ali.getLength() == 0) { ti.setError(tr("Alignment is empty!")); return false; } int coreLen = ali.getRow(0).getCoreEnd(); if (coreLen == 0) { ti.setError(tr("Alignment is empty!")); return false; } for (int i=0, n = ali.getNumRows(); i < n; i++) { const MAlignmentRow& row = ali.getRow(i); if (row.getCoreLength() != coreLen) { ti.setError(tr("Sequences in alignment have different sizes!")); return false; } } return true; } int MSAUtils::getRowIndexByName( const MAlignment& ma, const QString& name ) { int idx = 0; foreach(const MAlignmentRow& row, ma.getRows()) { if (row.getName() == name) { return idx; } ++idx; } return -1; } }//namespace ugene-1.9.8/src/corelibs/U2Core/src/util_algorithm/U2AnnotationUtils.cpp0000644000175000017500000002273211651544332024674 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include namespace U2 { QVector U2AnnotationUtils::fixLocationsForRemovedRegion( const U2Region& regionToDelete, QVector& regionList, AnnotationStrategyForResize s ) { //assert (s == AnnotationStrategyForResize_Remove || s == AnnotationStrategyForResize_Resize); QVector toDelete, toReplace; foreach(U2Region reg, regionList){ toDelete.append(reg); if (s != AnnotationStrategyForResize_Remove){ if(reg.contains(regionToDelete)){ reg.length -= regionToDelete.length; }else if (regionToDelete.contains(reg)) { reg.length = 0; }else if(reg.intersects(regionToDelete)){ if(reg.startPos <= regionToDelete.startPos){ reg.length -= reg.endPos() - regionToDelete.startPos; }else{ reg.length -= regionToDelete.endPos() - reg.startPos; reg.startPos = regionToDelete.startPos; } }else if(reg.startPos >= regionToDelete.endPos()){ reg.startPos -= regionToDelete.length; } } else { if(reg.intersects(regionToDelete) || regionToDelete.contains(reg)){ reg.length = 0; }else if(reg.startPos >= regionToDelete.endPos()){ reg.startPos -= regionToDelete.length; } } if (reg.length != 0) { toDelete.pop_back(); toReplace.append(reg); } } regionList.clear(); regionList << toReplace; return toDelete; } QVector U2AnnotationUtils::fixLocationsForInsertedRegion( qint64 insertPos, qint64 len, QVector& regionList, AnnotationStrategyForResize s ) { QVector toReplace, toDelete; foreach(U2Region reg, regionList){ if(reg.endPos() <= insertPos){ toReplace.append(reg); } else { if (s == AnnotationStrategyForResize_Resize){ if(reg.startPos < insertPos && reg.endPos() > insertPos){ reg.length += len; toReplace.append(reg); }else if(reg.startPos >= insertPos){ reg.startPos += len; toReplace.append(reg); } }else if(s == AnnotationStrategyForResize_Split){ if(reg.startPos < insertPos && reg.endPos() > insertPos){ U2Region firstPart, secondPart; firstPart.startPos = reg.startPos; firstPart.length = insertPos - reg.startPos; secondPart.startPos = firstPart.endPos() + len; secondPart.length = reg.length - firstPart.length; toReplace.append(firstPart); toReplace.append(secondPart); }else if(reg.startPos >= insertPos){ reg.startPos += len; toReplace.append(reg); } }else if(s == AnnotationStrategyForResize_Remove){ if(reg.startPos < insertPos && reg.endPos() > insertPos){ toDelete.append(reg); }else if(reg.startPos >= insertPos){ reg.startPos += len; toReplace.append(reg); } } } } regionList.clear(); regionList << toReplace; return toDelete; } QVector U2AnnotationUtils::fixLocationsForReplacedRegion( const U2Region& regionToReplace, qint64 newLen, QVector& loc, AnnotationStrategyForResize s ) { if (s == AnnotationStrategyForResize_Remove) { QVector l1 = fixLocationsForRemovedRegion(regionToReplace, loc, s); QVector l2 = fixLocationsForInsertedRegion(regionToReplace.startPos, newLen, loc, s); assert(l2.isEmpty()); Q_UNUSED(l2); return l1; } else { int offset = newLen - regionToReplace.length; if (s == AnnotationStrategyForResize_Resize && offset == 0) { return QVector(); } assert(s == AnnotationStrategyForResize_Resize); // FIXME do we ever need to SPLIT when replacing ??? QVector toReplace, toDelete; foreach(U2Region reg, loc){ if(reg.endPos() <= regionToReplace.startPos){ toReplace.append(reg); } else { if (reg.contains(regionToReplace)) { reg.length += offset; } else if (reg.startPos >= regionToReplace.endPos()) { reg.startPos += offset; } else { // start pos and/or end pos lie inside the regionToReplace // let's assume offset is applied at the region end if (offset > 0) { if (reg.endPos() <= regionToReplace.endPos()) { // leave it as is } else { // append tail reg.length += offset; } } else { if (reg.endPos() <= regionToReplace.endPos() + offset) { // leave it as is } else if (reg.startPos < regionToReplace.endPos() + offset && reg.endPos() >= regionToReplace.endPos()) { // crop inner subregion reg.length += offset; } else if (reg.startPos >= regionToReplace.endPos() + offset && reg.endPos() <= regionToReplace.endPos()) { // drop the region reg.length = 0; } else if (reg.startPos < regionToReplace.endPos() + offset) { // crop tail assert(reg.endPos() < regionToReplace.endPos() && reg.endPos() > regionToReplace.endPos() + offset); reg.length -= reg.endPos() - regionToReplace.startPos; } else { // crop head assert(reg.startPos >= regionToReplace.endPos() + offset && reg.startPos < regionToReplace.endPos()); assert(reg.endPos() > regionToReplace.endPos()); reg.length = reg.endPos() - regionToReplace.endPos(); reg.startPos = regionToReplace.endPos() + offset; } } } assert(reg.length >= 0); if (reg.length == 0) { toDelete.append(reg); } else { toReplace.append(reg); } } } loc.clear(); loc << toReplace; return toDelete; } } int U2AnnotationUtils::getRegionFrame(int sequenceLen, U2Strand strand, bool order, int region, const QVector& location) { int frame = 0; const U2Region& r = location.at(region); if (strand.isCompementary()) { frame = (sequenceLen - r.endPos()) % 3; } else { frame = r.startPos % 3; } if (!order){ //join -> need to join region with prev regions to derive frame if (strand.isCompementary()) { int offset = 0; for (int i = location.size(); --i > region;) { const U2Region& rb = location.at(i); offset += rb.length; } int dFrame = offset % 3; frame = (frame + (3 - dFrame)) % 3; } else { int offset = 0; for (int i = 0; i < region; i++) { const U2Region& rb = location.at(i); offset += rb.length; } int dFrame = offset % 3; frame = (frame + (3 - dFrame)) % 3; } } return frame; } bool U2AnnotationUtils::isSplitted( const U2Location& location, const U2Region& seqRange ) { QVector regions = location->regions; if (regions.size() != 2) { return false; } if ( regions[0].endPos() == seqRange.endPos() && regions[1].startPos == seqRange.startPos) { return true; } return false; } } //namespace ugene-1.9.8/src/corelibs/U2Core/src/util_algorithm/U2Bits.cpp0000644000175000017500000002153711651544332022444 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include #include namespace U2 { //static int getLenBits(int len) { // return len == 0 ? 3 : len < 0XFF ? 0 : len < 0xFFFF ? 1 : 2; //} static int getLenBitsSize(int len) { return len == 0 ? 0 : len < 0XFF ? 8 : len < 0xFFFF ? 16 : 32; } static void writeLength(uchar* bits, int len, int lenBitsLen) { if (lenBitsLen == 8) { // 00 U2Bits::writeInt8(bits, 2, (qint8)len); } else if (lenBitsLen == 16) { // 01 U2Bits::setBit(bits, 0); U2Bits::writeInt16(bits, 2, (qint16)len); } else if (lenBitsLen == 32) { // 10 U2Bits::setBit(bits, 1); U2Bits::writeInt16(bits, 2, (qint32)len); } else { U2Bits::setBit(bits, 0); // empty length => both bits set: 11 U2Bits::setBit(bits, 1); } } static int readLength(const uchar* bits, int& nBits) { bool b0 = U2Bits::getBit(bits, 0); bool b1 = U2Bits::getBit(bits, 1); if (b0 == b1) { if (!b0) { nBits = 8; return U2Bits::readInt8(bits, 2); } nBits = 0; return 0; } else if (b0) { nBits = 16; return U2Bits::readInt16(bits, 2); } else { nBits = 32; return U2Bits::readInt32(bits, 2); } } QByteArray U2BitCompression::compress(const char* text, int len, int alphabetSize, const int* alphabetCharNums, U2OpStatus& os) { // algorithm: // 1. compute chars freq -> derive number of bits per char // 2. assign bit masks per char. Do not assign any bit masks for non used alphabet chars // 3. compress chars // 4. create header with used char mask // Result bits [len type][len][used alpha bits][compressed text] // where [len type] is a type of length field: 00 -> empty, 01 -> 8 byte, 10 -> 16 bytes, 11 -> 32 bytes // [len] - length of the result sequence // [used alpha bits] bit is set if alpha char is used in the text. // [compressed text] the data in compressed form assert(alphabetSize <= 32); //avoid this check in runtime -> use this method correctly // find all used chars in text QVector visitVector(alphabetSize, false); bool* visited = visitVector.data(); for (int i = 0; i < len; i++) { uchar c = text[i]; int n = alphabetCharNums[c]; if (n == -1) { os.setError(tr("Bit compression: illegal character in text '%1'").arg(char(c))); return QByteArray(); } if (!visited[n]) { visited[n] = true; } } // assign sequential bit-mask for all used chars QVector maskVector(alphabetSize, 0); uchar* mask = maskVector.data(); uchar m = 0; for (int i = 0; i < alphabetSize; i++) { if (visited[i]) { mask[i] = m; m++; } } // store header and data to bit set int bitsPerChar = U2Bits::getNumberOfBitsPerChar(m); int compressedBitSize = len * bitsPerChar; int lenBits = getLenBitsSize(len); int headerSizeBits = 2 + lenBits + alphabetSize; int resultSizeBits = headerSizeBits + compressedBitSize; static QByteArray res; QByteArray bitSet = U2Bits::allocateBits(resultSizeBits); uchar* bits = (uchar*)bitSet.data(); writeLength(bits, len, lenBits); int pos = 2 + lenBits; for (; pos < alphabetSize; pos++) { if (visited[pos]) { U2Bits::setBit(bits, pos); } } for (int i = 0; i < len; i++, pos+=bitsPerChar) { uchar c = text[i]; int n = alphabetCharNums[c]; uchar m = mask[n]; U2Bits::setBits(bits, pos, &m, bitsPerChar); } return bitSet; } QByteArray U2BitCompression::uncompress(const char* data, const QByteArray& alphabetChars, U2OpStatus&) { // algorithm // 1. Derive all chars from header // 2. Assign bit masks per chars that have signed bit in header // 3. Unpack value int alphabetSize = alphabetChars.size(); const char* aChars = alphabetChars.data(); const uchar* bits = (const uchar*)data; int alphaMaskOffset = 0; int len = readLength(bits, alphaMaskOffset); // restore bit masks QVector visitVector(alphabetSize, false); bool* visited = visitVector.data(); int nChars = 0; for (int i = 0; i < alphabetSize; i++) { if (U2Bits::getBit(bits, i + alphaMaskOffset)) { visited[i] = true; nChars++; } } int bitsPerChar = U2Bits::getNumberOfBitsPerChar(nChars); QVector mask2Char(nChars, 0); uchar m = 0; for (int i = 0; i < alphabetSize; i++) { if (visited[i]) { mask2Char[m] = aChars[i]; m++; } } int pos = alphaMaskOffset + alphabetSize; #if QT_VERSION >= QT_VERSION_CHECK(4, 7, 0) QByteArray result(len, Qt::Uninitialized); #else QByteArray result(len, (char)0); #endif char* res = result.data(); for (int i = 0; i < len; i++, pos += bitsPerChar) { int m = U2Bits::bitsRange2Int32(bits, pos, bitsPerChar); char c = mask2Char[m]; assert(c != 0); res[i] = c; } return result; } QVector U2BitCompression::prepareCharNumsMask(const QByteArray& alphabetChars) { QVector res(256, -1); for (int i = 0, n = alphabetChars.size(); i < n; i++) { uchar a = (uchar)alphabetChars[i]; res[a] = i; } return res; } #define K_FACTOR 1.5 /** Compression is eligible if compressed text < original text length with a compression factor of K */ //static bool isCompressionNeeded(int textLen, int alphabetSize) { // int nBits = alphabetSize + U2Bits::getNumberOfBitsPerChar(alphabetSize) * textLen; // int compressedBytes = U2Bits::getNumberOfBytes(nBits); // return compressedBytes * K_FACTOR < textLen; //} ////////////////////////////////////////////////////////////////////////// // bits helper int U2Bits::getNumberOfBitsPerChar(int nChars) { int bitsPerChar = nChars <= 2 ? 1 : (nChars <= 4) ? 2 : (nChars <= 8) ? 3 : (nChars <= 16) ? 4 : 5; return bitsPerChar; } QByteArray U2Bits::allocateBits(int nBits) { int nBytes = getNumberOfBytes(nBits); #if QT_VERSION >= QT_VERSION_CHECK(4, 7, 0) return QByteArray(nBytes, Qt::Uninitialized); #else return QByteArray(nBytes, char(0)); #endif } void U2Bits::setBits(uchar* dstBits, int pos, const uchar* srcBits, int nBits) { // TODO: optimize for (int i = 0; i < nBits; i++) { bool val = getBit(srcBits, i); setBit(dstBits, i + pos, val); } } int U2Bits::bitsRange2Int32(const uchar* bits, int pos, int len) { //TODO: optimize assert(len <= 32); int res = 0; for (int i = 0; i < len; i++) { bool b = getBit(bits, pos + i); if (b) { res = res | (1 << i); } } return res; } qint8 U2Bits::readInt8(const uchar* bits, int pos) { int res = 0; for (int i = 0; i < 8; i++) { res = res << 1; if (U2Bits::getBit(bits, pos + i)) { res += 1; } } return qint8(res); } void U2Bits::writeInt8(uchar* bits, int pos, qint8 val) { const uchar* data = (const uchar*)&val; for (int i = 0; i < 8; i++) { if (U2Bits::getBit(data, i)) { U2Bits::setBit(bits, pos + i); } else { U2Bits::clearBit(bits, pos + i); } } } qint8 U2Bits::readInt16(const uchar* bits, int pos) { int res = (readInt8(bits, pos) << 8) + readInt8(bits, pos + 8); return qint16(res); } void U2Bits::writeInt16(uchar* bits, int pos, qint16 val) { writeInt8(bits, pos + 8, qint8(val)); writeInt8(bits, pos , qint8(val >> 8)); } qint8 U2Bits::readInt32(const uchar* bits, int pos) { int res = (readInt8(bits, pos) << 24) + (readInt8(bits, pos + 8) << 16) + (readInt8(bits, pos + 16) << 8) + readInt8(bits, pos + 24); return qint16(res); } void U2Bits::writeInt32(uchar* bits, int pos, qint32 val) { writeInt8(bits, pos + 24, qint8(val)); writeInt8(bits, pos + 16, qint8(val >> 8)); writeInt8(bits, pos + 8, qint8(val >> 16)); writeInt8(bits, pos, qint8(val >> 24)); } } //namespace ugene-1.9.8/src/corelibs/U2Core/src/util_algorithm/QVariantUtils.cpp0000644000175000017500000000156111651544332024075 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "QVariantUtils.h" ugene-1.9.8/src/corelibs/U2Core/src/util_algorithm/SequenceUtils.h0000644000175000017500000000446711651544332023575 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_SEQUENCE_UTILS_H_ #define _U2_SEQUENCE_UTILS_H_ #include #include #include namespace U2 { class DNATranslation; class U2OpStatus; class Document; class U2CORE_EXPORT SequenceUtils : public QObject { Q_OBJECT public: /** Extracts sequences regions If 'complTT' != NULL - reverse & complements regions. (Note: the order of complemented regions is also reversed) */ static QList extractRegions(const QByteArray& seq, const QVector& regions, DNATranslation* complTT); /** Joins sequence parts into a single sequence */ static QByteArray joinRegions(const QList& parts); /** Translates sequence parts, if join == true -> joins parts before translation is started */ static QList translateRegions(const QList& origParts, DNATranslation* aminoTT, bool join); /** Extract sequence parts marked by the regions*/ static QList extractSequence(const QByteArray& seq, const QVector& regions, DNATranslation* complTT, DNATranslation* aminoTT, bool join, bool circular); /** Returns regions locations as if they were joined */ static QVector toJoinedRegions(const QList& seqParts); static Document* mergeSequences(const Document* doc, int mergeGap, U2OpStatus& os); }; }//namespace #endif ugene-1.9.8/src/corelibs/U2Core/src/util_algorithm/MSAUtils.h0000644000175000017500000000327711651544332022443 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_MSA_UTILS_H_ #define _U2_MSA_UTILS_H_ #include #include namespace U2 { class GObject; class MAlignment; class MAlignmentRow; class TaskStateInfo; class U2OpStatus; class U2CORE_EXPORT MSAUtils : public QObject { Q_OBJECT public: static bool equalsIgnoreGaps(const MAlignmentRow& row, int startPos, const QByteArray& pattern); static MAlignment seq2ma(const QList& dnas, U2OpStatus& os); static QList ma2seq(const MAlignment& ma, bool trimGaps); // Returns row index or -1 if name is not present static int getRowIndexByName(const MAlignment& ma, const QString& name); //checks that alignment is not empty and all packed sequence parts has equal length static bool checkPackedModelSymmetry(MAlignment& ali, TaskStateInfo& ti); }; }//namespace #endif ugene-1.9.8/src/corelibs/U2Core/src/util_algorithm/QVariantUtils.h0000644000175000017500000000552711651544332023550 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_QVARUTILS_H_ #define _U2_QVARUTILS_H_ #include #include #include #include #include #include #include namespace U2 { class U2CORE_EXPORT QVariantUtils { public: static QVariant String2Var(const QString& string) { QDataStream s(QByteArray::fromBase64(string.toAscii())); return QVariant(s); } static QVariantMap string2Map(const QString& string, bool emptyMapIfError) { QDataStream s(QByteArray::fromBase64(string.toAscii())); QVariant res(QVariant::Map); s >> res; if (res.type() == QVariant::Map) { return res.toMap(); } assert(emptyMapIfError); Q_UNUSED(emptyMapIfError); return QVariantMap(); } static QString var2String(const QVariant& v) { QByteArray a; QDataStream s(&a, QIODevice::WriteOnly); s << v; QString res(a.toBase64()); return res; } static QString map2String(const QVariantMap& map) { return var2String(QVariant(map)); } static QList var2ftl(const QVariantList& lst) { QList atl; foreach(QVariant v, lst) { atl += qVariantValue >(v); } return atl; } static QVariant addStr2List(const QVariant& v, const QString& s) { if (v.canConvert(QVariant::StringList)) { QStringList l = v.toStringList(); return (l << s); } else { assert(v.type() == QVariant::Invalid); } return QVariant(s); } static QVariant addStr2List(const QVariant& v, const QStringList& sl) { if (v.canConvert(QVariant::StringList)) { QStringList l = v.toStringList(); return QVariant(l += sl); } else { assert(v.type() == QVariant::Invalid); } return QVariant(sl); } }; } //namespace #endif ugene-1.9.8/src/corelibs/U2Core/src/io/0000755000175000017500000000000011651544332016204 5ustar ilyailyaugene-1.9.8/src/corelibs/U2Core/src/io/LocalFileAdapter.h0000644000175000017500000000540111651544331021507 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_LOCAL_FILE_ADAPTER_H_ #define _U2_LOCAL_FILE_ADAPTER_H_ #include #include namespace U2 { class U2CORE_EXPORT LocalFileAdapterFactory: public IOAdapterFactory { Q_OBJECT public: LocalFileAdapterFactory(QObject* p = NULL); virtual IOAdapter* createIOAdapter(); virtual IOAdapterId getAdapterId() const {return BaseIOAdapters::LOCAL_FILE;} virtual const QString& getAdapterName() const {return name;} virtual bool isIOModeSupported(IOAdapterMode m) const {Q_UNUSED(m); return true;} //files can be read and be written virtual TriState isResourceAvailable(const GUrl& url) const {return QFileInfo(url.getURLString()).exists() ? TriState_Yes : TriState_No;} protected: QString name; }; class U2CORE_EXPORT GzippedLocalFileAdapterFactory: public LocalFileAdapterFactory { Q_OBJECT public: GzippedLocalFileAdapterFactory(QObject* p = NULL); virtual IOAdapter* createIOAdapter(); virtual IOAdapterId getAdapterId() const {return BaseIOAdapters::GZIPPED_LOCAL_FILE;} }; class U2CORE_EXPORT LocalFileAdapter: public IOAdapter { Q_OBJECT public: LocalFileAdapter(LocalFileAdapterFactory* f, QObject* o = NULL, bool bufferOptimization = false); ~LocalFileAdapter() {if (isOpen()) close();} virtual bool open(const GUrl& url, IOAdapterMode m); virtual bool isOpen() const {return f!=NULL;} virtual void close(); virtual qint64 readBlock(char* data, qint64 maxSize); virtual qint64 writeBlock(const char* data, qint64 size); virtual bool skip(qint64 nBytes); virtual qint64 left() const; virtual int getProgress() const; virtual qint64 bytesRead() const; virtual GUrl getURL() const; private: QFile* f; bool bufferOptimization; QByteArray buffer; char *bufData; qint64 bufLen; qint64 currentPos; static const quint64 BUF_SIZE; }; }//namespace #endif ugene-1.9.8/src/corelibs/U2Core/src/io/VFSAdapter.h0000644000175000017500000000444311651544332020321 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_MEM_BUF_ADAPTER_H_ #define _U2_MEM_BUF_ADAPTER_H_ #include namespace U2 { class U2CORE_EXPORT VFSAdapterFactory: public IOAdapterFactory { Q_OBJECT public: VFSAdapterFactory(QObject* p = NULL); virtual IOAdapter* createIOAdapter(); virtual IOAdapterId getAdapterId() const {return BaseIOAdapters::VFS_FILE;} virtual const QString& getAdapterName() const {return name;} virtual bool isIOModeSupported(IOAdapterMode m) const {Q_UNUSED(m); return true;} //files can be read and be written virtual TriState isResourceAvailable(const GUrl& url) const { assert(url.isVFSFile()); Q_UNUSED(url); return TriState_Yes; } protected: QString name; }; class U2CORE_EXPORT VFSAdapter: public IOAdapter { Q_OBJECT public: VFSAdapter(VFSAdapterFactory* f, QObject* o = NULL); ~VFSAdapter() {if (isOpen()) close();} virtual bool open(const GUrl& url, IOAdapterMode m); virtual bool isOpen() const {return buffer != NULL;} virtual void close(); virtual qint64 readBlock(char* data, qint64 maxSize); virtual qint64 writeBlock(const char* data, qint64 size); virtual bool skip(qint64 nBytes); virtual qint64 left() const; virtual int getProgress() const; virtual qint64 bytesRead() const; virtual GUrl getURL() const {return url;} private: GUrl url; QBuffer* buffer; }; }//namespace #endif // _U2_MEM_BUF_ADAPTER_H_ ugene-1.9.8/src/corelibs/U2Core/src/io/VirtualFileSystem.cpp0000644000175000017500000001213111651544332022341 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "VirtualFileSystem.h" #include #include #include #include #include #include namespace U2 { /******************************************* * VirtualFileSystem *******************************************/ const QString VirtualFileSystem::URL_PREFIX = "VFS"; const QString VirtualFileSystem::URL_NAME_SEPARATOR = "!@#$"; VirtualFileSystem::VirtualFileSystem() { } VirtualFileSystem::VirtualFileSystem( const QString & fsName ) : fileSystemName( fsName ) { } VirtualFileSystem::~VirtualFileSystem() { } bool VirtualFileSystem::createFile( const QString & filename, const QByteArray & data ) { if( files.contains( filename ) ) { return false; } files[filename] = data; return true; } bool VirtualFileSystem::mapFile( const QString & filename, const QString & filePath ) { IOAdapterFactory * iof = AppContext::getIOAdapterRegistry()->getIOAdapterFactoryById( BaseIOAdapters::url2io( filePath ) ); SAFE_POINT(iof != NULL, QString("Failed to find IO adapter factory: %1").arg(filePath), false); std::auto_ptr io( iof->createIOAdapter() ); if( !io->open( filePath, IOAdapterMode_Read ) ) { return false; } QByteArray bytes; while( !io->isEof() ) { QByteArray bytesBlock( READ_BLOCK_SZ, '\0' ); qint64 howMany = io->readBlock( bytesBlock.data(), READ_BLOCK_SZ ); if( -1 == howMany ) { return false; } else if( 0 == howMany) { assert( io->isEof() ); continue; } bytes.append( QByteArray( bytesBlock.data(), howMany ) ); } modifyFile( filename, bytes ); return true; } bool VirtualFileSystem::mapBack( const QString & filename, const QString & filePath ) const { if( !files.contains( filename ) ) { return false; } IOAdapterFactory * iof = AppContext::getIOAdapterRegistry()->getIOAdapterFactoryById( BaseIOAdapters::url2io( filePath ) ); SAFE_POINT(iof != NULL, QString("Failed to find IO adapter factory: %1").arg(filePath), false); std::auto_ptr io( iof->createIOAdapter() ); if( !io->open( filePath, IOAdapterMode_Write ) ) { return false; } io->writeBlock( files[filename] ); return true; } void VirtualFileSystem::modifyFile( const QString & filename, const QByteArray & data ) { files[filename] = data; } QByteArray VirtualFileSystem::removeFile( const QString & filename ) { return files.take( filename ); } void VirtualFileSystem::removeAllFiles() { QStringList keys = files.keys(); foreach( const QString & key, keys ) { removeFile( key ); } } bool VirtualFileSystem::fileExists( const QString & filename ) const { return files.contains( filename ); } QByteArray & VirtualFileSystem::getFileByName( const QString & filename ) { return files[filename]; } QByteArray VirtualFileSystem::getFileByName( const QString & filename ) const { return files.value( filename ); } void VirtualFileSystem::setId( const QString & id ) { fileSystemName = id; } QString VirtualFileSystem::getId() const { return fileSystemName; } QStringList VirtualFileSystem::getAllFilenames() const { return files.keys(); } /******************************************* * VirtualFileSystemRegistry *******************************************/ VirtualFileSystemRegistry::VirtualFileSystemRegistry() { } VirtualFileSystemRegistry::~VirtualFileSystemRegistry() { qDeleteAll( registry.values() ); } bool VirtualFileSystemRegistry::registerFileSystem( VirtualFileSystem * entry ) { SAFE_POINT(entry != NULL, "FS is NULL!", false); QString id = entry->getId(); if( registry.contains( id ) ) { return false; } registry[id] = entry; return true; } VirtualFileSystem * VirtualFileSystemRegistry::unregisterFileSystem( const QString & id ) { return registry.take( id ); } VirtualFileSystem * VirtualFileSystemRegistry::getFileSystemById( const QString & id ) const { return registry[id]; } QList< VirtualFileSystem* > VirtualFileSystemRegistry::getAllFileSystems() const { return registry.values(); } QStringList VirtualFileSystemRegistry::getAllIds() const { return registry.keys(); } } // U2 ugene-1.9.8/src/corelibs/U2Core/src/io/VFSAdapter.cpp0000644000175000017500000000720411651544332020652 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "VFSAdapter.h" #include #include namespace U2 { VFSAdapterFactory::VFSAdapterFactory(QObject* o) : IOAdapterFactory(o) { name = tr("Memory buffer"); } IOAdapter* VFSAdapterFactory::createIOAdapter() { return new VFSAdapter(this); } VFSAdapter::VFSAdapter(VFSAdapterFactory* factory, QObject* o) : IOAdapter(factory, o), url("", GUrl_VFSFile), buffer(NULL) { } bool VFSAdapter::open(const GUrl& _url, IOAdapterMode m) { SAFE_POINT(!isOpen(), "Adapter is already opened!", false); SAFE_POINT(buffer == NULL, "Buffers is not null!", false); // assume that all membuf adapters work with files in some vfs if( !_url.getURLString().startsWith( VirtualFileSystem::URL_PREFIX ) ) { return false; // not a file in vfs } VirtualFileSystemRegistry * vfsReg = AppContext::getVirtualFileSystemRegistry(); SAFE_POINT(vfsReg != NULL, "VirtualFileSystemRegistry not found!", false); QStringList urlArgs = _url.getURLString().mid( VirtualFileSystem::URL_PREFIX.size() ). split( VirtualFileSystem::URL_NAME_SEPARATOR, QString::SkipEmptyParts ); if( 2 != urlArgs.size() ) { // urlArgs - vfsname and filename return false; } VirtualFileSystem * vfs = vfsReg->getFileSystemById( urlArgs[0] ); if( NULL == vfs ) { return false; // no such vfs registered } if( !vfs->fileExists( urlArgs[1] ) ) { if( IOAdapterMode_Read == m ) { return false; } else { vfs->createFile( urlArgs[1], QByteArray() ); } } buffer = new QBuffer( &vfs->getFileByName( urlArgs[1] ) ); QIODevice::OpenMode iomode = m == IOAdapterMode_Read ? QIODevice::ReadOnly : QIODevice::WriteOnly | QIODevice::Truncate; if (!buffer->open(iomode)) { return false; } url = _url; return true; } void VFSAdapter::close() { SAFE_POINT(isOpen(), "Adapter is not opened!",); delete buffer; buffer = NULL; url = GUrl("", GUrl_VFSFile); } qint64 VFSAdapter::readBlock(char* data, qint64 size) { qint64 l = buffer->read(data, size); return l; } qint64 VFSAdapter::writeBlock(const char* data, qint64 size) { qint64 l = buffer->write(data, size); return l; } bool VFSAdapter::skip(qint64 nBytes) { SAFE_POINT(isOpen(), "Adapter is not opened!", false); qint64 p = buffer->pos(); return buffer->seek(p+nBytes); } qint64 VFSAdapter::left() const { SAFE_POINT(isOpen(), "Adapter is not opened!", -1); qint64 p = buffer->pos(); qint64 len = buffer->size(); return len - p; } int VFSAdapter::getProgress() const { SAFE_POINT(isOpen(), "Adapter is not opened!", -1); return int(100 * float(buffer->pos()) / buffer->size()); } qint64 VFSAdapter::bytesRead() const { return buffer->pos(); } };//namespace ugene-1.9.8/src/corelibs/U2Core/src/io/GUrlUtils.h0000644000175000017500000000664311651544331020257 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_GURL_UTILS_H_ #define _U2_GURL_UTILS_H_ #include #include #include #include #include namespace U2 { class TaskStateInfo; class Logger; class U2CORE_EXPORT GUrlUtils : public QObject { Q_OBJECT public: //gets the uncompressed extension for the URL. Filters 'gz' like suffixes static QString getUncompressedExtension(const GUrl& url); // ensures that url ends with one of the exts static GUrl ensureFileExt(const GUrl& url, const QStringList& typeExt); // returns url suitable for backup renaming (increments name for rolling file until non-existing name found) static QString rollFileName(const QString& url, const QString& rolledSuffix, const QSet& excludeList); // same as above but with empty suffix static QString rollFileName(const QString& url, const QSet& excludeList) { return rollFileName(url, "", excludeList);} // renames actual file by rolling its name static bool renameFileWithNameRoll(const QString& url, TaskStateInfo& ti, const QSet& excludeList = QSet(), Logger* log = NULL); // converts GUrl to QUrl static QUrl gUrl2qUrl( const GUrl& gurl); static QList gUrls2qUrls( const QList& gurls); // converts QUrl to GUrl static GUrl qUrl2gUrl( const QUrl& qurl); static QList qUrls2gUrls( const QList& qurls); // adds baseSuffix to the url. Ensures that URL ends with one of the exts from typeExt static QString prepareFileName(const QString& url, const QString& baseSuffix, const QStringList& typeExt); // adds count to the url. Ensures that URL ends with one of the exts from typeExt static QString prepareFileName(const QString& url, int count, const QStringList& typeExt); // checks that file path is valid: creates required directory if needed. // Returns canonical path to file. Does not create nor remove file, affects just directory // Returns empty string and error message if some error occurs // Sample usage: processing URLs in "save file" inputs static QString prepareFileLocation(const QString& filePath, QString& errorMessage); // checks that dir path is valid. Creates the directory if needed. // Returns canonical directory path. Does not affect directory if already exists. // Returns empty string and error message if some error occurs // Sample usage: processing URLs in "save dir" inputs static QString prepareDirLocation(const QString& dirPath, QString& errorMessage); }; } //namespace #endif ugene-1.9.8/src/corelibs/U2Core/src/io/HttpFileAdapter.cpp0000644000175000017500000002075311651544331021736 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "HttpFileAdapter.h" #include "ZlibAdapter.h" #include #include #include #include #include #include #include #include namespace U2 { #define MAX_GET_LENGTH 3000 HttpFileAdapterFactory::HttpFileAdapterFactory(QObject* o) : IOAdapterFactory(o) { name = tr("HTTP file"); } IOAdapter* HttpFileAdapterFactory::createIOAdapter() { return new HttpFileAdapter(this); } GzippedHttpFileAdapterFactory::GzippedHttpFileAdapterFactory( QObject * obj /* = 0 */ ) : HttpFileAdapterFactory( obj ) { name = tr("HTTP GZIP adaptor"); } IOAdapter * GzippedHttpFileAdapterFactory::createIOAdapter() { return new ZlibAdapter( new HttpFileAdapter(this) ); } QNetworkProxy HttpFileAdapterFactory::getProxyByUrl( const QUrl & url ) const { NetworkConfiguration* nc = AppContext::getAppSettings()->getNetworkConfiguration(); return nc->getProxyByUrl(url); } HttpFileAdapter::HttpFileAdapter(HttpFileAdapterFactory* factory, QObject* o) : IOAdapter(factory, o), is_cached(false), begin_ptr(-1), end_ptr(0), http(0), badstate(false), is_downloaded(false), downloaded(0), total(0) { chunk_list.push_back( QByteArray(CHUNKSIZE, char(0)) ); } bool HttpFileAdapter::open(const GUrl& url_, IOAdapterMode m) { SAFE_POINT (m == IOAdapterMode_Read, QString("Illegal IO mode: %1").arg(m), false); QUrl url( url_.getURLString().trimmed() ); if( !url.isValid() ) { return false; } bool https = url.scheme() == "https"; if( !url.scheme().isEmpty() && !https && url.scheme() != "http" ) { return false; } gurl = url_; init(); HttpFileAdapterFactory * f = qobject_cast ( getFactory() ); QNetworkProxy proxy = f->getProxyByUrl(url); return open( url.host(), url.path() + "?" + QString(url.encodedQuery()), proxy, -1 == url.port() ? (https ? 443:80) : url.port(), https ); } bool HttpFileAdapter::open( const QString& host, const QString & what, const QNetworkProxy & p, quint16 port, bool https ) { SAFE_POINT(!isOpen(), "Adapter is already opened!", false); if( http ) { close(); } http = new QHttp( host, https ? QHttp::ConnectionModeHttps : QHttp::ConnectionModeHttp, port ); //printf( "using proxy: %s on port %d\n", p.hostName().toStdString().c_str(), p.port() ); http->setProxy( p ); connect( http, SIGNAL(dataReadProgress(int,int)), this, SLOT(progress(int,int)), Qt::DirectConnection ); // connect( http, SIGNAL(stateChanged(int)), this, SLOT(state(int)), Qt::DirectConnection ); connect( http, SIGNAL(done(bool)), this, SLOT(done(bool)), Qt::DirectConnection ); connect( http, SIGNAL(readyRead(const QHttpResponseHeader&)), this, SLOT(add_data(const QHttpResponseHeader&)), Qt::DirectConnection ); if(what.length()>MAX_GET_LENGTH) { QString path = what.split("?").first(); QByteArray params = what.split("?").last().toAscii(); http->post(path,params); } else { http->get( what ); } return true; } void HttpFileAdapter::close() { SAFE_POINT(isOpen(), "Adapter is not opened!", ); if (!isOpen()) { return; } assert( http ); http->abort(); delete http; http = 0; gurl = GUrl(); init(); } qint64 HttpFileAdapter::readBlock(char* data, qint64 size) { SAFE_POINT(isOpen(), "Adapter is not opened!", 0); if( badstate ) { return -1; } assert( data ); assert( CHUNKSIZE != end_ptr ); size = waitData( size ); if( badstate ) { return -1; } rwmut.lock(); qint64 write_offs = 0; while( write_offs < size ) { int howmuch = qMin( size - write_offs, (qint64)firstChunkContains() ); readFromChunk( data + write_offs, howmuch ); write_offs += howmuch; } rwmut.unlock(); return size; } qint64 HttpFileAdapter::writeBlock(const char* , qint64) { SAFE_POINT(0, "Operation is not supported!",0); return 0; } bool HttpFileAdapter::skip(qint64 nBytes) { SAFE_POINT(isOpen(), "Adapter is not opened!", false); nBytes = waitData( nBytes ); rwmut.lock(); if( nBytes < 0 ) { assert( -nBytes <= CHUNKSIZE ); if( begin_ptr >= -nBytes ) { begin_ptr += nBytes; } else { if( !is_cached ) { rwmut.unlock(); return false; } chunk_list.prepend( cache ); begin_ptr = CHUNKSIZE - (-nBytes - begin_ptr); is_cached = false; } } else { rwmut.unlock(); return nBytes == skipAhead( nBytes ); } rwmut.unlock(); return true; } qint64 HttpFileAdapter::left() const { return (is_downloaded ? stored() : -1); } void HttpFileAdapter::init() { badstate = false; is_downloaded = false; is_cached= false; chunk_list.clear(); chunk_list.append( QByteArray(CHUNKSIZE, 0) ); loop.exit(); } void HttpFileAdapter::add_data( const QHttpResponseHeader & ) { rwmut.lock(); if( isEmpty() ) { begin_ptr = 0; } int howmuch = CHUNKSIZE - end_ptr; int got = http->read( chunk_list.last().data() + end_ptr, howmuch ); if( got < 0 ) { badstate = true; } else if( got < howmuch ) { end_ptr += got; } else { do { QByteArray newchunck( CHUNKSIZE, (char)0 ); got = http->read( newchunck.data(), CHUNKSIZE ); if( got < 0 ) { badstate = true; break; } chunk_list.append( newchunck ); } while( got == CHUNKSIZE ); end_ptr = got; } // cond.wakeOne(); loop.exit(); rwmut.unlock(); } qint64 HttpFileAdapter::stored() const { return (singleChunk() ? firstChunkContains() : firstChunkContains() + end_ptr + (chunk_list.size()-2) * CHUNKSIZE ); } void HttpFileAdapter::readFromChunk( char * data, int size ) { assert( size <= firstChunkContains() ); assert( !isEmpty() ); memcpy( data, chunk_list.first().data() + begin_ptr, size ); if( begin_ptr + size == CHUNKSIZE) { popFront(); } else { begin_ptr += size; } } void HttpFileAdapter::skipFromChunk( qint64 nbytes ) { assert( nbytes <= firstChunkContains() ); assert( !isEmpty() ); if( begin_ptr + nbytes == CHUNKSIZE) { popFront(); } else { begin_ptr += nbytes; } } void HttpFileAdapter::popFront() { if( singleChunk() ) { cache = chunk_list.first(); Empty(); } else { begin_ptr = 0; cache = chunk_list.takeFirst(); is_cached = true; } } qint64 HttpFileAdapter::skipAhead( qint64 nBytes ) { assert( nBytes >= 0 ); nBytes = qMin( nBytes, stored() ); qint64 skip_offs = 0; while( skip_offs < nBytes ) { int howmuch = qMin( nBytes - skip_offs, (qint64)firstChunkContains() ); skipFromChunk( howmuch ); skip_offs += howmuch; } return nBytes; } qint64 HttpFileAdapter::waitData( qint64 until ) { while (!is_downloaded && (until > stored()) ) { loop.exec(); } return qMin( until, stored() ); } void HttpFileAdapter::done( bool error ) { is_downloaded = true; badstate = error; loop.exit(); } int HttpFileAdapter::getProgress() const { return (total ? (int)( 100 * (float)downloaded / total ) : -1); } void HttpFileAdapter::state( int state ) { Q_UNUSED(state); // printf("downloading state: %d\n", state); } void HttpFileAdapter::progress( int done_, int total_ ) { downloaded = done_; total = total_; } }//namespace ugene-1.9.8/src/corelibs/U2Core/src/io/IOAdapter.h0000644000175000017500000001120211651544331020160 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_IOADAPTER_H_ #define _U2_IOADAPTER_H_ #include #include #include namespace U2 { enum IOAdapterMode { IOAdapterMode_Read, IOAdapterMode_Write, IOAdapterMode_Append }; class IOAdapter; class U2CORE_EXPORT IOAdapterFactory : public QObject { public: IOAdapterFactory(QObject* p) : QObject(p){} virtual IOAdapter* createIOAdapter() = 0; virtual IOAdapterId getAdapterId() const = 0; virtual const QString& getAdapterName() const = 0; virtual bool isIOModeSupported(IOAdapterMode m) const = 0; virtual TriState isResourceAvailable(const GUrl& url) const = 0; }; class U2CORE_EXPORT IOAdapter : public QObject { Q_OBJECT public: IOAdapter(IOAdapterFactory* f, QObject* o = NULL) : QObject(o), factory(f){} virtual ~IOAdapter(){} IOAdapterId getAdapterId() const {return factory->getAdapterId();} virtual const QString& getAdapterName() const {return factory->getAdapterName();} virtual bool isIOModeSupported(IOAdapterMode m) const {return factory->isIOModeSupported(m);} IOAdapterFactory* getFactory() const {return factory;} virtual bool open(const GUrl& url, IOAdapterMode m) = 0; virtual bool isOpen() const = 0; virtual void close() = 0; enum TerminatorHandling { Term_Exclude, // stop before terminators Term_Include, // include all terminators into result Term_Skip // do not include terminators to the result, but skip to after last terminator }; //return 0 if at the end of file, -1 if error virtual qint64 readUntil(char* buff, qint64 maxSize, const QBitArray& readTerminators, TerminatorHandling th, bool* terminatorFound = 0); virtual bool getChar(char* buff) {return 1 == readBlock(buff, 1);} //If an error occurs, this function returns -1 virtual qint64 readBlock(char* buff, qint64 maxSize) = 0; //read a single line of text and skips one EOL, returns length of line w/o terminator or -1 virtual qint64 readLine(char* buff, qint64 maxSize, bool* terminatorFound = 0); virtual qint64 writeBlock(const char* buff, qint64 size) = 0; qint64 writeBlock(const QByteArray& a) {return writeBlock(a.data(), a.size());} /** * Both positive and negative values are accepted. * Implementations should support skipping backwards within 32K of total read data. */ virtual bool skip(qint64 nBytes) = 0; //returns -1 if not supported virtual qint64 left() const = 0; /* Percent values in range 0..100, negative if unknown. */ virtual int getProgress() const = 0; bool isEof(); virtual qint64 bytesRead() const { return -1; } virtual GUrl getURL() const = 0; virtual QString toString() const {return getURL().getURLString();} private: IOAdapterFactory* factory; }; class U2CORE_EXPORT IOAdapterRegistry : public QObject { public: IOAdapterRegistry(QObject* p = NULL) : QObject(p) {} virtual bool registerIOAdapter(IOAdapterFactory* io) = 0; virtual bool unregisterIOAdapter(IOAdapterFactory* io) = 0; virtual const QList& getRegisteredIOAdapters() const = 0; virtual IOAdapterFactory* getIOAdapterFactoryById(IOAdapterId id) const = 0; }; class U2CORE_EXPORT BaseIOAdapters { public: static const IOAdapterId LOCAL_FILE; static const IOAdapterId GZIPPED_LOCAL_FILE; static const IOAdapterId HTTP_FILE; static const IOAdapterId GZIPPED_HTTP_FILE; static const IOAdapterId VFS_FILE; static IOAdapterId url2io(const GUrl& url); static QByteArray readFileHeader(const GUrl& url, int size = 65536); // io - opened ioadapter. before and after the call pos in file the same static QByteArray readFileHeader( IOAdapter* io, int size = 65536 ); }; }//namespace #endif ugene-1.9.8/src/corelibs/U2Core/src/io/IOAdapter.cpp0000644000175000017500000001171211651544331020521 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "IOAdapter.h" #include #include #include namespace U2 { const IOAdapterId BaseIOAdapters::LOCAL_FILE("local_file"); const IOAdapterId BaseIOAdapters::GZIPPED_LOCAL_FILE("local_file_gzip"); const IOAdapterId BaseIOAdapters::HTTP_FILE( "http_file" ); const IOAdapterId BaseIOAdapters::GZIPPED_HTTP_FILE( "http_file_gzip" ); const IOAdapterId BaseIOAdapters::VFS_FILE( "memory_buffer" ); IOAdapterId BaseIOAdapters::url2io(const GUrl& url) { if( url.isVFSFile() ) { return BaseIOAdapters::VFS_FILE; } if( url.isHyperLink() ) { if( url.lastFileSuffix() == "gz") { return BaseIOAdapters::GZIPPED_HTTP_FILE; } return BaseIOAdapters::HTTP_FILE; } if( url.lastFileSuffix() == "gz") { return BaseIOAdapters::GZIPPED_LOCAL_FILE; } return BaseIOAdapters::LOCAL_FILE; } QByteArray BaseIOAdapters::readFileHeader(const GUrl& url, int size) { QByteArray data; IOAdapterFactory* iof = AppContext::getIOAdapterRegistry()->getIOAdapterFactoryById(BaseIOAdapters::url2io(url)); std::auto_ptr adapter(iof->createIOAdapter()); bool res = adapter->open(url, IOAdapterMode_Read); if (!res) { return data;//BUG:420: report error } data.resize(size); int s = adapter->readBlock(data.data(), data.size()); if (s == -1) { data.resize(0); return data;//BUG:420: report error } if (s != data.size()) { data.resize(s); } return data; } QByteArray BaseIOAdapters::readFileHeader( IOAdapter* io, int sz ) { QByteArray data; if( NULL == io || !io->isOpen() ) { return data; } data.resize( sz ); int ret = io->readBlock( data.data(), sz ); if( -1 == ret ) { data.resize( 0 ); return data; } if( ret != sz ) { data.resize( ret ); } io->skip( -ret ); return data; } qint64 IOAdapter::readUntil(char* buf, qint64 maxSize, const QBitArray& readTerminators, TerminatorHandling th, bool* terminatorFound) { const qint64 CHUNK = (qint64)1024; const char *chunk_start, *start = buf, *end = buf + maxSize; bool found = false; qint64 len; qint64 termsSkipped = 0; do { chunk_start = buf; len = readBlock(buf, qMin(CHUNK, (qint64)end - (qint64)buf)); if (len < CHUNK) { // last chunk, no more data or buffer space end = buf + len; } const char* buf_end = buf + len; for(; buf < buf_end; buf++ ) { // loop exit invariant: buf is positioned after last accepted char if (readTerminators[(uchar)*buf]) { found = true; if (th == Term_Exclude) { break; } else if( Term_Skip == th ) { termsSkipped++; } } else if (found) { assert( Term_Include == th || Term_Skip == th ); break; } } } while (!found && buf < end); if (found) { bool b = skip((qint64)buf - (qint64)chunk_start - len); assert(b);// Cannot put back unused data; Q_UNUSED(b); } if (terminatorFound != NULL) { *terminatorFound = found; } return (qint64)buf - (qint64)start - termsSkipped; } bool IOAdapter::isEof() { char ch; int ret = readBlock( &ch, 1 ); if (ret == 1) { skip( -ret ); } return 0 == ret; } qint64 IOAdapter::readLine( char* buff, qint64 maxSize, bool* terminatorFound /* = 0*/ ) { bool b = false; if (!terminatorFound) { terminatorFound = &b; } qint64 len = readUntil(buff, maxSize, TextUtils::LINE_BREAKS, Term_Exclude, terminatorFound); if (*terminatorFound) { char ch; bool b = getChar(&ch); assert(b); if (ch == '\r') { // may be Windows EOL \r\n b = getChar(&ch); if (b && ch != '\n') { skip(-1); } } else { assert(ch == '\n'); } } return len; } }//namespace ugene-1.9.8/src/corelibs/U2Core/src/io/ZlibAdapter.cpp0000644000175000017500000003254111651544332021116 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "LocalFileAdapter.h" #include "ZlibAdapter.h" //using 3rd-party zlib (not included in ugene bundle) on *nix #if defined(Q_OS_LINUX) || defined(Q_OS_UNIX) #include #else #include "zlib.h" #endif #include namespace { using namespace U2; // used in GZipIndex building void setIfYouCan( bool what, bool* to ) { if( NULL != to ) { *to = what; } } // used in GZipIndex building void addAccessPoint( GZipIndex& index, int bits, qint64 in, qint64 out, quint32 left, char* wnd ) { assert( NULL != wnd ); QByteArray window; GZipIndexAccessPoint next; next.bits = bits; next.in = in; next.out = out; if (left) { window.append( QByteArray( wnd + GZipIndex::WINSIZE - left, left ) ); } if (left < quint32(GZipIndex::WINSIZE)) { window.append( QByteArray( wnd, GZipIndex::WINSIZE - left ) ); } next.window = qCompress( window ).toBase64(); index.points.append( next ); } } // anonymous namespace namespace U2 { class GzipUtil { public: GzipUtil(IOAdapter* io, bool doCompression); ~GzipUtil(); qint64 uncompress(char* outBuff, qint64 outSize); qint64 compress(const char* inBuff, qint64 inSize, bool finish = false); bool isCompressing() const {return doCompression;} qint64 getPos() const; bool skip( const GZipIndexAccessPoint& index, qint64 offset ); private: static const int CHUNK = 16384; z_stream strm; char buf[CHUNK]; IOAdapter* io; bool doCompression; qint64 curPos; // position of uncompressed file }; GzipUtil::GzipUtil(IOAdapter* io, bool doCompression) : io(io), doCompression(doCompression), curPos( 0 ) { //#ifdef _DEBUG qMemSet(buf, 0xDD, CHUNK); //#endif /* allocate inflate state */ strm.zalloc = Z_NULL; strm.zfree = Z_NULL; strm.opaque = Z_NULL; strm.avail_in = 0; strm.next_in = Z_NULL; int ret = doCompression ? /* write a simple gzip header and trailer around the compressed data */ deflateInit2(&strm, Z_DEFAULT_COMPRESSION, Z_DEFLATED, 16 + 15, 8, Z_DEFAULT_STRATEGY) /* enable zlib and gzip decoding with automatic header detection */ : inflateInit2(&strm, 32 + 15); assert(ret == Z_OK); Q_UNUSED(ret); } GzipUtil::~GzipUtil() { if (doCompression) { int ret = compress(NULL, 0, true); if( -1 != ret ) { assert(ret == 0); Q_UNUSED(ret); } deflateEnd(&strm); } else { inflateEnd(&strm); } } qint64 GzipUtil::getPos() const { return curPos; } qint64 GzipUtil::uncompress(char* outBuff, qint64 outSize) { /* Based on gun.c (example from zlib, copyrighted (C) 2003, 2005 Mark Adler) */ strm.avail_out = outSize; strm.next_out = (Bytef*)outBuff; do { /* run inflate() on input until output buffer is full */ if (strm.avail_in == 0) { // need more input strm.avail_in = io->readBlock(buf, CHUNK); strm.next_in = (Bytef*)buf; } if (strm.avail_in == quint32(-1)) { // TODO log error return -1; } if (strm.avail_in == 0) break; int ret = inflate(&strm, Z_SYNC_FLUSH); assert(ret != Z_STREAM_ERROR); /* state not clobbered */ switch (ret) { case Z_NEED_DICT: case Z_DATA_ERROR: case Z_MEM_ERROR: return -1; case Z_BUF_ERROR: case Z_STREAM_END: curPos += outSize - strm.avail_out; return outSize - strm.avail_out; } if (strm.avail_out != 0 && strm.avail_in != 0) { assert(0); break; } } while (strm.avail_out != 0); curPos += outSize - strm.avail_out; return outSize - strm.avail_out; } qint64 GzipUtil::compress(const char* inBuff, qint64 inSize, bool finish) { int ret; Q_UNUSED(ret); /* Based on gun.c (example from zlib, copyrighted (C) 2003, 2005 Mark Adler) */ strm.avail_in = inSize; strm.next_in = (Bytef*)inBuff; do { /* run deflate() on input until output buffer not full */ strm.avail_out = CHUNK; strm.next_out = (Bytef*)buf; ret = deflate(&strm, finish ? Z_FINISH : Z_NO_FLUSH); assert(ret != Z_STREAM_ERROR); /* state not clobbered */ int have = CHUNK - strm.avail_out; qint64 l = io->writeBlock(buf, have); if (l != have) { // TODO log error return -1; } } while (strm.avail_out == 0); if (strm.avail_in != 0) { assert(0); /* all input should be used */ // TODO log error return -1; } assert(!finish || ret == Z_STREAM_END); /* stream will be complete */ return inSize; } // based on zran.c ( example from zlib Copyright (C) 2005 Mark Adler ) bool GzipUtil::skip( const GZipIndexAccessPoint& here, qint64 offset ) { if( here.out > offset || 0 > offset ) { return false; } int ret = 0; bool ok = false; char discard[GZipIndex::WINSIZE]; LocalFileAdapter* localIO = qobject_cast< LocalFileAdapter* >( io ); if( NULL == localIO ) { return false; } ok = localIO->skip( here.in - ( here.bits ? 1 : 0 ) ); if ( !ok ) { return false; } inflateInit2( &strm, -15 ); if ( here.bits ) { char chr = 0; ok = io->getChar( &chr ); if( !ok ) { return false; } ret = chr; inflatePrime( &strm, here.bits, ret >> ( 8 - here.bits ) ); } inflateSetDictionary( &strm, ( const Bytef* )here.window.data(), GZipIndex::WINSIZE ); /* skip uncompressed bytes until offset reached, then satisfy request */ offset -= here.out; do { /* define where to put uncompressed data, and how much */ qint64 howMany = 0; if ( 0 == offset ) { /* at offset now */ break; /* all that we want */ } if ( offset > GZipIndex::WINSIZE ) { /* skip WINSIZE bytes */ howMany = GZipIndex::WINSIZE; } else if ( 0 != offset ) { /* last skip */ howMany = offset; } offset -= howMany; qint64 uncompressed = uncompress( discard, howMany ); if( uncompressed != howMany ) { return false; /* error or eof - cannot skip to desired position */ } } while ( 1 ); return true; } ZlibAdapter::ZlibAdapter(IOAdapter* io) : IOAdapter(io->getFactory()), io(io), z(NULL), buf(NULL), rewinded(0) {} ZlibAdapter::~ZlibAdapter() { close(); delete io; } void ZlibAdapter::close() { delete z; z = NULL; if (buf) { delete[] buf->rawData(); delete buf; buf = NULL; } if (io->isOpen()) io->close(); } bool ZlibAdapter::open(const GUrl& url, IOAdapterMode m ) { assert(!isOpen()); close(); bool res = io->open(url, m); if (res) { z = new GzipUtil(io, m == IOAdapterMode_Write); assert(z); if (m == IOAdapterMode_Read) { buf = new RingBuffer(new char[BUFLEN], BUFLEN); assert(buf); } } return res; } qint64 ZlibAdapter::readBlock(char* data, qint64 size) { if (!isOpen() || z->isCompressing()) { assert(0 && "not ready to read"); return false; } // first use data put back to buffer if any int cached = 0; if (rewinded != 0) { assert(rewinded > 0 && rewinded <= buf->length()); cached = buf->read(data, size, buf->length() - rewinded); if (cached == size) { rewinded -= size; return size; } assert(cached < size); rewinded = 0; } size = z->uncompress(data + cached, size - cached); if (size == -1) { return -1; } buf->append(data + cached, size); return size + cached; } qint64 ZlibAdapter::writeBlock(const char* data, qint64 size) { if (!isOpen() || !z->isCompressing()) { assert(0 && "not ready to write"); return false; } qint64 l = z->compress(data, size); return l; } bool ZlibAdapter::skip(qint64 nBytes) { if (!isOpen() || z->isCompressing()) { assert(0 && "not ready to seek"); return false; } assert(buf); nBytes -= rewinded; if (nBytes <= 0) { if (-nBytes <= buf->length()) { rewinded = -nBytes; return true; } return false; } rewinded = 0; char* tmp = new char[nBytes]; qint64 skipped = readBlock(tmp, nBytes); delete[] tmp; return skipped == nBytes; } bool ZlibAdapter::skip( const GZipIndexAccessPoint& point, qint64 offset ) { if( NULL == z ) { return false; } if( !point.window.size() || 0 > offset ) { return false; } return z->skip( point, offset ); } qint64 ZlibAdapter::bytesRead() const { return z->getPos() - rewinded; } // based on zran.c ( example from zlib Copyright (C) 2005 Mark Adler ) GZipIndex ZlibAdapter::buildGzipIndex( IOAdapter* io, qint64 span, bool* ok ) { assert( NULL != io && io->isOpen() ); int ret = 0; qint64 totin = 0; // our own total counters qint64 totout = 0; // to avoid 4GB limit qint64 last = 0; // totout value of last access point GZipIndex index; // index being generated z_stream strm; char input[GZipIndex::CHUNK]; char window[GZipIndex::WINSIZE]; /* initialize inflate */ strm.zalloc = Z_NULL; strm.zfree = Z_NULL; strm.opaque = Z_NULL; strm.avail_in = 0; strm.next_in = Z_NULL; ret = inflateInit2(&strm, 47); /* automatic zlib or gzip decoding */ if (ret != Z_OK) { setIfYouCan( false, ok ); return GZipIndex(); } /* inflate the input, maintain a sliding window, and build an index -- this also validates the integrity of the compressed data using the check information at the end of the gzip or zlib stream */ totin = totout = last = 0; strm.avail_out = 0; do { /* get some compressed data from input file */ strm.avail_in = io->readBlock( input, GZipIndex::CHUNK ); if ( -1 == int(strm.avail_in) || 0 == strm.avail_in ) { setIfYouCan( false, ok ); return GZipIndex(); } strm.next_in = ( Bytef* )&input[0]; /* process all of that, or until end of stream */ do { /* reset sliding window if necessary */ if (strm.avail_out == 0) { strm.avail_out = GZipIndex::WINSIZE; strm.next_out = (Bytef*)window; } /* inflate until out of input, output, or at end of block -- update the total input and output counters */ totin += strm.avail_in; totout += strm.avail_out; ret = inflate(&strm, Z_BLOCK); /* return at end of block */ totin -= strm.avail_in; totout -= strm.avail_out; if (ret == Z_MEM_ERROR || ret == Z_DATA_ERROR || ret == Z_NEED_DICT ) { setIfYouCan( false, ok ); return GZipIndex(); } if (ret == Z_STREAM_END) { break; } /* if at end of block, consider adding an index entry (note that if data_type indicates an end-of-block, then all of the uncompressed data from that block has been delivered, and none of the compressed data after that block has been consumed, except for up to seven bits) -- the totout == 0 provides an entry point after the zlib or gzip header, and assures that the index always has at least one access point; we avoid creating an access point after the last block by checking bit 6 of data_type */ if ((strm.data_type & 128) && !(strm.data_type & 64) && (totout == 0 || totout - last > span)) { addAccessPoint(index, strm.data_type & 7, totin, totout, strm.avail_out, window); last = totout; } } while (strm.avail_in != 0); } while (ret != Z_STREAM_END); (void)inflateEnd(&strm); setIfYouCan( true, ok ); return index; } qint64 ZlibAdapter::getUncompressedFileSizeInBytes(const GUrl &url) { QFile file(url.getURLString()); if (!file.open(QIODevice::ReadOnly)) { return -1; } int wordSizeInBytes = 4; file.seek(file.size() - wordSizeInBytes); QByteArray buffer = file.read(wordSizeInBytes); assert(buffer.size() == wordSizeInBytes); quint32 result = qFromLittleEndian((uchar*)buffer.data()); return result; } GUrl ZlibAdapter::getURL() const { return io->getURL(); } };//namespace ugene-1.9.8/src/corelibs/U2Core/src/io/GUrl.cpp0000644000175000017500000001374711651544331017574 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "GUrl.h" #include #include namespace U2 { static QString makeFilePathCanonical(const QString& originalUrl) { //ensure that name is canonical QString result = originalUrl.trimmed(); QString fileUrlPrefix = "file://"; if(result.startsWith(fileUrlPrefix)) { result = result.mid(fileUrlPrefix.length()); #ifdef Q_OS_WIN // on Windows, all slashes after "file:" can be trimmed, on Unix/Mac one must be kept to specify that it's an absolute path while(result.startsWith("/")) { result = result.mid(1); } #endif } // Windows drive letter, Qt resource designation or Samba share designation and name QString prefix; if(originalUrl.startsWith(':')) { // is a Qt resource prefix = ":"; result = result.mid(1); } else { result = QFileInfo(result).absoluteFilePath(); } #ifdef Q_OS_WIN bool isSambaPath = false; if(result.startsWith("//") && prefix.isEmpty()) { // keep Samba share designation prefix = "//"; isSambaPath = true; } #endif QStringList parts = result.split('/', QString::SkipEmptyParts); if(parts.size() > 0) { QStringList canonicalParts; #ifdef Q_OS_WIN // append drive spec letter or Samba server name to the prefix if(isSambaPath) { prefix += parts.takeFirst(); } else if(parts.at(0).endsWith(':') && parts.at(0).length() == 2 && prefix.isEmpty()) { // Windows drive letter designation prefix = parts.takeFirst(); } #endif // get rid of redundant '.' and '..' now QStringListIterator it(parts); while(it.hasNext()) { QString part = it.next(); if(part == ".") { continue; } else if(part == "..") { if(!canonicalParts.isEmpty()) { canonicalParts.removeLast(); } } else if (!part.isEmpty()) { canonicalParts.append(part); } } result = prefix + "/" + canonicalParts.join("/"); } return result; } GUrlType GUrl::getURLType(const QString& rawUrl) { GUrlType result = GUrl_File; if (rawUrl.startsWith("http://") || rawUrl.startsWith("https://")) { result = GUrl_Http; } else if (rawUrl.startsWith("ftp://")) { result = GUrl_Ftp; } else if( rawUrl.startsWith( VirtualFileSystem::URL_PREFIX ) ) { result = GUrl_VFSFile; } return result; } // constructs url specified by string. The type is parsed GUrl::GUrl(const QString& _urlString) { urlString = _urlString; type = getURLType(urlString); if (type == GUrl_File) { urlString = makeFilePathCanonical(urlString); } } // constructs url specified by string. The type provided as param GUrl::GUrl(const QString& _urlString, const GUrlType _type) { urlString = _urlString; type = _type; if (type == GUrl_File) { urlString = makeFilePathCanonical(urlString); } } GUrl::GUrl(const GUrl& anotherUrl) { urlString = anotherUrl.getURLString(); type = anotherUrl.getType(); } bool GUrl::operator ==(const GUrl& url) const { return urlString == url.getURLString(); } bool GUrl::operator !=(const GUrl& url) const { return !(*this == url); } static QString path(const GUrl* url) { //TODO: parse HTTP and other formats for path part QString result; if( url->isVFSFile() ) { return result; } result = url->getURLString(); return result; } QString GUrl::dirPath() const { QString result; if( isVFSFile() ) { return result; } result = QFileInfo(path(this)).absoluteDir().absolutePath(); return result; } QString GUrl::fileName() const { QString result; if( isVFSFile() ) { return result; } result = QFileInfo(path(this)).fileName(); return result; } QString GUrl::baseFileName() const { QString result; if( isVFSFile() ) { QStringList args = urlString.split( VirtualFileSystem::URL_NAME_SEPARATOR, QString::SkipEmptyParts, Qt::CaseSensitive ); if( 2 == args.size() ) { result = QFileInfo( args.at( 1 ) ).baseName(); } } else { result = QFileInfo(path(this)).baseName(); } return result; } QString GUrl::lastFileSuffix() const { QString result; if( isVFSFile() ) { return result; } result = QFileInfo(path(this)).suffix(); return result; } QString GUrl::completeFileSuffix() const { QString result; if( isVFSFile() ) { return result; } result = QFileInfo(path(this)).completeSuffix(); return result; } static bool registerMetas() { qRegisterMetaType("GUrl"); qRegisterMetaTypeStreamOperators("U2::GUrl"); return true; } QDataStream &operator<<(QDataStream &out, const GUrl &myObj) { out << myObj.getURLString() << myObj.getType(); return out; } QDataStream &operator>>(QDataStream &in, GUrl &myObj) { QString urlString; in >> urlString; int t; in >> t; GUrlType type = (GUrlType)t; myObj = GUrl(urlString, type); return in; } bool GUrl::registerMeta = registerMetas(); }//namespace ugene-1.9.8/src/corelibs/U2Core/src/io/RingBuffer.h0000644000175000017500000000316211651544332020410 0ustar ilyailya#ifndef _U2_RING_BUF_H_ #define _U2_RING_BUF_H_ namespace U2 { class RingBuffer { public: RingBuffer(char* buf, int size):data(buf),size(size),len(0),start(0){} inline int read(char* dest, int n, int index = 0) const; inline void append(const char* src, int n); int length() const {return len;} char* rawData() const {return data;} private: char* data; // buffer area int size; // buffer size int len; // length of buffered data int start; // start offset }; int RingBuffer::read(char *dest, int n, int index) const { assert (index < len); if (n > len - index) { n = len - index; } int begin = (start + index) % size; int end = (start + index + n) % size; if (begin < end) { memcpy(dest, data + begin, n); } else { assert(end + size - begin >= n); int l1 = qMin(n, size - begin); memcpy(dest, data + begin, l1); if (l1 < n) { memcpy(dest + l1, data, n - l1); } } return n; } void RingBuffer::append(const char *src, int n) { if (n >= size) { start = 0; len = size; memcpy(data, src + n - size, size); } else { int trail_len = qMin(len, size - n); int trail_start = (start + len - trail_len) % size; int trail_end = (start + len) % size; if (trail_start > trail_end) { assert(trail_start - trail_end >= n); memcpy(data + trail_end, src, n); } else { assert(trail_start + size - trail_end >= n); int l1 = qMin(size - trail_end, n); memcpy(data + trail_end, src, l1); if (l1 < n){ memcpy(data, src + l1, n - l1); } } start = trail_start; len += n; if (len > size) len = size; } } } //namespace #endif ugene-1.9.8/src/corelibs/U2Core/src/io/ZlibAdapter.h0000644000175000017500000000553411651544332020565 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_ZLIB_ADAPTER_H_ #define _U2_ZLIB_ADAPTER_H_ #include #include "RingBuffer.h" namespace U2 { class GzipUtil; struct GZipIndex; struct GZipIndexAccessPoint; class U2CORE_EXPORT ZlibAdapter: public IOAdapter { Q_OBJECT public: ZlibAdapter(IOAdapter* io); ~ZlibAdapter(); virtual bool open(const GUrl& url, IOAdapterMode m_ ); virtual bool isOpen() const {return io->isOpen();} virtual void close(); virtual qint64 readBlock(char* data, qint64 maxSize); virtual qint64 writeBlock(const char* data, qint64 size); virtual bool skip(qint64 nBytes); virtual qint64 left() const {return -1;} virtual int getProgress() const {return io->getProgress();} virtual qint64 bytesRead() const; virtual GUrl getURL() const; /** * should be invoked after open() ( needs z not null ) */ bool skip( const GZipIndexAccessPoint& point, qint64 offset ); /** *on error *ok set to false and GZipIndex() is returned * io - opened ioadapter, on the beginning of the file */ static GZipIndex buildGzipIndex( IOAdapter* io, qint64 span, bool* ok = NULL ); /** * returns -1 if a file is failed to open */ static qint64 getUncompressedFileSizeInBytes(const GUrl &url); private: static const int BUFLEN = 32768; IOAdapter* io; GzipUtil* z; RingBuffer* buf; // seek buffer int rewinded; // how much should read from seek buffer }; struct GZipIndexAccessPoint { qint64 out; // corresponding offset in uncompressed data qint64 in; // offset in input file of first full byte int bits; // number of bits (1-7) from byte at in - 1, or 0 QByteArray window; //preceding WINSIZE of uncompressed data }; struct U2CORE_EXPORT GZipIndex { static const int WINSIZE = 32768; static const qint64 SPAN = 1048576L; static const int CHUNK = 16384; QList< GZipIndexAccessPoint > points; }; // GZipIndex };//namespace #endif ugene-1.9.8/src/corelibs/U2Core/src/io/GUrlUtils.cpp0000644000175000017500000001554111651544331020607 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "GUrlUtils.h" #include #include #include #include #include #include namespace U2 { QString GUrlUtils::getUncompressedExtension(const GUrl& url) { QString ext = url.lastFileSuffix(); if (ext == "gz") { QString completeSuffix = url.completeFileSuffix(); QStringList suffixList = completeSuffix.split("."); ext = suffixList.empty() ? QString() : suffixList.first(); } return ext; } GUrl GUrlUtils::ensureFileExt(const GUrl& url, const QStringList& typeExt) { SAFE_POINT(!typeExt.isEmpty(), "Type extension is empty!", GUrl()); if( url.isVFSFile() ) { return url; } if (typeExt.isEmpty()) { return url; } if (typeExt.contains(GUrlUtils::getUncompressedExtension(url))) { return url; } return GUrl(url.getURLString() + "." + typeExt.first(), url.getType()); } bool GUrlUtils::renameFileWithNameRoll(const QString& original, TaskStateInfo& ti, const QSet& excludeList, Logger* log) { QString rolled = GUrlUtils::rollFileName(original, "_oldcopy", excludeList); if (rolled == original) { return true; } if (QFile(original).rename(rolled)) { if (log) { log->details(tr("Renamed %1 to %2").arg(original).arg(rolled)); } return true; } else { ti.setError(tr("Failed to rename %1 to %2").arg(original).arg(rolled)); return false; } } QString GUrlUtils::rollFileName(const QString& originalUrl, const QString& rolledSuffix, const QSet& excludeList) { QString pre = originalUrl, post; //pre and post url parts. A number will be placed between int idx = pre.lastIndexOf("."); if (idx != -1) { QString extSuffix = pre.mid(idx); if(extSuffix == ".gz") { pre.chop(extSuffix.length()); idx = pre.lastIndexOf("."); if(idx != -1) { extSuffix = pre.mid(idx) + extSuffix; pre.append(".gz"); } } if (!extSuffix.contains("\\")) { post = extSuffix; pre.chop(extSuffix.length()); } } QString resultUrl = originalUrl; int i = 0; while (QFile::exists(resultUrl) || excludeList.contains(resultUrl)) { resultUrl = pre + rolledSuffix + QString("%1").arg(++i) + post; } return resultUrl; } QUrl GUrlUtils::gUrl2qUrl( const GUrl& gurl) { if( gurl.isVFSFile() ) { return QUrl(); } QString str = gurl.getURLString(); if (str.startsWith("http://") || str.startsWith("https://") || str.startsWith("file://")) { return str; } else { return QUrl("file:///" + QFileInfo(str).absoluteFilePath()); } } QList GUrlUtils::gUrls2qUrls( const QList& gurls) { QList urls; foreach(const GUrl& gurl, gurls) { urls << gUrl2qUrl(gurl); } return urls; } GUrl GUrlUtils::qUrl2gUrl( const QUrl& qurl) { QString str = qurl.toString(); return GUrl(str); } QList GUrlUtils::qUrls2gUrls( const QList& qurls) { QList urls; foreach(const QUrl& qurl, qurls) { urls << qUrl2gUrl(qurl); } return urls; } QString GUrlUtils::prepareFileName(const QString& url, int count, const QStringList& typeExt) { return prepareFileName(url, QString("%1").arg(count, 3, 10, QChar('0')), typeExt); } QString GUrlUtils::prepareFileName(const QString& url, const QString& baseSuffix, const QStringList& typeExt) { QFileInfo fi(url); QStringList suffixList = fi.completeSuffix().split("."); QString ext; foreach(const QString& suffix, suffixList) { if (typeExt.contains(suffix)) { ext = suffix; break; } } if (ext.isEmpty()) { return url + QString(".%1.%2").arg(baseSuffix).arg(typeExt.first()); } QString base = fi.baseName(); while(!suffixList.isEmpty()) { QString nextSuffix = suffixList.takeFirst(); if (nextSuffix == ext) { break; } base += "." + nextSuffix; } QString result = QString("%1/%2.%3.%4").arg(fi.dir().path()).arg(base).arg(baseSuffix).arg(ext); if (!suffixList.isEmpty()) { result.append(".").append(suffixList.join(".")); } return result; } // checks that file path is valid: creates required directory if needed. // Returns canonical path to file. Does not create nor remove file, affects just directory // Sample usage: processing URLs in "save file" inputs QString GUrlUtils::prepareFileLocation(const QString& filePath, QString& errorMessage) { QFileInfo fi(filePath); QString dirPath = fi.absoluteDir().absolutePath(); QString canonicalDirPath = prepareDirLocation(dirPath, errorMessage); if (!errorMessage.isEmpty()) { return QString(); } // examples with "/" at the end: QString result = canonicalDirPath + (canonicalDirPath.endsWith("/") ? "" : "/") + fi.fileName(); return result; } // checks that dir path is valid. Creates the directory if needed. // Returns canonical directory path. Does not affect directory if already exists. // Sample usage: processing URLs in "save dir" inputs QString GUrlUtils::prepareDirLocation(const QString& dirPath, QString& errorMessage) { if (dirPath.isEmpty()) { errorMessage = tr("Directory is not specified"); return QString(); } QDir targetDir(dirPath); if (!targetDir.exists()) { QString absPath = targetDir.absolutePath(); if (!targetDir.mkpath(absPath)) { errorMessage = tr("Directory can't be created: %1").arg(absPath); return QString(); } targetDir = QDir(absPath); //It looks like QT caches results for QDir? Create new QDir instance in this case! if (!targetDir.isReadable()) { errorMessage = tr("Directory can't be read: %1").arg(absPath); return QString(); } } QString result = targetDir.canonicalPath(); return result; } }//namespace ugene-1.9.8/src/corelibs/U2Core/src/io/LocalFileAdapter.cpp0000644000175000017500000001131511651544331022043 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "LocalFileAdapter.h" #include "ZlibAdapter.h" #include namespace U2 { LocalFileAdapterFactory::LocalFileAdapterFactory(QObject* o) : IOAdapterFactory(o) { name = tr("Local file"); } IOAdapter* LocalFileAdapterFactory::createIOAdapter() { return new LocalFileAdapter(this); } GzippedLocalFileAdapterFactory::GzippedLocalFileAdapterFactory(QObject* o) : LocalFileAdapterFactory(o) { name = tr("GZIP file"); } IOAdapter* GzippedLocalFileAdapterFactory::createIOAdapter() { return new ZlibAdapter(new LocalFileAdapter(this)); } const quint64 LocalFileAdapter::BUF_SIZE = 1024*1024; LocalFileAdapter::LocalFileAdapter(LocalFileAdapterFactory* factory, QObject* o, bool b) : IOAdapter(factory, o), f(NULL), bufferOptimization(b) { bufferOptimization = true; if (bufferOptimization) { buffer = QByteArray(BUF_SIZE, '\0'); bufData = buffer.data(); } else { bufData = NULL; } bufLen = 0; currentPos = 0; } bool LocalFileAdapter::open(const GUrl& url, IOAdapterMode m) { SAFE_POINT(!isOpen(), "Adapter is already opened!", false); SAFE_POINT(f == NULL, "QFile is not null!", false); if (url.isEmpty()) { return false; } f = new QFile(url.getURLString()); QIODevice::OpenMode iomode; switch (m) { case IOAdapterMode_Read: iomode = QIODevice::ReadOnly; break; case IOAdapterMode_Write: iomode = QIODevice::WriteOnly | QIODevice::Truncate; break; case IOAdapterMode_Append: iomode = QIODevice::WriteOnly | QIODevice::Append; break; } bool res = f->open(iomode); if (!res) { delete f; f = NULL; return false; } return true; } void LocalFileAdapter::close() { SAFE_POINT(isOpen(), "Adapter is not opened!",); f->close(); delete f; f = NULL; } qint64 LocalFileAdapter::readBlock(char* data, qint64 size) { SAFE_POINT(isOpen(), "Adapter is not opened!",-1); qint64 l = 0; if (bufferOptimization) { qint64 copySize = 0; while (l < size) { if (currentPos == bufLen) { bufLen = f->read(bufData, BUF_SIZE); currentPos = 0; } copySize = qMin(bufLen - currentPos, size - l); if (0 == copySize) { break; } memcpy(data + l, bufData + currentPos, copySize); l += copySize; currentPos += copySize; } } else { l = f->read(data, size); } return l; } qint64 LocalFileAdapter::writeBlock(const char* data, qint64 size) { SAFE_POINT(isOpen(), "Adapter is not opened!",-1); qint64 l = f->write(data, size); return l; } bool LocalFileAdapter::skip(qint64 nBytes) { SAFE_POINT(isOpen(), "Adapter is not opened!",false); if (bufferOptimization) { qint64 newPos = currentPos + nBytes; if (newPos < 0 || newPos >= bufLen) { qint64 p = f->pos(); bool res = f->seek((p - bufLen + currentPos) + nBytes); bufLen = 0; currentPos = 0; return res; } else { currentPos = newPos; return true; } } else { qint64 p = f->pos(); return f->seek(p+nBytes); } } qint64 LocalFileAdapter::left() const { SAFE_POINT(isOpen(), "Adapter is not opened!",-1); qint64 p = f->pos(); qint64 len = f->size(); if (bufferOptimization) { p -= bufLen - currentPos; } return len - p; } int LocalFileAdapter::getProgress() const { SAFE_POINT(isOpen(), "Adapter is not opened!",false); return int(100 * float(bytesRead()) / f->size()); } qint64 LocalFileAdapter::bytesRead() const { qint64 p = f->pos(); if (bufferOptimization) { p -= bufLen - currentPos; } return p; } GUrl LocalFileAdapter::getURL() const { return GUrl(f->fileName(), GUrl_File); } };//namespace ugene-1.9.8/src/corelibs/U2Core/src/io/VirtualFileSystem.h0000644000175000017500000000641111651544332022012 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_VIRTUAL_FILE_SYSTEM_H_ #define _U2_VIRTUAL_FILE_SYSTEM_H_ #include #include #include #include #include namespace U2 { /* * VirtualFileSystem represents files mapped to memory * usage: map files to memory then use MemBufAdapter to read them */ class U2CORE_EXPORT VirtualFileSystem { public: // if you want MemBufAdapter reading-writing to your vfs: make url of your file as URL_PREFIX+vfsname+URL_NAME_SEPARATOR+filename static const QString URL_PREFIX; static const QString URL_NAME_SEPARATOR; // NOTE: vfs name should not contain this separator static const int READ_BLOCK_SZ = 4096; public: VirtualFileSystem(); VirtualFileSystem( const QString & fsName ); ~VirtualFileSystem(); // if file exist in vfs: return false, do nothing bool createFile( const QString & filename, const QByteArray & data ); // maps filePath file from disk to memory and adds it to vfs // if filename exists in vfs: replace prev bool mapFile( const QString & filename, const QString & filePath ); // maps back to disk (from memory) bool mapBack( const QString & filename, const QString & filePath ) const; // if file does not exist: create new file void modifyFile( const QString & filename, const QByteArray & data ); QByteArray removeFile( const QString & filename ); void removeAllFiles(); bool fileExists( const QString & filename ) const; QByteArray & getFileByName( const QString & filename ); QByteArray getFileByName( const QString & filename ) const; void setId( const QString & id ); QString getId() const; QStringList getAllFilenames() const; private: QString fileSystemName; // unique id of fs QMap< QString, QByteArray > files; }; // VirtualFileSystem class U2CORE_EXPORT VirtualFileSystemRegistry { public: VirtualFileSystemRegistry(); ~VirtualFileSystemRegistry(); bool registerFileSystem( VirtualFileSystem * entry ); VirtualFileSystem * unregisterFileSystem( const QString & id ); VirtualFileSystem * getFileSystemById( const QString & id ) const; QList< VirtualFileSystem* > getAllFileSystems() const; QStringList getAllIds() const; private: QMap< QString, VirtualFileSystem* > registry; }; // VirtualFileSystemRegistry } // U2 #endif // _U2_VIRTUAL_FILE_SYSTEM_H_ ugene-1.9.8/src/corelibs/U2Core/src/io/GUrl.h0000644000175000017500000000576411651544331017241 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_GURL_H_ #define _U2_GURL_H_ #include #include namespace U2 { /** GUrl is designed to provide an easy to use and error prone implementation or URL for DocumentModel in UGENE. The core of GUrl is string based representation of an URL: urlString. GUrl class enforces urlString to be always in correct canonical form. All oter fields are supplementary. Note: that 2 GUrls are considered equals if the urlStrings are equal. * Why not QUrl - QUrl is too error prone and requires a lot of external code to support valid state. * Why not QString - requires external utils to represent all urls in canonical form. Can't be to extended. */ /** Type of the URL */ enum GUrlType { GUrl_File, //local file or default URL type for unknown files GUrl_Http, //both http and https protocols GUrl_Ftp, GUrl_VFSFile //memory block }; class U2CORE_EXPORT GUrl { public: // constructs empty url. The default type -> file GUrl(){type = GUrl_File;} // constructs url specified by string. The type is parsed GUrl(const QString& urlString); // constructs url specified by string. The type provided as param GUrl(const QString& urlString, const GUrlType type); GUrl(const GUrl& anotherUrl); bool operator ==(const GUrl& url) const; bool operator !=(const GUrl& url) const; const QString& getURLString() const {return urlString;} GUrlType getType() const {return type;} bool isEmpty() const {return urlString.isEmpty();} bool isLocalFile() const {return type == GUrl_File;} bool isHyperLink() const {return type == GUrl_Http;} bool isVFSFile() const {return type == GUrl_VFSFile;} QString dirPath() const; QString fileName() const; QString baseFileName() const; QString lastFileSuffix() const; QString completeFileSuffix() const; static GUrlType getURLType(const QString& rawUrl); private: static bool registerMeta; QString urlString; GUrlType type; }; QDataStream &operator<<(QDataStream &out, const GUrl &myObj); QDataStream &operator>>(QDataStream &in, GUrl &myObj); }//namespace Q_DECLARE_METATYPE(U2::GUrl); #endif ugene-1.9.8/src/corelibs/U2Core/src/io/HttpFileAdapter.h0000644000175000017500000000777611651544331021415 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_HTTP_FILE_ADAPTER_H_ #define _U2_HTTP_FILE_ADAPTER_H_ #include #include #include #include class QHttp; class QHttpResponseHeader; class QMutex; namespace U2 { class U2CORE_EXPORT HttpFileAdapterFactory: public IOAdapterFactory { Q_OBJECT public: HttpFileAdapterFactory(QObject* p = NULL); virtual IOAdapter* createIOAdapter(); virtual IOAdapterId getAdapterId() const {return BaseIOAdapters::HTTP_FILE;} virtual const QString& getAdapterName() const {return name;} virtual bool isIOModeSupported(IOAdapterMode m) const {return m == IOAdapterMode_Read;} //read-only QNetworkProxy getProxyByUrl( const QUrl & url ) const; virtual TriState isResourceAvailable(const GUrl& ) const {return TriState_Unknown;} protected: QString name; }; class U2CORE_EXPORT GzippedHttpFileAdapterFactory : public HttpFileAdapterFactory { Q_OBJECT public: GzippedHttpFileAdapterFactory( QObject * obj = 0 ); virtual IOAdapter * createIOAdapter(); virtual IOAdapterId getAdapterId() const { return BaseIOAdapters::GZIPPED_HTTP_FILE; } }; class HttpFileAdapter: public IOAdapter { Q_OBJECT public: HttpFileAdapter(HttpFileAdapterFactory* f, QObject* o = NULL); ~HttpFileAdapter() {if (isOpen()) close();} virtual bool open(const GUrl& url, IOAdapterMode m); bool open(const QString& host, const QString & what, const QNetworkProxy & p, quint16 port=80, bool https=false); virtual bool isOpen() const {return (bool)http;} virtual void close(); virtual qint64 readBlock(char* data, qint64 maxSize); virtual qint64 writeBlock(const char* data, qint64 size); virtual bool skip(qint64 nBytes); virtual qint64 left() const; virtual int getProgress() const; virtual GUrl getURL() const {return gurl;} private: void init(); qint64 stored() const; inline bool singleChunk() const { return chunk_list.size() == 1; } inline int firstChunkContains() const {return (singleChunk() ? (isEmpty() ? 0 : end_ptr - begin_ptr) : CHUNKSIZE - begin_ptr);} inline void Empty() { assert( singleChunk() ); begin_ptr = -1; end_ptr = 0; } inline bool isEmpty() const { return -1 == begin_ptr && 0 == end_ptr; } void popFront(); void readFromChunk( char * data, int size ); void skipFromChunk( qint64 size ); qint64 skipAhead( qint64 nBytes ); qint64 waitData( qint64 until ); static const int CHUNKSIZE = 32 * 1024; QLinkedList chunk_list; QByteArray cache; bool is_cached; int begin_ptr; //pointer to the first byte of data in first chunk int end_ptr; //pointer to the first free byte in last chunk QHttp * http; bool badstate; bool is_downloaded; int downloaded; int total; // QMutex condmut; // QWaitCondition cond; QMutex rwmut; QEventLoop loop; GUrl gurl; private slots: void add_data( const QHttpResponseHeader & resp ); void done( bool error ); void state( int state ); //debug only void progress( int done, int total ); }; }//namespace #endif ugene-1.9.8/src/corelibs/U2Core/src/dbi/0000755000175000017500000000000011651544331016332 5ustar ilyailyaugene-1.9.8/src/corelibs/U2Core/src/dbi/U2SqlHelpers.cpp0000644000175000017500000003423311651544331021334 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "U2SqlHelpers.h" #include #include namespace U2 { void SQLiteUtils::addLimit(QString& sql, qint64 offset, qint64 count) { if (count == -1) { return; } sql = sql + QString(" LIMIT %1, %2").arg(offset).arg(count).toAscii(); } #define DB_ID_OFFSET 0 #define TYPE_OFFSET 8 #define DB_EXTRA_OFFSET 10 #define DATAID_MIN_LEN 10 static U2DataId emptyId; static QByteArray emptyBlob; static QString emptyString; U2DataId SQLiteUtils::toU2DataId(qint64 id, U2DataType type, const QByteArray& dbExtra) { if (id == 0) { return emptyId; } assert(sizeof(U2DataType)==2); int extraLen = dbExtra.size(); int len = DATAID_MIN_LEN + extraLen; #if QT_VERSION >= QT_VERSION_CHECK(4, 7, 0) QByteArray res(len, Qt::Uninitialized); #else QByteArray res(len, (char)0); #endif char* data = res.data(); ((qint64*)(data + DB_ID_OFFSET))[0] = id; ((U2DataType*)(data + TYPE_OFFSET))[0] = type; if (extraLen > 0) { qMemCopy(data + DB_EXTRA_OFFSET, dbExtra.constData(), dbExtra.size()); } return res; } quint64 SQLiteUtils::toDbiId(const U2DataId& id) { if (id.size() < DATAID_MIN_LEN) { return 0; } return *(qint64*)(id.constData() + DB_ID_OFFSET); } U2DataType SQLiteUtils::toType(const U2DataId& id) { if (id.size() < DATAID_MIN_LEN) { return 0; } return *(qint64*)(id.constData() + TYPE_OFFSET); } QByteArray SQLiteUtils::toDbExtra(const U2DataId& id) { if (id.size() < DATAID_MIN_LEN) { return emptyId; } return QByteArray(id.constData() + DB_EXTRA_OFFSET, id.length() - DB_EXTRA_OFFSET); } qint64 SQLiteUtils::remove(const QString& table, const QString& field, const U2DataId& id, qint64 expectedRows, DbRef* db, U2OpStatus& os) { SQLiteQuery q(QString("DELETE FROM %1 WHERE %2 = ?1").arg(table).arg(field), db, os); q.bindDataId(1, id); return q.update(expectedRows); } QString SQLiteUtils::text(const U2DataId& id) { QString res = QString("[Id: %1, Type: %2, Extra: %3]").arg(toDbiId(id)).arg(int(toType(id))).arg(toDbExtra(id).constData()); return res; } bool SQLiteUtils::isTableExists(const QString& tableName, DbRef* db, U2OpStatus& os) { SQLiteQuery q("SELECT name FROM sqlite_master WHERE type='table' AND name=?1", db, os); q.bindString(1, tableName); return q.step(); } ////////////////////////////////////////////////////////////////////////// // L10N QString SQLiteL10n::queryError(const QString& err) { return tr("Error querying database: %1").arg(err); } QString SQLiteL10n::tooManyResults() { return tr("Found more results than expected!"); } ////////////////////////////////////////////////////////////////////////// // Query //#define U2_TRACE_SQLITE_QUERIES #ifdef U2_TRACE_SQLITE_QUERIES static int nActiveQueries = 0; static void traceQueryPrepare(const QString& q) { nActiveQueries++; ioLog.trace(QString("SQLite new query! Active queries: %1, Q: %2").arg(nActiveQueries).arg(q)); } static void traceQueryDestroy(const QString& q) { nActiveQueries--; ioLog.trace(QString("SQLite destroying query! Active queries: %1, Q: %2").arg(nActiveQueries).arg(q)); } #endif SQLiteQuery::SQLiteQuery(const QString& _sql, DbRef* d, U2OpStatus& _os) : db(d), os(_os), st(NULL), sql(_sql) { prepare(); #ifdef U2_TRACE_SQLITE_QUERIES traceQueryPrepare(sql); #endif } SQLiteQuery::SQLiteQuery(const QString& _sql, qint64 offset, qint64 count, DbRef* d, U2OpStatus& _os) : db(d), os(_os), st(NULL), sql(_sql) { SQLiteUtils::addLimit(sql, offset, count); prepare(); #ifdef U2_TRACE_SQLITE_QUERIES traceQueryPrepare(sql); #endif } void SQLiteQuery::setError(const QString& err) { ioLog.trace("SQL: error: " + err + " in query: " + sql); if (!os.hasError()) { os.setError(err); } } void SQLiteQuery::prepare() { if (os.hasError()) { return; } QByteArray utf8 = sql.toUtf8(); int rc = sqlite3_prepare_v2(db->handle, utf8.constData() ,utf8.size(), &st, NULL); if (rc != SQLITE_OK) { setError(SQLiteL10n::queryError(sqlite3_errmsg(db->handle))); return; } assert(st!=NULL); } SQLiteQuery::~SQLiteQuery() { if (st != NULL) { int rc = sqlite3_finalize(st); if (rc != SQLITE_OK) { setError(QString("SQLite: Error finalizing statement: ") + SQLiteL10n::queryError(sqlite3_errmsg(db->handle))); return; } } #ifdef U2_TRACE_SQLITE_QUERIES traceQueryDestroy(sql); #endif } bool SQLiteQuery::reset(bool clearBindings) { if (hasError()) { return false; } assert(st != NULL); if (clearBindings) { int rc = sqlite3_clear_bindings(st); if (rc != SQLITE_OK) { setError(QString("SQLite: Error clearing statement bindings: ") + SQLiteL10n::queryError(sqlite3_errmsg(db->handle))); return false; } } int rc = sqlite3_reset(st); if (rc != SQLITE_OK) { setError(QString("SQLite: Error reseting statement: ") + SQLiteL10n::queryError(sqlite3_errmsg(db->handle))); return false; } return true; } bool SQLiteQuery::step() { if (hasError()) { return false; } assert(st != NULL); int rc = sqlite3_step(st); if (rc == SQLITE_DONE) { return false; } else if (rc == SQLITE_ROW) { return true; } setError(SQLiteL10n::tr("Unexpected query result code: %1 (%2)").arg(rc).arg(sqlite3_errmsg(db->handle))); return false; } void SQLiteQuery::ensureDone() { bool done = !step(); if (!done && !hasError()) { setError(SQLiteL10n::tooManyResults()); } } int SQLiteQuery::getInt32(int column) const { if (hasError()) { return -1; } assert(st!=NULL); return sqlite3_column_int(st, column); } qint64 SQLiteQuery::getInt64(int column) const { if (hasError()) { return -1; } assert(st!=NULL); return sqlite3_column_int64(st, column); } double SQLiteQuery::getDouble(int column) const { if (hasError()) { return -1; } assert(st!=NULL); return sqlite3_column_double(st, column); } U2DataId SQLiteQuery::getDataId(int column, U2DataType type, const QByteArray& dbExtra) const { if (hasError()) { return 0; } assert(st!=NULL); U2DataId res = SQLiteUtils::toU2DataId(getInt64(column), type, dbExtra); return res; } U2DataId SQLiteQuery::getDataIdExt(int column) const { if (hasError()) { return emptyId; } assert(st!=NULL); U2DataType type = getInt32(column + 1); if (type == U2Type::Unknown) { return emptyId; } QByteArray dbExtra = getBlob(column + 2); U2DataId res = SQLiteUtils::toU2DataId(getInt64(column), type, dbExtra); return res; } U2DataType SQLiteQuery::getDataType(int column) const { if (hasError()) { return U2Type::Unknown; } assert(st!=NULL); return (U2DataType)sqlite3_column_int(st, column); } QString SQLiteQuery::getString(int column) const { if (hasError()) { return emptyString; } assert(st!=NULL); return QString::fromUtf8((const char*)sqlite3_column_text(st, column)); } QByteArray SQLiteQuery::getCString(int column) const { if (hasError()) { return emptyBlob; } assert(st!=NULL); return QByteArray((const char*)sqlite3_column_text(st, column)); } QByteArray SQLiteQuery::getBlob(int column) const { if (hasError()) { return emptyBlob; } assert(st!=NULL); int nBytes = sqlite3_column_bytes(st, column); if (nBytes == 0) { return emptyBlob; } QByteArray res(static_cast(sqlite3_column_blob(st, column)), nBytes); return res; } // param binding methods void SQLiteQuery::bindDataId(int idx, const U2DataId& val) { bindInt64(idx, SQLiteUtils::toDbiId(val)); } void SQLiteQuery::bindType(int idx, U2DataType type) { bindInt64(idx, type); } void SQLiteQuery::bindString(int idx, const QString& val) { if (hasError()) { return; } assert(st!=NULL); QByteArray utf8 = val.toUtf8(); bool transient = true; int rc = sqlite3_bind_text(st, idx, utf8, utf8.length(), transient ? SQLITE_TRANSIENT : SQLITE_STATIC); if (rc != SQLITE_OK) { setError(SQLiteL10n::tr("Error binding text value! Query: '%1', idx: %2, value: '%3'").arg(sql).arg(idx).arg(val)); return; } } void SQLiteQuery::bindInt32(int idx, qint32 val) { if (hasError()) { return; } assert(st!=NULL); int rc = sqlite3_bind_int(st, idx, val); if (rc != SQLITE_OK) { setError(SQLiteL10n::tr("Error binding int32 value! Query: '%1', idx: %2, value: %3").arg(sql).arg(idx).arg(val)); return; } } void SQLiteQuery::bindDouble(int idx, double val) { if (hasError()) { return; } assert(st!=NULL); int rc = sqlite3_bind_double(st, idx, val); if (rc != SQLITE_OK) { setError(SQLiteL10n::tr("Error binding int64 value! Query: '%1', idx: %2, value: %3").arg(sql).arg(idx).arg(val)); return; } } void SQLiteQuery::bindInt64(int idx, qint64 val) { if (hasError()) { return; } assert(st!=NULL); int rc = sqlite3_bind_int64(st, idx, val); if (rc != SQLITE_OK) { setError(SQLiteL10n::tr("Error binding int64 value! Query: '%1', idx: %2, value: %3").arg(sql).arg(idx).arg(val)); return; } } void SQLiteQuery::bindBool(int idx, bool val) { if (hasError()) { return; } assert(st!=NULL); int b = (val == 0 ? 0 : 1); int rc = sqlite3_bind_int(st, idx, b); if (rc != SQLITE_OK) { setError(SQLiteL10n::tr("Error binding boolean value! Query: '%1', idx: %2, value: %3").arg(sql).arg(idx).arg(b)); return; } } void SQLiteQuery::bindBlob(int idx, const QByteArray& blob, bool transient) { if (hasError()) { return; } assert(st!=NULL); int rc = SQLITE_OK; if (blob.isEmpty()) { rc = sqlite3_bind_zeroblob(st, idx, -1); } else { rc = sqlite3_bind_blob(st, idx, blob.constData(), blob.size(), transient ? SQLITE_TRANSIENT : SQLITE_STATIC); } if (rc != SQLITE_OK) { setError(SQLiteL10n::tr("Error binding blob value! Query: '%1', idx: %2, size: %3").arg(sql).arg(idx).arg(blob.size())); return; } } void SQLiteQuery::execute() { update(-1); } qint64 SQLiteQuery::update(qint64 expectedRows) { if (step()) { qint64 res = getInt64(0); if (expectedRows != -1 && expectedRows != res) { setError(SQLiteL10n::tr("Unexpected row count! Query: '%1', rows: %2").arg(sql).arg(res)); } return res; } return -1; } qint64 SQLiteQuery::insert() { QMutexLocker(&db->lock); // lock db in order to retrieve valid row id for insert execute(); if (hasError()) { return -1; } return getLastRowId(); } U2DataId SQLiteQuery::insert(U2DataType type, const QByteArray& dbExtra) { qint64 lastRowId = insert(); if (hasError()) { return emptyId; } return SQLiteUtils::toU2DataId(lastRowId, type, dbExtra); } qint64 SQLiteQuery::selectInt64() { if (step()) { return getInt64(0); } if (!hasError()) { setError(SQLiteL10n::tr("Query produced no results: %1").arg(sql)); } return -1; } qint64 SQLiteQuery::selectInt64(qint64 defaultValue) { if (step()) { return getInt64(0); } return defaultValue; } U2DataId SQLiteQuery::selectDataId(U2DataType type, const QByteArray& dbExtra) { if (step()) { return SQLiteUtils::toU2DataId(getInt64(1), type, dbExtra); } return emptyId; } QList SQLiteQuery::selectDataIds(U2DataType type, const QByteArray& dbExtra) { QList res; while(step()) { U2DataId id = getDataId(0, type, dbExtra); res.append(id); } return res; } QList SQLiteQuery::selectDataIdsExt() { QList res; while(step()) { U2DataId id = getDataIdExt(0); res.append(id); } return res; } QStringList SQLiteQuery::selectStrings() { QStringList res; while (step()) { QString text = getString(0); res.append(text); } return res; } qint64 SQLiteQuery::getLastRowId() { qint64 sqliteId = sqlite3_last_insert_rowid(db->handle); return sqliteId; } ////////////////////////////////////////////////////////////////////////// // SQLite transaction helper SQLiteTransaction::SQLiteTransaction(DbRef* ref, U2OpStatus& _os) : db(ref), os(_os) { if (db->useTransaction && db->transactionDepth == 0) { db->lock.lock(); int rc = sqlite3_exec(db->handle, "BEGIN TRANSACTION;", NULL, NULL, NULL); if (rc != SQLITE_OK) { db->lock.unlock(); os.setError(SQLiteL10n::queryError(sqlite3_errmsg(db->handle))); return; } } db->transactionDepth++; } SQLiteTransaction::~SQLiteTransaction() { if (db->useTransaction && db->transactionDepth == 1) { int rc; if (os.hasError()) { rc = sqlite3_exec(db->handle, "ROLLBACK TRANSACTION;", NULL, NULL, NULL); } else { rc = sqlite3_exec(db->handle, "COMMIT TRANSACTION;", NULL, NULL, NULL); } db->lock.unlock(); if (rc != SQLITE_OK) { os.setError(SQLiteL10n::queryError(sqlite3_errmsg(db->handle))); } } db->transactionDepth--; } } //namespace ugene-1.9.8/src/corelibs/U2Core/src/dbi/U2DbiUtils.cpp0000644000175000017500000000443311651544331020770 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include #include #include #include namespace U2 { void U2DbiUtils::logNotSupported(U2DbiFeature f, U2Dbi* dbi, U2OpStatus& os) { QString msg = tr("Feature is not supported: %1, dbi: %2").arg(int(f)).arg(dbi == NULL ? QString("") : dbi->getDbiId()); coreLog.error(msg); if (!os.hasError()) { os.setError(msg); } #ifdef _DEBUG if (dbi->getFeatures().contains(f)) { coreLog.error("Calling not-supported method while features is listed in supported features list!"); } assert(0); #endif } ////////////////////////////////////////////////////////////////////////// // U2DbiHandle DbiHandle::DbiHandle(U2DbiFactoryId id, const QString& url, U2OpStatus& _os) : dbi(NULL), os(_os) { dbi = AppContext::getDbiRegistry()->getGlobalDbiPool()->openDbi(id, url, false, os); } DbiHandle::DbiHandle(U2DbiFactoryId id, const QString& url, bool create, U2OpStatus& _os) : dbi(NULL), os(_os) { dbi = AppContext::getDbiRegistry()->getGlobalDbiPool()->openDbi(id, url, create, os); } DbiHandle::DbiHandle(const DbiHandle & dbiHandle_) : dbi(dbiHandle_.dbi), os(dbiHandle_.os) { if (dbi != NULL) { AppContext::getDbiRegistry()->getGlobalDbiPool()->addRef(dbi, os); } } DbiHandle::~DbiHandle() { if (dbi != NULL) { AppContext::getDbiRegistry()->getGlobalDbiPool()->releaseDbi(dbi, os); } } } //namespace ugene-1.9.8/src/corelibs/U2Core/src/dbi/U2DbiRegistry.cpp0000644000175000017500000000767511651544331021513 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include #include #include #include namespace U2 { U2DbiRegistry::U2DbiRegistry(QObject *parent) : QObject(parent) { pool = new U2DbiPool(this); } U2DbiRegistry::~U2DbiRegistry() { qDeleteAll(factories.values()); } bool U2DbiRegistry::registerDbiFactory(U2DbiFactory *factory) { if(factories.contains(factory->getId())) { return false; } factories.insert(factory->getId(), factory); return true; } QList U2DbiRegistry::getRegisteredDbiFactories() const { return factories.keys(); } U2DbiFactory *U2DbiRegistry::getDbiFactoryById(U2DbiFactoryId id) const { return factories.value(id, NULL); } ////////////////////////////////////////////////////////////////////////// // U2DbiPool U2DbiPool::U2DbiPool(QObject* p) : QObject(p) { } U2Dbi* U2DbiPool::openDbi(U2DbiFactoryId id, const QString& url, bool create, U2OpStatus& os) { QMutexLocker m(&lock); ioLog.trace(QString("DbiPool: Opening DBI. Url: %1, factory: %2").arg(url).arg(id)); U2Dbi* dbi = NULL; if (url.isEmpty()) { os.setError(tr("No URL provided!")); return NULL; } if (dbiByUrl.contains(url)) { dbi = dbiByUrl[url]; int cnt = dbiCountersByUrl[url]; dbiCountersByUrl[url] = cnt + 1; } else { U2DbiFactory* f = AppContext::getDbiRegistry()->getDbiFactoryById(id); if (f == NULL) { os.setError(tr("Invalid database type: %1").arg(id)); return NULL; } dbi = f->createDbi(); QHash initProperties; initProperties[U2_DBI_OPTION_URL] = url; if (create) { initProperties[U2_DBI_OPTION_CREATE] = U2_DBI_VALUE_ON; } dbi->init(initProperties, QVariantMap(), os); if (os.hasError()) { delete dbi; return NULL; } dbiByUrl[url] = dbi; dbiCountersByUrl[url] = 1; } return dbi; } void U2DbiPool::addRef(U2Dbi * dbi, U2OpStatus & os) { QMutexLocker m(&lock); QString url = dbi->getInitProperties().value(U2_DBI_OPTION_URL); if (!dbiByUrl.contains(url)) { os.setError(tr("DbiPool: DBI not found! URL: %1").arg(url)); return; } assert(dbiCountersByUrl[url] > 0); int cnt = ++dbiCountersByUrl[url]; ioLog.trace(QString("DbiPool: Increasing reference count. Url: %1, ref-count: %2").arg(url).arg(cnt)); } void U2DbiPool::releaseDbi(U2Dbi* dbi, U2OpStatus& os) { QMutexLocker m(&lock); QString url = dbi->getInitProperties().value(U2_DBI_OPTION_URL); if (!dbiByUrl.contains(url)) { os.setError(tr("DbiPool: DBI not found! URL: %1").arg(url)); return; } int cnt = --dbiCountersByUrl[url]; ioLog.trace(QString("DbiPool: decreasing reference count. Url: %1, ref-count: %2").arg(url).arg(cnt)); if (cnt > 0) { return; } dbi->shutdown(os); delete dbi; dbiByUrl.remove(url); dbiCountersByUrl.remove(url); ioLog.trace(QString("DBIPool: resource is released. Url: %1").arg(url)); } } // namespace U2 ugene-1.9.8/src/corelibs/U2Core/src/dbi/DbiDocumentFormat.cpp0000644000175000017500000001113411651544331022404 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "DbiDocumentFormat.h" #include #include #include #include #include #include #include #include #include namespace U2 { DbiDocumentFormat::DbiDocumentFormat(const U2DbiFactoryId& _id, const DocumentFormatId& _formatId, const QString& _formatName, const QStringList& exts, QObject* p) : DocumentFormat(p, DocumentFormatFlags_W1, exts) { id = _id; formatId = _formatId; formatName = _formatName; supportedObjectTypes+=GObjectTypes::ASSEMBLY; formatFlags|=DocumentFormatFlag_NoPack; formatFlags|=DocumentFormatFlag_NoFullMemoryLoad; } Document* DbiDocumentFormat::createNewDocument(IOAdapterFactory* io, const QString& url, const QVariantMap& fs) { Document* d = DocumentFormat::createNewDocument(io, url, fs); return d; } static void renameObjectsIfNamesEqual(QList & objs) { for(int i = 0; i < objs.size(); ++i) { int howManyEquals = 0; for(int j = i + 1; j < objs.size(); ++j) { if(objs[i]->getGObjectName() == objs[j]->getGObjectName()) { objs[j]->setGObjectName(QString("%1 %2").arg(objs[j]->getGObjectName()).arg(++howManyEquals)); } } } } Document* DbiDocumentFormat::loadDocument(IOAdapter* io, TaskStateInfo& ts, const QVariantMap& fs, DocumentLoadMode) { //1. open db //2. read all assembly & sequence objects //3. close db QString url = io->getURL().getURLString(); DbiHandle handle(id, url, true, ts); if(ts.isCoR()) { return NULL; } U2ObjectDbi* odbi = handle.dbi->getObjectDbi(); QList objectIds = odbi->getObjects("/", 0, U2_DBI_NO_LIMIT, ts); if (ts.isCoR()) { return NULL; } QList objects; U2DataRef ref; ref.dbiId = url; ref.factoryId = id; foreach(U2DataId id, objectIds) { U2DataType objectType = handle.dbi->getEntityTypeById(id); switch (objectType) { case U2Type::Assembly: { ref.entityId = id; U2OpStatusImpl status; QString name = handle.dbi->getAssemblyDbi()->getAssemblyObject(id, status).visualName; if(status.hasError()) { coreLog.error(status.getError()); break; } if(name.isEmpty()) { assert(false); name = "Assembly"; } objects.append(new AssemblyObject(ref, name, QVariantMap())); break; } default: // do nothing break; } } renameObjectsIfNamesEqual(objects); Document* d = new Document(this, io->getFactory(), io->getURL(), objects, fs); return d; } void DbiDocumentFormat::storeDocument(Document* d, TaskStateInfo& ts, IOAdapter*) { // 1. get db // 2. call sync QString url = d->getURLString(); DbiHandle handle(id, url, true, ts); if (!ts.isCoR()) { handle.dbi->flush(ts); } } RawDataCheckResult DbiDocumentFormat::checkRawData(const QByteArray& rawData, const GUrl& url) const { U2DbiFactory* f = AppContext::getDbiRegistry()->getDbiFactoryById(id); if (f != NULL) { QHash props; props[U2_DBI_OPTION_URL] = url.getURLString(); U2OpStatusImpl os; bool ok = f->isValidDbi(props, rawData, os) && !os.hasError(); if (ok) { return FormatDetection_Matched; } } return FormatDetection_NotMatched; } }//namespace ugene-1.9.8/src/corelibs/U2Core/src/dbi/U2SqlHelpers.h0000644000175000017500000002244311651544331021001 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_SQL_HELPERS_H_ #define _U2_SQL_HELPERS_H_ #include #include #include #include struct sqlite3; struct sqlite3_stmt; namespace U2 { class SQLiteQuery; class U2CORE_EXPORT DbRef { public: DbRef() : handle(NULL), lock(QMutex::Recursive), useTransaction(true), transactionDepth(0){} DbRef(sqlite3* db) : handle(db), lock(QMutex::Recursive), useTransaction(true), transactionDepth(0) {} sqlite3* handle; QMutex lock; bool useTransaction; int transactionDepth; }; class U2CORE_EXPORT SQLiteUtils { public: /** Removes from the table all records with 'field' == id Checks 'expectedRowCount' the same way as 'update' method */ static qint64 remove(const QString& table, const QString& field, const U2DataId& id, qint64 expectedRows, DbRef* db, U2OpStatus& os); /** Converts internal database id to U2DataId*/ static U2DataId toU2DataId(qint64 id, U2DataType type, const QByteArray& dbExtra = QByteArray()); /** Converts U2DataId to internal database id*/ static quint64 toDbiId(const U2DataId& id); /** Extracts type info from U2DataId */ static U2DataType toType(const U2DataId& id); /** Extracts table info from U2DataId */ static QByteArray toDbExtra(const U2DataId& id); /** Adds limit operator to the sql query */ static void addLimit(QString& sql, qint64 offset, qint64 count); /** Return textual representation of the id */ static QString text(const U2DataId& id); /** Checks if the table exists in database */ static bool isTableExists(const QString& tableName, DbRef* db, U2OpStatus& os); }; /** Common localization messages for SQLiteDBI*/ class U2CORE_EXPORT SQLiteL10n : public QObject { Q_OBJECT public: static QString queryError(const QString& err); static QString tooManyResults(); }; /** SQLite query wrapper. Uses prepared statement internally An optimized and simplified interface for U2DBI needs. */ class U2CORE_EXPORT SQLiteQuery { private: public: /** Constructs prepared statement for SQLiteDB If failed the error message is written to 'os' */ SQLiteQuery(const QString& sql, DbRef* d, U2OpStatus& os); SQLiteQuery(const QString& sql, qint64 offset, qint64 count, DbRef* d, U2OpStatus& os); /** Releases all resources associated with the statement */ ~SQLiteQuery(); ////////////////////////////////////////////////////////////////////////// // Statement/query state manipulation methods /** Clears all bindings and resets statement */ bool reset(bool clearBindings = true); /** Executes next step of the statement Returns true there are more results to fetch and no error occurs */ bool step(); /** Ensures that there are no more results in result set Sets error message if more results are available */ void ensureDone(); ////////////////////////////////////////////////////////////////////////// // param binding methods /** Binds U2DataId */ void bindDataId(int idx, const U2DataId& val); /** Binds U2DataType */ void bindType(int idx, U2DataType type); /** Binds 32bit integer value*/ void bindInt32(int idx, qint32 val); /** Binds 64bit integer value*/ void bindInt64(int idx, qint64 val); /** Binds 64bit real value*/ void bindDouble(int idx, double val); /** Binds bool value */ void bindBool(int idx, bool val); /** Binds text string */ void bindString(int idx, const QString& val); /** Binds BLOB */ void bindBlob(int idx, const QByteArray& blob, bool transient = true); ////////////////////////////////////////////////////////////////////////// // result retrieval methods U2DataId getDataId(int column, U2DataType type, const QByteArray& dbExtra = QByteArray()) const; U2DataId getDataIdExt(int column) const; U2DataType getDataType(int column) const; int getInt32(int column) const; qint64 getInt64(int column) const; double getDouble(int column) const; QString getString(int column) const; QByteArray getCString(int column) const; QByteArray getBlob(int column) const; bool getBool(int column) const {return getInt32(column) != 0;} ////////////////////////////////////////////////////////////////////////// // Utility methods /** Executes update and returns last row id*/ qint64 insert(); /** Executes update and returns last row id converted to U2DataId using type info*/ U2DataId insert(U2DataType type, const QByteArray& dbExtra = QByteArray()); /** Executes query */ void execute(); /** Executes update and returns number of rows affected. Fails if result count != expectedRowCount 'expectedRowCount' == 1 disables row-count check */ qint64 update(qint64 expectedRows = -1); /** Selects a single int64 value */ qint64 selectInt64(); /** Selects a single int64 value, if no results found returns default value */ qint64 selectInt64(qint64 defaultValue); /** Selects a single U2DataId value */ U2DataId selectDataId(U2DataType type, const QByteArray& dbExtra = QByteArray()); /** Select list of ids and adds 'type' parameter to construct U2DataId */ QList selectDataIds(U2DataType type, const QByteArray& dbExtra = QByteArray()); /** Select id(col=0), type(col=1) pairs and constructs U2DataId */ QList selectDataIdsExt(); /** Select list of strings */ QStringList selectStrings(); ////////////////////////////////////////////////////////////////////////// // Query info methods const QString& getQueryText() const {return sql;} void setError(const QString& err); bool hasError() const {return os.hasError();} void setOpStatus(U2OpStatus& _os) {os = _os;} U2OpStatus& getOpStatus() {return os;} DbRef* getDb() const {return db;} private: /** Returns last insert row*/ qint64 getLastRowId(); void prepare(); DbRef* db; U2OpStatus& os; sqlite3_stmt* st; QString sql; }; /** Helper class to mark transaction regions */ class U2CORE_EXPORT SQLiteTransaction { public: SQLiteTransaction(DbRef* db, U2OpStatus& os); virtual ~SQLiteTransaction(); private: DbRef* db; U2OpStatus& os; }; /** Data loader adapter for SqlQueryIterator */ template class SqlRSLoader { public: virtual ~SqlRSLoader(){} virtual T load(SQLiteQuery* q) = 0; }; /** Filter for SqlRSIterator. Checks if value must be filtered out from the result */ template class SqlRSFilter { public: virtual ~SqlRSFilter(){} virtual bool filter(const T&) = 0; }; /** SQL query result set iterator */ template class SqlRSIterator : public U2DbiIterator { public: SqlRSIterator(SQLiteQuery* q, SqlRSLoader* l, SqlRSFilter* f, const T& d, U2OpStatus& o) : query(q), loader(l), filter(f), defaultValue(d), os(o), endOfStream(false) { fetchNext(); } virtual ~SqlRSIterator() { delete filter; delete loader; delete query; } virtual bool hasNext() { return !endOfStream; } virtual T next() { if (endOfStream) { assert(0); return defaultValue; } currentResult = nextResult; fetchNext(); return currentResult; } virtual T peek() { if (endOfStream) { assert(0); return defaultValue; } return nextResult; } private: void fetchNext() { do { if (!query->step()) { endOfStream = true; return; } nextResult = loader->load(query); } while (filter != NULL && !filter->filter(nextResult)); } SQLiteQuery* query; SqlRSLoader* loader; SqlRSFilter* filter; T defaultValue; U2OpStatus& os; bool endOfStream; T nextResult; T currentResult; }; class SqlDataIdRSLoader : public SqlRSLoader { public: SqlDataIdRSLoader(U2DataType _type, const QByteArray& _dbExra = QByteArray()) : type(_type), dbExtra(_dbExra){} U2DataId load(SQLiteQuery* q) { return q->getDataId(0, type, dbExtra);} protected: U2DataType type; QByteArray dbExtra; }; } //namespace #endif ugene-1.9.8/src/corelibs/U2Core/src/dbi/DbiDocumentFormat.h0000644000175000017500000000404511651544331022054 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_SQLITE_DOCUMENT_FORMAT_H_ #define _U2_SQLITE_DOCUMENT_FORMAT_H_ #include #include #include namespace U2 { /** UGENE v1 wrapper over DBI (UGENE v2 data access) interface */ class U2CORE_EXPORT DbiDocumentFormat: public DocumentFormat { Q_OBJECT public: DbiDocumentFormat(const U2DbiFactoryId& id, const DocumentFormatId& formatId, const QString& formatName, const QStringList& exits, QObject* p = NULL); virtual DocumentFormatId getFormatId() const {return formatId;} virtual const QString& getFormatName() const {return formatName;} virtual Document* createNewDocument(IOAdapterFactory* io, const QString& url, const QVariantMap& fs = QVariantMap()); virtual Document* loadDocument(IOAdapter* io, TaskStateInfo& ti, const QVariantMap& fs, DocumentLoadMode mode = DocumentLoadMode_Whole); virtual void storeDocument(Document* d, TaskStateInfo& ts, IOAdapter* io); virtual RawDataCheckResult checkRawData(const QByteArray& rawData, const GUrl& url = GUrl()) const; private: QString formatName; U2DbiFactoryId id; DocumentFormatId formatId; }; }//namespace #endif ugene-1.9.8/src/corelibs/U2Core/src/cmdline/0000755000175000017500000000000011651544331017207 5ustar ilyailyaugene-1.9.8/src/corelibs/U2Core/src/cmdline/CMDLineHelpProvider.h0000644000175000017500000000545511651544331023130 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_CMD_LINE_HELP_PROVIDER_ #define _U2_CMD_LINE_HELP_PROVIDER_ #include "U2Core/global.h" namespace U2 { class U2CORE_EXPORT CMDLineHelpProvider { public: CMDLineHelpProvider( const QString & _fullName, // Name of the option (e.g. "version") const QString & _shortDescription, // Description shown in the options list const QString & _fullDescription = QString(), // Description shown in the option's help const QString & _argsDescription = QString(), // Description of the option arguments const QString & _shortName = QString()) // Short name of the option (e.g. "v") : fullName(_fullName), shortDescription(_shortDescription), fullDescription(_fullDescription), argsDescription(_argsDescription), shortName(_shortName) { assert((_shortDescription.length() < 49) && ("The length of the short" " description must fit into the options list. If you need to create" " a short description longer than 49 characters, then register two" " or more CMDLineHelpProvider with the same fullName. They will be" " placed on different lines in the options list.")); } QString getHelpSectionFullName() const {return fullName;} QString getHelpSectionShortDescription() const { return shortDescription; } QString getHelpSectionFullDescription() const { return fullDescription; } QString getHelpSectionArgsDescription() const { return argsDescription; } QString getHelpSectionShortName() const {return shortName;} QString getHelpSectionNames() const { QString ret = fullName; if (!shortName.isEmpty()) { ret += " | -" + shortName; } return ret; } private: QString fullName; QString shortDescription; QString fullDescription; QString argsDescription; QString shortName; }; // CMDLineHelpProvider }//namespace #endif ugene-1.9.8/src/corelibs/U2Core/src/cmdline/CMDLineCoreOptions.cpp0000644000175000017500000000564111651544331023321 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include #include #include #include "CMDLineCoreOptions.h" namespace U2 { const QString CMDLineCoreOptions::INI_FILE = "ini-file"; const QString CMDLineCoreOptions::SUITE_URLS = "test-suite"; const QString CMDLineCoreOptions::API_TEST_URLS = "api-test-suite"; const QString CMDLineCoreOptions::TEST_REPORT = "test-report"; const QString CMDLineCoreOptions::HELP = "help"; const QString CMDLineCoreOptions::HELP_SHORT = "h"; const QString CMDLineCoreOptions::TRANSLATION = "lang"; const QString CMDLineCoreOptions::TEST_THREADS = "test-threads"; const QString CMDLineCoreOptions::TEAMCITY_OUTPUT = "log-teamcity-out"; const QString CMDLineCoreOptions::LOG_FORMAT = "log-format"; const QString CMDLineCoreOptions::LOG_LEVEL = "log-level"; const QString CMDLineCoreOptions::LAUNCH_TEST = "gui-test"; const QString CMDLineCoreOptions::USAGE = "usage"; void CMDLineCoreOptions::initHelp() { CMDLineRegistry * cmdLineRegistry = AppContext::getCMDLineRegistry(); assert( NULL != cmdLineRegistry ); CMDLineHelpProvider * helpSection = new CMDLineHelpProvider( HELP, tr( "Shows help information." ), "", // No full description "", // No arguments HELP_SHORT); CMDLineHelpProvider * loadSettingsFileSection = new CMDLineHelpProvider( INI_FILE, tr( "Loads UGENE configuration." ), tr( "Loads configuration from the specified .ini file. By default the UGENE.ini file is used." ), tr( "" )); CMDLineHelpProvider * translSection = new CMDLineHelpProvider( TRANSLATION, tr( "Specifies the language to use." ), tr( "Specifies the language to use. The following values are available: CS, EN, RU." ), tr( "" )); cmdLineRegistry->registerCMDLineHelpProvider( helpSection ); cmdLineRegistry->registerCMDLineHelpProvider( loadSettingsFileSection ); cmdLineRegistry->registerCMDLineHelpProvider( translSection ); } } // U2 ugene-1.9.8/src/corelibs/U2Core/src/cmdline/CMDLineUtils.cpp0000644000175000017500000000624711651544331022160 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include #include "CMDLineUtils.h" #include "CMDLineCoreOptions.h" namespace U2 { /*************************************************** * CMDLineRegistryUtils ***************************************************/ int CMDLineRegistryUtils::getParameterIndex( const QString & paramName, int startWith ) { QList params; setCMDLineParams( params ); int sz = params.size(); for( int i = qMax( 0, startWith ); i < sz; ++i ) { if( params[i].first == paramName ) { return i; } } return -1; } QStringList CMDLineRegistryUtils::getParameterValues( const QString & paramName, int startWith ) { QList params; setCMDLineParams( params ); QStringList res; int sz = params.size(); int paramIdx = getParameterIndex( paramName, startWith ); if( -1 == paramIdx ) { // no such parameter return res; } for( int i = paramIdx; i < sz; ++i ) { res << params[i].second; if( i + 1 < sz && !params[i + 1].first.isEmpty() ) { break; } } return res; } QStringList CMDLineRegistryUtils::getParameterValuesByWords( const QString & paramName, int startWith ) { QStringList words; QStringList res = getParameterValues( paramName, startWith ); QStringList::const_iterator it = res.constBegin(); while( it != res.constEnd() ) { words << it->split( QRegExp("\\s"), QString::SkipEmptyParts ); ++it; } return words; } QStringList CMDLineRegistryUtils::getPureValues( int startWithIdx ) { QList params; setCMDLineParams( params ); QStringList res; int sz = params.size(); for( int i = qMax( 0, startWithIdx ); i < sz; ++i ) { const StringPair & currentPair = params[i]; if( currentPair.first.isEmpty() ) { res << currentPair.second; } else { break; } } return res; } void CMDLineRegistryUtils::setCMDLineParams( QList & to ) { CMDLineRegistry * cmdlineRegistry = AppContext::getCMDLineRegistry(); if( cmdlineRegistry != NULL ) { to = cmdlineRegistry->getParameters(); } } /*************************************************** * CMDLineUtils ***************************************************/ void CMDLineUtils::init() { CMDLineCoreOptions::initHelp(); } } // U2 ugene-1.9.8/src/corelibs/U2Core/src/cmdline/CMDLineCoreOptions.h0000644000175000017500000000335511651544331022766 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_CMDLINE_OPTIONS_H_ #define _U2_CMDLINE_OPTIONS_H_ #include #include #include namespace U2 { // QObject needed for translations class U2CORE_EXPORT CMDLineCoreOptions : public QObject { Q_OBJECT public: static const QString INI_FILE; static const QString SUITE_URLS; static const QString API_TEST_URLS; static const QString TEST_REPORT; static const QString HELP; static const QString HELP_SHORT; static const QString TRANSLATION; static const QString TEST_THREADS; static const QString TEAMCITY_OUTPUT; static const QString LOG_FORMAT; static const QString LOG_LEVEL; static const QString LAUNCH_TEST; static const QString USAGE; public: // initialize help for core cmdline options static void initHelp(); }; // CMDLineCoreOptions } // U2 #endif // _U2_CMDLINE_OPTIONS_H_ ugene-1.9.8/src/corelibs/U2Core/src/cmdline/CMDLineRegistry.h0000644000175000017500000000467511651544331022340 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_CMD_LINE_REGISTRY_ #define _U2_CMD_LINE_REGISTRY_ #include #include #include namespace U2 { class CMDLineHelpProvider; typedef QPair StringPair; /* Reads command arguments into UGENE's command line parameters Convention: --paramName=paramValue -> (paramName, paramValue) -paramName paramValue -> (paramName, paramValue) paramValue1 paramValue2 -> ("", paramValue1), ("", paramValue2) */ class U2CORE_EXPORT CMDLineRegistry : public QObject { Q_OBJECT public: CMDLineRegistry(const QStringList& arguments); virtual ~CMDLineRegistry(); const QList & getParameters() const; // as they were in cmdline. Empty keys also here QStringList getOrderedParameterNames() const; // finding starts at startsWithIdx bool hasParameter( const QString & paramName, int startsWithIdx = 0 ) const; // returns value of first appearance from startWithIdx of paramName key QString getParameterValue( const QString & paramName, int startWithIdx = 0 ) const; void registerCMDLineHelpProvider(CMDLineHelpProvider* provider); void unregisterCMDLineHelpProvider(CMDLineHelpProvider* provider); const QList& listCMDLineHelpProviders() const { return helpProviders; } private: QList params; // pairs (paramName, paramValue) ordered as in the cmdline QList helpProviders; // sorted by section name }; // CMDLineRegistry } //namespace U2 #endif // _U2_CMD_LINE_REGISTRY_ ugene-1.9.8/src/corelibs/U2Core/src/cmdline/CMDLineRegistry.cpp0000644000175000017500000001106711651544331022664 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "CMDLineRegistry.h" #include "CMDLineHelpProvider.h" #include "CMDLineCoreOptions.h" namespace U2 { /*************************************************** * CMDLineRegistry ***************************************************/ const QString SINGLE_DASH = "-"; const QString DOUBLE_DASH = "--"; const QString EQUALS = "="; static bool isDoubleDashParameter(const QString& val) { return val.startsWith( DOUBLE_DASH ) && val.length() > 2 && val.at(2).isLetter(); } static bool isSingleDashParameter(const QString& val) { return val.startsWith( SINGLE_DASH ) && val.length() > 1 && val.at(1).isLetter(); } static bool tryParseDoubleDashParameter(const QString& argument, QString& paramName, QString ¶mValue) { if (!isDoubleDashParameter(argument)) { return false; } int nameEndIdx = argument.indexOf( EQUALS ); if (nameEndIdx == -1) { paramName = argument.mid(2); } else { paramName = argument.mid(2, nameEndIdx - 2); paramValue = argument.mid(nameEndIdx+1); } return true; } static bool tryParseSingleDashParameter(const QString& argument, const QString& nextArgument, QString& paramName, QString ¶mValue) { if (!isSingleDashParameter(argument)) { return false; } paramName = argument.mid(1); if (!isDoubleDashParameter(nextArgument) && !isSingleDashParameter(nextArgument)) { paramValue = nextArgument; } return true; } CMDLineRegistry::CMDLineRegistry(const QStringList& arguments) { int sz = arguments.size(); for( int i = 0; i < sz; i++ ) { const QString& argument = arguments.at( i ); StringPair pair; if ( !tryParseDoubleDashParameter(argument, pair.first, pair.second) ) { QString nextArgument; if (i < sz - 1) { nextArgument = arguments.at(i + 1); } if ( tryParseSingleDashParameter(argument, nextArgument, pair.first, pair.second) ) { if (!pair.second.isEmpty()) { i++; } } else { pair.second = argument; } } params << pair; } } CMDLineRegistry::~CMDLineRegistry() { qDeleteAll( helpProviders ); } const QList & CMDLineRegistry::getParameters() const { return params; } QStringList CMDLineRegistry::getOrderedParameterNames() const { QStringList res; QList::const_iterator it = params.constBegin(); while( it != params.constEnd() ) { res << it->first; ++it; } return res; } bool CMDLineRegistry::hasParameter( const QString & paramName, int startWithIdx ) const { int sz = params.size(); for( int i = qMax(0, startWithIdx); i < sz; ++i ) { const StringPair& param = params[i]; if( param.first == paramName ) { return true; } } return false; } QString CMDLineRegistry::getParameterValue( const QString & paramName, int startWithIdx ) const { int sz = params.size(); for( int i = qMax(0, startWithIdx); i < sz; ++i ) { const StringPair& param = params[i]; if( param.first == paramName ) { return param.second; } } return QString(); } static bool providerNameComparator(const CMDLineHelpProvider* p1, const CMDLineHelpProvider* p2) { return p1->getHelpSectionFullName().compare(p2->getHelpSectionFullName()) > 0; } void CMDLineRegistry::registerCMDLineHelpProvider(CMDLineHelpProvider* provider) { helpProviders.append(provider); qStableSort(helpProviders.begin(), helpProviders.end(), providerNameComparator); } void CMDLineRegistry::unregisterCMDLineHelpProvider(CMDLineHelpProvider* provider) { helpProviders.removeOne(provider); } } //namespace ugene-1.9.8/src/corelibs/U2Core/src/cmdline/CMDLineUtils.h0000644000175000017500000000372611651544331021624 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_CMDLINE_UTILS_H_ #define _U2_CMDLINE_UTILS_H_ #include #include #include namespace U2 { class U2CORE_EXPORT CMDLineRegistryUtils { public: // -1 if not found static int getParameterIndex( const QString & paramName, int startWith = 0 ); // in case: '-t a b c' return {a, b, c} static QStringList getParameterValues( const QString & paramName, int startWith = 0 ); // in case '-t "a b" c' return {a, b, c} not {"a b", c} static QStringList getParameterValuesByWords( const QString & paramName, int startWith = 0 ); // return list of all values that doesn't have keys ("", paramValue) // search starts at startWithIdx, stops at first (paramKey, paramValue) pair // by default, search starts at 1 because at params[0] is usually ("", programName) pair static QStringList getPureValues( int startWithIdx = 1 ); private: static void setCMDLineParams( QList & to ); }; // CMDLineRegistryUtils class U2CORE_EXPORT CMDLineUtils { public: static void init(); }; // CMDLineUtils } // U2 #endif // _U2_CMDLINE_UTILS_H_ ugene-1.9.8/src/corelibs/U2Core/src/tasks/0000755000175000017500000000000011651544332016722 5ustar ilyailyaugene-1.9.8/src/corelibs/U2Core/src/tasks/ExportToNewFileFromIndexTask.h0000644000175000017500000000415411651544332024574 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_EXPORT_TO_NEW_FILE_FROM_INDEX_TASK_H_ #define _U2_EXPORT_TO_NEW_FILE_FROM_INDEX_TASK_H_ #include #include #include namespace U2 { class IOAdapter; class GetDocumentFromIndexTask; class SaveDocumentStreamingTask; /* * Exported documents may be written to filename not in docNums list order */ class U2CORE_EXPORT ExportToNewFileFromIndexTask : public Task { Q_OBJECT public: ExportToNewFileFromIndexTask( const UIndex& index, const QList< int >& docNums, const QString& filename ); ~ExportToNewFileFromIndexTask(); virtual void prepare(); virtual ReportResult report(); private: QList< Task* > getDocTaskFinished( GetDocumentFromIndexTask* t ); QList< Task* > saveDocTaskFinished( SaveDocumentStreamingTask* t ); protected: virtual QList< Task* > onSubTaskFinished( Task* subTask ); IOAdapter* getOpenedIOAdapter(const QString& url); private: UIndex index; QList< int > docNums; QString exportFilename; QList< Document* > docsToSave; IOAdapter* io; SaveDocumentStreamingTask* saveCurDocTask; }; // ExportToNewFileFromIndexTask } // U2 #endif // _U2_EXPORT_TO_NEW_FILE_FROM_INDEX_TASK_H_ ugene-1.9.8/src/corelibs/U2Core/src/tasks/RemoveDocumentTask.h0000644000175000017500000000305011651544332022650 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_REMOVE_DOCUMENT_TASK_H_ #define _U2_REMOVE_DOCUMENT_TASK_H_ #include #include namespace U2 { class Document; class Project; class StateLock; class U2CORE_EXPORT RemoveMultipleDocumentsTask : public Task { Q_OBJECT public: RemoveMultipleDocumentsTask(Project* p, const QList& docs, bool saveModifiedDocs, bool useGUI); ~RemoveMultipleDocumentsTask(); virtual void prepare(); ReportResult report(); private: QPointer p; bool saveModifiedDocs; bool useGUI; StateLock* lock; QList > docPtrs; }; }//namespace #endif ugene-1.9.8/src/corelibs/U2Core/src/tasks/SaveDocumentStreamingTask.h0000644000175000017500000000301711651544332024166 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_SAVE_DOCUMENT_STREAMING_TASK_H_ #define _U2_SAVE_DOCUMENT_STREAMING_TASK_H_ #include namespace U2 { class Document; class StateLock; class IOAdapter; class U2CORE_EXPORT SaveDocumentStreamingTask : public Task { Q_OBJECT public: // io - opened io adapter SaveDocumentStreamingTask( Document* doc, IOAdapter* io ); ~SaveDocumentStreamingTask(); virtual void prepare(); virtual void run(); ReportResult report(); Document* getDocument() const; private: StateLock* lock; Document* doc; IOAdapter* io; }; // SaveDocumentStreamingTask } // U2 #endif // _U2_SAVE_DOCUMENT_STREAMING_TASK_H_ ugene-1.9.8/src/corelibs/U2Core/src/tasks/SaveDocumentTask.cpp0000644000175000017500000001724411651544332022656 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "SaveDocumentTask.h" #include #include #include #include #include #include #include #include #include #include #include #include namespace U2 { SaveDocumentTask::SaveDocumentTask(Document* _doc, IOAdapterFactory* _io, const GUrl& _url) : Task(tr("Save document"), TaskFlag_None), doc(_doc), iof(_io), url(_url), flags(SaveDoc_Overwrite) { assert(doc!=NULL); if (iof == NULL) { iof = doc->getIOAdapterFactory(); } if (url.isEmpty()) { url = doc->getURLString(); } lock = NULL; } SaveDocumentTask::SaveDocumentTask(Document* _doc, SaveDocFlags f, const QSet& _excludeFileNames) : Task(tr("Save document"), TaskFlag_None), doc(_doc), iof(doc->getIOAdapterFactory()), url(doc->getURL()), flags(f), excludeFileNames(_excludeFileNames) { assert(doc!=NULL); } void SaveDocumentTask::prepare() { if (doc.isNull()) { setError("Document was removed"); return; } lock = new StateLock(getTaskName()); doc->lockState(lock); } void SaveDocumentTask::run() { if (flags.testFlag(SaveDoc_Roll) && !GUrlUtils::renameFileWithNameRoll(url.getURLString(), stateInfo, excludeFileNames, &coreLog)) { return; } coreLog.info(tr("Saving document %1\n").arg(url.getURLString())); DocumentFormat* df = doc->getDocumentFormat(); if (flags.testFlag(SaveDoc_Append)) { std::auto_ptr io(iof->createIOAdapter()); if (!io->open(url, IOAdapterMode_Append)) { setError(L10N::errorOpeningFileWrite(url)); return; } df->storeDocument(doc, stateInfo, io.get()); } else { df->storeDocument(doc, stateInfo, iof, url); } } Task::ReportResult SaveDocumentTask::report() { if (lock!=NULL) { assert(!doc.isNull()); doc->unlockState(lock); delete lock; lock = NULL; } if (hasError() || doc.isNull()) { return ReportResult_Finished; } if (url == doc->getURL() && iof == doc->getIOAdapterFactory()) { doc->makeClean(); } if (doc) { doc->setLastUpdateTime(); } if (flags.testFlag(SaveDoc_DestroyAfter)) { doc->unload(); delete doc; } return Task::ReportResult_Finished; } ////////////////////////////////////////////////////////////////////////// /// save multiple SaveMiltipleDocuments::SaveMiltipleDocuments(const QList& docs, bool askBeforeSave) : Task(tr("Save multiple documents"), TaskFlag_NoRun) { bool saveAll = false; foreach(Document* doc, docs) { bool save=true; if (askBeforeSave) { QMessageBox::StandardButtons buttons = QMessageBox::StandardButtons(QMessageBox::Yes) | QMessageBox::No; if (docs.size() > 1) { buttons = buttons | QMessageBox::YesToAll | QMessageBox::NoToAll; } QMessageBox::StandardButton res = saveAll ? QMessageBox::YesToAll : QMessageBox::question(QApplication::activeWindow(), tr("Question?"), tr("Save document: %1").arg(doc->getURLString()), buttons, QMessageBox::Yes); if (res == QMessageBox::NoToAll) { break; } if (res == QMessageBox::YesToAll) { saveAll = true; } if (res == QMessageBox::No) { save = false; } } if (save) { addSubTask(new SaveDocumentTask(doc)); } } } QList SaveMiltipleDocuments::findModifiedDocuments(const QList& docs) { QList res; foreach(Document* doc, docs) { if (doc->isTreeItemModified()) { res.append(doc); } } return res; } ////////////////////////////////////////////////////////////////////////// // save a copy and add to project SaveCopyAndAddToProjectTask::SaveCopyAndAddToProjectTask(Document* doc, IOAdapterFactory* iof, const GUrl& _url) : Task (tr("Save a copy %1").arg(url.getURLString()), TaskFlags_NR_FOSCOE), url(_url) { origURL = doc->getURL(); df = doc->getDocumentFormat(); hints = doc->getGHintsMap(); saveTask = new SaveDocumentTask(doc, iof, url); saveTask->setExcludeFileNames(DocumentUtils::getNewDocFileNameExcludesHint()); addSubTask(saveTask); foreach(GObject* obj, doc->getObjects()) { info.append(UnloadedObjectInfo(obj)); } } Task::ReportResult SaveCopyAndAddToProjectTask::report() { if (hasError() || isCanceled()) { return ReportResult_Finished; } Project* p = AppContext::getProject(); if (p == NULL) { setError(tr("No active project found")); return ReportResult_Finished; } if (p->isStateLocked()) { setError(tr("Project is locked")); return ReportResult_Finished; } const GUrl& url = saveTask->getURL(); if (p->findDocumentByURL(url)) { setError(tr("Document is already added to the project %1").arg(url.getURLString())); return ReportResult_Finished; } Document* doc = new Document(df, saveTask->getIOAdapterFactory(), url, info, hints); foreach(GObject* o, doc->getObjects()) { GObjectUtils::updateRelationsURL(o, origURL, url); } doc->setModified(false); p->addDocument(doc); return ReportResult_Finished; } /////////////////////////////////////////////////////////////////////////// // relocate task RelocateDocumentTask::RelocateDocumentTask(const GUrl& fu, const GUrl& tu) : Task (tr("Relocate document %1 -> %2").arg(fu.getURLString()).arg(tu.getURLString()), TaskFlag_NoRun), fromURL(fu), toURL(tu) { } Task::ReportResult RelocateDocumentTask::report() { Project* p = AppContext::getProject(); if (p == NULL) { setError(tr("No active project found")); return ReportResult_Finished; } if (p->isStateLocked()) { setError(tr("Project is locked")); return ReportResult_Finished; } Document* d = p->findDocumentByURL(fromURL); if (d == NULL) { setError(L10N::errorDocumentNotFound(fromURL)); return ReportResult_Finished; } if (d->isLoaded()) { setError(tr("Only unloaded objects can be relocated")); return ReportResult_Finished; } d->setURL(toURL); if (fromURL.baseFileName() == d->getName() || fromURL.fileName() == d->getName()) { // if document name is default -> update it too d->setName(toURL.baseFileName()); } //update relations to new url foreach(Document* d, p->getDocuments()) { foreach(GObject* o, d->getObjects()) { GObjectUtils::updateRelationsURL(o, fromURL, toURL); } } return ReportResult_Finished; } }//namespace ugene-1.9.8/src/corelibs/U2Core/src/tasks/RemoveAnnotationsTask.cpp0000644000175000017500000000672411651544332023735 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "RemoveAnnotationsTask.h" #include "LoadDocumentTask.h" #include #include #include namespace U2 { RemoveAnnotationsTask::RemoveAnnotationsTask( AnnotationTableObject* ao, const QString& gName ) :Task("RemoveAnnotationsTask",TaskFlag_NoRun), aobj(ao), groupName(gName), pos(0) { annsSet = false; assert(ao != NULL); } void RemoveAnnotationsTask::prepare() { if (aobj == NULL) { stateInfo.setError(tr("Annotation object is not valid")); return; } /*subGroup = aobj->getRootGroup()->getSubgroup(groupName, false); if (subGroup == NULL) { stateInfo.setError(tr("Subgroup %1 is not found").arg(groupName)); return; } QSet annotations; subGroup->findAllAnnotationsInGroupSubTree(annotations); toDelete = annotations.toList(); GTIMER(c1,t1,"RemoveAnnotationsTask::report"); if (hasError() || isCanceled() ) { return ; } if (aobj->isStateLocked()) { stateInfo.setDescription(tr("Waiting for object lock released")); return ; } stateInfo.setDescription(""); int size = toDelete.size(); if (size == 0) { return ; }*/ // aobj->removeAnnotationsInGroup(toDelete, subGroup); } Task::ReportResult RemoveAnnotationsTask::report() { //aobj->releaseLocker(); if(!annsSet) { if(aobj->isLocked()) { return ReportResult_CallMeAgain; } else { subGroup = aobj->getRootGroup()->getSubgroup(groupName, false); if (subGroup == NULL) { return ReportResult_Finished; } QSet annotations; subGroup->findAllAnnotationsInGroupSubTree(annotations); toDelete = annotations.toList(); if (hasError() || isCanceled() ) { return ReportResult_Finished; } if (aobj->isStateLocked()) { stateInfo.setDescription(tr("Waiting for object lock released")); return ReportResult_Finished; } int size = toDelete.size(); if (size == 0) { return ReportResult_Finished; } annsSet = true; aobj->removeAnnotationsInGroup(toDelete, subGroup); return ReportResult_CallMeAgain; } } else { if(aobj->isLocked()) { return ReportResult_CallMeAgain; } else { aobj->cleanAnnotations(); annsSet = false; } } return ReportResult_Finished; } } // namespace ugene-1.9.8/src/corelibs/U2Core/src/tasks/CreateAnnotationTask.cpp0000644000175000017500000000652511651544332023517 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "CreateAnnotationTask.h" #include "LoadDocumentTask.h" #include #include #include #include namespace U2 { CreateAnnotationsTask::CreateAnnotationsTask(AnnotationTableObject* _ao, const QString& _g, QSharedDataPointer _data) : Task(tr("Create annotations"), TaskFlag_NoRun), aobj(_ao), groupName(_g), pos(0) { aData << _data; aRef.objName = _ao->getGObjectName(); } CreateAnnotationsTask::CreateAnnotationsTask(AnnotationTableObject* _ao, const QString& _g, QList _data) : Task(tr("Create annotations"), TaskFlag_NoRun), aobj(_ao), groupName(_g), pos(0) { aData = _data; aRef.objName = _ao->getGObjectName(); } CreateAnnotationsTask::CreateAnnotationsTask(const GObjectReference& r, const QString& _g, QList _data) : Task(tr("Create annotations"), TaskFlag_NoRun), aRef(r), groupName(_g), pos(0) { aData << _data; GObject* ao = (GObjectUtils::selectObjectByReference(aRef, UOF_LoadedAndUnloaded)); if (ao!=NULL && ao->isUnloaded()) { addSubTask(new LoadUnloadedDocumentTask(ao->getDocument())); } } Task::ReportResult CreateAnnotationsTask::report() { GTIMER(c1,t1,"CreateAnnotationsTask::report"); if (hasError() || isCanceled() || aData.size() == 0) { return ReportResult_Finished; } AnnotationTableObject* ao = NULL; if (aRef.isValid()) { assert(aobj.isNull()); ao = qobject_cast(GObjectUtils::selectObjectByReference(aRef, UOF_LoadedOnly)); } else { ao = aobj.data(); } if (ao == NULL) { stateInfo.setError(tr("Annotation object '%1' not found in active project: %2").arg(aRef.objName).arg(aRef.docUrl)); return ReportResult_Finished; } if (ao->isStateLocked()) { stateInfo.setDescription(tr("Waiting for object lock released")); return ReportResult_CallMeAgain; } stateInfo.setDescription(""); int brk = qMin(pos+10000, aData.size()); for (int i = pos; i < brk; i++) { annotations.append(new Annotation(aData.at(i))); } GTIMER(c2,t2,"CreateAnnotationsTask::report [addAnnotations]"); ao->addAnnotations(annotations.mid(pos), groupName); tpm = Progress_Manual; stateInfo.progress = 100*brk/aData.size(); if (brk != aData.size()) { pos = brk; return ReportResult_CallMeAgain; } return ReportResult_Finished; } } // namespace ugene-1.9.8/src/corelibs/U2Core/src/tasks/TLSTask.cpp0000644000175000017500000000476611651544332020730 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "TLSTask.h" namespace U2 { QThreadStorage TLSUtils::tls; /************************************************************************/ /* TaskLocalData */ /************************************************************************/ TLSContext* TLSUtils::current( QString contextId ) { Q_UNUSED(contextId) TLSContextRef* ref = tls.localData(); if (ref!=NULL) { assert(ref->ctx!=NULL); assert(ref->ctx->id == contextId); return ref->ctx; } assert(0); return NULL; } void TLSUtils::bindToTLSContext(TLSContext *ctx) { assert(ctx!=NULL); assert(!tls.hasLocalData()); tls.setLocalData(new TLSContextRef(ctx)); } void TLSUtils::detachTLSContext() { TLSContextRef* ref = tls.localData(); assert(ref!=NULL && ref->ctx!=NULL); ref->ctx = NULL; tls.setLocalData(NULL); } /************************************************************************/ /* TLSTask */ /************************************************************************/ TLSTask::TLSTask( const QString& _name, TaskFlags _flags, bool _deleteContext) :Task(_name, _flags), taskContext(NULL), deleteContext(_deleteContext) { } void TLSTask::prepare() { taskContext = createContextInstance(); } void TLSTask::run() { TLSUtils::bindToTLSContext(taskContext); try { _run(); } catch(...) { stateInfo.setError("_run() throws exception"); } TLSUtils::detachTLSContext(); } TLSTask::~TLSTask() { if(deleteContext) delete taskContext; taskContext = NULL; } } //namespace U2 ugene-1.9.8/src/corelibs/U2Core/src/tasks/LoadRemoteDocumentTask.cpp0000644000175000017500000004313311651544332024007 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "LoadRemoteDocumentTask.h" namespace U2 { const QString NCBI_ESEARCH_URL("http://eutils.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi?db=%1&term=%2&tool=UGENE"); const QString NCBI_EFETCH_URL("http://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi?db=%1&id=%2&retmode=text&rettype=%3&tool=UGENE"); const QString GENBANK_DNA("NCBI GenBank (DNA sequence)"); const QString GENBANK_PROTEIN("NCBI protein sequence database"); const QString PDB("PDB"); const QString SWISS_PROT("SWISS-PROT"); const QString UNIPROTKB_SWISS_PROT("UniProtKB/Swiss-Prot"); const QString UNIPROTKB_TREMBL("UniProtKB/TrEMBL"); // Entrez tools variables #define GENBANK_NUCLEOTIDE_ID "nucleotide" #define GENBANK_PROTEIN_ID "protein" #define GENBANK_FORMAT "gb" #define FASTA_FORMAT "fasta" LoadRemoteDocumentTask::LoadRemoteDocumentTask( const GUrl& fileUrl) : Task("LoadRemoteDocument", TaskFlags_NR_FOSCOE | TaskFlag_MinimizeSubtaskErrorText), copyDataTask(NULL), loadDocumentTask(NULL), doc(NULL) { sourceUrl = fileUrl; fileName = sourceUrl.fileName(); GCOUNTER( cvar, tvar, "LoadRemoteDocumentTask" ); } LoadRemoteDocumentTask::LoadRemoteDocumentTask( const QString& accId, const QString& dbNm) : Task("LoadRemoteDocument", TaskFlags_NR_FOSCOE | TaskFlag_MinimizeSubtaskErrorText), copyDataTask(NULL), loadDocumentTask(NULL), doc(NULL), accNumber(accId), dbName(dbNm) { RemoteDBRegistry::getRemoteDBRegistry().convertAlias(dbName); sourceUrl = GUrl(RemoteDBRegistry::getRemoteDBRegistry().getURL(accId, dbName)); if (sourceUrl.isHyperLink()) { fileName = sourceUrl.fileName(); } else { format = getFileFormat(dbName); fileName = accNumber + "." + format; } GCOUNTER( cvar, tvar, "LoadRemoteDocumentTask" ); } LoadRemoteDocumentTask::LoadRemoteDocumentTask(const QString & accId, const QString & dbNm, const QString & fullPathDir) : Task("LoadRemoteDocument", TaskFlags_NR_FOSCOE | TaskFlag_MinimizeSubtaskErrorText), copyDataTask(NULL), loadDocumentTask(NULL), doc(NULL), accNumber(accId), dbName(dbNm) { RemoteDBRegistry::getRemoteDBRegistry().convertAlias(dbName); sourceUrl = GUrl(RemoteDBRegistry::getRemoteDBRegistry().getURL(accId, dbName)); if( sourceUrl.isHyperLink() ) { fileName = sourceUrl.fileName(); } else { format = getFileFormat(dbName); accNumber.replace(";",","); QStringList accIds = accNumber.split(","); if (accIds.size() == 1 ) { fileName = accNumber + "." + format; } else if (accIds.size() > 1) { fileName = accIds.first() + "_misc." + format; } } fullPath = QDir::cleanPath(fullPathDir); fullPath = !fullPath.endsWith("/") ? fullPath + "/" : fullPath; GCOUNTER( cvar, tvar, "LoadRemoteDocumentTask" ); } QString LoadRemoteDocumentTask::getFileFormat(const QString & dbName) { QString dbId = RemoteDBRegistry::getRemoteDBRegistry().getDbEntrezName(dbName); if (dbId == GENBANK_NUCLEOTIDE_ID || dbId == GENBANK_PROTEIN_ID) { return GENBANK_FORMAT; } else { return FASTA_FORMAT; } } bool LoadRemoteDocumentTask::prepareDownloadDirectory(QString &path) { if (!QDir(path).exists()) { if (path == getDefaultDownloadDirectory()) { // Creating default directory if it doesn't exist if (!QDir().mkpath(path)) { return false; } } else { // We do not touch user specified directories from here return false; } } return true; } QString LoadRemoteDocumentTask::getDefaultDownloadDirectory() { QString path = AppContext::getAppSettings()->getUserAppsSettings()->getDownloadDirPath(); return path; } void LoadRemoteDocumentTask::prepare() { if (fileName.isEmpty()) { stateInfo.setError("Incorrect key identifier!"); return; } if (fullPath.isEmpty()) { fullPath = getDefaultDownloadDirectory(); } if (!prepareDownloadDirectory(fullPath)) { setError(QString("Directory %1 does not exist").arg(fullPath)); return; } fullPath += "/" + fileName; // Check if the file has already been downloaded RecentlyDownloadedCache* cache = AppContext::getRecentlyDownloadedCache(); if( cache != NULL && cache->contains(fileName)) { QString cachedUrl = cache->getFullPath(fileName); if( fullPath == cachedUrl ) { if ( initLoadDocumentTask() ) { addSubTask(loadDocumentTask); } return; } // else: user wants to save doc to new file -> download it from db } if (sourceUrl.isHyperLink()) { IOAdapterFactory* iof = AppContext::getIOAdapterRegistry()->getIOAdapterFactoryById(BaseIOAdapters::HTTP_FILE); IOAdapterFactory * iow = AppContext::getIOAdapterRegistry()->getIOAdapterFactoryById(BaseIOAdapters::LOCAL_FILE); copyDataTask = new CopyDataTask(iof, sourceUrl, iow, fullPath); addSubTask(copyDataTask); } else { assert(sourceUrl.isLocalFile()); QString dbId = RemoteDBRegistry::getRemoteDBRegistry().getDbEntrezName(dbName); if(dbId.isEmpty()) { setError(tr("Undefined database: '%1'").arg(dbName)); return; } else { loadDataFromEntrezTask = new LoadDataFromEntrezTask(dbId, accNumber,format,fullPath); addSubTask(loadDataFromEntrezTask); } } } Task::ReportResult LoadRemoteDocumentTask::report() { return ReportResult_Finished; } QList LoadRemoteDocumentTask::onSubTaskFinished( Task* subTask ) { QList subTasks; if (subTask->hasError()) { if( subTask == copyDataTask || subTask == loadDataFromEntrezTask ) { setError(tr("Cannot find %1 in %2 database").arg(accNumber).arg(dbName) + ": " + subTask->getError()); } return subTasks; } if (subTask == copyDataTask || subTask == loadDataFromEntrezTask) { if (initLoadDocumentTask()) { subTasks.append(loadDocumentTask); if (!subTask->isCanceled()) { RecentlyDownloadedCache * cache = AppContext::getRecentlyDownloadedCache(); if(cache != NULL) { cache->append(fullPath); } } else if (subTask == copyDataTask) { QFile notLoadedFile(fullPath); notLoadedFile.remove(); } } } else if ( subTask == loadDocumentTask) { doc = loadDocumentTask->getDocument(); } return subTasks; } bool LoadRemoteDocumentTask::initLoadDocumentTask( ) { Q_ASSERT(!fullPath.isEmpty()); // Check if the document has been loaded Project* proj = AppContext::getProject(); if (proj != NULL) { Document* foundDoc = proj->findDocumentByURL(fullPath); if (foundDoc != NULL) { doc = foundDoc; return false; } } // Detect format if (formatId.isEmpty()) { QList formats = DocumentUtils::detectFormat(fullPath); if (formats.isEmpty()) { stateInfo.setError("Unknown file format!"); return false; } else { formatId = formats.first().format->getFormatId(); } } IOAdapterFactory * iow = AppContext::getIOAdapterRegistry()->getIOAdapterFactoryById(BaseIOAdapters::LOCAL_FILE); loadDocumentTask = new LoadDocumentTask(formatId, fullPath, iow); return true; } Document* LoadRemoteDocumentTask::getDocument() { return doc; } //////////////////////////////////////////////////////////////////////////////////////////////////// RecentlyDownloadedCache::RecentlyDownloadedCache() { QStringList fileNames = AppContext::getAppSettings()->getUserAppsSettings()->getRecentlyDownloadedFileNames(); foreach (const QString& path, fileNames) { QFileInfo info(path); if (info.exists()) { append(path); } } } bool RecentlyDownloadedCache::contains(const QString& fileName) { if (!urlMap.contains(fileName)) { return false; } else { QString fullPath=getFullPath(fileName); QFile cachedFile(fullPath); return cachedFile.exists(); } } void RecentlyDownloadedCache::append( const QString& fileName ) { QFileInfo info(fileName); urlMap.insert(info.fileName(), fileName); } void RecentlyDownloadedCache::remove(const QString& fullPath) { urlMap.remove(QFileInfo(fullPath).fileName()); } QString RecentlyDownloadedCache::getFullPath( const QString& fileName ) { Q_ASSERT(urlMap.contains(fileName)); return urlMap.value(fileName); } RecentlyDownloadedCache::~RecentlyDownloadedCache() { //TODO: cache depends on AppSettings! get rid of this dependency! QStringList fileNames = urlMap.values(); AppSettings* settings = AppContext::getAppSettings(); Q_ASSERT(settings != NULL); UserAppsSettings* us = settings->getUserAppsSettings(); Q_ASSERT(us != NULL); us->setRecentlyDownloadedFileNames(fileNames); } ////////////////////////////////////////////////////////////////////////// LoadDataFromEntrezTask::LoadDataFromEntrezTask( const QString& dbId, const QString& accNum, const QString& retType, const QString& path ) : Task("LoadDataFromEntrez", TaskFlags_FOSCOE | TaskFlag_MinimizeSubtaskErrorText), db(dbId), accNumber(accNum), fullPath(path), format(retType) { } LoadDataFromEntrezTask::~LoadDataFromEntrezTask() { delete loop; delete networkManager; } void LoadDataFromEntrezTask::run() { stateInfo.progress = 0; ioLog.trace("Load data from Entrez started..."); loop = new QEventLoop; networkManager = new QNetworkAccessManager(); connect(networkManager, SIGNAL(finished(QNetworkReply*)), this, SLOT(sl_replyFinished(QNetworkReply*))); NetworkConfiguration* nc = AppContext::getAppSettings()->getNetworkConfiguration(); //TODO: use eSearch functionality for better request handling // Step zero: search for global Entrez index /*ioLog.trace("Request for global entrez index info..."); QString traceSearchUrl= QString(NCBI_ESEARCH_URL).arg(db).arg(accNumber); ioLog.trace(traceSearchUrl); QUrl request( NCBI_ESEARCH_URL.arg(db).arg(accNumber) ); QString rUrl(request.toString()); ioLog.trace(QString("Sending request: %1").arg(rUrl)); searchReply = networkManager->get(QNetworkRequest( request )); connect(searchReply, SIGNAL(error(QNetworkReply::NetworkError)), this, SLOT(sl_onError(QNetworkReply::NetworkError))); loop->exec(); if (resultIndex.isEmpty()) { stateInfo.setError("Result not found"); } if (stateInfo.hasError() ) { return; } ioLog.trace(QString("Global index is %1").arg(resultIndex)); */ ioLog.trace("Downloading file..."); // Step one: download the file QString traceFetchUrl = QString(NCBI_EFETCH_URL).arg(db).arg(accNumber).arg(format); QNetworkProxy proxy = nc->getProxyByUrl(traceFetchUrl); networkManager->setProxy(proxy); ioLog.trace(traceFetchUrl); QUrl requestUrl(NCBI_EFETCH_URL.arg(db).arg(accNumber).arg(format)); downloadReply = networkManager->get(QNetworkRequest(requestUrl)); connect(downloadReply, SIGNAL(error(QNetworkReply::NetworkError)), this, SLOT(sl_onError(QNetworkReply::NetworkError))); connect( downloadReply, SIGNAL(uploadProgress( qint64, qint64 )), this, SLOT(sl_uploadProgress(qint64,qint64)) ); loop->exec(); ioLog.trace("Download finished."); QByteArray result = downloadReply->readAll(); if ( ( result.size() < 100 ) && result.contains("Nothing has been found")) { setError(tr("Sequence with ID=%1 is not found.").arg(accNumber)); return; } QFile downloadedFile(fullPath); if (!downloadedFile.open(QIODevice::WriteOnly)) { stateInfo.setError("Cannot open file to write!"); return; } downloadedFile.write(result); downloadedFile.close(); } void LoadDataFromEntrezTask::sl_replyFinished( QNetworkReply* reply ) { if (reply == searchReply) { QXmlInputSource source(reply); ESearchResultHandler* handler = new ESearchResultHandler; xmlReader.setContentHandler(handler); xmlReader.setErrorHandler(handler); bool ok = xmlReader.parse(source); if (!ok) { assert(0); stateInfo.setError("Parsing eSearch result failed"); } else { resultIndex = handler->getResultIndex(); } delete handler; } else if (reply == downloadReply) { } loop->exit(); } void LoadDataFromEntrezTask::sl_onError( QNetworkReply::NetworkError error ) { stateInfo.setError(QString("NetworkReply error %1").arg(error)); loop->exit(); } void LoadDataFromEntrezTask::sl_uploadProgress( qint64 bytesSent, qint64 bytesTotal ) { stateInfo.progress = bytesSent/ bytesTotal * 100; } ////////////////////////////////////////////////////////////////////////// bool ESearchResultHandler::startElement( const QString &namespaceURI, const QString &localName, const QString &qName, const QXmlAttributes &attributes ) { Q_UNUSED(namespaceURI); Q_UNUSED(localName); Q_UNUSED(attributes); if (!metESearchResult && qName != "eSearchResult") { errorStr = QObject::tr("This is not ESearch result!"); return false; } if ("eSearchResult" == qName) { metESearchResult = true; } curText.clear(); return true; } bool ESearchResultHandler::endElement( const QString &namespaceURI, const QString &localName, const QString &qName ) { Q_UNUSED(namespaceURI); Q_UNUSED(localName); if ("Id" == qName) { index = curText; } return true; } ESearchResultHandler::ESearchResultHandler() { metESearchResult = false; } bool ESearchResultHandler::characters( const QString &str ) { curText += str; return true; } bool ESearchResultHandler::fatalError( const QXmlParseException &exception ) { Q_UNUSED(exception); assert(0); return false; } ////////////////////////////////////////////////////////////////////////// RemoteDBRegistry::RemoteDBRegistry() { queryDBs.insert(GENBANK_DNA, GENBANK_NUCLEOTIDE_ID); queryDBs.insert(GENBANK_PROTEIN, GENBANK_PROTEIN_ID); aliases.insert("genbank", GENBANK_DNA); aliases.insert("genbank-protein", GENBANK_PROTEIN); aliases.insert("pdb", PDB); aliases.insert("swissprot", SWISS_PROT); aliases.insert("uniprot", UNIPROTKB_SWISS_PROT); const QMap& entries = AppContext::getDBXRefRegistry()->getEntries(); foreach(const DBXRefInfo& info, entries.values()) { if (!info.fileUrl.isEmpty()) { httpDBs.insert(info.name, info.fileUrl); } } hints.insert(GENBANK_DNA, QObject::tr("Use Genbank DNA accession number. For example: NC_001363 or D11266")); hints.insert(GENBANK_PROTEIN, QObject::tr("Use Genbank protein accession number. For example: AAA59172.1")); hints.insert(PDB, QObject::tr("Use PDB molecule four-letter identifier. For example: 3INS or 1CRN")); hints.insert(SWISS_PROT, QObject::tr("Use SWISS-PROT accession number. For example: Q9IGQ6 or A0N8V2")); hints.insert(UNIPROTKB_SWISS_PROT, QObject::tr("Use UniProtKB/Swiss-Prot accession number. For example: P16152")); hints.insert(UNIPROTKB_TREMBL, QObject::tr("Use UniProtKB/TrEMBL accession number. For example: D0VTW9")); } RemoteDBRegistry& RemoteDBRegistry::getRemoteDBRegistry() { static RemoteDBRegistry registry; return registry; } QList RemoteDBRegistry::getDBs() { return ( queryDBs.keys() + httpDBs.keys() ); } QString RemoteDBRegistry::getURL( const QString& accId, const QString& dbName ) { QString result(""); if (httpDBs.contains(dbName)) { result = QString(httpDBs.value(dbName)).arg(accId); } return result; } QString RemoteDBRegistry::getDbEntrezName( const QString& dbName ) { return queryDBs.value(dbName); } QString RemoteDBRegistry::getHint( const QString& dbName ) { if (hints.contains(dbName)) { return hints.value(dbName); } else { return QObject::tr("Use %1 unique identifier.").arg(dbName); } } void RemoteDBRegistry::convertAlias( QString& dbName ) { if (aliases.contains(dbName)) { dbName = aliases.value(dbName); } } } //namespace ugene-1.9.8/src/corelibs/U2Core/src/tasks/RemovePartFromSequenceTask.h0000644000175000017500000000352711651544332024326 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_REMOVE_PART_FROM_SEQUENCE_TASK_H_ #define _U2_REMOVE_PART_FROM_SEQUENCE_TASK_H_ #include #include #include #include namespace U2 { class U2CORE_EXPORT RemovePartFromSequenceTask : public Task { Q_OBJECT public: RemovePartFromSequenceTask(DocumentFormatId _dfId, DNASequenceObject *_seqObj, U2Region _regionToDelete, U2AnnotationUtils::AnnotationStrategyForResize _str = U2AnnotationUtils::AnnotationStrategyForResize_Resize, const GUrl& _url = GUrl(), bool _mergeAnnotations = false); virtual Task::ReportResult report(); private: void fixAnnotations(); void preparationForSave(); DocumentFormatId dfId; bool mergeAnnotations; Document *curDoc; Document *newDoc; bool save; GUrl url; U2AnnotationUtils::AnnotationStrategyForResize strat; QList docs; DNASequenceObject *seqObj; U2Region regionToDelete; }; }//ns #endif ugene-1.9.8/src/corelibs/U2Core/src/tasks/TaskSignalMapper.cpp0000644000175000017500000000323611651544332022637 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "TaskSignalMapper.h" namespace U2 { void TaskSignalMapper::sl_taskStateChanged() { QObject* o = sender(); if (o) { Task* t = qobject_cast(o); if (t) { switch (t->getState()) { case Task::State_Prepared: emit si_taskPrepared(t); break; case Task::State_Running: emit si_taskRunning(t); break; case Task::State_Finished: emit si_taskFinished(t); if (t->hasError() || t->hasSubtasksWithErrors()) { emit si_taskFailed(t); } else { emit si_taskSucceeded(t); } break; case Task::State_New: break; } } } } } //namespace ugene-1.9.8/src/corelibs/U2Core/src/tasks/LoadRemoteDocumentTask.h0000644000175000017500000001210411651544332023446 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_LOAD_REMOTE_DOCUMENT_TASK_H_ #define _U2_LOAD_REMOTE_DOCUMENT_TASK_H_ #include #include #include #include #include #include #include #include #include namespace U2 { class Document; class CopyDataTask; class LoadDocumentTask; class LoadDataFromEntrezTask; class U2CORE_EXPORT RemoteDBRegistry { RemoteDBRegistry(); QMap queryDBs; QMap httpDBs; QMap hints; QMap aliases; public: QString getURL(const QString& accId, const QString& dbName); QString getDbEntrezName(const QString& dbName); void convertAlias(QString& dbName); QList getDBs(); QString getHint(const QString& dbName); //TODO: move this to AppContext static RemoteDBRegistry& getRemoteDBRegistry(); }; class U2CORE_EXPORT RecentlyDownloadedCache : public QObject { Q_OBJECT QMap urlMap; void loadCacheFromSettings(); void saveCacheToSettings(); public: RecentlyDownloadedCache(); ~RecentlyDownloadedCache(); bool contains(const QString& fileName); void append(const QString& fullPath); void remove(const QString& fullPath); QString getFullPath(const QString& fileName); void clear() { urlMap.clear(); } }; class U2CORE_EXPORT LoadRemoteDocumentTask : public Task { Q_OBJECT public: static QString getFileFormat(const QString & dbName); bool prepareDownloadDirectory(QString &path); static QString getDefaultDownloadDirectory(); public: LoadRemoteDocumentTask(const GUrl& url); LoadRemoteDocumentTask(const QString& accId, const QString& dbName); LoadRemoteDocumentTask(const QString & accId, const QString & dbName, const QString & fullPathDir); virtual void prepare(); virtual ReportResult report(); QString getLocalUrl(){ return fullPath; } Document* getDocument(); QString getAccNumber() const { return accNumber; } QString getDBName() const { return dbName; } protected: QList onSubTaskFinished(Task* subTask); private: bool openView; bool initLoadDocumentTask(); DocumentFormatId formatId; CopyDataTask* copyDataTask; LoadDocumentTask* loadDocumentTask; Document* doc; LoadDataFromEntrezTask* loadDataFromEntrezTask; GUrl sourceUrl; QString accNumber, dbName, format; QString fileName, fullPath; }; // This task makes queries to NCBI Entrez search engine, using eTools // First step: query eSearch to get global Entrez index // Second step: query eFetch to download file by index // About eTools: http://www.ncbi.nlm.nih.gov/bookshelf/br.fcgi?book=coursework&part=eutils class U2CORE_EXPORT LoadDataFromEntrezTask : public Task { Q_OBJECT public: LoadDataFromEntrezTask(const QString& dbId, const QString& accNumber, const QString& retType, const QString& fullPath); ~LoadDataFromEntrezTask(); virtual void run(); public slots: void sl_replyFinished(QNetworkReply* reply); void sl_onError(QNetworkReply::NetworkError error); void sl_uploadProgress( qint64 bytesSent, qint64 bytesTotal); private: QEventLoop* loop; QNetworkReply* searchReply; QNetworkReply* downloadReply; QNetworkAccessManager* networkManager; QXmlSimpleReader xmlReader; QString db, accNumber; QString resultIndex; QString fullPath, format; }; // Helper class to parse NCBI Entrez eSearch results class ESearchResultHandler : public QXmlDefaultHandler { bool metESearchResult; QString errorStr; QString curText; QString index; public: ESearchResultHandler(); bool startElement(const QString &namespaceURI, const QString &localName, const QString &qName, const QXmlAttributes &attributes); bool endElement(const QString &namespaceURI, const QString &localName, const QString &qName); bool characters(const QString &str); bool fatalError(const QXmlParseException &exception); QString errorString() const { return errorStr; } QString getResultIndex() const { return index; } }; } //namespace #endif // _U2_LOAD_REMOTE_DOCUMENT_TASK_H_ ugene-1.9.8/src/corelibs/U2Core/src/tasks/ReverseSequenceTask.h0000644000175000017500000000303611651544332023024 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_REVERSE_SEQUENCE_TASK_H_ #define _U2_REVERSE_SEQUENCE_TASK_H_ #include #include namespace U2 { class DNASequenceObject; class AnnotationTableObject; class DNATranslation; class DNASequenceSelection; class U2CORE_EXPORT ReverseSequenceTask : public Task { Q_OBJECT public: ReverseSequenceTask(DNASequenceObject* dnaObj, QList annotations, DNASequenceSelection* selection, DNATranslation* complTT); ReportResult report(); private: DNASequenceObject* seqObj; QList aObjs; DNASequenceSelection* selection; DNATranslation* complTr; }; }//ns #endif // _U2_REVERSE_SEQUENCE_TASK_H_ ugene-1.9.8/src/corelibs/U2Core/src/tasks/RemoveDocumentTask.cpp0000644000175000017500000000602711651544332023212 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "RemoveDocumentTask.h" #include "SaveDocumentTask.h" #include #include #include namespace U2 { RemoveMultipleDocumentsTask::RemoveMultipleDocumentsTask(Project* _p, const QList& _docs, bool _saveModifiedDocs, bool _useGUI) : Task(tr("Remove document"), TaskFlag_NoRun), p(_p), saveModifiedDocs(_saveModifiedDocs), useGUI(_useGUI) { assert(!_docs.empty()); assert(p!=NULL); foreach(Document* d, _docs) { docPtrs.append(d); } lock = new StateLock(getTaskName()); } RemoveMultipleDocumentsTask::~RemoveMultipleDocumentsTask() { assert(lock == NULL); } void RemoveMultipleDocumentsTask::prepare() { p->lockState(lock); if (p->isTreeItemModified() && saveModifiedDocs) { QList docs; foreach(Document* d, docPtrs) { if (d!=NULL) { docs.append(d); } } QList modifiedDocs = SaveMiltipleDocuments::findModifiedDocuments(docs); if (!modifiedDocs.isEmpty()) { addSubTask(new SaveMiltipleDocuments(modifiedDocs, useGUI)); } } } Task::ReportResult RemoveMultipleDocumentsTask::report() { if (lock!=NULL) { assert(!p.isNull()); p->unlockState(lock); delete lock; lock = NULL; Task* t = getSubtaskWithErrors(); if (t!=NULL) { stateInfo.setError(t->getError()); return Task::ReportResult_Finished; } } if (p.isNull()) { return Task::ReportResult_Finished; } if (p->isStateLocked()) { return Task::ReportResult_CallMeAgain; } foreach(Document* doc, docPtrs) { if ( doc != NULL ) { // check for "stay-alive" locked objects if ( doc->hasLocks(StateLockableTreeFlags_ItemAndChildren, StateLockFlag_LiveLock) ) { setError( tr("Cannot remove document %1, since it is locked by some task.").arg(doc->getName()) ); continue; } else { p->removeDocument(doc); } } } return Task::ReportResult_Finished; } }//namespace ugene-1.9.8/src/corelibs/U2Core/src/tasks/AddPartToSequenceTask.cpp0000644000175000017500000001567411651544332023601 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "AddPartToSequenceTask.h" #include #include #include #include #include #include #include #include #include #include #include #include #include namespace U2{ AddPartToSequenceTask::AddPartToSequenceTask(DocumentFormatId _dfId, DNASequenceObject *_seqObj, int _insertPos, DNASequence _seqPart, U2AnnotationUtils::AnnotationStrategyForResize _strat, const GUrl& _url, bool _mergeAnnotations) :Task(tr("Insert subsequence"), TaskFlag_NoRun), dfId(_dfId), mergeAnnotations(_mergeAnnotations), save(true), url(_url), strat(_strat), seqObj(_seqObj), insertPos(_insertPos), seqPart(_seqPart) { curDoc = seqObj->getDocument(); GCOUNTER( cvar, tvar, "Add part to sequence" ); if (url == curDoc->getURL() || _url.isEmpty()){ save = false; return; } } Task::ReportResult AddPartToSequenceTask::report(){ if(insertPos > seqObj->getSequenceLen()){ algoLog.error(tr("Insertion position is out of bounds")); return ReportResult_Finished; } Project *p = AppContext::getProject(); if(p != NULL){ docs = p->getDocuments(); } if(!docs.contains(curDoc)){ docs.append(curDoc); } if(curDoc->isStateLocked()){ coreLog.error(tr("Document is locked")); return ReportResult_Finished; } if(save){ preparationForSave(); } DNASequence sequence = seqObj->getDNASequence(); if(seqPart.length() == 0) { return ReportResult_Finished; } assert(sequence.alphabet == seqPart.alphabet); sequence.seq.insert(insertPos, seqPart.constData()); seqObj->setSequence(sequence); fixAnnotations(); if(save){ QList tasks; IOAdapterFactory* iof = AppContext::getIOAdapterRegistry()->getIOAdapterFactoryById(BaseIOAdapters::url2io(url)); tasks.append(new SaveDocumentTask(seqObj->getDocument(), iof, url)); Project *p = AppContext::getProject(); if(p != NULL){ tasks.append(new AddDocumentTask(newDoc)); } AppContext::getTaskScheduler()->registerTopLevelTask(new MultiTask("Save document and add it to project (optional)", tasks)); } return ReportResult_Finished; } void AddPartToSequenceTask::fixAnnotations(){ int len = seqPart.length(); foreach(Document *d, docs){ QList annotationTablesList = d->findGObjectByType(GObjectTypes::ANNOTATION_TABLE); foreach(GObject *table, annotationTablesList){ AnnotationTableObject *ato = (AnnotationTableObject*)table; if(ato->hasObjectRelation(seqObj, GObjectRelationRole::SEQUENCE)){ QList annList = ato->getAnnotations(); foreach(Annotation *an, annList){ QVector locs = an->getRegions(); U2AnnotationUtils::fixLocationsForInsertedRegion(insertPos, len, locs, strat); if (!locs.isEmpty()) { an->replaceRegions(locs); } else { ato->removeAnnotation(an); } } } } } } void AddPartToSequenceTask::preparationForSave(){ IOAdapterFactory* iof = AppContext::getIOAdapterRegistry()->getIOAdapterFactoryById(BaseIOAdapters::url2io(url)); DocumentFormat *df = AppContext::getDocumentFormatRegistry()->getFormatById(dfId);; if (iof == NULL) { return; } QList objList = curDoc->getObjects(); if(mergeAnnotations){ DNASequenceObject *oldObj = seqObj; newDoc = df->createNewDocument(iof, url, curDoc->getGHintsMap()); foreach(GObject* go, objList){ if(df->isObjectOpSupported(newDoc, DocumentFormat::DocObjectOp_Add, go->getGObjectType()) && (go->getGObjectType() != GObjectTypes::SEQUENCE || go == seqObj) && go->getGObjectType() != GObjectTypes::ANNOTATION_TABLE){ GObject *cl = go->clone(); newDoc->addObject(cl); if(go == seqObj){ seqObj = qobject_cast(cl); } GObjectUtils::updateRelationsURL(cl, curDoc->getURL(), url); } } AnnotationTableObject *newDocAto = new AnnotationTableObject("Annotations"); newDoc->addObject(newDocAto); newDocAto->addObjectRelation(seqObj, GObjectRelationRole::SEQUENCE); foreach(Document *d, docs){ QList annotationTablesList = d->findGObjectByType(GObjectTypes::ANNOTATION_TABLE); foreach(GObject *table, annotationTablesList){ AnnotationTableObject *ato = (AnnotationTableObject*)table; if(ato->hasObjectRelation(oldObj, GObjectRelationRole::SEQUENCE)){ foreach(Annotation *ann, ato->getAnnotations()){ QStringList groupNames; foreach(AnnotationGroup* gr,ann->getGroups()){ groupNames.append(gr->getGroupName()); } newDocAto->addAnnotation(new Annotation(ann->data()), groupNames); } } } } }else{ newDoc = df->createNewDocument(iof, url, curDoc->getGHintsMap()); foreach(GObject* go, objList){ if(df->isObjectOpSupported(newDoc, DocumentFormat::DocObjectOp_Add, go->getGObjectType())){ GObject *cl = go->clone(); newDoc->addObject(cl); if(go == seqObj){ seqObj = qobject_cast(cl); } GObjectUtils::updateRelationsURL(cl, curDoc->getURL(), url); } } } docs.append(newDoc); } }//ns ugene-1.9.8/src/corelibs/U2Core/src/tasks/ScriptTask.cpp0000644000175000017500000000541111651544332021516 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "ScriptTask.h" #include namespace U2 { ScriptTask::ScriptTask(const QString& taskName, const QString& _scriptText, const ScriptTaskSettings& _settings) : Task(taskName, _settings.mainThreadScript ? TaskFlag_NoRun : TaskFlag_None), scriptText(_scriptText), conf(_settings) { setVerboseLogMode(true); } void ScriptTask::run() { assert(!isMainThreadScript()); QScriptEngine engine; result = runScript(&engine, conf.inputParametersMap, scriptText, stateInfo); } Task::ReportResult ScriptTask::report() { if (isMainThreadScript()) { QScriptEngine engine; result = runScript(&engine, conf.inputParametersMap, scriptText, stateInfo); } return ReportResult_Finished; } QScriptValue ScriptTask::runScript(QScriptEngine* engine, const QMap& inputParametersMap, const QString& scriptText, TaskStateInfo& stateInfo) { // create new script engine QScriptValue result; // setup all input params as global vars QScriptValue thiz = engine->globalObject(); foreach(const QString& varName, inputParametersMap.keys()) { QScriptValue varVal = inputParametersMap.value(varName); thiz.setProperty(varName, varVal); } // check script syntax QScriptSyntaxCheckResult syntaxResult = engine->checkSyntax(scriptText); if (syntaxResult.state() != QScriptSyntaxCheckResult::Valid) { stateInfo.setError(tr("Script syntax check failed! Line: %1, error: %2").arg(syntaxResult.errorLineNumber()).arg(syntaxResult.errorMessage())); return result; } // run the script result = engine->evaluate(scriptText); if (engine->hasUncaughtException()) { stateInfo.setError(tr("Exception during script execution! Line: %1, error: %2") .arg(engine->uncaughtExceptionLineNumber()).arg(engine->uncaughtExceptionBacktrace().join("\n"))); } return result; } } //namespace ugene-1.9.8/src/corelibs/U2Core/src/tasks/TaskSignalMapper.h0000644000175000017500000000267211651544332022307 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_TASK_MAPPER_H_ #define _U2_TASK_MAPPER_H_ #include namespace U2 { class U2CORE_EXPORT TaskSignalMapper : public QObject { Q_OBJECT public: TaskSignalMapper(QObject* parent = NULL) : QObject(parent) {} TaskSignalMapper(Task* t) : QObject(t) { connect(t, SIGNAL(si_stateChanged()), SLOT(sl_taskStateChanged())); } public slots: void sl_taskStateChanged(); signals: void si_taskPrepared(Task*); void si_taskRunning(Task*); void si_taskFinished(Task*); void si_taskSucceeded(Task*); void si_taskFailed(Task*); }; } //namespace #endif ugene-1.9.8/src/corelibs/U2Core/src/tasks/ReplacePartOfSequenceTask.cpp0000644000175000017500000001662311651544332024441 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "ReplacePartOfSequenceTask.h" #include #include #include #include #include #include #include #include #include #include #include #include #include namespace U2 { ReplacePartOfSequenceTask::ReplacePartOfSequenceTask(DocumentFormatId _dfId, DNASequenceObject *_seqObj, U2Region _regionToReplace, const DNASequence& _newSeq, U2AnnotationUtils::AnnotationStrategyForResize _str, const GUrl& _url, bool _mergeAnnotations ) : Task(tr("Replace subsequence"), TaskFlag_NoRun), dfId(_dfId), mergeAnnotations(_mergeAnnotations), save(true), url(_url), strat(_str), seqObj(_seqObj), newSeq(_newSeq.seq), regionToReplace(_regionToReplace) { GCOUNTER( cvar, tvar, "ReplacePartOfSequenceTask" ); curDoc = seqObj->getDocument(); if(url == curDoc->getURL() || _url.isEmpty()){ save = false; return; } } Task::ReportResult ReplacePartOfSequenceTask::report(){ if(regionToReplace == U2Region(0,0)) { return ReportResult_Finished; } DNASequence sequence = seqObj->getDNASequence(); U2Region allSeq(0, sequence.length()); if(!allSeq.contains(regionToReplace)){ algoLog.error(tr("Region to replace larger then whole sequence")); return ReportResult_Finished; } Project *p = AppContext::getProject(); if(p != NULL){ if(p->isStateLocked()){ return ReportResult_CallMeAgain; } docs = p->getDocuments(); } if(!docs.contains(curDoc)){ docs.append(curDoc); } if(curDoc->isStateLocked()){ algoLog.error(tr("Document is locked")); return ReportResult_Finished; } if(save){ preparationForSave(); } sequence.seq.replace(regionToReplace.startPos, regionToReplace.length, newSeq); seqObj->setSequence(sequence); fixAnnotations(); if(save){ QList tasks; IOAdapterFactory* iof = AppContext::getIOAdapterRegistry()->getIOAdapterFactoryById(BaseIOAdapters::url2io(url)); tasks.append(new SaveDocumentTask(seqObj->getDocument(), iof, url.getURLString())); Project *p = AppContext::getProject(); if(p != NULL){ tasks.append(new AddDocumentTask(newDoc)); } AppContext::getTaskScheduler()->registerTopLevelTask(new MultiTask("Save document and add it to project (optional)", tasks)); } return ReportResult_Finished; } void ReplacePartOfSequenceTask::fixAnnotations() { int newLen = newSeq.size(); if (strat == U2AnnotationUtils::AnnotationStrategyForResize_Resize && regionToReplace.length == newLen) { return; } foreach(Document *d, docs){ QList annotationTablesList = d->findGObjectByType(GObjectTypes::ANNOTATION_TABLE); foreach(GObject *table, annotationTablesList){ AnnotationTableObject *ato = qobject_cast(table); if(ato->hasObjectRelation(seqObj, GObjectRelationRole::SEQUENCE)){ QList annList = ato->getAnnotations(); foreach(Annotation *an, annList){ QVector locs = an->getRegions(); U2AnnotationUtils::fixLocationsForReplacedRegion(regionToReplace, newLen, locs, strat); if(!locs.isEmpty()){ an->replaceRegions(locs); }else{ ato->removeAnnotation(an); } } } } } } void ReplacePartOfSequenceTask::preparationForSave() { IOAdapterFactory* iof = AppContext::getIOAdapterRegistry()->getIOAdapterFactoryById(BaseIOAdapters::url2io(url)); DocumentFormat *df = AppContext::getDocumentFormatRegistry()->getFormatById(dfId); if (iof == NULL) { return; } QList objList = curDoc->getObjects(); if(mergeAnnotations){ DNASequenceObject *oldObj = seqObj; newDoc = df->createNewDocument(iof, url, curDoc->getGHintsMap()); foreach(GObject* go, objList){ if(df->isObjectOpSupported(newDoc, DocumentFormat::DocObjectOp_Add, go->getGObjectType()) && (go->getGObjectType() != GObjectTypes::SEQUENCE || go == seqObj) && go->getGObjectType() != GObjectTypes::ANNOTATION_TABLE){ GObject *cl = go->clone(); newDoc->addObject(cl); if(go == seqObj){ seqObj = qobject_cast(cl); } GObjectUtils::updateRelationsURL(cl, curDoc->getURL(), url); } } AnnotationTableObject *newDocAto = new AnnotationTableObject("Annotations"); newDoc->addObject(newDocAto); newDocAto->addObjectRelation(seqObj, GObjectRelationRole::SEQUENCE); foreach(Document *d, docs){ QList annotationTablesList = d->findGObjectByType(GObjectTypes::ANNOTATION_TABLE); foreach(GObject *table, annotationTablesList){ AnnotationTableObject *ato = (AnnotationTableObject*)table; if(ato->hasObjectRelation(oldObj, GObjectRelationRole::SEQUENCE)){ foreach(Annotation *ann, ato->getAnnotations()){ QStringList groupNames; foreach(AnnotationGroup* gr,ann->getGroups()){ groupNames.append(gr->getGroupName()); } newDocAto->addAnnotation(new Annotation(ann->data()), groupNames); } } } } }else{ newDoc = df->createNewDocument(iof, url, curDoc->getGHintsMap()); foreach(GObject* go, objList){ if(df->isObjectOpSupported(newDoc, DocumentFormat::DocObjectOp_Add, go->getGObjectType())){ GObject *cl = go->clone(); newDoc->addObject(cl); if(go == seqObj){ seqObj = qobject_cast(cl); } GObjectUtils::updateRelationsURL(cl, curDoc->getURL(), url); } } } docs.append(newDoc); } } // U2 ugene-1.9.8/src/corelibs/U2Core/src/tasks/ReverseSequenceTask.cpp0000644000175000017500000000522211651544332023356 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include #include #include #include #include #include "ReverseSequenceTask.h" namespace U2 { ReverseSequenceTask::ReverseSequenceTask( DNASequenceObject* dObj, QList annotations, DNASequenceSelection* s, DNATranslation* transl ) :Task("ReverseSequenceTask", TaskFlags_NR_FOSCOE), seqObj(dObj), aObjs(annotations), selection(s), complTr(transl) { } Task::ReportResult ReverseSequenceTask::report() { DNASequence sequence = seqObj->getDNASequence(); if(sequence.length() == 0) { return ReportResult_Finished; } char* data = sequence.seq.data(); int len = sequence.length(); if (complTr != NULL) { complTr->translate(data, len); } TextUtils::reverse(data, len); seqObj->setSequence(sequence); // mirror selection if (selection != NULL) { QVector regions = selection->getSelectedRegions(); U2Region::mirror(len, regions); U2Region::reverse(regions); selection->setSelectedRegions(regions); } // fix annotation locations foreach (AnnotationTableObject* aObj, aObjs) { QList annotations = aObj->getAnnotations(); foreach (Annotation* a, annotations) { if (complTr != NULL) { U2Strand strand = a->getStrand(); a->setStrand(strand == U2Strand::Direct ? U2Strand::Complementary : U2Strand::Direct); } U2Location location = a->getLocation(); U2Region::mirror(len, location->regions); U2Region::reverse(location->regions); a->setLocation(location); } } return ReportResult_Finished; } }//namespace ugene-1.9.8/src/corelibs/U2Core/src/tasks/CreateFileIndexTask.cpp0000644000175000017500000002037111651544332023247 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "CreateFileIndexTask.h" #include #include #include #include #include #include #include #include #include #include #include #include //#include #include #include #include namespace U2 { const QString ACCESS_POINTS_SZ_TAG = "APS"; const QString ACCESS_POINT_TAG = "AP"; const QString ACCESS_POINT_WND_TAG = "APW"; const QString SPACE = " "; static void fillGzipIndex( UIndex::IOSection& ioSec, const GZipIndex& gzInd ) { int sz = gzInd.points.size(); int i = 0; ioSec.keys.insert( ACCESS_POINTS_SZ_TAG, QString::number( sz ) ); for( i = 0; i < sz; ++i ) { const GZipIndexAccessPoint& p = gzInd.points.at( i ); QString numTag = ACCESS_POINT_TAG + QString::number( i ); QString numVal = QString::number( p.bits ) + SPACE + QString::number( p.in ) + SPACE + QString::number( p.out ); ioSec.keys.insert( numTag, numVal ); QString wndTag = ACCESS_POINT_WND_TAG + QString::number( i ); QString wndVal = p.window; ioSec.keys.insert( wndTag, wndVal ); } } const QString CreateFileIndexTask::KEY_NAME = "name"; const QString CreateFileIndexTask::KEY_SEQ_LEN = "sequence_length"; const QString CreateFileIndexTask::KEY_SEQ_COUNT = "sequence_count"; const QString CreateFileIndexTask::KEY_ACCESSION = "accession"; const QString CreateFileIndexTask::KEY_DESCRIPTION = "description"; CreateFileIndexTask::CreateFileIndexTask( const QList< QString >& i, const QString& o, const QList< IOAdapterFactory* >& ifa, IOAdapterFactory* ofa ) :Task( tr( "Create index: %1" ).arg(QFileInfo(o).fileName()), TaskFlag_None ), inputUrls( i ), outputUrl( o ), inputFactories( ifa ), outputFactory( ofa ) { GCOUNTER( cvar, tvar, "CreateFileIndexTask" ); setVerboseLogMode(true); tpm = Progress_Manual; if( !inputUrls.size() ) { stateInfo.setError(tr( "No files to index" )); return; } if( inputUrls.size() != inputFactories.size() ) { stateInfo.setError(tr( "Internal error: inconsistent input data" )); return; } if( outputUrl.isEmpty() || !outputFactory ) { stateInfo.setError(tr( "Illegal output file parameters" )); return; } } void CreateFileIndexTask::fillIOSec( UIndex::IOSection& ioSec, const QString& url, IOAdapterFactory* factory, int num ) { assert( NULL != factory ); ioSec.sectionId = QString( "io_" ) + QString::number( num ); ioSec.ioAdapterId = factory->getAdapterId(); ioSec.url = url; if( BaseIOAdapters::LOCAL_FILE == ioSec.ioAdapterId ) { return; // filled all what we need } else if ( BaseIOAdapters::GZIPPED_LOCAL_FILE == ioSec.ioAdapterId ) { IOAdapterFactory* tmpFactory = AppContext::getIOAdapterRegistry()->getIOAdapterFactoryById( BaseIOAdapters::LOCAL_FILE ); LocalFileAdapterFactory* localFactory = qobject_cast< LocalFileAdapterFactory* >( tmpFactory ); assert( NULL != localFactory ); std::auto_ptr< LocalFileAdapter > localAdapter( qobject_cast< LocalFileAdapter* >( localFactory->createIOAdapter() ) ); if( !localAdapter->open( url, IOAdapterMode_Read ) ) { stateInfo.setError(tr( "Can't open file for read: '%1'" ).arg( url )); return; } bool indOk = false; GZipIndex gzInd = ZlibAdapter::buildGzipIndex( localAdapter.get(), GZipIndex::SPAN, &indOk ); if( !indOk ) { stateInfo.setError(tr( "Error creating gzipped output" )); return; } fillGzipIndex( ioSec, gzInd ); return; } else { // other io adapters not supported stateInfo.setError(tr( "Can't create index using %1 IO adapter").arg(ioSec.ioAdapterId)); } } void CreateFileIndexTask::readOneUrl( const QString& url, IOAdapterFactory* inputFactory, int num ) { assert( !url.isEmpty() && NULL != inputFactory && 0 <= num ); UIndex::IOSection ioSec; fillIOSec( ioSec, url, inputFactory, num ); if( stateInfo.hasError() ) { return; } ind.ios.append( ioSec ); std::auto_ptr< IOAdapter > io( inputFactory->createIOAdapter() ); if( !io->open( url, IOAdapterMode_Read ) ) { stateInfo.setError(tr( "Can't open file for read: '%1'" ).arg( url )); return; } while( !io->isEof() ) { QList dfList = DocumentUtils::detectFormat( io.get() ); if( dfList.isEmpty() ) { stateInfo.setError(tr( "Can't detect file format: %1").arg(url)); return; } DocumentFormat* df = dfList.first().format; if( !df->checkFlags(DocumentFormatFlag_SupportStreaming) ) { stateInfo.setError(tr( "UGENE can't index files of a specified format: %1" ).arg(df->getFormatName())); return; } qint64 startOff = io->bytesRead(); std::auto_ptr doc(df->loadDocument(io.get(), stateInfo, QVariantMap(), DocumentLoadMode_SingleObject)); if (hasError() || isCanceled()) { return; } assert(doc.get()!=NULL); qint64 endOff = io->bytesRead(); foreach(GObject* obj, doc->getObjects()) { UIndex::ItemSection item; item.ioSectionId = ioSec.sectionId; item.docFormat = df->getFormatId(); item.startOff = startOff; item.endOff = endOff; item.keys.unite(obj->getIndexInfo()); item.keys.insert(CreateFileIndexTask::KEY_NAME, obj->getGObjectName()); ind.items.append( item ); } } } void CreateFileIndexTask::readInputUrls() { int sz = inputUrls.size(); assert( sz == inputFactories.size() && sz > 0); for(int i = 0; i < sz; ++i ) { if( inputUrls[i].isEmpty() ) { uiLog.error("Found zero URL during indexing, skipping.."); continue; } if( NULL == inputFactories[i] ) { uiLog.error("Found zero IO adapter during indexing, skipping.."); continue; } readOneUrl( inputUrls[i], inputFactories[i], i ); if( stateInfo.hasError() || stateInfo.cancelFlag ) { return; } } } void CreateFileIndexTask::writeOutputUrl() { DocumentFormat* indFormat = AppContext::getDocumentFormatRegistry()->getFormatById( BaseDocumentFormats::INDEX ); assert( NULL != indFormat ); GObject* indObj = new UIndexObject( ind, UIndexObject::OBJ_NAME ); assert( NULL != indObj ); QList< GObject* > obj_list; obj_list.append( indObj ); Document* doc = new Document( indFormat, outputFactory, outputUrl, obj_list, QVariantMap() ); indFormat->storeDocument( doc, stateInfo ); delete doc; } void CreateFileIndexTask::run() { if( stateInfo.hasError() ) { return; } readInputUrls(); if( stateInfo.hasError() || stateInfo.cancelFlag ) { return; } stateInfo.progress = 0; writeOutputUrl(); } const QList & CreateFileIndexTask::getInputUrls() const { return inputUrls; } const QString & CreateFileIndexTask::getOutputUrl() const { return outputUrl; } } // U2 ugene-1.9.8/src/corelibs/U2Core/src/tasks/RemoveAnnotationsTask.h0000644000175000017500000000324411651544332023374 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_REMOVE_ANNOTATIONS_TASK_H_ #define _U2_REMOVE_ANNOTATIONS_TASK_H_ #include #include namespace U2 { class U2CORE_EXPORT RemoveAnnotationsTask : public Task { Q_OBJECT public: // Removes annotations of specified group, handles multiple annotaions ( > 10 000). // Also handles situations with locked objects. RemoveAnnotationsTask(AnnotationTableObject* ao, const QString& groupName); void prepare(); ReportResult report(); private: QPointer aobj; AnnotationGroup* subGroup; QString groupName; QList toDelete; int pos; bool annsSet; }; }//namespace #endif // _U2_REMOVE_ANNOTATIONS_TASK_H_ ugene-1.9.8/src/corelibs/U2Core/src/tasks/MultiTask.cpp0000644000175000017500000000236311651544332021347 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "MultiTask.h" namespace U2 { MultiTask::MultiTask( const QString & name, const QList& taskz ) : Task(name, TaskFlags_NR_FOSCOE), tasks(taskz) { setMaxParallelSubtasks(1); if( taskz.empty() ) { assert( false ); return; } foreach( Task * t, taskz ) { addSubTask(t); } } QList MultiTask::getTasks() const { return tasks; } } //namespace ugene-1.9.8/src/corelibs/U2Core/src/tasks/SequenceWalkerTask.cpp0000644000175000017500000001776211651544332023204 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "SequenceWalkerTask.h" #include #include namespace U2 { SequenceWalkerConfig::SequenceWalkerConfig() : seq(NULL), seqSize(0), complTrans(NULL), aminoTrans(NULL), chunkSize(0), lastChunkExtraLen(0), overlapSize(0), nThreads(MAX_PARALLEL_SUBTASKS_SERIAL) { strandToWalk = (complTrans!=NULL) ? StrandOption_Both : StrandOption_DirectOnly; } SequenceWalkerTask::SequenceWalkerTask(const SequenceWalkerConfig& c, SequenceWalkerCallback* cb, const QString& name, TaskFlags tf) : Task(name, tf), config(c), callback(cb) { assert(config.chunkSize > config.overlapSize); // if chunk == overlap -> infinite loop occurs assert(cb != NULL); assert(config.strandToWalk == StrandOption_DirectOnly || config.complTrans!=NULL); maxParallelSubtasks = config.nThreads; QList subs = prepareSubtasks(); foreach(SequenceWalkerSubtask* sub, subs) { addSubTask(sub); } } QList SequenceWalkerTask::prepareSubtasks() { QList res; if (config.range.isEmpty()) { config.range.startPos = 0; config.range.length = config.seqSize; } else { U2Region wholeSeqReg(0, config.seqSize); assert(wholeSeqReg.contains(config.range)); config.range = wholeSeqReg.intersect(config.range); } if (config.aminoTrans == NULL ) { //try walk direct and complement strands QVector chunks = splitRange(config.range, config.chunkSize, config.overlapSize, config.lastChunkExtraLen, false); if (config.strandToWalk == StrandOption_Both || config.strandToWalk == StrandOption_DirectOnly) { QList directTasks = createSubs(chunks, false, false); res+=directTasks; } if (config.strandToWalk == StrandOption_Both || config.strandToWalk == StrandOption_ComplementOnly) { assert(config.complTrans!=NULL); QList complTasks = createSubs(chunks, true, false); res+=complTasks; } } else { // try walk 3 direct and 3 complement translations if (config.strandToWalk == StrandOption_Both || config.strandToWalk == StrandOption_DirectOnly) { for (int i=0; i<3; i++) { U2Region strandRange(config.range.startPos + i, config.range.length - i); QVector chunks = splitRange(strandRange, config.chunkSize, config.overlapSize, config.lastChunkExtraLen, false); QList directTasks = createSubs(chunks, false, true); res+=directTasks; } } if (config.strandToWalk == StrandOption_Both || config.strandToWalk == StrandOption_ComplementOnly) { assert(config.complTrans!=NULL); for (int i=0; i<3; i++) { U2Region strandRange(config.range.startPos, config.range.length - i); QVector chunks = splitRange(strandRange, config.chunkSize, config.overlapSize, config.lastChunkExtraLen, true); QList complTasks = createSubs(chunks, true, true); res+=complTasks; } } } return res; } QList SequenceWalkerTask::createSubs(const QVector& chunks, bool doCompl, bool doAmino) { QList res; for (int i=0, n = chunks.size(); i 0 && i > 0; bool ro = config.overlapSize > 0 && i+1 < n; SequenceWalkerSubtask* t = new SequenceWalkerSubtask(this, chunk, lo, ro, config.seq + chunk.startPos, chunk.length, doCompl, doAmino); res.append(t); } return res; } QVector SequenceWalkerTask::splitRange(const U2Region& range, int chunkSize, int overlapSize, int lastChunkExtraLen, bool reverseMode) { assert(chunkSize > overlapSize); int stepSize = chunkSize - overlapSize; QVector res; for (int pos = range.startPos, end = range.endPos(), lastPos = range.startPos; lastPos < end; pos+=stepSize) { int chunkLen = qMin(pos + chunkSize, end) - pos; if (end - chunkLen - pos <= lastChunkExtraLen) { chunkLen = end-pos; } lastPos = pos+chunkLen; res.append(U2Region(pos, chunkLen)); } if (reverseMode) { QVector revertedRegions; foreach(const U2Region& r, res) { U2Region rr(range.startPos + (range.endPos() - r.endPos()), r.length); revertedRegions.prepend(rr); } res = revertedRegions; } return res; } ////////////////////////////////////////////////////////////////////////// // subtask SequenceWalkerSubtask::SequenceWalkerSubtask(SequenceWalkerTask* _t, const U2Region& glob, bool lo, bool ro, const char* _seq, int _len, bool _doCompl, bool _doAmino) : Task(tr("Sequence walker subtask"), TaskFlag_None), t(_t), globalRegion(glob), localSeq(_seq), originalLocalSeq(_seq), localLen(_len), originalLocalLen(_len), doCompl(_doCompl), doAmino(_doAmino), leftOverlap(lo), rightOverlap(ro) { tpm = Task::Progress_Manual; // get resources QList< TaskResourceUsage > resources = t->getCallback()->getResources( this ); foreach( const TaskResourceUsage & resource, resources ) { addTaskResource(resource); } } const char* SequenceWalkerSubtask::getRegionSequence() { if (needLocalRegionProcessing()) { prepareLocalRegion(); } return localSeq; } int SequenceWalkerSubtask::getRegionSequenceLen() { if (needLocalRegionProcessing()) { prepareLocalRegion(); } return localLen; } void SequenceWalkerSubtask::prepareLocalRegion() { assert(doAmino || doCompl); QByteArray res(localSeq, localLen); if (doCompl) { //do complement; assert(t->getConfig().complTrans!=NULL); const QByteArray& complementMap = t->getConfig().complTrans->getOne2OneMapper(); TextUtils::translate(complementMap, res.data(), res.length()); TextUtils::reverse(res.data(), res.length()); } if (doAmino) { assert(t->getConfig().aminoTrans!=NULL && t->getConfig().aminoTrans->isThree2One()); t->getConfig().aminoTrans->translate(res.data(), res.length(), res.data(), res.length()); int newLen = res.length()/3; res.resize(newLen); } processedSeqImage = res; localLen = processedSeqImage.size(); localSeq = processedSeqImage.constData(); } void SequenceWalkerSubtask::run() { assert(!t->hasError()); t->getCallback()->onRegion(this, stateInfo); } bool SequenceWalkerSubtask::intersectsWithOverlaps(const U2Region& reg) const { int overlap = getGlobalConfig().overlapSize; if (overlap == 0) { return false; } bool intersects = false; if (leftOverlap) { intersects = reg.intersects(U2Region(globalRegion.startPos, overlap)); } if (!intersects && rightOverlap) { intersects = reg.intersects(U2Region(globalRegion.endPos() - overlap, overlap)); } return intersects; } } //namespace ugene-1.9.8/src/corelibs/U2Core/src/tasks/AddSequencesToAlignmentTask.h0000644000175000017500000000310511651544332024423 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_ADD_SEQUENCES_TO_ALIGNMENT_TASK_H_ #define _U2_ADD_SEQUENCES_TO_ALIGNMENT_TASK_H_ #include #include #include namespace U2 { class LoadDocumentTask; class StateLock; class U2CORE_EXPORT AddSequencesToAlignmentTask : public Task { Q_OBJECT public: AddSequencesToAlignmentTask(MAlignmentObject* obj, const QStringList& filesWithSequences); void prepare(); QList onSubTaskFinished(Task* subTask); ReportResult report(); QPointer maObj; MAlignment bufMa; QStringList urls; StateLock* stateLock; }; }// namespace #endif //_U2_ADD_SEQUENCES_TO_ALIGNMENT_TASK_H_ ugene-1.9.8/src/corelibs/U2Core/src/tasks/LoadDocumentTask.cpp0000644000175000017500000004076211651544332022640 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "LoadDocumentTask.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #define GObjectHint_NamesList "gobject-hint-names-list" namespace U2 { /* TRANSLATOR U2::LoadUnloadedDocumentTask */ ////////////////////////////////////////////////////////////////////////// // DocumentProviderTask DocumentProviderTask::DocumentProviderTask(const QString& name, TaskFlags flags) : Task(name, flags), resultDocument(NULL) { documentDescription = tr("[unknown]"); } void DocumentProviderTask::cleanup(){ delete resultDocument; resultDocument = NULL; } ////////////////////////////////////////////////////////////////////////// // LoadUnloadedDocumentTask //TODO: support subtask sharing! //TODO: avoid multiple load tasks when opening view for unloaded doc! LoadUnloadedDocumentTask::LoadUnloadedDocumentTask(Document* d, const LoadDocumentTaskConfig& _config) : Task("", TaskFlags_NR_FOSCOE | TaskFlag_MinimizeSubtaskErrorText), subtask(NULL), unloadedDoc(d), config(_config) { assert(config.checkObjRef.objType != GObjectTypes::UNLOADED); setVerboseLogMode(true); setTaskName(tr("Load '%1'").arg(d->getName())); setUseDescriptionFromSubtask(true); assert(d!=NULL); } void LoadUnloadedDocumentTask::prepare() { if (unloadedDoc == NULL) { stateInfo.setError(tr("Document not found")); return; } DocumentFormatId format = unloadedDoc->getDocumentFormatId(); QString formatName = AppContext::getDocumentFormatRegistry()->getFormatById(format)->getFormatName(); IOAdapterFactory* iof = unloadedDoc->getIOAdapterFactory(); const GUrl& url = unloadedDoc->getURL(); coreLog.details(tr("Starting load document from %1, document format %2").arg(url.getURLString()).arg(formatName)); QVariantMap hints = unloadedDoc->getGHintsMap(); QStringList namesList; foreach(GObject* obj, unloadedDoc->getObjects()) { namesList << obj->getGObjectName(); } hints[GObjectHint_NamesList] = namesList; subtask = new LoadDocumentTask(format, url, iof, hints, config); addSubTask(subtask); resName = getResourceName(unloadedDoc); AppContext::getResourceTracker()->registerResourceUser(resName, this); } void LoadUnloadedDocumentTask::clearResourceUse() { if (!resName.isEmpty()) { AppContext::getResourceTracker()->unregisterResourceUser(resName, this); resName.clear(); } } Task::ReportResult LoadUnloadedDocumentTask::report() { Task::ReportResult res = ReportResult_Finished; Project* p = AppContext::getProject(); if (unloadedDoc == NULL) { stateInfo.setError(tr("Document was removed")); } else { propagateSubtaskError(); } if (hasError()) { if (!resName.isEmpty()) { clearResourceUse(); resName.clear(); } } else if (isCanceled() || (subtask!=NULL && subtask->isCanceled())) { //do nothing } else if (unloadedDoc->isLoaded()) { //do nothing } else if (p && p->isStateLocked()) { res = ReportResult_CallMeAgain; //wait until project is unlocked } else { assert(unloadedDoc->isStateLocked()); // all unloaded docs are always state locked //todo: move to utility method? const QList& locks = unloadedDoc->getStateLocks(); bool readyToLoad = true; foreach(StateLock* lock, locks) { if ( lock != unloadedDoc->getDocumentModLock(DocumentModLock_IO) && lock != unloadedDoc->getDocumentModLock(DocumentModLock_USER) && lock != unloadedDoc->getDocumentModLock(DocumentModLock_FORMAT_AS_CLASS) && lock != unloadedDoc->getDocumentModLock(DocumentModLock_FORMAT_AS_INSTANCE) && lock != unloadedDoc->getDocumentModLock(DocumentModLock_UNLOADED_STATE)) { readyToLoad = false; } } if (!readyToLoad) { stateInfo.setError(tr("Document is locked")); //todo: wait instead? } else { Document* doc = subtask->getDocument(); unloadedDoc->loadFrom(doc); // doc was load in a separate thread -> clone all GObjects assert(!unloadedDoc->isTreeItemModified()); assert(unloadedDoc->isLoaded()); } } if (res == ReportResult_Finished) { clearResourceUse(); } return res; } Document* LoadUnloadedDocumentTask::getDocument() const { return unloadedDoc; } QString LoadUnloadedDocumentTask::getResourceName(Document* d) { return QString(LoadUnloadedDocumentTask::tr("Project Document:") + ":" + d->getURLString()); } LoadUnloadedDocumentTask* LoadUnloadedDocumentTask::findActiveLoadingTask(Document* d) { QString res = getResourceName(d); QList tasks = AppContext::getResourceTracker()->getResourceUsers(res); foreach(Task* t, tasks) { LoadUnloadedDocumentTask* lut = qobject_cast(t); if (lut!=NULL) { return lut; } } return false; } bool LoadUnloadedDocumentTask::addLoadingSubtask(Task* t, const LoadDocumentTaskConfig& config) { GObject* o = GObjectUtils::selectObjectByReference(config.checkObjRef, UOF_LoadedAndUnloaded); if (o == NULL) { t->setError(tr("Annotation object not found")); return false; } if (o->isUnloaded()) { t->addSubTask(new LoadUnloadedDocumentTask(o->getDocument(), config)); return true; } return false; } ////////////////////////////////////////////////////////////////////////// // Load Document LoadDocumentTask::LoadDocumentTask(DocumentFormatId f, const GUrl& u, IOAdapterFactory* i, const QVariantMap& map, const LoadDocumentTaskConfig& _config) : DocumentProviderTask("", TaskFlag_None), format(NULL), url(u), iof(i), hints(map), config(_config) { setTaskName(tr("Read document: '%1'").arg(u.fileName())); documentDescription = u.getURLString(); format = AppContext::getDocumentFormatRegistry()->getFormatById(f); init(); } LoadDocumentTask::LoadDocumentTask(DocumentFormat* f, const GUrl& u, IOAdapterFactory* i, const QVariantMap& map, const LoadDocumentTaskConfig& _config) : DocumentProviderTask("", TaskFlag_None), format(NULL), url(u), iof(i), hints(map), config(_config) { setTaskName(tr("Read document: '%1'").arg(u.fileName())); documentDescription = u.getURLString(); format = f; init(); } void LoadDocumentTask::init() { tpm = Progress_Manual; if (format == NULL) { setError(tr("Document format is NULL!")); return; } if (iof == NULL) { setError(tr("IO adapter factory is NULL!")); return; } } LoadDocumentTask * LoadDocumentTask::getDefaultLoadDocTask(const GUrl& url) { if( url.isEmpty() ) { return NULL; } IOAdapterFactory * iof = AppContext::getIOAdapterRegistry()->getIOAdapterFactoryById( BaseIOAdapters::url2io( url ) ); if ( iof == NULL ) { return NULL; } QList dfs = DocumentUtils::detectFormat(url); if( dfs.isEmpty() ) { return NULL; } DocumentFormat * df = dfs.first().format; return new LoadDocumentTask( df->getFormatId(), url, iof ); } void LoadDocumentTask::prepare() { if(hasError() || isCanceled()) { return; } int memUseMB = 0; if(!format->getFlags().testFlag(DocumentFormatFlag_NoFullMemoryLoad)) { // document is fully loaded to memory QFileInfo file(url.getURLString()); memUseMB = file.size() / (1024*1024); double DEFAULT_COMPRESS_RATIO = 2.5; if (iof->getAdapterId() == BaseIOAdapters::GZIPPED_LOCAL_FILE) { quint64 fileSizeInBytes = ZlibAdapter::getUncompressedFileSizeInBytes(url); if (fileSizeInBytes < 0) { memUseMB *= DEFAULT_COMPRESS_RATIO; //Need to calculate compress level } else { memUseMB = fileSizeInBytes / (1024*1024); } } else if (iof->getAdapterId() == BaseIOAdapters::GZIPPED_HTTP_FILE) { memUseMB *= DEFAULT_COMPRESS_RATIO; //Need to calculate compress level } coreLog.trace(QString("load document:Memory resource %1").arg(memUseMB)); } if (memUseMB > 0) { QString error; Project *p = AppContext::getProject(); if (p) { if(!AppContext::getProject()->lockResources(memUseMB, url.getURLString(), error)) { stateInfo.setError(error); } } else { addTaskResource(TaskResourceUsage(RESOURCE_MEMORY, memUseMB, false)); } } } void LoadDocumentTask::run() { if(hasError() || isCanceled()) { return; } if (config.createDoc && iof->isResourceAvailable(url) == TriState_No) { if (iof->isIOModeSupported(IOAdapterMode_Write)) { resultDocument = format->createNewDocument(iof, url, hints); } else { setError(tr("Document not found %1").arg(url.getURLString())); } } else { QStringList renameList = hints.value(GObjectHint_NamesList).toStringList(); // removing this value from hints -> name list changes are not tracked in runtime // and used for LoadUnloadedDocument & LoadDocument privately hints.remove(GObjectHint_NamesList); try { resultDocument = format->loadDocument(iof, url, stateInfo, hints); } catch(std::bad_alloc) { resultDocument = NULL; setError(tr("Not enough memory to load document %1").arg(url.getURLString())); } if (resultDocument != NULL) { if (!renameList.isEmpty()) { renameObjects(resultDocument, renameList); } Document* convertedDoc = createCopyRestructuredWithHints(resultDocument, stateInfo); if (convertedDoc != NULL) { delete resultDocument; resultDocument = convertedDoc; } if (hints.contains(DocumentReadingMode_MaxObjectsInDoc) ) { int maxObjects = hints.value(DocumentReadingMode_MaxObjectsInDoc).toInt(); int docObjects = resultDocument->getObjects().size(); if (docObjects > maxObjects) { setError(tr("Maximum number of objects per document limit reached for %1. Try different options for opening the document!").arg(resultDocument->getURLString())); delete resultDocument; resultDocument = NULL; } } } } if (config.checkObjRef.isValid() && !hasError()) { processObjRef(); } assert(isCanceled() || resultDocument != NULL || hasError()); assert(resultDocument == NULL || resultDocument->isLoaded()); } Task::ReportResult LoadDocumentTask::report() { if (stateInfo.hasError() || isCanceled()) { return ReportResult_Finished; } assert(resultDocument != NULL); resultDocument->setLastUpdateTime(); return ReportResult_Finished; } void LoadDocumentTask::processObjRef() { assert(config.checkObjRef.isValid()); assert(resultDocument!=NULL); if (GObjectUtils::selectObjectByReference(config.checkObjRef, resultDocument->getObjects(), UOF_LoadedOnly) == NULL) { if (config.objFactory == NULL) { stateInfo.setError(tr("Object not found: %1").arg(config.checkObjRef.objName)); } else { assert(!resultDocument->isStateLocked()); Document::Constraints c; c.objectTypeToAdd.append(config.checkObjRef.objType); bool ok = resultDocument->checkConstraints(c); if (!ok) { stateInfo.setError(tr("Can't add object. Document format constraints check failed: %1").arg(resultDocument->getName())); } else { GObject* obj = config.objFactory->create(config.checkObjRef); assert(obj!=NULL); resultDocument->addObject(obj); } } } } Document* LoadDocumentTask::createCopyRestructuredWithHints(const Document* doc, U2OpStatus& os) { Document *resultDoc = NULL; const QVariantMap& hints = doc->getGHintsMap(); if (hints.value(DocumentReadingMode_SequenceAsAlignmentHint).toBool()) { QList seqObjects; MAlignment ma = MSAUtils::seq2ma(doc->getObjects(), os); if (ma.isEmpty()) { return NULL; } ma.trim(); MAlignmentObject* maObj = new MAlignmentObject(ma); QList objects; objects << maObj; DocumentFormatConstraints objTypeConstraints; objTypeConstraints.supportedObjectTypes << GObjectTypes::MULTIPLE_ALIGNMENT; bool makeReadOnly = !doc->getDocumentFormat()->checkConstraints(objTypeConstraints); resultDoc = new Document(doc->getDocumentFormat(), doc->getIOAdapterFactory(), doc->getURL(), objects, hints, makeReadOnly ? tr("Format does not support writing of alignments") : QString()); doc->propagateModLocks(resultDoc); } else if (hints.contains(DocumentReadingMode_SequenceMergeGapSize)) { int mergeGap = hints.value(DocumentReadingMode_SequenceMergeGapSize).toInt(); if (mergeGap < 0 || doc->findGObjectByType(GObjectTypes::SEQUENCE, UOF_LoadedOnly).count() <= 1) { return NULL; } resultDoc = SequenceUtils::mergeSequences(doc, mergeGap, os); if (os.hasError()) { delete resultDoc; resultDoc = NULL; } } return resultDoc; } void LoadDocumentTask::renameObjects(Document* doc, const QStringList& names) { if (doc->getObjects().size() != names.size()) { coreLog.trace(QString("Objects renaming failed! Objects in doc: %1, names: %2").arg(doc->getObjects().size()).arg(names.size())); return; } //drop names first QSet usedNames; QSet notRenamedObjects; foreach(GObject* obj, doc->getObjects()) { notRenamedObjects.insert(obj); usedNames.insert(obj->getGObjectName()); } const QList& objects = doc->getObjects(); int nObjects = objects.size(); int maxIters = nObjects; int currentIter = 0; //to avoid endless loop in case of duplicate names while (!notRenamedObjects.isEmpty() && currentIter < maxIters) { for (int i = 0; i < nObjects; i++) { GObject* obj = objects[i]; if (!notRenamedObjects.contains(obj)) { continue; } QString newName = names[i]; if (usedNames.contains(newName)) { continue; } QString oldName = obj->getGObjectName(); obj->setGObjectName(newName); usedNames.remove(oldName); usedNames.insert(newName); notRenamedObjects.remove(obj); } currentIter++; } } GObject* LDTObjectFactory::create(const GObjectReference& ref) { assert(ref.objType == GObjectTypes::ANNOTATION_TABLE); //TODO: handle other core types return new AnnotationTableObject(ref.objName); } }//namespace ugene-1.9.8/src/corelibs/U2Core/src/tasks/ExtractAnnotatedRegionTask.h0000644000175000017500000000434111651544332024334 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef __EXTRACT_ANNOTATED_REGION_TASK_H__ #define __EXTRACT_ANNOTATED_REGION_TASK_H__ #include #include #include #include namespace U2 { struct U2CORE_EXPORT ExtractAnnotatedRegionTaskSettings { ExtractAnnotatedRegionTaskSettings() : gapSym('-'), gapLength(0), translate(true), complement(true), extLeft(0), extRight(0) {} char gapSym; int gapLength; bool translate; bool complement; int extLeft; int extRight; }; class U2CORE_EXPORT ExtractAnnotatedRegionTask : public Task { Q_OBJECT public: ExtractAnnotatedRegionTask( const DNASequence & sequence, SharedAnnotationData sd, const ExtractAnnotatedRegionTaskSettings & cfg); void prepare(); void run(); DNASequence getResultedSequence() const {return resultedSeq;} SharedAnnotationData getResultedAnnotation() {return resultedAnn;} private: void prepareTranslations(); void extractLocations(QList& resParts, QVector& resLocation, const QVector& origLocation); DNASequence inputSeq; SharedAnnotationData inputAnn; ExtractAnnotatedRegionTaskSettings cfg; QVector extendedRegions; DNATranslation * complT; DNATranslation * aminoT; SharedAnnotationData resultedAnn; DNASequence resultedSeq; }; }// ns #endif ugene-1.9.8/src/corelibs/U2Core/src/tasks/AddDocumentTask.cpp0000644000175000017500000000672311651544332022450 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "AddDocumentTask.h" #include #include #include #include #include namespace U2 { AddDocumentTask::AddDocumentTask(Document * _d, const AddDocumentTaskConfig& _conf) : Task( tr("Adding document to project: %1").arg(_d->getURLString()), TaskFlags_NR_FOSCOE), document(_d), dpt(NULL), conf(_conf) { setSubtaskProgressWeight(0); SAFE_POINT(document->isMainThreadObject(), QString("Document added to the project does not belong to the main application thread: %1 !").arg(document->getURLString()),); } AddDocumentTask::AddDocumentTask(DocumentProviderTask * _dpt, const AddDocumentTaskConfig& c) : Task( tr("Adding document to project: %1").arg(_dpt->getDocumentDescription()), TaskFlags_NR_FOSCOE), document(NULL), dpt(_dpt), conf(c) { addSubTask(dpt); setSubtaskProgressWeight(0); } QList AddDocumentTask::onSubTaskFinished(Task* subTask) { QList res; if (propagateSubtaskError()) { return res; } if (subTask == dpt && dpt != NULL) { if(dpt->isCanceled()){ return res; } Document* doc = dpt->takeDocument(); if (!doc->isMainThreadModificationOnly()) { document = doc->clone(); delete doc; } else { document = doc; } if (AppContext::getProject() == NULL) { res << AppContext::getProjectLoader()->createNewProjectTask(); } else if (conf.unloadExistingDocument) { Document* oldDoc = AppContext::getProject()->findDocumentByURL(document->getURL()); if (oldDoc != NULL && oldDoc != document) { res << new RemoveMultipleDocumentsTask(AppContext::getProject(), QList() << oldDoc, false, false); } } } return res; } Task::ReportResult AddDocumentTask::report() { Project * p = AppContext::getProject(); if( p == NULL ) { // no project is opened setError(tr("No project is opened")); return ReportResult_Finished; } if( p->isStateLocked() ) { return ReportResult_CallMeAgain; } else if (document != NULL) { Document* sameURLDoc = p->findDocumentByURL(document->getURL()); if (sameURLDoc!=NULL) { stateInfo.setError(tr("Document is already added to the project %1").arg(document->getURL().getURLString())); } else { p->addDocument(document); } } else { stateInfo.setError(stateInfo.getError() + tr("Document was removed")); } return ReportResult_Finished; } }//namespace ugene-1.9.8/src/corelibs/U2Core/src/tasks/FailTask.h0000644000175000017500000000223211651544332020570 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_FAIL_TASK_H_ #define _U2_FAIL_TASK_H_ #include namespace U2 { class U2CORE_EXPORT FailTask : public Task { Q_OBJECT public: FailTask(const QString& msg) : Task(tr("Failure"), TaskFlag_NoRun) { stateInfo.setError(msg); } }; } //namespace #endif ugene-1.9.8/src/corelibs/U2Core/src/tasks/AddDocumentTask.h0000644000175000017500000000352411651544332022111 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_ADD_DOCUMENT_TASK_H_ #define _U2_ADD_DOCUMENT_TASK_H_ #include #include #include namespace U2 { class Document; class DocumentProviderTask; class AddDocumentTaskConfig { public: AddDocumentTaskConfig() : createProjectIfNeeded(true), unloadExistingDocument(false) {} bool createProjectIfNeeded; bool unloadExistingDocument; }; /** Adds document to active project. Waits for locks if any */ class U2CORE_EXPORT AddDocumentTask : public Task { Q_OBJECT public: AddDocumentTask(Document * d, const AddDocumentTaskConfig& c = AddDocumentTaskConfig()); AddDocumentTask(DocumentProviderTask* dp, const AddDocumentTaskConfig& c = AddDocumentTaskConfig()); ReportResult report(); QList onSubTaskFinished(Task* subTask); Document* getDocument() {return document;} private: Document* document; DocumentProviderTask* dpt; AddDocumentTaskConfig conf; }; }//namespace #endif ugene-1.9.8/src/corelibs/U2Core/src/tasks/CreateFileIndexTask.h0000644000175000017500000000420611651544332022713 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_CREATE_FILE_INDEX_TASK_H_ #define _U2_CREATE_FILE_INDEX_TASK_H_ #include #include #include #include namespace U2 { class U2CORE_EXPORT CreateFileIndexTask : public Task { Q_OBJECT public: static const QString KEY_NAME; static const QString KEY_SEQ_LEN; static const QString KEY_SEQ_COUNT; static const QString KEY_ACCESSION; static const QString KEY_DESCRIPTION; public: CreateFileIndexTask( const QList< QString >& inputUrls, const QString& outputUrl, const QList< IOAdapterFactory* >& inputFactories, IOAdapterFactory* outputFactory ); virtual void run(); const QList & getInputUrls() const; const QString & getOutputUrl() const; private: void readInputUrls(); void readOneUrl( const QString& url, IOAdapterFactory* fa, int ind ); void writeOutputUrl(); void fillIOSec(UIndex::IOSection& ioSec, const QString& url, IOAdapterFactory* factory, int num ); private: QList< QString > inputUrls; QString outputUrl; QList< IOAdapterFactory* > inputFactories; IOAdapterFactory* outputFactory; UIndex ind; }; // CreateFileIndexTask } // U2 #endif // _U2_CREATE_FILE_INDEX_TASK_H_ ugene-1.9.8/src/corelibs/U2Core/src/tasks/SaveDocumentTask.h0000644000175000017500000000607311651544332022321 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_SAVE_DOCUMENT_TASK_H_ #define _U2_SAVE_DOCUMENT_TASK_H_ #include #include #include #include namespace U2 { class Document; class StateLock; class IOAdapterFactory; class DocumentFormat; enum SaveDocFlag { SaveDoc_Overwrite = 0x0, SaveDoc_Append = 0x1, SaveDoc_Roll = 0x2, SaveDoc_DestroyAfter = 0x4 }; typedef QFlags SaveDocFlags; class U2CORE_EXPORT SaveDocumentTask : public Task { Q_OBJECT public: SaveDocumentTask(Document* doc, IOAdapterFactory* iof = NULL, const GUrl& url = GUrl()); SaveDocumentTask(Document* doc, SaveDocFlags flags, const QSet& excludeFileNames = QSet()); virtual void prepare(); virtual void run(); ReportResult report(); const GUrl& getURL() const {return url;} IOAdapterFactory* getIOAdapterFactory() const {return iof;} const QPointer& getDocument() const {return doc;} //used in file-name rolling mode void setExcludeFileNames(const QSet& _excludeFileNames) {excludeFileNames = _excludeFileNames;} private: StateLock* lock; QPointer doc; IOAdapterFactory* iof; GUrl url; SaveDocFlags flags; QSet excludeFileNames; }; class U2CORE_EXPORT SaveMiltipleDocuments: public Task { Q_OBJECT public: SaveMiltipleDocuments(const QList& docs, bool askBeforeSave); static QList findModifiedDocuments(const QList& docs); }; class U2CORE_EXPORT SaveCopyAndAddToProjectTask : public Task { Q_OBJECT public: SaveCopyAndAddToProjectTask(Document* doc, IOAdapterFactory* iof, const GUrl& url); ReportResult report(); private: SaveDocumentTask* saveTask; QList info; GUrl url; GUrl origURL; DocumentFormat* df; QVariantMap hints; }; class U2CORE_EXPORT RelocateDocumentTask : public Task { Q_OBJECT public: RelocateDocumentTask(const GUrl& fromURL, const GUrl& toURL); ReportResult report(); public: GUrl fromURL; GUrl toURL; }; }//namespace #endif ugene-1.9.8/src/corelibs/U2Core/src/tasks/AddSequencesToAlignmentTask.cpp0000644000175000017500000000741011651544332024761 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "AddSequencesToAlignmentTask.h" #include #include #include #include #include #include namespace U2 { AddSequencesToAlignmentTask::AddSequencesToAlignmentTask( MAlignmentObject* obj, const QStringList& fileWithSequencesUrls ) : Task("Add sequences to alignment task", TaskFlag_NoRun), maObj(obj), urls(fileWithSequencesUrls), stateLock(NULL) { assert(!fileWithSequencesUrls.isEmpty()); bufMa = maObj->getMAlignment(); } void AddSequencesToAlignmentTask::prepare() { if (maObj.isNull()) { stateInfo.setError(tr("Object is empty.")); return; } if (maObj->isStateLocked()) { stateInfo.setError(tr("Object is locked for modifications.")); return; } stateLock = new StateLock("Adding_files_to_alignment", StateLockFlag_LiveLock); maObj->lockState(stateLock); foreach( const QString& fileWithSequencesUrl, urls) { QList detectedFormats = DocumentUtils::detectFormat(fileWithSequencesUrl); if (!detectedFormats.isEmpty()) { IOAdapterFactory* factory = AppContext::getIOAdapterRegistry()->getIOAdapterFactoryById(BaseIOAdapters::LOCAL_FILE); DocumentFormat* format = detectedFormats.first().format; LoadDocumentTask* loadTask = new LoadDocumentTask(format->getFormatId(), fileWithSequencesUrl, factory); addSubTask(loadTask); } else { setError("Unknown format"); } } } QList AddSequencesToAlignmentTask::onSubTaskFinished( Task* subTask ) { QList subTasks; propagateSubtaskError(); if ( isCanceled() || hasError() ) { return subTasks; } LoadDocumentTask* loadTask = qobject_cast(subTask); assert(loadTask != NULL); Document* doc = loadTask->getDocument(); QList seqObjects = doc->findGObjectByType(GObjectTypes::SEQUENCE); foreach(GObject* obj, seqObjects) { DNASequenceObject* dnaObj = qobject_cast(obj); assert(dnaObj != NULL); DNAAlphabet* newAlphabet = DNAAlphabet::deriveCommonAlphabet(dnaObj->getAlphabet(), bufMa.getAlphabet()); if (newAlphabet != NULL) { bufMa.setAlphabet(newAlphabet); MAlignmentRow row(dnaObj->getDNASequence().getName(), dnaObj->getSequence(), 0); bufMa.addRow(row); } else { stateInfo.setError(tr("Sequence %1 from %2 has different alphabet").arg(dnaObj->getGObjectName()).arg(loadTask->getDocument()->getURLString())); } } return subTasks; } Task::ReportResult AddSequencesToAlignmentTask::report() { if (stateLock) { maObj->unlockState(stateLock); delete stateLock; } maObj->setMAlignment(bufMa); return ReportResult_Finished; } }ugene-1.9.8/src/corelibs/U2Core/src/tasks/CopyDataTask.cpp0000644000175000017500000000475111651544332021764 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "CopyDataTask.h" #include #include #include #include #include namespace U2 { CopyDataTask::CopyDataTask( IOAdapterFactory * _ioFrom, const GUrl& _urlFrom, IOAdapterFactory * _ioTo, const GUrl& _urlTo ) : Task(tr("Copy Data Task"), TaskFlag_None), ioFrom(_ioFrom), ioTo(_ioTo), urlFrom(_urlFrom), urlTo(_urlTo) { assert(ioFrom != NULL && ioTo != NULL); tpm = Progress_Manual; } void CopyDataTask::run() { std::auto_ptr from( ioFrom->createIOAdapter() ); std::auto_ptr where( ioTo->createIOAdapter() ); from->open( urlFrom, IOAdapterMode_Read ); if (!from->isOpen()) { stateInfo.setError(L10N::errorOpeningFileRead(urlFrom)); return; } qint64 count = 0; qint64 count_w = 0; QByteArray buff( BUFFSIZE, 0 ); count = from->readBlock( buff.data(), BUFFSIZE ); if (count == 0) { stateInfo.setError(tr("Cannot get data from: '%1'").arg(urlFrom.getURLString())); return; } if (!where->open( urlTo, IOAdapterMode_Write )) { stateInfo.setError(L10N::errorOpeningFileWrite(urlTo)); return; } while( count > 0 ) { count_w = where->writeBlock( buff.data(), count ); if( stateInfo.cancelFlag ) { break; } stateInfo.progress = from->getProgress(); count = from->readBlock( buff.data(), BUFFSIZE ); } if( count < 0 || count_w < 0 ) { if (!stateInfo.hasError()) { stateInfo.setError(tr("IO adapter error")); } } } }// namespace ugene-1.9.8/src/corelibs/U2Core/src/tasks/ExportToNewFileFromIndexTask.cpp0000644000175000017500000001144411651544332025127 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include #include #include #include #include "ExportToNewFileFromIndexTask.h" namespace U2 { ExportToNewFileFromIndexTask::ExportToNewFileFromIndexTask( const UIndex& i, const QList< int >& n, const QString& file ) : Task( tr( "Export from index" ), TaskFlag_NoRun ), index( i ), docNums( n ), exportFilename( file ), io( NULL ), saveCurDocTask( NULL ) { setVerboseLogMode(true); if( exportFilename.isEmpty() ) { stateInfo.setError(tr( "Export filename is empty" )); return; } if( UIndex::NO_ERR != index.checkConsistency() ) { stateInfo.setError(tr( "Index is inconsistent" )); return; } if( docNums.isEmpty() ) { stateInfo.setError(tr( "Document numbers list is empty" )); return; } tpm = Progress_SubTasksBased; } ExportToNewFileFromIndexTask::~ExportToNewFileFromIndexTask() { assert( docsToSave.isEmpty() ); assert( NULL == io ); } void ExportToNewFileFromIndexTask::prepare() { io = getOpenedIOAdapter(exportFilename); if( NULL == io ) { assert( stateInfo.hasError() ); return; } QList< Task* > subs; int itemsSz = index.items.size(); foreach(int docInd, docNums) { if( !( 0 <= docInd && itemsSz > docInd ) ) { setError(tr( "Invalid document number: %1, max: %2" ).arg(docInd).arg(itemsSz)); break; } subs << new GetDocumentFromIndexTask( index, docInd ); } if (hasError() || isCanceled()) { qDeleteAll( subs ); return; } foreach( Task* task, subs ) { addSubTask( task ); } } Task::ReportResult ExportToNewFileFromIndexTask::report() { if( NULL != io ) { delete io; io = NULL; } return ReportResult_Finished; } IOAdapter* ExportToNewFileFromIndexTask::getOpenedIOAdapter(const QString& url) { IOAdapterId ioId = BaseIOAdapters::url2io( url ); IOAdapterFactory* factory = AppContext::getIOAdapterRegistry()->getIOAdapterFactoryById( ioId ); if( NULL == factory ) { setError(tr( "No IO adapter found for URL: %1").arg(url)); return NULL; } IOAdapter* res = factory->createIOAdapter(); if( !res->open( url, IOAdapterMode_Write ) ) { setError(tr("Can't open file for write: '%1'").arg(url)); delete res; return NULL; } return res; } QList< Task* > ExportToNewFileFromIndexTask::getDocTaskFinished( GetDocumentFromIndexTask* t ) { assert( NULL != t ); QList< Task* > ret; Document* doc = t->takeDocument(); if( NULL == doc ) { stateInfo.setError(t->getError()); return ret; } docsToSave << doc; if( NULL == saveCurDocTask ) { saveCurDocTask = new SaveDocumentStreamingTask( docsToSave.takeFirst(), io ); ret << saveCurDocTask; } return ret; } QList< Task* > ExportToNewFileFromIndexTask::saveDocTaskFinished( SaveDocumentStreamingTask* t ) { assert( NULL != t ); QList< Task* > ret; Document* saved = t->getDocument(); assert( NULL != saved ); delete saved; if( docsToSave.isEmpty() ) { saveCurDocTask = NULL; } else { saveCurDocTask = new SaveDocumentStreamingTask( docsToSave.takeFirst(), io ); ret << saveCurDocTask; } return ret; } QList< Task* > ExportToNewFileFromIndexTask::onSubTaskFinished( Task* subTask ) { assert( NULL != subTask ); if (isCanceled() || hasError()) { return QList< Task* >(); } GetDocumentFromIndexTask* getDocTask = qobject_cast< GetDocumentFromIndexTask* >( subTask ); if( NULL != getDocTask ) { return getDocTaskFinished( getDocTask ); } SaveDocumentStreamingTask* saveDocTask = qobject_cast< SaveDocumentStreamingTask* >( subTask ); if( NULL != saveDocTask ) { return saveDocTaskFinished( saveDocTask ); } assert( false ); return QList< Task* >(); } } // U2 ugene-1.9.8/src/corelibs/U2Core/src/tasks/ExtractAnnotatedRegionTask.cpp0000644000175000017500000001024711651544332024671 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include #include #include #include #include #include "ExtractAnnotatedRegionTask.h" namespace U2{ ExtractAnnotatedRegionTask::ExtractAnnotatedRegionTask( const DNASequence & sequence_, SharedAnnotationData sd_, const ExtractAnnotatedRegionTaskSettings & cfg_ ) : Task( tr("Extract annotated regions"), TaskFlag_None ), inputSeq(sequence_), inputAnn(sd_), cfg(cfg_), complT(0), aminoT(0) { } void ExtractAnnotatedRegionTask::prepare() { prepareTranslations(); resultedSeq.alphabet = aminoT ? aminoT->getDstAlphabet() : complT ? complT->getDstAlphabet() : inputSeq.alphabet; // resultedSeq.info = inputSeq.info; resultedSeq.info[DNAInfo::ID] = inputSeq.getName(); } void ExtractAnnotatedRegionTask::prepareTranslations() { //TODO move these logic somewhere upstairs bool aminoSeq = inputSeq.alphabet->isAmino(); if (aminoSeq) { return; } if (cfg.complement && inputAnn->getStrand().isCompementary()) { QList compTTs = AppContext::getDNATranslationRegistry()-> lookupTranslation( inputSeq.alphabet, DNATranslationType_NUCL_2_COMPLNUCL ); if (!compTTs.isEmpty()) { complT = compTTs.first(); } } if (cfg.translate) { DNATranslationType dnaTranslType = (inputSeq.alphabet->getType() == DNAAlphabet_NUCL) ? DNATranslationType_NUCL_2_AMINO : DNATranslationType_RAW_2_AMINO; QList aminoTTs = AppContext::getDNATranslationRegistry()->lookupTranslation( inputSeq.alphabet, dnaTranslType ); if( !aminoTTs.isEmpty() ) { aminoT = aminoTTs.first(); } } } void ExtractAnnotatedRegionTask::run() { QVector safeLocation = inputAnn->getRegions(); U2Region::bound(0, inputSeq.length(), safeLocation); QList resParts = SequenceUtils::extractRegions(inputSeq.constData(), safeLocation, complT); QVector resLocation = SequenceUtils::toJoinedRegions(resParts); if (aminoT == NULL) { // extension does not work for translated annotations if (cfg.extLeft > 0) { int annStart = safeLocation.first().startPos; int preStart = qMax(0, annStart - cfg.extLeft); int preLen = annStart - preStart; QByteArray preSeq = inputSeq.seq.mid(preStart, preLen); resParts.prepend(preSeq); U2Region::shift(cfg.extLeft, resLocation); } if (cfg.extRight) { U2Region annRegion = U2Region::containingRegion(safeLocation); int annEnd = annRegion.endPos(); int postEnd = qMin(inputSeq.length(), annEnd + cfg.extRight); int postLen = postEnd - annEnd; QByteArray postSeq = inputSeq.seq.mid(annEnd, postLen); resParts.append(postSeq); } } else { resParts = SequenceUtils::translateRegions(resParts, aminoT, inputAnn->isJoin()); resLocation = SequenceUtils::toJoinedRegions(resParts); } resultedSeq.seq = resParts.size() == 1 ? resParts.first() : SequenceUtils::joinRegions(resParts); resultedAnn = inputAnn; resultedAnn->location->regions = resLocation; resultedAnn->setStrand(U2Strand::Direct); resultedAnn->setLocationOperator(inputAnn->getLocationOperator()); } } // U2 ugene-1.9.8/src/corelibs/U2Core/src/tasks/GetDocumentFromIndexTask.h0000644000175000017500000000354111651544332023753 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_GET_DOCUMENT_FROM_INDEX_TASK_H_ #define _U2_GET_DOCUMENT_FROM_INDEX_TASK_H_ #include #include #include namespace U2 { struct GZipIndexAccessPoint; class U2CORE_EXPORT GetDocumentFromIndexTask : public Task { Q_OBJECT public: GetDocumentFromIndexTask( const UIndex& index, int docNum ); ~GetDocumentFromIndexTask(); virtual void run(); virtual ReportResult report(); virtual void cleanup(); Document* getDocument() const; Document* takeDocument(); private: bool fillAccessPointNums( GZipIndexAccessPoint& point, const QString& numStr ); bool getGzipIndexAccessPoint( GZipIndexAccessPoint& ret, const UIndex::IOSection& ioSec, qint64 offset ); IOAdapter* getOpenedIOAdapter(const UIndex::ItemSection& itemSec, const UIndex::IOSection& ioSec); private: UIndex index; int docNum; Document* doc; }; // GetDocumentFromIndexTask } // U2 #endif // _U2_GET_DOCUMENT_FROM_INDEX_TASK_H_ ugene-1.9.8/src/corelibs/U2Core/src/tasks/AddPartToSequenceTask.h0000644000175000017500000000354211651544332023235 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_ADD_PART_TO_SEQUENCE_TASK_H_ #define _U2_ADD_PART_TO_SEQUENCE_TASK_H_ #include #include #include #include namespace U2 { class U2CORE_EXPORT AddPartToSequenceTask : public Task { Q_OBJECT public: AddPartToSequenceTask(DocumentFormatId _df, DNASequenceObject *_seqObj, int _insertPos, DNASequence _seqPart, U2AnnotationUtils::AnnotationStrategyForResize _strat = U2AnnotationUtils::AnnotationStrategyForResize_Resize, const GUrl& _url = GUrl(), bool _mergeAnnotations = false); Task::ReportResult report(); private: void fixAnnotations(); void preparationForSave(); DocumentFormatId dfId; bool mergeAnnotations; Document *curDoc; Document *newDoc; bool save; GUrl url; U2AnnotationUtils::AnnotationStrategyForResize strat; QList docs; DNASequenceObject *seqObj; int insertPos; DNASequence seqPart; }; }//ns #endif ugene-1.9.8/src/corelibs/U2Core/src/tasks/TLSTask.h0000644000175000017500000000451311651544332020363 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _TLS_TASK_H_ #define _TLS_TASK_H_ #include #include namespace U2 { /************************************************************************/ /* Task with task local storage */ /************************************************************************/ class U2CORE_EXPORT TLSContext { friend class TLSUtils; public: TLSContext(QString _id) : id(_id) {} private: // class unique id const QString id; }; class TLSContextRef { public: TLSContextRef(TLSContext* _ctx) : ctx(_ctx){} TLSContext* ctx; }; class U2CORE_EXPORT TLSUtils { public: // Gets task local context, assigned to current thread static TLSContext* current(QString contextId); // Creates TLSContextRef for current thread static void bindToTLSContext(TLSContext *ctx); // Deletes TLSContextRef for current thread static void detachTLSContext(); private: static QThreadStorage tls; }; class U2CORE_EXPORT TLSTask : public Task { Q_OBJECT public: TLSTask(const QString& _name, TaskFlags _flags = TaskFlags_FOSCOE, bool deleteContext = true); ~TLSTask(); // tls context removed here void run(); void prepare(); protected: // Unsafe run. Use this method in derivate classes virtual void _run() {} // Creates instance of TLSContext. By default invokes in prepare() virtual TLSContext* createContextInstance()=0; TLSContext* taskContext; bool deleteContext; }; } //namespace #endif // _TLS_TASK_H_ ugene-1.9.8/src/corelibs/U2Core/src/tasks/SaveDocumentStreamingTask.cpp0000644000175000017500000000425211651544332024523 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include #include #include #include "SaveDocumentStreamingTask.h" namespace U2 { SaveDocumentStreamingTask::SaveDocumentStreamingTask( Document* d, IOAdapter* i ) : Task(tr("Save document"), TaskFlags(TaskFlag_None)), lock(NULL), doc(d), io(i) { if( NULL == doc ) { stateInfo.setError(L10N::badArgument("doc")); return; } if( NULL == io || !io->isOpen() ) { stateInfo.setError(L10N::badArgument("IO adapter")); return; } lock = new StateLock( getTaskName() ); tpm = Progress_Manual; } SaveDocumentStreamingTask::~SaveDocumentStreamingTask() { assert( NULL == lock ); } void SaveDocumentStreamingTask::prepare() { if( stateInfo.hasError() ) { return; } doc->lockState( lock ); } void SaveDocumentStreamingTask::run() { if( stateInfo.hasError() ) { return; } DocumentFormat* df = doc->getDocumentFormat(); df->storeDocument( doc, stateInfo, io ); } Task::ReportResult SaveDocumentStreamingTask::report() { if( NULL != doc ) { doc->makeClean(); doc->unlockState( lock ); } if( NULL != lock ) { delete lock; lock = NULL; } return ReportResult_Finished; } Document* SaveDocumentStreamingTask::getDocument() const { return doc; } } // U2 ugene-1.9.8/src/corelibs/U2Core/src/tasks/CreateAnnotationTask.h0000644000175000017500000000367311651544332023165 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_CREATE_ANNOTATION_TASK_H_ #define _U2_CREATE_ANNOTATION_TASK_H_ #include #include namespace U2 { class AnnotationTableObject; class AnnotationData; class U2CORE_EXPORT CreateAnnotationsTask : public Task { Q_OBJECT public: // Adds annotations to the object. Waits object to be unlocked if needed // Works only in a context of active project CreateAnnotationsTask(AnnotationTableObject* o, const QString& group, SharedAnnotationData data); CreateAnnotationsTask(AnnotationTableObject* o, const QString& group, QList data); CreateAnnotationsTask(const GObjectReference& ref, const QString& group, QList data); ReportResult report(); const QList& getAnnotations() const {return annotations;} private: GObjectReference aRef; QPointer aobj; QString groupName; QList aData; QList annotations; int pos; }; }//namespace #endif ugene-1.9.8/src/corelibs/U2Core/src/tasks/CopyDataTask.h0000644000175000017500000000260111651544332021421 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_COPY_DATA_TASK_H_ #define _U2_COPY_DATA_TASK_H_ #include #include namespace U2 { class IOAdapterFactory; class U2CORE_EXPORT CopyDataTask : public Task { Q_OBJECT public: CopyDataTask( IOAdapterFactory * ioFrom, const GUrl& urlFrom, IOAdapterFactory * ioTo, const GUrl& urlTo ); virtual void run(); private: static const int BUFFSIZE = 32 * 1024; IOAdapterFactory * ioFrom; IOAdapterFactory * ioTo; GUrl urlFrom; GUrl urlTo; }; }// namespace #endif ugene-1.9.8/src/corelibs/U2Core/src/tasks/LoadDocumentTask.h0000644000175000017500000001153211651544332022276 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_LOAD_DOCUMENT_TASK_H_ #define _U2_LOAD_DOCUMENT_TASK_H_ #include #include #include #include #include namespace U2 { class Document; class DocumentFormat; class IOAdapterFactory; class StateLock; class LoadDocumentTask; /** Base interface for different document loading tasks */ class U2CORE_EXPORT DocumentProviderTask : public Task { Q_OBJECT public: DocumentProviderTask(const QString& name, TaskFlags flags); virtual ~DocumentProviderTask() {cleanup();} virtual Document* getDocument() {return resultDocument;} virtual Document* takeDocument() {Document* d = resultDocument; resultDocument = NULL; return d;} virtual void cleanup(); virtual QString getDocumentDescription() const {return documentDescription;} protected: Document* resultDocument; /** provider's document description */ QString documentDescription; }; // creates object using name and type info from ref //NOTE: the default impl can create only limited set of objects class U2CORE_EXPORT LDTObjectFactory : public QObject { public: LDTObjectFactory(QObject* p) : QObject(p){} virtual GObject* create(const GObjectReference& ref); }; class U2CORE_EXPORT LoadDocumentTaskConfig { public: LoadDocumentTaskConfig(bool _createDoc = false, const GObjectReference& _ref = GObjectReference(), LDTObjectFactory* _f = NULL) : createDoc(_createDoc), checkObjRef(_ref), objFactory(_f){} bool createDoc; // if document is failed to load and 'createDoc' is true -> it will be created GObjectReference checkObjRef; // if is valid task checks that ref is found in doc, fails if not LDTObjectFactory* objFactory; // if not NULL and 'checkObjRef' is not found -> 'objFactory' is used to create obj }; class U2CORE_EXPORT LoadUnloadedDocumentTask : public Task { Q_OBJECT public: LoadUnloadedDocumentTask(Document* d, const LoadDocumentTaskConfig& config = LoadDocumentTaskConfig()); virtual void prepare(); virtual ReportResult report(); static QString getResourceName(Document* d); Document* getDocument() const; const LoadDocumentTaskConfig& getConfig() const {return config;} static LoadUnloadedDocumentTask* findActiveLoadingTask(Document* d); static bool addLoadingSubtask(Task* t, const LoadDocumentTaskConfig& config); private: void clearResourceUse(); class LoadDocumentTask* subtask; QPointer unloadedDoc; QString resName; LoadDocumentTaskConfig config; }; class U2CORE_EXPORT LoadDocumentTask : public DocumentProviderTask { Q_OBJECT public: static LoadDocumentTask * getDefaultLoadDocTask( const GUrl & url ); public: LoadDocumentTask(DocumentFormatId format, const GUrl& url, IOAdapterFactory* iof, const QVariantMap& hints = QVariantMap(), const LoadDocumentTaskConfig& config = LoadDocumentTaskConfig()); LoadDocumentTask(DocumentFormat* format, const GUrl& url, IOAdapterFactory* iof, const QVariantMap& hints = QVariantMap(), const LoadDocumentTaskConfig& config = LoadDocumentTaskConfig()); virtual void run(); virtual void prepare(); virtual ReportResult report(); const GUrl& getURL() const {return url;} private: void init(); void processObjRef(); /** Creates new document that contains data from original one restructured to new form according to document hints For example: combines all sequences to alignment, merge sequences, etc Return NULL if no restructuring was made */ static Document* createCopyRestructuredWithHints(const Document* doc, U2OpStatus& os); static void renameObjects(Document* doc, const QStringList& names); DocumentFormat* format; const GUrl url; IOAdapterFactory* iof; QVariantMap hints; LoadDocumentTaskConfig config; }; }//namespace #endif ugene-1.9.8/src/corelibs/U2Core/src/tasks/TaskStarter.cpp0000644000175000017500000000207211651544332021676 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "TaskStarter.h" #include namespace U2 { void TaskStarter::registerTask() { if (t) { AppContext::getTaskScheduler()->registerTopLevelTask(t); t = NULL; } } } //namespace ugene-1.9.8/src/corelibs/U2Core/src/tasks/GetDocumentFromIndexTask.cpp0000644000175000017500000001536011651544332024310 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include #include #include #include #include "GetDocumentFromIndexTask.h" namespace U2 { const QString ACCESS_POINTS_SZ_TAG = "APS"; const QString ACCESS_POINT_TAG = "AP"; const QString ACCESS_POINT_WND_TAG = "APW"; const QString SPACE = " "; const int ACCESS_POINTS_NUMS_AMOUNT = 3; bool GetDocumentFromIndexTask::fillAccessPointNums( GZipIndexAccessPoint& point, const QString& numStr ) { QStringList nums = numStr.split( SPACE, QString::SkipEmptyParts ); if( ACCESS_POINTS_NUMS_AMOUNT != nums.size() ) { return false; } bool ok = false; point.bits = nums[0].toInt( &ok ); if( !ok || 0 > point.bits ) { return false; } point.in = nums[1].toLongLong( &ok ); if( !ok ) { return false; } point.out = nums[2].toLongLong( &ok ); if( !ok ) { return false; } return true; } bool GetDocumentFromIndexTask::getGzipIndexAccessPoint( GZipIndexAccessPoint& ret, const UIndex::IOSection& ioSec, qint64 offset ) { assert( 0 <= offset ); if( !ioSec.keys.contains( ACCESS_POINTS_SZ_TAG ) ) { return false; } bool ok = false; int indSz = ioSec.keys[ACCESS_POINTS_SZ_TAG].toInt( &ok ); if( !ok || 0 >= indSz ) { return false; } GZipIndexAccessPoint next; ok = fillAccessPointNums( next, ioSec.keys.value( ACCESS_POINT_TAG + QString::number( 0 ) ) ); if( !ok ) { return false; } int i = 0; for( i = 0; i < indSz; ++i ) { ret = next; if( indSz - 1 == i ) { break; } else { ok = fillAccessPointNums( next, ioSec.keys.value( ACCESS_POINT_TAG + QString::number( i + 1 ) ) ); if( !ok ) { return false; } if( next.out > offset ) { break; } } } QString wndTag = ACCESS_POINT_WND_TAG + QString::number( i ); if( !ioSec.keys.contains( wndTag ) ) { return false; } QByteArray wnd = QByteArray::fromBase64( ioSec.keys.value( wndTag ).toAscii() ); ret.window = qUncompress( wnd ); assert( GZipIndex::WINSIZE == ret.window.size() ); return true; } IOAdapter* GetDocumentFromIndexTask::getOpenedIOAdapter(const UIndex::ItemSection& itemSec, const UIndex::IOSection& ioSec) { IOAdapterId adId = ioSec.ioAdapterId; IOAdapterFactory* factory = AppContext::getIOAdapterRegistry()->getIOAdapterFactoryById( adId ); if( NULL == factory ) { setError(tr( "Can't find IO adapter: %1" ).arg( adId )); return NULL; } IOAdapter* ret = factory->createIOAdapter(); bool ok = ret->open( ioSec.url, IOAdapterMode_Read ); if( !ok ) { delete ret; setError(tr( "Can't open file for read: '%1'" ).arg(ioSec.url)); return NULL; } if( BaseIOAdapters::LOCAL_FILE == adId ) { bool ok = ret->skip( itemSec.startOff ); if( !ok ) { delete ret; setError(tr( "Error positioning in indexed file" )); return NULL; } } else if( BaseIOAdapters::GZIPPED_LOCAL_FILE == adId ) { ZlibAdapter* gzAdapter = qobject_cast< ZlibAdapter* >( ret ); assert( NULL != gzAdapter ); GZipIndexAccessPoint accessPoint; bool ok = getGzipIndexAccessPoint( accessPoint, ioSec, itemSec.startOff ); if( !ok ) { setError(tr( "GZIP index is corrupted" )); delete ret; return NULL; } ok = gzAdapter->skip( accessPoint, itemSec.startOff ); if( !ok ) { setError(tr( "Error positioning in indexed file" )); delete ret; return NULL; } } else { // others not supported return NULL; } return ret; } GetDocumentFromIndexTask::GetDocumentFromIndexTask( const UIndex& ind, int num ) : Task( tr( "Get document from index" ), TaskFlag_None ), index( ind ), docNum( num ), doc( NULL ) { tpm = Progress_Manual; if( !index.hasItems() ) { stateInfo.setError(tr( "Index is empty" )); return; } if( 0 > docNum || docNum >= index.items.size() ) { stateInfo.setError(tr( "Invalid document number: %1, max: %2").arg(docNum).arg(index.items.size())); return; } } GetDocumentFromIndexTask::~GetDocumentFromIndexTask() { cleanup(); } void GetDocumentFromIndexTask::run() { if( stateInfo.hasError() ) { return; } UIndex::ItemSection itemSec = index.items[docNum]; UIndex::IOSection ioSec = index.getIOSection( itemSec.ioSectionId ); if( ioSec.sectionId.isEmpty() ) { stateInfo.setError(tr( "Index is corrupted" )); return; } IOAdapter* ioAdapt = getOpenedIOAdapter( itemSec, ioSec); if( NULL == ioAdapt ) { assert( stateInfo.hasError() ); return; } assert( ioAdapt->isOpen() ); DocumentFormat* df = AppContext::getDocumentFormatRegistry()->getFormatById( itemSec.docFormat ); if( NULL == df ) { delete ioAdapt; stateInfo.setError(tr( "Unknown document format: %1" ).arg(itemSec.docFormat)); return; } doc = df->loadDocument( ioAdapt, stateInfo, QVariantMap(), DocumentLoadMode_SingleObject ); assert( isCanceled() || NULL != doc || hasError() ); assert( NULL == doc || doc->isLoaded() ); delete ioAdapt; } Task::ReportResult GetDocumentFromIndexTask::report() { if ( stateInfo.hasError() || isCanceled() ) { return ReportResult_Finished; } assert( NULL != doc ); return ReportResult_Finished; } void GetDocumentFromIndexTask::cleanup() { if( NULL != doc ) { delete doc; doc = NULL; } } Document* GetDocumentFromIndexTask::getDocument() const { return doc; } Document* GetDocumentFromIndexTask::takeDocument() { Document* ret = doc; doc = NULL; return ret; } } // U2 ugene-1.9.8/src/corelibs/U2Core/src/tasks/MultiTask.h0000644000175000017500000000232411651544332021011 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_MULTI_TASK_H_ #define _U2_MULTI_TASK_H_ #include #include #include namespace U2 { class U2CORE_EXPORT MultiTask : public Task { Q_OBJECT public: MultiTask( const QString & name, const QList& taskz ); QList getTasks() const; private: QList tasks; }; } //namespace #endif ugene-1.9.8/src/corelibs/U2Core/src/tasks/ScriptTask.h0000644000175000017500000000474711651544332021176 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_SCRIPT_TASK_H_ #define _U2_SCRIPT_TASK_H_ #include #include #include namespace U2 { // Class to configure script task class U2CORE_EXPORT ScriptTaskSettings { public: ScriptTaskSettings() : mainThreadScript(false) {} // Tells if to run script in main thread. Otherwise the task is executed during reporting stage bool mainThreadScript; // Map of input script parameters QMap inputParametersMap; }; // Basic implementation of script task class U2CORE_EXPORT ScriptTask : public Task { Q_OBJECT public: ScriptTask(const QString& taskName, const QString& scriptText, const ScriptTaskSettings& settings = ScriptTaskSettings()); // Returns settings this task was/will run with const ScriptTaskSettings& getSettings() const {return conf;} // Returns the result of script execution const QScriptValue& getResult() const {return result;} bool isMainThreadScript() const {return conf.mainThreadScript;} // Used to run script if mainThreadScript is FALSE void run(); // Used to run script if mainThreadScript is TRUE ReportResult report(); // Runs the script using given input parameters // Returns the result of the script // If error occurs -> sets the error message into 'errorMessage' parameter static QScriptValue runScript(QScriptEngine* engine, const QMap& inputParametersMap, const QString& scriptText, TaskStateInfo& stateInfo); private: QString scriptText; ScriptTaskSettings conf; QScriptValue result; }; } //namespace #endif ugene-1.9.8/src/corelibs/U2Core/src/tasks/SequenceWalkerTask.h0000644000175000017500000001122111651544332022631 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_SEQUENCE_WALKER_TASK_H_ #define _U2_SEQUENCE_WALKER_TASK_H_ #include #include namespace U2 { class DNATranslation; class SequenceWalkerSubtask; enum StrandOption { StrandOption_DirectOnly, StrandOption_ComplementOnly, StrandOption_Both }; class U2CORE_EXPORT SequenceWalkerConfig { public: //TODO: allow select custom strand only! SequenceWalkerConfig(); const char* seq; // sequence to split int seqSize; // size of the sequence to split U2Region range; // if not empty -> only this region is processed DNATranslation* complTrans; DNATranslation* aminoTrans; int chunkSize; // optimal chunk size, used by default for all regions except last one int lastChunkExtraLen; // extra length allowed to be added to the last chunk int overlapSize; // overlap for 2 neighbor regions int nThreads; StrandOption strandToWalk; }; class U2CORE_EXPORT SequenceWalkerCallback { public: virtual ~SequenceWalkerCallback(){} virtual void onRegion(SequenceWalkerSubtask* t, TaskStateInfo& ti) = 0; /* implement this to give SequenceWalkerSubtask required resources * here are resources for ONE(!) SequenceWalkerSubtask execution e.g. for one execution of onRegion function */ virtual QList< TaskResourceUsage > getResources( SequenceWalkerSubtask * t ) {Q_UNUSED(t); return QList< TaskResourceUsage >(); } }; class U2CORE_EXPORT SequenceWalkerTask : public Task { Q_OBJECT public: SequenceWalkerTask(const SequenceWalkerConfig& config, SequenceWalkerCallback* callback, const QString& name, TaskFlags tf = TaskFlags_NR_FOSCOE); SequenceWalkerCallback* getCallback() const {return callback;} const SequenceWalkerConfig& getConfig() const {return config;} // reverseMode - start splitting from the end of the range static QVector splitRange(const U2Region& range, int chunkSize, int overlapSize, int lastChunkExtraLen, bool reverseMode); void setError(const QString& err) {stateInfo.setError(err);} private: QList prepareSubtasks(); QList createSubs(const QVector& chunks, bool doCompl, bool doAmino); SequenceWalkerConfig config; SequenceWalkerCallback* callback; }; class U2CORE_EXPORT SequenceWalkerSubtask : public Task { Q_OBJECT public: SequenceWalkerSubtask(SequenceWalkerTask* t, const U2Region& globalReg, bool lo, bool ro, const char* localSeq, int localLen, bool doCompl, bool doAmino); void run(); const char* getRegionSequence(); int getRegionSequenceLen(); bool isDNAComplemented() const {return doCompl;} bool isAminoTranslated() const {return doAmino;} U2Region getGlobalRegion() const {return globalRegion;} const SequenceWalkerConfig& getGlobalConfig() const {return t->getConfig();} bool intersectsWithOverlaps(const U2Region& globalReg) const; bool hasLeftOverlap() const {return leftOverlap;} bool hasRightOverlap() const {return rightOverlap;} private: bool needLocalRegionProcessing() const {return (doAmino || doCompl) && processedSeqImage.isEmpty();} void prepareLocalRegion(); SequenceWalkerTask* t; U2Region globalRegion; const char* localSeq; const char* originalLocalSeq; int localLen; int originalLocalLen; bool doCompl; bool doAmino; bool leftOverlap; bool rightOverlap; QByteArray processedSeqImage; }; }//namespace #endif ugene-1.9.8/src/corelibs/U2Core/src/tasks/TaskStarter.h0000644000175000017500000000230711651544332021344 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_TASK_STARTER_H_ #define _U2_TASK_STARTER_H_ #include namespace U2 { /** * Intended for deferred task run, triggered by a signal. */ class U2CORE_EXPORT TaskStarter : public QObject { Q_OBJECT public: TaskStarter(Task* t) : QObject(t), t(t) {} public slots: void registerTask(); private: Task* t; }; } //namespace #endif ugene-1.9.8/src/corelibs/U2Core/src/tasks/ReplacePartOfSequenceTask.h0000644000175000017500000000370711651544332024105 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_REPLACE_PART_OF_SEQUENCE_TASK_H_ #define _U2_REPLACE_PART_OF_SEQUENCE_TASK_H_ #include #include #include #include namespace U2 { class Annotation; class U2CORE_EXPORT ReplacePartOfSequenceTask : public Task { Q_OBJECT public: ReplacePartOfSequenceTask(DocumentFormatId _dfId, DNASequenceObject *_seqObj, U2Region _regionToReplace, const DNASequence& newSeq, U2AnnotationUtils::AnnotationStrategyForResize _str = U2AnnotationUtils::AnnotationStrategyForResize_Resize, const GUrl& _url = GUrl(), bool _mergeAnnotations = false); virtual Task::ReportResult report(); private: void fixAnnotations(); void preparationForSave(); DocumentFormatId dfId; bool mergeAnnotations; Document *curDoc; Document *newDoc; bool save; GUrl url; U2AnnotationUtils::AnnotationStrategyForResize strat; QList docs; DNASequenceObject *seqObj; QByteArray newSeq; U2Region regionToReplace; }; } // U2 #endif //_U2_REPLACE_PART_OF_SEQUENCE_TASK_H_ ugene-1.9.8/src/corelibs/U2Core/src/tasks/RemovePartFromSequenceTask.cpp0000644000175000017500000001617511651544332024664 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "RemovePartFromSequenceTask.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include namespace U2 { RemovePartFromSequenceTask::RemovePartFromSequenceTask(DocumentFormatId _dfId, DNASequenceObject *_seqObj, U2Region _regionTodelete, U2AnnotationUtils::AnnotationStrategyForResize _str, const GUrl& _url, bool _mergeAnnotations ) :Task(tr("Remove subsequence"), TaskFlag_NoRun), dfId(_dfId), mergeAnnotations(_mergeAnnotations), save(true), url(_url), strat(_str), seqObj(_seqObj), regionToDelete(_regionTodelete) { GCOUNTER( cvar, tvar, "RemovePartFromSequenceTask" ); curDoc = seqObj->getDocument(); if(url == curDoc->getURL() || _url.isEmpty()){ save = false; return; } } Task::ReportResult RemovePartFromSequenceTask::report(){ if(regionToDelete == U2Region(0,0)) { return ReportResult_Finished; } DNASequence sequence = seqObj->getDNASequence(); U2Region allSeq(0, sequence.length()); if(!allSeq.contains(regionToDelete)){ algoLog.error(tr("Region to delete is larger than the whole sequence")); return ReportResult_Finished; } Project *p = AppContext::getProject(); if(p != NULL){ if(p->isStateLocked()){ return ReportResult_CallMeAgain; } docs = p->getDocuments(); } if(!docs.contains(curDoc)){ docs.append(curDoc); } if(curDoc->isStateLocked()){ algoLog.error(tr("Document is locked")); return ReportResult_Finished; } if(save){ preparationForSave(); } sequence.seq.remove(regionToDelete.startPos, regionToDelete.length); seqObj->setSequence(sequence); fixAnnotations(); if(save){ QList tasks; IOAdapterFactory* iof = AppContext::getIOAdapterRegistry()->getIOAdapterFactoryById(BaseIOAdapters::url2io(url)); tasks.append(new SaveDocumentTask(seqObj->getDocument(), iof, url.getURLString())); Project *p = AppContext::getProject(); if(p != NULL){ tasks.append(new AddDocumentTask(newDoc)); } AppContext::getTaskScheduler()->registerTopLevelTask(new MultiTask("Save document and add it to project (optional)", tasks)); } return ReportResult_Finished; } void RemovePartFromSequenceTask::fixAnnotations(){ foreach(Document *d, docs){ QList annotationTablesList = d->findGObjectByType(GObjectTypes::ANNOTATION_TABLE); foreach(GObject *table, annotationTablesList){ AnnotationTableObject *ato = qobject_cast(table); if(ato->hasObjectRelation(seqObj, GObjectRelationRole::SEQUENCE)){ QList annList = ato->getAnnotations(); foreach(Annotation *an, annList){ QVector locs = an->getRegions(); U2AnnotationUtils::fixLocationsForRemovedRegion(regionToDelete, locs, strat); if(!locs.isEmpty()){ an->replaceRegions(locs); }else{ ato->removeAnnotation(an); } } } } } } void RemovePartFromSequenceTask::preparationForSave(){ IOAdapterFactory* iof = AppContext::getIOAdapterRegistry()->getIOAdapterFactoryById(BaseIOAdapters::url2io(url)); DocumentFormat *df = AppContext::getDocumentFormatRegistry()->getFormatById(dfId); if (iof == NULL) { return; } QList objList = curDoc->getObjects(); if(mergeAnnotations){ DNASequenceObject *oldObj = seqObj; newDoc = df->createNewDocument(iof, url, curDoc->getGHintsMap()); foreach(GObject* go, objList){ if(df->isObjectOpSupported(newDoc, DocumentFormat::DocObjectOp_Add, go->getGObjectType()) && (go->getGObjectType() != GObjectTypes::SEQUENCE || go == seqObj) && go->getGObjectType() != GObjectTypes::ANNOTATION_TABLE){ GObject *cl = go->clone(); newDoc->addObject(cl); if(go == seqObj){ seqObj = qobject_cast(cl); } GObjectUtils::updateRelationsURL(cl, curDoc->getURL(), url); } } AnnotationTableObject *newDocAto = new AnnotationTableObject("Annotations"); newDoc->addObject(newDocAto); newDocAto->addObjectRelation(seqObj, GObjectRelationRole::SEQUENCE); foreach(Document *d, docs){ QList annotationTablesList = d->findGObjectByType(GObjectTypes::ANNOTATION_TABLE); foreach(GObject *table, annotationTablesList){ AnnotationTableObject *ato = (AnnotationTableObject*)table; if(ato->hasObjectRelation(oldObj, GObjectRelationRole::SEQUENCE)){ foreach(Annotation *ann, ato->getAnnotations()){ QStringList groupNames; foreach(AnnotationGroup* gr,ann->getGroups()){ groupNames.append(gr->getGroupName()); } newDocAto->addAnnotation(new Annotation(ann->data()), groupNames); } } } } }else{ newDoc = df->createNewDocument(iof, url, curDoc->getGHintsMap()); foreach(GObject* go, objList){ if(df->isObjectOpSupported(newDoc, DocumentFormat::DocObjectOp_Add, go->getGObjectType())){ GObject *cl = go->clone(); newDoc->addObject(cl); if(go == seqObj){ seqObj = qobject_cast(cl); } GObjectUtils::updateRelationsURL(cl, curDoc->getURL(), url); } } } docs.append(newDoc); } }//ns ugene-1.9.8/src/corelibs/U2Core/src/gobjects/0000755000175000017500000000000011651544331017374 5ustar ilyailyaugene-1.9.8/src/corelibs/U2Core/src/gobjects/DNASequenceObject.cpp0000644000175000017500000001234611651544331023330 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "DNASequenceObject.h" #include "GObjectTypes.h" #include #include #include #include namespace U2 { DNASequenceObjectSequenceDbiWrapper::DNASequenceObjectSequenceDbiWrapper(const QList & _seqObjs, U2Dbi * root) : QObject(_seqObjs.first()), U2SimpleSequenceDbi(root), seqObjs(_seqObjs){ } static DNASequenceObject* findObjById(const U2DataId & seqId, const QList & objs) { foreach(DNASequenceObject* obj, objs) { if(obj->getGObjectName().toUtf8() == seqId) { return obj; } } return NULL; } U2Sequence DNASequenceObjectSequenceDbiWrapper::getSequenceObject(const U2DataId& sequenceId, U2OpStatus& ) { DNASequenceObject * seqObj = findObjById(sequenceId, seqObjs); if(seqObj == NULL) { // FIXME raise error? return U2Sequence(); } Document* doc = seqObj->getDocument(); QString docUrl = (doc == NULL) ? QString("") : doc->getURLString(); U2Sequence res(seqObj->getGObjectName().toUtf8(), docUrl, 0); res.alphabet = seqObj->getAlphabet()->getId(); res.length = seqObj->getSequenceLen(); res.circular = seqObj->isCircular(); return res; } QByteArray DNASequenceObjectSequenceDbiWrapper::getSequenceData(const U2DataId& sequenceId, const U2Region& region, U2OpStatus& ) { GTIMER(c1, t1, "DNASequenceObjectSequenceDbiWrapper::getSequenceData"); DNASequenceObject * seqObj = findObjById(sequenceId, seqObjs); if(seqObj == NULL) { // FIXME raise error? return QByteArray(); } return seqObj->getSequence().mid(region.startPos, region.length); } DNASequenceObject::DNASequenceObject(const QString& name, const DNASequence& seq, const QVariantMap& hintsMap) : GObject(GObjectTypes::SEQUENCE, name, hintsMap), dnaSeq(seq), dbi(NULL) { assert(dnaSeq.alphabet!=NULL); seqRange = U2Region(0, dnaSeq.seq.length()); dbi = new DNASequenceObjectSequenceDbiWrapper(QList() << this, NULL); } DNASequenceObject::~DNASequenceObject() { delete dbi; } GObject* DNASequenceObject::clone() const { DNASequenceObject* cln = new DNASequenceObject(getGObjectName(), dnaSeq, getGHintsMap()); cln->setIndexInfo(getIndexInfo()); return cln; } void DNASequenceObject::setBase(int pos, char base) { SAFE_POINT(pos >=0 && pos < dnaSeq.length(), "Position is out of range!",); dnaSeq.seq[pos] = base; setModified(true); } bool DNASequenceObject::checkConstraints(const GObjectConstraints* c) const { const DNASequenceObjectConstraints* dnac = qobject_cast(c); bool resultDNAConstraints = true; bool resultAlphabetType = true; if (dnac->exactSequenceSize != dnaSeq.length()) { resultDNAConstraints = false; } if (dnac->exactSequenceSize <= 0) { resultDNAConstraints = true; } if (dnac->alphabetType != getAlphabet()->getType()) { resultAlphabetType = false; } if (dnac->alphabetType == DNAAlphabet_RAW) { resultAlphabetType = true; } return (resultDNAConstraints && resultAlphabetType); } void DNASequenceObject::setCircular(bool val) { dnaSeq.circular = val; } void DNASequenceObject::setSequence( DNASequence seq ){ dnaSeq = seq; U2Region range(0, seq.length()); seqRange = range; setModified(true); emit si_sequenceChanged(); } void DNASequenceObject::setQuality( const DNAQuality& quality ) { setModified(true); dnaSeq.quality = quality; emit si_sequenceChanged(); } DNASequenceObjectConstraints::DNASequenceObjectConstraints(QObject* p) : GObjectConstraints(GObjectTypes::SEQUENCE, p), exactSequenceSize(-1) { } /* U2Sequence DNASequenceObject::getSequenceObject(U2DataId sequenceId, U2OpStatus& os) { GObjectReference ref(this); U2Sequence res; res.id = sequenceId; res.dbiId = ref.docUrl + "|" + ref.objName; res.alphabet = dnaSeq.alphabet->getId(); res.length = dnaSeq.length(); res.circular = isCircular(); res.version = -1; // not supported return res; } QByteArray DNASequenceObject::getSequenceData(U2DataId sequenceId, const U2Region& region, U2OpStatus& os) { U2Region safeRegion = seqRange.intersect(region); if (safeRegion.isEmpty()) { return QByteArray(); } return dnaSeq.seq.mid(safeRegion.startPos, safeRegion.length); } */ }//namespace ugene-1.9.8/src/corelibs/U2Core/src/gobjects/GObjectUtils.h0000644000175000017500000000666511651544331022120 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_GOBJECT_UTILS_H_ #define _U2_GOBJECT_UTILS_H_ #include "GObjectTypes.h" #include namespace U2 { class AnnotationTableObject; class Annotation; class DNASequenceObject; class DNATranslation; class DNASequence; class GUrl; class U2CORE_EXPORT GObjectUtils { public: static QList select(const QList& objects, GObjectType type, UnloadedObjectFilter f); static GObject* selectOne(const QList& objects, GObjectType type, UnloadedObjectFilter f); static QList findAllObjects(UnloadedObjectFilter f, GObjectType t = GObjectType()); // select objects from 'fromObjects' // that are referenced by relations stored in 'obj' with 'relationRole' and 'type' static QList selectRelations(GObject* obj, GObjectType type, const QString& relationRole, const QList& fromObjects, UnloadedObjectFilter f); static QList findObjectsRelatedToObjectByRole(const GObject* obj, GObjectType resultObjType, const QString& relationRole, const QList& fromObjects, UnloadedObjectFilter f); // selects objects from 'fromObjects' with filter 'f' that have relation(relationRole, type) // 'availableObjectsOnly' -> check if the related object is in project static QList selectObjectsWithRelation(const QList& fromObjects, GObjectType type, const QString& relationRole, UnloadedObjectFilter f, bool availableObjectsOnly); static GObject* selectObjectByReference(const GObjectReference& r, const QList& fromObjects, UnloadedObjectFilter f); static GObject* selectObjectByReference(const GObjectReference& r, UnloadedObjectFilter f); static DNATranslation* findComplementTT(DNASequenceObject* so); static DNATranslation* findAminoTT(DNASequenceObject* so, bool fromHintsOnly, const QString& table = NULL); static DNATranslation* findBackTranslationTT(DNASequenceObject* so, const QString& table = NULL); //checks object type for both loaded and unloaded states static bool hasType(GObject* obj, const GObjectType& type); static void updateRelationsURL(GObject* o, const QString& fromURL, const QString& toURL); static void updateRelationsURL(GObject* o, const GUrl& fromURL, const GUrl& toURL); static void replaceAnnotationQualfier(Annotation* a, const QString& name, const QString& newVal, bool create = false); }; } // namespace #endif ugene-1.9.8/src/corelibs/U2Core/src/gobjects/GObjectTypes.h0000644000175000017500000000441111651544331022107 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_GOBJECT_TYPES_H_ #define _U2_GOBJECT_TYPES_H_ #include #include namespace U2 { class U2CORE_EXPORT GObjectTypeInfo { public: GObjectTypeInfo(){} GObjectTypeInfo(const GObjectType& _type, const QString& _name, const QString& _pluralName, const QString& treeSign, const QString iconURL); GObjectType type; QString name; QString pluralName; QString treeSign; QString iconURL; QIcon icon; }; class U2CORE_EXPORT GObjectTypes { public: static const GObjectType UNKNOWN; static const GObjectType UNLOADED; static const GObjectType TEXT; static const GObjectType SEQUENCE; static const GObjectType ANNOTATION_TABLE; static const GObjectType CHROMATOGRAM; static const GObjectType MULTIPLE_ALIGNMENT; static const GObjectType PHYLOGENETIC_TREE; static const GObjectType BIOSTRUCTURE_3D; static const GObjectType UINDEX; static const GObjectType ASSEMBLY; static GObjectType registerTypeInfo(const GObjectTypeInfo& ti); //Returns reference to the type by type. //WARN: Caching return value by reference is not safe -> it can be relocated if new type is registered static const GObjectTypeInfo& getTypeInfo(const GObjectType& type); static void initTypeTranslations(); //must be called only once after all translations are loaded static void initTypeIcons(); }; }//namespace #endif ugene-1.9.8/src/corelibs/U2Core/src/gobjects/DNAChromatogramObject.h0000644000175000017500000000256011651544331023645 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_DNA_CHROMATOGRAM_OBJECT_H_ #define _U2_DNA_CHROMATOGRAM_OBJECT_H_ #include #include namespace U2 { class U2CORE_EXPORT DNAChromatogramObject: public GObject { Q_OBJECT public: DNAChromatogramObject(const DNAChromatogram& chrom, const QString& objectName, const QVariantMap& hints = QVariantMap()); const DNAChromatogram& getChromatogram() const {return chrom;} virtual GObject* clone() const; protected: DNAChromatogram chrom; }; }//namespace #endif ugene-1.9.8/src/corelibs/U2Core/src/gobjects/TextObject.h0000644000175000017500000000263711651544331021630 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_TEXT_OBJECT_H_ #define _U2_TEXT_OBJECT_H_ #include #include "GObjectTypes.h" namespace U2 { class U2CORE_EXPORT TextObject: public GObject { Q_OBJECT public: TextObject(const QString& _text, const QString& objectName, const QVariantMap& hintsMap = QVariantMap()) : GObject(GObjectTypes::TEXT, objectName, hintsMap), text(_text){}; virtual const QString& getText() const {return text;} virtual void setText(const QString& newText); virtual GObject* clone() const; protected: QString text; }; }//namespace #endif ugene-1.9.8/src/corelibs/U2Core/src/gobjects/GObjectUtils.cpp0000644000175000017500000002146411651544331022445 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "GObjectUtils.h" #include "DNASequenceObject.h" #include "AnnotationTableObject.h" #include #include #include #include #include #include #include #include #include #include namespace U2 { QList GObjectUtils::select(const QList& objs, GObjectType t, UnloadedObjectFilter f) { QList res; foreach(GObject* o, objs) { bool isUnloaded = o->getGObjectType() == GObjectTypes::UNLOADED; if ((t.isEmpty() && (f == UOF_LoadedAndUnloaded || !isUnloaded)) || o->getGObjectType() == t) { res.append(o); } else if (f == UOF_LoadedAndUnloaded && isUnloaded) { UnloadedObject* uo = qobject_cast(o); if (uo->getLoadedObjectType() == t) { res.append(o); } } } return res; } GObject* GObjectUtils::selectOne(const QList& objects, GObjectType type, UnloadedObjectFilter f) { QList res = select(objects, type, f); return res.isEmpty() ? NULL : res.first(); } QList GObjectUtils::findAllObjects(UnloadedObjectFilter f, GObjectType t) { QList res; SAFE_POINT(AppContext::getProject()!=NULL, "No active project found", res); foreach(Document* doc, AppContext::getProject()->getDocuments()) { if (t.isEmpty()) { if (doc->isLoaded() || f == UOF_LoadedAndUnloaded) { res+=doc->getObjects(); } } else { res+=doc->findGObjectByType(t, f); } } return res; } QList GObjectUtils::selectRelations(GObject* obj, GObjectType type, const QString& relationRole, const QList& fromObjects, UnloadedObjectFilter f) { QList res; QList relations = obj->getObjectRelations(); foreach(const GObjectRelation& r, relations) { if (r.role != relationRole || (!type.isEmpty() && r.ref.objType!=type)) { continue; } GObject* obj = selectObjectByReference(r.ref, fromObjects, f); if (obj!=NULL) { res.append(obj); } } return res; } QList GObjectUtils::findObjectsRelatedToObjectByRole(const GObject* obj, GObjectType resultObjType, const QString& role, const QList& fromObjects, UnloadedObjectFilter f) { QList res; QList objects = select(fromObjects, resultObjType, f); foreach(GObject* o, objects) { if (o->hasObjectRelation(obj, role)) { res.append(o); } } return res; } QList GObjectUtils::selectObjectsWithRelation(const QList& objs, GObjectType type, const QString& relationRole, UnloadedObjectFilter f, bool availableObjectsOnly) { QSet availableObjects; if (availableObjectsOnly) { availableObjects = findAllObjects(f).toSet(); } QList res; foreach(GObject* obj, objs) { QList relations = obj->getObjectRelations(); foreach(const GObjectRelation& r, relations) { if (r.role != relationRole || (!type.isEmpty() && r.ref.objType!=type)) { continue; } if (availableObjectsOnly) { Document* doc = AppContext::getProject()->findDocumentByURL(r.ref.docUrl); GObject* refObj = doc == NULL ? NULL : doc->findGObjectByName(r.ref.objName); if (refObj == NULL || (f == UOF_LoadedOnly && refObj->getGObjectType() == GObjectTypes::UNLOADED)) { continue; } } res.append(obj); } } return res; } GObject* GObjectUtils::selectObjectByReference(const GObjectReference& r, UnloadedObjectFilter f) { return selectObjectByReference(r, findAllObjects(f, r.objType), f); } GObject* GObjectUtils::selectObjectByReference(const GObjectReference& r, const QList& fromObjects, UnloadedObjectFilter f) { foreach(GObject* o, fromObjects) { if (o->getGObjectName() != r.objName) { continue; } if ((o->getDocument() == NULL && !r.docUrl.isEmpty()) || (o->getDocument()->getURL() != r.docUrl)) { continue; } if (r.objType != o->getGObjectType()) { if (f != UOF_LoadedAndUnloaded) { continue; } if (o->getGObjectType()!=GObjectTypes::UNLOADED || r.objType != qobject_cast(o)->getLoadedObjectType()) { continue; } } return o; } return NULL; } DNATranslation* GObjectUtils::findComplementTT(DNASequenceObject* so) { if (!so->getAlphabet()->isNucleic()) { return NULL; } return AppContext::getDNATranslationRegistry()->lookupComplementTranslation(so->getAlphabet()); } DNATranslation* GObjectUtils::findAminoTT(DNASequenceObject* so, bool fromHintsOnly, const QString& table) { if (!so->getAlphabet()->isNucleic()) { return NULL; } DNATranslationRegistry* tr = AppContext::getDNATranslationRegistry(); QString tid = so->getGHints()->get(AMINO_TT_GOBJECT_HINT).toString(); if (table != NULL) { DNATranslation* res = tr->lookupTranslation(so->getAlphabet(), DNATranslationType_NUCL_2_AMINO, table); return res; } DNATranslation* res = tr->lookupTranslation(so->getAlphabet(), DNATranslationType_NUCL_2_AMINO, tid); if (res != NULL || fromHintsOnly) { return res; } QList aminoTs = tr->lookupTranslation(so->getAlphabet(), DNATranslationType_NUCL_2_AMINO); if (!aminoTs.empty()) { res = aminoTs.first(); } return res; } DNATranslation* GObjectUtils::findBackTranslationTT(DNASequenceObject* so, const QString& table) { if (!so->getAlphabet()->isAmino()) { return NULL; } DNATranslationRegistry* tr = AppContext::getDNATranslationRegistry(); if (table != NULL) { DNATranslation* res = tr->lookupTranslation(so->getAlphabet(), DNATranslationType_AMINO_2_NUCL, table); return res; } QList dnaTs = tr->lookupTranslation(so->getAlphabet(), DNATranslationType_AMINO_2_NUCL); DNATranslation* res = NULL; if (!dnaTs.empty()) { res = dnaTs.first(); } return res; } bool GObjectUtils::hasType(GObject* obj, const GObjectType& type) { if (obj->getGObjectType() == type) { return true; } if (obj->getGObjectType() != GObjectTypes::UNLOADED) { return false; } UnloadedObject* uo = qobject_cast(obj); return uo->getLoadedObjectType() == type; } void GObjectUtils::updateRelationsURL(GObject* o, const GUrl& fromURL, const GUrl& toURL) { updateRelationsURL(o, fromURL.getURLString(), toURL.getURLString()); } void GObjectUtils::updateRelationsURL(GObject* o, const QString& fromURL, const QString& toURL) { QList relations = o->getObjectRelations(); bool changed = false; for(int i=0; isetObjectRelations(relations); } } void GObjectUtils::replaceAnnotationQualfier( Annotation* a, const QString& name, const QString& newVal, bool create ) { QVector quals; a->findQualifiers(name, quals); foreach (const U2Qualifier& q, quals) { a->removeQualifier(q); } if (create || quals.size() > 0) { a->addQualifier(name, newVal); } } } //namespace ugene-1.9.8/src/corelibs/U2Core/src/gobjects/UIndexObject.cpp0000644000175000017500000000254311651544331022427 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "UIndexObject.h" namespace U2 { const QString UIndexObject::OBJ_NAME = "Index"; UIndexObject::UIndexObject( const UIndex& a_ind, const QString& name ) : GObject( GObjectTypes::UINDEX, name ), ind( a_ind ){} UIndex UIndexObject::getIndex() const { return ind; } GObject* UIndexObject::clone() const { UIndexObject* cln = new UIndexObject( ind, getGObjectName() ); cln->setIndexInfo(getIndexInfo()); return cln; } } // U2 ugene-1.9.8/src/corelibs/U2Core/src/gobjects/GObjectRelationRoles.cpp0000644000175000017500000000201611651544331024117 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "GObjectRelationRoles.h" namespace U2 { const QString GObjectRelationRole::SEQUENCE("sequence"); const QString GObjectRelationRole::ANNOTATION_TABLE("annotation_table"); } ugene-1.9.8/src/corelibs/U2Core/src/gobjects/MAlignmentObject.cpp0000644000175000017500000002174611651544331023274 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "MAlignmentObject.h" #include #include #include #include namespace U2 { GObject* MAlignmentObject::clone() const { MAlignmentObject* cln = new MAlignmentObject(msa, getGHintsMap()); cln->setIndexInfo(getIndexInfo()); return cln; } void MAlignmentObject::insertGap(int seqNum, int pos, int nGaps) { SAFE_POINT(!isStateLocked(), "Alignment state is locked!", ); MAlignment maBefore = msa; int length = msa.getLength(); for(int i = 0; i < seqNum; i++) { msa.insertChars(i, length, MAlignment_GapChar, nGaps); } msa.insertChars(seqNum, pos, MAlignment_GapChar, nGaps); for(int i = seqNum + 1; i < msa.getNumRows(); i++) { msa.insertChars(i, length, MAlignment_GapChar, nGaps); } msa.trim(); setModified(true); MAlignmentModInfo mi; mi.sequenceListChanged = false; emit si_alignmentChanged(maBefore, mi); } void MAlignmentObject::insertGap(int pos, int nGaps) { SAFE_POINT(!isStateLocked(), "Alignment state is locked!", ); SAFE_POINT(nGaps > 0, "Invalid number of gaps!",); MAlignment maBefore = msa; QByteArray gap(nGaps, MAlignment_GapChar); for (int i=0, n = msa.getNumRows(); i < n; i++) { msa.insertChars(i, pos, MAlignment_GapChar, nGaps); } setModified(true); MAlignmentModInfo mi; mi.sequenceListChanged = false; emit si_alignmentChanged(maBefore, mi); } void MAlignmentObject::insertGap( U2Region seqences, int pos, int nGaps ) { SAFE_POINT(!isStateLocked(), "Alignment state is locked!", ); MAlignment maBefore = msa; int length = msa.getLength(); int startSeq = seqences.startPos; int endSeq = startSeq + seqences.length; for(int i = 0; i < startSeq; i++) { msa.insertChars(i, length, MAlignment_GapChar, nGaps); } for (int i = startSeq; i < endSeq; ++i ) { msa.insertChars( i, pos, MAlignment_GapChar, nGaps); } for(int i = endSeq; i < msa.getNumRows(); i++) { msa.insertChars(i, length, MAlignment_GapChar, nGaps); } msa.trim(); setModified(true); MAlignmentModInfo mi; mi.sequenceListChanged = false; emit si_alignmentChanged(maBefore, mi); } int MAlignmentObject::deleteGap(int seqNum, int pos, int maxGaps) { SAFE_POINT(!isStateLocked(), "Alignment state is locked!", 0); MAlignment maBefore = msa; int n = 0, max = qBound(0, maxGaps, msa.getLength() - pos); while (n < max) { char c = msa.charAt(seqNum, pos + n); if (c != MAlignment_GapChar) { //not a gap break; } n++; } if (n == 0) { return 0; } msa.removeChars(seqNum, pos, n); setModified(true); MAlignmentModInfo mi; mi.sequenceListChanged = false; emit si_alignmentChanged(maBefore, mi); return n; } int MAlignmentObject::deleteGap(int pos, int maxGaps) { SAFE_POINT(!isStateLocked(), "Alignment state is locked!", 0); MAlignment maBefore = msa; //find min gaps in all sequences starting from pos int minGaps = maxGaps; int max = qBound(0, maxGaps, msa.getLength() - pos); foreach(const MAlignmentRow& row, msa.getRows()) { int nGaps = 0; for (int i = pos; i < pos + max; i++, nGaps++) { if (row.chatAt(i) != MAlignment_GapChar) { break; } } minGaps = qMin(minGaps, nGaps); if (minGaps == 0) { break; } } if (minGaps == 0) { return 0; } int nDeleted = minGaps; for (int i = 0, n = msa.getNumRows(); i < n; i++) { msa.removeChars(i, pos, nDeleted); } msa.setLength(msa.getLength() - nDeleted); setModified(true); MAlignmentModInfo mi; mi.sequenceListChanged = false; emit si_alignmentChanged(maBefore, mi); return nDeleted; } void MAlignmentObject::addRow(const DNASequence& seq, int seqIdx) { SAFE_POINT(!isStateLocked(), "Alignment state is locked!", ); MAlignment maBefore = msa; DNAAlphabet* newAlphabet = DNAAlphabet::deriveCommonAlphabet(seq.alphabet, getAlphabet()); assert(newAlphabet != NULL); msa.setAlphabet(newAlphabet); MAlignmentRow row(seq.getName(), seq.seq, 0); msa.addRow(row, seqIdx); setModified(true); MAlignmentModInfo mi; emit si_alignmentChanged(maBefore, mi); } void MAlignmentObject::removeRow(int seqNum) { SAFE_POINT(!isStateLocked(), "Alignment state is locked!", ); MAlignment maBefore = msa; msa.removeRow(seqNum); setModified(true); MAlignmentModInfo mi; mi.sequenceContentChanged = false; emit si_alignmentChanged(maBefore, mi); } void MAlignmentObject::setMAlignment(const MAlignment& newMa) { SAFE_POINT(!isStateLocked(), "Alignment state is locked!", ); MAlignment maBefore = msa; msa = newMa; msa.setName( getGObjectName() ); setModified(true); MAlignmentModInfo mi; emit si_alignmentChanged(maBefore, mi); } void MAlignmentObject::setGObjectName(const QString& newName) { msa.setName( newName ); GObject::setGObjectName(newName); } void MAlignmentObject::removeRegion(int startPos, int startRow, int nBases, int nRows, bool removeEmptyRows, bool changeAlignment) { SAFE_POINT(!isStateLocked(), "Alignment state is locked!", ); MAlignment maBefore = msa; msa.removeRegion(startPos, startRow, nBases, nRows, removeEmptyRows); setModified(true); MAlignmentModInfo mi; if(changeAlignment) { emit si_alignmentChanged(maBefore, mi); } } void MAlignmentObject::renameRow( int seqNum, const QString& newName ) { SAFE_POINT(!isStateLocked(), "Alignment state is locked!", ); SAFE_POINT(seqNum >= 0 && seqNum < msa.getNumRows(), QString("Invalid sequence number: %1").arg(seqNum), ); SAFE_POINT(!newName.isEmpty(), "New sequence name is empty!",); const QString& curName = msa.getRow(seqNum).getName(); if (curName == newName) { return; } MAlignment maBefore = msa; msa.renameRow(seqNum, newName); setModified(true); MAlignmentModInfo mi; emit si_alignmentChanged(maBefore, mi); } void MAlignmentObject::crop( U2Region window, const QSet& rowNames ) { SAFE_POINT(!isStateLocked(), "Alignment state is locked!", ); MAlignment maBefore = msa; msa.crop(window, rowNames); setModified(true); MAlignmentModInfo mi; emit si_alignmentChanged(maBefore, mi); } void MAlignmentObject::deleteGapsByAbsoluteVal(int val) { int length = msa.getLength(); MAlignment maBefore = msa; for(int i = 0; i < length; i++) { //columns int gapCount = 0; for(int j = 0; j < msa.getNumRows(); j++) { //sequences if(charAt(j,i) == '-') { gapCount++; } } if(gapCount >= val) { removeRegion(i, 0, 1, msa.getNumRows(), true, false); length--; i--; } } if (msa.isEmpty()) { msa = maBefore; return; } MAlignmentModInfo mi; emit si_alignmentChanged(maBefore, mi); } void MAlignmentObject::deleteAllGapColumn() { int length = msa.getLength(); MAlignment maBefore = msa; for(int i = 0; i < length; i++) { //columns int gapCount = 0; for(int j = 0; j < msa.getNumRows(); j++) { //sequences if(charAt(j,i) == '-') { gapCount++; } } if(gapCount == msa.getNumRows()) { removeRegion(i, 0, 1, msa.getNumRows(), true, false); length--; i--; } } MAlignmentModInfo mi; emit si_alignmentChanged(maBefore, mi); } void MAlignmentObject::moveRowsBlock( int firstRow, int numRows, int shift ) { SAFE_POINT(!isStateLocked(), "Alignment state is locked!", ); MAlignment maBefore = msa; msa.moveRowsBlock(firstRow, numRows, shift); setModified(true); MAlignmentModInfo mi; emit si_alignmentChanged(maBefore, mi); } static bool _registerMeta() { qRegisterMetaType("MAlignmentModInfo"); return true; } bool MAlignmentModInfo::registerMeta = _registerMeta(); }//namespace ugene-1.9.8/src/corelibs/U2Core/src/gobjects/AssemblyObject.cpp0000644000175000017500000000204711651544331023011 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "AssemblyObject.h" namespace U2 { GObject* AssemblyObject::clone() const { AssemblyObject* cln = new AssemblyObject(dbiRef, getGObjectName(), getGHintsMap()); return cln; } }//namespace ugene-1.9.8/src/corelibs/U2Core/src/gobjects/UnloadedObject.cpp0000644000175000017500000000410311651544331022760 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "UnloadedObject.h" #include #include namespace U2 { UnloadedObject::UnloadedObject(const QString& objectName, const GObjectType& lot, const QVariantMap& hintsMap) : GObject(GObjectTypes::UNLOADED, objectName, hintsMap) { setLoadedObjectType(lot); } UnloadedObject::UnloadedObject(const UnloadedObjectInfo& info) : GObject(GObjectTypes::UNLOADED, info.name, info.hints) { setLoadedObjectType(info.type); } GObject* UnloadedObject::clone() const { UnloadedObject* cln = new UnloadedObject(getGObjectName(), getLoadedObjectType(), getGHintsMap()); cln->setIndexInfo(getIndexInfo()); return cln; } void UnloadedObject::setLoadedObjectType(const GObjectType& lot) { SAFE_POINT(lot!=GObjectTypes::UNLOADED, "Unloaded object can't be a reference to another unloaded object!",); loadedObjectType = lot; } UnloadedObjectInfo::UnloadedObjectInfo(GObject* obj) { if (obj == NULL) { return; } name = obj->getGObjectName(); hints = obj->getGHintsMap(); if (obj->isUnloaded()) { UnloadedObject* uo = qobject_cast(obj); type = uo->getLoadedObjectType(); } else { type = obj->getGObjectType(); } } }//namespace ugene-1.9.8/src/corelibs/U2Core/src/gobjects/UnloadedObject.h0000644000175000017500000000334711651544331022436 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_UNLOADED_OBJECT_H_ #define _U2_UNLOADED_OBJECT_H_ #include #include "GObjectTypes.h" namespace U2 { class U2CORE_EXPORT UnloadedObjectInfo { public: UnloadedObjectInfo(GObject* obj = NULL); QString name; GObjectType type; QVariantMap hints; bool isValid() const {return !name.isEmpty() && !type.isEmpty() && type != GObjectTypes::UNLOADED;} }; class U2CORE_EXPORT UnloadedObject: public GObject { Q_OBJECT public: UnloadedObject(const QString& objectName, const GObjectType& loadedObjectType, const QVariantMap& hintsMap = QVariantMap()); UnloadedObject(const UnloadedObjectInfo& info); virtual GObject* clone() const; GObjectType getLoadedObjectType() const {return loadedObjectType;} void setLoadedObjectType(const GObjectType& lot); protected: GObjectType loadedObjectType; }; }//namespace #endif ugene-1.9.8/src/corelibs/U2Core/src/gobjects/BioStruct3DObject.cpp0000644000175000017500000000255611651544331023344 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "BioStruct3DObject.h" #include "U2Core/DNASequence.h" #include "GObjectTypes.h" namespace U2 { BioStruct3DObject::BioStruct3DObject(const BioStruct3D& struct3D, const QString& objectName, const QVariantMap& hintsMap) : GObject(GObjectTypes::BIOSTRUCTURE_3D, objectName, hintsMap), bioStruct3D(struct3D) { } GObject* BioStruct3DObject::clone() const { BioStruct3DObject* cln = new BioStruct3DObject(bioStruct3D,getGObjectName(), getGHintsMap()); cln->setIndexInfo(getIndexInfo()); return cln; } } //namespace ugene-1.9.8/src/corelibs/U2Core/src/gobjects/DNASequenceObject.h0000644000175000017500000000566711651544331023005 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_DNA_SEQUENCE_OBJECT_H_ #define _U2_DNA_SEQUENCE_OBJECT_H_ #include #include #include #include #include namespace U2 { class U2SequenceDbi; class U2CORE_EXPORT DNASequenceObject: public GObject { Q_OBJECT public: DNASequenceObject(const QString& name, const DNASequence& seq, const QVariantMap& hintsMap = QVariantMap()); ~DNASequenceObject(); const U2Region& getSequenceRange() const {return seqRange;} const QByteArray& getSequence() const {return dnaSeq.seq;} DNAAlphabet* getAlphabet() const {return dnaSeq.alphabet;} const DNAQuality& getQuality() const { return dnaSeq.quality; } const DNASequence& getDNASequence() const {return dnaSeq;} int getSequenceLen() const {return dnaSeq.length();} const QString getSequenceName() const {return dnaSeq.getName(); } virtual GObject* clone() const; void setBase(int pos, char base); virtual bool checkConstraints(const GObjectConstraints* c) const; void setSequence(DNASequence seq); void setQuality(const DNAQuality& quality); bool isCircular() const {return dnaSeq.circular;} void setCircular(bool val); U2SequenceDbi* asDbi() const {return dbi;} signals: void si_sequenceChanged(); protected: DNASequence dnaSeq; U2Region seqRange; U2SequenceDbi* dbi; }; class U2CORE_EXPORT DNASequenceObjectConstraints : public GObjectConstraints { Q_OBJECT public: DNASequenceObjectConstraints(QObject* p = NULL); int exactSequenceSize; DNAAlphabetType alphabetType; }; class U2CORE_EXPORT DNASequenceObjectSequenceDbiWrapper: public QObject, public U2SimpleSequenceDbi { public: DNASequenceObjectSequenceDbiWrapper(const QList & _seqObjs, U2Dbi * root); U2Sequence getSequenceObject(const U2DataId& sequenceId, U2OpStatus& os); QByteArray getSequenceData(const U2DataId& sequenceId, const U2Region& region, U2OpStatus& os); private: QList seqObjs; }; }//namespace #endif ugene-1.9.8/src/corelibs/U2Core/src/gobjects/PhyTreeObject.h0000644000175000017500000000344211651544331022257 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_PHYTREE_OBJECT_H_ #define _U2_PHYTREE_OBJECT_H_ #include "GObjectTypes.h" #include #include namespace U2 { class U2CORE_EXPORT PhyTreeObject : public GObject { Q_OBJECT public: PhyTreeObject(const PhyTree& _tree, const QString& objectName, const QVariantMap& hintsMap = QVariantMap()) : GObject(GObjectTypes::PHYLOGENETIC_TREE, objectName, hintsMap), tree(_tree){}; virtual const PhyTree& getTree() const {return tree;} // Warning! // PhyBranches can be accessed and modified! // TODO: move branches to private data, add getters and setters const PhyNode* findPhyNodeByName(const QString& name); virtual GObject* clone() const; // Utility functions // Compares number of nodes and nodes with names (how many nodes etc.) static bool treesAreAlike(const PhyTree& tree1, const PhyTree& tree2); protected: PhyTree tree; }; }//namespace #endif ugene-1.9.8/src/corelibs/U2Core/src/gobjects/GObjectTypes.cpp0000644000175000017500000001071511651544331022446 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "GObjectTypes.h" #include /* TRANSLATOR U2::GObject */ namespace U2 { GObjectTypeInfo::GObjectTypeInfo(const GObjectType& _type, const QString& _name, const QString& _pluralName, const QString& _treeSign, const QString _iconURL) : type(_type), name(_name), pluralName(_pluralName), treeSign(_treeSign), iconURL(_iconURL) { } #define REGISTER_TYPE_EX(VAR, ID, NAME, P_NAME, SIGN, ICON_URI) \ const GObjectType GObjectTypes::VAR = registerTypeInfo(GObjectTypeInfo(ID, NAME, P_NAME, SIGN, ICON_URI)) #define REGISTER_TYPE(VAR, ID, NAME, P_NAME, SIGN) \ REGISTER_TYPE_EX(VAR, ID, NAME, P_NAME, SIGN, "") /// variable id visual name plural name sign icon REGISTER_TYPE(UNKNOWN, "OT_UNKNOWN", GObject::tr("Unknown"), GObject::tr("Unknown"), "?"); REGISTER_TYPE(UNLOADED, "OT_UNLOADED", GObject::tr("Unloaded"), GObject::tr("Unloaded"), "u"); REGISTER_TYPE_EX(TEXT, "OT_TEXT", GObject::tr("Text"), GObject::tr("Text"), "t", ":core/images/texto.png"); REGISTER_TYPE_EX(SEQUENCE, "OT_SEQUENCE", GObject::tr("Sequence"), GObject::tr("Sequences"), "s", ":core/images/dna.png"); REGISTER_TYPE(ANNOTATION_TABLE, "OT_ANNOTATIONS", GObject::tr("Annotation"), GObject::tr("Annotations"), "a"); REGISTER_TYPE(CHROMATOGRAM, "OT_CHROMATOGRAM", GObject::tr("Chromatogram"), GObject::tr("Chromatograms"), "c"); REGISTER_TYPE_EX(MULTIPLE_ALIGNMENT, "OT_MSA", GObject::tr("Alignment"), GObject::tr("Alignments"), "m", ":core/images/msa.png"); REGISTER_TYPE_EX(PHYLOGENETIC_TREE, "OT_PTREE", GObject::tr("Tree"), GObject::tr("Trees"), "tr", ":core/images/tree.png"); REGISTER_TYPE_EX(BIOSTRUCTURE_3D, "OT_BIOSTRUCT3D", GObject::tr("3D model"), GObject::tr("3D models"), "3d", ":core/images/biostruct3d.png"); REGISTER_TYPE_EX(UINDEX, "OT_INDEX", GObject::tr("Index"), GObject::tr("Indexes"), "i", ":core/images/table.png"); REGISTER_TYPE(ASSEMBLY, "OT_ASSEMBLY", GObject::tr("Assembly"), GObject::tr("Assemblies"), "as"); static QHash& getTypeMap() { static QHash map; return map; } const GObjectTypeInfo& GObjectTypes::getTypeInfo(const QString& t) { QHash& m = getTypeMap(); if (m.contains(t)) { GObjectTypeInfo& r = m[t]; return r; } GObjectTypeInfo& r = m[GObjectTypes::UNKNOWN]; return r; } GObjectType GObjectTypes::registerTypeInfo(const GObjectTypeInfo& ti) { QHash& map = getTypeMap(); assert(!map.contains(ti.type)); map[ti.type] = ti; return ti.type; } void GObjectTypes::initTypeTranslations() { QHash& map = getTypeMap(); foreach(GObjectType t, map.keys()) { GObjectTypeInfo& info = map[t]; info.name = GObject::tr(info.name.toLocal8Bit().data()); info.pluralName = GObject::tr(info.pluralName.toLocal8Bit().data()); } } void GObjectTypes::initTypeIcons() { QHash& map = getTypeMap(); foreach(GObjectType t, map.keys()) { GObjectTypeInfo& info = map[t]; if (!info.iconURL.isEmpty()) { info.icon = QIcon(info.iconURL); } else { info.icon = QIcon(":/core/images/gobject.png"); } } } }//namespace ugene-1.9.8/src/corelibs/U2Core/src/gobjects/BioStruct3DObject.h0000644000175000017500000000263611651544331023010 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_BIOSTRUCT3D_OBJECT_H_ #define _U2_BIOSTRUCT3D_OBJECT_H_ #include #include #include namespace U2 { class U2CORE_EXPORT BioStruct3DObject: public GObject { Q_OBJECT public: BioStruct3DObject(const BioStruct3D& bioStruct, const QString& objectName, const QVariantMap& hintsMap = QVariantMap()); const BioStruct3D& getBioStruct3D() const { return bioStruct3D;} virtual GObject* clone() const; protected: BioStruct3D bioStruct3D; }; } //namespace #endif //_U2_BIOSTRUCT3D_OBJECT_H_ ugene-1.9.8/src/corelibs/U2Core/src/gobjects/UIndexObject.h0000644000175000017500000000251111651544331022067 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_UINDEX_OBJECT_H_ #define _U2_UINDEX_OBJECT_H_ #include #include #include "GObjectTypes.h" namespace U2 { class U2CORE_EXPORT UIndexObject : public GObject { Q_OBJECT public: static const QString OBJ_NAME; UIndexObject( const UIndex& a_ind, const QString& name ); UIndex getIndex() const; virtual GObject* clone() const; private: UIndex ind; }; // UIndexObject } // U2 #endif // _U2_UINDEX_OBJECT_H_ ugene-1.9.8/src/corelibs/U2Core/src/gobjects/AnnotationTableObject.cpp0000644000175000017500000006137211651544331024322 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "AnnotationTableObject.h" #include "GObjectTypes.h" #include "DNASequenceObject.h" #include #include #include #include #include // for Qt::escape #include #include namespace U2 { Annotation::Annotation(SharedAnnotationData _d): obj(NULL), d(_d) { } Annotation::~Annotation() { //todo: add state checks? } bool Annotation::isValidQualifierName(const QString& s) { return !s.isEmpty() && s.length() < 20 && TextUtils::fits(TextUtils::QUALIFIER_NAME_CHARS, s.toAscii().data(), s.length()); } bool Annotation::isValidQualifierValue(const QString& s) { Q_UNUSED(s); //todo: check whitespaces! return true; } bool Annotation::isValidAnnotationName(const QString& n) { //todo: optimize if (n.isEmpty() || n.length() > 100) { return false; } QBitArray validChars = TextUtils::ALPHA_NUMS; validChars['_'] = true; validChars['-'] = true; validChars[' '] = true; validChars['\''] = true; QByteArray name = n.toLocal8Bit(); if (!TextUtils::fits(validChars, name.constData(), name.size())) { return false; } if (name[0] == ' ' || name[name.size() - 1] == ' ') { return false; } return TextUtils::fits(TextUtils::ANNOTATIONS_NAME_CHARS, n.toAscii().data(), n.length()); } QString Annotation::getQualifiersTip(int maxRows, DNASequenceObject* seq, DNATranslation* comlTT, DNATranslation* aminoTT) const { QString tip; int rows = 0; const int QUALIFIER_VALUE_CUT = 40; if (d->qualifiers.size() != 0) { tip += ""; bool first = true; foreach (const U2Qualifier& q, d->qualifiers) { if (++rows > maxRows) { break; } QString val = q.value; if(val.length() > QUALIFIER_VALUE_CUT) { val = val.left(QUALIFIER_VALUE_CUT) + " ..."; } if (first) { first = false; } else { tip += "
    "; } tip += "" + Qt::escape(q.name) + " = " + Qt::escape(val); } tip += "
    "; } if (seq && rows <= maxRows && (getStrand().isCompementary() || comlTT != NULL)) { QVector loc = getRegions(); if (getStrand().isCompementary()) { qStableSort(loc.begin(), loc.end(), qGreater()); } QString seqVal; QString aminoVal; bool complete = true; for (int i = 0; i < loc.size(); i++) { if (!seqVal.isEmpty()) { seqVal += "^"; } if (!aminoVal.isEmpty()) { aminoVal += "^"; } const U2Region& r = loc.at(i); int len = qMin(int(r.length), QUALIFIER_VALUE_CUT - seqVal.length()); if (len != r.length) { complete = false; } if (getStrand().isCompementary()) { const char* str = seq->getSequence().constData() + r.endPos() - len; QByteArray ba(str, len); comlTT->translate(ba.data(), len); TextUtils::reverse(ba.data(), len); seqVal += QString::fromLocal8Bit(ba.data(), len); if (aminoTT!=NULL) { int aminoLen = aminoTT->translate(ba.data(), len); aminoVal += QString::fromLocal8Bit(ba.data(), aminoLen); } } else { const char* str = seq->getSequence().constData() + r.startPos; seqVal += QString::fromLocal8Bit(str, len); if (aminoTT!=NULL) { QByteArray ba(str, len); int aminoLen = aminoTT->translate(ba.data(), len); aminoVal += QString::fromLocal8Bit(ba.data(), aminoLen); } } if (seqVal.length() >= QUALIFIER_VALUE_CUT) { complete &= (i == loc.size() - 1); break; } } if(!complete || seqVal.length() > QUALIFIER_VALUE_CUT) { seqVal = seqVal.left(QUALIFIER_VALUE_CUT) + " ..."; } if(!complete || aminoVal.length() > QUALIFIER_VALUE_CUT) { aminoVal = aminoVal.left(QUALIFIER_VALUE_CUT) + " ..."; } if (!tip.isEmpty()) { tip+="
    "; } assert(seqVal.length() > 0); tip += "" + U2::AnnotationTableObject::tr("Sequence") + " = " + Qt::escape(seqVal) + ""; rows++; if (rows <= maxRows && aminoTT!=NULL) { tip+="
    "; tip += "" + U2::AnnotationTableObject::tr("Translation") + " = " + Qt::escape(aminoVal) + ""; } } return tip; } bool Annotation::annotationLessThan(Annotation *first, Annotation *second) { QListIterator firstIterator(first->getGroups()); QListIterator secondIterator(second->getGroups()); while(firstIterator.hasNext() && secondIterator.hasNext()) { if (firstIterator.peekNext()->getGroupName() < secondIterator.peekNext()->getGroupName()) { return true; } if (firstIterator.peekNext()->getGroupName() > secondIterator.peekNext()->getGroupName()) { return false; } firstIterator.next(); secondIterator.next(); } if (secondIterator.hasNext()) { if(first->getAnnotationName() < secondIterator.peekNext()->getGroupName()) { return true; } if(first->getAnnotationName() > secondIterator.peekNext()->getGroupName()) { return false; } secondIterator.next(); } if (firstIterator.hasNext()) { if(firstIterator.peekNext()->getGroupName() < second->getAnnotationName()) { return true; } if(firstIterator.peekNext()->getGroupName() > second->getAnnotationName()) { return false; } firstIterator.next(); } if (secondIterator.hasNext()) { return true; } if (firstIterator.hasNext()) { return false; } return (first->getAnnotationName() < second->getAnnotationName()); } const QVector& Annotation::getQualifiers() const { return d->qualifiers; } void Annotation::setAnnotationName(const QString& newName) { if (newName == d->name) { return; } SAFE_POINT(!newName.isEmpty(), "Annotation name is empty!",); QString oldName = d->name; d->name = newName; if (obj!=NULL) { obj->setModified(true); AnnotationModification md(AnnotationModification_NameChanged, this); obj->emit_onAnnotationModified(md); } } void Annotation::setLocationOperator(U2LocationOperator op) { if (op == getLocationOperator()) { return; } d->setLocationOperator(op); if (obj!=NULL) { obj->setModified(true); AnnotationModification md(AnnotationModification_LocationChanged, this); obj->emit_onAnnotationModified(md); } } void Annotation::setStrand(U2Strand s) { if (s == getStrand()) { return; } d->setStrand(s); if (obj!=NULL) { obj->setModified(true); AnnotationModification md(AnnotationModification_LocationChanged, this); obj->emit_onAnnotationModified(md); } } void Annotation::addLocationRegion(const U2Region& reg) { d->location->regions.append(reg); if (obj!=NULL) { obj->setModified(true); AnnotationModification md(AnnotationModification_LocationChanged, this); obj->emit_onAnnotationModified(md); } } void Annotation::addQualifier(const U2Qualifier& q) { d->qualifiers.append(q); if (obj!=NULL) { obj->setModified(true); QualifierModification md(AnnotationModification_QualifierAdded, this, q); obj->emit_onAnnotationModified(md); } } void Annotation::removeQualifier(const U2Qualifier& q) { assert(d->qualifiers.contains(q)); int idx = d->qualifiers.indexOf(q); d->qualifiers.remove(idx); if (obj!=NULL) { obj->setModified(true); QualifierModification md(AnnotationModification_QualifierRemoved, this, q); obj->emit_onAnnotationModified(md); } } void Annotation::setLocation(const U2Location& location ) { d->location = location; if (obj!=NULL) { AnnotationModification md(AnnotationModification_LocationChanged, this); obj->emit_onAnnotationModified(md); } } void Annotation::replaceRegions(const QVector& regions) { if (d->location->regions == regions) { return; } d->location->regions = regions; if (obj!=NULL) { AnnotationModification md(AnnotationModification_LocationChanged, this); obj->emit_onAnnotationModified(md); } } ////////////////////////////////////////////////////////////////////////// // Group AnnotationGroup::AnnotationGroup(AnnotationTableObject* p, const QString& _name, AnnotationGroup* parentGrp) : name(_name), obj(p), parentGroup(parentGrp) { assert(!name.isEmpty() && (!name.contains('/') || name == AnnotationGroup::ROOT_GROUP_NAME)); } AnnotationGroup::~AnnotationGroup() { //annotations are not removed here -> contract with ~AnnotationTableObject foreach(AnnotationGroup* g, subgroups) { delete g; } } void AnnotationGroup::findAllAnnotationsInGroupSubTree(QSet& set) const { set+=QSet::fromList(annotations); foreach(AnnotationGroup* g, subgroups) { g->findAllAnnotationsInGroupSubTree(set); } } void AnnotationGroup::addAnnotation(Annotation* a) { if (a->getGObject() == NULL) { //adding annotation to the object by adding it to the group. //usually this method is called for annotation with groupName!=annotationName obj->addAnnotation(a, getGroupPath()); return; } SAFE_POINT(a->getGObject() == obj, "Illegal object!",); assert(/*!annotations.contains(a) && */! a->groups.contains(this)); obj->setModified(true); annotations.append(a); a->groups.append(this); if (obj!=NULL && a->groups.size() > 1) { obj->setModified(true); AnnotationGroupModification md(AnnotationModification_AddedToGroup, a, this); obj->emit_onAnnotationModified(md); } } void AnnotationGroup::removeAnnotations(const QList& ans) { QList toRemoveFromObj; foreach(Annotation* a, ans) { assert(annotations.contains(a) && a->groups.contains(this)); if (a->groups.size() == 1) { toRemoveFromObj.append(a); } else { annotations.removeOne(a); a->groups.removeOne(this); if (obj!=NULL) { obj->setModified(true); AnnotationGroupModification md(AnnotationModification_RemovedFromGroup, a, this); obj->emit_onAnnotationModified(md); } } } if (!toRemoveFromObj.isEmpty()) { obj->removeAnnotations(toRemoveFromObj); } } void AnnotationGroup::removeAnnotation(Annotation* a) { assert(annotations.contains(a) && a->groups.contains(this)); if (a->groups.size() == 1) { SAFE_POINT(a->groups.first() == this, "Illegal group!",); obj->removeAnnotation(a); } else { annotations.removeOne(a); a->groups.removeOne(this); if (obj!=NULL) { obj->setModified(true); AnnotationGroupModification md(AnnotationModification_RemovedFromGroup, a, this); obj->emit_onAnnotationModified(md); } } } bool AnnotationGroup::isValidGroupName(const QString& n, bool pathMode) { if (n.isEmpty()) { return false; } //todo: optimize QBitArray validChars = TextUtils::ALPHA_NUMS; validChars['_'] = true; validChars['-'] = true; validChars[' '] = true; validChars['\''] = true; if (pathMode) { validChars['/'] = true; } QByteArray groupName = n.toLocal8Bit(); if (!TextUtils::fits(validChars, groupName.constData(), groupName.size())) { return false; } if (groupName[0] == ' ' || groupName[groupName.size()-1] == ' ') { return false; } return true; } AnnotationGroup* AnnotationGroup::getSubgroup(const QString& path, bool create) { if (path.isEmpty()) { return this; } int idx = path.indexOf('/'); QString name = idx < 0 ? path : (idx == 0 ? path.mid(idx+1) : path.left(idx)); AnnotationGroup* group = NULL; foreach (AnnotationGroup *g, subgroups) { if (g->getGroupName() == name) { group = g; break; } } if (group == NULL && create) { group = new AnnotationGroup(obj, name, this); subgroups.push_back(group); obj->emit_onGroupCreated(group); } if (idx <= 0 || group == NULL) { return group; } AnnotationGroup* result = group->getSubgroup(path.mid(idx+1), create); return result; } void AnnotationGroup::removeSubgroup(AnnotationGroup* g) { SAFE_POINT(g->getParentGroup() == this, "Illegal parent group!",); obj->setModified(true); g->clear(); subgroups.removeOne(g); obj->emit_onGroupRemoved(this, g); delete g; } void AnnotationGroup::clear() { while (!subgroups.isEmpty()) { removeSubgroup(subgroups.first()); } if (!annotations.isEmpty()) { removeAnnotations(annotations); } } bool AnnotationGroup::isParentOf(AnnotationGroup* g) const { if (g->getGObject() != obj || g == this) { return false; } for (AnnotationGroup* pg = g->getParentGroup(); pg!=NULL; pg = pg->getParentGroup()) { if ( pg == this) { return true; } } return false; } void AnnotationGroup::setGroupName(const QString& newName) { if (name == newName) { return; } QString oldName = name; name = newName; obj->setModified(true); obj->emit_onGroupRenamed(this, oldName); } QString AnnotationGroup::getGroupPath() const { if (parentGroup == NULL) { return QString(""); } if (parentGroup->parentGroup == NULL) { return name; } return parentGroup->getGroupPath() + "/" + name; } void AnnotationGroup::getSubgroupPaths(QStringList& res) const { if (!isRootGroup()) { res.append(getGroupPath()); } foreach(const AnnotationGroup* g, subgroups) { g->getSubgroupPaths(res); } } QDataStream& operator>>(QDataStream& dataStream, AnnotationGroup* parentGroup) { QString name; dataStream >> name; AnnotationGroup *group = parentGroup->getSubgroup(name, true); int s; dataStream >> s; for (int i = 0; i < s; ++i) { AnnotationData *adata = new AnnotationData; dataStream >> *adata; Annotation *a = new Annotation(QSharedDataPointer(adata)); group->addAnnotation(a); } dataStream >> s; for (int i = 0; i < s; ++i) dataStream >> group; return dataStream; } QDataStream& operator<<(QDataStream& dataStream, const AnnotationGroup& group) { dataStream << group.name; int s = group.annotations.size(); dataStream << s; for (int i = 0; i < s; ++i) dataStream << *group.annotations[i]->data(); s = group.subgroups.size(); dataStream << s; for (int i = 0; i < s; ++i) dataStream << *group.subgroups[i]; return dataStream; } ////////////////////////////////////////////////////////////////////////// /// Annotation table object const QString AnnotationGroup::ROOT_GROUP_NAME("/"); AnnotationTableObject::AnnotationTableObject(const QString& objectName, const QVariantMap& hintsMap) : GObject(GObjectTypes::ANNOTATION_TABLE, objectName, hintsMap) { rootGroup = new AnnotationGroup(this, AnnotationGroup::ROOT_GROUP_NAME, NULL); } AnnotationTableObject::~AnnotationTableObject() { foreach(Annotation* a, annotations) { delete a; } delete rootGroup; } GObject* AnnotationTableObject::clone() const { GTIMER(c2,t2,"AnnotationTableObject::clone"); AnnotationTableObject* cln = new AnnotationTableObject(getGObjectName(), getGHintsMap()); cln->setIndexInfo(getIndexInfo()); QMapremap; remap[rootGroup] = cln->rootGroup = new AnnotationGroup(cln, rootGroup->getGroupName(), NULL); QList lst; lst << rootGroup->getSubgroups(); while(!lst.isEmpty()){ AnnotationGroup* gr = lst.takeFirst(); AnnotationGroup* newParent = remap.value(gr->getParentGroup()); assert(newParent); AnnotationGroup* newGr = new AnnotationGroup(cln, gr->getGroupName(), newParent); newParent->subgroups << newGr; remap[gr] = newGr; lst << gr->getSubgroups(); } foreach(Annotation* a, annotations) { Annotation* newA = new Annotation(a->d); newA->obj = cln; cln->annotations << newA; foreach(AnnotationGroup* gr, a->getGroups()) { AnnotationGroup* newGr = remap.value(gr); assert(newGr); newA->groups << newGr; newGr->annotations << newA; } } cln->setModified(false); return cln; } void AnnotationTableObject::addAnnotation(Annotation* a, const QString& groupName) { SAFE_POINT(a->obj == NULL, "Annotation belongs to another object", ); a->obj = this; const QString& aName = a->getAnnotationName(); AnnotationGroup* defaultGroup = rootGroup->getSubgroup(groupName.isEmpty() ? aName : groupName, true); defaultGroup->addAnnotation(a); annotations.append(a); setModified(true); emit si_onAnnotationsAdded(QList()<obj == NULL, "Annotation belongs to another object", ); if(groupsNames.isEmpty()){ addAnnotation(a); return; } a->obj = this; const QString& aName = a->getAnnotationName(); foreach(QString groupName, groupsNames){ AnnotationGroup* defaultGroup = rootGroup->getSubgroup(groupName.isEmpty() ? aName : groupName, true); defaultGroup->addAnnotation(a); } annotations.append(a); setModified(true); emit si_onAnnotationsAdded(QList()<& list, const QString& groupName) { if (list.isEmpty()) { return; } annotations << list; GTIMER(c1,t1,"AnnotationTableObject::addAnnotations [populate data tree]"); AnnotationGroup* gr = NULL; if (groupName.isEmpty()) { QString prevName; foreach(Annotation* a, list) { assert(a->obj == NULL); a->obj = this; const QString& grName = a->getAnnotationName(); if (grName != prevName) { gr = rootGroup->getSubgroup(grName, true); prevName = grName; } gr->addAnnotation(a); } } else { gr = rootGroup->getSubgroup(groupName, true); foreach(Annotation* a, list) { assert(a->obj == NULL); a->obj = this; gr->addAnnotation(a); } } t1.stop(); setModified(true); GTIMER(c2,t2,"AnnotationTableObject::addAnnotations [notify]"); emit si_onAnnotationsAdded(list); } void AnnotationTableObject::removeAnnotations(const QList& annotations) { foreach(Annotation* a, annotations) { _removeAnnotation(a); } emit si_onAnnotationsRemoved(annotations); setModified(true); qDeleteAll(annotations); } void AnnotationTableObject::removeAnnotationsInGroup(const QList& _annotations, AnnotationGroup *group) { /*annotations = annotations.toSet().subtract(_annotations.toSet()).toList(); foreach(Annotation* a, _annotations) { a->obj = NULL; foreach(AnnotationGroup* ag, a->getGroups()) { ag->annotations.removeOne(a); } }*/ int recv = receivers(SIGNAL(si_onAnnotationsInGroupRemoved(const QList&, AnnotationGroup*))); annLocker.setToDelete(_annotations, group, recv); DeleteAnnotationsFromObjectTask *task = new DeleteAnnotationsFromObjectTask(_annotations, this, group); AppContext::getTaskScheduler()->registerTopLevelTask(task); /*int recv = receivers(SIGNAL(si_onAnnotationsInGroupRemoved(const QList&, AnnotationGroup*))); annLocker.setToDelete(_annotations, group, recv); emit si_onAnnotationsInGroupRemoved(_annotations, group); setModified(true);*/ //qDeleteAll(annotations); } void DeleteAnnotationsFromObjectTask::run() { /*aobj->annotations = aobj->annotations.toSet().subtract(anns.toSet()).toList(); foreach(Annotation* a, anns) { a->obj = NULL; foreach(AnnotationGroup* ag, a->getGroups()) { ag->annotations.removeOne(a); } }*/ foreach(Annotation* a, anns) { aobj->_removeAnnotation(a); } } Task::ReportResult DeleteAnnotationsFromObjectTask::report() { aobj->emit_onAnnotationsInGroupRemoved(anns, group); aobj->setModified(true); return ReportResult_Finished; } void AnnotationTableObject::releaseLocker() { annLocker.releaseLocker(); } bool AnnotationTableObject::isLocked() const { return annLocker.isLocked(); } void AnnotationTableObject::removeAnnotation(Annotation* a) { QList v; v<getGObject() == this, "Illegal annotation object!",); a->obj = NULL; annotations.removeOne(a); foreach(AnnotationGroup* ag, a->getGroups()) { ag->annotations.removeOne(a); } } void AnnotationTableObject::selectAnnotationsByName(const QString& name, QList& res) { foreach(Annotation* a, annotations) { if (a->getAnnotationName() == name) { res.append(a); } } } bool AnnotationTableObject::checkConstraints(const GObjectConstraints* c) const { const AnnotationTableObjectConstraints* ac = qobject_cast(c); SAFE_POINT(ac != NULL, "Illegal constraints type!", false); int fitSize = ac->sequenceSizeToFit; foreach(Annotation* a, annotations) { foreach(const U2Region& r, a->getRegions()) { if (r.endPos() > fitSize) { return false; } } } return true; } void AnnotationTableObject::cleanAnnotations() { assert(!annLocker.isLocked()); annLocker.sl_Clean(); } AnnotationTableObjectConstraints::AnnotationTableObjectConstraints(const AnnotationTableObjectConstraints& c, QObject* p) : GObjectConstraints(GObjectTypes::ANNOTATION_TABLE, p), sequenceSizeToFit(c.sequenceSizeToFit) { } AnnotationTableObjectConstraints::AnnotationTableObjectConstraints(QObject* p) : GObjectConstraints(GObjectTypes::ANNOTATION_TABLE, p), sequenceSizeToFit(0) { } bool annotationLessThanByRegion(const Annotation* a1, const Annotation* a2) { assert(!a1->getLocation()->isEmpty()); assert(!a2->getLocation()->isEmpty()); const U2Region& r1 = a1->getRegions().first(); const U2Region& r2 = a2->getRegions().first(); return r1 < r2; } bool annotationGreaterThanByRegion( const Annotation* a1, const Annotation* a2 ) { return annotationLessThanByRegion(a2, a1); } void AnnotationsLocker::setToDelete( const QList& _anns, AnnotationGroup *_parentGroup, int counter ) { anns = _anns; parentGroup = _parentGroup; deleteCounter = counter; } void AnnotationsLocker::releaseLocker(){ if(deleteCounter) { deleteCounter--; } } bool AnnotationsLocker::isLocked() const{ return deleteCounter != 0; } void AnnotationsLocker::sl_Clean(){ if(deleteCounter == 0) { qDeleteAll(anns); anns.clear(); parentGroup->getParentGroup()->removeSubgroup(parentGroup); } } AnnotationsLocker::AnnotationsLocker(): parentGroup(NULL), deleteCounter(0) { } }//namespace ugene-1.9.8/src/corelibs/U2Core/src/gobjects/PhyTreeObject.cpp0000644000175000017500000000376211651544331022617 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "PhyTreeObject.h" namespace U2 { GObject* PhyTreeObject::clone() const { PhyTreeObject* cln = new PhyTreeObject(tree, getGObjectName(), getGHintsMap()); cln->setIndexInfo(getIndexInfo()); return cln; } bool PhyTreeObject::treesAreAlike( const PhyTree& tree1, const PhyTree& tree2 ) { QList track1 = tree1->collectNodes(); QList track2 = tree2->collectNodes(); if (track1.count() != track2.count()) { return false; } foreach (const PhyNode* n1, track1) { if (n1->name.isEmpty()) { continue; } foreach (const PhyNode* n2, track2) { if (n2->name != n1->name) { continue; } if (n1->branches.count() != n2->branches.count()) { return false; } } } return true; } const PhyNode* PhyTreeObject::findPhyNodeByName( const QString& name ) { QList nodes = tree.constData()->collectNodes(); foreach (const PhyNode* node, nodes) { if (node->name == name) { return node; } } return NULL; } }//namespace ugene-1.9.8/src/corelibs/U2Core/src/gobjects/AnnotationTableObject.h0000644000175000017500000002525711651544331023771 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_ANNOTATION_TABLE_OBJECT_H_ #define _U2_ANNOTATION_TABLE_OBJECT_H_ #include #include #include #include #include namespace U2 { class Annotation; class U2Qualifier; class AnnotationGroup; class AnnotationTableObject; class DNASequenceObject; class DNATranslation; enum AnnotationModificationType { AnnotationModification_NameChanged, AnnotationModification_QualifierAdded, AnnotationModification_QualifierRemoved, AnnotationModification_LocationChanged, AnnotationModification_AddedToGroup, // Emitted when annotation is added to a group. // Note that first time annotation added to the object it automatically // has a group assigned and this signal is not emitted AnnotationModification_RemovedFromGroup }; class U2CORE_EXPORT AnnotationModification { public: AnnotationModification(AnnotationModificationType _type, Annotation* a) : type(_type), annotation(a) {} AnnotationModificationType type; Annotation* annotation; }; class U2CORE_EXPORT QualifierModification : public AnnotationModification { public: QualifierModification(AnnotationModificationType t, Annotation* a, const U2Qualifier& q) : AnnotationModification(t, a), qualifier(q) {} U2Qualifier qualifier; }; class U2CORE_EXPORT AnnotationGroupModification : public AnnotationModification { public: AnnotationGroupModification(AnnotationModificationType t, Annotation* a, AnnotationGroup* g) : AnnotationModification(t, a), group(g) {} AnnotationGroup* group; }; class U2CORE_EXPORT Annotation { friend class AnnotationGroup; friend class AnnotationTableObject; public: Annotation(SharedAnnotationData data); virtual ~Annotation(); static bool isValidAnnotationName(const QString& n); static bool isValidQualifierName(const QString& s); static bool isValidQualifierValue(const QString& s); AnnotationTableObject* getGObject() const { return obj;} const QString& getAnnotationName() const {return d->name;} void setAnnotationName(const QString& name); bool isOrder() const {return d->isOrder();} bool isJoin() const {return d->isJoin();} U2Strand getStrand() const {return d->getStrand();} void setStrand(U2Strand strand); U2LocationOperator getLocationOperator() {return d->getLocationOperator();} void setLocationOperator(U2LocationOperator op); const U2Location& getLocation() const {return d->location;} void setLocation(const U2Location& location ); const QVector& getRegions() const {return d->getRegions();} void replaceRegions(const QVector& regions); void addLocationRegion(const U2Region& reg); const QVector& getQualifiers() const; void addQualifier(const U2Qualifier& q); void addQualifier(const QString& name, const QString& val) {addQualifier(U2Qualifier(name, val));} void removeQualifier(const U2Qualifier& q); void removeQualifier(const QString& name, const QString& val) {removeQualifier(U2Qualifier(name, val));} const QList& getGroups() const {return groups;} void findQualifiers(const QString& name, QVector& res) const {return d->findQualifiers(name, res);} QString findFirstQualifierValue(const QString& name) const {return d->findFirstQualifierValue(name);} SharedAnnotationData data() const {return d;} QString getQualifiersTip(int maxRows, DNASequenceObject* = NULL, DNATranslation* complTT = NULL, DNATranslation* aminoTT = NULL) const; static bool annotationLessThan(Annotation *first, Annotation *second); private: AnnotationTableObject* obj; SharedAnnotationData d; QList groups; }; class U2CORE_EXPORT AnnotationGroup { friend class AnnotationTableObject; public: AnnotationGroup(AnnotationTableObject* p, const QString& _name, AnnotationGroup* parentGrp); ~AnnotationGroup(); static const QString ROOT_GROUP_NAME; static bool isValidGroupName(const QString& n, bool pathMode); void findAllAnnotationsInGroupSubTree(QSet& set) const; const QList& getAnnotations() const {return annotations;} void addAnnotation(Annotation* a); void removeAnnotation(Annotation* a); void removeAnnotations(const QList& annotations); const QList& getSubgroups() const {return subgroups;} void removeSubgroup(AnnotationGroup* g); const QString& getGroupName() const {return name;} QString getGroupPath() const; void setGroupName(const QString& newName); AnnotationTableObject* getGObject() const {return obj;} AnnotationGroup* getParentGroup() const {return parentGroup;} AnnotationGroup* getSubgroup(const QString& path, bool create); void getSubgroupPaths(QStringList& res) const; /// remove all subgroups and annotation refs void clear(); int getGroupDepth() const {return 1 + (parentGroup == NULL ? 0 : parentGroup->getGroupDepth());} bool isParentOf(AnnotationGroup* g) const; bool isRootGroup() const {return parentGroup == NULL;} //true if the parent of the group is root group bool isTopLevelGroup() const {return parentGroup!=NULL && parentGroup->isRootGroup();} private: friend U2CORE_EXPORT QDataStream& operator>>(QDataStream& dataStream, AnnotationGroup* parentGroup); friend U2CORE_EXPORT QDataStream& operator<<(QDataStream& dataStream, const AnnotationGroup& group); QString name; AnnotationTableObject* obj; AnnotationGroup* parentGroup; QList annotations; QList subgroups; }; U2CORE_EXPORT QDataStream& operator>>(QDataStream& dataStream, AnnotationGroup* parentGroup); U2CORE_EXPORT QDataStream& operator<<(QDataStream& dataStream, const AnnotationGroup& group); class AnnotationsLocker: public QObject { Q_OBJECT public: AnnotationsLocker(); void setToDelete(const QList& _anns, AnnotationGroup *_parentGroup, int counter); void releaseLocker(); bool isLocked() const; void sl_Clean(); private: QList anns; AnnotationGroup *parentGroup; int deleteCounter; }; class DeleteAnnotationsFromObjectTask: public Task { public: DeleteAnnotationsFromObjectTask(const QList _anns, AnnotationTableObject *_aobj, AnnotationGroup *_gr): Task(tr("Delete annotations from object task"), TaskFlag_None), anns(_anns), aobj(_aobj), group(_gr){} void run(); Task::ReportResult report(); private: QList anns; AnnotationTableObject *aobj; AnnotationGroup *group; }; class U2CORE_EXPORT AnnotationTableObject: public GObject { Q_OBJECT friend class Annotation; friend class AnnotationGroup; public: AnnotationTableObject(const QString& objectName, const QVariantMap& hintsMap = QVariantMap()); ~AnnotationTableObject(); const QList& getAnnotations() const {return annotations;} AnnotationGroup* getRootGroup() const {return rootGroup;} void addAnnotation(Annotation* a, const QString& groupName = QString()); void addAnnotation(Annotation* a, QStringList& groupsNames); void addAnnotations(const QList& annotations, const QString& groupName = QString()); void removeAnnotation(Annotation* a); void removeAnnotations(const QList& annotations); virtual GObject* clone() const; void selectAnnotationsByName(const QString& name, QList& res); bool checkConstraints(const GObjectConstraints* c) const; void removeAnnotationsInGroup(const QList& _annotations, AnnotationGroup *group); void releaseLocker(); bool isLocked() const; void cleanAnnotations(); protected: void emit_onAnnotationModified(const AnnotationModification& md) {emit si_onAnnotationModified(md);} void emit_onGroupCreated(AnnotationGroup* g) {emit si_onGroupCreated(g);} void emit_onGroupRemoved(AnnotationGroup* p, AnnotationGroup* g) {emit si_onGroupRemoved(p, g);} void emit_onGroupRenamed(AnnotationGroup* g, const QString& oldName) {emit si_onGroupRenamed(g, oldName);} void emit_onAnnotationsInGroupRemoved(const QList& l, AnnotationGroup* gr) {emit si_onAnnotationsInGroupRemoved(l, gr);} void _removeAnnotation(Annotation* a); QList annotations; AnnotationGroup* rootGroup; AnnotationsLocker annLocker; signals: //annotations added to the object and have valid groups assigned void si_onAnnotationsAdded(const QList& a); //annotations removed from the object and will be deleted, but still keeps references to groups and object void si_onAnnotationsRemoved(const QList& a); void si_onAnnotationsInGroupRemoved(const QList&, AnnotationGroup*); void si_onAnnotationModified(const AnnotationModification& md); void si_onGroupCreated(AnnotationGroup*); void si_onGroupRemoved(AnnotationGroup* p, AnnotationGroup* removed); void si_onGroupRenamed(AnnotationGroup*, const QString& oldName); friend class DeleteAnnotationsFromObjectTask; }; class U2CORE_EXPORT AnnotationTableObjectConstraints : public GObjectConstraints { Q_OBJECT public: AnnotationTableObjectConstraints(QObject* p = NULL); AnnotationTableObjectConstraints(const AnnotationTableObjectConstraints& c, QObject* p = NULL); int sequenceSizeToFit; }; bool U2CORE_EXPORT annotationLessThanByRegion(const Annotation* a1, const Annotation* a2); bool U2CORE_EXPORT annotationGreaterThanByRegion(const Annotation* a1, const Annotation* a2); }//namespace #endif ugene-1.9.8/src/corelibs/U2Core/src/gobjects/AssemblyObject.h0000644000175000017500000000261511651544331022457 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_ASSEMBLY_OBJECT_H_ #define _U2_ASSEMBLY_OBJECT_H_ #include #include #include namespace U2 { class U2CORE_EXPORT AssemblyObject : public GObject { Q_OBJECT public: AssemblyObject(const U2DataRef& ref, const QString& objectName, const QVariantMap& hints) : GObject(GObjectTypes::ASSEMBLY, objectName, hints), dbiRef(ref){}; virtual GObject* clone() const; const U2DataRef& getDbiRef() const {return dbiRef;} protected: U2DataRef dbiRef; }; }//namespace #endif ugene-1.9.8/src/corelibs/U2Core/src/gobjects/TextObject.cpp0000644000175000017500000000223511651544331022155 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "TextObject.h" namespace U2 { void TextObject::setText(const QString& newText) { text = newText; setModified(true); } GObject* TextObject::clone() const { TextObject* cln = new TextObject(text, getGObjectName(), getGHintsMap()); cln->setIndexInfo(getIndexInfo()); return cln; } }//namespace ugene-1.9.8/src/corelibs/U2Core/src/gobjects/DNAChromatogramObject.cpp0000644000175000017500000000251011651544331024173 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "DNAChromatogramObject.h" #include "GObjectTypes.h" namespace U2 { DNAChromatogramObject::DNAChromatogramObject(const DNAChromatogram& c, const QString& objectName,const QVariantMap& hints) : GObject(GObjectTypes::CHROMATOGRAM, objectName, hints), chrom(c) { } GObject* DNAChromatogramObject::clone() const { DNAChromatogramObject* cln = new DNAChromatogramObject(chrom, getGObjectName(), getGHintsMap()); cln->setIndexInfo(getIndexInfo()); return cln; } }//namespace ugene-1.9.8/src/corelibs/U2Core/src/gobjects/GObjectRelationRoles.h0000644000175000017500000000215011651544331023563 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_GOBJECT_RELATION_ROLES_H_ #define _U2_GOBJECT_RELATION_ROLES_H_ #include namespace U2 { class U2CORE_EXPORT GObjectRelationRole { public: static const QString SEQUENCE; static const QString ANNOTATION_TABLE; }; }//namespace #endif ugene-1.9.8/src/corelibs/U2Core/src/gobjects/MAlignmentObject.h0000644000175000017500000000547611651544331022743 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_MALIGNMENT_OBJECT_H_ #define _U2_MALIGNMENT_OBJECT_H_ #include #include #include #include "GObjectTypes.h" namespace U2 { class GHints; class DNASequence; class MAlignmentModInfo { public: MAlignmentModInfo() : sequenceContentChanged(true), sequenceListChanged(true) {} bool sequenceContentChanged; bool sequenceListChanged; private: static bool registerMeta; }; class U2CORE_EXPORT MAlignmentObject : public GObject { Q_OBJECT public: explicit MAlignmentObject(const MAlignment& a, const QVariantMap& hintsMap = QVariantMap()) : GObject(GObjectTypes::MULTIPLE_ALIGNMENT, a.getName(), hintsMap), msa(a){}; const MAlignment& getMAlignment() const {return msa;} char charAt(int seqNum, int pos) const {return msa.charAt(seqNum, pos);} virtual GObject* clone() const; void insertGap(int seqNum, int pos, int nGaps); void insertGap(int pos, int nGaps); void insertGap(U2Region seqences, int pos, int nGaps); int deleteGap(int seqNum, int pos, int maxGaps); int deleteGap(int pos, int maxGaps); void addRow(const DNASequence& seq, int seqIdx = -1); void removeRow(int seqNum); void renameRow(int seqNum, const QString& newName); void removeRegion(int startPos, int startRow, int nBases, int nRows, bool removeEmptyRows, bool changeAlignment = true); void crop(U2Region window, const QSet& rowNames); void setMAlignment(const MAlignment& ma); DNAAlphabet* getAlphabet() const { return msa.getAlphabet(); } virtual void setGObjectName(const QString& newName); void moveRowsBlock( int firstRow, int numRows, int delta); int getLength() const {return msa.getLength();} void deleteGapsByAbsoluteVal(int val); void deleteAllGapColumn(); signals: void si_alignmentChanged(const MAlignment& maBefore, const MAlignmentModInfo& modInfo); protected: MAlignment msa; }; }//namespace #endif ugene-1.9.8/src/corelibs/U2Core/src/models/0000755000175000017500000000000011651544332017060 5ustar ilyailyaugene-1.9.8/src/corelibs/U2Core/src/models/DocumentUtils.h0000644000175000017500000000675711651544332022047 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_DOCUMENT_UTILS_H_ #define _U2_DOCUMENT_UTILS_H_ #include #include #include "DocumentModel.h" namespace U2 { class DocumentImporter; /** Result of the format detection. contains score and ( format or importer ) instance pointer */ class U2CORE_EXPORT FormatDetectionResult { public: FormatDetectionResult() : format(NULL), importer(NULL){} DocumentFormat* format; DocumentImporter* importer; QByteArray rawData; GUrl url; QString extension; RawDataCheckResult rawDataCheckResult; QString getFormatDescriptionText() const; QString getFormatOrImporterName() const; int score() const {return rawDataCheckResult.score;} }; class U2CORE_EXPORT FormatDetectionConfig { public: FormatDetectionConfig() : bestMatchesOnly(true), useImporters(false), useExtensionBonus(true){} /** if true format detection algorithm returns list of best matches only */ bool bestMatchesOnly; /** if false format detection algorithm do not test format importers and returns only real formats */ bool useImporters; /** if true file extension is checked and bonus is added if extension is matched for a format*/ bool useExtensionBonus; }; class U2CORE_EXPORT DocumentUtils: public QObject { public: /* returns set with document urls */ static QSet getURLs(const QList& docs); /* The set of urls that should not be used for new documents returns list of loaded urls. Gets them from the active project */ static QSet getNewDocFileNameExcludesHint(); /* Detects document format. The best match goes first in the returned list */ static QList detectFormat(const GUrl& url, const FormatDetectionConfig& conf = FormatDetectionConfig()); /* Detects document format. The best match goes first in the returned list IOAdapter must be opened */ static QList detectFormat(IOAdapter* io, const FormatDetectionConfig& conf = FormatDetectionConfig()); /* Detects document format. The best match goes first in the returned list ext & url can be used here to add extension bonus to the final score */ static QList detectFormat(const QByteArray& rawData, const QString& ext = QString(), const GUrl& url = GUrl(), const FormatDetectionConfig& conf = FormatDetectionConfig()); static QList toFormats(const QList& infos); }; }//namespace #endif ugene-1.9.8/src/corelibs/U2Core/src/models/DocumentImport.cpp0000644000175000017500000000300211651544332022530 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include #include namespace U2 { DocumentImportersRegistry::~DocumentImportersRegistry() { qDeleteAll(importers); importers.clear(); } DocumentImporter* DocumentImportersRegistry::getDocumentImporter(const QString& importerId) const { foreach(DocumentImporter* i, importers) { if (i->getId() == importerId) { return i; } } return NULL; } void DocumentImportersRegistry::addDocumentImporter(DocumentImporter* i) { importers << i; if (i->getImporterDescription().isEmpty()) { coreLog.trace("Warn! Importer has no description: " + i->getImporterName()); } } } //namespace ugene-1.9.8/src/corelibs/U2Core/src/models/ProjectModel.cpp0000644000175000017500000000261611651544332022160 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include #include "ProjectModel.h" namespace U2 { void Project::setupToEngine(QScriptEngine *engine) { Document::setupToEngine(engine); qScriptRegisterMetaType(engine, toScriptValue, fromScriptValue); qScriptRegisterSequenceMetaType >(engine); }; QScriptValue Project::toScriptValue(QScriptEngine *engine, Project* const &in) { return engine->newQObject(in); } void Project::fromScriptValue(const QScriptValue &object, Project* &out) { out = qobject_cast(object.toQObject()); } }//namespace ugene-1.9.8/src/corelibs/U2Core/src/models/GObjectReference.h0000644000175000017500000000622211651544332022367 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_GOBJECT_REFERENCE_H_ #define _U2_GOBJECT_REFERENCE_H_ #include #include namespace U2 { class GObject; class U2CORE_EXPORT GObjectReference { public: GObjectReference(){} GObjectReference(const QString& _docUrl, const QString& _objName, const GObjectType& _type) : docUrl(_docUrl), objName(_objName), objType(_type){} GObjectReference(const GObject* obj, bool deriveLoadedType = true); bool isValid() const {return !docUrl.isEmpty() && !objName.isEmpty() && !objType.isEmpty();} bool operator ==(const GObjectReference& o) const; /** GObject reference keeps only string path of the document url. This must be enough to find document in the project while allows not to keep a complete url data here (for example username/password, etc...) */ QString docUrl; /** The name of the object */ QString objName; /** The type of the object */ GObjectType objType; private: static bool registerMeta; }; inline uint qHash(const GObjectReference& key) { return ::qHash(key.docUrl) + ::qHash(key.objName) + ::qHash(key.objType); } //TODO: add constraints on relation roles class U2CORE_EXPORT GObjectRelation { public: GObjectRelation(){} GObjectRelation(const GObjectReference& _ref, const QString& _role, const QString& _data = QString()) : ref(_ref), role(_role), data(_data){} bool isValid() const {return ref.isValid() && !role.isEmpty();} bool operator ==(const GObjectRelation& o) const; const QString& getDocURL() const {return ref.docUrl;} GObjectReference ref; QString role; QString data; private: static bool registerMeta; }; inline uint qHash(const GObjectRelation& key) { return qHash(key.ref) + ::qHash(key.role) + ::qHash(key.data); } QDataStream &operator<<(QDataStream &out, const GObjectReference &myObj); QDataStream &operator>>(QDataStream &in, GObjectReference &myObj); QDataStream &operator<<(QDataStream &out, const GObjectRelation &myObj); QDataStream &operator>>(QDataStream &in, GObjectRelation &myObj); }//namespace Q_DECLARE_METATYPE( U2::GObjectReference ) Q_DECLARE_METATYPE( U2::GObjectRelation ) Q_DECLARE_METATYPE( QList< U2::GObjectReference > ) Q_DECLARE_METATYPE( QList< U2::GObjectRelation > ) #endif ugene-1.9.8/src/corelibs/U2Core/src/models/StateLockableDataModel.cpp0000644000175000017500000002223111651544332024054 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "StateLockableDataModel.h" #include #include #include namespace U2 { StateLockableItem::StateLockableItem(QObject* p) : QObject(p), itemIsModified(false), mainThreadModificationOnly(false), modificationVersion(0) { QThread* appThread = QCoreApplication::instance()->thread(); QThread* objectThread = thread(); bool mainThread = appThread == objectThread; setMainThreadModificationOnly(mainThread); } StateLockableItem::~StateLockableItem(){ foreach(StateLock* lock, locks) { assert(!lock->getFlags().testFlag(StateLockFlag_LiveLock)); delete lock; } } static void checkThread(const StateLockableItem* i) { #ifdef _DEBUG if (i->isMainThreadModificationOnly()) { QThread* appThread = QCoreApplication::instance()->thread(); QThread* thisThread = QThread::currentThread(); QThread* itemThread = i->thread(); assert(appThread == thisThread); assert(appThread == itemThread); } #else Q_UNUSED(i); #endif } void StateLockableItem::lockState(StateLock* lock) { assert(!locks.contains(lock)); checkThread(this); locks.append(lock); if (locks.size() == 1) { emit si_lockedStateChanged(); } } void StateLockableItem::unlockState(StateLock* lock) { assert(locks.contains(lock)); checkThread(this); locks.removeOne(lock); if (locks.isEmpty()) { emit si_lockedStateChanged(); } } void StateLockableItem::setModified(bool newModifiedState, const QString& modType) { SAFE_POINT(newModifiedState == false || isModificationAllowed(modType), "Item modification not allowed", ); checkThread(this); if (newModifiedState) { modificationVersion++; } if (itemIsModified == newModifiedState) { return; } itemIsModified = newModifiedState; emit si_modifiedStateChanged(); } bool StateLockableItem::isMainThreadObject() const { QThread* at = QCoreApplication::instance()->thread(); QThread* ot = thread(); return at == ot; } ////////////////////////////////////////////////////////////////////////// // Tree StateLockableTreeItem::~StateLockableTreeItem() { // TODO: check that there are no live-locks and delete all child items assert(!hasLocks(StateLockableTreeItemBranch_Item, StateLockFlag_LiveLock)); } bool StateLockableTreeItem::isStateLocked() const { return StateLockableItem::isStateLocked() || (parentStateLockItem != NULL ? parentStateLockItem->isStateLocked() : false); } bool StateLockableTreeItem::isMainThreadModificationOnly() const { return StateLockableItem::isMainThreadModificationOnly() || (parentStateLockItem != NULL && parentStateLockItem->isMainThreadModificationOnly()); } void StateLockableTreeItem::lockState(StateLock* lock) { assert(!locks.contains(lock)); checkThread(this); bool wasUnlocked = !isStateLocked(); locks.append(lock); //notify all children on parent lock state change if (wasUnlocked) { foreach(StateLockableTreeItem* c, childItems) { c->onParentStateLocked(); } } emit si_lockedStateChanged(); } void StateLockableTreeItem::unlockState(StateLock* lock) { assert(locks.contains(lock)); checkThread(this); locks.removeOne(lock); bool becomeUnlocked = !isStateLocked(); emit si_lockedStateChanged(); if (becomeUnlocked) { foreach(StateLockableTreeItem* c, childItems) { c->onParentStateUnlocked(); } } } void StateLockableTreeItem::onParentStateLocked() { //parent has become locked -> check if my state is changed if (!locks.isEmpty()) { return; //nothing changed - was locked too } //notify children assert(isStateLocked()); foreach(StateLockableTreeItem* c, childItems) { c->onParentStateLocked(); } emit si_lockedStateChanged(); } void StateLockableTreeItem::onParentStateUnlocked() { //parent has become unlocked -> check if my state is changed if (!locks.isEmpty()) { return; //nothing changed - was still locked } //notify children assert(!isStateLocked()); emit si_lockedStateChanged(); foreach(StateLockableTreeItem* c, childItems) { c->onParentStateUnlocked(); } } void StateLockableTreeItem::setParentStateLockItem(StateLockableTreeItem* newParent) { SAFE_POINT(parentStateLockItem == NULL || newParent == NULL, "Parent item is already assigned", ); SAFE_POINT(newParent == NULL || newParent->isModificationAllowed(StateLockModType_AddChild), "Add-child modification is not allowed for new parent item!",); SAFE_POINT(parentStateLockItem == NULL || parentStateLockItem->isModificationAllowed(StateLockModType_AddChild), "Add-child modification is not allowed for old parent item!",); StateLockableTreeItem* oldParent = parentStateLockItem; parentStateLockItem = newParent; setParent(newParent); bool treeMod = isTreeItemModified(); if (newParent!=NULL) { setMainThreadModificationOnly(newParent->isMainThreadModificationOnly()); checkThread(this); newParent->childItems.insert(this); newParent->setModified(true, StateLockModType_AddChild); if (treeMod) { newParent->increaseNumModifiedChilds(numModifiedChildren + 1); } } else if (oldParent!=NULL) { oldParent->childItems.remove(this); oldParent->setModified(true, StateLockModType_AddChild); if (treeMod) { oldParent->decreaseNumModifiedChilds(numModifiedChildren + 1); } } } void StateLockableTreeItem::setModified(bool newModifiedState, const QString& modType) { SAFE_POINT(newModifiedState == false || isModificationAllowed(modType), "Item modification not allowed", ); checkThread(this); if (newModifiedState) { modificationVersion++; } if (itemIsModified == newModifiedState) { return; } itemIsModified = newModifiedState; bool parentUpdate = parentStateLockItem && numModifiedChildren == 0; if (itemIsModified && parentUpdate) { // let parent become modified first parentStateLockItem->increaseNumModifiedChilds(1); } emit si_modifiedStateChanged(); if (!itemIsModified && parentUpdate) { // let parent become clean last parentStateLockItem->decreaseNumModifiedChilds(1); } if (!hasModifiedChildren()) { checkThread(this); emit si_modifiedStateChanged(); } } void StateLockableTreeItem::increaseNumModifiedChilds(int n) { assert(n > 0); numModifiedChildren+=n; bool becomeModified = numModifiedChildren == n && !itemIsModified; if (parentStateLockItem) { parentStateLockItem->increaseNumModifiedChilds(n + (becomeModified ? 1 : 0) ); } if (becomeModified) { assert(isTreeItemModified()); checkThread(this); emit si_modifiedStateChanged(); } } void StateLockableTreeItem::decreaseNumModifiedChilds(int n) { assert(n > 0); assert(numModifiedChildren >= n); numModifiedChildren-=n; bool becomeClean = numModifiedChildren == 0 && !itemIsModified; if (parentStateLockItem) { parentStateLockItem->decreaseNumModifiedChilds(n + (becomeClean ? 1 : 0)); } if (becomeClean) { assert(!isTreeItemModified()); checkThread(this); emit si_modifiedStateChanged(); } } QList StateLockableTreeItem::findLocks(StateLockableTreeItemBranchFlags tf, StateLockFlag lf) const { QList res; if (tf.testFlag(StateLockableTreeItemBranch_Item)) { foreach(StateLock* lock, locks) { if (lock->getFlags().testFlag(lf)) { res.append(lock); } } } if (tf.testFlag(StateLockableTreeItemBranch_Parents) && parentStateLockItem!=NULL) { StateLockableTreeItemBranchFlags tflags(StateLockableTreeItemBranch_Parents | StateLockableTreeItemBranch_Item); res+=parentStateLockItem->findLocks(tflags, lf); } if (tf.testFlag(StateLockableTreeItemBranch_Children)) { StateLockableTreeItemBranchFlags tflags(StateLockableTreeItemBranch_Children| StateLockableTreeItemBranch_Item); foreach(const StateLockableTreeItem* child, childItems) { res+=child->findLocks(tflags, lf); } } return res; } }//namespace ugene-1.9.8/src/corelibs/U2Core/src/models/DocumentModel.h0000644000175000017500000003731311651544332021777 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_DOCUMENT_MODEL_H_ #define _U2_DOCUMENT_MODEL_H_ #include #include #include #include "StateLockableDataModel.h" #include #include #include #include namespace U2 { class TaskStateInfo; class Document; class GObject; class DocumentFormat; class IOAdapterFactory; class IOAdapter; class DocumentFormatConstraints; class GHints; /** Document loading mode */ enum DocumentLoadMode { // load all objects from document DocumentLoadMode_Whole, // load single (the first after the current io position) object DocumentLoadMode_SingleObject }; // Additional info about document format enum DocumentFormatFlag { // Document support reading objects from data stream and can detect object boundaries for all object types correctly DocumentFormatFlag_SupportStreaming = 1<<0, // Document support writing DocumentFormatFlag_SupportWriting = 1<<1, // Document can only contain 1 object: like text, raw sequence or some formats that do not support streaming DocumentFormatFlag_SingleObjectFormat = 1<<2, // Document can't be read from packed stream. Used for database files DocumentFormatFlag_NoPack = 1<<3, // Document is not fully loaded to memory. Used for database files DocumentFormatFlag_NoFullMemoryLoad = 1<<4 }; typedef QFlags DocumentFormatFlags; #define DocumentFormatFlags_SW (DocumentFormatFlags(DocumentFormatFlag_SupportStreaming) | DocumentFormatFlag_SupportWriting) #define DocumentFormatFlags_W1 (DocumentFormatFlags(DocumentFormatFlag_SupportWriting) | DocumentFormatFlag_SingleObjectFormat) // Result of the format detection algorithm // Note: High/Very High, Low/Very low selection is the result of the quality of detection algorithm // For example if detection algorithm is not advanced enough it must not use VeryHigh rating enum FormatDetectionScore { FormatDetection_NotMatched = -10, // format is not matched and can't be parsed at all FormatDetection_VeryLowSimilarity = 1, // very low similarity found. Parsing is allowed FormatDetection_LowSimilarity = 2, // save as very low, but slightly better, used as extra step in cross-formats differentiation FormatDetection_AverageSimilarity = 3, //see above FormatDetection_HighSimilarity = 4,//see above FormatDetection_VeryHighSimilarity = 5,//see above FormatDetection_Matched = 10 // here we 100% sure that we deal with a known and supported format. }; /** Set of hints provided by raw data check routines */ /** 'true' if file contain at least one sequence */ #define RawDataCheckResult_Sequence "sequence" /** 'true' if at least one sequence in file has gaps */ #define RawDataCheckResult_SequenceWithGaps "sequence-with-gaps" /** 'true' if multiple sequences were found */ #define RawDataCheckResult_MultipleSequences "multiple-sequences" /** contains estimation of minimal size of a sequence from document*/ #define RawDataCheckResult_MinSequenceSize "sequence-min-size" /** contains estimation of maximum size of a sequence from document */ #define RawDataCheckResult_MaxSequenceSize "sequence-max-size" /** The result of the document format detection: score and additional info that was parsed during raw data check */ class RawDataCheckResult { public: RawDataCheckResult() : score(FormatDetection_NotMatched){}; RawDataCheckResult(FormatDetectionScore _score) : score(_score){} /** Score of the detection */ int score; QVariantMap properties; }; /** Set of hints that can be processed during document loading */ #define DocumentReadingMode_SequenceMergeGapSize "merge-gap" #define DocumentReadingMode_SequenceMergingFinalSizeHint "merge-size" #define DocumentReadingMode_SequenceAsAlignmentHint "sequences-are-msa" #define DocumentReadingMode_SequenceAsShortReadsHint "sequences-are-short-reads" #define DocumentReadingMode_MaxObjectsInDoc "max-objects-in-doc" class U2CORE_EXPORT DocumentFormat: public QObject { Q_OBJECT public: static const QString CREATED_NOT_BY_UGENE; static const QString MERGED_SEQ_LOCK; enum DocObjectOp { DocObjectOp_Add, DocObjectOp_Remove }; DocumentFormat(QObject* p, DocumentFormatFlags _flags, const QStringList& fileExts = QStringList()) : QObject(p), formatFlags(_flags), fileExtensions(fileExts) {} /* returns unique document format id */ virtual DocumentFormatId getFormatId() const = 0; /* returns localized name of the format */ virtual const QString& getFormatName() const = 0; /* returns list of usual file extensions for the format Example: "fa", "fasta", "gb" ... */ virtual QStringList getSupportedDocumentFileExtensions() const {return fileExtensions;} virtual Document* createNewDocument(IOAdapterFactory* io, const GUrl& url, const QVariantMap& hints = QVariantMap()); /* io - opened IOAdapter. * if document format supports streaming reading it must correctly process DocumentLoadMode * otherwise, it will load all file from starting position ( default ) */ virtual Document* loadDocument(IOAdapter* io, TaskStateInfo& ti, const QVariantMap& hints, DocumentLoadMode mode = DocumentLoadMode_Whole) = 0; /** A method for compatibility with old code : creates IO adapter and loads document in DocumentLoadMode_Whole */ virtual Document* loadDocument(IOAdapterFactory* iof, const GUrl& url, TaskStateInfo& ti, const QVariantMap& hints); /** Loads single object in streaming mode. Note! this function is available only if format supports streaming mode */ virtual GObject* loadObject( IOAdapter* io, TaskStateInfo& ti); /** Loads single dna sequence in streaming mode. Note! this function is available only if format supports streaming mode and sequences as an stored data type */ virtual DNASequence* loadSequence( IOAdapter* io, TaskStateInfo& ti); virtual void storeDocument(Document* d, TaskStateInfo& ts, IOAdapterFactory* io = NULL, const GUrl& newDocURL = GUrl()); /* io - opened IOAdapter * so you can store many documents to this file */ virtual void storeDocument( Document* d, TaskStateInfo& ts, IOAdapter* io); /** Checks if object can be added/removed to the document */ virtual bool isObjectOpSupported(const Document* d, DocObjectOp op, GObjectType t) const; /* Returns score rating that indicates that the data supplied is recognized as a valid document format Note: Data can contain only first N (~1024) bytes of the file The URL value is optional and provided as supplementary option. URL value here can be empty in some special cases. */ virtual RawDataCheckResult checkRawData(const QByteArray& dataPrefix, const GUrl& url = GUrl()) const = 0; /** Returns generic format description */ virtual QString getFormatDescription() const {return formatDescription;} /* Checks that document format satisfies given constraints */ virtual bool checkConstraints(const DocumentFormatConstraints& c) const; /* Default implementation does nothing */ virtual void updateFormatSettings(Document* d) const {Q_UNUSED(d);} /* These object types can be produced by reading documents If the format supports write it must support write operation for all the object types it support */ const QSet& getSupportedObjectTypes() const {return supportedObjectTypes;} DocumentFormatFlags getFlags() const {return formatFlags;} bool checkFlags(DocumentFormatFlags flagsToCheck) const { return (formatFlags | flagsToCheck) == formatFlags;} protected: DocumentFormatFlags formatFlags; QStringList fileExtensions; QSet supportedObjectTypes; QString formatDescription; }; class DocumentFormatConstraints { public: DocumentFormatConstraints() : flagsToSupport(0), flagsToExclude(0), checkRawData(false), minDataCheckResult(FormatDetection_VeryLowSimilarity){} void clear() { flagsToSupport = 0; flagsToExclude = 0; checkRawData = false; rawData.clear(); minDataCheckResult = FormatDetection_VeryLowSimilarity; } void addFlagToSupport(DocumentFormatFlag f) {flagsToSupport |= f;} void addFlagToExclude(DocumentFormatFlag f) {flagsToExclude |= f;} // If 'true' the format supports write operation DocumentFormatFlags flagsToSupport; DocumentFormatFlags flagsToExclude; QSet supportedObjectTypes; bool checkRawData; QByteArray rawData; FormatDetectionScore minDataCheckResult; }; class DocumentImportersRegistry; class U2CORE_EXPORT DocumentFormatRegistry : public QObject { Q_OBJECT public: DocumentFormatRegistry(QObject* p = NULL) : QObject(p) {} virtual bool registerFormat(DocumentFormat* dfs) = 0; virtual bool unregisterFormat(DocumentFormat* dfs) = 0; virtual QList getRegisteredFormats() const = 0; virtual DocumentFormat* getFormatById(DocumentFormatId id) const = 0; virtual DocumentFormat* selectFormatByFileExtension(const QString& fileExt) const = 0; virtual QList selectFormats(const DocumentFormatConstraints& c) const = 0; virtual DocumentImportersRegistry* getImportSupport() = 0; signals: void si_documentFormatRegistered(DocumentFormat*); void si_documentFormatUnregistered(DocumentFormat*); }; enum DocumentModLock { DocumentModLock_IO, DocumentModLock_USER, DocumentModLock_FORMAT_AS_CLASS, DocumentModLock_FORMAT_AS_INSTANCE, DocumentModLock_UNLOADED_STATE, DocumentModLock_NUM_LOCKS }; class U2CORE_EXPORT Document : public StateLockableTreeItem { Q_OBJECT Q_PROPERTY( QString name WRITE setName READ getName ) Q_PROPERTY( GUrl url WRITE setURL READ getURL ) public: class Constraints { public: Constraints() : stateLocked(TriState_Unknown) {} TriState stateLocked; QList notAllowedStateLocks; // if document contains one of these locks -> it's not matched QList formats; // document format must be in list to match GObjectType objectTypeToAdd; // document must be ready to add objects of the specified type }; //Creates document in unloaded state. Populates it with unloaded objects Document(DocumentFormat* _df, IOAdapterFactory* _io, const GUrl& _url, const QList& unloadedObjects = QList(), const QVariantMap& hints = QVariantMap(), const QString& instanceModLockDesc = QString()); //Creates document in loaded state. Document(DocumentFormat* _df, IOAdapterFactory* _io, const GUrl& _url, const QList& objects, const QVariantMap& hints = QVariantMap(), const QString& instanceModLockDesc = QString()); virtual ~Document(); DocumentFormat* getDocumentFormat() const {return df;} DocumentFormatId getDocumentFormatId() const {return df->getFormatId();} IOAdapterFactory* getIOAdapterFactory() const {return io;} const QList& getObjects() const {return objects;} void addObject(GObject* ref); void removeObject(GObject* o); const QString& getName() const {return name;} void setName(const QString& newName); const GUrl& getURL() const {return url;} const QString& getURLString() const {return url.getURLString();} void setURL(const GUrl& newUrl); void makeClean(); GObject* findGObjectByName(const QString& name) const; QList findGObjectByType(GObjectType t, UnloadedObjectFilter f = UOF_LoadedOnly) const; bool isLoaded() const {return modLocks[DocumentModLock_UNLOADED_STATE] == 0;} void setLoaded(bool v); void loadFrom(const Document* d); bool unload(); Document* clone() const; bool checkConstraints(const Constraints& c) const; GHints* getGHints() const {return ctxState;} void setGHints(GHints* state); QVariantMap getGHintsMap() const; StateLock* getDocumentModLock(DocumentModLock type) const {return modLocks[type];} void propagateModLocks(Document* doc) const; bool hasUserModLock() const {return modLocks[DocumentModLock_USER]!=NULL;} void setUserModLock(bool v); virtual void setModified(bool modified, const QString& modType = QString()); virtual bool isModificationAllowed(const QString& modType); bool isModified() const { return isTreeItemModified(); } void setLastUpdateTime(); const QDateTime& getLastUpdateTime() const { return lastUpdateTime; } static void setupToEngine(QScriptEngine *engine); private: static QScriptValue toScriptValue(QScriptEngine *engine, Document* const &in); static void fromScriptValue(const QScriptValue &object, Document* &out); protected: void _removeObject(GObject* o); void _addObject(GObject* obj); void _addObjectToHierarchy(GObject* obj); void initModLocks(const QString& instanceModLockDesc, bool loaded); void checkUnloadedState() const; void checkLoadedState() const; void checkUniqueObjectNames() const; void addUnloadedObjects(const QList& info); DocumentFormat* const df; IOAdapterFactory* const io; GUrl url; QString name; /* display name == short pathname, excluding the path */ QList objects; GHints* ctxState; QDateTime lastUpdateTime; StateLock* modLocks[DocumentModLock_NUM_LOCKS]; bool loadStateChangeMode; signals: void si_urlChanged(); void si_nameChanged(); void si_objectAdded(GObject* o); void si_objectRemoved(GObject* o); void si_loadedStateChanged(); }; //TODO: decide if to use filters or constraints. May be it worth to remove Document::Constraints at all.. class U2CORE_EXPORT DocumentFilter { public: virtual ~DocumentFilter(){}; virtual bool matches(Document* doc) const = 0; }; class U2CORE_EXPORT DocumentConstraintsFilter : public DocumentFilter { public: DocumentConstraintsFilter(const Document::Constraints& _c) : constraints(_c){} virtual bool matches(Document* doc) const { return doc->checkConstraints(constraints); } protected: Document::Constraints constraints; }; class U2CORE_EXPORT DocumentMimeData : public QMimeData { Q_OBJECT public: static const QString MIME_TYPE; DocumentMimeData(Document* obj) : objPtr(obj){}; QPointer objPtr; bool hasFormat ( const QString & mimeType ) const { return (mimeType == MIME_TYPE);} QStringList formats () const {return (QStringList() << MIME_TYPE);} }; } //namespace Q_DECLARE_METATYPE(U2::Document*) #endif ugene-1.9.8/src/corelibs/U2Core/src/models/GHints.h0000644000175000017500000000474411651544332020436 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_GHINTS_H_ #define _U2_GHINTS_H_ #include #include namespace U2 { class U2CORE_EXPORT GHints { public: virtual ~GHints(){}; virtual QVariantMap getMap() const = 0; virtual void setMap(const QVariantMap& map) = 0; virtual QVariant get(const QString& key) const = 0; virtual void set(const QString& key, const QVariant& val) = 0; virtual void setAll(const QVariantMap& map); virtual int remove(const QString& key) = 0; static void dump(const QVariantMap& map); }; class U2CORE_EXPORT GHintsDefaultImpl : public GHints { public: GHintsDefaultImpl(const QVariantMap& _map = QVariantMap()) : map(_map) {} virtual QVariantMap getMap() const {return map;} virtual void setMap(const QVariantMap& _map) {map = _map;} virtual QVariant get(const QString& key) const {return map.value(key);} virtual void set(const QString& key, const QVariant& val) {map[key] = val;} virtual int remove(const QString& key) {return map.remove(key);} protected: QVariantMap map; }; class StateLockableTreeItem; class U2CORE_EXPORT ModTrackHints : public GHintsDefaultImpl { public: ModTrackHints(StateLockableTreeItem* _p, const QVariantMap& _map, bool _topParentMode) : GHintsDefaultImpl(_map), p(_p), topParentMode(_topParentMode){} virtual void setMap(const QVariantMap& _map); virtual void set(const QString& key, const QVariant& val); virtual int remove(const QString& key); private: void setModified(); StateLockableTreeItem* p; bool topParentMode; }; }//namespace #endif ugene-1.9.8/src/corelibs/U2Core/src/models/GObject.cpp0000644000175000017500000001546711651544332021116 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "GObject.h" #include "DocumentModel.h" #include "GHints.h" #include #include #include namespace U2 { GObject::GObject(QString _type, const QString& _name, const QVariantMap& hintsMap) : type (_type), name(_name) { assert(name.length() > 0); hints = new GHintsDefaultImpl(hintsMap); hints->set(GObjectHint_LastUsedObjectName, name); } GObject::~GObject() { delete hints; } QVariantMap GObject::getGHintsMap() const { return getGHints()->getMap(); } Document* GObject::getDocument() const { StateLockableTreeItem* sl = getParentStateLockItem(); Document* doc = qobject_cast(sl); return doc; } void GObject::setGHints(GHints* s) { delete hints; hints = s; } void GObject::setGObjectName(const QString& newName) { if (name == newName) { return; } SAFE_POINT(getDocument() == NULL || getDocument()->findGObjectByName(newName) == NULL, "Duplicate object name!",); QString oldName = name; name = newName; hints->set(GObjectHint_LastUsedObjectName, name); emit si_nameChanged(oldName); } QList GObject::getObjectRelations() const { QList res = hints->get(GObjectHint_RelatedObjects).value >(); return res; } void GObject::setObjectRelations(const QList& list) { hints->set(GObjectHint_RelatedObjects, QVariant::fromValue >(list)); } QList GObject::findRelatedObjectsByRole(const QString& role) const { QList res; QList relations = getObjectRelations(); foreach(const GObjectRelation& ref, relations) { if (ref.role == role) { res.append(ref); } } return res; } QList GObject::findRelatedObjectsByType(const GObjectType& objType) const { QList res; foreach(const GObjectRelation& rel, getObjectRelations()) { if (rel.ref.objType == objType) { res.append(rel); } } return res; } void GObject::addObjectRelation(const GObjectRelation& rel) { SAFE_POINT(rel.isValid(), "Object relation is not valid!", ); removeObjectRelation(rel); QList list = getObjectRelations(); list.append(rel); setObjectRelations(list); } void GObject::removeObjectRelation(const GObjectRelation& ref) { QList list = getObjectRelations(); bool ok = list.removeOne(ref); if (ok) { setObjectRelations(list); } } void GObject::addObjectRelation(const GObject* obj, const QString& role) { GObjectRelation rel(obj, role); addObjectRelation(rel); } bool GObject::hasObjectRelation(const GObjectRelation& r) const { return getObjectRelations().contains(r); } bool GObject::hasObjectRelation(const GObject* obj, const QString& role) const { GObjectRelation rel(obj, role); return hasObjectRelation(rel); } bool GObject::isUnloaded() const { return type == GObjectTypes::UNLOADED; } void GObject::updateRefInRelations(const GObjectReference& oldRef, const GObjectReference& newRef) { QList rels = getObjectRelations(); bool changed = false; for (int i = 0; i < rels.size(); i++) { GObjectRelation& rel = rels[i]; if (rel.ref == oldRef) { rel.ref = newRef; changed = true; } } if (changed) { setObjectRelations(rels); } } ////////////////////////////////////////////////////////////////////////// // GObjectReference GObjectReference::GObjectReference(const GObject* obj, bool deriveLoadedType) { assert(obj!=NULL && obj->getDocument()!=NULL); docUrl = obj->getDocument()->getURLString(); objName = obj->getGObjectName(); if (obj->isUnloaded() && deriveLoadedType) { const UnloadedObject* uo = qobject_cast(obj); objType = uo->getLoadedObjectType(); } else { objType = obj->getGObjectType(); } } bool GObjectReference::operator ==(const GObjectReference& r) const { return objName == r.objName && docUrl == r.docUrl && objType == r.objType; } bool GObjectRelation::operator ==(const GObjectRelation& r) const { return ref == r.ref && role == r.role && data == r.data; } QDataStream &operator<<(QDataStream &out, const GObjectReference &myObj) { out << myObj.docUrl << myObj.objName << myObj.objType; return out; } QDataStream &operator>>(QDataStream &in, GObjectReference &myObj) { in >> myObj.docUrl; in >> myObj.objName; in >> myObj.objType; return in; } QDataStream &operator<<(QDataStream &out, const GObjectRelation &myObj) { out << myObj.ref << myObj.role << myObj.data; return out; } QDataStream &operator>>(QDataStream &in, GObjectRelation &myObj) { in >> myObj.ref; in >> myObj.role; in >> myObj.data; return in; } static bool registerMetas1() { qRegisterMetaType("GObjectReference"); qRegisterMetaTypeStreamOperators("U2::GObjectReference"); qRegisterMetaType >("QList"); qRegisterMetaTypeStreamOperators< QList >("QList"); return true; } static bool registerMetas2() { qRegisterMetaType("GObjectRelation"); qRegisterMetaTypeStreamOperators("U2::GObjectRelation"); qRegisterMetaType >("QList"); qRegisterMetaTypeStreamOperators< QList >("QList"); return true; } bool GObjectReference::registerMeta = registerMetas1(); bool GObjectRelation::registerMeta = registerMetas2(); ////////////////////////////////////////////////////////////////////////// // mime const QString GObjectMimeData::MIME_TYPE("application/x-ugene-object-mime"); GObjectMimeData::~GObjectMimeData() { //printf("GObjectMimeData destroyed!\n"); } } //endif ugene-1.9.8/src/corelibs/U2Core/src/models/DocumentImport.h0000644000175000017500000000465711651544332022216 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_DOCUMENT_IMPORT_H_ #define _U2_DOCUMENT_IMPORT_H_ #include namespace U2 { class DocumentImporter; class DocumentProviderTask; class FormatDetectionResult; /** Registry for all DocumentImportHandlers */ class U2CORE_EXPORT DocumentImportersRegistry: public QObject { Q_OBJECT public: DocumentImportersRegistry(QObject* p = NULL) : QObject(p) {} ~DocumentImportersRegistry(); /** returns handler by its id */ DocumentImporter* getDocumentImporter(const QString& importerId) const; /** registers new document import handler */ void addDocumentImporter(DocumentImporter* i); const QList& getImporters() const {return importers;} private: QList importers; }; class U2CORE_EXPORT DocumentImporter : public QObject { Q_OBJECT public: DocumentImporter(const QString& _id, const QString& _name, QObject* o = NULL) : QObject(o), id(_id), name(_name){} virtual RawDataCheckResult checkRawData(const QByteArray& rawData, const GUrl& url) = 0; virtual DocumentProviderTask* createImportTask(const FormatDetectionResult& res, bool showWizard) = 0; virtual QString getImporterDescription() const {return importerDescription;} const QString& getImporterName() const {return name;} const QString& getId() const {return id;} const QList& getSupportedFileExtensions() const {return extensions;} protected: QString id; QString name; QList extensions; QString importerDescription; }; } //namespace #endif ugene-1.9.8/src/corelibs/U2Core/src/models/StateLockableDataModel.h0000644000175000017500000001332511651544332023525 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_STATE_LOCKS_H_ #define _U2_STATE_LOCKS_H_ #include #include namespace U2 { #define StateLockModType_AddChild "state-lock-mod-add-child" enum StateLockFlag { StateLockFlag_NoFlags = 0x00, StateLockFlag_LiveLock = 0x01, StateLockFlag_AnyFlags = 0xFF }; typedef QFlags StateLockFlags; class U2CORE_EXPORT StateLock { public: StateLock() : flags(StateLockFlag_NoFlags){} StateLock(const QString& _userDesc, StateLockFlags _flags = StateLockFlag_NoFlags) : userDesc(_userDesc), flags(_flags){} QString getUserDesc() const {return userDesc;} void setUserDesc(const QString& d) {userDesc = d;} StateLockFlags getFlags() const {return flags;} private: QString userDesc; StateLockFlags flags; }; class U2CORE_EXPORT StateLockableItem : public QObject { Q_OBJECT public: StateLockableItem(QObject* p = NULL); ~StateLockableItem(); int getStateLocksCount() const {return locks.size();} virtual bool isStateLocked() const {return !locks.isEmpty();} const QList& getStateLocks() const {return locks;} virtual void lockState(StateLock* lock); virtual void unlockState(StateLock* lock); virtual void setModified(bool modified, const QString& modType = QString()); virtual bool isModificationAllowed(const QString& modType) {Q_UNUSED(modType); return !isStateLocked();} virtual bool isItemModified() const {return itemIsModified;} /** Main thread model object can only be modified in main thread */ virtual bool isMainThreadModificationOnly() const {return mainThreadModificationOnly;} virtual void setMainThreadModificationOnly(bool v) { mainThreadModificationOnly = v;} virtual bool isMainThreadObject() const; //returns number of modifications done to this item virtual int getModificationVersion() const {return modificationVersion;} signals: void si_lockedStateChanged(); void si_modifiedStateChanged(); protected: QList locks; bool itemIsModified; bool mainThreadModificationOnly; int modificationVersion; }; ////////////////////////////////////////////////////////////////////////// /// Tree model enum StateLockableTreeItemBranchFlag { StateLockableTreeItemBranch_Item = 0x1, StateLockableTreeItemBranch_Parents = 0x2, StateLockableTreeItemBranch_Children = 0x4 }; typedef QFlags StateLockableTreeItemBranchFlags; #define StateLockableTreeFlags_ItemAndChildren (StateLockableTreeItemBranchFlags(StateLockableTreeItemBranch_Item) | StateLockableTreeItemBranch_Children) #define StateLockableTreeFlags_ItemAndParents (StateLockableTreeItemBranchFlags(StateLockableTreeItemBranch_Item) | StateLockableTreeItemBranch_Parents) #define StateLockableTreeFlags_ItemAndChildrenAndParents (StateLockableTreeFlags_ItemAndParents | StateLockableTreeItemBranch_Children) class U2CORE_EXPORT StateLockableTreeItem : public StateLockableItem { Q_OBJECT public: StateLockableTreeItem() : StateLockableItem(), parentStateLockItem(NULL), childLocksCount(0), numModifiedChildren(0){} ~StateLockableTreeItem(); virtual bool isStateLocked() const; virtual void lockState(StateLock* lock); virtual void unlockState(StateLock* lock); virtual void setModified(bool modified, const QString& modType = QString()); virtual bool isTreeItemModified () const {return numModifiedChildren > 0 || itemIsModified;} virtual bool hasModifiedChildren() const {return numModifiedChildren != 0;} StateLockableTreeItem* getParentStateLockItem() const { return parentStateLockItem; } bool hasLocks(StateLockableTreeItemBranchFlags treeFlags, StateLockFlag lockFlag = StateLockFlag_AnyFlags) const { return !findLocks(treeFlags, lockFlag).isEmpty(); } int countLocks(StateLockableTreeItemBranchFlags treeFlags, StateLockFlag lockFlag = StateLockFlag_AnyFlags) const { return findLocks(treeFlags, lockFlag).size(); } QList findLocks(StateLockableTreeItemBranchFlags treeFlags, StateLockFlag lockFlag = StateLockFlag_AnyFlags) const; virtual bool isMainThreadModificationOnly() const; protected: static void setParentStateLockItem_static(StateLockableTreeItem* child, StateLockableTreeItem* newParent) { child->setParentStateLockItem(newParent); } void setParentStateLockItem(StateLockableTreeItem* p); void increaseNumModifiedChilds(int n); void decreaseNumModifiedChilds(int n); void onParentStateLocked(); void onParentStateUnlocked(); const QSet& getChildItems() const {return childItems;} private: StateLockableTreeItem* parentStateLockItem; QSet childItems; int childLocksCount; int numModifiedChildren; }; }//namespace #endif ugene-1.9.8/src/corelibs/U2Core/src/models/GHints.cpp0000644000175000017500000000434711651544332020770 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "GHints.h" #include #include namespace U2 { void GHints::setAll(const QVariantMap& newMap) { foreach(const QString& key, newMap.keys()) { QVariant val = newMap.value(key); set(key, val); } } void GHints::dump(const QVariantMap& map) { foreach(QString k, map.keys()) { QList l = map.values(k); foreach(QVariant v, l) { coreLog.trace(QString("Hint: %1=%2").arg(k).arg(v.toString())); } } } void ModTrackHints::setMap(const QVariantMap& _map) { if (map == _map) { return; } map = _map; setModified(); } void ModTrackHints::set(const QString& key, const QVariant& val) { QVariant oldVal = get(key); if (oldVal == val) { return; } // QString newV = val.toString(); // QString oldV = oldVal.toString(); map[key] = val; setModified(); } int ModTrackHints::remove(const QString& key) { int r = map.remove(key); if (r != 0) { setModified(); } return r; } void ModTrackHints::setModified() { StateLockableTreeItem* modItem = p; while (modItem->getParentStateLockItem()!=NULL && topParentMode) { modItem = modItem->getParentStateLockItem(); } if (!modItem->isStateLocked()) { //TODO: use isModificationAllowed here! modItem->setModified(true); } } }//namespace ugene-1.9.8/src/corelibs/U2Core/src/models/DocumentUtils.cpp0000644000175000017500000001351711651544332022372 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "DocumentUtils.h" #include #include #include #include namespace U2 { QSet DocumentUtils::getURLs(const QList& docs) { QSet result; foreach(Document* d, docs) { result.insert(d->getURLString()); } return result; } QSet DocumentUtils::getNewDocFileNameExcludesHint() { QSet excludeFileNames; Project* p = AppContext::getProject(); if (p!=NULL) { excludeFileNames = DocumentUtils::getURLs(p->getDocuments()); } return excludeFileNames; } static void placeOrderedByScore(const FormatDetectionResult& info, QList& result, const FormatDetectionConfig& conf) { if (info.score() == FormatDetection_NotMatched) { return; } if (result.isEmpty()) { result.append(info); return; } if (conf.bestMatchesOnly) { int bestScore = result.first().score(); if (bestScore > info.score()) { return; } else if (bestScore < info.score()) { result.clear(); } result.append(info); return; } for (int i = 0; i < result.length(); i++) { int scoreI = result.at(i).score(); if (scoreI < info.score()) { result.insert(i, info); return; } } result.append(info); } #define FORMAT_DETECTION_EXT_BONUS 3 // returns formats with FormatDetectionResult != Not matched sorted by FormatDetectionResult // FormatDetectionResult is adjusted by +FORMAT_DETECTION_EXT_BONUS if extension is matched QList DocumentUtils::detectFormat( const QByteArray& rawData, const QString& ext, const GUrl& url, const FormatDetectionConfig& conf) { DocumentFormatRegistry* fr = AppContext::getDocumentFormatRegistry(); QList< DocumentFormatId > allFormats = fr->getRegisteredFormats(); QList result; foreach(const DocumentFormatId& id, allFormats) { DocumentFormat* f = fr->getFormatById(id); RawDataCheckResult cr = f->checkRawData(rawData, url); if (cr.score == FormatDetection_NotMatched) { continue; } if (conf.useExtensionBonus && f->getSupportedDocumentFileExtensions().contains(ext) && cr.score >= FormatDetection_VeryLowSimilarity) { cr.score += FORMAT_DETECTION_EXT_BONUS; } FormatDetectionResult res; res.format = f; res.rawDataCheckResult = cr; res.rawData = rawData; res.url = url; res.extension = ext; placeOrderedByScore(res, result, conf); } if (conf.useImporters) { DocumentImportersRegistry* importReg = AppContext::getDocumentFormatRegistry()->getImportSupport(); foreach(DocumentImporter* i, importReg->getImporters()) { RawDataCheckResult cr = i->checkRawData(rawData, url); if (conf.useExtensionBonus && i->getSupportedFileExtensions().contains(ext) && cr.score >= FormatDetection_VeryLowSimilarity) { cr.score += FORMAT_DETECTION_EXT_BONUS; } FormatDetectionResult res; res.importer = i; res.rawDataCheckResult = cr; res.rawData = rawData; res.url = url; res.extension = ext; placeOrderedByScore(res, result, conf); } } return result; } QList DocumentUtils::detectFormat(const GUrl& url, const FormatDetectionConfig& conf) { QList result; if( url.isEmpty() ) { return result; } QByteArray rawData = BaseIOAdapters::readFileHeader(url); if (rawData.isEmpty()) { return result; } QString ext = GUrlUtils::getUncompressedExtension(url); result = detectFormat(rawData, ext, url, conf); return result; } QList DocumentUtils::detectFormat(IOAdapter *io, const FormatDetectionConfig& conf) { QList result; if (io == NULL || !io->isOpen()) { return result; } QByteArray rawData = BaseIOAdapters::readFileHeader( io ); QString ext = GUrlUtils::getUncompressedExtension(io->getURL()); result = detectFormat( rawData, ext , io->getURL(), conf); return result; } QList DocumentUtils::toFormats(const QList& infos) { QList result; foreach(const FormatDetectionResult& info, infos) { if (info.format != NULL) { result << info.format; } } return result; } QString FormatDetectionResult::getFormatDescriptionText() const { QString text = format == NULL ? importer->getImporterDescription() : format->getFormatDescription(); return text; } QString FormatDetectionResult::getFormatOrImporterName() const { QString name = format == NULL ? importer->getImporterName() : format->getFormatName(); return name; } } //namespace ugene-1.9.8/src/corelibs/U2Core/src/models/ProjectModel.h0000644000175000017500000001100211651544332021612 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_PROJECT_MODEL_H_ #define _U2_PROJECT_MODEL_H_ #include "DocumentModel.h" #include "StateLockableDataModel.h" #define CURRENT_PROJECT_VERSION "1.0" namespace U2 { class GObjectViewState; class Document; class Project; class Task; class U2OpStatus; #define PROJECT_FILE_PURE_EXT QString("uprj") #define PROJECTFILE_EXT QString("." + PROJECT_FILE_PURE_EXT) //data loader hints #define ProjectLoaderHint_CloseActiveProject "close-active-project" #define ProjectLoaderHint_ForceFormatOptions "force-format-options" #define ProjectLoaderHint_LoadWithoutView "load-without-view" #define ProjectLoaderHint_LoadUnloadedDocument "load-unloaded-document" /// Service responsible for project loading / unloading class U2CORE_EXPORT ProjectLoader : public QObject { public: /** Opens files and adds them to the current project. If project does not exists - creates anonymous one If the file is project file - loads it. */ virtual Task* openWithProjectTask(const QList& urls, const QVariantMap& hints = QVariantMap()) = 0; /** Creates new project. If URL is empty the project created is anonymous */ virtual Task* createNewProjectTask(const GUrl& url = GUrl()) = 0; /** Loads project from the specified location */ virtual Task* createProjectLoadingTask(const GUrl& url, const QVariantMap& hints = QVariantMap()) = 0; /** Creates new project instance */ virtual Project* createProject(const QString& name, const QString& url, QList& documents, QList& states) = 0; Task* openWithProjectTask(const GUrl& url, const QVariantMap& hints = QVariantMap()) { QList urls; urls << url; return openWithProjectTask(urls, hints); }; }; /// Project model class U2CORE_EXPORT Project : public StateLockableTreeItem { Q_OBJECT Q_PROPERTY( QString name WRITE setProjectName READ getProjectName ) Q_PROPERTY( QString url WRITE setProjectURL READ getProjectURL ) Q_PROPERTY( QList docs READ getDocuments ) public: virtual const QString& getProjectName() const = 0; virtual void setProjectName(const QString& name) = 0; virtual const QString& getProjectURL() const = 0; virtual void setProjectURL(const QString&) = 0; virtual const QList& getDocuments() const = 0; Q_INVOKABLE virtual void addDocument(Document* d) = 0; Q_INVOKABLE virtual void removeDocument(Document* d, bool autodelete = true) = 0; Q_INVOKABLE virtual Document* findDocumentByURL(const QString& url) const = 0; Q_INVOKABLE virtual Document* findDocumentByURL(const GUrl& url) const = 0; virtual bool lockResources(int sizeMB, const QString & url, QString &error) = 0; virtual const QList& getGObjectViewStates() const =0; virtual void addGObjectViewState(GObjectViewState* s) = 0; virtual void removeGObjectViewState(GObjectViewState* s) = 0; virtual void makeClean() = 0; virtual quint64 getObjectIdCounter() const = 0; virtual void setObjectIdCounter(quint64 c) = 0; static void setupToEngine(QScriptEngine *engine); private: static QScriptValue toScriptValue(QScriptEngine *engine, Project* const &in); static void fromScriptValue(const QScriptValue &object, Project* &out); signals: void si_projectURLChanged(const QString& oldURL); void si_projectRenamed(Project* p); void si_documentAdded(Document* d); void si_documentRemoved(Document* d); void si_objectViewStateAdded(GObjectViewState*); void si_objectViewStateRemoved(GObjectViewState*); }; class DocumentSerialState { }; }//namespace Q_DECLARE_METATYPE(U2::Project*) Q_DECLARE_METATYPE(QList) #endif ugene-1.9.8/src/corelibs/U2Core/src/models/DocumentModel.cpp0000644000175000017500000004466111651544332022336 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include #include #include #include #include #include #include #include #include #include #include #include /* TRANSLATOR U2::DocumentFormat */ namespace U2 { const QString DocumentFormat::CREATED_NOT_BY_UGENE = DocumentFormat::tr( "The document is created not by UGENE" ); const QString DocumentFormat::MERGED_SEQ_LOCK = DocumentFormat::tr( "Document sequences were merged" ); const QString DocumentMimeData::MIME_TYPE("application/x-ugene-document-mime"); Document* DocumentFormat::createNewDocument(IOAdapterFactory* io, const GUrl& url, const QVariantMap& hints) { Document* d = new Document(this, io, url, QList(), hints); d->setLoaded(true); return d; } Document* DocumentFormat::loadDocument(IOAdapterFactory* iof, const GUrl& url, TaskStateInfo& ti, const QVariantMap& hints) { std::auto_ptr io(iof->createIOAdapter()); if (!io->open(url, IOAdapterMode_Read)) { ti.setError(L10N::errorOpeningFileRead(url)); return NULL; } Document * doc = loadDocument(io.get(), ti, hints, DocumentLoadMode_Whole); return doc; } GObject* DocumentFormat::loadObject(IOAdapter*, TaskStateInfo& ti) { ti.setError("This document format is not support streaming reading mode"); return NULL; } DNASequence* DocumentFormat::loadSequence(IOAdapter*, TaskStateInfo& ti) { ti.setError("This document format is not support streaming reading mode"); return NULL; } void DocumentFormat::storeDocument( Document* , TaskStateInfo& ts, IOAdapter* ) { assert(0); ts.setError(tr("Writing is not supported for this format (%1). Feel free to send a feature request though.").arg(getFormatName())); } void DocumentFormat::storeDocument(Document* doc, TaskStateInfo& ti, IOAdapterFactory* iof, const GUrl& newDocURL) { if (!formatFlags.testFlag(DocumentFormatFlag_SupportWriting)) { assert(0); ti.setError(tr("Writing is not supported for this format (%1). Feel free to send a feature request though.").arg(getFormatName())); return; } assert(doc->getDocumentModLock(DocumentModLock_FORMAT_AS_INSTANCE) == NULL); if (iof == NULL) { iof = doc->getIOAdapterFactory(); } //prepare URL GUrl url = newDocURL.isEmpty() ? doc->getURL() : newDocURL; if (url.isLocalFile()) { QString error; QString res = GUrlUtils::prepareFileLocation(url.getURLString(), error); if (!error.isEmpty()) { ti.setError(error); return; } Q_UNUSED(res); assert(res == url.getURLString()); //ensure that GUrls are always canonical } std::auto_ptr io(iof->createIOAdapter()); if (!io->open(url, IOAdapterMode_Write)) { ti.setError(L10N::errorOpeningFileWrite(url)); return; } storeDocument(doc, ti, io.get()); } bool DocumentFormat::checkConstraints(const DocumentFormatConstraints& c) const { assert(!supportedObjectTypes.isEmpty()); //extra check for DF state validation if (!checkFlags(c.flagsToSupport)) { return false; //requested to support writing or streaming but doesn't } if ((int(c.flagsToExclude) & int(formatFlags)) != 0) { return false; // filtered by exclude flags } if (c.checkRawData && checkRawData(c.rawData).score < c.minDataCheckResult) { return false; //raw data is not matched } foreach (GObjectType objType, c.supportedObjectTypes) { if (!supportedObjectTypes.contains(objType)) { // the object type is not in the supported list return false; } } return true; } bool DocumentFormat::isObjectOpSupported(const Document* d, DocObjectOp op, GObjectType t) const { assert(d->getDocumentFormat() == this); if (!supportedObjectTypes.contains(t)) { return false; } if (!checkFlags(DocumentFormatFlag_SupportWriting)) { return false; } if (op == DocObjectOp_Add) { int nObjects = d->getObjects().size(); if (nObjects != 0 && checkFlags(DocumentFormatFlag_SingleObjectFormat)) { return false; } } return true; } ////////////////////////////////////////////////////////////////////////// ///Document Document::Document(DocumentFormat* _df, IOAdapterFactory* _io, const GUrl& _url, const QList& unloadedObjects, const QVariantMap& hints, const QString& instanceModLockDesc) : StateLockableTreeItem(), df(_df), io(_io), url(_url) { ctxState = new GHintsDefaultImpl(hints); name = url.fileName(); qFill(modLocks, modLocks + DocumentModLock_NUM_LOCKS, (StateLock*)NULL); loadStateChangeMode = true; addUnloadedObjects(unloadedObjects); loadStateChangeMode = false; initModLocks(instanceModLockDesc, false); checkUnloadedState(); assert(!isModified()); } Document::Document(DocumentFormat* _df, IOAdapterFactory* _io, const GUrl& _url, const QList& _objects, const QVariantMap& hints, const QString& instanceModLockDesc) : StateLockableTreeItem(), df(_df), io(_io), url(_url) { ctxState = new GHintsDefaultImpl(hints); name = url.fileName(); loadStateChangeMode = true; qFill(modLocks, modLocks + DocumentModLock_NUM_LOCKS, (StateLock*)NULL); foreach(GObject* o, _objects) { _addObject(o); } loadStateChangeMode = false; initModLocks(instanceModLockDesc, true); checkLoadedState(); assert(!isModified()); } Document::~Document() { for (int i=0;isetGHints(NULL); } delete ctxState; } void Document::addObject(GObject* obj){ assert(obj != NULL && obj->getDocument()==NULL); assert(df->isObjectOpSupported(this, DocumentFormat::DocObjectOp_Add, obj->getGObjectType())); //assert(findGObjectByName(obj->getGObjectName())==NULL); assert(isLoaded()); assert(obj->getGObjectType()!=GObjectTypes::UNLOADED); assert(!obj->isTreeItemModified()); _addObject(obj); } void Document::_addObjectToHierarchy(GObject* obj) { obj->setParentStateLockItem(this); obj->setGHints(new ModTrackHints(this, obj->getGHintsMap(), true)); obj->setModified(false); objects.append(obj); } void Document::_addObject(GObject* obj) { _addObjectToHierarchy(obj); assert(objects.size() == getChildItems().size()); emit si_objectAdded(obj); } void Document::removeObject(GObject* obj) { assert(df->isObjectOpSupported(this, DocumentFormat::DocObjectOp_Remove, obj->getGObjectType())); assert(!obj->isTreeItemModified()); _removeObject(obj); } void Document::_removeObject(GObject* obj) { assert(obj->getParentStateLockItem() == this); obj->setModified(false); obj->setParentStateLockItem(NULL); objects.removeOne(obj); obj->setGHints(new GHintsDefaultImpl()); assert(objects.size() == getChildItems().size()); emit si_objectRemoved(obj); delete obj; } void Document::makeClean() { if (!isTreeItemModified()) { return; } setModified(false); foreach(GObject* obj, objects) { obj->setModified(false); } } GObject* Document::findGObjectByName(const QString& name) const { foreach(GObject* obj, objects) { if (obj->getGObjectName() == name) { return obj; } } return NULL; } QList Document::findGObjectByType(GObjectType t, UnloadedObjectFilter f) const { return GObjectUtils::select(objects, t, f); } Document* Document::clone() const { Document* doc = new Document(df, io, url, QList(), ctxState->getMap()); doc->loadFrom(this); return doc; } void Document::checkUnloadedState() const { #ifdef _DEBUG assert(!isLoaded()); bool hasNoLoadedObjects = findGObjectByType(GObjectTypes::UNLOADED, UOF_LoadedAndUnloaded).count() == objects.count(); assert(hasNoLoadedObjects); checkUniqueObjectNames(); #endif } void Document::checkUniqueObjectNames() const { #ifdef _DEBUG QSet names; foreach(GObject* o, objects) { const QString& name = o->getGObjectName(); assert(!names.contains(name)); names.insert(name); } #endif } void Document::checkLoadedState() const { #ifdef _DEBUG assert(isLoaded()); bool hasNoUnloadedObjects = findGObjectByType(GObjectTypes::UNLOADED, UOF_LoadedAndUnloaded).isEmpty(); assert(hasNoUnloadedObjects); checkUniqueObjectNames(); #endif } static StateLock* NULL_LOCK = NULL; void Document::loadFrom(const Document* d) { assert(d->getDocumentFormat() == df); assert(!isLoaded() && d->isLoaded()); d->checkLoadedState(); checkUnloadedState(); int nDocLocks = 0; qCount(modLocks, modLocks + DocumentModLock_NUM_LOCKS, NULL_LOCK, nDocLocks); nDocLocks = DocumentModLock_NUM_LOCKS - nDocLocks; #ifdef _DEBUG int totalLocks = locks.count(); assert(totalLocks == nDocLocks); #endif loadStateChangeMode = true; QMap unloadedInfo; foreach(GObject* obj, objects) { //remove all unloaded objects unloadedInfo.insert(obj->getGObjectName(), UnloadedObjectInfo(obj)); _removeObject(obj); } ctxState->setAll(d->getGHints()->getMap()); lastUpdateTime = d->getLastUpdateTime(); //copy instance modlocks if any StateLock* mLock = modLocks[DocumentModLock_FORMAT_AS_INSTANCE]; if (mLock!=NULL) { unlockState(mLock); delete mLock; modLocks[DocumentModLock_FORMAT_AS_INSTANCE] = NULL; } StateLock* dLock = d->modLocks[DocumentModLock_FORMAT_AS_INSTANCE]; if (dLock!=NULL) { modLocks[DocumentModLock_FORMAT_AS_INSTANCE] = new StateLock(dLock->getUserDesc()); lockState(modLocks[DocumentModLock_FORMAT_AS_INSTANCE]); } QList objects = d->getObjects(); foreach(GObject* origObj, objects) { GObject* clonedObj = origObj->clone(); //merge hints, TODO: add constrains to ObjectRelations!! UnloadedObjectInfo info = unloadedInfo.value(clonedObj->getGObjectName()); if (info.type == clonedObj->getGObjectType()) { QVariantMap mergedHints = clonedObj->getGHintsMap(); foreach(const QString& k, info.hints.keys()) { if (!mergedHints.contains(k)) { mergedHints.insert(k, info.hints.value(k)); } } clonedObj->getGHints()->setMap(mergedHints); } _addObject(clonedObj); } setLoaded(true); //TODO: rebind local objects relations if url!=d.url loadStateChangeMode = false; checkLoadedState(); } void Document::setLoaded(bool v) { if (v == isLoaded()) { return; } StateLock* l = modLocks[DocumentModLock_UNLOADED_STATE]; if (v) { unlockState(l); modLocks[DocumentModLock_UNLOADED_STATE] = NULL; delete l; checkLoadedState(); } else { assert(l == NULL); l = new StateLock(tr("Document is not loaded")); modLocks[DocumentModLock_UNLOADED_STATE] = l; lockState(l); checkUnloadedState(); } emit si_loadedStateChanged(); } void Document::initModLocks(const QString& instanceModLockDesc, bool loaded) { setLoaded(loaded); // must be locked for modifications if io-adapter does not support writes if (!io->isIOModeSupported(IOAdapterMode_Write)) { modLocks[DocumentModLock_IO] = new StateLock(tr("IO adapter does not support write operation")); lockState(modLocks[DocumentModLock_IO]); } // must be locked for modifications if not document format does not support writes if (!df->checkFlags(DocumentFormatFlag_SupportWriting)) { modLocks[DocumentModLock_FORMAT_AS_CLASS] = new StateLock(tr("No write support for document format")); lockState(modLocks[DocumentModLock_FORMAT_AS_CLASS]); } if (!instanceModLockDesc.isEmpty()) { modLocks[DocumentModLock_FORMAT_AS_INSTANCE] = new StateLock(instanceModLockDesc); lockState(modLocks[DocumentModLock_FORMAT_AS_INSTANCE]); } } void Document::setName(const QString& newName) { if (name == newName) { return; } name = newName; emit si_nameChanged(); } void Document::setURL(const GUrl& newUrl) { assert(!isLoaded() || !isStateLocked()); if (url == newUrl) { return; } url = newUrl; emit si_urlChanged(); } bool Document::checkConstraints(const Document::Constraints& c) const { if (c.stateLocked != TriState_Unknown) { if (c.stateLocked == TriState_No && isStateLocked()) { return false; } if (c.stateLocked == TriState_Yes && !isStateLocked()) { return false; } } if (!c.formats.isEmpty()) { bool found = false; foreach(DocumentFormatId f, c.formats) { if (df->getFormatId() == f) { found = true; break; } } if (!found) { return false; } } foreach(DocumentModLock l, c.notAllowedStateLocks) { if (modLocks[l]!=NULL) { return false; } } if (!c.objectTypeToAdd.isNull() && !df->isObjectOpSupported(this, DocumentFormat::DocObjectOp_Add, c.objectTypeToAdd)) { return false; } return true; } void Document::setUserModLock(bool v) { if (hasUserModLock() == v) { return; } if (v) { StateLock* sl = new StateLock(tr("Locked by user")); modLocks[DocumentModLock_USER] = sl; lockState(sl); } else { StateLock* sl = modLocks[DocumentModLock_USER]; modLocks[DocumentModLock_USER] = NULL; unlockState(sl); delete sl; } //hack: readonly settings are stored in project, so if document is in project -> mark project as modified if (getParentStateLockItem()!=NULL) { getParentStateLockItem()->setModified(true); } } bool Document::unload() { assert(isLoaded()); bool liveLocked = hasLocks(StateLockableTreeFlags_ItemAndChildren, StateLockFlag_LiveLock); if (liveLocked) { assert(0); return false; } loadStateChangeMode = true; int nDocLocks = 0; qCount(modLocks, modLocks + DocumentModLock_NUM_LOCKS, NULL_LOCK, nDocLocks); nDocLocks = DocumentModLock_NUM_LOCKS - nDocLocks; int totalLocks = locks.count(); if (nDocLocks!=totalLocks) { assert(0); return false; } QList unloadedInfo; foreach(GObject* obj, objects) { //Note: foreach copies object list unloadedInfo.append(UnloadedObjectInfo(obj)); _removeObject(obj); } addUnloadedObjects(unloadedInfo); StateLock* fl = modLocks[DocumentModLock_FORMAT_AS_INSTANCE]; if (fl != NULL) { unlockState(fl); modLocks[DocumentModLock_FORMAT_AS_INSTANCE] = NULL; } setLoaded(false); loadStateChangeMode = false; return true; } void Document::setModified(bool modified, const QString& modType) { if (loadStateChangeMode && modified && modType == StateLockModType_AddChild) { //ignore modification events during loading/unloading return; } StateLockableTreeItem::setModified(modified, modType); } bool Document::isModificationAllowed(const QString& modType) { bool ok = loadStateChangeMode && modType == StateLockModType_AddChild; ok = ok || StateLockableTreeItem::isModificationAllowed(modType); return ok; } void Document::setGHints(GHints* newHints) { assert(newHints!=NULL); //gobjects in document keep states in parent document map -> preserve gobject hints QList objectHints; for (int i = 0; i < objects.size(); i++) { GObject* obj = objects[i]; objectHints.append(obj->getGHintsMap()); } delete ctxState; ctxState = newHints; for (int i = 0;i < objects.size(); i++) { const QVariantMap& hints = objectHints[i]; GObject* obj = objects[i]; obj->getGHints()->setMap(hints); } } void Document::addUnloadedObjects(const QList& info) { foreach(const UnloadedObjectInfo& oi, info) { UnloadedObject* obj = new UnloadedObject(oi); _addObjectToHierarchy(obj); assert(obj->getDocument() == this); emit si_objectAdded(obj); } } QVariantMap Document::getGHintsMap() const { return ctxState->getMap(); } void Document::setupToEngine(QScriptEngine *engine) { qScriptRegisterMetaType(engine, toScriptValue, fromScriptValue); }; QScriptValue Document::toScriptValue(QScriptEngine *engine, Document* const &in) { return engine->newQObject(in); }; void Document::fromScriptValue(const QScriptValue &object, Document* &out) { out = qobject_cast(object.toQObject()); }; void Document::setLastUpdateTime() { QFileInfo fi(getURLString()); if (fi.exists()) { lastUpdateTime = fi.lastModified(); } } void Document::propagateModLocks(Document* doc) const { for (int i = 0; i < DocumentModLock_NUM_LOCKS; i++) { StateLock* lock = modLocks[i]; if (lock != NULL && doc->modLocks[i] != NULL) { StateLock* newLock = new StateLock(lock->getUserDesc(), lock->getFlags()); doc->modLocks[i] = newLock; doc->lockState(newLock); } } } }//namespace ugene-1.9.8/src/corelibs/U2Core/src/models/GObject.h0000644000175000017500000000766511651544332020564 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_GOBJECT_H_ #define _U2_GOBJECT_H_ #include #include "StateLockableDataModel.h" #include "GObjectReference.h" #include #include /** List of object relations */ #define GObjectHint_RelatedObjects "gobject-hint-related-objects" /** The same, but used in previous versions */ #define GObjectHint_RelatedObjectsLegacy "related_objs" /** Last used object name. Used in case if object is renamed but name is not saved to file */ #define GObjectHint_LastUsedObjectName "gobject-hint-last-used-object-name" /** When object is added to project, in-project-id is assigned that is unique per project */ #define GObjectHint_InProjectId "gobject-hint-in-project-id" namespace U2 { class Document; class GObjectConstraints; class GHints; class U2CORE_EXPORT GObject : public StateLockableTreeItem { friend class DocumentFormat; friend class Document; Q_OBJECT public: GObject(QString _type, const QString& _name, const QVariantMap& hints = QVariantMap()); virtual ~GObject(); virtual Document* getDocument() const; const QString& getGObjectName() const {return name;} virtual void setGObjectName(const QString& newName); GObjectType getGObjectType() const {return type;} virtual GObject* clone() const = 0; virtual bool checkConstraints(const GObjectConstraints* c) const {Q_UNUSED(c); return true;} GHints* getGHints() const {return hints;} QVariantMap getGHintsMap() const; void setGHints(GHints*); QList getObjectRelations() const; void setObjectRelations(const QList& obj); QList findRelatedObjectsByRole(const QString& role) const; QList findRelatedObjectsByType(const GObjectType& objType) const; void addObjectRelation(const GObjectRelation& ref); void addObjectRelation(const GObject* obj, const QString& role); void removeObjectRelation(const GObjectRelation& ref); void updateRefInRelations(const GObjectReference& oldRef, const GObjectReference& newRef); bool hasObjectRelation(const GObject* obj, const QString& role) const; bool hasObjectRelation(const GObjectRelation& r) const; QHash< QString, QString > getIndexInfo() const {return indexInfo;} void setIndexInfo( const QHash& ii) {indexInfo = ii;} bool isUnloaded() const; signals: void si_nameChanged(const QString& oldName); private: GObjectType type; QString name; GHints* hints; QHash indexInfo; }; class GObjectConstraints : public QObject { Q_OBJECT public: GObjectConstraints(const GObjectType& t, QObject* parent = NULL) : QObject(parent), objectType(t){} const GObjectType objectType; }; class U2CORE_EXPORT GObjectMimeData : public QMimeData { Q_OBJECT public: static const QString MIME_TYPE; GObjectMimeData(GObject* obj) : objPtr(obj){}; ~GObjectMimeData(); QPointer objPtr; }; }//namespace #endif ugene-1.9.8/src/corelibs/U2Core/src/datatype/0000755000175000017500000000000011651544331017407 5ustar ilyailyaugene-1.9.8/src/corelibs/U2Core/src/datatype/MAlignment.cpp0000644000175000017500000005532311651544331022156 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include #include "MAlignment.h" #include #include namespace U2 { ////////////////////////////////////////////////////////////////////////// // MAlignmentRow QByteArray MAlignmentRow::toByteArray(int length) const { assert(length >= getCoreEnd()); if (offset == 0 && sequence.length() == length) { return sequence; } QByteArray result; result.resize(length); char* data = result.data(); if (offset > 0) { qMemSet(data, MAlignment_GapChar, offset); } int seqLen = sequence.length(); qMemCopy(data + offset, sequence.constData(), seqLen); int readyLen = offset + seqLen; if (readyLen < length) { int dlen = length - readyLen; qMemSet(data + readyLen, MAlignment_GapChar, dlen); } return result; } void MAlignmentRow::setSequence(const QByteArray& _sequence, int _offset) { offset = _offset; sequence = _sequence; } int MAlignmentRow::getFirstNonGapIdx() const { int nonGapIdx = TextUtils::firstIndexOfNotEqualChar(sequence.constData(), sequence.size(), MAlignment_GapChar); if (nonGapIdx == -1) { return -1; } return offset + nonGapIdx; } int MAlignmentRow::getLastNonGapIdx() const { int nonGapIdx = TextUtils::lastIndexOfNotEqualChar(sequence.constData(), sequence.size(), MAlignment_GapChar); if (nonGapIdx == -1) { return -1; } return offset + nonGapIdx; } void MAlignmentRow::crop(MAlignmentRow* row, int startPos, int len) { int coreEnd = row->getCoreEnd(); if (startPos + len <= row->offset || startPos >= coreEnd) { //the result is empty row row->offset = 0; row->sequence.clear(); } else if (startPos <= row->offset && startPos + len >= coreEnd) { //offset changes, sequence remains row->offset -= startPos; } else if (startPos <= row->offset) { // the result is a prefix of the sequence int prefixLen = len - (row->offset - startPos); assert(prefixLen > 0 && prefixLen < row->sequence.length()); row->offset -= startPos; row->sequence = row->sequence.mid(0, prefixLen); } else if (startPos > row->offset && startPos + len < coreEnd) { // the result is a middle of the sequence int seqStartPos = startPos - row->offset; row->offset = 0; row->sequence = row->sequence.mid(seqStartPos, len); } else { // the result is a suffix of the sequence assert(startPos > row->offset && startPos + len >= coreEnd); int suffixStart = startPos - row->offset; int suffixLen = row->sequence.length() - suffixStart; row->offset = 0; row->sequence = row->sequence.mid(suffixStart, suffixLen); } } void MAlignmentRow::crop(int startPos, int length) { crop(this, startPos, length); } MAlignmentRow MAlignmentRow::mid(int startPos, int length) const { MAlignmentRow res = *this; crop(&res, startPos, length); return res; } void MAlignmentRow::append(const MAlignmentRow& anotherRow, int lengthBefore) { assert(lengthBefore >= getCoreEnd()); if (anotherRow.getCoreLength() == 0) { return; } int coreLenBefore = getCoreLength(); int coreEndBefore = getCoreEnd(); int sizeAfter = lengthBefore + anotherRow.offset + anotherRow.sequence.size() - offset; sequence.resize(sizeAfter); int gapSpaceLen = (lengthBefore - coreEndBefore) + anotherRow.offset; if (gapSpaceLen > 0) { qMemSet(sequence.data() + coreLenBefore, MAlignment_GapChar, gapSpaceLen); } qMemCopy(sequence.data() + coreLenBefore + gapSpaceLen, anotherRow.sequence.constData(), anotherRow.sequence.size()); } bool MAlignmentRow::minimize() { int leftMargin = getFirstNonGapIdx() - offset; int rightMargin = getLastNonGapIdx() + 1 - offset; bool shrinkLeft = leftMargin > 0; bool shrinkRight = rightMargin < sequence.size(); if (!shrinkLeft && !shrinkRight) { return false; } if (shrinkLeft && shrinkRight) { offset+=leftMargin; sequence = sequence.mid(leftMargin, rightMargin - leftMargin); } else if (shrinkLeft) { offset+=leftMargin; sequence = sequence.mid(leftMargin); } else { assert(shrinkRight); sequence = sequence.mid(0, rightMargin); } return true; } bool MAlignmentRow::simplify() { bool changed = false; QBitArray gapMap(256); gapMap[MAlignment_GapChar] = true; int newLen = TextUtils::remove(sequence.data(), sequence.length(), sequence.data(), gapMap); if (newLen != sequence.length()) { sequence.resize(newLen); changed = true; } changed = changed || offset > 0; offset = 0; return changed; } void MAlignmentRow::insertChar(int pos, char c) { int coreEnd = getCoreEnd(); if (pos > offset && pos < coreEnd) { //insert inside of the sequence int seqInsertPos = pos - offset; sequence.insert(seqInsertPos, c); } else if ( c != MAlignment_GapChar) { if (pos >= coreEnd) { //expand sequence right int oldSize = sequence.size(); int newSize = pos - offset; int dSize = newSize - oldSize; sequence.resize(newSize); qMemSet(sequence.data() + oldSize, MAlignment_GapChar, dSize - 1); sequence[newSize-1] = c; } else { //expand sequence left assert(pos <= offset); int oldSize = sequence.size(); int newSize = coreEnd - pos + 1; int dSize = newSize - oldSize; sequence.resize(newSize); memmove(sequence.data() + dSize, sequence.constData(), dSize); qMemSet(sequence.data(), MAlignment_GapChar, dSize); sequence[0] = c; offset = pos; } } } void MAlignmentRow::insertChars(int pos, char c, int count) { int coreEnd = getCoreEnd(); if (pos >= offset && pos < coreEnd) { //insert inside of the sequence int seqInsertPos = pos - offset; int suffixLen = sequence.size() - seqInsertPos; sequence.resize(sequence.size() + count); memmove(sequence.data() + pos + count, sequence.constData() + pos, suffixLen); qMemSet(sequence.data() + pos, c, count); } else if ( c != MAlignment_GapChar) { if (pos >= coreEnd) { //expand sequence right int oldSize = sequence.size(); int newSize = pos - offset + count; int dSize = newSize - oldSize; sequence.resize(newSize); qMemSet(sequence.data() + oldSize, MAlignment_GapChar, dSize - count); qMemSet(sequence.data() + oldSize + dSize - count, c, count); } else { //expand sequence left assert(pos <= offset); int oldSize = sequence.size(); int newSize = coreEnd - pos + count; int dSize = newSize - oldSize; sequence.resize(newSize); memmove(sequence.data() + dSize, sequence.constData(), dSize); qMemSet(sequence.data(), c, count); qMemSet(sequence.data() + count, MAlignment_GapChar, dSize - count); offset = pos; } } else if (pos >= coreEnd) { int oldSize = sequence.size(); int newSize = pos - offset + count; int dSize = newSize - oldSize; sequence.resize(newSize); qMemSet(sequence.data() + oldSize, MAlignment_GapChar, dSize - count); qMemSet(sequence.data() + oldSize + dSize - count, c, count); } else { // pos < offset offset+=count; } } void MAlignmentRow::insertChars(int pos, const char* str, int len) { int coreEnd = getCoreEnd(); if (pos > offset && pos < coreEnd) { //insert inside of the sequence int seqInsertPos = pos - offset; int suffixLen = sequence.size() - seqInsertPos; sequence.resize(sequence.size() + len); memmove(sequence.data() + pos + len, sequence.constData() + pos, suffixLen); qMemCopy(sequence.data() + pos, str, len); } else if (pos >= coreEnd) { //expand sequence right int oldSize = sequence.size(); int newSize = pos - offset + len; int dSize = newSize - oldSize; sequence.resize(newSize); qMemSet(sequence.data() + oldSize, MAlignment_GapChar, dSize - len); qMemCopy(sequence.data() + oldSize + dSize - len, str, len); } else { //expand sequence left assert(pos <= offset); int oldSize = sequence.size(); int newSize = coreEnd - pos + len; int dSize = newSize - oldSize; sequence.resize(newSize); memmove(sequence.data() + dSize, sequence.constData(), dSize); qMemCopy(sequence.data(), str, len); qMemSet(sequence.data() + len, MAlignment_GapChar, dSize - len); offset = pos; } } // Removes up to n characters starting from the specified position void MAlignmentRow::removeChars(int pos, int n) { int coreEnd = getCoreEnd(); assert(pos >=0 && n>=0 && pos + n <= coreEnd); if (pos >= coreEnd) { //out of the sequence range -> nothing to do //empty } else if (pos + n < offset) { // before the sequence -> reduce offset offset-=n; } else if (pos < offset) { //left clip offset = 0; int dLen = n - offset; sequence = sequence.mid(dLen); } else if (n < sequence.length()) { //mid clip int startClip = pos - offset; sequence = sequence.remove(startClip, n); QByteArray gaps(n, '-'); //gaps.fill('-'); sequence.append(gaps); } else { //right clip assert(pos + n >= coreEnd); int newLen = pos - offset; sequence = sequence.mid(0, newLen); } } void MAlignmentRow::removeChars(const QList& _positions) { QList positions = _positions; qSort(positions); bool sequenceChanged = false; QBitArray removedMap(256); removedMap[0] = true; for (int i = positions.size(); --i>=0; ) { int pos = positions.at(i); if (pos >= getCoreEnd()) { continue;; } if (pos < getCoreStart()) { offset-=(i + 1); break; } sequenceChanged = true; sequence[pos - offset] = 0; } if (sequenceChanged) { int newLen = TextUtils::remove(sequence.data(), sequence.length(), removedMap); assert(newLen < sequence.length()); sequence.resize(newLen); } } void MAlignmentRow::setName(const QString& newName) { assert(!newName.isEmpty()); name = newName; } bool MAlignmentRow::operator==(const MAlignmentRow& row) const { if (row.name != this->name) { return false; } if (offset == row.offset && sequence == row.sequence) { return true; } int ngs1 = getFirstNonGapIdx(); int ngs2 = row.getFirstNonGapIdx(); if (ngs1 != ngs2) { return false; } int nge1 = getLastNonGapIdx(); int nge2 = row.getLastNonGapIdx(); if (nge1 != nge2) { return false; } bool equal = true; for (int i = ngs1 + 1; i < nge1 && equal; i++) { char c1 = chatAt(i); char c2 = row.chatAt(i); equal = c1 == c2; } return equal; } void MAlignmentRow::setQuality( const DNAQuality& quality ) { assert(quality.qualCodes.length() == sequence.length()); if (quality.qualCodes.length() == sequence.length()) { dnaQuality = quality; } } ////////////////////////////////////////////////////////////////////////// // MAlignment impl //helper class to call MAlignment state check class MAStateCheck { public: MAStateCheck(const MAlignment* _ma) : ma(_ma) {} ~MAStateCheck() { #ifdef _DEBUG ma->check(); #endif } const MAlignment* ma; }; MAlignment::MAlignment(const QString& _name, DNAAlphabet* al, const QList& r) : alphabet(al), rows(r) { MAStateCheck check(this); assert(al==NULL || !_name.isEmpty()); //if not default constructor -> name must be provided setName(_name ); length = 0; for (int i=0, n = rows.size(); i < n; i++) { const MAlignmentRow& r = rows.at(i); length = qMax(length, r.getCoreEnd()); } } bool MAlignment::trim() { MAStateCheck check(this); int firstNonGap = length - 1; int lastNonGap = 0; for (int i=0, n = rows.size(); i < n; i++) { const MAlignmentRow& r = rows.at(i); int firstRowNonGap = r.getFirstNonGapIdx(); if (firstRowNonGap == -1) { continue; } int lastRowNonGap = r.getLastNonGapIdx(); assert(lastRowNonGap!=-1); firstNonGap = qMin(firstNonGap, firstRowNonGap); lastNonGap = qMax(lastNonGap, lastRowNonGap); } if (firstNonGap == 0 && lastNonGap == length - 1) { return false; //nothing to trim } int resultLen = lastNonGap - firstNonGap + 1; for (int i=0, n = rows.size(); i < n; i++) { MAlignmentRow& r = rows[i]; //r.crop(firstNonGap + 1, resultLen); r.crop(firstNonGap, resultLen); } length = resultLen; return true; } bool MAlignment::simplify() { MAStateCheck check(this); int newLen = 0; bool changed = false; for (int i=0, n = rows.size(); i < n; i++) { MAlignmentRow& r = rows[i]; changed = r.simplify() || changed; newLen = qMax(newLen, r.getCoreEnd()); } if (!changed) { assert(length == newLen); return false; } length = newLen; return true; } bool MAlignment::hasGaps() const { for (int i=0, n = rows.size(); i < n; i++) { const MAlignmentRow& row = rows.at(i); if (row.getCoreStart() > 0 || row.getCoreEnd() < length) { return true; } if (row.getFirstNonGapIdx() != row.getCoreStart()) { return true; } if (row.getLastNonGapIdx() != row.getCoreEnd() - 1) { return true; } } return false; } void MAlignment::clear() { MAStateCheck check(this); rows.clear(); length = 0; } MAlignment MAlignment::mid(int start, int len) const { assert(start >=0 && start + len <= length); MAlignment res(getName(), alphabet); MAStateCheck check(&res); foreach(const MAlignmentRow& r, rows) { MAlignmentRow mRow = r.mid(start, len); res.rows.append(mRow); } res.length = len; return res; } MAlignment& MAlignment::operator+=(const MAlignment& ma) { MAStateCheck check(this); assert(ma.alphabet == alphabet); int nSeq = getNumRows(); assert(ma.getNumRows() == nSeq); for (int i=0; i < nSeq; i++) { MAlignmentRow& myRow = rows[i]; const MAlignmentRow& anotherRow = ma.rows.at(i); myRow.append(anotherRow, length); } length += ma.length; return *this; } int MAlignment::estimateMemorySize() const { int result = info.size() * 20; //approximate info size estimation foreach(const MAlignmentRow& r, rows) { result += r.getCoreLength() + getName().length() * 2 + 12; //+12 -> overhead for byte array } return result; } bool MAlignment::crop(const U2Region& range, const QSet& seqNames ){ MAStateCheck check(this); QList newList, oldList = rows; foreach(const MAlignmentRow& row, rows){ const QString& rowName = row.getName(); if (seqNames.contains(rowName)){ MAlignmentRow newRow = row.mid(range.startPos, range.length); newList.append(newRow); } } //TODO: is modified? rows = newList; length = range.length; return true; } bool MAlignment::operator!=( const MAlignment& other ) const { return length!=other.length || alphabet != other.alphabet || rows != other.rows; } void MAlignment::addRow(const MAlignmentRow& row, int rowIndex) { MAStateCheck check(this); length = qMax(row.getCoreEnd(), length); int idx = rowIndex == -1 ? getNumRows() : qBound(0, rowIndex, getNumRows()); rows.insert(idx, row); } void MAlignment::removeRow(int rowIndex) { MAStateCheck check(this); rows.removeAt(rowIndex); if (rows.isEmpty()) { length = 0; } } void MAlignment::insertChar(int row, int pos, char c) { assert(alphabet->contains(c)); assert(row < getNumRows() && row >=0 ); assert(pos < length && pos >=0); MAStateCheck check(this); MAlignmentRow& r = rows[row]; r.insertChar(pos, c); length = qMax(length, r.getCoreEnd()); } void MAlignment::insertChars(int row, int pos, char c, int count) { assert(alphabet->contains(c)); assert(row < getNumRows() && row >=0 ); assert(pos <= length && pos >=0); MAStateCheck check(this); MAlignmentRow& r = rows[row]; r.insertChars(pos, c, count); length = qMax(length, r.getCoreEnd()); } void MAlignment::appendChars(int row, const char* str, int len) { const MAlignmentRow& r = getRow(row); insertChars(row, r.getCoreEnd(), str, len); } void MAlignment::insertChars(int row, int pos, const char* str, int len) { assert(row < getNumRows() && row >=0 ); assert(pos <= length && pos >=0); MAStateCheck check(this); MAlignmentRow& r = rows[row]; r.insertChars(pos, str, len); length = qMax(length, r.getCoreEnd()); } int MAlignment::calculateMinLength() const { int res = 0; foreach(const MAlignmentRow& row, rows) { res = qMax(row.getLastNonGapIdx() + 1, res); } return res; } void MAlignment::removeChars(int row, int pos, int n) { assert(row >= 0 && row < getNumRows()); assert(pos >= 0 && pos + n <= length && n > 0 && n > 0); MAStateCheck check(this); MAlignmentRow& r = rows[row]; bool lengthHolder = length == r.getCoreEnd(); r.removeChars(pos, n); if (lengthHolder) { length = qMax(length - n, calculateMinLength()); } } // Removes all columns from the row void MAlignment::removeChars(int row, const QList& columns) { int n = columns.length(); assert(row >=0 && row < getNumRows()); assert(n > 0); MAStateCheck check(this); MAlignmentRow& r = rows[row]; bool lengthHolder = length == r.getCoreEnd(); r.removeChars(columns); if (lengthHolder) { length = qMax(length - n, calculateMinLength()); } } void MAlignment::removeRegion(int startPos, int startRow, int nBases, int nRows, bool removeEmptyRows) { assert(startPos >= 0 && startPos + nBases <= length && nBases > 0); assert(startRow >= 0 && startRow + nRows <= getNumRows() && nRows > 0); MAStateCheck check(this); bool lengthHolder = false; for (int i = startRow + nRows; --i >= startRow;) { MAlignmentRow& r = rows[i]; lengthHolder = lengthHolder || length == r.getCoreEnd(); r.removeChars(startPos, nBases); if (removeEmptyRows && r.getCoreLength() == 0) { rows.removeAt(i); } } trim(); if (lengthHolder) { length = qMax(length - nBases, calculateMinLength()); } } void MAlignment::setLength(int newLength) { assert(newLength >=0); MAStateCheck check(this); if (newLength >= length) { length = newLength; return; } for (int i=0, n = getNumRows(); i < n; i++) { MAlignmentRow& row = rows[i]; row.crop(0, newLength); } length = newLength; } void MAlignment::renameRow(int row, const QString& name) { assert(row >= 0 && row < getNumRows()); assert(!name.isEmpty()); MAlignmentRow& r = rows[row]; r.setName(name); } void MAlignment::setAlphabet(DNAAlphabet* al) { assert(al!=NULL); alphabet = al; } void MAlignment::replaceChars(int row, char origChar, char resultChar) { assert(row >= 0 && row < getNumRows()); if (origChar == resultChar) { return; } MAlignmentRow& r = rows[row]; r.sequence.replace(origChar, resultChar); } void MAlignment::setRowSequence(int row, const QByteArray& sequence, int offset) { assert(row >= 0 && row < getNumRows()); MAStateCheck check(this); MAlignmentRow& r = rows[row]; r.setSequence(sequence, offset); length = qMax(length, r.getCoreEnd()); } void MAlignment::toUpperCase() { for (int i = 0, n = getNumRows(); i < n; i++) { MAlignmentRow& row = rows[i]; TextUtils::translate(TextUtils::UPPER_CASE_MAP, row.sequence.data(), row.sequence.length()); } } class CompareMARowsByName { public: CompareMARowsByName(bool _asc = true) : asc(_asc){} bool operator()(const MAlignmentRow& row1, const MAlignmentRow& row2) const { bool res = row1.getName() > row2.getName(); return asc ? !res : res; } bool asc; }; void MAlignment::sortRowsByName(bool asc) { MAStateCheck check(this); qStableSort(rows.begin(), rows.end(), CompareMARowsByName(asc)); } void MAlignment::moveRowsBlock( int startRow, int numRows, int delta ) { MAStateCheck check(this); // Assumption: numRows is rather big, delta is small (1~2) // It's more optimal to move abs(delta) of rows then the block itself int i = 0; int k = qAbs(delta); assert ( ( delta > 0 && startRow + numRows + delta - 1 < rows.length() ) || (delta < 0 && startRow + delta >= 0 && startRow + qAbs(delta) <= rows.length() ) ); QStack toMove; int fromRow = delta > 0 ? startRow + numRows : startRow + delta; while (i < k ) { MAlignmentRow row = rows.takeAt(fromRow); toMove.push(row); i++; } int toRow = delta > 0 ? startRow : startRow + numRows - k; while ( toMove.count() > 0 ) { MAlignmentRow row = toMove.pop(); rows.insert(toRow, row); } } QStringList MAlignment::getRowNames() const { QStringList rowNames; foreach(const MAlignmentRow& r, rows) { rowNames.append(r.getName()); } return rowNames; } void MAlignment::check() const { #ifdef DEBUG assert(getNumRows() != 0 || length == 0); for (int i = 0, n = getNumRows(); i < n; i++) { const MAlignmentRow& row = rows.at(i); assert(row.getCoreEnd() <= length); } #endif } static bool _registerMeta() { qRegisterMetaType("MAlignment"); return true; } bool MAlignment::registerMeta = _registerMeta(); }//namespace U2 ugene-1.9.8/src/corelibs/U2Core/src/datatype/BioStruct3D.cpp0000644000175000017500000002400311651544331022217 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "BioStruct3D.h" #include #include namespace U2 { /* class BioStruct3D */ QString BioStruct3D::MoleculeAnnotationTag("chain_info"); QString BioStruct3D::AlphaHelixAnnotationTag("alpha_helix"); QString BioStruct3D::BetaStrandAnnotationTag("beta_strand"); QString BioStruct3D::TurnAnnotationTag("turn"); QString BioStruct3D::ChainIdQualifierName("chain_id"); QString BioStruct3D::SecStructAnnotationTag("sec_struct"); QString BioStruct3D::SecStructTypeQualifierName("sec_struct_type"); BioStruct3D::BioStruct3D() : moleculeMap(), modelMap(), annotations(), secondaryStructures(), interMolecularBonds(), descr(), pdbId(), radius(0), rotationCenter(), transform() { transform.loadIdentity(); } BioStruct3D::BioStruct3D(const BioStruct3D &other) : moleculeMap(other.moleculeMap), modelMap(other.modelMap), annotations(other.annotations), secondaryStructures(other.secondaryStructures), interMolecularBonds(other.interMolecularBonds), descr(other.descr), pdbId(other.pdbId), radius(other.radius), rotationCenter(other.rotationCenter), transform(other.transform) { } void BioStruct3D::calcCenterAndMaxDistance() { Vector3D siteSum; Vector3D center; double dist; radius = 0.0; int numberOfAtoms = 0; // loop trough all atoms twice - once to get average center, then once to // find max distance from this center for (int i = 0; i < 2; ++i) { foreach (SharedMolecule molecule, moleculeMap) { foreach(Molecule3DModel model3d, molecule->models) { foreach (const AtomData* atom, model3d.atoms) { Vector3D site = atom->coord3d; if (i==0) { siteSum += atom->coord3d; ++numberOfAtoms; } else { dist = (site - center).length(); if (dist > radius){ radius = dist; } } } } } if (i == 0) { if (numberOfAtoms == 0) { algoLog.trace("Number of atoms is 0!"); } else { center = siteSum / numberOfAtoms; } } } algoLog.trace(QString("center: (%1,%2,%3)\n maxDistFromCenter: %4").arg(center.x).arg(center.y).arg(center.z).arg(radius) ); rotationCenter = center; } int BioStruct3D::getNumberOfAtoms() const { // get first coordinates set const AtomCoordSet& coordSet = modelMap.begin().value(); return coordSet.count(); } void BioStruct3D::generateAnnotations() { generateChainAnnotations(); generateSecStructureAnnotations(); } void BioStruct3D::generateChainAnnotations() { const char* molNameQualifier = "molecule_name"; //const char* pdbChainIdQualifier = "pdb_id"; QMap::iterator iter = moleculeMap.begin(); while (iter != moleculeMap.end()) { int length = iter.value()->residueMap.size(); SharedAnnotationData sd( new AnnotationData); sd->location->regions << U2Region(0,length); sd->name = BioStruct3D::MoleculeAnnotationTag; sd->qualifiers.append(U2Qualifier(ChainIdQualifierName, QString("%1").arg(iter.key()) )); sd->qualifiers.append(U2Qualifier(molNameQualifier, (*iter)->name)); (*iter)->annotations.append(sd); ++iter; } } int BioStruct3D::getNumberOfResidues() const { int numResidues = 0; foreach (SharedMolecule mol, moleculeMap) { numResidues += mol->residueMap.size(); } return numResidues; } const SharedAtom BioStruct3D::getAtomById( int atomIndex, int modelIndex ) const { if (modelMap.contains(modelIndex)) { const AtomCoordSet& coordSet = modelMap.value(modelIndex); if (coordSet.contains(atomIndex)) { return coordSet.value(atomIndex); } } return SharedAtom(NULL); } const SharedResidue BioStruct3D::getResidueById( int chainIndex, ResidueIndex residueIndex ) const { const SharedMolecule mol = moleculeMap.value(chainIndex); foreach (const ResidueIndex& id, mol->residueMap.keys() ){ if ( id.toInt() == residueIndex.toInt() ) { return mol->residueMap.value(id); } } return SharedResidue(NULL); } const QString BioStruct3D::getSecStructTypeName( SecondaryStructure::Type type ) { switch(type) { case SecondaryStructure::Type_AlphaHelix: return BioStruct3D::AlphaHelixAnnotationTag; case SecondaryStructure::Type_PiHelix: return "pi_helix"; case SecondaryStructure::Type_310Helix: return "310_helix"; case SecondaryStructure::Type_BetaStrand: return BioStruct3D::BetaStrandAnnotationTag; case SecondaryStructure::Type_BetaBridge: return "beta_bridge"; case SecondaryStructure::Type_Turn: return BioStruct3D::TurnAnnotationTag; case SecondaryStructure::Type_BendRegion: return "bend_region"; default: return QString("unknown"); } } void BioStruct3D::generateSecStructureAnnotations() { // TODO: issue 0000637 if (moleculeMap.isEmpty()) return; foreach (const SharedSecondaryStructure& struc, secondaryStructures) { SharedAnnotationData sd(NULL); int chainId = struc->chainIndex; assert(chainId != 0); int initResidueId = moleculeMap.value(chainId)->residueMap.constBegin().key().toInt(); sd = new AnnotationData; sd->name = BioStruct3D::SecStructAnnotationTag; U2Qualifier qual(SecStructTypeQualifierName, getSecStructTypeName(struc->type)); sd->qualifiers.append(qual); int numResidues = struc->endSequenceNumber - struc->startSequenceNumber + 1; int startIndex = struc->startSequenceNumber - initResidueId; U2Region chainRegion(startIndex, numResidues); sd->location->regions << chainRegion; Q_ASSERT(moleculeMap.contains(chainId)); moleculeMap[chainId]->annotations.append(sd); } } QByteArray BioStruct3D::getRawSequenceByChainId( int id ) const { QByteArray sequence(""); Q_ASSERT(moleculeMap.contains(id)); const SharedMolecule molecule = moleculeMap.value(id); foreach (const SharedResidue residue, molecule->residueMap) { QChar c = residue->acronym; sequence.append(c); } return sequence; } const QList BioStruct3D::getModelsNames() const { return modelMap.keys(); } const Molecule3DModel BioStruct3D::getModelByName(int moleculeId, int name) const { int index = modelMap.keys().indexOf(name); assert(index != -1 && "invalid model id"); return getModelByIndex(moleculeId, index); } const Molecule3DModel BioStruct3D::getModelByIndex(int moleculeId, int index) const { return moleculeMap[moleculeId]->models[index]; } /* class U2CORE_EXPORT BioStruct3DChainSelection */ BioStruct3DChainSelection::BioStruct3DChainSelection(const BioStruct3D &biostruct_) : biostruct(biostruct_), data(new BioStruct3DChainSelectionData()) {} BioStruct3DChainSelection::BioStruct3DChainSelection(const BioStruct3DChainSelection &other) : biostruct(other.biostruct), data(other.data) {} bool BioStruct3DChainSelection::inSelection(int chainId, int residueId) const { return data->selection.contains(chainId, residueId); } void BioStruct3DChainSelection::add(int chain, const U2Region ®ion) { int start = biostruct.moleculeMap[chain]->residueMap.begin().key().toInt(); for (int i = region.startPos; i < region.endPos(); ++i) { if (!data->selection.contains(chain, start + i)) { data->selection.insert(chain, start + i); } } } void BioStruct3DChainSelection::add(int chain, const QVector ®ions) { foreach (const U2Region ®ion, regions) { add(chain, region); } } void BioStruct3DChainSelection::remove(int chain, const U2Region ®ion) { int start = biostruct.moleculeMap[chain]->residueMap.begin().key().toInt(); for (int i = region.startPos; i < region.endPos(); ++i) { data->selection.remove(chain, start + i); } } void BioStruct3DChainSelection::remove(int chain, const QVector ®ions) { foreach (const U2Region ®ion, regions) { remove(chain, region); } } void BioStruct3DChainSelection::update(int chain, const U2Region &add, const U2Region &remove) { this->remove(chain, remove); this->add(chain, add); } void BioStruct3DChainSelection::update(int chain, const QVector &adds, const QVector &removes) { remove(chain, removes); add(chain, adds); } bool ResidueIndex::operator< ( const ResidueIndex& other ) const { if (order == other.order) { if (resId == other.resId) { return insCode < other.insCode; } else { return resId < other.resId; } } else { return order < other.order; } } bool ResidueIndex::operator==( const ResidueIndex& other ) const { return (other.insCode == insCode) && (other.resId == resId); } bool ResidueIndex::operator!=( const ResidueIndex& other ) const { return !(*this == other); } } // namespace U2 ugene-1.9.8/src/corelibs/U2Core/src/datatype/U2Region.cpp0000644000175000017500000001026211651544331021546 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include namespace U2 { QVector U2Region::join(QVector& regions) { QVector result = regions; qStableSort(result.begin(), result.end()); //sort by region start pos first for (int i = 0; i < result.size()-1;) { const U2Region& ri0 = result[i]; const U2Region& ri1 = result[i+1]; if (!ri0.intersects(ri1)) { i++; continue; } U2Region newRi = containingRegion(ri0, ri1); result[i] = newRi; result.remove(i+1); } return result; } void U2Region::bound(qint64 minPos, qint64 maxPos, QVector& regions) { for (int i = 0, n = regions.size(); i < n; i++) { U2Region& r = regions[i]; int start = qBound(minPos, r.startPos, maxPos); int end = qBound(minPos, r.endPos(), maxPos); r.startPos = start; r.length = end - start; } } void U2Region::mirror(qint64 mirrorPos, QVector& regions) { for (int i = 0, n = regions.size(); i < n; i++) { U2Region& r = regions[i]; assert(r.endPos() <= mirrorPos); r.startPos = mirrorPos - r.endPos(); } } void U2Region::divide(qint64 div, QVector& regions) { for (int i = 0, n = regions.size(); i < n; i++) { U2Region& r = regions[i]; r.startPos = r.startPos / div; } } void U2Region::multiply(qint64 mult, QVector& regions) { for (int i = 0, n = regions.size(); i < n; i++) { U2Region& r = regions[i]; r.startPos = r.startPos * mult; } } void U2Region::reverse(QVector& regions) { QVector old = regions; regions.clear(); foreach(const U2Region& r, old) { regions.prepend(r); } } void U2Region::shift(int offset, QVector& regions) { QVector res; for (int i = 0, n = regions.size(); i < n; i++) { U2Region& r = regions[i]; r.startPos += offset; } } int U2Region::findIntersectedRegion(const QVector& rs) const { for (int i = 0, n = rs.size(); i < n; i++) { const U2Region& r = rs[i]; if (intersects(r)) { return i; } } return -1; } int U2Region::findOverlappingRegion(const QVector& rs) const { for (int i = 0, n = rs.size(); i < n; i++) { const U2Region& r = rs[i]; if (r.contains(*this)) { return i; } } return -1; } void U2Region::removeAll(QVector& regionsToProcess, const QVector& regionsToRemove) { QVector result; foreach(const U2Region& pr, regionsToProcess) { if (regionsToRemove.indexOf(pr) == -1) { result.append(pr); } } regionsToProcess = result; } static bool _registerMeta() { qRegisterMetaType("U2Region"); qRegisterMetaTypeStreamOperators("U2::U2Region"); qRegisterMetaType >("QVector"); qRegisterMetaTypeStreamOperators< QVector >("QVector"); return true; } bool U2Region::registerMeta = _registerMeta(); QDataStream &operator<<(QDataStream &out, const U2Region &myObj) { out << myObj.startPos << myObj.length; return out; } QDataStream &operator>>(QDataStream &in, U2Region &myObj) { in >> myObj.startPos; in >> myObj.length; return in; } } //nsugene-1.9.8/src/corelibs/U2Core/src/datatype/DNAAlphabet.h0000644000175000017500000000674611651544331021640 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_DNA_ALPHABET_H_ #define _U2_DNA_ALPHABET_H_ #include #include #include namespace U2 { class U2CORE_EXPORT BaseDNAAlphabetIds : public QObject { public: // functions, because are used in static variable initialization: Text2SequenceWorker.cpp static const QString RAW(); static const QString NUCL_DNA_DEFAULT(); static const QString NUCL_DNA_EXTENDED(); static const QString NUCL_RNA_DEFAULT(); static const QString NUCL_RNA_EXTENDED(); static const QString AMINO_DEFAULT(); }; class U2CORE_EXPORT DNAAlphabet { public: DNAAlphabet(const QString& id, const QString& name, DNAAlphabetType t, const QBitArray& map, Qt::CaseSensitivity caseMode, char defSym); const QBitArray& getMap() const {return map;} const QString& getName() const {return name;} const QString& getId() const {return id;} bool contains(char c) const {return map.at(c);} bool containsAll(const char* str, int len) const; DNAAlphabetType getType() const {return type;} bool isCaseSensitive() const {return caseMode == Qt::CaseSensitive;} char getDefaultSymbol() const {return defSym;} bool isRaw() const {return type == DNAAlphabet_RAW;} bool isNucleic() const {return type == DNAAlphabet_NUCL;} bool isAmino() const {return type == DNAAlphabet_AMINO;} // returns sorted array of all chars used in alphabet // forceBothCases == true : even case-insensitive alphabet will return both cases // forceBothCases == false: case-sensitivity in result depends on alphabets case-sensitivity QByteArray getAlphabetChars(bool forceBothCases = false) const; int getNumAlphabetChars() const {return numChars;} static DNAAlphabet* deriveCommonAlphabet(DNAAlphabet* al1, DNAAlphabet* al2); private: QString id; QString name; DNAAlphabetType type; QBitArray map; Qt::CaseSensitivity caseMode; char defSym; int numChars; }; class U2CORE_EXPORT DNAAlphabetRegistry : public QObject { public: virtual bool registerAlphabet(DNAAlphabet* a) = 0; virtual void unregisterAlphabet(DNAAlphabet* a) = 0; virtual DNAAlphabet* findById(const QString id) const = 0; virtual QList getRegisteredAlphabets() const = 0; virtual DNAAlphabet* findAlphabet(const QByteArray& seq) const = 0; virtual QList findAlphabets(const QByteArray& seq) const = 0; virtual QList findAlphabets(const QByteArray& seq, const QVector& regionsToProcess, bool onlyOne) const = 0; }; }//namespace #endif ugene-1.9.8/src/corelibs/U2Core/src/datatype/BaseAlphabets.cpp0000644000175000017500000001015111651544331022607 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "DNAAlphabetRegistryImpl.h" #include namespace U2 { static void fillBitArray(QBitArray& map, const char* str, Qt::CaseSensitivity caseMode) { QByteArray line(str); foreach(char c, line) { if (caseMode == Qt::CaseSensitive) { map[(uchar)c]=true; } else { char lc = TextUtils::UPPER_CASE_MAP.at((uchar)c); char uc = TextUtils::LOWER_CASE_MAP.at((uchar)c); map[(uchar)lc] = true; map[(uchar)uc] = true; } } } #define CASE_OFFSET ('a'-'A') static void fill(QBitArray& map, const char *s, Qt::CaseSensitivity caseMode) { for(const char* i =s; *i!=0; i++) { char c = *i; map[int((uchar)c)] = true; if (caseMode == Qt::CaseInsensitive && c >='A' && c<='Z') { map[int((uchar)c) + CASE_OFFSET] = true; } } } #define REG(a) \ map[int((uchar)a)] = true; \ if (caseMode == DNAAlphabet::CaseInsensitive) { \ map[int((uchar)a) + CASE_OFFSET] = true; \ } void DNAAlphabetRegistryImpl::initBaseAlphabets() { //raw text { QBitArray map(256, true); DNAAlphabet* a = new DNAAlphabet(BaseDNAAlphabetIds::RAW(), tr("All symbols"), DNAAlphabet_RAW, map, Qt::CaseSensitive, '\0'); registerAlphabet(a); } //default DNA nucl { QBitArray map(256, false); fill(map, "ACGTN-", Qt::CaseInsensitive); DNAAlphabet* a = new DNAAlphabet(BaseDNAAlphabetIds::NUCL_DNA_DEFAULT(), tr("Standard DNA"), DNAAlphabet_NUCL, map, Qt::CaseInsensitive, 'N'); registerAlphabet(a); } //default RNA nucl { QBitArray map(256, false); fill(map, "ACGUN-", Qt::CaseInsensitive); DNAAlphabet* a = new DNAAlphabet(BaseDNAAlphabetIds::NUCL_RNA_DEFAULT(), tr("Standard RNA"), DNAAlphabet_NUCL, map, Qt::CaseInsensitive, 'N'); registerAlphabet(a); } //extended NUCL DNA { QBitArray map(256, false); fill(map, "ACGTMRWSYKVHDBNX-", Qt::CaseInsensitive); //X == N DNAAlphabet* a = new DNAAlphabet(BaseDNAAlphabetIds::NUCL_DNA_EXTENDED(), tr("Extended DNA"), DNAAlphabet_NUCL, map, Qt::CaseInsensitive, 'N'); registerAlphabet(a); } //extended NUCL RNA { QBitArray map(256, false); fill(map, "ACGUMRWSYKVHDBNX-", Qt::CaseInsensitive); //X == N DNAAlphabet* a = new DNAAlphabet(BaseDNAAlphabetIds::NUCL_RNA_EXTENDED(), tr("Extended RNA"), DNAAlphabet_NUCL, map, Qt::CaseInsensitive, 'N'); registerAlphabet(a); } //default amino { QBitArray map(256, false); // // http://www.jbc.org/cgi/reprint/243/13/3557.pdf IUPAC-IUB Commission on Biochemical Nomenclature fillBitArray(map, "ABCDEFGHIKLMNPQRSTVWXYZ*X-", Qt::CaseInsensitive); // http://en.wikipedia.org/wiki/Genetic_code#Variations_to_the_standard_genetic_code //O = pyrrolysine, U = selenocysteine fillBitArray(map, "OU", Qt::CaseInsensitive); DNAAlphabet* a = new DNAAlphabet(BaseDNAAlphabetIds::AMINO_DEFAULT(), tr("Standard amino"), DNAAlphabet_AMINO, map, Qt::CaseInsensitive, 'X'); registerAlphabet(a); } } }//namespace ugene-1.9.8/src/corelibs/U2Core/src/datatype/PFMatrix.cpp0000644000175000017500000001403411651544331021607 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "PFMatrix.h" #include "DIProperties.h" #include "U2Core/DNAAlphabet.h" namespace U2 { JasparInfo::JasparInfo(): properties(QMap()) { } JasparInfo::JasparInfo(const QMap& props): properties(props) { } JasparInfo::JasparInfo(const QString& line) { QStringList parsedData = line.split(";"); QString idData = parsedData.first(); QStringList base = idData.split(QRegExp("\\s")); QString id = base[0]; properties.insert(QString("id"), id); QString name = base[2]; properties.insert(QString("name"), name); base.removeFirst(); base.removeFirst(); base.removeFirst(); QString clss = base.join(" "); properties.insert(QString("class"), clss); for (int i = 1, n = parsedData.length(); i < n; i++) { QString curr = parsedData[i]; int left = curr.indexOf("\""); QString propName = curr.left(left).trimmed(); int right = curr.indexOf("\"", left + 1); QString propValue = curr.mid(left + 1, right - left - 1); properties.insert(propName, propValue); } } QString JasparInfo::getProperty(const QString &name) const { return properties.value(name); } QMap JasparInfo::getProperties() const { return properties; } PFMatrix::PFMatrix(const MAlignment &align, PFMatrixType _type): type(_type) { assert(!align.hasGaps()); length = (type == PFM_MONONUCLEOTIDE) ? align.getLength() : align.getLength() - 1; assert (length > 0); int size = (type == PFM_MONONUCLEOTIDE) ? 4 : 16; data.resize(size * length); qMemSet(data.data(), 0, size*length*sizeof(int)); if (type == PFM_MONONUCLEOTIDE) { for (int i = 0, n = align.getNumRows(); i < n; i++) { const QByteArray row = align.getRow(i).toByteArray(length); for (int j = 0; j < length; j++) { char curr = row[j]; data[DiProperty::index(curr) * length + j]++; } } } else { for (int i = 0, n = align.getNumRows(); i < n; i++) { const QByteArray row = align.getRow(i).toByteArray(length + 1); for (int j = 0; j < length; j++) { char curr = row[j]; char next = row[j+1]; data[DiProperty::index(curr, next) * length + j]++; } } } } PFMatrix::PFMatrix(const QList &seq, PFMatrixType _type) : type(_type) { assert(seq.length() > 0); length = seq[0]->length(); for (int i = 0, n = seq.length(); i < n; i++) { assert (seq[i]->alphabet->getType() == DNAAlphabet_NUCL); assert (length == seq[i]->length()); } int size = (type == PFM_MONONUCLEOTIDE) ? 4 : 16; length = (type == PFM_MONONUCLEOTIDE) ? seq[0]->length() : seq[0]->length() - 1; data.resize(size * length); qMemSet(data.data(), 0, size*length*sizeof(int)); if (type == PFM_MONONUCLEOTIDE) { for (int i = 0, n = seq.size(); i < n; i++) { const QByteArray& row = seq[i]->seq; for (int j = 0; j < length; j++) { char curr = row[j]; data[DiProperty::index(curr) * length + j]++; } } } else { for (int i = 0, n = seq.size(); i < n; i++) { const QByteArray& row = seq[i]->seq; for (int j = 0; j < length; j++) { char curr = row[j]; char next = row[j+1]; data[DiProperty::index(curr, next) * length + j]++; } } } } PFMatrix::PFMatrix(const QVarLengthArray& _data, const PFMatrixType _type): type(_type) { assert (_data.size() % 4 == 0); if (_type == PFM_DINUCLEOTIDE) { assert (_data.size() % 16 == 0); } data = _data; length = (_type == PFM_MONONUCLEOTIDE) ? (_data.size() / 4) : (_data.size() / 16); } PFMatrix PFMatrix::convertDi2Mono(const PFMatrix& source) { assert (source.getType() == PFM_DINUCLEOTIDE); int size = 4; int len = source.getLength(); QVarLengthArray matrix(size*(len+1)); qMemSet(matrix.data(), 0, size*(len+1)*sizeof(int)); for (int i = 0; i < size; i++) { for (int j = 0; j < len; j++) { for (int k = 0; k < 4; k++) { matrix[i*(len+1) + j] += source.data[source.index((i << 2) + k, j)]; } } for (int k = 0; k < 4; k++) { matrix[i*(len+1) + len] += source.data[source.index((k << 2) + i, len - 1)]; } } return PFMatrix(matrix, PFM_MONONUCLEOTIDE); } int PFMatrix::index(int row, int column) const { assert (row >= 0); assert (row < 16); if (type == PFM_MONONUCLEOTIDE) assert (row < 4); assert (column >= 0); assert (column < length); return row * length + column; } PFMatrixType PFMatrix::getType() const { return type; } int PFMatrix::getLength() const { return length; } int PFMatrix::getValue(int row, int column) const { int pos = index(row, column); return data[pos]; } void PFMatrix::setInfo(const U2::JasparInfo &in){ info = in; } QString PFMatrix::getProperty(const QString &propertyName) const { return info.getProperty(propertyName); } QMap PFMatrix::getProperties() const { return info.getProperties(); } }ugene-1.9.8/src/corelibs/U2Core/src/datatype/MAlignmentInfo.h0000644000175000017500000000576611651544331022445 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_MALIGNMENT_INFO_H_ #define _U2_MALIGNMENT_INFO_H_ #include #include namespace U2 { class U2CORE_EXPORT MAlignmentInfo { public: static const QString NAME; static const QString ACCESSION; static const QString DESCRIPTION; static const QString SS_CONSENSUS; /* Secondary structure consensus */ static const QString REFERENCE_LINE; /* #=GC RF annotation in Stockholm markup */ static const QString CUTOFFS; /* #=GF GA, NC, TC annotation in Stockholm markup */ enum Cutoffs { /* Should be same as in esl_msa.h( uhmmer plugin ) */ CUTOFF_TC1, CUTOFF_TC2, CUTOFF_GA1, CUTOFF_GA2, CUTOFF_NC1, CUTOFF_NC2 }; static bool isValid( const QVariantMap& map ); /* Checks obligatory fields in info */ static QString getName( const QVariantMap& map ); static void setName( QVariantMap& map, const QString& name ); static bool hasName( const QVariantMap& map ); static QString getAccession( const QVariantMap& map ); static void setAccession( QVariantMap& map, const QString& acc ); static bool hasAccession( const QVariantMap& map ); static QString getDescription( const QVariantMap& map ); static void setDescription( QVariantMap& map, const QString& desc ); static bool hasDescription( const QVariantMap& map ); static QString getSSConsensus( const QVariantMap& map ); static void setSSConsensus( QVariantMap& map, const QString& cs ); static bool hasSSConsensus( const QVariantMap& map ); static QString getReferenceLine( const QVariantMap& map ); static void setReferenceLine( QVariantMap& map ,const QString& rf ); static bool hasReferenceLine( const QVariantMap& map ); static float getCutoff( const QVariantMap& map, Cutoffs coff ); static bool hasCutoff( const QVariantMap& map, Cutoffs coff ); static void setCutoff( QVariantMap& map, Cutoffs coff, float val ); }; // MAlignmentInfo } // U2 #endif // _U2_MALIGNMENT_INFO_H_ ugene-1.9.8/src/corelibs/U2Core/src/datatype/Matrix44.cpp0000644000175000017500000000436411651544331021536 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "Matrix44.h" namespace U2 { /* class Matrix44 */ Matrix44::Matrix44() : m(16, 0.0) { loadIdentity(); } Matrix44::Matrix44(const float *data) : m(16) { for (int i = 0; i < 16; ++i) { m[i] = data[i]; } } Matrix44::Matrix44(const Matrix44 &other) : m(other.m) {} Matrix44& Matrix44::operator= (const Matrix44 &other) { m = other.m; return *this; } void Matrix44::loadZero() { m.fill(0.0); } void Matrix44::loadIdentity() { m.fill(0.0); for (int i = 0; i < 4; ++i) { m[i + i*4] = 1.0; } } float* Matrix44::data() { return m.data(); } const float* Matrix44::data() const { return m.constData(); } float& Matrix44::operator[] (unsigned int i) { return m[i]; } float Matrix44::operator[] (unsigned int i) const { return m[i]; } void Matrix44::load(const QVariantList &values) { assert(values.size() == 16); for (int i = 0; i < 16; ++i) { m[i] = values.at(i).value(); } } QVariantList Matrix44::store() { QVariantList values; for (int i = 0; i < 16; ++i ) { values.append(QVariant::fromValue(m[i])); } return values; } void Matrix44::transpose() { float *data = m.data(); for (int i = 0; i < 4; ++i) { for (int j = 0; j < i; ++j) { float tmp = data[i + j*4]; data[i + j*4] = data[j + i*4]; data[j + i*4] = tmp; } } } } // namespace U2 ugene-1.9.8/src/corelibs/U2Core/src/datatype/UIndex.h0000644000175000017500000000403111651544331020752 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_UINDEX_H_ #define _U2_UINDEX_H_ #include #include #include #include namespace U2 { class U2CORE_EXPORT UIndex { public: //errors enum UIndexError { NO_ERR, EMPTY_IO_ID, EMPTY_DOC_FORMAT, EMPTY_IO_ADAPTER, EMPTY_URL, BAD_OFFSET, NO_SUCH_IO, EMPTY_KEY_VAL }; struct U2CORE_EXPORT ItemSection { QString ioSectionId; DocumentFormatId docFormat; qint64 startOff; qint64 endOff; QHash keys; UIndexError checkConsistentcy() const; }; struct U2CORE_EXPORT IOSection { QString sectionId; IOAdapterId ioAdapterId; QString url; QHash< QString, QString > keys; UIndexError checkConsistentcy() const; }; IOSection getIOSection(const QString& id) const; bool hasItems() const; QList< ItemSection > items; QList< IOSection > ios; UIndexError checkConsistency() const; }; // UIndex } // U2 #endif // _U2_UINDEX_H_ ugene-1.9.8/src/corelibs/U2Core/src/datatype/DNASequence.cpp0000644000175000017500000000226511651544331022213 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "DNASequence.h" namespace U2 { DNASequence::DNASequence(const QString& name, const QByteArray& s, DNAAlphabet* a) : seq(s), alphabet(a), circular(false) { if (!name.isEmpty()) { info.insert(DNAInfo::ID, name); } } void DNASequence::setName( const QString& name ) { info.insert(DNAInfo::ID, name); } } //namespace ugene-1.9.8/src/corelibs/U2Core/src/datatype/DNAAlphabetRegistryImpl.cpp0000644000175000017500000000644711651544331024544 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "DNAAlphabetRegistryImpl.h" #include #include #include namespace U2 { /* TRANSLATOR U2::DNAAlphabetRegistryImpl */ DNAAlphabetRegistryImpl::DNAAlphabetRegistryImpl(DNATranslationRegistry* _tr) { treg = _tr; initBaseAlphabets(); initBaseTranslations(); } DNAAlphabetRegistryImpl::~DNAAlphabetRegistryImpl() { foreach(DNAAlphabet* a, alphabets) { delete a; } } static bool alphabetComplexityComparator(const DNAAlphabet* a1, const DNAAlphabet* a2) { int a1Size = a1->getMap().count(true); //TODO: cache this val int a2Size = a2->getMap().count(true); return a1Size < a2Size; } bool DNAAlphabetRegistryImpl::registerAlphabet(DNAAlphabet* a) { if (findById(a->getId())!=NULL) { return false; } alphabets.push_back(a); //WARN: original order for equal alphabets must not be changed (DNA must be before RNA) qStableSort(alphabets.begin(), alphabets.end(), alphabetComplexityComparator); return true; } void DNAAlphabetRegistryImpl::unregisterAlphabet(DNAAlphabet* a) { int n = alphabets.removeAll(a); assert(n==1); Q_UNUSED(n); } DNAAlphabet* DNAAlphabetRegistryImpl::findById(const QString id) const { foreach(DNAAlphabet* al, alphabets) { if (al->getId() == id) { return al; } } return NULL; } DNAAlphabet* DNAAlphabetRegistryImpl::findAlphabet(const QByteArray& seq) const { foreach(DNAAlphabet* al, alphabets) { if (DNAAlphabetUtils::matches(al, seq)) { return al; } } return NULL; } QList DNAAlphabetRegistryImpl::findAlphabets(const QByteArray& seq) const { QList res; foreach(DNAAlphabet* al, alphabets) { if (DNAAlphabetUtils::matches(al, seq)) { res.push_back(al); } } return res; } QList DNAAlphabetRegistryImpl::findAlphabets(const QByteArray& seq, const QVector& regionsToProcess, bool onlyOne) const { QList res; foreach(DNAAlphabet* al, alphabets) { bool err = false; foreach (const U2Region& r, regionsToProcess) { if (!DNAAlphabetUtils::matches(al, seq, r)) { err = true; break; } } if (!err) { res.push_back(al); if (onlyOne) { break; } } } return res; } }//namespace ugene-1.9.8/src/corelibs/U2Core/src/datatype/FeatureColors.h0000644000175000017500000000212511651544331022335 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_FEATURE_COLORS_H_ #define _U2_FEATURE_COLORS_H_ #include #include namespace U2 { class U2CORE_EXPORT FeatureColors { public: static QColor genLightColor(const QString& name); }; } //namespace #endif ugene-1.9.8/src/corelibs/U2Core/src/datatype/SMatrix.h0000644000175000017500000000664611651544331021163 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_SUBST_MATRIX_H #define _U2_SUBST_MATRIX_H #include #include #include namespace U2 { class U2CORE_EXPORT SScore { public: char c1; char c2; float score; SScore(char _c1, char _c2, float _score) : c1(_c1), c2(_c2), score(_score){} }; // Substitution, Scoring or Weight matrix model. // Example: Blosum70, PAM200, VTML200 class U2CORE_EXPORT SMatrix { public: SMatrix(const QString& name, DNAAlphabet* alphabet, const QList& rawMatrix, const QString& description = QString()); //constructs empty anonymous matrix SMatrix() { alphabet = NULL, minChar = 0; maxChar = 0; charsInRow = 0;} bool isEmpty() const {return scores.size() == 0;} float getScore(char c1, char c2) const; void setScore(char c1, char c2, float score); const QString& getName() const {return name;} const QString& getDescription() const {return description;} DNAAlphabet* getAlphabet() const {return alphabet;} float getMinScore() const {return minScore;} float getMaxScore() const {return maxScore;} //TODO: make this class serializable QVariant toQVariant() const; static SMatrix fromQVariant(const QVariant& v); private: int getScoreIdx(char c1, char c2) const; void copyCharValues(char src, char dst); QString name; QString description; DNAAlphabet* alphabet; QVarLengthArray scores; //TODO: make scores integer ? char minChar; // used for optimization of scores size. Minimal character in the alphabet. char maxChar; // used for optimization of scores size. Maximum character in the alphabet. int charsInRow; float minScore; float maxScore; QByteArray validCharacters; // used only for debugging now. Use array but not Set since number of characters is low }; inline float SMatrix::getScore(char c1, char c2) const { int idx = getScoreIdx(c1, c2); return scores[idx]; } inline void SMatrix::setScore(char c1, char c2, float score) { int idx = getScoreIdx(c1, c2); scores[idx] = score; } inline int SMatrix::getScoreIdx(char c1, char c2) const { assert(validCharacters.contains(c1)); assert(validCharacters.contains(c2)); int d1 = c1 - minChar; int d2 = c2 - minChar; assert(d1 < charsInRow && d2 < charsInRow && d1 >= 0 && d2 >= 0); return d1 * charsInRow + d2; } } // namespace #endif ugene-1.9.8/src/corelibs/U2Core/src/datatype/DNAChromatogram.h0000644000175000017500000000260611651544331022532 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_DNA_CHROMATOGRAM_H_ #define _U2_DNA_CHROMATOGRAM_H_ #include #include namespace U2 { class U2CORE_EXPORT DNAChromatogram { public: DNAChromatogram() : traceLength(0), seqLength(0), hasQV(false) {} int traceLength; int seqLength; QVector baseCalls; QVector A; QVector C; QVector G; QVector T; QVector prob_A; QVector prob_C; QVector prob_G; QVector prob_T; bool hasQV; }; } //namespace #endif ugene-1.9.8/src/corelibs/U2Core/src/datatype/UIndex.cpp0000644000175000017500000000525511651544331021316 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "UIndex.h" namespace { bool iosHasId( const QList< U2::UIndex::IOSection >& ios, const QString& look_for ) { foreach( U2::UIndex::IOSection io, ios ) { if( io.sectionId == look_for ) { return true; } } return false; } bool hasEmptyKeyVal( QHash< QString, QString > keys ) { QHash< QString, QString >::const_iterator it = keys.begin(); while( keys.end() != it ) { if( it.key().isEmpty() || it.value().isEmpty() ) { return true; } ++it; } return false; } } // anonymous namespace namespace U2 { UIndex::UIndexError UIndex::ItemSection::checkConsistentcy() const { if( ioSectionId.isEmpty() ) { return EMPTY_IO_ID; } if( docFormat.isEmpty() ) { return EMPTY_DOC_FORMAT; } if( 0 > startOff || 0 > endOff || endOff <= startOff ) { return BAD_OFFSET; } if( hasEmptyKeyVal( keys ) ) { return EMPTY_KEY_VAL; } return NO_ERR; } UIndex::UIndexError UIndex::IOSection::checkConsistentcy() const { if( sectionId.isEmpty() ) { return EMPTY_IO_ID; } if( ioAdapterId.isEmpty() ) { return EMPTY_IO_ADAPTER; } if( url.isEmpty() ) { return EMPTY_URL; } if( hasEmptyKeyVal( keys ) ) { return EMPTY_KEY_VAL; } return NO_ERR; } UIndex::IOSection UIndex::getIOSection(const QString& id) const { foreach( IOSection ioSec, ios ) { if( ioSec.sectionId == id ) { return ioSec; } } return IOSection(); // there is no section with id } bool UIndex::hasItems() const { return !items.isEmpty(); } UIndex::UIndexError UIndex::checkConsistency() const { foreach( ItemSection it, items ) { if( !iosHasId( ios, it.ioSectionId ) ) { return NO_SUCH_IO; } } return NO_ERR; } } // U2 ugene-1.9.8/src/corelibs/U2Core/src/datatype/FeatureColors.cpp0000644000175000017500000000361311651544331022673 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "FeatureColors.h" namespace U2 { static QList prepareColors() { QList colors; QString mustHave = "FF"; QStringList optional; optional<<"FF"<<"CC"<<"99"<<"66"<<"33"<<"00"; for(int i = 0; i < 3; i++) { for(int j=0; j < optional.size(); j++) { for(int k=1; k < optional.size(); k++) { //todo: avoid duplicates QString colorName = i == 0 ? mustHave + optional[j] + optional[k] : i == 1 ? optional[j] + mustHave + optional[k] : optional[j] + optional[k] + mustHave; QColor c("#"+colorName); assert(c.isValid()); colors.append(c); } } } return colors; } QColor FeatureColors::genLightColor(const QString& name) { static QList colors = prepareColors(); int hash = 0; QByteArray a = name.toAscii(); for (int i=0;i * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "PhyTree.h" #include namespace U2 { PhyTreeData::PhyTreeData() : rootNode(NULL) { } PhyTreeData::PhyTreeData(const PhyTreeData& other) : QSharedData(other) { rootNode = other.rootNode == NULL ? NULL : other.rootNode->clone(); } PhyTreeData::~PhyTreeData() { if (rootNode != NULL){ delete rootNode; rootNode = NULL; } } PhyNode::PhyNode() { } PhyBranch::PhyBranch() : node1(NULL), node2(NULL), distance(0) { } void PhyTreeData::print() const{ QList nodes; int tab = 0; int distance = 0; rootNode->print(nodes,distance, tab); } void PhyTreeData::validate() const { #ifdef _DEBUG if (rootNode != NULL) { QList track; rootNode->validate(track); } #endif } QList PhyTreeData::collectNodes() const { QList track; if (rootNode != NULL) { rootNode->validate(track); } return track; } void PhyNode::validate(QList& track) const { if ( track.contains(this) ) return; track.append(this); foreach(PhyBranch* b, branches) { assert(b->node1 != NULL && b->node2!=NULL); if (b->node1 != this) { b->node1->validate(track); } else if (b->node2 != this) { b->node2->validate(track); } } } bool PhyNode::isConnected(const PhyNode* node) const { foreach(PhyBranch* b, branches) { if (b->node1 == node || b->node2 == node) { return true; } } return false; } PhyBranch* PhyNode::addBranch(PhyNode* node1, PhyNode* node2, double distance) { assert(!node1->isConnected(node2)); PhyBranch* b = new PhyBranch(); b->distance = distance; b->node1 = node1; b->node2 = node2; node1->branches.append(b); node2->branches.append(b); return b; } void PhyNode::removeBranch(PhyNode* node1, PhyNode* node2) { foreach(PhyBranch* b, node1->branches) { if (b->node1 == node1 && b->node2 == node2) { node1->branches.removeAll(b); node2->branches.removeAll(b); delete b; return; } } assert(0); } void PhyNode::dumpBranches() const{ std::cout<<"Branches are: "; for(int i =0; inode1!=0){ node1name = branches[i]->node1->name; } QString node2name = "null"; if(branches[i]->node2!=0){ node2name = branches[i]->node2->name; } std::cout<<"branch from node "<distance<node2 != this) { delete branches[i]->node2; delete branches[i]; } } } PhyNode* PhyNode::clone() const { QSet track; addToTrack(track); QSet allBranches; QMap nodeTable; foreach(const PhyNode* n, track) { PhyNode* n2 = new PhyNode(); n2->name = n->name; nodeTable[n] = n2; foreach(PhyBranch* b, n->branches) { allBranches.insert(b); } } foreach(PhyBranch* b, allBranches) { PhyNode* node1 = nodeTable[b->node1]; PhyNode* node2 = nodeTable[b->node2]; assert(node1!=NULL && node2!=NULL); PhyNode::addBranch(node1, node2, b->distance); } PhyNode* myClone = nodeTable.value(this); assert(myClone!=NULL); return myClone; } void PhyNode::print(QList& nodes, int tab, int distance){ if(nodes.contains(this)){ return; } nodes.append(this); for(int i=0; iname.toAscii().constData() <<" distance: "< blist = this->branches; int s = blist.size(); for(int i=0; inode2!=0){ int d = blist[i]->distance; blist[i]->node2->print(nodes, tab, d); } } } void PhyNode::addToTrack(QSet& track) const { if (track.contains(this)) { return; } track.insert(this); foreach(PhyBranch* b, branches) { b->node1->addToTrack(track); b->node1->addToTrack(track); } } int PhyTreeUtils::getNumSeqsFromNode(const PhyNode *node, const QSet &names) { int size = node->branches.size(); if (size > 1) { int s = 0; for (int i = 0; i < size; ++i) { if (node->branches[i]->node2 != node) { int num = getNumSeqsFromNode(node->branches[i]->node2, names); if (!num) { return 0; } s += num; } } return s; } else { QString str = node->name; return names.contains(str.replace('_', ' ')) ? 1 : 0; } } }//namespace ugene-1.9.8/src/corelibs/U2Core/src/datatype/DNAInfo.h0000644000175000017500000001434011651544331021000 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_DNA_INFO_H_ #define _U2_DNA_INFO_H_ #include #include #include #include namespace U2 { class U2CORE_EXPORT DNAInfo { public: static const QString LOCUS; /* - A short mnemonic name for the entry, chosen to suggest the sequence's definition. Mandatory keyword/exactly one record. */ static const QString DEFINITION; /*- A concise description of the sequence. Mandatory keyword/one or more records. */ static const QString ACCESSION; /* - The primary accession number is a unique, unchanging identifier assigned to each GenBank sequence record. (Please use this identifier when citing information from GenBank.) Mandatory keyword/one or more records. */ static const QString VERSION; /* - A compound identifier consisting of the primary accession number and a numeric version number associated with the current version of the sequence data in the record. This is followed by an integer key (a "GI") assigned to the sequence by NCBI. Mandatory keyword/exactly one record. */ static const QString PROJECT; /* - The identifier of a project (such as a Genome Sequencing Project) to which a GenBank sequence record belongs. Optional keyword/one or more records. */ static const QString KEYWORDS; /* - Short phrases describing gene products and other information about an entry. Mandatory keyword in all annotated entries/one or more records. */ static const QString SEGMENT; /* - Information on the order in which this entry appears in a series of discontinuous sequences from the same molecule. Optional keyword (only in segmented entries)/exactly one record. */ static const QString SOURCE; /*- Common name of the organism or the name most frequently used in the literature. Mandatory keyword in all annotated entries/one or more records/includes one subkeyword. */ static const QString REFERENCE; /* - Citations for all articles containing data reported in this entry. Includes seven subkeywords and may repeat. Mandatory keyword/one or more records. */ static const QString AUTHORS; /*- Lists the authors of the citation. Optional subkeyword/one or more records. */ static const QString CONSRTM; /*- Lists the collective names of consortiums associated with the citation (eg, International Human Genome Sequencing Consortium), rather than individual author names. Optional subkeyword/one or more records. */ static const QString TITLE; /* - Full title of citation. Optional subkeyword (present in all but unpublished citations)/one or more records. */ static const QString JOURNAL; /*- Lists the journal name, volume, year, and page numbers of the citation. Mandatory subkeyword/one or more records. */ static const QString MEDLINE; /*- Provides the Medline unique identifier for a citation. Optional subkeyword/one record. NOTE: The MEDLINE linetype is obsolete and was removed from the GenBank flatfile format in April 2005. */ static const QString PUBMED; /*- Provides the PubMed unique identifier for a citation. Optional subkeyword/one record. */ static const QString REMARK; /* - Specifies the relevance of a citation to an entry. Optional subkeyword/one or more records. */ static const QString COMMENT; /* - Cross-references to other sequence entries, comparisons to other collections, notes of changes in LOCUS names, and other remarks. Optional keyword/one or more records/may include blank records.*/ static const QString FEATURES; /* - Table containing information on portions of the sequence that code for proteins and RNA molecules and information on experimentally determined sites of biological significance. Optional keyword/one or more records. */ static const QString CHAIN_ID; /* - Molecular chain index from corresponding macromolecular structure (PDB or MMDB) */ static const QString CONTIG; /*- This linetype provides information about how individual sequence records can be combined to form larger-scale biological objects, such as chromosomes or complete genomes. Rather than presenting actual sequence data, a special join() statement on the CONTIG line provides the accession numbers and basepair ranges of the underlying records which comprise the object. As of August 2005, the 2L chromosome arm of Drosophila melanogaster (accession number AE014134) provided a good example of CONTIG use. */ static const QString ORIGIN; /*- Specification of how the first base of the reported sequence is operationally located within the genome. Where possible, this includes its location within a larger genetic map. Mandatory keyword/exactly one record. - The ORIGIN line is followed by sequence data (multiple records). */ static const QString ID; static const QString DATE; static const QString EMBL_ID; static const QString FASTA_HDR; static QString getPrimaryAccession(const QVariantMap&); static QString getContig(const QVariantMap&); static QString getName(const QVariantMap&); }; class U2CORE_EXPORT DNALocusInfo { public: QString name; QString topology; QString molecule; QString division; QString date; }; class U2CORE_EXPORT DNASourceInfo { public: QString name; QString organism; QStringList taxonomy; QString organelle; }; class U2CORE_EXPORT DNAReferenceInfo { public: int id; QString range; QList< QPair > data; //TODO }; }//namespace Q_DECLARE_METATYPE(U2::DNALocusInfo) Q_DECLARE_METATYPE(U2::DNASourceInfo) Q_DECLARE_METATYPE(U2::DNAReferenceInfo) #endif ugene-1.9.8/src/corelibs/U2Core/src/datatype/MAlignmentInfo.cpp0000644000175000017500000000766111651544331022774 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include #include "MAlignmentInfo.h" namespace U2 { const QString MAlignmentInfo::NAME = "NAME"; const QString MAlignmentInfo::ACCESSION = "ACCESSION"; const QString MAlignmentInfo::DESCRIPTION = "DESCRIPTION"; const QString MAlignmentInfo::SS_CONSENSUS = "SS_CONSENSUS"; const QString MAlignmentInfo::REFERENCE_LINE = "REFERENCE_LINE"; const QString MAlignmentInfo::CUTOFFS = "CUTOFFS"; bool MAlignmentInfo::isValid( const QVariantMap& map ) { return hasName( map ); } static QVariant getValue( const QString& tag, const QVariantMap& map ) { return map.value( tag ); } static void setValue( QVariantMap& map, const QString& tag, const QVariant& val ) { assert( !tag.isEmpty() ); if( !val.isNull() ) { map.insert( tag, val ); } } QString MAlignmentInfo::getName( const QVariantMap& map ) { return getValue( NAME, map ).toString(); } void MAlignmentInfo::setName( QVariantMap& map, const QString& name ) { setValue( map, NAME, name ); } bool MAlignmentInfo::hasName( const QVariantMap& map ) { return !getName( map ).isEmpty(); } QString MAlignmentInfo::getAccession( const QVariantMap& map ) { return getValue( ACCESSION, map ).toString(); } void MAlignmentInfo::setAccession( QVariantMap& map, const QString& acc ) { setValue( map, ACCESSION, acc ); } bool MAlignmentInfo::hasAccession( const QVariantMap& map ) { return !getAccession( map ).isEmpty(); } QString MAlignmentInfo::getDescription( const QVariantMap& map ) { return getValue( DESCRIPTION, map ).toString(); } void MAlignmentInfo::setDescription( QVariantMap& map, const QString& desc ) { setValue( map, DESCRIPTION, desc ); } bool MAlignmentInfo::hasDescription( const QVariantMap& map ) { return !getDescription( map ).isEmpty(); } QString MAlignmentInfo::getSSConsensus( const QVariantMap& map ) { return getValue( SS_CONSENSUS, map ).toString(); } void MAlignmentInfo::setSSConsensus( QVariantMap& map, const QString& cs ) { setValue( map, SS_CONSENSUS, cs ); } bool MAlignmentInfo::hasSSConsensus( const QVariantMap& map ) { return !getSSConsensus( map ).isEmpty(); } QString MAlignmentInfo::getReferenceLine( const QVariantMap& map ) { return getValue( REFERENCE_LINE, map ).toString(); } void MAlignmentInfo::setReferenceLine( QVariantMap& map ,const QString& rf ) { setValue( map, REFERENCE_LINE, rf ); } bool MAlignmentInfo::hasReferenceLine( const QVariantMap& map ) { return !getReferenceLine( map ).isEmpty(); } void MAlignmentInfo::setCutoff( QVariantMap& map, Cutoffs coff, float val ) { setValue( map, CUTOFFS + QString::number( static_cast< int >( coff ) ), val ); } float MAlignmentInfo::getCutoff( const QVariantMap& map, Cutoffs coff ) { return static_cast< float >( getValue( CUTOFFS + QString::number( static_cast< int >( coff ) ), map ).toDouble() ); } bool MAlignmentInfo::hasCutoff( const QVariantMap& map, Cutoffs coff ) { bool ok = false; getValue( CUTOFFS + QString::number( static_cast< int >( coff ) ), map ).toDouble( &ok ); return ok; } } // U2 ugene-1.9.8/src/corelibs/U2Core/src/datatype/DNATranslationImpl.cpp0000644000175000017500000002217711651544331023567 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "DNATranslationImpl.h" #include #include #include namespace U2 { DNATranslation1to1Impl::DNATranslation1to1Impl(const QString& id, const QString& _name, DNAAlphabet* src, DNAAlphabet* dst, QByteArray mapper121) : DNATranslation(id, _name, src, dst) { map = mapper121; assert(map.size() == 256); } int DNATranslation1to1Impl::translate(const char* src, int src_len, char* dst, int dst_capacity) const { int len = qMin(src_len, dst_capacity); TextUtils::translate(map, src, len, dst); return len; } int DNATranslation1to1Impl::translate(char* src_and_dst, int len) const { TextUtils::translate(map, src_and_dst, len); return len; } ////////////////////////////////////////////////////////////////////////// /// 3->1 DNATranslation3to1Impl::DNATranslation3to1Impl(const QString& _id, const QString& _name, DNAAlphabet* src, DNAAlphabet* dst, const QList >& rm, char dc, const QMap >& _roles) : DNATranslation(_id, _name, src, dst), index(rm, dc), roles(_roles) { codons = new char*[DNATranslationRole_Num]; cod_lens = new int[DNATranslationRole_Num]; for (int j=0;j > i(roles); while (i.hasNext()) { i.next(); QList l = i.value(); DNATranslationRole r = i.key(); cod_lens[r] = l.size()*3; codons[r] = new char[l.size()*3]; for (int j = 0; jisCaseSensitive(); int resLen = qMin(src_len/3, dst_capacity); if (caseSensitive) { for(int dstIdx=0, srcIdx=0; dstIdx < resLen; dstIdx++, srcIdx+=3) { char c = index.map(src + srcIdx); dst[dstIdx] = c; } } else { char uc[3]; const QByteArray& ucMap = TextUtils::UPPER_CASE_MAP; for(int dstIdx=0, srcIdx=0; dstIdx < resLen; dstIdx++, srcIdx+=3) { TextUtils::translate(ucMap, src+srcIdx, 3, uc); char c = index.map(src + srcIdx); dst[dstIdx] = c; } } return resLen; } int DNATranslation3to1Impl::translate(char* src_and_dst, int len) const { return translate(src_and_dst, len, src_and_dst, len); } ////////////////////////////////////////////////////////////////////////// // 3-1 index Index3To1::Index3To1() { indexSize = 0; bitsPerChar = 0; bitsPerCharX2 = 0; qFill(maskByChar, maskByChar+256, 0); } void Index3To1::init(const QList& ts) { assert(indexSize == 0); // count number of different input chars in map QBitArray usedChars(256, false); foreach(const Triplet& t, ts) { usedChars[(quint8)t.c[0]] = true; usedChars[(quint8)t.c[1]] = true; usedChars[(quint8)t.c[2]] = true; } int nChars = usedChars.count(true); assert(nChars > 0); // count number of bit enough to encode all input chars bitsPerChar = 0; while ((1 << bitsPerChar) <= nChars) bitsPerChar++; #ifdef _DEBUG int prevPow = 1 << (bitsPerChar-1); int nextPow = 1 << bitsPerChar; assert(nChars < nextPow && nChars >= prevPow); assert(bitsPerChar<=8); //validity check assert(bitsPerChar<=6);//TODO: optimize large tables!! #endif bitsPerCharX2 = bitsPerChar * 2; //cache this value -> used for optimization // assign bit mask for every char char mask = 1; for (int i = 0; i < 256; i++) { if (usedChars[i]) { maskByChar[i] = mask; mask++; } else { maskByChar[i] = 0; } } mask--; //last value was not used indexSize = 1 + (mask << bitsPerCharX2) + (mask< 0); } void Index3To1::init(const QByteArray& alphabetChars) { int nChars = alphabetChars.size(); QList ts; for (int i1=0; i1 < nChars; i1++) { char c1 = alphabetChars[i1]; for (int i2=0; i2 < nChars; i2++) { char c2 = alphabetChars[i1]; for (int i3=0; i3 < nChars; i3++) { char c3 = alphabetChars[i1]; Triplet m(c1, c2, c3); ts.append(m); } } } init(ts); } ////////////////////////////////////////////////////////////////////////// /// 1->3 DNATranslation1to3Impl::DNATranslation1to3Impl(const QString& _id, const QString& _name, DNAAlphabet* src, DNAAlphabet* dst, const BackTranslationRules& rules) : DNATranslation(_id, _name, src, dst), index(rules) { qsrand(QDateTime::currentDateTime().toTime_t()); } DNATranslation1to3Impl::~DNATranslation1to3Impl() { } int DNATranslation1to3Impl::translate (const char* src, int src_len, char* dst, int dst_capacity, BackTranslationMode mode) const { bool caseSensitive = srcAlphabet->isCaseSensitive(); int resLen = qMin(src_len * 3, dst_capacity); switch (mode) { case USE_MOST_PROBABLE_CODONS : { if (caseSensitive) { for(int dstIdx=0, srcIdx=0; dstIdx < resLen; srcIdx++) { TripletP curr = index.map[index.index[(int)*(src + srcIdx)]]; dst[dstIdx++] = curr.c[0]; dst[dstIdx++] = curr.c[1]; dst[dstIdx++] = curr.c[2]; } } else { char uc; const QByteArray& ucMap = TextUtils::UPPER_CASE_MAP; for(int dstIdx=0, srcIdx=0; dstIdx < resLen; srcIdx++) { TextUtils::translate(ucMap, src+srcIdx, 1, &uc); TripletP curr = index.map[index.index[(int)*(src + srcIdx)]]; dst[dstIdx++] = curr.c[0]; dst[dstIdx++] = curr.c[1]; dst[dstIdx++] = curr.c[2]; } } break; } case USE_FREQUENCE_DISTRIBUTION : { if (caseSensitive) { for(int dstIdx=0, srcIdx=0; dstIdx < resLen; srcIdx++) { int p = qrand() % 100; int pos = index.index[(int)*(src + srcIdx)]; while (index.map[pos].p <= p) { p -= index.map[pos++].p; } TripletP curr = index.map[pos]; dst[dstIdx++] = curr.c[0]; dst[dstIdx++] = curr.c[1]; dst[dstIdx++] = curr.c[2]; } } else { char uc; const QByteArray& ucMap = TextUtils::UPPER_CASE_MAP; for(int dstIdx=0, srcIdx=0; dstIdx < resLen; srcIdx++) { TextUtils::translate(ucMap, src+srcIdx, 1, &uc); int p = qrand() % 100; int pos = index.index[(int)*(src + srcIdx)]; while (index.map[pos].p <= p) { p -= index.map[pos++].p; } TripletP curr = index.map[pos]; dst[dstIdx++] = curr.c[0]; dst[dstIdx++] = curr.c[1]; dst[dstIdx++] = curr.c[2]; } } break; } default: break; } return resLen; } int DNATranslation1to3Impl::translate(const char* src, int src_len, char* dst, int dst_capacity) const { return translate(src, src_len, dst, dst_capacity, USE_MOST_PROBABLE_CODONS); } int DNATranslation1to3Impl::translate(char* src_and_dst, int len) const { return translate(src_and_dst, len, src_and_dst, len, USE_MOST_PROBABLE_CODONS); } }//namespace ugene-1.9.8/src/corelibs/U2Core/src/datatype/DNAQuality.cpp0000644000175000017500000000432211651544331022067 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "DNAQuality.h" #include "DNAChromatogram.h" namespace U2 { static const QString SANGER("Sanger"); static const QString ILLUMINA("Illumina 1.3+"); static const QString SOLEXA("Solexa/Illumina 1.0"); DNAQuality::DNAQuality( const QByteArray& qualScore, DNAQualityType t /* = DNAQualityType_Sanger*/ ) : qualCodes(qualScore), type(t) { } int DNAQuality::getValue( int pos ) const { assert(pos >=0 && pos < qualCodes.count()); return ( (int)qualCodes.at(pos) - 33 ); } char DNAQuality::encode( int val, DNAQualityType type ) { if (type == DNAQualityType_Sanger ) { return (char) ( (val <= 93 ? val : 93) + 33 ); } else { return (char) ( (val <= 62 ? val : 62) + 64 ); } } QString DNAQuality::getDNAQualityNameByType( DNAQualityType t ) { switch(t){ case DnaQualityType_Solexa: return SOLEXA; case DNAQualityType_Illumina: return ILLUMINA; default: return SANGER; } } DNAQualityType DNAQuality::getDNAQualityTypeByName( const QString& name ) { if ( name == SOLEXA) { return DNAQualityType_Illumina; } else if (name == ILLUMINA) { return DNAQualityType_Illumina; } else { return DNAQualityType_Sanger; } } QStringList DNAQuality::getDNAQualityTypeNames() { QStringList res; res << SANGER << ILLUMINA << SOLEXA; return res; } } // U2 ugene-1.9.8/src/corelibs/U2Core/src/datatype/SMatrix.cpp0000644000175000017500000001074111651544331021505 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "SMatrix.h" #include #include #include namespace U2 { #define DEFAULT_FILL_VALUE -1000000.0f SMatrix::SMatrix(const QString& _name, DNAAlphabet* _alphabet, const QList& rawMatrix, const QString& _description) : name(_name), description(_description), alphabet(_alphabet) { validCharacters = alphabet->getAlphabetChars(); TextUtils::charBounds(validCharacters.constData(), validCharacters.size(), minChar, maxChar); charsInRow = maxChar - minChar + 1; scores.resize(charsInRow*charsInRow); qFill(scores.data(), scores.data() + scores.size(), -1000000); minScore = 1000000; maxScore = -1000000; foreach(const SScore& s, rawMatrix) { int idx = getScoreIdx(s.c1, s.c2); scores[idx] = s.score; minScore = qMin(minScore, s.score); maxScore = qMax(maxScore, s.score); } //try to fix amino alphabet for extended symbols if needed: U(Selenocysteine) & O(Pyrrolysine) if (alphabet->isAmino()) { if (getScore('U', 'U') == DEFAULT_FILL_VALUE) { // no score for 'U' symbol, use score value for 'C' (Cysteine) copyCharValues('C', 'U'); } if (getScore('O', 'O') == DEFAULT_FILL_VALUE) {// no score for 'U' symbol, use score value for 'K' (Lysine) copyCharValues('K', 'O'); } } //now for all symbols in alphabet without score set the minimal score foreach(char c1, validCharacters) { foreach(char c2, validCharacters) { float score = getScore(c1, c2); if (score == DEFAULT_FILL_VALUE) { setScore(c1, c2, minScore); } } } } void SMatrix::copyCharValues(char srcChar, char dstChar) { for (int i=0; i < validCharacters.size(); i++) { char c = validCharacters.at(i); float scoreSrc1 = getScore(srcChar, c); setScore(dstChar, c, scoreSrc1); float scoreSrc2 = getScore(c, srcChar); setScore(c, dstChar, scoreSrc2); } } QVariant SMatrix::toQVariant() const { QList res; res.append(name); res.append(description); res.append(alphabet->getId()); res.append(QChar(minChar)); res.append(QChar(maxChar)); res.append(charsInRow); res.append(validCharacters); res.append(double(minScore)); res.append(double(maxScore)); res.append(scores.size()); for (int i=0; i< scores.size(); i++) { res.append(double(scores[i])); } return res; } SMatrix SMatrix::fromQVariant(const QVariant& v) { QList list = v.toList(); SMatrix m; int n = 0; m.name = list.at(n++).toString(); m.description = list.at(n++).toString(); QString alphabetId = list.at(n++).toString(); m.alphabet = AppContext::getDNAAlphabetRegistry()->findById(alphabetId); m.minChar = list.at(n++).toChar().toAscii(); m.maxChar = list.at(n++).toChar().toAscii(); m.charsInRow = list.at(n++).toInt(); m.validCharacters = list.at(n++).toByteArray(); m.minScore = (float)list.at(n++).toDouble(); m.maxScore = (float)list.at(n++).toDouble(); int nScores = list.at(n++).toInt(); m.scores.resize(nScores); for(int i = 0; i< nScores; i++) { m.scores[i] = float(list.at(n++).toDouble()); } if (m.name.isEmpty() || m.alphabet == NULL || m.validCharacters.isEmpty() || !m.validCharacters.contains(m.minChar) || !m.validCharacters.contains(m.maxChar) || m.maxChar - m.minChar + 1 != m.charsInRow) { coreLog.error("Error during substitution matrix deserialization!"); return SMatrix(); } return m; } } // namespace ugene-1.9.8/src/corelibs/U2Core/src/datatype/AnnotationSettings.cpp0000644000175000017500000001200311651544331023742 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "AnnotationSettings.h" #include #include #include #include #include namespace U2 { #define SETTINGS_ROOT QString("annotation_settings/") #define MAX_CACHE_SIZE 1000 AnnotationSettingsRegistry::AnnotationSettingsRegistry(const QList& predefined) { changeSettings(predefined, false); read(); } AnnotationSettingsRegistry::~AnnotationSettingsRegistry() { save(); qDeleteAll(persistentMap); qDeleteAll(transientMap); } void AnnotationSettingsRegistry::changeSettings(const QList& settings, bool saveAsPersistent) { if (settings.isEmpty()) { return; } QStringList changedNames; foreach(AnnotationSettings* s, settings) { assert(s->color.isValid()); assert(!s->name.isEmpty()); persistentMap.remove(s->name); transientMap.remove(s->name); if (saveAsPersistent) { persistentMap[s->name] = s; } else { transientMap[s->name] = s; } changedNames.append(s->name); } emit si_annotationSettingsChanged(changedNames); } QStringList AnnotationSettingsRegistry::getAllSettings() const { return (persistentMap.keys() + transientMap.keys()).toSet().toList(); } AnnotationSettings* AnnotationSettingsRegistry::getAnnotationSettings(Annotation* a) { return getAnnotationSettings(a->getAnnotationName()); } AnnotationSettings* AnnotationSettingsRegistry::getAnnotationSettings(const QString& name) { //Search in persistent settings: AnnotationSettings* s = persistentMap.value(name); if (s != NULL) { return s; } //search in transient cache: s = transientMap.value(name); if (s!=NULL){ return s; } s = new AnnotationSettings(); s->name = name; s->color = FeatureColors::genLightColor(name); s->visible = true; if (transientMap.size() == MAX_CACHE_SIZE) { //todo: mutex!? transientMap.erase(transientMap.begin()); } transientMap[name]=s; return s; } void AnnotationSettingsRegistry::read() { Settings* s = AppContext::getSettings(); QStringList keys = s->getAllKeys(SETTINGS_ROOT); QList list; foreach(const QString& key, keys) { QString name = key.split('/').first(); AnnotationSettings* as = transientMap.value(name); if (as == NULL) { as = new AnnotationSettings(); as->name = name; } as->color = s->getValue(SETTINGS_ROOT + as->name + "/color", FeatureColors::genLightColor(as->name)).value(); as->visible = s->getValue(SETTINGS_ROOT + as->name + "/visible", true).toBool(); as->amino = s->getValue(SETTINGS_ROOT + as->name + "/amino", true).toBool(); QString qs = s->getValue(SETTINGS_ROOT + as->name + "/quals", "").toString(); if (!qs.isEmpty()) { as->nameQuals = qs.split(',', QString::SkipEmptyParts); } list.append(as); } changeSettings(list, false); } void AnnotationSettingsRegistry::save() { Settings* s = AppContext::getSettings(); QStringList keys = s->getAllKeys(SETTINGS_ROOT); foreach(const AnnotationSettings* as, persistentMap.values()) { s->setValue(SETTINGS_ROOT + as->name + "/color", as->color); s->setValue(SETTINGS_ROOT + as->name + "/visible", as->visible); s->setValue(SETTINGS_ROOT + as->name + "/amino", as->amino); s->setValue(SETTINGS_ROOT + as->name + "/quals", as->nameQuals.join(",")); } } ////////////////////////////////////////////////////////////////////////// AnnotationSettings::AnnotationSettings() { amino = false; color = Qt::black; visible = true; } AnnotationSettings::AnnotationSettings(const QString& _name, bool _amino, const QColor& _color, bool _visible) : name(_name), color(_color), amino(_amino), visible(_visible) { } bool AnnotationSettings::equals(const AnnotationSettings* as) const { return name == as->name && amino == as->amino && color == as->color && visible == as->visible && nameQuals == as->nameQuals; } }//namespace ugene-1.9.8/src/corelibs/U2Core/src/datatype/Vector3D.h0000644000175000017500000000445211651544331021216 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_VECTOR_MATH_H_ #define _U2_VECTOR_MATH_H_ #include #include #include namespace U2 { class Matrix44; class U2CORE_EXPORT Vector3D { public: double x, y, z; explicit Vector3D(double xi = 0.0, double yi = 0.0, double zi = 0.0); Vector3D(const Vector3D& v); Vector3D& operator = (const Vector3D& v); bool operator == (const Vector3D& other); bool operator != (const Vector3D& other); double& operator [] (unsigned int i); double operator [] (unsigned int i) const; Vector3D& operator += (const Vector3D& v); Vector3D& operator -= (const Vector3D& v); Vector3D& operator *= (double f); Vector3D& operator /= (double f); Vector3D& dot(const Matrix44 &m); void set(double xs, double ys, double zs); double length(void) const; double lengthSquared(void) const; void normalize(void); }; U2CORE_EXPORT Vector3D operator - (const Vector3D& a); U2CORE_EXPORT Vector3D operator + (const Vector3D& a, const Vector3D& b); U2CORE_EXPORT Vector3D operator - (const Vector3D& a, const Vector3D& b); U2CORE_EXPORT double vector_dot(const Vector3D& a, const Vector3D& b); U2CORE_EXPORT Vector3D vector_cross(const Vector3D& a, const Vector3D& b); U2CORE_EXPORT Vector3D operator * (const Vector3D& v, double f); U2CORE_EXPORT Vector3D operator * (double f, const Vector3D& v); U2CORE_EXPORT Vector3D operator / (const Vector3D& v, double f); }//namespace #endif //_U2_VECTOR_MATH_H_ ugene-1.9.8/src/corelibs/U2Core/src/datatype/DNAAlphabet.cpp0000644000175000017500000000527011651544331022162 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "DNAAlphabet.h" namespace U2 { const QString BaseDNAAlphabetIds::RAW() { return "RAW_ALPHABET"; } const QString BaseDNAAlphabetIds::NUCL_DNA_DEFAULT() { return "NUCL_DNA_DEFAULT_ALPHABET"; } const QString BaseDNAAlphabetIds::NUCL_RNA_DEFAULT() { return "NUCL_RNA_DEFAULT_ALPHABET"; } const QString BaseDNAAlphabetIds::NUCL_DNA_EXTENDED() { return "NUCL_DNA_EXTENDED_ALPHABET"; } const QString BaseDNAAlphabetIds::NUCL_RNA_EXTENDED (){ return "NUCL_RNA_EXTENDED_ALPHABET"; } const QString BaseDNAAlphabetIds::AMINO_DEFAULT() { return "AMINO_DEFAULT_ALPHABET"; } DNAAlphabet::DNAAlphabet(const QString& _id, const QString& _name, DNAAlphabetType _t, const QBitArray& _map, Qt::CaseSensitivity cm, char _defSym) : id(_id), name(_name), type(_t), map(_map), caseMode(cm), defSym(_defSym) { assert(map[defSym] == true); numChars = getAlphabetChars().count(); } QByteArray DNAAlphabet::getAlphabetChars(bool forceBothCases) const { QByteArray res; bool bothCases = forceBothCases || isCaseSensitive(); for (int i = 0; i < 256; i++) { if (map[i]) { bool skip = (!bothCases) && i >= 'a' && i <= 'z'; if (!skip) { res.append((char)i); } } } assert(!res.isEmpty()); return res; } DNAAlphabet* DNAAlphabet::deriveCommonAlphabet(DNAAlphabet* al1, DNAAlphabet* al2) { if (al1 == al2) { return al1; } if (al1->getType()!=al2->getType()) { return NULL; } DNAAlphabet* resAl = al1->getNumAlphabetChars() >= al2->getNumAlphabetChars() ? al1 : al2; return resAl; } bool DNAAlphabet::containsAll(const char* str, int len) const { for (int i=0; i < len; i++) { char c = str[i]; if (!contains(c)) { return false; } } return true; } } //namespace ugene-1.9.8/src/corelibs/U2Core/src/datatype/BioStruct3D.h0000644000175000017500000002043111651544331021665 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_BIOSTRUCT3D_H_ #define _U2_BIOSTRUCT3D_H_ #include #include #include #include #include #include #include #include #include namespace U2 { class U2Region; class U2CORE_EXPORT ResidueIndex { int resId; int order; // to keep order of residues in the chain char insCode; public: ResidueIndex() : resId(0), order(0), insCode(' ') {} ResidueIndex(int residueIdx, char insertionCode) : resId(residueIdx), order(0), insCode(insertionCode) {} bool operator<(const ResidueIndex& other) const; bool operator==(const ResidueIndex& other) const; bool operator!=(const ResidueIndex& other) const; int toInt() const { return resId; } void setOrder(int ord) { order = ord; } }; //! Represents biopolimer residue class ResidueData : public QSharedData { public: enum Type { TYPE_UNKNOWN, TYPE_PROTEIN, TYPE_DNA, TYPE_RNA }; Type type; QByteArray name; char acronym; int chainIndex; ResidueData() : type(TYPE_UNKNOWN), acronym(' '), chainIndex(0) {} }; typedef QSharedDataPointer SharedResidue; //! Represents atom class AtomData : public QSharedData { public: int atomicNumber; int chainIndex; ResidueIndex residueIndex; QByteArray name; Vector3D coord3d; float occupancy, temperature; public: AtomData() { chainIndex = 0; atomicNumber = 0; temperature = -1.0; occupancy = 0; } }; typedef QSharedDataPointer SharedAtom; //! Represents chemical bond between atoms class Bond { SharedAtom atom1; SharedAtom atom2; public: Bond(const SharedAtom& a1, const SharedAtom& a2) : atom1(a1), atom2(a2) { } const SharedAtom getAtom1() { return atom1; } const SharedAtom getAtom2() { return atom2; } }; //! Represents protein secondary structure: alpha-helix, beta-strand, turn class SecondaryStructure : public QSharedData { public: enum Type { Type_None = -1, Type_AlphaHelix, Type_PiHelix, Type_310Helix, Type_BetaStrand, Type_BetaBridge, Type_Turn, Type_BendRegion }; Type type; char chainIdentifier; int chainIndex; int startSequenceNumber; int endSequenceNumber; public: SecondaryStructure() : type(Type_None) { startSequenceNumber = 0; endSequenceNumber = 0; chainIndex = 0; chainIdentifier = 0; } }; typedef QSharedDataPointer SharedSecondaryStructure; //! Model 3D /*! Represents collection of molecule atomic coordinates and bonds */ class Molecule3DModel { public: QList atoms; QList bonds; }; //! Molecule /*! Represents molecule chain (biopolymer or any other) */ class MoleculeData : public QSharedData { public: MoleculeData(): engineered(false) {} MoleculeData(const QString& molName) : name(molName), engineered(false) {} QMap residueMap; // this list used by biostrct renderers // its indexes are NOT model ids taken from PDB QList models; QList annotations; QString name; bool engineered; }; typedef QSharedDataPointer SharedMolecule; typedef QHash AtomCoordSet; //! Biological 3D structure class U2CORE_EXPORT BioStruct3D { public: static QString SecStructAnnotationTag; static QString MoleculeAnnotationTag; static QString AlphaHelixAnnotationTag; static QString BetaStrandAnnotationTag; static QString TurnAnnotationTag; static QString ChainIdQualifierName; static QString SecStructTypeQualifierName; public: BioStruct3D(); /** This is not deep copy constructor */ BioStruct3D(const BioStruct3D &other); QMap moleculeMap; QMap modelMap; QList annotations; QList secondaryStructures; QList interMolecularBonds; QString descr; QByteArray pdbId; // Const member functions double getRadius() const { return radius; } const Vector3D& getCenter() const { return rotationCenter; } QByteArray getRawSequenceByChainId(int id) const; int getNumberOfAtoms() const; int getNumberOfResidues() const; static int residueIndexToInt(const ResidueIndex& idx); const SharedAtom getAtomById(int index, int modelIndex) const; const SharedResidue getResidueById(int chainIndex, ResidueIndex residueIndex) const; // Theese three methods need to solve confusion between model ids (same as in PDB) // and internal model indexes, both are used in UGENE // model ids should be used for user interface, and one fine day may become a strings // model index numbers used by internal UGENE parts, and shoud be consequent int values from 0 /** @returns list of model ids (same as in PDB), that can be not consequent */ const QList getModelsNames() const; /** @returns molecule model by it's model id (same as in PDB) */ const Molecule3DModel getModelByName(int moleculeId, int name) const; /** @returns model by it's index number in our data structure */ const Molecule3DModel getModelByIndex(int moleculeId, int index) const; // Modifiers void calcCenterAndMaxDistance(); void generateAnnotations(); /** Biostruct 3D model should be transforemd with this matrix */ void setTransform(const Matrix44 &m) { transform = m; } const Matrix44& getTransform() const { return transform; } public: // Static methods static const QString getSecStructTypeName(SecondaryStructure::Type type); private: void generateChainAnnotations(); void generateSecStructureAnnotations(); private: BioStruct3D& operator= (const BioStruct3D&); private: double radius; Vector3D rotationCenter; Matrix44 transform; }; //! Shared data for BioStruct3DSelection class BioStruct3DChainSelectionData : public QSharedData { public: BioStruct3DChainSelectionData() : QSharedData() {} BioStruct3DChainSelectionData(const BioStruct3DChainSelectionData &other) : QSharedData(), selection(other.selection) {} ~BioStruct3DChainSelectionData() {} // presented in map believed to be selected // can be optimized on assumption that residue ids are continual QMultiMap selection; }; // class BioStruct3DChainSelectionData //! Represents residue chain selection on BioStruct3D. class U2CORE_EXPORT BioStruct3DChainSelection { public: BioStruct3DChainSelection(const BioStruct3D &biostruct); BioStruct3DChainSelection(const BioStruct3DChainSelection &other); const BioStruct3D &getBioStruct3D() const { return biostruct; } bool inSelection(int chainId, int residueId) const; bool isEmpty() const { return data->selection.isEmpty(); } void add(int chain, const U2Region ®ion); void add(int chain, const QVector ®ions); void remove(int chain, const U2Region ®ion); void remove(int chain, const QVector ®ions); void update(int chain, const U2Region &add, const U2Region &remove); void update(int chain, const QVector &adds, const QVector &removes); private: const BioStruct3D &biostruct; QSharedDataPointer data; }; // class U2CORE_EXPORT BioStruct3DChainSelection } // namespace U2 #endif // _U2_BIOSTRUCT3D_H_ ugene-1.9.8/src/corelibs/U2Core/src/datatype/Vector3D.cpp0000644000175000017500000000726711651544331021560 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "Vector3D.h" #include namespace U2 { Vector3D::Vector3D(double xi, double yi, double zi) { x=xi; y=yi; z=zi; } Vector3D::Vector3D(const Vector3D& v) { x=v.x; y=v.y; z=v.z; } Vector3D& Vector3D::operator = (const Vector3D& v) { x=v.x; y=v.y; z=v.z; return *this; } void Vector3D::set(double xs, double ys, double zs) { x=xs; y=ys; z=zs; } bool Vector3D::operator == (const Vector3D& other) { return (x == other.x && y == other.y && z == other.z); } bool Vector3D::operator != (const Vector3D& other) { return !(*this == other); } double& Vector3D::operator [] (unsigned int i) { static double err = 0.0; if (i == 0) return x; else if (i == 1) return y; else if (i == 2) return z; else qCritical("Vector operator [] access out of range : %d", i); return err; } double Vector3D::operator [] (unsigned int i) const { if (i == 0) return x; else if (i == 1) return y; else if (i == 2) return z; else qCritical("Vector operator [] access out of range : %d", i); return 0.0; } Vector3D operator - (const Vector3D& a) { return Vector3D(-a.x, -a.y, -a.z); } Vector3D operator + (const Vector3D& a, const Vector3D& b) { return Vector3D(a.x+b.x, a.y+b.y, a.z+b.z); } Vector3D& Vector3D::operator += (const Vector3D& v) { x+=v.x; y+=v.y; z+=v.z; return *this; } Vector3D operator - (const Vector3D& a, const Vector3D& b) { return Vector3D(a.x-b.x, a.y-b.y, a.z-b.z); } Vector3D& Vector3D::operator -= (const Vector3D& v) { x-=v.x; y-=v.y; z-=v.z; return *this; } Vector3D operator * (const Vector3D& v, double f) { return Vector3D(v.x*f, v.y*f, v.z*f); } Vector3D operator * (double f, const Vector3D& v) { return Vector3D(v.x*f, v.y*f, v.z*f); } Vector3D& Vector3D::operator *= (double f) { x*=f; y*=f; z*=f; return *this; } Vector3D operator / (const Vector3D& v, double f) { return Vector3D(v.x/f, v.y/f, v.z/f); } Vector3D& Vector3D::operator /= (double f) { x/=f; y/=f; z/=f; return *this; } Vector3D& Vector3D::dot(const Matrix44 &m) { const Vector3D tmp = *this; const float *mdata = m.data(); x = tmp.x*mdata[0] + tmp.y*mdata[1] + tmp.z*mdata[2] + mdata[3]; y = tmp.x*mdata[4] + tmp.y*mdata[5] + tmp.z*mdata[6] + mdata[7]; z = tmp.x*mdata[8] + tmp.y*mdata[9] + tmp.z*mdata[10] + mdata[11]; return *this; } double Vector3D::length(void) const { return sqrt(x*x + y*y + z*z); } double Vector3D::lengthSquared(void) const { return (x*x + y*y + z*z); } void Vector3D::normalize(void) { *this /= length(); } double vector_dot(const Vector3D& a, const Vector3D& b) { return (a.x*b.x + a.y*b.y + a.z*b.z); } Vector3D vector_cross(const Vector3D& a, const Vector3D& b) { return Vector3D( a.y*b.z - a.z*b.y, a.z*b.x - a.x*b.z, a.x*b.y - a.y*b.x ); } } //namespace ugene-1.9.8/src/corelibs/U2Core/src/datatype/PWMatrix.cpp0000644000175000017500000000574211651544331021636 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "PWMatrix.h" #include namespace U2 { UniprobeInfo::UniprobeInfo(): properties(QMap()) { } UniprobeInfo::UniprobeInfo(const QMap& props): properties(props) { } QString UniprobeInfo::getProperty(const QString &name) const { return properties.value(name, QString("")); } QMap UniprobeInfo::getProperties() const { return properties; } UniprobeInfo::UniprobeInfo(const QString& data) { QStringList parsedData = data.split("\t"); QMap props; for (int i = 0, n = parsedData.length(); i < n; i++) { QString curr = parsedData[i]; props.insert(curr.section(":", 0).trimmed(), curr.section(":", 1).trimmed()); } } PWMatrix::PWMatrix(const QVarLengthArray& matrix, const PWMatrixType& _type) : data(matrix), type(_type) { length = (type == PWM_MONONUCLEOTIDE) ? (matrix.size() / 4) : (matrix.size() / 16); minSum = 0, maxSum = 0; for (int i = 0; i < length; i++) { float min = 1e6; float max = -1e6; for (int j = 0, n = (type == PWM_MONONUCLEOTIDE) ? 4 : 16; j < n; j++) { float curr = data[j * length + i]; min = qMin(min, curr); max = qMax(max, curr); } minSum += min; maxSum += max; } } int PWMatrix::index(int row, int column) const { assert (row >= 0); assert (row < 16); if (type == PWM_MONONUCLEOTIDE) assert (row < 4); assert (column >= 0); assert (column < length); return row * length + column; } PWMatrixType PWMatrix::getType() const { return type; } int PWMatrix::getLength() const { return length; } float PWMatrix::getValue(int row, int column) const { int pos = index(row, column); return data[pos]; } float PWMatrix::getMinSum() const { return minSum; } float PWMatrix::getMaxSum() const { return maxSum; } void PWMatrix::setInfo(const UniprobeInfo& _info) { info = _info; } QString PWMatrix::getProperty(const QString &p) const { return info.getProperty(p); } QMap PWMatrix::getProperties() const { return info.getProperties(); } }ugene-1.9.8/src/corelibs/U2Core/src/datatype/DNATranslationImpl.h0000644000175000017500000002113211651544331023222 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_DNA_TRANSLATION_IMPL_H_ #define _U2_DNA_TRANSLATION_IMPL_H_ #include #include namespace U2 { class DNATranslation1to1Impl : public DNATranslation { public: DNATranslation1to1Impl(const QString& id, const QString& _name, DNAAlphabet* src, DNAAlphabet* dst, QByteArray mapper121); virtual int translate(const char* src, int src_len, char* dst, int dst_capacity) const; virtual int translate(char* src_and_dst, int len) const; virtual bool isOne2One() const {return true;} virtual QByteArray getOne2OneMapper() const { return map;} private: QByteArray map; }; struct U2CORE_EXPORT Triplet { public: Triplet() { c[0] = c[1] = c[2] = '\0'; } Triplet(const char* s) { c[0] = s[0]; c[1] = s[1]; c[2] = s[2]; } Triplet(char c0, char c1, char c2) {c[0] = c0; c[1] = c1; c[2] = c2;} char c[3]; }; //Triplet extended with probability value, used for back translation struct U2CORE_EXPORT TripletP { public: TripletP() { c[0] = c[1] = c[2] = '\0'; p = 0; } TripletP(const char* s) { c[0] = s[0]; c[1] = s[1]; c[2] = s[2]; p = 0;} TripletP(char c0, char c1, char c2) {c[0] = c0; c[1] = c1; c[2] = c2; p = 0;} TripletP(const char* s, int p0) { c[0] = s[0]; c[1] = s[1]; c[2] = s[2]; p = p0;} TripletP(char c0, char c1, char c2, int p0) {c[0] = c0; c[1] = c1; c[2] = c2; p = p0;} bool operator <(const TripletP &other) const { return (p > other.p); } char c[3]; int p; //probability value, values in [0..100] }; class U2CORE_EXPORT Index3To1 { public: Index3To1(); void init(const QList& t); void init(const QByteArray& alphabetChars); int indexOf(const Triplet& t) const { return indexOf(t.c[0], t.c[1], t.c[2]); } int indexOf(const char* str) const { return indexOf(str[0], str[1], str[2]); } int indexOf(char c1, char c2, char c3) const { int m1 = maskByChar[(quint8)c1]; int m2 = maskByChar[(quint8)c2]; int m3 = maskByChar[(quint8)c3]; int i = (m1<<(bitsPerCharX2))+(m2<= 0 && i < indexSize); return i; } int getIndexSize() const {return indexSize;} private: int indexSize; int bitsPerChar; int bitsPerCharX2; char maskByChar[256]; }; template class Mapping3To1 { public: Mapping3To1(const Triplet& _t, const T& _res) : t(_t), res(_res){} Triplet t; T res; }; template class IndexedMapping3To1 { public: IndexedMapping3To1(const QList >& rawMapping, const T& defaultVal) { //init index; QList ts; foreach(const Mapping3To1& m, rawMapping) { ts.append(m.t); } index.init(ts); //allocate value area and fill it with default values int size = index.getIndexSize(); assert(size > 0); resultByIndex = new T[size]; qFill(resultByIndex, resultByIndex+size, defaultVal); //assign indexed values foreach(const Mapping3To1& m, rawMapping) { int i = index.indexOf(m.t); resultByIndex[i] = m.res; } } IndexedMapping3To1(const QByteArray& alphabetChars, const T& defaultVal) { //init index index.init(alphabetChars); //allocate value area and fill it with default values int size = index.getIndexSize(); assert(size > 0); resultByIndex = new T[size]; qFill(resultByIndex, resultByIndex+size, defaultVal); } ~IndexedMapping3To1() { delete[] resultByIndex; } const T& map(char c1, char c2, char c3) const { int i = index.indexOf(c1, c2, c3); return resultByIndex[i]; } const T& map(const char* str) const { int i = index.indexOf(str); return resultByIndex[i]; } const T& map(const Triplet& t) const { int i = index.indexOf(&t.c[0]); return resultByIndex[i]; } T& mapNC(char c1, char c2, char c3) { int i = index.indexOf(c1, c2, c3); return resultByIndex[i]; } T& mapNC(const char* str) { int i = index.indexOf(str); return resultByIndex[i]; } T& mapNC(const Triplet& t) { int i = index.indexOf(&t.c[0]); return resultByIndex[i]; } T*& mapData() { return resultByIndex;} int getMapSize() const {return index.getIndexSize();} private: Index3To1 index; T* resultByIndex; }; enum DNATranslationRole { DNATranslationRole_Unknown, DNATranslationRole_Start, DNATranslationRole_Start_Alternative, DNATranslationRole_Stop, DNATranslationRole_Num }; class DNATranslation3to1Impl : public DNATranslation { public: DNATranslation3to1Impl(const QString& _id, const QString& _name, DNAAlphabet* src, DNAAlphabet* dst, const QList >& mapping, char defaultChar, const QMap >& roles); virtual ~DNATranslation3to1Impl(); virtual int translate(const char* src, int src_len, char* dst, int dst_capacity) const; virtual int translate(char* src_and_dst, int len) const; virtual bool isThree2One() const {return true;} char translate3to1(char c1, char c2, char c3) const { return index.map(c1, c2, c3); } QMap > getCodons() const {return roles;} bool isStartCodon(const char* s) const; bool isStartCodon(char c1, char c2, char c3) const; bool isStopCodon(const char* s) const; bool isStopCodon(char c1, char c2, char c3) const; bool isCodon(DNATranslationRole role, const char* s) const; bool isCodon(DNATranslationRole role, char c1, char c2, char c3) const; private: IndexedMapping3To1 index; QMap > roles; char** codons; int* cod_lens; }; inline bool DNATranslation3to1Impl::isCodon(DNATranslationRole role, char c1, char c2, char c3) const { assert(role >=0 && role < DNATranslationRole_Num); const int len = cod_lens[role]; const char* arr = codons[role]; for (int i = 0; i < len ; i+=3) { if (arr[i] == c1 && arr[i+1] == c2 && arr[i+2] == c3) return true; } return false; } inline bool DNATranslation3to1Impl::isStartCodon(const char* s) const { return isCodon(DNATranslationRole_Start, s[0],s[1],s[2]); } inline bool DNATranslation3to1Impl::isStartCodon(char c1, char c2, char c3) const { return isCodon(DNATranslationRole_Start, c1,c2,c3); } inline bool DNATranslation3to1Impl::isStopCodon(const char* s) const { return isCodon(DNATranslationRole_Stop, s[0],s[1],s[2]); } inline bool DNATranslation3to1Impl::isStopCodon(char c1, char c2, char c3) const { return isCodon(DNATranslationRole_Stop, c1,c2,c3); } inline bool DNATranslation3to1Impl::isCodon(DNATranslationRole role, const char* s) const { return isCodon(role, s[0], s[1], s[2]); } ////////////////////////////////////// 1->3 struct BackTranslationRules { public: int index[256]; QVarLengthArray map; }; enum BackTranslationMode { USE_MOST_PROBABLE_CODONS, USE_FREQUENCE_DISTRIBUTION }; class DNATranslation1to3Impl : public DNATranslation { public: DNATranslation1to3Impl(const QString& _id, const QString& _name, DNAAlphabet* src, DNAAlphabet* dst, const BackTranslationRules& rules); virtual ~DNATranslation1to3Impl(); virtual int translate(const char* src, int src_len, char* dst, int dst_capacity, BackTranslationMode mode) const; virtual int translate(const char* src, int src_len, char* dst, int dst_capacity) const; virtual int translate(char* src_and_dst, int len) const; virtual bool isOne2Three() const {return true;} private: BackTranslationRules index; }; } //namespace #endif ugene-1.9.8/src/corelibs/U2Core/src/datatype/PFMatrix.h0000644000175000017500000000603011651544331021251 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_POSITION_FREQUENCY_MATRIX_H_ #define _U2_POSITION_FREQUENCY_MATRIX_H_ #include #include #include #include #include #include namespace U2 { //info for JASPAR matrices, contained in matrix_list.txt class U2CORE_EXPORT JasparInfo { public: //default empty constructor JasparInfo(); //constructor from parsed data JasparInfo(const QMap& properties); //constructor from matrix_list.txt string JasparInfo(const QString& line); QString getProperty (const QString& name) const; QMap getProperties() const; private: QMap properties; }; //Type of Position frequency matrix enum PFMatrixType { PFM_MONONUCLEOTIDE, PFM_DINUCLEOTIDE }; //Position frequency matrix class U2CORE_EXPORT PFMatrix { public: //create empty matrix PFMatrix() : data(QVarLengthArray()), length(0), type(PFM_MONONUCLEOTIDE) {}; //create matrix from pre-counted data PFMatrix(const QVarLengthArray& data, const PFMatrixType type); //create matrix from alignment (without gaps) PFMatrix(const MAlignment& data, const PFMatrixType type); //create matrix from set of sequences with equal length PFMatrix(const QList& data, const PFMatrixType type); //get internal index of position in 1-dimensional array int index (int row, int column) const; //get length of matrix row int getLength () const; //get type of matrix: mono- or dinucleotide PFMatrixType getType() const; //get value at specified position int getValue (int row, int column) const; //set JASPAR info for matrix void setInfo (const JasparInfo& info); //get specified Jaspar property QString getProperty (const QString& propertyName) const; //get all Jaspar properties QMap getProperties() const; //convert dinucleotide matrix to mononucleotide one static PFMatrix convertDi2Mono(const PFMatrix& source); private: QVarLengthArray data; int length; PFMatrixType type; JasparInfo info; }; }//namespace #endif ugene-1.9.8/src/corelibs/U2Core/src/datatype/PWMatrix.h0000644000175000017500000000536111651544331021300 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_POSITION_WEIGHT_MATRIX_H_ #define _U2_POSITION_WEIGHT_MATRIX_H_ #include #include namespace U2 { //Type of Weight matrix enum PWMatrixType { PWM_MONONUCLEOTIDE, PWM_DINUCLEOTIDE }; class U2CORE_EXPORT UniprobeInfo { public: //default empty constructor UniprobeInfo(); //constructor from parsed data UniprobeInfo(const QMap& properties); //constructor from raw data UniprobeInfo(const QString& data); QString getProperty (const QString& name) const; QMap getProperties() const; private: QMap properties; }; //Position frequency matrix //Also known as PSSM - Position score-specific matrix class U2CORE_EXPORT PWMatrix { public: //create empty matrix PWMatrix() : data(QVarLengthArray()), length(0), type(PWM_MONONUCLEOTIDE) {}; //create matrix from pre-counted data PWMatrix(const QVarLengthArray &matrix, const PWMatrixType& type); //get internal index of position in 1-dimensional array int index (int row, int column) const; //get length of matrix row int getLength () const; //get type of matrix: mono- or dinucleotide PWMatrixType getType() const; //get value at specified position float getValue (int row, int column) const; //get sum of minimum values in each column float getMinSum () const; //get sum of maximum values in each column float getMaxSum () const; //set UniPROBE info for matrix void setInfo (const UniprobeInfo& info); //get specified UniPROBE property QString getProperty (const QString& propertyName) const; //get all UniPROBE properties QMap getProperties() const; private: QVarLengthArray data; int length; PWMatrixType type; float minSum, maxSum; UniprobeInfo info; }; }//namespace #endif ugene-1.9.8/src/corelibs/U2Core/src/datatype/AnnotationData.cpp0000644000175000017500000000400511651544331023016 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "AnnotationData.h" namespace U2 { QDataStream& operator>>(QDataStream& dataStream, TriState& state) { int st; dataStream >> st; switch (st) { case 0: state = TriState_Yes; break; case 1: state = TriState_No; break; default: state = TriState_Unknown; } return dataStream; } QDataStream& operator<<(QDataStream& dataStream, const TriState& state) { switch (state) { case TriState_Yes: return dataStream << 0; case TriState_No: return dataStream << 1; default: return dataStream << 2; } } QDataStream& operator>>(QDataStream& dataStream, U2Qualifier& q) { return dataStream >> q.name >> q.value; } QDataStream& operator<<(QDataStream& dataStream, const U2Qualifier& q) { return dataStream << q.name << q.value; } QDataStream& operator>>(QDataStream& dataStream, AnnotationData& ) { assert(0); return dataStream; // return dataStream >> data.name >> data.location >> data.qualifiers; } QDataStream& operator<<(QDataStream& dataStream, const AnnotationData& ) { assert(0); return dataStream; // return dataStream << data.name << data.location << data.qualifiers; } } //namespace ugene-1.9.8/src/corelibs/U2Core/src/datatype/DNATranslation.h0000644000175000017500000000736311651544331022412 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_DNA_TRANSLATION_H_ #define _U2_DNA_TRANSLATION_H_ #include #include namespace U2 { class DNAAlphabet; enum DNATranslationType { DNATranslationType_UNKNOWN, DNATranslationType_NUCL_2_NUCL, DNATranslationType_NUCL_2_COMPLNUCL, DNATranslationType_NUCL_2_AMINO, DNATranslationType_AMINO_2_AMINO, DNATranslationType_AMINO_2_NUCL, DNATranslationType_RAW_2_NUCL, DNATranslationType_RAW_2_AMINO }; class U2CORE_EXPORT BaseDNATranslationIds: public QObject { public: static const QString NUCL_DNA_DEFAULT_COMPLEMENT; static const QString NUCL_RNA_DEFAULT_COMPLEMENT; static const QString NUCL_DNA_EXTENDED_COMPLEMENT; static const QString NUCL_RNA_EXTENDED_COMPLEMENT; }; #define DNATranslationID(n) "NCBI-GenBank #"#n #define DNABackTranslationID(type, name) "BackTranslation/"#type"/"#name #define AMINO_TT_GOBJECT_HINT "AminoTT" class U2CORE_EXPORT DNATranslation { public: DNATranslation(const QString& _id, const QString& _name, DNAAlphabet* src, DNAAlphabet* dst); virtual ~DNATranslation(){} virtual int translate(const char* src, int src_len, char* dst, int dst_capacity) const = 0; virtual int translate(char* src_and_dst, int len) const = 0; const QString& getTranslationName() const {return name;} const QString& getTranslationId() const {return id;} DNATranslationType getDNATranslationType() const {return type;} DNAAlphabet* getSrcAlphabet() const {return srcAlphabet;} DNAAlphabet* getDstAlphabet() const {return dstAlphabet;} virtual bool isOne2One() const {return false;} virtual bool isThree2One() const {return false;} virtual bool isOne2Three() const {return false;} virtual QByteArray getOne2OneMapper() const { assert(0); return QByteArray(256, 0); } virtual char translate3to1(char c1, char c2, char c3) const { Q_UNUSED(c1); Q_UNUSED(c2); Q_UNUSED(c3); assert(0); return 0; } virtual char* translate1to3(char c) const { Q_UNUSED(c); assert(0); return NULL; } protected: DNATranslationType type; QString name; QString id; DNAAlphabet* srcAlphabet; DNAAlphabet* dstAlphabet; }; class U2CORE_EXPORT DNATranslationRegistry : public QObject { public: DNATranslationRegistry(QObject* p=0) :QObject(p){} ~DNATranslationRegistry(); QStringList getDNATranlations() const; QStringList getDNATranslationIds() const; void registerDNATranslation(DNATranslation* t); QList lookupTranslation(DNAAlphabet* srcAlphabet, DNATranslationType type); DNATranslation* lookupTranslation(DNAAlphabet* srcAlphabet, DNATranslationType type, const QString& id); DNATranslation* lookupTranslation(const QString& id); DNATranslation* lookupComplementTranslation(DNAAlphabet* srcAlphabet); private: QList translations; }; } //namespace #endif ugene-1.9.8/src/corelibs/U2Core/src/datatype/AnnotationData.h0000644000175000017500000000721711651544331022473 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_ANNOTATION_DATA_H_ #define _U2_ANNOTATION_DATA_H_ #include #include #include #include namespace U2 { class U2CORE_EXPORT AnnotationData : public QSharedData { public: QString name; U2Location location; QVector qualifiers; AnnotationData() {location = new U2LocationData();} inline AnnotationData& operator= ( const AnnotationData & a ); inline void removeAllQualifiers(const QString& name, QStringList& values); inline void findQualifiers(const QString& name, QVector& res) const; inline QString findFirstQualifierValue(const QString& name) const; bool isJoin() const {return location->isJoin();} bool isOrder() const {return location->isOrder();} U2Strand getStrand() const {return location->strand;} void setStrand(U2Strand s) {location->strand = s;} U2LocationOperator getLocationOperator() const {return location->op;} void setLocationOperator(U2LocationOperator o) {location->op = o;} const QVector& getRegions() const {return location->regions;} }; typedef QSharedDataPointer SharedAnnotationData; U2CORE_EXPORT QDataStream& operator>>(QDataStream& dataStream, TriState& state); U2CORE_EXPORT QDataStream& operator<<(QDataStream& dataStream, const TriState& state); U2CORE_EXPORT QDataStream& operator>>(QDataStream& dataStream, U2Qualifier& q); U2CORE_EXPORT QDataStream& operator<<(QDataStream& dataStream, const U2Qualifier& q); U2CORE_EXPORT QDataStream& operator>>(QDataStream& dataStream, AnnotationData& data); U2CORE_EXPORT QDataStream& operator<<(QDataStream& dataStream, const AnnotationData& data); AnnotationData& AnnotationData::operator= ( const AnnotationData & a ) { name = a.name; location = a.location; qualifiers = a.qualifiers; return *this; } void AnnotationData::removeAllQualifiers(const QString& name, QStringList& values) { for (int i=qualifiers.size(); --i>=0;) { const U2Qualifier& q = qualifiers.at(i); if (q.name == name) { values.append(q.value); qualifiers.remove(i); } } } void AnnotationData::findQualifiers(const QString& name, QVector& res) const { foreach (const U2Qualifier& q, qualifiers) { if (q.name == name) { res.append(q); } } } QString AnnotationData::findFirstQualifierValue(const QString& name) const { foreach (const U2Qualifier& q, qualifiers) { if (q.name == name) { return q.value; } } return QString::null; } }//namespace Q_DECLARE_METATYPE(U2::AnnotationData); Q_DECLARE_METATYPE(U2::SharedAnnotationData); Q_DECLARE_METATYPE(QList); #endif ugene-1.9.8/src/corelibs/U2Core/src/datatype/DNATranslation.cpp0000644000175000017500000001065711651544331022745 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "DNATranslation.h" #include "DNAAlphabet.h" namespace U2 { DNATranslation::DNATranslation(const QString& _id, const QString& _name, DNAAlphabet* src, DNAAlphabet* dst) { name = _name; id = _id; srcAlphabet = src; dstAlphabet = dst; assert(srcAlphabet!=NULL && dstAlphabet!=NULL); DNAAlphabetType srcType = srcAlphabet->getType(); DNAAlphabetType dstType = dstAlphabet->getType(); type = DNATranslationType_UNKNOWN; if (srcType == DNAAlphabet_NUCL) { switch(dstType) { case DNAAlphabet_NUCL : type = dstAlphabet == srcAlphabet ? DNATranslationType_NUCL_2_COMPLNUCL : DNATranslationType_NUCL_2_NUCL; break; case DNAAlphabet_AMINO: type = DNATranslationType_NUCL_2_AMINO; break; default: assert(0); break; } } else if (srcType == DNAAlphabet_AMINO) { switch(dstType) { case DNAAlphabet_AMINO : type = DNATranslationType_AMINO_2_AMINO; break; case DNAAlphabet_NUCL : type = DNATranslationType_AMINO_2_NUCL; break; default: assert(0); break; } } else if (srcType == DNAAlphabet_RAW) { switch(dstType) { case DNAAlphabet_NUCL : type = DNATranslationType_RAW_2_NUCL; break; case DNAAlphabet_AMINO: type = DNATranslationType_RAW_2_AMINO; break; default: assert(0); break; } } assert(type!=DNATranslationType_UNKNOWN); } ////////////////////////////////////////////////////////////////////////// /// Registry QStringList DNATranslationRegistry::getDNATranlations() const { QStringList l; foreach(DNATranslation* t, translations) { l<getTranslationName(); } return l; } QStringList DNATranslationRegistry::getDNATranslationIds() const { QStringList l; foreach(DNATranslation* t, translations) { l<getTranslationId(); } return l; } void DNATranslationRegistry::registerDNATranslation(DNATranslation* t) { translations.push_back(t); } DNATranslationRegistry::~DNATranslationRegistry() { foreach(DNATranslation* t, translations) { delete t; } translations.clear(); } QList DNATranslationRegistry::lookupTranslation(DNAAlphabet* srcAlphabet, DNATranslationType type) { QList res; foreach(DNATranslation* t, translations) { if (t->getSrcAlphabet() == srcAlphabet && t->getDNATranslationType() == type) { res.append(t); } } return res; } DNATranslation* DNATranslationRegistry::lookupTranslation(DNAAlphabet* srcAlphabet, DNATranslationType type, const QString& id) { foreach(DNATranslation* t, translations) { if (t->getTranslationId() == id && t->getSrcAlphabet() == srcAlphabet && t->getDNATranslationType() == type) { return t; } } return NULL; } DNATranslation* DNATranslationRegistry::lookupTranslation(const QString& id) { foreach(DNATranslation* t, translations) { if (t->getTranslationId() == id) { return t; } } return NULL; } DNATranslation* DNATranslationRegistry::lookupComplementTranslation(DNAAlphabet* srcAlphabet) { assert(srcAlphabet->isNucleic()); QList complTs = lookupTranslation(srcAlphabet, DNATranslationType_NUCL_2_COMPLNUCL); if (complTs.isEmpty()) { return NULL; } return complTs.first(); } }//namespace ugene-1.9.8/src/corelibs/U2Core/src/datatype/DNAInfo.cpp0000644000175000017500000000611411651544331021333 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "DNAInfo.h" namespace U2 { const QString DNAInfo::LOCUS = "LOCUS"; const QString DNAInfo::DEFINITION = "DEFINITION"; const QString DNAInfo::ACCESSION = "ACCESSION"; const QString DNAInfo::VERSION = "VERSION"; const QString DNAInfo::PROJECT = "PROJECT"; const QString DNAInfo::SEGMENT = "SEGMENT"; const QString DNAInfo::SOURCE = "SOURCE"; const QString DNAInfo::KEYWORDS = "KEYWORDS"; const QString DNAInfo::REFERENCE = "REFERENCE"; const QString DNAInfo::AUTHORS = "AUTHORS"; const QString DNAInfo::CONSRTM = "CONSRTM"; const QString DNAInfo::TITLE = "TITLE"; const QString DNAInfo::JOURNAL = "JOURNAL"; const QString DNAInfo::MEDLINE = "MEDLINE"; const QString DNAInfo::PUBMED = "PUBMED"; const QString DNAInfo::REMARK = "REMARK"; const QString DNAInfo::COMMENT = "COMMENT"; const QString DNAInfo::FEATURES = "FEATURES"; const QString DNAInfo::CONTIG = "CONTIG"; const QString DNAInfo::ORIGIN = "ORIGIN"; const QString DNAInfo::CHAIN_ID = "CHAIN_ID"; const QString DNAInfo::DATE = "DATE"; const QString DNAInfo::FASTA_HDR = "FASTA_HDR"; const QString DNAInfo::EMBL_ID = "EMBL_ID"; const QString DNAInfo::ID = "ID"; QString DNAInfo::getPrimaryAccession( const QVariantMap& vm) { if (vm.contains(ACCESSION)) { QVariant v = vm.value(ACCESSION); assert(v.type() == QVariant::StringList); QStringList l = v.toStringList(); assert(!l.isEmpty()); return l.isEmpty() ? v.toString() : l.first(); } return QString(); } QString DNAInfo::getContig( const QVariantMap& vm) { if (vm.contains(CONTIG)) { QVariant v = vm.value(CONTIG); assert(v.type() == QVariant::StringList); QStringList l = v.toStringList(); assert(!l.isEmpty()); return l.isEmpty() ? v.toString() : l.join(QString()); } return QString(); } QString DNAInfo::getName( const QVariantMap& vm) { QString name; if (vm.contains(LOCUS)) { DNALocusInfo loi = vm.value(LOCUS).value(); name = loi.name; } if (name.isEmpty() && vm.contains(ID)) { name = vm.value(ID).toString(); } if (name.isEmpty() && vm.contains(ACCESSION)) { name = getPrimaryAccession(vm); } return name; } }//namespace ugene-1.9.8/src/corelibs/U2Core/src/datatype/PhyTree.h0000644000175000017500000000436011651544331021143 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_PHYTREE_H_ #define _U2_PHYTREE_H_ #include #include #include #include #include namespace U2 { class PhyBranch; class PhyNode; class U2CORE_EXPORT PhyTreeData : public QSharedData { public: PhyTreeData(); PhyTreeData(const PhyTreeData& other); ~PhyTreeData(); QList collectNodes() const; void validate() const; void print() const; PhyNode* rootNode; }; typedef QSharedDataPointer PhyTree; class U2CORE_EXPORT PhyNode { public: PhyNode(); void validate(QList& track) const; bool isConnected(const PhyNode* node) const; static PhyBranch* addBranch(PhyNode* node1, PhyNode* node2, double distance); static void removeBranch(PhyNode* node1, PhyNode* node2); PhyNode* clone() const; void addToTrack(QSet& track) const; QString name; QList branches; bool equals(PhyNode* other); void print(QList& nodes, int distance, int tab); void dumpBranches() const; ~PhyNode(); }; class U2CORE_EXPORT PhyBranch { public: PhyBranch(); PhyNode* node1; PhyNode* node2; double distance; }; class U2CORE_EXPORT PhyTreeUtils { public: static int getNumSeqsFromNode(const PhyNode *node, const QSet& names); }; }//namespace #endif ugene-1.9.8/src/corelibs/U2Core/src/datatype/DNASequence.h0000644000175000017500000000366011651544331021660 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_DNA_SEQUENCE_H_ #define _U2_DNA_SEQUENCE_H_ #include #include "DNAInfo.h" #include "DNAQuality.h" #include namespace U2 { class DNAAlphabet; class U2CORE_EXPORT DNASequence { public: DNASequence(const QString& name, const QByteArray& s = QByteArray(), DNAAlphabet* a = NULL); DNASequence(const QByteArray& s = QByteArray(), DNAAlphabet* a = NULL) : seq(s), alphabet(a), circular(false), quality(NULL) {} QVariantMap info; QByteArray seq; DNAAlphabet* alphabet; bool circular; DNAQuality quality; QString getName() const {return DNAInfo::getName(info);} void setName(const QString& name); bool isNull() const {return !alphabet && seq.length() == 0;} int length() const {return seq.length();} bool hasQualityScores() const {return (!quality.isEmpty()); } const char* constData() const {return seq.constData();} const QByteArray &constSequence() const {return seq;} }; }//namespace Q_DECLARE_METATYPE(U2::DNASequence) Q_DECLARE_METATYPE(QList) #endif ugene-1.9.8/src/corelibs/U2Core/src/datatype/DNAQuality.h0000644000175000017500000000326111651544331021535 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_DNA_QUALITY_H_ #define _U2_DNA_QUALITY_H_ #include #include #include namespace U2 { enum DNAQualityType { DNAQualityType_Sanger, DNAQualityType_Illumina, DnaQualityType_Solexa }; class U2CORE_EXPORT DNAQuality { public: DNAQuality() : type (DNAQualityType_Sanger) {} DNAQuality(const QByteArray& qualScore, DNAQualityType type = DNAQualityType_Sanger); QByteArray qualCodes; DNAQualityType type; bool isEmpty() const { return qualCodes.isEmpty(); } int getValue(int pos) const; static char encode(int val, DNAQualityType type); static QString getDNAQualityNameByType(DNAQualityType t); static DNAQualityType getDNAQualityTypeByName(const QString& name); static QStringList getDNAQualityTypeNames(); }; }//namespace #endif ugene-1.9.8/src/corelibs/U2Core/src/datatype/DIProperties.h0000644000175000017500000000407311651544331022135 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_DI_PROPERTIES_H_ #define _U2_DI_PROPERTIES_H_ #include #include #include #include #include namespace U2 { class U2CORE_EXPORT DiProperty : public QObject { Q_OBJECT public: static int inline index(char c1, char c2); static int inline index(char c); static char inline fromIndex(int index); static char inline fromIndexLo(int index); static char inline fromIndexHi(int index); }; int DiProperty::index(char n1, char n2) { int idx = (index(n1) << 2) + index(n2); assert(idx >= 0 && idx < 16); return idx; } int DiProperty::index(char c) { if (c == 'A') { return 0; } if (c == 'C') { return 1; } if (c == 'G') { return 2; } if (c == 'T' || c == 'U') {return 3;} return 0; //default is 'A' } char DiProperty::fromIndex(int index) { assert (index >=0); assert (index < 4); char a[] = "ACGT"; return a[index]; } char DiProperty::fromIndexLo(int index) { assert (index >= 0); assert (index < 16); return fromIndex(index & 3); } char DiProperty::fromIndexHi(int index) { assert (index >= 0); assert (index < 16); return fromIndex(index >> 2); } }//namespace #endif ugene-1.9.8/src/corelibs/U2Core/src/datatype/Matrix44.h0000644000175000017500000000277411651544331021206 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_MATRIX_44_H_ #define _U2_MATRIX_44_H_ #include #include namespace U2 { class U2CORE_EXPORT Matrix44 { public: Matrix44(); Matrix44(const float *data); Matrix44(const Matrix44 &other); Matrix44& operator= (const Matrix44 &other); void loadZero(); void loadIdentity(); void transpose(); float* data(); const float* data() const; float& operator[] (unsigned int i); float operator[] (unsigned int i) const; void load(const QVariantList &values); QVariantList store(); private: QVector m; }; // class Matrix44 } // namespace U2 #endif // #ifndef _U2_MATRIX_44_H_ ugene-1.9.8/src/corelibs/U2Core/src/datatype/DNAAlphabetRegistryImpl.h0000644000175000017500000000423611651544331024203 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _DNA_ALPHABET_REGISTRY_IMPL_H_ #define _DNA_ALPHABET_REGISTRY_IMPL_H_ #include namespace U2 { class DNATranslationRegistry; class U2CORE_EXPORT DNAAlphabetRegistryImpl : public DNAAlphabetRegistry { Q_OBJECT public: DNAAlphabetRegistryImpl(DNATranslationRegistry* tr); ~DNAAlphabetRegistryImpl(); virtual bool registerAlphabet(DNAAlphabet* a); virtual void unregisterAlphabet(DNAAlphabet* a); virtual DNAAlphabet* findById(const QString id) const; virtual QList getRegisteredAlphabets() const {return alphabets;} virtual DNAAlphabet* findAlphabet(const QByteArray& seq) const; virtual QList findAlphabets(const QByteArray& seq) const; virtual QList findAlphabets(const QByteArray& seq, const QVector& regionsToProcess, bool onlyOne) const; private: void initBaseAlphabets(); void initBaseTranslations(); void reg4tables(const char* amino, const char* role, const char* n1, const char* n2, const char* n3, const QString& id, const QString& name); void regPtables(const char* amino, const int* prob, const char* n1, const char* n2, const char* n3, const QString& id, const QString& name); QList alphabets; DNATranslationRegistry* treg; }; } //namespace #endif ugene-1.9.8/src/corelibs/U2Core/src/datatype/DNAAlphabetUtils.h0000644000175000017500000001430611651544331022650 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _DNA_ALPHABET_UTILS_H_ #define _DNA_ALPHABET_UTILS_H_ #include #include #include namespace U2 { class DNAAlphabetComparator { public: DNAAlphabetComparator(DNAAlphabet* _al1, DNAAlphabet* _al2) : al1(_al1), al2(_al2) { assert(al1->getType() == al2->getType()); } virtual ~DNAAlphabetComparator(){} virtual bool equals(char c1, char c2) const = 0; DNAAlphabet *al1; DNAAlphabet *al2; }; //NOTE: use comparators as template params to optimize comparison with virtual call // compares symbols exactly, 'N' does not match any symbol ('N'!='N') class ExactDNAAlphabetComparatorN0 : public DNAAlphabetComparator { public: ExactDNAAlphabetComparatorN0(DNAAlphabet* _al1, DNAAlphabet* _al2) : DNAAlphabetComparator(_al1, _al2){assert(al1==al2);} virtual bool equals(char c1, char c2) const {return c1 == c2 && c1!='N' && c2!='N';} }; // compares symbols, 'N' does not match any symbol except 'N' class ExactDNAAlphabetComparatorStrict : public DNAAlphabetComparator { public: ExactDNAAlphabetComparatorStrict(DNAAlphabet* _al1, DNAAlphabet* _al2) : DNAAlphabetComparator(_al1, _al2){assert(al1==al2);} virtual bool equals(char c1, char c2) const {return c1 == c2;} }; // compares symbols, 'N' matches any symbol if found in first sequence. N in the second sequence matches 'N' only class ExactDNAAlphabetComparatorN1M: public DNAAlphabetComparator { public: ExactDNAAlphabetComparatorN1M(DNAAlphabet* _al1, DNAAlphabet* _al2) : DNAAlphabetComparator(_al1, _al2){assert(al1==al2);} virtual bool equals(char c1, char c2) const {return c1 == c2 || c1 == 'N';} }; // compares symbols, 'N' matches any symbol class ExactDNAAlphabetComparatorN1M_N2M : public DNAAlphabetComparator { public: ExactDNAAlphabetComparatorN1M_N2M(DNAAlphabet* _al1, DNAAlphabet* _al2) : DNAAlphabetComparator(_al1, _al2){assert(al1==al2);} virtual bool equals(char c1, char c2) const {return c1 == c2 || c1 == 'N' || c2 == 'N';} }; #define DNA_AL_EX_INDEX_SIZE ('Z'- ' ' + 1) // compares extended alphabet symbols, 'N' matches any symbol class ExtendedDNAlphabetComparator : public DNAAlphabetComparator { public: ExtendedDNAlphabetComparator(DNAAlphabet* _al1, DNAAlphabet* _al2) : DNAAlphabetComparator(_al1, _al2) { assert(al1->isNucleic() && al2->isNucleic()); assert(al1->getId() == BaseDNAAlphabetIds::NUCL_DNA_EXTENDED() || al2->getId() == BaseDNAAlphabetIds::NUCL_DNA_EXTENDED() || al1->getId() == BaseDNAAlphabetIds::NUCL_RNA_DEFAULT() || al2->getId() == BaseDNAAlphabetIds::NUCL_RNA_DEFAULT() || al1->getId() == BaseDNAAlphabetIds::NUCL_RNA_EXTENDED() || al2->getId() == BaseDNAAlphabetIds::NUCL_RNA_EXTENDED() ); buildIndex(); } virtual bool equals(char c1, char c2) const { if (c1 == c2) { return true; } int a1Mask = getMatchMask(c1); int a2Mask = getMatchMask(c2); bool match = (a1Mask & a2Mask) != 0; return match; } private: inline void buildIndex(); inline int getMatchMask(char c) const; inline int bit(char c) const {assert(c>='A' && c<='Z'); return c - 'A' + 1;} int index[DNA_AL_EX_INDEX_SIZE]; }; void ExtendedDNAlphabetComparator::buildIndex() { /* R = G or A Y = C or T M = A or C K = G or T S = G or C W = A or T B = not A (C or G or T) D = not C (A or G or T) H = not G (A or C or T) V = not T (A or C or G) N = A or C or G or T */ qFill(index, index + DNA_AL_EX_INDEX_SIZE, 0); index['A'-' '] = (1<=0 && igetType() == DNAAlphabet_RAW) { rc = true; } else { rc = TextUtils::fits(al->getMap(), ba.constData(), ba.size()); } return rc; } static bool matches(DNAAlphabet* al, const QByteArray& ba, const U2Region& r) { GTIMER(cnt,tm,"DNAAlphabetUtils::matches(al,seq,reg)"); bool rc = false; if (al->getType() == DNAAlphabet_RAW) { rc = true; } else { rc = TextUtils::fits(al->getMap(), ba.constData() + r.startPos, r.length); } return rc; } }; }//namespace #endif ugene-1.9.8/src/corelibs/U2Core/src/datatype/AnnotationSettings.h0000644000175000017500000000447511651544331023425 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_ANNOTATION_SETTINGS_H_ #define _U2_ANNOTATION_SETTINGS_H_ #include #include #include namespace U2 { class Settings; class Annotation; class U2CORE_EXPORT AnnotationSettings { public: AnnotationSettings(); AnnotationSettings(const QString& name, bool amino, const QColor& color, bool visible); bool operator==(const AnnotationSettings* as) const {return equals(as);} bool equals(const AnnotationSettings* as) const; QString name; QColor color; bool amino; bool visible; QStringList nameQuals; //a value based on qualifiers value will be used instead of the annotation name }; class U2CORE_EXPORT AnnotationSettingsRegistry : public QObject { Q_OBJECT public: AnnotationSettingsRegistry(const QList& predefined); ~AnnotationSettingsRegistry(); QStringList getAllSettings() const; AnnotationSettings* getAnnotationSettings(const QString& name); AnnotationSettings* getAnnotationSettings(Annotation* a); // persistent==true -> save settings to file, ==false -> this session only void changeSettings(const QList& settings, bool saveAsPersistent); signals: void si_annotationSettingsChanged(const QStringList& changedSettings); private: void read(); void save(); QHash persistentMap; QHash transientMap; }; }//namespace #endif ugene-1.9.8/src/corelibs/U2Core/src/datatype/MAlignment.h0000644000175000017500000002510711651544331021620 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_MALIGNMENT_H_ #define _U2_MALIGNMENT_H_ #include #include #include "MAlignmentInfo.h" #include "DNAQuality.h" #include namespace U2 { class DNAAlphabet; // Default name for malignment #define MA_OBJECT_NAME QString("Multiple alignment") // Gap character #define MAlignment_GapChar '-' class MAlignment; //A row in multiple alignment structure class U2CORE_EXPORT MAlignmentRow { friend class MAlignment; public: MAlignmentRow(const QString& _name = QString(), const QByteArray& _sequence = QByteArray(), int _offset = 0) : name(_name), sequence(_sequence), offset(_offset) {} // Name of the row const QString& getName() const {return name;} // unpacked row version: array size == length; // All leading & trailing gaps are added to the result array // Length must be >= packed array length QByteArray toByteArray(int length) const; // Packed version. Client must apply offsets manually const QByteArray& getCore() const {return sequence;} // Start offset of the packed data int getCoreStart() const {return offset;} // Gets the length of the packed sequence int getCoreLength() const {return sequence.size();} // Return true if the packed sequence has DNA quality scores bool hasQuality() const { return (!dnaQuality.isEmpty()); } // Returns the DNA quality of the packed sequence const DNAQuality& getCoreQuality() const { return dnaQuality; } // End offset of the packed data. Not inclusive int getCoreEnd() const {return getCoreStart() + getCoreLength();} // Sets the packed sequence value and offset void setSequence(const QByteArray& coreSequence, int offset = 0); // Sets the DNA quality for the packed sequence void setQuality(const DNAQuality& quality); // Returns symbol in the specified position inline char chatAt(int pos) const; // Compares 2 rows. Rows are equal if their offsets, packed and names are equal inline bool operator!=(const MAlignmentRow& r) const; bool operator==(const MAlignmentRow& r) const; // The first non-gap character position in the row // - 1 if not found int getFirstNonGapIdx() const; // The last non-gap character in the row // -1 if not found int getLastNonGapIdx() const; // Crops the row -> keeps only specified region in the row void crop(int startPos, int length); // Returns new row of specified length, started with startPos MAlignmentRow mid(int startPos, int length) const; // Adds anotherRow data to this raw void append(const MAlignmentRow& anotherRow, int lengthBefore); // Inserts single character 'c' into specified position. void insertChar(int pos, char c); // Inserts 'count' characters 'c' into specified position. void insertChars(int pos, char c, int count); // Inserts string 'str' of length 'len' into specified position. void insertChars(int pos, const char* str, int len); // Removes single character in the specified position void removeChar(int pos) {removeChars(pos, 1);} // Removes up to n characters starting from the specified position void removeChars(int pos, int n); // Removes chars in specified positions void removeChars(const QList& positions); void setName(const QString& name); // Tries to minimize packed data length by removing leading & trailing gaps in packed data. // Do not change the content of the item. // Return true if succeed bool minimize(); // Removes all gaps. Sets offset to 0 // Returns true if changed bool simplify(); private: //helper method, common code for crop & mid static void crop(MAlignmentRow* row, int startPos, int length); // Row name QString name; // Row data, starts with offset QByteArray sequence; // DNA sequence quality scores DNAQuality dnaQuality; // Offset of the first char in 'sequence' int offset; }; // Multiple sequence alignment class U2CORE_EXPORT MAlignment { public: // Constructs new alignment. // The length of the alignment == max row length in the list MAlignment(const QString& name = QString(), DNAAlphabet* al = NULL, const QList& rows = QList()); // Clears the alignment. Makes alignment length == 0. Doesn't change alphabet or name void clear(); // Returns the name of the alignment QString getName() const { return MAlignmentInfo::getName(info); } // Sets the name of the alignment void setName( const QString& newName ) {MAlignmentInfo::setName( info, newName );} // Returns alignment alphabet DNAAlphabet* getAlphabet() const {return alphabet;} void setAlphabet(DNAAlphabet* al); QVariantMap getInfo() const {return info;} void setInfo(const QVariantMap& _info) {info = _info;} // Returns true if alignment length is 0 bool isEmpty() const {return getLength() == 0;} // Returns the length of the alignment int getLength() const { return length; } // Sets alignment length void setLength(int len); // Returns number of sequences (rows) in the alignment int getNumRows() const {return rows.size();} // Returns true if alignment contains gaps bool hasGaps() const; // Recomputes the length of the alignment and makes it as minimal as possible by // removing all leading and trailing gap columns // Returns true if the alignment is modified bool trim(); // Removes all gaps from all columns in the alignment // Returns true if alignment was changed bool simplify(); // Modifies the alignment by keeping data from the specified region and rows only bool crop(const U2Region& region, const QSet& rowNames); // creates sub alignment from the alignment. Do not trims the result MAlignment mid(int start, int len) const; // Adds new row to the alignment // Tries to trim the row if possible to avoid alignment change // Do not trim the original alignment // Note: debug version ensures that row alphabet is the same with alignment alphabet // If rowIndex == -1 -> appends row to the alignment void addRow(const MAlignmentRow& row, int rowIndex = -1); // Removes row from alignment. Does not change the length void removeRow(int rowIndex); // Joins two alignments. Alignments must have the same size MAlignment& operator+=(const MAlignment& ma); // Compares two alignments. Only alignments of the same length and content can be equal bool operator!=(const MAlignment& ma) const; // Returns a symbol in the specified sequence and position inline char charAt(int seqNum, int pos) const; // Estimates memory size consumed by alignment structure in bytes int estimateMemorySize() const; // Returns row of the alignment const MAlignmentRow& getRow(int row) const {return rows.at(row);} // Returns all rows in the alignment const QList& getRows() const {return rows;} // Returns all rows in the alignment QStringList getRowNames() const; // Inserts single character 'c' into specified position. // Can increase the overall alignment length void insertChar(int row, int pos, char c); // Inserts 'count' characters 'c' into specified position. // Can increase the overall alignment length void insertChars(int row, int pos, char c, int count); // Inserts string 'str' of length 'len' into specified position. // Can increase the overall alignment length void insertChars(int row, int pos, const char* str, int len); void appendChars(int row, const char* str, int len); // Removes single character in the specified position void removeChar(int row, int pos) { removeChars(row, pos, 1); } // Removes up to n characters starting from the specified position void removeChars(int row, int pos, int n = 1); // Removes all columns from the row void removeChars(int row, const QList& columns); // Removes region from the alignment. // If 'removeEmptyRows' is true, removes all empty rows from the processed region void removeRegion(int startPos, int startRow, int nBases, int nRows, bool removeEmptyRows); // Renames the row void renameRow(int row, const QString& name); // Sets the row sequence void setRowSequence(int row, const QByteArray& sequence, int offset = 0); // Replaces chars in the row void replaceChars(int row, char origChar, char resultChar); // Converts all rows sequences to upper case void toUpperCase(); // Sorts rows by name void sortRowsByName(bool asc = true); // Shifts a selection of consequent rows void moveRowsBlock( int startRow, int numRows, int delta ); // Checks model consistency void check() const; private: // Computes minimal length to hold the whole alignment int calculateMinLength() const; // Alphabet for all sequences in alignment DNAAlphabet* alphabet; // Sequences in the alignment QList rows; // The length of the alignment int length; // Additional alignment info QVariantMap info; private: static bool registerMeta; }; inline char MAlignment::charAt(int seqNum, int pos) const { const MAlignmentRow& mai = rows[seqNum]; char c = mai.chatAt(pos); return c; } inline char MAlignmentRow::chatAt(int pos) const { int seqPos = pos - offset; if (seqPos < 0 || seqPos >= sequence.size()) { return MAlignment_GapChar; } return sequence.at(seqPos); } inline bool MAlignmentRow::operator!=(const MAlignmentRow& row) const { return !(*this == row); } }//namespace Q_DECLARE_METATYPE(U2::MAlignment) #endif ugene-1.9.8/src/corelibs/U2Core/src/datatype/BaseTranslations.cpp0000644000175000017500000005552511651544331023403 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "DNAAlphabetRegistryImpl.h" #include "DNATranslationImpl.h" #include #include #include #include #include #include #include namespace U2 { const QString BaseDNATranslationIds::NUCL_DNA_DEFAULT_COMPLEMENT("NUCL_DNA_DEFAULT_COMPLEMENT"); const QString BaseDNATranslationIds::NUCL_RNA_DEFAULT_COMPLEMENT("NUCL_RNA_DEFAULT_COMPLEMENT"); const QString BaseDNATranslationIds::NUCL_DNA_EXTENDED_COMPLEMENT("NUCL_DNA_EXTENDED_COMPLEMENT"); const QString BaseDNATranslationIds::NUCL_RNA_EXTENDED_COMPLEMENT("NUCL_RNA_EXTENDED_COMPLEMENT"); #define DATA_DIR_KEY QString("back_translation") #define DATA_FILE_KEY QString("back_translation/lastFile") #define DEFAULT_ORGANISM_FILE QString("tables.xml") static void fill3To1(QList >& map, QMap >& codons, const DNAAlphabet* srcAl, const DNAAlphabet* dstAl, const char* amino, const char* role, const char* n1, const char* n2, const char* n3) { assert(srcAl->isNucleic()); Q_UNUSED(srcAl); assert(dstAl->isAmino()); Q_UNUSED(dstAl); int len = strlen(amino); assert(len == (int)strlen(role) && len == (int)strlen(n1) && len == (int)strlen(n2) && len == (int)strlen(n3)); for(int i=0; icontains(res)); assert(srcAl->contains(c1)); assert(srcAl->contains(c2)); assert(srcAl->contains(c3)); Triplet t(c1, c2, c3); Mapping3To1 m(t, res); map.append(m); if (role[i] == 'M') codons[DNATranslationRole_Start].append(t); else if (role[i] == 'L') codons[DNATranslationRole_Start_Alternative].append(t); else if (amino[i] == '*') codons[DNATranslationRole_Stop].append(t); } } static void fill1To3(BackTranslationRules& map, const DNAAlphabet* srcAl, const DNAAlphabet* dstAl, const char* amino, const int* prob, const char* n1, const char* n2, const char* n3) { assert(srcAl->isAmino()); Q_UNUSED(srcAl); assert(dstAl->isNucleic()); Q_UNUSED(dstAl); TripletP t('N', 'N', 'N', 100); map.map.append(t); map.index['-'] = map.map.size(); TripletP dash('-', '-', '-', 100); map.map.append(dash); int len = strlen(amino); assert(len == (int)strlen(n1) && len == (int)strlen(n2) && len == (int)strlen(n3)); QByteArray alph = srcAl->getAlphabetChars(); QList v; int sump; foreach (char c, alph) { v.clear(); sump = 0; for(int i=0; icontains(src)); assert(dstAl->contains(c1)); assert(dstAl->contains(c2)); assert(dstAl->contains(c3)); assert((0 <= p) && (p <= 100)); #endif TripletP t(c1, c2, c3, p); v.append(t); } if (v.empty()) { if (c != '-') { map.index[(int)c] = 0; map.index[(int)c] = 1; } } else { map.index[(int)c] = map.map.size(); qSort(v); v.first().p += (100 - sump); foreach (TripletP t, v) { map.map.append(t); } } } } static bool parseCutFile(const QString& url, char* amino, int* prob, char* n1, char* n2, char* n3) { QFile organismFile(url); if (organismFile.open(QFile::ReadOnly)) { QTextStream data(&organismFile); QString line; QStringList parsedData; QByteArray buf(4, '\0'); int pos = 0; bool ok = true; do { line = data.readLine(); if (line.isEmpty() || line.startsWith("#")) continue; parsedData = line.split(QRegExp("\\s"), QString::SkipEmptyParts); if ( parsedData.size() != 5 ) return false; if ( parsedData[0].length() != 3 ) return false; buf = parsedData[0].toAscii(); n1[pos] = buf[0]; n2[pos] = buf[1]; n3[pos] = buf[2]; if ( parsedData[1].length() != 1 ) return false; buf = parsedData[1].toAscii(); amino[pos] = buf[0]; double pr = parsedData[2].toDouble(&ok); if (!ok) return false; prob[pos] = qRound(pr); pos++; amino[pos] = n1[pos] = n2[pos] = n3[pos] = '\0'; } while (!line.isNull()); return true; } return false; } void DNAAlphabetRegistryImpl::reg4tables(const char* amino, const char* role, const char* n1, const char* n2, const char* n3, const QString& id, const QString& name) { { DNAAlphabet* srcAlphabet = findById(BaseDNAAlphabetIds::NUCL_DNA_DEFAULT()); DNAAlphabet* dstAlphabet = findById(BaseDNAAlphabetIds::AMINO_DEFAULT()); QList > map; QMap > codons; fill3To1(map, codons, srcAlphabet, dstAlphabet, amino, role, n1, n2, n3); DNATranslation* t = new DNATranslation3to1Impl(id, name, srcAlphabet, dstAlphabet, map, 'X', codons); treg->registerDNATranslation(t); } //extended NUCL DNA to AMINO -> all extended symbols lead to "unknown" { DNAAlphabet* srcAlphabet = findById(BaseDNAAlphabetIds::NUCL_DNA_EXTENDED()); DNAAlphabet* dstAlphabet = findById(BaseDNAAlphabetIds::AMINO_DEFAULT()); QList > map; QMap > codons; fill3To1(map, codons, srcAlphabet, dstAlphabet, amino, role, n1, n2, n3); DNATranslation* t = new DNATranslation3to1Impl(id, name, srcAlphabet, dstAlphabet, map, 'X', codons); treg->registerDNATranslation(t); } QByteArray an1(n1); const char* rn1 = an1.replace('T', 'U'); QByteArray an2(n2); const char* rn2 = an2.replace('T', 'U'); QByteArray an3(n3); const char* rn3 = an3.replace('T', 'U'); { DNAAlphabet* srcAlphabet = findById(BaseDNAAlphabetIds::NUCL_RNA_DEFAULT()); DNAAlphabet* dstAlphabet = findById(BaseDNAAlphabetIds::AMINO_DEFAULT()); QList > map; QMap > codons; fill3To1(map, codons, srcAlphabet, dstAlphabet, amino, role, rn1, rn2, rn3); DNATranslation* t = new DNATranslation3to1Impl(id, name, srcAlphabet, dstAlphabet, map, 'X', codons); treg->registerDNATranslation(t); } { DNAAlphabet* srcAlphabet = findById(BaseDNAAlphabetIds::NUCL_RNA_EXTENDED()); DNAAlphabet* dstAlphabet = findById(BaseDNAAlphabetIds::AMINO_DEFAULT()); QList > map; QMap > codons; fill3To1(map, codons, srcAlphabet, dstAlphabet, amino, role, rn1, rn2, rn3); DNATranslation* t = new DNATranslation3to1Impl(id, name, srcAlphabet, dstAlphabet, map, 'X', codons); treg->registerDNATranslation(t); } } void DNAAlphabetRegistryImpl::regPtables(const char* amino, const int* prob, const char* n1, const char* n2, const char* n3, const QString& id, const QString& name) { { DNAAlphabet* srcAlphabet = findById(BaseDNAAlphabetIds::AMINO_DEFAULT()); DNAAlphabet* dstAlphabet = findById(BaseDNAAlphabetIds::NUCL_DNA_DEFAULT()); BackTranslationRules map; fill1To3(map, srcAlphabet, dstAlphabet, amino, prob, n1, n2, n3); DNATranslation* t = new DNATranslation1to3Impl(id, name, srcAlphabet, dstAlphabet, map); treg->registerDNATranslation(t); } } #define CASE_OFFSET ('a'-'A') #define MAP(a, b) \ map[int(a)] = b; \ if (!srcAlphabet->isCaseSensitive()) { \ map[int(a) + CASE_OFFSET]=(b)+CASE_OFFSET; \ } void DNAAlphabetRegistryImpl::initBaseTranslations() { //default NUCL DNA complement { DNAAlphabet* srcAlphabet = findById(BaseDNAAlphabetIds::NUCL_DNA_DEFAULT()); DNAAlphabet* dstAlphabet = srcAlphabet; QByteArray map = TextUtils::createMap(srcAlphabet->getMap(), 'N'); MAP('A','T'); MAP('C','G'); MAP('G','C'); MAP('T','A'); DNATranslation* t = new DNATranslation1to1Impl(BaseDNATranslationIds::NUCL_DNA_DEFAULT_COMPLEMENT, tr("Complement for standard DNA"), srcAlphabet, dstAlphabet, map); treg->registerDNATranslation(t); } //default NUCL RNA complement { DNAAlphabet* srcAlphabet = findById(BaseDNAAlphabetIds::NUCL_RNA_DEFAULT()); DNAAlphabet* dstAlphabet = srcAlphabet; QByteArray map = TextUtils::createMap(srcAlphabet->getMap(), 'N'); MAP('A','U'); MAP('C','G'); MAP('G','C'); MAP('U','A'); DNATranslation* t = new DNATranslation1to1Impl(BaseDNATranslationIds::NUCL_RNA_DEFAULT_COMPLEMENT, tr("Complement for standard RNA"), srcAlphabet, dstAlphabet, map); treg->registerDNATranslation(t); } //extended NUCL DNA complement { //source: http://www.geneinfinity.org/sp_nucsymbols.html DNAAlphabet* srcAlphabet = findById(BaseDNAAlphabetIds::NUCL_DNA_EXTENDED()); DNAAlphabet* dstAlphabet = srcAlphabet; QByteArray map = TextUtils::createMap(srcAlphabet->getMap(), 'N'); MAP('A','T'); MAP('C','G'); MAP('G','C'); MAP('T','A'); MAP('M','K'); MAP('R','Y'); MAP('W','W'); MAP('S','S'); MAP('Y','R'); MAP('K','M'); MAP('V','B'); MAP('H','D'); MAP('D','H'); MAP('B','V'); DNATranslation* t = new DNATranslation1to1Impl(BaseDNATranslationIds::NUCL_DNA_EXTENDED_COMPLEMENT, tr("Complement for extended DNA"), srcAlphabet, dstAlphabet, map); treg->registerDNATranslation(t); } //extended NUCL RNA complement { //source: http://www.geneinfinity.org/sp_nucsymbols.html DNAAlphabet* srcAlphabet = findById(BaseDNAAlphabetIds::NUCL_RNA_EXTENDED()); DNAAlphabet* dstAlphabet = srcAlphabet; QByteArray map = TextUtils::createMap(srcAlphabet->getMap(), 'N'); MAP('A','U'); MAP('C','G'); MAP('G','C'); MAP('U','A'); MAP('M','K'); MAP('R','Y'); MAP('W','W'); MAP('S','S'); MAP('Y','R'); MAP('K','M'); MAP('V','B'); MAP('H','D'); MAP('D','H'); MAP('B','V'); DNATranslation* t = new DNATranslation1to1Impl(BaseDNATranslationIds::NUCL_RNA_EXTENDED_COMPLEMENT, tr("Complement for extended RNA"), srcAlphabet, dstAlphabet, map); treg->registerDNATranslation(t); } // source: http://www.ncbi.nlm.nih.gov/Taxonomy/Utils/wprintgc.cgi // 1. The Standard Code (transl_table=1) reg4tables( "FFLLSSSSYY**CC*WLLLLPPPPHHQQRRRRIIIMTTTTNNKKSSRRVVVVAAAADDEEGGGG", "---L---------------L---------------M----------------------------", "TTTTTTTTTTTTTTTTCCCCCCCCCCCCCCCCAAAAAAAAAAAAAAAAGGGGGGGGGGGGGGGG", "TTTTCCCCAAAAGGGGTTTTCCCCAAAAGGGGTTTTCCCCAAAAGGGGTTTTCCCCAAAAGGGG", "TCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAG", DNATranslationID(1), tr("1. The Standard Genetic Code")); //2. The Vertebrate Mitochondrial Code (transl_table=2) reg4tables( "FFLLSSSSYY**CCWWLLLLPPPPHHQQRRRRIIMMTTTTNNKKSS**VVVVAAAADDEEGGGG", "--------------------------------LLLM---------------L------------", "TTTTTTTTTTTTTTTTCCCCCCCCCCCCCCCCAAAAAAAAAAAAAAAAGGGGGGGGGGGGGGGG", "TTTTCCCCAAAAGGGGTTTTCCCCAAAAGGGGTTTTCCCCAAAAGGGGTTTTCCCCAAAAGGGG", "TCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAG", DNATranslationID(2), tr("2. The Vertebrate Mitochondrial Code")); //3. The Yeast Mitochondrial Code (transl_table=3) reg4tables( "FFLLSSSSYY**CCWWTTTTPPPPHHQQRRRRIIMMTTTTNNKKSSRRVVVVAAAADDEEGGGG", "----------------------------------LM----------------------------", "TTTTTTTTTTTTTTTTCCCCCCCCCCCCCCCCAAAAAAAAAAAAAAAAGGGGGGGGGGGGGGGG", "TTTTCCCCAAAAGGGGTTTTCCCCAAAAGGGGTTTTCCCCAAAAGGGGTTTTCCCCAAAAGGGG", "TCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAG", DNATranslationID(3), tr("3. The Yeast Mitochondrial Code")); //4. The Mold, Protozoan, and Coelenterate Mitochondrial Code and the Mycoplasma/Spiroplasma Code (transl_table=4) reg4tables( "FFLLSSSSYY**CCWWLLLLPPPPHHQQRRRRIIIMTTTTNNKKSSRRVVVVAAAADDEEGGGG", "--LL---------------L------------LLLM---------------L------------", "TTTTTTTTTTTTTTTTCCCCCCCCCCCCCCCCAAAAAAAAAAAAAAAAGGGGGGGGGGGGGGGG", "TTTTCCCCAAAAGGGGTTTTCCCCAAAAGGGGTTTTCCCCAAAAGGGGTTTTCCCCAAAAGGGG", "TCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAG", DNATranslationID(4), tr("4. The Mold, Protozoan, and Coelenterate Mitochondria and the Mycoplasma Code")); //5. The Invertebrate Mitochondrial Code (transl_table=5) reg4tables( "FFLLSSSSYY**CCWWLLLLPPPPHHQQRRRRIIMMTTTTNNKKSSSSVVVVAAAADDEEGGGG", "---L----------------------------LLLM---------------L------------", "TTTTTTTTTTTTTTTTCCCCCCCCCCCCCCCCAAAAAAAAAAAAAAAAGGGGGGGGGGGGGGGG", "TTTTCCCCAAAAGGGGTTTTCCCCAAAAGGGGTTTTCCCCAAAAGGGGTTTTCCCCAAAAGGGG", "TCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAG", DNATranslationID(5), tr("5. The Invertebrate Mitochondrial Code")); //6. The Ciliate, Dasycladacean and Hexamita Nuclear Code (transl_table=6) reg4tables( "FFLLSSSSYYQQCC*WLLLLPPPPHHQQRRRRIIIMTTTTNNKKSSRRVVVVAAAADDEEGGGG", "-----------------------------------M----------------------------", "TTTTTTTTTTTTTTTTCCCCCCCCCCCCCCCCAAAAAAAAAAAAAAAAGGGGGGGGGGGGGGGG", "TTTTCCCCAAAAGGGGTTTTCCCCAAAAGGGGTTTTCCCCAAAAGGGGTTTTCCCCAAAAGGGG", "TCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAG", DNATranslationID(6), tr("6. The Ciliate, Dasycladacean and Hexamita Nuclear Code")); //9. The Echinoderm and Flatworm Mitochondrial Code (transl_table=9) reg4tables( "FFLLSSSSYY**CCWWLLLLPPPPHHQQRRRRIIIMTTTTNNNKSSSSVVVVAAAADDEEGGGG", "-----------------------------------M---------------L------------", "TTTTTTTTTTTTTTTTCCCCCCCCCCCCCCCCAAAAAAAAAAAAAAAAGGGGGGGGGGGGGGGG", "TTTTCCCCAAAAGGGGTTTTCCCCAAAAGGGGTTTTCCCCAAAAGGGGTTTTCCCCAAAAGGGG", "TCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAG", DNATranslationID(9), tr("9. The Echinoderm and Flatworm Mitochondrial Code")); //10. The Euplotid Nuclear Code (transl_table=10) reg4tables( "FFLLSSSSYY**CCCWLLLLPPPPHHQQRRRRIIIMTTTTNNKKSSRRVVVVAAAADDEEGGGG", "-----------------------------------M----------------------------", "TTTTTTTTTTTTTTTTCCCCCCCCCCCCCCCCAAAAAAAAAAAAAAAAGGGGGGGGGGGGGGGG", "TTTTCCCCAAAAGGGGTTTTCCCCAAAAGGGGTTTTCCCCAAAAGGGGTTTTCCCCAAAAGGGG", "TCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAG", DNATranslationID(10), tr("10. The Euplotid Nuclear Code")); //11. The Bacterial and Plant Plastid Code (transl_table=11) reg4tables( "FFLLSSSSYY**CC*WLLLLPPPPHHQQRRRRIIIMTTTTNNKKSSRRVVVVAAAADDEEGGGG", "---L---------------L------------LLLM---------------L------------", "TTTTTTTTTTTTTTTTCCCCCCCCCCCCCCCCAAAAAAAAAAAAAAAAGGGGGGGGGGGGGGGG", "TTTTCCCCAAAAGGGGTTTTCCCCAAAAGGGGTTTTCCCCAAAAGGGGTTTTCCCCAAAAGGGG", "TCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAG", DNATranslationID(11), tr("11. The Bacterial and Plant Plastid Code")); //12. The Alternative Yeast Nuclear Code (transl_table=12) reg4tables( "FFLLSSSSYY**CC*WLLLSPPPPHHQQRRRRIIIMTTTTNNKKSSRRVVVVAAAADDEEGGGG", "-------------------L---------------M----------------------------", "TTTTTTTTTTTTTTTTCCCCCCCCCCCCCCCCAAAAAAAAAAAAAAAAGGGGGGGGGGGGGGGG", "TTTTCCCCAAAAGGGGTTTTCCCCAAAAGGGGTTTTCCCCAAAAGGGGTTTTCCCCAAAAGGGG", "TCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAG", DNATranslationID(12), tr("12. The Alternative Yeast Nuclear Code")); //13. The Ascidian Mitochondrial Code (transl_table=13) reg4tables( "FFLLSSSSYY**CCWWLLLLPPPPHHQQRRRRIIMMTTTTNNKKSSGGVVVVAAAADDEEGGGG", "---L------------------------------LM---------------L------------", "TTTTTTTTTTTTTTTTCCCCCCCCCCCCCCCCAAAAAAAAAAAAAAAAGGGGGGGGGGGGGGGG", "TTTTCCCCAAAAGGGGTTTTCCCCAAAAGGGGTTTTCCCCAAAAGGGGTTTTCCCCAAAAGGGG", "TCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAG", DNATranslationID(13), tr("13. The Ascidian Mitochondrial Code")); //14. The Alternative Flatworm Mitochondrial Code (transl_table=14) reg4tables( "FFLLSSSSYYY*CCWWLLLLPPPPHHQQRRRRIIIMTTTTNNNKSSSSVVVVAAAADDEEGGGG", "-----------------------------------M----------------------------", "TTTTTTTTTTTTTTTTCCCCCCCCCCCCCCCCAAAAAAAAAAAAAAAAGGGGGGGGGGGGGGGG", "TTTTCCCCAAAAGGGGTTTTCCCCAAAAGGGGTTTTCCCCAAAAGGGGTTTTCCCCAAAAGGGG", "TCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAG", DNATranslationID(14), tr("14. The Alternative Flatworm Mitochondrial Code")); //15. Blepharisma Nuclear Code (transl_table=15) reg4tables( "FFLLSSSSYY*QCC*WLLLLPPPPHHQQRRRRIIIMTTTTNNKKSSRRVVVVAAAADDEEGGGG", "-----------------------------------M----------------------------", "TTTTTTTTTTTTTTTTCCCCCCCCCCCCCCCCAAAAAAAAAAAAAAAAGGGGGGGGGGGGGGGG", "TTTTCCCCAAAAGGGGTTTTCCCCAAAAGGGGTTTTCCCCAAAAGGGGTTTTCCCCAAAAGGGG", "TCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAG", DNATranslationID(15), tr("15. Blepharisma Nuclear Code")); //16. Chlorophycean Mitochondrial Code (transl_table=16) reg4tables( "FFLLSSSSYY*LCC*WLLLLPPPPHHQQRRRRIIIMTTTTNNKKSSRRVVVVAAAADDEEGGGG", "-----------------------------------M----------------------------", "TTTTTTTTTTTTTTTTCCCCCCCCCCCCCCCCAAAAAAAAAAAAAAAAGGGGGGGGGGGGGGGG", "TTTTCCCCAAAAGGGGTTTTCCCCAAAAGGGGTTTTCCCCAAAAGGGGTTTTCCCCAAAAGGGG", "TCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAG", DNATranslationID(16), tr("16. Chlorophycean Mitochondrial Code")); //21. Trematode Mitochondrial Code (transl_table=21) reg4tables( "FFLLSSSSYY**CCWWLLLLPPPPHHQQRRRRIIMMTTTTNNNKSSSSVVVVAAAADDEEGGGG", "-----------------------------------M---------------L------------", "TTTTTTTTTTTTTTTTCCCCCCCCCCCCCCCCAAAAAAAAAAAAAAAAGGGGGGGGGGGGGGGG", "TTTTCCCCAAAAGGGGTTTTCCCCAAAAGGGGTTTTCCCCAAAAGGGGTTTTCCCCAAAAGGGG", "TCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAG", DNATranslationID(21), tr("21. Trematode Mitochondrial Code")); //22. Scenedesmus obliquus mitochondrial Code (transl_table=22) reg4tables( "FFLLSS*SYY*LCC*WLLLLPPPPHHQQRRRRIIIMTTTTNNKKSSRRVVVVAAAADDEEGGGG", "-----------------------------------M----------------------------", "TTTTTTTTTTTTTTTTCCCCCCCCCCCCCCCCAAAAAAAAAAAAAAAAGGGGGGGGGGGGGGGG", "TTTTCCCCAAAAGGGGTTTTCCCCAAAAGGGGTTTTCCCCAAAAGGGGTTTTCCCCAAAAGGGG", "TCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAG", DNATranslationID(22), tr("22. Scenedesmus obliquus Mitochondrial Code")); //23. Thraustochytrium Mitochondrial Code (transl_table=23) reg4tables( "FF*LSSSSYY**CC*WLLLLPPPPHHQQRRRRIIIMTTTTNNKKSSRRVVVVAAAADDEEGGGG", "--------------------------------L--M---------------L------------", "TTTTTTTTTTTTTTTTCCCCCCCCCCCCCCCCAAAAAAAAAAAAAAAAGGGGGGGGGGGGGGGG", "TTTTCCCCAAAAGGGGTTTTCCCCAAAAGGGGTTTTCCCCAAAAGGGGTTTTCCCCAAAAGGGG", "TCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAG", DNATranslationID(23), tr("23. Thraustochytrium Mitochondrial Code")); char amino[65], n1[65], n2[65], n3[65]; int prob[64]; QString dir = QDir::searchPaths( PATH_PREFIX_DATA ).first() + "/back_translation/"; QString lastOrganismFile = AppContext::getSettings()->getValue(DATA_FILE_KEY).toString(); if (lastOrganismFile.isEmpty() || !QFile::exists(lastOrganismFile)) { lastOrganismFile = dir + DEFAULT_ORGANISM_FILE; AppContext::getSettings()->setValue(DATA_FILE_KEY, lastOrganismFile); } QXmlStreamReader xml; QFile file(lastOrganismFile); if (!file.open(QFile::ReadOnly | QFile::Text)) { return; } xml.setDevice(&file); QString currentType; QString currentName; QString fileName; QString readableName; while (!xml.atEnd() && !xml.hasError()) { QXmlStreamReader::TokenType tt = xml.readNext(); if (tt == QXmlStreamReader::StartDocument) { continue; } if (tt == QXmlStreamReader::StartElement) { if (xml.name() == "CodonFrequencyTableList") { continue; } if (xml.name() == "Folder" && xml.attributes().value("name") == "Codon Frequency Tables") { continue; } if (xml.name() == "Folder") { currentType = xml.attributes().value("name").toString(); continue; } if (xml.name() == "CodonFrequencyTable") { currentName = xml.attributes().value("name").toString(); QStringList buf = currentName.split("."); buf.removeLast(); readableName = buf.join(".").replace("_", " "); fileName = currentType + "/" + currentName; if (parseCutFile(dir + fileName, amino, prob, n1, n2, n3)) regPtables(amino, prob, n1, n2, n3, "BackTranslation/" + fileName, readableName); } } } } } //namespace ugene-1.9.8/src/corelibs/U2Core/src/globals/0000755000175000017500000000000011651544331017217 5ustar ilyailyaugene-1.9.8/src/corelibs/U2Core/src/globals/NetworkConfiguration.h0000644000175000017500000000642211651544331023555 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_NETWORK_CONFIGURATION_H_ #define _U2_NETWORK_CONFIGURATION_H_ #include #include #include #include #ifndef QT_NO_OPENSSL #include #endif namespace U2 { typedef QNetworkProxy::ProxyType Proxy_t; class U2CORE_EXPORT ProxyConfig { public: ProxyConfig(): excepted_addr_enabled(false){} QMap< Proxy_t, QNetworkProxy > proxyz; //only one proxy for each type QMap< Proxy_t, bool > proxyz_usage; //true if proxy is used QStringList excepted_addr; bool excepted_addr_enabled; }; class U2CORE_EXPORT SslConfig { public: static const QString SSLV2; static const QString SSLV3; static const QString TLSV1; SslConfig() { protocols << SSLV2 << SSLV3 << TLSV1; } QList protocols; QString currentProtocol; }; class U2CORE_EXPORT RemoteRequestConfig { public: static const int DEFAULT_REMOTE_REQUEST_TIMEOUT_SECONDS; RemoteRequestConfig() {} int remoteRequestTimeout; }; class U2CORE_EXPORT NetworkConfiguration { public: NetworkConfiguration(); ~NetworkConfiguration(); QNetworkProxy getProxyByUrl( const QUrl & url ) const; QNetworkProxy getProxy( Proxy_t prtype ) const; bool isProxyUsed( Proxy_t prtype ) const; void removeProxy( Proxy_t prtype); int addProxy( const QNetworkProxy & p_ ); //returns non-zero if replacing void setProxyUsed( Proxy_t prtype, bool val ); void setExceptionsList( const QStringList & exc_addr ); QStringList getExceptionsList() const {return pc.excepted_addr; } bool exceptionsEnabled() const {return pc.excepted_addr_enabled;} void setExceptionsEnabled( bool st ) {pc.excepted_addr_enabled = st; } QString getSslProtocolName() const; QList getSslProtocolNames() const { return sslConfig.protocols; } void setSslProtocol(const QString& name); void copyFrom(const NetworkConfiguration& image); int remoteRequestTimeout() const { return rrConfig.remoteRequestTimeout; } void setRequestTimeout(const int timeout); #ifndef QT_NO_OPENSSL QSsl::SslProtocol getSslProtocol() const; #endif private: static Proxy_t url2type( const QUrl & url ); ProxyConfig pc; SslConfig sslConfig; RemoteRequestConfig rrConfig; }; } //namespace #endif ugene-1.9.8/src/corelibs/U2Core/src/globals/global.h0000644000175000017500000000600011651544331020624 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_COREAPI_H_ #define _U2_COREAPI_H_ #include #include #include #include #ifdef BUILDING_U2CORE_DLL # define U2CORE_EXPORT Q_DECL_EXPORT #else # define U2CORE_EXPORT Q_DECL_IMPORT #endif #ifdef BUILDING_U2FORMATS_DLL # define U2FORMATS_EXPORT Q_DECL_EXPORT #else # define U2FORMATS_EXPORT Q_DECL_IMPORT #endif #ifdef BUILDING_U2ALGORITHM_DLL # define U2ALGORITHM_EXPORT Q_DECL_EXPORT #else # define U2ALGORITHM_EXPORT Q_DECL_IMPORT #endif #ifdef BUILDING_U2TEST_DLL # define U2TEST_EXPORT Q_DECL_EXPORT #else # define U2TEST_EXPORT Q_DECL_IMPORT #endif #ifdef BUILDING_U2LANG_DLL # define U2LANG_EXPORT Q_DECL_EXPORT #else # define U2LANG_EXPORT Q_DECL_IMPORT #endif #ifdef BUILDING_U2REMOTE_DLL # define U2REMOTE_EXPORT Q_DECL_EXPORT #else # define U2REMOTE_EXPORT Q_DECL_IMPORT #endif #ifdef BUILDING_U2GUI_DLL # define U2GUI_EXPORT Q_DECL_EXPORT #else # define U2GUI_EXPORT Q_DECL_IMPORT #endif #ifdef BUILDING_U2VIEW_DLL # define U2VIEW_EXPORT Q_DECL_EXPORT #else # define U2VIEW_EXPORT Q_DECL_IMPORT #endif #ifdef BUILDING_U2MISC_DLL # define U2MISC_EXPORT Q_DECL_EXPORT #else # define U2MISC_EXPORT Q_DECL_IMPORT #endif #ifdef BUILDING_U2DESIGNER_DLL # define U2DESIGNER_EXPORT Q_DECL_EXPORT #else # define U2DESIGNER_EXPORT Q_DECL_IMPORT #endif //global #define GLOBAL_SETTINGS QString("global/") #define ENV_UGENE_DEV "UGENE_DEV" #define PATH_PREFIX_DATA "data" #define PATH_PREFIX_SCRIPTS "scripts" typedef QMap QStrStrMap; namespace U2 { //internal types: typedef QString DocumentFormatId; typedef QString GObjectType; typedef QString IOAdapterId; typedef QString GObjectViewFactoryId; typedef QString GTestFormatId; typedef int ServiceType; enum TriState { TriState_Unknown, TriState_Yes, TriState_No }; enum UnloadedObjectFilter { //used as a separate type but not 'bool' to improve readability UOF_LoadedAndUnloaded, UOF_LoadedOnly }; } enum DNAAlphabetType { DNAAlphabet_RAW, DNAAlphabet_NUCL, DNAAlphabet_AMINO }; #endif ugene-1.9.8/src/corelibs/U2Core/src/globals/DBXRefRegistry.cpp0000644000175000017500000000562211651544331022533 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "DBXRefRegistry.h" #include #include #include #include namespace U2 { #define DB_XREF_FILE_NAME "DBXRefRegistry.txt" DBXRefRegistry::DBXRefRegistry(QObject *p) : QObject(p) { QFile file( QString(PATH_PREFIX_DATA)+ ":" + DB_XREF_FILE_NAME ); if(!file.exists() || !file.open(QIODevice::ReadOnly)){ coreLog.error(tr("File with db_xref mappings not found: %1").arg(DB_XREF_FILE_NAME)); return; } QTextStream in(&file); while (!in.atEnd()) { QString line = in.readLine(); if(line.length()==0 || line.startsWith("#")) { continue; } QStringList fields = line.split("|"); if (fields.size()!=4) { coreLog.error(tr("Illegal db_xref file entry: %1").arg(line)); continue; } DBXRefInfo info(fields[0], fields[1], fields[2],fields[3].trimmed()); refsByKey[info.name] = info; } file.close(); } QScriptValue DBXRefRegistry::toScriptValue(QScriptEngine *engine, DBXRefRegistry* const &in) { return engine->newQObject(in); } void DBXRefRegistry::fromScriptValue(const QScriptValue &object, DBXRefRegistry* &out) { out = (DBXRefRegistry*)(object.toQObject()); } void DBXRefRegistry::setupToEngine(QScriptEngine *engine){ DBXRefInfo::setupToEngine(engine); qScriptRegisterMetaType(engine, toScriptValue, fromScriptValue); } QScriptValue DBXRefInfo::toScriptValue(QScriptEngine *engine, DBXRefInfo const &in) { QScriptValue res=engine->newObject(); res.setProperty("name", QScriptValue(engine,in.name)); res.setProperty("url", QScriptValue(engine,in.url)); res.setProperty("fileUrl", QScriptValue(engine,in.fileUrl)); res.setProperty("comment", QScriptValue(engine,in.comment)); return res; } void DBXRefInfo::fromScriptValue(const QScriptValue &object, DBXRefInfo &out) { out = *((DBXRefInfo*)(object.toQObject())); } void DBXRefInfo::setupToEngine(QScriptEngine *engine){ qScriptRegisterMetaType(engine, toScriptValue, fromScriptValue); } }//namespace ugene-1.9.8/src/corelibs/U2Core/src/globals/GAutoDeleteList.h0000644000175000017500000000257111651544331022373 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_AUTODELETE_LIST_H_ #define _U2_AUTODELETE_LIST_H_ #include namespace U2 { template class GAutoDeleteList : public QObject { public: GAutoDeleteList(QObject* p = NULL) : QObject(p){} virtual ~GAutoDeleteList() {qDeleteAll(qlist);} QList qlist; }; //todo: move to separate header template class gauto_array { public: gauto_array(T* p = NULL) : data(p){} ~gauto_array() { delete[] data; } T* get() const {return data;} T* data; }; }//namespace #endif ugene-1.9.8/src/corelibs/U2Core/src/globals/Task.cpp0000644000175000017500000001136411651544331020632 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "Task.h" #include #include namespace U2 { static qint64 genTaskId() { //todo: add main-thread model check static qint64 id = 0; qint64 res = ++id; return res; } Task::Task(const QString& _name, TaskFlags f) { taskName = _name; state = State_New; tpm = Progress_SubTasksBased; flags = f; taskId = genTaskId(); parentTask = NULL; progressWeightAsSubtask = 1; maxParallelSubtasks = MAX_PARALLEL_SUBTASKS_SERIAL; insidePrepare = false; } void Task::setMaxParallelSubtasks(int n) { SAFE_POINT(n >= 0, QString("max parallel subtasks must be >=0, value passed: %1").arg(n),); maxParallelSubtasks = n; } void Task::setTaskName(const QString& _taskName) { SAFE_POINT(isNew(), "Can only change name for new tasks!",); taskName = _taskName; } void Task::cancel() { foreach(Task* t, subtasks) { if (!t->isFinished()) { t->cancel(); } } stateInfo.cancelFlag = true; } void Task::addSubTask(Task* sub) { SAFE_POINT(sub != NULL, "Trying to add NULL subtask",); SAFE_POINT(sub->parentTask==NULL, "Task already has a parent!",); SAFE_POINT(state == State_New, "Parents can be assigned to tasks in NEW state only!",); sub->parentTask = this; subtasks.append(sub); emit si_subtaskAdded(sub); } void Task::cleanup() { assert(isFinished()); foreach(Task* sub, getSubtasks()) { sub->cleanup(); } } bool Task::propagateSubtaskError() { if (hasError()) { return true; } Task* badChild = getSubtaskWithErrors(); if (badChild) { stateInfo.setError(stateInfo.getError() + badChild->getError()); } return stateInfo.hasError(); } Task* Task::getSubtaskWithErrors() const { foreach(Task* sub, getSubtasks()) { if (sub->hasError()) { return sub; } } return NULL; } QList Task::onSubTaskFinished(Task*){ static QList stub; return stub; } int Task::getNumParallelSubtasks() const { int nParallel = maxParallelSubtasks; assert(nParallel >=0 ); if (nParallel == MAX_PARALLEL_SUBTASKS_AUTO) { nParallel = AppResourcePool::instance()->getIdealThreadCount(); } assert(nParallel>=1); return nParallel; } void Task::setMinimizeSubtaskErrorText(bool v) { assert(flags.testFlag(TaskFlag_FailOnSubtaskError)); setFlag(TaskFlag_MinimizeSubtaskErrorText, v); } void Task::addTaskResource(const TaskResourceUsage& r) { SAFE_POINT(state == Task::State_New, QString("Can't add task resource in current state: %1)").arg(getState()),); SAFE_POINT(!insidePrepare || !r.prepareStageLock, "Can't add prepare-time resource from within prepare function call!",); SAFE_POINT(!r.locked, QString("Resource is already locked, resource id: %1").arg(r.resourceId),); taskResources.append(r); } ////////////////////////////////////////////////////////////////////////// // task scheduler void TaskScheduler::addSubTask(Task* t, Task* sub) { SAFE_POINT(t != NULL, "When adding subtask to TaskScheduler, the parent task is NULL",); SAFE_POINT(sub->getParentTask() == NULL, "Task already has a parent!",); SAFE_POINT(sub != NULL, "When adding subtask to TaskScheduler, the subtask is NULL",); sub->parentTask = t; t->subtasks.append(sub); emit t->si_subtaskAdded(sub); } void TaskScheduler::setTaskState(Task* t, Task::State newState) { SAFE_POINT(t->getState() < newState, QString("Illegal task state change! Current state: %1, new state: %2").arg(t->getState()).arg(newState),); t->state = newState; emit t->si_stateChanged(); emit si_stateChanged(t); } void TaskScheduler::setTaskStateDesc(Task* t, const QString& desc) { t->stateInfo.setDescription(desc); } void TaskScheduler::setTaskInsidePrepare(Task* t, bool val) { t->insidePrepare = val; } }//namespace ugene-1.9.8/src/corelibs/U2Core/src/globals/AppResources.h0000644000175000017500000000610411651544331022004 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_APPRESOURCES_H_ #define _U2_APPRESOURCES_H_ #include #include namespace U2 { /** Thread resource - number of threads */ #define RESOURCE_THREAD 1 /** Memory resource - amount of memory in megabytes */ #define RESOURCE_MEMORY 2 /** CUDA GPU resource - ensures that device is busy or not*/ #define RESOURCE_CUDA_GPU 3 /** OPENCL GPU resource - ensures that device is busy or not*/ #define RESOURCE_OPENCL_GPU 4 /** Project resource. There is 1 project active in the system and if the resource is locked no project load/unload operation is possible */ #define RESOURCE_PROJECT 5 class U2CORE_EXPORT AppResource { public: AppResource(): resourceId(9), currentUse(0), maxUse(0){} AppResource(int id, int _maxUse, const QString& _name, const QString& _suffix = QString()) : resourceId(id), currentUse(0), maxUse(_maxUse), name(_name), suffix(_suffix){}; virtual ~AppResource(){} bool isAvailable(int n=1) const {return currentUse + n <= maxUse;} void acquire(int n=1) {assert(isAvailable(n)); currentUse += n;} void release(int n=1) {assert(currentUse-n>=0);currentUse -= n;} int resourceId; int currentUse; int maxUse; QString name; QString suffix; }; #define MIN_MEMORY_SIZE 200 class U2CORE_EXPORT AppResourcePool : public QObject { Q_OBJECT public: AppResourcePool(); virtual ~AppResourcePool(); int getIdealThreadCount() const {return idealThreadCount;} void setIdealThreadCount(int n); int getMaxThreadCount() const {return threadResource->maxUse;} void setMaxThreadCount(int n); int getMaxMemorySizeInMB() const {return memResource->maxUse;} void setMaxMemorySizeInMB(int m); static bool getCurrentAppMemory(int& mb); //size in megabytes, false is estimation only is used static bool isSSE2Enabled(); void registerResource(AppResource* r); AppResource* getResource(int id) const; static AppResourcePool* instance(); private: QHash resources; int idealThreadCount; AppResource* threadResource; AppResource* memResource; AppResource* projectResouce; AppResource* phyTreeResource; }; }//namespace #endif ugene-1.9.8/src/corelibs/U2Core/src/globals/Task.h0000644000175000017500000003211711651544331020276 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_TASK_H_ #define _U2_TASK_H_ #include #include #include #include #include #include #include namespace U2 { struct U2CORE_EXPORT TaskResourceUsage { TaskResourceUsage(int id = 0, int use = 0, bool prepareStage = false) : resourceId(id), resourceUse(use), prepareStageLock(prepareStage), locked(false) {} int resourceId; int resourceUse; bool prepareStageLock; bool locked; }; class TaskScheduler; /** Holds task state info about current error and progress Error variable is protected by RW lock to ensure safe multi-threaded updates */ class U2CORE_EXPORT TaskStateInfo : public U2OpStatus { public: TaskStateInfo() : progress(-1), cancelFlag(false), hasErr(false), lock(QReadWriteLock::NonRecursive) {} /* Percent values in range 0..100, negative if unknown. */ int progress; int cancelFlag; virtual bool hasError() const {return hasErr;} virtual QString getError() const {QReadLocker r(&lock); return error;} virtual void setError(const QString& err) {QWriteLocker w(&lock); error = err; hasErr = !error.isEmpty();} virtual bool isCanceled() const {return cancelFlag;} virtual void setCanceled(bool v) {cancelFlag = v;} virtual int getProgress() const {return progress;} virtual void setProgress(int v) {progress = v;} virtual QString getDescription() const {QReadLocker r(&lock); return desc;} virtual void setDescription(const QString& _desc) {QWriteLocker w(&lock); desc = _desc;} private: bool hasErr; QString desc; QString error; private: mutable QReadWriteLock lock; //the lock is used because error & stateDesc can be assigned from any thread }; class U2CORE_EXPORT TaskTimeInfo { public: TaskTimeInfo() : startTime(0), finishTime(0), timeOut(-1) {} //time in microseconds from Unix Epoch (UTC). See Timer.h qint64 startTime; //the time task is promoted to 'running' state qint64 finishTime; //the time task is promoted to 'finished' state int timeOut; //number of seconds to be passed before tasks is timed out, -1 -> timeout function is disabled }; #define MAX_PARALLEL_SUBTASKS_AUTO 0 #define MAX_PARALLEL_SUBTASKS_SERIAL 1 enum TaskFlag { // Base flags TaskFlag_None = 0, TaskFlag_NoRun = 1 << 1, TaskFlag_RunBeforeSubtasksFinished = 1 << 2, //subtask can be run before its subtasks finished TaskFlag_NoAutoDelete = 1 << 3, //for top level tasks only: task is not deleted by scheduler after task is finished // Behavior based on subtasks TaskFlag_FailOnSubtaskError = 1 << 10, //subtask error is propagated automatically TaskFlag_FailOnSubtaskCancel = 1 << 11, // error and cancel flag are set if subtask was canceled and parent is neither canceled nor have errors TaskFlag_PropagateSubtaskDesc = 1 << 12, // task use description from the subtask (last changed) // Reporting options TaskFlag_ReportingIsSupported = 1 << 20, // task supports reporting TaskFlag_ReportingIsEnabled = 1 << 21, // task is asked to generate report TaskFlag_VerboseStateLog = 1 << 22, //tasks prepared/finished state is dumped to the 'info' log category. Effective for top-level tasks only TaskFlag_MinimizeSubtaskErrorText = 1 << 23, //for TaskFlag_FailOnSubtaskError task minimizes the error text // excluding task-names info from the text TaskFlag_SuppressErrorNotification = 1 << 24 //for top level tasks only: if task fails, tells if notification is shown }; #define TaskFlags_FOSCOE (TaskFlags(TaskFlag_FailOnSubtaskError) | TaskFlag_FailOnSubtaskCancel) #define TaskFlags_NR_FOSCOE (TaskFlags_FOSCOE | TaskFlag_NoRun) #define TaskFlags_RBSF_FOSCOE (TaskFlags_FOSCOE | TaskFlag_RunBeforeSubtasksFinished) typedef QFlags TaskFlags; typedef QVarLengthArray TaskResources; class U2CORE_EXPORT Task : public QObject { Q_OBJECT friend class TaskScheduler; public: enum State { State_New, State_Prepared, State_Running, State_Finished }; enum ProgressManagement { Progress_Manual, Progress_SubTasksBased }; enum ReportResult { ReportResult_Finished, ReportResult_CallMeAgain }; //Creates new task with State_New state Task(const QString& _name, TaskFlags f); //Prepares Task to run //Task must request/prepare all resources it needs, create subtasks and define progress management type //This method called after Task is added to Scheduler from the main thread //After calling this method task gets State_Prepared state virtual void prepare(){} // Called by Scheduler from the separate thread. No updates to Project/Document model can be done from this method // Task gets State_Running state when its first of its subtasks is run virtual void run() {assert(0);} // assertion is added to find all tasks with RUN declared in flags but not implemented // Called from the main thread after run() is finished // Task must report all of it results if needed. // If task can't report right now (for example a model is state-locked) // task can return ReportResult_CallMeAgain. // If task locks some resources, it's a good place to release them // After task reporting succeeds, it gets State_Finished state virtual ReportResult report() {return ReportResult_Finished;} // Set's cancelFlag to true. Does not wait for task to be stopped void cancel(); bool isCanceled() const {return stateInfo.cancelFlag;} // Returns subtasks of the task. Task must prepare it's subtask on prepare() call and can't change them latter. QList getSubtasks() const {return subtasks;} QString getTaskName() const {return taskName;} State getState() const {return state;} const TaskStateInfo& getStateInfo() const { return stateInfo; } const TaskTimeInfo& getTimeInfo() const { return timeInfo; } int getProgress() const {return stateInfo.progress;} ProgressManagement getProgressManagementType() const {return tpm;} TaskFlags getFlags() const {return flags;} bool hasFlags(TaskFlags f) const {return flags & f;} void addSubTask(Task* sub); bool hasError() const {return stateInfo.hasError();} QString getError() const {return stateInfo.getError();} bool isFinished() const {return state == Task::State_Finished;} bool isRunning() const {return state == Task::State_Running;} bool isPrepared() const {return state == Task::State_Prepared;} bool isNew() const {return state == Task::State_New;} // When called for a finished task it must deallocate all resources it keeps. // ATTENTION: this method WILL NOT be called by Task Scheduler automatically. // It is guaranteed that only tests run by TestRunnerTask will be cleaned up. // So, if any task provides 'cleanup' method, it still MUST correctly clean up // its resources in destructor. virtual void cleanup(); virtual bool hasSubtasksWithErrors() const { return getSubtaskWithErrors() != NULL; } virtual bool propagateSubtaskError(); virtual Task* getSubtaskWithErrors() const; virtual qint64 getTaskId() const {return taskId;} virtual bool isTopLevelTask() const {return getParentTask() == 0;} virtual Task* getParentTask() const {return parentTask;} virtual Task* getTopLevelParentTask() {return isTopLevelTask() ? this : parentTask->getTopLevelParentTask();} virtual bool isReportingSupported() const {return flags.testFlag(TaskFlag_ReportingIsSupported);} virtual bool isReportingEnabled() const {return flags.testFlag(TaskFlag_ReportingIsEnabled);} virtual void setReportingEnabled(bool v) {assert(isReportingSupported()); setFlag(TaskFlag_ReportingIsEnabled, v);} virtual void setNoAutoDelete( bool v ) { setFlag( TaskFlag_NoAutoDelete, v ); } virtual QString generateReport() const {assert(0); return QString();} float getSubtaskProgressWeight() const {return progressWeightAsSubtask;} void setSubtaskProgressWeight(float v) {progressWeightAsSubtask = v;} bool useDescriptionFromSubtask() const {return flags.testFlag(TaskFlag_PropagateSubtaskDesc);} void setUseDescriptionFromSubtask(bool v) { setFlag(TaskFlag_PropagateSubtaskDesc, v);} bool isVerboseLogMode() const {return flags.testFlag(TaskFlag_VerboseStateLog);} void setVerboseLogMode(bool v) { setFlag(TaskFlag_VerboseStateLog, v); } bool isErrorNotificationSuppressed() const { return flags.testFlag(TaskFlag_SuppressErrorNotification); } void setErrorNotificationSuppression(bool v) { setFlag(TaskFlag_SuppressErrorNotification, v); } const TaskResources& getTaskResources() {return taskResources;} //WARN: if set to MAX_PARALLEL_SUBTASKS_AUTO, returns unprocessed value (MAX_PARALLEL_SUBTASKS_AUTO = 0) int getMaxParallelSubtasks() const {return maxParallelSubtasks;} // the difference from getMaxParralelSubtasks is that this method // will process MAX_PARALLEL_SUBTASKS_AUTO and will never return 0 virtual int getNumParallelSubtasks() const; void setMaxParallelSubtasks(int n); void setError(const QString& err) {stateInfo.setError(err);} void setMinimizeSubtaskErrorText(bool v); /** Number of seconds to be passed to mark task as failed by timeout */ void setTimeOut(int sec) {timeInfo.timeOut = sec;} /** Number of seconds to be passed to mark task as failed by timeout */ int getTimeOut() const { return timeInfo.timeOut;} void addTaskResource(const TaskResourceUsage& r); signals: void si_subtaskAdded(Task* sub); void si_progressChanged(); void si_descriptionChanged(); void si_stateChanged(); protected: /// Called by scheduler when subtask is finished. virtual QList onSubTaskFinished(Task* subTask); void setRunResources(const TaskResources& taskR) {assert(state <= State_Prepared); taskResources = taskR;} void setTaskName(const QString& taskName); TaskStateInfo stateInfo; TaskTimeInfo timeInfo; ProgressManagement tpm; float progressWeightAsSubtask; int maxParallelSubtasks; private: void setFlag(TaskFlag f, bool v) { flags = v ? (flags | f) : flags & (~f); } TaskFlags flags; QString taskName; State state; Task* parentTask; QList subtasks; qint64 taskId; TaskResources taskResources; bool insidePrepare; }; class U2CORE_EXPORT TaskScheduler : public QObject { Q_OBJECT public: virtual void registerTopLevelTask(Task* t) = 0; virtual void unregisterTopLevelTask(Task* t) = 0; virtual const QList& getTopLevelTasks() const = 0; virtual Task * getTopLevelTaskById( qint64 id ) const = 0; virtual QDateTime estimatedFinishTime(Task*) const = 0; virtual void cancelAllTasks() = 0; virtual QString getStateName(Task* t) const = 0; virtual void addThreadId(qint64 taskId, Qt::HANDLE id) = 0; virtual void removeThreadId(qint64 taskId) = 0; virtual qint64 getNameByThreadId(Qt::HANDLE id) const = 0; virtual QList getMessages() = 0; protected: TaskResources& getTaskResources(Task* t) {return t->taskResources;} TaskStateInfo& getTaskStateInfo(Task* t) {return t->stateInfo;} TaskTimeInfo& getTaskTimeInfo(Task* t) {return t->timeInfo;} void emit_taskProgressChanged(Task* t) {emit t->si_progressChanged();} void emit_taskDescriptionChanged(Task* t) {emit t->si_descriptionChanged();} QList onSubTaskFinished(Task* parentTask, Task* subTask) {return parentTask->onSubTaskFinished(subTask);} void addSubTask(Task* t, Task* sub); void setTaskState(Task* t, Task::State newState); void setTaskStateDesc(Task* t, const QString& desc); void setTaskInsidePrepare(Task* t, bool val); signals: void si_topLevelTaskRegistered(Task*); void si_topLevelTaskUnregistered(Task*); void si_stateChanged(Task* task); }; } //namespace #endif ugene-1.9.8/src/corelibs/U2Core/src/globals/BaseDocumentFormats.h0000644000175000017500000000375711651544331023311 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_DOCUMENT_FORMATS_H_ #define _U2_DOCUMENT_FORMATS_H_ #include namespace U2 { class U2CORE_EXPORT BaseDocumentFormats { public: static const DocumentFormatId PLAIN_TEXT; static const DocumentFormatId PLAIN_FASTA; static const DocumentFormatId PLAIN_GENBANK; static const DocumentFormatId PLAIN_EMBL; static const DocumentFormatId PLAIN_SWISS_PROT; static const DocumentFormatId ABIF; static const DocumentFormatId SCF; static const DocumentFormatId RAW_DNA_SEQUENCE; static const DocumentFormatId CLUSTAL_ALN; static const DocumentFormatId STOCKHOLM; static const DocumentFormatId NEWICK; static const DocumentFormatId PLAIN_PDB; static const DocumentFormatId INDEX; static const DocumentFormatId FASTQ; static const DocumentFormatId PLAIN_ASN; static const DocumentFormatId MSF; static const DocumentFormatId ACE; static const DocumentFormatId GFF; static const DocumentFormatId SRF; static const DocumentFormatId SAM; static const DocumentFormatId NEXUS; static const DocumentFormatId MEGA; static const DocumentFormatId PDW; }; }//namespace #endif ugene-1.9.8/src/corelibs/U2Core/src/globals/AppSettings.h0000644000175000017500000000332211651544331021631 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_APPSETTINGS_H_ #define _U2_APPSETTINGS_H_ #include namespace U2 { class NetworkConfiguration; class UserAppsSettings; class AppResourcePool; class TestRunnerSettings; /** A collection for all settings used in app that have C++ model description */ class U2CORE_EXPORT AppSettings { public: AppSettings() : nc(NULL), userAppsSettings(NULL), ri(NULL), trs(NULL) {} virtual ~AppSettings(){} NetworkConfiguration* getNetworkConfiguration() const {return nc;} UserAppsSettings* getUserAppsSettings() const {return userAppsSettings;} AppResourcePool* getAppResourcePool() const {return ri;} TestRunnerSettings* getTestRunnerSettings() const {return trs;} protected: NetworkConfiguration* nc; UserAppsSettings* userAppsSettings; AppResourcePool* ri; TestRunnerSettings* trs; }; }//namespace #endif ugene-1.9.8/src/corelibs/U2Core/src/globals/ServiceTypes.h0000644000175000017500000000277211651544331022025 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_SERVICE_TYPE_H_ #define _U2_SERVICE_TYPE_H_ #include "ServiceModel.h" namespace U2 { const ServiceType Service_PluginViewer = 1; const ServiceType Service_Project = 2; const ServiceType Service_ProjectView = 3; const ServiceType Service_DNAGraphPack = 10; const ServiceType Service_DNAExport = 11; const ServiceType Service_TestRunner = 12; const ServiceType Service_ScriptRegistry = 13; const ServiceType Service_ExternalToolSupport = 14; const ServiceType Service_GUITesting = 15; const ServiceType Service_MinCoreServiceId = 500; const ServiceType Service_MaxCoreServiceId = 1000; }//namespace #endif ugene-1.9.8/src/corelibs/U2Core/src/globals/Log.cpp0000644000175000017500000000702611651544331020451 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "Log.h" #include "Timer.h" #include namespace U2 { LogServer::LogServer() { qRegisterMetaType("LogMessage"); } LogServer* LogServer::getInstance() { static LogServer instance; return &instance; } QStringList LogServer::getCategories() const { QSet uniqueNames; QStringList result; foreach(const Logger* l, loggers) { foreach(const QString& category, l->getCategories()) { if (uniqueNames.contains(category)) { continue; } result.append(category); uniqueNames.insert(category); } } return result; } Logger::Logger(const QString& category1) { categoryNames << category1; init(); } Logger::Logger(const QString& category1, const QString& category2) { categoryNames << category1 << category2; init(); } Logger::Logger(const QString& category1, const QString& category2, const QString& category3) { categoryNames << category1 << category2 << category3; init(); } Logger::Logger(const QString& category1, const QString& category2, const QString& category3, const QString& category4) { categoryNames << category1 << category2 << category3 << category4; init(); } Logger::Logger(const QStringList& _categoryNames) { categoryNames = _categoryNames; init(); } void Logger::init() { LogServer* s = LogServer::getInstance(); s->loggers.append(this); } Logger::~Logger() { // TODO possible race condition at shutdown -> log service could already be destroyed // LogServer* s = LogServer::getInstance(); // s->categories.removeOne(this); categoryNames.clear(); } LogMessage::LogMessage(const QStringList& cat, LogLevel l, const QString& m) : categories(cat), level(l), text(m), time(GTimer::currentTimeMicros()) { } void Logger::message(LogLevel level, const QString& msg) { LogMessage m(categoryNames, level, msg); LogServer::getInstance()->message(m); } void Logger::message(LogLevel level, const QString& msg, const QString& extraCategory) { message(level, msg, QStringList(extraCategory)); } void Logger::message(LogLevel level, const QString& msg, const QStringList& extraCategories) { QStringList resultCategories = categoryNames; resultCategories << extraCategories; LogMessage m(resultCategories, level, msg); LogServer::getInstance()->message(m); } void Logger::log(LogLevel level, const QString& message, const QString& category) { log(level, message, QStringList(category)); } void Logger::log(LogLevel level, const QString& message, const QStringList& categoryies) { LogMessage m(categoryies, level, message); LogServer::getInstance()->message(m); } }//namespace ugene-1.9.8/src/corelibs/U2Core/src/globals/AppGlobalObject.h0000644000175000017500000000273011651544331022362 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_APP_GLOBAL_OBJECT_H_ #define _U2_APP_GLOBAL_OBJECT_H_ #include #include namespace U2 { // Represents some Application global resource identified by ID. // Only 1 resource of the given ID can exists per time // Note: This entity class is separated into a separate class to // make it QObject and add more features to it in the future, // for example like deallocation features. class U2CORE_EXPORT AppGlobalObject : public QObject, public Identifiable { Q_OBJECT public: AppGlobalObject(const QString& id) : Identifiable(id) {} }; } //namespace #endif ugene-1.9.8/src/corelibs/U2Core/src/globals/BaseDocumentFormats.cpp0000644000175000017500000000444511651544331023637 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "BaseDocumentFormats.h" namespace U2 { const DocumentFormatId BaseDocumentFormats::PLAIN_TEXT("text"); const DocumentFormatId BaseDocumentFormats::PLAIN_FASTA("fasta"); const DocumentFormatId BaseDocumentFormats::PLAIN_GENBANK("genbank"); const DocumentFormatId BaseDocumentFormats::PLAIN_EMBL("embl"); const DocumentFormatId BaseDocumentFormats::PLAIN_SWISS_PROT("swiss-prot"); const DocumentFormatId BaseDocumentFormats::ABIF("abi"); const DocumentFormatId BaseDocumentFormats::SCF("scf"); const DocumentFormatId BaseDocumentFormats::PLAIN_PDB("pdb"); const DocumentFormatId BaseDocumentFormats::RAW_DNA_SEQUENCE("raw"); const DocumentFormatId BaseDocumentFormats::CLUSTAL_ALN("clustal"); const DocumentFormatId BaseDocumentFormats::STOCKHOLM("stockholm"); const DocumentFormatId BaseDocumentFormats::NEWICK("newick"); const DocumentFormatId BaseDocumentFormats::INDEX("index"); const DocumentFormatId BaseDocumentFormats::FASTQ("fastq"); const DocumentFormatId BaseDocumentFormats::PLAIN_ASN("mmdb"); const DocumentFormatId BaseDocumentFormats::MSF("msf"); const DocumentFormatId BaseDocumentFormats::GFF("gff"); const DocumentFormatId BaseDocumentFormats::SRF("srfasta"); const DocumentFormatId BaseDocumentFormats::SAM("sam"); const DocumentFormatId BaseDocumentFormats::NEXUS("nexus"); const DocumentFormatId BaseDocumentFormats::MEGA("mega"); const DocumentFormatId BaseDocumentFormats::ACE("ace"); const DocumentFormatId BaseDocumentFormats::PDW("pdw"); }//namespace ugene-1.9.8/src/corelibs/U2Core/src/globals/AppContext.cpp0000644000175000017500000000166611651544331022021 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "AppContext.h" namespace U2 { AppContext* AppContext::instance = NULL; }//namespace ugene-1.9.8/src/corelibs/U2Core/src/globals/UserApplicationsSettings.h0000644000175000017500000000432511651544331024402 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_USER_APPLICATIONS_SETTINGS_H_ #define _U2_USER_APPLICATIONS_SETTINGS_H_ #include namespace U2 { class U2CORE_EXPORT UserAppsSettings : public QObject { Q_OBJECT public: QString getWebBrowserURL() const; void setWebBrowserURL(const QString& url); bool useDefaultWebBrowser() const; void setUseDefaultWebBrowser(bool state); QString getTranslationFile() const; void setTranslationFile(const QString& fn); bool openLastProjectAtStartup() const; void setOpenLastProjectAtStartup(bool v); //a style selected by user QString getVisualStyle() const; void setVisualStyle(const QString& newStyle); // specify dir for downloaded files QString getDownloadDirPath() const; void setDownloadDirPath(const QString& newPath) const; // recently downloaded file names QStringList getRecentlyDownloadedFileNames() const; void setRecentlyDownloadedFileNames(const QStringList& fileNames) const; // specify dir for downloaded files QString getTemporaryDirPath() const; void setTemporaryDirPath(const QString& newPath); bool isStatisticsCollectionEnabled() const; void setEnableCollectingStatistics(bool b); bool tabbedWindowLayout() const; void setTabbedWindowLayout(bool b); signals: void si_temporaryPathChanged(); void si_windowLayoutChanged(); }; }//namespace #endif ugene-1.9.8/src/corelibs/U2Core/src/globals/AutoAnnotationsSupport.cpp0000644000175000017500000001566111651544331024457 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include #include #include #include #include #include #include #include #include "AutoAnnotationsSupport.h" namespace U2 { const QString AutoAnnotationObject::AUTO_ANNOTATION_HINT("auto-annotation object"); AutoAnnotationsUpdater::AutoAnnotationsUpdater( const QString& nm, const QString& gName ) : groupName(gName), name(nm) { checkedByDefault = AppContext::getSettings()->getValue(AUTO_ANNOTATION_SETTINGS + groupName, false).toBool(); } AutoAnnotationsUpdater::~AutoAnnotationsUpdater() { AppContext::getSettings()->setValue(AUTO_ANNOTATION_SETTINGS + groupName, checkedByDefault); } QList AutoAnnotationsSupport::getAutoAnnotationUpdaters() { return aaUpdaters; } AutoAnnotationsUpdater* AutoAnnotationsSupport::findUpdaterByGroupName( const QString& groupName ) { foreach (AutoAnnotationsUpdater* updater, aaUpdaters) { if (updater->getGroupName() == groupName) { return updater; } } return NULL; } AutoAnnotationsUpdater* AutoAnnotationsSupport::findUpdaterByName( const QString& name ) { foreach (AutoAnnotationsUpdater* updater, aaUpdaters) { if (updater->getName() == name) { return updater; } } return NULL; } ////////////////////////////////////////////////////////////////////////// void AutoAnnotationsSupport::registerAutoAnnotationsUpdater( AutoAnnotationsUpdater* updater ) { aaUpdaters.append(updater); } void AutoAnnotationsSupport::unregisterAutoAnnotationsUpdater(AutoAnnotationsUpdater* updater){ aaUpdaters.removeOne(updater); } AutoAnnotationsSupport::~AutoAnnotationsSupport() { qDeleteAll(aaUpdaters); } bool AutoAnnotationsSupport::isAutoAnnotation( const AnnotationTableObject* obj ) { return obj->getGHintsMap().value(AutoAnnotationObject::AUTO_ANNOTATION_HINT).toBool(); } bool AutoAnnotationsSupport::isAutoAnnotation( const GObject* obj ) { bool isAnnotationObject = obj->getGObjectType() == GObjectTypes::ANNOTATION_TABLE; bool hasAutoAnnotationHint = obj->getGHintsMap().value(AutoAnnotationObject::AUTO_ANNOTATION_HINT).toBool(); return isAnnotationObject && hasAutoAnnotationHint; } ////////////////////////////////////////////////////////////////////////// AutoAnnotationObject::AutoAnnotationObject( DNASequenceObject* obj ) : dnaObj(obj) { QVariantMap hints; hints.insert(AUTO_ANNOTATION_HINT, true); aobj = new AnnotationTableObject(AutoAnnotationsSupport::tr("Auto-annotations [%1 | %2]") .arg(obj->getDocument()->getName()).arg(obj->getSequenceName()), hints); aobj->addObjectRelation(dnaObj, GObjectRelationRole::SEQUENCE); aaSupport = AppContext::getAutoAnnotationsSupport(); } AutoAnnotationObject::~AutoAnnotationObject() { delete aobj; } void AutoAnnotationObject::update() { QList aaUpdaters = aaSupport->getAutoAnnotationUpdaters(); handleUpdate(aaUpdaters); } void AutoAnnotationObject::updateGroup( const QString& groupName ) { AutoAnnotationsUpdater* updater = aaSupport->findUpdaterByGroupName(groupName); if (updater != NULL) { QList updaters; updaters << updater; handleUpdate(updaters); } } void AutoAnnotationObject::handleUpdate( QList updaters ) { QList subTasks; QStringList groupNames; foreach (AutoAnnotationsUpdater* updater, updaters) { // check constraints AutoAnnotationConstraints cns; cns.alphabet = dnaObj->getAlphabet(); cns.hints = dnaObj->getGHints(); if (!updater->checkConstraints(cns)) { continue; } // cleanup AnnotationGroup* root = aobj->getRootGroup(); AnnotationGroup* sub = root->getSubgroup(updater->getGroupName(), false); if (sub != NULL) { Task* t = new RemoveAnnotationsTask(aobj, updater->getGroupName()); subTasks.append(t); } // update if (enabledGroups.contains(updater->getGroupName())) { // create update tasks Task* t = updater->createAutoAnnotationsUpdateTask(this); if (t != NULL) { subTasks.append(t); } } groupNames.append(updater->getGroupName()); } // envelope to unlock annotation object if (!subTasks.isEmpty()) { AutoAnnotationsUpdateTask* updateTask = new AutoAnnotationsUpdateTask(this, subTasks); AppContext::getTaskScheduler()->registerTopLevelTask(updateTask); } } void AutoAnnotationObject::setGroupEnabled( const QString& groupName, bool enabled ) { if (enabled) { enabledGroups.insert(groupName); } else { enabledGroups.remove(groupName); } } void AutoAnnotationObject::emitStateChange( bool started ) { if (started) { emit si_updateStarted(); } else { emit si_updateFinshed(); } } ////////////////////////////////////////////////////////////////////////// const QString AutoAnnotationsUpdateTask::NAME("Auto-annotations update task"); AutoAnnotationsUpdateTask::AutoAnnotationsUpdateTask( AutoAnnotationObject* aaObj, QList updateTasks ) : Task(NAME, TaskFlags_NR_FOSCOE), aa(aaObj), lock(NULL), subTasks(updateTasks) { setMaxParallelSubtasks(1); } void AutoAnnotationsUpdateTask::prepare() { SAFE_POINT(aa != NULL, tr("Empty auto-annotation object"), ); lock = new StateLock("Auto-annotations update", StateLockFlag_LiveLock); aa->getSeqObject()->lockState(lock); aa->emitStateChange(true); foreach(Task* subtask, subTasks) { addSubTask(subtask); } } Task::ReportResult AutoAnnotationsUpdateTask::report() { if (aa != NULL ) { aa->emitStateChange(false); } if (lock != NULL) { aa->getSeqObject()->unlockState(lock); delete lock; } return ReportResult_Finished; } } //namespace ugene-1.9.8/src/corelibs/U2Core/src/globals/UserApplicationsSettings.cpp0000644000175000017500000001241111651544331024730 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "UserApplicationsSettings.h" #include #include #include #include #include #include #include #include namespace U2 { #define SETTINGS_ROOT QString("/user_apps/") #define WEB_BROWSER QString("web_browser") #define USE_DEFAULT_WEB_BROWSER QString("use_default_web_browser") #define TRANSLATION QString("translation_file") #define LAST_PROJECT_FLAG QString("open_last_project") #define VISUAL_STYLE QString("style") #define DOWNLOAD_DIR QString("download_file") #define RECENTLY_DOWNLOADED QString("recently_downloaded") #define TEMPORARY_DIR QString("temporary_dir") #define COLLECTING_STATISTICS QString("collecting_statistics") #define WINDOW_LAYOUT QString("tabbed_windows") QString UserAppsSettings::getWebBrowserURL() const { return AppContext::getSettings()->getValue(SETTINGS_ROOT + WEB_BROWSER, QString("")).toString(); } bool UserAppsSettings::useDefaultWebBrowser() const { return AppContext::getSettings()->getValue(SETTINGS_ROOT + USE_DEFAULT_WEB_BROWSER, true).toBool(); } void UserAppsSettings::setWebBrowserURL(const QString& url) { return AppContext::getSettings()->setValue(SETTINGS_ROOT + WEB_BROWSER, url); } void UserAppsSettings::setUseDefaultWebBrowser(bool state) { return AppContext::getSettings()->setValue(SETTINGS_ROOT + USE_DEFAULT_WEB_BROWSER, state); } QString UserAppsSettings::getTranslationFile() const { return AppContext::getSettings()->getValue(SETTINGS_ROOT + TRANSLATION, QString("")).toString(); } void UserAppsSettings::setTranslationFile(const QString& fn) { return AppContext::getSettings()->setValue(SETTINGS_ROOT + TRANSLATION, fn); } bool UserAppsSettings::openLastProjectAtStartup() const { return AppContext::getSettings()->getValue(SETTINGS_ROOT + LAST_PROJECT_FLAG, true).toBool(); } void UserAppsSettings::setOpenLastProjectAtStartup(bool v) { return AppContext::getSettings()->setValue(SETTINGS_ROOT + LAST_PROJECT_FLAG, v); } QString UserAppsSettings::getVisualStyle() const { QString defaultStyle = QApplication::style()->objectName(); #ifdef Q_OS_WIN #define DEFAULT_STYLE_NAME ".NET" const char* version = qVersion(); if (QString("4.4.0")!=version) { if (QStyleFactory::keys().contains(DEFAULT_STYLE_NAME)) { defaultStyle = DEFAULT_STYLE_NAME; } } #endif return AppContext::getSettings()->getValue(SETTINGS_ROOT + VISUAL_STYLE, defaultStyle).toString(); } void UserAppsSettings::setVisualStyle(const QString& newStyle) { return AppContext::getSettings()->setValue(SETTINGS_ROOT + VISUAL_STYLE, newStyle.toLower()); } QString UserAppsSettings::getDownloadDirPath() const { return AppContext::getSettings()->getValue(SETTINGS_ROOT + DOWNLOAD_DIR, QDir::homePath()+"/.UGENE_downloaded").toString(); } void UserAppsSettings::setDownloadDirPath(const QString& newPath) const { AppContext::getSettings()->setValue(SETTINGS_ROOT + DOWNLOAD_DIR, newPath); } QStringList UserAppsSettings::getRecentlyDownloadedFileNames() const { QStringList empty; return AppContext::getSettings()->getValue(SETTINGS_ROOT + RECENTLY_DOWNLOADED, empty).toStringList(); } void UserAppsSettings::setRecentlyDownloadedFileNames(const QStringList& fileNames) const { AppContext::getSettings()->setValue(SETTINGS_ROOT + RECENTLY_DOWNLOADED, fileNames); } QString UserAppsSettings::getTemporaryDirPath() const { return AppContext::getSettings()->getValue(SETTINGS_ROOT + TEMPORARY_DIR, QDesktopServices::storageLocation(QDesktopServices::TempLocation)).toString(); } void UserAppsSettings::setTemporaryDirPath(const QString& newPath) { AppContext::getSettings()->setValue(SETTINGS_ROOT + TEMPORARY_DIR, newPath); emit si_temporaryPathChanged(); } bool UserAppsSettings::isStatisticsCollectionEnabled() const { return AppContext::getSettings()->getValue(SETTINGS_ROOT + COLLECTING_STATISTICS).toBool(); } void UserAppsSettings::setEnableCollectingStatistics(bool b) { AppContext::getSettings()->setValue(SETTINGS_ROOT + COLLECTING_STATISTICS, b); } bool UserAppsSettings::tabbedWindowLayout() const { return AppContext::getSettings()->getValue(SETTINGS_ROOT + WINDOW_LAYOUT).toBool(); } void UserAppsSettings::setTabbedWindowLayout(bool b) { AppContext::getSettings()->setValue(SETTINGS_ROOT + WINDOW_LAYOUT, b); emit si_windowLayoutChanged(); } }//namespace ugene-1.9.8/src/corelibs/U2Core/src/globals/Log.h0000644000175000017500000001054011651544331020111 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_LOG_H_ #define _U2_LOG_H_ #include "global.h" #include #include #include namespace U2 { enum LogLevel { LogLevel_TRACE, LogLevel_DETAILS, LogLevel_INFO, LogLevel_ERROR, LogLevel_NumLevels}; class U2CORE_EXPORT LogMessage { public: LogMessage() {} LogMessage(const QStringList& cat, LogLevel l, const QString& m); QStringList categories; LogLevel level; QString text; qint64 time; //time in microseconds from Unix Epoch (UTC). See Timer.h }; class U2CORE_EXPORT Logger { public: Logger(const QString& category1); Logger(const QString& category1, const QString& category2); Logger(const QString& category1, const QString& category2, const QString& category3); Logger(const QString& category1, const QString& category2, const QString& category3, const QString& category4); Logger(const QStringList& categoryNames); virtual ~Logger(); static void log(LogLevel level, const QString& message, const QString& category); static void log(LogLevel level, const QString& message, const QStringList& categoryies); void message(LogLevel level, const QString& msg); void message(LogLevel level, const QString& msg, const QString& extraCategory); void message(LogLevel level, const QString& msg, const QStringList& extraCategories); void trace(const QString& msg) { message(LogLevel_TRACE, msg);} void details(const QString& msg) { message(LogLevel_DETAILS, msg);} void info(const QString& msg) { message(LogLevel_INFO, msg);} void error(const QString& msg) { message(LogLevel_ERROR, msg);} const QStringList& getCategories() const {return categoryNames;} private: void init(); QStringList categoryNames; }; class U2CORE_EXPORT LogServer : public QObject { Q_OBJECT friend class Logger; public: LogServer(); static LogServer* getInstance(); const QList& getLoggers() const {return loggers;} QStringList getCategories() const; private: void message(const LogMessage& m) {emit si_message(m);} QList loggers; signals: void si_message(const LogMessage& m); }; //TODO: support log category translation + use log category ids instead of the names in code // Log category for algorithms and computing details #define ULOG_CAT_ALGORITHM "Algorithms" // Log category for console output #define ULOG_CAT_CONSOLE "Console" // Log category for core service (internal model events) #define ULOG_CAT_CORE_SERVICES "Core Services" // Log category for IO events #define ULOG_CAT_IO "Input/Output" // Log category for remote service messages #define ULOG_CAT_REMOTE_SERVICE "Remote Service" // Log category for performance tracking #define ULOG_CAT_PERFORMANCE "Performance" // Log category for scripting related logs #define ULOG_CAT_SCRIPTS "Scripts" // Log category for task machinery related logs #define ULOG_CAT_TASKS "Tasks" // Log category for UI related events #define ULOG_CAT_USER_INTERFACE "User Interface" static Logger algoLog(ULOG_CAT_ALGORITHM); static Logger cmdLog(ULOG_CAT_CONSOLE); static Logger coreLog(ULOG_CAT_CORE_SERVICES); static Logger ioLog(ULOG_CAT_IO); static Logger rsLog(ULOG_CAT_REMOTE_SERVICE); static Logger perfLog(ULOG_CAT_PERFORMANCE); static Logger scriptLog(ULOG_CAT_SCRIPTS); static Logger taskLog(ULOG_CAT_TASKS); static Logger uiLog(ULOG_CAT_USER_INTERFACE); }//namespace Q_DECLARE_METATYPE( U2::LogMessage ) #endif ugene-1.9.8/src/corelibs/U2Core/src/globals/NetworkConfiguration.cpp0000644000175000017500000001547111651544331024114 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include #include #include #include "NetworkConfiguration.h" namespace U2 { static const char * SETTINGS_HTTP_PROXY_HOST = "network_settings/http_proxy/host"; static const char * SETTINGS_HTTP_PROXY_PORT = "network_settings/http_proxy/port"; static const char * SETTINGS_HTTP_PROXY_USER = "network_settings/http_proxy/user"; static const char * SETTINGS_HTTP_PROXY_PASSWORD = "network_settings/http_proxy/password"; static const char * SETTINGS_HTTP_PROXY_ENABLED = "network_settings/http_proxy/enabled"; static const char * SETTINGS_PROXY_EXCEPTED_URLS = "network_settings/proxy_exc_urls"; static const char * SETTINGS_PROXY_EXCEPTED_URLS_ENABLED = "network_settings/proxy_exc_urls_enabled"; static const char * SETTINGS_SSL_PROTOCOL = "network_settings/ssl_protocol"; static const char * SETTINGS_REMOTE_REQUEST_TIMEOUT = "network_settings/remote_request/timeout"; const QString SslConfig::TLSV1 = "TlsV1"; const QString SslConfig::SSLV2 = "SslV2"; const QString SslConfig::SSLV3 = "SslV3"; const int RemoteRequestConfig::DEFAULT_REMOTE_REQUEST_TIMEOUT_SECONDS = 60; NetworkConfiguration::NetworkConfiguration() { Settings * s = AppContext::getSettings(); pc.excepted_addr_enabled = s->getValue( SETTINGS_PROXY_EXCEPTED_URLS_ENABLED ).toBool(); pc.excepted_addr = s->getValue( SETTINGS_PROXY_EXCEPTED_URLS ).toStringList(); QString httpProxyHost = s->getValue( SETTINGS_HTTP_PROXY_HOST ).toString(); int httpProxyPort = s->getValue( SETTINGS_HTTP_PROXY_PORT ).toInt(); if( !httpProxyHost.isEmpty() && httpProxyPort ) { QNetworkProxy httpProxy( QNetworkProxy::HttpProxy, httpProxyHost, httpProxyPort ); QString user = s->getValue( SETTINGS_HTTP_PROXY_USER ).toString(); if (!user.isEmpty()) { QByteArray passwordEncoded = s->getValue( SETTINGS_HTTP_PROXY_PASSWORD ).toByteArray(); QString passwordDecoded = QByteArray::fromBase64(passwordEncoded); httpProxy.setUser(user); httpProxy.setPassword(passwordDecoded); } pc.proxyz[QNetworkProxy::HttpProxy] = httpProxy; pc.proxyz_usage[QNetworkProxy::HttpProxy] = s->getValue( SETTINGS_HTTP_PROXY_ENABLED ).toBool(); } sslConfig.currentProtocol = s->getValue(SETTINGS_SSL_PROTOCOL, SslConfig::SSLV3).toString(); rrConfig.remoteRequestTimeout = s->getValue(SETTINGS_REMOTE_REQUEST_TIMEOUT, RemoteRequestConfig::DEFAULT_REMOTE_REQUEST_TIMEOUT_SECONDS).toInt(); } NetworkConfiguration::~NetworkConfiguration() { Settings * s = AppContext::getSettings(); s->setValue( SETTINGS_PROXY_EXCEPTED_URLS_ENABLED, pc.excepted_addr_enabled ); s->setValue( SETTINGS_PROXY_EXCEPTED_URLS, pc.excepted_addr ); s->setValue( SETTINGS_SSL_PROTOCOL, sslConfig.currentProtocol ); s->setValue( SETTINGS_REMOTE_REQUEST_TIMEOUT, rrConfig.remoteRequestTimeout ); QNetworkProxy httpP = getProxy( QNetworkProxy::HttpProxy ); if( !httpP.hostName().isEmpty() ) { s->setValue( SETTINGS_HTTP_PROXY_HOST, httpP.hostName() ); s->setValue( SETTINGS_HTTP_PROXY_PORT, httpP.port() ); s->setValue( SETTINGS_HTTP_PROXY_USER, httpP.user()); s->setValue( SETTINGS_HTTP_PROXY_PASSWORD, httpP.password().toAscii().toBase64()); s->setValue( SETTINGS_HTTP_PROXY_ENABLED, isProxyUsed(QNetworkProxy::HttpProxy) ); } } int NetworkConfiguration::addProxy( const QNetworkProxy & p ) { int ret = !pc.proxyz.contains( p.type() ); pc.proxyz.insert( p.type(), p ); pc.proxyz_usage.insert( p.type(), false ); //needs explicit enabling return ret; } QNetworkProxy NetworkConfiguration::getProxyByUrl( const QUrl & url ) const { Proxy_t prtype = url2type( url ); if( pc.proxyz.contains( prtype ) ) { assert( pc.proxyz_usage.contains(prtype) ); if( pc.proxyz_usage[prtype] ) { return ( pc.excepted_addr_enabled && pc.excepted_addr.contains( url.toString() ) ? QNetworkProxy() : pc.proxyz[prtype] ); } } return QNetworkProxy(); } QNetworkProxy NetworkConfiguration::getProxy( Proxy_t prtype ) const { return (pc.proxyz.contains( prtype ) ? pc.proxyz[prtype] : QNetworkProxy() ); } void NetworkConfiguration::removeProxy( Proxy_t prtype ) { pc.proxyz.remove( prtype ); } bool NetworkConfiguration::isProxyUsed( Proxy_t prtype ) const { return pc.proxyz_usage.contains( prtype ) ? pc.proxyz_usage[prtype] : false; } void NetworkConfiguration::setExceptionsList( const QStringList & exc_addr ) { pc.excepted_addr = exc_addr; } void NetworkConfiguration::setProxyUsed( Proxy_t prtype, bool flag ) { if( pc.proxyz_usage.contains(prtype) ) { pc.proxyz_usage[prtype] = flag; } } Proxy_t NetworkConfiguration::url2type( const QUrl & url ) { if( "http" == url.scheme() || "https" == url.scheme() ) { return QNetworkProxy::HttpProxy; } if( "ftp" == url.scheme() ) { return QNetworkProxy::FtpCachingProxy; } assert( false ); return QNetworkProxy::NoProxy; } void NetworkConfiguration::copyFrom(const NetworkConfiguration& image) { pc = image.pc; sslConfig = image.sslConfig; rrConfig = image.rrConfig; } #ifndef QT_NO_OPENSSL QSsl::SslProtocol NetworkConfiguration::getSslProtocol() const { if (sslConfig.currentProtocol == SslConfig::SSLV2) { return QSsl::SslV2; } else if (sslConfig.currentProtocol == SslConfig::SSLV3) { return QSsl::SslV3; } else if (sslConfig.currentProtocol == SslConfig::TLSV1) { return QSsl::TlsV1; } else { return QSsl::SslV3; } } #endif QString NetworkConfiguration::getSslProtocolName() const { if (sslConfig.currentProtocol.isEmpty()) { return SslConfig::SSLV3; } else { return sslConfig.currentProtocol; } } void NetworkConfiguration::setSslProtocol( const QString& name ) { sslConfig.currentProtocol = name; } void NetworkConfiguration::setRequestTimeout( const int timeout ) { rrConfig.remoteRequestTimeout = timeout; } } //namespace ugene-1.9.8/src/corelibs/U2Core/src/globals/AppResources.cpp0000644000175000017500000001174111651544331022342 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "AppResources.h" #include #include #include #include #include #ifdef Q_OS_WIN #include #include #include //for IsProcessorFeaturePresent #endif namespace U2 { #define SETTINGS_ROOT QString("app_resource/") AppResourcePool::AppResourcePool() { Settings* s = AppContext::getSettings(); idealThreadCount = s->getValue(SETTINGS_ROOT + "idealThreadCount", QThread::idealThreadCount()).toInt(); int maxThreadCount = s->getValue(SETTINGS_ROOT + "maxThreadCount", 1000).toInt(); threadResource = new AppResource(RESOURCE_THREAD, maxThreadCount, tr("Threads")); registerResource(threadResource); int maxMem = s->getValue(SETTINGS_ROOT + "maxMem", 3 * 512).toInt(); //TODO: increase default value for 64bit ? memResource = new AppResource(RESOURCE_MEMORY, maxMem, tr("Memory"), tr("Mb")); registerResource(memResource); projectResouce = new AppResource(RESOURCE_PROJECT, 1, tr("Project")); registerResource(projectResouce); } AppResourcePool::~AppResourcePool() { qDeleteAll(resources.values()); } void AppResourcePool::setIdealThreadCount(int n) { SAFE_POINT(n > 0 && n <= threadResource->maxUse, QString("Invalid ideal threads count: %1").arg(n),); n = qBound(1, n, threadResource->maxUse); idealThreadCount = n; AppContext::getSettings()->setValue(SETTINGS_ROOT + "idealThreadCount", idealThreadCount); } void AppResourcePool::setMaxThreadCount(int n) { SAFE_POINT(n >= 1, QString("Invalid max threads count: %1").arg(n),); threadResource->maxUse = qMax(idealThreadCount, n); AppContext::getSettings()->setValue(SETTINGS_ROOT + "maxThreadCount", threadResource->maxUse ); } void AppResourcePool::setMaxMemorySizeInMB(int n) { SAFE_POINT(n >= MIN_MEMORY_SIZE, QString("Invalid max memory size: %1").arg(n),); memResource->maxUse = qMax(n, MIN_MEMORY_SIZE); AppContext::getSettings()->setValue(SETTINGS_ROOT + "maxMem", memResource->maxUse); } bool AppResourcePool::getCurrentAppMemory(int& mb) { #ifdef Q_OS_WIN HANDLE procHandle = GetCurrentProcess(); PROCESS_MEMORY_COUNTERS pmc; BOOL ok = GetProcessMemoryInfo(procHandle, &pmc, sizeof(procHandle)); if (!ok) { return false; } mb = (int)(pmc.WorkingSetSize/(1024*1024)); return true; #endif mb = MIN_MEMORY_SIZE; return false; } bool AppResourcePool::isSSE2Enabled() { bool answer = false; #if defined( Q_OS_WIN ) //Using WinAPI call on Windows. //Return Value //If the feature is supported, the return value is a nonzero value. //If the feature is not supported, the return value is zero. // //If the HAL does not support detection of the feature, //whether or not the hardware supports the feature, the return value is also zero. // //Windows 2000: This feature is not supported. // //Header: Winbase.h (include Windows.h) //Library: Kernel32.lib //DLL: Kernel32.dll answer = (bool)IsProcessorFeaturePresent( PF_XMMI64_INSTRUCTIONS_AVAILABLE ); #elif defined( __amd64__ ) || defined( __AMD64__ ) || defined( __x86_64__ ) || defined( _M_X64 ) answer = true; #elif defined( __i386__ ) || defined( __X86__ ) || defined( _M_IX86 ) //cpuid instruction: //- takes 0x1 on eax, //- returns standard features flags in edx, bit 26 is SSE2 flag //- clobbers ebx, ecx unsigned int fflags = 0; unsigned int stub = 0; __asm__ __volatile__ ( "push %%ebx; cpuid; mov %%ebx, %%edi; pop %%ebx" : "=a" (stub), "=D" (stub), "=c" (stub), "=d" (fflags) : "a" (0x1)); answer = ((fflags & (1<<26))!=0); #endif return answer; } void AppResourcePool::registerResource(AppResource* r) { SAFE_POINT(!resources.contains(r->resourceId), QString("Duplicate resource: ").arg(r->resourceId),); resources[r->resourceId] = r; } AppResource* AppResourcePool::getResource(int id) const { return resources.value(id, NULL); } AppResourcePool* AppResourcePool::instance() { return AppContext::getAppSettings()->getAppResourcePool(); } }//namespace ugene-1.9.8/src/corelibs/U2Core/src/globals/Identifiable.h0000644000175000017500000000222711651544331021752 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_IDENTIFIABLE_H_ #define _U2_IDENTIFIABLE_H_ #include namespace U2 { // A template of object with identity template class Identifiable { public: Identifiable(const T& _id) : id(_id) {} const T& getId() const {return id;} private: T id; }; } //namespace #endif ugene-1.9.8/src/corelibs/U2Core/src/globals/ResourceTracker.cpp0000644000175000017500000000401211651544331023023 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "ResourceTracker.h" #include #include "Task.h" namespace U2 { ResourceTracker::~ResourceTracker() { assert(resMap.isEmpty()); } void ResourceTracker::registerResourceUser(const QString& resourceName, Task* t) { TList list = resMap.value(resourceName); assert(!list.contains(t)); list.append(t); resMap[resourceName] = list; coreLog.details(tr("resource '%1' is used by '%2'").arg(resourceName).arg(t->getTaskName())); emit si_resourceUserRegistered(resourceName, t); } void ResourceTracker::unregisterResourceUser(const QString& resourceName, Task* t) { assert(resMap.contains(resourceName)); TList list = resMap.value(resourceName); assert(list.contains(t)); list.removeOne(t); if (list.isEmpty()) { resMap.remove(resourceName); } else { resMap[resourceName] = list; } coreLog.details(tr("resource '%1' is released by '%2'").arg(resourceName).arg(t->getTaskName())); emit si_resourceUserUnregistered(resourceName, t); } QList ResourceTracker::getResourceUsers(const QString& resourceName) { QList res = resMap.value(resourceName); return res; } } //namespace ugene-1.9.8/src/corelibs/U2Core/src/globals/Settings.h0000644000175000017500000000306311651544331021172 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_SETTINGS_H_ #define _U2_SETTINGS_H_ #include #include #include namespace U2 { class U2CORE_EXPORT Settings : public QObject { Q_OBJECT public: virtual QStringList getAllKeys(const QString& path) = 0; virtual bool contains(const QString& key) const = 0; virtual void remove(const QString& key) = 0; virtual QVariant getValue(const QString& key, const QVariant& defaultValue = QVariant()) const = 0; virtual void setValue(const QString& key, const QVariant& value) = 0; virtual QString toVersionKey(const QString& key) const = 0; virtual void sync()=0; virtual QString fileName() const = 0; }; } //namespace #endif ugene-1.9.8/src/corelibs/U2Core/src/globals/PluginModel.h0000644000175000017500000000537011651544331021614 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_PLUGINMODEL_H_ #define _U2_PLUGINMODEL_H_ #include #include #include namespace U2 { //BUG:417: add API version check class Service; class ServiceRegistry; class Plugin; class PluginSupport; class Task; #define U2_PLUGIN_INIT_FUNC ugene_plugin_init #define U2_PLUGIN_INIT_FUNC_NAME "ugene_plugin_init" typedef Plugin*(*PLUG_INIT_FUNC) (); enum PluginState { PluginState_Loaded, PluginState_FailedToLoad }; class U2CORE_EXPORT Plugin : public QObject { Q_OBJECT public: Plugin(const QString & _name, const QString& _desc, PluginState _state = PluginState_Loaded) : name(_name), description(_desc), state(_state){} //plugin is deallocated by plugin_support service when it's removed or on application shutting down virtual ~Plugin(){} const QString& getName() const {return name;} const QString& getDescription() const {return description;} PluginState getState() const {return state;} // returns list of services provided by the plugin // after plugin is loaded all services from this list are automatically registered const QList& getServices() const {return services;} protected: QString name, description; QList services; PluginState state; }; class U2CORE_EXPORT PluginSupport : public QObject { friend class LoadAllPluginsTask; Q_OBJECT public: virtual const QList& getPlugins() = 0; virtual Task* addPluginTask(const QString& pathToPlugin) = 0; //plugin will not be removed from the plugin list during the next app run virtual void setRemoveFlag(Plugin* p, bool v) = 0; virtual bool getRemoveFlag(Plugin* p) const = 0; virtual bool isAllPluginsLoaded() const = 0; signals: void si_pluginAdded(Plugin*); void si_pluginRemoveFlagChanged(Plugin*); void si_allStartUpPluginsLoaded(); }; }//namespace #endif ugene-1.9.8/src/corelibs/U2Core/src/globals/PluginModel.cpp0000644000175000017500000000155711651544331022152 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "PluginModel.h" ugene-1.9.8/src/corelibs/U2Core/src/globals/ExternalToolRegistry.cpp0000644000175000017500000000517211651544331024101 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "ExternalToolRegistry.h" #include #include #include namespace U2 { //////////////////////////////////////// //ExternalTool ExternalTool::ExternalTool(QString _name, QString _path) : name(_name), path(_path){ } ExternalTool::~ExternalTool() { } void ExternalTool::setPath(const QString& _path) { if (path!=_path) { path=_path; emit si_pathChanged(); } } void ExternalTool::setValid(bool _isValid){ isValidTool=_isValid; } void ExternalTool::setVersion(const QString& _version) { version=_version; } //////////////////////////////////////// //ExternalToolRegistry ExternalToolRegistry::~ExternalToolRegistry() { qDeleteAll(registry.values()); } ExternalTool* ExternalToolRegistry::getByName(const QString& id) { return registry.value(id, NULL); } bool ExternalToolRegistry::registerEntry(ExternalTool *t){ if (registry.contains(t->getName())) { return false; } else { registry.insert(t->getName(), t); return true; } } void ExternalToolRegistry::unregisterEntry(const QString &id){ delete registry.take(id); } QList ExternalToolRegistry::getAllEntries() const { return registry.values(); } QList< QList > ExternalToolRegistry::getAllEntriesSortedByToolKits() const { QList< QList > res; QList list=registry.values(); while(!list.isEmpty()){ QString name=list.first()->getToolKitName(); QList toolKitList; for(int i=0;igetToolKitName()){ toolKitList.append(list.takeAt(i)); i--; } } res.append(toolKitList); } return res; } }//namespace ugene-1.9.8/src/corelibs/U2Core/src/globals/Version.h0000644000175000017500000000322611651544331021020 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_VERSION_H_ #define _U2_VERSION_H_ #include namespace U2 { class U2CORE_EXPORT Version { public: // creates empty version structure Version(); // Current UGENE instance version static Version ugeneVersion(); // Current QT version static Version qtVersion(); static Version parseVersion(const QString& text); bool operator > (const Version& v) const; bool operator >= (const Version& v) const; bool operator < (const Version& v) const; bool operator <= (const Version& v) const; bool operator == (const Version& v) const; bool operator != (const Version& v) const {return !(v == *this);} int major; int minor; int patch; bool debug; QString text; QString suffix; bool isDevVersion; }; } //namespace #endif ugene-1.9.8/src/corelibs/U2Core/src/globals/IdRegistry.h0000644000175000017500000000165011651544331021457 0ustar ilyailya#ifndef _U2_COREAPI_ID_REGISTRY_H_ #define _U2_COREAPI_ID_REGISTRY_H_ namespace U2 { /************************************* * template class for default registry *************************************/ template class IdRegistry { public: virtual T* getById(const QString& id) {return registry.value(id);} virtual bool registerEntry(T* t) { if (registry.contains(t->getId())) { return false; } else { registry.insert(t->getId(), t); return true; } } virtual T* unregisterEntry(const QString& id) {return registry.take(id);} virtual ~IdRegistry() { qDeleteAll(registry.values());} virtual QList getAllEntries() const {return registry.values();} virtual QList getAllIds() const {return registry.uniqueKeys();} protected: QMap registry; }; // IdRegistry } // U2 #endif // _U2_COREAPI_ID_REGISTRY_H_ ugene-1.9.8/src/corelibs/U2Core/src/globals/Timer.h0000644000175000017500000000720011651544331020447 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_TIMER_H_ #define _U2_TIMER_H_ #include "global.h" #include "Counter.h" #include #ifdef Q_OS_WIN #include #else #include //#include #endif namespace U2 { class U2CORE_EXPORT GTimer : public QObject { Q_OBJECT public: //Returns microseconds since the Unix Epoch (Jan. 1, 1970), UTC inline static qint64 currentTimeMicros(); //suitable for values returned by GTimer::currentTimeMicros() call static QDateTime createDateTime(qint64 micros, Qt::TimeSpec spec = Qt::LocalTime); static int secsBetween(qint64 startTime, qint64 endTime) {return (int)((endTime-startTime)/(1000*1000));} static int millisBetween(qint64 startTime, qint64 endTime) {return (int)((endTime-startTime)/(1000));} }; #define WIN_USE_PERF_COUNTER class U2CORE_EXPORT TimeCounter { public: inline TimeCounter(GCounter* c, bool _start = true); inline ~TimeCounter(); inline void start(); inline void stop(); inline static qint64 getCounter(); static bool enabled; static double getCounterScale() {return frequency;} static const QString& getCounterSuffix() {return timeSuffix;} private: GCounter* totalCounter; qint64 startTime; bool started; static qint64 correction; static double frequency; static QString timeSuffix; }; #define GTIMER(cvar, tvar, name) \ static GCounter cvar(name, TimeCounter::getCounterSuffix(), TimeCounter::getCounterScale()); \ TimeCounter tvar(&cvar, true) #define WIN_UNIX_EPOCH_DELTA_MSEC qint64(11644473600000000) qint64 GTimer::currentTimeMicros() { qint64 res = 0; #ifdef Q_OS_WIN FILETIME time; GetSystemTimeAsFileTime(&time); // Convert FILETIME to Unix Epoch time res = (qint64)((quint64(time.dwHighDateTime)<<32) | time.dwLowDateTime) / 10; res-= WIN_UNIX_EPOCH_DELTA_MSEC; #else struct timeval tv; gettimeofday(&tv, NULL); res = qint64(tv.tv_sec)*1000*1000 + tv.tv_usec; #endif return res; } TimeCounter::TimeCounter(GCounter* c, bool _start) : totalCounter(c), startTime(0) { assert(totalCounter!=NULL); started = false; if (_start) { start(); } } TimeCounter::~TimeCounter() { if (started) { stop(); } } void TimeCounter::start() { assert(!started); startTime = getCounter(); started = true; } void TimeCounter::stop() { assert(started); qint64 endTime = getCounter(); totalCounter->totalCount += endTime - startTime - correction; started = false; } inline qint64 TimeCounter::getCounter() { #if defined(Q_OS_WIN) && defined(WIN_USE_PERF_COUNTER) LARGE_INTEGER count; QueryPerformanceCounter(&count); return count.QuadPart; #else return GTimer::currentTimeMicros(); #endif } } //namespace #endif ugene-1.9.8/src/corelibs/U2Core/src/globals/ProjectService.h0000644000175000017500000000343411651544331022323 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_PROJECT_SERVICE_H_ #define _U2_PROJECT_SERVICE_H_ #include #include #include #include #include namespace U2 { enum SaveProjectTaskKind { SaveProjectTaskKind_SaveProjectOnly, SaveProjectTaskKind_SaveProjectAndDocuments, SaveProjectTaskKind_SaveProjectAndDocumentsAskEach }; class U2CORE_EXPORT ProjectService : public Service { public: ProjectService(const QString& sname, const QString& sdesc) : Service(Service_Project, sname, sdesc, QList(), ServiceFlag_Singleton) {} virtual Project* getProject() const = 0; virtual Task* saveProjectTask(SaveProjectTaskKind kind) = 0; virtual Task* closeProjectTask() = 0; // hack to work around ambigous shortcuts virtual void enableSaveAction(bool e) = 0; }; }//namespace #endif ugene-1.9.8/src/corelibs/U2Core/src/globals/AppContext.h0000644000175000017500000003220311651544331021455 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_APPCONTEXT_H_ #define _U2_APPCONTEXT_H_ #include "global.h" namespace U2 { class PluginSupport; class ServiceRegistry; class ProjectLoader; class MainWindow; class ProjectView; class Project; class ProjectService; class PluginViewer; class Settings; class AppSettings; class AppSettingsGUI; class DocumentFormatRegistry; class IOAdapterRegistry; class DNATranslationRegistry; class DNAAlphabetRegistry; class GObjectViewFactoryRegistry; class ResourceTracker; class TaskScheduler; class DocumentFormatConfigurators; class AnnotationSettingsRegistry; class TestFramework; class DBXRefRegistry; class SubstMatrixRegistry; class SmithWatermanTaskFactoryRegistry; class MolecularSurfaceFactoryRegistry; class SWResultFilterRegistry; class MSAColorSchemeRegistry; class SecStructPredictAlgRegistry; class CudaGpuRegistry; class OpenCLGpuRegistry; class RecentlyDownloadedCache; class ProtocolInfoRegistry; class RemoteMachineMonitor; class PhyTreeGeneratorRegistry; class CMDLineRegistry; class MSAConsensusAlgorithmRegistry; class MSADistanceAlgorithmRegistry; class PWMConversionAlgorithmRegistry; class VirtualFileSystemRegistry; class DnaAssemblyAlgRegistry; class MSAAlignAlgRegistry; class AppGlobalObject; class DataBaseRegistry; class ExternalToolRegistry; class RepeatFinderTaskFactoryRegistry; class U2DbiRegistry; class QDActorPrototypeRegistry; class StructuralAlignmentAlgorithmRegistry; class AutoAnnotationsSupport; class CDSearchFactoryRegistry; class GUITestBase; class U2CORE_EXPORT AppContext : public QObject { Q_OBJECT public: virtual ~AppContext(){} static PluginSupport* getPluginSupport() {return getInstance()->_getPluginSupport();} static ServiceRegistry* getServiceRegistry() {return getInstance()->_getServiceRegistry();} static ProjectLoader* getProjectLoader() {return getInstance()->_getProjectLoader();} static Project* getProject() {return getInstance()->_getProject();} static ProjectService* getProjectService() {return getInstance()->_getProjectService();} static PluginViewer* getPluginViewer() {return getInstance()->_getPluginViewer();} /** admin level, readonly settings*/ static const Settings* getGlobalSettings() {return getInstance()->_getGlobalSettings();} /** per-user settings*/ static Settings* getSettings() {return getInstance()->_getSettings();} /** structured and preloaded settings */ static AppSettings * getAppSettings() { return getInstance()->_getAppSettings();} /** GUI for structured and preloaded settings */ static AppSettingsGUI* getAppSettingsGUI() {return getInstance()->_getAppSettingsGUI();} static MainWindow* getMainWindow() {return getInstance()->_getMainWindow();} static ProjectView* getProjectView() {return getInstance()->_getProjectView();} static DocumentFormatRegistry* getDocumentFormatRegistry() {return getInstance()->_getDocumentFormatRegistry();} static IOAdapterRegistry* getIOAdapterRegistry() {return getInstance()->_getIOAdapterRegistry();} static DNATranslationRegistry* getDNATranslationRegistry() {return getInstance()->_getDNATranslationRegistry();} static DNAAlphabetRegistry* getDNAAlphabetRegistry() {return getInstance()->_getDNAAlphabetRegistry();} static GObjectViewFactoryRegistry* getObjectViewFactoryRegistry() {return getInstance()->_getObjectViewFactoryRegistry();} static TaskScheduler* getTaskScheduler() {return getInstance()->_getTaskScheduler();} static ResourceTracker* getResourceTracker() {return getInstance()->_getResourceTracker();} static DocumentFormatConfigurators* getDocumentFormatConfigurators() {return getInstance()->_getDocumentFormatConfigurators();} static AnnotationSettingsRegistry* getAnnotationsSettingsRegistry() {return getInstance()->_getAnnotationsSettingsRegistry();} static TestFramework* getTestFramework() {return getInstance()->_getTestFramework();} static DBXRefRegistry* getDBXRefRegistry() {return getInstance()->_getDBXRefRegistry();} static SubstMatrixRegistry* getSubstMatrixRegistry() {return getInstance()->_getSubstMatrixRegistry();} static SmithWatermanTaskFactoryRegistry* getSmithWatermanTaskFactoryRegistry() {return getInstance()->_getSmithWatermanTaskFactoryRegistry();} static MolecularSurfaceFactoryRegistry* getMolecularSurfaceFactoryRegistry() {return getInstance()->_getMolecularSurfaceFactoryRegistry();} static SWResultFilterRegistry* getSWResultFilterRegistry() {return getInstance()->_getSWResultFilterRegistry();} static MSAColorSchemeRegistry* getMSAColorSchemeRegistry() { return getInstance()->_getMSAColorSchemeRegistry();} static SecStructPredictAlgRegistry* getSecStructPredictAlgRegistry() { return getInstance()->_getSecStructPredictAlgRegistry(); } static CudaGpuRegistry * getCudaGpuRegistry() { return getInstance()->_getCudaGpuRegistry(); } static OpenCLGpuRegistry * getOpenCLGpuRegistry() { return getInstance()->_getOpenCLGpuRegistry(); } static RecentlyDownloadedCache* getRecentlyDownloadedCache() { return getInstance()->_getRecentlyDownloadedCache(); } static ProtocolInfoRegistry * getProtocolInfoRegistry() { return getInstance()->_getProtocolInfoRegistry(); } static RemoteMachineMonitor * getRemoteMachineMonitor() { return getInstance()->_getRemoteMachineMonitor(); } static PhyTreeGeneratorRegistry *getPhyTreeGeneratorRegistry() {return getInstance()->_getPhyTreeGeneratorRegistry();} static CMDLineRegistry* getCMDLineRegistry() {return getInstance()->_getCMDLineRegistry();} static MSAConsensusAlgorithmRegistry* getMSAConsensusAlgorithmRegistry() {return getInstance()->_getMSAConsensusAlgorithmRegistry(); } static MSADistanceAlgorithmRegistry* getMSADistanceAlgorithmRegistry() {return getInstance()->_getMSADistanceAlgorithmRegistry(); } static PWMConversionAlgorithmRegistry* getPWMConversionAlgorithmRegistry() {return getInstance()->_getPWMConversionAlgorithmRegistry(); } static VirtualFileSystemRegistry * getVirtualFileSystemRegistry() { return getInstance()->_getVirtualFileSystemRegistry(); } static DnaAssemblyAlgRegistry* getDnaAssemblyAlgRegistry() { return getInstance()->_getDnaAssemblyAlgRegistry(); } static MSAAlignAlgRegistry* getMSAAlignAlgRegistry() { return getInstance()->_getMSAAlignAlgRegistry(); } static RepeatFinderTaskFactoryRegistry* getRepeatFinderTaskFactoryRegistry() {return getInstance()->_getRepeatFinderTaskFactoryRegistry();} static AutoAnnotationsSupport* getAutoAnnotationsSupport() { return getInstance()->_getAutoAnnotationsSupport(); } static CDSearchFactoryRegistry* getCDSFactoryRegistry() { return getInstance()->_getCDSFactoryRegistry(); } /** Registers application global resource */ static void registerGlobalObject(AppGlobalObject* obj) {return getInstance()->_registerGlobalObject(obj);} /** Unregisters application global resource */ static void unregisterGlobalObject(const QString& id) {return getInstance()->_unregisterGlobalObject(id);} /** Finds application global resource */ static AppGlobalObject* getGlobalObjectById(const QString& id) {return getInstance()->_getGlobalObjectById(id);} static DataBaseRegistry *getDataBaseRegistry() {return getInstance()->_getDataBaseRegistry();} static ExternalToolRegistry * getExternalToolRegistry() {return getInstance()->_getExternalToolRegistry();} static QDActorPrototypeRegistry* getQDActorProtoRegistry() { return getInstance()->_getQDActorFactoryRegistry(); } static StructuralAlignmentAlgorithmRegistry* getStructuralAlignmentAlgorithmRegistry() { return getInstance()->_getStructuralAlignmentAlgorithmRegistry(); } static U2DbiRegistry *getDbiRegistry() { return getInstance()->_getDbiRegistry(); } static bool isGUIMode() {return getInstance()->_isGUIMode(); } static QString getActiveWindowName() {return getInstance()->_getActiveWindowName();} static void setActiveWindowName(const QString &name) {getInstance()->_setActiveWindowName(name);} static GUITestBase *getGUITestBase() {return getInstance()->_getGUITestBase();} protected: static AppContext* getInstance() {assert(instance); return instance;} virtual PluginSupport* _getPluginSupport() const = 0; virtual ServiceRegistry* _getServiceRegistry() const = 0; virtual ProjectLoader* _getProjectLoader() const = 0; virtual Project* _getProject() const = 0; virtual ProjectService* _getProjectService() const = 0; virtual PluginViewer* _getPluginViewer() const = 0; virtual Settings* _getSettings() const = 0; virtual Settings* _getGlobalSettings() const = 0; virtual MainWindow* _getMainWindow() const = 0; virtual ProjectView* _getProjectView() const = 0; virtual DocumentFormatRegistry* _getDocumentFormatRegistry() const = 0; virtual IOAdapterRegistry* _getIOAdapterRegistry() const = 0; virtual DNATranslationRegistry* _getDNATranslationRegistry() const = 0; virtual DNAAlphabetRegistry* _getDNAAlphabetRegistry() const = 0; virtual GObjectViewFactoryRegistry* _getObjectViewFactoryRegistry() const = 0; virtual TaskScheduler* _getTaskScheduler() const = 0; virtual ResourceTracker* _getResourceTracker() const = 0; virtual DocumentFormatConfigurators* _getDocumentFormatConfigurators() const = 0; virtual AnnotationSettingsRegistry* _getAnnotationsSettingsRegistry() const = 0; virtual AppSettings * _getAppSettings() const = 0; virtual AppSettingsGUI* _getAppSettingsGUI() const = 0; virtual TestFramework* _getTestFramework() const = 0; virtual DBXRefRegistry* _getDBXRefRegistry() const = 0; virtual SubstMatrixRegistry* _getSubstMatrixRegistry() const = 0; virtual SmithWatermanTaskFactoryRegistry* _getSmithWatermanTaskFactoryRegistry() const = 0; virtual MolecularSurfaceFactoryRegistry* _getMolecularSurfaceFactoryRegistry()const = 0; virtual SWResultFilterRegistry* _getSWResultFilterRegistry() const = 0; virtual MSAColorSchemeRegistry* _getMSAColorSchemeRegistry() const = 0; virtual SecStructPredictAlgRegistry* _getSecStructPredictAlgRegistry() const = 0; virtual CudaGpuRegistry * _getCudaGpuRegistry() const = 0; virtual OpenCLGpuRegistry * _getOpenCLGpuRegistry() const = 0; virtual RecentlyDownloadedCache* _getRecentlyDownloadedCache() const = 0; virtual ProtocolInfoRegistry * _getProtocolInfoRegistry() const = 0; virtual RemoteMachineMonitor * _getRemoteMachineMonitor() const = 0; virtual PhyTreeGeneratorRegistry * _getPhyTreeGeneratorRegistry() const = 0; virtual CMDLineRegistry* _getCMDLineRegistry() const = 0; virtual MSAConsensusAlgorithmRegistry* _getMSAConsensusAlgorithmRegistry() const = 0; virtual MSADistanceAlgorithmRegistry* _getMSADistanceAlgorithmRegistry() const = 0; virtual PWMConversionAlgorithmRegistry* _getPWMConversionAlgorithmRegistry() const = 0; virtual VirtualFileSystemRegistry * _getVirtualFileSystemRegistry() const = 0; virtual DnaAssemblyAlgRegistry* _getDnaAssemblyAlgRegistry() const = 0; virtual MSAAlignAlgRegistry* _getMSAAlignAlgRegistry() const = 0; virtual DataBaseRegistry * _getDataBaseRegistry() const = 0; virtual ExternalToolRegistry * _getExternalToolRegistry() const = 0; virtual RepeatFinderTaskFactoryRegistry* _getRepeatFinderTaskFactoryRegistry() const = 0; virtual QDActorPrototypeRegistry* _getQDActorFactoryRegistry() const = 0; virtual StructuralAlignmentAlgorithmRegistry* _getStructuralAlignmentAlgorithmRegistry() const = 0; virtual AutoAnnotationsSupport* _getAutoAnnotationsSupport() const = 0; virtual U2DbiRegistry * _getDbiRegistry() const = 0; virtual CDSearchFactoryRegistry* _getCDSFactoryRegistry() const = 0; virtual GUITestBase* _getGUITestBase() const = 0; virtual void _registerGlobalObject(AppGlobalObject* go) = 0; virtual void _unregisterGlobalObject(const QString& id) = 0; virtual AppGlobalObject* _getGlobalObjectById(const QString& id) const = 0; virtual bool _isGUIMode() const = 0; virtual QString _getActiveWindowName() const = 0; virtual void _setActiveWindowName(const QString &name) = 0; static AppContext* instance; }; }//namespace #endif ugene-1.9.8/src/corelibs/U2Core/src/globals/DocumentFormatConfigurators.cpp0000644000175000017500000000317611651544331025427 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "DocumentFormatConfigurators.h" namespace U2 { DocumentFormatConfigurators::~DocumentFormatConfigurators() { foreach(DocumentFormatConfigurator* c, configs.values()) { delete c; } configs.clear(); } void DocumentFormatConfigurators::registerConfigurator(DocumentFormatConfigurator* c) { assert(!configs.contains(c->getFormatId())); configs[c->getFormatId()] = c; } void DocumentFormatConfigurators::unregisterConfigurator(const DocumentFormatId& id) { DocumentFormatConfigurator* c = configs.value(id); assert(c!=NULL); configs.remove(id); delete c; } DocumentFormatConfigurator* DocumentFormatConfigurators::findConfigurator(const DocumentFormatId& id) const { DocumentFormatConfigurator* c = configs.value(id); return c; } } //namespace ugene-1.9.8/src/corelibs/U2Core/src/globals/ServiceModel.cpp0000644000175000017500000000306511651544331022310 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "PluginModel.h" #include "ServiceModel.h" #include namespace U2 { Service::Service(ServiceType t, const QString& _name, const QString& _desc, const QList& _parentServices, ServiceFlags f) : type(t), name(_name), description(_desc), parentServices(_parentServices), state(ServiceState_Disabled_New), flags(f) { } void ServiceRegistry::_setServiceState(Service* s, ServiceState state) { assert(s->state!=state); ServiceState oldState = s->state; bool enabledBefore = s->isEnabled(); s->state = state; bool enabledAfter = s->isEnabled(); s->serviceStateChangedCallback(oldState, enabledBefore!=enabledAfter); emit si_serviceStateChanged(s, oldState); } }//namespace ugene-1.9.8/src/corelibs/U2Core/src/globals/Timer.cpp0000644000175000017500000000367511651544331021016 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "Timer.h" namespace U2 { QDateTime GTimer::createDateTime(qint64 micros, Qt::TimeSpec spec) { QDateTime res(QDate(1970, 1, 1), QTime(0, 0), Qt::UTC); res = res.addMSecs(micros/1000); assert(res.isValid()); return res.toTimeSpec(spec); } static double getFrequency() { double frequency = 0; #if defined(Q_OS_WIN) && defined(WIN_USE_PERF_COUNTER) LARGE_INTEGER freq; QueryPerformanceFrequency(&freq); frequency = (double)freq.QuadPart; #else frequency = 1000*1000; //microseconds #endif return frequency; } static qint64 getCorrection() { GCounter totalCounter("timer correction", "ticks", 1); totalCounter.dynamicCounter = true; TimeCounter tc(&totalCounter, false); tc.start(); tc.stop(); tc.start(); tc.stop(); tc.start(); tc.stop(); tc.start(); tc.stop(); qint64 correction = totalCounter.totalCount / 4; return correction; } qint64 TimeCounter::correction = getCorrection(); double TimeCounter::frequency = getFrequency(); bool TimeCounter::enabled = true; QString TimeCounter::timeSuffix("seconds"); } //namespace ugene-1.9.8/src/corelibs/U2Core/src/globals/ProjectService.cpp0000644000175000017500000000156211651544331022656 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "ProjectService.h" ugene-1.9.8/src/corelibs/U2Core/src/globals/Counter.h0000644000175000017500000000433211651544331021011 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_COUNTER_H_ #define _U2_COUNTER_H_ #include "global.h" #include namespace U2 { class U2CORE_EXPORT GCounter : public QObject { Q_OBJECT public: GCounter(const QString& name, const QString& suffix, double scale = 1); virtual ~GCounter(); static const QList& allCounters() {return getCounters();} QString name; QString suffix; qint64 totalCount; double counterScale; bool dynamicCounter; //true if created and deleted dynamically at application runtime (not static init time) double scaledTotal() const {return totalCount / counterScale;} protected: static QList& getCounters(); }; //Marks that counter will be reported by Shtirlitz //TODO: implement GPerformanceCounter for plugin_perf_monitor? class U2CORE_EXPORT GReportableCounter : public GCounter { Q_OBJECT public: GReportableCounter(const QString& name, const QString& suffix, double scale = 1); }; class U2CORE_EXPORT SimpleEventCounter { public: SimpleEventCounter(GCounter* tc) : totalCounter(tc), eventCount(1){ assert(tc!=NULL);} virtual ~SimpleEventCounter() {totalCounter->totalCount+=eventCount;} private: GCounter* totalCounter; qint64 eventCount; }; #define GCOUNTER(cvar, tvar, name) \ static GReportableCounter cvar(name, "", 1); \ SimpleEventCounter tvar(&cvar) } //namespace #endif ugene-1.9.8/src/corelibs/U2Core/src/globals/LogCache.cpp0000644000175000017500000000715411651544331021377 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "LogCache.h" #ifdef Q_OS_WIN32 #include "windows.h" #endif #include #define MAX_CACHE_SIZE 5000 namespace U2 { LogCache* LogCache::appGlobalCache = NULL; LogFilterItem::LogFilterItem(const QString& _category , LogLevel _minLevel) { category = _category; minLevel = _minLevel; } QString LogFilter::selectEffectiveCategory(const LogMessage& msg) const { QString result; foreach (const LogFilterItem& f, filters) { if (msg.level >= f.minLevel && msg.categories.contains(f.category)) { result = f.category; break; } } return result; } bool LogFilter::matches(const LogMessage& msg) const { return !selectEffectiveCategory(msg).isEmpty(); } ////////////////////////////////////////////////////////////////////////// // LogCache LogCache::LogCache() { connect(LogServer::getInstance(), SIGNAL(si_message(const LogMessage&)), SLOT(sl_onMessage(const LogMessage&))); } LogCache::~LogCache() { while (!messages.empty()) { LogMessage* m = messages.takeFirst(); delete m; } } void LogCache::sl_onMessage(const LogMessage& msg) { if (!filter.isEmpty() && !filter.matches(msg)) { return; } messages.append(new LogMessage(msg.categories, msg.level, msg.text)); updateSize(); } void LogCache::updateSize() { while (messages.size() > MAX_CACHE_SIZE) { LogMessage* m = messages.takeFirst(); delete m; } } void LogCache::setAppGlobalInstance(LogCache* cache) { assert(appGlobalCache == NULL); appGlobalCache = cache; } ////////////////////////////////////////////////////////////////////////// // Cache EXT LogCacheExt::LogCacheExt() { consoleEnabled = false; fileEnabled = false; } bool LogCacheExt::setFileOutputEnabled(const QString& fileName) { if (fileName.isEmpty()) { file.close(); fileEnabled = false; return true; } if (file.isOpen()) { file.close(); fileEnabled = false; } file.setFileName(fileName); if (!file.open(QIODevice::WriteOnly | QIODevice::Truncate)) { return false; } fileEnabled = true; return true; } void LogCacheExt::sl_onMessage(const LogMessage& msg) { if (!filter.isEmpty() && !filter.matches(msg)) { return; } if (consoleEnabled){ QByteArray ba = msg.text.toLocal8Bit(); char* buf = ba.data(); #ifdef Q_OS_WIN32 // a bit of magic to workaround Windows console encoding issues CharToOemA(buf,buf); #endif printf("%s\n", buf); } if (fileEnabled) { QByteArray ba = msg.text.toLocal8Bit(); char* buf = ba.data(); file.write(buf, ba.length()); file.write("\n", 1); file.flush(); } LogCache::sl_onMessage(msg); } }//namespace ugene-1.9.8/src/corelibs/U2Core/src/globals/DataBaseRegistry.h0000644000175000017500000000410411651544331022564 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _DATABASE_REGISTRY_ #define _DATABASE_REGISTRY_ #include #include #include #include #include #include #include namespace U2 { class HttpRequest { public: virtual void sendRequest(const QString &program,const QString &query) = 0; virtual QList getAnnotations() {return result;} virtual QString getError() { return error; } virtual QByteArray getOutputFile() {return NULL;} virtual ~HttpRequest() {}; bool connectionError; protected: HttpRequest(Task *_task):connectionError(false),error(""),task(_task){}; QString error; QList result; Task *task; }; class DataBaseFactory { public: virtual ~DataBaseFactory() {} virtual HttpRequest * getRequest(Task *t) = 0; }; class U2CORE_EXPORT DataBaseRegistry:public QObject{ Q_OBJECT public: DataBaseRegistry(QObject *o = 0); ~DataBaseRegistry(); bool registerDataBase(DataBaseFactory *f, const QString &id); DataBaseFactory *getFactoryById(const QString& id); bool isRegistered(const QString& id); private: QMap factories; }; } #endifugene-1.9.8/src/corelibs/U2Core/src/globals/AppGlobalObject.cpp0000644000175000017500000000156311651544331022720 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "AppGlobalObject.h" ugene-1.9.8/src/corelibs/U2Core/src/globals/DBXRefRegistry.h0000644000175000017500000000444211651544331022177 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_DBXREF_H_ #define _U2_DBXREF_H_ #include #include #include #include #include #include namespace U2 { class U2CORE_EXPORT DBXRefInfo { public: DBXRefInfo(){}; DBXRefInfo(const QString& _name, const QString& _url, const QString& _fileUrl, const QString& _comment) : name(_name), url(_url), fileUrl(_fileUrl), comment(_comment){} QString name; QString url; QString fileUrl; QString comment; static void setupToEngine(QScriptEngine *engine); private: static QScriptValue toScriptValue(QScriptEngine *engine, DBXRefInfo const &in); static void fromScriptValue(const QScriptValue &object, DBXRefInfo &out); }; class U2CORE_EXPORT DBXRefRegistry : public QObject { Q_OBJECT public: DBXRefRegistry(QObject* p = NULL); Q_INVOKABLE DBXRefInfo getRefByKey(const QString& dbxrefKey)const {return refsByKey.value(dbxrefKey);} static void setupToEngine(QScriptEngine *engine); const QMap& getEntries() { return refsByKey; } private: static QScriptValue toScriptValue(QScriptEngine *engine, DBXRefRegistry* const &in); static void fromScriptValue(const QScriptValue &object, DBXRefRegistry* &out); QMap refsByKey; }; }//namespace Q_DECLARE_METATYPE(U2::DBXRefRegistry*) Q_DECLARE_METATYPE(U2::DBXRefInfo) #endif ugene-1.9.8/src/corelibs/U2Core/src/globals/Version.cpp0000644000175000017500000000577311651544331021364 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "Version.h" // UGENE_VERSION must be supplied as a preprocessor directive #ifndef UGENE_VERSION #error UGENE_VERSION is not set! #endif namespace U2 { #define STRINGIFY(x) #x #define TOSTRING(x) STRINGIFY(x) #define UGENE_VERSION_STRING TOSTRING(UGENE_VERSION) #define VERSION_DEV_SUFFIX "dev" Version::Version() { major = minor = patch = 0; debug = false; text = "unknown"; } Version Version::parseVersion(const QString& text) { Version v; v.text = text; //parse sub-numbers and suffix int versionType = 0; QString currentNum; int textPos = 0; for (; textPos < v.text.length(); textPos++ ) { QChar c = v.text.at(textPos); if (c.isNumber()) { currentNum += c; } else { bool ok; int val = currentNum.toInt(&ok); if (!ok) { break; } if (versionType == 0) { v.major = val; } else if (versionType == 1) { v.minor = val; } else { v.patch = val; break; } versionType++; currentNum.clear(); } } v.suffix = v.text.mid(textPos); v.isDevVersion = v.suffix.contains(VERSION_DEV_SUFFIX); #ifdef _DEBUG v.debug = true; #else v.debug = false; #endif return v; } Version Version::ugeneVersion() { return parseVersion(UGENE_VERSION_STRING); } Version Version::qtVersion() { return parseVersion(QT_VERSION_STR); } bool Version::operator > (const Version& v) const { return v < *this; } bool Version::operator >= (const Version& v) const { return v <= *this; } bool Version::operator < (const Version& v) const { if (v.major != major) { return v.major > major; } if (v.minor != minor) { return v.minor > minor; } if (v.patch != patch) { return v.patch > patch; } return false; } bool Version::operator <= (const Version& v) const { return *this < v || *this == v; } bool Version::operator == (const Version& v) const { return major == v.major && minor == v.minor && patch == v.patch; } } //namespace ugene-1.9.8/src/corelibs/U2Core/src/globals/DocumentFormatConfigurators.h0000644000175000017500000000347211651544331025073 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_DOC_FORMAT_CONFIG_H_ #define _U2_DOC_FORMAT_CONFIG_H_ #include namespace U2 { class U2CORE_EXPORT DocumentFormatConfigurator : public QObject { Q_OBJECT public: DocumentFormatConfigurator(const DocumentFormatId& _formatId, QObject* p = NULL): QObject(p), formatId(_formatId){} DocumentFormatId getFormatId() const {return formatId;} virtual void configure(QVariantMap& info) = 0; protected: DocumentFormatId formatId; }; class U2CORE_EXPORT DocumentFormatConfigurators : public QObject { Q_OBJECT public: DocumentFormatConfigurators(QObject* p = NULL): QObject(p){} virtual ~DocumentFormatConfigurators(); void registerConfigurator(DocumentFormatConfigurator* c); void unregisterConfigurator(const DocumentFormatId& id); DocumentFormatConfigurator* findConfigurator(const DocumentFormatId& id) const; private: QMap configs; }; }//namespace #endif ugene-1.9.8/src/corelibs/U2Core/src/globals/GAutoDeleteList.cpp0000644000175000017500000000156311651544331022726 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "GAutoDeleteList.h" ugene-1.9.8/src/corelibs/U2Core/src/globals/LogCache.h0000644000175000017500000000501411651544331021035 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_LOG_CACHE_H_ #define _U2_LOG_CACHE_H_ #include #include #include namespace U2 { class U2CORE_EXPORT LogFilterItem { public: QString category; LogLevel minLevel; LogFilterItem(const QString& category = QString(), LogLevel minLevel = LogLevel_INFO); }; class U2CORE_EXPORT LogFilter { public: LogFilter(){} QList filters; bool isEmpty() const {return filters.isEmpty();} bool matches(const LogMessage& msg) const; QString selectEffectiveCategory(const LogMessage& msg) const; }; class U2CORE_EXPORT LogCache : public QObject { Q_OBJECT public: LogCache(); virtual ~LogCache(); static void setAppGlobalInstance(LogCache* cache); static LogCache* getAppGlobalInstance() {return appGlobalCache;} protected slots: virtual void sl_onMessage(const LogMessage& msg); private: static LogCache* appGlobalCache; void updateSize(); public: QList messages; LogFilter filter; }; /** Extended cache version that dumps messages to file or console */ class U2CORE_EXPORT LogCacheExt : public LogCache { Q_OBJECT public: LogCacheExt(); void setConsoleOutputEnabled(bool enabled) {consoleEnabled = enabled;} bool isConsoleOutputEnabled() const {return consoleEnabled;} bool setFileOutputEnabled(const QString& file); bool isFileOutputEnabled() const {return fileEnabled;} QString getFileOutputPath() const {return QFileInfo(file).canonicalFilePath();} protected slots: virtual void sl_onMessage(const LogMessage& msg); private: bool consoleEnabled; bool fileEnabled; QFile file; }; } //namespace #endif ugene-1.9.8/src/corelibs/U2Core/src/globals/ExternalToolRegistry.h0000644000175000017500000000640211651544331023543 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_EXTERNAL_TOOL_REGISTRY_H #define _U2_EXTERNAL_TOOL_REGISTRY_H #include #include #include #include #include #include #include #include namespace U2 { class U2CORE_EXPORT ExternalTool : public QObject { Q_OBJECT public: ExternalTool(QString name, QString path = ""); ~ExternalTool(); const QString& getName() const { return name; } const QString& getPath() const { return path; } const QIcon& getIcon() const { return icon; } const QIcon& getGrayIcon() const { return grayIcon; } const QIcon& getWarnIcon() const { return warnIcon; } const QString& getDescription() const { return description; } const QString& getExecutableFileName() const { return executableFileName; } const QStringList& getValidationArguments() const { return validationArguments; } const QString& getValidMessage() const { return validMessage; } const QString& getVersion() const { return version; } const QRegExp& getVersionRegExp() const { return versionRegExp; } const QString& getToolKitName() const { return toolKitName; } void setPath(const QString& _path); void setValid(bool _isValid); void setVersion(const QString& _version); bool isValid() const { return isValidTool; }//may be not needed signals: void si_pathChanged(); protected: QString name; QString path; QIcon icon; QIcon grayIcon; QIcon warnIcon; QString description; QString executableFileName; QStringList validationArguments; QString validMessage; QString version; QRegExp versionRegExp; bool isValidTool; QString toolKitName; }; // ExternalTool class U2CORE_EXPORT ExternalToolRegistry : public QObject { Q_OBJECT public: ~ExternalToolRegistry(); ExternalTool* getByName(const QString& id); bool registerEntry(ExternalTool* t); void unregisterEntry(const QString& id); QList getAllEntries() const; QList< QList > getAllEntriesSortedByToolKits() const; protected: QMap registry; QString temporaryDirectory; }; // ExternalToolRegistry } //namespace #endif // U2_EXTERNAL_TOOL_REGISTRY_H ugene-1.9.8/src/corelibs/U2Core/src/globals/DataBaseRegistry.cpp0000644000175000017500000000313211651544331023117 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "DataBaseRegistry.h" namespace U2 { DataBaseRegistry::DataBaseRegistry(QObject *o):QObject(o) { } DataBaseRegistry::~DataBaseRegistry() { foreach(const DataBaseFactory *dbf, factories) { delete dbf; } } bool DataBaseRegistry::registerDataBase(DataBaseFactory *f, const QString &id) { if(!isRegistered(id)) { factories[id] = f; return true; } else { return false; } } bool DataBaseRegistry::isRegistered(const QString& id) { if(factories.contains(id)) { return true; } else { return false; } } DataBaseFactory *DataBaseRegistry::getFactoryById(const QString &id) { if(isRegistered(id)) { return factories[id]; } else { return NULL; } } }ugene-1.9.8/src/corelibs/U2Core/src/globals/L10n.h0000644000175000017500000000574311651544331020113 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_L10N_H_ #define _U2_L10N_H_ #include #include namespace U2 { class U2CORE_EXPORT L10N: public QObject { Q_OBJECT public: // general purpose messages static QString errorTitle() { return tr("Error!");} static QString warningTitle() { return tr("Warning!");} static QString badArgument(const QString& name) { return tr("Internal error, bad argument: %1").arg(name);} static QString outOfMemory() {return tr("Out of memory!");} static QString internalError() {return tr("Internal error!");} // messages to work with files static QString errorOpeningFileRead(const GUrl& url) { return tr("Error opening URL for read: '%1'").arg(url.getURLString());} static QString errorOpeningFileWrite(const GUrl& url) { return tr("Error opening URL for write: '%1'").arg(url.getURLString());} static QString errorWritingFile(const GUrl& url) { return tr("Write error: '%1'").arg(url.getURLString());} static QString errorReadingFile(const GUrl& url) { return tr("Read error: %1").arg(url.getURLString());} static QString errorFileTooLarge(const GUrl& url) { return tr("File is too large: '%1'").arg(url.getURLString());} static QString errorFileNotFound(const GUrl& url) {return tr("File not found %1").arg(url.getURLString());} static QString errorIsNotAFile(const GUrl& url) {return tr("%1 is not a file").arg(url.getURLString());} static QString notValidFileFormat(const QString& type, const GUrl& url) {return tr("Invalid file format. Expected file format: %1, File: %2").arg(type).arg(url.getURLString());} // working with qt plugins: images, scripts, styles static QString errorImageSave(const QString& file, const QString& format) { return tr("Can't save image to file %1, format %2").arg(file).arg(format); } static QString errorDocumentNotFound(const GUrl& url) { return tr("Document not found: %1").arg(url.getURLString());} static QString suffixBp() { return tr(" bp");} // phylogenetic tree settings static QString treePhylogram() { return tr("Phylogram"); } static QString treeCladogram() { return tr("Cladogram"); } }; }//ns #endif ugene-1.9.8/src/corelibs/U2Core/src/globals/AutoAnnotationsSupport.h0000644000175000017500000001007111651544331024112 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_AUTO_ANNOTATIONS_SUPPORT_H_ #define _U2_AUTO_ANNOTATIONS_SUPPORT_H_ #include #include #include namespace U2 { class GObject; class GHints; class AnnotationTableObject; class DNASequenceObject; class DNAAlphabet; class StateLock; // This object represents in-memory AnnotationTableObject. // Auto-annotations are used to represent temporary algorithm results, // such as for example restriction sites or ORFS. // Auto-annotations are controlled by AnnotatedDNAView. class AutoAnnotationsUpdater; class AutoAnnotationsSupport; class U2CORE_EXPORT AutoAnnotationObject : public QObject { Q_OBJECT public: static const QString AUTO_ANNOTATION_HINT; AutoAnnotationObject(DNASequenceObject* obj); ~AutoAnnotationObject(); AnnotationTableObject* getAnnotationObject() const { return aobj; } DNASequenceObject* getSeqObject() const {return dnaObj; } void setGroupEnabled(const QString& groupName, bool enabled); void update(); void updateGroup(const QString& groupName); void emitStateChange(bool started); signals: void si_updateStarted(); void si_updateFinshed(); private: void handleUpdate(QList updaters); DNASequenceObject* dnaObj; AnnotationTableObject* aobj; AutoAnnotationsSupport* aaSupport; QSet enabledGroups; }; #define AUTO_ANNOTATION_SETTINGS "auto-annotations/" struct AutoAnnotationConstraints { AutoAnnotationConstraints() : alphabet(NULL), hints(NULL) {} DNAAlphabet* alphabet; GHints* hints; }; class U2CORE_EXPORT AutoAnnotationsUpdater : public QObject { Q_OBJECT private: QString groupName; QString name; bool checkedByDefault; public: AutoAnnotationsUpdater(const QString& nm, const QString& gName); virtual ~AutoAnnotationsUpdater(); const QString& getGroupName() { return groupName; } const QString& getName() { return name; } bool isCheckedByDefault() { return checkedByDefault; } void setCheckedByDefault(bool checked) { checkedByDefault = checked; } virtual bool checkConstraints(const AutoAnnotationConstraints& constraints) = 0; virtual Task* createAutoAnnotationsUpdateTask(const AutoAnnotationObject* aa) = 0; }; class U2CORE_EXPORT AutoAnnotationsSupport : public QObject { Q_OBJECT public: ~AutoAnnotationsSupport(); void registerAutoAnnotationsUpdater(AutoAnnotationsUpdater* updater); void unregisterAutoAnnotationsUpdater(AutoAnnotationsUpdater* updater); QList getAutoAnnotationUpdaters(); AutoAnnotationsUpdater* findUpdaterByGroupName(const QString& groupName); AutoAnnotationsUpdater* findUpdaterByName(const QString& name); static bool isAutoAnnotation(const AnnotationTableObject* obj); static bool isAutoAnnotation(const GObject* obj); private: QList aaUpdaters; }; class U2CORE_EXPORT AutoAnnotationsUpdateTask : public Task { Q_OBJECT public: AutoAnnotationsUpdateTask(AutoAnnotationObject* aaObj, QList subtasks); virtual void prepare(); ReportResult report(); static const QString NAME; protected: AutoAnnotationObject* aa; StateLock* lock; QList subTasks; }; } // namespace #endif ugene-1.9.8/src/corelibs/U2Core/src/globals/ServiceModel.h0000644000175000017500000001037411651544331021756 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_SERVICE_MODEL_H_ #define _U2_SERVICE_MODEL_H_ #include #include #include #include namespace U2 { class Task; class Plugin; class Service; enum ServiceState { ServiceState_Enabled, ServiceState_Disabled_New, ServiceState_Disabled_Manually, ServiceState_Disabled_ParentDisabled, ServiceState_Disabled_CircularDependency, ServiceState_Disabled_FailedToStart }; enum ServiceFlag { ServiceFlag_None = 0, //no flags ServiceFlag_Singleton = 1, //only one service with this id can be registered }; typedef QFlags ServiceFlags; class U2CORE_EXPORT Service : public QObject { friend class ServiceRegistry; friend class ServiceLock; Q_OBJECT public: Service(ServiceType t, const QString& _name, const QString& _desc, const QList& parentServices = QList(), ServiceFlags flags = ServiceFlag_None); const QList& getParentServiceTypes() const {return parentServices;} ServiceType getType() const {return type;} const QString& getName() const {return name;} const QString& getDescription() const {return description;} ServiceState getState() const {return state;} bool isDisabled() const {return state!=ServiceState_Enabled;} bool isEnabled() const {return !isDisabled();} ServiceFlags getFlags() const {return flags;} protected: /// returns NULL if no actions are required to enable service virtual Task* createServiceEnablingTask() {return NULL;} /// returns NULL if no actions are required to disable service virtual Task* createServiceDisablingTask() {return NULL;} virtual void serviceStateChangedCallback(ServiceState oldState, bool enabledStateChanged) { Q_UNUSED(oldState); Q_UNUSED(enabledStateChanged);} private: ServiceType type; QString name; QString description; QList parentServices; ServiceState state; ServiceFlags flags; }; ////////////////////////////////////////////////////////////////////////// // service registry class U2CORE_EXPORT ServiceRegistry : public QObject { Q_OBJECT public: /// Returns list of all registered services virtual const QList& getServices() const = 0; /// Finds service with the specified ServiceType virtual QList findServices(ServiceType t) const = 0; /// registers the service in a registry and initiates enabling task if all parent services are enabled /// if service started successfully - checks all child services if new services can be started virtual Task* registerServiceTask(Service* s) = 0; /// unregisters the service in a registry. /// if the service is enabled -> initiates service disabling task first virtual Task* unregisterServiceTask(Service* s) = 0; virtual Task* enableServiceTask(Service* s) = 0; virtual Task* disableServiceTask(Service* s) = 0; protected: void _setServiceState(Service* s, ServiceState state); Task* _createServiceEnablingTask(Service* s) {return s->createServiceEnablingTask();} Task* _createServiceDisablingTask(Service* s) {return s->createServiceDisablingTask();} signals: void si_serviceRegistered(Service* s); void si_serviceUnregistered(Service* s); void si_serviceStateChanged(Service* s, ServiceState oldState); }; }//namespace #endif ugene-1.9.8/src/corelibs/U2Core/src/globals/ResourceTracker.h0000644000175000017500000000313211651544331022472 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_RESOURCE_TRACKER_H_ #define _U2_RESOURCE_TRACKER_H_ #include #include #include namespace U2 { class Task; class U2CORE_EXPORT ResourceTracker : public QObject { Q_OBJECT public: ResourceTracker(){} ~ResourceTracker(); void registerResourceUser(const QString& resourceName, Task* t); void unregisterResourceUser(const QString& resourceName, Task* t); QList getResourceUsers(const QString& resourceName); signals: void si_resourceUserRegistered(const QString& rName, Task* t); void si_resourceUserUnregistered(const QString& rName, Task* t); private: typedef QList TList; typedef QMap RMap; RMap resMap; }; } //namespace #endif ugene-1.9.8/src/corelibs/U2Core/src/globals/Counter.cpp0000644000175000017500000000271411651544331021346 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "Counter.h" namespace U2 { QList& GCounter::getCounters() { static QList counters; return counters; } GCounter::GCounter(const QString& _name, const QString& s, double scale) : name(_name), suffix(s), totalCount(0), counterScale(scale) { assert(counterScale > 0); getCounters().append(this); dynamicCounter = false; } GCounter::~GCounter() { if (dynamicCounter) { getCounters().removeOne(this); } } GReportableCounter::GReportableCounter(const QString& name, const QString& suffix, double scale /* = 1 */) : GCounter(name, suffix, scale) { } } //namespace ugene-1.9.8/src/corelibs/U2Core/U2Core.pri0000644000175000017500000000173711651544331016630 0ustar ilyailya# include (U2Core.pri) MODULE_ID=U2Core include( ../../ugene_lib_common.pri ) UGENE_RELATIVE_DESTDIR = '' QT += network xml DEFINES+= QT_FATAL_ASSERT BUILDING_U2CORE_DLL use_bundled_zlib() { INCLUDEPATH += ../../libs_3rdparty/zlib/src LIBS += -lzlib } else { LIBS += -lz } LIBS += -L../../_release LIBS += -lugenedb INCLUDEPATH += ../../libs_3rdparty/sqlite3/src !debug_and_release|build_pass { CONFIG(debug, debug|release) { DESTDIR=../../_debug LIBS += -L../../_debug LIBS -= -L../../_release use_bundled_zlib() { LIBS += -lzlibd LIBS -= -lzlib } LIBS -= -lugenedb LIBS += -lugenedbd } CONFIG(release, debug|release) { DESTDIR=../../_release } } # Special compiler flags for windows configuration win32 { LIBS += Psapi.lib } unix { target.path = $$UGENE_INSTALL_DIR/$$UGENE_RELATIVE_DESTDIR INSTALLS += target } HEADERS += ../../include/U2Core/U2*.h ugene-1.9.8/src/corelibs/U2Core/transl/0000755000175000017500000000000011651544332016311 5ustar ilyailyaugene-1.9.8/src/corelibs/U2Core/transl/russian.ts0000644000175000017500000017021011651544332020346 0ustar ilyailya Document Document is not loaded Выгружен IO adapter does not support write operation Адаптер ввода/вывода не поддерживает запись No write support for document format Запись для данного формата не поддерживается Locked by user Заблокирован пользователем DocumentFormat The document is created not by UGENE Документ создан не в UGENE Document sequences were merged Последовательности из документа были соединены Writing is not supported for this format (%1). Feel free to send a feature request though. Запись в этот формат (%1) сейчас не поддерживается. Пожалуйста, сделайте запрос разработчикам. GObject Unknown Неизвестный тип Unloaded Не загруженный Text Текст Sequence Последовательность Sequences Последовательности Annotation Аннотация Annotations Аннотации Chromatogram Хроматограмма Chromatograms Хроматограммы Alignment Выравнивание Alignments Выравнивания Tree Дерево Trees Деревья 3D model 3D модель 3D models 3D модели Index Индекс Indexes Индексы Assembly Assemblies QObject This is not ESearch result! Use Genbank DNA accession number. For example: NC_001363 or D11266 Используйте Genbank Accession Number. Например: NC_001363 или D11266 Use Genbank protein accession number. For example: AAA59172.1 Используйте Genbank Accession Number. Например: AAA59172.1 Use PDB molecule four-letter identifier. For example: 3INS or 1CRN Используйте 4-х символьный идентификатор PDB. Например: 3INS или 1CRN Use SWISS-PROT accession number. For example: Q9IGQ6 or A0N8V2 Use UniProtKB/Swiss-Prot accession number. For example: P16152 Use UniProtKB/TrEMBL accession number. For example: D0VTW9 Use %1 unique identifier. Исплользуйте уникальный идентификатор %1. U2::AddDocumentTask add_document_task Добавление документа Add document to the project: %1 Добавить документ к проекту:%1 No project is opened Нет открытых проектов Document is already added to the project %1 Документ уже добавлен в проект: %1 Document was removed Документ был удалён U2::AddPartToSequenceTask Insert subsequence Вставка подпоследовательности Insertion position is out of bounds Insertion position is out of sequence bounds Позиция для вставки выходит за границы последовательности Document is locked Документ заблокирован U2::AddSequencesToAlignmentTask Sequence %1 from %2 has different alphabet Алфавит последовательности %1 из %2 отличается U2::AnnotationTableObject Sequence Последовательность Translation Трансляции U2::AppResourcePool Threads Потоки Memory Память Mb Project Проект Phytree Филогенетическое дерево U2::AutoAnnotationsSupport Auto-annotations [%1 | %2] U2::CMDLineCoreOptions ugene will continue executing after finishing given tasks ugene продолжит исполнение после завершения всех заданий read files with serialized tasks and run them запустить сериализованную задачу ugene из файла load test suites and run them запустить тестовые наборы set directory for test report установить директорию для отчета по тестированию set number of threads in test runner that can run at the same time установить количество потоков, которое будет использоваться в тестах load configuration from the specified file загрузить конфигурацию из заданного файла get settings from settings file установить настройки из файла настроек run given workflow schema запуск выбранной схемы дизайнера вычислительных схем Shows help information. Loads UGENE configuration. Loads configuration from the specified .ini file. By default the UGENE.ini file is used. <path_to_file> Specifies the language to use. Specifies the language to use. The following values are available: CS, EN, RU. <language_code> U2::CopyDataTask Copy Data Task Копирование данных Cannot get data from: '%1' Не могу извлечь данные из: "%1" No data in source Отсутствуют входные данные IO adapter error Внутренняя ошибка cannot_open_io_adapter Ошибка открытия адаптеров ввода/вывода io_adapter_error Внутренняя ошибка U2::CreateAnnotationsTask Create annotations Сохранение аннотаций Annotation object '%1' not found in active project: %2 Таблица аннотаций "%1" не найдена в проекте: %2 Waiting for object lock released Ожидание снятия блокировки U2::CreateFileIndexTask Create index: %1 Создание индекса: %1 No files to index Нет данных для индексирования Internal error: inconsistent input data Внутренняя ошибка Illegal output file parameters Can't open file for read: '%1' Ошибка открытия файла для чтения: %1 Error creating gzipped output Ошибка записи gzip Can't create index using %1 IO adapter Внутренняя ошибка: неподдерживаемый адаптер ввода/вывода %1 Can't detect file format: %1 Неизвестный формат файла: %1 UGENE can't index files of a specified format: %1 Индексирование указанного формата не поддерживается: %1 U2::DBXRefRegistry File with db_xref mappings not found: %1 Не найден файл реестра dbxref Illegal db_xref file entry: %1 Неверный формат элемента: "%1" U2::DNAAlphabetRegistryImpl All symbols Любые символы Standard DNA Standard RNA Extended DNA Extended RNA Standard amino Standard amino alphabet Стандартный алфавит аминокислот Standard DNA alphabet Стандартный алфавит ДНК Standard RNA alphabet Стандартный алфавит РНК Extended DNA alphabet Расширенный алфавит ДНК Extended RNA alphabet Расширенный алфавит РНК Complement for standard DNA комплeментарная трансляция к стандартному ДНК алфавиту Complement for standard RNA комплeментарная трансляция к стандартному РНК алфавиту Complement for extended DNA комплeментарная траснсляция для расширенного алфавита ДНК Complement for extended RNA комплeментарная трансляция к расширенному РНК алфавиту The file is not an XML codon usage database. Файл не является валидной базой данных использования кодонов. 1. The Standard Genetic Code 1. Стандартный Генетический Код 2. The Vertebrate Mitochondrial Code 2. Митохондриальный Код Позвоночных 3. The Yeast Mitochondrial Code 3. Митохондриальный Код Дрожжей 4. The Mold, Protozoan, and Coelenterate Mitochondria and the Mycoplasma Code 5. The Invertebrate Mitochondrial Code 5. Митохондриальный Код Позвоночных 6. The Ciliate, Dasycladacean and Hexamita Nuclear Code 9. The Echinoderm and Flatworm Mitochondrial Code 9. Митохондриальный Код Иглокожих и Плоских Червей 10. The Euplotid Nuclear Code 11. The Bacterial and Plant Plastid Code 11. Код Пластид Бактерий и Растений 12. The Alternative Yeast Nuclear Code 13. The Ascidian Mitochondrial Code 14. The Alternative Flatworm Mitochondrial Code 15. Blepharisma Nuclear Code 16. Chlorophycean Mitochondrial Code 21. Trematode Mitochondrial Code 22. Scenedesmus obliquus Mitochondrial Code 23. Thraustochytrium Mitochondrial Code U2::DocumentFormat The document is created not by UGENE Документ создан не в UGENE Document sequences were merged Последовательности из документа были соединены Writing is not supported for this format (%1). Feel free to send a feature request though. Запись в этот формат (%1) сейчас не поддерживается. Пожалуйста, сделайте запрос разработчикам. U2::ExportToNewFileFromIndexTask Invalid document number: %1, max: %2 Неверный номер документа: %1, предел %2 No IO adapter found for URL: %1 Can't open file for write: '%1' Ошибка открытия файла для записи: %1 Export filename is empty Не указано имя файла Index is inconsistent Индекс повреждён Document numbers list is empty Пустой список документов Export from index Экспорт из индекса U2::ExtractAnnotatedRegionTask Extract annotated regions Разбиение последовательности на аннотированные регионы U2::FailTask Failure Ошибка U2::GObject Unknown Неизвестный тип Unloaded Не загруженный Text Текст Sequence Последовательность Annotation Аннотация Chromatogram Хроматограмма Alignment Выравнивание Tree Дерево 3D model 3D модель Sequences Последовательности Annotations Аннотации Chromatograms Хроматограммы Alignments Выравнивания Trees Деревья 3D models 3D модели Index Индекс Indexes Индексы U2::GUrlUtils Renamed %1 to %2 Старый файл %1 переименован в %2 Failed to rename %1 to %2 Не удалось переименовать %1 в %2 Directory is not specified Директория не указана Directory can't be created: %1 Невозможно создать директорию: %1 Directory can't be read: %1 Файлы директории %1 невозможно открыть на чтение U2::GetDocumentFromIndexTask Can't find IO adapter: %1 Не найден адаптер ввода/вывода: %1 Can't open file for read: '%1' Ошибка открытия файла для чтения: %1 Error positioning in indexed file Ошибка позиционирования в индексе GZIP index is corrupted GZIP Индекс повреждён Get document from index Извлечение документа из индекса Index is empty Индекс пуст Invalid document number: %1, max: %2 Неверный номер документа: %1, предел %2 Index is corrupted Индекс повреждён Unknown document format: %1 Неизвестный формат документа: %1 U2::GzippedHttpFileAdapterFactory HTTP GZIP adaptor HTTP GZIP адаптер U2::GzippedLocalFileAdapterFactory GZIP file Локальный GZIP адаптер U2::HttpFileAdapterFactory HTTP file HTTP адаптер U2::L10N Error! Ошибка! Warning! Внимание! Out of memory! Error opening URL for read: '%1' Ошибка открытия файла для чтения: %1 Error opening URL for write: '%1' Ошибка открытия файла для записи: %1 Write error: '%1' Ошибка записи: %1 Read error: %1 Ошибка чтения: %1 File is too large: '%1' Слишком большой размер файла: %1 File not found %1 Файл не найден %1 %1 is not a file Invalid file format. Expected file format: %1, File: %2 Неверный формат файла. Ожидаемый формат: %1, Файл: %2 Can't save image to file %1, format %2 Не могу сохранить изображение в файл %1 формата %2 Document not found: %1 Документ не найден: %1 bp пара остатков п.о. Phylogram Филограмма Cladogram Кладограмма Search in Направление Internal error, bad argument: %1 Внутренняя ошибка! Неверный аргумент: %1 U2::LoadDocumentTask Invalid document format %1 Неверный формат: "%1" Read document: '%1' Чтение документа: %1 Document not found %1 Документ не найден: %1 Object not found: %1 Объект не найден: "%1" Can't add object. Document format constraints check failed: %1 Can't add object. Document format constrains check failed: %1 Не удалось добавить объект по ограничениям формата: %1 U2::LoadRemoteDocumentTask Undefined database: '%1' Cannot find %1 in %2 database U2::LoadUnloadedDocumentTask Document was removed Документ был удалён Project Document: Документ проекта Document is locked Документ заблокирован Load '%1' Загрузка: %1 Starting load document from %1, document format %2 Начата загрузка из "%1", формат документа: %2 Error: %1 Ошибка: %1 Document not found Документ не найден Annotation object not found Не найдена таблица аннотаций U2::LocalFileAdapterFactory Local file Локальный адаптер U2::MSAUtils Sequences have different alphabets. Алфавиты не совпадают Alignment is empty! Выравнивание пусто! Sequences in alignment have different sizes! Последовательности в выравнивании имеют разный размер! Sequence is too large for alignment: %1 Слишком большая последовательность для выравнивания: %1 U2::RelocateDocumentTask Relocate document %1 -> %2 Перемещение документа %1 -> %2 No active project found Нет проекта Project is locked Проект заблокирован Only unloaded objects can be relocated Можно перемещать только выгруженные документы U2::RemoveAnnotationsTask Annotation object is not valid Subgroup %1 is not found Waiting for object lock released Ожидание снятия блокировки U2::RemoveMultipleDocumentsTask Remove document Удаление документа U2::RemovePartFromSequenceTask Remove subsequence Удаление подпоследовательности Region to delete is larger than the whole sequence Region to delete larger then whole sequence Удаляемый регион выходит за границы последовательности Document is locked Документ заблокирован U2::ReplacePartOfSequenceTask Replace subsequence Region to replace larger then whole sequence Document is locked Документ заблокирован U2::ResourceTracker resource '%1' is used by '%2' Ресурс "%1" заблокирован задачей "%2" resource '%1' is released by '%2' Ресурс "%1" разблокирован задачей "%2" U2::SQLiteL10n Error querying database: %1 Found more results than expected! Unexpected query result code: %1 Error binding text value! Query: '%1', idx: %2, value: '%3' Error binding int32 value! Query: '%1', idx: %2, value: %3 Error binding int64 value! Query: '%1', idx: %2, value: %3 Error binding boolean value! Query: '%1', idx: %2, value: %3 Error binding blob value! Query: '%1', idx: %2, size: %3 Unexpected row count! Query: '%1', rows: %2 Query produced no results: %1 U2::SaveCopyAndAddToProjectTask Save a copy %1 Сохранение копии %1 No active project found Нет проекта Project is locked Проект заблокирован Document is already added to the project %1 Документ уже добавлен в проект: %1 U2::SaveDocumentStreamingTask Save document Сохранение документа U2::SaveDocumentTask Save document Сохранение документа Saving document %1 Сохранение документа: %1 U2::SaveMiltipleDocuments Save multiple documents Сохранение нескольких документов Question? Подтверждение Save document: %1 Сохранить документ: %1 U2::ScriptTask Script syntax check failed! Line: %1, error: %2 Проверка синтаксиса скрипта не удалась! В строке: "%1" обнаружена ошибка: "%2" Exception during script execution! Line: %1, error: %2 Во время работы скрипта возникло исключение! В строке: "%1" обнаружена ошибка: "%2" U2::SequenceWalkerSubtask Sequence walker subtask Обход части последовательности U2::VFSAdapterFactory Memory buffer Буфер в памяти U2AssemblyUtils Invalid CIGAR op: '%1'! U2BitCompression Bit compression: illegal character in text '%1' U2DbiPool No URL provided! Invalid database type: %1 DbiPool: DBI not found! URL: %1 U2DbiUtils Feature is not supported: %1, dbi: %2 ugene-1.9.8/src/corelibs/U2Core/transl/czech.ts0000644000175000017500000015200411651544332017757 0ustar ilyailya Document Document is not loaded Dokument není nahrán IO adapter does not support write operation IO adaptér nepodporuje operaci zápisu No write support for document format žádná podpora pro zápis pro formát dokumentu Locked by user Zamknuto uživatelem DocumentFormat The document is created not by UGENE Document sequences were merged Writing is not supported for this format (%1). Feel free to send a feature request though. Zápis není u tohoto formátu podporován (%1). Neostýchejte se však poslat žádost o tuto vlastnost. GObject Unknown Neznámý Unloaded Nenahraný Text Sequence Sekvence Sequences Sekvence Annotations Poznámky Annotation Poznámka Chromatogram Chromatograms Chromatogramy Alignment Zarovnání Alignments Zarovnání Tree Strom Trees Stromy 3D model Trojrozměrný model 3D models Trojrozměrné modely Index Rejstřík Indexes Rejstříky QObject This is not ESearch result! Toto není výsledek ESearch! Use Genbank DNA accession number. For example: NC_001363 or D11266 Použít číslo pro přistoupení k DNA v Genbank. Například: NC_001363 nebo D11266 Use Genbank protein accession number. For example: AAA59172.1 Použít číslo pro přistoupení k bílkovině (proteinu) v Genbank. Například: AAA59172.1 Use PDB molecule four-letter identifier. For example: 3INS or 1CRN Použít čtyřpísmenný identifikátor pro molekulu PDB. Například: 3INS nebo 1CRN Use SWISS-PROT accession number. For example: Q9IGQ6 or A0N8V2 Use UniProtKB/Swiss-Prot accession number. For example: P16152 Use UniProtKB/TrEMBL accession number. For example: D0VTW9 Use %1 unique identifier. Použít %1 jedinečný identifikátor. U2::AddDocumentTask add_document_task Add Document Task Add document to the project: %1 Přidat dokument do projektu: %1 No project is opened Document is already added to the project %1 Dokument je již přidán do projektu %1 Document was removed Dokument byl odstraněn document_removed Document was removed U2::AddPartToSequenceTask Add part to sequence Insert subsequence Insertion position is out of sequence bounds Position to insert is out of sequence bounds Document is in locked state Document is locked One of the documents is in locked state One of the documents is locked Insert subsequence Insert subsequence Insertion position is out of bounds Poloha k vložení je mimo hranice sekvence Document is locked Dokument je uzamčen U2::AddSequencesToAlignmentTask Sequence %1 from %2 has different alphabet Sekvence %1 z %2 má jinou abecedu U2::AnnotationTableObject Sequence Sekvence Translation Překlad U2::AppResourcePool Threads Vlákna Memory Paměť Mb Project Projekt Phytree Fylogenetický strom U2::CMDLineCoreOptions show help information Ukázat nápovědu ugene will continue executing after finishing given tasks Ugene bude pokračovat v provádění po dokončení zadaných úloh load test suites and run them Nahrát zkušební sady a provést je set directory for test report Nastavit adresář pro zprávu o zkoušce set number of threads in test runner that can run at the same time Nastavit počet vláken v provozovateli zkoušky, která mohou běžet ve stejnou dobu load configuration from the specified file Získat nastavení ze souboru s nastavením U2::CopyDataTask copy_data_task_name Copy Data Task Copy Data Task Úkol kopírování dat Cannot get data from: '%1' IO adapter error Chyba adaptéru IO cannot_open_io_adapter Cannot open IO adapter io_adapter_error IO adapter error no data in the source No data in source U2::CreateAnnotationsTask Create annotations Vytvořit poznámky Annotation object '%1' not found in active project: %2 Předmět poznámky '%1' nenalezen v činném projektu: %2 Waiting for object lock released Čeká se na uvolnění zámku předmětu U2::CreateFileIndexTask Create index: %1 Vytvořit rejstřík: %1 No files to index Žádné soubory pro rejstřík Internal error: inconsistent input data Vnitřní chyba: odporující si vstupní data Illegal output file parameters Neplatné parametry výstupního souboru Can't open file for read: '%1' Nelze otevřít soubor pro čtení: '%1' Error creating gzipped output Chyba při vytváření zazipovaného výstupu (gzip) Can't create index using %1 IO adapter Rejstřík nelze pomocí %1 IO adaptéru vytvořit Can't detect file format: %1 Nelze zjistit souborový formát: %1 UGENE can't index files of a specified format: %1 UGENE nedokáže vytvořit rejstřík ze souborů zadaného formátu: %1 U2::DBXRefRegistry dbxref_file_not_found_%1 File with db_xref mappings not found: %1 illegal_entry_%1 Illegal db_xref file entry: %1 File with db_xref mappings not found: %1 Soubor s přiřazením db_xref nenalezen: %1 Illegal db_xref file entry: %1 Neplatný záznam souboru db_xref: %1 U2::DNAAlphabetRegistryImpl raw_alphabet_name All symbols amino_default_alphabet_name Standard amino alphabet nucl_dna_default_alphabet_name Standard DNA alphabet nucl_rna_default_alphabet_name Standard RNA alphabet nucl_dna_extended_alphabet_name Extended DNA alphabet nucl_rna_extended_alphabet_name Extended RNA alphabet nucl_dna_default_to_nucl_compl Complement for standard DNA nucl_rna_default_to_nucl_compl Complement for standard RNA nucl_dna_extended_to_nucl_compl Complement for extended DNA nucl_rna_extended_to_nucl_compl Complement for extended RNA dna2amino 1 Standard 1. The Standard Genetic Code dna2amino 2 Vertebrate Mitochondrial 2. The Vertebrate Mitochondrial Code dna2amino 3 Yeast Mitochondrial 3. The Yeast Mitochondrial Code dna2amino 4 Protozoan Mitochondrial 4. The Mold, Protozoan, and Coelenterate Mitochondria and the Mycoplasma Code dna2amino 5 Invertebrate Mitochondrial 5. The Invertebrate Mitochondrial Code dna2amino 6 Ciliate Nuclear 6. The Ciliate, Dasycladacean and Hexamita Nuclear Code dna2amino 9 Flatworm Mitochondrial 9. The Echinoderm and Flatworm Mitochondrial Code dna2amino 10 Euplotid Nuclear 10. The Euplotid Nuclear Code dna2amino 11 Plant Plastid 11. The Bacterial and Plant Plastid Code dna2amino 12 Alternative Yeast Nuclear 12. The Alternative Yeast Nuclear Code dna2amino 13 Ascidian Mitochondrial 13. The Ascidian Mitochondrial Code dna2amino 14 Alternative Flatworm Mitochondrial 14. The Alternative Flatworm Mitochondrial Code dna2amino 15 Blepharisma Nuclear 15. Blepharisma Nuclear Code dna2amino 16 Chlorophycean Mitochondrial 16. Chlorophycean Mitochondrial Code dna2amino 21 Trematode Mitochondrial 21. Trematode Mitochondrial Code dna2amino 22 Scenedesmus obliquus Mitochondrial 22. Scenedesmus obliquus Mitochondrial Code dna2amino 23 Thraustochytrium Mitochondrial 23. Thraustochytrium Mitochondrial Code All symbols Všechny symboly Standard DNA Běžná DNA abeceda Standard RNA Běžná RNA abeceda Extended DNA Rozšířená DNA abeceda Extended RNA Rozšířená RNA abeceda Standard amino Běžná amino abeceda Complement for standard DNA Doplněk k běžné DNA Complement for standard RNA Doplněk k běžné RNA Complement for extended DNA Doplněk k rozšířené DNA Complement for extended RNA Doplněk k rozšířené RNA 1. The Standard Genetic Code 1. běžný genetický kód 2. The Vertebrate Mitochondrial Code 2. Mitochondriální kód obratlovců 3. The Yeast Mitochondrial Code 3. Mitochondriální kód kvasinek 4. The Mold, Protozoan, and Coelenterate Mitochondria and the Mycoplasma Code 4. Mitochondriální a mykoplazmatický kód plísní, prvoků a láčkovců 5. The Invertebrate Mitochondrial Code 5. Mitochondriální kód bezobratlých 6. The Ciliate, Dasycladacean and Hexamita Nuclear Code 6. Jaderný kód nálevníků, xxx a bičíkovců 9. The Echinoderm and Flatworm Mitochondrial Code 9. Mitochondriální kód ostnokožců a ploštěnců 10. The Euplotid Nuclear Code 10. Jaderný kód Euplotid 11. The Bacterial and Plant Plastid Code 11. Bakteriální kód a kód rostlinných plastid 12. The Alternative Yeast Nuclear Code 12. Náhradní jaderný kód kvasinek 13. The Ascidian Mitochondrial Code 13. Mitochondriální kód sumek 14. The Alternative Flatworm Mitochondrial Code 14. Náhradní mitochondriální kód a ploštěnců 15. Blepharisma Nuclear Code 15. Jaderný kód "Blepharisma" 16. Chlorophycean Mitochondrial Code 16. Mitochondriální kód sumek "Chlorophycean" 21. Trematode Mitochondrial Code 21. Mitochondriální kód motolice 22. Scenedesmus obliquus Mitochondrial Code 22. Mitochondriální kód "Scenedesmus obliquus" 23. Thraustochytrium Mitochondrial Code 23. Mitochondriální kód "Thraustochytrium" U2::DocumentFormat document_is_created_not_by_ugene Document was created not by UGENE U2::ExportToNewFileFromIndexTask Invalid document number: %1, max: %2 Neplatné číslo dokumentu: %1, max: %2 No IO adapter found for URL: %1 Pro adresu (URL): %1 nebyl nalezen žádný adaptér I/O Can't open file for write: '%1' Nelze otevřít soubor pro zápis: '%1' Export filename is empty Název souboru pro vyvedení je prázdný Index is inconsistent Rejstřík je nesouvislý Document numbers list is empty Seznam s čísly dokumentů je prázdný Export from index Vyvést z rejstříku U2::ExtractAnnotatedRegionTask Sequence split Extract annotated regions Extract annotated regions Získat oblasti opatřené poznámkou U2::FailTask Failure Neúspěch U2::GObject Annotations Annotations U2::GUrlUtils Renamed %1 to %2 Přejmenováno %1 na %2 Failed to rename %1 to %2 Nepodařilo se přejmenovat %1 na %2 Directory is not specified Adresář není určen Directory can't be created: %1 Adresář nelze vytvořit: %1 Directory can't be read: %1 Adresář nelze přečíst: %1 U2::GetDocumentFromIndexTask Can't find IO adapter: %1 Nelze najít IO adaptér: %1 Can't open file for read: '%1' Soubor nelze otevřít pro čtení: '%1' Error positioning in indexed file Chyba při umísťování v rejstříkovaném souboru GZIP index is corrupted Rejstřík GZIP je poškozen Get document from index Dostat dokument z rejstříku Index is empty Rejstřík je prázdný Invalid document number: %1, max: %2 Neplatný dokument s číslem: %1, max: %2 Index is corrupted Rejstřík je poškozen Unknown document format: %1 Neznámý formát dokumentu: %1 U2::GzippedHttpFileAdapterFactory http_file_gzip HTTP GZIP adaptor HTTP GZIP adaptor Soubor HTTP GZIP U2::GzippedLocalFileAdapterFactory local_file_gzip GZIP file GZIP file Soubor GZIP U2::HttpFileAdapterFactory http_file HTTP file HTTP file Soubor HTTP U2::L10N Error! Chyba! Warning! Varování! Error opening URL for read: '%1' Chyba při otevírání adresy (URL) pro čtení: '%1' Error opening URL for write: '%1' Chyba při otevírání adresy (URL) pro zápis: '%1' Write error: '%1' Chyba při zápisu: '%1' Read error: %1 Chyba při čtení: %1 File is too large: '%1' Soubor je příliš velký: '%1' File not found %1 Soubor nenalezen %1 Invalid file format. Expected file format: %1, File: %2 Can't save image to file %1, format %2 Nelze uložit obrázek do souboru %1, formát %2 Document not found: %1 bp Search in Internal error, bad argument: %1 Vnitřní chyba, špatný argument: %1 U2::LoadDocumentTask invalid_format_%1 Invalid document format %1 Read document: '%1' Číst dokument: '%1' Invalid document format %1 Neplatný formát dokumentu %1 Document not found %1 Dokument nenalezen %1 Object not found: %1 Předmět nenalezen %1 Can't add object. Document format constrains check failed: %1 Předmět nelze přidat. Ověření omezení formátu dokumentu se nezdařilo: %1 U2::LoadRemoteDocumentTask Cannot find %1 in %2 database U2::LoadUnloadedDocumentTask document_removed Document was removed project_doc_resource Project Document: document_is_locked Document is locked Load '%1' Nahrát '%1' Starting load document from %1, document format %2 Začíná se s nahráváním dokumentu z %1, formát dokumentu %2 Document was removed Dokument byl odstraněn Error: %1 Chyba: %1 Document not found Dokument nenalezen Document is locked Dokument je uzamknut Project Document: Projektový dokument: Annotation object not found Předmět s poznámkou nenalezen U2::LocalFileAdapterFactory local_file Local file Local file Místní soubor U2::MSAUtils Sequences have different alphabets. Sekvence mají rozdílné abecedy. Alignment is empty! Zarovnání je prázdné! Sequences in alignment have different sizes! Sekvence v zarovnání mají rozdílné velikosti! U2::RelocateDocumentTask Relocate document %1 -> %2 Přestěhovat dokument %1 -> %2 No active project found Nenalezen žádný činný projekt Project is locked Projekt je uzamknut Only unloaded objects can be relocated Pouze vyložené předměty mohou být přestěhovány U2::RemoveMultipleDocumentsTask remove_document_task_name Remove document Remove document Odstranit dokument U2::RemovePartFromSequenceTask Remove subsequence Remove subsequence Region to delete is larger than the whole sequence Cílová oblast je větší než celá sekvence Region to delete larger then whole sequence Target region is larger than the whole sequence Document is locked Dokument je uzamčen Document is in locked state Document is locked One of the documents is in locked state One of the documents is locked U2::ReplacePartOfSequenceTask Replace subsequence Region to replace larger then whole sequence Document is locked U2::ResourceTracker resource_use %1 by %2 resource '%1' is used by '%2' resource_release %1 by %2 resource '%1' is released by '%2' resource '%1' is used by '%2' prostředek '%1' je používán '%2' resource '%1' is released by '%2' prostředek '%1' je vydán '%2' U2::SaveCopyAndAddToProjectTask Save a copy %1 Uložit kopii %1 No active project found Nenalezen žádný činný projekt Project is locked Projekt je uzamknut Document is already added to the project %1 Dokument je již přidán do projektu %1 U2::SaveDocumentStreamingTask save_document_task_name Save document Save document Uložit dokument U2::SaveDocumentTask Save document Uložit dokument save_document_task_name Save document Saving document %1 Ukládá se dokument %1 U2::SaveMiltipleDocuments Save multiple documents Uložit více dokumentů Question? Otázka? Save document: %1 Uložit dokument: %1 save_multiple_documents_task_name Save multiple documents save_doc_title Question? save_doc_text: %1 Save document: %1 U2::ScriptTask Script syntax check failed! Line: %1, error: %2 Nepodařilo se ověřit skladbu skriptu! Řádek: %1, chyba: %2 Exception during script execution! Line: %1, error: %2 Výjimka při spuštění skriptu! Řádek: %1, chyba: %2 U2::SequenceWalkerSubtask sequence_walker_subtask Sequence walker subtask Sequence walker subtask Podúkol chodce sekvence U2::VFSAdapterFactory Memory buffer Vyrovnávací paměť paměti ugene-1.9.8/src/corelibs/U2Core/transl/english.ts0000644000175000017500000013140411651544332020315 0ustar ilyailya Document Document is not loaded IO adapter does not support write operation No write support for document format Locked by user DocumentFormat The document is created not by UGENE Document sequences were merged Writing is not supported for this format (%1). Feel free to send a feature request though. GObject Unknown Unloaded Text Sequence Sequences Annotation Annotations Chromatogram Chromatograms Alignment Alignments Tree Trees 3D model 3D models Index Indexes Assembly Assemblies QObject This is not ESearch result! Use Genbank DNA accession number. For example: NC_001363 or D11266 Use Genbank protein accession number. For example: AAA59172.1 Use PDB molecule four-letter identifier. For example: 3INS or 1CRN Use SWISS-PROT accession number. For example: Q9IGQ6 or A0N8V2 Use UniProtKB/Swiss-Prot accession number. For example: P16152 Use UniProtKB/TrEMBL accession number. For example: D0VTW9 Use %1 unique identifier. U2::AddDocumentTask Add document to the project: %1 No project is opened Document is already added to the project %1 Document was removed U2::AddPartToSequenceTask Insert subsequence Insertion position is out of bounds Document is locked U2::AddSequencesToAlignmentTask Sequence %1 from %2 has different alphabet U2::AnnotationTableObject Sequence Translation U2::AppResourcePool Threads Memory Mb Project Phytree U2::AutoAnnotationsSupport Auto-annotations [%1 | %2] U2::CMDLineCoreOptions Shows help information. Loads UGENE configuration. Loads configuration from the specified .ini file. By default the UGENE.ini file is used. <path_to_file> Specifies the language to use. Specifies the language to use. The following values are available: CS, EN, RU. <language_code> U2::CopyDataTask Copy Data Task Cannot get data from: '%1' IO adapter error U2::CreateAnnotationsTask Create annotations Annotation object '%1' not found in active project: %2 Waiting for object lock released U2::CreateFileIndexTask Create index: %1 No files to index Internal error: inconsistent input data Illegal output file parameters Can't open file for read: '%1' Error creating gzipped output Can't create index using %1 IO adapter Can't detect file format: %1 UGENE can't index files of a specified format: %1 U2::DBXRefRegistry File with db_xref mappings not found: %1 Illegal db_xref file entry: %1 U2::DNAAlphabetRegistryImpl All symbols Standard DNA Standard RNA Extended DNA Extended RNA Standard amino Complement for standard DNA Complement for standard RNA Complement for extended DNA Complement for extended RNA 1. The Standard Genetic Code 2. The Vertebrate Mitochondrial Code 3. The Yeast Mitochondrial Code 4. The Mold, Protozoan, and Coelenterate Mitochondria and the Mycoplasma Code 5. The Invertebrate Mitochondrial Code 6. The Ciliate, Dasycladacean and Hexamita Nuclear Code 9. The Echinoderm and Flatworm Mitochondrial Code 10. The Euplotid Nuclear Code 11. The Bacterial and Plant Plastid Code 12. The Alternative Yeast Nuclear Code 13. The Ascidian Mitochondrial Code 14. The Alternative Flatworm Mitochondrial Code 15. Blepharisma Nuclear Code 16. Chlorophycean Mitochondrial Code 21. Trematode Mitochondrial Code 22. Scenedesmus obliquus Mitochondrial Code 23. Thraustochytrium Mitochondrial Code U2::ExportToNewFileFromIndexTask Export from index Export filename is empty Index is inconsistent Document numbers list is empty Invalid document number: %1, max: %2 No IO adapter found for URL: %1 Can't open file for write: '%1' U2::ExtractAnnotatedRegionTask Extract annotated regions U2::FailTask Failure U2::GUrlUtils Renamed %1 to %2 Failed to rename %1 to %2 Directory is not specified Directory can't be created: %1 Directory can't be read: %1 U2::GetDocumentFromIndexTask Can't find IO adapter: %1 Can't open file for read: '%1' Error positioning in indexed file GZIP index is corrupted Get document from index Index is empty Invalid document number: %1, max: %2 Index is corrupted Unknown document format: %1 U2::GzippedHttpFileAdapterFactory HTTP GZIP adaptor U2::GzippedLocalFileAdapterFactory GZIP file U2::HttpFileAdapterFactory HTTP file U2::L10N Error! Warning! Internal error, bad argument: %1 Out of memory! Error opening URL for read: '%1' Error opening URL for write: '%1' Write error: '%1' Read error: %1 File is too large: '%1' File not found %1 %1 is not a file Invalid file format. Expected file format: %1, File: %2 Can't save image to file %1, format %2 Document not found: %1 bp Phylogram Cladogram U2::LoadDocumentTask Read document: '%1' Invalid document format %1 Document not found %1 Object not found: %1 Can't add object. Document format constraints check failed: %1 U2::LoadRemoteDocumentTask Undefined database: '%1' Cannot find %1 in %2 database U2::LoadUnloadedDocumentTask Load '%1' Document not found Starting load document from %1, document format %2 Document was removed Error: %1 Document is locked Project Document: Annotation object not found U2::LocalFileAdapterFactory Local file U2::MSAUtils Sequences have different alphabets. Alignment is empty! Sequences in alignment have different sizes! U2::RelocateDocumentTask Relocate document %1 -> %2 No active project found Project is locked Only unloaded objects can be relocated U2::RemoveAnnotationsTask Annotation object is not valid Subgroup %1 is not found Waiting for object lock released U2::RemoveMultipleDocumentsTask Remove document U2::RemovePartFromSequenceTask Remove subsequence Region to delete is larger than the whole sequence Document is locked U2::ReplacePartOfSequenceTask Replace subsequence Region to replace larger then whole sequence Document is locked U2::ResourceTracker resource '%1' is used by '%2' resource '%1' is released by '%2' U2::SQLiteL10n Error querying database: %1 Found more results than expected! Unexpected query result code: %1 Error binding text value! Query: '%1', idx: %2, value: '%3' Error binding int32 value! Query: '%1', idx: %2, value: %3 Error binding int64 value! Query: '%1', idx: %2, value: %3 Error binding boolean value! Query: '%1', idx: %2, value: %3 Error binding blob value! Query: '%1', idx: %2, size: %3 Unexpected row count! Query: '%1', rows: %2 Query produced no results: %1 U2::SaveCopyAndAddToProjectTask Save a copy %1 No active project found Project is locked Document is already added to the project %1 U2::SaveDocumentStreamingTask Save document U2::SaveDocumentTask Save document Saving document %1 U2::SaveMiltipleDocuments Save multiple documents Question? Save document: %1 U2::ScriptTask Script syntax check failed! Line: %1, error: %2 Exception during script execution! Line: %1, error: %2 U2::SequenceWalkerSubtask Sequence walker subtask U2::VFSAdapterFactory Memory buffer U2AssemblyUtils Invalid CIGAR op: '%1'! U2BitCompression Bit compression: illegal character in text '%1' U2DbiPool No URL provided! Invalid database type: %1 DbiPool: DBI not found! URL: %1 U2DbiUtils Feature is not supported: %1, dbi: %2 ugene-1.9.8/src/corelibs/U2Core/U2Core.pro0000644000175000017500000002531111651544331016630 0ustar ilyailyainclude (U2Core.pri) # Input HEADERS += src/cmdline/CMDLineCoreOptions.h \ src/cmdline/CMDLineHelpProvider.h \ src/cmdline/CMDLineRegistry.h \ src/cmdline/CMDLineUtils.h \ src/datatype/AnnotationData.h \ src/datatype/AnnotationSettings.h \ src/datatype/BioStruct3D.h \ src/datatype/DIProperties.h \ src/datatype/DNAAlphabet.h \ src/datatype/DNAAlphabetRegistryImpl.h \ src/datatype/DNAAlphabetUtils.h \ src/datatype/DNAChromatogram.h \ src/datatype/DNAInfo.h \ src/datatype/DNAQuality.h \ src/datatype/DNASequence.h \ src/datatype/DNATranslation.h \ src/datatype/DNATranslationImpl.h \ src/datatype/FeatureColors.h \ src/datatype/MAlignment.h \ src/datatype/MAlignmentInfo.h \ src/datatype/Matrix44.h \ src/datatype/PFMatrix.h \ src/datatype/PhyTree.h \ src/datatype/PWMatrix.h \ src/datatype/SMatrix.h \ src/datatype/UIndex.h \ src/datatype/Vector3D.h \ src/dbi/DbiDocumentFormat.h \ src/dbi/U2SqlHelpers.h \ src/globals/AppContext.h \ src/globals/AppGlobalObject.h \ src/globals/AppResources.h \ src/globals/AppSettings.h \ src/globals/AutoAnnotationsSupport.h \ src/globals/BaseDocumentFormats.h \ src/globals/Counter.h \ src/globals/DataBaseRegistry.h \ src/globals/DBXRefRegistry.h \ src/globals/DocumentFormatConfigurators.h \ src/globals/ExternalToolRegistry.h \ src/globals/GAutoDeleteList.h \ src/globals/global.h \ src/globals/Identifiable.h \ src/globals/IdRegistry.h \ src/globals/L10n.h \ src/globals/Log.h \ src/globals/LogCache.h \ src/globals/NetworkConfiguration.h \ src/globals/PluginModel.h \ src/globals/ProjectService.h \ src/globals/ResourceTracker.h \ src/globals/ServiceModel.h \ src/globals/ServiceTypes.h \ src/globals/Settings.h \ src/globals/Task.h \ src/globals/Timer.h \ src/globals/UserApplicationsSettings.h \ src/globals/Version.h \ src/gobjects/AnnotationTableObject.h \ src/gobjects/AssemblyObject.h \ src/gobjects/BioStruct3DObject.h \ src/gobjects/DNAChromatogramObject.h \ src/gobjects/DNASequenceObject.h \ src/gobjects/GObjectRelationRoles.h \ src/gobjects/GObjectTypes.h \ src/gobjects/GObjectUtils.h \ src/gobjects/MAlignmentObject.h \ src/gobjects/PhyTreeObject.h \ src/gobjects/TextObject.h \ src/gobjects/UIndexObject.h \ src/gobjects/UnloadedObject.h \ src/io/GUrl.h \ src/io/GUrlUtils.h \ src/io/HttpFileAdapter.h \ src/io/IOAdapter.h \ src/io/LocalFileAdapter.h \ src/io/RingBuffer.h \ src/io/VFSAdapter.h \ src/io/VirtualFileSystem.h \ src/io/ZlibAdapter.h \ src/models/DocumentImport.h \ src/models/DocumentModel.h \ src/models/DocumentUtils.h \ src/models/GHints.h \ src/models/GObject.h \ src/models/GObjectReference.h \ src/models/ProjectModel.h \ src/models/StateLockableDataModel.h \ src/selection/AnnotationSelection.h \ src/selection/DNASequenceSelection.h \ src/selection/DocumentSelection.h \ src/selection/GObjectSelection.h \ src/selection/LRegionsSelection.h \ src/selection/SelectionModel.h \ src/selection/SelectionTypes.h \ src/selection/SelectionUtils.h \ src/selection/TextSelection.h \ src/tasks/AddDocumentTask.h \ src/tasks/AddPartToSequenceTask.h \ src/tasks/AddSequencesToAlignmentTask.h \ src/tasks/CopyDataTask.h \ src/tasks/CreateAnnotationTask.h \ src/tasks/CreateFileIndexTask.h \ src/tasks/ExportToNewFileFromIndexTask.h \ src/tasks/ExtractAnnotatedRegionTask.h \ src/tasks/FailTask.h \ src/tasks/GetDocumentFromIndexTask.h \ src/tasks/LoadDocumentTask.h \ src/tasks/LoadRemoteDocumentTask.h \ src/tasks/MultiTask.h \ src/tasks/RemoveAnnotationsTask.h \ src/tasks/RemoveDocumentTask.h \ src/tasks/RemovePartFromSequenceTask.h \ src/tasks/ReplacePartOfSequenceTask.h \ src/tasks/ReverseSequenceTask.h \ src/tasks/SaveDocumentStreamingTask.h \ src/tasks/SaveDocumentTask.h \ src/tasks/ScriptTask.h \ src/tasks/SequenceWalkerTask.h \ src/tasks/TaskSignalMapper.h \ src/tasks/TaskStarter.h \ src/tasks/TLSTask.h \ src/util_algorithm/MSAUtils.h \ src/util_algorithm/QVariantUtils.h \ src/util_algorithm/SequenceUtils.h \ src/util_text/FormatUtils.h \ src/util_text/TextUtils.h SOURCES += src/cmdline/CMDLineCoreOptions.cpp \ src/cmdline/CMDLineRegistry.cpp \ src/cmdline/CMDLineUtils.cpp \ src/datatype/AnnotationData.cpp \ src/datatype/AnnotationSettings.cpp \ src/datatype/BaseAlphabets.cpp \ src/datatype/BaseTranslations.cpp \ src/datatype/BioStruct3D.cpp \ src/datatype/DNAAlphabet.cpp \ src/datatype/DNAAlphabetRegistryImpl.cpp \ src/datatype/DNAInfo.cpp \ src/datatype/DNAQuality.cpp \ src/datatype/DNASequence.cpp \ src/datatype/DNATranslation.cpp \ src/datatype/DNATranslationImpl.cpp \ src/datatype/FeatureColors.cpp \ src/datatype/MAlignment.cpp \ src/datatype/MAlignmentInfo.cpp \ src/datatype/Matrix44.cpp \ src/datatype/PFMatrix.cpp \ src/datatype/PhyTree.cpp \ src/datatype/PWMatrix.cpp \ src/datatype/SMatrix.cpp \ src/datatype/U2Region.cpp \ src/datatype/UIndex.cpp \ src/datatype/Vector3D.cpp \ src/dbi/DbiDocumentFormat.cpp \ src/dbi/U2DbiRegistry.cpp \ src/dbi/U2DbiUtils.cpp \ src/dbi/U2SqlHelpers.cpp \ src/globals/AppContext.cpp \ src/globals/AppGlobalObject.cpp \ src/globals/AppResources.cpp \ src/globals/AutoAnnotationsSupport.cpp \ src/globals/BaseDocumentFormats.cpp \ src/globals/Counter.cpp \ src/globals/DataBaseRegistry.cpp \ src/globals/DBXRefRegistry.cpp \ src/globals/DocumentFormatConfigurators.cpp \ src/globals/ExternalToolRegistry.cpp \ src/globals/GAutoDeleteList.cpp \ src/globals/Log.cpp \ src/globals/LogCache.cpp \ src/globals/NetworkConfiguration.cpp \ src/globals/PluginModel.cpp \ src/globals/ProjectService.cpp \ src/globals/ResourceTracker.cpp \ src/globals/ServiceModel.cpp \ src/globals/Task.cpp \ src/globals/Timer.cpp \ src/globals/UserApplicationsSettings.cpp \ src/globals/Version.cpp \ src/gobjects/AnnotationTableObject.cpp \ src/gobjects/AssemblyObject.cpp \ src/gobjects/BioStruct3DObject.cpp \ src/gobjects/DNAChromatogramObject.cpp \ src/gobjects/DNASequenceObject.cpp \ src/gobjects/GObjectRelationRoles.cpp \ src/gobjects/GObjectTypes.cpp \ src/gobjects/GObjectUtils.cpp \ src/gobjects/MAlignmentObject.cpp \ src/gobjects/PhyTreeObject.cpp \ src/gobjects/TextObject.cpp \ src/gobjects/UIndexObject.cpp \ src/gobjects/UnloadedObject.cpp \ src/io/GUrl.cpp \ src/io/GUrlUtils.cpp \ src/io/HttpFileAdapter.cpp \ src/io/IOAdapter.cpp \ src/io/LocalFileAdapter.cpp \ src/io/VFSAdapter.cpp \ src/io/VirtualFileSystem.cpp \ src/io/ZlibAdapter.cpp \ src/models/DocumentImport.cpp \ src/models/DocumentModel.cpp \ src/models/DocumentUtils.cpp \ src/models/GHints.cpp \ src/models/GObject.cpp \ src/models/ProjectModel.cpp \ src/models/StateLockableDataModel.cpp \ src/selection/AnnotationSelection.cpp \ src/selection/DocumentSelection.cpp \ src/selection/GObjectSelection.cpp \ src/selection/LRegionsSelection.cpp \ src/selection/SelectionModel.cpp \ src/selection/SelectionTypes.cpp \ src/selection/SelectionUtils.cpp \ src/tasks/AddDocumentTask.cpp \ src/tasks/AddPartToSequenceTask.cpp \ src/tasks/AddSequencesToAlignmentTask.cpp \ src/tasks/CopyDataTask.cpp \ src/tasks/CreateAnnotationTask.cpp \ src/tasks/CreateFileIndexTask.cpp \ src/tasks/ExportToNewFileFromIndexTask.cpp \ src/tasks/ExtractAnnotatedRegionTask.cpp \ src/tasks/GetDocumentFromIndexTask.cpp \ src/tasks/LoadDocumentTask.cpp \ src/tasks/LoadRemoteDocumentTask.cpp \ src/tasks/MultiTask.cpp \ src/tasks/RemoveAnnotationsTask.cpp \ src/tasks/RemoveDocumentTask.cpp \ src/tasks/RemovePartFromSequenceTask.cpp \ src/tasks/ReplacePartOfSequenceTask.cpp \ src/tasks/ReverseSequenceTask.cpp \ src/tasks/SaveDocumentStreamingTask.cpp \ src/tasks/SaveDocumentTask.cpp \ src/tasks/ScriptTask.cpp \ src/tasks/SequenceWalkerTask.cpp \ src/tasks/TaskSignalMapper.cpp \ src/tasks/TaskStarter.cpp \ src/tasks/TLSTask.cpp \ src/util_algorithm/MSAUtils.cpp \ src/util_algorithm/QVariantUtils.cpp \ src/util_algorithm/SequenceUtils.cpp \ src/util_algorithm/U2AnnotationUtils.cpp \ src/util_algorithm/U2AssemblyUtils.cpp \ src/util_algorithm/U2AttributeUtils.cpp \ src/util_algorithm/U2Bits.cpp \ src/util_text/FormatUtils.cpp \ src/util_text/TextUtils.cpp TRANSLATIONS += transl/czech.ts transl/english.ts transl/russian.ts ugene-1.9.8/src/corelibs/U2Formats/0000755000175000017500000000000011651544332015531 5ustar ilyailyaugene-1.9.8/src/corelibs/U2Formats/U2Formats.pro0000644000175000017500000000466611651544332020111 0ustar ilyailyainclude (U2Formats.pri) # Input HEADERS += src/ABIFormat.h \ src/ACEFormat.h \ src/ASNFormat.h \ src/ClustalWAlnFormat.h \ src/DocumentFormatUtils.h \ src/EMBLGenbankAbstractDocument.h \ src/EMBLPlainTextFormat.h \ src/FastaFormat.h \ src/FastqFormat.h \ src/GenbankFeatures.h \ src/GenbankLocationParser.h \ src/GenbankPlainTextFormat.h \ src/GFFFormat.h \ src/IndexFormat.h \ src/IOLibUtils.h \ src/MegaFormat.h \ src/MSFFormat.h \ src/NewickFormat.h \ src/NEXUSFormat.h \ src/NEXUSParser.h \ src/PDBFormat.h \ src/PDWFormat.h \ src/PlainTextFormat.h \ src/RawDNASequenceFormat.h \ src/SAMFormat.h \ src/SCFFormat.h \ src/StdResidueDictionary.h \ src/StockholmFormat.h \ src/StreamSequenceReader.h \ src/StreamSequenceWriter.h \ src/SwissProtPlainTextFormat.h \ src/tasks/ConvertAssemblyToSamTask.h SOURCES += src/ABIFormat.cpp \ src/ACEFormat.cpp \ src/ASNFormat.cpp \ src/ClustalWAlnFormat.cpp \ src/DocumentFormatUtils.cpp \ src/EMBLGenbankAbstractDocument.cpp \ src/EMBLPlainTextFormat.cpp \ src/FastaFormat.cpp \ src/FastqFormat.cpp \ src/GenbankFeatures.cpp \ src/GenbankLocationParser.cpp \ src/GenbankPlainTextFormat.cpp \ src/GFFFormat.cpp \ src/IndexFormat.cpp \ src/MegaFormat.cpp \ src/MSFFormat.cpp \ src/NewickFormat.cpp \ src/NEXUSFormat.cpp \ src/PDBFormat.cpp \ src/PDWFormat.cpp \ src/PlainTextFormat.cpp \ src/RawDNASequenceFormat.cpp \ src/SAMFormat.cpp \ src/SCFFormat.cpp \ src/StdResidueDictionary.cpp \ src/StockholmFormat.cpp \ src/StreamSequenceReader.cpp \ src/StreamSequenceWriter.cpp \ src/SwissProtPlainTextFormat.cpp \ src/tasks/ConvertAssemblyToSamTask.cpp RESOURCES += U2Formats.qrc TRANSLATIONS += transl/chinese \ transl/czech.ts \ transl/english.ts \ transl/russian.ts ugene-1.9.8/src/corelibs/U2Formats/U2Formats.qrc0000644000175000017500000000016211651544332020061 0ustar ilyailya datafiles/MMDBStdResidueDict ugene-1.9.8/src/corelibs/U2Formats/U2Formats.pri0000644000175000017500000000113311651544332020065 0ustar ilyailya# include (U2Formats.pri) MODULE_ID=U2Formats include( ../../ugene_lib_common.pri ) UGENE_RELATIVE_DESTDIR = '' DEFINES+= QT_FATAL_ASSERT BUILDING_U2FORMATS_DLL LIBS += -L../../_release -lU2Core -lU2Algorithm !debug_and_release|build_pass { CONFIG(debug, debug|release) { DESTDIR=../../_debug LIBS -= -L../../_release -lU2Core -lU2Algorithm LIBS += -L../../_debug -lU2Cored -lU2Algorithmd } CONFIG(release, debug|release) { DESTDIR=../../_release } } unix { target.path = $$UGENE_INSTALL_DIR/$$UGENE_RELATIVE_DESTDIR INSTALLS += target } ugene-1.9.8/src/corelibs/U2Formats/datafiles/0000755000175000017500000000000011651544332017465 5ustar ilyailyaugene-1.9.8/src/corelibs/U2Formats/datafiles/MMDBStdResidueDict0000644000175000017500000207334711651544332022747 0ustar ilyailyaBiostruc-residue-graph-set ::= { id { other-database { db "Standard residue dictionary", tag id 1 } }, residue-graphs { { id 1, descr { name "ALA" }, residue-type amino-acid, iupac-code { "A" }, atoms { { id 1, name " C ", iupac-code { " C " }, element c, ionizable-proton false }, { id 2, name " CA ", iupac-code { " CA " }, element c, ionizable-proton false }, { id 3, name " CB ", iupac-code { " CB " }, element c, ionizable-proton false }, { id 4, name " H ", iupac-code { " H " }, element h, ionizable-proton false }, { id 5, name " HA ", iupac-code { " HA " }, element h, ionizable-proton false }, { id 6, name " N ", iupac-code { " N " }, element n, ionizable-proton false }, { id 7, name " O ", iupac-code { " O " }, element o, ionizable-proton false }, { id 8, name "1HB ", iupac-code { "1HB " }, element h, ionizable-proton false }, { id 9, name "2HB ", iupac-code { "2HB " }, element h, ionizable-proton false }, { id 10, name "3HB ", iupac-code { "3HB " }, element h, ionizable-proton false } }, bonds { { atom-id-1 1, atom-id-2 7, bond-order partial-double }, { atom-id-1 2, atom-id-2 1, bond-order single }, { atom-id-1 2, atom-id-2 3, bond-order single }, { atom-id-1 2, atom-id-2 5, bond-order single }, { atom-id-1 3, atom-id-2 8, bond-order single }, { atom-id-1 3, atom-id-2 9, bond-order single }, { atom-id-1 3, atom-id-2 10, bond-order single }, { atom-id-1 6, atom-id-2 2, bond-order single }, { atom-id-1 6, atom-id-2 4, bond-order single } }, chiral-centers { { c 2, n1 6, n2 1, n3 3, sign positive } } }, { id 2, descr { name "ALA COOH" }, residue-type amino-acid, iupac-code { "A" }, atoms { { id 1, name " C ", iupac-code { " C " }, element c, ionizable-proton false }, { id 2, name " CA ", iupac-code { " CA " }, element c, ionizable-proton false }, { id 3, name " CB ", iupac-code { " CB " }, element c, ionizable-proton false }, { id 4, name " HA ", iupac-code { " HA " }, element h, ionizable-proton false }, { id 5, name " HXT", iupac-code { " HXT" }, element h, ionizable-proton true }, { id 6, name " N ", iupac-code { " N " }, element n, ionizable-proton false }, { id 7, name " O ", iupac-code { " O " }, element o, ionizable-proton false }, { id 8, name " OXT", iupac-code { " OXT" }, element o, ionizable-proton false }, { id 9, name "1HB ", iupac-code { "1HB " }, element h, ionizable-proton false }, { id 10, name "2HB ", iupac-code { "2HB " }, element h, ionizable-proton false }, { id 11, name "3HB ", iupac-code { "3HB " }, element h, ionizable-proton false }, { id 12, name " H ", iupac-code { " H " }, element h, ionizable-proton false } }, bonds { { atom-id-1 1, atom-id-2 7, bond-order partial-double }, { atom-id-1 1, atom-id-2 8, bond-order single }, { atom-id-1 2, atom-id-2 1, bond-order single }, { atom-id-1 2, atom-id-2 3, bond-order single }, { atom-id-1 2, atom-id-2 4, bond-order single }, { atom-id-1 3, atom-id-2 9, bond-order single }, { atom-id-1 3, atom-id-2 10, bond-order single }, { atom-id-1 3, atom-id-2 11, bond-order single }, { atom-id-1 6, atom-id-2 2, bond-order single }, { atom-id-1 8, atom-id-2 5, bond-order single }, { atom-id-1 6, atom-id-2 12, bond-order single } }, chiral-centers { { c 2, n1 6, n2 1, n3 3, sign positive } } }, { id 3, descr { name "ALA NH3+" }, residue-type amino-acid, iupac-code { "A" }, atoms { { id 1, name " C ", iupac-code { " C " }, element c, ionizable-proton false }, { id 2, name " CA ", iupac-code { " CA " }, element c, ionizable-proton false }, { id 3, name " CB ", iupac-code { " CB " }, element c, ionizable-proton false }, { id 4, name " HA ", iupac-code { " HA " }, element h, ionizable-proton false }, { id 5, name " N ", iupac-code { " N " }, element n, ionizable-proton false }, { id 6, name " O ", iupac-code { " O " }, element o, ionizable-proton false }, { id 7, name "1H ", iupac-code { "1H " }, element h, ionizable-proton true }, { id 8, name "1HB ", iupac-code { "1HB " }, element h, ionizable-proton false }, { id 9, name "2H ", iupac-code { "2H " }, element h, ionizable-proton true }, { id 10, name "2HB ", iupac-code { "2HB " }, element h, ionizable-proton false }, { id 11, name "3H ", iupac-code { "3H " }, element h, ionizable-proton true }, { id 12, name "3HB ", iupac-code { "3HB " }, element h, ionizable-proton false } }, bonds { { atom-id-1 1, atom-id-2 6, bond-order partial-double }, { atom-id-1 2, atom-id-2 1, bond-order single }, { atom-id-1 2, atom-id-2 3, bond-order single }, { atom-id-1 2, atom-id-2 4, bond-order single }, { atom-id-1 3, atom-id-2 8, bond-order single }, { atom-id-1 3, atom-id-2 10, bond-order single }, { atom-id-1 3, atom-id-2 12, bond-order single }, { atom-id-1 5, atom-id-2 2, bond-order single }, { atom-id-1 5, atom-id-2 7, bond-order single }, { atom-id-1 5, atom-id-2 9, bond-order single }, { atom-id-1 5, atom-id-2 11, bond-order single } }, chiral-centers { { c 2, n1 5, n2 1, n3 3, sign positive } } }, { id 4, descr { name "ARG" }, residue-type amino-acid, iupac-code { "R" }, atoms { { id 1, name " C ", iupac-code { " C " }, element c, ionizable-proton false }, { id 2, name " CA ", iupac-code { " CA " }, element c, ionizable-proton false }, { id 3, name " CB ", iupac-code { " CB " }, element c, ionizable-proton false }, { id 4, name " CD ", iupac-code { " CD " }, element c, ionizable-proton false }, { id 5, name " CG ", iupac-code { " CG " }, element c, ionizable-proton false }, { id 6, name " CZ ", iupac-code { " CZ " }, element c, ionizable-proton false }, { id 7, name " H ", iupac-code { " H " }, element h, ionizable-proton false }, { id 8, name " HA ", iupac-code { " HA " }, element h, ionizable-proton false }, { id 9, name " HE ", iupac-code { " HE " }, element h, ionizable-proton false }, { id 10, name " N ", iupac-code { " N " }, element n, ionizable-proton false }, { id 11, name " NE ", iupac-code { " NE " }, element n, ionizable-proton false }, { id 12, name " NH1", iupac-code { " NH1" }, element n, ionizable-proton false }, { id 13, name " NH2", iupac-code { " NH2" }, element n, ionizable-proton false }, { id 14, name " O ", iupac-code { " O " }, element o, ionizable-proton false }, { id 15, name "1HB ", iupac-code { "1HB " }, element h, ionizable-proton false }, { id 16, name "1HD ", iupac-code { "1HD " }, element h, ionizable-proton false }, { id 17, name "1HG ", iupac-code { "1HG " }, element h, ionizable-proton false }, { id 18, name "1HH1", iupac-code { "1HH1" }, element h, ionizable-proton true }, { id 19, name "1HH2", iupac-code { "1HH2" }, element h, ionizable-proton true }, { id 20, name "2HB ", iupac-code { "2HB " }, element h, ionizable-proton false }, { id 21, name "2HD ", iupac-code { "2HD " }, element h, ionizable-proton false }, { id 22, name "2HG ", iupac-code { "2HG " }, element h, ionizable-proton false }, { id 23, name "2HH1", iupac-code { "2HH1" }, element h, ionizable-proton true }, { id 24, name "2HH2", iupac-code { "2HH2" }, element h, ionizable-proton true } }, bonds { { atom-id-1 1, atom-id-2 14, bond-order partial-double }, { atom-id-1 2, atom-id-2 1, bond-order single }, { atom-id-1 2, atom-id-2 3, bond-order single }, { atom-id-1 2, atom-id-2 8, bond-order single }, { atom-id-1 3, atom-id-2 5, bond-order single }, { atom-id-1 3, atom-id-2 15, bond-order single }, { atom-id-1 3, atom-id-2 20, bond-order single }, { atom-id-1 4, atom-id-2 11, bond-order single }, { atom-id-1 4, atom-id-2 16, bond-order single }, { atom-id-1 4, atom-id-2 21, bond-order single }, { atom-id-1 5, atom-id-2 4, bond-order single }, { atom-id-1 5, atom-id-2 17, bond-order single }, { atom-id-1 5, atom-id-2 22, bond-order single }, { atom-id-1 6, atom-id-2 12, bond-order partial-double }, { atom-id-1 6, atom-id-2 13, bond-order partial-double }, { atom-id-1 10, atom-id-2 2, bond-order single }, { atom-id-1 10, atom-id-2 7, bond-order single }, { atom-id-1 11, atom-id-2 6, bond-order single }, { atom-id-1 11, atom-id-2 9, bond-order single }, { atom-id-1 12, atom-id-2 18, bond-order single }, { atom-id-1 12, atom-id-2 23, bond-order single }, { atom-id-1 13, atom-id-2 19, bond-order single }, { atom-id-1 13, atom-id-2 24, bond-order single } }, chiral-centers { { c 2, n1 10, n2 1, n3 3, sign positive } } }, { id 5, descr { name "ARG COOH" }, residue-type amino-acid, iupac-code { "R" }, atoms { { id 1, name " C ", iupac-code { " C " }, element c, ionizable-proton false }, { id 2, name " CA ", iupac-code { " CA " }, element c, ionizable-proton false }, { id 3, name " CB ", iupac-code { " CB " }, element c, ionizable-proton false }, { id 4, name " CD ", iupac-code { " CD " }, element c, ionizable-proton false }, { id 5, name " CG ", iupac-code { " CG " }, element c, ionizable-proton false }, { id 6, name " CZ ", iupac-code { " CZ " }, element c, ionizable-proton false }, { id 7, name " HA ", iupac-code { " HA " }, element h, ionizable-proton false }, { id 8, name " HE ", iupac-code { " HE " }, element h, ionizable-proton false }, { id 9, name " HXT", iupac-code { " HXT" }, element h, ionizable-proton true }, { id 10, name " N ", iupac-code { " N " }, element n, ionizable-proton false }, { id 11, name " NE ", iupac-code { " NE " }, element n, ionizable-proton false }, { id 12, name " NH1", iupac-code { " NH1" }, element n, ionizable-proton false }, { id 13, name " NH2", iupac-code { " NH2" }, element n, ionizable-proton false }, { id 14, name " O ", iupac-code { " O " }, element o, ionizable-proton false }, { id 15, name " OXT", iupac-code { " OXT" }, element o, ionizable-proton false }, { id 16, name "1HB ", iupac-code { "1HB " }, element h, ionizable-proton false }, { id 17, name "1HD ", iupac-code { "1HD " }, element h, ionizable-proton false }, { id 18, name "1HG ", iupac-code { "1HG " }, element h, ionizable-proton false }, { id 19, name "1HH1", iupac-code { "1HH1" }, element h, ionizable-proton true }, { id 20, name "1HH2", iupac-code { "1HH2" }, element h, ionizable-proton true }, { id 21, name "2HB ", iupac-code { "2HB " }, element h, ionizable-proton false }, { id 22, name "2HD ", iupac-code { "2HD " }, element h, ionizable-proton false }, { id 23, name "2HG ", iupac-code { "2HG " }, element h, ionizable-proton false }, { id 24, name "2HH1", iupac-code { "2HH1" }, element h, ionizable-proton true }, { id 25, name "2HH2", iupac-code { "2HH2" }, element h, ionizable-proton true }, { id 26, name " H ", iupac-code { " H " }, element h, ionizable-proton false } }, bonds { { atom-id-1 1, atom-id-2 14, bond-order partial-double }, { atom-id-1 1, atom-id-2 15, bond-order single }, { atom-id-1 2, atom-id-2 1, bond-order single }, { atom-id-1 2, atom-id-2 3, bond-order single }, { atom-id-1 2, atom-id-2 7, bond-order single }, { atom-id-1 3, atom-id-2 5, bond-order single }, { atom-id-1 3, atom-id-2 16, bond-order single }, { atom-id-1 3, atom-id-2 21, bond-order single }, { atom-id-1 4, atom-id-2 11, bond-order single }, { atom-id-1 4, atom-id-2 17, bond-order single }, { atom-id-1 4, atom-id-2 22, bond-order single }, { atom-id-1 5, atom-id-2 4, bond-order single }, { atom-id-1 5, atom-id-2 18, bond-order single }, { atom-id-1 5, atom-id-2 23, bond-order single }, { atom-id-1 6, atom-id-2 12, bond-order partial-double }, { atom-id-1 6, atom-id-2 13, bond-order partial-double }, { atom-id-1 10, atom-id-2 2, bond-order single }, { atom-id-1 11, atom-id-2 6, bond-order single }, { atom-id-1 11, atom-id-2 8, bond-order single }, { atom-id-1 12, atom-id-2 19, bond-order single }, { atom-id-1 12, atom-id-2 24, bond-order single }, { atom-id-1 13, atom-id-2 20, bond-order single }, { atom-id-1 13, atom-id-2 25, bond-order single }, { atom-id-1 15, atom-id-2 9, bond-order single }, { atom-id-1 10, atom-id-2 26, bond-order single } }, chiral-centers { { c 2, n1 10, n2 1, n3 3, sign positive } } }, { id 6, descr { name "ARG NH3+" }, residue-type amino-acid, iupac-code { "R" }, atoms { { id 1, name " C ", iupac-code { " C " }, element c, ionizable-proton false }, { id 2, name " CA ", iupac-code { " CA " }, element c, ionizable-proton false }, { id 3, name " CB ", iupac-code { " CB " }, element c, ionizable-proton false }, { id 4, name " CD ", iupac-code { " CD " }, element c, ionizable-proton false }, { id 5, name " CG ", iupac-code { " CG " }, element c, ionizable-proton false }, { id 6, name " CZ ", iupac-code { " CZ " }, element c, ionizable-proton false }, { id 7, name " HA ", iupac-code { " HA " }, element h, ionizable-proton false }, { id 8, name " HE ", iupac-code { " HE " }, element h, ionizable-proton false }, { id 9, name " N ", iupac-code { " N " }, element n, ionizable-proton false }, { id 10, name " NE ", iupac-code { " NE " }, element n, ionizable-proton false }, { id 11, name " NH1", iupac-code { " NH1" }, element n, ionizable-proton false }, { id 12, name " NH2", iupac-code { " NH2" }, element n, ionizable-proton false }, { id 13, name " O ", iupac-code { " O " }, element o, ionizable-proton false }, { id 14, name "1H ", iupac-code { "1H " }, element h, ionizable-proton true }, { id 15, name "1HB ", iupac-code { "1HB " }, element h, ionizable-proton false }, { id 16, name "1HD ", iupac-code { "1HD " }, element h, ionizable-proton false }, { id 17, name "1HG ", iupac-code { "1HG " }, element h, ionizable-proton false }, { id 18, name "1HH1", iupac-code { "1HH1" }, element h, ionizable-proton true }, { id 19, name "1HH2", iupac-code { "1HH2" }, element h, ionizable-proton true }, { id 20, name "2H ", iupac-code { "2H " }, element h, ionizable-proton true }, { id 21, name "2HB ", iupac-code { "2HB " }, element h, ionizable-proton false }, { id 22, name "2HD ", iupac-code { "2HD " }, element h, ionizable-proton false }, { id 23, name "2HG ", iupac-code { "2HG " }, element h, ionizable-proton false }, { id 24, name "2HH1", iupac-code { "2HH1" }, element h, ionizable-proton true }, { id 25, name "2HH2", iupac-code { "2HH2" }, element h, ionizable-proton true }, { id 26, name "3H ", iupac-code { "3H " }, element h, ionizable-proton true } }, bonds { { atom-id-1 1, atom-id-2 13, bond-order partial-double }, { atom-id-1 2, atom-id-2 1, bond-order single }, { atom-id-1 2, atom-id-2 3, bond-order single }, { atom-id-1 2, atom-id-2 7, bond-order single }, { atom-id-1 3, atom-id-2 5, bond-order single }, { atom-id-1 3, atom-id-2 15, bond-order single }, { atom-id-1 3, atom-id-2 21, bond-order single }, { atom-id-1 4, atom-id-2 10, bond-order single }, { atom-id-1 4, atom-id-2 16, bond-order single }, { atom-id-1 4, atom-id-2 22, bond-order single }, { atom-id-1 5, atom-id-2 4, bond-order single }, { atom-id-1 5, atom-id-2 17, bond-order single }, { atom-id-1 5, atom-id-2 23, bond-order single }, { atom-id-1 6, atom-id-2 11, bond-order partial-double }, { atom-id-1 6, atom-id-2 12, bond-order partial-double }, { atom-id-1 9, atom-id-2 2, bond-order single }, { atom-id-1 9, atom-id-2 14, bond-order single }, { atom-id-1 9, atom-id-2 20, bond-order single }, { atom-id-1 9, atom-id-2 26, bond-order single }, { atom-id-1 10, atom-id-2 6, bond-order single }, { atom-id-1 10, atom-id-2 8, bond-order single }, { atom-id-1 11, atom-id-2 18, bond-order single }, { atom-id-1 11, atom-id-2 24, bond-order single }, { atom-id-1 12, atom-id-2 19, bond-order single }, { atom-id-1 12, atom-id-2 25, bond-order single } }, chiral-centers { { c 2, n1 9, n2 1, n3 3, sign positive } } }, { id 7, descr { name "ASN" }, residue-type amino-acid, iupac-code { "N" }, atoms { { id 1, name " C ", iupac-code { " C " }, element c, ionizable-proton false }, { id 2, name " CA ", iupac-code { " CA " }, element c, ionizable-proton false }, { id 3, name " CB ", iupac-code { " CB " }, element c, ionizable-proton false }, { id 4, name " CG ", iupac-code { " CG " }, element c, ionizable-proton false }, { id 5, name " H ", iupac-code { " H " }, element h, ionizable-proton false }, { id 6, name " HA ", iupac-code { " HA " }, element h, ionizable-proton false }, { id 7, name " N ", iupac-code { " N " }, element n, ionizable-proton false }, { id 8, name " ND2", iupac-code { " ND2" }, element n, ionizable-proton false }, { id 9, name " O ", iupac-code { " O " }, element o, ionizable-proton false }, { id 10, name " OD1", iupac-code { " OD1" }, element o, ionizable-proton false }, { id 11, name "1HB ", iupac-code { "1HB " }, element h, ionizable-proton false }, { id 12, name "1HD2", iupac-code { "1HD2" }, element h, ionizable-proton false }, { id 13, name "2HB ", iupac-code { "2HB " }, element h, ionizable-proton false }, { id 14, name "2HD2", iupac-code { "2HD2" }, element h, ionizable-proton false } }, bonds { { atom-id-1 1, atom-id-2 9, bond-order partial-double }, { atom-id-1 2, atom-id-2 1, bond-order single }, { atom-id-1 2, atom-id-2 3, bond-order single }, { atom-id-1 2, atom-id-2 6, bond-order single }, { atom-id-1 3, atom-id-2 4, bond-order single }, { atom-id-1 3, atom-id-2 11, bond-order single }, { atom-id-1 3, atom-id-2 13, bond-order single }, { atom-id-1 4, atom-id-2 8, bond-order single }, { atom-id-1 4, atom-id-2 10, bond-order double }, { atom-id-1 7, atom-id-2 2, bond-order single }, { atom-id-1 7, atom-id-2 5, bond-order single }, { atom-id-1 8, atom-id-2 12, bond-order single }, { atom-id-1 8, atom-id-2 14, bond-order single } }, chiral-centers { { c 2, n1 7, n2 1, n3 3, sign positive } } }, { id 8, descr { name "ASN COOH" }, residue-type amino-acid, iupac-code { "N" }, atoms { { id 1, name " C ", iupac-code { " C " }, element c, ionizable-proton false }, { id 2, name " CA ", iupac-code { " CA " }, element c, ionizable-proton false }, { id 3, name " CB ", iupac-code { " CB " }, element c, ionizable-proton false }, { id 4, name " CG ", iupac-code { " CG " }, element c, ionizable-proton false }, { id 5, name " HA ", iupac-code { " HA " }, element h, ionizable-proton false }, { id 6, name " HXT", iupac-code { " HXT" }, element h, ionizable-proton true }, { id 7, name " N ", iupac-code { " N " }, element n, ionizable-proton false }, { id 8, name " ND2", iupac-code { " ND2" }, element n, ionizable-proton false }, { id 9, name " O ", iupac-code { " O " }, element o, ionizable-proton false }, { id 10, name " OD1", iupac-code { " OD1" }, element o, ionizable-proton false }, { id 11, name " OXT", iupac-code { " OXT" }, element o, ionizable-proton false }, { id 12, name "1HB ", iupac-code { "1HB " }, element h, ionizable-proton false }, { id 13, name "1HD2", iupac-code { "1HD2" }, element h, ionizable-proton false }, { id 14, name "2HB ", iupac-code { "2HB " }, element h, ionizable-proton false }, { id 15, name "2HD2", iupac-code { "2HD2" }, element h, ionizable-proton false }, { id 16, name " H ", iupac-code { " H " }, element h, ionizable-proton false } }, bonds { { atom-id-1 1, atom-id-2 9, bond-order partial-double }, { atom-id-1 1, atom-id-2 11, bond-order single }, { atom-id-1 2, atom-id-2 1, bond-order single }, { atom-id-1 2, atom-id-2 3, bond-order single }, { atom-id-1 2, atom-id-2 5, bond-order single }, { atom-id-1 3, atom-id-2 4, bond-order single }, { atom-id-1 3, atom-id-2 12, bond-order single }, { atom-id-1 3, atom-id-2 14, bond-order single }, { atom-id-1 4, atom-id-2 8, bond-order single }, { atom-id-1 4, atom-id-2 10, bond-order double }, { atom-id-1 7, atom-id-2 2, bond-order single }, { atom-id-1 8, atom-id-2 13, bond-order single }, { atom-id-1 8, atom-id-2 15, bond-order single }, { atom-id-1 11, atom-id-2 6, bond-order single }, { atom-id-1 7, atom-id-2 16, bond-order single } }, chiral-centers { { c 2, n1 7, n2 1, n3 3, sign positive } } }, { id 9, descr { name "ASN NH3+" }, residue-type amino-acid, iupac-code { "N" }, atoms { { id 1, name " C ", iupac-code { " C " }, element c, ionizable-proton false }, { id 2, name " CA ", iupac-code { " CA " }, element c, ionizable-proton false }, { id 3, name " CB ", iupac-code { " CB " }, element c, ionizable-proton false }, { id 4, name " CG ", iupac-code { " CG " }, element c, ionizable-proton false }, { id 5, name " HA ", iupac-code { " HA " }, element h, ionizable-proton false }, { id 6, name " N ", iupac-code { " N " }, element n, ionizable-proton false }, { id 7, name " ND2", iupac-code { " ND2" }, element n, ionizable-proton false }, { id 8, name " O ", iupac-code { " O " }, element o, ionizable-proton false }, { id 9, name " OD1", iupac-code { " OD1" }, element o, ionizable-proton false }, { id 10, name "1H ", iupac-code { "1H " }, element h, ionizable-proton true }, { id 11, name "1HB ", iupac-code { "1HB " }, element h, ionizable-proton false }, { id 12, name "1HD2", iupac-code { "1HD2" }, element h, ionizable-proton false }, { id 13, name "2H ", iupac-code { "2H " }, element h, ionizable-proton true }, { id 14, name "2HB ", iupac-code { "2HB " }, element h, ionizable-proton false }, { id 15, name "2HD2", iupac-code { "2HD2" }, element h, ionizable-proton false }, { id 16, name "3H ", iupac-code { "3H " }, element h, ionizable-proton true } }, bonds { { atom-id-1 1, atom-id-2 8, bond-order partial-double }, { atom-id-1 2, atom-id-2 1, bond-order single }, { atom-id-1 2, atom-id-2 3, bond-order single }, { atom-id-1 2, atom-id-2 5, bond-order single }, { atom-id-1 3, atom-id-2 4, bond-order single }, { atom-id-1 3, atom-id-2 11, bond-order single }, { atom-id-1 3, atom-id-2 14, bond-order single }, { atom-id-1 4, atom-id-2 7, bond-order single }, { atom-id-1 4, atom-id-2 9, bond-order double }, { atom-id-1 6, atom-id-2 2, bond-order single }, { atom-id-1 6, atom-id-2 10, bond-order single }, { atom-id-1 6, atom-id-2 13, bond-order single }, { atom-id-1 6, atom-id-2 16, bond-order single }, { atom-id-1 7, atom-id-2 12, bond-order single }, { atom-id-1 7, atom-id-2 15, bond-order single } }, chiral-centers { { c 2, n1 6, n2 1, n3 3, sign positive } } }, { id 10, descr { name "ASP" }, residue-type amino-acid, iupac-code { "D" }, atoms { { id 1, name " C ", iupac-code { " C " }, element c, ionizable-proton false }, { id 2, name " CA ", iupac-code { " CA " }, element c, ionizable-proton false }, { id 3, name " CB ", iupac-code { " CB " }, element c, ionizable-proton false }, { id 4, name " CG ", iupac-code { " CG " }, element c, ionizable-proton false }, { id 5, name " H ", iupac-code { " H " }, element h, ionizable-proton false }, { id 6, name " HA ", iupac-code { " HA " }, element h, ionizable-proton false }, { id 7, name " HD1", iupac-code { " HD1" }, element h, ionizable-proton false }, { id 8, name " HD2", iupac-code { " HD2" }, element h, ionizable-proton false }, { id 9, name " N ", iupac-code { " N " }, element n, ionizable-proton false }, { id 10, name " O ", iupac-code { " O " }, element o, ionizable-proton false }, { id 11, name " OD1", iupac-code { " OD1" }, element o, ionizable-proton false }, { id 12, name " OD2", iupac-code { " OD2" }, element o, ionizable-proton false }, { id 13, name "1HB ", iupac-code { "1HB " }, element h, ionizable-proton false }, { id 14, name "2HB ", iupac-code { "2HB " }, element h, ionizable-proton false } }, bonds { { atom-id-1 1, atom-id-2 10, bond-order partial-double }, { atom-id-1 2, atom-id-2 1, bond-order single }, { atom-id-1 2, atom-id-2 3, bond-order single }, { atom-id-1 2, atom-id-2 6, bond-order single }, { atom-id-1 3, atom-id-2 4, bond-order single }, { atom-id-1 3, atom-id-2 13, bond-order single }, { atom-id-1 3, atom-id-2 14, bond-order single }, { atom-id-1 4, atom-id-2 11, bond-order partial-double }, { atom-id-1 4, atom-id-2 12, bond-order partial-double }, { atom-id-1 9, atom-id-2 2, bond-order single }, { atom-id-1 9, atom-id-2 5, bond-order single }, { atom-id-1 11, atom-id-2 7, bond-order single }, { atom-id-1 12, atom-id-2 8, bond-order single } }, chiral-centers { { c 2, n1 9, n2 1, n3 3, sign positive } } }, { id 11, descr { name "ASP COOH" }, residue-type amino-acid, iupac-code { "D" }, atoms { { id 1, name " C ", iupac-code { " C " }, element c, ionizable-proton false }, { id 2, name " CA ", iupac-code { " CA " }, element c, ionizable-proton false }, { id 3, name " CB ", iupac-code { " CB " }, element c, ionizable-proton false }, { id 4, name " CG ", iupac-code { " CG " }, element c, ionizable-proton false }, { id 5, name " HA ", iupac-code { " HA " }, element h, ionizable-proton false }, { id 6, name " HD1", iupac-code { " HD1" }, element h, ionizable-proton false }, { id 7, name " HD2", iupac-code { " HD2" }, element h, ionizable-proton false }, { id 8, name " HXT", iupac-code { " HXT" }, element h, ionizable-proton true }, { id 9, name " N ", iupac-code { " N " }, element n, ionizable-proton false }, { id 10, name " O ", iupac-code { " O " }, element o, ionizable-proton false }, { id 11, name " OD1", iupac-code { " OD1" }, element o, ionizable-proton false }, { id 12, name " OD2", iupac-code { " OD2" }, element o, ionizable-proton false }, { id 13, name " OXT", iupac-code { " OXT" }, element o, ionizable-proton false }, { id 14, name "1HB ", iupac-code { "1HB " }, element h, ionizable-proton false }, { id 15, name "2HB ", iupac-code { "2HB " }, element h, ionizable-proton false }, { id 16, name " H ", iupac-code { " H " }, element h, ionizable-proton false } }, bonds { { atom-id-1 1, atom-id-2 10, bond-order partial-double }, { atom-id-1 1, atom-id-2 13, bond-order single }, { atom-id-1 2, atom-id-2 1, bond-order single }, { atom-id-1 2, atom-id-2 3, bond-order single }, { atom-id-1 2, atom-id-2 5, bond-order single }, { atom-id-1 3, atom-id-2 4, bond-order single }, { atom-id-1 3, atom-id-2 14, bond-order single }, { atom-id-1 3, atom-id-2 15, bond-order single }, { atom-id-1 4, atom-id-2 11, bond-order partial-double }, { atom-id-1 4, atom-id-2 12, bond-order partial-double }, { atom-id-1 9, atom-id-2 2, bond-order single }, { atom-id-1 11, atom-id-2 6, bond-order single }, { atom-id-1 12, atom-id-2 7, bond-order single }, { atom-id-1 13, atom-id-2 8, bond-order single }, { atom-id-1 9, atom-id-2 16, bond-order single } }, chiral-centers { { c 2, n1 9, n2 1, n3 3, sign positive } } }, { id 12, descr { name "ASP NH3+" }, residue-type amino-acid, iupac-code { "D" }, atoms { { id 1, name " C ", iupac-code { " C " }, element c, ionizable-proton false }, { id 2, name " CA ", iupac-code { " CA " }, element c, ionizable-proton false }, { id 3, name " CB ", iupac-code { " CB " }, element c, ionizable-proton false }, { id 4, name " CG ", iupac-code { " CG " }, element c, ionizable-proton false }, { id 5, name " HA ", iupac-code { " HA " }, element h, ionizable-proton false }, { id 6, name " HD1", iupac-code { " HD1" }, element h, ionizable-proton false }, { id 7, name " HD2", iupac-code { " HD2" }, element h, ionizable-proton false }, { id 8, name " N ", iupac-code { " N " }, element n, ionizable-proton false }, { id 9, name " O ", iupac-code { " O " }, element o, ionizable-proton false }, { id 10, name " OD1", iupac-code { " OD1" }, element o, ionizable-proton false }, { id 11, name " OD2", iupac-code { " OD2" }, element o, ionizable-proton false }, { id 12, name "1H ", iupac-code { "1H " }, element h, ionizable-proton true }, { id 13, name "1HB ", iupac-code { "1HB " }, element h, ionizable-proton false }, { id 14, name "2H ", iupac-code { "2H " }, element h, ionizable-proton true }, { id 15, name "2HB ", iupac-code { "2HB " }, element h, ionizable-proton false }, { id 16, name "3H ", iupac-code { "3H " }, element h, ionizable-proton true } }, bonds { { atom-id-1 1, atom-id-2 9, bond-order partial-double }, { atom-id-1 2, atom-id-2 1, bond-order single }, { atom-id-1 2, atom-id-2 3, bond-order single }, { atom-id-1 2, atom-id-2 5, bond-order single }, { atom-id-1 3, atom-id-2 4, bond-order single }, { atom-id-1 3, atom-id-2 13, bond-order single }, { atom-id-1 3, atom-id-2 15, bond-order single }, { atom-id-1 4, atom-id-2 10, bond-order partial-double }, { atom-id-1 4, atom-id-2 11, bond-order partial-double }, { atom-id-1 8, atom-id-2 2, bond-order single }, { atom-id-1 8, atom-id-2 12, bond-order single }, { atom-id-1 8, atom-id-2 14, bond-order single }, { atom-id-1 8, atom-id-2 16, bond-order single }, { atom-id-1 10, atom-id-2 6, bond-order single }, { atom-id-1 11, atom-id-2 7, bond-order single } }, chiral-centers { { c 2, n1 8, n2 1, n3 3, sign positive } } }, { id 13, descr { name "CYS" }, residue-type amino-acid, iupac-code { "C" }, atoms { { id 1, name " C ", iupac-code { " C " }, element c, ionizable-proton false }, { id 2, name " CA ", iupac-code { " CA " }, element c, ionizable-proton false }, { id 3, name " CB ", iupac-code { " CB " }, element c, ionizable-proton false }, { id 4, name " H ", iupac-code { " H " }, element h, ionizable-proton false }, { id 5, name " HA ", iupac-code { " HA " }, element h, ionizable-proton false }, { id 6, name " HG ", iupac-code { " HG " }, element h, ionizable-proton true }, { id 7, name " N ", iupac-code { " N " }, element n, ionizable-proton false }, { id 8, name " O ", iupac-code { " O " }, element o, ionizable-proton false }, { id 9, name " SG ", iupac-code { " SG " }, element s, ionizable-proton false }, { id 10, name "1HB ", iupac-code { "1HB " }, element h, ionizable-proton false }, { id 11, name "2HB ", iupac-code { "2HB " }, element h, ionizable-proton false } }, bonds { { atom-id-1 1, atom-id-2 8, bond-order partial-double }, { atom-id-1 2, atom-id-2 1, bond-order single }, { atom-id-1 2, atom-id-2 3, bond-order single }, { atom-id-1 2, atom-id-2 5, bond-order single }, { atom-id-1 3, atom-id-2 9, bond-order single }, { atom-id-1 3, atom-id-2 10, bond-order single }, { atom-id-1 3, atom-id-2 11, bond-order single }, { atom-id-1 7, atom-id-2 2, bond-order single }, { atom-id-1 7, atom-id-2 4, bond-order single }, { atom-id-1 9, atom-id-2 6, bond-order single } }, chiral-centers { { c 2, n1 7, n2 1, n3 3, sign positive } } }, { id 14, descr { name "CYS COOH" }, residue-type amino-acid, iupac-code { "C" }, atoms { { id 1, name " C ", iupac-code { " C " }, element c, ionizable-proton false }, { id 2, name " CA ", iupac-code { " CA " }, element c, ionizable-proton false }, { id 3, name " CB ", iupac-code { " CB " }, element c, ionizable-proton false }, { id 4, name " HA ", iupac-code { " HA " }, element h, ionizable-proton false }, { id 5, name " HG ", iupac-code { " HG " }, element h, ionizable-proton true }, { id 6, name " HXT", iupac-code { " HXT" }, element h, ionizable-proton true }, { id 7, name " N ", iupac-code { " N " }, element n, ionizable-proton false }, { id 8, name " O ", iupac-code { " O " }, element o, ionizable-proton false }, { id 9, name " OXT", iupac-code { " OXT" }, element o, ionizable-proton false }, { id 10, name " SG ", iupac-code { " SG " }, element s, ionizable-proton false }, { id 11, name "1HB ", iupac-code { "1HB " }, element h, ionizable-proton false }, { id 12, name "2HB ", iupac-code { "2HB " }, element h, ionizable-proton false }, { id 13, name " H ", iupac-code { " H " }, element h, ionizable-proton false } }, bonds { { atom-id-1 1, atom-id-2 8, bond-order partial-double }, { atom-id-1 1, atom-id-2 9, bond-order single }, { atom-id-1 2, atom-id-2 1, bond-order single }, { atom-id-1 2, atom-id-2 3, bond-order single }, { atom-id-1 2, atom-id-2 4, bond-order single }, { atom-id-1 3, atom-id-2 10, bond-order single }, { atom-id-1 3, atom-id-2 11, bond-order single }, { atom-id-1 3, atom-id-2 12, bond-order single }, { atom-id-1 7, atom-id-2 2, bond-order single }, { atom-id-1 10, atom-id-2 5, bond-order single }, { atom-id-1 9, atom-id-2 6, bond-order single }, { atom-id-1 7, atom-id-2 13, bond-order single } }, chiral-centers { { c 2, n1 7, n2 1, n3 3, sign positive } } }, { id 15, descr { name "CYS NH3+" }, residue-type amino-acid, iupac-code { "C" }, atoms { { id 1, name " C ", iupac-code { " C " }, element c, ionizable-proton false }, { id 2, name " CA ", iupac-code { " CA " }, element c, ionizable-proton false }, { id 3, name " CB ", iupac-code { " CB " }, element c, ionizable-proton false }, { id 4, name " HA ", iupac-code { " HA " }, element h, ionizable-proton false }, { id 5, name " HG ", iupac-code { " HG " }, element h, ionizable-proton true }, { id 6, name " N ", iupac-code { " N " }, element n, ionizable-proton false }, { id 7, name " O ", iupac-code { " O " }, element o, ionizable-proton false }, { id 8, name " SG ", iupac-code { " SG " }, element s, ionizable-proton false }, { id 9, name "1H ", iupac-code { "1H " }, element h, ionizable-proton true }, { id 10, name "1HB ", iupac-code { "1HB " }, element h, ionizable-proton false }, { id 11, name "2H ", iupac-code { "2H " }, element h, ionizable-proton true }, { id 12, name "2HB ", iupac-code { "2HB " }, element h, ionizable-proton false }, { id 13, name "3H ", iupac-code { "3H " }, element h, ionizable-proton true } }, bonds { { atom-id-1 1, atom-id-2 7, bond-order partial-double }, { atom-id-1 2, atom-id-2 1, bond-order single }, { atom-id-1 2, atom-id-2 3, bond-order single }, { atom-id-1 2, atom-id-2 4, bond-order single }, { atom-id-1 3, atom-id-2 8, bond-order single }, { atom-id-1 3, atom-id-2 10, bond-order single }, { atom-id-1 3, atom-id-2 12, bond-order single }, { atom-id-1 6, atom-id-2 2, bond-order single }, { atom-id-1 6, atom-id-2 9, bond-order single }, { atom-id-1 6, atom-id-2 11, bond-order single }, { atom-id-1 6, atom-id-2 13, bond-order single }, { atom-id-1 8, atom-id-2 5, bond-order single } }, chiral-centers { { c 2, n1 6, n2 1, n3 3, sign positive } } }, { id 16, descr { name "GLN" }, residue-type amino-acid, iupac-code { "Q" }, atoms { { id 1, name " C ", iupac-code { " C " }, element c, ionizable-proton false }, { id 2, name " CA ", iupac-code { " CA " }, element c, ionizable-proton false }, { id 3, name " CB ", iupac-code { " CB " }, element c, ionizable-proton false }, { id 4, name " CD ", iupac-code { " CD " }, element c, ionizable-proton false }, { id 5, name " CG ", iupac-code { " CG " }, element c, ionizable-proton false }, { id 6, name " H ", iupac-code { " H " }, element h, ionizable-proton false }, { id 7, name " HA ", iupac-code { " HA " }, element h, ionizable-proton false }, { id 8, name " N ", iupac-code { " N " }, element n, ionizable-proton false }, { id 9, name " NE2", iupac-code { " NE2" }, element n, ionizable-proton false }, { id 10, name " O ", iupac-code { " O " }, element o, ionizable-proton false }, { id 11, name " OE1", iupac-code { " OE1" }, element o, ionizable-proton false }, { id 12, name "1HB ", iupac-code { "1HB " }, element h, ionizable-proton false }, { id 13, name "1HE2", iupac-code { "1HE2" }, element h, ionizable-proton false }, { id 14, name "1HG ", iupac-code { "1HG " }, element h, ionizable-proton false }, { id 15, name "2HB ", iupac-code { "2HB " }, element h, ionizable-proton false }, { id 16, name "2HE2", iupac-code { "2HE2" }, element h, ionizable-proton true }, { id 17, name "2HG ", iupac-code { "2HG " }, element h, ionizable-proton false } }, bonds { { atom-id-1 1, atom-id-2 10, bond-order partial-double }, { atom-id-1 2, atom-id-2 1, bond-order single }, { atom-id-1 2, atom-id-2 3, bond-order single }, { atom-id-1 2, atom-id-2 7, bond-order single }, { atom-id-1 3, atom-id-2 5, bond-order single }, { atom-id-1 3, atom-id-2 12, bond-order single }, { atom-id-1 3, atom-id-2 15, bond-order single }, { atom-id-1 4, atom-id-2 9, bond-order single }, { atom-id-1 4, atom-id-2 11, bond-order double }, { atom-id-1 5, atom-id-2 4, bond-order single }, { atom-id-1 5, atom-id-2 14, bond-order single }, { atom-id-1 5, atom-id-2 17, bond-order single }, { atom-id-1 8, atom-id-2 2, bond-order single }, { atom-id-1 8, atom-id-2 6, bond-order single }, { atom-id-1 9, atom-id-2 13, bond-order single }, { atom-id-1 9, atom-id-2 16, bond-order single } }, chiral-centers { { c 2, n1 8, n2 1, n3 3, sign positive } } }, { id 17, descr { name "GLN COOH" }, residue-type amino-acid, iupac-code { "Q" }, atoms { { id 1, name " C ", iupac-code { " C " }, element c, ionizable-proton false }, { id 2, name " CA ", iupac-code { " CA " }, element c, ionizable-proton false }, { id 3, name " CB ", iupac-code { " CB " }, element c, ionizable-proton false }, { id 4, name " CD ", iupac-code { " CD " }, element c, ionizable-proton false }, { id 5, name " CG ", iupac-code { " CG " }, element c, ionizable-proton false }, { id 6, name " HA ", iupac-code { " HA " }, element h, ionizable-proton false }, { id 7, name " HXT", iupac-code { " HXT" }, element h, ionizable-proton true }, { id 8, name " N ", iupac-code { " N " }, element n, ionizable-proton false }, { id 9, name " NE2", iupac-code { " NE2" }, element n, ionizable-proton false }, { id 10, name " O ", iupac-code { " O " }, element o, ionizable-proton false }, { id 11, name " OE1", iupac-code { " OE1" }, element o, ionizable-proton false }, { id 12, name " OXT", iupac-code { " OXT" }, element o, ionizable-proton false }, { id 13, name "1HB ", iupac-code { "1HB " }, element h, ionizable-proton false }, { id 14, name "1HE2", iupac-code { "1HE2" }, element h, ionizable-proton false }, { id 15, name "1HG ", iupac-code { "1HG " }, element h, ionizable-proton false }, { id 16, name "2HB ", iupac-code { "2HB " }, element h, ionizable-proton false }, { id 17, name "2HE2", iupac-code { "2HE2" }, element h, ionizable-proton true }, { id 18, name "2HG ", iupac-code { "2HG " }, element h, ionizable-proton false }, { id 19, name " H ", iupac-code { " H " }, element h, ionizable-proton false } }, bonds { { atom-id-1 1, atom-id-2 10, bond-order partial-double }, { atom-id-1 1, atom-id-2 12, bond-order single }, { atom-id-1 2, atom-id-2 1, bond-order single }, { atom-id-1 2, atom-id-2 3, bond-order single }, { atom-id-1 2, atom-id-2 6, bond-order single }, { atom-id-1 3, atom-id-2 5, bond-order single }, { atom-id-1 3, atom-id-2 13, bond-order single }, { atom-id-1 3, atom-id-2 16, bond-order single }, { atom-id-1 4, atom-id-2 9, bond-order single }, { atom-id-1 4, atom-id-2 11, bond-order double }, { atom-id-1 5, atom-id-2 4, bond-order single }, { atom-id-1 5, atom-id-2 15, bond-order single }, { atom-id-1 5, atom-id-2 18, bond-order single }, { atom-id-1 8, atom-id-2 2, bond-order single }, { atom-id-1 9, atom-id-2 14, bond-order single }, { atom-id-1 9, atom-id-2 17, bond-order single }, { atom-id-1 12, atom-id-2 7, bond-order single }, { atom-id-1 8, atom-id-2 19, bond-order single } }, chiral-centers { { c 2, n1 8, n2 1, n3 3, sign positive } } }, { id 18, descr { name "GLN NH3+" }, residue-type amino-acid, iupac-code { "Q" }, atoms { { id 1, name " C ", iupac-code { " C " }, element c, ionizable-proton false }, { id 2, name " CA ", iupac-code { " CA " }, element c, ionizable-proton false }, { id 3, name " CB ", iupac-code { " CB " }, element c, ionizable-proton false }, { id 4, name " CD ", iupac-code { " CD " }, element c, ionizable-proton false }, { id 5, name " CG ", iupac-code { " CG " }, element c, ionizable-proton false }, { id 6, name " HA ", iupac-code { " HA " }, element h, ionizable-proton false }, { id 7, name " N ", iupac-code { " N " }, element n, ionizable-proton false }, { id 8, name " NE2", iupac-code { " NE2" }, element n, ionizable-proton false }, { id 9, name " O ", iupac-code { " O " }, element o, ionizable-proton false }, { id 10, name " OE1", iupac-code { " OE1" }, element o, ionizable-proton false }, { id 11, name "1H ", iupac-code { "1H " }, element h, ionizable-proton true }, { id 12, name "1HB ", iupac-code { "1HB " }, element h, ionizable-proton false }, { id 13, name "1HE2", iupac-code { "1HE2" }, element h, ionizable-proton false }, { id 14, name "1HG ", iupac-code { "1HG " }, element h, ionizable-proton false }, { id 15, name "2H ", iupac-code { "2H " }, element h, ionizable-proton true }, { id 16, name "2HB ", iupac-code { "2HB " }, element h, ionizable-proton false }, { id 17, name "2HE2", iupac-code { "2HE2" }, element h, ionizable-proton true }, { id 18, name "2HG ", iupac-code { "2HG " }, element h, ionizable-proton false }, { id 19, name "3H ", iupac-code { "3H " }, element h, ionizable-proton true } }, bonds { { atom-id-1 1, atom-id-2 9, bond-order partial-double }, { atom-id-1 2, atom-id-2 1, bond-order single }, { atom-id-1 2, atom-id-2 3, bond-order single }, { atom-id-1 2, atom-id-2 6, bond-order single }, { atom-id-1 3, atom-id-2 5, bond-order single }, { atom-id-1 3, atom-id-2 12, bond-order single }, { atom-id-1 3, atom-id-2 16, bond-order single }, { atom-id-1 4, atom-id-2 8, bond-order single }, { atom-id-1 4, atom-id-2 10, bond-order double }, { atom-id-1 5, atom-id-2 4, bond-order single }, { atom-id-1 5, atom-id-2 14, bond-order single }, { atom-id-1 5, atom-id-2 18, bond-order single }, { atom-id-1 7, atom-id-2 2, bond-order single }, { atom-id-1 7, atom-id-2 11, bond-order single }, { atom-id-1 7, atom-id-2 15, bond-order single }, { atom-id-1 7, atom-id-2 19, bond-order single }, { atom-id-1 8, atom-id-2 13, bond-order single }, { atom-id-1 8, atom-id-2 17, bond-order single } }, chiral-centers { { c 2, n1 7, n2 1, n3 3, sign positive } } }, { id 19, descr { name "GLU" }, residue-type amino-acid, iupac-code { "E" }, atoms { { id 1, name " C ", iupac-code { " C " }, element c, ionizable-proton false }, { id 2, name " CA ", iupac-code { " CA " }, element c, ionizable-proton false }, { id 3, name " CB ", iupac-code { " CB " }, element c, ionizable-proton false }, { id 4, name " CD ", iupac-code { " CD " }, element c, ionizable-proton false }, { id 5, name " CG ", iupac-code { " CG " }, element c, ionizable-proton false }, { id 6, name " H ", iupac-code { " H " }, element h, ionizable-proton false }, { id 7, name " HA ", iupac-code { " HA " }, element h, ionizable-proton false }, { id 8, name " HE1", iupac-code { " HE1" }, element h, ionizable-proton true }, { id 9, name " HE2", iupac-code { " HE2" }, element h, ionizable-proton true }, { id 10, name " N ", iupac-code { " N " }, element n, ionizable-proton false }, { id 11, name " O ", iupac-code { " O " }, element o, ionizable-proton false }, { id 12, name " OE1", iupac-code { " OE1" }, element o, ionizable-proton false }, { id 13, name " OE2", iupac-code { " OE2" }, element o, ionizable-proton false }, { id 14, name "1HB ", iupac-code { "1HB " }, element h, ionizable-proton false }, { id 15, name "1HG ", iupac-code { "1HG " }, element h, ionizable-proton false }, { id 16, name "2HB ", iupac-code { "2HB " }, element h, ionizable-proton false }, { id 17, name "2HG ", iupac-code { "2HG " }, element h, ionizable-proton false } }, bonds { { atom-id-1 1, atom-id-2 11, bond-order partial-double }, { atom-id-1 2, atom-id-2 1, bond-order single }, { atom-id-1 2, atom-id-2 3, bond-order single }, { atom-id-1 2, atom-id-2 7, bond-order single }, { atom-id-1 3, atom-id-2 5, bond-order single }, { atom-id-1 3, atom-id-2 14, bond-order single }, { atom-id-1 3, atom-id-2 16, bond-order single }, { atom-id-1 4, atom-id-2 12, bond-order partial-double }, { atom-id-1 4, atom-id-2 13, bond-order partial-double }, { atom-id-1 5, atom-id-2 4, bond-order single }, { atom-id-1 5, atom-id-2 15, bond-order single }, { atom-id-1 5, atom-id-2 17, bond-order single }, { atom-id-1 10, atom-id-2 2, bond-order single }, { atom-id-1 10, atom-id-2 6, bond-order single }, { atom-id-1 12, atom-id-2 8, bond-order single }, { atom-id-1 13, atom-id-2 9, bond-order single } }, chiral-centers { { c 2, n1 10, n2 1, n3 3, sign positive } } }, { id 20, descr { name "GLU COOH" }, residue-type amino-acid, iupac-code { "E" }, atoms { { id 1, name " C ", iupac-code { " C " }, element c, ionizable-proton false }, { id 2, name " CA ", iupac-code { " CA " }, element c, ionizable-proton false }, { id 3, name " CB ", iupac-code { " CB " }, element c, ionizable-proton false }, { id 4, name " CD ", iupac-code { " CD " }, element c, ionizable-proton false }, { id 5, name " CG ", iupac-code { " CG " }, element c, ionizable-proton false }, { id 6, name " HA ", iupac-code { " HA " }, element h, ionizable-proton false }, { id 7, name " HE1", iupac-code { " HE1" }, element h, ionizable-proton true }, { id 8, name " HE2", iupac-code { " HE2" }, element h, ionizable-proton true }, { id 9, name " HXT", iupac-code { " HXT" }, element h, ionizable-proton true }, { id 10, name " N ", iupac-code { " N " }, element n, ionizable-proton false }, { id 11, name " O ", iupac-code { " O " }, element o, ionizable-proton false }, { id 12, name " OE1", iupac-code { " OE1" }, element o, ionizable-proton false }, { id 13, name " OE2", iupac-code { " OE2" }, element o, ionizable-proton false }, { id 14, name " OXT", iupac-code { " OXT" }, element o, ionizable-proton false }, { id 15, name "1HB ", iupac-code { "1HB " }, element h, ionizable-proton false }, { id 16, name "1HG ", iupac-code { "1HG " }, element h, ionizable-proton false }, { id 17, name "2HB ", iupac-code { "2HB " }, element h, ionizable-proton false }, { id 18, name "2HG ", iupac-code { "2HG " }, element h, ionizable-proton false }, { id 19, name " H ", iupac-code { " H " }, element h, ionizable-proton false } }, bonds { { atom-id-1 1, atom-id-2 11, bond-order partial-double }, { atom-id-1 1, atom-id-2 14, bond-order single }, { atom-id-1 2, atom-id-2 1, bond-order single }, { atom-id-1 2, atom-id-2 3, bond-order single }, { atom-id-1 2, atom-id-2 6, bond-order single }, { atom-id-1 3, atom-id-2 5, bond-order single }, { atom-id-1 3, atom-id-2 15, bond-order single }, { atom-id-1 3, atom-id-2 17, bond-order single }, { atom-id-1 4, atom-id-2 12, bond-order partial-double }, { atom-id-1 4, atom-id-2 13, bond-order partial-double }, { atom-id-1 5, atom-id-2 4, bond-order single }, { atom-id-1 5, atom-id-2 16, bond-order single }, { atom-id-1 5, atom-id-2 18, bond-order single }, { atom-id-1 10, atom-id-2 2, bond-order single }, { atom-id-1 12, atom-id-2 7, bond-order single }, { atom-id-1 13, atom-id-2 8, bond-order single }, { atom-id-1 14, atom-id-2 9, bond-order single }, { atom-id-1 10, atom-id-2 19, bond-order single } }, chiral-centers { { c 2, n1 10, n2 1, n3 3, sign positive } } }, { id 21, descr { name "GLU NH3+" }, residue-type amino-acid, iupac-code { "E" }, atoms { { id 1, name " C ", iupac-code { " C " }, element c, ionizable-proton false }, { id 2, name " CA ", iupac-code { " CA " }, element c, ionizable-proton false }, { id 3, name " CB ", iupac-code { " CB " }, element c, ionizable-proton false }, { id 4, name " CD ", iupac-code { " CD " }, element c, ionizable-proton false }, { id 5, name " CG ", iupac-code { " CG " }, element c, ionizable-proton false }, { id 6, name " HA ", iupac-code { " HA " }, element h, ionizable-proton false }, { id 7, name " HE1", iupac-code { " HE1" }, element h, ionizable-proton true }, { id 8, name " HE2", iupac-code { " HE2" }, element h, ionizable-proton true }, { id 9, name " N ", iupac-code { " N " }, element n, ionizable-proton false }, { id 10, name " O ", iupac-code { " O " }, element o, ionizable-proton false }, { id 11, name " OE1", iupac-code { " OE1" }, element o, ionizable-proton false }, { id 12, name " OE2", iupac-code { " OE2" }, element o, ionizable-proton false }, { id 13, name "1H ", iupac-code { "1H " }, element h, ionizable-proton true }, { id 14, name "1HB ", iupac-code { "1HB " }, element h, ionizable-proton false }, { id 15, name "1HG ", iupac-code { "1HG " }, element h, ionizable-proton false }, { id 16, name "2H ", iupac-code { "2H " }, element h, ionizable-proton true }, { id 17, name "2HB ", iupac-code { "2HB " }, element h, ionizable-proton false }, { id 18, name "2HG ", iupac-code { "2HG " }, element h, ionizable-proton false }, { id 19, name "3H ", iupac-code { "3H " }, element h, ionizable-proton true } }, bonds { { atom-id-1 1, atom-id-2 10, bond-order partial-double }, { atom-id-1 2, atom-id-2 1, bond-order single }, { atom-id-1 2, atom-id-2 3, bond-order single }, { atom-id-1 2, atom-id-2 6, bond-order single }, { atom-id-1 3, atom-id-2 5, bond-order single }, { atom-id-1 3, atom-id-2 14, bond-order single }, { atom-id-1 3, atom-id-2 17, bond-order single }, { atom-id-1 4, atom-id-2 11, bond-order partial-double }, { atom-id-1 4, atom-id-2 12, bond-order partial-double }, { atom-id-1 5, atom-id-2 4, bond-order single }, { atom-id-1 5, atom-id-2 15, bond-order single }, { atom-id-1 5, atom-id-2 18, bond-order single }, { atom-id-1 9, atom-id-2 2, bond-order single }, { atom-id-1 9, atom-id-2 13, bond-order single }, { atom-id-1 9, atom-id-2 16, bond-order single }, { atom-id-1 9, atom-id-2 19, bond-order single }, { atom-id-1 11, atom-id-2 7, bond-order single }, { atom-id-1 12, atom-id-2 8, bond-order single } }, chiral-centers { { c 2, n1 9, n2 1, n3 3, sign positive } } }, { id 22, descr { name "GLY" }, residue-type amino-acid, iupac-code { "G" }, atoms { { id 1, name " C ", iupac-code { " C " }, element c, ionizable-proton false }, { id 2, name " CA ", iupac-code { " CA " }, element c, ionizable-proton false }, { id 3, name " H ", iupac-code { " H " }, element h, ionizable-proton false }, { id 4, name " N ", iupac-code { " N " }, element n, ionizable-proton false }, { id 5, name " O ", iupac-code { " O " }, element o, ionizable-proton false }, { id 6, name "1HA ", iupac-code { "1HA " }, element h, ionizable-proton false }, { id 7, name "2HA ", iupac-code { "2HA " }, element h, ionizable-proton false } }, bonds { { atom-id-1 1, atom-id-2 5, bond-order partial-double }, { atom-id-1 2, atom-id-2 1, bond-order single }, { atom-id-1 2, atom-id-2 6, bond-order single }, { atom-id-1 2, atom-id-2 7, bond-order single }, { atom-id-1 4, atom-id-2 2, bond-order single }, { atom-id-1 4, atom-id-2 3, bond-order single } } }, { id 23, descr { name "GLY COOH" }, residue-type amino-acid, iupac-code { "G" }, atoms { { id 1, name " C ", iupac-code { " C " }, element c, ionizable-proton false }, { id 2, name " CA ", iupac-code { " CA " }, element c, ionizable-proton false }, { id 3, name " HXT", iupac-code { " HXT" }, element h, ionizable-proton true }, { id 4, name " N ", iupac-code { " N " }, element n, ionizable-proton false }, { id 5, name " O ", iupac-code { " O " }, element o, ionizable-proton false }, { id 6, name " OXT", iupac-code { " OXT" }, element o, ionizable-proton false }, { id 7, name "1HA ", iupac-code { "1HA " }, element h, ionizable-proton false }, { id 8, name "2HA ", iupac-code { "2HA " }, element h, ionizable-proton false }, { id 9, name " H ", iupac-code { " H " }, element h, ionizable-proton false } }, bonds { { atom-id-1 1, atom-id-2 5, bond-order partial-double }, { atom-id-1 1, atom-id-2 6, bond-order single }, { atom-id-1 2, atom-id-2 1, bond-order single }, { atom-id-1 2, atom-id-2 7, bond-order single }, { atom-id-1 2, atom-id-2 8, bond-order single }, { atom-id-1 4, atom-id-2 2, bond-order single }, { atom-id-1 6, atom-id-2 3, bond-order single }, { atom-id-1 4, atom-id-2 9, bond-order single } } }, { id 24, descr { name "GLY NH3+" }, residue-type amino-acid, iupac-code { "G" }, atoms { { id 1, name " C ", iupac-code { " C " }, element c, ionizable-proton false }, { id 2, name " CA ", iupac-code { " CA " }, element c, ionizable-proton false }, { id 3, name " N ", iupac-code { " N " }, element n, ionizable-proton false }, { id 4, name " O ", iupac-code { " O " }, element o, ionizable-proton false }, { id 5, name "1H ", iupac-code { "1H " }, element h, ionizable-proton true }, { id 6, name "1HA ", iupac-code { "1HA " }, element h, ionizable-proton false }, { id 7, name "2H ", iupac-code { "2H " }, element h, ionizable-proton true }, { id 8, name "2HA ", iupac-code { "2HA " }, element h, ionizable-proton false }, { id 9, name "3H ", iupac-code { "3H " }, element h, ionizable-proton true } }, bonds { { atom-id-1 1, atom-id-2 4, bond-order partial-double }, { atom-id-1 2, atom-id-2 1, bond-order single }, { atom-id-1 2, atom-id-2 6, bond-order single }, { atom-id-1 2, atom-id-2 8, bond-order single }, { atom-id-1 3, atom-id-2 2, bond-order single }, { atom-id-1 3, atom-id-2 5, bond-order single }, { atom-id-1 3, atom-id-2 7, bond-order single }, { atom-id-1 3, atom-id-2 9, bond-order single } } }, { id 25, descr { name "HIS" }, residue-type amino-acid, iupac-code { "H" }, atoms { { id 1, name " C ", iupac-code { " C " }, element c, ionizable-proton false }, { id 2, name " CA ", iupac-code { " CA " }, element c, ionizable-proton false }, { id 3, name " CB ", iupac-code { " CB " }, element c, ionizable-proton false }, { id 4, name " CD2", iupac-code { " CD2" }, element c, ionizable-proton false }, { id 5, name " CE1", iupac-code { " CE1" }, element c, ionizable-proton false }, { id 6, name " CG ", iupac-code { " CG " }, element c, ionizable-proton false }, { id 7, name " H ", iupac-code { " H " }, element h, ionizable-proton false }, { id 8, name " HA ", iupac-code { " HA " }, element h, ionizable-proton false }, { id 9, name " HD1", iupac-code { " HD1" }, element h, ionizable-proton false }, { id 10, name " HD2", iupac-code { " HD2" }, element h, ionizable-proton false }, { id 11, name " HE1", iupac-code { " HE1" }, element h, ionizable-proton true }, { id 12, name " HE2", iupac-code { " HE2" }, element h, ionizable-proton true }, { id 13, name " N ", iupac-code { " N " }, element n, ionizable-proton false }, { id 14, name " ND1", iupac-code { " ND1" }, element n, ionizable-proton false }, { id 15, name " NE2", iupac-code { " NE2" }, element n, ionizable-proton false }, { id 16, name " O ", iupac-code { " O " }, element o, ionizable-proton false }, { id 17, name "1HB ", iupac-code { "1HB " }, element h, ionizable-proton false }, { id 18, name "2HB ", iupac-code { "2HB " }, element h, ionizable-proton false } }, bonds { { atom-id-1 1, atom-id-2 16, bond-order partial-double }, { atom-id-1 2, atom-id-2 1, bond-order single }, { atom-id-1 2, atom-id-2 3, bond-order single }, { atom-id-1 2, atom-id-2 8, bond-order single }, { atom-id-1 3, atom-id-2 6, bond-order single }, { atom-id-1 3, atom-id-2 17, bond-order single }, { atom-id-1 3, atom-id-2 18, bond-order single }, { atom-id-1 4, atom-id-2 10, bond-order single }, { atom-id-1 4, atom-id-2 15, bond-order single }, { atom-id-1 5, atom-id-2 11, bond-order single }, { atom-id-1 5, atom-id-2 15, bond-order double }, { atom-id-1 6, atom-id-2 4, bond-order double }, { atom-id-1 6, atom-id-2 14, bond-order single }, { atom-id-1 13, atom-id-2 2, bond-order single }, { atom-id-1 13, atom-id-2 7, bond-order single }, { atom-id-1 14, atom-id-2 5, bond-order single }, { atom-id-1 14, atom-id-2 9, bond-order single }, { atom-id-1 15, atom-id-2 12, bond-order single } }, chiral-centers { { c 2, n1 13, n2 1, n3 3, sign positive } } }, { id 26, descr { name "HIS COOH" }, residue-type amino-acid, iupac-code { "H" }, atoms { { id 1, name " C ", iupac-code { " C " }, element c, ionizable-proton false }, { id 2, name " CA ", iupac-code { " CA " }, element c, ionizable-proton false }, { id 3, name " CB ", iupac-code { " CB " }, element c, ionizable-proton false }, { id 4, name " CD2", iupac-code { " CD2" }, element c, ionizable-proton false }, { id 5, name " CE1", iupac-code { " CE1" }, element c, ionizable-proton false }, { id 6, name " CG ", iupac-code { " CG " }, element c, ionizable-proton false }, { id 7, name " HA ", iupac-code { " HA " }, element h, ionizable-proton false }, { id 8, name " HD1", iupac-code { " HD1" }, element h, ionizable-proton false }, { id 9, name " HD2", iupac-code { " HD2" }, element h, ionizable-proton false }, { id 10, name " HE1", iupac-code { " HE1" }, element h, ionizable-proton true }, { id 11, name " HE2", iupac-code { " HE2" }, element h, ionizable-proton true }, { id 12, name " HXT", iupac-code { " HXT" }, element h, ionizable-proton true }, { id 13, name " N ", iupac-code { " N " }, element n, ionizable-proton false }, { id 14, name " ND1", iupac-code { " ND1" }, element n, ionizable-proton false }, { id 15, name " NE2", iupac-code { " NE2" }, element n, ionizable-proton false }, { id 16, name " O ", iupac-code { " O " }, element o, ionizable-proton false }, { id 17, name " OXT", iupac-code { " OXT" }, element o, ionizable-proton false }, { id 18, name "1HB ", iupac-code { "1HB " }, element h, ionizable-proton false }, { id 19, name "2HB ", iupac-code { "2HB " }, element h, ionizable-proton false }, { id 20, name " H ", iupac-code { " H " }, element h, ionizable-proton false } }, bonds { { atom-id-1 1, atom-id-2 16, bond-order partial-double }, { atom-id-1 1, atom-id-2 17, bond-order single }, { atom-id-1 2, atom-id-2 1, bond-order single }, { atom-id-1 2, atom-id-2 3, bond-order single }, { atom-id-1 2, atom-id-2 7, bond-order single }, { atom-id-1 3, atom-id-2 6, bond-order single }, { atom-id-1 3, atom-id-2 18, bond-order single }, { atom-id-1 3, atom-id-2 19, bond-order single }, { atom-id-1 4, atom-id-2 9, bond-order single }, { atom-id-1 4, atom-id-2 15, bond-order single }, { atom-id-1 5, atom-id-2 10, bond-order single }, { atom-id-1 5, atom-id-2 15, bond-order double }, { atom-id-1 6, atom-id-2 4, bond-order double }, { atom-id-1 6, atom-id-2 14, bond-order single }, { atom-id-1 13, atom-id-2 2, bond-order single }, { atom-id-1 14, atom-id-2 5, bond-order single }, { atom-id-1 14, atom-id-2 8, bond-order single }, { atom-id-1 15, atom-id-2 11, bond-order single }, { atom-id-1 17, atom-id-2 12, bond-order single }, { atom-id-1 13, atom-id-2 20, bond-order single } }, chiral-centers { { c 2, n1 13, n2 1, n3 3, sign positive } } }, { id 27, descr { name "HIS NH3+" }, residue-type amino-acid, iupac-code { "H" }, atoms { { id 1, name " C ", iupac-code { " C " }, element c, ionizable-proton false }, { id 2, name " CA ", iupac-code { " CA " }, element c, ionizable-proton false }, { id 3, name " CB ", iupac-code { " CB " }, element c, ionizable-proton false }, { id 4, name " CD2", iupac-code { " CD2" }, element c, ionizable-proton false }, { id 5, name " CE1", iupac-code { " CE1" }, element c, ionizable-proton false }, { id 6, name " CG ", iupac-code { " CG " }, element c, ionizable-proton false }, { id 7, name " HA ", iupac-code { " HA " }, element h, ionizable-proton false }, { id 8, name " HD1", iupac-code { " HD1" }, element h, ionizable-proton false }, { id 9, name " HD2", iupac-code { " HD2" }, element h, ionizable-proton false }, { id 10, name " HE1", iupac-code { " HE1" }, element h, ionizable-proton true }, { id 11, name " HE2", iupac-code { " HE2" }, element h, ionizable-proton true }, { id 12, name " N ", iupac-code { " N " }, element n, ionizable-proton false }, { id 13, name " ND1", iupac-code { " ND1" }, element n, ionizable-proton false }, { id 14, name " NE2", iupac-code { " NE2" }, element n, ionizable-proton false }, { id 15, name " O ", iupac-code { " O " }, element o, ionizable-proton false }, { id 16, name "1H ", iupac-code { "1H " }, element h, ionizable-proton true }, { id 17, name "1HB ", iupac-code { "1HB " }, element h, ionizable-proton false }, { id 18, name "2H ", iupac-code { "2H " }, element h, ionizable-proton true }, { id 19, name "2HB ", iupac-code { "2HB " }, element h, ionizable-proton false }, { id 20, name "3H ", iupac-code { "3H " }, element h, ionizable-proton true } }, bonds { { atom-id-1 1, atom-id-2 15, bond-order partial-double }, { atom-id-1 2, atom-id-2 1, bond-order single }, { atom-id-1 2, atom-id-2 3, bond-order single }, { atom-id-1 2, atom-id-2 7, bond-order single }, { atom-id-1 3, atom-id-2 6, bond-order single }, { atom-id-1 3, atom-id-2 17, bond-order single }, { atom-id-1 3, atom-id-2 19, bond-order single }, { atom-id-1 4, atom-id-2 9, bond-order single }, { atom-id-1 4, atom-id-2 14, bond-order single }, { atom-id-1 5, atom-id-2 10, bond-order single }, { atom-id-1 5, atom-id-2 14, bond-order double }, { atom-id-1 6, atom-id-2 4, bond-order double }, { atom-id-1 6, atom-id-2 13, bond-order single }, { atom-id-1 12, atom-id-2 2, bond-order single }, { atom-id-1 12, atom-id-2 16, bond-order single }, { atom-id-1 12, atom-id-2 18, bond-order single }, { atom-id-1 12, atom-id-2 20, bond-order single }, { atom-id-1 13, atom-id-2 5, bond-order single }, { atom-id-1 13, atom-id-2 8, bond-order single }, { atom-id-1 14, atom-id-2 11, bond-order single } }, chiral-centers { { c 2, n1 12, n2 1, n3 3, sign positive } } }, { id 28, descr { name "ILE" }, residue-type amino-acid, iupac-code { "I" }, atoms { { id 1, name " C ", iupac-code { " C " }, element c, ionizable-proton false }, { id 2, name " CA ", iupac-code { " CA " }, element c, ionizable-proton false }, { id 3, name " CB ", iupac-code { " CB " }, element c, ionizable-proton false }, { id 4, name " CD1", iupac-code { " CD1" }, element c, ionizable-proton false }, { id 5, name " CG1", iupac-code { " CG1" }, element c, ionizable-proton false }, { id 6, name " CG2", iupac-code { " CG2" }, element c, ionizable-proton false }, { id 7, name " H ", iupac-code { " H " }, element h, ionizable-proton false }, { id 8, name " HA ", iupac-code { " HA " }, element h, ionizable-proton false }, { id 9, name " HB ", iupac-code { " HB " }, element h, ionizable-proton false }, { id 10, name " N ", iupac-code { " N " }, element n, ionizable-proton false }, { id 11, name " O ", iupac-code { " O " }, element o, ionizable-proton false }, { id 12, name "1HD1", iupac-code { "1HD1" }, element h, ionizable-proton false }, { id 13, name "1HG1", iupac-code { "1HG1" }, element h, ionizable-proton false }, { id 14, name "1HG2", iupac-code { "1HG2" }, element h, ionizable-proton false }, { id 15, name "2HD1", iupac-code { "2HD1" }, element h, ionizable-proton false }, { id 16, name "2HG1", iupac-code { "2HG1" }, element h, ionizable-proton false }, { id 17, name "2HG2", iupac-code { "2HG2" }, element h, ionizable-proton false }, { id 18, name "3HD1", iupac-code { "3HD1" }, element h, ionizable-proton false }, { id 19, name "3HG2", iupac-code { "3HG2" }, element h, ionizable-proton false } }, bonds { { atom-id-1 1, atom-id-2 11, bond-order partial-double }, { atom-id-1 2, atom-id-2 1, bond-order single }, { atom-id-1 2, atom-id-2 3, bond-order single }, { atom-id-1 2, atom-id-2 8, bond-order single }, { atom-id-1 3, atom-id-2 5, bond-order single }, { atom-id-1 3, atom-id-2 6, bond-order single }, { atom-id-1 3, atom-id-2 9, bond-order single }, { atom-id-1 4, atom-id-2 12, bond-order single }, { atom-id-1 4, atom-id-2 15, bond-order single }, { atom-id-1 4, atom-id-2 18, bond-order single }, { atom-id-1 5, atom-id-2 4, bond-order single }, { atom-id-1 5, atom-id-2 13, bond-order single }, { atom-id-1 5, atom-id-2 16, bond-order single }, { atom-id-1 6, atom-id-2 14, bond-order single }, { atom-id-1 6, atom-id-2 17, bond-order single }, { atom-id-1 6, atom-id-2 19, bond-order single }, { atom-id-1 10, atom-id-2 2, bond-order single }, { atom-id-1 10, atom-id-2 7, bond-order single } }, chiral-centers { { c 2, n1 10, n2 1, n3 3, sign positive }, { c 3, n1 2, n2 5, n3 6, sign positive } } }, { id 29, descr { name "ILE COOH" }, residue-type amino-acid, iupac-code { "I" }, atoms { { id 1, name " C ", iupac-code { " C " }, element c, ionizable-proton false }, { id 2, name " CA ", iupac-code { " CA " }, element c, ionizable-proton false }, { id 3, name " CB ", iupac-code { " CB " }, element c, ionizable-proton false }, { id 4, name " CD1", iupac-code { " CD1" }, element c, ionizable-proton false }, { id 5, name " CG1", iupac-code { " CG1" }, element c, ionizable-proton false }, { id 6, name " CG2", iupac-code { " CG2" }, element c, ionizable-proton false }, { id 7, name " HA ", iupac-code { " HA " }, element h, ionizable-proton false }, { id 8, name " HB ", iupac-code { " HB " }, element h, ionizable-proton false }, { id 9, name " HXT", iupac-code { " HXT" }, element h, ionizable-proton true }, { id 10, name " N ", iupac-code { " N " }, element n, ionizable-proton false }, { id 11, name " O ", iupac-code { " O " }, element o, ionizable-proton false }, { id 12, name " OXT", iupac-code { " OXT" }, element o, ionizable-proton false }, { id 13, name "1HD1", iupac-code { "1HD1" }, element h, ionizable-proton false }, { id 14, name "1HG1", iupac-code { "1HG1" }, element h, ionizable-proton false }, { id 15, name "1HG2", iupac-code { "1HG2" }, element h, ionizable-proton false }, { id 16, name "2HD1", iupac-code { "2HD1" }, element h, ionizable-proton false }, { id 17, name "2HG1", iupac-code { "2HG1" }, element h, ionizable-proton false }, { id 18, name "2HG2", iupac-code { "2HG2" }, element h, ionizable-proton false }, { id 19, name "3HD1", iupac-code { "3HD1" }, element h, ionizable-proton false }, { id 20, name "3HG2", iupac-code { "3HG2" }, element h, ionizable-proton false }, { id 21, name " H ", iupac-code { " H " }, element h, ionizable-proton false } }, bonds { { atom-id-1 1, atom-id-2 11, bond-order partial-double }, { atom-id-1 1, atom-id-2 12, bond-order single }, { atom-id-1 2, atom-id-2 1, bond-order single }, { atom-id-1 2, atom-id-2 3, bond-order single }, { atom-id-1 2, atom-id-2 7, bond-order single }, { atom-id-1 3, atom-id-2 5, bond-order single }, { atom-id-1 3, atom-id-2 6, bond-order single }, { atom-id-1 3, atom-id-2 8, bond-order single }, { atom-id-1 4, atom-id-2 13, bond-order single }, { atom-id-1 4, atom-id-2 16, bond-order single }, { atom-id-1 4, atom-id-2 19, bond-order single }, { atom-id-1 5, atom-id-2 4, bond-order single }, { atom-id-1 5, atom-id-2 14, bond-order single }, { atom-id-1 5, atom-id-2 17, bond-order single }, { atom-id-1 6, atom-id-2 15, bond-order single }, { atom-id-1 6, atom-id-2 18, bond-order single }, { atom-id-1 6, atom-id-2 20, bond-order single }, { atom-id-1 10, atom-id-2 2, bond-order single }, { atom-id-1 12, atom-id-2 9, bond-order single }, { atom-id-1 10, atom-id-2 21, bond-order single } }, chiral-centers { { c 2, n1 10, n2 1, n3 3, sign positive }, { c 3, n1 2, n2 5, n3 6, sign positive } } }, { id 30, descr { name "ILE NH3+" }, residue-type amino-acid, iupac-code { "I" }, atoms { { id 1, name " C ", iupac-code { " C " }, element c, ionizable-proton false }, { id 2, name " CA ", iupac-code { " CA " }, element c, ionizable-proton false }, { id 3, name " CB ", iupac-code { " CB " }, element c, ionizable-proton false }, { id 4, name " CD1", iupac-code { " CD1" }, element c, ionizable-proton false }, { id 5, name " CG1", iupac-code { " CG1" }, element c, ionizable-proton false }, { id 6, name " CG2", iupac-code { " CG2" }, element c, ionizable-proton false }, { id 7, name " HA ", iupac-code { " HA " }, element h, ionizable-proton false }, { id 8, name " HB ", iupac-code { " HB " }, element h, ionizable-proton false }, { id 9, name " N ", iupac-code { " N " }, element n, ionizable-proton false }, { id 10, name " O ", iupac-code { " O " }, element o, ionizable-proton false }, { id 11, name "1H ", iupac-code { "1H " }, element h, ionizable-proton true }, { id 12, name "1HD1", iupac-code { "1HD1" }, element h, ionizable-proton false }, { id 13, name "1HG1", iupac-code { "1HG1" }, element h, ionizable-proton false }, { id 14, name "1HG2", iupac-code { "1HG2" }, element h, ionizable-proton false }, { id 15, name "2H ", iupac-code { "2H " }, element h, ionizable-proton true }, { id 16, name "2HD1", iupac-code { "2HD1" }, element h, ionizable-proton false }, { id 17, name "2HG1", iupac-code { "2HG1" }, element h, ionizable-proton false }, { id 18, name "2HG2", iupac-code { "2HG2" }, element h, ionizable-proton false }, { id 19, name "3H ", iupac-code { "3H " }, element h, ionizable-proton true }, { id 20, name "3HD1", iupac-code { "3HD1" }, element h, ionizable-proton false }, { id 21, name "3HG2", iupac-code { "3HG2" }, element h, ionizable-proton false } }, bonds { { atom-id-1 1, atom-id-2 10, bond-order partial-double }, { atom-id-1 2, atom-id-2 1, bond-order single }, { atom-id-1 2, atom-id-2 3, bond-order single }, { atom-id-1 2, atom-id-2 7, bond-order single }, { atom-id-1 3, atom-id-2 5, bond-order single }, { atom-id-1 3, atom-id-2 6, bond-order single }, { atom-id-1 3, atom-id-2 8, bond-order single }, { atom-id-1 4, atom-id-2 12, bond-order single }, { atom-id-1 4, atom-id-2 16, bond-order single }, { atom-id-1 4, atom-id-2 20, bond-order single }, { atom-id-1 5, atom-id-2 4, bond-order single }, { atom-id-1 5, atom-id-2 13, bond-order single }, { atom-id-1 5, atom-id-2 17, bond-order single }, { atom-id-1 6, atom-id-2 14, bond-order single }, { atom-id-1 6, atom-id-2 18, bond-order single }, { atom-id-1 6, atom-id-2 21, bond-order single }, { atom-id-1 9, atom-id-2 2, bond-order single }, { atom-id-1 9, atom-id-2 11, bond-order single }, { atom-id-1 9, atom-id-2 15, bond-order single }, { atom-id-1 9, atom-id-2 19, bond-order single } }, chiral-centers { { c 2, n1 9, n2 1, n3 3, sign positive }, { c 3, n1 2, n2 5, n3 6, sign positive } } }, { id 31, descr { name "LEU" }, residue-type amino-acid, iupac-code { "L" }, atoms { { id 1, name " C ", iupac-code { " C " }, element c, ionizable-proton false }, { id 2, name " CA ", iupac-code { " CA " }, element c, ionizable-proton false }, { id 3, name " CB ", iupac-code { " CB " }, element c, ionizable-proton false }, { id 4, name " CD1", iupac-code { " CD1" }, element c, ionizable-proton false }, { id 5, name " CD2", iupac-code { " CD2" }, element c, ionizable-proton false }, { id 6, name " CG ", iupac-code { " CG " }, element c, ionizable-proton false }, { id 7, name " H ", iupac-code { " H " }, element h, ionizable-proton false }, { id 8, name " HA ", iupac-code { " HA " }, element h, ionizable-proton false }, { id 9, name " HG ", iupac-code { " HG " }, element h, ionizable-proton true }, { id 10, name " N ", iupac-code { " N " }, element n, ionizable-proton false }, { id 11, name " O ", iupac-code { " O " }, element o, ionizable-proton false }, { id 12, name "1HB ", iupac-code { "1HB " }, element h, ionizable-proton false }, { id 13, name "1HD1", iupac-code { "1HD1" }, element h, ionizable-proton false }, { id 14, name "1HD2", iupac-code { "1HD2" }, element h, ionizable-proton false }, { id 15, name "2HB ", iupac-code { "2HB " }, element h, ionizable-proton false }, { id 16, name "2HD1", iupac-code { "2HD1" }, element h, ionizable-proton false }, { id 17, name "2HD2", iupac-code { "2HD2" }, element h, ionizable-proton false }, { id 18, name "3HD1", iupac-code { "3HD1" }, element h, ionizable-proton false }, { id 19, name "3HD2", iupac-code { "3HD2" }, element h, ionizable-proton false } }, bonds { { atom-id-1 1, atom-id-2 11, bond-order partial-double }, { atom-id-1 2, atom-id-2 1, bond-order single }, { atom-id-1 2, atom-id-2 3, bond-order single }, { atom-id-1 2, atom-id-2 8, bond-order single }, { atom-id-1 3, atom-id-2 6, bond-order single }, { atom-id-1 3, atom-id-2 12, bond-order single }, { atom-id-1 3, atom-id-2 15, bond-order single }, { atom-id-1 4, atom-id-2 13, bond-order single }, { atom-id-1 4, atom-id-2 16, bond-order single }, { atom-id-1 4, atom-id-2 18, bond-order single }, { atom-id-1 5, atom-id-2 14, bond-order single }, { atom-id-1 5, atom-id-2 17, bond-order single }, { atom-id-1 5, atom-id-2 19, bond-order single }, { atom-id-1 6, atom-id-2 4, bond-order single }, { atom-id-1 6, atom-id-2 5, bond-order single }, { atom-id-1 6, atom-id-2 9, bond-order single }, { atom-id-1 10, atom-id-2 2, bond-order single }, { atom-id-1 10, atom-id-2 7, bond-order single } }, chiral-centers { { c 2, n1 10, n2 1, n3 3, sign positive } } }, { id 32, descr { name "LEU COOH" }, residue-type amino-acid, iupac-code { "L" }, atoms { { id 1, name " C ", iupac-code { " C " }, element c, ionizable-proton false }, { id 2, name " CA ", iupac-code { " CA " }, element c, ionizable-proton false }, { id 3, name " CB ", iupac-code { " CB " }, element c, ionizable-proton false }, { id 4, name " CD1", iupac-code { " CD1" }, element c, ionizable-proton false }, { id 5, name " CD2", iupac-code { " CD2" }, element c, ionizable-proton false }, { id 6, name " CG ", iupac-code { " CG " }, element c, ionizable-proton false }, { id 7, name " HA ", iupac-code { " HA " }, element h, ionizable-proton false }, { id 8, name " HG ", iupac-code { " HG " }, element h, ionizable-proton true }, { id 9, name " HXT", iupac-code { " HXT" }, element h, ionizable-proton true }, { id 10, name " N ", iupac-code { " N " }, element n, ionizable-proton false }, { id 11, name " O ", iupac-code { " O " }, element o, ionizable-proton false }, { id 12, name " OXT", iupac-code { " OXT" }, element o, ionizable-proton false }, { id 13, name "1HB ", iupac-code { "1HB " }, element h, ionizable-proton false }, { id 14, name "1HD1", iupac-code { "1HD1" }, element h, ionizable-proton false }, { id 15, name "1HD2", iupac-code { "1HD2" }, element h, ionizable-proton false }, { id 16, name "2HB ", iupac-code { "2HB " }, element h, ionizable-proton false }, { id 17, name "2HD1", iupac-code { "2HD1" }, element h, ionizable-proton false }, { id 18, name "2HD2", iupac-code { "2HD2" }, element h, ionizable-proton false }, { id 19, name "3HD1", iupac-code { "3HD1" }, element h, ionizable-proton false }, { id 20, name "3HD2", iupac-code { "3HD2" }, element h, ionizable-proton false }, { id 21, name " H ", iupac-code { " H " }, element h, ionizable-proton false } }, bonds { { atom-id-1 1, atom-id-2 11, bond-order partial-double }, { atom-id-1 1, atom-id-2 12, bond-order single }, { atom-id-1 2, atom-id-2 1, bond-order single }, { atom-id-1 2, atom-id-2 3, bond-order single }, { atom-id-1 2, atom-id-2 7, bond-order single }, { atom-id-1 3, atom-id-2 6, bond-order single }, { atom-id-1 3, atom-id-2 13, bond-order single }, { atom-id-1 3, atom-id-2 16, bond-order single }, { atom-id-1 4, atom-id-2 14, bond-order single }, { atom-id-1 4, atom-id-2 17, bond-order single }, { atom-id-1 4, atom-id-2 19, bond-order single }, { atom-id-1 5, atom-id-2 15, bond-order single }, { atom-id-1 5, atom-id-2 18, bond-order single }, { atom-id-1 5, atom-id-2 20, bond-order single }, { atom-id-1 6, atom-id-2 4, bond-order single }, { atom-id-1 6, atom-id-2 5, bond-order single }, { atom-id-1 6, atom-id-2 8, bond-order single }, { atom-id-1 10, atom-id-2 2, bond-order single }, { atom-id-1 12, atom-id-2 9, bond-order single }, { atom-id-1 10, atom-id-2 21, bond-order single } }, chiral-centers { { c 2, n1 10, n2 1, n3 3, sign positive } } }, { id 33, descr { name "LEU NH3+" }, residue-type amino-acid, iupac-code { "L" }, atoms { { id 1, name " C ", iupac-code { " C " }, element c, ionizable-proton false }, { id 2, name " CA ", iupac-code { " CA " }, element c, ionizable-proton false }, { id 3, name " CB ", iupac-code { " CB " }, element c, ionizable-proton false }, { id 4, name " CD1", iupac-code { " CD1" }, element c, ionizable-proton false }, { id 5, name " CD2", iupac-code { " CD2" }, element c, ionizable-proton false }, { id 6, name " CG ", iupac-code { " CG " }, element c, ionizable-proton false }, { id 7, name " HA ", iupac-code { " HA " }, element h, ionizable-proton false }, { id 8, name " HG ", iupac-code { " HG " }, element h, ionizable-proton true }, { id 9, name " N ", iupac-code { " N " }, element n, ionizable-proton false }, { id 10, name " O ", iupac-code { " O " }, element o, ionizable-proton false }, { id 11, name "1H ", iupac-code { "1H " }, element h, ionizable-proton true }, { id 12, name "1HB ", iupac-code { "1HB " }, element h, ionizable-proton false }, { id 13, name "1HD1", iupac-code { "1HD1" }, element h, ionizable-proton false }, { id 14, name "1HD2", iupac-code { "1HD2" }, element h, ionizable-proton false }, { id 15, name "2H ", iupac-code { "2H " }, element h, ionizable-proton true }, { id 16, name "2HB ", iupac-code { "2HB " }, element h, ionizable-proton false }, { id 17, name "2HD1", iupac-code { "2HD1" }, element h, ionizable-proton false }, { id 18, name "2HD2", iupac-code { "2HD2" }, element h, ionizable-proton false }, { id 19, name "3H ", iupac-code { "3H " }, element h, ionizable-proton true }, { id 20, name "3HD1", iupac-code { "3HD1" }, element h, ionizable-proton false }, { id 21, name "3HD2", iupac-code { "3HD2" }, element h, ionizable-proton false } }, bonds { { atom-id-1 1, atom-id-2 10, bond-order partial-double }, { atom-id-1 2, atom-id-2 1, bond-order single }, { atom-id-1 2, atom-id-2 3, bond-order single }, { atom-id-1 2, atom-id-2 7, bond-order single }, { atom-id-1 3, atom-id-2 6, bond-order single }, { atom-id-1 3, atom-id-2 12, bond-order single }, { atom-id-1 3, atom-id-2 16, bond-order single }, { atom-id-1 4, atom-id-2 13, bond-order single }, { atom-id-1 4, atom-id-2 17, bond-order single }, { atom-id-1 4, atom-id-2 20, bond-order single }, { atom-id-1 5, atom-id-2 14, bond-order single }, { atom-id-1 5, atom-id-2 18, bond-order single }, { atom-id-1 5, atom-id-2 21, bond-order single }, { atom-id-1 6, atom-id-2 4, bond-order single }, { atom-id-1 6, atom-id-2 5, bond-order single }, { atom-id-1 6, atom-id-2 8, bond-order single }, { atom-id-1 9, atom-id-2 2, bond-order single }, { atom-id-1 9, atom-id-2 11, bond-order single }, { atom-id-1 9, atom-id-2 15, bond-order single }, { atom-id-1 9, atom-id-2 19, bond-order single } }, chiral-centers { { c 2, n1 9, n2 1, n3 3, sign positive } } }, { id 34, descr { name "LYS" }, residue-type amino-acid, iupac-code { "K" }, atoms { { id 1, name " C ", iupac-code { " C " }, element c, ionizable-proton false }, { id 2, name " CA ", iupac-code { " CA " }, element c, ionizable-proton false }, { id 3, name " CB ", iupac-code { " CB " }, element c, ionizable-proton false }, { id 4, name " CD ", iupac-code { " CD " }, element c, ionizable-proton false }, { id 5, name " CE ", iupac-code { " CE " }, element c, ionizable-proton false }, { id 6, name " CG ", iupac-code { " CG " }, element c, ionizable-proton false }, { id 7, name " H ", iupac-code { " H " }, element h, ionizable-proton false }, { id 8, name " HA ", iupac-code { " HA " }, element h, ionizable-proton false }, { id 9, name " N ", iupac-code { " N " }, element n, ionizable-proton false }, { id 10, name " NZ ", iupac-code { " NZ " }, element n, ionizable-proton false }, { id 11, name " O ", iupac-code { " O " }, element o, ionizable-proton false }, { id 12, name "1HB ", iupac-code { "1HB " }, element h, ionizable-proton false }, { id 13, name "1HD ", iupac-code { "1HD " }, element h, ionizable-proton false }, { id 14, name "1HE ", iupac-code { "1HE " }, element h, ionizable-proton false }, { id 15, name "1HG ", iupac-code { "1HG " }, element h, ionizable-proton false }, { id 16, name "1HZ ", iupac-code { "1HZ " }, element h, ionizable-proton true }, { id 17, name "2HB ", iupac-code { "2HB " }, element h, ionizable-proton false }, { id 18, name "2HD ", iupac-code { "2HD " }, element h, ionizable-proton false }, { id 19, name "2HE ", iupac-code { "2HE " }, element h, ionizable-proton false }, { id 20, name "2HG ", iupac-code { "2HG " }, element h, ionizable-proton false }, { id 21, name "2HZ ", iupac-code { "2HZ " }, element h, ionizable-proton true }, { id 22, name "3HZ ", iupac-code { "3HZ " }, element h, ionizable-proton true } }, bonds { { atom-id-1 1, atom-id-2 11, bond-order partial-double }, { atom-id-1 2, atom-id-2 1, bond-order single }, { atom-id-1 2, atom-id-2 3, bond-order single }, { atom-id-1 2, atom-id-2 8, bond-order single }, { atom-id-1 3, atom-id-2 6, bond-order single }, { atom-id-1 3, atom-id-2 12, bond-order single }, { atom-id-1 3, atom-id-2 17, bond-order single }, { atom-id-1 4, atom-id-2 5, bond-order single }, { atom-id-1 4, atom-id-2 13, bond-order single }, { atom-id-1 4, atom-id-2 18, bond-order single }, { atom-id-1 5, atom-id-2 10, bond-order single }, { atom-id-1 5, atom-id-2 14, bond-order single }, { atom-id-1 5, atom-id-2 19, bond-order single }, { atom-id-1 6, atom-id-2 4, bond-order single }, { atom-id-1 6, atom-id-2 15, bond-order single }, { atom-id-1 6, atom-id-2 20, bond-order single }, { atom-id-1 9, atom-id-2 2, bond-order single }, { atom-id-1 9, atom-id-2 7, bond-order single }, { atom-id-1 10, atom-id-2 16, bond-order single }, { atom-id-1 10, atom-id-2 21, bond-order single }, { atom-id-1 10, atom-id-2 22, bond-order single } }, chiral-centers { { c 2, n1 9, n2 1, n3 3, sign positive } } }, { id 35, descr { name "LYS COOH" }, residue-type amino-acid, iupac-code { "K" }, atoms { { id 1, name " C ", iupac-code { " C " }, element c, ionizable-proton false }, { id 2, name " CA ", iupac-code { " CA " }, element c, ionizable-proton false }, { id 3, name " CB ", iupac-code { " CB " }, element c, ionizable-proton false }, { id 4, name " CD ", iupac-code { " CD " }, element c, ionizable-proton false }, { id 5, name " CE ", iupac-code { " CE " }, element c, ionizable-proton false }, { id 6, name " CG ", iupac-code { " CG " }, element c, ionizable-proton false }, { id 7, name " HA ", iupac-code { " HA " }, element h, ionizable-proton false }, { id 8, name " HXT", iupac-code { " HXT" }, element h, ionizable-proton true }, { id 9, name " N ", iupac-code { " N " }, element n, ionizable-proton false }, { id 10, name " NZ ", iupac-code { " NZ " }, element n, ionizable-proton false }, { id 11, name " O ", iupac-code { " O " }, element o, ionizable-proton false }, { id 12, name " OXT", iupac-code { " OXT" }, element o, ionizable-proton false }, { id 13, name "1HB ", iupac-code { "1HB " }, element h, ionizable-proton false }, { id 14, name "1HD ", iupac-code { "1HD " }, element h, ionizable-proton false }, { id 15, name "1HE ", iupac-code { "1HE " }, element h, ionizable-proton false }, { id 16, name "1HG ", iupac-code { "1HG " }, element h, ionizable-proton false }, { id 17, name "1HZ ", iupac-code { "1HZ " }, element h, ionizable-proton true }, { id 18, name "2HB ", iupac-code { "2HB " }, element h, ionizable-proton false }, { id 19, name "2HD ", iupac-code { "2HD " }, element h, ionizable-proton false }, { id 20, name "2HE ", iupac-code { "2HE " }, element h, ionizable-proton false }, { id 21, name "2HG ", iupac-code { "2HG " }, element h, ionizable-proton false }, { id 22, name "2HZ ", iupac-code { "2HZ " }, element h, ionizable-proton true }, { id 23, name "3HZ ", iupac-code { "3HZ " }, element h, ionizable-proton true }, { id 24, name " H ", iupac-code { " H " }, element h, ionizable-proton false } }, bonds { { atom-id-1 1, atom-id-2 11, bond-order partial-double }, { atom-id-1 1, atom-id-2 12, bond-order single }, { atom-id-1 2, atom-id-2 1, bond-order single }, { atom-id-1 2, atom-id-2 3, bond-order single }, { atom-id-1 2, atom-id-2 7, bond-order single }, { atom-id-1 3, atom-id-2 6, bond-order single }, { atom-id-1 3, atom-id-2 13, bond-order single }, { atom-id-1 3, atom-id-2 18, bond-order single }, { atom-id-1 4, atom-id-2 5, bond-order single }, { atom-id-1 4, atom-id-2 14, bond-order single }, { atom-id-1 4, atom-id-2 19, bond-order single }, { atom-id-1 5, atom-id-2 10, bond-order single }, { atom-id-1 5, atom-id-2 15, bond-order single }, { atom-id-1 5, atom-id-2 20, bond-order single }, { atom-id-1 6, atom-id-2 4, bond-order single }, { atom-id-1 6, atom-id-2 16, bond-order single }, { atom-id-1 6, atom-id-2 21, bond-order single }, { atom-id-1 9, atom-id-2 2, bond-order single }, { atom-id-1 10, atom-id-2 17, bond-order single }, { atom-id-1 10, atom-id-2 22, bond-order single }, { atom-id-1 10, atom-id-2 23, bond-order single }, { atom-id-1 12, atom-id-2 8, bond-order single }, { atom-id-1 9, atom-id-2 24, bond-order single } }, chiral-centers { { c 2, n1 9, n2 1, n3 3, sign positive } } }, { id 36, descr { name "LYS NH3+" }, residue-type amino-acid, iupac-code { "K" }, atoms { { id 1, name " C ", iupac-code { " C " }, element c, ionizable-proton false }, { id 2, name " CA ", iupac-code { " CA " }, element c, ionizable-proton false }, { id 3, name " CB ", iupac-code { " CB " }, element c, ionizable-proton false }, { id 4, name " CD ", iupac-code { " CD " }, element c, ionizable-proton false }, { id 5, name " CE ", iupac-code { " CE " }, element c, ionizable-proton false }, { id 6, name " CG ", iupac-code { " CG " }, element c, ionizable-proton false }, { id 7, name " HA ", iupac-code { " HA " }, element h, ionizable-proton false }, { id 8, name " N ", iupac-code { " N " }, element n, ionizable-proton false }, { id 9, name " NZ ", iupac-code { " NZ " }, element n, ionizable-proton false }, { id 10, name " O ", iupac-code { " O " }, element o, ionizable-proton false }, { id 11, name "1H ", iupac-code { "1H " }, element h, ionizable-proton true }, { id 12, name "1HB ", iupac-code { "1HB " }, element h, ionizable-proton false }, { id 13, name "1HD ", iupac-code { "1HD " }, element h, ionizable-proton false }, { id 14, name "1HE ", iupac-code { "1HE " }, element h, ionizable-proton false }, { id 15, name "1HG ", iupac-code { "1HG " }, element h, ionizable-proton false }, { id 16, name "1HZ ", iupac-code { "1HZ " }, element h, ionizable-proton true }, { id 17, name "2H ", iupac-code { "2H " }, element h, ionizable-proton true }, { id 18, name "2HB ", iupac-code { "2HB " }, element h, ionizable-proton false }, { id 19, name "2HD ", iupac-code { "2HD " }, element h, ionizable-proton false }, { id 20, name "2HE ", iupac-code { "2HE " }, element h, ionizable-proton false }, { id 21, name "2HG ", iupac-code { "2HG " }, element h, ionizable-proton false }, { id 22, name "2HZ ", iupac-code { "2HZ " }, element h, ionizable-proton true }, { id 23, name "3H ", iupac-code { "3H " }, element h, ionizable-proton true }, { id 24, name "3HZ ", iupac-code { "3HZ " }, element h, ionizable-proton true } }, bonds { { atom-id-1 1, atom-id-2 10, bond-order partial-double }, { atom-id-1 2, atom-id-2 1, bond-order single }, { atom-id-1 2, atom-id-2 3, bond-order single }, { atom-id-1 2, atom-id-2 7, bond-order single }, { atom-id-1 3, atom-id-2 6, bond-order single }, { atom-id-1 3, atom-id-2 12, bond-order single }, { atom-id-1 3, atom-id-2 18, bond-order single }, { atom-id-1 4, atom-id-2 5, bond-order single }, { atom-id-1 4, atom-id-2 13, bond-order single }, { atom-id-1 4, atom-id-2 19, bond-order single }, { atom-id-1 5, atom-id-2 9, bond-order single }, { atom-id-1 5, atom-id-2 14, bond-order single }, { atom-id-1 5, atom-id-2 20, bond-order single }, { atom-id-1 6, atom-id-2 4, bond-order single }, { atom-id-1 6, atom-id-2 15, bond-order single }, { atom-id-1 6, atom-id-2 21, bond-order single }, { atom-id-1 8, atom-id-2 2, bond-order single }, { atom-id-1 8, atom-id-2 11, bond-order single }, { atom-id-1 8, atom-id-2 17, bond-order single }, { atom-id-1 8, atom-id-2 23, bond-order single }, { atom-id-1 9, atom-id-2 16, bond-order single }, { atom-id-1 9, atom-id-2 22, bond-order single }, { atom-id-1 9, atom-id-2 24, bond-order single } }, chiral-centers { { c 2, n1 8, n2 1, n3 3, sign positive } } }, { id 37, descr { name "MET" }, residue-type amino-acid, iupac-code { "M" }, atoms { { id 1, name " C ", iupac-code { " C " }, element c, ionizable-proton false }, { id 2, name " CA ", iupac-code { " CA " }, element c, ionizable-proton false }, { id 3, name " CB ", iupac-code { " CB " }, element c, ionizable-proton false }, { id 4, name " CE ", iupac-code { " CE " }, element c, ionizable-proton false }, { id 5, name " CG ", iupac-code { " CG " }, element c, ionizable-proton false }, { id 6, name " H ", iupac-code { " H " }, element h, ionizable-proton false }, { id 7, name " HA ", iupac-code { " HA " }, element h, ionizable-proton false }, { id 8, name " N ", iupac-code { " N " }, element n, ionizable-proton false }, { id 9, name " O ", iupac-code { " O " }, element o, ionizable-proton false }, { id 10, name " SD ", iupac-code { " SD " }, element s, ionizable-proton false }, { id 11, name "1HB ", iupac-code { "1HB " }, element h, ionizable-proton false }, { id 12, name "1HE ", iupac-code { "1HE " }, element h, ionizable-proton false }, { id 13, name "1HG ", iupac-code { "1HG " }, element h, ionizable-proton false }, { id 14, name "2HB ", iupac-code { "2HB " }, element h, ionizable-proton false }, { id 15, name "2HE ", iupac-code { "2HE " }, element h, ionizable-proton false }, { id 16, name "2HG ", iupac-code { "2HG " }, element h, ionizable-proton false }, { id 17, name "3HE ", iupac-code { "3HE " }, element h, ionizable-proton false } }, bonds { { atom-id-1 1, atom-id-2 9, bond-order partial-double }, { atom-id-1 2, atom-id-2 1, bond-order single }, { atom-id-1 2, atom-id-2 3, bond-order single }, { atom-id-1 2, atom-id-2 7, bond-order single }, { atom-id-1 3, atom-id-2 5, bond-order single }, { atom-id-1 3, atom-id-2 11, bond-order single }, { atom-id-1 3, atom-id-2 14, bond-order single }, { atom-id-1 4, atom-id-2 12, bond-order single }, { atom-id-1 4, atom-id-2 15, bond-order single }, { atom-id-1 4, atom-id-2 17, bond-order single }, { atom-id-1 5, atom-id-2 10, bond-order single }, { atom-id-1 5, atom-id-2 13, bond-order single }, { atom-id-1 5, atom-id-2 16, bond-order single }, { atom-id-1 8, atom-id-2 2, bond-order single }, { atom-id-1 8, atom-id-2 6, bond-order single }, { atom-id-1 10, atom-id-2 4, bond-order single } }, chiral-centers { { c 2, n1 8, n2 1, n3 3, sign positive } } }, { id 38, descr { name "MET COOH" }, residue-type amino-acid, iupac-code { "M" }, atoms { { id 1, name " C ", iupac-code { " C " }, element c, ionizable-proton false }, { id 2, name " CA ", iupac-code { " CA " }, element c, ionizable-proton false }, { id 3, name " CB ", iupac-code { " CB " }, element c, ionizable-proton false }, { id 4, name " CE ", iupac-code { " CE " }, element c, ionizable-proton false }, { id 5, name " CG ", iupac-code { " CG " }, element c, ionizable-proton false }, { id 6, name " HA ", iupac-code { " HA " }, element h, ionizable-proton false }, { id 7, name " HXT", iupac-code { " HXT" }, element h, ionizable-proton true }, { id 8, name " N ", iupac-code { " N " }, element n, ionizable-proton false }, { id 9, name " O ", iupac-code { " O " }, element o, ionizable-proton false }, { id 10, name " OXT", iupac-code { " OXT" }, element o, ionizable-proton false }, { id 11, name " SD ", iupac-code { " SD " }, element s, ionizable-proton false }, { id 12, name "1HB ", iupac-code { "1HB " }, element h, ionizable-proton false }, { id 13, name "1HE ", iupac-code { "1HE " }, element h, ionizable-proton false }, { id 14, name "1HG ", iupac-code { "1HG " }, element h, ionizable-proton false }, { id 15, name "2HB ", iupac-code { "2HB " }, element h, ionizable-proton false }, { id 16, name "2HE ", iupac-code { "2HE " }, element h, ionizable-proton false }, { id 17, name "2HG ", iupac-code { "2HG " }, element h, ionizable-proton false }, { id 18, name "3HE ", iupac-code { "3HE " }, element h, ionizable-proton false }, { id 19, name " H ", iupac-code { " H " }, element h, ionizable-proton false } }, bonds { { atom-id-1 1, atom-id-2 9, bond-order partial-double }, { atom-id-1 1, atom-id-2 10, bond-order single }, { atom-id-1 2, atom-id-2 1, bond-order single }, { atom-id-1 2, atom-id-2 3, bond-order single }, { atom-id-1 2, atom-id-2 6, bond-order single }, { atom-id-1 3, atom-id-2 5, bond-order single }, { atom-id-1 3, atom-id-2 12, bond-order single }, { atom-id-1 3, atom-id-2 15, bond-order single }, { atom-id-1 4, atom-id-2 13, bond-order single }, { atom-id-1 4, atom-id-2 16, bond-order single }, { atom-id-1 4, atom-id-2 18, bond-order single }, { atom-id-1 5, atom-id-2 11, bond-order single }, { atom-id-1 5, atom-id-2 14, bond-order single }, { atom-id-1 5, atom-id-2 17, bond-order single }, { atom-id-1 8, atom-id-2 2, bond-order single }, { atom-id-1 11, atom-id-2 4, bond-order single }, { atom-id-1 10, atom-id-2 7, bond-order single }, { atom-id-1 8, atom-id-2 19, bond-order single } }, chiral-centers { { c 2, n1 8, n2 1, n3 3, sign positive } } }, { id 39, descr { name "MET NH3+" }, residue-type amino-acid, iupac-code { "M" }, atoms { { id 1, name " C ", iupac-code { " C " }, element c, ionizable-proton false }, { id 2, name " CA ", iupac-code { " CA " }, element c, ionizable-proton false }, { id 3, name " CB ", iupac-code { " CB " }, element c, ionizable-proton false }, { id 4, name " CE ", iupac-code { " CE " }, element c, ionizable-proton false }, { id 5, name " CG ", iupac-code { " CG " }, element c, ionizable-proton false }, { id 6, name " HA ", iupac-code { " HA " }, element h, ionizable-proton false }, { id 7, name " N ", iupac-code { " N " }, element n, ionizable-proton false }, { id 8, name " O ", iupac-code { " O " }, element o, ionizable-proton false }, { id 9, name " SD ", iupac-code { " SD " }, element s, ionizable-proton false }, { id 10, name "1H ", iupac-code { "1H " }, element h, ionizable-proton true }, { id 11, name "1HB ", iupac-code { "1HB " }, element h, ionizable-proton false }, { id 12, name "1HE ", iupac-code { "1HE " }, element h, ionizable-proton false }, { id 13, name "1HG ", iupac-code { "1HG " }, element h, ionizable-proton false }, { id 14, name "2H ", iupac-code { "2H " }, element h, ionizable-proton true }, { id 15, name "2HB ", iupac-code { "2HB " }, element h, ionizable-proton false }, { id 16, name "2HE ", iupac-code { "2HE " }, element h, ionizable-proton false }, { id 17, name "2HG ", iupac-code { "2HG " }, element h, ionizable-proton false }, { id 18, name "3H ", iupac-code { "3H " }, element h, ionizable-proton true }, { id 19, name "3HE ", iupac-code { "3HE " }, element h, ionizable-proton false } }, bonds { { atom-id-1 1, atom-id-2 8, bond-order partial-double }, { atom-id-1 2, atom-id-2 1, bond-order single }, { atom-id-1 2, atom-id-2 3, bond-order single }, { atom-id-1 2, atom-id-2 6, bond-order single }, { atom-id-1 3, atom-id-2 5, bond-order single }, { atom-id-1 3, atom-id-2 11, bond-order single }, { atom-id-1 3, atom-id-2 15, bond-order single }, { atom-id-1 4, atom-id-2 12, bond-order single }, { atom-id-1 4, atom-id-2 16, bond-order single }, { atom-id-1 4, atom-id-2 19, bond-order single }, { atom-id-1 5, atom-id-2 9, bond-order single }, { atom-id-1 5, atom-id-2 13, bond-order single }, { atom-id-1 5, atom-id-2 17, bond-order single }, { atom-id-1 7, atom-id-2 2, bond-order single }, { atom-id-1 7, atom-id-2 10, bond-order single }, { atom-id-1 7, atom-id-2 14, bond-order single }, { atom-id-1 7, atom-id-2 18, bond-order single }, { atom-id-1 9, atom-id-2 4, bond-order single } }, chiral-centers { { c 2, n1 7, n2 1, n3 3, sign positive } } }, { id 40, descr { name "PHE" }, residue-type amino-acid, iupac-code { "F" }, atoms { { id 1, name " C ", iupac-code { " C " }, element c, ionizable-proton false }, { id 2, name " CA ", iupac-code { " CA " }, element c, ionizable-proton false }, { id 3, name " CB ", iupac-code { " CB " }, element c, ionizable-proton false }, { id 4, name " CD1", iupac-code { " CD1" }, element c, ionizable-proton false }, { id 5, name " CD2", iupac-code { " CD2" }, element c, ionizable-proton false }, { id 6, name " CE1", iupac-code { " CE1" }, element c, ionizable-proton false }, { id 7, name " CE2", iupac-code { " CE2" }, element c, ionizable-proton false }, { id 8, name " CG ", iupac-code { " CG " }, element c, ionizable-proton false }, { id 9, name " CZ ", iupac-code { " CZ " }, element c, ionizable-proton false }, { id 10, name " H ", iupac-code { " H " }, element h, ionizable-proton false }, { id 11, name " HA ", iupac-code { " HA " }, element h, ionizable-proton false }, { id 12, name " HD1", iupac-code { " HD1" }, element h, ionizable-proton false }, { id 13, name " HD2", iupac-code { " HD2" }, element h, ionizable-proton false }, { id 14, name " HE1", iupac-code { " HE1" }, element h, ionizable-proton true }, { id 15, name " HE2", iupac-code { " HE2" }, element h, ionizable-proton true }, { id 16, name " HZ ", iupac-code { " HZ " }, element h, ionizable-proton false }, { id 17, name " N ", iupac-code { " N " }, element n, ionizable-proton false }, { id 18, name " O ", iupac-code { " O " }, element o, ionizable-proton false }, { id 19, name "1HB ", iupac-code { "1HB " }, element h, ionizable-proton false }, { id 20, name "2HB ", iupac-code { "2HB " }, element h, ionizable-proton false } }, bonds { { atom-id-1 1, atom-id-2 18, bond-order partial-double }, { atom-id-1 2, atom-id-2 1, bond-order single }, { atom-id-1 2, atom-id-2 3, bond-order single }, { atom-id-1 2, atom-id-2 11, bond-order single }, { atom-id-1 3, atom-id-2 8, bond-order single }, { atom-id-1 3, atom-id-2 19, bond-order single }, { atom-id-1 3, atom-id-2 20, bond-order single }, { atom-id-1 4, atom-id-2 6, bond-order partial-double }, { atom-id-1 4, atom-id-2 12, bond-order single }, { atom-id-1 5, atom-id-2 7, bond-order partial-double }, { atom-id-1 5, atom-id-2 13, bond-order single }, { atom-id-1 6, atom-id-2 9, bond-order partial-double }, { atom-id-1 6, atom-id-2 14, bond-order single }, { atom-id-1 7, atom-id-2 9, bond-order partial-double }, { atom-id-1 7, atom-id-2 15, bond-order single }, { atom-id-1 8, atom-id-2 4, bond-order partial-double }, { atom-id-1 8, atom-id-2 5, bond-order partial-double }, { atom-id-1 9, atom-id-2 16, bond-order single }, { atom-id-1 17, atom-id-2 2, bond-order single }, { atom-id-1 17, atom-id-2 10, bond-order single } }, chiral-centers { { c 2, n1 17, n2 1, n3 3, sign positive } } }, { id 41, descr { name "PHE COOH" }, residue-type amino-acid, iupac-code { "F" }, atoms { { id 1, name " C ", iupac-code { " C " }, element c, ionizable-proton false }, { id 2, name " CA ", iupac-code { " CA " }, element c, ionizable-proton false }, { id 3, name " CB ", iupac-code { " CB " }, element c, ionizable-proton false }, { id 4, name " CD1", iupac-code { " CD1" }, element c, ionizable-proton false }, { id 5, name " CD2", iupac-code { " CD2" }, element c, ionizable-proton false }, { id 6, name " CE1", iupac-code { " CE1" }, element c, ionizable-proton false }, { id 7, name " CE2", iupac-code { " CE2" }, element c, ionizable-proton false }, { id 8, name " CG ", iupac-code { " CG " }, element c, ionizable-proton false }, { id 9, name " CZ ", iupac-code { " CZ " }, element c, ionizable-proton false }, { id 10, name " HA ", iupac-code { " HA " }, element h, ionizable-proton false }, { id 11, name " HD1", iupac-code { " HD1" }, element h, ionizable-proton false }, { id 12, name " HD2", iupac-code { " HD2" }, element h, ionizable-proton false }, { id 13, name " HE1", iupac-code { " HE1" }, element h, ionizable-proton true }, { id 14, name " HE2", iupac-code { " HE2" }, element h, ionizable-proton true }, { id 15, name " HXT", iupac-code { " HXT" }, element h, ionizable-proton true }, { id 16, name " HZ ", iupac-code { " HZ " }, element h, ionizable-proton false }, { id 17, name " N ", iupac-code { " N " }, element n, ionizable-proton false }, { id 18, name " O ", iupac-code { " O " }, element o, ionizable-proton false }, { id 19, name " OXT", iupac-code { " OXT" }, element o, ionizable-proton false }, { id 20, name "1HB ", iupac-code { "1HB " }, element h, ionizable-proton false }, { id 21, name "2HB ", iupac-code { "2HB " }, element h, ionizable-proton false }, { id 22, name " H ", iupac-code { " H " }, element h, ionizable-proton false } }, bonds { { atom-id-1 1, atom-id-2 18, bond-order partial-double }, { atom-id-1 1, atom-id-2 19, bond-order single }, { atom-id-1 2, atom-id-2 1, bond-order single }, { atom-id-1 2, atom-id-2 3, bond-order single }, { atom-id-1 2, atom-id-2 10, bond-order single }, { atom-id-1 3, atom-id-2 8, bond-order single }, { atom-id-1 3, atom-id-2 20, bond-order single }, { atom-id-1 3, atom-id-2 21, bond-order single }, { atom-id-1 4, atom-id-2 6, bond-order partial-double }, { atom-id-1 4, atom-id-2 11, bond-order single }, { atom-id-1 5, atom-id-2 7, bond-order partial-double }, { atom-id-1 5, atom-id-2 12, bond-order single }, { atom-id-1 6, atom-id-2 9, bond-order partial-double }, { atom-id-1 6, atom-id-2 13, bond-order single }, { atom-id-1 7, atom-id-2 9, bond-order partial-double }, { atom-id-1 7, atom-id-2 14, bond-order single }, { atom-id-1 8, atom-id-2 4, bond-order partial-double }, { atom-id-1 8, atom-id-2 5, bond-order partial-double }, { atom-id-1 9, atom-id-2 16, bond-order single }, { atom-id-1 17, atom-id-2 2, bond-order single }, { atom-id-1 19, atom-id-2 15, bond-order single }, { atom-id-1 17, atom-id-2 22, bond-order single } }, chiral-centers { { c 2, n1 17, n2 1, n3 3, sign positive } } }, { id 42, descr { name "PHE NH3+" }, residue-type amino-acid, iupac-code { "F" }, atoms { { id 1, name " C ", iupac-code { " C " }, element c, ionizable-proton false }, { id 2, name " CA ", iupac-code { " CA " }, element c, ionizable-proton false }, { id 3, name " CB ", iupac-code { " CB " }, element c, ionizable-proton false }, { id 4, name " CD1", iupac-code { " CD1" }, element c, ionizable-proton false }, { id 5, name " CD2", iupac-code { " CD2" }, element c, ionizable-proton false }, { id 6, name " CE1", iupac-code { " CE1" }, element c, ionizable-proton false }, { id 7, name " CE2", iupac-code { " CE2" }, element c, ionizable-proton false }, { id 8, name " CG ", iupac-code { " CG " }, element c, ionizable-proton false }, { id 9, name " CZ ", iupac-code { " CZ " }, element c, ionizable-proton false }, { id 10, name " HA ", iupac-code { " HA " }, element h, ionizable-proton false }, { id 11, name " HD1", iupac-code { " HD1" }, element h, ionizable-proton false }, { id 12, name " HD2", iupac-code { " HD2" }, element h, ionizable-proton false }, { id 13, name " HE1", iupac-code { " HE1" }, element h, ionizable-proton true }, { id 14, name " HE2", iupac-code { " HE2" }, element h, ionizable-proton true }, { id 15, name " HZ ", iupac-code { " HZ " }, element h, ionizable-proton false }, { id 16, name " N ", iupac-code { " N " }, element n, ionizable-proton false }, { id 17, name " O ", iupac-code { " O " }, element o, ionizable-proton false }, { id 18, name "1H ", iupac-code { "1H " }, element h, ionizable-proton true }, { id 19, name "1HB ", iupac-code { "1HB " }, element h, ionizable-proton false }, { id 20, name "2H ", iupac-code { "2H " }, element h, ionizable-proton true }, { id 21, name "2HB ", iupac-code { "2HB " }, element h, ionizable-proton false }, { id 22, name "3H ", iupac-code { "3H " }, element h, ionizable-proton true } }, bonds { { atom-id-1 1, atom-id-2 17, bond-order partial-double }, { atom-id-1 2, atom-id-2 1, bond-order single }, { atom-id-1 2, atom-id-2 3, bond-order single }, { atom-id-1 2, atom-id-2 10, bond-order single }, { atom-id-1 3, atom-id-2 8, bond-order single }, { atom-id-1 3, atom-id-2 19, bond-order single }, { atom-id-1 3, atom-id-2 21, bond-order single }, { atom-id-1 4, atom-id-2 6, bond-order partial-double }, { atom-id-1 4, atom-id-2 11, bond-order single }, { atom-id-1 5, atom-id-2 7, bond-order partial-double }, { atom-id-1 5, atom-id-2 12, bond-order single }, { atom-id-1 6, atom-id-2 9, bond-order partial-double }, { atom-id-1 6, atom-id-2 13, bond-order single }, { atom-id-1 7, atom-id-2 9, bond-order partial-double }, { atom-id-1 7, atom-id-2 14, bond-order single }, { atom-id-1 8, atom-id-2 4, bond-order partial-double }, { atom-id-1 8, atom-id-2 5, bond-order partial-double }, { atom-id-1 9, atom-id-2 15, bond-order single }, { atom-id-1 16, atom-id-2 2, bond-order single }, { atom-id-1 16, atom-id-2 18, bond-order single }, { atom-id-1 16, atom-id-2 20, bond-order single }, { atom-id-1 16, atom-id-2 22, bond-order single } }, chiral-centers { { c 2, n1 16, n2 1, n3 3, sign positive } } }, { id 43, descr { name "PRO" }, residue-type amino-acid, iupac-code { "P" }, atoms { { id 1, name " C ", iupac-code { " C " }, element c, ionizable-proton false }, { id 2, name " CA ", iupac-code { " CA " }, element c, ionizable-proton false }, { id 3, name " CB ", iupac-code { " CB " }, element c, ionizable-proton false }, { id 4, name " CD ", iupac-code { " CD " }, element c, ionizable-proton false }, { id 5, name " CG ", iupac-code { " CG " }, element c, ionizable-proton false }, { id 6, name " HA ", iupac-code { " HA " }, element h, ionizable-proton false }, { id 7, name " N ", iupac-code { " N " }, element n, ionizable-proton false }, { id 8, name " O ", iupac-code { " O " }, element o, ionizable-proton false }, { id 9, name "1HB ", iupac-code { "1HB " }, element h, ionizable-proton false }, { id 10, name "1HD ", iupac-code { "1HD " }, element h, ionizable-proton false }, { id 11, name "1HG ", iupac-code { "1HG " }, element h, ionizable-proton false }, { id 12, name "2HB ", iupac-code { "2HB " }, element h, ionizable-proton false }, { id 13, name "2HD ", iupac-code { "2HD " }, element h, ionizable-proton false }, { id 14, name "2HG ", iupac-code { "2HG " }, element h, ionizable-proton false } }, bonds { { atom-id-1 1, atom-id-2 8, bond-order partial-double }, { atom-id-1 2, atom-id-2 1, bond-order single }, { atom-id-1 2, atom-id-2 3, bond-order single }, { atom-id-1 2, atom-id-2 6, bond-order single }, { atom-id-1 3, atom-id-2 5, bond-order single }, { atom-id-1 3, atom-id-2 9, bond-order single }, { atom-id-1 3, atom-id-2 12, bond-order single }, { atom-id-1 4, atom-id-2 10, bond-order single }, { atom-id-1 4, atom-id-2 13, bond-order single }, { atom-id-1 5, atom-id-2 4, bond-order single }, { atom-id-1 5, atom-id-2 11, bond-order single }, { atom-id-1 5, atom-id-2 14, bond-order single }, { atom-id-1 7, atom-id-2 2, bond-order single }, { atom-id-1 7, atom-id-2 4, bond-order single } }, chiral-centers { { c 2, n1 7, n2 1, n3 3, sign positive } } }, { id 44, descr { name "PRO COOH" }, residue-type amino-acid, iupac-code { "P" }, atoms { { id 1, name " C ", iupac-code { " C " }, element c, ionizable-proton false }, { id 2, name " CA ", iupac-code { " CA " }, element c, ionizable-proton false }, { id 3, name " CB ", iupac-code { " CB " }, element c, ionizable-proton false }, { id 4, name " CD ", iupac-code { " CD " }, element c, ionizable-proton false }, { id 5, name " CG ", iupac-code { " CG " }, element c, ionizable-proton false }, { id 6, name " HA ", iupac-code { " HA " }, element h, ionizable-proton false }, { id 7, name " HXT", iupac-code { " HXT" }, element h, ionizable-proton true }, { id 8, name " N ", iupac-code { " N " }, element n, ionizable-proton false }, { id 9, name " O ", iupac-code { " O " }, element o, ionizable-proton false }, { id 10, name " OXT", iupac-code { " OXT" }, element o, ionizable-proton false }, { id 11, name "1HB ", iupac-code { "1HB " }, element h, ionizable-proton false }, { id 12, name "1HD ", iupac-code { "1HD " }, element h, ionizable-proton false }, { id 13, name "1HG ", iupac-code { "1HG " }, element h, ionizable-proton false }, { id 14, name "2HB ", iupac-code { "2HB " }, element h, ionizable-proton false }, { id 15, name "2HD ", iupac-code { "2HD " }, element h, ionizable-proton false }, { id 16, name "2HG ", iupac-code { "2HG " }, element h, ionizable-proton false } }, bonds { { atom-id-1 1, atom-id-2 9, bond-order partial-double }, { atom-id-1 1, atom-id-2 10, bond-order single }, { atom-id-1 2, atom-id-2 1, bond-order single }, { atom-id-1 2, atom-id-2 3, bond-order single }, { atom-id-1 2, atom-id-2 6, bond-order single }, { atom-id-1 3, atom-id-2 5, bond-order single }, { atom-id-1 3, atom-id-2 11, bond-order single }, { atom-id-1 3, atom-id-2 14, bond-order single }, { atom-id-1 4, atom-id-2 12, bond-order single }, { atom-id-1 4, atom-id-2 15, bond-order single }, { atom-id-1 5, atom-id-2 4, bond-order single }, { atom-id-1 5, atom-id-2 13, bond-order single }, { atom-id-1 5, atom-id-2 16, bond-order single }, { atom-id-1 8, atom-id-2 2, bond-order single }, { atom-id-1 8, atom-id-2 4, bond-order single }, { atom-id-1 10, atom-id-2 7, bond-order single } }, chiral-centers { { c 2, n1 8, n2 1, n3 3, sign positive } } }, { id 45, descr { name "PRO NH3+" }, residue-type amino-acid, iupac-code { "P" }, atoms { { id 1, name " C ", iupac-code { " C " }, element c, ionizable-proton false }, { id 2, name " CA ", iupac-code { " CA " }, element c, ionizable-proton false }, { id 3, name " CB ", iupac-code { " CB " }, element c, ionizable-proton false }, { id 4, name " CD ", iupac-code { " CD " }, element c, ionizable-proton false }, { id 5, name " CG ", iupac-code { " CG " }, element c, ionizable-proton false }, { id 6, name " HA ", iupac-code { " HA " }, element h, ionizable-proton false }, { id 7, name " N ", iupac-code { " N " }, element n, ionizable-proton false }, { id 8, name " O ", iupac-code { " O " }, element o, ionizable-proton false }, { id 9, name "1HB ", iupac-code { "1HB " }, element h, ionizable-proton false }, { id 10, name "1HD ", iupac-code { "1HD " }, element h, ionizable-proton false }, { id 11, name "1HG ", iupac-code { "1HG " }, element h, ionizable-proton false }, { id 12, name "2H ", iupac-code { "2H " }, element h, ionizable-proton true }, { id 13, name "2HB ", iupac-code { "2HB " }, element h, ionizable-proton false }, { id 14, name "2HD ", iupac-code { "2HD " }, element h, ionizable-proton false }, { id 15, name "2HG ", iupac-code { "2HG " }, element h, ionizable-proton false }, { id 16, name "3H ", iupac-code { "3H " }, element h, ionizable-proton true } }, bonds { { atom-id-1 1, atom-id-2 8, bond-order partial-double }, { atom-id-1 2, atom-id-2 1, bond-order single }, { atom-id-1 2, atom-id-2 3, bond-order single }, { atom-id-1 2, atom-id-2 6, bond-order single }, { atom-id-1 3, atom-id-2 5, bond-order single }, { atom-id-1 3, atom-id-2 9, bond-order single }, { atom-id-1 3, atom-id-2 13, bond-order single }, { atom-id-1 4, atom-id-2 10, bond-order single }, { atom-id-1 4, atom-id-2 14, bond-order single }, { atom-id-1 5, atom-id-2 4, bond-order single }, { atom-id-1 5, atom-id-2 11, bond-order single }, { atom-id-1 5, atom-id-2 15, bond-order single }, { atom-id-1 7, atom-id-2 2, bond-order single }, { atom-id-1 7, atom-id-2 4, bond-order single }, { atom-id-1 7, atom-id-2 12, bond-order single }, { atom-id-1 7, atom-id-2 16, bond-order single } }, chiral-centers { { c 2, n1 7, n2 1, n3 3, sign positive } } }, { id 46, descr { name "SER" }, residue-type amino-acid, iupac-code { "S" }, atoms { { id 1, name " C ", iupac-code { " C " }, element c, ionizable-proton false }, { id 2, name " CA ", iupac-code { " CA " }, element c, ionizable-proton false }, { id 3, name " CB ", iupac-code { " CB " }, element c, ionizable-proton false }, { id 4, name " H ", iupac-code { " H " }, element h, ionizable-proton false }, { id 5, name " HA ", iupac-code { " HA " }, element h, ionizable-proton false }, { id 6, name " HG ", iupac-code { " HG " }, element h, ionizable-proton true }, { id 7, name " N ", iupac-code { " N " }, element n, ionizable-proton false }, { id 8, name " O ", iupac-code { " O " }, element o, ionizable-proton false }, { id 9, name " OG ", iupac-code { " OG " }, element o, ionizable-proton false }, { id 10, name "1HB ", iupac-code { "1HB " }, element h, ionizable-proton false }, { id 11, name "2HB ", iupac-code { "2HB " }, element h, ionizable-proton false } }, bonds { { atom-id-1 1, atom-id-2 8, bond-order partial-double }, { atom-id-1 2, atom-id-2 1, bond-order single }, { atom-id-1 2, atom-id-2 3, bond-order single }, { atom-id-1 2, atom-id-2 5, bond-order single }, { atom-id-1 3, atom-id-2 9, bond-order single }, { atom-id-1 3, atom-id-2 10, bond-order single }, { atom-id-1 3, atom-id-2 11, bond-order single }, { atom-id-1 7, atom-id-2 2, bond-order single }, { atom-id-1 7, atom-id-2 4, bond-order single }, { atom-id-1 9, atom-id-2 6, bond-order single } }, chiral-centers { { c 2, n1 7, n2 1, n3 3, sign positive } } }, { id 47, descr { name "SER COOH" }, residue-type amino-acid, iupac-code { "S" }, atoms { { id 1, name " C ", iupac-code { " C " }, element c, ionizable-proton false }, { id 2, name " CA ", iupac-code { " CA " }, element c, ionizable-proton false }, { id 3, name " CB ", iupac-code { " CB " }, element c, ionizable-proton false }, { id 4, name " HA ", iupac-code { " HA " }, element h, ionizable-proton false }, { id 5, name " HG ", iupac-code { " HG " }, element h, ionizable-proton true }, { id 6, name " HXT", iupac-code { " HXT" }, element h, ionizable-proton true }, { id 7, name " N ", iupac-code { " N " }, element n, ionizable-proton false }, { id 8, name " O ", iupac-code { " O " }, element o, ionizable-proton false }, { id 9, name " OG ", iupac-code { " OG " }, element o, ionizable-proton false }, { id 10, name " OXT", iupac-code { " OXT" }, element o, ionizable-proton false }, { id 11, name "1HB ", iupac-code { "1HB " }, element h, ionizable-proton false }, { id 12, name "2HB ", iupac-code { "2HB " }, element h, ionizable-proton false }, { id 13, name " H ", iupac-code { " H " }, element h, ionizable-proton false } }, bonds { { atom-id-1 1, atom-id-2 8, bond-order partial-double }, { atom-id-1 1, atom-id-2 10, bond-order single }, { atom-id-1 2, atom-id-2 1, bond-order single }, { atom-id-1 2, atom-id-2 3, bond-order single }, { atom-id-1 2, atom-id-2 4, bond-order single }, { atom-id-1 3, atom-id-2 9, bond-order single }, { atom-id-1 3, atom-id-2 11, bond-order single }, { atom-id-1 3, atom-id-2 12, bond-order single }, { atom-id-1 7, atom-id-2 2, bond-order single }, { atom-id-1 9, atom-id-2 5, bond-order single }, { atom-id-1 10, atom-id-2 6, bond-order single }, { atom-id-1 7, atom-id-2 13, bond-order single } }, chiral-centers { { c 2, n1 7, n2 1, n3 3, sign positive } } }, { id 48, descr { name "SER NH3+" }, residue-type amino-acid, iupac-code { "S" }, atoms { { id 1, name " C ", iupac-code { " C " }, element c, ionizable-proton false }, { id 2, name " CA ", iupac-code { " CA " }, element c, ionizable-proton false }, { id 3, name " CB ", iupac-code { " CB " }, element c, ionizable-proton false }, { id 4, name " HA ", iupac-code { " HA " }, element h, ionizable-proton false }, { id 5, name " HG ", iupac-code { " HG " }, element h, ionizable-proton true }, { id 6, name " N ", iupac-code { " N " }, element n, ionizable-proton false }, { id 7, name " O ", iupac-code { " O " }, element o, ionizable-proton false }, { id 8, name " OG ", iupac-code { " OG " }, element o, ionizable-proton false }, { id 9, name "1H ", iupac-code { "1H " }, element h, ionizable-proton true }, { id 10, name "1HB ", iupac-code { "1HB " }, element h, ionizable-proton false }, { id 11, name "2H ", iupac-code { "2H " }, element h, ionizable-proton true }, { id 12, name "2HB ", iupac-code { "2HB " }, element h, ionizable-proton false }, { id 13, name "3H ", iupac-code { "3H " }, element h, ionizable-proton true } }, bonds { { atom-id-1 1, atom-id-2 7, bond-order partial-double }, { atom-id-1 2, atom-id-2 1, bond-order single }, { atom-id-1 2, atom-id-2 3, bond-order single }, { atom-id-1 2, atom-id-2 4, bond-order single }, { atom-id-1 3, atom-id-2 8, bond-order single }, { atom-id-1 3, atom-id-2 10, bond-order single }, { atom-id-1 3, atom-id-2 12, bond-order single }, { atom-id-1 6, atom-id-2 2, bond-order single }, { atom-id-1 6, atom-id-2 9, bond-order single }, { atom-id-1 6, atom-id-2 11, bond-order single }, { atom-id-1 6, atom-id-2 13, bond-order single }, { atom-id-1 8, atom-id-2 5, bond-order single } }, chiral-centers { { c 2, n1 6, n2 1, n3 3, sign positive } } }, { id 49, descr { name "THR" }, residue-type amino-acid, iupac-code { "T" }, atoms { { id 1, name " C ", iupac-code { " C " }, element c, ionizable-proton false }, { id 2, name " CA ", iupac-code { " CA " }, element c, ionizable-proton false }, { id 3, name " CB ", iupac-code { " CB " }, element c, ionizable-proton false }, { id 4, name " CG2", iupac-code { " CG2" }, element c, ionizable-proton false }, { id 5, name " H ", iupac-code { " H " }, element h, ionizable-proton false }, { id 6, name " HA ", iupac-code { " HA " }, element h, ionizable-proton false }, { id 7, name " HB ", iupac-code { " HB " }, element h, ionizable-proton false }, { id 8, name " HG1", iupac-code { " HG1" }, element h, ionizable-proton false }, { id 9, name " N ", iupac-code { " N " }, element n, ionizable-proton false }, { id 10, name " O ", iupac-code { " O " }, element o, ionizable-proton false }, { id 11, name " OG1", iupac-code { " OG1" }, element o, ionizable-proton false }, { id 12, name "1HG2", iupac-code { "1HG2" }, element h, ionizable-proton false }, { id 13, name "2HG2", iupac-code { "2HG2" }, element h, ionizable-proton false }, { id 14, name "3HG2", iupac-code { "3HG2" }, element h, ionizable-proton false } }, bonds { { atom-id-1 1, atom-id-2 10, bond-order partial-double }, { atom-id-1 2, atom-id-2 1, bond-order single }, { atom-id-1 2, atom-id-2 3, bond-order single }, { atom-id-1 2, atom-id-2 6, bond-order single }, { atom-id-1 3, atom-id-2 4, bond-order single }, { atom-id-1 3, atom-id-2 7, bond-order single }, { atom-id-1 3, atom-id-2 11, bond-order single }, { atom-id-1 4, atom-id-2 12, bond-order single }, { atom-id-1 4, atom-id-2 13, bond-order single }, { atom-id-1 4, atom-id-2 14, bond-order single }, { atom-id-1 9, atom-id-2 2, bond-order single }, { atom-id-1 9, atom-id-2 5, bond-order single }, { atom-id-1 11, atom-id-2 8, bond-order single } }, chiral-centers { { c 2, n1 9, n2 1, n3 3, sign positive }, { c 3, n1 2, n2 11, n3 4, sign positive } } }, { id 50, descr { name "THR COOH" }, residue-type amino-acid, iupac-code { "T" }, atoms { { id 1, name " C ", iupac-code { " C " }, element c, ionizable-proton false }, { id 2, name " CA ", iupac-code { " CA " }, element c, ionizable-proton false }, { id 3, name " CB ", iupac-code { " CB " }, element c, ionizable-proton false }, { id 4, name " CG2", iupac-code { " CG2" }, element c, ionizable-proton false }, { id 5, name " HA ", iupac-code { " HA " }, element h, ionizable-proton false }, { id 6, name " HB ", iupac-code { " HB " }, element h, ionizable-proton false }, { id 7, name " HG1", iupac-code { " HG1" }, element h, ionizable-proton false }, { id 8, name " HXT", iupac-code { " HXT" }, element h, ionizable-proton true }, { id 9, name " N ", iupac-code { " N " }, element n, ionizable-proton false }, { id 10, name " O ", iupac-code { " O " }, element o, ionizable-proton false }, { id 11, name " OG1", iupac-code { " OG1" }, element o, ionizable-proton false }, { id 12, name " OXT", iupac-code { " OXT" }, element o, ionizable-proton false }, { id 13, name "1HG2", iupac-code { "1HG2" }, element h, ionizable-proton false }, { id 14, name "2HG2", iupac-code { "2HG2" }, element h, ionizable-proton false }, { id 15, name "3HG2", iupac-code { "3HG2" }, element h, ionizable-proton false }, { id 16, name " H ", iupac-code { " H " }, element h, ionizable-proton false } }, bonds { { atom-id-1 1, atom-id-2 10, bond-order partial-double }, { atom-id-1 1, atom-id-2 12, bond-order single }, { atom-id-1 2, atom-id-2 1, bond-order single }, { atom-id-1 2, atom-id-2 3, bond-order single }, { atom-id-1 2, atom-id-2 5, bond-order single }, { atom-id-1 3, atom-id-2 4, bond-order single }, { atom-id-1 3, atom-id-2 6, bond-order single }, { atom-id-1 3, atom-id-2 11, bond-order single }, { atom-id-1 4, atom-id-2 13, bond-order single }, { atom-id-1 4, atom-id-2 14, bond-order single }, { atom-id-1 4, atom-id-2 15, bond-order single }, { atom-id-1 9, atom-id-2 2, bond-order single }, { atom-id-1 11, atom-id-2 7, bond-order single }, { atom-id-1 12, atom-id-2 8, bond-order single }, { atom-id-1 9, atom-id-2 16, bond-order single } }, chiral-centers { { c 2, n1 9, n2 1, n3 3, sign positive }, { c 3, n1 2, n2 11, n3 4, sign positive } } }, { id 51, descr { name "THR NH3+" }, residue-type amino-acid, iupac-code { "T" }, atoms { { id 1, name " C ", iupac-code { " C " }, element c, ionizable-proton false }, { id 2, name " CA ", iupac-code { " CA " }, element c, ionizable-proton false }, { id 3, name " CB ", iupac-code { " CB " }, element c, ionizable-proton false }, { id 4, name " CG2", iupac-code { " CG2" }, element c, ionizable-proton false }, { id 5, name " HA ", iupac-code { " HA " }, element h, ionizable-proton false }, { id 6, name " HB ", iupac-code { " HB " }, element h, ionizable-proton false }, { id 7, name " HG1", iupac-code { " HG1" }, element h, ionizable-proton false }, { id 8, name " N ", iupac-code { " N " }, element n, ionizable-proton false }, { id 9, name " O ", iupac-code { " O " }, element o, ionizable-proton false }, { id 10, name " OG1", iupac-code { " OG1" }, element o, ionizable-proton false }, { id 11, name "1H ", iupac-code { "1H " }, element h, ionizable-proton true }, { id 12, name "1HG2", iupac-code { "1HG2" }, element h, ionizable-proton false }, { id 13, name "2H ", iupac-code { "2H " }, element h, ionizable-proton true }, { id 14, name "2HG2", iupac-code { "2HG2" }, element h, ionizable-proton false }, { id 15, name "3H ", iupac-code { "3H " }, element h, ionizable-proton true }, { id 16, name "3HG2", iupac-code { "3HG2" }, element h, ionizable-proton false } }, bonds { { atom-id-1 1, atom-id-2 9, bond-order partial-double }, { atom-id-1 2, atom-id-2 1, bond-order single }, { atom-id-1 2, atom-id-2 3, bond-order single }, { atom-id-1 2, atom-id-2 5, bond-order single }, { atom-id-1 3, atom-id-2 4, bond-order single }, { atom-id-1 3, atom-id-2 6, bond-order single }, { atom-id-1 3, atom-id-2 10, bond-order single }, { atom-id-1 4, atom-id-2 12, bond-order single }, { atom-id-1 4, atom-id-2 14, bond-order single }, { atom-id-1 4, atom-id-2 16, bond-order single }, { atom-id-1 8, atom-id-2 2, bond-order single }, { atom-id-1 8, atom-id-2 11, bond-order single }, { atom-id-1 8, atom-id-2 13, bond-order single }, { atom-id-1 8, atom-id-2 15, bond-order single }, { atom-id-1 10, atom-id-2 7, bond-order single } }, chiral-centers { { c 2, n1 8, n2 1, n3 3, sign positive }, { c 3, n1 2, n2 10, n3 4, sign positive } } }, { id 52, descr { name "TRP" }, residue-type amino-acid, iupac-code { "W" }, atoms { { id 1, name " C ", iupac-code { " C " }, element c, ionizable-proton false }, { id 2, name " CA ", iupac-code { " CA " }, element c, ionizable-proton false }, { id 3, name " CB ", iupac-code { " CB " }, element c, ionizable-proton false }, { id 4, name " CD1", iupac-code { " CD1" }, element c, ionizable-proton false }, { id 5, name " CD2", iupac-code { " CD2" }, element c, ionizable-proton false }, { id 6, name " CE2", iupac-code { " CE2" }, element c, ionizable-proton false }, { id 7, name " CE3", iupac-code { " CE3" }, element c, ionizable-proton false }, { id 8, name " CG ", iupac-code { " CG " }, element c, ionizable-proton false }, { id 9, name " CH2", iupac-code { " CH2" }, element c, ionizable-proton false }, { id 10, name " CZ2", iupac-code { " CZ2" }, element c, ionizable-proton false }, { id 11, name " CZ3", iupac-code { " CZ3" }, element c, ionizable-proton false }, { id 12, name " H ", iupac-code { " H " }, element h, ionizable-proton false }, { id 13, name " HA ", iupac-code { " HA " }, element h, ionizable-proton false }, { id 14, name " HD1", iupac-code { " HD1" }, element h, ionizable-proton false }, { id 15, name " HE1", iupac-code { " HE1" }, element h, ionizable-proton true }, { id 16, name " HE3", iupac-code { " HE3" }, element h, ionizable-proton false }, { id 17, name " HH2", iupac-code { " HH2" }, element h, ionizable-proton false }, { id 18, name " HZ2", iupac-code { " HZ2" }, element h, ionizable-proton false }, { id 19, name " HZ3", iupac-code { " HZ3" }, element h, ionizable-proton false }, { id 20, name " N ", iupac-code { " N " }, element n, ionizable-proton false }, { id 21, name " NE1", iupac-code { " NE1" }, element n, ionizable-proton false }, { id 22, name " O ", iupac-code { " O " }, element o, ionizable-proton false }, { id 23, name "1HB ", iupac-code { "1HB " }, element h, ionizable-proton false }, { id 24, name "2HB ", iupac-code { "2HB " }, element h, ionizable-proton false } }, bonds { { atom-id-1 1, atom-id-2 22, bond-order partial-double }, { atom-id-1 2, atom-id-2 1, bond-order single }, { atom-id-1 2, atom-id-2 3, bond-order single }, { atom-id-1 2, atom-id-2 13, bond-order single }, { atom-id-1 3, atom-id-2 8, bond-order single }, { atom-id-1 3, atom-id-2 23, bond-order single }, { atom-id-1 3, atom-id-2 24, bond-order single }, { atom-id-1 4, atom-id-2 14, bond-order single }, { atom-id-1 4, atom-id-2 21, bond-order single }, { atom-id-1 5, atom-id-2 6, bond-order partial-double }, { atom-id-1 5, atom-id-2 7, bond-order partial-double }, { atom-id-1 6, atom-id-2 10, bond-order partial-double }, { atom-id-1 7, atom-id-2 11, bond-order partial-double }, { atom-id-1 7, atom-id-2 16, bond-order single }, { atom-id-1 8, atom-id-2 4, bond-order double }, { atom-id-1 8, atom-id-2 5, bond-order single }, { atom-id-1 9, atom-id-2 17, bond-order single }, { atom-id-1 10, atom-id-2 9, bond-order partial-double }, { atom-id-1 10, atom-id-2 18, bond-order single }, { atom-id-1 11, atom-id-2 9, bond-order partial-double }, { atom-id-1 11, atom-id-2 19, bond-order single }, { atom-id-1 20, atom-id-2 2, bond-order single }, { atom-id-1 20, atom-id-2 12, bond-order single }, { atom-id-1 21, atom-id-2 6, bond-order single }, { atom-id-1 21, atom-id-2 15, bond-order single } }, chiral-centers { { c 2, n1 20, n2 1, n3 3, sign positive } } }, { id 53, descr { name "TRP COOH" }, residue-type amino-acid, iupac-code { "W" }, atoms { { id 1, name " C ", iupac-code { " C " }, element c, ionizable-proton false }, { id 2, name " CA ", iupac-code { " CA " }, element c, ionizable-proton false }, { id 3, name " CB ", iupac-code { " CB " }, element c, ionizable-proton false }, { id 4, name " CD1", iupac-code { " CD1" }, element c, ionizable-proton false }, { id 5, name " CD2", iupac-code { " CD2" }, element c, ionizable-proton false }, { id 6, name " CE2", iupac-code { " CE2" }, element c, ionizable-proton false }, { id 7, name " CE3", iupac-code { " CE3" }, element c, ionizable-proton false }, { id 8, name " CG ", iupac-code { " CG " }, element c, ionizable-proton false }, { id 9, name " CH2", iupac-code { " CH2" }, element c, ionizable-proton false }, { id 10, name " CZ2", iupac-code { " CZ2" }, element c, ionizable-proton false }, { id 11, name " CZ3", iupac-code { " CZ3" }, element c, ionizable-proton false }, { id 12, name " HA ", iupac-code { " HA " }, element h, ionizable-proton false }, { id 13, name " HD1", iupac-code { " HD1" }, element h, ionizable-proton false }, { id 14, name " HE1", iupac-code { " HE1" }, element h, ionizable-proton true }, { id 15, name " HE3", iupac-code { " HE3" }, element h, ionizable-proton false }, { id 16, name " HH2", iupac-code { " HH2" }, element h, ionizable-proton false }, { id 17, name " HXT", iupac-code { " HXT" }, element h, ionizable-proton true }, { id 18, name " HZ2", iupac-code { " HZ2" }, element h, ionizable-proton false }, { id 19, name " HZ3", iupac-code { " HZ3" }, element h, ionizable-proton false }, { id 20, name " N ", iupac-code { " N " }, element n, ionizable-proton false }, { id 21, name " NE1", iupac-code { " NE1" }, element n, ionizable-proton false }, { id 22, name " O ", iupac-code { " O " }, element o, ionizable-proton false }, { id 23, name " OXT", iupac-code { " OXT" }, element o, ionizable-proton false }, { id 24, name "1HB ", iupac-code { "1HB " }, element h, ionizable-proton false }, { id 25, name "2HB ", iupac-code { "2HB " }, element h, ionizable-proton false }, { id 26, name " H ", iupac-code { " H " }, element h, ionizable-proton false } }, bonds { { atom-id-1 1, atom-id-2 22, bond-order partial-double }, { atom-id-1 1, atom-id-2 23, bond-order single }, { atom-id-1 2, atom-id-2 1, bond-order single }, { atom-id-1 2, atom-id-2 3, bond-order single }, { atom-id-1 2, atom-id-2 12, bond-order single }, { atom-id-1 3, atom-id-2 8, bond-order single }, { atom-id-1 3, atom-id-2 24, bond-order single }, { atom-id-1 3, atom-id-2 25, bond-order single }, { atom-id-1 4, atom-id-2 13, bond-order single }, { atom-id-1 4, atom-id-2 21, bond-order single }, { atom-id-1 5, atom-id-2 6, bond-order partial-double }, { atom-id-1 5, atom-id-2 7, bond-order partial-double }, { atom-id-1 6, atom-id-2 10, bond-order partial-double }, { atom-id-1 7, atom-id-2 11, bond-order partial-double }, { atom-id-1 7, atom-id-2 15, bond-order single }, { atom-id-1 8, atom-id-2 4, bond-order double }, { atom-id-1 8, atom-id-2 5, bond-order single }, { atom-id-1 9, atom-id-2 16, bond-order single }, { atom-id-1 10, atom-id-2 9, bond-order partial-double }, { atom-id-1 10, atom-id-2 18, bond-order single }, { atom-id-1 11, atom-id-2 9, bond-order partial-double }, { atom-id-1 11, atom-id-2 19, bond-order single }, { atom-id-1 20, atom-id-2 2, bond-order single }, { atom-id-1 21, atom-id-2 6, bond-order single }, { atom-id-1 21, atom-id-2 14, bond-order single }, { atom-id-1 23, atom-id-2 17, bond-order single }, { atom-id-1 20, atom-id-2 26, bond-order single } }, chiral-centers { { c 2, n1 20, n2 1, n3 3, sign positive } } }, { id 54, descr { name "TRP NH3+" }, residue-type amino-acid, iupac-code { "W" }, atoms { { id 1, name " C ", iupac-code { " C " }, element c, ionizable-proton false }, { id 2, name " CA ", iupac-code { " CA " }, element c, ionizable-proton false }, { id 3, name " CB ", iupac-code { " CB " }, element c, ionizable-proton false }, { id 4, name " CD1", iupac-code { " CD1" }, element c, ionizable-proton false }, { id 5, name " CD2", iupac-code { " CD2" }, element c, ionizable-proton false }, { id 6, name " CE2", iupac-code { " CE2" }, element c, ionizable-proton false }, { id 7, name " CE3", iupac-code { " CE3" }, element c, ionizable-proton false }, { id 8, name " CG ", iupac-code { " CG " }, element c, ionizable-proton false }, { id 9, name " CH2", iupac-code { " CH2" }, element c, ionizable-proton false }, { id 10, name " CZ2", iupac-code { " CZ2" }, element c, ionizable-proton false }, { id 11, name " CZ3", iupac-code { " CZ3" }, element c, ionizable-proton false }, { id 12, name " HA ", iupac-code { " HA " }, element h, ionizable-proton false }, { id 13, name " HD1", iupac-code { " HD1" }, element h, ionizable-proton false }, { id 14, name " HE1", iupac-code { " HE1" }, element h, ionizable-proton true }, { id 15, name " HE3", iupac-code { " HE3" }, element h, ionizable-proton false }, { id 16, name " HH2", iupac-code { " HH2" }, element h, ionizable-proton false }, { id 17, name " HZ2", iupac-code { " HZ2" }, element h, ionizable-proton false }, { id 18, name " HZ3", iupac-code { " HZ3" }, element h, ionizable-proton false }, { id 19, name " N ", iupac-code { " N " }, element n, ionizable-proton false }, { id 20, name " NE1", iupac-code { " NE1" }, element n, ionizable-proton false }, { id 21, name " O ", iupac-code { " O " }, element o, ionizable-proton false }, { id 22, name "1H ", iupac-code { "1H " }, element h, ionizable-proton true }, { id 23, name "1HB ", iupac-code { "1HB " }, element h, ionizable-proton false }, { id 24, name "2H ", iupac-code { "2H " }, element h, ionizable-proton true }, { id 25, name "2HB ", iupac-code { "2HB " }, element h, ionizable-proton false }, { id 26, name "3H ", iupac-code { "3H " }, element h, ionizable-proton true } }, bonds { { atom-id-1 1, atom-id-2 21, bond-order partial-double }, { atom-id-1 2, atom-id-2 1, bond-order single }, { atom-id-1 2, atom-id-2 3, bond-order single }, { atom-id-1 2, atom-id-2 12, bond-order single }, { atom-id-1 3, atom-id-2 8, bond-order single }, { atom-id-1 3, atom-id-2 23, bond-order single }, { atom-id-1 3, atom-id-2 25, bond-order single }, { atom-id-1 4, atom-id-2 13, bond-order single }, { atom-id-1 4, atom-id-2 20, bond-order single }, { atom-id-1 5, atom-id-2 6, bond-order partial-double }, { atom-id-1 5, atom-id-2 7, bond-order partial-double }, { atom-id-1 6, atom-id-2 10, bond-order partial-double }, { atom-id-1 7, atom-id-2 11, bond-order partial-double }, { atom-id-1 7, atom-id-2 15, bond-order single }, { atom-id-1 8, atom-id-2 4, bond-order double }, { atom-id-1 8, atom-id-2 5, bond-order single }, { atom-id-1 9, atom-id-2 16, bond-order single }, { atom-id-1 10, atom-id-2 9, bond-order partial-double }, { atom-id-1 10, atom-id-2 17, bond-order single }, { atom-id-1 11, atom-id-2 9, bond-order partial-double }, { atom-id-1 11, atom-id-2 18, bond-order single }, { atom-id-1 19, atom-id-2 2, bond-order single }, { atom-id-1 19, atom-id-2 22, bond-order single }, { atom-id-1 19, atom-id-2 24, bond-order single }, { atom-id-1 19, atom-id-2 26, bond-order single }, { atom-id-1 20, atom-id-2 6, bond-order single }, { atom-id-1 20, atom-id-2 14, bond-order single } }, chiral-centers { { c 2, n1 19, n2 1, n3 3, sign positive } } }, { id 55, descr { name "TYR" }, residue-type amino-acid, iupac-code { "Y" }, atoms { { id 1, name " C ", iupac-code { " C " }, element c, ionizable-proton false }, { id 2, name " CA ", iupac-code { " CA " }, element c, ionizable-proton false }, { id 3, name " CB ", iupac-code { " CB " }, element c, ionizable-proton false }, { id 4, name " CD1", iupac-code { " CD1" }, element c, ionizable-proton false }, { id 5, name " CD2", iupac-code { " CD2" }, element c, ionizable-proton false }, { id 6, name " CE1", iupac-code { " CE1" }, element c, ionizable-proton false }, { id 7, name " CE2", iupac-code { " CE2" }, element c, ionizable-proton false }, { id 8, name " CG ", iupac-code { " CG " }, element c, ionizable-proton false }, { id 9, name " CZ ", iupac-code { " CZ " }, element c, ionizable-proton false }, { id 10, name " H ", iupac-code { " H " }, element h, ionizable-proton false }, { id 11, name " HA ", iupac-code { " HA " }, element h, ionizable-proton false }, { id 12, name " HD1", iupac-code { " HD1" }, element h, ionizable-proton false }, { id 13, name " HD2", iupac-code { " HD2" }, element h, ionizable-proton false }, { id 14, name " HE1", iupac-code { " HE1" }, element h, ionizable-proton true }, { id 15, name " HE2", iupac-code { " HE2" }, element h, ionizable-proton true }, { id 16, name " HH ", iupac-code { " HH " }, element h, ionizable-proton false }, { id 17, name " N ", iupac-code { " N " }, element n, ionizable-proton false }, { id 18, name " O ", iupac-code { " O " }, element o, ionizable-proton false }, { id 19, name " OH ", iupac-code { " OH " }, element o, ionizable-proton false }, { id 20, name "1HB ", iupac-code { "1HB " }, element h, ionizable-proton false }, { id 21, name "2HB ", iupac-code { "2HB " }, element h, ionizable-proton false } }, bonds { { atom-id-1 1, atom-id-2 18, bond-order partial-double }, { atom-id-1 2, atom-id-2 1, bond-order single }, { atom-id-1 2, atom-id-2 3, bond-order single }, { atom-id-1 2, atom-id-2 11, bond-order single }, { atom-id-1 3, atom-id-2 8, bond-order single }, { atom-id-1 3, atom-id-2 20, bond-order single }, { atom-id-1 3, atom-id-2 21, bond-order single }, { atom-id-1 4, atom-id-2 6, bond-order partial-double }, { atom-id-1 4, atom-id-2 12, bond-order single }, { atom-id-1 5, atom-id-2 7, bond-order partial-double }, { atom-id-1 5, atom-id-2 13, bond-order single }, { atom-id-1 6, atom-id-2 9, bond-order partial-double }, { atom-id-1 6, atom-id-2 14, bond-order single }, { atom-id-1 7, atom-id-2 9, bond-order partial-double }, { atom-id-1 7, atom-id-2 15, bond-order single }, { atom-id-1 8, atom-id-2 4, bond-order partial-double }, { atom-id-1 8, atom-id-2 5, bond-order partial-double }, { atom-id-1 9, atom-id-2 19, bond-order single }, { atom-id-1 17, atom-id-2 2, bond-order single }, { atom-id-1 17, atom-id-2 10, bond-order single }, { atom-id-1 19, atom-id-2 16, bond-order single } }, chiral-centers { { c 2, n1 17, n2 1, n3 3, sign positive } } }, { id 56, descr { name "TYR COOH" }, residue-type amino-acid, iupac-code { "Y" }, atoms { { id 1, name " C ", iupac-code { " C " }, element c, ionizable-proton false }, { id 2, name " CA ", iupac-code { " CA " }, element c, ionizable-proton false }, { id 3, name " CB ", iupac-code { " CB " }, element c, ionizable-proton false }, { id 4, name " CD1", iupac-code { " CD1" }, element c, ionizable-proton false }, { id 5, name " CD2", iupac-code { " CD2" }, element c, ionizable-proton false }, { id 6, name " CE1", iupac-code { " CE1" }, element c, ionizable-proton false }, { id 7, name " CE2", iupac-code { " CE2" }, element c, ionizable-proton false }, { id 8, name " CG ", iupac-code { " CG " }, element c, ionizable-proton false }, { id 9, name " CZ ", iupac-code { " CZ " }, element c, ionizable-proton false }, { id 10, name " HA ", iupac-code { " HA " }, element h, ionizable-proton false }, { id 11, name " HD1", iupac-code { " HD1" }, element h, ionizable-proton false }, { id 12, name " HD2", iupac-code { " HD2" }, element h, ionizable-proton false }, { id 13, name " HE1", iupac-code { " HE1" }, element h, ionizable-proton true }, { id 14, name " HE2", iupac-code { " HE2" }, element h, ionizable-proton true }, { id 15, name " HH ", iupac-code { " HH " }, element h, ionizable-proton false }, { id 16, name " HXT", iupac-code { " HXT" }, element h, ionizable-proton true }, { id 17, name " N ", iupac-code { " N " }, element n, ionizable-proton false }, { id 18, name " O ", iupac-code { " O " }, element o, ionizable-proton false }, { id 19, name " OH ", iupac-code { " OH " }, element o, ionizable-proton false }, { id 20, name " OXT", iupac-code { " OXT" }, element o, ionizable-proton false }, { id 21, name "1HB ", iupac-code { "1HB " }, element h, ionizable-proton false }, { id 22, name "2HB ", iupac-code { "2HB " }, element h, ionizable-proton false }, { id 23, name " H ", iupac-code { " H " }, element h, ionizable-proton false } }, bonds { { atom-id-1 1, atom-id-2 18, bond-order partial-double }, { atom-id-1 1, atom-id-2 20, bond-order single }, { atom-id-1 2, atom-id-2 1, bond-order single }, { atom-id-1 2, atom-id-2 3, bond-order single }, { atom-id-1 2, atom-id-2 10, bond-order single }, { atom-id-1 3, atom-id-2 8, bond-order single }, { atom-id-1 3, atom-id-2 21, bond-order single }, { atom-id-1 3, atom-id-2 22, bond-order single }, { atom-id-1 4, atom-id-2 6, bond-order partial-double }, { atom-id-1 4, atom-id-2 11, bond-order single }, { atom-id-1 5, atom-id-2 7, bond-order partial-double }, { atom-id-1 5, atom-id-2 12, bond-order single }, { atom-id-1 6, atom-id-2 9, bond-order partial-double }, { atom-id-1 6, atom-id-2 13, bond-order single }, { atom-id-1 7, atom-id-2 9, bond-order partial-double }, { atom-id-1 7, atom-id-2 14, bond-order single }, { atom-id-1 8, atom-id-2 4, bond-order partial-double }, { atom-id-1 8, atom-id-2 5, bond-order partial-double }, { atom-id-1 9, atom-id-2 19, bond-order single }, { atom-id-1 17, atom-id-2 2, bond-order single }, { atom-id-1 19, atom-id-2 15, bond-order single }, { atom-id-1 20, atom-id-2 16, bond-order single }, { atom-id-1 17, atom-id-2 23, bond-order single } }, chiral-centers { { c 2, n1 17, n2 1, n3 3, sign positive } } }, { id 57, descr { name "TYR NH3+" }, residue-type amino-acid, iupac-code { "Y" }, atoms { { id 1, name " C ", iupac-code { " C " }, element c, ionizable-proton false }, { id 2, name " CA ", iupac-code { " CA " }, element c, ionizable-proton false }, { id 3, name " CB ", iupac-code { " CB " }, element c, ionizable-proton false }, { id 4, name " CD1", iupac-code { " CD1" }, element c, ionizable-proton false }, { id 5, name " CD2", iupac-code { " CD2" }, element c, ionizable-proton false }, { id 6, name " CE1", iupac-code { " CE1" }, element c, ionizable-proton false }, { id 7, name " CE2", iupac-code { " CE2" }, element c, ionizable-proton false }, { id 8, name " CG ", iupac-code { " CG " }, element c, ionizable-proton false }, { id 9, name " CZ ", iupac-code { " CZ " }, element c, ionizable-proton false }, { id 10, name " HA ", iupac-code { " HA " }, element h, ionizable-proton false }, { id 11, name " HD1", iupac-code { " HD1" }, element h, ionizable-proton false }, { id 12, name " HD2", iupac-code { " HD2" }, element h, ionizable-proton false }, { id 13, name " HE1", iupac-code { " HE1" }, element h, ionizable-proton true }, { id 14, name " HE2", iupac-code { " HE2" }, element h, ionizable-proton true }, { id 15, name " HH ", iupac-code { " HH " }, element h, ionizable-proton false }, { id 16, name " N ", iupac-code { " N " }, element n, ionizable-proton false }, { id 17, name " O ", iupac-code { " O " }, element o, ionizable-proton false }, { id 18, name " OH ", iupac-code { " OH " }, element o, ionizable-proton false }, { id 19, name "1H ", iupac-code { "1H " }, element h, ionizable-proton true }, { id 20, name "1HB ", iupac-code { "1HB " }, element h, ionizable-proton false }, { id 21, name "2H ", iupac-code { "2H " }, element h, ionizable-proton true }, { id 22, name "2HB ", iupac-code { "2HB " }, element h, ionizable-proton false }, { id 23, name "3H ", iupac-code { "3H " }, element h, ionizable-proton true } }, bonds { { atom-id-1 1, atom-id-2 17, bond-order partial-double }, { atom-id-1 2, atom-id-2 1, bond-order single }, { atom-id-1 2, atom-id-2 3, bond-order single }, { atom-id-1 2, atom-id-2 10, bond-order single }, { atom-id-1 3, atom-id-2 8, bond-order single }, { atom-id-1 3, atom-id-2 20, bond-order single }, { atom-id-1 3, atom-id-2 22, bond-order single }, { atom-id-1 4, atom-id-2 6, bond-order partial-double }, { atom-id-1 4, atom-id-2 11, bond-order single }, { atom-id-1 5, atom-id-2 7, bond-order partial-double }, { atom-id-1 5, atom-id-2 12, bond-order single }, { atom-id-1 6, atom-id-2 9, bond-order partial-double }, { atom-id-1 6, atom-id-2 13, bond-order single }, { atom-id-1 7, atom-id-2 9, bond-order partial-double }, { atom-id-1 7, atom-id-2 14, bond-order single }, { atom-id-1 8, atom-id-2 4, bond-order partial-double }, { atom-id-1 8, atom-id-2 5, bond-order partial-double }, { atom-id-1 9, atom-id-2 18, bond-order single }, { atom-id-1 16, atom-id-2 2, bond-order single }, { atom-id-1 18, atom-id-2 15, bond-order single }, { atom-id-1 19, atom-id-2 16, bond-order single }, { atom-id-1 21, atom-id-2 16, bond-order single }, { atom-id-1 23, atom-id-2 16, bond-order single } }, chiral-centers { { c 2, n1 16, n2 1, n3 3, sign positive } } }, { id 58, descr { name "VAL" }, residue-type amino-acid, iupac-code { "V" }, atoms { { id 1, name " C ", iupac-code { " C " }, element c, ionizable-proton false }, { id 2, name " CA ", iupac-code { " CA " }, element c, ionizable-proton false }, { id 3, name " CB ", iupac-code { " CB " }, element c, ionizable-proton false }, { id 4, name " CG1", iupac-code { " CG1" }, element c, ionizable-proton false }, { id 5, name " CG2", iupac-code { " CG2" }, element c, ionizable-proton false }, { id 6, name " H ", iupac-code { " H " }, element h, ionizable-proton false }, { id 7, name " HA ", iupac-code { " HA " }, element h, ionizable-proton false }, { id 8, name " HB ", iupac-code { " HB " }, element h, ionizable-proton false }, { id 9, name " N ", iupac-code { " N " }, element n, ionizable-proton false }, { id 10, name " O ", iupac-code { " O " }, element o, ionizable-proton false }, { id 11, name "1HG1", iupac-code { "1HG1" }, element h, ionizable-proton false }, { id 12, name "1HG2", iupac-code { "1HG2" }, element h, ionizable-proton false }, { id 13, name "2HG1", iupac-code { "2HG1" }, element h, ionizable-proton false }, { id 14, name "2HG2", iupac-code { "2HG2" }, element h, ionizable-proton false }, { id 15, name "3HG1", iupac-code { "3HG1" }, element h, ionizable-proton false }, { id 16, name "3HG2", iupac-code { "3HG2" }, element h, ionizable-proton false } }, bonds { { atom-id-1 1, atom-id-2 10, bond-order partial-double }, { atom-id-1 2, atom-id-2 1, bond-order single }, { atom-id-1 2, atom-id-2 3, bond-order single }, { atom-id-1 2, atom-id-2 7, bond-order single }, { atom-id-1 3, atom-id-2 4, bond-order single }, { atom-id-1 3, atom-id-2 5, bond-order single }, { atom-id-1 3, atom-id-2 8, bond-order single }, { atom-id-1 4, atom-id-2 11, bond-order single }, { atom-id-1 4, atom-id-2 13, bond-order single }, { atom-id-1 4, atom-id-2 15, bond-order single }, { atom-id-1 5, atom-id-2 12, bond-order single }, { atom-id-1 5, atom-id-2 14, bond-order single }, { atom-id-1 5, atom-id-2 16, bond-order single }, { atom-id-1 9, atom-id-2 2, bond-order single }, { atom-id-1 9, atom-id-2 6, bond-order single } }, chiral-centers { { c 2, n1 9, n2 1, n3 3, sign positive } } }, { id 59, descr { name "VAL COOH" }, residue-type amino-acid, iupac-code { "V" }, atoms { { id 1, name " C ", iupac-code { " C " }, element c, ionizable-proton false }, { id 2, name " CA ", iupac-code { " CA " }, element c, ionizable-proton false }, { id 3, name " CB ", iupac-code { " CB " }, element c, ionizable-proton false }, { id 4, name " CG1", iupac-code { " CG1" }, element c, ionizable-proton false }, { id 5, name " CG2", iupac-code { " CG2" }, element c, ionizable-proton false }, { id 6, name " HA ", iupac-code { " HA " }, element h, ionizable-proton false }, { id 7, name " HB ", iupac-code { " HB " }, element h, ionizable-proton false }, { id 8, name " HXT", iupac-code { " HXT" }, element h, ionizable-proton true }, { id 9, name " N ", iupac-code { " N " }, element n, ionizable-proton false }, { id 10, name " O ", iupac-code { " O " }, element o, ionizable-proton false }, { id 11, name " OXT", iupac-code { " OXT" }, element o, ionizable-proton false }, { id 12, name "1HG1", iupac-code { "1HG1" }, element h, ionizable-proton false }, { id 13, name "1HG2", iupac-code { "1HG2" }, element h, ionizable-proton false }, { id 14, name "2HG1", iupac-code { "2HG1" }, element h, ionizable-proton false }, { id 15, name "2HG2", iupac-code { "2HG2" }, element h, ionizable-proton false }, { id 16, name "3HG1", iupac-code { "3HG1" }, element h, ionizable-proton false }, { id 17, name "3HG2", iupac-code { "3HG2" }, element h, ionizable-proton false }, { id 18, name " H ", iupac-code { " H " }, element h, ionizable-proton false } }, bonds { { atom-id-1 1, atom-id-2 10, bond-order partial-double }, { atom-id-1 1, atom-id-2 11, bond-order single }, { atom-id-1 2, atom-id-2 1, bond-order single }, { atom-id-1 2, atom-id-2 3, bond-order single }, { atom-id-1 2, atom-id-2 6, bond-order single }, { atom-id-1 3, atom-id-2 4, bond-order single }, { atom-id-1 3, atom-id-2 5, bond-order single }, { atom-id-1 3, atom-id-2 7, bond-order single }, { atom-id-1 4, atom-id-2 12, bond-order single }, { atom-id-1 4, atom-id-2 14, bond-order single }, { atom-id-1 4, atom-id-2 16, bond-order single }, { atom-id-1 5, atom-id-2 13, bond-order single }, { atom-id-1 5, atom-id-2 15, bond-order single }, { atom-id-1 5, atom-id-2 17, bond-order single }, { atom-id-1 9, atom-id-2 2, bond-order single }, { atom-id-1 11, atom-id-2 8, bond-order single }, { atom-id-1 9, atom-id-2 18, bond-order single } }, chiral-centers { { c 2, n1 9, n2 1, n3 3, sign positive } } }, { id 60, descr { name "VAL NH3+" }, residue-type amino-acid, iupac-code { "V" }, atoms { { id 1, name " C ", iupac-code { " C " }, element c, ionizable-proton false }, { id 2, name " CA ", iupac-code { " CA " }, element c, ionizable-proton false }, { id 3, name " CB ", iupac-code { " CB " }, element c, ionizable-proton false }, { id 4, name " CG1", iupac-code { " CG1" }, element c, ionizable-proton false }, { id 5, name " CG2", iupac-code { " CG2" }, element c, ionizable-proton false }, { id 6, name " HA ", iupac-code { " HA " }, element h, ionizable-proton false }, { id 7, name " HB ", iupac-code { " HB " }, element h, ionizable-proton false }, { id 8, name " N ", iupac-code { " N " }, element n, ionizable-proton false }, { id 9, name " O ", iupac-code { " O " }, element o, ionizable-proton false }, { id 10, name "1H ", iupac-code { "1H " }, element h, ionizable-proton true }, { id 11, name "1HG1", iupac-code { "1HG1" }, element h, ionizable-proton false }, { id 12, name "1HG2", iupac-code { "1HG2" }, element h, ionizable-proton false }, { id 13, name "2H ", iupac-code { "2H " }, element h, ionizable-proton true }, { id 14, name "2HG1", iupac-code { "2HG1" }, element h, ionizable-proton false }, { id 15, name "2HG2", iupac-code { "2HG2" }, element h, ionizable-proton false }, { id 16, name "3H ", iupac-code { "3H " }, element h, ionizable-proton true }, { id 17, name "3HG1", iupac-code { "3HG1" }, element h, ionizable-proton false }, { id 18, name "3HG2", iupac-code { "3HG2" }, element h, ionizable-proton false } }, bonds { { atom-id-1 1, atom-id-2 9, bond-order partial-double }, { atom-id-1 2, atom-id-2 1, bond-order single }, { atom-id-1 2, atom-id-2 3, bond-order single }, { atom-id-1 2, atom-id-2 6, bond-order single }, { atom-id-1 3, atom-id-2 4, bond-order single }, { atom-id-1 3, atom-id-2 5, bond-order single }, { atom-id-1 3, atom-id-2 7, bond-order single }, { atom-id-1 4, atom-id-2 11, bond-order single }, { atom-id-1 4, atom-id-2 14, bond-order single }, { atom-id-1 4, atom-id-2 17, bond-order single }, { atom-id-1 5, atom-id-2 12, bond-order single }, { atom-id-1 5, atom-id-2 15, bond-order single }, { atom-id-1 5, atom-id-2 18, bond-order single }, { atom-id-1 8, atom-id-2 2, bond-order single }, { atom-id-1 8, atom-id-2 10, bond-order single }, { atom-id-1 8, atom-id-2 13, bond-order single }, { atom-id-1 8, atom-id-2 16, bond-order single } }, chiral-centers { { c 2, n1 8, n2 1, n3 3, sign positive } } }, { id 61, descr { name " A DNA" }, residue-type deoxyribonucleotide, iupac-code { "A" }, atoms { { id 1, name " P ", iupac-code { " P " }, element p, ionizable-proton false }, { id 2, name " O1P", iupac-code { " O1P" }, element o, ionizable-proton false }, { id 3, name " O2P", iupac-code { " O2P" }, element o, ionizable-proton false }, { id 4, name " O5*", iupac-code { " O5*" }, element o, ionizable-proton false }, { id 5, name " C5*", iupac-code { " C5*" }, element c, ionizable-proton false }, { id 6, name " C4*", iupac-code { " C4*" }, element c, ionizable-proton false }, { id 7, name " O4*", iupac-code { " O4*" }, element o, ionizable-proton false }, { id 8, name " C3*", iupac-code { " C3*" }, element c, ionizable-proton false }, { id 9, name " O3*", iupac-code { " O3*" }, element o, ionizable-proton false }, { id 10, name " C2*", iupac-code { " C2*" }, element c, ionizable-proton false }, { id 11, name " C1*", iupac-code { " C1*" }, element c, ionizable-proton false }, { id 12, name " N9 ", iupac-code { " N9 " }, element n, ionizable-proton false }, { id 13, name " C8 ", iupac-code { " C8 " }, element c, ionizable-proton false }, { id 14, name " N7 ", iupac-code { " N7 " }, element n, ionizable-proton false }, { id 15, name " C5 ", iupac-code { " C5 " }, element c, ionizable-proton false }, { id 16, name " C6 ", iupac-code { " C6 " }, element c, ionizable-proton false }, { id 17, name " N6 ", iupac-code { " N6 " }, element n, ionizable-proton false }, { id 18, name " N1 ", iupac-code { " N1 " }, element n, ionizable-proton false }, { id 19, name " C2 ", iupac-code { " C2 " }, element c, ionizable-proton false }, { id 20, name " N3 ", iupac-code { " N3 " }, element n, ionizable-proton false }, { id 21, name " C4 ", iupac-code { " C4 " }, element c, ionizable-proton false }, { id 22, name "1H5*", iupac-code { "1H5*" }, element h, ionizable-proton false }, { id 23, name "2H5*", iupac-code { "2H5*" }, element h, ionizable-proton false }, { id 24, name " H4*", iupac-code { " H4*" }, element h, ionizable-proton false }, { id 25, name " H3*", iupac-code { " H3*" }, element h, ionizable-proton false }, { id 26, name "1H2*", iupac-code { "1H2*" }, element h, ionizable-proton false }, { id 27, name "2H2*", iupac-code { "2H2*" }, element h, ionizable-proton false }, { id 28, name " H1*", iupac-code { " H1*" }, element h, ionizable-proton false }, { id 29, name " H8 ", iupac-code { " H8 " }, element h, ionizable-proton false }, { id 30, name "1HN6", iupac-code { "1HN6" }, element h, ionizable-proton false }, { id 31, name "2HN6", iupac-code { "2HN6" }, element h, ionizable-proton false }, { id 32, name " H2 ", iupac-code { " H2 " }, element h, ionizable-proton false }, { id 33, name " H1P", iupac-code { " H1P" }, element h, ionizable-proton true }, { id 34, name " H2P", iupac-code { " H2P" }, element h, ionizable-proton true } }, bonds { { atom-id-1 1, atom-id-2 2, bond-order partial-double }, { atom-id-1 1, atom-id-2 3, bond-order partial-double }, { atom-id-1 1, atom-id-2 4, bond-order single }, { atom-id-1 4, atom-id-2 5, bond-order single }, { atom-id-1 5, atom-id-2 6, bond-order single }, { atom-id-1 5, atom-id-2 22, bond-order single }, { atom-id-1 5, atom-id-2 23, bond-order single }, { atom-id-1 6, atom-id-2 7, bond-order single }, { atom-id-1 6, atom-id-2 8, bond-order single }, { atom-id-1 6, atom-id-2 24, bond-order single }, { atom-id-1 7, atom-id-2 11, bond-order single }, { atom-id-1 8, atom-id-2 9, bond-order single }, { atom-id-1 8, atom-id-2 10, bond-order single }, { atom-id-1 8, atom-id-2 25, bond-order single }, { atom-id-1 10, atom-id-2 11, bond-order single }, { atom-id-1 10, atom-id-2 26, bond-order single }, { atom-id-1 10, atom-id-2 27, bond-order single }, { atom-id-1 11, atom-id-2 12, bond-order single }, { atom-id-1 11, atom-id-2 28, bond-order single }, { atom-id-1 12, atom-id-2 13, bond-order single }, { atom-id-1 12, atom-id-2 21, bond-order single }, { atom-id-1 13, atom-id-2 14, bond-order double }, { atom-id-1 13, atom-id-2 29, bond-order single }, { atom-id-1 14, atom-id-2 15, bond-order single }, { atom-id-1 15, atom-id-2 16, bond-order single }, { atom-id-1 15, atom-id-2 21, bond-order double }, { atom-id-1 16, atom-id-2 17, bond-order single }, { atom-id-1 16, atom-id-2 18, bond-order double }, { atom-id-1 17, atom-id-2 30, bond-order single }, { atom-id-1 17, atom-id-2 31, bond-order single }, { atom-id-1 18, atom-id-2 19, bond-order single }, { atom-id-1 19, atom-id-2 20, bond-order double }, { atom-id-1 19, atom-id-2 32, bond-order single }, { atom-id-1 20, atom-id-2 21, bond-order single }, { atom-id-1 2, atom-id-2 33, bond-order single }, { atom-id-1 3, atom-id-2 34, bond-order single } }, chiral-centers { { c 8, n1 6, n2 10, n3 9, sign positive }, { c 6, n1 5, n2 8, n3 7, sign positive }, { c 11, n1 7, n2 10, n3 12, sign positive } } }, { id 62, descr { name " A DNA 3'OH" }, residue-type deoxyribonucleotide, iupac-code { "A" }, atoms { { id 1, name " P ", iupac-code { " P " }, element p, ionizable-proton false }, { id 2, name " O1P", iupac-code { " O1P" }, element o, ionizable-proton false }, { id 3, name " O2P", iupac-code { " O2P" }, element o, ionizable-proton false }, { id 4, name " O5*", iupac-code { " O5*" }, element o, ionizable-proton false }, { id 5, name " C5*", iupac-code { " C5*" }, element c, ionizable-proton false }, { id 6, name " C4*", iupac-code { " C4*" }, element c, ionizable-proton false }, { id 7, name " O4*", iupac-code { " O4*" }, element o, ionizable-proton false }, { id 8, name " C3*", iupac-code { " C3*" }, element c, ionizable-proton false }, { id 9, name " O3*", iupac-code { " O3*" }, element o, ionizable-proton false }, { id 10, name " C2*", iupac-code { " C2*" }, element c, ionizable-proton false }, { id 11, name " C1*", iupac-code { " C1*" }, element c, ionizable-proton false }, { id 12, name " N9 ", iupac-code { " N9 " }, element n, ionizable-proton false }, { id 13, name " C8 ", iupac-code { " C8 " }, element c, ionizable-proton false }, { id 14, name " N7 ", iupac-code { " N7 " }, element n, ionizable-proton false }, { id 15, name " C5 ", iupac-code { " C5 " }, element c, ionizable-proton false }, { id 16, name " C6 ", iupac-code { " C6 " }, element c, ionizable-proton false }, { id 17, name " N6 ", iupac-code { " N6 " }, element n, ionizable-proton false }, { id 18, name " N1 ", iupac-code { " N1 " }, element n, ionizable-proton false }, { id 19, name " C2 ", iupac-code { " C2 " }, element c, ionizable-proton false }, { id 20, name " N3 ", iupac-code { " N3 " }, element n, ionizable-proton false }, { id 21, name " C4 ", iupac-code { " C4 " }, element c, ionizable-proton false }, { id 22, name "1H5*", iupac-code { "1H5*" }, element h, ionizable-proton false }, { id 23, name "2H5*", iupac-code { "2H5*" }, element h, ionizable-proton false }, { id 24, name " H4*", iupac-code { " H4*" }, element h, ionizable-proton false }, { id 25, name " H3*", iupac-code { " H3*" }, element h, ionizable-proton false }, { id 26, name "1H2*", iupac-code { "1H2*" }, element h, ionizable-proton false }, { id 27, name "2H2*", iupac-code { "2H2*" }, element h, ionizable-proton false }, { id 28, name " H1*", iupac-code { " H1*" }, element h, ionizable-proton false }, { id 29, name " H8 ", iupac-code { " H8 " }, element h, ionizable-proton false }, { id 30, name "1HN6", iupac-code { "1HN6" }, element h, ionizable-proton false }, { id 31, name "2HN6", iupac-code { "2HN6" }, element h, ionizable-proton false }, { id 32, name " H2 ", iupac-code { " H2 " }, element h, ionizable-proton false }, { id 33, name " H3T", iupac-code { " H3T" }, element h, ionizable-proton false }, { id 34, name " H1P", iupac-code { " H1P" }, element h, ionizable-proton true }, { id 35, name " H2P", iupac-code { " H2P" }, element h, ionizable-proton true } }, bonds { { atom-id-1 1, atom-id-2 2, bond-order partial-double }, { atom-id-1 1, atom-id-2 3, bond-order partial-double }, { atom-id-1 1, atom-id-2 4, bond-order single }, { atom-id-1 4, atom-id-2 5, bond-order single }, { atom-id-1 5, atom-id-2 6, bond-order single }, { atom-id-1 5, atom-id-2 22, bond-order single }, { atom-id-1 5, atom-id-2 23, bond-order single }, { atom-id-1 6, atom-id-2 7, bond-order single }, { atom-id-1 6, atom-id-2 8, bond-order single }, { atom-id-1 6, atom-id-2 24, bond-order single }, { atom-id-1 7, atom-id-2 11, bond-order single }, { atom-id-1 8, atom-id-2 9, bond-order single }, { atom-id-1 8, atom-id-2 10, bond-order single }, { atom-id-1 8, atom-id-2 25, bond-order single }, { atom-id-1 10, atom-id-2 11, bond-order single }, { atom-id-1 10, atom-id-2 26, bond-order single }, { atom-id-1 10, atom-id-2 27, bond-order single }, { atom-id-1 11, atom-id-2 12, bond-order single }, { atom-id-1 11, atom-id-2 28, bond-order single }, { atom-id-1 12, atom-id-2 13, bond-order single }, { atom-id-1 12, atom-id-2 21, bond-order single }, { atom-id-1 13, atom-id-2 14, bond-order double }, { atom-id-1 13, atom-id-2 29, bond-order single }, { atom-id-1 14, atom-id-2 15, bond-order single }, { atom-id-1 15, atom-id-2 16, bond-order single }, { atom-id-1 15, atom-id-2 21, bond-order double }, { atom-id-1 16, atom-id-2 17, bond-order single }, { atom-id-1 16, atom-id-2 18, bond-order double }, { atom-id-1 17, atom-id-2 30, bond-order single }, { atom-id-1 17, atom-id-2 31, bond-order single }, { atom-id-1 18, atom-id-2 19, bond-order single }, { atom-id-1 19, atom-id-2 20, bond-order double }, { atom-id-1 19, atom-id-2 32, bond-order single }, { atom-id-1 20, atom-id-2 21, bond-order single }, { atom-id-1 33, atom-id-2 9, bond-order single }, { atom-id-1 2, atom-id-2 34, bond-order single }, { atom-id-1 3, atom-id-2 35, bond-order single } }, chiral-centers { { c 8, n1 6, n2 10, n3 9, sign positive }, { c 6, n1 5, n2 8, n3 7, sign positive }, { c 11, n1 7, n2 10, n3 12, sign positive } } }, { id 63, descr { name " A DNA 5'OH" }, residue-type deoxyribonucleotide, iupac-code { "A" }, atoms { { id 1, name " O5*", iupac-code { " O5*" }, element o, ionizable-proton false }, { id 2, name " C5*", iupac-code { " C5*" }, element c, ionizable-proton false }, { id 3, name " C4*", iupac-code { " C4*" }, element c, ionizable-proton false }, { id 4, name " O4*", iupac-code { " O4*" }, element o, ionizable-proton false }, { id 5, name " C3*", iupac-code { " C3*" }, element c, ionizable-proton false }, { id 6, name " O3*", iupac-code { " O3*" }, element o, ionizable-proton false }, { id 7, name " C2*", iupac-code { " C2*" }, element c, ionizable-proton false }, { id 8, name " C1*", iupac-code { " C1*" }, element c, ionizable-proton false }, { id 9, name " N9 ", iupac-code { " N9 " }, element n, ionizable-proton false }, { id 10, name " C8 ", iupac-code { " C8 " }, element c, ionizable-proton false }, { id 11, name " N7 ", iupac-code { " N7 " }, element n, ionizable-proton false }, { id 12, name " C5 ", iupac-code { " C5 " }, element c, ionizable-proton false }, { id 13, name " C6 ", iupac-code { " C6 " }, element c, ionizable-proton false }, { id 14, name " N6 ", iupac-code { " N6 " }, element n, ionizable-proton false }, { id 15, name " N1 ", iupac-code { " N1 " }, element n, ionizable-proton false }, { id 16, name " C2 ", iupac-code { " C2 " }, element c, ionizable-proton false }, { id 17, name " N3 ", iupac-code { " N3 " }, element n, ionizable-proton false }, { id 18, name " C4 ", iupac-code { " C4 " }, element c, ionizable-proton false }, { id 19, name "1H5*", iupac-code { "1H5*" }, element h, ionizable-proton false }, { id 20, name "2H5*", iupac-code { "2H5*" }, element h, ionizable-proton false }, { id 21, name " H4*", iupac-code { " H4*" }, element h, ionizable-proton false }, { id 22, name " H3*", iupac-code { " H3*" }, element h, ionizable-proton false }, { id 23, name "1H2*", iupac-code { "1H2*" }, element h, ionizable-proton false }, { id 24, name "2H2*", iupac-code { "2H2*" }, element h, ionizable-proton false }, { id 25, name " H1*", iupac-code { " H1*" }, element h, ionizable-proton false }, { id 26, name " H8 ", iupac-code { " H8 " }, element h, ionizable-proton false }, { id 27, name "1HN6", iupac-code { "1HN6" }, element h, ionizable-proton false }, { id 28, name "2HN6", iupac-code { "2HN6" }, element h, ionizable-proton false }, { id 29, name " H2 ", iupac-code { " H2 " }, element h, ionizable-proton false }, { id 30, name " H5T", iupac-code { " H5T" }, element h, ionizable-proton false } }, bonds { { atom-id-1 1, atom-id-2 2, bond-order single }, { atom-id-1 2, atom-id-2 3, bond-order single }, { atom-id-1 2, atom-id-2 19, bond-order single }, { atom-id-1 2, atom-id-2 20, bond-order single }, { atom-id-1 3, atom-id-2 4, bond-order single }, { atom-id-1 3, atom-id-2 5, bond-order single }, { atom-id-1 3, atom-id-2 21, bond-order single }, { atom-id-1 4, atom-id-2 8, bond-order single }, { atom-id-1 5, atom-id-2 6, bond-order single }, { atom-id-1 5, atom-id-2 7, bond-order single }, { atom-id-1 5, atom-id-2 22, bond-order single }, { atom-id-1 7, atom-id-2 8, bond-order single }, { atom-id-1 7, atom-id-2 23, bond-order single }, { atom-id-1 7, atom-id-2 24, bond-order single }, { atom-id-1 8, atom-id-2 9, bond-order single }, { atom-id-1 8, atom-id-2 25, bond-order single }, { atom-id-1 9, atom-id-2 10, bond-order single }, { atom-id-1 9, atom-id-2 18, bond-order single }, { atom-id-1 10, atom-id-2 11, bond-order double }, { atom-id-1 10, atom-id-2 26, bond-order single }, { atom-id-1 11, atom-id-2 12, bond-order single }, { atom-id-1 12, atom-id-2 13, bond-order single }, { atom-id-1 12, atom-id-2 18, bond-order double }, { atom-id-1 13, atom-id-2 14, bond-order single }, { atom-id-1 13, atom-id-2 15, bond-order double }, { atom-id-1 14, atom-id-2 27, bond-order single }, { atom-id-1 14, atom-id-2 28, bond-order single }, { atom-id-1 15, atom-id-2 16, bond-order single }, { atom-id-1 16, atom-id-2 17, bond-order double }, { atom-id-1 16, atom-id-2 29, bond-order single }, { atom-id-1 17, atom-id-2 18, bond-order single }, { atom-id-1 30, atom-id-2 1, bond-order single } }, chiral-centers { { c 5, n1 3, n2 7, n3 6, sign positive }, { c 3, n1 2, n2 5, n3 4, sign positive }, { c 8, n1 4, n2 7, n3 9, sign positive } } }, { id 64, descr { name " C DNA" }, residue-type deoxyribonucleotide, iupac-code { "C" }, atoms { { id 1, name " P ", iupac-code { " P " }, element p, ionizable-proton false }, { id 2, name " O1P", iupac-code { " O1P" }, element o, ionizable-proton false }, { id 3, name " O2P", iupac-code { " O2P" }, element o, ionizable-proton false }, { id 4, name " O5*", iupac-code { " O5*" }, element o, ionizable-proton false }, { id 5, name " C5*", iupac-code { " C5*" }, element c, ionizable-proton false }, { id 6, name " C4*", iupac-code { " C4*" }, element c, ionizable-proton false }, { id 7, name " O4*", iupac-code { " O4*" }, element o, ionizable-proton false }, { id 8, name " C3*", iupac-code { " C3*" }, element c, ionizable-proton false }, { id 9, name " O3*", iupac-code { " O3*" }, element o, ionizable-proton false }, { id 10, name " C2*", iupac-code { " C2*" }, element c, ionizable-proton false }, { id 11, name " C1*", iupac-code { " C1*" }, element c, ionizable-proton false }, { id 12, name " N1 ", iupac-code { " N1 " }, element n, ionizable-proton false }, { id 13, name " C2 ", iupac-code { " C2 " }, element c, ionizable-proton false }, { id 14, name " O2 ", iupac-code { " O2 " }, element o, ionizable-proton false }, { id 15, name " N3 ", iupac-code { " N3 " }, element n, ionizable-proton false }, { id 16, name " C4 ", iupac-code { " C4 " }, element c, ionizable-proton false }, { id 17, name " N4 ", iupac-code { " N4 " }, element n, ionizable-proton false }, { id 18, name " C5 ", iupac-code { " C5 " }, element c, ionizable-proton false }, { id 19, name " C6 ", iupac-code { " C6 " }, element c, ionizable-proton false }, { id 20, name "1H5*", iupac-code { "1H5*" }, element h, ionizable-proton false }, { id 21, name "2H5*", iupac-code { "2H5*" }, element h, ionizable-proton false }, { id 22, name " H4*", iupac-code { " H4*" }, element h, ionizable-proton false }, { id 23, name " H3*", iupac-code { " H3*" }, element h, ionizable-proton false }, { id 24, name "1H2*", iupac-code { "1H2*" }, element h, ionizable-proton false }, { id 25, name "2H2*", iupac-code { "2H2*" }, element h, ionizable-proton false }, { id 26, name " H1*", iupac-code { " H1*" }, element h, ionizable-proton false }, { id 27, name "1HN4", iupac-code { "1HN4" }, element h, ionizable-proton false }, { id 28, name "2HN4", iupac-code { "2HN4" }, element h, ionizable-proton false }, { id 29, name " H5 ", iupac-code { " H5 " }, element h, ionizable-proton false }, { id 30, name " H6 ", iupac-code { " H6 " }, element h, ionizable-proton false }, { id 31, name " H1P", iupac-code { " H1P" }, element h, ionizable-proton true }, { id 32, name " H2P", iupac-code { " H2P" }, element h, ionizable-proton true } }, bonds { { atom-id-1 1, atom-id-2 2, bond-order partial-double }, { atom-id-1 1, atom-id-2 3, bond-order partial-double }, { atom-id-1 1, atom-id-2 4, bond-order single }, { atom-id-1 4, atom-id-2 5, bond-order single }, { atom-id-1 5, atom-id-2 6, bond-order single }, { atom-id-1 5, atom-id-2 20, bond-order single }, { atom-id-1 5, atom-id-2 21, bond-order single }, { atom-id-1 6, atom-id-2 7, bond-order single }, { atom-id-1 6, atom-id-2 8, bond-order single }, { atom-id-1 6, atom-id-2 22, bond-order single }, { atom-id-1 7, atom-id-2 11, bond-order single }, { atom-id-1 8, atom-id-2 9, bond-order single }, { atom-id-1 8, atom-id-2 10, bond-order single }, { atom-id-1 8, atom-id-2 23, bond-order single }, { atom-id-1 10, atom-id-2 11, bond-order single }, { atom-id-1 10, atom-id-2 24, bond-order single }, { atom-id-1 10, atom-id-2 25, bond-order single }, { atom-id-1 11, atom-id-2 12, bond-order single }, { atom-id-1 11, atom-id-2 26, bond-order single }, { atom-id-1 12, atom-id-2 13, bond-order single }, { atom-id-1 12, atom-id-2 19, bond-order single }, { atom-id-1 13, atom-id-2 14, bond-order double }, { atom-id-1 13, atom-id-2 15, bond-order single }, { atom-id-1 15, atom-id-2 16, bond-order double }, { atom-id-1 16, atom-id-2 17, bond-order single }, { atom-id-1 16, atom-id-2 18, bond-order single }, { atom-id-1 17, atom-id-2 27, bond-order single }, { atom-id-1 17, atom-id-2 28, bond-order single }, { atom-id-1 18, atom-id-2 19, bond-order double }, { atom-id-1 18, atom-id-2 29, bond-order single }, { atom-id-1 19, atom-id-2 30, bond-order single }, { atom-id-1 2, atom-id-2 31, bond-order single }, { atom-id-1 3, atom-id-2 32, bond-order single } }, chiral-centers { { c 8, n1 6, n2 10, n3 9, sign positive }, { c 6, n1 5, n2 8, n3 7, sign positive }, { c 11, n1 7, n2 10, n3 12, sign positive } } }, { id 65, descr { name " C DNA 3'OH" }, residue-type deoxyribonucleotide, iupac-code { "C" }, atoms { { id 1, name " P ", iupac-code { " P " }, element p, ionizable-proton false }, { id 2, name " O1P", iupac-code { " O1P" }, element o, ionizable-proton false }, { id 3, name " O2P", iupac-code { " O2P" }, element o, ionizable-proton false }, { id 4, name " O5*", iupac-code { " O5*" }, element o, ionizable-proton false }, { id 5, name " C5*", iupac-code { " C5*" }, element c, ionizable-proton false }, { id 6, name " C4*", iupac-code { " C4*" }, element c, ionizable-proton false }, { id 7, name " O4*", iupac-code { " O4*" }, element o, ionizable-proton false }, { id 8, name " C3*", iupac-code { " C3*" }, element c, ionizable-proton false }, { id 9, name " O3*", iupac-code { " O3*" }, element o, ionizable-proton false }, { id 10, name " C2*", iupac-code { " C2*" }, element c, ionizable-proton false }, { id 11, name " C1*", iupac-code { " C1*" }, element c, ionizable-proton false }, { id 12, name " N1 ", iupac-code { " N1 " }, element n, ionizable-proton false }, { id 13, name " C2 ", iupac-code { " C2 " }, element c, ionizable-proton false }, { id 14, name " O2 ", iupac-code { " O2 " }, element o, ionizable-proton false }, { id 15, name " N3 ", iupac-code { " N3 " }, element n, ionizable-proton false }, { id 16, name " C4 ", iupac-code { " C4 " }, element c, ionizable-proton false }, { id 17, name " N4 ", iupac-code { " N4 " }, element n, ionizable-proton false }, { id 18, name " C5 ", iupac-code { " C5 " }, element c, ionizable-proton false }, { id 19, name " C6 ", iupac-code { " C6 " }, element c, ionizable-proton false }, { id 20, name "1H5*", iupac-code { "1H5*" }, element h, ionizable-proton false }, { id 21, name "2H5*", iupac-code { "2H5*" }, element h, ionizable-proton false }, { id 22, name " H4*", iupac-code { " H4*" }, element h, ionizable-proton false }, { id 23, name " H3*", iupac-code { " H3*" }, element h, ionizable-proton false }, { id 24, name "1H2*", iupac-code { "1H2*" }, element h, ionizable-proton false }, { id 25, name "2H2*", iupac-code { "2H2*" }, element h, ionizable-proton false }, { id 26, name " H1*", iupac-code { " H1*" }, element h, ionizable-proton false }, { id 27, name "1HN4", iupac-code { "1HN4" }, element h, ionizable-proton false }, { id 28, name "2HN4", iupac-code { "2HN4" }, element h, ionizable-proton false }, { id 29, name " H5 ", iupac-code { " H5 " }, element h, ionizable-proton false }, { id 30, name " H6 ", iupac-code { " H6 " }, element h, ionizable-proton false }, { id 31, name " H3T", iupac-code { " H3T" }, element h, ionizable-proton false }, { id 32, name " H1P", iupac-code { " H1P" }, element h, ionizable-proton true }, { id 33, name " H2P", iupac-code { " H2P" }, element h, ionizable-proton true } }, bonds { { atom-id-1 1, atom-id-2 2, bond-order partial-double }, { atom-id-1 1, atom-id-2 3, bond-order partial-double }, { atom-id-1 1, atom-id-2 4, bond-order single }, { atom-id-1 4, atom-id-2 5, bond-order single }, { atom-id-1 5, atom-id-2 6, bond-order single }, { atom-id-1 5, atom-id-2 20, bond-order single }, { atom-id-1 5, atom-id-2 21, bond-order single }, { atom-id-1 6, atom-id-2 7, bond-order single }, { atom-id-1 6, atom-id-2 8, bond-order single }, { atom-id-1 6, atom-id-2 22, bond-order single }, { atom-id-1 7, atom-id-2 11, bond-order single }, { atom-id-1 8, atom-id-2 9, bond-order single }, { atom-id-1 8, atom-id-2 10, bond-order single }, { atom-id-1 8, atom-id-2 23, bond-order single }, { atom-id-1 10, atom-id-2 11, bond-order single }, { atom-id-1 10, atom-id-2 24, bond-order single }, { atom-id-1 10, atom-id-2 25, bond-order single }, { atom-id-1 11, atom-id-2 12, bond-order single }, { atom-id-1 11, atom-id-2 26, bond-order single }, { atom-id-1 12, atom-id-2 13, bond-order single }, { atom-id-1 12, atom-id-2 19, bond-order single }, { atom-id-1 13, atom-id-2 14, bond-order double }, { atom-id-1 13, atom-id-2 15, bond-order single }, { atom-id-1 15, atom-id-2 16, bond-order double }, { atom-id-1 16, atom-id-2 17, bond-order single }, { atom-id-1 16, atom-id-2 18, bond-order single }, { atom-id-1 17, atom-id-2 27, bond-order single }, { atom-id-1 17, atom-id-2 28, bond-order single }, { atom-id-1 18, atom-id-2 19, bond-order double }, { atom-id-1 18, atom-id-2 29, bond-order single }, { atom-id-1 19, atom-id-2 30, bond-order single }, { atom-id-1 31, atom-id-2 9, bond-order single }, { atom-id-1 2, atom-id-2 32, bond-order single }, { atom-id-1 3, atom-id-2 33, bond-order single } }, chiral-centers { { c 8, n1 6, n2 10, n3 9, sign positive }, { c 6, n1 5, n2 8, n3 7, sign positive }, { c 11, n1 7, n2 10, n3 12, sign positive } } }, { id 66, descr { name " C DNA 5'OH" }, residue-type deoxyribonucleotide, iupac-code { "C" }, atoms { { id 1, name " O5*", iupac-code { " O5*" }, element o, ionizable-proton false }, { id 2, name " C5*", iupac-code { " C5*" }, element c, ionizable-proton false }, { id 3, name " C4*", iupac-code { " C4*" }, element c, ionizable-proton false }, { id 4, name " O4*", iupac-code { " O4*" }, element o, ionizable-proton false }, { id 5, name " C3*", iupac-code { " C3*" }, element c, ionizable-proton false }, { id 6, name " O3*", iupac-code { " O3*" }, element o, ionizable-proton false }, { id 7, name " C2*", iupac-code { " C2*" }, element c, ionizable-proton false }, { id 8, name " C1*", iupac-code { " C1*" }, element c, ionizable-proton false }, { id 9, name " N1 ", iupac-code { " N1 " }, element n, ionizable-proton false }, { id 10, name " C2 ", iupac-code { " C2 " }, element c, ionizable-proton false }, { id 11, name " O2 ", iupac-code { " O2 " }, element o, ionizable-proton false }, { id 12, name " N3 ", iupac-code { " N3 " }, element n, ionizable-proton false }, { id 13, name " C4 ", iupac-code { " C4 " }, element c, ionizable-proton false }, { id 14, name " N4 ", iupac-code { " N4 " }, element n, ionizable-proton false }, { id 15, name " C5 ", iupac-code { " C5 " }, element c, ionizable-proton false }, { id 16, name " C6 ", iupac-code { " C6 " }, element c, ionizable-proton false }, { id 17, name "1H5*", iupac-code { "1H5*" }, element h, ionizable-proton false }, { id 18, name "2H5*", iupac-code { "2H5*" }, element h, ionizable-proton false }, { id 19, name " H4*", iupac-code { " H4*" }, element h, ionizable-proton false }, { id 20, name " H3*", iupac-code { " H3*" }, element h, ionizable-proton false }, { id 21, name "1H2*", iupac-code { "1H2*" }, element h, ionizable-proton false }, { id 22, name "2H2*", iupac-code { "2H2*" }, element h, ionizable-proton false }, { id 23, name " H1*", iupac-code { " H1*" }, element h, ionizable-proton false }, { id 24, name "1HN4", iupac-code { "1HN4" }, element h, ionizable-proton false }, { id 25, name "2HN4", iupac-code { "2HN4" }, element h, ionizable-proton false }, { id 26, name " H5 ", iupac-code { " H5 " }, element h, ionizable-proton false }, { id 27, name " H6 ", iupac-code { " H6 " }, element h, ionizable-proton false }, { id 28, name " H5T", iupac-code { " H5T" }, element h, ionizable-proton false } }, bonds { { atom-id-1 1, atom-id-2 2, bond-order single }, { atom-id-1 2, atom-id-2 3, bond-order single }, { atom-id-1 2, atom-id-2 17, bond-order single }, { atom-id-1 2, atom-id-2 18, bond-order single }, { atom-id-1 3, atom-id-2 4, bond-order single }, { atom-id-1 3, atom-id-2 5, bond-order single }, { atom-id-1 3, atom-id-2 19, bond-order single }, { atom-id-1 4, atom-id-2 8, bond-order single }, { atom-id-1 5, atom-id-2 6, bond-order single }, { atom-id-1 5, atom-id-2 7, bond-order single }, { atom-id-1 5, atom-id-2 20, bond-order single }, { atom-id-1 7, atom-id-2 8, bond-order single }, { atom-id-1 7, atom-id-2 21, bond-order single }, { atom-id-1 7, atom-id-2 22, bond-order single }, { atom-id-1 8, atom-id-2 9, bond-order single }, { atom-id-1 8, atom-id-2 23, bond-order single }, { atom-id-1 9, atom-id-2 10, bond-order single }, { atom-id-1 9, atom-id-2 16, bond-order single }, { atom-id-1 10, atom-id-2 11, bond-order double }, { atom-id-1 10, atom-id-2 12, bond-order single }, { atom-id-1 12, atom-id-2 13, bond-order double }, { atom-id-1 13, atom-id-2 14, bond-order single }, { atom-id-1 13, atom-id-2 15, bond-order single }, { atom-id-1 14, atom-id-2 24, bond-order single }, { atom-id-1 14, atom-id-2 25, bond-order single }, { atom-id-1 15, atom-id-2 16, bond-order double }, { atom-id-1 15, atom-id-2 26, bond-order single }, { atom-id-1 16, atom-id-2 27, bond-order single }, { atom-id-1 28, atom-id-2 1, bond-order single } }, chiral-centers { { c 5, n1 3, n2 7, n3 6, sign positive }, { c 3, n1 2, n2 5, n3 4, sign positive }, { c 8, n1 4, n2 7, n3 9, sign positive } } }, { id 67, descr { name " G DNA" }, residue-type deoxyribonucleotide, iupac-code { "G" }, atoms { { id 1, name " P ", iupac-code { " P " }, element p, ionizable-proton false }, { id 2, name " O1P", iupac-code { " O1P" }, element o, ionizable-proton false }, { id 3, name " O2P", iupac-code { " O2P" }, element o, ionizable-proton false }, { id 4, name " O5*", iupac-code { " O5*" }, element o, ionizable-proton false }, { id 5, name " C5*", iupac-code { " C5*" }, element c, ionizable-proton false }, { id 6, name " C4*", iupac-code { " C4*" }, element c, ionizable-proton false }, { id 7, name " O4*", iupac-code { " O4*" }, element o, ionizable-proton false }, { id 8, name " C3*", iupac-code { " C3*" }, element c, ionizable-proton false }, { id 9, name " O3*", iupac-code { " O3*" }, element o, ionizable-proton false }, { id 10, name " C2*", iupac-code { " C2*" }, element c, ionizable-proton false }, { id 11, name " C1*", iupac-code { " C1*" }, element c, ionizable-proton false }, { id 12, name " N9 ", iupac-code { " N9 " }, element n, ionizable-proton false }, { id 13, name " C8 ", iupac-code { " C8 " }, element c, ionizable-proton false }, { id 14, name " N7 ", iupac-code { " N7 " }, element n, ionizable-proton false }, { id 15, name " C5 ", iupac-code { " C5 " }, element c, ionizable-proton false }, { id 16, name " C6 ", iupac-code { " C6 " }, element c, ionizable-proton false }, { id 17, name " O6 ", iupac-code { " O6 " }, element o, ionizable-proton false }, { id 18, name " N1 ", iupac-code { " N1 " }, element n, ionizable-proton false }, { id 19, name " C2 ", iupac-code { " C2 " }, element c, ionizable-proton false }, { id 20, name " N2 ", iupac-code { " N2 " }, element n, ionizable-proton false }, { id 21, name " N3 ", iupac-code { " N3 " }, element n, ionizable-proton false }, { id 22, name " C4 ", iupac-code { " C4 " }, element c, ionizable-proton false }, { id 23, name "1H5*", iupac-code { "1H5*" }, element h, ionizable-proton false }, { id 24, name "2H5*", iupac-code { "2H5*" }, element h, ionizable-proton false }, { id 25, name " H4*", iupac-code { " H4*" }, element h, ionizable-proton false }, { id 26, name " H3*", iupac-code { " H3*" }, element h, ionizable-proton false }, { id 27, name "1H2*", iupac-code { "1H2*" }, element h, ionizable-proton false }, { id 28, name "2H2*", iupac-code { "2H2*" }, element h, ionizable-proton false }, { id 29, name " H1*", iupac-code { " H1*" }, element h, ionizable-proton false }, { id 30, name " H8 ", iupac-code { " H8 " }, element h, ionizable-proton false }, { id 31, name " H1 ", iupac-code { " H1 " }, element h, ionizable-proton false }, { id 32, name "1HN2", iupac-code { "1HN2" }, element h, ionizable-proton false }, { id 33, name "2HN2", iupac-code { "2HN2" }, element h, ionizable-proton false }, { id 34, name " H1P", iupac-code { " H1P" }, element h, ionizable-proton true }, { id 35, name " H2P", iupac-code { " H2P" }, element h, ionizable-proton true } }, bonds { { atom-id-1 1, atom-id-2 2, bond-order partial-double }, { atom-id-1 1, atom-id-2 3, bond-order partial-double }, { atom-id-1 1, atom-id-2 4, bond-order single }, { atom-id-1 4, atom-id-2 5, bond-order single }, { atom-id-1 5, atom-id-2 6, bond-order single }, { atom-id-1 5, atom-id-2 23, bond-order single }, { atom-id-1 5, atom-id-2 24, bond-order single }, { atom-id-1 6, atom-id-2 7, bond-order single }, { atom-id-1 6, atom-id-2 8, bond-order single }, { atom-id-1 6, atom-id-2 25, bond-order single }, { atom-id-1 7, atom-id-2 11, bond-order single }, { atom-id-1 8, atom-id-2 9, bond-order single }, { atom-id-1 8, atom-id-2 10, bond-order single }, { atom-id-1 8, atom-id-2 26, bond-order single }, { atom-id-1 10, atom-id-2 11, bond-order single }, { atom-id-1 10, atom-id-2 27, bond-order single }, { atom-id-1 10, atom-id-2 28, bond-order single }, { atom-id-1 11, atom-id-2 12, bond-order single }, { atom-id-1 11, atom-id-2 29, bond-order single }, { atom-id-1 12, atom-id-2 13, bond-order single }, { atom-id-1 12, atom-id-2 22, bond-order single }, { atom-id-1 13, atom-id-2 14, bond-order double }, { atom-id-1 13, atom-id-2 30, bond-order single }, { atom-id-1 14, atom-id-2 15, bond-order single }, { atom-id-1 15, atom-id-2 16, bond-order single }, { atom-id-1 15, atom-id-2 22, bond-order double }, { atom-id-1 16, atom-id-2 17, bond-order double }, { atom-id-1 16, atom-id-2 18, bond-order single }, { atom-id-1 18, atom-id-2 19, bond-order single }, { atom-id-1 18, atom-id-2 31, bond-order single }, { atom-id-1 19, atom-id-2 20, bond-order single }, { atom-id-1 19, atom-id-2 21, bond-order double }, { atom-id-1 20, atom-id-2 32, bond-order single }, { atom-id-1 20, atom-id-2 33, bond-order single }, { atom-id-1 21, atom-id-2 22, bond-order single }, { atom-id-1 2, atom-id-2 34, bond-order single }, { atom-id-1 3, atom-id-2 35, bond-order single } }, chiral-centers { { c 8, n1 6, n2 10, n3 9, sign positive }, { c 6, n1 5, n2 8, n3 7, sign positive }, { c 11, n1 7, n2 10, n3 12, sign positive } } }, { id 68, descr { name " G DNA 3'OH" }, residue-type deoxyribonucleotide, iupac-code { "G" }, atoms { { id 1, name " P ", iupac-code { " P " }, element p, ionizable-proton false }, { id 2, name " O1P", iupac-code { " O1P" }, element o, ionizable-proton false }, { id 3, name " O2P", iupac-code { " O2P" }, element o, ionizable-proton false }, { id 4, name " O5*", iupac-code { " O5*" }, element o, ionizable-proton false }, { id 5, name " C5*", iupac-code { " C5*" }, element c, ionizable-proton false }, { id 6, name " C4*", iupac-code { " C4*" }, element c, ionizable-proton false }, { id 7, name " O4*", iupac-code { " O4*" }, element o, ionizable-proton false }, { id 8, name " C3*", iupac-code { " C3*" }, element c, ionizable-proton false }, { id 9, name " O3*", iupac-code { " O3*" }, element o, ionizable-proton false }, { id 10, name " C2*", iupac-code { " C2*" }, element c, ionizable-proton false }, { id 11, name " C1*", iupac-code { " C1*" }, element c, ionizable-proton false }, { id 12, name " N9 ", iupac-code { " N9 " }, element n, ionizable-proton false }, { id 13, name " C8 ", iupac-code { " C8 " }, element c, ionizable-proton false }, { id 14, name " N7 ", iupac-code { " N7 " }, element n, ionizable-proton false }, { id 15, name " C5 ", iupac-code { " C5 " }, element c, ionizable-proton false }, { id 16, name " C6 ", iupac-code { " C6 " }, element c, ionizable-proton false }, { id 17, name " O6 ", iupac-code { " O6 " }, element o, ionizable-proton false }, { id 18, name " N1 ", iupac-code { " N1 " }, element n, ionizable-proton false }, { id 19, name " C2 ", iupac-code { " C2 " }, element c, ionizable-proton false }, { id 20, name " N2 ", iupac-code { " N2 " }, element n, ionizable-proton false }, { id 21, name " N3 ", iupac-code { " N3 " }, element n, ionizable-proton false }, { id 22, name " C4 ", iupac-code { " C4 " }, element c, ionizable-proton false }, { id 23, name "1H5*", iupac-code { "1H5*" }, element h, ionizable-proton false }, { id 24, name "2H5*", iupac-code { "2H5*" }, element h, ionizable-proton false }, { id 25, name " H4*", iupac-code { " H4*" }, element h, ionizable-proton false }, { id 26, name " H3*", iupac-code { " H3*" }, element h, ionizable-proton false }, { id 27, name "1H2*", iupac-code { "1H2*" }, element h, ionizable-proton false }, { id 28, name "2H2*", iupac-code { "2H2*" }, element h, ionizable-proton false }, { id 29, name " H1*", iupac-code { " H1*" }, element h, ionizable-proton false }, { id 30, name " H8 ", iupac-code { " H8 " }, element h, ionizable-proton false }, { id 31, name " H1 ", iupac-code { " H1 " }, element h, ionizable-proton false }, { id 32, name "1HN2", iupac-code { "1HN2" }, element h, ionizable-proton false }, { id 33, name "2HN2", iupac-code { "2HN2" }, element h, ionizable-proton false }, { id 34, name " H3T", iupac-code { " H3T" }, element h, ionizable-proton false }, { id 35, name " H1P", iupac-code { " H1P" }, element h, ionizable-proton true }, { id 36, name " H2P", iupac-code { " H2P" }, element h, ionizable-proton true } }, bonds { { atom-id-1 1, atom-id-2 2, bond-order partial-double }, { atom-id-1 1, atom-id-2 3, bond-order partial-double }, { atom-id-1 1, atom-id-2 4, bond-order single }, { atom-id-1 4, atom-id-2 5, bond-order single }, { atom-id-1 5, atom-id-2 6, bond-order single }, { atom-id-1 5, atom-id-2 23, bond-order single }, { atom-id-1 5, atom-id-2 24, bond-order single }, { atom-id-1 6, atom-id-2 7, bond-order single }, { atom-id-1 6, atom-id-2 8, bond-order single }, { atom-id-1 6, atom-id-2 25, bond-order single }, { atom-id-1 7, atom-id-2 11, bond-order single }, { atom-id-1 8, atom-id-2 9, bond-order single }, { atom-id-1 8, atom-id-2 10, bond-order single }, { atom-id-1 8, atom-id-2 26, bond-order single }, { atom-id-1 10, atom-id-2 11, bond-order single }, { atom-id-1 10, atom-id-2 27, bond-order single }, { atom-id-1 10, atom-id-2 28, bond-order single }, { atom-id-1 11, atom-id-2 12, bond-order single }, { atom-id-1 11, atom-id-2 29, bond-order single }, { atom-id-1 12, atom-id-2 13, bond-order single }, { atom-id-1 12, atom-id-2 22, bond-order single }, { atom-id-1 13, atom-id-2 14, bond-order double }, { atom-id-1 13, atom-id-2 30, bond-order single }, { atom-id-1 14, atom-id-2 15, bond-order single }, { atom-id-1 15, atom-id-2 16, bond-order single }, { atom-id-1 15, atom-id-2 22, bond-order double }, { atom-id-1 16, atom-id-2 17, bond-order double }, { atom-id-1 16, atom-id-2 18, bond-order single }, { atom-id-1 18, atom-id-2 19, bond-order single }, { atom-id-1 18, atom-id-2 31, bond-order single }, { atom-id-1 19, atom-id-2 20, bond-order single }, { atom-id-1 19, atom-id-2 21, bond-order double }, { atom-id-1 20, atom-id-2 32, bond-order single }, { atom-id-1 20, atom-id-2 33, bond-order single }, { atom-id-1 21, atom-id-2 22, bond-order single }, { atom-id-1 34, atom-id-2 9, bond-order single }, { atom-id-1 2, atom-id-2 35, bond-order single }, { atom-id-1 3, atom-id-2 36, bond-order single } }, chiral-centers { { c 8, n1 6, n2 10, n3 9, sign positive }, { c 6, n1 5, n2 8, n3 7, sign positive }, { c 11, n1 7, n2 10, n3 12, sign positive } } }, { id 69, descr { name " G DNA 5'OH" }, residue-type deoxyribonucleotide, iupac-code { "G" }, atoms { { id 1, name " O5*", iupac-code { " O5*" }, element o, ionizable-proton false }, { id 2, name " C5*", iupac-code { " C5*" }, element c, ionizable-proton false }, { id 3, name " C4*", iupac-code { " C4*" }, element c, ionizable-proton false }, { id 4, name " O4*", iupac-code { " O4*" }, element o, ionizable-proton false }, { id 5, name " C3*", iupac-code { " C3*" }, element c, ionizable-proton false }, { id 6, name " O3*", iupac-code { " O3*" }, element o, ionizable-proton false }, { id 7, name " C2*", iupac-code { " C2*" }, element c, ionizable-proton false }, { id 8, name " C1*", iupac-code { " C1*" }, element c, ionizable-proton false }, { id 9, name " N9 ", iupac-code { " N9 " }, element n, ionizable-proton false }, { id 10, name " C8 ", iupac-code { " C8 " }, element c, ionizable-proton false }, { id 11, name " N7 ", iupac-code { " N7 " }, element n, ionizable-proton false }, { id 12, name " C5 ", iupac-code { " C5 " }, element c, ionizable-proton false }, { id 13, name " C6 ", iupac-code { " C6 " }, element c, ionizable-proton false }, { id 14, name " O6 ", iupac-code { " O6 " }, element o, ionizable-proton false }, { id 15, name " N1 ", iupac-code { " N1 " }, element n, ionizable-proton false }, { id 16, name " C2 ", iupac-code { " C2 " }, element c, ionizable-proton false }, { id 17, name " N2 ", iupac-code { " N2 " }, element n, ionizable-proton false }, { id 18, name " N3 ", iupac-code { " N3 " }, element n, ionizable-proton false }, { id 19, name " C4 ", iupac-code { " C4 " }, element c, ionizable-proton false }, { id 20, name "1H5*", iupac-code { "1H5*" }, element h, ionizable-proton false }, { id 21, name "2H5*", iupac-code { "2H5*" }, element h, ionizable-proton false }, { id 22, name " H4*", iupac-code { " H4*" }, element h, ionizable-proton false }, { id 23, name " H3*", iupac-code { " H3*" }, element h, ionizable-proton false }, { id 24, name "1H2*", iupac-code { "1H2*" }, element h, ionizable-proton false }, { id 25, name "2H2*", iupac-code { "2H2*" }, element h, ionizable-proton false }, { id 26, name " H1*", iupac-code { " H1*" }, element h, ionizable-proton false }, { id 27, name " H8 ", iupac-code { " H8 " }, element h, ionizable-proton false }, { id 28, name " H1 ", iupac-code { " H1 " }, element h, ionizable-proton false }, { id 29, name "1HN2", iupac-code { "1HN2" }, element h, ionizable-proton false }, { id 30, name "2HN2", iupac-code { "2HN2" }, element h, ionizable-proton false }, { id 31, name " H5T", iupac-code { " H5T" }, element h, ionizable-proton false } }, bonds { { atom-id-1 1, atom-id-2 2, bond-order single }, { atom-id-1 2, atom-id-2 3, bond-order single }, { atom-id-1 2, atom-id-2 20, bond-order single }, { atom-id-1 2, atom-id-2 21, bond-order single }, { atom-id-1 3, atom-id-2 4, bond-order single }, { atom-id-1 3, atom-id-2 5, bond-order single }, { atom-id-1 3, atom-id-2 22, bond-order single }, { atom-id-1 4, atom-id-2 8, bond-order single }, { atom-id-1 5, atom-id-2 6, bond-order single }, { atom-id-1 5, atom-id-2 7, bond-order single }, { atom-id-1 5, atom-id-2 23, bond-order single }, { atom-id-1 7, atom-id-2 8, bond-order single }, { atom-id-1 7, atom-id-2 24, bond-order single }, { atom-id-1 7, atom-id-2 25, bond-order single }, { atom-id-1 8, atom-id-2 9, bond-order single }, { atom-id-1 8, atom-id-2 26, bond-order single }, { atom-id-1 9, atom-id-2 10, bond-order single }, { atom-id-1 9, atom-id-2 19, bond-order single }, { atom-id-1 10, atom-id-2 11, bond-order double }, { atom-id-1 10, atom-id-2 27, bond-order single }, { atom-id-1 11, atom-id-2 12, bond-order single }, { atom-id-1 12, atom-id-2 13, bond-order single }, { atom-id-1 12, atom-id-2 19, bond-order double }, { atom-id-1 13, atom-id-2 14, bond-order double }, { atom-id-1 13, atom-id-2 15, bond-order single }, { atom-id-1 15, atom-id-2 16, bond-order single }, { atom-id-1 15, atom-id-2 28, bond-order single }, { atom-id-1 16, atom-id-2 17, bond-order single }, { atom-id-1 16, atom-id-2 18, bond-order double }, { atom-id-1 17, atom-id-2 29, bond-order single }, { atom-id-1 17, atom-id-2 30, bond-order single }, { atom-id-1 18, atom-id-2 19, bond-order single }, { atom-id-1 31, atom-id-2 1, bond-order single } }, chiral-centers { { c 5, n1 3, n2 7, n3 6, sign positive }, { c 3, n1 2, n2 5, n3 4, sign positive }, { c 8, n1 4, n2 7, n3 9, sign positive } } }, { id 70, descr { name " T DNA" }, residue-type deoxyribonucleotide, iupac-code { "T" }, atoms { { id 1, name " P ", iupac-code { " P " }, element p, ionizable-proton false }, { id 2, name " O1P", iupac-code { " O1P" }, element o, ionizable-proton false }, { id 3, name " O2P", iupac-code { " O2P" }, element o, ionizable-proton false }, { id 4, name " O5*", iupac-code { " O5*" }, element o, ionizable-proton false }, { id 5, name " C5*", iupac-code { " C5*" }, element c, ionizable-proton false }, { id 6, name " C4*", iupac-code { " C4*" }, element c, ionizable-proton false }, { id 7, name " O4*", iupac-code { " O4*" }, element o, ionizable-proton false }, { id 8, name " C3*", iupac-code { " C3*" }, element c, ionizable-proton false }, { id 9, name " O3*", iupac-code { " O3*" }, element o, ionizable-proton false }, { id 10, name " C2*", iupac-code { " C2*" }, element c, ionizable-proton false }, { id 11, name " C1*", iupac-code { " C1*" }, element c, ionizable-proton false }, { id 12, name " N1 ", iupac-code { " N1 " }, element n, ionizable-proton false }, { id 13, name " C2 ", iupac-code { " C2 " }, element c, ionizable-proton false }, { id 14, name " O2 ", iupac-code { " O2 " }, element o, ionizable-proton false }, { id 15, name " N3 ", iupac-code { " N3 " }, element n, ionizable-proton false }, { id 16, name " C4 ", iupac-code { " C4 " }, element c, ionizable-proton false }, { id 17, name " O4 ", iupac-code { " O4 " }, element o, ionizable-proton false }, { id 18, name " C5 ", iupac-code { " C5 " }, element c, ionizable-proton false }, { id 19, name " C5M", iupac-code { " C5M" }, element c, ionizable-proton false }, { id 20, name " C6 ", iupac-code { " C6 " }, element c, ionizable-proton false }, { id 21, name "1H5*", iupac-code { "1H5*" }, element h, ionizable-proton false }, { id 22, name "2H5*", iupac-code { "2H5*" }, element h, ionizable-proton false }, { id 23, name " H4*", iupac-code { " H4*" }, element h, ionizable-proton false }, { id 24, name " H3*", iupac-code { " H3*" }, element h, ionizable-proton false }, { id 25, name "1H2*", iupac-code { "1H2*" }, element h, ionizable-proton false }, { id 26, name "2H2*", iupac-code { "2H2*" }, element h, ionizable-proton false }, { id 27, name " H1*", iupac-code { " H1*" }, element h, ionizable-proton false }, { id 28, name " H3 ", iupac-code { " H3 " }, element h, ionizable-proton false }, { id 29, name "1H5M", iupac-code { "1H5M" }, element h, ionizable-proton false }, { id 30, name "2H5M", iupac-code { "2H5M" }, element h, ionizable-proton false }, { id 31, name "3H5M", iupac-code { "3H5M" }, element h, ionizable-proton false }, { id 32, name " H6 ", iupac-code { " H6 " }, element h, ionizable-proton false }, { id 33, name " H1P", iupac-code { " H1P" }, element h, ionizable-proton true }, { id 34, name " H2P", iupac-code { " H2P" }, element h, ionizable-proton true } }, bonds { { atom-id-1 1, atom-id-2 2, bond-order partial-double }, { atom-id-1 1, atom-id-2 3, bond-order partial-double }, { atom-id-1 1, atom-id-2 4, bond-order single }, { atom-id-1 4, atom-id-2 5, bond-order single }, { atom-id-1 5, atom-id-2 6, bond-order single }, { atom-id-1 5, atom-id-2 21, bond-order single }, { atom-id-1 5, atom-id-2 22, bond-order single }, { atom-id-1 6, atom-id-2 7, bond-order single }, { atom-id-1 6, atom-id-2 8, bond-order single }, { atom-id-1 6, atom-id-2 23, bond-order single }, { atom-id-1 7, atom-id-2 11, bond-order single }, { atom-id-1 8, atom-id-2 9, bond-order single }, { atom-id-1 8, atom-id-2 10, bond-order single }, { atom-id-1 8, atom-id-2 24, bond-order single }, { atom-id-1 10, atom-id-2 11, bond-order single }, { atom-id-1 10, atom-id-2 25, bond-order single }, { atom-id-1 10, atom-id-2 26, bond-order single }, { atom-id-1 11, atom-id-2 12, bond-order single }, { atom-id-1 11, atom-id-2 27, bond-order single }, { atom-id-1 12, atom-id-2 13, bond-order single }, { atom-id-1 12, atom-id-2 20, bond-order single }, { atom-id-1 13, atom-id-2 14, bond-order double }, { atom-id-1 13, atom-id-2 15, bond-order single }, { atom-id-1 15, atom-id-2 16, bond-order single }, { atom-id-1 15, atom-id-2 28, bond-order single }, { atom-id-1 16, atom-id-2 17, bond-order double }, { atom-id-1 16, atom-id-2 18, bond-order single }, { atom-id-1 18, atom-id-2 19, bond-order single }, { atom-id-1 18, atom-id-2 20, bond-order double }, { atom-id-1 19, atom-id-2 29, bond-order single }, { atom-id-1 19, atom-id-2 30, bond-order single }, { atom-id-1 19, atom-id-2 31, bond-order single }, { atom-id-1 20, atom-id-2 32, bond-order single }, { atom-id-1 2, atom-id-2 33, bond-order single }, { atom-id-1 3, atom-id-2 34, bond-order single } }, chiral-centers { { c 8, n1 6, n2 10, n3 9, sign positive }, { c 6, n1 5, n2 8, n3 7, sign positive }, { c 11, n1 7, n2 10, n3 12, sign positive } } }, { id 71, descr { name " T DNA 3'OH" }, residue-type deoxyribonucleotide, iupac-code { "T" }, atoms { { id 1, name " P ", iupac-code { " P " }, element p, ionizable-proton false }, { id 2, name " O1P", iupac-code { " O1P" }, element o, ionizable-proton false }, { id 3, name " O2P", iupac-code { " O2P" }, element o, ionizable-proton false }, { id 4, name " O5*", iupac-code { " O5*" }, element o, ionizable-proton false }, { id 5, name " C5*", iupac-code { " C5*" }, element c, ionizable-proton false }, { id 6, name " C4*", iupac-code { " C4*" }, element c, ionizable-proton false }, { id 7, name " O4*", iupac-code { " O4*" }, element o, ionizable-proton false }, { id 8, name " C3*", iupac-code { " C3*" }, element c, ionizable-proton false }, { id 9, name " O3*", iupac-code { " O3*" }, element o, ionizable-proton false }, { id 10, name " C2*", iupac-code { " C2*" }, element c, ionizable-proton false }, { id 11, name " C1*", iupac-code { " C1*" }, element c, ionizable-proton false }, { id 12, name " N1 ", iupac-code { " N1 " }, element n, ionizable-proton false }, { id 13, name " C2 ", iupac-code { " C2 " }, element c, ionizable-proton false }, { id 14, name " O2 ", iupac-code { " O2 " }, element o, ionizable-proton false }, { id 15, name " N3 ", iupac-code { " N3 " }, element n, ionizable-proton false }, { id 16, name " C4 ", iupac-code { " C4 " }, element c, ionizable-proton false }, { id 17, name " O4 ", iupac-code { " O4 " }, element o, ionizable-proton false }, { id 18, name " C5 ", iupac-code { " C5 " }, element c, ionizable-proton false }, { id 19, name " C5M", iupac-code { " C5M" }, element c, ionizable-proton false }, { id 20, name " C6 ", iupac-code { " C6 " }, element c, ionizable-proton false }, { id 21, name "1H5*", iupac-code { "1H5*" }, element h, ionizable-proton false }, { id 22, name "2H5*", iupac-code { "2H5*" }, element h, ionizable-proton false }, { id 23, name " H4*", iupac-code { " H4*" }, element h, ionizable-proton false }, { id 24, name " H3*", iupac-code { " H3*" }, element h, ionizable-proton false }, { id 25, name "1H2*", iupac-code { "1H2*" }, element h, ionizable-proton false }, { id 26, name "2H2*", iupac-code { "2H2*" }, element h, ionizable-proton false }, { id 27, name " H1*", iupac-code { " H1*" }, element h, ionizable-proton false }, { id 28, name " H3 ", iupac-code { " H3 " }, element h, ionizable-proton false }, { id 29, name "1H5M", iupac-code { "1H5M" }, element h, ionizable-proton false }, { id 30, name "2H5M", iupac-code { "2H5M" }, element h, ionizable-proton false }, { id 31, name "3H5M", iupac-code { "3H5M" }, element h, ionizable-proton false }, { id 32, name " H6 ", iupac-code { " H6 " }, element h, ionizable-proton false }, { id 33, name " H3T", iupac-code { " H3T" }, element h, ionizable-proton false }, { id 34, name " H1P", iupac-code { " H1P" }, element h, ionizable-proton true }, { id 35, name " H2P", iupac-code { " H2P" }, element h, ionizable-proton true } }, bonds { { atom-id-1 1, atom-id-2 2, bond-order partial-double }, { atom-id-1 1, atom-id-2 3, bond-order partial-double }, { atom-id-1 1, atom-id-2 4, bond-order single }, { atom-id-1 4, atom-id-2 5, bond-order single }, { atom-id-1 5, atom-id-2 6, bond-order single }, { atom-id-1 5, atom-id-2 21, bond-order single }, { atom-id-1 5, atom-id-2 22, bond-order single }, { atom-id-1 6, atom-id-2 7, bond-order single }, { atom-id-1 6, atom-id-2 8, bond-order single }, { atom-id-1 6, atom-id-2 23, bond-order single }, { atom-id-1 7, atom-id-2 11, bond-order single }, { atom-id-1 8, atom-id-2 9, bond-order single }, { atom-id-1 8, atom-id-2 10, bond-order single }, { atom-id-1 8, atom-id-2 24, bond-order single }, { atom-id-1 10, atom-id-2 11, bond-order single }, { atom-id-1 10, atom-id-2 25, bond-order single }, { atom-id-1 10, atom-id-2 26, bond-order single }, { atom-id-1 11, atom-id-2 12, bond-order single }, { atom-id-1 11, atom-id-2 27, bond-order single }, { atom-id-1 12, atom-id-2 13, bond-order single }, { atom-id-1 12, atom-id-2 20, bond-order single }, { atom-id-1 13, atom-id-2 14, bond-order double }, { atom-id-1 13, atom-id-2 15, bond-order single }, { atom-id-1 15, atom-id-2 16, bond-order single }, { atom-id-1 15, atom-id-2 28, bond-order single }, { atom-id-1 16, atom-id-2 17, bond-order double }, { atom-id-1 16, atom-id-2 18, bond-order single }, { atom-id-1 18, atom-id-2 19, bond-order single }, { atom-id-1 18, atom-id-2 20, bond-order double }, { atom-id-1 19, atom-id-2 29, bond-order single }, { atom-id-1 19, atom-id-2 30, bond-order single }, { atom-id-1 19, atom-id-2 31, bond-order single }, { atom-id-1 20, atom-id-2 32, bond-order single }, { atom-id-1 33, atom-id-2 9, bond-order single }, { atom-id-1 2, atom-id-2 34, bond-order single }, { atom-id-1 3, atom-id-2 35, bond-order single } }, chiral-centers { { c 8, n1 6, n2 10, n3 9, sign positive }, { c 6, n1 5, n2 8, n3 7, sign positive }, { c 11, n1 7, n2 10, n3 12, sign positive } } }, { id 72, descr { name " T DNA 5'OH" }, residue-type deoxyribonucleotide, iupac-code { "T" }, atoms { { id 1, name " O5*", iupac-code { " O5*" }, element o, ionizable-proton false }, { id 2, name " C5*", iupac-code { " C5*" }, element c, ionizable-proton false }, { id 3, name " C4*", iupac-code { " C4*" }, element c, ionizable-proton false }, { id 4, name " O4*", iupac-code { " O4*" }, element o, ionizable-proton false }, { id 5, name " C3*", iupac-code { " C3*" }, element c, ionizable-proton false }, { id 6, name " O3*", iupac-code { " O3*" }, element o, ionizable-proton false }, { id 7, name " C2*", iupac-code { " C2*" }, element c, ionizable-proton false }, { id 8, name " C1*", iupac-code { " C1*" }, element c, ionizable-proton false }, { id 9, name " N1 ", iupac-code { " N1 " }, element n, ionizable-proton false }, { id 10, name " C2 ", iupac-code { " C2 " }, element c, ionizable-proton false }, { id 11, name " O2 ", iupac-code { " O2 " }, element o, ionizable-proton false }, { id 12, name " N3 ", iupac-code { " N3 " }, element n, ionizable-proton false }, { id 13, name " C4 ", iupac-code { " C4 " }, element c, ionizable-proton false }, { id 14, name " O4 ", iupac-code { " O4 " }, element o, ionizable-proton false }, { id 15, name " C5 ", iupac-code { " C5 " }, element c, ionizable-proton false }, { id 16, name " C5M", iupac-code { " C5M" }, element c, ionizable-proton false }, { id 17, name " C6 ", iupac-code { " C6 " }, element c, ionizable-proton false }, { id 18, name "1H5*", iupac-code { "1H5*" }, element h, ionizable-proton false }, { id 19, name "2H5*", iupac-code { "2H5*" }, element h, ionizable-proton false }, { id 20, name " H4*", iupac-code { " H4*" }, element h, ionizable-proton false }, { id 21, name " H3*", iupac-code { " H3*" }, element h, ionizable-proton false }, { id 22, name "1H2*", iupac-code { "1H2*" }, element h, ionizable-proton false }, { id 23, name "2H2*", iupac-code { "2H2*" }, element h, ionizable-proton false }, { id 24, name " H1*", iupac-code { " H1*" }, element h, ionizable-proton false }, { id 25, name " H3 ", iupac-code { " H3 " }, element h, ionizable-proton false }, { id 26, name "1H5M", iupac-code { "1H5M" }, element h, ionizable-proton false }, { id 27, name "2H5M", iupac-code { "2H5M" }, element h, ionizable-proton false }, { id 28, name "3H5M", iupac-code { "3H5M" }, element h, ionizable-proton false }, { id 29, name " H6 ", iupac-code { " H6 " }, element h, ionizable-proton false }, { id 30, name " H5T", iupac-code { " H5T" }, element h, ionizable-proton false } }, bonds { { atom-id-1 1, atom-id-2 2, bond-order single }, { atom-id-1 2, atom-id-2 3, bond-order single }, { atom-id-1 2, atom-id-2 18, bond-order single }, { atom-id-1 2, atom-id-2 19, bond-order single }, { atom-id-1 3, atom-id-2 4, bond-order single }, { atom-id-1 3, atom-id-2 5, bond-order single }, { atom-id-1 3, atom-id-2 20, bond-order single }, { atom-id-1 4, atom-id-2 8, bond-order single }, { atom-id-1 5, atom-id-2 6, bond-order single }, { atom-id-1 5, atom-id-2 7, bond-order single }, { atom-id-1 5, atom-id-2 21, bond-order single }, { atom-id-1 7, atom-id-2 8, bond-order single }, { atom-id-1 7, atom-id-2 22, bond-order single }, { atom-id-1 7, atom-id-2 23, bond-order single }, { atom-id-1 8, atom-id-2 9, bond-order single }, { atom-id-1 8, atom-id-2 24, bond-order single }, { atom-id-1 9, atom-id-2 10, bond-order single }, { atom-id-1 9, atom-id-2 17, bond-order single }, { atom-id-1 10, atom-id-2 11, bond-order double }, { atom-id-1 10, atom-id-2 12, bond-order single }, { atom-id-1 12, atom-id-2 13, bond-order single }, { atom-id-1 12, atom-id-2 25, bond-order single }, { atom-id-1 13, atom-id-2 14, bond-order double }, { atom-id-1 13, atom-id-2 15, bond-order single }, { atom-id-1 15, atom-id-2 16, bond-order single }, { atom-id-1 15, atom-id-2 17, bond-order double }, { atom-id-1 16, atom-id-2 26, bond-order single }, { atom-id-1 16, atom-id-2 27, bond-order single }, { atom-id-1 16, atom-id-2 28, bond-order single }, { atom-id-1 17, atom-id-2 29, bond-order single }, { atom-id-1 30, atom-id-2 1, bond-order single } }, chiral-centers { { c 5, n1 3, n2 7, n3 6, sign positive }, { c 3, n1 2, n2 5, n3 4, sign positive }, { c 8, n1 4, n2 7, n3 9, sign positive } } }, { id 73, descr { name " A RNA" }, residue-type ribonucleotide, iupac-code { "A" }, atoms { { id 1, name " P ", iupac-code { " P " }, element p, ionizable-proton false }, { id 2, name " O1P", iupac-code { " O1P" }, element o, ionizable-proton false }, { id 3, name " O2P", iupac-code { " O2P" }, element o, ionizable-proton false }, { id 4, name " O5*", iupac-code { " O5*" }, element o, ionizable-proton false }, { id 5, name " C5*", iupac-code { " C5*" }, element c, ionizable-proton false }, { id 6, name " C4*", iupac-code { " C4*" }, element c, ionizable-proton false }, { id 7, name " O4*", iupac-code { " O4*" }, element o, ionizable-proton false }, { id 8, name " C3*", iupac-code { " C3*" }, element c, ionizable-proton false }, { id 9, name " O3*", iupac-code { " O3*" }, element o, ionizable-proton false }, { id 10, name " C2*", iupac-code { " C2*" }, element c, ionizable-proton false }, { id 11, name " C1*", iupac-code { " C1*" }, element c, ionizable-proton false }, { id 12, name " N9 ", iupac-code { " N9 " }, element n, ionizable-proton false }, { id 13, name " C8 ", iupac-code { " C8 " }, element c, ionizable-proton false }, { id 14, name " N7 ", iupac-code { " N7 " }, element n, ionizable-proton false }, { id 15, name " C5 ", iupac-code { " C5 " }, element c, ionizable-proton false }, { id 16, name " C6 ", iupac-code { " C6 " }, element c, ionizable-proton false }, { id 17, name " N6 ", iupac-code { " N6 " }, element n, ionizable-proton false }, { id 18, name " N1 ", iupac-code { " N1 " }, element n, ionizable-proton false }, { id 19, name " C2 ", iupac-code { " C2 " }, element c, ionizable-proton false }, { id 20, name " N3 ", iupac-code { " N3 " }, element n, ionizable-proton false }, { id 21, name " C4 ", iupac-code { " C4 " }, element c, ionizable-proton false }, { id 22, name "1H5*", iupac-code { "1H5*" }, element h, ionizable-proton false }, { id 23, name "2H5*", iupac-code { "2H5*" }, element h, ionizable-proton false }, { id 24, name " H4*", iupac-code { " H4*" }, element h, ionizable-proton false }, { id 25, name " H3*", iupac-code { " H3*" }, element h, ionizable-proton false }, { id 26, name " H1*", iupac-code { " H1*" }, element h, ionizable-proton false }, { id 27, name " H8 ", iupac-code { " H8 " }, element h, ionizable-proton false }, { id 28, name "1HN6", iupac-code { "1HN6" }, element h, ionizable-proton false }, { id 29, name "2HN6", iupac-code { "2HN6" }, element h, ionizable-proton false }, { id 30, name " H2 ", iupac-code { " H2 " }, element h, ionizable-proton false }, { id 31, name " H1P", iupac-code { " H1P" }, element h, ionizable-proton true }, { id 32, name " H2P", iupac-code { " H2P" }, element h, ionizable-proton true }, { id 33, name " O2*", iupac-code { " O2*" }, element o, ionizable-proton false }, { id 34, name " H2*", iupac-code { " H2*" }, element h, ionizable-proton false }, { id 35, name " HO2", iupac-code { " HO2" }, element h, ionizable-proton false } }, bonds { { atom-id-1 1, atom-id-2 2, bond-order partial-double }, { atom-id-1 1, atom-id-2 3, bond-order partial-double }, { atom-id-1 1, atom-id-2 4, bond-order single }, { atom-id-1 4, atom-id-2 5, bond-order single }, { atom-id-1 5, atom-id-2 6, bond-order single }, { atom-id-1 5, atom-id-2 22, bond-order single }, { atom-id-1 5, atom-id-2 23, bond-order single }, { atom-id-1 6, atom-id-2 7, bond-order single }, { atom-id-1 6, atom-id-2 8, bond-order single }, { atom-id-1 6, atom-id-2 24, bond-order single }, { atom-id-1 7, atom-id-2 11, bond-order single }, { atom-id-1 8, atom-id-2 9, bond-order single }, { atom-id-1 8, atom-id-2 10, bond-order single }, { atom-id-1 8, atom-id-2 25, bond-order single }, { atom-id-1 10, atom-id-2 11, bond-order single }, { atom-id-1 11, atom-id-2 12, bond-order single }, { atom-id-1 11, atom-id-2 26, bond-order single }, { atom-id-1 12, atom-id-2 13, bond-order single }, { atom-id-1 12, atom-id-2 21, bond-order single }, { atom-id-1 13, atom-id-2 14, bond-order double }, { atom-id-1 13, atom-id-2 27, bond-order single }, { atom-id-1 14, atom-id-2 15, bond-order single }, { atom-id-1 15, atom-id-2 16, bond-order single }, { atom-id-1 15, atom-id-2 21, bond-order double }, { atom-id-1 16, atom-id-2 17, bond-order single }, { atom-id-1 16, atom-id-2 18, bond-order double }, { atom-id-1 17, atom-id-2 28, bond-order single }, { atom-id-1 17, atom-id-2 29, bond-order single }, { atom-id-1 18, atom-id-2 19, bond-order single }, { atom-id-1 19, atom-id-2 20, bond-order double }, { atom-id-1 19, atom-id-2 30, bond-order single }, { atom-id-1 20, atom-id-2 21, bond-order single }, { atom-id-1 2, atom-id-2 31, bond-order single }, { atom-id-1 3, atom-id-2 32, bond-order single }, { atom-id-1 10, atom-id-2 33, bond-order single }, { atom-id-1 10, atom-id-2 34, bond-order single }, { atom-id-1 33, atom-id-2 35, bond-order single } }, chiral-centers { { c 8, n1 6, n2 10, n3 9, sign positive }, { c 6, n1 5, n2 8, n3 7, sign positive }, { c 11, n1 7, n2 10, n3 12, sign positive } } }, { id 74, descr { name " A RNA 3'OH" }, residue-type ribonucleotide, iupac-code { "A" }, atoms { { id 1, name " P ", iupac-code { " P " }, element p, ionizable-proton false }, { id 2, name " O1P", iupac-code { " O1P" }, element o, ionizable-proton false }, { id 3, name " O2P", iupac-code { " O2P" }, element o, ionizable-proton false }, { id 4, name " O5*", iupac-code { " O5*" }, element o, ionizable-proton false }, { id 5, name " C5*", iupac-code { " C5*" }, element c, ionizable-proton false }, { id 6, name " C4*", iupac-code { " C4*" }, element c, ionizable-proton false }, { id 7, name " O4*", iupac-code { " O4*" }, element o, ionizable-proton false }, { id 8, name " C3*", iupac-code { " C3*" }, element c, ionizable-proton false }, { id 9, name " O3*", iupac-code { " O3*" }, element o, ionizable-proton false }, { id 10, name " C2*", iupac-code { " C2*" }, element c, ionizable-proton false }, { id 11, name " C1*", iupac-code { " C1*" }, element c, ionizable-proton false }, { id 12, name " N9 ", iupac-code { " N9 " }, element n, ionizable-proton false }, { id 13, name " C8 ", iupac-code { " C8 " }, element c, ionizable-proton false }, { id 14, name " N7 ", iupac-code { " N7 " }, element n, ionizable-proton false }, { id 15, name " C5 ", iupac-code { " C5 " }, element c, ionizable-proton false }, { id 16, name " C6 ", iupac-code { " C6 " }, element c, ionizable-proton false }, { id 17, name " N6 ", iupac-code { " N6 " }, element n, ionizable-proton false }, { id 18, name " N1 ", iupac-code { " N1 " }, element n, ionizable-proton false }, { id 19, name " C2 ", iupac-code { " C2 " }, element c, ionizable-proton false }, { id 20, name " N3 ", iupac-code { " N3 " }, element n, ionizable-proton false }, { id 21, name " C4 ", iupac-code { " C4 " }, element c, ionizable-proton false }, { id 22, name "1H5*", iupac-code { "1H5*" }, element h, ionizable-proton false }, { id 23, name "2H5*", iupac-code { "2H5*" }, element h, ionizable-proton false }, { id 24, name " H4*", iupac-code { " H4*" }, element h, ionizable-proton false }, { id 25, name " H3*", iupac-code { " H3*" }, element h, ionizable-proton false }, { id 26, name " H1*", iupac-code { " H1*" }, element h, ionizable-proton false }, { id 27, name " H8 ", iupac-code { " H8 " }, element h, ionizable-proton false }, { id 28, name "1HN6", iupac-code { "1HN6" }, element h, ionizable-proton false }, { id 29, name "2HN6", iupac-code { "2HN6" }, element h, ionizable-proton false }, { id 30, name " H2 ", iupac-code { " H2 " }, element h, ionizable-proton false }, { id 31, name " H3T", iupac-code { " H3T" }, element h, ionizable-proton false }, { id 32, name " H1P", iupac-code { " H1P" }, element h, ionizable-proton true }, { id 33, name " H2P", iupac-code { " H2P" }, element h, ionizable-proton true }, { id 34, name " O2*", iupac-code { " O2*" }, element o, ionizable-proton false }, { id 35, name " H2*", iupac-code { " H2*" }, element h, ionizable-proton false }, { id 36, name " HO2", iupac-code { " HO2" }, element h, ionizable-proton false } }, bonds { { atom-id-1 1, atom-id-2 2, bond-order partial-double }, { atom-id-1 1, atom-id-2 3, bond-order partial-double }, { atom-id-1 1, atom-id-2 4, bond-order single }, { atom-id-1 4, atom-id-2 5, bond-order single }, { atom-id-1 5, atom-id-2 6, bond-order single }, { atom-id-1 5, atom-id-2 22, bond-order single }, { atom-id-1 5, atom-id-2 23, bond-order single }, { atom-id-1 6, atom-id-2 7, bond-order single }, { atom-id-1 6, atom-id-2 8, bond-order single }, { atom-id-1 6, atom-id-2 24, bond-order single }, { atom-id-1 7, atom-id-2 11, bond-order single }, { atom-id-1 8, atom-id-2 9, bond-order single }, { atom-id-1 8, atom-id-2 10, bond-order single }, { atom-id-1 8, atom-id-2 25, bond-order single }, { atom-id-1 10, atom-id-2 11, bond-order single }, { atom-id-1 11, atom-id-2 12, bond-order single }, { atom-id-1 11, atom-id-2 26, bond-order single }, { atom-id-1 12, atom-id-2 13, bond-order single }, { atom-id-1 12, atom-id-2 21, bond-order single }, { atom-id-1 13, atom-id-2 14, bond-order double }, { atom-id-1 13, atom-id-2 27, bond-order single }, { atom-id-1 14, atom-id-2 15, bond-order single }, { atom-id-1 15, atom-id-2 16, bond-order single }, { atom-id-1 15, atom-id-2 21, bond-order double }, { atom-id-1 16, atom-id-2 17, bond-order single }, { atom-id-1 16, atom-id-2 18, bond-order double }, { atom-id-1 17, atom-id-2 28, bond-order single }, { atom-id-1 17, atom-id-2 29, bond-order single }, { atom-id-1 18, atom-id-2 19, bond-order single }, { atom-id-1 19, atom-id-2 20, bond-order double }, { atom-id-1 19, atom-id-2 30, bond-order single }, { atom-id-1 20, atom-id-2 21, bond-order single }, { atom-id-1 31, atom-id-2 9, bond-order single }, { atom-id-1 2, atom-id-2 32, bond-order single }, { atom-id-1 3, atom-id-2 33, bond-order single }, { atom-id-1 10, atom-id-2 34, bond-order single }, { atom-id-1 10, atom-id-2 35, bond-order single }, { atom-id-1 34, atom-id-2 36, bond-order single } }, chiral-centers { { c 8, n1 6, n2 10, n3 9, sign positive }, { c 6, n1 5, n2 8, n3 7, sign positive }, { c 11, n1 7, n2 10, n3 12, sign positive } } }, { id 75, descr { name " A RNA 5'OH" }, residue-type ribonucleotide, iupac-code { "A" }, atoms { { id 1, name " O5*", iupac-code { " O5*" }, element o, ionizable-proton false }, { id 2, name " C5*", iupac-code { " C5*" }, element c, ionizable-proton false }, { id 3, name " C4*", iupac-code { " C4*" }, element c, ionizable-proton false }, { id 4, name " O4*", iupac-code { " O4*" }, element o, ionizable-proton false }, { id 5, name " C3*", iupac-code { " C3*" }, element c, ionizable-proton false }, { id 6, name " O3*", iupac-code { " O3*" }, element o, ionizable-proton false }, { id 7, name " C2*", iupac-code { " C2*" }, element c, ionizable-proton false }, { id 8, name " C1*", iupac-code { " C1*" }, element c, ionizable-proton false }, { id 9, name " N9 ", iupac-code { " N9 " }, element n, ionizable-proton false }, { id 10, name " C8 ", iupac-code { " C8 " }, element c, ionizable-proton false }, { id 11, name " N7 ", iupac-code { " N7 " }, element n, ionizable-proton false }, { id 12, name " C5 ", iupac-code { " C5 " }, element c, ionizable-proton false }, { id 13, name " C6 ", iupac-code { " C6 " }, element c, ionizable-proton false }, { id 14, name " N6 ", iupac-code { " N6 " }, element n, ionizable-proton false }, { id 15, name " N1 ", iupac-code { " N1 " }, element n, ionizable-proton false }, { id 16, name " C2 ", iupac-code { " C2 " }, element c, ionizable-proton false }, { id 17, name " N3 ", iupac-code { " N3 " }, element n, ionizable-proton false }, { id 18, name " C4 ", iupac-code { " C4 " }, element c, ionizable-proton false }, { id 19, name "1H5*", iupac-code { "1H5*" }, element h, ionizable-proton false }, { id 20, name "2H5*", iupac-code { "2H5*" }, element h, ionizable-proton false }, { id 21, name " H4*", iupac-code { " H4*" }, element h, ionizable-proton false }, { id 22, name " H3*", iupac-code { " H3*" }, element h, ionizable-proton false }, { id 23, name " H1*", iupac-code { " H1*" }, element h, ionizable-proton false }, { id 24, name " H8 ", iupac-code { " H8 " }, element h, ionizable-proton false }, { id 25, name "1HN6", iupac-code { "1HN6" }, element h, ionizable-proton false }, { id 26, name "2HN6", iupac-code { "2HN6" }, element h, ionizable-proton false }, { id 27, name " H2 ", iupac-code { " H2 " }, element h, ionizable-proton false }, { id 28, name " H5T", iupac-code { " H5T" }, element h, ionizable-proton false }, { id 29, name " O2*", iupac-code { " O2*" }, element o, ionizable-proton false }, { id 30, name " H2*", iupac-code { " H2*" }, element h, ionizable-proton false }, { id 31, name " HO2", iupac-code { " HO2" }, element h, ionizable-proton false } }, bonds { { atom-id-1 1, atom-id-2 2, bond-order single }, { atom-id-1 2, atom-id-2 3, bond-order single }, { atom-id-1 2, atom-id-2 19, bond-order single }, { atom-id-1 2, atom-id-2 20, bond-order single }, { atom-id-1 3, atom-id-2 4, bond-order single }, { atom-id-1 3, atom-id-2 5, bond-order single }, { atom-id-1 3, atom-id-2 21, bond-order single }, { atom-id-1 4, atom-id-2 8, bond-order single }, { atom-id-1 5, atom-id-2 6, bond-order single }, { atom-id-1 5, atom-id-2 7, bond-order single }, { atom-id-1 5, atom-id-2 22, bond-order single }, { atom-id-1 7, atom-id-2 8, bond-order single }, { atom-id-1 8, atom-id-2 9, bond-order single }, { atom-id-1 8, atom-id-2 23, bond-order single }, { atom-id-1 9, atom-id-2 10, bond-order single }, { atom-id-1 9, atom-id-2 18, bond-order single }, { atom-id-1 10, atom-id-2 11, bond-order double }, { atom-id-1 10, atom-id-2 24, bond-order single }, { atom-id-1 11, atom-id-2 12, bond-order single }, { atom-id-1 12, atom-id-2 13, bond-order single }, { atom-id-1 12, atom-id-2 18, bond-order double }, { atom-id-1 13, atom-id-2 14, bond-order single }, { atom-id-1 13, atom-id-2 15, bond-order double }, { atom-id-1 14, atom-id-2 25, bond-order single }, { atom-id-1 14, atom-id-2 26, bond-order single }, { atom-id-1 15, atom-id-2 16, bond-order single }, { atom-id-1 16, atom-id-2 17, bond-order double }, { atom-id-1 16, atom-id-2 27, bond-order single }, { atom-id-1 17, atom-id-2 18, bond-order single }, { atom-id-1 28, atom-id-2 1, bond-order single }, { atom-id-1 7, atom-id-2 29, bond-order single }, { atom-id-1 7, atom-id-2 30, bond-order single }, { atom-id-1 29, atom-id-2 31, bond-order single } }, chiral-centers { { c 5, n1 3, n2 7, n3 6, sign positive }, { c 3, n1 2, n2 5, n3 4, sign positive }, { c 8, n1 4, n2 7, n3 9, sign positive } } }, { id 76, descr { name " C RNA" }, residue-type ribonucleotide, iupac-code { "C" }, atoms { { id 1, name " P ", iupac-code { " P " }, element p, ionizable-proton false }, { id 2, name " O1P", iupac-code { " O1P" }, element o, ionizable-proton false }, { id 3, name " O2P", iupac-code { " O2P" }, element o, ionizable-proton false }, { id 4, name " O5*", iupac-code { " O5*" }, element o, ionizable-proton false }, { id 5, name " C5*", iupac-code { " C5*" }, element c, ionizable-proton false }, { id 6, name " C4*", iupac-code { " C4*" }, element c, ionizable-proton false }, { id 7, name " O4*", iupac-code { " O4*" }, element o, ionizable-proton false }, { id 8, name " C3*", iupac-code { " C3*" }, element c, ionizable-proton false }, { id 9, name " O3*", iupac-code { " O3*" }, element o, ionizable-proton false }, { id 10, name " C2*", iupac-code { " C2*" }, element c, ionizable-proton false }, { id 11, name " C1*", iupac-code { " C1*" }, element c, ionizable-proton false }, { id 12, name " N1 ", iupac-code { " N1 " }, element n, ionizable-proton false }, { id 13, name " C2 ", iupac-code { " C2 " }, element c, ionizable-proton false }, { id 14, name " O2 ", iupac-code { " O2 " }, element o, ionizable-proton false }, { id 15, name " N3 ", iupac-code { " N3 " }, element n, ionizable-proton false }, { id 16, name " C4 ", iupac-code { " C4 " }, element c, ionizable-proton false }, { id 17, name " N4 ", iupac-code { " N4 " }, element n, ionizable-proton false }, { id 18, name " C5 ", iupac-code { " C5 " }, element c, ionizable-proton false }, { id 19, name " C6 ", iupac-code { " C6 " }, element c, ionizable-proton false }, { id 20, name "1H5*", iupac-code { "1H5*" }, element h, ionizable-proton false }, { id 21, name "2H5*", iupac-code { "2H5*" }, element h, ionizable-proton false }, { id 22, name " H4*", iupac-code { " H4*" }, element h, ionizable-proton false }, { id 23, name " H3*", iupac-code { " H3*" }, element h, ionizable-proton false }, { id 24, name " H1*", iupac-code { " H1*" }, element h, ionizable-proton false }, { id 25, name "1HN4", iupac-code { "1HN4" }, element h, ionizable-proton false }, { id 26, name "2HN4", iupac-code { "2HN4" }, element h, ionizable-proton false }, { id 27, name " H5 ", iupac-code { " H5 " }, element h, ionizable-proton false }, { id 28, name " H6 ", iupac-code { " H6 " }, element h, ionizable-proton false }, { id 29, name " H1P", iupac-code { " H1P" }, element h, ionizable-proton true }, { id 30, name " H2P", iupac-code { " H2P" }, element h, ionizable-proton true }, { id 31, name " O2*", iupac-code { " O2*" }, element o, ionizable-proton false }, { id 32, name " H2*", iupac-code { " H2*" }, element h, ionizable-proton false }, { id 33, name " HO2", iupac-code { " HO2" }, element h, ionizable-proton false } }, bonds { { atom-id-1 1, atom-id-2 2, bond-order partial-double }, { atom-id-1 1, atom-id-2 3, bond-order partial-double }, { atom-id-1 1, atom-id-2 4, bond-order single }, { atom-id-1 4, atom-id-2 5, bond-order single }, { atom-id-1 5, atom-id-2 6, bond-order single }, { atom-id-1 5, atom-id-2 20, bond-order single }, { atom-id-1 5, atom-id-2 21, bond-order single }, { atom-id-1 6, atom-id-2 7, bond-order single }, { atom-id-1 6, atom-id-2 8, bond-order single }, { atom-id-1 6, atom-id-2 22, bond-order single }, { atom-id-1 7, atom-id-2 11, bond-order single }, { atom-id-1 8, atom-id-2 9, bond-order single }, { atom-id-1 8, atom-id-2 10, bond-order single }, { atom-id-1 8, atom-id-2 23, bond-order single }, { atom-id-1 10, atom-id-2 11, bond-order single }, { atom-id-1 11, atom-id-2 12, bond-order single }, { atom-id-1 11, atom-id-2 24, bond-order single }, { atom-id-1 12, atom-id-2 13, bond-order single }, { atom-id-1 12, atom-id-2 19, bond-order single }, { atom-id-1 13, atom-id-2 14, bond-order double }, { atom-id-1 13, atom-id-2 15, bond-order single }, { atom-id-1 15, atom-id-2 16, bond-order double }, { atom-id-1 16, atom-id-2 17, bond-order single }, { atom-id-1 16, atom-id-2 18, bond-order single }, { atom-id-1 17, atom-id-2 25, bond-order single }, { atom-id-1 17, atom-id-2 26, bond-order single }, { atom-id-1 18, atom-id-2 19, bond-order double }, { atom-id-1 18, atom-id-2 27, bond-order single }, { atom-id-1 19, atom-id-2 28, bond-order single }, { atom-id-1 2, atom-id-2 29, bond-order single }, { atom-id-1 3, atom-id-2 30, bond-order single }, { atom-id-1 10, atom-id-2 31, bond-order single }, { atom-id-1 10, atom-id-2 32, bond-order single }, { atom-id-1 31, atom-id-2 33, bond-order single } }, chiral-centers { { c 8, n1 6, n2 10, n3 9, sign positive }, { c 6, n1 5, n2 8, n3 7, sign positive }, { c 11, n1 7, n2 10, n3 12, sign positive } } }, { id 77, descr { name " C RNA 3'OH" }, residue-type ribonucleotide, iupac-code { "C" }, atoms { { id 1, name " P ", iupac-code { " P " }, element p, ionizable-proton false }, { id 2, name " O1P", iupac-code { " O1P" }, element o, ionizable-proton false }, { id 3, name " O2P", iupac-code { " O2P" }, element o, ionizable-proton false }, { id 4, name " O5*", iupac-code { " O5*" }, element o, ionizable-proton false }, { id 5, name " C5*", iupac-code { " C5*" }, element c, ionizable-proton false }, { id 6, name " C4*", iupac-code { " C4*" }, element c, ionizable-proton false }, { id 7, name " O4*", iupac-code { " O4*" }, element o, ionizable-proton false }, { id 8, name " C3*", iupac-code { " C3*" }, element c, ionizable-proton false }, { id 9, name " O3*", iupac-code { " O3*" }, element o, ionizable-proton false }, { id 10, name " C2*", iupac-code { " C2*" }, element c, ionizable-proton false }, { id 11, name " C1*", iupac-code { " C1*" }, element c, ionizable-proton false }, { id 12, name " N1 ", iupac-code { " N1 " }, element n, ionizable-proton false }, { id 13, name " C2 ", iupac-code { " C2 " }, element c, ionizable-proton false }, { id 14, name " O2 ", iupac-code { " O2 " }, element o, ionizable-proton false }, { id 15, name " N3 ", iupac-code { " N3 " }, element n, ionizable-proton false }, { id 16, name " C4 ", iupac-code { " C4 " }, element c, ionizable-proton false }, { id 17, name " N4 ", iupac-code { " N4 " }, element n, ionizable-proton false }, { id 18, name " C5 ", iupac-code { " C5 " }, element c, ionizable-proton false }, { id 19, name " C6 ", iupac-code { " C6 " }, element c, ionizable-proton false }, { id 20, name "1H5*", iupac-code { "1H5*" }, element h, ionizable-proton false }, { id 21, name "2H5*", iupac-code { "2H5*" }, element h, ionizable-proton false }, { id 22, name " H4*", iupac-code { " H4*" }, element h, ionizable-proton false }, { id 23, name " H3*", iupac-code { " H3*" }, element h, ionizable-proton false }, { id 24, name " H1*", iupac-code { " H1*" }, element h, ionizable-proton false }, { id 25, name "1HN4", iupac-code { "1HN4" }, element h, ionizable-proton false }, { id 26, name "2HN4", iupac-code { "2HN4" }, element h, ionizable-proton false }, { id 27, name " H5 ", iupac-code { " H5 " }, element h, ionizable-proton false }, { id 28, name " H6 ", iupac-code { " H6 " }, element h, ionizable-proton false }, { id 29, name " H3T", iupac-code { " H3T" }, element h, ionizable-proton false }, { id 30, name " H1P", iupac-code { " H1P" }, element h, ionizable-proton true }, { id 31, name " H2P", iupac-code { " H2P" }, element h, ionizable-proton true }, { id 32, name " O2*", iupac-code { " O2*" }, element o, ionizable-proton false }, { id 33, name " H2*", iupac-code { " H2*" }, element h, ionizable-proton false }, { id 34, name " HO2", iupac-code { " HO2" }, element h, ionizable-proton false } }, bonds { { atom-id-1 1, atom-id-2 2, bond-order partial-double }, { atom-id-1 1, atom-id-2 3, bond-order partial-double }, { atom-id-1 1, atom-id-2 4, bond-order single }, { atom-id-1 4, atom-id-2 5, bond-order single }, { atom-id-1 5, atom-id-2 6, bond-order single }, { atom-id-1 5, atom-id-2 20, bond-order single }, { atom-id-1 5, atom-id-2 21, bond-order single }, { atom-id-1 6, atom-id-2 7, bond-order single }, { atom-id-1 6, atom-id-2 8, bond-order single }, { atom-id-1 6, atom-id-2 22, bond-order single }, { atom-id-1 7, atom-id-2 11, bond-order single }, { atom-id-1 8, atom-id-2 9, bond-order single }, { atom-id-1 8, atom-id-2 10, bond-order single }, { atom-id-1 8, atom-id-2 23, bond-order single }, { atom-id-1 10, atom-id-2 11, bond-order single }, { atom-id-1 11, atom-id-2 12, bond-order single }, { atom-id-1 11, atom-id-2 24, bond-order single }, { atom-id-1 12, atom-id-2 13, bond-order single }, { atom-id-1 12, atom-id-2 19, bond-order single }, { atom-id-1 13, atom-id-2 14, bond-order double }, { atom-id-1 13, atom-id-2 15, bond-order single }, { atom-id-1 15, atom-id-2 16, bond-order double }, { atom-id-1 16, atom-id-2 17, bond-order single }, { atom-id-1 16, atom-id-2 18, bond-order single }, { atom-id-1 17, atom-id-2 25, bond-order single }, { atom-id-1 17, atom-id-2 26, bond-order single }, { atom-id-1 18, atom-id-2 19, bond-order double }, { atom-id-1 18, atom-id-2 27, bond-order single }, { atom-id-1 19, atom-id-2 28, bond-order single }, { atom-id-1 29, atom-id-2 9, bond-order single }, { atom-id-1 2, atom-id-2 30, bond-order single }, { atom-id-1 3, atom-id-2 31, bond-order single }, { atom-id-1 10, atom-id-2 32, bond-order single }, { atom-id-1 10, atom-id-2 33, bond-order single }, { atom-id-1 32, atom-id-2 34, bond-order single } }, chiral-centers { { c 8, n1 6, n2 10, n3 9, sign positive }, { c 6, n1 5, n2 8, n3 7, sign positive }, { c 11, n1 7, n2 10, n3 12, sign positive } } }, { id 78, descr { name " C RNA 5'OH" }, residue-type ribonucleotide, iupac-code { "C" }, atoms { { id 1, name " O5*", iupac-code { " O5*" }, element o, ionizable-proton false }, { id 2, name " C5*", iupac-code { " C5*" }, element c, ionizable-proton false }, { id 3, name " C4*", iupac-code { " C4*" }, element c, ionizable-proton false }, { id 4, name " O4*", iupac-code { " O4*" }, element o, ionizable-proton false }, { id 5, name " C3*", iupac-code { " C3*" }, element c, ionizable-proton false }, { id 6, name " O3*", iupac-code { " O3*" }, element o, ionizable-proton false }, { id 7, name " C2*", iupac-code { " C2*" }, element c, ionizable-proton false }, { id 8, name " C1*", iupac-code { " C1*" }, element c, ionizable-proton false }, { id 9, name " N1 ", iupac-code { " N1 " }, element n, ionizable-proton false }, { id 10, name " C2 ", iupac-code { " C2 " }, element c, ionizable-proton false }, { id 11, name " O2 ", iupac-code { " O2 " }, element o, ionizable-proton false }, { id 12, name " N3 ", iupac-code { " N3 " }, element n, ionizable-proton false }, { id 13, name " C4 ", iupac-code { " C4 " }, element c, ionizable-proton false }, { id 14, name " N4 ", iupac-code { " N4 " }, element n, ionizable-proton false }, { id 15, name " C5 ", iupac-code { " C5 " }, element c, ionizable-proton false }, { id 16, name " C6 ", iupac-code { " C6 " }, element c, ionizable-proton false }, { id 17, name "1H5*", iupac-code { "1H5*" }, element h, ionizable-proton false }, { id 18, name "2H5*", iupac-code { "2H5*" }, element h, ionizable-proton false }, { id 19, name " H4*", iupac-code { " H4*" }, element h, ionizable-proton false }, { id 20, name " H3*", iupac-code { " H3*" }, element h, ionizable-proton false }, { id 21, name " H1*", iupac-code { " H1*" }, element h, ionizable-proton false }, { id 22, name "1HN4", iupac-code { "1HN4" }, element h, ionizable-proton false }, { id 23, name "2HN4", iupac-code { "2HN4" }, element h, ionizable-proton false }, { id 24, name " H5 ", iupac-code { " H5 " }, element h, ionizable-proton false }, { id 25, name " H6 ", iupac-code { " H6 " }, element h, ionizable-proton false }, { id 26, name " H5T", iupac-code { " H5T" }, element h, ionizable-proton false }, { id 27, name " O2*", iupac-code { " O2*" }, element o, ionizable-proton false }, { id 28, name " H2*", iupac-code { " H2*" }, element h, ionizable-proton false }, { id 29, name " HO2", iupac-code { " HO2" }, element h, ionizable-proton false } }, bonds { { atom-id-1 1, atom-id-2 2, bond-order single }, { atom-id-1 2, atom-id-2 3, bond-order single }, { atom-id-1 2, atom-id-2 17, bond-order single }, { atom-id-1 2, atom-id-2 18, bond-order single }, { atom-id-1 3, atom-id-2 4, bond-order single }, { atom-id-1 3, atom-id-2 5, bond-order single }, { atom-id-1 3, atom-id-2 19, bond-order single }, { atom-id-1 4, atom-id-2 8, bond-order single }, { atom-id-1 5, atom-id-2 6, bond-order single }, { atom-id-1 5, atom-id-2 7, bond-order single }, { atom-id-1 5, atom-id-2 20, bond-order single }, { atom-id-1 7, atom-id-2 8, bond-order single }, { atom-id-1 8, atom-id-2 9, bond-order single }, { atom-id-1 8, atom-id-2 21, bond-order single }, { atom-id-1 9, atom-id-2 10, bond-order single }, { atom-id-1 9, atom-id-2 16, bond-order single }, { atom-id-1 10, atom-id-2 11, bond-order double }, { atom-id-1 10, atom-id-2 12, bond-order single }, { atom-id-1 12, atom-id-2 13, bond-order double }, { atom-id-1 13, atom-id-2 14, bond-order single }, { atom-id-1 13, atom-id-2 15, bond-order single }, { atom-id-1 14, atom-id-2 22, bond-order single }, { atom-id-1 14, atom-id-2 23, bond-order single }, { atom-id-1 15, atom-id-2 16, bond-order double }, { atom-id-1 15, atom-id-2 24, bond-order single }, { atom-id-1 16, atom-id-2 25, bond-order single }, { atom-id-1 26, atom-id-2 1, bond-order single }, { atom-id-1 7, atom-id-2 27, bond-order single }, { atom-id-1 7, atom-id-2 28, bond-order single }, { atom-id-1 27, atom-id-2 29, bond-order single } }, chiral-centers { { c 5, n1 3, n2 7, n3 6, sign positive }, { c 3, n1 2, n2 5, n3 4, sign positive }, { c 8, n1 4, n2 7, n3 9, sign positive } } }, { id 79, descr { name " G RNA" }, residue-type ribonucleotide, iupac-code { "G" }, atoms { { id 1, name " P ", iupac-code { " P " }, element p, ionizable-proton false }, { id 2, name " O1P", iupac-code { " O1P" }, element o, ionizable-proton false }, { id 3, name " O2P", iupac-code { " O2P" }, element o, ionizable-proton false }, { id 4, name " O5*", iupac-code { " O5*" }, element o, ionizable-proton false }, { id 5, name " C5*", iupac-code { " C5*" }, element c, ionizable-proton false }, { id 6, name " C4*", iupac-code { " C4*" }, element c, ionizable-proton false }, { id 7, name " O4*", iupac-code { " O4*" }, element o, ionizable-proton false }, { id 8, name " C3*", iupac-code { " C3*" }, element c, ionizable-proton false }, { id 9, name " O3*", iupac-code { " O3*" }, element o, ionizable-proton false }, { id 10, name " C2*", iupac-code { " C2*" }, element c, ionizable-proton false }, { id 11, name " C1*", iupac-code { " C1*" }, element c, ionizable-proton false }, { id 12, name " N9 ", iupac-code { " N9 " }, element n, ionizable-proton false }, { id 13, name " C8 ", iupac-code { " C8 " }, element c, ionizable-proton false }, { id 14, name " N7 ", iupac-code { " N7 " }, element n, ionizable-proton false }, { id 15, name " C5 ", iupac-code { " C5 " }, element c, ionizable-proton false }, { id 16, name " C6 ", iupac-code { " C6 " }, element c, ionizable-proton false }, { id 17, name " O6 ", iupac-code { " O6 " }, element o, ionizable-proton false }, { id 18, name " N1 ", iupac-code { " N1 " }, element n, ionizable-proton false }, { id 19, name " C2 ", iupac-code { " C2 " }, element c, ionizable-proton false }, { id 20, name " N2 ", iupac-code { " N2 " }, element n, ionizable-proton false }, { id 21, name " N3 ", iupac-code { " N3 " }, element n, ionizable-proton false }, { id 22, name " C4 ", iupac-code { " C4 " }, element c, ionizable-proton false }, { id 23, name "1H5*", iupac-code { "1H5*" }, element h, ionizable-proton false }, { id 24, name "2H5*", iupac-code { "2H5*" }, element h, ionizable-proton false }, { id 25, name " H4*", iupac-code { " H4*" }, element h, ionizable-proton false }, { id 26, name " H3*", iupac-code { " H3*" }, element h, ionizable-proton false }, { id 27, name " H1*", iupac-code { " H1*" }, element h, ionizable-proton false }, { id 28, name " H8 ", iupac-code { " H8 " }, element h, ionizable-proton false }, { id 29, name " H1 ", iupac-code { " H1 " }, element h, ionizable-proton false }, { id 30, name "1HN2", iupac-code { "1HN2" }, element h, ionizable-proton false }, { id 31, name "2HN2", iupac-code { "2HN2" }, element h, ionizable-proton false }, { id 32, name " H1P", iupac-code { " H1P" }, element h, ionizable-proton true }, { id 33, name " H2P", iupac-code { " H2P" }, element h, ionizable-proton true }, { id 34, name " O2*", iupac-code { " O2*" }, element o, ionizable-proton false }, { id 35, name " H2*", iupac-code { " H2*" }, element h, ionizable-proton false }, { id 36, name " HO2", iupac-code { " HO2" }, element h, ionizable-proton false } }, bonds { { atom-id-1 1, atom-id-2 2, bond-order partial-double }, { atom-id-1 1, atom-id-2 3, bond-order partial-double }, { atom-id-1 1, atom-id-2 4, bond-order single }, { atom-id-1 4, atom-id-2 5, bond-order single }, { atom-id-1 5, atom-id-2 6, bond-order single }, { atom-id-1 5, atom-id-2 23, bond-order single }, { atom-id-1 5, atom-id-2 24, bond-order single }, { atom-id-1 6, atom-id-2 7, bond-order single }, { atom-id-1 6, atom-id-2 8, bond-order single }, { atom-id-1 6, atom-id-2 25, bond-order single }, { atom-id-1 7, atom-id-2 11, bond-order single }, { atom-id-1 8, atom-id-2 9, bond-order single }, { atom-id-1 8, atom-id-2 10, bond-order single }, { atom-id-1 8, atom-id-2 26, bond-order single }, { atom-id-1 10, atom-id-2 11, bond-order single }, { atom-id-1 11, atom-id-2 12, bond-order single }, { atom-id-1 11, atom-id-2 27, bond-order single }, { atom-id-1 12, atom-id-2 13, bond-order single }, { atom-id-1 12, atom-id-2 22, bond-order single }, { atom-id-1 13, atom-id-2 14, bond-order double }, { atom-id-1 13, atom-id-2 28, bond-order single }, { atom-id-1 14, atom-id-2 15, bond-order single }, { atom-id-1 15, atom-id-2 16, bond-order single }, { atom-id-1 15, atom-id-2 22, bond-order double }, { atom-id-1 16, atom-id-2 17, bond-order double }, { atom-id-1 16, atom-id-2 18, bond-order single }, { atom-id-1 18, atom-id-2 19, bond-order single }, { atom-id-1 18, atom-id-2 29, bond-order single }, { atom-id-1 19, atom-id-2 20, bond-order single }, { atom-id-1 19, atom-id-2 21, bond-order double }, { atom-id-1 20, atom-id-2 30, bond-order single }, { atom-id-1 20, atom-id-2 31, bond-order single }, { atom-id-1 21, atom-id-2 22, bond-order single }, { atom-id-1 2, atom-id-2 32, bond-order single }, { atom-id-1 3, atom-id-2 33, bond-order single }, { atom-id-1 10, atom-id-2 34, bond-order single }, { atom-id-1 10, atom-id-2 35, bond-order single }, { atom-id-1 34, atom-id-2 36, bond-order single } }, chiral-centers { { c 8, n1 6, n2 10, n3 9, sign positive }, { c 6, n1 5, n2 8, n3 7, sign positive }, { c 11, n1 7, n2 10, n3 12, sign positive } } }, { id 80, descr { name " G RNA 3'OH" }, residue-type ribonucleotide, iupac-code { "G" }, atoms { { id 1, name " P ", iupac-code { " P " }, element p, ionizable-proton false }, { id 2, name " O1P", iupac-code { " O1P" }, element o, ionizable-proton false }, { id 3, name " O2P", iupac-code { " O2P" }, element o, ionizable-proton false }, { id 4, name " O5*", iupac-code { " O5*" }, element o, ionizable-proton false }, { id 5, name " C5*", iupac-code { " C5*" }, element c, ionizable-proton false }, { id 6, name " C4*", iupac-code { " C4*" }, element c, ionizable-proton false }, { id 7, name " O4*", iupac-code { " O4*" }, element o, ionizable-proton false }, { id 8, name " C3*", iupac-code { " C3*" }, element c, ionizable-proton false }, { id 9, name " O3*", iupac-code { " O3*" }, element o, ionizable-proton false }, { id 10, name " C2*", iupac-code { " C2*" }, element c, ionizable-proton false }, { id 11, name " C1*", iupac-code { " C1*" }, element c, ionizable-proton false }, { id 12, name " N9 ", iupac-code { " N9 " }, element n, ionizable-proton false }, { id 13, name " C8 ", iupac-code { " C8 " }, element c, ionizable-proton false }, { id 14, name " N7 ", iupac-code { " N7 " }, element n, ionizable-proton false }, { id 15, name " C5 ", iupac-code { " C5 " }, element c, ionizable-proton false }, { id 16, name " C6 ", iupac-code { " C6 " }, element c, ionizable-proton false }, { id 17, name " O6 ", iupac-code { " O6 " }, element o, ionizable-proton false }, { id 18, name " N1 ", iupac-code { " N1 " }, element n, ionizable-proton false }, { id 19, name " C2 ", iupac-code { " C2 " }, element c, ionizable-proton false }, { id 20, name " N2 ", iupac-code { " N2 " }, element n, ionizable-proton false }, { id 21, name " N3 ", iupac-code { " N3 " }, element n, ionizable-proton false }, { id 22, name " C4 ", iupac-code { " C4 " }, element c, ionizable-proton false }, { id 23, name "1H5*", iupac-code { "1H5*" }, element h, ionizable-proton false }, { id 24, name "2H5*", iupac-code { "2H5*" }, element h, ionizable-proton false }, { id 25, name " H4*", iupac-code { " H4*" }, element h, ionizable-proton false }, { id 26, name " H3*", iupac-code { " H3*" }, element h, ionizable-proton false }, { id 27, name " H1*", iupac-code { " H1*" }, element h, ionizable-proton false }, { id 28, name " H8 ", iupac-code { " H8 " }, element h, ionizable-proton false }, { id 29, name " H1 ", iupac-code { " H1 " }, element h, ionizable-proton false }, { id 30, name "1HN2", iupac-code { "1HN2" }, element h, ionizable-proton false }, { id 31, name "2HN2", iupac-code { "2HN2" }, element h, ionizable-proton false }, { id 32, name " H3T", iupac-code { " H3T" }, element h, ionizable-proton false }, { id 33, name " H1P", iupac-code { " H1P" }, element h, ionizable-proton true }, { id 34, name " H2P", iupac-code { " H2P" }, element h, ionizable-proton true }, { id 35, name " O2*", iupac-code { " O2*" }, element o, ionizable-proton false }, { id 36, name " H2*", iupac-code { " H2*" }, element h, ionizable-proton false }, { id 37, name " HO2", iupac-code { " HO2" }, element h, ionizable-proton false } }, bonds { { atom-id-1 1, atom-id-2 2, bond-order partial-double }, { atom-id-1 1, atom-id-2 3, bond-order partial-double }, { atom-id-1 1, atom-id-2 4, bond-order single }, { atom-id-1 4, atom-id-2 5, bond-order single }, { atom-id-1 5, atom-id-2 6, bond-order single }, { atom-id-1 5, atom-id-2 23, bond-order single }, { atom-id-1 5, atom-id-2 24, bond-order single }, { atom-id-1 6, atom-id-2 7, bond-order single }, { atom-id-1 6, atom-id-2 8, bond-order single }, { atom-id-1 6, atom-id-2 25, bond-order single }, { atom-id-1 7, atom-id-2 11, bond-order single }, { atom-id-1 8, atom-id-2 9, bond-order single }, { atom-id-1 8, atom-id-2 10, bond-order single }, { atom-id-1 8, atom-id-2 26, bond-order single }, { atom-id-1 10, atom-id-2 11, bond-order single }, { atom-id-1 11, atom-id-2 12, bond-order single }, { atom-id-1 11, atom-id-2 27, bond-order single }, { atom-id-1 12, atom-id-2 13, bond-order single }, { atom-id-1 12, atom-id-2 22, bond-order single }, { atom-id-1 13, atom-id-2 14, bond-order double }, { atom-id-1 13, atom-id-2 28, bond-order single }, { atom-id-1 14, atom-id-2 15, bond-order single }, { atom-id-1 15, atom-id-2 16, bond-order single }, { atom-id-1 15, atom-id-2 22, bond-order double }, { atom-id-1 16, atom-id-2 17, bond-order double }, { atom-id-1 16, atom-id-2 18, bond-order single }, { atom-id-1 18, atom-id-2 19, bond-order single }, { atom-id-1 18, atom-id-2 29, bond-order single }, { atom-id-1 19, atom-id-2 20, bond-order single }, { atom-id-1 19, atom-id-2 21, bond-order double }, { atom-id-1 20, atom-id-2 30, bond-order single }, { atom-id-1 20, atom-id-2 31, bond-order single }, { atom-id-1 21, atom-id-2 22, bond-order single }, { atom-id-1 32, atom-id-2 9, bond-order single }, { atom-id-1 2, atom-id-2 33, bond-order single }, { atom-id-1 3, atom-id-2 34, bond-order single }, { atom-id-1 10, atom-id-2 35, bond-order single }, { atom-id-1 10, atom-id-2 36, bond-order single }, { atom-id-1 35, atom-id-2 37, bond-order single } }, chiral-centers { { c 8, n1 6, n2 10, n3 9, sign positive }, { c 6, n1 5, n2 8, n3 7, sign positive }, { c 11, n1 7, n2 10, n3 12, sign positive } } }, { id 81, descr { name " G RNA 5'OH" }, residue-type ribonucleotide, iupac-code { "G" }, atoms { { id 1, name " O5*", iupac-code { " O5*" }, element o, ionizable-proton false }, { id 2, name " C5*", iupac-code { " C5*" }, element c, ionizable-proton false }, { id 3, name " C4*", iupac-code { " C4*" }, element c, ionizable-proton false }, { id 4, name " O4*", iupac-code { " O4*" }, element o, ionizable-proton false }, { id 5, name " C3*", iupac-code { " C3*" }, element c, ionizable-proton false }, { id 6, name " O3*", iupac-code { " O3*" }, element o, ionizable-proton false }, { id 7, name " C2*", iupac-code { " C2*" }, element c, ionizable-proton false }, { id 8, name " C1*", iupac-code { " C1*" }, element c, ionizable-proton false }, { id 9, name " N9 ", iupac-code { " N9 " }, element n, ionizable-proton false }, { id 10, name " C8 ", iupac-code { " C8 " }, element c, ionizable-proton false }, { id 11, name " N7 ", iupac-code { " N7 " }, element n, ionizable-proton false }, { id 12, name " C5 ", iupac-code { " C5 " }, element c, ionizable-proton false }, { id 13, name " C6 ", iupac-code { " C6 " }, element c, ionizable-proton false }, { id 14, name " O6 ", iupac-code { " O6 " }, element o, ionizable-proton false }, { id 15, name " N1 ", iupac-code { " N1 " }, element n, ionizable-proton false }, { id 16, name " C2 ", iupac-code { " C2 " }, element c, ionizable-proton false }, { id 17, name " N2 ", iupac-code { " N2 " }, element n, ionizable-proton false }, { id 18, name " N3 ", iupac-code { " N3 " }, element n, ionizable-proton false }, { id 19, name " C4 ", iupac-code { " C4 " }, element c, ionizable-proton false }, { id 20, name "1H5*", iupac-code { "1H5*" }, element h, ionizable-proton false }, { id 21, name "2H5*", iupac-code { "2H5*" }, element h, ionizable-proton false }, { id 22, name " H4*", iupac-code { " H4*" }, element h, ionizable-proton false }, { id 23, name " H3*", iupac-code { " H3*" }, element h, ionizable-proton false }, { id 24, name " H1*", iupac-code { " H1*" }, element h, ionizable-proton false }, { id 25, name " H8 ", iupac-code { " H8 " }, element h, ionizable-proton false }, { id 26, name " H1 ", iupac-code { " H1 " }, element h, ionizable-proton false }, { id 27, name "1HN2", iupac-code { "1HN2" }, element h, ionizable-proton false }, { id 28, name "2HN2", iupac-code { "2HN2" }, element h, ionizable-proton false }, { id 29, name " H5T", iupac-code { " H5T" }, element h, ionizable-proton false }, { id 30, name " O2*", iupac-code { " O2*" }, element o, ionizable-proton false }, { id 31, name " H2*", iupac-code { " H2*" }, element h, ionizable-proton false }, { id 32, name " HO2", iupac-code { " HO2" }, element h, ionizable-proton false } }, bonds { { atom-id-1 1, atom-id-2 2, bond-order single }, { atom-id-1 2, atom-id-2 3, bond-order single }, { atom-id-1 2, atom-id-2 20, bond-order single }, { atom-id-1 2, atom-id-2 21, bond-order single }, { atom-id-1 3, atom-id-2 4, bond-order single }, { atom-id-1 3, atom-id-2 5, bond-order single }, { atom-id-1 3, atom-id-2 22, bond-order single }, { atom-id-1 4, atom-id-2 8, bond-order single }, { atom-id-1 5, atom-id-2 6, bond-order single }, { atom-id-1 5, atom-id-2 7, bond-order single }, { atom-id-1 5, atom-id-2 23, bond-order single }, { atom-id-1 7, atom-id-2 8, bond-order single }, { atom-id-1 8, atom-id-2 9, bond-order single }, { atom-id-1 8, atom-id-2 24, bond-order single }, { atom-id-1 9, atom-id-2 10, bond-order single }, { atom-id-1 9, atom-id-2 19, bond-order single }, { atom-id-1 10, atom-id-2 11, bond-order double }, { atom-id-1 10, atom-id-2 25, bond-order single }, { atom-id-1 11, atom-id-2 12, bond-order single }, { atom-id-1 12, atom-id-2 13, bond-order single }, { atom-id-1 12, atom-id-2 19, bond-order double }, { atom-id-1 13, atom-id-2 14, bond-order double }, { atom-id-1 13, atom-id-2 15, bond-order single }, { atom-id-1 15, atom-id-2 16, bond-order single }, { atom-id-1 15, atom-id-2 26, bond-order single }, { atom-id-1 16, atom-id-2 17, bond-order single }, { atom-id-1 16, atom-id-2 18, bond-order double }, { atom-id-1 17, atom-id-2 27, bond-order single }, { atom-id-1 17, atom-id-2 28, bond-order single }, { atom-id-1 18, atom-id-2 19, bond-order single }, { atom-id-1 29, atom-id-2 1, bond-order single }, { atom-id-1 7, atom-id-2 30, bond-order single }, { atom-id-1 7, atom-id-2 31, bond-order single }, { atom-id-1 30, atom-id-2 32, bond-order single } }, chiral-centers { { c 5, n1 3, n2 7, n3 6, sign positive }, { c 3, n1 2, n2 5, n3 4, sign positive }, { c 8, n1 4, n2 7, n3 9, sign positive } } }, { id 82, descr { name " U RNA" }, residue-type ribonucleotide, iupac-code { "U" }, atoms { { id 1, name " P ", iupac-code { " P " }, element p, ionizable-proton false }, { id 2, name " O1P", iupac-code { " O1P" }, element o, ionizable-proton false }, { id 3, name " O2P", iupac-code { " O2P" }, element o, ionizable-proton false }, { id 4, name " O5*", iupac-code { " O5*" }, element o, ionizable-proton false }, { id 5, name " C5*", iupac-code { " C5*" }, element c, ionizable-proton false }, { id 6, name " C4*", iupac-code { " C4*" }, element c, ionizable-proton false }, { id 7, name " O4*", iupac-code { " O4*" }, element o, ionizable-proton false }, { id 8, name " C3*", iupac-code { " C3*" }, element c, ionizable-proton false }, { id 9, name " O3*", iupac-code { " O3*" }, element o, ionizable-proton false }, { id 10, name " C2*", iupac-code { " C2*" }, element c, ionizable-proton false }, { id 11, name " C1*", iupac-code { " C1*" }, element c, ionizable-proton false }, { id 12, name " N1 ", iupac-code { " N1 " }, element n, ionizable-proton false }, { id 13, name " C2 ", iupac-code { " C2 " }, element c, ionizable-proton false }, { id 14, name " O2 ", iupac-code { " O2 " }, element o, ionizable-proton false }, { id 15, name " N3 ", iupac-code { " N3 " }, element n, ionizable-proton false }, { id 16, name " C4 ", iupac-code { " C4 " }, element c, ionizable-proton false }, { id 17, name " O4 ", iupac-code { " O4 " }, element o, ionizable-proton false }, { id 18, name " C5 ", iupac-code { " C5 " }, element c, ionizable-proton false }, { id 19, name " C6 ", iupac-code { " C6 " }, element c, ionizable-proton false }, { id 20, name "1H5*", iupac-code { "1H5*" }, element h, ionizable-proton false }, { id 21, name "2H5*", iupac-code { "2H5*" }, element h, ionizable-proton false }, { id 22, name " H4*", iupac-code { " H4*" }, element h, ionizable-proton false }, { id 23, name " H3*", iupac-code { " H3*" }, element h, ionizable-proton false }, { id 24, name " H1*", iupac-code { " H1*" }, element h, ionizable-proton false }, { id 25, name " H3 ", iupac-code { " H3 " }, element h, ionizable-proton false }, { id 26, name " H6 ", iupac-code { " H6 " }, element h, ionizable-proton false }, { id 27, name " H1P", iupac-code { " H1P" }, element h, ionizable-proton true }, { id 28, name " H2P", iupac-code { " H2P" }, element h, ionizable-proton true }, { id 29, name " O2*", iupac-code { " O2*" }, element o, ionizable-proton false }, { id 30, name " H2*", iupac-code { " H2*" }, element h, ionizable-proton false }, { id 31, name " HO2", iupac-code { " HO2" }, element h, ionizable-proton false }, { id 32, name " H5 ", iupac-code { " H5 " }, element h, ionizable-proton false } }, bonds { { atom-id-1 1, atom-id-2 2, bond-order partial-double }, { atom-id-1 1, atom-id-2 3, bond-order partial-double }, { atom-id-1 1, atom-id-2 4, bond-order single }, { atom-id-1 4, atom-id-2 5, bond-order single }, { atom-id-1 5, atom-id-2 6, bond-order single }, { atom-id-1 5, atom-id-2 20, bond-order single }, { atom-id-1 5, atom-id-2 21, bond-order single }, { atom-id-1 6, atom-id-2 7, bond-order single }, { atom-id-1 6, atom-id-2 8, bond-order single }, { atom-id-1 6, atom-id-2 22, bond-order single }, { atom-id-1 7, atom-id-2 11, bond-order single }, { atom-id-1 8, atom-id-2 9, bond-order single }, { atom-id-1 8, atom-id-2 10, bond-order single }, { atom-id-1 8, atom-id-2 23, bond-order single }, { atom-id-1 10, atom-id-2 11, bond-order single }, { atom-id-1 11, atom-id-2 12, bond-order single }, { atom-id-1 11, atom-id-2 24, bond-order single }, { atom-id-1 12, atom-id-2 13, bond-order single }, { atom-id-1 12, atom-id-2 19, bond-order single }, { atom-id-1 13, atom-id-2 14, bond-order double }, { atom-id-1 13, atom-id-2 15, bond-order single }, { atom-id-1 15, atom-id-2 16, bond-order single }, { atom-id-1 15, atom-id-2 25, bond-order single }, { atom-id-1 16, atom-id-2 17, bond-order double }, { atom-id-1 16, atom-id-2 18, bond-order single }, { atom-id-1 18, atom-id-2 19, bond-order double }, { atom-id-1 19, atom-id-2 26, bond-order single }, { atom-id-1 2, atom-id-2 27, bond-order single }, { atom-id-1 3, atom-id-2 28, bond-order single }, { atom-id-1 10, atom-id-2 29, bond-order single }, { atom-id-1 10, atom-id-2 30, bond-order single }, { atom-id-1 29, atom-id-2 31, bond-order single }, { atom-id-1 18, atom-id-2 32, bond-order single } }, chiral-centers { { c 8, n1 6, n2 10, n3 9, sign positive }, { c 6, n1 5, n2 8, n3 7, sign positive }, { c 11, n1 7, n2 10, n3 12, sign positive } } }, { id 83, descr { name " U RNA 3'OH" }, residue-type ribonucleotide, iupac-code { "U" }, atoms { { id 1, name " P ", iupac-code { " P " }, element p, ionizable-proton false }, { id 2, name " O1P", iupac-code { " O1P" }, element o, ionizable-proton false }, { id 3, name " O2P", iupac-code { " O2P" }, element o, ionizable-proton false }, { id 4, name " O5*", iupac-code { " O5*" }, element o, ionizable-proton false }, { id 5, name " C5*", iupac-code { " C5*" }, element c, ionizable-proton false }, { id 6, name " C4*", iupac-code { " C4*" }, element c, ionizable-proton false }, { id 7, name " O4*", iupac-code { " O4*" }, element o, ionizable-proton false }, { id 8, name " C3*", iupac-code { " C3*" }, element c, ionizable-proton false }, { id 9, name " O3*", iupac-code { " O3*" }, element o, ionizable-proton false }, { id 10, name " C2*", iupac-code { " C2*" }, element c, ionizable-proton false }, { id 11, name " C1*", iupac-code { " C1*" }, element c, ionizable-proton false }, { id 12, name " N1 ", iupac-code { " N1 " }, element n, ionizable-proton false }, { id 13, name " C2 ", iupac-code { " C2 " }, element c, ionizable-proton false }, { id 14, name " O2 ", iupac-code { " O2 " }, element o, ionizable-proton false }, { id 15, name " N3 ", iupac-code { " N3 " }, element n, ionizable-proton false }, { id 16, name " C4 ", iupac-code { " C4 " }, element c, ionizable-proton false }, { id 17, name " O4 ", iupac-code { " O4 " }, element o, ionizable-proton false }, { id 18, name " C5 ", iupac-code { " C5 " }, element c, ionizable-proton false }, { id 19, name " C6 ", iupac-code { " C6 " }, element c, ionizable-proton false }, { id 20, name "1H5*", iupac-code { "1H5*" }, element h, ionizable-proton false }, { id 21, name "2H5*", iupac-code { "2H5*" }, element h, ionizable-proton false }, { id 22, name " H4*", iupac-code { " H4*" }, element h, ionizable-proton false }, { id 23, name " H3*", iupac-code { " H3*" }, element h, ionizable-proton false }, { id 24, name " H1*", iupac-code { " H1*" }, element h, ionizable-proton false }, { id 25, name " H3 ", iupac-code { " H3 " }, element h, ionizable-proton false }, { id 26, name " H6 ", iupac-code { " H6 " }, element h, ionizable-proton false }, { id 27, name " H3T", iupac-code { " H3T" }, element h, ionizable-proton false }, { id 28, name " H1P", iupac-code { " H1P" }, element h, ionizable-proton true }, { id 29, name " H2P", iupac-code { " H2P" }, element h, ionizable-proton true }, { id 30, name " O2*", iupac-code { " O2*" }, element o, ionizable-proton false }, { id 31, name " H2*", iupac-code { " H2*" }, element h, ionizable-proton false }, { id 32, name " HO2", iupac-code { " HO2" }, element h, ionizable-proton false }, { id 33, name " H5 ", iupac-code { " H5 " }, element h, ionizable-proton false } }, bonds { { atom-id-1 1, atom-id-2 2, bond-order partial-double }, { atom-id-1 1, atom-id-2 3, bond-order partial-double }, { atom-id-1 1, atom-id-2 4, bond-order single }, { atom-id-1 4, atom-id-2 5, bond-order single }, { atom-id-1 5, atom-id-2 6, bond-order single }, { atom-id-1 5, atom-id-2 20, bond-order single }, { atom-id-1 5, atom-id-2 21, bond-order single }, { atom-id-1 6, atom-id-2 7, bond-order single }, { atom-id-1 6, atom-id-2 8, bond-order single }, { atom-id-1 6, atom-id-2 22, bond-order single }, { atom-id-1 7, atom-id-2 11, bond-order single }, { atom-id-1 8, atom-id-2 9, bond-order single }, { atom-id-1 8, atom-id-2 10, bond-order single }, { atom-id-1 8, atom-id-2 23, bond-order single }, { atom-id-1 10, atom-id-2 11, bond-order single }, { atom-id-1 11, atom-id-2 12, bond-order single }, { atom-id-1 11, atom-id-2 24, bond-order single }, { atom-id-1 12, atom-id-2 13, bond-order single }, { atom-id-1 12, atom-id-2 19, bond-order single }, { atom-id-1 13, atom-id-2 14, bond-order double }, { atom-id-1 13, atom-id-2 15, bond-order single }, { atom-id-1 15, atom-id-2 16, bond-order single }, { atom-id-1 15, atom-id-2 25, bond-order single }, { atom-id-1 16, atom-id-2 17, bond-order double }, { atom-id-1 16, atom-id-2 18, bond-order single }, { atom-id-1 18, atom-id-2 19, bond-order double }, { atom-id-1 19, atom-id-2 26, bond-order single }, { atom-id-1 27, atom-id-2 9, bond-order single }, { atom-id-1 2, atom-id-2 28, bond-order single }, { atom-id-1 3, atom-id-2 29, bond-order single }, { atom-id-1 10, atom-id-2 30, bond-order single }, { atom-id-1 10, atom-id-2 31, bond-order single }, { atom-id-1 30, atom-id-2 32, bond-order single }, { atom-id-1 18, atom-id-2 33, bond-order single } }, chiral-centers { { c 8, n1 6, n2 10, n3 9, sign positive }, { c 6, n1 5, n2 8, n3 7, sign positive }, { c 11, n1 7, n2 10, n3 12, sign positive } } }, { id 84, descr { name " U RNA 5'OH" }, residue-type ribonucleotide, iupac-code { "U" }, atoms { { id 1, name " O5*", iupac-code { " O5*" }, element o, ionizable-proton false }, { id 2, name " C5*", iupac-code { " C5*" }, element c, ionizable-proton false }, { id 3, name " C4*", iupac-code { " C4*" }, element c, ionizable-proton false }, { id 4, name " O4*", iupac-code { " O4*" }, element o, ionizable-proton false }, { id 5, name " C3*", iupac-code { " C3*" }, element c, ionizable-proton false }, { id 6, name " O3*", iupac-code { " O3*" }, element o, ionizable-proton false }, { id 7, name " C2*", iupac-code { " C2*" }, element c, ionizable-proton false }, { id 8, name " C1*", iupac-code { " C1*" }, element c, ionizable-proton false }, { id 9, name " N1 ", iupac-code { " N1 " }, element n, ionizable-proton false }, { id 10, name " C2 ", iupac-code { " C2 " }, element c, ionizable-proton false }, { id 11, name " O2 ", iupac-code { " O2 " }, element o, ionizable-proton false }, { id 12, name " N3 ", iupac-code { " N3 " }, element n, ionizable-proton false }, { id 13, name " C4 ", iupac-code { " C4 " }, element c, ionizable-proton false }, { id 14, name " O4 ", iupac-code { " O4 " }, element o, ionizable-proton false }, { id 15, name " C5 ", iupac-code { " C5 " }, element c, ionizable-proton false }, { id 16, name " C6 ", iupac-code { " C6 " }, element c, ionizable-proton false }, { id 17, name "1H5*", iupac-code { "1H5*" }, element h, ionizable-proton false }, { id 18, name "2H5*", iupac-code { "2H5*" }, element h, ionizable-proton false }, { id 19, name " H4*", iupac-code { " H4*" }, element h, ionizable-proton false }, { id 20, name " H3*", iupac-code { " H3*" }, element h, ionizable-proton false }, { id 21, name " H1*", iupac-code { " H1*" }, element h, ionizable-proton false }, { id 22, name " H3 ", iupac-code { " H3 " }, element h, ionizable-proton false }, { id 23, name " H6 ", iupac-code { " H6 " }, element h, ionizable-proton false }, { id 24, name " H5T", iupac-code { " H5T" }, element h, ionizable-proton false }, { id 25, name " O2*", iupac-code { " O2*" }, element o, ionizable-proton false }, { id 26, name " H2*", iupac-code { " H2*" }, element h, ionizable-proton false }, { id 27, name " HO2", iupac-code { " HO2" }, element h, ionizable-proton false }, { id 28, name " H5 ", iupac-code { " H5 " }, element h, ionizable-proton false } }, bonds { { atom-id-1 1, atom-id-2 2, bond-order single }, { atom-id-1 2, atom-id-2 3, bond-order single }, { atom-id-1 2, atom-id-2 17, bond-order single }, { atom-id-1 2, atom-id-2 18, bond-order single }, { atom-id-1 3, atom-id-2 4, bond-order single }, { atom-id-1 3, atom-id-2 5, bond-order single }, { atom-id-1 3, atom-id-2 19, bond-order single }, { atom-id-1 4, atom-id-2 8, bond-order single }, { atom-id-1 5, atom-id-2 6, bond-order single }, { atom-id-1 5, atom-id-2 7, bond-order single }, { atom-id-1 5, atom-id-2 20, bond-order single }, { atom-id-1 7, atom-id-2 8, bond-order single }, { atom-id-1 8, atom-id-2 9, bond-order single }, { atom-id-1 8, atom-id-2 21, bond-order single }, { atom-id-1 9, atom-id-2 10, bond-order single }, { atom-id-1 9, atom-id-2 16, bond-order single }, { atom-id-1 10, atom-id-2 11, bond-order double }, { atom-id-1 10, atom-id-2 12, bond-order single }, { atom-id-1 12, atom-id-2 13, bond-order single }, { atom-id-1 12, atom-id-2 22, bond-order single }, { atom-id-1 13, atom-id-2 14, bond-order double }, { atom-id-1 13, atom-id-2 15, bond-order single }, { atom-id-1 15, atom-id-2 16, bond-order double }, { atom-id-1 16, atom-id-2 23, bond-order single }, { atom-id-1 24, atom-id-2 1, bond-order single }, { atom-id-1 7, atom-id-2 25, bond-order single }, { atom-id-1 7, atom-id-2 26, bond-order single }, { atom-id-1 25, atom-id-2 27, bond-order single }, { atom-id-1 15, atom-id-2 28, bond-order single } }, chiral-centers { { c 5, n1 3, n2 7, n3 6, sign positive }, { c 3, n1 2, n2 5, n3 4, sign positive }, { c 8, n1 4, n2 7, n3 9, sign positive } } } } } ugene-1.9.8/src/corelibs/U2Formats/src/0000755000175000017500000000000011651544332016320 5ustar ilyailyaugene-1.9.8/src/corelibs/U2Formats/src/NEXUSFormat.h0000644000175000017500000000363611651544332020554 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_NEXUS_FORMAT_H_ #define _U2_NEXUS_FORMAT_H_ #include #include #include #include #include namespace U2 { class IOAdapter; class U2FORMATS_EXPORT NEXUSFormat : public DocumentFormat { Q_OBJECT public: NEXUSFormat(QObject *p); virtual DocumentFormatId getFormatId() const { return BaseDocumentFormats::NEXUS; } virtual const QString& getFormatName() const { return formatName; } virtual RawDataCheckResult checkRawData(const QByteArray &rawData, const GUrl& = GUrl()) const; virtual Document* loadDocument(IOAdapter *io, TaskStateInfo &ti, const QVariantMap &fs, DocumentLoadMode mode = DocumentLoadMode_Whole); virtual void storeDocument(Document *d, TaskStateInfo &ts, IOAdapter *io); private: QList loadObjects(IOAdapter *io, TaskStateInfo &ti); void storeObjects(QList objects, IOAdapter *io, TaskStateInfo &ti); private: QString formatName; }; } // namespace U2 #endif // #ifndef _U2_NEXUS_FORMAT_H_ ugene-1.9.8/src/corelibs/U2Formats/src/GenbankFeatures.cpp0000644000175000017500000004012011651544332022065 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "GenbankFeatures.h" #include #include #include #include namespace U2 { QMutex GBFeatureUtils::allKeys_mutex; QMutex GBFeatureUtils::getKeyGroups_mutex; QMutex GBFeatureUtils::getKey_mutex; const QByteArray GBFeatureUtils::QUALIFIER_AMINO_STRAND("ugene_amino_strand"); const QByteArray GBFeatureUtils::QUALIFIER_AMINO_STRAND_YES("yes"); const QByteArray GBFeatureUtils::QUALIFIER_AMINO_STRAND_NO("no"); const QByteArray GBFeatureUtils::QUALIFIER_NAME("ugene_name"); const QByteArray GBFeatureUtils::QUALIFIER_GROUP("ugene_group"); const QString GBFeatureUtils::DEFAULT_KEY = GBFeatureUtils::getKeyInfo(GBFeatureKey_misc_feature).text; const QString GBFeatureUtils::QUALIFIER_CUT = "cut"; const int GBFeatureUtils::MAX_KEY_LEN = 15; //max annotation key len in genbank or embl static QColor cl(const QString& txt) { QColor res; if (txt != "000000") { res.setNamedColor("#"+txt); } return res; } #define FKE(key, text, color, amino, desc, quals) \ features[key] = GBFeatureKeyInfo(key, text, color.isValid() ? color : FeatureColors::genLightColor(text), amino, desc); \ if (strlen(quals) > 0) { \ features[key].namingQuals = QString(quals).split(",", QString::SkipEmptyParts);\ } #define FK(key, text, color, amino, desc) \ FKE(key, text, color, amino, desc, "") const QVector& GBFeatureUtils::allKeys() { QMutexLocker locker(&allKeys_mutex); static QVector features(GBFeatureKey_NUM_KEYS); static bool inited = false; if (inited) { return features; } inited = true; FK(GBFeatureKey_attenuator, "attenuator", cl("000000"), false, tr("Sequence related to transcription termination")); FK(GBFeatureKey_C_region, "C_region", cl("000000"), false, tr("Span of the C immunological feature")); FK(GBFeatureKey_CAAT_signal, "CAAT_signal", cl("000000"), false, tr("`CAAT box' in eukaryotic promoters")); FKE(GBFeatureKey_CDS, "CDS", cl("9bffff"), true, tr("Sequence coding for amino acids in protein (includes stop codon)"), "protein_id,locus_tag,gene,function,product"); FK(GBFeatureKey_conflict, "conflict", cl("000000"), false, tr("Independent sequence determinations differ")); FK(GBFeatureKey_D_loop, "D-loop", cl("000000"), false, tr("Displacement loop")); FK(GBFeatureKey_D_segment, "D_segment", cl("000000"), false, tr("Span of the D immunological feature")); FK(GBFeatureKey_enhancer, "enhancer", cl("000000"), false, tr("Cis-acting enhancer of promoter function")); FK(GBFeatureKey_exon, "exon", cl("000000"), false, tr("Region that codes for part of spliced mRNA")); FKE(GBFeatureKey_gene, "gene", cl("00ffc8"), false, tr("Region that defines a functional gene, possibly including upstream (promotor, enhancer, etc) and downstream control elements, and for which a name has been assigned."), "gene,locus_tag,product,function"); FK(GBFeatureKey_GC_signal, "signal", cl("000000"), false, tr("`GC box' in eukaryotic promoters")); FK(GBFeatureKey_iDNA, "iDNA", cl("000000"), false, tr("Intervening DNA eliminated by recombination")); FK(GBFeatureKey_intron, "intron", cl("000000"), false, tr("Transcribed region excised by mRNA splicing")); FK(GBFeatureKey_J_region, "J_region", cl("000000"), false, tr("Span of the J immunological feature")); FK(GBFeatureKey_LTR, "LTR", cl("000000"), false, tr("Long terminal repeat")); FK(GBFeatureKey_mat_peptide, "mat_peptide", cl("000000"), true, tr("Mature peptide coding region (does not include stop codon)")); FK(GBFeatureKey_misc_binding, "misc_binding", cl("000000"), false, tr("Miscellaneous binding site")); FK(GBFeatureKey_misc_difference, "misc_difference", cl("000000"), false, tr("Miscellaneous difference feature")); FKE(GBFeatureKey_misc_feature, "misc_feature", cl("000000"), false, tr("Region of biological significance that cannot be described by any other feature") , "note"); FK(GBFeatureKey_misc_recomb, "misc_recomb", cl("000000"), false, tr("Miscellaneous, recombination feature")); FK(GBFeatureKey_misc_RNA, "misc_RNA", cl("000000"), false, tr("Miscellaneous transcript feature not defined by other RNA keys")); FK(GBFeatureKey_misc_signal, "misc_signal", cl("000000"), false, tr("Miscellaneous signal")); FK(GBFeatureKey_misc_structure, "misc_structure", cl("000000"), false, tr("Miscellaneous DNA or RNA structure")); FK(GBFeatureKey_modified_base, "modified_base", cl("000000"), false, tr("The indicated base is a modified nucleotide")); FK(GBFeatureKey_mRNA, "mRNA", cl("000000"), false, tr("Messenger RNA")); FK(GBFeatureKey_N_region, "N_region", cl("000000"), false, tr("Span of the N immunological feature")); FK(GBFeatureKey_old_sequence, "old_sequence", cl("000000"), false, tr("Presented sequence revises a previous version")); FK(GBFeatureKey_polyA_signal, "polyA_signal", cl("000000"), false, tr("Signal for cleavage & polyadenylation")); FK(GBFeatureKey_polyA_site, "polyA_site", cl("000000"), false, tr("Site at which polyadenine is added to mRNA")); FK(GBFeatureKey_precursor_RNA, "precursor_RNA", cl("000000"), false, tr("Any RNA species that is not yet the mature RNA product")); FK(GBFeatureKey_prim_transcript, "prim_transcript", cl("000000"), false, tr("Primary (unprocessed) transcript")); FK(GBFeatureKey_primer, "primer", cl("000000"), false, tr("Primer binding region used with PCR")); FK(GBFeatureKey_primer_bind, "primer_bind", cl("000000"), false, tr("Non-covalent primer binding site")); FK(GBFeatureKey_promoter, "promoter", cl("000000"), false, tr("A region involved in transcription initiation")); FK(GBFeatureKey_protein_bind, "protein_bind", cl("000000"), false, tr("Non-covalent protein binding site on DNA or RNA")); FK(GBFeatureKey_RBS, "RBS", cl("000000"), false, tr("Ribosome binding site")); FK(GBFeatureKey_rep_origin, "rep_origin", cl("000000"), false, tr("Replication origin for duplex DNA")); FK(GBFeatureKey_repeat_region, "repeat_region", cl("ccccff"), false, tr("Sequence containing repeated subsequences")); FK(GBFeatureKey_repeat_unit, "repeat_unit", cl("ccccff"), false, tr("One repeated unit of a repeat_region")); FK(GBFeatureKey_rRNA, "rRNA", cl("000000"), false, tr("Ribosomal RNA")); FK(GBFeatureKey_S_region, "S_region", cl("000000"), false, tr("Span of the S immunological feature")); FK(GBFeatureKey_satellite, "satellite", cl("000000"), false, tr("Satellite repeated sequence")); FK(GBFeatureKey_scRNA, "scRNA", cl("000000"), false, tr("Small cytoplasmic RNA")); FK(GBFeatureKey_sig_peptide, "sig_peptide", cl("000000"), false, tr("Signal peptide coding region")); FK(GBFeatureKey_snRNA, "snRNA", cl("000000"), false, tr("Small nuclear RNA")); FK(GBFeatureKey_source, "source", cl("cccccc"), false, tr("Identifies the biological source of the specified span of the sequence")); FK(GBFeatureKey_stem_loop, "stem_loop", cl("000000"), false, tr("Hair-pin loop structure in DNA or RNA")); FK(GBFeatureKey_STS, "STS", cl("00dcdc"), false, tr("Sequence Tagged Site; operationally unique sequence that identifies the combination of primer spans used in a PCR assay")); FK(GBFeatureKey_TATA_signal, "TATA_signal", cl("000000"), false, tr("`TATA box' in eukaryotic promoters")); FK(GBFeatureKey_terminator, "terminator", cl("000000"), false, tr("Sequence causing transcription termination")); FK(GBFeatureKey_transit_peptide, "transit_peptide", cl("000000"), false, tr("Transit peptide coding region")); FK(GBFeatureKey_transposon, "transposon", cl("000000"), false, tr("Transposable element (TN)")); FK(GBFeatureKey_tRNA, "tRNA", cl("c8fac8"), false, tr("Transfer RNA")); FK(GBFeatureKey_unsure, "unsure", cl("000000"), false, tr("Authors are unsure about the sequence in this region")); FK(GBFeatureKey_V_region, "V_region", cl("000000"), false, tr("Span of the V immunological feature")); FK(GBFeatureKey_variation, "variation", cl("ffff9b"), false, tr("A related population contains stable mutation")); FK(GBFeatureKey__10_signal, "-10_signal", cl("000000"), false, tr("`Pribnow box' in prokaryotic promoters")); FK(GBFeatureKey__35_signal, "-35_signal", cl("000000"), false, tr("`-35 box' in prokaryotic promoters")); FK(GBFeatureKey_3_clip, "3'clip", cl("000000"), false, tr("3'-most region of a precursor transcript removed in processing")); FK(GBFeatureKey_3_UTR, "3'UTR", cl("ffcde6"), false, tr("3' untranslated region (trailer)")); FK(GBFeatureKey_5_clip, "5'clip", cl("000000"), false, tr("5'-most region of a precursor transcript removed in processing")); FK(GBFeatureKey_5_UTR, "5'UTR", cl("ffc8c8"), false, tr("5' untranslated region (leader)")); FK(GBFeatureKey_Protein, "Protein", cl("000000"), false, tr("'Protein' feature key")); FK(GBFeatureKey_Region, "Region", cl("000000"), false, tr("'Region' feature key")); FK(GBFeatureKey_Site, "Site", cl("000000"), false, tr("'Site' feature key")); #ifdef _DEBUG for (int i=0; i& GBFeatureUtils::getKeyGroups() { QMutexLocker locker(&getKeyGroups_mutex); static QMultiMap groups; if (groups.isEmpty()) { QString genes = tr("Genes"); groups.insert(genes, GBFeatureKey_CDS); groups.insert(genes, GBFeatureKey_exon); groups.insert(genes, GBFeatureKey_gene); groups.insert(genes, GBFeatureKey_intron); groups.insert(genes, GBFeatureKey_mRNA); groups.insert(genes, GBFeatureKey_polyA_site); groups.insert(genes, GBFeatureKey_precursor_RNA); groups.insert(genes, GBFeatureKey_prim_transcript); groups.insert(genes, GBFeatureKey_promoter); groups.insert(genes, GBFeatureKey_3_clip); groups.insert(genes, GBFeatureKey_3_UTR); groups.insert(genes, GBFeatureKey_5_clip); groups.insert(genes, GBFeatureKey_5_UTR); QString signls = tr("Signals"); groups.insert(signls, GBFeatureKey_attenuator); groups.insert(signls, GBFeatureKey_CAAT_signal); groups.insert(signls, GBFeatureKey_GC_signal); groups.insert(signls, GBFeatureKey_enhancer); groups.insert(signls, GBFeatureKey_mat_peptide); groups.insert(signls, GBFeatureKey_misc_signal); groups.insert(signls, GBFeatureKey_rep_origin); groups.insert(signls, GBFeatureKey_polyA_site); groups.insert(signls, GBFeatureKey_polyA_signal); groups.insert(signls, GBFeatureKey_promoter); groups.insert(signls, GBFeatureKey_RBS); groups.insert(signls, GBFeatureKey_sig_peptide); groups.insert(signls, GBFeatureKey_terminator); groups.insert(signls, GBFeatureKey_transit_peptide); groups.insert(signls, GBFeatureKey_TATA_signal); groups.insert(signls, GBFeatureKey__35_signal); groups.insert(signls, GBFeatureKey__10_signal); QString binding = tr("Binding"); groups.insert(binding, GBFeatureKey_misc_binding); groups.insert(binding, GBFeatureKey_primer_bind); groups.insert(binding, GBFeatureKey_protein_bind); QString variation = tr("Variation"); groups.insert(variation, GBFeatureKey_conflict); groups.insert(variation, GBFeatureKey_misc_difference); groups.insert(variation, GBFeatureKey_modified_base); groups.insert(variation, GBFeatureKey_old_sequence); groups.insert(variation, GBFeatureKey_STS); groups.insert(variation, GBFeatureKey_unsure); groups.insert(variation, GBFeatureKey_variation); QString repeats = tr("Repeats"); groups.insert(repeats, GBFeatureKey_LTR); groups.insert(repeats, GBFeatureKey_repeat_region); groups.insert(repeats, GBFeatureKey_repeat_unit); groups.insert(repeats, GBFeatureKey_satellite); groups.insert(repeats, GBFeatureKey_transposon); //TODO: recheck grouping QString rna = tr("RNA"); groups.insert(rna, GBFeatureKey_misc_RNA); groups.insert(rna, GBFeatureKey_mRNA); groups.insert(rna, GBFeatureKey_rRNA); groups.insert(rna, GBFeatureKey_scRNA); groups.insert(rna, GBFeatureKey_snRNA); groups.insert(rna, GBFeatureKey_tRNA); QString misc = tr("Misc"); groups.insert(misc, GBFeatureKey_D_loop); groups.insert(misc, GBFeatureKey_iDNA); groups.insert(misc, GBFeatureKey_misc_binding); groups.insert(misc, GBFeatureKey_misc_feature); groups.insert(misc, GBFeatureKey_misc_recomb); groups.insert(misc, GBFeatureKey_misc_structure); groups.insert(misc, GBFeatureKey_primer); //TODO: recheck grouping groups.insert(misc, GBFeatureKey_source); groups.insert(misc, GBFeatureKey_stem_loop); groups.insert(misc, GBFeatureKey_Protein); groups.insert(misc, GBFeatureKey_Region); groups.insert(misc, GBFeatureKey_Site); QString spans = tr("Spans"); groups.insert(spans, GBFeatureKey_C_region); groups.insert(spans, GBFeatureKey_D_segment); groups.insert(spans, GBFeatureKey_J_region); groups.insert(spans, GBFeatureKey_N_region); groups.insert(spans, GBFeatureKey_S_region); groups.insert(spans, GBFeatureKey_V_region); #ifdef _DEBUG //check that no feature lost QVector featureInGroup(GBFeatureKey_NUM_KEYS, false); foreach(const QString& groupName, groups.keys()) { QList values = groups.values(groupName); foreach (GBFeatureKey k, values) { featureInGroup[k] = true; } } for (int i=0; i keysByText; if (keysByText.isEmpty()) { foreach(const GBFeatureKeyInfo& ki, allKeys()) { keysByText[ki.text] = ki.id; } } return keysByText.value(text, GBFeatureKey_UNKNOWN); } }//namespace ugene-1.9.8/src/corelibs/U2Formats/src/GFFFormat.h0000644000175000017500000000342711651544332020252 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_GFF_FORMAT_H_ #define _U2_GFF_FORMAT_H_ #include #include namespace U2 { class IOAdapter; class U2FORMATS_EXPORT GFFFormat : public DocumentFormat { Q_OBJECT public: GFFFormat(QObject* p); virtual DocumentFormatId getFormatId() const {return BaseDocumentFormats::GFF;} virtual const QString& getFormatName() const {return formatName;} virtual Document* loadDocument( IOAdapter* io, TaskStateInfo& ti, const QVariantMap& fs, DocumentLoadMode mode = DocumentLoadMode_Whole); virtual void storeDocument( Document* d, TaskStateInfo& ts, IOAdapter* io ); virtual RawDataCheckResult checkRawData(const QByteArray& rawData, const GUrl& = GUrl()) const; private: void load(IOAdapter* io, QList& objects, const QVariantMap& hints, TaskStateInfo& si); QStringList parseLine(QString line) const; QString formatName; }; }//namespace #endif ugene-1.9.8/src/corelibs/U2Formats/src/FastaFormat.h0000644000175000017500000000360211651544332020701 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_FASTA_FORMAT_H_ #define _U2_FASTA_FORMAT_H_ #include #include namespace U2 { class IOAdapter; class U2FORMATS_EXPORT FastaFormat : public DocumentFormat { Q_OBJECT public: FastaFormat(QObject* p); virtual DocumentFormatId getFormatId() const {return BaseDocumentFormats::PLAIN_FASTA;} virtual const QString& getFormatName() const {return formatName;} virtual Document* loadDocument( IOAdapter* io, TaskStateInfo& ti, const QVariantMap& fs, DocumentLoadMode mode = DocumentLoadMode_Whole); virtual GObject *loadObject( IOAdapter* io, TaskStateInfo& ti); virtual DNASequence *loadSequence( IOAdapter* io, TaskStateInfo& ti); void storeSequence(const DNASequence& sequence, IOAdapter* io, TaskStateInfo& ti); virtual void storeDocument( Document* d, TaskStateInfo& ts, IOAdapter* io ); virtual RawDataCheckResult checkRawData(const QByteArray& rawData, const GUrl& = GUrl()) const; private: QString formatName; }; }//namespace #endif ugene-1.9.8/src/corelibs/U2Formats/src/MSFFormat.cpp0000644000175000017500000003023311651544332020623 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "MSFFormat.h" #include #include #include #include #include #include #include #include #include namespace U2 { const int MSFFormat::CHECK_SUM_MOD = 10000; const QByteArray MSFFormat::MSF_FIELD = "MSF:"; const QByteArray MSFFormat::CHECK_FIELD = "Check:"; const QByteArray MSFFormat::LEN_FIELD = "Len:"; const QByteArray MSFFormat::NAME_FIELD = "Name:"; const QByteArray MSFFormat::TYPE_FIELD = "Type:"; const QByteArray MSFFormat::WEIGHT_FIELD = "Weight:"; const QByteArray MSFFormat::TYPE_VALUE_PROTEIN = "P"; const QByteArray MSFFormat::TYPE_VALUE_NUCLEIC = "N"; const double MSFFormat::WEIGHT_VALUE = 1.0; const QByteArray MSFFormat::END_OF_HEADER_LINE = ".."; const QByteArray MSFFormat::SECTION_SEPARATOR = "//"; const int MSFFormat::CHARS_IN_ROW = 50; const int MSFFormat::CHARS_IN_WORD = 10; /* TRANSLATOR U2::MSFFormat */ //TODO: recheck if it does support streaming! Fix isObjectOpSupported if not! MSFFormat::MSFFormat(QObject* p) : DocumentFormat(p, DocumentFormatFlags_SW, QStringList("msf")) { formatName = tr("MSF"); supportedObjectTypes+=GObjectTypes::MULTIPLE_ALIGNMENT; formatDescription = tr("MSF format is used to store multiple aligned sequences. Files include the sequence name and the sequence itself, which is usually aligned with other sequences in the file."); } static bool getNextLine(IOAdapter* io, QByteArray& line) { static int READ_BUFF_SIZE = 1024; QByteArray readBuffer(READ_BUFF_SIZE, '\0'); char* buff = readBuffer.data(); qint64 len; bool eolFound = false, eof = false; while (!eolFound) { len = io->readLine(buff, READ_BUFF_SIZE, &eolFound); if (len < READ_BUFF_SIZE && !eolFound) { eolFound = eof = true; } line += readBuffer; } if (len != READ_BUFF_SIZE) { line.resize(line.size() + len - READ_BUFF_SIZE); } line = line.simplified(); return eof; } static QByteArray getField(const QByteArray& line, const QByteArray& name) { int p = line.indexOf(name); if (p >= 0) { p += name.length(); if (line[p] == ' ') ++p; int q = line.indexOf(' ', p); if (q >= 0) return line.mid(p, q - p); else return line.mid(p); } return QByteArray(); } int MSFFormat::getCheckSum(const QByteArray& seq) { int sum = 0; static int CHECK_SUM_COUNTER_MOD = 57; for (int i = 0; i < seq.length(); ++i) { char ch = seq[i]; if (ch >= 'a' && ch <= 'z') { ch = ch + 'A' - 'a'; } sum = (sum + ((i % CHECK_SUM_COUNTER_MOD) + 1) * ch) % MSFFormat::CHECK_SUM_MOD; } return sum; } void MSFFormat::load(IOAdapter* io, QList& objects, TaskStateInfo& ti) { MAlignment al(io->getURL().baseFileName()); //skip comments int checkSum = -1; while (!ti.cancelFlag && checkSum < 0) { QByteArray line; if (getNextLine(io, line)) { ti.setError(MSFFormat::tr("Incorrect format")); return; } if (line.endsWith(END_OF_HEADER_LINE)) { bool ok; checkSum = getField(line, CHECK_FIELD).toInt(&ok); if (!ok || checkSum < 0) checkSum = CHECK_SUM_MOD; } ti.progress = io->getProgress(); } //read info int sum = 0; QMap seqs; while (!ti.cancelFlag) { QByteArray line; if (getNextLine(io, line)) { ti.setError(MSFFormat::tr("Unexpected end of file")); return; } if (line.startsWith(SECTION_SEPARATOR)) break; bool ok = false; QString name = QString::fromLocal8Bit(getField(line, NAME_FIELD).data()); if (name.isEmpty()) { continue; } int check = getField(line, CHECK_FIELD).toInt(&ok); if (!ok || check < 0) { sum = check = CHECK_SUM_MOD; } seqs.insert(name, check); al.addRow(MAlignmentRow(name)); if (sum < CHECK_SUM_MOD) { sum = (sum + check) % CHECK_SUM_MOD; } ti.progress = io->getProgress(); } if (checkSum < CHECK_SUM_MOD && sum < CHECK_SUM_MOD && sum != checkSum) { ti.setError(MSFFormat::tr("Check sum test failed")); return; } //read data bool eof = false; while (!eof && !ti.cancelFlag) { QByteArray line; eof = getNextLine(io, line); if (line.isEmpty()) { continue; } int i = 0, n = al.getNumRows(); for (; i < n; i++) { const MAlignmentRow& row = al.getRow(i); QByteArray t = row.getName().toLocal8Bit(); if (line.startsWith(t) && line[t.length()] == ' ') { break; } } if (i == n) { continue; } for (int q, p = line.indexOf(' ') + 1; p > 0; p = q + 1) { q = line.indexOf(' ', p); QByteArray subSeq = (q < 0) ? line.mid(p) : line.mid(p, q - p); al.appendChars(i, subSeq.constData(), subSeq.length()); } ti.progress = io->getProgress(); } //checksum for (int i=0; i objs; load(io, objs, ti); if (ti.hasError()) { qDeleteAll(objs); return NULL; } return new Document(this, io->getFactory(), io->getURL(), objs, fs); } static bool writeBlock(IOAdapter *io, Document* d, TaskStateInfo& ti, const QByteArray& buf) { int len = io->writeBlock(buf); if (len != buf.length()) { ti.setError(L10N::errorWritingFile(d->getURL())); return true; } return false; } void MSFFormat::storeDocument( Document* d, TaskStateInfo& ti, IOAdapter* io ) { const MAlignmentObject* obj = NULL; if((d->getObjects().size() != 1) || ((obj = qobject_cast(d->getObjects().first())) == NULL)) { ti.setError("No data to write;"); return; } const MAlignment& ma = obj->getMAlignment(); //precalculate seq writing params int maxNameLen = 0, maLen = ma.getLength(), checkSum = 0; static int maxCheckSumLen = 4; QMap checkSums; foreach(const MAlignmentRow& row , ma.getRows()) { QByteArray sequence = row.toByteArray(maLen).replace(MAlignment_GapChar, '.'); int seqCheckSum = getCheckSum(sequence); checkSums.insert(row.getName(), seqCheckSum); checkSum = (checkSum + seqCheckSum) % CHECK_SUM_MOD; maxNameLen = qMax(maxNameLen, row.getName().length()); } int maxLengthLen = QString::number(maLen).length(); //write first line QByteArray line = " " + MSF_FIELD; line += " " + QByteArray::number(maLen); line += " " + TYPE_FIELD; line += " " + obj->getAlphabet()->isAmino() ? TYPE_VALUE_PROTEIN : TYPE_VALUE_NUCLEIC; line += " " + QDateTime::currentDateTime().toString("dd.MM.yyyy hh:mm"); line += " " + CHECK_FIELD; line += " " + QByteArray::number(checkSum); line += " " + END_OF_HEADER_LINE + "\n\n"; if (writeBlock(io, d, ti, line)) return; //write info foreach(const MAlignmentRow& row, ma.getRows()) { QByteArray line = " " + NAME_FIELD; line += " " + QString(row.getName()).replace(' ', '_').leftJustified(maxNameLen+1); // since ' ' is a delimeter for MSF parser spaces in name not suppoted line += " " + LEN_FIELD; line += " " + QString("%1").arg(maLen, -maxLengthLen); line += " " + CHECK_FIELD; line += " " + QString("%1").arg(checkSums[row.getName()], -maxCheckSumLen); line += " " + WEIGHT_FIELD; line += " " + QByteArray::number(WEIGHT_VALUE) + "\n"; if (writeBlock(io, d, ti, line)) { return; } } if (writeBlock(io, d, ti, "\n" + SECTION_SEPARATOR + "\n\n")) { return; } for (int i = 0; !ti.cancelFlag && i < maLen; i += CHARS_IN_ROW) { /* write numbers */ { QByteArray line(maxNameLen + 2, ' '); QString t = QString("%1").arg(i + 1); QString s = QString("%1").arg(i + CHARS_IN_ROW < maLen ? i + CHARS_IN_ROW : maLen); int r = maLen - i < CHARS_IN_ROW ? maLen % CHARS_IN_ROW : CHARS_IN_ROW; r += (r - 1) / CHARS_IN_WORD - (t.length() + s.length()); line += t; if (r > 0) { line += QByteArray(r, ' '); line += s; } line += '\n'; if (writeBlock(io, d, ti, line)) { return; } } //write sequence foreach(const MAlignmentRow& row, ma.getRows()) { QByteArray line = row.getName().toLocal8Bit(); line.replace(' ', '_'); // since ' ' is a delimeter for MSF parser spaces in name not supported line = line.leftJustified(maxNameLen+1); for (int j = 0; j < CHARS_IN_ROW && i + j < maLen; j += CHARS_IN_WORD) { line += ' '; int nChars = qMin(CHARS_IN_WORD, maLen - (i + j)); line += row.mid(i + j, nChars).toByteArray(nChars).replace(MAlignment_GapChar, '.'); } line += '\n'; if (writeBlock(io, d, ti, line)) { return; } } if (writeBlock(io, d, ti, "\n")) { return; } } } RawDataCheckResult MSFFormat::checkRawData(const QByteArray& rawData, const GUrl&) const { const char* data = rawData.constData(); int size = rawData.size(); bool hasBinaryData = TextUtils::contains(TextUtils::BINARY, data, size); if (hasBinaryData) { return FormatDetection_NotMatched; } if (rawData.contains("MSF:") || rawData.contains("!!AA_MULTIPLE_ALIGNMENT 1.0") || rawData.contains("!!NA_MULTIPLE_ALIGNMENT 1.0") || (rawData.contains("Name:") && rawData.contains("Len:") && rawData.contains("Check:") && rawData.contains("Weight:"))) { return FormatDetection_VeryHighSimilarity; } if (rawData.contains("GDC ")) { return FormatDetection_AverageSimilarity; } //MSF documents may contain unlimited number of comment lines in header -> //it is impossible to determine if file has MSF format by some predefined //amount of raw data read from it. if (rawData.contains("GCG ") || rawData.contains("MSF ")) { return FormatDetection_LowSimilarity; } return FormatDetection_VeryLowSimilarity; } } //namespace U2 ugene-1.9.8/src/corelibs/U2Formats/src/ABIFormat.cpp0000644000175000017500000006544411651544332020605 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "ABIFormat.h" #include "IOLibUtils.h" #include "DocumentFormatUtils.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include /* TRANSLATOR U2::ABIFormat */ namespace U2 { ABIFormat::ABIFormat(QObject* p) : DocumentFormat(p, DocumentFormatFlags(0), QStringList() << "ab1" << "abi" << "abif") { formatName = tr("ABIF"); supportedObjectTypes+=GObjectTypes::SEQUENCE; supportedObjectTypes+=GObjectTypes::CHROMATOGRAM; } RawDataCheckResult ABIFormat::checkRawData(const QByteArray& rawData, const GUrl&) const { const char* data = rawData.constData(); int size = rawData.size(); if (size <= 4 || data[0]!='A' || data[1]!='B' || data[2]!='I' || data[3]!='F') { /* * Maybe we've got a file in MacBinary format in which case * we'll have an extra offset 128 bytes to add. */ data += 128; size -= 128; if (size <= 4 || data[0]!='A' || data[1]!='B' || data[2]!='I' || data[3]!='F') { return FormatDetection_NotMatched; } } bool hasBinaryBlocks = TextUtils::contains(TextUtils::BINARY, data, size); return hasBinaryBlocks ? FormatDetection_Matched : FormatDetection_NotMatched; } Document* ABIFormat::loadDocument(IOAdapter* io, TaskStateInfo& ti, const QVariantMap& fs, DocumentLoadMode) { QByteArray readBuff; QByteArray block(BUFF_SIZE, 0); quint64 len = 0; while ((len=io->readBlock(block.data(),BUFF_SIZE)) > 0) { readBuff.append(QByteArray(block.data(), len)); if (readBuff.size()>CHECK_MB) { ti.setError(L10N::errorFileTooLarge(io->getURL())); break; } } if (ti.hasError()) { return NULL; } SeekableBuf sf; sf.head = readBuff.constData(); sf.pos = 0; sf.size = readBuff.size(); Document* doc = parseABI(&sf, io, fs, ti); if (doc == NULL && !ti.hasError()) { ti.setError(tr("Not a valid ABIF file: %1").arg(io->toString())); } return doc; } /* * Copyright (c) Medical Research Council 1994. All rights reserved. * * Permission to use, copy, modify and distribute this software and its * documentation for any purpose is hereby granted without fee, provided that * this copyright and notice appears in all copies. * * This file was written by James Bonfield, Simon Dear, Rodger Staden, * as part of the Staden Package at the MRC Laboratory of Molecular * Biology, Hills Road, Cambridge, CB2 2QH, United Kingdom. * * MRC disclaims all warranties with regard to this software. */ /* * Title: seqIOABI * * File: seqIOABI.c * Purpose: Reading (not writing) of ABI sequences * Last update: Fri Sep 02, 1994 */ /* * The ABI magic number - "ABIF" */ #define ABI_MAGIC ((int) ((((('A'<<8)+'B')<<8)+'I')<<8)+'F') /* * The index is located towards the end of the ABI trace file. * It's location is given by a longword at a fixed place. */ #define IndexPO 26 #define IndexEntryLength 28 /* * Here are some labels we will be looking for, four chars packed * into an int_4 */ #define LABEL(a) ((int) ((((((a)[0]<<8)+(a)[1])<<8)+(a)[2])<<8)+(a)[3]) #define DataEntryLabel LABEL("DATA") #define BaseEntryLabel LABEL("PBAS") #define BasePosEntryLabel LABEL("PLOC") #define SpacingEntryLabel LABEL("SPAC") #define SignalEntryLabel LABEL("S/N%") #define FWO_Label LABEL("FWO_") #define MCHNLabel LABEL("MCHN") #define PDMFLabel LABEL("PDMF") #define SMPLLabel LABEL("SMPL") #define PPOSLabel LABEL("PPOS") #define CMNTLabel LABEL("CMNT") #define GelNameLabel LABEL("GELN") #define LANELabel LABEL("LANE") #define RUNDLabel LABEL("RUND") #define RUNTLabel LABEL("RUNT") #define MTXFLabel LABEL("MTXF") #define SPACLabel LABEL("SPAC") #define SVERLabel LABEL("SVER") #define MODLLabel LABEL("MODL") #define BaseConfLabel LABEL("PCON") #define baseIndex(B) ((B)=='C'?0:(B)=='A'?1:(B)=='G'?2:3) /* * Gets the offset of the ABI index. * Returns -1 for failure, 0 for success. */ static int getABIIndexOffset(SeekableBuf* fp, uint *indexO) { uint magic = 0; /* * Initialise header_fudge. * * This is usually zero, but maybe we've transfered a file in MacBinary * format in which case we'll have an extra 128 bytes to add to all * our fseeks. */ be_read_int_4(fp, &magic); if (magic != ABI_MAGIC) { fp->head += 128; fp->size -= 128; } if ((SeekBuf(fp, IndexPO, 0) != 0) || (!be_read_int_4(fp, indexO))) return -1; else return 0; } /* * From the ABI results file connected to `fp' whose index starts * at byte offset `indexO', return in `val' the `lw'th long word * from the `count'th entry labelled `label'. * The result is 0 for failure, or index offset for success. */ int getABIIndexEntryLW(SeekableBuf* fp, int indexO, uint label, uint count, int lw, uint *val) { int entryNum=-1; int i; uint entryLabel, entryLw1; do { entryNum++; if (SeekBuf(fp, indexO+(entryNum*IndexEntryLength), 0) != 0) return 0; if (!be_read_int_4(fp, &entryLabel)) return 0; if (!be_read_int_4(fp, &entryLw1)) return 0; } while (!(entryLabel == label && entryLw1 == count)); for(i=2; i<=lw; i++) { if (!be_read_int_4(fp, val)) return 0; } return indexO+(entryNum*IndexEntryLength); } /* * From the ABI results file connected to `fp' whose index starts * at byte offset `indexO', return in `val' the `sw'th short word * from the `count'th entry labelled `label'. * The result is 0 for failure, or index offset for success. */ int getABIIndexEntrySW(SeekableBuf* fp, int indexO, uint label, uint count, int sw, ushort *val) { int entryNum=-1; int i; uint entryLabel, entryLw1; do { entryNum++; if (SeekBuf(fp, indexO+(entryNum*IndexEntryLength), 0) != 0) return 0; if (!be_read_int_4(fp, &entryLabel)) return 0; if (!be_read_int_4(fp, &entryLw1)) return 0; } while (!(entryLabel == label && entryLw1 == count)); for(i=4; i<=sw; i++) { if (!be_read_int_2(fp, val)) return 0; } return indexO+(entryNum*IndexEntryLength); } /* * Get an "ABI String". These strings are either pointed to by the index * offset, or held in the offset itself when the string is <= 4 characters. * The "type" of the index entry is either 0x12 (a pascal string in which * case the first byte of the string determines its length) or a 0x02 (a * C-style string with length coming from the abi index). * * "string" will be max 256 bytes for the pascal string, but is of unknown * (and hence potentially buggy) length for C-strings. For now we live with * it as this entire file needs rewriting from scratch anyway. * * Returns -1 for failure, string length for success. */ int getABIString(SeekableBuf *fp, int indexO, uint label, uint count, char *string) { uint off; uint len; quint16 type; off = getABIIndexEntrySW(fp, indexO, label, count, 4, &type); if (!off) return -1; if ((off = getABIIndexEntryLW(fp, indexO, label, count, 4, &len))) { uchar len2 = 0; if (!len) return 0; /* Determine offset */ if (len <= 4) off += 20; else getABIIndexEntryLW(fp, indexO, label, count, 5, &off); /* Read length byte */ if (type == 0x12) { SeekBuf(fp, off, 0); be_read_int_1(fp, &len2); } else { len2 = len; } /* Read data (max 255 bytes) */ fp->read(string, len2); string[len2] = 0; return len2; } else { return -1; } } /* * Get an "ABI Int_1". This is raw 1-byte integer data pointed to by the * offset, or held in the offset itself when the data is <= 4 characters. * * If indexO is 0 then we do not search for (or indeed use) label and count, * but simply assume that we are already at the correct offset and read from * here. (NB: This negates the length <= 4 check.) * * Returns -1 for failure, length desired for success (it'll only fill out * up to max_data_len elements, but it gives an indication of whether there * was more to come). */ int getABIint1(SeekableBuf *fp, int indexO, uint label, uint count, uchar *data, int max_data_len) { uint off; uint len, len2; if (indexO) { if (!(off = getABIIndexEntryLW(fp, indexO, label, count, 4, &len))) return -1; if (!len) return 0; /* Determine offset */ if (len <= 4) off += 20; else getABIIndexEntryLW(fp, indexO, label, count, 5, &off); len2 = qMin((uint)max_data_len, len); SeekBuf(fp, off, 0); } else { len = len2 = max_data_len; } fp->read((char*)data, len2); return len; } /* * Get an "ABI Int_2". This is raw 2-byte integer data pointed to by the * offset, or held in the offset itself when the data is <= 4 characters. * * Returns -1 for failure, length desired for success (it'll only fill out * up to max_data_len elements, but it gives an indication of whether there * was more to come). */ int getABIint2(SeekableBuf *fp, int indexO, uint label, uint count, ushort *data, int max_data_len) { int len, l2; int i; len = getABIint1(fp, indexO, label, count, (uchar *)data, max_data_len*2); if (-1 == len) return -1; len /= 2; l2 = qMin(len, max_data_len); for (i = 0; i < l2; i++) { data[i] = be_int2((uchar*)(data+i)); } return len; } /* * Get an "ABI Int_4". This is raw 4-byte integer data pointed to by the * offset, or held in the offset itself when the data is <= 4 characters. * * Returns -1 for failure, length desired for success (it'll only fill out * up to max_data_len elements, but it gives an indication of whether there * was more to come). */ int getABIint4(SeekableBuf *fp, int indexO, uint label, uint count, uint *data, int max_data_len) { int len, l2; int i; len = getABIint1(fp, indexO, label, count, (uchar *)data, max_data_len*4); if (-1 == len) return -1; len /= 4; l2 = qMin(len, max_data_len); for (i = 0; i < l2; i++) { data[i] = be_int4((uchar*)(data+i)); } return len; } static void replace_nl(char *string) { char *cp; for (cp = string; *cp; cp++) { if (*cp == '\n') *cp = ' '; } } Document* ABIFormat::parseABI(SeekableBuf* fp, IOAdapter* io, const QVariantMap& fs, U2OpStatus& os) { float fspacing; /* average base spacing */ uint numPoints, numBases; uint signalO; int no_bases = 0; int sections = READ_ALL; uint fwo_; /* base -> lane mapping */ uint indexO; /* File offset where the index is */ uint baseO; /* File offset where the bases are stored */ uint dataCO; /* File offset where the C trace is stored */ uint dataAO; /* File offset where the A trace is stored */ uint dataGO; /* File offset where the G trace is stored */ uint dataTO; /* File offset where the T trace is stored */ uint offset; /* Generic offset */ uint offset2; /* Generic offset */ uint offset3; /* Generic offset */ uint offset4; /* Generic offset */ /* DATA block numbers for traces, in order of FWO_ */ int DataCount[4] = {9, 10, 11, 12}; DNAChromatogram cd; QString sequenceName; QString sequenceComment; QByteArray sequence; /* Get the index offset */ if (-1 == getABIIndexOffset(fp, &indexO)) return NULL; /* Get the number of points */ if (!getABIIndexEntryLW(fp,indexO,DataEntryLabel,DataCount[0], 3,&numPoints)) return NULL; /* Get the number of bases */ if (!getABIIndexEntryLW(fp,indexO,BaseEntryLabel,1,3,&numBases)) { no_bases = 1; numBases = 0; } /* Allocate the sequence */ /* Allocate space for the bases - 1 extra for the ->base field so * that we can treat it as a NULL terminated string. */ if (sections & READ_BASES) { cd.prob_A.resize(numBases+1); cd.prob_C.resize(numBases+1); cd.prob_G.resize(numBases+1); cd.prob_T.resize(numBases+1); cd.baseCalls.resize(numBases+1); } if (sections & READ_SAMPLES) { cd.A.resize(numPoints+1); cd.C.resize(numPoints+1); cd.G.resize(numPoints+1); cd.T.resize(numPoints+1); } /* Get the Filter Wheel Order (FWO_) field ... */ if (!getABIIndexEntryLW(fp,indexO,FWO_Label,1,5,&fwo_)) { /* Guess at CAGT */ fwo_ = 0x43414754; } /* * The order of the DATA fields is determined by the field FWO_ * Juggle around with data pointers to get it right */ if (sections & READ_SAMPLES) { uint *dataxO[4]; dataxO[0] = &dataCO; dataxO[1] = &dataAO; dataxO[2] = &dataGO; dataxO[3] = &dataTO; /*Get the positions of the four traces */ if (!(getABIIndexEntryLW(fp, indexO, DataEntryLabel, DataCount[0], 5, dataxO[baseIndex((char)(fwo_>>24&255))]) && getABIIndexEntryLW(fp, indexO, DataEntryLabel, DataCount[1], 5, dataxO[baseIndex((char)(fwo_>>16&255))]) && getABIIndexEntryLW(fp, indexO, DataEntryLabel, DataCount[2], 5, dataxO[baseIndex((char)(fwo_>>8&255))]) && getABIIndexEntryLW(fp, indexO, DataEntryLabel, DataCount[3], 5, dataxO[baseIndex((char)(fwo_&255))]))) { return NULL; } } /************************************************************* * Read the traces and bases information *************************************************************/ if (sections & READ_SAMPLES) { /* Read in the C trace */ if (SeekBuf(fp, dataCO, 0) == -1) return NULL; getABIint2(fp, 0, 0, 0, cd.C.data(), numPoints); /* Read in the A trace */ if (SeekBuf(fp, dataAO, 0) == -1) return NULL; getABIint2(fp, 0, 0, 0, cd.A.data(), numPoints); /* Read in the G trace */ if (SeekBuf(fp, dataGO, 0) == -1) return NULL; getABIint2(fp, 0, 0, 0, cd.G.data(), numPoints); /* Read in the T trace */ if (SeekBuf(fp, dataTO, 0) == -1) return NULL; getABIint2(fp, 0, 0, 0, cd.T.data(), numPoints); /* Compute highest trace peak */ /*for (i=0; i < numPoints; i++) { if (read->maxTraceVal < read->traceA[i]) read->maxTraceVal = read->traceA[i]; if (read->maxTraceVal < read->traceC[i]) read->maxTraceVal = read->traceC[i]; if (read->maxTraceVal < read->traceG[i]) read->maxTraceVal = read->traceG[i]; if (read->maxTraceVal < read->traceT[i]) read->maxTraceVal = read->traceT[i]; }*/ } if (no_bases || !(sections & READ_BASES)) { goto skip_bases; } /* Read in base confidence values */ { QVector conf(numBases); getABIint1(fp, indexO, BaseConfLabel, 1, conf.data(), numBases); /* Read in the bases */ if (!(getABIIndexEntryLW(fp, indexO, BaseEntryLabel, 1, 5, &baseO) && (SeekBuf(fp, baseO, 0) == 0) )) { return NULL; } sequence = QByteArray(numBases, 0); if (!fp->read(sequence.data(), numBases)) { return NULL; } for (uint i = 0; i < numBases; i++) { switch(sequence[i]) { case 'A': case 'a': cd.prob_A[i] = conf[i]; cd.prob_C[i] = 0; cd.prob_G[i] = 0; cd.prob_T[i] = 0; break; case 'C': case 'c': cd.prob_A[i] = 0; cd.prob_C[i] = conf[i]; cd.prob_G[i] = 0; cd.prob_T[i] = 0; break; case 'G': case 'g': cd.prob_A[i] = 0; cd.prob_C[i] = 0; cd.prob_G[i] = conf[i]; cd.prob_T[i] = 0; break; case 'T': case 't': cd.prob_A[i] = 0; cd.prob_C[i] = 0; cd.prob_G[i] = 0; cd.prob_T[i] = conf[i]; break; default: cd.prob_A[i] = 0; cd.prob_C[i] = 0; cd.prob_G[i] = 0; cd.prob_T[i] = 0; break; } } } /* Read in the base positions */ if (-1 == getABIint2(fp, indexO, BasePosEntryLabel, 1, cd.baseCalls.data(), numBases)) { return NULL; } /* * Check for corrupted traces where the bases are positioned on sample * coordinates which do not exist. Witnessed on some MegaBACE files. */ if (cd.baseCalls[numBases-1] > numPoints) { int n = cd.baseCalls[numBases-1]+1; cd.A.resize(n); cd.C.resize(n); cd.G.resize(n); cd.T.resize(n); numPoints = n; } skip_bases: /************************************************************* * Gather useful information - the comments field *************************************************************/ if (sections & READ_COMMENTS) { char buffer[257]; char commstr[256]; int spacing; ushort i2; uint i4; /* The ABI comments */ int clen = getABIString(fp, indexO, CMNTLabel, 1, commstr); if (clen != -1) { commstr[clen] = 0; char *commstrp = commstr; char *p; do { if ((p = strchr(commstrp, '\n'))){ *p++ = 0; } sequenceComment.append(QString("ABI Comment: %1\n").arg(commstrp)); } while((commstrp = p)); } /* Get Sample Name Offset */ if (-1 != getABIString(fp, indexO, SMPLLabel, 1, buffer)) { replace_nl(buffer); sequenceComment.append(QString("Sample: %1\n").arg(buffer)); sequenceName.append(buffer); } /* LANE */ if (-1 != getABIint2(fp, indexO, LANELabel, 1, &i2, 1)) { sequenceComment.append(QString("LANE=%1\n").arg(i2)); } /* Get Signal Strength Offset */ if (getABIIndexEntryLW(fp, indexO, SignalEntryLabel, 1, 5, &signalO)) { short C,A,G,T; short *base[4]; base[0] = &C; base[1] = &A; base[2] = &G; base[3] = &T; if (SeekBuf(fp, signalO, 0) != -1 && be_read_int_2(fp, (ushort *) base[baseIndex((char)(fwo_>>24&255))]) && be_read_int_2(fp, (ushort *) base[baseIndex((char)(fwo_>>16&255))]) && be_read_int_2(fp, (ushort *) base[baseIndex((char)(fwo_>>8&255))]) && be_read_int_2(fp, (ushort *) base[baseIndex((char)(fwo_&255))])) { sequenceComment.append(QString("SIGN=A=%1,C=%2,G=%3,T=%4\n").arg(A).arg(C).arg(G).arg(T)); } } /* Get the spacing.. it's a float but don't worry yet */ fspacing = 0; if (-1 != getABIint4(fp, indexO, SpacingEntryLabel, 1, (uint *)&spacing, 1)) { fspacing = int_to_float(spacing); sequenceComment.append(QString("SPAC=%1\n").arg(fspacing)); //-6.2f", } /* Correction for when spacing is negative. Why does this happen? */ if (fspacing <= 0) { if (numBases > 1) { if (sections & READ_BASES) fspacing = (float)(cd.baseCalls[numBases-1] - cd.baseCalls[0]) / (float) (numBases-1); else fspacing = (float) numPoints / (float) numBases; } else { fspacing = 1; } } /* Get primer position */ if (getABIIndexEntryLW(fp, indexO, PPOSLabel, 1, 5, (uint *)&i4)) { /* ppos stores in MBShort of pointer */ sequenceComment.append(QString("PRIM=%1\n").arg(i4>>16)); } /* RUND/RUNT */ if (getABIIndexEntryLW(fp, indexO, RUNDLabel, 1, 5, &offset) && getABIIndexEntryLW(fp, indexO, RUNDLabel, 2, 5, &offset2) && getABIIndexEntryLW(fp, indexO, RUNTLabel, 1, 5, &offset3) && getABIIndexEntryLW(fp, indexO, RUNTLabel, 2, 5, &offset4)) { //char buffer[1025]; char buffer_s[1025]; char buffer_e[1025]; struct tm t; uint rund_s, rund_e, runt_s, runt_e; rund_s = offset; rund_e = offset2; runt_s = offset3; runt_e = offset4; // sprintf(buffer, "%04d%02d%02d.%02d%02d%02d - %04d%02d%02d.%02d%02d%02d", // rund_s >> 16, (rund_s >> 8) & 0xff, rund_s & 0xff, // runt_s >> 24, (runt_s >> 16) & 0xff, (runt_s >> 8) & 0xff, // rund_e >> 16, (rund_e >> 8) & 0xff, rund_e & 0xff, // runt_e >> 24, (runt_e >> 16) & 0xff, (runt_e >> 8) & 0xff); QString buffer = QString("%1%2%3.%4%5%6 - %7%8%9.%10%11%12") .arg((rund_s >> 16), 4,10,QLatin1Char('0')).arg((rund_s >> 8) & 0xff, 2,10,QLatin1Char('0')) .arg((rund_s & 0xff), 2,10,QLatin1Char('0')).arg(runt_s >> 24, 2,10,QLatin1Char('0')) .arg((runt_s >> 16) & 0xff, 2,10,QLatin1Char('0')).arg((runt_s >> 8) & 0xff, 2,10,QLatin1Char('0')) .arg(rund_e >> 16, 4,10,QLatin1Char('0')).arg((rund_e >> 8) & 0xff, 2,10,QLatin1Char('0')) .arg(rund_e & 0xff, 2,10,QLatin1Char('0')).arg(runt_e >> 24, 2,10,QLatin1Char('0')) .arg((runt_e >> 16) & 0xff, 2,10,QLatin1Char('0')).arg((runt_e >> 8) & 0xff, 2,10,QLatin1Char('0')); memset(&t, 0, sizeof(t)); t.tm_mday = rund_s & 0xff; t.tm_mon = ((rund_s >> 8) & 0xff) - 1; t.tm_year = (rund_s >> 16) - 1900; t.tm_hour = runt_s >> 24; t.tm_min = (runt_s >> 16) & 0xff; t.tm_sec = (runt_s >> 8) & 0xff; t.tm_isdst = -1; /* * Convert struct tm to time_t. We ignore the time_t value, but * the conversion process will update the tm_wday element of * struct tm. */ mktime(&t); strftime(buffer_s, 1024, "%a %d %b %H:%M:%S %Y", &t); t.tm_mday = rund_e & 0xff; t.tm_mon = ((rund_e >> 8) & 0xff) - 1; t.tm_year = (rund_e >> 16) - 1900; t.tm_hour = runt_e >> 24; t.tm_min = (runt_e >> 16) & 0xff; t.tm_sec = (runt_e >> 8) & 0xff; t.tm_isdst = -1; /* * Convert struct tm to time_t. We ignore the time_t value, but * the conversion process will update the tm_wday element of * struct tm. */ mktime(&t); strftime(buffer_e, 1024, "%a %d %b %H:%M:%S %Y", &t); sequenceComment.append(QString("DATE=%1 to %2\nRUND=%3\n").arg(buffer_s).arg(buffer_e).arg(buffer)); } /* Get Dye Primer Offset */ if (-1 != getABIString(fp, indexO, PDMFLabel, 1, buffer)) { replace_nl(buffer); sequenceComment.append(QString("DYEP=%1\n").arg(buffer)); } /* Get Machine Name Offset */ if (-1 != getABIString(fp, indexO, MCHNLabel, 1, buffer)) { replace_nl(buffer); sequenceComment.append(QString("MACH=%1\n").arg(buffer)); } /* Machine model */ if (-1 != getABIString(fp, indexO, MODLLabel, 1, buffer)) { replace_nl(buffer); sequenceComment.append(QString("MODL=%1\n").arg(buffer)); } /* Matrix file */ if (-1 != getABIString(fp, indexO, MTXFLabel, 1, buffer)) { replace_nl(buffer); sequenceComment.append(QString("MTXF=%1\n").arg(buffer)); } /* Base calling version */ if (-1 != getABIString(fp, indexO, SPACLabel, 2, buffer)) { replace_nl(buffer); sequenceComment.append(QString("BCAL=%1\n").arg(buffer)); } /* Software versions */ if (-1 != getABIString(fp, indexO, SVERLabel, 1, buffer)) { replace_nl(buffer); sequenceComment.append(QString("VER1=%1\n").arg(buffer)); } if (-1 != getABIString(fp, indexO, SVERLabel, 2, buffer)) { replace_nl(buffer); sequenceComment.append(QString("VER2=%1\n").arg(buffer)); } /* Get Gel Name Offset */ if (-1 != getABIString(fp, indexO, GelNameLabel, 1, buffer)) { replace_nl(buffer); sequenceComment.append(QString("GELN=%1\n").arg(buffer)); } } /* SUCCESS */ cd.hasQV = true; cd.seqLength = sequence.size(); assert(sequence.size() == int(numBases)); cd.traceLength = numPoints; assert(cd.A.size() == int(numPoints + 1)); DNASequence dna(sequence); dna.info.insert(DNAInfo::COMMENT, sequenceComment.split("\n")); dna.info.insert(DNAInfo::ID, sequenceName); QList objects; DNASequenceObject* seqObj = DocumentFormatUtils::addSequenceObject(objects, sequenceName, dna, fs, os); if (os.hasError()) { return NULL; } SAFE_POINT(seqObj != NULL, "DocumentFormatUtils::addSequenceObject returned NULL but didn't set error", NULL); DNAChromatogramObject* chromObj = new DNAChromatogramObject(cd, "Chromatogram"); objects.append(chromObj); objects.append(new TextObject(sequenceComment, "Info")); Document* doc = new Document(this, io->getFactory(), io->getURL(), objects, fs); chromObj->addObjectRelation(GObjectRelation(GObjectReference(seqObj), GObjectRelationRole::SEQUENCE)); return doc; } }//namespace ugene-1.9.8/src/corelibs/U2Formats/src/FastqFormat.cpp0000644000175000017500000003343711651544332021265 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "FastqFormat.h" #include "DocumentFormatUtils.h" #include #include #include #include #include #include #include #include #include /* TRANSLATOR U2::FastqFormat */ namespace U2 { FastqFormat::FastqFormat(QObject* p) : DocumentFormat(p, DocumentFormatFlags_SW, QStringList("fastq")), fn(tr("FASTQ")) { supportedObjectTypes+=GObjectTypes::SEQUENCE; formatDescription = tr("FASTQ format is a text-based format for storing both a biological sequence (usually nucleotide sequence) and its corresponding quality scores. \ Both the sequence letter and quality score are encoded with a single ASCII character for brevity. \ It was originally developed at the Wellcome Trust Sanger Institute to bundle a FASTA sequence and its quality data, \ but has recently become the de facto standard for storing the output of high throughput sequencing instruments."); } RawDataCheckResult FastqFormat::checkRawData(const QByteArray& rawData, const GUrl&) const { const char* data = rawData.constData(); int size = rawData.size(); if (size <= 0 || data[0] != '@' ) { return FormatDetection_NotMatched; } bool hasBinaryBlocks = TextUtils::contains(TextUtils::BINARY, data, size); if (hasBinaryBlocks){ return FormatDetection_NotMatched; } RawDataCheckResult res(FormatDetection_AverageSimilarity); // here we propagate some property values without actual parsing // this must be fixed some day res.properties[RawDataCheckResult_Sequence] = true; res.properties[RawDataCheckResult_SequenceWithGaps] = false; res.properties[RawDataCheckResult_MultipleSequences] = true; res.properties[RawDataCheckResult_MinSequenceSize] = 10; res.properties[RawDataCheckResult_MaxSequenceSize] = 1000; return res; } #define BUFF_SIZE 4096 static bool readLine(QByteArray& target, IOAdapter* io, TaskStateInfo& ti, bool last = false, int * howManyRead = NULL) { bool lineOK = false; qint64 len, total = target.size(); do { if (target.capacity() - total < BUFF_SIZE) { target.reserve(target.capacity() + BUFF_SIZE); } char* buff = target.data() + total; len = io->readUntil(buff, BUFF_SIZE, TextUtils::LINE_BREAKS, IOAdapter::Term_Exclude, &lineOK); if(howManyRead != NULL) { *howManyRead += len; } ti.progress = io->getProgress(); total += len; } while (!ti.cancelFlag && !lineOK && len == BUFF_SIZE); if (lineOK) { target.resize(total); //put back start of another line //io->skip(len - BUFF_SIZE); //eat trailing white char ch; bool gotChar = io->getChar(&ch); bool get_white = gotChar && TextUtils::LINE_BREAKS[uchar(ch)]; if(gotChar && howManyRead != NULL) {*howManyRead = *howManyRead + 1;} assert(get_white); lineOK = get_white; } else if (!last) { ti.setError(U2::FastqFormat::tr("Unexpected end of file")); } return lineOK; } static const QByteArray SEQ_QUAL_SEPARATOR = "+"; // reads until new line, starting with separator // separator not included in read data static bool readUntil(QByteArray & target, IOAdapter * io, TaskStateInfo & ti, const QByteArray & separator) { QByteArray currentLine; while(1) { currentLine.clear(); int howMany = 0; readLine(currentLine, io, ti, false, &howMany); if( ti.hasError() ) { return false; } else if( currentLine.startsWith(separator) ) { io->skip(-1 * (howMany)); break; } else if( currentLine.isEmpty() ) { ti.setError( "Unexpected end of file" ); return false; } target.append(currentLine.trimmed()); } return true; } static bool readBlock( QByteArray & block, IOAdapter * io, TaskStateInfo & ti, qint64 size ) { assert(size >= 0); while( block.size() < size ) { QByteArray curBlock; readLine(curBlock, io, ti); if(ti.hasError()) { return false; } else if( curBlock.isEmpty() ) { ti.setError( "Unexpected end of file" ); return false; } block.append(curBlock); } return true; } /** * FASTQ format specification: http://maq.sourceforge.net/fastq.shtml */ static void load(IOAdapter* io, const GUrl& docUrl, QList& objects, const QVariantMap& hints, TaskStateInfo& ti, int gapSize, int predictedSize, QString& writeLockReason, DocumentLoadMode mode) { writeLockReason.clear(); QByteArray readBuff, secondBuff; bool merge = gapSize!=-1; QByteArray sequence; QByteArray qualityScores; QStringList headers; QSet names; QVector mergedMapping; QByteArray gapSequence((merge ? gapSize : 0), 0); sequence.reserve(predictedSize); qualityScores.reserve(predictedSize); int sequenceStart = 0; while (!ti.cancelFlag) { //read header readBuff.clear(); if (!readLine(readBuff, io, ti, (merge && !headers.isEmpty()) || !names.isEmpty())) { break; } if (readBuff[0]!= '@') { ti.setError(U2::FastqFormat::tr("Not a valid FASTQ file: %1. The @ identifier is not found.").arg(docUrl.getURLString())); break; } //read sequence if (!merge) { sequence.clear(); } else if (sequence.size() > 0) { sequence.append(gapSequence); } sequenceStart = sequence.size(); if(!readUntil(sequence, io, ti, SEQ_QUAL_SEPARATOR)) { break; } int seqLen = sequence.size() - sequenceStart; // read + secondBuff.clear(); secondBuff.reserve(readBuff.size()); if (!readLine(secondBuff, io, ti)) { break; } if (secondBuff[0]!= '+' || (secondBuff.size() != 1 && secondBuff.size() != readBuff.size()) || (readBuff.size() == secondBuff.size() && strncmp(readBuff.data()+1, secondBuff.data()+1, readBuff.size() - 1))) { ti.setError(U2::FastqFormat::tr("Not a valid FASTQ file: %1").arg(docUrl.getURLString())); break; } // read qualities qualityScores.clear(); if( !readBlock(qualityScores, io, ti, seqLen) ) { break; } if ( qualityScores.length() != sequence.length() - sequenceStart) { ti.setError(U2::FastqFormat::tr("Not a valid FASTQ file: %1. Bad quality scores: inconsistent size.").arg(docUrl.getURLString())); } QString headerLine = QString::fromLatin1(readBuff.data()+1, readBuff.length()-1); if (merge) { headers.append(headerLine); mergedMapping.append(U2Region(sequenceStart, seqLen)); } else { QString objName = TextUtils::variate(headerLine, "_", names); names.insert(objName); DNASequence seq( headerLine, sequence ); seq.quality = DNAQuality(qualityScores); seq.info.insert(DNAInfo::ID, headerLine); DocumentFormatUtils::addSequenceObject(objects, objName, seq, hints, ti); if (ti.hasError()) { break; } } if (mode == DocumentLoadMode_SingleObject) { break; } } assert(headers.size() == mergedMapping.size()); if (!ti.hasError() && !ti.cancelFlag && merge && !headers.isEmpty()) { DocumentFormatUtils::addMergedSequenceObject(objects, docUrl, headers, sequence, mergedMapping, hints, ti); } if (merge && headers.size() > 1) { writeLockReason = DocumentFormat::MERGED_SEQ_LOCK; } } Document* FastqFormat::loadDocument( IOAdapter* io, TaskStateInfo& ti, const QVariantMap& _fs, DocumentLoadMode mode) { if( NULL == io || !io->isOpen() ) { ti.setError(L10N::badArgument("IO adapter")); return NULL; } QVariantMap fs = _fs; QList objects; int gapSize = qBound(-1, DocumentFormatUtils::getMergeGap(_fs), 1000*1000); int predictedSize = qMax(100*1000, DocumentFormatUtils::getIntSettings(fs, DocumentReadingMode_SequenceMergingFinalSizeHint, gapSize==-1 ? 0 : io->left())); QString lockReason; load( io, io->getURL(), objects, fs, ti, gapSize, predictedSize, lockReason, mode); if (ti.hasError() || ti.cancelFlag) { qDeleteAll(objects); return NULL; } DocumentFormatUtils::updateFormatSettings(objects, fs); Document* doc = new Document( this, io->getFactory(), io->getURL(), objects, fs, lockReason ); return doc; } #define LINE_LEN 70 void FastqFormat::storeDocument( Document* d, TaskStateInfo& ts, IOAdapter* io ) { foreach (GObject* obj, d->getObjects()) { DNASequenceObject* seqObj = qobject_cast< DNASequenceObject* >( obj); if ( NULL == seqObj ) { ts.setError(L10N::badArgument("NULL sequence" )); continue; } try { //write header; QByteArray block; QString hdr = seqObj->getGObjectName(); block.append('@').append(hdr).append( '\n' ); if (io->writeBlock( block ) != block.length()) { throw 0; } // write sequence const char* seq = seqObj->getSequence().constData(); int len = seqObj->getSequence().length(); for (int i = 0; i < len; i += LINE_LEN ) { int chunkSize = qMin( LINE_LEN, len - i ); if (io->writeBlock( seq + i, chunkSize ) != chunkSize || !io->writeBlock( "\n", 1 )) { throw 0; } } //write transition block.clear(); block.append("+\n"); if (io->writeBlock( block ) != block.length()) { throw 0; } //write quality QByteArray buf; const char* quality = NULL; if (seqObj->getDNASequence().hasQualityScores()) { quality = seqObj->getQuality().qualCodes.constData(); len = seqObj->getQuality().qualCodes.length(); } else { // record the highest possible quality buf.fill('I',len); quality = buf.constData(); } for (int i = 0; i < len; i += LINE_LEN ) { int chunkSize = qMin( LINE_LEN, len - i ); if (io->writeBlock( quality + i, chunkSize ) != chunkSize || !io->writeBlock( "\n", 1 )) { throw 0; } } } catch (int) { GUrl url = seqObj->getDocument() ? seqObj->getDocument()->getURL() : GUrl(); ts.setError(L10N::errorWritingFile(url)); } } } GObject *FastqFormat::loadObject(IOAdapter *io, TaskStateInfo &ti) { DNASequence *seq = loadSequence(io, ti); if (ti.hasError()) { return NULL; } return new DNASequenceObject(seq->getName(), *seq); } DNASequence *FastqFormat::loadSequence(IOAdapter* io, TaskStateInfo& ti) { if( NULL == io || !io->isOpen() ) { ti.setError(L10N::badArgument("IO adapter")); return NULL; } QByteArray readBuff, secondBuff; QByteArray sequence; QByteArray qualityScores; int predictedSize = 1000; sequence.reserve(predictedSize); qualityScores.reserve(predictedSize); //read header if (!readLine(readBuff, io, ti)) { return NULL; } if (readBuff[0]!= '@') { ti.setError("Not a valid FASTQ file. The @ identifier is not found."); return NULL; } //read sequence if(!readUntil(sequence, io, ti, SEQ_QUAL_SEPARATOR)) { return NULL; } int seqLen = sequence.size(); // read + secondBuff.reserve(readBuff.size()); if (!readLine(secondBuff, io, ti)) { return NULL; } if (secondBuff[0]!= '+' || (secondBuff.size() != 1 && secondBuff.size() != readBuff.size()) || (readBuff.size() == secondBuff.size() && strncmp(readBuff.data()+1, secondBuff.data()+1, readBuff.size() - 1))) { ti.setError("Not a valid FASTQ file"); return NULL; } // read qualities if(!readBlock(qualityScores, io, ti, seqLen) ) { return NULL; } if ( qualityScores.length() != sequence.length() ) { ti.setError("Not a valid FASTQ file. Bad quality scores: inconsistent size."); } QByteArray headerLine = QByteArray::fromRawData(readBuff.data()+1, readBuff.length()-1); DNASequence *seq = new DNASequence(headerLine, sequence); seq->quality = DNAQuality(qualityScores); seq->alphabet = AppContext::getDNAAlphabetRegistry()->findById(BaseDNAAlphabetIds::NUCL_DNA_EXTENDED()); assert(seq->alphabet!=NULL); if (!seq->alphabet->isCaseSensitive()) { TextUtils::translate(TextUtils::UPPER_CASE_MAP, const_cast(seq->seq.constData()), seq->seq.length()); } return seq; } }//namespace ugene-1.9.8/src/corelibs/U2Formats/src/PlainTextFormat.h0000644000175000017500000000354011651544332021554 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_PLAIN_TEXT_FORMAT_H_ #define _U2_PLAIN_TEXT_FORMAT_H_ #include #include namespace U2 { class U2FORMATS_EXPORT PlainTextFormat : public DocumentFormat { Q_OBJECT public: PlainTextFormat(QObject* p); virtual DocumentFormatId getFormatId() const {return BaseDocumentFormats::PLAIN_TEXT;} virtual const QString& getFormatName() const {return formatName;} virtual Document* createNewDocument(IOAdapterFactory* io, const QString& url, const QVariantMap& fs = QVariantMap()); virtual Document* loadDocument(IOAdapter* io, TaskStateInfo& ti, const QVariantMap& fs, DocumentLoadMode mode = DocumentLoadMode_Whole); virtual void storeDocument(Document* d, TaskStateInfo& ts, IOAdapter* io); virtual RawDataCheckResult checkRawData(const QByteArray& rawData, const GUrl& = GUrl()) const; static void storeRawData(const QByteArray& data, TaskStateInfo& ts, IOAdapter* io); private: QString formatName; }; }//namespace #endif ugene-1.9.8/src/corelibs/U2Formats/src/StockholmFormat.cpp0000644000175000017500000006260411651544332022150 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "StockholmFormat.h" #include "DocumentFormatUtils.h" #include #include #include #include #include #include #include #include #include /* TRANSLATOR U2::StockholmFormat */ namespace U2 { const QByteArray StockholmFormat::FILE_ANNOTATION_ID = "#=GF ID"; const QByteArray StockholmFormat::FILE_ANNOTATION_AC = "#=GF AC"; const QByteArray StockholmFormat::FILE_ANNOTATION_DE = "#=GF DE"; const QByteArray StockholmFormat::FILE_ANNOTATION_GA = "#=GF GA"; const QByteArray StockholmFormat::FILE_ANNOTATION_NC = "#=GF NC"; const QByteArray StockholmFormat::FILE_ANNOTATION_TC = "#=GF TC"; const QByteArray StockholmFormat::UNI_ANNOTATION_MARK = "# UNIMARK"; const QByteArray StockholmFormat::COLUMN_ANNOTATION_SS_CONS = "#=GC SS_cons"; const QByteArray StockholmFormat::COLUMN_ANNOTATION_RF = "#=GC RF"; StockholmFormat::ReadError::ReadError(const GUrl& url) : StockholmBaseException( L10N::errorReadingFile(url) ){} StockholmFormat::WriteError::WriteError(const GUrl& url) : StockholmBaseException( L10N::errorWritingFile(url) ){} } // U2 const int BUF_SZ = 1024; const int SMALL_BUF_SZ = 128; const char TERM_SYM = '\0'; const int NO_BYTES = 0; const char NEW_LINE = '\n'; const char* HEADER = "# STOCKHOLM 1.0\n\n"; const char* HEADER_MIN = "# STOCKHOLM 1."; const int HEADER_SZ_MIN = 15; const char* EOF_STR = "//"; const char COMMENT_OR_MARKUP_LINE = '#'; const char* EMPTY_STR = ""; const int WRITE_BLOCK_LENGTH = 50; using namespace U2; //other not supported enum AnnotationTag { NO_TAG = -1, ID, AC, DE, SS_CONS, RF, GA, NC, TC }; //other types not supported enum AnnotationType { FILE_ANNOTATION, COLUMN_ANNOTATION, UNI_ANNOTATION }; struct Annotation { AnnotationType type; AnnotationTag tag; QString val; Annotation( AnnotationType ty, AnnotationTag t, QString v ) { type = ty, tag = t; val = v; } virtual ~Annotation(){} }; //#=GF annotations struct FileAnnotation : public Annotation { FileAnnotation( AnnotationTag t, QString v ): Annotation( FILE_ANNOTATION, t, v ){} }; //unipro ugene annotations struct UniAnnotation : public Annotation { UniAnnotation( AnnotationTag t, QString v ): Annotation( UNI_ANNOTATION, t, v ){} }; //#=GC annotations struct ColumnAnnotation : public Annotation { ColumnAnnotation( AnnotationTag t, QString v ): Annotation( COLUMN_ANNOTATION, t, v ){} }; static Annotation* findAnnotation( const QList< Annotation* >& annList, AnnotationType t, AnnotationTag tag ); //you should put annotations here after creation struct AnnotationBank { QList ann_list; void addAnnotation( Annotation* ann ) { if( NULL == ann ) { return; } if( COLUMN_ANNOTATION == ann->type ) { /* Column annotations usually written as blocks with seqs */ assert( SS_CONS == ann->tag || RF == ann->tag ); Annotation* nAnn = findAnnotation( ann_list, COLUMN_ANNOTATION, ann->tag ); if( NULL != nAnn ) { nAnn->val.append( ann->val ); delete ann; return; } } ann_list.append( ann ); } ~AnnotationBank() { qDeleteAll( ann_list ); } }; // AnnotationBank static Annotation* findAnnotation( const QList< Annotation* >& annList, AnnotationType t, AnnotationTag tag ) { Annotation* ret = NULL; foreach( Annotation* a, annList ) { assert( NULL != a ); if( a->type == t && a->tag == tag ) { ret = a; break; } } return ret; } static Annotation* getAnnotation( const QByteArray& l ) { QByteArray line = l.trimmed(); if ( line.startsWith( StockholmFormat::FILE_ANNOTATION_ID ) ) { QByteArray val = line.mid( StockholmFormat::FILE_ANNOTATION_ID.size() ).trimmed(); return ( val.size() )? new FileAnnotation( ID , val ) : NULL; } else if( line.startsWith( StockholmFormat::FILE_ANNOTATION_AC ) ) { QByteArray val = line.mid( StockholmFormat::FILE_ANNOTATION_AC.size() ).trimmed(); return ( val.size() )? new FileAnnotation( AC, val ) : NULL; } else if( line.startsWith( StockholmFormat::FILE_ANNOTATION_DE ) ) { QByteArray val = line.mid( StockholmFormat::FILE_ANNOTATION_DE.size() ).trimmed(); return ( val.size() )? new FileAnnotation( DE, val ) : NULL; } else if( line.startsWith( StockholmFormat::FILE_ANNOTATION_GA ) ) { QByteArray val = line.mid( StockholmFormat::FILE_ANNOTATION_GA.size() ).trimmed(); return ( val.size() )? new FileAnnotation( GA, val ) : NULL; } else if( line.startsWith( StockholmFormat::FILE_ANNOTATION_NC ) ) { QByteArray val = line.mid( StockholmFormat::FILE_ANNOTATION_NC.size() ).trimmed(); return ( val.size() )? new FileAnnotation( NC, val ) : NULL; } else if( line.startsWith( StockholmFormat::FILE_ANNOTATION_TC ) ) { QByteArray val = line.mid( StockholmFormat::FILE_ANNOTATION_TC.size() ).trimmed(); return ( val.size() )? new FileAnnotation( TC, val ) : NULL; } else if ( StockholmFormat::UNI_ANNOTATION_MARK == line ) { return new UniAnnotation( NO_TAG, line ); } else if( line.startsWith( StockholmFormat::COLUMN_ANNOTATION_SS_CONS ) ) { QByteArray val = line.mid( StockholmFormat::COLUMN_ANNOTATION_SS_CONS.size() ).trimmed(); return ( val.size() )? new ColumnAnnotation( SS_CONS, val ) : NULL; } else if( line.startsWith( StockholmFormat::COLUMN_ANNOTATION_RF ) ) { QByteArray val = line.mid( StockholmFormat::COLUMN_ANNOTATION_RF.size() ).trimmed(); return ( val.size() )? new ColumnAnnotation( RF, val ) : NULL; } return NULL; } static QString getMsaName( const AnnotationBank& ann_bank ) { foreach( Annotation* ann, ann_bank.ann_list ) { assert( NULL != ann ); if ( FILE_ANNOTATION == ann->type && ID == ann->tag ) { return ann->val; } } return QString::null; } static bool isUniFile( const AnnotationBank& ann_bank ) { foreach( Annotation* ann, ann_bank.ann_list ) { assert( NULL != ann ); if ( UNI_ANNOTATION == ann->type && StockholmFormat::UNI_ANNOTATION_MARK == ann->val ) { return true; } } return false; } static QString getAnnotationName( Annotation* ann ) { assert( NULL != ann ); AnnotationType t = ann->type; switch( t ) { case UNI_ANNOTATION: return QString( StockholmFormat::UNI_ANNOTATION_MARK ); case FILE_ANNOTATION: { AnnotationTag tag = ann->tag; switch( tag ) { case ID: return QString( StockholmFormat::FILE_ANNOTATION_ID ); case AC: return QString( StockholmFormat::FILE_ANNOTATION_AC ); case DE: return QString( StockholmFormat::FILE_ANNOTATION_DE ); case GA: return QString( StockholmFormat::FILE_ANNOTATION_GA ); case NC: return QString( StockholmFormat::FILE_ANNOTATION_NC ); case TC: return QString( StockholmFormat::FILE_ANNOTATION_TC ); default: assert( false ); } } case COLUMN_ANNOTATION: { AnnotationTag tag = ann->tag; switch( tag ) { case SS_CONS: return QString( StockholmFormat::COLUMN_ANNOTATION_SS_CONS ); case RF: return QString( StockholmFormat::COLUMN_ANNOTATION_RF ); default: assert( false ); } } default: assert( false ); } return QString(); } static QHash< QString, QString > getAnnotationMap( const AnnotationBank& annBank ) { QHash< QString, QString > ret; foreach( Annotation* ann, annBank.ann_list ) { assert( NULL != ann ); QString annName = getAnnotationName( ann ); ret[annName] = QString( ann->val ); } return ret; } template static void checkValThrowException( bool expected, T val1, T val2, const StockholmFormat::StockholmBaseException& e ) { if ( expected != ( val1 == val2 ) ) { throw e; } } static bool checkHeader( const char* data, int sz ) { assert( NULL != data && 0 <= sz ); if ( HEADER_SZ_MIN > sz ) { return false; } return QByteArray( data, sz ).startsWith( HEADER_MIN ); } //returns true if the line was skipped static bool skipCommentOrMarkup( IOAdapter* io, AnnotationBank& ann_bank ) { assert( NULL != io ); QByteArray buf( BUF_SZ, TERM_SYM ); bool term_there = false; int ret = io->readUntil( buf.data(), BUF_SZ, TextUtils::LINE_BREAKS, IOAdapter::Term_Exclude, &term_there ); checkValThrowException( false, -1, ret, StockholmFormat::ReadError(io->getURL()) ); if ( COMMENT_OR_MARKUP_LINE == buf[0] ) { QByteArray line; line.append( QByteArray( buf.data(), ret ) ); while ( !term_there ) { ret = io->readUntil( buf.data(), BUF_SZ, TextUtils::LINE_BREAKS, IOAdapter::Term_Exclude, &term_there ); checkValThrowException( false, -1, ret,StockholmFormat::ReadError(io->getURL()) ); if ( NO_BYTES == ret ) { break; } line.append( QByteArray( buf.data(), ret ) ); } ann_bank.addAnnotation( getAnnotation( line ) ); return true; } io->skip( -ret ); return false; } static void skipBlankLines( IOAdapter* io, QByteArray* lines = NULL ) { assert( NULL != io ); char c = 0; bool work = true; while ( work ) { int ret = io->readBlock( &c, 1 ); checkValThrowException( false, -1, ret, StockholmFormat::ReadError(io->getURL()) ); if ( NO_BYTES == ret ) { return; } work = TextUtils::LINE_BREAKS[(uchar)c] || TextUtils::WHITES[(uchar)c]; if ( lines && TextUtils::LINE_BREAKS[(uchar)c] ) { lines->append( c ); } } io->skip( -1 ); } //skips all that it can static void skipMany( IOAdapter* io, AnnotationBank& ann_bank ) { assert( NULL != io ); char c = 0; while ( 1 ) { bool ret = io->getChar( &c ); checkValThrowException( false, false, ret, StockholmFormat::ReadError(io->getURL()) ); if ( COMMENT_OR_MARKUP_LINE == c ) { io->skip( -1 ); skipCommentOrMarkup( io, ann_bank ); continue; } else if ( TextUtils::LINE_BREAKS[(uchar)c] || TextUtils::WHITES[(uchar)c] ) { skipBlankLines( io ); continue; } io->skip( -1 ); break; } } static bool eofMsa( IOAdapter* io ) { assert( NULL != io ); QByteArray buf( SMALL_BUF_SZ, TERM_SYM ); int ret = io->readUntil( buf.data(), SMALL_BUF_SZ, TextUtils::LINE_BREAKS, IOAdapter::Term_Include ); checkValThrowException( false, -1, ret, StockholmFormat::ReadError(io->getURL()) ); io->skip( -ret ); return EOF_STR == QByteArray( buf.data(), ret ).trimmed(); } static void readEofMsa( IOAdapter* io ) { assert( eofMsa( io ) ); QByteArray buf( SMALL_BUF_SZ, TERM_SYM ); int ret = io->readUntil( buf.data(), SMALL_BUF_SZ, TextUtils::LINE_BREAKS, IOAdapter::Term_Include ); checkValThrowException( false, -1, ret, StockholmFormat::ReadError(io->getURL()) ); } //returns end of sequence name in line static int getLine( IOAdapter* io, QByteArray& to ) { assert( NULL != io ); QByteArray buf( BUF_SZ, TERM_SYM ); bool there = false; while ( !there ) { int ret = io->readUntil( buf.data(), BUF_SZ, TextUtils::LINE_BREAKS, IOAdapter::Term_Exclude, &there ); checkValThrowException( false, -1, ret, StockholmFormat::ReadError(io->getURL()) ); if( NO_BYTES == ret ) { break; } to.append( QByteArray( buf.data(), ret ) ); } int sz = to.size(); int i = 0; for ( i = 0; i < sz; ++i ) { if ( TextUtils::WHITES[(uchar)to[i]] ) { break; } } return i; } static bool blockEnded( IOAdapter* io ) { assert( NULL != io ); QByteArray lines; skipBlankLines( io, &lines ); if ( eofMsa( io ) ) { return true; } int nl_count = 0; int lines_sz = lines.size(); for( int i = 0; i < lines_sz; ++i ) { nl_count = ( NEW_LINE == lines[i] )? nl_count + 1: nl_count; } return 1 < nl_count; } //calls after reading a block static bool checkSeqLength( const MAlignment& msa ) { int sz = msa.getNumRows(); int seq_length = (sz > 0)? msa.getRow(0).getCoreLength(): -1; bool ret = ( sz )? true: false; for ( int i = 0; i < sz; ++i ) { const MAlignmentRow & row = msa.getRow(i); int rowLength = row.getCoreLength(); if ( !( ret = ret && ( seq_length == rowLength ) ) ) { break; } } return ret; } static bool nameWasBefore( const MAlignment& msa, const QString& name ) { int n = msa.getNumRows(); bool ret = false; for( int i = 0; i < n; ++i ) { if ( name == msa.getRow(i).getName()) { ret = true; break; } } return ret; } static void changeGaps( QByteArray& seq ) { int seq_sz = seq.size(); for( int i = 0; i < seq_sz; ++i ) { if ( '.' == seq[i] ) { seq[i] = '-'; } } } // returns true if operation was not canceled static bool loadOneMsa( IOAdapter* io, TaskStateInfo& tsi, MAlignment& msa, AnnotationBank& ann_bank ) { assert( NULL != io ); QByteArray buf( BUF_SZ, TERM_SYM ); int ret = 0; //skip header skipBlankLines( io ); ret = io->readUntil( buf.data(), BUF_SZ, TextUtils::LINE_BREAKS, IOAdapter::Term_Exclude ); checkValThrowException( false, -1, ret, StockholmFormat::ReadError(io->getURL()) ); if ( !checkHeader( buf.data(), ret ) ) { throw StockholmFormat::BadFileData( StockholmFormat::tr( "invalid file: bad header line" ) ); } //read blocks bool firstBlock = true; while ( 1 ) { if( tsi.cancelFlag ) { return false; } skipMany( io, ann_bank ); if ( eofMsa( io ) ) { break; } bool hasSeqs = true; int seq_ind = 0; while ( hasSeqs ) { QByteArray line; int name_end = getLine( io, line ); QByteArray name = line.left( name_end ); QByteArray seq = line.mid( name_end + 1 ).trimmed(); if ( name.startsWith( COMMENT_OR_MARKUP_LINE ) ) { ann_bank.addAnnotation( getAnnotation( line ) ); hasSeqs = !blockEnded( io ); tsi.progress = io->getProgress(); continue; } changeGaps( seq ); if ( firstBlock ) { if ( EMPTY_STR == name ) { throw StockholmFormat::BadFileData( StockholmFormat::tr( "invalid file: empty sequence name" ) ); } if ( nameWasBefore( msa, QString( name.data() ) ) ) { throw StockholmFormat::BadFileData( StockholmFormat::tr( "invalid file: equal sequence names in one block" ) ); } MAlignmentRow row(name.data(), seq); msa.addRow(row); } else { const MAlignmentRow& row = msa.getRow(seq_ind); if( name != row.getName()) { throw StockholmFormat::BadFileData( StockholmFormat::tr( "invalid file: sequence names are not equal in blocks" ) ); } msa.appendChars(seq_ind, seq.constData(), seq.size()); } seq_ind++; hasSeqs = !blockEnded( io ); tsi.progress = io->getProgress(); } firstBlock = false; //check sequence length after every block if ( !checkSeqLength( msa ) ) { throw StockholmFormat::BadFileData( StockholmFormat::tr( "invalid file: sequences in block are not of equal size" ) ); } }// while( 1 ) readEofMsa( io ); skipBlankLines( io ); if ( msa.getNumRows() == 0 ) { throw StockholmFormat::BadFileData( StockholmFormat::tr( "invalid file: empty sequence alignment" ) ); } DocumentFormatUtils::assignAlphabet( msa ); if ( msa.getAlphabet() == NULL) { throw StockholmFormat::BadFileData( StockholmFormat::tr( "invalid file: unknown alphabet" ) ); } return true; } static void setMsaInfoCutoffs( QVariantMap& info, const QString& string, MAlignmentInfo::Cutoffs cof1, MAlignmentInfo::Cutoffs cof2 ) { QByteArray str = string.toAscii(); QTextStream txtStream( str ); float val1 = .0f; float val2 = .0f; txtStream >> val1 >> val2; MAlignmentInfo::setCutoff( info, cof1, val1 ); MAlignmentInfo::setCutoff( info, cof2, val2 ); } static void setMsaInfo( const QHash< QString, QString>& annMap, MAlignment& ma ) { QVariantMap info = ma.getInfo(); if (annMap.contains( StockholmFormat::FILE_ANNOTATION_AC ) ) { MAlignmentInfo::setAccession( info, annMap[StockholmFormat::FILE_ANNOTATION_AC] ); } if (annMap.contains( StockholmFormat::FILE_ANNOTATION_DE ) ) { MAlignmentInfo::setDescription( info, annMap[StockholmFormat::FILE_ANNOTATION_DE] ); } if (annMap.contains( StockholmFormat::COLUMN_ANNOTATION_SS_CONS ) ) { MAlignmentInfo::setSSConsensus( info, annMap[StockholmFormat::COLUMN_ANNOTATION_SS_CONS] ); } if (annMap.contains( StockholmFormat::COLUMN_ANNOTATION_RF ) ) { MAlignmentInfo::setReferenceLine( info, annMap[StockholmFormat::COLUMN_ANNOTATION_RF] ); } if (annMap.contains( StockholmFormat::FILE_ANNOTATION_GA ) ) { setMsaInfoCutoffs( info, annMap[StockholmFormat::FILE_ANNOTATION_GA], MAlignmentInfo::CUTOFF_GA1, MAlignmentInfo::CUTOFF_GA2 ); } if (annMap.contains( StockholmFormat::FILE_ANNOTATION_NC ) ) { setMsaInfoCutoffs( info, annMap[StockholmFormat::FILE_ANNOTATION_NC], MAlignmentInfo::CUTOFF_NC1, MAlignmentInfo::CUTOFF_NC2 ); } if (annMap.contains( StockholmFormat::FILE_ANNOTATION_TC ) ) { setMsaInfoCutoffs( info, annMap[StockholmFormat::FILE_ANNOTATION_TC], MAlignmentInfo::CUTOFF_TC1, MAlignmentInfo::CUTOFF_TC2 ); } ma.setInfo(info); } static void load( IOAdapter* io, QList& l, TaskStateInfo& tsi, bool& uni_file, bool onlyOne ) { assert( NULL != io ); QStringList names_list; QString filename = io->getURL().baseFileName(); while( !io->isEof() ) { MAlignment msa; AnnotationBank ann_bank; QString name; bool notCanceled = true; QHash< QString, QString > annMap; notCanceled = loadOneMsa( io, tsi, msa, ann_bank ); if( !notCanceled ) { break; } uni_file = uni_file || isUniFile( ann_bank ); name = getMsaName( ann_bank ); name = ( QString::null == name || names_list.contains( name ) )? filename + "_" + QString::number( l.size() ): name; names_list.append( name ); msa.setName( name ); annMap = getAnnotationMap( ann_bank ); setMsaInfo( annMap, msa ); MAlignmentObject* obj = new MAlignmentObject(msa); obj->setIndexInfo(annMap); l.append( obj ); if( onlyOne ) { break; } } } static int getMaxNameLen( const MAlignment& msa ) { assert( msa.getNumRows() != 0 ); int sz = msa.getNumRows(); int max_len = msa.getRow(0).getName().size(); for( int i = 0; i < sz; ++i ) { int name_len = msa.getRow(i).getName().size(); max_len = ( max_len < name_len )? name_len: max_len; } return max_len; } //returns a gap between name and sequence in block static QByteArray getNameSeqGap( int diff ) { assert( 0 <= diff ); QByteArray ret = " "; for( int i = 0; i < diff; ++i ) { ret.append( " " ); } return ret; } static void save( IOAdapter* io, const MAlignment& msa, const QString& name ) { assert( NULL != io ); assert( msa.getNumRows() ); int ret = 0; QByteArray header( HEADER ); ret = io->writeBlock( header ); checkValThrowException( true, header.size(), ret, StockholmFormat::WriteError(io->getURL()) ); QByteArray unimark = StockholmFormat::UNI_ANNOTATION_MARK + "\n\n"; ret = io->writeBlock( unimark ); checkValThrowException( true, unimark.size(), ret, StockholmFormat::WriteError(io->getURL()) ); QByteArray idAnn = StockholmFormat::FILE_ANNOTATION_ID + " " + name.toAscii() + "\n\n"; ret = io->writeBlock( idAnn ); checkValThrowException( true, idAnn.size(), ret, StockholmFormat::WriteError(io->getURL()) ); //write sequences int name_max_len = getMaxNameLen( msa ); int seq_len = msa.getLength(); int cur_seq_pos = 0; while ( 0 < seq_len ) { int block_len = ( WRITE_BLOCK_LENGTH >= seq_len )? seq_len: WRITE_BLOCK_LENGTH; //write block int nRows = msa.getNumRows(); for( int i = 0; i < nRows; ++i ) { const MAlignmentRow& row = msa.getRow(i); QByteArray name = row.getName().toAscii(); TextUtils::replace(name.data(), name.length(), TextUtils::WHITES, '_'); name += getNameSeqGap( name_max_len - row.getName().size() ); ret = io->writeBlock( name ); checkValThrowException( true, name.size(), ret, StockholmFormat::WriteError(io->getURL()) ); QByteArray seq = row.mid( cur_seq_pos, block_len ).toByteArray(block_len) + NEW_LINE; ret = io->writeBlock( seq ); checkValThrowException( true, seq.size(), ret, StockholmFormat::WriteError(io->getURL()) ); } ret = io->writeBlock( QByteArray( "\n\n" ) ); checkValThrowException( true, 2, ret, StockholmFormat::WriteError(io->getURL()) ); seq_len -= block_len; cur_seq_pos += block_len; } //write eof ret = io->writeBlock( QByteArray( "//\n" ) ); checkValThrowException( true, 3, ret, StockholmFormat::WriteError(io->getURL()) ); } namespace U2 { StockholmFormat::StockholmFormat( QObject *obj ) : DocumentFormat( obj , DocumentFormatFlags_SW, QStringList() << "sto") { format_name = tr( "Stockholm" ); supportedObjectTypes+=GObjectTypes::MULTIPLE_ALIGNMENT; } Document* StockholmFormat::loadDocument( IOAdapter* io, TaskStateInfo& ti, const QVariantMap& fs , DocumentLoadMode mode) { if( NULL == io || !io->isOpen() ) { ti.setError(L10N::badArgument("IO adapter")); return NULL; } QList obj_list; try { bool uniFile = false; QString write_lock_reason; load( io, obj_list, ti, uniFile, mode); if ( !uniFile ) { write_lock_reason = DocumentFormat::CREATED_NOT_BY_UGENE; } return new Document( this, io->getFactory(), io->getURL(), obj_list, fs, write_lock_reason ); } catch ( const StockholmBaseException& e ) { ti.setError(e.msg); } catch ( ... ) { ti.setError(tr( "unknown error occurred" )); } qDeleteAll(obj_list); return NULL; } void StockholmFormat::storeDocument( Document* doc, TaskStateInfo& ti, IOAdapter* io ) { try { foreach( GObject* p_obj, doc->getObjects() ) { const MAlignmentObject* aln_obj = qobject_cast( p_obj ); assert( NULL != aln_obj ); save( io, aln_obj->getMAlignment(), aln_obj->getGObjectName() ); if( ti.cancelFlag ) { return; } } } catch( const StockholmBaseException& ex ) { ti.setError( ex.msg ); } catch(...) { ti.setError(tr( "unknown error occurred" )); } } RawDataCheckResult StockholmFormat::checkRawData(const QByteArray& data, const GUrl&) const { bool headerIsOK = checkHeader( data.constData(), data.size()); return headerIsOK ? FormatDetection_VeryHighSimilarity : FormatDetection_NotMatched; } bool StockholmFormat::isObjectOpSupported( const Document *doc, DocObjectOp op, GObjectType t ) const { Q_UNUSED( op ); Q_UNUSED( doc ); assert( NULL != doc ); if ( GObjectTypes::MULTIPLE_ALIGNMENT != t ) { return false; } /*if (op == DocumentFormat::DocObjectOp_Add) { return doc->getObjects().isEmpty(); } return false;*/ return true; } } // U2 ugene-1.9.8/src/corelibs/U2Formats/src/StreamSequenceReader.h0000644000175000017500000000435211651544332022544 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_STREAM_SEQUENCE_READER_H_ #define _U2_STREAM_SEQUENCE_READER_H_ #include #include #include #include #include #include #include namespace U2 { class Document; class DocumentFormat; class IOAdapter; /** * * Class provides stream reading for large sequence files. * For example, dna assembly short reads usually are * of size 1GB and more, it is impossible to store whole file in RAM. * Note, that document format has to support DocumentReadMode_SingleObject * to be read by StreamSequenceReader. * In case of multiple files, they will be read subsequently. * */ class U2FORMATS_EXPORT StreamSequenceReader { struct ReaderContext { ReaderContext() : io(NULL), format(NULL) {} IOAdapter* io; DocumentFormat* format; }; QList readers; int currentReaderIndex; std::auto_ptr currentSeq; bool errorOccured; bool lookupPerformed; QString errorMessage; TaskStateInfo taskInfo; public: StreamSequenceReader(); ~StreamSequenceReader(); bool init(const QList& urls); bool hasNext(); bool hasError() { return errorOccured; } int getProgress(); QString getErrorMessage(); DNASequence* getNextSequenceObject(); }; } //namespace #endif //_U2_STREAM_SEQUENCE_READER_H_ ugene-1.9.8/src/corelibs/U2Formats/src/PDWFormat.h0000644000175000017500000000403211651544332020273 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_PDW_FORMAT_H_ #define _U2_PDW_FORMAT_H_ #include #include namespace U2 { class IOAdapter; class Annotation; class AnnotationTableObject; class DNASequenceObject; class U2FORMATS_EXPORT PDWFormat : public DocumentFormat { Q_OBJECT public: PDWFormat(QObject* p); virtual DocumentFormatId getFormatId() const {return BaseDocumentFormats::PDW;} virtual const QString& getFormatName() const {return formatName;} virtual Document* loadDocument( IOAdapter* io, TaskStateInfo& ti, const QVariantMap& fs, DocumentLoadMode mode = DocumentLoadMode_Whole); virtual RawDataCheckResult checkRawData(const QByteArray& rawData, const GUrl& = GUrl()) const; private: static QByteArray parseSequence(IOAdapter* io, TaskStateInfo& ti); static Annotation* parseAnnotation(IOAdapter* io, TaskStateInfo& ti); static QByteArray readPdwValue(const QByteArray& readBuf, const QByteArray& valueName); void load(IOAdapter* io, const GUrl& docUrl, QList& objects, TaskStateInfo& ti, DNASequenceObject* dnaObj, AnnotationTableObject* aObj); QString formatName; }; }//namespace #endif ugene-1.9.8/src/corelibs/U2Formats/src/NEXUSFormat.cpp0000644000175000017500000005567411651544332021120 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "NEXUSFormat.h" #include "NEXUSParser.h" #include #include #include #include #include #include #include #include namespace U2 { NEXUSFormat::NEXUSFormat(QObject *p) : DocumentFormat(p, DocumentFormatFlags(0), QStringList()<<"nex"<<"nxs") // disable writing and streaming for now { formatName = tr("NEXUS"); supportedObjectTypes += GObjectTypes::MULTIPLE_ALIGNMENT; supportedObjectTypes += GObjectTypes::PHYLOGENETIC_TREE; } const int Tokenizer::BUFF_SIZE = 1024; QString Tokenizer::look() { if (next.isNull()) { get(); } return next; } QString Tokenizer::get() { QString token = ""; QChar c; QChar quote; int nest = 0; enum State {NONE, QUOTED, WORD, NUMBER, SPACE, COMMENT, SYMBOL} state = NONE; while (true) { if (buffStream.atEnd()) { QByteArray tmp(BUFF_SIZE, '\0'); int len = io->readBlock(tmp.data(), BUFF_SIZE); if (len == 0) { break; } buff = tmp.left(len); buffStream.setString(&buff); } if (state == NONE) { // look at first symbol buffStream >> c; buffStream.seek(buffStream.pos() - 1); if (c == '"' || c == '\'') { state = QUOTED; } else if (c.isLetter() || c == '_') { state = WORD; } else if (c.isDigit() || c == '.') { state = NUMBER; } else if (c.isSpace()) { state = SPACE; } else if (c == '[') { state = COMMENT; } else { state = SYMBOL; } } if (state == QUOTED) { // read quoted string buffStream >> quote; buffStream >> c; while (c != quote && !c.isNull()) { token += c; buffStream >> c; } if (c == quote) { // next quoted string may appear 'asd''fgh' == 'asdfgh' buffStream >> c; buffStream.seek(buffStream.pos() - 1); if (c == '"' || c == '\'') { state = QUOTED; continue; } else { state = NONE; break; } } else { continue; } } else if (state == WORD) { // read whole word buffStream >> c; while ((c.isLetter() || c.isDigit() || c == '_' || c == '.') && !c.isNull()) { token += c; buffStream >> c; } if (!c.isNull()) { // put last symbol back buffStream.seek(buffStream.pos() - 1); state = NONE; break; } else { continue; } } else if (state == NUMBER) { // read whole number buffStream >> c; while ((c.isDigit() || c == '.' || c == 'e' ||c == 'E' || c == '+' ||c == '-') && !c.isNull()) { token += c; buffStream >> c; } if (!c.isNull()) { // put last symbol back buffStream.seek(buffStream.pos() - 1); state = NONE; break; } else { continue; } } else if (state == SPACE) { // skip whites buffStream.skipWhiteSpace(); state = NONE; if (token.isEmpty()) { continue; } else { break; } } else if (state == COMMENT) { // skip comment buffStream >> c; while (!c.isNull()) { if (c == ']') { --nest; } else if (c == '[') { ++nest; } if (nest == 0) { state = NONE; break; } buffStream >> c; } continue; } else if (state == SYMBOL) { // return single symbol buffStream >> c; token = c; state = NONE; break; } else { assert(0 && "Unknown status, see enum"); } } QString tmp = next; next = token; return tmp; } void Tokenizer::skipUntil(QString what, Qt::CaseSensitivity cs) { while (look().compare(what, cs) != 0) { get(); } } QStringList Tokenizer::getUntil(QString what, Qt::CaseSensitivity cs) { QStringList words; while (look().compare(what, cs) != 0) { words.append(get()); } return words; } QString Tokenizer::readUntil(QRegExp rwhat) { // push 'next' token back QString str = next + buffStream.readAll(); QString result = ""; while (true) { int pos = str.indexOf(rwhat); if (pos < 0) { result += str; QByteArray tmp(BUFF_SIZE, '\0'); int len = io->readBlock(tmp.data(), BUFF_SIZE); if (len == 0) { break; } str = tmp.left(len); } else { result += str.left(pos); buff = str.mid(pos); buffStream.setString(&buff); break; } } get(); return result; } // lower case const QString NEXUSParser::BEGIN = "begin"; const QString NEXUSParser::END = "end"; const QString NEXUSParser::BLK_TAXA = "taxa"; const QString NEXUSParser::BLK_DATA = "data"; const QString NEXUSParser::BLK_CHARACTERS = "characters"; const QString NEXUSParser::CMD_DIMENSIONS = "dimensions"; const QString NEXUSParser::CMD_FORMAT = "format"; const QString NEXUSParser::CMD_MATRIX = "matrix"; const QString NEXUSParser::BLK_TREES = "trees"; const QString NEXUSParser::CMD_TREE = "tree"; const QString NEXUSParser::CMD_UTREE = "utree"; QList NEXUSParser::loadObjects() { while (tz.look() != "") { if (!readBlock(global)) { break; } reportProgress(); } return objects; } bool NEXUSParser::skipCommand() { tz.skipUntil(";"); if (tz.get() != ";"){ errors.append("\';\' expected"); return false; } return true; } bool NEXUSParser::readSimpleCommand(Context &ctx) { tz.skip(); // command name QStringList wl = tz.getUntil(";"); while (!wl.isEmpty()) { QString name = wl.takeFirst(); QString value = ""; if (wl.size() > 1 && wl.first() == "=") { wl.removeFirst(); value = wl.takeFirst(); } ctx.insert(name, value); } if (tz.get() != ";"){ errors.append("\';\' expected"); return false; } return true; } bool NEXUSParser::readBlock(Context &ctx) { if (tz.get().toLower() != BEGIN){ errors.append(QString("\'%1\' expected").arg(BEGIN)); return false; } QString blockName = tz.get().toLower(); if (tz.get().toLower() != ";"){ errors.append(QString("\'%1\' expected").arg(";")); return false; } if (blockName == BLK_TAXA) { if (!readTaxaContents(ctx)) { return false; } } else if (blockName == BLK_DATA || blockName == BLK_CHARACTERS) { if (!readDataContents(ctx)) { return false; } } else if (blockName == BLK_TREES) { if (!readTreesContents(ctx)) { return false; } } else { if (!skipBlockContents()) { return false; } } if (tz.get().toLower() != END) { errors.append(QString("\'%1\' expected").arg(END)); return false; } if ((tz.get().toLower() != ";")){ errors.append(QString("\'%1\' expected").arg(";")); return false; } return true; } bool NEXUSParser::skipBlockContents() { tz.skipUntil(END); return true; } bool NEXUSParser::readTaxaContents(Context&) { while (true) { QString cmd = tz.look().toLower(); if (cmd == END) { break; } else { if (!skipCommand()) { return false; } } } return true; } bool NEXUSParser::readDataContents(Context &ctx) { while (true) { QString cmd = tz.look().toLower(); // cmd name if (cmd == CMD_FORMAT || cmd == CMD_DIMENSIONS) { if (!readSimpleCommand(ctx)) { return false; } } else if (cmd == CMD_MATRIX) { tz.get(); // cmd name == CMD_MATRIX QMap rows; // Read matrix while (true) { QString name = tz.get(); if (name == "") { errors.append("Unexpected EOF"); return false; } if (name == ";") { break; } name.replace('_', ' '); // Read value QString value = ""; value = tz.readUntil(QRegExp("\n|;")); // Remove spaces value.remove(QRegExp("\\s")); // Replace gaps if (ctx.contains("gap")) { value.replace(ctx["gap"], QChar(MAlignment_GapChar)); } if (rows.contains(name)) { MAlignmentRow &row = rows[name]; row.append( MAlignmentRow(name, value.toAscii()), row.getCoreEnd() ); } else { rows.insert(name, MAlignmentRow(name, value.toAscii())); } reportProgress(); } // Build MAlignment object MAlignment ma(tz.getIO()->getURL().baseFileName(), 0, rows.values()); // Determine alphabet & replace missing chars if (ctx.contains("missing")) { char missing = ctx["missing"].toAscii()[0]; DocumentFormatUtils::assignAlphabet(ma, missing); if (ma.getAlphabet() == 0) { errors.append("Unknown alphabet"); return false; } char ourMissing = ma.getAlphabet()->getDefaultSymbol(); // replace missing for (int i = 0; i < ma.getNumRows(); ++i) { ma.replaceChars(i, missing, ourMissing); } } else { DocumentFormatUtils::assignAlphabet(ma); } if (ma.getAlphabet() == 0) { errors.append("Unknown alphabet"); return false; } addObject(new MAlignmentObject(ma)); } else if (cmd == END) { break; } else { if (!skipCommand()) { return false; } } } return true; } bool NEXUSParser::readTreesContents(Context&) { while (true) { QString cmd = tz.look().toLower(); // cmd name bool weightDefault = false, weightValue = false; if (cmd == CMD_TREE || cmd == CMD_UTREE) { tz.skip(); // cmd name == CMD_TREE QString treeName = "Tree"; // "tree_name =" or "=" if (tz.look() == ";") { warnings.append("Empty tree"); continue; } else if (tz.look() == "=") { tz.skip(); // "=" } else { treeName = tz.get(); if (tz.get() != "="){ errors.append(QString("\'%1\' expected").arg("=")); return false; } } QStack nodeStack; nodeStack.push(new PhyNode()); QStack branchStack; enum State {NAME, WEIGHT} state = NAME; QString acc, name; QSet ops = QSet()<<"("<<","<<")"<<":"<<";"; while (true) { QString tok = tz.get(); if (tok == "") { errors.append("Unexpected EOF"); break; } if (!ops.contains(tok)) { acc += tok; continue; } if (tok == "(") { if (!acc.isEmpty()) { errors.append(QString("\'%1\' expected").arg(",")); break; } PhyNode *top = new PhyNode(); PhyBranch *br = nodeStack.top()->addBranch(nodeStack.top(), top, 1); nodeStack.push(top); branchStack.push(br); } else if (tok == "," || tok == ")") { if (nodeStack.size() < 2){ errors.append(QString("Unexpected \'%1\'").arg(")")); break; } double weight = 1; // default value if (state == WEIGHT) { if (!acc.isEmpty()) { // convert weight bool ok; weight = acc.toDouble(&ok); if (!ok){ errors.append(QString("Invalid weight value \'%1\'").arg(acc)); break; } weightValue = true; } else { // was ':' but was no value errors.append("Weight value expected"); break; } } else { assert(state == NAME); weightDefault = true; name = acc; acc.clear(); } name.replace('_', ' '); nodeStack.top()->name = name; branchStack.top()->distance = weight; nodeStack.pop(); branchStack.pop(); if (tok == ",") { PhyNode *top = new PhyNode(); PhyBranch *br = nodeStack.top()->addBranch(nodeStack.top(), top, 1); nodeStack.push(top); branchStack.push(br); } acc.clear(); state = NAME; } else if (tok == ":") { if (state == WEIGHT) { errors.append(QString("Unexpected \'%1\'").arg(":")); break; } name = acc; acc.clear(); state = WEIGHT; } else if (tok == ";") { if (state == NAME) { name = acc; } name.replace('_', ' '); nodeStack.top()->name = name; break; } else { assert(0 && "invalid state: all non ops symbols must go to acc"); } } if (weightDefault && weightValue) { errors.append("Weight value expected"); } else if (weightDefault) { warnings.append(QString("Tree '%1' weights set by default (1.0)").arg(treeName)); } if (hasError()) { // clean up PhyNode *n = nodeStack.pop(); delete n; // PhyNode::~PhyNode() is recursive warnings.push_back(QString("Tree '%1' ignored due following errors: %2").arg(treeName, errors.takeLast())); continue; } else { assert(nodeStack.size() == 1 && "Node stack must contain only root"); // build tree object PhyTree tree(new PhyTreeData()); tree->rootNode = nodeStack.pop(); addObject(new PhyTreeObject(tree, treeName)); } } else if (cmd == END) { break; } else { if (!skipCommand()) { return false; } } } return true; } void NEXUSParser::addObject(GObject *obj) { QString name = TextUtils::variate(obj->getGObjectName(), "_", objectNames, false, 1); objectNames.insert(name); obj->setGObjectName(name); objects.append(obj); } QList NEXUSFormat::loadObjects(IOAdapter *io, TaskStateInfo &ti) { assert(io && "io must exist"); const int HEADER_LEN = 6; QByteArray header(HEADER_LEN, 0); int rd = io->readLine(header.data(), HEADER_LEN); header.truncate(rd); if (header != "#NEXUS") { ti.setError(tr("#NEXUS header missing")); return QList(); } NEXUSParser parser(io, ti); QList objects = parser.loadObjects(); if (parser.hasError()) { QByteArray msg = "NEXUSParser: "; msg += parser.getErrors().first(); ti.setError(tr(msg.data())); } return objects; } Document* NEXUSFormat::loadDocument(IOAdapter *io, TaskStateInfo &ti, const QVariantMap &fs, DocumentLoadMode) { assert(io && "IO must exist"); QList objects = loadObjects(io, ti); if (ti.hasError()) { qDeleteAll(objects); return 0; } Document *d = new Document(this, io->getFactory(), io->getURL(), objects, fs); return d; } void writeHeader(IOAdapter *io, TaskStateInfo&) { QByteArray line; QTextStream(&line) << "#NEXUS\n\n"; io->writeBlock(line); } void writeMAligment(const MAlignment &ma, IOAdapter *io, TaskStateInfo&) { QByteArray line; QByteArray tabs, tab(4, ' '); QTextStream(&line) << tabs << "begin data;" << "\n"; io->writeBlock(line); line.clear(); tabs.append(tab); int ntax, nchar; ntax = ma.getNumRows(); nchar = ma.getLength(); QTextStream(&line) << tabs << "dimensions ntax=" << ntax << " nchar=" << nchar << ";\n"; io->writeBlock(line); line.clear(); QTextStream(&line) << tabs << "format gap=" << MAlignment_GapChar << ";\n"; io->writeBlock(line); line.clear(); QTextStream(&line) << tabs << "matrix" << "\n"; io->writeBlock(line); line.clear(); tabs.append(tab); const QList &rows = ma.getRows(); int nameMaxLen = 0; foreach (MAlignmentRow row, rows) { if (row.getName().size() > nameMaxLen) { nameMaxLen = row.getName().size(); } } nameMaxLen += 2; // quotes may appear foreach (const MAlignmentRow& row, rows) { QString name = row.getName(); if (name.contains(QRegExp("\\s"))) { name = "'" + name + "'"; } name = name.leftJustified(nameMaxLen); QTextStream(&line) << tabs << name << " " << row.toByteArray(nchar) << "\n"; io->writeBlock(line); line.clear(); } tabs.chop(tab.size()); QTextStream(&line) << tabs << ";" << "\n"; io->writeBlock(line); line.clear(); tabs.chop(tab.size()); QTextStream(&line) << tabs << "end;" << "\n"; io->writeBlock(line); line.clear(); } static void writeNode(PhyNode* node, IOAdapter* io) { int branches = node->branches.size(); if (branches == 1 && (node->name=="" || node->name=="ROOT")) { assert(node != node->branches[0]->node2); writeNode(node->branches[0]->node2, io); return; } if (branches > 1) { io->writeBlock("(", 1); bool first = true; for (int i = 0; i < branches; ++i) { if (node->branches[i]->node2 != node) { if (first) { first = false; } else { io->writeBlock(",", 1); } writeNode(node->branches[i]->node2, io); io->writeBlock(":", 1); io->writeBlock(QByteArray::number(node->branches[i]->distance)); } } io->writeBlock(")", 1); } else { bool quotes = node->name.contains(QRegExp("\\s")); if (quotes) { io->writeBlock("'", 1); } io->writeBlock(node->name.toAscii()); if (quotes) { io->writeBlock("'", 1); } } } // spike: PhyTreeData don't have own name void writePhyTree(const PhyTree &pt, QString name, IOAdapter *io, TaskStateInfo&) { QByteArray line; QByteArray tabs, tab(4, ' '); QTextStream(&line) << tabs << "begin trees;" << "\n"; io->writeBlock(line); line.clear(); tabs.append(tab); QTextStream(&line) << tabs << "tree " << name << " = "; io->writeBlock(line); line.clear(); writeNode(pt->rootNode, io); io->writeBlock(";\n", 2); tabs.chop(tab.size()); QTextStream(&line) << tabs << "end;" << "\n"; io->writeBlock(line); line.clear(); } void writePhyTree(const PhyTree &pt, IOAdapter *io, TaskStateInfo &ti) { writePhyTree(pt, "Tree", io, ti); } void NEXUSFormat::storeObjects(QList objects, IOAdapter *io, TaskStateInfo &ti) { assert(io && "IO must exist"); writeHeader(io, ti); foreach (GObject *object, objects) { MAlignmentObject *mao = qobject_cast (object); PhyTreeObject *pto = qobject_cast (object); if (mao) { writeMAligment(mao->getMAlignment(), io, ti); io->writeBlock(QByteArray("\n")); } else if (pto) { writePhyTree(pto->getTree(), pto->getGObjectName(), io, ti); io->writeBlock(QByteArray("\n")); } else { ti.setError("No data to write"); return; } } } void NEXUSFormat::storeDocument(Document *d, TaskStateInfo &ts, IOAdapter *io) { QList objects = d->getObjects(); storeObjects(objects, io, ts); } RawDataCheckResult NEXUSFormat::checkRawData(const QByteArray &rawData, const GUrl&) const { if (rawData.startsWith("#NEXUS")) { return FormatDetection_VeryHighSimilarity; } return FormatDetection_NotMatched; } } // namespace U2 ugene-1.9.8/src/corelibs/U2Formats/src/GenbankPlainTextFormat.h0000644000175000017500000000273711651544332023051 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_GENBANK_PLAIN_TEXT_FORMAT_H_ #define _U2_GENBANK_PLAIN_TEXT_FORMAT_H_ #include "EMBLGenbankAbstractDocument.h" namespace U2 { class U2FORMATS_EXPORT GenbankPlainTextFormat : public EMBLGenbankAbstractDocument { Q_OBJECT public: GenbankPlainTextFormat(QObject* p); virtual void storeDocument( Document* d, TaskStateInfo& ts, IOAdapter* io ); virtual RawDataCheckResult checkRawData(const QByteArray& rawData, const GUrl& = GUrl()) const; protected: bool readIdLine(ParserState*); bool readEntry(QByteArray&, ParserState*); //void readAnnotations(ParserState*, int offset); }; }//namespace #endif ugene-1.9.8/src/corelibs/U2Formats/src/ACEFormat.h0000644000175000017500000000363411651544332020240 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_ACE_FORMAT_H_ #define _U2_ACE_FORMAT_H_ #include #include #include #include #include namespace U2 { class IOAdapter; class U2FORMATS_EXPORT ACEFormat : public DocumentFormat { Q_OBJECT public: ACEFormat(QObject* p); virtual DocumentFormatId getFormatId() const { return BaseDocumentFormats::ACE; } virtual const QString& getFormatName() const { return formatName; } virtual Document* loadDocument(IOAdapter* io, TaskStateInfo& ti, const QVariantMap& fs, DocumentLoadMode mode = DocumentLoadMode_Whole); virtual RawDataCheckResult checkRawData(const QByteArray& rawData, const GUrl& = GUrl()) const; private: QString formatName; void load(IOAdapter* io, QList& objects, TaskStateInfo& ti); static const QString CO; static const QString RD; static const QString QA; static const QString AS; static const QString AF; static const QString BQ; }; } //namespace #endif ugene-1.9.8/src/corelibs/U2Formats/src/PDBFormat.cpp0000644000175000017500000010144511651544332020607 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "DocumentFormatUtils.h" #include "PDBFormat.h" namespace U2 { QHash PDBFormat::atomNumMap = createAtomNumMap(); QHash PDBFormat::acronymNameMap; PDBFormat::PDBFormat( QObject* p ) : DocumentFormat(p, DocumentFormatFlag(0), QStringList("pdb")) { formatName = tr("PDB"); formatDescription = tr("The Protein Data Bank (PDB) format provides a standard representation for macromolecular structure data derived from X-ray diffraction and NMR studies."); initUtilityMaps(); AtomConstants::init(); supportedObjectTypes+=GObjectTypes::BIOSTRUCTURE_3D; supportedObjectTypes+=GObjectTypes::SEQUENCE; supportedObjectTypes+=GObjectTypes::ANNOTATION_TABLE; } RawDataCheckResult PDBFormat::checkRawData(const QByteArray& rawData, const GUrl&) const { static const char* headerTag = "HEADER"; static const char* atomTag = "ATOM"; static const char* modelTag = "MODEL"; bool ok = false; if (rawData.startsWith(headerTag) || rawData.startsWith(atomTag) || rawData.startsWith(modelTag) ) { ok = true; } if (!ok) { return FormatDetection_NotMatched; } bool hasBinaryData = TextUtils::contains(TextUtils::BINARY, rawData.constData(), rawData.size()); return hasBinaryData ? FormatDetection_NotMatched : FormatDetection_HighSimilarity; } Document* PDBFormat::loadDocument( IOAdapter* io, TaskStateInfo& ti, const QVariantMap& fs, DocumentLoadMode) { GUrl url = io->getURL(); ioLog.trace("Start PDB parsing: " +url.getURLString()); BioStruct3D bioStruct; PDBParser pdbParser(io); clock_t t1 = clock(); pdbParser.parseBioStruct3D(bioStruct, ti); clock_t t2 = clock(); perfLog.trace("PDB file parsing time: " + QString::number((float)( t2 - t1)/ CLOCKS_PER_SEC )); if (ti.hasError() || ti.cancelFlag) { return NULL; } io->close(); ti.progress = 80; algoLog.trace("Calculating center and max distance..."); bioStruct.calcCenterAndMaxDistance(); ti.progress = 85; algoLog.trace("Generating chains annotations..."); bioStruct.generateAnnotations(); ti.progress = 90; calculateBonds(bioStruct); algoLog.trace("Calculating bonds..."); Document* doc = createDocumentFromBioStruct3D(bioStruct, this, io->getFactory(), url, ti, fs); ioLog.trace("PDB parsing finished: " + url.getURLString()); ti.progress = 100; return doc; } void PDBFormat::initUtilityMaps() { static bool initialized = false; if (!initialized) { // init acronymNameMap // amino acid residues acronymNameMap.insert("ALA", 'A'); acronymNameMap.insert("VAL", 'V'); acronymNameMap.insert("PHE", 'F'); acronymNameMap.insert("PRO", 'P'); acronymNameMap.insert("MET", 'M'); acronymNameMap.insert("ILE", 'I'); acronymNameMap.insert("LEU", 'L'); acronymNameMap.insert("ASP", 'D'); acronymNameMap.insert("GLU", 'E'); acronymNameMap.insert("GLY", 'G'); acronymNameMap.insert("LYS", 'K'); acronymNameMap.insert("ARG", 'R'); acronymNameMap.insert("SER", 'S'); acronymNameMap.insert("THR", 'T'); acronymNameMap.insert("TYR", 'Y'); acronymNameMap.insert("HIS", 'H'); acronymNameMap.insert("CYS", 'C'); acronymNameMap.insert("ASN", 'N'); acronymNameMap.insert("GLN", 'Q'); acronymNameMap.insert("TRP", 'W'); // dna acronymNameMap.insert("DA", 'A'); acronymNameMap.insert("DT", 'T'); acronymNameMap.insert("DG", 'G'); acronymNameMap.insert("DC", 'C'); acronymNameMap.insert("A", 'A'); acronymNameMap.insert("T", 'T'); acronymNameMap.insert("G", 'G'); acronymNameMap.insert("C", 'C'); acronymNameMap.insert("U", 'U'); // now we've initialized utility maps initialized = true; } } PDBFormat::PDBParser::PDBParser(IOAdapter* _io) : io(_io), currentPDBLine(""), currentChainIndex(' ') { currentChainIndex = 1; currentModelIndex = 0; currentChainIndentifier = ' '; flagMultipleModels = false; flagAtomRecordPresent = false; } #define READ_BUF_SIZE 4096 void PDBFormat::PDBParser::parseBioStruct3D( BioStruct3D& biostruct, TaskStateInfo& ti ) { QByteArray readBuff(READ_BUF_SIZE+1, 0); char* buf = readBuff.data(); qint64 len = 0; while (!ti.cancelFlag && !ti.hasError()) { bool lineOk = true; len = io->readUntil(buf, READ_BUF_SIZE, TextUtils::LINE_BREAKS, IOAdapter::Term_Include, &lineOk); if (len == 0) { break; } if (!lineOk) { ti.setError(U2::PDBFormat::tr("Line is too long")); return; } currentPDBLine = QString(QByteArray::fromRawData(buf, len)); ti.progress = io->getProgress()*0.8; if (currentPDBLine.startsWith("HEADER")) { parseHeader(biostruct, ti); continue; } if (currentPDBLine.startsWith("SEQRES")) { parseSequence(biostruct, ti); continue; } if (currentPDBLine.startsWith("HELIX ") || currentPDBLine.startsWith("SHEET ") || currentPDBLine.startsWith("TURN ")) { parseSecondaryStructure(biostruct, ti); continue; } if (currentPDBLine.startsWith("ATOM ") || currentPDBLine.startsWith("HETATM")) { parseAtom(biostruct, ti); continue; } if ( currentPDBLine.startsWith("TER") ) { ++currentChainIndex; continue; } if (currentPDBLine.startsWith("SPLIT ")) { ti.setError(U2::PDBFormat::tr("SPLIT recored is not supported")); break; } if (currentPDBLine.startsWith("MODEL")) { currentChainIndex = 1; parseModel(biostruct, ti); continue; } if (currentPDBLine.startsWith("ENDMDL")) { flagMultipleModels = true; ++currentModelIndex; continue; } } if (ti.cancelFlag || ti.hasError()) { return; } if (!flagAtomRecordPresent) { ti.setError(U2::PDBFormat::tr("Some mandaroty records are absent")); } updateSecStructChainIndexes(biostruct); } void PDBFormat::PDBParser::parseHeader( BioStruct3D& biostruct, TaskStateInfo&) { /* Record Format COLUMNS DATA TYPE FIELD DEFINITION ------------------------------------------------------------------------------------ 1 - 6 Record name "HEADER" 11 - 50 Classifies the molecule(s). 51 - 59 Deposition date. This is the date the coordinates were received at the PDB. 63 - 66 This identifier is unique within the PDB. */ QString desc = currentPDBLine.mid(10,40).trimmed(); QByteArray pdbId = currentPDBLine.mid(62,4).toAscii(); biostruct.descr = desc; biostruct.pdbId = pdbId; } bool PDBFormat::PDBParser::seqResContains(char chainIdentifier, int residueIndex, char acronym) { if (seqResMap.isEmpty()) { // the PDB file doesn't have seq res record -> we cannot use this method return true; } if (!seqResMap.contains(chainIdentifier) || residueIndex == 0) { return false; } QByteArray sequence = seqResMap.value(chainIdentifier); int numChars = sequence.size(); if ( residueIndex <= numChars) { return sequence[residueIndex - 1] == acronym; } else { return false; } } void PDBFormat::PDBParser::parseAtom( BioStruct3D& biostruct, TaskStateInfo&) { /* Record Format COLUMNS DEFINITION 1 - 6 Record name "ATOM " 7 - 11 Atom serial number. 13 - 16 Atom name. 17 Alternate location indicator. 18 - 20 Residue name. 22 Chain identifier. 23 - 26 Residue sequence number. 27 Code for insertion of residues. 31 - 38 Orthogonal coordinates for X in Angstroms. 39 - 46 Orthogonal coordinates for Y in Angstroms. 47 - 54 Orthogonal coordinates for Z in Angstroms. 55 - 60 Occupancy. 61 - 66 Temperature factor. 77 - 78 Element symbol, right-justified. 79 - 80 Charge on the atom. */ if (!flagAtomRecordPresent) flagAtomRecordPresent = true; bool isHetero = false; if (currentPDBLine.startsWith("HETATM")) { isHetero = true; } int id = currentPDBLine.mid(6,5).toInt(); QByteArray atomName = currentPDBLine.mid(12,4).toAscii().trimmed(); QByteArray residueName = currentPDBLine.mid(17,3).toAscii().trimmed(); int resId = currentPDBLine.mid(22,4).toAscii().toInt(); char insCode = currentPDBLine.at(26).toAscii(); char residueAcronym = PDBFormat::getAcronymByName(residueName); char chainIdentifier = currentPDBLine.at(21).toAscii(); ResidueIndex residueIndex(resId,insCode); bool atomIsInChain = !isHetero || seqResContains(chainIdentifier, residueIndex.toInt(), residueAcronym ); QByteArray elementName = currentPDBLine.mid(76,2).toAscii().trimmed(); QByteArray element = elementName.isEmpty() ? atomName.mid(0,1) : elementName; int atomicNumber = PDBFormat::getElementNumberByName(element); int chainIndex = chainIndexMap.contains(chainIdentifier) ? chainIndexMap.value(chainIdentifier) : currentChainIndex; if ( currentModelIndex == 0 && atomIsInChain ) { // Process residue if (!biostruct.moleculeMap.contains(chainIndex)) { createMolecule(chainIdentifier, biostruct, chainIndex); } SharedMolecule& mol = biostruct.moleculeMap[chainIndex]; if (currentResidueIndex != residueIndex) { SharedResidue residue( new ResidueData ); residue->name = residueName; residue->acronym = residueAcronym; if (residue->acronym == 'X') { ioLog.details(tr("PDB warning: unknown residue name: %1").arg(residue->name.constData())); } residue->chainIndex = chainIndex; currentResidueIndex = residueIndex; residueOrder++; residueIndex.setOrder(residueOrder); mol->residueMap.insert(residueIndex, residue); } } // Process atom double x,y,z; x = currentPDBLine.mid(30,8).toDouble(); y = currentPDBLine.mid(38,8).toDouble(); z = currentPDBLine.mid(46,8).toDouble(); double occupancy = currentPDBLine.mid(54,6).toDouble(); double temperature = currentPDBLine.mid(60,6).toDouble(); SharedAtom a(new AtomData); a->chainIndex = chainIndex; a->residueIndex = residueIndex; a->atomicNumber = atomicNumber; a->name = atomName; a->coord3d = Vector3D(x,y,z); a->occupancy = occupancy; a->temperature = temperature; biostruct.modelMap[currentModelIndex + 1].insert(id, a); if (atomIsInChain) { SharedMolecule& mol = biostruct.moleculeMap[chainIndex]; int numModels = mol->models.count(); if (currentModelIndex + 1 > numModels) { Molecule3DModel model; mol->models.append(model); } Molecule3DModel& model3D = mol->models[currentModelIndex]; model3D.atoms.insert(id, a); } } void PDBFormat::PDBParser::parseSecondaryStructure( BioStruct3D& biostruct, TaskStateInfo& ti ) { /* Record Format Examples 1 2 3 0123456789012345678901234567890123456 HELIX 1 H1 ILE 7 LEU 18 HELIX 2 H2 PRO 19 PRO 19 HELIX 3 H3 GLU 23 TYR 29 HELIX 4 H4 THR 30 THR 30 SHEET 1 S1 2 THR 2 CYS 4 SHEET 2 S2 2 CYS 32 ILE 35 SHEET 3 S3 2 THR 39 PRO 41 TURN 1 T1 GLY 42 TYR 44 */ SecondaryStructure::Type structureType = SecondaryStructure::Type_None; int startIndex; int endIndex; int startChainIDIndex; // int endChainIDIndex; if (currentPDBLine.startsWith("HELIX ")) { structureType = SecondaryStructure::Type_AlphaHelix; startChainIDIndex = 19; // endChainIDIndex = 31; startIndex = 21; endIndex = 33; } else if (currentPDBLine.startsWith("SHEET ")) { structureType = SecondaryStructure::Type_BetaStrand; startChainIDIndex = 21; // endChainIDIndex = 32; startIndex = 22; endIndex = 33; } else if (currentPDBLine.startsWith("TURN ")) { // TODO: is this is obsolete? structureType = SecondaryStructure::Type_Turn; startChainIDIndex = 19; // endChainIDIndex = 30; startIndex = 20; endIndex = 31; } else { Q_ASSERT(0); return; } if (currentPDBLine.length() < endIndex + 4) { ti.setError(U2::PDBFormat::tr("Invalid secondary structure record")); return; } char startChainID = currentPDBLine.at(startChainIDIndex).toAscii(); // char endChainID = currentPDBLine.at(endChainIDIndex).toAscii(); int startSequenceNumber = currentPDBLine.mid(startIndex, 4).toInt(); int endSequenceNumber = currentPDBLine.mid(endIndex, 4).toInt(); SharedSecondaryStructure secStruct( new SecondaryStructure ); secStruct->type = structureType; secStruct->chainIdentifier = startChainID; secStruct->startSequenceNumber = startSequenceNumber; secStruct->endSequenceNumber = endSequenceNumber; biostruct.secondaryStructures.append(secStruct); } // void PDBFormat::PDBParser::parseCompound(BioStruct3D& biostruct, TaskStateInfo& ti) // { // /* // Record Format // // COLUMNS DATA TYPE FIELD DEFINITION // 1 - 6 Record name "COMPND" // 8 - 10 Continuation // 11 - 70 Description of the molecular components. // */ // // const char* idTag = "MOL_ID"; // const char* nameTag = "MOLECULE"; // const char* chainsTag = "CHAIN"; // // const char* engTag = "ENGINEERED"; // const char* savedTag = "SAVED_LINE"; // const char* delimiterTag = ";"; // const char* transitionTag = "-"; // QByteArray specLine = currentPDBLine.mid(10).trimmed().toAscii(); // // //Q_UNUSED(engTag); // // bool saveRequired = false; // // if (specLine == "NULL") { // ti.setError(U2::PDBFormat::tr("compound_record_is_empty")); // return; // } // // if (currentMoleculeDescr.contains(savedTag)) { // specLine.prepend(currentMoleculeDescr.value(savedTag).toString().toAscii()); // currentMoleculeDescr.remove(savedTag); // } // // if (specLine.endsWith(transitionTag)) { // // look forward to guess if it is not an end of record // // (it could be, for example 1V6C) // QByteArray nextLine = getNextSpecLine(); // if (!nextLine.startsWith("COMPND")) { // //end of record detected // int lastCharIndex = specLine.length() - 1; // specLine.remove(lastCharIndex,1); // } else { // int length = specLine.length(); // // omit transition tag when saving specLine // currentMoleculeDescr.insert(savedTag, specLine.left(length - 1)); // return; // } // } // // if (!specLine.endsWith(delimiterTag)) { // // look forward to guess if transition required // QByteArray nextLine = getNextSpecLine(); // if (nextLine.startsWith("COMPND")) { // // this is transition, save this line // currentMoleculeDescr.insert(savedTag, specLine); // return; // } else { // saveRequired = true; // } // } // // if (specLine.startsWith(idTag) ) { // if (!currentMoleculeDescr.isEmpty()) { // saveRequired = true; // } // QByteArray molId = getSpecValue(specLine, idTag); // currentMoleculeDescr.insert(idTag, molId); // } else if (specLine.startsWith(nameTag)) { // QByteArray name = getSpecValue(specLine, nameTag); // currentMoleculeDescr.insert(nameTag, name); // } else if (specLine.startsWith(chainsTag)) { // QByteArray chainIds = getSpecValue(specLine, chainsTag); // currentMoleculeDescr.insert(chainsTag, chainIds); // } // // if (saveRequired) { // //TODO: Try to use this index from PDB Entry // //int index = currentMoleculeDescr.value(idTag).toInt(); // //Q_UNUSED(index); // QString name = currentMoleculeDescr.value(nameTag).toString(); // QString buffer = currentMoleculeDescr.value(chainsTag).toString(); // for( int j = 0; j < buffer.length(); ++j) { // QChar chainIdentifier = buffer.at(j); // if (chainIdentifier.isLetterOrNumber()) { // int molId = chainIndexMap.size() + 1; // chainIndexMap.insert(chainIdentifier, molId); // MoleculeData* data = new MoleculeData(); // data->name = name; // biostruct.moleculeMap.insert( molId, SharedMolecule(data) ); // } // } // Q_ASSERT(chainIndexMap.size() > 0); // if (chainIndexMap.size() == 0) { // ti.setError(U2::PDBFormat::tr("invalid_compound_record")); // return; // } // currentMoleculeDescr.clear(); // } // // } void PDBFormat::PDBParser::parseSequence( BioStruct3D& biostruct, TaskStateInfo& ti ) { Q_UNUSED(biostruct); /* Record Format COLUMNS DEFINITION 1 - 6 Record name "SEQRES" 8 - 10 Integer serNum Serial number of the SEQRES record for the current chain. Starts at 1 and increments by one each line. Reset to 1 for each chain. 12 Character chainID Chain identifier. This may be any single legal character, including a blank which is is used if there is only one chain. 14 - 17 Integer numRes Number of residues in the chain. This value is repeated on every record. 20 - ... Residues */ if (currentPDBLine.length() < 24 /* at least one residue */) { ti.setError(U2::PDBFormat::tr("Invalid SEQRES: less then 24 charachters")); return; } char chainIdentifier = currentPDBLine.at(11).toAscii(); if (!seqResMap.contains(chainIdentifier)) { seqResMap.insert(chainIdentifier, QByteArray()); } QStringList residues = currentPDBLine.mid(19).split(QRegExp("\\s+"), QString::SkipEmptyParts); QByteArray sequencePart; foreach (QString name, residues ) { SharedResidue residue( new ResidueData ); char acronym = PDBFormat::getAcronymByName(name.toAscii()); sequencePart.append(acronym); } seqResMap[chainIdentifier].append(sequencePart); } QByteArray PDBFormat::PDBParser::getSpecValue( const QByteArray& specLine, const QByteArray& valueName ) { const char* delimTag(";"); int startIndex = specLine.indexOf(valueName) + valueName.length() + 1; int lastIndex = specLine.indexOf(delimTag); return specLine.mid(startIndex, lastIndex - startIndex).trimmed(); } int PDBFormat::getElementNumberByName( const QByteArray& elementName ) { if (atomNumMap.contains(elementName)) return atomNumMap.value(elementName); else return 0; } // void PDBFormat::PDBParser::parseDBRef( BioStruct3D& biostruct, TaskStateInfo& ti ) // { // /* Record Format // // COLUMNS DATA TYPE FIELD DEFINITION // 1 - 6 Record name "DBREF " // 8 - 11 IDcode idCode ID code of this entry. // 13 Character chainID Chain identifier. // 15 - 18 Integer seqBegin Initial sequence number of the PDB sequence segment. // 19 AChar insertBegin Initial insertion code of the PDB sequence segment. // 21 - 24 Integer seqEnd Ending sequence number of the PDB sequence segment. // 25 AChar insertEnd Ending insertion code of the PDB sequence segment. // 27 - 32 LString database Sequence database name. // 34 - 41 LString dbAccession Sequence database accession code. // 43 - 54 LString dbIdCode Sequence database identification code. // 56 - 60 Integer dbseqBegin Initial sequence number of the database segment. // 61 AChar idbnsBeg Insertion code of initial residue of the segment, if PDB is the reference. // 63 - 67 Integer dbseqEnd Ending sequence number of the database segment. // 68 AChar dbinsEnd Insertion code of the ending residue of the segment, if PDB is the reference. // */ // // Q_UNUSED(biostruct); // Q_UNUSED(ti); // QChar chainIdentifier = currentPDBLine.at(12); // int chainIndex = getChainIndexByName(chainIdentifier); // if (chainIndex == 0) { // log.details(tr("Wanning: unknown chain index in dbref!")); // return; // } // // // int startIndex = currentPDBLine.mid(14,4).toInt(); // residueStartIndexMap.insert(chainIndex, startIndex); // // } QByteArray PDBFormat::PDBParser::getNextSpecLine() { QByteArray readBuf(READ_BUF_SIZE+1, 0); char* buf = readBuf.data(); bool lineOk; int len = io->readUntil(buf, READ_BUF_SIZE, TextUtils::LINE_BREAKS, IOAdapter::Term_Include, &lineOk); QByteArray line = QByteArray::fromRawData(buf, len); // retrieve back ioAdapter position io->skip(-len); return readBuf; } void PDBFormat::PDBParser::parseModel( BioStruct3D& biostruct, TaskStateInfo& ti ) { /* COLUMNS DATA TYPE FIELD DEFINITION 1 - 6 Record name "MODEL " 11 - 14 Integer serial Model serial number. */ //TODO: int modelIndex = currentPDBLine.mid(10,4).toInt(); Q_UNUSED(biostruct); Q_UNUSED(ti); } void PDBFormat::PDBParser::updateSecStructChainIndexes( BioStruct3D& biostruc ) { QMutableListIterator i(biostruc.secondaryStructures); while (i.hasNext()) { SharedSecondaryStructure& secStruc = i.next(); char chainIdentifier = secStruc->chainIdentifier; if (!chainIndexMap.contains(chainIdentifier)) { i.remove(); continue; } secStruc->chainIndex = chainIndexMap.value(chainIdentifier); } } void PDBFormat::PDBParser::createMolecule( char chainIdentifier, BioStruct3D &biostruct, int chainIndex ) { SharedMolecule newMol( new MoleculeData ); newMol->name = QString("chain %1").arg(chainIdentifier); biostruct.moleculeMap.insert(chainIndex,newMol); chainIndexMap.insert(chainIdentifier, chainIndex); } void PDBFormat::PDBParser::updateResidueIndexes( BioStruct3D& /*biostruc*/) { } char PDBFormat::getAcronymByName( const QByteArray& name ) { if (acronymNameMap.contains(name)) return acronymNameMap.value(name); else return char('X'); } void PDBFormat::fillBioStruct3DAnnotationTable( AnnotationTableObject* ao, const BioStruct3D& bioStruct ) { foreach (SharedAnnotationData sdata, bioStruct.annotations) { ao->addAnnotation(new Annotation(sdata), bioStruct.pdbId); } } static inline bool existsCovalentBond( double r1, double r2, double distance ) { static const double tolerance = 0.45; if (distance <= r1 + r2 + tolerance) { return true; } return false; } void PDBFormat::calculateBonds( BioStruct3D& bioStruct ) { // maxDisance = 2*MaxCovalentRadius + tolerance static const double maxRadius = 2.0; static const double maxDistance = 2*maxRadius + 0.45; //quint64 num_comps = 0, firstFilter = 0, secondFilter = 0; clock_t t1 = clock(); QMap::iterator molIter; QList::iterator modelIter; for (molIter = bioStruct.moleculeMap.begin(); molIter != bioStruct.moleculeMap.end(); ++molIter) { SharedMolecule& mol = molIter.value(); int numModels = mol->models.count(); for( int i = 0; i < numModels; ++i) { Molecule3DModel& model = mol->models[i]; QList::const_iterator i1,i2; QList::const_iterator constEnd = model.atoms.constEnd(); for (i1 = model.atoms.constBegin(); i1 != constEnd; ++i1) { const SharedAtom& a1 = (*i1); double r1 = AtomConstants::getAtomCovalentRadius(a1->atomicNumber); i2 = i1; for (++i2; i2 != constEnd; ++i2) { //++num_comps; const SharedAtom& a2 = (*i2); if ( ( qAbs(a2->coord3d.x - a1->coord3d.x) > maxDistance ) || ( qAbs(a2->coord3d.y - a1->coord3d.y) > maxDistance ) || ( qAbs(a2->coord3d.z - a1->coord3d.z) > maxDistance ) ) { continue; } //++firstFilter; if ( (qAbs(a2->coord3d.x - a1->coord3d.x) + qAbs(a2->coord3d.y - a1->coord3d.y) + qAbs(a2->coord3d.z - a1->coord3d.z) ) > maxDistance ) { continue; } //++secondFilter; double distance = (a1->coord3d - a2->coord3d).length(); double r2 = AtomConstants::getAtomCovalentRadius(a2->atomicNumber); if (existsCovalentBond(r1, r2, distance)) { model.bonds.append(Bond( a1, a2 )); } } } } } clock_t t2 = clock(); perfLog.trace("PDB bonds calculation time: " + QString::number((float)( t2 - t1)/ CLOCKS_PER_SEC )); //perfLog.trace(QString("num comparisons: %1").arg(num_comps)); //perfLog.trace(QString("passed through first filter: %1").arg(firstFilter)); //perfLog.trace(QString("passed through second filter: %1").arg(secondFilter)); } QHash PDBFormat::createAtomNumMap() { QHash atomNumMap; // Init atomNumMap atomNumMap.insert("H",1); atomNumMap.insert("HE",2); atomNumMap.insert("LI",3); atomNumMap.insert("BE",4); atomNumMap.insert("B",5); atomNumMap.insert("C",6); atomNumMap.insert("N",7); atomNumMap.insert("O",8); atomNumMap.insert("F",9); atomNumMap.insert("NE",10); atomNumMap.insert("NA",11); atomNumMap.insert("MG",12); atomNumMap.insert("AL",13); atomNumMap.insert("SI",14); atomNumMap.insert("P",15); atomNumMap.insert("S",16); atomNumMap.insert("CL",17); atomNumMap.insert("AR",18); atomNumMap.insert("K",19); atomNumMap.insert("CA",20); atomNumMap.insert("SC",21); atomNumMap.insert("TI",22); atomNumMap.insert("V",23); atomNumMap.insert("CR",24); atomNumMap.insert("MN",25); atomNumMap.insert("FE",26); atomNumMap.insert("CO",27); atomNumMap.insert("NI",28); atomNumMap.insert("CU",29); atomNumMap.insert("ZN",30); atomNumMap.insert("GA",31); atomNumMap.insert("GE",32); atomNumMap.insert("AS",33); atomNumMap.insert("SE",34); atomNumMap.insert("BR",35); atomNumMap.insert("KR",36); atomNumMap.insert("RB",37); atomNumMap.insert("SR",38); atomNumMap.insert("Y",39); atomNumMap.insert("ZR",40); atomNumMap.insert("NB",41); atomNumMap.insert("MO",42); atomNumMap.insert("TC",43); atomNumMap.insert("RU",44); atomNumMap.insert("RH",45); atomNumMap.insert("PD",46); atomNumMap.insert("AG",47); atomNumMap.insert("CD",48); atomNumMap.insert("IN",49); atomNumMap.insert("SN",50); atomNumMap.insert("SB",51); atomNumMap.insert("TE",52); atomNumMap.insert("I",53); atomNumMap.insert("XE",54); atomNumMap.insert("CS",55); atomNumMap.insert("BA",56); atomNumMap.insert("LA",57); atomNumMap.insert("CE",58); atomNumMap.insert("PR",59); atomNumMap.insert("ND",60); atomNumMap.insert("PM",61); atomNumMap.insert("SM",62); atomNumMap.insert("EU",63); atomNumMap.insert("GD",64); atomNumMap.insert("TB",65); atomNumMap.insert("DY",66); atomNumMap.insert("HO",67); atomNumMap.insert("ER",68); atomNumMap.insert("TM",69); atomNumMap.insert("YB",70); atomNumMap.insert("LU",71); atomNumMap.insert("HF",72); atomNumMap.insert("TA",73); atomNumMap.insert("W",74); atomNumMap.insert("RE",75); atomNumMap.insert("OS",76); atomNumMap.insert("IR",77); atomNumMap.insert("PT",78); atomNumMap.insert("AU",79); atomNumMap.insert("HG",80); atomNumMap.insert("TL",81); atomNumMap.insert("PB",82); atomNumMap.insert("BI",83); atomNumMap.insert("PO",84); atomNumMap.insert("AT",85); atomNumMap.insert("RN",86); atomNumMap.insert("FR",87); atomNumMap.insert("RA",88); atomNumMap.insert("AC",89); atomNumMap.insert("TH",90); atomNumMap.insert("PA",91); atomNumMap.insert("U",92); atomNumMap.insert("NP",93); atomNumMap.insert("PU",94); atomNumMap.insert("AM",95); atomNumMap.insert("CM",96); atomNumMap.insert("BK",97); atomNumMap.insert("CF",98); atomNumMap.insert("ES",99); atomNumMap.insert("FM",100); atomNumMap.insert("MD",101); atomNumMap.insert("NO",102); atomNumMap.insert("LR",103); return atomNumMap; } Document* PDBFormat::createDocumentFromBioStruct3D( BioStruct3D &bioStruct, DocumentFormat* format, IOAdapterFactory* iof, const GUrl& url, TaskStateInfo& ti, const QVariantMap& fs ) { Q_UNUSED(ti); QList objects; QMap< AnnotationTableObject*, DNASequenceObject*> relationsMap; QString objectName = bioStruct.pdbId.isEmpty() ? url.baseFileName() : bioStruct.pdbId; BioStruct3DObject* biostrucObj = new BioStruct3DObject(bioStruct, objectName); foreach(int key, bioStruct.moleculeMap.keys()) { // Create dna sequence object QByteArray sequence = bioStruct.getRawSequenceByChainId(key); QString sequenceName(QString(bioStruct.pdbId) + QString(" chain %1 sequence").arg(key)); DNAAlphabet* al = AppContext::getDNAAlphabetRegistry()->findAlphabet(sequence); DNASequence dna(sequence, al); dna.info.insert(DNAInfo::DEFINITION, sequenceName); dna.info.insert(DNAInfo::COMMENT, bioStruct.descr); dna.info.insert(DNAInfo::ID, sequenceName); dna.info.insert(DNAInfo::CHAIN_ID, key); DNASequenceObject* dnaObj = new DNASequenceObject(sequenceName, dna); // create AnnnotationTableObject AnnotationTableObject* aObj = new AnnotationTableObject(QString(bioStruct.pdbId) + QString(" chain %1 annotation").arg(key)); foreach (SharedAnnotationData sd, bioStruct.moleculeMap.value(key)->annotations) { aObj->addAnnotation(new Annotation(sd), ""); } objects.append(dnaObj); objects.append(aObj); relationsMap.insert(aObj, dnaObj); } objects.append(biostrucObj); Document* doc = new Document(format, iof, url, objects, fs); // set object relations QMap< AnnotationTableObject*, DNASequenceObject*>::const_iterator i; for (i = relationsMap.constBegin(); i != relationsMap.constEnd(); ++i) { DNASequenceObject* dnao = i.value(); AnnotationTableObject* ao = i.key(); ao->addObjectRelation(dnao, GObjectRelationRole::SEQUENCE); biostrucObj->addObjectRelation(dnao, GObjectRelationRole::SEQUENCE); biostrucObj->addObjectRelation(ao, GObjectRelationRole::ANNOTATION_TABLE); } return doc; } } //namespace ugene-1.9.8/src/corelibs/U2Formats/src/GenbankLocationParser.h0000644000175000017500000000257011651544332022710 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_GENBANK_LOCATION_PARSER_H #define _U2_GENBANK_LOCATION_PARSER_H #include #include #include #include namespace U2 { class AnnotationData; namespace Genbank { class U2FORMATS_EXPORT LocationParser { public: static void parseLocation(const char* str, int len, U2Location& location); static QString buildLocationString(const AnnotationData* a); static QString buildLocationString(const QVector& regions); }; }}//namespace #endif ugene-1.9.8/src/corelibs/U2Formats/src/ASNFormat.h0000644000175000017500000001405511651544332020270 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_ASN_FORMAT_H_ #define _U2_ASN_FORMAT_H_ #include #include #include #include #include #include "StdResidueDictionary.h" namespace U2 { class IOAdapter; class BioStruct3D; class MoleculeData; class ResidueData; class AnnotationTableObject; class DNASequenceObject; class AtomData; typedef QSharedDataPointer SharedAtom; typedef QHash AtomCoordSet; enum AsnElementKind { ASN_NO_KIND, ASN_SEQ, ASN_VALUE, ASN_ROOT }; class U2FORMATS_EXPORT AsnNode : public QObject { Q_OBJECT public: AsnNode(); AsnNode(const QByteArray& _name, AsnElementKind _kind); ~AsnNode(); QByteArray name, value; AsnElementKind kind; QList children; AsnNode* findChildByName(const QByteArray& name); AsnNode* getChildById(int id); private: static void deleteChildren(AsnNode* node); }; typedef QList AsnNodeList; class U2FORMATS_EXPORT ASNFormat : public DocumentFormat { Q_OBJECT public: ASNFormat(QObject* p); ~ASNFormat(); virtual DocumentFormatId getFormatId() const {return BaseDocumentFormats::PLAIN_ASN;} virtual const QString& getFormatName() const {return formatName;} virtual Document* loadDocument(IOAdapter* io, TaskStateInfo& ti, const QVariantMap& fs, DocumentLoadMode mode = DocumentLoadMode_Whole); virtual RawDataCheckResult checkRawData(const QByteArray& data, const GUrl& = GUrl()) const; class U2FORMATS_EXPORT AsnParser { static const char* filetypeTag; // Parsing state struct ParseState { QByteArray parentName; bool atEnd; int numOpenedTags; }; // Data IOAdapter *io; TaskStateInfo& ts; QByteArray buffer; char prev; ParseState curState; QByteArray curElementName, curElementValue; AsnElementKind curElementKind; bool validFile; bool haveErrors; bool insideRoot; bool fileAtEnd; QStack states; // Core bool readRootElement(); bool readNextElement(); void processValue(); void parseNextElement(AsnNode* node); void saveState(); void restoreState(); void dbgPrintCurrentState(); void initState(const QByteArray& parentName); // Utility static bool isQuoted(const QByteArray& str); static void removeQuotes(QByteArray& str); static void dbgPrintAsnTree(const AsnNode* rootElem, int level = 0); public: AsnParser(IOAdapter* _io, TaskStateInfo& _ts) : io(_io), ts(_ts), prev(' '), curElementKind(ASN_NO_KIND), validFile(false), haveErrors(false), insideRoot(false), fileAtEnd(false) {} ~AsnParser() {} AsnNode* loadAsnTree(); }; static QString getAsnNodeTypeName(const AsnNode* node); static AsnNode* findFirstNodeByName(AsnNode* rootElem, const QString& nodeName); static AsnNodeList findNodesByName(AsnNode* root, const QString& nodeName, AsnNodeList& lst ); private: QString formatName; struct AsnBaseException { QString msg; AsnBaseException( const QString& what ) : msg( what ){} }; struct AsnReadError : AsnBaseException { AsnReadError() : AsnBaseException(ASNFormat::tr("read error occurred")) { } }; struct AsnParserError : public AsnBaseException { AsnParserError( const QString& what ) : AsnBaseException( what ){} }; struct AsnBioStructError : public AsnBaseException { AsnBioStructError( const QString& what ) : AsnBaseException(QString(ASNFormat::tr("biostruct3d obj loading error: %1")).arg(what) ){} }; class BioStructLoader{ public: BioStructLoader() : standardDictionary(0), localDictionary(0) {} void loadBioStructFromAsnTree(AsnNode* rootNode, BioStruct3D& struc, TaskStateInfo& info); const StdResidueDictionary * getStandardDictionary() const {return standardDictionary;} void setStandardDictionary( const StdResidueDictionary * _standardDictionary ) {standardDictionary = _standardDictionary;} private: void loadBioStructModels(QList models, BioStruct3D& struc); void loadBioStructGraph(AsnNode* graphNode, BioStruct3D& struc); void loadBioStructPdbId( AsnNode* rootNode, BioStruct3D& struc); void loadBioStructSecondaryStruct( AsnNode* rootNode, BioStruct3D& struc ); void loadBioStructFeature( AsnNode* featureNode, BioStruct3D& struc ); void loadModelCoordsFromNode( AsnNode* node, AtomCoordSet& coordSet, QMap& molModels, const BioStruct3D& struc); void loadMoleculeFromNode(AsnNode* moleculeNode, MoleculeData* molecule); void loadIntraResidueBonds(BioStruct3D& struc); const StdResidue loadResidueFromNode(AsnNode* resNode, ResidueData* residue); private: const StdResidueDictionary *standardDictionary; std::auto_ptr localDictionary; QHash stdResidueCache; QMap atomSetCache; }; }; }//namespace #endif //_U2_ASN_FORMAT_H_ ugene-1.9.8/src/corelibs/U2Formats/src/EMBLPlainTextFormat.h0000644000175000017500000000264011651544332022214 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_EMBL_PLAIN_TEXT_FORMAT_H_ #define _U2_EMBL_PLAIN_TEXT_FORMAT_H_ #include "EMBLGenbankAbstractDocument.h" namespace U2 { class U2FORMATS_EXPORT EMBLPlainTextFormat : public EMBLGenbankAbstractDocument { Q_OBJECT public: EMBLPlainTextFormat(QObject* p); virtual RawDataCheckResult checkRawData(const QByteArray& rawData, const GUrl& = GUrl()) const; protected: bool readIdLine(ParserState*); bool readEntry(QByteArray&, ParserState*); //void readAnnotations(ParserState*, int offset); QMap tagMap; }; }//namespace #endif ugene-1.9.8/src/corelibs/U2Formats/src/EMBLGenbankAbstractDocument.h0000644000175000017500000001011211651544332023654 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_EMBL_GENBANK_ABSTRACT_DOCUMENT_H_ #define _U2_EMBL_GENBANK_ABSTRACT_DOCUMENT_H_ #include #include #include #include namespace U2 { class IOAdapter; class ParserState; class EMBLGenbankDataEntry; class U2FORMATS_EXPORT EMBLGenbankAbstractDocument : public DocumentFormat { Q_OBJECT public: EMBLGenbankAbstractDocument(const DocumentFormatId& id, const QString& formatName, int maxLineSize, DocumentFormatFlags flags, QObject* p); virtual DocumentFormatId getFormatId() const {return id;} virtual const QString& getFormatName() const {return formatName;} virtual Document* loadDocument(IOAdapter* io, TaskStateInfo& ti, const QVariantMap& fs, DocumentLoadMode mode = DocumentLoadMode_Whole); static const QString UGENE_MARK; static const QString DEFAULT_OBJ_NAME; // move to utils?? static QString genObjectName(QSet& usedNames, const QString& name, const QVariantMap& info, int n, const GObjectType& t); virtual DNASequence* loadSequence( IOAdapter* io, TaskStateInfo& ti); protected: virtual void load(IOAdapter* io, QList& objects, QVariantMap& fs, TaskStateInfo& si, QString& writeLockReason, DocumentLoadMode mode); virtual int readMultilineQualifier(IOAdapter* io, char* cbuff, int maxSize, bool prevLineHasMaxSize); virtual SharedAnnotationData readAnnotation(IOAdapter* io, char* cbuff, int contentLen, int bufSize, TaskStateInfo& si, int offset); virtual bool readSequence(QByteArray& sequence, ParserState*); virtual bool readEntry(QByteArray& sequence, ParserState*) = 0; virtual void readAnnotations(ParserState*, int offset); DocumentFormatId id; QString formatName; QByteArray fPrefix; QByteArray sequenceStartPrefix; int maxAnnotationLineLen; }; ////////////////////////////////////////////////////////////////////////// // header model class EMBLGenbankDataEntry { public: EMBLGenbankDataEntry() : seqLen(0), hasAnnotationObjectFlag(false), circular(false) {} /** locus name */ QString name; /** sequence len*/ int seqLen; QVariantMap tags; QList features; // hasAnnotationObjectFlag parameter is used to indicate that // annotation table object must present even if result list is empty bool hasAnnotationObjectFlag; bool circular; }; class ParserState { public: ParserState(int off, IOAdapter* io, EMBLGenbankDataEntry* e, TaskStateInfo& si) : valOffset(off), entry(e), io(io), buff(NULL), len(0), si(si) {} const int valOffset; EMBLGenbankDataEntry* entry; IOAdapter* io; static const int READ_BUFF_SIZE = 8192; char* buff; int len; TaskStateInfo& si; QString value() const; QString key () const; bool hasKey(const char*, int slen) const; bool hasKey(const char* s) const {return hasKey(s, strlen(s));} bool hasContinuation() const { return len > valOffset && hasKey(" ");} bool hasValue() const {return len > valOffset;} bool readNextLine(bool emptyOK = false); bool isNull() const {return entry->name.isNull();} }; }//namespace #endif ugene-1.9.8/src/corelibs/U2Formats/src/SwissProtPlainTextFormat.cpp0000644000175000017500000003551611651544332024015 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "SwissProtPlainTextFormat.h" #include "GenbankLocationParser.h" #include "GenbankFeatures.h" #include "DocumentFormatUtils.h" #include #include #include #include #include #include #include #include #include namespace U2 { /* TRANSLATOR U2::EMBLPlainTextFormat */ /* TRANSLATOR U2::EMBLGenbankAbstractDocument */ SwissProtPlainTextFormat::SwissProtPlainTextFormat(QObject* p) : EMBLGenbankAbstractDocument(BaseDocumentFormats::PLAIN_SWISS_PROT, tr("Swiss-Prot"), 80, DocumentFormatFlag_SupportStreaming, p) { fileExtensions << "sw" << "em" << "emb" << "embl" << "txt"; sequenceStartPrefix = "SQ"; fPrefix = "FT"; tagMap["DT"] = DNAInfo::DATE; //The DT (DaTe) lines shows the date of creation and last modification of the database entry. tagMap["DE"] = DNAInfo::DEFINITION; //The DE (DEscription) lines contain general descriptive information about the sequence stored. tagMap["KW"] = DNAInfo::KEYWORDS; //The KW (KeyWord) lines provide information that can be used to generate indexes of the sequence entries based on functional, structural, or other categories. tagMap["CC"] = DNAInfo::COMMENT; //The CC lines are free text comments on the entry, and are used to convey any useful information. } RawDataCheckResult SwissProtPlainTextFormat::checkRawData(const QByteArray& rawData, const GUrl&) const { //TODO: improve format checking const char* data = rawData.constData(); int size = rawData.size(); bool textOnly = !TextUtils::contains(TextUtils::BINARY, data, size); if (!textOnly || size < 100) { return FormatDetection_NotMatched; } bool tokenMatched = TextUtils::equals("ID ", data, 5); if (tokenMatched) { if(QString(rawData).contains(QRegExp("\\d+ AA."))){ return FormatDetection_HighSimilarity; } return FormatDetection_NotMatched; } return FormatDetection_NotMatched; } ////////////////////////////////////////////////////////////////////////// // loading bool SwissProtPlainTextFormat::readIdLine(ParserState* s) { if (!s->hasKey("ID", 2)) { s->si.setError(SwissProtPlainTextFormat::tr("ID is not the first line")); return false; } QString idLineStr= s->value(); QStringList tokens = idLineStr.split(" ", QString::SkipEmptyParts); if (idLineStr.length() < 4 || tokens.isEmpty()) { s->si.setError(SwissProtPlainTextFormat::tr("Error parsing ID line")); return false; } s->entry->name = tokens[0]; DNALocusInfo loi; loi.name = tokens[0]; QString third = tokens[2]; bool ok=false; s->entry->seqLen=third.toInt(&ok); if (!ok) { s->si.setError(SwissProtPlainTextFormat::tr("Error parsing ID line. Not found sequence length")); return false; } s->entry->tags.insert(DNAInfo::LOCUS, qVariantFromValue(loi)); return true; } bool SwissProtPlainTextFormat::readEntry(QByteArray& sequence, ParserState* st) { TaskStateInfo& si = st->si; QString lastTagName; bool hasLine = false; while (hasLine || st->readNextLine(false)) { hasLine = false; if (st->entry->name.isEmpty()) { readIdLine(st); assert(si.hasError() || !st->entry->name.isEmpty()); if (si.hasError()) { break; } continue; } // if (st->hasKey("FH") || st->hasKey("AH")) { continue; } if (st->hasKey("AC")) { //The AC (ACcession number) line lists the accession number(s) associated with an entry. QVariant v = st->entry->tags.value(DNAInfo::ACCESSION); QStringList l = st->value().split(QRegExp(";\\s*"), QString::SkipEmptyParts); st->entry->tags[DNAInfo::ACCESSION] = QVariantUtils::addStr2List(v, l); continue; } if (st->hasKey("OS")) { //The OS (Organism Species) line specifies the organism(s) which was (were) the source of the stored sequence. DNASourceInfo soi; soi.name = st->value(); soi.organism = soi.name; while (st->readNextLine()) { if (st->hasKey("OS")) { soi.organism.append(" ").append(st->value()); } else if (!st->hasKey("XX")) { break; } } if (st->hasKey("OC")) { //The OC (Organism Classification) lines contain the taxonomic classification of the source organism. soi.taxonomy += st->value(); while (st->readNextLine()) { if (st->hasKey("OC")) { soi.taxonomy.append(st->value()); } else if (!st->hasKey("XX")) { break; } } } if (st->hasKey("OG")) { //The OG (OrGanelle) line indicates if the gene coding for a protein originates from the mitochondria, the chloroplast, a cyanelle, or a plasmid. soi.organelle = st->value(); } else { hasLine = true; } st->entry->tags.insertMulti(DNAInfo::SOURCE, qVariantFromValue(soi)); continue; } if (st->hasKey("RF") || st->hasKey("RN")) { //The RN (Reference Number) line gives a sequential number to each reference citation in an entry. while (st->readNextLine() && st->buff[0] == 'R') { //TODO } hasLine = true; continue; } /*The FT (Feature Table) lines provide a precise but simple means for the annotation of the sequence data. The table describes regions or sites of interest in the sequence. In general the feature table lists posttranslational modifications, binding sites, enzyme active sites, local secondary structure or other characteristics reported in the cited references. */ if (st->hasKey("FT", 2)) { readAnnotations(st, sequence.size()); hasLine = true; continue; } //read simple tag; if (st->hasKey("//", 2)) { // end of entry return true; } else if (st->hasKey("SQ", 2)) { //reading sequence readSequence(sequence, st); return true; } QString key = st->key().trimmed(); if (tagMap.contains(key)) { key = tagMap.value(key); } if (lastTagName == key) { QVariant v = st->entry->tags.take(lastTagName); v = QVariantUtils::addStr2List(v, st->value()); st->entry->tags.insert(lastTagName, v); } else if (st->hasValue()) { lastTagName = key; st->entry->tags.insertMulti(lastTagName, st->value()); } } if (!st->isNull() && !si.hasError() && !si.cancelFlag) { si.setError(U2::EMBLGenbankAbstractDocument::tr("Record is truncated.")); } return false; } bool SwissProtPlainTextFormat::readSequence(QByteArray &res, ParserState *st){ IOAdapter* io = st->io; TaskStateInfo& si = st->si; si.setDescription(tr("Reading sequence %1").arg(st->entry->name)); int headerSeqLen = st->entry->seqLen; res.reserve(res.size() + headerSeqLen); static int READ_BUFF_SIZE = 4096; QByteArray readBuffer(READ_BUFF_SIZE, '\0'); char* buff = readBuffer.data(); //reading sequence QBuffer writer(&res); writer.open( QIODevice::WriteOnly | QIODevice::Append ); bool ok = true; int len; while (ok && (len = io->readLine(buff, READ_BUFF_SIZE)) > 0) { if (si.cancelFlag) { res.clear(); break; } if (len <= 0) { si.setError(tr("Error parsing sequence: unexpected empty line")); break; } if (buff[0] == '/') { //end of the sequence break; } //add buffer to result for (int i= 0; i < len; i++) { char c = buff[i]; if (c != ' ' && c != '\t') { ok = writer.putChar(c); if (!ok) { break; } } } if (!ok) { si.setError(tr("Error reading sequence: memory allocation failed")); break; } si.progress = io->getProgress(); } if (!si.hasError() && !si.cancelFlag && buff[0] != '/') { si.setError(tr("Sequence is truncated")); } writer.close(); return true; } void SwissProtPlainTextFormat::readAnnotations(ParserState *st, int offset){ st->si.setDescription(tr("Reading annotations %1").arg(st->entry->name)); st->entry->hasAnnotationObjectFlag = true; do { int fplen = fPrefix.length(); if (st->len >= 6 && TextUtils::equals(fPrefix.data(), st->buff, fplen)) { while (fplen < 5) { if (st->buff[fplen++] != ' ') { st->si.setError(tr("Invalid format of feature table")); break; } } } else { // end of feature table break; } //parsing feature; SharedAnnotationData f = readAnnotation(st->io, st->buff, st->len, ParserState::READ_BUFF_SIZE, st->si, offset); st->entry->features.push_back(f); } while (st->readNextLine()); } //column annotation data starts with #define A_COL 34 //column qualifier name starts with #define QN_COL 35 //column annotation key starts with #define K_COL 5 SharedAnnotationData SwissProtPlainTextFormat::readAnnotation(IOAdapter* io, char* cbuff, int len, int READ_BUFF_SIZE, TaskStateInfo& si, int offset){ AnnotationData* a = new AnnotationData(); SharedAnnotationData f(a); QString key = QString::fromAscii(cbuff+5, 10).trimmed(); if (key.isEmpty()) { si.setError(EMBLGenbankAbstractDocument::tr("Annotation name is empty")); return SharedAnnotationData(); } a->name = key; if(key == "STRAND" || key == "HELIX" || key == "TURN"){ a->qualifiers.append(U2Qualifier(GBFeatureUtils::QUALIFIER_GROUP, "Secondary structure")); } QString start= QString::fromAscii(cbuff+15, 5).trimmed(); if(start.isEmpty()){ si.setError(EMBLGenbankAbstractDocument::tr("Annotation start position is empty")); return SharedAnnotationData(); } QString end= QString::fromAscii(cbuff+22, 5).trimmed(); if(end.isEmpty()){ si.setError(EMBLGenbankAbstractDocument::tr("Annotation end position is empty")); return SharedAnnotationData(); } a->location->reset(); if(key == "DISULFID" && start != end){ a->location->op=U2LocationOperator_Order; U2Region reg1(start.toInt()-1,1); U2Region reg2(end.toInt()-1,1); a->location->regions.append(reg1); a->location->regions.append(reg2); }else{ U2Region reg(start.toInt()-1,end.toInt() - start.toInt()+1); a->location->regions.append(reg); } if (offset!=0) { U2Region::shift(offset, a->location->regions); } QString valQStr = QString::fromAscii(cbuff).split(QRegExp("\\n")).first().mid(34); QString nameQStr = "Description"; bool isDescription=true; const QByteArray& aminoQ = GBFeatureUtils::QUALIFIER_AMINO_STRAND; const QByteArray& nameQ = GBFeatureUtils::QUALIFIER_NAME; //here we have valid key and location; //reading qualifiers bool lineOk = true; while ((len = io->readUntil(cbuff, READ_BUFF_SIZE, TextUtils::LINE_BREAKS, IOAdapter::Term_Include, &lineOk) ) > 0) { if (len == 0 || len < QN_COL+1 || cbuff[K_COL]!=' ' || cbuff[0]!=fPrefix[0] || cbuff[1]!=fPrefix[1]) { io->skip(-len); if(isDescription && !valQStr.isEmpty()){ isDescription=false; a->qualifiers.append(U2Qualifier(nameQStr, valQStr)); } break; } if (!lineOk) { si.setError(EMBLGenbankAbstractDocument::tr("Unexpected line format")); break; } //parse line if(cbuff[A_COL] != '/'){//continue of description valQStr.append(" "); valQStr.append(QString::fromAscii(cbuff).split(QRegExp("\\n")).takeAt(0).mid(34)); }else{ for (; QN_COL < len && TextUtils::LINE_BREAKS[(uchar)cbuff[len-1]]; len--){}; //remove line breaks int flen = len + readMultilineQualifier(io, cbuff+len, READ_BUFF_SIZE-len, len == maxAnnotationLineLen); //now the whole feature is in cbuff int valStart = A_COL + 1; for (; valStart < flen && cbuff[valStart] != '='; valStart++){}; //find '==' and valStart if (valStart < flen) { valStart++; //skip '=' char } const QBitArray& WHITE_SPACES = TextUtils::WHITES; for (; valStart < flen && WHITE_SPACES[(uchar)cbuff[flen-1]]; flen--){}; //trim value const char* qname = cbuff + QN_COL; int qnameLen = valStart - (QN_COL + 1); const char* qval = cbuff + valStart; int qvalLen = flen - valStart; if (qnameLen == aminoQ.length() && TextUtils::equals(qname, aminoQ.constData(), qnameLen)) { //a->aminoFrame = qvalLen == aminoQYes.length() && TextUtils::equals(qval, aminoQYes.constData(), qvalLen) ? TriState_Yes // : (qvalLen == aminoQNo.length() && TextUtils::equals(qval, aminoQNo.constData(), qvalLen) ? TriState_No : TriState_Unknown); } else if (qnameLen == nameQ.length() && TextUtils::equals(qname, nameQ.constData(), qnameLen)) { a->name = QString::fromLocal8Bit(qval, qvalLen); } else { QString nameQStr = QString::fromLocal8Bit(qname, qnameLen); QString valQStr = QString::fromLocal8Bit(qval, qvalLen); a->qualifiers.append(U2Qualifier(nameQStr, valQStr)); } } } return f; } }//namespace ugene-1.9.8/src/corelibs/U2Formats/src/tasks/0000755000175000017500000000000011651544332017445 5ustar ilyailyaugene-1.9.8/src/corelibs/U2Formats/src/tasks/ConvertAssemblyToSamTask.cpp0000644000175000017500000001176011651544332025065 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include #include #include #include #include #include #include #include #include #include #include #include #include #include "ConvertAssemblyToSamTask.h" #include namespace U2 { ConvertAssemblyToSamTask::ConvertAssemblyToSamTask(GUrl db, GUrl sam) : Task("ConvertAssemblyToSamTask", (TaskFlag)(TaskFlag_ReportingIsSupported | TaskFlag_ReportingIsEnabled)), dbFileUrl(db), samFileUrl(sam), handle(NULL) { } ConvertAssemblyToSamTask::ConvertAssemblyToSamTask(const DbiHandle *h, GUrl sam) : Task("ConvertAssemblyToSamTask", (TaskFlag)(TaskFlag_ReportingIsSupported | TaskFlag_ReportingIsEnabled)), samFileUrl(sam), handle(h) { } void ConvertAssemblyToSamTask::run() { //init sam file SAMFormat samFormat; IOAdapterFactory* iof = AppContext::getIOAdapterRegistry()->getIOAdapterFactoryById(BaseIOAdapters::LOCAL_FILE); std::auto_ptr io(iof->createIOAdapter()); bool res = io->open(samFileUrl, IOAdapterMode_Write); SAFE_POINT(res == true, QString("Failed to open SAM file for write: %1").arg(samFileUrl.getURLString()),); //init assembly objects U2OpStatusImpl status; QSharedPointer dbiHandle; if (NULL == handle) { dbiHandle = QSharedPointer(new DbiHandle("SQLiteDbi", dbFileUrl.getURLString(), false, status)); handle = dbiHandle.data(); } U2ObjectDbi *odbi = handle->dbi->getObjectDbi(); U2AssemblyDbi *assDbi = handle->dbi->getAssemblyDbi(); QList objectIds = odbi->getObjects("/", 0, U2_DBI_NO_LIMIT, status); U2Region wholeAssembly; wholeAssembly.startPos = 0; QVector names; QVector lengths; foreach(U2DataId id, objectIds) { U2DataType objectType = handle->dbi->getEntityTypeById(id); if (U2Type::Assembly == objectType) { U2Assembly assembly = handle->dbi->getAssemblyDbi()->getAssemblyObject(id, status); int length = handle->dbi->getAttributeDbi()->getIntegerAttribute(id, status).value; names.append(assembly.visualName.replace(QRegExp("\\s|\\t"), "_").toAscii()); lengths.append(length); } } //writing to a sam file for an every object samFormat.storeHeader(io.get(), names, lengths); foreach(U2DataId id, objectIds) { U2DataType objectType = handle->dbi->getEntityTypeById(id); if (U2Type::Assembly == objectType) { U2Assembly assembly = handle->dbi->getAssemblyDbi()->getAssemblyObject(id, status); wholeAssembly.length = assDbi->getMaxEndPos(assembly.id, status); QByteArray refSeqName = assembly.visualName.replace(QRegExp("\\s|\\t"), "_").toAscii(); U2DbiIterator *dbiIterator = assDbi->getReads(assembly.id, wholeAssembly, status); DNASequence seq; while (dbiIterator->hasNext()) { U2AssemblyRead read = dbiIterator->next(); read->cigar; seq.seq = read->readSequence; seq.quality = read->quality; seq.setName(read->name); QByteArray cigar = U2AssemblyUtils::cigar2String(read->cigar); if(!QRegExp("[!-~]+").exactMatch(seq.quality.qualCodes)) { seq.quality.qualCodes = "*"; } if (cigar.isEmpty()) { cigar = "*"; } samFormat.storeAlignedRead(read->leftmostPos, seq, io.get(), refSeqName, wholeAssembly.length, false, true, cigar); } } } } QString ConvertAssemblyToSamTask::generateReport() const { if (hasError() || isCanceled()) { return QString("Conversion task was finished with an error: %1").arg(getError()); } return QString("Conversion task was finished. A new SAM file is: %2").arg(samFileUrl.getURLString()).arg(samFileUrl.getURLString()); } } // U2 ugene-1.9.8/src/corelibs/U2Formats/src/tasks/ConvertAssemblyToSamTask.h0000644000175000017500000000277611651544332024541 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_CONVERT_ASSEMBLY_TO_SAM_TASK_H_ #define _U2_CONVERT_ASSEMBLY_TO_SAM_TASK_H_ #include #include #include #include namespace U2 { class LoadDocumentTask; class DbiHandle; class U2FORMATS_EXPORT ConvertAssemblyToSamTask : public Task { Q_OBJECT public: ConvertAssemblyToSamTask(GUrl dbFileUrl, GUrl samFileUrl); ConvertAssemblyToSamTask(const DbiHandle *handle, GUrl samFileUrl); void run(); QString generateReport() const; private: GUrl dbFileUrl; GUrl samFileUrl; const DbiHandle *handle; }; }// U2 #endif //_U2_CONVERT_ASSEMBLY_TO_SAM_TASK_H_ ugene-1.9.8/src/corelibs/U2Formats/src/NewickFormat.cpp0000644000175000017500000002461711651544332021427 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "NewickFormat.h" #include #include #include #include namespace U2 { /* TRANSLATOR U2::IOAdapter */ /* TRANSLATOR U2::NewickFormat */ NewickFormat::NewickFormat(QObject* p) : DocumentFormat(p, DocumentFormatFlags_W1) { fileExtensions << "nwk" << "newick"; formatName = tr("Newick Standard"); formatDescription = tr("Newick is a simple format used to write out trees in a text file"); supportedObjectTypes += GObjectTypes::PHYLOGENETIC_TREE; } #define BUFF_SIZE 1024 static QList parseTrees(IOAdapter* io, TaskStateInfo& si); Document* NewickFormat::loadDocument(IOAdapter* io, TaskStateInfo& ti, const QVariantMap& fs, DocumentLoadMode) { QList objects = parseTrees(io, ti); if (ti.hasError()) { qDeleteAll(objects); return NULL; } Document* d = new Document(this, io->getFactory(), io->getURL(), objects, fs); return d; } static void writeNode(IOAdapter* io, PhyNode* node) { int branches = node->branches.size(); if (branches == 1 && (node->name == "" || node->name == "ROOT")) { assert(node != node->branches[0]->node2); writeNode(io, node->branches[0]->node2); return; } if (branches > 1) { io->writeBlock("(", 1); bool first = true; for (int i = 0; i < branches; ++i) { if (node->branches[i]->node2 != node) { if (first) { first = false; } else { io->writeBlock(",", 1); } writeNode(io, node->branches[i]->node2); io->writeBlock(":", 1); io->writeBlock(QByteArray::number(node->branches[i]->distance)); } } io->writeBlock(")", 1); } else { io->writeBlock(node->name.replace(' ', '_').toAscii()); } } void NewickFormat::storeDocument( Document* d, TaskStateInfo& ts, IOAdapter* io) { Q_UNUSED(ts); assert(d->getDocumentFormat() == this); foreach(GObject* obj, d->getObjects()) { PhyTreeObject* phyObj = qobject_cast(obj); if (phyObj != NULL) { writeNode(io, phyObj->getTree()->rootNode); io->writeBlock(";\n", 2); } } } RawDataCheckResult NewickFormat::checkRawData(const QByteArray& rawData, const GUrl&) const { const char* data = rawData.constData(); int size = rawData.size(); bool containsBinary = TextUtils::contains(TextUtils::BINARY, data, size); if (containsBinary) { return FormatDetection_NotMatched; } int brackets = 0; typedef enum { letter, letter_than_whites, any } Cases; Cases last = any; for (int i = 0; i < size; ++i) { switch (data[i]) { case '(': ++brackets; break; case ')': if (brackets == 0) { return FormatDetection_NotMatched; } --brackets; break; case ';': if (brackets != 0) { return FormatDetection_NotMatched; } break; default: if(data[i] < 0) { // for ex. if file contains utf-8 symbols return FormatDetection_NotMatched; } if (TextUtils::ALPHA_NUMS[data[i]] || data[i] == '-' || data[i] == '_') { if (last == letter_than_whites) { return FormatDetection_NotMatched; } last = letter; continue; } if (TextUtils::WHITES[data[i]]) { if (last == letter || last == letter_than_whites) { last = letter_than_whites; continue; } } } last = any; } if (QRegExp("[a-zA-Z\r\n]*").exactMatch(rawData)) { return FormatDetection_LowSimilarity; } int braces = (rawData.contains('(') ? 1 : 0) + (rawData.contains(')') ? 1 : 0) ; if (braces == 0 && rawData.length() > 50) { return FormatDetection_LowSimilarity; } if (braces == 1) { return FormatDetection_NotMatched; } return FormatDetection_HighSimilarity; } /* TODO: Unquoted labels may not contain blanks, parentheses, square brackets, single_quotes, colons, semicolons, or commas. Single quote characters in a quoted label are represented by two single quotes. Blanks or tabs may appear anywhere except within unquoted labels or branch_lengths. Newlines may appear anywhere except within labels or branch_lengths. Comments are enclosed in square brackets and may appear anywhere newlines are permitted. */ static QList parseTrees(IOAdapter *io, TaskStateInfo& si) { QList objects; QByteArray block(BUFF_SIZE, '\0'); int blockLen; bool done = true; QBitArray ops(256); ops['('] = ops[')'] = ops[':'] = ops[','] = ops[';'] = true; enum ReadState {RS_NAME, RS_WEIGHT}; ReadState state = RS_NAME; QString lastStr; PhyNode *rd = new PhyNode(); QStack nodeStack; QStack branchStack; nodeStack.push(rd); while ((blockLen = io->readBlock(block.data(), BUFF_SIZE)) > 0) { for (int i = 0; i < blockLen; ++i) { unsigned char c = block[i]; if (TextUtils::WHITES[(uchar)c]) { continue; } done = false; if (!ops[(uchar)c]) { //not ops -> cache lastStr.append(c); continue; } // use cached value if (state == RS_NAME) { nodeStack.top()->name = lastStr.replace('_', ' '); } else { assert(state == RS_WEIGHT); if (!branchStack.isEmpty()) { //ignore root node weight if present if (nodeStack.size() < 2) { si.setError(NewickFormat::tr("Unexpected weight: %1").arg(lastStr)); } bool ok = false; branchStack.top()->distance = lastStr.toDouble(&ok); if (!ok) { si.setError(NewickFormat::tr("Error parsing weight: %1").arg(lastStr)); break; } } } // advance in state if (c == '(') { //new child assert(!nodeStack.isEmpty()); PhyNode* pn = new PhyNode(); PhyBranch* bd = PhyNode::addBranch(nodeStack.top(),pn, 0); nodeStack.push(pn); branchStack.push(bd); state = RS_NAME; } else if (c == ':') { //weight start if (state == RS_WEIGHT) { si.setError(NewickFormat::tr("Unexpected weight start token: %1").arg(lastStr)); break; } state = RS_WEIGHT; } else if ( c == ',') { //new sibling assert(!nodeStack.isEmpty()); assert(!branchStack.isEmpty()); if (nodeStack.isEmpty() || branchStack.isEmpty()) { si.setError(NewickFormat::tr("Unexpected new sibling %1").arg(lastStr)); break; } nodeStack.pop(); branchStack.pop(); PhyNode* pn = new PhyNode(); PhyBranch* bd = PhyNode::addBranch(nodeStack.top(), pn, 0); nodeStack.push(pn); branchStack.push(bd); state = RS_NAME; } else if ( c == ')' ) { //end of the branch, go up nodeStack.pop(); if (nodeStack.isEmpty()) { si.setError(NewickFormat::tr("Unexpected closing bracket :%1").arg(lastStr)); break; } assert(!branchStack.isEmpty()); branchStack.pop(); state = RS_NAME; } else if (c == ';') { if (!branchStack.isEmpty() || nodeStack.size()!=1) { si.setError(NewickFormat::tr("Unexpected end of file")); break; } PhyTree tree(new PhyTreeData()); tree->rootNode = nodeStack.pop(); QString objName = (objects.size() == 0) ? QString("Tree") : QString("Tree%1").arg(objects.size() + 1); objects.append(new PhyTreeObject(tree, objName)); nodeStack.push(rd = new PhyNode()); done = true; } lastStr.clear(); } if (si.hasError() || si.cancelFlag) { delete rd; rd = NULL; break; } si.progress = io->getProgress(); } if (!si.hasError() && !si.cancelFlag) { if (!branchStack.isEmpty() || nodeStack.size()!=1) { delete rd; si.setError(NewickFormat::tr("Unexpected end of file")); return objects; } if (!done) { PhyNode *node = nodeStack.pop(); PhyTree tree(new PhyTreeData()); tree->rootNode = node; QString objName = (objects.size() == 0) ? QString("Tree") : QString("Tree%1").arg(objects.size() + 1); objects.append(new PhyTreeObject(tree, objName)); } else { delete rd; if (objects.empty()) { si.setError(NewickFormat::tr("Empty file")); } } } return objects; } }//namespace ugene-1.9.8/src/corelibs/U2Formats/src/PlainTextFormat.cpp0000644000175000017500000000722711651544332022115 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "PlainTextFormat.h" #include #include #include #include #include namespace U2 { /* TRANSLATOR U2::IOAdapter */ PlainTextFormat::PlainTextFormat(QObject* p) : DocumentFormat(p, DocumentFormatFlags_W1, QStringList("txt")) { formatName = tr("Plain text"); supportedObjectTypes+=GObjectTypes::TEXT; formatDescription = tr("A simple plain text file."); } Document* PlainTextFormat::createNewDocument(IOAdapterFactory* io, const QString& url, const QVariantMap& fs) { Document* d = DocumentFormat::createNewDocument(io, url, fs); GObject* o = new TextObject("", "Text"); d->addObject(o); return d; } #define BUFF_SIZE 1024 Document* PlainTextFormat::loadDocument(IOAdapter* io, TaskStateInfo& ti, const QVariantMap& fs, DocumentLoadMode) { QString text; int size = io->left(); if (size > 0) { text.reserve(size); } QByteArray block(BUFF_SIZE, '\0'); int blockLen = 0; while ((blockLen = io->readBlock(block.data(), BUFF_SIZE)) > 0) { int sizeBefore = text.length(); QString line = QString::fromLocal8Bit(block.data(), blockLen); text.append(line); if (text.length() != sizeBefore + blockLen) { ti.setError(L10N::errorReadingFile(io->getURL())); break; } ti.progress = io->getProgress(); } if (ti.hasError()) { return NULL; } //todo: check file-readonly status? TextObject* to = new TextObject(text, "Text"); QList objects; objects.append(to); Document* d = new Document(this, io->getFactory(), io->getURL(), objects, fs); return d; } void PlainTextFormat::storeDocument( Document* d, TaskStateInfo& ts, IOAdapter* io) { assert(d->getObjects().size() ==1); GObject* obj = d->getObjects().first(); TextObject* to = qobject_cast(obj); assert(to!=NULL); const QString& text = to->getText(); QByteArray local8bit = text.toLocal8Bit(); storeRawData(local8bit, ts, io); } void PlainTextFormat::storeRawData(const QByteArray& rawData, TaskStateInfo& ts, IOAdapter* io) { int nWritten = 0; int nTotal = rawData.size(); while(nWritten < nTotal) { int l = io->writeBlock(rawData.data() + nWritten, nTotal - nWritten); if (l <= 0 ) { ts.setError(L10N::errorWritingFile(io->getURL())); return; } nWritten+= l; } } RawDataCheckResult PlainTextFormat::checkRawData(const QByteArray& rawData, const GUrl&) const { const char* data = rawData.constData(); int size = rawData.size(); bool hasBinaryData = TextUtils::contains(TextUtils::BINARY, data, size); return hasBinaryData ? FormatDetection_NotMatched :FormatDetection_LowSimilarity; } }//namespace ugene-1.9.8/src/corelibs/U2Formats/src/GenbankFeatures.h0000644000175000017500000001636511651544332021550 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_GENBANK_FEATURES_H_ #define _U2_GENBANK_FEATURES_H_ #include #include #include #include #include namespace U2 { enum GBFeatureKey { GBFeatureKey_attenuator, // Sequence related to transcription termination GBFeatureKey_C_region, // Span of the C immunological feature GBFeatureKey_CAAT_signal, // `CAAT box' in eukaryotic promoters GBFeatureKey_CDS, // Sequence coding for amino acids in protein (includes stop codon) GBFeatureKey_conflict, // Independent sequence determinations differ GBFeatureKey_D_loop, // Displacement loop GBFeatureKey_D_segment, // Span of the D immunological feature GBFeatureKey_enhancer, // Cis-acting enhancer of promoter function GBFeatureKey_exon, // Region that codes for part of spliced mRNA GBFeatureKey_gene, // Region that defines a functional gene, possibly including upstream (promotor, enhancer, etc) and downstream control elements, and for which a name has been assigned. GBFeatureKey_GC_signal, // `GC box' in eukaryotic promoters GBFeatureKey_iDNA, // Intervening DNA eliminated by recombination GBFeatureKey_intron, // Transcribed region excised by mRNA splicing GBFeatureKey_J_region, // Span of the J immunological feature GBFeatureKey_LTR, // Long terminal repeat GBFeatureKey_mat_peptide, // Mature peptide coding region (does not include stop codon) GBFeatureKey_misc_binding, // Miscellaneous binding site GBFeatureKey_misc_difference, // Miscellaneous difference feature GBFeatureKey_misc_feature, // Region of biological significance that cannot be described by any other feature GBFeatureKey_misc_recomb, // Miscellaneous, recombination feature GBFeatureKey_misc_RNA, // Miscellaneous transcript feature not defined by other RNA keys GBFeatureKey_misc_signal, // Miscellaneous signal GBFeatureKey_misc_structure, // Miscellaneous DNA or RNA structure GBFeatureKey_modified_base, // The indicated base is a modified nucleotide GBFeatureKey_mRNA, // Messenger RNA GBFeatureKey_N_region, // Span of the N immunological feature GBFeatureKey_old_sequence, // Presented sequence revises a previous version GBFeatureKey_polyA_signal, // Signal for cleavage & polyadenylation GBFeatureKey_polyA_site, // Site at which polyadenine is added to mRNA GBFeatureKey_precursor_RNA, // Any RNA species that is not yet the mature RNA product GBFeatureKey_prim_transcript, // Primary (unprocessed) transcript GBFeatureKey_primer, // Primer binding region used with PCR GBFeatureKey_primer_bind, // Non-covalent primer binding site GBFeatureKey_promoter, // A region involved in transcription initiation GBFeatureKey_protein_bind, // Non-covalent protein binding site on DNA or RNA GBFeatureKey_RBS, // Ribosome binding site GBFeatureKey_rep_origin, // Replication origin for duplex DNA GBFeatureKey_repeat_region, // Sequence containing repeated subsequences GBFeatureKey_repeat_unit, // One repeated unit of a repeat_region GBFeatureKey_rRNA, // Ribosomal RNA GBFeatureKey_S_region, // Span of the S immunological feature GBFeatureKey_satellite, // Satellite repeated sequence GBFeatureKey_scRNA, // Small cytoplasmic RNA GBFeatureKey_sig_peptide, // Signal peptide coding region GBFeatureKey_snRNA, // Small nuclear RNA GBFeatureKey_source, // Identifies the biological source of the specified span of the sequence GBFeatureKey_stem_loop, // Hair-pin loop structure in DNA or RNA GBFeatureKey_STS, // Sequence Tagged Site; operationally unique sequence that identifies the combination of primer spans used in a PCR assay GBFeatureKey_TATA_signal, // `TATA box' in eukaryotic promoters GBFeatureKey_terminator, // Sequence causing transcription termination GBFeatureKey_transit_peptide, // Transit peptide coding region GBFeatureKey_transposon, // Transposable element (TN) GBFeatureKey_tRNA, // Transfer RNA GBFeatureKey_unsure, // Authors are unsure about the sequence in this region GBFeatureKey_V_region, // Span of the V immunological feature GBFeatureKey_variation, // A related population contains stable mutation GBFeatureKey__10_signal, // `Pribnow box' in prokaryotic promoters GBFeatureKey__35_signal, // `-35 box' in prokaryotic promoters GBFeatureKey_3_clip, // 3'-most region of a precursor transcript removed in processing GBFeatureKey_3_UTR, // 3' untranslated region (trailer) GBFeatureKey_5_clip, // 5'-most region of a precursor transcript removed in processing GBFeatureKey_5_UTR, // 5' untranslated region (leader) GBFeatureKey_Protein, // GBFeatureKey_Region, // GBFeatureKey_Site, // GBFeatureKey_NUM_KEYS, GBFeatureKey_UNKNOWN = GBFeatureKey_NUM_KEYS }; class U2FORMATS_EXPORT GBFeatureKeyInfo { public: GBFeatureKeyInfo() : id (GBFeatureKey_UNKNOWN), showOnaminoFrame(false) {} GBFeatureKeyInfo(GBFeatureKey _id, const QString& _text, const QColor& _color, bool _aminoFrame, QString _desc) : id (_id), text(_text), color(_color), showOnaminoFrame(_aminoFrame), desc(_desc) {} GBFeatureKey id; QString text; QColor color; bool showOnaminoFrame; QString desc; QStringList namingQuals; }; class U2FORMATS_EXPORT GBFeatureUtils : public QObject { Q_OBJECT public: static QMutex allKeys_mutex; static const QVector& allKeys(); static QMutex getKeyGroups_mutex; static const GBFeatureKeyInfo& getKeyInfo(GBFeatureKey key) {return allKeys().at(key);} static QMutex getKey_mutex; static const QMultiMap& getKeyGroups(); static GBFeatureKey getKey(const QString& text); static const QByteArray QUALIFIER_AMINO_STRAND; static const QByteArray QUALIFIER_AMINO_STRAND_YES; static const QByteArray QUALIFIER_AMINO_STRAND_NO; static const QByteArray QUALIFIER_NAME; static const QByteArray QUALIFIER_GROUP; static const QString DEFAULT_KEY; static const QString QUALIFIER_CUT; //max annotation key len in Genbank or EMBL formats static const int MAX_KEY_LEN; }; }//namespace #endif ugene-1.9.8/src/corelibs/U2Formats/src/EMBLGenbankAbstractDocument.cpp0000644000175000017500000005356311651544332024230 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "EMBLGenbankAbstractDocument.h" #include "GenbankLocationParser.h" #include "GenbankFeatures.h" #include "DocumentFormatUtils.h" #include #include #include #include #include #include #include #include #include #include #include #include namespace U2 { /* TRANSLATOR U2::EMBLGenbankAbstractDocument */ //TODO: local8bit or ascii?? EMBLGenbankAbstractDocument::EMBLGenbankAbstractDocument(const DocumentFormatId& _id, const QString& _formatName, int mls, DocumentFormatFlags flags, QObject* p) : DocumentFormat(p, flags), id(_id), formatName(_formatName), maxAnnotationLineLen(mls) { supportedObjectTypes+=GObjectTypes::ANNOTATION_TABLE; supportedObjectTypes+=GObjectTypes::SEQUENCE; } ////////////////////////////////////////////////////////////////////////// // loading Document* EMBLGenbankAbstractDocument::loadDocument(IOAdapter* io, TaskStateInfo& ti, const QVariantMap& _fs, DocumentLoadMode mode) { QVariantMap fs = _fs; QList objects; QString writeLockReason; load(io, objects, fs, ti, writeLockReason, mode); if (ti.hasError() || ti.cancelFlag) { return NULL; } DocumentFormatUtils::updateFormatSettings(objects, fs); Document* doc = new Document(this, io->getFactory(), io->getURL(), objects, fs, writeLockReason); return doc; } const QString EMBLGenbankAbstractDocument::UGENE_MARK("UNIMARK"); const QString EMBLGenbankAbstractDocument::DEFAULT_OBJ_NAME("unnamed"); void EMBLGenbankAbstractDocument::load(IOAdapter* io, QList& objects, QVariantMap& fs, TaskStateInfo& si, QString& writeLockReason, DocumentLoadMode mode) { writeLockReason.clear(); //get settings int gapSize = qBound(-1, DocumentFormatUtils::getMergeGap(fs), 1000*1000); bool merge = gapSize!=-1; QByteArray sequence; QByteArray gapSequence((merge ? gapSize : 0), 0); AnnotationTableObject* mergedAnnotations = NULL; QStringList contigs; QVector mergedMapping; int predictedSize = qMax(100*1000, DocumentFormatUtils::getIntSettings(fs, DocumentReadingMode_SequenceMergingFinalSizeHint, merge ? 0 : io->left())); sequence.reserve(predictedSize + (merge ? gapSize : 0)); QSet usedNames; bool toolMark = false; int sequenceStart = 0; GObjectReference sequenceRef(GObjectReference(io->getURL().getURLString(), "", GObjectTypes::SEQUENCE)); QByteArray readBuffer(ParserState::READ_BUFF_SIZE, '\0'); ParserState st(getFormatId() == BaseDocumentFormats::PLAIN_GENBANK ? 12 : 5, io, NULL, si); st.buff = readBuffer.data(); for (int i=0; !si.hasError() && !si.cancelFlag; i++) { if (!merge) { sequence.clear(); } else if (sequence.size() > 0) { sequence.append(gapSequence); sequenceStart = sequence.size(); } EMBLGenbankDataEntry data; st.entry = &data; si.setDescription(tr("Reading entry header")); if (!readEntry(sequence, &st)) { break; } // tolerate blank lines between records char ch; bool b; while ((b = st.io->getChar(&ch)) && (ch == '\n' || ch == '\r')){} if (b) { st.io->skip(-1); } toolMark = data.tags.contains(UGENE_MARK); AnnotationTableObject* annotationsObject = NULL; if (data.hasAnnotationObjectFlag) { QString annotationName = genObjectName(usedNames, data.name, data.tags, i+1, GObjectTypes::ANNOTATION_TABLE); if (merge && mergedAnnotations == NULL) { mergedAnnotations = new AnnotationTableObject(annotationName); } annotationsObject = merge ? mergedAnnotations : new AnnotationTableObject(annotationName); QStringList groupNames; foreach(SharedAnnotationData d, data.features) { groupNames.clear(); d->removeAllQualifiers(GBFeatureUtils::QUALIFIER_GROUP, groupNames); if (groupNames.isEmpty()) { annotationsObject->addAnnotation(new Annotation(d)); } else { Annotation* a = new Annotation(d); foreach(const QString& gName, groupNames) { annotationsObject->getRootGroup()->getSubgroup(gName, true)->addAnnotation(a); } } } if (!merge) { objects.append(annotationsObject); } } else { assert(data.features.isEmpty()); } if (!si.hasError() && !si.cancelFlag) { int sequenceLen = sequence.size() - sequenceStart; QString sequenceName = genObjectName(usedNames, data.name, data.tags, i+1, GObjectTypes::SEQUENCE); if (merge && sequenceLen == 0 && annotationsObject!=NULL) { si.setError(tr("Merge error: found annotations without sequence")); break; } else if (merge) { contigs.append(sequenceName); mergedMapping.append(U2Region(sequenceStart, sequenceLen)); } else if (sequenceLen!=0){ DNASequence seq(sequence); seq.info = data.tags; seq.circular = data.circular; DNASequenceObject* seqObj = DocumentFormatUtils::addSequenceObject(objects, sequenceName, seq, fs, si); if (si.hasError()) { break; } SAFE_POINT(seqObj != NULL, "DocumentFormatUtils::addSequenceObject returned NULL but didn't set error",); if (annotationsObject!=NULL) { sequenceRef.objName = seqObj->getGObjectName(); annotationsObject->addObjectRelation(GObjectRelation(sequenceRef, GObjectRelationRole::SEQUENCE)); } } } if( mode == DocumentLoadMode_SingleObject ) { break; } } if (!si.hasError() && !si.cancelFlag && merge && !contigs.isEmpty()) { assert(sequence.size() > gapSize); assert(qEqual(sequence.constEnd() - gapSize, sequence.constEnd(), gapSequence.constBegin())); sequence.resize(sequence.size() - gapSize);//remove last gap DNASequenceObject* so = DocumentFormatUtils::addMergedSequenceObject(objects, io->getURL(), contigs, sequence, mergedMapping, fs, si); if (si.hasError()) { qDeleteAll(objects); delete mergedAnnotations; return; } SAFE_POINT(so != NULL, "DocumentFormatUtils::addMergedSequenceObject returned NULL but didn't set error",); if (mergedAnnotations!=NULL) { sequenceRef.objName = so->getGObjectName(); mergedAnnotations->addObjectRelation(GObjectRelation(sequenceRef, GObjectRelationRole::SEQUENCE)); objects.append(mergedAnnotations); } } if (!si.hasError() && !si.cancelFlag && objects.isEmpty()) { si.setError(U2::Document::tr("Document is empty.")); } if (!toolMark) { writeLockReason = DocumentFormat::CREATED_NOT_BY_UGENE; } else if (merge && contigs.size() > 1) { writeLockReason = DocumentFormat::MERGED_SEQ_LOCK; } } //column annotation data starts with #define A_COL 21 //column qualifier name starts with #define QN_COL 22 //column annotation key starts with #define K_COL 5 static bool isNewQStart(const char* s, int l) { if (l < A_COL + 1 || s[A_COL]!='/') { return false; } const QBitArray& WHITES = TextUtils::WHITES; for (int i = QN_COL; i < l; i++) { char c = s[i]; if (c == '=' && i > QN_COL) { return true; } if (WHITES[(uchar)c]) { break; } } return false; } //TODO: make it IO active -> read util the end. Otherwise qualifier is limited in size by maxSize int EMBLGenbankAbstractDocument::readMultilineQualifier(IOAdapter* io, char* cbuff, int maxSize, bool _prevLineHasMaxSize) { int len = 0; bool lineOk = true; static const int MAX_LINE = 256; int sizeToSkip = maxSize - MAX_LINE; const QBitArray& LINE_BREAKS = TextUtils::LINE_BREAKS; bool breakWords = !_prevLineHasMaxSize; //todo: create a parameter and make it depends on annotation name. do { if (len >= sizeToSkip) { QByteArray skip(MAX_LINE, 0); char* skipBuff = skip.data(); do { int readLen = io->readUntil(skipBuff, MAX_LINE, TextUtils::LINE_BREAKS, IOAdapter::Term_Include, &lineOk); if (!lineOk) { continue;//todo: report error! } int lineLen = readLen; for (; A_COL < lineLen && LINE_BREAKS[(uchar)skipBuff[lineLen-1]]; lineLen--){}; //remove line breaks if (lineLen == 0 || lineLen < A_COL || skip[0]!=fPrefix[0] || skip[1]!=fPrefix[1] || skip[K_COL]!=' ' || (skip[A_COL]=='/' && isNewQStart(skip, lineLen))) { io->skip(-readLen); break; } } while (true); break; } char* lineBuf = cbuff + len; int readLen = io->readUntil(lineBuf, maxSize-len, TextUtils::LINE_BREAKS, IOAdapter::Term_Include, &lineOk); int lineLen = readLen; for (; A_COL < lineLen && LINE_BREAKS[(uchar)lineBuf[lineLen-1]]; lineLen--){}; //remove line breaks if (!lineOk || lineLen == 0 || lineLen < A_COL || lineBuf[0]!=fPrefix[0] || lineBuf[1]!=fPrefix[1] || lineBuf[K_COL]!=' ' || (lineBuf[A_COL]=='/' && isNewQStart(lineBuf, lineLen))) { io->skip(-readLen); break; } if (breakWords && lineLen-A_COL > 0 && lineBuf[A_COL]!=' ') { //add space to separate words cbuff[len] = ' '; len++; } qMemCopy(cbuff + len, lineBuf + A_COL, lineLen - A_COL); len+=lineLen-A_COL; breakWords = breakWords || lineLen < maxAnnotationLineLen; } while (true); return len; } QString EMBLGenbankAbstractDocument::genObjectName(QSet& usedNames, const QString& seqName, const QVariantMap& tags, int n, const GObjectType& t) { //try to check UGENE_MARK first QString name; QStringList unimark = tags.value(UGENE_MARK).toStringList(); if (!unimark.isEmpty()) { int pos = usedNames.size(); if (pos < unimark.size()) { name = unimark.at(pos); } } if (name.isEmpty()) { name = seqName; if (name.isEmpty()) { name = DNAInfo::getPrimaryAccession(tags); int spaceIdx = name.indexOf(' '); if (spaceIdx > 0) { name = name.left(spaceIdx-1); } if (name.isEmpty()) { name = EMBLGenbankAbstractDocument::DEFAULT_OBJ_NAME; } } if(t == GObjectTypes::ANNOTATION_TABLE) { name+=" features"; } else if (t == GObjectTypes::SEQUENCE) { name+=" sequence"; } } //now variate name if there are duplicates int n2 = 1; QString res = name; while (usedNames.contains(res)) { res = name + " " + QString::number(n) + (n2 == 1 ? QString("") : ("."+QString::number(n2))); } usedNames.insert(res); return res; } DNASequence* EMBLGenbankAbstractDocument::loadSequence( IOAdapter* io, TaskStateInfo& ti) { while(true) { std::auto_ptr document(loadDocument(io, ti, QVariantMap(), DocumentLoadMode_SingleObject)); if(ti.isCoR()) { return NULL; } foreach(GObject *object, document->getObjects()) { if(object->getGObjectType() == GObjectTypes::SEQUENCE) { return new DNASequence(((DNASequenceObject *)object)->getDNASequence()); } } } } static void checkQuotes(const char* str, int len, bool& outerQuotes, bool& doubleQuotes) { char qChar = '\"'; assert(len>=0); outerQuotes = str[0] == qChar && str[len-1]==qChar; for(int i=1; i < len; i++) { if (str[i-1]==qChar && str[i] == qChar) { doubleQuotes = true; break; } } } SharedAnnotationData EMBLGenbankAbstractDocument::readAnnotation(IOAdapter* io, char* cbuff, int len, int READ_BUFF_SIZE, TaskStateInfo& si, int offset) { AnnotationData* a = new AnnotationData(); SharedAnnotationData f(a); QString key = QString::fromAscii(cbuff+5, 15).trimmed(); if (key.isEmpty()) { si.setError(EMBLGenbankAbstractDocument::tr("Annotation name is empty")); return SharedAnnotationData(); } a->name = key; //qualifier starts on offset 22; int qlen = len + readMultilineQualifier(io, cbuff+len, READ_BUFF_SIZE - len, true); if (qlen < 21) { si.setError(EMBLGenbankAbstractDocument::tr("Error parsing location")); return SharedAnnotationData(); } Genbank::LocationParser::parseLocation(cbuff+21, qlen-21, a->location); if (a->location->isEmpty()) { si.setError(EMBLGenbankAbstractDocument::tr("Error parsing location")); return SharedAnnotationData(); } // omit sorting because of splitted annotations /*if (a->location->isMultiRegion()) { qSort(a->location->regions); }*/ if (offset!=0) { U2Region::shift(offset, a->location->regions); } const QBitArray& LINE_BREAKS = TextUtils::LINE_BREAKS; const QByteArray& aminoQ = GBFeatureUtils::QUALIFIER_AMINO_STRAND; //const QByteArray& aminoQYes = GBFeatureUtils::QUALIFIER_AMINO_STRAND_YES; //const QByteArray& aminoQNo = GBFeatureUtils::QUALIFIER_AMINO_STRAND_NO; const QByteArray& nameQ = GBFeatureUtils::QUALIFIER_NAME; //here we have valid key and location; //reading qualifiers bool lineOk = true; while ((len = io->readUntil(cbuff, READ_BUFF_SIZE, TextUtils::LINE_BREAKS, IOAdapter::Term_Include, &lineOk) ) > 0) { if (len == 0 || len < QN_COL+1 || cbuff[K_COL]!=' ' || cbuff[A_COL]!='/' || cbuff[0]!=fPrefix[0] || cbuff[1]!=fPrefix[1]) { io->skip(-len); break; } if (!lineOk) { si.setError(EMBLGenbankAbstractDocument::tr("Unexpected line format")); break; } for (; QN_COL < len && LINE_BREAKS[(uchar)cbuff[len-1]]; len--){}; //remove line breaks int flen = len + readMultilineQualifier(io, cbuff+len, READ_BUFF_SIZE-len, len == maxAnnotationLineLen); //now the whole feature is in cbuff int valStart = A_COL + 1; for (; valStart < flen && cbuff[valStart] != '='; valStart++){}; //find '==' and valStart if (valStart < flen) { valStart++; //skip '=' char } const QBitArray& WHITE_SPACES = TextUtils::WHITES; for (; valStart < flen && WHITE_SPACES[(uchar)cbuff[flen-1]]; flen--){}; //trim value const char* qname = cbuff + QN_COL; int qnameLen = valStart - (QN_COL + 1); const char* qval = cbuff + valStart; int qvalLen = flen - valStart; bool removeQuotes = false; bool containsDoubleQuotes = false; checkQuotes(qval, qvalLen, removeQuotes, containsDoubleQuotes); if (removeQuotes) { qval++; qvalLen-=2; } if (qnameLen == aminoQ.length() && TextUtils::equals(qname, aminoQ.constData(), qnameLen)) { //a->aminoFrame = qvalLen == aminoQYes.length() && TextUtils::equals(qval, aminoQYes.constData(), qvalLen) ? TriState_Yes // : (qvalLen == aminoQNo.length() && TextUtils::equals(qval, aminoQNo.constData(), qvalLen) ? TriState_No : TriState_Unknown); } else if (qnameLen == nameQ.length() && TextUtils::equals(qname, nameQ.constData(), qnameLen)) { a->name = QString::fromLocal8Bit(qval, qvalLen); } else { QString nameQStr = QString::fromLocal8Bit(qname, qnameLen); QString valQStr = QString::fromLocal8Bit(qval, qvalLen); if (containsDoubleQuotes) { valQStr = valQStr.replace("\"\"", "\""); } a->qualifiers.append(U2Qualifier(nameQStr, valQStr)); } } return f; } bool EMBLGenbankAbstractDocument::readSequence(QByteArray& res, ParserState* st) { // FIXME use ParserState instead IOAdapter* io = st->io; TaskStateInfo& si = st->si; si.setDescription(tr("Reading sequence %1").arg(st->entry->name)); int headerSeqLen = st->entry->seqLen; res.reserve(res.size() + headerSeqLen); static int READ_BUFF_SIZE = 4096; QByteArray readBuffer(READ_BUFF_SIZE, '\0'); char* buff = readBuffer.data(); //reading sequence QBuffer writer(&res); writer.open( QIODevice::WriteOnly | QIODevice::Append ); bool ok = true; int len; int dataOffset = 0; bool numIsPrefix = getFormatId() == BaseDocumentFormats::PLAIN_GENBANK; while (ok && (len = io->readLine(buff, READ_BUFF_SIZE)) > 0) { if (si.cancelFlag) { res.clear(); break; } if (len <= 0) { si.setError(tr("Error parsing sequence: unexpected empty line")); break; } if (buff[0] == '/') { //end of the sequence break; } //compute data offset bool foundNum = false; bool foundSpaceAfterNum = false; for(dataOffset = 0 ; dataOffset < len; dataOffset++) { char c = numIsPrefix ? buff[dataOffset] : buff[len - dataOffset - 1]; bool isNum = c >= '0' && c <= '9'; bool isSpace = c == ' ' || c == '\t'; if (!isSpace && (!isNum || foundSpaceAfterNum)) { if (!foundSpaceAfterNum) { //unknown character -> stop iteration dataOffset = len; } break; } foundNum = foundNum || isNum; foundSpaceAfterNum = foundSpaceAfterNum || (isSpace && foundNum); } if (dataOffset == len) { si.setError(tr("Error reading sequence: invalid sequence format")); break; } //add buffer to result for (int i= (numIsPrefix ? dataOffset : 0), n = (numIsPrefix ? len : len - dataOffset) ; i < n; i++) { char c = buff[i]; if (c != ' ' && c != '\t') { ok = writer.putChar(c); if (!ok) { break; } } } if (!ok) { si.setError(tr("Error reading sequence: memory allocation failed")); break; } si.progress = io->getProgress(); } if (!si.hasError() && !si.cancelFlag && buff[0] != '/') { si.setError(tr("Sequence is truncated")); } writer.close(); return true; //FIXME } void EMBLGenbankAbstractDocument::readAnnotations(ParserState* st, int offset) { st->si.setDescription(tr("Reading annotations %1").arg(st->entry->name)); st->entry->hasAnnotationObjectFlag = true; do { if (st->hasKey("XX") && getFormatId() == BaseDocumentFormats::PLAIN_EMBL) { continue; } int fplen = fPrefix.length(); if (st->len >= 6 && TextUtils::equals(fPrefix.data(), st->buff, fplen)) { while (fplen < 5) { if (st->buff[fplen++] != ' ') { st->si.setError(tr("Invalid format of feature table")); break; } } } else { // end of feature table break; } //parsing feature; SharedAnnotationData f = readAnnotation(st->io, st->buff, st->len, ParserState::READ_BUFF_SIZE, st->si, offset); st->entry->features.push_back(f); } while (st->readNextLine()); } bool ParserState::hasKey( const char* key, int slen ) const { assert(slen <= valOffset); if (slen <= len && TextUtils::equals(key, buff, slen)) { while (slen < qMin(valOffset, len)) { if (buff[slen++] != ' ') { return false; } } return true; } return false; } QString ParserState::value() const { return len > valOffset ? QString::fromLocal8Bit(buff + valOffset, len - valOffset) : QString(); } bool ParserState::readNextLine(bool emptyOK) { if (si.cancelFlag || si.hasError()) { len = 0; return false; } bool ok = false; len = io->readLine(buff, READ_BUFF_SIZE, &ok); si.progress = io->getProgress(); if (!ok && len == READ_BUFF_SIZE) { si.setError(U2::EMBLGenbankAbstractDocument::tr("Line is too long.")); } else if (len == -1) { si.setError(U2::EMBLGenbankAbstractDocument::tr("IO error.")); } return (len > 0 || (emptyOK && ok)); } QString ParserState::key() const { //assert(len > 0); return QString::fromLocal8Bit(buff, qMin(valOffset - 1, len)); } }//namespace ugene-1.9.8/src/corelibs/U2Formats/src/RawDNASequenceFormat.h0000644000175000017500000000325011651544332022407 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_RAW_DNA_SEQUENCE_FORMAT_H_ #define _U2_RAW_DNA_SEQUENCE_FORMAT_H_ #include #include namespace U2 { class U2FORMATS_EXPORT RawDNASequenceFormat : public DocumentFormat { Q_OBJECT public: RawDNASequenceFormat(QObject* p); virtual DocumentFormatId getFormatId() const {return BaseDocumentFormats::RAW_DNA_SEQUENCE;} virtual const QString& getFormatName() const {return formatName;} virtual Document* loadDocument(IOAdapter* io, TaskStateInfo& ti, const QVariantMap& fs, DocumentLoadMode mode = DocumentLoadMode_Whole); virtual void storeDocument(Document* d, TaskStateInfo& ts, IOAdapter* io); virtual RawDataCheckResult checkRawData(const QByteArray& rawData, const GUrl& = GUrl()) const; private: QString formatName; }; }//namespace #endif ugene-1.9.8/src/corelibs/U2Formats/src/ACEFormat.cpp0000644000175000017500000003614011651544332020571 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "ACEFormat.h" #include #include #include #include #include #include #include #include #include namespace U2 { const QString ACEFormat::CO = "CO"; const QString ACEFormat::RD = "RD"; const QString ACEFormat::QA = "QA"; const QString ACEFormat::AS = "AS"; const QString ACEFormat::AF = "AF"; const QString ACEFormat::BQ = "BQ"; ACEFormat::ACEFormat(QObject* p) : DocumentFormat(p, DocumentFormatFlags(0), QStringList("ace")) { formatName = tr("ACE"); supportedObjectTypes+=GObjectTypes::MULTIPLE_ALIGNMENT; } static int modifyLine(QString &line, int pos){ int curIdx = 0; char space = ' '; line=line.simplified(); for (int i=0; i < pos; i++){ curIdx = line.indexOf(space); if(-1== curIdx){ return 0; } line = line.mid(curIdx+1); } curIdx = line.indexOf(space); if(-1== curIdx){ return 0; } line = line.mid(0, curIdx); bool ok=false; int result = line.toInt(&ok); if(ok == false){ return -1; }else{ return result; } } static int prepareLine(QString &line, int pos){ int curIdx = 0; char space = ' '; line=line.simplified(); for (int i=0; i < pos; i++){ curIdx = line.indexOf(space); if(-1== curIdx){ return -1; } line = line.mid(curIdx+1); } return curIdx; } #define READS_COUNT_POS 3 static int readsCount(const QString& cur_line){ QString line = cur_line; return modifyLine(line, READS_COUNT_POS); } #define CONTIG_COUNT_POS 1 static int contigCount(const QString& cur_line){ QString line = cur_line; return modifyLine(line, CONTIG_COUNT_POS); } #define LAST_QA_POS 4 static int clearRange(const QString& cur_line){ QString line = cur_line; modifyLine(line, LAST_QA_POS); bool ok = true; int result = line.toInt(&ok); if(!ok){ return INT_MAX; }else{ return result; } } #define PADDED_START_POS 3 static int paddedStartCons(const QString& cur_line){ QString line = cur_line; modifyLine(line, PADDED_START_POS); bool ok = true; int result = line.toInt(&ok); if(!ok){ return INT_MAX; }else{ return result; } } #define READS_POS 3 static int readsPos(const QString& cur_line){ QString line = cur_line; prepareLine(line, READS_POS); if(-1 != line.indexOf(' ')){ return INT_MAX; } line = line.mid(0, line.length()); bool ok = true; int result = line.toInt(&ok); if(!ok){ return INT_MAX; }else{ return result; } } #define COMPLEMENT_POS 2 static int readsComplement(const QString& cur_line){ QString line = cur_line; prepareLine(line, COMPLEMENT_POS); if(line.startsWith("U")){ return 0; }else if (line.startsWith("C")){ return 1; }else{ return -1; } } static QString getName(const QString &line){ int curIdx = 0; char space = ' '; QString name = line.simplified(); curIdx = name.indexOf(space); if(-1== curIdx){ return ""; } name = name.mid(curIdx+1); curIdx = name.indexOf(space); if(-1== curIdx){ return ""; } name = name.mid(0,curIdx); return name; } static bool checkSeq(const QByteArray &seq){ for(int i =0; i &objects, U2::TaskStateInfo &ti) { QByteArray readBuff(READ_BUFF_SIZE+1, 0); char* buff = readBuff.data(); qint64 len = 0; int count = 0; char aceHeaderStartChar = 'C'; QBitArray aceHeaderStart = TextUtils::createBitMap(aceHeaderStartChar); char aceReadStartChar = 'R'; QBitArray aceReadStart = TextUtils::createBitMap(aceReadStartChar); char aceBStartChar = 'B'; QBitArray aceBStart = TextUtils::createBitMap(aceBStartChar); char aceQStartChar = 'Q'; QBitArray aceQStart = TextUtils::createBitMap(aceQStartChar); QByteArray sequence; QSet names; QMap< QString, int> posMap; QMap< QString, bool> complMap; //skip leading whites if present bool lineOk = true; len = io->readUntil(buff, READ_BUFF_SIZE, TextUtils::LINE_BREAKS, IOAdapter::Term_Include, &lineOk); if (len == 0) { //end if stream return ; } if (!lineOk) { ti.setError(ACEFormat::tr("Line is too long")); return ; } QString headerLine = QString(QByteArray::fromRawData(buff, len)).trimmed(); if (!headerLine.startsWith(AS)) { ti.setError(ACEFormat::tr("First line is not an ace header")); return ; } int contigC = contigCount(headerLine); if(-1==contigC){ ti.setError(ACEFormat::tr("No contig count tag in the header line")); return ; } for(int i =0; i < contigC; i++){ if(i==0){ QBitArray nonWhites = ~TextUtils::WHITES; io->readUntil(buff, READ_BUFF_SIZE, nonWhites, IOAdapter::Term_Exclude, &lineOk); //read header len = io->readUntil(buff, READ_BUFF_SIZE, TextUtils::LINE_BREAKS, IOAdapter::Term_Include, &lineOk); if (len == 0) { //end if stream return ; } if (!lineOk) { ti.setError(ACEFormat::tr("Line is too long")); return ; } headerLine = QString(QByteArray::fromRawData(buff, len)).trimmed(); if (!headerLine.startsWith(CO)) { ti.setError(ACEFormat::tr("Must be CO keyword")); return ; } }else{ do{ len = io->readUntil(buff, READ_BUFF_SIZE, TextUtils::LINE_BREAKS, IOAdapter::Term_Include, &lineOk); if (len == 0) { //end if stream ti.setError(ACEFormat::tr("Unexpected end of file")); return ; } if (!lineOk) { ti.setError(ACEFormat::tr("Line is too long")); return ; } headerLine = QString(QByteArray::fromRawData(buff, len)).trimmed(); }while (!headerLine.startsWith(CO)); } count = readsCount(headerLine); if(-1 == count){ ti.setError(ACEFormat::tr("There is no note about reads count")); return ; } QString readLine; QString name; QByteArray consensus; //consensus QString consName = getName(headerLine); if("" == consName){ ti.setError(ACEFormat::tr("There is no AF note")); return ; } if (names.contains(consName)) { ti.setError(ACEFormat::tr("A name is duplicated")); return ; } names.insert(consName); consensus.clear(); do { len = io->readUntil(buff, READ_BUFF_SIZE, aceBStart, IOAdapter::Term_Exclude, &lineOk); if (len <= 0) { ti.setError(ACEFormat::tr("No consensus")); return ; } len = TextUtils::remove(buff, len, TextUtils::WHITES); buff[len] = 0; consensus.append(buff); ti.progress = io->getProgress(); } while (!ti.cancelFlag && !lineOk); len = io->readUntil(buff, READ_BUFF_SIZE, TextUtils::LINE_BREAKS, IOAdapter::Term_Include, &lineOk); readLine = QString(QByteArray::fromRawData(buff, len)).trimmed(); if(!readLine.startsWith(BQ)){ ti.setError(ACEFormat::tr("BQ keyword hasn't been found")); return ; } consensus=consensus.toUpper(); if(!checkSeq(consensus)){ ti.setError(ACEFormat::tr("Bad consensus data")); return ; } consensus.replace('*',MAlignment_GapChar); MAlignment al(consName); al.addRow(MAlignmentRow(consName, consensus)); //AF int count1 = count; int readPos = 0; int complStrand = 0; int paddedStart = 0; while (!ti.cancelFlag && count1>0) { do{ len = io->readUntil(buff, READ_BUFF_SIZE, TextUtils::LINE_BREAKS, IOAdapter::Term_Include, &lineOk); if (len == 0) { //end if stream ti.setError(ACEFormat::tr("Unexpected end of file")); return ; } if (!lineOk) { ti.setError(ACEFormat::tr("Line is too long")); return ; } readLine = QString(QByteArray::fromRawData(buff, len)).trimmed(); }while (!readLine.startsWith(AF)); name = getName(readLine); if(!readLine.startsWith(AF) || "" == name){ ti.setError(ACEFormat::tr("There is no AF note")); return ; } readPos = readsPos(readLine); complStrand = readsComplement(readLine); if((INT_MAX == readPos) || (-1 == complStrand) ){ ti.setError(ACEFormat::tr("Bad AF note")); return ; } paddedStart = paddedStartCons(readLine); if(INT_MAX == paddedStart){ ti.setError(ACEFormat::tr("Bad AF note")); return ; } posMap.insert(name,paddedStart); if (names.contains(name)) { ti.setError(ACEFormat::tr("A name is duplicated")); return ; } bool cur_compl = (complStrand == 1); complMap.insert(name,cur_compl); names.insert(name); count1--; ti.progress = io->getProgress(); } //RD while (!ti.cancelFlag && count>0) { do{ len = io->readUntil(buff, READ_BUFF_SIZE, TextUtils::LINE_BREAKS, IOAdapter::Term_Include, &lineOk); if (len == 0) { //end if stream ti.setError(ACEFormat::tr("Unexpected end of file")); return ; } if (!lineOk) { ti.setError(ACEFormat::tr("Line is too long")); return ; } readLine = QString(QByteArray::fromRawData(buff, len)).trimmed(); }while (!readLine.startsWith(RD)); name = getName(readLine); if(!readLine.startsWith(RD) || "" == name){ ti.setError(ACEFormat::tr("There is no read note")); return ; } sequence.clear(); do { len = io->readUntil(buff, READ_BUFF_SIZE, aceQStart, IOAdapter::Term_Exclude, &lineOk); if (len <= 0) { ti.setError(ACEFormat::tr("No sequence")); return ; } len = TextUtils::remove(buff, len, TextUtils::WHITES); buff[len] = 0; sequence.append(buff); ti.progress = io->getProgress(); } while (!ti.cancelFlag && !lineOk); len = io->readUntil(buff, READ_BUFF_SIZE, TextUtils::LINE_BREAKS, IOAdapter::Term_Include, &lineOk); readLine = QString(QByteArray::fromRawData(buff, len)).trimmed(); if(!readLine.startsWith(QA)){ ti.setError(ACEFormat::tr("QA keyword hasn't been found")); return ; } int clearRangeStart = 0; int clearRangeEnd = 0; clearRangeStart = readsCount(readLine); if(-1==clearRangeStart){ ti.setError(ACEFormat::tr("QA error no clear range")); return ; } clearRangeEnd = clearRange(readLine); if(0==clearRangeEnd){ ti.setError(ACEFormat::tr("QA error no clear range")); return ; } len = sequence.length(); if(clearRangeStart > clearRangeEnd || clearRangeEnd > len){ ti.setError(ACEFormat::tr("QA error bad range")); return ; } sequence=sequence.toUpper(); if(!checkSeq(sequence)){ ti.setError(ACEFormat::tr("Bad sequence data")); return ; } if (!names.contains(name)) { ti.setError(ACEFormat::tr("A name is not match with AF names")); return ; }else{ names.remove(name); } sequence.replace('*',MAlignment_GapChar); sequence.replace('N',MAlignment_GapChar); sequence.replace('X',MAlignment_GapChar); bool isComplement = complMap.take(name); int pos = posMap.value(name) - 1; QString rowName(name); if(true == isComplement){ rowName.append("(rev-compl)"); } MAlignmentRow row; row.setName(rowName); row.setSequence(sequence, pos); al.addRow(row); count--; ti.progress = io->getProgress(); } DocumentFormatUtils::assignAlphabet(al); if (al.getAlphabet() == NULL) { ti.setError( ACEFormat::tr("Alphabet unknown")); return; } MAlignmentObject* obj = new MAlignmentObject(al); objects.append(obj); } } RawDataCheckResult ACEFormat::checkRawData(const QByteArray& rawData, const GUrl&) const { static const char* formatTag = "AS"; if (!rawData.startsWith(formatTag)) { return FormatDetection_NotMatched; } return FormatDetection_AverageSimilarity; } Document* ACEFormat::loadDocument(IOAdapter* io, TaskStateInfo& ti, const QVariantMap& fs, DocumentLoadMode) { QList objs; load(io, objs, ti); if (ti.hasError()) { qDeleteAll(objs); return NULL; } Document *doc = new Document(this, io->getFactory(), io->getURL(), objs, fs); return doc; } } //namespace ugene-1.9.8/src/corelibs/U2Formats/src/StdResidueDictionary.h0000644000175000017500000000434111651544332022574 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_STD_RESIDUE_DICTIONARY_H_ #define _U2_STD_RESIDUE_DICTIONARY_H_ #include #include #include namespace U2 { class AsnNode; enum ResidueType { DEOXYRIBONUCLEOTIDE, RIBONUCLEOTIDE, AMINO_ACID, OTHER = 255 }; struct StdBond { int atom1Id; int atom2Id; }; struct StdAtom { QByteArray name; int atomicNum; }; struct StdResidue { QByteArray name; ResidueType type; char code; QHash atoms; QList bonds; }; class StdResidueDictionary { QHash residues; bool load(const QString& fileName); void buildDictionaryFromAsnTree(AsnNode* rootElem); bool validate() const; static QMutex standardDictionaryLock; static std::auto_ptr standardDictionary; public: ~StdResidueDictionary(); static StdResidueDictionary* createStandardDictionary(); static StdResidueDictionary* createFromAsnTree(AsnNode* rootElem); //TODO : move this method to AppContext static const StdResidueDictionary* getStandardDictionary(); static ResidueType getResidueTypeByName(const QByteArray& name); const StdResidue getResidueById(int id) const; }; } // namespace #endif // _U2_STD_RESIDUE_DICTIONARY_H_ ugene-1.9.8/src/corelibs/U2Formats/src/RawDNASequenceFormat.cpp0000644000175000017500000001000011651544332022731 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "RawDNASequenceFormat.h" #include "DocumentFormatUtils.h" #include "PlainTextFormat.h" #include #include #include #include #include namespace U2 { /* TRANSLATOR U2::RawDNASequenceFormat */ /* TRANSLATOR U2::IOAdapter */ RawDNASequenceFormat::RawDNASequenceFormat(QObject* p) : DocumentFormat(p, DocumentFormatFlags_W1) { formatName = tr("Raw sequence"); fileExtensions << "seq" << "txt"; supportedObjectTypes+=GObjectTypes::SEQUENCE; formatDescription = tr("Raw sequence file - a whole content of the file is treated either as a single nucleotide or peptide sequence UGENE will remove all non-alphabetic chars from the result sequence"); } static void load(IOAdapter* io, QList& objects, const QVariantMap& hints, TaskStateInfo& ti) { static int READ_BUFF_SIZE = 4096; QByteArray readBuffer(READ_BUFF_SIZE, '\0'); char* buff = readBuffer.data(); int wholeSize = io->left(); const QBitArray& ALPHAS = TextUtils::ALPHA_NUMS; QByteArray seq; if (wholeSize != -1) { seq.reserve(wholeSize); } //reading sequence QBuffer writer(&seq); writer.open( QIODevice::WriteOnly | QIODevice::Append ); bool ok = true; int len = 0; while (ok && (len = io->readBlock(buff, READ_BUFF_SIZE)) > 0) { if (ti.cancelFlag) { break; } for (int i=0; igetProgress(); } writer.close(); if (ti.hasError()) { return; } if (seq.size() == 0) { ti.setError(RawDNASequenceFormat::tr("Sequence is empty")); return; } DNASequence dnaseq(seq); DocumentFormatUtils::addSequenceObject(objects, "Sequence", dnaseq, hints, ti); } Document* RawDNASequenceFormat::loadDocument(IOAdapter* io, TaskStateInfo& ti, const QVariantMap& fs, DocumentLoadMode) { QList objects; load(io, objects, fs, ti); if (ti.hasError()) { return NULL; } Document* doc = new Document(this, io->getFactory(), io->getURL(), objects, fs); return doc; } RawDataCheckResult RawDNASequenceFormat::checkRawData(const QByteArray& rawData, const GUrl&) const { const char* data = rawData.constData(); int size = rawData.size(); if(QRegExp("[a-zA-Z\r\n]*").exactMatch(rawData)) { return FormatDetection_VeryHighSimilarity; } bool hasBinaryData = TextUtils::contains(TextUtils::BINARY, data, size); //returning 'very low chance' here just because it's impossible to have 100% detection for this format return hasBinaryData ? FormatDetection_NotMatched : FormatDetection_VeryLowSimilarity; } void RawDNASequenceFormat::storeDocument( Document* d, TaskStateInfo& ts, IOAdapter* io) { assert(d->getObjects().size() ==1); GObject* obj = d->getObjects().first(); DNASequenceObject* so = qobject_cast(obj); assert(so!=NULL); PlainTextFormat::storeRawData(so->getDNASequence().seq, ts, io); } }//namespace ugene-1.9.8/src/corelibs/U2Formats/src/SCFFormat.h0000644000175000017500000000356711651544332020270 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_SCF_FORMAT_H_ #define _U2_SCF_FORMAT_H_ #include #include namespace U2 { class IOAdapter; class SeekableBuf; class DNAChromatogram; class DNASequence; class U2OpStatus; class U2FORMATS_EXPORT SCFFormat : public DocumentFormat { Q_OBJECT public: SCFFormat(QObject* p); virtual DocumentFormatId getFormatId() const {return BaseDocumentFormats::SCF;} virtual const QString& getFormatName() const {return formatName;} virtual Document* loadDocument(IOAdapter* io, TaskStateInfo& ti, const QVariantMap& fs, DocumentLoadMode mode = DocumentLoadMode_Whole); virtual RawDataCheckResult checkRawData(const QByteArray& rawData, const GUrl& = GUrl()) const; static void exportDocumentToSCF(const QString& fileName, const DNAChromatogram& cd, const DNASequence& dna, TaskStateInfo& ts); private: Document* parseSCF(SeekableBuf*, IOAdapterFactory* io, const GUrl& url, const QVariantMap& fs, U2OpStatus& os); QString formatName; }; }//namespace #endif ugene-1.9.8/src/corelibs/U2Formats/src/StockholmFormat.h0000644000175000017500000000545311651544332021614 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_STOCKHOLM_FORMAT_H_ #define _U2_STOCKHOLM_FORMAT_H_ #include #include #include namespace U2 { class IOAdapter; class U2FORMATS_EXPORT StockholmFormat : public DocumentFormat { Q_OBJECT public: static const QByteArray FILE_ANNOTATION_ID; static const QByteArray FILE_ANNOTATION_AC; static const QByteArray FILE_ANNOTATION_DE; static const QByteArray FILE_ANNOTATION_GA; static const QByteArray FILE_ANNOTATION_NC; static const QByteArray FILE_ANNOTATION_TC; static const QByteArray COLUMN_ANNOTATION_SS_CONS; static const QByteArray COLUMN_ANNOTATION_RF; static const QByteArray UNI_ANNOTATION_MARK; private: QString format_name; public: StockholmFormat( QObject* obj ); virtual DocumentFormatId getFormatId() const { return BaseDocumentFormats::STOCKHOLM; } virtual const QString& getFormatName() const { return format_name; } virtual Document* loadDocument(IOAdapter* io, TaskStateInfo& ti, const QVariantMap& fs, DocumentLoadMode mode = DocumentLoadMode_Whole); virtual void storeDocument( Document* doc, TaskStateInfo& ti, IOAdapter* io ); virtual RawDataCheckResult checkRawData(const QByteArray& data, const GUrl& = GUrl()) const; virtual bool isObjectOpSupported( const Document* d , DocumentFormat::DocObjectOp op, GObjectType t ) const; //exceptions struct StockholmBaseException { QString msg; StockholmBaseException( const QString& str ): msg( str ){} }; struct ReadError : public StockholmBaseException { ReadError(const GUrl& url); }; struct WriteError: public StockholmBaseException { WriteError(const GUrl& url); }; struct BadFileData : public StockholmBaseException { BadFileData( const QString& msg ): StockholmBaseException( msg ){} }; }; // StockholmFormat } // namespace #endif //_U2_STOCKHOLM_FORMAT_H_ ugene-1.9.8/src/corelibs/U2Formats/src/DocumentFormatUtils.cpp0000644000175000017500000002700111651544332022774 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "DocumentFormatUtils.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include namespace U2 { DNAAlphabet* DocumentFormatUtils::findAlphabet(const QByteArray& arr) { DNAAlphabetRegistry* r = AppContext::getDNAAlphabetRegistry(); return r->findAlphabet(arr); } DNAAlphabet* DocumentFormatUtils::findAlphabet(const QByteArray& arr, const QVector& regionsToProcess) { DNAAlphabetRegistry* r = AppContext::getDNAAlphabetRegistry(); QList als = r->findAlphabets(arr, regionsToProcess, true); assert(!als.empty()); return als.first(); } QList DocumentFormatUtils::findAlphabets(const QByteArray& arr) { DNAAlphabetRegistry* r = AppContext::getDNAAlphabetRegistry(); QList als = r->findAlphabets(arr); return als; } DNASequenceObject* DocumentFormatUtils::addSequenceObject(QList& objects, const QString& name, DNASequence& seq, const QVariantMap& hints, U2OpStatus& os) { if (hints.contains(DocumentReadingMode_MaxObjectsInDoc) && !hints.value(DocumentReadingMode_SequenceAsAlignmentHint).toBool()) { int n = hints.value(DocumentReadingMode_MaxObjectsInDoc).toInt(); if (n > 0 && n <= objects.size()) { os.setError(tr("Maximum number of objects per document limit reached. Try different options for opening the document!")); return NULL; } } if (seq.alphabet== NULL) { seq.alphabet = findAlphabet(seq.seq); if (seq.alphabet == NULL) { os.setError(tr("Undefined sequence alphabet")); return NULL; } } if (!seq.alphabet->isCaseSensitive()) { TextUtils::translate(TextUtils::UPPER_CASE_MAP, const_cast(seq.seq.constData()), seq.seq.length()); } trySqueeze(seq.seq); DNASequenceObject* so = new DNASequenceObject(name, seq); objects.append(so); return so; } DNASequenceObject* DocumentFormatUtils::addMergedSequenceObject(QList& objects, const GUrl& docUrl, const QStringList& contigNames, QByteArray& mergedSequence, const QVector& mergedMapping, const QVariantMap& hints, U2OpStatus& os) { if (contigNames.size() == 1) { DNAAlphabet* al = findAlphabet(mergedSequence); const QString& name = contigNames.first(); DNASequence seq( mergedSequence, al ); return DocumentFormatUtils::addSequenceObject(objects, name, seq, hints, os); } assert(contigNames.size() >=2); assert(contigNames.size() == mergedMapping.size()); DNAAlphabet* al = findAlphabet(mergedSequence, mergedMapping); char defSym = al->getDefaultSymbol(); //fill gaps with defSym for (int i = 1; i < mergedMapping.size(); i++) { const U2Region& prev = mergedMapping[i-1]; const U2Region& next = mergedMapping[i]; int gapSize = next.startPos - prev.endPos(); assert(gapSize >= 0); if (gapSize > 0) { qMemSet(mergedSequence.data() + prev.endPos(), defSym, (size_t)gapSize); } } DNASequence seq( mergedSequence, al ); DNASequenceObject* so = addSequenceObject(objects, "Sequence", seq, hints, os); if(os.hasError()) { return NULL; } SAFE_POINT(so != NULL, "DocumentFormatUtils::addSequenceObject returned NULL but didn't set error", NULL); AnnotationTableObject* ao = new AnnotationTableObject("Contigs"); //save relation if docUrl is not empty if (!docUrl.isEmpty()) { GObjectReference r(docUrl.getURLString(), so->getGObjectName(), GObjectTypes::SEQUENCE); ao->addObjectRelation(GObjectRelation(r, GObjectRelationRole::SEQUENCE)); } //save mapping info as annotations for (int i = 0; i < contigNames.size(); i++) { SharedAnnotationData d(new AnnotationData()); d->name = "contig"; d->location->regions << mergedMapping[i]; ao->addAnnotation(new Annotation(d), NULL); } objects.append(ao); return so; } #define MAX_REALLOC_SIZE (300*1000*1000) #define MIN_K_TO_REALLOC 1.07 void DocumentFormatUtils::trySqueeze(QByteArray& a) { //squeeze can cause 2x memory usage -> avoid squeezing of large arrays float k = float(a.capacity()) / a.size(); if (a.size() <= MAX_REALLOC_SIZE && k > MIN_K_TO_REALLOC) { a.squeeze(); } } int DocumentFormatUtils::getIntSettings(const QVariantMap& fs, const char* sName, int defVal) { QVariant v = fs.value(sName); if (v.type()!= QVariant::Int) { return defVal; } return v.toInt(); } void DocumentFormatUtils::updateFormatSettings(QList& objects, QVariantMap& fs) { //1. remove all cached sequence sizes //2. add new sizes QList sequences; foreach(GObject* obj, objects) { if (obj->getGObjectType() == GObjectTypes::SEQUENCE) { sequences.append(obj); } } if (sequences.size() == 1) { DNASequenceObject* so = qobject_cast(sequences.first()); int len = so->getSequence().length(); fs[DocumentReadingMode_SequenceMergingFinalSizeHint] = len; } } class ExtComparator { public: ExtComparator(const QString& _ext) : ext(_ext) {} bool operator()(const DocumentFormat* f1, const DocumentFormat* f2) const { int v1 = f1->getSupportedDocumentFileExtensions().contains(ext) ? 1 : 0; int v2 = f2->getSupportedDocumentFileExtensions().contains(ext) ? 1 : 0; return v2 < v1; // reverse sort -> make higher vals on the top } QString ext; }; QList DocumentFormatUtils::toIds(const QList& formats) { QList result; foreach(DocumentFormat* f, formats) { result.append(f->getFormatId()); } return result; } void DocumentFormatUtils::assignAlphabet(MAlignment& ma) { QList matchedAlphabets; for (int i=0, n = ma.getNumRows();i als = DocumentFormatUtils::findAlphabets(item.getCore()); if (i == 0) { matchedAlphabets = als; } else { QMutableListIterator it(matchedAlphabets); while (it.hasNext()) { DNAAlphabet* al = it.next(); if (!als.contains(al)) { it.remove(); } } if (matchedAlphabets.isEmpty()) { break; } } } if (matchedAlphabets.isEmpty()) { return; //nothing matched } ma.setAlphabet(matchedAlphabets.first()); if (!ma.getAlphabet()->isCaseSensitive()) { ma.toUpperCase(); } } void DocumentFormatUtils::assignAlphabet(MAlignment& ma, char ignore) { QList matchedAlphabets; for (int i=0, n = ma.getNumRows();i als = DocumentFormatUtils::findAlphabets(core); if (i == 0) { matchedAlphabets = als; } else { QMutableListIterator it(matchedAlphabets); while (it.hasNext()) { DNAAlphabet* al = it.next(); if (!als.contains(al)) { it.remove(); } } if (matchedAlphabets.isEmpty()) { break; } } } if (matchedAlphabets.isEmpty()) { return; //nothing matched } ma.setAlphabet(matchedAlphabets.first()); if (!ma.getAlphabet()->isCaseSensitive()) { ma.toUpperCase(); } } QList DocumentFormatUtils::predefinedSettings() { QList predefined; foreach(GBFeatureKeyInfo fi, GBFeatureUtils::allKeys()) { AnnotationSettings* as = new AnnotationSettings(); as->name = fi.text; as->amino = fi.showOnaminoFrame; as->color = fi.color; as->visible = as->name!="source"; as->nameQuals = fi.namingQuals; predefined.append(as); } AnnotationSettings* secStructAnnotationSettings = new AnnotationSettings(BioStruct3D::SecStructAnnotationTag, true, QColor(102,255, 0), true); secStructAnnotationSettings->nameQuals.append(BioStruct3D::SecStructTypeQualifierName); predefined.append(secStructAnnotationSettings); predefined.append(new AnnotationSettings(BioStruct3D::AlphaHelixAnnotationTag, true, QColor(102,255, 0), true)); predefined.append(new AnnotationSettings(BioStruct3D::BetaStrandAnnotationTag, true, QColor(255,255,153), true)); predefined.append(new AnnotationSettings(BioStruct3D::TurnAnnotationTag, true, QColor(255,85,127), true)); predefined.append(new AnnotationSettings(BioStruct3D::MoleculeAnnotationTag, false, QColor(0,255,0), false)); return predefined; } QList DocumentFormatUtils::toSequences(const GObject* obj) { QList res; const DNASequenceObject* seqObj = qobject_cast(obj); if (seqObj != NULL) { res << seqObj->getDNASequence(); return res; } const MAlignmentObject* maObj = qobject_cast(obj); DNAAlphabet* al = maObj->getMAlignment().getAlphabet(); foreach(const MAlignmentRow& row, maObj->getMAlignment().getRows()) { DNASequence seq; seq.seq = row.toByteArray(row.getCoreEnd()); seq.setName(row.getName()); seq.alphabet = al; res << seq; } return res; } // This property is replaced with (DocumentReadingMode_SequenceMergeGapSize "merge-gap") today // we keep this property for compatibility with previous version of UGENE only #define MERGE_MULTI_DOC_GAP_SIZE_SETTINGS_DEPRECATED "merge_gap" int DocumentFormatUtils::getMergeGap(const QVariantMap& hints) { int res = getIntSettings(hints, DocumentReadingMode_SequenceMergeGapSize, -1); if (res == -1) { res = getIntSettings(hints, MERGE_MULTI_DOC_GAP_SIZE_SETTINGS_DEPRECATED, -1); } return res; } } //namespace ugene-1.9.8/src/corelibs/U2Formats/src/ASNFormat.cpp0000644000175000017500000006641011651544332020625 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "DocumentFormatUtils.h" #include "ASNFormat.h" #include "PDBFormat.h" #include "StdResidueDictionary.h" /* TRANSLATOR U2::ASNFormat */ namespace U2 { ASNFormat::ASNFormat( QObject* p ) : DocumentFormat(p, DocumentFormatFlag(0), QStringList() << "prt") { formatName = tr("MMDB"); supportedObjectTypes+=GObjectTypes::BIOSTRUCTURE_3D; supportedObjectTypes+=GObjectTypes::SEQUENCE; supportedObjectTypes+=GObjectTypes::ANNOTATION_TABLE; } RawDataCheckResult ASNFormat::checkRawData(const QByteArray& rawData, const GUrl&) const { static const char* formatTag = "Ncbi-mime-asn1 ::= strucseq"; if (!rawData.startsWith(formatTag)) { return FormatDetection_NotMatched; } bool textOnly = !TextUtils::contains(TextUtils::BINARY, rawData.constData(), rawData.size()); return textOnly ? FormatDetection_VeryHighSimilarity : FormatDetection_NotMatched; } Document* ASNFormat::loadDocument(IOAdapter* io, TaskStateInfo& ti, const QVariantMap& fs, DocumentLoadMode) { BioStruct3D bioStruct; const StdResidueDictionary* stdResidueDict = StdResidueDictionary::getStandardDictionary(); if (stdResidueDict == NULL) { ti.setError(tr("Standard residue dictionary not found")); return NULL; } AsnParser asnParser(io, ti); ioLog.trace("ASN: Parsing: " +io->toString()); std::auto_ptr rootElem(asnParser.loadAsnTree()); ioLog.trace(QString("ASN tree for %1 was built").arg(io->toString())); ti.progress = 30; if (rootElem.get() != NULL) { BioStructLoader ldr; ldr.setStandardDictionary( stdResidueDict ); ldr.loadBioStructFromAsnTree(rootElem.get(), bioStruct, ti); } ti.progress = 80; if (ti.hasError() || ti.cancelFlag) { return NULL; } ioLog.trace(QString("BioStruct3D loaded from ASN tree (%1)").arg(io->toString())); bioStruct.calcCenterAndMaxDistance(); bioStruct.generateAnnotations(); ti.progress = 90; Document* doc = PDBFormat::createDocumentFromBioStruct3D(bioStruct, this, io->getFactory(), io->toString(), ti, fs); ioLog.trace("ASN Parsing finished: " + io->toString()); ti.progress = 100; return doc; } AsnNode* ASNFormat::findFirstNodeByName(AsnNode* rootElem, const QString& nodeName ) { if (rootElem->name == nodeName) { return rootElem; } foreach (AsnNode* node, rootElem->children) { AsnNode* child = findFirstNodeByName(node, nodeName); if (child != NULL) { return child; } } return NULL; } AsnNodeList ASNFormat::findNodesByName( AsnNode* root, const QString& nodeName, AsnNodeList& nodes /*= AsnNodeList()*/ ) { if (root->name == nodeName) { nodes.append(root); } foreach (AsnNode* child, root->children) { findNodesByName(child, nodeName, nodes); } return nodes; } QString ASNFormat::getAsnNodeTypeName( const AsnNode* node ) { switch(node->kind) { case ASN_NO_KIND: return QString("ASN_NO_KIND"); case ASN_ROOT: return QString("ASN_ROOT"); case ASN_SEQ: return QString("ASN_SEQ"); case ASN_VALUE: return QString("ASN_VALUE"); default: Q_ASSERT(0); } return QString(""); } void ASNFormat::BioStructLoader::loadBioStructPdbId( AsnNode* rootNode, BioStruct3D& struc) { AsnNode* nameNode = ASNFormat::findFirstNodeByName(rootNode, "name"); Q_ASSERT(nameNode != NULL); struc.pdbId = nameNode->value; } void ASNFormat::BioStructLoader::loadBioStructFromAsnTree( AsnNode* rootNode, BioStruct3D& struc, TaskStateInfo& ti ) { /* id SEQUENCE OF Biostruc-id, descr SEQUENCE OF Biostruc-descr OPTIONAL, chemical-graph Biostruc-graph, features SEQUENCE OF Biostruc-feature-set OPTIONAL, model SEQUENCE OF Biostruc-model OPTIONAL } */ try { localDictionary.reset(StdResidueDictionary::createFromAsnTree(rootNode)); // Load pdb Id loadBioStructPdbId(rootNode, struc); //Load biostruct molecules AsnNode* graphNode = findFirstNodeByName(rootNode, "chemical-graph"); if (graphNode == NULL ) { throw AsnBioStructError("models not found"); } loadBioStructGraph(graphNode, struc); //Load secondary structure AsnNode* featureSetNode = findFirstNodeByName(rootNode, "features"); if (featureSetNode != NULL ) { loadBioStructSecondaryStruct(featureSetNode, struc); } // Load biostruct models (coordinates) AsnNode* modelsNode = findFirstNodeByName(rootNode, "model"); if (modelsNode == NULL ) { throw AsnBioStructError("models not found"); } loadBioStructModels(modelsNode->children, struc); //TODO: implement loading bonds from file //loadIntraResidueBonds(struc); PDBFormat::calculateBonds(struc); stdResidueCache.clear(); atomSetCache.clear(); } catch ( const AsnBaseException& ex ) { ti.setError(ex.msg); return; } catch( ... ) { ti.setError(ASNFormat::tr("Unknown error occurred")); return; } } inline quint64 calcStdResidueIndex(int chainId, int resId) { return ( ((quint64) chainId << 32) | (quint64) resId ); } void ASNFormat::BioStructLoader::loadModelCoordsFromNode( AsnNode* modelNode, AtomCoordSet& coordSet, QMap& molModels, const BioStruct3D& struc) { /* Atomic-coordinates ::= SEQUENCE { number-of-points INTEGER, atoms Atom-pntrs, sites Model-space-points, temperature-factors Atomic-temperature-factors OPTIONAL, occupancies Atomic-occupancies OPTIONAL, alternate-conf-ids Alternate-conformation-ids OPTIONAL, conf-ensembles SEQUENCE OF Conformation-ensemble OPTIONAL } Model-space-points ::= SEQUENCE { scale-factor INTEGER, x SEQUENCE OF INTEGER, y SEQUENCE OF INTEGER, z SEQUENCE OF INTEGER } Atom-pntrs ::= SEQUENCE { number-of-ptrs INTEGER, molecule-ids SEQUENCE OF Molecule-id, residue-ids SEQUENCE OF Residue-id, atom-ids SEQUENCE OF Atom-id } */ AsnNode* aCoordsNode = modelNode->findChildByName("coordinates literal atomic"); bool ok = false; AsnNode* numAtomsNode = aCoordsNode->getChildById(0); int numAtoms = numAtomsNode->value.toInt(&ok); Q_ASSERT(ok == true); AsnNode* atomPntrsNode = aCoordsNode->getChildById(1); Q_ASSERT(atomPntrsNode->name == "atoms"); AsnNode* chainIds = atomPntrsNode->getChildById(1); AsnNode* resIds = atomPntrsNode->getChildById(2); AsnNode* atomIds = atomPntrsNode->getChildById(3); AsnNode* sitesNode = aCoordsNode->getChildById(2); Q_ASSERT(sitesNode->name == "sites"); AsnNode* sfNode = sitesNode->getChildById(0); AsnNode* xCoords = sitesNode->getChildById(1); AsnNode* yCoords = sitesNode->getChildById(2); AsnNode* zCoords = sitesNode->getChildById(3); int scaleFactor = sfNode->value.toInt(); for (int i = 0; i < numAtoms; ++i) { int chainId = chainIds->children.at(i)->value.toInt(); int resId = resIds->children.at(i)->value.toInt(); int atomId = atomIds->children.at(i)->value.toInt(); float x = (float) xCoords->children.at(i)->value.toInt() / scaleFactor; float y = (float) yCoords->children.at(i)->value.toInt() / scaleFactor; float z = (float) zCoords->children.at(i)->value.toInt() / scaleFactor; AtomData* a = new AtomData(); a->chainIndex = chainId; a->residueIndex = ResidueIndex(resId, ' '); a->coord3d = Vector3D(x,y,z); quint64 index = calcStdResidueIndex(chainId, resId); if (stdResidueCache.contains(index)) { StdResidue stdResidue = stdResidueCache.value(index); const StdAtom stdAtom = stdResidue.atoms.value(atomId); a->atomicNumber = stdAtom.atomicNum; a->name = stdAtom.name; //TODO: add this //a->occupancy = occupancy; //a->temperature = temperature; } SharedAtom atom(a); coordSet.insert(i + 1, atom); if (struc.moleculeMap.contains(chainId)) { molModels[chainId].atoms.append(atom); } //atomSetCache[index].insert(atomId, atom); } } const StdResidue ASNFormat::BioStructLoader::loadResidueFromNode(AsnNode* resNode, ResidueData* residue) { /* Residue ::= SEQUENCE { id Residue-id, name VisibleString OPTIONAL, residue-graph Residue-graph-pntr } Residue-graph-pntr ::= CHOICE { local Residue-graph-id, biostruc Biostruc-graph-pntr, standard Biostruc-residue-graph-set-pntr } Biostruc-residue-graph-set-pntr ::= SEQUENCE { biostruc-residue-graph-set-id Biostruc-id, residue-graph-id Residue-graph-id } */ AsnNode* resGraphPntrNode = resNode->getChildById(2); const StdResidueDictionary* dictionary = NULL; int stdResidueId = 0; bool ok = false; if ( (resGraphPntrNode->kind == ASN_VALUE) && (resGraphPntrNode->value.contains("local")) ) { dictionary = localDictionary.get(); stdResidueId = resGraphPntrNode->value.split(' ').at(1).toInt(&ok); } else if (resGraphPntrNode->name.contains("standard")) { dictionary = standardDictionary; stdResidueId = resGraphPntrNode->getChildById(1)->value.toInt(&ok); } else { Q_ASSERT(0); } Q_ASSERT(ok == true); const StdResidue stdResidue = dictionary->getResidueById(stdResidueId); residue->name = stdResidue.name; residue->acronym = stdResidue.code; return stdResidue; } void ASNFormat::BioStructLoader::loadMoleculeFromNode(AsnNode* moleculeNode, MoleculeData* molecule) { /* Molecule-graph ::= SEQUENCE { id Molecule-id, descr SEQUENCE OF Biomol-descr OPTIONAL, seq-id Seq-id OPTIONAL, residue-sequence SEQUENCE OF Residue, inter-residue-bonds SEQUENCE OF Inter-residue-bond OPTIONAL, sid PCSubstance-id OPTIONAL } Residue ::= SEQUENCE { id Residue-id, ... } */ int chainId = moleculeNode->getChildById(0)->value.toInt(); AsnNode* resideusNode = moleculeNode->findChildByName("residue-sequence"); foreach (AsnNode* resNode, resideusNode->children) { // Load residue id AsnNode* idNode = resNode->getChildById(0); int resId = idNode->value.toInt(); // Load residue ResidueData* resData = new ResidueData(); resData->chainIndex = chainId; StdResidue stdResidue = loadResidueFromNode(resNode, resData); molecule->residueMap.insert( ResidueIndex(resId, ' '), SharedResidue(resData)); stdResidueCache.insert(calcStdResidueIndex(chainId, resId), stdResidue); } } void ASNFormat::BioStructLoader::loadBioStructModels( QList modelNodes, BioStruct3D& struc) { /* Biostruc-model ::= SEQUENCE { id Model-id, type Model-type, descr SEQUENCE OF Model-descr OPTIONAL, model-space Model-space OPTIONAL, model-coordinates SEQUENCE OF Model-coordinate-set OPTIONAL } */ Q_ASSERT(modelNodes.count() != 0); foreach (AsnNode* modelNode, modelNodes) { // Load model id AsnNode* idNode = modelNode->getChildById(0); int modelId = idNode->value.toInt(); // Load model AtomCoordSet atomCoords; AsnNode* modelCoordsNode = modelNode->findChildByName("model-coordinates"); QMap molModels; loadModelCoordsFromNode(modelCoordsNode->getChildById(0), atomCoords, molModels, struc); struc.modelMap.insert(modelId, atomCoords); foreach (int chainId, struc.moleculeMap.keys()) { Q_ASSERT(molModels.contains(chainId)); struc.moleculeMap[chainId]->models.append(molModels.value(chainId)); } } } void ASNFormat::BioStructLoader::loadBioStructGraph( AsnNode* graphNode, BioStruct3D& struc ) { /* Biostruc-graph ::= SEQUENCE { descr SEQUENCE OF Biomol-descr OPTIONAL, molecule-graphs SEQUENCE OF Molecule-graph, inter-molecule-bonds SEQUENCE OF Inter-residue-bond OPTIONAL, residue-graphs SEQUENCE OF Residue-graph OPTIONAL } Molecule-graph ::= SEQUENCE { id Molecule-id, descr SEQUENCE OF Biomol-descr OPTIONAL, ... Biomol-descr ::= CHOICE { name VisibleString, molecule-type INTEGER { dna(1), rna(2), protein(3), other-biopolymer(4), solvent(5), other-nonpolymer(6), other(255) } ... */ AsnNode* moleculesNode = graphNode->findChildByName("molecule-graphs"); foreach (AsnNode* molNode, moleculesNode->children) { // Load molecule id bool ok = false; int molId = molNode->getChildById(0)->value.toInt(&ok); Q_ASSERT(ok == TRUE); // Load molecule data QByteArray molTypeName = molNode->findChildByName("descr")->findChildByName("molecule-type")->value; if (molTypeName == "protein" || molTypeName == "dna" || molTypeName == "rna") { MoleculeData* mol = new MoleculeData(); loadMoleculeFromNode(molNode, mol); struc.moleculeMap.insert(molId, SharedMolecule(mol)); } } } ASNFormat::~ASNFormat() { } void ASNFormat::BioStructLoader::loadBioStructSecondaryStruct( AsnNode* setsNode, BioStruct3D& struc ) { /* Biostruc-feature-set ::= SEQUENCE { id Biostruc-feature-set-id, descr SEQUENCE OF Biostruc-feature-set-descr OPTIONAL, features SEQUENCE OF Biostruc-feature } Biostruc-feature-set-descr ::= CHOICE { name VisibleString, pdb-comment VisibleString, other-comment VisibleString, attribution Pub } */ foreach (AsnNode* featureSet, setsNode->children) { QByteArray descr = featureSet->findChildByName("descr")->getChildById(0)->value; if (descr != "PDB secondary structure") { continue; } AsnNode* features = featureSet->getChildById(2); Q_ASSERT(features->name == "features"); foreach (AsnNode* featureNode, features->children) { loadBioStructFeature(featureNode, struc); } } } void ASNFormat::BioStructLoader::loadBioStructFeature( AsnNode* featureNode, BioStruct3D& struc ) { /* Biostruc-feature ::= SEQUENCE { id Biostruc-feature-id OPTIONAL, name VisibleString OPTIONAL, type INTEGER { helix(1), strand(2), sheet(3), turn(4), site(5), ... other(255) } OPTIONAL, property CHOICE { ... } OPTIONAL, location CHOICE {subgraph Chem-graph-pntrs, region Region-pntrs, alignment Chem-graph-alignment, similarity Region-similarity, indirect Other-feature } OPTIONAL } Residue-interval-pntr ::= SEQUENCE { molecule-id Molecule-id, from Residue-id, to Residue-id } */ AsnNode* typeNode = featureNode->findChildByName("type"); SecondaryStructure::Type ssType(SecondaryStructure::Type_None); if (typeNode->value == "helix") { ssType = SecondaryStructure::Type_AlphaHelix; } else if (typeNode->value == "strand" || typeNode->value == "sheet") { ssType = SecondaryStructure::Type_BetaStrand; } else if (typeNode->value == "turn") { ssType = SecondaryStructure::Type_Turn; } else { return; } AsnNode* locatioNode = featureNode->findChildByName("location subgraph residues interval")->getChildById(0); bool idOK = false, fromOK = false, toOK = false; int chainId = locatioNode->getChildById(0)->value.toInt(&idOK); int from = locatioNode->getChildById(1)->value.toInt(&fromOK); int to = locatioNode->getChildById(2)->value.toInt(&toOK); Q_ASSERT(idOK && fromOK && toOK); SecondaryStructure* ssData = new SecondaryStructure(); ssData->chainIndex = chainId; ssData->type = ssType; ssData->startSequenceNumber = from; ssData->endSequenceNumber = to; struc.secondaryStructures.append(SharedSecondaryStructure(ssData)); } bool containsAtom(const SharedAtom& atom, const BioStruct3D& struc) { foreach (const SharedMolecule mol, struc.moleculeMap) { foreach (const Molecule3DModel model, mol->models) { if (model.atoms.contains(atom)) { return true; } } } return false; } void ASNFormat::BioStructLoader::loadIntraResidueBonds( BioStruct3D& struc ) { Q_ASSERT(!stdResidueCache.isEmpty()); foreach(int chainId, struc.moleculeMap.keys()) { SharedMolecule& mol = struc.moleculeMap[chainId]; int numModels = mol->models.count(); for( int modelId = 0; modelId < numModels; ++modelId) { foreach( ResidueIndex resId, mol->residueMap.keys()) { quint64 index = calcStdResidueIndex(chainId, resId.toInt()); if (!stdResidueCache.contains(index)) { continue; } StdResidue residue = stdResidueCache.value(index); if (!atomSetCache.contains(index)) { continue; } const AtomCoordSet& atomSet = atomSetCache.value(index); Q_ASSERT(!atomSet.isEmpty()); foreach (const StdBond& bond, residue.bonds) { if ( (atomSet.contains(bond.atom1Id)) && (atomSet.contains(bond.atom2Id)) ) { const SharedAtom a1 = atomSet.value(bond.atom1Id); const SharedAtom a2 = atomSet.value(bond.atom2Id); mol->models[modelId].bonds.append(Bond(a1,a2)); } } } } } } /////////////////////////////////////////////////////////////////////////////////////////// #define READ_BUF_SIZE 4096 AsnNode* ASNFormat::AsnParser::loadAsnTree() { try { if (!readRootElement()) { throw AsnParserError( ASNFormat::tr("no root element") ); } AsnNode* rootElem = new AsnNode(curElementName, ASN_ROOT); parseNextElement(rootElem); if (states.count() != 0) { throw AsnParserError( ASNFormat::tr("states stack is not empty")); } return rootElem; } catch ( const AsnBaseException& ex ) { ts.setError(ex.msg); return NULL; } catch( ... ) { ts.setError(ASNFormat::tr("Unknown error occurred")); return NULL; } } bool ASNFormat::AsnParser::readRootElement() { Q_ASSERT(io->getProgress() == 0); QByteArray readBuff(READ_BUF_SIZE+1, 0); char* buf = readBuff.data(); quint64 len = 0; bool lineOk = true; len = io->readUntil(buf, READ_BUF_SIZE, TextUtils::LINE_BREAKS, IOAdapter::Term_Include, &lineOk); if (!lineOk) { throw AsnParserError(ASNFormat::tr("First line is too long")); } QString line = QString(QByteArray::fromRawData(buf, len)); if (line.contains("::=")) { // get mime type int start = line.indexOf("::=")+ 4; int finish = line.indexOf("{", start) - 1; QString mimeType = line.mid(start, finish - start); curElementName = mimeType.toAscii(); // initial state insideRoot = true; fileAtEnd = false; haveErrors = false; initState(mimeType.toAscii()); return true; } else { return false; } } void ASNFormat::AsnParser::initState( const QByteArray& parentName ) { curState.parentName = parentName; curState.numOpenedTags = 1; curState.atEnd = false; } void ASNFormat::AsnParser::parseNextElement( AsnNode* node ) { Q_ASSERT(insideRoot); while (!curState.atEnd) { if (readNextElement()) { if (curElementKind == ASN_VALUE) { AsnNode* child = new AsnNode(curElementName, curElementKind); child->value = curElementValue; node->children.append(child); } else if (curElementKind == ASN_SEQ) { saveState(); AsnNode* child = new AsnNode(curElementName, curElementKind); parseNextElement(child); restoreState(); node->children.append(child); } } else if (fileAtEnd) { break; } } } bool ASNFormat::AsnParser::readNextElement() { Q_ASSERT(insideRoot); buffer.clear(); char ch; bool insideQuotes = false; while (io->getChar(&ch)) { if (ch == '\"') { insideQuotes = insideQuotes ? false : true; } if ((ch == '{') && (!insideQuotes)) { ++curState.numOpenedTags; if (curState.numOpenedTags == 2) { // load current Element curElementName = buffer.trimmed(); curElementKind = ASN_SEQ; return true; } } if ((ch == ',') && (!insideQuotes)) { if ( curState.numOpenedTags == 2 ) { --curState.numOpenedTags; // sequence is finished, clear the buffer buffer.clear(); continue; } else { // read value processValue(); return true; } } if ((ch == '}') && (!insideQuotes)) { --curState.numOpenedTags; curState.atEnd = true; if (!buffer.trimmed().isEmpty()) { // read value processValue(); return true; } return false; } buffer += ch; prev = ch; } fileAtEnd = true; return false; } void ASNFormat::AsnParser::saveState() { states.push(curState); // init new state initState(curElementName); } void ASNFormat::AsnParser::restoreState() { Q_ASSERT(states.size() >= 1); curState = states.pop(); } void ASNFormat::AsnParser::processValue() { curElementValue.clear(); QByteArray valBuffer = buffer.trimmed(); QList valueList = valBuffer.split(' '); int numElements = valueList.count(); Q_ASSERT(numElements != 0); if (numElements == 1) { // there is only value curElementName.clear(); } else { curElementName = valueList.first().trimmed(); int numChars = curElementName.length() + 1; valBuffer.remove(0, numChars); } curElementValue = valBuffer; if (isQuoted(curElementValue)) { removeQuotes(curElementValue); } curElementKind = ASN_VALUE; } void ASNFormat::AsnParser::dbgPrintAsnTree( const AsnNode* rootElem, int deepness ) { ++deepness; foreach (const AsnNode* node, rootElem->children) { QString str; for (int i = 0; i < deepness; ++i) { str += " "; } str += QString("%1 (node)").arg(QString(node->name)); if (node->kind == ASN_VALUE) { str += QString(" value = %1").arg(QString(node->value)); } ioLog.trace(str); if (node->children.count() != 0) { dbgPrintAsnTree(node, deepness); } } --deepness; } bool ASNFormat::AsnParser::isQuoted( const QByteArray& str ) { int length = str.length(); static const char quoteChar('\"'); if ((str.at(0) == quoteChar) && (str.at(length - 1) == quoteChar)) { return true; } return false; } void ASNFormat::AsnParser::removeQuotes( QByteArray& str ) { int len = str.length(); str.remove(len - 1, 1); str.remove(0,1); } void ASNFormat::AsnParser::dbgPrintCurrentState() { qDebug("current element"); qDebug("\tname: %s", curElementName.constData()); qDebug("\tbuffer: %s", buffer.trimmed().constData()); qDebug("\tvalue: %s", curElementValue.constData()); switch(curElementKind) { case ASN_ROOT: qDebug("\tkind: ASN_ROOT"); break; case ASN_SEQ: qDebug("\tkind: ASN_SEQ"); break; case ASN_VALUE: qDebug("\tkind: ASN_VALUE"); break; default: Q_ASSERT(0); } if (haveErrors) qDebug("\terrors: yes"); else qDebug("\terrors: no"); qDebug(); } /////////////////////////////////////////////////////////////////////////////////////////// AsnNode::AsnNode() : name(""), kind(ASN_NO_KIND) { } AsnNode::AsnNode( const QByteArray& _name, AsnElementKind _kind ) : name(_name), kind (_kind) { } AsnNode::~AsnNode() { if (kind == ASN_ROOT) { deleteChildren(this); } } void AsnNode::deleteChildren( AsnNode* node ) { foreach(AsnNode* child, node->children) { deleteChildren(child); delete child; } } AsnNode* AsnNode::findChildByName( const QByteArray& name ) { foreach (AsnNode* child, children) { if (child->name == name) return child; } return NULL; } AsnNode* AsnNode::getChildById( int id ) { return children.at(id); } } //namespace ugene-1.9.8/src/corelibs/U2Formats/src/IndexFormat.h0000644000175000017500000000475211651544332020721 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_INDEX_FORMAT_H_ #define _U2_INDEX_FORMAT_H_ #include #include namespace U2 { class U2FORMATS_EXPORT IndexFormat : public DocumentFormat { Q_OBJECT public: static const int OBJECTS_IN_DOC = 1; static const QByteArray FILE_HEADER; static const QString WRITE_LOCK_REASON; private: QString format_name; public: IndexFormat( QObject* obj ); virtual DocumentFormatId getFormatId() const { return BaseDocumentFormats::INDEX; } virtual const QString& getFormatName() const { return format_name; } virtual Document* loadDocument(IOAdapter* io, TaskStateInfo& ti, const QVariantMap& fs, DocumentLoadMode mode = DocumentLoadMode_Whole); virtual void storeDocument( Document* d, TaskStateInfo& ts, IOAdapter* io); virtual RawDataCheckResult checkRawData(const QByteArray& data, const GUrl& = GUrl()) const; virtual bool isObjectOpSupported( const Document* d , DocumentFormat::DocObjectOp op, GObjectType t ) const; struct IndexFormatException { QString msg; IndexFormatException( const QString& what ) : msg( what ){} }; struct ReadError : public IndexFormatException { ReadError() : IndexFormatException( tr( "Read error occurred" ) ){} }; struct BadDataError : public IndexFormatException { BadDataError( const QString& what ) : IndexFormatException( what ){} }; struct WriteError : public IndexFormatException { WriteError() : IndexFormatException( tr( "Write error occurred" ) ){} }; }; // IndexFormat } // U2 #endif // _U2_INDEX_FORMAT_H_ ugene-1.9.8/src/corelibs/U2Formats/src/StreamSequenceWriter.h0000644000175000017500000000460611651544332022620 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_STREAM_SEQUENCE_WRITER_H_ #define _U2_STREAM_SEQUENCE_WRITER_H_ #include #include #include #include #include namespace U2 { /** * * Class provides stream writing for large alignment files. * It supports only SAM format. * */ class U2FORMATS_EXPORT StreamShortReadsWriter { IOAdapter* io; SAMFormat format; int numSeqWritten; int refSeqLength; QByteArray refSeqName; public: StreamShortReadsWriter(const GUrl& url, const QString& refName = QString(), int refLength = 0); ~StreamShortReadsWriter(); bool writeNextAlignedRead(int offset, const DNASequence& seq); void setRefSeqLength(int l) { refSeqLength = l;} void setRefSeqName(const QString& name ) { refSeqName = QString(name).replace(QRegExp("\\s|\\t"), "_").toAscii(); } int getNumSeqWritten() { return numSeqWritten; } void close(); }; /** * * Class provides stream writing for DNA short reads. * It currently supports FASTA formats and allows to write quality in separate file. * */ class FastaFormat; class U2FORMATS_EXPORT StreamShortReadWriter { FastaFormat* fastaFormat; IOAdapter* io; GUrl ouputPath; bool writeQuality; public: StreamShortReadWriter( bool writeQualityExplicitly = false); bool init(const GUrl& url); bool writeNextSequence(const DNASequence& seq); const GUrl& getOutputPath() { return ouputPath; } void close(); }; } //namespace #endif //_U2_STREAM_SEQUENCE_WRITER_H_ ugene-1.9.8/src/corelibs/U2Formats/src/EMBLPlainTextFormat.cpp0000644000175000017500000001704411651544332022553 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "EMBLPlainTextFormat.h" #include "GenbankLocationParser.h" #include "DocumentFormatUtils.h" #include #include #include #include #include #include #include #include #include namespace U2 { /* TRANSLATOR U2::EMBLPlainTextFormat */ /* TRANSLATOR U2::EMBLGenbankAbstractDocument */ EMBLPlainTextFormat::EMBLPlainTextFormat(QObject* p) : EMBLGenbankAbstractDocument(BaseDocumentFormats::PLAIN_EMBL, tr("EMBL"), 80, DocumentFormatFlag_SupportStreaming, p) { fileExtensions << "em" << "emb" << "embl"; formatDescription = tr("EMBL Flat File Format is a rich format for storing sequences and associated annotations"); sequenceStartPrefix = "SQ"; fPrefix = "FT"; tagMap["DT"] = DNAInfo::DATE; tagMap["PR"] = DNAInfo::PROJECT; tagMap["DE"] = DNAInfo::DEFINITION; tagMap["KW"] = DNAInfo::KEYWORDS; tagMap["CC"] = DNAInfo::COMMENT; tagMap["CO"] = DNAInfo::CONTIG; } RawDataCheckResult EMBLPlainTextFormat::checkRawData(const QByteArray& rawData, const GUrl&) const { //TODO: improve format checking const char* data = rawData.constData(); int size = rawData.size(); bool textOnly = !TextUtils::contains(TextUtils::BINARY, data, size); if (!textOnly || size < 100) { return FormatDetection_NotMatched; } bool tokenMatched = TextUtils::equals("ID ", data, 5); if (tokenMatched) { if(QString(rawData).contains(QRegExp("\\d+ AA."))){ return FormatDetection_NotMatched; } return FormatDetection_HighSimilarity; } return FormatDetection_NotMatched; } ////////////////////////////////////////////////////////////////////////// // loading bool EMBLPlainTextFormat::readIdLine(ParserState* s) { if (!s->hasKey("ID", 2)) { s->si.setError(EMBLPlainTextFormat::tr("ID is not the first line")); return false; } QString idLineStr= s->value(); QStringList tokens = idLineStr.split(";"); if (idLineStr.length() < 6 || tokens.isEmpty()) { s->si.setError(EMBLPlainTextFormat::tr("Error parsing ID line")); return false; } s->entry->name = tokens[0]; DNALocusInfo loi; loi.name = tokens[0]; if (tokens.size() > 1) { QString sec = tokens[1]; if (sec.startsWith("SV ")) { s->entry->tags[DNAInfo::VERSION] = tokens[0] + "." + sec.mid(3); } QString last = tokens.last(); if (last.endsWith("BP.")) { last.chop(3); s->entry->seqLen = last.toInt(); } } if (tokens.size() == 7) { // seems to be canonical header // http://www.ebi.ac.uk/embl/Documentation/User_manual/printable.html //1. Primary accession number //2. Sequence version number //3. Topology: 'circular' or 'linear' //4. Molecule type (see note 1 below) //5. Data class (methodological approach) //6. Taxonomic division (see section 3.2) //7. Sequence length (see note 2 below) loi.topology = tokens[2]; loi.molecule = tokens[3]; loi.division = tokens[5]; s->entry->circular = loi.topology == "circular"; } else { // remember just in case s->entry->tags.insert(DNAInfo::EMBL_ID, idLineStr); s->entry->circular = idLineStr.contains("circular"); } s->entry->tags.insert(DNAInfo::LOCUS, qVariantFromValue(loi)); return true; } bool EMBLPlainTextFormat::readEntry(QByteArray& sequence, ParserState* st) { TaskStateInfo& si = st->si; QString lastTagName; bool hasLine = false; while (hasLine || st->readNextLine(false)) { hasLine = false; if (st->entry->name.isEmpty()) { readIdLine(st); assert(si.hasError() || !st->entry->name.isEmpty()); if (si.hasError()) { break; } continue; } if (st->hasKey("FH") || st->hasKey("XX") || st->hasKey("AH")) { continue; } if (st->hasKey("AC")) { QVariant v = st->entry->tags.value(DNAInfo::ACCESSION); QStringList l = st->value().split(QRegExp(";\\s*"), QString::SkipEmptyParts); st->entry->tags[DNAInfo::ACCESSION] = QVariantUtils::addStr2List(v, l); continue; } if (st->hasKey("OS")) { DNASourceInfo soi; soi.name = st->value(); soi.organism = soi.name; while (st->readNextLine()) { if (st->hasKey("OS")) { soi.organism.append(" ").append(st->value()); } else if (!st->hasKey("XX")) { break; } } if (st->hasKey("OC")) { soi.taxonomy += st->value(); while (st->readNextLine()) { if (st->hasKey("OC")) { soi.taxonomy.append(st->value()); } else if (!st->hasKey("XX")) { break; } } } if (st->hasKey("OG")) { soi.organelle = st->value(); } else { hasLine = true; } st->entry->tags.insertMulti(DNAInfo::SOURCE, qVariantFromValue(soi)); continue; } if (st->hasKey("RF") || st->hasKey("RN")) { while (st->readNextLine() && st->buff[0] == 'R') { //TODO } hasLine = true; continue; } if (st->hasKey("FT", 2)) { readAnnotations(st, sequence.size()); hasLine = true; continue; } //read simple tag; if (st->hasKey("//", 2)) { // end of entry return true; } else if (st->hasKey("SQ", 2)) { //reading sequence readSequence(sequence, st); return true; } QString key = st->key().trimmed(); if (tagMap.contains(key)) { key = tagMap.value(key); } if (lastTagName == key) { QVariant v = st->entry->tags.take(lastTagName); v = QVariantUtils::addStr2List(v, st->value()); st->entry->tags.insert(lastTagName, v); } else if (st->hasValue()) { lastTagName = key; st->entry->tags.insertMulti(lastTagName, st->value()); } } if (!st->isNull() && !si.hasError() && !si.cancelFlag) { si.setError(U2::EMBLGenbankAbstractDocument::tr("Record is truncated.")); } return false; } }//namespace ugene-1.9.8/src/corelibs/U2Formats/src/ClustalWAlnFormat.h0000644000175000017500000000357711651544332022047 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_CLUSTAL_W_ALN_FORMAT_H_ #define _U2_CLUSTAL_W_ALN_FORMAT_H_ #include #include namespace U2 { class IOAdapter; class U2FORMATS_EXPORT ClustalWAlnFormat : public DocumentFormat { Q_OBJECT public: static const QByteArray CLUSTAL_HEADER; ClustalWAlnFormat(QObject* p); virtual DocumentFormatId getFormatId() const {return BaseDocumentFormats::CLUSTAL_ALN;} virtual const QString& getFormatName() const {return formatName;} virtual Document* loadDocument(IOAdapter* io, TaskStateInfo& ti, const QVariantMap& fs, DocumentLoadMode mode = DocumentLoadMode_Whole); virtual void storeDocument( Document* d, TaskStateInfo& ts, IOAdapter* io ); virtual RawDataCheckResult checkRawData(const QByteArray& rawData, const GUrl& = GUrl()) const; private: void save(IOAdapter* io, Document* doc, TaskStateInfo& ti); void load(IOAdapter* io, QList& objects, const QVariantMap& fs, TaskStateInfo& ti); QString formatName; }; }//namespace #endif ugene-1.9.8/src/corelibs/U2Formats/src/GenbankLocationParser.cpp0000644000175000017500000001344011651544332023241 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "GenbankLocationParser.h" #include #include namespace U2 { namespace Genbank { static int parseNum(const char* str, int len) { int num = 0; for (int i=0; i 9) { return -1; } num = num*10 + n; } return num; } static void checkNumberEnd(U2Location& location , int& x1, int& x2, const char* str, int len, bool addToResultsIfOne) { if (x1 < 0) { x1 = parseNum(str, len); } else { x2 = parseNum(str, len); } if (x2!=-1 || addToResultsIfOne) { if(x1 > x2){ if(x2 == -1){ x2 = qMax(x1, x2); //if x2 == -1 -> make it == x2 }else{ qSwap(x1, x2); //revers if x1 > x2 } } if (x1 > 0 && x1 <= x2) { int lLen = x2 - x1 + 1; //both x1 and x2 are inclusive location->regions << U2Region(x1-1, lLen); //-1 because in gb files location starts from 1 } } } #define STARTS_WITH(_str, _strlen, _token, _tokenlen) \ *(_str) == *(_token) && (_strlen) > (_tokenlen) && !qstrncmp((_token), (_str), (_tokenlen)) void LocationParser::parseLocation(const char* _str, int _len, U2Location& location) { //get a copy; QByteArray lineBuff(_str, _len); char* line = lineBuff.data(); //remove all white spaces int len = TextUtils::remove(_str, _len, line, TextUtils::WHITES); enum states {SKIPPING, READ_NUMBER, READ_DOT}; /** Init...*/ location->reset(); int state = SKIPPING; int x1 = -1; int x2 = -1; int numStart = 0; int dots = 0; /*----------------------------------*/ int i = 0; for (; iop = U2LocationOperator_Join; } else if (STARTS_WITH(strStart, strLen, "order(", 6)) { i+=5; location->op = U2LocationOperator_Order; } else if (STARTS_WITH(strStart, strLen, "complement(", 11)){ location->strand = U2Strand::Complementary; i+=10; } else if (c >= '0' && c <= '9') { if (state == READ_DOT && dots == 1 ) { if (x2 < 0) { //(a.b)..c ->skip b int j = i; for(; i < len && c >= '0' && c <= '9'; i++){ c = line[i]; } if (len-i > 2 && line[i]!=',') { i--; state = SKIPPING; continue; } else { // full location is something like (1.15)-> save '15' as x2 i=j; } } else { // a..(b.c) -> skip b x2=-1; } } if (state == READ_NUMBER) { continue; } state = READ_NUMBER; numStart = i; } else if (c=='.' || c=='^') { if (state==READ_NUMBER) { checkNumberEnd(location, x1, x2, line+numStart, i-numStart, false); } if (state!=READ_DOT) { state = READ_DOT; dots = c=='.' ? 1 : 2; //assume '^' == '..' } else { dots++; } } else if (c == ',' || c==')') { if (state==READ_NUMBER) { checkNumberEnd(location, x1, x2, line+numStart, i-numStart, true); } state = SKIPPING; x1=-1; x2=-1; } else if (c=='(' || c=='<' || c == '>'){ state = SKIPPING; } else { break;//code to parse braces and operators is not ready. } } if (state == READ_NUMBER) { checkNumberEnd(location, x1, x2, line+numStart, i-numStart, true); } } QString LocationParser::buildLocationString(const AnnotationData* d) { QVector location = d->getRegions(); bool complement = d->getStrand().isCompementary(); bool multi = location.size() > 1; QString locationStr = complement ? "complement(" : ""; if (!location.empty()) { if (multi) { locationStr += d->isOrder() ? "order(" : "join("; } locationStr += buildLocationString(location); } if (multi) { locationStr += ")"; } if (complement) { locationStr.append(")"); } return locationStr; } QString LocationParser::buildLocationString( const QVector& regions ) { QString locationStr; bool first = true; foreach (const U2Region& r, regions) { if (!first) { locationStr += ","; } else { first = false; } locationStr.append(QString::number(r.startPos+1).append("..").append(QString::number(r.endPos()))); } return locationStr; } }}//namespace ugene-1.9.8/src/corelibs/U2Formats/src/NEXUSParser.h0000644000175000017500000000627611651544332020563 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_NEXUS_PARSER_H_ #define _U2_NEXUS_PARSER_H_ #include #include #include namespace U2 { class GObject; class Tokenizer // Breaks input stream on tokens (QString) { public: Tokenizer(IOAdapter *io_) : io(io_) { assert(io_ && "IO must exist"); } QString look(); QString get(); void skip() { (void)get(); } QStringList getUntil(QString what, Qt::CaseSensitivity cs = Qt::CaseInsensitive); void skipUntil(QString what, Qt::CaseSensitivity cs = Qt::CaseInsensitive); QString readUntil(QRegExp rwhat); bool isEof() { return io->isEof(); } IOAdapter* getIO() { return io; } private: IOAdapter *io; QString next; static const int BUFF_SIZE; QString buff; QTextStream buffStream; }; class NEXUSParser // NEXUS File format parser { public: NEXUSParser (IOAdapter *io_, TaskStateInfo &ti_) : io(io_), ti(ti_), tz(io) { assert(io_ && "IO must exist"); } QList loadObjects(); bool hasError() { return !errors.isEmpty(); } bool hasWarnings() { return !warnings.isEmpty(); } const QStringList& getErrors() const { return errors; } const QStringList& getWarnings() const { return warnings; } private: typedef QMap Context; bool skipCommand(); bool readSimpleCommand(Context &ctx); bool readBlock(Context &ctx); bool skipBlockContents(); bool readTaxaContents(Context &ctx); bool readDataContents(Context &ctx); bool readTreesContents(Context &ctx); void reportProgress() { ti.progress = io->getProgress(); } // append object to objects, and resolve name conflicts void addObject(GObject *obj); private: static const QString BEGIN; static const QString END; static const QString BLK_TAXA; static const QString BLK_DATA; static const QString BLK_CHARACTERS; static const QString CMD_DIMENSIONS; static const QString CMD_FORMAT; static const QString CMD_MATRIX; static const QString BLK_TREES; static const QString CMD_TREE; static const QString CMD_UTREE; private: IOAdapter *io; TaskStateInfo &ti; Tokenizer tz; QList objects; QSet objectNames; Context global; QStringList errors, warnings; }; } // namespace U2 #endif // #ifndef _U2_NEXUS_PARSER_H_ ugene-1.9.8/src/corelibs/U2Formats/src/SCFFormat.cpp0000644000175000017500000010213111651544332020606 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "SCFFormat.h" #include "IOLibUtils.h" #include "DocumentFormatUtils.h" #include #include #include #include #include #include #include #include #include #include #include #include /* TRANSLATOR U2::SCFFormat */ namespace U2 { SCFFormat::SCFFormat(QObject* p) : DocumentFormat(p,DocumentFormatFlags(0), QStringList("scf")) { formatName = tr("SCF"); supportedObjectTypes+=GObjectTypes::SEQUENCE; supportedObjectTypes+=GObjectTypes::CHROMATOGRAM; } RawDataCheckResult SCFFormat::checkRawData(const QByteArray& rawData, const GUrl&) const { const char* data = rawData.constData(); int size = rawData.size(); if (size <= 4 || data[0]!='.' || data[1]!='s' || data[2]!='c' || data[3]!='f') { return FormatDetection_NotMatched; } bool hasBinaryData = TextUtils::contains(TextUtils::BINARY, data, size); return hasBinaryData ? FormatDetection_Matched: FormatDetection_NotMatched; } Document* SCFFormat::loadDocument(IOAdapter* io, TaskStateInfo& ti, const QVariantMap& fs, DocumentLoadMode) { GUrl url = io->getURL(); QByteArray readBuff; QByteArray block(BUFF_SIZE, 0); quint64 len = 0; while ((len=io->readBlock(block.data(),BUFF_SIZE)) > 0) { readBuff.append(QByteArray(block.data(), len)); if (readBuff.size()>CHECK_MB) { ti.setError(L10N::errorFileTooLarge(url)); break; } } if (ti.hasError()) { return NULL; } SeekableBuf sf; sf.head = readBuff.constData(); sf.pos = 0; sf.size = readBuff.size(); Document* doc = parseSCF(&sf, io->getFactory(), url, fs, ti); if (doc == NULL && !ti.hasError()) { if (!ti.hasError()) { ti.setError(tr("Failed to parse SCF file: %1").arg(url.getURLString())); } } return doc; } template void dumpVector(const QVector& v) { printf("Tha vector\n"); for (int i = 0; i < v.count(); ++i ){ printf("%d ", v[i]); } printf("\n\n"); } /* * Copyright (c) Medical Research Council 1994. All rights reserved. * * Permission to use, copy, modify and distribute this software and its * documentation for any purpose is hereby granted without fee, provided that * this copyright and notice appears in all copies. * * This file was written by James Bonfield, Simon Dear, Rodger Staden, * as part of the Staden Package at the MRC Laboratory of Molecular * Biology, Hills Road, Cambridge, CB2 2QH, United Kingdom. * * MRC disclaims all warranties with regard to this software. */ /* Title: read_scf.c Purpose: read IO of Standard Chromatogram Format sequences Last update: August 18 1994 Change log: 4 Feb 1992, Now draft proposal version 2 20 Feb 1992, Grab info from comment lines 19 Aug 1992, If SCF file has clip information, don't clip automatically 10 Nov 1992 SCF comments now stored in seq data structure 18 Aug 1994 Renamed from ReadIOSCF.c; now purely SCF IO (no Seq structs) */ /* The SCF magic number */ #define SCF_MAGIC ((int) ((((('.'<<8)+'s')<<8)+'c')<<8)+'f') /* prior to this was a different format */ #define SCF_VERSION_OLDEST 2.00F #define SCF_VERSION_OLD 2.02F /* The current SCF format level */ #define SCF_VERSION 3.00 /* *----------------------------------------------------------------------------- * Structures and typedefs *----------------------------------------------------------------------------- */ /* * Type definition for the Header structure */ typedef struct { uint magic_number; /* SCF_MAGIC */ uint samples; /* Number of elements in Samples matrix */ uint samples_offset; /* Byte offset from start of file */ uint bases; /* Number of bases in Bases matrix */ uint bases_left_clip; /* OBSOLETE: No. bases in left clip (vector) */ uint bases_right_clip; /* OBSOLETE: No. bases in right clip (qual) */ uint bases_offset; /* Byte offset from start of file */ uint comments_size; /* Number of bytes in Comment section */ uint comments_offset; /* Byte offset from start of file */ char version[4]; /* "version.revision" */ uint sample_size; /* precision of samples (in bytes) */ uint code_set; /* uncertainty codes used */ uint private_size; /* size of private data, 0 if none */ uint private_offset; /* Byte offset from start of file */ uint spare[18]; /* Unused */ } Header; /* * Header.sample_size == 1. */ typedef struct { uchar sample_A; /* Sample for A trace */ uchar sample_C; /* Sample for C trace */ uchar sample_G; /* Sample for G trace */ uchar sample_T; /* Sample for T trace */ } Samples1; /* * Header.sample_size == 2. */ typedef struct { ushort sample_A; /* Sample for A trace */ ushort sample_C; /* Sample for C trace */ ushort sample_G; /* Sample for G trace */ ushort sample_T; /* Sample for T trace */ } Samples2; /* * Type definition for the sequence data */ typedef struct { uint peak_index; /* Index into Samples matrix for base position */ uchar prob_A; /* Probability of it being an A */ uchar prob_C; /* Probability of it being an C */ uchar prob_G; /* Probability of it being an G */ uchar prob_T; /* Probability of it being an T */ char base; /* Base called */ uchar spare[3]; /* Spare */ } Bases; /* * Type definition for the comments */ typedef char Comments; /* Zero terminated list of \n separated entries */ /* * Reading SCF routines * ----------------- * Return: * 0 - success * -1 - failure */ int read_scf_header(SeekableBuf *fp, Header *h) { int i; if (be_read_int_4(fp,&h->magic_number)==0) return -1; if (h->magic_number != SCF_MAGIC) return -1; if (be_read_int_4(fp,&h->samples)==0) return -1; if (be_read_int_4(fp,&h->samples_offset)==0) return -1; if (be_read_int_4(fp,&h->bases)==0) return -1; if (be_read_int_4(fp,&h->bases_left_clip)==0) return -1; if (be_read_int_4(fp,&h->bases_right_clip)==0) return -1; if (be_read_int_4(fp,&h->bases_offset)==0) return -1; if (be_read_int_4(fp,&h->comments_size)==0) return -1; if (be_read_int_4(fp,&h->comments_offset)==0) return -1; if (!fp->read(&h->version[0],sizeof(h->version))) return -1; if (be_read_int_4(fp,&h->sample_size)==0) return -1; if (be_read_int_4(fp,&h->code_set)==0) return -1; if (be_read_int_4(fp,&h->private_size)==0) return -1; if (be_read_int_4(fp,&h->private_offset)==0) return -1; for (i=0;i<18;i++) if (be_read_int_4(fp,&h->spare[i])==0) return -1; return 0; } int read_scf_sample1(SeekableBuf *fp, Samples1 *s) { uchar buf[4]; if (!fp->read((char*)buf, 4)) return -1; s->sample_A = buf[0]; s->sample_C = buf[1]; s->sample_G = buf[2]; s->sample_T = buf[3]; return 0; } int read_scf_sample2(SeekableBuf *fp, Samples2 *s) { if (be_read_int_2(fp,&s->sample_A)==0) return -1; if (be_read_int_2(fp,&s->sample_C)==0) return -1; if (be_read_int_2(fp,&s->sample_G)==0) return -1; if (be_read_int_2(fp,&s->sample_T)==0) return -1; return 0; } int read_scf_samples1(SeekableBuf *fp, Samples1 *s, size_t num_samples) { for (size_t i = 0; i < num_samples; i++) { if (-1 == read_scf_sample1(fp, &(s[i]))) return -1; } return 0; } int read_scf_samples2(SeekableBuf *fp, Samples2 *s, size_t num_samples) { for (size_t i = 0; i < num_samples; i++) { if (-1 == read_scf_sample2(fp, &(s[i]))) return -1; } return 0; } void scf_delta_samples1 (char* samples, int num_samples) { /* do the reverse to: change a series of sample points to a series of delta delta values: ie change them first: delta = current_value - previous_value then delta_delta = delta - previous_delta */ #ifdef CLEAR_BUT_SLOW uchar p_sample; p_sample = 0; for (i=0;i 1; i--) { samples[i] = samples[i] - 2*samples[i-1] + samples[i-2]; } samples[1] = samples[1] - 2*samples[0]; #endif } else { #ifdef CLEAR_BUT_SLOW register ushort p_sample; p_sample = 0; for (i=0;i arr(num_samples); ushort* samples_out = arr.data(); /* version to read delta delta data in 2 bytes */ for (i = 0; i < num_samples; i++) { if (be_read_int_2(fp, samples_out + i) == 0) return -1; } scf_delta_samples2 ( samples_out, num_samples,0); for (i = 0; i < num_samples; i++) { (&s[i])->sample_A = samples_out[i]; } for (i = 0; i < num_samples; i++) { if (be_read_int_2(fp, samples_out + i) == 0) return -1; } scf_delta_samples2 ( samples_out, num_samples,0); for (i = 0; i < num_samples; i++) { (&s[i])->sample_C = samples_out[i]; } for (i = 0; i < num_samples; i++) { if (be_read_int_2(fp, samples_out + i) == 0) return -1; } scf_delta_samples2 ( samples_out, num_samples,0); for (i = 0; i < num_samples; i++) { (&s[i])->sample_G = samples_out[i]; } for (i = 0; i < num_samples; i++) { if (be_read_int_2(fp, samples_out + i) == 0) return -1; } scf_delta_samples2 ( samples_out, num_samples,0); for (i = 0; i < num_samples; i++) { (&s[i])->sample_T = samples_out[i]; } return 0; } int read_scf_samples31(SeekableBuf *fp, Samples1 *s, size_t num_samples) { size_t i; QVarLengthArray arr(num_samples); char* samples_out = arr.data(); /* version to read delta delta data in 1 byte */ if (fp->read(samples_out, num_samples)) return -1; scf_delta_samples1 ( samples_out, num_samples); for (i = 0; i < num_samples; i++) { (&s[i])->sample_A = samples_out[i]; } if (fp->read(samples_out, num_samples)) return -1; scf_delta_samples1 ( samples_out, num_samples); for (i = 0; i < num_samples; i++) { (&s[i])->sample_C = samples_out[i]; } if (fp->read(samples_out, num_samples)) return -1; scf_delta_samples1 ( samples_out, num_samples); for (i = 0; i < num_samples; i++) { (&s[i])->sample_G = samples_out[i]; } if (fp->read(samples_out, num_samples)) return -1; scf_delta_samples1 ( samples_out, num_samples); for (i = 0; i < num_samples; i++) { (&s[i])->sample_T = samples_out[i]; } return 0; } int read_scf_base(SeekableBuf *fp, Bases *b) { uchar buf[12]; if (!fp->read((char*)buf, 12)) return -1; b->peak_index = be_int4(buf); b->prob_A = buf[4]; b->prob_C = buf[5]; b->prob_G = buf[6]; b->prob_T = buf[7]; b->base = buf[8]; b->spare[0] = buf[9]; b->spare[1] = buf[10]; b->spare[2] = buf[11]; return 0; } int read_scf_bases(SeekableBuf *fp, Bases *b, size_t num_bases) { size_t i; for (i = 0; i < num_bases; i++) { if (-1 == read_scf_base(fp, &(b[i]))) return -1; } return 0; } int read_scf_bases3(SeekableBuf *fp, Bases *b, size_t num_bases) { size_t i; QVarLengthArray arr1(num_bases * 8); uchar *buf1 = arr1.data(); for (i = 0; i < num_bases; i++) { uint buf4; if (be_read_int_4(fp, &buf4) == 0) return -1; (&b[i])->peak_index = buf4; } if (!fp->read((char*)buf1, 8 * num_bases)) return -1; for (i=0; i < num_bases; i++) { (&b[i])->prob_A = buf1[i]; (&b[i])->prob_C = buf1[i+num_bases]; (&b[i])->prob_G = buf1[i+2*num_bases]; (&b[i])->prob_T = buf1[i+3*num_bases]; (&b[i])->base = buf1[i+4*num_bases]; (&b[i])->spare[0] = buf1[i+5*num_bases]; (&b[i])->spare[1] = buf1[i+6*num_bases]; (&b[i])->spare[2] = buf1[i+7*num_bases]; } return 0; } Document* SCFFormat::parseSCF(SeekableBuf* fp, IOAdapterFactory* iof, const GUrl& url, const QVariantMap& fs, U2OpStatus& os) { Header h; float scf_version; int sections = READ_ALL; /* Read header */ if (read_scf_header(fp, &h) == -1) { return false; } /* fake things for older style SCF -- SD */ if (h.sample_size != 1 && h.sample_size != 2) h.sample_size = 1; QString ver(h.version); ver.chop(4); scf_version = ver.toFloat(); /* Allocate memory */ DNAChromatogram cd; QByteArray sequence(h.bases, 0); if (sections & READ_SAMPLES) { /* Read samples */ if (SeekBuf(fp, h.samples_offset, 0 /* SEEK_SET */) != 0) { return NULL; } cd.A.resize(h.samples); cd.C.resize(h.samples); cd.G.resize(h.samples); cd.T.resize(h.samples); cd.traceLength = h.samples; int err; if (h.sample_size == 1) { QVector samples(h.samples); if ( 2.9 > scf_version ) { err= read_scf_samples1(fp, samples.data(), h.samples); } else { err= read_scf_samples31(fp, samples.data(), h.samples); } if (-1 == err) { return NULL; } for (uint i = 0; i < h.samples; i++) { cd.A[i] = samples[i].sample_A; cd.C[i] = samples[i].sample_C; cd.G[i] = samples[i].sample_G; cd.T[i] = samples[i].sample_T; } } else { QVector samples(h.samples); if (2.9 > scf_version ) { err= read_scf_samples2(fp, samples.data(), h.samples); } else { err= read_scf_samples32(fp, samples.data(), h.samples); } if (-1 == err) { return NULL; } for (uint i = 0; i < h.samples; i++) { cd.A[i] = samples[i].sample_A; cd.C[i] = samples[i].sample_C; cd.G[i] = samples[i].sample_G; cd.T[i] = samples[i].sample_T; } } } if (sections & READ_BASES) { /* Read bases */ if (SeekBuf(fp, h.bases_offset, 0 /* SEEK_SET */) != 0) { return NULL; } QVector bases(h.bases); if ( 2.9 > scf_version ) { if (-1 == read_scf_bases(fp, bases.data(), h.bases)) { return NULL; } } else { if (-1 == read_scf_bases3(fp, bases.data(), h.bases)) { return NULL; } } cd.seqLength = h.bases; cd.baseCalls.resize(h.bases); cd.prob_A.resize(h.bases); cd.prob_C.resize(h.bases); cd.prob_G.resize(h.bases); cd.prob_T.resize(h.bases); for (uint i = 0; iread(arr.data(), h.comments_size) ) { comments.append(arr); } } } cd.hasQV = true; DNASequence dna(sequence); QString sampleName; QStringList vals = comments.split("\n"); // detect sample name per http://www.ncbi.nlm.nih.gov/Traces/trace.cgi?cmd=show&f=formats&m=doc&s=format foreach(const QString& val, vals) { if (val.startsWith("NAME=")) { sampleName = val.mid(5); break; } } if (sampleName.isEmpty()) { sampleName = url.baseFileName(); } if (!sampleName.isEmpty()) { dna.info.insert(DNAInfo::ID, sampleName); } dna.info.insert(DNAInfo::COMMENT, vals); QList objects; DNASequenceObject* seqObj = DocumentFormatUtils::addSequenceObject(objects, sampleName + " sequence", dna, fs, os); if (os.hasError()) { return NULL; } SAFE_POINT(seqObj != NULL, "DocumentFormatUtils::addSequenceObject returned NULL but didn't set error", NULL); DNAChromatogramObject* chromObj = new DNAChromatogramObject(cd, sampleName + " chromatogram"); objects.append(chromObj); Document* doc = new Document(this, iof, url, objects, fs); chromObj->addObjectRelation(GObjectRelation(GObjectReference(seqObj), GObjectRelationRole::SEQUENCE)); return doc; } /* * Copyright (c) Medical Research Council 1994. All rights reserved. * * Permission to use, copy, modify and distribute this software and its * documentation for any purpose is hereby granted without fee, provided that * this copyright and notice appears in all copies. * * This file was written by James Bonfield, Simon Dear, Rodger Staden, * as part of the Staden Package at the MRC Laboratory of Molecular * Biology, Hills Road, Cambridge, CB2 2QH, United Kingdom. * * MRC disclaims all warranties with regard to this software. */ /* Title: write_scf.c Purpose: Output of Standard Chromatogram Format sequences Last update: August 18 1994 Change log: 4 Feb 1992, Now draft proposal version 2 23 Nov 92, SCF 2.0 + LaDeana's changes 11 Aug 93, Version 2.01 containing confidence values 18 Aug 1994 Renamed from writeSCF.c; now purely SCF IO (no Seq structs) Oct 95 major rewrite to make files more easily compressed. gzip now gets files to around 40% of original Version raised to 3.00 * We store in order: * Header * Samples * Bases * Comments * Private Two main types of change: 1: write data in lane order instead of all lanes together eg write Sample values for A, then Sample values for C, etc. 2: where appropriate write delta delta values instead of complete ones. ie write the differences in the differences between successive values */ const static int scf_version = 3; /* ---- Imports ---- */ // #include // #include /* IMPORT: fopen, fclose, fseek, ftell, fgetc, // EOF */ // #include // #include "io_lib/scf.h" /* IMPORT: scf structures */ // #include "io_lib/mach-io.h" /* IMPORT: be_write_int_1, be_write_int_2, be_write_int_4 */ // #include "io_lib/xalloc.h" // // #include "io_lib/stdio_hack.h" /* ---- Exports ---- */ int write_scf_header(FILE *fp, Header *h) { int i; if (be_write_int_4(fp,&h->magic_number)==false) return -1; if (be_write_int_4(fp,&h->samples)==false) return -1; if (be_write_int_4(fp,&h->samples_offset)==false) return -1; if (be_write_int_4(fp,&h->bases)==false) return -1; if (be_write_int_4(fp,&h->bases_left_clip)==false) return -1; if (be_write_int_4(fp,&h->bases_right_clip)==false) return -1; if (be_write_int_4(fp,&h->bases_offset)==false) return -1; if (be_write_int_4(fp,&h->comments_size)==false) return -1; if (be_write_int_4(fp,&h->comments_offset)==false) return -1; if (fwrite(h->version,sizeof(h->version),1,fp)!=1) return -1; if (be_write_int_4(fp,&h->sample_size)==false) return -1; if (be_write_int_4(fp,&h->code_set)==false) return -1; if (be_write_int_4(fp,&h->private_size)==false) return -1; if (be_write_int_4(fp,&h->private_offset)==false) return -1; for (i=0;i<18;i++) if (be_write_int_4(fp,&h->spare[i])==false) return -1; return 0; } // int write_scf_sample1(FILE *fp, Samples1 *s) // { // uchar buf[4]; // // buf[0] = s->sample_A; // buf[1] = s->sample_C; // buf[2] = s->sample_G; // buf[3] = s->sample_T; // if (4 != fwrite(buf, 1, 4, fp)) return -1; // // return 0; // } // // // int write_scf_sample2(FILE *fp, Samples2 *s) // { // ushort buf[4]; // // buf[0] = be_int2(reinterpret_cast (&s->sample_A) ); // buf[1] = be_int2(reinterpret_cast (&s->sample_C) ); // buf[2] = be_int2(reinterpret_cast (&s->sample_G) ); // buf[3] = be_int2(reinterpret_cast (&s->sample_T) ); // if (4 != fwrite(buf, 2, 4, fp)) return -1; // // return 0; // } // // // int write_scf_samples1(FILE *fp, Samples1 *s, size_t num_samples) { // size_t i; // // for (i = 0; i < num_samples; i++) { // if (-1 == write_scf_sample1(fp, &(s[i]))) // return -1; // } // // return 0; // } // int write_scf_samples2(FILE *fp, Samples2 *s, size_t num_samples) { // size_t i; // // for (i = 0; i < num_samples; i++) { // if (-1 == write_scf_sample2(fp, &(s[i]))) // return -1; // } // // return 0; // } int write_scf_samples31(FILE *fp, Samples1 *s, size_t num_samples) { size_t i; if (!num_samples) return 0; QVarLengthArray ar(num_samples); uchar *samples_out=ar.data(); for (i = 0; i < num_samples; i++) { samples_out[i] = (&s[i])->sample_A; } scf_delta_samples1 ( reinterpret_cast (samples_out), num_samples); if (num_samples != fwrite(samples_out, 1, num_samples, fp)) { return -1; } for (i = 0; i < num_samples; i++) { samples_out[i] = (&s[i])->sample_C; } scf_delta_samples1 ( reinterpret_cast(samples_out), num_samples); if (num_samples != fwrite(samples_out, 1, num_samples, fp)) { return -1; } for (i = 0; i < num_samples; i++) { samples_out[i] = (&s[i])->sample_G; } scf_delta_samples1 ( reinterpret_cast(samples_out), num_samples); if (num_samples != fwrite(samples_out, 1, num_samples, fp)) { return -1; } for (i = 0; i < num_samples; i++) { samples_out[i] = (&s[i])->sample_T; } scf_delta_samples1 ( reinterpret_cast(samples_out), num_samples); if (num_samples != fwrite(samples_out, 1, num_samples, fp)) { return -1; } return 0; } int write_scf_samples32(FILE *fp, Samples2 *s, size_t num_samples) { size_t i; if (!num_samples) return 0; QVarLengthArray ar(num_samples); ushort *samples_out = ar.data(); for (i = 0; i < num_samples; i++) { samples_out[i] = (&s[i])->sample_A; } scf_delta_samples2 ( samples_out, num_samples,1); for (i = 0; i < num_samples; i++) { samples_out[i] = be_int2(reinterpret_cast(&samples_out[i])); } if (num_samples != fwrite(samples_out, 2, num_samples, fp)) return -1; for (i = 0; i < num_samples; i++) { samples_out[i] = (&s[i])->sample_C; } scf_delta_samples2 ( samples_out, num_samples,1); for (i = 0; i < num_samples; i++) { samples_out[i] = be_int2(reinterpret_cast(&samples_out[i])); } if (num_samples != fwrite(samples_out, 2, num_samples, fp)) return -1; for (i = 0; i < num_samples; i++) { samples_out[i] = (&s[i])->sample_G; } scf_delta_samples2 ( samples_out, num_samples,1); for (i = 0; i < num_samples; i++) { samples_out[i] = be_int2(reinterpret_cast(&samples_out[i])); } if (num_samples != fwrite(samples_out, 2, num_samples, fp)) return -1; for (i = 0; i < num_samples; i++) { samples_out[i] = (&s[i])->sample_T; } scf_delta_samples2 ( samples_out, num_samples,1); for (i = 0; i < num_samples; i++) { samples_out[i] = be_int2(reinterpret_cast(&samples_out[i])); } if (num_samples != fwrite(samples_out, 2, num_samples, fp)) return -1; return 0; } int write_scf_base(FILE *fp, Bases *b) { uchar buf[12]; uchar *bufC; uint bufBegin[1]; *bufBegin = be_int4(reinterpret_cast(&b->peak_index)); bufC = (uchar*)bufBegin; buf[0] = bufC[0]; buf[1] = bufC[1]; buf[2] = bufC[2]; buf[3] = bufC[3]; buf[4] = b->prob_A; buf[5] = b->prob_C; buf[6] = b->prob_G; buf[7] = b->prob_T; buf[8] = b->base; buf[9] = b->spare[0]; buf[10] = b->spare[1]; buf[11] = b->spare[2]; if (12 != fwrite(buf, 1, 12, fp)) return -1; return 0; } int write_scf_bases(FILE *fp, Bases *b, size_t num_bases) { size_t i; for (i = 0; i < num_bases; i++) { if (-1 == write_scf_base(fp, &(b[i]))) return -1; } return 0; } int write_scf_bases3(FILE *fp, Bases *b, size_t num_bases) { size_t i; QVarLengthArray ar4(4 * num_bases); QVarLengthArray ar1(8 * num_bases); uint *buf4 = ar4.data(); uchar *buf1 = ar1.data(); for (i = 0; i < num_bases; i++) { buf4[i] = be_int4(reinterpret_cast( &(&b[i])->peak_index) ); } fwrite(buf4, 4, num_bases, fp); for (i=0; i < num_bases; i++) { buf1[i ] = (&b[i])->prob_A; buf1[i+ num_bases] = (&b[i])->prob_C; buf1[i+2*num_bases] = (&b[i])->prob_G; buf1[i+3*num_bases] = (&b[i])->prob_T; buf1[i+4*num_bases] = (&b[i])->base; buf1[i+5*num_bases] = (&b[i])->spare[0]; buf1[i+6*num_bases] = (&b[i])->spare[1]; buf1[i+7*num_bases] = (&b[i])->spare[2]; } if (8 * num_bases != (fwrite(buf1, 1, 8 * num_bases, fp))) { return -1; } return 0; } int write_scf_comment(FILE *fp, Comments *c, size_t s) { if (fwrite(c, 1, s, fp) != s) return -1; return 0; } /* * All of the above structs in a single scf format. */ typedef struct { Header header; union Samples { Samples1 *samples1; Samples2 *samples2; } samples; Bases *bases; Comments *comments; char *private_data; } Scf; /* * Request which (major) version of scf to use when writing. * Defaults to the latest. Currently suitable fields are * 2 and 3. * * Returns 0 for success, -1 for failure. */ // int set_scf_version(int version) { // if (version != 2 && version != 3) // return -1; // // scf_version = version; // return 0; // } inline QString scf_version_float2str(float f) { QString result = QString().sprintf("%1.2f", f); return result; } /* * Write Seq out as a .scf file to the 'fp' FILE * */ int fwrite_scf(Scf *scf, FILE *fp) { uint size; int err; /* * Init header offsets. * * We store in order: * Header * Samples * Bases * Comments * Private */ scf->header.samples_offset = (uint)sizeof(Header); size = scf->header.samples * (scf->header.sample_size == 1 ? sizeof(Samples1) : sizeof(Samples2)); scf->header.bases_offset = (uint)(scf->header.samples_offset + size); size = scf->header.bases * sizeof(Bases); scf->header.comments_offset = (uint)(scf->header.bases_offset + size); size = scf->header.comments_size; scf->header.private_offset = (uint)(scf->header.comments_offset + size); /* Init a few other things, such as the magic number */ scf->header.magic_number = SCF_MAGIC; if (scf_version == 3) { memcpy(scf->header.version, scf_version_float2str(SCF_VERSION).toAscii().constData(), 4); } else { memcpy(scf->header.version, scf_version_float2str(SCF_VERSION_OLD).toAscii().constData(), 4); } /* Write header */ if (write_scf_header(fp, &scf->header) == -1) return -1; if (scf_version == 3) { /* Write Samples */ if (scf->header.sample_size == 1) err = write_scf_samples31(fp, scf->samples.samples1, scf->header.samples); else err = write_scf_samples32(fp, scf->samples.samples2, scf->header.samples); if (-1 == err) return -1; /* Write Bases */ if (-1 == write_scf_bases3(fp, scf->bases, scf->header.bases)) return -1; } /* Write Comments */ if (-1 == write_scf_comment(fp, scf->comments, scf->header.comments_size)) return -1; /* Write private data */ if (scf->header.private_size) { if (scf->header.private_size != fwrite(scf->private_data, 1, scf->header.private_size, fp)) return -1; } return 0; } static void saveChromatogramToSCF(const DNAChromatogram& c, const QByteArray& seq, FILE* fp) { Scf scf; scf.comments = NULL; scf.private_data = NULL; scf.header.bases = c.seqLength; scf.header.samples = c.traceLength; scf.header.bases_left_clip = 0; scf.header.bases_right_clip = 0; scf.header.code_set = 2; // TODO: not sure if correct scf.header.comments_size = 0; scf.header.comments_offset = 0; scf.header.private_size = 0; // Fixed precision for saving scf.header.sample_size = 2; assert(c.seqLength == seq.length()); QVector bases(c.seqLength); for (int i = 0; i < c.seqLength; ++i) { bases[i].base = seq.at(i); bases[i].prob_A = c.prob_A.at(i); bases[i].prob_C = c.prob_C.at(i); bases[i].prob_G = c.prob_G.at(i); bases[i].prob_T = c.prob_T.at(i); bases[i].peak_index = c.baseCalls.at(i); } scf.bases = bases.data(); QVector samples(c.traceLength); for (int i = 0; i < c.traceLength; ++i) { samples[i].sample_A = c.A[i]; samples[i].sample_C = c.C[i]; samples[i].sample_G = c.G[i]; samples[i].sample_T = c.T[i]; } scf.samples.samples2 = samples.data(); fwrite_scf(&scf, fp); } void SCFFormat::exportDocumentToSCF( const QString& fileName, const DNAChromatogram& cd, const DNASequence& dna, TaskStateInfo& ts ) { { QFile file(fileName); if (!file.open(QIODevice::WriteOnly)) { ts.setError(L10N::errorOpeningFileWrite(fileName)); return; } file.close(); } FILE* fp = NULL; #ifdef Q_OS_WIN errno_t err = fopen_s(&fp, qPrintable(fileName), "wb+"); if (err != 0) { ts.setError(L10N::errorOpeningFileWrite(fileName)); return; } #else fp = fopen(qPrintable(fileName), "wb+"); #endif if (fp == NULL) { ts.setError(L10N::errorOpeningFileWrite(fileName)); return; } saveChromatogramToSCF(cd,dna.seq,fp); fclose(fp); } }//namespace ugene-1.9.8/src/corelibs/U2Formats/src/MegaFormat.h0000644000175000017500000000550511651544332020520 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_MEGA_FORMAT_H_ #define _U2_MEGA_FORMAT_H_ #include #include #include namespace U2 { class U2FORMATS_EXPORT MegaFormat : public DocumentFormat { Q_OBJECT public: MegaFormat(QObject* p); virtual DocumentFormatId getFormatId() const { return BaseDocumentFormats::MEGA; } virtual const QString& getFormatName() const { return formatName; } virtual Document* loadDocument(IOAdapter* io, TaskStateInfo& ti, const QVariantMap& fs, DocumentLoadMode mode = DocumentLoadMode_Whole); virtual void storeDocument(Document* d, TaskStateInfo& ts, IOAdapter* io ); virtual RawDataCheckResult checkRawData(const QByteArray& rawData, const GUrl& = GUrl()) const; private: QString formatName; void load(IOAdapter* io, QList& objects, TaskStateInfo& ti); void save(IOAdapter* io, Document* d, TaskStateInfo& ti); static void skipWhites(IOAdapter *io, QByteArray &line); static void readHeader(IOAdapter* io, QByteArray &line, TaskStateInfo &ti); static void readTitle(IOAdapter* io, QByteArray &line, TaskStateInfo &ti); static bool readName(IOAdapter* io, QByteArray &line, QByteArray &name, TaskStateInfo &ti); static bool readSequence(IOAdapter* io, QByteArray &line, TaskStateInfo &ti, QByteArray &value, bool *lastIteration); static void workUpIndels(MAlignment & al); static bool getNextLine(IOAdapter* io, QByteArray& line); static bool skipComments(IOAdapter* io, QByteArray &line, TaskStateInfo &ti); static bool checkName(QByteArray &name); static const QByteArray MEGA_HEADER; static const char MEGA_SEPARATOR; static const QByteArray MEGA_TITLE; static const QByteArray MEGA_UGENE_TITLE; static const char MEGA_IDENTICAL; static const char MEGA_INDEL; static const char MEGA_START_COMMENT; static const char MEGA_END_COMMENT; static const int BLOCK_LENGTH=45; }; } //namespace #endif ugene-1.9.8/src/corelibs/U2Formats/src/SAMFormat.cpp0000644000175000017500000004551111651544332020623 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "SAMFormat.h" #include "DocumentFormatUtils.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include namespace U2 { const QByteArray SAMFormat::VERSION = "1.0"; const QByteArray SAMFormat::SAM_SECTION_START = "@"; const QByteArray SAMFormat::SECTION_HEADER = "@HD"; const QByteArray SAMFormat::SECTION_SEQUENCE = "@SQ"; const QByteArray SAMFormat::SECTION_READ_GROUP = "@RG"; const QByteArray SAMFormat::SECTION_PROGRAM = "@PG"; const QByteArray SAMFormat::SECTION_COMMENT = "@CO"; const QByteArray SAMFormat::TAG_VERSION = "VN"; const QByteArray SAMFormat::TAG_SORT_ORDER = "SO"; const QByteArray SAMFormat::TAG_GROUP_ORDER = "GO"; const QByteArray SAMFormat::TAG_SEQUENCE_NAME = "SN"; const QByteArray SAMFormat::TAG_SEQUENCE_LENGTH = "LN"; const QByteArray SAMFormat::TAG_GENOME_ASSEMBLY_ID = "AS"; const QByteArray SAMFormat::TAG_SEQUENCE_MD5_SUM = "M5"; const QByteArray SAMFormat::TAG_SEQUENCE_URI = "UR"; const QByteArray SAMFormat::TAG_SEQUENCE_SPECIES = "SP"; const SAMFormat::Field SAMFormat::samFields[] = { //alignment section fields excluding optional tags Field("QNAME", "[ !-?A-~]+"), Field("FLAG", "[0-9]+"), Field("RNAME", "\\*|[!-()+-<>-~][ !-~]*"), Field("POS", "[0-9]+"), Field("MAPQ", "[0-9]+"), Field("CIGAR", "([0-9]+[MIDNSHP])+|\\*"), Field("RNEXT", "\\*|=|[!-()+-<>-~][!-~]*"), Field("PNEXT", "[0-9]+"), Field("TLEN", "-?[0-9]+"), Field("SEQ", "\\*|[A-Za-z=.]+"), Field("QUAL", "[!-~]+|\\*") }; bool SAMFormat::validateField(int num, QByteArray &field, TaskStateInfo *ti) { if(!samFields[num].getPattern().exactMatch(field)) { if(ti != NULL) { ti->setError(SAMFormat::tr("Field \"%1\" not matched pattern \"%2\", expected pattern \"%3\"").arg(samFields[num].name).arg(QString(field)).arg(samFields[num].getPattern().pattern())); } return false; } return true; } SAMFormat::SAMFormat( QObject* p ): DocumentFormat(p, DocumentFormatFlags_SW, QStringList()<< "sam") { formatName = tr("SAM"); supportedObjectTypes+=GObjectTypes::MULTIPLE_ALIGNMENT; skipDetection = false; } RawDataCheckResult SAMFormat::checkRawData( const QByteArray& rawData, const GUrl&) const { if (skipDetection) { return FormatDetection_NotMatched; } QRegExp rx("^@[A-Za-z][A-Za-z](\\t[A-Za-z][A-Za-z]:[ -~]+)"); //try to find SAM header if(rx.indexIn(rawData) != 0) { // if no header try to parse first alignment line QList fieldValues = rawData.split(SPACE); int readFieldsCount = fieldValues.count(); for(int i=0; i < qMin(11, readFieldsCount); i++) { if(!validateField(i, fieldValues[i])) { return FormatDetection_NotMatched; } } return FormatDetection_HighSimilarity; } return FormatDetection_VeryHighSimilarity; } static void prepareRead(const QByteArray& core, const QByteArray& quality, QByteArray& seq, QByteArray& qual, QByteArray& cigar) { bool gap = true; int lastCigarPos = 0; QList cigarTokens; for(int i = 0, coreLen = core.length(); i < coreLen; i++) { char c = core[i]; if(c == MAlignment_GapChar) { if(!gap) { if(i != lastCigarPos) { cigarTokens.append(U2CigarToken(U2CigarOp_M, i - lastCigarPos)); } gap = true; lastCigarPos = i; } } else { seq.push_back(c); if(!quality.isEmpty()) { qual.push_back(DNAQuality::encode(quality[i], DNAQualityType_Sanger)); } if(gap) { if(i != lastCigarPos) { cigarTokens.append(U2CigarToken(U2CigarOp_N, i - lastCigarPos)); } gap = false; lastCigarPos = i; } } } if(lastCigarPos != core.length() - 1) { cigarTokens.append(U2CigarToken(gap ? U2CigarOp_N : U2CigarOp_M, core.length() - 1 - lastCigarPos)); } if(cigarTokens.isEmpty()) { cigar = QByteArray("*"); } else { foreach(U2CigarToken token, cigarTokens) { assert(token.count != 0); cigar.append(QString::number(token.count)); switch(token.op) { case U2CigarOp_M: cigar.append("M"); break; case U2CigarOp_N: cigar.append("N"); break; default:; } } } } Document* SAMFormat::loadDocument( IOAdapter* io, TaskStateInfo& ti, const QVariantMap& _fs, DocumentLoadMode mode /*= DocumentLoadMode_Whole*/ ) { Q_UNUSED(mode); if( NULL == io || !io->isOpen() ) { ti.setError(L10N::badArgument("IO adapter")); return NULL; } QList objects; QVariantMap fs = _fs; QString lockReason; QMap maMap; //file may contain multiple MA objects MAlignment defaultMA("Alignment " + io->getURL().baseFileName()); QByteArray readBuffer(READ_BUFF_SIZE, '\0'); char* buff = readBuffer.data(); bool lineOk = false; QByteArray fields[11]; int len = 0; while(!ti.cancelFlag && (len = io->readLine(buff, READ_BUFF_SIZE, &lineOk)) > 0) { QByteArray line = QByteArray::fromRawData( buff, len ); if(line.startsWith(SAM_SECTION_START)) { //Parse sections QList tags; if(getSectionTags(line, SECTION_SEQUENCE, tags)) { //Parse sequence section foreach(QByteArray tag, tags) { if(tag.startsWith(TAG_SEQUENCE_NAME)) { // Set alignment name QString maName = QByteArray::fromRawData(tag.constData() + 3, tag.length() - 3); MAlignment ma; ma.setName(maName); maMap[maName] = ma; } } } else if(getSectionTags(line, SECTION_HEADER, tags)) { //Parse header section foreach(QByteArray tag, tags) { if(tag.startsWith(TAG_VERSION)) { //Check file format version QByteArray versionStr = QByteArray::fromRawData(tag.constData() + 3, tag.length() - 3); QList version = versionStr.split('.'); if(version[0].toInt() != 1 && version[1].toInt() > 3) { ti.setError(SAMFormat::tr("Unsupported file version \"%1\"").arg(QString(versionStr))); return NULL; } } } } // Skip other sections continue; } QList fieldValues = line.split(SPACE); int readFieldsCount = fieldValues.count(); //if(readFieldsCount < 11) readFieldsCount--; QBitArray terminators = TextUtils::WHITES | TextUtils::LINE_BREAKS; char lastTerminator = lineOk ? '\n' : 0; while(readFieldsCount < 11 && (len = io->readUntil(buff, READ_BUFF_SIZE, terminators, IOAdapter::Term_Include, &lineOk)) > 0) { QByteArray addline = QByteArray::fromRawData( buff, len - 1 ).simplified(); fieldValues[readFieldsCount - 1].append(addline); lastTerminator = buff[len-1]; if(lineOk) break; else { fieldValues[readFieldsCount - 1].append(lastTerminator); } } { bool merge = readFieldsCount < 11 ? false : true; /*if(readFieldsCount < 11)*/ { while(!TextUtils::LINE_BREAKS.at(lastTerminator) && (len = io->readUntil(buff, READ_BUFF_SIZE, terminators, IOAdapter::Term_Include, &lineOk)) > 0) { if(!lineOk) { len++; } QByteArray addline = QByteArray::fromRawData( buff, len - 1).simplified(); if(merge) { fieldValues[readFieldsCount - 1].append(addline); } else { fieldValues.append(addline); readFieldsCount++; } lastTerminator = buff[len - 1]; merge = !lineOk; } } // skiping optional tags if(!TextUtils::LINE_BREAKS.at(lastTerminator)) while((len = io->readLine(buff, READ_BUFF_SIZE, &lineOk)) > 0 && !lineOk); } if(readFieldsCount < 11) { ti.setError(SAMFormat::tr("Unexpected end of file")); return NULL; } for(int i=0; i < qMin(11, readFieldsCount); i++) { fields[i] = fieldValues[i]; if(!validateField(i, fields[i], &ti)) { return NULL; } } QString rname = fields[2]; if(rname != "*" && !maMap.contains(rname)) { //ioLog.info(SAMFormat::tr("Reference sequence \"%1\" not present in @SQ header").arg(rname)); rname = "*"; } MAlignmentRow row; short flag = fields[1].toShort(); bool isReversed = flag & 0x0010; row.setName(fields[0]); if(fields[9] == "*") { row.setSequence("", 0); } else { if(isReversed) { QByteArray &seq = fields[9]; DNAAlphabet *al = AppContext::getDNAAlphabetRegistry()->findAlphabet(seq); if(al == NULL) { ti.setError(SAMFormat::tr("Can't find alphabet for sequence \"%1\"").arg(QString(seq))); return NULL; } DNATranslation* tr = AppContext::getDNATranslationRegistry()->lookupComplementTranslation(al); if(tr == NULL) { ti.setError(SAMFormat::tr("Can't translation for alphabet \"%1\"").arg(al->getName())); return NULL; } TextUtils::translate(tr->getOne2OneMapper(), seq.data(), seq.size()); TextUtils::reverse(seq.data(), seq.size()); row.setSequence(seq, fields[3].toInt()-1); } else { row.setSequence(fields[9], fields[3].toInt()-1); } } if(fields[10] != "*") { if(isReversed) { QByteArray &seq = fields[10]; TextUtils::reverse(seq.data(), seq.size()); row.setQuality(DNAQuality(seq)); } else row.setQuality(DNAQuality(fields[10])); } if(rname == "*") { defaultMA.addRow(row); } else { maMap[rname].addRow(row); } ti.progress = io->getProgress(); } foreach(MAlignment ma, maMap.values()) { DocumentFormatUtils::assignAlphabet(ma); if (ma.getAlphabet() == NULL) { ti.setError( SAMFormat::tr("Alphabet is unknown")); return NULL; } objects.append(new MAlignmentObject(ma)); } if(defaultMA.getRows().count() != 0) { DocumentFormatUtils::assignAlphabet(defaultMA); if (defaultMA.getAlphabet() == NULL) { ti.setError( SAMFormat::tr("Alphabet is unknown")); return NULL; } objects.append(new MAlignmentObject(defaultMA)); } if (ti.hasError() || ti.cancelFlag) { qDeleteAll(objects); return NULL; } DocumentFormatUtils::updateFormatSettings(objects, fs); Document* doc = new Document(this, io->getFactory(), io->getURL(), objects, fs, lockReason); return doc; } void SAMFormat::storeDocument( Document* d, TaskStateInfo& ts, IOAdapter* io ) { //TODO: sorting options? if( NULL == d ) { ts.setError(L10N::badArgument("doc")); return; } if( NULL == io || !io->isOpen() ) { ts.setError(L10N::badArgument("IO adapter")); return; } QList maList; foreach(GObject *obj, d->findGObjectByType(GObjectTypes::MULTIPLE_ALIGNMENT)) { const MAlignmentObject* maObj = qobject_cast(obj); assert(maObj != NULL); maList.append(maObj); } QByteArray tab = "\t"; QByteArray block; //Writing header block.append(SECTION_HEADER).append("\t").append("VN:").append(VERSION).append("\n"); if (io->writeBlock( block ) != block.length()) { throw 0; } //Writing sequence section foreach(const MAlignmentObject* maObj, maList) { const MAlignment &ma = maObj->getMAlignment(); block.clear(); block.append(SECTION_SEQUENCE).append(tab).append(TAG_SEQUENCE_NAME).append(":").append(ma.getName().replace(QRegExp("\\s|\\t"), "_")) .append(tab).append(TAG_SEQUENCE_LENGTH).append(":").append(QByteArray::number(ma.getLength())).append("\n"); if (io->writeBlock( block ) != block.length()) { throw 0; } } //Writing alignment section foreach(const MAlignmentObject* maObj, maList) { const MAlignment &ma = maObj->getMAlignment(); QByteArray rname(ma.getName().replace(QRegExp("\\s|\\t"), "_").toAscii()); foreach(MAlignmentRow row, ma.getRows()) { block.clear(); //const QByteArray &core = row.getCore(); QByteArray qname = QString(row.getName()).replace(QRegExp("\\s|\\t"), "_").toAscii(); QByteArray flag("0"); // can contains strand, mapped/unmapped, etc. QByteArray pos = QByteArray::number(row.getCoreStart()+1); QByteArray mapq("255"); //255 indicating the mapping quality is not available QByteArray mrnm("*"); QByteArray mpos("0"); QByteArray isize("0"); QByteArray seq; QByteArray qual; QByteArray cigar; prepareRead(row.getCore(), row.getCoreQuality().qualCodes, seq, qual, cigar); if (row.hasQuality()) { row.getCoreQuality().qualCodes; } else { qual.reserve(seq.length()); qual.fill('I', seq.length()); } block = qname + tab + flag + tab+ rname + tab + pos + tab + mapq + tab + cigar + tab + mrnm + tab + mpos + tab + isize + tab + seq + tab + qual + "\n"; if (io->writeBlock( block ) != block.length()) { throw 0; } } } } bool SAMFormat::getSectionTags( QByteArray &line, const QByteArray §ionName, QList &tags ) { if(!line.startsWith(sectionName)) return false; QByteArray tagsLine = QByteArray::fromRawData(line.constData() + 3, line.length() - 3); tags = tagsLine.split(SPACE); return true; } bool SAMFormat::storeHeader(IOAdapter* io, const QVector &names, const QVector &lengths) { assert(names.size() > 0); assert(names.size() == lengths.size()); static const QByteArray TAB = "\t"; QByteArray block; block.append(SECTION_HEADER).append(TAB).append("VN:").append(VERSION).append("\n"); for (int i=0; iwriteBlock( block ) != block.length()) { return false; } block.clear(); return true; } bool SAMFormat::storeAlignedRead(int offset, const DNASequence& read, IOAdapter* io, const QByteArray& refName, int refLength, bool first, bool useCigar, const QByteArray &cigar) { static const QByteArray TAB = "\t"; static const QByteArray flag("0"); // can contains strand, mapped/unmapped, etc. static const QByteArray mapq("255"); //255 indicating the mapping quality is not available static const QByteArray mrnm("*"); static const QByteArray mpos("0"); static const QByteArray isize("0"); static const QString rowDataNotCigar = "%1" + TAB + flag + TAB + "%2" + TAB + "%3" + TAB + mapq + TAB + "%4M" + TAB + mrnm + TAB + mpos + TAB + isize + TAB + "%5" + TAB + "%6" + "\n"; static const QString rowDataCigar = "%1" + TAB + flag + TAB + "%2" + TAB + "%3" + TAB + mapq + TAB + "%4" + TAB + mrnm + TAB + mpos + TAB + isize + TAB + "%5" + TAB + "%6" + "\n"; if( NULL == io || !io->isOpen() ) { return false; } if (first) { QByteArray block; block.append(SECTION_HEADER).append(TAB).append("VN:").append(VERSION).append("\n"); block.append(SECTION_SEQUENCE).append(TAB).append(TAG_SEQUENCE_NAME).append(":"); block.append(refName).append(TAB); block.append(TAG_SEQUENCE_LENGTH).append(":").append(QByteArray::number(refLength)).append("\n"); if (io->writeBlock( block ) != block.length()) { return false; } block.clear(); } QByteArray qname = QString(read.getName()).replace(QRegExp("\\s|\\t"), "_").toAscii(); if (qname.isEmpty()) { qname = "contig"; } QByteArray qual; if (read.hasQualityScores()) { qual = read.quality.qualCodes; } else { qual.fill('I', read.seq.length()); } QString row; if (useCigar) { row = rowDataCigar.arg(qname.constData()) .arg(refName.constData()) .arg(offset+1) .arg(cigar.constData()) .arg(read.seq.constData()) .arg(qual.constData()); } else { row = rowDataNotCigar.arg(qname.constData()) .arg(refName.constData()) .arg(offset+1) .arg(read.seq.length()) .arg(read.seq.constData()) .arg(qual.constData()); } if (io->writeBlock(row.toAscii()) != row.length()) { return false; } return true; } }// namespace ugene-1.9.8/src/corelibs/U2Formats/src/DocumentFormatUtils.h0000644000175000017500000000520711651544332022445 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_DOCUMENT_FORMAT_UTILS_H_ #define _U2_DOCUMENT_FORMAT_UTILS_H_ #include #include namespace U2 { class Document; class DocumentFormat; class DNAAlphabet; class DNASequenceObject; class GObject; class MAlignment; class DNASequence; class GUrl; class AnnotationSettings; class U2OpStatus; class U2FORMATS_EXPORT DocumentFormatUtils : public QObject { Q_OBJECT public: static DNASequenceObject* addSequenceObject(QList& objects, const QString& name, DNASequence& seq, const QVariantMap& hints, U2OpStatus& os); /** if no docURL provided -> relations are not set*/ static DNASequenceObject* addMergedSequenceObject(QList& objects, const GUrl& docUrl, const QStringList& contigs, QByteArray& mergedSequence, const QVector& mergedMapping, const QVariantMap& hints, U2OpStatus& os); static DNAAlphabet* findAlphabet(const QByteArray& arr); static QList findAlphabets(const QByteArray& arr); static DNAAlphabet* findAlphabet(const QByteArray& arr, const QVector& regionsToProcess); static void trySqueeze(QByteArray& a); static int getIntSettings(const QVariantMap& fs, const char* sName, int defVal); static void updateFormatSettings(QList& objects, QVariantMap& fs); static QList toIds(const QList& formats); static void assignAlphabet(MAlignment& ma); static void assignAlphabet(MAlignment& ma, char ignore); static QList predefinedSettings(); /** Extracts sequences either from Sequence or MAlignment object */ static QList toSequences(const GObject* obj); static int getMergeGap(const QVariantMap& hints); }; }//namespace #endif ugene-1.9.8/src/corelibs/U2Formats/src/SAMFormat.h0000644000175000017500000001037511651544332020270 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _SAM_FORMAT_H #define _SAM_FORMAT_H #include #include namespace U2 { class IOAdapter; class DNASequence; class U2FORMATS_EXPORT SAMFormat : public DocumentFormat { Q_OBJECT public: SAMFormat(QObject* p = NULL); virtual DocumentFormatId getFormatId() const {return BaseDocumentFormats::SAM;} virtual const QString& getFormatName() const {return formatName;} virtual Document* loadDocument( IOAdapter* io, TaskStateInfo& ti, const QVariantMap& fs, DocumentLoadMode mode = DocumentLoadMode_Whole); virtual void storeDocument( Document* d, TaskStateInfo& ts, IOAdapter* io ); virtual RawDataCheckResult checkRawData(const QByteArray& rawData, const GUrl& = GUrl()) const; bool storeHeader(IOAdapter* io, const QVector &names, const QVector &lengths); bool storeAlignedRead(int offset, const DNASequence& read, IOAdapter* io, const QByteArray& refName, int refLength, bool first, bool useCigar = false, const QByteArray &cigar = ""); /** Temporary method to avoid conflict of SAM and importer */ void setNeverDetect(bool val) {skipDetection = val;} class Field { public: Field(QString _name, QString _pattern): name(_name), precompiled(_pattern) {} QString name; QRegExp getPattern() const { return QRegExp(precompiled); } private: const QRegExp precompiled; }; private: static bool getSectionTags(QByteArray &line, const QByteArray §ionName, QList &tags); static bool validateField(int num, QByteArray &field, TaskStateInfo *ti = NULL); static const QByteArray VERSION; static const QByteArray SAM_SECTION_START; static const QByteArray SECTION_HEADER; //Header static const QByteArray SECTION_SEQUENCE; //Sequence dictionary static const QByteArray SECTION_READ_GROUP; //read group static const QByteArray SECTION_PROGRAM; //Program static const QByteArray SECTION_COMMENT; //comment static const QByteArray TAG_VERSION; //File format version. static const QByteArray TAG_SORT_ORDER; //Sort order. Valid values are: unsorted, queryname or coordinate. static const QByteArray TAG_GROUP_ORDER; //Group order (full sorting is not imposed in a group). Valid values are: none, query or reference. static const QByteArray TAG_SEQUENCE_NAME; //Sequence name. Unique among all sequence records in the file. The value of this field is used in alignment records. static const QByteArray TAG_SEQUENCE_LENGTH; //Sequence length. static const QByteArray TAG_GENOME_ASSEMBLY_ID; //Genome assembly identifier. Refers to the reference genome assembly in an unambiguous form. Example: HG18. static const QByteArray TAG_SEQUENCE_MD5_SUM; //MD5 checksum of the sequence in the uppercase (gaps and space are removed) static const QByteArray TAG_SEQUENCE_URI; //URI of the sequence static const QByteArray TAG_SEQUENCE_SPECIES; //Species. static const int READ_BUFF_SIZE = 1024; static const char SPACE = '\t'; static const Field samFields[]; /* static const TAG_READ_GROUP_ID = "ID"; static const TAG_READ_GROUP_SAMPLE = "SM"; static const TAG_READ_GROUP_LIBRARY = "LB"; static const TAG_READ_GROUP_DESCRIPTION = "DS"; static const TAG_READ_GROUP_PLATFORM = "PU"; */ QString formatName; bool skipDetection; }; } //namespace #endif //_SAM_FORMAT_H ugene-1.9.8/src/corelibs/U2Formats/src/GFFFormat.cpp0000644000175000017500000004375211651544332020612 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "GFFFormat.h" #include "DocumentFormatUtils.h" #include #include #include #include #include #include #include #include #include #include namespace U2{ #define READ_BUFF_SIZE 4096 //file reader buffer size #define SEQUENCE_TAG " sequence" //tag for sequence object #define FEATURES_TAG " features" //tag for annotation table #define LINE_LEN 70 //line length for GFFFormat::GFFFormat(QObject* p):DocumentFormat(p, DocumentFormatFlags_SW, QStringList("gff")){ formatName = tr("GFF"); supportedObjectTypes+=GObjectTypes::ANNOTATION_TABLE; supportedObjectTypes+=GObjectTypes::SEQUENCE; } Document* GFFFormat::loadDocument( IOAdapter* io, TaskStateInfo& ti, const QVariantMap& fs, DocumentLoadMode){ if( NULL == io || !io->isOpen() ) { ti.setError(L10N::badArgument("IO adapter")); return NULL; } QList objects; load(io, objects, fs, ti); if (ti.hasError() || ti.cancelFlag) { qDeleteAll(objects); return NULL; } Document* doc = new Document( this, io->getFactory(), io->getURL(), objects); return doc; } int readLongLine(QString &buffer, IOAdapter* io, gauto_array &charbuff){ int len; buffer.clear(); do { len = io->readLine(charbuff.data, READ_BUFF_SIZE -1); charbuff.data[len] = '\0'; buffer.append(QString(charbuff.data)); }while (len == READ_BUFF_SIZE - 1); return buffer.length(); } void validateHeader( QStringList words){ bool isOk = false; if(words.size() < 2){ ioLog.info(GFFFormat::tr("Parsing error: invalid header")); } words[0] = words[0].remove("#"); if(!words[0].startsWith("gff-version")){ ioLog.info(GFFFormat::tr("Parsing error: file does not contain version header")); }else{ int ver = words[1].toInt(&isOk); if(!isOk){ ioLog.info(GFFFormat::tr("Parsing error: format version is not an integer")); } //is version supported if(ver != 3){ ioLog.info(GFFFormat::tr("Parsing error: GFF version %1 is not supported").arg(ver)); } } } static QMap initEscapeCharactersMap() { QMap ret; ret[";"] = "%3B"; ret["="] = "%3D"; ret[","] = "%2C"; ret["\t"] = "%09"; ret["%"] = "%25"; return ret; } static const QMap escapeCharacters = initEscapeCharactersMap(); static QString escapeBadCharacters(const QString & val) { QString ret(val); foreach(const QString & key, escapeCharacters.keys()) { ret.replace(key, escapeCharacters.value(key)); } return ret; } static QString fromEscapedString( const QString & val ) { QString ret(val); foreach( const QString & val, escapeCharacters.values() ) { ret.replace(val, escapeCharacters.key(val)); } return ret; } void GFFFormat::load(IOAdapter* io, QList& objects, const QVariantMap& hints, TaskStateInfo& si){ gauto_array buff = new char[READ_BUFF_SIZE]; int len = io->readLine(buff.data, READ_BUFF_SIZE); buff.data[len] = '\0'; QString qstrbuf(buff.data); QStringList words = qstrbuf.split(QRegExp("\\s+")); bool isOk; QSet atoSet; QMap seqMap; //header validation validateHeader(words); int lineNumber = 1; QMap joinedAnnotations; bool fastaSectionStarts = false; QString headerName, objName; QByteArray seq; QSet names; while((len = readLongLine(qstrbuf, io, buff)) > 0){ words = parseLine(qstrbuf); if(fastaSectionStarts){ if(words[0].startsWith(">") && headerName.isEmpty()){ headerName = words.join(" ").remove(">"); }else if(words[0].startsWith(">")){ headerName = TextUtils::variate(headerName, "_", names); names.insert(headerName); objName = headerName + SEQUENCE_TAG; DNASequence sequence(objName, seq); sequence.info.insert(DNAInfo::FASTA_HDR, objName); sequence.info.insert(DNAInfo::ID, objName); DNASequenceObject *dnaso = DocumentFormatUtils::addSequenceObject(objects, objName, sequence, hints, si); if (si.hasError()) { return; } SAFE_POINT(dnaso != NULL, "DocumentFormatUtils::addSequenceObject returned NULL but didn't set error",); seqMap.insert(objName, dnaso); headerName = words.join(" ").remove(">"); seq = ""; } else { if(words.size() > 1){ si.setError(tr("Parsing error: sequence in FASTA sequence has whitespaces at line %1").arg(lineNumber)); return; } seq.append(words[0]); } } else if (!words[0].startsWith("#")){ if(words.size() != 9){ si.setError(tr("Parsing error: too few fields at line %1").arg(lineNumber)); return; } //annotation's region int start = words[3].toInt(&isOk); if(!isOk){ si.setError(tr("Parsing error: start position at line %1 is not integer").arg(lineNumber)); return; } int end = words[4].toInt(&isOk); if(!isOk){ si.setError(tr("Parsing error: end position at line %1 is not integer").arg(lineNumber)); return; } if(start > end){ si.setError(tr("Parsing error: incorrect annotation region at line %1").arg(lineNumber)); return; } start--; U2Region range(start, end - start); QString groupName = words[2]; QString annName = groupName; //by default annotation named as group //annotation's qualifiers from attributes SharedAnnotationData d(new AnnotationData()); Annotation *a = NULL; bool newJoined = false; QString id; if(words[8] != "."){ QStringList pairs = words[8].split(";", QString::SkipEmptyParts); foreach(QString p, pairs){ QStringList qual = p.split("=", QString::SkipEmptyParts); if(qual.size() != 2){ si.setError(tr("Parsing error: one of the qualifiers in attributes are incorrect at line %1").arg(lineNumber)); return; } qual[0] = fromEscapedString(qual[0]); qual[1] = fromEscapedString(qual[1]); if(qual[0] == "name"){ annName = qual[1]; }else{ d->qualifiers.append(U2Qualifier(qual[0], qual[1])); if(qual[0] == "ID"){ id = qual[1]; if(joinedAnnotations.contains(id)){ a = *(joinedAnnotations.find(id)); bool hasIntersections = range.findIntersectedRegion(a->getRegions())!=-1; if(hasIntersections){ ioLog.info(tr("Wrong location for joined annotation at line %1. Line was skipped.").arg(lineNumber)); } else { a->addLocationRegion(range); } }else{ newJoined = true; } } } } } //if annotation joined, don't rewrite it data if(a == NULL){ a = new Annotation(d); if(newJoined){ joinedAnnotations.insert(id, a); } a->addLocationRegion(range); a->setAnnotationName(annName); QString atoName = words[0] + FEATURES_TAG; AnnotationTableObject *ato = NULL; foreach(GObject *ob, objects){ if(ob->getGObjectName() == atoName){ ato = (AnnotationTableObject *)ob; } } if(!ato){ ato = new AnnotationTableObject(atoName); objects.append(ato); atoSet.insert(ato); } //qualifiers from columns if(words[1] != "."){ a->addQualifier("source", words[1]); } if(words[5] != "."){ a->addQualifier("score", words[5]); } if(words[7] != "."){ a->addQualifier("phase", words[7]); } //strand detection if(words[6] == "-"){ a->setStrand(U2Strand::Complementary); } ato->addAnnotation(a, groupName); } }else{ if(words[0].startsWith("##fasta", Qt::CaseInsensitive)){ fastaSectionStarts = true; } } lineNumber++; } //handling last fasta sequence if(fastaSectionStarts){ headerName = TextUtils::variate(headerName, "_", names); names.insert(headerName); objName = headerName + SEQUENCE_TAG; DNASequence sequence(objName, seq); sequence.info.insert(DNAInfo::FASTA_HDR, objName); sequence.info.insert(DNAInfo::ID, objName); DNASequenceObject *dnaso = DocumentFormatUtils::addSequenceObject(objects, objName, sequence, hints, si); if (si.hasError()) { qDeleteAll(seqMap.values()); seqMap.clear(); return; } SAFE_POINT(dnaso != NULL, "DocumentFormatUtils::addSequenceObject returned NULL but didn't set error",); seqMap.insert(objName, dnaso); } //linking annotation tables with corresponding sequences foreach(AnnotationTableObject *ob, atoSet){ QString objName = ob->getGObjectName(); objName.replace(FEATURES_TAG, SEQUENCE_TAG); if(seqMap.contains(objName)){ GObjectReference sequenceRef(GObjectReference(io->getURL().getURLString(), "", GObjectTypes::SEQUENCE)); sequenceRef.objName = objName; ob->addObjectRelation(GObjectRelation(sequenceRef, GObjectRelationRole::SEQUENCE)); } } } RawDataCheckResult GFFFormat::checkRawData(const QByteArray& rawData, const GUrl&) const { const char* data = rawData.constData(); int size = rawData.size(); int n = TextUtils::skip(TextUtils::WHITES, data, size); int newSize = size - n; bool hasBinaryData = TextUtils::contains(TextUtils::BINARY, data, size); if(hasBinaryData){ return FormatDetection_NotMatched; } if (newSize <= 13) { return FormatDetection_NotMatched; } QString header(rawData); header = header.remove("#"); FormatDetectionScore res = FormatDetection_NotMatched; if(header.startsWith("gff-version")){ res = FormatDetection_Matched; } QString dataStr(rawData); QStringList qsl = dataStr.split("\n"); foreach(QString str, qsl){ if(!str.startsWith("#")){ QStringList l = parseLine(str); if(l.size() == 9){ bool b3, b4; l[3].toInt(&b3); l[4].toInt(&b4); if (b3 && b4){ res = qMax(res, FormatDetection_HighSimilarity) ; } else { return FormatDetection_NotMatched; } } } } return res; } QString normalizeQualifier(QString qual){ QRegExp rx(" +"); if(qual.contains(rx)){ qual.replace(rx, " "); } return qual; } QStringList GFFFormat::parseLine( QString line ) const{ QChar prev('a'); //as default value not empty char QString pair; QStringList result; QString word; foreach(QChar c, line){ pair.clear(); pair.append(prev); pair.append(c); if((c == '\t') || (pair == " \t") || (pair == " ")){ if((word != " ") && (word != " ") && !word.isEmpty()){ result.append(word); } word.clear(); }else{ word.append(c); } prev = c; } if((word != " ") && (word != " ") && !word.isEmpty()){ result.append(word); } return result; } void GFFFormat::storeDocument( Document* doc, TaskStateInfo& si, IOAdapter* io ){ QByteArray header("##gff-version\t3\n"); qint64 len = io->writeBlock(header); if (len!=header.size()) { si.setError(L10N::errorWritingFile(doc->getURL())); return; } QByteArray qbaRow; QList atos = doc->findGObjectByType(GObjectTypes::ANNOTATION_TABLE); int joinID = 0; QSet knownIDs; QStringList cleanRow; for(int i = 0; i != 9; i++){ cleanRow.append("."); } foreach(GObject *ato , atos){ QList aList = (qobject_cast(ato))->getAnnotations(); //retrieving known IDs foreach(const Annotation *ann, aList){ if(ann->isValidQualifierName("ID")){ knownIDs.insert(ann->findFirstQualifierValue("ID")); } } foreach(const Annotation *ann, aList){ QStringList row = cleanRow; QVector location = ann->getRegions(); QVector qualVec = ann->getQualifiers(); //generating unique ID for joined annotation if((location.size() > 1) && !ann->isValidQualifierName("ID")){ for(;knownIDs.contains(QString::number(joinID));joinID++); qualVec.append(U2Qualifier("ID", QString::number(joinID))); } foreach(const U2Region r, location){ QString name = ato->getGObjectName(); row[0] = name.left(name.size() - QString(FEATURES_TAG).size()); //removing previously added tag //filling strand field if(ann->getStrand().isCompementary()){ row[6] = "-"; } //filling location fields row[3] = QString::number(r.startPos + 1); row[4] = QString::number(r.endPos()); row[2] = (ann->getGroups().first())->getGroupName(); QString additionalQuals = "name=" + escapeBadCharacters(ann->getAnnotationName()); //filling fields with qualifiers data foreach(U2Qualifier q, qualVec){ if(q.name == "source"){ row[1] = normalizeQualifier(q.value); }else if(q.name == "score"){ row[5] = normalizeQualifier(q.value); }else if(q.name == "phase"){ row[7] = normalizeQualifier(q.value); }else{ additionalQuals.append(";" + escapeBadCharacters(q.name) + "=" + escapeBadCharacters(normalizeQualifier(q.value))); } } row[8] = additionalQuals; qbaRow = row.join("\t").toAscii() + "\n"; qint64 len = io->writeBlock(qbaRow); if (len!=qbaRow.size()) { si.setError(L10N::errorWritingFile(doc->getURL())); return; } } } } QList sequences = doc->findGObjectByType(GObjectTypes::SEQUENCE); if(!sequences.isEmpty()){ qbaRow = "##FASTA\n"; if (io->writeBlock(qbaRow) != qbaRow.size()) { si.setError(L10N::errorWritingFile(doc->getURL())); return; } foreach(GObject *s, sequences){ DNASequenceObject *dnaso = qobject_cast(s); QString fastaHeader = dnaso->getGObjectName(); int tagSize = QString(SEQUENCE_TAG).size(), headerSize = fastaHeader.size(); fastaHeader = fastaHeader.left(headerSize - tagSize); //removing previously added tag fastaHeader.prepend(">"); fastaHeader.append( '\n' ); qbaRow = fastaHeader.toAscii(); if (io->writeBlock(qbaRow) != qbaRow.size()) { si.setError(L10N::errorWritingFile(doc->getURL())); return; } const char* seq = dnaso->getSequence().constData(); int len = dnaso->getSequence().length(); for (int i = 0; i < len; i += LINE_LEN ) { int chunkSize = qMin( LINE_LEN, len - i ); if (io->writeBlock( seq + i, chunkSize ) != chunkSize || !io->writeBlock( "\n", 1 )) { si.setError(L10N::errorWritingFile(doc->getURL())); return; } } } } } } //namespace ugene-1.9.8/src/corelibs/U2Formats/src/ABIFormat.h0000644000175000017500000000326411651544332020242 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_ABI_FORMAT_H_ #define _U2_ABI_FORMAT_H_ #include #include namespace U2 { class IOAdapter; class SeekableBuf; class U2OpStatus; class U2FORMATS_EXPORT ABIFormat : public DocumentFormat { Q_OBJECT public: ABIFormat(QObject* p); virtual DocumentFormatId getFormatId() const {return BaseDocumentFormats::ABIF;} virtual const QString& getFormatName() const {return formatName;} virtual Document* loadDocument(IOAdapter* io, TaskStateInfo& ti, const QVariantMap& fs, DocumentLoadMode mode = DocumentLoadMode_Whole); virtual RawDataCheckResult checkRawData(const QByteArray& rawData, const GUrl& = GUrl()) const; private: Document* parseABI(SeekableBuf*, IOAdapter* io, const QVariantMap& fs, U2OpStatus& os); QString formatName; }; }//namespace #endif ugene-1.9.8/src/corelibs/U2Formats/src/PDWFormat.cpp0000644000175000017500000002020711651544332020630 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "PDWFormat.h" #include "DocumentFormatUtils.h" #include #include #include #include #include #include #include #include #include #include namespace U2 { /* TRANSLATOR U2::FastaFormat */ /* TRANSLATOR U2::IOAdapter */ /* TRANSLATOR U2::Document */ #define PDW_FORMAT_TAG "VERSION pDRAW 1.0" #define PDW_SEQUENCE_TAG "Sequence .." #define PDW_DNANAME_TAG "DNAname" #define PDW_ELEMENT_TAG "Element" #define PDW_ANNOTATION_TAG "Annotation" #define PDW_CIRCULAR_TAG "IScircular" PDWFormat::PDWFormat(QObject* p) : DocumentFormat(p, DocumentFormatFlag(0), QStringList()<<"pdw") { formatName = tr("pDRAW"); supportedObjectTypes+=GObjectTypes::SEQUENCE; supportedObjectTypes+=GObjectTypes::ANNOTATION_TABLE; } RawDataCheckResult PDWFormat::checkRawData(const QByteArray& rawData, const GUrl&) const { const char* data = rawData.constData(); int size = rawData.size(); if (!rawData.startsWith(PDW_FORMAT_TAG)) { return FormatDetection_NotMatched; } bool hasBinaryBlocks = TextUtils::contains(TextUtils::BINARY, data, size); return hasBinaryBlocks ? FormatDetection_NotMatched : FormatDetection_HighSimilarity; } #define READ_BUFF_SIZE 4096 void PDWFormat::load(IOAdapter* io, const GUrl& docUrl, QList& objects, TaskStateInfo& ti, DNASequenceObject* dnaObj, AnnotationTableObject* aObj) { QByteArray readBuff(READ_BUFF_SIZE+1, 0); char* buff = readBuff.data(); qint64 len = 0; bool lineOk = false; bool isCircular = false; QString dnaName(docUrl.baseFileName()); QList annotations; while (!ti.cancelFlag) { //read header len = io->readUntil(buff, READ_BUFF_SIZE, TextUtils::LINE_BREAKS, IOAdapter::Term_Include, &lineOk); if (len == 0) { //end if stream break; } if (!lineOk) { ti.setError(PDWFormat::tr("Line is too long")); } if (readBuff.startsWith(PDW_DNANAME_TAG)) { dnaName = readPdwValue(readBuff, PDW_DNANAME_TAG); } else if (readBuff.startsWith(PDW_SEQUENCE_TAG)) { QByteArray seq = parseSequence(io, ti); DNAAlphabet* alphabet = AppContext::getDNAAlphabetRegistry()->findAlphabet(seq); DNASequence dna(dnaName, seq , alphabet); if (isCircular) { DNALocusInfo loi; loi.topology = "circular"; loi.name = dnaName; dna.info.insert(DNAInfo::LOCUS, qVariantFromValue(loi)); } dnaObj = new DNASequenceObject(dnaName, dna); objects.append(dnaObj); break; } else if (readBuff.startsWith(PDW_CIRCULAR_TAG)) { QByteArray val = readPdwValue(readBuff, PDW_CIRCULAR_TAG); if (val == "YES") { isCircular = true; } } else if (readBuff.startsWith(PDW_ANNOTATION_TAG)) { Annotation* a = parseAnnotation(io, ti); assert(a != NULL); annotations.append(a); } } if (!annotations.isEmpty()) { aObj = new AnnotationTableObject(QString("%1 annotations").arg(dnaName)); aObj->addAnnotations(annotations); objects.append(aObj); } if (!ti.hasError() && !ti.cancelFlag && objects.isEmpty()) { ti.setError(Document::tr("Document is empty.")); } } Document* PDWFormat::loadDocument( IOAdapter* io, TaskStateInfo& ti, const QVariantMap& _fs, DocumentLoadMode mode) { Q_UNUSED(mode); DNASequenceObject* dnaObj = NULL; AnnotationTableObject* aObj = NULL; if( NULL == io || !io->isOpen() ) { ti.setError(L10N::badArgument("IO adapter")); return NULL; } QVariantMap fs = _fs; QList objects; load(io, io->getURL(), objects, ti, dnaObj, aObj); if (ti.hasError() || ti.cancelFlag) { qDeleteAll(objects); return NULL; } QString lockReason(DocumentFormat::CREATED_NOT_BY_UGENE); Document* doc = new Document(this, io->getFactory(), io->getURL(), objects, fs, lockReason); if ( (dnaObj != NULL) && (aObj != NULL)) { aObj->addObjectRelation(dnaObj, GObjectRelationRole::SEQUENCE); } return doc; } QByteArray PDWFormat::parseSequence( IOAdapter* io, TaskStateInfo& ti ) { QByteArray result; QByteArray readBuff(READ_BUFF_SIZE+1, 0); while (!ti.cancelFlag) { bool lineOk = false; qint64 len = io->readUntil(readBuff.data(), READ_BUFF_SIZE, TextUtils::LINE_BREAKS, IOAdapter::Term_Include, &lineOk); if (len == 0) { break; } if (!lineOk) { ti.setError(PDWFormat::tr("Line is too long")); } for (int i = 0; i < readBuff.size(); ++i) { char c = readBuff.at(i); if (c == '\n') { break; } if (c >= 'A' && c <= 'z') { result.append(c); } } } return result; } QByteArray PDWFormat::readPdwValue( const QByteArray& readBuf, const QByteArray& valueName ) { int startPos = valueName.length(); int endPos = readBuf.indexOf('\n'); return readBuf.mid(startPos, endPos - startPos + 1).trimmed(); } #define PDW_ANNOTATION_NUMBER "Annotation_Number" #define PDW_ANNOTATION_NAME "Annotation_Name" #define PDW_ANNOTATION_START "Annotation_Start" #define PDW_ANNOTATION_END "Annotation_End" #define PDW_ANNOTATION_ORIENT "Annotation_Orientation" Annotation* PDWFormat::parseAnnotation( IOAdapter* io, TaskStateInfo& ti ) { QByteArray readBuf(READ_BUFF_SIZE+1, 0); int startPos = -1, endPos = -1; QByteArray aName; bool cmpl = false; while (!ti.cancelFlag) { bool lineOk = false; qint64 len = io->readUntil(readBuf.data(), READ_BUFF_SIZE, TextUtils::LINE_BREAKS, IOAdapter::Term_Include, &lineOk); if (!readBuf.startsWith(PDW_ANNOTATION_TAG)) { break; } else if (readBuf.startsWith(PDW_ANNOTATION_NUMBER)) { io->skip(-len); break; } else if (readBuf.startsWith(PDW_ANNOTATION_NAME) ) { aName = readPdwValue(readBuf, PDW_ANNOTATION_NAME); if (aName.endsWith('\"')) { aName = aName.left(aName.length() - 1).trimmed(); } } else if (readBuf.startsWith(PDW_ANNOTATION_START) ) { startPos = readPdwValue(readBuf, PDW_ANNOTATION_START).toInt(); } else if (readBuf.startsWith(PDW_ANNOTATION_END) ) { endPos = readPdwValue(readBuf, PDW_ANNOTATION_END).toInt(); }else if (readBuf.startsWith(PDW_ANNOTATION_ORIENT) ) { int orientVal = readPdwValue(readBuf, PDW_ANNOTATION_ORIENT).toInt(); cmpl = orientVal == 0 ? true : false; } } SharedAnnotationData sd(new AnnotationData()); sd->name = aName; sd->location->regions << U2Region(startPos - 1, endPos - startPos + 1); sd->setStrand(cmpl ? U2Strand::Complementary : U2Strand::Direct); return new Annotation(sd); } }//namespace ugene-1.9.8/src/corelibs/U2Formats/src/GenbankPlainTextFormat.cpp0000644000175000017500000005642511651544332023407 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "GenbankPlainTextFormat.h" #include "GenbankLocationParser.h" #include "GenbankFeatures.h" #include "DocumentFormatUtils.h" #include #include #include #include #include #include #include #include #include #include #include #include namespace U2 { /* TRANSLATOR U2::GenbankPlainTextFormat */ /* TRANSLATOR U2::EMBLGenbankAbstractDocument */ /* TRANSLATOR U2::IOAdapter */ GenbankPlainTextFormat::GenbankPlainTextFormat(QObject* p) : EMBLGenbankAbstractDocument(BaseDocumentFormats::PLAIN_GENBANK, tr("Genbank"), 79, DocumentFormatFlags_SW, p) { formatDescription = tr("GenBank Flat File Format is a rich format for storing sequences and associated annotations"); fileExtensions << "gb" << "gbk" << "gen" << "genbank"; sequenceStartPrefix = "ORIGIN"; fPrefix = " "; } RawDataCheckResult GenbankPlainTextFormat::checkRawData(const QByteArray& rawData, const GUrl&) const { //TODO: improve handling const char* data = rawData.constData(); int size = rawData.size(); bool textOnly = !TextUtils::contains(TextUtils::BINARY, data, size); if (!textOnly || size < 100) { return FormatDetection_NotMatched; } bool startsWithLocus = TextUtils::equals("LOCUS ", data, 6); if (!startsWithLocus) { return FormatDetection_NotMatched; } RawDataCheckResult res(FormatDetection_VeryHighSimilarity); QByteArray seqStartPattern1 = "\n 1"; QByteArray seqStartPattern2 = "\nORIGIN"; res.properties[RawDataCheckResult_Sequence] = rawData.contains(seqStartPattern1) || rawData.contains(seqStartPattern2); bool multi = (rawData.indexOf(seqStartPattern1) != rawData.lastIndexOf(seqStartPattern1)) || (rawData.indexOf(seqStartPattern2) != rawData.lastIndexOf(seqStartPattern2)); res.properties[RawDataCheckResult_MultipleSequences] = multi; return res; } bool GenbankPlainTextFormat::readIdLine(ParserState* st) { if (!st->hasKey("LOCUS")) { st->si.setError(tr("LOCUS is not the first line")); return false; } QString locusStr = st->value(); QStringList tokens = locusStr.split(" ", QString::SkipEmptyParts); if (tokens.isEmpty()) { st->si.setError(tr("Error parsing LOCUS line")); return false; } // try improving name readability tokens[0] = tokens[0].replace(QRegExp("_(?![0-9])"), QChar(' ')); st->entry->name = tokens[0]; if (tokens.size() >= 3 && tokens[2] == "bp") { QString len = tokens[1]; st->entry->seqLen = len.toInt(); } if (tokens.size() == 7) { // seems to be canonical header DNALocusInfo loi; loi.name = tokens[0]; loi.topology = tokens[4]; loi.molecule = tokens[3]; loi.division = tokens[5]; loi.date = tokens[6]; st->entry->tags.insert(DNAInfo::LOCUS, qVariantFromValue(loi)); st->entry->circular = loi.topology == "circular"; } else { st->entry->tags.insert(DNAInfo::ID, tokens[0]); st->entry->tags.insert(DNAInfo::EMBL_ID, locusStr); st->entry->circular = locusStr.contains("circular"); } return true; } bool GenbankPlainTextFormat::readEntry(QByteArray& sequence, ParserState* st) { TaskStateInfo& si = st->si; QString lastTagName; bool hasLine = false; while (hasLine || st->readNextLine(true)) { hasLine = false; if (st->len == 0) { continue; } if (st->isNull()) { readIdLine(st); assert(si.hasError() || !st->entry->name.isEmpty()); continue; } if (st->hasKey("FEATURES") && st->readNextLine()) { readAnnotations(st, sequence.size()); hasLine = true; continue; } if (st->hasKey("SOURCE")) { DNASourceInfo soi; soi.name = st->value(); while (st->readNextLine() && st->hasContinuation()) { soi.name.append(st->value()); } if (st->hasKey(" ORGANISM")) { soi.organism = st->value(); while (st->readNextLine() && st->hasContinuation()) { soi.taxonomy.append(st->value()); } } else { st->si.setError(tr("incomplete SOURCE record")); break; } st->entry->tags.insertMulti(DNAInfo::SOURCE, qVariantFromValue(soi)); hasLine = true; continue; } if (st->hasKey("REFERENCE")) { while (st->readNextLine() && (st->hasValue() && st->buff[0] == ' ')) { //TODO } hasLine = true; continue; } if (st->hasKey("ACCESSION") || (st->hasContinuation() && lastTagName == "ACCESSION")) { QVariant v = st->entry->tags.value(DNAInfo::ACCESSION); st->entry->tags[DNAInfo::ACCESSION] = QVariantUtils::addStr2List(v, st->value().split(" ")); continue; } if (TextUtils::equals(st->buff, "//", 2)) { // end of entry return true; } if (st->hasKey("ORIGIN")) { if (st->hasValue()) { st->entry->tags.insert(DNAInfo::ORIGIN, st->value()); } if (st->readNextLine() && st->hasKey("CONTIG")) { QStringList s(st->value()); while (st->readNextLine() && st->hasContinuation()) { s.append(st->value()); } st->entry->tags.insert(DNAInfo::CONTIG, s); if (!TextUtils::equals(st->buff, "//", 2)) { break; } } else { if (st->len >0) { st->io->skip(-st->len - 1); } readSequence(sequence, st); } return true; } if (st->hasContinuation()) { QVariant v = st->entry->tags.take(lastTagName); v = QVariantUtils::addStr2List(v, st->value()); st->entry->tags.insert(lastTagName, v); } else if (st->hasValue()) { lastTagName = st->key().trimmed(); st->entry->tags.insertMulti(lastTagName, st->value()); } } if (!st->isNull() && !si.hasError() && !si.cancelFlag) { si.setError(U2::EMBLGenbankAbstractDocument::tr("Record is truncated.")); } return false; } ////////////////////////////////////////////////////////////////////////// /// saving static QString genLocusString(QList aos, DNASequenceObject* so); static void writeAnnotations(IOAdapter* io, QList aos, TaskStateInfo& si); static void writeSequence(IOAdapter* io, DNASequenceObject* ao, TaskStateInfo& si); static void prepareMultiline(QString& lineToChange, int spacesOnLineStart, bool newLineAtTheEnd = true, int maxLineLen = 79); #define VAL_OFF 12 static bool writeKeyword(IOAdapter* io, TaskStateInfo& si, const QString& key, const QString& value, bool wrap = true /*TODO*/) { Q_UNUSED(wrap); try { assert(key.length() < VAL_OFF); int klen = qMin(VAL_OFF - 1, key.length()); qint64 len = io->writeBlock(key.left(klen).toLocal8Bit()); if (len!=klen) { throw 0; } static char spaces[] = {' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' '}; int slen = VAL_OFF - klen; len = io->writeBlock(spaces, slen); if (len!=slen) { throw 0; } len = io->writeBlock(value.toLocal8Bit()); if (len!=value.size()) { throw 0; } static char eol[] = {'\n'}; if (!io->writeBlock(eol, 1)) { throw 0; } } catch( int ) { si.setError(GenbankPlainTextFormat::tr("Error writing document")); return false; } return true; } typedef QPair StrPair; static QList formatKeywords(DNASequenceObject* so) { QList res; QMultiMap tags(so->getDNASequence().info); tags.remove(DNAInfo::LOCUS); tags.remove(DNAInfo::ID); tags.remove(DNAInfo::CONTIG); tags.remove(DNAInfo::ORIGIN); tags.remove(EMBLGenbankAbstractDocument::UGENE_MARK); if (tags.contains(DNAInfo::ACCESSION)) { tags.insert(DNAInfo::ACCESSION, tags.take(DNAInfo::ACCESSION).toStringList().join(" ")); } QStringList order; order << DNAInfo::DEFINITION << DNAInfo::ACCESSION << DNAInfo::VERSION; order << DNAInfo::PROJECT << DNAInfo::KEYWORDS << DNAInfo::SEGMENT; foreach(const QString& key, order) { while (tags.contains(key)) { QVariant v = tags.take(key); if (v.canConvert(QVariant::String)) { res << qMakePair(key, v.toString()); } else if (v.canConvert(QVariant::StringList)) { QStringList l = v.toStringList(); if (l.size() == 0) { assert(0); continue; } res << qMakePair(key, l.takeFirst()); foreach(const QString& s, l) { res << qMakePair(QString(), s); } } else { assert(0); } } } { QString key = DNAInfo::SOURCE; while (tags.contains(key)) { QVariant v = tags.take(key); DNASourceInfo soi = v.value(); res << qMakePair(key, soi.name); if (!soi.organelle.isEmpty()) { res[res.size() - 1].second += " " + soi.organelle; } res << qMakePair(QString(" ORGANISM"), soi.organism); foreach(const QString& s, soi.taxonomy) { res << qMakePair(QString(), s); } } } { QString key = DNAInfo::REFERENCE; while (tags.contains(key)) { QVariant v = tags.take(key); DNAReferenceInfo ri = v.value(); //res << qMakePair(key, v.toString()); } } QMapIterator it(tags); while (it.hasNext()) { it.next(); if (it.value().type() == QVariant::String) { res << qMakePair(it.key(), it.value().toString()); } else if (it.value().type() == QVariant::StringList) { QStringList l = it.value().toStringList(); if (l.size() == 0) { assert(0); continue; } res << qMakePair(it.key(), l.takeFirst()); foreach(const QString& s, l) { res << qMakePair(QString(), s); } } else { assert(0); } } return res; } void GenbankPlainTextFormat::storeDocument( Document* doc, TaskStateInfo& si, IOAdapter* io ) { QList seqs = doc->findGObjectByType(GObjectTypes::SEQUENCE); QList anns = doc->findGObjectByType(GObjectTypes::ANNOTATION_TABLE); while (!seqs.isEmpty() || !anns.isEmpty()) { DNASequenceObject* so = seqs.isEmpty() ? NULL : static_cast(seqs.takeFirst()); QList aos; if (so) { if (!anns.isEmpty()) { aos = GObjectUtils::findObjectsRelatedToObjectByRole(so, GObjectTypes::ANNOTATION_TABLE, GObjectRelationRole::SEQUENCE, anns, UOF_LoadedOnly); foreach(GObject* o, aos) { anns.removeAll(o); } } } else { assert(!anns.isEmpty()); aos << anns.takeFirst(); } // write mandatory locus string QString locusString = genLocusString(aos, so); if (!writeKeyword(io, si, DNAInfo::LOCUS, locusString, false)) { return; } // write other keywords if (so) { QList lst(formatKeywords(so)); foreach (const StrPair& p, lst) { if (!writeKeyword(io, si, p.first, p.second)) { return; } } } //write tool mark QList annsAndSeqObjs; annsAndSeqObjs<getGObjectName(), false)) { return; } for (int x=1; x < annsAndSeqObjs.size(); x++) { if (!writeKeyword(io, si, QString(), annsAndSeqObjs[x]->getGObjectName(), false)) { return; } } } // write annotations if (!aos.isEmpty()) { writeAnnotations(io, aos, si); if (si.hasError()) { return; } } if (so) { //todo: store sequence alphabet! writeSequence(io, so, si); if (si.hasError()) { return; } } // write last line marker QByteArray lastLine("//\n"); qint64 len = io->writeBlock(lastLine); if (len!=lastLine.size()) { si.setError(L10N::errorWritingFile(doc->getURL())); return; } } } static QString getDate(){ const char* MonthsInEng[] = {" ", "JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC"}; return QDate::currentDate().toString("dd-") + MonthsInEng[QDate::currentDate().month()] + QDate::currentDate().toString("-yyyy"); } static QString padToLen(const QString& s, int width) { if (width > s.length()) { return s.leftJustified(width); } else { return s + " "; } } static QString genLocusString(QList aos, DNASequenceObject* so) { QString loc, date; if (so) { const DNASequence& dna = so->getDNASequence(); QString len = QString::number(dna.length()); loc = dna.getName(); if (loc.isEmpty()) { loc = so->getGObjectName(); } loc = padToLen(loc.replace(QChar(' '), QChar('_')), qMax(0, 28 - len.length())); loc.append(len).append(" bp "); if (dna.info.contains(DNAInfo::LOCUS)) { DNALocusInfo loi = dna.info.value(DNAInfo::LOCUS).value(); assert(!loi.name.isEmpty()); QString& mol = loi.molecule; if (mol.size() >= 3 && mol.at(2) != '-') loc.append(" "); loc = padToLen(loc.append(mol), 43); loc = padToLen(loc.append(loi.topology), 52); loc = loc.append(loi.division); date = loi.date; } else { if (so->isCircular()) { loc = padToLen(loc.append("CIRCULAR"), 52); } } } else { assert(!aos.isEmpty()); loc = !aos.isEmpty() ? aos.takeFirst()->getGObjectName() : "unknown"; //FIXME ??? } assert(!loc.isEmpty()); if (date.isEmpty()) { date = getDate(); } loc = padToLen(loc, 56) + date; return loc; } static void writeQualifier(const QString& name, const QString& val, IOAdapter* io, TaskStateInfo& si, const char* spaceLine) { int len = io->writeBlock(spaceLine, 21); if (len != 21) { si.setError(GenbankPlainTextFormat::tr("Error writing document")); return; } QString qstr; bool num; val.toInt(&num); if (num) { qstr = "/"+name+ "="+val; } else { qstr = "/"+name+ "=\""+val+"\""; } prepareMultiline(qstr, 21); len = io->writeBlock(qstr.toLocal8Bit()); if (len != qstr.length()) { si.setError(GenbankPlainTextFormat::tr("Error writing document")); } } static void writeAnnotations(IOAdapter* io, QList aos, TaskStateInfo& si) { assert(!aos.isEmpty()); QByteArray header("FEATURES Location/Qualifiers\n"); //write "FEATURES" qint64 len = io->writeBlock(header); if (len!=header.size()) { si.setError(GenbankPlainTextFormat::tr("Error writing document")); return; } //write every feature const char* spaceLine = TextUtils::SPACE_LINE.data(); // const QByteArray& aminoQ = GBFeatureUtils::QUALIFIER_AMINO_STRAND; // const QByteArray& aminoQYes = GBFeatureUtils::QUALIFIER_AMINO_STRAND_YES; // const QByteArray& aminoQNo = GBFeatureUtils::QUALIFIER_AMINO_STRAND_NO; const QByteArray& nameQ = GBFeatureUtils::QUALIFIER_NAME; const QByteArray& groupQ = GBFeatureUtils::QUALIFIER_GROUP; const QString& defaultKey = GBFeatureUtils::DEFAULT_KEY; QList sortedAnnotations; foreach(GObject* o, aos) { AnnotationTableObject* ao = qobject_cast(o); assert(ao); sortedAnnotations += ao->getAnnotations(); } qStableSort(sortedAnnotations.begin(), sortedAnnotations.end(), annotationLessThanByRegion); for(int i = 0; i < sortedAnnotations.size(); ++i) { Annotation * a = sortedAnnotations.at(i); assert(a != NULL); //write name of the feature len = io->writeBlock(spaceLine, 5); if (len != 5) { si.setError(GenbankPlainTextFormat::tr("Error writing document")); return; } QString aName = a->getAnnotationName(); GBFeatureKey key = GBFeatureUtils::getKey(aName); const QString& keyStr = key == GBFeatureKey_UNKNOWN ? defaultKey: aName; len = io->writeBlock(keyStr.toLocal8Bit()); if (len!=keyStr.length()) { si.setError(GenbankPlainTextFormat::tr("Error writing document")); return; } int nspaces = 22 - keyStr.length() - 6; assert(nspaces > 0); len = io->writeBlock(spaceLine, nspaces); if (len !=nspaces) { si.setError(GenbankPlainTextFormat::tr("Error writing document")); return; } //write location QString multiLineLocation = Genbank::LocationParser::buildLocationString(a->data()); prepareMultiline(multiLineLocation, 21); len = io->writeBlock(multiLineLocation.toLocal8Bit()); if (len != multiLineLocation.size()) { si.setError(GenbankPlainTextFormat::tr("Error writing document")); return; } //write qualifiers foreach (const U2Qualifier& q, a->getQualifiers()) { writeQualifier(q.name, q.value, io, si, spaceLine); if (si.hasError()) { return; } } //write name if its not the same as a name if (key == GBFeatureKey_UNKNOWN) { writeQualifier(nameQ, aName, io, si, spaceLine); } //write strand info //if (a->getAminoFrame() != TriState_Unknown) { // const QString& val = a->getAminoFrame() == TriState_No ? aminoQNo : aminoQYes; // writeQualifier(aminoQ, val, io, si, spaceLine); //} //write group const QList& groups = a->getGroups(); bool storeGroups = true; if (groups.size() == 1) { AnnotationGroup* ag = groups.first(); storeGroups = !ag->isTopLevelGroup() || ag->getGroupName()!=aName; } if (storeGroups) { foreach(AnnotationGroup* ag, a->getGroups()) { writeQualifier(groupQ, ag->getGroupPath(), io, si, spaceLine); } } } } static void writeSequence(IOAdapter* io, DNASequenceObject* ao, TaskStateInfo& si) { static const int charsInLine = 60; const QByteArray& seq = ao->getSequence(); int slen = seq.length(); const char* sequence = seq.constData(); const char* spaces = TextUtils::SPACE_LINE.constData(); QByteArray num; bool ok = true; int blen = io->writeBlock(QByteArray("ORIGIN\n")); if (blen != 7) { si.setError(L10N::errorWritingFile(ao->getDocument()->getURL())); return; } for (int pos = 0; pos < slen; pos+=charsInLine) { num.setNum(pos+1); //right spaces blen = 10 - num.length()-1; int l = (int)io->writeBlock(QByteArray::fromRawData(spaces, blen)); if (l!=blen) { ok = false; break; } //current pos l = (int)io->writeBlock(num); if (l != num.length()) { ok = false; break; } //sequence int last = qMin(pos+charsInLine, slen); for (int j=pos; j < last; j+=10) { l = (int)io->writeBlock(QByteArray::fromRawData(" ", 1)); if (l != 1) { ok = false; break; } int chunkLen = qMin(10, slen - j); l = io->writeBlock(QByteArray::fromRawData(sequence + j, chunkLen)); if (l!=chunkLen) { ok = false; break; } } if (!ok) { break; } //line end l = (int)io->writeBlock(QByteArray("\n", 1)); if (l != 1) { ok = false; break; } } if (!ok) { si.setError(L10N::errorWritingFile(ao->getDocument()->getURL())); } } // splits line into multiple lines adding 'spacesOnLineStart' to every line except first one // and '\n' to the end of every new line static void prepareMultiline(QString& line, int spacesOnLineStart, bool newLineAtTheEnd, int maxLineLen) { Q_ASSERT(spacesOnLineStart < maxLineLen); const int len = line.length() ; if (spacesOnLineStart + len > maxLineLen) { QByteArray spacesPrefix(spacesOnLineStart, ' '); QString newLine; int charsInLine = maxLineLen - spacesOnLineStart; int pos = 0; do { if (pos!=0) { newLine.append('\n'); newLine.append(spacesPrefix); } int pos2 = pos + charsInLine - 1; if (pos2 < len) { //not the last line while (pos2 > pos && !line[pos2].isSpace() && (line[pos2]!= ',')) { pos2--; } if (pos == pos2) { //we failed to find word end pos2 = pos + charsInLine - 1; } newLine.append(line.mid(pos, pos2 + 1 - pos)); } else { //last line newLine.append(line.mid(pos, len-pos)); } pos=pos2+1; } while (pos * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include #include #include #include #include "StdResidueDictionary.h" #include "ASNFormat.h" #include "PDBFormat.h" namespace U2 { QMutex StdResidueDictionary::standardDictionaryLock; std::auto_ptr StdResidueDictionary::standardDictionary(NULL); bool StdResidueDictionary::load( const QString& fileName ) { IOAdapterFactory* iof = AppContext::getIOAdapterRegistry()->getIOAdapterFactoryById(BaseIOAdapters::LOCAL_FILE); if (!iof) { return false; } std::auto_ptr io(iof->createIOAdapter()); bool ok = io->open(fileName, IOAdapterMode_Read); if (!ok) { return false; } TaskStateInfo ti; ASNFormat::AsnParser asnParser(io.get(),ti); AsnNode* rootElem = asnParser.loadAsnTree(); if (ti.hasError()) { return false; } buildDictionaryFromAsnTree(rootElem); return true; } #define STD_DICT_FILE_NAME ":format/datafiles/MMDBStdResidueDict" StdResidueDictionary* StdResidueDictionary::createStandardDictionary() { StdResidueDictionary* stdDictionary = new StdResidueDictionary(); if (!stdDictionary->load(STD_DICT_FILE_NAME)) { return NULL; } if (!stdDictionary->validate()) { return NULL; } return stdDictionary; } void buildStdAtomFromNode(AsnNode* atomNode, StdAtom& atom) { /* Atom ::= SEQUENCE { id Atom-id, name VisibleString OPTIONAL, iupac-code SEQUENCE OF VisibleString OPTIONAL, element ENUMERATED { ... }, ionizable-proton ENUMERATED { true(1), false(2), unknown(255) } OPTIONAL } */ // Load atom name atom.name = atomNode->getChildById(1)->value.trimmed(); // Load atom number QByteArray elementName = atomNode->getChildById(3)->value; atom.atomicNum = PDBFormat::getElementNumberByName(elementName.toUpper()); } void buildStdResidueFromNode(AsnNode* residueNode, StdResidue& residue) { /* Residue-graph ::= SEQUENCE { id Residue-graph-id, descr SEQUENCE OF Biomol-descr OPTIONAL, residue-type INTEGER { deoxyribonucleotide(1), ribonucleotide(2), amino-acid(3), other(255) } OPTIONAL, iupac-code SEQUENCE OF VisibleString OPTIONAL, atoms SEQUENCE OF Atom, bonds SEQUENCE OF Intra-residue-bond, chiral-centers SEQUENCE OF Chiral-center OPTIONAL } */ // we are making some assumptions about children indexes due to real file contents // Load residue name AsnNode* descrNode = residueNode->getChildById(1); residue.name = descrNode->getChildById(0)->value; // Load residue type QByteArray residueTypeName = residueNode->getChildById(2)->value; residue.type = StdResidueDictionary::getResidueTypeByName(residueTypeName); // Load residue code AsnNode* codeNode = residueNode->getChildById(3); residue.code = codeNode->getChildById(0)->value.at(0); // Load residue atoms AsnNode* atomsNode = residueNode->getChildById(4); foreach (AsnNode* node, atomsNode->children) { bool ok = false; int atomId = node->getChildById(0)->value.toInt(&ok); Q_ASSERT(ok == true); StdAtom atom; buildStdAtomFromNode(node, atom); residue.atoms.insert(atomId, atom); } // Load intra residue bonds AsnNode* bondsNode = residueNode->getChildById(5); foreach (AsnNode* node, bondsNode->children) { StdBond bond; bool id1OK = false, id2OK = false; bond.atom1Id = node->getChildById(0)->value.toInt(&id1OK); bond.atom2Id = node->getChildById(1)->value.toInt(&id2OK); Q_ASSERT(id1OK && id2OK); residue.bonds.append(bond); } } void StdResidueDictionary::buildDictionaryFromAsnTree( AsnNode* rootElem ) { /* Biostruc-residue-graph-set ::= SEQUENCE { id SEQUENCE OF Biostruc-id OPTIONAL, descr SEQUENCE OF Biomol-descr OPTIONAL, residue-graphs SEQUENCE OF Residue-graph } Residue-graph ::= SEQUENCE { id Residue-graph-id, ... } */ AsnNode* resGraphsNode = rootElem->findChildByName("residue-graphs"); // Load residues foreach (AsnNode* child, resGraphsNode->children) { bool ok = false; int id = child->getChildById(0)->value.toInt(&ok); Q_ASSERT(ok == true); StdResidue residue; buildStdResidueFromNode(child, residue); residues.insert(id, residue); } } U2::ResidueType StdResidueDictionary::getResidueTypeByName( const QByteArray& name ) { if (name == "amino-acid") { return AMINO_ACID; } else if (name == "deoxyribonucleotide") { return DEOXYRIBONUCLEOTIDE; } else if (name == "ribonucleotide") { return RIBONUCLEOTIDE; } else { return OTHER; } } bool StdResidueDictionary::validate() const { // TODO: replace with normal tests // simple validation tests #ifdef DEBUG Q_ASSERT(residues.count() == 84); const StdResidue& asp = residues.value(10); Q_ASSERT(asp.name == "ASP"); Q_ASSERT(asp.code == 'D'); Q_ASSERT(asp.type == AMINO_ACID); Q_ASSERT(asp.atoms.count() == 14 ); const QHash aspAtoms = asp.atoms; const StdAtom& atom = aspAtoms.value(5); Q_ASSERT(atom.name == "H"); Q_ASSERT(atom.atomicNum == 1); #endif return true; } const StdResidueDictionary* StdResidueDictionary::getStandardDictionary() { QMutexLocker locker( &standardDictionaryLock ); if (standardDictionary.get() == NULL) { standardDictionary.reset( createStandardDictionary() ); } return standardDictionary.get(); } StdResidueDictionary::~StdResidueDictionary() { } const StdResidue StdResidueDictionary::getResidueById( int id ) const { return residues.value(id); } StdResidueDictionary* StdResidueDictionary::createFromAsnTree( AsnNode* rootElem ) { AsnNode* resGraphsNode = ASNFormat::findFirstNodeByName(rootElem, "residue-graphs"); if (resGraphsNode == NULL) { return NULL; } StdResidueDictionary* localDictionary = new StdResidueDictionary(); // Load residues foreach (AsnNode* child, resGraphsNode->children) { bool ok = false; int id = child->getChildById(0)->value.toInt(&ok); Q_ASSERT(ok == true); StdResidue residue; buildStdResidueFromNode(child, residue); localDictionary->residues.insert(id, residue); } return localDictionary; } } //namespace ugene-1.9.8/src/corelibs/U2Formats/src/StreamSequenceWriter.cpp0000644000175000017500000000550711651544332023154 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include #include #include #include #include #include #include "StreamSequenceWriter.h" namespace U2 { StreamShortReadsWriter::StreamShortReadsWriter(const GUrl& url, const QString& refName , int refLength ) : numSeqWritten(0), refSeqLength(refLength) { refSeqName = QString(refName).replace(QRegExp("\\s|\\t"), "_").toAscii(); IOAdapterFactory* iof = AppContext::getIOAdapterRegistry()->getIOAdapterFactoryById(BaseIOAdapters::LOCAL_FILE); io = iof->createIOAdapter(); bool res = io->open(url, IOAdapterMode_Write); assert(res == true); Q_UNUSED(res); } bool StreamShortReadsWriter::writeNextAlignedRead( int offset, const DNASequence& seq ) { bool writeOk = format.storeAlignedRead(offset, seq, io, refSeqName, refSeqLength, numSeqWritten == 0); if (writeOk) { ++numSeqWritten; return true; } return false; } void StreamShortReadsWriter::close() { io->close(); } StreamShortReadsWriter::~StreamShortReadsWriter() { delete io; } StreamShortReadWriter::StreamShortReadWriter( bool writeQualityExplicitly) : writeQuality(writeQualityExplicitly) { DocumentFormat* df = AppContext::getDocumentFormatRegistry()->getFormatById(BaseDocumentFormats::PLAIN_FASTA); fastaFormat = qobject_cast (df); assert(fastaFormat != NULL); IOAdapterFactory* iof = AppContext::getIOAdapterRegistry()->getIOAdapterFactoryById(BaseIOAdapters::LOCAL_FILE); io = iof->createIOAdapter(); } bool StreamShortReadWriter::init( const GUrl& url ) { ouputPath = url; bool res = io->open(url, IOAdapterMode_Write); return res; } bool StreamShortReadWriter::writeNextSequence( const DNASequence& seq ) { TaskStateInfo info; fastaFormat->storeSequence(seq,io,info); return !info.hasError(); } void StreamShortReadWriter::close() { io->close(); } } //namespace ugene-1.9.8/src/corelibs/U2Formats/src/ClustalWAlnFormat.cpp0000644000175000017500000002522211651544332022371 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "ClustalWAlnFormat.h" #include #include #include #include #include #include #include #include #include #include #include #include #include namespace U2 { /* TRANSLATOR U2::ClustalWAlnFormat */ /* TRANSLATOR U2::IOAdapter */ const QByteArray ClustalWAlnFormat::CLUSTAL_HEADER = "CLUSTAL"; ClustalWAlnFormat::ClustalWAlnFormat(QObject* p) : DocumentFormat(p, DocumentFormatFlags_SW, QStringList("aln")) { formatName = tr("CLUSTALW"); supportedObjectTypes+=GObjectTypes::MULTIPLE_ALIGNMENT; } void ClustalWAlnFormat::load(IOAdapter* io, QList& objects, const QVariantMap&, TaskStateInfo& ti) { static int READ_BUFF_SIZE = 1024; QByteArray readBuffer(READ_BUFF_SIZE, '\0'); char* buff = readBuffer.data(); const QBitArray& LINE_BREAKS = TextUtils::LINE_BREAKS; const QBitArray& WHITES = TextUtils::WHITES; QString objName = io->getURL().baseFileName(); MAlignment al(objName); bool lineOk = false; bool firstBlock = true; int sequenceIdx = 0; int valStartPos = 0; int valEndPos = 0; //1 skip first line int len = io->readUntil(buff, READ_BUFF_SIZE, LINE_BREAKS, IOAdapter::Term_Include, &lineOk); if (!lineOk || !readBuffer.startsWith( CLUSTAL_HEADER )) { ti.setError( ClustalWAlnFormat::tr("Illegal header line")); } //read data while (!ti.cancelFlag && (len = io->readUntil(buff, READ_BUFF_SIZE, LINE_BREAKS, IOAdapter::Term_Include, &lineOk)) > 0) { if( QByteArray::fromRawData( buff, len ).startsWith( CLUSTAL_HEADER ) ) { io->skip( -len ); break; } int numNs = 0; while(len > 0 && LINE_BREAKS[(uchar)buff[len-1]]) { if ( buff[len-1] =='\n') { numNs++; } len--; } if (len == 0) { if (al.getNumRows() == 0) { continue;//initial empty lines } ti.setError( ClustalWAlnFormat::tr("Error parsing file")); break; } QByteArray line = QByteArray::fromRawData( buff, len ); if (valStartPos == 0) { int spaceIdx = line.indexOf(' '); int valIdx = spaceIdx + 1; while (valIdx < len && WHITES[(uchar)buff[valIdx]]) { valIdx++; } if (valIdx <= 0 || valIdx >= len-1) { ti.setError( ClustalWAlnFormat::tr("Invalid alignment format")); break; } valStartPos = valIdx; } valEndPos = valStartPos + 1; //not inclusive while (valEndPos < len && !WHITES[(uchar)buff[valEndPos]]) { valEndPos++; } if (valEndPos!=len) { //there were numbers trimmed -> trim spaces now while (valEndPos > valStartPos && buff[valEndPos] == ' ') { valEndPos--; } valEndPos++; //leave non-inclusive } QByteArray name = line.left(valStartPos).trimmed(); QByteArray value = line.mid(valStartPos, valEndPos - valStartPos); int seqsInModel = al.getNumRows(); bool lastBlockLine = (!firstBlock && sequenceIdx == seqsInModel) || numNs >=2 || name.isEmpty() || value.contains(' ') || value.contains(':') || value.contains('.'); if (firstBlock) { if (lastBlockLine && name.isEmpty()) { //if name is not empty -> this is a sequence but consensus (for Clustal files without consensus) // this is consensus line - skip it } else { assert(al.getNumRows() == sequenceIdx); al.addRow(MAlignmentRow(name, value)); } } else { int rowIdx = -1; if (sequenceIdx < seqsInModel) { rowIdx = sequenceIdx; } else if (sequenceIdx == seqsInModel) { assert(lastBlockLine); // consensus line } else { ti.setError( ClustalWAlnFormat::tr("Incorrect number of sequences in block")); break; } if (rowIdx != -1) { const MAlignmentRow& row = al.getRow(rowIdx); if (row.getName() != name) { ti.setError( ClustalWAlnFormat::tr("Sequence names are not matched")); break; } al.appendChars(rowIdx, value.constData(), value.size()); } } if (lastBlockLine) { firstBlock = false; if (!MSAUtils::checkPackedModelSymmetry(al, ti)) { break; } sequenceIdx = 0; } else { sequenceIdx++; } ti.progress = io->getProgress(); } MSAUtils::checkPackedModelSymmetry(al, ti); if (ti.hasError()) { return; } DocumentFormatUtils::assignAlphabet(al); if (al.getAlphabet() == NULL) { ti.setError( ClustalWAlnFormat::tr("Alphabet is unknown")); return; } MAlignmentObject* obj = new MAlignmentObject(al); objects.append(obj); } Document* ClustalWAlnFormat::loadDocument(IOAdapter* io, TaskStateInfo& ti, const QVariantMap& fs, DocumentLoadMode) { QList objects; load(io, objects, fs, ti); if (ti.hasError()) { qDeleteAll( objects ); return NULL; } assert(objects.size() == 1); return new Document(this, io->getFactory(), io->getURL(), objects, fs); } #define MAX_LINE_LEN 80 #define MAX_NAME_LEN 39 #define SEQ_ALIGNMENT 5 void ClustalWAlnFormat::save(IOAdapter* io, Document* d, TaskStateInfo& ti) { const MAlignmentObject* obj = NULL; if( (d->getObjects().size() != 1) || ((obj = qobject_cast(d->getObjects().first())) == NULL)) { ti.setError("No data to write;"); return; } const MAlignment& ma = obj->getMAlignment(); //write header QByteArray header("CLUSTAL W 2.0 multiple sequence alignment\n\n"); int len = io->writeBlock(header); if (len != header.length()) { ti.setError(L10N::errorWritingFile(d->getURL())); return; } //precalculate seq writing params int maxNameLength = 0; foreach(const MAlignmentRow& row, ma.getRows()) { maxNameLength = qMax(maxNameLength, row.getName().length()); } maxNameLength = qMin(maxNameLength, MAX_NAME_LEN); int aliLen = ma.getLength(); QByteArray consensus(aliLen, MAlignment_GapChar); MSAConsensusAlgorithmFactory* algoFactory = AppContext::getMSAConsensusAlgorithmRegistry()->getAlgorithmFactory(BuiltInConsensusAlgorithms::CLUSTAL_ALGO); std::auto_ptr algo(algoFactory->createAlgorithm(ma)); MSAConsensusUtils::updateConsensus(ma, consensus, algo.get()); int maxNumLength = 1 + (aliLen < 10 ? 1 : (int)log10((double)aliLen)); int seqStart = maxNameLength + 2; //+1 for space separator if (seqStart % SEQ_ALIGNMENT != 0) { seqStart = seqStart + SEQ_ALIGNMENT - (seqStart % SEQ_ALIGNMENT); } int seqEnd = MAX_LINE_LEN - maxNumLength - 1; if (seqEnd % SEQ_ALIGNMENT != 0) { seqEnd = seqEnd - (seqEnd % SEQ_ALIGNMENT); } assert(seqStart % SEQ_ALIGNMENT == 0 && seqEnd % SEQ_ALIGNMENT == 0 && seqEnd > seqStart); int seqPerPage = seqEnd - seqStart; const char* spaces = TextUtils::SPACE_LINE.constData(); //write sequence for(int i = 0; i < aliLen; i+=seqPerPage) { int partLen = i + seqPerPage > aliLen ? aliLen - i : seqPerPage; foreach(const MAlignmentRow& row, ma.getRows()) { QByteArray line = row.getName().toAscii(); if (line.length() > MAX_NAME_LEN) { line = line.left(MAX_NAME_LEN); } TextUtils::replace(line.data(), line.length(), TextUtils::WHITES, '_'); line.append(QByteArray::fromRawData(spaces, seqStart - line.length())); line.append(row.mid(i, partLen).toByteArray(partLen)); line.append(' '); line.append(QString::number(qMin(i+seqPerPage, aliLen))); assert(line.length() <= MAX_LINE_LEN); line.append('\n'); len = io->writeBlock(line); if (len != line.length()) { ti.setError(L10N::errorWritingFile(d->getURL())); return; } } //write consensus QByteArray line = QByteArray::fromRawData(spaces, seqStart); line.append(consensus.mid(i, partLen)); line.append("\n\n"); len = io->writeBlock(line); if (len != line.length()) { ti.setError(L10N::errorWritingFile(d->getURL())); return; } } } void ClustalWAlnFormat::storeDocument( Document* d, TaskStateInfo& ti, IOAdapter* io ) { if( NULL == d ) { ti.setError(L10N::badArgument("doc")); return; } if( NULL == io || !io->isOpen() ) { ti.setError(L10N::badArgument("IO adapter")); return; } save(io, d, ti); } RawDataCheckResult ClustalWAlnFormat::checkRawData(const QByteArray& data, const GUrl&) const { if (TextUtils::contains(TextUtils::BINARY, data.constData(), data.size())) { return FormatDetection_NotMatched; } if (!data.startsWith(CLUSTAL_HEADER)) { return FormatDetection_NotMatched; } QTextStream s(data); QString line = s.readLine(); if ( (line == CLUSTAL_HEADER) || (line.endsWith("multiple sequence alignment")) ) { return FormatDetection_Matched; } return FormatDetection_AverageSimilarity; } }//namespace ugene-1.9.8/src/corelibs/U2Formats/src/IOLibUtils.h0000644000175000017500000000742511651544332020460 0ustar ilyailya#ifndef _U2_IO_LIB_UTILS_H_ #define _U2_IO_LIB_UTILS_H_ namespace U2 { #define BUFF_SIZE 8196 #define CHECK_MB 1024*1024 class SeekableBuf { public: const char* head; int pos; int size; const uchar* ubuf() const {return (const uchar*)(head + pos);} const char* buf() const {return (head + pos);} uchar next() {return *(head + pos++);} int read(char* buf, int len) { if (pos + len <= size) { memcpy(buf, head + pos, len); pos += len; return len; } return 0; } }; inline int SeekBuf(SeekableBuf* fp, int offset, int origin) { if (0 == origin && offset >= 0 && offset < fp->size) { fp->pos = offset; return 0; } return 1; } inline uint be_int4(const uchar* buf) { uchar c1 = *(buf++); uchar c2 = *(buf++); uchar c3 = *(buf++); uchar c4 = *(buf++); return (c1<<24) + (c2<<16) + (c3<<8) + c4; } inline ushort be_int2(const uchar* buf) { uchar c1 = *(buf++); uchar c2 = *(buf++); return (c1<<8) + c2; } inline int be_read_int_1(SeekableBuf* fp, uchar *i1) { if ((fp->pos + 1) > fp->size) { return 0; } *i1 = fp->next(); return 1; } inline int be_read_int_2(SeekableBuf* fp, ushort *i2) { if ((fp->pos + 2) > fp->size) { return 0; } *i2 = be_int2(fp->ubuf()); fp->pos += 2; return 1; } inline int be_read_int_4(SeekableBuf* fp, uint *i4) { if ((fp->pos + 4) > fp->size) { return 0; } *i4 = be_int4(fp->ubuf()); fp->pos += 4; return 1; } /* * Write a big-endian int1 */ inline int be_write_int_1(FILE *fp, uchar *i1) { if (fwrite(i1, sizeof(uchar), 1, fp) != 1) return (0); return (1); } /* * Write a big-endian int2 */ inline int be_write_int_2(FILE *fp, ushort *i2) { ushort i = be_int2( reinterpret_cast(i2) ); if (fwrite(&i, 2, 1, fp) != 1) return (0); return (1); } /* * Write a big-endian int4 */ inline int be_write_int_4(FILE *fp, uint *i4) { uint i = be_int4(reinterpret_cast (i4)); if (fwrite(&i, 4, 1, fp) != 1) return (0); return (1); } /* * Copyright (c) Medical Research Council 1994. All rights reserved. * * Permission to use, copy, modify and distribute this software and its * documentation for any purpose is hereby granted without fee, provided that * this copyright and notice appears in all copies. * * MRC disclaims all warranties with regard to this software. */ #define READ_BASES (1<<0) #define READ_SAMPLES (1<<1) #define READ_COMMENTS (1<<2) #define READ_ALL (READ_BASES | READ_SAMPLES | READ_COMMENTS) #define IEEE inline float int_to_float(int in) /* ** interpret the integer in as a ** floating point number in IEEE format */ { /* Assume `in' is stored as a float according to the ANSI IEEE 754-1985 standard. See the tables below: s = sign ( 1 bit) e = biased exponent (8 bits) f = fraction (23 bits) floating point number = (-1)^s 2^(e-127) 1.f Bits Name Content 31 Sign 1 iff number is negative 23-30 Exponent Eight-Bit exponent, biased by 127 0-22 Fraction 23-bit fraction component of normalised significant. The "one" bit is "hidden" If IEEE floating point format is supported on your machine... ensure there is a #define IEEE somewhere. */ #ifdef IEEE union { int i; float f; } cvt; cvt.i = in; return cvt.f; #else int fraction; int exponent; int sign; fraction = in & ( (1<<23)-1 ); exponent = (in >> 23) & ( (1<<8)-1 ); sign = (in >> 31); return (float) ( (sign?-1.0:1.0) * exp ( log ( (double) 2.0) * (double) (exponent - 127 - 23) ) * (double) ((1<<23)+fraction)) ; #endif } } //namespace #endif ugene-1.9.8/src/corelibs/U2Formats/src/PDBFormat.h0000644000175000017500000001010711651544332020246 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_PDB_FORMAT_H_ #define _U2_PDB_FORMAT_H_ #include #include #include #include namespace U2 { class IOAdapter; class AnnotationTableObject; class DNASequenceObject; class AtomData; typedef QSharedDataPointer SharedAtom; class U2FORMATS_EXPORT PDBFormat : public DocumentFormat { Q_OBJECT public: PDBFormat(QObject* p); virtual DocumentFormatId getFormatId() const {return BaseDocumentFormats::PLAIN_PDB;} virtual const QString& getFormatName() const {return formatName;} virtual Document* loadDocument(IOAdapter* io, TaskStateInfo& ti, const QVariantMap& fs, DocumentLoadMode mode = DocumentLoadMode_Whole); virtual RawDataCheckResult checkRawData(const QByteArray& rawData, const GUrl& = GUrl()) const; static int getElementNumberByName(const QByteArray& elementName); static char getAcronymByName(const QByteArray& name); static QHash createAtomNumMap(); static void calculateBonds(BioStruct3D& bioStruct); static Document* createDocumentFromBioStruct3D(BioStruct3D &bioStruct, DocumentFormat* format, IOAdapterFactory* iof, const GUrl& url, TaskStateInfo& ti, const QVariantMap& fs ); private: QString formatName; static QHash atomNumMap; static QHash acronymNameMap; void initUtilityMaps(); void updateSecStructChainIndexes(BioStruct3D& biostruc); void fillBioStruct3DAnnotationTable(AnnotationTableObject* ao, const BioStruct3D& bioStruct); class PDBParser { private: // Data IOAdapter *io; QString currentPDBLine; ResidueIndex currentResidueIndex; int currentChainIndex; int currentModelIndex; int residueOrder; char currentChainIndentifier; bool flagMultipleModels, flagAtomRecordPresent; QHash chainIndexMap; QHash seqResMap; QSet resIndSet; // Methods QByteArray getSpecValue(const QByteArray& specLine, const QByteArray& valueName); void parseHeader(BioStruct3D& biostruct, TaskStateInfo& ti); void parseCompound(BioStruct3D& biostruct, TaskStateInfo& ti); void parseDBRef(BioStruct3D& biostruct, TaskStateInfo& ti); void parseSequence(BioStruct3D& biostruct, TaskStateInfo& ti); void parseSecondaryStructure(BioStruct3D& biostruct, TaskStateInfo& ti); void parseHet(BioStruct3D& biostruct, TaskStateInfo& ti); void parseAtomConnections(BioStruct3D& biostruct, TaskStateInfo& ti); void parseAtom(BioStruct3D& biostruct, TaskStateInfo& ti); void createMolecule( char chainIdentifier, BioStruct3D &biostruct, int chainIndex ); void parseModel(BioStruct3D& biostruct, TaskStateInfo& ti); void updateSecStructChainIndexes( BioStruct3D& biostruc ); void updateResidueIndexes( BioStruct3D& biostruc ); bool seqResContains(char chainIdentier, int residueIndex, char acronym); QByteArray getNextSpecLine(); public: PDBParser(IOAdapter* io); void parseBioStruct3D(BioStruct3D& biostruct, TaskStateInfo& ts); }; }; }//namespace #endif ugene-1.9.8/src/corelibs/U2Formats/src/StreamSequenceReader.cpp0000644000175000017500000000737311651544332023105 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include #include #include #include #include #include "StreamSequenceReader.h" namespace U2 { DNASequence* StreamSequenceReader::getNextSequenceObject() { if (hasNext()) { DNASequence* result = currentSeq.get(); lookupPerformed = false; return result; } return NULL; } StreamSequenceReader::StreamSequenceReader() : currentReaderIndex(-1), currentSeq(NULL), errorOccured(false), lookupPerformed(false) { } bool StreamSequenceReader::hasNext() { if (readers.isEmpty()) { return false; } if (!lookupPerformed) { if (currentReaderIndex < 0 || currentReaderIndex >= readers.count()) { return false; } while (currentReaderIndex < readers.count()) { ReaderContext ctx = readers.at(currentReaderIndex); DNASequence *newSeq = ctx.format->loadSequence(ctx.io, taskInfo); currentSeq.reset(newSeq); if (NULL == newSeq) { ++currentReaderIndex; } else { lookupPerformed = true; break; } } } if (currentSeq.get() == NULL) { return false; } return true; } bool StreamSequenceReader::init( const QList& urls ) { foreach (const GUrl& url, urls) { QList detectedFormats = DocumentUtils::detectFormat(url); if (detectedFormats.isEmpty()) { taskInfo.setError(QString("File %1 unsupported format.").arg(url.getURLString())); break; } ReaderContext ctx; ctx.format = detectedFormats.first().format; if ( ctx.format->getFlags().testFlag(DocumentFormatFlag_SupportStreaming) == false ) { break; } IOAdapterFactory* factory = AppContext::getIOAdapterRegistry()->getIOAdapterFactoryById(BaseIOAdapters::LOCAL_FILE); IOAdapter* io = factory->createIOAdapter(); if (!io->open(url, IOAdapterMode_Read)) { break; } ctx.io = io; readers.append(ctx); } if (readers.isEmpty()) { taskInfo.setError("Unsupported file format or short reads list is empty"); return false; } else { currentReaderIndex = 0; return true; } } QString StreamSequenceReader::getErrorMessage() { return taskInfo.getError(); } int StreamSequenceReader::getProgress() { if (readers.count() == 0) { return 0; } float factor = 1/readers.count(); int progress = 0; for (int i = 0; i < readers.count(); ++i) { progress += (int)(factor * readers[i].io->getProgress()); } return progress; } StreamSequenceReader::~StreamSequenceReader() { for(int i =0; i < readers.size(); ++i) { delete readers[i].io; readers[i].io = NULL; } } } //namespace ugene-1.9.8/src/corelibs/U2Formats/src/MegaFormat.cpp0000644000175000017500000004074411651544332021057 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "MegaFormat.h" #include #include #include #include #include #include #include #include namespace U2 { const QByteArray MegaFormat::MEGA_HEADER="mega"; const QByteArray MegaFormat::MEGA_UGENE_TITLE="!Title Ugene Mega;\n\n"; const QByteArray MegaFormat::MEGA_TITLE="TITLE"; const char MegaFormat::MEGA_SEPARATOR='#'; const char MegaFormat::MEGA_IDENTICAL='.'; const char MegaFormat::MEGA_INDEL='-'; const char MegaFormat::MEGA_START_COMMENT='!'; const char MegaFormat::MEGA_END_COMMENT=';'; MegaFormat::MegaFormat(QObject* p) : DocumentFormat(p, DocumentFormatFlags_SW, QStringList("meg")) { formatName = tr("Mega"); supportedObjectTypes+=GObjectTypes::MULTIPLE_ALIGNMENT; } Document* MegaFormat::loadDocument(IOAdapter* io, TaskStateInfo& ti, const QVariantMap& fs, DocumentLoadMode) { QList objs; load(io, objs, ti); if (ti.hasError()) { qDeleteAll(objs); return NULL; } return new Document(this, io->getFactory(), io->getURL(), objs, fs); } void MegaFormat::storeDocument( Document* d, TaskStateInfo& ti, IOAdapter* io ) { if( NULL == d ) { ti.setError(L10N::badArgument("doc")); return; } if( NULL == io || !io->isOpen() ) { ti.setError(L10N::badArgument("IO adapter")); return; } save(io, d, ti); } RawDataCheckResult MegaFormat::checkRawData(const QByteArray& rawData, const GUrl&) const { QByteArray line=rawData.trimmed(); if (!line.startsWith(MEGA_SEPARATOR)) { return FormatDetection_NotMatched; } line=line.mid(1); line=line.trimmed(); if (!line.startsWith(MEGA_HEADER)) { return FormatDetection_NotMatched; } return FormatDetection_Matched; } static bool checkModel(const MAlignment& al, TaskStateInfo& ti) { //check that all sequences are of equal size int size = 0; for (int i=0, n = al.getNumRows(); ireadLine(buff, READ_BUFF_SIZE, &eolFound); if (len < READ_BUFF_SIZE && !eolFound) eolFound = eof = true; line += readBuffer; } if (len != READ_BUFF_SIZE) line.resize(line.size() + len - READ_BUFF_SIZE); return eof; } bool MegaFormat::checkName(QByteArray &name) { if (name.contains(MEGA_SEPARATOR) || name.contains(MEGA_START_COMMENT) || name.contains(MEGA_END_COMMENT)) { return false; } return true; } bool MegaFormat::readName(IOAdapter* io, QByteArray &line, QByteArray &name, TaskStateInfo &ti) { bool eof=false; line=line.mid(1); line=line.trimmed(); skipWhites(io, line); if (line.isEmpty()) { return true; } line=line.simplified(); int spaceIdx=line.indexOf(' '); if (-1!=spaceIdx) { name=line.left(spaceIdx); line=line.mid(spaceIdx); } else { name=line; eof=getNextLine(io, line); line=line.simplified(); } if (!checkName(name)) { ti.setError(MegaFormat::tr("Bad name of sequence")); } ti.progress=io->getProgress(); return eof; } bool MegaFormat::skipComments(IOAdapter *io, QByteArray &line, TaskStateInfo &ti) { int i=0; bool eof=false; bool hasEnd=false; while (1) { while (igetProgress(); return eof; } void MegaFormat::workUpIndels(MAlignment& al) { QByteArray firstSequence=al.getRow(0).getCore(); for (int i=1; i &objects, U2::TaskStateInfo &ti) { MAlignment al(io->getURL().baseFileName()); QByteArray line; bool eof=false; bool firstBlock=true; int sequenceIdx=0; bool lastIteration=false; readHeader(io, line, ti); if (ti.hasError()) { return; } readTitle(io, line, ti); if (ti.hasError()) { return; } //read data while (!ti.cancelFlag && !lastIteration) { QByteArray name; QByteArray value; //read name of a sequence if (readName(io, line, name, ti)) { if (!eof && name.isEmpty()) { ti.setError(MegaFormat::tr("Incorrect format")); return; } else if (name.isEmpty()) { break; } } if (ti.hasError()) { return; } //read the sequence eof=readSequence(io, line, ti, value, &lastIteration); if (ti.hasError()) { return; } if (0==sequenceIdx && value.contains(MEGA_IDENTICAL)) { ti.setError(MegaFormat::tr("Identical symbol at the first sequence")); return; } if (firstBlock) { for (int i=0; igetName()!=name) { ti.setError(MegaFormat::tr("Incorrect order of sequences' names")); return; } al.appendChars(sequenceIdx, value.constData(), value.size()); } sequenceIdx++; if (sequenceIdx==al.getNumRows()) { sequenceIdx=0; } } } checkModel(al, ti); if (ti.hasError()) { return; } DocumentFormatUtils::assignAlphabet(al); if (al.getAlphabet() == NULL) { ti.setError(MegaFormat::tr("Alphabet unknown")); return; } workUpIndels(al); //replace '.' by symbols from the first sequence MAlignmentObject* obj = new MAlignmentObject(al); objects.append(obj); } void MegaFormat::save(U2::IOAdapter *io, U2::Document *d, U2::TaskStateInfo &ti) { const MAlignmentObject* obj = NULL; if( (d->getObjects().size() != 1) || ((obj = qobject_cast(d->getObjects().first())) == NULL)) { ti.setError("No data to write;"); return; } const MAlignment& ma = obj->getMAlignment(); //write header QByteArray header; header.append(MEGA_SEPARATOR).append(MEGA_HEADER).append("\n").append(MEGA_UGENE_TITLE); int len = io->writeBlock(header); if (len != header.length()) { ti.setError(L10N::errorWritingFile(d->getURL())); return; } int maxNameLength=0; foreach (MAlignmentRow item, ma.getRows()) { maxNameLength = qMax(maxNameLength, item.getName().length()); } //write data int seqLength=ma.getLength(); int writtenLength=0; while (writtenLength seqLength ? seqLength - writtenLength : BLOCK_LENGTH); line.append(currentBlock).append('\n'); len = io->writeBlock(line); if (len != line.length()) { ti.setError(L10N::errorWritingFile(d->getURL())); return; } } writtenLength+=BLOCK_LENGTH; io->writeBlock("\n\n"); } } void MegaFormat::readHeader(U2::IOAdapter *io, QByteArray &line, U2::TaskStateInfo &ti) { skipWhites(io, line); if (line.isEmpty()) { ti.setError(MegaFormat::tr("No header")); return; } if (!line.startsWith(MEGA_SEPARATOR)) { ti.setError(MegaFormat::tr("No # before header")); return; } line=line.mid(1); line=line.trimmed(); skipWhites(io, line); if (line.isEmpty()) { ti.setError(MegaFormat::tr("No header")); return; } if (!line.startsWith(MEGA_HEADER)) { ti.setError(MegaFormat::tr("Not MEGA-header")); return; } line=line.mid(MEGA_HEADER.length()); line=line.trimmed(); ti.progress = io->getProgress(); } void MegaFormat::skipWhites(U2::IOAdapter *io, QByteArray &line) { while (line.isEmpty()) { if (getNextLine(io, line)) { if (line.isEmpty()) { return; } } line=line.trimmed(); } } void MegaFormat::readTitle(U2::IOAdapter *io, QByteArray &line, U2::TaskStateInfo &ti) { skipWhites(io, line); if (line.isEmpty()) { ti.setError(MegaFormat::tr("No data in file")); return; } bool comment=false; if (MEGA_START_COMMENT==line[0]) { line=line.mid(1); line=line.trimmed(); comment=true; skipWhites(io, line); if (line.isEmpty()) { ti.setError(MegaFormat::tr("No data in file")); return; } } line=line.simplified(); QByteArray word=line.left(MEGA_TITLE.length()); word=word.toUpper(); if (MEGA_TITLE!=word) { ti.setError(MegaFormat::tr("Incorrect title")); return; } line=line.mid(MEGA_TITLE.length()); if (!line.isEmpty() && (TextUtils::ALPHA_NUMS[line[0]] || MEGA_IDENTICAL==line[0] || MEGA_INDEL==line[0])){ ti.setError(MegaFormat::tr("Incorrect title")); return; } //read until # if (comment) { skipComments(io, line, ti); } else { int sepIdx=line.indexOf(MEGA_SEPARATOR); while (-1==sepIdx) { if (getNextLine(io, line)) { if (line.isEmpty()) { ti.setError(MegaFormat::tr("No data in file")); return; } } sepIdx=line.indexOf(MEGA_SEPARATOR); } line=line.mid(sepIdx); } ti.progress = io->getProgress(); } bool MegaFormat::readSequence(U2::IOAdapter *io, QByteArray &line, U2::TaskStateInfo &ti, QByteArray &value, bool *lastIteration) { bool hasPartOfSequence=false; bool eof=false; while (!ti.cancelFlag) { //delete spaces from the sequence untill # int spaceIdx=line.indexOf(' '); int separatorIdx; while (-1!=spaceIdx) { separatorIdx=line.indexOf(MEGA_SEPARATOR); if (-1!=separatorIdx && separatorIdxgetProgress(); line=line.simplified(); continue; } separatorIdx=line.indexOf(MEGA_SEPARATOR); int commentIdx=line.indexOf(MEGA_START_COMMENT); int sequenceEnd=(-1==separatorIdx)?line.size():separatorIdx; sequenceEnd=(-1==commentIdx)?sequenceEnd:qMin(sequenceEnd, commentIdx); //check symbols in the sequence for (int i=0; igetProgress(); line=line.simplified(); continue; } eof=true; break; } ti.progress = io->getProgress(); line=line.simplified(); continue; } else { line=line.mid(separatorIdx); break; } } return eof; } } //namespace ugene-1.9.8/src/corelibs/U2Formats/src/FastaFormat.cpp0000644000175000017500000002737711651544332021253 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "FastaFormat.h" #include "DocumentFormatUtils.h" #include #include #include #include #include #include #include #include #include #include namespace U2 { /* TRANSLATOR U2::FastaFormat */ /* TRANSLATOR U2::IOAdapter */ /* TRANSLATOR U2::Document */ FastaFormat::FastaFormat(QObject* p) : DocumentFormat(p, DocumentFormatFlags_SW, QStringList()<<"fa"<<"mpfa"<<"fna"<<"fsa"<<"fas"<<"fasta"<<"sef"<<"seq"<<"seqs") { formatName = tr("FASTA"); supportedObjectTypes+=GObjectTypes::SEQUENCE; supportedObjectTypes+=GObjectTypes::MULTIPLE_ALIGNMENT; formatDescription = tr("FASTA format is a text-based format for representing either nucleotide sequences or peptide sequences, in which base pairs or amino acids are represented using single-letter codes. The format also allows for sequence names and comments to precede the sequences."); } static QVariantMap analyzeRawData(const QByteArray& data) { int hasGaps = false; int minLen = -1; int maxLen = -1; int len = 0; int nSequences = 0; QTextStream input(data, QIODevice::ReadOnly); QString line; do { line = input.readLine(); if (line[0] == '>') { nSequences++; if (len > 0) { minLen = minLen == -1 ? len : qMin(minLen, len); maxLen = maxLen == -1 ? len : qMax(maxLen, len); } len = 0; } else { len += line.length(); if (!hasGaps && line.contains(MAlignment_GapChar)) { hasGaps = true; } } } while (!line.isEmpty()); QVariantMap res; res[RawDataCheckResult_Sequence] = true; if (hasGaps) { res[RawDataCheckResult_SequenceWithGaps] = true; } if (nSequences > 1) { res[RawDataCheckResult_MultipleSequences] = true; } if (minLen > 0) { res[RawDataCheckResult_MaxSequenceSize] = maxLen; res[RawDataCheckResult_MinSequenceSize] = minLen; } return res; } RawDataCheckResult FastaFormat::checkRawData(const QByteArray& rawData, const GUrl&) const { const char* data = rawData.constData(); int size = rawData.size(); int n = TextUtils::skip(TextUtils::WHITES, data, size); int newSize = size - n; const char* newData = data + n; if (newSize <= 0 || newData[0] != '>' ) { return FormatDetection_NotMatched; } bool hasBinaryBlocks = TextUtils::contains(TextUtils::BINARY, data, size); if (hasBinaryBlocks) { return FormatDetection_NotMatched; } //ok, format is matched -> add hints on sequence sizes RawDataCheckResult res(FormatDetection_Matched); res.properties = analyzeRawData(data); return res; } #define READ_BUFF_SIZE 4096 static void load(IOAdapter* io, const GUrl& docUrl, QList& objects, const QVariantMap& hints, TaskStateInfo& ti, int gapSize, int predictedSize, QString& writeLockReason, DocumentLoadMode mode) { writeLockReason.clear(); QByteArray readBuff(READ_BUFF_SIZE+1, 0); char* buff = readBuff.data(); qint64 len = 0; static char fastaHeaderStartChar = '>'; static QBitArray fastaHeaderStart = TextUtils::createBitMap(fastaHeaderStartChar); bool merge = gapSize!=-1; QByteArray sequence; QStringList headers; QSet names; QVector mergedMapping; QByteArray gapSequence((merge ? gapSize : 0), 0); sequence.reserve(predictedSize); //skip leading whites if present bool lineOk = true; static QBitArray nonWhites = ~TextUtils::WHITES; io->readUntil(buff, READ_BUFF_SIZE, nonWhites, IOAdapter::Term_Exclude, &lineOk); int sequenceStart = 0; while (!ti.cancelFlag) { //read header len = io->readUntil(buff, READ_BUFF_SIZE, TextUtils::LINE_BREAKS, IOAdapter::Term_Include, &lineOk); if (len == 0) { //end if stream break; } if (!lineOk) { ti.setError(FastaFormat::tr("Line is too long")); } QString headerLine = QString(QByteArray::fromRawData(buff+1, len-1)).trimmed(); if (buff[0]!= fastaHeaderStartChar) { ti.setError(FastaFormat::tr("First line is not a FASTA header")); } //read sequence if (!merge) { sequence.clear(); } else if (sequence.size() > 0) { sequence.append(gapSequence); sequenceStart = sequence.size(); } do { len = io->readUntil(buff, READ_BUFF_SIZE, fastaHeaderStart, IOAdapter::Term_Exclude); if (len <= 0) { break; } len = TextUtils::remove(buff, len, TextUtils::WHITES); buff[len] = 0; sequence.append(buff); ti.progress = io->getProgress(); } while (!ti.cancelFlag); if (merge) { headers.append(headerLine); mergedMapping.append(U2Region(sequenceStart, sequence.size() - sequenceStart)); } else { DNASequence seq(headerLine, sequence); QString objName; if (mode != DocumentLoadMode_SingleObject) { objName = TextUtils::variate(headerLine, "_", names); names.insert(objName); //TODO parse header seq.info.insert(DNAInfo::FASTA_HDR, headerLine); seq.info.insert(DNAInfo::ID, headerLine); } else { objName = headerLine; } DocumentFormatUtils::addSequenceObject(objects, objName, seq, hints, ti); if (ti.hasError()) { qDeleteAll(objects); objects.clear(); return; } } if( mode == DocumentLoadMode_SingleObject ) { break; } } assert(headers.size() == mergedMapping.size()); if (!ti.hasError() && !ti.cancelFlag && merge && !headers.isEmpty()) { DocumentFormatUtils::addMergedSequenceObject(objects, docUrl, headers, sequence, mergedMapping, hints, ti); } if (!ti.hasError() && !ti.cancelFlag && objects.isEmpty()) { ti.setError(Document::tr("Document is empty.")); } if (merge && headers.size() > 1) { writeLockReason = DocumentFormat::MERGED_SEQ_LOCK; } } Document* FastaFormat::loadDocument( IOAdapter* io, TaskStateInfo& ti, const QVariantMap& _fs, DocumentLoadMode mode) { if( NULL == io || !io->isOpen() ) { ti.setError(L10N::badArgument("IO adapter")); return NULL; } QVariantMap fs = _fs; QList objects; int gapSize = qBound(-1, DocumentFormatUtils::getMergeGap(fs), 1000*1000); int predictedSize = qMax(1000, DocumentFormatUtils::getIntSettings(fs, DocumentReadingMode_SequenceMergingFinalSizeHint, gapSize==-1 ? 0 : io->left())); QString lockReason; load(io, io->getURL(), objects, fs, ti, gapSize, predictedSize, lockReason, mode); if (ti.hasError() || ti.cancelFlag) { qDeleteAll(objects); objects.clear(); return NULL; } DocumentFormatUtils::updateFormatSettings(objects, fs); Document* doc = new Document(this, io->getFactory(), io->getURL(), objects, fs, lockReason); return doc; } #define LINE_LEN 70 static void saveOneFasta( IOAdapter* io, const DNASequence& sequence, GObject*, TaskStateInfo& tsi ) { //writing header; // TODO better header out of info tags /*QString hdr = seqObj->getDNASequence().info.value(DNAInfo::FASTA_HDR).toString(); if (hdr.isEmpty()) { hdr = seqObj->getGObjectName(); }*/ QByteArray block; QString hdr = sequence.getName(); block.append('>').append(hdr).append( '\n' ); if (io->writeBlock( block ) != block.length()) { tsi.setError(L10N::errorWritingFile(io->getURL())); return; } const char* seq = sequence.seq.constData(); int len = sequence.seq.length(); for (int i = 0; i < len; i += LINE_LEN ) { int chunkSize = qMin( LINE_LEN, len - i ); if (io->writeBlock( seq + i, chunkSize ) != chunkSize || !io->writeBlock( "\n", 1 )) { tsi.setError(L10N::errorWritingFile(io->getURL())); return; } } } void FastaFormat::storeDocument( Document* doc, TaskStateInfo& ts, IOAdapter* io ) { //TODO: check saved op states!!! foreach( GObject* o, doc->getObjects() ) { QList sequences = DocumentFormatUtils::toSequences(o); foreach(const DNASequence& s, sequences) { saveOneFasta( io, s, o, ts ); if (ts.isCoR()) { break; } } } } GObject *FastaFormat::loadObject(IOAdapter *io, TaskStateInfo &ti) { DNASequence *seq = loadSequence(io, ti); if (ti.hasError()) { return NULL; } return new DNASequenceObject(seq->getName(), *seq); } DNASequence *FastaFormat::loadSequence(IOAdapter* io, TaskStateInfo& ti) { static char fastaHeaderStartChar = '>'; static QBitArray fastaHeaderStart = TextUtils::createBitMap(fastaHeaderStartChar); static QBitArray nonWhites = ~TextUtils::WHITES; if( NULL == io || !io->isOpen() ) { ti.setError(L10N::badArgument("IO adapter")); return NULL; } QByteArray readBuff(READ_BUFF_SIZE+1, 0); char* buff = readBuff.data(); qint64 len = 0; //skip leading whites if present bool lineOk = true; io->readUntil(buff, READ_BUFF_SIZE, nonWhites, IOAdapter::Term_Exclude, &lineOk); //read header len = io->readUntil(buff, READ_BUFF_SIZE, TextUtils::LINE_BREAKS, IOAdapter::Term_Include, &lineOk); if (len == 0) { //end of stream return NULL; } if (!lineOk) { ti.setError(FastaFormat::tr("Line is too long")); } QByteArray headerLine = QByteArray(buff + 1, len-1).trimmed(); if (buff[0]!= fastaHeaderStartChar) { ti.setError(FastaFormat::tr("First line is not a FASTA header")); } //read sequence QByteArray sequence; int predictedSize = 1000; sequence.reserve(predictedSize); do { len = io->readUntil(buff, READ_BUFF_SIZE, fastaHeaderStart, IOAdapter::Term_Exclude); if (len <= 0) { break; } len = TextUtils::remove(buff, len, TextUtils::WHITES); buff[len] = 0; sequence.append(buff); } while (!ti.cancelFlag); DNASequence *seq = new DNASequence(headerLine, sequence); seq->alphabet = AppContext::getDNAAlphabetRegistry()->findById(BaseDNAAlphabetIds::NUCL_DNA_EXTENDED()); assert(seq->alphabet!=NULL); if (!seq->alphabet->isCaseSensitive()) { TextUtils::translate(TextUtils::UPPER_CASE_MAP, const_cast(seq->seq.constData()), seq->seq.length()); } return seq; } void FastaFormat::storeSequence( const DNASequence& sequence, IOAdapter* io, TaskStateInfo& ti ) { saveOneFasta(io, sequence, NULL, ti); } }//namespace ugene-1.9.8/src/corelibs/U2Formats/src/SwissProtPlainTextFormat.h0000644000175000017500000000324711651544332023456 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_SWISS_PROT_PLAIN_TEXT_FORMAT_H_ #define _U2_SWISS_PROT_PLAIN_TEXT_FORMAT_H_ #include "EMBLGenbankAbstractDocument.h" namespace U2 { class U2FORMATS_EXPORT SwissProtPlainTextFormat : public EMBLGenbankAbstractDocument { Q_OBJECT public: SwissProtPlainTextFormat(QObject* p); virtual RawDataCheckResult checkRawData(const QByteArray& rawData, const GUrl& = GUrl()) const; protected: bool readIdLine(ParserState*); bool readEntry(QByteArray&, ParserState*); bool readSequence(QByteArray& sequence, ParserState*); void readAnnotations(ParserState*, int offset); SharedAnnotationData readAnnotation(IOAdapter* io, char* cbuff, int contentLen, int bufSize, TaskStateInfo& si, int offset); //void readAnnotations(ParserState*, int offset); QMap tagMap; }; }//namespace #endif ugene-1.9.8/src/corelibs/U2Formats/src/NewickFormat.h0000644000175000017500000000317311651544332021066 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_NEWICK_FORMAT_H_ #define _U2_NEWICK_FORMAT_H_ #include #include namespace U2 { class U2FORMATS_EXPORT NewickFormat : public DocumentFormat { Q_OBJECT public: NewickFormat(QObject* p); virtual DocumentFormatId getFormatId() const {return BaseDocumentFormats::NEWICK;} virtual const QString& getFormatName() const {return formatName;} virtual Document* loadDocument(IOAdapter* io, TaskStateInfo& ti, const QVariantMap& fs, DocumentLoadMode mode = DocumentLoadMode_Whole); virtual void storeDocument( Document* d, TaskStateInfo& ts, IOAdapter* io); virtual RawDataCheckResult checkRawData(const QByteArray& rawData, const GUrl& = GUrl()) const; private: QString formatName; }; }//namespace #endif ugene-1.9.8/src/corelibs/U2Formats/src/MSFFormat.h0000644000175000017500000000462011651544332020271 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_MSF_FORMAT_H_ #define _U2_MSF_FORMAT_H_ #include #include namespace U2 { class IOAdapter; class U2FORMATS_EXPORT MSFFormat : public DocumentFormat { Q_OBJECT public: MSFFormat(QObject* p); virtual DocumentFormatId getFormatId() const { return BaseDocumentFormats::MSF; } virtual const QString& getFormatName() const { return formatName; } virtual Document* loadDocument(IOAdapter* io, TaskStateInfo& ti, const QVariantMap& fs, DocumentLoadMode mode = DocumentLoadMode_Whole); virtual void storeDocument( Document* d, TaskStateInfo& ts, IOAdapter* io ); virtual RawDataCheckResult checkRawData(const QByteArray& rawData, const GUrl& = GUrl()) const; private: void save(IOAdapter* io, Document* doc, TaskStateInfo& ti); void load(IOAdapter* io, QList& objects, TaskStateInfo& ti); QString formatName; static int getCheckSum(const QByteArray& seq); static const int CHECK_SUM_MOD; static const QByteArray MSF_FIELD; static const QByteArray CHECK_FIELD; static const QByteArray LEN_FIELD; static const QByteArray NAME_FIELD; static const QByteArray TYPE_FIELD; static const QByteArray WEIGHT_FIELD; static const QByteArray TYPE_VALUE_PROTEIN; static const QByteArray TYPE_VALUE_NUCLEIC; static const double WEIGHT_VALUE; static const QByteArray END_OF_HEADER_LINE; static const QByteArray SECTION_SEPARATOR; static const int CHARS_IN_ROW; static const int CHARS_IN_WORD; }; }//namespace #endif ugene-1.9.8/src/corelibs/U2Formats/src/IndexFormat.cpp0000644000175000017500000003764711651544332021265 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include #include #include #include #include #include #include #include "IndexFormat.h" /* TRANSLATOR U2::IndexFormat */ using namespace U2; const int BUF_SZ = 1024; const int SMALL_BUF_SZ = 128; const char NULL_SYM = '\0'; const int NO_BYTES = 0; const QByteArray QUOTE = "\""; const char CQUOTE = '"'; const QByteArray NEW_LINE = QByteArray( 1, '\n' ); const QByteArray TAB = QByteArray( 1, '\t' ); const int BAD_OFFSET = -1; const int READ_ONE_CHAR = 1; const QByteArray EOF_SECTION = "//"; const QByteArray ITEM_SEC = "IT"; const QByteArray IO_SEC = "IO"; enum SectionId { UNKNOWN_SEC_ID = -1, ITEM_SEC_ID, IO_SEC_ID }; const QByteArray IO_TAG = "IO"; const QByteArray DOC_TAG = "DO"; const QByteArray START_OFF_TAG = "SO"; const QByteArray END_OFF_TAG = "EO"; const QByteArray ID_TAG = "ID"; const QByteArray ADAPT_TAG = "AD"; const QByteArray URL_TAG = "UR"; enum TagId { UNKNOWN_TAG_ID = -1, IO_TAG_ID, DOC_TAG_ID, START_OFF_TAG_ID, END_OFF_TAG_ID, ID_TAG_ID, ADAPT_TAG_ID, URL_TAG_ID }; static SectionId getSectionId( const QByteArray& sec_name ) { if( ITEM_SEC == sec_name ) { return ITEM_SEC_ID; } else if( IO_SEC == sec_name ) { return IO_SEC_ID; } return UNKNOWN_SEC_ID; } static TagId getTagId( const QByteArray& tag ) { if( IO_TAG == tag ) { return IO_TAG_ID; } else if( DOC_TAG == tag ) { return DOC_TAG_ID; } else if( START_OFF_TAG == tag ) { return START_OFF_TAG_ID; } else if( END_OFF_TAG == tag ) { return END_OFF_TAG_ID; } else if( ID_TAG == tag ) { return ID_TAG_ID; } else if( ADAPT_TAG == tag ) { return ADAPT_TAG_ID; } else if( URL_TAG == tag ) { return URL_TAG_ID; } return UNKNOWN_TAG_ID; } static void checkReadError( int ret ) { if( -1 == ret ) { throw IndexFormat::ReadError(); } } static QString getErrorString( UIndex::UIndexError err ) { switch( err ) { case UIndex::EMPTY_IO_ID: return IndexFormat::tr( "Empty io identifier in item section" ); case UIndex::EMPTY_DOC_FORMAT: return IndexFormat::tr( "Empty document format in item section " ); case UIndex::EMPTY_IO_ADAPTER: return IndexFormat::tr( "Empty io adapter identifier in io section" ); case UIndex::EMPTY_URL: return IndexFormat::tr( "Empty url in io section" ); case UIndex::BAD_OFFSET: return IndexFormat::tr( "Bad offset in item section" ); case UIndex::NO_SUCH_IO: return IndexFormat::tr( "Unrecognized io section id in item section" ); default: break; } return IndexFormat::tr( "Unknown index error occurred" ); // unrecognized error code } static void checkWriteError( quint64 wanted_to_write, quint64 how_many_wrote ) { if( wanted_to_write != how_many_wrote ) { throw IndexFormat::WriteError(); } } static bool checkHeader( const char* data, int sz ) { assert( NULL != data && 0 <= sz ); if( IndexFormat::FILE_HEADER.size() > sz ) { return false; } QByteArray header = QByteArray().fromRawData( data, sz ).trimmed(); return header.startsWith( IndexFormat::FILE_HEADER ); } static void readLine( IOAdapter* io, QByteArray* to = NULL ) { assert( NULL != io ); QByteArray buf( BUF_SZ, NULL_SYM ); bool there = false; while ( !there ) { int ret = io->readUntil( buf.data(), BUF_SZ, TextUtils::LINE_BREAKS, IOAdapter::Term_Include, &there ); checkReadError( ret ); if( NO_BYTES == ret ) { break; } if( NULL != to ) { to->append( QByteArray().fromRawData( buf.data(), ret ) ); } } } static void skipLinesAndWhites( IOAdapter* io ) { assert( NULL != io ); bool is_line_or_white = true; char c = 0; while( is_line_or_white ) { int ret = io->readBlock( &c, READ_ONE_CHAR ); checkReadError( ret ); if( NO_BYTES == ret ) { return; } is_line_or_white = TextUtils::LINE_BREAKS[uchar(c)] || TextUtils::WHITES[uchar(c)]; } io->skip( -READ_ONE_CHAR ); } static bool isEof( IOAdapter* io ) { assert( NULL != io ); skipLinesAndWhites( io ); QByteArray buf( SMALL_BUF_SZ, NULL_SYM ); int ret = io->readBlock( buf.data(), SMALL_BUF_SZ ); checkReadError( ret ); io->skip( -ret ); return NO_BYTES == ret; } static bool isEofSection( IOAdapter* io ) { assert( NULL != io ); skipLinesAndWhites( io ); QByteArray line( SMALL_BUF_SZ, NULL_SYM ); int ret = io->readUntil( line.data(), SMALL_BUF_SZ, TextUtils::LINE_BREAKS, IOAdapter::Term_Include ); checkReadError( ret ); io->skip( -ret ); return EOF_SECTION == QByteArray( line.data(), ret ).trimmed(); } static void readEofSection( IOAdapter* io ) { assert( NULL != io ); if ( !isEofSection( io ) ) { return; } readLine( io ); skipLinesAndWhites( io ); } // if odd quote sequence found then end = true static QByteArray unQuoteWord( const QByteArray& word, bool* end, int* ind = NULL ) { assert( NULL != end ); int sz = word.size(); assert( sz ); QByteArray ret; int i = 0; for( i = 0; i < sz; ++i ) { if( CQUOTE != word[i] ) { ret.append( word[i] ); } else { if( sz - 1 != i && CQUOTE == word[i+1] ) { ret.append( word[i] ); i++; continue; } *end = true; if( NULL != ind ) { *ind = i; } break; } } return ret; } static void getTagValue( QByteArray& tag, QByteArray& val, const QByteArray& ln ) { QByteArray line = ln.trimmed(); assert( line.size() ); if( CQUOTE != line[0] ) { throw IndexFormat::BadDataError( IndexFormat::tr( "Bad value in item section: tag" ) ); } bool end = false; int tagEnd = -1; tag = unQuoteWord( line.mid( 1 ), &end, &tagEnd ); if( !end ) { throw IndexFormat::BadDataError( IndexFormat::tr( "Bad value in item section: tag" ) ); } assert( -1 != tagEnd ); QByteArray vLine = line.mid( tagEnd + 2 ).trimmed(); assert( vLine.size() ); if( CQUOTE != vLine[0] ) { throw IndexFormat::BadDataError( IndexFormat::tr( "Bad value in item section: val" ) ); } val = unQuoteWord( vLine.mid( 1 ), &end ); if( !end ) { throw IndexFormat::BadDataError( IndexFormat::tr( "Bad value in item section: val" ) ); } } static void readIOSection( IOAdapter* io, UIndex::IOSection& io_sec ) { assert( NULL != io ); while( !isEofSection( io ) ) { QByteArray line; readLine( io, &line ); QByteArray tag; QByteArray val; getTagValue( tag, val, line ); TagId tag_id = getTagId( tag ); switch( tag_id ) { case ID_TAG_ID: io_sec.sectionId = QString( val ); break; case ADAPT_TAG_ID: io_sec.ioAdapterId = QString( val ); break; case URL_TAG_ID: io_sec.url = QString( val ); break; default: io_sec.keys[QString( tag )] = QString( val ); } } readEofSection( io ); } static void readItemSection( IOAdapter* io, UIndex::ItemSection& item ) { assert( NULL != io ); while( !isEofSection( io ) ) { QByteArray line; readLine( io, &line ); QByteArray tag; QByteArray val; getTagValue( tag, val, line ); TagId tag_id = getTagId( tag ); switch( tag_id ) { case IO_TAG_ID: item.ioSectionId = QString( val ); break; case DOC_TAG_ID: item.docFormat = QString( val ); break; case START_OFF_TAG_ID: { bool ok = false; qint64 converted = val.toLongLong( &ok ); item.startOff = ( ok )? converted: BAD_OFFSET; } break; case END_OFF_TAG_ID: { bool ok = false; qint64 converted = val.toLongLong( &ok ); item.endOff = ( ok )? converted: BAD_OFFSET; } break; default: item.keys[QString( tag )] = QString( val ); } } // !EofSection readEofSection( io ); } static void load( IOAdapter* io, QList< GObject* >& obj_list, TaskStateInfo& tsi ) { assert( NULL != io ); QByteArray line; skipLinesAndWhites( io ); readLine( io, &line ); if( !checkHeader( line.data(), line.size() ) ) { throw IndexFormat::BadDataError( IndexFormat::tr( "invalid header" ) ); } UIndex ind; while( !isEof( io ) ) { if( tsi.cancelFlag ) { return; } skipLinesAndWhites( io ); line.clear(); readLine( io, &line ); QByteArray section_name = line.trimmed(); SectionId sec_id = getSectionId( section_name ); switch( sec_id ) { case ITEM_SEC_ID: { UIndex::ItemSection item; UIndex::UIndexError err = UIndex::NO_ERR; readItemSection( io, item ); err = item.checkConsistentcy(); if( UIndex::NO_ERR == err ) { ind.items.push_back( item ); } else { // has errors throw IndexFormat::BadDataError( getErrorString( err ) ); } } break; case IO_SEC_ID: { UIndex::IOSection io_sec; UIndex::UIndexError err = UIndex::NO_ERR; readIOSection( io, io_sec ); err = io_sec.checkConsistentcy(); if( UIndex::NO_ERR == err ) { ind.ios.push_back( io_sec ); } else { throw IndexFormat::BadDataError( getErrorString( err ) ); } } break; default: throw IndexFormat::BadDataError( IndexFormat::tr( "Unknown section found" ) ); } tsi.progress = io->getProgress(); } UIndex::UIndexError err = ind.checkConsistency(); if( UIndex::NO_ERR != err ) { throw IndexFormat::BadDataError( getErrorString( err ) ); } if( !ind.hasItems() ) { throw IndexFormat::BadDataError( IndexFormat::tr( "no items found in index file" ) ); } UIndexObject* obj = new UIndexObject( ind, UIndexObject::OBJ_NAME ); obj_list.append( obj ); } static void writeOneWord( IOAdapter* io, const QByteArray& word ) { assert( NULL != io ); quint64 ret = 0; ret = io->writeBlock( word ); checkWriteError( word.size(), ret ); } static QByteArray quotedWord( const QByteArray& str ) { QByteArray word; int sz = str.size(); int i = 0; for( i = 0; i < sz; ++i ) { if( QUOTE[0] == str[i] ) { word.push_back( QUOTE ); } word.push_back( str[i] ); } return QUOTE + word + QUOTE; } static void writeTagValue( IOAdapter* io, const QByteArray& tag, const QByteArray& val ) { assert( NULL != io ); writeOneWord( io, quotedWord( tag ) ); writeOneWord( io, TAB ); writeOneWord( io, quotedWord( val ) ); writeOneWord( io, NEW_LINE ); } static void save( IOAdapter* io, const UIndex& ind ) { assert( NULL != io ); QList< UIndex::ItemSection > items = ind.items; QList< UIndex::IOSection > ios = ind.ios; //write header writeOneWord( io, IndexFormat::FILE_HEADER ); writeOneWord( io, NEW_LINE ); //write io sections foreach( UIndex::IOSection io_sec, ios ) { writeOneWord( io, IO_SEC + NEW_LINE ); writeTagValue( io, ID_TAG, io_sec.sectionId.toAscii() ); writeTagValue( io, ADAPT_TAG, io_sec.ioAdapterId.toAscii() ); writeTagValue( io, URL_TAG, io_sec.url.toAscii() ); QHash< QString, QString >::const_iterator it = io_sec.keys.begin(); while( io_sec.keys.end() != it ) { writeTagValue( io, it.key().toAscii(), it.value().toAscii() ); ++it; } writeOneWord( io, EOF_SECTION + NEW_LINE ); } //write items sections foreach( UIndex::ItemSection item, items ) { writeOneWord( io, ITEM_SEC + NEW_LINE ); writeTagValue( io, IO_TAG, item.ioSectionId.toAscii() ); writeTagValue( io, DOC_TAG, item.docFormat.toAscii() ); writeTagValue( io, START_OFF_TAG, QString::number( item.startOff ).toAscii() ); writeTagValue( io, END_OFF_TAG, QString::number( item.endOff ).toAscii() ); QHash< QString, QString >::const_iterator it = item.keys.begin(); while( item.keys.end() != it ) { writeTagValue( io, it.key().toAscii(), it.value().toAscii() ); ++it; } writeOneWord( io, EOF_SECTION + NEW_LINE ); } } namespace U2 { const QByteArray IndexFormat::FILE_HEADER = "UINDEX"; const QString IndexFormat::WRITE_LOCK_REASON = "Index files are read only"; IndexFormat::IndexFormat( QObject* obj ) : DocumentFormat( obj, DocumentFormatFlag_SupportWriting, QStringList("uind")) { format_name = tr("Index"); supportedObjectTypes+=GObjectTypes::UINDEX; } Document* IndexFormat::loadDocument( IOAdapter* io, TaskStateInfo& tsi, const QVariantMap& fs, DocumentLoadMode mode) { Q_UNUSED(mode); QList< GObject* > obj_list; try { load( io, obj_list, tsi ); assert( OBJECTS_IN_DOC == obj_list.size() || tsi.cancelFlag ); Document* doc = new Document( this, io->getFactory(), io->getURL(), obj_list, fs, WRITE_LOCK_REASON ); return doc; } catch ( const IndexFormatException& ex ) { tsi.setError(ex.msg); } catch( ... ) { tsi.setError(IndexFormat::tr( "Unknown error occurred" )); } qDeleteAll( obj_list ); return NULL; } void IndexFormat::storeDocument( Document* doc, TaskStateInfo& ts, IOAdapter* io) { try { foreach( GObject* p_obj, doc->getObjects() ) { const UIndexObject* ind_obj = qobject_cast< const UIndexObject* >( p_obj ); assert( NULL != ind_obj ); save( io, ind_obj->getIndex() ); } } catch( const IndexFormatException& ex ) { ts.setError(ex.msg); } catch(...) { ts.setError(IndexFormat::tr( "Unknown error occurred" )); } } RawDataCheckResult IndexFormat::checkRawData(const QByteArray& data, const GUrl&) const { bool headerIsOk = checkHeader( data.constData(), data.size()); return headerIsOk ? FormatDetection_Matched: FormatDetection_NotMatched; } bool IndexFormat::isObjectOpSupported(const Document* doc, DocumentFormat::DocObjectOp op, GObjectType t) const { if (!DocumentFormat::isObjectOpSupported(doc, op, t)) { return false; } if (op == DocumentFormat::DocObjectOp_Add) { return doc->getObjects().isEmpty(); } return false; } } // U2 ugene-1.9.8/src/corelibs/U2Formats/src/FastqFormat.h0000644000175000017500000000345711651544332020731 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_FASTQ_FORMAT_H_ #define _U2_FASTQ_FORMAT_H_ #include #include #include namespace U2 { class IOAdapter; class U2FORMATS_EXPORT FastqFormat : public DocumentFormat { Q_OBJECT public: FastqFormat(QObject* p); virtual DocumentFormatId getFormatId() const {return BaseDocumentFormats::FASTQ;} virtual const QString& getFormatName() const {return fn;} virtual Document* loadDocument(IOAdapter* io, TaskStateInfo& ti, const QVariantMap& fs, DocumentLoadMode mode = DocumentLoadMode_Whole); virtual GObject *loadObject( IOAdapter* io, TaskStateInfo& ti); virtual DNASequence *loadSequence( IOAdapter* io, TaskStateInfo& ti); virtual void storeDocument( Document* d, TaskStateInfo& ts, IOAdapter* io ); virtual RawDataCheckResult checkRawData(const QByteArray& rawData, const GUrl& = GUrl()) const; private: QString fn; }; }//namespace #endif ugene-1.9.8/src/corelibs/U2Formats/transl/0000755000175000017500000000000011651544332017034 5ustar ilyailyaugene-1.9.8/src/corelibs/U2Formats/transl/chinese.ts0000644000175000017500000021003511651544332021023 0ustar ilyailya Document Document is empty. 文档是空的。 SQLiteL10n Failed to detect assembly storage format: %1 检测数据集存储类型 %1 失败 Failed to parse packed row range info %1 Attribute not found! Unsupported attribute type: %1 不支持属性类型:%1 Not a %1 SQLite database: %2 %2 不是一个 %1 类型的 SQLite 数据库 Warning! Database of version %1 was created with a newer %2 version: %3. Not all database features are supported! U2::ABIFormat ABIF ABIF 格式 Not a valid ABIF file: %1 不是一个合法的 ABIF 文件:%1 U2::ACEFormat ACE ACE 格式 Line is too long 某一行太长 First line is not an ace header 第一行不是 ace 的头 No contig count tag in the header line 标头行里没有 contig 的计数标志 Must be CO keyword 必须是 CO 关键字 Unexpected end of file 未知的文件结尾 There is no note about reads count There is no AF note 没有 AF 注释 A name is duplicated 有名称重复 No consensus 不一致 BQ keyword hasn't been found 没有找到 BQ 关键字 Bad consensus data Bad AF note AF 注释错误 There is no read note No sequence 没有序列 QA keyword hasn't been found 没有找到 QA 关键字 QA error no clear range QA 错误:范围不清 QA error bad range QA 错误:范围错误 Bad sequence data 序列质量欠佳 A name is not match with AF names 有名称与 AF 名称不匹配 Alphabet unknown 序列的类型未知 U2::ASNFormat MMDB MMDB Standard residue dictionary not found Unknown error occurred 发生未知错误 no root element states stack is not empty First line is too long 首行过长 read error occurred 发生读取错误 biostruct3d obj loading error: %1 导入 biostruct3d 对象时发生错误:%1 U2::ClustalWAlnFormat CLUSTALW CLUSTALW 格式 Illegal header line 非法的标头行 Error parsing file 解析文件时发生错误 Invalid alignment format 非法的比对格式 Incorrect number of sequences in block 区块中的序列数量有误 Sequence names are not matched 序列名称不对应 Alphabet is unknown 序列的类型未知 U2::Document Document is empty. 文档是空的。 U2::DocumentFormatUtils Maximum number of objects per document limit reached. Try different options for opening the document! 已经超过每个文档允许的对象数目了,请尝试其它选项以打开该文档! Undefined sequence alphabet 无法确定序列类型 U2::EMBLGenbankAbstractDocument Reading entry header 正在读取标头行 Merge error: found annotations without sequence 合并时发生错误:有一些注释没有对应的序列 Annotation name is empty 注释的名称为空 Error parsing location 解析位置时发生错误 Unexpected line format 位置的行格式 Reading sequence %1 正在读取序列 %1 Error parsing sequence: unexpected empty line 解析序列时发生错误:存在未知的空行 Error reading sequence: invalid sequence format 读取序列时发生错误:序列格式不合法 Error reading sequence: memory allocation failed 读取序列时发生错误:分配内存失败 Sequence is truncated 序列已被截短 Reading annotations %1 正在读取注释 %1 Invalid format of feature table 特征列表的格式不合法 Line is too long. 某一行过长。 IO error. IO(输入/输出)错误。 Record is truncated. 记录已被截短。 Annotation start position is empty 某个注释的起始位置为空 Annotation end position is empty 某个注释的终止位置为空 U2::EMBLPlainTextFormat EMBL EMBL 格式 EMBL Flat File Format is a rich format for storing sequences and associated annotations EMBL 平文本文件格式是一种丰富型的序列格式,可存储序列以及与其相关的注释 ID is not the first line 第一行不是序列的 ID 号 Error parsing ID line 解析 ID 行时发生错误 U2::FastaFormat FASTA FASTA 格式 FASTA format is a text-based format for representing either nucleotide sequences or peptide sequences, in which base pairs or amino acids are represented using single-letter codes. The format also allows for sequence names and comments to precede the sequences. FASTA 是一种基于文本的核酸序列或蛋白质序列格式,每个碱基或氨基酸都使用单个字母来表示。该格式还可以在序列前面添加必要的名称和注释等。 Line is too long 某一行太长 First line is not a FASTA header 第一行不是 FASTA 格式的头 U2::FastqFormat FASTQ FASTQ 格式 FASTQ format is a text-based format for storing both a biological sequence (usually nucleotide sequence) and its corresponding quality scores. Both the sequence letter and quality score are encoded with a single ASCII character for brevity. It was originally developed at the Wellcome Trust Sanger Institute to bundle a FASTA sequence and its quality data, but has recently become the de facto standard for storing the output of high throughput sequencing instruments. FASTQ 是一种基于文本的序列格式,其存储的信息包括生物序列(一般是核酸序列)以及对应的测序质量评价得分。为了简单起见,序列的每个碱基和质量得分都分别以一个 ASCII 字符来表示。这种格式最初来源于 Wellcome Trust Sanger Institute,用于绑定 FASTA 序列与其对应的质量评价数据,但现在已经成为存储高通量测序结果的事实标准。 Unexpected end of file 未知的文件结尾 Not a valid FASTQ file: %1. The @ identifier is not found. 不是一个合法的 FASTQ 文件:%1,因为没有找到 @ 标识符。 Not a valid FASTQ file: %1 不是一个合法的 FASTQ 文件:%1 Not a valid FASTQ file: %1. Bad quality scores: inconsistent size. 不是一个合法的 FASTQ 文件:%1,质量评分有问题,与序列的长度不一致。 U2::GBFeatureUtils Sequence related to transcription termination 与转录终止相关的序列 Span of the C immunological feature C-免疫特征区 `CAAT box' in eukaryotic promoters 真核基因启动子中的 CAAT 盒(CAAT box) Sequence coding for amino acids in protein (includes stop codon) 蛋白质编码区(包括终止密码) Independent sequence determinations differ 不同测定结果所得的差异序列 Displacement loop D 环 Span of the D immunological feature D-免疫特征区 Cis-acting enhancer of promoter function 顺式作用增强子,强化启动子功能 Region that codes for part of spliced mRNA 外显子,成熟 mRNA 的一部分 Region that defines a functional gene, possibly including upstream (promotor, enhancer, etc) and downstream control elements, and for which a name has been assigned. 基因区域,包括上游启动子、增强子和下游控制区。 `GC box' in eukaryotic promoters 真核生物启动子中 GC 盒 Intervening DNA eliminated by recombination 重组引入的 DNA 插入区 Transcribed region excised by mRNA splicing 内含子,在 mRNA 剪切过程中被切除的转录区 Span of the J immunological feature J-免疫特征区 Long terminal repeat 长终止重复序列 Mature peptide coding region (does not include stop codon) 成熟肽编码区(不包括终止密码) Miscellaneous binding site 其它结合位点 Miscellaneous difference feature 其它特征区 Region of biological significance that cannot be described by any other feature 其它尚未确定的重要生物功能区 Miscellaneous, recombination feature 其它重组特征区 Miscellaneous transcript feature not defined by other RNA keys 其它尚未确定的转录特征区 Miscellaneous signal 其它信号区 Miscellaneous DNA or RNA structure 其它 DNA 或 RNA 结构 The indicated base is a modified nucleotide 修饰碱基 Messenger RNA 信使 RNA 区域 Span of the N immunological feature N-免疫特征区 Presented sequence revises a previous version 旧版本序列 Signal for cleavage & polyadenylation 剪切 & 多聚 A 信号区 Site at which polyadenine is added to mRNA mRNA 的多聚 A 添加位点 Any RNA species that is not yet the mature RNA product 前体 RNA Primary (unprocessed) transcript 初始(未处理)转录产物 Primer binding region used with PCR PCR 引物结合位点 Non-covalent primer binding site 引物非共价结合位点 A region involved in transcription initiation 启动子区域,参与转录起始过程 Non-covalent protein binding site on DNA or RNA 蛋白质非共价结合位点 Ribosome binding site 核糖体结合位点 Replication origin for duplex DNA DNA 双链复制起始区 Sequence containing repeated subsequences 重复序列区域 One repeated unit of a repeat_region 重复序列区域的重复单位 Ribosomal RNA 核糖体 RNA Span of the S immunological feature S-免疫特征区 Satellite repeated sequence 卫星 DNA 重复序列 Small cytoplasmic RNA 胞浆内小 RNA Signal peptide coding region 信号肽编码区 Small nuclear RNA 核内小 RNA Identifies the biological source of the specified span of the sequence 该序列的来源 Hair-pin loop structure in DNA or RNA DNA 或 RNA 中的发夹环结构 Sequence Tagged Site; operationally unique sequence that identifies the combination of primer spans used in a PCR assay 序列标签位点 `TATA box' in eukaryotic promoters 真核生物启动子中 TATA 盒(TATA box) Sequence causing transcription termination 转录终止位点 Transit peptide coding region 转运肽编码区 Transposable element (TN) 转座子(TN) Transfer RNA 转移 RNA Authors are unsure about the sequence in this region 未确定区 Span of the V immunological feature V-免疫特征区 A related population contains stable mutation 变异区 `Pribnow box' in prokaryotic promoters 原核生物启动子中的 -10 位点 `-35 box' in prokaryotic promoters 原核生物启动子中的 -35 位点 3'-most region of a precursor transcript removed in processing 前体 mRNA 在转录后加工时切除的 3’端区域 3' untranslated region (trailer) 3’ 端不翻译区域 5'-most region of a precursor transcript removed in processing 前体 mRNA 在转录后加工时切除的 5’端区域 5' untranslated region (leader) 5’ 端不翻译区域 'Protein' feature key 蛋白质 'Region' feature key 区域 'Site' feature key 位点 Genes 基因 Signals 信号 Binding 绑定 Variation 变异 Repeats 重复序列 RNA RNA Misc 未知区域 Spans 序列范围 U2::GFFFormat GFF GFF 格式 Parsing error: invalid header 解析错误:不合法的标头 Parsing error: file does not contain version header 解析错误:文件头部没有包含版本号 Parsing error: format version is not an integer 解析错误:版本号出现了非整数值 Parsing error: GFF version %1 is not supported 解析错误:不支持 GFF 版本 %1 Parsing error: sequence in FASTA sequence has whitespaces at line %1 解析错误:FASTA 序列的第 %1 行出现了空格 Parsing error: too few fields at line %1 解析错误:第 %1 行的条目太少 Parsing error: start position at line %1 is not integer 解析错误:第 %1 行的起始位置不是一个整数 Parsing error: end position at line %1 is not integer 解析错误:第 %1 行的结束位置不是一个整数 Parsing error: incorrect annotation region at line %1 解析错误:第 %1 行的注释区域不正确 Parsing error: one of the qualifiers in attributes are incorrect at line %1 解析错误:第 %1 行的属性值有错误 Wrong location for joined annotation at line %1. Line was skipped. 第 %1 行在连接注释时位置错误,已跳过该行。 U2::GenbankPlainTextFormat Genbank Genbank 格式 GenBank Flat File Format is a rich format for storing sequences and associated annotations GenBank 平文本文件格式是一种丰富型的序列格式,可存储序列以及与其相关的注释 LOCUS is not the first line 第一行不是 LOCUS 项 Error parsing LOCUS line 解析 LOCUS 这一行时发生错误 incomplete SOURCE record SOURCE(来源) 记录不完整 Error writing document 写入文档时发生错误 U2::IndexFormat Empty io identifier in item section Empty document format in item section 条目栏中文件格式为空 Empty io adapter identifier in io section Empty url in io section Bad offset in item section Unrecognized io section id in item section Unknown index error occurred 发生未知的索引错误 Bad value in item section: tag Bad value in item section: val invalid header 非法的头 Unknown section found no items found in index file 索引文件中没有找到条目 Index 索引 Unknown error occurred 发生未知错误 Read error occurred 发生读取错误 Write error occurred 发生写入错误 U2::MSFFormat MSF MSF 格式 MSF format is used to store multiple aligned sequences. Files include the sequence name and the sequence itself, which is usually aligned with other sequences in the file. MSF 是用于存储多序列比对的一种格式。文件包含序列的名称和序列本身,并且与文件中的其它序列进行了比对。 Incorrect format 错误的格式 Unexpected end of file 未知的文件结尾 Check sum test failed 未能通过求和测试 Alphabet unknown 序列的类型未知 U2::MegaFormat Mega Mega 格式 Found sequences of different sizes 有若干条序列长度不等 Model is of zero size Bad name of sequence 序列名称非法 Unexpected # in comments 注释中出现了未知的 # 号 A comment has not end 某条注释没有结尾 Unexpected symbol between comments 注释之间出现了未知符号 Incorrect format 错误的格式 Identical symbol at the first sequence Incorrect order of sequences' names 序列名称的顺序不正确 Alphabet unknown 序列的类型未知 No header 没有头 No # before header 头的前面没有 # 符号 Not MEGA-header 不是 MEGA-头 No data in file 文件中没有数据 Incorrect title 标题不正确 Sequence has empty part 序列有空白区 Bad symbols in a sequence 某条序列中有非法字符 U2::NEXUSFormat NEXUS NEXUS 格式 #NEXUS header missing #NEXUS 标头缺失 U2::NewickFormat Newick Standard 标准 Newick 格式 Newick is a simple format used to write out trees in a text file Newick 是一种在文本文件中描述进化树的简单格式 Unexpected weight: %1 Error parsing weight: %1 Unexpected weight start token: %1 Unexpected new sibling %1 Unexpected closing bracket :%1 未知的闭合括号:%1 Unexpected end of file 未知的文件结尾 Empty file 文件为空 U2::PDBFormat PDB PDB 格式 The Protein Data Bank (PDB) format provides a standard representation for macromolecular structure data derived from X-ray diffraction and NMR studies. PDB(蛋白质数据库)格式提供了蛋白分子结构的标准,多来源于 X 射线衍射或者 NMR 研究。 Line is too long 某一行太长 SPLIT recored is not supported 不支持 SPLIT 记录 Some mandaroty records are absent 缺失一些必需的记录 PDB warning: unknown residue name: %1 PDB 警告:未知的残基名称:%1 Invalid secondary structure record 存在非法的二级结构记录 Invalid SEQRES: less then 24 charachters 存在非法的 SEQRES:少于 24 个氨基酸 U2::PDWFormat pDRAW pDRAW 格式 Line is too long 某一行太长 U2::PlainTextFormat Plain text 平文本格式 A simple plain text file. 简单的平文本文件。 U2::RawDNASequenceFormat Raw sequence 原始序列格式 Raw sequence file - a whole content of the file is treated either as a single nucleotide or peptide sequence UGENE will remove all non-alphabetic chars from the result sequence 原始序列文件 - 文件的所有内容被视为单独的一条核酸序列或多肽序列,UGENE 会移除所有非字母的字符 Sequence is empty 序列为空 U2::SAMFormat Field "%1" not matched pattern "%2", expected pattern "%3" 栏目“%1”的模式“%2”没有匹配,应该匹配“%3” SAM SAM 格式 Unsupported file version "%1" 不支持版本“%1” Unexpected end of file 未知的文件结尾 Can't find alphabet for sequence "%1" 无法找到序列“%1”的类型 Can't translation for alphabet "%1" 无法翻译序列“%1” Alphabet is unknown 序列的类型未知 U2::SCFFormat SCF SCF 格式 Failed to parse SCF file: %1 解析 SCF 格式时发生错误:%1 U2::SQLiteL10N Error during RTree index creation: %1! Check if SQLite library has RTree index support! No location found for annotation: %1 在注释 %1 中未能找到位置 There is no assembly object with the specified id. 对于该 id 号没有合适的对象。 Unsupported reads storage type: %1 不支持读取存储类型 %1 Assembly object not found. 未能找到合适的对象。 Packing method is not supported: %1 不支持该种打包方式:%1 Packed data is empty! 打包的数据为空! Packing method prefix is not supported: %1 不支持该种打包方式索引:%1 Data is corrupted, no name end marker found: %1 数据有损坏,未能找到名称结束标记:%1 Data is corrupted, no sequence end marker found: %1 数据有损坏,未能找到序列结束标记:%1 Data is corrupted, no CIGAR end marker found: %1 数据有损坏,未能找到 CIGAR 结束标记:%1 Error checking SQLite database: %1! 检查 SQLite 数据库时发生错误:%1! Error creating table: %1, error: %2 创建表格 %1 时发生错误,错误类型:%2 Database is already opened! 数据库已经打开! Illegal database state: %1 非法的数据库状态:%1 URL is not specified 未指定 URL 地址 Error opening SQLite database: %1! 打开 SQLite 数据库时发生错误:%1! Database is already closed! 数据库已经关闭! Illegal database state %1! 非法的数据库状态 %1! Failed to close database: %1, err: %2 关闭数据库 %1 时发生错误,错误:%2 Not an object! Id: %1, type: %2 ID:%1,类型:%2 不是一个对象! Object: %1 not found in folder: %2 没有在目录 %2 中找到对象 %1 Unknown object type! Id: %1, type: %2 ID:%1,类型:%2 对象类型未知! Object not found. 没有找到对象。 Folder not found :%1 没有找到文件夹:%1 Sequence object not found. 没有找到序列对象。 Sequence object is not set! 没有设置序列对象! U2::StockholmFormat invalid file: bad header line 文件非法:标头行有错误 invalid file: empty sequence name 文件非法:缺失序列名字 invalid file: equal sequence names in one block 文件非法:某个区块内出现了相同的序列名字 invalid file: sequence names are not equal in blocks 文件非法:序列名字在各区块之间不一致 invalid file: sequences in block are not of equal size 文件非法:区块内的序列不等长 invalid file: empty sequence alignment 文件非法:存在空的序列比对 invalid file: unknown alphabet 文件非法:未知的序列类型 Stockholm Stockholm 格式 unknown error occurred 发生了未知错误 U2::SwissProtPlainTextFormat Swiss-Prot Swiss-Prot 格式 ID is not the first line 第一行不是序列的 ID 号 Error parsing ID line 解析 ID 行时发生错误 Error parsing ID line. Not found sequence length 解析 ID 行时发生错误:未找到序列长度 Reading sequence %1 正在读取序列 %1 Error parsing sequence: unexpected empty line 解析序列时发生错误:存在未知的空行 Error reading sequence: memory allocation failed 读取序列时发生错误:分配内存失败 Sequence is truncated 序列已被截短 Reading annotations %1 正在读取注释 %1 Invalid format of feature table 特征列表的格式不合法 ugene-1.9.8/src/corelibs/U2Formats/transl/russian.ts0000644000175000017500000016170111651544332021076 0ustar ilyailya Document Document is empty. Файл не содержит данных. U2::ABIFormat ABIF Not a valid ABIF file: %1 Некорректный ABIF файл: %1 U2::ACEFormat ACE Line is too long Строка слишком длинная First line is not an ace header Первая строка не является заголовком ACE No contig count tag in the header line Отсутствует тег числа контигов в строке заголовка Must be CO keyword Ожидается ключевое слово CO Unexpected end of file Неожиданный конец файла There is no note about reads count Отсуствтует информация о числе считываний There is no AF note Отсутствует A name is duplicated Повторные вхождения имени No consensus Отсутствует консенсунс BQ keyword hasn't been found Не найдено ключевое слово BQ Bad consensus data Плохие данные в консенсусе Bad AF note There is no read note No sequence Нет последовательности QA keyword hasn't been found Ключевое слово QA не было найдено QA error no clear range QA error bad range Ошибка QA: плохой регион Bad sequence data Некорректные данные в последовательности A name is not mutch with AF names Alphabet unknown Неизвестный алфавит U2::ASNFormat MMDB read error occurred Ошибка чтения biostruct3d obj loading error: %1 Ошибка загрузки трехмерной структуры: %1 Unknown error occurred Неизвестная ошибка no root element Отсутствует корневой элемент states stack is not empty Стек состояний не пуст First line is too long Первая строка слишком длинная Standard residue dictionary not found Стандартный словарь остатков не найден U2::ClustalWAlnFormat found_sequences_of_different_size Обнаружены последовательности разной длины model_of_0_size Модель нулевой длины illegal_header_line Неверный заголовок Illegal header line Неправильная строка заголовка Error parsing file Ошибка разбора формата Invalid alignment format Неверный формат выравнивания Incorrect number of sequences in block Неверное количество последовательностей в блоке Sequence names are not matched Встретилось непарное имя последовательности Alphabet is unknown Неизвестный алфавит CLUSTALW U2::Document Document is empty. Файл не содержит данных. U2::EMBLGenbankAbstractDocument Annotation name is empty Не указано имя аннотации Error parsing location Не указан регион аннотации Error parsing sequence: unexpected empty line Ошибка чтения последовательности: пустая строка Error reading sequence: invalid sequence format Ошибка чтения последовательности: неверный формат Error reading sequence: memory allocation failed Ошибка чтения последовательности: не удалось выделить память Unexpected line format Слишком длинная строка или неожиданный конец файла Reading entry header Чтение заголовка Merge error: found annotations without sequence Ошибка слияния: обнаружена таблица аннотаций без соотв последовательности. Reading sequence %1 Чтение последовательности: %1 Sequence is truncated Последовательность повреждена. Reading annotations %1 Чтение аннотаций: %1 Invalid format of feature table Таблица аннотаций повреждена. Line is too long. Слишком длинная строка. IO error. Ошибка чтения Record is truncated. Данные повреждены. U2::EMBLPlainTextFormat EMBL ID is not the first line Строка идентификатора должна идти первой Error parsing ID line Неверный заголовок U2::FastaFormat Line is too long Слишком длинная строка First line is not a FASTA header Неправильный заголовок FASTA FASTA U2::FastqFormat Unexpected end of file Неожиданный конец файла FASTQ Not a valid FASTQ file: %1. The @ identifier is not found. Некорректный FASTQ файл: %1. Идентификатор @ не найден. Not a valid FASTQ file: %1 Некорректный FASTQ файл: %1 Not a valid FASTQ file: %1. Bad quality scores: inconsistent size. Некорректный FASTQ файл: %1. Ошибка вычисления оценки точности: некорректный размер. U2::GBFeatureUtils Sequence related to transcription termination Span of the C immunological feature `CAAT box' in eukaryotic promoters Sequence coding for amino acids in protein (includes stop codon) Independent sequence determinations differ Displacement loop Span of the D immunological feature Cis-acting enhancer of promoter function Region that codes for part of spliced mRNA Region that defines a functional gene, possibly including upstream (promotor, enhancer, etc) and downstream control elements, and for which a name has been assigned. `GC box' in eukaryotic promoters Intervening DNA eliminated by recombination Transcribed region excised by mRNA splicing Span of the J immunological feature Long terminal repeat Mature peptide coding region (does not include stop codon) Miscellaneous binding site Miscellaneous difference feature Region of biological significance that cannot be described by any other feature Miscellaneous, recombination feature Miscellaneous transcript feature not defined by other RNA keys Miscellaneous signal Miscellaneous DNA or RNA structure The indicated base is a modified nucleotide Messenger RNA Span of the N immunological feature Presented sequence revises a previous version Signal for cleavage & polyadenylation Site at which polyadenine is added to mRNA Any RNA species that is not yet the mature RNA product Primary (unprocessed) transcript Primer binding region used with PCR Non-covalent primer binding site A region involved in transcription initiation Non-covalent protein binding site on DNA or RNA Ribosome binding site Replication origin for duplex DNA Sequence containing repeated subsequences One repeated unit of a repeat_region Ribosomal RNA Span of the S immunological feature Satellite repeated sequence Small cytoplasmic RNA Signal peptide coding region Small nuclear RNA Identifies the biological source of the specified span of the sequence Hair-pin loop structure in DNA or RNA Sequence Tagged Site; operationally unique sequence that identifies the combination of primer spans used in a PCR assay `TATA box' in eukaryotic promoters Sequence causing transcription termination Transit peptide coding region Transposable element (TN) Transfer RNA Authors are unsure about the sequence in this region Span of the V immunological feature A related population contains stable mutation `Pribnow box' in prokaryotic promoters `-35 box' in prokaryotic promoters 3'-most region of a precursor transcript removed in processing 3' untranslated region (trailer) 5'-most region of a precursor transcript removed in processing 5' untranslated region (leader) 'Protein' feature key 'Region' feature key 'Site' feature key Genes Signals Binding Variation Repeats RNA Misc Spans U2::GFFFormat GFF Parsing error: invalid header Parsing error: file does not contain version header Parsing error: format version is not an integer Parsing error: GFF version %1 is not supported Parsing error: too few fields at line %1 Parsing error: start position at line %1 is not integer Parsing error: end position at line %1 is not integer Parsing error: incorrect annotation region at line %1 Parsing error: one of the qualifiers in attributes are incorrect Wrong location for joined annotation at line %1. Line was skipped. Fasta sequence inclusion is not supported for GFF U2::GenbankPlainTextFormat Error writing document Ошибка записи Genbank LOCUS is not the first line Строка локуса должна идти первой Error parsing LOCUS line Ошибка чтения локуса incomplete SOURCE record Данные повреждены: запись SOURCE U2::IndexFormat Index Индекс Read error occurred Ошибка чтения Write error occurred Ошибка записи Empty io identifier in item section Пустой идентификатор в секции 'item' Empty document format in item section Не задан формат документа в секции 'item' Empty io adapter identifier in io section Не задан идентификатор адаптера файла в секции 'io' Empty url in io section Не задан путь к файлу в секции 'io' Bad offset in item section Неверное смещение в секции 'io' Unrecognized io section id in item section Неверный идентификатор адаптера файла в сеции 'item' Unknown index error occurred Произошла неизвестная ошибка invalid header Неверный заголовок файла Unknown section found Неизвестная секция файла no items found in index file Не найдено ни одной секции 'item' Unknown error occurred Неизвестная ошибка Bad value in item section: tag Bad value in item section: val U2::MSFFormat MSF Incorrect format Неверный формат Unexpected end of file Неожиданный конец файла Check sum test failed Проверка контрольной суммы не удалась Alphabet unknown Неизвестный алфавит U2::MegaFormat Mega MEGA Found sequences of different sizes Обнаружены последовательности разной длины Model is of zero size Модель нулевой длины Bad name of sequence Неверное имя последовательности Unexpected # in comments Неожиданный символ "#" в комментариях A comment has not end У комментария отсутствует окончание Unexpected symbol between comments Неоижданные символы между комментариями Incorrect format Неверный формат Identical symbol at the first sequence Идентичный символ в первой последовательности Incorrect order of sequences' names Неправильный порядок имён последовательностей Alphabet unknown Неизвестный алфавит No header Отсутствует заголовок No # before header Отсутствует символ "#" перед заголовком Not MEGA-header Не является заголовком MEGA No data in file Отсутствуют данные в файле Incorrect title Неправильный заголовок Sequence has empty part Часть последовательности пустая Bad symbols in a sequence Некорректные символы в последовательности U2::NEXUSFormat NEXUS #NEXUS header missing U2::NewickFormat Newick Standard Стандарт Newick Unexpected weight: %1 Неожиданный вес: %1 Error parsing weight: %1 Ошибка обработки веса: %1 Unexpected weight start token: %1 Unexpected new sibling %1 Unexpected closing bracket :%1 Неожиданная закрывающая скобка: %1 Unexpected end of file Неожиданный конец файла Empty file Файл пуст U2::PDBFormat Line is too long Слишком длинная строка SPLIT recored is not supported Some mandaroty records are absent PDB warning: unknown residue name: %1 Invalid secondary structure record Invalid SEQRES: less then 24 charachters PDB U2::PlainTextFormat Plain text Текст U2::RawDNASequenceFormat Raw sequence Произвольная последовательность Seqeunce is empty Последовательность пуста U2::SAMFormat Field "%1" not matched pattern "%2", expected pattern "%3" SAM Unsupported file version "%1" Неподдерживаемая версия файла "%1" Unexpected end of file Неожиданный конец файла Unexpected reference sequence name value "%1" Неожиданное значение имени референсной последовательности "%1" Alphabet is unknown Неизвестный алфавит U2::SCFFormat SCF Not a valid SCF file: %1 Некорректный SCF файл: %1 U2::SRFastaFormat ShortReadsFasta Line is too long Строка слишком длинная first_line_is_not_a_fasta_header Неправильный заголовок FASTA Incorrect sequence header: offset is not present Неправильный заголовок последовательности: отсутствует смещение Incorrect sequence header: unable to parse sequence offset Неправильный заголовок последовательности: невозможно обработать смещение последовательности First line is not a FASTA header Первая строка не является заголовком FASTA Alphabet is unknown Неизвестный алфавит U2::StockholmFormat Stockholm unknown error occurred Ошибка invalid file: bad header line Неверный заголовок invalid file: empty sequence name Не указано имя последовательности invalid file: equal sequence names in one block одинаковые имена последовательностей в блоке invalid file: sequence names are not equal in blocks Непарное имя последовательности в блоке invalid file: sequences in block are not of equal size Блок содержит последовательности разной длины invalid file: empty sequence alignment Выравнивание не содержит последовательностей invalid file: unknown alphabet Не удалось установить алфавит ugene-1.9.8/src/corelibs/U2Formats/transl/czech.ts0000644000175000017500000017041711651544332020512 0ustar ilyailya Document Document is empty. Dokument je prázdný. U2::ABIFormat ABIF Not a valid ABIF file: %1 Není platným souborem ABIF: %1 U2::ACEFormat ACE Line is too long First line is not an ace header No contig count tag in the header line Must be CO keyword Unexpected end of file There is no note about reads count There is no AF note A name is duplicated No consensus BQ keyword hasn't been found Bad consensus data Bad AF note There is no read note No sequence QA keyword hasn't been found QA error no clear range QA error bad range Bad sequence data A name is not mutch with AF names Alphabet unknown U2::ASNFormat MMDB read error occurred Vyskytla se chyba čtení biostruct3d obj loading error: %1 Chyba při nahrávání biostruct3d obj: %1 Unknown error occurred Vyskytla se neznámá chyba no root element žádný kořenový prvek states stack is not empty Zásobník stavů není prázdný First line is too long První řádek je příliš dlouhý Standard residue dictionary not found Běžný slovník reziduí nenalezen U2::ClustalWAlnFormat found_sequences_of_different_size Found sequences of different sizes model_of_0_size Model is of zero size illegal_header_line Illegal header line Illegal header line Neplatný řádek záhlaví Error parsing file Chyba při zpracování souboru Invalid alignment format Neplatný formát zarovnání Incorrect number of sequences in block Nesprávný počet sekvencí v bloku Sequence names are not matched Názvy sekvencí se neshodují Alphabet is unknown Abeceda je neznámá error_parsing_file Error parsing file invalid_alignment_format Invalid alignment format incorrect_num_seqs_in_block Incorrect number of sequences in block seq_name_not_matched Sequence names are not matched alphabet_unknown Alphabet is unknown CLUSTALW U2::Document Document is empty. Dokument je prázdný. U2::EMBLGenbankAbstractDocument annotation_name_is_empty Annotation name is empty annotation_location_is_empty Error parsing location error_reading_sequence_abnormal_term Error parsing sequence: unexpected empty line error_reading_sequence_invalid_format Error reading sequence: invalid sequence format erorr_reading_sequence_enable_to_add_more_data Error reading sequence: memory allocation failed line_is_too_long_or_unexpected_oef Unexpected line format Reading entry header Čte se záhlaví záznamu Merge error: found annotations without sequence Chyba při slučování: nalezeny poznámky bez sekvence Annotation name is empty Název poznámky je prázdný Error parsing location Chyba při zpracování umístění poznámky Unexpected line format Neočekávaný formát řádku Reading sequence %1 Čte se sekvence %1 Error parsing sequence: unexpected empty line Chyba při zpracování sekvence: neočekávaný prázdný řádek Error reading sequence: invalid sequence format Chyba při čtení sekvence: neplatný formát sekvence Error reading sequence: memory allocation failed Chyba při čtení sekvence: přidělení paměti selhalo Sequence is truncated Sekvence je zkrácena Reading annotations %1 Čtou se poznámky %1 Invalid format of feature table Neplatný formát nebo tabulka funkcí Line is too long. Řádek je příliš dlouhý. IO error. Chyba I/O. Record is truncated. Záznam je zkrácen. U2::EMBLPlainTextFormat EMBL ID is not the first line ID není na prvním řádku Error parsing ID line Chyba při zpracování řádku s ID U2::FastaFormat line_is_too_long Line is too long first_line_is_not_a_fasta_header First line is not a FASTA header FASTA FASTA Line is too long Řádek je příliš dlouhý First line is not a FASTA header První řádek není hlavičkou FASTA U2::FastqFormat Unexpected end of file Neočekávaný konec souboru FASTQ Not a valid FASTQ file: %1. The @ identifier is not found. Neplatný soubor FASTQ: %1. Identifikátor @ nenalezen. Not a valid FASTQ file: %1 Neplatný soubor FASTQ: %1 Not a valid FASTQ file: %1. Bad quality scores: inconsistent size. Neplatný soubor FASTQ: %1. Špatné výsledky u kvality: odporující si velikost. U2::GBFeatureUtils Sequence related to transcription termination Sekvence mající spojitost s ukončením přepisu (transkripce) Span of the C immunological feature Rozpětí imunologického rysu C `CAAT box' in eukaryotic promoters `CAAT box' v eukaryotických pořadatelích Sequence coding for amino acids in protein (includes stop codon) Kódování sekvence pro aminokyseliny v bílkovině (zahrnuje zastavovací kodon) Independent sequence determinations differ Odlišení určení nezávislé sekvence Displacement loop Smyčka přemístění Span of the D immunological feature Rozpětí imunologického rysu D Cis-acting enhancer of promoter function Cis-sloužící vylepšovač funkce pořadatele Region that codes for part of spliced mRNA Oblast, která kóduje pro část stočené mRNA Region that defines a functional gene, possibly including upstream (promotor, enhancer, etc) and downstream control elements, and for which a name has been assigned. Oblast stanovující funkční gen, možná včetně ovládacích prvků proti proudu (pořadatel, vylepšovač atd.) a po proudu, a kterému byl přiřazen název. `GC box' in eukaryotic promoters `GC box' v eukaryotických pořadatelích Intervening DNA eliminated by recombination Mezilehlá DNA odstraněná rekombinací Transcribed region excised by mRNA splicing Přepsaná oblast vynechaná spojováním mRNA Span of the J immunological feature Rozpětí imunologického rysu J Long terminal repeat Dlouhé konečné opakování Mature peptide coding region (does not include stop codon) Oblast kódování zralého peptidu (nezahrnuje stavěcí kodon) Miscellaneous binding site Různé vázající místo Miscellaneous difference feature Různý rozlišovací znak Region of biological significance that cannot be described by any other feature Oblast s biologickým významem, kterou nelze popsat žádným jiným znakem Miscellaneous, recombination feature Různé, znak rekombinace Miscellaneous transcript feature not defined by other RNA keys Různý znak přepisu (transkripce) nevymezený v jiných klíčích RNA Miscellaneous signal Různá znamení Miscellaneous DNA or RNA structure Různá stavba DNA nebo RNA The indicated base is a modified nucleotide Naznačený základ je pozměněným nukleotidem Messenger RNA RNA nositel biologické informace Span of the N immunological feature Rozpětí imunologického rysu N Presented sequence revises a previous version Předložená sekvence poopravuje předchozí verzi Signal for cleavage & polyadenylation Znamení pro buněčné dělení & polyadenylaci Site at which polyadenine is added to mRNA Místo, na kterém je polyadenin přidán do mRNA Any RNA species that is not yet the mature RNA product Jakýkoli druh RNA, který ještě není zralým produktem RNA Primary (unprocessed) transcript Hlavní (nezpracovaný) přepis (transkripce) Primer binding region used with PCR Základová vázající oblast použitá s PCR Non-covalent primer binding site Nekovalentní základové vázající místo A region involved in transcription initiation Oblast zapojená do zahájení přepisu (transkripce) Non-covalent protein binding site on DNA or RNA Nekovalentní bílkovinné vázající místo na DNA nebo RNA Ribosome binding site Ribozomové vázající místo Replication origin for duplex DNA Původ replikace pro zdvojenou DNA Sequence containing repeated subsequences Sekvence obsahující opakující se podsekvence One repeated unit of a repeat_region Jedna opakující se jednotka oblasti opakování Ribosomal RNA Ribozomová RNA Span of the S immunological feature Rozpětí imunologického rysu S Satellite repeated sequence Přidružená opakující se sekvence Small cytoplasmic RNA Malá cytoplazmatická RNA Signal peptide coding region Oblast kódování významného peptidu Small nuclear RNA Malá jaderná RNA Identifies the biological source of the specified span of the sequence Určuje biologický zdroj daného rozpětí sekvence Hair-pin loop structure in DNA or RNA Vlásenková stavba smyčky v DNA nebo RNA Sequence Tagged Site; operationally unique sequence that identifies the combination of primer spans used in a PCR assay Označené místo sekvence; provozně jedinečná sekvence, která určuje spojení rozpětí základové barvy použitých ve zkoušce PCR `TATA box' in eukaryotic promoters `TATA box' v eukaryotických předkladatelích Sequence causing transcription termination Sekvence způsobující ukončení přepisu (transkripce) Transit peptide coding region Oblast kódování průjezdního peptidu Transposable element (TN) Transpozon (přemístitelná část genetického materiálu, TN) Transfer RNA Přenést RNA Authors are unsure about the sequence in this region Autoři si sekvencí v této oblasti nejsou jisti Span of the V immunological feature Rozpětí imunologického rysu V A related population contains stable mutation Související populace obsahuje stálou mutaci `Pribnow box' in prokaryotic promoters `Pribnow box' v prokaryotických předkladatelích `-35 box' in prokaryotic promoters `-35 box' v prokaryotických předkladatelích 3'-most region of a precursor transcript removed in processing Oblast 3'-most přepisu (transkripce) předchůdce odstraněna při zpracování 3' untranslated region (trailer) 3' nepřeložená oblast (na konci) 5'-most region of a precursor transcript removed in processing Oblast 5'-most přepisu (transkripce) předchůdce odstraněna při zpracování 5' untranslated region (leader) 5' nepřeložená oblast (na začátku) 'Protein' feature key 'Region' feature key 'Site' feature key Genes Geny Signals Signály Binding Vazba Variation Obměna Repeats Opakování RNA Misc Různé Spans Rozpětí U2::GFFFormat GFF Parsing error: invalid header Chyba zpracování: neplatná hlavička Parsing error: file does not contain version header Chyba zpracování: soubor neobsahuje hlavičku s verzí Parsing error: format version is not an integer Chyba zpracování: formát verze není celé číslo Parsing error: GFF version %1 is not supported Chyba zpracování: verze %1 není podporována Parsing error: too few fields at line %1 Chyba zpracování: příliš mnoho polí na řádku %1 Parsing error: start position at line %1 is not integer Chyba zpracování: začáteční poloha na řádku %1 není celé číslo Parsing error: end position at line %1 is not integer Chyba zpracování: koncová poloha na řádku %1 není celé číslo Parsing error: incorrect annotation region at line %1 Chyba zpracování: nesprávná oblast s poznámkou na řádku %1 Parsing error: one of the qualifiers in attributes are incorrect Chyba zpracování: jeden z modifikátorů ve vlastnostech není správný Wrong location for joined annotation at line %1. Line was skipped. Fasta sequence inclusion is not supported for GFF U2::GenbankPlainTextFormat error writing document Error writing document Genbank LOCUS is not the first line LOCUS není první řádek Error parsing LOCUS line Chyba při zpracování řádku LOCUS incomplete SOURCE record Neúplný SOURCE záznam Error writing document Chyba při zápisu dokumentu U2::IndexFormat Index Rejstřík Read error occurred Vyskytla se chyba čtení Write error occurred Vyskytla se chyba zápisu Empty io identifier in item section Prázdný identifikátor IO v položkové části Empty document format in item section Prázdný formát dokumentu v položkové části Empty io adapter identifier in io section Prázdný identifikátor adaptéru IO v části IO Empty url in io section Prázdná adresa (URL) v části IO Bad offset in item section Špatný posun v položkové části Unrecognized io section id in item section Nerozpoznaný identifikátor části IO v části IO Unknown index error occurred Vyskytla se neznámá chyba rejstříku invalid header Neplatná hlavička Unknown section found Nalezena neznámá část no items found in index file V souboru s rejstříkem nebyly nalezeny žádné položky Unknown error occurred Vyskytla se neznámá chyba Bad value in item section: tag Špatná hodnota v položkové části: tag Bad value in item section: val Špatná hodnota v položkové části: val U2::MSFFormat MSF Incorrect format Nesprávný formát Unexpected end of file Neočekávaný konec souboru Check sum test failed Zkouška kontrolního součtu se nezdařila Alphabet unknown Neznámá abeceda U2::MegaFormat Mega Found sequences of different sizes Model is of zero size Bad name of sequence Unexpected # in comments A comment has not end Unexpected symbol between comments Incorrect format Identical symbol at the first sequence Incorrect order of sequences' names Alphabet unknown No header No # before header Not MEGA-header No data in file Incorrect title Sequence has empty part Bad symbols in a sequence U2::NEXUSFormat NEXUS #NEXUS header missing U2::NewickFormat Newick Standard Unexpected weight: %1 Neočekávaná váha: %1 Error parsing weight: %1 Chyba při zpracování váhy: %1 Unexpected weight start token: %1 Neočekávaný symbol na začátku váhy: %1 Unexpected new sibling %1 Unexpected closing bracket :%1 Neočekávaná zavírající závorka:%1 Unexpected end of file Neočekávaný konec souboru Empty file Prázdný soubor weight_unexpected_%1 Unexpected weight: %1 weight_parse_error_%1 Error parsing weight: %1 unexpected_weight_start_%1 Unexpected weight start token: %1 unexpected_closing_bracket_%1 Unexpected closing bracket :%1 unexpected_eof Unexpected end of file U2::PDBFormat line_is_too_long Line is too long SPLIT_record_not_supported SPLIT recored is not supported mandatory_records_absent Some mandaroty records are absent invalid_header_record Invalid HEADER record ivalid_atom_record Invalid ATOM record invalid_secondary_structure_record Invalid secondary structure record compound_record_is_empty COMPND record is empty invalid_compound_record Invalid COMPND record invalid_seqres_less_then_24 Invalid SEQRES: less then 24 charachters invalid_seqres_chain_index_not_found Invalid SEQRES: chain index not found PDB Line is too long Řádek je příliš dlouhý SPLIT recored is not supported SPLIT zaznamenaný není podporován Some mandaroty records are absent Některé povinné záznamy nejsou přítomné PDB warning: unknown residue name: %1 Varování: neznámý název zbytku: %1 Invalid secondary structure record Neplatný záznam vedlejší stavby Invalid SEQRES: less then 24 charachters Neplatný SEQRES: méně než 24 znaků U2::PlainTextFormat plain_text_format Plain text Plain text Prostý text U2::RawDNASequenceFormat raw_dna_sequence_format Raw sequence sequence_is_empty Seqeunce is empty Raw sequence Surová sekvence Seqeunce is empty Sekvence je prázdná U2::SAMFormat Field "%1" not matched pattern "%2", expected pattern "%3" SAM Unsupported file version "%1" Nepodporovaná verze souboru "%1" Unexpected end of file Neočekávaný konec souboru Unexpected reference sequence name value "%1" Neočekávaná hodnota názvu srovnávací sekvence "%1" Alphabet is unknown Abeceda je neznámá alphabet_unknown Alphabet is unknown U2::SCFFormat SCF Not a valid SCF file: %1 Není platným souborem SCF: %1 U2::SRFastaFormat ShortReadsFasta Line is too long First line is not a FASTA header První řádek není hlavičkou FASTA Incorrect sequence header: unable to parse sequence offset Nesprávná hlavička sekvence: nelze zpracovat posun sekvence Incorrect sequence header: offset is not present Nesprávná hlavička sekvence: posun není přítomen Alphabet is unknown Abeceda je neznámá first_line_is_not_a_fasta_header First line is not a FASTA header U2::StockholmFormat Stockholm unknown error occurred Vyskytla se neznámá chyba invalid file: bad header line Neplatný soubor: špatný řádek v hlavičce invalid file: empty sequence name Neplatný soubor: prázdný název sekvence invalid file: equal sequence names in one block Neplatný soubor: stejné názvy sekvencí v jednom bloku invalid file: sequence names are not equal in blocks Neplatný soubor: názvy sekvencí nejsou v blocích stejné invalid file: sequences in block are not of equal size Neplatný soubor: sekvence v bloku nemají stejnou velikost invalid file: empty sequence alignment Neplatný soubor: prázdné zarovnání sekvence invalid file: unknown alphabet Neplatný soubor: neznámá abeceda ugene-1.9.8/src/corelibs/U2Formats/transl/english.ts0000644000175000017500000014024411651544332021042 0ustar ilyailya Document Document is empty. U2::ABIFormat ABIF Not a valid ABIF file: %1 U2::ACEFormat ACE Line is too long First line is not an ace header No contig count tag in the header line Must be CO keyword Unexpected end of file There is no note about reads count There is no AF note A name is duplicated No consensus BQ keyword hasn't been found Bad consensus data Bad AF note There is no read note No sequence QA keyword hasn't been found QA error no clear range QA error bad range Bad sequence data A name is not mutch with AF names Alphabet unknown U2::ASNFormat MMDB Standard residue dictionary not found Unknown error occurred no root element states stack is not empty First line is too long read error occurred biostruct3d obj loading error: %1 U2::ClustalWAlnFormat CLUSTALW Illegal header line Error parsing file Invalid alignment format Incorrect number of sequences in block Sequence names are not matched Alphabet is unknown U2::Document Document is empty. U2::EMBLGenbankAbstractDocument Reading entry header Merge error: found annotations without sequence Annotation name is empty Error parsing location Unexpected line format Reading sequence %1 Error parsing sequence: unexpected empty line Error reading sequence: invalid sequence format Error reading sequence: memory allocation failed Sequence is truncated Reading annotations %1 Invalid format of feature table Line is too long. IO error. Record is truncated. U2::EMBLPlainTextFormat EMBL ID is not the first line Error parsing ID line U2::FastaFormat FASTA Line is too long First line is not a FASTA header U2::FastqFormat FASTQ Unexpected end of file Not a valid FASTQ file: %1. The @ identifier is not found. Not a valid FASTQ file: %1 Not a valid FASTQ file: %1. Bad quality scores: inconsistent size. U2::GBFeatureUtils Sequence related to transcription termination Span of the C immunological feature `CAAT box' in eukaryotic promoters Sequence coding for amino acids in protein (includes stop codon) Independent sequence determinations differ Displacement loop Span of the D immunological feature Cis-acting enhancer of promoter function Region that codes for part of spliced mRNA Region that defines a functional gene, possibly including upstream (promotor, enhancer, etc) and downstream control elements, and for which a name has been assigned. `GC box' in eukaryotic promoters Intervening DNA eliminated by recombination Transcribed region excised by mRNA splicing Span of the J immunological feature Long terminal repeat Mature peptide coding region (does not include stop codon) Miscellaneous binding site Miscellaneous difference feature Region of biological significance that cannot be described by any other feature Miscellaneous, recombination feature Miscellaneous transcript feature not defined by other RNA keys Miscellaneous signal Miscellaneous DNA or RNA structure The indicated base is a modified nucleotide Messenger RNA Span of the N immunological feature Presented sequence revises a previous version Signal for cleavage & polyadenylation Site at which polyadenine is added to mRNA Any RNA species that is not yet the mature RNA product Primary (unprocessed) transcript Primer binding region used with PCR Non-covalent primer binding site A region involved in transcription initiation Non-covalent protein binding site on DNA or RNA Ribosome binding site Replication origin for duplex DNA Sequence containing repeated subsequences One repeated unit of a repeat_region Ribosomal RNA Span of the S immunological feature Satellite repeated sequence Small cytoplasmic RNA Signal peptide coding region Small nuclear RNA Identifies the biological source of the specified span of the sequence Hair-pin loop structure in DNA or RNA Sequence Tagged Site; operationally unique sequence that identifies the combination of primer spans used in a PCR assay `TATA box' in eukaryotic promoters Sequence causing transcription termination Transit peptide coding region Transposable element (TN) Transfer RNA Authors are unsure about the sequence in this region Span of the V immunological feature A related population contains stable mutation `Pribnow box' in prokaryotic promoters `-35 box' in prokaryotic promoters 3'-most region of a precursor transcript removed in processing 3' untranslated region (trailer) 5'-most region of a precursor transcript removed in processing 5' untranslated region (leader) 'Protein' feature key 'Region' feature key 'Site' feature key Genes Signals Binding Variation Repeats RNA Misc Spans U2::GFFFormat GFF Parsing error: invalid header Parsing error: file does not contain version header Parsing error: format version is not an integer Parsing error: GFF version %1 is not supported Parsing error: too few fields at line %1 Parsing error: start position at line %1 is not integer Parsing error: end position at line %1 is not integer Parsing error: incorrect annotation region at line %1 Parsing error: one of the qualifiers in attributes are incorrect Wrong location for joined annotation at line %1. Line was skipped. Fasta sequence inclusion is not supported for GFF U2::GenbankPlainTextFormat Genbank LOCUS is not the first line Error parsing LOCUS line incomplete SOURCE record Error writing document U2::IndexFormat Empty io identifier in item section Empty document format in item section Empty io adapter identifier in io section Empty url in io section Bad offset in item section Unrecognized io section id in item section Unknown index error occurred Bad value in item section: tag Bad value in item section: val invalid header Unknown section found no items found in index file Index Unknown error occurred Read error occurred Write error occurred U2::MSFFormat MSF Incorrect format Unexpected end of file Check sum test failed Alphabet unknown U2::MegaFormat Mega Found sequences of different sizes Model is of zero size Bad name of sequence Unexpected # in comments A comment has not end Unexpected symbol between comments Incorrect format Identical symbol at the first sequence Incorrect order of sequences' names Alphabet unknown No header No # before header Not MEGA-header No data in file Incorrect title Sequence has empty part Bad symbols in a sequence U2::NEXUSFormat NEXUS #NEXUS header missing U2::NewickFormat Newick Standard Unexpected weight: %1 Error parsing weight: %1 Unexpected weight start token: %1 Unexpected new sibling %1 Unexpected closing bracket :%1 Unexpected end of file Empty file U2::PDBFormat PDB Line is too long SPLIT recored is not supported Some mandaroty records are absent PDB warning: unknown residue name: %1 Invalid secondary structure record Invalid SEQRES: less then 24 charachters U2::PlainTextFormat Plain text U2::RawDNASequenceFormat Raw sequence Seqeunce is empty U2::SAMFormat Field "%1" not matched pattern "%2", expected pattern "%3" SAM Unsupported file version "%1" Unexpected end of file Unexpected reference sequence name value "%1" Alphabet is unknown U2::SCFFormat SCF Not a valid SCF file: %1 U2::SRFastaFormat ShortReadsFasta Line is too long First line is not a FASTA header Incorrect sequence header: unable to parse sequence offset Incorrect sequence header: offset is not present Alphabet is unknown U2::StockholmFormat invalid file: bad header line invalid file: empty sequence name invalid file: equal sequence names in one block invalid file: sequence names are not equal in blocks invalid file: sequences in block are not of equal size invalid file: empty sequence alignment invalid file: unknown alphabet Stockholm unknown error occurred ugene-1.9.8/src/corelibs/U2Gui/0000755000175000017500000000000011651544333014643 5ustar ilyailyaugene-1.9.8/src/corelibs/U2Gui/U2Gui.qrc0000644000175000017500000001063611651544332016312 0ustar ilyailya images/add_existing_document.png images/arrow_rotate_clockwise.png images/add_new_document.png images/adv_widget_menu.png images/create_annotation.png images/create_annotation_icon.png images/group_green_active.png images/zoom_in.png images/zoom_out.png images/zoom_sel.png images/zoom_reg.png images/zoom_rows.png images/zoom_whole.png images/document.png images/ro_document.png images/gobject.png images/copy_sequence.png images/copy_complement_sequence.png images/copy_translation.png images/copy_complement_translation.png images/copy_annotation_sequence.png images/copy_annotation_translation.png images/find_dialog.png images/remove_selected_documents.png images/load_selected_documents.png images/annotation_settings.png images/lock.png images/lock_open.png images/unload_document.png images/select_region.png images/goto.png images/msa.png images/plus.png images/minus.png images/tt_switch.png images/show_compl.png images/show_trans.png images/bookmark_add.png images/bookmark_edit.png images/bookmark_remove.png images/bookmark_item.png images/bookmark.png images/bookmark_inactive.png images/add_column.png images/remove_column.png images/color_wheel.png images/msaed_remove_columns_with_gaps.png images/msaed_remove_all_gaps.png images/uindexview_select_field.png images/predefined_annotation_groups.png images/lock_scales.png images/sync_lock.png images/sync_scales.png images/ruler.png images/table.png images/table_add.png images/do_complement.png images/group_auto.png images/sw.png images/chart_bar.png images/align.png images/biostruct3d.png images/texto.png images/msa_find_prev.png images/msa_find_next.png images/font.png images/font_default.png images/ssp_logo.png images/cam2.png images/chart_organisation.png images/page_refresh.png images/printer.png images/phylip.png images/sam.png images/sort_ascending.png images/remote_machine_monitor.png images/remote_machine_ping_yes.png images/remote_machine_ping_no.png images/remote_machine_ping_waiting_response.png images/text_ab.png images/align_tree_labels.png images/undo.png images/redo.png images/tree.png images/dna.png images/sum.png images/question.png images/close.png images/info_notification.png images/error_notification.png images/pushpin.png images/pushpin_fixed.png images/close_2.png images/dna_helix.png images/tree_layout.png images/notch.png ugene-1.9.8/src/corelibs/U2Gui/images/0000755000175000017500000000000011651544333016110 5ustar ilyailyaugene-1.9.8/src/corelibs/U2Gui/images/unload_document.png0000644000175000017500000000102611651544333021775 0ustar ilyailyaPNG  IHDRatEXtSoftwareAdobe ImageReadyqe<IDATxbd?!cP4[d H3$gA0as؀ظ a!dAp 0tf  mnnpzZß3e8nFF`/%{aR]`]|>rj8z@ǷIiW'/ի*j0VwM Ëȟ[ZӆR[MƳa /[KTe+&2+)RӗWΣPZGhP@#S?E@\w+tרއIENDB`ugene-1.9.8/src/corelibs/U2Gui/images/phylip.png0000644000175000017500000000030511651544333020121 0ustar ilyailyaPNG  IHDRaIDATxڵR  fy4B5[ocs,X v)102d Wj+g2j+k|AJޝX$M"u$ܼAc /YkA;s NMPxltOuۚ>.KװSIENDB`ugene-1.9.8/src/corelibs/U2Gui/images/bookmark_item.png0000644000175000017500000000604111651544332021441 0ustar ilyailyaPNG  IHDRa pHYs   OiCCPPhotoshop ICC profilexڝSgTS=BKKoR RB&*! J!QEEȠQ, !{kּ> H3Q5 B.@ $pd!s#~<<+"x M0B\t8K@zB@F&S`cbP-`'{[! eDh;VEX0fK9-0IWfH  0Q){`##xFW<+*x<$9E[-qWW.(I+6aa@.y24x6_-"bbϫp@t~,/;m%h^ uf@Wp~<5j>{-]cK'Xto(hw?G%fIq^D$.Tʳ?D*A, `6B$BB dr`)B(Ͱ*`/@4Qhp.U=pa( Aa!ڈbX#!H$ ɈQ"K5H1RT UH=r9\F;2G1Q= C7F dt1r=6Ыhڏ>C03l0.B8, c˱" VcϱwE 6wB aAHXLXNH $4 7 Q'"K&b21XH,#/{C7$C2'ITFnR#,4H#dk9, +ȅ3![ b@qS(RjJ4e2AURݨT5ZBRQ4u9̓IKhhitݕNWGw Ljg(gwLӋT071oUX**| J&*/Tު UUT^S}FU3S ԖUPSSg;goT?~YYLOCQ_ cx,!k u5&|v*=9C3J3WRf?qtN (~))4L1e\kXHQG6EYAJ'\'GgSSݧ M=:.kDwn^Loy}/TmG X $ <5qo</QC]@Caaᄑ.ȽJtq]zۯ6iܟ4)Y3sCQ? 0k߬~OCOg#/c/Wװwa>>r><72Y_7ȷOo_C#dz%gA[z|!?:eAAA!h쐭!ΑiP~aa~ 'W?pX15wCsDDDޛg1O9-J5*>.j<74?.fYXXIlK9.*6nl {/]py.,:@LN8A*%w% yg"/6шC\*NH*Mz쑼5y$3,幄'L Lݛ:v m2=:1qB!Mggfvˬen/kY- BTZ(*geWf͉9+̳ې7ᒶKW-X潬j9(xoʿܔĹdff-[n ڴ VE/(ۻCɾUUMfeI?m]Nmq#׹=TR+Gw- 6 U#pDy  :v{vg/jBFS[b[O>zG499?rCd&ˮ/~јѡ򗓿m|x31^VwwO| (hSЧc3- cHRMz%u0`:o_FLIDATxڤKQǿ'rRwp!P[Tn6GDES 9(wqzzk;N/;"" C@ $) L@$C&fwd@ H3>XԺ Ą8:H5T3g\lWgpΫT8,+iKЗ ~Xo7s)LU뼐!9g>fu9 ? b câ!Lz0p^/wLZUJ8Yg~چmP.$䉀Z]~l!xIENDB`ugene-1.9.8/src/corelibs/U2Gui/images/tree_layout.png0000644000175000017500000000126111651544333021152 0ustar ilyailyaPNG  IHDRasRGBbKGD pHYs  tIME '4H\1IDAT8ˍ=LQࢂh0hbXvvTYQj be JtY, 3H8K^=S;s7.nQjK3 ! rgz)EZbُ8L/U>(puMIENDB`ugene-1.9.8/src/corelibs/U2Gui/images/goto.png0000644000175000017500000000065311651544332017571 0ustar ilyailyaPNG  IHDRatEXtSoftwareAdobe ImageReadyqe<MIDATxb?%q?~õ wlj/M I 0AZHIOƆԃ} 4Pɻ/ s?2cc]k/3}t^ Хr2H÷~]o3|@֖oL'ỳ aj 6G B< e8z_pA ?~b5"ڌJn gc{k fgm:-L_M䜸?$:Ư1s}WUX 8|^0aGIENDB`ugene-1.9.8/src/corelibs/U2Gui/images/copy_complement_sequence.png0000644000175000017500000000125211651544332023702 0ustar ilyailyaPNG  IHDRatEXtSoftwareAdobe ImageReadyqe<LIDATxڤSKhAGEz"R1[[i/z`*hR < Z֊)<(jVE#ҘM6;/w&ݤ67 R<6gu=<*έf'!ͥ٘l>DRP,WpBB*|v?NE%x9)`KihJCCQ<9Ɍu{#R]>/QߘЪ3Iǜ[fp@ڥ?Ȉ0fi*R``iHZ.ԔeIh?_~oU5 J=] Y uwn>$3`^Jy@)e|ٶamYv% ֝ 3/qBR3(!q+!Q8l"#$P`I\o])51 IeºP?Yl:(}BKB&AGZb ! .F}D} =׈>!)hVAp$t&}!Y$օ>|BKLLobCyT?XI4Ch:Q2uWw.zo/CI!d ^J},琐S;*)*1VPsI!1Z\ CQ֠*hʐ)ƓY{]on`̀USXNjpdט6FA+r ɥWhi~.ꆄT@YAP y 83OSRk5[ ^|..E&Bʼn&3ɜhbyR'nAhPKc!!å^#.bj2%+@5M6gI?1M@25-!'Bke8+FOR&i9/xY a-a:Ka CfWWe29t 8-WiB0(c WH쨕hNa^@,IENDB`ugene-1.9.8/src/corelibs/U2Gui/images/table_add.png0000644000175000017500000000122711651544333020517 0ustar ilyailyaPNG  IHDRagAMA7tEXtSoftwareAdobe ImageReadyqe<)IDAT8˥OHTQ*ȨTFa4ۤBmMDUWQ EDhaDYZb,#j,7%&acλo[]|swϱ1rZh g5AiFA.ق(hvTSDCRҽpAhzJVQTᬿuߗlWR@D0l{ R'8^y/FĊ]]6ׁ7a2e4>c(syfr_O0X2>h:l:Rz'@rW+9rk<c(sZ)H- $ :FiiO_!:Ƕ<)xhAl! |b{J :vFB sYUt7p&uaʢư{G?~Xos ]L5t[ >;MS3yyKKN_ Di|(QW!9=A['(\^ܰ6:αm9X0ֱ`LIENDB`ugene-1.9.8/src/corelibs/U2Gui/images/align_tree_labels.png0000644000175000017500000000056711651544332022260 0ustar ilyailyaPNG  IHDRsO/sRGBbKGD pHYs  tIME  IDAT(œM0_TJ"x Ë{rnƥYegn<(!<(=>>Q1sk3`Ak(P׵( ޿=9,wpHeYzfƞ4Vl ˲[f3#cs ND``'o ܟ)Z%"ض "ro0MzEp1H"3 %^ u}FHԇ-ӄh8ޫL|=Z̩IENDB`ugene-1.9.8/src/corelibs/U2Gui/images/lock_open.png0000644000175000017500000000132711651544332020571 0ustar ilyailyaPNG  IHDRagAMA7tEXtSoftwareAdobe ImageReadyqe<iIDAT8ukQ;i )R5pB 7+) a܈@@Ņ ʕ4jh>3q\!{8{jzZ{+cc c̽ ^Pi@R!y+++Iպ199Зz|(OJ%h4h6OTRaNzq)bl6/A Pfgg) ; T3ưAOsjj:ohXk{ibbb BWWQSXk9s ш5IRkuO 9w*Q c(!hdUU|Hy|>) 4E1@(vSVOezn, %+ts$~[Zv'P($|̬K?ǰs;bXn E"9a9w.t]p8,~f3!̈́bb-]F(.;`YT} m+BQhh8]e d2)[wí#L%:{ aD<4mغ~gH(DM *߫yP5;N_r,X5u&`m$:8Lz(n4x6%ԨYbYck7#932%^H7r2y8;wwěDox(x>G }D{ޠR7 oug.IENDB`ugene-1.9.8/src/corelibs/U2Gui/images/ruler2.png0000644000175000017500000000067111651544333020035 0ustar ilyailyaPNG  IHDRatEXtSoftwareAdobe ImageReadyqe<[IDATxSJA=w& (&BD[m?O$46"(vAdQXňavggv((Z/\0dE/$#nn2TA$շtW>385 I=_LΌ aa,"8jQk| GEM$m$!a]w`_«ˬ3q<d[M`` h;Y x1Ė"t'Ʋ W@ l> iiU00,lup l2bC:WZk0:YŒ=9nWBy(o a"`=ZM?v1DYNcyڑY~3A*7k><`?ʥd`g!G Xa6 P+j(4SEtYk][/TSOZ/Q7Qr-:xŵ:Qjޝv\E,<)hˍkTͻحe|cElAǘn%ly#p2Ya4 ?}pl! zyzх2ׅÀDa()̻@f )$BIENDB`ugene-1.9.8/src/corelibs/U2Gui/images/sort_ascending.png0000644000175000017500000000077211651544333021626 0ustar ilyailyaPNG  IHDRatIME + ʆ pHYsiTSgAMA aIDATxc`@HLȜҶ_~l)d]Go3<<f*\1 L&_4\p2sc{A=_|9̀~C XYY JCǏ ̀,Ѻ@'}m l@W0|r1P7=;^L<;(0gzwnHa$>a@ ??@2JJJDZQ׻/..nǥ&cCa AOOoFooo%6͞ 7q11DO{p h{?ϰ_qx d.fziMD5Ro޼x4(F)ԁIENDB`ugene-1.9.8/src/corelibs/U2Gui/images/remote_machine_ping_yes.png0000644000175000017500000000103611651544333023472 0ustar ilyailyaPNG  IHDRatEXtSoftwareAdobe ImageReadyqe<IDATxڼ+DQHr0x6J6R3ERRbx&׻~jb0"in4a0@`@\.^gr=t:';z4;WVl䓊=R.JeO}>;]ZfF l4 >T*ue6/R) 8cR.hP.K@AD"bdL:ŀyT m6ۓzNN]0?ZPY($w ]bo{$ԆaAx<~x>H(RLNIENDB`ugene-1.9.8/src/corelibs/U2Gui/images/pushpin.png0000644000175000017500000000041311651544333020302 0ustar ilyailyaPNG  IHDR Vu\sRGBbKGDC pHYs  tIME 88!sIDAT(υ1P C_>UP/]BHBoq82THH$AROIERo켮x0&ο CbK=pNھDfDɿs@Jrl *pj3K-dFIENDB`ugene-1.9.8/src/corelibs/U2Gui/images/adv_widget_menu.png0000644000175000017500000000611611651544332021762 0ustar ilyailyaPNG  IHDRa pHYs   OiCCPPhotoshop ICC profilexڝSgTS=BKKoR RB&*! J!QEEȠQ, !{kּ> H3Q5 B.@ $pd!s#~<<+"x M0B\t8K@zB@F&S`cbP-`'{[! eDh;VEX0fK9-0IWfH  0Q){`##xFW<+*x<$9E[-qWW.(I+6aa@.y24x6_-"bbϫp@t~,/;m%h^ uf@Wp~<5j>{-]cK'Xto(hw?G%fIq^D$.Tʳ?D*A, `6B$BB dr`)B(Ͱ*`/@4Qhp.U=pa( Aa!ڈbX#!H$ ɈQ"K5H1RT UH=r9\F;2G1Q= C7F dt1r=6Ыhڏ>C03l0.B8, c˱" VcϱwE 6wB aAHXLXNH $4 7 Q'"K&b21XH,#/{C7$C2'ITFnR#,4H#dk9, +ȅ3![ b@qS(RjJ4e2AURݨT5ZBRQ4u9̓IKhhitݕNWGw Ljg(gwLӋT071oUX**| J&*/Tު UUT^S}FU3S ԖUPSSg;goT?~YYLOCQ_ cx,!k u5&|v*=9C3J3WRf?qtN (~))4L1e\kXHQG6EYAJ'\'GgSSݧ M=:.kDwn^Loy}/TmG X $ <5qo</QC]@Caaᄑ.ȽJtq]zۯ6iܟ4)Y3sCQ? 0k߬~OCOg#/c/Wװwa>>r><72Y_7ȷOo_C#dz%gA[z|!?:eAAA!h쐭!ΑiP~aa~ 'W?pX15wCsDDDޛg1O9-J5*>.j<74?.fYXXIlK9.*6nl {/]py.,:@LN8A*%w% yg"/6шC\*NH*Mz쑼5y$3,幄'L Lݛ:v m2=:1qB!Mggfvˬen/kY- BTZ(*geWf͉9+̳ې7ᒶKW-X潬j9(xoʿܔĹdff-[n ڴ VE/(ۻCɾUUMfeI?m]Nmq#׹=TR+Gw- 6 U#pDy  :v{vg/jBFS[b[O>zG499?rCd&ˮ/~јѡ򗓿m|x31^VwwO| (hSЧc3- cHRMz%u0`:o_FyIDATxԓ1OQ7" AZ C@굵$BiIk] (% fޣl 9#՛1@Ҡv жce޹Z" :*EiIƼ/zߣ< 5"s`#!vAz ^&"xp6zJ?%U[Qf؄a4M]+dȳ#",ԔuY=D.Y2ZP <uD;p4j~R5SfaMSgyG 5^I|x8||}@~!NW lmdP3] Ec|IENDB`ugene-1.9.8/src/corelibs/U2Gui/images/remove_column.png0000644000175000017500000000032011651544333021463 0ustar ilyailyaPNG  IHDRaIDATxcd0f<6 AEY$dXMLd@dVa 2̜i ~oAȆ]0w30 30Κ7.  ufb8IENDB`ugene-1.9.8/src/corelibs/U2Gui/images/copy_sequence.png0000644000175000017500000000120711651544332021457 0ustar ilyailyaPNG  IHDRatEXtSoftwareAdobe ImageReadyqe<)IDATxڤSMHQ>Sc.)WbEADK[DP; Z Fe~VG[-2?zfu}^™{g99wBX25eT Q qC]m%޴dn?'w_;eҿ­'I$}x: j*P41d '˵ ]]vg`LQTG1l'f3`.vO%9"?橙M͹ACUEQ\7¡/:amIHy8V5 at@sk<#}6݇@/1s;o?0|߿`" Wfcce04a Krrm))UFFf==_3p1ׯA |`qV^0KTTXX),,-Pq4yWY֯_ͭtKfϞk`Hedʃ5} @@Sϟ qrrrLf}ի,--JZ$Ur/fh.N`9D^P\ LLl@ĀCb|2@>?, ip4p# i bbbfg |_ +à@2rqq233;Hd/Lh!ƿtIENDB`ugene-1.9.8/src/corelibs/U2Gui/images/create_annotation_icon.png0000644000175000017500000000126411651544332023325 0ustar ilyailyaPNG  IHDRatEXtSoftwareAdobe ImageReadyqe<VIDATxڴSQHSa>Rge2sX CVDЃDA -!ŧ^ARBT4((aX锊D`K6vw;b1~9|QJ_oG|;X<:1 UBRJZJFnʕb&*in[P1²Fl@Nq1WbJ JX35z5.] ?8 1%tpt>ω7YAͩ_%+8xyzf7/CEVe Qa&e.2$gQ"ac *ٵM8O(pĩJm&&k%*K;eiqfH,MSBYC5os5N ((iV2lPdg}LkxK`|q$tu~wJg8vCC&fC@zI&}ń_O}Y#TmΦV -H6G{]#4p~4AcD 9lofZ\*^[ݾ) } {o,3 :vۨ5̧]45d4 n-`i6}ƼIENDB`ugene-1.9.8/src/corelibs/U2Gui/images/document.png0000644000175000017500000000046111651544332020434 0ustar ilyailyaPNG  IHDRaIDATxڥ AG &h`,K&AѿIpdE d2qO[ϯMo;c<*R|DEf%LS \@b#?G$<2+ab W+ے;pnJؾ_ ^ЧFxǬu a;`+p C4C } ;eI3 fvU a;`+)9M4C =Eg xn:ugzIENDB`ugene-1.9.8/src/corelibs/U2Gui/images/zoom_whole.png0000644000175000017500000000662211651544333021006 0ustar ilyailyaPNG  IHDRa pHYs   OiCCPPhotoshop ICC profilexڝSgTS=BKKoR RB&*! J!QEEȠQ, !{kּ> H3Q5 B.@ $pd!s#~<<+"x M0B\t8K@zB@F&S`cbP-`'{[! eDh;VEX0fK9-0IWfH  0Q){`##xFW<+*x<$9E[-qWW.(I+6aa@.y24x6_-"bbϫp@t~,/;m%h^ uf@Wp~<5j>{-]cK'Xto(hw?G%fIq^D$.Tʳ?D*A, `6B$BB dr`)B(Ͱ*`/@4Qhp.U=pa( Aa!ڈbX#!H$ ɈQ"K5H1RT UH=r9\F;2G1Q= C7F dt1r=6Ыhڏ>C03l0.B8, c˱" VcϱwE 6wB aAHXLXNH $4 7 Q'"K&b21XH,#/{C7$C2'ITFnR#,4H#dk9, +ȅ3![ b@qS(RjJ4e2AURݨT5ZBRQ4u9̓IKhhitݕNWGw Ljg(gwLӋT071oUX**| J&*/Tު UUT^S}FU3S ԖUPSSg;goT?~YYLOCQ_ cx,!k u5&|v*=9C3J3WRf?qtN (~))4L1e\kXHQG6EYAJ'\'GgSSݧ M=:.kDwn^Loy}/TmG X $ <5qo</QC]@Caaᄑ.ȽJtq]zۯ6iܟ4)Y3sCQ? 0k߬~OCOg#/c/Wװwa>>r><72Y_7ȷOo_C#dz%gA[z|!?:eAAA!h쐭!ΑiP~aa~ 'W?pX15wCsDDDޛg1O9-J5*>.j<74?.fYXXIlK9.*6nl {/]py.,:@LN8A*%w% yg"/6шC\*NH*Mz쑼5y$3,幄'L Lݛ:v m2=:1qB!Mggfvˬen/kY- BTZ(*geWf͉9+̳ې7ᒶKW-X潬j9(xoʿܔĹdff-[n ڴ VE/(ۻCɾUUMfeI?m]Nmq#׹=TR+Gw- 6 U#pDy  :v{vg/jBFS[b[O>zG499?rCd&ˮ/~јѡ򗓿m|x31^VwwO| (hSЧc3- cHRMz%u0`:o_FIDATxڌkTW=3sgL31Fh~ ". (uu颖BK7 m1~J͈;s?=B" w}O`bj쑲< u4Nj%Q]9Lpaq:9xrkF=Dٍx&>"ChqљCEE߻=?pd0Nd Zz(hV`0~*t1K!&0e05q߭'hrFRFupBJxEI{ 91wxrhJse !JL!d[A{kN!.ò"pyyhrh1H CAY3`Q=[K_"!}mQ_ C 8lFu.}3 DArgQцt7xYz4P]X> 8US׷N9d瘑KDOᰏp .'yD7n5W/?8TKIk:X%*áIENDB`ugene-1.9.8/src/corelibs/U2Gui/images/group_auto.png0000644000175000017500000000136311651544332021004 0ustar ilyailyaPNG  IHDRatEXtSoftwareAdobe ImageReadyqe<IDATxڤSMOQ=әbej'DIQ.F..JZ ƺ".L(& $y? :w@9{s羧H)?wRҀIxI~>N5Ϋq(2Cr|GRwiR2/;B͚D4*UF`V AUD=d>Ȼ7U /Zam=zv4Pm*Fߗ> /+LLDx`,|`UDeg7Ҭ? vrE+#W 0iWEZDVM9IZ ȕF#ýN ]˛B/oK!OUQlZxԧ[ Ԥ"WOw gב"K{T= 6k6^}R܍1N*jA}&[:=A UQ|蜵7sn*rV_/&7x\F8hРɃX3 Kn׋B]Vl<9 Xs0Z)"jmBP#aj%جqXtnb-NDCŸlu/_X/%lvMdUwԧ #Wb6H'aOgv'9 H3Q5 B.@ $pd!s#~<<+"x M0B\t8K@zB@F&S`cbP-`'{[! eDh;VEX0fK9-0IWfH  0Q){`##xFW<+*x<$9E[-qWW.(I+6aa@.y24x6_-"bbϫp@t~,/;m%h^ uf@Wp~<5j>{-]cK'Xto(hw?G%fIq^D$.Tʳ?D*A, `6B$BB dr`)B(Ͱ*`/@4Qhp.U=pa( Aa!ڈbX#!H$ ɈQ"K5H1RT UH=r9\F;2G1Q= C7F dt1r=6Ыhڏ>C03l0.B8, c˱" VcϱwE 6wB aAHXLXNH $4 7 Q'"K&b21XH,#/{C7$C2'ITFnR#,4H#dk9, +ȅ3![ b@qS(RjJ4e2AURݨT5ZBRQ4u9̓IKhhitݕNWGw Ljg(gwLӋT071oUX**| J&*/Tު UUT^S}FU3S ԖUPSSg;goT?~YYLOCQ_ cx,!k u5&|v*=9C3J3WRf?qtN (~))4L1e\kXHQG6EYAJ'\'GgSSݧ M=:.kDwn^Loy}/TmG X $ <5qo</QC]@Caaᄑ.ȽJtq]zۯ6iܟ4)Y3sCQ? 0k߬~OCOg#/c/Wװwa>>r><72Y_7ȷOo_C#dz%gA[z|!?:eAAA!h쐭!ΑiP~aa~ 'W?pX15wCsDDDޛg1O9-J5*>.j<74?.fYXXIlK9.*6nl {/]py.,:@LN8A*%w% yg"/6шC\*NH*Mz쑼5y$3,幄'L Lݛ:v m2=:1qB!Mggfvˬen/kY- BTZ(*geWf͉9+̳ې7ᒶKW-X潬j9(xoʿܔĹdff-[n ڴ VE/(ۻCɾUUMfeI?m]Nmq#׹=TR+Gw- 6 U#pDy  :v{vg/jBFS[b[O>zG499?rCd&ˮ/~јѡ򗓿m|x31^VwwO| (hSЧc3- cHRMz%u0`:o_FIDATxb?6g\rUval3`_|aaP`bbp1փ, D+bUqQ ~ceh[A #<@pѱg\-0q j f0hxU{ :0l}E.C½{oރy= X% o_{9 ]gV|uD"67 #9-ֹxڳ8cu.^9-'.0.CОm9 y ?iC#IENDB`ugene-1.9.8/src/corelibs/U2Gui/images/msa.png0000644000175000017500000000033211651544332017373 0ustar ilyailyaPNG  IHDRatEXtSoftwareAdobe ImageReadyqe<|IDATxb?%Bc/ȁ;qF%0~k` (6@7&2̓ObLΟ/2, z#ܤ܃R*6!lNa0^0.)gIENDB`ugene-1.9.8/src/corelibs/U2Gui/images/minus.png0000644000175000017500000000052211651544332017747 0ustar ilyailyaPNG  IHDRttEXtSoftwareAdobe ImageReadyqe<IDATxR;n@}6زddDirZ* 8$#TH$WQEBYxXҚ&#};fG\b v4b4=Szg;h[-dZcooŁEaK N0yIBuo8v-ec_k$~%~'\J<۫u; -KhG+HH+>d]5^ģ&7#b5yUFH /w`*_[@IENDB`ugene-1.9.8/src/corelibs/U2Gui/images/zoom_reg.png0000644000175000017500000000150011651544333020433 0ustar ilyailyaPNG  IHDRatEXtSoftwareAdobe ImageReadyqe<IDATxڌRIhA}t;$!3qGAQqAH,z xR& (BT\ (=(&nD4dLeuK0U_G`KWG5y ½4kNu{"_!xrRK254:0|^̎|-5s1RX"Mrݟ >n 10H6.qBpq!&]e*(xYQ2$Dן+CO4K%xycS& B◚dlYHaVk@)ȶ=_jGT1mx(L6o,0#su3p}RTR7PF9 Y]GiVPDb,q%N{nxe̳m>jε@x )5SgFx Q`||Dd各?.VoU^]@SCoB* *3Ȳn2<;QӢO/h@YaV=I_Ăr\5sYgTB3s\iEbGТ>%z5rOGʣiyDh"Ruч3E ֭_d>2}qK-4g~.j -y钬< [?]k^s,8:OWLDe'-w6ibKdbV"F0 'B?EDCR#HY҂Ҝ:gjSѹM7qw?vo+CG/{99{Q `> ف7l\V,%q?hw^1LKK@ܑqx՘NgycyUØ=pŞ{ŏj0}|h|54&=>,TUMŸ%G{kkQ2?K۲5a/ A¸ k4ɾcr9'HQmalI⢳/N;a2j (*q'%95rq`6c{.l{jf ݓBnf&7ijjL,n<>eUi+%ņe9R\VJe)J)*0w]o t YX,{R%l2Zk faOԅY /Q^BTUN7*D]镓,(?3IN& PmC +Q> hU3]ϖ? 3P܇IENDB`ugene-1.9.8/src/corelibs/U2Gui/images/sw.png0000644000175000017500000000153311651544333017251 0ustar ilyailyaPNG  IHDRatEXtSoftwareAdobe ImageReadyqe<IDATxt{HSQϽ]ͦ[)6l 1AdfHPR+^ЃAh) LVkVmnswsOs~νü$Bn@@ `@ d;vb}ϐΘ6gMw\~6n:m oYkQIDATxڤSK@ iC fs?@WUW]]t8tppuPfPn\Gz^ M!<{ޑ#4OI*@@ya?(۲*VwK %C.!>uBG/Cx#2s 3*2\@D2-+%_88+tTC<'?u$\Hw6=opNub$-Uhr7ĭ)ޙ^o&p-]L+tf98PIʹU͙q0M C;iP@IENDB`ugene-1.9.8/src/corelibs/U2Gui/images/pushpin_fixed.png0000644000175000017500000000037611651544333021471 0ustar ilyailyaPNG  IHDR Vu\sRGBbKGDC pHYs  tIME  F~IDAT(Ͻ1 Q hc!/bQdBPčMlL&l"fwLq)"" 8cD3q 8T>R9}% &tY}vMuR&[d/e'8+yIENDB`ugene-1.9.8/src/corelibs/U2Gui/images/annotation_settings.png0000644000175000017500000000103111651544332022702 0ustar ilyailyaPNG  IHDRatEXtSoftwareAdobe ImageReadyqe<IDATxڤkAǿof^IbI+BۣDЂ<*x$xRz7<[[.h^ІnǬo"ݘ awg>]X_\aXF,̍UMXoJI`uqRk4*zןW`rDcDg㨴zQa<EG?@jXmд5?R YyP&eHv |slMu]A;8x|kFIUPKsUqz8A> ,]*c\8/iPv?I Z 8hndz[09.0-tXm;PF.Ialom7>=տ3` m28qc %T)AJt՛H GMIENDB`ugene-1.9.8/src/corelibs/U2Gui/images/copy_complement_translation.png0000644000175000017500000000122211651544332024425 0ustar ilyailyaPNG  IHDRatEXtSoftwareAdobe ImageReadyqe<4IDATxڤSMh@~YŃQJQ=XAC=UEEQ{A^\-XԭzPݕ^bw&d2g&f7ZY>xyd/D>|J<<:m[6! Dp#wc734YڀnTz}7Z(U7ϊl`sK$[,><5y}5ٶa^fFZ҉f5K1:m.vaHsuk:Mq'G˩B"ڲLwÅ[auЯS)v*4pՐS$AN'I9H^΢aH/ƓRï3S>,| L(X]OP+ ѕ_F,.᤾m8,oקG֥hӄGX THHT>(eqUsP)FQ{1힛X8g1hb" ODR$U}71" ySh\/LIENDB`ugene-1.9.8/src/corelibs/U2Gui/images/ro_document.png0000644000175000017500000000105711651544333021137 0ustar ilyailyaPNG  IHDRaIDATxڥ_HSQ?ww{A*OVԃ=2 !?/>s,EdE>yX$-- 9 [gPpQ{ ,5[.ٻWQ=Uf Բ7'Xp3ʎnPe*/t][[k G8ѮlA͂L+N#kAlۉNO˵>LWlb{2hs àۍT*=䭛vRf0Ʊ#-8<R+VObcbps!k%FX[:-^& .wطqIENDB`ugene-1.9.8/src/corelibs/U2Gui/images/align.png0000644000175000017500000000067211651544332017714 0ustar ilyailyaPNG  IHDRatEXtSoftwareAdobe ImageReadyqe<\IDATxb?Eછu 5,LjZ L  N(//_?0aʔ)7rj<2rP 7XEYi4!aAa,d Ä?d={0l 0گ>~.98VX, 8U(j tW| c`0@VÄ! U (!/"2---\d5ap X>ߎ;0€oiNk _IG_CP,_EE応qqqՠ^NPU ?mg $`}ݦ xIENDB`ugene-1.9.8/src/corelibs/U2Gui/images/sum.png0000644000175000017500000000044111651544333017421 0ustar ilyailyaPNG  IHDR7gAMA7tEXtSoftwareAdobe ImageReadyqe<IDAT(cπ2ѡ3GrÄ)ɘ;CAA s XPP?#15Jh4<ȃ(Ik]%[Pj*bmwwݙzsssG4 \ 'z!E%=]]Y}ԧy}23uas/9q0N pzYa=-V.X;:{{;* )xѻ폜-Kr AI5*x onMPl[Jw.PL\71rnWMAR2^[?dXvbٱu%WFQmď! >S?'X`'.! "ٻ.+@µVe9v (0r!m܇%mvP@%C=~少7ou \/e=^@nmwv5@"<)ګP>#хfWձ6Z]i)h\aAʫ %qf_ FUlB\IENDB`ugene-1.9.8/src/corelibs/U2Gui/images/notch.png0000644000175000017500000000034311651544332017730 0ustar ilyailyaPNG  IHDRaIDATxݑ D:Z(rn]uf,klɼ Λ] 53L^W؝KTTB:1]TD :@~K! nYH̯yB)jLn i l^"SZUO/F9vIENDB`ugene-1.9.8/src/corelibs/U2Gui/images/close_2.png0000644000175000017500000000030711651544332020143 0ustar ilyailyaPNG  IHDR Vu\sRGBbKGDC pHYs  tIME  $"\GIDAT(c`ę)ƆF\+## 4122a"կL3ÜM InFw?}(3@@IENDB`ugene-1.9.8/src/corelibs/U2Gui/images/copy_translation.png0000644000175000017500000000116311651544332022206 0ustar ilyailyaPNG  IHDRatEXtSoftwareAdobe ImageReadyqe<IDATxڤSMhA~Wx*RA*E z^D ,cAEѢ7/VhC=xxb jTSSzMfgfgǙYLbЁ337[Ctfy?0BR ݝːy^"΋c7>wh HW}ji2ϊ<`Km@©Fܞ.tn[WFtBCvkZ&k 1Tf45np\&]nYt\՛4`2FdTzR cdj$IyH]ʢ$B1{I ]|CG2*^a5̡xT¸TԀ0k 1P7#6R_K>,`h:Zwv\r1ӆd>|IF?.F(:ܘHQhBPgVaJz# `qNC,E8 _?p %'fZfO/F@@XЙ[_:]8m缔ܓā[q"s5fٸL+@s< 1L"ܾݶa Pp ||DH4l~1/}- 7bm__kߤݔxNr@OAHd$"&UcEb"h1XF{{+|T?[tg)$<7oٲyM}+$ g$b(.F@@#fQX__Yio4`*oc[h?ѸmB-K14_pA-"3mN2{P6LhiNG{p\&~F+Ftm+VS"u6xeJ:qq+B !ydda"]Bb`-yW=ԈH`Zkrd>jjL6& (*bZV<@ J VD#IWry/svxCJj+ImvIq*3عV\Ma"6Μ::blN N$MYI/t&*t/cuFR5Wfu/(|UW]/X0%Wa*,w-_XTT:2GDvJي^9uؘ5NYKP˜ܼ%KMAC@G[.<}'^A3J]aSI*dky.ĘOj)%&ǖ-[v)ӱR.lл!M9DQ@E&Qz|s9T;;cN;ğ+,y}1cᘀ@~zW\~ɽjx!{ ˢ,W2D>3 ؃@?[o ně ;<hpKʋ &JGoVef'|>O~Hj;vd3;1z(Yy7Z\\82pKiNe|׵uƉcɲD!(v_r|̇ H"J5Ylq_߆N$=cXndHXM%}"O7ѥkQ[i/ܾ=0,WV ,-_ekl33yՙi ;GuwCXrap/޼視SӲ"(ߡJ`4g M?(ͫ r-PWTa4E'IAW.Ӕ`nmVݾ E PiL&#@3TMd=&:)+7f͜1eȓ5r'FYrSb)ȂXѣJލQ*SKR)qag%g b0x.d-st2E&B M3F*;VH Z#WAaB+5wWi`UWG_|̕<՘*e%5g­JnDZtw_-PR7Hd1x8gyi <|qCOL(:@<;tyB^Vׯ1F\nw&x|ҁA6Ε+ 4>#2&vlvossM\1qg "yQ @':A@I3x`努e+&X~_)=[aD?-p%,Rz%Fd5 kkmQd^b'tIƭ[w-Yt/_<'hiq6OcOMeDO9L|S!{*Q(c\)}Cye5pd1Au)>j-V;Tr <"@)JU2f:qfănɝfb+Wm77O\%Ii]:%uK~1FuvZڲ"ꚥvK`IkwF˗.O&ɢ3'4cي.g]|eYLd {mi"+!!CSadoHR0N{poa?Pѻb1ST {dOs8G]Cd4.IIG02K*G?2@6m;qk'C<2J;"fT*jKj 7@-}7!l#yu kV܂|WO?Dk +PjkbUJL Fv2!]iZnێ=A sqd+F|1dr9Mx"AҧAݷSe0XN@l)Pt8xhW|дk{ QBxa2_K#cgH@~æJҽjqMO *w{XN{͚ry(qرB2nĴkf-c? DPs<,/ۙQ\ͯmݾk=!pAx \ʏ~yϽa :Z &'y!;_˛fm̼a$%^@xUuX;y25YvFh"NVX߰Oœ2<2C:dF1 nImiJ}mV7xF'FI塻JP08\.Qɔ^L '"{KL"-ʀTzvw +++LN/趤_R)'y.LdU 3 N;e1eqv#EM۱_[U_c%ȬF\Ny_~.g`R~ŭ;T8S^^[J ,3kHhn19sUv:T/Mc>_&rq,?:gbqz8c`ug.Y֭opnܫ{ ٯN|;'=>_0Gda1gN*U,Zr,\TVknyYN mjszba STBݎHƛG?>2LnٵqˡM=GjsǼ% G`p͏;LJB}+VtXNmמGD# R@xZ$ Io,F؈/N$`!'Eãu!ފB1@6B(%!&{g|Uv۟Rc./?{jRG!MT\GOxj ׫skqMn$!V2IQd;Գ1Tt&o;OLCh?|n%d"D1;>wzS"(.vq.CP} oIH*yy.}y(=YNS|nH`cFE!uC_z=p&H1oT9 S'>@$.\U';O[ 9TX`T:7bfqu_c߾m k۷Tg[ :z &beUMG1y׮9T_pnǓ_,r%)Z|[#GmsΝQE \T&Rͷa,%䕫V;ݷ;LIƠ8V*+IsL ᛌnnYn!H)JN##\Vr*צdrwd+7GgcL 6uC uK&|^<+b,oUZn 52j1i9 Tdc85.ybR&PSS-!KqŹ|XA !qO% 6K. d+ xيzЕ "N0cxumb6@;~IY.pجnuӚrql5G+*H6q)t&ЈJc=q b0dMfr`RR:pYt8LvZKnS9P"lp'rwC'vGQ9--w> R,odgnڲ#/ӑ0atgL%5 _ӯJJ_,3>v.g(X-*.e#5QYk:A_o##h,.-gjigX1fZH aɍx*'~C/-z\<12-fv[A1hzbcwWǸSK%11AoCQbn5q3Q55Khm1'ČV9 }TJQ0lqU|pStҸC3:b]_7wrf T%gn-,4)p_&p<0%sAVÈ<8݊f6S)|ņZhH獆 R1{o P32I+O,G["&  IO?% x2eXq['6Ly< k$BWS^jqPmb_0.zD~i'8`06ݮGg.*;W+U3{6cYsn.fEROrdE!O4Hlj 9X wU R gd7KM" %)Wl6ٙ3oJ`Hv9Y.V52%ޖlXXC(h,Fgz2fb⒲Ve+XLpF+ȋ؟Nٜ>5))NKM ؓqW$TY'!Jd({0>[XXѐ qĔs%Z[6m.*d -a ^$e5Yp;y\/Q ȟ_ۄW4\ }c~{>杁UR[wz8;.Ə¿/8n#b?'Ujj/l i^-%-Dlu**cpAOxIV0F1y(3ӽv݆Xý\Gٟ׮OSLL)>O"*rlvø=883*aӶJGщtRķtfcj=iԡYG kD0cZs߆TUF/,:3UZŬDmp$n%xdeHd}Ύ?|*R;C;CKWd+6JR'\TXxY#"9W05.?ԉI6gldU$;$( \AAHt\U9d;js+<߼̖[tڢ WR :-JR Noxi+v]Bm*u՞R$QJRE55xV$&)hL_XLpOegcP\0կYݢwO^#H ='LW`"gfp-J)>p Mr9%*Wydx*279jONB-?;Eu};DPvnƮLLm&,"U??>p30T(U@q7Z<y $U).*DC̋mSoMh`O>d&]RLv#Z ˒@=~s\'THD']-sT20Kxu8\^qcGUzF1'gg^Eť-+Ufa2y{ 281|3Sơhçhݺݩ%/Cj=?G ? /k~?TЭ^>;]Ҧk^+*J/ l;5͵kߘ̉vVbف1MAڎcN{ Y|ZG<:,f3$?x=ͦP4^LJM?[ :+hβ4уERS >LZ>ԗB-я?{itM1Ϗ3X&4sVȰLy#-~>oǘTD"GqIbG*Bu,r\{t2n >1fGa.f Ѻ>p_|wizVϴ4FF .*Ktoill6[Wg!`VCv5qMH?ҎML ?ߺ}u7]3F΂$8¿w65;uSᚍشC'`r* AcRh¥s{z^)P;7ZDud-*o8f-@DU˰0iV8ޜ-XnϽ[cCp:达jKSJCn+XoO5rJԌJo޸;Hz1^OEϞ[./+DafGv:x]%LĕG7Bۄ~5Kedd22q(bᱸi9zɃ^ilVLnw-e}sïX:'7)~BcLd f<ϐI1Z3Txz~cvL7K" Y])1 Jz::m(JE#Ɵ=n^qI vߠ/!Af:M> 9#2O˖/JgU润>alWI,CfCuu GBU]]/4m9t鉭$ pkbLgd`)H q'H`YnƏIYxEzaӱJ1vA DF4L&S Ll3 ʦo抗-E84+V5-TN,ì2?I^~'}lwn(yMԑ߿{lUŢE!f EBԕ>9|5gr{VV\թ_7ݘk*G}Gz j'ph]hC{Ӌ a<܍R?KjXKшWnZAT2#[zB=<K&afeG?=ϾC'{N~8,f\k$1njiYT-<9yvr_uDYX Q=^Z[>םN3&.6  =cMyÍNTL?A9aomߖ{=!eS+Vԧgm{`G9Hiqc>) SXQ"*.?pp*D ۠K6 -d}ّgynܴ}hhݺ0Bfh_D ) c>m;[V/j^n~(BNfn:# dutTUׇ9`6p`F{\˗ΏLAS=1!N_]#ܱAm~/lmFf͝b4Gp/T@̩ g^b:ki$2f4:-c #jqeu zsş.".F@@_TfueUᙊn(sB0Lemmxxa rQ&^9w^gs%?@@@X _a:nf6r4Sbᡁ1S{KqnqeyE0>9$O# ,и_\nm-Yy\Nq7ny/IuO 7OCrEabt F4Aa(G+Qg ]ɾ m7xƭC]xiXvڃǽ=ֱs E9˖-cH|BcNBPD-UUWB7pɳHڸ[a@$ * Ċʚ\bn:Azޕ pwz䂥˖_/]HjY fIUæ텅ō瀲RX"+T 'OueD"Z\zM 1_NףS,57͛oYU/fs3xq{׮ Qv{h^,/_Ąwc8Wtu܌r]N x-KUIM*[_:uKsk?iNN^(26mI89~|-**숗xxxH0]NGwvD9r.]ܹs'kn7x釯i+MM'<'?؈VZ;hD_3K\| U([ɚ}\>~vf/?O~q1#jkjFٯy]1SBȜfRG6g;176N;婌LuCf+I?|逸(/̈j:+"FY.WHHP|~m~^t2f$׮nAӧ;f£.-+}=q1BP* d!fsi 'yj,Y}Q[PP-`;w2fzg-3b1#|Ç_۹kw̠Wճ_/5^ڲe;󹣳M#.F@@XȨ6@\-w>]3eed2~f7Ma!xdX|Și:;ԚO?p{A\UqLz}׭K# ,@)X 3x nnhZZr,Ռ^oz~h`"$~zbKqsIq1/Ķ2F_A6fFËT9q1B nw;}47 {ߛx8}|R]3\N_Gs%-bb3l1a4ի^())Qq\fL,f[)璘/4BԜvV"%b VeܺvM}dЃx)ofnq1‚EII͛|$YT_KhM<<;bܜln翴(.F@@X(/sm$A \b:$)# ${ET O~"*@@@@q< 2w/k;kIENDB`ugene-1.9.8/src/corelibs/U2Gui/images/add_new_document.png0000644000175000017500000003211211651544332022113 0ustar ilyailyaPNG  IHDRSi]1]tEXtSoftwareAdobe ImageReadyqe<3IDATx]`K!J X(Sԧ ( +byH) -rgwvv. 9s S~7#4% OKp|b+=*Z($ޭ2_*~W/M;U;D&Ukv<M2_a{nq* #el`VRO +d@ \AY&Fa,6S@ Ezf(ZX1Sv@f 6S3]}@7n f"1!|A #[qe89Y8|YGd$dP0# #&:0dPՏ*vBig.!h'l#bumV^* 1U IqT4hn)1l@L@ADHa$hGcuZtj܆bO/2(ke*ي5nzv@cCթ"":3G~`!;|02Q_Fbuo?J؎g:dH?1D$b)X4jtxk~WKRA4 |u  Gb'G gk~|p(~/YNWms^OSIê7JI'=g52iq6!`>O#UIt2*Fx_wIkScuR'P\h^z)0Tc*vЦ-1UL ,R46 1:1| qURS iXYdD`Χ1q;])^ tKbuV.㪘bA!7ڗ6yQk'042Q2,g*f/I'K'W4*4ƉYUT`5C'WUct>p9|nAEj+Nwm&#=N<&+MO++^!:ӈ[8cva͵? UVRk*фO.aA Ģi~vSbFF"UT1u!Ƕ冿ggk}\0uzL…Gqnϳ銕~Oz%ܩ7_c^֟Z0T+M\ y-7F)py@,<v4!X]GmNi U<ms:/wUk+N!ycZ?娮rUlqCCbXiG A*/e;VD:)KGԩ^ U;ڵ╃]W t%͒J;@Ur>!«d!?Npae, 5)b1*#r(FY,#!4r1p0O%;Qqdll>EaǞ{>R_%uC&z@G"Mq((*]Ԟ.g(ڑB2J !0G"#;3}g=å{N;u_UrcWIBsxt>Q_Pv("W/s-2VbqDPʁ ǖUƣ/cՄUypQF ΌY|9 DNYRp @Cs∪x0Q>XS8Oo[z_}D#*%:͉0;}+=w V͏mw c8v+J#tK_‚mڐ=қ-q8%uȒ*AY}2X׭@m%Yd_b$N9_R2}R:de6o%lN$+k֮]*O#L,^.$IU[2y󖃡0͹8_B9`Z"掠OҮ " #Ÿ8f']CS,).Y6icC@7LNֶea֭Ǣ GPEn]YT{s h/H5i *7P5I){5`*f@{e.U#u+%ZLEMs$Ldx,4uSzPK_dq8 ޽W_=t޼r5oƿarb5v+.doټ",iN+/N=dvC/[CfϾ57_N̙3eꖸ$)SMLz=#o>hy+ 18{zᝂщ-G>}cOXYRn~ 8nܸ鹉)8cn3d~դʾq&F吗5:h}vpg١aψxV4*<0:udx*~yLbst8+?]ӫI7\A^Zj]'@kC\O?E`mm|xrg ;nec_z s;뿳_C-oA68zK4Ukf$bLB=E4uq#B}H~OT>d5'kZ0Oe  QOv|>uyW$;sE_؛CLxmWx#wl7g o/UaFm縗; 3s))'EYvpcyȐsrz-7{#oifONn_Khy?Fѯr dg3^b{7_uh!?@U[E")**dٗC cޤj,C =cfs9|vžz-f5r+OAPs 'OأO>c%B{|͚[[24->nMgǎY5_|/G˺bn?J+-K@nڹa>7vj_,=Gu!'$ZK]gX^u1ՙ_7LkS3 $ZUUy`ef>l-C6lfcW،]3:3;EAwh#;É_䳚nw+a|RoO~iS j&;Cd!aZH@zx9'~s9#&Ox1^7;| Rbφ_̞U5 VsC:PwCvy^'9K,:l !ƿ[%/$e7T9C%wRm\$|e|RyҌjGe-jN+]KKԿGW&Z-XjGn 7~,s;;I&hcuovM-gjꇠHs#}&hS+~eQDT5ڣ. 3PDPȏ*YZbLm8hvMwr9ĄJXa;Y`At5?w_,YV;儀|.8xhMɝ:ҷ5% <ߛ35˰,}0hJγX K\~WoU=|Hj۽{7=رI[Fy]Y~F4k͒8 sU+a.#Ç^NT6@ 3ǐJU. I9}_~%8=-j UO1՞@Lz>ØsX IrDշWϻﺃD? n A(CU^A%$+dC~oҧO,Oώ'HKԳ|<}&GЈ44z{?%+zgGp^*,YsrBHOqW(iQ*9oד[q?"U<ݫ_sKjo@'lKǟ{)>.Dۚ]$H@n䫞|s$, pYrϕC S7-iJ!M6I_`H:+w)[pü#CM|D> Y=-:=tuv9!R/g\>h=oϋmC0Ç 3Ճ\ qEȁ|'&nұn*!XZ_Vg,>{i_5y ~! ʨ@3|u&DfEތϷWcsE͵o ovf9?i)G߭UCD>y=챧nʲIXHRq|1YsWİnfƝbI,&xƾE݀:%H~/؁<H)J` 5ѶyqsxN`⯋nxggz,m-[Ιa 1RSgwUDz-ey>B'wZgu9?gZOB_̞cg{0"xI1<.y|7nbI(<'K4e^Wï @ 3qZv i/dGΎm #^T/|)<:g2-m5GӦtg[JOrg/\|' 驭έJbBViW}V7gaeB>8$c#^qBDFl;N(aY/a 7U_}6m'3xt6T\Y!_`weoWn2X,V[Uo0S˄## l^ҽ2y'Y,旬)bMCpn0Zm9{gir9c g%ƒfܥ(c{sn|[UYt_Uzʵ#y.\!o ojy"o{/;^5k4++w{?7AhM.rapUTTX&tލ&H:=G.]Y ]2ށ8r^:}$ۡMAϹ=M@ F Wv /=6ܴODj|Ĭ]Tс"4pCi8kioOi-4\p&3D."e;RӾ}ON*ۏ%cTł`2Vi>%NEe ajc'(&!T+ŐHTSU S]jI։I¹\QݫS)¾``?ijckc3Zt}~k+;r;͖NUIYtvveY{'lZ6=s[_XYYf z/NM`$&C>d;A&K]8c/@̷T*vi| :VLeOIs^·LYL7PŴT8"Z*f0ej9B-Ieti81mƮq׀qm%ks%M)Z#ǺEh]ַ,-$nzyfIԱ_0dUih`0h?/\"TD/< ~Z_IN7,~bY<BѰ޽%9S͏ [MFrw.,@Weؓe0$ |ƬvU#ph'fqꕇ8#3{zjnS!SN9?zLbwd7x60vVtt>Ԑ4m#KA's {"R8v#.ܩ#oB|x`IҚ@A@1cx0F_rl7AE)e DewAi: qZL6@y--u%IIQ2w~dB~)&NoεSIw1B2..)b9R Zqr>;k k6w2i:&p;nE@Z̮uv@:Uj.olKrV eJNoN.ފ8 ۍQb6ެu1[q95%'tk^B`t )8F5b󶵾a)ӦOdT^׿_f€0׆]?!w;]r5QO}z^[)Sb֔lkdzMƎlSj?ӽi˯ēW6+cKqis[N|frvӭRW,ّ@˄p,T[bumICV&P)8d%|r20.1/oJwqo|G> 7=Ƿq^VV'L$9Y_-h_]Y;*PE+N[[u[o'"*2򁖅%U<Ι3' +(*PS['F}Lǀ1 Utk? 2$&!R+ǧR /\T-8SO>y $p5 Cd9XrMיVzmǾ=}?p,[y2,1rKf_wwߖWY7 Q$O{kEEE2pJ7~}Y;-,ۏW("7Uh~ў1>e(x'T+sv h/ u&ugbs"e`Od)vfyw9_ǭO?ΝǦTg/g[aӖ}]<,E={ʍ% ;,b5xYVQmtyeĀVʰٜ_*ԛUt+~E}][xe"rx7e*I3ӧQv1Vǟ"mLvD6NJHZtYI6#1IǟyWi؟Oǻ^:}Dm<*]zH,r]CNeM]}ʗ sƩ/ol??,kb+'B`)JG1n뺶l"3ddIҖũeL8%)Ն[qA;#a`S^NqaK;ɥPİ~[~CXB*<ūdEwe7Yi2r I8~ܳ-Ȭ)3!{ƾcf5̏%seZB]!H-gŸm/;ќ]=j.f@%[ @Jo[ypq¯~,XO9uÀ.e^~)>o<זdE+O14u H~Rʉ|̏Z93aUcؼnNn~i˷̫tژS$}-d2j1(XhE 8knʴ(EҧJB2Q3:">K ͽa1CBDWV#'t>?\mO)ǷMI2LBxYZfb3&Dv3-^"6+L%TrT x1rּ{lBIQ-<'}$Xa㛺_vނ9q A,n/rcbR(7MFږFI&̩Nc$IWԗ/_tT_M)2bUne^·o[#+%A$.)х.9co~k!Yɔr!ïkNyEW eNZJ4FGhV?̋ woc I'UHt~Z3&,.ʎ3>4qIp3{[tERYQ92&n{J9qUڶIu&~-"YIF!E;5鵍m? IyHHsy^ ukIG#fvGBЂ[IQӶFթ ũ9ܫmF̥0es-;[ _|JqPp;0?+Kgq2Y<RWyvHNsC0G$ ܮ]}ˊ/.+ԏl/In[ؿGu.o۸qӲnع]}cFmn ٗCF’={,, lko;ekӫg~`0ܴiv+-Be{KKÁΪCP&Oj"T/w<-)["|œU9ZrqNsYt U\BC<k֬%Qz iTڥۙ]xHW|0TzC|W[ʛ| _:lrC}Ǿ]j$KkdSansǓ$CVoDqUW_?C2fڽ[=J$SmN$|D mشGޗT m۫о x>}O_%5kMTuMGtqxn6$nY߽,,TW${_Uڵfg o?uldrnqfAKCa|U.S'HtȂ.1 ~ά|R ξTPu:uZYwS0߯}f//)M^tLM#ԠklB[O}p9[1aҌ'vMyGb}32Ax҈J6)s5~9eYOyPNIuJK˨@IǚQS;cqu%g>3?9Haaj0b!)N:soY` wdl2"s;n !]KcN<4ڗ93ݾ( BR=Ty,# ]Ft[e ue Ƕm iWSu '0smumY7سgO;ucיM[9t>8ُ!STQŨE`EUx@m<2CqBAAky6U1 j髛5>m*eSHٍC>삐J*F!Hم!`(bdQ0ܾ7lWO\'d1tÊ3*f})ϯMQTS`-ˍqrBTE~'뚊Y;ٙt>h,}O[MHJ"Jb<*\իRS>h ӁF~,{zu,,Ƒ@އz쳺K)P>J{Ϡ}l9< &$bp[7on6>uDv<*-j7-aIq#ITI/}<|er±ͥwM=]'mNd6MdHD!.[bc9q∆Y-O1fNF]i '۸\M+V+J[KPϝ`ѐ+ ZRCC%?)*3^(a`y/YODWO䓤.]N?}d4(=Ųޒ+.=9)I"jό.F?}OKKs \t3mQ鸊Q<~g.}z#PM¨:(Ho|ȐА*8sr-*X:u/ڞђD7ݱ!5\4uC@|lt$r=Er?]AZ>J~&$DuH3k  uBdZ·,NJ|vl]}NR:ۡߥ!Uoޤ % %XU#!'[/}tŤ}o^хER\]Ì.nU;- DPɏ 3O*qgw۷oV 빔?A߱~0Ɋ>:LR܍B[(5Kʒn jsq*. Cmʊ<(Fd='3$eSEC2-i}i=wѪ̜m$?PR 'RhL4AC"%'4/D3q@Qx1NNc{,s jVLVS@eVX| '*HB] Ol|U(Og5g 'Y&AW8s(*K$E|({RRcGoN>f4 04Y/%۠V ~* 4g !폨tP:I;|lո;|`L\/ Ul섉o`kߝ]|Iůc ?KV\ݰys,>}lnψ# 3).)C}UA]֟f[8{`h+.E~|W/ U-xֻS?~)~)O>c a߶ ?ӚW9BK3LvpdR_d߈DhOI!@DCML*V&vfE 7fG*HXr 'P)dҴAe80< Is+zHwCW0 DQ)b+EF!jP#i E~ҀB|X=:prUeQUp8TS='G~Q{g]] a f،Pۧ7\Qn>pUTϡ&PcT&?|u4#dGb4h?{riq_̫{R>S b>A^',1 e>y/a x/JsQs8(Q>A@ 0@ÔIENDB`ugene-1.9.8/src/corelibs/U2Gui/images/page_refresh.png0000644000175000017500000000153211651544332021250 0ustar ilyailyaPNG  IHDRagAMA7tEXtSoftwareAdobe ImageReadyqe<IDATmheu?9|b*VI+R$he!A!AeSB?D-!}r$sJZf6u;<}]~ǽoJu۝X)Au|;3SyrѝuN  cL^UYR>^.>i|ĉ)DSB0Yx3S<{Zp"̒|9D@(Jy+gmsK#@N'%¿U,̘N&%x3 Ѹ1\0 ia5Y~ /0`6︯~ /mGMQT*n/\ifo" `Y &%KMWCdJg0 03\bN-gN{)nMW GX𪆙aXw3Pポl[+9'9ȹOW|TAS_q:v\O `/ #!M |4Yxi-۷ȟ!DbU; {K6-X:E"W+_!T-{! ,BW׵݋7dپִhfmwܙ+"h!E}ȓ``&19ky&w%ńevqIENDB`ugene-1.9.8/src/corelibs/U2Gui/images/show_compl.png0000644000175000017500000000573611651544333021003 0ustar ilyailyaPNG  IHDRa pHYs   OiCCPPhotoshop ICC profilexڝSgTS=BKKoR RB&*! J!QEEȠQ, !{kּ> H3Q5 B.@ $pd!s#~<<+"x M0B\t8K@zB@F&S`cbP-`'{[! eDh;VEX0fK9-0IWfH  0Q){`##xFW<+*x<$9E[-qWW.(I+6aa@.y24x6_-"bbϫp@t~,/;m%h^ uf@Wp~<5j>{-]cK'Xto(hw?G%fIq^D$.Tʳ?D*A, `6B$BB dr`)B(Ͱ*`/@4Qhp.U=pa( Aa!ڈbX#!H$ ɈQ"K5H1RT UH=r9\F;2G1Q= C7F dt1r=6Ыhڏ>C03l0.B8, c˱" VcϱwE 6wB aAHXLXNH $4 7 Q'"K&b21XH,#/{C7$C2'ITFnR#,4H#dk9, +ȅ3![ b@qS(RjJ4e2AURݨT5ZBRQ4u9̓IKhhitݕNWGw Ljg(gwLӋT071oUX**| J&*/Tު UUT^S}FU3S ԖUPSSg;goT?~YYLOCQ_ cx,!k u5&|v*=9C3J3WRf?qtN (~))4L1e\kXHQG6EYAJ'\'GgSSݧ M=:.kDwn^Loy}/TmG X $ <5qo</QC]@Caaᄑ.ȽJtq]zۯ6iܟ4)Y3sCQ? 0k߬~OCOg#/c/Wװwa>>r><72Y_7ȷOo_C#dz%gA[z|!?:eAAA!h쐭!ΑiP~aa~ 'W?pX15wCsDDDޛg1O9-J5*>.j<74?.fYXXIlK9.*6nl {/]py.,:@LN8A*%w% yg"/6шC\*NH*Mz쑼5y$3,幄'L Lݛ:v m2=:1qB!Mggfvˬen/kY- BTZ(*geWf͉9+̳ې7ᒶKW-X潬j9(xoʿܔĹdff-[n ڴ VE/(ۻCɾUUMfeI?m]Nmq#׹=TR+Gw- 6 U#pDy  :v{vg/jBFS[b[O>zG499?rCd&ˮ/~јѡ򗓿m|x31^VwwO| (hSЧc3- cHRMz%u0`:o_F IDATxS1j1 d;Cܤ3{FyE. ;.w׸p)&sEâfw%!kWD+q< @ɑ5ϻ@z^oh1 "IAĺF5GY־;]l{ԁ;]pZje'{ HfuE2?etN[L b<6K_#eźXLȒOCۅ$ڎcvl5vHi vA$now}qqIENDB`ugene-1.9.8/src/corelibs/U2Gui/images/tree.png0000644000175000017500000000131511651544333017555 0ustar ilyailyaPNG  IHDRatEXtSoftwareAdobe ImageReadyqe<oIDATxڤkAǿofw&?VZ+U,?՛g-_ vegXɬr+د##5D=<艉"[bFpi=] &ad}~rv!CG ۧ фHGB-Q5; Ud+<.tQѵ` 8/ݻ[&Cap>QjtL{8fPNe&Fͯ3h.eópYPe<>/a.Tq\ڛ +S/ؤF Ҧ LqIޮ#8ܳs@WkeY,K` P=8IENDB`ugene-1.9.8/src/corelibs/U2Gui/images/zoom_sel.png0000644000175000017500000000153011651544333020444 0ustar ilyailyaPNG  IHDR;mGtEXtSoftwareAdobe ImageReadyqe<IDATxڔR]HQfκj[JnYZC V>HFEDEQOABP> E=d?DQ$DTTZld*뺶43ssT|s=gowiUI<9ͫ4iZHs6m2"BZB i B*%qj w0ޤ&=1u]!06.`} S|ڰ:r]&c; ?ύxH*``8}C)܇}6 cgxhHjmS&gc$bg IL$Q6Ó>=8> 2|h{q# qtEV{aS/>9;KT9 47^qm;q|}~״kòa 78sx^!GAdžfTn{@?5+/z;57gz]Ci ٻK&lW| 3 X vRe׊WD|V׌0z yzH>/EAl+T]Gcv£gmJ7(zH~^_{DrlA=2KJBe o@ZSاb}=Ds< ~,BQ?T[LQF7$|~8FG]hSaxP+L ,}Et#5\u>?Ve%ۿ2>@>a{fmޓU[Yon!4!X8V8|l~mO7y*|?IENDB`ugene-1.9.8/src/corelibs/U2Gui/images/error_notification.png0000644000175000017500000000160711651544332022520 0ustar ilyailyaPNG  IHDR/\sRGBbKGD pHYs  IDAT8}ke;3nͦ MꏭBJ(޴x Y=Mo),BSbF68pq,QMs6XohʉO__02=eu?^a9_."‚odVlbן?Gqyw/__%6-fPid/ }N8 py:<72aIE*r_}yk3M(nL?jkW l2ȟ(_,b_t}  n ߟ}^t{w?~=׀UwW)С}Bטil<Xg 6o b1ecKBA lIENDB`ugene-1.9.8/src/corelibs/U2Gui/images/color_wheel.png0000644000175000017500000000157411651544332021126 0ustar ilyailyaPNG  IHDRagAMA7tEXtSoftwareAdobe ImageReadyqe<IDAT8UMheoٝov+/4 ` PE^O) x"DЋz(XEi)H 5g&ٝ8-=g69! :}gV{L@1;_ο0|q$.6C-ş+eIQx״gcsGm"JDZ#Ģ\G-DE+,(#"Wp!G 6!!6.2z.io/e42iB$B"4`z0rxѪ^5il>6bE`t~w]Wmrwf34H&\_3fu!|Dp@Tܞ4PS#*PB #Љmw߸:$:F˫ 3+vG-$*s}z;rs"QWH.-Lmf(*,5'A8+J^$֣IT\ G GGDv%H/JjIBp ɳ}NiOFpCz`KT"ԇ),F/K2h\~ ^pgoPr 6g%bkQTP< ɝ2/DX?3@)%iYRhU2UC T:.',q{_` XQz"j u"g[1:׶Bx<:d< YDlf?6eu_$3(,ߐlG9HƷFlNҊaU….\V- TMG(R\)&\ky $XlT[m<.Vnگ7]?]y40bf [Z[$0A`]* U%zyv)^Q#Ē#W+I3hrIENDB`ugene-1.9.8/src/corelibs/U2Gui/images/remote_machine_ping_no.png0000644000175000017500000000072611651544333023313 0ustar ilyailyaPNG  IHDRatEXtSoftwareAdobe ImageReadyqe<xIDATxڤSn@(!7P HD:u cʀ(hhh@goX68 7D {y >%wa%fph@۰8S=$\q{tA k5[4/1x{Q\ܱUH1M aĞ5n*K 5nYi4j2akQðn8E\c+φu|=XG5_AJbY̑rW(!K%`djܔLD> 4f^q:gw"L8S=jpnd7pĭK^ IENDB`ugene-1.9.8/src/corelibs/U2Gui/images/chart_bar.png0000644000175000017500000000103511651544332020541 0ustar ilyailyaPNG  IHDRagAMA7tEXtSoftwareAdobe ImageReadyqe<IDAT8˥jVQF׉'j$`BWbv vv>`SAwRnqDH$)ff*.SYW+2QD=O><.M.ndG %cQl]'B /+fR9허 jp?v !!x$e߿ܽqS%ov@tHs0@ IbQ_Kr<-SGհncvarLMْ[O"KwN6*fcn 5aڲ3f3rt-0WN bB_vƚN2P+J@\hԕ6 cN'?p^XĊE]Ylna+҄JsJ,x @ *nIxd$e=OIENDB`ugene-1.9.8/src/corelibs/U2Gui/images/info_notification.png0000644000175000017500000000150411651544332022316 0ustar ilyailyaPNG  IHDR/\sRGBbKGD pHYs  IDAT8}Ohg3ffm6B5]%%R"zP(䮅֛HP<Kr,PRxQZTLMٝٙo>w~<;S &--"@\zC=3)Dj%Vy}듥.,jbn/Ocۜ*>wX/.U|_'[39씔j+r&N>g,iNMwAx_!.4\dUzfeW<J z{śtf|Z mj(exe0rجV , <ۅ 9E\$ 3vFB x9Eȣz&u! $Bhj#O!Bt&=w; gQJk$I-dyjI(I-$W$JkFy9ެ\3B ?|s V=  %raX vx徾͓?N?`$c،bt*&O[U*埳/>W3"i^c@l gIo84~F,0Z$e{Vq M o@;߾3|˗/ Dyڋo#t0V?kޖ 9 yY&ib`xpQPd΁@W|p*=# ֦ 'z4ƍcUAgo2,_h} pfOaHcw+MK^bp֖ci޵ 0+g,y "T\j UcYyFt)>ҁ/X]n1 f06@ eX2ó>FTEar)10!; 33ßo,PC N  ~a Àln>?0˳20b` ^ `@(+`r(^%G@B׌O ].͸ `98b4,IENDB`ugene-1.9.8/src/corelibs/U2Gui/images/sync_scales.png0000644000175000017500000000054711651544333021132 0ustar ilyailyaPNG  IHDRatEXtSoftwareAdobe ImageReadyqe< IDATxڄSQ 0 MNAcyEvo㇈~kMf"s@h׾&/rcs$ps ³$PA9`Nй+\FIvMkDů/ey'4k,$29xB ~2|-CYѸyQ {*2 b\=߬$h3[4V " 4 #\ `wr 'W u%`xD2rTD+o"#,*zIENDB`ugene-1.9.8/src/corelibs/U2Gui/images/group_green_active.png0000644000175000017500000000147711651544332022475 0ustar ilyailyaPNG  IHDRaIDATx}IhaISӨѦZcŢ *QA\"ԊIxxł-6mp)65]4I3If7.y{3=wǪ+Rf=O.f];N!_19 K*7Ȋopi(t#W-=M_O*.No͌l (rTJ/ B ǵPeHEAM#o}'AĒŵu\i]CU9B5U<⚑65d3E nvt~'q ZWk,_Q{6p4Z "1dp:y/X!|.ȼ$b"Vߙ+`s6c]&HCT<"Ly/y ^pѦйek-&lG[1p^Ad,b,>3u8H9eo۲M~5R?4$42~|@ p]$3C&R<愍\uÖxYX.gYoTH&?püLO9CO*B+IU)0MyFtF>evc@o:Mdg)|ϻ@D+עljClwg~Da?/Jy;^4\Uk#Q7t1gµ@jmN7&>5.4'ߋ2yNfoF2aӝhcq6IENDB`ugene-1.9.8/src/corelibs/U2Gui/images/remote_machine_monitor.png0000644000175000017500000000143011651544333023342 0ustar ilyailyaPNG  IHDRagAMA7IDATxOHqƟ{5ۆs@%$H,SEA/<_|1556B!W<L&)Ϸ}zzzzMMMjPB,fuuuIH.C&NG"`WW[4XZ{M^| Rq=|x@ 8633 /e`׺$B8+ElbylGG! دT 2f`:ICEm MۇL &$VEy06661??Y,d2T*6~<}>"Mqlq,B:NY`@@UΞ&7nb U~WC~r)sssj =0@\6[xy^8U;O;QGJR-X|OpixH(%,Hs$JHE_xxK zm)RA3ʮRFZƃ7PO/B%EI_e!|$HLvx|nJ`rr$A~-vP3Eծ^ J^ qP{*ئ^S2[  L@gggFq{*,$35$(oUlUt]%K70>>FӭL&_(YA000,PX__($ q"R5Cϟyg2H$nd~)Jp;;;MLL1v;8`Zz z' шQ6f__VY=nddx؁Ҹ%l:::Xvnn жN X"8:!A9IHgK^T CR)[Sÿ"'kvcxgzȬ[IENDB`ugene-1.9.8/src/corelibs/U2Gui/images/do_complement.png0000644000175000017500000000121511651544332021441 0ustar ilyailyaPNG  IHDRatEXtSoftwareAdobe ImageReadyqe</IDATxڤSKhQ=o(MU4M[KBp!.\Y;]U JqhۮO5(b@uIV4Z'y_$+XǼy9{0c ֳ,skޑ \+,j-y+\Rp¹;ó[`@3^J@:(T/!y!+h8 S!, ~lnξpT9?4Ђ'&%.H6H667܂f%f6Qxl]TUby?~>~\xp-z|~YYe_Ƴ+#aFEP~TdWs5!<'xQ!T,9t<im>E82 Oy۽iVEjP؎)7D fNz5azy\gʭ\%ᾘ8Anj2䛑<^az嵌k'3od^Q'X{Mg1.ۚ%F5=',qpkEDR%HOIENDB`ugene-1.9.8/src/corelibs/U2Gui/images/bookmark_edit.png0000644000175000017500000000156711651544332021440 0ustar ilyailyaPNG  IHDRatEXtSoftwareAdobe ImageReadyqe<IDATxdiHTQ7.3:0Bلiմ@ eZ C %!J mDQZ-Pؗh i2 t1Rqt}oZ4Dž{?GE!( ,JC!Y W 2c(C~$IvN7'}HY`h\"emS!PP+ËI}cc.)VA+*R$ "ȝՍ.zТ\H)THACsKE{UE4gu2_^ /9k!`!|`QD1q +UE1%Ik~ˉ}ūGJQ(-d\_#7o'bBi@~ttл'pgۺM H5S(LO8eN&63b̜43u=K//(EМ-pbZ~.7Zmu&!d Z Y/66A06J Hu&e%%`/hEpZ^70#"L2al@~D*k!ZpPvvD~X uvteyYhڳːQfXz襞t"Kf } H3Q5 B.@ $pd!s#~<<+"x M0B\t8K@zB@F&S`cbP-`'{[! eDh;VEX0fK9-0IWfH  0Q){`##xFW<+*x<$9E[-qWW.(I+6aa@.y24x6_-"bbϫp@t~,/;m%h^ uf@Wp~<5j>{-]cK'Xto(hw?G%fIq^D$.Tʳ?D*A, `6B$BB dr`)B(Ͱ*`/@4Qhp.U=pa( Aa!ڈbX#!H$ ɈQ"K5H1RT UH=r9\F;2G1Q= C7F dt1r=6Ыhڏ>C03l0.B8, c˱" VcϱwE 6wB aAHXLXNH $4 7 Q'"K&b21XH,#/{C7$C2'ITFnR#,4H#dk9, +ȅ3![ b@qS(RjJ4e2AURݨT5ZBRQ4u9̓IKhhitݕNWGw Ljg(gwLӋT071oUX**| J&*/Tު UUT^S}FU3S ԖUPSSg;goT?~YYLOCQ_ cx,!k u5&|v*=9C3J3WRf?qtN (~))4L1e\kXHQG6EYAJ'\'GgSSݧ M=:.kDwn^Loy}/TmG X $ <5qo</QC]@Caaᄑ.ȽJtq]zۯ6iܟ4)Y3sCQ? 0k߬~OCOg#/c/Wװwa>>r><72Y_7ȷOo_C#dz%gA[z|!?:eAAA!h쐭!ΑiP~aa~ 'W?pX15wCsDDDޛg1O9-J5*>.j<74?.fYXXIlK9.*6nl {/]py.,:@LN8A*%w% yg"/6шC\*NH*Mz쑼5y$3,幄'L Lݛ:v m2=:1qB!Mggfvˬen/kY- BTZ(*geWf͉9+̳ې7ᒶKW-X潬j9(xoʿܔĹdff-[n ڴ VE/(ۻCɾUUMfeI?m]Nmq#׹=TR+Gw- 6 U#pDy  :v{vg/jBFS[b[O>zG499?rCd&ˮ/~јѡ򗓿m|x31^VwwO| (hSЧc3- cHRMz%u0`:o_FIDATxڤ͋\E^II cmA'.,ĝ`l\+d?!Q\FE]d%nQщ4/Wt3Yh6.uԹPGTs^Z1-"g%`0nx( i_6l(YAUѼWB}vV?ԑWPyo-UEUrdURJ)3'=9ި@KfR~{kEcC)鹢c{~ވ[EWX @k."x8\) &5.@Vb3>`l6:@GUW|I1b+?:v`.V딨F#xb'VU_W~FL5;{sX#WsΫSV}Y‹N,y͏ڍ]zyepi)B ΰy'p99仏S9j5JW ݌^DÖ7v\I0~uZz'I1U_ٽ|Ӵ0aWD.XkWdJxz,{t{k;tEBX2kvaNZoPw.0YLPNj1B|뻗>ZH EPALէZIENDB`ugene-1.9.8/src/corelibs/U2Gui/images/ssp_logo.png0000644000175000017500000000101611651544333020441 0ustar ilyailyaPNG  IHDRagAMA7tEXtSoftwareAdobe ImageReadyqe<IDAT8c?%,M_| z}u~ k^{ ~ _ ǪSˏ--9 ,``7mwpD׺ @> пȒ﵍ֿSVI{=N<_*ؕ~`SnAIENDB`ugene-1.9.8/src/corelibs/U2Gui/images/text_ab.png0000644000175000017500000000105111651544333020241 0ustar ilyailyaPNG  IHDRatIME 3UjM pHYsiTSgAMA aIDATxR;HQkI jVEt!"ZY6A0Z$BbK=!"Bp+Qt'qavg}obsϹ>iv4!%,4ZTj"CWJo7_nt*\T@x>G59L!~7׽*w)WPfz1M~7DB&ɖS:4eA5#FCcPYzT=Mt&rC\<1Ԩ&G'4^a?lNRwj$I2:7i>8upH~u: X?mq[w`BygD\$Nw ɝM&IP\^}.e~!szKV=Vtxu cOpAŁ_[zYQN) Jp"V9q}RE[7wIENDB`ugene-1.9.8/src/corelibs/U2Gui/images/arrow_rotate_clockwise.png0000644000175000017500000000113211651544332023365 0ustar ilyailyaPNG  IHDRagAMA7tEXtSoftwareAdobe ImageReadyqe<IDAT8˵NZQy8DF NJ5XBр/DiEmAD0@Դ8Ҵ% Y@41_go,9'(ٹ-;5Cc-^؊֐X >څտN~1ՅW v\N)i7mp- $t+@UVlf0˼߂|@%#ZDD>U㮤##Lz(27ύ > YAW _yydzr7<B8WEeSO`J\''A9-K0BFg}5Հ# w !zBq7˅+đ6s۔CeTH`9ܷyhvע)DH&TiHH9KI$ mֵL\i9IENDB`ugene-1.9.8/src/corelibs/U2Gui/images/msa_find_next.png0000644000175000017500000000111611651544332021432 0ustar ilyailyaPNG  IHDRatEXtSoftwareAdobe ImageReadyqe<IDATxڤS=l@T!BbBU!1tb`T!200fޱc;tHHRCNHM HCuw>N$>aoWiP(2Ď˱'%Ę '51|ԨS{)ԗ3e k$&S򮦝3٬,3) G'ucm7}+WoΦit[Fژ*5OCkZ{߀rLȐo == V`gsDa:1P#ԡloA؆i y`GpԨ ( &!!sF=4;`ݏ n [IENDB`ugene-1.9.8/src/corelibs/U2Gui/images/lock.png0000644000175000017500000000135511651544332017551 0ustar ilyailyaPNG  IHDRagAMA7tEXtSoftwareAdobe ImageReadyqe<IDAT8mRAkA}I54JMhAA[==AySP@Ns"zZF4(&Ivvf}kڵ:13|ߛތa6ciiiD)5'adbYb.7B d,z н<Ït:c&j:@D©+]^XXorynRC]R`L$ARd٪Gj5߬VT*`Lkmz#C4;]Ccy摽R^|*--ؖBHXꘚnUL?`  9A~ HӲ}.v_!apǙVdw(k,l E(}{Ŕ`CkI[C.=`: @y DQnh > OK(J3vT'Q?l.Ϲ^8G `s?Zqr͇oEIENDB`ugene-1.9.8/src/corelibs/U2Gui/images/chart_organisation.png0000644000175000017500000000067411651544332022502 0ustar ilyailyaPNG  IHDRagAMA7tEXtSoftwareAdobe ImageReadyqe<NIDAT8˵RJQ=+Z@C@Vl$[Dt˘P`B4z`̙DyNj\3ʀ -kL"Ҡ6C4BX$/FL#si> ƴfN rZ ]s}ȑec[բ( xB f<Άd:7CFBHC >~,[뤤p}^Ahvsr)򗹹 ?[L7̢+B"U \br\h^[ W(T!͂vc|IENDB`ugene-1.9.8/src/corelibs/U2Gui/images/tt_switch.png0000644000175000017500000000034011651544333020623 0ustar ilyailyaPNG  IHDRatEXtSoftwareAdobe ImageReadyqe<IDATxb?%Bc43q0O W JVd̂p!'>FbMhd"d;!q0@N 064+aAvdFB[Z@DFJ3@咶ԊӢIENDB`ugene-1.9.8/src/corelibs/U2Gui/images/question.png0000644000175000017500000000033411651544333020465 0ustar ilyailyaPNG  IHDRd0PLTEwww#tRNSKIDATxcH a AXaipʖ,5Ő jJ39U Ӷ\LS9IENDB`ugene-1.9.8/src/corelibs/U2Gui/images/add_column.png0000644000175000017500000000034011651544332020717 0ustar ilyailyaPNG  IHDRaIDATxcd0f<6 AEY$dXMLd@dVa 2̜i ~od< f2 430"@ LKcH5 lKpfh.u \@ |@]vS`IENDB`ugene-1.9.8/src/corelibs/U2Gui/images/lock_scales.png0000644000175000017500000000121611651544332021077 0ustar ilyailyaPNG  IHDRatEXtSoftwareAdobe ImageReadyqe<0IDATxlSKA~Fzh[&MA% xrӃ'sJ.$lSM ;v}͌4 ;)d2^KKbC[d"F3k4@,BwN" ȮӌhD^^~jHl},v6䙳3n4H$I& h5YWhP!LBVx !.P!ƺ jUtƂ1jO2;>lg2hXdv]fi7N@8;<|a`tlۦ#2bKvv>\YGG/Jexf)ȫeM<X,3YSH ECON^g,&,:"%se印_*8.I* :v}@$p8$6>s&{GEҬ&-v s\-r^&ț!̓ lk !IENDB`ugene-1.9.8/src/corelibs/U2Gui/images/bookmark.png0000644000175000017500000000127011651544332020422 0ustar ilyailyaPNG  IHDRaIDATxڕOSAƿ{[ZC"W"_C44W.qQ.k ƍ HQ Zoo{{Ό#$ƄJdV9͑JLnJہv`I{ϞN[\ؽ'@d8`GHƉl}6 j궻No@ 7}f.$'Oa\b&e%WQ%H;X* ?3H\pʧD0|O!  ͯ 乃 z䪴]osr$GAMp&#&בt@[@]lH rd wPD@TؕPW5 rOo\$)g &K@ؼ'efi^E:W%0 ,  ƛ9m\ H3Q5 B.@ $pd!s#~<<+"x M0B\t8K@zB@F&S`cbP-`'{[! eDh;VEX0fK9-0IWfH  0Q){`##xFW<+*x<$9E[-qWW.(I+6aa@.y24x6_-"bbϫp@t~,/;m%h^ uf@Wp~<5j>{-]cK'Xto(hw?G%fIq^D$.Tʳ?D*A, `6B$BB dr`)B(Ͱ*`/@4Qhp.U=pa( Aa!ڈbX#!H$ ɈQ"K5H1RT UH=r9\F;2G1Q= C7F dt1r=6Ыhڏ>C03l0.B8, c˱" VcϱwE 6wB aAHXLXNH $4 7 Q'"K&b21XH,#/{C7$C2'ITFnR#,4H#dk9, +ȅ3![ b@qS(RjJ4e2AURݨT5ZBRQ4u9̓IKhhitݕNWGw Ljg(gwLӋT071oUX**| J&*/Tު UUT^S}FU3S ԖUPSSg;goT?~YYLOCQ_ cx,!k u5&|v*=9C3J3WRf?qtN (~))4L1e\kXHQG6EYAJ'\'GgSSݧ M=:.kDwn^Loy}/TmG X $ <5qo</QC]@Caaᄑ.ȽJtq]zۯ6iܟ4)Y3sCQ? 0k߬~OCOg#/c/Wװwa>>r><72Y_7ȷOo_C#dz%gA[z|!?:eAAA!h쐭!ΑiP~aa~ 'W?pX15wCsDDDޛg1O9-J5*>.j<74?.fYXXIlK9.*6nl {/]py.,:@LN8A*%w% yg"/6шC\*NH*Mz쑼5y$3,幄'L Lݛ:v m2=:1qB!Mggfvˬen/kY- BTZ(*geWf͉9+̳ې7ᒶKW-X潬j9(xoʿܔĹdff-[n ڴ VE/(ۻCɾUUMfeI?m]Nmq#׹=TR+Gw- 6 U#pDy  :v{vg/jBFS[b[O>zG499?rCd&ˮ/~јѡ򗓿m|x31^VwwO| (hSЧc3- cHRMz%u0`:o_FkIDATxڤRMkSA=/3i56*E7«".\(V pQpUvڥ ƠQ~k"Mv 9ιZ)6pgw`5`Ƙ6~'ȶ47.#D)GhL]Z[il_Ê?⫷?FL25ד$g>/Ӭ}`λ\ژCV*?ޛ)%pe4A EUD3 zߎ1%%BnjJ4}0qbnVJkjh[n cKDA H{x')DXAw-X*AScTpTL$ :B0T?H@oonSH Z;*̍MyONFq' *P[UKdEխoVY&Hk`W[4OcX 2$Vr:XI}uZ0q+-v^^<,ʎ2΋ycbưl.wm/ k?`|zů<8? :mh5m8/L׫k"{hhٸIENDB`ugene-1.9.8/src/corelibs/U2Gui/images/dna.png0000644000175000017500000000153611651544332017364 0ustar ilyailyaPNG  IHDRatEXtSoftwareAdobe ImageReadyqe<IDATxdSiHTQ{oXS"[6ZPIeDEH!-DD'DhQ ̢E31M2dQٞۛIG|s"b?zH̅I@k³}(,1L`&[2U F JM$RӦ,f&~CmGԺpuz"m=TyˈHq ˏO)x(]qH6P(t]J`8|=-g[/}/Ǩ:x49Z`¿+<렊'=hhP=#O[?رIENDB`ugene-1.9.8/src/corelibs/U2Gui/images/uindexview_select_field.png0000644000175000017500000000611611651544333023513 0ustar ilyailyaPNG  IHDRa pHYs   OiCCPPhotoshop ICC profilexڝSgTS=BKKoR RB&*! J!QEEȠQ, !{kּ> H3Q5 B.@ $pd!s#~<<+"x M0B\t8K@zB@F&S`cbP-`'{[! eDh;VEX0fK9-0IWfH  0Q){`##xFW<+*x<$9E[-qWW.(I+6aa@.y24x6_-"bbϫp@t~,/;m%h^ uf@Wp~<5j>{-]cK'Xto(hw?G%fIq^D$.Tʳ?D*A, `6B$BB dr`)B(Ͱ*`/@4Qhp.U=pa( Aa!ڈbX#!H$ ɈQ"K5H1RT UH=r9\F;2G1Q= C7F dt1r=6Ыhڏ>C03l0.B8, c˱" VcϱwE 6wB aAHXLXNH $4 7 Q'"K&b21XH,#/{C7$C2'ITFnR#,4H#dk9, +ȅ3![ b@qS(RjJ4e2AURݨT5ZBRQ4u9̓IKhhitݕNWGw Ljg(gwLӋT071oUX**| J&*/Tު UUT^S}FU3S ԖUPSSg;goT?~YYLOCQ_ cx,!k u5&|v*=9C3J3WRf?qtN (~))4L1e\kXHQG6EYAJ'\'GgSSݧ M=:.kDwn^Loy}/TmG X $ <5qo</QC]@Caaᄑ.ȽJtq]zۯ6iܟ4)Y3sCQ? 0k߬~OCOg#/c/Wװwa>>r><72Y_7ȷOo_C#dz%gA[z|!?:eAAA!h쐭!ΑiP~aa~ 'W?pX15wCsDDDޛg1O9-J5*>.j<74?.fYXXIlK9.*6nl {/]py.,:@LN8A*%w% yg"/6шC\*NH*Mz쑼5y$3,幄'L Lݛ:v m2=:1qB!Mggfvˬen/kY- BTZ(*geWf͉9+̳ې7ᒶKW-X潬j9(xoʿܔĹdff-[n ڴ VE/(ۻCɾUUMfeI?m]Nmq#׹=TR+Gw- 6 U#pDy  :v{vg/jBFS[b[O>zG499?rCd&ˮ/~јѡ򗓿m|x31^VwwO| (hSЧc3- cHRMz%u0`:o_FyIDATxԓ1OQ7" AZ C@굵$BiIk] (% fޣl 9#՛1@Ҡv жce޹Z" :*EiIƼ/zߣ< 5"s`#!vAz ^&"xp6zJ?%U[Qf؄a4M]+dȳ#",ԔuY=D.Y2ZP <uD;p4j~R5SfaMSgyG 5^I|x8||}@~!NW lmdP3] Ec|IENDB`ugene-1.9.8/src/corelibs/U2Gui/images/zoom_out.png0000644000175000017500000000142711651544333020475 0ustar ilyailyaPNG  IHDRatEXtSoftwareAdobe ImageReadyqe<IDATxڌKTQƿ}sfh(^ zH"꩗z? ǂz )0JEg:̹)胵g~[_R)vW H狛c@yBHtj?Vxn2lopŵ+ژid D0M; ^:s`=fZu<{;}jG+#>hGq( ۤSYY# *+Y)PjCRq<نPGj*+p<lj |^H;gQ3Zr(mh:}p?j!u iŢ~ʃd]&yA4Mp oB˙i-GM^3.,B{Y;K;y wYpD/S=Z$jh`Ys0ܞ^S8E`Ík %0]Ր?s@C/§/ќʼn^6dW53dt;1 DyN%[@c Oj-gYw!%=dçQGG/X;J pn9"#U2Un&\MaSriDs."қ=~ñ+[hM>G.F. TU)4&t0^`yy$3W\:Än?,8ފbIENDB`ugene-1.9.8/src/corelibs/U2Gui/images/msaed_remove_columns_with_gaps.png0000644000175000017500000000112411651544332025066 0ustar ilyailyaPNG  IHDRatEXtSoftwareAdobe ImageReadyqe<IDATxb?%o߿3|˗/ Dy]- @.c+@(0Հ% cIRRWutt+(74*7իu@ }@/쏇 Z*/u֯{Cf-AR5E WW땀WA&"1,Haպ sf yVPd@@#00331V58\MMj{f? c ݃74 81|~_T')P<+w.Vίш/ go0l H?ݽrٕ-%5 _Br߼d!Q-ink[:w#׮͗hכ^^xgbkʕymRb*a!j__ RxqT1ˢ$3gn,XԩlDv}ncǩO@5' 0IENDB`ugene-1.9.8/src/corelibs/U2Gui/images/plus.png0000644000175000017500000000112411651544333017577 0ustar ilyailyaPNG  IHDRatEXtSoftwareAdobe ImageReadyqe<IDATxڤS;KA 1#B,5`!v"6b#hEFBB*h$qI.w#9cnٙofR蕘 %=nK+ta i00"z 2ݢK GɾޥcrJ(^D@Q#;V*4xpEL[ R(("@d13&*< _l 6U' h]gwypqDxC3 T\5Mj.!̻|;D?}6%f wf UGsPHWsdQyPa43U%9` 0¨Xb>:ǓFvggNU)qu}}kEmpk]+oO"xNjo:B1 Ef?|٫ϫ3ט~  =oCzs~P͐~:G`0 ak@\oahSj{̴t@XF ԶSZj2vښC/Cp 2T K`P\qg ڏY"f@ `t]<׀OX0^ V ĿdD `2Th{IENDB`ugene-1.9.8/src/corelibs/U2Gui/images/add_existing_document.png0000644000175000017500000003532411651544332023164 0ustar ilyailyaPNG  IHDRSi]1]tEXtSoftwareAdobe ImageReadyqe<:vIDATx] `E깓$pCD`>l(((((.\6ZX(((((.`ciAPPPPP\LG=\(((((.2Gb>pvRPPPT…*f%:IAAAs *`(((((gRNa=ت#{|tUE! ۶mgx/}vPGLt=E"hyS/cӳ]e磠H<cNf" 1!TG((((wB|YȺ*\8((((OFLuB\XcQI´E"ဪf^H#5LT_%3pHy{{ryb SPp{qY2EP_ߨtr~X4Fi5ŘH3q16 (II1*>"k:Ab=iS6|Lei>J}EaB/F;)QPPPo^J"Aڮ3qXHL7rұcG=\((((?!eJU~A"H ~V棠H@?,c+^Hi,j 4/f((((d$t~X 4 & \@dWѩ>| ADbJ+# xʏ2 /PǴ\(ٳWZymIW%n+ݻy(YP"r7oE"Yq3GAAAO&I Q4N/kVިB 2}G^f>vRPPP_ړNDH{MK1)&ǒ523azNG{H}G5Eb>!bb1' iXE7ډ Q`|Of>D/8wWD`R24.$}qGAAAq9i'|BI1#h%"!ZBΓ^*dѳ.t8>VRdOAa.Ւo ,qX,0P `0G{s?dOO^);d,.*u"GPL&ՏN-f7b7YCk^+:5Տ9 bEӧ7mLKϾɤJU[xcu7trzUY'{n<7a(Q,^ָߩc/~8i֙ Տw^b[Gu<:K_@p#=+Y)xOrUCHd-l5ɂ(/R󰞯A7;t_+>VI}+ T`wRw4R=&ݫǸ韖S.5YJrWe a+B w|[)lY𞸕I{Oj8$9Zlx׻p򆉐QgN5AbMT,A˼FZ*[q*_E!<$r X^`UXdD6qPVx-aO";VtŔ9OC}q29uin\aEBDÕi5*wW+6mĴT3{|r.Z9*WQDqF S)fN{@WVV}3(tom&=<ɪd:bsҺiӫ40{`%PUVNhf{}]׋G3 Ufޯٶg|_M]7bBw/ _P[ J1A&d&2)ā,džb%ô'kgY͢PUzQ|gW ٣zR*ɒ ėS`'S \ޡS>`dxpz]^R;4I3W_w^s/ՙj+5ēOYbQhO<m|R4u#>V -"*4J|l=wg+ּK+U?›kt]n\SVpI:ǜ9GO}k3狐S%K܎ƍNj vڜF%*Rb^-P+}^5. =y%:@ⴋ-JyS1$d!+@u+yu-$|Cqq6jq\Lx\ۜPSp=*npq}gn,/&͹qIJ) K#d&f48(*bH8mƖpE5$"*njb SƤ5ň[k˫7f+喛 ?'jh&]QjEⳆ_ x8؉ij!V)f<N{6q.)&8Y ovB~b#N{=7H[ԏN?˗/*˾6csS-=wo NɗP;_R>4wtGd3gWZ=?/(kJWVk|~sOWp69]ڵ!s-ٲT*9jGs΄$_ګ/> VGn{4ɃoݺlRy }i&{Oi/)۞YPS?[v%x76o/LߏpKɔ|3~GǨrG"꾮.wZtW˾h+@K@8nEoHA[a5iMS̬MwkZE~vBVv7<d1UoV ’e[L6-ilEnckLm;to)A|yS؄Fd"zvD!xnO=Ed*4H}lXI!9?^=k>jot dgUΝnU?~dmƄIǢ#?P)S!W^5|{sHN*Hψcsrs5cDT)n}Wm{л 9~\vMmh{?,_əCw8^ |dsϪ kU7m䙚$([:u;5HqACJ~{ym0qi{Y w&{ޑJr)}M5h&1pb(^d3q*۪dGıԴHn) 1&@6)6uSnjO.><9loъl_rZUЪN7,7\ ǝa\nRc\ɘq W|1s]H|ݸىuɴ+Vt`%Jk98<}ؚ%M2,Z.mogȻ3;YFY6Qկ$OW=EI_̛OrǛnt&ڪ}=ϙ3Azጥ hoGMg ,][LzF=͙6u4%PVDVS5)ŧdoX#{M?^oߤK4rHqi jȤ! 3$t~O7Myp<Ŷ탚55䣾BΘ4A yMP&4hI&OHXWӆGrӏ39XI 6crÏ;ој\SkW[#0 V^^-8J$+&9tI0tO%IE$0 @X-Sk^8|^xmR9? J._tޮ]7#I֗QPΑ}{^Sys#}5O9kp?5T`&;Rߨ֭߀$-cPbgs͘[TT?vx-y]`3|:TR>&y_ȧ5i25x%2Sf~Q`GJwAv[w*(,L,\x?gD\(ׅW_}׮#K 3nty'rK9sk-F;<4|CAjq#gO<޶]E^FҕPuWN@׬Iǰ6lٺ8k}(Ȗ@6rԯw0ci!70޽z|-h bYRYz),C&_O։TzSړ}zbk{/Tnϩq DZ]iD*B@˪>#(n)R,xL@'JEPSPmș3ܫU=\4 ;ϗ>oD}}1g |{ˍ\V0pP1;~ӶKmf?{4O @yW^xPY/1Wԣ 3L?v@Le&W٣?opg~ŽO5lݸAc?Q VR ET֦UKrA9pzAqz}+.ۦ|>G|p"w ËT߫o?VP*yyqwU-wۃ꼒3v|`Pk>COkvgy@N6}~jyӃƅj;%8=_K@66n޺Tl$|3n!9I5y۟7-[&7/c#GZ5'yeԉH2weXXL i|e'"t(4p|<4EsɽVvawK^"e&v"w/ J×Q=$^ M@O00 Ӟ4R|&M~m@`M`O>x<)/o'3aeXU|`Tפ~%fmБC6)f. y|A!#0^|5ϖLQ& \IX)j+IE))x3er8CFdgt1^&ybE%5#</,,PrHPzHV$xȨEc) fnHϽ O1XY\Z@Y2T&C5]b2ޗ^V4+@ W Գ;͐ko@Yؖ_ OSN|Ǧ[<^&e hs@⧳EjA[hq8Pj )Ǒx._٬Icgfe44Lä_zW&;Y(qjFς EI!(\qH1<{4$)z~nl]>e}VQZvl S<4nZ/t^I1˯з#vt(_Kd9pxyiM}|G <`ԓrOZBå49ujウaA>{ Ҽ;RC.3e7d޺3hwh~e4 ^/wyl 9AVoatZ Ie JKsʴOmaK_0K I)!O4)zܕ_2kkZ × jؙzTld;d䘒Zp"ʣ~zN=Y sX>8 sV[&JDT\B/2Hw.qaӟGzُk mÍmM,#],3(nCʓĬS:uV,R0Ni2'"d1Gx(Y )lY#|Xuji5.!:[|1f%{'՗Ok֬-KNSc-}{CuX;7%܋u/ ncٛ|l$iq5y߯ K,6ŚqQ%;>ާ&k7iep厳;:÷xY?_{|VRw>GeƫzoWfdFDC3Vߧ.~A;C >ӟV0`~sLpmQy߆ydŬcS 72vM `{%ǁ֮ĔsD`aoXw[\7em/* KͲ\vKZ /$,"#Ly꼄PRLeVAQ[b3I ';'/N)\vf؅[e|_QeIY{~.]Ɩa/%ZHI$lڴY|jN$g)DI=Eli2cl -WMAzq믿Nuи^Äi.?cKz퍷>:<:q?m[3Py 2.WP;<4mya]q{qP?X)ygKD@Pi[8)h I`mQ̳P&*Sff6vzpH'hfZrL m8;jxRsQ~=hw6.2z?pX3|2z>yIbVSkOITp'Bv@$)$W|$s:B_G;υkڠ贱H}`?Gu6A ޴C0335'}|}5}K޸1#AUa35M`$cW j Z392퟇!峑=!(gEwO9&Mfܿ/.EϸIP-.V:m' )14Ι"Dq71b{,dM)إf} 3txdՓ@JSeW|UH{.G5jF3 e.w6+koj1U8\ْW<|6Sy~IMHabʍ62z'ıýb5g^(KmLn+oX|b1d2,&E|ƚL23BmаɘUR\T! WL&ǯt'AKd ΆpittYO?S>uS'L!]Ju2 ?]Aur1|UݓՂe?dGz ڌ\>8NYV 3q믹:L$n/ϛc9}Zie=Bc޲ukޣ1 O3O?}# 4C]Q ֠Êދ 'aK#~iflbq.9N<2/o)SHgH服|eE.YaR.;w KOYIz? 9:.Y_j\ё8i螮;YTC>R"JJ6LYjTB6..1K1D=G*/gEl?Ifj7/WrY򴢸F|ziި[N~uE݌I>\s[텧" _~"k~͛E s-F?m%ĥgi_՗&@wY O!GP y;6&2}ֽ#b.]%C361:gBwz k!Zcm9^׸Q[%RDoF^;"u]LrL۝{5F'_A{O48lmfto߱K޲U`Zm ,9R,Db $G<Ũ.V/ ^2ub BIxA%[~i@M# elCu _g1O3aշ!éK|IߖXCݜAZ1g Np0.'w<uQ9 NwOW ivKMBs\5^|*?lL懌DTA!-eN> d#wgmVM2VN_h㯽y:Mnf}L_8"Pr&69\w9z'_֓!)?bKΦ:$(J`\өB=WsYF(U%6۰1[SO>Z^)Wiaf#DFMgqR b o4$RC^*SY 'щ[ƈ/AxAN|'yل3'E^gսS%TP 9&j|URxA/p͝u;ҫ=,Cydxwo-N"HV8V)Ȉs/K#>X/1|~7?HA !knsiKRW0:L٠w>4?䡿kB0xU29?Ӛxmꯒpob5b%3c,}.(; $[͚iEjMcPoϙ4g<Ȳ $. rt_N+#֬sRI#\w7hJcH87~soliM@8k^"pkRdX w8||}6Bcw6oV{ŔY0ŔKbVbbzڋ:XXX0iEʋ anΉġ(jT`dWB+? x<˖-We ۾_s)vh~o+]]?w¤j ڴbܽJ77k 醛`Y/1!Ǝ@k^z?fwNrfH3>o7i#+^;gђsyRM?+WzƏ`̜ ߯D{O_^#Z50O?7i?9wF1۬#P6@׋l}X,-^p6|t9yڴp֬/X,ܼ/蘠=xB;“塇MGYq'|ԇ#i;W)Sڴ>\h#1O;ؤվRhxœsT,.~bz:d q;# _+IZQ& yy76nDDԏg|,EnJnr<Ӽ`S4ؓc IPwt2~*Hk4wH ?82wKV.ݺu+ZŕDuh=R;uu%E ˝%@ꏢv ?" MFsx>k[^lw[溈 Y$96iaQ<\hÇf5g>JWe</r)#E8r0pf1MDB~=p0r>is$2g=\ 6:Լ~M)A~'[sd^vEŐy|䴙! XAML|6_˜60 ȝaTkP<_uH?͆^B+J8M[rܐyҐTk|܆UpOCGmj{ҔO<_h8bH!N}6Zuϔ4r6}ixԱ5DwwC&|[a]\:aq)?y;k C>Ybyg<1d>-QuEAPy9=@^!s/!o؂?ְy@,j bW~0lPEZ`R_ B;X"5vOs :HC"қM yܼc=΀kϸcLMntX("9'NUA&U # Ka %wS^̠B 1hl),R7x'_|b)a/ȿvzrr]|Lqpa=q*F x~ˍ-[TwZ*?kuLI$31Z@dw2WڭI:+4'sO`?_F W5C6*'Mٮzqظ)gCG7I'pj8}/ڳ﵁c( u sgry2˧lh/_LоLu,,Rx>(ׁ۝U`$lyƥ"J_))4/762rZa4PgdP}M8 k b!K@66#,cO0Y[I+9FomN<,+Ϊ fێ]/5tRenOoBtY<+d`?_)OZToƲOjP{'{cZ G_ܳ4'`1VE;#?_7淕^sK䰤W#X1;D󨬠4TBb·NƔ3,?9y^<$ɓyxxǤ ȣN E':k׮- 2ZK(ȕ"pbyy-(o v2Cűo'{ >NzuЦi9}Nd \Mn.bOk8_ j $KXVYD][ K"^ܔ@u+.Π?U"$d+/iԨ\Mʤ/a!oc Pȵ%t\z17*\GAQi&MF.7Q[ ZHP|xNi,ڜ H;qY8/ZĄf(opwƙl]aڶcU!oI Iй mg>`Y~ɟ|4yunݺUM}vޓaVG"G2 =$ | T䜞ھWHzMynۺ'X{T)dgx$OL{8F^ĂOL D'TC9jk2f 1ɴTQT7ԨS0gK}i+YdQ˦zOި&$J"yR"H9<6l'>ЀۤE2<6t萷#' ?ð}B[pЦ5r2x=^\ >;w\&N:n/e-Ώ5In{rɑ4Eu"?ejh"DvZ<}g|,9#8qǩ'I&СΛp/Y'zjr۶za]z) xX&$R׬]/8"kԈa5^-'o'ps\)((((HFY8X/mٲW>:+G3y:>#=6x8")x.a77NCVHE'9H&OLb<)DRRRffS s+('YQPPP$&+*(饈1̱rᣏ?$1q <9+S\)co6`O1 "lꢥGAAAM0_ ;`I3 ^%?i&{4&Q1'^ELx)#fCa T|ݪe~e8,AN͋"Of"p؝:uڌZ2'MzV>]4`(3njp,9# uU=QGAAAQ]/D<M9dIQl)%A_X#< #I5QΒW C⢕}1 j*I~$"$/I_Ğ8I X9_GG;)(((|Efب SvإRY=9}y9e-~|@"u_dCNoEe߭;CE|83e> Ĥx> XvxX{Qk5 *=D2E_J u1bCGO3ÙaFpA"gWx9,۫HQ棠HL[Zr]A[ ge> fĔb`-^BAAAqQ8/X,4&uN"1'G)VS(t:e> LIsG~C2* )QPPP$" >XPCsvTQPPP\P$gW5_)vB`YV<9e"8h2E2i*`hE2*T\R棠HSAU9X H=|D{,8ABu.7S4  /. TH}߂o…g\XQPPPT/`Jy9@ (#8)P=A'c 5| gs8v;I߉d(%Aq:04PGAAA(<;Q簸{' RG$HUbV.f!N VX<,?8)QPPP$ D$3~"W9g%'d$0}܎X sD~ܳDÅ,,0@{l6|:~X V{S >ITⓆ@B~$/R棠8s)~nH 6"rOs UGSyK0%0,l2ri2E"Q  P_`> =IENDB`ugene-1.9.8/src/corelibs/U2Gui/images/bookmark_remove.png0000644000175000017500000000167111651544332022004 0ustar ilyailyaPNG  IHDRatEXtSoftwareAdobe ImageReadyqe<[IDATxd_lSeƟ=vڳkn6ʀ3ˆA#f \ ra LreDP#݂  Y`!jD9{=0pwi `uR!CLI:00 ]vs4`lb,V ><.oq\` !f(x6<ƵKzsCo͑>=WnMD`R55x62‘!ʧod\e'AUu25*xx|\* EmW[]\g&7n?=D{:8_R:َh|WBa,Z6a;6t:$mY,ApjTqt3Yft`KlZ }<[O鹼V@(ebON[9؟_z`kS9}'ȏϠu/*"6 1HH8 tHi~z:h\Zag9~"&h9\R5:j]ҽv56 kBe@k<]J$EC ܷ?MKײ~Y\,bk3ga}6凗TYSnV4^H&w'/DmB!OoXަJ 7e,̓ØJ"9xgF_7@oYtbFׯ=Hmj_TFP#^1Lu0CHuc,LNLo 6M3F$qWa>dvKlo'7do;IENDB`ugene-1.9.8/src/corelibs/U2Gui/images/predefined_annotation_groups.png0000644000175000017500000000260711651544333024561 0ustar ilyailyaPNG  IHDRatEXtSoftwareAdobe ImageReadyqe< iTXtXML:com.adobe.xmp kIDATxڌR1K#A}39O" leFP,,lD" l@1FbDh."Vdo~ؙo=fY&h+b뻣 =UśoiqBp:﵋pjK0P. "( XYpX(;GԔB Ğp33~twGy*GG#|>_T6׺~.<=tx܎˺G\I,/98h6<<쒰W[{R)^IP!ؘdޮҔGH`h=;C_(Ʋ$Mr 8­ 1$"+]}?*flf jc#g</Irr,@4jlNh,noC($2d.cl՟B8IaǩWK!TFvoV v iiQ 3-WE<V)IENDB`ugene-1.9.8/src/corelibs/U2Gui/images/ruler.png0000644000175000017500000000120211651544333017742 0ustar ilyailyaPNG  IHDRatEXtSoftwareAdobe ImageReadyqe<$IDATxڤSO`~Z[ #19rH w&4#ī׊;u:mYum6m Om{># O0t zvy5R8Nhÿ6 Qmx hm-Vf GEL9 y!Mh/So <8nFH\}*KrV +y#6Yj(9\8~b֠ӽEɭ:FR`' ̰̓VdkZSO+v6^Qr/xD4ۣO9e~UpaW&Df,n Gh";gxZ.}ͮMdJª'_h5m7ۃ5 >0 Wc$3-MA2.J.UDi_;.,ݨ)Y~Q*TNDzm!|5D33ۚ\אTXO:N<+PA=+l u#TXCT^G{cm6cSO53 癗DjLk:Ԭz҈/cSӫA%pMSɩ.0e5AHk2L2/ 'D춛q HB\"Bଅ!O % ^ԫ(L;&|ap4X <\}u7.0q8+Mm<(XUW#mڊ}y)vg»H4A>46$%SIENDB`ugene-1.9.8/src/corelibs/U2Gui/src/0000755000175000017500000000000011651544333015432 5ustar ilyailyaugene-1.9.8/src/corelibs/U2Gui/src/UnloadDocumentTask.cpp0000644000175000017500000001224611651544333021707 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "UnloadDocumentTask.h" #include #include #include #include #include #include #include #include #include #include #include #include #include namespace U2 { ////////////////////////////////////////////////////////////////////////// // unload document UnloadDocumentTask::UnloadDocumentTask(Document* _doc, bool save) : Task(tr("Unload document task: %1").arg(_doc->getURLString()), TaskFlag_NoRun), doc(_doc), saveTask(NULL) { if (save) { saveTask = new SaveDocumentTask(doc); addSubTask(saveTask); } setVerboseLogMode(true); } Task::ReportResult UnloadDocumentTask::report() { if (doc.isNull() || !doc->isLoaded()) { return Task::ReportResult_Finished; } propagateSubtaskError(); QString errPrefix = tr("Document '%1' can't be unloaded: ").arg(doc->getName()); if (hasError()) { assert(saveTask!=NULL); coreLog.error(errPrefix + tr("save failed!")); return Task::ReportResult_Finished; } QString error = checkSafeUnload(doc); if (!error.isEmpty()) { stateInfo.setError(errPrefix + error); coreLog.error(stateInfo.getError()); return Task::ReportResult_Finished; } bool ok = doc->unload(); if (!ok) { stateInfo.setError(errPrefix + tr("unexpected error")); coreLog.error(stateInfo.getError()); } return Task::ReportResult_Finished; } void UnloadDocumentTask::runUnloadTaskHelper(const QList& docs, UnloadDocumentTask_SaveMode sm) { QMap failedToUnload; // document can be unloaded if there are no active view with this doc + it's not state locked by user TriState saveAll = sm == UnloadDocumentTask_SaveMode_Ask ? TriState_Unknown : (sm == UnloadDocumentTask_SaveMode_NotSave ? TriState_No : TriState_Yes); foreach(Document* doc, docs) { QString err = checkSafeUnload(doc); if (!err.isEmpty()) { failedToUnload[doc] = err; continue; } bool saveCurrentDoc = doc->isModified() && saveAll == TriState_Yes; if (doc->isModified() && saveAll == TriState_Unknown) { QMessageBox::StandardButtons buttons = QMessageBox::StandardButtons(QMessageBox::Yes) | QMessageBox::No; if (docs.size() > 1) { buttons = buttons | QMessageBox::YesToAll | QMessageBox::NoToAll; } QMessageBox::StandardButton res = saveAll ? QMessageBox::YesToAll : QMessageBox::question(NULL, tr("Question?"), tr("Save document: %1").arg(doc->getURLString()), buttons, QMessageBox::Yes); if (res == QMessageBox::NoToAll) { saveAll = TriState_No; } else if (res == QMessageBox::YesToAll) { saveAll = TriState_Yes; saveCurrentDoc = true; } else if (res == QMessageBox::No) { saveCurrentDoc = false; } else { assert(res == QMessageBox::Yes); saveCurrentDoc = true; } } AppContext::getTaskScheduler()->registerTopLevelTask(new UnloadDocumentTask(doc, saveCurrentDoc)); } if (!failedToUnload.isEmpty()) { QString text = tr("Failed to unload document")+"
    "; foreach(Document* doc, failedToUnload.keys()) { QString err = failedToUnload[doc]; text+=doc->getName()+" : " + err + "
    "; coreLog.error(tr("Failed to unload document: %1, error: %2").arg(doc->getName()).arg(err)); } QMessageBox::warning(QApplication::activeWindow(), tr("Warning"), text); } } QString UnloadDocumentTask::checkSafeUnload(Document* doc) { bool hasViews = !GObjectViewUtils::findViewsWithAnyOfObjects(doc->getObjects()).isEmpty(); if (hasViews) { return tr("There is an active view with document content"); } bool liveLocked = doc->hasLocks(StateLockableTreeFlags_ItemAndChildren, StateLockFlag_LiveLock); if (liveLocked) { return tr("Document is locked by some algorithm and cannot be unloaded"); } return QString(); } }//namespace ugene-1.9.8/src/corelibs/U2Gui/src/ObjectViewModel.h0000644000175000017500000002655511651544333020642 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_OBJECT_VIEW_MODEL_H_ #define _U2_OBJECT_VIEW_MODEL_H_ #include #include "MainWindow.h" #include #include #include #include namespace U2 { class GObjectViewFactory; class GObjectView; class Task; class GObject; class Document; class MultiGSelection; class GObjectViewObjectHandler; class U2GUI_EXPORT GObjectViewFactoryRegistry: public QObject { public: GObjectViewFactoryRegistry(QObject* p = NULL) : QObject(p){}; void registerGObjectViewFactory(GObjectViewFactory* f); void unregisterGObjectViewFactory(GObjectViewFactory* f); GObjectViewFactory* getFactoryById(GObjectViewFactoryId id) const; QList getAllFactories() const {return mapping.values();} private: QMap mapping; }; class GObjectReference; class U2GUI_EXPORT GObjectViewState : public QObject { Q_OBJECT public: GObjectViewState(GObjectViewFactoryId _factoryId, const QString& _viewName, const QString& _stateName, const QVariantMap& _stateData, QObject* p = NULL) : QObject(p), factoryId(_factoryId), viewName(_viewName), stateName(_stateName), stateData(_stateData){} GObjectViewFactoryId getViewFactoryId() const {return factoryId;} const QString& getViewName() const {return viewName;} void setViewName(const QString& newName); const QString& getStateName() const {return stateName;} void setStateName(const QString& newName); const QVariantMap& getStateData() const {return stateData;} void setStateData(const QVariantMap& data); static const QString APP_CLOSING_STATE_NAME; signals: void si_stateModified(GObjectViewState* thiz); private: GObjectViewFactoryId factoryId; QString viewName; QString stateName; QVariantMap stateData; }; class U2GUI_EXPORT GObjectViewFactory : public QObject { public: static const GObjectViewFactoryId SIMPLE_TEXT_FACTORY; GObjectViewFactory(GObjectViewFactoryId _id, const QString& _name, QObject* p = NULL) : QObject(p), id(_id), name(_name){} GObjectViewFactoryId getId() const {return id;} QString getName() const {return name;} virtual bool canCreateView(const MultiGSelection& multiSelection) = 0; virtual bool supportsSavedStates() const {return false;} virtual bool isStateInSelection(const MultiGSelection& multiSelection, const QVariantMap& stateData) { Q_UNUSED(multiSelection); Q_UNUSED(stateData); return false; } virtual Task* createViewTask(const MultiGSelection& multiSelection, bool single = false) = 0; virtual Task* createViewTask(const QString& viewName, const QVariantMap& stateData) { Q_UNUSED(viewName); Q_UNUSED(stateData); assert(0); return NULL; } protected: GObjectViewFactoryId id; QString name; }; class GObjectViewCloseInterface; class U2GUI_EXPORT GObjectView : public QObject { Q_OBJECT public: GObjectView(GObjectViewFactoryId factoryId, const QString& viewName, QObject* p=NULL); GObjectViewFactoryId getFactoryId() const {return factoryId;} const QString& getName() const {return viewName;} void setName(const QString& name); QWidget* getWidget(); const QList& getObjects() const {return objects;} // Returns true if view contains this object bool containsObject(GObject* obj) const; // Returns true if view contains any objects from the document bool containsDocumentObjects(Document* doc) const; virtual QVariantMap saveState() {return QVariantMap();} virtual Task* updateViewTask(const QString& stateName, const QVariantMap& stateData) {assert(0); Q_UNUSED(stateName); Q_UNUSED(stateData); return NULL;} virtual bool checkAddToView(const MultiGSelection& multiSelection) {Q_UNUSED(multiSelection); return false;} virtual Task* addToViewTask(const MultiGSelection& multiSelection) {assert(0); Q_UNUSED(multiSelection); return NULL;} void setClosingInterface(GObjectViewCloseInterface* i); virtual void buildStaticToolbar(QToolBar* tb); virtual void buildStaticMenu(QMenu* n); virtual bool canAddObject(GObject* obj); // returns error string if object can't be added by some reason virtual QString addObject(GObject* o); virtual void removeObject(GObject* o); virtual void saveWidgetState() {} virtual void addObjectHandler(GObjectViewObjectHandler* oh) {objectHandlers.append(oh);} virtual void removeObjectHandler(GObjectViewObjectHandler* oh) {objectHandlers.removeOne(oh);} protected: /** if 'true' is returned -> view will be closed */ virtual bool onObjectRemoved(GObject* o); virtual void onObjectAdded(GObject* o); virtual void onObjectRenamed(GObject* obj, const QString& oldName) {Q_UNUSED(obj); Q_UNUSED(oldName);} protected: virtual void _removeObject(GObject* o); virtual QWidget* createWidget() = 0; signals: void si_buildPopupMenu(GObjectView* v, QMenu* m); void si_buildStaticMenu(GObjectView* v, QMenu* m); void si_buildStaticToolbar(GObjectView* v, QToolBar* tb); void si_objectAdded(GObjectView* v, GObject* obj); void si_objectRemoved(GObjectView* v, GObject* obj); void si_nameChanged(const QString& oldName); protected slots: void sl_onObjectRemovedFromDocument(GObject* o); void sl_onObjectNameChanged(const QString&); virtual void sl_onDocumentAdded(Document*); virtual void sl_onDocumentRemoved(Document*); virtual void sl_onDocumentLoadedStateChanged() {} protected: GObjectViewFactoryId factoryId; QString viewName; QWidget* widget; QList objects; QList requiredObjects; GObjectViewCloseInterface* closeInterface; bool closing; QList objectHandlers; }; class U2GUI_EXPORT GObjectViewCloseInterface { public: virtual ~GObjectViewCloseInterface(){} virtual void closeView() = 0; }; class U2GUI_EXPORT GObjectViewWindow : public MWMDIWindow, public GObjectViewCloseInterface { Q_OBJECT public: GObjectViewWindow(GObjectView* view, const QString& _viewName, bool _persistent = false); const QList& getObjects() const {return view->getObjects();} GObjectViewFactoryId getViewFactoryId() const {return view->getFactoryId();} bool isObjectView() const {return true;} bool isPersistent() const {return persistent;} void setPersistent(bool v); QString getViewName() const {return view->getName();} GObjectView* getObjectView() const {return view;} virtual void closeView(); GObjectViewFactory* getViewFactory() const; virtual void setupMDIToolbar(QToolBar* tb); virtual void setupViewMenu(QMenu* n); protected: bool onCloseEvent(); signals: void si_persistentStateChanged(GObjectViewWindow* thiz); private: void updateDocumentConnections(Document* o, bool added); protected: GObjectView* view; bool persistent; }; ////////////////////////////////////////////////////////////////////////// // Customization class U2GUI_EXPORT GObjectViewUtils { public: static QList findStatesByViewName(const QString& viewName); static GObjectViewState* findStateByName(const QString& viewName, const QString& stateName); static GObjectViewState* findStateInList(const QString& viewName, const QString& stateName, const QList& states); static QList getAllActiveViews(); static QList findViewsByFactoryId(GObjectViewFactoryId id); static QList findViewsWithObject(GObject* obj); static QList findViewsWithAnyOfObjects(const QList& objs); static GObjectViewWindow* findViewByName(const QString& name); static QString genUniqueViewName(const Document* doc, const GObject* obj); static QString genUniqueViewName(const QString& viewName); static QString genUniqueStateName(const QString& stateName); static QList selectStates(const MultiGSelection& ms, const QList& states); static QList selectStates(GObjectViewFactory* f, const MultiGSelection& ms, const QList& states); // Returns active object view window. // Returns NULL if active window is not object view window static GObjectViewWindow* getActiveObjectViewWindow(); }; #define GObjectViewAction_DefaultOrder 100 class U2GUI_EXPORT GObjectViewAction : public QAction { Q_OBJECT public: GObjectViewAction(QObject* p, GObjectView* v, const QString& text, int order = GObjectViewAction_DefaultOrder) : QAction(text, p), view(v), actionOrder(order) {} GObjectView* getObjectView() const {return view;} int getActionOrder() const {return actionOrder;} void addToMenuWithOrder(QMenu* menu); private: GObjectView* view; // Action order can be used to set-up relative action position in GUI elements int actionOrder; }; class U2GUI_EXPORT GObjectViewObjectHandler { public: virtual ~GObjectViewObjectHandler(){} virtual bool canHandle(GObjectView* v, GObject* obj) {Q_UNUSED(v); Q_UNUSED(obj); return false;} virtual void onObjectAdded(GObjectView* v, GObject* obj) {Q_UNUSED(v); Q_UNUSED(obj);} virtual void onObjectRemoved(GObjectView* v, GObject* obj) {Q_UNUSED(v); Q_UNUSED(obj);} }; class U2GUI_EXPORT GObjectViewWindowContext : public QObject, public GObjectViewObjectHandler { Q_OBJECT public: GObjectViewWindowContext(QObject* p, const GObjectViewFactoryId& id); virtual ~GObjectViewWindowContext(); void init(); QList getViewActions(GObjectView* view) const; protected: /// init context associated with 'view' virtual void initViewContext(GObjectView* view) = 0; void addViewResource(GObjectView* view, QObject* r); void addViewAction(GObjectViewAction* a) {addViewResource(a->getObjectView(), a);} protected slots: virtual void sl_windowAdded(MWMDIWindow*); virtual void sl_windowClosing(MWMDIWindow*); virtual void sl_buildContextMenu(GObjectView* v, QMenu* m) {buildMenu(v, m);} virtual void sl_buildStaticMenu(GObjectView* v, QMenu* m) {buildMenu(v, m);} protected: virtual void buildMenu(GObjectView* v, QMenu* m){Q_UNUSED(v); Q_UNUSED(m);} virtual void disconnectView(GObjectView* v); QMap > viewResources; GObjectViewFactoryId id; private: bool initialzed; }; }//namespace #endif ugene-1.9.8/src/corelibs/U2Gui/src/OpenViewTask.cpp0000644000175000017500000002536711651544333020532 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "OpenViewTask.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include namespace U2 { /* TRANSLATOR U2::LoadUnloadedDocumentTask */ ////////////////////////////////////////////////////////////////////////// // LoadUnloadedDocumentAndOpenViewTask LoadUnloadedDocumentAndOpenViewTask::LoadUnloadedDocumentAndOpenViewTask(Document* d) : Task("", TaskFlags_NR_FOSCOE | TaskFlag_MinimizeSubtaskErrorText) { loadUnloadedTask = new LoadUnloadedDocumentTask(d); setUseDescriptionFromSubtask(true); setVerboseLogMode(true); setTaskName(tr("Load document: '%1'").arg(d->getName())); addSubTask(loadUnloadedTask); } static Task* createOpenViewTask(const MultiGSelection& ms) { QList fs = AppContext::getObjectViewFactoryRegistry()->getAllFactories(); QList ls; foreach(GObjectViewFactory* f, fs) { //check if new view can be created if (f->canCreateView(ms)) { ls.append(f); } } if (ls.size() > 1) { GObjectViewFactory* f = AppContext::getObjectViewFactoryRegistry()->getFactoryById(GObjectViewFactory::SIMPLE_TEXT_FACTORY); if (ls.contains(f)) { // ignore auxiliary text data ls.removeAll(f); } } if (ls.size() == 1) { GObjectViewFactory* f = ls.first(); Task* t = f->createViewTask(ms, true); return t; } return NULL; } QList LoadUnloadedDocumentAndOpenViewTask::onSubTaskFinished(Task* subTask) { QList res; if (subTask != loadUnloadedTask || hasError() || isCanceled()) { return res; } // look if saved state can be loaded Document* doc = loadUnloadedTask->getDocument(); assert(doc->isLoaded()); res.append( new OpenViewTask(doc)); return res; } ////////////////////////////////////////////////////////////////////////// // OpenViewTask OpenViewTask::OpenViewTask( Document* d ) : Task("Open view", TaskFlags_NR_FOSCOE | TaskFlag_MinimizeSubtaskErrorText ), doc(d) { assert(doc != NULL); assert(doc->isLoaded()); } void OpenViewTask::prepare() { QList res; //if any of existing views has added an object from the document -> do not open new view const QList& docObjects = doc->getObjects(); if (!GObjectViewUtils::findViewsWithAnyOfObjects(docObjects).isEmpty()) { return; } //try open new view GObjectSelection os; os.addToSelection(docObjects); MultiGSelection ms; ms.addSelection(&os); QList sl = GObjectViewUtils::selectStates(ms, AppContext::getProject()->getGObjectViewStates()); if (sl.size() == 1) { GObjectViewState* state = sl.first(); GObjectViewFactory* f = AppContext::getObjectViewFactoryRegistry()->getFactoryById(state->getViewFactoryId()); assert(f!=NULL); res.append(f->createViewTask(state->getViewName(), state->getStateData())); } else { Task* openViewTask = createOpenViewTask(ms); if (openViewTask!=NULL) { openViewTask->setSubtaskProgressWeight(0); res.append(openViewTask); } } if (res.isEmpty()) { // no view can be opened -> check special case: loaded object contains annotations associated with sequence // -> load sequence and open view for it; foreach(GObject* obj, doc->findGObjectByType(GObjectTypes::ANNOTATION_TABLE)) { QList rels = obj->findRelatedObjectsByRole(GObjectRelationRole::SEQUENCE); if (rels.isEmpty()) { continue; } const GObjectRelation& rel = rels.first(); Document* seqDoc = AppContext::getProject()->findDocumentByURL(rel.ref.docUrl); if (seqDoc!=NULL) { if (seqDoc->isLoaded()) { //try open sequence view GObject* seqObj = seqDoc->findGObjectByName(rel.ref.objName); if (seqObj!=NULL && seqObj->getGObjectType() == GObjectTypes::SEQUENCE) { GObjectSelection os2; os2.addToSelection(seqObj); MultiGSelection ms2; ms2.addSelection(&os2); Task* openViewTask = createOpenViewTask(ms2); if (openViewTask!=NULL) { openViewTask->setSubtaskProgressWeight(0); res.append(openViewTask); } } } else { //try load doc and open sequence view AppContext::getTaskScheduler()->registerTopLevelTask(new LoadUnloadedDocumentAndOpenViewTask(seqDoc)); } } if (!res.isEmpty()) { //one view is ok break; } } } foreach(Task* task, res) { addSubTask(task); } } ////////////////////////////////////////////////////////////////////////// LoadRemoteDocumentAndOpenViewTask::LoadRemoteDocumentAndOpenViewTask( const QString& accId, const QString& dbName ) : Task("LoadRemoteDocumentAndOpenView", TaskFlags_NR_FOSCOE | TaskFlag_MinimizeSubtaskErrorText), loadRemoteDocTask(NULL) { accNumber = accId; databaseName = dbName; } LoadRemoteDocumentAndOpenViewTask::LoadRemoteDocumentAndOpenViewTask( const GUrl& url ) : Task(tr("Load remote document and open view"), TaskFlags_NR_FOSCOE | TaskFlag_MinimizeSubtaskErrorText), loadRemoteDocTask(NULL) { docUrl = url; } LoadRemoteDocumentAndOpenViewTask::LoadRemoteDocumentAndOpenViewTask(const QString& accId, const QString& dbName, const QString & fp) : Task(tr("Load remote document and open view"), TaskFlags_NR_FOSCOE | TaskFlag_MinimizeSubtaskErrorText), loadRemoteDocTask(NULL) { accNumber = accId; databaseName = dbName; fullpath = fp; } void LoadRemoteDocumentAndOpenViewTask::prepare() { if (docUrl.isEmpty()) { loadRemoteDocTask = new LoadRemoteDocumentTask(accNumber, databaseName, fullpath); } else { loadRemoteDocTask = new LoadRemoteDocumentTask(docUrl); } addSubTask(loadRemoteDocTask); } QList LoadRemoteDocumentAndOpenViewTask::onSubTaskFinished( Task* subTask ) { QList subTasks; if (subTask->hasError()) { return subTasks; } if (subTask->isCanceled()) { return subTasks; } if (subTask == loadRemoteDocTask ) { // hack for handling errors with http requests with bad resource id Document * d = loadRemoteDocTask->getDocument(); if(d->getDocumentFormatId() == BaseDocumentFormats::PLAIN_TEXT) { setError(tr("Cannot find %1 in %2 database").arg(accNumber).arg(databaseName)); // try to delete file with response that was created QFile::remove(d->getURLString()); // and remove it from downloaded cache RecentlyDownloadedCache * cache = AppContext::getRecentlyDownloadedCache(); if( cache != NULL ) { cache->remove(d->getURLString()); } return subTasks; } QString fullPath = loadRemoteDocTask->getLocalUrl(); Project* proj = AppContext::getProject(); if (proj == NULL) { subTasks.append(AppContext::getProjectLoader()->openWithProjectTask(fullPath)); } else { Document* doc = loadRemoteDocTask->getDocument(); assert(doc != NULL); if ( proj->getDocuments().contains(doc) ) { if (doc->isLoaded()) { subTasks.append(new OpenViewTask(doc)); } else { subTasks.append(new LoadUnloadedDocumentAndOpenViewTask(doc)); } } else { // Add document to project DocumentFormat* format = doc->getDocumentFormat(); IOAdapterFactory * iof = AppContext::getIOAdapterRegistry()->getIOAdapterFactoryById(BaseIOAdapters::LOCAL_FILE); Document* clonedDoc = new Document(format, iof, fullPath); clonedDoc->loadFrom(doc); // doc was loaded in a separate thread -> clone all GObjects assert(!clonedDoc->isTreeItemModified()); assert(clonedDoc->isLoaded()); subTasks.append(new AddDocumentTask(clonedDoc)); subTasks.append(new LoadUnloadedDocumentAndOpenViewTask(clonedDoc)); } } } return subTasks; } AddDocumentAndOpenViewTask::AddDocumentAndOpenViewTask( Document* doc, const AddDocumentTaskConfig& conf) :Task(tr("Opening view for document: %1").arg(doc->getURL().fileName()), TaskFlags_NR_FOSCOE) { setMaxParallelSubtasks(1); addSubTask(new AddDocumentTask(doc, conf)); } AddDocumentAndOpenViewTask::AddDocumentAndOpenViewTask( DocumentProviderTask* dp, const AddDocumentTaskConfig& conf ) :Task(tr("Opening view for document: %1").arg(dp->getDocumentDescription()), TaskFlags_NR_FOSCOE) { setMaxParallelSubtasks(1); addSubTask(new AddDocumentTask(dp, conf)); } QList AddDocumentAndOpenViewTask::onSubTaskFinished(Task* t) { QList res; AddDocumentTask* addTask = qobject_cast(t); if (addTask != NULL && !addTask->getStateInfo().isCoR()) { Document* doc = addTask->getDocument(); assert(doc != NULL); res << new LoadUnloadedDocumentAndOpenViewTask(doc); } return res; } }//namespace ugene-1.9.8/src/corelibs/U2Gui/src/Notification.h0000644000175000017500000000630211651544333020232 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _TOOL_TIP_H_ #define _TOOL_TIP_H_ #include #include #include "MainWindow.h" #include "NotificationWidget.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include namespace U2 { #define MAX_NOTIFICATION 100 enum NotificationType { Info_Not, Error_Not, Report_Not }; class U2GUI_EXPORT Notification: public QLabel { Q_OBJECT public: Notification(const QString& message, NotificationType _type, QAction *_action = 0); ~Notification() {} void showNotification(int x, int y); QString getText() const; NotificationType getType() const; virtual bool eventFilter( QObject * watched, QEvent * event ); void increaseCounter(); private slots: void sl_timeout(); private: void dissapear(); void generateCSS(bool isHovered); void generateCSSforCloseButton(bool isHovered); signals: void si_dissapear(); void si_delete(); protected: bool event(QEvent *e); void mousePressEvent(QMouseEvent *ev); private: QAction *action; QLabel *close; QTimer timer; QString text; NotificationType type; int timeCounter; //counter for duplicate notifications int counter; }; class U2GUI_EXPORT NotificationStack: public QObject { Q_OBJECT public: NotificationStack(QObject *o = NULL); ~NotificationStack(); void addNotification(Notification *t); // a shortcut to addNotification for quick reporting errors void addError(const QString& errorMessage); int count() const; Notification *getNotification(int row) const; QList getItems() const; void showStack(); bool hasError() const; void setFixed(bool val); private slots: void sl_notificationDissapear(); void sl_delete(); signals: void si_changed(); private: NotificationWidget *w; QList notifications; QList notificationsOnScreen; int notificationPosition; int notificationNumber; }; } #endif ugene-1.9.8/src/corelibs/U2Gui/src/PluginViewer.h0000644000175000017500000000235111651544333020224 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_PLUGIN_VIEWER_H_ #define _U2_PLUGIN_VIEWER_H_ #include #include #include class QAction; namespace U2 { class U2GUI_EXPORT PluginViewer : public Service { Q_OBJECT public: PluginViewer(const QString& name, const QString& desc) : Service(Service_PluginViewer, name, desc) {} }; } //namespace #endif ugene-1.9.8/src/corelibs/U2Gui/src/ObjectViewModel.cpp0000644000175000017500000004223211651544333021163 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "ObjectViewModel.h" #include #include #include #include #include #include #include #include #include //BUG:535 refactor closing interface. //Idea: make it QObject and call 'deleteLater' on it namespace U2 { const QString GObjectViewState::APP_CLOSING_STATE_NAME("Auto saved"); const GObjectViewFactoryId GObjectViewFactory::SIMPLE_TEXT_FACTORY("SimpleTextView"); void GObjectViewState::setViewName(const QString& newName) { // this method is not a real state modification: state caches view name as a reference, but not its internal data // it is used only on view renaming viewName = newName; } void GObjectViewState::setStateName(const QString& newName) { if (newName == stateName) { return; } stateName = newName; emit si_stateModified(this); } void GObjectViewState::setStateData(const QVariantMap& data) { stateData = data; emit si_stateModified(this); } void GObjectViewFactoryRegistry::registerGObjectViewFactory(GObjectViewFactory* f) { mapping[f->getId()] = f; } void GObjectViewFactoryRegistry::unregisterGObjectViewFactory(GObjectViewFactory* f) { assert(GObjectViewUtils::findViewsByFactoryId(f->getId()).isEmpty()); mapping.remove(f->getId()); } GObjectViewFactory* GObjectViewFactoryRegistry::getFactoryById(GObjectViewFactoryId t) const { return mapping.value(t, NULL); } ////////////////////////////////////////////////////////////////////////// /// GObjectView GObjectView::GObjectView(GObjectViewFactoryId _factoryId, const QString& _viewName, QObject* prnt): QObject(prnt) { factoryId = _factoryId; viewName = _viewName; widget = NULL; closeInterface = NULL; closing = false; Project* p = AppContext::getProject(); assert(p!=NULL); connect(p, SIGNAL(si_documentAdded(Document*)), SLOT(sl_onDocumentAdded(Document*))); connect(p, SIGNAL(si_documentRemoved(Document*)), SLOT(sl_onDocumentRemoved(Document*))); foreach(Document* d, p->getDocuments()) { sl_onDocumentAdded(d); } } bool GObjectView::canAddObject(GObject* obj) { if (objects.contains(obj)) { return false; } foreach(GObjectViewObjectHandler* h, objectHandlers) { if (h->canHandle(this, obj)) { return true; } } return false; } QString GObjectView::addObject(GObject* o) { assert(!closing); if (objects.contains(o)) { return tr("Object is already added to view %1!").arg(o->getGObjectName()); } bool canBeAdded = canAddObject(o); if (!canBeAdded) { foreach(GObjectViewObjectHandler* h, objectHandlers) { canBeAdded = h->canHandle(this, o); if (canBeAdded) { break; } } } if (!canBeAdded) { return tr("Can't add object: %1").arg(o->getGObjectName()); } objects.push_back(o); onObjectAdded(o); emit si_objectAdded(this, o); return QString::null; } void GObjectView::_removeObject(GObject* o) { o->disconnect(this); int i = objects.removeAll(o); assert(i==1); Q_UNUSED(i); closing = onObjectRemoved(o) || closing; emit si_objectRemoved(this, o); if (requiredObjects.contains(o)) { closing = true; } } void GObjectView::removeObject(GObject* o) { assert(!closing); _removeObject(o); if (closing) { closeInterface->closeView(); } } void GObjectView::sl_onObjectRemovedFromDocument(GObject* o) { if (objects.contains(o)) { _removeObject(o); if (closing) { closeInterface->closeView(); } } } bool GObjectView::onObjectRemoved(GObject* obj) { foreach(GObjectViewObjectHandler* oh, objectHandlers) { oh->onObjectRemoved(this, obj); } return false; } void GObjectView::onObjectAdded(GObject* obj) { connect(obj, SIGNAL(si_nameChanged(const QString&)), SLOT(sl_onObjectNameChanged(const QString&))); foreach(GObjectViewObjectHandler* oh, objectHandlers) { oh->onObjectAdded(this, obj); } } void GObjectView::sl_onDocumentAdded(Document* d) { connect(d, SIGNAL(si_objectRemoved(GObject*)), SLOT(sl_onObjectRemovedFromDocument(GObject*))); connect(d, SIGNAL(si_loadedStateChanged()), SLOT(sl_onDocumentLoadedStateChanged())); } void GObjectView::sl_onDocumentRemoved(Document* d) { if (closing) { return; } d->disconnect(this); foreach(GObject* o, d->getObjects()) { if (objects.contains(o)) { _removeObject(o); } if (closing) { closeInterface->closeView(); break; } } } void GObjectView::sl_onObjectNameChanged(const QString& oldName) { Project* p = AppContext::getProject(); if (p == NULL) { return; } GObject* obj = qobject_cast(sender()); SAFE_POINT(obj != NULL, "Can't locate renamed object!",); onObjectRenamed(obj, oldName); } QWidget* GObjectView::getWidget() { if (widget == NULL) { assert(closeInterface!=NULL); widget = createWidget(); } return widget; } void GObjectView::setClosingInterface(GObjectViewCloseInterface* i) { closeInterface = i; } void GObjectView::buildStaticToolbar(QToolBar* tb) { emit si_buildStaticToolbar(this, tb); } void GObjectView::buildStaticMenu(QMenu* m) { emit si_buildStaticMenu(this, m); } // Returns true if view contains this object bool GObjectView::containsObject(GObject* obj) const { return objects.contains(obj); } // Returns true if view contains any objects from the document bool GObjectView::containsDocumentObjects(Document* doc) const { bool result = false; foreach(GObject* o, doc->getObjects()) { if (objects.contains(o)) { result = true; break; } } return result; } void GObjectView::setName(const QString& newName) { QString oldName = viewName; if (oldName == newName) { return; } viewName = newName; emit si_nameChanged(oldName); } ////////////////////////////////////////////////////////////////////////// /// GObjectViewWindow GObjectViewWindow::GObjectViewWindow(GObjectView* v, const QString& _viewName, bool _persistent) : MWMDIWindow(_viewName), view(v), persistent(_persistent) { v->setParent(this); v->setClosingInterface(this); QVBoxLayout *layout = new QVBoxLayout(); layout->setMargin(0); QWidget* viewWidget = v->getWidget(); viewWidget->setParent(this); layout->addWidget(viewWidget); setLayout(layout); setWindowIcon(viewWidget->windowIcon()); } void GObjectViewWindow::setPersistent(bool v) { if (persistent==v) { return; } persistent = v; emit si_persistentStateChanged(this); } void GObjectViewWindow::closeView() { AppContext::getMainWindow()->getMDIManager()->closeMDIWindow(this); } bool GObjectViewWindow::onCloseEvent() { view->saveWidgetState(); return true; } GObjectViewFactory* GObjectViewWindow::getViewFactory() const { GObjectViewFactory* f = AppContext::getObjectViewFactoryRegistry()->getFactoryById(view->getFactoryId()); assert(f); return f; } void GObjectViewWindow::setupMDIToolbar(QToolBar* tb) { view->buildStaticToolbar(tb); } void GObjectViewWindow::setupViewMenu(QMenu* m) { view->buildStaticMenu(m); } ////////////////////////////////////////////////////////////////////////// /// Utils GObjectViewWindow* GObjectViewUtils::findViewByName(const QString& name) { QList windows = AppContext::getMainWindow()->getMDIManager()->getWindows(); QList result; foreach(MWMDIWindow* w, windows) { if (w->windowTitle() == name) { GObjectViewWindow* v = qobject_cast(w); if (v!=NULL) { return v; } } } return NULL; } QString GObjectViewUtils::genUniqueViewName(const QString& name) { assert(!name.isEmpty()); QSet usedNames; //set of names is derived from acttive views & saved states QList windows = AppContext::getMainWindow()->getMDIManager()->getWindows(); foreach(MWMDIWindow* w, windows) { usedNames.insert(w->windowTitle()); } Project* p = AppContext::getProject(); if (p!=NULL) { foreach(const GObjectViewState* s, p->getGObjectViewStates()) { usedNames.insert(s->getViewName()); } } QString res = TextUtils::variate(name, " ", usedNames, false, 2); return res; } QString GObjectViewUtils::genUniqueStateName(const QString& stateName) { QSet existingNames; const QList states = AppContext::getProject()->getGObjectViewStates(); foreach(GObjectViewState* s, states) { existingNames.insert(s->getStateName()); } QString res = TextUtils::variate(stateName, " ", existingNames, false, 2); return res; } QString GObjectViewUtils::genUniqueViewName(const Document* doc, const GObject* obj) { QString objName = obj->getGObjectName(); QString viewName = doc->getURL().baseFileName() + " " + objName; return genUniqueViewName(viewName); } QList GObjectViewUtils::findStatesByViewName(const QString& viewName) { QList result; if (AppContext::getProject() != NULL) { const QList& states = AppContext::getProject()->getGObjectViewStates(); foreach(GObjectViewState* s, states) { if (s->getViewName() == viewName) { result.push_back(s); } } } return result; } GObjectViewState* GObjectViewUtils::findStateByName(const QString& viewName, const QString& stateName) { Project* p = AppContext::getProject(); assert(p); const QList& allStates = p->getGObjectViewStates(); return findStateInList(viewName, stateName, allStates); } GObjectViewState* GObjectViewUtils::findStateInList(const QString& viewName, const QString& stateName, const QList& states) { foreach(GObjectViewState* s , states) { if (s->getViewName() == viewName && s->getStateName() == stateName) { return s; } } return NULL; } QList GObjectViewUtils::getAllActiveViews() { QList windows = AppContext::getMainWindow()->getMDIManager()->getWindows(); QList result; foreach(MWMDIWindow* w, windows) { GObjectViewWindow* ov = qobject_cast(w); if (ov!=NULL) { result.append(ov); } } return result; } QList GObjectViewUtils::findViewsByFactoryId(GObjectViewFactoryId id) { QList result; MainWindow* mw = AppContext::getMainWindow(); if (mw == NULL || mw->getMDIManager() == NULL) { return result; //MW is closed } QList windows = mw->getMDIManager()->getWindows(); foreach(MWMDIWindow* w, windows) { GObjectViewWindow* ov = qobject_cast(w); if (ov!=NULL && ov->getViewFactoryId() == id) { result.push_back(ov); } } return result; } QList GObjectViewUtils::selectStates(const MultiGSelection& ms, const QList& states) { QList fs = AppContext::getObjectViewFactoryRegistry()->getAllFactories(); QList result; foreach(GObjectViewFactory* f, fs) { QList fResult = selectStates(f, ms, states); result+=fResult; } return result; } QList GObjectViewUtils::selectStates(GObjectViewFactory* f, const MultiGSelection& ms, const QList& states) { QList result; foreach (GObjectViewState* s, states) { if (s->getViewFactoryId() == f->getId()) { if (f->isStateInSelection(ms, s->getStateData())) { result.append(s); } } } return result; } QList GObjectViewUtils::findViewsWithObject(GObject* obj) { QList res; QList activeViews = getAllActiveViews(); foreach(GObjectViewWindow* vw, activeViews) { if (vw->getObjects().contains(obj)) { res.append(vw); } } return res; } QList GObjectViewUtils::findViewsWithAnyOfObjects(const QList& objs) { QList res; foreach(GObject* obj, objs) { QList tmp = findViewsWithObject(obj); res+=tmp; } return res; } GObjectViewWindow* GObjectViewUtils::getActiveObjectViewWindow() { MWMDIWindow* w = AppContext::getMainWindow()->getMDIManager()->getActiveWindow(); return qobject_cast(w); } ////////////////////////////////////////////////////////////////////////// // GObjectViewWindowContext GObjectViewWindowContext::GObjectViewWindowContext(QObject* p, const GObjectViewFactoryId& _id) : QObject(p) , id(_id), initialzed(false) {} void GObjectViewWindowContext::init() { initialzed = true; MWMDIManager* mdi = AppContext::getMainWindow()->getMDIManager(); connect(mdi, SIGNAL(si_windowAdded(MWMDIWindow*)), SLOT(sl_windowAdded(MWMDIWindow*))); connect(mdi, SIGNAL(si_windowClosing(MWMDIWindow*)), SLOT(sl_windowClosing(MWMDIWindow*))); foreach(MWMDIWindow* w, mdi->getWindows()) { sl_windowAdded(w); } } GObjectViewWindowContext::~GObjectViewWindowContext() { assert(initialzed); MWMDIManager* mdi = AppContext::getMainWindow()->getMDIManager(); if (mdi == NULL) { //TODO: disconnect context on view removal and assert (mdi!=NULL) here. return; } foreach(MWMDIWindow* w, mdi->getWindows()) { GObjectViewWindow* ow = qobject_cast(w); if (ow == NULL || (!id.isEmpty() && ow->getViewFactoryId() != id)) { continue; } GObjectView* v = ow->getObjectView(); disconnectView(v); } } void GObjectViewWindowContext::sl_windowAdded(MWMDIWindow* w) { GObjectViewWindow* ow = qobject_cast(w); if (ow == NULL || (!id.isEmpty() && ow->getViewFactoryId() != id)) { return; } GObjectView* v = ow->getObjectView(); assert(!viewResources.contains(v)); v->addObjectHandler(this); initViewContext(v); connect(v, SIGNAL(si_buildPopupMenu(GObjectView*, QMenu*)), SLOT(sl_buildContextMenu(GObjectView*, QMenu*))); connect(v, SIGNAL(si_buildStaticMenu(GObjectView*, QMenu*)), SLOT(sl_buildStaticMenu(GObjectView*, QMenu*))); } void GObjectViewWindowContext::sl_windowClosing(MWMDIWindow* w) { GObjectViewWindow* ow = qobject_cast(w); if (ow == NULL || (!id.isEmpty() && ow->getViewFactoryId() != id)) { return; } GObjectView* v = ow->getObjectView(); disconnectView(v); } void GObjectViewWindowContext::disconnectView(GObjectView* v) { QList resources = viewResources[v]; foreach(QObject* a, resources) { a->deleteLater(); // deliver close signals, save view states first } viewResources.remove(v); v->removeObjectHandler(this); } void GObjectViewWindowContext::addViewResource(GObjectView* v, QObject* r) { assert(v!=NULL && (!id.isEmpty() || v->getFactoryId() == id)); QList resources = viewResources[v]; assert(!resources.contains(r)); resources.append(r); viewResources[v] = resources; } QList GObjectViewWindowContext::getViewActions(GObjectView* v) const { QList actions; QList resources = viewResources[v]; foreach(QObject* obj, resources) { GObjectViewAction* a = qobject_cast(obj); if (a!=NULL) { actions.append(a); } } return actions; } ////////////////////////////////////////////////////////////////////////// // GObjectViewAction void GObjectViewAction::addToMenuWithOrder(QMenu* menu) { foreach(QAction* action, menu->actions()) { GObjectViewAction* viewAction = qobject_cast(action); if (viewAction != NULL && viewAction->getActionOrder() > actionOrder) { menu->insertAction(action, this); return; } } menu->addAction(this); } }//namespace ugene-1.9.8/src/corelibs/U2Gui/src/NotificationWidget.h0000644000175000017500000000414411651544333021400 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _NOTIFICATION_WIDGET_H #define _NOTIFICATION_WIDGET_H #include #include #include #include #include #include #include #include #include namespace U2 { #define TT_HEIGHT 50 #define TT_WIDTH 200 #define TS_HEIGHT 350 #define TS_WIDTH TT_WIDTH + 27 class Header: public QFrame { Q_OBJECT public: Header(QWidget *w = NULL); bool isFixed(); protected: void mousePressEvent(QMouseEvent *me) ; void mouseMoveEvent(QMouseEvent *me) ; bool eventFilter(QObject *, QEvent *); private: QLabel *close; QLabel *pin; bool fix; QPoint startPos; QPoint clickPos; QPoint offset; }; class NotificationWidget: public QFrame { Q_OBJECT public: NotificationWidget(QWidget *w = NULL); Header *titleBar() const; void addNotification(QWidget *w); bool removeNotification(QWidget *w); void setFixed(bool val); protected: bool event(QEvent *event); private: QScrollArea *scrlArea; QVBoxLayout *layout; QFrame *frame; Header *header; QPoint m_old_pos; bool m_mouse_down; bool left, right, bottom; bool isFixed; }; } //namespace #endif ugene-1.9.8/src/corelibs/U2Gui/src/ProjectParsing.cpp0000644000175000017500000003573611651544333021106 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "ProjectParsing.h" #include #include #include #include #include #include #include namespace U2 { static QString map2String(const QVariantMap& map) { QByteArray a; QVariant v(map); QDataStream s(&a, QIODevice::WriteOnly); s << v; QString res(a.toBase64()); return res; } static QVariantMap string2Map(const QString& string, bool emptyMapIfError) { Q_UNUSED(emptyMapIfError); QDataStream s(QByteArray::fromBase64(string.toAscii())); QVariant res(QVariant::Map); s >> res; if (res.type() == QVariant::Map) { return res.toMap(); } assert(emptyMapIfError); return QVariantMap(); } static QList toAbsoluteRelations(const QList& relList, const QDir& projDir) { QList absoluteRelations; foreach(GObjectRelation rel, relList){ if (GUrl::getURLType(rel.ref.docUrl) == GUrl_File) { //make URL absolute QFileInfo ff(rel.ref.docUrl); if(!ff.isAbsolute()){ QFileInfo tmpFi(projDir.path() + "/" + rel.ref.docUrl); rel.ref.docUrl = tmpFi.canonicalFilePath(); } } absoluteRelations.append(rel); } return absoluteRelations; } static QList hintToRelations(QVariant qv, const QDir& projDir) { if(!qv.isNull()) { return toAbsoluteRelations(qv.value >(), projDir); } else { return QList(); } } static QVariant relationsToHint(const QList &relList) { return QVariant::fromValue >(relList); } static QList removeDuplicates(const QList &relList) { return relList.toSet().toList(); } static QVariant toRelativeRelations(const QList& absRelations, const QDir& projDir, const QMap& urlRemap = QMap()) { QList relativeRelations; foreach (const GObjectRelation& absRel, absRelations) { GObjectRelation relRel = absRel; relRel.ref.docUrl = urlRemap.value(absRel.getDocURL(), absRel.getDocURL()); if (GUrl::getURLType(relRel.getDocURL()) == GUrl_File) { //make URL absolute #ifdef _DEBUG //ensure internal URLs are always canonical QFileInfo fi(relRel.getDocURL()); QString canonicalPath = fi.canonicalFilePath(); assert(canonicalPath.isEmpty() || canonicalPath == relRel.getDocURL()); #endif QString relativeURL = projDir.relativeFilePath(relRel.getDocURL()); relRel.ref.docUrl = relativeURL; } relativeRelations.append(relRel); } return QVariant::fromValue >(relativeRelations); } void ProjectFileUtils::saveProjectFile(TaskStateInfo& ts, Project* project, const QString& projectUrl, const QMap& docUrlRemap) { QDomDocument xmlDoc("GB2PROJECT"); QDomElement projectElement = xmlDoc.createElement("gb2project"); projectElement.setAttribute("name", project->getProjectName()); const QString ver(CURRENT_PROJECT_VERSION); projectElement.setAttribute("version", ver); projectElement.setAttribute("oid", project->getObjectIdCounter()); QFileInfo projectFile(projectUrl); QDir projectDir = projectFile.absoluteDir(); //save documents foreach(Document* gbDoc, project->getDocuments()) { gbDoc->getDocumentFormat()->updateFormatSettings(gbDoc); QString docUrl = gbDoc->getURLString(); if (docUrlRemap.contains(docUrl)) { docUrl = docUrlRemap.value(docUrl); } QString adapterId = gbDoc->getIOAdapterFactory()->getAdapterId(); QDomElement docElement = xmlDoc.createElement("document"); docElement.setAttribute("io-adapter", adapterId); //for local file save relative path if (adapterId == BaseIOAdapters::LOCAL_FILE || adapterId == BaseIOAdapters::GZIPPED_LOCAL_FILE) { QString relativeUrl = projectDir.relativeFilePath(docUrl); docElement.setAttribute("url", relativeUrl); } else { docElement.setAttribute("url", docUrl); } //store lock info for documents DocumentFormat* f = gbDoc->getDocumentFormat(); QString formatId = f->getFormatId(); docElement.setAttribute("format", formatId); docElement.setAttribute("readonly", gbDoc->hasUserModLock() ? 1 : 0); StateLock* l = gbDoc->getDocumentModLock(DocumentModLock_FORMAT_AS_INSTANCE); if (l!=NULL) { docElement.setAttribute("format-lock", 1); } //store doc-level hints if (!gbDoc->getGHintsMap().isEmpty()) { QString hintsStr = map2String(gbDoc->getGHintsMap()); QDomText hintsNode = xmlDoc.createCDATASection(hintsStr); docElement.appendChild(hintsNode); } //now save unloaded objects info for all document objects foreach(GObject* obj, gbDoc->getObjects()) { QDomElement objElement = xmlDoc.createElement("object"); UnloadedObjectInfo info(obj); objElement.setAttribute("name", info.name); objElement.setAttribute("type", info.type); if (!info.hints.isEmpty()) { //for all object relations make path relative info.hints[GObjectHint_RelatedObjects] = toRelativeRelations(obj->getObjectRelations(), projectDir, docUrlRemap); QString hintsStr = map2String(info.hints); QDomText hintsNode = xmlDoc.createCDATASection(hintsStr); objElement.appendChild(hintsNode); } docElement.appendChild(objElement); } projectElement.appendChild(docElement); } //save views states foreach(GObjectViewState* view, project->getGObjectViewStates()) { //save document info QDomElement viewElement = xmlDoc.createElement("view"); viewElement.setAttribute("factory", view->getViewFactoryId()); viewElement.setAttribute("viewName", view->getViewName()); viewElement.setAttribute("stateName", view->getStateName()); QString dataStr = map2String(view->getStateData()); QDomText textNode = xmlDoc.createCDATASection(dataStr); viewElement.appendChild(textNode); projectElement.appendChild(viewElement); } xmlDoc.appendChild(projectElement); QByteArray rawData = xmlDoc.toByteArray(); // printf(">>%s", xmlDoc.toString().toStdString().c_str()); //check that project directory exists if (!projectDir.exists()) { QDir root; root.mkpath(projectDir.absolutePath()); } //save project file text to file QFile f(projectUrl); if (f.open(QIODevice::WriteOnly | QIODevice::Truncate)) { qint64 s = f.write(rawData); f.close(); if (s!=rawData.size()) { ts.setError(L10N::errorWritingFile(projectUrl)); } } else { ts.setError(L10N::errorOpeningFileWrite(projectUrl)); } } void ProjectFileUtils::loadXMLProjectModel(const QString& url, TaskStateInfo& si, QDomDocument& doc, QString& version) { assert(doc.isNull()); QFile f(url); if (!f.open(QIODevice::ReadOnly)) { si.setError(L10N::errorOpeningFileRead(url)); return; } QByteArray xmlData = f.readAll(); f.close(); bool res = doc.setContent(xmlData); if (!res) { si.setError(L10N::notValidFileFormat("XML", url)); return; } const QString curVerStr(CURRENT_PROJECT_VERSION); QDomElement projectElement = doc.documentElement(); version = projectElement.attribute("version"); if(!version.isEmpty()){ bool ok; double projVer = version.toDouble(&ok), curVer = curVerStr.toDouble(); if (!ok) { si.setError(tr("Project version is not a double value")); doc.clear(); } if (projVer > curVer){ si.setError(tr("Project file was created by a newer version of UGENE. Please update UGENE.")); doc.clear(); } } if (!res || doc.doctype().name()!="GB2PROJECT") { si.setError( tr("Not a valid UGENE project file %1").arg(url) ); doc.clear(); } } ////////////////////////////////////////////////////////////////////////// void ProjectParserRegistry::init(){ parsers.qlist.append(new ProjectParser10()); } ProjectParser* ProjectParserRegistry::getProjectParserByVersion( const QString& id ){ foreach(ProjectParser *p, parsers.qlist){ if(p->getVersion() == id){ return p; } } return NULL; } ProjectParserRegistry * ProjectParserRegistry::instance(){ static ProjectParserRegistry ppr; return &ppr; } ////////////////////////////////////////////////////////////////////////// // Parser for v1.0 format Project* ProjectParser10::createProjectFromXMLModel( const QString& pURL, const QDomDocument& xmlDoc, TaskStateInfo& si ){ Q_UNUSED(si); //TODO: report about errors using si!!! QDomElement projectElement = xmlDoc.documentElement(); QString name = projectElement.attribute("name"); quint64 oid = qMax(quint64(0), projectElement.attribute("oid").toULongLong()); QList documents; QList states; //read all documents QSet docUrls; QDomNodeList documentList = projectElement.elementsByTagName("document"); for(int i=0; i < documentList.size(); i++) { QDomNode dn = documentList.item(i); if (!dn.isElement()) { continue; } QDomElement docElement = dn.toElement(); QString ioAdapterId = docElement.attribute("io-adapter"); QFileInfo proj(pURL); //QString docURL = proj.absoluteDir().path() + "/" + docElement.attribute("url"); QString fURL(docElement.attribute("url")); QFileInfo fi(docElement.attribute("url")); QString xmlDocUrl = docElement.attribute("url"); QString docUrl = xmlDocUrl; if ( ioAdapterId == BaseIOAdapters::GZIPPED_LOCAL_FILE || ioAdapterId == BaseIOAdapters::LOCAL_FILE ){ if(!fi.isAbsolute()) { QString tmp = proj.absoluteDir().path() + "/" + docElement.attribute("url"); QFileInfo ff(proj.absoluteDir().path() + "/" + docElement.attribute("url")); docUrl = ff.canonicalFilePath(); if (docUrl.isEmpty()) { docUrl = ff.absoluteFilePath(); } } else { docUrl = fi.canonicalFilePath(); if (docUrl.isEmpty()) { docUrl = fi.absoluteFilePath(); } } } if (docUrl.isEmpty()) { ioLog.info(tr("Can't find project file: %1, ignoring").arg(fi.absoluteFilePath())); continue; } if (docUrls.contains(docUrl)) { ioLog.info(tr("Duplicate document found: %1, ignoring").arg(docUrl)); continue; } docUrls.insert(docUrl); DocumentFormatId format = docElement.attribute("format"); bool readonly = docElement.attribute("readonly").toInt() != 0; bool instanceLock = docElement.attribute("format-lock").toInt() != 0; IOAdapterFactory* iof = AppContext::getIOAdapterRegistry()->getIOAdapterFactoryById(ioAdapterId); DocumentFormat* df = AppContext::getDocumentFormatRegistry()->getFormatById(format); if (df == NULL) { // this can happen when close ugene on startup continue; } QVariantMap fs = string2Map(docElement.text(), true); QList unloadedObjects; QDomNodeList objectList = docElement.elementsByTagName("object"); QSet objNames; for(int j=0; j < objectList.size(); j++) { QDomNode on = objectList.item(j); if (!on.isElement()) { continue; } QDomElement objElement = on.toElement(); UnloadedObjectInfo info; info.name = objElement.attribute("name"); info.type = objElement.attribute("type"); info.hints = string2Map(objElement.text(), true); if (!info.hints.isEmpty()) { // For backward compatibility: join relations from old and new hint key, avoid duplication QList relations; relations << hintToRelations(info.hints[GObjectHint_RelatedObjects], proj.absoluteDir()); relations << hintToRelations(info.hints[GObjectHint_RelatedObjectsLegacy], proj.absoluteDir()); relations = removeDuplicates(relations); if(! relations.empty()) { info.hints[GObjectHint_RelatedObjects] = relationsToHint(relations); } } if (info.isValid() && !objNames.contains(info.name)) { unloadedObjects.append(info); objNames.insert(info.name); } } Document* d = new Document(df, iof, docUrl, unloadedObjects, fs, instanceLock ? tr("The last loaded state was locked by format") : QString()); d->setUserModLock(readonly); documents.append(d); } // read all saved views QDomNodeList viewElements = projectElement.elementsByTagName("view"); for(int i=0;icreateProject(name, pURL, documents, states); project->setObjectIdCounter(oid); return project; } } //namespace ugene-1.9.8/src/corelibs/U2Gui/src/MainWindow.cpp0000644000175000017500000000215411651544333020214 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "MainWindow.h" namespace U2 { //thread safe design in main thread model static int windowCounter = 0; MWMDIWindow::MWMDIWindow(const QString& windowName) : windowId(++windowCounter) { setWindowTitle(windowName); setObjectName(windowName); } } //namespace ugene-1.9.8/src/corelibs/U2Gui/src/Notification.cpp0000644000175000017500000002372611651544333020576 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "Notification.h" namespace U2 { Notification::Notification(const QString &message, NotificationType _type, QAction *_action):QLabel(NULL), action(_action), text(message), type(_type) { setMinimumWidth(TT_WIDTH); setMaximumWidth(TT_WIDTH); setMaximumHeight(TT_HEIGHT); setFrameStyle(QFrame::StyledPanel); close = new QLabel(this); QBoxLayout *h = new QHBoxLayout(this); setLayout(h); counter = 1; QFontMetrics metrics(font()); setText(metrics.elidedText(message, Qt::ElideRight, width()-50)); setToolTip(message); generateCSS(false); generateCSSforCloseButton(false); //setWindowFlags (Qt::FramelessWindowHint); setWindowFlags (Qt::ToolTip); close->installEventFilter(this); h->addStretch(); h->addWidget(close); close->hide(); setMouseTracking(true); close->setAttribute(Qt::WA_Hover); close->setFixedSize(16,16); } void Notification::generateCSS(bool isHovered) { QString bgColor; QString img; QString fontColor; QString border; switch(type) { case Info_Not: bgColor = "background-color: #BDE5F8;"; fontColor = "color: #00529B;"; img = "background-image: url(':core/images/info_notification.png');" ; break; case Error_Not: bgColor = "background-color: #FFBABA;"; fontColor = "color: #D8000C;"; img = "background-image: url(':core/images/error_notification.png');" ; break; case Report_Not: bgColor = "background-color: #BDE5F8;"; fontColor = "color: #00529B;"; img = "background-image: url(':core/images/info_notification.png');" ; break; default: assert(0); } if(isHovered) { border = "border: 2px solid;"; } else { border = "border: 1px solid;"; } QString css; css.append(border); css.append("padding: 2px 2px 2px 20px;"); css.append("background-repeat: no-repeat;"); css.append("background-position: left center;"); css.append(fontColor); css.append(bgColor); css.append(img); setStyleSheet(css); } void Notification::generateCSSforCloseButton(bool isHovered) { QString css; QString background; if(isHovered) { css = "border: 1px solid;"; background = "background-color: #C0C0C0;"; } else { css = "border: none;"; background = "background-color: transparent;"; } css.append("border-radius: 3px;"); css.append("background-position: center center;"); css.append("paddling: 2px 2px 2px 2px;"); css.append(background); css.append("background-image: url(':core/images/close.png');"); close->setStyleSheet(css); } bool Notification::event(QEvent *e) { if(e->type() == QEvent::ToolTip) { QHelpEvent *hEvent = static_cast(e); QToolTip::showText(hEvent->globalPos(), QString(text)); return true; } if(e->type() == QEvent::HoverEnter) { generateCSS(true); } if(e->type() == QEvent::HoverLeave) { generateCSS(false); } return QWidget::event(e); } void Notification::mousePressEvent(QMouseEvent *ev) { if(ev->button() == Qt::LeftButton) { if(timer.isActive()) { dissapear(); } if(action) { action->trigger(); } else if(!timer.isActive()){ QDialog dlg(AppContext::getMainWindow()->getQMainWindow()); QVBoxLayout vLayout; QHBoxLayout hLayout; QPushButton ok; QCheckBox isDelete; ok.setText("Ok"); isDelete.setText(tr("Remove notification after closing")); isDelete.setChecked(true); connect(&ok, SIGNAL(clicked()), &dlg, SLOT(accept())); hLayout.addWidget(&isDelete); hLayout.addWidget(&ok); dlg.setLayout(&vLayout); QTextEdit txtEdit; txtEdit.setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); dlg.setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); txtEdit.setReadOnly(true); txtEdit.setText(text); vLayout.addWidget(&txtEdit); vLayout.addLayout(&hLayout); dlg.setWindowTitle(tr("Detailed message")); AppContext::getMainWindow()->getNotificationStack()->setFixed(true); if(dlg.exec() == QDialog::Accepted) { if(isDelete.isChecked()) { emit si_delete(); } } AppContext::getMainWindow()->getNotificationStack()->setFixed(false); } } } bool Notification::eventFilter(QObject *, QEvent *event) { if(event->type() == QEvent::MouseButtonPress) { QMouseEvent *e= static_cast(event); if(e->button() == Qt::LeftButton) { emit si_delete(); return true; } } else if(event->type() == QEvent::HoverEnter) { generateCSSforCloseButton(true); } else if(event->type() == QEvent::HoverLeave) { generateCSSforCloseButton(false); } return false; } void Notification::showNotification(int x, int y) { timeCounter = 0; timer.setInterval(20); connect(&timer, SIGNAL(timeout()), SLOT(sl_timeout())); timer.start(); show(); move(x,y); resize(TT_WIDTH, 0); } void Notification::dissapear() { setMinimumHeight(TT_HEIGHT); close->show(); setAttribute(Qt::WA_Hover); hide(); timer.stop(); emit si_dissapear(); } void Notification::sl_timeout() { QRect rect = geometry(); if(rect.height() >= TT_HEIGHT) { ++timeCounter; if(timeCounter > 100) { dissapear(); } } else { move(rect.topLeft().x(), rect.topLeft().y() - 10); resize(TT_WIDTH, rect.height() + 10); } } QString Notification::getText() const { return text; } NotificationType Notification::getType() const { return type; } void Notification::increaseCounter(){ counter++; QFontMetrics metrics(font()); QString addText = "(" + QString::number(counter) + ")"; int cWidth = metrics.width(addText); setText(metrics.elidedText(text, Qt::ElideRight, width()-50 - cWidth ) + addText); } NotificationStack::NotificationStack(QObject *o /* = NULL */): QObject(o), notificationPosition(0), notificationNumber(0) { w = new NotificationWidget(AppContext::getMainWindow()->getQMainWindow()); } NotificationStack::~NotificationStack() { foreach(Notification* t, notifications) { delete t; } delete w; } bool NotificationStack::hasError() const { foreach(Notification *n, notifications) { if(n->getType() == Error_Not) { return true; } } return false; } void NotificationStack::addNotification(Notification *t) { foreach(Notification *nt, notificationsOnScreen) { if(nt->getText().split("]")[1] == t->getText().split("]")[1]) { //there is always minimum one ']' symbol nt->increaseCounter(); delete t; return; } } if(notifications.count() >= MAX_NOTIFICATION) { Notification *toRemove = notifications.takeAt(0); if(!notificationsOnScreen.removeOne(toRemove)) { if(notificationsOnScreen.contains(toRemove)) { notificationsOnScreen.removeOne(toRemove); toRemove->deleteLater(); } } } notifications.append(t); notificationsOnScreen.append(t); emit si_changed(); connect(t, SIGNAL(si_delete()), this, SLOT(sl_delete()), Qt::DirectConnection); QPoint pos = AppContext::getMainWindow()->getQMainWindow()->geometry().bottomRight(); t->showNotification(pos.x() - TT_WIDTH, pos.y() - 50 - notificationPosition); notificationNumber++; notificationPosition += TT_HEIGHT; connect(t, SIGNAL(si_dissapear()), SLOT(sl_notificationDissapear())); } void NotificationStack::addError(const QString& errorMessage) { Notification *t = new Notification(errorMessage, Error_Not); addNotification(t); } void NotificationStack::sl_notificationDissapear() { notificationNumber--; if(notificationNumber == 0) { notificationPosition = 0; } Notification *t = qobject_cast(sender()); t->show(); t->setParent(w); w->addNotification(t); notificationsOnScreen.removeOne(t); } void NotificationStack::sl_delete() { Notification *t = qobject_cast(sender()); int i = notifications.indexOf(t); assert(i != -1); w->removeNotification(t); notifications.takeAt(i); emit si_changed(); //t->deleteLater(); } int NotificationStack::count() const { return notifications.count(); } Notification *NotificationStack::getNotification(int row) const { return notifications[row]; } QList NotificationStack::getItems() const { return notifications; } void NotificationStack::showStack() { QPoint pos = AppContext::getMainWindow()->getQMainWindow()->geometry().bottomRight(); w->move(pos.x() - w->width(), pos.y() - w->height()); w->show(); w->setWindowState(Qt::WindowActive); } void NotificationStack::setFixed(bool val) { w->setFixed(val); } } ugene-1.9.8/src/corelibs/U2Gui/src/ProjectView.h0000644000175000017500000000336111651544333020047 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_PROJECT_VIEW_H_ #define _U2_PROJECT_VIEW_H_ #include #include #include #include class QMenu; class QAction; namespace U2 { class DocumentSelection; class GObjectSelection; class U2GUI_EXPORT ProjectView : public Service { Q_OBJECT public: ProjectView(const QString& sname, const QString& sdesc) : Service(Service_ProjectView, sname, sdesc, QList()< * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_OBJECT_VIEW_TASKS_H_ #define _U2_OBJECT_VIEW_TASKS_H_ #include #include #include #include namespace U2 { class Document; class GObject; class Project; class U2GUI_EXPORT ObjectViewTask : public Task { Q_OBJECT public: enum Type { Type_Open, Type_Update }; ObjectViewTask(GObjectView* view, const QString& stateName, const QVariantMap& s = QVariantMap()); ObjectViewTask(GObjectViewFactoryId fid, const QString& viewName = QString(), const QVariantMap& s = QVariantMap()); virtual void prepare(); virtual ReportResult report(); virtual void open(){}; virtual void update(){}; virtual void onDocumentLoaded(Document* d){ Q_UNUSED(d); } static Document* createDocumentAndAddToProject(const QString& docUrl, Project* p); protected: Type taskType; QVariantMap stateData; QPointer view; QString viewName; bool stateIsIllegal; QStringList objectsNotFound; QStringList documentsNotFound; QList > documentsToLoad; QList > documentsFailedToLoad; QList > selectedObjects; }; class U2GUI_EXPORT AddToViewTask : public Task { Q_OBJECT public: AddToViewTask(GObjectView* v, GObject* obj); ReportResult report(); QPointer objView; QString viewName; GObjectReference objRef; QPointer objDoc; }; } // namespace #endif ugene-1.9.8/src/corelibs/U2Gui/src/ProjectParsing.h0000644000175000017500000000446711651544333020550 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_PROJECT_UTILS__H_ #define _U2_PROJECT_UTILS__H_ #include #include class QDomDocument; typedef QMap StrMap; namespace U2 { //TODO eliminate dependency on object views and move to private?? class U2GUI_EXPORT ProjectParser : public QObject { Q_OBJECT public: virtual Project* createProjectFromXMLModel(const QString& url, const QDomDocument& xmlDoc, TaskStateInfo& si) = 0; virtual QString getVersion(){assert(false); return QString();}; }; class U2GUI_EXPORT ProjectParserRegistry { public: ProjectParser* getProjectParserByVersion(const QString& id); static ProjectParserRegistry* instance(); private: ProjectParserRegistry(ProjectParserRegistry &ppr){Q_UNUSED(ppr); assert(0);}; ProjectParserRegistry(){init();}; void init(); GAutoDeleteList parsers; }; class ProjectParser10 : public ProjectParser { Q_OBJECT public: ProjectParser10(){}; Project* createProjectFromXMLModel(const QString& url, const QDomDocument& xmlDoc, TaskStateInfo& si); QString getVersion(){return QString("1.0");}; }; class U2GUI_EXPORT ProjectFileUtils : public QObject { Q_OBJECT public: static void saveProjectFile(TaskStateInfo& ts, Project* p, const QString& projectUrl, const StrMap& docUrlRemap = StrMap()); static void loadXMLProjectModel(const QString& url, TaskStateInfo& si, QDomDocument& doc, QString& version); }; } //namespace #endif ugene-1.9.8/src/corelibs/U2Gui/src/NotificationWidget.cpp0000644000175000017500000001240611651544333021733 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "NotificationWidget.h" namespace U2 { Header:: Header(QWidget *w):QFrame(w) { setAutoFillBackground(true); QPalette pal; pal.setBrush(backgroundRole(),QBrush(palette().highlight().color())); pal.setBrush(foregroundRole(), QBrush(Qt::white)); setPalette(pal); //setBackgroundRole(QPalette::Highlight); close= new QLabel(this); pin = new QLabel(this); QPixmap pix = QPixmap(":core/images/close_2.png"); close->setPixmap(pix); pix = QPixmap(":/core/images/pushpin_fixed.png"); pin->setPixmap(pix); pin->setMinimumHeight(12); close->setMinimumHeight(12); close->setToolTip(tr("close")); pin->setToolTip(tr("Always on top")); pin->installEventFilter(this); close->installEventFilter(this); QLabel *label = new QLabel(this); label->setText("Notifications"); w->setWindowTitle("Notifications"); QHBoxLayout *hbox = new QHBoxLayout(this); hbox->addWidget(label); hbox->addWidget(pin); hbox->addWidget(close); hbox->insertStretch(1, 500); hbox->setSpacing(0); setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed); fix = false; } bool Header::isFixed() { return fix; } bool Header::eventFilter(QObject *o, QEvent *e) { if(e->type() == QEvent::MouseButtonPress) { QMouseEvent *event = static_cast(e); if(event->button() == Qt::LeftButton) { if(o == close) { parentWidget()->close(); } else { fix = !fix; if(fix) { pin->setPixmap(QPixmap(":/core/images/pushpin.png")); parentWidget()->setWindowState(Qt::WindowActive); } else { pin->setPixmap(QPixmap(":/core/images/pushpin_fixed.png")); parentWidget()->setWindowState(Qt::WindowActive); } } } } return false; } void Header::mousePressEvent(QMouseEvent *me) { startPos = me->globalPos(); clickPos = mapToParent(me->pos()); offset = startPos - mapToGlobal(QPoint(0,0)); } void Header::mouseMoveEvent(QMouseEvent *me) { parentWidget()->move(me->globalPos() - offset); startPos = me->globalPos(); } NotificationWidget::NotificationWidget(QWidget *w): QFrame(w){ m_mouse_down = false; isFixed = false; setFrameShape(Panel); setWindowFlags(Qt::ToolTip); setMouseTracking(true); frame = new QFrame(); layout = new QVBoxLayout(); layout->addStretch(); layout->setMargin(3); frame->setLayout(layout); header = new Header(this); scrlArea = new QScrollArea(this); scrlArea->setWidget(frame); scrlArea->setWidgetResizable(true); scrlArea->installEventFilter(this); QVBoxLayout *vbox = new QVBoxLayout(); vbox->addWidget(header); vbox->setMargin(0); vbox->setSpacing(0); setLayout(vbox); QVBoxLayout *lbox = new QVBoxLayout(); lbox->addWidget(scrlArea); lbox->setMargin(0); lbox->setSpacing(0); vbox->addLayout(lbox); int newWidth = TT_WIDTH + layout->margin()*2 + 4; setFixedSize(newWidth, header->height() + 40); } Header *NotificationWidget::titleBar() const { return header; } void NotificationWidget::setFixed(bool val) { isFixed = val; } bool NotificationWidget::event(QEvent *event) { if(event->type() == QEvent::WindowDeactivate) { if(!header->isFixed() && !isFixed) { close(); } return false; } return QFrame::event(event); } void NotificationWidget::addNotification(QWidget *w) { int newWidth = width(); int newHeight = height() + TT_HEIGHT; if(height() + TT_HEIGHT >= TS_HEIGHT) { newWidth = TS_WIDTH; } if(newHeight >= TS_HEIGHT) { newHeight = TS_HEIGHT; } setFixedSize(newWidth, newHeight); layout->insertWidget(0, w); } bool NotificationWidget::removeNotification(QWidget *w) { if(layout->indexOf(w) == -1) { //Can't delete notification that isn't in stack return false; } layout->removeWidget(w); w->close(); delete w; int notificationCount = layout->count(); if(notificationCount * TT_HEIGHT + header->height() <= TS_HEIGHT) { int newWidth = TT_WIDTH + layout->margin()*2 + 4; setFixedSize(newWidth, notificationCount * (TT_HEIGHT + 6) + header->height()); } if(notificationCount == 1) { close(); } return true; } } ugene-1.9.8/src/corelibs/U2Gui/src/AppSettingsGUI.h0000644000175000017500000000604611651544333020417 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_APPSETTINGS_GUI_H_ #define _U2_APPSETTINGS_GUI_H_ #include #include namespace U2 { class AppSettingsGUIPageController; /** public class to access GUI */ class U2GUI_EXPORT AppSettingsGUI : public QObject { Q_OBJECT public: AppSettingsGUI(QObject* p = NULL) : QObject(p){}; virtual bool registerPage(AppSettingsGUIPageController* page, const QString& beforePage = QString()) = 0; virtual bool unregisterPage(AppSettingsGUIPageController* page) = 0; virtual void showSettingsDialog(const QString& pageId = QString()) const = 0; virtual QList getRegisteredPages() const = 0; }; /** Data stored on the page */ class U2GUI_EXPORT AppSettingsGUIPageState: public QObject { Q_OBJECT public: AppSettingsGUIPageState(QObject* p = NULL) : QObject(p) {} }; /** Page widget */ class U2GUI_EXPORT AppSettingsGUIPageWidget: public QWidget { Q_OBJECT public: AppSettingsGUIPageWidget(QWidget* w = NULL) : QWidget(w){} //reads data from 'state' and initializes the widget state virtual void setState(AppSettingsGUIPageState* state) = 0; //returns 'state' of the widget or error if state is not complete // the result structure is automatically deleted by controller virtual AppSettingsGUIPageState* getState(QString& errMsg) const = 0; }; /** Page factory/controller */ class U2GUI_EXPORT AppSettingsGUIPageController: public QObject { Q_OBJECT public: AppSettingsGUIPageController(const QString& s, const QString& _id, QObject* p = NULL) : QObject(p), name(s), id(_id) {} const QString& getPageName() const {return name;} const QString& getPageId() const {return id;} virtual AppSettingsGUIPageState* getSavedState() = 0; virtual void saveState(AppSettingsGUIPageState* s) = 0; //creates widget and initializes its values with 'data' content virtual AppSettingsGUIPageWidget* createWidget(AppSettingsGUIPageState* data) = 0; private: QString name; QString id; }; #define APP_SETTINGS_GUI_NETWORK "network" #define APP_SETTINGS_GUI_LOG "log" #define APP_SETTINGS_USER_APPS "user_apps" #define APP_SETTINGS_RESOURCES "resources" }//namespace #endif ugene-1.9.8/src/corelibs/U2Gui/src/util_gui/0000755000175000017500000000000011651544333017253 5ustar ilyailyaugene-1.9.8/src/corelibs/U2Gui/src/util_gui/BaseDocumentFormatConfigurators.cpp0000644000175000017500000000775011651544333026260 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "BaseDocumentFormatConfigurators.h" #include #include #include #include #include #include #include #include #include #include #include namespace U2 { void BaseDocumentFormatConfigurators::initBuiltInConfigurators() { AppContext::getDocumentFormatConfigurators()->registerConfigurator(new MultiPartDocFormatConfigurator(BaseDocumentFormats::PLAIN_FASTA)); AppContext::getDocumentFormatConfigurators()->registerConfigurator(new MultiPartDocFormatConfigurator(BaseDocumentFormats::PLAIN_GENBANK)); AppContext::getDocumentFormatConfigurators()->registerConfigurator(new MultiPartDocFormatConfigurator(BaseDocumentFormats::PLAIN_EMBL)); AppContext::getDocumentFormatConfigurators()->registerConfigurator(new MultiPartDocFormatConfigurator(BaseDocumentFormats::FASTQ)); } #define SETTINGS_ROOT "format_settings/" void BaseDocumentFormatConfigurators::loadDefaultFormatSettings(const DocumentFormatId& format, QVariantMap& formatSettings) { QVariant v = AppContext::getSettings()->getValue(SETTINGS_ROOT + format); if (v.type() != QVariant::Map) { return; } formatSettings = v.toMap(); } void BaseDocumentFormatConfigurators::saveDefaultFormatSettings(const DocumentFormatId& format, const QVariantMap& formatSettings) { AppContext::getSettings()->setValue(SETTINGS_ROOT + format, formatSettings); } void MultiPartDocFormatConfigurator::configure(QVariantMap& info) { DocumentFormat* f = AppContext::getDocumentFormatRegistry()->getFormatById(formatId); // create GUI QDialog configDialog; Ui_FormatSettingsDialog dModel; configDialog.setWindowIcon(QIcon(":/ugene/images/ugene_16.png")); dModel.setupUi(&configDialog); Ui_MultipartDocFormatConfiguratorWidget wModel; QGroupBox * w = new QGroupBox(); w->setTitle(tr("%1 format settings").arg(f->getFormatName())); wModel.setupUi(w); dModel.verticalLayout->insertWidget(0, w); // fill GUI with default settings BaseDocumentFormatConfigurators::loadDefaultFormatSettings(formatId, info); int mergeGap = -1; QString mergeToken = DocumentReadingMode_SequenceMergeGapSize; QVariant v = info.value(mergeToken); if (v.isValid()) { mergeGap = v.toInt(); } if (mergeGap == -1) { wModel.separateRB->setChecked(true); } else { wModel.mergeRB->setChecked(true); wModel.gapSpin->setValue(mergeGap); } //execute dialog int r = configDialog.exec(); if (r != QDialog::Accepted) { return; } //save settings to model if (wModel.separateRB->isChecked()) { info.clear(); } else { info[mergeToken] = wModel.gapSpin->value(); } //save settings to user-settings if needed if (dModel.saveCB->isChecked()) { BaseDocumentFormatConfigurators::saveDefaultFormatSettings(formatId, info); } } } //namespace ugene-1.9.8/src/corelibs/U2Gui/src/util_gui/CopyDocumentDialogController.cpp0000644000175000017500000000513111651544333025554 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "CopyDocumentDialogController.h" #include "SaveDocumentGroupController.h" #include "ui/ui_CopyDocumentDialog.h" #include "U2Misc/DialogUtils.h" #include #include #include #include #include #include #include namespace U2{ CopyDocumentDialogController::CopyDocumentDialogController(Document* d, QWidget *p) : QDialog(p) { ui = new Ui_CopyDocumentDialog(); ui->setupUi(this); SaveDocumentGroupControllerConfig conf; foreach (GObject* obj, d->getObjects()) { conf.dfc.supportedObjectTypes+=obj->getGObjectType(); } conf.dfc.addFlagToSupport(DocumentFormatFlag_SupportWriting); conf.fileDialogButton = ui->browseButton; conf.fileNameEdit = ui->fileNameEdit; conf.formatCombo = ui->formatCombo; conf.parentWidget = this; saveController = new SaveDocumentGroupController(conf, this); QString fileName = GUrlUtils::rollFileName(d->getURLString(), "_copy", DocumentUtils::getNewDocFileNameExcludesHint()); ui->fileNameEdit->setText(fileName); } QString CopyDocumentDialogController::getDocumentURL() const { QString path = saveController->getSaveFileName(); if(ui->compressCheck->isChecked()) { QString suffix = path.split(".").last(); if(suffix != "gz") { return path + ".gz"; } } return path; } DocumentFormatId CopyDocumentDialogController::getDocumentFormatId() const { return saveController->getFormatIdToSave(); } CopyDocumentDialogController::~CopyDocumentDialogController() { delete ui; } bool CopyDocumentDialogController::getAddToProjectFlag() const { return ui->addToProjCheck->isChecked(); } }//namespace ugene-1.9.8/src/corelibs/U2Gui/src/util_gui/ProjectTreeController.cpp0000644000175000017500000014103611651544333024256 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "ProjectTreeController.h" #include "UnloadDocumentTask.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include /* TRANSLATOR U2::ProjectTreeController */ namespace U2 { class TreeUpdateHelper { public: TreeUpdateHelper(QSet& _itemsToUpdate) :itemsToUpdate(_itemsToUpdate) { assert(itemsToUpdate.isEmpty());} virtual ~TreeUpdateHelper() { foreach(ProjViewItem* i, itemsToUpdate) { i->updateVisual(); } itemsToUpdate.clear(); } QSet& itemsToUpdate; }; bool PTCObjectRelationFilter::filter(GObject* o) const { return !o->hasObjectRelation(rel); } ProjectTreeController::ProjectTreeController(QObject* parent, QTreeWidget* _tree, const ProjectTreeControllerModeSettings& m) : QObject(parent), mode(m) { markActiveView = NULL; setObjectName("ProjectTreeController"); tree = _tree; tree->setSelectionMode(mode.allowMultipleSelection ? QAbstractItemView::ExtendedSelection : QAbstractItemView::SingleSelection); tree->headerItem()->setHidden(true); tree->setContextMenuPolicy(Qt::CustomContextMenu); connect(tree->itemDelegate(), SIGNAL(closeEditor(QWidget*,QAbstractItemDelegate::EndEditHint)), SLOT(sl_onCloseEditor(QWidget*,QAbstractItemDelegate::EndEditHint))); documentIcon.addFile(":/core/images/document.png"); roDocumentIcon.addFile(":/core/images/ro_document.png"); removeSelectedDocumentsAction = new QAction(QIcon(":core/images/remove_selected_documents.png"), tr("Remove selected documents"), this); removeSelectedDocumentsAction->setShortcut(QKeySequence::Delete); removeSelectedDocumentsAction->setShortcutContext(Qt::WidgetWithChildrenShortcut); tree->addAction(removeSelectedDocumentsAction); connect(removeSelectedDocumentsAction, SIGNAL(triggered()), SLOT(sl_onRemoveSelectedDocuments())); loadSelectedDocumentsAction = new QAction(QIcon(":core/images/load_selected_documents.png"), tr("Load selected documents"), this); loadSelectedDocumentsAction->setShortcuts(QList() << Qt::Key_Enter << Qt::Key_Return); loadSelectedDocumentsAction->setShortcutContext(Qt::WidgetWithChildrenShortcut); tree->addAction(loadSelectedDocumentsAction); connect(loadSelectedDocumentsAction, SIGNAL(triggered()), SLOT(sl_onLoadSelectedDocuments())); addReadonlyFlagAction = new QAction(tr("Lock document for editing"), this); connect(addReadonlyFlagAction, SIGNAL(triggered()), SLOT(sl_onToggleReadonly())); removeReadonlyFlagAction = new QAction(tr("Unlock document for editing"), this); connect(removeReadonlyFlagAction, SIGNAL(triggered()), SLOT(sl_onToggleReadonly())); unloadSelectedDocumentsAction = new QAction(QIcon(":core/images/unload_document.png"), tr("Unload selected document"), this); connect(unloadSelectedDocumentsAction, SIGNAL(triggered()), SLOT(sl_onUnloadSelectedDocuments())); renameAction = new QAction(tr("Rename..."), this); connect(renameAction, SIGNAL(triggered()), SLOT(sl_onRename())); groupByDocumentAction = new QAction(tr("Group by document"), this); groupByDocumentAction->setObjectName("Group_by_document_action"); groupByDocumentAction->setCheckable(true); groupByDocumentAction->setChecked(mode.groupMode == ProjectTreeGroupMode_ByDocument); connect(groupByDocumentAction, SIGNAL(triggered()), SLOT(sl_onGroupByDocument())); groupByTypeAction = new QAction(tr("Group by type"), this); groupByTypeAction->setObjectName("Group_by_type_action"); groupByTypeAction->setCheckable(true); groupByTypeAction->setChecked(mode.groupMode == ProjectTreeGroupMode_ByType); connect(groupByTypeAction, SIGNAL(triggered()), SLOT(sl_onGroupByType())); groupFlatAction = new QAction(tr("No groups"), this); groupFlatAction->setObjectName("No_groups_action"); groupFlatAction->setCheckable(true); groupFlatAction->setChecked(mode.groupMode == ProjectTreeGroupMode_Flat); connect(groupFlatAction, SIGNAL(triggered()), SLOT(sl_onGroupFlat())); QActionGroup* ag = new QActionGroup(this); ag->addAction(groupByDocumentAction); ag->addAction(groupByTypeAction); ag->addAction(groupFlatAction); connect(tree, SIGNAL(itemSelectionChanged()), SLOT(sl_onTreeSelectionChanged())); connect(tree, SIGNAL(customContextMenuRequested(const QPoint &)), SLOT(sl_onContextMenuRequested(const QPoint &))); connect(tree, SIGNAL(itemDoubleClicked(QTreeWidgetItem*, int)), SLOT(sl_onItemDoubleClicked(QTreeWidgetItem*, int ))); tree->installEventFilter(this); Project* pr = AppContext::getProject(); connect(pr, SIGNAL(si_documentAdded(Document*)), SLOT(sl_onDocumentAddedToProject(Document*))); connect(pr, SIGNAL(si_documentRemoved(Document*)), SLOT(sl_onDocumentRemovedFromProject(Document*))); MWMDIManager* mdi = AppContext::getMainWindow()->getMDIManager(); connect(mdi, SIGNAL(si_windowActivated(MWMDIWindow*)), SLOT(sl_windowActivated(MWMDIWindow*))); connectModel(); updateSettings(mode); connectToResourceTracker(); // if any window is active - check it content sl_windowActivated(mdi->getActiveWindow()); } void ProjectTreeController::connectToResourceTracker() { connect(AppContext::getResourceTracker(), SIGNAL(si_resourceUserRegistered(const QString&, Task*)), SLOT(sl_onResourceUserRegistered(const QString&, Task*))); connect(AppContext::getResourceTracker(), SIGNAL(si_resourceUserUnregistered(const QString&, Task*)), SLOT(sl_onResourceUserUnregistered(const QString&, Task*))); foreach(Document* d, AppContext::getProject()->getDocuments()) { const QString resName = LoadUnloadedDocumentTask::getResourceName(d); QList users = AppContext::getResourceTracker()->getResourceUsers(resName); foreach(Task* t, users) { sl_onResourceUserRegistered(resName, t); } } } void ProjectTreeController::connectModel() { Project* p = AppContext::getProject(); const QList& docs = p->getDocuments(); foreach(Document* d, docs) { connectDocument(d); } } void ProjectTreeController::connectDocument(Document* d) { connect(d, SIGNAL(si_modifiedStateChanged()), SLOT(sl_onDocumentModifiedStateChanged())); connect(d, SIGNAL(si_loadedStateChanged()), SLOT(sl_onDocumentLoadedStateChanged())); connect(d, SIGNAL(si_objectAdded(GObject*)), SLOT(sl_onObjectAdded(GObject*))); connect(d, SIGNAL(si_objectRemoved(GObject*)), SLOT(sl_onObjectRemoved(GObject*))); connect(d, SIGNAL(si_lockedStateChanged()), SLOT(sl_onLockedStateChanged())); connect(d, SIGNAL(si_urlChanged()), SLOT(sl_onDocumentURLorNameChanged())); connect(d, SIGNAL(si_nameChanged()), SLOT(sl_onDocumentURLorNameChanged())); const QList& objects = d->getObjects(); foreach(GObject* o, objects) { connectGObject(o); } } void ProjectTreeController::disconnectDocument(Document* d) { d->disconnect(this); const QList& objects = d->getObjects(); foreach(GObject* o, objects) { o->disconnect(this); } Task* t = LoadUnloadedDocumentTask::findActiveLoadingTask(d); if (t) { t->disconnect(this); t->cancel(); } } void ProjectTreeController::connectGObject(GObject* o) { connect(o, SIGNAL(si_modifiedStateChanged()), SLOT(sl_onObjectModifiedStateChanged())); connect(o, SIGNAL(si_nameChanged(const QString&)), SLOT(sl_onObjectNameChanged(const QString&))); } void ProjectTreeController::buildTree() { const QList& docs = AppContext::getProject()->getDocuments(); foreach(Document* d, docs) { buildDocumentTree(d); } } GObjectType ProjectTreeController::getLoadedObjectType(GObject* obj) const { GObjectType t = obj->getGObjectType(); if (t == GObjectTypes::UNLOADED) { UnloadedObject* uo = qobject_cast(obj); t = uo->getLoadedObjectType(); if (t == GObjectTypes::UNLOADED) { coreLog.details(tr("Unloaded object refers to unloaded type: %1").arg(obj->getGObjectName())); t = GObjectTypes::UNKNOWN; } } return t; } // if objects number in document < MAX_OBJECTS_TO_AUTOEXPAND - document content will be automatically expanded on loading #define MAX_OBJECTS_TO_AUTOEXPAND 20 // if documents number in project < MAX_DOCUMENTS_TO_AUTOEXPAND - document content will be automatically expanded on loading #define MAX_DOCUMENTS_TO_AUTOEXPAND 20 void ProjectTreeController::buildDocumentTree(Document* d) { TreeUpdateHelper h(itemsToUpdate); ProjViewItem* topItem = NULL; bool docIsShown = mode.isDocumentShown(d); if (docIsShown) { topItem = findDocumentItem(d, true); } const QList& objs = d->getObjects(); foreach(GObject* obj, objs) { assert(obj->getDocument() == d); if (mode.isObjectShown(obj)) { if (mode.groupMode == ProjectTreeGroupMode_ByType) { topItem = findTypeItem(getLoadedObjectType(obj), true); } ProjViewObjectItem* oItem = findGObjectItem(topItem, obj); if (oItem == NULL) { oItem = new ProjViewObjectItem(obj, this); if (mode.groupMode != ProjectTreeGroupMode_ByDocument || topItem == NULL) { insertTreeItemSorted(topItem, oItem); } else { //keep natural mode, as in file topItem->addChild(oItem); } if (topItem!=NULL) { itemsToUpdate.insert(topItem); } } } } if (topItem!=NULL && topItem->childCount() > 0) { insertTreeItemSorted(NULL, topItem); if (docIsShown && d->isLoaded() && topItem->childCount() < MAX_OBJECTS_TO_AUTOEXPAND) { //avoid system slowdown without user interaction -> do not auto expand docs with huge number of objects topItem->setExpanded(true); } } } ProjViewTypeItem* ProjectTreeController::findTypeItem(const GObjectType& t) const { assert(t!=GObjectTypes::UNLOADED); for (int i=0;itopLevelItemCount(); i++) { ProjViewItem* item = static_cast(tree->topLevelItem(i)); if (!item->isTypeItem()) { continue; } ProjViewTypeItem* typeItem = static_cast(item); if (typeItem->otype == t) { return typeItem; } } return NULL; } ProjViewTypeItem* ProjectTreeController::findTypeItem(const GObjectType& t, bool create) { ProjViewTypeItem *res = findTypeItem(t); if (res == NULL && create) { res = new ProjViewTypeItem(t, this); tree->addTopLevelItem(res); } return res; } ProjViewDocumentItem* ProjectTreeController::findDocumentItem(Document* doc) const { for (int i=0;itopLevelItemCount(); i++) { ProjViewItem* item = static_cast(tree->topLevelItem(i)); if (!item->isDocumentItem()) { continue; } ProjViewDocumentItem* docItem = static_cast(item); if (docItem->doc == doc) { return docItem; } } return NULL; } ProjViewDocumentItem* ProjectTreeController::findDocumentItem(Document* doc, bool create){ ProjViewDocumentItem* res = findDocumentItem(doc); if (res == NULL && create) { res = new ProjViewDocumentItem(doc, this); tree->addTopLevelItem(res); } return res; } ProjViewObjectItem* ProjectTreeController::findGObjectItem(GObject* obj) const { return findGObjectItem(obj->getDocument(), obj); } ProjViewObjectItem* ProjectTreeController::findGObjectItem(Document* doc, GObject* obj) const { assert(doc == obj->getDocument() || obj->getDocument() == NULL); assert(doc != NULL); ProjViewItem* topItem = NULL; if (mode.groupMode == ProjectTreeGroupMode_ByDocument) { topItem = findDocumentItem(doc); } else if (mode.groupMode == ProjectTreeGroupMode_ByType) { topItem = findTypeItem(getLoadedObjectType(obj)); } return findGObjectItem(topItem, obj); } ProjViewObjectItem* ProjectTreeController::findGObjectItem(ProjViewItem* topItem, GObject* obj) const { if (topItem!=NULL) { for (int i = 0 ; i < topItem->childCount(); i++) { ProjViewObjectItem* item = static_cast(topItem->child(i)); if (item->obj == obj) { return item; } } } else { for (int i=0; i < tree->topLevelItemCount(); i++) { ProjViewItem* item = static_cast(tree->topLevelItem(i)); if (!item->isObjectItem()) { continue; } ProjViewObjectItem* objItem = static_cast(item); if (objItem->obj == obj) { return objItem; } } } return NULL; } void ProjectTreeController::sl_onTreeSelectionChanged() { updateSelection(); updateActions(); } bool ProjectTreeController::eventFilter(QObject* o, QEvent* e) { if (e->type() == QEvent::KeyPress) { QKeyEvent *kEvent = (QKeyEvent*)e; int key = kEvent->key(); bool hasSelection = !((QTreeWidget *)o)->selectedItems().isEmpty(); if (key == Qt::Key_F2 && hasSelection) { sl_onRename(); return true; } else if ( (key == Qt::Key_Return || key == Qt::Key_Enter) && hasSelection) { ProjViewItem *item = static_cast(((QTreeWidget *)o)->selectedItems().last()); if (item->isObjectItem() && !item->flags().testFlag(Qt::ItemIsEditable)) { ProjViewObjectItem *objItem = static_cast(item); emit si_returnPressed(objItem->obj); } } } return false; } void ProjectTreeController::sl_onCloseEditor(QWidget*,QAbstractItemDelegate::EndEditHint) { QTreeWidgetItem* item = tree->currentItem(); SAFE_POINT(item != NULL, "Unexpected current item on edit!",); ProjViewItem* pvi = static_cast(item); SAFE_POINT(pvi->isObjectItem(), "Not an object type item on edit!",); ProjViewObjectItem* objItem = static_cast(pvi); if (!AppContext::getProject()->isStateLocked()) { QString newName = item->text(0); coreLog.trace(QString("Renaming object %1 to %2").arg(objItem->obj->getGObjectName()).arg(newName)); objItem->obj->setGObjectName(newName); } objItem->setFlags(objItem->flags() & ~Qt::ItemIsEditable); objItem->updateVisual(); } void ProjectTreeController::updateSelection() { QList items = tree->selectedItems(); if (items.isEmpty()) { objectSelection.clear(); documentSelection.clear(); return; } QList selectedDocs; QList selectedObjs; foreach(QTreeWidgetItem* item , items) { ProjViewItem* pvi = static_cast(item); if (pvi->isDocumentItem()) { ProjViewDocumentItem* di = static_cast(pvi); selectedDocs.push_back(di->doc); } else if (pvi->isObjectItem()) { ProjViewObjectItem* oi = static_cast(pvi); selectedObjs.push_back(oi->obj); } } objectSelection.setSelection(selectedObjs); documentSelection.setSelection(selectedDocs); } void ProjectTreeController::sl_onItemDoubleClicked(QTreeWidgetItem * item, int) { ProjViewItem* pvi = static_cast(item); if (pvi->isObjectItem()) { emit si_doubleClicked((static_cast(pvi))->obj); } else if (pvi->isDocumentItem()) { Document* d = (static_cast(pvi))->doc; if (!d->isLoaded() && pvi->childCount() == 0) { //children > 0 -> expand action assert(loadSelectedDocumentsAction->isEnabled()); loadSelectedDocumentsAction->trigger(); } } else { assert(pvi->isTypeItem()); } } void ProjectTreeController::sl_onContextMenuRequested(const QPoint&) { QMenu m; if (loadSelectedDocumentsAction->isEnabled()) { m.addAction(loadSelectedDocumentsAction); } if (unloadSelectedDocumentsAction->isEnabled()) { m.addAction(unloadSelectedDocumentsAction); } if (addReadonlyFlagAction->isEnabled()) { m.addAction(addReadonlyFlagAction); } if (removeReadonlyFlagAction->isEnabled()) { m.addAction(removeReadonlyFlagAction); } ProjectView* pv = AppContext::getProjectView(); if (pv != NULL) { QAction* addExistingDocumentAction = new QAction(pv->getAddExistingDocumentAction()->icon(), tr("Existing document"), &m); connect(addExistingDocumentAction, SIGNAL(triggered()), pv->getAddExistingDocumentAction(), SLOT(trigger())); QMenu* addMenu = m.addMenu(tr("Add")); addMenu->menuAction()->setObjectName( ACTION_PROJECT__ADD_MENU); addMenu->addAction(addExistingDocumentAction); QMenu* editMenu = m.addMenu(tr("Edit")); editMenu->menuAction()->setObjectName( ACTION_PROJECT__EDIT_MENU); editMenu->addAction(renameAction); } QMenu* removeMenu = m.addMenu(tr("Remove")); removeMenu->addAction(removeSelectedDocumentsAction); removeMenu->setEnabled(removeSelectedDocumentsAction->isEnabled()); emit si_onPopupMenuRequested(m); m.setObjectName("popMenu"); m.exec(QCursor::pos()); } QSet ProjectTreeController::getDocsInSelection(bool deriveFromObjects) { QSet docsInSelection = documentSelection.getSelectedDocuments().toSet(); if (deriveFromObjects) { foreach(GObject* o, objectSelection.getSelectedObjects()) { Document* doc = o->getDocument(); assert(doc!=NULL); docsInSelection.insert(doc); } } return docsInSelection; } void ProjectTreeController::updateActions() { bool hasUnloadedDocumentInSelection = false; bool hasLoadedDocumentInSelection = false; QSet docsItemsInSelection = getDocsInSelection(false); QSet docsInSelection = getDocsInSelection(true);//mode.groupMode != ProjectTreeGroupMode_ByDocument); foreach(Document* d, docsInSelection) { if (!d->isLoaded()) { hasUnloadedDocumentInSelection = true; break; } else { hasLoadedDocumentInSelection = true; } } removeSelectedDocumentsAction->setEnabled(!docsItemsInSelection.isEmpty()); loadSelectedDocumentsAction->setEnabled(hasUnloadedDocumentInSelection); unloadSelectedDocumentsAction->setEnabled(hasLoadedDocumentInSelection); addReadonlyFlagAction->setEnabled(docsInSelection.size() == 1 && !docsInSelection.toList().first()->hasUserModLock() && !docsInSelection.toList().first()->isStateLocked()); removeReadonlyFlagAction->setEnabled(docsInSelection.size() == 1 && docsInSelection.toList().first()->isLoaded() && docsInSelection.toList().first()->hasUserModLock()); if (!docsItemsInSelection.isEmpty()) { loadSelectedDocumentsAction->setText(tr("Load selected documents")); unloadSelectedDocumentsAction->setText(tr("Unload selected documents")); } else { loadSelectedDocumentsAction->setText(tr("Load selected objects")); unloadSelectedDocumentsAction->setText(tr("Unload selected objects")); } QList selItems = tree->selectedItems(); bool renameIsOk = false; if (selItems.size() == 1) { ProjViewItem *item = static_cast(selItems.last()); if (item != NULL && item->isObjectItem() && !AppContext::getProject()->isStateLocked()) { renameIsOk = true; } } renameAction->setEnabled(renameIsOk); } void ProjectTreeController::sl_onRemoveSelectedDocuments() { Project* p = AppContext::getProject(); QSet docsInSelection = getDocsInSelection(mode.groupMode != ProjectTreeGroupMode_ByDocument); if (!docsInSelection.isEmpty()) { AppContext::getTaskScheduler()->registerTopLevelTask(new RemoveMultipleDocumentsTask(p, docsInSelection.toList(), true, true)); } } void ProjectTreeController::sl_onLoadSelectedDocuments() { QSet docsInSelection = getDocsInSelection(true);//mode.groupMode != ProjectTreeGroupMode_ByDocument); QList docsToLoad; foreach(Document* d, docsInSelection) { if (!d->isLoaded() && LoadUnloadedDocumentTask::findActiveLoadingTask(d)==NULL) { docsToLoad.append(d); } } runLoadDocumentTasks(docsToLoad); } void ProjectTreeController::sl_onUnloadSelectedDocuments() { QList docsToUnload; QSet docsInSelection = getDocsInSelection(true);//mode.groupMode != ProjectTreeGroupMode_ByDocument); foreach(Document* doc, docsInSelection) { if (doc->isLoaded()) { docsToUnload.append(doc); } } UnloadDocumentTask::runUnloadTaskHelper(docsToUnload, UnloadDocumentTask_SaveMode_Ask); } void ProjectTreeController::runLoadDocumentTasks(const QList& docs) { QList tasks; if (mode.loadTaskProvider!=NULL) { tasks = mode.loadTaskProvider->createLoadDocumentTasks(docs); } else { foreach(Document* d, docs) { tasks << new LoadUnloadedDocumentTask(d); } } foreach(Task* t, tasks) { AppContext::getTaskScheduler()->registerTopLevelTask(t); } } void ProjectTreeController::sl_onDocumentAddedToProject(Document* d) { //todo: sort? buildDocumentTree(d); connectDocument(d); updateActions(); } void ProjectTreeController::sl_onDocumentRemovedFromProject(Document* d) { disconnectDocument(d); disconnect(tree, SIGNAL(itemSelectionChanged()), this, SLOT(sl_onTreeSelectionChanged())); if (mode.groupMode == ProjectTreeGroupMode_ByDocument) { ProjViewDocumentItem* di = findDocumentItem(d); delete di; } else { foreach (GObject* obj, d->getObjects()) { ProjViewObjectItem* oi = findGObjectItem(d,obj); if (mode.groupMode == ProjectTreeGroupMode_ByType) { ProjViewTypeItem* topItem = findTypeItem(getLoadedObjectType(obj), true); topItem->removeChild(oi); if (topItem->childCount() == 0) { delete topItem; } else { topItem->updateVisual(); } } delete oi; } } updateSelection(); updateActions(); connect(tree, SIGNAL(itemSelectionChanged()), SLOT(sl_onTreeSelectionChanged())); } void ProjectTreeController::sl_onToggleReadonly() { QSet docsInSelection = getDocsInSelection(true); if (docsInSelection.size()!=1) { return; } Document* doc = docsInSelection.toList().first(); if (doc->hasUserModLock()) { doc->setUserModLock(false); } else { doc->setUserModLock(true); } } void ProjectTreeController::sl_onLockedStateChanged() { QObject * who = sender(); Document* doc = qobject_cast(who); assert(doc!=NULL); ProjViewDocumentItem* di = findDocumentItem(doc); if (mode.readOnlyFilter == TriState_Unknown) { if (di!=NULL) { di->updateVisual(false); } } else { //remove/add document and its objects bool remove = (doc->isStateLocked() && mode.readOnlyFilter == TriState_Yes) || (!doc->isStateLocked() && mode.readOnlyFilter == TriState_No); if (remove) { if (di!=NULL) { delete di; } else { foreach(GObject* obj, doc->getObjects()) { ProjViewObjectItem* oi = findGObjectItem(di, obj); if (oi!=NULL) { delete oi; oi = NULL; } } } disconnectDocument(doc); } else { //add state locked document and its objects //ensure document assert(di == NULL); buildDocumentTree(doc); connectDocument(doc); } updateSelection(); } updateActions(); } void ProjectTreeController::sl_onRename() { QList selItems = tree->selectedItems(); if (selItems.size() != 1) { return; } ProjViewItem *item = static_cast(selItems.last()); if (item != NULL && item->isObjectItem() && !AppContext::getProject()->isStateLocked()) { ProjViewObjectItem *objItem = static_cast(item); QString oldName = objItem->obj->getGObjectName(); objItem->setFlags(objItem->flags() | Qt::ItemIsEditable); objItem->setText(0, objItem->obj->getGObjectName()); tree->editItem(objItem); } } void ProjectTreeController::flattenDocumentItem(ProjViewDocumentItem* docItem) { assert(mode.groupMode == ProjectTreeGroupMode_Flat); while (docItem->childCount()!=0) { ProjViewItem* item = static_cast(docItem->takeChild(0)); assert(item->isObjectItem()); ProjViewObjectItem* objItem = static_cast(item); if (mode.isObjectShown(objItem->obj)) { tree->addTopLevelItem(objItem); objItem->updateVisual(); } else { delete objItem; } } } void ProjectTreeController::sl_onDocumentLoadedStateChanged() { Document* d = qobject_cast(sender()); ProjViewDocumentItem* docItem = findDocumentItem(d); if (!mode.isDocumentShown(d)) { // document item can be automatically removed from the view after its loaded due to filters if (docItem != NULL) { if (mode.groupMode == ProjectTreeGroupMode_Flat) { flattenDocumentItem(docItem); } delete docItem; docItem = NULL; } } if (docItem != NULL && d->getObjects().size() < MAX_OBJECTS_TO_AUTOEXPAND && AppContext::getProject()->getDocuments().size() < MAX_DOCUMENTS_TO_AUTOEXPAND) { docItem->setExpanded(d->isLoaded()); } updateActions(); } void ProjectTreeController::sl_onDocumentModifiedStateChanged() { Document* d = qobject_cast(sender()); assert(d!=NULL); if (!mode.isDocumentShown(d)) { return; } updateActions(); ProjViewDocumentItem* di = findDocumentItem(d); if (di!=NULL) { di->updateVisual(); } } void ProjectTreeController::updateObjectVisual(GObject* obj) { SAFE_POINT(obj != NULL, "Object is NULL in updateObjectVisual()", ); if (!mode.isObjectShown(obj)) { return; } ProjViewObjectItem* item = findGObjectItem(obj->getDocument(), obj); SAFE_POINT(item != NULL, QString("item not found for object %1").arg(obj->getGObjectName()), ); item->updateVisual(); } void ProjectTreeController::sl_onObjectModifiedStateChanged() { updateActions(); updateObjectVisual(qobject_cast(sender())); } void ProjectTreeController::sl_onObjectNameChanged(const QString&) { updateActions(); updateObjectVisual(qobject_cast(sender())); } void ProjectTreeController::sl_onObjectAdded(GObject* obj) { if (!mode.isObjectShown(obj)) { return; } Document* doc = obj->getDocument(); assert(doc!=NULL); ProjViewItem* topItem = NULL; if (mode.groupMode == ProjectTreeGroupMode_ByType) { topItem = findTypeItem(getLoadedObjectType(obj), true); } else if (mode.isDocumentShown(doc)) { topItem = findDocumentItem(doc); if (topItem == NULL) { //doc is not really shown yet -> add it using general routine buildDocumentTree(doc); connectDocument(doc); return; } } connectGObject(obj); ProjViewObjectItem* objItem = new ProjViewObjectItem(obj, this); if (mode.groupMode != ProjectTreeGroupMode_ByDocument || topItem == NULL) { insertTreeItemSorted(topItem, objItem); } else { //keep natural mode, as in file topItem->addChild(objItem); } if (topItem != NULL) { topItem->updateVisual(); } updateActions(); } void ProjectTreeController::sl_onObjectRemoved(GObject* obj) { Document* doc = qobject_cast(sender()); assert(doc!=NULL); ProjViewObjectItem* objItem = findGObjectItem(doc, obj); if (objItem == NULL) { assert(!objectSelection.contains(obj)); return; } ProjViewItem* pi = static_cast(objItem->parent()); delete objItem; if (pi!=NULL && pi->isTypeItem()) { pi->updateVisual(); } objectSelection.removeFromSelection(obj); updateActions(); } void ProjectTreeController::sl_onResourceUserRegistered(const QString& res, Task* t) { Q_UNUSED(res); LoadUnloadedDocumentTask* lut = qobject_cast(t); if (lut == NULL) { return; } connect(lut, SIGNAL(si_progressChanged()), SLOT(sl_onLoadingDocumentProgressChanged())); } #define MAX_OBJS_TO_SHOW_LOAD_PROGRESS 100 void ProjectTreeController::updateLoadingState(Document* doc) { if (mode.isDocumentShown(doc)) { ProjViewDocumentItem* di = findDocumentItem(doc); if (di) { di->updateVisual(); } } if (doc->getObjects().size() < MAX_OBJS_TO_SHOW_LOAD_PROGRESS) { foreach(GObject* obj, doc->getObjects()) { ProjViewObjectItem* oi; if (mode.isObjectShown(obj) && (oi = findGObjectItem(doc, obj))) { oi->updateVisual(); } } } } void ProjectTreeController::sl_onResourceUserUnregistered(const QString& res, Task* t) { Q_UNUSED(res); LoadUnloadedDocumentTask* lut = qobject_cast(t); if (lut == NULL) { return; } lut->disconnect(this); Document* doc = lut->getDocument(); if (doc!=NULL) { updateLoadingState(doc); } } void ProjectTreeController::sl_onLoadingDocumentProgressChanged() { LoadUnloadedDocumentTask* lut = qobject_cast(sender()); assert(lut!=NULL); Document* doc = lut->getDocument(); updateLoadingState(doc); } void ProjectTreeController::updateSettings(const ProjectTreeControllerModeSettings& _mode) { // try to keep GObject selection while reseting view QList objects = getGObjectSelection()->getSelectedObjects(); bool groupModeChanged = _mode.groupMode != mode.groupMode; //bool filtersChanged = _mode.objectFilter!= mode.objectFilter || _mode.documentFilter != mode.documentFilter; mode = _mode; if (groupModeChanged) { tree->clear(); } else { filterItemsRecursive(NULL); } buildTree(); updateActions(); bool madeVisible = false; foreach(GObject* obj, objects) { ProjViewObjectItem* oi = findGObjectItem(obj->getDocument(), obj); if (oi!=NULL) { oi->setSelected(true); if (!madeVisible) { madeVisible = true; tree->scrollToItem(oi); } } } } void ProjectTreeController::filterItemsRecursive(ProjViewItem* pi) { TreeUpdateHelper h(itemsToUpdate); if (pi == NULL) { for(int i=0; i < tree->topLevelItemCount(); i++) { ProjViewItem* ci = static_cast(tree->topLevelItem(i)); if (ci->isDocumentItem()) { ProjViewDocumentItem* di = static_cast(ci); if (!mode.isDocumentShown(di->doc)) { delete di; i--; } else { filterItemsRecursive(di); } } else if (ci->isTypeItem()) { filterItemsRecursive(ci); if (ci->childCount() == 0) { itemsToUpdate.remove(ci); delete ci; i--; } } else { assert(ci->isObjectItem()); ProjViewObjectItem* oi = static_cast(ci); bool filterObject = !mode.isObjectShown(oi->obj) || (mode.isDocumentShown(oi->obj->getDocument()) && oi->parent() == NULL); if (filterObject) { delete oi; i--; } } } } else { for(int i=0; ichildCount(); i++) { ProjViewItem* ci = static_cast(pi->child(i)); assert(ci->isObjectItem()); ProjViewObjectItem* oi = static_cast(ci); if (!mode.isObjectShown(oi->obj)) { delete oi; i--; itemsToUpdate.insert(pi); } } } } void ProjectTreeController::sl_onGroupByDocument() { if (mode.groupMode == ProjectTreeGroupMode_ByDocument) { return; } ProjectTreeControllerModeSettings newMode = mode; newMode.groupMode= ProjectTreeGroupMode_ByDocument; updateSettings(newMode); } void ProjectTreeController::sl_onGroupByType() { if (mode.groupMode == ProjectTreeGroupMode_ByType) { return; } ProjectTreeControllerModeSettings newMode = mode; newMode.groupMode= ProjectTreeGroupMode_ByType; updateSettings(newMode); } void ProjectTreeController::sl_onGroupFlat() { if (mode.groupMode == ProjectTreeGroupMode_Flat) { return; } ProjectTreeControllerModeSettings newMode = mode; newMode.groupMode= ProjectTreeGroupMode_Flat; updateSettings(newMode); } void ProjectTreeController::insertTreeItemSorted(ProjViewItem* p, ProjViewItem* item) { if (p == NULL) { //top level for (int i=0, n = tree->topLevelItemCount(); i < n; i++) { ProjViewItem* otherItem = static_cast(tree->topLevelItem(i)); if (*item < *otherItem) { tree->insertTopLevelItem(i, item); return; } } tree->addTopLevelItem(item); } else { for (int i = 0, n = p->childCount(); i < n; i++) { ProjViewItem* otherItem = static_cast(p->child(i)); if (*item < *otherItem) { p->insertChild(i, item); return; } } p->addChild(item); } } void ProjectTreeController::sl_onDocumentURLorNameChanged() { Document* doc = qobject_cast(sender()); ProjViewDocumentItem* di = findDocumentItem(doc); if (!mode.isDocumentShown(doc)) { delete di; return; } if (di != NULL) { di->updateVisual(); return; } di = new ProjViewDocumentItem(doc, this); tree->addTopLevelItem(di); } void ProjectTreeController::highlightItem(Document *doc){ assert(doc); ProjViewDocumentItem *item = findDocumentItem(doc); if (item) { //item can be NULL here if custom filter is used item->setSelected(true); } } void ProjectTreeController::sl_windowActivated(MWMDIWindow* w) { if (!mode.markActive) { return; } if (mode.groupMode == ProjectTreeGroupMode_ByType) { // only second level objects has 'active' info for (int i=0; i < tree->topLevelItemCount(); i++) { ProjViewItem* item1 = static_cast(tree->topLevelItem(i)); for (int j=0; j < item1->childCount(); j++) { ProjViewItem* item2 = static_cast(item1->child(j)); item2->updateActive(); } } } else { // first level objects has 'active' info for (int i=0; i < tree->topLevelItemCount(); i++) { ProjViewItem* item = static_cast(tree->topLevelItem(i)); item->updateActive(); } } // listen all add/remove to view events if (markActiveView != NULL) { markActiveView->disconnect(this); markActiveView = NULL; } GObjectViewWindow* ow = qobject_cast(w); if (ow != NULL) { uiLog.trace(QString("Project view now listens object events in '%1' view").arg(ow->windowTitle())); markActiveView = ow->getObjectView(); connect(markActiveView, SIGNAL(si_objectAdded(GObjectView*, GObject*)), SLOT(sl_objectAddedToActiveView(GObjectView*, GObject*))); connect(markActiveView, SIGNAL(si_objectRemoved(GObjectView*, GObject*)), SLOT(sl_objectRemovedFromActiveView(GObjectView*, GObject*))); } } void ProjectTreeController::updateObjectActiveStateVisual(GObject* o) { if (mode.groupMode == ProjectTreeGroupMode_ByDocument) { ProjViewDocumentItem* di = findDocumentItem(o->getDocument()); if (di!=NULL) { di->updateActive(); } } else { ProjViewObjectItem* oi = findGObjectItem(o); oi->updateActive(); } } void ProjectTreeController::sl_objectAddedToActiveView(GObjectView*, GObject* o) { uiLog.trace(QString("Processing object add to active view in project tree: %1").arg(o->getGObjectName())); updateObjectActiveStateVisual(o); } void ProjectTreeController::sl_objectRemovedFromActiveView(GObjectView*, GObject* o) { uiLog.trace(QString("Processing object remove form active view in project tree: %1").arg(o->getGObjectName())); updateObjectActiveStateVisual(o); } ////////////////////////////////////////////////////////////////////////// /// Tree Items void ProjViewItem::updateActive() { if (!markedAsActive && !isActive()) { return; } uiLog.trace(QString("Updating active status for %1").arg(text(0))); for (int i = 0, n = childCount(); i < n ; i++ ) { ProjViewItem* item = static_cast(child(i)); item->updateActive(); } updateVisual(false); } ProjViewDocumentItem::ProjViewDocumentItem(Document* _doc, ProjectTreeController* c) : ProjViewItem(c), doc(_doc) { updateVisual(); } bool ProjViewDocumentItem::operator< ( const QTreeWidgetItem & other ) const { const ProjViewItem& pi = (const ProjViewItem&)other; if (pi.isDocumentItem()) { const ProjViewDocumentItem& di = (const ProjViewDocumentItem&)other; return doc->getName() < di.doc->getName(); } else { assert(pi.isObjectItem()); const ProjViewObjectItem& oi = (const ProjViewObjectItem&)other; return doc->getName() < oi.obj->getGObjectName(); } } #define MODIFIED_ITEM_COLOR "#0032a0" void ProjViewDocumentItem::updateVisual(bool recursive) { if (recursive) { for (int i = 0, n = childCount(); i < n ; i++ ) { ProjViewObjectItem* oi = static_cast(child(i)); oi->updateVisual(recursive); } } //update text QString text; if (doc->isModified()) { setData(0, Qt::TextColorRole, QColor(MODIFIED_ITEM_COLOR)); } else { setData(0, Qt::TextColorRole, QVariant()); } markedAsActive = controller->getModeSettings().markActive && isActive(); if (markedAsActive) { setData(0, Qt::FontRole, controller->getModeSettings().activeFont); } else { setData(0, Qt::FontRole, QVariant()); } if (!doc->isLoaded()) { LoadUnloadedDocumentTask* t = LoadUnloadedDocumentTask::findActiveLoadingTask(doc); if (t == NULL) { text+="[unloaded]"; } else { text+=ProjectTreeController::tr("[loading %1%]").arg(t->getProgress()); } } text+=doc->getName(); setData(0, Qt::DisplayRole, text); //update icon bool showLockedIcon = doc->isStateLocked(); if (!doc->isLoaded() && doc->getStateLocks().size() == 1 && doc->getDocumentModLock(DocumentModLock_UNLOADED_STATE)!=NULL) { showLockedIcon = false; } setIcon(0, showLockedIcon ? controller->roDocumentIcon : controller->documentIcon); //update tooltip QString tooltip = doc->getURLString(); if (doc->isStateLocked()) { tooltip.append("

    ").append(ProjectTreeController::tr("Locks:")); StateLockableItem* docContext = doc->getParentStateLockItem(); if (docContext != NULL && docContext->isStateLocked()) { tooltip.append("
     * ").append(ProjectTreeController::tr("Project is locked")); } foreach(StateLock* lock, doc->getStateLocks()) { if (!doc->isLoaded() && lock == doc->getDocumentModLock(DocumentModLock_FORMAT_AS_INSTANCE)) { continue; //do not visualize some locks for unloaded document } tooltip.append("
     * ").append(lock->getUserDesc()); } } setData(0, Qt::ToolTipRole, tooltip); } bool ProjViewDocumentItem::isActive() const { GObjectViewWindow* w = GObjectViewUtils::getActiveObjectViewWindow(); if (w == NULL) { return false; } return w->getObjectView()->containsDocumentObjects(doc); } ProjViewObjectItem::ProjViewObjectItem(GObject* _obj, ProjectTreeController* c) : ProjViewItem(c), obj(_obj) { updateVisual(); } bool ProjViewObjectItem::operator< ( const QTreeWidgetItem & other ) const { const ProjViewItem& pi = (const ProjViewItem&)other; if (pi.isObjectItem()) { const ProjViewObjectItem& oi = (const ProjViewObjectItem&)other; return obj->getGObjectName() < oi.obj->getGObjectName(); } else { assert(pi.isDocumentItem()); const ProjViewDocumentItem& di = (const ProjViewDocumentItem&)other; return obj->getGObjectName() < di.doc->getName(); } } void ProjViewObjectItem::updateVisual(bool ) { QString text; GObjectType t = obj->getGObjectType(); bool unloaded = t == GObjectTypes::UNLOADED; if (unloaded) { setDisabled(true); t = qobject_cast(obj)->getLoadedObjectType(); } const GObjectTypeInfo& ti = GObjectTypes::getTypeInfo(t); text+="[" + ti.treeSign + "] "; if (unloaded && obj->getDocument()->getObjects().size() < MAX_OBJS_TO_SHOW_LOAD_PROGRESS) { LoadUnloadedDocumentTask* t = LoadUnloadedDocumentTask::findActiveLoadingTask(obj->getDocument()); if (t != NULL) { text+=ProjectTreeController::tr("[loading %1%]").arg(t->getProgress()); } } if (obj->isItemModified()) { setData(0, Qt::TextColorRole, QColor(MODIFIED_ITEM_COLOR)); } else { setData(0, Qt::TextColorRole, QVariant()); } markedAsActive = controller->getModeSettings().markActive && isActive(); if (markedAsActive) { setData(0, Qt::FontRole, controller->getModeSettings().activeFont); } else { setData(0, Qt::FontRole, QVariant()); } text+=obj->getGObjectName(); ProjectTreeGroupMode groupMode = controller->getModeSettings().groupMode; if (groupMode == ProjectTreeGroupMode_ByType || groupMode == ProjectTreeGroupMode_Flat) { text+=" ["+obj->getDocument()->getName()+"]"; } setData(0, Qt::DisplayRole, text); setIcon(0, ti.icon); QString tooltip; //todo: make tooltip for object items if (groupMode == ProjectTreeGroupMode_Flat) { tooltip.append(obj->getDocument()->getURLString()); } setToolTip(0, tooltip); } bool ProjViewObjectItem::isActive() const { GObjectViewWindow* w = GObjectViewUtils::getActiveObjectViewWindow(); if (w == NULL) { return false; } return w->getObjectView()->containsObject(obj); } ProjViewTypeItem::ProjViewTypeItem(const GObjectType& t, ProjectTreeController* c) : ProjViewItem(c), otype(t) { typePName = GObjectTypes::getTypeInfo(t).pluralName; updateVisual(false); } bool ProjViewTypeItem::operator< ( const QTreeWidgetItem & other ) const { assert( ((const ProjViewItem&)other).isTypeItem() ); const ProjViewTypeItem& ti = (const ProjViewTypeItem&)other; return otype < ti.otype; } void ProjViewTypeItem::updateVisual(bool recursive) { static QIcon groupIcon(":/core/images/group_green_active.png"); assert(!recursive); Q_UNUSED(recursive); //TODO: remove this param setText(0, typePName + " (" +QString::number(childCount())+")"); setIcon(0, groupIcon); } ////////////////////////////////////////////////////////////////////////// // settings bool ProjectTreeControllerModeSettings::isDocumentShown(Document* doc) const { if (groupMode != ProjectTreeGroupMode_ByDocument && groupMode != ProjectTreeGroupMode_Flat) { return false; } if (groupMode == ProjectTreeGroupMode_Flat && (doc->isLoaded() || !doc->getObjects().isEmpty())) { return false; // only unloaded docs without cached object info are shown in flat mode } //filter by readonly state //TODO: revise readonly filters; //if the only lock is unloaded state lock -> not show it bool isReadonly = ! (doc->getStateLocks().size() == 1 && doc->getDocumentModLock(DocumentModLock_UNLOADED_STATE)!=NULL); bool res = readOnlyFilter == TriState_Unknown ? true : (readOnlyFilter == TriState_Yes && !isReadonly) || (readOnlyFilter == TriState_No && isReadonly); if (!res) { return false; } //filter by object types if (!objectTypesToShow.isEmpty()) { const QList& docObjs = doc->getObjects(); if (!docObjs.isEmpty()) { //ok we have mapping about document objects -> apply filter to the objects bool found = false; foreach(GObject* o, docObjs) { found = isObjectShown(o); if (found) { break; } } if (!found) { return false; } } else { if (!doc->isLoaded()) { DocumentFormatConstraints c; c.supportedObjectTypes += objectTypesToShow.toSet(); res = doc->getDocumentFormat()->checkConstraints(c); } else { res = false; } if (!res) { return false; } } } //filter by name foreach(const QString& token, tokensToShow) { if (!doc->getURLString().contains(token)) { return false; } } // check custom filter if (documentFilter!= NULL && documentFilter->filter(doc)) { return false; } //TODO: make document visible in GroupByDoc mode if any of its objects is visible and avoid flattening? return true; } bool ProjectTreeControllerModeSettings::isObjectShown(GObject* o) const { //filter by type GObjectType t = o->isUnloaded() ? qobject_cast(o)->getLoadedObjectType() : o->getGObjectType(); bool res = isTypeShown(t); if (!res) { return false; } //filter by readonly flag Document* doc = o->getDocument(); //TODO: revise readonly filters -> use isStateLocked or hasReadonlyLock ? res = readOnlyFilter == TriState_Unknown ? true : (readOnlyFilter == TriState_Yes && !doc->isStateLocked()) || (readOnlyFilter == TriState_No && doc->isStateLocked()); if (!res) { return false; } //filter by exclude list foreach(const QPointer& p, excludeObjectList) { if (p.isNull()) { continue; } if (o == p.data()) { return false; } } //filter by internal obj properties if (!objectConstraints.isEmpty()) { res = true; foreach(const GObjectConstraints* c, objectConstraints) { if (o->getGObjectType() != c->objectType) { continue; } res = o->checkConstraints(c); if (!res) { return false; } } } //filter by name foreach(const QString& token, tokensToShow) { if (!o->getGObjectName().contains(token)) { return false; } } // check custom filter if (objectFilter != NULL && objectFilter->filter(o)) { return false; } return true; } bool ProjectTreeControllerModeSettings::isTypeShown(GObjectType t) const { if (objectTypesToShow.isEmpty()) { return true; } return objectTypesToShow.contains(t); } }//namespace ugene-1.9.8/src/corelibs/U2Gui/src/util_gui/GObjectComboBoxController.cpp0000644000175000017500000001463211651544333024777 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "GObjectComboBoxController.h" #include #include #include #include #include namespace U2 { GObjectComboBoxController::GObjectComboBoxController(QObject* p, const GObjectComboBoxControllerConstraints& _c, QComboBox* _cb) : QObject(p), settings(_c), combo(_cb) { connect(AppContext::getProject(), SIGNAL(si_documentAdded(Document*)), SLOT(sl_onDocumentAdded(Document*))); connect(AppContext::getProject(), SIGNAL(si_documentRemoved(Document*)), SLOT(sl_onDocumentRemoved(Document*))); foreach(Document* d, AppContext::getProject()->getDocuments()) { sl_onDocumentAdded(d); } objectIcon = QIcon(":core/images/gobject.png"); unloadedObjectIcon = objectIcon.pixmap(QSize(16, 16), QIcon::Disabled); combo->setInsertPolicy(QComboBox::InsertAlphabetically); updateCombo(); } void GObjectComboBoxController::updateCombo() { combo->clear(); foreach(Document* d, AppContext::getProject()->getDocuments()) { addDocumentObjects(d); } QList allObjs = GObjectUtils::findAllObjects(UOF_LoadedAndUnloaded); for (int i=0, n = combo->count(); iitemData(i).value(); GObject* obj = GObjectUtils::selectObjectByReference(ref, allObjs, UOF_LoadedAndUnloaded); if (!obj->isUnloaded()) { combo->setCurrentIndex(i); break; } } } void GObjectComboBoxController::addDocumentObjects(Document* d) { foreach(GObject* obj, d->getObjects()) { addObject(obj); } } void GObjectComboBoxController::removeDocumentObjects(Document* d) { foreach(GObject* obj, d->getObjects()) { removeObject(obj); } } QString GObjectComboBoxController::itemText(GObject* o) { QString res = o->getGObjectName() + " [" + o->getDocument()->getName() + "]"; return res; } static int findItem(QComboBox* cb, const GObjectReference& objRef) { for (int i=0; i < cb->count(); i++) { GObjectReference ref = cb->itemData(i).value(); if (ref == objRef) { return i; } } return -1; } void GObjectComboBoxController::addObject(GObject* obj) { GObjectType t = obj->getGObjectType(); if (settings.uof == UOF_LoadedOnly && t == GObjectTypes::UNLOADED) { return; } if (!settings.typeFilter.isEmpty()) { if (t == GObjectTypes::UNLOADED && settings.uof == UOF_LoadedAndUnloaded) { t = qobject_cast(obj)->getLoadedObjectType(); } if (t != settings.typeFilter) { return; } } if (settings.relationFilter.isValid() && !obj->hasObjectRelation(settings.relationFilter)) { return; } if (settings.onlyWritable && obj->isStateLocked()) { int olocksCount = obj->getStateLocks().count(); int dlocksCount = obj->getDocument()->getStateLocks().count(); if (!obj->isUnloaded() || olocksCount != 0 || dlocksCount != 1 ) { return; } //else this is unloaded object state lock } #ifdef _DEBUG int n = findItem(combo, obj); assert(n==-1); #endif connect(obj, SIGNAL(si_lockedStateChanged()), SLOT(sl_lockedStateChanged())); combo->addItem(obj->isUnloaded() ? unloadedObjectIcon: objectIcon, itemText(obj), QVariant::fromValue(GObjectReference(obj))); } void GObjectComboBoxController::removeObject(const GObjectReference& ref) { int n = findItem(combo, ref); if (n >= 0) { combo->removeItem(n); } } bool GObjectComboBoxController::setSelectedObject(const GObjectReference& objRef) { int n = findItem(combo, objRef); if (n < 0) { return false; } combo->setCurrentIndex(n); return true; } GObject* GObjectComboBoxController::getSelectedObject() const { int n = combo->currentIndex(); if (n == -1) { return NULL; } GObjectReference r = combo->itemData(n).value(); assert(r.isValid()); GObject* obj = GObjectUtils::selectObjectByReference(r, GObjectUtils::findAllObjects(UOF_LoadedAndUnloaded), UOF_LoadedAndUnloaded); assert(obj!=NULL); return obj; } void GObjectComboBoxController::sl_onDocumentAdded(Document* d) { connect(d, SIGNAL(si_objectAdded(GObject*)), SLOT(sl_onObjectAdded(GObject*))); connect(d, SIGNAL(si_objectRemoved(GObject*)), SLOT(sl_onObjectRemoved(GObject*))); if (d->isLoaded()) { addDocumentObjects(d); } } void GObjectComboBoxController::sl_onDocumentRemoved(Document* d) { if (d->isLoaded()) { removeDocumentObjects(d); } } void GObjectComboBoxController::sl_onObjectAdded(GObject* obj) { addObject(obj); } void GObjectComboBoxController::sl_onObjectRemoved(GObject* obj) { Document* doc = qobject_cast(sender()); assert(doc!=NULL); QString t = obj->getGObjectType(); if (t == GObjectTypes::UNLOADED && settings.uof == UOF_LoadedAndUnloaded) { t = qobject_cast(obj)->getLoadedObjectType(); } removeObject(GObjectReference(doc->getURLString(), obj->getGObjectName(), t)); obj->disconnect(this); } void GObjectComboBoxController::sl_lockedStateChanged() { if (!settings.onlyWritable) { return; } GObject* obj = qobject_cast(sender()); if (obj->isStateLocked()) { removeObject(obj); } else { if (findItem(combo, obj) == -1) { addObject(obj); } } } }//namespace ugene-1.9.8/src/corelibs/U2Gui/src/util_gui/CreateDocumentFromTextDialogController.h0000644000175000017500000000353411651544333027210 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_CREATE_DOCUMENT_FROM_TEXT_DIALOG_CONTROLLER_H_ #define _U2_CREATE_DOCUMENT_FROM_TEXT_DIALOG_CONTROLLER_H_ #include "SeqPasterWidgetController.h" #include #include #include #include class Ui_CreateDocumentFromTextDialog; namespace U2 { class U2GUI_EXPORT CreateDocumentFromTextDialogController : public QDialog { Q_OBJECT public: CreateDocumentFromTextDialogController(QWidget* p = NULL); ~CreateDocumentFromTextDialogController(); virtual void accept(); virtual void reject(); Document* getDocument(){return doc;}; private slots: void sl_browseButtonClicked(); void sl_indexChanged(int index); void sl_projectLoaded(); void sl_filepathTextChanged(const QString &text); private: void addSeqPasterWidget(); void acceptWithExistingProject(); Document *doc; SeqPasterWidgetController *w; QString filter; Ui_CreateDocumentFromTextDialog* ui; }; }//ns #endifugene-1.9.8/src/corelibs/U2Gui/src/util_gui/AnnotationSettingsDialogImpl.cpp0000644000175000017500000001550611651544333025563 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "AnnotationSettingsDialogImpl.h" #include "AnnotationSettingsDialogController.h" #include #include #include #include #include #include #include #include #include #include #include namespace U2 { #define NAME_COLUMN 0 #define COLOR_COLUMN 1 #define AMINO_COLUMN 2 #define HIGHLIGHT_COLUMN 3 #define QUALIFIER_COLUMN 4 void AnnotationSettingsDialogController::run(QWidget* p) { AnnotationSettingsDialogImpl d(p); d.exec(); } AnnotationSettingsDialogImpl::AnnotationSettingsDialogImpl(QWidget* p) : QDialog(p) { setupUi(this); tree->headerItem()->setToolTip(NAME_COLUMN, tr("Annotation name")); tree->headerItem()->setToolTip(COLOR_COLUMN, tr("A color used to highlight annotation")); tree->headerItem()->setToolTip(AMINO_COLUMN, tr("If checked the annotation will be shown on amino strand")); tree->headerItem()->setToolTip(HIGHLIGHT_COLUMN, tr("If unchecked the annotation will not be highlighted with color")); tree->headerItem()->setToolTip(QUALIFIER_COLUMN, tr("A comma-separated list of qualifier names.
    The value of qualifiers will be shown instead of the annotation names in PanView")); connect(tree, SIGNAL(itemClicked(QTreeWidgetItem*, int)), SLOT(sl_itemClicked(QTreeWidgetItem*, int))); connect(tree, SIGNAL(itemDoubleClicked(QTreeWidgetItem*, int)), SLOT(sl_itemDoubleClicked(QTreeWidgetItem*, int))); connect(okButton, SIGNAL(clicked()), SLOT(sl_okClicked())); loadModel(); } /* static void findAllAnnotationsNamesInProject(QSet& allAnnotations) { Project* p = AppContext::getProject(); foreach(Document* doc , p->getDocuments()) { foreach(GObject* obj, doc->getObjects()) { if (obj->getGObjectType() == GObjectTypes::ANNOTATION_TABLE) { AnnotationTableObject* ao = qobject_cast(obj); foreach(Annotation* a, ao->getAnnotations()) { allAnnotations.insert(a->getAnnotationName()); } } } } } */ static void findAllAnnotationsNamesInSettings(QSet& allAnnotations) { AnnotationSettingsRegistry* asr = AppContext::getAnnotationsSettingsRegistry(); foreach(const QString& s, asr->getAllSettings()) { allAnnotations.insert(s); } } static bool caseInsensitiveLessThan(const QString &s1, const QString &s2) { return s1.toLower() < s2.toLower(); } void AnnotationSettingsDialogImpl::loadModel() { QSet allAnnotations; //findAllAnnotationsNamesInProject(allAnnotations); findAllAnnotationsNamesInSettings(allAnnotations); QStringList sortedList = allAnnotations.toList(); qSort(sortedList.begin(), sortedList.end(), caseInsensitiveLessThan); AnnotationSettingsRegistry* asr = AppContext::getAnnotationsSettingsRegistry(); foreach(const QString& name, sortedList) { AnnotationSettings* as = asr->getAnnotationSettings(name); ASTreeItem* item = new ASTreeItem(as); tree->addTopLevelItem(item); } } void AnnotationSettingsDialogImpl::storeModel() { AnnotationSettingsRegistry* asr = AppContext::getAnnotationsSettingsRegistry(); QList mods; for (int i=0; itopLevelItemCount(); i++) { ASTreeItem *item = static_cast(tree->topLevelItem(i)); item->fillModel(); const AnnotationSettings& s = item->as; AnnotationSettings* orig = asr->getAnnotationSettings(s.name); if (!s.equals(orig)) { orig->amino = s.amino; orig->visible = s.visible; orig->color = s.color; orig->nameQuals = s.nameQuals; mods.append(orig); } } if (!mods.isEmpty()) { asr->changeSettings(mods, true); } } void AnnotationSettingsDialogImpl::sl_okClicked() { storeModel(); accept(); } void AnnotationSettingsDialogImpl::sl_itemClicked(QTreeWidgetItem * i, int column) { if (column != 1) { return; } ASTreeItem* item = static_cast(i); QColor c = QColorDialog::getColor(item->as.color, this); item->as.color = c; item->drawColorCell(); } void AnnotationSettingsDialogImpl::sl_itemDoubleClicked(QTreeWidgetItem* item, int col) { if (col!=QUALIFIER_COLUMN) { return; } ASTreeItem* ai = static_cast(item); //TODO controller TextEditorDialog d(this, tr("Visual qualifiers for %1").arg(ai->as.name), tr("Please enter a comma-separated list of qualifier names." "
    The value of qualifiers (with list priority) will be shown instead of the annotation names in PanView"), ai->as.nameQuals.join(","), true); int rc = d.exec(); if (rc == QDialog::Rejected){ return; } QString text = d.getText().simplified().replace(" ", ""); if (text.isEmpty()) { ai->as.nameQuals.clear(); } else { ai->as.nameQuals = text.split(',', QString::SkipEmptyParts); } ai->setText(QUALIFIER_COLUMN, ai->as.nameQuals.join(",")); } ////////////////////////////////////////////////////////////////////////// ASTreeItem::ASTreeItem(const AnnotationSettings* _as) : as(*_as) { setText(NAME_COLUMN, as.name); drawColorCell(); setCheckState(AMINO_COLUMN, as.amino ? Qt::Checked : Qt::Unchecked); setCheckState(HIGHLIGHT_COLUMN, as.visible ? Qt::Checked : Qt::Unchecked); QString qNames = as.nameQuals.join(","); setText(QUALIFIER_COLUMN, qNames); setToolTip(QUALIFIER_COLUMN, qNames); } void ASTreeItem::fillModel() { as.amino = checkState(AMINO_COLUMN) == Qt::Checked; as.visible = checkState(HIGHLIGHT_COLUMN) == Qt::Checked; } void ASTreeItem::drawColorCell() { QIcon icon = GUIUtils::createSquareIcon(as.color, 14); setIcon(COLOR_COLUMN, icon); } }//namespace ugene-1.9.8/src/corelibs/U2Gui/src/util_gui/ObjectViewTreeController.h0000644000175000017500000000774511651544333024366 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_OBJECTVIEW_TREE_CONTROLLER_ #define _U2_OBJECTVIEW_TREE_CONTROLLER_ #include #include #include #include namespace U2 { class OVTItem; class OVTViewItem; class OVTStateItem; class U2GUI_EXPORT ObjectViewTreeController : public QObject { Q_OBJECT public: ObjectViewTreeController(QTreeWidget* w); QAction* getAddStateAction() const {return addStateAction;} QAction* getRenameStateAction() const {return renameStateAction;} QAction* getRemoveStateAction() const {return removeStateAction;} const QIcon& getActiveBookmarkIcon() const {return bookmarkActiveIcon;} const QIcon& getInactiveBookmarkIcon() const {return bookmarkInactiveIcon;} OVTViewItem* findViewItem(const QString& name); private slots: void sl_onMdiWindowAdded(MWMDIWindow*); void sl_onMdiWindowClosing(MWMDIWindow*); void sl_onViewStateAdded(GObjectViewState*); void sl_onStateModified(GObjectViewState*); void sl_onViewStateRemoved(GObjectViewState*); void sl_onViewPersistentStateChanged(GObjectViewWindow* ); void sl_onContextMenuRequested(const QPoint &); void sl_onTreeCurrentChanged(QTreeWidgetItem * current, QTreeWidgetItem * previous); void sl_onItemActivated(QTreeWidgetItem*, int); void sl_onItemChanged(QTreeWidgetItem*, int); void sl_onViewNameChanged(const QString&); void sl_activateView(); void sl_addState(); void sl_removeState(); void sl_renameState(); private: void updateActions(); void buildTree(); void connectModel(); void makeViewPersistent(GObjectViewWindow* w); void makeViewTransient(GObjectViewWindow* w); OVTStateItem* findStateItem(GObjectViewState* s); OVTItem* currentItem() const; OVTViewItem* currentViewItem(bool deriveFromState=false) const; OVTStateItem* currentStateItem() const; GObjectViewState* findStateToOpen() const; void addViewWindow(GObjectViewWindow*); void addState(GObjectViewState*); void removeState(GObjectViewState* s); private: QTreeWidget* tree; QAction* activateViewAction; QAction* addStateAction; QAction* removeStateAction; QAction* renameStateAction; QIcon bookmarkStateIcon; QIcon bookmarkActiveIcon; QIcon bookmarkInactiveIcon; }; class OVTItem : public QTreeWidgetItem { public: OVTItem(ObjectViewTreeController* c) : controller(c) {} bool isRootItem() {return parent() == NULL;} virtual bool isViewItem() const {return false;} virtual bool isStateItem() const {return false;} virtual void updateVisual() = 0; ObjectViewTreeController* controller; }; class OVTViewItem: public OVTItem { public: OVTViewItem(GObjectViewWindow* view, ObjectViewTreeController* c); OVTViewItem(const QString& viewName, ObjectViewTreeController* c); virtual bool isViewItem() const {return true;} virtual void updateVisual(); QString viewName;//BUG:416: remove this field? GObjectViewWindow* viewWindow; }; class OVTStateItem : public OVTItem { public: OVTStateItem(GObjectViewState* state, OVTViewItem* parent, ObjectViewTreeController* c); virtual bool isStateItem() const {return true;} virtual void updateVisual(); GObjectViewState* state; }; }//namespace #endif ugene-1.9.8/src/corelibs/U2Gui/src/util_gui/GUIUtils.h0000644000175000017500000000353311651544333021075 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_GUI_UTILS_H_ #define _U2_GUI_UTILS_H_ #include #include #include #include #include namespace U2 { class U2GUI_EXPORT GUIUtils : public QObject { Q_OBJECT public: static QAction* findAction(const QList& actions, const QString& name); static QAction* findActionAfter(const QList& actions, const QString& name); static QMenu* findSubMenu(QMenu* m, const QString& name); static void disableEmptySubmenus(QMenu* m); static QIcon createSquareIcon(const QColor& c, int size); static QIcon createRoundIcon(const QColor& c, int size); // Sets 'muted' look and feel. The item looks like disabled but still active and can be selected static void setMutedLnF(QTreeWidgetItem* item, bool disabled, bool recursive = false); static bool isMutedLnF(QTreeWidgetItem* item); static bool runWebBrowser(const QString& url); }; } //namespace #endif ugene-1.9.8/src/corelibs/U2Gui/src/util_gui/RemovePartFromSequenceDialogController.cpp0000644000175000017500000001316711651544333027554 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "RemovePartFromSequenceDialogController.h" #include "ui/ui_RemovePartFromSequenceDialog.h" #include #include #include #include #include #include #include #include namespace U2{ RemovePartFromSequenceDialogController::RemovePartFromSequenceDialogController(U2Region _toDelete, U2Region _source, const QString & docUrl, QWidget *p ) :QDialog(p), filter(""), toDelete(_toDelete), source(_source) { ui = new Ui_RemovePartFromSequenceDialog; ui->setupUi(this); QFileInfo fi(docUrl); ui->filepathEdit->setText(fi.absoluteDir().absolutePath() + "/" + fi.baseName() + "_new" + "." + fi.completeSuffix()); connect(ui->browseButton, SIGNAL(clicked()), SLOT(sl_browseButtonClicked())); AnnotationData ad; ad.location->regions << toDelete; ui->removeLocationEdit->setText(Genbank::LocationParser::buildLocationString(&ad)); connect(ui->formatBox, SIGNAL(currentIndexChanged(int)), this, SLOT(sl_indexChanged(int))); ui->formatBox->addItem("FASTA", BaseDocumentFormats::PLAIN_FASTA); ui->formatBox->addItem("Genbank", BaseDocumentFormats::PLAIN_GENBANK); connect(ui->mergeAnnotationsBox, SIGNAL(toggled(bool)), this, SLOT(sl_mergeAnnotationsToggled(bool))); sl_indexChanged(0); } void RemovePartFromSequenceDialogController::accept(){ QString genbankRegion = ui->removeLocationEdit->text(); U2Location location; Genbank::LocationParser::parseLocation(genbankRegion.toAscii().constData(), genbankRegion.length(), location); if (location->isMultiRegion()){ QMessageBox::critical(this, this->windowTitle(), tr("There must be only one region to delete")); return; } if (location->isEmpty()){ QMessageBox::critical(this, this->windowTitle(), tr("Unable to parse region to delete")); return; } toDelete = location->regions.first(); if (toDelete == source) { QMessageBox::critical(this, this->windowTitle(), tr("Cannot remove the whole sequence")); return; } if (toDelete.startPos < source.startPos || toDelete.endPos() > source.endPos()){ QMessageBox::critical(this, this->windowTitle(), tr("Region to delete is out of sequence bounds")); return; } //this->close(); QDialog::accept(); } void RemovePartFromSequenceDialogController::sl_browseButtonClicked(){ LastOpenDirHelper h; h.url = QFileDialog::getSaveFileName(this, tr("Select file to save..."), h.dir, filter); ui->filepathEdit->setText(h.url); sl_indexChanged(ui->formatBox->currentIndex()); } U2AnnotationUtils::AnnotationStrategyForResize RemovePartFromSequenceDialogController::getStrategy(){ if(ui->removeRB->isChecked()){ return U2AnnotationUtils::AnnotationStrategyForResize_Remove; }else{ assert(ui->resizeRB->isChecked()); return U2AnnotationUtils::AnnotationStrategyForResize_Resize; } } void RemovePartFromSequenceDialogController::sl_indexChanged( int index){ DocumentFormatId currentId = (ui->formatBox->itemData(index)).toString(); filter = DialogUtils::prepareDocumentsFileFilter(currentId, false); DocumentFormat *df = AppContext::getDocumentFormatRegistry()->getFormatById(currentId); QString newExt = df->getSupportedDocumentFileExtensions().first(); QString filepath = ui->filepathEdit->text(); if (filepath.isEmpty()){ return; } QFileInfo fi(filepath); ui->filepathEdit->setText(fi.absoluteDir().absolutePath() + "/" + fi.baseName() + "." + newExt); } void RemovePartFromSequenceDialogController::sl_mergeAnnotationsToggled( bool ){ if(ui->mergeAnnotationsBox->isChecked()){ ui->formatBox->removeItem(ui->formatBox->findText("FASTA")); }else{ ui->formatBox->addItem("FASTA", BaseDocumentFormats::PLAIN_FASTA); } sl_indexChanged(ui->formatBox->findText("Genbank")); } bool RemovePartFromSequenceDialogController::modifyCurrentDocument() const { return !ui->saveToAnotherBox->isChecked(); } QString RemovePartFromSequenceDialogController::getNewDocumentPath() const { return ui->filepathEdit->text(); } bool RemovePartFromSequenceDialogController::mergeAnnotations() const { return (ui->mergeAnnotationsBox->isChecked() && !modifyCurrentDocument()); } DocumentFormatId RemovePartFromSequenceDialogController::getDocumentFormatId() const { return ui->formatBox->itemData(ui->formatBox->currentIndex()).toString(); } RemovePartFromSequenceDialogController::~RemovePartFromSequenceDialogController() { delete ui; } }//ns ugene-1.9.8/src/corelibs/U2Gui/src/util_gui/AddNewDocumentDialogImpl.h0000644000175000017500000000330011651544333024223 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_ADD_NEW_DOCUMENT_DIALOG_IMPL_H_ #define _U2_ADD_NEW_DOCUMENT_DIALOG_IMPL_H_ #include "AddNewDocumentDialogController.h" #include namespace U2 { class DocumentFormatComboboxController; class AddNewDocumentDialogImpl : public QDialog, public Ui::AddNewDocumentDialog { Q_OBJECT AddNewDocumentDialogImpl(QWidget* p, AddNewDocumentDialogModel& m, const DocumentFormatConstraints& c); friend class AddNewDocumentDialogController; private slots: void sl_documentURLButtonClicked(); void sl_createButtonClicked(); void sl_documentURLEdited(); void sl_typeComboCurrentChanged(int i); void sl_gzipChecked(bool state); private: void updateState(); QString currentURL(); AddNewDocumentDialogModel model; DocumentFormatComboboxController* formatController; }; }//namespace #endif ugene-1.9.8/src/corelibs/U2Gui/src/util_gui/DownloadRemoteFileDialog.h0000644000175000017500000000343611651544333024275 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_DOWNLOAD_REMOTE_FILE_DIALOG_H_ #define _U2_DOWNLOAD_REMOTE_FILE_DIALOG_H_ #include #include #include #include #include #include class QNetworkReply; class QNetworkAccessManager; class Ui_DownloadRemoteFileDialog; namespace U2 { class U2GUI_EXPORT DownloadRemoteFileDialog : public QDialog { Q_OBJECT bool isQueryDB; QString resUrl; static QString defaultDB; public slots: void sl_updateHint(const QString& dbName); void sl_saveFilenameButtonClicked(); public: DownloadRemoteFileDialog(QWidget *p = NULL); ~DownloadRemoteFileDialog(); QString getDBName() const; QString getResourceId() const; QString getFullpath() const; virtual void accept(); private: void setSaveFilename(); Ui_DownloadRemoteFileDialog* ui; }; } // namespace #endif //_U2_DOWNLOAD_REMOTE_FILE_DIALOG_H_ ugene-1.9.8/src/corelibs/U2Gui/src/util_gui/AnnotationSettingsDialogController.h0000644000175000017500000000214711651544333026447 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_ANNOTATION_SETTINGS_DIALOG_CONTROLLER_H_ #define _U2_ANNOTATION_SETTINGS_DIALOG_CONTROLLER_H_ #include namespace U2 { class U2GUI_EXPORT AnnotationSettingsDialogController { public: static void run(QWidget* p); }; }//namespace #endif ugene-1.9.8/src/corelibs/U2Gui/src/util_gui/RemovePartFromSequenceDialogController.h0000644000175000017500000000372011651544333027213 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_REMOVE_PART_FROM_SEQUENCE_CONTROLLER_H_ #define _U2_REMOVE_PART_FROM_SEQUENCE_CONTROLLER_H_ #include #include #include #include class Ui_RemovePartFromSequenceDialog; namespace U2{ class U2GUI_EXPORT RemovePartFromSequenceDialogController : public QDialog { Q_OBJECT public: RemovePartFromSequenceDialogController(U2Region _toDelete, U2Region _source, const QString & docUrl, QWidget *p = NULL); ~RemovePartFromSequenceDialogController(); virtual void accept(); bool modifyCurrentDocument() const;; QString getNewDocumentPath() const;; U2AnnotationUtils::AnnotationStrategyForResize getStrategy(); U2Region getRegionToDelete() const {return toDelete;}; bool mergeAnnotations() const;; DocumentFormatId getDocumentFormatId() const;; private slots: void sl_browseButtonClicked(); void sl_indexChanged(int); void sl_mergeAnnotationsToggled(bool); private: QString filter; U2Region toDelete; U2Region source; Ui_RemovePartFromSequenceDialog* ui; }; }//ns #endif ugene-1.9.8/src/corelibs/U2Gui/src/util_gui/ProjectDocumentComboBoxController.h0000644000175000017500000000330111651544333026223 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_PROJECT_DOCUMENT_COMBOBOX_CONTROLLER #define _U2_PROJECT_DOCUMENT_COMBOBOX_CONTROLLER #include #include #include namespace U2 { class Project; class U2GUI_EXPORT ProjectDocumentComboBoxController : public QObject { Q_OBJECT public: ProjectDocumentComboBoxController(Project* p, QComboBox* cb, QObject* parent, const DocumentFilter* f); ~ProjectDocumentComboBoxController(); Document* getDocument() const; void selectDocument(Document* d); void selectDocument(const QString& url); private slots: void sl_onDocumentAdded(Document* d); void sl_onDocumentRemoved(Document* d); private: bool checkConstraints(Document* d); void addDocument(Document* d); void removeDocument(Document* d); Project* p; QComboBox* cb; const DocumentFilter* filter; }; } // namespace #endif ugene-1.9.8/src/corelibs/U2Gui/src/util_gui/CreateAnnotationWidgetController.h0000644000175000017500000000721211651544333026074 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_CREATE_ANNOTATION_WIDGET_CONTROLLER_H_ #define _U2_CREATE_ANNOTATION_WIDGET_CONTROLLER_H_ #include #include #include #include class Ui_CreateAnnotationWidget; namespace U2 { class GObjectComboBoxController; class U2GUI_EXPORT CreateAnnotationModel { public: CreateAnnotationModel(); GObjectReference sequenceObjectRef; // this object is selected by default bool defaultIsNewDoc; //new doc field is selected by default bool hideLocation; // hides location field and does not check it in validate() bool hideAnnotationName; // hides annotation name field bool useUnloadedObjects; QString groupName; // default groupname. If empty -> value is used (annotationObject->name value). SharedAnnotationData data; // holds name and location of the annotation GObjectReference annotationObjectRef; // the object to be loaded QString newDocUrl; // the URL of new document with annotation table to be created int sequenceLen; //length of target sequence for validation purposes AnnotationTableObject* getAnnotationObject() const; }; class U2GUI_EXPORT CreateAnnotationWidgetController : public QObject { Q_OBJECT public: CreateAnnotationWidgetController(const CreateAnnotationModel& m, QObject* p); ~CreateAnnotationWidgetController(); // returns error message or empty string if no error found; // does not create any new objects QString validate(); // Ensures that annotationObeject is valid // for a validated model creates new document (newDocUrl), adds annotation table object // to the document created and stores the reference to the object to annotationObject // Does nothing if annotationObject is not NULL void prepareAnnotationObject(); // add model property instead ?? bool isNewObject() const; void setFocusToNameEdit(); QWidget* getWidget() const {return w;} const CreateAnnotationModel& getModel() const {return model;} //receiver object must have sl_setPredefinedAnnotationName(), TODO: move this utility to a separate class static QMenu* createAnnotationNamesMenu(QWidget* p, QObject* receiver); private slots: void sl_onNewDocClicked(); void sl_onLoadObjectsClicked(); void sl_setPredefinedAnnotationName(); void sl_groupName(); void sl_complementLocation(); void sl_setPredefinedGroupName(); private: void updateModel(); CreateAnnotationModel model; GObjectComboBoxController* occ; QWidget* w; Ui_CreateAnnotationWidget* ui; QString GROUP_NAME_AUTO; }; } // namespace #endif ugene-1.9.8/src/corelibs/U2Gui/src/util_gui/SaveDocumentGroupController.h0000644000175000017500000000501511651544333025103 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_SAVE_DOCUMENT_GROUP_CONTROLLER_H_ #define _U2_SAVE_DOCUMENT_GROUP_CONTROLLER_H_ #include #include #include #include namespace U2{ class DocumentFormatComboboxController; class SaveDocumentGroupControllerConfig { public: DocumentFormatConstraints dfc; // format constraints applied for formats combo QToolButton* fileDialogButton; // a button to open save file dialog QString saveTitle; // a title for save file dialog QString defaultFileName; // filename set by default QComboBox* formatCombo; // combo widget to list formats QLineEdit* fileNameEdit; // edit for file name DocumentFormatId defaultFormatId; // format selected by default QWidget* parentWidget; // parent widget for file dialog }; /* Controls 'save document' fields : - combo with document format selection - edit field with document name */ class U2GUI_EXPORT SaveDocumentGroupController : public QObject { Q_OBJECT public: SaveDocumentGroupController(const SaveDocumentGroupControllerConfig& conf, QObject* parent); QString getSaveFileName() const {return conf.fileNameEdit->text();} DocumentFormatId getFormatIdToSave() const; DocumentFormat* getFormatToSave() const; QString getDefaultFileName() const {return conf.defaultFileName;} private slots: void sl_fileNameChanged(const QString& v); void sl_saveButtonClicked(); void sl_formatChanged(const QString& newFormat); private: DocumentFormatComboboxController* comboController; SaveDocumentGroupControllerConfig conf; }; }//namespace #endif ugene-1.9.8/src/corelibs/U2Gui/src/util_gui/ProjectTreeItemSelectorDialogImpl.h0000644000175000017500000000313711651544333026140 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_PROJECT_TREE_ITEM_SELECTOR_DIALOG_IMPL_H_ #define _U2_PROJECT_TREE_ITEM_SELECTOR_DIALOG_IMPL_H_ #include #include namespace U2 { class ProjectTreeController; class ProjectTreeControllerModeSettings; class Document; class GObject; class ProjectTreeItemSelectorDialogImpl: public QDialog, public Ui::ProjectTreeItemSelectorDialogBase { Q_OBJECT public: bool acceptByDoubleClick; private slots: void sl_objectClicked(GObject* obj); private: friend class ProjectTreeItemSelectorDialog; ProjectTreeItemSelectorDialogImpl(QWidget* p, const ProjectTreeControllerModeSettings& s); ~ProjectTreeItemSelectorDialogImpl(); ProjectTreeController* controller; }; }//namespace #endif ugene-1.9.8/src/corelibs/U2Gui/src/util_gui/ui/0000755000175000017500000000000011651544333017670 5ustar ilyailyaugene-1.9.8/src/corelibs/U2Gui/src/util_gui/ui/RemovePartFromSequenceDialog.ui0000644000175000017500000001217011651544333025751 0ustar ilyailya RemovePartFromSequenceDialog 0 0 319 277 Remove subsequence Region to remove Qt::Horizontal 108 17 Qt::Horizontal 108 23 Remove Cancel Annotations region resolving mode Resize true Remove true Save to new file true false Merge annotations to this file Document location: ... Document format: OKButton clicked() RemovePartFromSequenceDialog accept() 205 119 168 71 cancelButton clicked() RemovePartFromSequenceDialog reject() 288 119 168 71 ugene-1.9.8/src/corelibs/U2Gui/src/util_gui/ui/EditQualifierDialog.ui0000644000175000017500000000602011651544333024074 0ustar ilyailya EditQualifierDialog 0 0 319 230 Edit qualifier Name 20 Value false Qt::Horizontal 40 20 OK true Cancel cancelButton clicked() EditQualifierDialog reject() 351 161 241 91 nameEdit returnPressed() EditQualifierDialog accept() 257 19 241 91 okButton clicked() EditQualifierDialog accept() 270 207 159 114 ugene-1.9.8/src/corelibs/U2Gui/src/util_gui/ui/ProjectTreeItemSelectorDialogBase.ui0000644000175000017500000000426411651544333026716 0ustar ilyailya ProjectTreeItemSelectorDialogBase 0 0 712 461 Select Item 1 Qt::Horizontal 40 20 OK true Cancel cancelButton clicked() ProjectTreeItemSelectorDialogBase reject() 580 438 355 230 okButton clicked() ProjectTreeItemSelectorDialogBase accept() 663 438 355 230 ugene-1.9.8/src/corelibs/U2Gui/src/util_gui/ui/MultipartDocFormatConfiguratorWidget.ui0000644000175000017500000000426211651544333027542 0ustar ilyailya MultipartDocFormatConfiguratorWidget 0 0 331 75 0 0 Create annotation Separate sequences Merge sequences Gap length: false Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter 10000 100 mergeRB toggled(bool) gapSpin setEnabled(bool) 245 17 284 48 ugene-1.9.8/src/corelibs/U2Gui/src/util_gui/ui/AnnotationSettingsDialog.ui0000644000175000017500000000500411651544333025201 0ustar ilyailya AnnotationSettingsDialog 0 0 561 524 Visualization settings for annotations false false Name Color Amino Highlight Visual Qualifier Qt::Horizontal 40 20 OK true true Cancel cancelButton clicked() AnnotationSettingsDialog reject() 568 496 308 259 ugene-1.9.8/src/corelibs/U2Gui/src/util_gui/ui/ExportImageDialog.ui0000644000175000017500000002014611651544333023576 0ustar ilyailya ImageExportForm 0 0 372 203 0 0 Export Image false false 0 0 File name ... 0 0 Format 0 0 80 0 0 0 0 0 Width 0 0 80 0 0 0 Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter px 1 9999 0 0 Height 0 0 80 0 0 0 Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter px 1 9999 Qt::Horizontal 40 20 OK Cancel 100 80 Qt::Horizontal 100 80 Quality Qt::Vertical 20 40 cancelButton clicked() ImageExportForm reject() 320 215 190 127 okButton clicked() ImageExportForm accept() 210 215 190 127 qualityHorizontalSlider valueChanged(int) qualitySpinBox setValue(int) 184 147 329 147 qualitySpinBox valueChanged(int) qualityHorizontalSlider setValue(int) 329 147 184 147 ugene-1.9.8/src/corelibs/U2Gui/src/util_gui/ui/AddNewDocumentDialog.ui0000644000175000017500000001077711651544333024224 0ustar ilyailya AddNewDocumentDialog 0 0 613 293 Add new document false 0 0 :/core/images/add_new_document.png QFrame::Box QFrame::Raised Document format Document location ... Qt::Horizontal 40 20 Qt::LeftToRight Compress file Qt::Vertical 20 2 Qt::Horizontal 40 20 Create Cancel cancelButton clicked() AddNewDocumentDialog reject() 20 20 20 20 ugene-1.9.8/src/corelibs/U2Gui/src/util_gui/ui/CreateAnnotationWidget.ui0000644000175000017500000001724511651544333024642 0ustar ilyailya CreateAnnotationWidget 0 0 492 218 0 0 400 58 Create annotations 0 Save annotation(s) to Existing annotation table true ... :/core/images/load_selected_documents.png:/core/images/load_selected_documents.png Create new table false false ... Annotation parameters 0 0 Group name Predefined group names ... :/core/images/group_auto.png:/core/images/group_auto.png 0 0 Annotation name 100 Predefined annotation names :/core/images/predefined_annotation_groups.png:/core/images/predefined_annotation_groups.png 0 0 Location Annotation location in GenBank format Add/remove complement flag ... :/core/images/do_complement.png:/core/images/do_complement.png groupNameEdit annotationNameEdit locationEdit newFileRB toggled(bool) newFileEdit setEnabled(bool) 67 92 392 92 newFileRB toggled(bool) newFileButton setEnabled(bool) 67 92 681 92 existingObjectRB toggled(bool) existingObjectCombo setEnabled(bool) 67 54 392 54 existingObjectRB toggled(bool) existingObjectButton setEnabled(bool) 67 54 681 54 ugene-1.9.8/src/corelibs/U2Gui/src/util_gui/ui/CreateDocumentFromTextDialog.ui0000644000175000017500000000647211651544333025753 0ustar ilyailya CreateDocumentFromTextDialog 0 0 370 194 Create document Document location: ... Document format: Sequence name: Save file immediately Qt::Horizontal 108 23 Create Cancel OKButton clicked() CreateDocumentFromTextDialog accept() 268 264 199 142 cancelButton clicked() CreateDocumentFromTextDialog reject() 351 264 199 142 ugene-1.9.8/src/corelibs/U2Gui/src/util_gui/ui/CreateObjectRelationDialog.ui0000644000175000017500000000422411651544333025401 0ustar ilyailya CreateObjectRelationDialog 0 0 290 352 Edit object relations Associate object with: Qt::Horizontal 40 20 Ok Cancel okButotn clicked() CreateObjectRelationDialog accept() 157 329 144 175 cancelButton clicked() CreateObjectRelationDialog reject() 240 329 144 175 ugene-1.9.8/src/corelibs/U2Gui/src/util_gui/ui/SeqPasterWidget.ui0000644000175000017500000001034011651544333023300 0ustar ilyailya SeqPasterWidget 0 0 300 302 Create annotation 6 0 Paste data here 300 150 Custom settings false Custom settings Alphabet: Skip unknown symbols true Replace unknown symbols with false 0 0 1 1 20 20 9 9 1 skipRB toggled(bool) symbolToReplaceEdit setDisabled(bool) 98 191 225 216 replaceRB toggled(bool) symbolToReplaceEdit setEnabled(bool) 98 216 225 216 useCustomSettingsBox toggled(bool) groupBox setEnabled(bool) 135 115 135 184 ugene-1.9.8/src/corelibs/U2Gui/src/util_gui/ui/DownloadRemoteFileDialog.ui0000644000175000017500000001076511651544333025103 0ustar ilyailya DownloadRemoteFileDialog 0 0 405 177 Fetch data from remote database Resource ID: Database: 0 0 Save to directory: ... Qt::Vertical 20 21 true Hint Use database unique identifier. Qt::Vertical 20 21 QLayout::SetMaximumSize Qt::Horizontal 40 20 OK Cancel acceptButton clicked() DownloadRemoteFileDialog accept() 172 77 151 50 rejectButton clicked() DownloadRemoteFileDialog reject() 255 77 151 50 ugene-1.9.8/src/corelibs/U2Gui/src/util_gui/ui/CopyDocumentDialog.ui0000644000175000017500000000652011651544333023763 0ustar ilyailya CopyDocumentDialog 0 0 625 156 Save a copy true Save to file File format ... Add to project true Compress file false Qt::Horizontal 40 20 Save Cancel createButton clicked() CopyDocumentDialog accept() 222 107 176 65 cancelButton clicked() CopyDocumentDialog reject() 305 107 176 65 ugene-1.9.8/src/corelibs/U2Gui/src/util_gui/ui/FormatSettingsDialog.ui0000644000175000017500000000452611651544333024327 0ustar ilyailya FormatSettingsDialog 0 0 298 51 Custom settings Qt::Vertical 20 4 Save as default settings Qt::Horizontal 40 20 OK Cancel cancelButton clicked() FormatSettingsDialog reject() 400 54 224 38 okButotn clicked() FormatSettingsDialog accept() 317 54 224 38 ugene-1.9.8/src/corelibs/U2Gui/src/util_gui/ui/EditSequenceDialog.ui0000644000175000017500000001230011651544333023721 0ustar ilyailya EditSequenceDialog 0 0 457 295 Annotations region resolving mode Resize true Remove Split Position to insert 10 20 51 20 99999 true Save to new file true false Document location: ... Document format: Merge annotations to this file Qt::Horizontal 108 23 OK Cancel OKButton clicked() EditSequenceDialog accept() 188 158 159 91 cancelButton clicked() EditSequenceDialog reject() 271 158 159 91 ugene-1.9.8/src/corelibs/U2Gui/src/util_gui/EditQualifierDialog.h0000644000175000017500000000276111651544333023301 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_EDIT_QUALIFIER_DIALOG_H_ #define _U2_EDIT_QUALIFIER_DIALOG_H_ #include #include #include class Ui_EditQualifierDialog; namespace U2 { class U2GUI_EXPORT EditQualifierDialog: public QDialog { Q_OBJECT public: EditQualifierDialog(QWidget* p, const U2Qualifier& q, bool ro, bool existingQualifier ); ~EditQualifierDialog(); virtual void accept(); const U2Qualifier& getModifiedQualifier() const {return q;} protected: bool eventFilter(QObject *obj, QEvent *e); private: U2Qualifier q; Ui_EditQualifierDialog* ui; }; }//namespace #endif ugene-1.9.8/src/corelibs/U2Gui/src/util_gui/AddNewDocumentDialogController.h0000644000175000017500000000303411651544333025451 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_ADD_NEW_DOCUMENT_DIALOG_CTRL_H_ #define _U2_ADD_NEW_DOCUMENT_DIALOG_CTRL_H_ #include #include namespace U2 { class U2GUI_EXPORT AddNewDocumentDialogModel { public: AddNewDocumentDialogModel(const QString& _url = QString::null, DocumentFormatId _format = DocumentFormatId::null) : url(_url), io(IOAdapterId::null), format(_format), successful(false){} QString url; IOAdapterId io; DocumentFormatId format; bool successful; }; class U2GUI_EXPORT AddNewDocumentDialogController { public: static void run(QWidget* p, AddNewDocumentDialogModel& m, const DocumentFormatConstraints& c); }; }//namespace #endif ugene-1.9.8/src/corelibs/U2Gui/src/util_gui/ProjectDocumentComboBoxController.cpp0000644000175000017500000000506711651544333026571 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "ProjectDocumentComboBoxController.h" #include namespace U2 { ProjectDocumentComboBoxController::ProjectDocumentComboBoxController(Project* _p, QComboBox* _cb, QObject* parent, const DocumentFilter* f) : QObject(parent), p(_p), cb(_cb), filter(f) { assert(filter!=NULL); cb->setInsertPolicy(QComboBox::InsertAlphabetically); connect(p, SIGNAL(si_documentAdded(Document*)), SLOT(sl_onDocumentAdded(Document*))); connect(p, SIGNAL(si_documentRemoved(Document*)), SLOT(sl_onDocumentRemoved(Document*))); foreach(Document* d, p->getDocuments()) { if (filter->matches(d)) { addDocument(d); } } } ProjectDocumentComboBoxController::~ProjectDocumentComboBoxController() { } void ProjectDocumentComboBoxController::sl_onDocumentAdded(Document* d) { if (filter->matches(d)) { addDocument(d); } } void ProjectDocumentComboBoxController::sl_onDocumentRemoved(Document* d) { removeDocument(d); } void ProjectDocumentComboBoxController::addDocument(Document* d) { cb->addItem(d->getURLString()); } void ProjectDocumentComboBoxController::removeDocument(Document* d) { int i =cb->findText(d->getURLString()); if (i >=0 ) { cb->removeItem(i); } } void ProjectDocumentComboBoxController::selectDocument(const QString& url) { int i = cb->findText(url); if (i >= 0) { cb->setCurrentIndex(i); } } void ProjectDocumentComboBoxController::selectDocument(Document* d) { assert(filter->matches(d)); selectDocument(d->getURLString()); } Document* ProjectDocumentComboBoxController::getDocument() const { QString url = cb->currentText(); if (url.isEmpty()) { return NULL; } Document* doc = p->findDocumentByURL(url); assert(doc); return doc; } } // namespace ugene-1.9.8/src/corelibs/U2Gui/src/util_gui/CreateAnnotationDialog.h0000644000175000017500000000277711651544333024017 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_CREATE_ANNOTATION_DIALOG_H_ #define _U2_CREATE_ANNOTATION_DIALOG_H_ #include #include namespace U2 { class CreateAnnotationWidgetController; class CreateAnnotationModel; class U2GUI_EXPORT CreateAnnotationDialog : public QDialog { Q_OBJECT public: //saves the results to the provided model CreateAnnotationDialog(QWidget* p, CreateAnnotationModel& m); private slots: void sl_onCreateClicked(bool); void sl_onCancelClicked(bool); private: CreateAnnotationModel& model; CreateAnnotationWidgetController* annWidgetController; QPushButton* createButton; QPushButton* cancelButton; }; } // namespace #endif ugene-1.9.8/src/corelibs/U2Gui/src/util_gui/EditSequenceDialogController.h0000644000175000017500000000436611651544333025177 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_EDIT_SEQUENCE_CONTROLLER_H_ #define _U2_EDIT_SEQUENCE_CONTROLLER_H_ #include #include #include #include #include #include class Ui_EditSequenceDialog; namespace U2{ enum EditSequenceDialogMode { EditSequenceMode_Replace, EditSequenceMode_Insert }; struct U2GUI_EXPORT EditSequencDialogConfig { EditSequenceDialogMode mode; U2Region source; DNAAlphabet* alphabet; QByteArray initialText; }; class U2GUI_EXPORT EditSequenceDialogController : public QDialog { Q_OBJECT public: EditSequenceDialogController(EditSequencDialogConfig cfg, QWidget *p = NULL); ~EditSequenceDialogController(); virtual void accept(); DNASequence getNewSequence(){return w->getSequence();}; GUrl getDocumentPath(); int getPosToInsert(){return pos;}; U2AnnotationUtils::AnnotationStrategyForResize getAnnotationStrategy(); bool mergeAnnotations(); DocumentFormatId getDocumentFormatId(); private slots: void sl_browseButtonClicked(); void sl_indexChanged(int); void sl_mergeAnnotationsToggled(bool); private: void addSeqpasterWidget(); bool modifyCurrentDocument(); QString filter; int pos; SeqPasterWidgetController *w; EditSequencDialogConfig config; Ui_EditSequenceDialog* ui; }; }//ns #endif ugene-1.9.8/src/corelibs/U2Gui/src/util_gui/ObjectViewTreeController.cpp0000644000175000017500000003670511651544333024717 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "ObjectViewTreeController.h" #include #include #include #include #include #include //TODO: // track factory registry and show only the states with factories available // delete view state if factory refuses create view namespace U2 { ObjectViewTreeController::ObjectViewTreeController(QTreeWidget* w) : QObject(w), tree(w) { bookmarkStateIcon = QIcon(":core/images/bookmark_item.png"); bookmarkActiveIcon = QIcon(":core/images/bookmark.png"); bookmarkInactiveIcon = QIcon(":core/images/bookmark_inactive.png"); tree->headerItem()->setHidden(true); tree->setSelectionMode(QAbstractItemView::SingleSelection); tree->setContextMenuPolicy(Qt::CustomContextMenu); connect(tree, SIGNAL(currentItemChanged(QTreeWidgetItem *, QTreeWidgetItem*)), SLOT(sl_onTreeCurrentChanged(QTreeWidgetItem *, QTreeWidgetItem*))); connect(tree, SIGNAL(customContextMenuRequested(const QPoint &)), SLOT(sl_onContextMenuRequested(const QPoint &))); connect(tree, SIGNAL(itemActivated(QTreeWidgetItem*, int)), SLOT(sl_onItemActivated(QTreeWidgetItem*, int))); connect(tree, SIGNAL(itemChanged(QTreeWidgetItem*, int)), SLOT(sl_onItemChanged(QTreeWidgetItem*, int))); activateViewAction = new QAction(tr("Activate view"), this); activateViewAction->setShortcut(QKeySequence(Qt::Key_Space)); activateViewAction->setShortcutContext(Qt::WidgetWithChildrenShortcut); connect(activateViewAction, SIGNAL(triggered()), SLOT(sl_activateView())); addStateAction = new QAction(tr("Add bookmark"), this); addStateAction->setIcon(QIcon(":core/images/bookmark_add.png")); connect(addStateAction, SIGNAL(triggered()), SLOT(sl_addState())); removeStateAction = new QAction(tr("Remove bookmark"), this); removeStateAction->setIcon(QIcon(":core/images/bookmark_remove.png")); removeStateAction->setShortcut(QKeySequence(Qt::Key_Delete)); removeStateAction->setShortcutContext(Qt::WidgetWithChildrenShortcut); connect(removeStateAction, SIGNAL(triggered()), SLOT(sl_removeState())); renameStateAction = new QAction(tr("Rename bookmark"), this); renameStateAction->setIcon(QIcon(":core/images/bookmark_edit.png")); renameStateAction->setShortcut(QKeySequence(Qt::Key_F2)); renameStateAction->setShortcutContext(Qt::WidgetWithChildrenShortcut); connect(renameStateAction, SIGNAL(triggered()), SLOT(sl_renameState())); tree->addAction(activateViewAction); tree->addAction(removeStateAction); tree->addAction(renameStateAction); connectModel(); buildTree(); updateActions(); } void ObjectViewTreeController::connectModel() { Project* p = AppContext::getProject(); connect(p, SIGNAL(si_objectViewStateAdded(GObjectViewState*)), SLOT(sl_onViewStateAdded(GObjectViewState*))); connect(p, SIGNAL(si_objectViewStateRemoved(GObjectViewState*)), SLOT(sl_onViewStateRemoved(GObjectViewState*))); MWMDIManager* mdi = AppContext::getMainWindow()->getMDIManager(); connect(mdi, SIGNAL(si_windowAdded(MWMDIWindow*)), SLOT(sl_onMdiWindowAdded(MWMDIWindow*))); connect(mdi, SIGNAL(si_windowClosing(MWMDIWindow*)), SLOT(sl_onMdiWindowClosing(MWMDIWindow*))); } void ObjectViewTreeController::buildTree() { tree->clear(); const QList& states= AppContext::getProject()->getGObjectViewStates(); foreach(GObjectViewState* s, states) { addState(s); } QList views = GObjectViewUtils::getAllActiveViews(); foreach(GObjectViewWindow* v, views) { addViewWindow(v); } } void ObjectViewTreeController::addViewWindow(GObjectViewWindow* viewWindow) { viewWindow->installEventFilter(this); connect(viewWindow, SIGNAL(si_persistentStateChanged(GObjectViewWindow*)), SLOT(sl_onViewPersistentStateChanged(GObjectViewWindow*))); connect(viewWindow->getObjectView(), SIGNAL(si_nameChanged(const QString&)), SLOT(sl_onViewNameChanged(const QString&))); OVTViewItem* vi = findViewItem(viewWindow->getViewName()); if (vi == NULL) { vi = new OVTViewItem(viewWindow, this); tree->addTopLevelItem(vi); } else { assert(vi->viewWindow == NULL); vi->viewWindow = viewWindow; vi->updateVisual(); } } void ObjectViewTreeController::addState(GObjectViewState* s) { OVTViewItem* vi = findViewItem(s->getViewName()); if (vi == NULL) { vi = new OVTViewItem(s->getViewName(), this); tree->addTopLevelItem(vi); } OVTStateItem* si = findStateItem(s); SAFE_POINT(si == NULL, QString("State item is already exists: %1 -> %2").arg(s->getViewName()).arg(s->getStateName()),); si = new OVTStateItem(s, vi, this); si->setIcon(0, bookmarkStateIcon); vi->addChild(si); } void ObjectViewTreeController::removeState(GObjectViewState* s) { OVTStateItem* si = findStateItem(s); SAFE_POINT(si != NULL, QString("Failed to find state item to remove: %1 -> %2").arg(s->getViewName()).arg(s->getStateName()),); OVTViewItem* vi = static_cast(si->parent()); delete si; if (vi->childCount() == 0) { if (vi->viewWindow==NULL) { delete vi; } else { makeViewTransient(vi->viewWindow); } } } OVTItem* ObjectViewTreeController::currentItem() const { QTreeWidgetItem* i = tree->currentItem(); return static_cast(i); } OVTViewItem* ObjectViewTreeController::currentViewItem(bool deriveFromState) const { OVTItem* i = currentItem(); OVTViewItem* vi = (i != NULL && i->isViewItem()) ? static_cast(i) : NULL; if (vi == NULL && deriveFromState) { OVTStateItem* si = currentStateItem(); if (si!=NULL) { vi = static_cast(si->parent()); } } return vi; } OVTStateItem* ObjectViewTreeController::currentStateItem() const { OVTItem* i = currentItem(); return (i != NULL && i->isStateItem()) ? static_cast(i) : NULL; } GObjectViewState* ObjectViewTreeController::findStateToOpen() const { OVTStateItem* si = currentStateItem(); GObjectViewState* state = NULL; if (si!=NULL) { state = si->state; } else { OVTViewItem* vi = currentViewItem(); if (vi!=NULL && vi->viewWindow == NULL) { const QList& allStates = AppContext::getProject()->getGObjectViewStates(); state = GObjectViewUtils::findStateInList(vi->viewName, GObjectViewState::APP_CLOSING_STATE_NAME, allStates); } } return state; } void ObjectViewTreeController::updateActions() { OVTStateItem* si = currentStateItem(); OVTViewItem* vi = currentViewItem(true); bool hasActiveView = vi!=NULL && vi->viewWindow!=NULL; GObjectViewState* stateToOpen = findStateToOpen(); bool canAddStates = hasActiveView && vi->viewWindow->getViewFactory()->supportsSavedStates(); activateViewAction->setEnabled(hasActiveView || stateToOpen!=NULL); addStateAction->setEnabled(canAddStates); removeStateAction->setEnabled(si!=NULL || (vi!=NULL && vi->childCount() > 0)); renameStateAction->setEnabled(si!=NULL); } void ObjectViewTreeController::sl_onMdiWindowAdded(MWMDIWindow* w) { GObjectViewWindow* vw = qobject_cast(w); if (vw == NULL) { return; } addViewWindow(vw); updateActions(); } void ObjectViewTreeController::sl_onMdiWindowClosing(MWMDIWindow* w) { GObjectViewWindow* wv = qobject_cast(w); if (wv == NULL) { return; } OVTViewItem* vi = findViewItem(wv->getViewName()); SAFE_POINT(vi != NULL, QString("Can't find view item on window closing! View name: %1").arg(wv->getViewName()),); if (wv->isPersistent()) { vi->viewWindow = NULL; vi->updateVisual(); } else { assert(vi->childCount() == 0); delete vi; } updateActions(); } void ObjectViewTreeController::sl_onViewStateAdded(GObjectViewState* s) { addState(s); updateActions(); connect(s, SIGNAL(si_stateModified(GObjectViewState*)), SLOT(sl_onStateModified(GObjectViewState*))); } void ObjectViewTreeController::sl_onViewStateRemoved(GObjectViewState* s) { removeState(s); updateActions(); s->disconnect(this); } void ObjectViewTreeController::sl_onViewPersistentStateChanged(GObjectViewWindow* v) { OVTViewItem* vi = findViewItem(v->getViewName()); vi->updateVisual(); updateActions(); } OVTViewItem* ObjectViewTreeController::findViewItem(const QString& name) { for(int i =0; i< tree->topLevelItemCount(); i++) { OVTViewItem* vi = static_cast(tree->topLevelItem(i)); if (vi->viewName == name) { return vi; } } return NULL; } OVTStateItem* ObjectViewTreeController::findStateItem(GObjectViewState* s) { OVTViewItem* vi = findViewItem(s->getViewName()); if (vi == NULL) { return NULL; } for(int i = 0; i< vi->childCount(); i++) { OVTStateItem* si = static_cast(vi->child(i)); if (si->state == s) { return si; } } return NULL; } void ObjectViewTreeController::sl_onContextMenuRequested(const QPoint & pos) { Q_UNUSED(pos); QMenu popup; bool hasItemSelected = tree->currentItem()!=NULL; if(hasItemSelected) { popup.addAction(activateViewAction); } popup.addAction(addStateAction); popup.addAction(renameStateAction); popup.addAction(removeStateAction); //TODO: emit si_onPopupMenuRequested(*popup); if (!popup.isEmpty()) { popup.exec(QCursor::pos()); } } void ObjectViewTreeController::sl_onTreeCurrentChanged(QTreeWidgetItem * current, QTreeWidgetItem * previous) { Q_UNUSED(current); Q_UNUSED(previous); updateActions(); } void ObjectViewTreeController::sl_activateView() { OVTViewItem* vi = currentViewItem(); if (vi!=NULL && vi->viewWindow!=NULL) { //raise existing view, no state change AppContext::getMainWindow()->getMDIManager()->activateWindow(vi->viewWindow); return; } //open closed view by state or update state of the active view GObjectViewState* state = findStateToOpen(); if (state==NULL) { return; } GObjectViewWindow* view = GObjectViewUtils::findViewByName(state->getViewName()); if (view!=NULL) { assert(view->isPersistent()); AppContext::getMainWindow()->getMDIManager()->activateWindow(view); if (state!=NULL) { // state was selected -> apply state AppContext::getTaskScheduler()->registerTopLevelTask(view->getObjectView()->updateViewTask(state->getStateName(), state->getStateData())); } } else { GObjectViewFactory* f = AppContext::getObjectViewFactoryRegistry()->getFactoryById(state->getViewFactoryId()); AppContext::getTaskScheduler()->registerTopLevelTask(f->createViewTask(state->getViewName(), state->getStateData())); } } void ObjectViewTreeController::sl_onItemActivated(QTreeWidgetItem* i, int col) { Q_UNUSED(i); Q_UNUSED(col); sl_activateView(); } void ObjectViewTreeController::makeViewPersistent(GObjectViewWindow* w) { assert(!w->isPersistent()); assert(w->getViewFactory()->supportsSavedStates()); w->setPersistent(true); } void ObjectViewTreeController::sl_addState() { OVTViewItem* vi = currentViewItem(true); SAFE_POINT(vi != NULL, QString("Can't find view item to add state!"),); SAFE_POINT(vi->viewWindow != NULL, QString("View window is NULL: %1").arg(vi->viewName),); if (!vi->viewWindow->isPersistent()) { makeViewPersistent(vi->viewWindow); } assert(vi->viewWindow->isPersistent()); QString stateName = GObjectViewUtils::genUniqueStateName(tr("New bookmark")); //todo: avoid localization here? QVariantMap state = vi->viewWindow->getObjectView()->saveState(); GObjectViewState* s = new GObjectViewState(vi->viewWindow->getViewFactoryId(), vi->viewWindow->getViewName(), stateName, state); AppContext::getProject()->addGObjectViewState(s); vi->setExpanded(true); } void ObjectViewTreeController::makeViewTransient(GObjectViewWindow* w) { assert(w->isPersistent()); w->setPersistent(false); } void ObjectViewTreeController::sl_removeState() { OVTStateItem* si = currentStateItem(); Project* p = AppContext::getProject(); if (si!=NULL) { assert(si->state!=NULL); p->removeGObjectViewState(si->state); } else { OVTViewItem* vi = currentViewItem(); SAFE_POINT(vi != NULL, QString("Can't find view item to remove its state!"),); int childs = vi->childCount(); assert(childs > 0); for (int i=0; i< childs; i++) { OVTStateItem* si2 = static_cast(vi->child(0)); p->removeGObjectViewState(si2->state); } } } void ObjectViewTreeController::sl_renameState() { OVTStateItem* si = currentStateItem(); SAFE_POINT(si != NULL, QString("Can't find state item to rename!"),); si->setFlags(si->flags() | Qt::ItemIsEditable); tree->editItem(si); //tree->disconnect(this, SLOT(sl_onItemChanged(QTreeWidgetItem*, int))); si->setFlags(si->flags() ^ Qt::ItemIsEditable); } void ObjectViewTreeController::sl_onItemChanged(QTreeWidgetItem* i, int c) { assert(c == 0); Q_UNUSED(c); OVTItem* oi = static_cast(i); if (oi->isViewItem()) { OVTViewItem* vi = static_cast(oi); assert(vi->text(0).endsWith(vi->viewName)); Q_UNUSED(vi); return; } assert(oi->isStateItem()); OVTStateItem* si = static_cast(oi); QString newName = si->text(0); GObjectViewState* state = GObjectViewUtils::findStateByName(si->state->getViewName(), newName); if (state == si->state) { return; } if (state != NULL) { //todo: show error! return; } if (newName.isEmpty()) { //todo: show error return; } si->state->setStateName(newName); } void ObjectViewTreeController::sl_onStateModified(GObjectViewState* s) { OVTStateItem* si = findStateItem(s); SAFE_POINT(si != NULL, QString("Can't find state item to update: %1 -> %2").arg(s->getViewName()).arg(s->getStateName()),); si->updateVisual(); } void ObjectViewTreeController::sl_onViewNameChanged(const QString& oldName) { OVTViewItem* vi = findViewItem(oldName); SAFE_POINT(vi, QString("Can't find view item to rename: %1").arg(oldName),); vi->updateVisual(); } ////////////////////////////////////////////////////////////////////////// /// tree items OVTViewItem::OVTViewItem(GObjectViewWindow* v, ObjectViewTreeController* c) : OVTItem (c), viewName(v->getViewName()), viewWindow(v) { updateVisual(); } OVTViewItem::OVTViewItem(const QString& _viewName, ObjectViewTreeController* c) : OVTItem (c), viewName(_viewName), viewWindow(NULL) { updateVisual(); } void OVTViewItem::updateVisual() { setIcon(0, viewWindow == NULL ? controller->getInactiveBookmarkIcon() : controller->getActiveBookmarkIcon()); viewName = viewWindow == NULL ? viewName : viewWindow->getViewName(); QString text = viewName; setText(0, text); } OVTStateItem::OVTStateItem(GObjectViewState* _state, OVTViewItem* parent, ObjectViewTreeController* c) : OVTItem(c), state(_state) { updateVisual(); parent->addChild(this); } void OVTStateItem::updateVisual() { setText(0, state->getStateName()); } }//namespace ugene-1.9.8/src/corelibs/U2Gui/src/util_gui/GObjectComboBoxController.h0000644000175000017500000000467711651544333024454 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_GOBJECT_COMBOBOX_CONTROLLER_H_ #define _U2_GOBJECT_COMBOBOX_CONTROLLER_H_ #include #include #include namespace U2 { //TODO: use custom class for objects filtering, share it with ProjectTreeController class GObjectComboBoxControllerConstraints { public: GObjectComboBoxControllerConstraints() { onlyWritable = false; uof = UOF_LoadedOnly; } GObjectType typeFilter; GObjectRelation relationFilter; bool onlyWritable; UnloadedObjectFilter uof; }; class U2GUI_EXPORT GObjectComboBoxController : public QObject { Q_OBJECT public: GObjectComboBoxController(QObject* p, const GObjectComboBoxControllerConstraints& c, QComboBox* combo); bool setSelectedObject(GObject* obj) {return setSelectedObject(GObjectReference(obj));} bool setSelectedObject(const GObjectReference& ref); GObject* getSelectedObject() const; private slots: void sl_onDocumentAdded(Document* d); void sl_onDocumentRemoved(Document* d); void sl_onObjectAdded(GObject* o); void sl_onObjectRemoved(GObject* o); void sl_lockedStateChanged(); private: void updateCombo(); void addObject(GObject*); void removeObject(const GObjectReference& ref); void addDocumentObjects(Document* d); void removeDocumentObjects(Document* d); QString itemText(GObject* o); GObjectComboBoxControllerConstraints settings; QComboBox* combo; QIcon objectIcon; QIcon unloadedObjectIcon; }; }//namespace #endif ugene-1.9.8/src/corelibs/U2Gui/src/util_gui/CopyDocumentDialogController.h0000644000175000017500000000300511651544333025217 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_COPY_DOCUMENT_DIALOG_CONTROLLER_H_ #define _U2_COPY_DOCUMENT_DIALOG_CONTROLLER_H_ #include #include #include class Ui_CopyDocumentDialog; namespace U2 { class SaveDocumentGroupController; class U2GUI_EXPORT CopyDocumentDialogController : public QDialog { Q_OBJECT public: CopyDocumentDialogController(Document* d, QWidget* p); ~CopyDocumentDialogController(); QString getDocumentURL() const; bool getAddToProjectFlag() const; DocumentFormatId getDocumentFormatId() const; private: SaveDocumentGroupController* saveController; Ui_CopyDocumentDialog* ui; }; }//ns #endif ugene-1.9.8/src/corelibs/U2Gui/src/util_gui/CreateAnnotationDialog.cpp0000644000175000017500000000574011651544333024343 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "CreateAnnotationDialog.h" #include "CreateAnnotationWidgetController.h" #include #include #include #include #include #include #include #include #include namespace U2 { CreateAnnotationDialog::CreateAnnotationDialog(QWidget* p, CreateAnnotationModel& m) : QDialog(p), model(m){ annWidgetController = new CreateAnnotationWidgetController(m, this); this->setObjectName("new_annotation_dialog"); QHBoxLayout* buttonsLayout = new QHBoxLayout(); buttonsLayout->addStretch(1); createButton = new QPushButton(tr("Create"), this); createButton->setObjectName("create_button"); buttonsLayout->addWidget(createButton); cancelButton = new QPushButton(tr("Cancel"), this); cancelButton->setObjectName("cancel_button"); buttonsLayout->addWidget(cancelButton); QVBoxLayout* topLayout = new QVBoxLayout(); topLayout->setObjectName("new_annotation_dialog_layout"); QWidget * annWidget = annWidgetController->getWidget(); topLayout->addWidget(annWidget); annWidget->setMinimumSize(annWidget->layout()->minimumSize()); annWidget->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed); topLayout->addLayout(buttonsLayout); setLayout(topLayout); setMaximumHeight(layout()->minimumSize().height()); connect(createButton, SIGNAL(clicked(bool)), SLOT(sl_onCreateClicked(bool))); connect(cancelButton, SIGNAL(clicked(bool)), SLOT(sl_onCancelClicked(bool))); annWidgetController->setFocusToNameEdit(); setWindowTitle(tr("Create annotation")); } void CreateAnnotationDialog::sl_onCreateClicked(bool) { QString err = annWidgetController->validate(); if (!err.isEmpty()) { QMessageBox::warning(this, tr("Error"), err); return; } annWidgetController->prepareAnnotationObject(); model = annWidgetController->getModel(); accept(); } void CreateAnnotationDialog::sl_onCancelClicked(bool) { reject(); } } // namespace ugene-1.9.8/src/corelibs/U2Gui/src/util_gui/ProjectTreeItemSelectorDialog.h0000644000175000017500000000253211651544333025314 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_PROJECT_TREE_ITEM_SELECTOR_DIALOG_H_ #define _U2_PROJECT_TREE_ITEM_SELECTOR_DIALOG_H_ #include class QWidget; namespace U2 { class ProjectTreeControllerModeSettings; class Document; class GObject; class U2GUI_EXPORT ProjectTreeItemSelectorDialog { public: static QList selectDocuments(const ProjectTreeControllerModeSettings& s, QWidget* p); static QList selectObjects(const ProjectTreeControllerModeSettings& s, QWidget* p); }; }//namespace #endif ugene-1.9.8/src/corelibs/U2Gui/src/util_gui/logview/0000755000175000017500000000000011651544333020727 5ustar ilyailyaugene-1.9.8/src/corelibs/U2Gui/src/util_gui/logview/LogView.h0000644000175000017500000000732511651544333022463 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_LOGVIEW_IMPL_ #define _U2_LOGVIEW_IMPL_ #include #include #include #include #include #include #include namespace U2 { class LogCache; class LogMessage; class LogFilter; class SearchHighlighter: public QSyntaxHighlighter { public: SearchHighlighter(QTextDocument *doc): QSyntaxHighlighter(doc) {} QRegExp reg_exp; void highlightBlock(const QString &text); }; enum LogViewSearchBoxMode { LogViewSearchBox_Visible, LogViewSearchBox_Auto, //TODO: not supported today LogViewSearchBox_Hidden }; class U2GUI_EXPORT LogViewWidget : public QWidget, public LogSettingsHolder { Q_OBJECT public: /** If categoriesFilter is not-empty LogViewWidget shows log messages only from categories listed in categoriesFilter LogSettings are ignored in this case */ LogViewWidget(LogCache* c); LogViewWidget(const LogFilter& filter); void resetView(); bool isShown(const LogMessage& msg); bool isShown(const QString& txt); /** returns first category in the msg.categories that match 'show-filter' criteria*/ QString getEffectiveCategory(const LogMessage& msg) const; virtual void setSettings(const LogSettings& s); void setSearchBoxMode(LogViewSearchBoxMode mode); protected: void addMessage(const LogMessage& msg); void addText(const QString& text); void showEvent(QShowEvent *e); void hideEvent(QHideEvent *e); private slots: void sl_onMessage(const LogMessage& msg); void sl_onTextEdited(const QString& text); void popupMenu(const QPoint &pos); void sl_openSettingsDialog(); void sl_logSettingsChanged(); void sl_dumpCounters(); void sl_clear(); void sl_addSeparator(); void sl_showHideEdit(); void searchPopupMenu(const QPoint &pos); void setSearchCaseSensitive(); void useRegExp(); private: struct EntryStruct { bool is_plain_text; LogMessage msg; EntryStruct(const QString &txt): is_plain_text(true) { msg.text = txt; } EntryStruct(const LogMessage &_msg): is_plain_text(false), msg(_msg) {} }; QString prepareText(const LogMessage& msg) const; void init(); void resetText(); QPlainTextEdit* edit; QLineEdit* searchEdit; QList original_text; QShortcut* shortcut; SearchHighlighter* highlighter; bool caseSensitive, useRegexp; int messageCounter; LogCache* cache; QAction* showViewAction; QAction* showSettingsAction; QAction* dumpCountersAction; QAction* clearAction; QAction* addSeparatorAction; bool connected; //for debug only }; } //namespace #endif ugene-1.9.8/src/corelibs/U2Gui/src/util_gui/logview/LogView.cpp0000644000175000017500000002730511651544333023016 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "LogView.h" #include #include #include #include #include #include #include #include #include #include #include #include namespace U2 { static void checkThread() { #ifdef _DEBUG QThread* appThread = QApplication::instance()->thread(); QThread* thisThread = QThread::currentThread(); assert (appThread == thisThread); #endif } #define MAX_VISIBLE_MESSAGES 1000 LogViewWidget::LogViewWidget(const LogFilter& filter) { cache = new LogCache(); cache->filter = filter; cache->setParent(this); init(); } LogViewWidget::LogViewWidget(LogCache* c) { cache = c; init(); } void LogViewWidget::init() { connected = false; caseSensitive = true; useRegexp = true; setWindowTitle(tr("Log")); setWindowIcon(QIcon(":ugene/images/book_open.png")); settings.reinitAll(); showSettingsAction = new QAction(tr("Settings"), this); showSettingsAction->setIcon(QIcon(":ugene/images/log_settings.png")); connect(showSettingsAction, SIGNAL(triggered()), SLOT(sl_openSettingsDialog())); dumpCountersAction = new QAction(tr("Dump performance counters"), this); connect(dumpCountersAction, SIGNAL(triggered()), SLOT(sl_dumpCounters())); addSeparatorAction = new QAction(tr("Append separator"), this); connect(addSeparatorAction, SIGNAL(triggered()), SLOT(sl_addSeparator())); clearAction = new QAction(tr("Clear log"), this); connect(clearAction, SIGNAL(triggered()), SLOT(sl_clear())); QVBoxLayout* l = new QVBoxLayout(); l->setSpacing(0); l->setMargin(0); l->setContentsMargins(0, 0, 0, 0); setLayout(l); edit = new QPlainTextEdit(); edit->setUndoRedoEnabled(false); edit->setReadOnly(true); edit->setLineWrapMode(QPlainTextEdit::WidgetWidth); edit->setContextMenuPolicy(Qt::CustomContextMenu); edit->setTextInteractionFlags(Qt::NoTextInteraction|Qt::TextSelectableByMouse|Qt::TextSelectableByKeyboard); edit->setMaximumBlockCount(MAX_VISIBLE_MESSAGES); searchEdit = new QLineEdit(); searchEdit->setContextMenuPolicy(Qt::CustomContextMenu); shortcut = new QShortcut(QString("/"), this, 0, 0, Qt::WidgetWithChildrenShortcut); highlighter = new SearchHighlighter(edit->document()); l->addWidget(edit); l->addWidget(searchEdit); QObject::connect(edit, SIGNAL(customContextMenuRequested(const QPoint &)),this,SLOT(popupMenu(const QPoint &))); QObject::connect(searchEdit, SIGNAL(customContextMenuRequested(const QPoint &)),this,SLOT(searchPopupMenu(const QPoint &))); QObject::connect(shortcut, SIGNAL(activated()),this,SLOT(sl_showHideEdit())); QObject::connect(searchEdit, SIGNAL(textEdited(const QString &)),this,SLOT(sl_onTextEdited(const QString &))); resetView(); } void LogViewWidget::popupMenu(const QPoint& pos) { Q_UNUSED(pos); QMenu popup; QAction* copyAction = popup.addAction(tr("Copy"), edit, SLOT(copy())); copyAction->setShortcut(QKeySequence(Qt::CTRL | Qt::Key_C)); copyAction->setEnabled(edit->textCursor().hasSelection()); popup.addAction(dumpCountersAction); popup.addAction(addSeparatorAction); popup.addAction(clearAction); if (cache == LogCache::getAppGlobalInstance()) { //customization is allowed only for global cache today popup.addAction(showSettingsAction); } popup.exec(QCursor::pos()); } void SearchHighlighter::highlightBlock(const QString &text) { if (reg_exp.pattern() == "") return; QTextCharFormat cf; cf.setBackground(Qt::green); for (int pos = 0; (pos = reg_exp.indexIn(text, pos)) != -1;) { int length = reg_exp.matchedLength(); if (length == 0) { ++pos; continue; } setFormat(pos, length, cf); pos += length; } } void LogViewWidget::sl_showHideEdit() { if (searchEdit->isVisible()) searchEdit->hide(); else { searchEdit->show(); searchEdit->setFocus(); } } void LogViewWidget::resetText() { edit->clear(); foreach(EntryStruct e, original_text) { if (isShown(e.msg.text)) { if(e.is_plain_text) { edit->appendHtml(e.msg.text); } else { edit->appendHtml(prepareText(e.msg)); } } } } void LogViewWidget::sl_onTextEdited(const QString & text) { QRegExp re(text); if (highlighter->reg_exp.patternSyntax() == QRegExp::RegExp && !re.isValid()) return; highlighter->reg_exp.setPattern(text); resetText(); } bool LogViewWidget::isShown(const QString & txt) { if (highlighter->reg_exp.indexIn(txt, 0) < 0) { return false; } return true; } void LogViewWidget::sl_openSettingsDialog() { AppContext::getAppSettingsGUI()->showSettingsDialog(APP_SETTINGS_GUI_LOG); } void LogViewWidget::searchPopupMenu(const QPoint &pos) { Q_UNUSED(pos); QMenu popup; QAction *action = popup.addAction(tr("logview_set_case"), this, SLOT(setSearchCaseSensitive())); action->setCheckable(true); action->setChecked(caseSensitive); action = popup.addAction(tr("logview_use_regexp"), this, SLOT(useRegExp())); action->setCheckable(true); action->setChecked(useRegexp); popup.exec(QCursor::pos()); } void LogViewWidget::setSearchCaseSensitive() { caseSensitive = !caseSensitive; if (caseSensitive) { highlighter->reg_exp.setCaseSensitivity(Qt::CaseSensitive); } else { highlighter->reg_exp.setCaseSensitivity(Qt::CaseInsensitive); } resetText(); } void LogViewWidget::useRegExp() { useRegexp = !useRegexp; if (useRegexp) { highlighter->reg_exp.setPatternSyntax(QRegExp::RegExp); } else { highlighter->reg_exp.setPattern(searchEdit->text()); highlighter->reg_exp.setPatternSyntax(QRegExp::FixedString); } resetText(); } void LogViewWidget::resetView() { QTime startTime = QTime::currentTime(); edit->clear(); original_text.clear(); QList messagesToShow; for (int i= cache->messages.size(); --i>=0;) { LogMessage* m = cache->messages[i]; if (isShown(*m)) { original_text.prepend(*m); if (!isShown(m->text)) { continue; } messagesToShow.prepend(m); if (messagesToShow.count() == MAX_VISIBLE_MESSAGES) { break; } } } foreach(LogMessage* m, messagesToShow) { edit->appendHtml(prepareText(*m)); } edit->moveCursor(QTextCursor::End); edit->moveCursor(QTextCursor::StartOfLine); edit->ensureCursorVisible(); QTime endTime = QTime::currentTime(); perfLog.trace(QString("Log view update time %1 millis").arg(startTime.msecsTo(endTime))); searchEdit->setFocus(); } void LogViewWidget::sl_onMessage(const LogMessage& msg) { checkThread(); if (isVisible()) { addMessage(msg); } } void LogViewWidget::showEvent(QShowEvent *e) { Q_UNUSED(e); assert(!connected); connect(LogServer::getInstance(), SIGNAL(si_message(const LogMessage&)), SLOT(sl_onMessage(const LogMessage&))); connected = true; resetView(); } void LogViewWidget::hideEvent(QHideEvent *e) { Q_UNUSED(e); //do not use any resources when hidden LogServer::getInstance()->disconnect(this); connected = false; edit->clear(); } bool LogViewWidget::isShown(const LogMessage& msg) { QString category = getEffectiveCategory(msg); return !category.isEmpty(); } QString LogViewWidget::getEffectiveCategory(const LogMessage& msg) const { QString result; if (cache->filter.isEmpty()) { if (!settings.activeLevelGlobalFlag[msg.level]) { return QString(); } foreach (const QString& category, msg.categories) { const LoggerSettings& cs = settings.getLoggerSettings(category); if (cs.activeLevelFlag[msg.level]) { result = category; break; } } } else { result = cache->filter.selectEffectiveCategory(msg); } return result; } void LogViewWidget::setSettings(const LogSettings& s) { if (settings == s) { return; } LogSettingsHolder::setSettings(s); resetView(); } QString LogViewWidget::prepareText(const LogMessage& msg) const { QString color = settings.enableColor? settings.levelColors[msg.level] : QString(); QString prefix = "[" + settings.logPattern + "]"; QString category = settings.showCategory ? "[" + getEffectiveCategory(msg) + "]" : QString(); QString level = settings.showLevel ? "[" + LogCategories::getLocalizedLevelName(msg.level) + "]" : QString(); QStringList date = GTimer::createDateTime(msg.time).toString("yyyy:yy:MM:dd:hh:mm:ss:zz").split(":"); prefix.replace("YYYY", date[0]); prefix.replace("YY", date[1]); prefix.replace("MM", date[2]); prefix.replace("dd", date[3]); prefix.replace("hh", date[4]); prefix.replace("mm", date[5]); prefix.replace("ss", date[6]); prefix.replace("zzz", date[7]); prefix.prepend(level); prefix.prepend(category); QString spacing = prefix.isEmpty() ? QString() : QString(" "); QString text = "" + prefix + spacing + msg.text +"
    "; return text; } void LogViewWidget::addMessage(const LogMessage& msg) { if (!isShown(msg)) { return; } original_text.append(msg); addText(prepareText(msg)); } void LogViewWidget::addText(const QString& txt) { if (!isShown(txt)) { return; } edit->appendHtml(txt); edit->moveCursor(QTextCursor::End); edit->moveCursor(QTextCursor::StartOfLine); edit->ensureCursorVisible(); } void LogViewWidget::sl_logSettingsChanged() { if (isVisible()) { resetView(); } } void LogViewWidget::sl_dumpCounters() { QString text = "Counters report start ***********************\n"; original_text.append(text); addText(text); foreach(GCounter* c, GCounter::allCounters()) { double val = c->scaledTotal(); text = c->name + " " + QString::number(val) + " " + c->suffix; original_text.append(text); addText(text); } text = "Counters report end ***********************\n"; original_text.append(text); addText(text); } void LogViewWidget::sl_addSeparator() { QString text = "\n==================================================\n"; original_text.append(text); addText(text); } void LogViewWidget::sl_clear() { cache->messages.clear(); edit->clear(); original_text.clear(); } void LogViewWidget::setSearchBoxMode(LogViewSearchBoxMode mode) { if (mode == LogViewSearchBox_Visible) { searchEdit->setVisible(true); } else { searchEdit->setVisible(false); } } }//namespace ugene-1.9.8/src/corelibs/U2Gui/src/util_gui/SaveDocumentGroupController.cpp0000644000175000017500000000746011651544333025444 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "SaveDocumentGroupController.h" #include #include #include #include #include namespace U2 { SaveDocumentGroupController::SaveDocumentGroupController(const SaveDocumentGroupControllerConfig& _conf, QObject* _parent) : QObject(_parent) { conf = _conf; if (conf.saveTitle.isEmpty()) { conf.saveTitle = tr("Select file location"); } assert(conf.parentWidget!=NULL); conf.fileNameEdit->setText(conf.defaultFileName); comboController = new DocumentFormatComboboxController(this, conf.formatCombo, conf.dfc, conf.defaultFormatId); connect(conf.fileNameEdit, SIGNAL(textChanged(const QString&)), SLOT(sl_fileNameChanged(const QString&))); connect(conf.fileDialogButton, SIGNAL(clicked()), SLOT(sl_saveButtonClicked())); connect(comboController->comboBox(), SIGNAL(currentIndexChanged ( const QString& )), SLOT(sl_formatChanged(const QString&))); } void SaveDocumentGroupController::sl_fileNameChanged(const QString& newName) { GUrl url(newName); QString ext = GUrlUtils::getUncompressedExtension(url); DocumentFormatRegistry* formatRegistry = AppContext::getDocumentFormatRegistry(); DocumentFormat* df = formatRegistry->selectFormatByFileExtension(ext); if (df!=NULL && df->checkConstraints(conf.dfc)) { comboController->setActiveFormatId(df->getFormatId()); } } DocumentFormatId SaveDocumentGroupController::getFormatIdToSave() const { return comboController->getActiveFormatId(); } DocumentFormat* SaveDocumentGroupController::getFormatToSave() const { DocumentFormatId id = getFormatIdToSave(); if (id.isEmpty()) { return NULL; } return AppContext::getDocumentFormatRegistry()->getFormatById(id); } void SaveDocumentGroupController::sl_saveButtonClicked() { //prepare filters QString filter = DialogUtils::prepareDocumentsFileFilter(conf.dfc, false); // find the default one QString selectedFilterExt = "*." + getFormatToSave()->getSupportedDocumentFileExtensions().first(); QString selectedFilter; foreach (QString filterLine, filter.split(";;")) { if (filterLine.contains(selectedFilterExt)) { selectedFilter = filterLine; break; } } // show the dialog LastOpenDirHelper lod; lod.url = QFileDialog::getSaveFileName(conf.parentWidget, conf.saveTitle, lod, filter, &selectedFilter); if (lod.url.isEmpty()) { return; } conf.fileNameEdit->setText(lod.url); } void SaveDocumentGroupController::sl_formatChanged( const QString& ) { if (conf.fileNameEdit->text().isEmpty()) { return; } DocumentFormatId id = comboController->getActiveFormatId(); QString fileExt = AppContext::getDocumentFormatRegistry()->getFormatById(id)->getSupportedDocumentFileExtensions().first(); GUrl url = conf.fileNameEdit->text(); conf.fileNameEdit->setText(QString("%1/%2.%3").arg(url.dirPath()).arg(url.baseFileName()).arg(fileExt)); } } //namespace ugene-1.9.8/src/corelibs/U2Gui/src/util_gui/DocumentFormatComboboxController.h0000644000175000017500000000403211651544333026107 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_DOCUMENT_FORMAT_COMBOBOX_CONTROLLER_H_ #define _U2_DOCUMENT_FORMAT_COMBOBOX_CONTROLLER_H_ #include #include namespace U2 { class U2GUI_EXPORT DocumentFormatComboboxController : public QObject { Q_OBJECT public: DocumentFormatComboboxController(QObject* p, QComboBox* combo, const DocumentFormatConstraints& c, DocumentFormatId active = DocumentFormatId::null); void updateConstraints(const DocumentFormatConstraints& c); DocumentFormatId getActiveFormatId() const; void setActiveFormatId(DocumentFormatId); bool hasSelectedFormat() const {return !getActiveFormatId().isNull();} QList getFormatsInCombo(); QComboBox* comboBox() { return combo; } static void fill(QComboBox* combo, QList& ids, DocumentFormatId active); static DocumentFormatId getActiveFormatId(QComboBox* combo); static QList getFormatsInCombo(QComboBox* combo); private slots: void sl_onDocumentFormatRegistered(DocumentFormat*); void sl_onDocumentFormatUnregistered(DocumentFormat*); private: void updateCombo(DocumentFormatId active); QComboBox* combo; DocumentFormatConstraints c; }; } #endif ugene-1.9.8/src/corelibs/U2Gui/src/util_gui/EditQualifierDialog.cpp0000644000175000017500000000554611651544333023640 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "EditQualifierDialog.h" #include #include #include namespace U2 { EditQualifierDialog::EditQualifierDialog(QWidget* p, const U2Qualifier& q, bool ro, bool existingQualifier) : QDialog(p) { ui = new Ui_EditQualifierDialog; ui->setupUi(this); if(true == ro){ this->setWindowTitle(tr("View qualifier")); } if( !existingQualifier ) { // adding new qualifier setWindowTitle("Add new qualifier"); } ui->nameEdit->setReadOnly(ro); ui->valueEdit->setReadOnly(ro); ui->nameEdit->setText(q.name); ui->valueEdit->setText(q.value); ui->valueEdit->installEventFilter(this); } bool EditQualifierDialog::eventFilter(QObject *obj, QEvent *e) { Q_UNUSED(obj); QEvent::Type t = e->type(); if (t == QEvent::KeyPress) { QKeyEvent* ke = (QKeyEvent*)e; int key = ke->key(); if (key == Qt::Key_Tab) { ui->nameEdit->setFocus(); return true; } if (key == Qt::Key_Enter || key == Qt::Key_Return) { accept(); return true; } } return false; } static QString simplify(const QString& s) { QString res = s; res = res.replace("\t", " "); res = res.replace("\r", ""); res = res.replace("\n", " "); res = res.trimmed(); return res; } void EditQualifierDialog::accept() { if (ui->nameEdit->isReadOnly()) { QDialog::accept(); return; } QString name = simplify(ui->nameEdit->text()); QString val = simplify(ui->valueEdit->toPlainText()); if (!Annotation::isValidQualifierName(name)) { QMessageBox::critical(this, tr("Error!"), tr("Illegal qualifier name")); return; } if (!Annotation::isValidQualifierValue(val)) { QMessageBox::critical(this, tr("Error!"), tr("Illegal qualifier value")); return; } q = U2Qualifier(name, val); QDialog::accept(); } EditQualifierDialog::~EditQualifierDialog() { delete ui; } }//namespace ugene-1.9.8/src/corelibs/U2Gui/src/util_gui/DocumentFormatComboboxController.cpp0000644000175000017500000001014511651544333026444 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "DocumentFormatComboboxController.h" #include namespace U2 { DocumentFormatComboboxController::DocumentFormatComboboxController(QObject* p, QComboBox* cb, const DocumentFormatConstraints& _c, DocumentFormatId active) : QObject(p), combo(cb), c(_c) { assert(combo->count()==0); DocumentFormatRegistry* fr = AppContext::getDocumentFormatRegistry(); connect(fr, SIGNAL(si_documentFormatRegistered(DocumentFormat*)), SLOT(sl_onDocumentFormatRegistered(DocumentFormat*))); connect(fr, SIGNAL(si_documentFormatUnregistered(DocumentFormat*)), SLOT(sl_onDocumentFormatUnregistered(DocumentFormat*))); updateCombo(active); } void DocumentFormatComboboxController::sl_onDocumentFormatRegistered(DocumentFormat* f) { if (!f->checkConstraints(c)) { return; } combo->addItem(QIcon(), f->getFormatName(), f->getFormatId()); } void DocumentFormatComboboxController::sl_onDocumentFormatUnregistered(DocumentFormat* f) { for (int i=0;icount();i++) { DocumentFormatId id = combo->itemData(i).toString(); if (id == f->getFormatId()) { combo->removeItem(i); return; } } } DocumentFormatId DocumentFormatComboboxController::getActiveFormatId() const { return getActiveFormatId(combo); } void DocumentFormatComboboxController::setActiveFormatId(DocumentFormatId id) { for (int i=0, n=combo->count(); iitemData(i).toString(); if (id == tmpId) { combo->setCurrentIndex(i); return; } } assert(0); } QList DocumentFormatComboboxController::getFormatsInCombo() { return getFormatsInCombo(combo); } void DocumentFormatComboboxController::updateConstraints(const DocumentFormatConstraints& _c) { c = _c; updateCombo(getActiveFormatId()); } void DocumentFormatComboboxController::updateCombo(DocumentFormatId active) { DocumentFormatRegistry* fr = AppContext::getDocumentFormatRegistry(); QList selectedFormats; foreach(DocumentFormatId id, fr->getRegisteredFormats()) { DocumentFormat* f = fr->getFormatById(id); if (f->checkConstraints(c)) { selectedFormats.append(id); } } fill(combo, selectedFormats, active); } void DocumentFormatComboboxController::fill(QComboBox* combo, QList& formatIds, DocumentFormatId active) { combo->clear(); DocumentFormatRegistry* fr = AppContext::getDocumentFormatRegistry(); foreach(DocumentFormatId id, formatIds) { DocumentFormat* f = fr->getFormatById(id); combo->addItem(QIcon(), f->getFormatName(), f->getFormatId()); if (f->getFormatId () == active) { combo->setCurrentIndex(combo->count()-1); } } combo->model()->sort(0); } DocumentFormatId DocumentFormatComboboxController::getActiveFormatId(QComboBox* combo) { int i = combo->currentIndex(); if (i==-1) { return DocumentFormatId::null; } DocumentFormatId id = combo->itemData(i).toString(); return id; } QList DocumentFormatComboboxController::getFormatsInCombo(QComboBox* combo) { QList res; for (int i = 0, n = combo->count(); i < n; i++) { DocumentFormatId id = combo->itemData(i).toString(); res.append(id); } return res; } }//namespace ugene-1.9.8/src/corelibs/U2Gui/src/util_gui/ProjectTreeItemSelectorDialog.cpp0000644000175000017500000000557111651544333025655 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "ProjectTreeItemSelectorDialog.h" #include "ProjectTreeItemSelectorDialogImpl.h" #include "ProjectTreeController.h" #include #include #include #include #include #include namespace U2 { ProjectTreeItemSelectorDialogImpl::ProjectTreeItemSelectorDialogImpl(QWidget* p, const ProjectTreeControllerModeSettings& s) : QDialog(p) { setupUi(this); controller = new ProjectTreeController(this, treeWidget, s); //TODO: fix bug with double clicking on gobject //connect(controller, SIGNAL(si_doubleClicked(GObject*)), SLOT(sl_objectClicked(GObject*))); acceptByDoubleClick = true; } void ProjectTreeItemSelectorDialogImpl::sl_objectClicked(GObject* obj) { Document* d = obj->getDocument(); assert(d != NULL); if (!d->isLoaded()) { QAction* loadSelectedDocumentsAction = controller->getLoadSeletectedDocumentsAction(); assert(loadSelectedDocumentsAction->isEnabled()); loadSelectedDocumentsAction->trigger(); return; } if (acceptByDoubleClick) { accept(); } } ProjectTreeItemSelectorDialogImpl::~ProjectTreeItemSelectorDialogImpl() { delete controller; } QList ProjectTreeItemSelectorDialog::selectDocuments(const ProjectTreeControllerModeSettings& s, QWidget* p) { QList res; ProjectTreeItemSelectorDialogImpl d(p, s); int rc = d.exec(); if (rc == QDialog::Accepted) { const DocumentSelection* ds = d.controller->getDocumentSelection(); res << ds->getSelectedDocuments(); } return res; } QList ProjectTreeItemSelectorDialog::selectObjects(const ProjectTreeControllerModeSettings& s, QWidget* p) { QList res; ProjectTreeItemSelectorDialogImpl d(p, s); int rc = d.exec(); if (rc == QDialog::Accepted) { const GObjectSelection* os = d.controller->getGObjectSelection(); res << os->getSelectedObjects(); } return res; } }//namespace ugene-1.9.8/src/corelibs/U2Gui/src/util_gui/SeqPasterWidgetController.cpp0000644000175000017500000001103211651544333025073 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include"SeqPasterWidgetController.h" #include "ui/ui_SeqPasterWidget.h" #include #include namespace U2{ SeqPasterWidgetController::SeqPasterWidgetController( QWidget *p, const QByteArray& initText ): QWidget(p), preferred(0) { ui = new Ui_SeqPasterWidget; //TODO: add not null project checking ui->setupUi(this); if (!initText.isEmpty()) { ui->sequenceEdit->setPlainText(initText); } QList alps = AppContext::getDNAAlphabetRegistry()->getRegisteredAlphabets(); foreach(DNAAlphabet *a, alps){ ui->alphabetBox->addItem(a->getName(), a->getId()); } connect(ui->alphabetBox, SIGNAL(currentIndexChanged(const QString&)), SLOT(sl_currentindexChanged(const QString&))); } QByteArray SeqPasterWidgetController::getNormSequence(DNAAlphabet * alph, const QByteArray & seq, bool replace, QChar replaceChar) { assert(alph != NULL); QByteArray ret; if(alph->getId() == BaseDNAAlphabetIds::RAW()){ foreach(QChar c, seq){ QChar::Category cat = c.category(); if((cat != QChar::Separator_Space) && (cat != QChar::Other_Control)){ ret.append(c); } } }else{ QByteArray alphabetSymbols = alph->getAlphabetChars(true); for(int i = 0; i < seq.size(); i++){ QChar c = seq.at(i); if(alphabetSymbols.indexOf(c) > -1){ ret.append(c); }else{ if (replace){ ret.append(replaceChar); } } } } if(!alph->isCaseSensitive()){ ret = ret.toUpper(); } return ret; } QString SeqPasterWidgetController::validate(){ if(ui->sequenceEdit->toPlainText().isEmpty()){ return tr("Input sequence is empty"); } bool replace = ui->replaceRB->isChecked(); if(replace && ui->symbolToReplaceEdit->text().isEmpty()) { return tr("Replace symbol is empty"); } QByteArray seq = ((ui->sequenceEdit->document())->toPlainText()).toUtf8(); seq=QString(seq).remove(QRegExp("\\s")).toAscii(); DNAAlphabetRegistry *r = AppContext::getDNAAlphabetRegistry(); DNAAlphabet *alph = NULL; if(ui->useCustomSettingsBox->isChecked()){ alph = r->findById((ui->alphabetBox->itemData(ui->alphabetBox->currentIndex())).toString()); }else{ if(preferred != NULL){ alph = preferred; }else{ alph = r->findAlphabet(seq); } } if(alph == NULL){ return tr("Alphabet not detected"); } QChar replaceChar = replace ? ui->symbolToReplaceEdit->text().at(0) : QChar(); QByteArray normSequence = getNormSequence(alph, seq, replace, replaceChar); resultSeq = DNASequence("New Sequence", normSequence, alph); return QString(); } void SeqPasterWidgetController::sl_currentindexChanged( const QString& newText){ DNAAlphabetRegistry *r = AppContext::getDNAAlphabetRegistry(); if((r->findById(BaseDNAAlphabetIds::RAW()))->getName() == newText){ ui->skipRB->setDisabled(true); ui->replaceRB->setDisabled(true); ui->symbolToReplaceEdit->setDisabled(true); }else{ ui->skipRB->setEnabled(true); ui->replaceRB->setEnabled(true); ui->symbolToReplaceEdit->setEnabled(true); } } void SeqPasterWidgetController::disableCustomSettings(){ ui->useCustomSettingsBox->setChecked(false); ui->useCustomSettingsBox->setDisabled(true); ui->useCustomSettingsBox->hide(); ui->groupBox->hide(); } void SeqPasterWidgetController::setPreferredAlphabet( DNAAlphabet *alp ){ preferred = alp; } SeqPasterWidgetController::~SeqPasterWidgetController() { delete ui; } }//ns ugene-1.9.8/src/corelibs/U2Gui/src/util_gui/AddNewDocumentDialogImpl.cpp0000644000175000017500000001255011651544333024565 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "AddNewDocumentDialogImpl.h" #include "DocumentFormatComboboxController.h" #include #include #include #include #include #include #include #include #include namespace U2 { //BUG:419: add label to dialog with state description! #define SETTINGS_LASTFORMAT "add_new_document/last_format" #define SETTINGS_LASTDIR "add_new_document/last_dir" AddNewDocumentDialogImpl::AddNewDocumentDialogImpl(QWidget* p, AddNewDocumentDialogModel& m, const DocumentFormatConstraints& c) : QDialog(p), model(m) { setupUi(this); if (model.format.isEmpty()) { model.format = AppContext::getSettings()->getValue(SETTINGS_LASTFORMAT, QString("")).toString(); } documentURLEdit->setText(model.url); formatController = new DocumentFormatComboboxController(this, documentTypeCombo, c, model.format); model.successful = false; connect(documentURLButton, SIGNAL(clicked()), SLOT(sl_documentURLButtonClicked())); connect(createButton, SIGNAL(clicked()), SLOT(sl_createButtonClicked())); connect(documentURLEdit, SIGNAL(editingFinished()), SLOT(sl_documentURLEdited())); connect(documentTypeCombo, SIGNAL(currentIndexChanged(int)), SLOT(sl_typeComboCurrentChanged(int))); connect(gzipCheckBox, SIGNAL(toggled(bool)), SLOT(sl_gzipChecked(bool))); updateState(); } void AddNewDocumentDialogController::run(QWidget* p, AddNewDocumentDialogModel& m, const DocumentFormatConstraints& c) { Project* proj = AppContext::getProject(); if (proj->isStateLocked()) { QMessageBox::critical(NULL, L10N::errorTitle(), AddNewDocumentDialogImpl::tr("Project is locked")); m.successful = false; return; } AddNewDocumentDialogImpl d(p, m, c); d.exec(); m = d.model; assert(proj->findDocumentByURL(m.url) == NULL); } void AddNewDocumentDialogImpl::updateState() { bool ready = formatController->hasSelectedFormat(); if (ready) { const QString& url = currentURL(); ready = !url.isEmpty() && QFileInfo(url).absoluteDir().exists(); if (ready) { Project* p = AppContext::getProject(); ready = p->findDocumentByURL(url) == NULL; } } createButton->setDisabled(!ready); } QString AddNewDocumentDialogImpl::currentURL() { QString url = documentURLEdit->text(); if (url.isEmpty()) { return url; } bool extOk = false; QString extraExt = ".gz"; if (url.endsWith(extraExt)) { url.chop(extraExt.size()); } DocumentFormatId fid = formatController->getActiveFormatId(); DocumentFormat* df = AppContext::getDocumentFormatRegistry()->getFormatById(fid); if (df) { foreach(QString ext, df->getSupportedDocumentFileExtensions()) { if (url.endsWith(ext)) { extOk = true; break; } } if (!extOk) { url+="."+df->getSupportedDocumentFileExtensions().first(); } } if (gzipCheckBox->isChecked()) { url += extraExt; } documentURLEdit->setText(url); QFileInfo fi(url); return fi.absoluteFilePath(); } void AddNewDocumentDialogImpl::sl_documentURLButtonClicked() { QString url = currentURL(); if (url.isEmpty()) { url = AppContext::getSettings()->getValue(SETTINGS_LASTDIR, QString("")).toString(); } QString filter = DialogUtils::prepareDocumentsFileFilter(formatController->getActiveFormatId(), false); QString name = QFileDialog::getSaveFileName(this, tr("Save file"), url, filter); if (!name.isEmpty()) { documentURLEdit->setText(name); AppContext::getSettings()->setValue(SETTINGS_LASTDIR, QFileInfo(name).absoluteDir().absolutePath()); updateState(); } } void AddNewDocumentDialogImpl::sl_createButtonClicked() { model.format = formatController->getActiveFormatId(); assert(!model.format.isEmpty()); model.url = currentURL(); model.io = gzipCheckBox->isChecked() ? BaseIOAdapters::GZIPPED_LOCAL_FILE : BaseIOAdapters::LOCAL_FILE; model.successful = true; AppContext::getSettings()->setValue(SETTINGS_LASTFORMAT, model.format); accept(); } void AddNewDocumentDialogImpl::sl_documentURLEdited() { updateState(); } void AddNewDocumentDialogImpl::sl_typeComboCurrentChanged(int i) { Q_UNUSED(i); QString url = documentURLEdit->text(); if (!url.isEmpty()) { /* chop obsolete extensions */ if (gzipCheckBox->isChecked() && url.endsWith(".gz")) { url.chop(3); } int dot = url.lastIndexOf('.'); if (dot > 0) { url.chop(url.size() - dot); } documentURLEdit->setText(url); } updateState(); } void AddNewDocumentDialogImpl::sl_gzipChecked(bool on) { Q_UNUSED(on); updateState(); } }//namespace ugene-1.9.8/src/corelibs/U2Gui/src/util_gui/EditSequenceDialogController.cpp0000644000175000017500000001351011651544333025521 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "EditSequenceDialogController.h" #include "ui/ui_EditSequenceDialog.h" #include #include #include #include #include #include #include namespace U2{ EditSequenceDialogController::EditSequenceDialogController( EditSequencDialogConfig cfg, QWidget* p) : QDialog(p), filter(""), pos(1), config(cfg) { ui = new Ui_EditSequenceDialog; ui->setupUi(this); connect(ui->browseButton, SIGNAL(clicked()), SLOT(sl_browseButtonClicked())); addSeqpasterWidget(); w->disableCustomSettings(); w->setPreferredAlphabet(cfg.alphabet); if (cfg.mode == EditSequenceMode_Insert) { setWindowTitle(tr("Insert sequence")); } else { setWindowTitle(tr("Replace sequence")); ui->splitRB->setEnabled(false); //ui->insertPositionSpin->setEnabled(false); ui->insertPositionBox->setEnabled(false); } ui->insertPositionSpin->setMinimum(1); ui->insertPositionSpin->setMaximum(cfg.source.length + 1); connect(ui->formatBox, SIGNAL(currentIndexChanged(int)), this, SLOT(sl_indexChanged(int))); ui->formatBox->addItem("FASTA", BaseDocumentFormats::PLAIN_FASTA); ui->formatBox->addItem("Genbank", BaseDocumentFormats::PLAIN_GENBANK); connect(ui->mergeAnnotationsBox, SIGNAL(toggled(bool)), this, SLOT(sl_mergeAnnotationsToggled(bool))); sl_indexChanged(0); } void EditSequenceDialogController::accept(){ QString validationError = w->validate(); if(!validationError.isEmpty()){ QMessageBox::critical(this, this->windowTitle(), validationError); return; } if (w->getSequence().seq == config.initialText && config.mode == EditSequenceMode_Replace ) { QDialog::reject(); return; } if(!modifyCurrentDocument()){ QFileInfo fi(ui->filepathEdit->text()); QDir dirToSave(fi.dir()); if (!dirToSave.exists()){ QMessageBox::critical(this, this->windowTitle(), tr("Directory to save is not exists")); return; } if(ui->filepathEdit->text().isEmpty()){ QMessageBox::critical(this, this->windowTitle(), tr("Entered path is empty")); return; } if(fi.baseName().isEmpty()){ QMessageBox::critical(this, this->windowTitle(), tr("Filename is empty")); return; } } pos = ui->insertPositionSpin->value() - 1; QDialog::accept(); } void EditSequenceDialogController::addSeqpasterWidget(){ w = new SeqPasterWidgetController(this, config.initialText); ui->globalLayout->insertWidget(0, w); } void EditSequenceDialogController::sl_browseButtonClicked(){ LastOpenDirHelper h; h.url = QFileDialog::getSaveFileName(this, tr("Select file to save..."), h.dir, filter); ui->filepathEdit->setText(h.url); sl_indexChanged(ui->formatBox->currentIndex()); } U2AnnotationUtils::AnnotationStrategyForResize EditSequenceDialogController::getAnnotationStrategy() { if(ui->resizeRB->isChecked()){ return U2AnnotationUtils::AnnotationStrategyForResize_Resize; }else if(ui->splitRB->isChecked()){ return U2AnnotationUtils::AnnotationStrategyForResize_Split; }else{ assert(ui->removeRB->isChecked()); return U2AnnotationUtils::AnnotationStrategyForResize_Remove; } } void EditSequenceDialogController::sl_indexChanged( int index){ DocumentFormatId currentId = (ui->formatBox->itemData(index)).toString(); filter = DialogUtils::prepareDocumentsFileFilter(currentId, false); DocumentFormat *df = AppContext::getDocumentFormatRegistry()->getFormatById(currentId); QString newExt = df->getSupportedDocumentFileExtensions().first(); QString filepath = ui->filepathEdit->text(); if (filepath.isEmpty()){ return; } QFileInfo fi(filepath); ui->filepathEdit->setText(fi.absoluteDir().absolutePath() + "/" + fi.baseName() + "." + newExt); } void EditSequenceDialogController::sl_mergeAnnotationsToggled( bool state){ Q_UNUSED(state); if(ui->mergeAnnotationsBox->isChecked()){ ui->formatBox->removeItem(ui->formatBox->findText("FASTA")); }else{ ui->formatBox->addItem("FASTA", BaseDocumentFormats::PLAIN_FASTA); } sl_indexChanged(ui->formatBox->findText("Genbank")); } GUrl EditSequenceDialogController::getDocumentPath() { if (modifyCurrentDocument()) { return GUrl(); } else { return GUrl(ui->filepathEdit->text()); } } EditSequenceDialogController::~EditSequenceDialogController() { delete ui; } bool EditSequenceDialogController::mergeAnnotations() { return (ui->mergeAnnotationsBox->isChecked() && !modifyCurrentDocument()); } U2::DocumentFormatId EditSequenceDialogController::getDocumentFormatId() { return ui->formatBox->itemData(ui->formatBox->currentIndex()).toString(); } bool EditSequenceDialogController::modifyCurrentDocument() { return !ui->saveToAnotherBox->isChecked(); } } // U2 ugene-1.9.8/src/corelibs/U2Gui/src/util_gui/CreateObjectRelationDialogController.cpp0000644000175000017500000000647311651544333027205 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "CreateObjectRelationDialogController.h" #include #include #include #include #include #include #include namespace U2 { CreateObjectRelationDialogController::CreateObjectRelationDialogController(GObject* _assObj, const QList& _objects, const QString& _role, bool rd, const QString& relationHint, QWidget* p) : QDialog(p), selectedObject(NULL), assObj(_assObj), objects(_objects), role(_role), removeDuplicates(rd) { assert(!objects.isEmpty()); assert(!role.isEmpty()); assert(assObj!=NULL); ui = new Ui_CreateObjectRelationDialog; ui->setupUi(this); QIcon objectIcon(":/core/images/gobject.png"); foreach(GObject* obj, objects) { ui->listWidget->addItem(new QListWidgetItem(objectIcon, obj->getGObjectName())); } ui->listWidget->setItemSelected(ui->listWidget->item(0), true); ui->relationHintLabel->setText(relationHint); } void CreateObjectRelationDialogController::accept() { int idx = ui->listWidget->currentRow(); assert(idx>=0 && idx < objects.size()); GObject* selObj = objects[idx]; if (role == GObjectRelationRole::SEQUENCE && assObj->getGObjectType() == GObjectTypes::ANNOTATION_TABLE) { DNASequenceObject* dnaObj = qobject_cast(selObj); AnnotationTableObject* ao = qobject_cast(assObj); AnnotationTableObjectConstraints c; c.sequenceSizeToFit = dnaObj->getSequenceLen(); bool res = ao->checkConstraints(&c); if (!res) { int rc = QMessageBox::question(this, tr("Warning"), tr("Found annotations that are out of the sequence range, continue?"), QMessageBox::Yes, QMessageBox::No); if (rc == QMessageBox::No) { return; } } if (removeDuplicates) { QList oldRel = assObj->findRelatedObjectsByRole(role); foreach(const GObjectRelation& r, oldRel) { assObj->removeObjectRelation(r); } } assObj->addObjectRelation(selObj, role); } selectedObject = selObj; QDialog::accept(); } CreateObjectRelationDialogController::~CreateObjectRelationDialogController() { delete ui; } }//namespace ugene-1.9.8/src/corelibs/U2Gui/src/util_gui/ExportImageDialog.h0000644000175000017500000000455311651544333022777 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_EXPORT_IMAGE_DIALOG_H_ #define _U2_EXPORT_IMAGE_DIALOG_H_ #include #include #include #include class Ui_ImageExportForm; namespace U2 { class U2GUI_EXPORT ExportImageDialog : public QDialog { Q_OBJECT public: ExportImageDialog(QWidget* widget, bool showSizeRuler=false, bool useVectorFormats=false, const QString& file = QString("untitled")); ExportImageDialog(QWidget* widget, QRect rect, bool showSizeRuler=false, bool useVectorFormats=false, const QString& file = QString("untitled")); virtual bool exportToSVG(); virtual bool exportToPDF(); virtual bool exportToBitmap(); const QString& getFilename(){return filename;} const QString& getFormat(){return format;} bool hasQuality(); int getWidth(); int getHeight(); int getQuality(); public slots: virtual void accept(); private slots: void sl_onBrowseButtonClick(); void sl_onFormatsBoxItemChanged(const QString& text); private: void setupComponents(); void setSizeControlsEnabled(bool enabled); static bool isVectorGraphicFormat(const QString& formatName); static int getVectorFormatIdByName(const QString& formatName); private: QList supportedFormats; QWidget* widget; QString filename; QString origFilename; QString format; LastOpenDirHelper lod; Ui_ImageExportForm* ui; QRect rect; bool showSizeRuler; bool useVectorFormats; }; // class ExportImageDialog } // namespace #endif ugene-1.9.8/src/corelibs/U2Gui/src/util_gui/SeqPasterWidgetController.h0000644000175000017500000000332011651544333024541 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_SEQ_PASTER_WIDGET_CONTROLLER_H_ #define _U2_SEQ_PASTER_WIDGET_CONTROLLER_H_ #include #include #include class Ui_SeqPasterWidget; namespace U2{ class U2GUI_EXPORT SeqPasterWidgetController : public QWidget { Q_OBJECT public: SeqPasterWidgetController(QWidget *p = NULL, const QByteArray& initText = QByteArray()); ~SeqPasterWidgetController(); QString validate(); DNASequence getSequence() const {return resultSeq;} void disableCustomSettings(); void setPreferredAlphabet(DNAAlphabet *alp); static QByteArray getNormSequence(DNAAlphabet * alph, const QByteArray & seq, bool replace, QChar replaceChar); private slots: void sl_currentindexChanged(const QString&); private: DNAAlphabet *preferred; DNASequence resultSeq; Ui_SeqPasterWidget* ui; }; }//ns #endif ugene-1.9.8/src/corelibs/U2Gui/src/util_gui/GUIUtils.cpp0000644000175000017500000001354511651544333021434 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "GUIUtils.h" #include #include #include #include #include #include #include #include #include #include #include #include namespace U2 { QAction* GUIUtils::findAction(const QList& actions, const QString& name) { foreach(QAction* a, actions) { const QString& aname = a->objectName(); if (aname == name) { return a; } } return NULL; } QAction* GUIUtils::findActionAfter(const QList& actions, const QString& name) { bool found = false; foreach(QAction* a, actions) { if (found) { return a; } const QString& aname = a->objectName(); if (aname == name) { found = true; } } if (found) { return NULL; } return actions.first(); } QMenu* GUIUtils::findSubMenu(QMenu* m, const QString& name) { QAction* action = findAction(m->actions(), name); if (action == NULL) { return NULL; } return action->menu(); } void GUIUtils::disableEmptySubmenus(QMenu* m) { foreach(QAction* action, m->actions()) { QMenu* am = action->menu(); if (am!=NULL && am->actions().isEmpty()) { action->setEnabled(false); } } } QIcon GUIUtils::createSquareIcon(const QColor& c, int size) { int w = size; int h = size; QPixmap pix(w, h); QPainter p(&pix); p.setPen(Qt::black); p.drawRect(0, 0, w-1, h-1); p.fillRect(1, 1, w-2, h-2, c); p.end(); return QIcon(pix); } QIcon GUIUtils::createRoundIcon(const QColor& c, int size) { int w = size; int h = size; QPixmap pix(w, h); pix.fill(Qt::transparent); QPainter p(&pix); QPainterPath ep; //ep.addEllipse(1, 1, w-2, h-2); ep.addEllipse(0, 0, w-1, h-1); p.fillPath(ep, c); p.setPen(Qt::black); p.drawEllipse(0, 0, w-1, h-1); p.end(); return QIcon(pix); } bool GUIUtils::runWebBrowser(const QString& url) { bool useDefaultWebBrowser = AppContext::getAppSettings()->getUserAppsSettings()->useDefaultWebBrowser(); if (url.isEmpty()) { QMessageBox::critical(NULL, tr("Error!"), tr("Document URL is empty!")); return false; } QString program = AppContext::getAppSettings()->getUserAppsSettings()->getWebBrowserURL(); bool ok = !program.isEmpty() && QFile(program).exists(); if(useDefaultWebBrowser){ bool launched = QDesktopServices::openUrl(QUrl(url)); if (!launched){ QMessageBox::critical(NULL, tr("Error!"), tr("Unable to launch default web browser.")); AppContext::getAppSettings()->getUserAppsSettings()->setUseDefaultWebBrowser(false); AppContext::getAppSettingsGUI()->showSettingsDialog(APP_SETTINGS_USER_APPS); program = AppContext::getAppSettings()->getUserAppsSettings()->getWebBrowserURL(); ok = !program.isEmpty() && QFile(program).exists(); if (!ok) { return false; } QString p = program; QStringList arguments; arguments.append(url); QProcess myProcess; return myProcess.startDetached(program, arguments); }else { return launched; } }else{ if (!ok) { QMessageBox::critical(NULL, tr("Error!"), tr("Please specify the browser executable")); AppContext::getAppSettingsGUI()->showSettingsDialog(APP_SETTINGS_USER_APPS); program = AppContext::getAppSettings()->getUserAppsSettings()->getWebBrowserURL(); ok = !program.isEmpty() && QFile(program).exists(); } if (!ok) { return false; } QString p = program; QStringList arguments; arguments.append(url); QProcess myProcess; return myProcess.startDetached(program, arguments); } } bool GUIUtils::isMutedLnF(QTreeWidgetItem* item) { static QBrush disabledBrush; if (disabledBrush.style() == Qt::NoBrush) { disabledBrush = QApplication::palette().brush(QPalette::Disabled, QPalette::Foreground); } return item->foreground(0) == disabledBrush; } void GUIUtils::setMutedLnF( QTreeWidgetItem* item, bool enableMute, bool recursive) { QPalette::ColorGroup colorGroup = enableMute ? QPalette::Disabled : QPalette::Active; QBrush brush = QApplication::palette().brush(colorGroup, QPalette::Foreground); int count = item->columnCount(); for (int column = 0; column < count; column++) { item->setForeground(column, brush); } if (recursive) { int childCount = item->childCount(); for (int i = 0; i < childCount; ++i) { QTreeWidgetItem* childItem = item->child(i); if (!isMutedLnF(childItem)) { setMutedLnF(childItem, enableMute, recursive); } } } } } //endif ugene-1.9.8/src/corelibs/U2Gui/src/util_gui/CreateDocumentFromTextDialogController.cpp0000644000175000017500000001713011651544333027540 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "CreateDocumentFromTextDialogController.h" #include "ui/ui_CreateDocumentFromTextDialog.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include namespace U2{ CreateDocumentFromTextDialogController::CreateDocumentFromTextDialogController(QWidget* p): QDialog(p) { ui = new Ui_CreateDocumentFromTextDialog(); ui->setupUi(this); //TODO: use format name here ui->formatBox->addItem("FASTA", BaseDocumentFormats::PLAIN_FASTA); ui->formatBox->addItem("Genbank", BaseDocumentFormats::PLAIN_GENBANK); connect(ui->browseButton, SIGNAL(clicked()), SLOT(sl_browseButtonClicked())); connect(ui->formatBox, SIGNAL(currentIndexChanged(int)), this, SLOT(sl_indexChanged(int))); connect(ui->filepathEdit, SIGNAL(textChanged ( const QString &)), this, SLOT(sl_filepathTextChanged(const QString &))); ui->nameEdit->setText("Sequence"); sl_indexChanged(0); addSeqPasterWidget(); } void CreateDocumentFromTextDialogController::sl_browseButtonClicked(){ LastOpenDirHelper h; h.url = QFileDialog::getSaveFileName(this, tr("Select file to save..."), h.dir, filter); ui->filepathEdit->setText(QDir::toNativeSeparators(h.url)); sl_indexChanged(ui->formatBox->currentIndex()); } void CreateDocumentFromTextDialogController::accept(){ QString validationError = w->validate(); if(!validationError.isEmpty()){ QMessageBox::critical(this, this->windowTitle(), validationError); return; } QFileInfo fi(ui->filepathEdit->text()); if(fi.baseName().isEmpty()){ QMessageBox::critical(this, this->windowTitle(), tr("Filename is empty")); return; } if(ui->filepathEdit->text().isEmpty()){ QMessageBox::critical(this, this->windowTitle(), tr("No path specified")); return; } QString errorMessage; QString fullPath = GUrlUtils::prepareFileLocation(ui->filepathEdit->text(), errorMessage); if (fullPath.isEmpty()) { QMessageBox::critical(this, L10N::errorTitle(), errorMessage); return; } if(ui->nameEdit->text().isEmpty()) { QMessageBox::critical(this, this->windowTitle(), tr("Sequence name is empty")); return; } if(AppContext::getProject() == NULL) { Task * openProj = AppContext::getProjectLoader()->createNewProjectTask(); connect(openProj, SIGNAL(si_stateChanged()), this, SLOT(sl_projectLoaded())); AppContext::getTaskScheduler()->registerTopLevelTask(openProj); return; } acceptWithExistingProject(); } void CreateDocumentFromTextDialogController::sl_projectLoaded() { Task * openProjTask = qobject_cast(sender()); assert(openProjTask != NULL); if(openProjTask->getState() != Task::State_Finished) { return; } if( AppContext::getProject() == NULL ) { QMessageBox::warning(this, tr("Error"), tr("The project cannot be created")); close(); QDialog::reject(); return; } acceptWithExistingProject(); } void CreateDocumentFromTextDialogController::acceptWithExistingProject() { Project *p = AppContext::getProject(); QString errorMessage; Q_UNUSED(errorMessage); QString fullPath = GUrlUtils::prepareFileLocation(ui->filepathEdit->text(), errorMessage); GUrl url(fullPath); Document *loadedDoc=p->findDocumentByURL(url); if (loadedDoc) { coreLog.details("The document already in the project"); QMessageBox::warning(this, tr("warning"), tr("The document already in the project")); return; } QList objects; const QString seqName(ui->nameEdit->text()); DNASequence seq = w->getSequence(); QVariantMap hints; U2OpStatusImpl os; DocumentFormatUtils::addSequenceObject(objects, seqName, seq, hints, os); SAFE_POINT_OP(os,); IOAdapterFactory* iof = AppContext::getIOAdapterRegistry()->getIOAdapterFactoryById(BaseIOAdapters::url2io(ui->filepathEdit->text())); QVariant currentId = ui->formatBox->itemData(ui->formatBox->currentIndex()); DocumentFormat *df = AppContext::getDocumentFormatRegistry()->getFormatById(currentId.toString()); doc = new Document(df, iof, fullPath, objects); doc->setModified(true); p->addDocument(doc); if(ui->saveImmediatelyBox->isChecked()){ AppContext::getTaskScheduler()->registerTopLevelTask(new SaveDocumentTask(doc, doc->getIOAdapterFactory(), doc->getURL())); } // Open view for created document DocumentSelection ds; ds.setSelection(QList() <getAllFactories()) { if(f->canCreateView(ms)) { AppContext::getTaskScheduler()->registerTopLevelTask(f->createViewTask(ms)); break; } } this->close(); QDialog::accept(); } void CreateDocumentFromTextDialogController::reject(){ QDialog::reject(); this->close(); } void CreateDocumentFromTextDialogController::addSeqPasterWidget(){ w = new SeqPasterWidgetController(this); ui->verticalLayout->insertWidget(0, w); } void CreateDocumentFromTextDialogController::sl_indexChanged( int index ){ DocumentFormatId currentId = (ui->formatBox->itemData(index)).toString(); filter = DialogUtils::prepareDocumentsFileFilter(currentId, false); DocumentFormat *df = AppContext::getDocumentFormatRegistry()->getFormatById(currentId); QString newExt = df->getSupportedDocumentFileExtensions().first(); QString filepath = ui->filepathEdit->text(); if (filepath.isEmpty()){ return; } QFileInfo fi(filepath); ui->filepathEdit->setText(fi.absoluteDir().absolutePath() + "/" + fi.baseName() + "." + newExt); } CreateDocumentFromTextDialogController::~CreateDocumentFromTextDialogController() { delete ui; } void CreateDocumentFromTextDialogController::sl_filepathTextChanged( const QString &text ){ QFileInfo newFile(text); if(ui->nameEdit->text() != newFile.baseName()){ newFile.baseName().isEmpty() ? ui->nameEdit->setText("Sequence") : ui->nameEdit->setText(newFile.baseName()); } } }//ns ugene-1.9.8/src/corelibs/U2Gui/src/util_gui/ProjectTreeController.h0000644000175000017500000002427411651544333023727 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_PROJECT_TREE_CONTROLLER_H_ #define _U2_PROJECT_TREE_CONTROLLER_H_ #include #include #include #include #include #include #include #include namespace U2 { class Task; class GObjectConstraints; class MWMDIWindow; class ProjViewItem; class ProjViewDocumentItem; class ProjViewTypeItem; class ProjViewObjectItem; class GObjectView; class U2GUI_EXPORT LoadDocumentTaskProvider { public: virtual ~LoadDocumentTaskProvider(){}; virtual QList createLoadDocumentTasks(const QList& docs) const = 0; }; enum ProjectTreeGroupMode { ProjectTreeGroupMode_Flat, //objects are not grouped, only unloaded documents are shown ProjectTreeGroupMode_ByDocument, //objects are grouped by document ProjectTreeGroupMode_ByType, //objects are grouped by type ProjectTreeGroupMode_Min = ProjectTreeGroupMode_Flat, ProjectTreeGroupMode_Max = ProjectTreeGroupMode_ByType }; //filtered objects and documents are not shown in project tree class PTCObjectFilter : public QObject{ public: PTCObjectFilter(QObject* p = NULL) : QObject(p){} virtual bool filter(GObject* o) const = 0; }; class PTCDocumentFilter : public QObject { public: PTCDocumentFilter(QObject* p): QObject(p) {} virtual bool filter(Document* d) const = 0; }; class PTCObjectRelationFilter : public PTCObjectFilter { public: PTCObjectRelationFilter(const GObjectRelation& _rel, QObject* p = NULL) : PTCObjectFilter(p), rel(_rel){} bool filter(GObject* o) const; GObjectRelation rel; }; class U2GUI_EXPORT ProjectTreeControllerModeSettings { public: ProjectTreeControllerModeSettings() : allowMultipleSelection(true), readOnlyFilter(TriState_Unknown), loadTaskProvider(NULL), groupMode(ProjectTreeGroupMode_ByDocument), objectFilter(NULL), documentFilter(NULL), markActive(false){} QList objectTypesToShow; // show only objects of specified type QList objectConstraints; // show only objects that fits constraints QList > excludeObjectList; // do not show these objects QStringList tokensToShow; // show documents/objects with all of tokens in a name bool allowMultipleSelection; //use multiple selection in tree TriState readOnlyFilter; // unknown->all, true->filter(exclude) readonly, false -> keep only readonly LoadDocumentTaskProvider* loadTaskProvider; // use custom LoadDocumentTask factory instead of default ProjectTreeGroupMode groupMode; // group mode for objects //Note that objectFilter and documentFilter are called only on object add/remove ops! //WARN: object and document filters live-range is controlled by the side created these objects PTCObjectFilter* objectFilter; PTCDocumentFilter* documentFilter; bool markActive; QFont activeFont; bool isDocumentShown(Document* doc) const; bool isTypeShown(GObjectType t) const; bool isObjectShown(GObject* o) const ; }; class U2GUI_EXPORT ProjectTreeController : public QObject { Q_OBJECT public: ProjectTreeController(QObject* parent, QTreeWidget* tree, const ProjectTreeControllerModeSettings& mode); const DocumentSelection* getDocumentSelection() const {return &documentSelection;} const GObjectSelection* getGObjectSelection() const {return &objectSelection;} void updateSettings(const ProjectTreeControllerModeSettings& mode); QAction* getGroupByDocumentAction() const {return groupByDocumentAction;} QAction* getGroupByTypeAction() const {return groupByTypeAction;} QAction* getGroupFlatAction() const {return groupFlatAction;} QAction* getLoadSeletectedDocumentsAction() { return loadSelectedDocumentsAction; } const ProjectTreeControllerModeSettings& getModeSettings() const {return mode;} void highlightItem(Document*); protected: bool virtual eventFilter(QObject* o, QEvent* e); signals: void si_onPopupMenuRequested(QMenu& popup); void si_doubleClicked(GObject*); void si_returnPressed(GObject*); private slots: void sl_onTreeSelectionChanged(); void sl_onContextMenuRequested(const QPoint & pos); void sl_onRemoveSelectedDocuments(); void sl_onLoadSelectedDocuments(); void sl_onUnloadSelectedDocuments(); void sl_onDocumentAddedToProject(Document* d); void sl_onDocumentRemovedFromProject(Document* d); void sl_onDocumentModifiedStateChanged(); void sl_onDocumentLoadedStateChanged(); void sl_onDocumentURLorNameChanged(); void sl_onObjectAdded(GObject* o); void sl_onObjectRemoved(GObject* o); void sl_onObjectModifiedStateChanged(); void sl_onObjectNameChanged(const QString&); void sl_onItemDoubleClicked(QTreeWidgetItem * item, int column); void sl_onResourceUserRegistered(const QString& res, Task* t); void sl_onResourceUserUnregistered(const QString& res, Task* t); void sl_onLoadingDocumentProgressChanged(); void sl_onToggleReadonly(); void sl_onLockedStateChanged(); void sl_onRename(); void sl_onGroupByDocument(); void sl_onGroupByType(); void sl_onGroupFlat(); void sl_windowActivated(MWMDIWindow*); void sl_objectAddedToActiveView(GObjectView*, GObject*); void sl_objectRemovedFromActiveView(GObjectView*, GObject*); void sl_onCloseEditor(QWidget*,QAbstractItemDelegate::EndEditHint); private: void updateActions(); void updateSelection(); void connectModel(); void connectDocument(Document* d); void disconnectDocument(Document* d); void connectToResourceTracker(); void connectGObject(GObject* d); void buildTree(); void buildDocumentTree(Document* d); void flattenDocumentItem(ProjViewDocumentItem* docItem); void runLoadDocumentTasks(const QList& docs); GObjectType getLoadedObjectType(GObject* obj) const; void filterItemsRecursive(ProjViewItem* pi); QSet getDocsInSelection(bool deriveFromObjects); void insertTreeItemSorted(ProjViewItem* p, ProjViewItem* item); void updateLoadingState(Document* d); void updateObjectActiveStateVisual(GObject* o); void updateObjectVisual(GObject* obj); ProjViewDocumentItem* findDocumentItem(Document* d) const; ProjViewDocumentItem* findDocumentItem(Document* d, bool create); ProjViewObjectItem* findGObjectItem(GObject* o) const; ProjViewObjectItem* findGObjectItem(Document* d, GObject* o) const; ProjViewObjectItem* findGObjectItem(ProjViewItem* pi, GObject* o) const; ProjViewTypeItem* findTypeItem(const GObjectType& t) const; ProjViewTypeItem* findTypeItem(const GObjectType& t, bool create); QTreeWidget* tree; QAction* removeSelectedDocumentsAction; QAction* loadSelectedDocumentsAction; QAction* unloadSelectedDocumentsAction; QAction* addReadonlyFlagAction; QAction* removeReadonlyFlagAction; QAction* renameAction; QAction* groupByDocumentAction; QAction* groupByTypeAction; QAction* groupFlatAction; GObjectSelection objectSelection; DocumentSelection documentSelection; ProjectTreeControllerModeSettings mode; QSet itemsToUpdate; GObjectView* markActiveView; public: QIcon documentIcon; QIcon roDocumentIcon; }; class U2GUI_EXPORT ProjViewItem : public QTreeWidgetItem , public QObject{ public: ProjViewItem(ProjectTreeController* c) : QObject(NULL), controller(c), markedAsActive(false) {} bool isRootItem() {return QTreeWidgetItem::parent() == NULL;} virtual bool isDocumentItem() const {return false;} virtual bool isTypeItem() const {return false;} virtual bool isObjectItem() const {return false;} // checks if item must be marked as active virtual bool isActive() const {return false;} // updates item visual state virtual void updateVisual(bool recursive = false) = 0; // updates active item visual state only virtual void updateActive(); virtual QTreeWidgetItem *parent() {return QTreeWidgetItem::parent();} ProjectTreeController* controller; bool markedAsActive; }; class U2GUI_EXPORT ProjViewTypeItem : public ProjViewItem { public: ProjViewTypeItem(const GObjectType& t, ProjectTreeController* c); virtual bool isTypeItem() const {return true;} virtual bool operator< ( const QTreeWidgetItem & other ) const; virtual void updateVisual(bool recursive = false); GObjectType otype; QString typePName; }; class U2GUI_EXPORT ProjViewDocumentItem : public ProjViewItem { public: ProjViewDocumentItem(Document* _doc, ProjectTreeController* c); virtual bool isDocumentItem() const {return true;} virtual void updateVisual(bool recursive = false); bool isActive() const; virtual bool operator< ( const QTreeWidgetItem & other ) const; Document* doc; }; class U2GUI_EXPORT ProjViewObjectItem : public ProjViewItem { public: ProjViewObjectItem(GObject* _obj, ProjectTreeController* c); virtual bool isObjectItem() const {return true;} virtual void updateVisual(bool recursive = false); bool isActive() const; virtual bool operator< ( const QTreeWidgetItem & other ) const; GObject* obj; }; }//namespace #endif ugene-1.9.8/src/corelibs/U2Gui/src/util_gui/CreateObjectRelationDialogController.h0000644000175000017500000000330011651544333026634 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_CREATE_OBJECT_RELATION_DIALOG_CONTROLLER_H_ #define _U2_CREATE_OBJECT_RELATION_DIALOG_CONTROLLER_H_ #include #include class Ui_CreateObjectRelationDialog; namespace U2 { class GObject; class U2GUI_EXPORT CreateObjectRelationDialogController : public QDialog { Q_OBJECT public: CreateObjectRelationDialogController(GObject* obj, const QList& objects, const QString& role, bool removeDuplicates, const QString& relationHint, QWidget* p = NULL); ~CreateObjectRelationDialogController(); GObject* selectedObject; GObject* assObj; QList objects; QString role; bool removeDuplicates; public slots: virtual void accept(); private: Ui_CreateObjectRelationDialog* ui; }; } //namespace #endif ugene-1.9.8/src/corelibs/U2Gui/src/util_gui/AnnotationSettingsDialogImpl.h0000644000175000017500000000335211651544333025224 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_ANNOTATION_SETTINGS_DIALOG_IMPL_H_ #define _U2_ANNOTATION_SETTINGS_DIALOG_IMPL_H_ #include #include #include #include namespace U2 { class AnnotationSettingsDialogImpl : public QDialog, public Ui_AnnotationSettingsDialog { Q_OBJECT public: AnnotationSettingsDialogImpl(QWidget* p); private slots: void sl_itemClicked(QTreeWidgetItem * item, int column); void sl_okClicked(); void sl_itemDoubleClicked(QTreeWidgetItem* item, int col); private: void loadModel(); void storeModel(); }; ////////////////////////////////////////////////////////////////////////// class ASTreeItem : public QTreeWidgetItem { public: ASTreeItem(const AnnotationSettings* as); void fillModel(); void drawColorCell(); AnnotationSettings as; }; }//namespace #endif ugene-1.9.8/src/corelibs/U2Gui/src/util_gui/ExportImageDialog.cpp0000644000175000017500000002533111651544333023327 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "ExportImageDialog.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include namespace U2 { static const QString IMAGE_DIR = "image"; static const QString SVG_FORMAT = "svg"; static const int SVG_FORMAT_ID = 1; static const QString PS_FORMAT = "ps"; static const int PS_FORMAT_ID = 2; static const QString PDF_FORMAT = "pdf"; ExportImageDialog::ExportImageDialog( QWidget* widget, bool _showSizeRuler, bool _useVectorFormats, const QString& _filename ) : QDialog(widget), widget(widget), filename(_filename), origFilename(_filename), lod(IMAGE_DIR, QDir::homePath()), showSizeRuler(_showSizeRuler), useVectorFormats(_useVectorFormats) { ui = new Ui_ImageExportForm; ui->setupUi(this); if(useVectorFormats){ supportedFormats.append("svg"); supportedFormats.append("ps"); supportedFormats.append("pdf"); } QList list=QImageWriter::supportedImageFormats(); foreach(QByteArray format,list){ if(format != "ico"){ supportedFormats.append(QString(format)); } } setupComponents(); } ExportImageDialog::ExportImageDialog( QWidget* widget, QRect _rect, bool _showSizeRuler, bool _useVectorFormats, const QString& _filename ) : QDialog(widget), widget(widget), filename(_filename), origFilename(_filename), lod(IMAGE_DIR, QDir::homePath()), rect(_rect), showSizeRuler(_showSizeRuler), useVectorFormats(_useVectorFormats) { ui = new Ui_ImageExportForm; ui->setupUi(this); if(useVectorFormats){ supportedFormats.append("svg"); supportedFormats.append("ps"); supportedFormats.append("pdf"); } QList list=QImageWriter::supportedImageFormats(); foreach(QByteArray format,list){ if(format != "ico"){ supportedFormats.append(QString(format)); } } setupComponents(); } int ExportImageDialog::getWidth(){ return ui->widthSpinBox->value(); } int ExportImageDialog::getHeight(){ return ui->heightSpinBox->value(); } void ExportImageDialog::setupComponents() { if(!showSizeRuler){ ui->widthLabel->hide(); ui->widthSpinBox->hide(); ui->heightLabel->hide(); ui->heightSpinBox->hide(); } ui->widthSpinBox->setValue(widget->width()); ui->heightSpinBox->setValue(widget->height()); foreach (const QString &format, supportedFormats) { ui->formatsBox->addItem(format); } filename = lod.dir + "/" + origFilename + "." + ui->formatsBox->currentText(); filename = GUrlUtils::rollFileName(filename, "_copy", QSet()); ui->fileNameEdit->setText(QDir::cleanPath(QDir::toNativeSeparators(filename))); setSizeControlsEnabled(!isVectorGraphicFormat(ui->formatsBox->currentText())); connect(ui->browseFileButton, SIGNAL(clicked()), this, SLOT(sl_onBrowseButtonClick())); connect(ui->formatsBox, SIGNAL(currentIndexChanged(const QString&)), this, SLOT(sl_onFormatsBoxItemChanged(const QString&))); sl_onFormatsBoxItemChanged(ui->formatsBox->currentText()); setMaximumHeight(layout()->minimumSize().height()); } void ExportImageDialog::accept() { filename = ui->fileNameEdit->text(); if (filename.isEmpty()) { QMessageBox::warning(this, tr("Error"), tr("The filename is empty!")); return; } format = ui->formatsBox->currentText(); if (QFile::exists(filename)) { int res = QMessageBox::warning(this, tr("Overwrite file?"), tr("The file \"%1\" already exists. Do you wish to overwrite it?").arg(filename), QMessageBox::Yes, QMessageBox::No); if (res == QMessageBox::No) { return; } } lod.url = filename; ioLog.info(tr("Saving image to '%1'...").arg(filename)); QCursor cursor = this->cursor(); setCursor(Qt::WaitCursor); if(rect.isEmpty()){ rect = widget->rect(); } bool result=false; if (isVectorGraphicFormat(format)) { int formatId = getVectorFormatIdByName(format); if(formatId == SVG_FORMAT_ID){ result=exportToSVG(); }else if(formatId == PS_FORMAT_ID){ result=exportToPDF(); } } else { result=exportToBitmap(); } if (!result) { QMessageBox::critical(this, L10N::errorTitle(), L10N::errorImageSave(filename, format)); return; } setCursor(cursor); ioLog.info("Done!"); QDialog::accept(); } bool ExportImageDialog::exportToSVG(){ bool result=false; QPainter painter; QSvgGenerator generator; generator.setFileName(filename); generator.setSize(rect.size()); generator.setViewBox(rect); painter.setRenderHint(QPainter::Antialiasing); painter.begin(&generator); widget->render(&painter); result = painter.end(); //fix for UGENE-76 QDomDocument doc("svg"); QFile file(lod.url); bool ok=file.open(QIODevice::ReadOnly); if (!ok && !result){ result=false; } ok=doc.setContent(&file); if (!ok && !result) { file.close(); result=false; } if(result){ file.close(); QDomNodeList radialGradients=doc.elementsByTagName("radialGradient"); for(uint i=0;irender(&painter); return painter.end(); } bool ExportImageDialog::exportToBitmap(){ // QImage image(ui->widthSpinBox->value(), ui->heightSpinBox->value(), QImage::Format_RGB32); // image.fill(palette().color(QPalette::Window).rgb()); // QPainter painter; // painter.begin(&image); // widget->render(&painter); // bool result = painter.end(); // return (result && image.save(filename)); QPixmap image = QPixmap::grabWidget(widget, rect); if(hasQuality()){ return image.save(filename, qPrintable(format),getQuality()); }else{ return image.save(filename, qPrintable(format)); } } bool ExportImageDialog::hasQuality(){ return ui->qualitySpinBox->isEnabled(); } int ExportImageDialog::getQuality(){ return ui->qualitySpinBox->value(); } void ExportImageDialog::sl_onBrowseButtonClick() { QString curFormat = ui->formatsBox->currentText(); assert(supportedFormats.contains(curFormat)); QList formats(supportedFormats); formats.removeAll(curFormat); formats.prepend(curFormat); QString fileFormats; for(int i = 0; i < formats.size(); ++i) { QString formatName = formats.at(i); fileFormats += formatName.toUpper() + " format (*." + formatName + ");;"; } QString fileName = ui->fileNameEdit->text(); LastOpenDirHelper lod(IMAGE_DIR); lod.url = QFileDialog::getSaveFileName(this, tr("Save image to..."), fileName, fileFormats, 0, QFileDialog::DontConfirmOverwrite); if (lod.url.isEmpty()) { return; } QString ext = QFileInfo(lod.url).suffix().toLower(); if (ext.isEmpty() || !supportedFormats.contains(ext)) { ext = ui->formatsBox->currentText(); lod.url += "." + ext; } ui->fileNameEdit->setText(QDir::toNativeSeparators(lod.url)); int index = ui->formatsBox->findText(ext); ui->formatsBox->setCurrentIndex(index); setSizeControlsEnabled(!isVectorGraphicFormat(ui->formatsBox->currentText())); } void ExportImageDialog::sl_onFormatsBoxItemChanged(const QString &text) { QString format = text; assert(supportedFormats.contains(text)); QString fileName = ui->fileNameEdit->text(); // Remove old suffix if present QString ext = QFileInfo(fileName).suffix().toLower(); if (supportedFormats.contains(ext)) { fileName.chop(ext.size() + 1); } fileName += "." + format; ui->fileNameEdit->setText(QDir::toNativeSeparators(fileName)); setSizeControlsEnabled(!isVectorGraphicFormat(format)); if((format == "jpeg") || (format == "jpg") || (format == "png")){ ui->qualityLabel->setEnabled(true); ui->qualityHorizontalSlider->setEnabled(true); ui->qualitySpinBox->setEnabled(true); }else{ ui->qualityLabel->setEnabled(false); ui->qualityHorizontalSlider->setEnabled(false); ui->qualitySpinBox->setEnabled(false); } } bool ExportImageDialog::isVectorGraphicFormat( const QString& formatName ) { if ((formatName == SVG_FORMAT) || (formatName == PS_FORMAT) || (formatName == PDF_FORMAT)) { return true; } return false; } int ExportImageDialog::getVectorFormatIdByName( const QString& formatName ) { if (formatName == SVG_FORMAT) { return SVG_FORMAT_ID; } else if ((formatName == PS_FORMAT) || (formatName == PDF_FORMAT)) { return PS_FORMAT_ID; } else return -1; return -1; } void ExportImageDialog::setSizeControlsEnabled(bool enabled) { ui->widthLabel->setEnabled(enabled); ui->heightLabel->setEnabled(enabled); ui->widthSpinBox->setEnabled(enabled); ui->heightSpinBox->setEnabled(enabled); } } // namespace ugene-1.9.8/src/corelibs/U2Gui/src/util_gui/BaseDocumentFormatConfigurators.h0000644000175000017500000000313211651544333025713 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_BASE_DOC_FORMAT_CONFIG_H_ #define _U2_BASE_DOC_FORMAT_CONFIG_H_ #include #include namespace U2 { class U2GUI_EXPORT BaseDocumentFormatConfigurators { public: static void initBuiltInConfigurators(); static void loadDefaultFormatSettings(const DocumentFormatId& format, QVariantMap& formatSettings); static void saveDefaultFormatSettings(const DocumentFormatId& format, const QVariantMap& formatSettings); }; class U2GUI_EXPORT MultiPartDocFormatConfigurator : public DocumentFormatConfigurator { Q_OBJECT public: MultiPartDocFormatConfigurator(DocumentFormatId id) : DocumentFormatConfigurator(id) {}; virtual void configure(QVariantMap& info); }; }//namespace #endif ugene-1.9.8/src/corelibs/U2Gui/src/util_gui/DownloadRemoteFileDialog.cpp0000644000175000017500000001144011651544333024622 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include #include #include #include #include #include #include #include #include #include #include #include #include #include "DownloadRemoteFileDialog.h" #include "ui/ui_DownloadRemoteFileDialog.h" #include "OpenViewTask.h" #define SAVE_DIR QString("downloadremotefiledialog/savedir") namespace U2 { QString DownloadRemoteFileDialog::defaultDB(""); DownloadRemoteFileDialog::DownloadRemoteFileDialog(QWidget *p):QDialog(p), isQueryDB(false) { ui = new Ui_DownloadRemoteFileDialog; ui->setupUi(this); connect(ui->databasesBox, SIGNAL(currentIndexChanged ( const QString&)), SLOT( sl_updateHint(const QString&))); connect(ui->saveFilenameToolButton, SIGNAL(clicked()), SLOT(sl_saveFilenameButtonClicked())); RemoteDBRegistry& registry = RemoteDBRegistry::getRemoteDBRegistry(); const QList dataBases = registry.getDBs(); foreach(const QString& dbName, dataBases) { ui->databasesBox->addItem(dbName); } if (!defaultDB.isEmpty()) { int index = ui->databasesBox->findText(defaultDB); Q_ASSERT(index < dataBases.count()); ui->databasesBox->setCurrentIndex(index); } setSaveFilename(); } const QString DOWNLOAD_REMOTE_FILE_DOMAIN = "DownloadRemoteFileDialog"; void DownloadRemoteFileDialog::sl_saveFilenameButtonClicked() { LastOpenDirHelper lod(DOWNLOAD_REMOTE_FILE_DOMAIN); QString filename = QFileDialog::getExistingDirectory(this, tr("Select directory to save"), lod.dir); if(!filename.isEmpty()) { ui->saveFilenameLineEdit->setText(filename); lod.url = filename; } } static const QString DEFAULT_FILENAME = "file.format"; void DownloadRemoteFileDialog::setSaveFilename() { QString dir = AppContext::getSettings()->getValue(SAVE_DIR, "").value(); if(dir.isEmpty()) { dir = LoadRemoteDocumentTask::getDefaultDownloadDirectory(); assert(!dir.isEmpty()); } ui->saveFilenameLineEdit->setText(QDir::toNativeSeparators(dir)); } QString DownloadRemoteFileDialog::getResourceId() const { return ui->idLineEdit->text().trimmed(); } QString DownloadRemoteFileDialog::getDBName() const { return ui->databasesBox->currentText(); } QString DownloadRemoteFileDialog::getFullpath() const { return ui->saveFilenameLineEdit->text(); } void DownloadRemoteFileDialog::accept() { defaultDB = getDBName(); QString resourceId = getResourceId(); if( resourceId.isEmpty() ) { QMessageBox::critical(this, L10N::errorTitle(), tr("Resource id is empty!")); ui->idLineEdit->setFocus(); return; } QString fullPath = getFullpath(); if( ui->saveFilenameLineEdit->text().isEmpty() ) { QMessageBox::critical(this, L10N::errorTitle(), tr("No directory selected for saving file!")); ui->saveFilenameLineEdit->setFocus(); return; } QString errorMessage; fullPath = GUrlUtils::prepareDirLocation(fullPath, errorMessage); if (fullPath.isEmpty()) { QMessageBox::critical(this, L10N::errorTitle(), errorMessage); ui->saveFilenameLineEdit->setFocus(); return; } Task* task = new LoadRemoteDocumentAndOpenViewTask(resourceId, getDBName(), fullPath); AppContext::getTaskScheduler()->registerTopLevelTask(task); QDialog::accept(); } void DownloadRemoteFileDialog::sl_updateHint(const QString& dbName) { RemoteDBRegistry& registry = RemoteDBRegistry::getRemoteDBRegistry(); QString hint = registry.getHint(dbName); ui->hintLabel->setText(hint); ui->idLineEdit->setToolTip(hint); } DownloadRemoteFileDialog::~DownloadRemoteFileDialog() { AppContext::getSettings()->setValue(SAVE_DIR, ui->saveFilenameLineEdit->text()); delete ui; } } //namespace ugene-1.9.8/src/corelibs/U2Gui/src/util_gui/CreateAnnotationWidgetController.cpp0000644000175000017500000003403411651544333026431 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "CreateAnnotationWidgetController.h" #include #include "GObjectComboBoxController.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include //#define SETTINGS_LAST_USED_ANNOTATION_NAME "create_annotation/last_name" #define SETTINGS_LASTDIR "create_annotation/last_dir" namespace U2 { /* TRANSLATOR U2::CreateAnnotationWidgetController */ CreateAnnotationModel::CreateAnnotationModel() : defaultIsNewDoc(false), hideLocation(false), hideAnnotationName(false) { data = new AnnotationData(); useUnloadedObjects = false; } AnnotationTableObject* CreateAnnotationModel::getAnnotationObject() const { GObject* res = GObjectUtils::selectObjectByReference(annotationObjectRef, UOF_LoadedOnly); AnnotationTableObject* aobj = qobject_cast(res); assert(aobj!=NULL); return aobj; } CreateAnnotationWidgetController::CreateAnnotationWidgetController(const CreateAnnotationModel& m, QObject* p) : QObject(p), model(m) { this->setObjectName("CreateAnnotationWidgetController"); assert(AppContext::getProject()!=NULL); assert(model.sequenceObjectRef.isValid()); w = new QWidget(); ui = new Ui_CreateAnnotationWidget; ui->setupUi(w); if (model.hideLocation) { ui->locationLabel->hide(); ui->locationEdit->hide(); ui->complementButton->hide(); } if( model.hideAnnotationName ) { ui->annotationNameEdit->hide(); ui->annotationNameLabel->hide(); ui->showNameGroupsButton->hide(); } else { QMenu* menu = createAnnotationNamesMenu(w, this); ui->showNameGroupsButton->setMenu(menu); ui->showNameGroupsButton->setPopupMode(QToolButton::InstantPopup); } QString dir = AppContext::getSettings()->getValue(SETTINGS_LASTDIR).toString(); if (dir.isEmpty() || !QDir(dir).exists()) { dir = QDir::homePath(); } dir+="/"; QString baseName = "MyDocument"; QString ext = ".gb"; QString url = dir + baseName + ext; for (int i=1; QFileInfo(url).exists() || AppContext::getProject()->findDocumentByURL(url)!= NULL; i++) { url = dir + baseName +"_"+QString::number(i) + ext; } ui->newFileEdit->setText(url); GROUP_NAME_AUTO = CreateAnnotationWidgetController::tr(""); GObjectComboBoxControllerConstraints occc; occc.relationFilter.ref = model.sequenceObjectRef; occc.relationFilter.role = GObjectRelationRole::SEQUENCE; occc.typeFilter = GObjectTypes::ANNOTATION_TABLE; occc.onlyWritable = true; occc.uof = model.useUnloadedObjects ? UOF_LoadedAndUnloaded : UOF_LoadedOnly; occ = new GObjectComboBoxController(this, occc, ui->existingObjectCombo); if (model.annotationObjectRef.isValid()) { occ->setSelectedObject(model.annotationObjectRef); } //default field values if (!model.data->name.isEmpty()) { ui->annotationNameEdit->setText(model.data->name); } else if (!model.hideAnnotationName) { //QString name = AppContext::getSettings()->getValue(SETTINGS_LAST_USED_ANNOTATION_NAME, QString("misc_feature")).toString(); ui->annotationNameEdit->setText("misc_feature"); } ui->annotationNameEdit->selectAll(); ui->groupNameEdit->setText(model.groupName.isEmpty() ? GROUP_NAME_AUTO : model.groupName); if (!model.data->location->isEmpty()) { QString locationString = Genbank::LocationParser::buildLocationString(model.data); ui->locationEdit->setText(locationString); } if (model.defaultIsNewDoc || ui->existingObjectCombo->count() == 0) { ui->existingObjectRB->setCheckable(false); ui->existingObjectRB->setDisabled(true); ui->existingObjectCombo->setDisabled(true); ui->existingObjectButton->setDisabled(true); ui->newFileRB->setChecked(true); } connect(ui->newFileButton, SIGNAL(clicked()), SLOT(sl_onNewDocClicked())); connect(ui->existingObjectButton, SIGNAL(clicked()), SLOT(sl_onLoadObjectsClicked())); connect(ui->groupNameButton, SIGNAL(clicked()), SLOT(sl_groupName())); connect(ui->complementButton, SIGNAL(clicked()), SLOT(sl_complementLocation())); } void CreateAnnotationWidgetController::sl_onNewDocClicked() { QString openUrl = QFileInfo(ui->newFileEdit->text()).absoluteDir().absolutePath(); QString filter = DialogUtils::prepareDocumentsFileFilter(BaseDocumentFormats::PLAIN_GENBANK, false); QString name = QFileDialog::getSaveFileName(NULL, tr("Save file"), openUrl, filter); if (!name.isEmpty()) { ui->newFileEdit->setText(name); AppContext::getSettings()->setValue(SETTINGS_LASTDIR, QFileInfo(name).absoluteDir().absolutePath()); } } class PTCAnnotationObjectFilter: public PTCObjectRelationFilter { public: PTCAnnotationObjectFilter(const GObjectRelation& _rel, bool _allowUnloaded, QObject* p = NULL) : PTCObjectRelationFilter(_rel, p), allowUnloaded(_allowUnloaded){} bool filter(GObject* obj) const { if (PTCObjectRelationFilter::filter(obj)) { return true; } if (obj->isUnloaded()) { return !allowUnloaded; } assert(qobject_cast(obj)!=NULL); return obj->isStateLocked(); } bool allowUnloaded; }; void CreateAnnotationWidgetController::sl_onLoadObjectsClicked() { ProjectTreeControllerModeSettings s; s.allowMultipleSelection = false; s.objectTypesToShow.append(GObjectTypes::ANNOTATION_TABLE); s.groupMode = ProjectTreeGroupMode_Flat; GObjectRelation rel(model.sequenceObjectRef, GObjectRelationRole::SEQUENCE); std::auto_ptr filter(new PTCAnnotationObjectFilter(rel, model.useUnloadedObjects)); s.objectFilter = filter.get(); QList objs = ProjectTreeItemSelectorDialog::selectObjects(s, w); if (objs.isEmpty()) { return; } assert(objs.size() == 1); GObject* obj = objs.first(); occ->setSelectedObject(obj); } QString CreateAnnotationWidgetController::validate() { updateModel(); if (!model.annotationObjectRef.isValid()) { if (model.newDocUrl.isEmpty()) { return tr("Select annotation saving parameters"); } if (AppContext::getProject()->findDocumentByURL(model.newDocUrl)!=NULL) { return tr("Document is already added to the project: '%1'").arg(model.newDocUrl); } QFileInfo fi(model.newDocUrl); QString dirUrl = QFileInfo(ui->newFileEdit->text()).absoluteDir().absolutePath(); QDir dir(dirUrl); if (!dir.exists()) { return tr("Illegal folder: %1").arg(dirUrl); } } if (model.data->name.isEmpty()) { ui->annotationNameEdit->setFocus(); return tr("Annotation name is empty"); } if (model.data->name.length() > GBFeatureUtils::MAX_KEY_LEN) { ui->annotationNameEdit->setFocus(); return tr("Annotation name is too long!\nMaximum allowed size: %1 (Genbank format compatibility issue)").arg(GBFeatureUtils::MAX_KEY_LEN); } if (!Annotation::isValidAnnotationName(model.data->name)) { ui->annotationNameEdit->setFocus(); return tr("Illegal annotation name"); } if (model.groupName.isEmpty()) { ui->groupNameEdit->setFocus(); return tr("Group name is empty"); } if (!AnnotationGroup::isValidGroupName(model.groupName, true)) { ui->groupNameEdit->setFocus(); return tr("Illegal group name"); } static const QString INVALID_LOCATION = tr("Invalid location! Location must be in GenBank format.\nSimple examples:\n1..10\njoin(1..10,15..45)\ncomplement(5..15)"); if (!model.hideLocation && model.data->location->isEmpty()) { ui->locationEdit->setFocus(); return INVALID_LOCATION; } foreach(U2Region reg, model.data->getRegions()){ if( reg.endPos() > model.sequenceLen || reg.startPos < 0 || reg.endPos() < reg.startPos) { return INVALID_LOCATION; } } // AppContext::getSettings()->setValue(SETTINGS_LAST_USED_ANNOTATION_NAME, model.data->name); return QString::null; } void CreateAnnotationWidgetController::updateModel() { model.data->name = ui->annotationNameEdit->text(); model.groupName = ui->groupNameEdit->text(); if (model.groupName == GROUP_NAME_AUTO) { model.groupName = model.data->name; } model.data->location->reset(); if (!model.hideLocation) { QByteArray locEditText = ui->locationEdit->text().toAscii(); Genbank::LocationParser::parseLocation( locEditText.constData(), ui->locationEdit->text().length(), model.data->location); } if (ui->existingObjectRB->isChecked()) { model.annotationObjectRef = occ->getSelectedObject(); model.newDocUrl = ""; } else { model.annotationObjectRef = GObjectReference(); model.newDocUrl = ui->newFileEdit->text(); } } void CreateAnnotationWidgetController::prepareAnnotationObject() { QString v = validate(); assert(v.isEmpty()); if (!model.annotationObjectRef.isValid() && ui->newFileRB->isChecked()) { assert(!model.newDocUrl.isEmpty()); assert(AppContext::getProject()->findDocumentByURL(model.newDocUrl)==NULL); IOAdapterFactory* iof = AppContext::getIOAdapterRegistry()->getIOAdapterFactoryById(BaseIOAdapters::LOCAL_FILE); DocumentFormat* df = AppContext::getDocumentFormatRegistry()->getFormatById(BaseDocumentFormats::PLAIN_GENBANK); Document* d = df->createNewDocument(iof, model.newDocUrl); AnnotationTableObject* aobj = new AnnotationTableObject("Annotations"); aobj->addObjectRelation(GObjectRelation(model.sequenceObjectRef, GObjectRelationRole::SEQUENCE)); d->addObject(aobj); AppContext::getProject()->addDocument(d); model.annotationObjectRef = aobj; } } static bool caseInsensitiveLessThan(const QString &s1, const QString &s2) { return s1.toLower() < s2.toLower(); } QMenu* CreateAnnotationWidgetController::createAnnotationNamesMenu(QWidget* p, QObject* receiver) { assert(p!=NULL && receiver!=NULL); QMenu* m = new QMenu(p); const QMultiMap& nameGroups = GBFeatureUtils::getKeyGroups(); QStringList groupNames = nameGroups.uniqueKeys(); qSort(groupNames.begin(), groupNames.end(), caseInsensitiveLessThan); foreach(const QString& groupName, groupNames) { QMenu* groupMenu = m->addMenu(groupName); QList keys = nameGroups.values(groupName); QStringList names; foreach(GBFeatureKey k, keys) { names.append(GBFeatureUtils::getKeyInfo(k).text); } qSort(names.begin(), names.end(), caseInsensitiveLessThan); foreach(const QString& name, names) { QAction* a = new QAction(name, groupMenu); connect(a, SIGNAL(triggered()), receiver, SLOT(sl_setPredefinedAnnotationName())); groupMenu->addAction(a); } } return m; } void CreateAnnotationWidgetController::sl_setPredefinedAnnotationName() { QAction* a = qobject_cast(sender()); QString text = a->text(); ui->annotationNameEdit->setText(text); } void CreateAnnotationWidgetController::sl_groupName() { GObject* obj = occ->getSelectedObject(); QStringList groupNames; groupNames << GROUP_NAME_AUTO; if (obj != NULL && !obj->isUnloaded()) { AnnotationTableObject* ao = qobject_cast(obj); ao->getRootGroup()->getSubgroupPaths(groupNames); } assert(groupNames.size() >= 1); if (groupNames.size() == 1) { ui->groupNameEdit->setText(groupNames.first()); return; } qSort(groupNames); QMenu m(w); QPoint menuPos = ui->groupNameButton->mapToGlobal(ui->groupNameButton->rect().bottomLeft()); foreach(const QString& str, groupNames) { QAction* a = new QAction(str, &m); connect(a, SIGNAL(triggered()), SLOT(sl_setPredefinedGroupName())); m.addAction(a); } m.exec(menuPos); } void CreateAnnotationWidgetController::sl_setPredefinedGroupName() { QAction* a = qobject_cast(sender()); QString name = a->text(); ui->groupNameEdit->setText(name); } void CreateAnnotationWidgetController::sl_complementLocation() { QString text = ui->locationEdit->text(); if (text.startsWith("complement(") && text.endsWith(")")) { ui->locationEdit->setText(text.mid(11, text.length()-12)); } else { ui->locationEdit->setText("complement(" + text + ")"); } } CreateAnnotationWidgetController::~CreateAnnotationWidgetController() { delete ui; } bool CreateAnnotationWidgetController::isNewObject() const { return ui->newFileRB->isChecked(); } void CreateAnnotationWidgetController::setFocusToNameEdit() { ui->annotationNameEdit->setFocus(); } } // namespace ugene-1.9.8/src/corelibs/U2Gui/src/MainWindow.h0000644000175000017500000001335211651544333017663 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_MAIN_WINDOW_H_ #define _U2_MAIN_WINDOW_H_ #include #include #include #include #include class QAction; class QMdiSubWindow; class QDockWidget; class QMenu; class QToolBar; class QMainWindow; // menu #define MWMENU_FILE "mwmenu_file" #define MWMENU_ACTIONS "mwmenu_actions" #define MWMENU_SETTINGS "mwmenu_settings" #define MWMENU_TOOLS "mwmenu_tools" #define MWMENU_TOOLS_MALIGN "mwmenu_tools_malign" #define MWMENU_TOOLS_ASSEMBLY "mwmenu_tools_assembly" #define MWMENU_WINDOW "mwmenu_window" #define MWMENU_HELP "mwmenu_help" // toolbar #define MWTOOLBAR_MAIN "mwtoolbar_main" #define MWTOOLBAR_ACTIVEMDI "mwtoolbar_activemdi" //actions #define ACTION__EXIT "action__exit" #define ACTION__ABOUT "action__about" #define ACTION__LOGVIEW "action__logview" #define ACTION__PLUGINS_VIEW "action__plugins" #define ACTION_PROJECTSUPPORT__NEW_PROJECT "action_projectsupport__new_project" #define ACTION_PROJECTSUPPORT__OPEN_PROJECT "action_projectsupport__open_project" #define ACTION_PROJECTSUPPORT__SAVE_PROJECT "action_projectsupport__save_project" #define ACTION_PROJECTSUPPORT__CLOSE_PROJECT "action_projectsupport__close_project" #define ACTION_PROJECTSUPPORT__RECENT_PROJECTS_MENU "action_projectsupport__recent_projects_menu" #define ACTION_PROJECTSUPPORT__EXPORT_PROJECT "action_projectsupport__export_project" #define ACTION_PROJECT__ADD_MENU "action_project__add_menu" #define ACTION_PROJECT__ADD_NEW_DOCUMENT "action_project__add_new_document" #define ACTION_PROJECT__ADD_EXISTING_DOCUMENT "action_project__add_existing_document" #define ACTION_PROJECT__EDIT_MENU "action_project__edit_menu" #define DOCK_PROJECT_VIEW "dock_project_view" #define DOCK_TASK_VIEW "dock_task_view" #define DOCK_LOG_VIEW "dock_log_view" namespace U2 { class MWMDIManager; class MWDockManager; class NotificationStack; class U2GUI_EXPORT MainWindow : public QObject { Q_OBJECT public: virtual QMenu* getTopLevelMenu(const QString& sysName) const = 0; virtual QToolBar* getToolbar(const QString& sysName) const = 0; virtual QMainWindow* getQMainWindow() const = 0; virtual MWMDIManager* getMDIManager() const = 0; virtual MWDockManager* getDockManager() const = 0; virtual NotificationStack* getNotificationStack() const = 0; virtual void setWindowTitle(const QString& title) = 0; }; ////////////////////////////////////////////////////////////////////////// /// MDI class U2GUI_EXPORT MWMDIWindow : public QWidget { Q_OBJECT friend class MWMDIManager; public: MWMDIWindow(const QString& _windowName); virtual void setupMDIToolbar(QToolBar*) {} virtual void setupViewMenu(QMenu*) {} int getId() const {return windowId;} protected: /* returns true if a window may be closed, false otherwise */ virtual bool onCloseEvent() {return true;} protected: int windowId; }; class U2GUI_EXPORT MWMDIManager : public QObject { Q_OBJECT public: MWMDIManager(QObject* p) : QObject(p){} /** Adds the specified window to MainWindow layout and activates it. */ virtual void addMDIWindow(MWMDIWindow* w) = 0; virtual bool closeMDIWindow(MWMDIWindow* w) = 0; virtual QList getWindows() const = 0; virtual MWMDIWindow* getWindowById(int id) const = 0; virtual void activateWindow(MWMDIWindow* w) = 0; virtual MWMDIWindow* getActiveWindow() const = 0; signals: void si_windowAdded(MWMDIWindow* w); void si_windowClosing(MWMDIWindow* w); void si_windowActivated(MWMDIWindow* w); protected: /* returns true if the window agreed to close, false otherwise */ bool onCloseEvent(MWMDIWindow* w) {return w->onCloseEvent();} }; ////////////////////////////////////////////////////////////////////////// /// DOCK enum MWDockArea { MWDockArea_Left, MWDockArea_Right, MWDockArea_Bottom, MWDockArea_MaxDocks }; class U2GUI_EXPORT MWDockManager: public QObject { Q_OBJECT public: MWDockManager(QObject* p) : QObject(p){} virtual QAction* registerDock(MWDockArea area, QWidget* w, const QKeySequence& ks = QKeySequence()) = 0; virtual QWidget* findWidget(const QString& widgetObjName) = 0; virtual QWidget* getActiveWidget(MWDockArea a) = 0; virtual QWidget* activateDock(const QString& widgetObjName) = 0; virtual QWidget* toggleDock(const QString& widgetObjName) = 0; }; }//namespace Q_DECLARE_METATYPE(U2::MainWindow*) Q_DECLARE_METATYPE(U2::MWMDIManager*) Q_DECLARE_METATYPE(U2::MWDockManager*) #endif ugene-1.9.8/src/corelibs/U2Gui/src/ObjectViewTasks.cpp0000644000175000017500000001111011651544333021177 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "ObjectViewTasks.h" #include #include #include #include #include #include #include #include #include namespace U2 { /* TRANSLATOR U2::ObjectViewTask */ ObjectViewTask::ObjectViewTask(GObjectView* _view, const QString& stateName, const QVariantMap& s) : Task("", TaskFlag_NoRun), taskType(Type_Update), stateData(s), view(_view), stateIsIllegal(false) { assert(view!=NULL); const QString& vName = view->getName(); setTaskName(tr("Update '%1' to '%2' state").arg(vName).arg(stateName)); setVerboseLogMode(true); } ObjectViewTask::ObjectViewTask(GObjectViewFactoryId fid, const QString& vName, const QVariantMap& s) : Task("", TaskFlag_NoRun), taskType(Type_Open), stateData(s), view(NULL), viewName(vName), stateIsIllegal(false) { if (vName.isEmpty()) { QString factoryName = AppContext::getObjectViewFactoryRegistry()->getFactoryById(fid)->getName(); setTaskName(tr("Open new '%1'").arg(factoryName)); } else { setTaskName(tr("Open '%1'").arg(vName)); } setVerboseLogMode(true); } void ObjectViewTask::prepare() { QSet processed; foreach(QPointer pd, documentsToLoad) { if (!pd.isNull() && !processed.contains(pd)){ addSubTask(new LoadUnloadedDocumentTask(pd)); processed.insert(pd); } } } Task::ReportResult ObjectViewTask::report() { foreach(QPointer pd, documentsToLoad) { if (pd.isNull()){ continue; } if (!pd->isLoaded()) { documentsFailedToLoad.append(pd); continue; } onDocumentLoaded(pd); } if (taskType == Type_Open) { open(); } else { assert(taskType == Type_Update); update(); } if (stateIsIllegal) { //todo: ask to remove illegal state } return ReportResult_Finished; } Document* ObjectViewTask::createDocumentAndAddToProject( const QString& docUrl, Project* p ) { SAFE_POINT(p!=NULL, "Project is NULL!", NULL); QFileInfo fi(docUrl); if (!fi.exists()) { return NULL; } IOAdapterFactory * iof = AppContext::getIOAdapterRegistry()->getIOAdapterFactoryById(BaseIOAdapters::url2io(docUrl)); QList dfs = DocumentUtils::detectFormat(docUrl); if (dfs.isEmpty()) { return NULL; } Document* doc = new Document( dfs.first().format, iof, GUrl(docUrl) ); p->addDocument(doc); return doc; } ////////////////////////////////////////////////////////////////////////// // AddToViewTask AddToViewTask::AddToViewTask(GObjectView* v, GObject* obj) : Task(tr("Add object to view %1").arg(obj->getGObjectName()), TaskFlags_NR_FOSCOE), objView(v), viewName(v->getName()), objRef(obj), objDoc(obj->getDocument()) { assert(objDoc!=NULL); if (obj->isUnloaded()) { addSubTask(new LoadUnloadedDocumentTask(objDoc)); } } Task::ReportResult AddToViewTask::report() { if (hasError() || isCanceled()) { return ReportResult_Finished; } if (objDoc == NULL) { stateInfo.setError(tr("Document was removed %1").arg(objRef.docUrl)); return ReportResult_Finished; } GObject* obj = objDoc->findGObjectByName(objRef.objName); if (obj == NULL) { stateInfo.setError(tr("Object not found %1").arg(objRef.objName)); return ReportResult_Finished; } if (objView == NULL) { stateInfo.setError(tr("View was closed %1").arg(viewName)); return ReportResult_Finished; } objView->addObject(obj); return ReportResult_Finished; } } // namespace ugene-1.9.8/src/corelibs/U2Gui/src/OpenViewTask.h0000644000175000017500000000501011651544333020156 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_OPEN_DOCUMENT_TASK_H_ #define _U2_OPEN_DOCUMENT_TASK_H_ #include #include #include namespace U2 { class Document; class LoadDocumentTask; class LoadRemoteDocumentTask; class DocumentProviderTask; class U2GUI_EXPORT LoadUnloadedDocumentAndOpenViewTask : public Task { Q_OBJECT public: LoadUnloadedDocumentAndOpenViewTask(Document* d); protected: virtual QList onSubTaskFinished(Task* subTask); private: void clearResourceUse(); class LoadUnloadedDocumentTask* loadUnloadedTask; }; class U2GUI_EXPORT LoadRemoteDocumentAndOpenViewTask : public Task { Q_OBJECT public: LoadRemoteDocumentAndOpenViewTask(const QString& accId, const QString& dbName); LoadRemoteDocumentAndOpenViewTask(const QString& accId, const QString& dbName, const QString & fullpath); LoadRemoteDocumentAndOpenViewTask(const GUrl& url); virtual void prepare(); protected: QList onSubTaskFinished(Task* subTask); private: QString accNumber, databaseName; QString fullpath; GUrl docUrl; LoadRemoteDocumentTask* loadRemoteDocTask; }; class U2GUI_EXPORT OpenViewTask : public Task { Q_OBJECT public: OpenViewTask(Document* d); protected: void prepare(); private: Document* doc; }; class U2GUI_EXPORT AddDocumentAndOpenViewTask : public Task { Q_OBJECT public: AddDocumentAndOpenViewTask(Document* d, const AddDocumentTaskConfig& conf = AddDocumentTaskConfig()); AddDocumentAndOpenViewTask(DocumentProviderTask* d, const AddDocumentTaskConfig& conf = AddDocumentTaskConfig()); protected: QList onSubTaskFinished(Task* t); }; }//namespace #endif ugene-1.9.8/src/corelibs/U2Gui/src/UnloadDocumentTask.h0000644000175000017500000000317311651544333021353 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_UNLOAD_DOCUMENT_TASK_H_ #define _U2_UNLOAD_DOCUMENT_TASK_H_ #include #include #include #include namespace U2 { class Document; class SaveDocumentTask; enum UnloadDocumentTask_SaveMode { UnloadDocumentTask_SaveMode_Ask, UnloadDocumentTask_SaveMode_NotSave, UnloadDocumentTask_SaveMode_Save }; class U2GUI_EXPORT UnloadDocumentTask: public Task { Q_OBJECT public: UnloadDocumentTask(Document* doc, bool save); ReportResult report(); static void runUnloadTaskHelper(const QList& docs, UnloadDocumentTask_SaveMode sm); static QString checkSafeUnload(Document* d); private: QPointer doc; SaveDocumentTask* saveTask; }; }//namespace #endif ugene-1.9.8/src/corelibs/U2Gui/U2Gui.pro0000644000175000017500000001054011651544332016317 0ustar ilyailyainclude (U2Gui.pri) # Input HEADERS += src/AppSettingsGUI.h \ src/MainWindow.h \ src/Notification.h \ src/NotificationWidget.h \ src/ObjectViewModel.h \ src/ObjectViewTasks.h \ src/OpenViewTask.h \ src/PluginViewer.h \ src/ProjectParsing.h \ src/ProjectView.h \ src/UnloadDocumentTask.h \ src/util_gui/AddNewDocumentDialogController.h \ src/util_gui/AddNewDocumentDialogImpl.h \ src/util_gui/AnnotationSettingsDialogController.h \ src/util_gui/AnnotationSettingsDialogImpl.h \ src/util_gui/BaseDocumentFormatConfigurators.h \ src/util_gui/CopyDocumentDialogController.h \ src/util_gui/CreateAnnotationDialog.h \ src/util_gui/CreateAnnotationWidgetController.h \ src/util_gui/CreateDocumentFromTextDialogController.h \ src/util_gui/CreateObjectRelationDialogController.h \ src/util_gui/DocumentFormatComboboxController.h \ src/util_gui/DownloadRemoteFileDialog.h \ src/util_gui/EditQualifierDialog.h \ src/util_gui/EditSequenceDialogController.h \ src/util_gui/ExportImageDialog.h \ src/util_gui/GObjectComboBoxController.h \ src/util_gui/GUIUtils.h \ src/util_gui/ObjectViewTreeController.h \ src/util_gui/ProjectDocumentComboBoxController.h \ src/util_gui/ProjectTreeController.h \ src/util_gui/ProjectTreeItemSelectorDialog.h \ src/util_gui/ProjectTreeItemSelectorDialogImpl.h \ src/util_gui/RemovePartFromSequenceDialogController.h \ src/util_gui/SaveDocumentGroupController.h \ src/util_gui/SeqPasterWidgetController.h \ src/util_gui/logview/LogView.h FORMS += src/util_gui/ui/AddNewDocumentDialog.ui \ src/util_gui/ui/AnnotationSettingsDialog.ui \ src/util_gui/ui/CopyDocumentDialog.ui \ src/util_gui/ui/CreateAnnotationWidget.ui \ src/util_gui/ui/CreateDocumentFromTextDialog.ui \ src/util_gui/ui/CreateObjectRelationDialog.ui \ src/util_gui/ui/DownloadRemoteFileDialog.ui \ src/util_gui/ui/EditQualifierDialog.ui \ src/util_gui/ui/EditSequenceDialog.ui \ src/util_gui/ui/ExportImageDialog.ui \ src/util_gui/ui/FormatSettingsDialog.ui \ src/util_gui/ui/MultipartDocFormatConfiguratorWidget.ui \ src/util_gui/ui/ProjectTreeItemSelectorDialogBase.ui \ src/util_gui/ui/RemovePartFromSequenceDialog.ui \ src/util_gui/ui/SeqPasterWidget.ui SOURCES += src/MainWindow.cpp \ src/Notification.cpp \ src/NotificationWidget.cpp \ src/ObjectViewModel.cpp \ src/ObjectViewTasks.cpp \ src/OpenViewTask.cpp \ src/ProjectParsing.cpp \ src/UnloadDocumentTask.cpp \ src/util_gui/AddNewDocumentDialogImpl.cpp \ src/util_gui/AnnotationSettingsDialogImpl.cpp \ src/util_gui/BaseDocumentFormatConfigurators.cpp \ src/util_gui/CopyDocumentDialogController.cpp \ src/util_gui/CreateAnnotationDialog.cpp \ src/util_gui/CreateAnnotationWidgetController.cpp \ src/util_gui/CreateDocumentFromTextDialogController.cpp \ src/util_gui/CreateObjectRelationDialogController.cpp \ src/util_gui/DocumentFormatComboboxController.cpp \ src/util_gui/DownloadRemoteFileDialog.cpp \ src/util_gui/EditQualifierDialog.cpp \ src/util_gui/EditSequenceDialogController.cpp \ src/util_gui/ExportImageDialog.cpp \ src/util_gui/GObjectComboBoxController.cpp \ src/util_gui/GUIUtils.cpp \ src/util_gui/ObjectViewTreeController.cpp \ src/util_gui/ProjectDocumentComboBoxController.cpp \ src/util_gui/ProjectTreeController.cpp \ src/util_gui/ProjectTreeItemSelectorDialog.cpp \ src/util_gui/RemovePartFromSequenceDialogController.cpp \ src/util_gui/SaveDocumentGroupController.cpp \ src/util_gui/SeqPasterWidgetController.cpp \ src/util_gui/logview/LogView.cpp RESOURCES += U2Gui.qrc TRANSLATIONS += transl/czech.ts transl/english.ts transl/russian.ts ugene-1.9.8/src/corelibs/U2Gui/transl/0000755000175000017500000000000011651544333016146 5ustar ilyailyaugene-1.9.8/src/corelibs/U2Gui/transl/russian.ts0000644000175000017500000020265011651544333020207 0ustar ilyailya AddExistingDocumentDialog Add existing document Добавить существующий докумет Document location: Адрес документа: ... Document format: Формат: Force read-only mode Открыть только для чтения Custom settings Дополнительные опции Save file to disk before opening Сохранить локальную копию Add Добавить Cancel Отменить AddNewDocumentDialog Add new document Создание документа Document format Формат Document location Адрес документа ... Compress file Применить компрессию gzip Create Создать Cancel Отменить AnnotationSettingsDialog Visualization settings for annotations Настройки визуализации аннотаций Name Имя Color Цвет Amino Амино Highlight Маркировка OK Готово Cancel Отмена Visual Qualifier Визуальный квалификатор CopyDocumentDialog Copy Document Создать копию документа File name: Имя файла Format: Формат Save a copy Сохранить копию документа Save to file Сохранить в файл File format Формат файла Add to project Добавить в проект ... Compress file Применить компрессию gzip Save Сохранить Create Создать Cancel Отмена CreateAnnotationWidget ... Create annotations Создание аннотации Save annotation(s) to Сохранить результат(ы) в Existing annotation table Существующую таблицу Create new table Новую таблицу Annotation parameters Параметры аннотирования Group name Имя группы Predefined group names Annotation name Имя аннотации Location Позиция Predefined annotation names Стандартные имена аннотаций Annotation location in GenBank format Местоположение аннотации (в формате GenBank) Add/remove complement flag Добавить/снять флаг комплементарности CreateDocumentFromTextDialog Create document Создание документа Document location: Адрес документа: ... Document format: Формат: Sequence name Имя последовательности Sequence Последовательность Create Создать Cancel Отмена Save file immediately Записать файл на диск CreateNewObjectDialog Object name Имя объекта: Object type Тип объекта: Document Документ: ... ... Create Создать Cancel Отменить Create new object Создание объекта CreateObjectRelationDialog Edit object relations Создание связи объекта Associate object with: Связь: Ok Готово Cancel Отмена DownloadRemoteFileDialog Fetch data from remote database Получить данные из удаленной базы Please enter the ID and choose database. Введите идентификатор и выберите базу данных. Resource ID: Идентификатор: Database: База данных: Save to directory: Сохранить в директорию: ... ... Hint Подсказка Use database unique identifier. Использовать уникальный идентификатор базы данных. OK ОК Cancel Отмена EditQualifierDialog Edit qualifier Редактировать квалификатор Name Имя Value Значение Cancel Отмена OK Готово EditSequenceDialog Annotations region resolving mode Способ обработки аннотаций Resize Изменить размер Remove Удалить Split Разбить Position to insert Позиция для вставки Save to new file Сохранить в новый файл Document location: Адрес документа: ... ... Document format: Формат: Merge annotations to this file Сохранить связанные аннотации OK Cancel FormatSettingsDialog Custom settings Дополнительные опции Save as default settings Использовать по умолчанию OK Готово Cancel Отмена MultipartDocFormatConfiguratorWidget Create annotation Separate sequences Разделить последовательности Merge sequences Объединить последовательности Gap length: Длина пропуска ProjectTreeItemSelectorDialogBase Select Item Выбор элемента 1 OK Готово Cancel Отмена RemovePartFromSequenceDialog Remove subsequence Удаление подпоследовательности Region to remove Удаляемый регион Remove Удалить Cancel Отмена Annotations region resolving mode Способ обработки аннотаций Resize Изменить размер Save to new file Сохранить в новый файл Merge annotations to this file Сохранить связанные аннотации Document location: Адрес документа: ... Document format: Формат: SelectFormatToSaveDialog Select format to save sequence Выберите формат для сохранения последовательности Create Готово Cancel Отмена SeqPasterWidget Create annotation Paste data here Вставьте текст: Custom settings Дополнительные опции Alphabet: Алфавит: Skip unknown symbols Пропускать неизвестные символы Replace unknown symbols with Заменять незивестные символы: SeqPasterWidgetController Input sequence is empty Входная последовательность пуста Replace symbol is empty Alphabet not detected Алфавит не определён U2::AddExistingDocumentDialogImpl Error! Внутренняя ошибка Project is locked Проект заблокирован open_file_dialog_caption Выбор документа Open file Выбор файла для индексирования File %1 does not exist! Файл %1 не существует! File %1 does not exist! Файл %1 не существует! Document URL is empty! Не указан адрес документа Document is already added! Документ уже добавлен в проект Document format is not selected! Не выбран формат IO adapter not found! Не найден адаптер ввода/вывода Save as Сохранить как U2::AddNewDocumentDialogImpl Save file Создание документа Error! Ошибка Project is locked Проект заблокирован U2::AddToViewTask Add object to view %1 Добавление объекта в окно: %1 Document was removed %1 Документ был удалён: %1 Object not found %1 Объект не найден: "%1" View was closed %1 Окно было закрыто: %1 U2::AnnotationSettingsDialogImpl Annotation name Имя аннотации A color used to highlight annotation If checked the annotation will be shown on amino strand If unchecked the annotation will not be highlighted with color A comma-separated list of qualifier names.<br> The value of qualifiers will be shown instead of the annotation names in PanView Visual qualifiers for %1 Please enter a comma-separated list of qualifier names.<br> <i>The value of qualifiers (with list priority) will be shown instead of the annotation names in PanView</i> U2::CreateAnnotationDialog Create Создать Cancel Отменить Error Ошибка валидации Create annotation Создание аннотации U2::CreateAnnotationWidgetController <auto> <авто> Save file Создание документа Select annotation saving parameters Не выбран объект для размещения аннотации Document is already added to the project: '%1' Документ уже существует: %1 Illegal folder: %1 Не найден путь: %1 Annotation name is empty Не указано имя аннотации Annotation name is too long! Maximum allowed size: %1 (Genbank format compatibility issue) Annotation name is too long Слишком длинное имя аннотации Illegal annotation name Нелегальные символы в имени аннотации. Допустимы только цифры, буквы и подчёркивания Group name is empty Не указано имя группы Illegal group name Нелегальные символы в имени группы Invalid location! Location must be in GenBank format. Simple examples: 1..10 join(1..10,15..45) complement(5..15) Ошибка в задании региона! Регион должен быть задан в формате GenBank. Простые примеры: 1..10 join(1..10,15..45) complement(5..15) Invalid location Неверный регион U2::CreateDocumentFromTextDialogController Select file to save... Сохранение файла Directory to save is not exists Директория не существует No path specified Путь не задан warning Внимание The document already in the project Документ уже открыт в проекте Entered save filepath is empty Не задан путь Sequence name is empty Имя последовательности пусто Filename is empty Не задано имя файла U2::CreateObjectRelationDialogController warning Внимание annotations_out_of_range Аннотированный регион выходит за пределы последовательности Warning Внимание Found annotations that are out of the sequence range, continue? Найдены аннотации, выходящие за границы последовательности. Продолжить? U2::DownloadRemoteFileDialog Select file to save Укажите сохраняемый файл Select directory to save Папка для сохранения Error! Ошибка! Resource id is empty! Идентификатор ресурса пуст! No directory selected for saving file! Не задана директория для сохранения файла! Directory doesn't exists Папка не существует Directory %1 doesn't exists Do you wish to create this directory? Папка %1 не существует Вы желаете создать эту папку? Unable to create directory %1! Невозможно создать папку %1! Directory %1 does not exist! Директория %1 не существует! U2::EditQualifierDialog Error! Проблема Illegal qualifier name Нелегальные символы в имени квалификатора Illegal qualifier value Нелегальные символы в значении квалификатора U2::EditSequenceDialogController Insert sequence Вставить последовательность Replace sequence Заменить последовательность Directory to save is not exists Директория не существует Entered path is empty Не задан путь Filename is empty Не задано имя файла Select file to save... Сохранение файла U2::GObjectView Object is already added to view %1! Объект уже добавлен в окно "%1" Can't add object: %1 Не удалось добавить объект: %1 U2::GUIUtils Error! Ошибка Document URL is empty! Пустая ссылка Unable to launch default web browser. Не удалось запустить стандартный браузер Интернет Please specify the browser executable Не указано приложение браузера U2::Header close Always on top U2::LoadRemoteDocumentAndOpenViewTask Cannot find %1 in %2 database Load remote document and open view U2::LoadUnloadedDocumentAndOpenViewTask Load document: '%1' Загрузка документа: %1 U2::LogViewWidget Log Settings Dump performance counters Append separator Clear log Copy Копировать logview_set_case logview_use_regexp U2::MultiPartDocFormatConfigurator %1 format settings Опции формата %1 U2::Notification Remove notification after closing Detailed message U2::ObjectViewTask Update '%1' to '%2' state Обновление "%1" в состояние "%2" Open new '%1' Открытие нового окна '%1' Open '%1' Открытие окна '%1' U2::ObjectViewTreeController Activate view Переключиться на окно Add bookmark Добавить закладку Remove bookmark Удалить закладку Rename bookmark Переименовать закладку New bookmark Закладка U2::ProjectFileUtils error_open_file %1 Ошибка открытия файла "%1" Project version is not a double value Версия проекта не является вещественным значением Project file was created by a newer version of UGENE. Please update UGENE. Файл проекта был создан более ранней версией UGENE. Пожалуйста, обновите UGENE. Not a valid UGENE project file %1 Некорректный файл проекта UGENE: "%1" U2::ProjectParser10 Can't find project file: %1, ignoring Duplicate document found: %1, ignoring The last loaded state was locked by format U2::ProjectTreeController Remove selected documents Удалить выбранные документы Load selected documents Загрузить выбранные документы Add Добавить Remove Удалить [loading %1%] [прочитано %1%] Existing document Существующий документ Unload selected document Выгрузить выбранные документы Locks: Блокировки: Project is locked Проект заблокирован Group by document Группировать по файлам Group by type Группировать по типам No groups Не группировать Unloaded object refers to unloaded type: %1 Выгруженный объект %1 ссылается на неизвестный тип Unload selected documents Выгрузить выбранные документы Load selected objects Загрузить выбранные объекты Unload selected objects Выгрузить выбранные объекты Lock document for editing Заблокировать внесение изменений Unlock document for editing Снять блокировку изменений U2::RemovePartFromSequenceDialogController There must be only one region to delete Допускается только один регион Unable to parse region to delete Некорректный регион Cannot remove the whole sequence Невозможно уделить всю последовательность Region to delete is out of sequence bounds Регион выходит за границы последовательности Select file to save... Сохранение файла U2::SaveDocumentGroupController Select file location Укажите местонахождение файла U2::UnloadDocumentTask Unload document task: %1 Выгрузка документа: %1 Document '%1' can't be unloaded: Документ "%1" не может быть выгружен save failed! Сохранение провалилось unexpected error неизвестная ошибка Question? Подтверждение Save document: %1 %1 был изменён, сохранить документ? Failed to unload document Не удалось выгрузить документ Failed to unload document: %1, error: %2 There is an active view with document content Документ используется в открытых окнах Document is locked by some algorithm and cannot be unloaded Документ был заблокирован одним из алгоритмов и не может быть выгружен Warning Внимание ugene-1.9.8/src/corelibs/U2Gui/transl/czech.ts0000644000175000017500000021476211651544333017626 0ustar ilyailya AddExistingDocumentDialog add_existing_document_caption Add existing document document_url_label Document location: Add existing document Přidat stávající dokument Document location: Umístění dokumentu: ... Document format: Formát dokumentu: Force read-only mode Vynutit režim pouze pro čtení Custom settings Vlastní nastavení Save file to disk before opening Uložit soubor na disk před otevřením Add Přidat Cancel Zrušit force_format_label Document format: force_read_only_label Force read-only mode add_button Add cancel_button Cancel custom_format_settings Custom settings save2disk_label Save file to disk before opening AddNewDocumentDialog add_new_document_caption Add new document document_type_label Document format document_url_label Document location Add new document Přidat nový dokument Document format Formát dokumentu Document location Umístění dokumentu ... Compress file Zhustit soubor Create Vytvořit Cancel Zrušit create_button Create cancel_button Cancel compress_check Compress file AnnotationSettingsDialog annotation_settings_dialog_title Visualization settings for annotations Visualization settings for annotations Nastavení znázornění pro poznámky Name Název Color Barva Amino Highlight Zvýraznit OK Cancel Zrušit Visual Qualifier Viditelný modifikátor CopyDocumentDialog Copy Document Copy document File name: Document location Format: Document format Save a copy Uložit kopii Save to file Uložit do souboru File format Souborový formát Add to project Přidat do projektu ... Compress file Zhustit soubor Save Uložit Cancel Zrušit CreateAnnotationWidget ... create_annotation_widget Create annotations Save annotation(s) to Uložit poznámku(y) do Existing annotation table Tabulka stávajících poznámek Create new table Vytvořit novou tabulku Annotation parameters Parametry poznámek Group name Název skupiny Predefined group names Předem určené názvy skupin Annotation name Název poznámky Location Umístění Predefined annotation names Create annotations Vytvořit poznámky Annotation location in GenBank format Add/remove complement flag Přidat/Odstranit příznak doplňku CreateDocumentFromTextDialog Create document Vytvořit dokument Document location: Umístění dokumentu: ... Document format: Formát dokumentu: Sequence name Sequence Create Vytvořit OK Create Cancel Zrušit Save file immediately CreateNewObjectDialog object_name_label Object name object_type_label Object type object_document_label Document create_new_document_buton ... create_button Create cancel_button Cancel create_new_object_dialog_caption Create new object Create new object Vytvořit nový předmět Object name Název předmětu Object type Typ předmětu Document Dokument ... Create Vytvořit Cancel Zrušit CreateObjectRelationDialog create_object_relation_title Edit object relations relation_hint Associate object with: ok_button Ok cancel_button Cancel Edit object relations Upravit vztahy mezi předměty Associate object with: Spojit předmět s: Ok OK Cancel Zrušit DownloadRemoteFileDialog Fetch data from remote database Natáhnout data ze vzdálené databáze Resource ID: ID zdroje: Database: Databáze: Save to directory: ... Hint Rada Use database unique identifier. Použít jedinečný databázový identifikátor. OK OK Cancel Zrušit EditQualifierDialog Edit qualifier Upravit modifikátor Name Název Value Hodnota Cancel Zrušit OK EditSequenceDialog Annotations region resolving mode Annotated regions resolving Resize Resize Remove Remove Split Split Position to insert Start position Save to new file Save resulted document to a new file Document location: Document location: ... Document format: Document format: Merge annotations to this file OK Cancel Cancel FormatSettingsDialog Custom settings Nastavení vlastního formátu Save as default settings Uložit jako výchozí nastavení OK Cancel Zrušit MultipartDocFormatConfiguratorWidget Form Create annotation separate_label Separate sequences merge_label Merge sequences gap_label Gap length: Create annotation Create annotation Separate sequences Merge sequences Gap length: ProjectTreeItemSelectorDialogBase Select Item 1 OK Cancel Cancel RemovePartFromSequenceDialog Remove subsequence Odstranit podsekvenci Region to remove Oblast k odstranění OK Remove Cancel Zrušit Annotations region resolving mode Režim vyřešení oblasti opatřené poznámkami Resize Změnit velikost Remove Odstranit Save to new file Uložit výsledný dokument do nového souboru Merge annotations to this file Sloučit poznámky do tohoto souboru Document location: Vyberte umístění dokumentu: ... Document format: Formát dokumentu: SelectFormatToSaveDialog Select format to save sequence Vyberte formát pro uložení sekvence Create Vytvořit OK Create Cancel Zrušit SeqPasterWidget Form Create annotation Paste data here Zde vložit data: Use custom settings Custom settings Create annotation Vytvořit poznámku Custom settings Vlastní nastavení Alphabet: Abeceda: Skip unknown symbols Přeskočit neznámé symboly Replace unknown symbols with Neznámé symboly nahradit SeqPasterWidgetController Input sequence is empty Vstupní sekvence je prázdná Replace symbol is empty Alphabet not detected Nelze určit abecedu U2::AddExistingDocumentDialogImpl open_file_dialog_caption Select document to add dwnld_file_dialog_caption Save as error Error! url_is_empty Document URL is empty! document_is_already_added Document is already added! no_format_selected Document format is not selected! no_io_adapter_found IO adapter not found! project_is_locked Project is locked Error! Chyba! Project is locked Projekt je uzamknut Open file Vyberte dokument, který se má přidat File %1 does not exist! Document URL is empty! Adresa dokumentu (URL) je prázdná! Document is already added! Dokument je již přidán! Document format is not selected! Formát dokumentu není vybrán! IO adapter not found! IO adaptér nenalezen! Save as Uložit jako U2::AddNewDocumentDialogImpl save_file_dialog_caption Save file error Error! project_is_locked Project is locked Error! Error! Project is locked Projekt je uzamknut Save file Uložit soubor U2::AddToViewTask Add object to view %1 Přidat předmět do pohledu %1 Document was removed %1 Dokument byl odstraněn %1 Object not found %1 Předmět nebyl nalezen %1 View was closed %1 Pohled byl zavřen %1 U2::AnnotationSettingsDialogImpl Annotation name Název poznámky A color used to highlight annotation Barva použitá ke zvýraznění poznámky If checked the annotation will be shown on amino strand Je-li zaškrtnuto, poznámka bude ukazována při amino řetězci If unchecked the annotation will not be highlighted with color Není-li zaškrtnuto, poznámka nebude zvýrazňována barvou A comma-separated list of qualifier names.<br> The value of qualifiers will be shown instead of the annotation names in PanView Čárkou oddělený seznam názvů modifikátorů<br> Hodnota modifikátorů se bude ukazovat místo názvů poznámek v přehledovém pohledu Visual qualifiers for %1 Viditelné modifikátory pro %1 Please enter a comma-separated list of qualifier names.<br> <i>The value of qualifiers (with list priority) will be shown instead of the annotation names in PanView</i> Zadejte, prosím, čárkou oddělený seznam názvů modifikátorů<br> <i>Hodnota modifikátorů (s předností v seznamu) se bude ukazovat místo názvů poznámek v přehledovém pohledu</i> U2::CreateAnnotationDialog create_button Create cancel_button Cancel invalid_state_info Error Create Vytvořit Cancel Zrušit Create annotation Vytvořit poznámku Error Chyba U2::CreateAnnotationWidgetController group_name_auto <auto> save_file_dialog_caption Save file no_document_or_annotation_object_selected Select annotation saving parameters document_exists_%1 Document is already added to the project: '%1' dir_not_exists_%1 Illegal folder: %1 <auto> Save file Uložit soubor Select annotation saving parameters Vybrat parametry pro uložení poznámky Document is already added to the project: '%1' Dokument je již přidán do projektu: '%1' Illegal folder: %1 Neplatná složka: %1 Annotation name is empty Název poznámky je prázdný Annotation name is too long! Maximum allowed size: %1 (Genbank format compatibility issue) Název poznámky je příliš dlouhý: %1 (Genbank format compatibility issue) Illegal annotation name Neplatný název poznámky Group name is empty Název skupiny je prázdný Illegal group name Neplatný název skupiny Invalid location! Location must be in GenBank format. Simple examples: 1..10 join(1..10,15..45) complement(5..15) Neplatné umístění U2::CreateDocumentFromTextDialogController Select file to save... Vybrat soubor pro uložení... Directory to save is not exists Target directory does not exist No path specified Filename is empty Název souboru pro uložení je prázdný warning Warning! The document already in the project Entered save filepath is empty No path specified Sequence name is empty Filename to save is empty Filename is empty U2::CreateObjectRelationDialogController warning Warning! annotations_out_of_range Annotations is out of the sequence range Warning Varování Found annotations that are out of the sequence range, continue? Nalezeny poznámky, které jsou mimo rozsah sekvence. Pokračovat? U2::DownloadRemoteFileDialog Select directory to save Error! Error! Resource id is empty! No directory selected for saving file! U2::EditQualifierDialog Error! Chyba! Illegal qualifier name Neplatný název modifikátoru Illegal qualifier value Neplatná hodnota modifikátoru U2::EditSequenceDialogController Insert sequence Replace sequence Directory to save is not exists Cílový adresář neexistuje Entered path is empty Zadaná cesta je prázdná Filename is empty Název souboru pro uložení je prázdný Select file to save... Vybrat soubor pro uložení... U2::GObjectView object_is_already_added_to_view_%1 Object is already added to view %1! Object is already added to view %1! Předmět je již přidán do pohledu %1! Can't add object: %1 Nelze přidat předmět: %1 U2::GUIUtils error Error! Error! Chyba! Document URL is empty! Unable to launch default web browser. Nelze spustit výchozí internetový prohlížeč. Please specify the browser executable Zadejte, prosím, spustitelný soubor prohlížeče setup_web_browser Please specify the browser executable url_is_empty Document URL is empty! U2::Header close Always on top U2::LoadRemoteDocumentAndOpenViewTask Load remote document and open view Cannot find %1 in %2 database U2::LoadUnloadedDocumentAndOpenViewTask Load document: '%1' Nahrát dokument: '%1' U2::LogViewWidget Log Settings Dump performance counters Append separator Clear log Copy logview_set_case logview_use_regexp U2::MultiPartDocFormatConfigurator %1_format_settings %1 format settings %1 format settings %1 nastavení formátu U2::Notification Remove notification after closing Detailed message U2::ObjectViewTask Update '%1' to '%2' state Obnovit '%1' na stav '%2' Open new '%1' Otevřít nový '%1' Open '%1' Otevřít '%1' U2::ObjectViewTreeController activate_view_action Activate view add_bookmark Add bookmark remove_bookmark Remove bookmark rename_bookmark Rename bookmark Activate view Zapnout pohled Add bookmark Přidat záložku Remove bookmark Odstranit záložku Rename bookmark Přejmenovat záložku New bookmark Nová záložka U2::ProjectFileUtils Project version is not a double value Verze projektu není zdvojená hodnota Project file was created by a newer version of UGENE. Please update UGENE. Soubor s projektem byl vytvořen v novější verzi UGENE. Aktualizujte, prosím, UGENE. Not a valid UGENE project file %1 Není platným souborem s projektem UGENE: %1 U2::ProjectParser10 Can't find project file: %1, ignoring Duplicate document found: %1, ignoring The last loaded state was locked by format Poslední nahraný stav byl zamčen formátem U2::ProjectTreeController remove_selected_documents_action Remove selected documents load_selected_documents_action Load selected documents add_submenu Add remove_submenu Remove [loading %1%] [nahrává se %1%] existing_document Existing document unload_sel_doc Unload selected document locks: Locks: project_is_locked Project is locked Group by document Seskupit podle dokumentu Group by type Seskupit podle typu No groups Žádné skupiny Unloaded object refers to unloaded type: %1 Vyložené předměty odkazují na vyložené typy: %1 Load selected documents Nahrát vybrané dokumenty Remove selected documents Odstranit vybrané dokumenty Unload selected document Vyložit vybrané dokumenty Existing document Stávající dokument Add Přidat Remove Odstranit Unload selected documents Vyložit vybrané dokumenty Load selected objects Nahrát vybrané předměty Unload selected objects Vyložit vybrané předměty Locks: Zámky: Project is locked Projekt je uzamknut Lock document for editing Zamknout dokument pro úpravy Unlock document for editing Odemknout dokument pro úpravy U2::RemovePartFromSequenceDialogController There must be only one region to delete Je povolena pouze jedna oblast Unable to parse region to delete Nelze zpracovat cílovou oblast Cannot remove the whole sequence Nelze odstranit celou sekvenci Region to delete is out of sequence bounds Cílová oblast je mimo hranic sekvence Select file to save... Vybrat soubor pro uložení... U2::SaveDocumentGroupController Select file location Vybrat umístění souboru U2::UnloadDocumentTask Unload document task: %1 Úkol vyložení dokumentu: %1 Question? Save document: %1 Uložit dokument: %1 Failed to unload document Failed to unload document: %1, error: %2 There is an active view with document content Document is locked by some algorithm and cannot be unloaded unload_document_%1 Unload document task: %1 Document '%1' can't be unloaded: Dokument '%1' nelze vyložit: save failed! Uložení se nezdařilo! unexpected error Neočekávaná chyba save_doc_title Question? save_doc_text: %1 Save document: %1 document_failed_to_unload: Failed to unload document Warning Upozornění document has active views There is an active view with document content document is live-locked Document is locked by some algorithm and can't be unloaded ugene-1.9.8/src/corelibs/U2Gui/transl/english.ts0000644000175000017500000015331211651544333020154 0ustar ilyailya AddExistingDocumentDialog Add existing document Document location: ... Document format: Force read-only mode Custom settings Save file to disk before opening Add Cancel AddNewDocumentDialog Add new document Document format Document location ... Compress file Create Cancel AnnotationSettingsDialog Visualization settings for annotations Name Color Amino Highlight Visual Qualifier OK Cancel CopyDocumentDialog Save a copy Save to file File format ... Add to project Compress file Save Cancel CreateAnnotationWidget Create annotations Save annotation(s) to Existing annotation table ... Create new table Annotation parameters Group name Predefined group names Annotation name Predefined annotation names Location Annotation location in GenBank format Add/remove complement flag CreateDocumentFromTextDialog Create document Document location: ... Document format: Sequence name Sequence Save file immediately Create Cancel CreateNewObjectDialog Create new object Object name Object type Document ... Create Cancel CreateObjectRelationDialog Edit object relations Associate object with: Ok Cancel DownloadRemoteFileDialog Fetch data from remote database Resource ID: Database: Save to directory: ... Hint Use database unique identifier. OK Cancel EditQualifierDialog Edit qualifier Name Value Cancel OK EditSequenceDialog Annotations region resolving mode Resize Remove Split Position to insert Save to new file Document location: ... Document format: Merge annotations to this file OK Cancel FormatSettingsDialog Custom settings Save as default settings OK Cancel MultipartDocFormatConfiguratorWidget Create annotation Separate sequences Merge sequences Gap length: ProjectTreeItemSelectorDialogBase Select Item 1 OK Cancel RemovePartFromSequenceDialog Remove subsequence Region to remove Remove Cancel Annotations region resolving mode Resize Save to new file Merge annotations to this file Document location: ... Document format: SelectFormatToSaveDialog Select format to save sequence Create Cancel SeqPasterWidget Create annotation Paste data here Custom settings Alphabet: Skip unknown symbols Replace unknown symbols with SeqPasterWidgetController Input sequence is empty Replace symbol is empty Alphabet not detected U2::AddExistingDocumentDialogImpl Error! Project is locked Open file File %1 does not exist! Document URL is empty! Document is already added! Document format is not selected! IO adapter not found! Save as U2::AddNewDocumentDialogImpl Project is locked Save file U2::AddToViewTask Add object to view %1 Document was removed %1 Object not found %1 View was closed %1 U2::AnnotationSettingsDialogImpl Annotation name A color used to highlight annotation If checked the annotation will be shown on amino strand If unchecked the annotation will not be highlighted with color A comma-separated list of qualifier names.<br> The value of qualifiers will be shown instead of the annotation names in PanView Visual qualifiers for %1 Please enter a comma-separated list of qualifier names.<br> <i>The value of qualifiers (with list priority) will be shown instead of the annotation names in PanView</i> U2::CreateAnnotationDialog Create Cancel Create annotation Error U2::CreateAnnotationWidgetController Save file Select annotation saving parameters <auto> Document is already added to the project: '%1' Illegal folder: %1 Annotation name is empty Annotation name is too long! Maximum allowed size: %1 (Genbank format compatibility issue) Illegal annotation name Group name is empty Illegal group name Invalid location! Location must be in GenBank format. Simple examples: 1..10 join(1..10,15..45) complement(5..15) U2::CreateDocumentFromTextDialogController Select file to save... No path specified Sequence name is empty Filename is empty warning The document already in the project U2::CreateObjectRelationDialogController Warning Found annotations that are out of the sequence range, continue? U2::DownloadRemoteFileDialog Select directory to save Resource id is empty! No directory selected for saving file! U2::EditQualifierDialog Error! Illegal qualifier name Illegal qualifier value U2::EditSequenceDialogController Insert sequence Replace sequence Directory to save is not exists Entered path is empty Filename is empty Select file to save... U2::GObjectView Object is already added to view %1! Can't add object: %1 U2::GUIUtils Error! Document URL is empty! Unable to launch default web browser. Please specify the browser executable U2::Header close Always on top U2::LoadRemoteDocumentAndOpenViewTask Cannot find %1 in %2 database Load remote document and open view U2::LoadUnloadedDocumentAndOpenViewTask Load document: '%1' U2::LogViewWidget Log Settings Dump performance counters Append separator Clear log Copy logview_set_case logview_use_regexp U2::MultiPartDocFormatConfigurator %1 format settings U2::Notification Remove notification after closing Detailed message U2::ObjectViewTask Update '%1' to '%2' state Open new '%1' Open '%1' U2::ObjectViewTreeController Activate view Add bookmark Remove bookmark Rename bookmark New bookmark U2::ProjectFileUtils Project version is not a double value Project file was created by a newer version of UGENE. Please update UGENE. Not a valid UGENE project file %1 U2::ProjectParser10 Can't find project file: %1, ignoring Duplicate document found: %1, ignoring The last loaded state was locked by format U2::ProjectTreeController Remove selected documents Load selected documents Lock document for editing Unlock document for editing Unload selected document Group by document Group by type No groups Unloaded object refers to unloaded type: %1 Existing document Add Remove Unload selected documents Load selected objects Unload selected objects [loading %1%] Locks: Project is locked U2::RemovePartFromSequenceDialogController There must be only one region to delete Unable to parse region to delete Cannot remove the whole sequence Region to delete is out of sequence bounds Select file to save... U2::SaveDocumentGroupController Select file location U2::UnloadDocumentTask Unload document task: %1 Document '%1' can't be unloaded: save failed! unexpected error Question? Save document: %1 Failed to unload document Failed to unload document: %1, error: %2 Warning There is an active view with document content Document is locked by some algorithm and cannot be unloaded ugene-1.9.8/src/corelibs/U2Gui/U2Gui.pri0000644000175000017500000000130011651544332016303 0ustar ilyailya# include (U2Gui.pri) MODULE_ID=U2Gui include( ../../ugene_lib_common.pri ) UGENE_RELATIVE_DESTDIR = '' QT += network xml svg DEFINES+= QT_FATAL_ASSERT BUILDING_U2GUI_DLL INCLUDEPATH += ../U2Private/src LIBS += -L../../_release -lU2Core -lU2Formats -lU2Misc -lU2Private !debug_and_release|build_pass { CONFIG(debug, debug|release) { DESTDIR=../../_debug LIBS -= -L../../_release -lU2Core -lU2Formats -lU2Misc -lU2Private LIBS += -L../../_debug -lU2Cored -lU2Formatsd -lU2Miscd -lU2Privated } CONFIG(release, debug|release) { DESTDIR=../../_release } } unix { target.path = $$UGENE_INSTALL_DIR/$$UGENE_RELATIVE_DESTDIR INSTALLS += target } ugene-1.9.8/src/corelibs/U2Misc/0000755000175000017500000000000011651544333015012 5ustar ilyailyaugene-1.9.8/src/corelibs/U2Misc/U2Misc.pro0000644000175000017500000000177311651544333016646 0ustar ilyailyainclude (U2Misc.pri) # Input HEADERS += src/AuthenticationDialog.h \ src/DialogUtils.h \ src/GlassView.h \ src/GraphUtils.h \ src/GScrollBar.h \ src/HBar.h \ src/PositionSelector.h \ src/RangeSelector.h \ src/ScaleBar.h \ src/ScriptEditorDialog.h \ src/TextEditorDialog.h \ src/TreeWidgetUtils.h FORMS += src/ui/AuthentificationDialog.ui \ src/ui/ScriptEditorDialog.ui \ src/ui/TextEditorDialog.ui SOURCES += src/AuthenticationDialog.cpp \ src/DialogUtils.cpp \ src/GlassView.cpp \ src/GraphUtils.cpp \ src/GScrollBar.cpp \ src/HBar.cpp \ src/PositionSelector.cpp \ src/RangeSelector.cpp \ src/ScaleBar.cpp \ src/ScriptEditorDialog.cpp \ src/TextEditorDialog.cpp \ src/TreeWidgetUtils.cpp TRANSLATIONS += transl/czech.ts transl/english.ts transl/russian.ts ugene-1.9.8/src/corelibs/U2Misc/U2Misc.pri0000644000175000017500000000104611651544333016631 0ustar ilyailya# include (U2Misc.pri) UGENE_RELATIVE_DESTDIR = '' MODULE_ID=U2Misc include( ../../ugene_lib_common.pri ) DEFINES+= QT_FATAL_ASSERT BUILDING_U2MISC_DLL LIBS += -L../../_release -lU2Core !debug_and_release|build_pass { CONFIG(debug, debug|release) { DESTDIR=../../_debug LIBS -= -L../../_release -lU2Core LIBS += -L../../_debug -lU2Cored } CONFIG(release, debug|release) { DESTDIR=../../_release } } unix { target.path = $$UGENE_INSTALL_DIR/$$UGENE_RELATIVE_DESTDIR INSTALLS += target } ugene-1.9.8/src/corelibs/U2Misc/src/0000755000175000017500000000000011651544333015601 5ustar ilyailyaugene-1.9.8/src/corelibs/U2Misc/src/PositionSelector.cpp0000644000175000017500000000752011651544333021616 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "PositionSelector.h" #include #include #include #include #include #include #include namespace U2 { PositionSelector::PositionSelector(QWidget* p, int s, int e) : QWidget(p), rangeStart(s), rangeEnd(e), posEdit(NULL), autoclose(false), dialog(NULL) { init(); QToolButton* goButton = new QToolButton(this); goButton->setText(tr("Go!")); goButton->setToolTip(tr("Go to position")); connect(goButton, SIGNAL(clicked(bool)), SLOT(sl_onButtonClicked(bool))); layout()->addWidget(goButton); } void PositionSelector::init() { int w = qMax(((int)log10((double)rangeEnd))*10, 70); posEdit = new QLineEdit(this); posEdit->setValidator(new QIntValidator(rangeStart, rangeEnd, posEdit)); if (dialog == NULL) { posEdit->setFixedWidth(w); } else { posEdit->setMinimumWidth(qMax(120, w)); } posEdit->setAlignment(Qt::AlignRight); posEdit->setToolTip("Enter position here"); connect(posEdit, SIGNAL(returnPressed()), SLOT(sl_onReturnPressed())); QHBoxLayout* l = new QHBoxLayout(this); if (dialog == NULL) { l->setContentsMargins(5, 0, 5, 0); l->setSizeConstraint(QLayout::SetFixedSize); } else { l->setMargin(0); } setLayout(l); if (dialog!=NULL) { QLabel* posLabel = new QLabel(tr("Position"), this); posLabel->setSizePolicy(QSizePolicy::Maximum, QSizePolicy::Preferred); l->addWidget(posLabel); } l->addWidget(posEdit); } PositionSelector::PositionSelector(QDialog* d, int s, int e, bool _a) : QWidget(d), rangeStart(s), rangeEnd(e), posEdit(NULL), autoclose(_a), dialog(d) { init(); QPushButton* okButton = new QPushButton(this); okButton->setText(tr("Go!")); okButton->setDefault(true); connect(okButton, SIGNAL(clicked(bool)), SLOT(sl_onButtonClicked(bool))); QPushButton* cancelButton = new QPushButton(this); cancelButton->setText(tr("Cancel")); connect(cancelButton, SIGNAL(clicked()), d, SLOT(reject())); QHBoxLayout* l3 = new QHBoxLayout(); l3->setMargin(0); l3->addStretch(); l3->addWidget(cancelButton); l3->addWidget(okButton); assert(dialog!=NULL); QVBoxLayout* l2 = new QVBoxLayout(); l2->addWidget(this); l2->addStretch(); l2->addLayout(l3); dialog->setLayout(l2); dialog->resize(l2->minimumSize()); //todo: add checkbox to handle 'autoclose' state } PositionSelector::~PositionSelector(){ } void PositionSelector::sl_onButtonClicked(bool checked) { Q_UNUSED(checked); exec(); } void PositionSelector::sl_onReturnPressed(){ exec(); } void PositionSelector::exec() { bool ok = false; QString text = posEdit->text(); int v = text.toInt(&ok); if (!ok || v < rangeStart || v > rangeEnd) { return; } emit si_positionChanged(v); if (dialog!=NULL && autoclose) { dialog->accept(); } } } //namespace ugene-1.9.8/src/corelibs/U2Misc/src/ScriptEditorDialog.cpp0000644000175000017500000002132611651544333022044 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "ScriptEditorDialog.h" #include #include #include #include #include #include #include #include namespace U2 { ScriptEditorDialog::ScriptEditorDialog(QWidget* w, const QString& roHeaderText, const QString & scriptText) :QDialog(w) { ui = new Ui_ScriptEditorDialog(); ui->setupUi(this); setModal(true); ui->headerEdit->setText(roHeaderText); ui->headerEdit->setReadOnly(true); ScriptHighlighter* h1 = new ScriptHighlighter(ui->headerEdit->document()); h1->setParent(this); ScriptHighlighter* h2 = new ScriptHighlighter(ui->scriptEdit->document()); h2->setParent(this); ui->scriptEdit->setText(scriptText); connect(ui->checkButton, SIGNAL(clicked()), SLOT(sl_checkSyntax())); connect(ui->openButton, SIGNAL(clicked()), SLOT(sl_openScript())); connect(ui->saveButton, SIGNAL(clicked()), SLOT(sl_saveScript())); connect(ui->saveAsButton, SIGNAL(clicked()), SLOT(sl_saveAsScript())); connect(ui->scriptPathEdit, SIGNAL(textChanged(const QString&)), SLOT(sl_nameChanged(const QString&))); connect(ui->scriptEdit, SIGNAL(textChanged()), SLOT(sl_scriptChanged())); connect(ui->scriptEdit, SIGNAL(cursorPositionChanged()), SLOT(sl_cursorPositionChanged())); updateState(); } void ScriptEditorDialog::sl_nameChanged(const QString&) { updateState(); } void ScriptEditorDialog::sl_scriptChanged() { updateState(); } void ScriptEditorDialog::updateState() { bool hasScript = !ui->scriptEdit->toPlainText().simplified().isEmpty(); bool hasPath = !ui->scriptPathEdit->text().isEmpty(); ui->saveButton->setEnabled(hasPath && hasScript); } void ScriptEditorDialog::setScriptText(const QString& text) { ui->scriptPathEdit->clear(); ui->scriptEdit->setText(text); } void ScriptEditorDialog::setScriptPath(const QString& path) { QFile file(path); bool ok = file.open(QFile::ReadOnly); if (file.size() > 100*1000) { QMessageBox::critical(this, L10N::errorTitle(), tr("File is too large %1").arg(path)); return; } if (!ok) { QMessageBox::critical(this, L10N::errorTitle(), L10N::errorOpeningFileRead(path)); return; } QByteArray script = file.readAll(); ui->scriptEdit->setText(script); ui->scriptPathEdit->setText(path); } #define SCRIPTS_DOMAIN QString("scripts") void ScriptEditorDialog::sl_openScript() { LastOpenDirHelper ld(SCRIPTS_DOMAIN); ld.url = QFileDialog::getOpenFileName(this, tr("Select script to open"), ld.dir, getScriptsFileFilter()); if (ld.url.isEmpty()) { return; } setScriptPath(ld.url); } void ScriptEditorDialog::sl_saveScript() { QString url = ui->scriptPathEdit->text(); if (url.isEmpty()) { sl_saveAsScript(); } else { save(url); } } void ScriptEditorDialog::sl_saveAsScript() { QString script = ui->scriptEdit->toPlainText(); if (script.simplified().isEmpty()) { QMessageBox::critical(this, L10N::errorTitle(), tr("Script is empty!")); return; } LastOpenDirHelper ld(SCRIPTS_DOMAIN); ld.url = QFileDialog::getSaveFileName(this, tr("Save script to file"), ld.dir, getScriptsFileFilter()); if (ld.url.isEmpty()) { return; } save(ld.url); } void ScriptEditorDialog::save(const QString& url) { QString script = ui->scriptEdit->toPlainText(); QFile file(url); bool ok = file.open(QFile::WriteOnly | QFile::Truncate); if (!ok) { QMessageBox::critical(this, L10N::errorTitle(), L10N::errorWritingFile(url)); return; } file.write(script.toLocal8Bit()); ui->scriptPathEdit->setText(url); } QString ScriptEditorDialog::getScriptsFileFilter() { return DialogUtils::prepareFileFilter(tr("Script files"), QStringList("js"), true); } void ScriptEditorDialog::sl_checkSyntax() { QScriptEngine engine; QString header = ui->headerEdit->toPlainText(); QString scriptText = header + "\n" + ui->scriptEdit->toPlainText(); QScriptSyntaxCheckResult syntaxResult = engine.checkSyntax(scriptText); if (syntaxResult.state() != QScriptSyntaxCheckResult::Valid) { int line = syntaxResult.errorLineNumber(); line -= header.split("\n").size(); QString errorMessage = tr("Script syntax check failed! Line: %1, error: %2").arg(line).arg(syntaxResult.errorMessage()); QMessageBox::warning(this, tr("Check result"), errorMessage); } else { QMessageBox::information(this, tr("Check result"), tr("Syntax is OK!")); } } ScriptEditorDialog::~ScriptEditorDialog() { delete ui; } QString ScriptEditorDialog::getScriptText() const { return ui->scriptEdit->toPlainText(); } void ScriptEditorDialog::sl_cursorPositionChanged(){ int lineNumber = ui->scriptEdit->textCursor().block().blockNumber(); ui->lineInfo->setText("Line: " + QString::number(lineNumber + 1)); } ////////////////////////////////////////////////////////////////////////// // Script highlighter ScriptHighlighter::ScriptHighlighter(QTextDocument *parent) : QSyntaxHighlighter(parent) { HighlightingRule rule; keywordFormat.setForeground(Qt::darkBlue); keywordFormat.setFontWeight(QFont::Bold); QStringList keywordPatterns; keywordPatterns << "\\bvar\\b" << "\\bArray\\b" << "\\bfunction\\b" << "\\breturn\\b" << "\\barguments\\b" << "\\bif\\b" << "\\belse\\b" << "\\bfor\\b" << "\\bswitch\\b" << "\\bcase\\b" << "\\bbreak\\b" << "\\bwhile\\b"; foreach (const QString &pattern, keywordPatterns) { rule.pattern = QRegExp(pattern); rule.format = keywordFormat; highlightingRules.append(rule); } // Values QTextCharFormat valueFormat; valueFormat.setForeground(Qt::blue); rule.format = valueFormat; rule.pattern = QRegExp("\\btrue\\b|\\bfalse\\b|\\b[0-9]+\\b"); highlightingRules.append(rule); QTextCharFormat functionFormat; functionFormat.setForeground(Qt::darkBlue); rule.format = functionFormat; rule.pattern = QRegExp("\\b[A-Za-z0-9_]+(?=\\()"); highlightingRules.append(rule); // Quotation QTextCharFormat quotationFormat; quotationFormat.setForeground(Qt::blue); rule.format = quotationFormat; rule.pattern = QRegExp("\"[^\"]*\""); highlightingRules.append(rule); // Single Line Comments QTextCharFormat singleLineCommentFormat; singleLineCommentFormat.setForeground(Qt::darkGreen); rule.format = singleLineCommentFormat; rule.pattern = QRegExp("//[^\n]*"); highlightingRules.append(rule); multiLineCommentFormat.setForeground(Qt::darkGreen); commentStartExpression = QRegExp("/\\*"); commentEndExpression = QRegExp("\\*/"); } void ScriptHighlighter::highlightBlock(const QString &text) { foreach (const HighlightingRule &rule, highlightingRules) { QRegExp expression(rule.pattern); int index = expression.indexIn(text); while (index >= 0) { int length = expression.matchedLength(); setFormat(index, length, rule.format); index = expression.indexIn(text, index + length); } } setCurrentBlockState(0); int startIndex = 0; if (previousBlockState() != 1) { startIndex = commentStartExpression.indexIn(text); } while (startIndex >= 0) { int endIndex = commentEndExpression.indexIn(text, startIndex); int commentLength; if (endIndex == -1) { setCurrentBlockState(1); commentLength = text.length() - startIndex; } else { commentLength = endIndex - startIndex + commentEndExpression.matchedLength(); } setFormat(startIndex, commentLength, multiLineCommentFormat); startIndex = commentStartExpression.indexIn(text, startIndex + commentLength); } } }// namespace ugene-1.9.8/src/corelibs/U2Misc/src/GlassView.cpp0000644000175000017500000000504311651544333020213 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "GlassView.h" #include #include #include namespace U2 { void GlassView::setGlass(GlassPane* glp) { glass = glp; if (glass) { glass->resize(viewport()->size()); } //scene()->update(); viewport()->update(); } void GlassView::paintEvent( QPaintEvent * e) { QGraphicsView::paintEvent(e); if (glass) { QPainter painter; painter.begin(viewport()); //painter.setClipRect(e->rect()); glass->paint(&painter); } } void GlassView::scrollContentsBy(int dx, int dy) { QGraphicsView::scrollContentsBy(dx,dy); if (glass) { viewport()->update(); } } bool GlassView::viewportEvent( QEvent * e ) { if (glass) { switch (e->type()) { case QEvent::Resize: glass->resize(((QResizeEvent*)e)->size()); case QEvent::Paint: return QGraphicsView::viewportEvent(e); case QEvent::MouseButtonDblClick: case QEvent::MouseButtonPress: case QEvent::MouseButtonRelease: case QEvent::KeyPress: case QEvent::KeyRelease: case QEvent::FocusIn: case QEvent::FocusOut: case QEvent::Enter : case QEvent::Leave: case QEvent::Wheel: case QEvent::DragEnter: case QEvent::DragMove: case QEvent::DragLeave: case QEvent::Drop: case QEvent::HoverEnter: case QEvent::HoverLeave: case QEvent::HoverMove: if (glass->eventFilter(this, e)) { return true; } break; default: break; } } // else return QGraphicsView::viewportEvent(e); } }//namespace ugene-1.9.8/src/corelibs/U2Misc/src/TextEditorDialog.cpp0000644000175000017500000000352511651544333021525 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "TextEditorDialog.h" #include #include namespace U2 { TextEditorDialog::TextEditorDialog(QWidget* parent, const QString& title, const QString& label, const QString& text, bool acceptOnEnter) : QDialog(parent) { ui = new Ui_TextEditorDialog(); ui->setupUi(this); setWindowTitle(title); ui->valueLabel->setText(label); ui->textEdit->setPlainText(text); if (acceptOnEnter) { ui->textEdit->installEventFilter(this); } } bool TextEditorDialog::eventFilter(QObject *o, QEvent *e) { if (o == ui->textEdit) { if (e->type() == QEvent::KeyPress) { QKeyEvent* ke = (QKeyEvent*)e; if (ke->key() == Qt::Key_Enter || ke->key() == Qt::Key_Return) { accept(); return true; } } } return false; } QString TextEditorDialog::getText() { return ui->textEdit->toPlainText(); } TextEditorDialog::~TextEditorDialog() { delete ui; } } //namespace ugene-1.9.8/src/corelibs/U2Misc/src/RangeSelector.h0000644000175000017500000000336111651544333020512 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_RANGE_SELECTOR_H_ #define _U2_RANGE_SELECTOR_H_ #include #include #include namespace U2 { class U2MISC_EXPORT RangeSelector : public QWidget { Q_OBJECT public: RangeSelector(QWidget* p, int rangeStart, int rangeEnd); RangeSelector(QDialog* d, int rangeStart, int rangeEnd, int len, bool autoclose); ~RangeSelector(); int getStart() const; int getEnd() const; signals: void si_rangeChanged(int startPos, int endPos); private slots: void sl_onGoButtonClicked(bool); void sl_onMinButtonClicked(bool); void sl_onMaxButtonClicked(bool); void sl_onReturnPressed(); private: void init(); void exec(); int rangeStart; int rangeEnd; int len; QLineEdit* startEdit; QLineEdit* endEdit; QDialog* dialog; bool autoclose; }; }//namespace #endif ugene-1.9.8/src/corelibs/U2Misc/src/RangeSelector.cpp0000644000175000017500000001327111651544333021046 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "RangeSelector.h" #include #include #include #include #include #include #include namespace U2 { RangeSelector::RangeSelector(QWidget* p, int s, int e) : QWidget(p), rangeStart(s), rangeEnd(e), startEdit(NULL), endEdit(NULL), dialog(NULL), autoclose(false) { init(); QToolButton* goButton = new QToolButton(this); goButton->setText(tr("Ok")); connect(goButton, SIGNAL(clicked(bool)), SLOT(sl_onGoButtonClicked(bool))); layout()->addWidget(goButton); } void RangeSelector::init() { int w = qMax(((int)log10((double)rangeEnd))*10, 70); startEdit = new QLineEdit(this); startEdit->setValidator(new QIntValidator(1, len, startEdit)); if (dialog == NULL) { startEdit->setFixedWidth(w); } else { startEdit->setMinimumWidth(w); } startEdit->setAlignment(Qt::AlignRight); startEdit->setText(QString::number(rangeStart)); connect(startEdit, SIGNAL(returnPressed()), SLOT(sl_onReturnPressed())); endEdit = new QLineEdit(this); endEdit->setValidator(new QIntValidator(1, len, startEdit)); if (dialog == NULL) { endEdit->setFixedWidth(w); } else { endEdit->setMinimumWidth(w); } endEdit->setAlignment(Qt::AlignRight); endEdit->setText(QString::number(rangeEnd)); connect(endEdit, SIGNAL(returnPressed()), SLOT(sl_onReturnPressed())); QToolButton* minButton = new QToolButton(this); minButton->setText(tr("Min")); connect(minButton, SIGNAL(clicked(bool)), SLOT(sl_onMinButtonClicked(bool))); QToolButton* maxButton = new QToolButton(this); maxButton->setText(tr("Max")); connect(maxButton, SIGNAL(clicked(bool)), SLOT(sl_onMaxButtonClicked(bool))); if (dialog != NULL) { minButton->setShortcut(QKeySequence(Qt::ALT | Qt::Key_Z)); maxButton->setShortcut(QKeySequence(Qt::ALT | Qt::Key_X)); } QHBoxLayout* l = new QHBoxLayout(this); if (dialog == NULL) { l->setContentsMargins(5, 0, 5, 0); l->setSizeConstraint(QLayout::SetFixedSize); } else { l->setMargin(0); } setLayout(l); QLabel* rangeLabel = new QLabel(tr("Range:"), this); rangeLabel->setSizePolicy(QSizePolicy::Maximum, QSizePolicy::Preferred); startEdit->setObjectName("start_edit_line"); endEdit->setObjectName("end_edit_line"); minButton->setObjectName("min_val_button"); maxButton->setObjectName("max_val_button"); this->setObjectName("range_selector"); l->addWidget(rangeLabel); l->addWidget(minButton); l->addWidget(startEdit); l->addWidget(new QLabel(tr("-"), this)); l->addWidget(endEdit); l->addWidget(maxButton); } RangeSelector::RangeSelector(QDialog* d, int s, int e, int _len, bool a) : QWidget(d), rangeStart(s), rangeEnd(e), len(_len), startEdit(NULL), endEdit(NULL), dialog(d), autoclose(a) { init(); QPushButton* okButton = new QPushButton(this); okButton->setText(tr("Ok")); okButton->setDefault(true); okButton->setObjectName("ok_button"); connect(okButton, SIGNAL(clicked(bool)), SLOT(sl_onGoButtonClicked(bool))); QPushButton* cancelButton = new QPushButton(this); cancelButton->setText(tr("Cancel")); cancelButton->setObjectName("cancel_button"); connect(cancelButton, SIGNAL(clicked()), d, SLOT(reject())); QHBoxLayout* l3 = new QHBoxLayout(); l3->setMargin(0); l3->addStretch(); l3->addWidget(okButton); l3->addWidget(cancelButton); assert(dialog!=NULL); QVBoxLayout* l2 = new QVBoxLayout(); l2->addWidget(this); l2->addStretch(); l2->addLayout(l3); dialog->setObjectName("range_selection_dialog"); dialog->setLayout(l2); dialog->resize(l2->minimumSize()); } RangeSelector::~RangeSelector(){ // printf("DELETED\n"); } void RangeSelector::sl_onGoButtonClicked(bool checked) { Q_UNUSED(checked); exec(); } void RangeSelector::sl_onReturnPressed() { exec(); } void RangeSelector::exec() { bool ok = false; int v1 = startEdit->text().toInt(&ok); if (!ok || v1 < 1 || v1 > len) { return; } int v2 = endEdit->text().toInt(&ok); if (!ok || v2 < v1 || v2 > len) { return; } emit si_rangeChanged(v1, v2); if (dialog!=NULL && autoclose) { dialog->accept(); } } void RangeSelector::sl_onMinButtonClicked(bool checked) { Q_UNUSED(checked); startEdit->setText(QString::number(1)); } void RangeSelector::sl_onMaxButtonClicked(bool checked) { Q_UNUSED(checked); endEdit->setText(QString::number(len)); } int RangeSelector::getStart() const { bool ok = false; int v = startEdit->text().toInt(&ok); assert(ok); return v; } int RangeSelector::getEnd() const { bool ok = false; int v = endEdit->text().toInt(&ok); assert(ok); return v; } } //namespace ugene-1.9.8/src/corelibs/U2Misc/src/PositionSelector.h0000644000175000017500000000316511651544333021264 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_POSITION_SELECTOR_H_ #define _U2_POSITION_SELECTOR_H_ #include #include #include #include namespace U2 { class U2MISC_EXPORT PositionSelector : public QWidget { Q_OBJECT public: PositionSelector(QWidget* p, int rangeStart, int rangeEnd); PositionSelector(QDialog* d, int rangeStart, int rangeEnd, bool autoclose); ~PositionSelector(); QLineEdit* getPosEdit() const {return posEdit;} signals: void si_positionChanged(int pos); private slots: void sl_onButtonClicked(bool); void sl_onReturnPressed(); private: void init(); void exec(); int rangeStart; int rangeEnd; QLineEdit* posEdit; bool autoclose; QDialog* dialog; }; }//namespace #endif ugene-1.9.8/src/corelibs/U2Misc/src/TreeWidgetUtils.h0000644000175000017500000000251611651544333021042 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_TREE_WIDGET_UTILS_H_ #define _U2_TREE_WIDGET_UTILS_H_ #include #include namespace U2{ class TreeWidgetVisitor { public: virtual ~TreeWidgetVisitor(){} virtual bool isChildVisitRequired(QTreeWidgetItem*) {return true;} virtual void visit(QTreeWidgetItem* item) = 0; }; class U2MISC_EXPORT TreeWidgetUtils { private: TreeWidgetUtils(){} public: static void visitDFS(QTreeWidget* tree, TreeWidgetVisitor* visitor); }; } #endif ugene-1.9.8/src/corelibs/U2Misc/src/TreeWidgetUtils.cpp0000644000175000017500000000271511651544333021376 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "TreeWidgetUtils.h" namespace U2 { static void visitBranchDFS(QTreeWidgetItem* item, TreeWidgetVisitor* visitor) { if (visitor->isChildVisitRequired(item)) { for (int i = 0; i < item->childCount(); i++) { QTreeWidgetItem* child = item->child(i); visitBranchDFS(child, visitor); } } visitor->visit(item); } void TreeWidgetUtils::visitDFS(QTreeWidget* tree, TreeWidgetVisitor* visitor) { for (int i = 0; i < tree->topLevelItemCount(); i++) { QTreeWidgetItem* child = tree->topLevelItem(i); visitBranchDFS(child, visitor); } } } //namespace ugene-1.9.8/src/corelibs/U2Misc/src/GlassView.h0000644000175000017500000000315411651544333017661 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_GLASS_VIEW_H_ #define _U2_GLASS_VIEW_H_ #include #include class QTextDocument; namespace U2 { class U2MISC_EXPORT GlassPane : public QWidget { Q_OBJECT public: GlassPane(QWidget* parent = 0) : QWidget(parent) {} virtual void paint(QPainter*) = 0; virtual bool eventFilter(QObject*, QEvent* e) { return this->event(e); } }; class U2MISC_EXPORT GlassView : public QGraphicsView { Q_OBJECT public: GlassView(QGraphicsScene * scene) : QGraphicsView(scene), glass(NULL) {} public slots: void setGlass(GlassPane*); protected: bool viewportEvent(QEvent * event); void paintEvent(QPaintEvent *); void scrollContentsBy(int dx, int dy); GlassPane* glass; }; }//namespace #endif ugene-1.9.8/src/corelibs/U2Misc/src/DialogUtils.h0000644000175000017500000000575511651544333020206 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_DIALOG_UTILS_H_ #define _U2_DIALOG_UTILS_H_ #include #include #include #include namespace U2 { class DocumentFormatConstraints; class Logger; class TaskStateInfo; class U2MISC_EXPORT DialogUtils : public QObject { Q_OBJECT public: static void showProjectIsLockedWarning(QWidget* p = NULL); static QString prepareFileFilter(const QString& name, const QStringList& exts, bool any = true, const QStringList& extraExts = QStringList(".gz")); static QString prepareDocumentsFileFilter(const DocumentFormatId& fid, bool any, const QStringList& extraExts = QStringList(".gz")); //returns filter for all formats supported. All-docs filter is returned first if any==true static QString prepareDocumentsFileFilter(bool any, const QStringList& extraExts = QStringList(".gz")); static QString prepareDocumentsFileFilter(const DocumentFormatConstraints& c, bool any); static QString prepareDocumentsFileFilterByObjType(const GObjectType& t, bool any); static QString getLastOpenFileDir(const QString& toolType = QString(), const QString& defaultVal = QString()); static void setLastOpenFileDir(const QString& ld, const QString& toolType = QString()); static QPair selectFileForScreenShot(QWidget * parent); }; class U2MISC_EXPORT LastOpenDirHelper { public: LastOpenDirHelper(const QString& domain = QString(), const QString& defaultVal = QString()); //reads dir virtual ~LastOpenDirHelper(); //if url is not empty -> derives dir from url and stores it operator const QString&() const {return dir;} void saveURLDir2LastOpenDir(); QString domain; //last used dir QString dir; // value returned by file dialog QString url; }; class U2MISC_EXPORT FileLineEdit : public QLineEdit { Q_OBJECT public: FileLineEdit(const QString& filter, const QString& type, bool multi, QWidget *parent) : QLineEdit(parent), FileFilter(filter), type(type), multi(multi) {} private slots: void sl_onBrowse(); private: QString FileFilter; QString type; bool multi; }; } // namespace #endif ugene-1.9.8/src/corelibs/U2Misc/src/AuthenticationDialog.h0000644000175000017500000000254611651544333022060 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_AUTHENTIFICATION_DIALOG_H_ #define _U2_AUTHENTIFICATION_DIALOG_H_ #include #include class Ui_AuthentificationDialog; namespace U2 { class U2MISC_EXPORT AuthDialog : public QDialog { Q_OBJECT public: AuthDialog(QWidget* parent); ~AuthDialog(); QString getUserName() const; QString getPasswd() const; bool rememberAuthData() const; private slots: void sl_onOkButtonClicked(); private: Ui_AuthentificationDialog* ui; }; } // namespace #endif ugene-1.9.8/src/corelibs/U2Misc/src/ui/0000755000175000017500000000000011651544333016216 5ustar ilyailyaugene-1.9.8/src/corelibs/U2Misc/src/ui/ScriptEditorDialog.ui0000644000175000017500000000757511651544333022326 0ustar ilyailya ScriptEditorDialog 0 0 506 339 Script editor Used script ... Script text Qt::Vertical Check syntax Save Qt::Horizontal 40 20 Clear Save as.. Done Cancel Line: cancelButton clicked() ScriptEditorDialog reject() 352 189 199 105 okButton clicked() ScriptEditorDialog accept() 271 189 199 105 ugene-1.9.8/src/corelibs/U2Misc/src/ui/AuthentificationDialog.ui0000644000175000017500000000650111651544333023175 0ustar ilyailya AuthentificationDialog 0 0 284 127 Authentification Enter name: Qt::Horizontal 68 20 Enter password: Qt::Horizontal 68 20 QLineEdit::Password Qt::Vertical 20 4 Qt::Horizontal 40 20 OK Cancel Remember me cancelButton clicked() AuthentificationDialog reject() 137 48 92 35 ugene-1.9.8/src/corelibs/U2Misc/src/ui/TextEditorDialog.ui0000644000175000017500000000422711651544333021775 0ustar ilyailya TextEditorDialog 0 0 400 300 Value editor Value: Qt::Horizontal 40 20 OK true Cancel okButton clicked() TextEditorDialog accept() 268 277 199 149 cancelButton clicked() TextEditorDialog reject() 351 277 199 149 ugene-1.9.8/src/corelibs/U2Misc/src/GraphUtils.cpp0000644000175000017500000003756111651544333020403 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "GraphUtils.h" #include #include #include #include namespace U2 { static void drawNum(QPainter& p, int x1, int x2, const QString& num, int lBorder, int rBorder, int y1, int y2) { if (x1 < lBorder|| x2 > rBorder) { return; } QRect rect(x1, y1, x2-x1+1, y2-y1+1); p.drawText(rect, Qt::AlignVCenter | Qt::AlignHCenter, num); } #define MIN_RULER_LEN 10 void GraphUtils::drawRuler(QPainter& p, const QPoint& pos, qint64 len, qint64 start, qint64 end, const QFont& font, const RulerConfig& c) { if (start == end || len < MIN_RULER_LEN) { return; } p.save(); assert(c.drawArrow != c.drawBorderNotches); assert(c.drawArrow ? c.drawAxis : true); p.setFont(font); QFontMetrics fm = p.fontMetrics(); int cw = fm.width('0'); int ch = fm.height(); QString st = FormatUtils::splitThousands(start); QString en = FormatUtils::splitThousands(end); int stW = fm.width(st); int enW = fm.width(en); qint64 span = qMax(start, end) - qMin(start, end); int chunk = c.predefinedChunk == 0 ? calculateChunk(start, end, len, p) : c.predefinedChunk; assert(span / chunk < 1000); while (chunk > span) { chunk /= 2; } float scale = len / (float)span; if (c.direction == BTT) { if(c.drawAxis) { p.drawLine(pos.x(), pos.y() - c.extraAxisLenBefore, pos.x(), pos.y() + len + c.extraAxisLenAfter); } if (c.drawBorderNotches) { p.drawLine(pos.x()-c.notchSize, pos.y(), pos.x() + c.notchSize, pos.y()); p.drawLine(pos.x()-c.notchSize, pos.y() + len, pos.x() + c.notchSize, pos.y() + len); } if (c.drawArrow) { p.drawLine(pos.x(), pos.y(), pos.x() - c.arrowWidth, pos.y() + c.arrowLen); p.drawLine(pos.x(), pos.y(), pos.x() + c.arrowWidth, pos.y() + c.arrowLen); } if (c.drawNumbers) { if (c.textPosition == LEFT) { p.drawText(pos.x() - c.textOffset - st.length() * cw, pos.y() + len, st); p.drawText(pos.x() - c.textOffset - en.length() * cw, pos.y() + ch, en); } else { assert(c.textPosition == RIGHT); p.drawText(pos.x() + c.textOffset, pos.y() + len, st); p.drawText(pos.x() + c.textOffset, pos.y() + ch, en); } } } else if (c.direction == TTB) { int notchDX1 = c.notchSize; int notchDX2 = c.notchSize; QFontMetrics fm(font); int fontHeight = fm.height(); if(c.drawAxis) { p.drawLine(pos.x(), pos.y() - c.extraAxisLenBefore , pos.x(), pos.y() + len + c.extraAxisLenAfter); } if (c.drawBorderNotches) { p.drawLine(pos.x()- c.notchSize, pos.y(), pos.x() + c.notchSize, pos.y()); p.drawLine(pos.x()- c.notchSize, pos.y() + len, pos.x() + c.notchSize, pos.y() + len); } if (c.drawArrow) { p.drawLine(pos.x(), pos.y() + len, pos.x() - c.arrowWidth, pos.y() + len - c.arrowLen); p.drawLine(pos.x(), pos.y() + len, pos.x() + c.arrowWidth, pos.y() + len - c.arrowLen); } if (start / chunk != end / chunk) { int currnotch; if(c.correction != NULL){ currnotch = c.correction; }else{ currnotch = chunk * (start / chunk + 1); } for (; currnotch < end; currnotch += chunk) { int y = qRound((end - currnotch) * scale); if (c.drawNotches) { p.drawLine(pos.x() - notchDX1, pos.y() + len - y, pos.x() + notchDX2, pos.y() + len - y); } if (c.drawNumbers) { QString snum = FormatUtils::formatNumber(currnotch); if( y > fontHeight){ if (c.textPosition == LEFT) { p.drawText(pos.x() - c.textOffset - snum.length() * cw, pos.y() + len - y, snum); }else{ assert(c.textPosition == RIGHT); p.drawText(pos.x() + c.textOffset - snum.length() * cw, pos.y() + len - y, snum); } } } } } if (c.drawNumbers) { QString endStr = QString::number(end); int roundedEnd = end, endLen = endStr.length(); if (endLen >= 4){ endStr = endStr.left(endLen - 3); roundedEnd = endStr.toInt() * pow((double)10 , (double)(3)); //roundedEnd = endStr.toInt() * pow((double)10 , (double)(endLen - 3)); } endStr = FormatUtils::formatNumber(roundedEnd); if (c.textPosition == LEFT) { p.drawText(pos.x() - c.textOffset - endStr.length() * cw, pos.y() + len, endStr); } else { assert(c.textPosition == RIGHT); p.drawText(pos.x() + c.textOffset - endStr.length() * cw, pos.y() + len, endStr); } } } else { int notchDY1 = c.notchSize; int notchDY2 = c.notchSize; if (c.singleSideNotches) { if (c.textPosition == LEFT) { notchDY2 = 0; } else { notchDY1 = 0; } } if(c.drawAxis) { p.drawLine(pos.x() - c.extraAxisLenBefore, pos.y(), pos.x() + len + c.extraAxisLenAfter, pos.y()); } if (c.drawBorderNotches) { p.drawLine(pos.x(), pos.y() - notchDY1, pos.x(), pos.y() + notchDY2); p.drawLine(pos.x() + len, pos.y() - notchDY1, pos.x() + len, pos.y() + notchDY2); } //text properties int yt1 = c.textPosition == LEFT ? pos.y() - c.textOffset - ch : pos.y() + c.textOffset; int yt2 = c.textPosition == LEFT ? pos.y() - c.textOffset : pos.y() + c.textOffset + ch; int stX1 = pos.x() + c.textBorderStart; int stX2 = pos.x() + stW; int enX1 = pos.x() + len - enW; int enX2 = pos.x() + len - c.textBorderEnd; if (c.drawNumbers) { drawNum(p, stX1, stX2, st, stX1, stX2, yt1, yt2); drawNum(p, enX1, enX2, en, enX1, enX2, yt1, yt2); } if (c.direction == LTR) { int leftborder = stX2; int rightborder= enX1; if (c.drawArrow) { p.drawLine(pos.x() + len, pos.y(), pos.x() + len - c.arrowLen, pos.y() - c.arrowWidth); p.drawLine(pos.x() + len, pos.y(), pos.x() + len - c.arrowLen, pos.y() + c.arrowWidth); } if (start / chunk != end / chunk) { int currnotch; if(c.correction != NULL){ currnotch = c.correction; }else{ currnotch = chunk * (start / chunk + 1); } for (; currnotch < end; currnotch += chunk) { int x = qRound(scale * (currnotch - start)); if (c.drawNotches) { p.drawLine(pos.x() + x, pos.y() - notchDY1, pos.x() + x, pos.y() + notchDY2); } if (c.drawNumbers) { QString snum = FormatUtils::formatNumber(currnotch); int notchleft = pos.x() + x - snum.length() * cw / 2; int notchright = notchleft + snum.length() * cw; drawNum(p, notchleft, notchright, snum, leftborder, rightborder, yt1, yt2); } } } } else if (c.direction == RTL) { int leftborder = enX2; int rightborder= stX1; if (c.drawArrow) { p.drawLine(pos.x(), pos.y(), pos.x() + c.arrowLen, pos.y() - c.arrowWidth); p.drawLine(pos.x(), pos.y(), pos.x() + c.arrowLen, pos.y() + c.arrowWidth); } if (start / chunk != end / chunk) { int currnotch; if(c.correction != NULL){ currnotch = c.correction; }else{ currnotch = chunk * (start / chunk + 1); } for (; currnotch < end; currnotch += chunk) { int x = qRound((currnotch - start) * scale); if (c.drawNotches) { p.drawLine(pos.x() + len - x, pos.y() - notchDY1, pos.x() + len - x, pos.y() + notchDY2); } if (c.drawNumbers) { QString snum = FormatUtils::formatNumber(currnotch); int notchleft = pos.x() + len - x - snum.length() * cw / 2; int notchright = notchleft + snum.length() * cw; drawNum(p, notchleft, notchright, snum, leftborder, rightborder, yt1, yt2); } } } } } p.restore(); } int GraphUtils::findChunk(qint64 len, qint64 span, int N) { int dN = 0; int chunk = 1; while (span > 2 * chunk) { //dN = chunk > (1000 * 1000)? cw * 2 : (chunk > 1000 ? cw * 2 : 0); qint64 reqLen = qint64((double(span) / chunk) * (N - dN)); assert(reqLen > 0); if (reqLen < len) { break; } if (reqLen / 2 < len) { int cchunk = chunk*2; //dN = cchunk > (1000 * 1000)? cw * 2 :cchunk > 1000 ? cw * 2 : 0; qint64 reqLen2 = qint64((double(span) / cchunk) * (N - dN)); if (reqLen2 < len) { chunk = cchunk; break; } } if (reqLen / 5 < len) { int cchunk = chunk*5; //dN = cchunk > (1000 * 1000)? cw * 2 :cchunk > 1000 ? cw * 2 : 0; qint64 reqLen5 = qint64((double(span) / cchunk) * (N - dN)); if (reqLen5 < len) { chunk = cchunk; break; } } chunk *= 10; } assert(span / chunk < 1000); while (chunk > span) { chunk /= 2; } return chunk; } /* void GraphUtils::drawDensityPlot(QPainter& p, QRect& drawRect, QRect& calcRect, quint32 n, quint32* x, quint32* y, quint32* len){ if (n == 0) { return; } quint32 PIX_SIZE = 2; quint32 squaresX = drawRect.width() / PIX_SIZE; quint32 squaresY = drawRect.height() / PIX_SIZE; if (squaresX == 0 || squaresY == 0) { return; } quint32 dMapSize = squaresX* squaresY; quint32* densityMap = new quint32[dMapSize]; memset(densityMap, 0, dMapSize * 4); double xScale = calcRect.width() / (double) squaresX; double yScale = calcRect.height() / (double) squaresY; quint32 offsetX = calcRect.x(); quint32 offsetY = calcRect.y(); quint32 i; for (i = 0; i < n; i++) { quint32 x0 = x[i] - offsetX; quint32 y0 = y[i] - offsetY; quint32 l = len[i]; quint32 sx = quint32(x0 / xScale); quint32 sy = quint32(y0 / yScale); quint32 index = sx* squaresY + sy; densityMap[index]++; if (l > xScale || l > yScale) { quint32 lx = l; quint32 ly = l; while (lx || ly) { if (lx) { sx++; lx = lx > xScale ? quint32(lx - xScale) : 0; } if (ly) { sy++; ly = ly > yScale ? quint32(ly - yScale) : 0; } } index = sx * squaresY + sy; densityMap[index]++; } } float maxDensity = 0; for (i = 0; i < dMapSize; i++) { if (densityMap[i] < maxDensity) { continue; } maxDensity = densityMap[i]; if (maxDensity > 1000) { maxDensity = 1000; break; } } double k = 1.7; quint32 EXP = 0; while (maxDensity >= 1) { EXP++; maxDensity = maxDensity / k; } double m = 1; for (i = 0; i < EXP; i++) { m = m * k; } quint32 MAX = (quint32) m; quint32* colors = new quint32[MAX + 1]; for (i = 0; i < MAX; colors[i++] = 0xFFFFFF) ; quint32 color; double exp = 1; float dc = 255. / (EXP - 1); for (i = 1; i <= EXP; i++) { double endExp = exp* k; quint32 c = 255 - (quint32) (i* dc); color = (c << 16) + (c << 8) + c; for (quint32 j = (quint32) exp; j <= (quint32) endExp; j++) { colors[j] = color; } exp = endExp; } colors[MAX] = 0; for (quint32 xi = 0; xi < squaresX; xi++) { quint32 xo = xi* squaresY; for (quint32 yj = 0; yj < squaresY; yj++) { quint32 d = densityMap[xo + yj]; if (d == 0) { continue; } d > MAX && (d = MAX); color = colors[d]; p.fillRect(QRect(xi * PIX_SIZE, yj * PIX_SIZE, PIX_SIZE, PIX_SIZE), QBrush(color)); } } delete colors; delete[] densityMap; } */ static QVector prepareColors() { QVector colors(6*6*6); //00 = 0, 1 = 33, 2 = 66, 3 = 99, 4 = CC, 5 = FF int nLightColors = 0; for(int i=0; i< colors.count(); i++) { int color = i; int r = 0x33 * (color%6); int g = 0x33 * ((color/6)%6); int b = 0x33 * ((color/36)%6); if (r==0xFF || g==0xFF || b==0xFF) { colors[nLightColors] = QColor(r, g, b); nLightColors++; } } return colors; } QColor GraphUtils::proposeLightColorByKey(const QString& key) { //TODO: make thread safe! static QVector colors = prepareColors(); int hash =0; uint len = key.length(); for (int j=len-1; j>=0; j--) { hash+=key.at(j).toAscii(); } return colors.at((hash*hash)%colors.size()); } int GraphUtils::calculateChunk( qint64 start, qint64 end, qint64 len, const QPainter &p ){ QFontMetrics fm = p.fontMetrics(); int cw = fm.width('0'); //the width of the bigger number int N = cw * qMax(QString::number(start).length(), QString::number(end).length()) * 4 / 3; qint64 span = qMax(start, end) - qMin(start, end); int dN = 0; int chunk = 1; while (span > 2 * chunk) { dN = chunk > (1000 * 1000)? cw * 2 : (chunk > 1000 ? cw * 2 : 0); qint64 reqLen = qint64((double(span) / chunk) * (N - dN)); assert(reqLen > 0); if (reqLen < len) { break; } if (reqLen / 2 < len) { int cchunk = chunk*2; dN = cchunk > (1000 * 1000)? cw * 2 :cchunk > 1000 ? cw * 2 : 0; qint64 reqLen2 = qint64((double(span) / cchunk) * (N - dN)); if (reqLen2 < len) { chunk = cchunk; break; } } if (reqLen / 5 < len) { int cchunk = chunk*5; dN = cchunk > (1000 * 1000)? cw * 2 :cchunk > 1000 ? cw * 2 : 0; qint64 reqLen5 = qint64((double(span) / cchunk) * (N - dN)); if (reqLen5 < len) { chunk = cchunk; break; } } chunk *= 10; } return chunk; } }//namespace ugene-1.9.8/src/corelibs/U2Misc/src/TextEditorDialog.h0000644000175000017500000000255611651544333021175 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_TEXT_EDITOR_DIALOG_H_ #define _U2_TEXT_EDITOR_DIALOG_H_ #include #include class Ui_TextEditorDialog; namespace U2 { class U2MISC_EXPORT TextEditorDialog : public QDialog { Q_OBJECT public: TextEditorDialog(QWidget* parent, const QString& title, const QString& label, const QString& text, bool acceptOnEnter); ~TextEditorDialog(); QString getText(); protected: bool eventFilter(QObject *, QEvent *); private: Ui_TextEditorDialog* ui; }; } // namespace #endif ugene-1.9.8/src/corelibs/U2Misc/src/DialogUtils.cpp0000644000175000017500000001610111651544333020524 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "DialogUtils.h" #include #include #include #include #include #include #include #include #include #include namespace U2 { static bool isKDE() { static bool result = false; #if defined Q_WS_X11 static bool checked = false; if (!checked) { QString ds = qgetenv("DESKTOP_SESSION"); QString uid = qgetenv("KDE_SESSION_UID"); QString version = qgetenv("KDE_SESSION_VERSION"); result = (ds == "kde") || uid.toInt() > 0 || version.toInt() > 0; checked = true; } #endif return result; } static QString getAllFilesFilter() { if (isKDE()) { return "*"; } return "*.*"; } void DialogUtils::showProjectIsLockedWarning(QWidget* p) { QMessageBox::critical(p, tr("Error"), tr("Project is locked"), QMessageBox::Ok, QMessageBox::NoButton); } QString DialogUtils::prepareFileFilter(const QString& name, const QStringList& exts, bool any, const QStringList& extra) { QString line = name + " ("; foreach(QString ext, exts) { line+=" *."+ext; } foreach(QString ext, exts) { foreach(QString s, extra) { line+=" *."+ext+s; } } line+=" )"; if (any) { line += ";;" + tr("All files") + " ( "+getAllFilesFilter()+" )"; } return line; } static QStringList getExtra(DocumentFormat* df, const QStringList& originalExtra) { bool useExtra = !df->getFlags().testFlag(DocumentFormatFlag_NoPack); if (useExtra) { return originalExtra; } return QStringList(); } QString DialogUtils::prepareDocumentsFileFilter(const DocumentFormatId& fid, bool any, const QStringList& extra) { DocumentFormat* df = AppContext::getDocumentFormatRegistry()->getFormatById(fid); QStringList effectiveExtra = getExtra(df, extra); QString result = prepareFileFilter(df->getFormatName(), df->getSupportedDocumentFileExtensions(), any, effectiveExtra); return result; } QString DialogUtils::prepareDocumentsFileFilter(bool any, const QStringList& extra) { DocumentFormatRegistry* fr = AppContext::getDocumentFormatRegistry(); QList ids = fr->getRegisteredFormats(); QStringList result; foreach(DocumentFormatId id , ids) { DocumentFormat* df = fr->getFormatById(id); QStringList effectiveExtra = getExtra(df, extra); result << prepareFileFilter(df->getFormatName(), df->getSupportedDocumentFileExtensions(), false, effectiveExtra); } foreach(DocumentImporter* importer, fr->getImportSupport()->getImporters()) { QStringList importerExts = importer->getSupportedFileExtensions(); result << prepareFileFilter(importer->getImporterName(), importerExts, false, QStringList()); } result.sort(); if (any) { result.prepend(tr("All files") + " ( " + getAllFilesFilter() + " )"); } return result.join(";;"); } QString DialogUtils::prepareDocumentsFileFilter(const DocumentFormatConstraints& c, bool any) { QStringList result; QList ids = AppContext::getDocumentFormatRegistry()->getRegisteredFormats(); foreach(const DocumentFormatId& id, ids) { DocumentFormat* df = AppContext::getDocumentFormatRegistry()->getFormatById(id); if (df->checkConstraints(c)) { result.append(prepareDocumentsFileFilter(id, false)); } } result.sort(); if (any) { result.prepend(tr("All files") + " (" + getAllFilesFilter() + " )"); } return result.join(";;"); } QString DialogUtils::prepareDocumentsFileFilterByObjType(const GObjectType& t, bool any) { DocumentFormatConstraints c; c.supportedObjectTypes += t; return prepareDocumentsFileFilter(c, any); } QPair DialogUtils::selectFileForScreenShot(QWidget * parent) { QMap filters; filters[ "PNG - Portable Network Graphics (*.png)" ] = "png"; filters[ "JPG/JPEG format (*.jpg)" ] = "jpg"; filters[ "TIF - Tagged Image File format (*.tiff)" ] = "tiff"; LastOpenDirHelper lod("image"); QString selectedFilter; lod.url = QFileDialog::getSaveFileName(parent, tr("Export alignment image"), lod.dir, QStringList(filters.keys()).join(";;"), &selectedFilter); return QPair(lod.url, filters.value(selectedFilter)); } #define SETTINGS_ROOT QString("gui/") QString DialogUtils::getLastOpenFileDir(const QString& toolType, const QString& defaultVal) { QString key = SETTINGS_ROOT + (toolType.isEmpty() ? "" : toolType + "/") + "lastDir"; QString defDir = defaultVal; if (defDir.isEmpty() && toolType.isEmpty()) { defDir = QDir::searchPaths( PATH_PREFIX_DATA ).first() + "/samples"; } QString res = AppContext::getSettings()->getValue(key, defDir).toString(); return res; } void DialogUtils::setLastOpenFileDir(const QString& ld, const QString& toolType) { QString key = SETTINGS_ROOT + (toolType.isEmpty() ? "" : toolType + "/") + "lastDir"; AppContext::getSettings()->setValue(key, ld); } LastOpenDirHelper::LastOpenDirHelper(const QString& d, const QString& defaultVal) { domain = d; dir = DialogUtils::getLastOpenFileDir(domain, defaultVal); } LastOpenDirHelper::~LastOpenDirHelper() { saveURLDir2LastOpenDir(); } void LastOpenDirHelper::saveURLDir2LastOpenDir() { if (!url.isEmpty()) { QString newDir = QFileInfo(url).absoluteDir().absolutePath(); if (dir != newDir) { DialogUtils::setLastOpenFileDir(newDir, domain); } } } /******************************** * FileLineEdit ********************************/ void FileLineEdit::sl_onBrowse() { LastOpenDirHelper lod(type); QString name; if (multi) { QStringList lst = QFileDialog::getOpenFileNames(NULL, tr("Select file(s)"), lod.dir, FileFilter); name = lst.join(";"); if (!lst.isEmpty()) { lod.url = lst.first(); } } else { lod.url = name = QFileDialog::getSaveFileName(NULL, tr("Select a file"), lod.dir, FileFilter, 0, QFileDialog::DontConfirmOverwrite); } if (!name.isEmpty()) { setText(name); } setFocus(); } } // namespace ugene-1.9.8/src/corelibs/U2Misc/src/HBar.h0000644000175000017500000000260011651544333016564 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_HBAR_H_ #define _U2_HBAR_H_ #include #include namespace U2 { /////////////////////////////////////////////////////////////////////////////////////////// // Header widget toolbar class U2MISC_EXPORT HBar : public QToolBar { public: HBar(QWidget* w) : QToolBar(w){} protected: void paintEvent(QPaintEvent* pe) { Q_UNUSED(pe); //do not draw any special toolbar control -> make is merged with parent widget } }; } //namespace #endif ugene-1.9.8/src/corelibs/U2Misc/src/ScriptEditorDialog.h0000644000175000017500000000461111651544333021507 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_SCRIPT_EDITOR_DIALOG_H_ #define _U2_SCRIPT_EDITOR_DIALOG_H_ #include #include #include class Ui_ScriptEditorDialog; namespace U2 { class U2MISC_EXPORT ScriptEditorDialog : public QDialog { Q_OBJECT public: ScriptEditorDialog(QWidget* p, const QString& roHeaderText, const QString & text = QString()); ~ScriptEditorDialog(); void setScriptText(const QString& text); void setScriptPath(const QString& path); QString getScriptText() const; static QString getScriptsFileFilter(); private slots: void sl_checkSyntax(); void sl_openScript(); void sl_saveScript(); void sl_saveAsScript(); void sl_nameChanged(const QString&); void sl_scriptChanged(); void sl_cursorPositionChanged(); private: void updateState(); void save(const QString& url); Ui_ScriptEditorDialog* ui; }; class ScriptHighlighter : public QSyntaxHighlighter { Q_OBJECT public: ScriptHighlighter(QTextDocument *parent = 0); protected: void highlightBlock(const QString &text); private: struct HighlightingRule { QRegExp pattern; QTextCharFormat format; }; QVector highlightingRules; QRegExp commentStartExpression; QRegExp commentEndExpression; QTextCharFormat keywordFormat; QTextCharFormat classFormat; QTextCharFormat singleLineCommentFormat; QTextCharFormat multiLineCommentFormat; QTextCharFormat quotationFormat; QTextCharFormat functionFormat; }; } //namespace #endif ugene-1.9.8/src/corelibs/U2Misc/src/ScaleBar.cpp0000644000175000017500000000514111651544333017762 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "ScaleBar.h" #include namespace U2 { ScaleBar::ScaleBar(QWidget* parent) : QWidget(parent) { scaleBar = new QSlider(Qt::Vertical); scaleBar->setTracking(true); scaleBar->setRange(100,2000); scaleBar->setTickPosition(QSlider::TicksLeft); scaleBar->setTickInterval(100); connect(scaleBar,SIGNAL(valueChanged(int)),SIGNAL(valueChanged(int))); minusButton = new QToolButton(); //icon minusButton->setText(QString(tr("-"))); minusButton->setIcon(QIcon(":core/images/minus.png")); minusButton->setFixedSize(20,20); minusButton->setAutoRepeat(true); minusButton->setAutoRepeatInterval(20); plusButton = new QToolButton(); //icon plusButton->setText(QString(tr("+"))); plusButton->setIcon(QIcon(":core/images/plus.png")); plusButton->setAutoRepeat(true); plusButton->setAutoRepeatInterval(20); plusButton->setFixedSize(20,20); connect(minusButton,SIGNAL(clicked()),SLOT(sl_minusButtonClicked())); connect(plusButton,SIGNAL(clicked()),SLOT(sl_plusButtonClicked())); //layout QVBoxLayout *zoomLayout = new QVBoxLayout(); zoomLayout->addWidget(plusButton); zoomLayout->addWidget(scaleBar); zoomLayout->addWidget(minusButton); zoomLayout->setMargin(0); zoomLayout->setSpacing(0); setLayout(zoomLayout); setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Preferred); } void ScaleBar::sl_minusButtonClicked() { scaleBar->setValue(scaleBar->value()-scaleBar->pageStep()); } void ScaleBar::sl_plusButtonClicked() { scaleBar->setValue(scaleBar->value()+scaleBar->pageStep()); } }//namespace ugene-1.9.8/src/corelibs/U2Misc/src/ScaleBar.h0000644000175000017500000000301311651544333017423 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_SCALE_BAR_H_ #define _U2_SCALE_BAR_H_ #include #include #include namespace U2 { class U2MISC_EXPORT ScaleBar : public QWidget { Q_OBJECT public: ScaleBar(QWidget* parent = 0); QSlider* slider() const {return scaleBar;} int value() const {return scaleBar->value();} void setValue(int v) {scaleBar->setValue(v);} signals: void valueChanged(int); private slots: void sl_minusButtonClicked(); void sl_plusButtonClicked(); protected: QSlider* scaleBar; QToolButton* minusButton; QToolButton* plusButton; }; } // namespace #endif ugene-1.9.8/src/corelibs/U2Misc/src/HBar.cpp0000644000175000017500000000155011651544333017122 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "HBar.h" ugene-1.9.8/src/corelibs/U2Misc/src/AuthenticationDialog.cpp0000644000175000017500000000351511651544333022410 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include #include #include "AuthenticationDialog.h" namespace U2 { AuthDialog::AuthDialog( QWidget* parent ) : QDialog(parent) { ui = new Ui_AuthentificationDialog(); ui->setupUi(this); connect(ui->OKButton, SIGNAL(clicked()), SLOT(sl_onOkButtonClicked())); } QString AuthDialog::getUserName() const { return ui->nameEdit->text(); } QString AuthDialog::getPasswd() const { return ui->passEdit->text(); } bool AuthDialog::rememberAuthData() const { return ui->rememberBox->isChecked(); } void AuthDialog::sl_onOkButtonClicked() { if (ui->nameEdit->text().isEmpty() ) { QMessageBox::critical( this, tr( "Error!" ), tr("User name is not set.") ); return; } else if (ui->passEdit->text().isEmpty()) { QMessageBox::critical( this, tr("Error!"), tr("Password is not set.") ); return; } else { accept(); } } AuthDialog::~AuthDialog() { delete ui; } } // namespace ugene-1.9.8/src/corelibs/U2Misc/src/GScrollBar.h0000644000175000017500000000254011651544333017745 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_GSCROLL_BAR_H_ #define _U2_GSCROLL_BAR_H_ #include #include namespace U2 { class U2MISC_EXPORT GScrollBar : public QScrollBar { public: GScrollBar(Qt::Orientation o, QWidget *p=0) : QScrollBar(o, p){} void setupRepeatAction(SliderAction action, int thresholdTime=100, int repeatTime=50) { QScrollBar::setRepeatAction(action, thresholdTime, repeatTime); } SliderAction getRepeatAction() const {return repeatAction();} }; } //namespace #endif ugene-1.9.8/src/corelibs/U2Misc/src/GScrollBar.cpp0000644000175000017500000000155611651544333020306 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "GScrollBar.h" ugene-1.9.8/src/corelibs/U2Misc/src/GraphUtils.h0000644000175000017500000000564111651544333020042 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #if !defined(GRAPHUTILS_H) #define GRAPHUTILS_H #include #include #include namespace U2 { #define PI 3.1415926535897932384626433832795 class U2MISC_EXPORT GraphUtils { public: enum Direction { LTR, RTL, BTT, TTB }; enum TextPos { LEFT, RIGHT }; struct RulerConfig { RulerConfig() { drawArrow = false; arrowLen = 5; arrowWidth = 2; notchSize = 2; textOffset = 3; drawNumbers = true; drawNotches = true; drawBorderNotches = true; singleSideNotches = false; drawAxis = true; direction = LTR; textPosition = RIGHT; extraAxisLenBefore =0; extraAxisLenAfter =0; textBorderStart = 2; textBorderEnd = 2; predefinedChunk = 0; correction = 0; } bool drawArrow; int arrowLen; int arrowWidth; int notchSize; int textOffset; int extraAxisLenBefore; int extraAxisLenAfter; int textBorderStart; //offset in pixels for the first text label at the start pos int textBorderEnd; //offset in pixels for the last text label at the end pos int predefinedChunk; int correction; bool drawNumbers; bool drawNotches; bool drawBorderNotches; bool singleSideNotches; bool drawAxis; Direction direction; TextPos textPosition; }; static void drawRuler(QPainter& p, const QPoint& pos, qint64 len, qint64 start, qint64 end, const QFont& f, const RulerConfig& config); static int calculateChunk(qint64 start, qint64 end, qint64 len, const QPainter &p); static int findChunk(qint64 len, qint64 span, int N); //static void drawDensityPlot(QPainter& p, QRect& drawRect, QRect& calcRect, quint32 n, quint32* x, quint32 *y, quint32* len); static QColor proposeLightColorByKey(const QString& key); }; } //namespace #endif ugene-1.9.8/src/corelibs/U2Misc/transl/0000755000175000017500000000000011651544333016315 5ustar ilyailyaugene-1.9.8/src/corelibs/U2Misc/transl/russian.ts0000644000175000017500000002470011651544333020354 0ustar ilyailya AuthentificationDialog Authentification Аутентификация Enter name: Введите имя: Enter password: Введите пароль: OK Cancel Отмена Remember me Запомнить меня ScriptEditorDialog Script editor Редактор скрипта Used script Используемый скрипт ... ... Script text Текст скрипта Check syntax Проверить синтаксис Save Сохранить Clear Очистить Save as.. Сохранить как... Done Готово Cancel Отмена TextEditorDialog Value editor Value: OK Готово Cancel Отмена U2::AuthDialog Error! Ошибка! User name is not set. Имя пользователя не задано. Password is not set. Пароль не установлен. U2::DialogUtils Error Ошибка Project is locked Проект заблокирован All files Все файлы copy копия Renamed %1 to %2 Старый файл %1 переименован в %2 Failed to rename %1 to %2 Не удалось переименовать %1 в %2 U2::FileLineEdit Select file(s) Выберите файл(ы) Select a file Выберите файл U2::PositionSelector Go! Перейти! Position Позиция Cancel Отмена U2::RangeSelector Min Мин Max Макс Range: Регион: - Ok Перейти Cancel Отменить U2::ScaleBar - + U2::ScriptEditorDialog File is too large %1 Файл "%1" слишком большой Select script to open Выберите скрипт Script is empty! Скрипт пуст! Save script to file Сохранить скрипт в файл Script files Файлы скрипта Script syntax check failed! Line: %1, error: %2 Проверка синтаксиса скрипта не удалась! В строке: %1 обнаружена ошибка: %2 Check result Результат проверки Syntax is OK! Проверка синтаксиса удачна! ugene-1.9.8/src/corelibs/U2Misc/transl/czech.ts0000644000175000017500000002443311651544333017767 0ustar ilyailya AuthentificationDialog Authentification Enter name: Enter password: OK Cancel Cancel Remember me ScriptEditorDialog Script editor Skriptovací editor Used script Použitý skript ... Script text Text skriptu Check syntax Ověřit skladbu Save Uložit Clear Smazat Save as.. Uložit jako... Done Hotovo Cancel Zrušit TextEditorDialog Value editor Editor hodnot Value: Hodnota: OK Cancel Zrušit U2::AuthDialog Error! Error! User name is not set. Password is not set. U2::DialogUtils project_is_locked_title Error project_is_locked_message Project is locked All files Všechny soubory Error Chyba Project is locked Projekt je uzamknut U2::FileLineEdit Select file(s) Select a file U2::PositionSelector go_text Go! Position Poloha Go! Jít! Cancel Zrušit U2::RangeSelector min Min max Max range_label Range: - - Ok Min Max Range: Rozsah: Cancel Zrušit U2::ScaleBar - - + U2::ScriptEditorDialog File is too large %1 Soubor je příliš velký %1 Select script to open Vybrat skript k otevření Script is empty! Skript je prázdný! Save script to file Uložit skript do souboru Script files Soubory se skripty Script syntax check failed! Line: %1, error: %2 Nepodařilo se ověřit skladbu skriptu! Řádek: %1, chyba: %2 Check result Ověřit výsledek Syntax is OK! Skladba je v pořádku! ugene-1.9.8/src/corelibs/U2Misc/transl/english.ts0000644000175000017500000002212011651544333020313 0ustar ilyailya AuthentificationDialog Authentification Enter name: Enter password: OK Cancel Remember me ScriptEditorDialog Script editor Used script ... Script text Check syntax Save Clear Save as.. Done Cancel TextEditorDialog Value editor Value: OK Cancel U2::AuthDialog Error! User name is not set. Password is not set. U2::DialogUtils Error Project is locked All files U2::FileLineEdit Select file(s) Select a file U2::PositionSelector Go! Position Cancel U2::RangeSelector Ok Min Max Range: - Cancel U2::ScaleBar - + U2::ScriptEditorDialog File is too large %1 Select script to open Script is empty! Save script to file Script files Script syntax check failed! Line: %1, error: %2 Check result Syntax is OK! ugene-1.9.8/src/corelibs/U2Lang/0000755000175000017500000000000011651544333015000 5ustar ilyailyaugene-1.9.8/src/corelibs/U2Lang/U2Lang.pro0000644000175000017500000000576011651544333016622 0ustar ilyailyainclude (U2Lang.pri) # Input HEADERS += src/library/BaseActorCategories.h \ src/library/BaseAttributes.h \ src/library/BasePorts.h \ src/library/BaseSlots.h \ src/library/BaseTypes.h \ src/library/LocalDomain.h \ src/library/ScriptLibrary.h \ src/model/ActorModel.h \ src/model/ActorPrototypeRegistry.h \ src/model/Attribute.h \ src/model/Configuration.h \ src/model/ConfigurationEditor.h \ src/model/ConfigurationValidator.h \ src/model/Datatype.h \ src/model/DatatypeConversion.h \ src/model/Descriptor.h \ src/model/IntegralBus.h \ src/model/IntegralBusModel.h \ src/model/IntegralBusType.h \ src/model/Peer.h \ src/model/Port.h \ src/model/QDConstraint.h \ src/model/QDScheme.h \ src/model/QueryDesignerRegistry.h \ src/model/Schema.h \ src/model/WorkflowEnv.h \ src/model/WorkflowManager.h \ src/model/WorkflowTransport.h \ src/model/ExternalToolCfg.h \ src/support/CoreLibConstants.h \ src/support/HRSchemaSerializer.h \ src/support/MapDatatypeEditor.h \ src/support/RunSchemaForTask.h \ src/support/SchemaSerializer.h \ src/support/WorkflowEnvImpl.h \ src/support/WorkflowIOTasks.h \ src/support/WorkflowRunTask.h \ src/support/WorkflowSettings.h \ src/support/WorkflowUtils.h SOURCES += src/library/BaseActorCategories.cpp \ src/library/BaseAttributes.cpp \ src/library/BasePorts.cpp \ src/library/BaseSlots.cpp \ src/library/BaseTypes.cpp \ src/library/LocalDomain.cpp \ src/library/ScriptLibrary.cpp \ src/model/ActorModel.cpp \ src/model/ActorPrototypeRegistry.cpp \ src/model/Attribute.cpp \ src/model/Configuration.cpp \ src/model/Datatype.cpp \ src/model/Descriptor.cpp \ src/model/IntegralBus.cpp \ src/model/IntegralBusModel.cpp \ src/model/IntegralBusType.cpp \ src/model/Port.cpp \ src/model/QDConstraint.cpp \ src/model/QDScheme.cpp \ src/model/QueryDesignerRegistry.cpp \ src/model/Schema.cpp \ src/model/WorkflowEnv.cpp \ src/model/WorkflowTransport.cpp \ src/support/CoreLibConstants.cpp \ src/support/HRSchemaSerializer.cpp \ src/support/MapDatatypeEditor.cpp \ src/support/RunSchemaForTask.cpp \ src/support/SchemaSerializer.cpp \ src/support/WorkflowEnvImpl.cpp \ src/support/WorkflowIOTasks.cpp \ src/support/WorkflowRunTask.cpp \ src/support/WorkflowSettings.cpp \ src/support/WorkflowUtils.cpp TRANSLATIONS += transl/czech.ts transl/english.ts transl/russian.ts ugene-1.9.8/src/corelibs/U2Lang/U2Lang.pri0000644000175000017500000000105711651544333016607 0ustar ilyailya# include (U2Lang.pri) MODULE_ID=U2Lang include( ../../ugene_lib_common.pri ) UGENE_RELATIVE_DESTDIR = '' QT += xml DEFINES+= QT_FATAL_ASSERT BUILDING_U2LANG_DLL LIBS += -L../../_release -lU2Core !debug_and_release|build_pass { CONFIG(debug, debug|release) { DESTDIR=../../_debug LIBS += -L../../_debug -lU2Cored LIBS -= -L../../_release -lU2Core } CONFIG(release, debug|release) { DESTDIR=../../_release } } unix { target.path = $$UGENE_INSTALL_DIR/$$UGENE_RELATIVE_DESTDIR INSTALLS += target } ugene-1.9.8/src/corelibs/U2Lang/src/0000755000175000017500000000000011651544333015567 5ustar ilyailyaugene-1.9.8/src/corelibs/U2Lang/src/library/0000755000175000017500000000000011651544333017233 5ustar ilyailyaugene-1.9.8/src/corelibs/U2Lang/src/library/BaseAttributes.h0000644000175000017500000000337511651544333022335 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef __U2_WORKFLOW_BASE_ATTRIBUTES_H_ #define __U2_WORKFLOW_BASE_ATTRIBUTES_H_ #include namespace U2 { namespace Workflow { class U2LANG_EXPORT BaseAttributes : public QObject { Q_OBJECT public: static const Descriptor URL_IN_ATTRIBUTE(); static const Descriptor URL_OUT_ATTRIBUTE(); static const Descriptor URL_LOCATION_ATTRIBUTE(); static const Descriptor DOCUMENT_FORMAT_ATTRIBUTE(); static const Descriptor ACCUMULATE_OBJS_ATTRIBUTE(); static const Descriptor READ_BY_LINES_ATTRIBUTE(); static const Descriptor FILE_MODE_ATTRIBUTE(); static const Descriptor STRAND_ATTRIBUTE(); static const QString STRAND_BOTH(); static const QString STRAND_DIRECT(); static const QString STRAND_COMPLEMENTARY(); static const QVariantMap STRAND_ATTRIBUTE_VALUES_MAP(); }; // BaseAttributes } // Workflow } // U2 #endif // __U2_WORKFLOW_BASE_ATTRIBUTES_H_ ugene-1.9.8/src/corelibs/U2Lang/src/library/BaseSlots.cpp0000644000175000017500000000411211651544333021634 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "BaseSlots.h" static const QString SEQ_SLOT_ID("sequence"); static const QString MA_SLOT_ID("msa"); static const QString FEATURE_TABLE_SLOT_ID("annotations"); static const QString TEXT_SLOT_ID("text"); static const QString URL_SLOT_ID("url"); static const QString FASTA_HEADER_SLOT_ID("fasta-header"); namespace U2 { namespace Workflow { const Descriptor BaseSlots::DNA_SEQUENCE_SLOT() { return Descriptor(SEQ_SLOT_ID, tr("Sequence"), tr("A biological sequence")); } const Descriptor BaseSlots::MULTIPLE_ALIGNMENT_SLOT() { return Descriptor(MA_SLOT_ID, tr("MSA"), tr("A multiple sequence alignment")); } const Descriptor BaseSlots::ANNOTATION_TABLE_SLOT() { return Descriptor(FEATURE_TABLE_SLOT_ID, tr("Set of annotations"), tr("A set of annotated regions")); } const Descriptor BaseSlots::TEXT_SLOT() { return Descriptor(TEXT_SLOT_ID, tr("Plain text"), tr("Plain text reading or splitting to strings.")); } const Descriptor BaseSlots::URL_SLOT() { return Descriptor(URL_SLOT_ID, tr("Source URL"), tr("Location of a corresponding input file.")); } const Descriptor BaseSlots::FASTA_HEADER_SLOT() { return Descriptor(FASTA_HEADER_SLOT_ID, tr("FASTA header"), tr("A header line for the FASTA record.")); } } // Workflow } // U2 ugene-1.9.8/src/corelibs/U2Lang/src/library/BaseAttributes.cpp0000644000175000017500000000761711651544333022673 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "BaseAttributes.h" static const QString URL_LOCATION_ATTR_ID("url_location"); static const QString URL_OUT_ATTR_ID("url-out"); static const QString URL_IN_ATTR_ID("url-in"); static const QString DOCUMENT_FORMAT_ATTR_ID("document-format"); static const QString APPEND_ATTR_ID("accumulate"); static const QString READ_BY_LINES_ATTR_ID("read-by-lines"); static const QString FILE_MODE_ATTR_ID("write-mode"); static const QString STRAND_ATTR_ID("strand"); namespace U2 { namespace Workflow { const Descriptor BaseAttributes::URL_IN_ATTRIBUTE() { return Descriptor(URL_IN_ATTR_ID, tr("Input files"), tr("Semicolon-separated list of paths to the input files.")); } const Descriptor BaseAttributes::URL_OUT_ATTRIBUTE() { return Descriptor(URL_OUT_ATTR_ID, tr("Output file"), tr("Location of output data file. If this attribute is set," " slot \"Location\" in port will not be used")); } const Descriptor BaseAttributes::URL_LOCATION_ATTRIBUTE() { return Descriptor(URL_LOCATION_ATTR_ID, tr("Located on"), tr("Machine file(s) are located on")); } const Descriptor BaseAttributes::DOCUMENT_FORMAT_ATTRIBUTE() { return Descriptor(DOCUMENT_FORMAT_ATTR_ID, tr("Document format"), tr("Document format of output file")); } const Descriptor BaseAttributes::ACCUMULATE_OBJS_ATTRIBUTE() { return Descriptor(APPEND_ATTR_ID, tr("Accumulate objects"), tr("Accumulate all incoming data in one file or create separate files for each input." "In the latter case, an incremental numerical suffix is added to the file name.")); } const Descriptor BaseAttributes::READ_BY_LINES_ATTRIBUTE() { return Descriptor(READ_BY_LINES_ATTR_ID, tr("Read by lines"), tr("Read input file by lines")); } const Descriptor BaseAttributes::FILE_MODE_ATTRIBUTE() { return Descriptor(FILE_MODE_ATTR_ID, tr("Existing file"), tr("If a target file already exists, you can specify" " how it should be handled: either overwritten, renamed" " or appended (if supported by file format). If Rename option is chosen existing file will be renamed.")); } const Descriptor BaseAttributes::STRAND_ATTRIBUTE() { return Descriptor(STRAND_ATTR_ID, tr("Search in"), tr("Which strands should be searched: direct, complement or both.")); } const QString BaseAttributes::STRAND_BOTH() { return "both"; } const QString BaseAttributes::STRAND_DIRECT() { return "direct"; } const QString BaseAttributes::STRAND_COMPLEMENTARY() { return "complementary"; } const QVariantMap BaseAttributes::STRAND_ATTRIBUTE_VALUES_MAP() { QVariantMap strandMap; // The constant strings are used to generate the translations properly. // When a string is used as an argument of the strandMap, nothing is generated. const QString bothStrands = tr("both strands"); const QString directStrand = tr("direct strand"); const QString complementaryStrand = tr("complementary strand"); strandMap[bothStrands] = STRAND_BOTH(); strandMap[directStrand] = STRAND_DIRECT(); strandMap[complementaryStrand] = STRAND_COMPLEMENTARY(); return strandMap; } } // Workflow } // U2 ugene-1.9.8/src/corelibs/U2Lang/src/library/BaseSlots.h0000644000175000017500000000263411651544333021310 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef __U2_WORKFLOW_BASE_SLOTS_H_ #define __U2_WORKFLOW_BASE_SLOTS_H_ #include namespace U2 { namespace Workflow { class U2LANG_EXPORT BaseSlots : public QObject { Q_OBJECT public: static const Descriptor DNA_SEQUENCE_SLOT(); static const Descriptor MULTIPLE_ALIGNMENT_SLOT(); static const Descriptor ANNOTATION_TABLE_SLOT(); static const Descriptor TEXT_SLOT(); static const Descriptor URL_SLOT(); static const Descriptor FASTA_HEADER_SLOT(); }; // BaseSlots } // Workflow } // U2 #endif // __U2_WORKFLOW_BASE_SLOTS_H_ ugene-1.9.8/src/corelibs/U2Lang/src/library/ScriptLibrary.cpp0000644000175000017500000006270111651544333022536 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "ScriptLibrary.h" #include namespace U2 { void WorkflowScriptLibrary::initEngine(QScriptEngine * engine) { QScriptValue foo = engine->globalObject(); foo.setProperty("subsequence",engine->newFunction(getSubsequence)); foo.setProperty("complement", engine->newFunction(complement)); foo.setProperty("size", engine->newFunction(sequenceSize)); foo.setProperty("translate", engine->newFunction(translate)); foo.setProperty("charAt", engine->newFunction(charAt)); foo.setProperty("alphabetType", engine->newFunction(alphabetType)); foo.setProperty("getName", engine->newFunction(sequenceName)); foo.setProperty("printToLog",engine->newFunction(debugOut)); foo.setProperty("isAmino", engine->newFunction(isAmino)); foo.setProperty("getMinimumQuality", engine->newFunction(getMinimumQuality)); foo.setProperty("hasQuality",engine->newFunction(hasQuality)); foo.setProperty("sequenceFromText", engine->newFunction(sequenceFromText)); foo.setProperty("createAlignment", engine->newFunction(createAlignment)); foo.setProperty("sequenceFromAlignment",engine->newFunction(getSequenceFromAlignment)); foo.setProperty("addToAlignment",engine->newFunction(addToAlignment)); foo.setProperty("findInAlignment",engine->newFunction(findInAlignment)); foo.setProperty("removeFromAlignment",engine->newFunction(removeFromAlignment)); foo.setProperty("rowNum",engine->newFunction(rowNum)); foo.setProperty("columnNum",engine->newFunction(columnNum)); foo.setProperty("alignmentAlphabetType",engine->newFunction(alignmentAlphabetType)); foo.setProperty("annotatedRegions", engine->newFunction(getAnnotationRegion)); foo.setProperty("addQualifier", engine->newFunction(addQualifier)); foo.setProperty("getLocation", engine->newFunction(getLocation)); foo.setProperty("filterByQualifier", engine->newFunction(filterByQualifier)); } QScriptValue WorkflowScriptLibrary::getSubsequence(QScriptContext *ctx, QScriptEngine *engine) { if(ctx->argumentCount() != 3) { return ctx->throwError(QObject::tr("Incorrect number of arguments")); } else { int beg, end; QScriptValue calee = ctx->callee(); DNASequence dna = ctx->argument(0).toVariant().value(); try { beg = ctx->argument(1).toInt32(); end = ctx->argument(2).toInt32(); } catch(...) { return ctx->throwError(QObject::tr("Incorrect arguments")); } if(dna.seq.isEmpty()) { return ctx->throwError(QObject::tr("Empty or invalid sequence")); } DNASequence subsequence(dna.seq.mid(beg, end - beg),dna.alphabet); calee.setProperty("res", engine->newVariant(QVariant::fromValue(subsequence))); return calee.property("res"); } } QScriptValue WorkflowScriptLibrary::concatSequence(QScriptContext *ctx, QScriptEngine *engine) { if(ctx->argumentCount() < 1) { return ctx->throwError(QObject::tr("Incorrect number of arguments")); } QByteArray result; DNAAlphabet *alph = AppContext::getDNAAlphabetRegistry()->findById(BaseDNAAlphabetIds::NUCL_DNA_DEFAULT()); for(int i = 0; i < ctx->argumentCount();i++) { DNASequence dna = ctx->argument(0).toVariant().value(); if(dna.seq.isEmpty()) { return ctx->throwError(QObject::tr("Empty or invalid sequence")); } if(dna.alphabet->isAmino()) { alph = AppContext::getDNAAlphabetRegistry()->findById(BaseDNAAlphabetIds::AMINO_DEFAULT()); } result.append(dna.seq); } DNASequence concatenation("joined sequence", result, alph); QScriptValue calee = ctx->callee(); calee.setProperty("res", engine->newVariant(QVariant::fromValue(concatenation))); return calee.property("res"); } QScriptValue WorkflowScriptLibrary::complement(QScriptContext *ctx, QScriptEngine *engine) { if(ctx->argumentCount() != 1) { return ctx->throwError(QObject::tr("Incorrect number of arguments")); } DNASequence dna = ctx->argument(0).toVariant().value(); if(dna.seq.isEmpty()) { return ctx->throwError(QObject::tr("Empty or invalid sequence")); } if( !dna.alphabet->isNucleic() ) { return ctx->throwError(QObject::tr("Alphabet must be nucleotide")); } DNATranslation *complTT = AppContext::getDNATranslationRegistry()->lookupComplementTranslation(dna.alphabet); complTT->translate(dna.seq.data(),dna.seq.size(), dna.seq.data(), dna.seq.size()); QScriptValue calee = ctx->callee(); calee.setProperty("res", engine->newVariant(QVariant::fromValue(dna))); return calee.property("res"); } QScriptValue WorkflowScriptLibrary::sequenceSize(QScriptContext *ctx, QScriptEngine *engine) { if(ctx->argumentCount() != 1) { return ctx->throwError(QObject::tr("Incorrect number of arguments")); } DNASequence seq = ctx->argument(0).toVariant().value(); if(seq.seq.isEmpty()) { return ctx->throwError(QObject::tr("Empty or invalid sequence")); } int size = seq.length(); QScriptValue calee = ctx->callee(); calee.setProperty("res", engine->newVariant(size)); return calee.property("res"); } QScriptValue WorkflowScriptLibrary::translate(QScriptContext *ctx, QScriptEngine *engine) { if(ctx->argumentCount() < 1 && ctx->argumentCount() > 2) { return ctx->throwError(QObject::tr("Incorrect number of arguments")); } DNASequence seq = ctx->argument(0).toVariant().value(); if(seq.seq.isEmpty()) { return ctx->throwError(QObject::tr("Empty or invalid sequence")); } bool aminoSeq = seq.alphabet->isAmino(); if( aminoSeq ) { return ctx->throwError(QObject::tr("Alphabet must be nucleotide")); } int offset = 0; if(ctx->argumentCount() == 2) { offset = ctx->argument(1).toInt32(); if(offset < 0 && offset > 2) { return ctx->throwError(QObject::tr("Offset must be from interval [0,2]")); } } DNATranslationType dnaTranslType = (seq.alphabet->getType() == DNAAlphabet_NUCL) ? DNATranslationType_NUCL_2_AMINO : DNATranslationType_RAW_2_AMINO; QList aminoTTs = AppContext::getDNATranslationRegistry()->lookupTranslation( seq.alphabet, dnaTranslType ); if( aminoTTs.isEmpty() ) { return ctx->throwError(QObject::tr("Translation table is empty")); } DNATranslation *aminoT = aminoTTs.first(); aminoT->translate(seq.seq.data() + offset, seq.length() - offset, seq.seq.data(), seq.length()); seq.seq.resize(seq.length()/3); QScriptValue calee = ctx->callee(); calee.setProperty("res", engine->newVariant(QVariant::fromValue(seq))); return calee.property("res"); } QScriptValue WorkflowScriptLibrary::charAt(QScriptContext *ctx, QScriptEngine *engine) { if(ctx->argumentCount()!= 2) { return ctx->throwError(QObject::tr("Incorrect number of arguments")); } DNASequence seq = ctx->argument(0).toVariant().value(); if(seq.seq.isEmpty()) { return ctx->throwError(QObject::tr("Empty or invalid sequence")); } if(!ctx->argument(1).isNumber()) { return ctx->throwError(QObject::tr("Second argument must be a number")); } int position = ctx->argument(1).toInt32(); if(position > seq.length() || position < 0) { return ctx->throwError(QObject::tr("Position is out of range")); } QString c(seq.seq.at(position)); QScriptValue calee = ctx->callee(); calee.setProperty("res", engine->newVariant(c)); return calee.property("res"); } QScriptValue WorkflowScriptLibrary::sequenceName(QScriptContext *ctx, QScriptEngine *) { if(ctx->argumentCount() != 1) { return ctx->throwError(QObject::tr("Incorrect number of arguments")); } DNASequence seq = ctx->argument(0).toVariant().value(); if(seq.seq.isEmpty()) { return ctx->throwError(QObject::tr("Empty or invalid sequence")); } QString name = seq.getName(); QScriptValue calee = ctx->callee(); calee.setProperty("res", name); return calee.property("res"); } QScriptValue WorkflowScriptLibrary::alphabetType(QScriptContext *ctx, QScriptEngine *engine) { if(ctx->argumentCount() != 1) { return ctx->throwError(QObject::tr("Incorrect number of arguments")); } DNASequence seq = ctx->argument(0).toVariant().value(); if(seq.seq.isEmpty()) { return ctx->throwError(QObject::tr("Empty or invalid sequence")); } QString alph = seq.alphabet->getName(); QScriptValue calee = ctx->callee(); calee.setProperty("res", engine->newVariant(alph)); return calee.property("res"); } QScriptValue WorkflowScriptLibrary::sequenceFromText(QScriptContext *ctx, QScriptEngine *engine) { if(ctx->argumentCount() != 1) { return ctx->throwError(QObject::tr("Incorrect number of arguments")); } QString text = ctx->argument(0).toString(); //QString name = ctx->argument(1).toString(); DNASequence seq(text.toAscii()); DNAAlphabetRegistry* r = AppContext::getDNAAlphabetRegistry(); seq.alphabet = r->findAlphabet(seq.seq); if(seq.alphabet->getId() == BaseDNAAlphabetIds::RAW()) { seq.seq = QByteArray(); } QScriptValue calee = ctx->callee(); calee.setProperty("res", engine->newVariant(QVariant::fromValue(seq))); return calee.property("res"); } QScriptValue WorkflowScriptLibrary::isAmino(QScriptContext *ctx, QScriptEngine *) { if(ctx->argumentCount() != 1) { return ctx->throwError(QObject::tr("Incorrect number of arguments")); } DNASequence seq = ctx->argument(0).toVariant().value(); if(seq.seq.isEmpty()) { return ctx->throwError(QObject::tr("Empty or invalid sequence")); } bool isAmino = seq.alphabet->isAmino(); QScriptValue calee = ctx->callee(); calee.setProperty("res", isAmino); return calee.property("res"); } QScriptValue WorkflowScriptLibrary::getMinimumQuality(QScriptContext *ctx, QScriptEngine *) { if(ctx->argumentCount() != 1) { return ctx->throwError(QObject::tr("Incorrect number of arguments")); } DNASequence seq = ctx->argument(0).toVariant().value(); if(seq.seq.isEmpty()) { return ctx->throwError(QObject::tr("Empty or invalid sequence")); } QByteArray codes = seq.quality.qualCodes; int minQual = 100; for(int i = 0; i < codes.size();i++) { if(minQual > codes[i]) { minQual = codes[i]; } } QScriptValue calee = ctx->callee(); calee.setProperty("res", minQual); return calee.property("res"); } QScriptValue WorkflowScriptLibrary::hasQuality(QScriptContext *ctx, QScriptEngine *) { if(ctx->argumentCount() != 1) { return ctx->throwError(QObject::tr("Incorrect number of arguments")); } DNASequence seq = ctx->argument(0).toVariant().value(); if(seq.seq.isEmpty()) { return ctx->throwError(QObject::tr("Empty or invalid sequence")); } QByteArray codes = seq.quality.qualCodes; bool isHasQuality = !codes.isEmpty(); QScriptValue calee = ctx->callee(); calee.setProperty("res", isHasQuality); return calee.property("res"); } QScriptValue WorkflowScriptLibrary::getSequenceFromAlignment(QScriptContext *ctx, QScriptEngine *engine) { if(ctx->argumentCount() != 2 && ctx->argumentCount() != 4) { return ctx->throwError(QObject::tr("Incorrect number of arguments")); } MAlignment align = ctx->argument(0).toVariant().value(); if(align.isEmpty()) { return ctx->throwError(QObject::tr("Invalid alignment")); } if(!ctx->argument(1).isNumber()) { return ctx->throwError(QObject::tr("Second argument must be a number")); } int row = ctx->argument(1).toVariant().toInt(); if(row < 0 || row > align.getNumRows()) { return ctx->throwError(QObject::tr("Row is out of range")); } MAlignmentRow aRow = align.getRow(row); aRow.simplify(); QByteArray arr = aRow.toByteArray(aRow.getCoreLength()); if(ctx->argumentCount() == 4) { int beg = ctx->argument(1).toInt32(); int len = ctx->argument(2).toInt32(); if(beg <= 0 || beg > arr.length()) { return ctx->throwError(QObject::tr("Offset is out of range")); } if(len <= 0 || (beg + len) > arr.length()) { return ctx->throwError(QObject::tr("Length is out of range")); } arr.mid(beg,len); } DNASequence seq(aRow.getName(),arr,align.getAlphabet()); QScriptValue calee = ctx->callee(); calee.setProperty("res", engine->newVariant(QVariant::fromValue(seq))); return calee.property("res"); } QScriptValue WorkflowScriptLibrary::findInAlignment(QScriptContext *ctx, QScriptEngine *engine) { if(ctx->argumentCount() != 2) { return ctx->throwError(QObject::tr("Incorrect number of arguments")); } QString name; DNASequence seq; MAlignment aln = ctx->argument(0).toVariant().value(); if(aln.isEmpty()) { return ctx->throwError(QObject::tr("Invalid alignment")); } int row = 0; QScriptValue val = ctx->argument(1); if(val.isString()) { name = val.toString(); row = aln.getRowNames().indexOf(name); } else { seq = val.toVariant().value(); if(seq.seq.isEmpty()) { return ctx->throwError(QObject::tr("Empty or invalid sequence")); } foreach(const DNASequence& alnSeq, MSAUtils::ma2seq(aln,true)) { if(alnSeq.seq == seq.seq) { break; } row++; } if(row == aln.getNumRows()) { row = -1; } } QScriptValue calee = ctx->callee(); calee.setProperty("res", engine->newVariant(row)); return calee.property("res"); } QScriptValue WorkflowScriptLibrary::createAlignment(QScriptContext *ctx, QScriptEngine *engine) { if(ctx->argumentCount() < 1) { return ctx->throwError(QObject::tr("Incorrect number of arguments")); } MAlignment align; DNASequence seq = ctx->argument(0).toVariant().value(); if(seq.seq.isEmpty()) { return ctx->throwError(QObject::tr("Empty or invalid sequence")); } align.setAlphabet(seq.alphabet); align.addRow( MAlignmentRow(seq.getName(),seq.seq) ); for(int i = 1; i < ctx->argumentCount(); i++) { DNASequence seq = ctx->argument(i).toVariant().value(); if(seq.seq.isEmpty()) { return ctx->throwError(QObject::tr("Empty or invalid sequence")); } if(seq.alphabet != align.getAlphabet()) { return ctx->throwError(QObject::tr("Alphabets of each sequence must be the same")); } align.addRow(MAlignmentRow(seq.getName(),seq.seq)); } QScriptValue calee = ctx->callee(); calee.setProperty("res", engine->newVariant(QVariant::fromValue(align))); return calee.property("res"); } QScriptValue WorkflowScriptLibrary::addToAlignment(QScriptContext *ctx, QScriptEngine *engine) { if(ctx->argumentCount() < 2 && ctx->argumentCount() >3) { return ctx->throwError(QObject::tr("Incorrect number of arguments")); } MAlignment align = ctx->argument(0).toVariant().value(); DNASequence seq = ctx->argument(1).toVariant().value(); if(seq.seq.isEmpty()) { return ctx->throwError(QObject::tr("Empty or invalid sequence")); } if(align.isEmpty()) { //return ctx->throwError(QObject::tr("Invalid alignment")); //align = new MAlignment("alignment"); align.setAlphabet(seq.alphabet); } if(seq.alphabet != align.getAlphabet()) { return ctx->throwError(QObject::tr("Alphabets don't match")); } int row = -1; if(ctx->argumentCount() == 3) { if(!ctx->argument(2).isNumber()) { return ctx->throwError(QObject::tr("Third argument must be a number")); } row = ctx->argument(2).toInt32(); if(row > align.getLength()) { row = -1; } } align.addRow(MAlignmentRow(seq.getName(),seq.seq),row); QScriptValue calee = ctx->callee(); calee.setProperty("res", engine->newVariant(QVariant::fromValue(align))); return calee.property("res"); } QScriptValue WorkflowScriptLibrary::removeFromAlignment(QScriptContext *ctx, QScriptEngine *engine) { if(ctx->argumentCount() != 2) { return ctx->throwError(QObject::tr("Incorrect number of arguments")); } MAlignment aln = ctx->argument(0).toVariant().value(); if(aln.isEmpty()) { return ctx->throwError(QObject::tr("Invalid alignment")); } if(!ctx->argument(1).isNumber()) { return ctx->throwError(QObject::tr("Second argument must be a number")); } int row = ctx->argument(1).toInt32(); if(row < 0 || row >= aln.getLength()) { return ctx->throwError(QObject::tr("Row is out of range")); } aln.removeRow(row); QScriptValue calee = ctx->callee(); calee.setProperty("res", engine->newVariant(QVariant::fromValue(aln))); return calee.property("res"); } QScriptValue WorkflowScriptLibrary::rowNum(QScriptContext *ctx, QScriptEngine *engine) { if(ctx->argumentCount()!= 1) { return ctx->throwError(QObject::tr("Incorrect number of arguments")); } MAlignment aln = ctx->argument(0).toVariant().value(); if(aln.isEmpty()) { return ctx->throwError(QObject::tr("Invalid alignment")); } int num = aln.getNumRows(); QScriptValue calee = ctx->callee(); calee.setProperty("res", engine->newVariant(num)); return calee.property("res"); } QScriptValue WorkflowScriptLibrary::columnNum(QScriptContext *ctx, QScriptEngine *engine) { if(ctx->argumentCount()!= 1) { return ctx->throwError(QObject::tr("Incorrect number of arguments")); } MAlignment aln = ctx->argument(0).toVariant().value(); if(aln.isEmpty()) { return ctx->throwError(QObject::tr("Invalid alignment")); } int num = aln.getLength(); QScriptValue calee = ctx->callee(); calee.setProperty("res", engine->newVariant(num)); return calee.property("res"); } QScriptValue WorkflowScriptLibrary::alignmentAlphabetType(QScriptContext *ctx, QScriptEngine *engine) { if(ctx->argumentCount()!= 1) { return ctx->throwError(QObject::tr("Incorrect number of arguments")); } MAlignment aln = ctx->argument(0).toVariant().value(); if(aln.isEmpty()) { return ctx->throwError(QObject::tr("Invalid alignment")); } QString alph = aln.getAlphabet()->getName(); QScriptValue calee = ctx->callee(); calee.setProperty("res", engine->newVariant(alph)); return calee.property("res"); } QScriptValue WorkflowScriptLibrary::getAnnotationRegion(QScriptContext *ctx, QScriptEngine *engine) { if(ctx->argumentCount() != 3) { return ctx->throwError(QObject::tr("Incorrect number of arguments")); } DNASequence seq = ctx->argument(0).toVariant().value(); if(seq.seq.isEmpty()) { return ctx->throwError(QObject::tr("Empty or invalid sequence")); } QList anns = ctx->argument(1).toVariant().value< QList >(); if(anns.isEmpty()) { return ctx->throwError(QObject::tr("Invalid annotations")); } QString name = ctx->argument(2).toString(); if(name.isEmpty()) { return ctx->throwError(QObject::tr("Empty name")); } QList result; foreach(const SharedAnnotationData &ann, anns) { if(ann->name == name) { DNASequence resultedSeq; const QByteArray & sequence = seq.seq; QVector location = ann->getRegions(); QByteArray & res = resultedSeq.seq; QVector extendedRegions; //extend regions U2Region sequenceRange(0, sequence.size()); foreach(const U2Region& reg, location) { U2Region ir = reg.intersect(sequenceRange); extendedRegions << ir; } for( int i = 0, end = extendedRegions.size(); i < end; ++i ) { U2Region reg = extendedRegions.at(i); QByteArray partSeq(sequence.constData() + reg.startPos, reg.length); res.append(partSeq); } resultedSeq.alphabet = seq.alphabet; result << resultedSeq; } } QScriptValue calee = ctx->callee(); QScriptValue flag = engine->globalObject(); flag.setProperty("list", engine->newVariant(true)); calee.setProperty("res", engine->newVariant(QVariant::fromValue >(result))); return calee.property("res"); } QScriptValue WorkflowScriptLibrary::filterByQualifier(QScriptContext *ctx, QScriptEngine *engine) { if(ctx->argumentCount()!= 3) { return ctx->throwError(QObject::tr("Incorrect number of arguments")); } QList anns = ctx->argument(0).toVariant().value< QList >(); if(anns.isEmpty()) { return ctx->throwError(QObject::tr("Invalid annotations")); } QString qual = ctx->argument(1).toString(); if(qual.isEmpty()) { return ctx->throwError(QObject::tr("Empty qualifier name")); } QString val = ctx->argument(2).toString(); if(val.isEmpty()) { return ctx->throwError(QObject::tr("Empty qualifier value")); } QList res; foreach(const SharedAnnotationData &ann, anns) { if(ann->qualifiers.contains(U2Qualifier(qual, val))) { res << ann; } } QScriptValue calee = ctx->callee(); calee.setProperty("res", engine->newVariant(QVariant::fromValue >(res))); return calee.property("res"); } QScriptValue WorkflowScriptLibrary::addQualifier(QScriptContext *ctx, QScriptEngine *engine) { if(ctx->argumentCount() < 3 && ctx->argumentCount() > 4) { return ctx->throwError(QObject::tr("Incorrect number of arguments")); } QList anns = ctx->argument(0).toVariant().value< QList >(); if(anns.isEmpty()) { return ctx->throwError(QObject::tr("Invalid annotations")); } QString qual = ctx->argument(1).toString(); if(qual.isEmpty()) { return ctx->throwError(QObject::tr("Empty qualifier name")); } QString val = ctx->argument(2).toString(); if(val.isEmpty()) { return ctx->throwError(QObject::tr("Empty qualifier value")); } if(ctx->argumentCount() == 4) { QString name = ctx->argument(3).toString(); if(name.isEmpty()) { return ctx->throwError(QObject::tr("forth argument must be a string")); } for(int i = 0;iname == name) { anns[i]->qualifiers.append(U2Qualifier(qual,val)); } } } else { for(int i = 0;iqualifiers.append(U2Qualifier(qual,val)); } } QScriptValue calee = ctx->callee(); calee.setProperty("res", engine->newVariant(QVariant::fromValue >(anns))); return calee.property("res"); } QScriptValue WorkflowScriptLibrary::getLocation(QScriptContext *ctx, QScriptEngine *engine) { if(ctx->argumentCount() != 2) { return ctx->throwError(QObject::tr("Incorrect number of arguments")); } QList anns = ctx->argument(0).toVariant().value< QList >(); if(anns.isEmpty()) { return ctx->throwError(QObject::tr("Invalid annotations")); } if(!ctx->argument(1).isNumber()) { return ctx->throwError(QObject::tr("Second argument must be a number")); } int num = ctx->argument(1).toInt32(); if(num < 0 || num > anns.size()) { return ctx->throwError(QObject::tr("Index is out of range")); } QVector loc = anns[num]->getRegions(); QScriptValue calee = ctx->callee(); calee.setProperty("res", engine->newVariant(QVariant::fromValue >(loc))); return calee.property("res"); } QScriptValue WorkflowScriptLibrary::debugOut(QScriptContext *ctx, QScriptEngine *) { QString msg = ""; if(ctx->argument(0).isNumber()) { msg = QString::number(ctx->argument(0).toInt32()); } else if(ctx->argument(0).isString()) { msg = ctx->argument(0).toString(); } else if(ctx->argument(0).isBool()) { if(ctx->argument(0).toBool()) { msg = "true"; } else { msg = "false"; } } scriptLog.details(msg); return 0; } } // U2 ugene-1.9.8/src/corelibs/U2Lang/src/library/LocalDomain.h0000644000175000017500000001077511651544333021600 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_WORKFLOW_LOCAL_DOMAIN_H_ #define _U2_WORKFLOW_LOCAL_DOMAIN_H_ #include #include #include #include #include #include namespace U2 { namespace LocalWorkflow { using namespace Workflow; /** * currently, all wd workers inherits this class * * base class for workers in integral bus model */ class U2LANG_EXPORT BaseWorker : public QObject, public Worker, public CommunicationSubject { Q_OBJECT public: BaseWorker(Actor* a, bool autoTransitBus = true); virtual ~BaseWorker(); virtual ActorId getActorId() const; // reimplemented from CommunicationSubject virtual bool addCommunication(const QString& name, CommunicationChannel* _ch); virtual CommunicationChannel* getCommunication(const QString& name); // if you want your worker support scripts -> you should call this function to get Messages from channels // call this when channel has message // after calling: set all needed values for running your worker // called from 'tick' and then setup worker params virtual Message getMessageAndSetupScriptValues( CommunicationChannel * channel ); private: // bind values from input ports to script vars. // This function is called before 'get' data from channel -> to set up parameters for scripting void bindScriptValues(); protected: Actor* actor; // integral buses of actor's ports QMap ports; // workflow settings: worker task should fail on first error //bool failFast; }; // BaseWorker /** * simple realization of scheduler * worker tasks run sequentially, not in parallel * * bind to BaseWorker class as actor's workers */ class U2LANG_EXPORT SimplestSequentialScheduler : public Scheduler { public: SimplestSequentialScheduler(Schema* sh); virtual ~SimplestSequentialScheduler(); // reimplemented from Worker virtual void init(); virtual bool isReady(); virtual Task* tick(); virtual bool isDone(); virtual void cleanup(); virtual WorkerState getWorkerState(ActorId); private: Schema* schema; BaseWorker* lastWorker; Task* lastTask; }; // SimplestSequentialScheduler /** * simple realization of Communnication channel */ class U2LANG_EXPORT SimpleQueue : public CommunicationChannel { public: SimpleQueue(); virtual ~SimpleQueue(){} // reimplemented from CommunicationChannel virtual Message get(); virtual Message look() const; virtual void put(const Message& m); virtual int hasMessage() const; virtual int takenMessages()const; virtual int hasRoom(const DataType* ) const; virtual bool isEnded() const; virtual void setEnded(); // capacity is INT_MAX virtual int capacity() const; // does nothing virtual void setCapacity(int); protected: // first in, first out QQueue que; // 'end' flag bool ended; // int takenMsgs; }; // SimpleQueue /** * runtime domain for SimplestSequentialScheduler and SimpleQueue * * currently, container for all DomainFactories of computational tasks */ class U2LANG_EXPORT LocalDomainFactory : public DomainFactory { public: static const QString ID; public: LocalDomainFactory(); virtual ~LocalDomainFactory(){} virtual Worker* createWorker(Actor*); virtual CommunicationChannel* createConnection(Link*); virtual Scheduler* createScheduler(Schema*); virtual void destroy(Scheduler*, Schema*); }; // LocalDomainFactory }//Workflow namespace }//GB2 namespace #endif // _U2_WORKFLOW_LOCAL_DOMAIN_H_ ugene-1.9.8/src/corelibs/U2Lang/src/library/ScriptLibrary.h0000644000175000017500000000706511651544333022205 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _WORKFLOW_SCRIPT_FUNC_H_ #define _WORKFLOW_SCRIPT_FUNC_H_ #include #include #include #include #include #include #include #include namespace U2 { class U2LANG_EXPORT WorkflowScriptLibrary { public: static void initEngine(QScriptEngine * engine); // ================== Sequence ======================= static QScriptValue getSubsequence(QScriptContext *ctx, QScriptEngine *engine); static QScriptValue concatSequence(QScriptContext *ctx, QScriptEngine *engine); static QScriptValue complement(QScriptContext *ctx, QScriptEngine *engine); static QScriptValue sequenceSize(QScriptContext *ctx, QScriptEngine *engine); static QScriptValue translate(QScriptContext *ctx, QScriptEngine *engine); static QScriptValue charAt(QScriptContext *ctx, QScriptEngine *engine); static QScriptValue sequenceName(QScriptContext *ctx, QScriptEngine *); static QScriptValue alphabetType(QScriptContext *ctx, QScriptEngine *engine); static QScriptValue sequenceFromText(QScriptContext *ctx, QScriptEngine *engine); static QScriptValue isAmino(QScriptContext *ctx, QScriptEngine *); static QScriptValue getMinimumQuality(QScriptContext *ctx, QScriptEngine *); static QScriptValue hasQuality(QScriptContext *ctx, QScriptEngine *); // ================== Alignment ======================= static QScriptValue getSequenceFromAlignment(QScriptContext *ctx, QScriptEngine *engine); static QScriptValue findInAlignment(QScriptContext *ctx, QScriptEngine *engine); static QScriptValue createAlignment(QScriptContext *ctx, QScriptEngine *engine); static QScriptValue addToAlignment(QScriptContext *ctx, QScriptEngine *engine); static QScriptValue removeFromAlignment(QScriptContext *ctx, QScriptEngine *engine); static QScriptValue rowNum(QScriptContext *ctx, QScriptEngine *engine); static QScriptValue columnNum(QScriptContext *ctx, QScriptEngine *engine); static QScriptValue alignmentAlphabetType(QScriptContext *ctx, QScriptEngine *engine); // ================== Annotations ======================= static QScriptValue getAnnotationRegion(QScriptContext *ctx, QScriptEngine *engine); static QScriptValue filterByQualifier(QScriptContext *ctx, QScriptEngine *engine); static QScriptValue addQualifier(QScriptContext *ctx, QScriptEngine *engine); static QScriptValue getLocation(QScriptContext *ctx, QScriptEngine *engine); // ================== Misc ======================= static QScriptValue debugOut(QScriptContext *ctx, QScriptEngine *); }; // WorkflowScriptLibrary } // U2 #endif ugene-1.9.8/src/corelibs/U2Lang/src/library/BasePorts.h0000644000175000017500000000274311651544333021314 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef __U2_WORKFLOW_BASE_PORTS_H_ #define __U2_WORKFLOW_BASE_PORTS_H_ #include #include namespace U2 { namespace Workflow { class U2LANG_EXPORT BasePorts { public: static const QString OUT_MSA_PORT_ID(); static const QString IN_MSA_PORT_ID(); static const QString OUT_SEQ_PORT_ID(); static const QString IN_SEQ_PORT_ID(); static const QString OUT_ANNOTATIONS_PORT_ID(); static const QString IN_ANNOTATIONS_PORT_ID(); static const QString OUT_TEXT_PORT_ID(); static const QString IN_TEXT_PORT_ID(); }; // BasePorts } // Workflow } // U2 #endif // __U2_WORKFLOW_BASE_PORTS_H_ ugene-1.9.8/src/corelibs/U2Lang/src/library/BaseActorCategories.h0000644000175000017500000000315011651544333023254 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_WORKFLOW_BASE_LIB_H_ #define _U2_WORKFLOW_BASE_LIB_H_ #include namespace U2 { namespace Workflow { class U2LANG_EXPORT BaseActorCategories : public QObject { Q_OBJECT public: static const Descriptor CATEGORY_DATASRC(); static const Descriptor CATEGORY_DATASINK(); static const Descriptor CATEGORY_CONVERTERS(); static const Descriptor CATEGORY_BASIC(); static const Descriptor CATEGORY_ALIGNMENT(); static const Descriptor CATEGORY_ASSEMBLY(); static const Descriptor CATEGORY_TRANSCRIPTION(); static const Descriptor CATEGORY_SCRIPT(); static const Descriptor CATEGORY_STATISTIC(); static const Descriptor CATEGORY_EXTERNAL(); }; // BaseActorCategories }//Workflow namespace }//GB2 namespace #endif ugene-1.9.8/src/corelibs/U2Lang/src/library/BasePorts.cpp0000644000175000017500000000277711651544333021656 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "BasePorts.h" namespace U2 { namespace Workflow { const QString BasePorts::OUT_MSA_PORT_ID() { return "out-msa"; } const QString BasePorts::IN_MSA_PORT_ID() { return "in-msa"; } const QString BasePorts::OUT_SEQ_PORT_ID() { return "out-sequence"; } const QString BasePorts::IN_SEQ_PORT_ID() { return "in-sequence"; } const QString BasePorts::OUT_ANNOTATIONS_PORT_ID() { return "out-annotations"; } const QString BasePorts::IN_ANNOTATIONS_PORT_ID() { return "in-annotations"; } const QString BasePorts::OUT_TEXT_PORT_ID() { return "out-text"; } const QString BasePorts::IN_TEXT_PORT_ID() { return "in-text"; } } // Workflow } // U2 ugene-1.9.8/src/corelibs/U2Lang/src/library/BaseActorCategories.cpp0000644000175000017500000000427711651544333023622 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include #include "LocalDomain.h" #include "BaseActorCategories.h" namespace U2 { namespace Workflow { const Descriptor BaseActorCategories::CATEGORY_DATASRC() { return Descriptor("a", tr("Data Readers"), ""); } const Descriptor BaseActorCategories::CATEGORY_DATASINK() { return Descriptor("b", tr("Data Writers"), ""); } const Descriptor BaseActorCategories::CATEGORY_CONVERTERS() { return Descriptor("bc", tr("Data Converters"), ""); } const Descriptor BaseActorCategories::CATEGORY_BASIC() { return Descriptor("c", tr("Basic Analysis"), ""); } const Descriptor BaseActorCategories::CATEGORY_STATISTIC() { return Descriptor("st", tr("Utils"), ""); } const Descriptor BaseActorCategories::CATEGORY_ALIGNMENT() { return Descriptor("d", tr("Multiple Sequence Alignment"), ""); } const Descriptor BaseActorCategories::CATEGORY_ASSEMBLY() { return Descriptor("asm", tr("DNA Assembly"), ""); } const Descriptor BaseActorCategories::CATEGORY_TRANSCRIPTION() { return Descriptor("tr", tr("Transcription Factor"), ""); } const Descriptor BaseActorCategories::CATEGORY_SCRIPT() { return Descriptor("sa", tr("Custom Elements with Script"), ""); } const Descriptor BaseActorCategories::CATEGORY_EXTERNAL() { return Descriptor("ex", tr("Custom Elements with CMD Tools"),""); } }//Workflow namespace }//GB2 namespace ugene-1.9.8/src/corelibs/U2Lang/src/library/BaseTypes.h0000644000175000017500000000511411651544333021304 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef __U2_BASE_TYPES_H_ #define __U2_BASE_TYPES_H_ #include namespace U2 { class U2LANG_EXPORT BaseTypes : public QObject { Q_OBJECT public: static DataTypePtr DNA_SEQUENCE_TYPE(); static DataTypePtr ANNOTATION_TABLE_LIST_TYPE(); static DataTypePtr ANNOTATION_TABLE_TYPE(); static DataTypePtr MULTIPLE_ALIGNMENT_TYPE(); static DataTypePtr STRING_TYPE(); static DataTypePtr BOOL_TYPE(); static DataTypePtr NUM_TYPE(); static DataTypePtr ANY_TYPE(); }; // BaseTypes // value factories for core datatypes /** * DatatypeValueFactory realization for string type */ class StringTypeValueFactory : public DataTypeValueFactory { public: virtual QVariant getValueFromString( const QString & str, bool * ok = NULL ) const; virtual QString getId() const { return BaseTypes::STRING_TYPE()->getId(); } }; // StringTypeValueFactory /** * DatatypeValueFactory realization for bool type */ class BoolTypeValueFactory : public DataTypeValueFactory { public: static const QString TRUE_STR; static const QString FALSE_STR; static const QString YES_STR; static const QString NO_STR; static const QString ONE_STR; static const QString NIL_STR; public: virtual QVariant getValueFromString( const QString & str, bool * ok = NULL ) const; virtual QString getId() const { return BaseTypes::BOOL_TYPE()->getId(); } }; // BoolTypeValueFactory /** * DatatypeValueFactory realization for num type */ class NumTypeValueFactory : public DataTypeValueFactory { public: virtual QVariant getValueFromString( const QString & str, bool * ok = NULL ) const; virtual QString getId() const { return BaseTypes::NUM_TYPE()->getId(); } }; // NumTypeValueFactory } #endif // __U2_BASE_TYPES_H_ ugene-1.9.8/src/corelibs/U2Lang/src/library/LocalDomain.cpp0000644000175000017500000002210111651544333022115 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "LocalDomain.h" #include #include #include #include namespace U2 { namespace LocalWorkflow { const QString LocalDomainFactory::ID("domain.local.bio"); /***************************** * BaseWorker *****************************/ BaseWorker::BaseWorker(Actor* a, bool autoTransitBus) : actor(a) { foreach(Port* p, a->getPorts()) { if (qobject_cast(p)) { IntegralBus* bus = new IntegralBus(p); ports.insert(p->getId(), bus); p->setPeer(bus); } } if (autoTransitBus) { foreach(Port* p, a->getInputPorts()) { IntegralBus* bus = p->castPeer(); foreach(Port* op, a->getOutputPorts()) { if (p->isInput() != op->isInput()) { IntegralBus* ob = op->castPeer(); ob->addComplement(bus); bus->addComplement(ob); } } } } a->setPeer(this); //failFast = WorkflowSettings::failFast(); } BaseWorker::~BaseWorker() { foreach(Port* p, actor->getPorts()) { if (qobject_cast(p)) { p->setPeer(NULL); } } qDeleteAll(ports.values()); actor->setPeer(NULL); } bool BaseWorker::addCommunication(const QString& id, CommunicationChannel* ch) { Q_UNUSED(id); Q_UNUSED(ch); assert(0); return false; } CommunicationChannel * BaseWorker::getCommunication(const QString& name) { return ports.value(name); } ActorId BaseWorker::getActorId() const { return actor->getId(); } Message BaseWorker::getMessageAndSetupScriptValues( CommunicationChannel * channel ) { assert(channel != NULL); assert(channel->hasMessage()); bindScriptValues(); return channel->get(); } void BaseWorker::bindScriptValues() { foreach( IntegralBus * bus, ports.values() ) { assert(bus != NULL); if(!bus->hasMessage()) { // means that it is bus for output port continue; } QVariantMap busData = bus->look().getData().toMap(); foreach( Attribute * attribute, actor->getParameters().values() ) { assert(attribute != NULL); foreach(const QString & slotDesc, busData.keys()) { ActorId actorId = IntegralBusType::parseSlotDesc(slotDesc); QString attrId = IntegralBusType::parseAttributeIdFromSlotDesc(slotDesc); QString portId = bus->getPortId(); IntegralBusPort * busPort = qobject_cast(actor->getPort(portId)); assert(busPort != NULL); Actor * bindedAttrOwner = busPort->getLinkedActorById(actorId); if(bindedAttrOwner == NULL) { continue; } //attrId.replace(".", "_"); //attrId.replace("-", "_"); AttributeScript & attrScript = attribute->getAttributeScript(); if( !attrScript.getScriptText().isEmpty() ) { //attrScript.setVarValueWithId(attrId, busData.value(slotDesc)); attrScript.setScriptVar(attrId, busData.value(slotDesc)); } } } } } /***************************** * SimplestSequentialScheduler *****************************/ SimplestSequentialScheduler::SimplestSequentialScheduler(Schema* sh) : schema(sh), lastWorker(NULL), lastTask(NULL) { } void SimplestSequentialScheduler::init() { foreach(Actor* a, schema->getProcesses()) { a->castPeer()->init(); } } bool SimplestSequentialScheduler::isReady() { foreach(Actor* a, schema->getProcesses()) { if (a->castPeer()->isReady()) { return true; } } return false; } Task* SimplestSequentialScheduler::tick() { foreach(Actor* a, schema->getProcesses()) { if (a->castPeer()->isReady()) { lastWorker = a->castPeer(); return lastTask = lastWorker->tick(); } } assert(0); return NULL; } bool SimplestSequentialScheduler::isDone() { foreach(Actor* a, schema->getProcesses()) { if (!a->castPeer()->isDone()) { return false; } } return true; } void SimplestSequentialScheduler::cleanup() { foreach(Actor* a, schema->getProcesses()) { a->castPeer()->cleanup(); } } SimplestSequentialScheduler::~SimplestSequentialScheduler() { } U2::Workflow::WorkerState SimplestSequentialScheduler::getWorkerState( ActorId id) { Actor* a = schema->actorById(id); assert(a); BaseWorker* w = a->castPeer(); if (lastWorker == w) { Task* t = lastTask; if (w->isDone() && t && t->isFinished()) { return WorkerDone; } return WorkerRunning; } if (w->isDone()) { return WorkerDone; } else if (w->isReady()) { return WorkerReady; } return WorkerWaiting; } /***************************** * SimpleQueue *****************************/ SimpleQueue::SimpleQueue() : ended(false), takenMsgs(0) { } Message SimpleQueue::get() { assert(hasMessage()); takenMsgs++; return que.dequeue(); } Message SimpleQueue::look() const { assert(hasMessage()); return que.head(); } void SimpleQueue::put(const Message& m) { que.enqueue(m); } int SimpleQueue::hasMessage() const { return que.size(); } int SimpleQueue::takenMessages() const { return takenMsgs; } int SimpleQueue::hasRoom(const DataType* ) const { return 1000; } bool SimpleQueue::isEnded() const { return ended && que.isEmpty(); } void SimpleQueue::setEnded() { ended = true; } int SimpleQueue::capacity() const { return INT_MAX; } void SimpleQueue::setCapacity(int) { } /***************************** * LocalDomainFactory *****************************/ LocalDomainFactory::LocalDomainFactory() : DomainFactory(ID) { } static CommunicationSubject* setupBus(Port* p) { QString id = p->getId(); BaseWorker* worker = p->owner()->castPeer(); assert(worker); CommunicationSubject* subj = worker; IntegralBus* bus = qobject_cast(p->castPeer()); if (bus) { assert(subj->getCommunication(id) == dynamic_cast(bus)); subj = bus; } else if (subj) { assert(0); bus = new IntegralBus(p); p->setPeer(bus); subj->addCommunication(id, bus); subj = bus; foreach(Port* op, p->owner()->getPorts()) { if (p->isInput() != op->isInput()) { IntegralBus* ob = qobject_cast(op->castPeer()); if (ob) { ob->addComplement(bus); bus->addComplement(ob); } } } } return subj; } Worker* LocalDomainFactory::createWorker(Actor* a) { Worker* w = NULL; DomainFactory* f = getById(a->getProto()->getId()); if (f) { w = f->createWorker(a); #ifdef _DEBUG assert(w); BaseWorker* bw = dynamic_cast(w); assert(qobject_cast(bw)); assert(bw == a->getPeer()); #endif } return w; } CommunicationChannel* LocalDomainFactory::createConnection(Link* l) { SimpleQueue* cc = NULL; QString srcId = l->source()->getId(); QString dstId = l->destination()->getId(); CommunicationSubject* src = setupBus(l->source()); CommunicationSubject* dst = setupBus(l->destination()); if (src && dst) { cc = new SimpleQueue(); src->addCommunication(srcId, cc); dst->addCommunication(dstId, cc); } l->setPeer(cc); return cc; } Scheduler* LocalDomainFactory::createScheduler(Schema* sh) { SimplestSequentialScheduler* sc = new SimplestSequentialScheduler(sh); return sc; } void LocalDomainFactory::destroy( Scheduler* sh, Schema* schema) { foreach(Link* l, schema->getFlows()) { delete l->castPeer(); l->setPeer(NULL); } foreach(Actor* a, schema->getProcesses()) { delete a->castPeer(); } delete sh; } } // Workflow namespace } // U2 namespace ugene-1.9.8/src/corelibs/U2Lang/src/library/BaseTypes.cpp0000644000175000017500000001435111651544333021642 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include #include "BaseTypes.h" namespace U2 { static const QString DNA_SEQUENCE_TYPE_ID("seq"); static const QString ANNOTATION_TABLE_LIST_TYPE_ID("ann-table-list"); static const QString ANNOTATION_TABLE_TYPE_ID("ann_table"); static const QString MULTIPLE_ALIGNMENT_TYPE_ID("malignment"); static const QString STRING_TYPE_ID("string"); static const QString BOOL_TYPE_ID("bool"); static const QString NUM_TYPE_ID("number"); static const QString ANY_TYPE_ID("void"); using namespace Workflow; DataTypePtr BaseTypes::DNA_SEQUENCE_TYPE() { DataTypeRegistry* dtr = WorkflowEnv::getDataTypeRegistry(); assert(dtr); static bool startup = true; if (startup) { dtr->registerEntry(DataTypePtr(new DataType(DNA_SEQUENCE_TYPE_ID, tr("Sequence"), tr("A sequence")))); startup = false; } return dtr->getById(DNA_SEQUENCE_TYPE_ID); } DataTypePtr BaseTypes::ANNOTATION_TABLE_TYPE() { DataTypeRegistry* dtr = WorkflowEnv::getDataTypeRegistry(); assert(dtr); static bool startup = true; if (startup) { dtr->registerEntry(DataTypePtr(new DataType(ANNOTATION_TABLE_TYPE_ID, tr("Set of annotations"), tr("A set of annotated features in a sequence")))); startup = false; } return dtr->getById(ANNOTATION_TABLE_TYPE_ID); } DataTypePtr BaseTypes::ANNOTATION_TABLE_LIST_TYPE() { DataTypeRegistry* dtr = WorkflowEnv::getDataTypeRegistry(); assert(dtr); static bool startup = true; if (startup) { dtr->registerEntry(DataTypePtr(new ListDataType( Descriptor(ANNOTATION_TABLE_LIST_TYPE_ID, tr("List of annotations"), tr("A list of sequence annotations")), BaseTypes::ANNOTATION_TABLE_TYPE()))); startup = false; } return dtr->getById(ANNOTATION_TABLE_LIST_TYPE_ID); } DataTypePtr BaseTypes::MULTIPLE_ALIGNMENT_TYPE() { DataTypeRegistry* dtr = WorkflowEnv::getDataTypeRegistry(); assert(dtr); static bool startup = true; if (startup) { dtr->registerEntry(DataTypePtr(new DataType(MULTIPLE_ALIGNMENT_TYPE_ID, tr("Multiple alignment"), tr("Set of aligned sequences")))); startup = false; } return dtr->getById(MULTIPLE_ALIGNMENT_TYPE_ID); } DataTypePtr BaseTypes::STRING_TYPE() { DataTypeRegistry* dtr = WorkflowEnv::getDataTypeRegistry(); assert(dtr); static bool startup = true; if (startup) { dtr->registerEntry(DataTypePtr(new DataType(STRING_TYPE_ID, tr("String"), tr("A string of characters")))); startup = false; } return dtr->getById(STRING_TYPE_ID); } DataTypePtr BaseTypes::BOOL_TYPE() { DataTypeRegistry* dtr = WorkflowEnv::getDataTypeRegistry(); assert(dtr); static bool startup = true; if (startup) { dtr->registerEntry(DataTypePtr(new DataType(BOOL_TYPE_ID, tr("Boolean"), tr("A boolean value (true/false)")))); startup = false; } return dtr->getById(BOOL_TYPE_ID); } DataTypePtr BaseTypes::NUM_TYPE() { DataTypeRegistry* dtr = WorkflowEnv::getDataTypeRegistry(); assert(dtr); static bool startup = true; if (startup) { dtr->registerEntry(DataTypePtr(new DataType(NUM_TYPE_ID, tr("Number"), tr("A number")))); startup = false; } return dtr->getById(NUM_TYPE_ID); } DataTypePtr BaseTypes::ANY_TYPE() { DataTypeRegistry* dtr = WorkflowEnv::getDataTypeRegistry(); assert(dtr); static bool startup = true; if (startup) { dtr->registerEntry(DataTypePtr(new DataType(ANY_TYPE_ID, tr("Undefined"), tr("A void type")))); startup = false; } return dtr->getById(ANY_TYPE_ID); } static void setIfNotNull( bool * to, bool val ) { if( to != NULL ) { *to = val; } } /**************************************** * StringTypeValueFactory ****************************************/ QVariant StringTypeValueFactory::getValueFromString( const QString & str, bool * ok ) const { setIfNotNull( ok, true ); return qVariantFromValue( str ); } /**************************************** * BoolTypeValueFactory ****************************************/ const QString BoolTypeValueFactory::TRUE_STR = "true"; const QString BoolTypeValueFactory::FALSE_STR = "false"; const QString BoolTypeValueFactory::YES_STR = "yes"; const QString BoolTypeValueFactory::NO_STR = "no"; const QString BoolTypeValueFactory::ONE_STR = "1"; const QString BoolTypeValueFactory::NIL_STR = "0"; QVariant BoolTypeValueFactory::getValueFromString( const QString & s, bool * ok ) const { QString str = s.toLower(); if( str == TRUE_STR || str == YES_STR || str == ONE_STR ) { setIfNotNull( ok, true ); return qVariantFromValue( true ); } if( str == FALSE_STR || str == NO_STR || str == NIL_STR ) { setIfNotNull( ok, true ); return qVariantFromValue( false ); } setIfNotNull( ok, false ); return QVariant(); } /**************************************** * NumTypeValueFactory ****************************************/ QVariant NumTypeValueFactory::getValueFromString( const QString & str, bool * okArg ) const { bool ok = false; int intCandidate = str.toInt(&ok); if(ok) { setIfNotNull(okArg, true); return qVariantFromValue(intCandidate); } double doubleCandidate = str.toDouble(&ok); if(ok) { setIfNotNull(okArg, true); return qVariantFromValue(doubleCandidate); } setIfNotNull(okArg, false); return QVariant(); } } // U2 ugene-1.9.8/src/corelibs/U2Lang/src/support/0000755000175000017500000000000011651544333017303 5ustar ilyailyaugene-1.9.8/src/corelibs/U2Lang/src/support/SchemaSerializer.h0000644000175000017500000000465611651544333022721 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_WORKFLOW_SERIALIZER_H_ #define _U2_WORKFLOW_SERIALIZER_H_ #include #include class QDomDocument; class QDomElement; namespace U2 { namespace Workflow { /** * utility class for serialization/deserialization schema and all schema elements * serialization to xml become obsolete. See HRSchemaSerializer * */ class U2LANG_EXPORT SchemaSerializer : public QObject { Q_OBJECT public: // old schemas support static const QMap ELEM_TYPES_MAP; static QString getElemType(const QString & t); static const QString WORKFLOW_DOC; static void readConfiguration(Configuration*, const QDomElement& ); static void readParamAliases( QMap &, const QDomElement& ); static void saveIterations(const QList&, QDomElement& ); static void readIterations(QList&, const QDomElement&,const QMap&); static QDomElement saveActor(const Actor*, QDomElement&); static QDomElement savePort(const Port*, QDomElement&); static QDomElement saveLink(const Link*, QDomElement&); static QString readMeta(Metadata* meta, const QDomElement& proj); static void updatePortBindings(const QList & procs); static void schema2xml(const Schema& scema, QDomDocument& xml); static QString xml2schema(const QDomElement& projectElement, Schema* schema, QMap& remapping, bool stopOnErrors = true); private: static QMap initElemTypesMap(); }; // SchemaSerializer } //namespace Workflow } //namespace U2 #endif ugene-1.9.8/src/corelibs/U2Lang/src/support/CoreLibConstants.cpp0000644000175000017500000000400611651544333023223 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "CoreLibConstants.h" namespace U2 { namespace Workflow { const QString CoreLibConstants::READ_TEXT_PROTO_ID("read-text"); const QString CoreLibConstants::WRITE_TEXT_PROTO_ID("write-text"); const QString CoreLibConstants::WRITE_FASTA_PROTO_ID("write-fasta"); const QString CoreLibConstants::WRITE_GENBANK_PROTO_ID("write-genbank"); const QString CoreLibConstants::WRITE_CLUSTAL_PROTO_ID("write-clustalw"); const QString CoreLibConstants::WRITE_STOCKHOLM_PROTO_ID("write-stockholm"); const QString CoreLibConstants::WRITE_MSA_PROTO_ID("write-msa"); const QString CoreLibConstants::WRITE_SEQ_PROTO_ID("write-sequence"); const QString CoreLibConstants::WRITE_FASTQ_PROTO_ID("write-fastq"); const QString CoreLibConstants::GENERIC_READ_MA_PROTO_ID("read-msa"); const QString CoreLibConstants::GENERIC_READ_SEQ_PROTO_ID("read-sequence"); const QString CoreLibConstants::TEXT_TYPESET_ID("text.content"); const QString CoreLibConstants::WORKFLOW_ON_CLOUD_TASK_ID("cloud.workflow"); const QString CoreLibConstants::WORKFLOW_SCHEMA_ATTR("workflow.shema"); const QString CoreLibConstants::DATA_IN_ATTR("data.in"); const QString CoreLibConstants::DATA_OUT_ATTR("data.out"); } // Workflow } // U2 ugene-1.9.8/src/corelibs/U2Lang/src/support/SchemaSerializer.cpp0000644000175000017500000004137111651544333023247 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include #include #include #include #include #include #include #include #include "SchemaSerializer.h" //Q_DECLARE_METATYPE(U2::Workflow::CfgMap) namespace U2 { namespace Workflow { const QMap SchemaSerializer::ELEM_TYPES_MAP = SchemaSerializer::initElemTypesMap(); const QString SchemaSerializer::WORKFLOW_DOC = "GB2WORKFLOW"; static const QString WORKFLOW_EL = "workflow"; static const QString DOMAIN_EL = "workflow"; static const QString PROCESS_EL = "process"; static const QString ITERATION_EL = "iteration"; static const QString PORT_EL = "port"; static const QString PARAMS_EL = "params"; static const QString DATAFLOW_EL = "dataflow"; static const QString ID_ATTR = "id"; static const QString NAME_ATTR = "name"; static const QString TYPE_ATTR = "type"; static const QString SRC_PORT_ATTR = "sprt"; static const QString SRC_PROC_ATTR = "sprc"; static const QString DST_PORT_ATTR = "dprt"; static const QString DST_PROC_ATTR = "dprc"; static const QString ALIASES_EL = "paramAliases"; static const QString SCRIPT_TEXT = "scriptText"; static void saveConfiguration(const Configuration& cfg, QDomElement& owner) { QVariantMap qm; foreach (Attribute* a, cfg.getParameters()) { qm[a->getId()] = a->toVariant(); } QDomElement el = owner.ownerDocument().createElement(PARAMS_EL); owner.appendChild(el); el.appendChild(owner.ownerDocument().createTextNode(QVariantUtils::map2String(qm))); } static void saveParamAliases(const QMap & aliases, QDomElement & owner ) { QDomElement el = owner.ownerDocument().createElement( ALIASES_EL ); QMap::const_iterator it = aliases.constBegin(); while( it != aliases.constEnd() ) { el.setAttribute( it.key(), it.value() ); ++it; } owner.appendChild( el ); } QMap SchemaSerializer::initElemTypesMap() { QMap map; map["read.malignment"] = "read-msa"; map["read.remote"] = "fetch-sequence"; map["read.sequence"] = "read-sequence"; map["read.text"] = "read-text"; map["write.malignment"] = "write-msa"; map["write.clustalw"] = "write-clustalw"; map["write.fasta"] = "write-fasta"; map["write.fastq"] = "write-fastq"; map["write.gbk"] = "write-genbank"; map["write.text"] = "write-text"; map["write.sequence"] = "write-sequence"; map["write.stockholm"] = "write-stockholm"; map["annotator.collocation"] = "collocated-annotation-search"; map["sequence.extract"] = "extract-annotated-sequence"; map["repeat.finder"] = "repeats-search"; map["find.pattern"] = "search"; map["import.phred.quality"] = "import-phred-qualities"; map["blastall"] = "blast"; map["blastPlus"] = "blast-plus"; map["orf.marker"] = "orf-search"; map["remote.query"] = "blast-ncbi"; map["find.smithwaterman"] = "ssearch"; map["bowtie.assembly"] = "bowtie"; map["bowtie.indexer"] = "bowtie-build-index"; map["bowtie.index.reader"] = "bowtie-read-index"; map["uhmmer.build"] = "hmm2-build"; map["uhmmer.search"] = "hmm2-search"; map["uhmmer.read"] = "hmm2-read-profile"; map["uhmmer.write"] = "hmm2-write-profile"; map["clustalw.align"] = "clustalw"; map["kalign.align"] = "kalign"; map["mafft.align"] = "mafft"; map["muscle.align"] = "muscle"; map["tcoffee.align"] = "tcoffee"; map["pfmatrix.build"] = "fmatrix-build"; map["sitecon.build"] = "sitecon-build"; map["pwmatrix.build"] = "wmatrix-build"; map["pfmatrix.convert"] = "fmatrix-to-wmatrix"; map["pfmatrix.read"] = "fmatrix-read"; map["sitecon.read"] = "sitecon-read"; map["pwmatrix.read"] = "wmatrix-read"; map["sitecon.search"] = "sitecon-search"; map["pwmatrix.search"] = "wmatrix-search"; map["pfmatrix.write"] = "fmatrix-write"; map["sitecon.write"] = "sitecon-write"; map["pwmatrix.write"] = "wmatrix-write"; return map; } QString SchemaSerializer::getElemType(const QString & t) { if(ELEM_TYPES_MAP.contains(t)) { return ELEM_TYPES_MAP.value(t); } return t; } QDomElement SchemaSerializer::saveActor(const Actor* proc, QDomElement& proj) { QDomElement docElement = proj.ownerDocument().createElement(PROCESS_EL); docElement.setAttribute(ID_ATTR, proc->getId()); docElement.setAttribute(TYPE_ATTR, proc->getProto()->getId()); docElement.setAttribute(NAME_ATTR, proc->getLabel()); docElement.setAttribute(SCRIPT_TEXT, proc->getScript() == 0? "" : proc->getScript()->getScriptText()); saveConfiguration(*proc, docElement); saveParamAliases( proc->getParamAliases(), docElement ); proj.appendChild(docElement); return docElement; } //static Actor* readActor(const QDomElement& procElement) { // const QString name = procElement.attribute(TYPE_ATTR); // ActorPrototype* proto = WorkflowEnv::getProtoRegistry()->getProto(name); // if (!proto) { // return NULL; // } // Actor* proc = proto->createInstance(); // if (proc) { // SchemaSerializer::readConfiguration(proc, procElement); // proc->setLabel(procElement.attribute(NAME_ATTR)); // SchemaSerializer::readParamAliases( proc->getParamAliases(), procElement ); // } // return proc; //} QDomElement SchemaSerializer::saveLink(const Link* link, QDomElement& proj) { QDomElement docElement = proj.ownerDocument().createElement(DATAFLOW_EL); docElement.setAttribute(SRC_PORT_ATTR, link->source()->getId()); docElement.setAttribute(SRC_PROC_ATTR, link->source()->owner()->getId()); docElement.setAttribute(DST_PORT_ATTR, link->destination()->getId()); docElement.setAttribute(DST_PROC_ATTR, link->destination()->owner()->getId()); proj.appendChild(docElement); return docElement; } QDomElement SchemaSerializer::savePort(const Port* port, QDomElement& owner) { QDomElement el = owner.ownerDocument().createElement(PORT_EL); el.setAttribute(ID_ATTR, port->getId()); saveConfiguration(*port, el); owner.appendChild(el); return el; } void SchemaSerializer::schema2xml(const Schema& schema, QDomDocument& xml) { QDomElement projectElement = xml.createElement(WORKFLOW_EL); xml.appendChild(projectElement); foreach(Actor* a, schema.getProcesses()) { QDomElement el = saveActor(a, projectElement); foreach(Port* p, a->getPorts()) { savePort(p, el); } } foreach(Link* l, schema.getFlows()) { saveLink(l, projectElement); } QDomElement el = xml.createElement(DOMAIN_EL); el.setAttribute(NAME_ATTR, schema.getDomain()); projectElement.appendChild(el); } void SchemaSerializer::saveIterations(const QList& lst, QDomElement& proj) { foreach(const Iteration& it, lst) { QDomElement el = proj.ownerDocument().createElement(ITERATION_EL); el.setAttribute(ID_ATTR, it.id); el.setAttribute(NAME_ATTR, it.name); QVariant v = qVariantFromValue(it.cfg); el.appendChild(proj.ownerDocument().createTextNode(QVariantUtils::var2String(v))); proj.appendChild(el); } } void SchemaSerializer::readIterations(QList& lst, const QDomElement& proj, const QMap& remapping) { QDomNodeList paramNodes = proj.elementsByTagName(ITERATION_EL); for(int i=0; i(var)) { it.cfg = var.value(); } if (qVariantCanConvert(var)) { IterationCfg tmp = var.value(); QMapIterator tit(tmp); while (tit.hasNext()) { tit.next(); it.cfg[tit.key().first].insert(tit.key().second, tit.value()); } } it.remap(remapping); lst.append(it); } } void SchemaSerializer::readConfiguration(Configuration* cfg, const QDomElement& owner) { QDomNodeList paramNodes = owner.elementsByTagName(PARAMS_EL); for(int i=0; i it(qm); while (it.hasNext()) { it.next(); QVariant val = it.value(); QString keyStr = it.key(); if(cfg->hasParameter(keyStr)) { cfg->getParameter(keyStr)->fromVariant(val); } } } } void SchemaSerializer::readParamAliases( QMap & aliases, const QDomElement& owner ) { QDomNodeList alisesNodes = owner.elementsByTagName( ALIASES_EL ); int sz = alisesNodes.size(); for( int i = 0; i < sz; ++i ) { QDomNamedNodeMap map = alisesNodes.at( i ).toElement().attributes(); int mapSz = map.length(); for( int j = 0; j < mapSz; ++j ) { QDomNode node = map.item( j ); QString nodeName = node.nodeName(); QString nodeValue = node.nodeValue(); aliases.insert( nodeName, nodeValue ); } } } static const QString META_EL = "info"; //static void saveMeta(const Workflow::Metadata* meta, QDomElement& proj){ // QDomElement el = proj.ownerDocument().createElement(META_EL); // proj.appendChild(el); // el.setAttribute(NAME_ATTR, meta->name); // el.appendChild(proj.ownerDocument().createCDATASection(meta->comment)); //} QString SchemaSerializer::readMeta(Workflow::Metadata* meta, const QDomElement& proj) { QDomElement el = proj.elementsByTagName(META_EL).item(0).toElement(); meta->name = el.attribute(NAME_ATTR); meta->comment = el.text(); return el.isNull() ? tr("no metadata") : QString(); } static Port * findPort(const QList & procs, const ActorId & actorId, const QString & portId) { foreach(Actor * a, procs) { if(a->getId() == actorId) { foreach(Port * p, a->getPorts()) { if(p->getId() == portId) { return p; } } return NULL; } } return NULL; } void SchemaSerializer::updatePortBindings(const QList & procs) { foreach(Actor * actor, procs) { foreach(Port * p, actor->getInputPorts()) { IntegralBusPort * port = qobject_cast(p); QStrStrMap busMap = port->getParameter(IntegralBusPort::BUS_MAP_ATTR_ID)->getAttributeValue(); foreach(const QString & key, busMap.uniqueKeys()) { QString val = busMap.value(key); QStringList vals = val.split(":", QString::SkipEmptyParts); if(vals.size() == 2) { ActorId actorId = str2aid(vals.at(0)); QString slot = vals.at(1); Port * inP = findPort(procs, actorId, slot); if(!inP) {continue;} DataTypePtr inPType = inP->Port::getType(); QMap inPTypeMap = inPType->getDatatypesMap(); if(inP != NULL && inPType->isMap() && inPTypeMap.keys().size() == 1) { Descriptor d = inPTypeMap.keys().at(0); QString newVal = actorId + ":" + d.getId(); coreLog.details(QString("remapping old xml schema for key %1: old value: %2, new value: %3"). arg(key).arg(val).arg(newVal)); port->setBusMapValue(key, newVal); } } } } } } QString SchemaSerializer::xml2schema(const QDomElement& projectElement, Schema* schema, QMap& idmap, bool stopIfError) { QMap procMap; QDomElement domainEl = projectElement.elementsByTagName(DOMAIN_EL).item(0).toElement(); if (!domainEl.isNull()) { schema->setDomain(domainEl.attribute(NAME_ATTR)); } ActorPrototypeRegistry* registry = WorkflowEnv::getProtoRegistry(); QDomNodeList procNodes = projectElement.elementsByTagName(PROCESS_EL); for(int i=0; igetProto(name); if (!proto) { if (stopIfError) { return tr("Invalid content: unknown process type %1").arg(name); } else { continue; } } AttributeScript *script; const QString scriptText = procElement.attribute(SCRIPT_TEXT); if(scriptText.isEmpty()) { script = NULL; } else { script = new AttributeScript(); script->setScriptText(scriptText); } Actor* proc = proto->createInstance(script); readConfiguration(proc, procElement); readParamAliases( proc->getParamAliases(), procElement ); proc->setLabel(procElement.attribute(NAME_ATTR)); procMap[id] = proc; schema->addProcess(proc); //read port params QDomNodeList nl = procElement.elementsByTagName(PORT_EL); for(int j=0; jgetPort(eid); if (!p) { if (stopIfError) { return tr("Invalid content: unknown port %1 requested for %2").arg(eid).arg(name); } else { continue; } } readConfiguration(p, el); } } QMapIterator it(procMap); while(it.hasNext()) { it.next(); idmap[it.key()] = it.value()->getId(); } foreach(Actor* a, procMap) { a->remap(idmap); } QDomNodeList flowNodes = projectElement.elementsByTagName(DATAFLOW_EL); for(int i=0; igetPort(inP); Port* output = procMap[outId]->getPort(outP); if ((!input || !output || !input->canBind(output))) { if (stopIfError) { return tr("Invalid content: cannot bind [%1 : %2] to [%3 : %4]"). arg(inId).arg(inP).arg(outId).arg(outP); } } else { Link* l = new Link(input, output); schema->addFlow(l); } } updatePortBindings(procMap.values()); return QString(); } }//namespace Workflow }//namespace U2 ugene-1.9.8/src/corelibs/U2Lang/src/support/WorkflowUtils.h0000644000175000017500000001405711651544333022316 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_WORKFLOW_UTILS_H_ #define _U2_WORKFLOW_UTILS_H_ #include #include #include #include #include #include class QListWidgetItem; namespace U2 { class Descriptor; class DocumentFormat; using namespace Workflow; class U2LANG_EXPORT WorkflowUtils : public QObject { Q_OBJECT public: static QString getRichDoc(const Descriptor& d); static void setQObjectProperties(QObject&, const QVariantMap&); static QString getDropUrl(QList& fs, const QMimeData* md); static QStringList expandToUrls(const QString&); static const QStringList WD_FILE_EXTENSIONS; static const QString WD_XML_FORMAT_EXTENSION; #define ACTOR_REF (Qt::UserRole) #define PORT_REF (Qt::UserRole + 1) #define ITERATION_REF (Qt::UserRole + 2) #define TEXT_REF (Qt::UserRole + 3) //constructs fancy list widget items with icons, must be used only within UI (when icons can be constructed) static bool validate(const Workflow::Schema&, QList* = NULL); //more common version of the above method. Uses *_REFs as keys. Does not create any icons static bool validate(const Workflow::Schema& s, QList >* infoList ); static bool validate( const Workflow::Schema& s, QStringList & errs); static QList findMatchingTypes(DataTypePtr set, DataTypePtr elementDataType); static QStringList findMatchingTypesAsStringList(DataTypePtr set, DataTypePtr elementDatatype); static QList findMatchingCandidates(DataTypePtr from, DataTypePtr to, const Descriptor & key); static QList findMatchingCandidates(DataTypePtr from, DataTypePtr elementDatatype); static Descriptor getCurrentMatchingDescriptor(const QList & candidates, DataTypePtr to, const Descriptor & key, const QStrStrMap & bindings); static DataTypePtr getToDatatypeForBusport(IntegralBusPort * p); static DataTypePtr getFromDatatypeForBusport(IntegralBusPort * p, DataTypePtr to); // find schema with 'name' in common folders or from settings static QString findPathToSchemaFile(const QString & name); static void getLinkedActorsId(Actor *a, QList &linkedActors); //get list of ID's of all linked actors static QString getStringForParameterDisplayRole(const QVariant & value); static Actor * findActorByParamAlias(const QList & procs, const QString & alias, QString & attrName, bool writeLog = true); static Descriptor getSlotDescOfDatatype(const DataTypePtr & dt); private: static QStringList initExtensions(); }; // WorkflowUtils /** * provides utility functions for ActorDocument purposes */ class U2LANG_EXPORT PrompterBaseImpl : public ActorDocument, public Prompter { Q_OBJECT public: PrompterBaseImpl(Actor* p = 0) : ActorDocument(p) {} static bool isWildcardURL(const QString& url) {return url.indexOf(QRegExp("[*?\\[\\]]")) >= 0;} virtual ActorDocument * createDescription(Actor*) = 0; QString getURL(const QString& id, bool * empty = NULL ); QString getScreenedURL(IntegralBusPort* input, const QString& id, const QString& slot); QString getRequiredParam(const QString& id); QVariant getParameter(const QString& id); QString getProducers(const QString& port, const QString& slot); static QString getHyperlink(const QString& id, const QString& val); static QString getHyperlink(const QString& id, int val); static QString getHyperlink(const QString& id, qreal val); virtual QString composeRichDoc() = 0; virtual void update(const QVariantMap& cfg) {map = cfg; sl_actorModified();} protected slots: virtual void sl_actorModified() { /*Actor* a = qobject_cast(sender()); if (!a) { a = qobject_cast(sender())->owner(); }*/ setHtml(QString("
    %1

    %2") .arg(target->getLabel()).arg(composeRichDoc())); } protected: QVariantMap map; }; // PrompterBaseImpl /** * template realization of Prompter and ActorDocument in one entity * represents creating description, updating description and displaying description facilities * * only classes that inherit ActorDocument can be used as a template argument * provides */ template class PrompterBase : public PrompterBaseImpl { public: PrompterBase(Actor* p = 0, bool listenInputs = true) : PrompterBaseImpl(p), listenInputs(listenInputs) {} virtual ActorDocument* createDescription(Actor* a) { T* doc = new T(a); doc->connect(a, SIGNAL(si_labelChanged()), SLOT(sl_actorModified())); doc->connect(a, SIGNAL(si_modified()), SLOT(sl_actorModified())); if (listenInputs) { foreach(Workflow::Port* input, a->getInputPorts()) { doc->connect(input, SIGNAL(bindingChanged()), SLOT(sl_actorModified())); } } foreach(Workflow::Port* input, a->getOutputPorts()) { doc->connect(input, SIGNAL(bindingChanged()), SLOT(sl_actorModified())); } //} return doc; } protected: bool listenInputs; }; // PrompterBase }//namespace #endif ugene-1.9.8/src/corelibs/U2Lang/src/support/RunSchemaForTask.h0000644000175000017500000000644511651544333022644 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _RUN_SCHEMA_FOR_TASK_H_ #define _RUN_SCHEMA_FOR_TASK_H_ #include #include #include #include #include #include #include namespace U2 { using namespace Workflow; class U2LANG_EXPORT WorkflowRunSchemaForTaskCallback { public: // if true: saves input data to tmpfile and set --in=tmpfile virtual bool saveInput()const = 0; // for saving input data (sequence, msa ...) virtual QList createInputData() const {return QList();} // format of input file to save virtual DocumentFormatId inputFileFormat() const {return QString();} // pairs (alias, value) virtual QVariantMap getSchemaData() const = 0; // if true: save result to temporary file (with out and format parameters) // and load result document after running schema virtual bool saveOutput() const = 0; // will set --format alias virtual DocumentFormatId outputFileFormat() const {return QString();} }; // WorkflowRunSchemaForTaskCallback class U2LANG_EXPORT WorkflowRunSchemaForTask : public DocumentProviderTask { Q_OBJECT public: WorkflowRunSchemaForTask(const QString& schemaName, WorkflowRunSchemaForTaskCallback* callback, const QVariantMap& resultDocHints = QVariantMap()); ~WorkflowRunSchemaForTask(); virtual QList onSubTaskFinished(Task* subTask); virtual ReportResult report(); private: void setSchemaSettings(); void setSchemaSettings(const QVariantMap & data); private: WorkflowRunSchemaForTaskCallback* callback; LoadWorkflowTask* loadSchemaTask; Schema schema; Document* inputDocument; SaveDocumentTask* saveInputTask; QTemporaryFile saveInputTmpFile; QString saveInputTmpFilename; WorkflowRunInProcessTask* runSchemaTask; QTemporaryFile resultTmpFile; QString resultTmpFilename; LoadDocumentTask* loadResultTask; QString schemaName; QVariantMap resultDocHints; }; // WorkflowRunSchemaForTask } // namespace U2 #endif // #ifndef _RUN_SCHEMA_FOR_TASK_H_ ugene-1.9.8/src/corelibs/U2Lang/src/support/RunSchemaForTask.cpp0000644000175000017500000001722111651544333023171 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include #include #include #include #include "RunSchemaForTask.h" namespace U2 { using namespace Workflow; /*************************** * WorkflowRunSchemaForTask ***************************/ static QString SCHEMA_DIR_PATH = QString("%1:schemas_private/").arg(PATH_PREFIX_DATA); static QString findSchemaPath(const QString & schemaName) { foreach(const QString & ext, WorkflowUtils::WD_FILE_EXTENSIONS) { QString candidate = SCHEMA_DIR_PATH + schemaName + "." + ext; if(QFile::exists(candidate)) { return candidate; } } return QString(); } WorkflowRunSchemaForTask::WorkflowRunSchemaForTask(const QString & scName, WorkflowRunSchemaForTaskCallback * c, const QVariantMap& _resultDocHints) : DocumentProviderTask(tr("Run workflow schema for task %1").arg(scName), TaskFlag_NoRun), callback(c), loadSchemaTask(NULL), inputDocument(NULL), saveInputTask(NULL), runSchemaTask(NULL), loadResultTask(NULL), schemaName(scName) { assert(callback != NULL); resultDocHints = _resultDocHints; if (callback->saveInput()) { DocumentFormat * inputDf = AppContext::getDocumentFormatRegistry()->getFormatById(callback->inputFileFormat()); assert(inputDf != NULL); saveInputTmpFile.setFileTemplate(QString("%1/XXXXXX.%2").arg(QDir::tempPath()).arg(inputDf->getSupportedDocumentFileExtensions().first())); if(!saveInputTmpFile.open()) { setError(tr("Cannot create temporary file for writing")); return; } saveInputTmpFilename = saveInputTmpFile.fileName(); saveInputTmpFile.close(); } if (callback->saveOutput()) { DocumentFormat * outputDf = AppContext::getDocumentFormatRegistry()->getFormatById(callback->outputFileFormat()); assert(outputDf != NULL); resultTmpFile.setFileTemplate(QString("%1/XXXXXX.%2").arg(QDir::tempPath()).arg(outputDf->getSupportedDocumentFileExtensions().first())); if(!resultTmpFile.open()) { setError(tr("Cannot create temporary file for reading and writing")); return; } resultTmpFilename = resultTmpFile.fileName(); resultTmpFile.close(); } QString schemaPath = findSchemaPath(schemaName); if (schemaPath.isEmpty()) { assert(false); setError(tr("Internal error: cannot find schema %1").arg(schemaName)); return; } loadSchemaTask = new LoadWorkflowTask(&schema, NULL, schemaPath); addSubTask(loadSchemaTask); } WorkflowRunSchemaForTask::~WorkflowRunSchemaForTask() { delete inputDocument; } static const QString INPUT_FILE_ALIAS("in"); static const QString OUTPUT_FILE_ALIAS("out"); static const QString OUTPUT_FILE_FORMAT_ALIAS("format"); void WorkflowRunSchemaForTask::setSchemaSettings() { QVariantMap data(callback->getSchemaData()); if(callback->saveInput()) { data[INPUT_FILE_ALIAS] = qVariantFromValue(saveInputTmpFilename); } if(callback->saveOutput()) { data[OUTPUT_FILE_ALIAS] = qVariantFromValue(resultTmpFilename); data[OUTPUT_FILE_FORMAT_ALIAS] = qVariantFromValue(callback->outputFileFormat()); } setSchemaSettings(data); } void WorkflowRunSchemaForTask::setSchemaSettings(const QVariantMap & data) { foreach(const QString & key, data.keys()) { QString attrName; Actor * actor = WorkflowUtils::findActorByParamAlias(schema.getProcesses(), key, attrName, false); if(actor == NULL) { assert(false); setError(tr("Internal error: cannot find alias '%1' for schema '%2'").arg(key).arg(schemaName)); return; } Attribute * attr = actor->getParameter(attrName); if(attr == NULL) { assert(false); setError(tr("Internal error: cannot find attribute '%1' for schema '%2'").arg(attrName).arg(schemaName)); } attr->setAttributeValue(data.value(key)); } } QList WorkflowRunSchemaForTask::onSubTaskFinished(Task* subTask) { propagateSubtaskError(); QList res; if(hasError() || isCanceled()) { return res; } enum WhatNext { SAVE_INPUT, RUN_SCHEMA, LOAD_RESULT, NOTHING }; WhatNext what = NOTHING; if(loadSchemaTask == subTask) { if(callback->saveInput()) { what = SAVE_INPUT; } else { assert(callback->inputFileFormat().isEmpty()); assert(callback->createInputData().isEmpty()); what = RUN_SCHEMA; } } else if(saveInputTask == subTask) { what = RUN_SCHEMA; } else if(runSchemaTask == subTask && callback->saveOutput()) { // result saved to temp file: load result from it what = LOAD_RESULT; } switch(what) { case SAVE_INPUT: { assert(inputDocument == NULL); assert(!saveInputTmpFilename.isEmpty()); IOAdapterFactory * iof = AppContext::getIOAdapterRegistry()->getIOAdapterFactoryById(BaseIOAdapters::url2io(saveInputTmpFilename)); assert(iof != NULL); DocumentFormat * df = AppContext::getDocumentFormatRegistry()->getFormatById(callback->inputFileFormat()); assert(df != NULL); ioLog.details(tr("Saving workflow schema input to '%1'").arg(saveInputTmpFilename)); inputDocument = new Document(df, iof, saveInputTmpFilename, callback->createInputData()); saveInputTask = new SaveDocumentTask(inputDocument); res << saveInputTask; } break; case RUN_SCHEMA: { setSchemaSettings(); if(hasError()) { return res; } taskLog.details(tr("Running workflow schema %1 in separate process").arg(schemaName)); runSchemaTask = new WorkflowRunInProcessTask(schema, schema.getIterations()); res << runSchemaTask; } break; case LOAD_RESULT: { IOAdapterFactory * iof = AppContext::getIOAdapterRegistry()->getIOAdapterFactoryById(BaseIOAdapters::url2io(resultTmpFilename)); assert(iof != NULL); ioLog.details(tr("Loading result file '%1'").arg(resultTmpFilename)); loadResultTask = new LoadDocumentTask(callback->outputFileFormat(), resultTmpFilename, iof, resultDocHints); res << loadResultTask; } break; case NOTHING: if (loadResultTask != NULL && loadResultTask->getDocument() != NULL) { Document* doc = loadResultTask->getDocument(); resultDocument = doc->clone(); } break; default: assert(false); } return res; } Task::ReportResult WorkflowRunSchemaForTask::report() { propagateSubtaskError(); return ReportResult_Finished; } } // namespace U2 ugene-1.9.8/src/corelibs/U2Lang/src/support/WorkflowSettings.h0000644000175000017500000000461611651544333023016 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_WORKFLOW_SETTINGS_H_ #define _U2_WORKFLOW_SETTINGS_H_ #include #include #include #include namespace U2 { class Watcher : public QObject { Q_OBJECT signals: void changed(); friend class WorkflowSettings; }; #define SETTINGS QString("workflowview/") class U2LANG_EXPORT WorkflowSettings { public: static bool showGrid(); static void setShowGrid(bool v); static bool snap2Grid(); static void setSnap2Grid(bool v); static bool monitorRun(); static void setMonitorRun(bool v); /*static bool failFast(); static void setFailFast(bool v);*/ static QString defaultStyle(); static void setDefaultStyle(const QString&); static QFont defaultFont(); static void setDefaultFont(const QFont&); static const QString getUserDirectory(); static void setUserDirectory(const QString &dir); static QColor getBGColor(); static void setBGColor(const QColor &color); static int getRunMode(); static void setRunMode(int md); static bool getScriptingMode(); static void setScriptingMode(bool md); static bool runInSeparateProcess(); static void setRunInSeparateProcess(bool m); static bool hasRunInSeparateProcess(); static void setCmdlineUgenePath(const QString & path); static QString getCmdlineUgenePath(); static void setExternalToolDirectory(const QString &newDir); static const QString getExternalToolDirectory(); static Watcher * const watcher; }; }//namespace #endif ugene-1.9.8/src/corelibs/U2Lang/src/support/WorkflowIOTasks.h0000644000175000017500000000411011651544333022520 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_WORKFLOW_IO_TASK_H_ #define _U2_WORKFLOW_IO_TASK_H_ #include #include #include #include class QDomDocument; namespace U2 { using namespace Workflow; class U2LANG_EXPORT LoadWorkflowTask : public Task { Q_OBJECT public: LoadWorkflowTask(Schema* schema, Metadata* meta, const QString& url); virtual void run(); Task::ReportResult report(); Schema* getSchema() const {return schema;} QString getURL() const {return url;} Metadata * getMetadata() {return meta;} QMap getRemapping() {return remap;} enum FileFormat { HR, XML, UNKNOWN }; static FileFormat detectFormat(const QString & rawData); protected: const QString url; Schema* schema; Metadata* meta; QString rawData; FileFormat format; QMap remap; }; // LoadWorkflowTask class U2LANG_EXPORT SaveWorkflowTask : public Task { Q_OBJECT public: SaveWorkflowTask(Schema* schema, const Metadata& meta, bool copyMode); Task::ReportResult report(); virtual void run(); private: QString rawData; QString url; }; // SaveWorkflowTask } //namespace #endif ugene-1.9.8/src/corelibs/U2Lang/src/support/CoreLibConstants.h0000644000175000017500000000361711651544333022677 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_WORKFLOW_CORE_LIB_CONSTANTS_H_ #define _U2_WORKFLOW_CORE_LIB_CONSTANTS_H_ #include #include namespace U2 { namespace Workflow { class U2LANG_EXPORT CoreLibConstants { public: static const QString WRITE_FASTA_PROTO_ID; static const QString READ_TEXT_PROTO_ID; static const QString WRITE_TEXT_PROTO_ID; static const QString WRITE_GENBANK_PROTO_ID; static const QString WRITE_FASTQ_PROTO_ID; static const QString GENERIC_READ_MA_PROTO_ID; static const QString GENERIC_READ_SEQ_PROTO_ID; static const QString WRITE_CLUSTAL_PROTO_ID; static const QString WRITE_STOCKHOLM_PROTO_ID; static const QString WRITE_MSA_PROTO_ID; static const QString WRITE_SEQ_PROTO_ID; static const QString TEXT_TYPESET_ID; static const QString WORKFLOW_ON_CLOUD_TASK_ID; static const QString WORKFLOW_SCHEMA_ATTR; static const QString DATA_IN_ATTR; static const QString DATA_OUT_ATTR; }; // CoreLibConstants } // Workflow } // U2 #endif // _U2_WORKFLOW_CORE_LIB_CONSTANTS_H_ ugene-1.9.8/src/corelibs/U2Lang/src/support/WorkflowIOTasks.cpp0000644000175000017500000000753111651544333023065 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include #include #include #include #include #include #include #include #include #include "WorkflowIOTasks.h" namespace U2 { using namespace Workflow; /************************************ * LoadWorkflowTask ************************************/ LoadWorkflowTask::LoadWorkflowTask(Schema* s, Workflow::Metadata* m, const QString& u): Task(tr("Loading schema"), TaskFlag_None), url(u), schema(s), meta(m) { assert(schema != NULL); } void LoadWorkflowTask::run() { ioLog.details(tr("Loading workflow schema from file: %1").arg(url)); QFile file(url); if (!file.open(QIODevice::ReadOnly)) { stateInfo.setError(L10N::errorOpeningFileRead(url)); return; } QTextStream in(&file); in.setCodec("UTF-8"); rawData = in.readAll(); format = detectFormat(rawData); if(format == UNKNOWN) { setError(tr("Undefined format: plain text or xml expected")); return; } } Task::ReportResult LoadWorkflowTask::report() { if(stateInfo.hasError()) { return ReportResult_Finished; } QString err; if(format == HR) { err = HRSchemaSerializer::string2Schema(rawData, schema, meta, &remap); } else if(format == XML) { setError(tr("Sorry! XML schema format is obsolete and not supported. You can create new schema in GUI mode" " or write it by yourself. Check our documentation for details!")); return ReportResult_Finished; } else { // check in constructor assert(false); } if(!err.isEmpty()) { setError(err); schema->reset(); if(meta) { meta->reset(); } return ReportResult_Finished; } if(meta) { meta->url = url; } return ReportResult_Finished; } LoadWorkflowTask::FileFormat LoadWorkflowTask::detectFormat(const QString & rawData) { if(rawData.trimmed().startsWith(HRSchemaSerializer::HEADER_LINE)) { return HR; } else if(rawData.trimmed().startsWith("")) { return XML; } else { return UNKNOWN; } } /************************************ * SaveWorkflowTask ************************************/ SaveWorkflowTask::SaveWorkflowTask(Schema* schema, const Metadata& meta, bool copyMode) : Task(tr("Save workflow schema task"), TaskFlag_None), url(meta.url) { assert(schema != NULL); rawData = HRSchemaSerializer::schema2String(*schema, &meta, copyMode); } void SaveWorkflowTask::run() { if(hasError() || isCanceled()) { return; } QFile file(url); if(!file.open(QIODevice::WriteOnly)) { setError(L10N::errorOpeningFileWrite(url)); return; } QTextStream out(&file); out.setCodec("UTF-8"); out << rawData; } Task::ReportResult SaveWorkflowTask::report() { return ReportResult_Finished; } }//namespace ugene-1.9.8/src/corelibs/U2Lang/src/support/HRSchemaSerializer.h0000644000175000017500000001661411651544333023150 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_WORKFLOW_HR_SCHEMA_SERIALIZER_H_ #define _U2_WORKFLOW_HR_SCHEMA_SERIALIZER_H_ #include #include #include #include #include #include #include namespace U2 { using namespace Workflow; class ExternalProcessConfig; class DataConfig; class AttributeConfig; class U2LANG_EXPORT HRSchemaSerializer : public QObject { Q_OBJECT public: static const QString BLOCK_START; static const QString BLOCK_END; static const QString SERVICE_SYM; static const QString QUOTE; static const QString NEW_LINE; static const QString UNKNOWN_ERROR; static const QString NO_ERROR; static const QString HEADER_LINE; static const QString OLD_XML_HEADER; static const QString BODY_START; static const QString META_START; static const QString DOT_ITERATION_START; static const QString ITERATION_START; static const QString DATAFLOW_SIGN; static const QString EQUALS_SIGN; static const QString UNDEFINED_CONSTRUCT; static const QString TYPE_ATTR; static const QString SCRIPT_ATTR; static const QString NAME_ATTR; static const QString ELEM_ID_ATTR; static const QString DOT; static const QString DASH; static const QString ITERATION_ID; static const QString ALIASES_START; static const QString ALIASES_HELP_START; static const QString VISUAL_START; static const QString UNDEFINED_META_BLOCK; static const QString TAB; static const QString NO_NAME; static const QString COLON; static const QString SEMICOLON; static const QString INPUT_START; static const QString OUTPUT_START; static const QString ATTRIBUTES_START; static const QString TYPE_PORT; static const QString FORMAT_PORT; static const QString CMDLINE; static const QString DESCRIPTION; static const QString PROMPTER; static const QString FUNCTION_START; static const QString ACTOR_BINDINGS; public: struct U2LANG_EXPORT ReadFailed { ReadFailed(const QString & msg) : what(msg) {} QString what; }; // ReadFailed struct U2LANG_EXPORT Tokenizer { void tokenize(const QString & data); void tokenizeLine(const QString & line, QTextStream & s); void tokenizeBlock(const QString & line, QTextStream & s); void addToken(const QString & t); void appendToken(const QString & t, bool skipEmpty = true); void removeCommentTokens(); void assertToken(const QString & etalon); QString take(); QString look() const; bool notEmpty()const {return !tokens.isEmpty();} enum States { START_WORD }; // States QStringList tokens; int depth; }; // Tokenizer struct U2LANG_EXPORT ParsedPairs { ParsedPairs(Tokenizer & tokenizer); ParsedPairs() {} QMap equalPairs; QMap blockPairs; static QPair parseOneEqual(Tokenizer & tokenizer); }; // ParsedPairs struct U2LANG_EXPORT FlowGraph { FlowGraph( const QList >& d ); bool findPath(Actor * from, Port * to) const; void removeDuplicates(); void minimize(); QMap > graph; QList > dataflowLinks; int findRecursion; }; // FlowGraph typedef QMap NamesMap; static void parseHeader(Tokenizer & tokenizer, Metadata * meta); static void parseBodyHeader(Tokenizer & tokenizer, Metadata * meta, bool needName = true); static Actor* parseElementsDefinition(Tokenizer & tokenizer, const QString & actorName, QMap & actorMap, QMap* idMap = NULL); static void backwardIncapability(); static QPair parseDataflow(Tokenizer & tokenizer, const QString & srcTok, const QMap & actorMap); static QString parseAt(const QString & dottedStr, int ind); static Iteration parseIteration(Tokenizer & tokenizer, const QString & iterationName, const QMap & actorMap, bool pasteMode = false); static void parseActorBindings(Tokenizer &tokenizer, const QMap &actorMap, QList > &links); static void parseAliases(Tokenizer & tokenizer, const QMap & actorMap); static void parseAliasesHelp(Tokenizer & tokenizer, const QList & procs); // if slot has no val-> add it to binding static void addEmptyValsToBindings(const QList & procs); // idMap not null in copy mode static QString string2Schema(const QString & data, Schema * schema, Metadata * meta = NULL, QMap* idMap = NULL); static void addPart( QString & to, const QString & w); static QString header2String(const Metadata * meta); static QString makeBlock(const QString & title, const QString & name, const QString & blockItself, int tabsNum = 1, bool nl = false, bool sc = false); static QString makeEqualsPair(const QString & key, const QString & value, int tabsNum = 2); static QString makeArrowPair( const QString & left, const QString & right, int tabsNum = 1 ); static QString scriptBlock(const QString & scriptText, int tabsNum = 3); static QString elementsDefinition(const QList & procs, const NamesMap & nmap, bool copyMode = false); static QString dataflowDefinition(const QList & procs, const NamesMap & nmap); static QString iterationsDefinition(const QList & iterations, const NamesMap & nmap, bool checkDummyIteration = true); static QString schemaAliases(const QList & procs, const NamesMap& nmap); static QString aliasesHelp(const QList & procs); static NamesMap generateElementNames(const QList& procs); static QString schema2String(const Schema & schema, const Metadata * meta, bool copyMode = false); static ExternalProcessConfig* string2Actor(const QString & bytes); static QString actor2String(ExternalProcessConfig *cfg); static ExternalProcessConfig *parseActorBody(Tokenizer & tokenizer); static void parsePorts(Tokenizer & tokenizer, QList& ports); static void parseAttributes(Tokenizer & tokenizer, QList& attrs); static QMap deepCopy(const Schema& from, Schema* to); }; } // U2 #endif // _U2_WORKFLOW_HR_SCHEMA_SERIALIZER_H_ ugene-1.9.8/src/corelibs/U2Lang/src/support/WorkflowEnvImpl.h0000644000175000017500000000300511651544333022557 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_WORKFLOW_ENVIMPL_H_ #define _U2_WORKFLOW_ENVIMPL_H_ #include namespace U2 { namespace Workflow { /** * Workflow environment container implementation */ class U2LANG_EXPORT WorkflowEnvImpl : public WorkflowEnv { protected: virtual ~WorkflowEnvImpl(); virtual DataTypeRegistry* initDataRegistry(); virtual ActorPrototypeRegistry* initProtoRegistry(); virtual DomainFactoryRegistry* initDomainRegistry(); virtual DataTypeValueFactoryRegistry* initDataTypeValueFactoryRegistry(); virtual ExternalToolCfgRegistry* initExternalToolCfgRegistry(); }; // WorkflowEnvImpl } //namespace Workflow } //namespace U2 #endif ugene-1.9.8/src/corelibs/U2Lang/src/support/WorkflowRunTask.cpp0000644000175000017500000006173711651544333023147 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "WorkflowRunTask.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include namespace U2 { static const QString OUTPUT_PROGRESS_OPTION("ugene-output-progress-state"); static const QString OUTPUT_ERROR_OPTION("ugene-output-error"); static const int UPDATE_PROGRESS_INTERVAL = 500; static const int TICK_UPDATE_INTERVAL = 1000; static const QString OUTPUT_PROGRESS_TAG("task-progress="); static const QString ERROR_KEYWORD("#%*ugene-finished-with-error#%*"); static const QString STATE_KEYWORD("#%&state#%&"); static const QString MSG_NUM_KEYWORD("#%$msgnum#%$"); static const QString MSG_PASSED_KEYWORD("#%$msgpassed#%$"); /******************************************* * WorkflowRunTask *******************************************/ WorkflowRunTask::WorkflowRunTask(const Schema& sh, QList lst, const QMap& remap) : WorkflowAbstractRunner(tr("Execute workflow"), TaskFlags(TaskFlag_NoRun) | TaskFlag_ReportingIsSupported), rmap(remap), flows(sh.getFlows()) { GCOUNTER( cvar, tvar, "WorkflowRunTask" ); assert(!lst.isEmpty()); foreach(const Iteration& it, lst) { WorkflowIterationRunTask* t = new WorkflowIterationRunTask(sh, it); connect(t, SIGNAL(si_ticked()), SIGNAL(si_ticked())); addSubTask(t); } setMaxParallelSubtasks(MAX_PARALLEL_SUBTASKS_AUTO); if(AppContext::getCMDLineRegistry()->hasParameter(OUTPUT_PROGRESS_OPTION)) { QTimer * timer = new QTimer(this); connect(timer, SIGNAL(timeout()), SLOT(sl_outputProgressAndState())); timer->start(UPDATE_PROGRESS_INTERVAL); } } void WorkflowRunTask::sl_outputProgressAndState() { coreLog.info(QString("%1%2").arg(OUTPUT_PROGRESS_TAG).arg(getProgress())); foreach(const ActorId & id, rmap.values()) { QList ret; foreach(Task* t, getSubtasks()) { WorkflowIterationRunTask* rt = qobject_cast(t); ret << rt->getState(id); } if(!rmap.key(id).isEmpty()) { assert(ret.size() == 1); coreLog.info(QString("%1:%2:%3").arg(STATE_KEYWORD).arg(rmap.key(id)).arg((int)ret.first())); } } foreach(Link * l, flows) { ActorId srcId = rmap.key(l->source()->owner()->getId()); ActorId dstId = rmap.key(l->destination()->owner()->getId()); assert(!srcId.isEmpty() && !dstId.isEmpty()); coreLog.info(QString("%1:%2:%3:%4").arg(MSG_NUM_KEYWORD).arg(srcId).arg(dstId).arg(getMsgNum(l))); coreLog.info(QString("%1:%2:%3:%4").arg(MSG_PASSED_KEYWORD).arg(srcId).arg(dstId).arg(getMsgPassed(l))); } } QString WorkflowRunTask::generateReport() const { QString res; res+=""; res+=QString("").arg(tr("Iterations")).arg(tr("Status")).arg(tr("Details")); foreach(Task* sub, getSubtasks()) { QString name = Qt::escape(sub->getTaskName()); QString status = sub->hasError() ? tr("Failed") : sub->isCanceled() ? tr("Canceled") : tr("Finished"); QString error = Qt::escape(sub->getError()).replace("\n", "
    "); //AppContext::getTaskScheduler()->getStateName(sub); if (sub->hasError()) { name = ""+name+""; status = ""+status+""; } else if (sub->isCanceled()) { status = ""+status+""; } else { status = ""+status+""; } res+=QString("").arg(name).arg(status).arg(error); QStringList links = (static_cast(sub))->getFiles(); if(!links.isEmpty() && !sub->hasError()) { res += QString("").arg(tr("Output files:")); foreach(const QString &link, links) { res += QString("").arg(link).arg(link); } } res+=""; } res+="
    %1%2%3
    %1%2%3
    %1
    %2
    "; return res; } QList WorkflowRunTask::getState( Actor* actor) { QList ret; foreach(Task* t, getSubtasks()) { WorkflowIterationRunTask* rt = qobject_cast(t); ret << rt->getState(actor->getId()); } return ret; } int WorkflowRunTask::getMsgNum( Link* l) { int ret = 0; foreach(Task* t, getSubtasks()) { WorkflowIterationRunTask* rt = qobject_cast(t); ret += rt->getMsgNum(l); } return ret; } int WorkflowRunTask::getMsgPassed(Link* l) { int ret = 0; foreach(Task* t, getSubtasks()) { ret += qobject_cast(t)->getMsgPassed(l); } return ret; } Task::ReportResult WorkflowRunTask::report() { propagateSubtaskError(); if(hasError() && AppContext::getCMDLineRegistry()->hasParameter(OUTPUT_ERROR_OPTION)) { coreLog.info(QString("%1%2%1").arg(ERROR_KEYWORD).arg(getError())); } return ReportResult_Finished; } /******************************************* * WorkflowIterationRunTask *******************************************/ WorkflowIterationRunTask::WorkflowIterationRunTask(const Schema& sh, const Iteration& it) : Task(QString("%1").arg(it.name), TaskFlags_NR_FOSCOE), schema(new Schema()), scheduler(NULL) { rmap = HRSchemaSerializer::deepCopy(sh, schema); schema->applyConfiguration(it, rmap); if(schema->getDomain().isEmpty()) { QList factories = WorkflowEnv::getDomainRegistry()->getAllEntries(); assert(!factories.isEmpty()); schema->setDomain(factories.isEmpty() ? "" : factories.at(0)->getId()); } DomainFactory* df = WorkflowEnv::getDomainRegistry()->getById(schema->getDomain()); if (!df) { stateInfo.setError( tr("Unknown domain %1").arg(schema->getDomain()) ); return; } } WorkflowIterationRunTask::~WorkflowIterationRunTask() { lmap.clear(); DomainFactory* df = WorkflowEnv::getDomainRegistry()->getById(schema->getDomain()); if (df) { df->destroy(scheduler, schema); } scheduler = NULL; delete schema; } void WorkflowIterationRunTask::prepare() { if( hasError() || isCanceled() ) { return; } DomainFactory* df = WorkflowEnv::getDomainRegistry()->getById(schema->getDomain()); assert( df != NULL ); // checked in constructor foreach(Actor* a, schema->getProcesses()) { Worker* w = df->createWorker(a); if (!w) { stateInfo.setError( tr("Failed to create worker %1 %2 in domain %3")\ .arg(a->getProto()->getId()).arg(a->getId()).arg(schema->getDomain()) ); return; } } foreach(Link* l, schema->getFlows()) { CommunicationChannel* cc = df->createConnection(l); if (!cc) { stateInfo.setError( tr("Failed to create connection %1 %2 in domain %3") ); //fixme return; } QStringList lst; lst << rmap.key(l->source()->owner()->getId()); lst << (l->source()->getId()); lst << rmap.key(l->destination()->owner()->getId()); lst << (l->destination()->getId()); QString key = lst.join("|"); lmap.insert(key, cc); } scheduler = df->createScheduler(schema); if (!scheduler) { stateInfo.setError( tr("Failed to create scheduler in domain %1").arg(df->getDisplayName()) ); return; } scheduler->init(); while(scheduler->isReady() && !isCanceled()) { Task* t = scheduler->tick(); if (t) { addSubTask(t); break; } } } QList WorkflowIterationRunTask::onSubTaskFinished(Task* subTask) { QList tasks; if (subTask->hasError()) { emit si_ticked(); propagateSubtaskError(); return tasks; } while(scheduler->isReady() && !isCanceled()) { Task* t = scheduler->tick(); if (t) { tasks << t; break; } } emit si_ticked(); return tasks; } DocumentFormat *getDocumentFormatByProtoId(QString protoId) { DocumentFormatId formatId; if (CoreLibConstants::WRITE_TEXT_PROTO_ID == protoId) { formatId = BaseDocumentFormats::PLAIN_TEXT; } else if (CoreLibConstants::WRITE_FASTA_PROTO_ID == protoId) { formatId = BaseDocumentFormats::PLAIN_FASTA; } else if (CoreLibConstants::WRITE_GENBANK_PROTO_ID == protoId) { formatId = BaseDocumentFormats::PLAIN_GENBANK; } else if (CoreLibConstants::WRITE_CLUSTAL_PROTO_ID == protoId) { formatId = BaseDocumentFormats::CLUSTAL_ALN; } else if (CoreLibConstants::WRITE_STOCKHOLM_PROTO_ID == protoId) { formatId = BaseDocumentFormats::STOCKHOLM; } else if (CoreLibConstants::WRITE_FASTQ_PROTO_ID == protoId ) { formatId = BaseDocumentFormats::FASTQ; } else { return NULL; } return AppContext::getDocumentFormatRegistry()->getFormatById(formatId); } static QStringList getOutputFiles(const QList & procs) { QStringList res; foreach(Actor *a, procs) { // commented because of UGENE-537 //Attribute * formatAttr = a->getParameter(BaseAttributes::DOCUMENT_FORMAT_ATTRIBUTE().getId()); foreach(Attribute *attr, a->getProto()->getAttributes()) { if(attr->getId() == BaseAttributes::URL_OUT_ATTRIBUTE().getId()) { QString str = a->getParameter(BaseAttributes::URL_OUT_ATTRIBUTE().getId())->getAttributeValue(); // commented because of UGENE-537 /*DocumentFormat *format = NULL; if (NULL != formatAttr) { QString formatId = formatAttr->getAttributeValue(); format = AppContext::getDocumentFormatRegistry()->getFormatById(formatId); } else { format = getDocumentFormatByProtoId(a->getProto()->getId()); } if (NULL != format) { str = GUrlUtils::ensureFileExt(GUrl(str), format->getSupportedDocumentFileExtensions()).getURLString(); }*/ QUrl url(str); if(url.isValid()) { res << url.toString(); } } } } return res; } Task::ReportResult WorkflowIterationRunTask::report() { if (scheduler) { scheduler->cleanup(); if (!scheduler->isDone()) { if(!hasError() && !isCanceled()) { setError(tr("No workers are ready, while not all workers are done. Schema is broken?")); } } } fileLinks = getOutputFiles(schema->getProcesses()); return ReportResult_Finished; } WorkerState WorkflowIterationRunTask::getState(const ActorId& id) { if (scheduler) { return scheduler->getWorkerState(rmap.value(id)); } return WorkerWaiting; } static QString getKey(Link * l) { QStringList lst; lst << (l->source()->owner()->getId()); lst << (l->source()->getId()); lst << (l->destination()->owner()->getId()); lst << (l->destination()->getId()); return lst.join("|"); } int WorkflowIterationRunTask::getMsgNum( Link* l) { CommunicationChannel* cc = lmap.value(getKey(l)); if (cc) { return cc->hasMessage(); } return 0; } int WorkflowIterationRunTask::getMsgPassed(Link* l) { CommunicationChannel * cc = lmap.value(getKey(l)); if(cc != NULL) { return cc->takenMessages(); } return 0; } QStringList WorkflowIterationRunTask::getFiles() const { return fileLinks; } /******************************************* * WorkflowRunInProcessTask *******************************************/ WorkflowRunInProcessTask::WorkflowRunInProcessTask(const Schema & sc, const QList & its) : WorkflowAbstractRunner(tr("Execute workflow in separate process"), TaskFlags(TaskFlag_NoRun) | TaskFlag_ReportingIsSupported) { GCOUNTER(cvar, tvar, "WorkflowRunInProcessTask"); assert(!its.isEmpty()); foreach(const Iteration& it, its) { WorkflowIterationRunInProcessTask * t = new WorkflowIterationRunInProcessTask(sc, it); addSubTask(t); } setMaxParallelSubtasks(MAX_PARALLEL_SUBTASKS_AUTO); QTimer * timer = new QTimer(this); connect(timer, SIGNAL(timeout()), SIGNAL(si_ticked())); timer->start(TICK_UPDATE_INTERVAL); } Task::ReportResult WorkflowRunInProcessTask::report() { propagateSubtaskError(); return ReportResult_Finished; } QList WorkflowRunInProcessTask::getState(Actor * a) { QList ret; foreach(Task * t, getSubtasks()) { WorkflowIterationRunInProcessTask * it = qobject_cast(t); ret << it->getState(a); } return ret; } int WorkflowRunInProcessTask::getMsgNum(Link * l) { int ret = 0; foreach(Task* t, getSubtasks()) { WorkflowIterationRunInProcessTask* rt = qobject_cast(t); ret += rt->getMsgNum(l); } return ret; } int WorkflowRunInProcessTask::getMsgPassed(Link * l) { int ret = 0; foreach(Task* t, getSubtasks()) { WorkflowIterationRunInProcessTask* rt = qobject_cast(t); ret += rt->getMsgPassed(l); } return ret; } QString WorkflowRunInProcessTask::generateReport() const { QString res; res+=""; res+=QString("").arg(tr("Iterations")).arg(tr("Status")).arg(tr("Details")); foreach(Task* sub, getSubtasks()) { QString name = Qt::escape(sub->getTaskName()); QString status = sub->hasError() ? tr("Failed") : sub->isCanceled() ? tr("Canceled") : tr("Finished"); QString error = Qt::escape(sub->getError()).replace("\n", "
    "); if (sub->hasError()) { name = ""+name+""; status = ""+status+""; } else if (sub->isCanceled()) { status = ""+status+""; } else { status = ""+status+""; } res+=QString("").arg(name).arg(status).arg(error); QStringList links = (qobject_cast(sub))->getFiles(); if(!links.isEmpty() && !sub->hasError()) { res += QString("").arg(tr("Output files:")); foreach(const QString &link, links) { res += QString("").arg(link).arg(link); } } res+=""; } res+="
    %1%2%3
    %1%2%3
    %1
    %2
    "; return res; } /******************************************* * WorkflowIterationRunInProcessTask *******************************************/ WorkflowIterationRunInProcessTask::WorkflowIterationRunInProcessTask(const Schema & sc, const Iteration & it) : Task(QString("Execute iteration '%1'").arg(it.name), TaskFlags_NR_FOSCOE), schema(new Schema()), saveSchemaTask(NULL), monitor(NULL) { tempFile.setFileTemplate(QString("%1/XXXXXX.uwl").arg(QDir::tempPath())); if(!tempFile.open()) { setError(tr("Cannot create temporary file for saving schema!")); return; } Metadata meta; meta.url = tempFile.fileName(); tempFile.close(); rmap = HRSchemaSerializer::deepCopy(sc, schema); schema->applyConfiguration(it, rmap); schema->getIterations().clear(); saveSchemaTask = new SaveWorkflowTask(schema, meta, true); saveSchemaTask->setSubtaskProgressWeight(0); addSubTask(saveSchemaTask); } WorkflowIterationRunInProcessTask::~WorkflowIterationRunInProcessTask() { delete schema; } QList WorkflowIterationRunInProcessTask::onSubTaskFinished(Task* subTask) { QList res; propagateSubtaskError(); if(hasError() || isCanceled()) { return res; } if(saveSchemaTask == subTask) { monitor = new WorkflowRunInProcessMonitorTask(tempFile.fileName()); monitor->setSubtaskProgressWeight(1); res << monitor; } else if(monitor == subTask) { monitor = NULL; } else { assert(false); } return res; } Task::ReportResult WorkflowIterationRunInProcessTask::report() { return ReportResult_Finished; } WorkerState WorkflowIterationRunInProcessTask::getState(Actor* a) { return monitor != NULL ? monitor->getState(rmap.value(a->getId())) : WorkerWaiting; } int WorkflowIterationRunInProcessTask::getMsgNum(Link * l) { if(monitor != NULL) { ActorId srcId = rmap.value(l->source()->owner()->getId()); ActorId dstId = rmap.value(l->destination()->owner()->getId()); assert(!srcId.isEmpty() && !dstId.isEmpty()); return monitor->getMsgNum(QString("%1:%2").arg(srcId).arg(dstId)); } else { return 0; } } int WorkflowIterationRunInProcessTask::getMsgPassed(Link * l) { if(monitor != NULL) { ActorId srcId = rmap.value(l->source()->owner()->getId()); ActorId dstId = rmap.value(l->destination()->owner()->getId()); assert(!srcId.isEmpty() && !dstId.isEmpty()); return monitor->getMsgPassed(QString("%1:%2").arg(srcId).arg(dstId)); } else { return 0; } } QStringList WorkflowIterationRunInProcessTask::getFiles() { return getOutputFiles(schema->getProcesses()); } /*********************************** * WorkflowRunInProcessMonitorTask ***********************************/ WorkflowRunInProcessMonitorTask::WorkflowRunInProcessMonitorTask(const QString & path) : Task(tr("Monitoring execution of workflow schema"), TaskFlag_NoRun), schemaPath(path), proc(new QProcess(this)){ QStringList args; // FIXME: use defined constants! args << QString("--task=%1").arg(schemaPath); args << "--log-no-task-progress"; args << "--log-level-info"; args << QString("--%1").arg(OUTPUT_PROGRESS_OPTION); args << "--lang=en"; args << QString("--%1").arg(OUTPUT_ERROR_OPTION); connect(proc, SIGNAL(error(QProcess::ProcessError)), SLOT(sl_onError(QProcess::ProcessError))); connect(proc, SIGNAL(readyReadStandardOutput()), SLOT(sl_onReadStandardOutput())); QString cmdlineUgenePath(WorkflowSettings::getCmdlineUgenePath()); assert(!cmdlineUgenePath.isEmpty()); QString line = cmdlineUgenePath; foreach(const QString& arg, args ) { line+=" " + arg; } coreLog.details("Starting UGENE workflow in separate process: " + line); proc->start(cmdlineUgenePath, args); bool startedSuccessfully = proc->waitForStarted(); if(!startedSuccessfully) { setError(tr("Cannot start process '%1'").arg(cmdlineUgenePath)); return; } } WorkflowRunInProcessMonitorTask::~WorkflowRunInProcessMonitorTask() { } void WorkflowRunInProcessMonitorTask::sl_onError(QProcess::ProcessError err) { QString msg; switch(err) { case QProcess::FailedToStart: msg = tr("The process '%1' failed to start. Either the invoked program is missing, " "or you may have insufficient permissions to invoke the program").arg(WorkflowSettings::getCmdlineUgenePath()); break; case QProcess::Crashed: msg = tr("The process '%1' crashed some time after starting successfully").arg(WorkflowSettings::getCmdlineUgenePath()); break; case QProcess::WriteError: case QProcess::ReadError: msg = tr("Error occurred while reading from or writing to channel"); break; default: msg = tr("Unknown error occurred"); } setError(msg); } void WorkflowRunInProcessMonitorTask::sl_onReadStandardOutput() { QString data(proc->readAllStandardOutput()); int errInd = data.indexOf(ERROR_KEYWORD); if(errInd >= 0) { int errIndEnd = data.indexOf(ERROR_KEYWORD, errInd + 1); assert(errIndEnd > errInd); if(errIndEnd > errInd) { setError(data.mid(errInd + ERROR_KEYWORD.size(), errIndEnd - errInd - ERROR_KEYWORD.size())); } else { assert(false); setError(data.mid(errInd + ERROR_KEYWORD.size() + 1)); } return; } QStringList words = data.split(QRegExp("\\s+")); int sz = words.size(); for(int i = 0; i < sz; ++i) { QString word = words.at(i); if(word.startsWith(OUTPUT_PROGRESS_TAG)) { QString numStr = words.at(i).mid(OUTPUT_PROGRESS_TAG.size()); bool ok = false; int num = numStr.toInt(&ok); if(ok && num >= 0) { stateInfo.progress = qMin(num, 100); } } else if(word.startsWith(STATE_KEYWORD)) { QStringList stWords = word.split(":"); if(stWords.size() == 3) { bool ok = false; int num = stWords.at(2).toInt(&ok); if(ok && num >= 0) { WorkerState st = (WorkerState)num; states[stWords.at(1)] = st; } } } else if(word.startsWith(MSG_NUM_KEYWORD)) { QStringList msgNumWords = word.split(":"); if(msgNumWords.size() == 4) { bool ok = false; int num = msgNumWords.at(3).toInt(&ok); if(ok && num >= 0) { msgNums[QString("%1:%2").arg(msgNumWords.at(1)).arg(msgNumWords.at(2))] = num; } } } else if(word.startsWith(MSG_PASSED_KEYWORD)) { QStringList msgPassedWords = word.split(":"); if(msgPassedWords.size() == 4) { bool ok = false; int num = msgPassedWords.at(3).toInt(&ok); if(ok && num >= 0) { msgPassed[QString("%1:%2").arg(msgPassedWords.at(1)).arg(msgPassedWords.at(2))] = num; } } } } } Task::ReportResult WorkflowRunInProcessMonitorTask::report() { assert(proc != NULL); if(hasError()) { return ReportResult_Finished; } if(isCanceled()) { proc->kill(); return ReportResult_Finished; } QProcess::ProcessState st = proc->state(); if(st == QProcess::Running) { return ReportResult_CallMeAgain; } return ReportResult_Finished; } WorkerState WorkflowRunInProcessMonitorTask::getState(const ActorId& id) { return states.value(id, WorkerWaiting); } int WorkflowRunInProcessMonitorTask::getMsgNum(const QString & ids) { return msgNums.value(ids, 0); } int WorkflowRunInProcessMonitorTask::getMsgPassed(const QString & ids) { return msgPassed.value(ids, 0); } /************************** * CheckCmdlineUgeneUtils **************************/ static QStringList generateCandidatesWithExt(const QString & path) { QStringList res; res << path; res << path + ".exe"; return res; } static QStringList generateCandidates(const QString & prefix) { QStringList res; res << generateCandidatesWithExt(prefix + "/" + "ugene"); res << generateCandidatesWithExt(prefix + "/" + "ugened"); res << generateCandidatesWithExt(prefix + "/" + "ugenecl"); res << generateCandidatesWithExt(prefix + "/" + "ugenecld"); return res; } static QString getCmdlineUgenePath() { QString executableDir = QCoreApplication::applicationDirPath(); QStringList candidates(generateCandidates(executableDir)); foreach(const QString & candidate, candidates) { if(QFile::exists(candidate)) { return candidate; } } coreLog.info(WorkflowRunTask::tr("Command line UGENE path not found, a possibility to run in separate process will be disabled")); return QString(); } void CheckCmdlineUgeneUtils::setCmdlineUgenePath() { QString path = getCmdlineUgenePath(); WorkflowSettings::setCmdlineUgenePath(path); if(!WorkflowSettings::hasRunInSeparateProcess()) { WorkflowSettings::setRunInSeparateProcess(!path.isEmpty()); } } }//namespace ugene-1.9.8/src/corelibs/U2Lang/src/support/WorkflowSettings.cpp0000644000175000017500000001721411651544333023347 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "WorkflowSettings.h" #include #include #include #include #include #include #include #include #include namespace U2 { #define GRID_STATE SETTINGS + "showGrid" #define SNAP_STATE SETTINGS + "snap2rid" #define LOCK_STATE SETTINGS + "monitorRun" #define FAIL_STATE SETTINGS + "failFast" #define STYLE SETTINGS + "style" #define FONT SETTINGS + "font" #define DIR "workflow_settings/path" #define BG_COLOR SETTINGS + "bgcolor" #define RUN_MODE SETTINGS + "runMode" #define SCRIPT_MODE SETTINGS + "scriptMode" #define RUN_IN_SEPARATE_PROC SETTINGS + "runInSeparateProcess" #define CMDLINE_UGENE_PATH SETTINGS + "cmdlineUgenePath" #define EXTERNAL_TOOL_WORKER_PATH SETTINGS + "externalToolWorkerPath" Watcher* const WorkflowSettings::watcher = new Watcher; bool WorkflowSettings::showGrid() { return AppContext::getSettings()->getValue(GRID_STATE, true).toBool(); } void WorkflowSettings::setShowGrid( bool v ) { if (showGrid() != v) { AppContext::getSettings()->setValue(GRID_STATE, v); emit watcher->changed(); } } bool WorkflowSettings::snap2Grid() { return AppContext::getSettings()->getValue(SNAP_STATE, true).toBool(); } void WorkflowSettings::setSnap2Grid( bool v ) { AppContext::getSettings()->setValue(SNAP_STATE, v); } bool WorkflowSettings::monitorRun() { return AppContext::getSettings()->getValue(LOCK_STATE, true).toBool(); } void WorkflowSettings::setMonitorRun( bool v ) { AppContext::getSettings()->setValue(LOCK_STATE, v); } /*bool WorkflowSettings::failFast() { return AppContext::getSettings()->getValue(FAIL_STATE, true).toBool(); } void WorkflowSettings::setFailFast( bool v ) { AppContext::getSettings()->setValue(FAIL_STATE, v); }*/ QString WorkflowSettings::defaultStyle() { return AppContext::getSettings()->getValue(STYLE, "ext").toString(); } void WorkflowSettings::setDefaultStyle(const QString& s) { AppContext::getSettings()->setValue(STYLE, s); } QFont WorkflowSettings::defaultFont() { return AppContext::getSettings()->getValue(FONT, true).value(); } void WorkflowSettings::setDefaultFont(const QFont& f) { if (defaultFont() != f) { AppContext::getSettings()->setValue(FONT, qVariantFromValue(f)); emit watcher->changed(); } } const QString WorkflowSettings::getUserDirectory() { Settings *s = AppContext::getSettings(); QString defaultPath = QDir::searchPaths( PATH_PREFIX_DATA ).first() + "/workflow_samples/" + "users/"; QString path = s->getValue(DIR, defaultPath).toString(); return path; } void WorkflowSettings::setUserDirectory(const QString &newDir) { Settings *s = AppContext::getSettings(); QString defaultPath = QDir::searchPaths( PATH_PREFIX_DATA ).first() + "/workflow_samples/" + "users/"; QString path = s->getValue(DIR, defaultPath).toString(); AppContext::getSettings()->setValue(DIR, newDir); if(path != newDir) { QDir dir(path); if(!dir.exists()) { return; } dir.setNameFilters(QStringList() << "*.usa"); QFileInfoList fileList = dir.entryInfoList(); foreach(const QFileInfo &fileInfo, fileList) { QString newFileUrl = newDir + fileInfo.fileName(); QFile::copy(fileInfo.filePath(), newFileUrl); } } } const QString WorkflowSettings::getExternalToolDirectory() { Settings *s = AppContext::getSettings(); GUrl url(s->fileName()); QString defaultPath = url.dirPath(); defaultPath += "/ExternalToolConfig/"; QString path = s->getValue(EXTERNAL_TOOL_WORKER_PATH, defaultPath).toString(); return path; } void WorkflowSettings::setExternalToolDirectory(const QString &newDir) { Settings *s = AppContext::getSettings(); GUrl url(s->fileName()); QString defaultPath = url.dirPath(); defaultPath += "/ExternalToolConfig/"; QString path = s->getValue(EXTERNAL_TOOL_WORKER_PATH, defaultPath).toString(); s->setValue(EXTERNAL_TOOL_WORKER_PATH, newDir); if(path != newDir) { QDir dir(path); if(!dir.exists()) { return; } dir.setNameFilters(QStringList() << "*.etc"); QFileInfoList fileList = dir.entryInfoList(); foreach(const QFileInfo &fileInfo, fileList) { QString newFileUrl = newDir + fileInfo.fileName(); QFile::copy(fileInfo.filePath(), newFileUrl); } } } QColor WorkflowSettings::getBGColor() { Settings *s = AppContext::getSettings(); QColor ret(Qt::darkCyan); ret.setAlpha(200); int r,g,b,a; ret.getRgb(&r,&g,&b,&a); QString defaultColor = QString::number(r) + "," + QString::number(g) + "," + QString::number(b) + "," + QString::number(a); QString color = s->getValue(BG_COLOR,defaultColor).toString(); QStringList lst = color.split(","); if(lst.size() != 4) { return ret; } r = lst[0].toInt(); g = lst[1].toInt(); b = lst[2].toInt(); a = lst[3].toInt(); QColor res(r,g,b,a); return res; } void WorkflowSettings::setBGColor(const QColor &color) { int r,g,b,a; color.getRgb(&r,&g,&b,&a); QString newColor = QString::number(r) + "," + QString::number(g) + "," + QString::number(b) + "," + QString::number(a); Settings *s = AppContext::getSettings(); s->setValue(BG_COLOR, newColor); } int WorkflowSettings::getRunMode() { Settings * s = AppContext::getSettings(); int ret = 0; QString runModeStr = s->getValue(RUN_MODE).value(); if( !runModeStr.isEmpty() ) { bool ok = false; int num = runModeStr.toInt(&ok); if(ok && num >= 0) { ret = num; } } return ret; } void WorkflowSettings::setRunMode(int md) { Settings * s = AppContext::getSettings(); s->setValue(RUN_MODE, QString::number(md)); } bool WorkflowSettings::getScriptingMode() { return AppContext::getSettings()->getValue(SCRIPT_MODE, QVariant(false)).value(); } void WorkflowSettings::setScriptingMode(bool md) { AppContext::getSettings()->setValue(SCRIPT_MODE, md); } bool WorkflowSettings::runInSeparateProcess() { return AppContext::getSettings()->getValue(RUN_IN_SEPARATE_PROC, QVariant(false)).value(); } bool WorkflowSettings::hasRunInSeparateProcess() { return AppContext::getSettings()->contains(RUN_IN_SEPARATE_PROC); } void WorkflowSettings::setRunInSeparateProcess(bool m) { return AppContext::getSettings()->setValue(RUN_IN_SEPARATE_PROC, m); } QString WorkflowSettings::getCmdlineUgenePath() { return AppContext::getSettings()->getValue(CMDLINE_UGENE_PATH).value(); } void WorkflowSettings::setCmdlineUgenePath(const QString & path) { AppContext::getSettings()->setValue(CMDLINE_UGENE_PATH, path); } }//namespace ugene-1.9.8/src/corelibs/U2Lang/src/support/WorkflowEnvImpl.cpp0000644000175000017500000000451611651544333023122 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "WorkflowEnvImpl.h" #include "U2Lang/ActorPrototypeRegistry.h" #include #include #include #include #include namespace U2 { namespace Workflow { DataTypeRegistry* WorkflowEnvImpl::initDataRegistry() { qRegisterMetaTypeStreamOperators("QStrStrMap"); qRegisterMetaTypeStreamOperators("CfgMap"); qRegisterMetaTypeStreamOperators("IterationCfg"); DataTypeRegistry * r = new DataTypeRegistry(); return r; } DomainFactoryRegistry* WorkflowEnvImpl::initDomainRegistry() { DomainFactoryRegistry* r = new DomainFactoryRegistry(); return r; } ActorPrototypeRegistry* WorkflowEnvImpl::initProtoRegistry() { ActorPrototypeRegistry* r = new ActorPrototypeRegistry(); return r; } DataTypeValueFactoryRegistry* WorkflowEnvImpl::initDataTypeValueFactoryRegistry() { DataTypeValueFactoryRegistry* ret = new DataTypeValueFactoryRegistry(); ret->registerEntry( new StringTypeValueFactory() ); ret->registerEntry( new BoolTypeValueFactory() ); ret->registerEntry( new NumTypeValueFactory() ); return ret; } WorkflowEnvImpl::~WorkflowEnvImpl() { delete domain; delete proto; delete data; delete dvfReg; } ExternalToolCfgRegistry* WorkflowEnvImpl::initExternalToolCfgRegistry() { ExternalToolCfgRegistry *ecfgReg = new ExternalToolCfgRegistry(); return ecfgReg; } }//namespace Workflow }//namespace U2 ugene-1.9.8/src/corelibs/U2Lang/src/support/MapDatatypeEditor.cpp0000644000175000017500000002716111651544333023376 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "MapDatatypeEditor.h" namespace U2 { using namespace Workflow; /******************************* * MapDatatypeEditor *******************************/ static const int KEY_COLUMN = 0; static const int VALUE_COLUMN = 1; MapDatatypeEditor::MapDatatypeEditor(Configuration* cfg, const QString& prop, DataTypePtr from, DataTypePtr to) : cfg(cfg), propertyName(prop), from(from), to(to), table(NULL) {} QWidget* MapDatatypeEditor::getWidget() { return createGUI(from, to); } QWidget* MapDatatypeEditor::createGUI(DataTypePtr from, DataTypePtr to) { if(!from || !to || !from->isMap() || !to->isMap()) { assert(false); return NULL; } bool infoMode = (to == from); if (infoMode) { table = new QTableWidget(0,1); //table->setHorizontalHeaderLabels((QStringList() << tr("Data on the bus"))); } else { table = new QTableWidget(0,2); //table->setHorizontalHeaderLabels((QStringList() << tr("Accepted inputs") << tr("Data from bus") )); table->setItemDelegateForColumn(VALUE_COLUMN, new DescriptorListEditorDelegate(this)); } table->horizontalHeader()->setResizeMode(QHeaderView::Interactive); table->horizontalHeader()->setStretchLastSection(true); table->verticalHeader()->hide(); table->horizontalHeader()->hide(); QSizePolicy sizePolicy5(QSizePolicy::Expanding, QSizePolicy::Expanding); sizePolicy5.setHorizontalStretch(0); sizePolicy5.setVerticalStretch(2); sizePolicy5.setHeightForWidth(table->sizePolicy().hasHeightForWidth()); table->setSizePolicy(sizePolicy5); table->setBaseSize(QSize(0, 100)); table->setEditTriggers(QAbstractItemView::CurrentChanged|QAbstractItemView::DoubleClicked|QAbstractItemView::EditKeyPressed|QAbstractItemView::SelectedClicked); table->setAlternatingRowColors(true); table->setSelectionMode(QAbstractItemView::SingleSelection); table->setTextElideMode(Qt::ElideMiddle); table->setShowGrid(false); //table->setWordWrap(false); table->setCornerButtonEnabled(false); int height = QFontMetrics(QFont()).height() + 6; const QList& keys = to->getAllDescriptors(); QMap bindingsMap = cfg->getParameter(propertyName)->getAttributeValue(); table->setRowCount(keys.size()); int keysSz = keys.size(); for(int i = 0; i < keysSz; i++) { Descriptor key = keys.at(i); // set key item QTableWidgetItem* keyItem = new QTableWidgetItem(key.getDisplayName()); keyItem->setToolTip(to->getDatatypeByDescriptor(key)->getDisplayName()); keyItem->setData(Qt::UserRole, qVariantFromValue(key)); keyItem->setFlags(Qt::ItemIsSelectable); table->setItem(i, KEY_COLUMN, keyItem); table->setRowHeight(i, height); if (infoMode) { continue; } // set value item DataTypePtr elementDatatype = to->getDatatypeByDescriptor(key); QList candidates = WorkflowUtils::findMatchingCandidates(from, to, key); Descriptor current = WorkflowUtils::getCurrentMatchingDescriptor(candidates, to, key, bindingsMap); QTableWidgetItem* valueItem = new QTableWidgetItem(current.getDisplayName()); valueItem->setData(Qt::UserRole, qVariantFromValue(current)); valueItem->setData(Qt::UserRole+1, qVariantFromValue >(candidates)); if (elementDatatype->isList()) { valueItem->setData(Qt::UserRole+2, true); } table->setItem(i, VALUE_COLUMN, valueItem); } QWidget* widget = new QWidget(); QSizePolicy sizePolicy1(QSizePolicy::Ignored, QSizePolicy::Preferred); sizePolicy1.setHorizontalStretch(0); sizePolicy1.setVerticalStretch(0); sizePolicy1.setHeightForWidth(widget->sizePolicy().hasHeightForWidth()); widget->setSizePolicy(sizePolicy1); QVBoxLayout* verticalLayout = new QVBoxLayout(widget); verticalLayout->setSpacing(0); verticalLayout->setMargin(0); verticalLayout->addWidget(table); //verticalLayout->addWidget(doc = new QTextEdit(widget)); //doc->setEnabled(false); connect(table, SIGNAL(itemSelectionChanged()), SLOT(sl_showDoc())); return widget; } int MapDatatypeEditor::getOptimalHeight() { if(table) { return table->rowHeight(0) * (table->model()->rowCount() + 1); } else { return 0; } } static QString formatDoc(const Descriptor& s, const Descriptor& d) { return U2::MapDatatypeEditor::tr("The input slot %1
    is bound to
    the bus slot %2") .arg(s.getDisplayName()) .arg(d.getDisplayName()); } void MapDatatypeEditor::sl_showDoc() { QList list = table->selectedItems(); QString text = ""; if (list.size() == 1) { if (isInfoMode()) { //doc->setText(DesignerUtils::getRichDoc(list.at(0)->data(Qt::UserRole).value())); text = WorkflowUtils::getRichDoc(list.at(0)->data(Qt::UserRole).value()); } else { int row = list.at(0)->row(); Descriptor d = table->item(row, KEY_COLUMN)->data(Qt::UserRole).value(); Descriptor s = table->item(row, VALUE_COLUMN)->data(Qt::UserRole).value(); //doc->setText(formatDoc(d, s)); text = formatDoc(d, s); } } else { //doc->setText(""); } emit si_showDoc(text); } void MapDatatypeEditor::commit() { QMap map; if (table && !isInfoMode()) { for (int i = 0; i < table->rowCount(); i++) { QString key = table->item(i, KEY_COLUMN)->data(Qt::UserRole).value().getId(); QString val = table->item(i, VALUE_COLUMN)->data(Qt::UserRole).value().getId(); map[key] = val; } } cfg->setParameter(propertyName, qVariantFromValue(map)); sl_showDoc(); } /******************************* * BusPortEditor *******************************/ BusPortEditor::BusPortEditor(IntegralBusPort* p) : MapDatatypeEditor(p, IntegralBusPort::BUS_MAP_ATTR_ID, DataTypePtr(), DataTypePtr()), port(p) { to = WorkflowUtils::getToDatatypeForBusport(p); from = WorkflowUtils::getFromDatatypeForBusport(p, to); } QWidget* BusPortEditor::createGUI(DataTypePtr from, DataTypePtr to) { QWidget* w = MapDatatypeEditor::createGUI(from, to); if (table && port->getWidth() == 0) { /*if (port->isInput()) { table->setHorizontalHeaderLabels((QStringList() << U2::MapDatatypeEditor::tr("Accepted inputs"))); } else { table->setHorizontalHeaderLabels((QStringList() << U2::MapDatatypeEditor::tr("Provided outputs"))); }*/ } else if (table) { connect(table->model(), SIGNAL(dataChanged(const QModelIndex&, const QModelIndex&)), this, SLOT(handleDataChanged(const QModelIndex&, const QModelIndex&))); } return w; } void BusPortEditor::handleDataChanged(const QModelIndex & topLeft, const QModelIndex & bottomRight) { Q_UNUSED(topLeft); Q_UNUSED(bottomRight); commit(); } /******************************* * DescriptorListEditorDelegate *******************************/ QWidget *DescriptorListEditorDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem &/* option */, const QModelIndex &/* index */) const { QComboBox* editor = new QComboBox(parent); editor->setSizeAdjustPolicy(QComboBox::AdjustToContentsOnFirstShow); return editor; } void DescriptorListEditorDelegate::setEditorData(QWidget *editor, const QModelIndex &index) const { QString current = index.model()->data(index, Qt::UserRole).value().getId(); QList list = index.model()->data(index, Qt::UserRole+1).value >(); QComboBox *combo = static_cast(editor); if (index.model()->data(index, Qt::UserRole+2).toBool()) { QStringList curList = current.split(";"); QStandardItemModel* cm = new QStandardItemModel(list.size(), 1, combo); for (int i = 0; i < list.size(); ++i) { Descriptor d = list[i]; QStandardItem* item = new QStandardItem(d.getDisplayName()); item->setCheckable(true); item->setEditable(false); item->setSelectable(false); item->setCheckState(curList.contains(d.getId())? Qt::Checked: Qt::Unchecked); item->setData(qVariantFromValue(d)); cm->setItem(i, item); } combo->setModel(cm); QListView* vw = new QListView(combo); vw->setModel(cm); combo->setView(vw); //vw->setEditTriggers(QAbstractItemView::AllEditTriggers); } else { combo->clear(); int currentIdx = 0; for (int i = 0; i < list.size(); ++i) { combo->addItem(list[i].getDisplayName(), qVariantFromValue(list[i])); if (list[i] == current) { currentIdx = i; } } combo->setCurrentIndex(currentIdx); } } void DescriptorListEditorDelegate::setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const { QComboBox *combo = static_cast(editor); QVariant value; if (index.model()->data(index, Qt::UserRole+2).toBool()) { QStandardItemModel* cm = qobject_cast(combo->model()); Descriptor res; QStringList ids; for(int i = 0; i< cm->rowCount();++i){ if (cm->item(i)->checkState() == Qt::Checked) { res = cm->item(i)->data().value(); ids << res.getId(); } } if (ids.isEmpty()) { value = qVariantFromValue(Descriptor("", tr(""), tr("Default value"))); } else if (ids.size() == 1) { value = qVariantFromValue(res); } else { value = qVariantFromValue(Descriptor(ids.join(";"), tr(""), tr("List of values"))); } } else { value = combo->itemData(combo->currentIndex()); } model->setData(index, value, Qt::UserRole); model->setData(index, value.value().getDisplayName(), Qt::DisplayRole); } }//namespace U2 ugene-1.9.8/src/corelibs/U2Lang/src/support/WorkflowUtils.cpp0000644000175000017500000004350111651544333022645 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "WorkflowUtils.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include namespace U2 { /***************************** * WorkflowUtils *****************************/ const QStringList WorkflowUtils::WD_FILE_EXTENSIONS = initExtensions(); const QString WorkflowUtils::WD_XML_FORMAT_EXTENSION("uws"); QStringList WorkflowUtils::initExtensions() { QStringList exts; exts << "uwl"; return exts; } QString WorkflowUtils::getRichDoc(const Descriptor& d) { if(d.getDisplayName().isEmpty()) { if( d.getDocumentation().isEmpty() ) { return QString(); } else { return QString("%1").arg(d.getDocumentation()); } } else { if( d.getDocumentation().isEmpty() ) { return QString("%1").arg(d.getDisplayName()); } else { return QString("%1 : %2").arg(d.getDisplayName()).arg(d.getDocumentation()); } } } QString WorkflowUtils::getDropUrl(QList& fs, const QMimeData* md) { QString url; const GObjectMimeData* gomd = qobject_cast(md); const DocumentMimeData* domd = qobject_cast(md); if (gomd) { GObject* obj = gomd->objPtr.data(); if (obj) { fs << obj->getDocument()->getDocumentFormat(); url = obj->getDocument()->getURLString(); } } else if (domd) { Document* doc = domd->objPtr.data(); if (doc) { fs << doc->getDocumentFormat(); url = doc->getURLString(); } } else if (md->hasUrls()) { QList urls = md->urls(); if (urls.size() == 1) { url = urls.first().toLocalFile(); QList formats = DocumentUtils::detectFormat(url); foreach(const FormatDetectionResult& di, formats) { fs << di.format; } } } return url; } void WorkflowUtils::setQObjectProperties(QObject &o , const QVariantMap & params) { QMapIterator i(params); while (i.hasNext()) { i.next(); //log.debug("set param " + i.key() + "="+i.value().toString()); o.setProperty(i.key().toAscii(), i.value()); } } QStringList WorkflowUtils::expandToUrls(const QString& s) { QStringList urls = s.split(";"); QStringList result; QRegExp wcard("[*?\\[\\]]"); foreach(QString url, urls) { int idx = url.indexOf(wcard); if (idx >= 0) { int dirIdx = url.lastIndexOf('/', idx); QDir dir; if (dirIdx >= 0) { dir = QDir(url.left(dirIdx)); url = url.right(url.length() - dirIdx - 1); } foreach(QFileInfo fi, dir.entryInfoList((QStringList() << url), QDir::Files|QDir::NoSymLinks)) { result << fi.absoluteFilePath(); } } else { //if (QFile::exists(url)) { result << url; } } } return result; } bool WorkflowUtils::validate(const Schema& schema, QList* infoList) { bool good = true; foreach (Actor* a, schema.getProcesses()) { foreach(Port* p, a->getPorts()) { QStringList l; bool ag = p->validate(l); good &= ag; if (infoList && !l.isEmpty()) { foreach(QString s, l) { QListWidgetItem* item = new QListWidgetItem(a->getProto()->getIcon(), QString("%1 : %2").arg(a->getLabel()).arg(s)); item->setData(PORT_REF, p->getId()); item->setData(ACTOR_REF, a->getId()); infoList->append(item); } } } } foreach (const Iteration& it, schema.getIterations()) { Schema sh; QMap map = HRSchemaSerializer::deepCopy(schema, &sh); sh.applyConfiguration(it, map); foreach (Actor* a, sh.getProcesses()) { QStringList l; bool ag = a->validate(l); good &= ag; if (infoList && !l.isEmpty()) { foreach(QString s, l) { QListWidgetItem* item = new QListWidgetItem(a->getProto()->getIcon(), tr("Iteration '%3', %1 : %2").arg(a->getLabel()).arg(s).arg(it.name)); item->setData(ACTOR_REF, map.key(a->getId())); item->setData(ITERATION_REF, it.id); infoList->append(item); } } } } return good; } bool WorkflowUtils::validate(const Schema& schema, QList >* infoList) { bool good = true; foreach (Actor* a, schema.getProcesses()) { foreach(Port* p, a->getPorts()) { QStringList l; bool ag = p->validate(l); good &= ag; if (infoList && !l.isEmpty()) { foreach(QString s, l) { QMap item; item[TEXT_REF] = QString("%1 : %2").arg(a->getLabel()).arg(s); item[PORT_REF] = p->getId(); item[ACTOR_REF] = a->getId(); infoList->append(item); } } } } foreach (const Iteration& it, schema.getIterations()) { Schema sh; QMap map = HRSchemaSerializer::deepCopy(schema, &sh); sh.applyConfiguration(it, map); foreach (Actor* a, sh.getProcesses()) { QStringList l; bool ag = a->validate(l); good &= ag; if (infoList && !l.isEmpty()) { foreach(QString s, l) { QMap item; item[TEXT_REF] = tr("Iteration '%3', %1 : %2").arg(a->getLabel()).arg(s).arg(it.name); item[ACTOR_REF] = map.key(a->getId()); item[ITERATION_REF] = it.id; infoList->append(item); } } } } return good; } // used in cmdline schema validating bool WorkflowUtils::validate( const Workflow::Schema& schema, QStringList & errs ) { bool good = true; foreach (Actor* a, schema.getProcesses()) { foreach(Port* p, a->getPorts()) { QStringList l; good &= p->validate(l); foreach(const QString & s, l) { errs.append(QString("%1 : %2").arg(a->getLabel()).arg(s)); } } } foreach (const Iteration& it, schema.getIterations()) { Schema sh; QMap map = HRSchemaSerializer::deepCopy(schema, &sh); sh.applyConfiguration(it, map); foreach (Actor* a, sh.getProcesses()) { foreach( Attribute * attr, a->getParameters() ) { assert(attr != NULL); if( attr->isRequiredAttribute() && (attr->isEmpty() || attr->isEmptyString()) ) { good = false; errs.append(tr("%2: Required parameter is not set: %1 (use --%3 option)"). arg(attr->getDisplayName()).arg(a->getLabel()).arg(a->getParamAliases().value(attr->getId()))); } } ConfigurationValidator * baseValidator = a->getValidator(); ScreenedParamValidator * screenedParamValidator = dynamic_cast(baseValidator); if(screenedParamValidator != NULL) { QString err = screenedParamValidator->validate(a); if( !err.isEmpty() ) { good = false; errs.append( QString("%3: %1 (use --%2 option)").arg(err).arg( a->getParamAliases().value(a->getParameter(screenedParamValidator->getId())->getId())).arg(a->getLabel())); } } else if( baseValidator != NULL ) { QStringList l; good &= baseValidator->validate(a, l); foreach(const QString & s, l) { errs.append(QString("%1: %2").arg(a->getLabel()).arg(s)); } } } } return good; } QList WorkflowUtils::findMatchingTypes(DataTypePtr set, DataTypePtr elementDataType) { QList result; foreach(const Descriptor& d, set->getAllDescriptors()) { if (set->getDatatypeByDescriptor(d) == elementDataType) { result.append(d); } } return result; } QStringList WorkflowUtils::findMatchingTypesAsStringList(DataTypePtr set, DataTypePtr elementDatatype) { QList descList = findMatchingTypes(set, elementDatatype); QStringList res; foreach( const Descriptor & desc, descList ) { res << desc.getId(); } return res; } const Descriptor EMPTY_VALUES_DESC("", WorkflowUtils::tr(""), WorkflowUtils::tr("Default value")); QList WorkflowUtils::findMatchingCandidates(DataTypePtr from, DataTypePtr elementDatatype) { QList candidates = findMatchingTypes(from, elementDatatype); if (elementDatatype->isList()) { candidates += findMatchingTypes(from, elementDatatype->getDatatypeByDescriptor()); } else { candidates.append(EMPTY_VALUES_DESC); } return candidates; } QList WorkflowUtils::findMatchingCandidates(DataTypePtr from, DataTypePtr to, const Descriptor & key) { return findMatchingCandidates(from, to->getDatatypeByDescriptor(key)); } Descriptor WorkflowUtils::getCurrentMatchingDescriptor(const QList & candidates, DataTypePtr to, const Descriptor & key, const QStrStrMap & bindings) { DataTypePtr elementDatatype = to->getDatatypeByDescriptor(key); if (elementDatatype->isList()) { QString currentVal = bindings.value(key.getId()); if (!currentVal.isEmpty()) { return Descriptor(currentVal, tr(""), tr("List of values")); } else { return EMPTY_VALUES_DESC; } } else { int idx = bindings.contains(key.getId()) ? candidates.indexOf(bindings.value(key.getId())) : 0; return idx >= 0 ? candidates.at(idx) : candidates.first(); } } DataTypePtr WorkflowUtils::getToDatatypeForBusport(IntegralBusPort * p) { assert(p != NULL); DataTypePtr to; DataTypePtr t = to = p->getType(); if (!t->isMap()) { QMap map; map.insert(*p, t); to = new MapDataType(Descriptor(), map); //IntegralBusType* bt = new IntegralBusType(Descriptor(), QMap()); //bt->addOutput(t, p); } return to; } DataTypePtr WorkflowUtils::getFromDatatypeForBusport(IntegralBusPort * p, DataTypePtr to) { assert(p != NULL); DataTypePtr from; if (p->isOutput() || p->getWidth() == 0) { //nothing to edit, go info mode from = to; } else { //port is input and has links, go editing mode IntegralBusType* bt = new IntegralBusType(Descriptor(), QMap()); bt->addInputs(p); from = bt; } return from; } QString WorkflowUtils::findPathToSchemaFile(const QString & name) { // full path given if( QFile::exists( name ) ) { return name; } // search schema in data dir QString filenameWithDataPrefix = QString( PATH_PREFIX_DATA ) + ":" + "cmdline/" + name; if( QFile::exists( filenameWithDataPrefix ) ) { return filenameWithDataPrefix; } foreach(const QString & ext, WorkflowUtils::WD_FILE_EXTENSIONS) { QString filenameWithDataPrefixAndExt = QString( PATH_PREFIX_DATA ) + ":" + "cmdline/" + name + "." + ext; if( QFile::exists( filenameWithDataPrefixAndExt ) ) { return filenameWithDataPrefixAndExt; } } // if no such file found -> search name in settings. user saved schemas Settings * settings = AppContext::getSettings(); assert( settings != NULL ); // FIXME: same as WorkflowSceneIOTasks::SCHEMA_PATHS_SETTINGS_TAG QVariantMap pathsMap = settings->getValue( "workflow_settings/schema_paths" ).toMap(); QString path = pathsMap.value( name ).toString(); if( QFile::exists( path ) ) { return path; } return QString(); } void WorkflowUtils::getLinkedActorsId(Actor *a, QList &linkedActors) { if(!linkedActors.contains(a->getId())) { linkedActors.append( a->getId() ); foreach(Port *p, a->getPorts()) { foreach(Port *pp, p->getLinks().keys()) { getLinkedActorsId(pp->owner(), linkedActors); } } } else { return; } } Descriptor WorkflowUtils::getSlotDescOfDatatype(const DataTypePtr & dt) { QString dtId = dt->getId(); if(dtId == BaseTypes::DNA_SEQUENCE_TYPE()->getId()) { return BaseSlots::DNA_SEQUENCE_SLOT(); } if(dtId == BaseTypes::ANNOTATION_TABLE_TYPE()->getId()) { return BaseSlots::ANNOTATION_TABLE_SLOT(); } if(dtId == BaseTypes::MULTIPLE_ALIGNMENT_TYPE()->getId()) { return BaseSlots::MULTIPLE_ALIGNMENT_SLOT(); } if(dtId == BaseTypes::STRING_TYPE()->getId()) { return BaseSlots::TEXT_SLOT(); } assert(false); return *dt; } static QStringList initLowerToUpperList() { QStringList res; res << "true"; res << "false"; return res; } static const QStringList lowerToUpperList = initLowerToUpperList(); QString WorkflowUtils::getStringForParameterDisplayRole(const QVariant & value) { QString str = value.toString(); if(lowerToUpperList.contains(str)) { return str.at(0).toUpper() + str.mid(1); } return str; } Actor * WorkflowUtils::findActorByParamAlias(const QList & procs, const QString & alias, QString & attrName, bool writeLog) { QList actors; foreach(Actor * actor, procs) { assert( actor != NULL ); if(actor->getParamAliases().values().contains(alias)) { actors << actor; } } if (actors.isEmpty()) { return NULL; } else if( actors.size() > 1 ) { if(writeLog) { coreLog.error(WorkflowUtils::tr("%1 actors in schema have '%2' alias").arg(actors.size()).arg(alias)); } } Actor * ret = actors.first(); attrName = ret->getParamAliases().key( alias ); return ret; } /***************************** * PrompterBaseImpl *****************************/ QVariant PrompterBaseImpl::getParameter(const QString& id) { if (map.contains(id)) { return map.value(id); } else { return target->getParameter(id)->getAttributePureValue(); } } QString PrompterBaseImpl::getURL(const QString& id, bool * empty ) { QString url = getParameter(id).toString(); if( empty != NULL ) { *empty = false; } if( !target->getParameter(id)->getAttributeScript().isEmpty() ) { url = "got from user script"; } else if (url.isEmpty()) { url = ""+tr("unset")+""; if( empty != NULL ) { *empty = true; } } else if (url.indexOf(";") != -1) { url = tr("the list of files"); } else { url = QFileInfo(url).fileName(); } return url; } QString PrompterBaseImpl::getRequiredParam(const QString& id) { QString url = getParameter(id).toString(); if (url.isEmpty()) { url = ""+tr("unset")+""; } return url; } QString PrompterBaseImpl::getScreenedURL(IntegralBusPort* input, const QString& id, const QString& slot) { bool empty = false; QString attrUrl = QString("%1").arg(getURL(id, &empty)); if( !empty ) { return attrUrl; } Actor * origin = input->getProducer( slot ); QString slotUrl; if( origin != NULL ) { slotUrl = tr("file(s) alongside of input sources of %1").arg(origin->getLabel()); return slotUrl; } assert( !attrUrl.isEmpty() ); return attrUrl; } QString PrompterBaseImpl::getProducers( const QString& port, const QString& slot ) { IntegralBusPort* input = qobject_cast(target->getPort(port)); QList producers = input->getProducers(slot); QStringList labels; foreach(Actor* a, producers) { labels << a->getLabel(); } return labels.join(", "); } QString PrompterBaseImpl::getHyperlink(const QString& id, const QString& val) { return QString("%2").arg(id).arg(val); } QString PrompterBaseImpl::getHyperlink(const QString& id, int val) { return getHyperlink(id, QString::number(val)); } QString PrompterBaseImpl::getHyperlink(const QString& id, qreal val) { return getHyperlink(id, QString::number(val)); } }//namespace ugene-1.9.8/src/corelibs/U2Lang/src/support/WorkflowRunTask.h0000644000175000017500000001132211651544333022575 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_FLOWTASK_H_ #define _U2_FLOWTASK_H_ #include #include #include #include #include #include #include #include #include #include namespace U2 { namespace Workflow { class CommunicationChannel; } using namespace Workflow; class U2LANG_EXPORT WorkflowAbstractRunner : public Task { Q_OBJECT public: WorkflowAbstractRunner(const QString& n, TaskFlags f) : Task(n, f) {} virtual QList getState(Actor*) = 0; virtual int getMsgNum(Link*) = 0; virtual int getMsgPassed(Link*) = 0; }; // WorkflowAbstractRunner typedef QMap ActorMap; class U2LANG_EXPORT WorkflowRunTask : public WorkflowAbstractRunner { Q_OBJECT public: WorkflowRunTask(const Schema&, QList, const ActorMap& rmap = ActorMap()); virtual QString generateReport() const; virtual ReportResult report(); virtual QList getState(Actor*); virtual int getMsgNum(Link*); virtual int getMsgPassed(Link*); signals: void si_ticked(); private slots: void sl_outputProgressAndState(); private: QMap rmap; QList flows; }; // WorkflowRunTask class WorkflowIterationRunTask : public Task { Q_OBJECT public: WorkflowIterationRunTask(const Schema&, const Iteration&); ~WorkflowIterationRunTask(); virtual void prepare(); virtual ReportResult report(); signals: void si_ticked(); public: WorkerState getState(const ActorId& id); int getMsgNum(Link*); int getMsgPassed(Link*); QStringList getFiles() const; protected: virtual QList onSubTaskFinished(Task* subTask); private: Schema* schema; Scheduler* scheduler; QMap rmap; QMap lmap; QStringList fileLinks; }; class U2LANG_EXPORT WorkflowRunInProcessTask : public WorkflowAbstractRunner { Q_OBJECT public: WorkflowRunInProcessTask(const Schema & sc, const QList & its); virtual QString generateReport() const; virtual ReportResult report(); virtual QList getState(Actor*); virtual int getMsgNum(Link*); virtual int getMsgPassed(Link*); signals: void si_ticked(); }; // WorkflowRunInProcessTask class WorkflowRunInProcessMonitorTask; class WorkflowIterationRunInProcessTask : public Task { Q_OBJECT public: WorkflowIterationRunInProcessTask(const Schema & sc, const Iteration & it); ~WorkflowIterationRunInProcessTask(); virtual ReportResult report(); virtual QList onSubTaskFinished(Task* subTask); WorkerState getState(Actor*); int getMsgNum(Link * l); int getMsgPassed(Link * l); QStringList getFiles(); private: Schema* schema; QTemporaryFile tempFile; SaveWorkflowTask * saveSchemaTask; WorkflowRunInProcessMonitorTask * monitor; QMap rmap; }; // WorkflowIterationRunInProcessTask class WorkflowRunInProcessMonitorTask : public Task { Q_OBJECT public: WorkflowRunInProcessMonitorTask(const QString & schemaPath); ~WorkflowRunInProcessMonitorTask(); virtual ReportResult report(); WorkerState getState(const ActorId & id); int getMsgNum(const QString & ids); int getMsgPassed(const QString & ids); private slots: void sl_onError(QProcess::ProcessError); void sl_onReadStandardOutput(); private: QString schemaPath; QProcess * proc; QMap states; QMap msgNums; QMap msgPassed; }; // WorkflowRunInProcessMonitorTask class U2LANG_EXPORT CheckCmdlineUgeneUtils { public: static void setCmdlineUgenePath(); }; // CheckCmdlineUgeneTask } //namespace #endif ugene-1.9.8/src/corelibs/U2Lang/src/support/MapDatatypeEditor.h0000644000175000017500000000624111651544333023037 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_WORKFLOW_MAP_EDITOR_H_ #define _U2_WORKFLOW_MAP_EDITOR_H_ #include #include class QTableWidget; class QTextEdit; namespace U2 { /** * base class for controllers of map datatype attribute editors of configuration * this is base class for port data editors * * from - type came from integral bus * to type of port * prop - busmap property name */ class U2LANG_EXPORT MapDatatypeEditor : public QObject, public ConfigurationEditor { Q_OBJECT public: MapDatatypeEditor(Configuration* cfg, const QString& prop, DataTypePtr from, DataTypePtr to); virtual ~MapDatatypeEditor() {} virtual QWidget* getWidget(); virtual void commit(); int getOptimalHeight(); private slots: void sl_showDoc(); signals: void si_showDoc(const QString&); protected: bool isInfoMode() const {return from == to;} virtual QWidget* createGUI(DataTypePtr from, DataTypePtr to); protected: Configuration* cfg; const QString propertyName; DataTypePtr from, to; QTableWidget* table; QTextEdit* doc; }; // MapDatatypeEditor namespace Workflow { class IntegralBusPort;} /** * IntegralBusPort realization of MapDatatypeEditor */ class U2LANG_EXPORT BusPortEditor : public MapDatatypeEditor { Q_OBJECT public: BusPortEditor(Workflow::IntegralBusPort* p); virtual ~BusPortEditor() {} protected: virtual QWidget* createGUI(DataTypePtr from, DataTypePtr to); Workflow::IntegralBusPort* port; private slots: void handleDataChanged(const QModelIndex & topLeft, const QModelIndex & bottomRight); }; // BusPortEditor class U2LANG_EXPORT DescriptorListEditorDelegate : public QItemDelegate { Q_OBJECT public: DescriptorListEditorDelegate(QObject *parent = 0) : QItemDelegate(parent) {} virtual ~DescriptorListEditorDelegate() {} virtual QWidget *createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const; virtual void setEditorData(QWidget *editor, const QModelIndex &index) const; virtual void setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const; //void updateEditorGeometry(QWidget *editor, // const QStyleOptionViewItem &option, const QModelIndex &index) const; }; // DescriptorListEditorDelegate }//namespace U2 #endif ugene-1.9.8/src/corelibs/U2Lang/src/support/HRSchemaSerializer.cpp0000644000175000017500000014523011651544333023500 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include #include #include #include #include #include #include #include #include #include #include #include #include "HRSchemaSerializer.h" namespace U2 { const QString HRSchemaSerializer::BLOCK_START = "{"; const QString HRSchemaSerializer::BLOCK_END = "}"; const QString HRSchemaSerializer::SERVICE_SYM = "#"; const QString HRSchemaSerializer::QUOTE = "\""; const QString HRSchemaSerializer::NEW_LINE = "\n"; const QString HRSchemaSerializer::UNKNOWN_ERROR = HRSchemaSerializer::tr("Error: unknown exception caught"); const QString HRSchemaSerializer::NO_ERROR = ""; const QString HRSchemaSerializer::HEADER_LINE = "#!UGENE_WORKFLOW"; const QString HRSchemaSerializer::OLD_XML_HEADER = ""; const QString HRSchemaSerializer::BODY_START = "workflow"; const QString HRSchemaSerializer::META_START = ".meta"; const QString HRSchemaSerializer::DOT_ITERATION_START = ".iteration"; const QString HRSchemaSerializer::ITERATION_START = "iteration"; const QString HRSchemaSerializer::DATAFLOW_SIGN = "->"; const QString HRSchemaSerializer::EQUALS_SIGN = ":"; const QString HRSchemaSerializer::UNDEFINED_CONSTRUCT = HRSchemaSerializer::tr("Undefined construct at '%1 %2'"); const QString HRSchemaSerializer::TYPE_ATTR = "type"; const QString HRSchemaSerializer::SCRIPT_ATTR = "script"; const QString HRSchemaSerializer::NAME_ATTR = "name"; const QString HRSchemaSerializer::ELEM_ID_ATTR = "elem-id"; const QString HRSchemaSerializer::DOT = "."; const QString HRSchemaSerializer::DASH = "-"; const QString HRSchemaSerializer::ITERATION_ID = "id"; const QString HRSchemaSerializer::ALIASES_START = "aliases"; const QString HRSchemaSerializer::ALIASES_HELP_START = "help"; const QString HRSchemaSerializer::VISUAL_START = "visual"; const QString HRSchemaSerializer::UNDEFINED_META_BLOCK = HRSchemaSerializer::tr("Undefined block in .meta: '%1'"); const QString HRSchemaSerializer::TAB = " "; const QString HRSchemaSerializer::NO_NAME = ""; const QString HRSchemaSerializer::COLON = ":"; const QString HRSchemaSerializer::SEMICOLON = ";"; const QString HRSchemaSerializer::INPUT_START = ".inputs"; const QString HRSchemaSerializer::OUTPUT_START = ".outputs"; const QString HRSchemaSerializer::ATTRIBUTES_START = ".attributes"; const QString HRSchemaSerializer::TYPE_PORT = "type"; const QString HRSchemaSerializer::FORMAT_PORT = "format"; const QString HRSchemaSerializer::CMDLINE = "cmdline"; const QString HRSchemaSerializer::DESCRIPTION = "description"; const QString HRSchemaSerializer::PROMPTER = "templatedescription"; const QString HRSchemaSerializer::FUNCTION_START = "@"; const QString HRSchemaSerializer::ACTOR_BINDINGS = ".actor-bindings"; template static void setIfNotNull(const T & what, T * to) { if(to != NULL) { *to = what; } } static Attribute* getAttribute(Actor * proc, const QString & attrId) { assert(proc != NULL); if( proc->hasParameter(attrId) ) { return proc->getParameter(attrId); } else if( proc->hasParameter(BaseAttributes::URL_IN_ATTRIBUTE().getId()) && attrId == BaseAttributes::URL_LOCATION_ATTRIBUTE().getId() ) { Attribute * attr = new Attribute(BaseAttributes::URL_LOCATION_ATTRIBUTE(), BaseTypes::BOOL_TYPE(), false, true); proc->addParameter( BaseAttributes::URL_LOCATION_ATTRIBUTE().getId(), attr); return attr; } return NULL; } static QVariant getAttrValue(Actor * proc, const QString & attrId, const QString & valueStr) { Attribute * attr = getAttribute(proc, attrId); if(attr == NULL) { throw HRSchemaSerializer::ReadFailed(HRSchemaSerializer::tr("Parameter '%1' undefined for element '%2'"). arg(attrId).arg(proc->getLabel())); } DataTypeValueFactory * valueFactory = WorkflowEnv::getDataTypeValueFactoryRegistry()->getById(attr->getAttributeType()->getId()); if( valueFactory == NULL ) { throw HRSchemaSerializer::ReadFailed(HRSchemaSerializer::tr("Cannot parse value from '%1': no value factory").arg(valueStr)); } bool ok = false; QVariant value = valueFactory->getValueFromString(valueStr, &ok); if(!ok) { throw HRSchemaSerializer::ReadFailed(HRSchemaSerializer::tr("Cannot parse value from '%1'").arg(valueStr)); } return value; } static QString makeIndent(int tabsNum) { tabsNum = tabsNum <= 0 ? 0 : tabsNum; QString res; for(int i = 0; i < tabsNum; ++i) { res += HRSchemaSerializer::TAB; } return res; } static QString quotedString(const QString & str) { return HRSchemaSerializer::QUOTE + str + HRSchemaSerializer::QUOTE; } static QString valueString(const QString & s) { QString str = s; str.replace("\"", "'"); if( str.contains(QRegExp("\\s") ) || str.contains(HRSchemaSerializer::SEMICOLON) || str.contains(HRSchemaSerializer::EQUALS_SIGN) || str.contains(HRSchemaSerializer::DATAFLOW_SIGN) || str.contains(HRSchemaSerializer::BLOCK_START) || str.contains(HRSchemaSerializer::BLOCK_END)) { return quotedString(str); } else { return str; } } QString HRSchemaSerializer::Tokenizer::take() { if(tokens.isEmpty()) { throw ReadFailed(HRSchemaSerializer::tr("Unexpected end of file")); } return tokens.takeFirst(); } QString HRSchemaSerializer::Tokenizer::look() const { if(tokens.isEmpty()) { throw ReadFailed(HRSchemaSerializer::tr("Unexpected end of file")); } return tokens.first(); } void HRSchemaSerializer::Tokenizer::appendToken(const QString & t, bool skipEmpty) { if(t.isEmpty() && skipEmpty) { return; } if(t == BLOCK_START) { depth++; } if(t == BLOCK_END) { depth--; } tokens.append(t); } void HRSchemaSerializer::Tokenizer::addToken(const QString & t) { QString tok = t.trimmed().replace("'", "\""); if(tok.isEmpty() || tok == SEMICOLON) { return; } if(tok.contains(EQUALS_SIGN) && tok != EQUALS_SIGN) { int ind = tok.indexOf(EQUALS_SIGN); assert(ind != -1); appendToken(tok.mid(0, ind)); appendToken(EQUALS_SIGN); appendToken(tok.mid(ind + 1)); return; } if(tok.contains(DATAFLOW_SIGN) && tok != DATAFLOW_SIGN) { QStringList splitted = tok.split(DATAFLOW_SIGN); assert(splitted.size() == 2); appendToken(splitted.at(0)); appendToken(DATAFLOW_SIGN); appendToken(splitted.at(1)); return; } if(tok.endsWith(BLOCK_START) && tok != BLOCK_START) { appendToken(tok.mid(0, tok.size() - BLOCK_START.size())); appendToken(BLOCK_START); return; } if( tok.startsWith(BLOCK_START) && tok != BLOCK_START ) { appendToken(BLOCK_START); appendToken(tok.mid(1)); return; } if(tok.startsWith(BLOCK_END) && tok != BLOCK_END) { appendToken(BLOCK_END); appendToken(tok.mid(1)); return; } if(tok.endsWith(BLOCK_END) && tok != BLOCK_END) { appendToken(tok.mid(0, tok.size() - BLOCK_END.size())); appendToken(BLOCK_END); return; } appendToken(tok); } void HRSchemaSerializer::Tokenizer::removeCommentTokens() { foreach(const QString & t, tokens) { if(t.startsWith(SERVICE_SYM)) { tokens.removeAll(t); } } } void HRSchemaSerializer::Tokenizer::assertToken(const QString & etalon) { QString candidate = take(); if( candidate != etalon ) { throw ReadFailed(HRSchemaSerializer::tr("Expected '%1', got %2").arg(etalon).arg(candidate)); } } static bool isBlockLine(const QString & str) { int bInd = str.indexOf(HRSchemaSerializer::BLOCK_START); int eInd = str.indexOf(HRSchemaSerializer::EQUALS_SIGN); if(bInd == -1) { return false; } else { if(eInd == -1) { return true; } else { return bInd < eInd; } } } void HRSchemaSerializer::Tokenizer::tokenize(const QString & d) { depth = 0; QString data = d; QTextStream stream(&data); bool isElemDef = false; bool elemDefHeader = false; while(1) { QString line = stream.readLine().trimmed(); if(line.isEmpty()) { if(stream.atEnd()) { break; } continue; } if( line.startsWith(SERVICE_SYM) ) { tokens.append(line); continue; } if(depth == 1) { isElemDef = !line.startsWith(META_START) && !line.startsWith(DOT_ITERATION_START) && !line.contains(DATAFLOW_SIGN) && !line.startsWith(INPUT_START) && !line.startsWith(OUTPUT_START) && !line.startsWith(ATTRIBUTES_START); elemDefHeader = true; } else { elemDefHeader = false; } if(isElemDef && !elemDefHeader && isBlockLine(line)) { tokenizeBlock(line, stream); continue; } tokenizeLine(line, stream); } } static void skipDelimiters(QTextStream & s) { while(!s.atEnd()) { qint64 curPos = s.pos(); QChar ch; s >> ch; if(ch.isSpace() || ch == HRSchemaSerializer::NEW_LINE.at(0) || ch == HRSchemaSerializer::SEMICOLON.at(0)) { continue; } s.seek(curPos); break; } } void HRSchemaSerializer::Tokenizer::tokenizeBlock(const QString & line, QTextStream & s) { if(!line.contains(BLOCK_START)) { throw ReadFailed(HRSchemaSerializer::tr("Expected '%1', near '%2'").arg(BLOCK_START).arg(line)); } QString tok = line.mid(0, line.indexOf(BLOCK_START)).trimmed(); appendToken(tok); appendToken(BLOCK_START); QString blockTok; QString ln = line.mid(line.indexOf(BLOCK_START) + 1); if(ln.isEmpty()) { ln = s.readLine(); } ln += NEW_LINE; QTextStream stream(&ln); int level = 0; while(!stream.atEnd()) { QChar ch; stream >> ch; if(ch == BLOCK_START.at(0)) { level++; } if(ch == BLOCK_END.at(0)) { if(level-- == 0) { appendToken(blockTok.trimmed(), false); appendToken(BLOCK_END); skipDelimiters(stream); if(!stream.atEnd()) { tokenizeBlock(stream.readAll(), s); } return; } } blockTok.append(ch); if(stream.atEnd()) { ln = s.readLine() + NEW_LINE; stream.setString(&ln); } } } void HRSchemaSerializer::Tokenizer::tokenizeLine(const QString & l, QTextStream & s) { QString line = l; QTextStream stream(&line); QString curToken; bool finishAtQuote = false; while(!stream.atEnd()) { QChar ch; stream >> ch; if( stream.atEnd() && finishAtQuote && ch != QUOTE.at(0) ) { line = s.readLine(); stream.setString(&line); } if(ch.isSpace() || ch == SEMICOLON.at(0)) { if(!finishAtQuote) { addToken(curToken); curToken.clear(); continue; } else { curToken.append(ch); } } else if(ch == QUOTE.at(0)) { if( finishAtQuote ) { appendToken(curToken); curToken.clear(); finishAtQuote = false; } else { addToken(curToken); curToken.clear(); finishAtQuote = true; } continue; } else if (ch == FUNCTION_START.at(0)) { if (finishAtQuote) { curToken.append(ch); } else { addToken(curToken); curToken.clear(); addToken(ch); } } else { curToken.append(ch); } } addToken(curToken); } HRSchemaSerializer::ParsedPairs::ParsedPairs(HRSchemaSerializer::Tokenizer & tokenizer) { while(tokenizer.notEmpty() && tokenizer.look() != BLOCK_END) { QString tok = tokenizer.take(); QString next = tokenizer.take(); if( next == EQUALS_SIGN ) { equalPairs[tok] = tokenizer.take(); } else if(next == BLOCK_START) { blockPairs[tok] = tokenizer.take(); tokenizer.take(); // BLOCK_END of script block } else { throw ReadFailed(HRSchemaSerializer::tr("Expected %3 or %1 after %2").arg(BLOCK_START).arg(tok).arg(EQUALS_SIGN)); } } } QPair HRSchemaSerializer::ParsedPairs::parseOneEqual(Tokenizer & tokenizer) { QPair res; res.first = tokenizer.take(); if(tokenizer.take() != EQUALS_SIGN) { throw ReadFailed(HRSchemaSerializer::tr("%2 expected after %1").arg(res.first).arg(EQUALS_SIGN)); } res.second = tokenizer.take(); return res; } HRSchemaSerializer::FlowGraph::FlowGraph( const QList >& d ) : dataflowLinks(d) { removeDuplicates(); for(int i = 0; i < dataflowLinks.size(); ++i) { const QPair & pair = dataflowLinks.at(i); if(!graph.contains(pair.first)) { graph[pair.first] = QList(); } graph.find(pair.first)->append(pair.second); } } void HRSchemaSerializer::FlowGraph::removeDuplicates() { QList > links; for(int i = 0; i < dataflowLinks.size(); ++i) { const QPair & p = dataflowLinks.at(i); bool found = false; for(int j = 0; j < links.size(); ++j) { const QPair & pair = links.at(j); if(pair.first == p.first && pair.second == p.second) { found = true; break; } } if(!found) { links << p; } } dataflowLinks = links; } bool HRSchemaSerializer::FlowGraph::findPath(Actor * from, Port * to) const { static const int RECURSION_MAX = 100; if(findRecursion == RECURSION_MAX) { throw ReadFailed(tr("Cannot create flow graph")); } foreach(Port * p, from->getOutputPorts()) { if(graph[p].contains(to) ) { return true; } foreach(Port * connection, graph[p]) { if(findPath(connection->owner(), to)) { return true; } } } return false; } void HRSchemaSerializer::FlowGraph::minimize() { for(int i = 0; i < dataflowLinks.size(); ++i) { Port * src = dataflowLinks.at(i).first; Port * dst = dataflowLinks.at(i).second; foreach(Port * p, graph[src]) { findRecursion = 0; if(findPath(p->owner(), dst) ){ graph.find(src)->removeAll(dst); break; } } } } struct WorkflowSchemaReaderData { WorkflowSchemaReaderData(const QString & bytes, Schema * s, Metadata * m, QMap* im) : schema(s), meta(m), idMap(im) { tokenizer.tokenize(bytes); } HRSchemaSerializer::Tokenizer tokenizer; Schema * schema; Metadata * meta; QMap actorMap; QList > dataflowLinks; QList > links; QMap * idMap; }; // WorkflowSchemaReaderData void HRSchemaSerializer::parseHeader(Tokenizer & tokenizer, Metadata * meta) { QString head = tokenizer.take(); QString realHead = HEADER_LINE.trimmed(); if(!head.startsWith(realHead)) { if( tokenizer.notEmpty() && head + " " + tokenizer.take() == OLD_XML_HEADER ) { throw ReadFailed(tr("XML schema format is obsolete and not supported")); } throw ReadFailed(tr("Bad header: expected '%1', got '%2'").arg(realHead).arg(head)); } QString desc; while(tokenizer.look().startsWith(SERVICE_SYM)) { desc += tokenizer.take().mid(SERVICE_SYM.size()) + HRSchemaSerializer::NEW_LINE; } setIfNotNull(desc, meta == NULL ? NULL : &meta->comment); } void HRSchemaSerializer::parseBodyHeader(Tokenizer & tokenizer, Metadata * meta, bool needName) { QString bodyStart = tokenizer.take(); if( bodyStart != BODY_START ) { throw ReadFailed(tr("Bad header: expected '%1', got '%2'").arg(BODY_START).arg(bodyStart)); } if(tokenizer.look() == BLOCK_START) { if(needName) { coreLog.details(tr("Schema name not specified")); } } else { setIfNotNull(tokenizer.take(), meta == NULL ? NULL : &meta->name); } } Actor* HRSchemaSerializer::parseElementsDefinition(Tokenizer & tokenizer, const QString & actorName, QMap & actorMap, QMap* idMap) { if( actorName.contains(QRegExp("\\s")) ) { throw ReadFailed(tr("Element name cannot contain whitespaces: '%1'").arg(actorName)); } if(actorName.contains(DOT)) { throw ReadFailed(tr("Element name cannot contain dots: '%1'").arg(actorName)); } if(actorMap.contains(actorName)) { throw ReadFailed(tr("Element '%1' already defined").arg(actorName)); } ParsedPairs pairs(tokenizer); QString procType = pairs.equalPairs.take(TYPE_ATTR); if( procType.isEmpty() ) { throw ReadFailed(tr("Type attribute not set for %1 element").arg(actorName)); } ActorPrototype * proto = WorkflowEnv::getProtoRegistry()->getProto(SchemaSerializer::getElemType(procType)); if(proto == NULL) { throw ReadFailed(tr("Unknown type of %1 element: %2").arg(actorName).arg(procType)); } QString procScriptText = pairs.blockPairs.take(SCRIPT_ATTR); Actor * proc = proto->createInstance(procScriptText.isEmpty() ? NULL : new AttributeScript(procScriptText)); actorMap[actorName] = proc; QString procName = pairs.equalPairs.take(NAME_ATTR); if( procName.isEmpty() ) { throw ReadFailed(tr("Name attribute not set for %1 element").arg(actorName)); } proc->setLabel(procName); ActorId oldId = str2aid(pairs.equalPairs.take(ELEM_ID_ATTR)); if(idMap != NULL && !oldId.isEmpty()) { idMap->insert(oldId, proc->getId()); } foreach(const QString & key, pairs.blockPairs.keys()) { proc->getParameter(key)->getAttributeScript().setScriptText(pairs.blockPairs.value(key)); } foreach( const QString & key, pairs.equalPairs.keys() ) { proc->getParameter(key)->setAttributeValue(getAttrValue(proc, key, pairs.equalPairs.value(key))); } return proc; } QString HRSchemaSerializer::parseAt(const QString & dottedStr, int ind) { QStringList list = dottedStr.split(DOT); return list.size() > ind ? list.at(ind) : ""; } static QString parseAfter(const QString & dottedStr, int ind) { QStringList list = dottedStr.split(HRSchemaSerializer::DOT); QString res; for(int i = ind + 1; i < list.size(); ++i) { res += list.at(i) + HRSchemaSerializer::DOT; } return res.mid(0, res.size() - HRSchemaSerializer::DOT.size()); } void HRSchemaSerializer::backwardIncapability() { throw ReadFailed(tr("It is a workflow file which is not supported in this version of UGENE. Please, try to install UGENE 1.10 or later")); } static void skipBlock(HRSchemaSerializer::Tokenizer & tokenizer) { while(tokenizer.look() != HRSchemaSerializer::BLOCK_END) { QString tok = tokenizer.take(); if( tok == HRSchemaSerializer::BLOCK_START ) { skipBlock(tokenizer); } } tokenizer.take(); } Iteration HRSchemaSerializer::parseIteration(Tokenizer & tokenizer, const QString & iterationName, const QMap & actorMap, bool pasteMode) { QPair idPair = ParsedPairs::parseOneEqual(tokenizer); if( idPair.first != ITERATION_ID) { throw ReadFailed(tr("%1 definition expected at .iterations block").arg(ITERATION_ID)); } Iteration iteration(iterationName); bool ok = false; iteration.id = idPair.second.toInt(&ok); if(!ok) { throw ReadFailed(tr("Cannot parse integer from '%1': iteration id").arg(idPair.second)); } while(tokenizer.look() != BLOCK_END) { QString actorName = tokenizer.take(); if( !actorMap.contains(actorName)) { if(!pasteMode) { throw ReadFailed(tr("Element id '%1' undefined in .iteration block").arg(actorName)); } else { tokenizer.assertToken(BLOCK_START); skipBlock(tokenizer); continue; } } tokenizer.assertToken(BLOCK_START); ParsedPairs pairs(tokenizer); tokenizer.assertToken(BLOCK_END); if( !pairs.blockPairs.isEmpty() ) { throw ReadFailed(tr("No block definitions allowed in .iteration block: %1").arg(iteration.name)); } foreach(const QString & key, pairs.equalPairs.keys()) { iteration.cfg[actorMap[actorName]->getId()][key] = getAttrValue(actorMap[actorName], key, pairs.equalPairs.value(key)); } } return iteration; } void HRSchemaSerializer::parseAliases(Tokenizer & tokenizer, const QMap & actorMap) { ParsedPairs pairs(tokenizer); if( !pairs.blockPairs.isEmpty() ) { throw ReadFailed(tr("No other blocks allowed in aliases block")); } foreach(const QString & key, pairs.equalPairs.keys()) { QString actorName = parseAt(key, 0); Actor * actor = actorMap.value(actorName); if( actor == NULL ) { throw ReadFailed(tr("%1 element undefined in aliases block").arg(actorName)); } QString attributeId = parseAt(key, 1); if( !actor->hasParameter(attributeId) ) { throw ReadFailed(tr("%1 has no parameter %2: in aliases block").arg(actorName).arg(attributeId)); } actor->getParamAliases()[attributeId] = pairs.equalPairs.value(key); } } void HRSchemaSerializer::parseAliasesHelp(Tokenizer & tokenizer, const QList & procs) { ParsedPairs pairs(tokenizer); if(!pairs.blockPairs.isEmpty()) { throw ReadFailed(tr("No other blocks allowed in help block")); } foreach(const QString & key, pairs.equalPairs.keys()) { QString paramName; Actor * actor = WorkflowUtils::findActorByParamAlias(procs, key, paramName, false); if(actor == NULL) { throw ReadFailed(tr("Undefined parameter alias used in help block: '%1'").arg(key)); } QString help = pairs.equalPairs.value(key); assert(!help.isEmpty()); actor->getAliasHelp()[key] = help; } } QPair HRSchemaSerializer::parseDataflow(Tokenizer & tokenizer, const QString & srcTok, const QMap & actorMap) { QString srcActorName = parseAt(srcTok, 0); QString srcSlotId = parseAfter(srcTok, 0); if(!actorMap.contains(srcActorName)) { throw ReadFailed(tr("Undefined element id '%1' at '%2'").arg(srcActorName).arg(srcTok)); } bool slotFound = false; Port * srcPort = NULL; foreach(Port * port, actorMap.value(srcActorName)->getOutputPorts()) { DataTypePtr dt = port->Port::getType(); QList descs = dt->getAllDescriptors(); descs << *dt; slotFound = slotFound || descs.contains(srcSlotId); if(slotFound) { srcPort = port; break; } } if(!slotFound) { throw ReadFailed(tr("Undefined slot id '%1' at '%2'").arg(srcSlotId).arg(srcTok)); } tokenizer.take(); // "->" QString destTok = tokenizer.take(); QString destActorName = parseAt(destTok, 0); QString destPortId = parseAt(destTok, 1); QString destSlotId = parseAfter(destTok, 1); if( !actorMap.contains(destActorName) ) { throw ReadFailed(tr("Undefined element id '%1' at '%2'").arg(destActorName).arg(destTok)); } Port * destPort = actorMap.value(destActorName)->getPort(destPortId); if(destPort == NULL) { throw ReadFailed(tr("Undefined port id '%1' at '%2'").arg(destPortId).arg(destTok)); } if( !destPort->isInput() ) { throw ReadFailed(tr("Destination port should be input: %1").arg(destPortId)); } DataTypePtr dt = destPort->Port::getType(); QList descs = dt->getAllDescriptors(); descs << *dt; if(!descs.contains(destSlotId)) { throw ReadFailed(tr("Undefined slot id '%1' at '%2'").arg(destSlotId).arg(destTok)); } qobject_cast(destPort)->setBusMapValue(destSlotId, actorMap.value(srcActorName)->getId() + ":" + srcSlotId); return QPair(srcPort, destPort); } static QPair parseLinkVisualBlock(WorkflowSchemaReaderData& data, const QString & from, const QString & to) { QString srcActorName = HRSchemaSerializer::parseAt(from, 0); Actor * srcActor = data.actorMap.value(srcActorName); if(srcActor == NULL) { throw HRSchemaSerializer::ReadFailed(HRSchemaSerializer::tr("Undefined element id: '%1'").arg(srcActorName)); } QString srcPortId = HRSchemaSerializer::parseAt(from, 1); Port * srcPort = srcActor->getPort(srcPortId); if(srcPort == NULL) { throw HRSchemaSerializer::ReadFailed(HRSchemaSerializer::tr("Cannot find '%1' port at '%2'").arg(srcPortId).arg(srcActorName)); } QString dstActorName = HRSchemaSerializer::parseAt(to, 0); Actor * dstActor = data.actorMap.value(dstActorName); if(dstActor == NULL) { throw HRSchemaSerializer::ReadFailed(HRSchemaSerializer::tr("Undefined element id: '%1'").arg(dstActorName)); } QString dstPortId = HRSchemaSerializer::parseAt(to, 1); Port * dstPort = dstActor->getPort(dstPortId); if(dstPort == NULL) { throw HRSchemaSerializer::ReadFailed(HRSchemaSerializer::tr("Cannot find '%1' port at '%2'").arg(dstPortId).arg(dstActorName)); } return QPair(srcPort, dstPort); } static void parseVisual(WorkflowSchemaReaderData & data) { while(data.tokenizer.look() != HRSchemaSerializer::BLOCK_END) { QString tok = data.tokenizer.take(); QString next = data.tokenizer.take(); if(tok == HRSchemaSerializer::BLOCK_START) { skipBlock(data.tokenizer); } if(next == HRSchemaSerializer::BLOCK_START) { data.tokenizer.take(); skipBlock(data.tokenizer); } else if(next == HRSchemaSerializer::DATAFLOW_SIGN) { QString to = data.tokenizer.take(); data.links << parseLinkVisualBlock(data, tok, to); } } } static void parseMeta(WorkflowSchemaReaderData & data) { while(data.tokenizer.look() != HRSchemaSerializer::BLOCK_END) { QString tok = data.tokenizer.take(); if(tok == HRSchemaSerializer::ALIASES_START) { data.tokenizer.assertToken(HRSchemaSerializer::BLOCK_START); HRSchemaSerializer::parseAliases(data.tokenizer, data.actorMap); data.tokenizer.assertToken(HRSchemaSerializer::BLOCK_END); } else if(tok == HRSchemaSerializer::VISUAL_START) { data.tokenizer.assertToken(HRSchemaSerializer::BLOCK_START); parseVisual(data); data.tokenizer.assertToken(HRSchemaSerializer::BLOCK_END); } else if(tok == HRSchemaSerializer::ALIASES_HELP_START) { data.tokenizer.assertToken(HRSchemaSerializer::BLOCK_START); HRSchemaSerializer::parseAliasesHelp(data.tokenizer, data.actorMap.values()); data.tokenizer.assertToken(HRSchemaSerializer::BLOCK_END); } else { throw HRSchemaSerializer::ReadFailed(HRSchemaSerializer::UNDEFINED_META_BLOCK.arg(tok)); } } } static void parseBody(WorkflowSchemaReaderData & data) { HRSchemaSerializer::Tokenizer & tokenizer = data.tokenizer; while(tokenizer.notEmpty() && tokenizer.look() != HRSchemaSerializer::BLOCK_END) { QString tok = tokenizer.take(); QString next = tokenizer.look(); if(tok == HRSchemaSerializer::META_START) { tokenizer.assertToken(HRSchemaSerializer::BLOCK_START); parseMeta(data); tokenizer.assertToken(HRSchemaSerializer::BLOCK_END); } else if(tok == HRSchemaSerializer::DOT_ITERATION_START) { QString itName = tokenizer.look() == HRSchemaSerializer::BLOCK_START ? "" : tokenizer.take(); tokenizer.assertToken(HRSchemaSerializer::BLOCK_START); data.schema->getIterations() << HRSchemaSerializer::parseIteration(tokenizer, itName, data.actorMap); tokenizer.assertToken(HRSchemaSerializer::BLOCK_END); } else if (tok == HRSchemaSerializer::ACTOR_BINDINGS) { HRSchemaSerializer::backwardIncapability(); } else if (tok == HRSchemaSerializer::FUNCTION_START) { HRSchemaSerializer::backwardIncapability(); } else if(next == HRSchemaSerializer::DATAFLOW_SIGN) { data.dataflowLinks << HRSchemaSerializer::parseDataflow(tokenizer, tok, data.actorMap); } else if(next == HRSchemaSerializer::BLOCK_START) { tokenizer.take(); Actor * proc = HRSchemaSerializer::parseElementsDefinition(tokenizer, tok, data.actorMap, data.idMap); data.schema->addProcess(proc); tokenizer.assertToken(HRSchemaSerializer::BLOCK_END); } else { throw HRSchemaSerializer::ReadFailed(HRSchemaSerializer::UNDEFINED_CONSTRUCT.arg(tok).arg(next)); } } } static void tryToConnect(Schema * schema, Port * input, Port * output) { if(!input || !output || !input->canBind(output)) { throw HRSchemaSerializer::ReadFailed(HRSchemaSerializer::tr("Cannot bind %1:%2 to %3:%4"). arg(input->owner()->getId()).arg(input->getId()).arg(output->owner()->getId()).arg(output->getId())); } schema->addFlow(new Link(input, output)); } static void setFlows(WorkflowSchemaReaderData & data) { if(!data.links.isEmpty()) { for(int i = 0; i < data.links.size(); ++i) { const QPair & pair = data.links.at(i); tryToConnect(data.schema, pair.first, pair.second); } } else { HRSchemaSerializer::FlowGraph graph(data.dataflowLinks); graph.minimize(); foreach(Port * input, graph.graph.keys()) { foreach(Port * output, graph.graph.value(input)) { tryToConnect(data.schema, input, output); } } } } void HRSchemaSerializer::addEmptyValsToBindings(const QList & procs) { foreach(Actor * actor, procs) { foreach(Port * p, actor->getInputPorts()) { IntegralBusPort * port = qobject_cast(p); QStrStrMap busMap = port->getParameter(IntegralBusPort::BUS_MAP_ATTR_ID)->getAttributeValue(); DataTypePtr t = port->Port::getType(); assert(t->isMap()); QMap typeMap = t->getDatatypesMap(); foreach(const Descriptor & d, typeMap.keys()) { if(!busMap.contains(d.getId())) { port->setBusMapValue(d.getId(), ""); } } } } } QString HRSchemaSerializer::string2Schema(const QString & bytes, Schema * schema, Metadata * meta, QMap* idMap) { try { WorkflowSchemaReaderData data(bytes, schema, meta, idMap); parseHeader(data.tokenizer, data.meta); data.tokenizer.removeCommentTokens(); parseBodyHeader(data.tokenizer, data.meta); if( schema != NULL ) { data.tokenizer.assertToken(BLOCK_START); parseBody(data); data.tokenizer.assertToken(BLOCK_END); if(data.schema->getIterations().isEmpty()) { data.schema->getIterations() << Iteration("Default iteration"); } setFlows(data); addEmptyValsToBindings(data.actorMap.values()); } } catch( const HRSchemaSerializer::ReadFailed & ex ) { return ex.what; } catch (...) { return UNKNOWN_ERROR; } return NO_ERROR; } void HRSchemaSerializer::parsePorts(Tokenizer & tokenizer, QList& ports) { while(tokenizer.look() != BLOCK_END) { DataConfig cfg; cfg.attrName = tokenizer.take(); tokenizer.assertToken(HRSchemaSerializer::BLOCK_START); ParsedPairs pairs(tokenizer); cfg.type = pairs.equalPairs.take(TYPE_PORT); cfg.format = pairs.equalPairs.take(FORMAT_PORT); cfg.description = pairs.equalPairs.take(DESCRIPTION); tokenizer.assertToken(HRSchemaSerializer::BLOCK_END); ports << cfg; } } void HRSchemaSerializer::parseAttributes(Tokenizer & tokenizer, QList& attrs) { while(tokenizer.look() != BLOCK_END) { AttributeConfig cfg; cfg.attrName = tokenizer.take(); tokenizer.assertToken(HRSchemaSerializer::BLOCK_START); ParsedPairs pairs(tokenizer); cfg.type = pairs.equalPairs.take(TYPE_PORT); cfg.description = pairs.equalPairs.take(DESCRIPTION); tokenizer.assertToken(HRSchemaSerializer::BLOCK_END); attrs << cfg; } } ExternalProcessConfig* HRSchemaSerializer::parseActorBody(Tokenizer & tokenizer) { ExternalProcessConfig *cfg = new ExternalProcessConfig(); cfg->name = tokenizer.take(); while(tokenizer.notEmpty() && tokenizer.look() != HRSchemaSerializer::BLOCK_END) { QString tok = tokenizer.take(); QString next = tokenizer.look(); if(tok == HRSchemaSerializer::INPUT_START) { tokenizer.assertToken(HRSchemaSerializer::BLOCK_START); HRSchemaSerializer::parsePorts(tokenizer, cfg->inputs); tokenizer.assertToken(HRSchemaSerializer::BLOCK_END); } else if(tok == HRSchemaSerializer::OUTPUT_START) { tokenizer.assertToken(HRSchemaSerializer::BLOCK_START); HRSchemaSerializer::parsePorts(tokenizer, cfg->outputs); tokenizer.assertToken(HRSchemaSerializer::BLOCK_END); } else if(tok == HRSchemaSerializer::ATTRIBUTES_START) { tokenizer.assertToken(HRSchemaSerializer::BLOCK_START); HRSchemaSerializer::parseAttributes(tokenizer, cfg->attrs); tokenizer.assertToken(HRSchemaSerializer::BLOCK_END); } else if(tok == HRSchemaSerializer::BLOCK_START) { //tokenizer.take(); /*Actor * proc = HRSchemaSerializer::parseElementsDefinition(tokenizer, tok, data.actorMap, data.idMap); data.schema->addProcess(proc); tokenizer.assertToken(HRSchemaSerializer::BLOCK_END);*/ } else if(tok == HRSchemaSerializer::CMDLINE) { tokenizer.assertToken(COLON); cfg->cmdLine = tokenizer.take(); } else if(tok == HRSchemaSerializer::DESCRIPTION) { tokenizer.assertToken(COLON); cfg->description = tokenizer.take(); }else if(tok == HRSchemaSerializer::PROMPTER) { tokenizer.assertToken(COLON); cfg->templateDescription = tokenizer.take(); } else { throw HRSchemaSerializer::ReadFailed(HRSchemaSerializer::UNDEFINED_CONSTRUCT.arg(tok).arg(next)); } } return cfg; } ExternalProcessConfig* HRSchemaSerializer::string2Actor(const QString & bytes) { ExternalProcessConfig *cfg = NULL; try { WorkflowSchemaReaderData data(bytes, NULL, NULL, NULL); parseHeader(data.tokenizer, data.meta); cfg = parseActorBody(data.tokenizer); } catch (...) { return NULL; } return cfg; } void HRSchemaSerializer::addPart( QString & to, const QString & w) { QString what = w; if( !what.endsWith(NEW_LINE) ) { what.append(NEW_LINE); } to += what + NEW_LINE; } QString HRSchemaSerializer::header2String(const Metadata * meta) { QString res = HRSchemaSerializer::HEADER_LINE + "\n"; if(meta != NULL) { QStringList descLines = meta->comment.split(HRSchemaSerializer::NEW_LINE, QString::KeepEmptyParts); foreach(const QString & line, descLines) { res += HRSchemaSerializer::SERVICE_SYM + line + HRSchemaSerializer::NEW_LINE; } } return res; } QString HRSchemaSerializer::makeBlock(const QString & title, const QString & name, const QString & blockItself, int tabsNum, bool nl, bool sc) { QString indent = makeIndent(tabsNum); QString blockStart = BLOCK_START + NEW_LINE; if(nl) { blockStart += NEW_LINE; } QString blockEnd = BLOCK_END; if(sc) { blockEnd += SEMICOLON; } blockEnd += NEW_LINE; return indent + title + " " + valueString(name) + blockStart + blockItself + indent + blockEnd; } QString HRSchemaSerializer::makeEqualsPair(const QString & key, const QString & value, int tabsNum) { return makeIndent(tabsNum) + key + EQUALS_SIGN + valueString(value) + SEMICOLON + NEW_LINE; } QString HRSchemaSerializer::makeArrowPair( const QString & left, const QString & right, int tabsNum ) { return makeIndent(tabsNum) + left + DATAFLOW_SIGN + right; } QString HRSchemaSerializer::scriptBlock(const QString & scriptText, int tabsNum) { QString indent = makeIndent(tabsNum); QString res; QStringList scriptLines = scriptText.split(NEW_LINE, QString::SkipEmptyParts); foreach(const QString & line, scriptLines) { res += indent + line + NEW_LINE; } return res; } static QString elementsDefinitionBlock(Actor * actor, bool copyMode) { assert(actor != NULL); QString res; // save global attributes res += HRSchemaSerializer::makeEqualsPair(HRSchemaSerializer::TYPE_ATTR, actor->getProto()->getId()); res += HRSchemaSerializer::makeEqualsPair(HRSchemaSerializer::NAME_ATTR, actor->getLabel()); if(copyMode) { res += HRSchemaSerializer::makeEqualsPair(HRSchemaSerializer::ELEM_ID_ATTR, actor->getId()); } AttributeScript * actorScript = actor->getScript(); if(actorScript != NULL && !actorScript->getScriptText().trimmed().isEmpty()) { res += HRSchemaSerializer::makeBlock(HRSchemaSerializer::SCRIPT_ATTR, HRSchemaSerializer::NO_NAME, actorScript->getScriptText() + HRSchemaSerializer::NEW_LINE, 2, false, true); } // save local attributes foreach(Attribute * attribute, actor->getParameters().values()) { assert(attribute != NULL); QString attributeId = attribute->getId(); assert(!attributeId.contains(QRegExp("\\s"))); const AttributeScript & attrScript = attribute->getAttributeScript(); if(!attrScript.isEmpty()) { res += HRSchemaSerializer::makeBlock(attributeId, HRSchemaSerializer::NO_NAME, attrScript.getScriptText() + HRSchemaSerializer::NEW_LINE, 2, false, true); continue; } QVariant value = attribute->getAttributePureValue(); assert(value.isNull() || value.canConvert()); QString valueStr = value.toString(); if(!valueStr.isEmpty()) { res += HRSchemaSerializer::makeEqualsPair(attributeId, valueStr); } } return res; } QString HRSchemaSerializer::elementsDefinition(const QList & procs, const NamesMap & nmap, bool copyMode) { QString res; foreach( Actor * actor, procs) { res += makeBlock(nmap[actor->getId()], NO_NAME, elementsDefinitionBlock(actor, copyMode)); } return res + NEW_LINE; } static bool containsProcWithId(const QList & procs, const ActorId & id) { foreach(Actor * a, procs) { if(a->getId() == id) { return true; } } return false; } QString HRSchemaSerializer::dataflowDefinition(const QList & procs, const NamesMap & nmap) { QString res; foreach(Actor * actor, procs) { foreach(Port * inputPort, actor->getInputPorts()) { QStrStrMap busMap = inputPort->getParameter(IntegralBusPort::BUS_MAP_ATTR_ID)->getAttributeValue(); foreach( const QString & key, busMap.keys() ) { QStringList srcList = busMap.value(key).split(";", QString::SkipEmptyParts); foreach(QString src, srcList) { if(src.isEmpty()) { continue; } src = src.replace(COLON, DOT); ActorId srcActorId = parseAt(src, 0); if(containsProcWithId(procs, srcActorId)) { res += makeArrowPair(src.replace(srcActorId, nmap[srcActorId]), nmap[actor->getId()] + DOT + inputPort->getId() + DOT + key) + NEW_LINE; } } } } } return res + NEW_LINE; } static QString elementsIterationData(const QVariantMap & data) { QString res; foreach( const QString & attributeId, data.uniqueKeys() ) { assert(!attributeId.contains(QRegExp("\\s"))); QVariant value = data.value(attributeId); assert(value.isNull() || value.canConvert()); QString valueStr = value.toString(); if(!valueStr.isEmpty()) { res += HRSchemaSerializer::makeEqualsPair(attributeId, valueStr, 3); } } return res; } static QString iterationData(const Iteration & iteration, const HRSchemaSerializer::NamesMap& nmap) { QString res = HRSchemaSerializer::makeEqualsPair(HRSchemaSerializer::ITERATION_ID, QString::number(iteration.id)) + HRSchemaSerializer::NEW_LINE; foreach(const ActorId & aid, iteration.cfg.uniqueKeys() ) { QString blockName = nmap[aid]; if(blockName.isEmpty()) { blockName = aid; } res += HRSchemaSerializer::makeBlock(blockName, HRSchemaSerializer::NO_ERROR, elementsIterationData(iteration.cfg.value(aid)), 2); } return res; } QString HRSchemaSerializer::iterationsDefinition(const QList & iterations, const NamesMap& nmap, bool checkDummyIteration) { if(checkDummyIteration) { if( iterations.size() == 1 && iterations.at(0).isEmpty()) { return QString(); } } QString res; foreach( const Iteration & iteration, iterations ) { res += HRSchemaSerializer::makeBlock(HRSchemaSerializer::DOT_ITERATION_START, iteration.name, iterationData(iteration, nmap)); } return res; } static QString visualData(const Schema & schema, const HRSchemaSerializer::NamesMap& nmap) { QString res; foreach(Link* link, schema.getFlows()) { Port * src = link->source(); Port * dst = link->destination(); res += HRSchemaSerializer::makeArrowPair(nmap[src->owner()->getId()] + HRSchemaSerializer::DOT + src->getId(), nmap[dst->owner()->getId()] + HRSchemaSerializer::DOT + dst->getId(), 0) + HRSchemaSerializer::NEW_LINE; } return res; } static QString metaData(const Schema & schema, const HRSchemaSerializer::NamesMap& nmap) { QString res; if(schema.hasParamAliases()) { res += HRSchemaSerializer::makeBlock(HRSchemaSerializer::ALIASES_START, HRSchemaSerializer::NO_NAME, HRSchemaSerializer::schemaAliases(schema.getProcesses(), nmap), 2); } if(schema.hasAliasHelp()) { res += HRSchemaSerializer::makeBlock(HRSchemaSerializer::ALIASES_HELP_START, HRSchemaSerializer::NO_NAME, HRSchemaSerializer::aliasesHelp(schema.getProcesses()), 2); } res += HRSchemaSerializer::makeBlock(HRSchemaSerializer::VISUAL_START, HRSchemaSerializer::NO_NAME, visualData(schema, nmap), 2); return res; } QString HRSchemaSerializer::schemaAliases(const QList & procs, const NamesMap& nmap) { QString res; foreach(Actor * actor, procs) { const QMap & aliases = actor->getParamAliases(); foreach(const QString & attrId, aliases.uniqueKeys()) { res += HRSchemaSerializer::makeEqualsPair(nmap[actor->getId()] + HRSchemaSerializer::DOT + attrId, aliases.value(attrId), 3); } } return res; } QString HRSchemaSerializer::aliasesHelp(const QList & procs) { QString res; foreach(Actor * a, procs) { const QMap & aliasesHelp = a->getAliasHelp(); foreach(const QString & alias, aliasesHelp.keys()) { assert(a->getParamAliases().values().contains(alias)); res += HRSchemaSerializer::makeEqualsPair(alias, aliasesHelp.value(alias), 3); } } return res; } static QString generateElementName(Actor * proc, const QList& existing) { QString candidate = proc->getProto()->getId().replace(HRSchemaSerializer::DOT, HRSchemaSerializer::DASH). replace(QRegExp("\\s+"), HRSchemaSerializer::DASH); QList similar; foreach(const QString & s, existing) { if(s.startsWith(candidate)) { similar << s; } } if(similar.isEmpty()) { return candidate; } return candidate + QString::number(similar.size() + 1); } HRSchemaSerializer::NamesMap HRSchemaSerializer::generateElementNames(const QList& procs) { QMap nmap; foreach(Actor * proc, procs) { nmap[proc->getId()] = generateElementName(proc, nmap.values()); } return nmap; } static QString bodyItself(const Schema & schema, bool copyMode) { HRSchemaSerializer::NamesMap nmap = HRSchemaSerializer::generateElementNames(schema.getProcesses()); QString res; res += HRSchemaSerializer::elementsDefinition(schema.getProcesses(), nmap, copyMode); res += HRSchemaSerializer::dataflowDefinition(schema.getProcesses(), nmap); res += HRSchemaSerializer::iterationsDefinition(schema.getIterations(), nmap, false); res += HRSchemaSerializer::makeBlock(HRSchemaSerializer::META_START, HRSchemaSerializer::NO_NAME, metaData(schema, nmap)); return res; } QString HRSchemaSerializer::schema2String(const Schema & schema, const Metadata * meta, bool copyMode) { QString res; addPart(res, header2String(meta)); addPart(res, makeBlock(BODY_START, meta ? meta->name : "", bodyItself(schema, copyMode), 0, true)); return res; } QMap HRSchemaSerializer::deepCopy(const Schema& from, Schema* to) { assert(to != NULL); QString data = schema2String(from, NULL, true); QMap idMap; QString err = string2Schema(data, to, NULL, &idMap); if(!err.isEmpty()) { coreLog.details(err); to->reset(); return QMap(); } to->setDeepCopyFlag(true); return idMap; } static QString inputsDefenition(const QList &inputs) { QString res = HRSchemaSerializer::TAB + HRSchemaSerializer::INPUT_START + " {\n"; foreach(const DataConfig cfg, inputs) { res += HRSchemaSerializer::TAB + HRSchemaSerializer::TAB + cfg.attrName + " {\n"; res += HRSchemaSerializer::TAB + HRSchemaSerializer::TAB + HRSchemaSerializer::TAB + "type:" + cfg.type + ";\n"; res += HRSchemaSerializer::TAB + HRSchemaSerializer::TAB + HRSchemaSerializer::TAB + "format:" + cfg.format + ";\n"; if(!cfg.description.isEmpty()) { res += HRSchemaSerializer::TAB + HRSchemaSerializer::TAB + HRSchemaSerializer::TAB + "description:\"" + cfg.description + "\";\n"; } res += HRSchemaSerializer::TAB + HRSchemaSerializer::TAB + "}\n"; } res += HRSchemaSerializer::TAB + "}\n"; return res; } static QString outputsDefenition(const QList &inputs) { QString res = HRSchemaSerializer::TAB + HRSchemaSerializer::OUTPUT_START + " {\n"; foreach(const DataConfig cfg, inputs) { res += HRSchemaSerializer::TAB + HRSchemaSerializer::TAB + cfg.attrName + " {\n"; res += HRSchemaSerializer::TAB + HRSchemaSerializer::TAB + HRSchemaSerializer::TAB + "type:" + cfg.type + ";\n"; res += HRSchemaSerializer::TAB + HRSchemaSerializer::TAB + HRSchemaSerializer::TAB + "format:" + cfg.format + ";\n"; if(!cfg.description.isEmpty()) { res += HRSchemaSerializer::TAB + HRSchemaSerializer::TAB + HRSchemaSerializer::TAB + "description:\"" + cfg.description + "\";\n"; } res += HRSchemaSerializer::TAB + HRSchemaSerializer::TAB + "}\n"; } res += HRSchemaSerializer::TAB + "}\n"; return res; } static QString attributesDefinition(const QList &attrs) { QString res = HRSchemaSerializer::TAB + HRSchemaSerializer::ATTRIBUTES_START + " {\n"; foreach(const AttributeConfig &cfg, attrs) { res += HRSchemaSerializer::TAB + HRSchemaSerializer::TAB + cfg.attrName + " {\n"; res += HRSchemaSerializer::TAB + HRSchemaSerializer::TAB + HRSchemaSerializer::TAB + "type:" + cfg.type + ";\n"; if(!cfg.description.isEmpty()) { res += HRSchemaSerializer::TAB + HRSchemaSerializer::TAB + HRSchemaSerializer::TAB + "description:\"" + cfg.description + "\";\n"; } res += HRSchemaSerializer::TAB + HRSchemaSerializer::TAB + "}\n"; } res += HRSchemaSerializer::TAB + "}\n"; return res; } QString HRSchemaSerializer::actor2String(ExternalProcessConfig *cfg ) { QString res = HRSchemaSerializer::HEADER_LINE + "\n"; res += "\"" + cfg->name + "\" {\n"; res += inputsDefenition(cfg->inputs); res += outputsDefenition(cfg->outputs); res += attributesDefinition(cfg->attrs); res += HRSchemaSerializer::TAB + HRSchemaSerializer::CMDLINE + ":\"" + cfg->cmdLine + "\";\n"; if(!cfg->description.isEmpty()) { res += HRSchemaSerializer::TAB + HRSchemaSerializer::DESCRIPTION + ":\"" + cfg->description + "\";\n"; } if(!cfg->templateDescription.isEmpty()) { res += HRSchemaSerializer::TAB + HRSchemaSerializer::PROMPTER + ":\"" + cfg->templateDescription + "\";\n"; } res += "}"; return res; } } // U2ugene-1.9.8/src/corelibs/U2Lang/src/model/0000755000175000017500000000000011651544333016667 5ustar ilyailyaugene-1.9.8/src/corelibs/U2Lang/src/model/QDConstraint.h0000644000175000017500000000632511651544333021417 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_QD_CONSTRAINT_H_ #define _U2_QD_CONSTRAINT_H_ #include namespace U2 { typedef QString QDConstraintType; class U2LANG_EXPORT QDConstraintTypes { public: static const QDConstraintType DISTANCE; }; class U2LANG_EXPORT QDConstraint { public: QDConstraint(const QList& _units, QDConstraintType _type=QDConstraintTypes::DISTANCE) : cfg(NULL), type(_type), units(_units) {} virtual ~QDConstraint() {} QDParameters* getParameters() const { return cfg; } const QList& getSchemeUnits() const { return units; } virtual QDConstraintType constraintType() const { return type; } virtual QString getText(QDSchemeUnit* u1, QDSchemeUnit* u2) const=0; virtual bool drawArrow(QDSchemeUnit* u1, QDSchemeUnit* u2) const=0; void setUIEditor(ConfigurationEditor* ed) { cfg->setEditor(ed); } protected: QDParameters* cfg; QDConstraintType type; QList units; }; enum QDDistanceType {E2S, E2E, S2S, S2E}; class U2LANG_EXPORT QDDistanceConstraint : public QDConstraint { public: QDDistanceConstraint(const QList& _units, QDDistanceType type, int min, int max); virtual ~QDDistanceConstraint(); QDSchemeUnit* getSource() const { return units.at(0); } QDSchemeUnit* getDestination() const { return units.at(1); } int getMin() const; int getMax() const; void setMin(int min); void setMax(int max); QDDistanceType distanceType() const { return distType; } QString getText(QDSchemeUnit*, QDSchemeUnit*) const; bool drawArrow(QDSchemeUnit*, QDSchemeUnit*) const { return true; } void invert(); private: QDDistanceType distType; }; class U2LANG_EXPORT QDConstraintController { public: static const QString DISTANCE_CONSTRAINT_EL; static const QString TYPE_ATTR; static const QString MIN_LEN_ATTR; static const QString MAX_LEN_ATTR; static const QString SRC_ATTR; static const QString DST_ATTR; public: static bool match(QDConstraint* c, const QDResultUnit& r1, const QDResultUnit& r2, bool complement = false); static U2Region matchLocation(QDDistanceConstraint* dc, const QDResultUnit& r, bool complement = false); static QDDistanceType getInvertedType(QDDistanceType type); private: static bool match(const U2Region& srcReg, const U2Region& dstReg, QDDistanceType type, int min, int max); }; }//namespace #endif ugene-1.9.8/src/corelibs/U2Lang/src/model/Datatype.h0000644000175000017500000001223711651544333020620 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_WORKFLOW_DATATYPE_H_ #define _U2_WORKFLOW_DATATYPE_H_ #include #include #include namespace U2 { class DataType; typedef QExplicitlySharedDataPointer DataTypePtr; /** * represents a type for every data actor work with * all data got from user has some Datatype * all data passed from actor to actor has some Datatype */ class U2LANG_EXPORT DataType : public Descriptor, public QSharedData { public: // there are 3 types of Datatype enum Kind { // simple types: string, int, bool, sequence, msa... Single, // complex types // used as types of ports // Data between actors passed as values of such complex types // list - list of values of some type List, // Map Map }; // Kind DataType(const QString& id, const QString& name, const QString& desc); DataType(const Descriptor& d); virtual ~DataType() {} /*virtual bool equals(DataTypePtr t) const {return t == this;} */ // default kind() is Single virtual Kind kind() const; inline bool isSingle() const {return kind() == Single;} inline bool isMap() const {return kind() == Map;} inline bool isList() const {return kind() == List;} // default: empty descriptor // in map type: corresponding descriptor // in list type: element type virtual DataTypePtr getDatatypeByDescriptor(const Descriptor& idd=Descriptor(QString())) const; // used only in map type: returns list of all types from map // default: empty list virtual QList getAllDescriptors() const; // used only in map type // default: empty map virtual QMap getDatatypesMap() const; // finds Descriptor identified with 'id' in list of Descriptors from getAllDescriptors function Descriptor getDatatypeDescriptor(const QString& id) const; }; // DataType /** * represents complex type. * in fact, map of pairs (Descriptor, Datatype) * Usage: for passing many objects of different types (see IntegralBusType) */ class U2LANG_EXPORT MapDataType : public DataType { public: MapDataType(const Descriptor& d, const QMap& m); // reimplemented from Datatype virtual DataType::Kind kind() const; virtual DataTypePtr getDatatypeByDescriptor(const Descriptor& d) const; virtual QList getAllDescriptors() const; virtual QMap getDatatypesMap() const; protected: // types map QMap map; }; // MapDataType /** * represents complex type * list of elements of 1 type */ class U2LANG_EXPORT ListDataType : public DataType { public: ListDataType(const Descriptor& d, DataTypePtr el); // reimplemented from Datatype virtual DataType::Kind kind() const; virtual DataTypePtr getDatatypeByDescriptor(const Descriptor& idd=Descriptor(QString())) const; protected: // DataTypePtr listElementDatatype; }; // ListDataType /** * standard registry for datatypes * we use it because we want to have 1 instance of each datatype * and place where we can get it * usage: see BaseTypes */ class DataTypeRegistry { public: virtual ~DataTypeRegistry(); virtual DataTypePtr getById(const QString& id) const; virtual bool registerEntry(DataTypePtr t); virtual DataTypePtr unregisterEntry(const QString& id); virtual QList getAllEntries() const; virtual QList getAllIds() const; protected: // standard map QMap registry; }; // DataTypeRegistry /** * abstract factory for creating values from String * used in cmdline: user pass values for attributes, we need convert them to qvariants * because attributes saves values in qvariant */ class DataTypeValueFactory { public: DataTypeValueFactory() {} virtual ~DataTypeValueFactory() {} virtual QVariant getValueFromString( const QString & str, bool * ok = NULL ) const = 0; virtual QString getId() const = 0; }; // DataTypeValueFactory /** * Standard registry for DatatypeValueFactories */ typedef IdRegistry DataTypeValueFactoryRegistry; } //namespace U2 #endif // _U2_WORKFLOW_DATATYPE_H_ ugene-1.9.8/src/corelibs/U2Lang/src/model/ActorPrototypeRegistry.h0000644000175000017500000000336111651544333023572 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_WORKFLOW_REG_H_ #define _U2_WORKFLOW_REG_H_ #include namespace U2 { namespace Workflow { /** * registry of actor prototypes * register proto to one of groups - computational categories * * Base categories are listed in BioActorLibrary */ class U2LANG_EXPORT ActorPrototypeRegistry: public QObject { Q_OBJECT public: virtual ~ActorPrototypeRegistry(); // standard registry void registerProto(const Descriptor& group, ActorPrototype* proto); ActorPrototype* unregisterProto(const QString& id); const QMap >& getProtos() const {return groups;} ActorPrototype* getProto(const QString& id) const; signals: void si_registryModified(); private: QMap > groups; }; // ActorPrototypeRegistry }//namespace Workflow }//namespace U2 #endif // _U2_WORKFLOW_REG_H_ ugene-1.9.8/src/corelibs/U2Lang/src/model/QDScheme.cpp0000644000175000017500000006532511651544333021037 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "QDScheme.h" #include "QDConstraint.h" #include #include namespace U2 { void QDParameters::setParameter(const QString& name, const QVariant& val) { Configuration::setParameter(name, val); emit si_modified(); } //QDActor ////////////////////////////////////////////////////////////////////////// const int QDActor::DEFAULT_MAX_RESULT_LENGTH(10000); QDActor::QDActor(QDActorPrototype const* _proto) : scheme(NULL), proto(_proto), strand(QDStrand_Both), simmetric(false) { cfg = new QDActorParameters; foreach(Attribute* a, proto->getParameters()) { cfg->addParameter(a->getId(), new Attribute(*a)); } ConfigurationEditor* ed = proto->getEditor(); if (ed) { cfg->setEditor(ed); } const QMap& attrs = cfg->getParameters(); QMapIterator it(attrs); while (it.hasNext()) { it.next(); defaultCfg[it.key()] = it.value()->getAttributePureValue(); } } QDActor::~QDActor() { qDeleteAll(paramConstraints); delete cfg; } void QDActor::reset() { const QMap& attrs = cfg->getParameters(); foreach(const QString& key, attrs.keys()) { Attribute* a = attrs[key]; a->setAttributeValue(defaultCfg.value(key)); } } bool contains(const QDResultUnit& res, const QVector& location) { foreach(const U2Region& r, location) { if (r.contains(res->region)) { return true; } } return false; } void QDActor::filterResults(const QVector& ) { /*QList res = results; foreach(QDResultGroup* grp, res) { foreach(const QDResultUnit& ru, grp->getResultsList()) { if (!contains(ru, location)) { results.removeOne(grp); break; } } }*/ } QList QDActor::popResults() { QList res = results; results.clear(); return res; } static const QString KEY_ATTR = "key"; QList< QPair > QDActor::saveConfiguration() const { QList< QPair > res; QMapIterator it(cfg->getParameters()); QString annKey = cfg->getAnnotationKey(); if (annKey.contains(' ')) { annKey = "\"" + annKey + "\""; } res.append(qMakePair(KEY_ATTR, annKey)); while (it.hasNext()) { it.next(); Attribute* a = it.value(); if (a->getAttributePureValue()==defaultCfg.value(it.key())) { continue; } //QString displayName = QDAttributeNameConverter::convertAttrName(a->getDisplayName()); QString displayName = a->getId(); QPair newAttr = qMakePair(displayName, a->getAttributePureValue().toString()); res.append(newAttr); } return res; } void QDActor::loadConfiguration(const QList< QPair >& strMap) { foreach(const StringAttribute& attr, strMap) { if ( attr.first==KEY_ATTR ) { cfg->setAnnotationKey(attr.second); } QMapIterator paramsIterator(cfg->getParameters()); while(paramsIterator.hasNext()) { paramsIterator.next(); Attribute* a = paramsIterator.value(); if (QDAttributeNameConverter::convertAttrName(a->getId())==attr.first) { QVariant val = QDAttributeValueMapper::stringToAttributeValue(attr.second); cfg->setParameter(a->getId(), val); break; } } } } QDStrandOption QDActor::getStrandToRun() const { QDStrandOption schemaStrand = scheme->getStrand(); QDStrandOption strand2run = QDStrand_Both; if (schemaStrand!=QDStrand_Both) { if (schemaStrand==QDStrand_DirectOnly) { strand2run = strand; } if (schemaStrand==QDStrand_ComplementOnly) { if (strand==QDStrand_DirectOnly) { strand2run = QDStrand_ComplementOnly; } if (strand==QDStrand_ComplementOnly) { strand2run = QDStrand_DirectOnly; } } } return strand2run; } QDStrandOption QDActor::getStrand() const { if (hasStrand()) { return strand; } //return QDStrand_DirectOnly; return QDStrand_Both; } void QDActor::setStrand( QDStrandOption stOp ) { strand = stOp; emit si_strandChanged(strand); } QList QDActor::getConstraints() const { QList res; foreach(QDSchemeUnit* su, units) { res << su->getConstraints(); } return res; } //QDSchemeUnit ////////////////////////////////////////////////////////////////////////// QString QDSchemeUnit::getPersonalName() const { const QList& units = actor->getSchemeUnits(); if(units.size()==1) { return actor->getParameters()->getLabel(); } QDSchemeUnit* s = const_cast(this); assert(units.contains(s)); int idx = units.indexOf(s) + 1; QString result = QString("%1_%2") .arg(actor->getParameters()->getLabel()) .arg(QString::number(idx)); return result; } QList QDSchemeUnit::getDistanceConstraints() const { QList res; foreach(QDConstraint* c, schemeConstraints) { QDDistanceConstraint* dc = static_cast(c); if (dc) { res.append(dc); } } return res; } //QDScheme ////////////////////////////////////////////////////////////////////////// QDScheme::~QDScheme() { foreach(QDActor* a, actors) { removeActor(a); } } void QDScheme::addActor(QDActor* a) { assert(!actors.contains(a)); assert(a->scheme==NULL); foreach(QDSchemeUnit* su, a->getSchemeUnits()) { assert(su->getConstraints().isEmpty()); Q_UNUSED(su); } a->scheme = this; actors.append(a); emit si_schemeChanged(); } bool QDScheme::removeActor(QDActor* a) { if(actors.contains(a)) { foreach(QDSchemeUnit* su, a->getSchemeUnits()) { foreach(QDConstraint* c, su->getConstraints()) { removeConstraint(c); } } actors.removeOne(a); const QString& ag = getActorGroup(a); if (!ag.isEmpty()) { actorGroups[ag].removeOne(a); } delete a; emit si_schemeChanged(); return true; } return false; } void QDScheme::addConstraint(QDConstraint* constraint) { foreach(QDSchemeUnit* su, constraint->getSchemeUnits()) { assert(actors.contains(su->getActor())); su->schemeConstraints.append(constraint); } emit si_schemeChanged(); } void QDScheme::removeConstraint(QDConstraint* constraint) { const QList& constraintUnits = constraint->getSchemeUnits(); foreach(QDSchemeUnit* su, constraintUnits) { QDActor* actor = su->getActor(); Q_UNUSED(actor); assert(actors.contains(actor)); assert(su->getConstraints().contains(constraint)); su->schemeConstraints.removeOne(constraint); } delete constraint; emit si_schemeChanged(); } QList QDScheme::getConstraints() const { QList res; foreach(QDActor* actor, actors) { foreach(QDSchemeUnit* su, actor->getSchemeUnits()) { foreach(QDConstraint* c, su->getConstraints()) { if (!res.contains(c)) { res.append(c); } } } } return res; } QList QDScheme::getConstraints(QDSchemeUnit const* su1, QDSchemeUnit const* su2) const { QList sharedConstraints; const QList& su1Cons = su1->getConstraints(); const QList& su2Cons = su2->getConstraints(); foreach(QDConstraint* con, su1Cons) { if (su2Cons.contains(con)) { sharedConstraints.append(con); } } return sharedConstraints; } void QDScheme::clear() { //delete dna; dna = NULL; foreach(QDActor* a, actors) { removeActor(a); } actorGroups.clear(); emit si_schemeChanged(); } QList currentRoute; QList< QList > routes; QDSchemeUnit* routeDst = NULL; QList QDScheme::findPaths(QDSchemeUnit* src, QDSchemeUnit* dst) { assert(currentRoute.isEmpty()); assert(routes.isEmpty()); assert(!routeDst); routeDst = dst; currentRoute.append(src); findRoute(src); QList res; foreach(const QList& route, routes) { QList paths; for (int i=0, m=route.size()-1; i joint = getConstraints(src, dst); //include "parameter" constraints foreach(QDConstraint* con, src->getActor()->getParamConstraints()) { if (con->getSchemeUnits().contains(src) && con->getSchemeUnits().contains(dst)) { joint.append(con); } } QList jointCons; foreach(QDConstraint* con, joint) { QDDistanceConstraint* dc = static_cast(con); if (dc) { jointCons.append(dc); } } assert(!jointCons.isEmpty()); if (paths.isEmpty()) { foreach(QDDistanceConstraint* dc, jointCons) { QDPath* newPath = new QDPath; bool ok = newPath->addConstraint(dc); assert(ok); Q_UNUSED(ok); paths << newPath; } } else { QList newPaths; for (int i=1, n=jointCons.size(); iclone(); bool ok = newPath->addConstraint(jointCons.at(i)); assert(ok); Q_UNUSED(ok); newPaths.append(newPath); } } foreach(QDPath* path, paths) { bool ok = path->addConstraint(jointCons.at(0)); assert(ok); Q_UNUSED(ok); } paths << newPaths; } } res.append(paths); } currentRoute.clear(); routes.clear(); routeDst = NULL; return res; } void QDScheme::findRoute(QDSchemeUnit* curSu) { if (curSu==routeDst) { routes.append(currentRoute); } else { //build list of adjacent vertexes QList adjacentList; QList dcList = curSu->getDistanceConstraints(); //include "parameter" constraints foreach(QDConstraint* con, curSu->getActor()->getParamConstraints()) { if (con->constraintType()==QDConstraintTypes::DISTANCE) { QDDistanceConstraint* dc = static_cast(con); if (dc->getSchemeUnits().contains(curSu)) { dcList.append(dc); } } } foreach(QDDistanceConstraint* dc, dcList) { QDSchemeUnit* adj = NULL; QDSchemeUnit* dcSrc = dc->getSource(); QDSchemeUnit* dcDst = dc->getDestination(); if (curSu==dcSrc) { adj = dcDst; } else { assert(curSu==dcDst); adj = dcSrc; } if (!adjacentList.contains(adj)) { adjacentList.append(adj); } } foreach(QDSchemeUnit* adj, adjacentList) { if (!currentRoute.contains(adj)) { currentRoute.append(adj); findRoute(adj); currentRoute.removeOne(adj); } } } } //QDPath ////////////////////////////////////////////////////////////////////////// QDPath::~QDPath() { delete overallConstraint; } QDPath* QDPath::clone() const { QDPath* cln = new QDPath; cln->constraints = constraints; cln->pathSrc = pathSrc; cln->pathDst = pathDst; return cln; } bool QDPath::addConstraint(QDDistanceConstraint* dc) { assert(!constraints.contains(dc)); QDSchemeUnit* dcSrc = dc->getSource(); QDSchemeUnit* dcDst = dc->getDestination(); if (!pathSrc) { assert(!pathDst); pathSrc = dcSrc; pathDst = dcDst; constraints.append(dc); schemeUnits << pathSrc << pathDst; } else if (pathDst==dcSrc) { pathDst = dcDst; constraints.append(dc); schemeUnits << pathDst; } else if (pathDst==dcDst) { pathDst = dcSrc; constraints.append(dc); schemeUnits << pathDst; } else if (pathSrc==dcSrc) { pathSrc = dcDst; constraints.prepend(dc); schemeUnits << pathSrc; } else if (pathSrc==dcDst) { pathSrc = dcSrc; constraints.prepend(dc); schemeUnits << pathSrc; } else { return false; } return true; } QDDistanceConstraint* QDPath::toConstraint() { if (constraints.isEmpty()) { return NULL; } delete overallConstraint; int minDist=0, maxDist=0; QDSchemeUnit* curSu = pathSrc; for (int i=0, n=constraints.size(); igetSource(); QDSchemeUnit* curDcDst = curDc->getDestination(); if (curSu==curDcSrc) { curSu = curDcDst; minDist += curDc->getMin(); maxDist += curDc->getMax(); if (!nextDc) { continue; } QDSchemeUnit* nextDcSrc = nextDc->getSource(); QDSchemeUnit* nextDcDst = nextDc->getDestination(); if (nextDcSrc==curSu) { if (curDc->distanceType()==S2S || curDc->distanceType()==E2S) { if (nextDc->distanceType()==E2S || nextDc->distanceType()==E2E) { minDist+=curSu->getActor()->getMinResultLen(); maxDist+=curSu->getActor()->getMaxResultLen(); } } else { // S2E || E2E if (nextDc->distanceType()==S2S || nextDc->distanceType()==S2E) { minDist-=curSu->getActor()->getMaxResultLen(); maxDist-=curSu->getActor()->getMinResultLen(); } } } else { assert(nextDcDst==curSu); Q_UNUSED(nextDcDst); if (curDc->distanceType()==E2S || curDc->distanceType()==S2S) { if (nextDc->distanceType()==S2E || nextDc->distanceType()==E2E) { minDist+=curSu->getActor()->getMinResultLen(); maxDist+=curSu->getActor()->getMaxResultLen(); } } else { // S2E || E2E if (nextDc->distanceType()==S2S || nextDc->distanceType()==E2S) { minDist-=curSu->getActor()->getMaxResultLen(); maxDist-=curSu->getActor()->getMinResultLen(); } } } } else { assert(curSu==curDcDst); curSu = curDcSrc; minDist -= curDc->getMax(); maxDist -= curDc->getMin(); if (!nextDc) { continue; } QDSchemeUnit* nextDcSrc = nextDc->getSource(); QDSchemeUnit* nextDcDst = nextDc->getDestination(); if (nextDcSrc==curSu) { if (curDc->distanceType()==S2S || curDc->distanceType()==S2E) { if (nextDc->distanceType()==E2S || nextDc->distanceType()==E2E) { minDist+=curSu->getActor()->getMinResultLen(); maxDist+=curSu->getActor()->getMaxResultLen(); } } else { // E2S || E2E if (nextDc->distanceType()==S2S || nextDc->distanceType()==S2E) { minDist-=curSu->getActor()->getMaxResultLen(); maxDist-=curSu->getActor()->getMinResultLen(); } } } else { assert(nextDcDst==curSu); Q_UNUSED(nextDcDst); if (curDc->distanceType()==E2S || curDc->distanceType()==E2E) { if (nextDc->distanceType()==S2S || nextDc->distanceType()==E2S) { minDist-=curSu->getActor()->getMaxResultLen(); maxDist-=curSu->getActor()->getMinResultLen(); } } else { // S2E || S2S if (nextDc->distanceType()==S2E || nextDc->distanceType()==E2E) { minDist+=curSu->getActor()->getMinResultLen(); maxDist+=curSu->getActor()->getMaxResultLen(); } } } } } if (maxDist units; units << pathSrc << pathDst; QDDistanceType distType = E2S; if (pathSrc==firstDc->getSource()) { if (pathDst==lastDc->getSource()) { if (firstDc->distanceType()==S2S || firstDc->distanceType()==S2E) { if (lastDc->distanceType()==S2S || lastDc->distanceType()==S2E) { distType = S2S; } else { // E2S || E2E distType = S2E; } } else { // E2S || E2E if (lastDc->distanceType()==S2S || lastDc->distanceType()==S2E) { distType = E2S; } else { // E2S || E2E distType = E2E; } } } else { assert(pathDst==lastDc->getDestination()); if (firstDc->distanceType()==S2S || firstDc->distanceType()==S2E) { if (lastDc->distanceType()==S2S || lastDc->distanceType()==E2S) { distType = S2S; } else { // S2E || E2E distType = S2E; } } else { // E2S || E2E if (lastDc->distanceType()==S2S || lastDc->distanceType()==E2S) { distType = E2S; } else { // S2E || E2E distType = E2E; } } } } else { assert(pathSrc==firstDc->getDestination()); if (pathDst==lastDc->getSource()) { if (firstDc->distanceType()==S2S || firstDc->distanceType()==E2S) { if (lastDc->distanceType()==S2S || lastDc->distanceType()==S2E) { distType = S2S; } else { // E2S || E2E distType = S2E; } } else { // S2E || E2E if (lastDc->distanceType()==E2S || lastDc->distanceType()==E2E) { distType = E2E; } else { // S2S || S2E distType = E2S; } } } else { assert(pathDst==lastDc->getDestination()); if (firstDc->distanceType()==S2S || firstDc->distanceType()==E2S) { if (lastDc->distanceType()==S2S || lastDc->distanceType()==E2S) { distType = S2S; } else { // S2E || E2E distType = S2E; } } else { // S2E || E2E if (lastDc->distanceType()==S2S || lastDc->distanceType()==E2S) { distType = E2S; } else { // S2E || E2E distType = E2E; } } } } overallConstraint = new QDDistanceConstraint(units, distType, minDist, maxDist); return overallConstraint; } void QDScheme::setOrder(QDActor* a, int serialNum) { assert(actors.contains(a)); int aIdx = actors.indexOf(a); if (serialNum<0) { actors.move(aIdx, 0); return; } if (serialNum>=actors.size()) { actors.move(aIdx, actors.size()-1); return; } actors.move(aIdx, serialNum); } bool QDScheme::isValid() const { bool res = true; foreach(QDActor* actor, getActors()) { QDActorParameters* cfg = actor->getParameters(); QStringList errorList; if (!cfg->validate(errorList)) { res = false; foreach(const QString& errMsg, errorList) { coreLog.error(QObject::tr("%1. %2").arg(cfg->getLabel()).arg(errMsg)); } } } foreach(QDConstraint* con, getConstraints()) { if (con->constraintType()==QDConstraintTypes::DISTANCE) { QDDistanceConstraint* dc = static_cast(con); if (dc->getMin()>dc->getMax()) { coreLog.error(QObject::tr("Invalid distance values")); res = false; } QDActor* src = dc->getSource()->getActor(); QDActor* dst = dc->getDestination()->getActor(); QString group = getActorGroup(src); if (!group.isEmpty() && getActors(group).contains(dst)) { coreLog.error(QObject::tr("Constraints can not be placed between elements of the same group")); res = false; } } } return res; } QDActor* QDScheme::getActorByLabel(const QString& label) const { foreach(QDActor* a, actors) { if (a->getParameters()->getLabel()==label) { return a; } } return NULL; } void QDScheme::addActorToGroup( QDActor* a, const QString& group ) { assert(actors.contains(a)); assert(getActorGroup(a).isEmpty()); assert(actorGroups.keys().contains(group)); actorGroups[group].append(a); emit si_schemeChanged(); } bool QDScheme::removeActorFromGroup( QDActor* a ) { const QString& group = getActorGroup(a); if (!group.isEmpty()) { bool res = actorGroups[group].removeOne(a); if (res) { emit si_schemeChanged(); } } return false; } void QDScheme::createActorGroup( const QString& name ) { assert(validateGroupName(name)); assert(!actorGroups.keys().contains(name)); actorGroups.insert(name, QList()); actorGroupReqNum[name] = 1; emit si_schemeChanged(); } bool QDScheme::removeActorGroup( const QString& name ) { bool res = actorGroups.remove(name); emit si_schemeChanged(); return res; } QString QDScheme::getActorGroup( QDActor* a ) const { QMapIterator< QString, QList > i(actorGroups); while (i.hasNext()) { i.next(); if (i.value().contains(a)) { return i.key(); } } return QString(); } bool QDScheme::validateGroupName( const QString& name ) const { if (name.isEmpty()) { return false; } return true; } void QDScheme::setRequiredNum(const QString& group, int num) { assert(actorGroups.keys().contains(group)); const QList& grpMembrs = actorGroups.value(group); Q_UNUSED(grpMembrs); assert(num<=grpMembrs.size()); actorGroupReqNum[group] = num; emit si_schemeChanged(); } void QDScheme::adaptActorsOrder() { QList actorsQueue; foreach(QDActor* a, actors) { QString group = getActorGroup(a); if (group.isEmpty()) { assert(!actorsQueue.contains(a)); actorsQueue.append(a); } else if (!actorsQueue.contains(a)) { const QList& groupActors = getActors(group); actorsQueue.append(groupActors); } } actors = actorsQueue; } //QDResultGroup ////////////////////////////////////////////////////////////////////////// void QDResultGroup::add(const QDResultUnit& res) { if(results.isEmpty()) { startPos = res->region.startPos; endPos = res->region.endPos(); } else { if (res->region.startPos < startPos) { startPos = res->region.startPos; } if (res->region.endPos() > endPos) { endPos = res->region.endPos(); } } results.append(res); } void QDResultGroup::add(const QList& res) { foreach(const QDResultUnit& r, res) { add(r); } } void QDResultGroup::buildGroupFromSingleResult(const QDResultUnit& ru, QList& results) { QDStrandOption groupStrand = ru->strand == U2Strand::Direct ? QDStrand_DirectOnly : QDStrand_ComplementOnly; QDResultGroup* g = new QDResultGroup(groupStrand); g->add(ru); results.append(g); } //AttributeValueMapper ////////////////////////////////////////////////////////////////////////// const QMap QDAttributeValueMapper::BOOLEAN_MAP(initBooleanMap()); QMap QDAttributeValueMapper::initBooleanMap() { QMap map; map.insertMulti("true", true); map.insertMulti("yes", true); map.insertMulti("1", true); map.insertMulti("false", false); map.insertMulti("no", false); map.insertMulti("0", false); return map; } QVariant QDAttributeValueMapper::stringToAttributeValue(const QString& str) { if (getType(str)==BOOLEAN_TYPE) { return qVariantFromValue(BOOLEAN_MAP.value(str)); } return qVariantFromValue(str); } QDAttributeValueMapper::ValueType QDAttributeValueMapper::getType(const QString& val) { if (BOOLEAN_MAP.keys().contains(val)) { return BOOLEAN_TYPE; } else { return UNKNOWN_TYPE; } } }//namespace ugene-1.9.8/src/corelibs/U2Lang/src/model/ActorPrototypeRegistry.cpp0000644000175000017500000000432311651544333024124 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include namespace U2 { namespace Workflow { void ActorPrototypeRegistry::registerProto(const Descriptor& group, ActorPrototype* proto) { // debug check for proto name QString id = proto->getId(); Q_UNUSED(id); assert(!id.contains(".")); groups[group].append(proto); emit si_registryModified(); } ActorPrototype* ActorPrototypeRegistry::unregisterProto(const QString& id) { QMap >::iterator it; for (it = groups.begin(); it != groups.end(); ++it) { QList& l = it.value(); foreach(ActorPrototype* p, l) { if (p->getId() == id) { l.removeAll(p); if (l.isEmpty()) { groups.remove(it.key()); } emit si_registryModified(); return p; } } } return NULL; } ActorPrototype* ActorPrototypeRegistry::getProto(const QString& id) const { foreach(QList l, groups.values()) { foreach(ActorPrototype* p, l) { if (p->getId() == id) { return p; } } } return NULL; } ActorPrototypeRegistry::~ActorPrototypeRegistry() { foreach(QList l, groups) { qDeleteAll(l); } groups.clear(); } }//namespace Workflow }//namespace U2 ugene-1.9.8/src/corelibs/U2Lang/src/model/Descriptor.cpp0000644000175000017500000000423611651544333021516 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include #include "Descriptor.h" namespace U2 { /************************** * Descriptor **************************/ Descriptor::Descriptor(const QString& id, const QString& name, const QString& doc) : id(id), name(name), desc(doc) { } Descriptor::Descriptor(const QString& _id) : id(_id), name(_id), desc(_id) { } Descriptor::Descriptor(const char* _id) : id(_id), name(_id), desc(_id) { } Descriptor::Descriptor() { } QString Descriptor::getId() const { return id; } QString Descriptor::getDisplayName() const { return name; } QString Descriptor::getDocumentation() const { return desc; } void Descriptor::setId(const QString& i) { id = i; } void Descriptor::setDocumentation(const QString& d) { desc = d; } void Descriptor::setDisplayName(const QString& n) { name = n; } /************************** * VisualDescriptor **************************/ VisualDescriptor::VisualDescriptor(const Descriptor& d, const QString & _iconPath) : Descriptor(d), iconPath(_iconPath) { } void VisualDescriptor::setIconPath( const QString & ip ) { iconPath = ip; } QIcon VisualDescriptor::getIcon() { if( icon.isNull() && !iconPath.isEmpty() ) { icon = QIcon(iconPath); } return icon; } void VisualDescriptor::setIcon( QIcon i ) { assert( iconPath.isEmpty() ); icon = i; } } // U2 ugene-1.9.8/src/corelibs/U2Lang/src/model/WorkflowManager.h0000644000175000017500000000673611651544333022161 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_WORKFLOW_MNGR_H_ #define _U2_WORKFLOW_MNGR_H_ #include #include #include #include #include #include #include #include #include #include #include namespace U2 { namespace Workflow { /** * Worker represents actor at runtime * takes input data from and puts output data to CommunicationChannels * * base class */ class U2LANG_EXPORT Worker { public: virtual ~Worker() {} // initialize input and output ports virtual void init() = 0; // if data in the ports is ready virtual bool isReady() = 0; // get data from actor and return task // if you want your worker support scripting: // use BaseWorker::getMessageAndSetupScriptValues to take data from port virtual Task* tick() = 0; // nothing to do virtual bool isDone() = 0; // opened files, etc... virtual void cleanup() = 0; }; // Worker /** * runtime state of worker */ enum WorkerState { WorkerWaiting, WorkerReady, WorkerRunning, WorkerDone }; // WorkerState /** * Worker for whole schema * can decide if workers can run in parallel or any other analysis */ class U2LANG_EXPORT Scheduler : public Worker { public: virtual WorkerState getWorkerState(ActorId) = 0; }; // Scheduler /** * represents controller between actor and runtime realizations of actor (Worker) * is a container of such controllers (inherits IdRegistry) * represents set of tasks of some computational domain * * says how to execute your worker (Scheduler and CommunicationChannel) * Usage: create execution domain factory (e.g. LocalDomainFactory) and register there your tasks factories */ class U2LANG_EXPORT DomainFactory : public IdRegistry, public Descriptor { public: DomainFactory(const Descriptor& d) : Descriptor(d) {} DomainFactory(const QString& id) : Descriptor(id) {} virtual ~DomainFactory(){} // computational tasks domain virtual Worker* createWorker(Actor*) = 0; // execution domain virtual CommunicationChannel* createConnection(Link*) {return NULL;} virtual Scheduler* createScheduler(Schema*) {return NULL;} virtual void destroy(Scheduler*, Schema*) {} }; // DomainFactory /** * standard registry of factories * Usage: register here execution domain factories (see usage of DomainFactory) */ class U2LANG_EXPORT DomainFactoryRegistry : public IdRegistry { }; // DomainFactoryRegistry }//Workflow namespace }//GB2 namespace #endif ugene-1.9.8/src/corelibs/U2Lang/src/model/QueryDesignerRegistry.h0000644000175000017500000000274611651544333023370 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_QUERY_DESIGNER_REGISTRY_H_ #define _U2_QUERY_DESIGNER_REGISTRY_H_ #include "QDScheme.h" #include namespace U2 { class U2LANG_EXPORT QDActorPrototypeRegistry : public QObject, public IdRegistry { Q_OBJECT public: void registerProto(QDActorPrototype* _factory); QDActorPrototype* unregisterProto(const QString& id); QList getProtos() { return IdRegistry::getAllEntries(); } QDActorPrototype* getProto(const QString& id) { return IdRegistry::getById(id); } signals: void si_registryModified(); }; }//namespace #endif ugene-1.9.8/src/corelibs/U2Lang/src/model/ActorModel.cpp0000644000175000017500000002033211651544333021424 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "ActorModel.h" #include "ConfigurationEditor.h" namespace U2 { namespace Workflow { /************************** * Actor **************************/ Actor::Actor(ActorPrototype* proto, AttributeScript * _script) : proto(proto), doc(NULL), script(_script) { if(script == NULL) { if(proto->isScriptFlagSet()) { script = new AttributeScript(); script->setScriptText(""); } else { script = NULL; } } if(script != NULL) { setupVariablesForPort(); setupVariablesForAttribute(); } } Actor::Actor(const Actor&) : QObject(), Configuration(), Peer() { assert(false); } Actor::~Actor() { qDeleteAll(ports.values()); delete doc; delete script; } void Actor::setupVariablesForPort() { foreach(const PortDescriptor *descr, proto->getPortDesciptors()) { QString prefix; if(descr->isInput()) { prefix = "in_"; } else { prefix = "out_"; } DataTypePtr dataTypePtr = descr->getType(); if(dataTypePtr->isMap()) { QMap map = dataTypePtr->getDatatypesMap(); foreach(const Descriptor & d, map.keys()) { Descriptor var(prefix + d.getId(), d.getDisplayName(), d.getDocumentation()); script->setScriptVar(var, QVariant()); } } else if(dataTypePtr->isList()) { foreach(const Descriptor & typeDescr, dataTypePtr->getAllDescriptors()) { Descriptor var(prefix + typeDescr.getId(), typeDescr.getDisplayName(), typeDescr.getDocumentation()); script->setScriptVar(var, QVariant()); } } else { QString id = prefix + dataTypePtr->getId(); QString displayName = dataTypePtr->getDisplayName(); QString doc = prefix + dataTypePtr->getDocumentation(); script->setScriptVar(Descriptor(id,displayName,doc), QVariant()); } } } void Actor::setupVariablesForAttribute() { foreach( Attribute * attribute, proto->getAttributes() ) { assert(attribute != NULL); QString attrVarName = attribute->getDisplayName(); script->setScriptVar(Descriptor(attribute->getId().replace(".","_"), attrVarName.replace(".", "_"), attribute->getDocumentation()), QVariant()); } } AttributeScript * Actor::getScript() const { return script; } void Actor::setScript(AttributeScript* _script) { script->setScriptText(_script->getScriptText()); } ActorPrototype * Actor::getProto() const { return proto; } ActorId Actor::getId() const { return QString("%1").arg( (int) (size_t) this); } QString Actor::getLabel() const { if( label.isEmpty() ) { return QString("%1 %2").arg(getProto()->getDisplayName()).arg(getId()); } else { return label; } } void Actor::setLabel(const QString& l) { label = l; emit si_labelChanged(); } Port * Actor::getPort(const QString& id) const { return ports.value(id); } QList Actor::getPorts() const { return ports.values(); } QList Actor::getInputPorts() const { QList l; foreach (Port* p, ports.values()) if (p->isInput()) l< Actor::getOutputPorts() const { QList l; foreach (Port* p, ports.values()) if (p->isOutput()) l< & Actor::getParamAliases() const { return paramAliases; } QMap & Actor::getParamAliases() { return paramAliases; } bool Actor::hasParamAliases() const { return !paramAliases.isEmpty(); } const QMap & Actor::getAliasHelp() const { return aliasHelpDescs; } QMap & Actor::getAliasHelp() { return aliasHelpDescs; } bool Actor::hasAliasHelp() const { foreach(const QString & alias, paramAliases.values()) { if(aliasHelpDescs.contains(alias)) { return true; } } return false; } void Actor::remap(const QMap& m) { foreach(Port* p, ports) { p->remap(m); } } /************************** * ActorPrototype **************************/ QList ActorPrototype::getPortDesciptors() const { return ports; } QList ActorPrototype::getAttributes() const { return attrs; } void ActorPrototype::addAttribute( Attribute * a ) { assert(a != NULL); attrs << a; } int ActorPrototype::removeAttribute( Attribute * attr ) { assert(attr != NULL); return attrs.removeAll( attr ); } void ActorPrototype::setEditor(ConfigurationEditor* e) { assert(e != NULL); ed = e; } ConfigurationEditor * ActorPrototype::getEditor()const { return ed; } void ActorPrototype::setValidator(ConfigurationValidator* v) { assert(v != NULL); val = v; } void ActorPrototype::setPrompter(Prompter* p) { assert(p != NULL); prompter = p; } void ActorPrototype::setPortValidator(const QString& id, ConfigurationValidator* v) { assert(v != NULL); portValidators[id] = v; } bool ActorPrototype::isAcceptableDrop(const QMimeData*, QVariantMap* ) const { return false; } Port* ActorPrototype::createPort(const PortDescriptor& d, Actor* p) { return new Port(d, p); } Actor* ActorPrototype::createInstance(AttributeScript *script, const QVariantMap& params) { Actor* proc = new Actor(this, script); foreach(PortDescriptor* pd, getPortDesciptors()) { Port* p = createPort(*pd, proc); QString pid = pd->getId(); if (portValidators.contains(pid)) { p->setValidator(portValidators.value(pid)); } proc->ports[pid] = p; } foreach(Attribute* a, getAttributes()) { proc->addParameter(a->getId(), new Attribute(*a)); } if (ed) { proc->setEditor(ed); } if (val) { proc->setValidator(val); } if (prompter) { proc->setDescription(prompter->createDescription(proc)); } QMapIterator i(params); while (i.hasNext()) { i.next(); proc->setParameter(i.key(), i.value()); } return proc; } Attribute * ActorPrototype::getAttribute( const QString & id ) const { Attribute * res = NULL; foreach( Attribute * a, attrs ) { if( a->getId() == id ) { res = a; break; } } return res; } void ActorPrototype::setScriptFlag(bool flag) { isScript = flag; } ActorPrototype::ActorPrototype(const Descriptor& d, const QList& ports, const QList& attrs) : VisualDescriptor(d), attrs(attrs), ports(ports), ed(NULL), val(NULL), prompter(NULL), isScript(false) { } ActorPrototype::~ActorPrototype() { qDeleteAll(attrs); qDeleteAll(ports); delete ed; delete val; delete prompter; qDeleteAll(portValidators); } /************************** * ActorDocument **************************/ ActorDocument::ActorDocument(Actor* a) : QTextDocument(a), target(a) { } //void ActorDocument::update(const QVariantMap& ) { //} }//Workflow namespace }//GB2namespace ugene-1.9.8/src/corelibs/U2Lang/src/model/Schema.cpp0000644000175000017500000000777311651544333020611 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "Schema.h" #include "ActorModel.h" namespace U2 { namespace Workflow { /************************** * Schema **************************/ Schema::Schema() : deepCopy(false) { } Schema::~Schema() { reset(); } Schema::Schema( const Schema & other ) { *this = other; } Schema & Schema::operator =( const Schema & other ) { procs = other.procs; flows = other.flows; iterations = other.iterations; domain = other.domain; deepCopy = false; return *this; } void Schema::applyConfiguration(const Iteration& cfg, QMap remap) { foreach(Actor* a, procs) { ActorId id = remap.key(a->getId()); if (cfg.cfg.contains(id)) { a->setParameters(cfg.cfg.value(id)); } } } void Schema::reset() { if (deepCopy) { qDeleteAll(flows); flows.clear(); qDeleteAll(procs); procs.clear(); } } Actor* Schema::actorById( ActorId id) { foreach(Actor* a, procs) { if (a->getId() == id) { return a; } } return NULL; } int Schema::iterationById(int id) { for(int i = 0; i < iterations.size(); i++) { if (iterations.at(i).id == id) { return i; } } return -1; } QString Schema::getDomain() const { return domain; } void Schema::setDomain(const QString & d) { domain = d; } const QList & Schema::getIterations() const { return iterations; } QList & Schema::getIterations() { return iterations; } const QList & Schema::getProcesses() const { return procs; } void Schema::addProcess(Actor * a) { assert(a != NULL); procs.append(a); } const QList & Schema::getFlows() const { return flows; } void Schema::addFlow(Link* l) { assert(l != NULL); flows.append(l); } void Schema::setDeepCopyFlag(bool flag) { deepCopy = flag; } bool Schema::hasParamAliases() const { foreach(Actor * actor, procs) { if(actor->hasParamAliases()) { return true; } } return false; } bool Schema::hasAliasHelp() const { foreach(Actor * a, procs) { if(a->hasAliasHelp()) { return true; } } return false; } /************************** * Iteration **************************/ Iteration::Iteration() : id(nextId()) { } Iteration::Iteration(const QString& n) : name(n), id(nextId()) { } Iteration::Iteration(const Iteration & it) : name(it.name), id(it.id), cfg(it.cfg) { } int Iteration::nextId() { static int id = 0; return id++; } void Iteration::remap(QMap map) { CfgMap newCfg; QMapIterator< ActorId, QVariantMap> it(cfg); while (it.hasNext()) { it.next(); newCfg.insert(map.value(it.key()), it.value()); } cfg = newCfg; } bool Iteration::isEmpty() const { return cfg.isEmpty(); } QVariantMap Iteration::getParameters(const ActorId& id) const { return cfg.value(id); } /************************** * Metadata **************************/ Metadata::Metadata() { reset(); } void Metadata::reset() { name = QString(); comment = QString(); url = QString(); } }//Workflow namespace }//GB2namespace ugene-1.9.8/src/corelibs/U2Lang/src/model/Port.h0000644000175000017500000000746611651544333020001 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_WORKFLOW_PORT_H_ #define _U2_WORKFLOW_PORT_H_ #include #include #include namespace U2 { namespace Workflow { class Actor; class Link; /** * identity data of a port */ class U2LANG_EXPORT PortDescriptor : public Descriptor { public: PortDescriptor(const Descriptor& desc, DataTypePtr type, bool input, bool multi = false, uint f = 0); virtual ~PortDescriptor() {} bool isInput() const; bool isOutput() const; bool isMulti() const; uint getFlags() const; virtual DataTypePtr getType() const; DataTypePtr getOutputType() const; protected: // type of data that this port contains DataTypePtr type; // port can be input (receives data) or output (sends data) bool input; // port can get data from many sources bool multi; // for user purposes // see usage in implementations e.g. IntegralBusModel.cpp uint flags; }; // PortDescriptor /** * Port is a place where communication channels meet actors * actually, Port itself does not need to be a configuration * nowadays, BusPort uses 1 attribute BUS_MAP to store StrStr map of values that come to port * see BusPort for details * Configuration is chosen for extensibility * * Peer needs in realizations to store CommunicationChannel that goes throw a port. see BaseWorker::BaseWorker */ class U2LANG_EXPORT Port : public QObject, public PortDescriptor, public Configuration, public Peer { Q_OBJECT public: Port(const PortDescriptor& d, Actor* p); virtual ~Port() {} Actor* owner() const; QMap getLinks() const; virtual void addLink(Link*); virtual void removeLink(Link*); // how many links goes throw this port int getWidth() const; // reimplemented Configuration::setParameter virtual void setParameter(const QString& name, const QVariant& val); // simple check if one port can be binded to other // port types doesn't check here virtual bool canBind(const Port* other) const; // reimplemented Configuration::remap // empty implementation virtual void remap(const QMap&); signals: // emitted when link is added or removed from bindings void bindingChanged(); protected: // owner of this port Actor* proc; // links with other ports QMap bindings; }; // Port /** * represents connection between 2 ports * as if ports are binded to actors, link represents connection between 2 actors * * Peer needs to store CommunicationChannel. See LocalDomainFactory::createConnection as example */ class U2LANG_EXPORT Link : public Peer { public: Link(); Link(Port* p1, Port* p2); virtual ~Link() {} // adds this link to p1 and p2 bindings void connect(Port* p1, Port* p2); Port* source() const; Port* destination() const; private: // output port of some actor Port *src; // input port of some actor Port *dest; }; // Link } } // U2 #endif // _U2_WORKFLOW_PORT_H_ ugene-1.9.8/src/corelibs/U2Lang/src/model/WorkflowEnv.cpp0000644000175000017500000000266011651544333021662 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include #include "WorkflowEnv.h" namespace U2 { namespace Workflow { WorkflowEnv* WorkflowEnv::instance; bool WorkflowEnv::init(WorkflowEnv* env) { if (instance) { assert(0);// Duplicate initialization; return false; } env->data = env->initDataRegistry(); env->proto = env->initProtoRegistry(); env->domain = env->initDomainRegistry(); instance = env; env->dvfReg = env->initDataTypeValueFactoryRegistry(); env->ecfgReg = env->initExternalToolCfgRegistry(); return true; } }// namespace Workflow }//namespace U2 ugene-1.9.8/src/corelibs/U2Lang/src/model/QDConstraint.cpp0000644000175000017500000001726711651544333021761 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include #include "QDConstraint.h" namespace U2 { const QDConstraintType QDConstraintTypes::DISTANCE("QD_Distance_Constraint"); QDDistanceConstraint::QDDistanceConstraint(const QList& _units, QDDistanceType type, int min, int max) : QDConstraint(_units, QDConstraintTypes::DISTANCE), distType(type) { assert(_units.size()==2); cfg = new QDParameters; Descriptor mind(QDConstraintController::MIN_LEN_ATTR, QObject::tr("Min distance"), QObject::tr("Minimum distance")); Descriptor maxd(QDConstraintController::MAX_LEN_ATTR, QObject::tr("Max distance"), QObject::tr("Maximum distance")); Attribute* minAttr = new Attribute(mind, BaseTypes::NUM_TYPE(), true, QVariant(min)); Attribute* maxAttr = new Attribute(maxd, BaseTypes::NUM_TYPE(), true, QVariant(max)); cfg->addParameter(minAttr->getId(), minAttr); cfg->addParameter(maxAttr->getId(), maxAttr); } QDDistanceConstraint::~QDDistanceConstraint() { delete cfg; } int QDDistanceConstraint::getMin() const { return cfg->getParameter(QDConstraintController::MIN_LEN_ATTR)->getAttributeValue(); } int QDDistanceConstraint::getMax() const { return cfg->getParameter(QDConstraintController::MAX_LEN_ATTR)->getAttributeValue(); } void QDDistanceConstraint::setMin(int min) { cfg->setParameter(QDConstraintController::MIN_LEN_ATTR, qVariantFromValue(min)); } void QDDistanceConstraint::setMax(int max) { cfg->setParameter(QDConstraintController::MAX_LEN_ATTR, qVariantFromValue(max)); } QString QDDistanceConstraint::getText(QDSchemeUnit*, QDSchemeUnit*) const { int minVal = getMin(); int maxVal = getMax(); if(minVal==maxVal) { return QString("%1 bp").arg(QString::number(minVal)); } return QString("%1..%2 bp").arg(QString::number(minVal)).arg(QString::number(maxVal)); } void QDDistanceConstraint::invert() { units.swap(0,1); setMin(-getMax()); setMax(-getMin()); distType = QDConstraintController::getInvertedType(distType); } //QDConstraintController ////////////////////////////////////////////////////////////////////////// const QString QDConstraintController::DISTANCE_CONSTRAINT_EL("distance"); const QString QDConstraintController::TYPE_ATTR("type"); const QString QDConstraintController::MIN_LEN_ATTR("min"); const QString QDConstraintController::MAX_LEN_ATTR("max"); const QString QDConstraintController::SRC_ATTR("src"); const QString QDConstraintController::DST_ATTR("dst"); QDDistanceType QDConstraintController::getInvertedType(QDDistanceType type) { if (type==E2E) { return S2S; } if (type==S2S) { return E2E; } return type; } bool QDConstraintController::match(QDConstraint* c, const QDResultUnit& r1, const QDResultUnit& r2, bool complement) { QDDistanceConstraint* dc = static_cast(c); assert(dc); const U2Region& reg1 = r1->region; const U2Region& reg2 = r2->region; QDDistanceType dist = dc->distanceType(); int min = dc->getMin(); int max = dc->getMax(); if(dc->getSource()==r1->owner) { if (complement) { return match(reg2, reg1, getInvertedType(dist), min, max); } else { return match(reg1, reg2, dist, min, max); } } else { assert(dc->getSource()==r2->owner); if (complement) { return match(reg1, reg2, getInvertedType(dist), min, max); } else { return match(reg2, reg1, dist, min, max); } } } bool QDConstraintController::match(const U2Region& srcReg, const U2Region& dstReg, QDDistanceType type, int min, int max) { switch (type) { case E2S: { int srcEnds = srcReg.endPos(); int dstStarts = dstReg.startPos; int distance = dstStarts - srcEnds; if(distance<=max && distance>=min) { return true; } } return false; case S2E: { int srcStarts = srcReg.startPos; int dstEnds = dstReg.endPos(); int distance = dstEnds - srcStarts; if(distance<=max && distance>=min) { return true; } } return false; case S2S: { int srcStarts = srcReg.startPos; int dstStarts = dstReg.startPos; int distance = dstStarts - srcStarts; if(distance<=max && distance>=min) { return true; } } return false; case E2E: { int srcEnds = srcReg.endPos(); int dstEnds = dstReg.endPos(); int distance = dstEnds - srcEnds; if(distance<=max && distance>=min) { return true; } } return false; } return false; } U2Region QDConstraintController::matchLocation(QDDistanceConstraint* dc, const QDResultUnit& r, bool complement) { int start = 0; int end = 0; QDSchemeUnit* src = NULL; QDSchemeUnit* dst = NULL; QDDistanceType type = dc->distanceType(); int minDist = dc->getMin(); int maxDist = dc->getMax(); if (complement) { src = dc->getDestination(); dst = dc->getSource(); type = getInvertedType(type); } else { src = dc->getSource(); dst = dc->getDestination(); } if (src==r->owner) { int len = dst->getActor()->getMaxResultLen(); switch (type) { case E2S: start = r->region.endPos() + minDist; end = r->region.endPos() + maxDist + len; break; case E2E: end = r->region.endPos() + maxDist; start = r->region.endPos() + minDist - len; break; case S2S: start = r->region.startPos + minDist; end = r->region.startPos + maxDist + len; break; case S2E: end = r->region.startPos + maxDist; start = r->region.startPos + minDist - len; break; } } else { assert(dst==r->owner); int len = src->getActor()->getMaxResultLen(); switch (type) { case E2S: start = r->region.startPos - maxDist - len; end = r->region.startPos - minDist; break; case E2E: end = r->region.endPos() - minDist; start = r->region.endPos() - maxDist - len; break; case S2S: start = r->region.startPos - maxDist; end = r->region.startPos - minDist + len; break; case S2E: start = r->region.endPos() - maxDist; end = r->region.endPos() - minDist + len; break; } } return U2Region(start, end-start); } }//namespace ugene-1.9.8/src/corelibs/U2Lang/src/model/IntegralBusType.h0000644000175000017500000000411011651544333022115 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_INTEGRAL_BUS_TYPE_H_ #define _U2_INTEGRAL_BUS_TYPE_H_ #include #include namespace U2 { namespace Workflow { /** * IntegralPort can receive data from actors that are not connected with him directly * but connected in transitive closure of schema graph * * for such purposes, we need IntegralBusType */ class U2LANG_EXPORT IntegralBusType : public MapDataType { public: IntegralBusType(const Descriptor& d, const QMap& m); // add port's type to map void addInputs(const Port* p); void addOutput(DataTypePtr, const Port* producer); public: // in busmap (see IntegralBusPort) attributes of other actors saved as 'actorId:attrId' // these are utility functions to work with it static Descriptor assignSlotDesc(const Descriptor& elementDesc, const Port* producer); static ActorId parseSlotDesc(const QString& id); static QString parseAttributeIdFromSlotDesc(const QString & str); // when schema is deeply copied we need to remap actorIds in busmap static void remap(QStrStrMap& busMap, const QMap&); }; // IntegralBusType } //namespace Workflow } //namespace U2 #endif // _U2_INTEGRAL_BUS_TYPE_H_ ugene-1.9.8/src/corelibs/U2Lang/src/model/WorkflowTransport.h0000644000175000017500000000576011651544333022577 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_WORKFLOW_TRANSPORT_H_ #define _U2_WORKFLOW_TRANSPORT_H_ #include #include namespace U2 { namespace Workflow { /** * Message is entity for data that is passed between actors in runtime */ class U2LANG_EXPORT Message { public: Message(DataTypePtr _t, const QVariant& d); int getId() const; DataTypePtr getType() const; QVariant getData() const; private: static int nextid(); private: // message identifier int id; // type of data DataTypePtr t; // data itself QVariant data; }; // Message /** * pure virtual controller of passing/receiving messages */ class U2LANG_EXPORT CommunicationChannel { public: virtual ~CommunicationChannel() {} // take message from channel virtual Message get() = 0; // look at message without getting it out of channel // Message is united of data that was putted to outer channels // used in scripting virtual Message look() const = 0; // after calling message is in channel until get() invocation virtual void put(const Message& m) = 0; // how many messages in channel virtual int hasMessage() const = 0; // how many messages taken from channel virtual int takenMessages() const = 0; // virtual int hasRoom(const DataType* t = NULL) const = 0; // user can set 'ended' flag to channel // it means that no other data will be supplied to it virtual bool isEnded() const = 0; virtual void setEnded() = 0; // how many messages can be put to channel virtual int capacity() const = 0; virtual void setCapacity(int) = 0; }; // CommunicationChannel /** * represents entity that communicate with others by CommunicationChannel * moreover, it binds channels to port identifiers */ class U2LANG_EXPORT CommunicationSubject { public: virtual ~CommunicationSubject() {} virtual bool addCommunication(const QString& portId, CommunicationChannel* ch) = 0; virtual CommunicationChannel* getCommunication(const QString& portId) = 0; }; // CommunicationSubject }//Workflow namespace }//GB2 namespace #endif // _U2_WORKFLOW_TRANSPORT_H_ ugene-1.9.8/src/corelibs/U2Lang/src/model/QDScheme.h0000644000175000017500000002363111651544333020476 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_QD_SCHEME_H_ #define _U2_QD_SCHEME_H_ #include #include #include #include namespace U2 { enum QDStrandOption { QDStrand_DirectOnly, QDStrand_ComplementOnly, QDStrand_Both }; class U2LANG_EXPORT QDParameters : public QObject, public Configuration { Q_OBJECT public: virtual void setParameter(const QString& name, const QVariant& val); virtual void remap(const QMap&) {} signals: void si_modified(); }; class U2LANG_EXPORT QDActorParameters : public QDParameters { Q_OBJECT public: QDActorParameters() : annKey("misc_feature") {} void setLabel(const QString& l) { label = l; emit si_modified(); } const QString& getLabel() const { return label; } void setAnnotationKey(const QString& key) { annKey = key; emit si_modified(); } const QString& getAnnotationKey() const { return annKey; } private: QString label; QString annKey; }; class QDSchemeUnit; class U2LANG_EXPORT QDResultUnitData : public QSharedData { public: QDResultUnitData() : owner(NULL){} QDSchemeUnit* owner; U2Strand strand; U2Region region; QVector quals; }; typedef QSharedDataPointer QDResultUnit; class U2LANG_EXPORT QDResultGroup { public: QDResultGroup(QDStrandOption _strand = QDStrand_DirectOnly) : strand(_strand), startPos(0), endPos(0) {} U2Region location() const; void add(const QDResultUnit& res); void add(const QList& res); const QList& getResultsList() const; public: static void buildGroupFromSingleResult(const QDResultUnit& ru, QList& results); public: QDStrandOption strand; private: int startPos; int endPos; QList results; }; inline U2Region QDResultGroup::location() const { return U2Region(startPos, endPos-startPos); } inline const QList& QDResultGroup::getResultsList() const { return results; } typedef QPair StringAttribute; class QDScheme; class QDConstraint; class QDActor; class U2LANG_EXPORT QDActorPrototype { public: QDActorPrototype() : editor(NULL) {} virtual ~QDActorPrototype() { qDeleteAll(attributes); delete editor; } const QList& getParameters() const { return attributes; } ConfigurationEditor* getEditor() const { return editor; } const Descriptor& getDescriptor() const { return descriptor; } QString getId() const { return descriptor.getId(); } QString getDisplayName() const { return descriptor.getDisplayName(); } virtual QIcon getIcon() const { return QIcon(); } virtual QDActor* createInstance() const=0; protected: QList attributes; ConfigurationEditor* editor; Descriptor descriptor; }; class U2LANG_EXPORT QDActor : public QObject { friend class QDScheme; Q_OBJECT public: QDActor(QDActorPrototype const* proto); virtual ~QDActor(); QDScheme* getScheme() const { return scheme; } QDActorPrototype const* getProto() const { return proto; } QDActorParameters* getParameters() const { return cfg; } QString getUnitId(QDSchemeUnit* su) const { return units.key(su); } QDSchemeUnit* getSchemeUnit(const QString& id) const { return units.value(id); } QList getSchemeUnits() const { return units.values(); } const QList& getParamConstraints() const { return paramConstraints; } QDStrandOption getStrand() const; void setStrand(QDStrandOption stOp); virtual void updateEditor() {} bool hasAnyDirection() const { return getStrand()==QDStrand_Both; } bool hasForwardDirection() const { return getStrand()==QDStrand_DirectOnly; } bool hasBackwardDirection() const { return getStrand()==QDStrand_ComplementOnly; } bool isSimmetric() const { return simmetric; } QList getConstraints() const; QString getActorType() const { return proto->getId(); } const QString& annotateAs() const { return cfg->getAnnotationKey(); } void filterResults(const QVector& location); QList popResults(); void reset(); virtual int getMinResultLen() const=0; virtual int getMaxResultLen() const=0; virtual QString getText() const=0; virtual Task* getAlgorithmTask(const QVector& location)=0; virtual bool hasStrand() const { return true; } //implement in subclass to provide configuration representation in serialized scheme virtual QList< QPair > saveConfiguration() const; virtual void loadConfiguration(const QList< QPair >& strMap); //implement in subclass to customize the color of the visual actor representation virtual QColor defaultColor() const { return QColor(0x98,0xff, 0xc5); } signals: void si_strandChanged(QDStrandOption); public: static const int DEFAULT_MAX_RESULT_LENGTH; protected: QDStrandOption getStrandToRun() const; protected: QDScheme* scheme; QDActorPrototype const* proto; QDActorParameters* cfg; QMap units; QList paramConstraints; QList results; QMap defaultCfg; QDStrandOption strand; bool simmetric; }; class QDDistanceConstraint; class U2LANG_EXPORT QDSchemeUnit { friend class QDScheme; public: QDSchemeUnit(QDActor* parent) : actor(parent) {} const QList& getConstraints() const { return schemeConstraints; } QList getDistanceConstraints() const; QDActor* getActor() const { return actor; } QString getPersonalName() const; QString getId() const { QDSchemeUnit* thisPtr = const_cast(this); return actor->getUnitId(thisPtr); } private: QDActor* actor; QList schemeConstraints; }; class U2LANG_EXPORT QDPath { public: QDPath() : pathSrc(NULL), pathDst(NULL), overallConstraint(NULL) {} ~QDPath(); QDPath* clone() const; bool addConstraint(QDDistanceConstraint* dc); QDSchemeUnit const* getSrc() const { return pathSrc; } QDSchemeUnit const* getDst() const { return pathDst; } const QList& getConstraints() const { return constraints; } //returns unsorted list of involved scheme units const QList& getSchemeUnits() const { return schemeUnits; } QDDistanceConstraint* toConstraint(); private: QDSchemeUnit* pathSrc; QDSchemeUnit* pathDst; QDDistanceConstraint* overallConstraint; QList constraints; QList schemeUnits; }; class DNASequenceObject; class U2LANG_EXPORT QDScheme : public QObject { Q_OBJECT public: QDScheme() : dna(NULL), strand(QDStrand_Both) {} ~QDScheme(); void clear(); void addActor(QDActor* a); void addConstraint(QDConstraint* constraint); bool removeActor(QDActor* a); void removeConstraint(QDConstraint* constraint); DNASequenceObject* getDNA() const { return dna; } void setDNA(DNASequenceObject* sequence) { dna = sequence; } const QList& getActors() const { return actors; } QList getConstraints() const; QList getConstraints(QDSchemeUnit const* su1, QDSchemeUnit const* su2) const; QList findPaths(QDSchemeUnit* src, QDSchemeUnit* dst); void setOrder(QDActor* a, int serialNum); bool isEmpty() const { return actors.isEmpty(); } bool isValid() const; QDActor* getActorByLabel(const QString& label) const; QDStrandOption getStrand() const { return strand; } void setStrand(QDStrandOption opt) { strand = opt; } //actor group methods void adaptActorsOrder(); QString getActorGroup(QDActor* a) const; QList getActorGroups() const { return actorGroups.keys(); } QList getActors(const QString& group) const { return actorGroups.value(group); } void addActorToGroup(QDActor* a, const QString& group); bool removeActorFromGroup(QDActor* a); void createActorGroup(const QString& name); bool removeActorGroup(const QString& name); bool validateGroupName(const QString& name) const; int getRequiredNumber(const QString& group) const { return actorGroupReqNum.value(group); } void setRequiredNum(const QString& group, int num); signals: void si_schemeChanged(); private: void findRoute(QDSchemeUnit* curSu); private: QList actors; QMap< QString, QList > actorGroups; QMap< QString, int > actorGroupReqNum; DNASequenceObject* dna; QDStrandOption strand; }; class U2LANG_EXPORT QDAttributeNameConverter { public: static QString convertAttrName(const QString& str) { return str.toLower().replace(' ', '_'); } }; class U2LANG_EXPORT QDAttributeValueMapper { public: enum ValueType { BOOLEAN_TYPE, UNKNOWN_TYPE }; static QVariant stringToAttributeValue(const QString& str); static ValueType getType(const QString& val); public: static const QMap BOOLEAN_MAP; private: static QMap initBooleanMap(); }; }//namespace #endif ugene-1.9.8/src/corelibs/U2Lang/src/model/IntegralBusModel.cpp0000644000175000017500000003425511651544333022604 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include #include #include #include #include #include "IntegralBusModel.h" #include "IntegralBusType.h" /* TRANSLATOR U2::Workflow::IntegralBusPort */ namespace U2 { namespace Workflow { /******************************* * IntegralBusPort *******************************/ static void filterAmbiguousSlots(QList& keys, const QMap& map, QStrStrMap& result) { foreach(DataTypePtr val, map) { const QList lst = map.keys(val); if (lst.size() != 1) { foreach(Descriptor d, lst) { result.insert(d.getId(), ""); keys.removeOne(d); } } } } static Actor* getLinkedActor(ActorId id, Port* output) { if (output->owner()->getId() == id) { return output->owner(); } foreach(Port* transit, output->owner()->getInputPorts()) { foreach(Port* p, transit->getLinks().uniqueKeys()) { Actor* a = getLinkedActor(id,p); if (a) return a; } } return NULL; } static QMap getListMappings(const QStrStrMap& bm, const Port* p) { assert(p->isInput()); DataTypePtr dt = p->getType(); QMap res; if (dt->isList()) { QString val = bm.value(p->getId()); if (!val.isEmpty()) { res.insert(p->getId(), val.split(";")); } } else if (dt->isMap()) { foreach(Descriptor d, dt->getAllDescriptors()) { QString val = bm.value(d.getId()); if (dt->getDatatypeByDescriptor(d)->isList() && !val.isEmpty()) { res.insert(d.getId(), val.split(";")); } } } return res; } const QString IntegralBusPort::BUS_MAP_ATTR_ID = "bus-map"; IntegralBusPort::IntegralBusPort(const PortDescriptor& d, Actor* p) : Port(d,p), recursing(false) { addParameter(BUS_MAP_ATTR_ID, new Attribute(Descriptor(BUS_MAP_ATTR_ID), DataTypePtr())); } DataTypePtr IntegralBusPort::getType() const { return isInput() ? type : getBusType(); } DataTypePtr IntegralBusPort::getBusType() const { if (recursing) { return DataTypePtr(new IntegralBusType(Descriptor(), QMap())); } recursing = true; IntegralBusType* t = new IntegralBusType(Descriptor(*this), QMap()); foreach (Port* p, owner()->getInputPorts()) { if ((p->getFlags()&BLIND_INPUT) == 0){ t->addInputs(p); } } t->addOutput(type, this); recursing = false; return DataTypePtr(t); } Actor* IntegralBusPort::getProducer(const QString& slot) { QList l = getProducers(slot); if (l.size() == 1) { return l.first(); } else { return NULL; } } QList IntegralBusPort::getProducers(const QString& slot) { QList res; Attribute* at = getParameter(BUS_MAP_ATTR_ID); if(at == NULL) { return res; } QStrStrMap busMap = at->getAttributeValue(); QString slotValue = busMap.value(slot); QStringList vals = slotValue.split(";"); foreach(QString val, vals) { ActorId id = IntegralBusType::parseSlotDesc(val); Actor * a = getLinkedActorById(id); if(a != NULL) { res << a; } } return res; } Actor* IntegralBusPort::getLinkedActorById(ActorId id) const { QList res; foreach(Port* peer, getLinks().uniqueKeys()) { Actor* ac = getLinkedActor(id,peer); if(ac != NULL) { res << ac; } } Actor * ret = NULL; if( res.size() == 0 ) { ret = NULL; } else if( res.size() > 1 ) { ret = res.first(); assert(false); } else { ret = res.first(); } return ret; } void IntegralBusPort::remap(const QMap& m) { Attribute* a = getParameter(BUS_MAP_ATTR_ID); if (a) { QStrStrMap busMap = a->getAttributeValue(); IntegralBusType::remap(busMap, m); setParameter(BUS_MAP_ATTR_ID, qVariantFromValue(busMap)); } } void IntegralBusPort::setBusMapValue(const QString & slotId, const QString & value) { if( !isInput() ) { return; } QStrStrMap busMap = getParameter(IntegralBusPort::BUS_MAP_ATTR_ID)->getAttributeValue(); if(busMap[slotId].isEmpty()) { busMap[slotId] = value; } else { busMap[slotId] = busMap[slotId] + ";" + value; } setParameter(BUS_MAP_ATTR_ID, qVariantFromValue(busMap)); } void IntegralBusPort::setupBusMap() { if( !isInput() || getWidth() != 1 ) { return; } DataTypePtr to = getType(); assert(to->isMap()); // all port types made as map datatypes DataTypePtr from = bindings.uniqueKeys().first()->getType(); QList keys = to->getAllDescriptors(); QStrStrMap busMap = getParameter(IntegralBusPort::BUS_MAP_ATTR_ID)->getAttributeValue(); filterAmbiguousSlots(keys, to->getDatatypesMap(), busMap); foreach(const Descriptor & key, keys) { // FIXME: hack for not binding 'Location' slot if(key == BaseSlots::URL_SLOT()) { busMap.insert(key.getId(), ""); continue; } DataTypePtr elementDatatype = to->getDatatypeByDescriptor(key); QStringList candidates = WorkflowUtils::findMatchingTypesAsStringList(from, elementDatatype); if (elementDatatype->isList()) { candidates += WorkflowUtils::findMatchingTypesAsStringList(from, elementDatatype->getDatatypeByDescriptor()); QString res = candidates.join(";"); if(candidates.size() != 1) { busMap.insert(key.getId(), ""); } else { busMap.insert(key.getId(), res); } } else if (candidates.size() == 0) { //no unambiguous match, reset busMap.insert(key.getId(), ""); } else { // for string type initial value - empty. Because string type is always path to file and not needed for binding if( elementDatatype == BaseTypes::STRING_TYPE() ) { // FIXME: should use special hints for descriptors? foreach(const QString & str, candidates) { if(str.split(":").at(1) == BaseSlots::URL_SLOT().getId()) { candidates.removeAll(str); } } if(candidates.size() == 1) { busMap.insert(key.getId(), candidates.first()); } else { busMap.insert(key.getId(), ""); } } else { bool fl = false; QMap links = this->getLinks(); Port *port = links.keys().first(); DataTypePtr ptr = port->getOutputType(); if(ptr->isMap()) { foreach(const Descriptor & desc, ptr->getAllDescriptors()) { if(key.getId() == desc.getId()) { foreach(const QString &str, candidates) { if(str.split(":").first() == port->owner()->getId()) { busMap.insert(key.getId(), str); fl = true; } } } } } else { if(key.getId() == ptr->getId()) { foreach(const QString &str, candidates) { if(str.split(":").first() == port->owner()->getId()) { busMap.insert(key.getId(), str); fl = true; } } } } if(!fl) { busMap.insert(key.getId(), candidates.first()); } } } } setParameter(BUS_MAP_ATTR_ID, qVariantFromValue(busMap)); } bool IntegralBusPort::validate(QStringList& l) const { bool good = Configuration::validate(l); if (isInput() && !validator) { good &= ScreenedSlotValidator::validate(QStringList(), this, l); } return good; } /******************************* * ScreenedSlotValidator *******************************/ bool ScreenedSlotValidator::validate( const QStringList& screenedSlots, const IntegralBusPort* vport, QStringList& l) { bool good = true; { if (vport->getWidth() == 0) { l.append(IntegralBusPort::tr("No input data supplied")); return false; } QStrStrMap bm = vport->getParameter(IntegralBusPort::BUS_MAP_ATTR_ID)->getAttributeValue(); int busWidth = bm.size(); QMap listMap = getListMappings(bm, vport); // iterate over all producers and exclude valid mappings from bus bindings foreach(Port* p, vport->getLinks().uniqueKeys()) { assert(qobject_cast(p));//TBD? DataTypePtr t = p->getType(); assert(t->isMap()); { foreach(Descriptor d, t->getAllDescriptors()) { foreach(QString key, bm.keys(d.getId())) { //log.debug("reducing bus from key="+ikey+" to="+rkey); assert(!key.isEmpty()); bm.remove(key); } foreach(QString key, listMap.uniqueKeys()) { QStringList& l = listMap[key]; l.removeAll(d.getId()); if (l.isEmpty()) { listMap.remove(key); bm.remove(key); } } } } } if (busWidth == bm.size()) { l.append(IntegralBusPort::tr("No input data supplied")); good = false; } { QMapIterator it(bm); while (it.hasNext()) { it.next(); const QString& slot = it.key(); QString slotName = vport->getType()->getDatatypeDescriptor(slot).getDisplayName(); //assert(!slotName.isEmpty()); if (it.value().isEmpty()) { if (!screenedSlots.contains(slot)) { l.append(IntegralBusPort::tr("Warning, empty input slot: %1").arg(slotName)); } } else { l.append(IntegralBusPort::tr("Bad slot binding: %1 to %2").arg(slotName).arg(it.value())); good = false; } } } { QMapIterator it(listMap); while (it.hasNext()) { it.next(); const QString& slot = it.key(); QString slotName = vport->getType()->getDatatypeDescriptor(slot).getDisplayName(); assert(!slotName.isEmpty()); assert(!it.value().isEmpty()); l.append(IntegralBusPort::tr("Bad slot binding: %1 to %2").arg(slotName).arg(it.value().join(","))); good = false; } } } return good; } bool ScreenedSlotValidator::validate( const Configuration* cfg, QStringList& output ) const { return validate(screenedSlots, static_cast(cfg), output); } /******************************* * ScreenedParamValidator *******************************/ ScreenedParamValidator::ScreenedParamValidator(const QString& id, const QString& port, const QString& slot) : id(id), port(port), slot(slot) {} bool ScreenedParamValidator::validate(const Configuration* cfg, QStringList& output) const { QString err = validate(cfg); if( !err.isEmpty() ) { output.append(err); return false; } return true; } QString ScreenedParamValidator::validate(const Configuration * cfg) const { Attribute* param = cfg->getParameter(id); QVariant val = param->getAttributePureValue(); const Workflow::Actor* a = dynamic_cast(cfg); assert(a); Workflow::Port* p = a->getPort(port); assert(p->isInput()); QVariant busMap = p->getParameter(Workflow::IntegralBusPort::BUS_MAP_ATTR_ID)->getAttributePureValue(); QString slotVal = busMap.value().value(slot); const bool noParam = ( val.isNull() || val.toString().isEmpty() ) && param->getAttributeScript().isEmpty(); const bool noSlot = slotVal.isNull() || slotVal.isEmpty(); if (noParam && noSlot) { QString slotName = p->getType()->getDatatypeDescriptor(slot).getDisplayName(); assert(!slotName.isEmpty()); return U2::WorkflowUtils::tr("Either parameter '%1' or input slot '%2' must be set") .arg(param->getDisplayName()).arg(slotName);//FIXME translator class } if (noParam == noSlot) { QString slotName = p->getType()->getDatatypeDescriptor(slot).getDisplayName(); assert(!slotName.isEmpty()); /*return U2::WorkflowUtils::tr("Warning, parameter '%1' overrides bus data slot '%2'") .arg(param->getDisplayName()).arg(slotName);//FIXME translator class*/ } return QString(); } }//Workflow namespace }//GB2namespace ugene-1.9.8/src/corelibs/U2Lang/src/model/Port.cpp0000644000175000017500000000675611651544333020335 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "Port.h" namespace U2 { namespace Workflow { /************************** * PortDescriptor **************************/ PortDescriptor::PortDescriptor(const Descriptor& desc, DataTypePtr t, bool input, bool multi, uint f ) : Descriptor(desc), type(t), input(input), multi(multi), flags(f) { assert(type->isMap()); if(input) { assert(!multi && "currently wd model cannot handle multi input ports"); } } bool PortDescriptor::isInput() const { return input; } bool PortDescriptor::isOutput() const { return !input; } bool PortDescriptor::isMulti() const { return multi; } uint PortDescriptor::getFlags() const { return flags; } DataTypePtr PortDescriptor::getType() const { return type; } DataTypePtr PortDescriptor::getOutputType() const { return type; } /************************** * Port **************************/ Port::Port(const PortDescriptor& d, Actor* p) : PortDescriptor(d), proc(p) { } Actor * Port::owner() const { return proc; } QMap Port::getLinks() const { return bindings; } int Port::getWidth() const { return bindings.size(); } void Port::setParameter(const QString& name, const QVariant& val) { Configuration::setParameter(name, val); emit bindingChanged(); } void Port::remap(const QMap&) { } bool Port::canBind(const Port* other) const { if (this == other || proc == other->proc || isInput() == other->isInput()) { return false; } if ((!isMulti() && getWidth() != 0) || (!other->isMulti() && other->getWidth() != 0)) { return false; } return !bindings.contains(const_cast(other)); } void Port::addLink(Link* b) { Port* peer = isInput()? b->source() : b->destination(); assert(this == (isInput()? b->destination() : b->source())); //assert(canBind(peer)); assert(!bindings.contains(peer)); bindings[peer] = b; emit bindingChanged(); } void Port::removeLink(Link* b) { Port* peer = isInput()? b->source() : b->destination(); assert(this == (isInput()? b->destination() : b->source())); assert(bindings.contains(peer)); bindings.remove(peer); emit bindingChanged(); } /************************** * Link **************************/ Link::Link() : src(NULL), dest(NULL) { } Link::Link(Port* p1, Port* p2) { connect(p1, p2); } Port * Link::source() const { return src; } Port * Link::destination() const { return dest; } void Link::connect(Port* p1, Port* p2) { assert(p1->canBind(p2)); if (p1->isInput()) { dest = p1; src = p2; } else { dest = p2; src = p1; } p1->addLink(this); p2->addLink(this); } } } // U2 ugene-1.9.8/src/corelibs/U2Lang/src/model/Descriptor.h0000644000175000017500000000572311651544333021165 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_DESC_H_ #define _U2_DESC_H_ #include #include #include #include #include namespace U2 { /** * Class Descriptor represents an uniquely identifiable entity, * which can be exposed to user in some way. So it also has a name and a description. */ class U2LANG_EXPORT Descriptor { public: Descriptor(const QString& id, const QString& name, const QString& doc); Descriptor(const QString& _id); Descriptor(const char* _id); Descriptor(); virtual ~Descriptor() {} // standard getters/setters QString getId() const; QString getDisplayName() const; QString getDocumentation() const; void setId(const QString& i); void setDisplayName(const QString& n); void setDocumentation(const QString& d); // descriptors with equal id's are equal inline bool operator==(const Descriptor& d) const { return id == d.id; } inline bool operator!=(const Descriptor& d) const { return id != d.id; } inline bool operator==(const QString& s) const { return id == s; } inline bool operator!=(const QString& s) const { return id != s; } // necessary for using with QMap e.g. QMap inline bool operator<(const Descriptor& d) const { return id < d.id; } protected: // entity identifier QString id; // entity name QString name; // description of entity QString desc; }; // Descriptor /** * It is a Descriptor with icon */ class U2LANG_EXPORT VisualDescriptor : public Descriptor { public: VisualDescriptor(const Descriptor& d, const QString & _iconPath = QString()); //getIcon will create icon from its path (if path exists) on the first call. //This is compatibility issue for congene. QIcon getIcon(); void setIcon(QIcon icon_); void setIconPath( const QString & iconPath_ ); private: // full path to the icon QString iconPath; // user defined or taken from iconPath icon QIcon icon; }; // VisualDescriptor } //namespace U2 Q_DECLARE_METATYPE(U2::Descriptor) Q_DECLARE_METATYPE(QList) #endif ugene-1.9.8/src/corelibs/U2Lang/src/model/IntegralBusModel.h0000644000175000017500000001041111651544333022235 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_WORKFLOW_BUS_MODEL_H_ #define _U2_WORKFLOW_BUS_MODEL_H_ #include namespace U2 { namespace Workflow { /** * To support passing data that is not produced by linked actor-neighbour * but produced by actor connected in transitive closure of schema graph * information of such data is saved in busmap - StrStr map * saved as attribute with BUS_MAP_ATTR_ID id * * in such cases port need to know who will produce needed data * thats why we need new Port * */ class U2LANG_EXPORT IntegralBusPort : public Port { Q_OBJECT public: // attribute for busmap static const QString BUS_MAP_ATTR_ID; static const uint BLIND_INPUT = 1 << 16; public: IntegralBusPort(const PortDescriptor& d, Actor* p); virtual DataTypePtr getType() const; DataTypePtr getOwnType() const {return type;} // slot is list pairs (actorId:attrId);(actorId:attrId);(actorId:attrId)... Actor* getProducer(const QString& slot); QList getProducers(const QString& slot); Actor* getLinkedActorById(ActorId id) const; // find matching data and assign it void setupBusMap(); virtual bool validate(QStringList&) const; // reimplemented from Configuration virtual void remap(const QMap&); // used when loading schema void setBusMapValue(const QString & slotId, const QString & value); protected: virtual DataTypePtr getBusType() const; //bool getNearestData(const Descriptor & key, QStringList candidates); // mutable bool recursing; }; // IntegralBusPort /** * as if ActorPrototype creates ports for actor * we need special actor prototype for IntegralBusPort */ class U2LANG_EXPORT IntegralBusActorPrototype : public ActorPrototype { public: IntegralBusActorPrototype(const Descriptor& desc, const QList& ports = QList(), const QList& attrs = QList()) : ActorPrototype(desc, ports, attrs) {} virtual Port* createPort(const PortDescriptor& d, Actor* p) {return new IntegralBusPort(d, p);} }; // IntegralBusActorPrototype /** * validates if binding in busmap to some actor's data is correct */ class U2LANG_EXPORT ScreenedSlotValidator : public ConfigurationValidator { public: ScreenedSlotValidator(const QString& slot): screenedSlots(slot) {} static bool validate(const QStringList& screenedSlots, const IntegralBusPort*, QStringList& output); virtual bool validate(const Configuration*, QStringList& output) const; protected: QStringList screenedSlots; }; // ScreenedSlotValidator /** * When attribute can be set by user or can be chosen from integral bus * this validator checks that only one must be chosen */ class U2LANG_EXPORT ScreenedParamValidator : public ConfigurationValidator { public: ScreenedParamValidator(const QString& id, const QString& port, const QString& slot); virtual ~ScreenedParamValidator() {} virtual bool validate(const Configuration*, QStringList& output) const; QString validate(const Configuration * cfg) const; QString getId() const {return id;} QString getPort() const {return port;} QString getSlot() const {return slot;} protected: QString id; QString port; QString slot; }; // ScreenedParamValidator }//namespace Workflow }//namespace U2 typedef QMap QStrStrMap; Q_DECLARE_METATYPE(QStrStrMap) #endif ugene-1.9.8/src/corelibs/U2Lang/src/model/Schema.h0000644000175000017500000001005411651544333020240 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_WORKFLOW_ITERATION_H_ #define _U2_WORKFLOW_ITERATION_H_ #include #include typedef QPair IterationCfgKey; typedef QMap IterationCfg; typedef QMap CfgMap; Q_DECLARE_METATYPE(IterationCfg) Q_DECLARE_METATYPE(CfgMap) namespace U2 { namespace Workflow { class Actor; class Link; class Iteration; /** * Schema is oriented graph of actors * graph is oriented because Link has orientation */ class U2LANG_EXPORT Schema { public: Schema(); virtual ~Schema(); Schema( const Schema & other ); Schema & operator=( const Schema & other ); // after schema is copied its actor's id's changed // in that case we need to configurate new schema with values from Iteration using actors mapping void applyConfiguration(const Iteration&, QMap); Actor* actorById(ActorId); int iterationById(int); QString getDomain() const; void setDomain(const QString & d); const QList & getIterations() const; QList & getIterations(); const QList & getProcesses() const; void addProcess(Actor * a); const QList & getFlows() const; void addFlow(Link* l); void setDeepCopyFlag(bool flag); void reset(); bool hasParamAliases() const; bool hasAliasHelp() const; private: // set of actors QList procs; // set of links between actors QList flows; // list of iterations that user has fulfilled QList iterations; // name of domain in which we work now // default is LocalDomainFactory::ID QString domain; // true if schema was deeply copied // this means that every actor, link and iteration was copied // if true -> need to delete all corresponding data bool deepCopy; }; // Schema /** * Iteration is a set of values for schema's attributes * * using schema and iteration you can parametrize schema and then run it */ class U2LANG_EXPORT Iteration { public: Iteration(); Iteration(const QString& name); Iteration(const Iteration & it); QVariantMap getParameters(const ActorId& id) const; // when actor changes id (if schema was deeply copied) // we need to remap iteration's data to new actorId void remap(QMap); bool isEmpty() const; private: static int nextId(); public: // each configuration has name // default name is 'default' QString name; // int id; // for each actor in schema iteration saves QVariantMap of it's attributes values // QMap // this QVariantMap contains only those attributes that were changed by user QMap cfg; }; // Iteration /** * Schema's metadata * saves with schema to file and loads with it * * Schema don't aggregate metadata (see WorkflowViewController for usage) */ class U2LANG_EXPORT Metadata { public: Metadata(); void reset(); public: QString name; QString url; QString comment; }; // Metadata }//Workflow namespace }//GB2 namespace #endif // _U2_WORKFLOW_ITERATION_H_ ugene-1.9.8/src/corelibs/U2Lang/src/model/Configuration.h0000644000175000017500000000573311651544333021657 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_WORKFLOW_CONFIGURATION_H_ #define _U2_WORKFLOW_CONFIGURATION_H_ #include "ConfigurationValidator.h" #include "ConfigurationEditor.h" namespace U2 { /** * Set of named attributes * additionally, has editor and can be validated */ class U2LANG_EXPORT Configuration { public: Configuration(); virtual ~Configuration(); virtual QMap getParameters() const; // returns NULL if no parameter identified with 'name' virtual Attribute* getParameter(const QString& name) const; // returns removed parameter // caller takes ownership of the attribute virtual Attribute * removeParameter( const QString & name ); virtual void addParameter( const QString & name, Attribute * attr ); // sets if only parameter with 'name' exists virtual void setParameter(const QString& name, const QVariant& val); void setParameters(const QVariantMap&); virtual bool hasParameter(const QString & name) const; // getters/setters virtual ConfigurationEditor* getEditor(); void setEditor(ConfigurationEditor* ed); virtual ConfigurationValidator* getValidator(); void setValidator(ConfigurationValidator* v); // returns 'false' if validations fails, otherwise 'true' // if validation fails, new errors appended to errorList virtual bool validate(QStringList& errorList) const; // when schema copied, actors in new schema get new id's // in this case, we need to remap all links between actors // see Port realizations virtual void remap(const QMap&) = 0; virtual QList getAttributes() const; protected: // controller for ui editor of this configuration ConfigurationEditor* editor; // standard validations if required attribute is empty are done in validate() function // this validator can make any non-trivial validations ConfigurationValidator* validator; private: // named attributes QMap params; QList attrs; //For sorting attributes by order of creation }; // Configuration } // U2 #endif // _U2_WORKFLOW_CONFIGURATION_H_ ugene-1.9.8/src/corelibs/U2Lang/src/model/WorkflowEnv.h0000644000175000017500000000522511651544333021327 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_WORKFLOW_ENV_H_ #define _U2_WORKFLOW_ENV_H_ #include #include #include #include "Descriptor.h" namespace U2 { class DataTypeRegistry; namespace Workflow { class DomainFactoryRegistry; class ActorPrototypeRegistry; /** * base class for workflow environment * has one instance * same as AppContext only for workflow * * see WorkflowEnvImpl for realization */ class U2LANG_EXPORT WorkflowEnv { public: static bool init(WorkflowEnv* instance); static void shutdown() { delete instance; instance = NULL;} static DataTypeRegistry* getDataTypeRegistry() {return getInstance()->data;} static ActorPrototypeRegistry* getProtoRegistry() {return getInstance()->proto;} static DomainFactoryRegistry* getDomainRegistry() {return getInstance()->domain;} static DataTypeValueFactoryRegistry* getDataTypeValueFactoryRegistry() { return getInstance()->dvfReg; } static ExternalToolCfgRegistry* getExternalCfgRegistry() {return getInstance()->ecfgReg;} protected: static WorkflowEnv* instance; static WorkflowEnv* getInstance() {assert(instance); return instance;} public: virtual ~WorkflowEnv() {} protected: virtual DataTypeRegistry* initDataRegistry() = 0; virtual ActorPrototypeRegistry* initProtoRegistry() = 0; virtual DomainFactoryRegistry* initDomainRegistry() = 0; virtual DataTypeValueFactoryRegistry* initDataTypeValueFactoryRegistry() = 0; virtual ExternalToolCfgRegistry* initExternalToolCfgRegistry() = 0; protected: DataTypeRegistry* data; ActorPrototypeRegistry* proto; DomainFactoryRegistry* domain; DataTypeValueFactoryRegistry* dvfReg; ExternalToolCfgRegistry *ecfgReg; }; // WorkflowEnv } //namespace Workflow } //namespace U2 #endif // _U2_WORKFLOW_ENV_H_ ugene-1.9.8/src/corelibs/U2Lang/src/model/DatatypeConversion.h0000644000175000017500000000067411651544333022670 0ustar ilyailya#ifndef _U2_DATATYPECONV_H_ #define _U2_DATATYPECONV_H_ namespace U2 { //TODO rethink... class U2LANG_EXPORT DataTypeConvertion { public: enum ConvertionType { Equal, Narrow, Wide, None }; virtual QVariant convert(const QVariant& d, const DataTypePtr from, const DataTypePtr to) = 0; virtual ConvertionType canConvert(const DataTypePtr from, const DataTypePtr to) = 0; }; } //namespace #endif ugene-1.9.8/src/corelibs/U2Lang/src/model/IntegralBus.cpp0000644000175000017500000001622711651544333021622 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "IntegralBus.h" #include "IntegralBusType.h" #include #include namespace U2 { namespace Workflow { static QMap getListMappings(const QStrStrMap& bm, const Port* p) { assert(p->isInput()); DataTypePtr dt = p->getType(); QMap res; if (dt->isList()) { if (bm.contains(p->getId())) { res.insert(p->getId(), bm.value(p->getId()).split(";")); } } else if (dt->isMap()) { foreach(Descriptor d, dt->getAllDescriptors()) { if (dt->getDatatypeByDescriptor(d)->isList() && bm.contains(d.getId())) { res.insert(d.getId(), bm.value(d.getId()).split(";")); } } } return res; } IntegralBus::IntegralBus(Port* p) : busType(p->getType()), complement(NULL), portId(p->getId()), takenMsgs(0) { QString name = p->owner()->getLabel() + "[" + p->owner()->getId()+"]"; if (p->isInput()) { Attribute* a = p->getParameter(IntegralBusPort::BUS_MAP_ATTR_ID); if(a == NULL) { assert(false); return; } busMap = a->getAttributeValue(); assert(!busMap.isEmpty()); QMapIterator it(busMap); while (it.hasNext()) { it.next(); coreLog.trace(QString("%1 - input bus map key=%2 val=%3").arg(name).arg(it.key()).arg(it.value())); } listMap = getListMappings(busMap, p); } else { // p is output IntegralBusPort* bp = qobject_cast(p); DataTypePtr t = bp ? bp->getOwnType() : p->getType(); if (t->isMap()) { foreach(Descriptor d, t->getAllDescriptors()) { QString key = d.getId(); QString val = IntegralBusType::assignSlotDesc(d, p).getId(); busMap.insert(key, val); } } else { QString key = p->getId(); QString val = IntegralBusType::assignSlotDesc(*p, p).getId(); busMap.insert(key, val); } QMapIterator it(busMap); while (it.hasNext()) { it.next(); coreLog.trace(QString("%1 - output bus map key=%2 val=%3").arg(name).arg(it.key()).arg(it.value())); } } } bool IntegralBus::addCommunication(const QString& id, CommunicationChannel* ch) { outerChannels.insertMulti(id, ch); return true; } CommunicationChannel * IntegralBus::getCommunication(const QString& id) { return outerChannels.value(id); } Message IntegralBus::get() { QVariantMap result; context.clear(); foreach (CommunicationChannel* ch, outerChannels) { Message m = ch->get(); assert(m.getData().type() == QVariant::Map); QVariantMap imap = m.getData().toMap(); context.unite(imap); foreach(QString ikey, imap.uniqueKeys()) { QVariant ival = imap.value(ikey); foreach(QString rkey, busMap.keys(ikey)) { coreLog.trace("reducing bus from key="+ikey+" to="+rkey); result[rkey] = ival; } QMapIterator lit(listMap); while (lit.hasNext()) { lit.next(); QString rkey = lit.key(); assert(!lit.value().isEmpty()); if (lit.value().contains(ikey)) { QVariantList vl = result[rkey].toList(); if (m.getType()->getDatatypeByDescriptor(ikey)->isList()) { vl += ival.toList(); coreLog.trace("reducing bus key="+ikey+" to list of "+rkey); } else { vl.append(ival); coreLog.trace("reducing bus key="+ikey+" to list element of "+rkey); } result[rkey] = vl; } } } } //assert(busType->isMap() || result.size() == 1); QVariant data; if (busType->isMap()) { data.setValue(result); } else if (result.size() == 1) { data = result.values().at(0); } if (complement) { complement->setContext(context); } takenMsgs++; return Message(busType, data); } Message IntegralBus::look() const { QVariantMap result; foreach(CommunicationChannel* channel, outerChannels) { assert(channel != NULL); Message message = channel->look(); assert(message.getData().type() == QVariant::Map); result.unite(message.getData().toMap()); } return Message(busType, result); } Message IntegralBus::composeMessage(const Message& m) { QVariantMap data(getContext()); if (m.getData().type() == QVariant::Map) { QMapIterator it(m.getData().toMap()); while (it.hasNext()) { it.next(); QString key = busMap.value(it.key()); coreLog.trace("putting key="+key+" remapped from="+it.key()); data.insert(key, it.value()); } } else { assert(busMap.size() == 1); data.insert(busMap.values().first(), m.getData()); } return Message(busType, data); } void IntegralBus::put(const Message& m) { Message busMessage = composeMessage(m); foreach(CommunicationChannel* ch, outerChannels) { ch->put(busMessage); } } int IntegralBus::hasMessage() const { if (outerChannels.isEmpty()) { return 0; } int num = INT_MAX; foreach(CommunicationChannel* ch, outerChannels) { num = qMin(num, ch->hasMessage()); } return num; } int IntegralBus::takenMessages() const { return takenMsgs; } int IntegralBus::hasRoom(const DataType*) const { if (outerChannels.isEmpty()) { return 0; } int num = INT_MAX; foreach(CommunicationChannel* ch, outerChannels) { num = qMin(num, ch->hasRoom()); } return num; } bool IntegralBus::isEnded() const { foreach(CommunicationChannel* ch, outerChannels) { if (ch->isEnded()) { #ifdef _DEBUG foreach(CommunicationChannel* dbg, outerChannels) { assert(dbg->isEnded()); } #endif return true; } } return false; } void IntegralBus::setEnded() { foreach(CommunicationChannel* ch, outerChannels) { ch->setEnded(); } } }//namespace Workflow }//namespace U2 ugene-1.9.8/src/corelibs/U2Lang/src/model/Attribute.h0000644000175000017500000001412511651544333021006 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_WORKFLOW_ATTR_H_ #define _U2_WORKFLOW_ATTR_H_ #include #include #include #include #include #include #include #include #include namespace U2 { typedef QString ActorId; inline ActorId str2aid(const QString& s) {return s;} /** * attribute value can be obtained from script */ class U2LANG_EXPORT AttributeScript { public: AttributeScript(const QString & text); AttributeScript() {} bool isEmpty() const; void setScriptText(const QString & t); const QString & getScriptText() const; void setScriptVar(const Descriptor & desc, const QVariant & val); const QMap & getScriptVars() const; void clearScriptVars(); bool hasVarWithId(const QString & varName)const; bool hasVarWithDesc(const QString & varName)const; void setVarValueWithId(const QString & varName, const QVariant & value); private: QString text; QMap vars; // (desc, val) }; // AttributeScript /** * Value of certain type that can be identified by (descriptors) id */ class U2LANG_EXPORT Attribute : public Descriptor { public: Attribute(const Descriptor& d, const DataTypePtr type, bool required = false, const QVariant & defaultValue = QVariant()); // getters/setters const DataTypePtr getAttributeType()const; bool isRequiredAttribute() const; void setAttributeValue(const QVariant & newVal); // attribute value is kept in qvariant // but it can be transformed to value of specific type using scripting or not (see getAttributeValue) const QVariant & getAttributePureValue() const; // base realization without scripting. to support scripting for other types: see template realizations template T getAttributeValue() const { return getAttributeValueWithoutScript(); } const AttributeScript & getAttributeScript() const; // used to change script data AttributeScript & getAttributeScript(); // stores value and script data in variant // used in saving schema to xml QVariant toVariant() const; // reads value and script from variant // used in reading schema from xml bool fromVariant(const QVariant& variant); bool isEmpty() const; bool isEmptyString() const; bool isVisible(const QVariantMap &values) const; void addRelation(const QString& attrName, const QVariant &attrValue); private: template T getAttributeValueWithoutScript() const { return value.value(); } void debugCheckAttributeId() const; private: // type of value const DataTypePtr type; // attribute can be required or not // values of required attributes cannot be empty // used in configuration validations const bool required; // pure value. if script exists, value should be processed throw it QVariant value; // script text and variable values for script evaluating // script variables get values only in runtime AttributeScript scriptData; bool hasRelation; QMap relation; }; // Attribute // getAttributeValue function realizations with scripting support template<> inline QString Attribute::getAttributeValue() const { if( scriptData.isEmpty() ) { return getAttributeValueWithoutScript(); } // run script QScriptEngine engine; QMap scriptVars; foreach( const Descriptor & key, scriptData.getScriptVars().uniqueKeys() ) { assert(!key.getId().isEmpty()); scriptVars[key.getId()] = engine.newVariant(scriptData.getScriptVars().value(key)); } TaskStateInfo tsi; WorkflowScriptLibrary::initEngine(&engine); QScriptValue scriptResult = ScriptTask::runScript(&engine, scriptVars, scriptData.getScriptText(), tsi); // FIXME: report errors! // FIXME: write to log if( tsi.cancelFlag ) { if( !tsi.hasError() ) { tsi.setError("Script task canceled"); } } if(tsi.hasError()) { return QString(); } if( scriptResult.isString() ) { return scriptResult.toString(); } return QString(); } template<> inline int Attribute::getAttributeValue() const { if( scriptData.isEmpty() ) { return getAttributeValueWithoutScript(); } QScriptEngine engine; QMap scriptVars; foreach( const Descriptor & key, scriptData.getScriptVars().uniqueKeys() ) { assert(!key.getId().isEmpty()); scriptVars[key.getId()] = engine.newVariant(scriptData.getScriptVars().value(key)); } TaskStateInfo tsi; QScriptValue scriptResult = ScriptTask::runScript(&engine, scriptVars, scriptData.getScriptText(), tsi); if( tsi.cancelFlag ) { if( !tsi.hasError() ) { tsi.setError("Script task canceled"); } } if(tsi.hasError()) { return 0; } if( scriptResult.isNumber() ) { return scriptResult.toInt32(); } return 0; } } // U2 namespace Q_DECLARE_METATYPE(U2::AttributeScript) #endif ugene-1.9.8/src/corelibs/U2Lang/src/model/Configuration.cpp0000644000175000017500000000610011651544333022177 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include #include #include #include "ConfigurationEditor.h" #include "Configuration.h" namespace U2 { Configuration::Configuration() : editor(NULL), validator(NULL) { } Configuration::~Configuration() { qDeleteAll(params.values()); } QMap Configuration::getParameters() const { return params; } Attribute * Configuration::getParameter(const QString & name) const { return params.value(name); } Attribute * Configuration::removeParameter( const QString & name ) { Attribute *attr = params.take(name); attrs.removeOne(attr); return attr; } void Configuration::addParameter( const QString & name, Attribute * attr ) { assert(attr != NULL); params[name] = attr; attrs << attr; } void Configuration::setParameter(const QString& name, const QVariant& val) { if(params.contains(name)) { params[name]->setAttributeValue(val); } } void Configuration::setParameters(const QVariantMap& cfg) { QMapIterator it(cfg); while (it.hasNext()) { it.next(); setParameter(it.key(), it.value()); } } bool Configuration::hasParameter(const QString & name) const { return params.contains(name); } ConfigurationEditor * Configuration::getEditor() { return editor; } void Configuration::setEditor(ConfigurationEditor* ed) { assert(ed != NULL); editor = ed; } ConfigurationValidator * Configuration::getValidator() { return validator; } void Configuration::setValidator(ConfigurationValidator* v) { assert(v != NULL); validator = v; } bool Configuration::validate(QStringList& errorList) const { bool good = true; foreach(Attribute* a, getParameters()) { if( !a->isRequiredAttribute() ) { continue; } if( (a->isEmpty() || a->isEmptyString()) &&a->getAttributeScript().isEmpty()) { good = false; errorList.append(U2::WorkflowUtils::tr("Required parameter is not set: %1").arg(a->getDisplayName())); } } if (validator) { good &= validator->validate(this, errorList); } return good; } QList Configuration::getAttributes() const { return /*params.values()*/attrs;; } } // U2 ugene-1.9.8/src/corelibs/U2Lang/src/model/Attribute.cpp0000644000175000017500000001244311651544333021342 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include #include #include #include "Attribute.h" namespace U2 { /************************************* * Attribute *************************************/ Attribute::Attribute(const Descriptor& d, const DataTypePtr t, bool req, const QVariant & defaultValue ) : Descriptor(d), type(t), required(req), value(defaultValue), hasRelation(false) { debugCheckAttributeId(); } void Attribute::debugCheckAttributeId() const { QString id = getId(); Q_UNUSED(id); assert(id != HRSchemaSerializer::TYPE_ATTR); assert(id != HRSchemaSerializer::NAME_ATTR); assert(id != HRSchemaSerializer::SCRIPT_ATTR); assert(id != HRSchemaSerializer::ELEM_ID_ATTR); } const DataTypePtr Attribute::getAttributeType()const { return type; } bool Attribute::isRequiredAttribute() const { return required; } void Attribute::setAttributeValue(const QVariant & newVal) { value = newVal; } const QVariant & Attribute::getAttributePureValue() const { return value; } const AttributeScript & Attribute::getAttributeScript() const { return scriptData; } AttributeScript & Attribute::getAttributeScript() { return scriptData; } QVariant Attribute::toVariant() const { QVariantList res; res << value; res << qVariantFromValue(scriptData.getScriptText()); QVariantList scriptVars; foreach( const Descriptor & varDesc, scriptData.getScriptVars().keys() ) { scriptVars << qVariantFromValue(varDesc.getId()); } res << QVariant(scriptVars); return res; } bool Attribute::fromVariant(const QVariant& variant) { if( !variant.canConvert( QVariant::List ) ) { return false; } QVariantList args = variant.toList(); if( args.size() != 3 ) { return false; } value = args.at(0); QVariant scriptTextVal = args.at(1); QString scriptText; if( scriptTextVal.canConvert(QVariant::String) ) { scriptText = scriptTextVal.toString(); } scriptData.setScriptText(scriptText); QVariant descs = args.at(2); if( descs.canConvert(QVariant::List) ) { QVariantList descList = descs.toList(); for( int i = 0; i < descList.size(); ++i ) { scriptData.setScriptVar(Descriptor(descList.at(i).value(), "", "" ), QVariant()); } } return true; } bool Attribute::isEmpty() const { return !value.isValid() || value.isNull(); } bool Attribute::isEmptyString() const { return value.type() == QVariant::String && getAttributeValue().isEmpty(); } bool Attribute::isVisible(const QVariantMap &values) const { if(hasRelation) { QMapIterator i(relation); while (i.hasNext()) { i.next(); if(values.value(i.key()) == i.value()){ return true; } } return false;//(values.value(relatedAttribute) == relatedAttributeValue); } else { return true; } } void Attribute::addRelation(const QString& attrName, const QVariant &attrValue) { hasRelation = true; relation.insertMulti(attrName, attrValue); } /************************************* * AttributeScript *************************************/ AttributeScript::AttributeScript(const QString & t) : text(t) {} bool AttributeScript::isEmpty() const { return text.isEmpty(); } void AttributeScript::setScriptText(const QString & t) { text = t; } const QString & AttributeScript::getScriptText() const { return text; } const QMap & AttributeScript::getScriptVars() const { return vars; } void AttributeScript::clearScriptVars() { vars.clear(); } void AttributeScript::setScriptVar(const Descriptor & desc, const QVariant & val) { vars.insert(desc, val); } bool AttributeScript::hasVarWithId(const QString & varName) const { foreach(const Descriptor & varDesc, vars.keys()) { if( varDesc.getId() == varName ) { return true; } } return false; } bool AttributeScript::hasVarWithDesc(const QString & varName) const { foreach(const Descriptor & varDesc, vars.keys()) { if( varDesc.getDisplayName() == varName ) { return true; } } return false; } void AttributeScript::setVarValueWithId(const QString & varName, const QVariant & value) { foreach(const Descriptor & varDesc, vars.keys()) { if( varDesc.getId() == varName ) { vars[varDesc] = value; } } } } // U2 ugene-1.9.8/src/corelibs/U2Lang/src/model/IntegralBus.h0000644000175000017500000000557111651544333021267 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_WORKFLOW_INTEGRAL_BUS_H_ #define _U2_WORKFLOW_INTEGRAL_BUS_H_ #include #include namespace U2 { namespace Workflow { /** * represents communication channel for support passing data between actors * connected in transitive closure of schema graph * * is a container of communications with other actors */ class U2LANG_EXPORT IntegralBus : public QObject, public CommunicationSubject, public CommunicationChannel { Q_OBJECT public: IntegralBus(Port* peer); // reimplemented from CommunicationSubject virtual bool addCommunication(const QString& id, CommunicationChannel* ch); virtual CommunicationChannel* getCommunication(const QString& id); // reimplemented from CommunicationChannel virtual Message get(); virtual Message look() const; virtual void put(const Message& m); virtual int hasMessage() const; virtual int takenMessages() const; virtual int hasRoom(const DataType* t = NULL) const; virtual bool isEnded() const; virtual void setEnded(); virtual int capacity() const {return 1;} virtual void setCapacity(int) {} virtual QVariantMap getContext() const {return context;} virtual void setContext(const QVariantMap& m) {context = m;} virtual void addComplement(IntegralBus* b) {assert(!complement);complement = b;} QString getPortId() const {return portId;} protected: virtual Message composeMessage(const Message&); protected: // type of port integral bus is binded to DataTypePtr busType; // communications with other ports QMap outerChannels; // busmap of port integral bus is binded to QStrStrMap busMap; // QMap listMap; // QVariantMap context; // IntegralBus* complement; // integral bus is binded to port with this id QString portId; // int takenMsgs; }; // IntegralBus }//Workflow namespace }//GB2 namespace #endif // _U2_WORKFLOW_INTEGRAL_BUS_H_ ugene-1.9.8/src/corelibs/U2Lang/src/model/ActorModel.h0000644000175000017500000001576611651544333021110 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_WORKFLOW_MODEL_H_ #define _U2_WORKFLOW_MODEL_H_ #include #include #include #include #include #include #include #include #include namespace U2 { namespace Workflow { class Actor; class ActorDocument; class Prompter; /** * Actor represents particular semantic template * and can be configured via set of template-specific parameters * ActorPrototype is such a template */ class U2LANG_EXPORT ActorPrototype : public VisualDescriptor { public: ActorPrototype(const Descriptor& desc, const QList& ports = QList(), const QList& attrs = QList()); virtual ~ActorPrototype(); QList getPortDesciptors() const; QList getAttributes() const; Attribute * getAttribute( const QString & id ) const; void addAttribute( Attribute * a ); int removeAttribute( Attribute * attr ); void setEditor(ConfigurationEditor* e); ConfigurationEditor * getEditor() const; // validator has setter but no getter void setValidator(ConfigurationValidator* v); // prompter has no getter void setPrompter(Prompter* p); // port validators has no getters // all validators will be used as validator in corresponding port // see createInstance() void setPortValidator(const QString& id, ConfigurationValidator* v); // for drag'n'drop purposes virtual bool isAcceptableDrop(const QMimeData*, QVariantMap* = NULL) const; virtual Actor* createInstance(AttributeScript *script = NULL, const QVariantMap& params = QVariantMap()); void setScriptFlag(bool flag = true); bool isScriptFlagSet() {return isScript;} protected: // create port and sets p as owner of new port // caller should add created port to actor's ports see createInstance virtual Port* createPort(const PortDescriptor& d, Actor* p); protected: // list of attributes // can be changed via addAttribute and removeAttribute QList attrs; // list of port's // real Port's are created via createPort QList ports; // controller for actor's configuration editor ConfigurationEditor* ed; // makes any non-trivial validations ConfigurationValidator* val; // some realization of Prompter (e.g. PrompterBaseImpl) Prompter* prompter; // as if each port is configuration // we need port validators // QString here - id of corresponding PortDescriptor QMap portValidators; // actor can be written on a script by user // in such case user can define attributes and input, output ports of actor bool isScript; }; // ActorPrototype /** * It is a configuration - it has set of named attributes * with set of Ports and links between them * * represents one of ActorPrototypes * Peer is needed for saving Worker that is associated with current actor (see SimplestSequentialScheduler::tick()) */ class U2LANG_EXPORT Actor: public QObject, public Configuration, public Peer { Q_OBJECT public: virtual ~Actor(); ActorPrototype* getProto() const; // currently, size_t(this) is used // such id will change between 2 ugene launches ActorId getId() const; QString getLabel() const; void setLabel(const QString& l); Port* getPort(const QString& id) const; QList getPorts() const; QList getInputPorts() const; QList getOutputPorts() const; // reimplemented: Configuration::setParameter virtual void setParameter(const QString& name, const QVariant& val); // NULL if description not set by user ActorDocument* getDescription() const; void setDescription(ActorDocument* d); const QMap & getParamAliases() const; QMap & getParamAliases(); bool hasParamAliases() const; const QMap & getAliasHelp() const; QMap & getAliasHelp(); bool hasAliasHelp() const; // reimplemented: Configuration::remap virtual void remap(const QMap&); // setups variables for script void setupVariablesForPort(); void setupVariablesForAttribute(); AttributeScript *getScript() const; void setScript(AttributeScript* _script); signals: void si_labelChanged(); void si_modified(); protected: friend class ActorPrototype; Actor(ActorPrototype* proto, AttributeScript *script); Actor(const Actor&); protected: // name of actor // can be set by user // default is: 'proto->getDisplayName() actorId' QString label; // semantic template of this actor ActorPrototype* proto; // ports, binded to their names QMap ports; // description of actor // has setter and getter ActorDocument* doc; // user can set aliases for schema parameters and use them in cmdline // ( paramName, alias ) pairs QMap paramAliases; // (alias, alias help message) pairs QMap aliasHelpDescs; // actor can be written on script // this object identifies it's text and variables AttributeScript * script; }; // Actor /** * base class for container of rich document of actor's description */ class U2LANG_EXPORT ActorDocument : public QTextDocument { public: ActorDocument(Actor* a); virtual ~ActorDocument() {} // actor's description is changed when attribute value changes // e.g. "read sequence from '1.fa'" // see realization in PrompterBaseImpl virtual void update(const QVariantMap& ) = 0; protected: // document's target Actor* target; }; // ActorDocument /** * base class for factory of Actor's documents */ class U2LANG_EXPORT Prompter { public: virtual ActorDocument* createDescription(Actor*) = 0; virtual ~Prompter() {}; }; // Prompter }//Workflow namespace }//GB2 namespace #endif // _U2_WORKFLOW_MODEL_H_ ugene-1.9.8/src/corelibs/U2Lang/src/model/ConfigurationValidator.h0000644000175000017500000000272511651544333023523 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_WORKFLOW_CONFIGURATION_VALIDATOR_H_ #define _U2_WORKFLOW_CONFIGURATION_VALIDATOR_H_ #include namespace U2 { class Configuration; /** * base class for configuration validators * standard Configuration::validate does only simple validations: checks if required attribute is not empty * here you can set non-trivial validations */ class U2LANG_EXPORT ConfigurationValidator { public: virtual ~ConfigurationValidator() { } virtual bool validate(const Configuration*, QStringList& output) const = 0; }; // ConfigurationValidator } // U2 #endif // _U2_WORKFLOW_CONFIGURATION_VALIDATOR_H_ ugene-1.9.8/src/corelibs/U2Lang/src/model/Peer.h0000644000175000017500000000270511651544333017737 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_WORKFLOW_PEER_H_ #define _U2_WORKFLOW_PEER_H_ #include namespace U2 { namespace Workflow { /** * wrapper throw 'void*' * use as a base class to store any pointer in your class */ class U2LANG_EXPORT Peer { public: Peer() : peer(NULL) {} virtual ~Peer() {} // casting to whatever you want template inline T* castPeer() const { return (T*)(peer); } void* getPeer() const {return peer;} void setPeer(void* p) { peer = p; } protected: // any pointer void* peer; }; // Peer } // Workflow } // U2 #endif // _U2_WORKFLOW_PEER_H_ ugene-1.9.8/src/corelibs/U2Lang/src/model/IntegralBusType.cpp0000644000175000017500000000655711651544333022471 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "IntegralBusType.h" #include "IntegralBusModel.h" #include namespace U2 { namespace Workflow { IntegralBusType::IntegralBusType(const Descriptor& d, const QMap& m) : MapDataType(d, m) { } Descriptor IntegralBusType::assignSlotDesc(const Descriptor& d, const Port* p) { QString id = QString("%1:%2").arg(p->owner()->getId()).arg(d.getId()); QString name = U2::Workflow::IntegralBusPort::tr("%1 (by %2)").arg(d.getDisplayName()).arg(p->owner()->getLabel()); QString doc = d.getDocumentation(); return Descriptor(id, name, doc); } ActorId IntegralBusType::parseSlotDesc(const QString& id) { QStringList lst = id.split(":"); QString sid = lst.first(); ActorId aid = str2aid(sid); return aid; } QString IntegralBusType::parseAttributeIdFromSlotDesc(const QString & str) { QStringList lst = str.split(":"); if( lst.size() == 2 ) { return lst.at(1); } else { return QString(); } } void IntegralBusType::remap(QStrStrMap& busMap, const QMap& m) { foreach(QString key, busMap.uniqueKeys()) { QStringList newValList; foreach(QString val, busMap.value(key).split(";")) { QStringList lst = val.split(":"); QString sid = lst.first(); ActorId id = str2aid(sid); coreLog.trace("trying remap key="+key+" sid="+sid); if (m.contains(id)) { QString newSid = QString("%1").arg(m.value(id)); lst.replace(0, newSid); QString newVal = lst.join(":"); coreLog.trace("remapping old="+val+" to new="+newVal); val = newVal; } newValList.append(val); } busMap.insert(key, newValList.join(";")); } } void IntegralBusType::addInputs(const Port* p) { if (p->isInput()) { foreach(Port* peer, p->getLinks().uniqueKeys()) { DataTypePtr pt = peer->getType(); if (qobject_cast(peer)) { assert(pt->isMap()); map.unite(pt->getDatatypesMap()); } else { addOutput(pt, peer); } } } } void IntegralBusType::addOutput(DataTypePtr t, const Port* producer) { if (t->isMap()) { foreach(Descriptor d, t->getAllDescriptors()) { map[assignSlotDesc(d, producer)] = t->getDatatypeByDescriptor(d); } } else { map[assignSlotDesc(*producer, producer)] = t; } } }//Workflow namespace }//GB2namespace ugene-1.9.8/src/corelibs/U2Lang/src/model/ConfigurationEditor.h0000644000175000017500000000440411651544333023020 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_WORKFLOW_CFG_EDITOR_H_ #define _U2_WORKFLOW_CFG_EDITOR_H_ #include #include class QWidget; namespace U2 { class ConfigurationEditor; class PropertyDelegate; /** * base class for controller of configuration editor * editing comes from delegates (see PropertyDelegate) */ class U2LANG_EXPORT ConfigurationEditor { public: enum ItemValueRole { ItemValueRole = Qt::UserRole + 2, ItemListValueRole }; // ItemValueRole public: virtual ~ConfigurationEditor() {} // editing widget virtual QWidget* getWidget() { return NULL; } // this controller is a container of delegates virtual PropertyDelegate* getDelegate(const QString&) { return NULL; } virtual PropertyDelegate* removeDelegate( const QString&) { return NULL; } virtual void addDelegate( PropertyDelegate * , const QString & ) {} // commit data to model virtual void commit() {} }; // ConfigurationEditor /** * provides display and editing facilities for data items * in our case, inheritors will provide this facilities for attributes of configuration */ class U2LANG_EXPORT PropertyDelegate : public QItemDelegate { public: PropertyDelegate(QObject * parent = 0) : QItemDelegate(parent) {} virtual ~PropertyDelegate() {} virtual QVariant getDisplayValue(const QVariant& v) const {return v;} }; // PropertyDelegate }//GB2 namespace #endif ugene-1.9.8/src/corelibs/U2Lang/src/model/QueryDesignerRegistry.cpp0000644000175000017500000000247011651544333023715 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "QueryDesignerRegistry.h" namespace U2 { void QDActorPrototypeRegistry::registerProto(QDActorPrototype* _factory) { IdRegistry::registerEntry(_factory); emit si_registryModified(); } QDActorPrototype* QDActorPrototypeRegistry::unregisterProto(const QString& id) { QDActorPrototype* removed = IdRegistry::unregisterEntry(id); if(removed) { emit si_registryModified(); } return removed; } }//namespace ugene-1.9.8/src/corelibs/U2Lang/src/model/WorkflowTransport.cpp0000644000175000017500000000245311651544333023126 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "WorkflowTransport.h" namespace U2 { namespace Workflow { Message::Message(DataTypePtr _t, const QVariant& d) : id(nextid()), t(_t), data(d) { } int Message::nextid() { static QAtomicInt id(0); return id.fetchAndAddRelaxed(1); //memory model?? } int Message::getId() const { return id; } DataTypePtr Message::getType() const { return t; } QVariant Message::getData() const { return data; } } //Workflow namespace } //GB2 namespace ugene-1.9.8/src/corelibs/U2Lang/src/model/ExternalToolCfg.h0000644000175000017500000000336011651544333022102 0ustar ilyailya#ifndef ExternalToolCfg_h__ #define ExternalToolCfg_h__ #include #include #include #include #include #include namespace U2 { #define SEQ_WITH_ANNS QString("Sequence_with_annotations") class U2LANG_EXPORT DataConfig { public: QString attrName; QString type; QString format; QString description; }; class U2LANG_EXPORT AttributeConfig { public: QString attrName; QString type; QString description; //PropertyDelegate *delegate; }; class U2LANG_EXPORT ExternalProcessConfig { public: QList inputs; QList outputs; QList attrs; QString cmdLine; QString name; QString description; QString templateDescription; }; class U2LANG_EXPORT ExternalToolCfgRegistry: public QObject { Q_OBJECT public: ExternalToolCfgRegistry(QObject *p = NULL): QObject(p) {} bool registerExternalTool(ExternalProcessConfig *cfg) { if(configs.contains(cfg->name)) { return false; } else { configs.insert(cfg->name, cfg); return true; } } ExternalProcessConfig *getConfigByName(const QString& name) const { if(configs.contains(name)) { return configs.value(name); } else { return NULL; } } void unregisterConfig(const QString &name) { configs.remove(name); } QList getConfigs() const { return configs.values(); } private: QMap configs; }; } #endif // ExternalToolCfg_h__ ugene-1.9.8/src/corelibs/U2Lang/src/model/Datatype.cpp0000644000175000017500000000652111651544333021152 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "Datatype.h" namespace U2 { /***************************** * DataType *****************************/ DataType::DataType(const QString& id, const QString& name, const QString& desc) : Descriptor(id, name, desc){ } DataType::DataType(const Descriptor& d) : Descriptor(d) { } DataType::Kind DataType::kind() const { return Single; } QList DataType::getAllDescriptors()const { return QList(); } QMap DataType::getDatatypesMap() const { return QMap(); } DataTypePtr DataType::getDatatypeByDescriptor(const Descriptor& idd) const { Q_UNUSED(idd); return DataTypePtr(); } Descriptor DataType::getDatatypeDescriptor(const QString& id) const { QList lst = getAllDescriptors(); int idx = lst.indexOf(id); return idx == -1 ? "" : lst.at(idx); } /***************************** * MapDataType *****************************/ MapDataType::MapDataType(const Descriptor& d, const QMap& m) : DataType(d), map(m) { } DataType::Kind MapDataType::kind() const { return DataType::Map; } DataTypePtr MapDataType::getDatatypeByDescriptor(const Descriptor& d) const { return map.value(d); } QList MapDataType::getAllDescriptors() const { return map.uniqueKeys(); } QMap MapDataType::getDatatypesMap() const { return map; } /***************************** * ListDataType *****************************/ ListDataType::ListDataType(const Descriptor& d, DataTypePtr el) : DataType(d), listElementDatatype(el) { } DataType::Kind ListDataType::kind() const { return DataType::List; } DataTypePtr ListDataType::getDatatypeByDescriptor(const Descriptor& idd) const { Q_UNUSED(idd); return listElementDatatype; } /***************************** * DatatypeRegistry *****************************/ DataTypeRegistry::~DataTypeRegistry() { registry.clear(); } DataTypePtr DataTypeRegistry::getById(const QString& id) const { return registry.value(id); } bool DataTypeRegistry::registerEntry(DataTypePtr t) { if (registry.contains(t->getId())) { return false; } else { registry.insert(t->getId(), t); return true; } } DataTypePtr DataTypeRegistry::unregisterEntry(const QString& id) { return registry.take(id); } QList DataTypeRegistry::getAllEntries() const { return registry.values(); } QList DataTypeRegistry::getAllIds() const { return registry.uniqueKeys(); } } // U2 ugene-1.9.8/src/corelibs/U2Lang/transl/0000755000175000017500000000000011651544333016303 5ustar ilyailyaugene-1.9.8/src/corelibs/U2Lang/transl/russian.ts0000644000175000017500000017267711651544333020363 0ustar ilyailya QObject Min distance Minimum distance Max distance Maximum distance %1. %2 Invalid distance values Constraints can not be placed between elements of the same group Incorrect number of arguments Incorrect arguments Empty or invalid sequence Alphabet must be nucleotide Offset must be from interval [0,2] Translation table is empty Second argument must be a number Position is out of range Invalid alignment Row is out of range Offset is out of range Length is out of range Alphabets of each sequence must be the same Alphabets don't match Third argument must be a number Invalid annotations Empty name Empty qualifier name Empty qualifier value forth argument must be a string Index is out of range U2::BaseTypes Sequence Последовательность A sequence Биологически-значимая последовательность (ДНК, РНК, протеины) Set of DNA annotations Набор аннотаций A set of annotated features in a DNA sequence Набор (список) аннотированных регионов биологической последовательности List of Annotations Набор аннотаций A list of DNA sequence annotations Набор (список) аннотированных регионов биологической последовательности Multiple Aligment Множественное выравнивание Set of aligned sequences Множественное выравнивание String Тип Строка A string of characters Строка символов Boolean Логический тип A boolean value (true/false) Значение бинарной логики (истина/ложь) Number Числовой тип A number Число Undefined Неопределённый тип A void type Пустое значение U2::BioDataTypes Sequence Последовательность A sequence Биологически-значимая последовательность (ДНК, РНК, протеины) Annotation Аннотация An annotation of a sequence region Аннотированный регион биологической последовательности, имеет имя и набор квалификаторов Set of DNA annotations Набор аннотаций A set of annotated features in a DNA sequence Набор (список) аннотированных регионов биологической последовательности. List of Annotations Набор аннотаций A list of DNA sequence annotations Набор (список) аннотированных регионов биологической последовательности. Chromatogram Хроматограмма A sequence chromatogram Хроматограмма биологической последовательности. Multiple Aligment Множественное выравнивание Set of aligned sequences Множественное выравнивание U2::CoreDataTypes String Тип Строка A string of characters Строка символов. Boolean Логический тип A boolean value (true/false) Значение бинарной логики (истина/ложь) Number Числовой тип A number Число Undefined Неопределённый тип A void type Пустое значение U2::CreateSchemaForTask CreateSchemaTask Создание Схемы Can't find schema file %1 Не могу найти файл схемы %1 U2::DescriptorListEditorDelegate <empty> <пустой> Default value Значение по умолчанию <List of values> <Список значений> List of values Список значений U2::HRSchemaSerializer Error: unknown exception caught Undefined construct at '%1 %2' Undefined block in .meta: '%1' Parameter '%1' undefined for element '%2' Cannot parse value from '%1': no value factory Cannot parse value from '%1' Unexpected end of file Неожиданный конец файла Expected '%1', got %2 Expected '%1', near '%2' Expected %3 or %1 after %2 %2 expected after %1 Cannot create flow graph XML schema format is obsolete and not supported Bad header: expected '%1', got '%2' Schema name not specified Element name cannot contain whitespaces: '%1' Element name cannot contain dots: '%1' Element '%1' already defined Type attribute not set for %1 element Unknown type of %1 element: %2 Name attribute not set for %1 element No other blocks allowed in aliases block %1 definition expected at .iterations block Cannot parse integer from '%1': iteration id Element id '%1' undefined in .iteration block No block definitions allowed in .iteration block: %1 %1 element undefined in aliases block %1 has no parameter %2: in aliases block No other blocks allowed in help block Undefined parameter alias used in help block: '%1' Undefined element id '%1' at '%2' Undefined slot id '%1' at '%2' Undefined port id '%1' at '%2' Destination port should be input: %1 Undefined element id: '%1' Cannot find '%1' port at '%2' Cannot bind %1:%2 to %3:%4 U2::LoadWorkflowTask Loading schema Загрузка схемы Loading schema from file: %1 Чтение схемы из файла: %1 Undefined format: plain text or xml expected Sorry! XML schema format is obsolete and not supported. You can create new schema in GUI mode or write it by yourself. Check our documentation for details! Invalid content: %1 Невалидное содержимое xml-файла:%1 U2::MapDatatypeEditor Data on the bus Доступные данные Accepted inputs Входные данные The input slot <b>%1</b><br>is bound to<br>the bus slot <b>%2</b> Входной слот <b>%1</b><br>привязан к<br>слоту шины <b>%2</b> Provided outputs Выходные данные U2::PrompterBaseImpl unset не указан file(s) alongside of input sources of <u>%1</u> файл(ы) рядом с исходным(и) <u>%1</u> the list of files список файлов U2::RunSchemaForTask %1 actors in schema have '%2' alias %1 объектов схемы имеют %2 параметр alias '%1' not set in schema параметр %1 не задан в схеме actor parameter '%1' not found параметр %1 не найден U2::SaveWorkflowTask Save workflow schema task U2::Workflow::BaseActorCategories Data Readers Чтение данных Data Writers Запись данных Data Converters Конвертация данных Basic Analysis Базовый анализ Utils Утилиты Multiple Sequence Alignment Множественное выравнивание DNA Assembly Сборка ДНК Transcription Factor Фактор транскрипции Custom Elements with Script Элементы пользователя со скриптами Custom Elements with CMD Tools Элементы пользователя с внешними утилитами U2::Workflow::BaseAttributes Input files Входные файлы Semicolon-separated list of paths to the input files. Пути к файлам входных данных. Output file Выходной файл Location of output data file. If this attribute is set, slot "Location" in port will not be used Путь до выходного файла данных. Если даный атрибут задан, то слот "Путь к файлу" порта не будет задействован Located on Расположение файлов Machine file(s) are located on Компьютер, на котором расположены входные файлы Document format Формат файла Document format of output file Формат выходного файла Accumulate objects Объединить объекты Accumulate all incoming data in one file or create separate files for each input.In the latter case, an incremental numerical suffix is added to the file name. Объединить все данные в один файли или создать отдельные файлы. В последнем случае к имени файлов будет добавлен порядковый суффикс. Read by lines Читать по строкам Read input file by lines Читать входной файл по строкам Existing file Файл уже существует If a target file already exists, you can specify how it should be handled: either overwritten, renamed or appended (if supported by file format). If Rename option is chosen existing file will be renamed. Если указанный файл уже существует, вы можете указать как его обработать: переписать, переименовать или добавить к нему данные (если поддерживается форматом). Если выбрана опция переименовать, будет переименован существующий файл. Search in Искать в Which strands should be searched: direct, complement or both. Ищет в прямой, комлементарной или обеих цепях последовательности. both strands обеих цепях direct strand прямой цепи complementary strand комплементарной цепи U2::Workflow::BaseSlots Sequence Последовательность A biological sequence Биологически-значимая последовательность (ДНК,РНК,протеины) MSA Множественное выравнивание A multiple sequence alignment Множественное выравнивание Set of annotations Набор аннотаций A set of annotated regions Набор (список) аннотированных регионов Plain text Текст Plain text reading or splitting to strings. Source URL Путь до файла Location of a corresponding input file. Путь до соответствующего входного файла. FASTA header FASTA заголовок A header line for the FASTA record. Строка заголовка для FASTA последовательности. U2::Workflow::BioActorLibrary Data sources Источники данных Data sinks Приёмники данных Other Разное Basic analysis Базовый анализ Multiple sequence alignment Множественные выравнивания DNA assembly Сборка ДНК Transcription factor Фактор транскрипции Custom elements Элементы пользователя Sequence Последовательность A biological sequence Биологически-значимая последовательность (ДНК,РНК,протеины) MSA Множественное выравнивание A multiple sequence alignment Множественное выравнивание Set of annotations Набор аннотаций A set of annotated regions Набор (список) аннотированных регионов Existing file Файл уже существует If a target file already exists, you can specify how it should be handled: either overwritten, renamed or appended (if supported by file format). Если записываемый файл уже существует, можно указать что с ним делать: перезаписать поверх, переименовать или дописать в конец файла. U2::Workflow::CoreLibConstants Location Путь к файлу Semicolon-separated list of paths to the input files. Пути к файлам входных данных. Input files Входные файлы Location of output data file Пути к файлам выходных данных Output files Выходные файлы Plain text Текст Location of output data file. If this attribute is set, slot "Location" in port will not be used Путь до выходного файла данных. Если даный атрибут задан, то слот "Путь к файлу" порта не будет задействован Source URL Путь до файла Location of a corresponding input file. Путь до соответствующего входного файла. Located on Расположение файлов Machine file(s) are located on Компьютер, на котором расположены входные файлы U2::Workflow::IntegralBusPort No input data supplied Не обеспечен входными данными Warning, empty input slot: %1 Внимание, пустой слот входных данных: %1 Bad slot binding: %1 to %2 Неправильная привязка слота: %1 к %2 %1 (by %2) %1 (из %2) U2::Workflow::SchemaSerializer no metadata Нет описания схемы Invalid content: duplicate process %1 Обнаружен дублирующий идентификатор задачи: %1 Invalid content: unknown process type %1 Неизвестный тип задачи: %1 Invalid content: unknown port %1 requested for %2 Неизвестный порт %1 для задачи %2 Invalid content: no such process %1 to bind Соединение с несуществующей задачей: %1 Invalid content: cannot bind [%1 : %2] to [%3 : %4] Не удалось соединить порты задач: [%1 : %2] к [%3 : %4] U2::WorkflowIterationRunInProcessTask Cannot create temporary file for saving schema! U2::WorkflowIterationRunTask Unknown domain %1 Неизвестное имя среды исполнения: %1 Failed to create worker %1 %2 in domain %3 Не удалось создать процесс %1 %2 для среды исполнения %3 Failed to create connection %1 %2 in domain %3 Не удалось создать соединение процессов %1 %2 для среды исполнения %3 Failed to create scheduler in domain %1 Не удалось создать планировщик для среды исполнения %1 No workers are ready, while not all workers are done. Schema is broken? Все процессы находятся в состоянии "не готовы" (обработали входные данные), но не все процессы находятся в состоянии "завершил исполнение". Пожалуйста, проверьте схему. Schema did not finish. Схема завершена не полностью. U2::WorkflowRunInProcessMonitorTask Monitoring execution of workflow schema Cannot start process '%1' The process '%1' failed to start. Either the invoked program is missing, or you may have insufficient permissions to invoke the program The process '%1' crashed some time after starting successfully Error occurred while reading from or writing to channel Unknown error occurred U2::WorkflowRunInProcessTask Execute workflow in separate process Iterations Итерации Status Состояние Details Детали Failed Провалилась Canceled Отменена Finished Завершена Output files: U2::WorkflowRunSchemaForTask Run workflow schema for task %1 Cannot create temporary file for writing Cannot create temporary file for reading and writing Internal error: cannot find schema %1 Internal error: cannot find alias '%1' for schema '%2' Internal error: cannot find attribute '%1' for schema '%2' U2::WorkflowRunTask Execute workflow schema Выполнение вычислительной схемы Execute workflow Main Основная Iterations Итерации Status Состояние Details Детали Failed Провалилась Canceled Отменена Finished Завершена Output files: U2::WorkflowUtils Required parameter is not set: %1 Не указан обязательный параметр "%1" Either parameter '%1' or input slot '%2' must be set Необходимо указать значение для параметра "%1" либо связать входной слот "%2" Warning, parameter '%1' overrides bus data slot '%2' Внимание, установленный параметр "%1" переопределяет входной слот "%2" Iteration '%3', %1 : %2 Итерация '%3', %1 : %2 %2: Required parameter is not set: %1 (use --%3 option) %2: Не задан необходимый параметр: %1 (используйте опцию --%3) <empty> <пустой> Default value Значение по умолчанию <List of values> <Список значений> List of values Список значений %1 actors in schema have '%2' alias %1 объектов схемы имеют %2 параметр ugene-1.9.8/src/corelibs/U2Lang/transl/czech.ts0000644000175000017500000013341211651544333017753 0ustar ilyailya QObject Min distance Minimum distance Max distance Maximum distance %1. %2 Invalid distance values Constraints can not be placed between elements of the same group U2::BaseTypes Sequence Sekvence A sequence Sekvence Set of DNA annotations Soubor poznámek k DNA A set of annotated features in a DNA sequence Soubor znaků opatřených poznámkou v sekvenci DNA List of Annotations Seznam poznámek A list of DNA sequence annotations Seznam poznámek k sekvenci DNA Multiple Aligment Společné zarovnání Set of aligned sequences Soubor zarovnaných sekvencí String Řetězec A string of characters Řetězec znaků Boolean Booleánský A boolean value (true/false) Booleánská hodnota (pravdivé/chybné) Number Číslo A number Číslo Undefined Nestanoveno A void type Typ prázdného místa U2::BioDataTypes Sequence Sekvence A sequence Sekvence Set of DNA annotations Soubor poznámek k DNA A set of annotated features in a DNA sequence Soubor znaků opatřených poznámkou v sekvenci DNA List of Annotations Seznam poznámek A list of DNA sequence annotations Seznam poznámek k sekvenci DNA Multiple Aligment Společné zarovnání Set of aligned sequences Soubor zarovnaných sekvencí Aligned set of sequences Set of aligned sequences U2::CoreDataTypes String Řetězec A string of characters Řetězec znaků Boolean Booleánský A boolean value (true/false) Booleánská hodnota (pravdivé/chybné) Number Číslo A number Číslo Undefined Nestanoveno A void type Typ prázdného místa U2::DescriptorListEditorDelegate <empty> <prázdný> Default value Výchozí hodnota <List of values> <Seznam hodnot> List of values Seznam hodnot U2::HRSchemaSerializer XML schema format is obsolete and not supported Bad header: expected '%1', got '%2' Schema name not specified Parameter '%1' undefined for element '%2' Error: unknown exception caught Undefined construct at '%1 %2' Undefined block in .meta: '%1' Cannot parse value from '%1': no value factory Cannot parse value from '%1' Unexpected end of file Expected '%1', got %2 Expected '%1', near '%2' Expected %3 or %1 after %2 %2 expected after %1 Cannot create flow graph Element name cannot contain whitespaces: '%1' Element name cannot contain dots: '%1' Element '%1' already defined Type attribute not set for %1 element Unknown type of %1 element: %2 Name attribute not set for %1 element No other blocks allowed in aliases block %1 definition expected at .iterations block Cannot parse integer from '%1': iteration id Element id '%1' undefined in .iteration block No block definitions allowed in .iteration block: %1 %1 element undefined in aliases block %1 has no parameter %2: in aliases block No other blocks allowed in help block Undefined parameter alias used in help block: '%1' Undefined element id '%1' at '%2' Undefined slot id '%1' at '%2' Undefined port id '%1' at '%2' Destination port should be input: %1 Undefined element id: '%1' Cannot find '%1' port at '%2' Cannot bind %1:%2 to %3:%4 U2::LoadWorkflowTask Loading schema Nahrává se schéma Loading schema from file: %1 Nahrává se schéma ze souboru: %1 Undefined format: plain text or xml expected Sorry! XML schema format is obsolete and not supported. You can create new schema in GUI mode or write it by yourself. Check our documentation for details! Invalid content: %1 Invalid xml content:%1 U2::MapDatatypeEditor Data on the bus Data na sběrnici Accepted inputs Přijaté vstupy Data from bus Data ze sběrnice The input slot <b>%1</b><br>is bound to<br>the bus slot <b>%2</b> Vstupní místo <b>%1</b><br>je spojeno s<br>místem sběrnice <b>%2</b> Provided outputs Poskytnuté výstupy U2::PrompterBaseImpl unset Nenastavený file(s) alongside of input sources of <u>%1</u> Soubor(y) společně se vstupními zdroji <u>%1</u> the list of files Seznam souborů U2::RunSchemaForTask %1 actors in schema have '%2' alias %1 objects in schema have '%2' alias U2::SaveWorkflowTask Save workflow schema task U2::Workflow::BaseActorCategories Data sources Zdroje dat Data sinks Jímky dat Data converters Basic analysis Základní rozbor Utils Multiple sequence alignment Více zarovnání sekvence DNA assembly Shromáždění DNA Transcription factor Custom elements U2::Workflow::BaseAttributes Input files Vstupní souborů Semicolon-separated list of paths to the input files. Output file Výstupní soubor Location of output data file. If this attribute is set, slot "Location" in port will not be used Located on Umístěn na Machine file(s) are located on Soubor(y) stroje jsou umístěny na Document format Document format of output file Accumulate objects Accumulate all incoming data in one file or create separate files for each input.In the latter case, an incremental numerical suffix is added to the file name. Read by lines Read input file by lines Existing file Stávající soubor If a target file already exists, you can specify how it should be handled: either overwritten, renamed or appended (if supported by file format). If Rename option is chosen existing file will be renamed. If a target file already exists, you can specifyhow it should be handled: either overwritten, renamed or appended (if supported by file format). Pokud cílový soubor již existuje, můžete zadat, jak se s ním má zacházet: buď přepsat, přejmenovat nebo přidat (pokud je od formátu souboru podporován). Search in Which strands should be searched: direct, complement or both. both strands direct strand complementary strand U2::Workflow::BaseSlots Sequence Sekvence A biological sequence Biologická sekvence MSA A multiple sequence alignment Více zarovnání sekvence Set of annotations Soubor poznámek A set of annotated regions Soubor oblastí opatřených poznámkou Plain text Plain text reading or splitting to strings. Source URL Zdrojová adresa (URL) Location of a corresponding input file. Umístění odpovídajícího vstupního souboru. FASTA header A header line for the FASTA record. U2::Workflow::BioActorLibrary Data sources Zdroje dat Data sinks Jímky dat Basic analysis Základní rozbor Multiple sequence alignment Více zarovnání sekvence DNA assembly Shromáždění DNA Sequence Sekvence A biological sequence Biologická sekvence A multiple sequence alignment Více zarovnání sekvence Set of annotations Soubor poznámek A set of annotated regions Soubor oblastí opatřených poznámkou Existing file Stávající soubor If a target file already exists, you can specifyhow it should be handled: either overwritten, renamed or appended (if supported by file format). Pokud cílový soubor již existuje, můžete zadat, jak se s ním má zacházet: buď přepsat, přejmenovat nebo přidat (pokud je od formátu souboru podporován). U2::Workflow::CoreLibConstants Input files Vstupní souborů Output file Výstupní soubor Source URL Zdrojová adresa (URL) Location of a corresponding input file. Umístění odpovídajícího vstupního souboru. Located on Umístěn na Machine file(s) are located on Soubor(y) stroje jsou umístěny na U2::Workflow::IntegralBusPort No input data supplied Neopatřena žádná vstupní data Warning, empty input slot: %1 Varování, prázdné vstupní místo: %1 Bad slot binding: %1 to %2 Špatné svázání místa: %1 s %2 %1 (by %2) %1 (od %2) U2::Workflow::SchemaSerializer no metadata Žádná metadata Invalid content: duplicate process %1 Neplatný obsah: zdvojený proces %1 Invalid content: unknown process type %1 Neplatný obsah: neznámý typ procesu %1 Invalid content: unknown port %1 requested for %2 Neplatný obsah: neznámá přípojka %1 požadována pro %2 Invalid content: no such process %1 to bind Neplatný obsah: žádný takový proces %1 ke svázání Invalid content: cannot bind [%1 : %2] to [%3 : %4] Neplatný obsah: nelze svázat [%1 : %2] s [%3 : %4] U2::WorkflowIterationRunInProcessTask Cannot create temporary file for saving schema! U2::WorkflowIterationRunTask Unknown domain %1 Neznámá doména %1 Failed to create worker %1 %2 in domain %3 Nepodařilo se vytvořit pracovníka %1 %2 v doméně %3 Failed to create connection %1 %2 in domain %3 Nepodařilo se vytvořit spojení %1 %2 v doméně %3 Failed to create scheduler in domain %1 Nepodařilo se vytvořit plánovač v doméně %1 No workers are ready, while not all workers are done. Schema is broken? U2::WorkflowRunInProcessMonitorTask Monitoring execution of workflow schema Cannot start process '%1' The process '%1' failed to start. Either the invoked program is missing, or you may have insufficient permissions to invoke the program The process '%1' crashed some time after starting successfully Error occurred while reading from or writing to channel Unknown error occurred U2::WorkflowRunInProcessTask Execute workflow in separate process Iterations Opakování Status Stav Details Podrobnosti Failed Nepodařilo se Canceled Zrušeno Finished Dokončeno Output files: U2::WorkflowRunSchemaForTask Run workflow schema for task %1 Cannot create temporary file for writing Cannot create temporary file for reading and writing Internal error: cannot find schema %1 Internal error: cannot find alias '%1' for schema '%2' Internal error: cannot find attribute '%1' for schema '%2' U2::WorkflowRunTask Execute workflow Provést nákres pracovního postupu Iterations Opakování Status Stav Details Podrobnosti Failed Nepodařilo se Canceled Zrušeno Finished Dokončeno Output files: U2::WorkflowUtils Required parameter is not set: %1 Požadovaný parametr není nastaven: %1 Either parameter '%1' or input slot '%2' must be set Musí být nastaven buď parametr '%1' nebo vstupní místo '%2' Warning, parameter '%1' overrides bus data slot '%2' Varování, parameter '%1' potlačuje místo s daty sběrnice '%2' Iteration '%3', %1 : %2 Opakování '%3', %1 : %2 %2: Required parameter is not set: %1 (use --%3 option) <empty> <prázdný> Default value Výchozí hodnota <List of values> <Seznam hodnot> List of values Seznam hodnot %1 actors in schema have '%2' alias %1 objects in schema have '%2' alias ugene-1.9.8/src/corelibs/U2Lang/transl/english.ts0000644000175000017500000013172611651544333020316 0ustar ilyailya QObject Min distance Minimum distance Max distance Maximum distance %1. %2 Invalid distance values Constraints can not be placed between elements of the same group Incorrect number of arguments Incorrect arguments Empty or invalid sequence Alphabet must be nucleotide Offset must be from interval [0,2] Translation table is empty Second argument must be a number Position is out of range Invalid alignment Row is out of range Offset is out of range Length is out of range Alphabets of each sequence must be the same Alphabets don't match Third argument must be a number Invalid annotations Empty name Empty qualifier name Empty qualifier value forth argument must be a string Index is out of range U2::BaseTypes Sequence A sequence Set of DNA annotations A set of annotated features in a DNA sequence List of Annotations A list of DNA sequence annotations Multiple Aligment Set of aligned sequences String A string of characters Boolean A boolean value (true/false) Number A number Undefined A void type U2::DescriptorListEditorDelegate <empty> Default value <List of values> List of values U2::HRSchemaSerializer Error: unknown exception caught Undefined construct at '%1 %2' Undefined block in .meta: '%1' Parameter '%1' undefined for element '%2' Cannot parse value from '%1': no value factory Cannot parse value from '%1' Unexpected end of file Expected '%1', got %2 Expected '%1', near '%2' Expected %3 or %1 after %2 %2 expected after %1 Cannot create flow graph XML schema format is obsolete and not supported Bad header: expected '%1', got '%2' Schema name not specified Element name cannot contain whitespaces: '%1' Element name cannot contain dots: '%1' Element '%1' already defined Type attribute not set for %1 element Unknown type of %1 element: %2 Name attribute not set for %1 element No other blocks allowed in aliases block %1 definition expected at .iterations block Cannot parse integer from '%1': iteration id Element id '%1' undefined in .iteration block No block definitions allowed in .iteration block: %1 %1 element undefined in aliases block %1 has no parameter %2: in aliases block No other blocks allowed in help block Undefined parameter alias used in help block: '%1' Undefined element id '%1' at '%2' Undefined slot id '%1' at '%2' Undefined port id '%1' at '%2' Destination port should be input: %1 Undefined element id: '%1' Cannot find '%1' port at '%2' Cannot bind %1:%2 to %3:%4 U2::LoadWorkflowTask Loading schema Loading schema from file: %1 Undefined format: plain text or xml expected Sorry! XML schema format is obsolete and not supported. You can create new schema in GUI mode or write it by yourself. Check our documentation for details! U2::MapDatatypeEditor The input slot <b>%1</b><br>is bound to<br>the bus slot <b>%2</b> U2::PrompterBaseImpl unset the list of files file(s) alongside of input sources of <u>%1</u> U2::SaveWorkflowTask Save workflow schema task U2::Workflow::BaseActorCategories Data Readers Data Writers Data Converters Basic Analysis Utils Multiple Sequence Alignment DNA Assembly Transcription Factor Custom Elements with Script Custom Elements with CMD Tools U2::Workflow::BaseAttributes Input files Semicolon-separated list of paths to the input files. Output file Location of output data file. If this attribute is set, slot "Location" in port will not be used Located on Machine file(s) are located on Document format Document format of output file Accumulate objects Accumulate all incoming data in one file or create separate files for each input.In the latter case, an incremental numerical suffix is added to the file name. Read by lines Read input file by lines Existing file If a target file already exists, you can specify how it should be handled: either overwritten, renamed or appended (if supported by file format). If Rename option is chosen existing file will be renamed. Search in Which strands should be searched: direct, complement or both. both strands direct strand complementary strand U2::Workflow::BaseSlots Sequence A biological sequence MSA A multiple sequence alignment Set of annotations A set of annotated regions Plain text Plain text reading or splitting to strings. Source URL Location of a corresponding input file. FASTA header A header line for the FASTA record. U2::Workflow::IntegralBusPort No input data supplied Warning, empty input slot: %1 Bad slot binding: %1 to %2 %1 (by %2) U2::Workflow::SchemaSerializer no metadata Invalid content: duplicate process %1 Invalid content: unknown process type %1 Invalid content: unknown port %1 requested for %2 Invalid content: no such process %1 to bind Invalid content: cannot bind [%1 : %2] to [%3 : %4] U2::WorkflowIterationRunInProcessTask Cannot create temporary file for saving schema! U2::WorkflowIterationRunTask Unknown domain %1 Failed to create worker %1 %2 in domain %3 Failed to create connection %1 %2 in domain %3 Failed to create scheduler in domain %1 No workers are ready, while not all workers are done. Schema is broken? U2::WorkflowRunInProcessMonitorTask Monitoring execution of workflow schema Cannot start process '%1' The process '%1' failed to start. Either the invoked program is missing, or you may have insufficient permissions to invoke the program The process '%1' crashed some time after starting successfully Error occurred while reading from or writing to channel Unknown error occurred U2::WorkflowRunInProcessTask Execute workflow in separate process Iterations Status Details Failed Canceled Finished Output files: U2::WorkflowRunSchemaForTask Run workflow schema for task %1 Cannot create temporary file for writing Cannot create temporary file for reading and writing Internal error: cannot find schema %1 Internal error: cannot find alias '%1' for schema '%2' Internal error: cannot find attribute '%1' for schema '%2' U2::WorkflowRunTask Execute workflow Iterations Status Details Failed Canceled Finished Output files: U2::WorkflowUtils Required parameter is not set: %1 Either parameter '%1' or input slot '%2' must be set Iteration '%3', %1 : %2 %2: Required parameter is not set: %1 (use --%3 option) <empty> Default value <List of values> List of values %1 actors in schema have '%2' alias ugene-1.9.8/src/corelibs/U2Designer/0000755000175000017500000000000011651544332015656 5ustar ilyailyaugene-1.9.8/src/corelibs/U2Designer/U2Designer.pri0000644000175000017500000000121611651544332020341 0ustar ilyailya# include (U2Designer.pri) MODULE_ID=U2Designer include( ../../ugene_lib_common.pri ) UGENE_RELATIVE_DESTDIR = '' QT += svg DEFINES+= QT_FATAL_ASSERT BUILDING_U2DESIGNER_DLL LIBS += -L../../_release -lU2Core -lU2Misc -lU2Lang -lU2Gui !debug_and_release|build_pass { CONFIG(debug, debug|release) { DESTDIR=../../_debug LIBS -= -L../../_release -lU2Core -lU2Misc -lU2Lang -lU2Gui LIBS += -L../../_debug -lU2Cored -lU2Miscd -lU2Langd -lU2Guid } CONFIG(release, debug|release) { DESTDIR=../../_release } } unix { target.path = $$UGENE_INSTALL_DIR/$$UGENE_RELATIVE_DESTDIR INSTALLS += target } ugene-1.9.8/src/corelibs/U2Designer/src/0000755000175000017500000000000011651544332016445 5ustar ilyailyaugene-1.9.8/src/corelibs/U2Designer/src/QDScheduler.h0000644000175000017500000001312211651544332020760 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_QD_SCHEDULER_H_ #define _U2_QD_SCHEDULER_H_ #include #include #include namespace U2 { class AnnotationTableObject; class LoadUnloadedDocumentTask; class QDRunSettings { public: QDRunSettings(): sequenceObj(NULL), annotationsObj(NULL), scheme(NULL), offset(0), outputType(Group) {} DNASequenceObject* sequenceObj; AnnotationTableObject* annotationsObj; GObjectReference annotationsObjRef; QString groupName; U2Region region; QDScheme* scheme; QString viewName; int offset; enum OutputType { Group, Single }; OutputType outputType; }; class QDStep { public: QDStep(QDScheme* _scheme); void next(); bool hasNext() const; bool hasPrev() const; QDActor* getActor() const { return actor; } const QList& getLinkedActors() const { return linkedActors; } QList getConstraints(QDSchemeUnit* subj, QDSchemeUnit* linked) const; private: void initTotalMap(); private: QDScheme* scheme; QDActor* actor; QList linkedActors; QMap< QPair, QList > constraintsMap; }; class QDScheduler; class Annotation; class QDResultLinker { public: QDResultLinker(QDScheduler* _sched); QVector findLocation(QDStep* step); void updateCandidates(QDStep* step, int& progress); QDScheduler* getScheduler() const { return sched; } int getCandidatesNumber() const { return candidates.size(); } bool isCancelled() const { return cancelled; } void prepareAnnotations(); void createAnnotations(const QString& groupPrefix); void createMergedAnnotations(const QString& groupPrefix); void pushToTable(); private: void formGroupResults(); void processNewResults(int& progress); void initCandidates(int& progress); void updateCandidates(int& progress); bool canAdd(QDResultGroup* actorResult, QDResultGroup* candidate, bool complement) const; QDStrandOption findResultStrand(QDResultGroup* actorRes); //inverts repeat pair if any for complement search QList prepareComplResults(QDResultGroup* src) const; static QString prepareAnnotationName(const QDResultUnit& res); private: QDScheme* scheme; QDScheduler* sched; bool cancelled; QDStep* currentStep; bool needInit; QList candidates; QMap< QDResultUnit, Annotation* > result2annotation; QList currentResults; QMap< QDActor*, QList > currentGroupResults; QMap< QString, QList > annotations; }; class QDFindLocationTask : public Task { Q_OBJECT public: QDFindLocationTask(QDStep* _step, QDResultLinker* _linker) : Task(tr("Find resultLocation"), TaskFlag_None), step(_step), linker(_linker) {} void run(); QVector getSearchLocation() { return searchLocation; } QVector getResultLocation() { return resultLocation; } public: static const int REGION_DELTA; private: QDStep* step; QDResultLinker* linker; QVector resultLocation; QVector searchLocation; }; class QDLinkResultsTask : public Task { Q_OBJECT public: QDLinkResultsTask(QDStep* _step, QDResultLinker* _linker): Task(tr("Link results"), TaskFlag_None), step(_step), linker(_linker) { tpm = Progress_Manual; } void run() { linker->updateCandidates(step, stateInfo.progress); } private: QDStep* step; QDResultLinker* linker; }; class QDTask : public Task { Q_OBJECT public: QDTask(QDStep* _step, QDResultLinker* _linker); QList onSubTaskFinished(Task* subTask); private slots: void sl_updateProgress(); private: QDStep* step; QDResultLinker* linker; QDFindLocationTask* findLocationTask; Task* runTask; QVector curActorLocation; }; class U2DESIGNER_EXPORT QDCreateAnnotationsTask : public Task { Q_OBJECT public: QDCreateAnnotationsTask(QDResultLinker* linker) : Task(tr("Prepare annotations task"), TaskFlag_None), linker(linker) {} void run() { linker->prepareAnnotations(); } private: QDResultLinker* linker; }; class U2DESIGNER_EXPORT QDScheduler : public Task { Q_OBJECT public: QDScheduler(const QDRunSettings& settings); ~QDScheduler(); QList onSubTaskFinished(Task* subTask); const QDRunSettings& getSettings() const { return settings; } QDResultLinker* getLinker() const { return linker; } Task::ReportResult report(); private slots: void sl_updateProgress(); private: QDRunSettings settings; QDResultLinker* linker; LoadUnloadedDocumentTask* loadTask; QDCreateAnnotationsTask* createAnnsTask; QDStep* currentStep; int progressDelta; }; }//namespace #endif ugene-1.9.8/src/corelibs/U2Designer/src/QDScheduler.cpp0000644000175000017500000007253711651544332021332 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "QDScheduler.h" #include #include #include #include #include #include #include #include #include #include namespace U2 { //QDScheduler ////////////////////////////////////////////////////////////////////////// static int PROCESSING_PROGRESS_WEIGHT(80); QDScheduler::QDScheduler(const QDRunSettings& _settings) : Task(tr("QDScheduler"), TaskFlags_NR_FOSCOE), settings(_settings) { GCOUNTER( cvar, tvar, "QueryDesignerScheduler" ); loadTask = NULL; createAnnsTask = NULL; linker = new QDResultLinker(this); settings.scheme->adaptActorsOrder(); currentStep = new QDStep(settings.scheme); tpm = Progress_Manual; stateInfo.progress = 0; // if annotation table is not added to project // annotations will be added in subtask thread // => leave some progress bar space for it Document* annObjDoc = settings.annotationsObj == NULL ? NULL : settings.annotationsObj->getDocument(); if (annObjDoc) { progressDelta = 100 / settings.scheme->getActors().size(); } else { progressDelta = PROCESSING_PROGRESS_WEIGHT / settings.scheme->getActors().size(); } if (settings.annotationsObj == NULL) { GObject* ao = GObjectUtils::selectObjectByReference(settings.annotationsObjRef, UOF_LoadedAndUnloaded); if (ao == NULL) { setError(tr("Can't find annotation object: %1 in document: %2").arg(settings.annotationsObjRef.objName).arg(settings.annotationsObjRef.docUrl)); return; } LoadDocumentTaskConfig cfg(false, settings.annotationsObjRef); loadTask = new LoadUnloadedDocumentTask(ao->getDocument(), cfg); addSubTask(loadTask); } QDTask* qdt = new QDTask(currentStep, linker); addSubTask(qdt); } QDScheduler::~QDScheduler() { delete linker; delete currentStep; } QList QDScheduler::onSubTaskFinished(Task* subTask) { QList subs; if (subTask->hasError()) { propagateSubtaskError(); return subs; } if (isCanceled() || linker->isCancelled() || subTask == createAnnsTask) { return subs; } if (subTask == loadTask) { settings.annotationsObj = qobject_cast(loadTask->getDocument()->findGObjectByName(settings.annotationsObjRef.objName)); return subs; } if (settings.annotationsObj == NULL) { setError(tr("Annotation object is not available")); return subs; } if (currentStep->hasNext()) { currentStep->next(); QDTask* t = new QDTask(currentStep, linker); connect(t, SIGNAL(si_progressChanged()), SLOT(sl_updateProgress())); subs.append(t); } else { createAnnsTask = new QDCreateAnnotationsTask(linker); subs.append(createAnnsTask); } return subs; } #define PUSH_WEIGTH ( 1.0f - PROCESSING_PROGRESS_WEIGHT / 100.0f ) void QDScheduler::sl_updateProgress() { Task* sub = qobject_cast(sender()); int numProcessed = currentStep->getLinkedActors().size(); if (numProcessed < settings.scheme->getActors().size()) { stateInfo.progress = progressDelta * ( numProcessed + sub->getProgress()/100.0f ); } else { stateInfo.progress = PROCESSING_PROGRESS_WEIGHT + PUSH_WEIGTH * sub->getProgress(); } } Task::ReportResult QDScheduler::report() { if (stateInfo.isCanceled() || stateInfo.hasError()) { return ReportResult_Finished; } linker->pushToTable(); // last task is finished, add annotation table object to view if needed if (!settings.viewName.isEmpty()) { GObjectViewWindow* viewWindow = GObjectViewUtils::findViewByName(settings.viewName); if (viewWindow != NULL) { viewWindow->getObjectView()->addObject(settings.annotationsObj); } } return ReportResult_Finished; } //QDResultLinker ////////////////////////////////////////////////////////////////////////// QDResultLinker::QDResultLinker(QDScheduler* _sched) : scheme(_sched->getSettings().scheme), sched(_sched), cancelled(false), currentStep(NULL), needInit(true) {} QString QDResultLinker::prepareAnnotationName(const QDResultUnit& res) { QString aname = res->owner->getActor()->annotateAs(); if (aname=="") { foreach(const U2Qualifier& qual, res->quals) { if (qual.name == "id") { return qual.value; } } } return aname; } // for 1..3, 5..7 returns 1..7 U2Region uniteRegions(const QVector& regions) { assert(!regions.isEmpty()); qint64 startPos = regions.first().startPos; qint64 endPos = regions.first().endPos(); for (int i=1, n=regions.size(); i joinRegions(QVector& regions) { QVector result; qSort(regions); for(int i=0, size=regions.size(); i QDResultLinker::findLocation(QDStep* step) { QVector res; if (candidates.isEmpty()) { res << scheme->getDNA()->getSequenceRange(); return res; } QDActor* actor = step->getActor(); const QList& units = actor->getSchemeUnits(); foreach(QDResultGroup* candidate, candidates) { bool complement = candidate->strand == QDStrand_ComplementOnly; QVector actorLocation; foreach(QDSchemeUnit* su, units) { U2Region suRegion = scheme->getDNA()->getSequenceRange(); foreach(const QDResultUnit& ru, candidate->getResultsList()) { foreach(QDConstraint* c, step->getConstraints(su, ru->owner)) { QDDistanceConstraint* dc = static_cast(c); const U2Region& reg = QDConstraintController::matchLocation(dc, ru, complement); suRegion = suRegion.intersect(reg); } } if (suRegion.isEmpty()) { actorLocation.clear(); break; } else { actorLocation.append(suRegion); } } if (!actorLocation.isEmpty()) { const U2Region& region4candidate = uniteRegions(actorLocation); res.append(region4candidate); } } res = joinRegions(res); return res; } void QDResultLinker::updateCandidates(QDStep* step, int& progress) { currentStep = step; QDActor* currentActor = step->getActor(); currentResults = currentActor->popResults(); QString actorGroup = scheme->getActorGroup(currentActor); if (!actorGroup.isEmpty()) { QList grpMembers = scheme->getActors(actorGroup); int unlinkedGroupMembersLeft = grpMembers.size()-1; foreach(QDActor* a, grpMembers) { if (step->getLinkedActors().contains(a)) { unlinkedGroupMembersLeft--; } } assert(unlinkedGroupMembersLeft>=0); currentGroupResults.insertMulti(currentActor, currentResults); if (unlinkedGroupMembersLeft==0) { formGroupResults(); processNewResults(progress); QMapIterator< QDActor*, QList > i(currentGroupResults); while(i.hasNext()) { i.next(); const QList& res = i.value(); qDeleteAll(res); } currentGroupResults.clear(); qDeleteAll(currentResults); currentResults.clear(); } } else { processNewResults(progress); qDeleteAll(currentResults); currentResults.clear(); } } template QList addNextSelection(const QList& prev, const QList& source, QList< QList >& result) { int idx = prev.size()-1; while (idx>=0) { const T& item = prev.at(idx); int itemIdx = source.indexOf(item); if (itemIdx newSelection(prev); for (int i=idx; i(); } template void buildSelections(const QList& source, int len, QList< QList >& result) { QList newSelection; for (int i=0; igetActor(); QString grp = scheme->getActorGroup(currentActor); const QList& grpMembers = scheme->getActors(grp); assert(grpMembers.size()==currentGroupResults.size()); QList< QList > groupSelections; int reqNum = scheme->getRequiredNumber(grp); for (int resNum=reqNum, n=grpMembers.size(); resNum<=n; resNum++) { buildSelections(grpMembers, resNum, groupSelections); } currentResults.clear(); foreach(const QList& selection, groupSelections) { assert(currentGroupResults.keys().contains(selection.first())); QList results = currentGroupResults.value(selection.first()); for(int i=1; i newResults; assert(currentGroupResults.keys().contains(selection.at(i))); QList nextResults = currentGroupResults.value(selection.at(i)); foreach(QDResultGroup* res, results) { foreach(QDResultGroup* nextRes, nextResults) { QDResultGroup* newRes = new QDResultGroup(*res); newRes->add(nextRes->getResultsList()); newResults.append(newRes); } } results = newResults; } currentResults.append(results); } currentGroupResults.clear(); } void QDResultLinker::processNewResults(int& progress) { if(needInit) { initCandidates(progress); needInit = false; } else { perfLog.details(QString("Finding matches %1 candidates x %2 results") .arg(candidates.size()).arg(currentResults.size())); qint64 start, end; start = GTimer::currentTimeMicros(); updateCandidates(progress); end = GTimer::currentTimeMicros(); perfLog.details(QString("Updating groups finished in %1 ms").arg(GTimer::millisBetween(start,end))); } if (candidates.isEmpty()) { cancelled = true; } } //void QDResultLinker::filterActorResults(QList&) { // foreach(QDResultGroup* actorResult, currentResults) { // for(int i=0, n=actorResult.size(); i& sharedConstraints = constraintsMap.value(qMakePair(res1->owner, res2->owner)); // foreach(QDConstraint* c, sharedConstraints) { // if (!QDConstraintController::match(c, res1, res2)) { // currentResults.removeOne(actorResult); // } // } // } // } // } //} void QDResultLinker::initCandidates(int& progress) { int i = 0; foreach(QDResultGroup* actorRes, currentResults) { QDStrandOption candidateStrand = findResultStrand(actorRes); QDResultGroup* newCandidate = new QDResultGroup(candidateStrand); newCandidate->add(actorRes->getResultsList()); candidates.append(newCandidate); progress = 100 * ++i / currentResults.size(); } } QDStrandOption QDResultLinker::findResultStrand(QDResultGroup* actorRes) { QDStrandOption curActorStrand = currentStep->getActor()->getStrand(); QDStrandOption resStrand = QDStrand_Both; if (curActorStrand==QDStrand_DirectOnly) { resStrand = actorRes->strand; } else if (curActorStrand==QDStrand_ComplementOnly) { if (actorRes->strand==QDStrand_DirectOnly) { resStrand = QDStrand_ComplementOnly; } else if (actorRes->strand==QDStrand_ComplementOnly) { resStrand = QDStrand_DirectOnly; } else { resStrand = QDStrand_Both; } } else { resStrand = scheme->getStrand(); } return resStrand; } void QDResultLinker::updateCandidates(int& progress) { QList newCandidates; int i = 0; foreach(QDResultGroup* candidate, candidates) { foreach(QDResultGroup* actorRes, currentResults) { if (sched->isCanceled()) { return; } bool matches = false; //define for what schema strand result is QDStrandOption resStrand = findResultStrand(actorRes); if ( resStrand!=QDStrand_Both && candidate->strand!=QDStrand_Both && resStrand!=candidate->strand ) { continue; } // bool complement; if (scheme->getStrand()==QDStrand_DirectOnly) { matches = canAdd(actorRes, candidate, false); complement = false; } else if (scheme->getStrand()==QDStrand_ComplementOnly) { matches = canAdd(actorRes, candidate, true); complement = true; } else { if (resStrand==QDStrand_DirectOnly) { matches = canAdd(actorRes, candidate, false); complement = false; } else if (resStrand==QDStrand_ComplementOnly) { matches = canAdd(actorRes, candidate, true); complement = true; } else { matches = canAdd(actorRes, candidate, false); if (!matches) { matches = canAdd(actorRes, candidate, true); complement = true; } else { complement = false; } } } if (matches) { QDResultGroup* newCandidate = new QDResultGroup(*candidate); newCandidate->add(actorRes->getResultsList()); #ifdef DEBUG if (newCandidate->strand==QDStrand_DirectOnly) { assert(!complement); } if (newCandidate->strand==QDStrand_ComplementOnly) { assert(complement); } #endif //if strand was not defined if (newCandidate->strand == QDStrand_Both) { newCandidate->strand = complement ? QDStrand_ComplementOnly : QDStrand_DirectOnly; } newCandidates.append(newCandidate); } } delete candidate; progress = 100 * ++i / candidates.size(); } candidates = newCandidates; } bool QDResultLinker::canAdd(QDResultGroup* actorResult, QDResultGroup* candidate, bool complement) const { QList actorResults; QList candidateResults; if (complement) { actorResults = prepareComplResults(actorResult); candidateResults = prepareComplResults(candidate); } else { actorResults = actorResult->getResultsList(); candidateResults = candidate->getResultsList(); } foreach(const QDResultUnit& actorResUnit, actorResults) { foreach(const QDResultUnit& candidateResUnit, candidateResults) { const QList& cl = currentStep->getConstraints(actorResUnit->owner, candidateResUnit->owner); foreach(QDConstraint* c, cl) { if(!QDConstraintController::match(c, actorResUnit, candidateResUnit, complement)) { return false; } } } } return true; } QList QDResultLinker::prepareComplResults( QDResultGroup* src ) const { QList res = src->getResultsList(); QList simActors; foreach (QDResultUnit ru, res) { QDActor* a = ru->owner->getActor(); if (a->isSimmetric() && !simActors.contains(a)) { simActors.append(a); QList units = a->getSchemeUnits(); for (int i=0, n=units.size()/2; i it(res); while(it.hasNext()) { QDResultUnit& resUn = it.next(); if (resUn->owner==begin) { resUn->owner = end; } else if (resUn->owner==end) { resUn->owner = begin; } } } } } return res; } #define RESULT_PREFIX "Result" void QDResultLinker::prepareAnnotations() { qint64 start(0), end(0); perfLog.details(QString("%1 groups").arg(candidates.size())); start = GTimer::currentTimeMicros(); if (sched->getSettings().outputType == QDRunSettings::Single ) { createMergedAnnotations(RESULT_PREFIX); } else { createAnnotations(RESULT_PREFIX); } end = GTimer::currentTimeMicros(); perfLog.details(QString("push to table in %1 ms").arg(GTimer::millisBetween(start, end))); } void QDResultLinker::createAnnotations(const QString& groupPrefix) { int counter = 0; foreach(QDResultGroup* candidate, candidates) { if (sched->isCanceled()) { return; } const QString& grpName = QString("%1 %2") .arg(groupPrefix) .arg(QString::number(++counter)); QList groupAnns; foreach(const QDResultUnit& res, candidate->getResultsList()) { Annotation* a = result2annotation.value(res, NULL); if (a == NULL) { SharedAnnotationData ad(new AnnotationData()); ad->name = prepareAnnotationName(res); ad->setStrand(res->strand); ad->location->regions.append(res->region); ad->qualifiers = res->quals; a = new Annotation(ad); result2annotation[res] = a; } groupAnns.append(a); } annotations[grpName] = groupAnns; delete candidate; } candidates.clear(); } void QDResultLinker::createMergedAnnotations(const QString& groupPrefix) { const QDRunSettings& settings = sched->getSettings(); int offset = settings.offset; const U2Region& seqRange = scheme->getDNA()->getSequenceRange(); QList anns; foreach(QDResultGroup* candidate, candidates) { if (sched->isCanceled()) { return; } qint64 startPos = candidate->getResultsList().first()->region.startPos; qint64 endPos = candidate->getResultsList().first()->region.endPos(); foreach(QDResultUnit ru, candidate->getResultsList()) { startPos = qMin(startPos, ru->region.startPos); endPos = qMax(endPos, ru->region.endPos()); } startPos = qMax(seqRange.startPos, startPos - offset); endPos = qMin(seqRange.endPos(), endPos + offset); U2Region r(startPos, endPos-startPos); SharedAnnotationData ad(new AnnotationData()); ad->name = groupPrefix; ad->location->regions.append(r); anns.append(new Annotation(ad)); delete candidate; } candidates.clear(); annotations[""] = anns; } void QDResultLinker::pushToTable() { const QDRunSettings& settings = sched->getSettings(); AnnotationTableObject* ao = settings.annotationsObj; assert(ao != NULL); AnnotationGroup* root = ao->getRootGroup(); if (!settings.groupName.isEmpty()) { root = root->getSubgroup(settings.groupName, true); } QMapIterator< QString, QList > iter(annotations); while (iter.hasNext()) { iter.next(); AnnotationGroup* ag = NULL; if (iter.key().isEmpty()) { ag = root; } else { ag = root->getSubgroup(iter.key(), true); } foreach(Annotation* a, iter.value()) { ag->addAnnotation(a); } } } //QDStep ////////////////////////////////////////////////////////////////////////// QDStep::QDStep(QDScheme* _scheme) : scheme(_scheme) { assert(!scheme->getActors().isEmpty()); actor = scheme->getActors().first(); initTotalMap(); } void QDStep::initTotalMap() { QList units; foreach(QDActor const* a, scheme->getActors()) { units << a->getSchemeUnits(); } for(int srcIdx=0; srcIdx sharedConstraints = scheme->getConstraints(srcSu, dstSu); //build rough constraint if there is no direct constraints if (sharedConstraints.isEmpty()) { const QList& paths = scheme->findPaths(srcSu, dstSu); //use only paths containing no linked units except source(destination) /*QList allowedPaths = paths; foreach(QDPath* path, paths) { const QList& pathUnits = path->getSchemeUnits(); bool containsLinked = false; foreach(QDSchemeUnit* su, linkedUnits) { if (pathUnits.contains(su)) { if (containsLinked) { allowedPaths.removeOne(path); break; } else { containsLinked = true; } } } }*/ QList allowedPaths = paths;// //remove paths containing optional items QMutableListIterator i(allowedPaths); while(i.hasNext()) { QDPath* p = i.next(); foreach(QDSchemeUnit* su, p->getSchemeUnits()) { if (su!=srcSu && su!=dstSu) { QDActor* a = su->getActor(); QString group = scheme->getActorGroup(a); if (!group.isEmpty()) { i.remove(); } } } } //create overall constraint from list of paths between srcSu and dstSu if (!allowedPaths.isEmpty()) { QDDistanceConstraint* overallConstraint = allowedPaths.first()->toConstraint(); int min = overallConstraint->getMin(); int max = overallConstraint->getMax(); for (int i=1, n=allowedPaths.size(); itoConstraint(); //assert(curDc->distanceType()==overallConstraint->distanceType()); if (curDc->getSource()!=overallConstraint->getSource()) { curDc->invert(); } assert(curDc->getSource()==overallConstraint->getSource()); assert(curDc->getDestination()==overallConstraint->getDestination()); min = qMax(min, curDc->getMin()); max = qMin(max, curDc->getMax()); } overallConstraint->setMin(min); overallConstraint->setMax(max); sharedConstraints.append(overallConstraint); } } constraintsMap.insertMulti(qMakePair(srcSu, dstSu), sharedConstraints); constraintsMap.insertMulti(qMakePair(dstSu, srcSu), sharedConstraints); } } } QList QDStep::getConstraints(QDSchemeUnit* subj, QDSchemeUnit* linked) const { const QPair& pair = qMakePair(subj, linked); assert(constraintsMap.contains(pair)); //assert(actor->getSchemeUnits().contains(subj)); return constraintsMap.value(pair); } void QDStep::next() { linkedActors.append(actor); const QList& actors = scheme->getActors(); int idx = actors.indexOf(actor)+1; assert(idx>=0 && idx& actors = scheme->getActors(); int idx = actors.indexOf(actor); if (++idx>=actors.size()) { return false; } return true; } bool QDStep::hasPrev() const { const QList& actors = scheme->getActors(); int idx = actors.indexOf(actor); if (idx>0) { return true; } return false; } //QDTask ////////////////////////////////////////////////////////////////////////// QDTask::QDTask(QDStep* _step, QDResultLinker* _linker) : Task(tr("Query task: %1").arg(_step->getActor()->getParameters()->getLabel()), TaskFlag_NoRun), step(_step), linker(_linker), runTask(NULL) { tpm = Progress_Manual; stateInfo.progress = 0; findLocationTask = new QDFindLocationTask(step, linker); addSubTask(findLocationTask); } QList QDTask::onSubTaskFinished(Task* subTask) { QList subs; if (subTask->hasError()) { propagateSubtaskError(); return subs; } if (isCanceled()) { return subs; } if (subTask==findLocationTask) { stateInfo.progress = 10; const QVector& searchLocation = findLocationTask->getSearchLocation(); curActorLocation = findLocationTask->getResultLocation(); if (searchLocation.isEmpty()) { return subs; } runTask = step->getActor()->getAlgorithmTask(searchLocation); assert(runTask); connect(runTask, SIGNAL(si_progressChanged()), SLOT(sl_updateProgress())); subs.append(runTask); } if (subTask==runTask) { stateInfo.progress = 50; assert(!curActorLocation.isEmpty()); step->getActor()->filterResults(curActorLocation); QDLinkResultsTask* linkTask = new QDLinkResultsTask(step, linker); connect(linkTask, SIGNAL(si_progressChanged()), SLOT(sl_updateProgress())); subs.append(linkTask); } return subs; } static const float FIND_LOC_PROGRESS_WEIGHT = 0.05f; static const float RUN_TASK_PROGRESS_WEIGHT = 0.45f; static const float LINK_TASK_PROGRESS_WEIGHT = 0.5f; static const int RUN_START = FIND_LOC_PROGRESS_WEIGHT*100; static const int LINK_START = (FIND_LOC_PROGRESS_WEIGHT + RUN_TASK_PROGRESS_WEIGHT) * 100; void QDTask::sl_updateProgress() { Task* sub = qobject_cast(sender()); if (sub==findLocationTask) { } else if (sub==runTask) { stateInfo.progress = RUN_START + sub->getProgress() * RUN_TASK_PROGRESS_WEIGHT; } else { //linkTask stateInfo.progress = LINK_START + sub->getProgress() * LINK_TASK_PROGRESS_WEIGHT; } } //QDFindLocationtask ////////////////////////////////////////////////////////////////////////// const int QDFindLocationTask::REGION_DELTA(10); void QDFindLocationTask::run() { const U2Region& seqReg = linker->getScheduler()->getSettings().region; if (step->hasPrev()) { resultLocation = linker->findLocation(step); foreach(const U2Region& r, resultLocation) { int startPos = qMax(seqReg.startPos, r.startPos-REGION_DELTA); int endPos = qMin(seqReg.endPos(), r.endPos()+REGION_DELTA); U2Region extended(startPos, endPos - startPos); searchLocation.append(extended); } searchLocation = joinRegions(searchLocation); } else { resultLocation << seqReg; searchLocation = resultLocation; } } }//namespace ugene-1.9.8/src/corelibs/U2Designer/src/WorkflowGUIUtils.cpp0000644000175000017500000001173211651544332022355 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "WorkflowGUIUtils.h" #include #include #include #include #include #include namespace U2 { void DesignerGUIUtils::paintSamplesArrow(QPainter* painter) { QPen pen(Qt::darkGray); pen.setWidthF(2); painter->setPen(pen); painter->setRenderHint(QPainter::SmoothPixmapTransform); QFont f = painter->font(); painter->resetTransform(); f.setFamily("Times New Roman"); f.setPointSizeF(20); f.setItalic(true); painter->setFont(f); QRectF approx(50,50, 400, 400); QString txt = QObject::tr("Select a sample to start"); QRectF res = painter->boundingRect(approx, Qt::AlignLeft | Qt::AlignTop, txt); res.adjust(-5,-3,15,3); QPainterPath p(QPointF(5, res.center().y())); p.lineTo(res.topLeft()); p.lineTo(res.topRight()); p.lineTo(res.bottomRight()); p.lineTo(res.bottomLeft()); p.closeSubpath(); QColor yc = QColor(255,255,160);//QColor(Qt::yellow).lighter();yc.setAlpha(127); painter->fillPath(p, QBrush(yc)); painter->drawPath(p); painter->setPen(Qt::black); painter->drawText(approx, Qt::AlignLeft | Qt::AlignTop, txt); } void DesignerGUIUtils::paintSamplesDocument(QPainter* painter, QTextDocument* doc, int w, int h, const QPalette& pal) { int pageWidth = qMax(w - 100, 100); int pageHeight = qMax(h - 100, 100); if (pageWidth != doc->pageSize().width()) { doc->setPageSize(QSize(pageWidth, pageHeight)); } QSize ts = doc->size().toSize(); QRect textRect(w / 2 - pageWidth / 2, h / 2 - pageHeight / 2, pageWidth, pageHeight); textRect.setSize(ts); int pad = 10; QRect clearRect = textRect.adjusted(-pad, -pad, pad, pad); painter->setPen(Qt::NoPen); painter->setBrush(QColor(0, 0, 0, 63)); int shade = 10; painter->drawRect(clearRect.x() + clearRect.width() + 1, clearRect.y() + shade, shade, clearRect.height() + 1); painter->drawRect(clearRect.x() + shade, clearRect.y() + clearRect.height() + 1, clearRect.width() - shade + 1, shade); painter->setRenderHint(QPainter::Antialiasing, false); painter->setBrush(QColor(255, 255, 255/*, 220*/)); painter->setPen(Qt::black); painter->drawRect(clearRect); painter->setClipRegion(textRect, Qt::IntersectClip); painter->translate(textRect.topLeft()); QAbstractTextDocumentLayout::PaintContext ctx; QLinearGradient g(0, 0, 0, textRect.height()); g.setColorAt(0, Qt::black); g.setColorAt(0.9, Qt::black); g.setColorAt(1, Qt::transparent); //pal.setBrush(QPalette::Text, g); ctx.palette = pal; ctx.clip = QRect(0, 0, textRect.width(), textRect.height()); doc->documentLayout()->draw(painter, ctx); } void DesignerGUIUtils::setupSamplesDocument(const Descriptor& d, const QIcon& ico, QTextDocument* doc) { QString text = "" "" "" "" "" "" "

    %1


    %3
    %4
    %5
    " ""; QString img("img://img"); doc->addResource(QTextDocument::ImageResource, QUrl(img), ico.pixmap(200)); QString body = Qt::escape(d.getDocumentation()).replace("\n", "
    "); int brk = body.indexOf("

    "); int shift = 8; if (brk <= 0) { brk = body.indexOf("
    "); shift = 4; } QString body2; if (brk > 0) { body2 = body.mid(brk + shift); body = body.left(brk); } text = text.arg(d.getDisplayName()).arg(img).arg(body).arg(body2) .arg(QObject::tr("Double click to load the sample")); doc->setHtml(text); QFont f; //f.setFamily("Times New Roman"); f.setPointSizeF(12); doc->setDefaultFont(f); } }//namespace ugene-1.9.8/src/corelibs/U2Designer/src/WorkflowGUIUtils.h0000644000175000017500000000260111651544332022015 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_WORKFLOW_GUI_UTILS_H_ #define _U2_WORKFLOW_GUI_UTILS_H_ #include class QPainter; class QTextDocument; class QPalette; class QIcon; namespace U2 { class Descriptor; class U2DESIGNER_EXPORT DesignerGUIUtils { public: static void paintSamplesArrow(QPainter* painter); static void paintSamplesDocument(QPainter* painter, QTextDocument* doc, int pageWidth, int pageHeight, const QPalette& pal); static void setupSamplesDocument(const Descriptor& d, const QIcon& ico, QTextDocument* res); }; }//namespace #endif ugene-1.9.8/src/corelibs/U2Designer/src/DesignerUtils.cpp0000644000175000017500000000243111651544332021732 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "DesignerUtils.h" #include #include //TODO FIX translator namespace U2 { QString DesignerUtils::getSchemaFileFilter(bool any, bool addOldExt) { QStringList exts(WorkflowUtils::WD_FILE_EXTENSIONS); if(addOldExt) { exts << WorkflowUtils::WD_XML_FORMAT_EXTENSION; } return DialogUtils::prepareFileFilter(WorkflowUtils::tr("UGENE workflow schemes"), exts, any); } } //nsugene-1.9.8/src/corelibs/U2Designer/src/DelegateEditors.h0000644000175000017500000002512711651544332021671 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_WORKFLOW_URL_H_ #define _U2_WORKFLOW_URL_H_ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include namespace U2 { /** * simple realization of configuration editor */ class U2DESIGNER_EXPORT DelegateEditor : public ConfigurationEditor { public: DelegateEditor(const QMap& map) : delegates(map) {} DelegateEditor(const QString& s, PropertyDelegate* d) {delegates.insert(s,d);} virtual ~DelegateEditor() {qDeleteAll(delegates.values());} virtual PropertyDelegate* getDelegate(const QString& name) {return delegates.value(name);} virtual PropertyDelegate* removeDelegate( const QString & name ) {return delegates.take( name );} virtual void addDelegate( PropertyDelegate * del, const QString & name ) { delegates.insert( name, del ); } virtual void commit() {} protected: QMap delegates; }; // DelegateEditor class U2DESIGNER_EXPORT URLLineEdit : public QLineEdit { Q_OBJECT public: URLLineEdit(const QString& filter, const QString& type, bool multi, bool isPath, bool saveFile, QWidget *parent, const QString &format = "") : QLineEdit(parent), FileFilter(filter), type(type), multi(multi), isPath(isPath), saveFile(saveFile), fileFormat(format) {} protected: void focusOutEvent ( QFocusEvent * event ); private slots: void sl_onBrowse(); signals: void si_finished(); private: QString FileFilter; QString type; bool multi; bool isPath; bool saveFile; QString fileFormat; }; class U2DESIGNER_EXPORT URLDelegate : public PropertyDelegate { Q_OBJECT public: URLDelegate(const QString& filter, const QString& type, bool multi = false, bool isPath = false, bool saveFile = true, QObject *parent = 0, const QString &format = "") : PropertyDelegate(parent), FileFilter(filter), type(type), multi(multi), isPath(isPath), showButton( true ), saveFile(saveFile), currentEditor(NULL), fileFormat(format) { } virtual ~URLDelegate() {} virtual QWidget *createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const; virtual void setEditorData(QWidget *editor, const QModelIndex &index) const; virtual void setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const; public slots: void sl_showEditorButton( bool show ); void sl_commit(); void sl_formatChanged(const QString &newFormat); protected: QString FileFilter; QString type; bool multi; bool isPath; bool showButton; bool saveFile; // sets when you need only 1 file for reading (is set with multi=false) mutable QWidget* currentEditor; QString text; QString fileFormat; }; class U2DESIGNER_EXPORT SpinBoxDelegate : public PropertyDelegate { Q_OBJECT public: SpinBoxDelegate(const QVariantMap& props = QVariantMap(), QObject *parent = 0) : PropertyDelegate(parent), spinProperties(props), currentEditor(NULL) {} virtual ~SpinBoxDelegate() {} QWidget *createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const; void setEditorData(QWidget *editor, const QModelIndex &index) const; void setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const; QVariant getDisplayValue(const QVariant&) const; void setEditorProperty(const char* name, const QVariant& val); signals: void si_valueChanged(int); private: QVariantMap spinProperties; mutable QPointer currentEditor; }; class U2DESIGNER_EXPORT DoubleSpinBoxDelegate : public PropertyDelegate { public: DoubleSpinBoxDelegate(const QVariantMap& props = QVariantMap(), QObject *parent = 0) : PropertyDelegate(parent), spinProperties(props) {} virtual ~DoubleSpinBoxDelegate() {} QWidget *createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const; void setEditorData(QWidget *editor, const QModelIndex &index) const; void setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const; QVariant getDisplayValue(const QVariant&) const; private: QVariantMap spinProperties; }; class U2DESIGNER_EXPORT ComboBoxDelegate : public PropertyDelegate { Q_OBJECT public: ComboBoxDelegate(const QVariantMap& items, QObject *parent = 0) : PropertyDelegate(parent), items(items) {} virtual ~ComboBoxDelegate() {} QWidget *createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const; void setEditorData(QWidget *editor, const QModelIndex &index) const; void setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const; QVariant getDisplayValue(const QVariant&) const; signals: void si_valueChanged( const QString & newVal ) const; protected: QVariantMap items; }; class U2DESIGNER_EXPORT FileModeDelegate : public ComboBoxDelegate { public: FileModeDelegate(bool appendSupported, QObject *parent = 0); virtual ~FileModeDelegate() {} }; class U2DESIGNER_EXPORT SchemaRunModeDelegate : public ComboBoxDelegate { Q_OBJECT public: static const QString THIS_COMPUTER_STR; static const QString REMOTE_COMPUTER_STR; public: SchemaRunModeDelegate(QObject * parent = 0); virtual ~SchemaRunModeDelegate() {} public slots: void sl_valueChanged( const QString & val ); signals: void si_showOpenFileButton( bool show ); }; // SchemaRunModeDelegate class U2DESIGNER_EXPORT AttributeScriptDelegate : public PropertyDelegate { Q_OBJECT public: AttributeScriptDelegate(QObject *parent = 0); virtual ~AttributeScriptDelegate(); QWidget *createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const; void setEditorData(QWidget *editor, const QModelIndex &index) const; void setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const; QVariant getDisplayValue(const QVariant&) const; static QString createScriptHeader(const AttributeScript & attrScript); private slots: void sl_comboActivated(int); }; // AttributeScriptDelegate //class U2DESIGNER_EXPORT InputPortDataDelegate : public ComboBoxDelegate { // Q_OBJECT //public: // InputPortDataDelegate(const QVariantMap& items, QObject *parent = NULL ); // virtual ~InputPortDataDelegate(); // // QWidget *createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const; // void setEditorData(QWidget *editor, const QModelIndex &index) const; // void setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const; // QVariant getDisplayValue(const QVariant&) const; // //}; // InputPortDataDelegatedes class U2DESIGNER_EXPORT StingListEdit : public QLineEdit { Q_OBJECT public: StingListEdit(QWidget *parent) : QLineEdit(parent) {} protected: void focusOutEvent(QFocusEvent *event); signals: void si_finished(); private slots: void sl_onExpand(); }; class U2DESIGNER_EXPORT StringListDelegate : public PropertyDelegate { Q_OBJECT public: StringListDelegate(QObject *parent = 0) : PropertyDelegate(parent), showButton(true) {} virtual ~StringListDelegate() {} virtual QWidget *createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const; void setEditorData(QWidget *editor, const QModelIndex &index) const; void setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const; public slots: void sl_showEditorButton(bool show); void sl_commit(); private: static const QString EDITOR; bool showButton; mutable QWidget *currentEditor; }; class SelectorDialogHandler { public: virtual QDialog *createSelectorDialog(const QString& init) = 0; virtual QString getSelectedString(QDialog *dlg) = 0; }; class U2DESIGNER_EXPORT StringSelectorDelegate: public PropertyDelegate { Q_OBJECT public: StringSelectorDelegate(const QString& _initValue, SelectorDialogHandler *_f, QObject *o = NULL): PropertyDelegate(o), initValue(_initValue), f(_f) {} virtual ~StringSelectorDelegate() {} virtual QWidget *createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const; void setEditorData(QWidget *editor, const QModelIndex &index) const; void setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const ; private slots: void sl_onClick(); void sl_commit(); private: mutable QLineEdit *valueEdit; mutable QWidget *currentEditor; QString initValue; bool multipleSelection; SelectorDialogHandler *f; }; class U2DESIGNER_EXPORT CharacterDelegate : public PropertyDelegate { Q_OBJECT public: CharacterDelegate(QObject *parent = 0) : PropertyDelegate(parent) {} virtual ~CharacterDelegate() {} virtual QWidget *createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const; virtual void setEditorData(QWidget *editor, const QModelIndex &index) const; virtual void setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const; }; // CharacterDelegate }//namespace U2 #endif ugene-1.9.8/src/corelibs/U2Designer/src/DelegateEditors.cpp0000644000175000017500000005570411651544332022230 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include #include #include #include #include #include #include #include "DelegateEditors.h" #include #include namespace U2 { /******************************** * SpinBoxDelegate ********************************/ QWidget *SpinBoxDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem &/* option */, const QModelIndex &/* index */) const { currentEditor = new QSpinBox(parent); connect(currentEditor, SIGNAL(valueChanged(int)), SIGNAL(si_valueChanged(int))); WorkflowUtils::setQObjectProperties(*currentEditor, spinProperties); return currentEditor; } void SpinBoxDelegate::setEditorData(QWidget *editor, const QModelIndex &index) const { int value = index.model()->data(index, ConfigurationEditor::ItemValueRole).toInt(); QSpinBox *spinBox = static_cast(editor); spinBox->setValue(value); } void SpinBoxDelegate::setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const { QSpinBox *spinBox = static_cast(editor); spinBox->interpretText(); int value = spinBox->value(); model->setData(index, value, ConfigurationEditor::ItemValueRole); } QVariant SpinBoxDelegate::getDisplayValue( const QVariant& v) const { QSpinBox editor; WorkflowUtils::setQObjectProperties(editor, spinProperties); editor.setValue(v.toInt()); return editor.text(); } void SpinBoxDelegate::setEditorProperty(const char* name, const QVariant& val ) { spinProperties[name] = val; if (!currentEditor.isNull()) { currentEditor->setProperty(name, val); } } /******************************** * DoubleSpinBoxDelegate ********************************/ QWidget *DoubleSpinBoxDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem &/* option */, const QModelIndex &/* index */) const { QDoubleSpinBox *editor = new QDoubleSpinBox(parent); WorkflowUtils::setQObjectProperties(*editor, spinProperties); return editor; } void DoubleSpinBoxDelegate::setEditorData(QWidget *editor, const QModelIndex &index) const { double value = index.model()->data(index, ConfigurationEditor::ItemValueRole).toDouble(); QDoubleSpinBox *spinBox = static_cast(editor); spinBox->setValue(value); } void DoubleSpinBoxDelegate::setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const { QDoubleSpinBox *spinBox = static_cast(editor); spinBox->interpretText(); double value = spinBox->value(); model->setData(index, value, ConfigurationEditor::ItemValueRole); } QVariant DoubleSpinBoxDelegate::getDisplayValue( const QVariant& v) const { QDoubleSpinBox editor; WorkflowUtils::setQObjectProperties(editor, spinProperties); editor.setValue(v.toDouble()); return editor.text(); } /******************************** * ComboBoxDelegate ********************************/ QWidget *ComboBoxDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem &/* option */, const QModelIndex &/* index */) const { QComboBox *editor = new QComboBox(parent); //editor->setFrame(false); //editor->setSizePolicy(QSizePolicy(QSizePolicy::Preferred,QSizePolicy::Preferred)); QMapIterator it(items); while (it.hasNext()) { it.next(); editor->addItem(it.key(), it.value()); } connect( editor, SIGNAL( activated( const QString & ) ), this, SIGNAL( si_valueChanged( const QString & ) ) ); return editor; } void ComboBoxDelegate::setEditorData(QWidget *editor, const QModelIndex &index) const { QVariant val = index.model()->data(index, ConfigurationEditor::ItemValueRole); QComboBox *box = static_cast(editor); int idx = box->findData(val); box->setCurrentIndex(idx); } void ComboBoxDelegate::setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const { QComboBox *box = static_cast(editor); QVariant val = box->itemData(box->currentIndex()); model->setData(index, val, ConfigurationEditor::ItemValueRole); } QVariant ComboBoxDelegate::getDisplayValue(const QVariant& val) const { QString display = items.key(val); emit si_valueChanged( display ); return QVariant( display ); } /******************************** * URLLineEdit ********************************/ void URLLineEdit::sl_onBrowse() { LastOpenDirHelper lod(type); QString lastDir = lod.dir; if(!text().isEmpty()) { QString curPath(text()); int slashPos = curPath.lastIndexOf("/"); slashPos = qMax(slashPos, curPath.lastIndexOf("\\")); if (slashPos >= 0) { QDir dir(curPath.left(slashPos + 1)); if (dir.exists()) { lastDir = dir.absolutePath(); } } } QString name; if(isPath){ lod.url = name = QFileDialog::getExistingDirectory(NULL, tr("Select a directory"), lastDir); }else if (multi) { QStringList lst = QFileDialog::getOpenFileNames(NULL, tr("Select file(s)"), lastDir, FileFilter); name = lst.join(";"); if (!lst.isEmpty()) { lod.url = lst.first(); } } else { if(saveFile) { lod.url = name = QFileDialog::getSaveFileName(NULL, tr("Select a file"), lastDir, FileFilter, 0, QFileDialog::DontConfirmOverwrite); DocumentFormat *format = AppContext::getDocumentFormatRegistry()->getFormatById(fileFormat); if (NULL != format && !name.isEmpty()) { QString newName(name); GUrl url(newName); QString lastSuffix = url.lastFileSuffix(); if ("gz" == lastSuffix) { int dotPos = newName.length() - lastSuffix.length() - 1; if ((dotPos >= 0) && (QChar('.') == newName[dotPos])) { newName = url.getURLString().left(dotPos); GUrl tmp(newName); lastSuffix = tmp.lastFileSuffix(); } } bool foundExt = false; foreach (QString supExt, format->getSupportedDocumentFileExtensions()) { if (lastSuffix == supExt) { foundExt = true; break; } } if (!foundExt) { name = name + "." + format->getSupportedDocumentFileExtensions().first(); } else { int dotPos = newName.length() - lastSuffix.length() - 1; if ((dotPos < 0) || (QChar('.') != newName[dotPos])) { name = name + "." + format->getSupportedDocumentFileExtensions().first(); } } } } else { lod.url = name = QFileDialog::getOpenFileName(NULL, tr("Select a file"), lastDir, FileFilter ); } } if (!name.isEmpty()) { setText(name); QKeyEvent accept(QEvent::KeyPress, Qt::Key_Enter, Qt::NoModifier); } setFocus(); } void URLLineEdit::focusOutEvent ( QFocusEvent * ) { emit si_finished(); } /******************************** * URLDelegate ********************************/ QWidget *URLDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem &/* option */, const QModelIndex &/* index */) const { QWidget * widget = new QWidget(parent); URLLineEdit* documentURLEdit = new URLLineEdit(FileFilter, type, multi, isPath, saveFile, widget, fileFormat); documentURLEdit->setObjectName("URLLineEdit"); documentURLEdit->setFrame(false); documentURLEdit->setSizePolicy(QSizePolicy(QSizePolicy::Preferred,QSizePolicy::Preferred)); widget->setFocusProxy(documentURLEdit); QToolButton * toolButton = new QToolButton(widget); toolButton->setVisible( showButton ); toolButton->setText("..."); toolButton->setSizePolicy(QSizePolicy(QSizePolicy::Fixed,QSizePolicy::Preferred)); connect(toolButton, SIGNAL(clicked()), documentURLEdit, SLOT(sl_onBrowse())); QHBoxLayout* layout = new QHBoxLayout(widget); layout->setSpacing(0); layout->setMargin(0); layout->addWidget(documentURLEdit); layout->addWidget(toolButton); currentEditor = widget; connect(documentURLEdit, SIGNAL(si_finished()), SLOT(sl_commit())); return widget; } void URLDelegate::sl_commit() { URLLineEdit *edit = static_cast(sender()); //sender()->disconnect(this); if(edit->text() != text) { text = edit->text(); if (currentEditor) { emit commitData(currentEditor); } //currentEditor->setFocusPolicy(Qt::NoFocus); } //connect(sender(), SIGNAL(editingFinished()), SLOT(sl_commit())); } void URLDelegate::setEditorData(QWidget *editor, const QModelIndex &index) const { QString val = index.model()->data(index, ConfigurationEditor::ItemValueRole).toString(); QLineEdit* ed = editor->findChild("URLLineEdit"); assert(ed); ed->setText(val); } void URLDelegate::setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const { QLineEdit* ed = editor->findChild("URLLineEdit"); assert(ed); QString val = ed->text().replace('\\', '/').trimmed(); model->setData(index, val, ConfigurationEditor::ItemValueRole); if (multi) { QVariantList vl; foreach(QString s, val.split(";")) { vl.append(s.trimmed()); } model->setData(index, vl, ConfigurationEditor::ItemListValueRole); } } void URLDelegate::sl_showEditorButton( bool show ) { showButton = show; } void URLDelegate::sl_formatChanged(const QString &newFormat) { if (newFormat.isEmpty()) { return; } DocumentFormat *format = AppContext::getDocumentFormatRegistry()->getFormatById(newFormat); if (NULL != format) { FileFilter = DialogUtils::prepareDocumentsFileFilter(newFormat, true); } else { FileFilter = newFormat + " files (*." + newFormat + ")"; } fileFormat = newFormat; } /******************************** * FileModeDelegate ********************************/ FileModeDelegate::FileModeDelegate(bool appendSupported, QObject *parent) : ComboBoxDelegate(QVariantMap(), parent) { items.insert(U2::WorkflowUtils::tr("Overwrite"), SaveDoc_Overwrite); items.insert(U2::WorkflowUtils::tr("Rename"), SaveDoc_Roll); if (appendSupported) { items.insert(U2::WorkflowUtils::tr("Append"), SaveDoc_Append); } } /******************************** * SchemaRunModeDelegate ********************************/ const QString SchemaRunModeDelegate::THIS_COMPUTER_STR = SchemaRunModeDelegate::tr( "This computer" ); const QString SchemaRunModeDelegate::REMOTE_COMPUTER_STR = SchemaRunModeDelegate::tr( "Remote computer" ); SchemaRunModeDelegate::SchemaRunModeDelegate( QObject * parent ) : ComboBoxDelegate( QVariantMap(), parent ) { items.insert( THIS_COMPUTER_STR, true ); items.insert( REMOTE_COMPUTER_STR, false ); connect( this, SIGNAL( si_valueChanged( const QString & ) ), this, SLOT( sl_valueChanged( const QString & ) ) ); } void SchemaRunModeDelegate::sl_valueChanged( const QString & val ) { emit si_showOpenFileButton( THIS_COMPUTER_STR == val ); } /******************************** * AttributeScriptDelegate ********************************/ QString AttributeScriptDelegate::createScriptHeader(const AttributeScript & attrScript) { QString header; foreach( const Descriptor & desc, attrScript.getScriptVars().keys() ) { header += QString("var %1; // %2\n").arg(desc.getId()).arg(desc.getDisplayName()); } return header; } const int NO_SCRIPT_ITEM_ID = 0; const int USER_SCRIPT_ITEM_ID = 1; const QPair NO_SCRIPT_ITEM_STR("no script", NO_SCRIPT_ITEM_ID); const QPair USER_SCRIPT_ITEM_STR("user script", USER_SCRIPT_ITEM_ID); const QString SCRIPT_PROPERTY = "combo_script_property"; AttributeScriptDelegate::AttributeScriptDelegate(QObject *parent) : PropertyDelegate(parent) { } AttributeScriptDelegate::~AttributeScriptDelegate() { } void AttributeScriptDelegate::sl_comboActivated(int itemId ) { QComboBox * editor = qobject_cast(sender()); assert(editor != NULL); switch(itemId) { case NO_SCRIPT_ITEM_ID: { editor->setItemData( USER_SCRIPT_ITEM_ID, "", ConfigurationEditor::ItemValueRole ); return; } case USER_SCRIPT_ITEM_ID: { QComboBox * combo = qobject_cast(sender()); assert(combo != NULL); AttributeScript attrScript = combo->property(SCRIPT_PROPERTY.toAscii().constData()).value(); ScriptEditorDialog dlg(editor, createScriptHeader(attrScript)); dlg.setScriptText(attrScript.getScriptText()); int rc = dlg.exec(); if(rc != QDialog::Accepted) { editor->setItemData( USER_SCRIPT_ITEM_ID, qVariantFromValue(attrScript), ConfigurationEditor::ItemValueRole ); return; } attrScript.setScriptText(dlg.getScriptText()); editor->setItemData( USER_SCRIPT_ITEM_ID, qVariantFromValue(attrScript), ConfigurationEditor::ItemValueRole ); return; } default: assert(false); } } QWidget * AttributeScriptDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem &, const QModelIndex &) const { QComboBox *editor = new QComboBox(parent); editor->addItem(NO_SCRIPT_ITEM_STR.first); editor->addItem(USER_SCRIPT_ITEM_STR.first); connect(editor, SIGNAL(activated(int)), SLOT(sl_comboActivated(int))); return editor; } void AttributeScriptDelegate::setEditorData(QWidget *editor, const QModelIndex &index) const { QComboBox * combo = qobject_cast(editor); assert(combo != NULL); AttributeScript attrScript = index.model()->data(index, ConfigurationEditor::ItemValueRole).value(); if( attrScript.isEmpty() ) { combo->setCurrentIndex(NO_SCRIPT_ITEM_STR.second); } else { combo->setCurrentIndex(USER_SCRIPT_ITEM_STR.second); } combo->setProperty(SCRIPT_PROPERTY.toAscii().constData(), qVariantFromValue(attrScript)); } void AttributeScriptDelegate::setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const { QComboBox * combo = qobject_cast(editor); assert(combo != NULL); model->setData(index, combo->itemData(USER_SCRIPT_ITEM_ID, ConfigurationEditor::ItemValueRole), ConfigurationEditor::ItemValueRole); } QVariant AttributeScriptDelegate::getDisplayValue(const QVariant& val) const{ AttributeScript attrScript = val.value(); QString ret = attrScript.isEmpty() ? NO_SCRIPT_ITEM_STR.first : USER_SCRIPT_ITEM_STR.first; return QVariant(ret); } /******************************** * AttributeScriptDelegate ********************************/ //InputPortDataDelegate::InputPortDataDelegate(const QVariantMap& items, QObject *parent ) : ComboBoxDelegate(items, parent) { //} // //InputPortDataDelegate::~InputPortDataDelegate() { //} /* class WCOREAPI_EXPORT ListLineEdit : public QLineEdit */ void StingListEdit::sl_onExpand() { QDialog editor(0); editor.setWindowTitle(StringListDelegate::tr("Enter items")); QPushButton *accept = new QPushButton(StringListDelegate::tr("Ok"), &editor); connect(accept, SIGNAL(clicked()), &editor, SLOT(accept())); QPushButton *reject = new QPushButton(StringListDelegate::tr("Cancel"), &editor); connect(reject, SIGNAL(clicked()), &editor, SLOT(reject())); QHBoxLayout *buttonsLayout = new QHBoxLayout(0); buttonsLayout->addStretch(); buttonsLayout->addWidget(accept); buttonsLayout->addWidget(reject); QTextEdit *edit = new QTextEdit("", &editor); foreach (const QString &item, text().split(";", QString::SkipEmptyParts)) { edit->append(item.trimmed()); } QVBoxLayout *layout = new QVBoxLayout(&editor); layout->addWidget(edit); layout->addLayout(buttonsLayout); editor.setLayout(layout); editor.exec(); if (editor.result() == QDialog::Accepted) { QString s = edit->toPlainText(); s.replace("\n", "; "); setText(s); emit editingFinished(); } } void StingListEdit::focusOutEvent ( QFocusEvent * ) { emit si_finished(); } /* class ListEditDelegate : public PropertyDelegate */ const QString StringListDelegate::EDITOR("ListLineEdit"); QWidget* StringListDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem &, const QModelIndex &) const { QWidget *widget = new QWidget(parent); StingListEdit *edit = new StingListEdit(widget); edit->setObjectName(EDITOR); edit->setFrame(false); edit->setSizePolicy(QSizePolicy(QSizePolicy::Preferred,QSizePolicy::Preferred)); widget->setFocusProxy(edit); QToolButton *button = new QToolButton(widget); button->setVisible(showButton); button->setText("..."); button->setSizePolicy(QSizePolicy(QSizePolicy::Fixed,QSizePolicy::Preferred)); connect(button, SIGNAL(clicked()), edit, SLOT(sl_onExpand())); QHBoxLayout *layout = new QHBoxLayout(widget); layout->setSpacing(0); layout->setMargin(0); layout->addWidget(edit); layout->addWidget(button); currentEditor = widget; connect(edit, SIGNAL(si_finished()), SLOT(sl_commit())); return widget; } void StringListDelegate::sl_commit() { //sender()->disconnect(this); emit commitData(currentEditor); } void StringListDelegate::setEditorData(QWidget *editor, const QModelIndex &index) const { QString val = index.model()->data(index, ConfigurationEditor::ItemValueRole).toString(); QLineEdit *ed = editor->findChild(EDITOR); assert(ed); ed->setText(val); } void StringListDelegate::setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const { QLineEdit *ed = editor->findChild(EDITOR); assert(ed); QString val = ed->text(); model->setData(index, val, ConfigurationEditor::ItemValueRole); QVariantList vl; foreach(const QString &s, val.split(";", QString::SkipEmptyParts)) { vl.append(s.trimmed()); } model->setData(index, vl, ConfigurationEditor::ItemListValueRole); } void StringListDelegate::sl_showEditorButton(bool show) { showButton = show; } /******************************** * StringSelectorDelegate ********************************/ QWidget *StringSelectorDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem &, const QModelIndex &) const { QWidget * editor = new QWidget(parent); valueEdit = new QLineEdit(editor); valueEdit->setObjectName("valueEdit"); //valueEdit->setReadOnly(true); valueEdit->setFrame(false); valueEdit->setSizePolicy(QSizePolicy(QSizePolicy::Preferred,QSizePolicy::Preferred)); editor->setFocusProxy(valueEdit); QToolButton * toolButton = new QToolButton(editor); toolButton->setVisible( true ); toolButton->setText("..."); toolButton->setSizePolicy(QSizePolicy(QSizePolicy::Fixed,QSizePolicy::Preferred)); connect(toolButton, SIGNAL(clicked()), SLOT(sl_onClick())); QHBoxLayout* layout = new QHBoxLayout(editor); layout->setSpacing(0); layout->setMargin(0); layout->addWidget(valueEdit); layout->addWidget(toolButton); currentEditor = editor; connect(valueEdit, SIGNAL(editingFinished()), SLOT(sl_commit())); return editor; } void StringSelectorDelegate::sl_commit() { //sender()->disconnect(this); emit commitData(currentEditor); } void StringSelectorDelegate::sl_onClick() { QDialog *dlg = f->createSelectorDialog(initValue); if(dlg->exec() == QDialog::Accepted) { valueEdit->setText(f->getSelectedString(dlg)); sl_commit(); } delete dlg; } void StringSelectorDelegate::setEditorData(QWidget *, const QModelIndex &index) const { QString val = index.model()->data(index, ConfigurationEditor::ItemValueRole).toString(); valueEdit->setText(val); } void StringSelectorDelegate::setModelData(QWidget *, QAbstractItemModel *model, const QModelIndex &index) const { QString val = valueEdit->text().trimmed(); model->setData(index, val, ConfigurationEditor::ItemValueRole); if (multipleSelection) { QVariantList vl; foreach(QString s, val.split(",")) { vl.append(s.trimmed()); } model->setData(index, vl, ConfigurationEditor::ItemListValueRole); } } /******************************** * CharacterDelegate ********************************/ QWidget *CharacterDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem &/* option */, const QModelIndex &/* index */) const { QLineEdit * lineEdit = new QLineEdit(parent); lineEdit->setMaxLength(1); return lineEdit; } void CharacterDelegate::setEditorData(QWidget *editor, const QModelIndex &index) const { QString val = index.model()->data(index, ConfigurationEditor::ItemValueRole).toString(); QLineEdit * lineEdit = qobject_cast(editor); assert(lineEdit); lineEdit->setText(val); } void CharacterDelegate::setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const { QLineEdit * lineEdit = qobject_cast(editor); assert(lineEdit); QString val = lineEdit->text(); model->setData(index, val, ConfigurationEditor::ItemValueRole); } }//namespace U2 ugene-1.9.8/src/corelibs/U2Designer/src/DesignerUtils.h0000644000175000017500000000214311651544332021377 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_DESIGNER_UTILS_H_ #define _U2_DESIGNER_UTILS_H_ #include namespace U2 { class U2DESIGNER_EXPORT DesignerUtils { public: static QString getSchemaFileFilter(bool any, bool addOldExt = false); }; // DesignerUtils }//namespace #endif ugene-1.9.8/src/corelibs/U2Designer/U2Designer.pro0000644000175000017500000000057111651544332020352 0ustar ilyailyainclude (U2Designer.pri) # Input HEADERS += src/DelegateEditors.h \ src/DesignerUtils.h \ src/QDScheduler.h \ src/WorkflowGUIUtils.h SOURCES += src/DelegateEditors.cpp \ src/DesignerUtils.cpp \ src/QDScheduler.cpp \ src/WorkflowGUIUtils.cpp TRANSLATIONS += transl/czech.ts transl/english.ts transl/russian.ts ugene-1.9.8/src/corelibs/U2Designer/transl/0000755000175000017500000000000011651544332017161 5ustar ilyailyaugene-1.9.8/src/corelibs/U2Designer/transl/russian.ts0000644000175000017500000001327211651544332021222 0ustar ilyailya QObject Select a sample to start Double click to load the sample U2::QDFindLocationTask Find resultLocation U2::QDImportToTableTask Results to annotation table U2::QDLinkResultsTask Link results U2::QDScheduler QDScheduler Can't find annotation object: %1 in document: %2 Query Designer No matches found. Annotation object is not available U2::QDTask Query task: %1 Empty search location for %1 %1 error. U2::SchemaRunModeDelegate This computer Данный компьютер Remote computer Удаленный компьютер U2::StringListDelegate Enter items Введите элементы Ok OK Cancel Отмена U2::URLLineEdit Select a directory Укажите директорию Select a file Выберите файл Select file(s) Выберите файл(ы) U2::WorkflowUtils Overwrite Переписать Rename Переименовать Append Дописать WorkflowUtils UGENE workflow schemes Вычислительные схемы UGENE ugene-1.9.8/src/corelibs/U2Designer/transl/czech.ts0000644000175000017500000001276111651544332020634 0ustar ilyailya QObject Select a sample to start Double click to load the sample U2::QDFindLocationTask Find resultLocation U2::QDImportToTableTask Results to annotation table U2::QDLinkResultsTask Link results U2::QDScheduler QDScheduler Can't find annotation object: %1 in document: %2 Query Designer No matches found. Annotation object is not available U2::QDTask Query task: %1 Empty search location for %1 %1 error. U2::SchemaRunModeDelegate This computer Tento počítač Remote computer Vzdálený počítač U2::StringListDelegate Enter items Ok Cancel Cancel U2::URLLineEdit Select a directory Select a file Vybrat soubor Select file(s) Vybrat soubor(y) U2::WorkflowUtils Overwrite Rename Append WorkflowUtils UGENE workflow schemes Nákres pracovního postupu UGENE ugene-1.9.8/src/corelibs/U2Designer/transl/english.ts0000644000175000017500000001261011651544332021162 0ustar ilyailya QObject Select a sample to start Double click to load the sample U2::QDFindLocationTask Find resultLocation U2::QDImportToTableTask Results to annotation table U2::QDLinkResultsTask Link results U2::QDScheduler QDScheduler Can't find annotation object: %1 in document: %2 Query Designer No matches found. Annotation object is not available U2::QDTask Query task: %1 Empty search location for %1 %1 error. U2::SchemaRunModeDelegate This computer Remote computer U2::StringListDelegate Enter items Ok Cancel U2::URLLineEdit Select a directory Select file(s) Select a file U2::WorkflowUtils Overwrite Rename Append WorkflowUtils UGENE workflow schemes ugene-1.9.8/src/corelibs/U2Algorithm/0000755000175000017500000000000011651544331016043 5ustar ilyailyaugene-1.9.8/src/corelibs/U2Algorithm/U2Algorithm.pro0000644000175000017500000001733011651544330020725 0ustar ilyailyainclude (U2Algorithm.pri) # Input HEADERS += src/molecular_geometry/GeomUtils.h \ src/molecular_geometry/MolecularSurface.h \ src/molecular_geometry/MolecularSurfaceFactoryRegistry.h \ src/molecular_geometry/VanDerWaalsSurface.h \ src/phyltree/CreatePhyTreeSettings.h \ src/phyltree/PhyTreeGenerator.h \ src/phyltree/PhyTreeGeneratorRegistry.h \ src/phyltree/PhyTreeGeneratorTask.h \ src/registry/CDSearchTaskFactoryRegistry.h \ src/registry/CudaGpuRegistry.h \ src/registry/DnaAssemblyAlgRegistry.h \ src/registry/DnaAssemblyTask.h \ src/registry/MSAAlignAlgRegistry.h \ src/registry/MSAAlignTask.h \ src/registry/OpenCLGpuRegistry.h \ src/registry/RepeatFinderTaskFactoryRegistry.h \ src/registry/SecStructPredictAlgRegistry.h \ src/registry/SecStructPredictTask.h \ src/registry/SubstMatrixRegistry.h \ src/smith_waterman/SmithWatermanReportCallback.h \ src/smith_waterman/SmithWatermanResult.h \ src/smith_waterman/SmithWatermanResultFilters.h \ src/smith_waterman/SmithWatermanSettings.h \ src/smith_waterman/SmithWatermanTaskFactory.h \ src/smith_waterman/SmithWatermanTaskFactoryRegistry.h \ src/smith_waterman/SmithWatermanUtil.h \ src/smith_waterman/SWResultFilterRegistry.h \ src/structural_alignment/StructuralAlignmentAlgorithm.h \ src/structural_alignment/StructuralAlignmentAlgorithmFactory.h \ src/structural_alignment/StructuralAlignmentAlgorithmRegistry.h \ src/util_algorithm/BinaryFindOpenCL.h \ src/util_algorithm/BitsTable.h \ src/util_algorithm/DynTable.h \ src/util_algorithm/EnzymeModel.h \ src/util_algorithm/FindAlgorithm.h \ src/util_algorithm/FindAlgorithmTask.h \ src/util_algorithm/ORFAlgorithmTask.h \ src/util_algorithm/ORFFinder.h \ src/util_algorithm/RollingArray.h \ src/util_algorithm/RollingMatrix.h \ src/util_algorithm/SArrayBasedFindTask.h \ src/util_algorithm/SArrayIndex.h \ src/util_algorithm/SArrayIndexSerializer.h \ src/util_cds/CDSearchTaskFactory.h \ src/util_dna_assembly/DnaAssemblyMultiTask.h \ src/util_msa_consensus/BuiltInConsensusAlgorithms.h \ src/util_msa_consensus/MSAConsensusAlgorithm.h \ src/util_msa_consensus/MSAConsensusAlgorithmClustal.h \ src/util_msa_consensus/MSAConsensusAlgorithmDefault.h \ src/util_msa_consensus/MSAConsensusAlgorithmLevitsky.h \ src/util_msa_consensus/MSAConsensusAlgorithmRegistry.h \ src/util_msa_consensus/MSAConsensusAlgorithmStrict.h \ src/util_msa_consensus/MSAConsensusUtils.h \ src/util_msa_distance/BuiltInDistanceAlgorithms.h \ src/util_msa_distance/MSADistanceAlgorithm.h \ src/util_msa_distance/MSADistanceAlgorithmHamming.h \ src/util_msa_distance/MSADistanceAlgorithmHammingRevCompl.h \ src/util_msa_distance/MSADistanceAlgorithmRegistry.h \ src/util_msaedit/CreateSubalignmentTask.h \ src/util_msaedit/MAlignmentUtilTasks.h \ src/util_repeat_finder/RepeatFinderSettings.h \ src/util_repeat_finder/RepeatFinderTaskFactory.h \ src/util_weight_matrix/BuiltInPWMConversionAlgorithms.h \ src/util_weight_matrix/PWMConversionAlgorithm.h \ src/util_weight_matrix/PWMConversionAlgorithmBVH.h \ src/util_weight_matrix/PWMConversionAlgorithmLOD.h \ src/util_weight_matrix/PWMConversionAlgorithmMCH.h \ src/util_weight_matrix/PWMConversionAlgorithmNLG.h \ src/util_weight_matrix/PWMConversionAlgorithmRegistry.h \ src/util_gpu/opencl/OpenCLHelper.h \ src/util_gpu/opencl/OpenCLUtils.h SOURCES += src/molecular_geometry/GeomUtils.cpp \ src/molecular_geometry/MolecularSurface.cpp \ src/molecular_geometry/MolecularSurfaceFactoryRegistry.cpp \ src/molecular_geometry/VanDerWaalsSurface.cpp \ src/phyltree/CreatePhyTreeSettings.cpp \ src/phyltree/PhyTreeGeneratorRegistry.cpp \ src/phyltree/PhyTreeGeneratorTask.cpp \ src/registry/CudaGpuRegistry.cpp \ src/registry/DnaAssemblyAlgRegistry.cpp \ src/registry/DnaAssemblyTask.cpp \ src/registry/MSAAlignAlgRegistry.cpp \ src/registry/MSAAlignTask.cpp \ src/registry/OpenCLGpuRegistry.cpp \ src/registry/RepeatFinderTaskFactoryRegistry.cpp \ src/registry/SecStructPredictAlgRegistry.cpp \ src/registry/SecStructPredictTask.cpp \ src/registry/SubstMatrixRegistry.cpp \ src/smith_waterman/SmithWatermanReportCallback.cpp \ src/smith_waterman/SmithWatermanResult.cpp \ src/smith_waterman/SmithWatermanResultFilters.cpp \ src/smith_waterman/SmithWatermanTaskFactoryRegistry.cpp \ src/smith_waterman/SmithWatermanUtil.cpp \ src/smith_waterman/SWResultFilterRegistry.cpp \ src/structural_alignment/StructuralAlignmentAlgorithm.cpp \ src/structural_alignment/StructuralAlignmentAlgorithmFactory.cpp \ src/structural_alignment/StructuralAlignmentAlgorithmRegistry.cpp \ src/util_algorithm/BinaryFindOpenCL.cpp \ src/util_algorithm/BitsTable.cpp \ src/util_algorithm/EnzymeModel.cpp \ src/util_algorithm/FindAlgorithm.cpp \ src/util_algorithm/FindAlgorithmTask.cpp \ src/util_algorithm/ORFAlgorithmTask.cpp \ src/util_algorithm/ORFFinder.cpp \ src/util_algorithm/SArrayBasedFindTask.cpp \ src/util_algorithm/SArrayIndex.cpp \ src/util_algorithm/SArrayIndexSerializer.cpp \ src/util_dna_assembly/DnaAssemblyMultiTask.cpp \ src/util_msa_consensus/BuiltInConsensusAlgorithms.cpp \ src/util_msa_consensus/MSAConsensusAlgorithm.cpp \ src/util_msa_consensus/MSAConsensusAlgorithmClustal.cpp \ src/util_msa_consensus/MSAConsensusAlgorithmDefault.cpp \ src/util_msa_consensus/MSAConsensusAlgorithmLevitsky.cpp \ src/util_msa_consensus/MSAConsensusAlgorithmRegistry.cpp \ src/util_msa_consensus/MSAConsensusAlgorithmStrict.cpp \ src/util_msa_consensus/MSAConsensusUtils.cpp \ src/util_msa_distance/BuiltInDistanceAlgorithms.cpp \ src/util_msa_distance/MSADistanceAlgorithm.cpp \ src/util_msa_distance/MSADistanceAlgorithmHamming.cpp \ src/util_msa_distance/MSADistanceAlgorithmHammingRevCompl.cpp \ src/util_msa_distance/MSADistanceAlgorithmRegistry.cpp \ src/util_msaedit/CreateSubalignmentTask.cpp \ src/util_msaedit/MAlignmentUtilTasks.cpp \ src/util_weight_matrix/BuiltInPWMConversionAlgorithms.cpp \ src/util_weight_matrix/PWMConversionAlgorithm.cpp \ src/util_weight_matrix/PWMConversionAlgorithmBVH.cpp \ src/util_weight_matrix/PWMConversionAlgorithmLOD.cpp \ src/util_weight_matrix/PWMConversionAlgorithmMCH.cpp \ src/util_weight_matrix/PWMConversionAlgorithmNLG.cpp \ src/util_weight_matrix/PWMConversionAlgorithmRegistry.cpp \ src/util_gpu/opencl/OpenCLHelper.cpp \ src/util_gpu/opencl/OpenCLUtils.cpp RESOURCES += U2Algorithm.qrc TRANSLATIONS += transl/czech.ts transl/english.ts transl/russian.ts ugene-1.9.8/src/corelibs/U2Algorithm/U2Algorithm.pri0000644000175000017500000000106511651544330020715 0ustar ilyailya# include (U2Algorithm.pri) MODULE_ID=U2Algorithm include( ../../ugene_lib_common.pri ) UGENE_RELATIVE_DESTDIR = '' DEFINES+= QT_FATAL_ASSERT BUILDING_U2ALGORITHM_DLL LIBS += -L../../_release -lU2Core !debug_and_release|build_pass { CONFIG(debug, debug|release) { DESTDIR=../../_debug LIBS -= -L../../_release -lU2Core LIBS += -L../../_debug -lU2Cored } CONFIG(release, debug|release) { DESTDIR=../../_release } } unix { target.path = $$UGENE_INSTALL_DIR/$$UGENE_RELATIVE_DESTDIR INSTALLS += target } ugene-1.9.8/src/corelibs/U2Algorithm/src/0000755000175000017500000000000011651544331016632 5ustar ilyailyaugene-1.9.8/src/corelibs/U2Algorithm/src/util_algorithm/0000755000175000017500000000000011651544331021655 5ustar ilyailyaugene-1.9.8/src/corelibs/U2Algorithm/src/util_algorithm/ORFAlgorithmTask.cpp0000644000175000017500000000410711651544331025503 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "ORFAlgorithmTask.h" #include #include #include namespace U2 { #define MAX_RESULTS 100000 ORFFindTask::ORFFindTask(const ORFAlgorithmSettings& s, const QByteArray& seq) : Task (tr("ORF find"), TaskFlag_None), config(s), sequence(seq) { GCOUNTER( cvar, tvar, "ORFFindTask" ); tpm = Progress_Manual; assert(config.proteinTT && config.proteinTT->isThree2One()); } void ORFFindTask::run() { ORFFindAlgorithm::find(dynamic_cast(this), config, sequence.constData(), sequence.size(), stateInfo.cancelFlag, stateInfo.progress); } void ORFFindTask::onResult(const ORFFindResult& r) { QMutexLocker locker(&lock); if (newResults.size() > MAX_RESULTS) { if (!isCanceled()) { stateInfo.setError( tr("Number of results exceeds %1").arg(MAX_RESULTS) ); cancel(); } return; } assert((r.region.length + r.joinedRegion.length) % 3 == 0); newResults.append(r); } QList ORFFindTask::popResults() { lock.lock(); QList res = newResults; newResults.clear(); lock.unlock(); return res; } } //namespace ugene-1.9.8/src/corelibs/U2Algorithm/src/util_algorithm/SArrayBasedFindTask.h0000644000175000017500000000402611651544331025614 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_SARRAY_BASED_FIND_TASK_H_ #define _U2_SARRAY_BASED_FIND_TASK_H_ #include #include #include #include "BitsTable.h" namespace U2 { class SArrayIndex; #define MAX_PERCENTAGE 100 struct U2ALGORITHM_EXPORT SArrayBasedSearchSettings { SArrayBasedSearchSettings() : query(""), useBitMask(false), unknownChar('\0'), bitMask(NULL), ptMismatches(0), nMismatches(0), absMismatches(true) {} QByteArray query; bool useBitMask; char unknownChar; quint32 bitMaskCharBitsNum; const quint32* bitMask; int ptMismatches; int nMismatches; bool absMismatches; }; class U2ALGORITHM_EXPORT SArrayBasedFindTask : public Task { Q_OBJECT public: SArrayBasedFindTask(SArrayIndex* i, const SArrayBasedSearchSettings& s, bool onlyFirstMatch = false); virtual void run(); virtual void cleanup(); const QList getResults() const { return results; } private: void runSearch(); void runSearchWithMismatches(); SArrayIndex* index; SArrayBasedSearchSettings* config; QList results; QMutex lock; bool onlyFirstMatch; }; } //namespace #endif // _U2_SARRAY_BASED_FIND_TASK_H_ ugene-1.9.8/src/corelibs/U2Algorithm/src/util_algorithm/RollingMatrix.h0000644000175000017500000000442011651544331024621 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_ROLLING_MATRIX_H_ #define _U2_ROLLING_MATRIX_H_ #include namespace U2 { //TODO: rename n,m to rows, columns class U2ALGORITHM_EXPORT RollingMatrix { public: RollingMatrix(int _n, int _m) : n(_n), m(_m), column0(0) { data = new int[n*m]; } virtual ~RollingMatrix() { delete[] data; } virtual int get(int x, int y) const { int transX = transposeX(x); int transY = transposeY(y); int idx = getIdx(transX, transY); return data[idx]; } void set(int x, int y, int v) { int transX = transposeX(x); int transY = transposeY(y); int idx = getIdx(transX, transY); data[idx] = v; } void dump() const { printf("----------------\n"); for (int j=0; j=0 && y>=0 && x= 0 && x < n); return (column0 + x) % n ; } int transposeY(int y) const { assert(y >= 0 && y < m); return y; } protected: int n; int m; int* data; int column0; }; } //namespace #endif ugene-1.9.8/src/corelibs/U2Algorithm/src/util_algorithm/SArrayIndex.h0000644000175000017500000002055311651544331024224 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_SARRAY_INDEX_H_ #define _U2_SARRAY_INDEX_H_ #include #include #include namespace U2 { class SArrayIndex; class DNASequenceObject; class BitsTable; /// A task to create SArrayIndex class U2ALGORITHM_EXPORT CreateSArrayIndexTask : public Task { Q_OBJECT public: CreateSArrayIndexTask(const DNASequenceObject* obj, int windowSize, bool useBitMask = false, bool prebuiltIdx = false, const QString &fileName = "", const QString &refFileName = ""); CreateSArrayIndexTask(const char* seq, quint32 size, quint32 w, char unknownChar=0, const quint32* bitTable = NULL, quint32 bitCharLen = 0, quint32 skipGap = 0, quint32 _gapOffset=0); ~CreateSArrayIndexTask(); void run(); void cleanup(); SArrayIndex* index; inline quint32 getPrefixSize()const{ return w;} char getUnknownChar() const {return unknownChar; } const quint32* getBitTable() const {return bitTable; } private: const char* seq; quint32 size; quint32 w; char unknownChar; const quint32* bitTable; quint32 bitCharLen; quint32 skipGap; quint32 gapOffset; bool prebuiltIdx; QString indexFileName; QString refFileName; BitsTable bt; }; /// Main SArrayIndex structure class U2ALGORITHM_EXPORT SArrayIndex { friend class SArrayIndexSerializer; public: class SAISearchContext { public: SAISearchContext() : currSample(NULL), currPos(-1), bitValue(0xFFFFFFFF) {}; virtual ~SAISearchContext(){} const char* currSample; int currPos; quint32 bitValue; }; //qlt - quick lookup table, size = 0 disable it's usage SArrayIndex(const char *serStart, const quint32* bitTable, int bitCharLen); SArrayIndex(const char* seq, quint32 size, quint32 w, TaskStateInfo& ti, char unknownChar=0, const quint32* bitTable = NULL, int bitCharLen = 0, int skipGap = 0, int gapOffset=0); virtual ~SArrayIndex(); quint32 getBitValue(const char *seq) const; bool find(SAISearchContext* c, const char* seq); bool findBit(SAISearchContext* c, quint32 bitValue, const char* seq); int nextArrSeqPos(SAISearchContext* c); //-1 -> end /** compares subsequence with offsets x1 and x2, returns -1;0;1 */ inline int compare(quint32 x1, quint32 x2) const ; int compare(const char* seq1, const char* seq2) const; /** x1 and x2 is bitMask*/ int compareBit(const quint32* x1, const quint32* x2) const; /** x1 and x2 is sArray*/ int compareBitByPos(const quint32* x1, const quint32* x2) const; /**compares only after bits chars*/ int compareAfterBits(quint32 bitMaskPos, const char* afterBitsSeq) const; inline quint32 seq2val(const char* seq) const; inline const char* val2seq(quint32 offs) const; // value of sarray element -> seq inline const char* sarr2seq(const quint32* sarr) const; // pointer to sarray element -> seq inline const char* idx2seq(quint32 idx) const; // index in sarray element -> seq int getCharsInMask() const {return wCharsInMask;} quint32 getBitFilter() const {return bitFilter;} const quint32* getMaskedSequence() const {return bitMask;} const quint32* getSArray() const {return sArray;} quint32 getSArraySize() const {return arrLen;} int getPrefixSize() const { return w; } int getSequenceLength() const { return seqLen; } const char* getIndexedSequence() const {return seqStart; } private: int w, w4, wRest, skipGap, gapOffset; int arrLen; // size of the array == sequence len with unknown chars removed quint32* sArray; // sorted offsets (or direct addr) to the sequence quint32* bitMask; // for all suffixes in sArray this mask contains bit-masked prefix (32-bit) quint32 bitFilter; int wCharsInMask; int wAfterBits; const quint32 *bitTable; int bitCharLen; const char* seqStart; int seqLen; int l1Step; int L1_SIZE; quint32* l1bitMask; // compressed bitMask. Used to localize range before accessing to the real bitMask void sort(quint32* x, int off, int len); void sortBit(quint32* x, int off, int len); void sortBitClassic(quint32* x, int off, int len); int partition(quint32* x, int p, int r); //swaps bit mask values. Swap corresponding sArray values too inline void swapBit(quint32* x1, quint32* x2) const; /** Swaps x[a .. (a+n-1)] with x[b .. (b+n-1)]. */ inline void vecswap(quint32* x, quint32 a, quint32 b, quint32 n); inline int vecswapBit(quint32* x1, quint32* x2, quint32 n); /** Returns index of the median of the three indexed x[] values.*/ inline quint32 med3(quint32* x, quint32 a, quint32 b, quint32 c); inline quint32 med3Bit(quint32* x, quint32 a, quint32 b, quint32 c); void debugCheck(char c); }; void SArrayIndex::swapBit(quint32* x1, quint32* x2) const { //swaps bit mask values. Swap corresponding sArray values too assert(x1 - bitMask >= 0 && x1 - bitMask < arrLen); assert(x2 - bitMask >= 0 && x2 - bitMask < arrLen); quint32* a1 = sArray+(x1-bitMask); quint32* a2 = sArray+(x2-bitMask); qSwap(*x1, *x2); qSwap(*a1, *a2); } /** Swaps x[a .. (a+n-1)] with x[b .. (b+n-1)]. */ void SArrayIndex::vecswap(quint32* x, quint32 a, quint32 b, quint32 n) { for (quint32 i=0; i 0 ? b : ac > 0 ? c : a); } quint32 SArrayIndex::med3Bit(quint32* x, quint32 a, quint32 b, quint32 c) { int bc = compareBit(x+b, x+c); int ac = compareBit(x+a, x+c); return compareBit(x+a, x+b) < 0 ? (bc < 0 ? b : ac < 0 ? c : a) : (bc > 0 ? b : ac > 0 ? c : a); } quint32 SArrayIndex::seq2val(const char* seq) const { //#ifndef _LP64 //assuming 32bit platform -> address is used as value // //TODO: check if there is any benefit in storing direct addresses // return (quint32)seq; //#else assert(seq >=seqStart && seq<=seqStart+seqLen); return seq - seqStart; // on 64-bit platform index stores sequence offsets //#endif } const char* SArrayIndex::val2seq(quint32 val) const { //#ifndef _LP64 //assuming 32bit platform -> index stores direct addresses // //TODO: check if there is any benefit in storing direct addresses // const char* res = (const char*)val; // assert(res >= seqStart && res < seqStart + seqLen); // return res; //#else assert(val < quint32(seqLen)); // on 64-bit platform index stores sequence offsets return seqStart + val; //#endif } const char* SArrayIndex::sarr2seq(const quint32* sarr) const { assert(sarr >= sArray && sarr < sArray + arrLen); return val2seq(*sarr); } const char* SArrayIndex::idx2seq(quint32 idx) const { return sarr2seq(sArray + idx); } int SArrayIndex::compare(quint32 x1, quint32 x2) const { return compare(val2seq(x1), val2seq(x2)); } } //namespace #endif ugene-1.9.8/src/corelibs/U2Algorithm/src/util_algorithm/FindAlgorithm.cpp0000644000175000017500000005354011651544331025117 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "FindAlgorithm.h" #include #include #include #include #include #include #include namespace U2 { class StrandContext { public: StrandContext(int width, int height, bool insDel, const char* p) : dynTable(width, height, insDel), pattern(p) { } StrandContext( const char * data, int arr_size, const char * p ) //using rolling array only in subst mode : rollArr( data, arr_size ), pattern(p) { } StrandContext() : pattern(NULL) {} DynTable dynTable; RollingArray rollArr; const char* pattern; FindAlgorithmResult res; }; static bool isDirect(FindAlgorithmStrand s) { return s == FindAlgorithmStrand_Both || s == FindAlgorithmStrand_Direct; } static bool isComplement(FindAlgorithmStrand s) { return s == FindAlgorithmStrand_Both || s == FindAlgorithmStrand_Complement; } //TODO: in BothStrands&SingleShot mode it's impossible to find result on complement strand if there also a result on direct strand from the same pos! static void findInAmino( FindAlgorithmResultsListener* rl, DNATranslation* aminoTT, DNATranslation* complTT, FindAlgorithmStrand strand, bool insDel, const char* seq, const U2Region& range, const char* pattern, int patternLen, bool singleShot, int maxErr, int& stopFlag, int& percentsCompleted, int& currentPos) { assert(aminoTT->getSrcAlphabet()->isNucleic() && aminoTT->getDstAlphabet()->isAmino()); int width = patternLen + maxErr; int height = patternLen; QByteArray revPattern(pattern); TextUtils::reverse(revPattern.data(), patternLen); StrandContext context[] = { StrandContext(width, height, insDel, pattern), StrandContext(width, height, insDel, pattern), StrandContext(width, height, insDel, pattern), StrandContext(width, height, insDel, revPattern.data()), StrandContext(width, height, insDel, revPattern.data()), StrandContext(width, height, insDel, revPattern.data()) }; int onePercentLen = range.length / 100; int leftTillPercent = onePercentLen; percentsCompleted = 0; currentPos = 0; int conStart = isDirect(strand)? 0 : 1; int conEnd = isComplement(strand) ? 2 : 1; QByteArray complMap = complTT == NULL ? QByteArray() : complTT->getOne2OneMapper(); int patternLenInNucl = 3 * patternLen; for (int i=range.startPos, end = range.endPos(), translStrand = 0; i specialize loops char amino = ci == 0 ? aminoTT->translate3to1( seq[i], seq[i+1], seq[i+2]) : //direct amino aminoTT->translate3to1(complMap.at( (quint8) seq[i+2]), complMap.at((quint8) seq[i+1]), complMap.at( (quint8)seq[i]) ); //compl amino bool matched = (amino == p[j]); dt.match(j, matched); } int err = dt.getLast(); if (!res.isEmpty() && (err > maxErr || (i-res.region.startPos) >= patternLenInNucl)) { rl->onResult(res); res.clear(); if (singleShot) { if( insDel ) { sShot_retflag = true; } else { return; } } } if (err <= maxErr) { int newLen = dt.getLastLen(); newLen *= 3; if (res.isEmpty() || res.err > err || (res.err == err && newLen < res.region.length)) { assert(newLen + 3 * maxErr >= patternLenInNucl); int newStart = i - newLen + 3; if (insDel || (range.contains(newStart) && range.contains(newStart + newLen - 1))) {//boundary check for mismatch mode assert(insDel || newLen == patternLenInNucl); assert(newStart >= range.startPos); assert(newStart+newLen <= range.endPos()); res.region.startPos = newStart; res.region.length = newLen; res.err = err; res.strand = (ci == 1) ? U2Strand::Complementary : U2Strand::Direct; res.translation = true; if( !insDel && singleShot ) { rl->onResult( res ); res.clear(); sShot_retflag = true; } } } } dt.shiftColumn(); if (leftTillPercent == 0) { percentsCompleted = qMin(percentsCompleted+1,100); leftTillPercent = onePercentLen; } }//ci if( sShot_retflag ) { return; } } for (int i=0; i < 6; i++) { if (!context[i].res.isEmpty()) { //todo: order by startpos? assert(insDel || context[i].res.region.length == patternLenInNucl); rl->onResult(context[i].res); } } } static void findInAmino_subst( FindAlgorithmResultsListener* rl, DNATranslation* aminoTT, DNATranslation* complTT, FindAlgorithmStrand strand, const char* seq, const U2Region& range, const char* pattern, int patternLen, bool singleShot, int maxErr, int& stopFlag, int& percentsCompleted, int& currentPos) { assert(aminoTT->getSrcAlphabet()->isNucleic() && aminoTT->getDstAlphabet()->isAmino()); int patternLenInNucl = 3 * patternLen; if( range.length < patternLenInNucl ) { currentPos = range.endPos(); return; } QByteArray revPattern(pattern); // TextUtils::reverse(revPattern.data(), patternLen); QByteArray translatedPiece1( patternLen, 0 ); QByteArray translatedPiece2( patternLen, 0 ); QByteArray translatedPiece3( patternLen, 0 ); int tail = range.length - patternLenInNucl - 2; tail = tail > 0 ? 0 : tail; aminoTT->translate( seq + range.startPos, patternLenInNucl + tail + 2, translatedPiece1.data(), patternLen ); aminoTT->translate( seq + range.startPos+1, patternLenInNucl + tail + 1, translatedPiece2.data(), patternLen ); aminoTT->translate( seq + range.startPos+2, patternLenInNucl + tail, translatedPiece3.data(), patternLen ); QByteArray translatedPiece1c( patternLen, 0 ); QByteArray translatedPiece2c( patternLen, 0 ); QByteArray translatedPiece3c( patternLen, 0 ); QByteArray compl_seq( patternLenInNucl + tail + 2, 0 ); complTT->translate( seq + range.startPos, patternLenInNucl + tail + 2, compl_seq.data(), patternLenInNucl + tail + 2); TextUtils::reverse( compl_seq.data(), compl_seq.size() ); int compl_tail = qBound( 0, int(range.length - patternLenInNucl), 2); int if0slot = 0 == compl_tail; int if1slot = 1 == compl_tail; int if2slot = 2 == compl_tail; aminoTT->translate( compl_seq.data()+compl_tail, patternLenInNucl, translatedPiece1c.data(), patternLen ); aminoTT->translate( compl_seq.data()+2*if0slot+if2slot, patternLenInNucl-2*if0slot, translatedPiece2c.data(), patternLen ); aminoTT->translate( compl_seq.data()+2*if1slot+if0slot, patternLenInNucl-if0slot-if1slot, translatedPiece3c.data(), patternLen ); StrandContext context[] = { StrandContext(translatedPiece1, patternLen, pattern), StrandContext(translatedPiece2, patternLen, pattern), StrandContext(translatedPiece3, patternLen, pattern), StrandContext(translatedPiece1c, patternLen, revPattern.data()), StrandContext(translatedPiece2c, patternLen, revPattern.data()), StrandContext(translatedPiece3c, patternLen, revPattern.data()), }; int onePercentLen = range.length / 100; int leftTillPercent = onePercentLen; percentsCompleted = 0; currentPos = 0; int conStart = isDirect(strand)? 0 : 1; int conEnd = isComplement(strand) ? 2 : 1; QByteArray complMap = complTT ? complTT->getOne2OneMapper() : QByteArray(); for( int i = range.startPos, end = range.endPos(), translStrand = 0; i < end - patternLenInNucl + 1 && !stopFlag; i++, leftTillPercent--, translStrand = translStrand == 2 ? 0 : translStrand + 1) { currentPos = i; for (int ci = conStart; ci < conEnd; ci++) { StrandContext & ctx = context[ci * 3 + translStrand]; const char * p = ctx.pattern; FindAlgorithmResult & res = ctx.res; bool match = true; int curErr = 0; for ( int j = 0; j < patternLen; j++ ) { char rollchar = ctx.rollArr.get(j); if( rollchar != p[j] && ++curErr > maxErr ) { match = false; break; } } if( i + patternLenInNucl + 2 < end ) { int wheree = i + patternLenInNucl; char c1 = ci ? complMap.at( (quint8)seq[wheree+2] ) : seq[wheree]; char c2 = ci ? complMap.at((quint8)seq[wheree+1] ) : seq[wheree+1]; char c3 = ci ? complMap.at((quint8)seq[wheree] ) : seq[wheree+2]; char newchar = aminoTT->translate3to1( c1, c2, c3 ); ci ? ctx.rollArr.push_front_pop_back( newchar ) : ctx.rollArr.push_back_pop_front( newchar ); } if( match ) { currentPos += 1; res.region.startPos = i; res.region.length = patternLenInNucl; res.err = curErr; res.strand = (ci == 1) ? U2Strand::Complementary : U2Strand::Direct; res.translation = true; rl->onResult(res); } if (leftTillPercent == 0) { percentsCompleted = qMin(percentsCompleted+1,100); leftTillPercent = onePercentLen; } }//strand if( singleShot ) { for( int j = conStart; j < conEnd; ++j ) { int cur_ctx = j * 3 + translStrand; if( !context[cur_ctx].res.isEmpty() ) { context[cur_ctx].res.clear(); return; } } } } //base pos currentPos = range.endPos(); } static char* createAmbiguousBaseMap() { // Source: http://www.ncbi.nlm.nih.gov/blast/fasta.shtml // Unknown symbol is zero: no match const int SIZE = 128; static char map[SIZE]; for (int i = 0; i < SIZE; i++) { map[i] = 0x00; } map['A'] = 0x01; // Bitmask: 00000001 map['C'] = 0x02; // Bitmask: 00000010 map['G'] = 0x04; // Bitmask: 00000100 map['T'] = 0x08; // Bitmask: 00001000 map['U'] = 0x08; // Bitmask: 00001000 map['M'] = 0x03; // Bitmask: 00000011 map['R'] = 0x05; // Bitmask: 00000101 map['W'] = 0x09; // Bitmask: 00001001 map['S'] = 0x06; // Bitmask: 00000110 map['Y'] = 0x0A; // Bitmask: 00001010 map['K'] = 0x0C; // Bitmask: 00001100 map['V'] = 0x07; // Bitmask: 00000111 map['H'] = 0x0B; // Bitmask: 00001011 map['D'] = 0x0D; // Bitmask: 00001101 map['B'] = 0x0E; // Bitmask: 00001110 map['N'] = 0x0F; // Bitmask: 00001111 map['X'] = 0x0F; // Bitmask: 00001111 return &map[0]; } inline bool cmpAmbiguous( char a, char b){ static char* charMap = createAmbiguousBaseMap(); assert( a >= 0 && b >= 0 ); char c1 = charMap[uchar(a)]; char c2 = charMap[uchar(b)]; return c1 & c2; } inline bool match_pattern(const char* seq, const char* p, int start, int patternLen, int maxErr, int& curErr ) { bool match = true; curErr = 0; for ( int j = 0; j < patternLen; j++ ) { if( seq[start+j] != p[j] && ++curErr > maxErr ) { match = false; break; } } return match; } inline bool match_pattern_ambiguous(const char* seq, const char* p, int start, int patternLen, int maxErr, int& curErr ) { bool match = true; curErr = 0; for ( int j = 0; j < patternLen; j++ ) { if( !cmpAmbiguous(seq[start+j],p[j]) && ++curErr > maxErr ) { match = false; break; } } return match; } static void find_subst( FindAlgorithmResultsListener* rl, DNATranslation* aminoTT, DNATranslation* complTT, FindAlgorithmStrand strand, const char* seq, const U2Region& range, const char* pattern, int patternLen, bool singleShot, bool useAmbiguousBases, int maxErr, int& stopFlag, int& percentsCompleted, int& currentPos) { assert(complTT == NULL || complTT->isOne2One()); if (aminoTT != NULL) { findInAmino_subst(rl, aminoTT, complTT, strand, seq, range, pattern, patternLen, singleShot, maxErr, stopFlag, percentsCompleted, currentPos); return; } if( range.length - patternLen < 0 ) { currentPos = range.endPos(); return; } char* complPattern = NULL; QByteArray tmp; if (isComplement(strand)) { assert(complTT!=NULL); tmp.resize(patternLen); complPattern = tmp.data(); TextUtils::translate(complTT->getOne2OneMapper(), pattern, patternLen, complPattern); TextUtils::reverse(complPattern, patternLen); } StrandContext context[] = { StrandContext(0, 0, false, pattern), StrandContext(0, 0, false, complPattern) }; int onePercentLen = range.length/100; int leftTillPercent = onePercentLen; percentsCompleted = 0; currentPos = range.startPos; int conStart = isDirect(strand)? 0 : 1; int conEnd = isComplement(strand) ? 2 : 1; assert(conStart < conEnd); for (int i=range.startPos, end = range.endPos(); i < end - patternLen + 1 && !stopFlag; i++, leftTillPercent--) { currentPos = i; for (int ci = conStart; ci < conEnd; ci++) { StrandContext& ctx = context[ci]; const char* p = ctx.pattern; FindAlgorithmResult& res = ctx.res; bool match = true; int curErr = 0; if (useAmbiguousBases) { match = match_pattern_ambiguous(seq, p, i, patternLen, maxErr, curErr); } else { match = match_pattern(seq, p, i, patternLen, maxErr, curErr); } if( match ) { ++currentPos; res.region.startPos = i; res.region.length = patternLen; res.err = curErr; res.strand = (ci == 1) ? U2Strand::Complementary : U2Strand::Direct; rl->onResult(res); // res.clear(); } if (leftTillPercent == 0) { percentsCompleted = qMin(percentsCompleted+1,100); leftTillPercent = onePercentLen; } }//strand if( singleShot ) { for( int j = conStart; j < conEnd; ++j ) { if( !context[j].res.isEmpty() ) { return; } } } } //base pos currentPos = range.endPos(); } void FindAlgorithm::find( FindAlgorithmResultsListener* rl, DNATranslation* aminoTT, // if aminoTT!=NULL -> pattern must contain amino data and sequence must contain DNA data DNATranslation* complTT, // if complTT!=NULL -> sequence is complemented before comparison with pattern FindAlgorithmStrand strand, // if not direct there complTT must not be NULL bool insDel, bool useAmbiguousBases, const char* seq, int seqLen, const U2Region& range, const char* pattern, int patternLen, bool singleShot, int maxErr, int& stopFlag, int& percentsCompleted, int& currentPos) { Q_UNUSED(seqLen); assert(complTT == NULL || complTT->isOne2One()); assert(patternLen > maxErr); if( !insDel ) { find_subst( rl, aminoTT, complTT, strand, seq, range, pattern, patternLen, singleShot, useAmbiguousBases, maxErr, stopFlag, percentsCompleted, currentPos ); return; } if (aminoTT != NULL) { findInAmino(rl, aminoTT, complTT, strand, insDel, seq, range, pattern, patternLen, singleShot, maxErr, stopFlag, percentsCompleted, currentPos); return; } char* complPattern = NULL; QByteArray tmp; if (isComplement(strand)) { assert(complTT!=NULL); tmp.resize(patternLen); complPattern = tmp.data(); TextUtils::translate(complTT->getOne2OneMapper(), pattern, patternLen, complPattern); TextUtils::reverse(complPattern, patternLen); } int width = patternLen + maxErr; int height = patternLen; StrandContext context[] = { StrandContext(width, height, insDel, pattern), StrandContext(width, height, insDel, complPattern) }; int onePercentLen = range.length/100; int leftTillPercent = onePercentLen; percentsCompleted = 0; currentPos = range.startPos; int conStart = isDirect(strand)? 0 : 1; int conEnd = isComplement(strand) ? 2 : 1; assert(conStart < conEnd); for (int i=range.startPos, end = range.endPos(); i < end && !stopFlag; i++, leftTillPercent--) { currentPos = i; bool sShot_retflag = false; for (int ci = conStart; ci < conEnd; ci++) { StrandContext& ctx = context[ci]; DynTable& dt = ctx.dynTable; const char* p = ctx.pattern; FindAlgorithmResult& res = ctx.res; for (int j=0; j maxErr || (i-res.region.startPos) >= patternLen)) { rl->onResult(res); res.clear(); if (singleShot) { if( insDel ) { sShot_retflag = true; } else { return; } } } if (err <= maxErr) { int newLen = dt.getLastLen(); if (res.isEmpty() || res.err > err || (res.err == err && newLen < res.region.length)) { // assert(newLen + maxErr >= patternLen); int newStart = i-newLen+1; if (insDel || (range.contains(newStart) && range.contains(newStart + newLen - 1))) {//boundary check for mismatch mode assert(insDel || newLen == patternLen); assert(newStart >= range.startPos); assert(newStart+newLen <= range.endPos()); res.region.startPos = newStart; res.region.length = newLen; res.err = err; res.strand = (ci == 1) ? U2Strand::Complementary : U2Strand::Direct; res.translation = (aminoTT != NULL) ? true : false; if( !insDel && singleShot ) { rl->onResult( res ); res.clear(); sShot_retflag = true; } } } } dt.shiftColumn(); if (leftTillPercent == 0) { percentsCompleted = qMin(percentsCompleted+1,100); leftTillPercent = onePercentLen; } }//strand if( sShot_retflag ) { return; } } //base pos for (int i=0; i<2; i++) { if (!context[i].res.isEmpty()) { //todo: order by startpos? assert(insDel || context[i].res.region.length == patternLen); rl->onResult(context[i].res); } } } }//namespace ugene-1.9.8/src/corelibs/U2Algorithm/src/util_algorithm/SArrayIndex.cpp0000644000175000017500000005153411651544331024562 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "SArrayIndex.h" #include "SArrayIndexSerializer.h" #include #include #include #include namespace U2 { CreateSArrayIndexTask::CreateSArrayIndexTask(const char* _seq, quint32 _size, quint32 _w, char _unknownChar, const quint32* _bitTable, quint32 _bitCharLen, quint32 _skipGap, quint32 _gapOffset) :Task("Create SArray index", TaskFlag_None), index(NULL), seq(_seq), size(_size), w(_w), unknownChar(_unknownChar), bitTable(_bitTable), bitCharLen(_bitCharLen), skipGap(_skipGap), gapOffset(_gapOffset), indexFileName(""), refFileName("") { prebuiltIdx = false; } CreateSArrayIndexTask::CreateSArrayIndexTask( const DNASequenceObject* obj, int windowSize, bool useBitMask, bool _prebuiltIdx, const QString &idxFN,const QString &refFN ) :Task("Create SArray index", TaskFlag_None), index(NULL), seq(obj->getDNASequence().constData()), size(obj->getSequenceLen()), w(windowSize), unknownChar('\0'), skipGap(0), gapOffset(0), prebuiltIdx(_prebuiltIdx), indexFileName(idxFN), refFileName(refFN) { DNAAlphabetType seqType = obj->getAlphabet()->getType(); unknownChar = seqType == DNAAlphabet_AMINO ? 'X' : seqType==DNAAlphabet_NUCL ? 'N' : '\0'; if (useBitMask) { bitTable = bt.getBitMaskCharBits(seqType); bitCharLen = bt.getBitMaskCharBitsNum(seqType); } else { bitTable = NULL; bitCharLen = 0; } } CreateSArrayIndexTask::~CreateSArrayIndexTask() { if (index!=NULL){ cleanup(); } } void CreateSArrayIndexTask::run() { if (prebuiltIdx) { index = new SArrayIndex(seq, bitTable, bitCharLen); SArrayIndexSerializer::deserialize(index, indexFileName, stateInfo); } else { index = new SArrayIndex(seq, size, w, stateInfo, unknownChar, bitTable, bitCharLen, skipGap, gapOffset); SArrayIndexSerializer::serialize(index, indexFileName, refFileName); } } void CreateSArrayIndexTask::cleanup() { delete index; index = 0; } ////////////////////////////////////////////////////////////////////////// // index SArrayIndex::SArrayIndex(const char *_seqStart, const quint32* _bitTable, int _bitCharLen) : w(0), w4(0), wRest(0), skipGap(0), gapOffset(0), arrLen(0), sArray(NULL), bitMask(NULL), bitFilter(0), wCharsInMask(0), wAfterBits(0), bitTable(_bitTable), bitCharLen(_bitCharLen), seqStart(_seqStart), seqLen(0), l1Step(0), L1_SIZE(0), l1bitMask(NULL) { } SArrayIndex::SArrayIndex(const char* seq, quint32 seqSize, quint32 _len, TaskStateInfo& ti, char unknownChar, const quint32* _bitTable, int _bitCharLen, int _gap, int _gapOffset) : w(_len), w4(_len/4), wRest(_len%4), skipGap(_gap), gapOffset(_gapOffset), bitTable(_bitTable), bitCharLen(_bitCharLen), l1Step(0), L1_SIZE(0), l1bitMask(NULL) { quint64 t1 = GTimer::currentTimeMicros(); seqLen = seqSize; arrLen = seqLen - w + 1; if (skipGap > 0) { arrLen = (arrLen / skipGap) + 1; } sArray = new quint32[arrLen]; if (bitTable!=NULL && bitCharLen>0 && bitCharLen<=5) { wCharsInMask = qMin(30 / bitCharLen, w);//30 to avoid +- overflow wAfterBits = qMax(0, w - wCharsInMask); if (wCharsInMask * bitCharLen == 32) { bitFilter = 0xFFFFFFFF; } else { bitFilter = (1<<(bitCharLen * wCharsInMask))-1; } } else { bitMask = NULL; bitFilter = wAfterBits = wCharsInMask = 0; } quint32* arunner = sArray; seqStart = seq; const char* seqEnd= seqStart+seqSize - w + 1; if (unknownChar == 0) { quint32 step = 1 + skipGap; for (const char* crunner = seqStart+gapOffset; crunner < seqEnd; arunner++, crunner+=step) { *arunner=seq2val(crunner); } } else { //filter suffixes with unknown char from result int oldLen = arrLen; const char* crunner = seqStart; int lastErrDist = 0; for (; crunner < seqEnd && lastErrDist < w - 1; crunner++) { if (*crunner != unknownChar) { lastErrDist++; continue; } lastErrDist = 0; } const char* cpos = crunner - w; int gapLeft = _gapOffset; quint32 w1 = w - 1; if (arrLen != 0) { while ( ++cpos < seqEnd ) { if (*(cpos + w1) != unknownChar) { lastErrDist++; if (lastErrDist >= w && gapLeft-- == 0) { *arunner = seq2val(cpos); arunner++; gapLeft = skipGap; } continue; } lastErrDist = 0; gapLeft = _gapOffset; } } arrLen = arunner - sArray; algoLog.trace(QString("filtered len %1, percent %2\n").arg(oldLen - arrLen).arg((arrLen/(float)(oldLen!=0?oldLen:1)))); } // here sArray is initialized with default values and is not sorted arrLen = arunner - sArray; if (bitTable != NULL) { //mask all prefixes in sArray with 32-bit values bitMask = new quint32[arrLen]; quint32 bitValue = 0; quint32* arunner = sArray; quint32* mrunner = bitMask; // Used for optimization - do not recompute whole bit mask if only 1 symbol changes // Note 1: at this moment arrays is not sorted and points to sequential regions // Note 2: expectedNext is not matched if some region was excluded from sarray quint32 expectedNext = 0; quint32 wCharsInMask1 = wCharsInMask - 1; for (quint32* end = mrunner + arrLen; mrunner < end; arunner++, mrunner++) { const char* seq = sarr2seq(arunner); if (*arunner == expectedNext && expectedNext != 0) { //pop first bit, push wCharsInMask1 char to the mask bitValue = ((bitValue << bitCharLen) | bitTable[uchar(*(seq + wCharsInMask1))]) & bitFilter; #ifdef _DEBUG // double check that optimization doesn't break anything quint32 bitValue2 = getBitValue(seq); assert(bitValue == bitValue2); #endif } else { //recompute the mask if we have some symbols skipped bitValue = getBitValue(seq); } expectedNext = seq2val(seq + 1); *mrunner = bitValue; } } if (ti.cancelFlag) { return; } //now sort sArray. Use bit-mask if available if (bitMask!=NULL) { sortBit(bitMask, 0, arrLen); //sortBitClassic(bitMask, 0, arrLen-1); //create L1 cache for bitMask if (arrLen < 200*1000) { L1_SIZE = arrLen; l1Step = 1; l1bitMask = bitMask; } else { L1_SIZE = 8192; l1bitMask = new quint32[L1_SIZE]; l1Step = arrLen / L1_SIZE; for (int i=0; i < L1_SIZE; i++) { l1bitMask[i] = bitMask[i*l1Step]; } l1bitMask[L1_SIZE-1] = bitMask[arrLen-1]; } } else { sort(sArray, 0, arrLen); } quint64 t2 = GTimer::currentTimeMicros(); perfLog.details(QString("SArray index creation time: %1").arg(double(t2-t1)/(1000*1000))); #ifdef _DEBUG debugCheck(unknownChar); #endif } SArrayIndex::~SArrayIndex() { delete[] sArray; if (bitMask!=l1bitMask) { delete[] l1bitMask; } delete bitMask; } quint32 SArrayIndex::getBitValue(const char *seq) const { quint32 bitValue = 0; for (int i = 0; i < wCharsInMask; i++) { bitValue = (bitValue << bitCharLen) | bitTable[uchar(*(seq+i))]; } return bitValue; } //Stable sort of sequences void SArrayIndex::sort(quint32* x, int off, int len) { // Insertion sort on smallest arrays if (len < 7) { for (int i=off; i off && compare(x[j-1],x[j])>0; j--) { qSwap(x[j], x[j-1]); } } return; } // Choose a partition element, v quint32 m = off + len / 2; // Small arrays, middle element if (len > 7) { quint32 l = off; quint32 n = off + len - 1; if (len > 40) { // Big arrays, pseudo median of 9 quint32 s = len / 8; l = med3(x, l, l+s, l+2*s); m = med3(x, m-s, m, m+s); n = med3(x, n-2*s, n-s, n); } m = med3(x, l, m, n); // Mid-size, med of 3 } quint32 v = x[m]; // Establish Invariant: v* (v)* v* int a = off, b = off, c = off + len - 1, d = c; while(true) { int cr; while (b <= c && (cr = compare(v, x[b])) >= 0) { if (cr == 0) { qSwap(x[a],x[b]); a++; } b++; } while (c >= b && (cr = compare(x[c], v)) >=0 ) { if (cr == 0) { qSwap(x[c],x[d]); d--; } c--; } if (b > c) { break; } qSwap(x[b], x[c]); b++; c--; } // Swap partition elements back to middle int s, n = off + len; s = qMin(a-off, b-a ); vecswap(x, off, b-s, s); s = qMin(d-c, n-d-1); vecswap(x, b, n-s, s); // Recursively sort non-partition-elements if ((s = b-a) > 1) { sort(x, off, s); } if ((s = d-c) > 1) { sort(x, n-s, s); } } //Stable sort of sequences void SArrayIndex::sortBit(quint32* x, int off, int len) { // Insertion sort on smallest arrays if (len < 7) { for (int i=off; i off && compareBit(x+j-1,x+j)>0; j--) { swapBit(x+j, x+j-1); } } return; } // Choose a partition element, v quint32 m = off + len / 2; // Small arrays, middle element if (len > 7) { quint32 l = off; quint32 n = off + len - 1; if (len > 40) { // Big arrays, pseudo median of 9 quint32 s = len / 8; l = med3Bit(x, l, l+s, l+2*s); m = med3Bit(x, m-s, m, m+s); n = med3Bit(x, n-2*s, n-s, n); } m = med3Bit(x, l, m, n); // Mid-size, med of 3 } quint32* v = x + m; // Establish Invariant: v* (v)* v* int a = off, b = a, c = off + len - 1, d = c; while(true) { int cr; while (b <= c && (cr = compareBit(v, x+b)) >=0 ) { if (cr == 0) { (x+b==v) && (v=x+a);//save middle pos value swapBit(x+a++,x+b); } b++; } while (c >= b && (cr = compareBit(x+c, v)) >=0 ) { if (cr == 0) { (x+c==v) && (v=x+d);//save middle pos value swapBit(x+c, x+d--); } c--; } if (b > c) { break; } swapBit(x+b++, x+c--); } // Swap partition elements back to middle int s, n = off + len; s = qMin(a-off, b-a ); vecswapBit(x+off, x+b-s, s); s = qMin(d-c, n-d-1); vecswapBit(x+b, x+n-s, s); // Recursively sort non-partition-elements if ((s = b-a) > 1) { sortBit(x, off, s); } if ((s = d-c) > 1) { sortBit(x, n-s, s); } } int SArrayIndex::partition(quint32* x, int l, int r) { quint32* xv = x + l; int i = l - 1, j = r + 1; while (true) { while (compareBit(x + (--j), xv) > 0){} while (compareBit(x + (++i), xv) < 0){} if (i >= j) { return j; } swapBit(x+i, x+j); } } void SArrayIndex::sortBitClassic(quint32* x, int l, int r) { if (l < r) { int q = partition(x, l, r); sortBitClassic(x, l, q); sortBitClassic(x, q + 1, r); } } // Compare by char sequences, then by their position in main sequence int SArrayIndex::compare(const char* seq1, const char* seq2) const { //TODO: use memcmp instead? int res = qstrncmp(seq1, seq2, w); return res; //==0 ? seq1-seq2 : res; // const quint32* a1 = (const quint32*)seq1; // const quint32* a2 = (const quint32*)seq2; // int rc = 0; // for (const quint32* aend1 = a1 + w4; a1 < aend1; a1++, a2++) { // rc = *a1-*a2; // if (rc != 0) { // return rc; // } // } // if (wRest > 0) { // const char* b1 = (const char*)a1; // const char* b2 = (const char*)a2; // rc = *b1 - *b2; // if (rc!=0) { // return rc; // } // if (wRest > 1) { // b1++; b2++; // rc = *b1-*b2; // if (rc != 0) { // return rc; // } // return wRest > 2 ? *++b1-*++b2: 0; // } // } // return seq1-seq2; } // Compare by char sequences, then by their position in main sequence int SArrayIndex::compareBit(const quint32* x1, const quint32* x2) const { int rc = *x1-*x2; if ( rc != 0 || wAfterBits == 0) { return rc; } const char* b1 = sarr2seq(sArray+(x1-bitMask))+wCharsInMask; const char* b2 = sarr2seq(sArray+(x2-bitMask))+wCharsInMask; for (const char* end = b1+wAfterBits; b1 < end; b1++, b2++) { rc=*b1-*b2; if ( rc != 0 ) { return rc; } } return 0; } int SArrayIndex::compareAfterBits(quint32 bitMaskPos, const char* seq) const { const char* b1 = sarr2seq(sArray+bitMaskPos)+wCharsInMask; const char* b2 = seq; int rc = 0; for (const char* end = b1+wAfterBits; b1 < end; b1++, b2++) { rc=*b1-*b2; if (rc != 0) { return rc; } } return 0; } int SArrayIndex::compareBitByPos(const quint32* x1, const quint32* x2) const { int rc = bitMask[x1-sArray]-bitMask[x2-sArray]; if ( rc != 0 ) { return rc; } const char* b1 = sarr2seq(x1)+wCharsInMask; const char* b2 = sarr2seq(x2)+wCharsInMask; for (const char* end = b1+wAfterBits; b1 0) { high = mid - 1; } else { // match! t->currSample = seq; int i = mid; // Find first match position while(--i >= 0) { int res = compare(sarr2seq(a+i), seq); if (res != 0) { break; } } t->currPos = i + 1; return true; } } return false; } bool SArrayIndex::findBit(SArrayIndex::SAISearchContext* t, quint32 bitValue, const char* seq) { int low = 0; int high = L1_SIZE - 1; quint32* a = l1bitMask; while (low <= high) { int mid = (low + high) / 2; int rc = a[mid] - bitValue; if (rc < 0) { low = mid + 1; } else if (rc > 0) { high = mid - 1; } else { for(low=mid+1; low < arrLen && a[low]==bitValue; low++){}; for(high=mid-1;high > 0 && a[high]==bitValue; high--){}; break; } } int newLow = high > 0 ? high * l1Step : 0; high = low < L1_SIZE - 1 ? low * l1Step : arrLen - 1; low = newLow; a = bitMask; while (low <= high) { int mid = (low + high) >> 1; int rc = a[mid] - bitValue; if (rc < 0) { low = mid + 1; } else if (rc > 0) { high = mid - 1; } else {//found bitMask if (wAfterBits == 0) { quint32* maskPos = bitMask+mid; for (; maskPos > bitMask && compareBit(maskPos, maskPos-1) == 0; maskPos--){}; t->currPos = maskPos - bitMask; } else { quint32 midVal = a[mid]; const char* afterBitsSeq = seq + wCharsInMask; bool found = false; rc = compareAfterBits(mid, afterBitsSeq); if (rc == 0) { found = true;// moving to the start of the search item while (mid > 0 && a[mid-1] == midVal && compareAfterBits(mid-1, afterBitsSeq) == 0) { mid--; } } else if (rc > 0) { // search item have lower index for (mid = mid-1; int(mid) >= 0 && a[mid] == midVal; mid--) { if (compareAfterBits(mid, afterBitsSeq) == 0) { found = true; while (mid > 0 && a[mid-1] == midVal && compareAfterBits(mid-1, afterBitsSeq) == 0) { mid--; } break; } } } else { //if (rc < 0) { // search item have higher index for (mid = mid+1; mid < arrLen && a[mid] == midVal; mid++) { if (compareAfterBits(mid, afterBitsSeq) == 0) { found = true; break; } } } if (!found) { return false; } t->currPos = mid; } t->bitValue = bitValue; t->currSample = seq; return true; } } return false; } int SArrayIndex::nextArrSeqPos(SArrayIndex::SAISearchContext* t) { if (t->currPos==-1) { return -1; } int seqPos = sarr2seq(sArray + t->currPos) - seqStart; t->currPos++; if (t->currPos == arrLen || (bitMask!=NULL && compareBit(bitMask + t->currPos-1, bitMask + t->currPos)) || (bitMask==NULL && compare(sarr2seq(sArray + t->currPos), t->currSample))) { t->currPos=-1; } return seqPos; } void SArrayIndex::debugCheck(char unknownChar){ for (int i=1; i < arrLen; i++) { bool fail = bitMask == NULL ? compare(sArray[i-1], sArray[i]) > 0 : bitMask[i-1] > bitMask[i]; if (fail) { algoLog.error("SArray index internal check error 1"); assert(0); } } if (bitMask!=NULL) { quint32* prev = bitMask; for (int i=1; i < arrLen; i++) { quint32* next = bitMask+i; if (compareBit(prev, next) > 0) { algoLog.error("SArray index internal check error 2"); assert(0); } prev = next; } quint32 prevMask = 0; for (int i=1; i < arrLen; i++) { quint32 newMask = bitMask[i]; if (prevMask == newMask) { const char* prevC = sarr2seq(sArray + i - 1); const char* newC = sarr2seq(sArray + i); if (memcmp(prevC, newC, wCharsInMask)) { algoLog.error("SArray index internal check error 3"); assert(0); } } prevMask = newMask; } for (int i=1; i < L1_SIZE; i++) { if (l1bitMask[i-1] > l1bitMask[i]) { algoLog.error("SArray index internal check error 4"); } } } if (unknownChar!=0) { for (int i=0; i < arrLen; i++) { const char* prefix = sarr2seq(sArray + i); for (int j=0; j < w; j++) { if (prefix[j] == unknownChar) { algoLog.error("SArray index internal check error 5"); assert(0); } } } } } template inline void writeNum(T n, QFile &file) { n = qToBigEndian(n); char *num = (char*)&n; file.write(num, 4); } template inline T readNum(char *num, QFile &file) { file.read(num, 4); T n = *((T*)num); n = qFromBigEndian(n); return n; } }//namespace ugene-1.9.8/src/corelibs/U2Algorithm/src/util_algorithm/BinaryFindOpenCL.cpp0000644000175000017500000002705711651544331025462 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "BinaryFindOpenCL.h" #include #include #include #include #include #include #include namespace U2 { NumberType* BinaryFindOpenCL::launch() { time_t time1 = time(NULL); size_t usageGPUMem = 0; size_t usageGPUConstantMem = 0; const int lowerBound = 0; const int uperBound = numbersSize; cl_int err = CL_SUCCESS; int presaveDepthNum = 2000; if (numbersSize < presaveDepthNum) { presaveDepthNum = numbersSize; } NumberType* preSaveBounds = new NumberType[presaveDepthNum]; gauto_array preSaveBoundsPtr(preSaveBounds); NumberType* preSaveValues = new NumberType[presaveDepthNum]; gauto_array preSaveValuesPtr(preSaveValues); prepareBinarySearch(numbers, lowerBound, uperBound, preSaveBounds, preSaveValues, presaveDepthNum - 1); cl_uint clNumDevices = 1; cl_device_id deviceId = (cl_device_id) AppContext::getOpenCLGpuRegistry()->getAnyEnabledGpu()->getId(); const OpenCLHelper& openCLHelper = AppContext::getOpenCLGpuRegistry()->getOpenCLHelper(); if (!openCLHelper.isLoaded()) { coreLog.error(openCLHelper.getErrorString()); return 0; } algoLog.trace("Creating a context"); clContext = openCLHelper.clCreateContext_p(0, clNumDevices, &deviceId, NULL, NULL, &err); if (hasOPENCLError(err, "clContext() failed")) return 0; //open and read file contains OPENCL code clProgram = OpenCLUtils::createProgramByResource(clContext, deviceId, ":src/util_gpu/opencl/BinaryFind.cl", openCLHelper, err); if (hasOPENCLError(err, "createProgramByResource() failed")) return 0; clKernel = openCLHelper.clCreateKernel_p(clProgram, "binarySearch_classic", &err); hasOPENCLError(err, "clCreateKernel"); int iterationsNum = 20000; if (numbersSize < iterationsNum) { iterationsNum = numbersSize / 2 + 1; } size_t localWorkSize = 32; if (findNumbersSize < localWorkSize) { localWorkSize = findNumbersSize; } size_t blocksNum = (findNumbersSize + iterationsNum - 1) / iterationsNum; blocksNum = (blocksNum + localWorkSize - 1) / localWorkSize; const size_t globalWorkSize = blocksNum * localWorkSize; algoLog.details(QObject::tr("blocks: %1 globalWorkSize %2 localWorkSize %3 iterationsNum %4").arg(blocksNum).arg(globalWorkSize).arg(localWorkSize).arg(iterationsNum)); buf_findMeArray = openCLHelper.clCreateBuffer_p(clContext, CL_MEM_READ_WRITE | CL_MEM_COPY_HOST_PTR, sizeof(NumberType) * findNumbersSize, (void*)findNumbers, &err); if (hasOPENCLError(err, "buf_findMeArray clCreateBuffer")) return 0; usageGPUMem += sizeof(NumberType) * findNumbersSize; const int outputArraySize = findNumbersSize; buf_sortedArray = openCLHelper.clCreateBuffer_p(clContext, CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR, sizeof(NumberType) * numbersSize, (void*)numbers, &err); if (hasOPENCLError(err, "buf_sortedArray clCreateBuffer")) return 0; usageGPUMem += sizeof(NumberType) * numbersSize; buf_preSaveBounds = openCLHelper.clCreateBuffer_p(clContext, CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR, sizeof(NumberType) * presaveDepthNum, (void*)preSaveBounds, &err); if (hasOPENCLError(err, "buf_preSaveBounds clCreateBuffer")) return 0; usageGPUMem += sizeof(NumberType) * presaveDepthNum; buf_preSaveValues = openCLHelper.clCreateBuffer_p(clContext, CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR, sizeof(NumberType) * presaveDepthNum, (void*)preSaveValues, &err); if (hasOPENCLError(err, "buf_preSaveValues clCreateBuffer")) return 0; usageGPUConstantMem += sizeof(NumberType) * presaveDepthNum; cl_uint n = 0; err = openCLHelper.clSetKernelArg_p(clKernel, n++, sizeof(cl_mem), (void*)&buf_sortedArray); if (hasOPENCLError(err, QString("clSetKernelArg argNum: %1").arg(n))) return 0; err = openCLHelper.clSetKernelArg_p(clKernel, n++, sizeof(cl_mem), (void*)&buf_findMeArray); if (hasOPENCLError(err, QString("clSetKernelArg argNum: %1").arg(n))) return 0; err = openCLHelper.clSetKernelArg_p(clKernel, n++, sizeof(cl_int), (void*)&findNumbersSize); if (hasOPENCLError(err, QString("clSetKernelArg argNum: %1").arg(n))) return 0; err = openCLHelper.clSetKernelArg_p(clKernel, n++, sizeof(cl_int), (void*)&lowerBound); if (hasOPENCLError(err, QString("clSetKernelArg argNum: %1").arg(n))) return 0; err = openCLHelper.clSetKernelArg_p(clKernel, n++, sizeof(cl_int), (void*)&uperBound); if (hasOPENCLError(err, QString("clSetKernelArg argNum: %1").arg(n))) return 0; err = openCLHelper.clSetKernelArg_p(clKernel, n++, sizeof(cl_int), (void*)&iterationsNum); if (hasOPENCLError(err, QString("clSetKernelArg argNum: %1").arg(n))) return 0; err = openCLHelper.clSetKernelArg_p(clKernel, n++, sizeof(cl_mem), (void*)&buf_preSaveBounds); if (hasOPENCLError(err, QString("clSetKernelArg argNum: %1").arg(n))) return 0; err = openCLHelper.clSetKernelArg_p(clKernel, n++, sizeof(cl_mem), (void*)&buf_preSaveValues); if (hasOPENCLError(err, QString("clSetKernelArg argNum: %1").arg(n))) return 0; err = openCLHelper.clSetKernelArg_p(clKernel, n++, sizeof(cl_int), (void*)&presaveDepthNum); if (hasOPENCLError(err, QString("clSetKernelArg argNum: %1").arg(n))) return 0; err = openCLHelper.clSetKernelArg_p(clKernel, n++, sizeof(NumberType) * presaveDepthNum, NULL); if (hasOPENCLError(err, QString("clSetKernelArg argNum: %1").arg(n))) return 0; err = openCLHelper.clSetKernelArg_p(clKernel, n++, sizeof(NumberType), (void*)&filter); if (hasOPENCLError(err, QString("clSetKernelArg argNum: %1").arg(n))) return 0; clCommandQueue = openCLHelper.clCreateCommandQueue_p(clContext, deviceId, CL_QUEUE_OUT_OF_ORDER_EXEC_MODE_ENABLE, &err); if (hasOPENCLError(err, "cl::CommandQueue() failed ")) return 0; err = openCLHelper.clEnqueueNDRangeKernel_p( clCommandQueue, clKernel, 1, NULL, &globalWorkSize, &localWorkSize, 0, NULL, &clEvent1); if (hasOPENCLError(err, "clEnqueueNDRangeKernel")) return 0; err = openCLHelper.clWaitForEvents_p(1, &clEvent1); if (hasOPENCLError(err, "clWaitForEvents 1")) return 0; if (clEvent1) { err = openCLHelper.clReleaseEvent_p (clEvent1); if (hasOPENCLError(err, "clReleaseEvent 1 failed")) return 0; } NumberType* outputArray = new NumberType[outputArraySize]; err = openCLHelper.clEnqueueReadBuffer_p(clCommandQueue, buf_findMeArray, CL_FALSE, 0, sizeof(NumberType) * outputArraySize, outputArray, 0, NULL, &clEvent2); if (hasOPENCLError(err, "clCommandQueue")) { delete[] outputArray; return 0; } err = openCLHelper.clWaitForEvents_p(1, &clEvent2); if (hasOPENCLError(err, "clWaitForEvents")) { delete[] outputArray; return 0; } if (clEvent2) { err = openCLHelper.clReleaseEvent_p (clEvent2); if (hasOPENCLError(err, "clReleaseEvent 2 failed")) return 0; } time_t time2 = time(NULL); algoLog.details(QObject::tr("GPU execution time: %1 GPUMem ussage: %2 Mb GPUContantMem %3 Kb") .arg((time2 - time1)) .arg(usageGPUMem / 1024 / 1024) .arg(usageGPUConstantMem / 1024)); return outputArray; } void BinaryFindOpenCL::prepareBinarySearch(const NumberType* arr, int lowerBound, int upperBound, NumberType* resBounds, NumberType* resValues, const int depthNum) { if (depthNum != 0) { const int step = (upperBound - lowerBound) / (depthNum); for (int i = 1; i < depthNum; i++) { resBounds[i] = step * i; resValues[i] = arr[resBounds[i]]; } } resBounds[0] = lowerBound; resValues[0] = arr[resBounds[0]]; resBounds[depthNum] = upperBound - 1; resValues[depthNum] = arr[resBounds[depthNum]]; } BinaryFindOpenCL::~BinaryFindOpenCL() { algoLog.details(QObject::tr("clear OpenCL resources")); cl_int err = CL_SUCCESS; const OpenCLHelper& openCLHelper = AppContext::getOpenCLGpuRegistry()->getOpenCLHelper(); if (clKernel) { err = openCLHelper.clReleaseKernel_p(clKernel); hasOPENCLError(err, "clReleaseEvent failed"); } if (clProgram) { err = openCLHelper.clReleaseProgram_p(clProgram); hasOPENCLError(err, "clReleaseEvent failed"); } if (clCommandQueue) { err = openCLHelper.clReleaseCommandQueue_p(clCommandQueue); hasOPENCLError(err, "clReleaseEvent failed"); } if (clContext) { err = openCLHelper.clReleaseContext_p(clContext); hasOPENCLError(err, "clReleaseEvent failed"); } if (buf_sortedArray) { err = openCLHelper.clReleaseMemObject_p(buf_sortedArray); hasOPENCLError(err, "clReleaseMemObject failed"); } if (buf_findMeArray) { err = openCLHelper.clReleaseMemObject_p(buf_findMeArray); hasOPENCLError(err, "clReleaseMemObject failed"); } if (buf_outPutArray) { err = openCLHelper.clReleaseMemObject_p(buf_outPutArray); hasOPENCLError(err, "clReleaseMemObject failed"); } if (buf_preSaveBounds) { err = openCLHelper.clReleaseMemObject_p(buf_preSaveBounds); hasOPENCLError(err, "clReleaseMemObject failed"); } if (buf_preSaveValues) { err = openCLHelper.clReleaseMemObject_p(buf_preSaveValues); hasOPENCLError(err, "clReleaseMemObject failed"); } } BinaryFindOpenCL::BinaryFindOpenCL(const NumberType *_numbers, const int _numbersSize, const NumberType *_findNumbers, const int _findNumbersSize, const NumberType _filter) : numbers(_numbers), numbersSize(_numbersSize), findNumbers(_findNumbers), findNumbersSize(_findNumbersSize), filter(_filter) { clEvent1 = 0; clEvent2 = 0; clKernel = 0; clProgram = 0; clCommandQueue = 0; clContext = 0; buf_sortedArray = 0; buf_findMeArray = 0; buf_outPutArray = 0; buf_preSaveBounds = 0; buf_preSaveValues = 0; } bool BinaryFindOpenCL::hasOPENCLError(int err, QString errorMessage) { if(err != 0) { algoLog.error(QString("OPENCL: %1; Error code (%2)").arg(errorMessage).arg(err)); return true; } else { return false; } } }//namespace ugene-1.9.8/src/corelibs/U2Algorithm/src/util_algorithm/FindAlgorithm.h0000644000175000017500000001230711651544331024560 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_FINDALGORITHM_H_ #define _U2_FINDALGORITHM_H_ #include #include #include namespace U2 { class U2ALGORITHM_EXPORT FindAlgorithmResult { public: FindAlgorithmResult() : err(0) {} FindAlgorithmResult(const U2Region& _r, bool t, U2Strand s, int _err) : region(_r), translation(t), strand(s), err(_err){} void clear() {region.startPos = 0; region.length = 0; translation = false; strand = U2Strand::Direct; err = 0;} bool isEmpty() const {return region.startPos == 0 && region.length == 0;} bool operator ==(const FindAlgorithmResult& o) const { return region == o.region && err == o.err && strand == o.strand && translation == o.translation; } SharedAnnotationData toAnnotation(const QString& name) const { SharedAnnotationData data; data = new AnnotationData; data->name = name; data->location->regions << region; data->setStrand(strand); data->qualifiers.append(U2Qualifier("mismatches", QString::number(err))); return data; } U2Region region; bool translation; U2Strand strand; int err; static QList toTable(const QList& res, const QString& name) { QList list; foreach (const FindAlgorithmResult& f, res) { list.append(f.toAnnotation(name)); } return list; } }; class DNATranslation; class U2ALGORITHM_EXPORT FindAlgorithmResultsListener { public: virtual ~FindAlgorithmResultsListener(){} virtual void onResult(const FindAlgorithmResult& r) = 0; }; enum FindAlgorithmStrand { FindAlgorithmStrand_Both, FindAlgorithmStrand_Direct, FindAlgorithmStrand_Complement }; class U2ALGORITHM_EXPORT FindAlgorithmSettings { public: FindAlgorithmSettings(const QByteArray& pattern = QByteArray(), FindAlgorithmStrand strand = FindAlgorithmStrand_Direct, DNATranslation* complementTT = NULL, DNATranslation* proteinTT = NULL, const U2Region& searchRegion = U2Region(), bool singleShot = false, int maxErr = 0, bool insDel = false, bool ambBases = false ) : pattern(pattern), strand(strand), complementTT(complementTT), proteinTT(proteinTT), searchRegion(searchRegion), singleShot(singleShot), maxErr(maxErr), insDelAlg(insDel), useAmbiguousBases (ambBases) {} QByteArray pattern; FindAlgorithmStrand strand; DNATranslation* complementTT; DNATranslation* proteinTT; U2Region searchRegion; bool singleShot; int maxErr; bool insDelAlg; bool useAmbiguousBases; }; class U2ALGORITHM_EXPORT FindAlgorithm { public: // Note: pattern is never affected by either aminoTT or complTT static void find( FindAlgorithmResultsListener* rl, DNATranslation* aminoTT, // if aminoTT!=NULL -> pattern must contain amino data and sequence must contain DNA data DNATranslation* complTT, // if complTT!=NULL -> sequence is complemented before comparison with pattern FindAlgorithmStrand strand, // if not direct there complTT must not be NULL bool insDel, bool supportAmbigiousBases, const char* sequence, int seqLen, const U2Region& range, const char* pattern, int patternLen, bool singleShot, int maxErr, int& stopFlag, int& percentsCompleted, int& currentPos); static void find( FindAlgorithmResultsListener* rl, const FindAlgorithmSettings& config, const char* sequence, int seqLen, int& stopFlag, int& percentsCompleted, int& currentPos) { find(rl, config.proteinTT, config.complementTT, config.strand, config.insDelAlg, config.useAmbiguousBases, sequence, seqLen, config.searchRegion, config.pattern.constData(), config.pattern.length(), config.singleShot, config.maxErr, stopFlag, percentsCompleted, currentPos); } }; }//namespace #endif ugene-1.9.8/src/corelibs/U2Algorithm/src/util_algorithm/EnzymeModel.h0000644000175000017500000000561011651544331024260 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_ENZYME_MODEL_H_ #define _U2_ENZYME_MODEL_H_ #include #include #include #include #include namespace U2 { class DNAAlphabet; #define QUALIFIER_LEFT_TERM "5'term" #define QUALIFIER_LEFT_OVERHANG "5'overhang" #define QUALIFIER_LEFT_TYPE "5'type" #define QUALIFIER_LEFT_STRAND "5'strand" #define QUALIFIER_RIGHT_TERM "3'term" #define QUALIFIER_RIGHT_OVERHANG "3'overhang" #define QUALIFIER_RIGHT_TYPE "3'type" #define QUALIFIER_RIGHT_STRAND "3'strand" #define QUALIFIER_SOURCE "fragment_source" #define QUALIFIER_INVERTED "fragment_inverted" #define OVERHANG_TYPE_BLUNT "blunt" #define OVERHANG_TYPE_STICKY "sticky" #define OVERHANG_STRAND_DIRECT "direct" #define OVERHANG_STRAND_COMPL "rev-compl" #define ANNOTATION_GROUP_FRAGMENTS "fragments" #define ANNOTATION_GROUP_ENZYME "enzyme" #define ENZYME_CUT_UNKNOWN 0x7FFFFF #define ENZYME_LIST_SEPARATOR "," class U2ALGORITHM_EXPORT EnzymeSettings { public: static const QString DATA_DIR_KEY; static const QString DATA_FILE_KEY; static const QString LAST_SELECTION; static const QString ENABLE_HIT_COUNT; static const QString MAX_HIT_VALUE; static const QString MIN_HIT_VALUE; static const QString NON_CUT_REGION; static const QString MAX_RESULTS; static const QString COMMON_ENZYMES; }; class U2ALGORITHM_EXPORT EnzymeData : public QSharedData { public: EnzymeData(); QString id; QString accession; QString type; QByteArray seq; int cutDirect; //starts from the first char in direct strand int cutComplement; // starts from the first char in complement strand, negative->right offset QString organizm; DNAAlphabet* alphabet; }; typedef QSharedDataPointer SEnzymeData; } //namespace #endif ugene-1.9.8/src/corelibs/U2Algorithm/src/util_algorithm/ORFFinder.cpp0000644000175000017500000002361111651544331024142 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "ORFFinder.h" #include #include #include #include #include #include #include #include namespace U2 { const QString ORFAlgorithmSettings::ANNOTATION_GROUP_NAME("orf"); const QString ORFAlgorithmSettings::STRAND_BOTH("both strands"); const QString ORFAlgorithmSettings::STRAND_DIRECT("direct"); const QString ORFAlgorithmSettings::STRAND_COMPL("complement"); static bool isDirect(ORFAlgorithmStrand s) { return s == ORFAlgorithmStrand_Both || s == ORFAlgorithmStrand_Direct; } static bool isComplement(ORFAlgorithmStrand s) { return s == ORFAlgorithmStrand_Both || s == ORFAlgorithmStrand_Complement; } void ORFFindAlgorithm::find( ORFFindResultsListener* rl, const ORFAlgorithmSettings& cfg, const char* sequence, int seqLen, int& stopFlag, int& percentsCompleted) { Q_UNUSED(seqLen); assert(cfg.proteinTT && cfg.proteinTT->isThree2One()); assert(seqLen >= cfg.searchRegion.endPos() - 1); DNATranslation3to1Impl* aTT = (DNATranslation3to1Impl*)cfg.proteinTT; bool mustFit = cfg.mustFit; bool mustInit = cfg.mustInit; bool allowAltStart = cfg.allowAltStart; bool allowOverlap = cfg.allowOverlap; bool circularSearch = cfg.circularSearch; int minLen = qMax(cfg.minLen, 3); int onePercentLen = cfg.searchRegion.length/100; if (cfg.strand == ORFAlgorithmStrand_Both) onePercentLen /=2; int leftTillPercent = onePercentLen; percentsCompleted = 0; if (isDirect(cfg.strand)) { QList start[3]; if (!mustInit) { for (int i=0; i<3;i++) { int frame = (cfg.searchRegion.startPos + i)%3; start[frame].append(cfg.searchRegion.startPos + i); } } int end = cfg.searchRegion.endPos(); for(int i = cfg.searchRegion.startPos; i < end && !stopFlag; i++, leftTillPercent--) { int frame = i%3; QList* initiators = start + frame; if (!initiators->isEmpty() && aTT->isStopCodon(sequence + i)) { foreach(int initiator, *initiators) { int len = i - initiator; if (len>=minLen) rl->onResult(ORFFindResult(U2Region(initiator, len), frame)); } initiators->clear(); if (!mustInit) { initiators->append(i+3); } } else if (initiators->isEmpty() || allowOverlap) { if (aTT->isStartCodon(sequence + i) || (allowAltStart && aTT->isCodon(DNATranslationRole_Start_Alternative, sequence + i)) ) { if (initiators->isEmpty() || initiators->last() != i) { initiators->append(i); } } } if (leftTillPercent == 0) { percentsCompleted = qMin(percentsCompleted+1,100); leftTillPercent = onePercentLen; } } if(circularSearch && !stopFlag){ //circular int regLen = end - cfg.searchRegion.startPos; int minInitiator = end; bool initiatorsRemain = false; for (int i=0; i<3;i++) { foreach(int initiator, start[i]) { if(initiator < minInitiator){ minInitiator = initiator; initiatorsRemain = true; } } } for(int i = cfg.searchRegion.startPos; i < minInitiator && !stopFlag && initiatorsRemain; i++) { int frame =(regLen+i)%3; QList* initiators = start + frame; if (!initiators->isEmpty() && aTT->isStopCodon(sequence + i)) { foreach(int initiator, *initiators) { int len = regLen + i - initiator; if (len>=minLen){ rl->onResult(ORFFindResult(U2Region(initiator, end-initiator), U2Region(cfg.searchRegion.startPos, i), frame)); } } initiators->clear(); } } } if (!mustFit && !stopFlag) { //check if non-terminated ORFs remained for (int i=0; i<3;i++) { foreach(int initiator, start[i]) { int len = end - initiator - i; len -= len%3; if (len>=minLen) rl->onResult(ORFFindResult(U2Region(initiator, len), i + 1)); } } } } if (isComplement(cfg.strand)) { assert(cfg.complementTT && cfg.complementTT->isOne2One()); QByteArray revComplDna(cfg.searchRegion.length, 0); cfg.complementTT->translate(sequence + cfg.searchRegion.startPos, cfg.searchRegion.length, revComplDna.data(), cfg.searchRegion.length); TextUtils::reverse(revComplDna.data(), revComplDna.size()); const char* rcSeq = revComplDna.data(); const char* rcSeqCyrcular = rcSeq; QList start[3]; if (!mustInit) { for (int i=0; i<3;i++) { int frame = (cfg.searchRegion.endPos() - i)%3; start[frame].append(cfg.searchRegion.endPos() - i); } } int end = cfg.searchRegion.startPos; for(int i = cfg.searchRegion.endPos(); i >= end && !stopFlag; rcSeq++, i--, leftTillPercent--) { int frame = i%3; QList* initiators = start + frame; if (!initiators->isEmpty() && aTT->isStopCodon(rcSeq)) { foreach(int initiator, *initiators) { int len = initiator - i; if (len>=minLen) rl->onResult(ORFFindResult(U2Region(i, len), frame - 3)); } initiators->clear(); if (!mustInit) { initiators->append(i-3); } } else if (initiators->isEmpty() || allowOverlap) { if (aTT->isStartCodon(rcSeq) || (allowAltStart && aTT->isCodon(DNATranslationRole_Start_Alternative, rcSeq)) ) { if (initiators->isEmpty() || initiators->last() != i) { initiators->append(i); } } } if (leftTillPercent == 0) { percentsCompleted = qMin(percentsCompleted+1,100); leftTillPercent = onePercentLen; } } if(circularSearch && !stopFlag){ int regLen = cfg.searchRegion.endPos() - cfg.searchRegion.startPos; int maxInitiator = -1; bool initiatorsRemain = false; for (int i=0; i<3;i++) { foreach(int initiator, start[i]) { if(initiator > maxInitiator){ maxInitiator = initiator; initiatorsRemain = true; } } } for(int i = cfg.searchRegion.endPos(); i >= maxInitiator && !stopFlag && initiatorsRemain; rcSeqCyrcular++, i--) { int frame =(regLen+i)%3; QList* initiators = start + frame; if (!initiators->isEmpty() && aTT->isStopCodon(rcSeqCyrcular)) { foreach(int initiator, *initiators) { int len = regLen + initiator - i ; if (len>=minLen){ rl->onResult(ORFFindResult(U2Region(i, cfg.searchRegion.endPos()-i), U2Region(end, initiator), frame - 3)); } } initiators->clear(); } } } if (!mustFit && !stopFlag) { //check if non-terminated ORFs remained for (int i=0; i<3;i++) { foreach(int initiator, start[i]) { int ind = end + i%3; int len = initiator - ind; len -= len%3; if (len>=minLen) rl->onResult(ORFFindResult(U2Region(ind, len), i - 3)); } } } } } QString ORFAlgorithmSettings::getStrandStringId(ORFAlgorithmStrand strand) { if (strand == ORFAlgorithmStrand_Direct) { return STRAND_DIRECT; } else if (strand == ORFAlgorithmStrand_Complement) { return STRAND_COMPL; } else { assert (strand == ORFAlgorithmStrand_Both ); return STRAND_BOTH; } } ORFAlgorithmStrand ORFAlgorithmSettings::getStrandByStringId( const QString& id ) { if (id == STRAND_DIRECT) { return ORFAlgorithmStrand_Direct; } else if (id == STRAND_COMPL) { return ORFAlgorithmStrand_Complement; } else { return ORFAlgorithmStrand_Both; } } }//namespace ugene-1.9.8/src/corelibs/U2Algorithm/src/util_algorithm/FindAlgorithmTask.h0000644000175000017500000000364011651544331025403 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_FIND_ENZYMES_TASK_H_ #define _U2_FIND_ENZYMES_TASK_H_ #include #include #include "FindAlgorithm.h" #include namespace U2 { class DNATranslation; class U2ALGORITHM_EXPORT FindAlgorithmTaskSettings : public FindAlgorithmSettings { public: FindAlgorithmTaskSettings() {} FindAlgorithmTaskSettings(const FindAlgorithmSettings& f) : FindAlgorithmSettings(f) {} QByteArray sequence; }; class U2ALGORITHM_EXPORT FindAlgorithmTask : public Task, public FindAlgorithmResultsListener { Q_OBJECT public: FindAlgorithmTask(const FindAlgorithmTaskSettings& s); virtual void run(); virtual void onResult(const FindAlgorithmResult& r); int getCurrentPos() const {return currentPos;} QList popResults(); const FindAlgorithmTaskSettings& getSettings() const {return config;} private: FindAlgorithmTaskSettings config; int currentPos; bool complementRun; QList newResults; QMutex lock; }; } //namespace #endif ugene-1.9.8/src/corelibs/U2Algorithm/src/util_algorithm/SArrayIndexSerializer.cpp0000644000175000017500000002065111651544331026610 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include #include "SArrayIndexSerializer.h" namespace U2 { const QString SArrayIndexSerializer::SARRAY_HEADER("#UGENE suffix array index\n"); const QString SArrayIndexSerializer::SARRAY_PARAMETERS("#file \"%1\", sequence's length = %2, w = %3, gap offset = %4\n"); void SArrayIndexSerializer::serialize(const SArrayIndex *index, const QString &indexFileName, const QString &refFileName) { assert(NULL != index); QFile file(indexFileName); if (indexFileName.isEmpty() || !file.open(QIODevice::WriteOnly)) { return; } QByteArray data; data = SARRAY_HEADER.toAscii(); data += SARRAY_PARAMETERS.arg(refFileName).arg(index->seqLen).arg(index->w).arg(index->gapOffset).toAscii(); data += QByteArray::number(index->w, 10) + ", "; data += QByteArray::number(index->w4, 10) + ", "; data += QByteArray::number(index->wRest, 10) + ", "; data += QByteArray::number(index->skipGap, 10) + ", "; data += QByteArray::number(index->gapOffset, 10) + ", "; data += QByteArray::number(index->arrLen, 10) + ", "; data += QByteArray::number(index->seqLen, 10) + ", "; data += QByteArray::number(index->bitFilter, 10) + ", "; data += QByteArray::number(index->wCharsInMask, 10) + ", "; data += QByteArray::number(index->wAfterBits, 10) + ", "; data += QByteArray::number(index->l1Step, 10) + ", "; data += QByteArray::number(index->L1_SIZE, 10) + "\n"; file.write(data); QByteArray writeBuffer(BUFF_SIZE, '\0'); char *buff = writeBuffer.data(); writeArray(file, buff, index->sArray, index->arrLen); if (NULL != index->bitMask) { writeArray(file, buff, index->bitMask, index->arrLen); writeArray(file, buff, index->l1bitMask, index->L1_SIZE); } file.close(); } void SArrayIndexSerializer::writeArray(QFile &file, char *buff, quint32 *array, int len) { int pos = 0; QByteArray line; quint32 number = 0; quint32 tmpNum = 0; char c = 0; long long divider = 10; int numberLength = 0; for (int i = 0; i < len; ++i) { number = array[i]; if (0 == number) { divider = 10; numberLength = 1; } else { tmpNum = number; divider = 1; numberLength = 0; while (0 != tmpNum) { tmpNum /=10; divider *= 10; numberLength++; } divider /= 10; } assert(numberLength > 0); while (1) { if (pos == BUFF_SIZE) { file.write(buff, BUFF_SIZE); pos = 0; } if (0 == numberLength) { buff[pos] = '\n'; pos++; break; } else { tmpNum = number/divider; c = tmpNum + '0'; buff[pos] = c; pos++; number = number - tmpNum*divider; numberLength--; divider /= 10; } } } file.write(buff, pos); } inline int getNextInt(QByteArray &data, bool &eol, bool &intErr) { int commaIdx = data.indexOf(','); if (-1 == commaIdx) { commaIdx = data.length(); eol = true; } QByteArray result = data.left(commaIdx).trimmed(); data = data.mid(commaIdx+1).trimmed(); char c = 0; for (int i = 0; i < result.length(); i++) { c = result[i]; if (c <'0' || c>'9') { intErr = true; return -1; } } return result.toInt(); } void SArrayIndexSerializer::readArray(QFile &file, char *buff, int *len, int *pos, int *bytes, int *lineIdx, quint32 *array, int arrLen, TaskStateInfo& ti) { quint32 number = 0; int numberLength = 0; bool newLine = true; Q_UNUSED(newLine); //used only in assertions for (int i = 0; i < arrLen; i++) { number = 0; numberLength = 0; assert(newLine); while (1) { if (*pos == *len) { ti.progress = (int)(100 *(*bytes/(double)file.size())); *len = file.read(buff, BUFF_SIZE); *bytes += *len; *pos = 0; if (*len <= 0) { break; } if (ti.cancelFlag) { return; } } char c = buff[*pos]; if ('\n' == c || 0 == c) { (*pos)++; (*lineIdx)++; newLine = true; break; } else if (c >='0' && c<='9') { number = number*10+(c-'0'); (*pos)++; numberLength++; newLine = false; } else { ti.setError(QString("Not digit in the number at line %1").arg(*lineIdx)); return; } } if (0 == *len && (arrLen - 1) != i) { ti.setError("There is not enough array's values it the file-index"); return; } if (0 == numberLength) { ti.setError(QString("Empty array's value at line %1").arg(*lineIdx-1)); return; } array[i] = number; } } void SArrayIndexSerializer::deserialize(SArrayIndex *index, const QString &indexFileName, TaskStateInfo& ti) { QFile file(indexFileName); if (!file.open(QIODevice::ReadOnly)) { ti.setError("Can't open file-index"); return; } QByteArray data; bool eol = false; bool intErr = false; int lineIdx = 0; do { data = file.readLine().trimmed(); lineIdx++; } while (data.length() > 0 && '#' == data[0]); if (0 == data.length()) { ti.setError("Empty parameters' line in the file-index"); return; } index->w = getNextInt(data, eol, intErr); index->w4 = getNextInt(data, eol, intErr); index->wRest = getNextInt(data, eol, intErr); index->skipGap = getNextInt(data, eol, intErr); index->gapOffset = getNextInt(data, eol, intErr); index->arrLen = getNextInt(data, eol, intErr); index->seqLen = getNextInt(data, eol, intErr); index->bitFilter = getNextInt(data, eol, intErr); index->wCharsInMask = getNextInt(data, eol, intErr); index->wAfterBits = getNextInt(data, eol, intErr); index->l1Step = getNextInt(data, eol, intErr); if (eol) { ti.setError("Too little amount of parameters in the file-index"); return; } index->L1_SIZE = getNextInt(data, eol, intErr); if (intErr) { ti.setError("Bad integer for some parameter in the file-index"); return; } if (index->w <= 0 || index->arrLen <= 0) { ti.setError("Negative index's parameters"); return; } index->sArray = new quint32[index->arrLen]; QByteArray readBuffer(BUFF_SIZE, '\0'); char *buff = readBuffer.data(); lineIdx++; int len = 0; int pos = 0; int bytes = len; readArray(file, buff, &len, &pos, &bytes, &lineIdx, index->sArray, index->arrLen, ti); if (ti.cancelFlag || ti.hasError()) { file.close(); return; } index->bitMask = new quint32[index->arrLen]; readArray(file, buff, &len, &pos, &bytes, &lineIdx, index->bitMask, index->arrLen, ti); if (ti.cancelFlag || ti.hasError()) { file.close(); return; } index->l1bitMask = new quint32[index->L1_SIZE]; readArray(file, buff, &len, &pos, &bytes, &lineIdx, index->l1bitMask, index->L1_SIZE, ti); file.close(); } } //namespace ugene-1.9.8/src/corelibs/U2Algorithm/src/util_algorithm/SArrayIndexSerializer.h0000644000175000017500000000322211651544331026250 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_SARRAY_INDEX_SERIALIZER_H_ #define _U2_SARRAY_INDEX_SERIALIZER_H_ #include "SArrayIndex.h" #include #include namespace U2 { class U2ALGORITHM_EXPORT SArrayIndexSerializer { public: static void serialize(const SArrayIndex *index, const QString &indexFileName, const QString &refFileName); static void deserialize(SArrayIndex *index, const QString &indexFileName, TaskStateInfo& ti); private: static const QString SARRAY_HEADER; static const QString SARRAY_PARAMETERS; static const int BUFF_SIZE = 1048576; static void writeArray(QFile &file, char *buff, quint32 *array, int len); static void readArray(QFile &file, char *buff, int *len, int *pos, int *bytes, int *lineIdx, quint32 *array, int arrLen, TaskStateInfo& ti); }; } //namespace #endif ugene-1.9.8/src/corelibs/U2Algorithm/src/util_algorithm/BitsTable.cpp0000644000175000017500000000463311651544331024240 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "BitsTable.h" namespace U2 { const quint32 BitsTable::NUCL_BITS_SIZE = 2; const quint32 BitsTable::PROTEIN_BITS_SIZE = 5; const quint32 BitsTable::RAW_BITS_SIZE = 8; BitsTable::BitsTable () { for (int i = 256; --i >= 0;) { PROTEIN_BITS[i] = 0; NUCL_BITS[i] = 0; RAW_BITS[i] = i; } quint32 pBits= 1; PROTEIN_BITS['A'] = pBits++; PROTEIN_BITS['C'] = pBits++; PROTEIN_BITS['D'] = pBits++; PROTEIN_BITS['E'] = pBits++; PROTEIN_BITS['F'] = pBits++; PROTEIN_BITS['G'] = pBits++; PROTEIN_BITS['H'] = pBits++; PROTEIN_BITS['I'] = pBits++; PROTEIN_BITS['K'] = pBits++; PROTEIN_BITS['L'] = pBits++; PROTEIN_BITS['M'] = pBits++; PROTEIN_BITS['N'] = pBits++; PROTEIN_BITS['P'] = pBits++; PROTEIN_BITS['Q'] = pBits++; PROTEIN_BITS['R'] = pBits++; PROTEIN_BITS['S'] = pBits++; PROTEIN_BITS['T'] = pBits++; PROTEIN_BITS['V'] = pBits++; PROTEIN_BITS['W'] = pBits++; PROTEIN_BITS['Y'] = pBits++; PROTEIN_BITS['*'] = pBits; PROTEIN_BITS['+'] = pBits; PROTEIN_BITS['#'] = pBits; NUCL_BITS['A'] = 0x0; //00 NUCL_BITS['C'] = 0x1; //01 NUCL_BITS['T'] = 0x2; //10 NUCL_BITS['G'] = 0x3; //11 //todo: RNA? } quint32 BitsTable::getBitMaskCharBitsNum(DNAAlphabetType al) const { return al == DNAAlphabet_NUCL ? NUCL_BITS_SIZE : al == DNAAlphabet_AMINO ? PROTEIN_BITS_SIZE : RAW_BITS_SIZE; } const quint32* BitsTable::getBitMaskCharBits(DNAAlphabetType al) const { return al == DNAAlphabet_NUCL ? NUCL_BITS: al == DNAAlphabet_AMINO ? PROTEIN_BITS: RAW_BITS; } }//namespace ugene-1.9.8/src/corelibs/U2Algorithm/src/util_algorithm/SArrayBasedFindTask.cpp0000644000175000017500000001307611651544331026154 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "SArrayIndex.h" #include "SArrayBasedFindTask.h" namespace U2 { #define PCHAR_MATCH(x, y) (*(x) == *(y) && *(x) != unknownChar) SArrayBasedFindTask::SArrayBasedFindTask( SArrayIndex* i, const SArrayBasedSearchSettings& s, bool _onlyFirstMatch ) : Task("SArrayBasedFindTask", TaskFlag_None), index(i), config(new SArrayBasedSearchSettings(s)), onlyFirstMatch(_onlyFirstMatch) { assert(index); } void SArrayBasedFindTask::run() { runSearchWithMismatches(); } void SArrayBasedFindTask::runSearch() { bool haveResults = true; SArrayIndex::SAISearchContext context; const char* querySeq = config->query.constData(); if (config->useBitMask) { const quint32* bm = config->bitMask; int charBitsNum = config->bitMaskCharBitsNum; quint32 bitValue = 0; int wCharsInMask = index->getCharsInMask(); const char* posS = querySeq; char unknownChar = config->unknownChar; for (int cleanChars = 0; cleanChars < wCharsInMask; posS++) { if (*posS == unknownChar) { cleanChars = 0; bitValue = 0; } else { bitValue = (bitValue << charBitsNum) | bm[uchar(*posS)]; cleanChars++; } } haveResults = index->findBit(&context,bitValue,querySeq); } else { haveResults = index->find(&context,querySeq); } if (haveResults) { int pos = -1; while( ( pos = index->nextArrSeqPos(&context) ) != -1 ) { results.append(pos + 1); } } } void SArrayBasedFindTask::runSearchWithMismatches() { const char* querySeq = config->query.constData(); const char* arraySeq = index->getIndexedSequence(); char unknownChar = config->unknownChar; int CMAX = 0; if (config->absMismatches) { CMAX = config->nMismatches; } else { CMAX = (config->query.length() * config->ptMismatches) / MAX_PERCENTAGE; } int W = config->query.size(); int q = W / (CMAX + 1); int prefixSize = index->getPrefixSize(); assert(prefixSize <= q); if (prefixSize > q) { setError( QString("Too large SArrayIndex window (%1) for %2-mismatch search").arg(prefixSize).arg(CMAX) ); return; } for (int i = 0; i < W - prefixSize + 1; ++i) { const char* seq = querySeq + i; SArrayIndex::SAISearchContext context; bool haveResults = false; if (config->useBitMask) { const quint32* bm = config->bitMask; int charBitsNum = config->bitMaskCharBitsNum; quint32 bitValue = 0; int wCharsInMask = index->getCharsInMask(); const char* posS = querySeq; char unknownChar = config->unknownChar; for (int cleanChars = 0; cleanChars < wCharsInMask; posS++) { if (*posS == unknownChar) { cleanChars = 0; bitValue = 0; } else { bitValue = (bitValue << charBitsNum) | bm[uchar(*posS)]; cleanChars++; } } haveResults = index->findBit(&context,bitValue,seq); } else { haveResults = index->find(&context,seq); } if (!haveResults) { continue; } int pos = -1; const char* endS = querySeq + W; const char* endA = arraySeq + index->getSequenceLength(); while( ( pos = index->nextArrSeqPos(&context) ) != -1 ) { int c = 0; // forward collect const char* posS = seq + prefixSize; const char* posA = arraySeq + pos + prefixSize; for ( ; (posS < endS) && (c <= CMAX); posS++, posA++) { if (posA >= endA) { // out of arrraySeq boundaries - > do not need to continue c = CMAX + 1; break; } c += PCHAR_MATCH(posS, posA) ? 0 : 1; } // backward collect posS = seq - 1; posA = arraySeq + pos - 1; for ( ; (posS >= querySeq) && (c <= CMAX); posS--, posA--) { if (posA < arraySeq) { // out of arrraySeq boundaries - > do not need to continue c = CMAX + 1; break; } c += PCHAR_MATCH(posS, posA) ? 0 : 1; } int result = pos - i + 1; if ( (c <= CMAX) && (!results.contains(result))) { results.append(result); if (onlyFirstMatch) { break; } } } } } void SArrayBasedFindTask::cleanup() { delete config; config = NULL; } } // U2 ugene-1.9.8/src/corelibs/U2Algorithm/src/util_algorithm/RollingArray.h0000644000175000017500000001016011651544331024431 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_ROLLING_ARRAY_H_ #define _U2_ROLLING_ARRAY_H_ #include namespace U2 { //todo: not tested! template class RollingArray { public: RollingArray(int maxSize); RollingArray( const T * data, int size ); inline RollingArray() : startRollPos(0), endRollPos(0), maxSize(0){}; inline int getMaxSize() const; inline int size() const; inline void set(int pos, T val); inline T get(int pos) const; inline T& get(int pos); inline void push_back_pop_front(T val); inline void push_front_pop_back(T val); private: inline void push(T val); inline void push_front(T val); inline T pop(); inline T pop_front(); inline int toRollPos(int pos) const; inline int toPos(int rollPos) const; QVector buf; int startRollPos; int endRollPos; int maxSize; }; template inline RollingArray::RollingArray(int ms) { assert(ms > 0); maxSize = ms; buf.resize(maxSize); startRollPos = 0; endRollPos = 0; } template inline RollingArray::RollingArray( const T * data, int size ) : buf(size), startRollPos(0), endRollPos(size-1), maxSize(size) { for (int i = 0; i < buf.size(); ++i) buf[i] = *(data + i); } template inline int RollingArray::getMaxSize() const { return maxSize; } template inline int RollingArray::size() const { int res = toPos(endRollPos); return res + 1; } template void RollingArray::set(int pos, T val) { int rollPos = toRollPos(pos); buf[rollPos] = val; } template T RollingArray::get(int pos) const { int rollPos = toRollPos(pos); return buf[rollPos]; } template T& RollingArray::get(int pos) { int rollPos = toRollPos(pos); return buf[rollPos]; } template void RollingArray::push(T val) { // int pos = size(); // assert(pos < maxSize); endRollPos++; if (endRollPos >= maxSize) { endRollPos = 0; } buf[endRollPos] = val; } template inline void RollingArray::push_front(T val) { --startRollPos; if( startRollPos < 0 ) { startRollPos = maxSize - 1; } buf[startRollPos] = val; } template T RollingArray::pop() { T res = buf[endRollPos]; endRollPos--; if (endRollPos < 0) { endRollPos = maxSize-1; } return res; } template inline T RollingArray::pop_front() { T res = buf[startRollPos]; ++startRollPos; if( startRollPos >= maxSize ) { startRollPos = 0; } return res; } template inline void RollingArray::push_back_pop_front( T val ) { if( size() == getMaxSize() ) { pop_front(); } push( val ); } template inline void RollingArray::push_front_pop_back(T val) { if( size() == getMaxSize() ) { pop(); } push_front(val); } template int RollingArray::toRollPos(int pos) const { assert(pos < size() && pos >= 0); int rollPos = pos + startRollPos; if (rollPos >= maxSize) { rollPos-=maxSize; } return rollPos; } template int RollingArray::toPos(int rollPos) const { int pos = rollPos - startRollPos; if (pos < 0) { pos += maxSize; } return pos; } } //namespace #endif ugene-1.9.8/src/corelibs/U2Algorithm/src/util_algorithm/DynTable.h0000644000175000017500000001206711651544331023536 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_DYN_TABLE_H_ #define _U2_DYN_TABLE_H_ #include "RollingMatrix.h" namespace U2 { struct U2ALGORITHM_EXPORT MatchScores { int match; int mismatch; int ins; int del; }; class U2ALGORITHM_EXPORT DynTable : public RollingMatrix { public: enum FillStrategy { Strategy_Max, Strategy_Min }; DynTable(int n, int m, bool _allowInsDel) : RollingMatrix(n, m), allowInsDel(_allowInsDel) { init(); scores.match = DEFAULT_SCORE_MATCH; scores.ins = DEFAULT_SCORE_INS; scores.del = DEFAULT_SCORE_DEL; scores.mismatch = DEFAULT_SCORE_MISMATCH; strategy = Strategy_Min; } DynTable(): RollingMatrix(0,0), allowInsDel(false) { } DynTable( int n, int m, bool _allowInsDel, MatchScores _scores, FillStrategy _strategy = Strategy_Min ) : RollingMatrix(n, m), allowInsDel(_allowInsDel), scores(_scores), strategy(_strategy) { init(); } int getLast() const { return get_value(n-1, m-1); } int getLastLen() const { return getLen(n-1, m-1); } void match(int y, bool ok) { match( n-1, y, ok ); } virtual int get(int x, int y) const { if (y<0) {return 0;} if (x<0) {return y+1;} return RollingMatrix::get(x, y); } protected: void match( int x, int y, bool ok ) { int d = get_value( x-1, y-1 ); int res = d + (ok ? scores.match : scores.mismatch); if( allowInsDel ) { int u = get_value(x, y-1); int l = get_value(x-1, y); int insdelRes = 0; switch( strategy ) { case Strategy_Min: insdelRes = qMin( l+scores.ins, u+scores.del ); res = qMin( insdelRes, res ); break; default: assert( false ); } } set_pair( x, y, res, ok ); } int getLen(int x, int y) const { if (y == -1) { return 0; } assert(x!=-1); if (!allowInsDel) { return 1 + getLen(x-1, y-1); } int v = get_value(x, y); bool match = get_flag( x, y ); int d = get_value(x-1, y-1); int l = get_value(x-1, y); int u = get_value(x, y-1); if( match && v == d + scores.match ) { return 1 + getLen( x-1, y-1 ); } if ( v == u + scores.del ) { //prefer deletion in X sequence to minimize result len return getLen(x, y-1); } if ( !match && v == d + scores.mismatch ) { // prefer mismatch instead of insertion into X sequence return 1 + getLen(x-1, y-1); } assert( v == l + scores.ins ); Q_UNUSED(l); return 1 + getLen(x-1, y); // this is insertion into X sequence } private: void init() { for (int i=0; i * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_BITS_TABLE_H_ #define _U2_BITS_TABLE_H_ #include namespace U2 { class U2ALGORITHM_EXPORT BitsTable { public: quint32 NUCL_BITS[256]; const static quint32 NUCL_BITS_SIZE; quint32 PROTEIN_BITS[256]; const static quint32 PROTEIN_BITS_SIZE; quint32 RAW_BITS[256]; const static quint32 RAW_BITS_SIZE; BitsTable(); virtual ~BitsTable(){} quint32 getBitMaskCharBitsNum(DNAAlphabetType alType) const; const quint32* getBitMaskCharBits(DNAAlphabetType alType) const; }; } //namespace #endif ugene-1.9.8/src/corelibs/U2Algorithm/src/util_algorithm/ORFFinder.h0000644000175000017500000001146711651544331023615 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_ORFFINDALGORITHM_H_ #define _U2_ORFFINDALGORITHM_H_ #include #include #include namespace U2 { class DNATranslation; class U2ALGORITHM_EXPORT ORFFindResult { public: ORFFindResult () : region(0, 0), frame(0), isJoined(false){} ORFFindResult (const U2Region& _r, int frame) : region(_r), frame(frame), isJoined(false){} ORFFindResult (const U2Region& _r, const U2Region& _r_joined, int frame) :region(_r), joinedRegion(_r_joined), frame(frame), isJoined(true){} void clear() {region.startPos = 0; region.length = 0; frame = 0;} bool isEmpty() const {return region.startPos == 0 && region.length == 0;} bool operator ==(const ORFFindResult& o) const { return region == o.region && frame == o.frame; } SharedAnnotationData toAnnotation(const QString& name) const { SharedAnnotationData data; data = new AnnotationData; data->name = name; data->location->regions << region; if(isJoined){ data->location->regions << joinedRegion; } data->setStrand(frame < 0 ? U2Strand::Complementary : U2Strand::Direct); //data->qualifiers.append(U2Qualifier("frame", QString::number(frame))); data->qualifiers.append(U2Qualifier("dna_len", QString::number(region.length))); if (region.length >= 6) { // 3 bp - end codon data->qualifiers.append(U2Qualifier("protein_len", QString::number(region.length/3))); } return data; } U2Region region; U2Region joinedRegion; bool isJoined; int frame; static QList toTable(const QList& res, const QString& name) { QList list; foreach (const ORFFindResult& f, res) { list.append(f.toAnnotation(name)); } return list; } }; class U2ALGORITHM_EXPORT ORFFindResultsListener { public: virtual ~ORFFindResultsListener(){} virtual void onResult(const ORFFindResult& r) = 0; }; enum ORFAlgorithmStrand { ORFAlgorithmStrand_Both, ORFAlgorithmStrand_Direct, ORFAlgorithmStrand_Complement }; class U2ALGORITHM_EXPORT ORFAlgorithmSettings { public: ORFAlgorithmSettings(ORFAlgorithmStrand strand = ORFAlgorithmStrand_Both, DNATranslation* complementTT = NULL, DNATranslation* proteinTT = NULL, const U2Region& searchRegion = U2Region(), int minLen = 0, bool mustFit = false, bool mustInit = true, bool allowAltStart = false, bool allowOverlap = false, bool circularSearch = false ) : strand(strand), complementTT(complementTT), proteinTT(proteinTT), searchRegion(searchRegion), minLen(minLen), mustFit(mustFit), mustInit(mustInit), allowAltStart(allowAltStart), allowOverlap(allowOverlap), circularSearch(circularSearch) {} ORFAlgorithmStrand strand; DNATranslation* complementTT; DNATranslation* proteinTT; U2Region searchRegion; int minLen; bool mustFit; bool mustInit; bool allowAltStart; bool allowOverlap; bool circularSearch; static const QString ANNOTATION_GROUP_NAME; // strand string ids static const QString STRAND_DIRECT; static const QString STRAND_COMPL; static const QString STRAND_BOTH; static QString getStrandStringId(ORFAlgorithmStrand strand); static ORFAlgorithmStrand getStrandByStringId(const QString& id); }; class U2ALGORITHM_EXPORT ORFFindAlgorithm { public: static void find( ORFFindResultsListener* rl, const ORFAlgorithmSettings& config, const char* sequence, int seqLen, int& stopFlag, int& percentsCompleted); }; }//namespace #endif ugene-1.9.8/src/corelibs/U2Algorithm/src/util_algorithm/BinaryFindOpenCL.h0000644000175000017500000000417511651544331025123 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_BINARYFINDOPENCL_H_ #define _U2_BINARYFINDOPENCL_H_ #include #include #include namespace U2 { typedef cl_long NumberType; class U2ALGORITHM_EXPORT BinaryFindOpenCL { public: BinaryFindOpenCL(const NumberType* _numbers, const int _numbersSize, const NumberType* _findNumbers, const int _findNumbersSize, const NumberType filter = CL_LONG_MAX); ~BinaryFindOpenCL(); NumberType* launch(); bool hasError() {return isError;} private: bool hasOPENCLError(cl_int err, QString errorMessage); void prepareBinarySearch(const NumberType* arr, int lowerBound, int upperBound, NumberType* resBounds, NumberType* resValues, const int depthNum); bool isError; const NumberType* numbers; const int numbersSize; const NumberType* findNumbers; const size_t findNumbersSize; const NumberType filter; cl_event clEvent1; cl_event clEvent2; cl_kernel clKernel; cl_program clProgram; cl_command_queue clCommandQueue; cl_context clContext; cl_mem buf_sortedArray; cl_mem buf_findMeArray; cl_mem buf_outPutArray; cl_mem buf_preSaveBounds; cl_mem buf_preSaveValues; }; }//namespace #endif // _U2_BINARYFINDOPENCL_H_ ugene-1.9.8/src/corelibs/U2Algorithm/src/util_algorithm/EnzymeModel.cpp0000644000175000017500000000156711651544331024622 0ustar ilyailya#include "EnzymeModel.h" namespace U2 { const QString EnzymeSettings::DATA_DIR_KEY("enzymes"); const QString EnzymeSettings::DATA_FILE_KEY("plugin_enzymes/lastFile"); const QString EnzymeSettings::LAST_SELECTION("plugin_enzymes/selection"); const QString EnzymeSettings::ENABLE_HIT_COUNT("plugin_enzymes/enable_hit_count"); const QString EnzymeSettings::MAX_HIT_VALUE("plugin_enzymes/max_hit_value"); const QString EnzymeSettings::MIN_HIT_VALUE("plugin_enzymes/min_hit_value"); const QString EnzymeSettings::NON_CUT_REGION("plugin_enzymes/non_cut_region"); const QString EnzymeSettings::MAX_RESULTS("plugin_enzymes/max_results"); const QString EnzymeSettings::COMMON_ENZYMES( "ClaI,BamHI,BglII,DraI,EcoRI,EcoRV,HindIII,PstI,SalI,SmaI,XmaI"); EnzymeData::EnzymeData() { cutDirect = ENZYME_CUT_UNKNOWN; cutComplement = ENZYME_CUT_UNKNOWN; alphabet = NULL; } } // namespace ugene-1.9.8/src/corelibs/U2Algorithm/src/util_algorithm/FindAlgorithmTask.cpp0000644000175000017500000000432611651544331025740 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "FindAlgorithmTask.h" #include #include #include namespace U2 { FindAlgorithmTask::FindAlgorithmTask(const FindAlgorithmTaskSettings& s) : Task (tr("Find in sequence task"), TaskFlag_None), config(s), currentPos(0) { GCOUNTER(cvar, tvar, "FindAlgorithmTask"); tpm = Progress_Manual; complementRun = false; currentPos = s.searchRegion.startPos; assert(config.strand == FindAlgorithmStrand_Direct || config.complementTT!=NULL); } void FindAlgorithmTask::run() { FindAlgorithm::find(dynamic_cast(this), config.proteinTT, config.complementTT, config.strand, config.insDelAlg, config.useAmbiguousBases, config.sequence.constData(), config.sequence.size(), config.searchRegion, config.pattern.constData(), config.pattern.length(), config.singleShot, config.maxErr, stateInfo.cancelFlag, stateInfo.progress, currentPos); } void FindAlgorithmTask::onResult(const FindAlgorithmResult& r) { lock.lock(); newResults.append(r); lock.unlock(); } QList FindAlgorithmTask::popResults() { lock.lock(); QList res = newResults; newResults.clear(); lock.unlock(); return res; } } //namespace ugene-1.9.8/src/corelibs/U2Algorithm/src/util_algorithm/ORFAlgorithmTask.h0000644000175000017500000000300611651544331025145 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_ORF_ALG_TASK_H_ #define _U2_ORF_ALG_TASK_H_ #include #include #include "ORFFinder.h" #include namespace U2 { class U2ALGORITHM_EXPORT ORFFindTask : public Task, public ORFFindResultsListener { Q_OBJECT public: ORFFindTask(const ORFAlgorithmSettings& s, const QByteArray& seq); virtual void run(); virtual void onResult(const ORFFindResult& r); QList popResults(); const ORFAlgorithmSettings& getSettings() const {return config;} private: ORFAlgorithmSettings config; QList newResults; QMutex lock; QByteArray sequence; }; } //namespace #endif ugene-1.9.8/src/corelibs/U2Algorithm/src/util_cds/0000755000175000017500000000000011651544331020440 5ustar ilyailyaugene-1.9.8/src/corelibs/U2Algorithm/src/util_cds/CDSearchTaskFactory.h0000644000175000017500000000362611651544331024407 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_CDS_TASK_FACTORY_H_ #define _U2_CDS_TASK_FACTORY_H_ #include namespace U2 { class U2ALGORITHM_EXPORT CDDNames { public: static QString CDD_DB() { return "CDD"; } static QString PFAM_DB() { return "Pfam"; } static QString SMART_DB() { return "Smart"; } static QString COG_DB() { return "Cog"; } static QString KOG_DB() { return "Kog"; } static QString PRK_DB() { return "Prk"; } static QString TIGR_DB() { return "Tigr"; } }; class DNAAlphabet; class U2ALGORITHM_EXPORT CDSearchSettings { public: CDSearchSettings() : ev(0.01f), alp(NULL) {} float ev; DNAAlphabet* alp; QByteArray query; QString localDbFolder; QString dbName; }; class Task; class U2ALGORITHM_EXPORT CDSearchResultListener { public: virtual QList getCDSResults() const = 0; virtual Task* getTask() const = 0; }; class U2ALGORITHM_EXPORT CDSearchFactory { public: virtual CDSearchResultListener* createCDSearch(const CDSearchSettings& settings) const = 0; }; } //namespace #endif ugene-1.9.8/src/corelibs/U2Algorithm/src/phyltree/0000755000175000017500000000000011651544331020466 5ustar ilyailyaugene-1.9.8/src/corelibs/U2Algorithm/src/phyltree/CreatePhyTreeSettings.h0000644000175000017500000000261311651544331025066 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_CREATE_PHYTREE_SETTINGS_H #define _U2_CREATE_PHYTREE_SETTINGS_H #include #include #include #include namespace U2{ class U2ALGORITHM_EXPORT CreatePhyTreeSettings{ public: CreatePhyTreeSettings(); QString algorithmId; QString matrixId; GUrl fileUrl; bool useGammaDistributionRates; double alphaFactor; double ttRatio; // transition transversion ratio bool bootstrap; int replicates; int seed; double fraction; QString consensusID; }; } #endif ugene-1.9.8/src/corelibs/U2Algorithm/src/phyltree/PhyTreeGeneratorRegistry.h0000644000175000017500000000320011651544331025612 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef PHYTREEGENERATORREGISTRY_H #define PHYTREEGENERATORREGISTRY_H #include "PhyTreeGenerator.h" namespace U2 { class U2ALGORITHM_EXPORT PhyTreeGeneratorRegistry : public QObject { public: PhyTreeGeneratorRegistry(QObject* pOwn = 0); ~PhyTreeGeneratorRegistry(); bool registerPhyTreeGenerator(PhyTreeGenerator* generator, const QString& gen_id); bool hadRegistered(const QString& surfId); PhyTreeGenerator* getGenerator(const QString& surfId); QStringList getNameList(); private: QMap genMap; // Copy prohibition PhyTreeGeneratorRegistry(const PhyTreeGeneratorRegistry& m); PhyTreeGeneratorRegistry& operator=(const PhyTreeGeneratorRegistry& m); }; } // namespace U2 #endif ugene-1.9.8/src/corelibs/U2Algorithm/src/phyltree/CreatePhyTreeSettings.cpp0000644000175000017500000000204511651544331025420 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "CreatePhyTreeSettings.h" namespace U2{ CreatePhyTreeSettings::CreatePhyTreeSettings() : algorithmId(""), matrixId(""), useGammaDistributionRates(false), bootstrap(false), consensusID("") { } } ugene-1.9.8/src/corelibs/U2Algorithm/src/phyltree/PhyTreeGeneratorRegistry.cpp0000644000175000017500000000362311651544331026156 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include namespace U2 { PhyTreeGeneratorRegistry::PhyTreeGeneratorRegistry( QObject* pOwn /*= 0*/ ) : QObject(pOwn) {} PhyTreeGeneratorRegistry::~PhyTreeGeneratorRegistry() { foreach( PhyTreeGenerator* generator, genMap.values()) { delete generator; } } bool PhyTreeGeneratorRegistry::registerPhyTreeGenerator( PhyTreeGenerator* generator , const QString& gen_id) { if (genMap.contains(gen_id)){ return false; } genMap.insert(gen_id, generator); return true; } bool PhyTreeGeneratorRegistry::hadRegistered( const QString& gen_id) { return genMap.contains(gen_id); } PhyTreeGenerator* PhyTreeGeneratorRegistry::getGenerator(const QString& gen_id) { if (genMap.contains(gen_id)) { return genMap.value(gen_id); } else { return NULL; } } QStringList PhyTreeGeneratorRegistry::getNameList() { return genMap.keys(); } } // namespace U2 ugene-1.9.8/src/corelibs/U2Algorithm/src/phyltree/PhyTreeGeneratorTask.cpp0000644000175000017500000000403211651544331025243 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include #include #include #include #include namespace U2 { PhyTreeGeneratorTask::PhyTreeGeneratorTask(const MAlignment& ma, const CreatePhyTreeSettings& _settings) : Task(tr("Calculating Phylogenetic Tree"), TaskFlags_FOSCOE), inputMA(ma), settings(_settings) { tpm = Task::Progress_Manual; QString algId = settings.algorithmId; PhyTreeGeneratorRegistry* registry = AppContext::getPhyTreeGeneratorRegistry(); generator = registry->getGenerator(algId); assert(generator!=NULL); if (generator == NULL) { stateInfo.setError(tr("Tree construction algorithm %1 not found").arg(algId)); } } void PhyTreeGeneratorTask::run() { if (!hasError()) { calculateTree(); } } void PhyTreeGeneratorTask::calculateTree() { stateInfo.progress = 0; stateInfo.setDescription(tr("Calculating phylogenetic tree")); result = generator->calculatePhyTree(inputMA, settings, stateInfo); stateInfo.progress = 100; } Task::ReportResult PhyTreeGeneratorTask::report() { return ReportResult_Finished; } } //namespace ugene-1.9.8/src/corelibs/U2Algorithm/src/phyltree/PhyTreeGeneratorTask.h0000644000175000017500000000313011651544331024706 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef __PHYTREEGENERATORTASK_H #define __PHYTREEGENERATORTASK_H #include #include "PhyTreeGenerator.h" #include namespace U2{ class U2ALGORITHM_EXPORT PhyTreeGeneratorTask: public Task{ Q_OBJECT public: PhyTreeGeneratorTask(const MAlignment& ma, const CreatePhyTreeSettings& _settings); ~PhyTreeGeneratorTask(){}; void run(); PhyTree getResult() { return result; } const CreatePhyTreeSettings& getSettings() { return settings; } ReportResult report(); private: void calculateTree(); PhyTreeGenerator* generator; const MAlignment& inputMA; PhyTree result; CreatePhyTreeSettings settings; }; } //namespace #endif ugene-1.9.8/src/corelibs/U2Algorithm/src/phyltree/PhyTreeGenerator.h0000644000175000017500000000262111651544331024067 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _PHYTREEGENERATOR #define _PHYTREEGENERATOR #include #include #include #include "CreatePhyTreeSettings.h" #include namespace U2{ class CreatePhyTreeDialogController; class U2ALGORITHM_EXPORT PhyTreeGenerator{ public: virtual PhyTree calculatePhyTree(const MAlignment& ma, const CreatePhyTreeSettings& s, TaskStateInfo& ti) = 0; // TODO create separate class®istry virtual void setupCreatePhyTreeUI(CreatePhyTreeDialogController* c, const MAlignment& ma) = 0; }; } #endif ugene-1.9.8/src/corelibs/U2Algorithm/src/util_repeat_finder/0000755000175000017500000000000011651544331022476 5ustar ilyailyaugene-1.9.8/src/corelibs/U2Algorithm/src/util_repeat_finder/RepeatFinderTaskFactory.h0000644000175000017500000000237411651544331027400 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_REPEAT_FINDER_TASK_FACTORY_H_ #define _U2_REPEAT_FINDER_TASK_FACTORY_H_ #include "RepeatFinderSettings.h" #include namespace U2 { class RepeatFinderTaskFactory { public: virtual Task* getTaskInstance(const RepeatFinderSettings& config) const = 0; virtual ~RepeatFinderTaskFactory() {} virtual void setRFResultsListener(Task*, RFResultsListener*) = 0; }; } // namespace #endif ugene-1.9.8/src/corelibs/U2Algorithm/src/util_repeat_finder/RepeatFinderSettings.h0000644000175000017500000000616111651544331026744 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_REPEAT_FINDER_SETTINGS_H_ #define _U2_REPEAT_FINDER_SETTINGS_H_ #include namespace U2 { class DNAAlphabet; enum RFAlgorithm { RFAlgorithm_Auto, RFAlgorithm_Diagonal, RFAlgorithm_Suffix }; class RFResult { public: RFResult() : x(0), y(0), l(0){} RFResult(int _x, int _y, int _len) : x(_x), y(_y), l(_len){} bool operator==(const RFResult& r) const {return x == r.x && y == r.y && l == r.l;} bool operator!=(const RFResult& r) const {return !(*this == r);} bool operator <(const RFResult& r) const {return (x != r.x) ? x < r.x : (y != r.y) ? y < r.y: (l < r.l);} int x; int y; int l; }; class RFResultsListener { public: virtual void onResult(const RFResult& r) = 0; virtual void onResults(const QVector& v) = 0; }; struct RepeatFinderSettings { RepeatFinderSettings() : l(NULL), seqX(NULL), sizeX(0), inverted(false), seqY(NULL), sizeY(0), al(NULL), w(0), mismatches(0), alg(RFAlgorithm_Auto), nThreads(0) {} RepeatFinderSettings( RFResultsListener* _l, const char *_seqX, int _sizeX, bool _inverted, const char *_seqY, int _sizeY, DNAAlphabet *_al, int _w, int _mismatches, RFAlgorithm _alg, int _nThreads = MAX_PARALLEL_SUBTASKS_AUTO ) : l(_l), seqX(_seqX), sizeX(_sizeX), inverted(_inverted), seqY(_seqY), sizeY(_sizeY), al(_al), w(_w), mismatches(_mismatches), alg(_alg), nThreads(_nThreads) {} RFResultsListener* l; const char * seqX; int sizeX; bool inverted; const char * seqY; int sizeY; DNAAlphabet * al; int w; int mismatches; RFAlgorithm alg; int nThreads; bool operator==(const RepeatFinderSettings& op) const { return l == op.l && seqX == op.seqX && sizeX == op.sizeX && inverted == op.inverted && seqY == op.seqY && sizeY == op.sizeY && al == op.al && w == op.w && mismatches == op.mismatches && alg == op.alg && nThreads == op.nThreads; } }; } // namespace #endif ugene-1.9.8/src/corelibs/U2Algorithm/src/smith_waterman/0000755000175000017500000000000011651544331021654 5ustar ilyailyaugene-1.9.8/src/corelibs/U2Algorithm/src/smith_waterman/SmithWatermanReportCallback.h0000644000175000017500000000405611651544331027426 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_SMITH_WATERMAN_REPORT_CALLBACK_H_ #define _U2_SMITH_WATERMAN_REPORT_CALLBACK_H_ #include #include #include namespace U2 { class U2ALGORITHM_EXPORT SmithWatermanReportCallback { public: virtual QString report(const QList& ) { return QString(); } virtual ~SmithWatermanReportCallback() {} }; class U2ALGORITHM_EXPORT SmithWatermanReportCallbackImpl: public QObject, public SmithWatermanReportCallback { Q_OBJECT public: SmithWatermanReportCallbackImpl(AnnotationTableObject* _aobj, const QString& _annotationName, const QString& _annotationGroup, QObject* pOwn = 0); virtual QString report(const QList& result); const QList& getAnotations() const {return anns;} private: QString annotationName; QString annotationGroup; QPointer aObj; QList anns; bool autoReport; }; } // namespace #endif ugene-1.9.8/src/corelibs/U2Algorithm/src/smith_waterman/SmithWatermanResult.h0000644000175000017500000000437311651544331026016 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_SMITH_WATERMAN_RESULT_H_ #define _U2_SMITH_WATERMAN_RESULT_H_ #include #include #include namespace U2 { struct U2ALGORITHM_EXPORT SmithWatermanResult { SharedAnnotationData toAnnotation(const QString& name) const { SharedAnnotationData data; data = new AnnotationData; data->name = name; data->location->regions << region; data->setStrand(strand); data->qualifiers.append(U2Qualifier("score", QString::number(score))); return data; } bool operator<(const SmithWatermanResult& op1) const { if (score < op1.score) { return true; } else { return false; } } U2Strand strand; bool trans; float score; U2Region region; }; class U2ALGORITHM_EXPORT SmithWatermanResultListener { public: virtual void pushResult(const SmithWatermanResult& r) { result.append(r); } virtual void pushResult( const QList& r ) { result.append( r ); } virtual QList popResults() { QList res = result; result.clear(); return res; } virtual QList getResults() const { return result; } virtual ~SmithWatermanResultListener() {} private: QList result; }; } // namespace #endif ugene-1.9.8/src/corelibs/U2Algorithm/src/smith_waterman/SmithWatermanTaskFactoryRegistry.h0000644000175000017500000000317611651544331030523 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_SMITH_WATERMAN_ALG_REGISTRY_H_ #define _U2_SMITH_WATERMAN_ALG_REGISTRY_H_ #include #include #include #include #include #include namespace U2 { class U2ALGORITHM_EXPORT SmithWatermanTaskFactoryRegistry: public QObject { Q_OBJECT public: SmithWatermanTaskFactoryRegistry(QObject* pOwn = 0); ~SmithWatermanTaskFactoryRegistry(); bool registerFactory(SmithWatermanTaskFactory* factory, const QString& factoryId); bool hadRegistered(const QString& factoryId); SmithWatermanTaskFactory* getFactory(const QString& factoryId); QStringList getListFactoryNames(); private: QMutex mutex; QHash factories; }; } // namespace #endif ugene-1.9.8/src/corelibs/U2Algorithm/src/smith_waterman/SmithWatermanUtil.h0000644000175000017500000000370311651544331025451 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_SMITH_WATERMAN_UTIL_H_ #define _U2_SMITH_WATERMAN_UTIL_H_ #include "SmithWatermanResult.h" namespace U2 { class SMatrix; class U2ALGORITHM_EXPORT SmithWatermanUtil { public: static float calcScoreItSelf(const SMatrix& m, const char* pattern, int patternLen); static int calcWindowLen(bool transl, int sequenceLen, int patternLen, float scoreItSelf, float thresholdScore, float scoreGapOpen, float scoreGapExtd); static float calcScoreThreshold(float percent, float scoreItSelf); static int calcOverlapSize(bool transl, int windowLen, float scoreItSelf, float scoreGapOpen, float scoreGapExtd); static bool removeIdenticalResults(QList* lst); }; } //namespace #endif ugene-1.9.8/src/corelibs/U2Algorithm/src/smith_waterman/SmithWatermanTaskFactoryRegistry.cpp0000644000175000017500000000372511651544331031056 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "SmithWatermanTaskFactoryRegistry.h" #include #include namespace U2 { SmithWatermanTaskFactoryRegistry::SmithWatermanTaskFactoryRegistry(QObject* pOwn): QObject(pOwn) { } SmithWatermanTaskFactoryRegistry::~SmithWatermanTaskFactoryRegistry() { foreach (const SmithWatermanTaskFactory* factory, factories) { delete factory; } } bool SmithWatermanTaskFactoryRegistry::registerFactory( SmithWatermanTaskFactory* factory, const QString& factoryId) { QMutexLocker locker(&mutex); if (factories.contains(factoryId)) { return false; } factories[factoryId] = factory; return true; } SmithWatermanTaskFactory* SmithWatermanTaskFactoryRegistry::getFactory(const QString& factoryId) { return factories.value(factoryId, 0); } QStringList SmithWatermanTaskFactoryRegistry::getListFactoryNames() { return factories.keys(); } bool SmithWatermanTaskFactoryRegistry::hadRegistered(const QString& factoryId) { return factories.contains(factoryId); } } // namespace ugene-1.9.8/src/corelibs/U2Algorithm/src/smith_waterman/SWResultFilterRegistry.cpp0000644000175000017500000000371611651544331027016 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "SWResultFilterRegistry.h" #include namespace U2 { SWResultFilterRegistry::SWResultFilterRegistry(QObject* pOwn): QObject(pOwn) { registerFilter(new SWRF_EmptyFilter()); SmithWatermanResultFilter* f = new SWRF_WithoutIntersect(); registerFilter(f); defaultFilterId = f->getId(); } SWResultFilterRegistry::~SWResultFilterRegistry() { QList swFilters = filters.values(); foreach (SmithWatermanResultFilter* swFilter, swFilters) { delete swFilter; } } QStringList SWResultFilterRegistry::getFiltersIds() const { return filters.keys(); } SmithWatermanResultFilter* SWResultFilterRegistry::getFilter(const QString& id) { return filters.value(id, 0); } bool SWResultFilterRegistry::isRegistered(const QString& id) const { return filters.contains(id); } bool SWResultFilterRegistry::registerFilter( SmithWatermanResultFilter* filter ) { QMutexLocker locker(&mutex); QString id = filter->getId(); if (filters.contains(id)) { return false; } filters[id] = filter; return true; } } // namespace ugene-1.9.8/src/corelibs/U2Algorithm/src/smith_waterman/SmithWatermanUtil.cpp0000644000175000017500000000662611651544331026013 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "SmithWatermanUtil.h" #include namespace U2 { float SmithWatermanUtil::calcScoreItSelf(const SMatrix& m, const char* pattern, int patternLen) { float score = 0.0F; for (int i = 0; i < patternLen; i++) { score += m.getScore(pattern[i], pattern[i]); } return score; } int SmithWatermanUtil::calcWindowLen(bool transl, int sequenceLen, int patternLen, float scoreItSelf, float thresholdScore, float scoreGapOpen, float scoreGapExtd) { int tail = (thresholdScore - scoreItSelf + scoreGapOpen) / scoreGapExtd; tail = qMax(tail, 0); int windowLen = qMin(patternLen + tail, sequenceLen); if (transl) { windowLen *= 3; } return windowLen; } float SmithWatermanUtil::calcScoreThreshold(float percent, float scoreItSelf) { if (percent < 0 || 100 < percent) { percent = 100; } float factor = (percent / 100.0F); return factor * scoreItSelf; } int SmithWatermanUtil::calcOverlapSize(bool transl, int windowLen, float scoreItSelf, float scoreGapOpen, float scoreGapExtd) { int dependSize = (scoreGapOpen - scoreItSelf) / scoreGapExtd; if (transl) { dependSize *= 3; } return qMax(windowLen, dependSize); } //greater score goes first static bool revScoreComparator(const SmithWatermanResult &s0, const SmithWatermanResult &s1) { bool res = false; if (s0.score < s1.score) { res = false; } else if (s0.score == s1.score) { const U2Region& r0 = s0.region; const U2Region& r1 = s1.region; res = r0 < r1; } else { res = true; } return res; } bool SmithWatermanUtil::removeIdenticalResults(QList* lst) { QList& results = *lst; qSort(results.begin(), results.end(), revScoreComparator); int i = 0; int size = results.size(); while (i < size) { int j = i + 1; while (j < size) { const SmithWatermanResult& currItem = results[i]; const SmithWatermanResult& someItem = results[j]; if (currItem.region == someItem.region && currItem.strand == someItem.strand) { results.removeAt(j); size--; continue; } j++; } i++; } return true; } } // namespace ugene-1.9.8/src/corelibs/U2Algorithm/src/smith_waterman/SmithWatermanResult.cpp0000644000175000017500000000162711651544331026350 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "SmithWatermanResult.h" namespace U2 { } // namespace ugene-1.9.8/src/corelibs/U2Algorithm/src/smith_waterman/SmithWatermanResultFilters.cpp0000644000175000017500000000651011651544331027675 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "SmithWatermanResultFilters.h" #include namespace U2 { /*************************************** * SWRF_EmptyFilter ***************************************/ const QString SWRF_EmptyFilter::ID = "none"; // Without any filtering bool SWRF_EmptyFilter::applyFilter(QList* /*lst*/) { return true; } SmithWatermanResultFilter* SWRF_EmptyFilter::clone() const { return new SWRF_EmptyFilter(*this); } bool SWRF_EmptyFilter::needErase( const SmithWatermanResult& /*currItem*/, const SmithWatermanResult& /*someItem*/) const { return false; } QString SWRF_EmptyFilter::getId() const { return ID; } /*************************************** * SWRF_WithoutIntersect ***************************************/ const QString SWRF_WithoutIntersect::ID = "filter-intersections"; //greater score goes first static bool revScoreComparator(const SmithWatermanResult &s0, const SmithWatermanResult &s1) { bool res = false; if (s0.score < s1.score) { res = false; } else if (s0.score == s1.score) { U2Region r0 = s0.region; U2Region r1 = s1.region; res = r0 < r1; } else { res = true; } return res; } // Filtering all intersects result bool SWRF_WithoutIntersect::applyFilter(QList* lst) { QList& results = *lst; qSort(results.begin(), results.end(), revScoreComparator); int i = 0; int size = results.size(); while (i < size) { int j = i + 1; while (j < size) { const SmithWatermanResult& currItem = results[i]; const SmithWatermanResult& someItem = results[j]; if (needErase(currItem, someItem)) { results.removeAt(j); size--; continue; } j++; } i++; } return true; } SmithWatermanResultFilter* SWRF_WithoutIntersect::clone() const { return new SWRF_WithoutIntersect(*this); } bool SWRF_WithoutIntersect::needErase( const SmithWatermanResult& currItem, const SmithWatermanResult& someItem) const { U2Region currRegion = currItem.region; U2Region someRegion = someItem.region; if (currRegion.intersects(someRegion) && currItem.strand == someItem.strand) { return true; } return false; } QString SWRF_WithoutIntersect::getId() const { return ID; } } // namesapce U2 ugene-1.9.8/src/corelibs/U2Algorithm/src/smith_waterman/SmithWatermanResultFilters.h0000644000175000017500000000423411651544331027343 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_SMITH_WATERMAN_RESULT_FILTERS_H_ #define _U2_SMITH_WATERMAN_RESULT_FILTERS_H_ #include #include #include namespace U2 { class U2ALGORITHM_EXPORT SmithWatermanResultFilter { public: virtual bool applyFilter(QList* lst) = 0; virtual SmithWatermanResultFilter* clone() const = 0; virtual ~SmithWatermanResultFilter() {}; virtual QString getId() const = 0; }; class U2ALGORITHM_EXPORT SWRF_EmptyFilter: public SmithWatermanResultFilter { private: static const QString ID; public: virtual bool applyFilter(QList* lst); virtual SmithWatermanResultFilter* clone() const; virtual QString getId() const; private: bool needErase(const SmithWatermanResult& currItem, const SmithWatermanResult& someItem) const; }; class U2ALGORITHM_EXPORT SWRF_WithoutIntersect: public SmithWatermanResultFilter { private: static const QString ID; public: virtual bool applyFilter(QList* lst); virtual SmithWatermanResultFilter* clone() const; virtual QString getId() const; private: bool needErase(const SmithWatermanResult& currItem, const SmithWatermanResult& someItem) const; }; } // namesapce #endif ugene-1.9.8/src/corelibs/U2Algorithm/src/smith_waterman/SWResultFilterRegistry.h0000644000175000017500000000320411651544331026453 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_SW_RESULT_FILTER_REGISTRY_H_ #define _U2_SW_RESULT_FILTER_REGISTRY_H_ #include #include #include namespace U2 { class U2ALGORITHM_EXPORT SWResultFilterRegistry: public QObject { Q_OBJECT public: SWResultFilterRegistry(QObject* pOwn = 0); ~SWResultFilterRegistry(); QStringList getFiltersIds() const; SmithWatermanResultFilter* getFilter(const QString& id); bool isRegistered(const QString& id) const; bool registerFilter( SmithWatermanResultFilter* filter ); const QString& getDefaultFilterId() {return defaultFilterId;} private: QMutex mutex; QHash filters; QString defaultFilterId; }; } // namespace #endif ugene-1.9.8/src/corelibs/U2Algorithm/src/smith_waterman/SmithWatermanTaskFactory.h0000644000175000017500000000253711651544331026772 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_SMITH_WATERMAN_TASK_FACTORY_H_ #define _U2_SMITH_WATERMAN_TASK_FACTORY_H_ #include "SmithWatermanSettings.h" #include namespace U2 { class SmithWatermanTaskFactory { public: virtual Task* getTaskInstance(const SmithWatermanSettings& config, const QString& taskName) const = 0; virtual bool hasAdvancedSettings() const { return false; } virtual void execAdvancedDialog() {} virtual ~SmithWatermanTaskFactory() {} }; } // namespace #endif ugene-1.9.8/src/corelibs/U2Algorithm/src/smith_waterman/SmithWatermanSettings.h0000644000175000017500000000517211651544331026336 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_SMITH_WATERMAN_SETTINGS_H_ #define _U2_SMITH_WATERMAN_SETTINGS_H_ #include #include #include #include #include #include #include #include namespace U2 { static inline bool isComplement(StrandOption strand) { return StrandOption_Both== strand || StrandOption_ComplementOnly == strand; } static inline bool isDirect(StrandOption strand) { return StrandOption_Both== strand || StrandOption_DirectOnly == strand; } struct GapModel { float scoreGapOpen; float scoreGapExtd; }; struct SmithWatermanSettings { SmithWatermanSettings() : percentOfScore(0), complTT( NULL ), aminoTT( NULL ), resultListener( NULL ), resultFilter( NULL ), resultCallback( NULL ) { } QByteArray ptrn; QByteArray sqnc; U2Region globalRegion; StrandOption strand; float percentOfScore; GapModel gapModel; SMatrix pSm; DNATranslation* complTT; DNATranslation* aminoTT; SmithWatermanResultListener* resultListener; SmithWatermanResultFilter* resultFilter; SmithWatermanReportCallback* resultCallback; bool operator==(const SmithWatermanSettings& op) const { return ptrn == op.ptrn && sqnc == op.sqnc && globalRegion == op.globalRegion && strand == op.strand && gapModel.scoreGapExtd == op.gapModel.scoreGapExtd && gapModel.scoreGapOpen == op.gapModel.scoreGapOpen; } }; } // namespace #endif ugene-1.9.8/src/corelibs/U2Algorithm/src/smith_waterman/SmithWatermanReportCallback.cpp0000644000175000017500000000402011651544331027750 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "SmithWatermanReportCallback.h" namespace U2 { SmithWatermanReportCallbackImpl::SmithWatermanReportCallbackImpl( AnnotationTableObject* _aobj, const QString& _annotationName, const QString& _annotationGroup, QObject* pOwn): QObject(pOwn), annotationName(_annotationName), annotationGroup(_annotationGroup), aObj(_aobj), autoReport(_aobj != NULL) { } QString SmithWatermanReportCallbackImpl::report(const QList& results) { if (autoReport && aObj.isNull()) { return tr("Annotation object not found."); } if (autoReport && aObj->isStateLocked()) { return tr("Annotation table is read-only"); } foreach (const SmithWatermanResult& res , results) { anns.append(res.toAnnotation(annotationName)); } if (autoReport) { QList annotations; foreach(const SharedAnnotationData& ad, anns) { annotations.append(new Annotation(ad)); } aObj->addAnnotations(annotations, annotationGroup); } return QString(); } } // namespace ugene-1.9.8/src/corelibs/U2Algorithm/src/util_weight_matrix/0000755000175000017500000000000011651544331022542 5ustar ilyailyaugene-1.9.8/src/corelibs/U2Algorithm/src/util_weight_matrix/PWMConversionAlgorithm.cpp0000644000175000017500000000223411651544331027627 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "PWMConversionAlgorithm.h" namespace U2 { PWMConversionAlgorithmFactory::PWMConversionAlgorithmFactory(const QString& algoId, QObject* p): QObject(p), algorithmId(algoId) { } PWMConversionAlgorithm::PWMConversionAlgorithm(PWMConversionAlgorithmFactory* _factory, QObject* p) : QObject(p), factory(_factory) { } }ugene-1.9.8/src/corelibs/U2Algorithm/src/util_weight_matrix/PWMConversionAlgorithmBVH.cpp0000644000175000017500000000466311651544331030177 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "PWMConversionAlgorithmBVH.h" #include namespace U2 { PWMConversionAlgorithmFactoryBVH::PWMConversionAlgorithmFactoryBVH(QObject* p) : PWMConversionAlgorithmFactory(BuiltInPWMConversionAlgorithms::BVH_ALGO, p) { } PWMConversionAlgorithm* PWMConversionAlgorithmFactoryBVH::createAlgorithm(QObject* p){ return new PWMConversionAlgorithmBVH(this, p); } QString PWMConversionAlgorithmFactoryBVH::getName() const { return "Berg and von Hippel"; } QString PWMConversionAlgorithmFactoryBVH::getDescription() const { return tr("Berg and von Hippel weight function"); } PWMatrix PWMConversionAlgorithmBVH::convert(const PFMatrix& matrix) { int size = (matrix.getType() == PFM_MONONUCLEOTIDE) ? 4 : 16; int length = matrix.getLength(); QVarLengthArray best(length); qMemSet(best.data(), 0, length*sizeof(int)); for (int i = 0; i < size; i++) { for (int j = 0; j < length; j++) { if (best[j] < matrix.getValue(i, j)) { best[j] = matrix.getValue(i, j); } } } QVarLengthArray res(size*length); for (int i = 0; i < size; i++) { for (int j = 0; j < length; j++) { res[matrix.index(i, j)] = log((matrix.getValue(i, j) + 0.5) / (best[j] + 0.5)); } } PWMatrix w(res, (matrix.getType() == PFM_MONONUCLEOTIDE) ? PWM_MONONUCLEOTIDE : PWM_DINUCLEOTIDE); w.setInfo(UniprobeInfo(matrix.getProperties())); return w; } PWMConversionAlgorithmBVH::PWMConversionAlgorithmBVH(PWMConversionAlgorithmFactory* factory, QObject* p) : PWMConversionAlgorithm(factory, p) { } }ugene-1.9.8/src/corelibs/U2Algorithm/src/util_weight_matrix/PWMConversionAlgorithmLOD.h0000644000175000017500000000332411651544331027634 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_PWM_CONVERSION_ALGORITHM_LOD_H_ #define _U2_PWM_CONVERSION_ALGORITHM_LOD_H_ #include #include #include #include "PWMConversionAlgorithm.h" #include "BuiltInPWMConversionAlgorithms.h" namespace U2 { class U2ALGORITHM_EXPORT PWMConversionAlgorithmFactoryLOD : public PWMConversionAlgorithmFactory { Q_OBJECT public: PWMConversionAlgorithmFactoryLOD(QObject* p = NULL); virtual PWMConversionAlgorithm* createAlgorithm(QObject* parent); virtual QString getDescription() const; virtual QString getName() const; }; class U2ALGORITHM_EXPORT PWMConversionAlgorithmLOD : public PWMConversionAlgorithm { Q_OBJECT public: PWMConversionAlgorithmLOD(PWMConversionAlgorithmFactory* factory, QObject* p = NULL); virtual PWMatrix convert(const PFMatrix& matrix); }; }//namespace #endif ugene-1.9.8/src/corelibs/U2Algorithm/src/util_weight_matrix/PWMConversionAlgorithmLOD.cpp0000644000175000017500000000527611651544331030177 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "PWMConversionAlgorithmLOD.h" #include #include namespace U2 { PWMConversionAlgorithmFactoryLOD::PWMConversionAlgorithmFactoryLOD(QObject* p) : PWMConversionAlgorithmFactory(BuiltInPWMConversionAlgorithms::LOD_ALGO, p) { } PWMConversionAlgorithm* PWMConversionAlgorithmFactoryLOD::createAlgorithm(QObject* p){ return new PWMConversionAlgorithmLOD(this, p); } QString PWMConversionAlgorithmFactoryLOD::getName() const { return tr("log-odds"); } QString PWMConversionAlgorithmFactoryLOD::getDescription() const { return tr("log-odds weight function"); } PWMatrix PWMConversionAlgorithmLOD::convert(const PFMatrix& matrix) { int size = (matrix.getType() == PFM_MONONUCLEOTIDE) ? 4 : 16; int length = matrix.getLength(); float bj = 1.0 / size; int sum[16]; qMemSet(sum, 0, size*sizeof(int)); int all_hits = 0; for (int i = 0; i < size; i++) { for (int j = 0; j < length; j++) { sum[i] += matrix.getValue(i, j); all_hits += matrix.getValue(i, j); } } if (all_hits <= 0) { return PWMatrix(); } float p[16]; for (int i = 0; i < size; i++) { p[i] = sum[i]; p[i] /= all_hits; if (qAbs(p[i]) <= 1e-9) { return PWMatrix(); } } QVarLengthArray res(size*length); int N = all_hits / length; for (int i = 0; i < size; i++) { for (int j = 0; j < length; j++) { res[matrix.index(i, j)] = log(((matrix.getValue(i, j) + bj) / (N + 1)) / p[i]); } } PWMatrix w(res, (matrix.getType() == PFM_MONONUCLEOTIDE) ? PWM_MONONUCLEOTIDE : PWM_DINUCLEOTIDE); w.setInfo(UniprobeInfo(matrix.getProperties())); return w; } PWMConversionAlgorithmLOD::PWMConversionAlgorithmLOD(PWMConversionAlgorithmFactory* factory, QObject* p) : PWMConversionAlgorithm(factory, p) { } } ugene-1.9.8/src/corelibs/U2Algorithm/src/util_weight_matrix/BuiltInPWMConversionAlgorithms.cpp0000644000175000017500000000226411651544331031304 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "BuiltInPWMConversionAlgorithms.h" namespace U2 { const QString BuiltInPWMConversionAlgorithms::BVH_ALGO("Berg and von Hippel"); const QString BuiltInPWMConversionAlgorithms::LOD_ALGO("Log-odds"); const QString BuiltInPWMConversionAlgorithms::MCH_ALGO("Match"); const QString BuiltInPWMConversionAlgorithms::NLG_ALGO("NLG"); }//namespace ugene-1.9.8/src/corelibs/U2Algorithm/src/util_weight_matrix/PWMConversionAlgorithm.h0000644000175000017500000000352711651544331027302 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_PWM_CONVERSION_ALGORITHM_H_ #define _U2_PWM_CONVERSION_ALGORITHM_H_ #include #include #include namespace U2 { class PWMConversionAlgorithm; class U2ALGORITHM_EXPORT PWMConversionAlgorithmFactory : public QObject { Q_OBJECT public: PWMConversionAlgorithmFactory(const QString& algoId, QObject* p = NULL); virtual PWMConversionAlgorithm* createAlgorithm(QObject* parent = NULL) = 0; QString getId() const {return algorithmId;} virtual QString getDescription() const = 0; virtual QString getName() const = 0; private: QString algorithmId; }; class U2ALGORITHM_EXPORT PWMConversionAlgorithm : public QObject { Q_OBJECT public: PWMConversionAlgorithm(PWMConversionAlgorithmFactory* factory, QObject* p = NULL); virtual PWMatrix convert (const PFMatrix& matrix) = 0; QString getId() const {return factory->getId();} private: PWMConversionAlgorithmFactory* factory; }; }//namespace #endif ugene-1.9.8/src/corelibs/U2Algorithm/src/util_weight_matrix/PWMConversionAlgorithmNLG.cpp0000644000175000017500000000513711651544331030175 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "PWMConversionAlgorithmNLG.h" #include namespace U2 { PWMConversionAlgorithmFactoryNLG::PWMConversionAlgorithmFactoryNLG(QObject* p) : PWMConversionAlgorithmFactory(BuiltInPWMConversionAlgorithms::NLG_ALGO, p) { } PWMConversionAlgorithm* PWMConversionAlgorithmFactoryNLG::createAlgorithm(QObject* p){ return new PWMConversionAlgorithmNLG(this, p); } QString PWMConversionAlgorithmFactoryNLG::getName() const { return tr("NLG"); } QString PWMConversionAlgorithmFactoryNLG::getDescription() const { return tr("NLG weight function"); } PWMatrix PWMConversionAlgorithmNLG::convert(const PFMatrix& matrix) { int size = (matrix.getType() == PFM_MONONUCLEOTIDE) ? 4 : 16; int sum[16]; qMemSet(sum, 0, size*sizeof(int)); int all_hits = 0; for (int i = 0; i < size; i++) { for (int j = 0, n = matrix.getLength(); j < n; j++) { sum[i] += matrix.getValue(i, j); all_hits += matrix.getValue(i, j); } } if (all_hits <= 0) { return PWMatrix(); } float p[16]; for (int i = 0; i < size; i++) { p[i] = sum[i]; p[i] /= all_hits; if (qAbs(p[i]) <= 1e-9) { return PWMatrix(); } } QVarLengthArray res(size*matrix.getLength()); for (int i = 0; i < size; i++) { for (int j = 0, n = matrix.getLength(); j < n; j++) { res[matrix.index(i, j)] = -matrix.getValue(i, j)*log(p[i]); } } PWMatrix w(res, (matrix.getType() == PFM_MONONUCLEOTIDE) ? PWM_MONONUCLEOTIDE : PWM_DINUCLEOTIDE); w.setInfo(UniprobeInfo(matrix.getProperties())); return w; } PWMConversionAlgorithmNLG::PWMConversionAlgorithmNLG(PWMConversionAlgorithmFactory* factory, QObject* p) : PWMConversionAlgorithm(factory, p) { } } ugene-1.9.8/src/corelibs/U2Algorithm/src/util_weight_matrix/BuiltInPWMConversionAlgorithms.h0000644000175000017500000000235111651544331030746 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_BUILT_IN_PWM_CONVERSION_ALGORITHMS_H_ #define _U2_BUILT_IN_PWM_CONVERSION_ALGORITHMS_H_ #include #include namespace U2 { class U2ALGORITHM_EXPORT BuiltInPWMConversionAlgorithms { public: static const QString BVH_ALGO; static const QString LOD_ALGO; static const QString MCH_ALGO; static const QString NLG_ALGO; }; }//namespace #endif ugene-1.9.8/src/corelibs/U2Algorithm/src/util_weight_matrix/PWMConversionAlgorithmBVH.h0000644000175000017500000000332511651544331027636 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_PWM_CONVERSION_ALGORITHM_BVH_H_ #define _U2_PWM_CONVERSION_ALGORITHM_BVH_H_ #include #include #include #include "PWMConversionAlgorithm.h" #include "BuiltInPWMConversionAlgorithms.h" namespace U2 { class U2ALGORITHM_EXPORT PWMConversionAlgorithmFactoryBVH : public PWMConversionAlgorithmFactory { Q_OBJECT public: PWMConversionAlgorithmFactoryBVH(QObject* p = NULL); virtual PWMConversionAlgorithm* createAlgorithm(QObject* parent); virtual QString getDescription() const; virtual QString getName() const; }; class U2ALGORITHM_EXPORT PWMConversionAlgorithmBVH : public PWMConversionAlgorithm { Q_OBJECT public: PWMConversionAlgorithmBVH(PWMConversionAlgorithmFactory* factory, QObject* p = NULL); virtual PWMatrix convert(const PFMatrix& matrix); }; }//namespace #endif ugene-1.9.8/src/corelibs/U2Algorithm/src/util_weight_matrix/PWMConversionAlgorithmMCH.cpp0000644000175000017500000000527011651544331030162 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "PWMConversionAlgorithmMCH.h" #include namespace U2 { PWMConversionAlgorithmFactoryMCH::PWMConversionAlgorithmFactoryMCH(QObject* p) : PWMConversionAlgorithmFactory(BuiltInPWMConversionAlgorithms::MCH_ALGO, p) { } PWMConversionAlgorithm* PWMConversionAlgorithmFactoryMCH::createAlgorithm(QObject* p){ return new PWMConversionAlgorithmMCH(this, p); } QString PWMConversionAlgorithmFactoryMCH::getName() const { return tr("Match"); } QString PWMConversionAlgorithmFactoryMCH::getDescription() const { return tr("Match weight function"); } PWMatrix PWMConversionAlgorithmMCH::convert(const PFMatrix& matrix) { int size = (matrix.getType() == PFM_MONONUCLEOTIDE) ? 4 : 16; int all_hits = 0; if (matrix.getLength() <= 0) { return PWMatrix(); } for (int i = 0; i < size; i++) { for (int j = 0, n = matrix.getLength(); j < n; j++) { all_hits += matrix.getValue(i, j); } } if (all_hits <= 0) { return PWMatrix(); } QVarLengthArray res(size * matrix.getLength()); int N = all_hits / matrix.getLength(); for (int j = 0, n = matrix.getLength(); j < n; j++) { float coef = 0; for (int i = 0; i < size; i++) { if (matrix.getValue(i, j) <= 0) { return PWMatrix(); } coef += matrix.getValue(i, j) * log((float)size * matrix.getValue(i, j) / N); } for (int i = 0; i < size; i++) { res[matrix.index(i, j)] = matrix.getValue(i, j) * coef; } } PWMatrix w(res, (matrix.getType() == PFM_MONONUCLEOTIDE) ? PWM_MONONUCLEOTIDE : PWM_DINUCLEOTIDE); w.setInfo(UniprobeInfo(matrix.getProperties())); return w; } PWMConversionAlgorithmMCH::PWMConversionAlgorithmMCH(PWMConversionAlgorithmFactory* factory, QObject* p) : PWMConversionAlgorithm(factory, p) { } } ugene-1.9.8/src/corelibs/U2Algorithm/src/util_weight_matrix/PWMConversionAlgorithmNLG.h0000644000175000017500000000332411651544331027636 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_PWM_CONVERSION_ALGORITHM_NLG_H_ #define _U2_PWM_CONVERSION_ALGORITHM_NLG_H_ #include #include #include #include "PWMConversionAlgorithm.h" #include "BuiltInPWMConversionAlgorithms.h" namespace U2 { class U2ALGORITHM_EXPORT PWMConversionAlgorithmFactoryNLG : public PWMConversionAlgorithmFactory { Q_OBJECT public: PWMConversionAlgorithmFactoryNLG(QObject* p = NULL); virtual PWMConversionAlgorithm* createAlgorithm(QObject* parent); virtual QString getDescription() const; virtual QString getName() const; }; class U2ALGORITHM_EXPORT PWMConversionAlgorithmNLG : public PWMConversionAlgorithm { Q_OBJECT public: PWMConversionAlgorithmNLG(PWMConversionAlgorithmFactory* factory, QObject* p = NULL); virtual PWMatrix convert(const PFMatrix& matrix); }; }//namespace #endif ugene-1.9.8/src/corelibs/U2Algorithm/src/util_weight_matrix/PWMConversionAlgorithmMCH.h0000644000175000017500000000332411651544331027625 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_PWM_CONVERSION_ALGORITHM_MCH_H_ #define _U2_PWM_CONVERSION_ALGORITHM_MCH_H_ #include #include #include #include "PWMConversionAlgorithm.h" #include "BuiltInPWMConversionAlgorithms.h" namespace U2 { class U2ALGORITHM_EXPORT PWMConversionAlgorithmFactoryMCH : public PWMConversionAlgorithmFactory { Q_OBJECT public: PWMConversionAlgorithmFactoryMCH(QObject* p = NULL); virtual PWMConversionAlgorithm* createAlgorithm(QObject* parent); virtual QString getDescription() const; virtual QString getName() const; }; class U2ALGORITHM_EXPORT PWMConversionAlgorithmMCH : public PWMConversionAlgorithm { Q_OBJECT public: PWMConversionAlgorithmMCH(PWMConversionAlgorithmFactory* factory, QObject* p = NULL); virtual PWMatrix convert(const PFMatrix& matrix); }; }//namespace #endif ugene-1.9.8/src/corelibs/U2Algorithm/src/util_weight_matrix/PWMConversionAlgorithmRegistry.cpp0000644000175000017500000000452411651544331031364 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "PWMConversionAlgorithmRegistry.h" #include "PWMConversionAlgorithmBVH.h" #include "PWMConversionAlgorithmLOD.h" #include "PWMConversionAlgorithmMCH.h" #include "PWMConversionAlgorithmNLG.h" namespace U2 { PWMConversionAlgorithmRegistry::PWMConversionAlgorithmRegistry(QObject* p) : QObject(p) { addAlgorithm(new PWMConversionAlgorithmFactoryBVH()); addAlgorithm(new PWMConversionAlgorithmFactoryLOD()); addAlgorithm(new PWMConversionAlgorithmFactoryMCH()); addAlgorithm(new PWMConversionAlgorithmFactoryNLG()); } PWMConversionAlgorithmRegistry::~PWMConversionAlgorithmRegistry() { QList list = algorithms.values(); foreach(PWMConversionAlgorithmFactory* algo, list) { delete algo; } } PWMConversionAlgorithmFactory* PWMConversionAlgorithmRegistry::getAlgorithmFactory(const QString& algoId) { return algorithms.value(algoId); } void PWMConversionAlgorithmRegistry::addAlgorithm(PWMConversionAlgorithmFactory* algo) { const QString& id = algo->getId(); PWMConversionAlgorithmFactory* oldVersion = algorithms.value(id); if (oldVersion!=NULL) { delete oldVersion; oldVersion = NULL; } algorithms[id] = algo; } QStringList PWMConversionAlgorithmRegistry::getAlgorithmIds() const { QList list = algorithms.values(); QStringList result; foreach(PWMConversionAlgorithmFactory* algo, list) { result.append(algo->getId()); } return result; } }//namespace ugene-1.9.8/src/corelibs/U2Algorithm/src/util_weight_matrix/PWMConversionAlgorithmRegistry.h0000644000175000017500000000315511651544331031030 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_PWM_CONVERSION_ALGORITHM_REGISTRY_H_ #define _U2_PWM_CONVERSION_ALGORITHM_REGISTRY_H_ #include "PWMConversionAlgorithm.h" #include namespace U2 { class PWMConversionAlgorithm; class U2ALGORITHM_EXPORT PWMConversionAlgorithmRegistry : public QObject { Q_OBJECT public: PWMConversionAlgorithmRegistry(QObject* p = NULL); ~PWMConversionAlgorithmRegistry(); PWMConversionAlgorithmFactory* getAlgorithmFactory(const QString& algoId); void addAlgorithm(PWMConversionAlgorithmFactory* algo); QStringList getAlgorithmIds() const ; QList getAlgorithmFactories() const {return algorithms.values();} private: QMap algorithms; }; }//namespace #endif ugene-1.9.8/src/corelibs/U2Algorithm/src/util_gpu/0000755000175000017500000000000011651544331020462 5ustar ilyailyaugene-1.9.8/src/corelibs/U2Algorithm/src/util_gpu/opencl/0000755000175000017500000000000011651544331021742 5ustar ilyailyaugene-1.9.8/src/corelibs/U2Algorithm/src/util_gpu/opencl/OpenCLHelper.cpp0000644000175000017500000002341711651544331024735 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "OpenCLHelper.h" #include #include namespace U2 { const static char * clGetPlatformIDs_n ("clGetPlatformIDs"); const static char * clGetPlatformInfo_n ("clGetPlatformInfo"); const static char * clGetDeviceIDs_n ("clGetDeviceIDs"); const static char * clGetDeviceInfo_n ("clGetDeviceInfo"); const static char * clCreateContext_n ("clCreateContext"); const static char * clCreateBuffer_n ("clCreateBuffer"); const static char * clCreateProgramWithSource_n ("clCreateProgramWithSource"); const static char * clGetProgramBuildInfo_n ("clGetProgramBuildInfo"); const static char * clCreateKernel_n ("clCreateKernel"); const static char * clSetKernelArg_n ("clSetKernelArg"); const static char * clCreateCommandQueue_n ("clCreateCommandQueue"); const static char * clEnqueueNDRangeKernel_n ("clEnqueueNDRangeKernel"); const static char * clWaitForEvents_n ("clWaitForEvents"); const static char * clEnqueueReadBuffer_n ("clEnqueueReadBuffer"); const static char * clFinish_n ("clFinish"); const static char * clBuildProgram_n ("clBuildProgram"); const static char * clReleaseEvent_n ("clReleaseEvent"); const static char * clReleaseKernel_n ("clReleaseKernel"); const static char * clReleaseProgram_n ("clReleaseProgram"); const static char * clReleaseCommandQueue_n ("clReleaseCommandQueue"); const static char * clReleaseContext_n ("clReleaseContext"); const static char * clReleaseMemObject_n ("clReleaseMemObject"); OpenCLHelper::OpenCLHelper() : openclLib( OPENCL_DRIVER_LIB ) { coreLog.details( QObject::tr("Loading OPENCL driver library") ); openclLib.load(); if( !openclLib.isLoaded() ) { coreLog.details( QObject::tr("Cannot load OpenCL library. Error while loading %1").arg(openclLib.fileName()) ); status = Error_NoDriverLib; return; } clGetPlatformIDs_p = clGetPlatformIDs_f( openclLib.resolve(clGetPlatformIDs_n)); if( !clGetPlatformIDs_p ) { coreLog.details( QObject::tr("Cannot resolve symbol %1").arg(clGetPlatformIDs_n) ); status = Error_BadDriverLib; return; } clGetPlatformInfo_p = clGetPlatformInfo_f( openclLib.resolve(clGetPlatformInfo_n)); if( !clGetPlatformInfo_p ) { coreLog.details( QObject::tr("Cannot resolve symbol %1").arg(clGetPlatformInfo_n) ); status = Error_BadDriverLib; return; } clGetDeviceIDs_p = clGetDeviceIDs_f( openclLib.resolve(clGetDeviceIDs_n)); if( !clGetDeviceIDs_p ) { coreLog.details( QObject::tr("Cannot resolve symbol %1").arg(clGetDeviceIDs_n) ); status = Error_BadDriverLib; return; } clGetDeviceInfo_p = clGetDeviceInfo_f( openclLib.resolve(clGetDeviceInfo_n)); if( !clGetDeviceInfo_p ) { coreLog.details( QObject::tr("Cannot resolve symbol %1").arg(clGetDeviceInfo_n) ); status = Error_BadDriverLib; return; } //**************************************** clCreateContext_p = clCreateContext_f( openclLib.resolve(clCreateContext_n)); if( !clCreateContext_p ) { coreLog.details( QObject::tr("Cannot resolve symbol %1").arg(clCreateContext_n) ); status = Error_BadDriverLib; return; } clCreateBuffer_p = clCreateBuffer_f( openclLib.resolve(clCreateBuffer_n)); if( !clCreateBuffer_p ) { coreLog.details( QObject::tr("Cannot resolve symbol %1").arg(clCreateBuffer_n) ); status = Error_BadDriverLib; return; } clCreateProgramWithSource_p = clCreateProgramWithSource_f( openclLib.resolve(clCreateProgramWithSource_n)); if( !clCreateProgramWithSource_p ) { coreLog.details( QObject::tr("Cannot resolve symbol %1").arg(clCreateProgramWithSource_n) ); status = Error_BadDriverLib; return; } clGetProgramBuildInfo_p = clGetProgramBuildInfo_f( openclLib.resolve(clGetProgramBuildInfo_n)); if( !clGetProgramBuildInfo_p ) { coreLog.details( QObject::tr("Cannot resolve symbol %1").arg(clGetProgramBuildInfo_n) ); status = Error_BadDriverLib; return; } clCreateKernel_p = clCreateKernel_f( openclLib.resolve(clCreateKernel_n)); if( !clCreateKernel_p ) { coreLog.details( QObject::tr("Cannot resolve symbol %1").arg(clCreateKernel_n) ); status = Error_BadDriverLib; return; } clSetKernelArg_p = clSetKernelArg_f( openclLib.resolve(clSetKernelArg_n)); if( !clSetKernelArg_p ) { coreLog.details( QObject::tr("Cannot resolve symbol %1").arg(clSetKernelArg_n) ); status = Error_BadDriverLib; return; } clCreateCommandQueue_p = clCreateCommandQueue_f( openclLib.resolve(clCreateCommandQueue_n)); if( !clCreateCommandQueue_p ) { coreLog.details( QObject::tr("Cannot resolve symbol %1").arg(clCreateCommandQueue_n) ); status = Error_BadDriverLib; return; } clEnqueueNDRangeKernel_p = clEnqueueNDRangeKernel_f( openclLib.resolve(clEnqueueNDRangeKernel_n)); if( !clEnqueueNDRangeKernel_p ) { coreLog.details( QObject::tr("Cannot resolve symbol %1").arg(clEnqueueNDRangeKernel_n) ); status = Error_BadDriverLib; return; } clWaitForEvents_p = clWaitForEvents_f( openclLib.resolve(clWaitForEvents_n)); if( !clWaitForEvents_p ) { coreLog.details( QObject::tr("Cannot resolve symbol %1").arg(clWaitForEvents_n) ); status = Error_BadDriverLib; return; } clEnqueueReadBuffer_p = clEnqueueReadBuffer_f( openclLib.resolve(clEnqueueReadBuffer_n)); if( !clEnqueueReadBuffer_p ) { coreLog.details( QObject::tr("Cannot resolve symbol %1").arg(clEnqueueReadBuffer_n) ); status = Error_BadDriverLib; return; } clFinish_p = clFinish_f( openclLib.resolve(clFinish_n)); if( !clFinish_p ) { coreLog.details( QObject::tr("Cannot resolve symbol %1").arg(clFinish_n) ); status = Error_BadDriverLib; return; } clBuildProgram_p = clBuildProgram_f( openclLib.resolve(clBuildProgram_n)); if( !clBuildProgram_p ) { coreLog.details( QObject::tr("Cannot resolve symbol %1").arg(clBuildProgram_n) ); status = Error_BadDriverLib; return; } clReleaseEvent_p = clReleaseEvent_f( openclLib.resolve(clReleaseEvent_n)); if( !clReleaseEvent_p ) { coreLog.details( QObject::tr("Cannot resolve symbol %1").arg(clReleaseEvent_n) ); status = Error_BadDriverLib; return; } clReleaseKernel_p = clReleaseKernel_f( openclLib.resolve(clReleaseKernel_n)); if( !clReleaseKernel_p ) { coreLog.details( QObject::tr("Cannot resolve symbol %1").arg(clReleaseKernel_n) ); status = Error_BadDriverLib; return; } clReleaseProgram_p = clReleaseProgram_f( openclLib.resolve(clReleaseProgram_n)); if( !clReleaseProgram_p ) { coreLog.details( QObject::tr("Cannot resolve symbol %1").arg(clReleaseProgram_n) ); status = Error_BadDriverLib; return; } clReleaseCommandQueue_p = clReleaseCommandQueue_f( openclLib.resolve(clReleaseCommandQueue_n)); if( !clReleaseCommandQueue_p ) { coreLog.details( QObject::tr("Cannot resolve symbol %1").arg(clReleaseCommandQueue_n) ); status = Error_BadDriverLib; return; } clReleaseContext_p = clReleaseContext_f( openclLib.resolve(clReleaseContext_n)); if( !clReleaseContext_p ) { coreLog.details( QObject::tr("Cannot resolve symbol %1").arg(clReleaseContext_n) ); status = Error_BadDriverLib; return; } clReleaseMemObject_p = clReleaseMemObject_f( openclLib.resolve(clReleaseMemObject_n)); if( !clReleaseMemObject_p ) { coreLog.details( QObject::tr("Cannot resolve symbol %1").arg(clReleaseMemObject_n) ); status = Error_BadDriverLib; return; } status = Error_NoError; } OpenCLHelper::~OpenCLHelper() { openclLib.unload(); } QString OpenCLHelper::getErrorString() const { switch (status) { case Error_NoDriverLib: { return QObject::tr("Cannot load library: %1").arg(OPENCL_DRIVER_LIB); } case Error_BadDriverLib: { return QObject::tr("Some errors occurs in library: %1").arg(OPENCL_DRIVER_LIB); } case Error_NoError: { return ""; } default: { return ""; } } } } //namespace ugene-1.9.8/src/corelibs/U2Algorithm/src/util_gpu/opencl/OpenCLUtils.h0000644000175000017500000000252211651544331024255 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef __OPENCL_UTILS_H__ #define __OPENCL_UTILS_H__ #include "OpenCLHelper.h" #include namespace U2 { class U2ALGORITHM_EXPORT OpenCLUtils { public: OpenCLUtils(); static cl_program createProgramByResource( cl_context clContext, cl_device_id deviceId, const QString& resourceName, const OpenCLHelper& openCLHelper, cl_int& err); }; }//namespace #endif //__OPENCL_UTILS_H__ ugene-1.9.8/src/corelibs/U2Algorithm/src/util_gpu/opencl/BinaryFind.cl0000755000175000017500000000663611651544331024325 0ustar ilyailya typedef long NumberType; __kernel void binarySearch_classic( __const __global NumberType * sortedArray, __global NumberType * findMeArray, __const int findMeArraySize, __const unsigned int globalLowerBound, __const unsigned int globalUpperBound, __const unsigned int numberOfIteration, __const __global NumberType* preSaveBounds, __const __global NumberType* c_preSaveValues, __const int preSaveDepth, __local NumberType* preSaveValues, __const NumberType filter) { const unsigned int tid = get_global_id(0); event_t event = 0; async_work_group_copy(preSaveValues, c_preSaveValues, preSaveDepth, event); unsigned int iterPos = tid * numberOfIteration; if (iterPos >= findMeArraySize) { return; } NumberType lowBound = 0, highBound = 0, findMe = 0, preLowBound = 0, preUpperBound = 0, preMid = 0, preCurValue = 0, mid = 0, curValue = 0; const NumberType firstPreMid = preSaveDepth / 2; const NumberType firstPreCurValue = preSaveValues[firstPreMid]; NumberType preAns = 0; for (int i = iterPos; i < iterPos + numberOfIteration; i++) { findMe = findMeArray[i]; //TODO: optimize if ((findMe & filter) > (preSaveValues[preSaveDepth - 1] & filter)) { findMeArray[i] = -1; continue; } preLowBound = 0; preUpperBound = preSaveDepth; preMid = firstPreMid; preCurValue = firstPreCurValue; //*****search in const memory for (int j = 0; preLowBound <= preUpperBound && (preCurValue & filter) != (findMe & filter); j++){ if ((findMe & filter) > (preCurValue & filter)) { preLowBound = preMid + 1; } else { preUpperBound = preMid - 1; } preMid = preLowBound + (preUpperBound - preLowBound) / 2; preCurValue = preSaveValues[preMid]; } if (((preCurValue & filter) == (findMe & filter))) { //findMeArray[i] = preSaveBounds[preMid]; preAns = preSaveBounds[preMid]; for(;preAns>=0 && (sortedArray[preAns] & filter)==(findMe & filter); preAns--){}; findMeArray[i] = preAns + 1; continue; } else { lowBound = preSaveBounds[preUpperBound]; highBound = preSaveBounds[preLowBound]; } //******* mid = lowBound + (highBound - lowBound) / 2; curValue = sortedArray[mid]; for (int j = 0; lowBound <= highBound && (curValue & filter) != (findMe & filter); j++){ if ((findMe & filter) > (curValue & filter)) { lowBound = mid + 1; } else { highBound = mid - 1; } mid = lowBound + (highBound - lowBound) / 2; curValue = sortedArray[mid]; } if (((curValue & filter) == (findMe & filter))) { //findMeArray[i] = mid; preAns = mid; for(;preAns>=0 && (sortedArray[preAns] & filter)==(findMe & filter); preAns--){}; findMeArray[i] = preAns + 1; } else { findMeArray[i] = -1; } } } ugene-1.9.8/src/corelibs/U2Algorithm/src/util_gpu/opencl/OpenCLUtils.cpp0000644000175000017500000000513511651544331024613 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "OpenCLUtils.h" #include #include #include #include namespace U2 { OpenCLUtils::OpenCLUtils(){} cl_program OpenCLUtils::createProgramByResource( cl_context clContext, cl_device_id deviceId, const QString& resourceName, const OpenCLHelper& openCLHelper, cl_int& err) { //open and read file contains OPENCL code QByteArray file; QFile data(resourceName); if (data.open(QFile::ReadOnly)) { file = data.readAll(); data.close(); } else { ioLog.error(QString("No source file: %1").arg(data.errorString())); return 0; } const char* sourceCode = file.constData(); const size_t sourceLength = file.size(); cl_program clProgram = openCLHelper.clCreateProgramWithSource_p(clContext, 1, &sourceCode, &sourceLength, &err); if(err != 0) { coreLog.error(QString("OPENCL: clCreateProgramWithSource, Error code (%2)").arg(err)); return 0; } err = openCLHelper.clBuildProgram_p(clProgram, 0, NULL, NULL, NULL, NULL); if (err != CL_SUCCESS) { size_t logSize = 1; openCLHelper.clGetProgramBuildInfo_p(clProgram, deviceId, CL_PROGRAM_BUILD_LOG, 0, NULL, &logSize); gauto_array logStr(new char[logSize]); openCLHelper.clGetProgramBuildInfo_p(clProgram, deviceId, CL_PROGRAM_BUILD_LOG, logSize, logStr.get(), &logSize); coreLog.error(QObject::tr("OPENCL: BUILD LOG \n ******************** \n %1 \n ********************").arg(logStr.get())); coreLog.error(QObject::tr("OPENCL: Program::build() failed. (%1)").arg(err)); return 0; } return clProgram; } }//namespace ugene-1.9.8/src/corelibs/U2Algorithm/src/util_gpu/opencl/OpenCLHelper.h0000644000175000017500000001636611651544331024407 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef __OPENCL_HELPER__ #define __OPENCL_HELPER__ #include #include #include #include #define OPENCL_DRIVER_LIB "OpenCL" namespace U2 { class U2ALGORITHM_EXPORT OpenCLHelper { public: typedef CL_API_ENTRY cl_int ( CL_API_CALL *clGetPlatformIDs_f)( cl_uint num_entries, cl_platform_id *platforms, cl_uint *num_platforms) CL_API_SUFFIX__VERSION_1_1; typedef CL_API_ENTRY cl_int ( CL_API_CALL *clGetPlatformInfo_f)( cl_platform_id platform, cl_platform_info param_name, size_t param_value_size, void *param_value, size_t *param_value_size_ret) CL_API_SUFFIX__VERSION_1_1; typedef CL_API_ENTRY cl_int ( CL_API_CALL *clGetDeviceIDs_f)( cl_platform_id platform, cl_device_type device_type, cl_uint num_entries, cl_device_id *devices, cl_uint *num_devices) CL_API_SUFFIX__VERSION_1_1; typedef CL_API_ENTRY cl_int ( CL_API_CALL *clGetDeviceInfo_f)( cl_device_id device, cl_device_info param_name, size_t param_value_size, void *param_value, size_t *param_value_size_ret) CL_API_SUFFIX__VERSION_1_1; typedef CL_API_ENTRY cl_context ( CL_API_CALL *clCreateContext_f)( const cl_context_properties *properties, cl_uint num_devices, const cl_device_id *devices, void (CL_CALLBACK *pfn_notify)(const char *errinfo, const void *private_info, size_t cb, void *user_data), void *user_data, cl_int *errcode_ret) CL_API_SUFFIX__VERSION_1_1; typedef CL_API_ENTRY cl_mem ( CL_API_CALL *clCreateBuffer_f)( cl_context context, cl_mem_flags flags, size_t size, void *host_ptr, cl_int *errcode_ret) CL_API_SUFFIX__VERSION_1_1; typedef CL_API_ENTRY cl_program ( CL_API_CALL *clCreateProgramWithSource_f)( cl_context context, cl_uint count, const char **strings, const size_t *lengths, cl_int *errcode_ret) CL_API_SUFFIX__VERSION_1_1; typedef CL_API_ENTRY cl_int ( CL_API_CALL *clGetProgramBuildInfo_f)( cl_program program, cl_device_id device, cl_program_build_info param_name, size_t param_value_size, void *param_value, size_t *param_value_size_ret) CL_API_SUFFIX__VERSION_1_1; typedef CL_API_ENTRY cl_kernel ( CL_API_CALL *clCreateKernel_f)( cl_program program, const char *kernel_name, cl_int *errcode_ret) CL_API_SUFFIX__VERSION_1_1; typedef CL_API_ENTRY cl_int ( CL_API_CALL *clSetKernelArg_f)( cl_kernel kernel, cl_uint arg_index, size_t arg_size, const void *arg_value) CL_API_SUFFIX__VERSION_1_1; typedef CL_API_ENTRY cl_command_queue ( CL_API_CALL *clCreateCommandQueue_f)( cl_context context, cl_device_id device, cl_command_queue_properties properties, cl_int *errcode_ret) CL_API_SUFFIX__VERSION_1_1; typedef CL_API_ENTRY cl_int ( CL_API_CALL *clEnqueueNDRangeKernel_f)( cl_command_queue command_queue, cl_kernel kernel, cl_uint work_dim, const size_t *global_work_offset, const size_t *global_work_size, const size_t *local_work_size, cl_uint num_events_in_wait_list, const cl_event *event_wait_list, cl_event *event) CL_API_SUFFIX__VERSION_1_1; typedef CL_API_ENTRY cl_int ( CL_API_CALL *clWaitForEvents_f)( cl_uint num_events, const cl_event *event_list) CL_API_SUFFIX__VERSION_1_1; typedef CL_API_ENTRY cl_int ( CL_API_CALL *clEnqueueReadBuffer_f)(cl_command_queue command_queue, cl_mem buffer, cl_bool blocking_read, size_t offset, size_t cb, void *ptr, cl_uint num_events_in_wait_list, const cl_event *event_wait_list, cl_event *event) CL_API_SUFFIX__VERSION_1_1; typedef CL_API_ENTRY cl_int ( CL_API_CALL *clFinish_f)(cl_command_queue command_queue) CL_API_SUFFIX__VERSION_1_1; typedef CL_API_ENTRY cl_int ( CL_API_CALL *clReleaseEvent_f)(cl_event event) CL_API_SUFFIX__VERSION_1_1; typedef CL_API_ENTRY cl_int ( CL_API_CALL *clReleaseKernel_f)(cl_kernel kernel) CL_API_SUFFIX__VERSION_1_1; typedef CL_API_ENTRY cl_int ( CL_API_CALL *clReleaseProgram_f)(cl_program program) CL_API_SUFFIX__VERSION_1_1; typedef CL_API_ENTRY cl_int ( CL_API_CALL *clReleaseCommandQueue_f)(cl_command_queue command_queue) CL_API_SUFFIX__VERSION_1_1; typedef CL_API_ENTRY cl_int ( CL_API_CALL *clReleaseContext_f)(cl_context context) CL_API_SUFFIX__VERSION_1_1; typedef CL_API_ENTRY cl_int ( CL_API_CALL *clReleaseMemObject_f)(cl_mem memobj) CL_API_SUFFIX__VERSION_1_1; typedef CL_API_ENTRY cl_int ( CL_API_CALL *clBuildProgram_f)(cl_program program, cl_uint num_devices, const cl_device_id *device_list, const char *options, void (CL_CALLBACK *pfn_notify)(cl_program program, void *user_data), void *user_data) CL_API_SUFFIX__VERSION_1_1; clGetPlatformIDs_f clGetPlatformIDs_p; clGetPlatformInfo_f clGetPlatformInfo_p; clGetDeviceIDs_f clGetDeviceIDs_p; clGetDeviceInfo_f clGetDeviceInfo_p; clCreateContext_f clCreateContext_p; clCreateBuffer_f clCreateBuffer_p; clCreateProgramWithSource_f clCreateProgramWithSource_p; clGetProgramBuildInfo_f clGetProgramBuildInfo_p; clCreateKernel_f clCreateKernel_p; clSetKernelArg_f clSetKernelArg_p; clCreateCommandQueue_f clCreateCommandQueue_p; clEnqueueNDRangeKernel_f clEnqueueNDRangeKernel_p; clWaitForEvents_f clWaitForEvents_p; clEnqueueReadBuffer_f clEnqueueReadBuffer_p; clFinish_f clFinish_p; clBuildProgram_f clBuildProgram_p; clReleaseEvent_f clReleaseEvent_p; clReleaseKernel_f clReleaseKernel_p; clReleaseProgram_f clReleaseProgram_p; clReleaseCommandQueue_f clReleaseCommandQueue_p; clReleaseContext_f clReleaseContext_p; clReleaseMemObject_f clReleaseMemObject_p; enum OpenCLHelperError { Error_NoError, Error_NoDriverLib, Error_BadDriverLib, }; bool isLoaded() const {return (status == Error_NoError);} QString getErrorString() const; OpenCLHelper(); ~OpenCLHelper(); private: OpenCLHelper& operator=( const OpenCLHelper &s ); OpenCLHelper(const OpenCLHelper &); private: OpenCLHelperError status; QLibrary openclLib; }; } #endif //__OPENCL_HELPER__ ugene-1.9.8/src/corelibs/U2Algorithm/src/util_msa_distance/0000755000175000017500000000000011651544331022321 5ustar ilyailyaugene-1.9.8/src/corelibs/U2Algorithm/src/util_msa_distance/BuiltInDistanceAlgorithms.h0000644000175000017500000000224311651544331027546 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_BUILT_IN_DISTANCE_ALGORITHMS_H_ #define _U2_BUILT_IN_DISTANCE_ALGORITHMS_H_ #include #include namespace U2 { class U2ALGORITHM_EXPORT BuiltInDistanceAlgorithms { public: static const QString HAMMING_ALGO; static const QString HAMMING_REVCOMPL_ALGO; }; }//namespace #endif ugene-1.9.8/src/corelibs/U2Algorithm/src/util_msa_distance/MSADistanceAlgorithmHammingRevCompl.cpp0000644000175000017500000000547211651544331031750 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "MSADistanceAlgorithmHammingRevCompl.h" #include #include #include #include namespace U2 { MSADistanceAlgorithmFactoryHammingRevCompl::MSADistanceAlgorithmFactoryHammingRevCompl(QObject* p) : MSADistanceAlgorithmFactory(BuiltInDistanceAlgorithms::HAMMING_REVCOMPL_ALGO, DistanceAlgorithmFlag_Nucleic, p) { } QString MSADistanceAlgorithmFactoryHammingRevCompl::getDescription() const { return tr("Based on Hamming distance between two sequences"); } QString MSADistanceAlgorithmFactoryHammingRevCompl::getName() const { return tr("Hamming reverse-complement"); } MSADistanceAlgorithm* MSADistanceAlgorithmFactoryHammingRevCompl::createAlgorithm(const MAlignment& ma, QObject* ) { return new MSADistanceAlgorithmHammingRevCompl(this, ma); } ////////////////////////////////////////////////////////////////////////// // Algorithm void MSADistanceAlgorithmHammingRevCompl::run() { QList compTTs = AppContext::getDNATranslationRegistry()-> lookupTranslation(ma.getAlphabet(), DNATranslationType_NUCL_2_COMPLNUCL); assert (!compTTs.isEmpty()); DNATranslation* trans = compTTs.first(); int nSeq = ma.getNumRows(); MAlignment revtransl; revtransl.setAlphabet(ma.getAlphabet()); for (int i = 0; i < nSeq; i++) { QByteArray arr = ma.getRow(i).toByteArray(ma.getLength()); trans->translate(arr.data(), arr.length()); TextUtils::reverse(arr.data(), arr.length()); revtransl.addRow(MAlignmentRow(ma.getRow(i).getName(), arr)); } for (int i = 0; i < nSeq; i++) { for (int j = i; j < nSeq; j++) { int sim = 0; for (int k = 0; k < ma.getLength(); k++) { if (ma.charAt(i, k) == revtransl.charAt(j, k)) sim++; } lock.lock(); distanceTable[i][j] = distanceTable[j][i] = sim; lock.unlock(); } } } } //namespace ugene-1.9.8/src/corelibs/U2Algorithm/src/util_msa_distance/BuiltInDistanceAlgorithms.cpp0000644000175000017500000000210411651544331030075 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "BuiltInDistanceAlgorithms.h" namespace U2 { const QString BuiltInDistanceAlgorithms::HAMMING_ALGO("Hamming"); const QString BuiltInDistanceAlgorithms::HAMMING_REVCOMPL_ALGO("Hamming reverse-complement"); }//namespace ugene-1.9.8/src/corelibs/U2Algorithm/src/util_msa_distance/MSADistanceAlgorithmRegistry.h0000644000175000017500000000327311651544331030172 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_MSA_DISTANCE_ALGORITHM_REGISTRY_H_ #define _U2_MSA_DISTANCE_ALGORITHM_REGISTRY_H_ #include "MSADistanceAlgorithm.h" #include namespace U2 { class MSADistanceAlgorithm; class U2ALGORITHM_EXPORT MSADistanceAlgorithmRegistry : public QObject { Q_OBJECT public: MSADistanceAlgorithmRegistry(QObject* p = NULL); ~MSADistanceAlgorithmRegistry(); MSADistanceAlgorithmFactory* getAlgorithmFactory(const QString& algoId); void addAlgorithm(MSADistanceAlgorithmFactory* algo); QStringList getAlgorithmIds() const ; QList getAlgorithmFactories() const {return algorithms.values();} QList getAlgorithmFactories(DistanceAlgorithmFlags flags) const; private: QMap algorithms; }; }//namespace #endif ugene-1.9.8/src/corelibs/U2Algorithm/src/util_msa_distance/MSADistanceAlgorithmRegistry.cpp0000644000175000017500000000507411651544331030526 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "MSADistanceAlgorithmRegistry.h" #include "MSADistanceAlgorithmHamming.h" #include "MSADistanceAlgorithmHammingRevCompl.h" namespace U2 { MSADistanceAlgorithmRegistry::MSADistanceAlgorithmRegistry(QObject* p) : QObject(p) { addAlgorithm(new MSADistanceAlgorithmFactoryHamming()); //addAlgorithm(new MSADistanceAlgorithmFactoryHammingRevCompl()); } MSADistanceAlgorithmRegistry::~MSADistanceAlgorithmRegistry() { QList list = algorithms.values(); foreach(MSADistanceAlgorithmFactory* algo, list) { delete algo; } } MSADistanceAlgorithmFactory* MSADistanceAlgorithmRegistry::getAlgorithmFactory(const QString& algoId) { return algorithms.value(algoId); } void MSADistanceAlgorithmRegistry::addAlgorithm(MSADistanceAlgorithmFactory* algo) { const QString& id = algo->getId(); MSADistanceAlgorithmFactory* oldVersion = algorithms.value(id); if (oldVersion!=NULL) { delete oldVersion; oldVersion = NULL; } algorithms[id] = algo; } QStringList MSADistanceAlgorithmRegistry::getAlgorithmIds() const { QList list = algorithms.values(); QStringList result; foreach(MSADistanceAlgorithmFactory* algo, list) { result.append(algo->getId()); } return result; } QList MSADistanceAlgorithmRegistry::getAlgorithmFactories(DistanceAlgorithmFlags flags) const { QList allFactories = getAlgorithmFactories(); QList result; foreach(MSADistanceAlgorithmFactory* f, allFactories) { if ((flags & f->getFlags()) == flags) { result.append(f); } } return result; } }//namespace ugene-1.9.8/src/corelibs/U2Algorithm/src/util_msa_distance/MSADistanceAlgorithmHamming.h0000644000175000017500000000334411651544331027741 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_MSA_DISTANCE_ALGORITHM_HAMMING_H_ #define _U2_MSA_DISTANCE_ALGORITHM_HAMMING_H_ #include "MSADistanceAlgorithm.h" #include "BuiltInDistanceAlgorithms.h" namespace U2 { // Hamming algorithm is based on Hamming distance between sequences class U2ALGORITHM_EXPORT MSADistanceAlgorithmFactoryHamming: public MSADistanceAlgorithmFactory { Q_OBJECT public: MSADistanceAlgorithmFactoryHamming(QObject* p = NULL); virtual MSADistanceAlgorithm* createAlgorithm(const MAlignment& ma, QObject* parent); virtual QString getDescription() const; virtual QString getName() const; }; class U2ALGORITHM_EXPORT MSADistanceAlgorithmHamming : public MSADistanceAlgorithm { Q_OBJECT public: MSADistanceAlgorithmHamming(MSADistanceAlgorithmFactoryHamming* f, const MAlignment& ma) : MSADistanceAlgorithm(f, ma){} virtual void run(); }; }//namespace #endif ugene-1.9.8/src/corelibs/U2Algorithm/src/util_msa_distance/MSADistanceAlgorithmHamming.cpp0000644000175000017500000000404311651544331030271 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "MSADistanceAlgorithmHamming.h" #include namespace U2 { MSADistanceAlgorithmFactoryHamming::MSADistanceAlgorithmFactoryHamming(QObject* p) : MSADistanceAlgorithmFactory(BuiltInDistanceAlgorithms::HAMMING_ALGO, DistanceAlgorithmFlags_NuclAmino, p) { } QString MSADistanceAlgorithmFactoryHamming::getDescription() const { return tr("Based on Hamming distance between two sequences"); } QString MSADistanceAlgorithmFactoryHamming::getName() const { return tr("Hamming"); } MSADistanceAlgorithm* MSADistanceAlgorithmFactoryHamming::createAlgorithm(const MAlignment& ma, QObject* ) { return new MSADistanceAlgorithmHamming(this, ma); } ////////////////////////////////////////////////////////////////////////// // Algorithm void MSADistanceAlgorithmHamming::run() { int nSeq = ma.getNumRows(); for (int i = 0; i < nSeq; i++) { for (int j = i; j < nSeq; j++) { int sim = 0; for (int k = 0; k < ma.getLength(); k++) { if (ma.charAt(i, k) == ma.charAt(j, k)) sim++; } lock.lock(); distanceTable[i][j] = distanceTable[j][i] = sim; lock.unlock(); } } } } //namespace ugene-1.9.8/src/corelibs/U2Algorithm/src/util_msa_distance/MSADistanceAlgorithmHammingRevCompl.h0000644000175000017500000000343011651544331031405 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_MSA_DISTANCE_ALGORITHM_HAMMING_COMPL_H_ #define _U2_MSA_DISTANCE_ALGORITHM_HAMMING_COMPL_H_ #include "MSADistanceAlgorithm.h" #include "BuiltInDistanceAlgorithms.h" namespace U2 { // Hamming algorithm is based on Hamming distance between sequences class U2ALGORITHM_EXPORT MSADistanceAlgorithmFactoryHammingRevCompl: public MSADistanceAlgorithmFactory { Q_OBJECT public: MSADistanceAlgorithmFactoryHammingRevCompl(QObject* p = NULL); virtual MSADistanceAlgorithm* createAlgorithm(const MAlignment& ma, QObject* parent); virtual QString getDescription() const; virtual QString getName() const; }; class U2ALGORITHM_EXPORT MSADistanceAlgorithmHammingRevCompl : public MSADistanceAlgorithm { Q_OBJECT public: MSADistanceAlgorithmHammingRevCompl(MSADistanceAlgorithmFactoryHammingRevCompl* f, const MAlignment& ma) : MSADistanceAlgorithm(f, ma){} virtual void run(); }; }//namespace #endif ugene-1.9.8/src/corelibs/U2Algorithm/src/util_msa_distance/MSADistanceAlgorithm.h0000644000175000017500000000610511651544331026436 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_MSA_DISTANCE_ALGORITHM_H_ #define _U2_MSA_DISTANCE_ALGORITHM_H_ #include #include #include #include #include #include namespace U2 { class MAlignment; class MSADistanceAlgorithm; class DNAAlphabet; enum DistanceAlgorithmFlag { DistanceAlgorithmFlag_Nucleic = 1 << 0, DistanceAlgorithmFlag_Amino = 1 << 1, DistanceAlgorithmFlag_Raw = 1 << 2, }; typedef QFlags DistanceAlgorithmFlags; #define DistanceAlgorithmFlags_AllAlphabets (DistanceAlgorithmFlags(DistanceAlgorithmFlag_Nucleic) | DistanceAlgorithmFlag_Amino | DistanceAlgorithmFlag_Raw) #define DistanceAlgorithmFlags_NuclAmino (DistanceAlgorithmFlags(DistanceAlgorithmFlag_Nucleic) | DistanceAlgorithmFlag_Amino) class U2ALGORITHM_EXPORT MSADistanceAlgorithmFactory : public QObject { Q_OBJECT public: MSADistanceAlgorithmFactory(const QString& algoId, DistanceAlgorithmFlags flags, QObject* p = NULL); virtual MSADistanceAlgorithm* createAlgorithm(const MAlignment& ma, QObject* parent = NULL) = 0; QString getId() const {return algorithmId;} DistanceAlgorithmFlags getFlags() const {return flags;} virtual QString getDescription() const = 0; virtual QString getName() const = 0; // utility method static DistanceAlgorithmFlags getAphabetFlags(const DNAAlphabet* al); private: QString algorithmId; DistanceAlgorithmFlags flags; }; class U2ALGORITHM_EXPORT MSADistanceAlgorithm : public Task { Q_OBJECT public: MSADistanceAlgorithm(MSADistanceAlgorithmFactory* factory, const MAlignment& ma); int getSimilarity(int row1, int row2); virtual QString getDescription() const {return factory->getDescription();} virtual QString getName() const {return factory->getName();} QString getId() const {return factory->getId();} MSADistanceAlgorithmFactory* getFactory() const {return factory;} private: MSADistanceAlgorithmFactory* factory; protected: MAlignment ma; QVarLengthArray > distanceTable; QMutex lock; }; }//namespace #endif ugene-1.9.8/src/corelibs/U2Algorithm/src/util_msa_distance/MSADistanceAlgorithm.cpp0000644000175000017500000000445011651544331026772 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "MSADistanceAlgorithm.h" #include #include #include namespace U2 { ////////////////////////////////////////////////////////////////////////// // Factory MSADistanceAlgorithmFactory::MSADistanceAlgorithmFactory(const QString& algoId, DistanceAlgorithmFlags _flags, QObject* p) : QObject(p), algorithmId(algoId), flags(_flags) { } DistanceAlgorithmFlags MSADistanceAlgorithmFactory::getAphabetFlags(const DNAAlphabet* al) { if (al->getType() == DNAAlphabet_AMINO) { return DistanceAlgorithmFlag_Amino; } else if (al->getType() == DNAAlphabet_NUCL) { return DistanceAlgorithmFlag_Nucleic; } assert(al->getType() == DNAAlphabet_RAW); return DistanceAlgorithmFlag_Raw; } ////////////////////////////////////////////////////////////////////////// // Algorithm MSADistanceAlgorithm::MSADistanceAlgorithm(MSADistanceAlgorithmFactory* _factory, const MAlignment& _ma) : Task(tr("MSA distance algorithm \"%1\" task").arg(_factory->getName()), TaskFlag_None), factory(_factory), ma(_ma) { for (int i = 0; i < ma.getNumRows(); i++) { distanceTable.append(QVarLengthArray(ma.getNumRows())); qMemSet(distanceTable[i].data(), 0, ma.getNumRows() * sizeof(int)); } } int MSADistanceAlgorithm::getSimilarity(int row1, int row2) { lock.lock(); int res = distanceTable[row1][row2]; lock.unlock(); return res; } } //namespace ugene-1.9.8/src/corelibs/U2Algorithm/src/util_dna_assembly/0000755000175000017500000000000011651544331022330 5ustar ilyailyaugene-1.9.8/src/corelibs/U2Algorithm/src/util_dna_assembly/DnaAssemblyMultiTask.h0000644000175000017500000000335611651544331026550 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_DNA_ASSEMBLY_MULTI_TASK_ #define _U2_DNA_ASSEMBLY_MULTI_TASK_ #include #include #include namespace U2 { class Document; class U2ALGORITHM_EXPORT DnaAssemblyMultiTask : public Task { Q_OBJECT public: DnaAssemblyMultiTask(const DnaAssemblyToRefTaskSettings& settings, bool viewResult = false, bool justBuildIndex = false); virtual void prepare(); virtual ReportResult report(); virtual QString generateReport() const; QList onSubTaskFinished(Task* subTask); bool getOpenViewFlag() { return openView; } const DnaAssemblyToRefTaskSettings& getSettings() const {return settings;} private: DnaAssemblyToRefTaskSettings settings; DnaAssemblyToReferenceTask* assemblyToRefTask; //Document* doc; QList shortReadUrls; bool openView; bool justBuildIndex; }; } // namespace #endif ugene-1.9.8/src/corelibs/U2Algorithm/src/util_dna_assembly/DnaAssemblyMultiTask.cpp0000644000175000017500000000652211651544331027101 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "DnaAssemblyMultiTask.h" #include #include #include #include #include namespace U2 { DnaAssemblyMultiTask::DnaAssemblyMultiTask( const DnaAssemblyToRefTaskSettings& s, bool view, bool _justBuildIndex ) : Task("DnaAssemblyMultiTask", TaskFlags_NR_FOSCOE | TaskFlag_ReportingIsSupported | TaskFlag_ReportingIsEnabled), settings(s), assemblyToRefTask(NULL), shortReadUrls(s.shortReadUrls), openView(view), justBuildIndex(_justBuildIndex) { } void DnaAssemblyMultiTask::prepare() { // perform assembly QString algName = settings.algName; DnaAssemblyAlgorithmEnv* env= AppContext::getDnaAssemblyAlgRegistry()->getAlgorithm(algName); assert(env); if (env == NULL) { setError(QString("Algorithm %1 is not found").arg(algName)); return; } assemblyToRefTask = env->getTaskFactory()->createTaskInstance(settings, justBuildIndex); addSubTask(assemblyToRefTask); } Task::ReportResult DnaAssemblyMultiTask::report() { return ReportResult_Finished; } QList DnaAssemblyMultiTask::onSubTaskFinished( Task* subTask ) { QList subTasks; if (subTask->hasError() || isCanceled()) { return subTasks; } if (subTask == assemblyToRefTask) { qint64 time=(subTask->getTimeInfo().finishTime - subTask->getTimeInfo().startTime); taskLog.details(QString("Assembly to reference task time: %1").arg((double)time/(1000*1000))); } if ( subTask == assemblyToRefTask && settings.openView ) { Task* openTask = AppContext::getProjectLoader()->openWithProjectTask(settings.resultFileName); if (openTask != NULL) { subTasks << openTask; } } return subTasks; } QString DnaAssemblyMultiTask::generateReport() const { QString res; if (hasError() || isCanceled()) { return QString("Assembly task finished with error: %1").arg(getError()); } if (justBuildIndex) { res = settings.algName + QString(" index-file for %1 was built successfully") .arg(settings.refSeqUrl.fileName()); } else if (assemblyToRefTask->isHaveResult()) { res = QString("Assembly to reference %1 was finished successfully") .arg(settings.refSeqUrl.fileName()); } else { res = QString("Assembly to reference %1 was failed. No possible alignment was found") .arg(settings.refSeqUrl.fileName()); } return res; } } // namespace ugene-1.9.8/src/corelibs/U2Algorithm/src/registry/0000755000175000017500000000000011651544331020502 5ustar ilyailyaugene-1.9.8/src/corelibs/U2Algorithm/src/registry/RepeatFinderTaskFactoryRegistry.cpp0000644000175000017500000000371111651544331027464 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "RepeatFinderTaskFactoryRegistry.h" #include #include namespace U2 { RepeatFinderTaskFactoryRegistry::RepeatFinderTaskFactoryRegistry(QObject* pOwn): QObject(pOwn) { } RepeatFinderTaskFactoryRegistry::~RepeatFinderTaskFactoryRegistry() { foreach (const RepeatFinderTaskFactory* factory, factories) { delete factory; } } bool RepeatFinderTaskFactoryRegistry::registerFactory( RepeatFinderTaskFactory* factory, const QString& factoryId) { QMutexLocker locker(&mutex); if (factories.contains(factoryId)) { return false; } factories[factoryId] = factory; return true; } RepeatFinderTaskFactory* RepeatFinderTaskFactoryRegistry::getFactory(const QString& factoryId) { return factories.value(factoryId, 0); } QStringList RepeatFinderTaskFactoryRegistry::getListFactoryNames() { return factories.keys(); } bool RepeatFinderTaskFactoryRegistry::hadRegistered(const QString& factoryId) { return factories.contains(factoryId); } } // namespace ugene-1.9.8/src/corelibs/U2Algorithm/src/registry/SecStructPredictAlgRegistry.h0000644000175000017500000000345011651544331026264 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_SEC_STRUCT_PREDICT_ALG_REGISTRY_H_ #define _U2_SEC_STRUCT_PREDICT_ALG_REGISTRY_H_ #include #include #include #include #include namespace U2 { class SecStructPredictTaskFactory; class SecStructPredictTask; class U2ALGORITHM_EXPORT SecStructPredictAlgRegistry : public QObject { Q_OBJECT public: SecStructPredictAlgRegistry(QObject* pOwn = 0); ~SecStructPredictAlgRegistry(); bool registerAlgorithm(SecStructPredictTaskFactory* alg, const QString& algId); bool hadRegistered(const QString& algId); SecStructPredictTaskFactory* getAlgorithm(const QString& algId); QStringList getAlgNameList(); private: QMutex mutex; QMap algMap; // Copy prohibition SecStructPredictAlgRegistry(const SecStructPredictAlgRegistry& m); SecStructPredictAlgRegistry& operator=(const SecStructPredictAlgRegistry& m); }; } // namespace #endif ugene-1.9.8/src/corelibs/U2Algorithm/src/registry/CudaGpuRegistry.h0000644000175000017500000000515611651544331023743 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef __CUDA_GPU_REGISTRY_H__ #define __CUDA_GPU_REGISTRY_H__ #include #include namespace U2 { typedef int CudaGpuId; #define CUDA_GPU_REGISTRY_SETTINGS "/cuda_gpu_registry" //stores settings for concrete GPU. The key for appending - textual representation of CudaGpuId #define CUDA_GPU_REGISTRY_SETTINGS_GPU_SPECIFIC "/cuda_gpu_registry/gpu_specific" #define CUDA_GPU_SETTINGS_ENABLED "/enabled" class U2ALGORITHM_EXPORT CudaGpuModel { public: CudaGpuModel( const QString & _name, const CudaGpuId & _id, quint64 _globalMemorySize, bool _enabled = true ) : name(_name), id(_id), globalMemorySizeBytes(_globalMemorySize), enabled(_enabled), acquired(false) {}; QString getName() const {return name;} CudaGpuId getId() const {return id;} quint64 getGlobalMemorySizeBytes() const {return globalMemorySizeBytes;} bool isEnabled() const { return enabled;} void setEnabled(bool b) {enabled = b;} bool isAcquired() const {return acquired;} void setAcquired( bool a ) {acquired = a;} bool isReady() {return !isAcquired() && isEnabled(); } private: //TODO: add another cuda device properties from cudaDeviceProp QString name; CudaGpuId id; quint64 globalMemorySizeBytes; bool enabled; bool acquired; }; class U2ALGORITHM_EXPORT CudaGpuRegistry { public: ~CudaGpuRegistry(); void registerCudaGpu( CudaGpuModel * gpu ); CudaGpuModel * getGpuById( CudaGpuId id ) const; QList getRegisteredGpus() const; CudaGpuModel * getAnyEnabledGpu() const; CudaGpuModel * acquireAnyReadyGpu(); bool empty() const { return gpus.empty(); } private: void saveGpusSettings() const; QHash< CudaGpuId, CudaGpuModel * > gpus; }; } //namespace #endif //__CUDA_GPU_REGISTRY_H__ ugene-1.9.8/src/corelibs/U2Algorithm/src/registry/CudaGpuRegistry.cpp0000644000175000017500000000452111651544331024271 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include #include #include #include #include #include "CudaGpuRegistry.h" namespace U2 { CudaGpuRegistry::~CudaGpuRegistry() { saveGpusSettings(); qDeleteAll( gpus.values() ); } void CudaGpuRegistry::registerCudaGpu( CudaGpuModel * gpu ) { assert( !gpus.contains(gpu->getId()) ); gpus.insert( gpu->getId(), gpu ); } CudaGpuModel * CudaGpuRegistry::getGpuById( CudaGpuId id ) const { return gpus.value( id, 0 ); } QList CudaGpuRegistry::getRegisteredGpus() const { return gpus.values(); } CudaGpuModel * CudaGpuRegistry::getAnyEnabledGpu() const { QHash::const_iterator it = std::find_if( gpus.begin(), gpus.end(), std::mem_fun(&CudaGpuModel::isEnabled) ); if( gpus.end() != it ) { return *it; } return 0; } CudaGpuModel * CudaGpuRegistry::acquireAnyReadyGpu() { QHash::iterator it = std::find_if( gpus.begin(), gpus.end(), std::mem_fun(&CudaGpuModel::isReady) ); if( gpus.end() != it ) { (*it)->setAcquired(true); return *it; } return 0; } void CudaGpuRegistry::saveGpusSettings() const { Settings * s = AppContext::getSettings(); foreach( CudaGpuModel * m, gpus ) { QString key = CUDA_GPU_REGISTRY_SETTINGS_GPU_SPECIFIC + QString::number(m->getId()) + CUDA_GPU_SETTINGS_ENABLED; s->setValue( key, QVariant::fromValue(m->isEnabled()) ); } } } //namespace ugene-1.9.8/src/corelibs/U2Algorithm/src/registry/SecStructPredictTask.h0000644000175000017500000000362611651544331024737 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_SEC_STRUCT_PREDICT_TASK_H_ #define _U2_SEC_STRUCT_PREDICT_TASK_H_ #include #include namespace U2 { class U2ALGORITHM_EXPORT SecStructPredictTask : public Task { Q_OBJECT public: SecStructPredictTask(const QByteArray& seq); const QList& getResults() const { return results; } const QByteArray getSSFormatResults() const { return output; } protected: QByteArray sequence, output; QList results; }; class U2ALGORITHM_EXPORT SecStructPredictTaskFactory { public: virtual SecStructPredictTask* createTaskInstance(const QByteArray& inputSeq) = 0; virtual ~SecStructPredictTaskFactory() {} }; #define SEC_STRUCT_PREDICT_TASK_FACTORY(c) \ public: \ static const QString taskName; \ class Factory : public SecStructPredictTaskFactory { \ public: \ Factory() { } \ SecStructPredictTask* createTaskInstance(const QByteArray& inputSeq) { return new c(inputSeq); } \ }; } //namespace #endif // _U2_SEC_STRUCT_PREDICT_TASK_H_ ugene-1.9.8/src/corelibs/U2Algorithm/src/registry/RepeatFinderTaskFactoryRegistry.h0000644000175000017500000000323111651544331027126 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_REPEAT_FINDER_ALG_REGISTRY_H_ #define _U2_REPEAT_FINDER_ALG_REGISTRY_H_ #include #include #include #include #include #include namespace U2 { enum RepeatFinderTaskFactoryId {}; class U2ALGORITHM_EXPORT RepeatFinderTaskFactoryRegistry: public QObject { Q_OBJECT public: RepeatFinderTaskFactoryRegistry(QObject* pOwn = 0); ~RepeatFinderTaskFactoryRegistry(); bool registerFactory(RepeatFinderTaskFactory* factory, const QString& factoryId); bool hadRegistered(const QString& factoryId); RepeatFinderTaskFactory* getFactory(const QString& factoryId); QStringList getListFactoryNames(); private: QMutex mutex; QHash factories; }; } // namespace #endif ugene-1.9.8/src/corelibs/U2Algorithm/src/registry/OpenCLGpuRegistry.cpp0000644000175000017500000000460311651544331024536 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include #include #include #include #include #include "OpenCLGpuRegistry.h" namespace U2 { OpenCLGpuRegistry::~OpenCLGpuRegistry() { saveGpusSettings(); qDeleteAll( gpus.values() ); } void OpenCLGpuRegistry::registerOpenCLGpu( OpenCLGpuModel * gpu ) { assert( !gpus.contains(gpu->getId()) ); gpus.insert( gpu->getId(), gpu ); } OpenCLGpuModel * OpenCLGpuRegistry::getGpuById( OpenCLGpuId id ) const { return gpus.value( id, 0 ); } QList OpenCLGpuRegistry::getRegisteredGpus() const { return gpus.values(); } OpenCLGpuModel * OpenCLGpuRegistry::getAnyEnabledGpu() const { QHash::const_iterator it = std::find_if( gpus.begin(), gpus.end(), std::mem_fun(&OpenCLGpuModel::isEnabled) ); if( gpus.end() != it ) { return *it; } return 0; } OpenCLGpuModel * OpenCLGpuRegistry::acquireAnyReadyGpu() { QHash::iterator it = std::find_if( gpus.begin(), gpus.end(), std::mem_fun(&OpenCLGpuModel::isReady) ); if( gpus.end() != it ) { (*it)->setAcquired(true); return *it; } return 0; } void OpenCLGpuRegistry::saveGpusSettings() const { Settings * s = AppContext::getSettings(); foreach( OpenCLGpuModel * m, gpus ) { QString key = OPENCL_GPU_REGISTRY_SETTINGS_GPU_SPECIFIC + QString::number(m->getId()) + OPENCL_GPU_SETTINGS_ENABLED; s->setValue( key, QVariant::fromValue(m->isEnabled()) ); } } } //namespace ugene-1.9.8/src/corelibs/U2Algorithm/src/registry/MSAAlignAlgRegistry.h0000644000175000017500000000441611651544331024430 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_MSA_ALIGN_ALG_REGISTRY_H_ #define _U2_MSA_ALIGN_ALG_REGISTRY_H_ #include #include #include #include #include namespace U2 { class MSAAlignTaskFactory; class MSAAlignGUIExtensionsFactory; class MSAAlignAlgorithmEnv; class U2ALGORITHM_EXPORT MSAAlignAlgRegistry : public QObject { Q_OBJECT public: MSAAlignAlgRegistry(QObject* pOwn = 0); ~MSAAlignAlgRegistry(); bool registerAlgorithm(MSAAlignAlgorithmEnv* env); MSAAlignAlgorithmEnv* unregisterAlgorithm(const QString& id); MSAAlignAlgorithmEnv* getAlgorithm(const QString& id) const; QStringList getRegisteredAlgorithmIds() const; private: mutable QMutex mutex; QMap algorithms; Q_DISABLE_COPY(MSAAlignAlgRegistry); }; class U2ALGORITHM_EXPORT MSAAlignAlgorithmEnv { public: MSAAlignAlgorithmEnv(const QString& id, MSAAlignTaskFactory* tf , MSAAlignGUIExtensionsFactory* guiExt); virtual ~MSAAlignAlgorithmEnv(); const QString& getId() const {return id;} MSAAlignTaskFactory* getTaskFactory() const {return taskFactory;} MSAAlignGUIExtensionsFactory* getGUIExtFactory() const {return guiExtFactory;} private: Q_DISABLE_COPY(MSAAlignAlgorithmEnv); protected: QString id; MSAAlignTaskFactory* taskFactory; MSAAlignGUIExtensionsFactory* guiExtFactory; }; } // namespace #endif ugene-1.9.8/src/corelibs/U2Algorithm/src/registry/DnaAssemblyTask.h0000644000175000017500000000555611651544331023713 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_DNA_ASSEMBLY_TASK_H_ #define _U2_DNA_ASSEMBLY_TASK_H_ #include #include #include #include #include namespace U2 { class Document; class U2ALGORITHM_EXPORT DnaAssemblyToRefTaskSettings { public: DnaAssemblyToRefTaskSettings() : prebuiltIndex(false), openView(false), samOutput(true) {} void setCustomSettings(const QMap& settings); QVariant getCustomValue(const QString& optionName, const QVariant& defaultVal) const; bool hasCustomValue(const QString & name) const; void setCustomValue(const QString& optionName, const QVariant& val); public: QList shortReads; QList shortReadUrls; GUrl refSeqUrl; GUrl resultFileName; QString indexFileName; QString algName; bool prebuiltIndex; bool openView; bool samOutput; private: QMap customSettings; }; class U2ALGORITHM_EXPORT DnaAssemblyToReferenceTask : public Task { Q_OBJECT public: DnaAssemblyToReferenceTask(const DnaAssemblyToRefTaskSettings& settings, TaskFlags flags = TaskFlags_FOSCOE, bool justBuildIndex = false); virtual ~DnaAssemblyToReferenceTask() {} bool isHaveResult() const {return haveResults;} protected: const DnaAssemblyToRefTaskSettings& settings; bool justBuildIndex; bool haveResults; }; class U2ALGORITHM_EXPORT DnaAssemblyToRefTaskFactory { public: virtual DnaAssemblyToReferenceTask* createTaskInstance(const DnaAssemblyToRefTaskSettings& settings, bool justBuildIndex = false) = 0; virtual ~DnaAssemblyToRefTaskFactory() {} }; #define DNA_ASSEMBLEY_TO_REF_TASK_FACTORY(c) \ public: \ static const QString taskName; \ class Factory : public DnaAssemblyToRefTaskFactory { \ public: \ Factory() { } \ DnaAssemblyToReferenceTask* createTaskInstance(const DnaAssemblyToRefTaskSettings& s, bool justBuildIndex = false) { return new c(s, justBuildIndex); } \ }; } // U2 #endif // _U2_DNA_ASSEMBLEY_TASK_H_ ugene-1.9.8/src/corelibs/U2Algorithm/src/registry/SecStructPredictAlgRegistry.cpp0000644000175000017500000000362411651544331026622 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include #include "SecStructPredictAlgRegistry.h" #include namespace U2 { SecStructPredictAlgRegistry::SecStructPredictAlgRegistry( QObject* pOwn /*= 0*/ ) : QObject(pOwn) { } SecStructPredictAlgRegistry::~SecStructPredictAlgRegistry() { foreach( SecStructPredictTaskFactory* factory, algMap.values()) { delete factory; } } bool SecStructPredictAlgRegistry::registerAlgorithm( SecStructPredictTaskFactory* alg, const QString& algId ) { QMutexLocker locker(&mutex); if (algMap.contains(algId)){ return false; } algMap.insert(algId, alg); return true; } bool SecStructPredictAlgRegistry::hadRegistered( const QString& algId ) { return algMap.contains(algId); } SecStructPredictTaskFactory* SecStructPredictAlgRegistry::getAlgorithm( const QString& algId ) { if (algMap.contains(algId)) { return algMap.value(algId); } else { return NULL; } } QStringList SecStructPredictAlgRegistry::getAlgNameList() { return algMap.keys(); } } ugene-1.9.8/src/corelibs/U2Algorithm/src/registry/SubstMatrixRegistry.h0000644000175000017500000000344611651544331024700 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_SUBST_MATRIX_REGISTRY_H_ #define _U2_SUBST_MATRIX_REGISTRY_H_ #include #include #include #include #include namespace U2 { class U2ALGORITHM_EXPORT SubstMatrixRegistry : public QObject { Q_OBJECT public: SubstMatrixRegistry(QObject* pOwn = 0); SMatrix getMatrix(const QString& name); QList getMatrices() const; QStringList getMatrixNames() const; QList selectMatricesByAlphabet(DNAAlphabet* al) const; QStringList selectMatrixNamesByAlphabet(DNAAlphabet* al) const; void registerMatrix(const SMatrix& m); static SMatrix readMatrixFromFile(const QString& fileName, QString& error); private: void readMatrices(); static SMatrix parseMatrix(const QString& name, const QByteArray& text, QString& error); mutable QMutex mutex; QMap matrixByName; }; } // namespace #endif ugene-1.9.8/src/corelibs/U2Algorithm/src/registry/DnaAssemblyAlgRegistry.cpp0000644000175000017500000000535411651544331025574 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "DnaAssemblyAlgRegistry.h" #include #include namespace U2 { DnaAssemblyAlgorithmEnv::DnaAssemblyAlgorithmEnv(const QString& _id, DnaAssemblyToRefTaskFactory* _tf, DnaAssemblyGUIExtensionsFactory* _g, bool indexSupported, bool _sd) : id(_id), taskFactory(_tf), guiExtFactory(_g), supportsIndexFiles(indexSupported), supportsDbi(_sd) { } DnaAssemblyAlgorithmEnv::~DnaAssemblyAlgorithmEnv() { delete taskFactory; delete guiExtFactory; } DnaAssemblyAlgRegistry::DnaAssemblyAlgRegistry( QObject* pOwn /*= 0*/ ) : QObject(pOwn) { } DnaAssemblyAlgRegistry::~DnaAssemblyAlgRegistry() { foreach( DnaAssemblyAlgorithmEnv* algo, algorithms.values()) { delete algo; } } bool DnaAssemblyAlgRegistry::registerAlgorithm(DnaAssemblyAlgorithmEnv* algo) { QMutexLocker locker(&mutex); if (algorithms.contains(algo->getId())){ return false; } algorithms.insert(algo->getId(), algo); return true; } DnaAssemblyAlgorithmEnv* DnaAssemblyAlgRegistry::unregisterAlgorithm(const QString& id) { QMutexLocker locker(&mutex); if (!algorithms.contains(id)) { return NULL; } DnaAssemblyAlgorithmEnv* res = algorithms.value(id); algorithms.remove(id); return res; } DnaAssemblyAlgorithmEnv* DnaAssemblyAlgRegistry::getAlgorithm( const QString& id) const { QMutexLocker locker(&mutex); return algorithms.value(id); } QStringList DnaAssemblyAlgRegistry::getRegisteredAlgorithmIds() const { return algorithms.keys(); } QStringList DnaAssemblyAlgRegistry::getRegisteredAlgorithmsWithIndexFileSupport() const { QStringList result; foreach( DnaAssemblyAlgorithmEnv* algo, algorithms.values()) { if (algo->isIndexFilesSupported()) { result << algo->getId(); } } return result; } } //namespace ugene-1.9.8/src/corelibs/U2Algorithm/src/registry/DnaAssemblyTask.cpp0000644000175000017500000000342011651544331024232 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "DnaAssemblyTask.h" namespace U2 { DnaAssemblyToReferenceTask::DnaAssemblyToReferenceTask( const DnaAssemblyToRefTaskSettings& s, TaskFlags _flags, bool _justBuildIndex ) : Task("DnaAssemblyToRefTask", _flags), settings(s), justBuildIndex(_justBuildIndex) { } QVariant DnaAssemblyToRefTaskSettings::getCustomValue( const QString& optionName, const QVariant& defaultVal ) const { if (customSettings.contains(optionName)) { return customSettings.value(optionName); } else { return defaultVal; } } bool DnaAssemblyToRefTaskSettings::hasCustomValue(const QString & name) const { return customSettings.contains(name); } void DnaAssemblyToRefTaskSettings::setCustomValue( const QString& optionName, const QVariant& val ) { customSettings.insert(optionName,val); } void DnaAssemblyToRefTaskSettings::setCustomSettings( const QMap& settings ) { customSettings = settings; } } // U2 ugene-1.9.8/src/corelibs/U2Algorithm/src/registry/SecStructPredictTask.cpp0000644000175000017500000000206311651544331025264 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "SecStructPredictTask.h" namespace U2 { SecStructPredictTask::SecStructPredictTask(const QByteArray& seq) : Task (tr("Secondary structure predict"), TaskFlag_None), sequence(seq) { } } //namespace ugene-1.9.8/src/corelibs/U2Algorithm/src/registry/MSAAlignTask.h0000644000175000017500000000467011651544331023100 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_MSA_ALIGN_TASK_H_ #define _U2_MSA_ALIGN_TASK_H_ #include #include #include #include #include #include namespace U2 { class Document; class U2ALGORITHM_EXPORT MSAAlignTaskSettings { public: MSAAlignTaskSettings() : loadResultDocument(false), useAminoMode(false) {} GUrl resultFileName; QString algName; bool loadResultDocument; bool useAminoMode; void setCustomSettings(const QMap& settings); QVariant getCustomValue(const QString& optionName, const QVariant& defaultVal) const; void setCustomValue(const QString& optionName, const QVariant& val); private: QMap customSettings; }; class U2ALGORITHM_EXPORT MSAAlignTask : public Task { Q_OBJECT public: MSAAlignTask(MAlignmentObject* obj, const MSAAlignTaskSettings& settings, TaskFlags flags = TaskFlags_FOSCOE); virtual ~MSAAlignTask() {} protected: MAlignmentObject* obj; const MSAAlignTaskSettings& settings; }; class U2ALGORITHM_EXPORT MSAAlignTaskFactory { public: virtual MSAAlignTask* createTaskInstance(MAlignmentObject* obj, const MSAAlignTaskSettings& settings) = 0; virtual ~MSAAlignTaskFactory() {} }; #define MSA_ALIGN_TASK_FACTORY(c) \ public: \ static const QString taskName; \ class Factory : public MSAAlignTaskFactory { \ public: \ Factory() { } \ MSAAlignTask* createTaskInstance(MAlignmentObject* obj, const MSAAlignTaskSettings& s) { return new c(obj, s); } \ }; } // U2 #endif // _U2_MSA_ALIGN_TASK_H_ ugene-1.9.8/src/corelibs/U2Algorithm/src/registry/SubstMatrixRegistry.cpp0000644000175000017500000001716311651544331025234 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "SubstMatrixRegistry.h" #include #include #include namespace U2 { SubstMatrixRegistry::SubstMatrixRegistry(QObject* pOwn) : QObject(pOwn) { readMatrices(); } SMatrix SubstMatrixRegistry::getMatrix(const QString& name) { QMutexLocker lock(&mutex); return matrixByName.value(name); } QList SubstMatrixRegistry::getMatrices() const { QMutexLocker lock(&mutex); return matrixByName.values(); } QStringList SubstMatrixRegistry::getMatrixNames() const { QMutexLocker lock(&mutex); QStringList result; foreach(const SMatrix& m, matrixByName.values()) { result.append(m.getName()); } return result; } QList SubstMatrixRegistry::selectMatricesByAlphabet(DNAAlphabet* al) const { QMutexLocker lock(&mutex); QList result; foreach(const SMatrix& m, getMatrices()) { if (m.getAlphabet() == al) { result.append(m); } } return result; } QStringList SubstMatrixRegistry::selectMatrixNamesByAlphabet(DNAAlphabet* al) const { QMutexLocker lock(&mutex); QStringList result; foreach(const SMatrix& m, matrixByName.values()) { DNAAlphabet* mAlpha = m.getAlphabet(); if (al->getType() == mAlpha->getType() && al->getNumAlphabetChars() <= mAlpha->getNumAlphabetChars()) { result.append(m.getName()); } } result.sort(); return result; } void SubstMatrixRegistry::registerMatrix(const SMatrix& m) { assert(!m.isEmpty()); QMutexLocker lock(&mutex); matrixByName[m.getName()] = m; } void SubstMatrixRegistry::readMatrices() { QString builtInMatrixDir = QDir::searchPaths( PATH_PREFIX_DATA ).first() + "/weight_matrix"; QStringList ls = QDir(builtInMatrixDir).entryList(QStringList("*.txt")); for (int i = 0; i < ls.size(); i++) { const QString& fileName = ls.at(i); QFileInfo fi(builtInMatrixDir + "/" + fileName); coreLog.details(tr("Reading substitution matrix from %1").arg(fi.canonicalFilePath())); QString error; SMatrix matrix = readMatrixFromFile(fi.canonicalFilePath(), error); if (!matrix.isEmpty()) { assert(error.isEmpty()); registerMatrix(matrix); } else { assert(!error.isEmpty()); coreLog.error(tr("Error weight matrix file '%1' : %2").arg(fi.canonicalFilePath()).arg(error)); } } } SMatrix SubstMatrixRegistry::readMatrixFromFile(const QString& fileName, QString& error) { QFile file(fileName); if (!file.open(QIODevice::ReadOnly)) { error = tr("Error opening file for read: %1").arg(fileName); return SMatrix(); } int fileSize = (int)file.size(); QByteArray data(fileSize, 0); int readSize = file.read(data.data(), fileSize); if (readSize!=fileSize) { error = tr("Error reading file: %1").arg(fileName); return SMatrix(); } return parseMatrix(QFileInfo(fileName).completeBaseName(), data, error); } SMatrix SubstMatrixRegistry::parseMatrix(const QString& name, const QByteArray& text, QString& error) { QList lines = text.split('\n'); QByteArray alphaRow; QList charScores; QString description; DNAAlphabet* alphabet = NULL; QByteArray mappedAlphas; //cache of mapped characters. Used to check that no character is mapped twice // put comments into description for (int i=0; i < lines.length(); i++) { QString line = lines.at(i).trimmed(); if (line.isEmpty()) { continue; } if (line.startsWith("#")) { QString commentLine = line.mid(1).trimmed(); if (line.isEmpty() && commentLine.isEmpty()) { continue; //skip first empty lines } description += commentLine + "\n"; continue; } if (alphaRow.isEmpty()) { // this is the first row with symbols QStringList tokens = line.simplified().split(' '); foreach (const QString& token, tokens) { if (token.length() != 1) { error = tr("Invalid character token '%1' , line %2").arg(token).arg(i+1); return SMatrix(); } char c = token.at(0).toUpper().toAscii(); if (alphaRow.contains(c)) { error = tr("Duplicate character '%1' , line %2").arg(token).arg(i+1); return SMatrix(); } alphaRow.append(c); } alphabet = AppContext::getDNAAlphabetRegistry()->findAlphabet(alphaRow); if (!alphabet->isAmino() && !alphabet->isNucleic()) { error = tr("Alphabet is neither nucleic nor protein!"); return SMatrix(); } if (!alphaRow.contains(alphabet->getDefaultSymbol())) { error = tr("Matrix doesn't contains score for default alphabet character '%1'").arg(alphabet->getDefaultSymbol()); return SMatrix(); } } else { // this is the [second +] row with scores QStringList tokens = line.simplified().split(' '); QString token = tokens.at(0); if (token.length() !=1 ) { error = tr("Invalid character token '%1' , line %2").arg(token).arg(i+1); return SMatrix(); } char c1 = token.at(0).toUpper().toAscii(); if (!alphaRow.contains(c1)) { error = tr("Invalid character row '%1' , line %2").arg(token).arg(i+1); return SMatrix(); } if (mappedAlphas.contains(c1)) { error = tr("Duplicate character mapping '%1' , line %2").arg(token).arg(i+1); return SMatrix(); } mappedAlphas.append(c1); if (tokens.length() - 1 != alphaRow.length()) { error = tr("Invalid number of columns '%1' , line %2").arg(tokens.length()).arg(i+1); return SMatrix(); } for (int j=1; j < tokens.length(); j++) { const QString& weightToken = tokens.at(j); bool ok = true; float weight = weightToken.toFloat(&ok); if (!ok) { error = tr("Can't parse numeric value '%1', line %2").arg(weightToken).arg(i+1); return SMatrix(); } char c2 = alphaRow.at(j-1); charScores.append(SScore(c1, c2, weight)); } } } if (alphabet == NULL) { error = tr("Unexpected end of file!"); return SMatrix(); } assert(alphaRow.size() > 0 && charScores.size() == alphaRow.size()*alphaRow.size()); return SMatrix(name, alphabet, charScores, description); } } // namespace ugene-1.9.8/src/corelibs/U2Algorithm/src/registry/MSAAlignAlgRegistry.cpp0000644000175000017500000000444311651544331024763 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "MSAAlignAlgRegistry.h" #include #include namespace U2 { MSAAlignAlgorithmEnv::MSAAlignAlgorithmEnv(const QString& _id, MSAAlignTaskFactory* _tf, MSAAlignGUIExtensionsFactory* _g) : id(_id), taskFactory(_tf), guiExtFactory(_g) { } MSAAlignAlgorithmEnv::~MSAAlignAlgorithmEnv() { delete taskFactory; delete guiExtFactory; } MSAAlignAlgRegistry::MSAAlignAlgRegistry( QObject* pOwn /*= 0*/ ) : QObject(pOwn) { } MSAAlignAlgRegistry::~MSAAlignAlgRegistry() { foreach( MSAAlignAlgorithmEnv* algo, algorithms.values()) { delete algo; } } bool MSAAlignAlgRegistry::registerAlgorithm(MSAAlignAlgorithmEnv* algo) { QMutexLocker locker(&mutex); if (algorithms.contains(algo->getId())){ return false; } algorithms.insert(algo->getId(), algo); return true; } MSAAlignAlgorithmEnv* MSAAlignAlgRegistry::unregisterAlgorithm(const QString& id) { QMutexLocker locker(&mutex); if (!algorithms.contains(id)) { return NULL; } MSAAlignAlgorithmEnv* res = algorithms.value(id); algorithms.remove(id); return res; } MSAAlignAlgorithmEnv* MSAAlignAlgRegistry::getAlgorithm( const QString& id) const { QMutexLocker locker(&mutex); return algorithms.value(id); } QStringList MSAAlignAlgRegistry::getRegisteredAlgorithmIds() const { return algorithms.keys(); } } //namespace ugene-1.9.8/src/corelibs/U2Algorithm/src/registry/DnaAssemblyAlgRegistry.h0000644000175000017500000000521611651544331025236 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_DNA_ASSEMBLY_ALG_REGISTRY_H_ #define _U2_DNA_ASSEMBLY_ALG_REGISTRY_H_ #include #include #include #include #include namespace U2 { class DnaAssemblyToRefTaskFactory; class DnaAssemblyGUIExtensionsFactory; class DnaAssemblyAlgorithmEnv; class U2ALGORITHM_EXPORT DnaAssemblyAlgRegistry : public QObject { Q_OBJECT public: DnaAssemblyAlgRegistry(QObject* pOwn = 0); ~DnaAssemblyAlgRegistry(); bool registerAlgorithm(DnaAssemblyAlgorithmEnv* env); DnaAssemblyAlgorithmEnv* unregisterAlgorithm(const QString& id); DnaAssemblyAlgorithmEnv* getAlgorithm(const QString& id) const; QStringList getRegisteredAlgorithmIds() const; QStringList getRegisteredAlgorithmsWithIndexFileSupport() const; private: mutable QMutex mutex; QMap algorithms; Q_DISABLE_COPY(DnaAssemblyAlgRegistry); }; class U2ALGORITHM_EXPORT DnaAssemblyAlgorithmEnv { public: DnaAssemblyAlgorithmEnv(const QString& id, DnaAssemblyToRefTaskFactory* tf , DnaAssemblyGUIExtensionsFactory* guiExt, bool supportsIndexFiles, bool supportsDbi); virtual ~DnaAssemblyAlgorithmEnv(); const QString& getId() const {return id;} bool isIndexFilesSupported() const {return supportsIndexFiles;} bool isDbiSupported() const {return supportsDbi;} DnaAssemblyToRefTaskFactory* getTaskFactory() const {return taskFactory;} DnaAssemblyGUIExtensionsFactory* getGUIExtFactory() const {return guiExtFactory;} private: Q_DISABLE_COPY(DnaAssemblyAlgorithmEnv); protected: QString id; DnaAssemblyToRefTaskFactory* taskFactory; DnaAssemblyGUIExtensionsFactory* guiExtFactory; bool supportsIndexFiles; bool supportsDbi; }; } // namespace #endif ugene-1.9.8/src/corelibs/U2Algorithm/src/registry/CDSearchTaskFactoryRegistry.h0000644000175000017500000000412211651544331026172 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_CDS_FACTORY_REGISTRY_H_ #define _U2_CDS_FACTORY_REGISTRY_H_ #include namespace U2 { class U2ALGORITHM_EXPORT CDSearchFactoryRegistry : public QObject { Q_OBJECT public: CDSearchFactoryRegistry() : localSearchFactory(NULL), remoteSearchFactory(NULL) {} ~CDSearchFactoryRegistry() { delete localSearchFactory; delete remoteSearchFactory; } enum SearchType { LocalSearch, RemoteSearch }; void registerFactory(CDSearchFactory* factory, SearchType type) { if (type == LocalSearch) { assert(localSearchFactory == NULL); localSearchFactory = factory; } else if (type == RemoteSearch) { assert(remoteSearchFactory == NULL); remoteSearchFactory = factory; } else { assert(0); } } CDSearchFactory* getFactory(SearchType type) const { if (type == LocalSearch) { return localSearchFactory; } else if (type == RemoteSearch) { return remoteSearchFactory; } else { assert(0); return NULL; } } private: CDSearchFactory* localSearchFactory; CDSearchFactory* remoteSearchFactory; }; } //namespace #endif ugene-1.9.8/src/corelibs/U2Algorithm/src/registry/MSAAlignTask.cpp0000644000175000017500000000306611651544331023431 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "MSAAlignTask.h" namespace U2 { MSAAlignTask::MSAAlignTask(MAlignmentObject* _obj, const MSAAlignTaskSettings& s, TaskFlags _flags) : Task("MSAAlignTask", _flags), obj(_obj), settings(s) {} QVariant MSAAlignTaskSettings::getCustomValue( const QString& optionName, const QVariant& defaultVal ) const { if (customSettings.contains(optionName)) { return customSettings.value(optionName); } else { return defaultVal; } } void MSAAlignTaskSettings::setCustomValue( const QString& optionName, const QVariant& val ) { customSettings.insert(optionName,val); } void MSAAlignTaskSettings::setCustomSettings( const QMap& settings ) { customSettings = settings; } } // U2 ugene-1.9.8/src/corelibs/U2Algorithm/src/registry/OpenCLGpuRegistry.h0000644000175000017500000000742411651544331024207 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef __OPEN_CL_GPU_REGISTRY_H__ #define __OPEN_CL_GPU_REGISTRY_H__ #include #include #include namespace U2 { typedef long OpenCLGpuId; #define OPENCL_GPU_REGISTRY_SETTINGS "/opencl_gpu_registry" //stores settings for concrete GPU. The key for appending - textual representation of OpenCLGpuId #define OPENCL_GPU_REGISTRY_SETTINGS_GPU_SPECIFIC "/opencl_gpu_registry/gpu_specific" #define OPENCL_GPU_SETTINGS_ENABLED "/enabled" class U2ALGORITHM_EXPORT OpenCLGpuModel { public: OpenCLGpuModel( const QString & _name, const OpenCLGpuId & _id, quint64 _platformId, quint64 _globalMemorySizeBytes, quint64 _localMemorySizeBytes, quint32 _maxComputeUnits, size_t _maxWorkGroupSize, quint32 _maxClockFrequency, bool _enabled = true) : name(_name), id(_id), platformId(_platformId), globalMemorySizeBytes(_globalMemorySizeBytes), localMemorySizeBytes(_localMemorySizeBytes), maxComputeUnits(_maxComputeUnits), maxWorkGroupSize(_maxWorkGroupSize), maxClockFrequency(_maxClockFrequency), enabled(_enabled), acquired(false) {}; QString getName() const {return name;} OpenCLGpuId getId() const {return id;} quint64 getGlobalMemorySizeBytes() const {return globalMemorySizeBytes;} quint64 getLocalMemorySizeBytes() const {return localMemorySizeBytes;} quint32 getMaxComputeUnits() const {return maxComputeUnits;} size_t getMaxWorkGroupSize() const {return maxWorkGroupSize;} quint32 getMaxClockFrequency() const {return maxClockFrequency;} quint64 getPlatformId() const {return platformId;} bool isEnabled() const {return enabled;} void setEnabled(bool b) {enabled = b;} bool isAcquired() const {return acquired;} void setAcquired( bool a) {acquired = a;} bool isReady() {return !isAcquired() && isEnabled(); } private: //TODO: add another opencl device properties QString name; OpenCLGpuId id; quint64 platformId; quint64 globalMemorySizeBytes; quint64 localMemorySizeBytes; quint32 maxComputeUnits; size_t maxWorkGroupSize; quint32 maxClockFrequency; bool enabled; bool acquired; }; class U2ALGORITHM_EXPORT OpenCLGpuRegistry { public: ~OpenCLGpuRegistry(); void registerOpenCLGpu( OpenCLGpuModel * gpu ); OpenCLGpuModel * getGpuById( OpenCLGpuId id ) const; QList getRegisteredGpus() const; OpenCLGpuModel * getAnyEnabledGpu() const; OpenCLGpuModel * acquireAnyReadyGpu(); bool empty() const { return gpus.empty(); } const OpenCLHelper& getOpenCLHelper() {return openCLHelper;} private: void saveGpusSettings() const; QHash< OpenCLGpuId, OpenCLGpuModel * > gpus; OpenCLHelper openCLHelper; }; } //namespace #endif //__OPEN_CL_GPU_REGISTRY_H__ ugene-1.9.8/src/corelibs/U2Algorithm/src/util_msa_consensus/0000755000175000017500000000000011651544331022547 5ustar ilyailyaugene-1.9.8/src/corelibs/U2Algorithm/src/util_msa_consensus/MSAConsensusAlgorithmLevitsky.cpp0000644000175000017500000001225711651544331031205 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "MSAConsensusAlgorithmLevitsky.h" #include namespace U2 { MSAConsensusAlgorithmFactoryLevitsky::MSAConsensusAlgorithmFactoryLevitsky(QObject* p) : MSAConsensusAlgorithmFactory(BuiltInConsensusAlgorithms::LEVITSKY_ALGO, ConsensusAlgorithmFlags(ConsensusAlgorithmFlag_Nucleic ) | ConsensusAlgorithmFlag_SupportThreshold, p) { } QString MSAConsensusAlgorithmFactoryLevitsky::getDescription() const { return tr("The algorithm proposed by Victor Levitsky to work with DNA alignments.\n" \ "Collects global alignment frequency for every symbol using extended (15 symbols) DNA alphabet first.\n" \ "For every column selects the most rare symbol in the whole alignment with percentage in the column " \ "greater or equals to the threshold value." ); } QString MSAConsensusAlgorithmFactoryLevitsky::getName() const { return tr("Levitsky"); } MSAConsensusAlgorithm* MSAConsensusAlgorithmFactoryLevitsky::createAlgorithm(const MAlignment& ma, QObject* p) { return new MSAConsensusAlgorithmLevitsky(this, ma, p); } ////////////////////////////////////////////////////////////////////////// // Algorithm /* Code table from Victor Levitsky: A A 1 T T 1 G G 1 C C 1 W A,T 2 WEAK R A,G 2 PURINE M A,C 2 AMINO- (+ charge) K T,G 2 KETO- (- charge) Y T,C 2 PYRIMIDINE S G,C 2 STRONG B T,G,C 3 not A (B is near with A in Latin alphabet) V A,G,C 3 not T (---||---) H A,T,C 3 not G (---||---) D A,T,G 3 not C (---||---) N A,T,G,C 4 Any */ static void registerHit(int* data, char c) { int idx = uchar(c); data[idx]++; switch(c) { case 'A': data['W']++; data['R']++; data['M']++; data['V']++; data['H']++; data['D']++; data['N']++; break; case 'C': data['M']++; data['Y']++; data['S']++; data['B']++; data['V']++; data['H']++; data['N']++; break; case 'G': data['R']++; data['K']++; data['S']++; data['B']++; data['V']++; data['D']++; data['N']++; break; case 'T': case 'U': data['W']++; data['K']++; data['Y']++; data['B']++; data['H']++; data['D']++; data['N']++; break; } } MSAConsensusAlgorithmLevitsky::MSAConsensusAlgorithmLevitsky(MSAConsensusAlgorithmFactoryLevitsky* f, const MAlignment& ma, QObject* p) : MSAConsensusAlgorithm(f, p) { globalFreqs.resize(256); qMemSet(globalFreqs.data(), 0, globalFreqs.size() * 4); int* freqsData = globalFreqs.data(); int len = ma.getLength(); foreach (const MAlignmentRow& row, ma.getRows()) { for (int i = 0; i < len; i++) { char c = row.chatAt(i); registerHit(freqsData, c); } } } char MSAConsensusAlgorithmLevitsky::getConsensusChar(const MAlignment& msa, int column) const { // count local freqs first QVarLengthArray localFreqs(256); qMemSet(localFreqs.data(), 0, localFreqs.size() * 4); int* freqsData = localFreqs.data(); int nSeq = msa.getNumRows(); for (int seq = 0; seq < nSeq; seq++) { char c = msa.charAt(seq, column); registerHit(freqsData, c); } //find all symbols with freq > threshold, select one with the lowest global freq char selectedChar = MAlignment_GapChar; int selectedGlobalFreq = nSeq * msa.getLength(); int thresholdScore = getThreshold(); int minFreq = int(float(nSeq) * thresholdScore / 100); for (int c = 'A'; c <= 'Y'; c++) { int localFreq = freqsData[uchar(c)]; if (localFreq < minFreq) { continue; } int globalFreq = globalFreqs[uchar(c)]; if (globalFreq < selectedGlobalFreq) { selectedGlobalFreq = globalFreq; selectedChar = c; } } return selectedChar; } } //namespace ugene-1.9.8/src/corelibs/U2Algorithm/src/util_msa_consensus/MSAConsensusAlgorithmClustal.cpp0000644000175000017500000001170411651544331030776 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "MSAConsensusAlgorithmClustal.h" #include #include namespace U2 { QString MSAConsensusAlgorithmFactoryClustal::getDescription() const { return tr("Emulates ClustalW program and file format behavior."); } QString MSAConsensusAlgorithmFactoryClustal::getName() const { return tr("ClustalW"); } MSAConsensusAlgorithm* MSAConsensusAlgorithmFactoryClustal::createAlgorithm(const MAlignment&, QObject* p) { return new MSAConsensusAlgorithmClustal(this, p); } ////////////////////////////////////////////////////////////////////////// //Algorithm char MSAConsensusAlgorithmClustal::getConsensusChar(const MAlignment& msa, int pos) const { if (!msa.getAlphabet()->isAmino()) { // for nucleic alphabet work as strict algorithm but use ' ' as default char defChar = ' '; char pc = msa.getRows().first().chatAt(pos); if (pc == MAlignment_GapChar) { pc = defChar; } for (int s = 1, nSeq = msa.getNumRows(); s < nSeq; s++) { const MAlignmentRow& row = msa.getRow(s); char c = row.chatAt(pos); if (c != pc) { pc = defChar; break; } } char res = (pc == defChar) ? defChar : '*'; return res; } else { /* From ClustalW doc: '*' indicates positions which have a single, fully conserved residue ':' indicates that one of the following 'strong' groups is fully conserved: STA, NEQK, NHQK, NDEQ, QHRK, MILV, MILF, HY, FYW, '.' indicates that one of the following 'weaker' groups is fully conserved: CSA, ATV, SAG, STNK, STPA, SGND, SNDEQK, NDEQHK, NEQHRK, FVLIM, HFY */ static QByteArray strongGroups[] = {"STA", "NEQK", "NHQK", "NDEQ", "QHRK", "MILV", "MILF", "HY", "FYW"}; static QByteArray weakGroups[] = {"CSA", "ATV", "SAG", "STNK", "STPA", "SGND", "SNDEQK", "NDEQHK", "NEQHRK", "FVLIM", "HFY"}; static int maxStrongGroupLen = 4; static int maxWeakGroupLen = 6; QByteArray currentGroup; //TODO: optimize 'currentGroup' related code! for (int s = 0, nSeq = msa.getNumRows(); s < nSeq; s++) { const MAlignmentRow& row = msa.getRow(s); char c = row.chatAt(pos); if (!currentGroup.contains(c)) { currentGroup.append(c); } } char consChar = MAlignment_GapChar; if (currentGroup.size() == 1) { consChar = (currentGroup[0] == MAlignment_GapChar) ? ' ' : '*'; } else { bool ok = false; int currentLen = currentGroup.length(); const char* currentGroupData = currentGroup.data(); //check strong groups if (currentLen <= maxStrongGroupLen) { for (int sgi=0, sgn = sizeof(strongGroups) / sizeof(QByteArray); sgi < sgn && !ok; sgi++) { bool matches = true; const QByteArray& sgroup = strongGroups[sgi]; for (int j=0; j < currentLen && matches; j++) { char c = currentGroupData[j]; matches = sgroup.contains(c); } ok = matches; } if (ok) { consChar = ':'; } } //check weak groups if (!ok && currentLen <= maxWeakGroupLen) { for (int wgi=0, wgn = sizeof(weakGroups) / sizeof(QByteArray); wgi < wgn && !ok; wgi++) { bool matches = true; const QByteArray& wgroup = weakGroups[wgi]; for (int j=0; j < currentLen && matches; j++) { char c = currentGroupData[j]; matches = wgroup.contains(c); } ok = matches; } if (ok) { consChar = '.'; } } //use default if (!ok) { consChar = ' '; } } //amino return consChar; } } } //namespace ugene-1.9.8/src/corelibs/U2Algorithm/src/util_msa_consensus/MSAConsensusAlgorithmLevitsky.h0000644000175000017500000000435011651544331030645 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_MSA_CONSENSUS_ALGORITHM_LEVITSKY_H_ #define _U2_MSA_CONSENSUS_ALGORITHM_LEVITSKY_H_ #include "MSAConsensusAlgorithm.h" #include "BuiltInConsensusAlgorithms.h" #include namespace U2 { // DNA/RNA only consensus, that tries to // 1) switch to extended nucleic alphabet when there is no 100% match // 2) uses threshold score and selects the most rare (in whole alignment) symbol that has greater score class U2ALGORITHM_EXPORT MSAConsensusAlgorithmFactoryLevitsky: public MSAConsensusAlgorithmFactory { Q_OBJECT public: MSAConsensusAlgorithmFactoryLevitsky(QObject* p = NULL); virtual MSAConsensusAlgorithm* createAlgorithm(const MAlignment& ma, QObject* parent); virtual QString getDescription() const; virtual QString getName() const; virtual int getMinThreshold() const {return 50;} virtual int getMaxThreshold() const {return 100;} virtual int getDefaultThreshold() const {return 90;} virtual QString getThresholdSuffix() const {return QString("%");} }; class U2ALGORITHM_EXPORT MSAConsensusAlgorithmLevitsky: public MSAConsensusAlgorithm { Q_OBJECT public: MSAConsensusAlgorithmLevitsky(MSAConsensusAlgorithmFactoryLevitsky* f, const MAlignment& ma, QObject* p = NULL); virtual char getConsensusChar(const MAlignment& ma, int column) const; private: QVarLengthArray globalFreqs; }; }//namespace #endif ugene-1.9.8/src/corelibs/U2Algorithm/src/util_msa_consensus/MSAConsensusAlgorithmStrict.cpp0000644000175000017500000000451411651544331030640 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "MSAConsensusAlgorithmStrict.h" #include #include "MSAConsensusUtils.h" #include namespace U2 { MSAConsensusAlgorithmFactoryStrict::MSAConsensusAlgorithmFactoryStrict(QObject* p) : MSAConsensusAlgorithmFactory(BuiltInConsensusAlgorithms::STRICT_ALGO, ConsensusAlgorithmFlags_AllAlphabets | ConsensusAlgorithmFlag_SupportThreshold, p) { } QString MSAConsensusAlgorithmFactoryStrict::getDescription() const { return tr("The algorithm returns gap character ('-') if symbol frequency in a column is lower than threshold specified."); } QString MSAConsensusAlgorithmFactoryStrict::getName() const { return tr("Strict"); } MSAConsensusAlgorithm* MSAConsensusAlgorithmFactoryStrict::createAlgorithm(const MAlignment&, QObject* p) { return new MSAConsensusAlgorithmStrict(this, p); } ////////////////////////////////////////////////////////////////////////// // Algorithm char MSAConsensusAlgorithmStrict::getConsensusChar(const MAlignment& msa, int column) const { QVector freqsByChar(256, 0); int nonGaps = 0; uchar topChar = MSAConsensusUtils::getColumnFreqs(msa, column, freqsByChar, nonGaps); //use gap is top char frequency is lower than threshold int nSeq = msa.getNumRows(); int currentThreshold = getThreshold(); int cntToUseGap = int(currentThreshold / 100.0 * nSeq); int topFreq = freqsByChar[topChar]; char res = topFreq < cntToUseGap ? MAlignment_GapChar : (char)topChar; return res; } } //namespace ugene-1.9.8/src/corelibs/U2Algorithm/src/util_msa_consensus/MSAConsensusAlgorithm.h0000644000175000017500000001016311651544331027111 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_MSA_CONSENSUS_ALGORITHM_H_ #define _U2_MSA_CONSENSUS_ALGORITHM_H_ #include #include namespace U2 { class MAlignment; class MSAConsensusAlgorithm; class DNAAlphabet; enum ConsensusAlgorithmFlag { ConsensusAlgorithmFlag_Nucleic = 1 << 0, ConsensusAlgorithmFlag_Amino = 1 << 1, ConsensusAlgorithmFlag_Raw = 1 << 2, ConsensusAlgorithmFlag_SupportThreshold = 1 << 3, }; typedef QFlags ConsensusAlgorithmFlags; #define ConsensusAlgorithmFlags_AllAlphabets (ConsensusAlgorithmFlags(ConsensusAlgorithmFlag_Nucleic) | ConsensusAlgorithmFlag_Amino | ConsensusAlgorithmFlag_Raw) #define ConsensusAlgorithmFlags_NuclAmino (ConsensusAlgorithmFlags(ConsensusAlgorithmFlag_Nucleic) | ConsensusAlgorithmFlag_Amino) class U2ALGORITHM_EXPORT MSAConsensusAlgorithmFactory : public QObject { Q_OBJECT public: MSAConsensusAlgorithmFactory(const QString& algoId, ConsensusAlgorithmFlags flags, QObject* p = NULL); virtual MSAConsensusAlgorithm* createAlgorithm(const MAlignment& ma, QObject* parent = NULL) = 0; QString getId() const {return algorithmId;} ConsensusAlgorithmFlags getFlags() const {return flags;} virtual QString getDescription() const = 0; virtual QString getName() const = 0; virtual bool supportsThreshold() const {return flags.testFlag(ConsensusAlgorithmFlag_SupportThreshold);} virtual int getMinThreshold() const = 0; virtual int getMaxThreshold() const = 0; virtual int getDefaultThreshold() const = 0; virtual QString getThresholdSuffix() const {return QString();} // utility method static ConsensusAlgorithmFlags getAphabetFlags(const DNAAlphabet* al); private: QString algorithmId; ConsensusAlgorithmFlags flags; }; class U2ALGORITHM_EXPORT MSAConsensusAlgorithm : public QObject { Q_OBJECT public: MSAConsensusAlgorithm(MSAConsensusAlgorithmFactory* factory, QObject* p = NULL); /** Returns consensus char and score for the given row Score is a number: [0, num] sequences. Usually is means count of the char in the row Note that consensus character may be out of the to MSA alphabet symbols range */ virtual char getConsensusCharAndScore(const MAlignment& ma, int column, int& score) const; virtual char getConsensusChar(const MAlignment& ma, int column) const = 0; virtual QString getDescription() const {return factory->getDescription();} virtual QString getName() const {return factory->getName();} virtual void setThreshold(int val); virtual int getThreshold() const {return threshold;} bool supportsThreshold() const {return factory->supportsThreshold();} virtual int getMinThreshold() const {return factory->getMinThreshold();} virtual int getMaxThreshold() const {return factory->getMaxThreshold();} virtual int getDefaultThreshold() const {return factory->getDefaultThreshold();} virtual QString getThresholdSuffix() const {return factory->getThresholdSuffix();} QString getId() const {return factory->getId();} MSAConsensusAlgorithmFactory* getFactory() const {return factory;} signals: void si_thresholdChanged(int); private: MSAConsensusAlgorithmFactory* factory; int threshold; }; }//namespace #endif ugene-1.9.8/src/corelibs/U2Algorithm/src/util_msa_consensus/MSAConsensusAlgorithmClustal.h0000644000175000017500000000375211651544331030447 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_MSA_CONSENSUS_ALGORITHM_CLUSTAL_H_ #define _U2_MSA_CONSENSUS_ALGORITHM_CLUSTAL_H_ #include "MSAConsensusAlgorithm.h" #include "BuiltInConsensusAlgorithms.h" namespace U2 { class U2ALGORITHM_EXPORT MSAConsensusAlgorithmFactoryClustal : public MSAConsensusAlgorithmFactory { Q_OBJECT public: MSAConsensusAlgorithmFactoryClustal(QObject* p = NULL) : MSAConsensusAlgorithmFactory(BuiltInConsensusAlgorithms::CLUSTAL_ALGO, ConsensusAlgorithmFlags_AllAlphabets, p){} virtual MSAConsensusAlgorithm* createAlgorithm(const MAlignment& ma, QObject* parent); virtual QString getDescription() const; virtual QString getName() const; virtual int getMinThreshold() const {return 0;} virtual int getMaxThreshold() const {return 0;} virtual int getDefaultThreshold() const {return 0;} }; class U2ALGORITHM_EXPORT MSAConsensusAlgorithmClustal : public MSAConsensusAlgorithm { Q_OBJECT public: MSAConsensusAlgorithmClustal(MSAConsensusAlgorithmFactoryClustal* f, QObject* p = NULL) : MSAConsensusAlgorithm(f, p){} virtual char getConsensusChar(const MAlignment& ma, int column) const; }; }//namespace #endif ugene-1.9.8/src/corelibs/U2Algorithm/src/util_msa_consensus/MSAConsensusAlgorithmDefault.cpp0000644000175000017500000000566111651544331030760 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "MSAConsensusAlgorithmDefault.h" #include #include namespace U2 { MSAConsensusAlgorithmFactoryDefault::MSAConsensusAlgorithmFactoryDefault(QObject* p) : MSAConsensusAlgorithmFactory(BuiltInConsensusAlgorithms::DEFAULT_ALGO, ConsensusAlgorithmFlags_NuclAmino | ConsensusAlgorithmFlag_SupportThreshold, p) { } QString MSAConsensusAlgorithmFactoryDefault::getDescription() const { return tr("Based on JalView algorithm. Returns '+' if there are 2 characters with high frequency. Returns symbol in lower case if the symbol content in a row is lower than the threshold specified."); } QString MSAConsensusAlgorithmFactoryDefault::getName() const { return tr("Default"); } MSAConsensusAlgorithm* MSAConsensusAlgorithmFactoryDefault::createAlgorithm(const MAlignment&, QObject* p) { return new MSAConsensusAlgorithmDefault(this, p); } ////////////////////////////////////////////////////////////////////////// // Algorithm char MSAConsensusAlgorithmDefault::getConsensusCharAndScore(const MAlignment& msa, int pos, int& cnt) const { //TODO: use var-length array! QVector > freqs(32); int ch = MAlignment_GapChar; int nSeq = msa.getNumRows(); for (int seq = 0; seq < nSeq; seq++) { uchar c = (uchar)msa.charAt(seq, pos); if (c >= 'A' && c <= 'Z') { int idx = c - 'A'; assert(idx >=0 && idx <= freqs.size()); freqs[idx].first++; freqs[idx].second = c; } } qSort(freqs); int p1 = freqs[freqs.size()-1].first; int p2 = freqs[freqs.size()-2].first; if (p1 == 0 || (p1 == 1 && nSeq > 1)) { ch = MAlignment_GapChar; cnt = 0; } else { int c1 = freqs[freqs.size()-1].second; ch = p2 == p1 ? '+' : c1; cnt = p1; } //lowercase alpha chars with < threshold% content int currentThreshold = getThreshold(); int cntToUseLowerCase = int(currentThreshold / 100.0 * nSeq); if (cnt < cntToUseLowerCase && (ch >='A' && ch <='Z')) { ch = ch + ('a'-'A'); } return ch; } } //namespace ugene-1.9.8/src/corelibs/U2Algorithm/src/util_msa_consensus/MSAConsensusAlgorithmRegistry.cpp0000644000175000017500000000542111651544331031176 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "MSAConsensusAlgorithmRegistry.h" #include "MSAConsensusAlgorithmDefault.h" #include "MSAConsensusAlgorithmStrict.h" #include "MSAConsensusAlgorithmClustal.h" #include "MSAConsensusAlgorithmLevitsky.h" namespace U2 { MSAConsensusAlgorithmRegistry::MSAConsensusAlgorithmRegistry(QObject* p) : QObject(p) { addAlgorithm(new MSAConsensusAlgorithmFactoryDefault()); addAlgorithm(new MSAConsensusAlgorithmFactoryStrict()); addAlgorithm(new MSAConsensusAlgorithmFactoryClustal()); addAlgorithm(new MSAConsensusAlgorithmFactoryLevitsky()); } MSAConsensusAlgorithmRegistry::~MSAConsensusAlgorithmRegistry() { QList list = algorithms.values(); foreach(MSAConsensusAlgorithmFactory* algo, list) { delete algo; } } MSAConsensusAlgorithmFactory* MSAConsensusAlgorithmRegistry::getAlgorithmFactory(const QString& algoId) { return algorithms.value(algoId); } void MSAConsensusAlgorithmRegistry::addAlgorithm(MSAConsensusAlgorithmFactory* algo) { const QString& id = algo->getId(); MSAConsensusAlgorithmFactory* oldVersion = algorithms.value(id); if (oldVersion!=NULL) { delete oldVersion; oldVersion = NULL; } algorithms[id] = algo; } QStringList MSAConsensusAlgorithmRegistry::getAlgorithmIds() const { QList list = algorithms.values(); QStringList result; foreach(MSAConsensusAlgorithmFactory* algo, list) { result.append(algo->getId()); } return result; } QList MSAConsensusAlgorithmRegistry::getAlgorithmFactories(ConsensusAlgorithmFlags flags) const { QList allFactories = getAlgorithmFactories(); QList result; foreach(MSAConsensusAlgorithmFactory* f, allFactories) { if ((flags & f->getFlags()) == flags) { result.append(f); } } return result; } }//namespace ugene-1.9.8/src/corelibs/U2Algorithm/src/util_msa_consensus/MSAConsensusUtils.cpp0000644000175000017500000001357211651544331026625 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "MSAConsensusUtils.h" #include "MSAConsensusAlgorithm.h" #include #include #include namespace U2 { void MSAConsensusUtils::updateConsensus(const MAlignment& msa, QByteArray& cons, MSAConsensusAlgorithm* algo) { U2Region r(0, msa.getLength()); updateConsensus(msa, r, cons, algo); } void MSAConsensusUtils::updateConsensus(const MAlignment& msa, const U2Region& region, QByteArray& cons, MSAConsensusAlgorithm* algo) { QVector l; l.append(region); updateConsensus(msa, l, cons, algo); } void MSAConsensusUtils::updateConsensus(const MAlignment& msa, const QVector& regions, QByteArray& cons, MSAConsensusAlgorithm* algo) { if (msa.isEmpty()) { return; } int aliLen = msa.getLength(); if (cons.length()!=aliLen) { cons.resize(aliLen); } foreach(const U2Region& r, regions) { for (int i = r.startPos, n = r.endPos(); i < n ; i++) { cons[i] = algo->getConsensusChar(msa, i); } } } QString MSAConsensusUtils::getConsensusPercentTip(const MAlignment& msa, int pos, int minReportPercent, int maxReportChars) { QVector > freqs(32); //TODO: try QVarLengthArray? assert(pos>=0 && pos < msa.getLength()); int nSeq = msa.getNumRows(); assert(nSeq > 0); if (nSeq == 0) { return QString(); } int gaps = 0; for (int seq = 0; seq < nSeq; seq++) { uchar c = (uchar)msa.charAt(seq, pos); if (c >= 'A' && c <= 'Z') { int idx = c - 'A'; freqs[idx].first++; freqs[idx].second = c; } else { // count gaps ++gaps; } } qSort(freqs); double percentK = 100.0 / nSeq; QString res = ""; int i = 0; for(; i < 32; i++) { int p = freqs[freqs.size()-i-1].first; double percent = p * percentK; if (percent < minReportPercent || percent < 1.0 / nSeq) { break; } if (i == maxReportChars) { break; } int c = freqs[freqs.size()-i-1].second; res = res + ""; res = res + ""; res = res + ""; res = res + ""; } if (i == 0) { return ""; } if (i == maxReportChars) { res+=""; } // adding gaps statstics if (gaps != 0) { double gapsPercent = gaps*percentK; res += ""; res = res + ""; res = res + ""; res = res + ""; } res+="
    " + QChar(c) + "" + QString::number(percent, 'f', 1) + "%" + QString::number(p) + "
    ...
    " + QObject::tr("Gaps:") + "" + QString::number(gapsPercent, 'f', 1) + "%" + QString::number(gaps) + "
    "; return res; } void MSAConsensusUtils::unpackConsensusCharsFromInt(quint32 val, char* charVal, int* maskPos) { for (int i = 0; i < 4; i++) { quint32 byteVal = (val >> (i * 8)) & 0xFF; maskPos[i] = byteVal >> 5; charVal[i] = (maskPos[i] < 4) ? (byteVal & 0x1F) + 'A' : 0; } } uchar MSAConsensusUtils::getColumnFreqs(const MAlignment& ma, int pos, QVector& freqsByChar, int& nonGapChars) { assert(freqsByChar.size() == 256); freqsByChar.fill(0); nonGapChars = 0; uchar maxC = 0; int maxCFreq = 0; int* freqs = freqsByChar.data(); int nSeq = ma.getNumRows(); for (int seq = 0; seq < nSeq; seq++) { uchar c = (uchar)ma.charAt(seq, pos); freqs[c]++; if (c!=MAlignment_GapChar && freqs[c] > maxCFreq) { maxCFreq = freqs[c]; maxC = c; } if (c!=MAlignment_GapChar) { nonGapChars++; } } return maxC; } quint32 MSAConsensusUtils::packConsensusCharsToInt(const MAlignment& msa, int pos, const int* mask4, bool gapsAffectPercents) { QVector > freqs(32); int numNoGaps = 0; int nSeq = msa.getNumRows(); for (int seq = 0; seq < nSeq; seq++) { uchar c = (uchar)msa.charAt(seq, pos); if (c >= 'A' && c <= 'Z') { int idx = c - 'A'; freqs[idx].first++; freqs[idx].second = c; numNoGaps++; } } qSort(freqs); if (!gapsAffectPercents && numNoGaps == 0) { return 0xE0E0E0E0;//'4' in masks, '0' in values } int res = 0; double percentK = 100.0 / (gapsAffectPercents ? nSeq : numNoGaps); for (int i=0;i < 4;i++) { int p = int(freqs[freqs.size()-i-1].first * percentK); quint32 rangeBits = (p >= mask4[0]) ? 0 : (p >= mask4[1]) ? 1 : (p >= mask4[2]) ? 2 : (p >= mask4[3]) ? 3 : 4; quint32 charVal = rangeBits == 4 ? 'A' : quint32(freqs[freqs.size()-i-1].second); quint32 maskedVal = (rangeBits << 5) | (charVal - 'A'); //3 bits for range, 5 for symbol assert(maskedVal <= 255); res = res | (maskedVal << (8 * i)); } return res; } }//namespace ugene-1.9.8/src/corelibs/U2Algorithm/src/util_msa_consensus/BuiltInConsensusAlgorithms.h0000644000175000017500000000234211651544331030222 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_BUILT_IN_CONSENSUS_ALGORITHMS_H_ #define _U2_BUILT_IN_CONSENSUS_ALGORITHMS_H_ #include #include namespace U2 { class U2ALGORITHM_EXPORT BuiltInConsensusAlgorithms { public: static const QString DEFAULT_ALGO; static const QString CLUSTAL_ALGO; static const QString STRICT_ALGO; static const QString LEVITSKY_ALGO; }; }//namespace #endif ugene-1.9.8/src/corelibs/U2Algorithm/src/util_msa_consensus/MSAConsensusAlgorithmRegistry.h0000644000175000017500000000331011651544331030636 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_MSA_CONSENSUS_ALGORITHM_REGISTRY_H_ #define _U2_MSA_CONSENSUS_ALGORITHM_REGISTRY_H_ #include "MSAConsensusAlgorithm.h" #include namespace U2 { class MSAConsensusAlgorithm; class U2ALGORITHM_EXPORT MSAConsensusAlgorithmRegistry : public QObject { Q_OBJECT public: MSAConsensusAlgorithmRegistry(QObject* p = NULL); ~MSAConsensusAlgorithmRegistry(); MSAConsensusAlgorithmFactory* getAlgorithmFactory(const QString& algoId); void addAlgorithm(MSAConsensusAlgorithmFactory* algo); QStringList getAlgorithmIds() const ; QList getAlgorithmFactories() const {return algorithms.values();} QList getAlgorithmFactories(ConsensusAlgorithmFlags flags) const; private: QMap algorithms; }; }//namespace #endif ugene-1.9.8/src/corelibs/U2Algorithm/src/util_msa_consensus/MSAConsensusAlgorithmDefault.h0000644000175000017500000000437411651544331030425 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_MSA_CONSENSUS_ALGORITHM_DEFAULT_H_ #define _U2_MSA_CONSENSUS_ALGORITHM_DEFAULT_H_ #include "MSAConsensusAlgorithm.h" #include "BuiltInConsensusAlgorithms.h" namespace U2 { // Default algorithm is based on JalView experience. It also makes letters with low threshold lowercase class U2ALGORITHM_EXPORT MSAConsensusAlgorithmFactoryDefault: public MSAConsensusAlgorithmFactory { Q_OBJECT public: MSAConsensusAlgorithmFactoryDefault(QObject* p = NULL); virtual MSAConsensusAlgorithm* createAlgorithm(const MAlignment& ma, QObject* parent); virtual QString getDescription() const; virtual QString getName() const; virtual int getMinThreshold() const {return 1;} virtual int getMaxThreshold() const {return 100;} virtual int getDefaultThreshold() const {return 100;} virtual QString getThresholdSuffix() const {return QString("%");} }; class U2ALGORITHM_EXPORT MSAConsensusAlgorithmDefault : public MSAConsensusAlgorithm { Q_OBJECT public: MSAConsensusAlgorithmDefault(MSAConsensusAlgorithmFactoryDefault* f, QObject* p = NULL) : MSAConsensusAlgorithm(f, p){} virtual char getConsensusChar(const MAlignment& ma, int column) const { int countStub = 0; return getConsensusCharAndScore(ma, column, countStub); } virtual char getConsensusCharAndScore(const MAlignment& ma, int column, int& score) const; }; }//namespace #endif ugene-1.9.8/src/corelibs/U2Algorithm/src/util_msa_consensus/MSAConsensusUtils.h0000644000175000017500000000510111651544331026257 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_MSA_CONSENSUS_UTILS_H_ #define _U2_MSA_CONSENSUS_UTILS_H_ #include #include #include namespace U2 { class MSAConsensusAlgorithm; class MAlignment; class U2ALGORITHM_EXPORT MSAConsensusUtils : public QObject { Q_OBJECT public: static void updateConsensus(const MAlignment& msa, QByteArray& cons, MSAConsensusAlgorithm* algo); static void updateConsensus(const MAlignment& msa, const U2Region& region, QByteArray& cons, MSAConsensusAlgorithm* algo); static void updateConsensus(const MAlignment& msa, const QVector& region, QByteArray& cons, MSAConsensusAlgorithm* algo); static QString getConsensusPercentTip(const MAlignment& msa, int pos, int minReportPercent, int maxReportChars); // mask4 must contain 4 descending percent values (>= used), example: 100, 75, 50, 33 // countGaps tells if to include gaps into percent computation // result: up to 4 most used chars (from 'A' to 'Z') are packed into return value // WARN: the lowest val in mask must be >= 25 // WARN: works only for alphabet chars (A - Z) static quint32 packConsensusCharsToInt(const MAlignment& msa, int pos, const int* mask4, bool gapsAffectPercents); // up to 4 chars can be unpacked to charVal values, their percent ranges are saved to mark3Pos static void unpackConsensusCharsFromInt(quint32 val, char* charVal, int* maskPos); // computes frequency by char. Returns the most frequent char that is not gap. // nonGapChars = sum of all non-gap characters // TODO: use var-length array instead of the vector! static uchar getColumnFreqs(const MAlignment& ma, int pos, QVector& freqsByChar, int& nonGapChars); }; }//namespace #endif ugene-1.9.8/src/corelibs/U2Algorithm/src/util_msa_consensus/MSAConsensusAlgorithm.cpp0000644000175000017500000000507111651544331027446 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "MSAConsensusAlgorithm.h" #include "MSAConsensusUtils.h" #include #include #include namespace U2 { ////////////////////////////////////////////////////////////////////////// // Factory MSAConsensusAlgorithmFactory::MSAConsensusAlgorithmFactory(const QString& algoId, ConsensusAlgorithmFlags _flags, QObject* p) : QObject(p), algorithmId(algoId), flags(_flags) { } ConsensusAlgorithmFlags MSAConsensusAlgorithmFactory::getAphabetFlags(const DNAAlphabet* al) { if (al->getType() == DNAAlphabet_AMINO) { return ConsensusAlgorithmFlag_Amino; } else if (al->getType() == DNAAlphabet_NUCL) { return ConsensusAlgorithmFlag_Nucleic; } assert(al->getType() == DNAAlphabet_RAW); return ConsensusAlgorithmFlag_Raw; } ////////////////////////////////////////////////////////////////////////// // Algorithm MSAConsensusAlgorithm::MSAConsensusAlgorithm(MSAConsensusAlgorithmFactory* _factory, QObject* p) : QObject(p), factory(_factory) , threshold(0) { } char MSAConsensusAlgorithm::getConsensusCharAndScore(const MAlignment& ma, int column, int& score) const { char consensusChar = getConsensusChar(ma, column); //now compute score using most freq character int nonGaps = 0; QVector freqsByChar(256); uchar topChar = MSAConsensusUtils::getColumnFreqs(ma, column, freqsByChar, nonGaps); score = freqsByChar[topChar]; return consensusChar; } void MSAConsensusAlgorithm::setThreshold(int val) { int newThreshold = qBound(getMinThreshold(), val, getMaxThreshold()); if (newThreshold == threshold) { return; } threshold = newThreshold; emit si_thresholdChanged(newThreshold); } } //namespace ugene-1.9.8/src/corelibs/U2Algorithm/src/util_msa_consensus/BuiltInConsensusAlgorithms.cpp0000644000175000017500000000225111651544331030554 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "BuiltInConsensusAlgorithms.h" namespace U2 { const QString BuiltInConsensusAlgorithms::DEFAULT_ALGO("Default"); const QString BuiltInConsensusAlgorithms::CLUSTAL_ALGO("Clustal"); const QString BuiltInConsensusAlgorithms::STRICT_ALGO("Strict"); const QString BuiltInConsensusAlgorithms::LEVITSKY_ALGO("Levitsky"); }//namespace ugene-1.9.8/src/corelibs/U2Algorithm/src/util_msa_consensus/MSAConsensusAlgorithmStrict.h0000644000175000017500000000401511651544331030301 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_MSA_CONSENSUS_ALGORITHM_STRICT_H_ #define _U2_MSA_CONSENSUS_ALGORITHM_STRICT_H_ #include "MSAConsensusAlgorithm.h" #include "BuiltInConsensusAlgorithms.h" namespace U2 { // Strict consensus: returns non-gap character only of all characters in the column are equal class U2ALGORITHM_EXPORT MSAConsensusAlgorithmFactoryStrict: public MSAConsensusAlgorithmFactory { Q_OBJECT public: MSAConsensusAlgorithmFactoryStrict(QObject* p = NULL); virtual MSAConsensusAlgorithm* createAlgorithm(const MAlignment& ma, QObject* parent); virtual QString getDescription() const; virtual QString getName() const; virtual int getMinThreshold() const {return 1;} virtual int getMaxThreshold() const {return 100;} virtual int getDefaultThreshold() const {return 100;} virtual QString getThresholdSuffix() const {return QString("%");} }; class U2ALGORITHM_EXPORT MSAConsensusAlgorithmStrict : public MSAConsensusAlgorithm { Q_OBJECT public: MSAConsensusAlgorithmStrict(MSAConsensusAlgorithmFactoryStrict* f, QObject* p = NULL) : MSAConsensusAlgorithm(f, p){} virtual char getConsensusChar(const MAlignment& ma, int column) const; }; }//namespace #endif ugene-1.9.8/src/corelibs/U2Algorithm/src/structural_alignment/0000755000175000017500000000000011651544331023100 5ustar ilyailyaugene-1.9.8/src/corelibs/U2Algorithm/src/structural_alignment/StructuralAlignmentAlgorithmRegistry.h0000644000175000017500000000432311651544331032662 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_STRUCTURAL_ALIGNMENT_ALGORITHM_REGISTRY_H_ #define _U2_STRUCTURAL_ALIGNMENT_ALGORITHM_REGISTRY_H_ #include #include namespace U2 { class StructuralAlignmentAlgorithm; class StructuralAlignmentAlgorithmFactory; class StructuralAlignmentTask; class StructuralAlignmentTaskSettings; class U2ALGORITHM_EXPORT StructuralAlignmentAlgorithmRegistry : public QObject { Q_OBJECT public: StructuralAlignmentAlgorithmRegistry(QObject *parent = 0); ~StructuralAlignmentAlgorithmRegistry(); void registerAlgorithmFactory(StructuralAlignmentAlgorithmFactory *factory, const QString &id); StructuralAlignmentAlgorithmFactory* getAlgorithmFactory(const QString &id); StructuralAlignmentAlgorithm* createStructuralAlignmentAlgorithm(const QString &algorithm); StructuralAlignmentTask* createStructuralAlignmentTask(const QString &algorithm, const StructuralAlignmentTaskSettings &settings); QList getFactoriesIds() const; private: StructuralAlignmentAlgorithmRegistry(const StructuralAlignmentAlgorithmRegistry&); StructuralAlignmentAlgorithmRegistry& operator= (const StructuralAlignmentAlgorithmRegistry&); private: QMap factories; }; // class StructuralAlignmentAlgorithmRegistry } // namespace U2 #endif // #ifndef _U2_STRUCTURAL_ALIGNMENT_ALGORITHM_REGISTRY_H_ ././@LongLink0000000000000000000000000000014700000000000011567 Lustar rootrootugene-1.9.8/src/corelibs/U2Algorithm/src/structural_alignment/StructuralAlignmentAlgorithmRegistry.cppugene-1.9.8/src/corelibs/U2Algorithm/src/structural_alignment/StructuralAlignmentAlgorithmRegistry.c0000644000175000017500000000445011651544331032656 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "StructuralAlignmentAlgorithmRegistry.h" #include "StructuralAlignmentAlgorithmFactory.h" namespace U2 { /* class U2ALGORITHM_EXPORT StructuralAlignmentAlgorithmRegistry : public QObject */ StructuralAlignmentAlgorithmRegistry::StructuralAlignmentAlgorithmRegistry(QObject *parent) : QObject(parent), factories() { } StructuralAlignmentAlgorithmRegistry::~StructuralAlignmentAlgorithmRegistry() { foreach (StructuralAlignmentAlgorithmFactory *f, factories) { delete f; } } void StructuralAlignmentAlgorithmRegistry::registerAlgorithmFactory(StructuralAlignmentAlgorithmFactory *factory, const QString &id) { assert(!factories.contains(id)); factories.insert(id, factory); } StructuralAlignmentAlgorithmFactory* StructuralAlignmentAlgorithmRegistry::getAlgorithmFactory(const QString &id) { return factories.value(id, 0); } QList StructuralAlignmentAlgorithmRegistry::getFactoriesIds() const { return factories.keys(); } StructuralAlignmentAlgorithm* StructuralAlignmentAlgorithmRegistry::createStructuralAlignmentAlgorithm(const QString &algorithm) { return getAlgorithmFactory(algorithm)->create(); } StructuralAlignmentTask* StructuralAlignmentAlgorithmRegistry::createStructuralAlignmentTask(const QString &algorithm, const StructuralAlignmentTaskSettings &settings) { StructuralAlignmentTask *t = new StructuralAlignmentTask(getAlgorithmFactory(algorithm)->create(), settings); return t; } } // namespace U2 ././@LongLink0000000000000000000000000000014600000000000011566 Lustar rootrootugene-1.9.8/src/corelibs/U2Algorithm/src/structural_alignment/StructuralAlignmentAlgorithmFactory.cppugene-1.9.8/src/corelibs/U2Algorithm/src/structural_alignment/StructuralAlignmentAlgorithmFactory.cp0000644000175000017500000000165311651544331032637 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "StructuralAlignmentAlgorithmFactory.h" namespace U2 { } // namespace U2 ugene-1.9.8/src/corelibs/U2Algorithm/src/structural_alignment/StructuralAlignmentAlgorithm.cpp0000644000175000017500000000606511651544331031471 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "StructuralAlignmentAlgorithm.h" namespace U2 { /* class U2ALGORITHM_EXPORT BioStruct3DReference */ QString BioStruct3DReference::print() const { QString s = obj->getGObjectName(); if (chains.size() == 1) { int chainId = chains.first(); s += QString(" chain %1").arg(chainId); s += QString(" region %1..%2").arg(chainRegion.startPos + 1).arg(chainRegion.endPos()); } else { s += " chains ["; foreach (int chain, chains) { s += QString::number(chain) + ","; } s.chop(1); s += "]"; } s += QString(" model %3").arg(modelId); return s; } /* class U2ALGORITHM_EXPORT StructuralAlignmentTask : public Task */ StructuralAlignmentTask::StructuralAlignmentTask(StructuralAlignmentAlgorithm *_algorithm, const StructuralAlignmentTaskSettings &_settings) : Task("StructuralAlignmentTask", TaskFlag(TaskFlag_ReportingIsSupported | TaskFlag_ReportingIsEnabled)), algorithm(_algorithm), settings(_settings), result() {} void StructuralAlignmentTask::run() { result = algorithm->align(settings, stateInfo); } Task::ReportResult StructuralAlignmentTask::report() { return ReportResult_Finished; } QString StructuralAlignmentTask::generateReport() const { QString res; if (!hasError()) { res += QString("Structural alignment finished on %1 (reference) vs %2").arg(settings.ref.print(), settings.alt.print()) + "

    "; res += QString("RMSD = %1").arg(result.rmsd); res += "
    "; res += "Transform = "; res += ""; res += ""; res += ""; for (int i = 0; i < 16; ++i) { res += ""; if ((i+1) % 4 == 0 && i < 15) { res += "<\tr>"; } } res += ""; res += "
    " + QString::number(result.transform[i]) + "
    "; res += "
    "; } else { res += QString("Structural alignment on %1 (reference) vs %2 failed").arg(settings.ref.print(), settings.alt.print()); } return res; } } // namespace U2 ugene-1.9.8/src/corelibs/U2Algorithm/src/structural_alignment/StructuralAlignmentAlgorithm.h0000644000175000017500000000773111651544331031137 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_STRUCTURAL_ALIGNMENT_ALGORITHM_H_ #define _U2_STRUCTURAL_ALIGNMENT_ALGORITHM_H_ #include #include #include #include #include #include namespace U2 { /** Reference to a subset of BioStruct3D */ // Maybe this class must be merged with BioStruct3DChainSelection class U2ALGORITHM_EXPORT BioStruct3DReference { public: BioStruct3DReference(const BioStruct3DObject *_obj, int _chainId, const U2Region &_chainRegion, int _modelId) : obj(_obj), chains(), chainRegion(_chainRegion), modelId(_modelId) { chains << _chainId; } BioStruct3DReference(const BioStruct3DObject *_obj, const QList &_chains, int _modelId) : obj(_obj), chains(_chains), chainRegion(), modelId(_modelId) { assert(obj); // if one chain selected set region from start to end if (chains.size() == 1) { int chainId = chains.first(); int length = obj->getBioStruct3D().moleculeMap.value(chainId)->residueMap.size(); chainRegion = U2Region(0, length); } } /** Pretty print structure reference description */ QString print() const; const BioStruct3DObject *obj; QList chains; // when more than one chain selected, region ignored U2Region chainRegion; int modelId; }; // class BioStruct3DReference class U2ALGORITHM_EXPORT StructuralAlignmentTaskSettings { public: StructuralAlignmentTaskSettings(const BioStruct3DReference &_ref, const BioStruct3DReference &_alt) : ref(_ref), alt(_alt) {} BioStruct3DReference ref, alt; }; // struct StructuralAlignmentTaskSettings /** Structural alignment algorithm result */ class U2ALGORITHM_EXPORT StructuralAlignment { public: StructuralAlignment() : rmsd(0.0), transform() {} double rmsd; Matrix44 transform; }; // class StructuralAlignment /** Structural alignment algorithm abstract interface */ class U2ALGORITHM_EXPORT StructuralAlignmentAlgorithm { public: /** Test settings for algorithm specific constraints. * @returns "" on ok and error descripton on fail */ virtual QString validate(const StructuralAlignmentTaskSettings &settings) = 0; virtual StructuralAlignment align(const StructuralAlignmentTaskSettings &settings, TaskStateInfo &state) = 0; }; // class StructuralAlignmentAlgorithm /** Task wrapper for structural alignment algorithm */ class U2ALGORITHM_EXPORT StructuralAlignmentTask : public Task { Q_OBJECT public: StructuralAlignmentTask(StructuralAlignmentAlgorithm *algorithm, const StructuralAlignmentTaskSettings &settings); virtual void run(); Task::ReportResult report(); QString generateReport() const; StructuralAlignment getResult() const { return result; } StructuralAlignmentTaskSettings getSettings() const { return settings; } private: std::auto_ptr algorithm; StructuralAlignmentTaskSettings settings; StructuralAlignment result; }; // class StructuralAlignmentTask } // namespace U2 #endif // #ifndef _U2_STRUCTURAL_ALIGNMENT_ALGORITHM_H_ ugene-1.9.8/src/corelibs/U2Algorithm/src/structural_alignment/StructuralAlignmentAlgorithmFactory.h0000644000175000017500000000236311651544331032463 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_STRUCTURAL_ALIGNMENT_ALGORITHM_FACTORY_H_ #define _U2_STRUCTURAL_ALIGNMENT_ALGORITHM_FACTORY_H_ #include #include "StructuralAlignmentAlgorithm.h" namespace U2 { class U2ALGORITHM_EXPORT StructuralAlignmentAlgorithmFactory { public: virtual StructuralAlignmentAlgorithm* create() = 0; }; } // namespace U2 #endif // #ifndef _U2_STRUCTURAL_ALIGNMENT_ALGORITHM_FACTORY_H_ ugene-1.9.8/src/corelibs/U2Algorithm/src/util_msaedit/0000755000175000017500000000000011651544331021315 5ustar ilyailyaugene-1.9.8/src/corelibs/U2Algorithm/src/util_msaedit/CreateSubalignmentTask.cpp0000644000175000017500000000673111651544331026427 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "CreateSubalignmentTask.h" #include #include #include #include #include #include #include namespace U2{ CreateSubalignmentTask::CreateSubalignmentTask(MAlignmentObject* _maObj, const CreateSubalignmentSettings& settings ) : Task(tr("Extract selected as MSA task"), TaskFlags_NR_FOSCOE), maObj(_maObj), cfg(settings) { curDoc = maObj->getDocument(); newDoc = NULL; if (cfg.url == curDoc->getURL() || cfg.url.isEmpty()) { saveToAnother = false; } } void CreateSubalignmentTask::prepare() { QString ext = cfg.url.completeFileSuffix(); DocumentFormatRegistry *dfr = AppContext::getDocumentFormatRegistry(); DocumentFormat *dfd = dfr->getFormatById(BaseDocumentFormats::CLUSTAL_ALN); foreach(const DocumentFormatId &dfId, dfr->getRegisteredFormats()) { DocumentFormat *df = dfr->getFormatById(dfId); foreach(const QString &dfExt, df->getSupportedDocumentFileExtensions()) { if (ext.endsWith(dfExt)) { dfd = df; break; } } } newDoc = curDoc; IOAdapterFactory* iof = AppContext::getIOAdapterRegistry()->getIOAdapterFactoryById(BaseIOAdapters::url2io(cfg.url)); if (saveToAnother) { QList GObjList = curDoc->getObjects(); newDoc = dfd->createNewDocument(iof, cfg.url, curDoc->getGHintsMap()); foreach(GObject* go, GObjList){ GObject *cl = go->clone(); newDoc->addObject(cl); if (go == maObj){ maObj = static_cast (cl); } } foreach(GObject* o, newDoc->getObjects()) { GObjectUtils::updateRelationsURL(o, curDoc->getURL(), cfg.url); } } else { if(newDoc->isStateLocked()) { coreLog.error(tr("Document is locked")); return; } } //TODO: add "remove empty rows and columns" flag to crop function QSet rowNames; foreach (const QString& name, cfg.seqNames) { rowNames.insert(name); } maObj->crop(cfg.window, rowNames); if (cfg.saveImmediately) { addSubTask(new SaveDocumentTask(newDoc, iof, cfg.url)); } } void CreateSubalignmentTask::cleanup() { if (newDoc != NULL) { delete newDoc; newDoc = NULL; } } Document* CreateSubalignmentTask::takeDocument() { Document* doc = newDoc; newDoc = NULL; return doc; } CreateSubalignmentTask::~CreateSubalignmentTask() { cleanup(); } } ugene-1.9.8/src/corelibs/U2Algorithm/src/util_msaedit/CreateSubalignmentTask.h0000644000175000017500000000402511651544331026066 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_CREATE_SUBALIGNMENT_TASK_H_ #define _U2_CREATE_SUBALIGNMENT_TASK_H_ #include #include #include #include namespace U2{ class U2ALGORITHM_EXPORT CreateSubalignmentSettings { public: CreateSubalignmentSettings(const U2Region& w, const QStringList& sNames, const GUrl& path, bool save, bool add) : window(w), seqNames(sNames), url(path), saveImmediately(save), addToProject(add) {} U2Region window; QStringList seqNames; GUrl url; bool saveImmediately; bool addToProject; }; class U2ALGORITHM_EXPORT CreateSubalignmentTask : public Task { Q_OBJECT public: CreateSubalignmentTask(MAlignmentObject* _maObj, const CreateSubalignmentSettings& settings ); ~CreateSubalignmentTask(); virtual void prepare(); virtual void cleanup(); Document* takeDocument(); const CreateSubalignmentSettings& getSettings() { return cfg; } private: Document* curDoc; MAlignmentObject* maObj; CreateSubalignmentSettings cfg; Document* newDoc; bool saveToAnother; }; } #endif ugene-1.9.8/src/corelibs/U2Algorithm/src/util_msaedit/MAlignmentUtilTasks.cpp0000644000175000017500000001054511651544331025725 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include #include #include #include #include #include "MAlignmentUtilTasks.h" namespace U2 { ////////////////////////////////////////////////////////////////////////// /// TranslateMSA2AminoTask TranslateMSA2AminoTask::TranslateMSA2AminoTask( MAlignmentObject* obj ) : Task("TranslateMSA2AminoTask", TaskFlags_FOSCOE), maObj(obj) { assert(maObj != NULL); assert(maObj->getAlphabet()->isNucleic()); translations = AppContext::getDNATranslationRegistry()->lookupTranslation(maObj->getAlphabet(), DNATranslationType_NUCL_2_AMINO); } void TranslateMSA2AminoTask::run() { assert(!translations.isEmpty()); if (translations.isEmpty()) { setError(tr("Unable to find suitable translation for %1").arg(maObj->getGObjectName())); return; } DNATranslation* transl = translations.first(); QList lst = MSAUtils::ma2seq(maObj->getMAlignment(), true); resultMA = MAlignment(maObj->getMAlignment().getName(),transl->getDstAlphabet()) ; foreach (const DNASequence& dna, lst) { int buflen = dna.length() / 3; QByteArray buf(buflen,'\0'); transl->translate(dna.seq.constData(), dna.length(), buf.data(), buflen); buf.replace("*","X"); MAlignmentRow row(dna.getName(), buf); resultMA.addRow(row); } } Task::ReportResult TranslateMSA2AminoTask::report() { if (!resultMA.isEmpty()) { maObj->setMAlignment(resultMA); } return ReportResult_Finished; } ////////////////////////////////////////////////////////////////////////// /// MSAAlignMultiTask MSAAlignMultiTask::MSAAlignMultiTask( MAlignmentObject* obj, MAlignmentGObjectTask* t, bool toAmino ) : Task ("MSAAlignMultiTask",TaskFlags_FOSCOE), alignTask(t), maObj(obj), clonedObj(NULL), convertToAmino(toAmino) { setMaxParallelSubtasks(1); } void MSAAlignMultiTask::prepare() { if (convertToAmino == true && maObj->getAlphabet()->isNucleic()) { clonedObj = qobject_cast ( maObj->clone() ); alignTask->setMAObject(clonedObj); bufMA = clonedObj->getMAlignment(); addSubTask(new TranslateMSA2AminoTask(clonedObj)); } addSubTask(alignTask); } Task::ReportResult MSAAlignMultiTask::report() { if (!bufMA.isEmpty() && convertToAmino) { maObj->setMAlignment(bufMA); } return ReportResult_Finished; } void MSAAlignMultiTask::run() { if ( hasError() || isCanceled() ) { return; } if (bufMA.isEmpty() || !convertToAmino) { return; } // applying a gap map assert(clonedObj != NULL); const MAlignment& newMA = clonedObj->getMAlignment(); const QList& rows = newMA.getRows(); // If the rows where rearranged we need to find index of each one. // However, what if the rows have equal names? // Do we have to keep some MAP in memory? foreach (const MAlignmentRow& row, rows) { int rowIdx = MSAUtils::getRowIndexByName(bufMA, row.getName()); if (rowIdx == -1) { setError(tr("Can not find row %1 in original alignment.").arg(row.getName())); return; } for (int pos =0; pos < row.getCoreEnd(); ++pos) { char c = newMA.charAt(rowIdx, pos); if (c == MAlignment_GapChar) { bufMA.insertChars(rowIdx,pos,MAlignment_GapChar,3); } } } bufMA.trim(); } } // U2 ugene-1.9.8/src/corelibs/U2Algorithm/src/util_msaedit/MAlignmentUtilTasks.h0000644000175000017500000000474211651544331025374 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_MALIGNMENT_UTIL_TASKS #define _U2_MALIGNMENT_UTIL_TASKS #include #include #include namespace U2 { class DNATranslation; /** Performs in-place translation of malignment object */ class U2ALGORITHM_EXPORT TranslateMSA2AminoTask : public Task { Q_OBJECT public: TranslateMSA2AminoTask(MAlignmentObject* obj ); const MAlignment& getTaskResult() { return resultMA; } void run(); ReportResult report(); private: MAlignment resultMA; MAlignmentObject* maObj; QList translations; }; /** Wrapper for multiple alginment task */ class U2ALGORITHM_EXPORT MAlignmentGObjectTask : public Task { Q_OBJECT public: MAlignmentGObjectTask(const QString& taskName, TaskFlags f, MAlignmentObject* maobj) : Task(taskName, f), obj(maobj) {} void setMAObject(MAlignmentObject* maobj) { obj = maobj; } MAlignmentObject* getMAObject() { return obj; } protected: QPointer obj; }; /** Multi task converts alignment object to amino representation if possible. This allows to: 1) speed up alignment 2) avoid errors of inserting gaps within codon boundaries */ class U2ALGORITHM_EXPORT MSAAlignMultiTask : public Task { Q_OBJECT public: MSAAlignMultiTask(MAlignmentObject* obj, MAlignmentGObjectTask* alignTask, bool convertToAmino); virtual void prepare(); virtual void run(); virtual ReportResult report(); protected: MAlignmentGObjectTask* alignTask; MAlignmentObject *maObj, *clonedObj; bool convertToAmino; MAlignment bufMA; }; } // U2 #endif // _U2_MALIGNMENT_UTIL_TASKS ugene-1.9.8/src/corelibs/U2Algorithm/src/molecular_geometry/0000755000175000017500000000000011651544331022530 5ustar ilyailyaugene-1.9.8/src/corelibs/U2Algorithm/src/molecular_geometry/MolecularSurface.cpp0000644000175000017500000001217611651544330026476 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include #include #include #include "MolecularSurface.h" #include "MolecularSurfaceFactoryRegistry.h" namespace U2 { double AtomConstants::atomRadiusTable[NUM_ELEMENTS] = {0.0}; void AtomConstants::init() { static bool initialized = false; if (!initialized) { // Init atomRadiusTable atomRadiusTable[1] = 0.23; atomRadiusTable[5] = 0.83; atomRadiusTable[6] = 0.68; atomRadiusTable[7] = 0.68; atomRadiusTable[8] = 0.68; atomRadiusTable[9] = 0.64; atomRadiusTable[14] = 1.20; atomRadiusTable[15] = 1.05; atomRadiusTable[16] = 1.02; atomRadiusTable[17] = 0.99; atomRadiusTable[33] = 1.21; atomRadiusTable[34] = 1.22; atomRadiusTable[35] = 1.21; atomRadiusTable[52] = 1.47; atomRadiusTable[53] = 1.40; // now we've initialized utility maps initialized = true; } } // MolecularSurface const float MolecularSurface::TOLERANCE = 1.0f; const QVector &MolecularSurface::getFaces() const { return faces; } QList MolecularSurface::findAtomNeighbors( const SharedAtom& a, const QList& atoms ) { QList neighbors; // maximum covalent radius in angstroms static const float maxAtomRadius = 1.0; static const float doubleRadius = 2*maxAtomRadius; Vector3D v1 = a->coord3d; foreach (const SharedAtom& neighbor, atoms) { if (neighbor == a) { continue; } Vector3D v2 = neighbor->coord3d; if ( ( qAbs(v1.x - v2.x) <= doubleRadius) && ( qAbs(v1.y - v2.y) <= doubleRadius ) && ( qAbs(v1.z - v2.z) <= doubleRadius ) ) { neighbors.append(neighbor); } } return neighbors; } U2::GeodesicSphere MolecularSurface::getAtomSurfaceDots( const SharedAtom& a, int detaillevel ) { QVector surfaceDots; float radius = TOLERANCE + AtomConstants::getAtomCovalentRadius(a->atomicNumber); //Calculate sphere surface dots GeodesicSphere sphere(a->coord3d, radius, detaillevel); return sphere; } bool MolecularSurface::vertexNeighboursOneOf( const Vector3D& v, const QList& atoms ) { foreach (const SharedAtom& a, atoms) { float r = AtomConstants::getAtomCovalentRadius(a->atomicNumber) + TOLERANCE; //Vector3D v2 = a->coord3d; //qDebug("testing if vertex (%f,%f,%f) neighbors atom (%f,%f,%f) of radius %f", v.x, v.y, v.z, v2.x, v2.y, v2.z, radius); if ( sqr(v.x - a->coord3d.x) + sqr(v.y - a->coord3d.y) + sqr(v.z - a->coord3d.z ) <= r*r ) { return true; } } return false; } qint64 MolecularSurface::estimateMemoryUsage( int numberOfAtoms ) { Q_UNUSED(numberOfAtoms); // this many elements we can keep in container int maxInt = std::numeric_limits::max(); return maxInt*sizeof(double)*6; } MolecularSurfaceCalcTask::MolecularSurfaceCalcTask( const QString& surfaceTypeName, const QList& _atoms ) :Task(tr("Molecular surface calculation"), TaskFlag_None), typeName(surfaceTypeName), atoms(_atoms) { MolecularSurfaceFactory *factory= AppContext::getMolecularSurfaceFactoryRegistry()->getSurfaceFactory(typeName); molSurface = factory->createInstance(); qint64 memUseMB = (molSurface->estimateMemoryUsage(atoms.size())) / 1024 / 1024; algoLog.trace(QString("Estimated memory usage: %1 MB").arg(memUseMB)); addTaskResource(TaskResourceUsage(RESOURCE_MEMORY, memUseMB, true)); tpm = Progress_Manual; } void MolecularSurfaceCalcTask::run() { stateInfo.progress = 0; molSurface->calculate(atoms, stateInfo.progress); } std::auto_ptr MolecularSurfaceCalcTask::getCalculatedSurface() { assert(molSurface != NULL); MolecularSurface* returnValue = molSurface; molSurface = NULL; return std::auto_ptr(returnValue); } Task::ReportResult MolecularSurfaceCalcTask::report() { int numFaces = molSurface->getFaces().size(); algoLog.trace(QString("Number of atoms: %1, number of faces: %2").arg(atoms.size()).arg(numFaces)); algoLog.trace(QString("Used memory: %1 MB").arg( ( (qint64) numFaces* sizeof(double)* 3*6) / 1024 / 1024 )); return ReportResult_Finished; } } // namespace ugene-1.9.8/src/corelibs/U2Algorithm/src/molecular_geometry/VanDerWaalsSurface.h0000644000175000017500000000256511651544331026371 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef VANDERWAALSSURFACE_H #define VANDERWAALSSURFACE_H #include "MolecularSurface.h" namespace U2 { class U2ALGORITHM_EXPORT VanDerWaalsSurface : public MolecularSurface { public: VanDerWaalsSurface(); qint64 estimateMemoryUsage(int numberOfAtoms); virtual void calculate(const QList& atoms, int& progress); }; class U2ALGORITHM_EXPORT VanDerWaalsSurfaceFactory : public MolecularSurfaceFactory { public: virtual MolecularSurface *createInstance()const; }; } // namespace U2 #endif // VANDERWAALSSURFACE_H ugene-1.9.8/src/corelibs/U2Algorithm/src/molecular_geometry/GeomUtils.h0000644000175000017500000000346111651544330024614 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_GEOM_UTILS_H_ #define _U2_GEOM_UTILS_H_ #include #include #include namespace U2 { const float PI = 3.14159265f; const float Rad2Deg = 57.2957795f; const float Deg2Rad = 0.017453293f; struct U2ALGORITHM_EXPORT Face { Face() {} Vector3D v[3]; Vector3D n[3]; }; //! Builds sphere class U2ALGORITHM_EXPORT GeodesicSphere { QVector vertices; QVector faces; static std::auto_ptr< QVector > elementarySphere; static int currentDetailLevel; static void interpolate(const Vector3D& v1, const Vector3D& v2, const Vector3D& v3, QVector* v, int detailLevel); public: GeodesicSphere(const Vector3D& center, float radius, int detaillevel); static QVector* createGeodesicSphere(int detailLevel); QVector getVertices() { return vertices; } QVector getFaces() { return faces; } }; } //namespace #endif // _U2_GEOM_UTILS_H_ ugene-1.9.8/src/corelibs/U2Algorithm/src/molecular_geometry/MolecularSurface.h0000644000175000017500000000545511651544330026145 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_BIOSTRUCT3D_MOLECULAR_SURFACE_H_ #define _U2_BIOSTRUCT3D_MOLECULAR_SURFACE_H_ #include #include #include #include #include #include #include #include "GeomUtils.h" namespace U2 { template inline T sqr(const T& x) { return x*x; } class U2ALGORITHM_EXPORT AtomConstants { static const int NUM_ELEMENTS = 120; static double atomRadiusTable[NUM_ELEMENTS]; public: inline static double getAtomCovalentRadius(int atomicNumber); static void init(); }; double AtomConstants::getAtomCovalentRadius( int atomicNumber ) { Q_ASSERT(atomicNumber < NUM_ELEMENTS); return atomRadiusTable[atomicNumber]; } class U2ALGORITHM_EXPORT MolecularSurface { protected: static const float TOLERANCE; public: virtual void calculate(const QList& atoms, int& progress)=0; virtual qint64 estimateMemoryUsage(int numberOfAtoms); const QVector &getFaces()const; protected: QVector faces; public: static QList findAtomNeighbors(const SharedAtom& a, const QList& atoms); static GeodesicSphere getAtomSurfaceDots(const SharedAtom& a, int detaillevel); static bool vertexNeighboursOneOf(const Vector3D& v, const QList& atoms); }; class U2ALGORITHM_EXPORT MolecularSurfaceCalcTask : public Task { Q_OBJECT MolecularSurface* molSurface; QString typeName; const QList atoms; public: MolecularSurfaceCalcTask(const QString& surfaceTypeName, const QList& atoms); std::auto_ptr getCalculatedSurface(); virtual void run(); virtual ReportResult report(); }; class U2ALGORITHM_EXPORT MolecularSurfaceFactory { public: virtual MolecularSurface *createInstance()const=0; virtual bool hasConstraints(const BioStruct3D&) const { return false; } }; } //namespace #endif //_U2_BIOSTRUCT3D_MOLECULAR_SURFACE_H_ ugene-1.9.8/src/corelibs/U2Algorithm/src/molecular_geometry/MolecularSurfaceFactoryRegistry.h0000644000175000017500000000330011651544330031211 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef MOLECULARSURFACEFACTORYREGISTRY_H #define MOLECULARSURFACEFACTORYREGISTRY_H #include "MolecularSurface.h" namespace U2 { class U2ALGORITHM_EXPORT MolecularSurfaceFactoryRegistry : public QObject { public: MolecularSurfaceFactoryRegistry(QObject* pOwn = 0); ~MolecularSurfaceFactoryRegistry(); bool registerSurfaceFactory(MolecularSurfaceFactory* surf, const QString& surfId); bool hadRegistered(const QString& surfId); MolecularSurfaceFactory* getSurfaceFactory(const QString& surfId); QStringList getSurfNameList(); private: QMap surfMap; // Copy prohibition MolecularSurfaceFactoryRegistry(const MolecularSurfaceFactoryRegistry& m); MolecularSurfaceFactoryRegistry& operator=(const MolecularSurfaceFactoryRegistry& m); }; } // namespace U2 #endif // MOLECULARSURFACEFACTORYREGISTRY_H ugene-1.9.8/src/corelibs/U2Algorithm/src/molecular_geometry/MolecularSurfaceFactoryRegistry.cpp0000644000175000017500000000371311651544330031554 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "VanDerWaalsSurface.h" #include "MolecularSurfaceFactoryRegistry.h" namespace U2 { MolecularSurfaceFactoryRegistry::MolecularSurfaceFactoryRegistry( QObject* pOwn /*= 0*/ ) : QObject(pOwn) { registerSurfaceFactory(new VanDerWaalsSurfaceFactory(),QString("vdWS")); } MolecularSurfaceFactoryRegistry::~MolecularSurfaceFactoryRegistry() { foreach( MolecularSurfaceFactory* factory, surfMap.values()) { delete factory; } } bool MolecularSurfaceFactoryRegistry::registerSurfaceFactory( MolecularSurfaceFactory* surf, const QString& surfId ) { if (surfMap.contains(surfId)){ return false; } surfMap.insert(surfId, surf); return true; } bool MolecularSurfaceFactoryRegistry::hadRegistered( const QString& surfId ) { return surfMap.contains(surfId); } MolecularSurfaceFactory* MolecularSurfaceFactoryRegistry::getSurfaceFactory( const QString& surfId ) { if (surfMap.contains(surfId)) { return surfMap.value(surfId); } else { return NULL; } } QStringList MolecularSurfaceFactoryRegistry::getSurfNameList() { return surfMap.keys(); } } // namespace U2 ugene-1.9.8/src/corelibs/U2Algorithm/src/molecular_geometry/VanDerWaalsSurface.cpp0000644000175000017500000000542211651544331026717 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "VanDerWaalsSurface.h" namespace U2 { // VanDerWaalsSurface // determined by geodesic sphere detail level static int FACTOR = 64; VanDerWaalsSurface::VanDerWaalsSurface() { } void VanDerWaalsSurface::calculate(const QList &atoms, int& progress) { // Van Der Vaals surface calculation // based on atom radius (look for neighbours, exclude unneeded atoms) int overall = atoms.size(); int counter = 0; int detaillevel = 2; if (atoms.size() > 10000) { detaillevel = 1; } foreach (const SharedAtom& a, atoms) { QList neighbors = findAtomNeighbors(a, atoms); GeodesicSphere surface = getAtomSurfaceDots(a, detaillevel); QVector surfaceDots = surface.getVertices(); QVector reducedVertices; foreach (const Vector3D& v, surfaceDots) { if ( vertexNeighboursOneOf(v, neighbors) ) { continue; } else { reducedVertices.append(v); } } QVector surfaceFaces = surface.getFaces(); foreach (const Face& face, surfaceFaces) { if ( reducedVertices.contains(face.v[0]) || reducedVertices.contains(face.v[1]) || reducedVertices.contains(face.v[2]) ) { faces.append(face); } } counter++; progress = counter * 100 / overall; } } //void VanDerWaalsSurface::calculate(const BioStruct3D& bioStruct) //{ // Vector3D center = bioStruct.getCenter(); // float radius = bioStruct.getMaxDistFromCenter(); // GeodesicSphere sphere(center, radius); // vertices = sphere.getVertices(); //} qint64 VanDerWaalsSurface::estimateMemoryUsage( int numberOfAtoms ) { return numberOfAtoms*FACTOR*sizeof(double)*3*6*1.5; } // VanDerWaalsSurfaceFactory MolecularSurface *VanDerWaalsSurfaceFactory::createInstance()const { return new VanDerWaalsSurface(); } } // namespace U2 ugene-1.9.8/src/corelibs/U2Algorithm/src/molecular_geometry/GeomUtils.cpp0000644000175000017500000001012311651544330025140 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include #include "GeomUtils.h" namespace U2 { std::auto_ptr< QVector > GeodesicSphere::elementarySphere(NULL); int GeodesicSphere::currentDetailLevel = 1; GeodesicSphere::GeodesicSphere( const Vector3D& center, float radius, int detaillevel) { if (elementarySphere.get() == NULL || currentDetailLevel != detaillevel) { elementarySphere.reset(createGeodesicSphere(detaillevel)); currentDetailLevel = detaillevel; } QVector normals; vertices.resize(elementarySphere->count()); qCopy(elementarySphere->begin(), elementarySphere->end(), vertices.begin()); int size = vertices.count(); for (int i = 0; i < size; ++i) { Vector3D& vertex = vertices[i]; vertex.normalize(); normals.append(vertex); vertex *= radius; vertex += center; } for (int i = 0; i < size; i+= 3) { Face face; face.v[0] = vertices.at(i); face.v[1] = vertices.at(i+1); face.v[2] = vertices.at(i+2); face.n[0] = normals.at(i); face.n[1] = normals.at(i+1); face.n[2] = normals.at(i+2); faces.append(face); } } void GeodesicSphere::interpolate( const Vector3D& v1, const Vector3D& v2, const Vector3D& v3, QVector* v, int detailLevel ) { if (0 == detailLevel) { v->append(v1); v->append(v2); v->append(v3); return; } Vector3D nv1( (v1.x + v2.x) / 2, (v1.y + v2.y) / 2, (v1.z + v2.z) / 2 ); Vector3D nv2( (v2.x + v3.x) / 2, (v2.y + v3.y) / 2, (v2.z + v3.z) / 2 ); Vector3D nv3( (v3.x + v1.x) / 2, (v3.y + v1.y) / 2, (v3.z + v1.z) / 2 ); interpolate(nv1, nv2, nv3,v, detailLevel - 1); interpolate(v1, nv1, nv3,v, detailLevel - 1); interpolate(nv1, v2, nv2,v, detailLevel - 1); interpolate(nv3, nv2, v3,v, detailLevel - 1); return; } QVector* GeodesicSphere::createGeodesicSphere( int detailLevel ) { QVector base; base.resize(24); // up base[0] = Vector3D(-1.0f, 0.0f, 0.0f); base[1] = Vector3D(0.0f, 1.0f, 0.0f); base[2] = Vector3D(0.0f, 0.0f, -1.0f); base[3] = Vector3D(0.0f, 0.0f, -1.0f); base[4] = Vector3D(0.0f, 1.0f, 0.0f); base[5] = Vector3D(1.0f, 0.0f, 0.0f); base[6] = Vector3D(1.0f, 0.0f, 0.0f); base[7] = Vector3D(0.0f, 1.0f, 0.0f); base[8] = Vector3D(0.0f, 0.0f, 1.0f); base[9] = Vector3D(0.0f, 0.0f, 1.0f); base[10] = Vector3D(0.0f, 1.0f, 0.0f); base[11] = Vector3D(-1.0f, 0.0f, 0.0f); //down base[12] = Vector3D(-1.0f, 0.0f, 0.0f); base[13] = Vector3D(0.0f, 0.0f, -1.0f); base[14] = Vector3D(0.0f, -1.0f, 0.0f); base[15] = Vector3D(0.0f, 0.0f, -1.0f); base[16] = Vector3D(1.0f, 0.0f, 0.0f); base[17] = Vector3D(0.0f, -1.0f, 0.0f); base[18] = Vector3D(1.0f, 0.0f, 0.0f); base[19] = Vector3D(0.0f, 0.0f, 1.0f); base[20] = Vector3D(0.0f, -1.0f, 0.0f); base[21] = Vector3D(0.0f, 0.0f, 1.0f); base[22] = Vector3D(-1.0f, 0.0f, 0.0f); base[23] = Vector3D(0.0f, -1.0f, 0.0f); QVector* v = new QVector(); for (int i = 0; i < 24; i += 3) { interpolate(base.at(i), base.at(i+1), base.at(i+2),v, detailLevel); } return v; } } //namespace ugene-1.9.8/src/corelibs/U2Algorithm/transl/0000755000175000017500000000000011651544331017346 5ustar ilyailyaugene-1.9.8/src/corelibs/U2Algorithm/transl/russian.ts0000644000175000017500000004253111651544331021407 0ustar ilyailya PhyTreeGeneratorTask Calculating Phylogenetic Tree Создание филогенетического дерева Calculating phylogenetic tree Создание филогенетического дерева QObject Loading OPENCL driver library Cannot load OpenCL library. Error while loading %1 Cannot resolve symbol %1 Cannot load library: %1 Some errors occurs in library: %1 Gaps: U2::FindAlgorithmTask Find in sequence task Поиск Смита-Ватермана U2::MSAConsensusAlgorithmFactoryClustal Emulates ClustalW program and file format behavior. Эмулирует программу ClustalW и её интерпретацию формата файла. ClustalW Схема ClustalW U2::MSAConsensusAlgorithmFactoryDefault Based on JalView algorithm. Returns '+' if there are 2 characters with high frequency. Returns symbol in lower case if the symbol content in a row is lower than the threshold specified. В основе лежит алгоритм JalView. Возвращает '+'ˇ, если имеется 2 символа с высокой частотой. Возвращает символ в нижнем регистре, если символ содержится в ряду меньшее число раз, чем это указано в пороге. Default Схема по умолчанию U2::MSAConsensusAlgorithmFactoryLevitsky The algorithm proposed by Victor Levitsky to work with DNA alignments. Collects global alignment frequency for every symbol using extended (15 symbols) DNA alphabet first. For every column selects the most rare symbol in the whole alignment with percentage in the column greater or equals to the threshold value. Алгоритм представлен Виктором Левицким для работы с выравниваниями ДНК. В первую очередь алгоритм вычисляет глобальную частоту появления каждого символа в выравнивании с использованием расширенного (15-символьного) алфавита ДНК. Для каждого столбца выбирается наиболее редко встречаемый символ во всём выравнивании, такой что процентное соотношение его появления в столбце больше либо равно значению порога. Levitsky Схема Левицкого U2::MSAConsensusAlgorithmFactoryStrict The algorithm returns gap character ('-') if symbol frequency in a column is lower than threshold specified. Алгоритм возвращает символ пропуска ('-'), если частота появления символа в столбце меньше, чем величина, заданная в пороге. Strict Строгая схема U2::MSADistanceAlgorithm MSA distance algorithm "%1" task U2::MSADistanceAlgorithmFactoryHamming Based on Hamming distance between two sequences Hamming U2::MSADistanceAlgorithmFactoryHammingRevCompl Based on Hamming distance between two sequences Hamming reverse-complement U2::MolecularSurfaceCalcTask Molecular surface calculation Вычисление молекулярной поверхности U2::ORFFindTask ORF find Поиск ORF (рамок считывания) U2::PWMConversionAlgorithmFactoryBVH Berg and von Hippel weight function Весовая функция Берга-Гиппеля U2::PWMConversionAlgorithmFactoryLOD log-odds log-odds weight function U2::PWMConversionAlgorithmFactoryMCH Match Match weight function U2::PWMConversionAlgorithmFactoryNLG NLG NLG weight function U2::PhyTreeGeneratorTask Calculating Phylogenetic Tree Создание филогенетического дерева Calculating phylogenetic tree Создание филогенетического дерева U2::SecStructPredictTask Secondary structure predict Предсказание вторичной структуры U2::SmithWatermanReportCallbackImpl Annotation object not found. Не найдена таблица аннотаций Annotation table is read-only Запрещена запись в таблицу аннотаций U2::SubstMatrixRegistry Matrix %1 already registered. Матрица %1 уже зарегестрирована. Error parsing weight-matrix file: %1 Ошибка чтения матрицы: %1 Reading substitution matrix from %1 Error weight matrix file '%1' : %2 Ошибка в файле матрицы "%1" : "%2" Error opening file for read: %1 Ошибка открытия файла для чтения: "%1" Error reading file: %1 Ошибка чтения файла: "%1" Invalid character token '%1' , line %2 Неверный символ: "%1" в строке: "%2" Duplicate character '%1' , line %2 Дублированный символ: "%1" в строке "%2" Alphabet is neither nucleic nor protein! Алфавит не является ни нуклеиновым, ни протеиновым! Matrix doesn't contains score for default alphabet character '%1' Invalid character row '%1' , line %2 Некорректная последовательность символов "%1" в строке: %2" Duplicate character mapping '%1' , line %2 Invalid number of columns '%1' , line %2 Неверное число столбцов "%1" в строке %2 Can't parse numeric value '%1', line %2 Не могу распознать числовое значение "%1" в строке "%2" Unexpected end of file! Неожиданный конец файла! ugene-1.9.8/src/corelibs/U2Algorithm/transl/czech.ts0000644000175000017500000003650011651544331021016 0ustar ilyailya PhyTreeGeneratorTask Calculating Phylogenetic Tree Počítá se fylogenetický strom Calculating phylogenetic tree Počítá se fylogenetický strom QObject Loading OPENCL driver library Cannot load OpenCL library. Error while loading %1 Cannot resolve symbol %1 Cannot load library: %1 Some errors occurs in library: %1 Gaps: U2::FindAlgorithmTask find_in_sequence_task Find in sequence task Find in sequence task Najít v úkolu sekvence U2::MSAConsensusAlgorithmFactoryClustal Emulates ClustalW program and file format behavior. Napodobuje program ClustalW a chování jeho souborového formátu. ClustalW U2::MSAConsensusAlgorithmFactoryDefault Based on JalView algorithm. Returns '+' if there are 2 characters with high frequency. Returns symbol in lower case if the symbol content in a row is lower than the threshold specified. Založeno na algoritmu JalView. Vrací '+', pokud tu jsou 2 znaky s vysokou četností. Vrací symbol v malých písmenech, pokud je obsah symbolu na řádku nižší, než je zadaný práh Default Výchozí U2::MSAConsensusAlgorithmFactoryLevitsky The algorithm proposed by Victor Levitsky to work with DNA alignments. Collects global alignment frequency for every symbol using extended (15 symbols) DNA alphabet first. For every column selects the most rare symbol in the whole alignment with percentage in the column greater or equals to the threshold value. Algoritmus navržený Viktorem Levitskym pro práci se zarovnáním DNA. Sbírá četnost celkového zarovnání pro každý symbol používající nejprve rozšířenou abecedu DNA (15 symbolů). Pro každý sloupec vybere nejvzácnější symbol v celém zarovnání s procentním podílem ve sloupci větším, než je prahová hodnota, nebo stejným. Levitsky U2::MSAConsensusAlgorithmFactoryStrict The algorithm returns gap character ('-') if symbol frequency in a column is lower than threshold specified. Algoritmus vrací znak mezery ('-'), pokud je četnost symbolu ve sloupci nižší, než je zadaný práh. Strict U2::MSADistanceAlgorithm MSA distance algorithm "%1" task U2::MSADistanceAlgorithmFactoryHamming Based on Hamming distance between two sequences Hamming U2::MSADistanceAlgorithmFactoryHammingRevCompl Based on Hamming distance between two sequences Hamming reverse-complement U2::MolecularSurfaceCalcTask Molecular surface calculation Výpočet povrchu molekul U2::ORFFindTask ORF find Hledání ORF U2::PWMConversionAlgorithmFactoryBVH Berg and von Hippel weight function Bergova a von Hippelova funkce váhy U2::PWMConversionAlgorithmFactoryLOD log-odds log-odds weight function Funkce váhy log-odds U2::PWMConversionAlgorithmFactoryMCH Match Shoda Match weight function Funkce váhy shody U2::PWMConversionAlgorithmFactoryNLG NLG NLG weight function Funkce váhy NLG U2::SecStructPredictTask Secondary structure predict Předpověď druhotné stavby U2::SmithWatermanReportCallbackImpl Annotation object not found. Předmět s poznámkou nenalezen. Annotation table is read-only Tabulka s poznámkou je pouze pro čtení U2::SubstMatrixRegistry Reading substitution matrix from %1 Error weight matrix file '%1' : %2 Chyba v souboru váhové matice '%1' : %2 Error opening file for read: %1 Chyba při otevírání souboru pro čtení: %1 Error reading file: %1 Chyba při čtení souboru: %1 Invalid character token '%1' , line %2 Neplatné symbol znaku '%1' , řádek %2 Duplicate character '%1' , line %2 Zdvojený znak '%1' , řádek %2 Alphabet is neither nucleic nor protein! Abeceda není ani nukleová ani proteinová! Matrix doesn't contains score for default alphabet character '%1' Matice neobsahuje zápis pro výchozí abecední znak '%1' Invalid character row '%1' , line %2 Neplatný řádek znaku '%1' , řádek %2 Duplicate character mapping '%1' , line %2 Zdvojené přiřazení znaku '%1' , řádek %2 Invalid number of columns '%1' , line %2 Neplatné počet sloupců '%1' , řádek %2 Can't parse numeric value '%1', line %2 Nelze zpracovat číselnou hodnotu '%1' , řádek %2 Unexpected end of file! Neočekávaný konec souboru! ugene-1.9.8/src/corelibs/U2Algorithm/transl/english.ts0000644000175000017500000003310611651544331021352 0ustar ilyailya PhyTreeGeneratorTask Calculating Phylogenetic Tree Calculating phylogenetic tree QObject Loading OPENCL driver library Cannot load OpenCL library. Error while loading %1 Cannot resolve symbol %1 Cannot load library: %1 Some errors occurs in library: %1 Gaps: U2::FindAlgorithmTask Find in sequence task U2::MSAConsensusAlgorithmFactoryClustal Emulates ClustalW program and file format behavior. ClustalW U2::MSAConsensusAlgorithmFactoryDefault Based on JalView algorithm. Returns '+' if there are 2 characters with high frequency. Returns symbol in lower case if the symbol content in a row is lower than the threshold specified. Default U2::MSAConsensusAlgorithmFactoryLevitsky The algorithm proposed by Victor Levitsky to work with DNA alignments. Collects global alignment frequency for every symbol using extended (15 symbols) DNA alphabet first. For every column selects the most rare symbol in the whole alignment with percentage in the column greater or equals to the threshold value. Levitsky U2::MSAConsensusAlgorithmFactoryStrict The algorithm returns gap character ('-') if symbol frequency in a column is lower than threshold specified. Strict U2::MSADistanceAlgorithm MSA distance algorithm "%1" task U2::MSADistanceAlgorithmFactoryHamming Based on Hamming distance between two sequences Hamming U2::MSADistanceAlgorithmFactoryHammingRevCompl Based on Hamming distance between two sequences Hamming reverse-complement U2::MolecularSurfaceCalcTask Molecular surface calculation U2::ORFFindTask ORF find U2::PWMConversionAlgorithmFactoryBVH Berg and von Hippel weight function U2::PWMConversionAlgorithmFactoryLOD log-odds log-odds weight function U2::PWMConversionAlgorithmFactoryMCH Match Match weight function U2::PWMConversionAlgorithmFactoryNLG NLG NLG weight function U2::SecStructPredictTask Secondary structure predict U2::SmithWatermanReportCallbackImpl Annotation object not found. Annotation table is read-only U2::SubstMatrixRegistry Reading substitution matrix from %1 Error weight matrix file '%1' : %2 Error opening file for read: %1 Error reading file: %1 Invalid character token '%1' , line %2 Duplicate character '%1' , line %2 Alphabet is neither nucleic nor protein! Matrix doesn't contains score for default alphabet character '%1' Invalid character row '%1' , line %2 Duplicate character mapping '%1' , line %2 Invalid number of columns '%1' , line %2 Can't parse numeric value '%1', line %2 Unexpected end of file! ugene-1.9.8/src/corelibs/U2Algorithm/U2Algorithm.qrc0000644000175000017500000000020011651544330020676 0ustar ilyailya src/util_gpu/opencl/BinaryFind.cl ugene-1.9.8/src/ugenecl/0000755000175000017500000000000011651544337013534 5ustar ilyailyaugene-1.9.8/src/ugenecl/ugenecl.rc0000644000175000017500000000310411651544337015502 0ustar ilyailyaIDI_ICON1 ICON DISCARDABLE "images/ugene.ico" IDI_ICON2 ICON DISCARDABLE "images/ext.ico" #include #define STRINGIFY(x) #x #define TOSTRING(x) STRINGIFY(x) #define UGENE_VERSION_STRING TOSTRING(UGENE_VERSION) #ifndef DEBUG #define VER_DEBUG 0 #else #define VER_DEBUG VS_FF_DEBUG #endif VS_VERSION_INFO VERSIONINFO FILEVERSION UGENE_VER_MAJOR,UGENE_VER_MINOR,UGENE_VER_BUILD,UGENE_VER_REVISION PRODUCTVERSION UGENE_VER_MAJOR,UGENE_VER_MINOR,UGENE_VER_BUILD FILEFLAGSMASK VS_FFI_FILEFLAGSMASK //FILEFLAGS (VER_PRIVATEBUILD|VER_PRERELEASE|VER_DEBUG) FILEFLAGS (VER_DEBUG) //FILEOS VOS__WINDOWS32 FILETYPE VFT_APP BEGIN BLOCK "StringFileInfo" BEGIN BLOCK "040904E4" BEGIN VALUE "CompanyName", "Unipro, Russia" VALUE "FileDescription", "Command line interface of UGENE" VALUE "FileVersion", TOSTRING(UGENE_VER_MAJOR.UGENE_VER_MINOR.UGENE_VER_BUILD.UGENE_VER_REVISION) //VALUE "InternalName", VER_INTERNALNAME_STR //VALUE "LegalCopyright", VER_LEGALCOPYRIGHT_STR //VALUE "LegalTrademarks1", VER_LEGALTRADEMARKS1_STR //VALUE "LegalTrademarks2", VER_LEGALTRADEMARKS2_STR VALUE "OriginalFilename", "ugenecl" VALUE "ProductName", "Unipro UGENE" VALUE "ProductVersion", UGENE_VERSION_STRING VALUE "Comments", "UGENE is a free cross-platform genome analysis suite: http://ugene.unipro.ru/" END END END ugene-1.9.8/src/ugenecl/images/0000755000175000017500000000000011651544337015001 5ustar ilyailyaugene-1.9.8/src/ugenecl/images/ext.ico0000644000175000017500000001246611651544337016306 0ustar ilyailya h&  (  @  3f3f 3f3f! 3f3f !׃׃!3f3f! ׃׃ 3f3f!!! ׃׃׃ 3f3f!!!!׃׃׃׃3f3f׃! ! ׃׃3f3f׃׃׃ 3f3f׃׃׃3f3f !׃׃3f3f ׃׃3f3f3f3f 3f3f?( @   * F W X9)T-[,Z'P b3 )T-\3f,Z v b< 3-\3f,Z'P b3 )T-\3f,Z v b<   3-\3f,Z'P b3  * F W X9)T-\3f,Z v b: kutf b3  3-[3f,Z'P Y  lw׃tv b< -[3f3f,Z ]$  !3w׃tf b5$$-\3f3f,Z c5  lw׃tv c ] Y;1)T-\3f,Z v b< !3w׃tttf c8:M-[3f,Z'P b3  lw׃׃׃tv d _m,Z3f3f,Zv b<  !3w׃׃׃tttz@]3f3f@]zf b5$  lwvv׃׃׃ɉ@]3f3f@]ɉtv c ] Y9   !5w׃׃ɉ@]3f3f@]ɉ׃tttf b3  lwv|@]3f3f@]zu׃׃׃tv b<   5-[3f3f,ZmNw׃׃׃tf b3 -[3f3f,Z _:kwvv׃tv b<-\3f3f,Z d82 & !5w׃tf b3)T-\3f,Z v c< lw׃tv a 3-[3f,Z'P Y  !3w׃us-[3f3f,Z ]$  lwvu-\3f3f,Z c5     )T-\3f,Z v b< 3-\3f,Z'P b3 )T-\3f,Z v `9 3-\3f,Z(Q H)T-\-[)S, ?`0@`0ugene-1.9.8/src/ugenecl/images/ugene.ico0000644000175000017500000021306611651544337016610 0ustar ilyailya hhn(     f + 300 %600F\00hj@@ (BVq@@ (B~@@(@@h (  =;:J753Z855W865W865W854W854W854W854W854W854W854W864W853W;98Z('+%g[>@2D7D7D7C7A4@2A3C5B5B5B5?1UI)<98[UJ). 2%2%0"(2&;15* (+0#0",C6964W[O.5(:-6)<0H?'1#7*4'J=965W^S1:->0;.G= 9+9,OB976WbV6@2<.lfR[R:~we7)>1SF:76WfZF8E7N@C5 tL@I:]O+:87WocFRCL>K=TE!J;uSG)N@bT2;87WsgKWI$RD QC YK(PAvYM0TE gY8;98WwkO]N+XI'VI'^P.VG"v^R5YJ&l^=<99W{oTbS1]N,\N-dU4\L)zcW:_P-pcC<:9WsYgY7cT3aS3iZ:bR/{g[?eV3ugH=::Ww^m_>n`ArgOwnXrgOm_@n`@m_>nbHvlVshRk^?k\;{lN=;:Wx_oa@rdDpaAo_>pa@qbCqbCpbBo`@m]|nP=::Z{Ӆz`|d|d|d|d|d|d|d|d|d|d|czb蕊sB@@K( (+,. 0"0#1#2%2&4'5&5(5* 6)7)7*9+9,:-;.;1<.<0>0>1?1@1@1@2@2@2A3A4B5B5B5C5 C5 C5C6C7D7E7F8F8G= H?'I:J;J=K=L>L>L@N@N@OBPAQC RCRD SFSG)TE TE!UI)UJ)VG"VI'WI$WJ$XI'YJ&YK(YM0[O.[R:\L)\N-]N+]N,]O+^P.^R5^S1_P-aS3bR/bS1bT2bV6cT3cW:dU4eV3fZ<gY7gY8g[>g[?iZ:k\;k^?k_Al^=lfRm]<m^<m^>m_>m_@n`@n`AnbHo_>o`@oa@ocFpa@paApbBpcCqbCrdDrgOsgKshRugHvlVwkOwnX{lN{oT|nP~wesYw^x_z`zb|c|dtuv{zvs{c***)! '$$$BC  (L / 2Uû.9[jMĖ>`,Ǵ# ˪"%Gh4-̩+8&ʯ60Rv<5ɧ3A1ȳ?7Z~F=ƨ;J:ŲK@bPHESDTIiYQO^N]Vza\WeXd_nq}}opnrgfu|xsw{{ytkltm( 2""""""# "  DC EUUA" U24S"!TT"1TT"2TT!#2$T"#T"#2$T"#T"#2$T"#T"32$T"#T"3233"#3"323"32""333333333(( /.2).-09.-17.-17.-17.-17.-07.-07.-07.-07.-07.-07.-07.-07.-07.-07.-07.-07.-17! $wmWOC(SH,SG,SG,RG,RG+RG*RG*RG*RF*RF*QF*QF*QF*QF*QE*NC(lcM.-17\P2*/!/!/!.!.!,'&'+-,,,+'QE(.-17aU72$7*6)6*5',;0SK7]WFSL8;0*2&4'4'4&0"VK-.-17cX95(:-:-9+4(~x~4( 5(8+7+4&YM..-17e[;:,?2>15(5(;.0B5 <-`ZCwicQ8)@2C6jcOB2K=D5 XO4C6G9E7 cX:-,17rfKL>PAJ=c[CJ;OAK=VL0J?K=J<g[>-,17ujNQBTF!OB#d[CN@SE!PBXN2PE'PAO@k^B-,07xlQUF#YJ&SG(g^GSDWI&TF!\Q7VK-TF SE nbG-,07zoUZK']N+XK,jaJXI$\M+YJ%`T:ZO2YJ&XI%qeK-,07~rY]O-aS0\O1mbL\M*`R0]N+cX>^R5]N+\N*thN-,07u\bT2fW5`R5ofPaR/dV5aS0e[BaU:aS/`Q/wkQ-,07x_gX6j[:cV:qiUeV3hZ9fW5i^FdY>fW4eV4zoT-,07{ck\;n`@k]?{n|xlaGl]l]u\-,07~gpa@sdEsdEsdErdEsdDrdDrcDrcDqcCqcCqcCqcBqcBpbBpbBo`>u\,+09ъ~f錁j猁j猁j猁j猁j猁j猁j猁j猁j猁j猁j猁j猁j猁j猁j猀h蛒.-1)((&'*,,.!0"2$2&4&4(4( 5(5(6)6*7*8)8*9,:,;.;0;0<-<.0>1?2@2@2B2B5 C6C6D5 E7 G9J;J<J=J?K=L>N@NC(O@OB#PAPAPBPE'QBQE(QE*QF*RF*RG,SDSE SG(SH,SK7SL8TF UF#VK-VL0WI&XI$XK,XN2XO4YJ%YJ&YM.ZK'ZO2\M*\M+\N*\O1\P0\P2\Q7]O-]WF^R5^S2`Q/`R0`R5`T:`U6`ZCaR/aS/aS0aU:bT2cV:cX9cX:cX>c[CdV5dY>d[CeV3eV4e[;e[BfW4fW5gX6g[>g^GhZ9h\?h]?iY8iZ9i^FicQj[9j[:j]BjaJjcOk[:k\;k]?k^Bk`Bl]<l^>laGlcMm^=mbLn^>n`@nbGo`>o`Aoa@oaAofPpa@pbBpbCpcCqcBqcCqcDqeKqiUrcDrdDrdErfKsdDsdEthNujNwkQwmWxlQzoTzoU~rY~xu\{n}qx_u~{cwx~f~ghj{|/?;;;;:::::99998/U7_ @XA Dg  ׳  Mp Ty"`ǵ}Z"'% _'-#!,%J$'&h-3*j(2,E+,)u6B1m.=4I520CL>vXTP#wnV3&3&4'4&4&4&3&4&4&3&3&3%2#0"0"0"2$2$3%2$2$2$2$1$1#1#1#. QCYVQ#yoW6(5(6)6)6)6)6)6)6)3%++3( <2=48.."). 4'4'4'4&4&4&4&4&1#SF ZVR#zpX8+8+9,9,9,9,9,9,0"6+miaKC3+5'7*6)6)6)6)5)2&UH ZVR#zqY:-;.;.;.;.;.;.1#PI;0%7)9,8+8+8+8+5(WI!ZWS#|r[=/=0>1>0>1>15'SM>1%:-;.;.;.;.7*YL#ZWS#|r\@2@2A3@3@2>0>3rof3%>1=0=0=0:-\N&[WT#}t]B4 B5 B5 B5 C5 8)ywp|svqeA7>/@2?2?21_R+[WT"v`H:H:I;I;E7 OF-A7D5G:G9G98)lgY:,E7E7D7 A4 aS.\WT"xbK=J=K>K>E7_XF=0 J<I<I<I<G8LB(>1 H:H:G:D7cV1\XT"zdM@N@N@N@F7jdVA3 L?M?L?L?K=H=!B6K<K=K<G9eX4\YU"{eQBQCQCQCH:rnc{E7OAOAOAOAOAH=F;N?M?M@J<hZ7]YU"}gSD SE!TF"TF!K<wskwH9SE RD RD QDRCI>!J?#PBPCPBM?k]:]ZV"~iVG#VH%VH%VH%M>yvmyK<UG#UG#TG#TG#TF L@%ND)RDSE!SE PBm`=]ZV"jYJ&YJ(YK(YK(PA{wnyN@XJ'XJ'WJ&WI&WH#OC(QG-UG!UH$UH$SD!pb@^ZV"m\M)[M+\N+\N+SD|xoyQCZL)ZL)ZL)ZL)ZK'QF*TI/XJ$XK'XJ'UG$rdC^ZV!n^P,^P-_P/^P.VG#}ypyTE"]O-]O-]O,\N,]N*SH-VK1[L'[M*[M*YJ'tfE_ZW!oaR/`R1aS2aS1YJ&~zrxWH%`R0_Q0_Q0_Q/_Q-VJ0XL4^O*]P-]O-[L*vhH_[X!qdU2cU4dV5dV5\L){syZK(cT3bT2bT3bT2bT0YM2[O7`Q.`R1`R0^O-ykK_[X!sgW6fW7fX7fX7^O,|t{]N+eW6eW6eW6dV5dV3ZO5]R9cT1cU3cU3aR0|nN`\Y!uiZ9iZ:i[;i[:aQ/~v}`P.hY9hY9hY9gY8hX6]Q7_TiY7hZ:hZ9fX6sS`]Z!xn`?n_@n`An`Am_>i_Kuoauo`un`uobi_Ll]m^>l^>m^=hZ>mfWuo`tm_uo`ogYfZ=k]1 >3@2A3 A4 A7B6D5D7 E7E8F;G9H9H:H=HFHI>!J<J=KB-KC3L>L@%MB(N?N@N@ND)OF-PBPBQF*QG-QK<RDRD SH-TF"TI/UG$VH!VH%VJ0XJ&XTOYJ(YL#YM2YN5YUPZL)[L'[WT\M*\N&\WT]N,]Q7]YU^P-^Q*^R9_Q0_T<_XF_[X`Q.`R0`U>`]ZbT2cU4c^\dU2eV5eX6ea]fZ=gY8hY6hZ>iZ9i_Ki_Lj\:j\<jdVjfZl\;l]=lhdm_@mfWmgYn`>n`ApaBpbDpnmrdCrdErncroftfFtm_ufHulSun`vhHvqewhGwskykKyoWywpzpXzvm|nN|r[|r\|xo~pP~t]~zqsSv`|s}uxbuVwzd}wY}gy}z\~im~`noqosuwxz}}mDDDDDDDDDDDDDDDDDDDDDDDDDDD?_"-111111111-----------------%l_}%?5D 6D  mʵ' ;D 4Ӕ ;G4 AGy IG 󺑀OG &j OG / p UJ$$((S$$$$* \J+,,,i(((($!$$$^M1555 x---,+!+,,$bM6688$66655##011,gM:<<<($::888).5661qM>@@@1,>>>>;*3;::6sMHHHH55EEEEF29>>>:vMNNQN:8KKKKH7=FHH@zTVVYV>}{yqnkA:,). 8+6)6)5(5(5(5(5(5(5(5(5(4'ZM'zun$ wJ<9,;.:-:-:-:-9,9,9,9,:-9+*QLB=5'+9+8+8+8+7*7*7*7*6)6)6)6)\M'zvo$ wL=:-;.=0=0=0=0=0=0=0=0=/-"ZWS-0@2@2@2?1?1?2>1?21$hfcIC84&>0=0=01>1>1>1>1=0=01bT.{wp$ zSEB5 D7C6 C6 C6 C6 D6 ?0D<%JC25* 1&1%6, OI;9.?1B3A3@3@3A3A3@2bT0{wp$ zTFD7F9F9F9F9F9G:8*gc]0& :+D6E8 E8 B48*2)IB3<.C5 C5 C5 C5 B4 B4 A3 dV1{wp$ |UG!F8H:H:H:H:H:G9:-D<,@1I;F9F9F9E8G9;,JD7b_W;.D7D7 D7 C6 C6 C6 B5 eW3|wq$ |XJ"I;J=J=J=J=I<H:@47, J;H:I:H:H:H:H:F8 :/ {xu<.G9F8F8F9F9F9D6gY5|wq$ ~ZL%J<L>L>L>L>L>I:D9zwq?1 J=J=J=J=J=J=J=J;:.;/ I;I;I;I;H:H:F9hZ6}xr$ ~[M'L>N@N@N@N@N@I;H>(ie\C5 L>L>L>L>K>K>K=L>=/ yvq=1K=J<J<J<J<J<H;j\8}xr$ ]O*NAPCOBOAOAOAL<ME2a\RG8OAN@N@N@N@N@N@OA@1 sph>4M>L>L>L>L>K=I<k]:~yr$ _P,PBRDRDRDRDRDL>PH9^XLI;PBPBPBPBPBOBOBPCB4miaA6OAOAN@N@N@N@L>m_<~yr$ `R-RDTF!TF!TF!SE SE!N@SL=\VIK<RDRDQCQCQCQCQCRDD6mh_B8!QBOBOBOBOBOBN@n`=~yr$ aT0SF"VH$VH$UG$UG$UG#PAVOA]XKL?TF!SE!TF!TF!TF"TF"SF"TG!G7mj`D;%SERD RDQCRCRCOApb@zs$ dU1UG$WI&WI&WI&WI&VI&QCVPA_YLOAUH$VH$VH$UG#UG#UG#UG#VH#I:ojbH>*TFTF"TF"TF!TF!TF!RD rdBzt$ eV3WI&YK(XJ'XJ'XJ'XJ'TDXQC`YMQBVI&WI&WI&VI&VI%VI%VI%WJ%I;pjbJ@+VG UG#UG#UG#UG#TF#SE"seC{t$ hY6YJ)ZL*[M*[M)[M)[M*UG ZSDa[MSDYK(YK(YK(YK(YK(YK(YK(YL'L=okbMC.XJ#VJ%VJ%VJ%VH&WI&UG%ugF{t$ iZ7[M*]O,]O,\N,\N,\N+XI#ZSEa[NUF![M*[L*[L*[L*[L*[L*[L*\M*N@pkbMD0ZK%YK(YK(YK(YK(YK(XJ&vhG{v$ j\9\N,^P.^P.^P.^P.^P.ZK%\UFb[OWI#]O,\N,\N,\N,]N+\N+\N+]O+PBpkbOE1[L'[L*[L*[L*[L*ZL)YK(xiH{v$ l];^O.`Q0`Q0`Q0_Q/_R/[M(]UHc\PYK&^Q/_Q/^P/^P/^P.]O-]O-^P-SD!qlcPF2^O(]O+\N+\N+\N+\N,[M+zkJ|v$ n`=`R1bT3bT3bT2bT2bS2^N*]VIc\P[L(aR1`R0`Q0`R0`R0`R0`R0aS0UF$rlcRH4`Q+^P.^P.^P.^P.^P.]O,{lL|v$ o`>aS2cU4cU4cU4cU4cU4_P,^WJd]Q]N*bT2bS2bS2bS2bS2bS2aS2bT1VH%rldSI5aR.`R0`R0`R0_Q/_Q/^P.|nM|v$ rbAcU4eW6eW6eW6eW6eV5`Q-_YKd]S_Q-cU5cV4cV4cU4cU4cU3cU3dV4XJ(rmdTK6dU/aS2aS2aS2bT2bS2aR0pO}w$ sdCfW7hY9gY8gY8gY8gY8cT/`ZMe_TbS/fX7fW6fW6fW6eW6eW6eW6fW5ZL*qnfUL9eV2dV4dV4dV4cU4cU4bT2qR}w$ teDfX8hZ:hZ:hZ:hZ9hZ9dU2b[Mf`UbS0gY8gY8gY8gY8fX7fX7fX7gY7[M,rnfWM:gX4eX6eV5eV5eV5dV5cU4rS}w$ whGi[:k]l^>l^>l^>l^>iZ7c\QgaWfW4k]n_@n_@n_@m_@m_?n_=aWEqmgzunwtlwtlwslyunsoi_WFl]l^>l^>l]=l]=l]=l]=m^=j[:`XKsqkxtmwslwslwslytmlhb_T>l];j\eW7dV7eV7eV7dV7dU7fW9m_>l_>m^>m^>m^>l^>l^=k]=yZy$ ~nOoaBqcDqcDqcDqcDqcDqcDqcDrdDrdDrcCrcCrcCrcCqcCpbCobCobCpbCpbCpbCoaBoaBoaBoaBoaBpaBpbBpbBpaApaAoaAoaAoaAn`An`An_@n_@n_@m_@m_@m^?{]z$ ~pQqcDseFseFseFsdFrdErdErdErdErdErdErdErdEqcEqcEqcDqcDqcDqcDqcDqcDqcDqcDqcDqcDqcDqbCqbCpbCpbCpbCpbCpbCpbCpbCpbCoaBoaBoaBpaBpaBn`A|^z$ rSseGugIugIugHugHugHugHugHtfHseGseGseGseGtfGtfGtfGteGteGseFseFseFseFseFseErdErdErdErdErcErcEqcDqcDqcDqcDqcDqcDrdErdEqbCqbCqbCoaB~_{$ sTtfHvhJvhJvhJvhJvhJvhJvhJugJvhJvhJvhJvhIvhIugIugIugIugIugIugIugIugItfHtfHtfHtfHtfHtfHtfHtfHtfGtfGtfGtfGtfFseFseFseFrdFreFreFrdEa{$ qSseFtfHtfHtfHtfHtfHtfHtfHtfHtfHtfHtfHtfHtfHtfHtfHtfHtfHtfHtfHtfHtfHtfHtfHtfGtfGtfGtfGtfGtfGtfGtfGtfGtfGtfGseGseGseGseGseFseFrdEbz%}_qRsTsTsTsTsTsTsTsTsTsTsTsTsTsTsTsTsTsTsTsTsTsTsTsTsTsTsTsTsTsTsTsTsTsTsTsTsTsTrTrTqSp ½լꡙ颛颛颛颛颛颛颛颛颛颛颛颛颛颛颛颛颛颛颛颛颛颛颛颛颛颛颛颛颛颛颛颛颛颛颛颛颛颛颛颛顚鼵𠞛(0`'+. .# 0& 1'2$3)5(6+ 7/9,:. ;3#=1>0>4?1 A3A6B4 B;+C5C:#D9F8 F8H>)I;I;IB2IC8J@+JD7K=L=MC.MD1N@N@NANI<PBPBPF2PH9RDRD!RH4SL=SMATETF!TK6UF$UPKVH#VH%VM9VPAXI"XJ&XJ(XO=XQCZL&ZL)ZSDZWS[M,\M'\N*\N,]VF]VI^P)^P.^XK^XL_P0_T>`Q+`R-`R0`XKaWEaZMbT.bT1b\Pb_WcU4dU/dU2dV5d]Re_TfW9fX6fX8f`Vfc]hY6hZ9hfcie\j\:j\<l];l]=m_@mh_mian`=n`ApbBpjbqcDqlcqmerdBrdErnjspiteFtfHtoitssvhGvhIwslwtlxjIxskxslxtlzvp{lL|{y}nN}ys~pQpOqR{vrT|v~yuTvWy{wYyZ{]|^}_buay|p½X59997777777755555555555555555555555555550/}/5 9  >    > *{ B 3̟ G$  8 L$ E L'i  S(  S+ԽfX4  * Y4 f   ^5  "[ ^=####  gB$$$$$####### gG$(((((j$$$$###$kH),,)))&Z)(((((((|$$$$$#kM,/////$.O,,,,,)),q')(((($rS/55500'2K////////p+)))))(rY599777+>>>:,?>>>>4AW,:>>::::>u!5777750yg?CFCCF5DW/???????B$u%=::::>7}gFIIIIH=DW5FCCCCCCH)u&B?????>kIMMMMMBJZ9IIIIHHHH,u&BCCCCC?mMTTTPTGKZ>MPMMMIIM0w-LHHHHIFrTYYYYYHKZCTTTTTTTT7w1RMMMMMIrY\\\\\MN`HYYYYYYYY:w1STTTPPMt\cccc_SN`S\\\\\\\_?x6]YYYYYTybhddddXWaXccccccccCx;^___\\Y}dhhhhh^WeYddddcccgFx;cc____\kllkklcZe^hhhhhhhkM|;ghddddclnnnnngZecllllllkmP@kkkhhhdnooooorVx|JmnnnnnnnnkU|qQmllkkkhsttttttshbbbbbhossooosssoonb_____bonnnnnnntvvvvvvvzzvvvvvttttttttttttttttsssssoooooov}}}zzzzzzzzzvvvvvvvvvvvvvttttttttttttttts}~~~~~~}}}}~~~}}}}}}}zzzzzzzvvvvvvzztttt~~~~~~~~~~~~~}}}}zzzz}~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}}}}}}zʿŷ(0`333333333333333333333332"""""""""""""""""""""30#1#1#1#1#14DDD3#1DUDDDUC#14TDDDDDEC#1TDDDDDDDT0#14DDDDDDDDDB#2DDDDUUUDDDT#2TDDED3DTDDD0#2TDES EDDE@#24DDE0TDDB#25DDTEDDC#25DDSETDS#2EDES5TDS#2EDES5TDS#2"""EDUS 5UDT#2"""EDUS"""!5UDT!#2"""DDUC"""!5UDT""!#2"""#DDUC"""!5UDT"""#2"""#DDUC""""!5UDD"""32"""#DDEC""""!5TDD"""32"""#DDEC""""!5TDD""""32"""#DDEC""""!4TDD""""32"""#DDEC"""""4TDD""""32"""#DDEC"""""4DDD""""32"""#DDDC"""""4DDD""""32"""#DDDC"""""4DDD""""33"""#DDDC"""""4DDD""""33"""#DDDC"""""4DDD""""33"""#DDDC"""""4DDD""""33"""#DDDC"""""4DDT""""33"""#EDEC"""""4TDT""""33"""#3333"""""3333""""333332""""3""""""""""""33333333333333333333"""333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333C3333333333333333333333D333333333333333333333C(@ # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #1 #D #E #E #E #E #E #E #E #E #E #E #E #E #E #E #E #E #E #E #E #E #E #E #E #E #E #E #E #E #E #E #E #E #E #E #E #E #E #E #E #E #E #E #E #E #E #E #E #E #E #E #E #E #E #E #E #E #E #D #1 #¾ޭ񗑈󕏆󕏆󕏆󕏆󕏆󕏆󔏆󔏆󕏆󕏆󕏆󔏆󔏆󔏆󔏆󔏆󔏆󔏆󔏆󔏆󔏆󔏆󔏆󔏆󔏆󔏆󔏆󔏆󔏆󔏆󔏆󔏆󔏆󔏆󔏆󔏆󔏆󔏆󔏆󔏆󔏆󔏆󔏆󔏆󔏆󔏆󔏆󔏆󔏆󔏆󔏆󔏆󔏆󔏆󔏆󖐇󫦞󽻶 #D #rcAXI$VH"VH"VH"UG"UG"UG"UG"UG"UG"UG"UG"UG"UG"UG"UG"UG"TF!TF!TF TF TF TF TF TF TF TF TF TE TE TF TE TE TE TE TETETETETETETETETETETETETETETETETETETESDSDUF pa? #E #XI%5(3&3&3&3&3&2%2%2%2%2%2%2%2%2%2%2%2%2%2%1$1$1$1$1$1$1$1$1$1$1$1$1$0#0#0#0#0#0#0#0#0#0#0#0#0#0#0#0#/"/"/"/"/"/"/"2%UG" #E #WI#4'2$2$2$1$1$1$1$1$1#1#1#1#0#0#0#0#0#0#0#0#0#/"/"/"/"/"/"/"/"/"/"/"/"/"/".!.!.!.!.!.!.!.!.!.!.!.!.!- - - - - - - 0#TF #E #XJ%5(3%3%3%3%3%3%3%3%3%3%3%2$2$2$2$2$2$2$2$1$1$1$1$1$1#1#1#1#0#0#0#0#0#0#0#0#0#0#0#0#/"/"/"/"/"/"/"/"/"/"/"/"/".!.!1$UG" #E #ZL&7*4'4'4&4&4&3&3&3&3&3&3&3&3&3&3&3&3%3%3%3%3%3%3%3%3%3%3%3%3%2$2$2$2$2$2$2$2$2$2$2$1$1$1$1$1$1#1#1#1#0#0#0#0#0#0#3&WH# #E #ZL'8+5(5(5(4'4'4'4'4'4'4'4'4'4'4'4'4'4'4'4&4&4&3&3&3&3&3&3&3&3&3&3&3&3%3%3%3%3%3%3%3%3%3%3%3%3%2$2$2$2$2$2$2$2$2$2$4'WI# #E #[L'9,6)6)6)6)6)5(5(5(5(5(5(5(5(5(5(5(5(5(4'4'4'5(5(5'4&2$2$1$2$2$3%5'5'4'4&4&3&3&3&3&3&3&3&3&3&3&3&3%3%3%3%3%3%3%3%5(XI$ #E #\N):-7*7*7*7*7*7*7*7*7*7*7*7*7*6)6)6)6)6)6)7)4&,$#.&6.!81%;4)80%4- .%#$+3%6(5(5(5(5(4'4'4'4'4'4'4'4'4'4'4'4'4'4'4'6)YK& #E #]O*<.8+8+8+8+8+8+8+8+8+8+8+8+8+8+8+7*7*9+3%%6.#^YS]XR3, %1$7)6)6)6)6)5(5(5(5(5(5(5(5(5(5(5(5(5(8+ZL' #E #]O*=0:-:-9,9,9,9,9,9,9,9,9,9,9,9,9,9,8*&B=5<6/&7)7*7*7*7*7*7*6)6)6)6)6)6)6)6)6)6)9,[L' #E #^P+>0;.;.;.;.;.;.;.;.:-:-:-:-:-:-;-5')!zxxusr% 5'9+8+8+8+8+8+8+8+8+8+7*7*7*7*7*:-\M( #E #_Q,?107*5/'1+#7);.:-:-:-:-:-:-:-:-:-:-:-:-1>1>1>1>1>1>1=/-%)!;-0^P+ #E #aS/B5 @2@2@2@2@2@2@2@2@2?2?2@2,"~~~~)>0=0=0=0=0=0=01>1>1>1>1>1>1=0=0=0@2`Q- #E #dU1E8C5 C5 B4 B4 B4 B4 B4 B4 B4 B4 B4.$+"@2?2?2?2?2?2?2?2?2?2?2A4 aS. #E #dV2F9C6 C6 C6 C6 C6 C6 C6 C6 C5 C5 >1HB:kgcB;13+2)3*?8,`\VMHA;.A3A3@2@2@2@2@2@2@2@2B5 aS/ #E #fX3G9E8E8D7D7D7D7D7D7D7E7 5* zyw/(5)@2C5C5C5@28+*"zxv1&B4B4 B4 B4 A4A4A4A4A4A4C6 bT0 #E #gY5H:F9F9F9F9F9F9F9F9F9F8 4+*#B4F8 D7 D7D7 D7 C6 D7 D6(2)C5C5 C5 C5 C5 C5 B4 B4 B4 B4 D7cU0 #E #hZ6I<H:H:H:H:H:H:H:H:G9E7 B<1HCJ<J<J<J<J<J<I;I;I;C6 UPH1(I: H:H:H:G9G9G9G9G9G9H:7, urnVQI@2E8E8E8E8E8E8E8E8E8F9eW3 #E #j\8M?K=J=J=J=J=J=J=J=K=A4ie`rnj<0I;I;I;I;I;I;I;I;I;I;H:C6 NH@kgb<0 H:G9G9G9G9G9F9F9F9H:gX4 #E #k]:NAL>L>L>L>L>L>L>L>L>>2xusZUMD7J=J=J=J=J=J=J=J=J=J=J<I;@9-{xv:.I;I;I;I;I;I;H:H:H:I<gY5 #E #l^;OBN@N@N@N@N@N@N@M?N@=1KE;I;L>L>L>L>L>K>K>K>K=K=K=K=<4%:/K=J<J<J<J<J<J<J<J<K>i[7 #E #n_3C<0L>N@M?M?M?M?M?M?M?M?M?M?M?<3":/L>K=K=K=K=K=K=K=J=L>j[8 #E #n`>RE!QCQCPBPBPBPBPBPBQC>4C;.O@OBOAOAOAOAOAOAOAOAOAOAO@<3 :0N?M?M?M?M?M?M?L>L>M@j\9 #E #pa?SE"RDRDRDRDRDRDRDRDRD>5 A9+PBPBPBPBPBPBPBPBOBOBOBOBQB:1;1OAOAOAN@N@N@N@N@N@OAl]: #E #qc@UG#TF!TF!TF!TF!TF!SE SE SE!TF?5"B:*RCRDRDRDQCQCQCQCQCQCQCQCRD<2;2 QBOBOBOBOBOBOBOBOBQCm^; #E #rdBVI&TF#UG#UG#TF"TF"TF"TF"TF"VG?6$C;,SDTF!TF!SE SE SE SE SE!SE!RE!RE!RE TE=3=4"RDQCQCQCQCPBQCQCQCRD n_< #E #seCWI'VH%VH%VH%VH%VH%VH%VH$VH$WH!@7%D<,TFTF"TF"TF"TF"TF"TF"TF"TF"TF"TF"TF"UF>5!@7&SERE!RE RE RDRDRDRDRDSE"pa? #E #tfDYK(WI&WI&WI&WI&WI&WI&VI&VI&XI"A8&E=.WH!VH$VH$VH$VH$UG#UG#UG#UG#UG#UG#UG#WH!@6#B:*TFTF"TF"TF"TF"TF!TF!TF!TF!UG#qc@ #E #ufE[L*YK(YK(XJ'XJ'XJ'XJ'XJ'XJ'ZK%C:(F>/XI#VI&VI&WI&WI&VI&VI%VI%VI%VI%VI%VI%WI"A7$C;+VG UG#UG#UG#UG#UG#UG#TF#TF#VH%qc@ #E #vhG\N,[L*ZL)ZL)ZL)ZL)ZL)ZL)ZL)[L&D;)G?0YJ$XJ'XJ'XJ'XJ'XJ'XJ'XJ'XJ'XJ'XJ'WJ&YJ$B9%E=-WI"VI%VI%VI%VI%VI%VH%VH%VH%WI'sdC #E #whH]O-[M+[M+[M+[M*[M*[M*[M*[M*\M'E<*H@0[L&ZL)ZL)ZL)ZL)ZL)ZL)YK(YK(YK(YK(YK([L&C9&F>.YJ$XJ'WJ&WJ&WJ&WJ&WI&WI&WI&YK(tfD #E #xjI^P.]O,]O,]O,\N,\N,\N,\N+\N+^O)F=+IA2\M'[M*[L*[L*[L*[L*[L*[L*[L*[L*[L*[L*\M'D:'F>/ZK%YK(YK(YK(YK(YK(YK(YK(YK(ZL)tfE #E #ykJ`R0^P.^P.^P.^P.^P.^P.^P.^P.`Q+H?-JA3^O)]O,\N,\N+\N+\N+\N+\N+\N+\N+\N+\N+^O)F<)H?0[L'[L*[L*[L*[L*[L*[L*ZL)ZL)[M+vgF #E #zlKaR1_Q/_Q/_Q/_Q/_Q/_Q/_Q/_Q/aR-H?.KB4^P+^P.^P.^P.^P.^P.^P-^P-]O,]O,]O,]O,_P+G=*I@1]N(\N+\N+[M+[M+[M+[M+[M+[M+]O-whG #E #|mMbT3aR1aR1aR1aR1aR1`R0`R0`R0bS.J@/LC5`Q,_Q/_Q/_Q/^P/^P/^P/^P/^P.^P.^P.^P.`R,H>+I@1^O)]O,]O,]O,]O,]O,]O,]O,]O,^P.xjI #E #}oNdV4bT3bT3bT3bT3bT2bT2bS2bS2dT/JA0LD6bS-aR1aR1`R0`R0`R0`R0`R0`R0`R0`R0`R0bS/J@-KB4`Q,^P/^P.^P.^P.^P.^P.^P.^P._Q/yjJ #E #~pPdV5cU4cU4cU4cU4cU4cU4cU4cU4eV1KB1ME7cT/bT2bT2bS2bS2bS2bS2bS2bS2bS2aS1aS1cT/KA.LC4aR.`R0`R0`R0`R0_Q/_Q/_Q/_Q/aR1zlK #E #pQfX7dV5dV5dV5dV5dV5dV5dV5dV5fW3LC2NF8dV1cU4cU4cU3cU3bT3bT3bT3bT3bT3bT3bT3dV1KB/MD5cT/bS2aS1aS1aS1aS1aS1aR1aR1bT2|mL #E #rShY9fX7fX7fX7fX7fX7fX7fW6fW6gX4MD4OG9fW3dV5dV5dV5dV5dV5dV5dV5dV4dV4dV4dV4fW3MD1ME6dU0bT3bT3bT3bT3bT3bT3bT3bT3dV4}oN #E #sTi[:hY9hY9gY8gY8gY8gY8gY8gY8iZ5OF5PH:hY4fX7fW6fW6fW6fW6fW6eW6eW6eW6eW6eV5gX4NE2NF8eV2dV5dV4dV4dV4dV4cU4cU4cU4dV5}oP #E #tUj[;hZ:hZ:hZ:hZ:hZ:hZ9hZ9hZ9j[7OF5QI;hY5gY8gY8gY8gY8gY8gY8fX7fX7fX7fX7fX7hY6OF3OG8gX4eW6eW6eV5eV5eV5eV5dV5dV5fX7pQ #E #uWk]=j\;j\;j[;j[;i[;j[;j[;i[;k\9QH8RJl^>l^>l^>l^>l^>l^>l^>o`=RI9SK=l]:k][Q?gec~{x{yv{yv{yv{yv{yv{yv~{xljhWO?n_=l^>l^>l^>l^>l]=l]=l]=l]=l]=l]=l]=n_<\Q=ca_}{x{yv{yv{yv{yv{yv{yv~{xjhgWN>l]:j\l^@cV;_S9_S9_S9_S9_S9_S9_S9_R8aU:k]>l^=l]=l]=l]=l]=l]=l]=l]=l]=m^>vW #E #{]rdEqbCqbCpbCpbCpbCpbCpbCpbCpbCpbBqbBqbBpbApbApbApbApbApbApbApaAoaAn`An`An`An`An`An`An`An`An`An`An_@n_@n_@n`@o`?o`?o`?o`?o`?o`?n_?n_?n_?n_?n_?m_?m_?m_?m_?m_?l^?l^?l^>l^>n_@xY #E #|^sdFqcDqcDqcDqcDqcDqcDqcDqcDqcDqcDqcDqcDqcDqbCqbCqbCqbCqbCpbCpbCpbCpbCpbCpbCpbCpbCpbCpbBoaBoaBoaBoaBoaBoaBoaBoaBoaBoaBn`An`An`An`An`An`An`An`An`An`An_@n_@n_@n_@n_@n_@n_@oaByZ #E #}`tfHseFseFseFseFseFsdFrdErdErdErdErdErdErdErdErdErdErdEqcEqcEqcDqcDqcDqcDqcDqcDqcDqcDqcDqcDqcDqcDqcDqcDqcDqbCqbCqbCpbCpbCpbCpbCpbCpbCpbCpbCpbCpbCpbCoaBoaBoaBoaBoaBoaBoaBpbCz\ #E #bvhItfHtfHtfHtfGtfGtfGtfGtfGtfGtfGtfGtfGseFseFseFseFseFseFseFseFseFsdFsdFrdErdErdErdErdErdErdErdErdEqcEqcEqcDqcDqcDqcDqcDqcDqcDqcDqcDqcDqcDqcDqcDqcDqcDqcDqbCqbCqbCqbCqbCqcD{] #E #cvhJugIugIugIugIugIugIugIugIugHugHtfHtfHtfHtfHtfHtfHtfHtfHtfHtfGtfGtfGtfGtfGtfGtfGtfGtfGtfGtfGseFseFseFseFseFseFseFsdFsdFrdErdErdErdErdErdErdErdErdErdErdEqcDqcDqcDqcDqcDsdF|^ #E #dwiKvhJvhJvhJvhJvhJvhJvhJvhJvhJvhJvhJvhJvhJvhJvhJvhJvhIvhIugIugIugIugIugIugIugIugIugIugIugItfHtfHtfHtfHtfHtfHtfHtfHtfHtfHtfGtfGtfGtfGtfGtfGtfGtfGtfGtfGseFseFseFseFseFseFtfH}_ #E #dwiKvhJvhJvhJvhJvhJvhJvhJvhJvhJvhJvhJvhJvhJvhJvhJvhJvhJvhJvhJvhJvhJvhJvhJvhJvhJvhJvhJvhJvhJvhJvhJvhJvhIvhIvhIvhIugIugIugIugIugIugIugIugIugIugHtfHtfHtfHtfHtfHtfHtfHtfHtfHvhI~a #E #eykMwiKwiKwiKwiKwiKwiKwiKwiKwiKwiKwiKwiKwiKwiKwiKwiKwiKwiKwiKwiKwiKwiKwiKwiKwiKwiKwiKwiKwiKwiKwiKwiKwiKwiKwiKwiKwiKwiKwiKwiKwiKwiKwiKwiKwiKwiKwiKwiKwiKwiKwiKwiKvhJvhJvhJxjLd #D #}eddddddddddddddddddddddddddddddddddddddddddddddddddddddde} #1 #ܻ # #(@ # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #1 #D #E #E #E #E #E #E #E #E #E #E #E #E #E #E #E #E #E #E #E #E #E #E #E #E #E #E #E #E #E #E #E #E #E #E #E #E #E #E #E #E #E #E #E #E #E #E #E #E #E #E #E #E #E #E #E #E #E #D #1 #¾ޭ񗑈󕏆󕏆󕏆󕏆󕏆󕏆󔏆󔏆󕏆󕏆󕏆󔏆󔏆󔏆󔏆󔏆󔏆󔏆󔏆󔏆󔏆󔏆󔏆󔏆󔏆󔏆󔏆󔏆󔏆󔏆󔏆󔏆󔏆󔏆󔏆󔏆󔏆󔏆󔏆󔏆󔏆󔏆󔏆󔏆󔏆󔏆󔏆󔏆󔏆󔏆󔏆󔏆󔏆󔏆󔏆󖐇󫦞󽻶 #D #rcAXI$VH"VH"VH"UG"UG"UG"UG"UG"UG"UG"UG"UG"UG"UG"UG"UG"TF!TF!TF TF TF TF TF TF TF TF TF TE TE TF TE TE TE TE TETETETETETETETETETETETETETETETETETETESDSDUF pa? #E #XI%5(3&3&3&3&3&2%2%2%2%2%2%2%2%2%2%2%2%2%2%1$1$1$1$1$1$1$1$1$1$1$1$1$0#0#0#0#0#0#0#0#0#0#0#0#0#0#0#0#/"/"/"/"/"/"/"2%UG" #E #WI#4'2$2$2$1$1$1$1$1$1#1#1#1#0#0#0#0#0#0#0#0#0#/"/"/"/"/"/"/"/"/"/"/"/"/"/".!.!.!.!.!.!.!.!.!.!.!.!.!- - - - - - - 0#TF #E #XJ%5(3%3%3%3%3%3%3%3%3%3%3%2$2$2$2$2$2$2$2$1$1$1$1$1$1#1#1#1#0#0#0#0#0#0#0#0#0#0#0#0#/"/"/"/"/"/"/"/"/"/"/"/"/".!.!1$UG" #E #ZL&7*4'4'4&4&4&3&3&3&3&3&3&3&3&3&3&3&3%3%3%3%3%3%3%3%3%3%3%3%3%2$2$2$2$2$2$2$2$2$2$2$1$1$1$1$1$1#1#1#1#0#0#0#0#0#0#3&WH# #E #ZL'8+5(5(5(4'4'4'4'4'4'4'4'4'4'4'4'4'4'4'4&4&4&3&3&3&3&3&3&3&3&3&3&3&3%3%3%3%3%3%3%3%3%3%3%3%3%2$2$2$2$2$2$2$2$2$2$4'WI# #E #[L'9,6)6)6)6)6)5(5(5(5(5(5(5(5(5(5(5(5(5(4'4'4'5(5(5'4&2$2$1$2$2$3%5'5'4'4&4&3&3&3&3&3&3&3&3&3&3&3&3%3%3%3%3%3%3%3%5(XI$ #E #\N):-7*7*7*7*7*7*7*7*7*7*7*7*7*6)6)6)6)6)6)7)4&,$#.&6.!81%;4)80%4- .%#$+3%6(5(5(5(5(4'4'4'4'4'4'4'4'4'4'4'4'4'4'4'6)YK& #E #]O*<.8+8+8+8+8+8+8+8+8+8+8+8+8+8+8+7*7*9+3%%6.#^YS]XR3, %1$7)6)6)6)6)5(5(5(5(5(5(5(5(5(5(5(5(5(8+ZL' #E #]O*=0:-:-9,9,9,9,9,9,9,9,9,9,9,9,9,9,8*&B=5<6/&7)7*7*7*7*7*7*6)6)6)6)6)6)6)6)6)6)9,[L' #E #^P+>0;.;.;.;.;.;.;.;.:-:-:-:-:-:-;-5')!zxxusr% 5'9+8+8+8+8+8+8+8+8+8+7*7*7*7*7*:-\M( #E #_Q,?107*5/'1+#7);.:-:-:-:-:-:-:-:-:-:-:-:-1>1>1>1>1>1>1=/-%)!;-0^P+ #E #aS/B5 @2@2@2@2@2@2@2@2@2?2?2@2,"~~~~)>0=0=0=0=0=0=01>1>1>1>1>1>1=0=0=0@2`Q- #E #dU1E8C5 C5 B4 B4 B4 B4 B4 B4 B4 B4 B4.$+"@2?2?2?2?2?2?2?2?2?2?2A4 aS. #E #dV2F9C6 C6 C6 C6 C6 C6 C6 C6 C5 C5 >1HB:kgcB;13+2)3*?8,`\VMHA;.A3A3@2@2@2@2@2@2@2@2B5 aS/ #E #fX3G9E8E8D7D7D7D7D7D7D7E7 5* zyw/(5)@2C5C5C5@28+*"zxv1&B4B4 B4 B4 A4A4A4A4A4A4C6 bT0 #E #gY5H:F9F9F9F9F9F9F9F9F9F8 4+*#B4F8 D7 D7D7 D7 C6 D7 D6(2)C5C5 C5 C5 C5 C5 B4 B4 B4 B4 D7cU0 #E #hZ6I<H:H:H:H:H:H:H:H:G9E7 B<1HCJ<J<J<J<J<J<I;I;I;C6 UPH1(I: H:H:H:G9G9G9G9G9G9H:7, urnVQI@2E8E8E8E8E8E8E8E8E8F9eW3 #E #j\8M?K=J=J=J=J=J=J=J=K=A4ie`rnj<0I;I;I;I;I;I;I;I;I;I;H:C6 NH@kgb<0 H:G9G9G9G9G9F9F9F9H:gX4 #E #k]:NAL>L>L>L>L>L>L>L>L>>2xusZUMD7J=J=J=J=J=J=J=J=J=J=J<I;@9-{xv:.I;I;I;I;I;I;H:H:H:I<gY5 #E #l^;OBN@N@N@N@N@N@N@M?N@=1KE;I;L>L>L>L>L>K>K>K>K=K=K=K=<4%:/K=J<J<J<J<J<J<J<J<K>i[7 #E #n_3C<0L>N@M?M?M?M?M?M?M?M?M?M?M?<3":/L>K=K=K=K=K=K=K=J=L>j[8 #E #n`>RE!QCQCPBPBPBPBPBPBQC>4C;.O@OBOAOAOAOAOAOAOAOAOAOAO@<3 :0N?M?M?M?M?M?M?L>L>M@j\9 #E #pa?SE"RDRDRDRDRDRDRDRDRD>5 A9+PBPBPBPBPBPBPBPBOBOBOBOBQB:1;1OAOAOAN@N@N@N@N@N@OAl]: #E #qc@UG#TF!TF!TF!TF!TF!SE SE SE!TF?5"B:*RCRDRDRDQCQCQCQCQCQCQCQCRD<2;2 QBOBOBOBOBOBOBOBOBQCm^; #E #rdBVI&TF#UG#UG#TF"TF"TF"TF"TF"VG?6$C;,SDTF!TF!SE SE SE SE SE!SE!RE!RE!RE TE=3=4"RDQCQCQCQCPBQCQCQCRD n_< #E #seCWI'VH%VH%VH%VH%VH%VH%VH$VH$WH!@7%D<,TFTF"TF"TF"TF"TF"TF"TF"TF"TF"TF"TF"UF>5!@7&SERE!RE RE RDRDRDRDRDSE"pa? #E #tfDYK(WI&WI&WI&WI&WI&WI&VI&VI&XI"A8&E=.WH!VH$VH$VH$VH$UG#UG#UG#UG#UG#UG#UG#WH!@6#B:*TFTF"TF"TF"TF"TF!TF!TF!TF!UG#qc@ #E #ufE[L*YK(YK(XJ'XJ'XJ'XJ'XJ'XJ'ZK%C:(F>/XI#VI&VI&WI&WI&VI&VI%VI%VI%VI%VI%VI%WI"A7$C;+VG UG#UG#UG#UG#UG#UG#TF#TF#VH%qc@ #E #vhG\N,[L*ZL)ZL)ZL)ZL)ZL)ZL)ZL)[L&D;)G?0YJ$XJ'XJ'XJ'XJ'XJ'XJ'XJ'XJ'XJ'XJ'WJ&YJ$B9%E=-WI"VI%VI%VI%VI%VI%VH%VH%VH%WI'sdC #E #whH]O-[M+[M+[M+[M*[M*[M*[M*[M*\M'E<*H@0[L&ZL)ZL)ZL)ZL)ZL)ZL)YK(YK(YK(YK(YK([L&C9&F>.YJ$XJ'WJ&WJ&WJ&WJ&WI&WI&WI&YK(tfD #E #xjI^P.]O,]O,]O,\N,\N,\N,\N+\N+^O)F=+IA2\M'[M*[L*[L*[L*[L*[L*[L*[L*[L*[L*[L*\M'D:'F>/ZK%YK(YK(YK(YK(YK(YK(YK(YK(ZL)tfE #E #ykJ`R0^P.^P.^P.^P.^P.^P.^P.^P.`Q+H?-JA3^O)]O,\N,\N+\N+\N+\N+\N+\N+\N+\N+\N+^O)F<)H?0[L'[L*[L*[L*[L*[L*[L*ZL)ZL)[M+vgF #E #zlKaR1_Q/_Q/_Q/_Q/_Q/_Q/_Q/_Q/aR-H?.KB4^P+^P.^P.^P.^P.^P.^P-^P-]O,]O,]O,]O,_P+G=*I@1]N(\N+\N+[M+[M+[M+[M+[M+[M+]O-whG #E #|mMbT3aR1aR1aR1aR1aR1`R0`R0`R0bS.J@/LC5`Q,_Q/_Q/_Q/^P/^P/^P/^P/^P.^P.^P.^P.`R,H>+I@1^O)]O,]O,]O,]O,]O,]O,]O,]O,^P.xjI #E #}oNdV4bT3bT3bT3bT3bT2bT2bS2bS2dT/JA0LD6bS-aR1aR1`R0`R0`R0`R0`R0`R0`R0`R0`R0bS/J@-KB4`Q,^P/^P.^P.^P.^P.^P.^P.^P._Q/yjJ #E #~pPdV5cU4cU4cU4cU4cU4cU4cU4cU4eV1KB1ME7cT/bT2bT2bS2bS2bS2bS2bS2bS2bS2aS1aS1cT/KA.LC4aR.`R0`R0`R0`R0_Q/_Q/_Q/_Q/aR1zlK #E #pQfX7dV5dV5dV5dV5dV5dV5dV5dV5fW3LC2NF8dV1cU4cU4cU3cU3bT3bT3bT3bT3bT3bT3bT3dV1KB/MD5cT/bS2aS1aS1aS1aS1aS1aR1aR1bT2|mL #E #rShY9fX7fX7fX7fX7fX7fX7fW6fW6gX4MD4OG9fW3dV5dV5dV5dV5dV5dV5dV5dV4dV4dV4dV4fW3MD1ME6dU0bT3bT3bT3bT3bT3bT3bT3bT3dV4}oN #E #sTi[:hY9hY9gY8gY8gY8gY8gY8gY8iZ5OF5PH:hY4fX7fW6fW6fW6fW6fW6eW6eW6eW6eW6eV5gX4NE2NF8eV2dV5dV4dV4dV4dV4cU4cU4cU4dV5}oP #E #tUj[;hZ:hZ:hZ:hZ:hZ:hZ9hZ9hZ9j[7OF5QI;hY5gY8gY8gY8gY8gY8gY8fX7fX7fX7fX7fX7hY6OF3OG8gX4eW6eW6eV5eV5eV5eV5dV5dV5fX7pQ #E #uWk]=j\;j\;j[;j[;i[;j[;j[;i[;k\9QH8RJl^>l^>l^>l^>l^>l^>l^>o`=RI9SK=l]:k][Q?gec~{x{yv{yv{yv{yv{yv{yv~{xljhWO?n_=l^>l^>l^>l^>l]=l]=l]=l]=l]=l]=l]=n_<\Q=ca_}{x{yv{yv{yv{yv{yv{yv~{xjhgWN>l]:j\l^@cV;_S9_S9_S9_S9_S9_S9_S9_R8aU:k]>l^=l]=l]=l]=l]=l]=l]=l]=l]=m^>vW #E #{]rdEqbCqbCpbCpbCpbCpbCpbCpbCpbCpbBqbBqbBpbApbApbApbApbApbApbApaAoaAn`An`An`An`An`An`An`An`An`An`An_@n_@n_@n`@o`?o`?o`?o`?o`?o`?n_?n_?n_?n_?n_?m_?m_?m_?m_?m_?l^?l^?l^>l^>n_@xY #E #|^sdFqcDqcDqcDqcDqcDqcDqcDqcDqcDqcDqcDqcDqcDqbCqbCqbCqbCqbCpbCpbCpbCpbCpbCpbCpbCpbCpbCpbBoaBoaBoaBoaBoaBoaBoaBoaBoaBoaBn`An`An`An`An`An`An`An`An`An`An_@n_@n_@n_@n_@n_@n_@oaByZ #E #}`tfHseFseFseFseFseFsdFrdErdErdErdErdErdErdErdErdErdErdEqcEqcEqcDqcDqcDqcDqcDqcDqcDqcDqcDqcDqcDqcDqcDqcDqcDqbCqbCqbCpbCpbCpbCpbCpbCpbCpbCpbCpbCpbCpbCoaBoaBoaBoaBoaBoaBoaBpbCz\ #E #bvhItfHtfHtfHtfGtfGtfGtfGtfGtfGtfGtfGtfGseFseFseFseFseFseFseFseFseFsdFsdFrdErdErdErdErdErdErdErdErdEqcEqcEqcDqcDqcDqcDqcDqcDqcDqcDqcDqcDqcDqcDqcDqcDqcDqcDqbCqbCqbCqbCqbCqcD{] #E #cvhJugIugIugIugIugIugIugIugIugHugHtfHtfHtfHtfHtfHtfHtfHtfHtfHtfGtfGtfGtfGtfGtfGtfGtfGtfGtfGtfGseFseFseFseFseFseFseFsdFsdFrdErdErdErdErdErdErdErdErdErdErdEqcDqcDqcDqcDqcDsdF|^ #E #dwiKvhJvhJvhJvhJvhJvhJvhJvhJvhJvhJvhJvhJvhJvhJvhJvhJvhIvhIugIugIugIugIugIugIugIugIugIugIugItfHtfHtfHtfHtfHtfHtfHtfHtfHtfHtfGtfGtfGtfGtfGtfGtfGtfGtfGtfGseFseFseFseFseFseFtfH}_ #E #dwiKvhJvhJvhJvhJvhJvhJvhJvhJvhJvhJvhJvhJvhJvhJvhJvhJvhJvhJvhJvhJvhJvhJvhJvhJvhJvhJvhJvhJvhJvhJvhJvhJvhIvhIvhIvhIugIugIugIugIugIugIugIugIugIugHtfHtfHtfHtfHtfHtfHtfHtfHtfHvhI~a #E #eykMwiKwiKwiKwiKwiKwiKwiKwiKwiKwiKwiKwiKwiKwiKwiKwiKwiKwiKwiKwiKwiKwiKwiKwiKwiKwiKwiKwiKwiKwiKwiKwiKwiKwiKwiKwiKwiKwiKwiKwiKwiKwiKwiKwiKwiKwiKwiKwiKwiKwiKwiKwiKvhJvhJvhJxjLd #D #}eddddddddddddddddddddddddddddddddddddddddddddddddddddddde} #1 #ܻ # #(@$% (*+#,#-%.!/(/( 1(2$2*3-"5(6+ 9,:.:/;5,<0 <2<3"=0=1?8,@2@6#@7%A4B5 B8%B:*B:-B;1B<0B=5D:'D;)E8E=-F8F<*G?0H:H>+H?-H?0HB:HC<I;I@1J@.JE?KB4KE;KG@L>LC2LC4MD5MH@NANE2NF8O@PBPBPG4QH9RDRDRD RH6RJ<TETF!UPHVH"VH%WN>XI"XJ&YK(ZL&ZL)ZUM[Q?\M'\N*\N,\Q=]XR^P+^P._R8`Q+`R-`R0`\VaT:bT2cT/cU4cV<ca_dT/dV1dV5eX=fX3fX6gY8gechZ6hZ9j\9j\<jfajhgl]:l^=ljhm^@n`>n`Apa>pbBqcDrdBrdErnjtfFtfHurnusrvhGvhJxjIxjLxuszlKzxvzxx|nM}oP}{x~pP~~rRsTtUuWwXxYz\|^}`~acd}¾èÂROOOOOOOOOOOOOOOOMMMMMMMMMMMLLMLLLLLLLLLLLLLLLLLLLLLLLHHMS  OR  MS  OU OU RU  RZ SZ ]̴] UZ%՚U^وYa ZbZb^caf69bl(bl*1w# d>co*(((((((((  fp3*********( ((((( (gs3333-----*#2********( #((((*ls:333333333N ----******-N(*(((((((*ou::33333333w3333333333->w-********3oy?:::::::::W(33333333333-3333333333pyD???????:B83:::::::::::3333333333:s}D????????C$:?::::::::::B::::::::3:u}IDDDDDDDDC"B???????????BB::::::::?uMHHHHHHHHG!CDDDDDDD????CB?????????yOMMMMMIIML!GHHHDDDDDDDDGC????????DyPMOOMMMMMO"GMMIIIIMMIIILGDDDDDDDDI}SPPPPPPPPO)LMMMMMMMMMMMLLIIIHHHHHMTSSSSSSPPR )OPPPPOOOOOOOO!LMMMMMMMMOVTTSSSSSSU&,RPPSSPPPPPPPR!OOOOOOOMMP[VVVVVVVVU',SSSSSSSSSSSSS )RPPPPPPPPS[ZZZZZZZZY+0UVVVVVVTTTTTU )SSSSSSSSST_[[[[[[ZZ^+4YZVVVVVVVVVVY&,UTTTTTTTTVc________a/7^[[ZZZZZZZZZ^+0UVVVVVVVVZc________b/7^_______[[[[^+4YZZZZZZZZ[fccccccccg5gѡT2.4*s;8aϝN,)-$o62]ΙI&"&n1-X͗D k*&Tʓ? kV!!Pɏ: Lnj6P5_HƉ2"EĆ.yȒ%A4 "HǬ]@>;9:<Eo#ѾG͕}||~~|zz|}dhnhadlh`g޶vWܨT[S[_۳qRNUMVZ|ڰmLJPGRVxٮhFCKBMPs׫eA>E<~GJp֪`;7A5}@Flӥ\45/$4BiҢX0eOs9'?eҡT3->*;bϝQ0(0ƚ@!+6_΢V852)6@9*.32>eӼw^\ZXYZ[c1ΆLJLԢŊqsysopopwtnu侃eԪaiagn_ڰ\d\ciߺ{YޱW^V^d޸vTPYPY_޵sNKTITY}ݲnHEOBLTzگjAA<1I@Pv٭f>n[}4Ls٫b@:J8Hpק_=6<ĞK/8DmխdEB?6CLF7Kba`bM<>=>Xb`aZ><=<9W;<==3v}0;7:>7:96S8:'.v}-998848;4663P}5787*t{*500590330N{2455(sx'2232.36.10-Ky/1%rx%0q!""kv "߿#;nbz 7l W #5j G ' ) 1h /Y .f  1/Y ,f osf)ch'a?ـ%`< #^ a̵5"] "\ Vs >Ѓ֚gghgegfgfgfedca|eefedcdcbbaa_zߚbbcbca]]\\`ba`a][ZZ[`_]wߙ`_``^_opoo`]^ZgonnhY]]\Zuߙ]T}߂R\[ZSݾU[ZZXsߕZZ[[P~PY;VRTXWWUpߓWWXXN}MWWVVTPRTUURnߒUUVVK{JTRNPROlߐRRSSIzGRQ;OKMOPOLiߍOOPPGzEPONNLIKLMMJgMMNNDxALIFIJKJGeJJKK@w>JGDFGHHDcGH=v;GDA߿CEB`DF;s8DA>?BCB?]BC8m5BA>=;??@6<=<9X==>>4Y/<5D1:7V9:;;3H62;:9$g+73T778851+')%Df(41Q~55455(w}q8-20/P}12334/3o#100/-N|/01011&Mׁ$-.-+M{-.!Iـ$',+'Jy*+,,+, ,jDzC'*)(%Hx() *$)34/"&'&#Fw&&'&'&%$"$%%$%$# Dr !! >@BCBA@@A@HDEdHHIIBQ@BIHG4l9DEDAbDDEEC=7562Kk7CBB?_B=C7z涀wB;@?@=]@@A@A>=r2>==<:\==>4S0:;:8Z;9.(+40S43434320233211.Q}.-,+*&LOPONJnؒl8mk~f  ich#Hih32D̾}fedcg˼meMLMLKOhcLJIHGF JfcJIIHGFEDGcaHFEDCBEb_FDCDDCBCBA@A@D`]ECB@;:>@A@=879>?=A_\C@?=EglkliG<>= :Kjkjjkka?;=<;@]ZA>8PW6<;;2g>8:>\X@<5NU4;:1e<6988  s <6 /9W ;4Z6 92  *5= 91 ֩^ 70 /  6.  d׀; 5-T3,s݀ۂM3+Dӊ)2* @vͺh.0)$# /'.&-#+'/I.,+,,+*).N빜ӋDɜmɧɜɴȘҦ$jihlyihgfe hwhggfedcfwfedcbad}w}dcbcbababba``_b|w{cbaab`ZXYXY^`_]WVX^a{wzb_WntstoW]^] ^[XpsrrssgT]\\[_ywx`^[]˂bX]\ RoܻP[Z^xww_]]\]]X\ހaV[Z[[Z [Qn޺NZZY\vwu\ZVZހ_TYXYOn܀޺MXWVZuwt\YTYހ_SXWMl܀޺LV UUYtwrYWRYހ_QVUVLl܀޺LUTSWswpWUQWހ]OTSTJl܀޺JR QQUpwoVT SOV]MRHk݀޺HPTowmTR NU[KP Ek޺FNONRmwkSP KU[ION ODk޻FLML PkwkQOON IS[HML MAk޻DKOkwiOL GRYEK ?j޻CIJ IIMiwgMKJ EQYCI =j޺AGFJhwfLI DPXAHG H;jߺ?F JhweJHHG BPW?F 9i޴;D CDDHewcHFEE@MV=DDC D7h߳8BFcwbFD >JXBaw_C@ ;>d6> =>0uߙ1=<A`w^A> ;8v1= <-ߋ.; ::?^w\?=<:2+<:;: 8-y-89=]wZ=: 9+<2:9 89-F`-76;\wY;9+d$,5775+)E.5 449[wW:761:C(%%*Jߨ+143 449ZwV8545$ԫg$27YwU6434.<߬'/1 005XwT5212#jF'0 //../4WwR30/ހقـ[/-2UwQ2/+vׁ݁U, +0TwP1.-, -+N݀ ̋7+*++*)/TwO/+*"M{Ƕo=!*))(.RwN.*)*%'144/#%)(' -QwL-))('( &''&%#"##%&%%&%%$*PwL+'&%$#)OwJ)%$#"!'MwL,*))()(''('&'&,PwiPNMLKOluç{yw{N$Nλ3̦׫6xwvwvz}wvuts v{vuutsrqt{tsrqpor{rqrqpopopoonp{rpoopnhfgfgmnmnledfmlo{pnmmn`ryxyt_l mj_txwwxxl_ljm{nlidրigkjk`tπַYjiihl{mkkjkkgdـheihiih i^tٸXihgk{jhebـgcgf g]sٷWge dh{jhgcaـgbfe f[rٷVed ccg{hfea`ـf_dc dZsٷUdbe{ec__ـe]b abWsٷTa` __c~{~db ^_e[a` aUrٷR_^b}{|b` \]dY__^ _SrٷP]]\`{{z`^ Z]dW]\ ]QqٸP[ Z^z{y_]]\ W[cV[ \OqٸNZY]x{x][ U[aTY ZLq۸MXW VVZw{v[YX TZaQVWWV XJqܷKVUTXv{uZW VRX`OVU VIpݷIT Wv{sWVVU PX_MT UFo޲ER QRRUs{rVTSSOU^KRRQ RDoްBPOSq{pTR MS_JPOOPBoޭAOON Rp{oSPPO KNdGON @uޥ?MLPn{nPN IHjCLK ={ܚJ 9ۍ:I HHMl{jMJ H=7JHIH F8}9FKk{iJHG7C@HGFFEG;Mf:DCIi{gIF8j.:CEEC81M;C BBGi{fGDC*?CK2004R٦6?BA@@AAFh{dECBC/Ӯڀl0@?Df{dCA B ==Bf{bC@?)>?0nM4>==<<;;b{^>;:9:9'Uڀ؁ƌ?*98776.?@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@>+  it32]¿y~mjhjm~^~webabew~X leSOONMORdlEibPMKJLOaiFiaNKJIHIL^fFhaNKJIHGHGHHL]dChaNKJIHGHGHGK]dChaNKJIHGHGFGJ\dCg`MJIHGHGEDGJ[cCg`MJIHGHGFEDFI[cCf_LIHGHGFEDCDGZbCf_LHHGFEDCDGZbCd]KGHGFEDCBCFYaCd\JGFEDCBCFYaCd\JGDCBA@BEW_Cc[IFDCBA@?@?@AEW_CbZHECBA@?@??@?CV^CbZHECBBA@A@?@?@??@?>?CT]CaYFCBA@?><=>?@?@@??<;988::>>=?CT]CaYFCBAA@BBCCBCCBA@?>>?@@A@?@?>>=>AT]C`XEB@ ?@@?C[amopopond^D??>?>=<<>BW^mopopond]C>::<;=@T]C`XEA@?>>?EgptkF?==>=<BbktkE>::<;=@T]C^VC?@?>==9FыӹL=::<;:98DЋӷJ;88:;>R[C^UC?>==9HߋîM=::<;:97D݋K:889:;>R[C]UC?>=<;;9G߇޽M=99;:986C߇޽J98988:=PYC]TB?=<;;9Gއ޽M=88;:876Cއ ݽI9778987889=PYC]TA=;998Fއ޽L<88:9875Bއ ݽH86678;OXC]T@=;878Fއ ޽L;889:98 7874BއݽH8657;NXC[R>;:9877Eއ ޽K:6678 7763AއݽG7547567;NWC[R>;:9 8875Dއ޽K:657663AއݽG754657;MWCZQ=:98 7655Dއ ޾J95577876 55442@އ ݽG73255459LVCZQ=:87875Dއ ޾J954776 55442@އ ݽG72255458LVCYP<987874Cއ޽I84354331?އݽG700347LVCYP;78764CއݽH84354330>އ ݽF5002347KUCWN;765332Aއ۽G72143110>އ ݽE50022125ISCWM;75332AއڼG700430/0>އ ݽE400121025ISCVL9541@ބ ڼG71021 0//=܄ݽD3/014HRCVL854001@ބ ڻG600121 00/.=܄ݽD3/./0/3HRCVL74320?ނغF5..010/0/-<܂ ݽD3--//0/.//3GQCUK7432 10//?ނػF5../00/0/-<܀܂ ݽD3-,//./3FQCTJ6310/?ނټE4--/0/0/,,+:݁܀ݽA0*),.2EPCTJ630/0/../?ނځۼF4-,/. ,,+:׀܀޽B0*),.2DOCRH410 /.-.>ހ۽E3,+.-,++*9ڀݽA0)(+-1DOCRH400/--.>ހ۾E3,+.-,++*9ڀ ޽B/)(*+-0DOCQG3//.++-=ݿD2*),+)8޾A/)(*)+.CNCQF3/.++-=ݿD2)(,+(7׀ ޾A.(()*)+.CNCPE3/,+ ))+;׀ C1)(*(7ـ޾A.'&'(),BMCPE2.,+((+;C0)()*)(''7׀ ޾A.&%'((,BMCOD1-+*((*:¬A.('()(''&&6޾@-%%''('('+ALCOD0-+* )(():ـ¬A.(''('('& 6׀ ޾@-%$''&'+@LCOD0,**)(''(9íA.&%'('('$$%5޾?,#"%&'+@KCOD/,**))('(9ĬA.%$'&&$$%5޾?,#"%'+?KCMB-*('&&'8ĮA.%#&%""$4ݾ=*! #%)*&#" $5Ʈ?* ! ! 1ڵ3!#9D@I>*&#"!! #5Ʈ?*     1ڴ3!#8D@G<'#! ! !2ŭ=(  0ڶ1#8C@G<&# "  !2ŭ=(0ڶ1#7C@G<&" 0ɱ>).گ1!6B@G<%! 0ʲ>)/ٮ/!6B@F;$ /ڀѹB,2ک,5A@F;#-ڀӻC,2٧*5A@D9#)ڀ׿D, 4ـ ٟ'4@@D8#'ڀE- 5ـٜ'4@@C7! %tځN5#9فٓy#4@@C7! #rف Q8$:فؐv!3@@B6i^D(A؅j1>@B6edH+Dׂg1>@@4Xrw[ 7RtY 0=~@@4Snc! >YpU 0=~@@4 C^ـޢ# ]y׀ _D /<~@@3 >X߮)  jY>/<~@?2  /HہԾK1  0տH.    .;~@?2  *Bـ[@   '?ـ йB)   .;~@~>1  0ـۣ&  e޽0 +9}@~>1 *كݶ8#   $}ـܵ) +9}@~>;:64+' "1y@{2# !$$! "1y@{2# /y@z1# /y@z2#.x@z1#.x@z0".x@z0"-x=z/!-x@z/!,x=y-*x=z-+x@z/!-x@}3$ !0|@G:# 8FFUG2.-,+*))+/ESH|yxwx{MH|UNB>@=@=@FFMH(     ""÷¿t[~}~XqnlkmpH ~nkihghghil}D }lihghghgj}C }lihghgfgj{C }lihghgfegjzC }lhhgfefizC }khghgfedcdgy~C }jghgfedcdgy~C }kggfedcbcfx}C |jgfedcbcfx}C zjgedcbabew|C zifedcb`bew|C ~ygdcba`adv{C ~ygdcba`a`_`_`_cv{C }xgdba`_`_^__cuzC }xgdba`_``__`_^_^_btzC |weba`aa`_ZXXWVWWX_`_`_`_^^__XWVUTSSVW\]^^]^atzC |web`_`_`_^YYZY\\_^^]]XWXXWX[[^^]^asyC {vda`a_TTbftvtvtieSR^_^]_^SS^bsvtvtgcRQ\]\[]`rxC {vc_`_``_RSkqvoTQ]_^]_^QSfltmSP[]\[]`rxC zuc__^__]MU͋δWM[]\][KS̋δUKY[Z[^qwC ztb_^_]KUًۼYM[]\]ZJS؋ۼWKY[Z[^qwC ztc_]_]KUމٻXMZ\[\ZJSމٺVKXZYZ]pvC ztb_]^\KUމٺXMZ\[\YJSމٹVKXZYZ]pvC xr`]\[\ZJTމٺWLY[ZYYZY[XJSމٹUJWYXY\ouC xr`]\[\YJTމٺWLY[ZYYZY[XJSމٹUJVYXWXWXX\ouC wq^[Z[XJTމٺVKWYXYVIRމٹUJVXWXWXW[msC wq^[Z[XISމٺVKWYXWXWXXVIRމٹUIUWVWZlsC vp^[YZWISމٺUJWYX WXXWUHQމٹTHUWVUW[lsC vp^[YXZWISމٺUJUWXW VVWUGQމٹTHTVUVYlsC uo\YXUGQމ ٺUJVWXWVWWUGPމٹSGSUTVYlsC uo\XXWUFQމٺUIUWVWUFPމٹSGSUTVYlsC sm[WXWVWWUFPމٺTHTVUTVTDNމٹRFRTSRTWjqC sl[WVWUEPމٺTHTVUTVTDNމٹRFRTSRTWjqC sl[WUVTDOއڻSGRTS TRCMهٹQEPRQRUipC slYVUVTDOއڻSGRTS TRCMهٹQEPRQRUipC slZVTSTRCNޅ؁ڼRFQSR SQBLهٹPDOQPQTgnC slYVTSTRCNޅ؀۽SFQSR SPBLهٹPDNOPOPPTgnC qjWTRSQBMރ؁ڽQEOQP ROBLمٹNBNPSgnC qjWTRSPBMރ؁ܽREOQPOPO PQOAKمٹNANOSfnC piURQRPBMރ ݾQDNP M@JځفٹNAMNMNOSelC piURQROBMރ ݾQCNO M?JځفٹNALNMORdlC ohURPQNBMށ؃ ߿PCNPPOPON OOM?IށځٺNAKLMQdlC ohUQPOPOMBMށ؃߿PBNON OM>IށځٺNAJLMPdlC ngSPOPO POM@Kف PBLML MKJށ®OAKLKLJ;FځٺM@HJIKNckC kdSOMK>Jށ­OAJLKLJ;FځٺM@HJIKNckC kdRNLJ=I܀®OAIJH;FځٺL?GIHILaiC kdQNLJ=IíOAHJH:FځٺL?FHGHGHHLaiC kdOLKJKIFGE8EڹH:EFGK_g@ ibLIHF:FůM=FGFGE7DٵG9DEDEI]e@ ibLHHGE9FůM=EFD7DصF9CEDEI\d@ haLHGHHGHGHGE9EůL@?@?@@DZb@ d\IECBCA6AкM5Cק=2>@?@??@?CYa@ d\HECBCA6@ҼM;?@AB@?@>4Cץ=1=?>?CXa@ d\GCBA?5?տO5C֞<1=>=?CW`@ d\FCBA@@A?5>P=>>?>4D֛<1<>=>BW`@ c[EB@>3;zWC<;??>=<5FՓ};1;=<>BW`@ c[EA@?>2;wZF;:>=<6GԒ{:1;=<>BW`@ bZD@@? >>?>3:oف eP;8=<<;;8JہӅo809;:<@U^@ bZC??>=3:kفiS<8<=<<::;Nہ҂l819;:<@U^@ aYC?>=<5:av݁{d71:;:989DYڀyb718:9:>T]@ aXC?=<5:]r݁܃k819; :968J`ځt_619:9:=T]@ `WB><;:7:Ncޣ7+8:9:8/5e|dO63789=T]@ `WB><;:79J^߯:-79:97.6q_K52788QҾR>54898786+;܁ ϻQ>557878787;S\@ _V@<:!9988:KaL3178998787 335G܁ ʶL954767;R\@ ^U>:9886.>ށ؁ܤ4'36787887785#+m܁ ٸ<,45457;R[@ ^U>:98786,:ށ؁߶@1336676 43+6܁ ذ8)4547;Q[@ ]T=986,4u؁فӒ|4)+,12521-+%-cy܁فՓ|4)246:PZ@ ]T<8876,4i؁فݨF91033433113={܁ف҈q2)246:PZ@ ]T<8876503FZ܁ف!Ԯh[?8.,**+,6;R^܁ځ `K1.23259OY@ \S<876512=P܁ف!õrSL?=::<>HNiu܁ځ ѾT@2023259OY@ [R;76543)6ރفހہك׫7)/1248OY@ [Q;7542'2݃ف¿ہكԛ1%0248OY@ ZP;7432-1K`܁فހ ہڃbM.*01026MW@ ZP:6432/1>R܁فہڃ˸S?.,010/0/016MW@ YO952 1/(3|فمڇ܅م Փ|1%.0/015MW@ YO9520%-iفمڇۅمˀi+"./005MW@ YO84210/?ك؁ًځك ذ<,+,/0/0/.//4LV@ YO84210.(4Ѐك؁ًځك ϝ0#,-/./3KV@ XN620 /0/)+ڇ؁هى У8*))..-/3KV@ WM510/0/ (*;Kޟ ثE5*(,-,+.2JU@ WM500/ ..//((+8ܟ ɕ4''(,-,+.2JU@ VL4//.- ()0;{ړÊv7,((**+*-1IT@ VL3//.- ('#+cvړ лq^( &(+*-1IT@ VL4/.-,++)((,JX߅݅ȾQD+&'(()*),0HS@ VK3/-,-*(!6Bsɳ}n<1 ')*),0HS@ VK3/+*))(+>FdmȿlbE<)&'(()(+/HS@ VK2.+*(+*'%+2LUrzzrTK0)$&()('('(*/HS@ UJ1-*)('('&'),7:@ADDGGCC@?96,)'&'('()-GR@ UJ1-*)(''&! %',-/011/.,+&$ $%'((-GR@ SH0,)('('&%%&%&'&%&',EP@ SH0,)('('&&$%%'&%',DP@ SH/+(''&'&%$%',EP@ SH/*('&%$',DP@ SH.*('('&%$#&+CO@ SH.)('&%$#&*CO@ QF,'&%$#"!$)CO@ QE,'%$#"!$(CO@ PE,'%$#"! #'BN@ PE,'%$#"! #'BN@ PD,'&%$#"%)CO@ SH0,+*)('('&'(-GR@ f\IECBABBA@BEZdF qfSPONONMNNMLNRcnH M H |UNBD@FFMH$  źĈķyf[ ~{zyz}K zwxwvwzF zwwvutwzF zwvutvyF zwvutstwF zwvutstwF yvutsrqsvF yvutsrqsvF yvtsrqtF yvtsrqpqtF wtsrqpsF wtsrqpoporF vsqpoponoosF vsqpoponorF urqpqpopononmlnqF urpoponoonmlmmnnmlnqF spopopomhgcefklnmlkedabcjklmpF ronoljfedehinmjidcbcghlmpF soonmom_^fjx{x{ymi\\lnlnl`_bfvxxwxyxkg\\jljknF ronmom\]msxq[Zknlnl]]iovo[ZiljknF qnlmolW]͉ɱ^VilkjliV\̉ɱ\TgjihjmF qnlolU]ӋԻ_VilkjliU\؊Ի]TgjihghhimF pmlknkU]ׇ Ը_VhkjjikhT[ׇԶ]Tfihk~F pmlknkU]և Ը_VhkjjikhTZև Զ]Tfhhgk}F nkjiij iikhT\ՇԸ^UgjhjgSYՇԶ\Sehghgfggk~F nkjiij iikhS[Շ Ը^Ugihg hifSYՇԶ\Rdgfgk|F mjhjgS[ՇԸ]Tehghg hgeSYՇ Զ\Segfedfj|F mjhghg hifS[Շ Ը]TeghgfgdRYՇԶ\Rdgedfi|F ~lihieS[Շ Ը\Seggfe fgdRXՇԶ[QbedcdgzF ~lhhg hgdS[ՇԸ\RdgfegdQYՇԶ[QbedcdgzC ~kghgf ggdQYՇԸ\RegdfcPWՇԶZPadbdgzF |kgfgdPYՇԸ\RcfdfcPXՇԶZPadbdgzC |kgdfcOXՇ׺[QadcbdaNVՇ ԶZP`cbbabey~C |ifdfcOXՇػ[QadcbdaNVՇ ԶZP`cbba`bey~C {gdcebNWՆ ڼZP`cba c`NV׆ԶYO^a`adw|C {gdcebNWՅ ۽[P`cba c`NVՄ ԶYO^``_`_cw|C zgdbdaMVՄ ޾ZO_ba` b_MUׄ ԶXN]_`_^__cv{C zgdbdaMVՃ ޾ZO_b`_`_`a_MUՂԶXM]_^_cu{C ~yeba`b_MVՂ ߿ZO]`_`_`_]KSׂԶVK]_]^btzC ~yeb`_`_ `a_MVՁ ߿ZN]_^_\JSՁԶVK\^]^atzC |wda`a^KTՀYM]_^]^_]KS׀ԶVK[]\[]atzC |wd``_ ``^KTՀYM\^]_\JSԶVK[]\[]`tzC {vc__^__]KT݀ XL\^]]\^[IRԷUJY[Z[^syC {uc_^_\JT߀ XL\^]]\^[IRԷUJX[Z[^syC ztc_]\ _\JT܂WKZ\[ \YGP ԷUJWZYZ]qwC zta^]\^[IS߀WKZ\[\YGPԷTIWZYYXZ]qwC zta][\YHR߀¯VJY[ZY [XFO ԷTIVYXY\qwC zt`][\YHR߀®VJX[ZY XX[XFOԷTIUWXWXW[qwC ys_\[[Z [XGQۀ ¯VJWYX YVENڀԷSHUWXWVWW[pvC ys_\[[Z[XGQӀ߀ ®VJVXXW XWUEOԷSGUWVW[ovC xr^[YX ZWFP݀ïUIUWXWWXWXXWXWVWWUDNշQETVUTVZmtC xr^[XWXWXYWFPӀ߀ ïUHUWVWV WUCN շQETVUTVZmtC wq\YX!WXWWXWUDNïTHUWWVUWUBMָPDRTUYmtC wq[WXWV WUCN߀ ïTGUWVUWTBMַPDRTUYmtC vp[WWVWWUCMՀ߀ ïSFRT URBM߀մMBQSRSWlsC vo[WVWTBMՀįSFRTURAL߀ճMBPSRSVlsC unZVTTUTVTBMՀ߀ ïREQSTSRTQ@K ֮LAORQPPQRUlsC unZVTTUTVSBMՀۀįREQSTSRTQ@K ֮K@ORPOPPOPRUkrC tmYUTSTQBLԀۀ îQDPRQRO?J߀֯I>NQPQTjqC tmYUTSTQBLԀۀ įQDPRQPRO?J߀֮I>MOPOPOSjqC slWSROAJӀۀ ŰQCNPQN=H߀լH>MOPONOOSipC slVSROAJӀۀ ƲQBNOPOM=H߀ժH=MONOShpC slURQPQNAJӀۀ ̷TENPOPOPOM?K ԦFK ԤFKހҞEKހҜELހГDFHGHGHGKdlC nfQMKKJKJBEbtڅpC=GIH GBCQd vbC>FGFGKclC meOKJI HDFUg߂ ޣ?5FIHF;@i~hUC@EFEGKajC meOKJIHGDEQc׀݀ ޮB6EG E9@u݀dRB@EFJajC ldMIHGFEDT߀ ҾWEABGGHGFEC3A܀ʷTDAADCFJ`iC ldLHHGEE@PՀހ dP@>FGFE A@@CDC A?4> ӯA4ACBDH_hC kcKGFEDEC7?v߀ ԓ~=279>@C @?:7/6g|ϓ~<3@BACG^gC kbKGEDEC8>l܀ިM@==?@A @@?==:C~̉t;4@BACG^gC i`JFCB>?L^߀ծm`F@754457>CXcdQ=;@A@BF]fC h`JFCB@@CT܂ķuYRFDBBDFOUlx˹YG>=?@@?@?@AF]fC i`IECBA?4?Հ߀׀ Ѫ>1=@?@AE]fC h`IECB@2;ׁހ¿ցϚ9.=?@@E]fC f^GCA@9;Pcׁ߂ ׁ eQ:8>??>=>?D\eC f^GCA@ ?<=?C[d@ e]FB@ ?@>1;~Ձ ߉ ցΓ}9/;=<=?D\eC e]FA@?=07lց ލ Ձ Ɓl4-<>=<?C[d@ e]EA@?@?> ??;:8FՃۃ݃׃ ҮB489<;>BZc@ e]E@@?> =;0;փځ܁փ ˛7,9;<;>BZc@ d\D?>= >=78AQՅ׉Յ ҵM>77:;:<@Yb@ d[C?= >>876CՅ֋Յ ʠ>278;;:<@Yb@ d\D?=<;;<;67@NՊԃՊ ҪL>449:98;?Yb@ d[C?< ;;=<762>ׁ՗ԁ Ŕ;045:;9878778:?Yb@ cZB>;:9667A}Փʿx>44578:>Xa@ cZB>;: ;:75,3gy֘ ˷tb0)36778789>Xa@ bYA=:9877615O[ׅׅĻUJ30557878787678=W`@ bYA=:98786*,=Guԇı~pC9*)67678=W`@ bY@<87765525ELiqɁļpgIB3122556567:87876%77665544220034>AFHIIMMIHGE@>43001133445479876!7743.,'&%&.056789987430.&%&'+-2366546;T^@ `W=8765432233223323435:S]@ `W=8765454421123354359S]@ _V<76543249S]@ _U<7543248S]@ _V<754321037S]@ _U<74320/0/027S]@ ]S:53210/0//005Q[@ ]S953210/0/./05Q[@ ]S94210/0/.-./4PZ@ ]S94210/0/-./4PZ@ ]S953210/0/016Q[@ aW>9876546;T_C ulVSRQPOPONOPTirH }sa]\[ZY[^r{H M H XUBD@HHMH(   "  "t8mk@). F) K/X<Z>[?[?[?[?[?[?[?[?[?[?[?[?[?[?[?[?[?[?[?[?[?[?[?[?[?[?[?[?[?[?[?[?[?[?[?[?[?[?[?[?[?[?[?[?[?[?[?[?[?[?[?[?[?[?[?[?[?[?[?[?[?[?[?[?[?[?[?[?[?[?[?[?[?[?[?[?[?[?[?[?[?[?[?[?[?[?[?[?[?[?[?[?[?[?[?[?[?[?[?[?[?[?[?[?[?[?[?[?[?[?[?[?[?[?Y>T<)-EKXZ[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[YT8/)/<>??????????????????????????????????????????????????????????????????????????????????????????????????????????????????> * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_FOREVER_TASK_H_ #define _U2_FOREVER_TASK_H_ #include namespace U2 { /* need for congene not to die */ class ForeverTask : public Task { Q_OBJECT public: ForeverTask(); ~ForeverTask(); virtual void run(); }; // ForeverTask } // U2 #endif // _U2_FOREVER_TASK_H_ ugene-1.9.8/src/ugenecl/src/TaskStatusBar.h0000644000175000017500000000305711651544337017234 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _TASK_STATUS_BAR_CON_H_ #define _TASK_STATUS_BAR_CON_H_ #include #define TSB_SETTINGS_ROOT QString("task_status_bar_settings/") namespace U2 { class TaskStatusBarCon : public QObject { Q_OBJECT public: static const QString NO_TASK_STATUS_BAR_CMD_OPTION; private: static bool helpRegistered; static void setTSBCmdlineHelp(); public: TaskStatusBarCon(); ~TaskStatusBarCon(); private slots: void sl_taskStateChanged(Task* t); void sl_taskStateChanged(); void sl_update(); private: void setTSBSettings(); void updateState(); void setTaskToTrack(Task* t); Task* taskToTrack; QString emptyLine; }; }//namespace #endif ugene-1.9.8/src/ugenecl/src/LogDriver.cpp0000644000175000017500000002766011651544337016737 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "LogDriver.h" #include #include #include #include #include #include #include "TaskStatusBar.h" #ifdef Q_OS_WIN32 #include "windows.h" #endif #include //#include #define LOG_SETTINGS_ROOT QString("log_settings/") namespace U2 { const QString LogDriver::LOG_SHOW_DATE_CMD_OPTION = "log-show-date"; const QString LogDriver::LOG_SHOW_LEVEL_CMD_OPTION = "log-show-level"; const QString LogDriver::LOG_SHOW_CATEGORY_CMD_OPTION = "log-show-category"; const QString LogDriver::LOG_LEVEL_NONE_CMD_OPTION = "log-level-none"; const QString LogDriver::LOG_LEVEL_ERROR_CMD_OPTION = "log-level-error"; const QString LogDriver::LOG_LEVEL_INFO_CMD_OPTION = "log-level-info"; const QString LogDriver::LOG_LEVEL_DETAILS_CMD_OPTION = "log-level-details"; const QString LogDriver::LOG_LEVEL_TRACE_CMD_OPTION = "log-level-trace"; const QString LogDriver::COLOR_OUTPUT_CMD_OPTION = "log-color-output"; const QString LogDriver::LOG_SETTINGS_ACTIVE_FLAG = "activeFlagLevel"; //const QString LogDriver::LOG_FORMAT = "log-format"; //const QString LogDriver::LOG_LEVEL = "log-level"; bool LogDriver::helpRegistered = false; LogDriver::LogDriver() : printToConsole (true) { connect(LogServer::getInstance(), SIGNAL(si_message(const LogMessage&)), SLOT(sl_onMessage(const LogMessage&))); if( !helpRegistered ) { setLogCmdlineHelp(); } setLogSettings(); setCmdLineSettings(); } void LogDriver::setLogCmdlineHelp() { assert( !helpRegistered ); helpRegistered = true; CMDLineRegistry * cmdLineRegistry = AppContext::getCMDLineRegistry(); assert( NULL != cmdLineRegistry ); CMDLineHelpProvider * logFormat = new CMDLineHelpProvider( CMDLineCoreOptions::LOG_FORMAT, tr( "Specifies the format of a log line." ), tr( "Specifies the format of a log line." "\n\nUse the following notations:" " L - level, C - category, YYYY or YY - year, MM - month, dd - day," " hh - hour, mm - minutes, ss - seconds, zzz - milliseconds." " \n\nBy default, logformat=\"[L][hh:mm]\"." ), tr( "\"\"" )); CMDLineHelpProvider * logLevel = new CMDLineHelpProvider( CMDLineCoreOptions::LOG_LEVEL, tr( "Sets the log level." ), tr( "Sets the log level per category. If a category is not specified," " the log level is applied to all categories." "\n\nThe following categories are available: \n\"Algorithms\"" ", \"Console\", \"Core Services\", \"Input/Output\", \"Performance\"" ", \"Remote Service\", \"Scripts\", \"Tasks\"." "\n\nThe following log levels are available: TRACE, DETAILS, INFO, ERROR or NONE." "\n\nBy default, loglevel=\"ERROR\"." ), tr( "\"= [= ...]\" | " )); CMDLineHelpProvider *coloredOutput = new CMDLineHelpProvider( LogDriver::COLOR_OUTPUT_CMD_OPTION, tr("Enables colored output.")); cmdLineRegistry->registerCMDLineHelpProvider( logFormat ); cmdLineRegistry->registerCMDLineHelpProvider( logLevel ); cmdLineRegistry->registerCMDLineHelpProvider(coloredOutput); } QString LogDriver::getLevelName(int i) const{ switch(i) { case 0: return "TRACE"; case 1: return "DETAILS"; case 2: return "INFO"; case 3: return "ERROR"; default: return ""; } } void LogDriver::setLogSettings() { CMDLineRegistry *cmd = AppContext::getCMDLineRegistry(); if(cmd->hasParameter(CMDLineCoreOptions::LOG_FORMAT)) { QString logFormat = cmd->getParameterValue(CMDLineCoreOptions::LOG_FORMAT); settings.showLevel = logFormat.contains("L", Qt::CaseSensitive); settings.showCategory = logFormat.contains("C", Qt::CaseSensitive); settings.showDate = logFormat.contains(QRegExp("[M{2}Y{2,4}d{2}H{2}m{2}s{2}z{3}]")); settings.logPattern = logFormat; } else if(cmd->hasParameter( LOG_SHOW_DATE_CMD_OPTION ) || //old options cmd->hasParameter( LOG_SHOW_LEVEL_CMD_OPTION ) || cmd->hasParameter( LOG_SHOW_CATEGORY_CMD_OPTION )){ settings.logPattern = ""; if (cmd->hasParameter( LOG_SHOW_DATE_CMD_OPTION )) { settings.showDate = true; settings.logPattern += "[hh:mm]"; } if (cmd->hasParameter( LOG_SHOW_LEVEL_CMD_OPTION )) { settings.showLevel = true; settings.logPattern += "[L]"; } if (cmd->hasParameter( LOG_SHOW_CATEGORY_CMD_OPTION )) { settings.showCategory = true; settings.logPattern += "[C]"; } } else{ settings.logPattern = "[hh:mm][L]"; } QString logLevel; if(cmd->hasParameter(CMDLineCoreOptions::LOG_LEVEL)){ logLevel = cmd->getParameterValue(CMDLineCoreOptions::LOG_LEVEL); } else if( cmd->hasParameter( LOG_LEVEL_NONE_CMD_OPTION ) ){ logLevel = "NONE"; } else if(cmd->hasParameter( LOG_LEVEL_ERROR_CMD_OPTION )) { logLevel = "ERROR"; }else if( cmd->hasParameter( LOG_LEVEL_INFO_CMD_OPTION ) ) { logLevel = "INFO"; } else if( cmd->hasParameter( LOG_LEVEL_DETAILS_CMD_OPTION ) ) { logLevel = "DETAILS"; } else if( cmd->hasParameter( LOG_LEVEL_TRACE_CMD_OPTION ) ) { logLevel = "TRACE"; }else { logLevel = "ERROR"; } LogServer* ls = LogServer::getInstance(); const QStringList& categoryList = ls->getCategories(); logLevel = logLevel.remove(" "); QStringList cats = logLevel.split(QRegExp("[,=]")); LogCategories::init(); if(cats.size() == 1) { int minLevel = 10; for (int i=0; i= minLevel); } foreach(const QString &str, categoryList) { LoggerSettings cs; cs.categoryName = str; for (int i=0; i= minLevel); } settings.categories[str] = cs; } } else { foreach(const QString &str, categoryList) { LoggerSettings cs; cs.categoryName = str; QString catWithoutSpaces = str; catWithoutSpaces = catWithoutSpaces.remove(" "); if(logLevel.contains(catWithoutSpaces)) { int ind = cats.indexOf(catWithoutSpaces); QString level = cats[ind + 1]; int minLevel = 10; for (int i=0; i minLevel); } } } else { for (int i=0; ihasParameter( COLOR_OUTPUT_CMD_OPTION )) { colored = true; } else { colored = false; } if (cmdLineRegistry->hasParameter( CMDLineCoreOptions::TEAMCITY_OUTPUT )) { settings->setValue( LOG_SETTINGS_ROOT + "teamcityOut", true ); } } QString LogDriver::prepareText(const LogMessage& msg) const { QString prefix = settings.logPattern; prefix.replace("C", getEffectiveCategory(msg)); prefix.replace("L", LogCategories::getLocalizedLevelName(msg.level)); QStringList date = GTimer::createDateTime(msg.time).toString("yyyy:yy:MM:dd:hh:mm:ss:zzz").split(":"); prefix.replace("YYYY", date[0]); prefix.replace("YY", date[1]); prefix.replace("MM", date[2]); prefix.replace("dd", date[3]); prefix.replace("hh", date[4]); prefix.replace("mm", date[5]); prefix.replace("ss", date[6]); prefix.replace("zzz", date[7]); QString spacing = prefix.isEmpty() ? QString() : QString(" "); QString text = prefix + spacing + msg.text; return text; } void LogDriver::sl_onMessage(const LogMessage& msg) { if (!printToConsole || !settings.activeLevelGlobalFlag[msg.level]) { return; } QString effCategory = getEffectiveCategory(msg); if (effCategory.isEmpty()) { return; } //this is Hard Code if (msg.text.contains(QString("##teamcity"))&&(!AppContext::getSettings()->getValue("log_settings/teamcityOut",true).toBool())) { return; } if (effCategory == ULOG_CAT_USER_INTERFACE) { return; //do not print UI related messages } QByteArray ba = prepareText(msg).toLocal8Bit(); char* buf = ba.data(); #ifdef Q_OS_WIN32 // a bit of magic to workaround Windows console encoding issues CharToOemA(buf,buf); #endif if(AppContext::getSettings()->getValue(TSB_SETTINGS_ROOT + "showTaskStatusBar", true).toBool()){ printf(" \r");//80 spaces for remove TaskStatusBar } if(!colored/*AppContext::getSettings()->getValue(LOG_SETTINGS_ROOT + "colorOut", false).toBool()*/){ printf("%s \n", buf); }else{ #ifdef Q_OS_WIN32 if (msg.level==LogLevel_ERROR){ SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_INTENSITY | FOREGROUND_RED ); } else if (msg.level==LogLevel_DETAILS){ SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_INTENSITY | FOREGROUND_GREEN ); } else if (msg.level==LogLevel_TRACE){ SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_INTENSITY | FOREGROUND_BLUE ); } printf("%s \n", buf); SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), 0x0007); #else //TO DO: for MacOs release coloring function if (msg.level==LogLevel_ERROR){ printf("\e[31m%s \e[0m\n", buf); }else if (msg.level==LogLevel_DETAILS){ printf("\e[32m%s \e[0m\n", buf); }else if (msg.level==LogLevel_TRACE){ printf("\e[34m%s \e[0m\n", buf); } #endif } fflush(stdout); } QString LogDriver::getEffectiveCategory(const LogMessage& msg) const { QString result; foreach (const QString& category, msg.categories) { const LoggerSettings& cs = settings.getLoggerSettings(category); if (cs.activeLevelFlag[msg.level]) { result = category; break; } } return result; } }//namespace ugene-1.9.8/src/ugenecl/src/DumpVersionTask.cpp0000644000175000017500000000344711651544337020135 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include #include #include #include #include "DumpHelpTask.h" #include "DumpVersionTask.h" namespace U2 { const QString DumpVersionTask::VERSION_CMDLINE_OPTION = "version"; const QString DumpVersionTask::VERSION_CMDLINE_OPTION_SHORT = "v"; void DumpVersionTask::initHelp() { CMDLineHelpProvider * versionSection = new CMDLineHelpProvider( VERSION_CMDLINE_OPTION, tr( "Shows version information." ), "", // No full description "", // No arguments VERSION_CMDLINE_OPTION_SHORT); AppContext::getCMDLineRegistry()->registerCMDLineHelpProvider( versionSection ); } DumpVersionTask::DumpVersionTask() : Task(tr("Dump version information task"), TaskFlag_None) { } void DumpVersionTask::run() { fprintf(stdout, "%s", DumpHelpTask::VERSION_INFO.toAscii().constData()); fprintf(stdout, "Using Qt %s\n", qVersion()); } } // U2 ugene-1.9.8/src/ugenecl/src/TestStarter.h0000644000175000017500000000423011651544337016757 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_TEST_RUNNER_PLUGIN_H_ #define _U2_TEST_RUNNER_PLUGIN_H_ #include #include namespace U2 { class GTestSuite; class GTestFormat; class TestViewController; class GTestEnvironment; class TestRunnerTask; #define NUM_THREADS_VAR "NUM_THREADS" class TestStarter : public Task { Q_OBJECT public: TestStarter(const QStringList& urls); virtual ~TestStarter(); virtual void prepare(); virtual void cleanup(); virtual ReportResult report(); const QList getTestSuites() const {return suites;} void addTestSuite(GTestSuite*); void removeTestSuite(GTestSuite*); GTestSuite* findTestSuiteByURL(const QString& url); GTestEnvironment* getEnv() { return env;} signals: void si_testSuiteAdded(GTestSuite* ts); void si_testSuiteRemoved(GTestSuite* ts); public slots: void sl_refresh(); private: void readSavedSuites(); void saveSuites(); void readBuiltInVars(); void deallocateSuites(); void readEnvForKeys(QStringList keys); void saveEnv(); void updateDefaultEnvValues(GTestSuite* ts); TestRunnerTask* createRunTask(); QStringList urls; QList suites; GTestEnvironment* env; TestRunnerTask* ttask; }; } //namespace #endif ugene-1.9.8/src/ugenecl/src/ForeverTask.cpp0000644000175000017500000000235511651544337017267 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include #include #include "ForeverTask.h" #define FOREVER_TASK_LOG_CAT "Forever task" namespace U2 { Logger log( FOREVER_TASK_LOG_CAT ); ForeverTask::ForeverTask() : Task( "Forever task", TaskFlag_None ) { log.trace( tr( "Forever task created" ) ); } ForeverTask::~ForeverTask() { } void ForeverTask::run() { QEventLoop loop; loop.exec(); } } // U2 ugene-1.9.8/src/ugenecl/src/DumpLicenseTask.cpp0000644000175000017500000000355311651544337020070 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include #include #include #include #include "DumpLicenseTask.h" namespace U2 { const QString DumpLicenseTask::LICENSE_CMDLINE_OPTION = "license"; const QString DumpLicenseTask::LICENCE_FILENAME = "license"; void DumpLicenseTask::initHelp() { CMDLineRegistry * cmdlineRegistry = AppContext::getCMDLineRegistry(); CMDLineHelpProvider * helpSection = new CMDLineHelpProvider( LICENSE_CMDLINE_OPTION, tr( "Shows license information." )); cmdlineRegistry->registerCMDLineHelpProvider(helpSection); } DumpLicenseTask::DumpLicenseTask() : Task(tr("Dump license information task"), TaskFlag_None) { } void DumpLicenseTask::run() { QFile file(QString( PATH_PREFIX_DATA ) + ":" + LICENCE_FILENAME ); if(!file.open(QIODevice::ReadOnly)) { setError("Cannot find license file"); return; } QByteArray licenseText = file.readAll(); fprintf(stdout, "%s", licenseText.constData()); } } // U2 ugene-1.9.8/src/ugenecl/src/DumpHelpTask.h0000644000175000017500000000250711651544337017041 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_HELP_DUMPER_ #define _U2_HELP_DUMPER_ #include namespace U2 { class DumpHelpTask : public Task { Q_OBJECT public: static void dumpHelp(); // for debug uses only static void dumpParameters(); static const QString VERSION_INFO; public: DumpHelpTask(); virtual void prepare(); protected: /// Called by scheduler when subtask is finished. virtual QList onSubTaskFinished(Task* subTask); }; } //namespace U2 #endif ugene-1.9.8/src/ugenecl/src/ShutdownTask.h0000644000175000017500000000243711651544337017140 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_SHUTDOWN_TASK_H_ #define _U2_SHUTDOWN_TASK_H_ #include #include namespace U2 { class ShutdownTask : public Task { Q_OBJECT public: ShutdownTask(QCoreApplication* app); void prepare(); ReportResult report(); protected slots: void startShutdown(); protected: virtual QList onSubTaskFinished(Task* subTask); private: QCoreApplication* app; }; }//namespace #endif ugene-1.9.8/src/ugenecl/src/Main.cpp0000644000175000017500000004530611651544337015723 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "ForeverTask.h" #include "LogDriver.h" #include "ShutdownTask.h" #include "TestStarter.h" #include "TaskStatusBar.h" #include "DumpLicenseTask.h" #include "DumpVersionTask.h" #include "DumpHelpTask.h" #include #define TR_SETTINGS_ROOT QString("test_runner/") /* TRANSLATOR U2::AppContextImpl */ using namespace U2; static void registerCoreServices() { ServiceRegistry* sr = AppContext::getServiceRegistry(); TaskScheduler* ts = AppContext::getTaskScheduler(); Q_UNUSED(sr); Q_UNUSED(ts); // unlike ugene's UI Main.cpp we don't create PluginViewerImpl, ProjectViewImpl // ts->registerTopLevelTask(sr->registerServiceTask(new ScriptRegistryService())); } // we will run task that don't die //static void setCongeneStayAlive() { // AppContext::getTaskScheduler()->registerTopLevelTask( new ForeverTask() ); //} static bool openDocs() { bool ret = false; QStringList suiteUrls = CMDLineRegistryUtils::getParameterValuesByWords( CMDLineCoreOptions::SUITE_URLS ); if( suiteUrls.size() > 0 ) { TestStarter* ts=new TestStarter( suiteUrls ); GTestEnvironment* envs=ts->getEnv(); envs->setVar(TIME_OUT_VAR, AppContext::getSettings()->getValue(TR_SETTINGS_ROOT + TIME_OUT_VAR,QString("0")).toString()); envs->setVar(NUM_THREADS_VAR, AppContext::getSettings()->getValue(TR_SETTINGS_ROOT + NUM_THREADS_VAR,QString("5")).toString()); QObject::connect(AppContext::getPluginSupport(), SIGNAL(si_allStartUpPluginsLoaded()), new TaskStarter(ts), SLOT(registerTask())); ret = true; } return ret; } static void updateStaticTranslations() { GObjectTypes::initTypeTranslations(); } static void setScriptsSearchPath() { QStringList scriptsSearchPath; const static char * RELATIVE_SCRIPTS_DIR = "/scripts"; const static char * RELATIVE_DEV_SCRIPTS_DIR = "/../../scripts"; QString appDirPath = QCoreApplication::applicationDirPath(); if( QDir(appDirPath+RELATIVE_SCRIPTS_DIR).exists() ) { scriptsSearchPath.push_back( appDirPath+RELATIVE_SCRIPTS_DIR ); } else if( QDir(appDirPath+RELATIVE_DEV_SCRIPTS_DIR).exists() ) { scriptsSearchPath.push_back( appDirPath+RELATIVE_DEV_SCRIPTS_DIR ); } if( scriptsSearchPath.empty() ) { scriptsSearchPath.push_back("/"); } QDir::setSearchPaths( PATH_PREFIX_SCRIPTS, scriptsSearchPath ); } static void setDataSearchPaths() { //set search paths for data files QStringList dataSearchPaths; const static char * RELATIVE_DATA_DIR = "/data"; const static char * RELATIVE_DEV_DATA_DIR = "/../../data"; //on windows data is normally located in the application directory QString appDirPath = QCoreApplication::applicationDirPath(); if( QDir(appDirPath+RELATIVE_DATA_DIR).exists() ) { dataSearchPaths.push_back( appDirPath+RELATIVE_DATA_DIR ); } else if( QDir(appDirPath+RELATIVE_DEV_DATA_DIR).exists() ) { //data location for developers dataSearchPaths.push_back( appDirPath+RELATIVE_DEV_DATA_DIR ); } if( dataSearchPaths.empty() ) { dataSearchPaths.push_back("/"); } #if (defined(Q_OS_LINUX) || defined(Q_OS_UNIX)) && defined( UGENE_DATA_DIR ) //using directory which is set during installation process on linux QString ugene_data_dir( UGENE_DATA_DIR ); if( QDir(ugene_data_dir).exists() ) { dataSearchPaths.push_back( QString(UGENE_DATA_DIR) ); } #endif QDir::setSearchPaths( PATH_PREFIX_DATA, dataSearchPaths ); //now data files may be opened using QFile( "data:some_data_file" ) } static void setSearchPaths() { setDataSearchPaths(); setScriptsSearchPath(); } class GApplication: public QCoreApplication { //Move to the core? same code in ugenecl and ugeneui public: GApplication(int & argc, char ** argv): QCoreApplication(argc, argv) {} virtual bool notify(QObject * receiver, QEvent * event ) { bool res = false; #if defined(USE_CRASHHANDLER) && defined(NDEBUG) try { res = QCoreApplication::notify(receiver, event); } catch(...) { if(CrashHandler::buffer) { CrashHandler::releaseReserve(); } CrashHandler::runMonitorProcess("C++ exception|Unhandled exception"); } #else res = QCoreApplication::notify(receiver, event); #endif return res; } }; int main(int argc, char **argv) { #if defined(USE_CRASHHANDLER) && defined(NDEBUG) CrashHandler::setupHandler(); CrashHandler::allocateReserve(); #endif const char* build = QT_VERSION_STR, *runtime = qVersion(); if (strcmp(build, runtime) > 0){ printf("Installed Qt version must be %s or greater \r\n", QT_VERSION_STR); return -1; } if (argc == 1) { Version version = Version::ugeneVersion(); fprintf(stderr, "Console interface for Unipro UGENE v%s\n" #ifdef Q_OS_WIN "Hint: Use 'ugeneui.exe' command to run GUI version of UGENE\n" "Hint: Use 'ugene.exe --help' or 'ugene.exe --help=' for more information\n" #else "Hint: Use 'ugene -ui' command to run GUI version of UGENE\n" "Hint: Use 'ugene --help' or 'ugene --help=' for more information\n" #endif , version.text.toAscii().constData()); return -1; } GTIMER(c1, t1, "main()->QApp::exec"); GApplication app(argc, argv); QCoreApplication::addLibraryPath(QCoreApplication::applicationDirPath()); QString devPluginsPath = QDir(QCoreApplication::applicationDirPath()+"/../../installer/windows").absolutePath(); QCoreApplication::addLibraryPath(devPluginsPath); //dev version setSearchPaths(); AppContextImpl* appContext = AppContextImpl::getApplicationContext(); // parse all cmdline arguments CMDLineRegistry* cmdLineRegistry = new CMDLineRegistry(app.arguments()); appContext->setCMDLineRegistry(cmdLineRegistry); //1 create settings SettingsImpl* globalSettings = new SettingsImpl(QSettings::SystemScope); appContext->setGlobalSettings(globalSettings); SettingsImpl * settings = new SettingsImpl( QSettings::UserScope ); appContext->setSettings( settings ); AppSettings* appSettings = new AppSettingsImpl(); appContext->setAppSettings(appSettings); UserAppsSettings* userAppSettings = AppContext::getAppSettings()->getUserAppsSettings(); // set translations QTranslator translator; QString cmdlineTransl = cmdLineRegistry->getParameterValue(CMDLineCoreOptions::TRANSLATION); cmdlineTransl = cmdlineTransl.isEmpty() ? cmdlineTransl : "transl_" + cmdlineTransl; QString transFile[] = { cmdlineTransl, userAppSettings->getTranslationFile(), "transl_" + QLocale::system().name(), "transl_en" }; bool trOK = false; bool skipFirst = transFile[0].isEmpty(); bool skipSecond = transFile[1].isEmpty(); for (int i = 0; i < 4; ++i) { if((i == 0 && skipFirst) || (i == 1 && skipSecond)) { continue; } if (!translator.load(transFile[i], QCoreApplication::applicationDirPath())) { fprintf(stderr, "Translation not found: %s\n", transFile[i].toAscii().constData()); } else { trOK = true; break; } } if (!trOK) { fprintf(stderr, "No translations found, exiting\n"); return 1; } app.installTranslator(&translator); updateStaticTranslations(); // 2 create functional components of congene LogDriver logs; coreLog.details(AppContextImpl::tr("UGENE initialization started")); ResourceTracker* resTrack = new ResourceTracker(); appContext->setResourceTracker(resTrack); TaskSchedulerImpl* ts = new TaskSchedulerImpl(appSettings->getAppResourcePool()); appContext->setTaskScheduler(ts); AnnotationSettingsRegistry* asr = new AnnotationSettingsRegistry(DocumentFormatUtils::predefinedSettings()); appContext->setAnnotationSettingsRegistry(asr); TestFramework* tf = new TestFramework(); appContext->setTestFramework(tf); RepeatFinderTaskFactoryRegistry* rfr = new RepeatFinderTaskFactoryRegistry(); appContext->setRepeatFinderTaskFactoryRegistry(rfr); QDActorPrototypeRegistry* qpr = new QDActorPrototypeRegistry(); appContext->setQDActorFactoryRegistry(qpr); CMDLineUtils::init(); DumpLicenseTask::initHelp(); DumpVersionTask::initHelp(); PhyTreeGeneratorRegistry* phyreg = new PhyTreeGeneratorRegistry(); appContext->setPhyTreeGeneratorRegistry(phyreg); // unlike ugene's main.cpp we don't create MainWindowImpl, AppSettingsGUI and GObjectViewFactoryRegistry ExternalToolRegistry* etr = new ExternalToolRegistry(); appContext->setExternalToolRegistry(etr); U2DbiRegistry *dbiRegistry = new U2DbiRegistry(); appContext->setDbiRegistry(dbiRegistry); PluginSupportImpl* psp = new PluginSupportImpl(); appContext->setPluginSupport(psp); ServiceRegistryImpl* sreg = new ServiceRegistryImpl() ; appContext->setServiceRegistry(sreg); DocumentFormatRegistryImpl* dfr = new DocumentFormatRegistryImpl(); appContext->setDocumentFormatRegistry(dfr); DocumentFormatConfigurators* dfc = new DocumentFormatConfigurators(); appContext->setDocumentFormatConfigurators(dfc); BaseDocumentFormatConfigurators::initBuiltInConfigurators(); IOAdapterRegistryImpl* io = new IOAdapterRegistryImpl(); appContext->setIOAdapterRegistry(io); DNATranslationRegistry* dtr = new DNATranslationRegistry(); appContext->setDNATranslationRegistry(dtr); DNAAlphabetRegistry* dal = new DNAAlphabetRegistryImpl(dtr); appContext->setDNAAlphabetRegistry(dal); // unlike ugene's main.cpp we don't create ScriptManagerView, MSAColorSchemeRegistry DBXRefRegistry *dbxrr = new DBXRefRegistry(); appContext->setDBXRefRegistry(dbxrr); MSAConsensusAlgorithmRegistry* msaConsReg = new MSAConsensusAlgorithmRegistry(); appContext->setMSAConsensusAlgorithmRegistry(msaConsReg); MSADistanceAlgorithmRegistry* msaDistReg = new MSADistanceAlgorithmRegistry(); appContext->setMSADistanceAlgorithmRegistry(msaDistReg); PWMConversionAlgorithmRegistry* pwmConvReg = new PWMConversionAlgorithmRegistry(); appContext->setPWMConversionAlgorithmRegistry(pwmConvReg); SubstMatrixRegistry* smr = new SubstMatrixRegistry(); appContext->setSubstMatrixRegistry(smr); SmithWatermanTaskFactoryRegistry* swar = new SmithWatermanTaskFactoryRegistry(); appContext->setSmithWatermanTaskFactoryRegistry(swar); MolecularSurfaceFactoryRegistry* msfr = new MolecularSurfaceFactoryRegistry(); appContext->setMolecularSurfaceFactoryRegistry(msfr); SWResultFilterRegistry* swrfr = new SWResultFilterRegistry(); appContext->setSWResultFilterRegistry(swrfr); SecStructPredictAlgRegistry* sspar = new SecStructPredictAlgRegistry(); appContext->setSecStructPedictAlgRegistry(sspar); CudaGpuRegistry * cgr = new CudaGpuRegistry(); appContext->setCudaGpuRegistry( cgr ); OpenCLGpuRegistry * oclgr = new OpenCLGpuRegistry(); appContext->setOpenCLGpuRegistry( oclgr ); RecentlyDownloadedCache* rdc = new RecentlyDownloadedCache(); appContext->setRecentlyDownloadedCache(rdc); DistributedComputingUtil * distrUtil = new DistributedComputingUtil(); VirtualFileSystemRegistry * vfsReg = new VirtualFileSystemRegistry(); appContext->setVirtualFileSystemRegistry( vfsReg ); Workflow::WorkflowEnv::init(new Workflow::WorkflowEnvImpl()); Workflow::WorkflowEnv::getDomainRegistry()->registerEntry(new LocalWorkflow::LocalDomainFactory()); DnaAssemblyAlgRegistry* assemblyReg = new DnaAssemblyAlgRegistry(); appContext->setDnaAssemblyAlgRegistry(assemblyReg); MSAAlignAlgRegistry* alignReg = new MSAAlignAlgRegistry(); appContext->setMSAAlignAlgRegistry(alignReg); DataBaseRegistry* dbr = new DataBaseRegistry(); appContext->setDataBaseRegistry(dbr); CDSearchFactoryRegistry* cdsfr = new CDSearchFactoryRegistry(); appContext->setCDSearchFactoryRegistry(cdsfr); StructuralAlignmentAlgorithmRegistry *saar = new StructuralAlignmentAlgorithmRegistry(); appContext->setStructuralAlignmentAlgorithmRegistry(saar); TaskStatusBarCon* tsbc=new TaskStatusBarCon(); // show help if need bool showHelp = cmdLineRegistry->hasParameter(CMDLineCoreOptions::HELP) || cmdLineRegistry->hasParameter(CMDLineCoreOptions::USAGE) || cmdLineRegistry->hasParameter(CMDLineCoreOptions::HELP_SHORT); if( showHelp ) { QObject::connect( psp, SIGNAL( si_allStartUpPluginsLoaded()), new TaskStarter(new DumpHelpTask()), SLOT(registerTask())); } bool showLicense = cmdLineRegistry->hasParameter(DumpLicenseTask::LICENSE_CMDLINE_OPTION); if( showLicense ) { QObject::connect(psp, SIGNAL(si_allStartUpPluginsLoaded()), new TaskStarter(new DumpLicenseTask()), SLOT(registerTask())); } bool showVersion = cmdLineRegistry->hasParameter(DumpVersionTask::VERSION_CMDLINE_OPTION); showVersion = showVersion || cmdLineRegistry->hasParameter(DumpVersionTask::VERSION_CMDLINE_OPTION_SHORT); if(showVersion) { QObject::connect(psp, SIGNAL(si_allStartUpPluginsLoaded()), new TaskStarter(new DumpVersionTask()), SLOT(registerTask())); } openDocs(); registerCoreServices(); GCOUNTER(cvar, tvar, "ugenecl launch"); //3 run QT t1.stop(); coreLog.info(AppContextImpl::tr("UGENE started")); ShutdownTask watchQuit(&app); int rc = app.exec(); //4 deallocate resources Workflow::WorkflowEnv::shutdown(); delete tsbc; delete distrUtil; appContext->setVirtualFileSystemRegistry( NULL ); delete vfsReg; appContext->setRecentlyDownloadedCache(NULL); delete rdc; delete swrfr; appContext->setSWResultFilterRegistry(NULL); delete swar; appContext->setSmithWatermanTaskFactoryRegistry(NULL); delete msfr; appContext->setMolecularSurfaceFactoryRegistry(NULL); delete smr; appContext->setSubstMatrixRegistry(NULL); delete sreg; appContext->setServiceRegistry(NULL); delete psp; appContext->setPluginSupport(NULL); delete tf; appContext->setTestFramework(0); delete dal; appContext->setDNAAlphabetRegistry(NULL); delete dbxrr; appContext->setDBXRefRegistry(0); delete dtr; appContext->setDNATranslationRegistry(NULL); delete io; appContext->setIOAdapterRegistry(NULL); delete dfc; appContext->setDocumentFormatConfigurators(NULL); delete dfr; appContext->setDocumentFormatRegistry(NULL); delete ts; appContext->setTaskScheduler(NULL); delete asr; appContext->setAnnotationSettingsRegistry(NULL); delete resTrack; appContext->setResourceTracker(NULL); delete cgr; appContext->setCudaGpuRegistry(NULL); delete oclgr; appContext->setOpenCLGpuRegistry(NULL); delete appSettings; appContext->setAppSettings(NULL); delete settings; appContext->setSettings(NULL); delete globalSettings; appContext->setGlobalSettings(NULL); delete cmdLineRegistry; appContext->setCMDLineRegistry(NULL); delete sspar; appContext->setSecStructPedictAlgRegistry(NULL); appContext->setExternalToolRegistry(NULL); delete etr; delete msaConsReg; appContext->setMSAConsensusAlgorithmRegistry(NULL); delete msaDistReg; appContext->setMSADistanceAlgorithmRegistry(NULL); appContext->setPWMConversionAlgorithmRegistry(NULL); delete pwmConvReg; delete dbr; appContext->setDataBaseRegistry(NULL); appContext->setQDActorFactoryRegistry(NULL); delete qpr; delete cdsfr; appContext->setCDSearchFactoryRegistry(NULL); appContext->setStructuralAlignmentAlgorithmRegistry(NULL); delete saar; return rc; } ugene-1.9.8/src/ugenecl/src/LogDriver.h0000644000175000017500000000417011651544337016373 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_LOG_DRIVER_H_ #define _U2_LOG_DRIVER_H_ #include #include namespace U2 { class LogDriver : public QObject, public LogSettingsHolder { Q_OBJECT public: static const QString LOG_SHOW_DATE_CMD_OPTION; static const QString LOG_SHOW_LEVEL_CMD_OPTION; static const QString LOG_SHOW_CATEGORY_CMD_OPTION; static const QString LOG_LEVEL_NONE_CMD_OPTION; static const QString LOG_LEVEL_ERROR_CMD_OPTION; static const QString LOG_LEVEL_INFO_CMD_OPTION; static const QString LOG_LEVEL_DETAILS_CMD_OPTION; static const QString LOG_LEVEL_TRACE_CMD_OPTION; static const QString LOG_SETTINGS_ACTIVE_FLAG; static const QString COLOR_OUTPUT_CMD_OPTION; //static const QString LOG_FORMAT; //static const QString LOG_LEVEL; static void setLogCmdlineHelp(); void setLogSettings(); private: static bool helpRegistered; public: LogDriver(); virtual ~LogDriver() {} private: void setCmdLineSettings(); QString getEffectiveCategory(const LogMessage& msg) const; QString getLevelName(int i) const; private slots: void sl_onMessage(const LogMessage& msg); QString prepareText(const LogMessage& msg) const; private: bool printToConsole; bool colored; }; } //namespace #endif ugene-1.9.8/src/ugenecl/src/DumpLicenseTask.h0000644000175000017500000000240411651544337017527 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_UGENECL_DUMP_LICENCE_TASK_H_ #define _U2_UGENECL_DUMP_LICENCE_TASK_H_ #include namespace U2 { class DumpLicenseTask : public Task { Q_OBJECT public: static const QString LICENSE_CMDLINE_OPTION; static const QString LICENCE_FILENAME; static void initHelp(); public: DumpLicenseTask(); virtual void run(); }; // DumpLicenseTask } #endif // _U2_UGENECL_DUMP_LICENCE_TASK_H_ ugene-1.9.8/src/ugenecl/src/DumpHelpTask.cpp0000644000175000017500000002177311651544337017402 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "DumpHelpTask.h" #include #ifdef Q_OS_WIN32 #include "windows.h" #endif #include #include #include #include #include #include #include #include #include #include void printStringToConsole(const char* format, const QString& str){ QByteArray ba = str.toLocal8Bit(); char* buf = ba.data(); #ifdef Q_OS_WIN32 // a bit of magic to workaround Windows console encoding issues CharToOemA(buf,buf); #endif printf(format, buf); } namespace U2 { const QString DumpHelpTask::VERSION_INFO = QString("\nConsole version of UGENE %1\n").arg(Version::ugeneVersion().text); static void dumpProgramNameAndUsage() { printStringToConsole( "%s" , DumpHelpTask::VERSION_INFO); printStringToConsole("%s", "Usage: ugene [[--task=]task_name] [--task_parameter=value] [-task_parameter value] " "[--option[=value]] [-option [value]]\n\n"); } static void dumpSectionName( const QString & name ) { printStringToConsole( " --%-20s", name); } static void dumpSectionContent( const QString & content ) { printStringToConsole( "\t%s", content); } static void dumpSectionIndent() { printStringToConsole( "%28s", " " ); } static void dumpTaskName(const QString & taskName) { printStringToConsole( " %-20s\n", taskName); } static void dumpOptionHelpSyntax(const QString & option, const QString & argsDescription) { QString optionHelp; if (argsDescription.isEmpty()) { optionHelp = "ugene --" + option; } else { optionHelp = "ugene --" + option + "=" + argsDescription; } printStringToConsole( "%s\n", optionHelp); } static void dumpOptionHelpDescription(const QString & description) { printStringToConsole( "%s\n", description); } void DumpHelpTask::dumpHelp() { dumpProgramNameAndUsage(); printStringToConsole("%s", "\nOptions: \n" ); QString prevSectionName; QList helpProviders = AppContext::getCMDLineRegistry()->listCMDLineHelpProviders(); foreach (CMDLineHelpProvider* hProvider, helpProviders) { assert(hProvider != NULL); const QString& sectionName = hProvider->getHelpSectionNames(); if(sectionName != prevSectionName) { dumpSectionName( sectionName ); prevSectionName = sectionName; } else { dumpSectionIndent(); } dumpSectionContent( hProvider->getHelpSectionShortDescription() ); printStringToConsole("%s", "\n"); } printStringToConsole("%s", "\n" ); printStringToConsole("%s", "\nAvailable tasks:\n"); QStringList dataDirs = QDir::searchPaths(PATH_PREFIX_DATA); foreach(const QString & url, dataDirs ) { QString dirUrl = url + "/cmdline/"; QDir dir(dirUrl); if(dir.exists()) { QStringList entries = dir.entryList(QDir::Files | QDir::Readable); foreach( const QString & file, entries ) { foreach(const QString & ext, WorkflowUtils::WD_FILE_EXTENSIONS) { if( file.endsWith(ext) ) { dumpTaskName(file.mid(0, file.size() - ext.size() - 1)); // 1 comes from "." break; } } } } } printStringToConsole("%s", "Use ugene --help= to get full help\n"); } void DumpHelpTask::prepare() { CMDLineRegistry * cmdlineRegistry = AppContext::getCMDLineRegistry(); assert(cmdlineRegistry != NULL); if (cmdlineRegistry->hasParameter(CMDLineCoreOptions::USAGE)) { dumpProgramNameAndUsage(); return; } QString paramName = cmdlineRegistry->getParameterValue( CMDLineCoreOptions::HELP ); paramName = paramName.isEmpty() ? cmdlineRegistry->getParameterValue(CMDLineCoreOptions::HELP_SHORT) : paramName; if( paramName.isEmpty() ) { dumpHelp(); return; } QList helpProviders = AppContext::getCMDLineRegistry()->listCMDLineHelpProviders(); int ind = 0; int sz = helpProviders.size(); for( ind = 0; ind < sz; ++ind ) { CMDLineHelpProvider * cur = helpProviders.at(ind); if( cur->getHelpSectionFullName() == paramName || cur->getHelpSectionShortName() == paramName) { break; } } if(ind == sz) { // try to find help of workflow designer schema with such name QString pathToSchema = WorkflowUtils::findPathToSchemaFile(paramName); if( pathToSchema.isEmpty() ) { coreLog.error(tr("Can't find help for '%1'").arg(paramName)); return; } // will be deleted in sl_loadSchemaStateChanged Schema * schema = new Schema(); Metadata * meta = new Metadata(); schema->setDeepCopyFlag(true); addSubTask(new LoadWorkflowTask( schema, meta, pathToSchema )); return; } // Dumping help of the selected section in the registered help pages // printStringToConsole("%s", "\n" ); assert(0 != helpProviders.at(ind)->getHelpSectionFullName()); dumpOptionHelpSyntax(helpProviders.at(ind)->getHelpSectionFullName(), helpProviders.at(ind)->getHelpSectionArgsDescription()); printStringToConsole("%s", "\n" ); QString description; if (!helpProviders.at(ind)->getHelpSectionFullDescription().isEmpty()) { description = helpProviders.at(ind)->getHelpSectionFullDescription(); } else { assert(!helpProviders.at(ind)->getHelpSectionShortDescription().isEmpty()); description = helpProviders.at(ind)->getHelpSectionShortDescription(); // If the section has several short descriptions, append the next short descriptions for (int i = ind + 1; i < sz; ++i) { CMDLineHelpProvider * provider = helpProviders.at(i); if( provider->getHelpSectionFullName() != paramName && provider->getHelpSectionShortName() != paramName) { break; } description += "\n"; description += helpProviders.at(i)->getHelpSectionShortDescription(); } } dumpOptionHelpDescription(description); } static void dumpSchemaMetadata(Metadata * meta) { assert(meta != NULL); printStringToConsole( "\n%s\n", meta->comment); } static void dumpSchemaCmdlineParameters( Schema * schema ) { assert(schema != NULL); printStringToConsole("%s", "Parameters:\n"); foreach( Actor * actor, schema->getProcesses() ) { assert(actor != NULL); QMap::const_iterator it = actor->getParamAliases().constBegin(); while( it != actor->getParamAliases().constEnd() ) { QString alias = it.value(); dumpSectionName(alias); Attribute * attr = actor->getParameter(it.key()); assert(attr != NULL); if(actor->getAliasHelp().contains(alias)) { dumpSectionContent( QString("%1 [%2]").arg(actor->getAliasHelp().value(alias)).arg(attr->getAttributeType()->getDisplayName())); } else { dumpSectionContent(DumpHelpTask::tr("No help available for this parameter")); } printStringToConsole("%s", "\n" ); ++it; } } printStringToConsole("%s", "\n" ); } QList DumpHelpTask::onSubTaskFinished(Task* subTask) { LoadWorkflowTask * loadTask = qobject_cast(subTask); assert(loadTask != NULL); Schema * schema = loadTask->getSchema(); Metadata * meta = loadTask->getMetadata(); dumpSchemaMetadata(meta); dumpSchemaCmdlineParameters(schema); delete schema; delete meta; return QList(); } void DumpHelpTask::dumpParameters() { QList params = AppContext::getCMDLineRegistry()->getParameters(); QList::const_iterator it = params.constBegin(); while( it != params.constEnd() ) { printStringToConsole( "key: \"%s\"", it->first); printStringToConsole( " and value: \"%s\"\n", it->second); ++it; } } DumpHelpTask::DumpHelpTask(): Task(tr("Dump help task"), TaskFlags_NR_FOSCOE) { } } //namespace ugene-1.9.8/src/ugenecl/src/ShutdownTask.cpp0000644000175000017500000001071011651544337017464 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "ShutdownTask.h" #include #include #include #include #include namespace U2 { ShutdownTask::ShutdownTask(QCoreApplication* app) : Task(tr("Shutdown"), TaskFlags_NR_FOSCOE | TaskFlag_NoAutoDelete), app(app) { connect(AppContext::getTaskScheduler(), SIGNAL(si_topLevelTaskUnregistered(Task*)), SLOT(startShutdown())); connect(app, SIGNAL(aboutToQuit()), SLOT(startShutdown())); } void ShutdownTask::startShutdown() { if (sender() == app) { coreLog.info("Shutdown initiated by user"); } else { if (AppContext::getTaskScheduler()->getTopLevelTasks().size() != 0) { return; } coreLog.info("All tasks finished, shutting down"); } app->disconnect(this, SLOT(startShutdown())); AppContext::getTaskScheduler()->disconnect(this, SLOT(startShutdown())); AppContext::getTaskScheduler()->registerTopLevelTask(this); } static bool isReadyToBeDisabled(Service* s, ServiceRegistry* sr) { ServiceType st = s->getType(); int nServicesOfTheSameType = sr->findServices(st).size(); assert(nServicesOfTheSameType >= 1); foreach(Service* child, sr->getServices()) { if (!child->getParentServiceTypes().contains(st) || !child->isEnabled()) { continue; } if (nServicesOfTheSameType == 1) { return false; } } return true; } static Service* findServiceToDisable(ServiceRegistry* sr) { int nEnabled = 0; foreach(Service* s, sr->getServices()) { nEnabled+= s->isEnabled() ? 1 : 0; if (s->isEnabled() && isReadyToBeDisabled(s, sr)) { return s; } } assert(nEnabled == 0); return NULL; } class CancelAllTask : public Task { public: CancelAllTask() : Task(U2::ShutdownTask::tr("Cancel active tasks"), TaskFlag_NoRun) {} void prepare() { // cancel all tasks but ShutdownTask QList activeTopTasks = AppContext::getTaskScheduler()->getTopLevelTasks(); activeTopTasks.removeOne(getTopLevelParentTask()); foreach(Task* t, activeTopTasks) { coreLog.trace(QString("Canceling: %1").arg(t->getTaskName())); t->cancel(); } } ReportResult report() { foreach(Task* t, AppContext::getTaskScheduler()->getTopLevelTasks()) { if (t->isCanceled() && !t->isFinished()) { return ReportResult_CallMeAgain; } } return ReportResult_Finished; } }; void ShutdownTask::prepare() { coreLog.info(tr("Starting shutdown process...")); addSubTask(new CancelAllTask()); } QList ShutdownTask::onSubTaskFinished(Task* subTask) { QList res; if (isCanceled() || subTask->hasError()) { return res; //stop shutdown process } ServiceRegistry* sr = AppContext::getServiceRegistry(); Service* s = findServiceToDisable(sr); if (s!=NULL) { res.append(sr->disableServiceTask(s)); } return res; } Task::ReportResult ShutdownTask::report() { if (stateInfo.cancelFlag) { coreLog.info(tr("Shutdown was canceled")); return Task::ReportResult_Finished; } if (propagateSubtaskError()) { coreLog.error(tr("Shutdown failed, error: %1").arg(stateInfo.getError())); return Task::ReportResult_Finished; } #ifdef _DEBUG const QList& services = AppContext::getServiceRegistry()->getServices(); foreach(Service* s, services) { assert(s->isDisabled()); } #endif app->quit(); return Task::ReportResult_Finished; } }//namespace ugene-1.9.8/src/ugenecl/src/DumpVersionTask.h0000644000175000017500000000240511651544337017573 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_DUMP_VERSION_TASK_H__ #define _U2_DUMP_VERSION_TASK_H__ #include namespace U2 { class DumpVersionTask : public Task { Q_OBJECT public: static const QString VERSION_CMDLINE_OPTION; static const QString VERSION_CMDLINE_OPTION_SHORT; static void initHelp(); public: DumpVersionTask(); virtual void run(); }; // DumpVersionTask } // U2 #endif // _U2_DUMP_VERSION_TASK_H__ ugene-1.9.8/src/ugenecl/src/TestStarter.cpp0000644000175000017500000002010511651544337017311 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "TestStarter.h" #include #include #include #include #include #include #define SETTINGS_ROOT QString("test_runner/") namespace U2 { TestStarter::TestStarter( const QStringList& urls ) : Task(tr("Test loader"), TaskFlags_NR_FOSCOE), urls(urls) { env = new GTestEnvironment(); readBuiltInVars(); } TestStarter::~TestStarter() { cleanup(); assert(suites.isEmpty()); } void TestStarter::prepare() { if (urls.isEmpty()) { readSavedSuites(); } else { foreach (const QString& url, urls) { if (url.endsWith(".list")) { QStringList errs; QList tsl=GTestSuite::readTestSuiteList(url, errs); if (!errs.isEmpty()) { ioLog.error("Error reading test suites: \n" + errs.join("\n")); } else { foreach(GTestSuite* ts, tsl) { addTestSuite(ts); } } } else { QString err; GTestSuite* ts=GTestSuite::readTestSuite(url, err); if (!err.isEmpty()) { ioLog.error("Error reading test suites: \n" + err); }else{ addTestSuite(ts); } } } } ttask = createRunTask(); addSubTask(ttask = createRunTask()); } void TestStarter::cleanup() { //saveSuites(); //saveEnv(); deallocateSuites(); delete env; env = NULL; //Task::cleanup(); } void TestStarter::addTestSuite(GTestSuite *ts) { //TO DO: check bug when test suites duplicated assert(!findTestSuiteByURL(ts->getURL())); assert(!suites.contains(ts)); suites.append(ts); GTestEnvironment * tsEnv = ts->getEnv(); const QStringList & tsEnvKeys = tsEnv->getVars().keys(); QStringList tsEnvResultedKeys; //skipping non-empty variables foreach( const QString & key, tsEnvKeys ) { if( tsEnv->getVar(key).isEmpty() ) { tsEnvResultedKeys.push_back( key ); } } readEnvForKeys(tsEnvResultedKeys); updateDefaultEnvValues(ts); emit si_testSuiteAdded(ts); } void TestStarter::updateDefaultEnvValues(GTestSuite* ts) { QMap vars = env->getVars(); if (vars.contains("COMMON_DATA_DIR") && vars.value("COMMON_DATA_DIR").isEmpty()) { env->setVar("COMMON_DATA_DIR", QFileInfo(ts->getURL()).absoluteDir().absolutePath() + "/_common_data"); } if (vars.contains("TEMP_DATA_DIR") && vars.value("TEMP_DATA_DIR").isEmpty()) { env->setVar("TEMP_DATA_DIR", QFileInfo(ts->getURL()).absoluteDir().absolutePath()+"/_tmp"); } } void TestStarter::removeTestSuite(GTestSuite* ts) { assert(suites.contains(ts)); suites.removeOne(ts); //todo: cleanup vars, but leave built-in saveEnv(); emit si_testSuiteRemoved(ts); } GTestSuite* TestStarter::findTestSuiteByURL(const QString& url) { foreach(GTestSuite* t, suites) { if (t->getURL() == url) { return t; } } return NULL; } void TestStarter::readBuiltInVars() { QStringList biVars; biVars< vars = env->getVars(); if (!vars.contains(NUM_THREADS_VAR) || vars.value(NUM_THREADS_VAR).isEmpty()) { env->setVar(NUM_THREADS_VAR, "5"); } if (!vars.contains(TIME_OUT_VAR) || vars.value(TIME_OUT_VAR).isEmpty()) { env->setVar(TIME_OUT_VAR, "0"); } } void TestStarter::readSavedSuites() { //TODO: do it in in service startup task!!! QStringList suiteUrls = AppContext::getSettings()->getValue(SETTINGS_ROOT + "suites", QStringList()).toStringList(); QString err; QMap env; QString url; foreach(const QString& url, suiteUrls) { GTestSuite* ts = GTestSuite::readTestSuite(url, err); if (ts == NULL) { ioLog.error(tr("error_reading_ts_%1_error_%2").arg(url).arg(err)); } else { addTestSuite(ts); } } } void TestStarter::saveSuites() { QStringList list; foreach(GTestSuite* s, suites) { list.append(s->getURL()); } AppContext::getSettings()->setValue(SETTINGS_ROOT + "suites", list); } void TestStarter::deallocateSuites() { foreach(GTestSuite* s, suites) { emit si_testSuiteRemoved(s); delete s; } suites.clear(); } void TestStarter::readEnvForKeys(QStringList keys) { foreach(const QString& k, keys) { QString val = env->getVar(k); if (val.isEmpty()) { val = AppContext::getSettings()->getValue(SETTINGS_ROOT + "env/"+ k, QString()).toString(); env->setVar(k, val); } } } void TestStarter::saveEnv() { foreach(const QString& k, env->getVars().keys()) { QString val = env->getVar(k); if (!val.isEmpty()) { AppContext::getSettings()->setValue(SETTINGS_ROOT + "env/"+ k, val); } else { AppContext::getSettings()->remove(SETTINGS_ROOT + "env/"+ k); } } } void TestStarter::sl_refresh() { saveSuites(); deallocateSuites(); readSavedSuites(); } TestRunnerTask* TestStarter::createRunTask() { if (env->containsEmptyVars()) { coreLog.error(tr("Not all environment variables set")); return NULL; } QList testsToRun; foreach(GTestSuite* ts, suites) { foreach(GTestRef* tref, ts->getTests()) { testsToRun << new GTestState(tref); } } if (testsToRun.isEmpty()) { coreLog.error(tr("No tests found")); } bool ok; // QTime* temp=new QTime; // *temp=QTime::currentTime(); // startRunTime = temp; int numberTestsToRun= getEnv()->getVar(NUM_THREADS_VAR).toInt(&ok); if(!ok || numberTestsToRun <= 0 ){numberTestsToRun=5;} TestRunnerTask* ttask = new TestRunnerTask(testsToRun, getEnv(),numberTestsToRun); return ttask; } Task::ReportResult TestStarter::report() { int numPassed=0, numFailed=0; uiLog.info(tr("Testing report:")); uiLog.info(tr("---------------")); if (ttask->isFinished() && !ttask->hasError()) { foreach(GTestState* t, ttask->getStateByTestMap()) { uiLog.info(tr("State: %1 - Test %2:%3 %4").arg(t->isPassed() ? "pass" : "FAIL").arg(t->getTestRef()->getSuite()->getName()).arg(t->getTestRef()->getShortName()).arg(t->isPassed() ? "" : "- Details: "+t->getErrorMessage())); if(t->isPassed()){ numPassed++; }else{ numFailed++; } //printf("%s\n",tr("------------------Test %1 %2").arg(t->getTestRef()->getShortName()).arg(t->isPassed() ? "OK" : t->getErrorMessage()).toLocal8Bit()); } uiLog.info(tr("---------------")); uiLog.info(tr("Summary - Number of tests: %1 | Tests passed: %2 | Tests failed: %3").arg(QString::number(numPassed+numFailed)).arg(QString::number(numPassed)).arg(QString::number(numFailed))); } else { uiLog.error("Test run problem: " + ttask->getError()); //printf("%s\n",QString("--------- Test run problem: " + ttask->getError()).toLocal8Bit()); } return ReportResult_Finished; } }//namespace ugene-1.9.8/src/ugenecl/src/TaskStatusBar.cpp0000644000175000017500000001673211651544337017573 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "TaskStatusBar.h" #ifdef Q_OS_WIN32 #include "windows.h" #endif #include #include #include #include #include #include #include #include #include #define LOG_SETTINGS_ROOT QString("log_settings/") #define sizeProgress 10 namespace U2 { const QString TaskStatusBarCon::NO_TASK_STATUS_BAR_CMD_OPTION = "log-no-task-progress"; bool TaskStatusBarCon::helpRegistered = false; TaskStatusBarCon::TaskStatusBarCon() { taskToTrack = NULL; #ifdef Q_OS_WIN32 //TO DO: May be use following variant, but it don`t work always //COORD conSize=GetLargestConsoleWindowSize(GetStdHandle(STD_OUTPUT_HANDLE)); //printf("X=%d, Y=%d\n",conSize.X,conSize.Y); emptyLine=QString((int)80-1, QChar(' '));//80 spaces #endif if( !helpRegistered ) { setTSBCmdlineHelp(); } setTSBSettings(); Settings * settings = AppContext::getSettings(); if( settings->getValue( TSB_SETTINGS_ROOT + "showTaskStatusBar", false ).toBool() ){ connect(AppContext::getTaskScheduler(), SIGNAL(si_stateChanged(Task*)), SLOT(sl_taskStateChanged(Task*))); updateState(); } } void TaskStatusBarCon::setTSBCmdlineHelp() { assert( !helpRegistered ); helpRegistered = true; CMDLineRegistry * cmdLineRegistry = AppContext::getCMDLineRegistry(); assert( NULL != cmdLineRegistry ); CMDLineHelpProvider * noTSBSection = new CMDLineHelpProvider( NO_TASK_STATUS_BAR_CMD_OPTION, tr( "Specifies not to show the task progress." ), tr( "A task progress is shown by default when a task is running." " This option specifies not to show the progress." )); cmdLineRegistry->registerCMDLineHelpProvider( noTSBSection ); } void TaskStatusBarCon::setTSBSettings() { if (AppContext::getCMDLineRegistry()->hasParameter( NO_TASK_STATUS_BAR_CMD_OPTION )) { AppContext::getSettings()->setValue( TSB_SETTINGS_ROOT + "showTaskStatusBar", false); } else { AppContext::getSettings()->setValue( TSB_SETTINGS_ROOT + "showTaskStatusBar", true); } } TaskStatusBarCon::~TaskStatusBarCon(){ printf(" \r");//80 spaces } void TaskStatusBarCon::updateState() { if (taskToTrack == NULL) { return; } int nTasks = AppContext::getTaskScheduler()->getTopLevelTasks().size();//+1 is hard code int nSubTasks = taskToTrack->getSubtasks().size(); int progress = taskToTrack->getProgress(); if (progress==-1) { progress=0; } char progressLine[sizeProgress+3]; progressLine[0]='['; progressLine[sizeProgress+1]=']'; progressLine[sizeProgress+2]='\0'; for(int i=0;igetTaskName().toLocal8Bit(); char* buf = ba.data(); #ifdef Q_OS_WIN32 // a bit of magic to workaround Windows console encoding issues CharToOemA(buf,buf); #endif static int working; char ch = 0; if (working==0){ ch='\\'; working=1; }else if (working==1){ ch='|'; working=2; }else if (working==2){ ch='/'; working=3; }else if (working==3){ ch='-'; working=0; }else{ working=0; } #ifdef Q_OS_WIN32 //TO DO: Need refactoring this place for linux printf("%s\r", emptyLine.toAscii().constData());//80 spaces //printf(" \r");//80 spaces #endif if(!AppContext::getSettings()->getValue(LOG_SETTINGS_ROOT + "colorOut", false).toBool()){ if (nSubTasks<=1){ printf("%c %s %d%% Tasks: %d, Info: %s \r",ch,progressLine,progress,nTasks+1,buf); }else{ printf("%c %s %d%% Tasks: %d, SubTs: %d, Info: %s \r",ch,progressLine,progress,nTasks+1,nSubTasks,buf); } }else{ #ifdef Q_OS_WIN32 if (nSubTasks<=1){ SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_INTENSITY | FOREGROUND_RED ); printf("%c %s %d%% ",ch,progressLine,progress); SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_INTENSITY | FOREGROUND_GREEN ); printf("Tasks: %d, Info: %s \r",nTasks+1,buf); }else{ SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_INTENSITY | FOREGROUND_RED ); printf("%c %s %d%% ",ch,progressLine,progress); SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_INTENSITY | FOREGROUND_GREEN ); printf("Tasks: %d, SubTs: %d, Info: %s \r",nTasks+1,nSubTasks,buf); } SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE),0x0007 );//0x0007 is white color #else if (nSubTasks<=1){ printf("\e[31m%c %s %d%% \e[32mTasks: %d, Info: %s \e[0m\r",ch,progressLine,progress,nTasks+1,buf); }else{ printf("\e[31m%c %s %d%% \e[32mTasks: %d, SubTs: %d, Info: %s \e[0m\r",ch,progressLine,progress,nTasks+1,nSubTasks,buf); } #endif } } void TaskStatusBarCon::sl_taskStateChanged(Task* t) { assert(taskToTrack == NULL); if (t->isFinished()) { return; } WorkflowRunTask* workflowTask = qobject_cast(t); if (workflowTask == NULL) { // track progress only for workflow tasks return; } setTaskToTrack(t); AppContext::getTaskScheduler()->disconnect(this); } void TaskStatusBarCon::setTaskToTrack(Task* t) { assert(taskToTrack == NULL); taskToTrack = t; connect(taskToTrack, SIGNAL(si_stateChanged()), SLOT(sl_taskStateChanged())); connect(taskToTrack, SIGNAL(si_progressChanged()), SLOT(sl_update())); connect(taskToTrack, SIGNAL(si_descriptionChanged()), SLOT(sl_update())); updateState(); } void TaskStatusBarCon::sl_taskStateChanged() { assert(taskToTrack == sender()); if (!taskToTrack->isFinished()) { updateState(); return; } taskToTrack->disconnect(this); taskToTrack = NULL; foreach(Task* newT, AppContext::getTaskScheduler()->getTopLevelTasks()) { if (!newT->isFinished()) { setTaskToTrack(newT); break; } } if (taskToTrack == NULL) { connect(AppContext::getTaskScheduler(), SIGNAL(si_stateChanged(Task*)), SLOT(sl_taskStateChanged(Task*))); } updateState(); } void TaskStatusBarCon::sl_update() { updateState(); } } //namespace ugene-1.9.8/src/ugenecl/ugenecl.pri0000644000175000017500000000263311651544337015676 0ustar ilyailya# include (ugenecl.pri) include( ../ugene_globals.pri ) UGENE_RELATIVE_DESTDIR = '' QT += xml network script webkit TEMPLATE = app CONFIG +=qt dll thread debug_and_release console DEFINES+= QT_DLL QT_FATAL_ASSERT INCLUDEPATH += src _tmp ../include ../corelibs/U2Private/src LIBS += -L../_release -lU2Core -lU2Algorithm -lU2Formats -lU2Gui -lU2Test -lU2Remote -lU2Misc -lU2Lang -lU2Private -lugenedb !debug_and_release|build_pass { CONFIG(debug, debug|release) { TARGET = ugenecld DEFINES+=_DEBUG DESTDIR=../_debug MOC_DIR=_tmp/moc/debug OBJECTS_DIR=_tmp/obj/debug LIBS -= -L../_release -lU2Core -lU2Algorithm -lU2Formats -lU2Gui -lU2Test -lU2Remote -lU2Misc -lU2Lang -lU2Private -lugenedb LIBS += -L../_debug -lU2Cored -lU2Algorithmd -lU2Formatsd -lU2Guid -lU2Testd -lU2Remoted -lU2Miscd -lU2Langd -lU2Privated -lugenedbd } CONFIG(release, debug|release) { TARGET = ugenecl DESTDIR=../_release DEFINES+=NDEBUG MOC_DIR=_tmp/moc/release OBJECTS_DIR=_tmp/obj/release } } UI_DIR=_tmp/ui RCC_DIR=_tmp/rcc win32 { LIBS += -luser32 # to import CharToOemA with nmake build QMAKE_CXXFLAGS_WARN_ON = -W3 QMAKE_CFLAGS_WARN_ON = -W3 RC_FILE = ugenecl.rc } macx { RC_FILE = images/ugenecl_mac.icns } unix { target.path = $$UGENE_INSTALL_DIR/$$UGENE_RELATIVE_DESTDIR INSTALLS += target } ugene-1.9.8/src/ugenecl/ugenecl.pro0000644000175000017500000000111111651544337015672 0ustar ilyailyainclude (ugenecl.pri) # Input HEADERS += src/DumpHelpTask.h \ src/DumpLicenseTask.h \ src/DumpVersionTask.h \ src/ForeverTask.h \ src/LogDriver.h \ src/ShutdownTask.h \ src/TaskStatusBar.h \ src/TestStarter.h SOURCES += src/DumpHelpTask.cpp \ src/DumpLicenseTask.cpp \ src/DumpVersionTask.cpp \ src/ForeverTask.cpp \ src/LogDriver.cpp \ src/Main.cpp \ src/ShutdownTask.cpp \ src/TaskStatusBar.cpp \ src/TestStarter.cpp ugene-1.9.8/src/ugene_globals.pri0000644000175000017500000001027711651544342015437 0ustar ilyailyainclude (ugene_version.pri) UGENE_GLOBALS_DEFINED=1 DEFINES+=UGENE_VERSION=$${UGENE_VERSION} DEFINES+=UGENE_VER_MAJOR=$${UGENE_VER_MAJOR} DEFINES+=UGENE_VER_MINOR=$${UGENE_VER_MINOR} DEFINES+=UGENE_VER_BUILD=$${UGENE_VER_BUILD} DEFINES+=UGENE_VER_REVISION=$${UGENE_VER_REVISION} win32 : CONFIG -= flat #group the files within the source/header group depending on the directory they reside in file system win32 : QMAKE_CXXFLAGS += /MP # use parallel build with nmake win32 : DEFINES+= _WINDOWS win32 : QMAKE_CFLAGS_RELEASE = -O2 -Oy- -MD win32 : QMAKE_CXXFLAGS_RELEASE = -O2 -Oy- -MD win32 : QMAKE_LFLAGS_RELEASE = /INCREMENTAL:NO /MAP /MAPINFO:EXPORT isEmpty( INSTALL_PREFIX ) : INSTALL_PREFIX = /usr isEmpty( INSTALL_BINDIR ) : INSTALL_BINDIR = $$INSTALL_PREFIX/bin isEmpty( INSTALL_LIBDIR ) { INSTALL_LIBDIR = $$INSTALL_PREFIX/lib #installing to lib64 on 64-bit platforms: contains (QMAKE_HOST.arch, x86_64) : INSTALL_LIBDIR = $$INSTALL_PREFIX/lib64 } isEmpty( INSTALL_MANDIR ) : INSTALL_MANDIR = $$INSTALL_PREFIX/share/man isEmpty( INSTALL_DATADIR ) : INSTALL_DATADIR = $$INSTALL_PREFIX/share isEmpty( UGENE_INSTALL_DESKTOP ) : UGENE_INSTALL_DESKTOP = $$INSTALL_DATADIR/applications isEmpty( UGENE_INSTALL_PIXMAPS ) : UGENE_INSTALL_PIXMAPS = $$INSTALL_DATADIR/pixmaps isEmpty( UGENE_INSTALL_DATA ) : UGENE_INSTALL_DATA = $$INSTALL_DATADIR/ugene/data isEmpty( UGENE_INSTALL_DIR ) : UGENE_INSTALL_DIR = $$INSTALL_LIBDIR/ugene isEmpty( UGENE_INSTALL_BINDIR ) : UGENE_INSTALL_BINDIR = $$INSTALL_BINDIR isEmpty( UGENE_INSTALL_MAN ) : UGENE_INSTALL_MAN = $$INSTALL_MANDIR/man1 CONFIG(x64) { DEFINES += UGENE_X86_64 } else:CONFIG(ppc) { DEFINES += UGENE_PPC } else { DEFINES += UGENE_X86 } macx : DEFINES += RUN_WORKFLOW_IN_THREADS # uncomment when building on Cell BE # UGENE_CELL = 1 # Checking if processor is SSE2 capable. # On Windows UGENE relies on run-time check. # # Needed for: # 1) adding -msse2 compilation flag if needed (currently uhmmer and smith_waterman2) # 2) performing run-time check using cpuid instruction on intel proccessors. isEmpty( UGENE_SSE2_DETECTED ) { UGENE_SSE2_DETECTED = 0 !win32 : exists( /proc/cpuinfo ) { system( grep sse2 /proc/cpuinfo > /dev/null ) { UGENE_SSE2_DETECTED = 1 } } macx { !ppc{ system(/usr/sbin/system_profiler SPHardwareDataType | grep Processor | grep Intel > /dev/null) { UGENE_SSE2_DETECTED = 1 } } } } defineTest( use_sse2 ) { win32 : return (true) contains( UGENE_SSE2_DETECTED, 1 ) : return (true) return (false) } # CUDA environment UGENE_NVCC = nvcc UGENE_CUDA_LIB_DIR = $$(CUDA_LIB_PATH) UGENE_CUDA_INC_DIR = $$(CUDA_INC_PATH) # CUDA detection tools isEmpty(UGENE_CUDA_DETECTED) : UGENE_CUDA_DETECTED = 0 defineTest( use_cuda ) { contains( UGENE_CUDA_DETECTED, 1) : return (true) return (false) } # OPENCL detection tools isEmpty(UGENE_OPENCL_DETECTED) : UGENE_OPENCL_DETECTED = 1 defineTest( use_opencl ) { contains( UGENE_OPENCL_DETECTED, 1) : return (true) return (false) } # Crash handler isEmpty(USE_CRASH_HANDLER) : USE_CRASH_HANDLER = 1 defineTest( use_crash_handler) { macx: return (false) contains(USE_CRASH_HANDLER, 1): return (true) return (false) } release : use_crash_handler() { DEFINES+=USE_CRASHHANDLER } # establishing binary-independet data directory for *nix installation unix { DEFINES *= UGENE_DATA_DIR=\\\"$$UGENE_INSTALL_DATA\\\" } # new conditional function for case 'unix but not macx' defineTest( unix_not_mac ) { unix : !macx { return (true) } return (false) } #By default, UGENE uses bundled zlib (libs_3rdparty/zlib) on windows and mac os. #On any OS it can be forced using the following variable # UGENE_USE_BUNDLED_ZLIB = 1 defineTest( use_bundled_zlib ) { contains( UGENE_USE_BUNDLED_ZLIB, 1 ) : return (true) contains( UGENE_USE_BUNDLED_ZLIB, 0 ) : return (false) unix_not_mac() : return (false) return (true) } #Variable enabling exclude list for ugene modules UGENE_EXCLUDE_LIST_ENABLED = 1 defineTest( exclude_list_enabled ) { contains( UGENE_EXCLUDE_LIST_ENABLED, 1 ) : return (true) return (false) } ugene-1.9.8/src/include/0000755000175000017500000000000011651544336013534 5ustar ilyailyaugene-1.9.8/src/include/U2Test/0000755000175000017500000000000011651544336014662 5ustar ilyailyaugene-1.9.8/src/include/U2Test/GUITestBase.h0000644000175000017500000000007411651544336017113 0ustar ilyailya#include "../../corelibs/U2Test/src/gui_tests/GUITestBase.h"ugene-1.9.8/src/include/U2Test/XMLTestFormat.h0000644000175000017500000000007611651544336017507 0ustar ilyailya#include "../../corelibs/U2Test/src/xmltest/XMLTestFormat.h" ugene-1.9.8/src/include/U2Test/TestRunnerSettings.h0000644000175000017500000000007111651544336020663 0ustar ilyailya#include "../../corelibs/U2Test/src/TestRunnerSettings.h"ugene-1.9.8/src/include/U2Test/TestRunnerTask.h0000644000175000017500000000006711651544336017772 0ustar ilyailya#include "../../corelibs/U2Test/src/TestRunnerTask.h" ugene-1.9.8/src/include/U2Test/GTestFrameworkComponents.h0000644000175000017500000000010111651544336021775 0ustar ilyailya#include "../../corelibs/U2Test/src/GTestFrameworkComponents.h" ugene-1.9.8/src/include/U2Test/GTest.h0000644000175000017500000000005611651544336016062 0ustar ilyailya#include "../../corelibs/U2Test/src/GTest.h" ugene-1.9.8/src/include/U2Test/GUITestService.h0000644000175000017500000000007711651544336017644 0ustar ilyailya#include "../../corelibs/U2Test/src/gui_tests/GUITestService.h"ugene-1.9.8/src/include/U2Test/XMLTestUtils.h0000644000175000017500000000007511651544336017356 0ustar ilyailya#include "../../corelibs/U2Test/src/xmltest/XMLTestUtils.h" ugene-1.9.8/src/include/U2View/0000755000175000017500000000000011651544336014655 5ustar ilyailyaugene-1.9.8/src/include/U2View/CreateCircularBranchesTask.h0000644000175000017500000000012311651544336022203 0ustar ilyailya#include "../../corelibs/U2View/src/util_ov_phyltree/CreateCircularBranchesTask.h" ugene-1.9.8/src/include/U2View/PanViewRows.h0000644000175000017500000000011111651544336017243 0ustar ilyailya#include "../../corelibs/U2View/src/util_ov_annotated_dna/PanViewRows.h" ugene-1.9.8/src/include/U2View/TreeViewerTasks.h0000644000175000017500000000011011651544336020105 0ustar ilyailya#include "../../corelibs/U2View/src/util_ov_phyltree/TreeViewerTasks.h" ugene-1.9.8/src/include/U2View/CreateBranchesTask.h0000644000175000017500000000011311651544336020515 0ustar ilyailya#include "../../corelibs/U2View/src/util_ov_phyltree/CreateBranchesTask.h" ugene-1.9.8/src/include/U2View/WindowStepSelectorWidget.h0000644000175000017500000000012611651544336021775 0ustar ilyailya#include "../../corelibs/U2View/src/util_ov_annotated_dna/WindowStepSelectorWidget.h" ugene-1.9.8/src/include/U2View/UIndexSupport.h0000644000175000017500000000010711651544336017615 0ustar ilyailya#include "../../corelibs/U2View/src/util_ov_indexview/UIndexSupport.h" ugene-1.9.8/src/include/U2View/FindDialog.h0000644000175000017500000000010311651544336017020 0ustar ilyailya#include "../../corelibs/U2View/src/util_find_dialog/FindDialog.h" ugene-1.9.8/src/include/U2View/GraphicsCircularBranchItem.h0000644000175000017500000000012311651544336022204 0ustar ilyailya#include "../../corelibs/U2View/src/util_ov_phyltree/GraphicsCircularBranchItem.h" ugene-1.9.8/src/include/U2View/MSAEditorFactory.h0000644000175000017500000000011011651544336020135 0ustar ilyailya#include "../../corelibs/U2View/src/util_ov_msaedit/MSAEditorFactory.h" ugene-1.9.8/src/include/U2View/CreateRectangularBranchesTask.h0000644000175000017500000000012611651544336022711 0ustar ilyailya#include "../../corelibs/U2View/src/util_ov_phyltree/CreateRectangularBranchesTask.h" ugene-1.9.8/src/include/U2View/UIndexViewHeaderItemWidgetImpl.h0000644000175000017500000000013011651544336022765 0ustar ilyailya#include "../../corelibs/U2View/src/util_ov_indexview/UIndexViewHeaderItemWidgetImpl.h" ugene-1.9.8/src/include/U2View/MSAEditorConsensusArea.h0000644000175000017500000000011611651544336021305 0ustar ilyailya#include "../../corelibs/U2View/src/util_ov_msaedit/MSAEditorConsensusArea.h" ugene-1.9.8/src/include/U2View/SubstMatrixDialog.h0000644000175000017500000000011511651544336020430 0ustar ilyailya#include "../../corelibs/U2View/src/util_smith_waterman/SubstMatrixDialog.h" ugene-1.9.8/src/include/U2View/ADVConstants.h0000644000175000017500000000011211651544336017327 0ustar ilyailya#include "../../corelibs/U2View/src/util_ov_annotated_dna/ADVConstants.h" ugene-1.9.8/src/include/U2View/MSAColorScheme.h0000644000175000017500000000010611651544336017567 0ustar ilyailya#include "../../corelibs/U2View/src/util_ov_msaedit/MSAColorScheme.h" ugene-1.9.8/src/include/U2View/TreeViewerFactory.h0000644000175000017500000000011211651544336020431 0ustar ilyailya#include "../../corelibs/U2View/src/util_ov_phyltree/TreeViewerFactory.h" ugene-1.9.8/src/include/U2View/SecStructPredictUtils.h0000644000175000017500000000012511651544336021277 0ustar ilyailya#include "../../corelibs/U2View/src/util_sec_struct_predict/SecStructPredictUtils.h" ugene-1.9.8/src/include/U2View/ADVSequenceObjectContext.h0000644000175000017500000000012611651544336021624 0ustar ilyailya#include "../../corelibs/U2View/src/util_ov_annotated_dna/ADVSequenceObjectContext.h" ugene-1.9.8/src/include/U2View/DetView.h0000644000175000017500000000010511651544336016371 0ustar ilyailya#include "../../corelibs/U2View/src/util_ov_annotated_dna/DetView.h" ugene-1.9.8/src/include/U2View/AnnotatedDNAViewTasks.h0000644000175000017500000000012311651544336021123 0ustar ilyailya#include "../../corelibs/U2View/src/util_ov_annotated_dna/AnnotatedDNAViewTasks.h" ugene-1.9.8/src/include/U2View/DnaAssemblyGUIExtension.h0000644000175000017500000000012111651544336021464 0ustar ilyailya#include "../../corelibs/U2View/src/util_dna_assembly/DnaAssemblyGUIExtension.h" ugene-1.9.8/src/include/U2View/ADVSingleSequenceWidget.h0000644000175000017500000000012511651544336021435 0ustar ilyailya#include "../../corelibs/U2View/src/util_ov_annotated_dna/ADVSingleSequenceWidget.h" ugene-1.9.8/src/include/U2View/MSAEditorNameList.h0000644000175000017500000000011111651544336020243 0ustar ilyailya#include "../../corelibs/U2View/src/util_ov_msaedit/MSAEditorNameList.h" ugene-1.9.8/src/include/U2View/TreeSettingsDialog.h0000644000175000017500000000010311651544336020560 0ustar ilyailya#include "../../corelibs/U2View/src/phyltree/TreeSettingsDialog.h" ugene-1.9.8/src/include/U2View/ADVSyncViewManager.h0000644000175000017500000000012011651544336020414 0ustar ilyailya#include "../../corelibs/U2View/src/util_ov_annotated_dna/ADVSyncViewManager.h" ugene-1.9.8/src/include/U2View/ADVClipboard.h0000644000175000017500000000011211651544336017252 0ustar ilyailya#include "../../corelibs/U2View/src/util_ov_annotated_dna/ADVClipboard.h" ugene-1.9.8/src/include/U2View/DeleteGapsDialog.h0000644000175000017500000000011011651544336020153 0ustar ilyailya#include "../../corelibs/U2View/src/util_ov_msaedit/DeleteGapsDialog.h" ugene-1.9.8/src/include/U2View/UIndexViewerFactory.h0000644000175000017500000000011511651544336020731 0ustar ilyailya#include "../../corelibs/U2View/src/util_ov_indexview/UIndexViewerFactory.h" ugene-1.9.8/src/include/U2View/SimpleTextObjectViewTasks.h0000644000175000017500000000012211651544336022107 0ustar ilyailya#include "../../corelibs/U2View/src/util_ov_textview/SimpleTextObjectViewTasks.h" ugene-1.9.8/src/include/U2View/ButtonSettingsDialog.h0000644000175000017500000000010511651544336021136 0ustar ilyailya#include "../../corelibs/U2View/src/phyltree/ButtonSettingsDialog.h" ugene-1.9.8/src/include/U2View/UIndexExportToNewFileDialogImpl.h0000644000175000017500000000013111651544336023136 0ustar ilyailya#include "../../corelibs/U2View/src/util_ov_indexview/UIndexExportToNewFileDialogImpl.h" ugene-1.9.8/src/include/U2View/GraphicsBranchItem.h0000644000175000017500000000011311651544336020516 0ustar ilyailya#include "../../corelibs/U2View/src/util_ov_phyltree/GraphicsBranchItem.h" ugene-1.9.8/src/include/U2View/MSAEditorBaseOffsetsCache.h0000644000175000017500000000012111651544336021660 0ustar ilyailya#include "../../corelibs/U2View/src/util_ov_msaedit/MSAEditorBaseOffsetsCache.h" ugene-1.9.8/src/include/U2View/MSAAlignDialog.h0000644000175000017500000000010511651544336017535 0ustar ilyailya#include "../../corelibs/U2View/src/util_msa_align/MSAAlignDialog.h" ugene-1.9.8/src/include/U2View/MSAEditorConsensusCache.h0000644000175000017500000000011711651544336021441 0ustar ilyailya#include "../../corelibs/U2View/src/util_ov_msaedit/MSAEditorConsensusCache.h" ugene-1.9.8/src/include/U2View/MSAEditorTasks.h0000644000175000017500000000010611651544336017620 0ustar ilyailya#include "../../corelibs/U2View/src/util_ov_msaedit/MSAEditorTasks.h" ugene-1.9.8/src/include/U2View/GraphicsRectangularBranchItem.h0000644000175000017500000000012611651544336022712 0ustar ilyailya#include "../../corelibs/U2View/src/util_ov_phyltree/GraphicsRectangularBranchItem.h" ugene-1.9.8/src/include/U2View/SimpleTextObjectView.h0000644000175000017500000000011511651544336021103 0ustar ilyailya#include "../../corelibs/U2View/src/util_ov_textview/SimpleTextObjectView.h" ugene-1.9.8/src/include/U2View/UIndexViewWidgetKey.h0000644000175000017500000000011511651544336020667 0ustar ilyailya#include "../../corelibs/U2View/src/util_ov_indexview/UIndexViewWidgetKey.h" ugene-1.9.8/src/include/U2View/AddSequencesToAlignmentTask.h0000644000175000017500000000012311651544336022353 0ustar ilyailya#include "../../corelibs/U2View/src/util_ov_msaedit/AddSequencesToAlignmentTask.h" ugene-1.9.8/src/include/U2View/TextSettingsDialog.h0000644000175000017500000000010311651544336020605 0ustar ilyailya#include "../../corelibs/U2View/src/phyltree/TextSettingsDialog.h" ugene-1.9.8/src/include/U2View/AnnotatedDNAViewState.h0000644000175000017500000000012311651544336021116 0ustar ilyailya#include "../../corelibs/U2View/src/util_ov_annotated_dna/AnnotatedDNAViewState.h" ugene-1.9.8/src/include/U2View/PanView.h0000644000175000017500000000010511651544336016373 0ustar ilyailya#include "../../corelibs/U2View/src/util_ov_annotated_dna/PanView.h" ugene-1.9.8/src/include/U2View/SmithWatermanDialog.h0000644000175000017500000000011711651544336020730 0ustar ilyailya#include "../../corelibs/U2View/src/util_smith_waterman/SmithWatermanDialog.h" ugene-1.9.8/src/include/U2View/MSAEditorOffsetsView.h0000644000175000017500000000011411651544336020776 0ustar ilyailya#include "../../corelibs/U2View/src/util_ov_msaedit/MSAEditorOffsetsView.h" ugene-1.9.8/src/include/U2View/AutoAnnotationUtils.h0000644000175000017500000000012011651544336021003 0ustar ilyailya#include "../../corelibs/U2View/src/util_ov_annotated_dna/AutoAnnotationUtils.h"ugene-1.9.8/src/include/U2View/TreeViewer.h0000644000175000017500000000010311651544336017101 0ustar ilyailya#include "../../corelibs/U2View/src/util_ov_phyltree/TreeViewer.h" ugene-1.9.8/src/include/U2View/AnnotatedDNAView.h0000644000175000017500000000011611651544336020117 0ustar ilyailya#include "../../corelibs/U2View/src/util_ov_annotated_dna/AnnotatedDNAView.h" ugene-1.9.8/src/include/U2View/AnnotationsTreeView.h0000644000175000017500000000012111651544336020770 0ustar ilyailya#include "../../corelibs/U2View/src/util_ov_annotated_dna/AnnotationsTreeView.h" ugene-1.9.8/src/include/U2View/Overview.h0000644000175000017500000000010611651544336016631 0ustar ilyailya#include "../../corelibs/U2View/src/util_ov_annotated_dna/Overview.h" ugene-1.9.8/src/include/U2View/BranchSettingsDialog.h0000644000175000017500000000010511651544336021060 0ustar ilyailya#include "../../corelibs/U2View/src/phyltree/BranchSettingsDialog.h" ugene-1.9.8/src/include/U2View/MSAEditorSequenceArea.h0000644000175000017500000000011511651544336021074 0ustar ilyailya#include "../../corelibs/U2View/src/util_ov_msaedit/MSAEditorSequenceArea.h" ugene-1.9.8/src/include/U2View/AlignmentLogo.h0000644000175000017500000000010511651544336017561 0ustar ilyailya#include "../../corelibs/U2View/src/util_ov_msaedit/AlignmentLogo.h" ugene-1.9.8/src/include/U2View/BuildIndexDialog.h0000644000175000017500000000011211651544336020167 0ustar ilyailya#include "../../corelibs/U2View/src/util_dna_assembly/BuildIndexDialog.h" ugene-1.9.8/src/include/U2View/CreatePhyTreeDialogController.h0000644000175000017500000000011611651544336022714 0ustar ilyailya#include "../../corelibs/U2View/src/phyltree/CreatePhyTreeDialogController.h" ugene-1.9.8/src/include/U2View/MSAAlignGUIExtension.h0000644000175000017500000000011311651544336020656 0ustar ilyailya#include "../../corelibs/U2View/src/util_msa_align/MSAAlignGUIExtension.h" ugene-1.9.8/src/include/U2View/UIndexViewer.h0000644000175000017500000000010611651544336017401 0ustar ilyailya#include "../../corelibs/U2View/src/util_ov_indexview/UIndexViewer.h" ugene-1.9.8/src/include/U2View/TreeViewerState.h0000644000175000017500000000011011651544336020100 0ustar ilyailya#include "../../corelibs/U2View/src/util_ov_phyltree/TreeViewerState.h" ugene-1.9.8/src/include/U2View/DnaAssemblyDialog.h0000644000175000017500000000011311651544336020343 0ustar ilyailya#include "../../corelibs/U2View/src/util_dna_assembly/DnaAssemblyDialog.h" ugene-1.9.8/src/include/U2View/DnaAssemblyUtils.h0000644000175000017500000000011211651544336020243 0ustar ilyailya#include "../../corelibs/U2View/src/util_dna_assembly/DnaAssemblyUtils.h" ugene-1.9.8/src/include/U2View/MSAEditor.h0000644000175000017500000000010111651544336016605 0ustar ilyailya#include "../../corelibs/U2View/src/util_ov_msaedit/MSAEditor.h" ugene-1.9.8/src/include/U2View/CreateSubalignimentDialogController.h0000644000175000017500000000013311651544336024134 0ustar ilyailya#include "../../corelibs/U2View/src/util_ov_msaedit/CreateSubalignimentDialogController.h" ugene-1.9.8/src/include/U2View/CreateUnrootedBranchesTask.h0000644000175000017500000000012311651544336022236 0ustar ilyailya#include "../../corelibs/U2View/src/util_ov_phyltree/CreateUnrootedBranchesTask.h" ugene-1.9.8/src/include/U2View/EditAnnotationDialogController.h0000644000175000017500000000013411651544336023130 0ustar ilyailya#include "../../corelibs/U2View/src/util_ov_annotated_dna/EditAnnotationDialogController.h" ugene-1.9.8/src/include/U2View/ADVUtils.h0000644000175000017500000000010611651544336016456 0ustar ilyailya#include "../../corelibs/U2View/src/util_ov_annotated_dna/ADVUtils.h" ugene-1.9.8/src/include/U2View/UIndexViewWidgetImpl.h0000644000175000017500000000011611651544336021041 0ustar ilyailya#include "../../corelibs/U2View/src/util_ov_indexview/UIndexViewWidgetImpl.h" ugene-1.9.8/src/include/U2View/WebWindow.h0000644000175000017500000000006111651544336016730 0ustar ilyailya#include "../../corelibs/U2View/src/WebWindow.h" ugene-1.9.8/src/include/U2View/AnnotatedDNAViewFactory.h0000644000175000017500000000012511651544336021447 0ustar ilyailya#include "../../corelibs/U2View/src/util_ov_annotated_dna/AnnotatedDNAViewFactory.h" ugene-1.9.8/src/include/U2View/ADVSequenceWidget.h0000644000175000017500000000011711651544336020274 0ustar ilyailya#include "../../corelibs/U2View/src/util_ov_annotated_dna/ADVSequenceWidget.h" ugene-1.9.8/src/include/U2View/GraphicsUnrootedBranchItem.h0000644000175000017500000000012311651544336022237 0ustar ilyailya#include "../../corelibs/U2View/src/util_ov_phyltree/GraphicsUnrootedBranchItem.h" ugene-1.9.8/src/include/U2View/ConvertAssemblyToSamDialog.h0000644000175000017500000000012311651544336022226 0ustar ilyailya#include "../../corelibs/U2View/src/util_dna_assembly/ConvertAssemblyToSamDialog.h"ugene-1.9.8/src/include/U2View/UIndexViewerTasks.h0000644000175000017500000000011311651544336020405 0ustar ilyailya#include "../../corelibs/U2View/src/util_ov_indexview/UIndexViewerTasks.h" ugene-1.9.8/src/include/U2View/CreateRulerDialogController.h0000644000175000017500000000013111651544336022422 0ustar ilyailya#include "../../corelibs/U2View/src/util_ov_annotated_dna/CreateRulerDialogController.h" ugene-1.9.8/src/include/U2View/TreeViewerUtils.h0000644000175000017500000000011011651544336020120 0ustar ilyailya#include "../../corelibs/U2View/src/util_ov_phyltree/TreeViewerUtils.h" ugene-1.9.8/src/include/U2View/ADVAnnotationCreation.h0000644000175000017500000000012311651544336021154 0ustar ilyailya#include "../../corelibs/U2View/src/util_ov_annotated_dna/ADVAnnotationCreation.h" ugene-1.9.8/src/include/U2View/MSAEditorState.h0000644000175000017500000000010611651544336017613 0ustar ilyailya#include "../../corelibs/U2View/src/util_ov_msaedit/MSAEditorState.h" ugene-1.9.8/src/include/U2View/SecStructDialog.h0000644000175000017500000000011711651544336020064 0ustar ilyailya#include "../../corelibs/U2View/src/util_sec_struct_predict/SecStructDialog.h" ugene-1.9.8/src/include/U2View/ADVGraphModel.h0000644000175000017500000000011311651544336017376 0ustar ilyailya#include "../../corelibs/U2View/src/util_ov_annotated_dna/ADVGraphModel.h" ugene-1.9.8/src/include/U2View/CreatePhyTreeWidget.h0000644000175000017500000000010411651544336020671 0ustar ilyailya#include "../../corelibs/U2View/src/phyltree/CreatePhyTreeWidget.h" ugene-1.9.8/src/include/U2View/GSequenceLineViewAnnotated.h0000644000175000017500000000013011651544336022200 0ustar ilyailya#include "../../corelibs/U2View/src/util_ov_annotated_dna/GSequenceLineViewAnnotated.h" ugene-1.9.8/src/include/U2View/MSAEditorUndoFramework.h0000644000175000017500000000011611651544336021317 0ustar ilyailya#include "../../corelibs/U2View/src/util_ov_msaedit/MSAEditorUndoFramework.h" ugene-1.9.8/src/include/U2View/ConsensusSelectorDialogController.h0000644000175000017500000000013111651544336023666 0ustar ilyailya#include "../../corelibs/U2View/src/util_ov_msaedit/ConsensusSelectorDialogController.h" ugene-1.9.8/src/include/U2View/GSequenceGraphView.h0000644000175000017500000000012011651544336020513 0ustar ilyailya#include "../../corelibs/U2View/src/util_ov_annotated_dna/GSequenceGraphView.h" ugene-1.9.8/src/include/U2View/ADVSplitWidget.h0000644000175000017500000000011411651544336017614 0ustar ilyailya#include "../../corelibs/U2View/src/util_ov_annotated_dna/ADVSplitWidget.h" ugene-1.9.8/src/include/U2View/GSequenceLineView.h0000644000175000017500000000011711651544336020347 0ustar ilyailya#include "../../corelibs/U2View/src/util_ov_annotated_dna/GSequenceLineView.h" ugene-1.9.8/src/include/U2View/MSAEditorStatusBar.h0000644000175000017500000000011211651544336020440 0ustar ilyailya#include "../../corelibs/U2View/src/util_ov_msaedit/MSAEditorStatusBar.h" ugene-1.9.8/src/include/U2View/GraphicsButtonItem.h0000644000175000017500000000011311651544336020574 0ustar ilyailya#include "../../corelibs/U2View/src/util_ov_phyltree/GraphicsButtonItem.h" ugene-1.9.8/src/include/U2Remote/0000755000175000017500000000000011651544336015176 5ustar ilyailyaugene-1.9.8/src/include/U2Remote/SerializeUtils.h0000644000175000017500000000007011651544336020314 0ustar ilyailya#include "../../corelibs/U2Remote/src/SerializeUtils.h" ugene-1.9.8/src/include/U2Remote/ProtocolUI.h0000644000175000017500000000006411651544336017406 0ustar ilyailya#include "../../corelibs/U2Remote/src/ProtocolUI.h" ugene-1.9.8/src/include/U2Remote/PingTask.h0000644000175000017500000000006211651544336017065 0ustar ilyailya#include "../../corelibs/U2Remote/src/PingTask.h" ugene-1.9.8/src/include/U2Remote/SynchHttp.h0000644000175000017500000000006311651544336017272 0ustar ilyailya#include "../../corelibs/U2Remote/src/SynchHttp.h" ugene-1.9.8/src/include/U2Remote/RemoteWorkflowRunTask.h0000644000175000017500000000007711651544336021651 0ustar ilyailya#include "../../corelibs/U2Remote/src/RemoteWorkflowRunTask.h" ugene-1.9.8/src/include/U2Remote/RemoteMachine.h0000644000175000017500000000006711651544336020072 0ustar ilyailya#include "../../corelibs/U2Remote/src/RemoteMachine.h" ugene-1.9.8/src/include/U2Remote/ProtocolInfo.h0000644000175000017500000000006611651544336017766 0ustar ilyailya#include "../../corelibs/U2Remote/src/ProtocolInfo.h" ugene-1.9.8/src/include/U2Remote/RemoteMachineMonitorDialogController.h0000644000175000017500000000011611651544336024621 0ustar ilyailya#include "../../corelibs/U2Remote/src/RemoteMachineMonitorDialogController.h" ugene-1.9.8/src/include/U2Remote/DistributedComputingUtil.h0000644000175000017500000000010211651544336022346 0ustar ilyailya#include "../../corelibs/U2Remote/src/DistributedComputingUtil.h" ugene-1.9.8/src/include/U2Remote/RemoteMachineScanner.h0000644000175000017500000000007611651544336021404 0ustar ilyailya#include "../../corelibs/U2Remote/src/RemoteMachineScanner.h" ugene-1.9.8/src/include/U2Remote/RemoteMachineMonitor.h0000644000175000017500000000007611651544336021442 0ustar ilyailya#include "../../corelibs/U2Remote/src/RemoteMachineMonitor.h" ugene-1.9.8/src/include/U2Remote/TaskDistributor.h0000644000175000017500000000007111651544336020502 0ustar ilyailya#include "../../corelibs/U2Remote/src/TaskDistributor.h" ugene-1.9.8/src/include/U2Remote/RemoteMachineTasks.h0000644000175000017500000000007411651544336021076 0ustar ilyailya#include "../../corelibs/U2Remote/src/RemoteMachineTasks.h" ugene-1.9.8/src/include/U2Remote/Serializable.h0000644000175000017500000000006611651544336017757 0ustar ilyailya#include "../../corelibs/U2Remote/src/Serializable.h" ugene-1.9.8/src/include/U2Core/0000755000175000017500000000000011651544335014632 5ustar ilyailyaugene-1.9.8/src/include/U2Core/ExportToNewFileFromIndexTask.h0000644000175000017500000000011211651544335022472 0ustar ilyailya#include "../../corelibs/U2Core/src/tasks/ExportToNewFileFromIndexTask.h" ugene-1.9.8/src/include/U2Core/RemoveDocumentTask.h0000644000175000017500000000010011651544335020551 0ustar ilyailya#include "../../corelibs/U2Core/src/tasks/RemoveDocumentTask.h" ugene-1.9.8/src/include/U2Core/SaveDocumentStreamingTask.h0000644000175000017500000000010711651544335022073 0ustar ilyailya#include "../../corelibs/U2Core/src/tasks/SaveDocumentStreamingTask.h" ugene-1.9.8/src/include/U2Core/NetworkConfiguration.h0000644000175000017500000000010411651544335021157 0ustar ilyailya#include "../../corelibs/U2Core/src/globals/NetworkConfiguration.h" ugene-1.9.8/src/include/U2Core/U2Annotation.h0000644000175000017500000001735711651544335017341 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_ANNOTATION_H_ #define _U2_ANNOTATION_H_ #include #include #include #include #include namespace U2 { /** Annotation qualifier - a textual property/remark for annotation */ class U2CORE_EXPORT U2Qualifier { public: /** Name of qualifier */ QString name; /** Value of qualifier */ QString value; /** Constructs new empty (and invalid) qualifier */ U2Qualifier(){} /** Constructs new qualifier instance with name and value set */ U2Qualifier(const QString& _name, const QString& _value) : name(_name), value(_value){} /** U2Qualifier is valid if its name is not empty */ bool isValid() const {return !name.isEmpty();} /** Any two qualifiers are equal if their names & values are equal */ bool operator== ( const U2Qualifier & q ) const { return q.name == name && q.value == value; } /** Any two qualifiers are not equal if either their names or values are not equal */ bool operator!= ( const U2Qualifier & q ) const { return !(*this == q); } }; /** For annotation with multiple regions this flag indicates how to process joins */ enum U2LocationOperator { /** Location elements must be joined */ U2LocationOperator_Join = 1, /** No need to join location elements */ U2LocationOperator_Order = 2 }; /** Type of location region */ enum U2LocationRegionType { /** default */ U2LocationRegionType_Default = 0, /** a site between indicated adjoining bases */ U2LocationRegionType_Site = 1, /** a single base chosen from within a specified range of bases (not allowed for new entries) */ U2LocationRegionType_SingleBase = 2 }; /** Annotation location */ class U2CORE_EXPORT U2LocationData : public QSharedData { public: /** Location operator */ U2LocationOperator op; /** Strand of the location. */ U2Strand strand; /** Descriptor of the region: no special info, site, ... Note that all non-default values are affective only for single region locations */ U2LocationRegionType regionType; /** Annotation region extends further to the left */ bool truncateLeft; /** Annotation region extends further to the right */ bool truncateRight; /** Annotated regions coordinates */ QVector regions; /** Constructs empty location */ U2LocationData() { reset(); } bool isEmpty() const {return regions.isEmpty();} /** Resets location to initial empty state */ void reset(); bool isOrder() const {return op == U2LocationOperator_Order;} bool isJoin() const {return op == U2LocationOperator_Join;} bool isMultiRegion() const {return regions.size() > 1;} bool isSingleRegion() const {return regions.size() == 1;} bool operator==(const U2LocationData& l) const; bool operator!=(const U2LocationData& l) const {return !(*this == l);} }; inline bool U2LocationData::operator==(const U2LocationData& l) const { bool res = regions == l.regions && strand == l.strand && op == l.op && regionType == l.regionType && truncateLeft == l.truncateLeft && truncateRight == l.truncateRight; return res; } /** U2Location is a shared pointer to U2LocationData The difference in behavior with normal shared pointer is that it creates default U2LocationData for non-arg constructor and compares LocationData by value for == and != operators */ class U2CORE_EXPORT U2Location { public: U2Location() : d(new U2LocationData()){} U2Location( U2LocationData *l) : d(l){} U2LocationData& operator*() {return *d;} const U2LocationData& operator*() const {return *d;} U2LocationData* operator->() {return d;} const U2LocationData* operator->() const {return d;} U2LocationData *data() {return d.data(); } const U2LocationData *data() const {return d.constData();} inline operator U2LocationData *() { return d; } inline operator const U2LocationData *() const { return d; } U2Location& operator=(const U2Location& other) {d = other.d; return *this;} private: QSharedDataPointer d; }; inline bool operator!= ( const U2Location & ptr1, const U2Location & ptr2 ) {return *ptr1 != *ptr2;} inline bool operator!= ( const U2Location & ptr1, const U2LocationData * ptr2 ) {return *ptr1 != *ptr2;} inline bool operator!= ( const U2LocationData * ptr1, const U2Location & ptr2 ) {return *ptr1 != *ptr2;} inline bool operator== ( const U2Location & ptr1, const U2Location & ptr2 ) {return *ptr1 == *ptr2;} inline bool operator== ( const U2Location & ptr1, const U2LocationData * ptr2 ) {return *ptr1 == *ptr2;} inline bool operator== ( const U2LocationData * ptr1, const U2Location & ptr2 ) {return *ptr1 == *ptr2;} /** Sequence annotation. Used to annotate set of sequence regions */ class U2CORE_EXPORT U2Annotation : public U2Entity { public: /** Sequence this annotation is related to */ U2DataId sequenceId; /** Key (name) of the annotation */ QString key; /** Annotation location */ U2Location location; /** Annotation related qualifiers (textual properties) */ QVector qualifiers; /** Version of the annotation. Same as modification count */ qint64 version; }; /** Group of the annotations represents a tree-like hierarchy of annotations related to some sequence. Group holds references to annotation and one annotation can be included into multiple groups If an annotation does not belong to any group -> the annotation must be removed by DBI */ class U2CORE_EXPORT U2AnnotationGroup : public U2Entity { public: /** Parent group for this group */ U2DataId parentGroupId; /** Object (sequence) this group is related to */ U2DataId sequenceId; /** Group name, may contain any readable characters except '/' symbol used to separate group path */ QString name; /** Group path Path construction algorithm: parent-name2 + "/" + parent-name1 + "/" + ... + "/" + groupName Note: group path includes current group name */ QString path; /** Modification counter of group fields, content and annotation names included into the group */ qint64 localVersion; /** Modification counter updated any (any depth) child group is modified */ qint64 globalVersion; }; ////////////////////////////////////////////////////////////////////////// // functions impl inline void U2LocationData::reset() { regions.clear(); strand = U2Strand::Direct; op = U2LocationOperator_Join; regionType = U2LocationRegionType_Default; truncateLeft = false; truncateRight = false; } } //namespace #endif ugene-1.9.8/src/include/U2Core/DNASequenceSelection.h0000644000175000017500000000010611651544335020741 0ustar ilyailya#include "../../corelibs/U2Core/src/selection/DNASequenceSelection.h" ugene-1.9.8/src/include/U2Core/U2CoreAttributes.h0000644000175000017500000000426411651544335020157 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_CORE_ATTRIBUTES_H_ #define _U2_CORE_ATTRIBUTES_H_ #include namespace U2 { ////////////////////////////////////////////////////////////////////////// // Reserved attribute names class U2CORE_EXPORT U2BaseAttributeName { /** Reserved to represent length: sequence or alignment This attribute can be artificial and derived directly from structure values If structure length is updated, system is responsible to update the attribute too */ static const QString length;// = "length"; /** Reserved to represent alphabet: sequence or alignment This attribute can be artificial and derived directly from structure values If structure alphabet is updated, system is responsible to update the attribute too */ static const QString alphabet;// = "alphabet"; /** Reserved to represent GC-content: sequence or alignment This attribute can be artificial and derived directly from structure values If structure gc-content is updated, system is responsible to update the attribute too */ static const QString gc_content;// = "GC-content"; /** Structure modification date */ static const QString update_time;// = "update-time"; /** Structure creation date */ static const QString create_date; // = "creation-time"; }; #endif ugene-1.9.8/src/include/U2Core/U2AbstractDbi.h0000644000175000017500000002566211651544335017407 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ /** Default DBI implementations */ #ifndef _U2_ABSTRACT_DBI_H_ #define _U2_ABSTRACT_DBI_H_ #include #include #include #include #include #include #include #include namespace U2 { /** Default (empty) implementation for optional DBI methods */ class U2AbstractDbi : public U2Dbi { public: U2AbstractDbi(const U2DbiFactoryId& fid) { state = U2DbiState_Void; factoryId = fid; } virtual bool flush(U2OpStatus&) {return true;} virtual U2DbiState getState() const {return state;} virtual U2DbiId getDbiId() const {return dbiId;} virtual U2DbiFactoryId getFactoryId() const {return factoryId;} virtual const QSet& getFeatures() const {return features;} virtual QHash getInitProperties() const {return initProperties;} virtual QHash getDbiMetaInfo(U2OpStatus&) {return metaInfo;} virtual U2SequenceDbi* getSequenceDbi() {return NULL;} virtual U2AnnotationDbi* getAnnotationRDbi() {return NULL;} virtual U2MsaDbi* getMsaDbi() {return NULL;} virtual U2AssemblyDbi* getAssemblyDbi() {return NULL;} virtual U2AttributeDbi* getAttributeDbi() {return NULL;} virtual U2ObjectDbi* getObjectDbi() {return NULL;} virtual U2CrossDatabaseReferenceDbi* getCrossDatabaseReferenceDbi() {return NULL;} virtual U2DataType getEntityTypeById(const U2DataId&) const {return U2Type::Unknown;} protected: U2DbiState state; U2DbiId dbiId; U2DbiFactoryId factoryId; QSet features; QHash initProperties; QHash metaInfo; }; /** Default no-op implementation for write methods of U2ObjectDbi */ class U2SimpleObjectDbi : public U2ObjectDbi { protected: U2SimpleObjectDbi(U2Dbi* rootDbi) : U2ObjectDbi(rootDbi) {} virtual void removeObject(const U2DataId&, const QString&, U2OpStatus& os) { U2DbiUtils::logNotSupported(U2DbiFeature_RemoveObjects, getRootDbi(), os); } virtual void removeObjects(const QList&, const QString&, U2OpStatus& os) { U2DbiUtils::logNotSupported(U2DbiFeature_RemoveObjects, getRootDbi(), os); } virtual void createFolder(const QString&, U2OpStatus& os) { U2DbiUtils::logNotSupported(U2DbiFeature_ChangeFolders, getRootDbi(), os); } virtual void removeFolder(const QString&, U2OpStatus& os) { U2DbiUtils::logNotSupported(U2DbiFeature_ChangeFolders, getRootDbi(), os); } virtual void addObjectsToFolder(const QList&, const QString&, U2OpStatus& os) { U2DbiUtils::logNotSupported(U2DbiFeature_ChangeFolders, getRootDbi(), os); } virtual void moveObjects(const QList&, const QString&, const QString&, U2OpStatus& os) { U2DbiUtils::logNotSupported(U2DbiFeature_ChangeFolders, getRootDbi(), os); } }; /** Default no-op implementation for write methods of U2SequenceDbi */ class U2SimpleSequenceDbi: public U2SequenceDbi { protected: U2SimpleSequenceDbi(U2Dbi* rootDbi) : U2SequenceDbi(rootDbi) {} virtual void createSequenceObject(U2Sequence&, const QString&, U2OpStatus& os) { U2DbiUtils::logNotSupported(U2DbiFeature_WriteSequence, getRootDbi(), os); } virtual void updateSequenceData(const U2DataId&, const U2Region&, const QByteArray&, U2OpStatus& os) { U2DbiUtils::logNotSupported(U2DbiFeature_WriteSequence, getRootDbi(), os); } }; /** Default no-op implementation for write methods of U2MsaDbi */ class U2SimpleMsaDbi: public U2MsaDbi{ protected: U2SimpleMsaDbi(U2Dbi* rootDbi) : U2MsaDbi(rootDbi) {} virtual void createMsaObject(U2Msa&, const QString&, U2OpStatus& os) { U2DbiUtils::logNotSupported(U2DbiFeature_WriteMsa, getRootDbi(), os); } virtual void removeSequences(U2Msa&, const QList , U2OpStatus &os) { U2DbiUtils::logNotSupported(U2DbiFeature_WriteMsa, getRootDbi(), os); } virtual void addSequences(U2Msa&, const QList&, U2OpStatus& os) { U2DbiUtils::logNotSupported(U2DbiFeature_WriteMsa, getRootDbi(), os); } }; /** Default no-op implementation for write methods of U2AssemblyDbi */ class U2SimpleAssemblyDbi: public U2AssemblyDbi{ protected: U2SimpleAssemblyDbi(U2Dbi* rootDbi) : U2AssemblyDbi(rootDbi) {} virtual void createAssemblyObject(U2Assembly&, const QString&, U2DbiIterator*, U2AssemblyReadsImportInfo&, U2OpStatus& os) { U2DbiUtils::logNotSupported(U2DbiFeature_WriteAssembly, getRootDbi(), os); } virtual void updateAssemblyObject(const U2Assembly&, U2OpStatus& os) { U2DbiUtils::logNotSupported(U2DbiFeature_WriteAssembly, getRootDbi(), os); } virtual void removeReads(const U2DataId&, const QList&, U2OpStatus& os) { U2DbiUtils::logNotSupported(U2DbiFeature_WriteAssembly, getRootDbi(), os); } virtual void addReads(const U2DataId&, U2DbiIterator*, U2OpStatus& os) { U2DbiUtils::logNotSupported(U2DbiFeature_WriteAssembly, getRootDbi(), os); } virtual void pack(const U2DataId&, U2AssemblyPackStat&, U2OpStatus& os) { U2DbiUtils::logNotSupported(U2DbiFeature_AssemblyReadsPacking, getRootDbi(), os); } virtual void calculateCoverage(const U2DataId&, const U2Region&, U2AssemblyCoverageStat&, U2OpStatus& os) { U2DbiUtils::logNotSupported(U2DbiFeature_AssemblyCoverageStat, getRootDbi(), os); } }; /** Default no-op implementation for write methods of U2AnnotationDbi */ class U2SimpleAnnotationDbi: public U2AnnotationDbi { protected: U2SimpleAnnotationDbi(U2Dbi* rootDbi) : U2AnnotationDbi(rootDbi) {} virtual U2AnnotationGroup createGroup(const U2DataId&, const QString&, U2OpStatus& os) { U2DbiUtils::logNotSupported(U2DbiFeature_WriteSequenceAnnotations, getRootDbi(), os); return U2AnnotationGroup(); } virtual U2AnnotationGroup moveGroup(const U2DataId&, const QString&, U2OpStatus& os) { U2DbiUtils::logNotSupported(U2DbiFeature_WriteSequenceAnnotations, getRootDbi(), os); return U2AnnotationGroup(); } virtual void createAnnotation(U2Annotation&, U2OpStatus& os) { U2DbiUtils::logNotSupported(U2DbiFeature_WriteSequenceAnnotations, getRootDbi(), os); } virtual void createAnnotations(QList&, U2OpStatus& os) { U2DbiUtils::logNotSupported(U2DbiFeature_WriteSequenceAnnotations, getRootDbi(), os); } virtual void removeAnnotation(const U2DataId&, U2OpStatus& os) { U2DbiUtils::logNotSupported(U2DbiFeature_WriteSequenceAnnotations, getRootDbi(), os); } virtual void removeAnnotations(const QList&, U2OpStatus& os) { U2DbiUtils::logNotSupported(U2DbiFeature_WriteSequenceAnnotations, getRootDbi(), os); } virtual void updateLocation(const U2DataId&, const U2Location&, U2OpStatus& os) { U2DbiUtils::logNotSupported(U2DbiFeature_WriteSequenceAnnotations, getRootDbi(), os); } virtual void updateName(const U2DataId&, const QString&, U2OpStatus& os) { U2DbiUtils::logNotSupported(U2DbiFeature_WriteSequenceAnnotations, getRootDbi(), os); } virtual void createQualifier(const U2DataId&, const U2Qualifier&, U2OpStatus& os) { U2DbiUtils::logNotSupported(U2DbiFeature_WriteSequenceAnnotations, getRootDbi(), os); } virtual void removeQualifier(const U2DataId&, const U2Qualifier&, U2OpStatus& os) { U2DbiUtils::logNotSupported(U2DbiFeature_WriteSequenceAnnotations, getRootDbi(), os); } virtual void addToGroup(const U2DataId&, const U2DataId&, U2OpStatus& os) { U2DbiUtils::logNotSupported(U2DbiFeature_WriteSequenceAnnotations, getRootDbi(), os); } virtual void removeFromGroup(const U2DataId&, const U2DataId, U2OpStatus& os) { U2DbiUtils::logNotSupported(U2DbiFeature_WriteSequenceAnnotations, getRootDbi(), os); } }; /** Default no-op implementation for write methods of U2AttributeDbi */ class U2SimpleAttributeDbi: public U2AttributeDbi { protected: U2SimpleAttributeDbi(U2Dbi* rootDbi) : U2AttributeDbi(rootDbi) {} virtual void removeAttributes(const QList&, U2OpStatus& os) { U2DbiUtils::logNotSupported(U2DbiFeature_WriteAttributes, getRootDbi(), os); } virtual void removeObjectAttributes(const U2DataId&, U2OpStatus& os) { U2DbiUtils::logNotSupported(U2DbiFeature_WriteAttributes, getRootDbi(), os); } virtual void createIntegerAttribute(U2IntegerAttribute&, U2OpStatus& os) { U2DbiUtils::logNotSupported(U2DbiFeature_WriteAttributes, getRootDbi(), os); } virtual void createRealAttribute(U2RealAttribute&, U2OpStatus& os) { U2DbiUtils::logNotSupported(U2DbiFeature_WriteAttributes, getRootDbi(), os); } virtual void createStringAttribute(U2StringAttribute&, U2OpStatus& os) { U2DbiUtils::logNotSupported(U2DbiFeature_WriteAttributes, getRootDbi(), os); } virtual void createByteArrayAttribute(U2ByteArrayAttribute&, U2OpStatus& os) { U2DbiUtils::logNotSupported(U2DbiFeature_WriteAttributes, getRootDbi(), os); } }; class U2SimpleCrossDatabaseReferenceDbi: public U2CrossDatabaseReferenceDbi { public: virtual U2CrossDatabaseReference getCrossReference(const U2DataId&, U2OpStatus& os) { U2DbiUtils::logNotSupported(U2DbiFeature_WriteCrossDatabaseReferences, getRootDbi(), os); return U2CrossDatabaseReference(); } virtual void updateCrossReference(const U2CrossDatabaseReference&, U2OpStatus& os) { U2DbiUtils::logNotSupported(U2DbiFeature_WriteCrossDatabaseReferences, getRootDbi(), os); } }; }//namespace #endif ugene-1.9.8/src/include/U2Core/global.h0000644000175000017500000000006611651544335016245 0ustar ilyailya#include "../../corelibs/U2Core/src/globals/global.h" ugene-1.9.8/src/include/U2Core/CMDLineHelpProvider.h0000644000175000017500000000010311651544335020534 0ustar ilyailya#include "../../corelibs/U2Core/src/cmdline/CMDLineHelpProvider.h" ugene-1.9.8/src/include/U2Core/GAutoDeleteList.h0000644000175000017500000000007711651544335020005 0ustar ilyailya#include "../../corelibs/U2Core/src/globals/GAutoDeleteList.h" ugene-1.9.8/src/include/U2Core/DNAAlphabet.h0000644000175000017500000000007411651544335017047 0ustar ilyailya#include "../../corelibs/U2Core/src/datatype/DNAAlphabet.h" ugene-1.9.8/src/include/U2Core/U2ObjectDbi.h0000644000175000017500000001523311651544335017043 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_OBJECT_DBI_H_ #define _U2_OBJECT_DBI_H_ #include #include namespace U2 { /** An primary interface to access database content Any database contains objects that are placed into folders Folders have unique string IDs - constructed similar to full folders names on Unix systems The root folder "/" is required for any DBI */ class U2CORE_EXPORT U2ObjectDbi : public U2ChildDbi { protected: U2ObjectDbi(U2Dbi* rootDbi) : U2ChildDbi(rootDbi) {} public: /** Returns number of top-level U2Objects in database */ virtual qint64 countObjects(U2OpStatus& os) = 0; /** Returns number of top-level U2Objects with the specified type in database */ virtual qint64 countObjects(U2DataType type, U2OpStatus& os) = 0; /** Lists database top-level objects, starts with 'offset' and limits by 'count'. The 'offset' and 'count' can be arbitrarily large but should not be negative. Also, 'count' can have special value 'DBI_NO_LIMIT'. */ virtual QList getObjects(qint64 offset, qint64 count, U2OpStatus& os) = 0; /** Lists database top-level objects of the specified type, starts with 'offset' and limits by 'count'. The 'offset' and 'count' can be arbitrarily large but should not be negative. Also, 'count' can have special value 'DBI_NO_LIMIT'. */ virtual QList getObjects(U2DataType type, qint64 offset, qint64 count, U2OpStatus& os) = 0; /** Returns parents for the entity. If entity is object, returns other object this object is a part of If object is not a part of any other object and does not belongs to any folder - it's automatically removed. */ virtual QList getParents(const U2DataId& entityId, U2OpStatus& os) = 0; /** Returns list of folders stored in database. Folders are represented as paths, separated by '/' character. At least one root folder is required. */ virtual QStringList getFolders(U2OpStatus& os) = 0; /** Returns version of the folder. The folder version increases if new object(s)/subfolder(s) are added into this folder Note that if object(s)/folder(s) are added into one of the subfolders the folder version is not changed */ virtual qint64 getFolderLocalVersion(const QString& folder, U2OpStatus& os) = 0; /** Returns version of the folder that changes every time object(s)/folder(s) added to the specified folder or any of its child folders */ virtual qint64 getFolderGlobalVersion(const QString& folder, U2OpStatus& os) = 0; /** Returns number of top-level U2Objects in folder */ virtual qint64 countObjects(const QString& folder, U2OpStatus& os) = 0; /** Lists database top-level objects of the specified type, starts with 'offset' and limits by 'count'. The 'offset' and 'count' can be arbitrarily large but should not be negative. Also, 'count' can have special value 'DBI_NO_LIMIT'. */ virtual QList getObjects(const QString& folder, qint64 offset, qint64 count, U2OpStatus& os) = 0; /** Returns all folders this object must be shown in */ virtual QStringList getObjectFolders(const U2DataId& objectId, U2OpStatus& os) = 0; /** Returns version of the given object */ virtual qint64 getObjectVersion(const U2DataId& objectId, U2OpStatus& os) = 0; /** Removes object from the specified folder. If folder is empty - removes object from all folders. Note: the object & all related data is automatically removed from database when object is not placed in any folder or is not a part of any other more complex object (ex: sequence in msa) Requires: U2DbiFeature_RemoveObjects feature support */ virtual void removeObject(const U2DataId& dataId, const QString& folder, U2OpStatus& os) = 0; /** Removes collection of objects from the specified folder. If folder is empty - removes object from all folders. Note: the object & all related data is automatically removed from database when object is not placed in any folder or is not a part of any other more complex object (ex: sequence in msa) Requires: U2DbiFeature_RemoveObjects feature support */ virtual void removeObjects(const QList& dataIds, const QString& folder, U2OpStatus& os) = 0; /** Creates folder in the database. The specified path must be a valid unique path, not existing in the database. It is not required that parent folders must exist, they are created automatically. Requires: U2DbiFeature_ChangeFolders feature support */ virtual void createFolder(const QString& path, U2OpStatus& os) = 0; /** Removes folder. The folder must be existing path. Runs GC check for all objects in the folder Requires: U2DbiFeature_ChangeFolders feature support */ virtual void removeFolder(const QString& folder, U2OpStatus& os) = 0; /** Adds objects to the specified folder. All objects must exist and have a top-level type. Requires: U2DbiFeature_ChangeFolders feature support */ virtual void addObjectsToFolder(const QList& objectIds, const QString& toFolder, U2OpStatus& os) = 0; /** Moves objects between folders. 'fromFolder' must be existing path containing all specified objects. 'toFolder' must be existing path or empty string. If 'toFolder' is empty, removes the objects from 'fromFolder' and deletes non-top-level objects without parents, if any appear in the specified list. Otherwise, moves the specified objects between the specified folders, omitting duplicates. Requires: U2DbiFeature_ChangeFolders feature support */ virtual void moveObjects(const QList& objectIds, const QString& fromFolder, const QString& toFolder, U2OpStatus& os) = 0; }; } //namespace #endif ugene-1.9.8/src/include/U2Core/U2OpStatusUtils.h0000644000175000017500000000561411651544335020023 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_OPSTATUS_UTILS_H_ #define _U2_OPSTATUS_UTILS_H_ #include #include namespace U2 { /** Default helper stub for U2OpStatus Note: implementation is not thread safe! */ class U2CORE_EXPORT U2OpStatusImpl : public U2OpStatus { public: //#define FORCE_OP_STATUS_CHECK #ifdef FORCE_OP_STATUS_CHECK U2OpStatusImpl() : cancelFlag(false), progress(-1) , muted(false), checked(false) {} ~U2OpStatusImpl() { if (!muted) { assert(checked); } } void markChecked() const {checked = true;} #else U2OpStatusImpl() : cancelFlag(false), progress(-1) {} void markChecked() const {} #endif virtual void setError(const QString & err) {error = err;} virtual QString getError() const {markChecked(); return error;} virtual bool hasError() const {markChecked(); return !error.isEmpty();} virtual bool isCanceled() const {return cancelFlag != 0;} virtual void setCanceled(bool v) {cancelFlag = v;} virtual int getProgress() const {return progress;} virtual void setProgress(int v) {progress = v;} virtual QString getDescription() const {return statusDesc;} virtual void setDescription(const QString& desc) {statusDesc = desc;} private: /** Keeps error message if operation failed */ QString error; /** Keeps current operation state description */ QString statusDesc; /** Indicates if operation is canceled or not. If yes - processing must be stopped */ int cancelFlag; /** Current operation progress. -1 - unknown */ int progress; #ifdef FORCE_OP_STATUS_CHECK /** Operation check state. If not muted - user must ask operation if there was an error! */ bool muted; /** If true, operation result was checked by user */ mutable bool checked; #endif }; /** Logs operation status error using specified log category */ #define LOG_OP(os)\ if (os.hasError()) {\ coreLog.error(QString("Operation failed: %1 at %2:%3").arg(os.getError()).arg(__FILE__).arg(__LINE__));\ } }// namespace #endif ugene-1.9.8/src/include/U2Core/RemovePartFromSequenceTask.h0000644000175000017500000000011011651544335022217 0ustar ilyailya#include "../../corelibs/U2Core/src/tasks/RemovePartFromSequenceTask.h" ugene-1.9.8/src/include/U2Core/AppResources.h0000644000175000017500000000007411651544335017417 0ustar ilyailya#include "../../corelibs/U2Core/src/globals/AppResources.h" ugene-1.9.8/src/include/U2Core/U2Alphabet.h0000644000175000017500000000226711651544335016741 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_ALPHABET_H_ #define _U2_ALPHABET_H_ #include namespace U2 { /** Bio-sequence alphabet. TODO: UGENE1.x DNAAlphabet impl must be moved here after refactoring */ class U2CORE_EXPORT U2AlphabetId { public: U2AlphabetId(){} U2AlphabetId(QString aid) : id(aid){} QString id; }; } // namespace #endif ugene-1.9.8/src/include/U2Core/GObjectUtils.h0000644000175000017500000000007511651544335017343 0ustar ilyailya#include "../../corelibs/U2Core/src/gobjects/GObjectUtils.h" ugene-1.9.8/src/include/U2Core/LocalFileAdapter.h0000644000175000017500000000007311651544335020136 0ustar ilyailya#include "../../corelibs/U2Core/src/io/LocalFileAdapter.h" ugene-1.9.8/src/include/U2Core/U2Bits.h0000644000175000017500000000742411651544335016122 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_BITS_H_ #define _U2_BITS_H_ #include #include #include namespace U2 { class U2OpStatus; /** Utility class that can compress any string with a small alphabet size ( < 20-30 symbols types) */ class U2CORE_EXPORT U2BitCompression : public QObject { public: static QByteArray compress(const char* text, int uncompressedLen, int alphabetSize, const int* alphabetCharNums, U2OpStatus& os); static QByteArray uncompress(const char* data, const QByteArray& alphabetChars, U2OpStatus& os); static QVector prepareCharNumsMask(const QByteArray& alphabetChars); static bool isCompressionNeeded(int textLen, int alphabetSize); }; /** Bits manipulation helper */ class U2CORE_EXPORT U2Bits { public: static int getBitInByte(int pos); static int getByteIndex(int bit); static int getNumberOfBytes(int nBits); static int getNumberOfBitsPerChar(int nChars); static QByteArray allocateBits(int nBits); static bool getBit(const uchar* bitSet, int idx); static void setBit(uchar* bits, int pos, bool val) { if (val) setBit(bits, pos); else clearBit(bits, pos);} static void setBit(uchar* bits, int pos); static void clearBit(uchar* bits, int pos); static void setBits(uchar* dstBits, int pos, const uchar* srcBits, int nBits); static int bitsRange2Int32(const uchar* bits, int pos, int len); static qint64 makeFirstNSignedBitsValue(int nBits); static qint8 readInt8(const uchar* bits, int pos); static void writeInt8(uchar* bits, int pos, qint8 val); static qint8 readInt16(const uchar* bits, int pos); static void writeInt16(uchar* bits, int pos, qint16 val); static qint8 readInt32(const uchar* bits, int pos); static void writeInt32(uchar* bits, int pos, qint32 val); }; inline int U2Bits::getBitInByte(int pos) { return pos & 7; // use last 3 bits } inline int U2Bits::getByteIndex(int bit) { return (bit >> 3); // we store 8 bits (2^3) per word } inline int U2Bits::getNumberOfBytes(int nBits) { return nBits == 0 ? 0 : getByteIndex(nBits - 1) + 1; } inline bool U2Bits::getBit(const uchar* bits, int idx) { const uchar* b = bits + + getByteIndex(idx); int bitInByte = getBitInByte(idx); bool res = bool(*b & uchar(1 << bitInByte)); return res; } inline void U2Bits::setBit(uchar* bits, int pos) { int idx = getByteIndex(pos); uchar* b = bits + idx; int bitInByte = getBitInByte(pos); *b = *b | uchar(1 << bitInByte); } inline void U2Bits::clearBit(uchar* bits, int pos) { int idx = getByteIndex(pos); uchar* b = bits + idx; int bitInByte = getBitInByte(pos); *b = *b & ~uchar(1 << bitInByte); } inline qint64 U2Bits::makeFirstNSignedBitsValue(int nBits) { static qint64 allSignedBitsValue = 0xFFFFFFFFFFFFFFFFLL; qint64 res = allSignedBitsValue; res = res << nBits; return ~res; } } //namespace #endif ugene-1.9.8/src/include/U2Core/LoadRemoteDocumentTask.h0000644000175000017500000000010411651544335021353 0ustar ilyailya#include "../../corelibs/U2Core/src/tasks/LoadRemoteDocumentTask.h" ugene-1.9.8/src/include/U2Core/U2Attribute.h0000644000175000017500000000417711651544335017166 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_ATTRIBUTE_H_ #define _U2_ATTRIBUTE_H_ #include #include #include #include namespace U2 { /** Attribute for any top-level object record. Some name/value are supported internally and must be tracked by the system on sequence modification */ class U2CORE_EXPORT U2Attribute : public U2Entity { public: U2Attribute() : version(0) {} /** parent object id */ U2DataId objectId; /** Additional object id, optional */ U2DataId childId; /** parent object version this attribute is related to. If <=0 -> any is OK. */ qint64 version; /* Name of the attribute */ QString name; }; /** 64 bit signed integer attribute */ class U2CORE_EXPORT U2IntegerAttribute : public U2Attribute { public: U2IntegerAttribute() : value(0) {} qint64 value; }; /** 64 bit real attribute */ class U2CORE_EXPORT U2RealAttribute : public U2Attribute { public: U2RealAttribute() : value(0.0) {} double value; }; /** String attribute */ class U2CORE_EXPORT U2StringAttribute : public U2Attribute { public: QString value; }; /** Byte array attribute */ class U2CORE_EXPORT U2ByteArrayAttribute: public U2Attribute { public: QByteArray value; }; } //namespace #endif ugene-1.9.8/src/include/U2Core/U2AnnotationsDbi.h0000644000175000017500000001402311651544335020126 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_ANNOTATION_DBI_H_ #define _U2_ANNOTATION_DBI_H_ #include #include #include namespace U2 { /** An interface to obtain 'read' access to sequence annotations */ class U2CORE_EXPORT U2AnnotationDbi : public U2ChildDbi { protected: U2AnnotationDbi(U2Dbi* rootDbi) : U2ChildDbi(rootDbi){} public: /** Returns group by path. Path construction algorithm: parent-name2 + "/" + parent-name1 + "/" + ... + "/" + groupName */ virtual U2AnnotationGroup getGroupByPath(const U2DataId& sequenceId, const QString& path, U2OpStatus& os) =0; /** Returns all subgroups of the given group */ virtual QList getSubgroups(const U2DataId& groupId, U2OpStatus& os) = 0; /** Reads annotation group by id */ virtual U2AnnotationGroup getGroup(const U2DataId& groupId, U2OpStatus& os) = 0; /** Creates new group. If group already exists - returns existing instance Requires: U2DbiFeature_WriteAnnotation feature support */ virtual U2AnnotationGroup createGroup(const U2DataId& sequenceId, const QString& path, U2OpStatus& os) = 0; /** Changes group path. If destination group is already exists operation fails. Requires: U2DbiFeature_WriteAnnotation feature support */ virtual U2AnnotationGroup moveGroup(const U2DataId& groupId, const QString& newPath, U2OpStatus& os) = 0; /** Returns number of annotations for the given sequence object in the given region. Counts all annotations whose location intersects the region. If region is [0, U2_DBI_NO_LIMIT] - returns all annotation for the given sequence */ virtual qint64 countSequenceAnnotations(const U2DataId& sequenceId, const U2Region& region, U2OpStatus& os) = 0; /** Returns number of annotations in the given sequence group object in the given region. Counts all annotations whose location intersects the region. If region is [0, U2_DBI_NO_LIMIT] - returns all annotation for the given sequence */ virtual qint64 countGroupAnnotations(const U2DataId& sequenceId, const U2Region& region, U2OpStatus& os) = 0; /** Returns annotations for the given sequence object Orders result by qualifier if not empty */ virtual U2DbiIterator* getAnnotationsBySequence(const U2DataId& sequenceId, const U2Region& region, const QString& orderByQualifier, U2OpStatus& os) = 0; /** Returns annotations for the given group Orders result by qualifier if not empty */ virtual U2DbiIterator* getAnnotationsByGroup(const U2DataId& sequenceId, const U2Region& region, const QString& orderByQualifier, U2OpStatus& os) = 0; /** Reads annotation entity by id */ virtual U2Annotation getAnnotation(const U2DataId& annotationId, U2OpStatus& os) = 0; /** Returns groups this annotation belongs to */ virtual QList getAnnotationGroups(const U2DataId& annotationId, U2OpStatus& os) = 0; /** Adds list of new annotations. Assigns Ids to annotations added Requires: U2DbiFeature_WriteAnnotation feature support */ virtual void createAnnotations(QList& annotations, const U2DataId& group, U2OpStatus& os) = 0; /** Removes annotation from database Requires: U2DbiFeature_WriteAnnotation feature support */ virtual void removeAnnotation(const U2DataId& annotationId, U2OpStatus& os) = 0; /** Removes annotations from database Requires: U2DbiFeature_WriteAnnotation feature support */ virtual void removeAnnotations(const QList& annotationIds, U2OpStatus& os) = 0; /** Changes annotations location Requires: U2DbiFeature_WriteAnnotation feature support */ virtual void updateLocation(const U2DataId& annotationId, const U2Location& location, U2OpStatus& os) = 0; /** Changes annotations name Requires: U2DbiFeature_WriteAnnotation feature support */ virtual void updateName(const U2DataId& annotationId, const QString& newName, U2OpStatus& os) = 0; /** Adds new qualifier to annotation Requires: U2DbiFeature_WriteAnnotation feature support */ virtual void createQualifier(const U2DataId& annotationId, const U2Qualifier& q, U2OpStatus& os) = 0; /** Removes existing qualifier from annotation Requires: U2DbiFeature_WriteAnnotation feature support */ virtual void removeQualifier(const U2DataId& annotationId, const U2Qualifier& q, U2OpStatus& os) = 0; /** Adds annotation to the specified group Requires: U2DbiFeature_WriteAnnotation feature support */ virtual void addToGroup(const U2DataId& groupId, const U2DataId& annotationId, U2OpStatus& os) = 0; /** Removes annotation from the specified group If annotation belongs to no group, it is removed Requires: U2DbiFeature_WriteAnnotation feature support */ virtual void removeFromGroup(const U2DataId& groupId, const U2DataId& annotationId, U2OpStatus& os) = 0; }; } //namespace #endif ugene-1.9.8/src/include/U2Core/GObjectTypes.h0000644000175000017500000000007511651544335017347 0ustar ilyailya#include "../../corelibs/U2Core/src/gobjects/GObjectTypes.h" ugene-1.9.8/src/include/U2Core/DNAChromatogramObject.h0000644000175000017500000000010611651544335021075 0ustar ilyailya#include "../../corelibs/U2Core/src/gobjects/DNAChromatogramObject.h" ugene-1.9.8/src/include/U2Core/AnnotationSelection.h0000644000175000017500000000010511651544335020757 0ustar ilyailya#include "../../corelibs/U2Core/src/selection/AnnotationSelection.h" ugene-1.9.8/src/include/U2Core/TextObject.h0000644000175000017500000000007311651544335017056 0ustar ilyailya#include "../../corelibs/U2Core/src/gobjects/TextObject.h" ugene-1.9.8/src/include/U2Core/ReverseSequenceTask.h0000644000175000017500000000010111651544335020722 0ustar ilyailya#include "../../corelibs/U2Core/src/tasks/ReverseSequenceTask.h" ugene-1.9.8/src/include/U2Core/MAlignmentInfo.h0000644000175000017500000000007711651544335017656 0ustar ilyailya#include "../../corelibs/U2Core/src/datatype/MAlignmentInfo.h" ugene-1.9.8/src/include/U2Core/DocumentUtils.h0000644000175000017500000000007411651544335017603 0ustar ilyailya#include "../../corelibs/U2Core/src/models/DocumentUtils.h" ugene-1.9.8/src/include/U2Core/U2SafePoints.h0000644000175000017500000000764711651544335017303 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ /** A framework to check, trace and recover from error situation in release mode. The logic is similar to usual assertions in debug mode but in release mode the check is performed and if not passed - the error message is dumped to log. This log can be analyzed and sent as a part of crash handler report NOTE: all checks below work in release mode. Be careful not to make code slow! */ #ifndef _U2_SAFE_POINTS_ #define _U2_SAFE_POINTS_ #include #include /** Recover utility. Must be used when code tries to recover from invalid internal state by returning from the method some default value. Traces the message to log. Asserts in debug mode. Warning: never use this function as a simple check since it stops application execution in debug mode use CHECK_OP instead */ #define SAFE_POINT(condition, message, result) \ if (!(condition)) { \ coreLog.error(QString("Trying to recover from error: %1 at %2:%3").arg(message).arg(__FILE__).arg(__LINE__)); \ assert(condition); \ return result; \ } \ /** Recover utility. Must be used when code tries to recover from invalid internal state by returning from the method some default value. Dumps the message to the error-level log. Asserts in debug mode. Warning: never use this function as a simple check since it stops application execution in debug mode use CHECK_OP instead */ #define SAFE_POINT_OP(os, result) \ if (os.hasError()) { \ coreLog.error(QString("Trying to recover from error: %1 at %2:%3").arg(os.getError()).arg(__FILE__).arg(__LINE__)); \ assert(0); \ return result; \ } \ /** FAIL utility. Same as SAFE_POINT but uses unconditional fail. Can be used in code that must be unreachable */ #define FAIL(message, result) \ coreLog.error(QString("Trying to recover from error: %1 at %2:%3").arg(message).arg(__FILE__).arg(__LINE__)); \ assert(0); \ return result; \ /** Checks condition is false and returns the result if it is Code style hint: use CHECK macro only to make error processing more compact but not all if {return;} patterns ! */ #define CHECK(condition, result) \ if (!condition) { \ return result; \ } /** Checks condition is false and returns the result if it is. Before the result is returned the 'extraOp' operation is performed (for example logging) Code style hint: use CHECK macro only to make error processing more compact but not all if {return;} patterns ! */ #define CHECK_EXT(condition, extraOp, result) \ if (!condition) { \ extraOp; \ return result; \ } /** Checks that operation is neither not failed nor canceled and returns the result if it does */ #define CHECK_OP(os, result) CHECK(!os.isCoR(), result) /** Checks that operation is neither failed nor canceled and returns the result if it does. Before the result is returned the 'extraOp' operation is performed (for example logging) */ #define CHECK_OP_EXT(os, extraOp, result) CHECK_EXT(!(os.isCoR()), extraOp, result) #endif ugene-1.9.8/src/include/U2Core/SelectionTypes.h0000644000175000017500000000010011651544335017744 0ustar ilyailya#include "../../corelibs/U2Core/src/selection/SelectionTypes.h" ugene-1.9.8/src/include/U2Core/Task.h0000644000175000017500000000006411651544335015705 0ustar ilyailya#include "../../corelibs/U2Core/src/globals/Task.h" ugene-1.9.8/src/include/U2Core/BaseDocumentFormats.h0000644000175000017500000000010311651544335020702 0ustar ilyailya#include "../../corelibs/U2Core/src/globals/BaseDocumentFormats.h" ugene-1.9.8/src/include/U2Core/UIndex.h0000644000175000017500000000006711651544335016202 0ustar ilyailya#include "../../corelibs/U2Core/src/datatype/UIndex.h" ugene-1.9.8/src/include/U2Core/VFSAdapter.h0000644000175000017500000000006511651544335016743 0ustar ilyailya#include "../../corelibs/U2Core/src/io/VFSAdapter.h" ugene-1.9.8/src/include/U2Core/AppSettings.h0000644000175000017500000000007311651544335017244 0ustar ilyailya#include "../../corelibs/U2Core/src/globals/AppSettings.h" ugene-1.9.8/src/include/U2Core/FeatureColors.h0000644000175000017500000000007611651544335017563 0ustar ilyailya#include "../../corelibs/U2Core/src/datatype/FeatureColors.h" ugene-1.9.8/src/include/U2Core/ServiceTypes.h0000644000175000017500000000007411651544335017431 0ustar ilyailya#include "../../corelibs/U2Core/src/globals/ServiceTypes.h" ugene-1.9.8/src/include/U2Core/SMatrix.h0000644000175000017500000000007011651544335016367 0ustar ilyailya#include "../../corelibs/U2Core/src/datatype/SMatrix.h" ugene-1.9.8/src/include/U2Core/DNAChromatogram.h0000644000175000017500000000010011651544335017740 0ustar ilyailya#include "../../corelibs/U2Core/src/datatype/DNAChromatogram.h" ugene-1.9.8/src/include/U2Core/AppGlobalObject.h0000644000175000017500000000007711651544335017777 0ustar ilyailya#include "../../corelibs/U2Core/src/globals/AppGlobalObject.h" ugene-1.9.8/src/include/U2Core/GObjectReference.h0000644000175000017500000000007711651544335020143 0ustar ilyailya#include "../../corelibs/U2Core/src/models/GObjectReference.h" ugene-1.9.8/src/include/U2Core/SelectionModel.h0000644000175000017500000000010011651544335017700 0ustar ilyailya#include "../../corelibs/U2Core/src/selection/SelectionModel.h" ugene-1.9.8/src/include/U2Core/U2CrossDatabaseReferenceDbi.h0000644000175000017500000000354611651544335022176 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_CDR_DBI_H_ #define _U2_CDR_DBI_H_ #include #include namespace U2 { class U2CORE_EXPORT U2CrossDatabaseReferenceDbi : public U2ChildDbi { protected: U2CrossDatabaseReferenceDbi(U2Dbi* rootDbi) : U2ChildDbi(rootDbi){} public: /** Adds new remote object to database. Sets local object id assigned to the new value Requires: U2DbiFeature_WriteCrossDatabaseReferences */ virtual void createCrossReference(U2CrossDatabaseReference& reference, U2OpStatus& os) = 0; /** Loads remote object information from DB Requires: U2DbiFeature_ReadCrossDatabaseReferences */ virtual U2CrossDatabaseReference getCrossReference(const U2DataId& objectId, U2OpStatus& os) = 0; /** Updates all fields of cross database reference object Requires: U2DbiFeature_WriteCrossDatabaseReferences */ virtual void updateCrossReference(const U2CrossDatabaseReference& reference, U2OpStatus& os) = 0; }; } //namespace #endif ugene-1.9.8/src/include/U2Core/DocumentModel.h0000644000175000017500000000007411651544335017543 0ustar ilyailya#include "../../corelibs/U2Core/src/models/DocumentModel.h" ugene-1.9.8/src/include/U2Core/TaskSignalMapper.h0000644000175000017500000000007611651544335020213 0ustar ilyailya#include "../../corelibs/U2Core/src/tasks/TaskSignalMapper.h" ugene-1.9.8/src/include/U2Core/UserApplicationsSettings.h0000644000175000017500000000011011651544335022001 0ustar ilyailya#include "../../corelibs/U2Core/src/globals/UserApplicationsSettings.h" ugene-1.9.8/src/include/U2Core/GHints.h0000644000175000017500000000006511651544335016200 0ustar ilyailya#include "../../corelibs/U2Core/src/models/GHints.h" ugene-1.9.8/src/include/U2Core/GUrlUtils.h0000644000175000017500000000006411651544335016675 0ustar ilyailya#include "../../corelibs/U2Core/src/io/GUrlUtils.h" ugene-1.9.8/src/include/U2Core/CMDLineCoreOptions.h0000644000175000017500000000010211651544335020374 0ustar ilyailya#include "../../corelibs/U2Core/src/cmdline/CMDLineCoreOptions.h" ugene-1.9.8/src/include/U2Core/U2Sequence.h0000644000175000017500000000304411651544335016763 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_SEQUENCE_H_ #define _U2_SEQUENCE_H_ #include #include #include namespace U2 { /** Sequence representation. 'Length' field contains the overall length of all sequence parts. */ class U2CORE_EXPORT U2Sequence : public U2Object { public: U2Sequence() : length (0), circular(false){} U2Sequence(U2DataId id, QString dbId, qint64 version) : U2Object(id, dbId, version), length(0){} /** Sequence alphabet id */ U2AlphabetId alphabet; /** Length of the sequence */ qint64 length; /** A flag to mark that sequence is circular */ bool circular; }; } // namespace #endif ugene-1.9.8/src/include/U2Core/GObjectSelection.h0000644000175000017500000000010211651544335020157 0ustar ilyailya#include "../../corelibs/U2Core/src/selection/GObjectSelection.h" ugene-1.9.8/src/include/U2Core/U2MsaDbi.h0000644000175000017500000001173711651544335016362 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_MSA_DBI_H_ #define _U2_MSA_DBI_H_ #include #include #include namespace U2 { /** An interface to obtain access to multiple sequence alignment */ class U2CORE_EXPORT U2MsaDbi : public U2ChildDbi { protected: U2MsaDbi(U2Dbi* rootDbi) : U2ChildDbi(rootDbi) {} public: /** Reads Msa objects by id */ virtual U2Msa getMsaObject(const U2DataId& id, U2OpStatus& os) = 0; /** Returns number of sequences in MSA*/ virtual qint64 getSequencesCount(const U2DataId& msaId, U2OpStatus& os) = 0; /** Returns region of Msa rows. Total number of MSA rows is equal to number of sequences in MSA. The 'firstRow' and 'numRows' must specify valid subset of rows in the alignment. */ virtual QList getRows(const U2DataId& msaId, qint32 firstRow, qint32 numRows, U2OpStatus& os) = 0; /** Return number of sequences in alignment that intersect given coord. 'Intersect' here means that first non gap character is <= coord <= last non gap character. The coord should be a valid coordinate within alignment bounds, i.e. non-negative and less than alignment length. */ virtual qint32 countSequencesAt(const U2DataId& msaId, qint64 coord, U2OpStatus& os) = 0; /** Return 'count' sequences starting with 'offset' that intersect given coordinate. The coord should be a valid coordinate within alignment bounds, i.e. non-negative and less than alignment length. The 'offset' and 'count' can be arbitrarily large but should not be negative. Also, 'count' can have special value 'DBI_NO_LIMIT'. */ virtual QList getSequencesAt(const U2DataId& msaId, qint64 coord, qint32 offset, qint32 count, U2OpStatus& os) = 0; /** Return number of sequences in alignment that intersect given region. The region should be a valid region within alignment bounds, i.e. non-negative and less than alignment length. 'Intersect' here means that first non gap character is <= coord <= last non gap character */ virtual qint32 countSequencesAt(const U2DataId& msaId, const U2Region& r, U2OpStatus& os) = 0; /** Return 'count' sequences starting with 'offset' that intersect given region. The region should be a valid region within alignment bounds, i.e. non-negative and less than alignment length. The 'offset' and 'count' can be arbitrarily large but should not be negative. Also, 'count' can have special value 'DBI_NO_LIMIT'. */ virtual QList getSequencesAt(const U2DataId& msaId, const U2Region& r, qint32 offset, qint32 count, U2OpStatus& os) = 0; /** Return number of sequences in alignment that that have non-gap character at the given coord. The coord should be a valid coordinate within alignment bounds, i.e. non-negative and less than alignment length.*/ virtual qint32 countSequencesWithoutGapAt(const U2DataId& msaId, qint64 coord, U2OpStatus& os) = 0; /** Return 'count' sequence starting with 'offset' alignment that that have non-gap character at the given coord. The coord should be a valid coordinate within alignment bounds, i.e. non-negative and less than alignment length. The 'offset' and 'count' can be arbitrarily large but should not be negative. Also, 'count' can have special value 'DBI_NO_LIMIT'. */ virtual QList getSequencesWithoutGapAt(const U2DataId& msaId, qint64 coord, qint32 offset, qint32 count, U2OpStatus& os) = 0; /** Creates new empty Msa object Requires: U2DbiFeature_WriteMsa feature support */ virtual void createMsaObject(U2Msa& msa, const QString& folder, U2OpStatus& os) = 0; /** Removes sequences from MSA Automatically removes affected sequences that are not anymore located in some folder nor Msa object Requires: U2DbiFeature_WriteMsa feature support */ virtual void removeSequences(U2Msa& msa, const QList sequenceIds, U2OpStatus& os) = 0; /** Adds sequences to MSA Requires: U2DbiFeature_WriteMsa feature support */ virtual void addSequences(U2Msa& msa, const QList& rows, U2OpStatus& os) = 0; }; } //namespace #endif ugene-1.9.8/src/include/U2Core/DNAInfo.h0000644000175000017500000000007011651544335016216 0ustar ilyailya#include "../../corelibs/U2Core/src/datatype/DNAInfo.h" ugene-1.9.8/src/include/U2Core/U2Range.h0000644000175000017500000000267211651544335016255 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_RANGE_H_ #define _U2_RANGE_H_ #include namespace U2 { /** Range or interval or values Usually used by functions that must return not exact value, but interval: [min, max] */ template class U2Range { public: U2Range(T _minValue = 0, T _maxValue = 0) : minValue(_minValue), maxValue(_maxValue){} T minValue; T maxValue; }; template U2Range operator +(const U2Range& r1, const U2Range& r2) { U2Range result(qMin(r1.minValue, r2.minValue), qMax(r1.maxValue, r2.maxValue)); return result; } }//namespace #endif ugene-1.9.8/src/include/U2Core/U2AttributeDbi.h0000644000175000017500000001174711651544335017606 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_ATTR_DBI_H_ #define _U2_ATTR_DBI_H_ #include #include #include namespace U2 { /** A configuration for sorting by attribute operation */ class U2CORE_EXPORT U2DbiSortConfig { public: U2DbiSortConfig() : ascending(true) {} /** Sort column*/ QString sortColumnName; /** Type of the sort column: Integer, Real or String attribute type*/ U2DataType columnType; /** Tells if sorting is ascending or descending */ bool ascending; /** Folder to localize sorting. If empty all folders are processed */ QString folder; }; /** An interface to obtain access to object attributes */ class U2CORE_EXPORT U2AttributeDbi: public U2ChildDbi { protected: U2AttributeDbi(U2Dbi* rootDbi) : U2ChildDbi(rootDbi){} public: /** Returns all attribute names available in the database */ virtual QStringList getAvailableAttributeNames(U2OpStatus& os) = 0; /** Returns ids of all attributes with a name 'attributeName' for the object referenced by 'objectId'. If 'attributeName' is empty returns all object attributes. */ virtual QList getObjectAttributes(const U2DataId& objectId, const QString& attributeName, U2OpStatus& os) = 0; /** Returns ids of all attributes with a childId 'childId' and a name 'attributeName' for the object referenced by 'objectId'. If 'attributeName' is empty returns ids of all object attributes with a specified childId. */ virtual QList getObjectPairAttributes(const U2DataId& objectId, const U2DataId& childId, const QString& attributeName, U2OpStatus& os) = 0; /** Loads integer attribute by id. If there is no integer attribute with the specified id returns */ virtual U2IntegerAttribute getIntegerAttribute(const U2DataId& attributeId, U2OpStatus& os) = 0; /** Loads real attribute by id */ virtual U2RealAttribute getRealAttribute(const U2DataId& attributeId, U2OpStatus& os) = 0; /** Loads String attribute by id */ virtual U2StringAttribute getStringAttribute(const U2DataId& attributeId, U2OpStatus& os) = 0; /** Loads byte attribute by id */ virtual U2ByteArrayAttribute getByteArrayAttribute(const U2DataId& attributeId, U2OpStatus& os) = 0; /** Sorts all objects in database according to U2DbiSortConfig provided Requires U2DbiFeature_AttributeSorting support */ virtual QList sort(const U2DbiSortConfig& sc, qint64 offset, qint64 count, U2OpStatus& os) = 0; /** Removes attributes from database Requires U2DbiFeature_WriteAttribute feature support */ virtual void removeAttributes(const QList& attributeIds, U2OpStatus& os) = 0; /** Removes all attributes associated with the object Requires U2DbiFeature_WriteAttribute feature support */ virtual void removeObjectAttributes(const U2DataId& objectId, U2OpStatus& os) = 0; /** Creates int64 attribute in database. ObjectId must be already set in attribute and present in the same database Requires U2DbiFeature_WriteAttribute feature support */ virtual void createIntegerAttribute(U2IntegerAttribute& a, U2OpStatus& os) = 0; /** Creates real64 attribute in database. ObjectId must be already set in attribute and present in the same database Requires U2DbiFeature_WriteAttribute feature support */ virtual void createRealAttribute(U2RealAttribute& a, U2OpStatus& os) = 0; /** Creates String attribute in database. ObjectId must be already set in attribute and present in the same database Requires U2DbiFeature_WriteAttribute feature support */ virtual void createStringAttribute(U2StringAttribute& a, U2OpStatus& os) = 0; /** Creates Byte attribute in database. ObjectId must be already set in attribute and present in the same database Requires U2DbiFeature_WriteAttribute feature support */ virtual void createByteArrayAttribute(U2ByteArrayAttribute& a, U2OpStatus& os) = 0; }; } //namespace #endif ugene-1.9.8/src/include/U2Core/RemoveAnnotationsTask.h0000644000175000017500000000010311651544335021273 0ustar ilyailya#include "../../corelibs/U2Core/src/tasks/RemoveAnnotationsTask.h" ugene-1.9.8/src/include/U2Core/U2Assembly.h0000644000175000017500000001356511651544335017003 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_ASSEMBLY_H_ #define _U2_ASSEMBLY_H_ #include #include #include namespace U2 { /** * CIGAR string operation. * CIGAR string represents complex ins/del model for short-reads. * * Meanings of the operations are the following: * * - M - 'alignment match' * Either match or mismatch to reference. * * - I - 'insertion' * Insertion to the reference. Residues marked as 'I' must be skipped when * counting 'real' read length and must be skipped when read is aligned to * reference. * * - D - 'deletion' * Deletion from the reference. Gaps must be inserted to the read when read * is aligned to reference. Deleted regions must be added to the 'real' * read length. * * - N - 'skip' * Skipped region from the reference. Skips behave exactly as deletions, * however have different biological meaning: they make sense _only_ in * mRNA-to-genome alignment where represent an intron. * * - S - 'soft clipping' * Regions which do not match to the reference, behave exactly as insertions. * Must be located at the start or the end of the read (see * SAM spec and CigarValidator) * * - H - 'hard clipping' * Regions which do not match to the reference, skipped by hardware (not * present in read sequence). Hard clipping does not affects read length or * visualization * * - P - 'padding' (TODO) * Silent Deletion from padded reference. Someday we should find out how to * handle this. Padding does not affect read length. * * - = - 'sequence match' * Exact match to reference. * * - X - 'sequence mismatch' * Mismatch to reference. * * See also: U2AssemblyUtils::getCigarExtraLength(), ShortReadIterator. */ enum U2CigarOp { U2CigarOp_Invalid = 0, U2CigarOp_D = 1, // deleted U2CigarOp_I = 2, // inserted U2CigarOp_H = 3, // hard-clipped U2CigarOp_M = 4, // alignment match U2CigarOp_N = 5, // skipped U2CigarOp_P = 6, // padded U2CigarOp_S = 7, // soft-clipped U2CigarOp_EQ = 8, // sequence match U2CigarOp_X = 9, // sequence mismatch }; /** CIGAR token: operation + count */ class U2CORE_EXPORT U2CigarToken { public: U2CigarToken() : op (U2CigarOp_M), count(1){} U2CigarToken(U2CigarOp _op, int _count) : op(_op), count(_count){} U2CigarOp op; int count; }; /** assembly read flags */ enum ReadFlag { None = 0, Fragmented = 1 << 0, FragmentsAligned = 1 << 1, Unmapped = 1 << 2, NextUnmapped = 1 << 3, Reverse = 1 << 4, NextReverse = 1 << 5, FirstInTemplate = 1 << 6, LastInTemplate = 1 << 7, SecondaryAlignment = 1 << 8, FailsChecks = 1 << 9, Duplicate = 1 << 10, DnaExtAlphabet = 1 << 16 }; /** Utility class to work with flags */ class ReadFlagsUtils { public: static bool isExtendedAlphabet(qint64 flags) { return flags & DnaExtAlphabet; } static bool isComplementaryRead(qint64 flags) { return flags & Reverse; } static bool isPairedRead(qint64 flags) { return flags & Fragmented; } static bool isUnmappedRead(qint64 flags) { return flags & Unmapped; } }; /** Row of assembly: sequence, leftmost position and CIGAR */ class U2CORE_EXPORT U2AssemblyReadData : public U2Entity, public QSharedData { public: U2AssemblyReadData() : leftmostPos(0), effectiveLen(0), packedViewRow(0), mappingQuality(255){} /** Name of the read, ASCII string */ QByteArray name; /** Left-most position of the read */ qint64 leftmostPos; /** Length of the read with CIGAR affect applied */ qint64 effectiveLen; /** Position of the read in packed view */ qint64 packedViewRow; /** CIGAR info for the read */ QList cigar; /** Sequence of the read. The array is not empty only if sequence is embedded into the read */ QByteArray readSequence; /** Quality string */ QByteArray quality; /** Mapping quality */ quint8 mappingQuality; /** Read flags */ qint64 flags; }; typedef QSharedDataPointer U2AssemblyRead; /** Assembly representation */ class U2CORE_EXPORT U2Assembly : public U2Object { public: U2Assembly() {} U2Assembly(U2DataId id, QString dbId, qint64 version) : U2Object(id, dbId, version) {} U2DataId referenceId; }; /** Statistics information collected during the reads packing algorithm */ class U2AssemblyPackStat { public: U2AssemblyPackStat() : maxProw(0), readsCount(0) {} /** Maximum packed row value after pack algorithm */ int maxProw; /** Number of reads packed */ qint64 readsCount; }; /** Statistics information collected during the reads packing algorithm */ class U2AssemblyCoverageStat { public: U2AssemblyCoverageStat() {} QVector< U2Range > coverage; }; } //namespace #endif ugene-1.9.8/src/include/U2Core/Log.h0000644000175000017500000000006311651544335015523 0ustar ilyailya#include "../../corelibs/U2Core/src/globals/Log.h" ugene-1.9.8/src/include/U2Core/U2DbiRegistry.h0000644000175000017500000000422611651544335017445 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_DBI_REGISTRY_H_ #define _U2_DBI_REGISTRY_H_ #include #include #include namespace U2 { class U2DbiPool; /** Keep all DBI types registered in the system */ class U2CORE_EXPORT U2DbiRegistry : public QObject { Q_OBJECT public: U2DbiRegistry(QObject *parent = NULL); ~U2DbiRegistry(); virtual bool registerDbiFactory(U2DbiFactory *factory); virtual QList getRegisteredDbiFactories() const; virtual U2DbiFactory *getDbiFactoryById(U2DbiFactoryId id) const; U2DbiPool* getGlobalDbiPool() const {return pool;} private: QHash factories; U2DbiPool* pool; }; /** Class to access to DBI connections Roles: creates new DBIs on user request track connection live range (using ref counters) closes unused DBIs */ class U2CORE_EXPORT U2DbiPool : public QObject { Q_OBJECT public: U2DbiPool(QObject* p = NULL); U2Dbi* openDbi(U2DbiFactoryId id, const QString& url, bool create, U2OpStatus& os); void addRef(U2Dbi * dbi, U2OpStatus & os); void releaseDbi(U2Dbi* dbi, U2OpStatus& os); private: QHash dbiByUrl; QHash dbiCountersByUrl; QMutex lock; }; } // namespace U2 #endif // _U2_DBI_REGISTRY_H_ ugene-1.9.8/src/include/U2Core/AddSequencesToAlignmentTask.h0000644000175000017500000000011111651544335022325 0ustar ilyailya#include "../../corelibs/U2Core/src/tasks/AddSequencesToAlignmentTask.h" ugene-1.9.8/src/include/U2Core/IOAdapter.h0000644000175000017500000000006411651544335016613 0ustar ilyailya#include "../../corelibs/U2Core/src/io/IOAdapter.h" ugene-1.9.8/src/include/U2Core/LRegionsSelection.h0000644000175000017500000000010311651544335020365 0ustar ilyailya#include "../../corelibs/U2Core/src/selection/LRegionsSelection.h" ugene-1.9.8/src/include/U2Core/DocumentImport.h0000644000175000017500000000007411651544335017755 0ustar ilyailya#include "../../corelibs/U2Core/src/models/DocumentImport.h"ugene-1.9.8/src/include/U2Core/CMDLineRegistry.h0000644000175000017500000000007711651544335017753 0ustar ilyailya#include "../../corelibs/U2Core/src/cmdline/CMDLineRegistry.h" ugene-1.9.8/src/include/U2Core/Identifiable.h0000644000175000017500000000007411651544335017363 0ustar ilyailya#include "../../corelibs/U2Core/src/globals/Identifiable.h" ugene-1.9.8/src/include/U2Core/Settings.h0000644000175000017500000000007011651544335016600 0ustar ilyailya#include "../../corelibs/U2Core/src/globals/Settings.h" ugene-1.9.8/src/include/U2Core/PluginModel.h0000644000175000017500000000007311651544335017222 0ustar ilyailya#include "../../corelibs/U2Core/src/globals/PluginModel.h" ugene-1.9.8/src/include/U2Core/UnloadedObject.h0000644000175000017500000000007711651544335017671 0ustar ilyailya#include "../../corelibs/U2Core/src/gobjects/UnloadedObject.h" ugene-1.9.8/src/include/U2Core/TextUtils.h0000644000175000017500000000007311651544335016750 0ustar ilyailya#include "../../corelibs/U2Core/src/util_text/TextUtils.h" ugene-1.9.8/src/include/U2Core/ExtractAnnotatedRegionTask.h0000644000175000017500000000011011651544335022232 0ustar ilyailya#include "../../corelibs/U2Core/src/tasks/ExtractAnnotatedRegionTask.h" ugene-1.9.8/src/include/U2Core/RingBuffer.h0000644000175000017500000000006511651544335017035 0ustar ilyailya#include "../../corelibs/U2Core/src/io/RingBuffer.h" ugene-1.9.8/src/include/U2Core/SelectionUtils.h0000644000175000017500000000010011651544335017740 0ustar ilyailya#include "../../corelibs/U2Core/src/selection/SelectionUtils.h" ugene-1.9.8/src/include/U2Core/Vector3D.h0000644000175000017500000000007111651544335016432 0ustar ilyailya#include "../../corelibs/U2Core/src/datatype/Vector3D.h" ugene-1.9.8/src/include/U2Core/StateLockableDataModel.h0000644000175000017500000000010511651544335021267 0ustar ilyailya#include "../../corelibs/U2Core/src/models/StateLockableDataModel.h" ugene-1.9.8/src/include/U2Core/Version.h0000644000175000017500000000006711651544335016433 0ustar ilyailya#include "../../corelibs/U2Core/src/globals/Version.h" ugene-1.9.8/src/include/U2Core/IdRegistry.h0000644000175000017500000000007211651544335017067 0ustar ilyailya#include "../../corelibs/U2Core/src/globals/IdRegistry.h" ugene-1.9.8/src/include/U2Core/Timer.h0000644000175000017500000000006511651544335016064 0ustar ilyailya#include "../../corelibs/U2Core/src/globals/Timer.h" ugene-1.9.8/src/include/U2Core/DNASequenceObject.h0000644000175000017500000000010211651544335020216 0ustar ilyailya#include "../../corelibs/U2Core/src/gobjects/DNASequenceObject.h" ugene-1.9.8/src/include/U2Core/ProjectService.h0000644000175000017500000000007611651544335017735 0ustar ilyailya#include "../../corelibs/U2Core/src/globals/ProjectService.h" ugene-1.9.8/src/include/U2Core/FailTask.h0000644000175000017500000000006611651544335016503 0ustar ilyailya#include "../../corelibs/U2Core/src/tasks/FailTask.h" ugene-1.9.8/src/include/U2Core/AddDocumentTask.h0000644000175000017500000000007511651544335020017 0ustar ilyailya#include "../../corelibs/U2Core/src/tasks/AddDocumentTask.h" ugene-1.9.8/src/include/U2Core/CreateFileIndexTask.h0000644000175000017500000000010111651544335020611 0ustar ilyailya#include "../../corelibs/U2Core/src/tasks/CreateFileIndexTask.h" ugene-1.9.8/src/include/U2Core/U2Type.h0000644000175000017500000001260711651544335016141 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_TYPE_H_ #define _U2_TYPE_H_ #include namespace U2 { /** UGENE built-in data-types Note: unsigned used to reveal all possible math ops with it. U2DataType - data types supported by U2Dbi U2DataId - object ids associated with Data by U2Dbi. Note that U2DataId == empty check must be suppoted by DBI to check empty fields. */ typedef quint16 U2DataType; typedef QByteArray U2DataId; /** ID of the DBI Factory. Defines type of the DBI driver. Examples: 'sqlite', 'mysql', 'fasta'.... */ typedef QString U2DbiFactoryId; /** ID of the DBI. Points to DBI instance inside of the given DBI factory Usually is an URL or the DBI file/resource */ typedef QString U2DbiId; /** Built in types Note: Maximum value used for type must be <=4096 */ class U2CORE_EXPORT U2Type { public: /** Type is unknown. Default value. */ static const U2DataType Unknown = 0; /** Object types */ static const U2DataType Sequence = 1; static const U2DataType Msa = 2; static const U2DataType PhyTree = 3; static const U2DataType Assembly = 4; static const U2DataType CrossDatabaseReference = 999; /** SCO (non-object, non-root) types */ static const U2DataType Annotation = 1000; static const U2DataType AnnotationGroup = 1001; /** Assembly read */ static const U2DataType AssemblyRead = 1100; /** MSA */ static const U2DataType MsaRow = 1200; /** Attribute types */ static const U2DataType AttributeInteger = 2001; static const U2DataType AttributeReal = 2002; static const U2DataType AttributeString = 2003; static const U2DataType AttributeByteArray = 2004; static bool isObjectType(U2DataType type) {return type > 0 && type < 999;} static bool isAttributeType(U2DataType type) {return type >=2000 && type < 2100;} }; /** Cross database data reference */ class U2CORE_EXPORT U2DataRef { public: U2DataRef() {} U2DataRef(const QString& _dbiId, const U2DataId& _entityId, const U2DbiFactoryId& fid) : dbiId(_dbiId),entityId(_entityId), factoryId(fid){} /** database id */ QString dbiId; /** DB local data reference */ U2DataId entityId; /** Object version number this reference is valid for */ qint64 version; /** Type of the dbi driver (factory)*/ U2DbiFactoryId factoryId; }; /** Base class for all data types that can be referenced by some ID */ class U2CORE_EXPORT U2Entity { public: U2Entity(){} U2Entity(U2DataId _id) : id(_id){} virtual ~U2Entity(){} U2DataId id; }; /** Base marker class for all First-class-objects stored in the database */ class U2CORE_EXPORT U2Object : public U2Entity { public: U2Object() : version(0){} U2Object(U2DataId id, const QString& _dbId, qint64 v) : U2Entity(id), dbiId(_dbId), version(v) {} /** Source of the object: database id */ QString dbiId; /** Version of the object. Same as modification count of the object */ qint64 version; /** The name of the object shown to user. Any reasonably short text */ QString visualName; }; /** If database keeps annotations/attributes for data entity stored in another database U2CrossDatabaseReference used as a parent object for all local data */ class U2CORE_EXPORT U2CrossDatabaseReference : public U2Object { public: U2CrossDatabaseReference() {} U2CrossDatabaseReference(U2DataId id, QString dbId, qint64 version) : U2Object(id, dbId, version) {} // remote data element id; U2DataRef dataRef; }; /** Template class for DBI iterators */ template class U2DbiIterator { public: virtual ~U2DbiIterator(){} /** returns true if there are more reads to iterate*/ virtual bool hasNext() = 0; /** returns next read and shifts one element*/ virtual T next() = 0; /** returns next read without shifting*/ virtual T peek() = 0; }; class U2Strand { public: enum Direction { Direct = 1, Complementary = -1 }; U2Strand() : value(Direct) {} U2Strand(Direction val) {value = val == Complementary ? Complementary : Direct;} bool isDirect() const { return value == Direct;} bool isCompementary() const { return value == Complementary;} bool operator==(const U2Strand& s) const {return value == s.value;} bool operator!=(const U2Strand& s) const {return value != s.value;} private: int value; }; } //namespace #endif ugene-1.9.8/src/include/U2Core/SaveDocumentTask.h0000644000175000017500000000007611651544335020226 0ustar ilyailya#include "../../corelibs/U2Core/src/tasks/SaveDocumentTask.h" ugene-1.9.8/src/include/U2Core/SequenceUtils.h0000644000175000017500000000010411651544335017567 0ustar ilyailya#include "../../corelibs/U2Core/src/util_algorithm/SequenceUtils.h" ugene-1.9.8/src/include/U2Core/BioStruct3D.h0000644000175000017500000000007411651544335017111 0ustar ilyailya#include "../../corelibs/U2Core/src/datatype/BioStruct3D.h" ugene-1.9.8/src/include/U2Core/ZlibAdapter.h0000644000175000017500000000006611651544335017206 0ustar ilyailya#include "../../corelibs/U2Core/src/io/ZlibAdapter.h" ugene-1.9.8/src/include/U2Core/AppContext.h0000644000175000017500000000007211651544335017067 0ustar ilyailya#include "../../corelibs/U2Core/src/globals/AppContext.h" ugene-1.9.8/src/include/U2Core/DNATranslationImpl.h0000644000175000017500000000010311651544335020440 0ustar ilyailya#include "../../corelibs/U2Core/src/datatype/DNATranslationImpl.h" ugene-1.9.8/src/include/U2Core/PhyTreeObject.h0000644000175000017500000000007611651544335017515 0ustar ilyailya#include "../../corelibs/U2Core/src/gobjects/PhyTreeObject.h" ugene-1.9.8/src/include/U2Core/PFMatrix.h0000644000175000017500000000007111651544335016473 0ustar ilyailya#include "../../corelibs/U2Core/src/datatype/PFMatrix.h" ugene-1.9.8/src/include/U2Core/U2OpStatus.h0000644000175000017500000000340111651544335016772 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_OPSTATUS_H_ #define _U2_OPSTATUS_H_ #include namespace U2 { /** Operation status. If operation failed, the reason is written in 'error' field If operation hangs, it can be canceled with 'cancelFlag' */ class U2CORE_EXPORT U2OpStatus { public: virtual ~U2OpStatus(){} virtual void setError(const QString & err) = 0; virtual QString getError() const = 0; virtual bool hasError() const = 0; virtual bool isCanceled() const = 0; virtual void setCanceled(bool v) = 0; virtual bool isCoR() const {return isCanceled() || hasError();} /** Returns progress value in percents. Special value '-1' is used to indicate 'No info' progress state */ virtual int getProgress() const = 0; virtual void setProgress(int v) = 0; virtual QString getDescription() const = 0; virtual void setDescription(const QString& desc) = 0; }; } //namespace #endif ugene-1.9.8/src/include/U2Core/Counter.h0000644000175000017500000000006711651544335016425 0ustar ilyailya#include "../../corelibs/U2Core/src/globals/Counter.h" ugene-1.9.8/src/include/U2Core/PWMatrix.h0000644000175000017500000000007111651544335016514 0ustar ilyailya#include "../../corelibs/U2Core/src/datatype/PWMatrix.h" ugene-1.9.8/src/include/U2Core/DataBaseRegistry.h0000644000175000017500000000010011651544335020167 0ustar ilyailya#include "../../corelibs/U2Core/src/globals/DataBaseRegistry.h" ugene-1.9.8/src/include/U2Core/LRegion.h0000644000175000017500000000007011651544335016337 0ustar ilyailya#include "../../corelibs/U2Core/src/datatype/LRegion.h" ugene-1.9.8/src/include/U2Core/GetDocumentFromIndexTask.h0000644000175000017500000000010611651544335021655 0ustar ilyailya#include "../../corelibs/U2Core/src/tasks/GetDocumentFromIndexTask.h" ugene-1.9.8/src/include/U2Core/U2AssemblyUtils.h0000644000175000017500000000523411651544335020016 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_ASSEMBLY_UTILS_H_ #define _U2_ASSEMBLY_UTILS_H_ #include namespace U2 { /** Predefined region - acts as hint for a function that whole assembly must be processed */ #define U2_ASSEMBLY_REGION_MAX U2Region(0, LLONG_MAX) /** Predefined integer attribute for coverage First 4 bytes - lower coverage bound Last 4 bytes - upper coverage bound */ #define U2_ASSEMBLY_COVERAGE_ATTRIBUTE_LOWER "assembly-coverage-1m" /** U2Assembly and related structures utility functions */ class U2CORE_EXPORT U2AssemblyUtils : public QObject { Q_OBJECT private: U2AssemblyUtils(){} public: /** Returns CIGAR operation for the given char, case insensitive If failed, error text is stored in 'err' */ static U2CigarOp char2Cigar(char c, QString& err); /** Returns char representation of the given CIGAR op */ static char cigar2Char(U2CigarOp op); /** Parses CIGAR string (SAM/BAM format specs) Returns the result as a set of U2CigarTokens. If parsing is failed, the fail reason is stored in 'err' parameter */ static QList parseCigar(const QByteArray& cigarString, QString& err); /** Returns string representation of the CIGAR */ static QByteArray cigar2String(const QList& cigar); /** Returns extra read length produced by CIGAR. Can be negative. */ static qint64 getCigarExtraLength(const QList& cigar); /** Returns read effective length: sequence length + CIGAR */ static qint64 getEffectiveReadLength(const U2AssemblyRead& read); /** Returns all characters that may appear in CIGAR string */ static QByteArray getCigarAlphabetChars(); }; } //namespace #endif ugene-1.9.8/src/include/U2Core/U2Msa.h0000644000175000017500000000352711651544335015741 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_MSA_H_ #define _U2_MSA_H_ #include namespace U2 { /** Gap model for Msa: for every sequence it keeps gaps map */ class U2CORE_EXPORT U2MsaGap { public: U2MsaGap() : offset(0), gap(0){} U2MsaGap(qint64 off, qint64 g) : offset(off), gap(g){} /** Offset of the gap in sequence*/ qint64 offset; /** number of gaps */ qint64 gap; }; /** Row of multiple alignment: gaps map and sequence id */ class U2CORE_EXPORT U2MsaRow { public: U2DataId rowId; U2DataId sequenceId; QList gaps; }; /** Multiple sequence alignment representation */ class U2CORE_EXPORT U2Msa : public U2Object { public: U2Msa(){} U2Msa(U2DataId id, QString dbId, qint64 version) : U2Object(id, dbId, version) {} /** Alignment alphabet. All sequence in alignment must have alphabet that fits into alignment alphabet */ U2AlphabetId alphabet; }; } //namespace #endif ugene-1.9.8/src/include/U2Core/U2AttributeUtils.h0000644000175000017500000000344311651544335020202 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_ATTRIBUTE_UTILS_H_ #define _U2_ATTRIBUTE_UTILS_H_ #include namespace U2 { class U2AttributeDbi; class U2OpStatus; /** U2Attribute utility functions */ class U2CORE_EXPORT U2AttributeUtils : public QObject { Q_OBJECT private: U2AttributeUtils(){} public: static qint64 findIntegerAttribute(U2AttributeDbi* adbi, const U2DataId& objectId, const QString& name, qint64 defaultVal, U2OpStatus& os); static double findRealAttribute(U2AttributeDbi* adbi, const U2DataId& objectId, const QString& name, double defaultVal, U2OpStatus& os); static QByteArray findByteArrayAttribute(U2AttributeDbi* adbi, const U2DataId& objectId, const QString& name, const QByteArray& defaultVal, U2OpStatus& os); static QString findStringAttribute(U2AttributeDbi* adbi, const U2DataId& objectId, const QString& name, const QString& defaultVal, U2OpStatus& os); }; } //namespace #endif ugene-1.9.8/src/include/U2Core/AddPartToSequenceTask.h0000644000175000017500000000010311651544335021133 0ustar ilyailya#include "../../corelibs/U2Core/src/tasks/AddPartToSequenceTask.h" ugene-1.9.8/src/include/U2Core/BioStruct3DObject.h0000644000175000017500000000010211651544335020230 0ustar ilyailya#include "../../corelibs/U2Core/src/gobjects/BioStruct3DObject.h" ugene-1.9.8/src/include/U2Core/DNATranslation.h0000644000175000017500000000007711651544335017630 0ustar ilyailya#include "../../corelibs/U2Core/src/datatype/DNATranslation.h" ugene-1.9.8/src/include/U2Core/AnnotationData.h0000644000175000017500000000007711651544335017713 0ustar ilyailya#include "../../corelibs/U2Core/src/datatype/AnnotationData.h" ugene-1.9.8/src/include/U2Core/TLSTask.h0000644000175000017500000000006511651544335016271 0ustar ilyailya#include "../../corelibs/U2Core/src/tasks/TLSTask.h" ugene-1.9.8/src/include/U2Core/MSAUtils.h0000644000175000017500000000007711651544335016450 0ustar ilyailya#include "../../corelibs/U2Core/src/util_algorithm/MSAUtils.h" ugene-1.9.8/src/include/U2Core/UIndexObject.h0000644000175000017500000000007511651544335017330 0ustar ilyailya#include "../../corelibs/U2Core/src/gobjects/UIndexObject.h" ugene-1.9.8/src/include/U2Core/CreateAnnotationTask.h0000644000175000017500000000010211651544335021055 0ustar ilyailya#include "../../corelibs/U2Core/src/tasks/CreateAnnotationTask.h" ugene-1.9.8/src/include/U2Core/DocumentSelection.h0000644000175000017500000000010311651544335020421 0ustar ilyailya#include "../../corelibs/U2Core/src/selection/DocumentSelection.h" ugene-1.9.8/src/include/U2Core/QVariantUtils.h0000644000175000017500000000010411651544335017544 0ustar ilyailya#include "../../corelibs/U2Core/src/util_algorithm/QVariantUtils.h" ugene-1.9.8/src/include/U2Core/DBXRefRegistry.h0000644000175000017500000000007611651544335017611 0ustar ilyailya#include "../../corelibs/U2Core/src/globals/DBXRefRegistry.h" ugene-1.9.8/src/include/U2Core/CopyDataTask.h0000644000175000017500000000007211651544335017331 0ustar ilyailya#include "../../corelibs/U2Core/src/tasks/CopyDataTask.h" ugene-1.9.8/src/include/U2Core/LoadDocumentTask.h0000644000175000017500000000007611651544335020207 0ustar ilyailya#include "../../corelibs/U2Core/src/tasks/LoadDocumentTask.h" ugene-1.9.8/src/include/U2Core/VirtualFileSystem.h0000644000175000017500000000007411651544335020437 0ustar ilyailya#include "../../corelibs/U2Core/src/io/VirtualFileSystem.h" ugene-1.9.8/src/include/U2Core/U2Region.h0000644000175000017500000001506511651544335016444 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_REGION_H_ #define _U2_REGION_H_ #include #include namespace U2 { /** Linear 64bit region */ class U2CORE_EXPORT U2Region { public: U2Region(): startPos(0), length(0){} U2Region(qint64 s, qint64 l): startPos(s), length(l){} /** Region start position. */ qint64 startPos; /** Region length. */ qint64 length; ////////////////////////// Member functions and operators //////////////////// /** Region end position, exclusive. */ qint64 endPos() const {return startPos + length;} /** Central point of the region. */ qint64 center() const { return startPos + length / 2 ;} /** Checks if this region has zero length. */ bool isEmpty() const {return length == 0; } /** Checks whether the specified point falls inside this region. */ bool contains(qint64 pos) const {return pos>=startPos && pos < endPos();} /** Checks whether the specified region fits inside this region or is equal. */ bool contains(const U2Region& r) const {return r.startPos >= startPos && r.endPos() <= endPos();} /** Checks whether the specified region has common points with this region. */ bool intersects(const U2Region& r) const; /** Returns the intersection between 2 regions, or empty value if regions do not intersect. */ U2Region intersect(const U2Region& r) const; /** Checks whether this region has common points with any region in the specified list. Returns the index of the first region found or -1 if no matches found */ int findIntersectedRegion(const QVector& rs) const; /** Checks whether this region has common points with any region in the specified list. Returns the index of the first region found or -1 if no matches found */ bool intersects(const QVector& rs) const {return findIntersectedRegion(rs) != -1;} /** Checks whether this region is located inside of any region in the specified list. Returns the index of the first region found or -1 if no matches found */ int findOverlappingRegion(const QVector& regions) const; /** Checks if the specified region is equal to this region. */ bool operator== ( const U2Region & r ) const { return r.startPos == startPos && r.length == length; } /** Checks whether the specified region is not equal to this region. */ bool operator!= ( const U2Region & r ) const { return r.startPos != startPos || r.length != length; } /** Compares 2 regions by start position. Returns true if this region starts strictly earlier than the specified one. */ bool operator<(const U2Region &r) const {return startPos < r.startPos;} ///////////////////////// Class functions ///////////////////////////////// /** Returns least common region which contains both of the 2 specified regions. */ static U2Region containingRegion(const U2Region& r1, const U2Region& r2); /** Returns least common region which contains all of the specified regions. */ static U2Region containingRegion(const QVector& regions); /** Normalizes the specified list by joining overlapping regions. This function sorts regions by starting position then iterates through them and replaces all groups of intersecting regions by containing regions. */ static QVector join(QVector& regions); /** Fixes start & len for all regions to ensure that the result region has startPos >= minPos & endPos <= maxPos */ static void bound(qint64 minPos, qint64 maxPos, QVector& regions); /** mirrors regions by mirror pos: startPos = mirrorPos - startPos */ static void mirror(qint64 mirrorPos, QVector& regions); /** divides regions by div : startPos = startPos / div */ static void divide(qint64 div, QVector& regions); /** multiplies regions by mult : startPos = startPos * mult */ static void multiply(qint64 mult, QVector& regions); /** Reverses order of regions in the list */ static void reverse(QVector& regions); /** shifts regions by offset pos: startPos = startPos + offset */ static void shift(int offset, QVector& regions); /** Removes all items from 'regionsToRemove' from 'regionsToProcess'*/ static void removeAll(QVector& regionsToProcess, const QVector& regionsToRemove); private: static bool registerMeta; }; //////////////////// inline implementations /////////////////////////// inline bool U2Region::intersects(const U2Region& r) const { qint64 sd = startPos - r.startPos; return (sd >= 0) ? (sd < r.length) : (-sd < length); } inline U2Region U2Region::intersect(const U2Region& r) const { qint64 newStart = qMax(startPos, r.startPos); qint64 newEnd = qMin(endPos(), r.endPos()); if (newStart > newEnd) { return U2Region(); } return U2Region(newStart, newEnd - newStart); } inline U2Region U2Region::containingRegion(const U2Region& r1, const U2Region& r2) { qint64 newStart = qMin(r1.startPos, r2.startPos); qint64 newEnd = qMax(r1.endPos(), r2.endPos()); return U2Region(newStart, newEnd - newStart); } inline U2Region U2Region::containingRegion(const QVector& regions) { assert(!regions.isEmpty()); U2Region res = regions.first(); foreach(const U2Region& r, regions) { res = containingRegion(res, r); } return res; } U2CORE_EXPORT QDataStream &operator<<(QDataStream &out, const U2Region &myObj); U2CORE_EXPORT QDataStream &operator>>(QDataStream &in, U2Region &myObj); }//namespace Q_DECLARE_TYPEINFO(U2::U2Region, Q_PRIMITIVE_TYPE); Q_DECLARE_METATYPE( U2::U2Region) Q_DECLARE_METATYPE( QVector< U2::U2Region >) #endif ugene-1.9.8/src/include/U2Core/DocumentFormatConfigurators.h0000644000175000017500000000011311651544335022473 0ustar ilyailya#include "../../corelibs/U2Core/src/globals/DocumentFormatConfigurators.h" ugene-1.9.8/src/include/U2Core/CMDLineUtils.h0000644000175000017500000000007411651544335017240 0ustar ilyailya#include "../../corelibs/U2Core/src/cmdline/CMDLineUtils.h" ugene-1.9.8/src/include/U2Core/PhyTree.h0000644000175000017500000000007011651544335016360 0ustar ilyailya#include "../../corelibs/U2Core/src/datatype/PhyTree.h" ugene-1.9.8/src/include/U2Core/U2DbiUtils.h0000644000175000017500000000620011651544335016727 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_DBI_UTILS_H_ #define _U2_DBI_UTILS_H_ #include #include namespace U2 { class U2OpStatus; /** Helper class that allocates connection in constructor and automatically releases it in the destructor It uses app-global connection pool. Note: DbiHandle caches U2OpStatus and reuses it in destructor on DBI release. Ensure that U2OpStatus live range contains DbiHandle live range */ class U2CORE_EXPORT DbiHandle { public: /** Opens connection to existing DBI */ DbiHandle(U2DbiFactoryId id, const QString& url, U2OpStatus& os); /** Opens connection to existing DBI or create news DBI*/ DbiHandle(U2DbiFactoryId id, const QString& url, bool create, U2OpStatus& os); DbiHandle(const DbiHandle & dbiHandle_); ~DbiHandle(); U2Dbi* dbi; U2OpStatus& os; private: //TODO DbiHandle & operator=(const DbiHandle & DbiHandle_); }; /** Iterator over buffered data set */ template class BufferedDbiIterator : public U2DbiIterator { public: BufferedDbiIterator(const QList& _buffer, const T& _errValue = T()) : buffer(_buffer), pos(0), errValue(_errValue) {} /** returns true if there are more reads to iterate*/ virtual bool hasNext() { return pos < buffer.size(); } /** returns next read and shifts one element*/ virtual T next() { if (!hasNext()) { return errValue; } const T& res = buffer.at(pos); pos++; return res; } /** returns next read without shifting*/ virtual T peek() { if (!hasNext()) { return errValue; } return buffer.at(pos); } private: QList buffer; int pos; T errValue; }; class U2CORE_EXPORT U2DbiUtils : public QObject{ Q_OBJECT public: /** Logs that operation called is not supported by DBI If U2OpStatus has no error set, sets the error message */ static void logNotSupported(U2DbiFeature f, U2Dbi* dbi, U2OpStatus& os); template static QList toList(U2DbiIterator* it); }; template QList U2DbiUtils::toList(U2DbiIterator* it) { QList result; while (it->hasNext()) { result << it->next(); } return result; } }// namespace #endif ugene-1.9.8/src/include/U2Core/DNASequence.h0000644000175000017500000000007411651544335017077 0ustar ilyailya#include "../../corelibs/U2Core/src/datatype/DNASequence.h" ugene-1.9.8/src/include/U2Core/MultiTask.h0000644000175000017500000000006711651544335016723 0ustar ilyailya#include "../../corelibs/U2Core/src/tasks/MultiTask.h" ugene-1.9.8/src/include/U2Core/GUrl.h0000644000175000017500000000005711651544335015656 0ustar ilyailya#include "../../corelibs/U2Core/src/io/GUrl.h" ugene-1.9.8/src/include/U2Core/LogCache.h0000644000175000017500000000007011651544335016445 0ustar ilyailya#include "../../corelibs/U2Core/src/globals/LogCache.h" ugene-1.9.8/src/include/U2Core/ExternalToolRegistry.h0000644000175000017500000000010411651544335021147 0ustar ilyailya#include "../../corelibs/U2Core/src/globals/ExternalToolRegistry.h" ugene-1.9.8/src/include/U2Core/DNAQuality.h0000644000175000017500000000007311651544335016756 0ustar ilyailya#include "../../corelibs/U2Core/src/datatype/DNAQuality.h" ugene-1.9.8/src/include/U2Core/DIProperties.h0000644000175000017500000000007511651544335017356 0ustar ilyailya#include "../../corelibs/U2Core/src/datatype/DIProperties.h" ugene-1.9.8/src/include/U2Core/ProjectModel.h0000644000175000017500000000007311651544335017372 0ustar ilyailya#include "../../corelibs/U2Core/src/models/ProjectModel.h" ugene-1.9.8/src/include/U2Core/AnnotationTableObject.h0000644000175000017500000000010611651544335021211 0ustar ilyailya#include "../../corelibs/U2Core/src/gobjects/AnnotationTableObject.h" ugene-1.9.8/src/include/U2Core/U2AnnotationUtils.h0000644000175000017500000000621011651544335020344 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_ANNOTATION_UTILS_H_ #define _U2_ANNOTATION_UTILS_H_ #include namespace U2 { /** U2Annotation and related structures utility functions */ class U2CORE_EXPORT U2AnnotationUtils : public QObject { Q_OBJECT private: U2AnnotationUtils(){} public: enum AnnotationStrategyForResize{ AnnotationStrategyForResize_Resize, AnnotationStrategyForResize_Remove, AnnotationStrategyForResize_Split }; /** Corrects annotation locations for a sequence. The passed list is updated with new locations, the returned list contains removed locations if any. If specified strategy is 'remove', removes all locations which intersect the removed region or fall inside it. */ static QVector fixLocationsForRemovedRegion(const U2Region& regionToDelete, QVector& loc, AnnotationStrategyForResize s); /** Corrects annotation locations for a sequence. The passed list is updated with new locations, the returned list contains removed locations if any. If specified strategy is 'remove', removes all locations which contain the insert position inside them. Note, if a region starts at the insert position, it is just moved to the right. */ static QVector fixLocationsForInsertedRegion(qint64 insertPos, qint64 len, QVector& loc, AnnotationStrategyForResize s); /** Corrects annotation locations for a sequence. The passed list is updated with new locations, the returned list contains removed locations if any. If specified strategy is 'remove', removes all locations which intersect the modified region or fall inside it. */ static QVector fixLocationsForReplacedRegion(const U2Region& regionToDelete, qint64 newLen, QVector& loc, AnnotationStrategyForResize s); /** returns translation frame[0,1,2] the region is placed on */ static int getRegionFrame(int sequenceLen, U2Strand strand, bool order, int region, const QVector& location); /** Returns true if annotation location is splitted by sequence "edges". For example, location JOIN(N..SeqSize - 1, 0..M) is splitted. **/ static bool isSplitted(const U2Location& location, const U2Region& seqRange); }; } //namespace #endif ugene-1.9.8/src/include/U2Core/Matrix44.h0000644000175000017500000000007111651544335016415 0ustar ilyailya#include "../../corelibs/U2Core/src/datatype/Matrix44.h" ugene-1.9.8/src/include/U2Core/U2Dbi.h0000644000175000017500000002061711651544335015716 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_DBI_H_ #define _U2_DBI_H_ #include "U2Type.h" #include #include #include #include #include #include #include namespace U2 { // For the classes below, see description in class definition class U2ObjectDbi; class U2SequenceDbi; class U2AnnotationDbi; class U2CrossDatabaseReferenceDbi; class U2MsaDbi; class U2AssemblyDbi; class U2AttributeDbi; class U2OpStatus; class U2Dbi; /** A constant to retrieve all available data. */ #define U2_DBI_NO_LIMIT -1 /** Init time DBI parameter name to specify URL of the database */ #define U2_DBI_OPTION_URL "url" /** Init time DBI parameter name to specify that database must be created if not exists */ #define U2_DBI_OPTION_CREATE "create" /** Init time DBI parameter value. Indicates boolean 'Yes' or 'true'. */ #define U2_DBI_VALUE_ON "1" /** Operational state of the database. */ enum U2CORE_EXPORT U2DbiState { U2DbiState_Void = 1, U2DbiState_Starting = 2, U2DbiState_Ready = 3, U2DbiState_Stopping = 4 }; /** DBI feature flags */ enum U2CORE_EXPORT U2DbiFeature { /** DBI supports sequence reading methods */ U2DbiFeature_ReadSequence = 1, /** DBI supports MSA reading methods */ U2DbiFeature_ReadMsa = 2, /** DBI supports Assembly reading methods */ U2DbiFeature_ReadAssembly = 3, /** DBI supports sequence annotations reading methods */ U2DbiFeature_ReadSequenceAnnotations = 4, /** DBI supports read methods for attributes */ U2DbiFeature_ReadAttributes = 5, /** DBI supports read methods for remote objects */ U2DbiFeature_ReadCrossDatabaseReferences = 6, /** DBI supports changing/storing sequences */ U2DbiFeature_WriteSequence = 101, /** DBI supports changing/storing multiple sequence alignments */ U2DbiFeature_WriteMsa = 102, /** DBI supports changing/storing assemblies */ U2DbiFeature_WriteAssembly = 103 /** DBI supports changing/storing sequence annotations*/, U2DbiFeature_WriteSequenceAnnotations = 104, /** DBI supports changing/storing attributes */ U2DbiFeature_WriteAttributes = 105, /** DBI supports cross database references */ U2DbiFeature_WriteCrossDatabaseReferences = 106, /** DBI supports removal of objects */ U2DbiFeature_RemoveObjects = 200, /** DBI supports set folder modification operations */ U2DbiFeature_ChangeFolders = 201, /** DBI provides optimized algorithm for assembly reads packing */ U2DbiFeature_AssemblyReadsPacking = 300, /** DBI provides optimized algorithm for coverage calculation */ U2DbiFeature_AssemblyCoverageStat = 301, /** DBI provides optimized algorithm for sorting attributes */ U2DbiFeature_AttributeSorting = 400, }; /** DBI factory provides functions to create new DBI instances and check file content to ensure that file is a valid database file */ class U2DbiFactory { public: U2DbiFactory() {} virtual ~U2DbiFactory(){}; /** Creates new DBI instance */ virtual U2Dbi *createDbi() = 0; /** Returns DBI type ID */ virtual U2DbiFactoryId getId() const = 0; /** Checks that data pointed by properties is a valid DBI resource rawData param is used for compatibility with UGENE 1.x format detection and can be used by factory directly to check database header */ virtual bool isValidDbi(const QHash& properties, const QByteArray& rawData, U2OpStatus& os) const = 0; }; /** Database access interface. Database examples: fasta file, genbank file, BAM file, SQLite file */ class U2CORE_EXPORT U2Dbi { public: virtual ~U2Dbi(){} ////////////////////////////////////////////////////////////////////////// // base methods that any DBI must support /** Boots the database up to functional state. Some property names are reserved: 'url' - url of the DBI 'create' - '1' or '0'- if DBI does not exist, asks to create instance if possible 'user', 'password' - user and password to access to the DBI The 'persistentData' parameter provides database state saved from previous session in a project or workspace, if any. @see shutdown() */ virtual void init(const QHash& properties, const QVariantMap& persistentData, U2OpStatus& os) = 0; /** Stops the database and frees up used resources. Returns persistent database state for external storage in a project or workspace, if any. For example, plain-file-based DBI can store certain settings or preferences between sessions, which may not fit into particular file format. Note: this method will call flush() @see init() */ virtual QVariantMap shutdown(U2OpStatus& os) = 0; /** Ensures that dbi state is synchronized with storage Return 'true' of operation is successful */ virtual bool flush(U2OpStatus& os) = 0; /** Unique database id. Usually is an URL of the database */ virtual U2DbiId getDbiId() const = 0; /** Return factory instance for this DBI */ virtual U2DbiFactoryId getFactoryId() const = 0; /** Returns all features supported by this DBI instance */ virtual const QSet& getFeatures() const = 0; /** Returns properties used to initialize the database */ virtual QHash getInitProperties() const = 0; /** Returns database meta-info. Any set of properties to be shown to user */ virtual QHash getDbiMetaInfo(U2OpStatus&) = 0; /** Returns type of the entity referenced by the given ID */ virtual U2DataType getEntityTypeById(const U2DataId& id) const = 0; /** Returns current DBI state */ virtual U2DbiState getState() const = 0; /** Database interface to access objects All dbi implementations must support a subset of this interface */ virtual U2ObjectDbi* getObjectDbi() = 0; /** U2Sequence related DBI routines Not NULL only if U2DbiFeature_ReadSequences supported */ virtual U2SequenceDbi* getSequenceDbi() = 0; /** U2Annotation related DBI routines Not NULL only if U2DbiFeature_ReadAnnotations supported */ virtual U2AnnotationDbi* getAnnotationRDbi() = 0; /** U2Annotation related DBI routines Not NULL only if U2DbiFeature_ReadMsa supported */ virtual U2MsaDbi* getMsaDbi() = 0; /** U2Annotation related DBI routines Not NULL only if U2DbiFeature_ReadAssembly supported */ virtual U2AssemblyDbi* getAssemblyDbi() = 0; /** U2Attribute related DBI routines Not NULL only if U2DbiFeature_ReadAttributes supported */ virtual U2AttributeDbi* getAttributeDbi() = 0; /** Cross database references handling routines Not NULL only if U2DbiFeature_ReadCrossDatabaseReferences supported */ virtual U2CrossDatabaseReferenceDbi* getCrossDatabaseReferenceDbi() = 0; }; /** Base class for all *Dbi classes provided by U2Dbi Contains reference to root-level dbi */ class U2CORE_EXPORT U2ChildDbi { protected: U2ChildDbi(U2Dbi* _rootDbi) : rootDbi (_rootDbi){} virtual ~U2ChildDbi(){} public: U2Dbi* getRootDbi() const { return rootDbi; } private: U2Dbi* rootDbi; }; } //namespace #endif ugene-1.9.8/src/include/U2Core/DNAAlphabetRegistryImpl.h0000644000175000017500000000011011651544335021411 0ustar ilyailya#include "../../corelibs/U2Core/src/datatype/DNAAlphabetRegistryImpl.h" ugene-1.9.8/src/include/U2Core/L10n.h0000644000175000017500000000006411651544335015515 0ustar ilyailya#include "../../corelibs/U2Core/src/globals/L10n.h" ugene-1.9.8/src/include/U2Core/U2AssemblyDbi.h0000644000175000017500000001636611651544335017424 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_ASSEMBLY_DBI_H_ #define _U2_ASSEMBLY_DBI_H_ #include #include #include namespace U2 { /** Class used to iterate huge amount of assembly reads and optimize assembly import operation to DBI */ class U2AssemblyReadsIterator { public: /** returns true if there are more reads to iterate*/ virtual bool hasNext() = 0; /** returns next read or error */ virtual U2AssemblyRead next(U2OpStatus& os) = 0; }; /** Additional reads info used during reads import into assembly */ class U2AssemblyReadsImportInfo { public: U2AssemblyReadsImportInfo() : nReads(0), packed(false), computeCoverage(false), maxEndPosHint(0), coverageBasesPerPoint(1) {} /** Number of reads added during import */ qint64 nReads; /** Specifies if assembly was packed at import time*/ bool packed; /* Place where to save pack statistics */ U2AssemblyPackStat packStat; /** Specifies if assembly coverage is needed to be computed at import time*/ bool computeCoverage; /** coverage size hint - tells max end pos for reads if not 0*/ int maxEndPosHint; /** Place to save coverage info */ U2AssemblyCoverageStat coverage; /** Shows how many real bases are in 1 coverage point */ int coverageBasesPerPoint; }; /** An interface to obtain access to assembly data */ class U2CORE_EXPORT U2AssemblyDbi : public U2ChildDbi { protected: U2AssemblyDbi(U2Dbi* rootDbi) : U2ChildDbi(rootDbi) {} public: /** Reads assembly object by its id. If there is no assembly object with the specified id returns a default constructed assembly object. */ virtual U2Assembly getAssemblyObject(const U2DataId& id, U2OpStatus& os) = 0; /** Returns number of reads located near or intersecting the region. The region should be a valid region within alignment bounds, i.e. non-negative and less than alignment length. If there is no assembly object with the specified id returns -1. Note: 'near' here means that DBI is not forced to return precise number of reads that intersects the region and some deviations is allowed in order to apply performance optimizations. Note2: Use U2_ASSEMBLY_REGION_MAX to count all reads in assembly in effective way */ virtual qint64 countReads(const U2DataId& assemblyId, const U2Region& r, U2OpStatus& os) = 0; /** Returns reads that intersect given region. If there is no assembly object with the specified id returns NULL. Note: iterator instance must be deallocated by caller method */ virtual U2DbiIterator* getReads(const U2DataId& assemblyId, const U2Region& r, U2OpStatus& os) = 0; /** Returns reads with packed row value bounded by 'minRow' and 'maxRow' that intersect given region. If there is no assembly object with the specified id returns NULL. Note: iterator instance must be deallocated by caller method */ virtual U2DbiIterator* getReadsByRow(const U2DataId& assemblyId, const U2Region& r, qint64 minRow, qint64 maxRow, U2OpStatus& os) = 0; /** Returns reads with a specified name. Used to find paired reads that must have equal names. If there is no assembly object with the specified id returns NULL. Note: iterator instance must be deallocated by caller method. */ virtual U2DbiIterator* getReadsByName(const U2DataId& assemblyId, const QByteArray& name, U2OpStatus& os) = 0; /** Returns maximum packed row value of reads that intersect 'r'. 'Intersect' here means that region(leftmost pos, rightmost pos) intersects with 'r' If there is no assembly object with the specified id returns -1. */ virtual qint64 getMaxPackedRow(const U2DataId& assemblyId, const U2Region& r, U2OpStatus& os) = 0; /** Count 'length of assembly' - position of the rightmost base of all reads. If there is no assembly object with the specified id returns -1. */ virtual qint64 getMaxEndPos(const U2DataId& assemblyId, U2OpStatus& os) = 0; /** Creates new empty assembly object. Reads iterator can be NULL. If iterator is not NULL adapter can automatically try to pack reads. If pack is performed, the corresponding structure is filled with pack statistics. Assembly object gets its id assigned. Folder 'folder' must exist in database. Requires: U2DbiFeature_WriteAssembly feature support */ virtual void createAssemblyObject(U2Assembly& assembly, const QString& folder, U2DbiIterator* it, U2AssemblyReadsImportInfo& importInfo, U2OpStatus& os) = 0; /** Updates assembly object fields. Requires: U2DbiFeature_WriteAssembly feature support. */ virtual void updateAssemblyObject(const U2Assembly& assembly, U2OpStatus& os) = 0; /** Removes reads from assembly. Automatically removes affected sequences that are not anymore accessible from folders. Requires: U2DbiFeature_WriteAssembly feature support. */ virtual void removeReads(const U2DataId& assemblyId, const QList& readIds, U2OpStatus& os) = 0; /** Adds sequences to assembly. Reads got their ids assigned. Requires: U2DbiFeature_WriteAssembly feature support. */ virtual void addReads(const U2DataId& assemblyId, U2DbiIterator* it, U2OpStatus& os) = 0; /** Packs assembly rows: assigns packedViewRow value (i.e. read's vertical position in view) for every read in assembly so that reads do not overlap. Requires: U2DbiFeature_WriteAssembly and U2DbiFeature_AssemblyReadsPacking features support */ virtual void pack(const U2DataId& assemblyId, U2AssemblyPackStat& stats, U2OpStatus& os) = 0; /** Calculates coverage information for the given region and stores it in 'c' structure. U2Region 'region' passed to the method is split into N sequential windows of equal length, where N is 'c.coverage' vector size. Number of reads intersecting each window is guaranteed to be in range stored at corresponding index in vector 'c.coverage'. */ virtual void calculateCoverage(const U2DataId& assemblyId, const U2Region& region, U2AssemblyCoverageStat& c, U2OpStatus& os) = 0; }; } //namespace #endif ugene-1.9.8/src/include/U2Core/FormatUtils.h0000644000175000017500000000007511651544335017256 0ustar ilyailya#include "../../corelibs/U2Core/src/util_text/FormatUtils.h" ugene-1.9.8/src/include/U2Core/AssemblyObject.h0000644000175000017500000000007711651544335017715 0ustar ilyailya#include "../../corelibs/U2Core/src/gobjects/AssemblyObject.h" ugene-1.9.8/src/include/U2Core/ScriptTask.h0000644000175000017500000000007011651544335017067 0ustar ilyailya#include "../../corelibs/U2Core/src/tasks/ScriptTask.h" ugene-1.9.8/src/include/U2Core/AutoAnnotationsSupport.h0000644000175000017500000000010611651544335021523 0ustar ilyailya#include "../../corelibs/U2Core/src/globals/AutoAnnotationsSupport.h" ugene-1.9.8/src/include/U2Core/ServiceModel.h0000644000175000017500000000007411651544335017365 0ustar ilyailya#include "../../corelibs/U2Core/src/globals/ServiceModel.h" ugene-1.9.8/src/include/U2Core/SequenceWalkerTask.h0000644000175000017500000000010011651544335020533 0ustar ilyailya#include "../../corelibs/U2Core/src/tasks/SequenceWalkerTask.h" ugene-1.9.8/src/include/U2Core/DNAAlphabetUtils.h0000644000175000017500000000010111651544335020057 0ustar ilyailya#include "../../corelibs/U2Core/src/datatype/DNAAlphabetUtils.h" ugene-1.9.8/src/include/U2Core/HttpFileAdapter.h0000644000175000017500000000007211651544335020022 0ustar ilyailya#include "../../corelibs/U2Core/src/io/HttpFileAdapter.h" ugene-1.9.8/src/include/U2Core/ResourceTracker.h0000644000175000017500000000007711651544335020112 0ustar ilyailya#include "../../corelibs/U2Core/src/globals/ResourceTracker.h" ugene-1.9.8/src/include/U2Core/TaskStarter.h0000644000175000017500000000007111651544335017250 0ustar ilyailya#include "../../corelibs/U2Core/src/tasks/TaskStarter.h" ugene-1.9.8/src/include/U2Core/U2SqlHelpers.h0000644000175000017500000000006711651544335017277 0ustar ilyailya#include "../../corelibs/U2Core/src/dbi/U2SqlHelpers.h"ugene-1.9.8/src/include/U2Core/DbiDocumentFormat.h0000644000175000017500000000007411651544335020352 0ustar ilyailya#include "../../corelibs/U2Core/src/dbi/DbiDocumentFormat.h"ugene-1.9.8/src/include/U2Core/AnnotationSettings.h0000644000175000017500000000010311651544335020630 0ustar ilyailya#include "../../corelibs/U2Core/src/datatype/AnnotationSettings.h" ugene-1.9.8/src/include/U2Core/GObjectRelationRoles.h0000644000175000017500000000010511651544335021017 0ustar ilyailya#include "../../corelibs/U2Core/src/gobjects/GObjectRelationRoles.h" ugene-1.9.8/src/include/U2Core/GObject.h0000644000175000017500000000006611651544335016322 0ustar ilyailya#include "../../corelibs/U2Core/src/models/GObject.h" ugene-1.9.8/src/include/U2Core/MAlignment.h0000644000175000017500000000007311651544335017036 0ustar ilyailya#include "../../corelibs/U2Core/src/datatype/MAlignment.h" ugene-1.9.8/src/include/U2Core/ReplacePartOfSequenceTask.h0000644000175000017500000000010711651544335022004 0ustar ilyailya#include "../../corelibs/U2Core/src/tasks/ReplacePartOfSequenceTask.h" ugene-1.9.8/src/include/U2Core/TextSelection.h0000644000175000017500000000007711651544335017601 0ustar ilyailya#include "../../corelibs/U2Core/src/selection/TextSelection.h" ugene-1.9.8/src/include/U2Core/MAlignmentObject.h0000644000175000017500000000010111651544335020155 0ustar ilyailya#include "../../corelibs/U2Core/src/gobjects/MAlignmentObject.h" ugene-1.9.8/src/include/U2Core/U2SequenceDbi.h0000644000175000017500000000604011651544335017401 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_SEQUENCE_DBI_H_ #define _U2_SEQUENCE_DBI_H_ #include #include #include namespace U2 { /** An interface to access to sequence objects */ class U2CORE_EXPORT U2SequenceDbi : public U2ChildDbi { protected: U2SequenceDbi(U2Dbi* rootDbi) : U2ChildDbi(rootDbi){} public: /** Reads sequence object from database by its id. If there is no sequence object with the specified id returns a default constructed value. */ virtual U2Sequence getSequenceObject(const U2DataId& sequenceId, U2OpStatus& os) = 0; /** Reads specified sequence data region from database. The region must be valid region within sequence bounds. If there is no sequence with the specified id returns an empty QByteArray. */ virtual QByteArray getSequenceData(const U2DataId& sequenceId, const U2Region& region, U2OpStatus& os) = 0; /** Adds a new (empty) sequence instance into database. Sets the assigned id to the passed U2Sequence instance. The folder must exist in the database. Note: Use 'updateSequenceData' method to supply data to the created sequence. Requires: U2DbiFeature_WriteSequence feature support */ virtual void createSequenceObject(U2Sequence& sequence, const QString& folder, U2OpStatus& os) = 0; /** Updates sequence region: replaces 'regionToReplace' sequence region with 'dataToInsert'. Note: 'regionToReplace' length can differ from dataToInsert length, so the method can be used to insert/remove sequence regions. WARNING: The passed region 'startPos' has to be between 0 and sequence length inclusive. If the sequence is empty 'regionToReplace.startPos' has to be 0. //TODO think about annotations: should we fix locations automatically?? If yes, emit notifications?? // varlax: I think this should be left to user, no automatic fixes. Requires: U2DbiFeature_WriteSequence feature support */ virtual void updateSequenceData(const U2DataId& sequenceId, const U2Region& regionToReplace, const QByteArray& dataToInsert, U2OpStatus& os) = 0; }; } //namespace #endif ugene-1.9.8/src/include/opencl/0000755000175000017500000000000011651544336015014 5ustar ilyailyaugene-1.9.8/src/include/opencl/legacy/0000755000175000017500000000000011651544336016260 5ustar ilyailyaugene-1.9.8/src/include/opencl/legacy/cl_platform.h0000644000175000017500000011221511651544336020735 0ustar ilyailya/********************************************************************************** * Copyright (c) 2008-2010 The Khronos Group Inc. * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and/or associated documentation files (the * "Materials"), to deal in the Materials without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Materials, and to * permit persons to whom the Materials are furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Materials. * * THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS. **********************************************************************************/ /* $Revision: 11803 $ on $Date: 2010-06-25 22:32:12 +0530 (Fri, 25 Jun 2010) $ */ #ifndef __CL_PLATFORM_H #define __CL_PLATFORM_H #ifdef __APPLE__ /* Contains #defines for AVAILABLE_MAC_OS_X_VERSION_10_6_AND_LATER below */ #include #endif #ifdef __cplusplus extern "C" { #endif #if defined(_WIN32) #define CL_API_ENTRY #define CL_API_CALL __stdcall #define CL_CALLBACK __stdcall #else #define CL_API_ENTRY #define CL_API_CALL #define CL_CALLBACK #endif #ifdef __APPLE__ #define CL_EXTENSION_WEAK_LINK __attribute__((weak_import)) #define CL_API_SUFFIX__VERSION_1_0 AVAILABLE_MAC_OS_X_VERSION_10_6_AND_LATER #define CL_EXT_SUFFIX__VERSION_1_0 CL_EXTENSION_WEAK_LINK AVAILABLE_MAC_OS_X_VERSION_10_6_AND_LATER #define CL_API_SUFFIX__VERSION_1_1 CL_EXTENSION_WEAK_LINK #define CL_EXT_SUFFIX__VERSION_1_1 CL_EXTENSION_WEAK_LINK #define CL_EXT_SUFFIX__VERSION_1_0_DEPRECATED CL_EXTENSION_WEAK_LINK AVAILABLE_MAC_OS_X_VERSION_10_6_AND_LATER #else #define CL_EXTENSION_WEAK_LINK #define CL_API_SUFFIX__VERSION_1_0 #define CL_EXT_SUFFIX__VERSION_1_0 #define CL_API_SUFFIX__VERSION_1_1 #define CL_EXT_SUFFIX__VERSION_1_1 #define CL_EXT_SUFFIX__VERSION_1_0_DEPRECATED #endif #if (defined (_WIN32) && defined(_MSC_VER)) /* scalar types */ typedef signed __int8 cl_char; typedef unsigned __int8 cl_uchar; typedef signed __int16 cl_short; typedef unsigned __int16 cl_ushort; typedef signed __int32 cl_int; typedef unsigned __int32 cl_uint; typedef signed __int64 cl_long; typedef unsigned __int64 cl_ulong; typedef unsigned __int16 cl_half; typedef float cl_float; typedef double cl_double; /* Macro names and corresponding values defined by OpenCL */ #define CL_CHAR_BIT 8 #define CL_SCHAR_MAX 127 #define CL_SCHAR_MIN (-127-1) #define CL_CHAR_MAX CL_SCHAR_MAX #define CL_CHAR_MIN CL_SCHAR_MIN #define CL_UCHAR_MAX 255 #define CL_SHRT_MAX 32767 #define CL_SHRT_MIN (-32767-1) #define CL_USHRT_MAX 65535 #define CL_INT_MAX 2147483647 #define CL_INT_MIN (-2147483647-1) #define CL_UINT_MAX 0xffffffffU #define CL_LONG_MAX ((cl_long) 0x7FFFFFFFFFFFFFFFLL) #define CL_LONG_MIN ((cl_long) -0x7FFFFFFFFFFFFFFFLL - 1LL) #define CL_ULONG_MAX ((cl_ulong) 0xFFFFFFFFFFFFFFFFULL) #define CL_FLT_DIG 6 #define CL_FLT_MANT_DIG 24 #define CL_FLT_MAX_10_EXP +38 #define CL_FLT_MAX_EXP +128 #define CL_FLT_MIN_10_EXP -37 #define CL_FLT_MIN_EXP -125 #define CL_FLT_RADIX 2 #define CL_FLT_MAX 340282346638528859811704183484516925440.0f #define CL_FLT_MIN 1.175494350822287507969e-38f #define CL_FLT_EPSILON 0x1.0p-23f #define CL_DBL_DIG 15 #define CL_DBL_MANT_DIG 53 #define CL_DBL_MAX_10_EXP +308 #define CL_DBL_MAX_EXP +1024 #define CL_DBL_MIN_10_EXP -307 #define CL_DBL_MIN_EXP -1021 #define CL_DBL_RADIX 2 #define CL_DBL_MAX 179769313486231570814527423731704356798070567525844996598917476803157260780028538760589558632766878171540458953514382464234321326889464182768467546703537516986049910576551282076245490090389328944075868508455133942304583236903222948165808559332123348274797826204144723168738177180919299881250404026184124858368.0 #define CL_DBL_MIN 2.225073858507201383090e-308 #define CL_DBL_EPSILON 2.220446049250313080847e-16 #define CL_M_E 2.718281828459045090796 #define CL_M_LOG2E 1.442695040888963387005 #define CL_M_LOG10E 0.434294481903251816668 #define CL_M_LN2 0.693147180559945286227 #define CL_M_LN10 2.302585092994045901094 #define CL_M_PI 3.141592653589793115998 #define CL_M_PI_2 1.570796326794896557999 #define CL_M_PI_4 0.785398163397448278999 #define CL_M_1_PI 0.318309886183790691216 #define CL_M_2_PI 0.636619772367581382433 #define CL_M_2_SQRTPI 1.128379167095512558561 #define CL_M_SQRT2 1.414213562373095145475 #define CL_M_SQRT1_2 0.707106781186547572737 #define CL_M_E_F 2.71828174591064f #define CL_M_LOG2E_F 1.44269502162933f #define CL_M_LOG10E_F 0.43429449200630f #define CL_M_LN2_F 0.69314718246460f #define CL_M_LN10_F 2.30258512496948f #define CL_M_PI_F 3.14159274101257f #define CL_M_PI_2_F 1.57079637050629f #define CL_M_PI_4_F 0.78539818525314f #define CL_M_1_PI_F 0.31830987334251f #define CL_M_2_PI_F 0.63661974668503f #define CL_M_2_SQRTPI_F 1.12837922573090f #define CL_M_SQRT2_F 1.41421353816986f #define CL_M_SQRT1_2_F 0.70710676908493f #define CL_NAN (CL_INFINITY - CL_INFINITY) #define CL_HUGE_VALF ((cl_float) 1e50) #define CL_HUGE_VAL ((cl_double) 1e500) #define CL_MAXFLOAT CL_FLT_MAX #define CL_INFINITY CL_HUGE_VALF #else #include /* scalar types */ typedef int8_t cl_char; typedef uint8_t cl_uchar; typedef int16_t cl_short __attribute__((aligned(2))); typedef uint16_t cl_ushort __attribute__((aligned(2))); typedef int32_t cl_int __attribute__((aligned(4))); typedef uint32_t cl_uint __attribute__((aligned(4))); typedef int64_t cl_long __attribute__((aligned(8))); typedef uint64_t cl_ulong __attribute__((aligned(8))); typedef uint16_t cl_half __attribute__((aligned(2))); typedef float cl_float __attribute__((aligned(4))); typedef double cl_double __attribute__((aligned(8))); /* Macro names and corresponding values defined by OpenCL */ #define CL_CHAR_BIT 8 #define CL_SCHAR_MAX 127 #define CL_SCHAR_MIN (-127-1) #define CL_CHAR_MAX CL_SCHAR_MAX #define CL_CHAR_MIN CL_SCHAR_MIN #define CL_UCHAR_MAX 255 #define CL_SHRT_MAX 32767 #define CL_SHRT_MIN (-32767-1) #define CL_USHRT_MAX 65535 #define CL_INT_MAX 2147483647 #define CL_INT_MIN (-2147483647-1) #define CL_UINT_MAX 0xffffffffU #define CL_LONG_MAX ((cl_long) 0x7FFFFFFFFFFFFFFFLL) #define CL_LONG_MIN ((cl_long) -0x7FFFFFFFFFFFFFFFLL - 1LL) #define CL_ULONG_MAX ((cl_ulong) 0xFFFFFFFFFFFFFFFFULL) #define CL_FLT_DIG 6 #define CL_FLT_MANT_DIG 24 #define CL_FLT_MAX_10_EXP +38 #define CL_FLT_MAX_EXP +128 #define CL_FLT_MIN_10_EXP -37 #define CL_FLT_MIN_EXP -125 #define CL_FLT_RADIX 2 #define CL_FLT_MAX 0x1.fffffep127f #define CL_FLT_MIN 0x1.0p-126f #define CL_FLT_EPSILON 0x1.0p-23f #define CL_DBL_DIG 15 #define CL_DBL_MANT_DIG 53 #define CL_DBL_MAX_10_EXP +308 #define CL_DBL_MAX_EXP +1024 #define CL_DBL_MIN_10_EXP -307 #define CL_DBL_MIN_EXP -1021 #define CL_DBL_RADIX 2 #define CL_DBL_MAX 0x1.fffffffffffffp1023 #define CL_DBL_MIN 0x1.0p-1022 #define CL_DBL_EPSILON 0x1.0p-52 #define CL_M_E 2.718281828459045090796 #define CL_M_LOG2E 1.442695040888963387005 #define CL_M_LOG10E 0.434294481903251816668 #define CL_M_LN2 0.693147180559945286227 #define CL_M_LN10 2.302585092994045901094 #define CL_M_PI 3.141592653589793115998 #define CL_M_PI_2 1.570796326794896557999 #define CL_M_PI_4 0.785398163397448278999 #define CL_M_1_PI 0.318309886183790691216 #define CL_M_2_PI 0.636619772367581382433 #define CL_M_2_SQRTPI 1.128379167095512558561 #define CL_M_SQRT2 1.414213562373095145475 #define CL_M_SQRT1_2 0.707106781186547572737 #define CL_M_E_F 2.71828174591064f #define CL_M_LOG2E_F 1.44269502162933f #define CL_M_LOG10E_F 0.43429449200630f #define CL_M_LN2_F 0.69314718246460f #define CL_M_LN10_F 2.30258512496948f #define CL_M_PI_F 3.14159274101257f #define CL_M_PI_2_F 1.57079637050629f #define CL_M_PI_4_F 0.78539818525314f #define CL_M_1_PI_F 0.31830987334251f #define CL_M_2_PI_F 0.63661974668503f #define CL_M_2_SQRTPI_F 1.12837922573090f #define CL_M_SQRT2_F 1.41421353816986f #define CL_M_SQRT1_2_F 0.70710676908493f #if defined( __GNUC__ ) #define CL_HUGE_VALF __builtin_huge_valf() #define CL_HUGE_VAL __builtin_huge_val() #define CL_NAN __builtin_nanf( "" ) #else #define CL_HUGE_VALF ((cl_float) 1e50) #define CL_HUGE_VAL ((cl_double) 1e500) float nanf( const char * ); #define CL_NAN nanf( "" ) #endif #define CL_MAXFLOAT CL_FLT_MAX #define CL_INFINITY CL_HUGE_VALF #endif #include /* Mirror types to GL types. Mirror types allow us to avoid deciding which headers to load based on whether we are using GL or GLES here. */ typedef unsigned int cl_GLuint; typedef int cl_GLint; typedef unsigned int cl_GLenum; /* * Vector types * * Note: OpenCL requires that all types be naturally aligned. * This means that vector types must be naturally aligned. * For example, a vector of four floats must be aligned to * a 16 byte boundary (calculated as 4 * the natural 4-byte * alignment of the float). The alignment qualifiers here * will only function properly if your compiler supports them * and if you don't actively work to defeat them. For example, * in order for a cl_float4 to be 16 byte aligned in a struct, * the start of the struct must itself be 16-byte aligned. * * Maintaining proper alignment is the user's responsibility. */ /* Define basic vector types */ #if defined( __VEC__ ) #include /* may be omitted depending on compiler. AltiVec spec provides no way to detect whether the header is required. */ typedef vector unsigned char __cl_uchar16; typedef vector signed char __cl_char16; typedef vector unsigned short __cl_ushort8; typedef vector signed short __cl_short8; typedef vector unsigned int __cl_uint4; typedef vector signed int __cl_int4; typedef vector float __cl_float4; #define __CL_UCHAR16__ 1 #define __CL_CHAR16__ 1 #define __CL_USHORT8__ 1 #define __CL_SHORT8__ 1 #define __CL_UINT4__ 1 #define __CL_INT4__ 1 #define __CL_FLOAT4__ 1 #endif #if defined( __SSE__ ) #if defined( __MINGW64__ ) #include #else #include #endif #if defined( __GNUC__ ) typedef float __cl_float4 __attribute__((vector_size(16))); #else typedef __m128 __cl_float4; #endif #define __CL_FLOAT4__ 1 #endif #if defined( __SSE2__ ) #if defined( __MINGW64__ ) #include #else #include #endif #if defined( __GNUC__ ) typedef cl_uchar __cl_uchar16 __attribute__((vector_size(16))); typedef cl_char __cl_char16 __attribute__((vector_size(16))); typedef cl_ushort __cl_ushort8 __attribute__((vector_size(16))); typedef cl_short __cl_short8 __attribute__((vector_size(16))); typedef cl_uint __cl_uint4 __attribute__((vector_size(16))); typedef cl_int __cl_int4 __attribute__((vector_size(16))); typedef cl_ulong __cl_ulong2 __attribute__((vector_size(16))); typedef cl_long __cl_long2 __attribute__((vector_size(16))); typedef cl_double __cl_double2 __attribute__((vector_size(16))); #else typedef __m128i __cl_uchar16; typedef __m128i __cl_char16; typedef __m128i __cl_ushort8; typedef __m128i __cl_short8; typedef __m128i __cl_uint4; typedef __m128i __cl_int4; typedef __m128i __cl_ulong2; typedef __m128i __cl_long2; typedef __m128d __cl_double2; #endif #define __CL_UCHAR16__ 1 #define __CL_CHAR16__ 1 #define __CL_USHORT8__ 1 #define __CL_SHORT8__ 1 #define __CL_INT4__ 1 #define __CL_UINT4__ 1 #define __CL_ULONG2__ 1 #define __CL_LONG2__ 1 #define __CL_DOUBLE2__ 1 #endif #if defined( __MMX__ ) #include #if defined( __GNUC__ ) typedef cl_uchar __cl_uchar8 __attribute__((vector_size(8))); typedef cl_char __cl_char8 __attribute__((vector_size(8))); typedef cl_ushort __cl_ushort4 __attribute__((vector_size(8))); typedef cl_short __cl_short4 __attribute__((vector_size(8))); typedef cl_uint __cl_uint2 __attribute__((vector_size(8))); typedef cl_int __cl_int2 __attribute__((vector_size(8))); typedef cl_ulong __cl_ulong1 __attribute__((vector_size(8))); typedef cl_long __cl_long1 __attribute__((vector_size(8))); typedef cl_float __cl_float2 __attribute__((vector_size(8))); #else typedef __m64 __cl_uchar8; typedef __m64 __cl_char8; typedef __m64 __cl_ushort4; typedef __m64 __cl_short4; typedef __m64 __cl_uint2; typedef __m64 __cl_int2; typedef __m64 __cl_ulong1; typedef __m64 __cl_long1; typedef __m64 __cl_float2; #endif #define __CL_UCHAR8__ 1 #define __CL_CHAR8__ 1 #define __CL_USHORT4__ 1 #define __CL_SHORT4__ 1 #define __CL_INT2__ 1 #define __CL_UINT2__ 1 #define __CL_ULONG1__ 1 #define __CL_LONG1__ 1 #define __CL_FLOAT2__ 1 #endif #if defined( __AVX__ ) #if defined( __MINGW64__ ) #include #else #include #endif #if defined( __GNUC__ ) typedef cl_float __cl_float8 __attribute__((vector_size(32))); typedef cl_double __cl_double4 __attribute__((vector_size(32))); #else typedef __m256 __cl_float8; typedef __m256d __cl_double4; #endif #define __CL_FLOAT8__ 1 #define __CL_DOUBLE4__ 1 #endif /* Define alignment keys */ #if defined( __GNUC__ ) #define CL_ALIGNED(_x) __attribute__ ((aligned(_x))) #elif defined( _WIN32) && (_MSC_VER) /* Alignment keys neutered on windows because MSVC can't swallow function arguments with alignment requirements */ /* http://msdn.microsoft.com/en-us/library/373ak2y1%28VS.71%29.aspx */ /* #include */ /* #define CL_ALIGNED(_x) _CRT_ALIGN(_x) */ #define CL_ALIGNED(_x) #else #warning Need to implement some method to align data here #define CL_ALIGNED(_x) #endif /* Indicate whether .xyzw, .s0123 and .hi.lo are supported */ #if defined( __GNUC__) && ! defined( __STRICT_ANSI__ ) /* .xyzw and .s0123...{f|F} are supported */ #define CL_HAS_NAMED_VECTOR_FIELDS 1 /* .hi and .lo are supported */ #define CL_HAS_HI_LO_VECTOR_FIELDS 1 #endif /* Define cl_vector types */ /* ---- cl_charn ---- */ typedef union { cl_char CL_ALIGNED(2) s[2]; #if defined( __GNUC__) && ! defined( __STRICT_ANSI__ ) __extension__ struct{ cl_char x, y; }; __extension__ struct{ cl_char s0, s1; }; __extension__ struct{ cl_char lo, hi; }; #endif #if defined( __CL_CHAR2__) __cl_char2 v2; #endif }cl_char2; typedef union { cl_char CL_ALIGNED(4) s[4]; #if defined( __GNUC__) && ! defined( __STRICT_ANSI__ ) __extension__ struct{ cl_char x, y, z, w; }; __extension__ struct{ cl_char s0, s1, s2, s3; }; __extension__ struct{ cl_char2 lo, hi; }; #endif #if defined( __CL_CHAR2__) __cl_char2 v2[2]; #endif #if defined( __CL_CHAR4__) __cl_char4 v4; #endif }cl_char4; /* cl_char3 is identical in size, alignment and behavior to cl_char4. See section 6.1.5. */ typedef cl_char4 cl_char3; typedef union { cl_char CL_ALIGNED(8) s[8]; #if defined( __GNUC__) && ! defined( __STRICT_ANSI__ ) __extension__ struct{ cl_char x, y, z, w; }; __extension__ struct{ cl_char s0, s1, s2, s3, s4, s5, s6, s7; }; __extension__ struct{ cl_char4 lo, hi; }; #endif #if defined( __CL_CHAR2__) __cl_char2 v2[4]; #endif #if defined( __CL_CHAR4__) __cl_char4 v4[2]; #endif #if defined( __CL_CHAR8__ ) __cl_char8 v8; #endif }cl_char8; typedef union { cl_char CL_ALIGNED(16) s[16]; #if defined( __GNUC__) && ! defined( __STRICT_ANSI__ ) __extension__ struct{ cl_char x, y, z, w, __spacer4, __spacer5, __spacer6, __spacer7, __spacer8, __spacer9, sa, sb, sc, sd, se, sf; }; __extension__ struct{ cl_char s0, s1, s2, s3, s4, s5, s6, s7, s8, s9, sA, sB, sC, sD, sE, sF; }; __extension__ struct{ cl_char8 lo, hi; }; #endif #if defined( __CL_CHAR2__) __cl_char2 v2[8]; #endif #if defined( __CL_CHAR4__) __cl_char4 v4[4]; #endif #if defined( __CL_CHAR8__ ) __cl_char8 v8[2]; #endif #if defined( __CL_CHAR16__ ) __cl_char16 v16; #endif }cl_char16; /* ---- cl_ucharn ---- */ typedef union { cl_uchar CL_ALIGNED(2) s[2]; #if defined( __GNUC__) && ! defined( __STRICT_ANSI__ ) __extension__ struct{ cl_uchar x, y; }; __extension__ struct{ cl_uchar s0, s1; }; __extension__ struct{ cl_uchar lo, hi; }; #endif #if defined( __cl_uchar2__) __cl_uchar2 v2; #endif }cl_uchar2; typedef union { cl_uchar CL_ALIGNED(4) s[4]; #if defined( __GNUC__) && ! defined( __STRICT_ANSI__ ) __extension__ struct{ cl_uchar x, y, z, w; }; __extension__ struct{ cl_uchar s0, s1, s2, s3; }; __extension__ struct{ cl_uchar2 lo, hi; }; #endif #if defined( __CL_UCHAR2__) __cl_uchar2 v2[2]; #endif #if defined( __CL_UCHAR4__) __cl_uchar4 v4; #endif }cl_uchar4; /* cl_uchar3 is identical in size, alignment and behavior to cl_uchar4. See section 6.1.5. */ typedef cl_uchar4 cl_uchar3; typedef union { cl_uchar CL_ALIGNED(8) s[8]; #if defined( __GNUC__) && ! defined( __STRICT_ANSI__ ) __extension__ struct{ cl_uchar x, y, z, w; }; __extension__ struct{ cl_uchar s0, s1, s2, s3, s4, s5, s6, s7; }; __extension__ struct{ cl_uchar4 lo, hi; }; #endif #if defined( __CL_UCHAR2__) __cl_uchar2 v2[4]; #endif #if defined( __CL_UCHAR4__) __cl_uchar4 v4[2]; #endif #if defined( __CL_UCHAR8__ ) __cl_uchar8 v8; #endif }cl_uchar8; typedef union { cl_uchar CL_ALIGNED(16) s[16]; #if defined( __GNUC__) && ! defined( __STRICT_ANSI__ ) __extension__ struct{ cl_uchar x, y, z, w, __spacer4, __spacer5, __spacer6, __spacer7, __spacer8, __spacer9, sa, sb, sc, sd, se, sf; }; __extension__ struct{ cl_uchar s0, s1, s2, s3, s4, s5, s6, s7, s8, s9, sA, sB, sC, sD, sE, sF; }; __extension__ struct{ cl_uchar8 lo, hi; }; #endif #if defined( __CL_UCHAR2__) __cl_uchar2 v2[8]; #endif #if defined( __CL_UCHAR4__) __cl_uchar4 v4[4]; #endif #if defined( __CL_UCHAR8__ ) __cl_uchar8 v8[2]; #endif #if defined( __CL_UCHAR16__ ) __cl_uchar16 v16; #endif }cl_uchar16; /* ---- cl_shortn ---- */ typedef union { cl_short CL_ALIGNED(4) s[2]; #if defined( __GNUC__) && ! defined( __STRICT_ANSI__ ) __extension__ struct{ cl_short x, y; }; __extension__ struct{ cl_short s0, s1; }; __extension__ struct{ cl_short lo, hi; }; #endif #if defined( __CL_SHORT2__) __cl_short2 v2; #endif }cl_short2; typedef union { cl_short CL_ALIGNED(8) s[4]; #if defined( __GNUC__) && ! defined( __STRICT_ANSI__ ) __extension__ struct{ cl_short x, y, z, w; }; __extension__ struct{ cl_short s0, s1, s2, s3; }; __extension__ struct{ cl_short2 lo, hi; }; #endif #if defined( __CL_SHORT2__) __cl_short2 v2[2]; #endif #if defined( __CL_SHORT4__) __cl_short4 v4; #endif }cl_short4; /* cl_short3 is identical in size, alignment and behavior to cl_short4. See section 6.1.5. */ typedef cl_short4 cl_short3; typedef union { cl_short CL_ALIGNED(16) s[8]; #if defined( __GNUC__) && ! defined( __STRICT_ANSI__ ) __extension__ struct{ cl_short x, y, z, w; }; __extension__ struct{ cl_short s0, s1, s2, s3, s4, s5, s6, s7; }; __extension__ struct{ cl_short4 lo, hi; }; #endif #if defined( __CL_SHORT2__) __cl_short2 v2[4]; #endif #if defined( __CL_SHORT4__) __cl_short4 v4[2]; #endif #if defined( __CL_SHORT8__ ) __cl_short8 v8; #endif }cl_short8; typedef union { cl_short CL_ALIGNED(32) s[16]; #if defined( __GNUC__) && ! defined( __STRICT_ANSI__ ) __extension__ struct{ cl_short x, y, z, w, __spacer4, __spacer5, __spacer6, __spacer7, __spacer8, __spacer9, sa, sb, sc, sd, se, sf; }; __extension__ struct{ cl_short s0, s1, s2, s3, s4, s5, s6, s7, s8, s9, sA, sB, sC, sD, sE, sF; }; __extension__ struct{ cl_short8 lo, hi; }; #endif #if defined( __CL_SHORT2__) __cl_short2 v2[8]; #endif #if defined( __CL_SHORT4__) __cl_short4 v4[4]; #endif #if defined( __CL_SHORT8__ ) __cl_short8 v8[2]; #endif #if defined( __CL_SHORT16__ ) __cl_short16 v16; #endif }cl_short16; /* ---- cl_ushortn ---- */ typedef union { cl_ushort CL_ALIGNED(4) s[2]; #if defined( __GNUC__) && ! defined( __STRICT_ANSI__ ) __extension__ struct{ cl_ushort x, y; }; __extension__ struct{ cl_ushort s0, s1; }; __extension__ struct{ cl_ushort lo, hi; }; #endif #if defined( __CL_USHORT2__) __cl_ushort2 v2; #endif }cl_ushort2; typedef union { cl_ushort CL_ALIGNED(8) s[4]; #if defined( __GNUC__) && ! defined( __STRICT_ANSI__ ) __extension__ struct{ cl_ushort x, y, z, w; }; __extension__ struct{ cl_ushort s0, s1, s2, s3; }; __extension__ struct{ cl_ushort2 lo, hi; }; #endif #if defined( __CL_USHORT2__) __cl_ushort2 v2[2]; #endif #if defined( __CL_USHORT4__) __cl_ushort4 v4; #endif }cl_ushort4; /* cl_ushort3 is identical in size, alignment and behavior to cl_ushort4. See section 6.1.5. */ typedef cl_ushort4 cl_ushort3; typedef union { cl_ushort CL_ALIGNED(16) s[8]; #if defined( __GNUC__) && ! defined( __STRICT_ANSI__ ) __extension__ struct{ cl_ushort x, y, z, w; }; __extension__ struct{ cl_ushort s0, s1, s2, s3, s4, s5, s6, s7; }; __extension__ struct{ cl_ushort4 lo, hi; }; #endif #if defined( __CL_USHORT2__) __cl_ushort2 v2[4]; #endif #if defined( __CL_USHORT4__) __cl_ushort4 v4[2]; #endif #if defined( __CL_USHORT8__ ) __cl_ushort8 v8; #endif }cl_ushort8; typedef union { cl_ushort CL_ALIGNED(32) s[16]; #if defined( __GNUC__) && ! defined( __STRICT_ANSI__ ) __extension__ struct{ cl_ushort x, y, z, w, __spacer4, __spacer5, __spacer6, __spacer7, __spacer8, __spacer9, sa, sb, sc, sd, se, sf; }; __extension__ struct{ cl_ushort s0, s1, s2, s3, s4, s5, s6, s7, s8, s9, sA, sB, sC, sD, sE, sF; }; __extension__ struct{ cl_ushort8 lo, hi; }; #endif #if defined( __CL_USHORT2__) __cl_ushort2 v2[8]; #endif #if defined( __CL_USHORT4__) __cl_ushort4 v4[4]; #endif #if defined( __CL_USHORT8__ ) __cl_ushort8 v8[2]; #endif #if defined( __CL_USHORT16__ ) __cl_ushort16 v16; #endif }cl_ushort16; /* ---- cl_intn ---- */ typedef union { cl_int CL_ALIGNED(8) s[2]; #if defined( __GNUC__) && ! defined( __STRICT_ANSI__ ) __extension__ struct{ cl_int x, y; }; __extension__ struct{ cl_int s0, s1; }; __extension__ struct{ cl_int lo, hi; }; #endif #if defined( __CL_INT2__) __cl_int2 v2; #endif }cl_int2; typedef union { cl_int CL_ALIGNED(16) s[4]; #if defined( __GNUC__) && ! defined( __STRICT_ANSI__ ) __extension__ struct{ cl_int x, y, z, w; }; __extension__ struct{ cl_int s0, s1, s2, s3; }; __extension__ struct{ cl_int2 lo, hi; }; #endif #if defined( __CL_INT2__) __cl_int2 v2[2]; #endif #if defined( __CL_INT4__) __cl_int4 v4; #endif }cl_int4; /* cl_int3 is identical in size, alignment and behavior to cl_int4. See section 6.1.5. */ typedef cl_int4 cl_int3; typedef union { cl_int CL_ALIGNED(32) s[8]; #if defined( __GNUC__) && ! defined( __STRICT_ANSI__ ) __extension__ struct{ cl_int x, y, z, w; }; __extension__ struct{ cl_int s0, s1, s2, s3, s4, s5, s6, s7; }; __extension__ struct{ cl_int4 lo, hi; }; #endif #if defined( __CL_INT2__) __cl_int2 v2[4]; #endif #if defined( __CL_INT4__) __cl_int4 v4[2]; #endif #if defined( __CL_INT8__ ) __cl_int8 v8; #endif }cl_int8; typedef union { cl_int CL_ALIGNED(64) s[16]; #if defined( __GNUC__) && ! defined( __STRICT_ANSI__ ) __extension__ struct{ cl_int x, y, z, w, __spacer4, __spacer5, __spacer6, __spacer7, __spacer8, __spacer9, sa, sb, sc, sd, se, sf; }; __extension__ struct{ cl_int s0, s1, s2, s3, s4, s5, s6, s7, s8, s9, sA, sB, sC, sD, sE, sF; }; __extension__ struct{ cl_int8 lo, hi; }; #endif #if defined( __CL_INT2__) __cl_int2 v2[8]; #endif #if defined( __CL_INT4__) __cl_int4 v4[4]; #endif #if defined( __CL_INT8__ ) __cl_int8 v8[2]; #endif #if defined( __CL_INT16__ ) __cl_int16 v16; #endif }cl_int16; /* ---- cl_uintn ---- */ typedef union { cl_uint CL_ALIGNED(8) s[2]; #if defined( __GNUC__) && ! defined( __STRICT_ANSI__ ) __extension__ struct{ cl_uint x, y; }; __extension__ struct{ cl_uint s0, s1; }; __extension__ struct{ cl_uint lo, hi; }; #endif #if defined( __CL_UINT2__) __cl_uint2 v2; #endif }cl_uint2; typedef union { cl_uint CL_ALIGNED(16) s[4]; #if defined( __GNUC__) && ! defined( __STRICT_ANSI__ ) __extension__ struct{ cl_uint x, y, z, w; }; __extension__ struct{ cl_uint s0, s1, s2, s3; }; __extension__ struct{ cl_uint2 lo, hi; }; #endif #if defined( __CL_UINT2__) __cl_uint2 v2[2]; #endif #if defined( __CL_UINT4__) __cl_uint4 v4; #endif }cl_uint4; /* cl_uint3 is identical in size, alignment and behavior to cl_uint4. See section 6.1.5. */ typedef cl_uint4 cl_uint3; typedef union { cl_uint CL_ALIGNED(32) s[8]; #if defined( __GNUC__) && ! defined( __STRICT_ANSI__ ) __extension__ struct{ cl_uint x, y, z, w; }; __extension__ struct{ cl_uint s0, s1, s2, s3, s4, s5, s6, s7; }; __extension__ struct{ cl_uint4 lo, hi; }; #endif #if defined( __CL_UINT2__) __cl_uint2 v2[4]; #endif #if defined( __CL_UINT4__) __cl_uint4 v4[2]; #endif #if defined( __CL_UINT8__ ) __cl_uint8 v8; #endif }cl_uint8; typedef union { cl_uint CL_ALIGNED(64) s[16]; #if defined( __GNUC__) && ! defined( __STRICT_ANSI__ ) __extension__ struct{ cl_uint x, y, z, w, __spacer4, __spacer5, __spacer6, __spacer7, __spacer8, __spacer9, sa, sb, sc, sd, se, sf; }; __extension__ struct{ cl_uint s0, s1, s2, s3, s4, s5, s6, s7, s8, s9, sA, sB, sC, sD, sE, sF; }; __extension__ struct{ cl_uint8 lo, hi; }; #endif #if defined( __CL_UINT2__) __cl_uint2 v2[8]; #endif #if defined( __CL_UINT4__) __cl_uint4 v4[4]; #endif #if defined( __CL_UINT8__ ) __cl_uint8 v8[2]; #endif #if defined( __CL_UINT16__ ) __cl_uint16 v16; #endif }cl_uint16; /* ---- cl_longn ---- */ typedef union { cl_long CL_ALIGNED(16) s[2]; #if defined( __GNUC__) && ! defined( __STRICT_ANSI__ ) __extension__ struct{ cl_long x, y; }; __extension__ struct{ cl_long s0, s1; }; __extension__ struct{ cl_long lo, hi; }; #endif #if defined( __CL_LONG2__) __cl_long2 v2; #endif }cl_long2; typedef union { cl_long CL_ALIGNED(32) s[4]; #if defined( __GNUC__) && ! defined( __STRICT_ANSI__ ) __extension__ struct{ cl_long x, y, z, w; }; __extension__ struct{ cl_long s0, s1, s2, s3; }; __extension__ struct{ cl_long2 lo, hi; }; #endif #if defined( __CL_LONG2__) __cl_long2 v2[2]; #endif #if defined( __CL_LONG4__) __cl_long4 v4; #endif }cl_long4; /* cl_long3 is identical in size, alignment and behavior to cl_long4. See section 6.1.5. */ typedef cl_long4 cl_long3; typedef union { cl_long CL_ALIGNED(64) s[8]; #if defined( __GNUC__) && ! defined( __STRICT_ANSI__ ) __extension__ struct{ cl_long x, y, z, w; }; __extension__ struct{ cl_long s0, s1, s2, s3, s4, s5, s6, s7; }; __extension__ struct{ cl_long4 lo, hi; }; #endif #if defined( __CL_LONG2__) __cl_long2 v2[4]; #endif #if defined( __CL_LONG4__) __cl_long4 v4[2]; #endif #if defined( __CL_LONG8__ ) __cl_long8 v8; #endif }cl_long8; typedef union { cl_long CL_ALIGNED(128) s[16]; #if defined( __GNUC__) && ! defined( __STRICT_ANSI__ ) __extension__ struct{ cl_long x, y, z, w, __spacer4, __spacer5, __spacer6, __spacer7, __spacer8, __spacer9, sa, sb, sc, sd, se, sf; }; __extension__ struct{ cl_long s0, s1, s2, s3, s4, s5, s6, s7, s8, s9, sA, sB, sC, sD, sE, sF; }; __extension__ struct{ cl_long8 lo, hi; }; #endif #if defined( __CL_LONG2__) __cl_long2 v2[8]; #endif #if defined( __CL_LONG4__) __cl_long4 v4[4]; #endif #if defined( __CL_LONG8__ ) __cl_long8 v8[2]; #endif #if defined( __CL_LONG16__ ) __cl_long16 v16; #endif }cl_long16; /* ---- cl_ulongn ---- */ typedef union { cl_ulong CL_ALIGNED(16) s[2]; #if defined( __GNUC__) && ! defined( __STRICT_ANSI__ ) __extension__ struct{ cl_ulong x, y; }; __extension__ struct{ cl_ulong s0, s1; }; __extension__ struct{ cl_ulong lo, hi; }; #endif #if defined( __CL_ULONG2__) __cl_ulong2 v2; #endif }cl_ulong2; typedef union { cl_ulong CL_ALIGNED(32) s[4]; #if defined( __GNUC__) && ! defined( __STRICT_ANSI__ ) __extension__ struct{ cl_ulong x, y, z, w; }; __extension__ struct{ cl_ulong s0, s1, s2, s3; }; __extension__ struct{ cl_ulong2 lo, hi; }; #endif #if defined( __CL_ULONG2__) __cl_ulong2 v2[2]; #endif #if defined( __CL_ULONG4__) __cl_ulong4 v4; #endif }cl_ulong4; /* cl_ulong3 is identical in size, alignment and behavior to cl_ulong4. See section 6.1.5. */ typedef cl_ulong4 cl_ulong3; typedef union { cl_ulong CL_ALIGNED(64) s[8]; #if defined( __GNUC__) && ! defined( __STRICT_ANSI__ ) __extension__ struct{ cl_ulong x, y, z, w; }; __extension__ struct{ cl_ulong s0, s1, s2, s3, s4, s5, s6, s7; }; __extension__ struct{ cl_ulong4 lo, hi; }; #endif #if defined( __CL_ULONG2__) __cl_ulong2 v2[4]; #endif #if defined( __CL_ULONG4__) __cl_ulong4 v4[2]; #endif #if defined( __CL_ULONG8__ ) __cl_ulong8 v8; #endif }cl_ulong8; typedef union { cl_ulong CL_ALIGNED(128) s[16]; #if defined( __GNUC__) && ! defined( __STRICT_ANSI__ ) __extension__ struct{ cl_ulong x, y, z, w, __spacer4, __spacer5, __spacer6, __spacer7, __spacer8, __spacer9, sa, sb, sc, sd, se, sf; }; __extension__ struct{ cl_ulong s0, s1, s2, s3, s4, s5, s6, s7, s8, s9, sA, sB, sC, sD, sE, sF; }; __extension__ struct{ cl_ulong8 lo, hi; }; #endif #if defined( __CL_ULONG2__) __cl_ulong2 v2[8]; #endif #if defined( __CL_ULONG4__) __cl_ulong4 v4[4]; #endif #if defined( __CL_ULONG8__ ) __cl_ulong8 v8[2]; #endif #if defined( __CL_ULONG16__ ) __cl_ulong16 v16; #endif }cl_ulong16; /* --- cl_floatn ---- */ typedef union { cl_float CL_ALIGNED(8) s[2]; #if defined( __GNUC__) && ! defined( __STRICT_ANSI__ ) __extension__ struct{ cl_float x, y; }; __extension__ struct{ cl_float s0, s1; }; __extension__ struct{ cl_float lo, hi; }; #endif #if defined( __CL_FLOAT2__) __cl_float2 v2; #endif }cl_float2; typedef union { cl_float CL_ALIGNED(16) s[4]; #if defined( __GNUC__) && ! defined( __STRICT_ANSI__ ) __extension__ struct{ cl_float x, y, z, w; }; __extension__ struct{ cl_float s0, s1, s2, s3; }; __extension__ struct{ cl_float2 lo, hi; }; #endif #if defined( __CL_FLOAT2__) __cl_float2 v2[2]; #endif #if defined( __CL_FLOAT4__) __cl_float4 v4; #endif }cl_float4; /* cl_float3 is identical in size, alignment and behavior to cl_float4. See section 6.1.5. */ typedef cl_float4 cl_float3; typedef union { cl_float CL_ALIGNED(32) s[8]; #if defined( __GNUC__) && ! defined( __STRICT_ANSI__ ) __extension__ struct{ cl_float x, y, z, w; }; __extension__ struct{ cl_float s0, s1, s2, s3, s4, s5, s6, s7; }; __extension__ struct{ cl_float4 lo, hi; }; #endif #if defined( __CL_FLOAT2__) __cl_float2 v2[4]; #endif #if defined( __CL_FLOAT4__) __cl_float4 v4[2]; #endif #if defined( __CL_FLOAT8__ ) __cl_float8 v8; #endif }cl_float8; typedef union { cl_float CL_ALIGNED(64) s[16]; #if defined( __GNUC__) && ! defined( __STRICT_ANSI__ ) __extension__ struct{ cl_float x, y, z, w, __spacer4, __spacer5, __spacer6, __spacer7, __spacer8, __spacer9, sa, sb, sc, sd, se, sf; }; __extension__ struct{ cl_float s0, s1, s2, s3, s4, s5, s6, s7, s8, s9, sA, sB, sC, sD, sE, sF; }; __extension__ struct{ cl_float8 lo, hi; }; #endif #if defined( __CL_FLOAT2__) __cl_float2 v2[8]; #endif #if defined( __CL_FLOAT4__) __cl_float4 v4[4]; #endif #if defined( __CL_FLOAT8__ ) __cl_float8 v8[2]; #endif #if defined( __CL_FLOAT16__ ) __cl_float16 v16; #endif }cl_float16; /* --- cl_doublen ---- */ typedef union { cl_double CL_ALIGNED(16) s[2]; #if defined( __GNUC__) && ! defined( __STRICT_ANSI__ ) __extension__ struct{ cl_double x, y; }; __extension__ struct{ cl_double s0, s1; }; __extension__ struct{ cl_double lo, hi; }; #endif #if defined( __CL_DOUBLE2__) __cl_double2 v2; #endif }cl_double2; typedef union { cl_double CL_ALIGNED(32) s[4]; #if defined( __GNUC__) && ! defined( __STRICT_ANSI__ ) __extension__ struct{ cl_double x, y, z, w; }; __extension__ struct{ cl_double s0, s1, s2, s3; }; __extension__ struct{ cl_double2 lo, hi; }; #endif #if defined( __CL_DOUBLE2__) __cl_double2 v2[2]; #endif #if defined( __CL_DOUBLE4__) __cl_double4 v4; #endif }cl_double4; /* cl_double3 is identical in size, alignment and behavior to cl_double4. See section 6.1.5. */ typedef cl_double4 cl_double3; typedef union { cl_double CL_ALIGNED(64) s[8]; #if defined( __GNUC__) && ! defined( __STRICT_ANSI__ ) __extension__ struct{ cl_double x, y, z, w; }; __extension__ struct{ cl_double s0, s1, s2, s3, s4, s5, s6, s7; }; __extension__ struct{ cl_double4 lo, hi; }; #endif #if defined( __CL_DOUBLE2__) __cl_double2 v2[4]; #endif #if defined( __CL_DOUBLE4__) __cl_double4 v4[2]; #endif #if defined( __CL_DOUBLE8__ ) __cl_double8 v8; #endif }cl_double8; typedef union { cl_double CL_ALIGNED(128) s[16]; #if defined( __GNUC__) && ! defined( __STRICT_ANSI__ ) __extension__ struct{ cl_double x, y, z, w, __spacer4, __spacer5, __spacer6, __spacer7, __spacer8, __spacer9, sa, sb, sc, sd, se, sf; }; __extension__ struct{ cl_double s0, s1, s2, s3, s4, s5, s6, s7, s8, s9, sA, sB, sC, sD, sE, sF; }; __extension__ struct{ cl_double8 lo, hi; }; #endif #if defined( __CL_DOUBLE2__) __cl_double2 v2[8]; #endif #if defined( __CL_DOUBLE4__) __cl_double4 v4[4]; #endif #if defined( __CL_DOUBLE8__ ) __cl_double8 v8[2]; #endif #if defined( __CL_DOUBLE16__ ) __cl_double16 v16; #endif }cl_double16; /* Macro to facilitate debugging * Usage: * Place CL_PROGRAM_STRING_DEBUG_INFO on the line before the first line of your source. * The first line ends with: CL_PROGRAM_STRING_BEGIN \" * Each line thereafter of OpenCL C source must end with: \n\ * The last line ends in "; * * Example: * * const char *my_program = CL_PROGRAM_STRING_BEGIN "\ * kernel void foo( int a, float * b ) \n\ * { \n\ * // my comment \n\ * *b[ get_global_id(0)] = a; \n\ * } \n\ * "; * * This should correctly set up the line, (column) and file information for your source * string so you can do source level debugging. */ #define __CL_STRINGIFY( _x ) # _x #define _CL_STRINGIFY( _x ) __CL_STRINGIFY( _x ) #define CL_PROGRAM_STRING_DEBUG_INFO "#line " _CL_STRINGIFY(__LINE__) " \"" __FILE__ "\" \n\n" #ifdef __cplusplus } #endif #endif /* __CL_PLATFORM_H */ ugene-1.9.8/src/include/opencl/legacy/cl.h0000644000175000017500000014150711651544336017037 0ustar ilyailya/******************************************************************************* * Copyright (c) 2008-2010 The Khronos Group Inc. * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and/or associated documentation files (the * "Materials"), to deal in the Materials without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Materials, and to * permit persons to whom the Materials are furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Materials. * * THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS. ******************************************************************************/ /* $Revision: 11708 $ on $Date: 2010-06-14 12:06:24 +0530 (Mon, 14 Jun 2010) $ */ #ifndef __OPENCL_CL_H #define __OPENCL_CL_H #include "cl_platform.h" #ifdef __cplusplus extern "C" { #endif /******************************************************************************/ typedef struct _cl_platform_id * cl_platform_id; typedef struct _cl_device_id * cl_device_id; typedef struct _cl_context * cl_context; typedef struct _cl_command_queue * cl_command_queue; typedef struct _cl_mem * cl_mem; typedef struct _cl_program * cl_program; typedef struct _cl_kernel * cl_kernel; typedef struct _cl_event * cl_event; typedef struct _cl_sampler * cl_sampler; typedef cl_uint cl_bool; /* WARNING! Unlike cl_ types in cl_platform.h, cl_bool is not guaranteed to be the same size as the bool in kernels. */ typedef cl_ulong cl_bitfield; typedef cl_bitfield cl_device_type; typedef cl_uint cl_platform_info; typedef cl_uint cl_device_info; typedef cl_bitfield cl_device_fp_config; typedef cl_uint cl_device_mem_cache_type; typedef cl_uint cl_device_local_mem_type; typedef cl_bitfield cl_device_exec_capabilities; typedef cl_bitfield cl_command_queue_properties; typedef intptr_t cl_context_properties; typedef cl_uint cl_context_info; typedef cl_uint cl_command_queue_info; typedef cl_uint cl_channel_order; typedef cl_uint cl_channel_type; typedef cl_bitfield cl_mem_flags; typedef cl_uint cl_mem_object_type; typedef cl_uint cl_mem_info; typedef cl_uint cl_image_info; typedef cl_uint cl_buffer_create_type; typedef cl_uint cl_addressing_mode; typedef cl_uint cl_filter_mode; typedef cl_uint cl_sampler_info; typedef cl_bitfield cl_map_flags; typedef cl_uint cl_program_info; typedef cl_uint cl_program_build_info; typedef cl_int cl_build_status; typedef cl_uint cl_kernel_info; typedef cl_uint cl_kernel_work_group_info; typedef cl_uint cl_event_info; typedef cl_uint cl_command_type; typedef cl_uint cl_profiling_info; typedef struct _cl_image_format { cl_channel_order image_channel_order; cl_channel_type image_channel_data_type; } cl_image_format; typedef struct _cl_buffer_region { size_t origin; size_t size; } cl_buffer_region; /******************************************************************************/ /* Error Codes */ #define CL_SUCCESS 0 #define CL_DEVICE_NOT_FOUND -1 #define CL_DEVICE_NOT_AVAILABLE -2 #define CL_COMPILER_NOT_AVAILABLE -3 #define CL_MEM_OBJECT_ALLOCATION_FAILURE -4 #define CL_OUT_OF_RESOURCES -5 #define CL_OUT_OF_HOST_MEMORY -6 #define CL_PROFILING_INFO_NOT_AVAILABLE -7 #define CL_MEM_COPY_OVERLAP -8 #define CL_IMAGE_FORMAT_MISMATCH -9 #define CL_IMAGE_FORMAT_NOT_SUPPORTED -10 #define CL_BUILD_PROGRAM_FAILURE -11 #define CL_MAP_FAILURE -12 #define CL_MISALIGNED_SUB_BUFFER_OFFSET -13 #define CL_EXEC_STATUS_ERROR_FOR_EVENTS_IN_WAIT_LIST -14 #define CL_INVALID_VALUE -30 #define CL_INVALID_DEVICE_TYPE -31 #define CL_INVALID_PLATFORM -32 #define CL_INVALID_DEVICE -33 #define CL_INVALID_CONTEXT -34 #define CL_INVALID_QUEUE_PROPERTIES -35 #define CL_INVALID_COMMAND_QUEUE -36 #define CL_INVALID_HOST_PTR -37 #define CL_INVALID_MEM_OBJECT -38 #define CL_INVALID_IMAGE_FORMAT_DESCRIPTOR -39 #define CL_INVALID_IMAGE_SIZE -40 #define CL_INVALID_SAMPLER -41 #define CL_INVALID_BINARY -42 #define CL_INVALID_BUILD_OPTIONS -43 #define CL_INVALID_PROGRAM -44 #define CL_INVALID_PROGRAM_EXECUTABLE -45 #define CL_INVALID_KERNEL_NAME -46 #define CL_INVALID_KERNEL_DEFINITION -47 #define CL_INVALID_KERNEL -48 #define CL_INVALID_ARG_INDEX -49 #define CL_INVALID_ARG_VALUE -50 #define CL_INVALID_ARG_SIZE -51 #define CL_INVALID_KERNEL_ARGS -52 #define CL_INVALID_WORK_DIMENSION -53 #define CL_INVALID_WORK_GROUP_SIZE -54 #define CL_INVALID_WORK_ITEM_SIZE -55 #define CL_INVALID_GLOBAL_OFFSET -56 #define CL_INVALID_EVENT_WAIT_LIST -57 #define CL_INVALID_EVENT -58 #define CL_INVALID_OPERATION -59 #define CL_INVALID_GL_OBJECT -60 #define CL_INVALID_BUFFER_SIZE -61 #define CL_INVALID_MIP_LEVEL -62 #define CL_INVALID_GLOBAL_WORK_SIZE -63 /* OpenCL Version */ #define CL_VERSION_1_0 1 #define CL_VERSION_1_1 1 /* cl_bool */ #define CL_FALSE 0 #define CL_TRUE 1 /* cl_platform_info */ #define CL_PLATFORM_PROFILE 0x0900 #define CL_PLATFORM_VERSION 0x0901 #define CL_PLATFORM_NAME 0x0902 #define CL_PLATFORM_VENDOR 0x0903 #define CL_PLATFORM_EXTENSIONS 0x0904 /* cl_device_type - bitfield */ #define CL_DEVICE_TYPE_DEFAULT (1 << 0) #define CL_DEVICE_TYPE_CPU (1 << 1) #define CL_DEVICE_TYPE_GPU (1 << 2) #define CL_DEVICE_TYPE_ACCELERATOR (1 << 3) #define CL_DEVICE_TYPE_ALL 0xFFFFFFFF /* cl_device_info */ #define CL_DEVICE_TYPE 0x1000 #define CL_DEVICE_VENDOR_ID 0x1001 #define CL_DEVICE_MAX_COMPUTE_UNITS 0x1002 #define CL_DEVICE_MAX_WORK_ITEM_DIMENSIONS 0x1003 #define CL_DEVICE_MAX_WORK_GROUP_SIZE 0x1004 #define CL_DEVICE_MAX_WORK_ITEM_SIZES 0x1005 #define CL_DEVICE_PREFERRED_VECTOR_WIDTH_CHAR 0x1006 #define CL_DEVICE_PREFERRED_VECTOR_WIDTH_SHORT 0x1007 #define CL_DEVICE_PREFERRED_VECTOR_WIDTH_INT 0x1008 #define CL_DEVICE_PREFERRED_VECTOR_WIDTH_LONG 0x1009 #define CL_DEVICE_PREFERRED_VECTOR_WIDTH_FLOAT 0x100A #define CL_DEVICE_PREFERRED_VECTOR_WIDTH_DOUBLE 0x100B #define CL_DEVICE_MAX_CLOCK_FREQUENCY 0x100C #define CL_DEVICE_ADDRESS_BITS 0x100D #define CL_DEVICE_MAX_READ_IMAGE_ARGS 0x100E #define CL_DEVICE_MAX_WRITE_IMAGE_ARGS 0x100F #define CL_DEVICE_MAX_MEM_ALLOC_SIZE 0x1010 #define CL_DEVICE_IMAGE2D_MAX_WIDTH 0x1011 #define CL_DEVICE_IMAGE2D_MAX_HEIGHT 0x1012 #define CL_DEVICE_IMAGE3D_MAX_WIDTH 0x1013 #define CL_DEVICE_IMAGE3D_MAX_HEIGHT 0x1014 #define CL_DEVICE_IMAGE3D_MAX_DEPTH 0x1015 #define CL_DEVICE_IMAGE_SUPPORT 0x1016 #define CL_DEVICE_MAX_PARAMETER_SIZE 0x1017 #define CL_DEVICE_MAX_SAMPLERS 0x1018 #define CL_DEVICE_MEM_BASE_ADDR_ALIGN 0x1019 #define CL_DEVICE_MIN_DATA_TYPE_ALIGN_SIZE 0x101A #define CL_DEVICE_SINGLE_FP_CONFIG 0x101B #define CL_DEVICE_GLOBAL_MEM_CACHE_TYPE 0x101C #define CL_DEVICE_GLOBAL_MEM_CACHELINE_SIZE 0x101D #define CL_DEVICE_GLOBAL_MEM_CACHE_SIZE 0x101E #define CL_DEVICE_GLOBAL_MEM_SIZE 0x101F #define CL_DEVICE_MAX_CONSTANT_BUFFER_SIZE 0x1020 #define CL_DEVICE_MAX_CONSTANT_ARGS 0x1021 #define CL_DEVICE_LOCAL_MEM_TYPE 0x1022 #define CL_DEVICE_LOCAL_MEM_SIZE 0x1023 #define CL_DEVICE_ERROR_CORRECTION_SUPPORT 0x1024 #define CL_DEVICE_PROFILING_TIMER_RESOLUTION 0x1025 #define CL_DEVICE_ENDIAN_LITTLE 0x1026 #define CL_DEVICE_AVAILABLE 0x1027 #define CL_DEVICE_COMPILER_AVAILABLE 0x1028 #define CL_DEVICE_EXECUTION_CAPABILITIES 0x1029 #define CL_DEVICE_QUEUE_PROPERTIES 0x102A #define CL_DEVICE_NAME 0x102B #define CL_DEVICE_VENDOR 0x102C #define CL_DRIVER_VERSION 0x102D #define CL_DEVICE_PROFILE 0x102E #define CL_DEVICE_VERSION 0x102F #define CL_DEVICE_EXTENSIONS 0x1030 #define CL_DEVICE_PLATFORM 0x1031 /* 0x1032 reserved for CL_DEVICE_DOUBLE_FP_CONFIG */ /* 0x1033 reserved for CL_DEVICE_HALF_FP_CONFIG */ #define CL_DEVICE_PREFERRED_VECTOR_WIDTH_HALF 0x1034 #define CL_DEVICE_HOST_UNIFIED_MEMORY 0x1035 #define CL_DEVICE_NATIVE_VECTOR_WIDTH_CHAR 0x1036 #define CL_DEVICE_NATIVE_VECTOR_WIDTH_SHORT 0x1037 #define CL_DEVICE_NATIVE_VECTOR_WIDTH_INT 0x1038 #define CL_DEVICE_NATIVE_VECTOR_WIDTH_LONG 0x1039 #define CL_DEVICE_NATIVE_VECTOR_WIDTH_FLOAT 0x103A #define CL_DEVICE_NATIVE_VECTOR_WIDTH_DOUBLE 0x103B #define CL_DEVICE_NATIVE_VECTOR_WIDTH_HALF 0x103C #define CL_DEVICE_OPENCL_C_VERSION 0x103D /* cl_device_fp_config - bitfield */ #define CL_FP_DENORM (1 << 0) #define CL_FP_INF_NAN (1 << 1) #define CL_FP_ROUND_TO_NEAREST (1 << 2) #define CL_FP_ROUND_TO_ZERO (1 << 3) #define CL_FP_ROUND_TO_INF (1 << 4) #define CL_FP_FMA (1 << 5) #define CL_FP_SOFT_FLOAT (1 << 6) /* cl_device_mem_cache_type */ #define CL_NONE 0x0 #define CL_READ_ONLY_CACHE 0x1 #define CL_READ_WRITE_CACHE 0x2 /* cl_device_local_mem_type */ #define CL_LOCAL 0x1 #define CL_GLOBAL 0x2 /* cl_device_exec_capabilities - bitfield */ #define CL_EXEC_KERNEL (1 << 0) #define CL_EXEC_NATIVE_KERNEL (1 << 1) /* cl_command_queue_properties - bitfield */ #define CL_QUEUE_OUT_OF_ORDER_EXEC_MODE_ENABLE (1 << 0) #define CL_QUEUE_PROFILING_ENABLE (1 << 1) /* cl_context_info */ #define CL_CONTEXT_REFERENCE_COUNT 0x1080 #define CL_CONTEXT_DEVICES 0x1081 #define CL_CONTEXT_PROPERTIES 0x1082 #define CL_CONTEXT_NUM_DEVICES 0x1083 /* cl_context_info + cl_context_properties */ #define CL_CONTEXT_PLATFORM 0x1084 /* cl_command_queue_info */ #define CL_QUEUE_CONTEXT 0x1090 #define CL_QUEUE_DEVICE 0x1091 #define CL_QUEUE_REFERENCE_COUNT 0x1092 #define CL_QUEUE_PROPERTIES 0x1093 /* cl_mem_flags - bitfield */ #define CL_MEM_READ_WRITE (1 << 0) #define CL_MEM_WRITE_ONLY (1 << 1) #define CL_MEM_READ_ONLY (1 << 2) #define CL_MEM_USE_HOST_PTR (1 << 3) #define CL_MEM_ALLOC_HOST_PTR (1 << 4) #define CL_MEM_COPY_HOST_PTR (1 << 5) /* cl_channel_order */ #define CL_R 0x10B0 #define CL_A 0x10B1 #define CL_RG 0x10B2 #define CL_RA 0x10B3 #define CL_RGB 0x10B4 #define CL_RGBA 0x10B5 #define CL_BGRA 0x10B6 #define CL_ARGB 0x10B7 #define CL_INTENSITY 0x10B8 #define CL_LUMINANCE 0x10B9 #define CL_Rx 0x10BA #define CL_RGx 0x10BB #define CL_RGBx 0x10BC /* cl_channel_type */ #define CL_SNORM_INT8 0x10D0 #define CL_SNORM_INT16 0x10D1 #define CL_UNORM_INT8 0x10D2 #define CL_UNORM_INT16 0x10D3 #define CL_UNORM_SHORT_565 0x10D4 #define CL_UNORM_SHORT_555 0x10D5 #define CL_UNORM_INT_101010 0x10D6 #define CL_SIGNED_INT8 0x10D7 #define CL_SIGNED_INT16 0x10D8 #define CL_SIGNED_INT32 0x10D9 #define CL_UNSIGNED_INT8 0x10DA #define CL_UNSIGNED_INT16 0x10DB #define CL_UNSIGNED_INT32 0x10DC #define CL_HALF_FLOAT 0x10DD #define CL_FLOAT 0x10DE /* cl_mem_object_type */ #define CL_MEM_OBJECT_BUFFER 0x10F0 #define CL_MEM_OBJECT_IMAGE2D 0x10F1 #define CL_MEM_OBJECT_IMAGE3D 0x10F2 /* cl_mem_info */ #define CL_MEM_TYPE 0x1100 #define CL_MEM_FLAGS 0x1101 #define CL_MEM_SIZE 0x1102 #define CL_MEM_HOST_PTR 0x1103 #define CL_MEM_MAP_COUNT 0x1104 #define CL_MEM_REFERENCE_COUNT 0x1105 #define CL_MEM_CONTEXT 0x1106 #define CL_MEM_ASSOCIATED_MEMOBJECT 0x1107 #define CL_MEM_OFFSET 0x1108 /* cl_image_info */ #define CL_IMAGE_FORMAT 0x1110 #define CL_IMAGE_ELEMENT_SIZE 0x1111 #define CL_IMAGE_ROW_PITCH 0x1112 #define CL_IMAGE_SLICE_PITCH 0x1113 #define CL_IMAGE_WIDTH 0x1114 #define CL_IMAGE_HEIGHT 0x1115 #define CL_IMAGE_DEPTH 0x1116 /* cl_addressing_mode */ #define CL_ADDRESS_NONE 0x1130 #define CL_ADDRESS_CLAMP_TO_EDGE 0x1131 #define CL_ADDRESS_CLAMP 0x1132 #define CL_ADDRESS_REPEAT 0x1133 #define CL_ADDRESS_MIRRORED_REPEAT 0x1134 /* cl_filter_mode */ #define CL_FILTER_NEAREST 0x1140 #define CL_FILTER_LINEAR 0x1141 /* cl_sampler_info */ #define CL_SAMPLER_REFERENCE_COUNT 0x1150 #define CL_SAMPLER_CONTEXT 0x1151 #define CL_SAMPLER_NORMALIZED_COORDS 0x1152 #define CL_SAMPLER_ADDRESSING_MODE 0x1153 #define CL_SAMPLER_FILTER_MODE 0x1154 /* cl_map_flags - bitfield */ #define CL_MAP_READ (1 << 0) #define CL_MAP_WRITE (1 << 1) /* cl_program_info */ #define CL_PROGRAM_REFERENCE_COUNT 0x1160 #define CL_PROGRAM_CONTEXT 0x1161 #define CL_PROGRAM_NUM_DEVICES 0x1162 #define CL_PROGRAM_DEVICES 0x1163 #define CL_PROGRAM_SOURCE 0x1164 #define CL_PROGRAM_BINARY_SIZES 0x1165 #define CL_PROGRAM_BINARIES 0x1166 /* cl_program_build_info */ #define CL_PROGRAM_BUILD_STATUS 0x1181 #define CL_PROGRAM_BUILD_OPTIONS 0x1182 #define CL_PROGRAM_BUILD_LOG 0x1183 /* cl_build_status */ #define CL_BUILD_SUCCESS 0 #define CL_BUILD_NONE -1 #define CL_BUILD_ERROR -2 #define CL_BUILD_IN_PROGRESS -3 /* cl_kernel_info */ #define CL_KERNEL_FUNCTION_NAME 0x1190 #define CL_KERNEL_NUM_ARGS 0x1191 #define CL_KERNEL_REFERENCE_COUNT 0x1192 #define CL_KERNEL_CONTEXT 0x1193 #define CL_KERNEL_PROGRAM 0x1194 /* cl_kernel_work_group_info */ #define CL_KERNEL_WORK_GROUP_SIZE 0x11B0 #define CL_KERNEL_COMPILE_WORK_GROUP_SIZE 0x11B1 #define CL_KERNEL_LOCAL_MEM_SIZE 0x11B2 #define CL_KERNEL_PREFERRED_WORK_GROUP_SIZE_MULTIPLE 0x11B3 #define CL_KERNEL_PRIVATE_MEM_SIZE 0x11B4 /* cl_event_info */ #define CL_EVENT_COMMAND_QUEUE 0x11D0 #define CL_EVENT_COMMAND_TYPE 0x11D1 #define CL_EVENT_REFERENCE_COUNT 0x11D2 #define CL_EVENT_COMMAND_EXECUTION_STATUS 0x11D3 #define CL_EVENT_CONTEXT 0x11D4 /* cl_command_type */ #define CL_COMMAND_NDRANGE_KERNEL 0x11F0 #define CL_COMMAND_TASK 0x11F1 #define CL_COMMAND_NATIVE_KERNEL 0x11F2 #define CL_COMMAND_READ_BUFFER 0x11F3 #define CL_COMMAND_WRITE_BUFFER 0x11F4 #define CL_COMMAND_COPY_BUFFER 0x11F5 #define CL_COMMAND_READ_IMAGE 0x11F6 #define CL_COMMAND_WRITE_IMAGE 0x11F7 #define CL_COMMAND_COPY_IMAGE 0x11F8 #define CL_COMMAND_COPY_IMAGE_TO_BUFFER 0x11F9 #define CL_COMMAND_COPY_BUFFER_TO_IMAGE 0x11FA #define CL_COMMAND_MAP_BUFFER 0x11FB #define CL_COMMAND_MAP_IMAGE 0x11FC #define CL_COMMAND_UNMAP_MEM_OBJECT 0x11FD #define CL_COMMAND_MARKER 0x11FE #define CL_COMMAND_ACQUIRE_GL_OBJECTS 0x11FF #define CL_COMMAND_RELEASE_GL_OBJECTS 0x1200 #define CL_COMMAND_READ_BUFFER_RECT 0x1201 #define CL_COMMAND_WRITE_BUFFER_RECT 0x1202 #define CL_COMMAND_COPY_BUFFER_RECT 0x1203 #define CL_COMMAND_USER 0x1204 /* command execution status */ #define CL_COMPLETE 0x0 #define CL_RUNNING 0x1 #define CL_SUBMITTED 0x2 #define CL_QUEUED 0x3 /* cl_buffer_create_type */ #define CL_BUFFER_CREATE_TYPE_REGION 0x1220 /* cl_profiling_info */ #define CL_PROFILING_COMMAND_QUEUED 0x1280 #define CL_PROFILING_COMMAND_SUBMIT 0x1281 #define CL_PROFILING_COMMAND_START 0x1282 #define CL_PROFILING_COMMAND_END 0x1283 /********************************************************************************************************/ /* Platform API */ extern CL_API_ENTRY cl_int CL_API_CALL clGetPlatformIDs(cl_uint /* num_entries */, cl_platform_id * /* platforms */, cl_uint * /* num_platforms */) CL_API_SUFFIX__VERSION_1_0; extern CL_API_ENTRY cl_int CL_API_CALL clGetPlatformInfo(cl_platform_id /* platform */, cl_platform_info /* param_name */, size_t /* param_value_size */, void * /* param_value */, size_t * /* param_value_size_ret */) CL_API_SUFFIX__VERSION_1_0; /* Device APIs */ extern CL_API_ENTRY cl_int CL_API_CALL clGetDeviceIDs(cl_platform_id /* platform */, cl_device_type /* device_type */, cl_uint /* num_entries */, cl_device_id * /* devices */, cl_uint * /* num_devices */) CL_API_SUFFIX__VERSION_1_0; extern CL_API_ENTRY cl_int CL_API_CALL clGetDeviceInfo(cl_device_id /* device */, cl_device_info /* param_name */, size_t /* param_value_size */, void * /* param_value */, size_t * /* param_value_size_ret */) CL_API_SUFFIX__VERSION_1_0; /* Context APIs */ extern CL_API_ENTRY cl_context CL_API_CALL clCreateContext(const cl_context_properties * /* properties */, cl_uint /* num_devices */, const cl_device_id * /* devices */, void (CL_CALLBACK * /* pfn_notify */)(const char *, const void *, size_t, void *), void * /* user_data */, cl_int * /* errcode_ret */) CL_API_SUFFIX__VERSION_1_0; extern CL_API_ENTRY cl_context CL_API_CALL clCreateContextFromType(const cl_context_properties * /* properties */, cl_device_type /* device_type */, void (CL_CALLBACK * /* pfn_notify*/ )(const char *, const void *, size_t, void *), void * /* user_data */, cl_int * /* errcode_ret */) CL_API_SUFFIX__VERSION_1_0; extern CL_API_ENTRY cl_int CL_API_CALL clRetainContext(cl_context /* context */) CL_API_SUFFIX__VERSION_1_0; extern CL_API_ENTRY cl_int CL_API_CALL clReleaseContext(cl_context /* context */) CL_API_SUFFIX__VERSION_1_0; extern CL_API_ENTRY cl_int CL_API_CALL clGetContextInfo(cl_context /* context */, cl_context_info /* param_name */, size_t /* param_value_size */, void * /* param_value */, size_t * /* param_value_size_ret */) CL_API_SUFFIX__VERSION_1_0; /* Command Queue APIs */ extern CL_API_ENTRY cl_command_queue CL_API_CALL clCreateCommandQueue(cl_context /* context */, cl_device_id /* device */, cl_command_queue_properties /* properties */, cl_int * /* errcode_ret */) CL_API_SUFFIX__VERSION_1_0; extern CL_API_ENTRY cl_int CL_API_CALL clRetainCommandQueue(cl_command_queue /* command_queue */) CL_API_SUFFIX__VERSION_1_0; extern CL_API_ENTRY cl_int CL_API_CALL clReleaseCommandQueue(cl_command_queue /* command_queue */) CL_API_SUFFIX__VERSION_1_0; extern CL_API_ENTRY cl_int CL_API_CALL clGetCommandQueueInfo(cl_command_queue /* command_queue */, cl_command_queue_info /* param_name */, size_t /* param_value_size */, void * /* param_value */, size_t * /* param_value_size_ret */) CL_API_SUFFIX__VERSION_1_0; #ifdef CL_USE_DEPRECATED_OPENCL_1_0_APIS #warning CL_USE_DEPRECATED_OPENCL_1_0_APIS is defined. These APIs are unsupported and untested in OpenCL 1.1! /* * WARNING: * This API introduces mutable state into the OpenCL implementation. It has been REMOVED * to better facilitate thread safety. The 1.0 API is not thread safe. It is not tested by the * OpenCL 1.1 conformance test, and consequently may not work or may not work dependably. * It is likely to be non-performant. Use of this API is not advised. Use at your own risk. * * Software developers previously relying on this API are instructed to set the command queue * properties when creating the queue, instead. */ extern CL_API_ENTRY cl_int CL_API_CALL clSetCommandQueueProperty(cl_command_queue /* command_queue */, cl_command_queue_properties /* properties */, cl_bool /* enable */, cl_command_queue_properties * /* old_properties */) CL_EXT_SUFFIX__VERSION_1_0_DEPRECATED; #endif /* CL_USE_DEPRECATED_OPENCL_1_0_APIS */ /* Memory Object APIs */ extern CL_API_ENTRY cl_mem CL_API_CALL clCreateBuffer(cl_context /* context */, cl_mem_flags /* flags */, size_t /* size */, void * /* host_ptr */, cl_int * /* errcode_ret */) CL_API_SUFFIX__VERSION_1_0; extern CL_API_ENTRY cl_mem CL_API_CALL clCreateSubBuffer(cl_mem /* buffer */, cl_mem_flags /* flags */, cl_buffer_create_type /* buffer_create_type */, const void * /* buffer_create_info */, cl_int * /* errcode_ret */) CL_API_SUFFIX__VERSION_1_1; extern CL_API_ENTRY cl_mem CL_API_CALL clCreateImage2D(cl_context /* context */, cl_mem_flags /* flags */, const cl_image_format * /* image_format */, size_t /* image_width */, size_t /* image_height */, size_t /* image_row_pitch */, void * /* host_ptr */, cl_int * /* errcode_ret */) CL_API_SUFFIX__VERSION_1_0; extern CL_API_ENTRY cl_mem CL_API_CALL clCreateImage3D(cl_context /* context */, cl_mem_flags /* flags */, const cl_image_format * /* image_format */, size_t /* image_width */, size_t /* image_height */, size_t /* image_depth */, size_t /* image_row_pitch */, size_t /* image_slice_pitch */, void * /* host_ptr */, cl_int * /* errcode_ret */) CL_API_SUFFIX__VERSION_1_0; extern CL_API_ENTRY cl_int CL_API_CALL clRetainMemObject(cl_mem /* memobj */) CL_API_SUFFIX__VERSION_1_0; extern CL_API_ENTRY cl_int CL_API_CALL clReleaseMemObject(cl_mem /* memobj */) CL_API_SUFFIX__VERSION_1_0; extern CL_API_ENTRY cl_int CL_API_CALL clGetSupportedImageFormats(cl_context /* context */, cl_mem_flags /* flags */, cl_mem_object_type /* image_type */, cl_uint /* num_entries */, cl_image_format * /* image_formats */, cl_uint * /* num_image_formats */) CL_API_SUFFIX__VERSION_1_0; extern CL_API_ENTRY cl_int CL_API_CALL clGetMemObjectInfo(cl_mem /* memobj */, cl_mem_info /* param_name */, size_t /* param_value_size */, void * /* param_value */, size_t * /* param_value_size_ret */) CL_API_SUFFIX__VERSION_1_0; extern CL_API_ENTRY cl_int CL_API_CALL clGetImageInfo(cl_mem /* image */, cl_image_info /* param_name */, size_t /* param_value_size */, void * /* param_value */, size_t * /* param_value_size_ret */) CL_API_SUFFIX__VERSION_1_0; extern CL_API_ENTRY cl_int CL_API_CALL clSetMemObjectDestructorCallback( cl_mem /* memobj */, void (CL_CALLBACK * /*pfn_notify*/)( cl_mem /* memobj */, void* /*user_data*/), void * /*user_data */ ) CL_API_SUFFIX__VERSION_1_1; /* Sampler APIs */ extern CL_API_ENTRY cl_sampler CL_API_CALL clCreateSampler(cl_context /* context */, cl_bool /* normalized_coords */, cl_addressing_mode /* addressing_mode */, cl_filter_mode /* filter_mode */, cl_int * /* errcode_ret */) CL_API_SUFFIX__VERSION_1_0; extern CL_API_ENTRY cl_int CL_API_CALL clRetainSampler(cl_sampler /* sampler */) CL_API_SUFFIX__VERSION_1_0; extern CL_API_ENTRY cl_int CL_API_CALL clReleaseSampler(cl_sampler /* sampler */) CL_API_SUFFIX__VERSION_1_0; extern CL_API_ENTRY cl_int CL_API_CALL clGetSamplerInfo(cl_sampler /* sampler */, cl_sampler_info /* param_name */, size_t /* param_value_size */, void * /* param_value */, size_t * /* param_value_size_ret */) CL_API_SUFFIX__VERSION_1_0; /* Program Object APIs */ extern CL_API_ENTRY cl_program CL_API_CALL clCreateProgramWithSource(cl_context /* context */, cl_uint /* count */, const char ** /* strings */, const size_t * /* lengths */, cl_int * /* errcode_ret */) CL_API_SUFFIX__VERSION_1_0; extern CL_API_ENTRY cl_program CL_API_CALL clCreateProgramWithBinary(cl_context /* context */, cl_uint /* num_devices */, const cl_device_id * /* device_list */, const size_t * /* lengths */, const unsigned char ** /* binaries */, cl_int * /* binary_status */, cl_int * /* errcode_ret */) CL_API_SUFFIX__VERSION_1_0; extern CL_API_ENTRY cl_int CL_API_CALL clRetainProgram(cl_program /* program */) CL_API_SUFFIX__VERSION_1_0; extern CL_API_ENTRY cl_int CL_API_CALL clReleaseProgram(cl_program /* program */) CL_API_SUFFIX__VERSION_1_0; extern CL_API_ENTRY cl_int CL_API_CALL clBuildProgram(cl_program /* program */, cl_uint /* num_devices */, const cl_device_id * /* device_list */, const char * /* options */, void (CL_CALLBACK * /* pfn_notify */)(cl_program /* program */, void * /* user_data */), void * /* user_data */) CL_API_SUFFIX__VERSION_1_0; extern CL_API_ENTRY cl_int CL_API_CALL clUnloadCompiler(void) CL_API_SUFFIX__VERSION_1_0; extern CL_API_ENTRY cl_int CL_API_CALL clGetProgramInfo(cl_program /* program */, cl_program_info /* param_name */, size_t /* param_value_size */, void * /* param_value */, size_t * /* param_value_size_ret */) CL_API_SUFFIX__VERSION_1_0; extern CL_API_ENTRY cl_int CL_API_CALL clGetProgramBuildInfo(cl_program /* program */, cl_device_id /* device */, cl_program_build_info /* param_name */, size_t /* param_value_size */, void * /* param_value */, size_t * /* param_value_size_ret */) CL_API_SUFFIX__VERSION_1_0; /* Kernel Object APIs */ extern CL_API_ENTRY cl_kernel CL_API_CALL clCreateKernel(cl_program /* program */, const char * /* kernel_name */, cl_int * /* errcode_ret */) CL_API_SUFFIX__VERSION_1_0; extern CL_API_ENTRY cl_int CL_API_CALL clCreateKernelsInProgram(cl_program /* program */, cl_uint /* num_kernels */, cl_kernel * /* kernels */, cl_uint * /* num_kernels_ret */) CL_API_SUFFIX__VERSION_1_0; extern CL_API_ENTRY cl_int CL_API_CALL clRetainKernel(cl_kernel /* kernel */) CL_API_SUFFIX__VERSION_1_0; extern CL_API_ENTRY cl_int CL_API_CALL clReleaseKernel(cl_kernel /* kernel */) CL_API_SUFFIX__VERSION_1_0; extern CL_API_ENTRY cl_int CL_API_CALL clSetKernelArg(cl_kernel /* kernel */, cl_uint /* arg_index */, size_t /* arg_size */, const void * /* arg_value */) CL_API_SUFFIX__VERSION_1_0; extern CL_API_ENTRY cl_int CL_API_CALL clGetKernelInfo(cl_kernel /* kernel */, cl_kernel_info /* param_name */, size_t /* param_value_size */, void * /* param_value */, size_t * /* param_value_size_ret */) CL_API_SUFFIX__VERSION_1_0; extern CL_API_ENTRY cl_int CL_API_CALL clGetKernelWorkGroupInfo(cl_kernel /* kernel */, cl_device_id /* device */, cl_kernel_work_group_info /* param_name */, size_t /* param_value_size */, void * /* param_value */, size_t * /* param_value_size_ret */) CL_API_SUFFIX__VERSION_1_0; /* Event Object APIs */ extern CL_API_ENTRY cl_int CL_API_CALL clWaitForEvents(cl_uint /* num_events */, const cl_event * /* event_list */) CL_API_SUFFIX__VERSION_1_0; extern CL_API_ENTRY cl_int CL_API_CALL clGetEventInfo(cl_event /* event */, cl_event_info /* param_name */, size_t /* param_value_size */, void * /* param_value */, size_t * /* param_value_size_ret */) CL_API_SUFFIX__VERSION_1_0; extern CL_API_ENTRY cl_event CL_API_CALL clCreateUserEvent(cl_context /* context */, cl_int * /* errcode_ret */) CL_API_SUFFIX__VERSION_1_1; extern CL_API_ENTRY cl_int CL_API_CALL clRetainEvent(cl_event /* event */) CL_API_SUFFIX__VERSION_1_0; extern CL_API_ENTRY cl_int CL_API_CALL clReleaseEvent(cl_event /* event */) CL_API_SUFFIX__VERSION_1_0; extern CL_API_ENTRY cl_int CL_API_CALL clSetUserEventStatus(cl_event /* event */, cl_int /* execution_status */) CL_API_SUFFIX__VERSION_1_1; extern CL_API_ENTRY cl_int CL_API_CALL clSetEventCallback( cl_event /* event */, cl_int /* command_exec_callback_type */, void (CL_CALLBACK * /* pfn_notify */)(cl_event, cl_int, void *), void * /* user_data */) CL_API_SUFFIX__VERSION_1_1; /* Profiling APIs */ extern CL_API_ENTRY cl_int CL_API_CALL clGetEventProfilingInfo(cl_event /* event */, cl_profiling_info /* param_name */, size_t /* param_value_size */, void * /* param_value */, size_t * /* param_value_size_ret */) CL_API_SUFFIX__VERSION_1_0; /* Flush and Finish APIs */ extern CL_API_ENTRY cl_int CL_API_CALL clFlush(cl_command_queue /* command_queue */) CL_API_SUFFIX__VERSION_1_0; extern CL_API_ENTRY cl_int CL_API_CALL clFinish(cl_command_queue /* command_queue */) CL_API_SUFFIX__VERSION_1_0; /* Enqueued Commands APIs */ extern CL_API_ENTRY cl_int CL_API_CALL clEnqueueReadBuffer(cl_command_queue /* command_queue */, cl_mem /* buffer */, cl_bool /* blocking_read */, size_t /* offset */, size_t /* cb */, void * /* ptr */, cl_uint /* num_events_in_wait_list */, const cl_event * /* event_wait_list */, cl_event * /* event */) CL_API_SUFFIX__VERSION_1_0; extern CL_API_ENTRY cl_int CL_API_CALL clEnqueueReadBufferRect(cl_command_queue /* command_queue */, cl_mem /* buffer */, cl_bool /* blocking_read */, const size_t * /* buffer_offset */, const size_t * /* host_offset */, const size_t * /* region */, size_t /* buffer_row_pitch */, size_t /* buffer_slice_pitch */, size_t /* host_row_pitch */, size_t /* host_slice_pitch */, void * /* ptr */, cl_uint /* num_events_in_wait_list */, const cl_event * /* event_wait_list */, cl_event * /* event */) CL_API_SUFFIX__VERSION_1_1; extern CL_API_ENTRY cl_int CL_API_CALL clEnqueueWriteBuffer(cl_command_queue /* command_queue */, cl_mem /* buffer */, cl_bool /* blocking_write */, size_t /* offset */, size_t /* cb */, const void * /* ptr */, cl_uint /* num_events_in_wait_list */, const cl_event * /* event_wait_list */, cl_event * /* event */) CL_API_SUFFIX__VERSION_1_0; extern CL_API_ENTRY cl_int CL_API_CALL clEnqueueWriteBufferRect(cl_command_queue /* command_queue */, cl_mem /* buffer */, cl_bool /* blocking_read */, const size_t * /* buffer_offset */, const size_t * /* host_offset */, const size_t * /* region */, size_t /* buffer_row_pitch */, size_t /* buffer_slice_pitch */, size_t /* host_row_pitch */, size_t /* host_slice_pitch */, const void * /* ptr */, cl_uint /* num_events_in_wait_list */, const cl_event * /* event_wait_list */, cl_event * /* event */) CL_API_SUFFIX__VERSION_1_1; extern CL_API_ENTRY cl_int CL_API_CALL clEnqueueCopyBuffer(cl_command_queue /* command_queue */, cl_mem /* src_buffer */, cl_mem /* dst_buffer */, size_t /* src_offset */, size_t /* dst_offset */, size_t /* cb */, cl_uint /* num_events_in_wait_list */, const cl_event * /* event_wait_list */, cl_event * /* event */) CL_API_SUFFIX__VERSION_1_0; extern CL_API_ENTRY cl_int CL_API_CALL clEnqueueCopyBufferRect(cl_command_queue /* command_queue */, cl_mem /* src_buffer */, cl_mem /* dst_buffer */, const size_t * /* src_origin */, const size_t * /* dst_origin */, const size_t * /* region */, size_t /* src_row_pitch */, size_t /* src_slice_pitch */, size_t /* dst_row_pitch */, size_t /* dst_slice_pitch */, cl_uint /* num_events_in_wait_list */, const cl_event * /* event_wait_list */, cl_event * /* event */) CL_API_SUFFIX__VERSION_1_1; extern CL_API_ENTRY cl_int CL_API_CALL clEnqueueReadImage(cl_command_queue /* command_queue */, cl_mem /* image */, cl_bool /* blocking_read */, const size_t * /* origin[3] */, const size_t * /* region[3] */, size_t /* row_pitch */, size_t /* slice_pitch */, void * /* ptr */, cl_uint /* num_events_in_wait_list */, const cl_event * /* event_wait_list */, cl_event * /* event */) CL_API_SUFFIX__VERSION_1_0; extern CL_API_ENTRY cl_int CL_API_CALL clEnqueueWriteImage(cl_command_queue /* command_queue */, cl_mem /* image */, cl_bool /* blocking_write */, const size_t * /* origin[3] */, const size_t * /* region[3] */, size_t /* input_row_pitch */, size_t /* input_slice_pitch */, const void * /* ptr */, cl_uint /* num_events_in_wait_list */, const cl_event * /* event_wait_list */, cl_event * /* event */) CL_API_SUFFIX__VERSION_1_0; extern CL_API_ENTRY cl_int CL_API_CALL clEnqueueCopyImage(cl_command_queue /* command_queue */, cl_mem /* src_image */, cl_mem /* dst_image */, const size_t * /* src_origin[3] */, const size_t * /* dst_origin[3] */, const size_t * /* region[3] */, cl_uint /* num_events_in_wait_list */, const cl_event * /* event_wait_list */, cl_event * /* event */) CL_API_SUFFIX__VERSION_1_0; extern CL_API_ENTRY cl_int CL_API_CALL clEnqueueCopyImageToBuffer(cl_command_queue /* command_queue */, cl_mem /* src_image */, cl_mem /* dst_buffer */, const size_t * /* src_origin[3] */, const size_t * /* region[3] */, size_t /* dst_offset */, cl_uint /* num_events_in_wait_list */, const cl_event * /* event_wait_list */, cl_event * /* event */) CL_API_SUFFIX__VERSION_1_0; extern CL_API_ENTRY cl_int CL_API_CALL clEnqueueCopyBufferToImage(cl_command_queue /* command_queue */, cl_mem /* src_buffer */, cl_mem /* dst_image */, size_t /* src_offset */, const size_t * /* dst_origin[3] */, const size_t * /* region[3] */, cl_uint /* num_events_in_wait_list */, const cl_event * /* event_wait_list */, cl_event * /* event */) CL_API_SUFFIX__VERSION_1_0; extern CL_API_ENTRY void * CL_API_CALL clEnqueueMapBuffer(cl_command_queue /* command_queue */, cl_mem /* buffer */, cl_bool /* blocking_map */, cl_map_flags /* map_flags */, size_t /* offset */, size_t /* cb */, cl_uint /* num_events_in_wait_list */, const cl_event * /* event_wait_list */, cl_event * /* event */, cl_int * /* errcode_ret */) CL_API_SUFFIX__VERSION_1_0; extern CL_API_ENTRY void * CL_API_CALL clEnqueueMapImage(cl_command_queue /* command_queue */, cl_mem /* image */, cl_bool /* blocking_map */, cl_map_flags /* map_flags */, const size_t * /* origin[3] */, const size_t * /* region[3] */, size_t * /* image_row_pitch */, size_t * /* image_slice_pitch */, cl_uint /* num_events_in_wait_list */, const cl_event * /* event_wait_list */, cl_event * /* event */, cl_int * /* errcode_ret */) CL_API_SUFFIX__VERSION_1_0; extern CL_API_ENTRY cl_int CL_API_CALL clEnqueueUnmapMemObject(cl_command_queue /* command_queue */, cl_mem /* memobj */, void * /* mapped_ptr */, cl_uint /* num_events_in_wait_list */, const cl_event * /* event_wait_list */, cl_event * /* event */) CL_API_SUFFIX__VERSION_1_0; extern CL_API_ENTRY cl_int CL_API_CALL clEnqueueNDRangeKernel(cl_command_queue /* command_queue */, cl_kernel /* kernel */, cl_uint /* work_dim */, const size_t * /* global_work_offset */, const size_t * /* global_work_size */, const size_t * /* local_work_size */, cl_uint /* num_events_in_wait_list */, const cl_event * /* event_wait_list */, cl_event * /* event */) CL_API_SUFFIX__VERSION_1_0; extern CL_API_ENTRY cl_int CL_API_CALL clEnqueueTask(cl_command_queue /* command_queue */, cl_kernel /* kernel */, cl_uint /* num_events_in_wait_list */, const cl_event * /* event_wait_list */, cl_event * /* event */) CL_API_SUFFIX__VERSION_1_0; extern CL_API_ENTRY cl_int CL_API_CALL clEnqueueNativeKernel(cl_command_queue /* command_queue */, void (*user_func)(void *), void * /* args */, size_t /* cb_args */, cl_uint /* num_mem_objects */, const cl_mem * /* mem_list */, const void ** /* args_mem_loc */, cl_uint /* num_events_in_wait_list */, const cl_event * /* event_wait_list */, cl_event * /* event */) CL_API_SUFFIX__VERSION_1_0; extern CL_API_ENTRY cl_int CL_API_CALL clEnqueueMarker(cl_command_queue /* command_queue */, cl_event * /* event */) CL_API_SUFFIX__VERSION_1_0; extern CL_API_ENTRY cl_int CL_API_CALL clEnqueueWaitForEvents(cl_command_queue /* command_queue */, cl_uint /* num_events */, const cl_event * /* event_list */) CL_API_SUFFIX__VERSION_1_0; extern CL_API_ENTRY cl_int CL_API_CALL clEnqueueBarrier(cl_command_queue /* command_queue */) CL_API_SUFFIX__VERSION_1_0; /* Extension function access * * Returns the extension function address for the given function name, * or NULL if a valid function can not be found. The client must * check to make sure the address is not NULL, before using or * calling the returned function address. */ extern CL_API_ENTRY void * CL_API_CALL clGetExtensionFunctionAddress(const char * /* func_name */) CL_API_SUFFIX__VERSION_1_0; #ifdef __cplusplus } #endif #endif /* __OPENCL_CL_H */ ugene-1.9.8/src/include/U2Formats/0000755000175000017500000000000011651544335015355 5ustar ilyailyaugene-1.9.8/src/include/U2Formats/NEXUSFormat.h0000644000175000017500000000006611651544335017603 0ustar ilyailya#include "../../corelibs/U2Formats/src/NEXUSFormat.h" ugene-1.9.8/src/include/U2Formats/GFFFormat.h0000644000175000017500000000006411651544335017301 0ustar ilyailya#include "../../corelibs/U2Formats/src/GFFFormat.h" ugene-1.9.8/src/include/U2Formats/FastaFormat.h0000644000175000017500000000006611651544335017737 0ustar ilyailya#include "../../corelibs/U2Formats/src/FastaFormat.h" ugene-1.9.8/src/include/U2Formats/PlainTextFormat.h0000644000175000017500000000007211651544335020606 0ustar ilyailya#include "../../corelibs/U2Formats/src/PlainTextFormat.h" ugene-1.9.8/src/include/U2Formats/StreamSequenceReader.h0000644000175000017500000000007711651544335021601 0ustar ilyailya#include "../../corelibs/U2Formats/src/StreamSequenceReader.h" ugene-1.9.8/src/include/U2Formats/PDWFormat.h0000644000175000017500000000006411651544335017331 0ustar ilyailya#include "../../corelibs/U2Formats/src/PDWFormat.h" ugene-1.9.8/src/include/U2Formats/GenbankPlainTextFormat.h0000644000175000017500000000010111651544335022065 0ustar ilyailya#include "../../corelibs/U2Formats/src/GenbankPlainTextFormat.h" ugene-1.9.8/src/include/U2Formats/ACEFormat.h0000644000175000017500000000006411651544335017267 0ustar ilyailya#include "../../corelibs/U2Formats/src/ACEFormat.h" ugene-1.9.8/src/include/U2Formats/ConvertAssemblyToSamTask.h0000644000175000017500000000011111651544335022426 0ustar ilyailya#include "../../corelibs/U2Formats/src/tasks/ConvertAssemblyToSamTask.h" ugene-1.9.8/src/include/U2Formats/GenbankLocationParser.h0000644000175000017500000000010011651544335021730 0ustar ilyailya#include "../../corelibs/U2Formats/src/GenbankLocationParser.h" ugene-1.9.8/src/include/U2Formats/ASNFormat.h0000644000175000017500000000006411651544335017320 0ustar ilyailya#include "../../corelibs/U2Formats/src/ASNFormat.h" ugene-1.9.8/src/include/U2Formats/EMBLPlainTextFormat.h0000644000175000017500000000007611651544335021252 0ustar ilyailya#include "../../corelibs/U2Formats/src/EMBLPlainTextFormat.h" ugene-1.9.8/src/include/U2Formats/EMBLGenbankAbstractDocument.h0000644000175000017500000000010611651544335022713 0ustar ilyailya#include "../../corelibs/U2Formats/src/EMBLGenbankAbstractDocument.h" ugene-1.9.8/src/include/U2Formats/GenbankFeatures.h0000644000175000017500000000007211651544335020571 0ustar ilyailya#include "../../corelibs/U2Formats/src/GenbankFeatures.h" ugene-1.9.8/src/include/U2Formats/RawDNASequenceFormat.h0000644000175000017500000000007711651544335021450 0ustar ilyailya#include "../../corelibs/U2Formats/src/RawDNASequenceFormat.h" ugene-1.9.8/src/include/U2Formats/SCFFormat.h0000644000175000017500000000006411651544335017312 0ustar ilyailya#include "../../corelibs/U2Formats/src/SCFFormat.h" ugene-1.9.8/src/include/U2Formats/StockholmFormat.h0000644000175000017500000000007211651544335020641 0ustar ilyailya#include "../../corelibs/U2Formats/src/StockholmFormat.h" ugene-1.9.8/src/include/U2Formats/IndexFormat.h0000644000175000017500000000006611651544335017750 0ustar ilyailya#include "../../corelibs/U2Formats/src/IndexFormat.h" ugene-1.9.8/src/include/U2Formats/StreamSequenceWriter.h0000644000175000017500000000007711651544335021653 0ustar ilyailya#include "../../corelibs/U2Formats/src/StreamSequenceWriter.h" ugene-1.9.8/src/include/U2Formats/SRFastaFormat.h0000644000175000017500000000007011651544335020177 0ustar ilyailya#include "../../corelibs/U2Formats/src/SRFastaFormat.h" ugene-1.9.8/src/include/U2Formats/ClustalWAlnFormat.h0000644000175000017500000000007411651544335021071 0ustar ilyailya#include "../../corelibs/U2Formats/src/ClustalWAlnFormat.h" ugene-1.9.8/src/include/U2Formats/NEXUSParser.h0000644000175000017500000000006611651544335017607 0ustar ilyailya#include "../../corelibs/U2Formats/src/NEXUSParser.h" ugene-1.9.8/src/include/U2Formats/MegaFormat.h0000644000175000017500000000006511651544335017551 0ustar ilyailya#include "../../corelibs/U2Formats/src/MegaFormat.h" ugene-1.9.8/src/include/U2Formats/DocumentFormatUtils.h0000644000175000017500000000007611651544335021501 0ustar ilyailya#include "../../corelibs/U2Formats/src/DocumentFormatUtils.h" ugene-1.9.8/src/include/U2Formats/DocumentFormats.h0000644000175000017500000000007311651544335020640 0ustar ilyailya#include "../../corelibs/U2Formats/src/DocumentFormats.h" ugene-1.9.8/src/include/U2Formats/SAMFormat.h0000644000175000017500000000006411651544335017317 0ustar ilyailya#include "../../corelibs/U2Formats/src/SAMFormat.h" ugene-1.9.8/src/include/U2Formats/ABIFormat.h0000644000175000017500000000006411651544335017272 0ustar ilyailya#include "../../corelibs/U2Formats/src/ABIFormat.h" ugene-1.9.8/src/include/U2Formats/PDBFormat.h0000644000175000017500000000006411651544335017304 0ustar ilyailya#include "../../corelibs/U2Formats/src/PDBFormat.h" ugene-1.9.8/src/include/U2Formats/SwissProtPlainTextFormat.h0000644000175000017500000000010311651544335022477 0ustar ilyailya#include "../../corelibs/U2Formats/src/SwissProtPlainTextFormat.h" ugene-1.9.8/src/include/U2Formats/NewickFormat.h0000644000175000017500000000006711651544335020122 0ustar ilyailya#include "../../corelibs/U2Formats/src/NewickFormat.h" ugene-1.9.8/src/include/U2Formats/MSFFormat.h0000644000175000017500000000006411651544335017324 0ustar ilyailya#include "../../corelibs/U2Formats/src/MSFFormat.h" ugene-1.9.8/src/include/U2Formats/FastqFormat.h0000644000175000017500000000006611651544335017757 0ustar ilyailya#include "../../corelibs/U2Formats/src/FastqFormat.h" ugene-1.9.8/src/include/U2Gui/0000755000175000017500000000000011651544336014467 5ustar ilyailyaugene-1.9.8/src/include/U2Gui/CreateDocumentFromTextDialogController.h0000644000175000017500000000012611651544335024415 0ustar ilyailya#include "../../corelibs/U2Gui/src/util_gui/CreateDocumentFromTextDialogController.h" ugene-1.9.8/src/include/U2Gui/ObjectViewModel.h0000644000175000017500000000006611651544335017663 0ustar ilyailya#include "../../corelibs/U2Gui/src/ObjectViewModel.h" ugene-1.9.8/src/include/U2Gui/ObjectViewTreeController.h0000644000175000017500000000011011651544335021554 0ustar ilyailya#include "../../corelibs/U2Gui/src/util_gui/ObjectViewTreeController.h" ugene-1.9.8/src/include/U2Gui/Notification.h0000644000175000017500000000006311651544335017264 0ustar ilyailya#include "../../corelibs/U2Gui/src/Notification.h" ugene-1.9.8/src/include/U2Gui/GUIUtils.h0000644000175000017500000000007011651544335016301 0ustar ilyailya#include "../../corelibs/U2Gui/src/util_gui/GUIUtils.h" ugene-1.9.8/src/include/U2Gui/DownloadRemoteFileDialog.h0000644000175000017500000000011011651544335021472 0ustar ilyailya#include "../../corelibs/U2Gui/src/util_gui/DownloadRemoteFileDialog.h" ugene-1.9.8/src/include/U2Gui/AnnotationSettingsDialogController.h0000644000175000017500000000012211651544335023651 0ustar ilyailya#include "../../corelibs/U2Gui/src/util_gui/AnnotationSettingsDialogController.h" ugene-1.9.8/src/include/U2Gui/RemovePartFromSequenceDialogController.h0000644000175000017500000000012611651544335024423 0ustar ilyailya#include "../../corelibs/U2Gui/src/util_gui/RemovePartFromSequenceDialogController.h" ugene-1.9.8/src/include/U2Gui/ProjectDocumentComboBoxController.h0000644000175000017500000000012111651544335023433 0ustar ilyailya#include "../../corelibs/U2Gui/src/util_gui/ProjectDocumentComboBoxController.h" ugene-1.9.8/src/include/U2Gui/CreateAnnotationWidgetController.h0000644000175000017500000000012011651544335023276 0ustar ilyailya#include "../../corelibs/U2Gui/src/util_gui/CreateAnnotationWidgetController.h" ugene-1.9.8/src/include/U2Gui/PluginViewer.h0000644000175000017500000000006311651544335017256 0ustar ilyailya#include "../../corelibs/U2Gui/src/PluginViewer.h" ugene-1.9.8/src/include/U2Gui/NotificationWidget.h0000644000175000017500000000007111651544335020427 0ustar ilyailya#include "../../corelibs/U2Gui/src/NotificationWidget.h" ugene-1.9.8/src/include/U2Gui/SaveDocumentGroupController.h0000644000175000017500000000011311651544335022310 0ustar ilyailya#include "../../corelibs/U2Gui/src/util_gui/SaveDocumentGroupController.h" ugene-1.9.8/src/include/U2Gui/EditQualifierDialog.h0000644000175000017500000000010311651544335020500 0ustar ilyailya#include "../../corelibs/U2Gui/src/util_gui/EditQualifierDialog.h" ugene-1.9.8/src/include/U2Gui/AddNewDocumentDialogController.h0000644000175000017500000000011611651544335022662 0ustar ilyailya#include "../../corelibs/U2Gui/src/util_gui/AddNewDocumentDialogController.h" ugene-1.9.8/src/include/U2Gui/CreateAnnotationDialog.h0000644000175000017500000000010611651544335021212 0ustar ilyailya#include "../../corelibs/U2Gui/src/util_gui/CreateAnnotationDialog.h" ugene-1.9.8/src/include/U2Gui/EditSequenceDialogController.h0000644000175000017500000000011411651544335022375 0ustar ilyailya#include "../../corelibs/U2Gui/src/util_gui/EditSequenceDialogController.h" ugene-1.9.8/src/include/U2Gui/GObjectComboBoxController.h0000644000175000017500000000011111651544335021642 0ustar ilyailya#include "../../corelibs/U2Gui/src/util_gui/GObjectComboBoxController.h" ugene-1.9.8/src/include/U2Gui/CopyDocumentDialogController.h0000644000175000017500000000011411651544335022430 0ustar ilyailya#include "../../corelibs/U2Gui/src/util_gui/CopyDocumentDialogController.h" ugene-1.9.8/src/include/U2Gui/ProjectTreeItemSelectorDialog.h0000644000175000017500000000011511651544335022522 0ustar ilyailya#include "../../corelibs/U2Gui/src/util_gui/ProjectTreeItemSelectorDialog.h" ugene-1.9.8/src/include/U2Gui/ProjectView.h0000644000175000017500000000006211651544335017076 0ustar ilyailya#include "../../corelibs/U2Gui/src/ProjectView.h" ugene-1.9.8/src/include/U2Gui/LogView.h0000644000175000017500000000007711651544335016217 0ustar ilyailya#include "../../corelibs/U2Gui/src/util_gui/logview/LogView.h" ugene-1.9.8/src/include/U2Gui/ObjectViewTasks.h0000644000175000017500000000006611651544335017710 0ustar ilyailya#include "../../corelibs/U2Gui/src/ObjectViewTasks.h" ugene-1.9.8/src/include/U2Gui/DocumentFormatComboboxController.h0000644000175000017500000000012011651544335023314 0ustar ilyailya#include "../../corelibs/U2Gui/src/util_gui/DocumentFormatComboboxController.h" ugene-1.9.8/src/include/U2Gui/ProjectParsing.h0000644000175000017500000000006511651544335017572 0ustar ilyailya#include "../../corelibs/U2Gui/src/ProjectParsing.h" ugene-1.9.8/src/include/U2Gui/AppSettingsGUI.h0000644000175000017500000000006511651544335017446 0ustar ilyailya#include "../../corelibs/U2Gui/src/AppSettingsGUI.h" ugene-1.9.8/src/include/U2Gui/ExportImageDialog.h0000644000175000017500000000010111651544335020173 0ustar ilyailya#include "../../corelibs/U2Gui/src/util_gui/ExportImageDialog.h" ugene-1.9.8/src/include/U2Gui/MainWindow.h0000644000175000017500000000006111651544335016710 0ustar ilyailya#include "../../corelibs/U2Gui/src/MainWindow.h" ugene-1.9.8/src/include/U2Gui/SeqPasterWidgetController.h0000644000175000017500000000011111651544336021750 0ustar ilyailya#include "../../corelibs/U2Gui/src/util_gui/SeqPasterWidgetController.h" ugene-1.9.8/src/include/U2Gui/ProjectTreeController.h0000644000175000017500000000010511651544335021125 0ustar ilyailya#include "../../corelibs/U2Gui/src/util_gui/ProjectTreeController.h" ugene-1.9.8/src/include/U2Gui/CreateObjectRelationDialogController.h0000644000175000017500000000012411651544335024050 0ustar ilyailya#include "../../corelibs/U2Gui/src/util_gui/CreateObjectRelationDialogController.h" ugene-1.9.8/src/include/U2Gui/OpenViewTask.h0000644000175000017500000000006311651544335017215 0ustar ilyailya#include "../../corelibs/U2Gui/src/OpenViewTask.h" ugene-1.9.8/src/include/U2Gui/BaseDocumentFormatConfigurators.h0000644000175000017500000000011711651544335023126 0ustar ilyailya#include "../../corelibs/U2Gui/src/util_gui/BaseDocumentFormatConfigurators.h" ugene-1.9.8/src/include/U2Gui/UnloadDocumentTask.h0000644000175000017500000000007111651544336020402 0ustar ilyailya#include "../../corelibs/U2Gui/src/UnloadDocumentTask.h" ugene-1.9.8/src/include/U2Misc/0000755000175000017500000000000011651544336014636 5ustar ilyailyaugene-1.9.8/src/include/U2Misc/RangeSelector.h0000644000175000017500000000006511651544336017545 0ustar ilyailya#include "../../corelibs/U2Misc/src/RangeSelector.h" ugene-1.9.8/src/include/U2Misc/PositionSelector.h0000644000175000017500000000007011651544336020311 0ustar ilyailya#include "../../corelibs/U2Misc/src/PositionSelector.h" ugene-1.9.8/src/include/U2Misc/TreeWidgetUtils.h0000644000175000017500000000006711651544336020076 0ustar ilyailya#include "../../corelibs/U2Misc/src/TreeWidgetUtils.h" ugene-1.9.8/src/include/U2Misc/GlassView.h0000644000175000017500000000006111651544336016710 0ustar ilyailya#include "../../corelibs/U2Misc/src/GlassView.h" ugene-1.9.8/src/include/U2Misc/DialogUtils.h0000644000175000017500000000006311651544336017226 0ustar ilyailya#include "../../corelibs/U2Misc/src/DialogUtils.h" ugene-1.9.8/src/include/U2Misc/AuthenticationDialog.h0000644000175000017500000000007411651544336021107 0ustar ilyailya#include "../../corelibs/U2Misc/src/AuthenticationDialog.h" ugene-1.9.8/src/include/U2Misc/TextEditorDialog.h0000644000175000017500000000007011651544336020217 0ustar ilyailya#include "../../corelibs/U2Misc/src/TextEditorDialog.h" ugene-1.9.8/src/include/U2Misc/HBar.h0000644000175000017500000000005411651544336015622 0ustar ilyailya#include "../../corelibs/U2Misc/src/HBar.h" ugene-1.9.8/src/include/U2Misc/ScriptEditorDialog.h0000644000175000017500000000007211651544336020541 0ustar ilyailya#include "../../corelibs/U2Misc/src/ScriptEditorDialog.h" ugene-1.9.8/src/include/U2Misc/ScaleBar.h0000644000175000017500000000006011651544336016457 0ustar ilyailya#include "../../corelibs/U2Misc/src/ScaleBar.h" ugene-1.9.8/src/include/U2Misc/GScrollBar.h0000644000175000017500000000006211651544336016777 0ustar ilyailya#include "../../corelibs/U2Misc/src/GScrollBar.h" ugene-1.9.8/src/include/U2Misc/GraphUtils.h0000644000175000017500000000006211651544336017067 0ustar ilyailya#include "../../corelibs/U2Misc/src/GraphUtils.h" ugene-1.9.8/src/include/U2Lang/0000755000175000017500000000000011651544336014624 5ustar ilyailyaugene-1.9.8/src/include/U2Lang/SchemaSerializer.h0000644000175000017500000000010011651544336020216 0ustar ilyailya#include "../../corelibs/U2Lang/src/support/SchemaSerializer.h" ugene-1.9.8/src/include/U2Lang/QDConstraint.h0000644000175000017500000000007211651544336017345 0ustar ilyailya#include "../../corelibs/U2Lang/src/model/QDConstraint.h" ugene-1.9.8/src/include/U2Lang/Datatype.h0000644000175000017500000000006611651544336016552 0ustar ilyailya#include "../../corelibs/U2Lang/src/model/Datatype.h" ugene-1.9.8/src/include/U2Lang/BaseAttributes.h0000644000175000017500000000007611651544336017721 0ustar ilyailya#include "../../corelibs/U2Lang/src/library/BaseAttributes.h" ugene-1.9.8/src/include/U2Lang/ActorPrototypeRegistry.h0000644000175000017500000000010411651544336021517 0ustar ilyailya#include "../../corelibs/U2Lang/src/model/ActorPrototypeRegistry.h" ugene-1.9.8/src/include/U2Lang/WorkflowManager.h0000644000175000017500000000007511651544336020104 0ustar ilyailya#include "../../corelibs/U2Lang/src/model/WorkflowManager.h" ugene-1.9.8/src/include/U2Lang/QueryDesignerRegistry.h0000644000175000017500000000010311651544336021306 0ustar ilyailya#include "../../corelibs/U2Lang/src/model/QueryDesignerRegistry.h" ugene-1.9.8/src/include/U2Lang/BaseSlots.h0000644000175000017500000000007111651544336016672 0ustar ilyailya#include "../../corelibs/U2Lang/src/library/BaseSlots.h" ugene-1.9.8/src/include/U2Lang/WorkflowUtils.h0000644000175000017500000000007511651544336017632 0ustar ilyailya#include "../../corelibs/U2Lang/src/support/WorkflowUtils.h" ugene-1.9.8/src/include/U2Lang/RunSchemaForTask.h0000644000175000017500000000010011651544336020143 0ustar ilyailya#include "../../corelibs/U2Lang/src/support/RunSchemaForTask.h" ugene-1.9.8/src/include/U2Lang/Port.h0000644000175000017500000000006211651544336015717 0ustar ilyailya#include "../../corelibs/U2Lang/src/model/Port.h" ugene-1.9.8/src/include/U2Lang/LocalDomain.h0000644000175000017500000000007311651544336017157 0ustar ilyailya#include "../../corelibs/U2Lang/src/library/LocalDomain.h" ugene-1.9.8/src/include/U2Lang/ScriptLibrary.h0000644000175000017500000000007511651544336017570 0ustar ilyailya#include "../../corelibs/U2Lang/src/library/ScriptLibrary.h" ugene-1.9.8/src/include/U2Lang/IntegralBusType.h0000644000175000017500000000007511651544336020060 0ustar ilyailya#include "../../corelibs/U2Lang/src/model/IntegralBusType.h" ugene-1.9.8/src/include/U2Lang/WorkflowSettings.h0000644000175000017500000000010011651544336020317 0ustar ilyailya#include "../../corelibs/U2Lang/src/support/WorkflowSettings.h" ugene-1.9.8/src/include/U2Lang/BasePorts.h0000644000175000017500000000007111651544336016675 0ustar ilyailya#include "../../corelibs/U2Lang/src/library/BasePorts.h" ugene-1.9.8/src/include/U2Lang/WorkflowTransport.h0000644000175000017500000000007711651544336020530 0ustar ilyailya#include "../../corelibs/U2Lang/src/model/WorkflowTransport.h" ugene-1.9.8/src/include/U2Lang/WorkflowIOTasks.h0000644000175000017500000000007711651544336020051 0ustar ilyailya#include "../../corelibs/U2Lang/src/support/WorkflowIOTasks.h" ugene-1.9.8/src/include/U2Lang/QDScheme.h0000644000175000017500000000006611651544336016430 0ustar ilyailya#include "../../corelibs/U2Lang/src/model/QDScheme.h" ugene-1.9.8/src/include/U2Lang/CoreLibConstants.h0000644000175000017500000000010011651544336020200 0ustar ilyailya#include "../../corelibs/U2Lang/src/support/CoreLibConstants.h" ugene-1.9.8/src/include/U2Lang/BaseActorCategories.h0000644000175000017500000000010311651544336020640 0ustar ilyailya#include "../../corelibs/U2Lang/src/library/BaseActorCategories.h" ugene-1.9.8/src/include/U2Lang/Descriptor.h0000644000175000017500000000007011651544336017110 0ustar ilyailya#include "../../corelibs/U2Lang/src/model/Descriptor.h" ugene-1.9.8/src/include/U2Lang/HRSchemaSerializer.h0000644000175000017500000000010211651544336020452 0ustar ilyailya#include "../../corelibs/U2Lang/src/support/HRSchemaSerializer.h" ugene-1.9.8/src/include/U2Lang/IntegralBusModel.h0000644000175000017500000000007611651544336020200 0ustar ilyailya#include "../../corelibs/U2Lang/src/model/IntegralBusModel.h" ugene-1.9.8/src/include/U2Lang/WorkflowEnvImpl.h0000644000175000017500000000007711651544336020106 0ustar ilyailya#include "../../corelibs/U2Lang/src/support/WorkflowEnvImpl.h" ugene-1.9.8/src/include/U2Lang/Schema.h0000644000175000017500000000006411651544336016175 0ustar ilyailya#include "../../corelibs/U2Lang/src/model/Schema.h" ugene-1.9.8/src/include/U2Lang/Configuration.h0000644000175000017500000000007311651544336017604 0ustar ilyailya#include "../../corelibs/U2Lang/src/model/Configuration.h" ugene-1.9.8/src/include/U2Lang/WorkflowEnv.h0000644000175000017500000000007111651544336017256 0ustar ilyailya#include "../../corelibs/U2Lang/src/model/WorkflowEnv.h" ugene-1.9.8/src/include/U2Lang/DatatypeConversion.h0000644000175000017500000000010011651544336020605 0ustar ilyailya#include "../../corelibs/U2Lang/src/model/DatatypeConversion.h" ugene-1.9.8/src/include/U2Lang/BaseTypes.h0000644000175000017500000000007111651544336016672 0ustar ilyailya#include "../../corelibs/U2Lang/src/library/BaseTypes.h" ugene-1.9.8/src/include/U2Lang/Attribute.h0000644000175000017500000000006711651544336016743 0ustar ilyailya#include "../../corelibs/U2Lang/src/model/Attribute.h" ugene-1.9.8/src/include/U2Lang/IntegralBus.h0000644000175000017500000000007111651544336017212 0ustar ilyailya#include "../../corelibs/U2Lang/src/model/IntegralBus.h" ugene-1.9.8/src/include/U2Lang/ActorModel.h0000644000175000017500000000007011651544336017023 0ustar ilyailya#include "../../corelibs/U2Lang/src/model/ActorModel.h" ugene-1.9.8/src/include/U2Lang/ConfigurationValidator.h0000644000175000017500000000010411651544336021445 0ustar ilyailya#include "../../corelibs/U2Lang/src/model/ConfigurationValidator.h" ugene-1.9.8/src/include/U2Lang/Peer.h0000644000175000017500000000006211651544336015666 0ustar ilyailya#include "../../corelibs/U2Lang/src/model/Peer.h" ugene-1.9.8/src/include/U2Lang/ConfigurationEditor.h0000644000175000017500000000010111651544336020743 0ustar ilyailya#include "../../corelibs/U2Lang/src/model/ConfigurationEditor.h" ugene-1.9.8/src/include/U2Lang/WorkflowRunTask.h0000644000175000017500000000007711651544336020123 0ustar ilyailya#include "../../corelibs/U2Lang/src/support/WorkflowRunTask.h" ugene-1.9.8/src/include/U2Lang/ExternalToolCfg.h0000644000175000017500000000007411651544336020036 0ustar ilyailya#include "../../corelibs/U2Lang/src/model/ExternalToolCfg.h"ugene-1.9.8/src/include/U2Lang/MapDatatypeEditor.h0000644000175000017500000000010111651544336020345 0ustar ilyailya#include "../../corelibs/U2Lang/src/support/MapDatatypeEditor.h" ugene-1.9.8/src/include/U2Designer/0000755000175000017500000000000011651544335015502 5ustar ilyailyaugene-1.9.8/src/include/U2Designer/QDScheduler.h0000644000175000017500000000006711651544335020021 0ustar ilyailya#include "../../corelibs/U2Designer/src/QDScheduler.h" ugene-1.9.8/src/include/U2Designer/WorkflowGUIUtils.h0000644000175000017500000000007411651544335021054 0ustar ilyailya#include "../../corelibs/U2Designer/src/WorkflowGUIUtils.h" ugene-1.9.8/src/include/U2Designer/DelegateEditors.h0000644000175000017500000000007311651544335020717 0ustar ilyailya#include "../../corelibs/U2Designer/src/DelegateEditors.h" ugene-1.9.8/src/include/U2Designer/DesignerUtils.h0000644000175000017500000000007111651544335020432 0ustar ilyailya#include "../../corelibs/U2Designer/src/DesignerUtils.h" ugene-1.9.8/src/include/U2Algorithm/0000755000175000017500000000000011651544335015670 5ustar ilyailyaugene-1.9.8/src/include/U2Algorithm/StructuralAlignmentAlgorithmRegistry.h0000644000175000017500000000014611651544335025451 0ustar ilyailya#include "../../corelibs/U2Algorithm/src/structural_alignment/StructuralAlignmentAlgorithmRegistry.h" ugene-1.9.8/src/include/U2Algorithm/MSAConsensusAlgorithmLevitsky.h0000644000175000017500000000013511651544335023763 0ustar ilyailya#include "../../corelibs/U2Algorithm/src/util_msa_consensus/MSAConsensusAlgorithmLevitsky.h" ugene-1.9.8/src/include/U2Algorithm/SmithWatermanReportCallback.h0000644000175000017500000000012711651544335023435 0ustar ilyailya#include "../../corelibs/U2Algorithm/src/smith_waterman/SmithWatermanReportCallback.h" ugene-1.9.8/src/include/U2Algorithm/SmithWatermanResult.h0000644000175000017500000000011711651544335022022 0ustar ilyailya#include "../../corelibs/U2Algorithm/src/smith_waterman/SmithWatermanResult.h" ugene-1.9.8/src/include/U2Algorithm/SecStructPredictAlgRegistry.h0000644000175000017500000000012111651544335023442 0ustar ilyailya#include "../../corelibs/U2Algorithm/src/registry/SecStructPredictAlgRegistry.h" ugene-1.9.8/src/include/U2Algorithm/CudaGpuRegistry.h0000644000175000017500000000010511651544335021116 0ustar ilyailya#include "../../corelibs/U2Algorithm/src/registry/CudaGpuRegistry.h" ugene-1.9.8/src/include/U2Algorithm/CreatePhyTreeSettings.h0000644000175000017500000000011311651544335022261 0ustar ilyailya#include "../../corelibs/U2Algorithm/src/phyltree/CreatePhyTreeSettings.h" ugene-1.9.8/src/include/U2Algorithm/SArrayBasedFindTask.h0000644000175000017500000000011711651544335021624 0ustar ilyailya#include "../../corelibs/U2Algorithm/src/util_algorithm/SArrayBasedFindTask.h" ugene-1.9.8/src/include/U2Algorithm/RollingMatrix.h0000644000175000017500000000011111651544335020625 0ustar ilyailya#include "../../corelibs/U2Algorithm/src/util_algorithm/RollingMatrix.h" ugene-1.9.8/src/include/U2Algorithm/SArrayIndex.h0000644000175000017500000000010711651544335020230 0ustar ilyailya#include "../../corelibs/U2Algorithm/src/util_algorithm/SArrayIndex.h" ugene-1.9.8/src/include/U2Algorithm/MSAConsensusAlgorithm.h0000644000175000017500000000012511651544335022227 0ustar ilyailya#include "../../corelibs/U2Algorithm/src/util_msa_consensus/MSAConsensusAlgorithm.h" ugene-1.9.8/src/include/U2Algorithm/BuiltInDistanceAlgorithms.h0000644000175000017500000000013011651544334023105 0ustar ilyailya#include "../../corelibs/U2Algorithm/src/util_msa_distance/BuiltInDistanceAlgorithms.h" ugene-1.9.8/src/include/U2Algorithm/SecStructPredictTask.h0000644000175000017500000000011211651544335022110 0ustar ilyailya#include "../../corelibs/U2Algorithm/src/registry/SecStructPredictTask.h" ugene-1.9.8/src/include/U2Algorithm/RepeatFinderTaskFactoryRegistry.h0000644000175000017500000000012511651544335024313 0ustar ilyailya#include "../../corelibs/U2Algorithm/src/registry/RepeatFinderTaskFactoryRegistry.h" ugene-1.9.8/src/include/U2Algorithm/MSAConsensusAlgorithmClustal.h0000644000175000017500000000013411651544335023557 0ustar ilyailya#include "../../corelibs/U2Algorithm/src/util_msa_consensus/MSAConsensusAlgorithmClustal.h" ugene-1.9.8/src/include/U2Algorithm/SmithWatermanTaskFactoryRegistry.h0000644000175000017500000000013411651544335024526 0ustar ilyailya#include "../../corelibs/U2Algorithm/src/smith_waterman/SmithWatermanTaskFactoryRegistry.h" ugene-1.9.8/src/include/U2Algorithm/SmithWatermanUtil.h0000644000175000017500000000011511651544335021457 0ustar ilyailya#include "../../corelibs/U2Algorithm/src/smith_waterman/SmithWatermanUtil.h" ugene-1.9.8/src/include/U2Algorithm/BuiltInConsensusAlgorithms.h0000644000175000017500000000013211651544334023335 0ustar ilyailya#include "../../corelibs/U2Algorithm/src/util_msa_consensus/BuiltInConsensusAlgorithms.h" ugene-1.9.8/src/include/U2Algorithm/PhyTreeGeneratorRegistry.h0000644000175000017500000000011611651544335023017 0ustar ilyailya#include "../../corelibs/U2Algorithm/src/phyltree/PhyTreeGeneratorRegistry.h" ugene-1.9.8/src/include/U2Algorithm/OpenCLUtils.h0000644000175000017500000000011211651544335020174 0ustar ilyailya#include "../../corelibs/U2Algorithm/src/util_gpu/opencl/OpenCLUtils.h" ugene-1.9.8/src/include/U2Algorithm/FindAlgorithm.h0000644000175000017500000000011111651544335020561 0ustar ilyailya#include "../../corelibs/U2Algorithm/src/util_algorithm/FindAlgorithm.h" ugene-1.9.8/src/include/U2Algorithm/VanDerWaalsSurface.h0000644000175000017500000000012211651544335021514 0ustar ilyailya#include "../../corelibs/U2Algorithm/src/molecular_geometry/VanDerWaalsSurface.h" ugene-1.9.8/src/include/U2Algorithm/cl_platform.h0000644000175000017500000000011711651544335020342 0ustar ilyailya#include "../../corelibs/U2Algorithm/src/util_gpu/opencl/legacy/cl_platform.h" ugene-1.9.8/src/include/U2Algorithm/MSAConsensusAlgorithmRegistry.h0000644000175000017500000000013511651544335023761 0ustar ilyailya#include "../../corelibs/U2Algorithm/src/util_msa_consensus/MSAConsensusAlgorithmRegistry.h" ugene-1.9.8/src/include/U2Algorithm/PWMConversionAlgorithmLOD.h0000644000175000017500000000013111651544335022753 0ustar ilyailya#include "../../corelibs/U2Algorithm/src/util_weight_matrix/PWMConversionAlgorithmLOD.h" ugene-1.9.8/src/include/U2Algorithm/MSAAlignAlgRegistry.h0000644000175000017500000000011111651544335021602 0ustar ilyailya#include "../../corelibs/U2Algorithm/src/registry/MSAAlignAlgRegistry.h" ugene-1.9.8/src/include/U2Algorithm/EnzymeModel.h0000644000175000017500000000010711651544335020267 0ustar ilyailya#include "../../corelibs/U2Algorithm/src/util_algorithm/EnzymeModel.h" ugene-1.9.8/src/include/U2Algorithm/GeomUtils.h0000644000175000017500000000011111651544335017742 0ustar ilyailya#include "../../corelibs/U2Algorithm/src/molecular_geometry/GeomUtils.h" ugene-1.9.8/src/include/U2Algorithm/RepeatFinderTaskFactory.h0000644000175000017500000000012711651544335022564 0ustar ilyailya#include "../../corelibs/U2Algorithm/src/util_repeat_finder/RepeatFinderTaskFactory.h" ugene-1.9.8/src/include/U2Algorithm/CreateSubalignmentTask.h0000644000175000017500000000012011651544335022431 0ustar ilyailya#include "../../corelibs/U2Algorithm/src/util_msaedit/CreateSubalignmentTask.h" ugene-1.9.8/src/include/U2Algorithm/cl.h0000644000175000017500000000010611651544335016434 0ustar ilyailya#include "../../corelibs/U2Algorithm/src/util_gpu/opencl/legacy/cl.h" ugene-1.9.8/src/include/U2Algorithm/DnaAssemblyTask.h0000644000175000017500000000010511651544335021062 0ustar ilyailya#include "../../corelibs/U2Algorithm/src/registry/DnaAssemblyTask.h" ugene-1.9.8/src/include/U2Algorithm/PWMConversionAlgorithm.h0000644000175000017500000000012611651544335022420 0ustar ilyailya#include "../../corelibs/U2Algorithm/src/util_weight_matrix/PWMConversionAlgorithm.h" ugene-1.9.8/src/include/U2Algorithm/MolecularSurface.h0000644000175000017500000000012011651544335021266 0ustar ilyailya#include "../../corelibs/U2Algorithm/src/molecular_geometry/MolecularSurface.h" ugene-1.9.8/src/include/U2Algorithm/MSAConsensusAlgorithmDefault.h0000644000175000017500000000013411651544335023534 0ustar ilyailya#include "../../corelibs/U2Algorithm/src/util_msa_consensus/MSAConsensusAlgorithmDefault.h" ugene-1.9.8/src/include/U2Algorithm/SubstMatrixRegistry.h0000644000175000017500000000011111651544335022050 0ustar ilyailya#include "../../corelibs/U2Algorithm/src/registry/SubstMatrixRegistry.h" ugene-1.9.8/src/include/U2Algorithm/RepeatFinderSettings.h0000644000175000017500000000012411651544335022127 0ustar ilyailya#include "../../corelibs/U2Algorithm/src/util_repeat_finder/RepeatFinderSettings.h" ugene-1.9.8/src/include/U2Algorithm/MSAConsensusUtils.h0000644000175000017500000000012111651544335021375 0ustar ilyailya#include "../../corelibs/U2Algorithm/src/util_msa_consensus/MSAConsensusUtils.h" ugene-1.9.8/src/include/U2Algorithm/MSADistanceAlgorithmRegistry.h0000644000175000017500000000013311651544335023531 0ustar ilyailya#include "../../corelibs/U2Algorithm/src/util_msa_distance/MSADistanceAlgorithmRegistry.h" ugene-1.9.8/src/include/U2Algorithm/MolecularSurfaceFactoryRegistry.h0000644000175000017500000000013711651544335024357 0ustar ilyailya#include "../../corelibs/U2Algorithm/src/molecular_geometry/MolecularSurfaceFactoryRegistry.h" ugene-1.9.8/src/include/U2Algorithm/SmithWatermanResultFilters.h0000644000175000017500000000012611651544335023353 0ustar ilyailya#include "../../corelibs/U2Algorithm/src/smith_waterman/SmithWatermanResultFilters.h" ugene-1.9.8/src/include/U2Algorithm/MSADistanceAlgorithmHamming.h0000644000175000017500000000013211651544335023300 0ustar ilyailya#include "../../corelibs/U2Algorithm/src/util_msa_distance/MSADistanceAlgorithmHamming.h" ugene-1.9.8/src/include/U2Algorithm/FindAlgorithmTask.h0000644000175000017500000000011511651544335021410 0ustar ilyailya#include "../../corelibs/U2Algorithm/src/util_algorithm/FindAlgorithmTask.h" ugene-1.9.8/src/include/U2Algorithm/StructuralAlignmentAlgorithm.h0000644000175000017500000000013611651544335023717 0ustar ilyailya#include "../../corelibs/U2Algorithm/src/structural_alignment/StructuralAlignmentAlgorithm.h" ugene-1.9.8/src/include/U2Algorithm/SWResultFilterRegistry.h0000644000175000017500000000012211651544335022463 0ustar ilyailya#include "../../corelibs/U2Algorithm/src/smith_waterman/SWResultFilterRegistry.h" ugene-1.9.8/src/include/U2Algorithm/MSAAlignTask.h0000644000175000017500000000010211651544335020250 0ustar ilyailya#include "../../corelibs/U2Algorithm/src/registry/MSAAlignTask.h" ugene-1.9.8/src/include/U2Algorithm/DnaAssemblyMultiTask.h0000644000175000017500000000012311651544335022075 0ustar ilyailya#include "../../corelibs/U2Algorithm/src/util_dna_assembly/DnaAssemblyMultiTask.h" ugene-1.9.8/src/include/U2Algorithm/BuiltInPWMConversionAlgorithms.h0000644000175000017500000000013611651544334024072 0ustar ilyailya#include "../../corelibs/U2Algorithm/src/util_weight_matrix/BuiltInPWMConversionAlgorithms.h" ugene-1.9.8/src/include/U2Algorithm/PWMConversionAlgorithmBVH.h0000644000175000017500000000013111651544335022754 0ustar ilyailya#include "../../corelibs/U2Algorithm/src/util_weight_matrix/PWMConversionAlgorithmBVH.h" ugene-1.9.8/src/include/U2Algorithm/SArrayIndexSerializer.h0000644000175000017500000000012111651544335022256 0ustar ilyailya#include "../../corelibs/U2Algorithm/src/util_algorithm/SArrayIndexSerializer.h" ugene-1.9.8/src/include/U2Algorithm/PWMConversionAlgorithmNLG.h0000644000175000017500000000013111651544335022755 0ustar ilyailya#include "../../corelibs/U2Algorithm/src/util_weight_matrix/PWMConversionAlgorithmNLG.h" ugene-1.9.8/src/include/U2Algorithm/StructuralAlignmentAlgorithmFactory.h0000644000175000017500000000014511651544335025247 0ustar ilyailya#include "../../corelibs/U2Algorithm/src/structural_alignment/StructuralAlignmentAlgorithmFactory.h" ugene-1.9.8/src/include/U2Algorithm/RollingArray.h0000644000175000017500000000011011651544335020436 0ustar ilyailya#include "../../corelibs/U2Algorithm/src/util_algorithm/RollingArray.h" ugene-1.9.8/src/include/U2Algorithm/PWMConversionAlgorithmMCH.h0000644000175000017500000000013111651544335022744 0ustar ilyailya#include "../../corelibs/U2Algorithm/src/util_weight_matrix/PWMConversionAlgorithmMCH.h" ugene-1.9.8/src/include/U2Algorithm/DynTable.h0000644000175000017500000000010411651544335017536 0ustar ilyailya#include "../../corelibs/U2Algorithm/src/util_algorithm/DynTable.h" ugene-1.9.8/src/include/U2Algorithm/DnaAssemblyAlgRegistry.h0000644000175000017500000000011411651544335022414 0ustar ilyailya#include "../../corelibs/U2Algorithm/src/registry/DnaAssemblyAlgRegistry.h" ugene-1.9.8/src/include/U2Algorithm/MSADistanceAlgorithmHammingRevCompl.h0000644000175000017500000000014211651544335024751 0ustar ilyailya#include "../../corelibs/U2Algorithm/src/util_msa_distance/MSADistanceAlgorithmHammingRevCompl.h" ugene-1.9.8/src/include/U2Algorithm/MSADistanceAlgorithm.h0000644000175000017500000000012311651544335021777 0ustar ilyailya#include "../../corelibs/U2Algorithm/src/util_msa_distance/MSADistanceAlgorithm.h" ugene-1.9.8/src/include/U2Algorithm/BitsTable.h0000644000175000017500000000010511651544334017705 0ustar ilyailya#include "../../corelibs/U2Algorithm/src/util_algorithm/BitsTable.h" ugene-1.9.8/src/include/U2Algorithm/SmithWatermanTaskFactory.h0000644000175000017500000000012411651544335022774 0ustar ilyailya#include "../../corelibs/U2Algorithm/src/smith_waterman/SmithWatermanTaskFactory.h" ugene-1.9.8/src/include/U2Algorithm/PhyTreeGeneratorTask.h0000644000175000017500000000011211651544335022105 0ustar ilyailya#include "../../corelibs/U2Algorithm/src/phyltree/PhyTreeGeneratorTask.h" ugene-1.9.8/src/include/U2Algorithm/ORFFinder.h0000644000175000017500000000010511651544335017613 0ustar ilyailya#include "../../corelibs/U2Algorithm/src/util_algorithm/ORFFinder.h" ugene-1.9.8/src/include/U2Algorithm/OpenCLHelper.h0000644000175000017500000000011111651544335020312 0ustar ilyailya#include "../../corelibs/U2Algorithm/src/util_gpu/opencl/OpenCLHelper.h" ugene-1.9.8/src/include/U2Algorithm/PhyTreeGenerator.h0000644000175000017500000000010611651544335021265 0ustar ilyailya#include "../../corelibs/U2Algorithm/src/phyltree/PhyTreeGenerator.h" ugene-1.9.8/src/include/U2Algorithm/BinaryFindOpenCL.h0000644000175000017500000000011411651544334021122 0ustar ilyailya#include "../../corelibs/U2Algorithm/src/util_algorithm/BinaryFindOpenCL.h" ugene-1.9.8/src/include/U2Algorithm/SmithWatermanSettings.h0000644000175000017500000000012111651544335022337 0ustar ilyailya#include "../../corelibs/U2Algorithm/src/smith_waterman/SmithWatermanSettings.h" ugene-1.9.8/src/include/U2Algorithm/PWMConversionAlgorithmRegistry.h0000644000175000017500000000013611651544335024152 0ustar ilyailya#include "../../corelibs/U2Algorithm/src/util_weight_matrix/PWMConversionAlgorithmRegistry.h" ugene-1.9.8/src/include/U2Algorithm/MAlignmentUtilTasks.h0000644000175000017500000000011511651544335021735 0ustar ilyailya#include "../../corelibs/U2Algorithm/src/util_msaedit/MAlignmentUtilTasks.h" ugene-1.9.8/src/include/U2Algorithm/CDSearchTaskFactoryRegistry.h0000644000175000017500000000012011651544335023352 0ustar ilyailya#include "../../corelibs/U2Algorithm/src/registry/CDSearchTaskFactoryRegistry.h"ugene-1.9.8/src/include/U2Algorithm/CDSearchTaskFactory.h0000644000175000017500000000011011651544335021620 0ustar ilyailya#include "../../corelibs/U2Algorithm/src/util_cds/CDSearchTaskFactory.h"ugene-1.9.8/src/include/U2Algorithm/OpenCLGpuRegistry.h0000644000175000017500000000010711651544335021364 0ustar ilyailya#include "../../corelibs/U2Algorithm/src/registry/OpenCLGpuRegistry.h" ugene-1.9.8/src/include/U2Algorithm/ORFAlgorithmTask.h0000644000175000017500000000011411651544335021155 0ustar ilyailya#include "../../corelibs/U2Algorithm/src/util_algorithm/ORFAlgorithmTask.h" ugene-1.9.8/src/include/U2Algorithm/MSAConsensusAlgorithmStrict.h0000644000175000017500000000013311651544335023417 0ustar ilyailya#include "../../corelibs/U2Algorithm/src/util_msa_consensus/MSAConsensusAlgorithmStrict.h" ugene-1.9.8/src/plugins_3rdparty/0000755000175000017500000000000011651544320015413 5ustar ilyailyaugene-1.9.8/src/plugins_3rdparty/hmm2/0000755000175000017500000000000011651544312016257 5ustar ilyailyaugene-1.9.8/src/plugins_3rdparty/hmm2/hmm2.pro0000644000175000017500000000556311651544326017662 0ustar ilyailyainclude (hmm2.pri) # Input HEADERS += src/HMMIO.h \ src/HMMIOWorker.h \ src/TaskLocalStorage.h \ src/uHMMPlugin.h \ src/hmmer2/config.h \ src/hmmer2/funcs.h \ src/hmmer2/structs.h \ src/u_build/HMMBuildDialogController.h \ src/u_build/HMMBuildWorker.h \ src/u_build/uhmmbuild.h \ src/u_calibrate/HMMCalibrateDialogController.h \ src/u_calibrate/HMMCalibrateTask.h \ src/u_calibrate/uhmmcalibrate.h \ src/u_search/hmmer_ppu.h \ src/u_search/HMMSearchDialogController.h \ src/u_search/HMMSearchTask.h \ src/u_search/HMMSearchWorker.h \ src/u_search/uhmmsearch.h \ src/u_search/uhmmsearch_cell.h \ src/u_search/uhmmsearch_opt.h \ src/u_search/uhmmsearch_sse.h \ src/u_spu/hmmer_spu.h \ src/u_tests/uhmmerTests.h FORMS += src/u_build/ui/HMMBuildDialog.ui \ src/u_calibrate/ui/HMMCalibrateDialog.ui \ src/u_search/ui/HMMSearchDialog.ui SOURCES += src/HMMIO.cpp \ src/HMMIOWorker.cpp \ src/TaskLocalStorage.cpp \ src/uHMMPlugin.cpp \ src/hmmer2/aligneval.cpp \ src/hmmer2/alphabet.cpp \ src/hmmer2/altivec_algorithms.cpp \ src/hmmer2/checksum.cpp \ src/hmmer2/cluster.cpp \ src/hmmer2/core_algorithms.cpp \ src/hmmer2/fast_algorithms.cpp \ src/hmmer2/histogram.cpp \ src/hmmer2/iupac.cpp \ src/hmmer2/masks.cpp \ src/hmmer2/mathsupport.cpp \ src/hmmer2/modelmakers.cpp \ src/hmmer2/msa.cpp \ src/hmmer2/plan7.cpp \ src/hmmer2/prior.cpp \ src/hmmer2/sqerror.cpp \ src/hmmer2/sre_math.cpp \ src/hmmer2/sre_random.cpp \ src/hmmer2/sre_string.cpp \ src/hmmer2/tophits.cpp \ src/hmmer2/trace.cpp \ src/hmmer2/vectorops.cpp \ src/hmmer2/weight.cpp \ src/u_build/HMMBuildDialogController.cpp \ src/u_build/HMMBuildWorker.cpp \ src/u_build/uhmmbuild.cpp \ src/u_calibrate/HMMCalibrateDialogController.cpp \ src/u_calibrate/HMMCalibrateTask.cpp \ src/u_calibrate/uhmmcalibrate.cpp \ src/u_search/hmmer_ppu.cpp \ src/u_search/HMMSearchDialogController.cpp \ src/u_search/HMMSearchTask.cpp \ src/u_search/HMMSearchWorker.cpp \ src/u_search/uhmmsearch.cpp \ src/u_search/uhmmsearch_cell.cpp \ src/u_search/uhmmsearch_opt.cpp \ src/u_search/uhmmsearch_sse.cpp \ src/u_spu/hmmer_spu.c \ src/u_spu/hmmercell_spu.c \ src/u_tests/uhmmerTests.cpp RESOURCES += hmm2.qrc TRANSLATIONS += transl/english.ts transl/russian.ts ugene-1.9.8/src/plugins_3rdparty/hmm2/hmm2.qrc0000644000175000017500000000027011651544326017635 0ustar ilyailya images/hmmer_16.png images/hmmer_32.png images/hmmer_64.png ugene-1.9.8/src/plugins_3rdparty/hmm2/images/0000755000175000017500000000000011651544311017523 5ustar ilyailyaugene-1.9.8/src/plugins_3rdparty/hmm2/images/hmmer_16.png0000644000175000017500000000042711651544326021660 0ustar ilyailyaPNG  IHDR(-StEXtSoftwareAdobe ImageReadyqe<0PLTEЧѐqڞ솟oLLlOLLLLyPtRNS#]aIDATxd VQ. Lm쵲 Ř وK"V2h7oHwcLXR a‹0#30- IENDB`ugene-1.9.8/src/plugins_3rdparty/hmm2/images/hmmer_32.png0000644000175000017500000000364711651544326021665 0ustar ilyailyaPNG  IHDR tEXtSoftwareAdobe ImageReadyqe<IIDATxڬV{pTι}߯$]` !48! FLAp} ~QfMYX jA@c%j"emӕN?0Tª "dB.yd=FDxbԡi]t@6[^ ;#12L "UKE눌D Щ=;a퉂+~4˞"=x3|t(+MO[<5vIM7HYy@n]~-8AFW"C.r'P1WJU<$'юQc z>Vv|YK$dw] >N`TÎ/dˉt#Los]ۯ^kXGĈMbkgPOmwʰtN@X6ƺs{Z+iMK=%aP \:v3/1OY1 ɉ89|[(?ȟRyQU04(Mtxiъ=]s&~׍՗5~مO$H. n+%4fp: = f`uz8N1TEl 8i1|u&)gFΈ$ϔmm6;wv_7?8<<ȩ7`7͠ y09p:uGktp˒m+%ZRI%[^4>q`I_{K3dMІ9m.ɣ0f$eJ"gCj]M_nРVwoiKsgk/byQ0T޼kaQͱBG1Hs$b:}еΠbjnѧrߴ@_-k<"G?y஢"w۷vc;yD)$$/q+1g~F72UT8I>mg8i"טQD,v>7>(`}Tpc$f";:xřcdM9;o4t'v>V,j@Ee,>ycuUG=;ac1>d;%UR nVt4ԹX4E6"M,~_@i(_c(\A3f# *`ZZ<>xMK[>Yv{0㞁4\^dZI fg)(B#cϕcr֩[+5̬|;Ua8^CIENDB`ugene-1.9.8/src/plugins_3rdparty/hmm2/images/hmmer_64.png0000644000175000017500000001115111651544326021657 0ustar ilyailyaPNG  IHDR@@% tEXtSoftwareAdobe ImageReadyqe< IDATxZ xTE[=B [HdADDEĕ>GYFeEGe6θ(I Y$@B^sLT݉|O_{9uszgz<qjPG6s!Cg%"6@o(_S_B$yf.?HUX볋XiD-WVfG:8GdώA@ܵ5i(׿uhN#c1-F%Hr$pr&5l(6 e1ow'h(. 0X=baYAɅEv`N'cxBfQ8x' hd+HNlFHn?B*34 d^dUc!D=)!m=<|L6705Ɖ֠Ò^k.eį#2T踆60ɐY"?|p ٌK릈;?:YRu6=<½8wgX"pN{OrK(pb8woS2N#4,vVޮd*N')͜i͜Qaz`P[^Bv&4ðYinUVNGǫ UW0Fs wdFMm?i})SCg,̛423^[pviI8Gɒz iN[ l b/v֦vFtRKsW߫zk18Sia゙;ZdhPEhO$fH @:HohWgiFI/q]p"}x0$|OS0jJa\ VA.12\Qz}[knB1zB7C6^oB4H Q^btXEk@RY$p%V-WW[M) }~ !N~4=?hcU>xkH/S{X/ r)qaRHwCEwh'^WGZp>EqŦ [T%iPRgAE6,4o!i VfMbBbWX I맇rʱ*5Yfyc2KgñPkLq写=y.7zu=6G$!q@Uf\SXL8t k:{u Y@b%?Dx]U6aV.,\tUzȧP/~n1F9W у")Dh˜)V*ez<ު7y@xw vp6soBʳڱpYS@} g ڗ@qɜ)gb_v&ZܖUb.6Nb3DųJv6Y<ʾ5L:(Cـ1Ü 5 LI~MaN/zh6ybzAאrV"6'v-k|*4)-9}ϿU*GЙλ;kBZx Hn;'TfϖSBc9)hDIO{?rr0>lw(k~ <⌾ᥤ@~')w:3`uPW.q=D tVawGzVhڢ~'lPIQDν8xx'a7Z%kAm8oo=βLdŴחIeEE$f"mX h"1?\Zbvv ɯyed M1)Tm[4hM^y/|YM*W*W?4~X]1-l$L0,)5hVNpKt9C܇eݭWZ=_U=`!WupoK#EsO\ \eͪ}7p8eVJLRPjt9ou~l{,nڳ:{af|x)xYlY[2\W^JpYy4&w yUOԴ5+76j;?i̵ͯ>`͡eʼn>Ⳮ@˶r_nXіiH:fPm17GzI? RzA=xSA.[5Y޽~"c%E 4# nAt PjVׄ}e{6h{ǼW9f̤BDc=\2E +A-^;{nkto/C \o#b AUW+ت!V*O4hx 8E:(P!7n|+vS]&MʼnRs eD:!.F(x oH@I'w%.I (0|֔_.[XW>xM7mQjqv2'.s`\' nzZ9gv:—o9M[ !C.Ix'^ḭ+?IUyYa_Q92 Ɓ=o2[  M=;&4J6Y҂ o)(ToĴYs?fx"s8"}A;/~m' |߆F8AKlN6Ӄ~UU>9s*4$v*8Ƈj nNLHЯ,Ⱥi!+_$1-:%]u 9㓛xJ/4{1;v:'\mSeU/N66%0P;;%lS"늡q83w"V@g> *ƭ:ZGn0Qb"k3㲳yp&*Y@a 8V@ Ko{XG̴$rb2Xqة#c ~*"b.MLk J~#ldXڗa[ӳ%qlKC~r*IENDB`ugene-1.9.8/src/plugins_3rdparty/hmm2/hmm2.pri0000644000175000017500000000207611651544326017650 0ustar ilyailya# include (hmm2.pri) PLUGIN_ID=hmm2 PLUGIN_NAME=HMM2 PLUGIN_VENDOR=Unipro CONFIG += warn_off include( ../../ugene_plugin_common.pri ) win32 { QMAKE_CXXFLAGS+=/wd4244 /wd4305 } unix { contains( UGENE_CELL, 1 ) { # message( "building for Cell BE..." ) INCLUDEPATH += $(CELL_TOP)/usr/include DEFINES += ALTIVEC USE_SDK30 UGENE_CELL LIBS += -m32 -lspe2 -lsync src/u_spu/hmmercell_spu.a -lm QMAKE_LIBDIR += $(CELL_TOP)/usr/lib QMAKE_CXXFLAGS += -maltivec QMAKE_CLEAN += src/u_spu/*.d src/u_spu/*.o src/u_spu/*.a src/u_spu/hmmercell_spu target.depends = spe spe.target = src/u_spu/hmmercell_spu.a spe.commands = cd src/u_spu && make -f makefile USE_SDK30=1 QMAKE_EXTRA_TARGETS = spe PRE_TARGETDEPS = src/u_spu/hmmercell_spu.a } } #adding SSE2 gcc compiler flag if building on SSE2 capable CPU use_sse2() { !win32 { QMAKE_CXXFLAGS += -msse2 QMAKE_CFLAGS_DEBUG += -msse2 QMAKE_CFLAGS_RELEASE += -msse2 } DEFINES += HMMER_BUILD_WITH_SSE2 } ugene-1.9.8/src/plugins_3rdparty/hmm2/src/0000755000175000017500000000000011651544312017046 5ustar ilyailyaugene-1.9.8/src/plugins_3rdparty/hmm2/src/TaskLocalStorage.cpp0000644000175000017500000000510011651544326022755 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "TaskLocalStorage.h" HMMERTaskLocalData::HMMERTaskLocalData() { sre_randseed = 42; rnd = 0; rnd1 = 0; rnd2 = 0; } struct HMMERTaskLocalData *getHMMERTaskLocalData() { return U2::TaskLocalData::current(); } namespace U2 { QHash TaskLocalData::data; QThreadStorage TaskLocalData::tls; QMutex TaskLocalData::mutex; HMMERTaskLocalData* TaskLocalData::current(){ static HMMERTaskLocalData def; ContextIdContainer* idc = tls.localData(); if (idc!=NULL){ QMutexLocker ml(&mutex); HMMERTaskLocalData* res = data.value(idc->contextId); assert(res!=NULL); return res; } else { return &def; } } HMMERTaskLocalData* TaskLocalData::createHMMContext(qint64 contextId, bool bindThreadToContext) { QMutexLocker ml(&mutex); assert(!data.contains(contextId)); HMMERTaskLocalData* ctx = new HMMERTaskLocalData(); data[contextId] = ctx; if (bindThreadToContext) { bindToHMMContext(contextId); } return ctx; } void TaskLocalData::freeHMMContext(qint64 contextId) { QMutexLocker ml(&mutex); HMMERTaskLocalData* v = data.value(contextId); assert(v!=NULL); int n = data.remove(contextId); Q_UNUSED(n); assert(n == 1); delete v; } void TaskLocalData::bindToHMMContext(qint64 contextId){ assert(!tls.hasLocalData()); ContextIdContainer* idc = new ContextIdContainer(contextId); tls.setLocalData(idc); } qint64 TaskLocalData::detachFromHMMContext() { ContextIdContainer *idc = tls.localData(); assert(idc!=NULL); qint64 contextId = idc->contextId; tls.setLocalData(NULL); //automatically deletes prev data return contextId; } }//namespace ugene-1.9.8/src/plugins_3rdparty/hmm2/src/u_search/0000755000175000017500000000000011651544311020636 5ustar ilyailyaugene-1.9.8/src/plugins_3rdparty/hmm2/src/u_search/uhmmsearch.cpp0000644000175000017500000002346211651544327023514 0ustar ilyailya#include "uhmmsearch.h" #include #include #include #include #include #ifdef UGENE_CELL #include "hmmer_ppu.h" #include "uhmmsearch_cell.h" #endif #include "uhmmsearch_opt.h" #ifdef HMMER_BUILD_WITH_SSE2 #include "uhmmsearch_sse.h" #endif namespace U2 { static void main_loop_serial(struct plan7_s *hmm, const char* seq, int seqLen, struct threshold_s *thresh, int do_forward, int do_null2, int do_xnu, struct histogram_s *histogram, struct tophit_s *ghit, struct tophit_s *dhit, int *ret_nseq, TaskStateInfo& ti); QList UHMMSearch::search(plan7_s* _hmm, const char* seq, int seqLen, const UHMMSearchSettings& s, TaskStateInfo& si) { plan7_s * hmm = HMMIO::cloneHMM( _hmm ); //Set up optional Pfam score thresholds. threshold_s thresh; // contains all threshold (cutoff) info thresh.globE = s.globE; // use a reasonable Eval threshold thresh.globT = -FLT_MAX; // but no bit threshold thresh.domT = s.domT; // no domain bit threshold thresh.domE = s.domE; // and no domain Eval threshold thresh.autocut = CUT_NONE; // and no Pfam cutoffs used thresh.Z = s.eValueNSeqs; // Z not preset; use actual # of seqs int do_null2 = TRUE; // TRUE to adjust scores with null model #2 int do_forward = FALSE; // TRUE to use Forward() not Viterbi() int do_xnu = FALSE; // TRUE to filter sequences thru XNU QList res; // the results of the method //get HMMERTaskLocalData HMMERTaskLocalData *tld = getHMMERTaskLocalData(); alphabet_s *al = &tld->al; SetAlphabet(hmm->atype); P7Logoddsify(hmm, !do_forward); //TODO: clone model to avoid changes in it or make it thread safe?? if (do_xnu && al->Alphabet_type == hmmNUCLEIC) { si.setError( "The HMM is a DNA model, and you can't use the --xnu filter on DNA data" ); return res; } /***************************************************************** * Set up optional Pfam score thresholds. * Can do this before starting any searches, since we'll only use 1 HMM. *****************************************************************/ if (!SetAutocuts(&thresh, hmm)) { si.setError( "HMM did not contain the GA, TC, or NC cutoffs you needed" ); return res; } // set up structures for storing output histogram_s *histogram = AllocHistogram(-200, 200, 100); //keeps full histogram of all scores tophit_s *ghit = AllocTophits(200); // per-seq hits: 200=lumpsize tophit_s *dhit = AllocTophits(200); // domain hits: 200=lumpsize int nseq = 0; // number of sequences searched #ifdef UGENE_CELL if( HMMSearchAlgo_CellOptimized == s.alg ) { if( hmm->M < MAX_HMM_LENGTH ) { main_loop_spe(hmm, seq, seqLen, &thresh, do_forward, do_null2, do_xnu, histogram, ghit, dhit, &nseq, si); } else { main_loop_serial(hmm, seq, seqLen, &thresh, do_forward, do_null2, do_xnu, histogram, ghit, dhit, &nseq, si); } } else #elif defined(HMMER_BUILD_WITH_SSE2) if( HMMSearchAlgo_SSEOptimized == s.alg ) { main_loop_opt(hmm, seq, seqLen, &thresh, do_forward, do_null2, do_xnu, histogram, ghit, dhit, &nseq, si, sseScoring); } else #endif if( HMMSearchAlgo_Conservative == s.alg ) { main_loop_serial(hmm, seq, seqLen, &thresh, do_forward, do_null2, do_xnu, histogram, ghit, dhit, &nseq, si); } else { assert( false && "bad hmmsearch algorithm selected" ); } // Process hit lists, produce text output // Set the theoretical EVD curve in our histogram using calibration in the HMM, if available. if (hmm->flags & PLAN7_STATS) { ExtremeValueSetHistogram(histogram, hmm->mu, hmm->lambda, histogram->lowscore, histogram->highscore, 0); } if (!thresh.Z) { thresh.Z = nseq; // set Z for good now that we're done } //report our output FullSortTophits(dhit); //int namewidth = MAX(8, TophitsMaxName(ghit)); // max width of sequence name // Report domain hits (sorted on E-value) for (int i = 0; i < dhit->num && !si.cancelFlag; i++) { float sc; // score of an HMM search double pvalue; // pvalue of an HMM score double evalue; // evalue of an HMM score char *name, *desc; // hit sequence name and description double motherp; // pvalue of a whole seq HMM score float mothersc; // score of a whole seq parent of domain int sqfrom, sqto; // coordinates in sequence int sqlen; // length of seq that was hit int hmmfrom, hmmto; // coordinate in HMM int ndom; // total # of domains in this seq int domidx; // number of this domain GetRankedHit(dhit, i, &pvalue, &sc, &motherp, &mothersc, &name, NULL, &desc, &sqfrom, &sqto, &sqlen, // seq position info &hmmfrom, &hmmto, NULL, // HMM position info &domidx, &ndom, // domain info NULL); // alignment info evalue = pvalue * (double) thresh.Z; if (motherp * (double) thresh.Z > thresh.globE || mothersc < thresh.globT) { continue; } else if (evalue <= thresh.domE && sc >= thresh.domT) { // hmm reports results in range [1...N] -> translate it to [0..N) res.append(UHMMSearchResult(U2Region(sqfrom-1, sqto-sqfrom+1), sc, evalue)); } } //Clean-up and exit. FreeHistogram(histogram); FreeTophits(ghit); FreeTophits(dhit); FreePlan7( hmm ); return res; } // Function: main_loop_serial() // Date: SRE, Wed Sep 23 10:20:49 1998 [St. Louis] // // Purpose: Search an HMM against a sequence database. // main loop for the serial (non-PVM, non-threads) // version. // // In: HMM and open sqfile, plus options // Out: histogram, global hits list, domain hits list, nseq. // // Args: hmm - the HMM to search with. // seq, // seqLen // thresh - score/evalue threshold info // do_forward - TRUE to score using Forward() // do_null2 - TRUE to use ad hoc null2 score correction // do_xnu - TRUE to apply XNU mask // histogram - RETURN: score histogram // ghit - RETURN: ranked global scores // dhit - RETURN: ranked domain scores // ret_nseq - RETURN: actual number of seqs searched // // Returns: (void) static void main_loop_serial(struct plan7_s *hmm, const char* seq, int seqLen, struct threshold_s *thresh, int do_forward, int do_null2, int do_xnu, struct histogram_s *histogram, struct tophit_s *ghit, struct tophit_s *dhit, int *ret_nseq, TaskStateInfo& ti) { //get HMMERTaskLocalData HMMERTaskLocalData *tld = getHMMERTaskLocalData(); alphabet_s *al = &tld->al; struct dpmatrix_s *mx; // DP matrix, growable struct p7trace_s *tr; // traceback unsigned char *dsq; // digitized target sequence float sc; // score of an HMM search double pvalue; // pvalue of an HMM score double evalue; // evalue of an HMM score // Create a DP matrix; initially only two rows big, but growable; // we overalloc by 25 rows (L dimension) when we grow; not growable // in model dimension, since we know the hmm size mx = CreatePlan7Matrix(1, hmm->M, 25, 0); assert(seqLen > 0); dsq = DigitizeSequence(seq, seqLen); if (do_xnu && al->Alphabet_type == hmmAMINO) { XNU(dsq, seqLen); } // 1. Recover a trace by Viterbi. // In extreme cases, the alignment may be literally impossible; // in which case, the score comes out ridiculously small (but not // necessarily <= -INFTY, because we're not terribly careful // about underflow issues), and tr will be returned as NULL. if (P7ViterbiSpaceOK(seqLen, hmm->M, mx)) { sc = P7Viterbi(dsq, seqLen, hmm, mx, &tr); } else { sc = P7SmallViterbi(dsq, seqLen, hmm, mx, &tr, ti.progress); } // 2. If we're using Forward scores, calculate the // whole sequence score; this overrides anything // PostprocessSignificantHit() is going to do to the per-seq score. if (do_forward) { sc = P7Forward(dsq, seqLen, hmm, NULL); if (do_null2) sc -= TraceScoreCorrection(hmm, tr, dsq); } // 2. Store score/pvalue for global alignment; will sort on score, // which in hmmsearch is monotonic with E-value. // Keep all domains in a significant sequence hit. // We can only make a lower bound estimate of E-value since // we don't know the final value of nseq yet, so the list // of hits we keep in memory is >= the list we actually // output. // pvalue = PValue(hmm, sc); evalue = thresh->Z ? (double) thresh->Z * pvalue : (double) pvalue; if (sc >= thresh->globT && evalue <= thresh->globE) { sc = PostprocessSignificantHit(ghit, dhit, tr, hmm, dsq, seqLen, "sequence", //todo: sqinfo.name, NULL, NULL, do_forward, sc, do_null2, thresh, FALSE); // FALSE-> not hmmpfam mode, hmmsearch mode } AddToHistogram(histogram, sc); P7FreeTrace(tr); free(dsq); FreePlan7Matrix(mx); return; } } //namespace ugene-1.9.8/src/plugins_3rdparty/hmm2/src/u_search/uhmmsearch_cell.cpp0000644000175000017500000005144511651544327024515 0ustar ilyailya#ifdef UGENE_CELL #include "hmmer_ppu.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #ifdef USE_SDK30 #include #include #else #include #endif #include #include extern spe_program_handle_t hmmercell_spu; namespace U2 { #define NO_HUGE_PAGES #define NUM_OF_SEQS_UPPER_LIMIT 243971 #ifdef USE_SDK30 typedef struct spethreads_t { void *cb; spe_context_ptr_t speids; } spethreads_t; spethreads_t spethreads[16]; void *ppu_pthread_function(void *arg) { spethreads_t *threaddata = (spethreads_t *) arg; spe_context_ptr_t ctx; unsigned int entry = SPE_DEFAULT_ENTRY; ctx = threaddata->speids; if (spe_context_run(ctx, &entry, 0, threaddata->cb, NULL, NULL) < 0) { perror ("Failed running context"); exit (1); } pthread_exit(NULL); return NULL; } #endif void placeSequenceIntoBufferHP( const char * seq, int seqlen, int * seqArray, int * lenArray, int * currindex, spe_jobEntity * jobqueue, unsigned char ** addr ){ unsigned char * dsq; unsigned char * currPtr = *addr; int currentIndex = *currindex; spe_jobEntity * speJobQueue = jobqueue; assert( seqlen <= MAX_SEQ_LENGTH ); dsq = DigitizeSequenceHP(seq, seqlen, currPtr); assert( NULL != dsq ); currentIndex++; seqArray[currentIndex] = (unsigned long)dsq; lenArray[currentIndex] = (unsigned long)seqlen; speJobQueue[currentIndex].seqNumber = currentIndex; speJobQueue[currentIndex].seqAddr = (unsigned int)dsq; speJobQueue[currentIndex].seqLength = seqlen; speJobQueue[currentIndex].seqDMALength = (seqlen+129)&~0x7F; speJobQueue[currentIndex].seqProcessed = 0; speJobQueue[currentIndex].seqViterbiResult = 0.0; speJobQueue[currentIndex].seqTracebackStatus = TRACEBACK_UNCHECKED; speJobQueue[currentIndex].seqTraceAddr = 0; *currindex = *currindex + 1; currPtr = currPtr + seqlen + 2; currPtr = (unsigned char*) (((int) currPtr + 127) & (~0x7F)); *addr = currPtr; } class GlobalRegSearcher { public: int offset; GlobalRegSearcher( int _offs ) : offset(_offs) {}; bool operator() ( U2::U2Region reg ) { if( reg.startPos == offset ) { return true; } return false; } }; void main_loop_spe( struct plan7_s * hmm, const char * seq, int seqlen, struct threshold_s *thresh, int do_forward, int do_null2, int do_xnu, struct histogram_s * histogram, struct tophit_s * ghit, struct tophit_s * dhit, int * ret_nseq, U2::TaskStateInfo & ti) { Q_UNUSED( do_xnu ); Q_UNUSED( ret_nseq ); Q_UNUSED( ti ); // using namespace U2; int initBufSize = 1; int cushBufSize = initBufSize; struct dpmatrix_s * mx; struct p7trace_s * tr; float sc = .0f; double pvalue = 0.; double evalue = 0.; int SPE_THREADS = 8; int i = 0; int l = 0; #ifdef USE_SDK30 spe_context_ptr_t spe_ids[SPE_THREADS]; pthread_t threads[SPE_THREADS]; #else speid_t spe_ids[SPE_THREADS]; spe_gid_t spe_gid; #endif spe_initContextSB * spe_contexts; spe_jobEntity * jobQueue; int jobQueueIndex; volatile int nomoreSeqs_var __attribute__ ((aligned (128))); atomic_ea_t nomoreSeqs; addr64 long_addr_nomoreSeqs; volatile int lastConsumed_var __attribute__ ((aligned (128))); atomic_ea_t lastConsumed; addr64 long_addr_lastConsumed; volatile int bufferEntries_var __attribute__ ((aligned (128))); atomic_ea_t bufferEntries; addr64 long_addr_bufferEntries; volatile int bufferMutex_var __attribute__ ((aligned (128))); mutex_ea_t bufferMutex; addr64 long_addr_bufferMutex; volatile int bufferEmptyCond_var __attribute__ ((aligned (128))); cond_ea_t bufferEmptyCond; addr64 long_addr_bufferEmptyCond; int * scratchBuffer; hmm_offsets * offsets; int * sequencesMatrix; int * lengthMatrix; int numSeqs = 0; int numTracebacks = 0; char * mem_addr = NULL; unsigned char * seqAddr; int seqsFinished = 0; int numCushion = 0; /*--------------1 - SETUP: ALLOCATE MEMORY FOR DATA STRUCTURES---------------------*/ nomoreSeqs_var = 0; long_addr_nomoreSeqs.ui[0] = 0; long_addr_nomoreSeqs.ui[1] = (unsigned int) (&nomoreSeqs_var); nomoreSeqs = (atomic_ea_t) long_addr_nomoreSeqs.ull; lastConsumed_var = 0; long_addr_lastConsumed.ui[0] = 0; long_addr_lastConsumed.ui[1] = (unsigned int) (&lastConsumed_var); lastConsumed = (atomic_ea_t) long_addr_lastConsumed.ull; bufferEntries_var = 0; long_addr_bufferEntries.ui[0] = 0; long_addr_bufferEntries.ui[1] = (unsigned int) (&bufferEntries_var); bufferEntries = (atomic_ea_t) long_addr_bufferEntries.ull; bufferMutex_var = 0; long_addr_bufferMutex.ui[0] = 0; long_addr_bufferMutex.ui[1] = (unsigned int) (&bufferMutex_var); bufferMutex = (mutex_ea_t) long_addr_bufferMutex.ull; bufferEmptyCond_var = 0; long_addr_bufferEmptyCond.ui[0] = 0; long_addr_bufferEmptyCond.ui[1] = (unsigned int) (&bufferEmptyCond_var); bufferEmptyCond = (cond_ea_t) long_addr_bufferEmptyCond.ull; #ifndef NO_HUGE_PAGES assert( false && "correct huge pages realization is not implemented yet" ); //FIXME: implement correct 'huge pages' memory allocation #else mem_addr = (char *) memalign( 128, 0x09000000 ); memset( mem_addr, 0, 0x09000000 ); #endif assert( NULL != mem_addr ); //Allocate all data structures on mapped area scratchBuffer = (int*) (mem_addr + 0x0000000); offsets = (hmm_offsets*) (mem_addr + 0x0050000); spe_contexts = (spe_initContextSB*) (mem_addr + 0x0051000); sequencesMatrix = (int*) (mem_addr + 0x0400000); lengthMatrix = (int*) ((unsigned long)((char *)sequencesMatrix + NUM_OF_SEQS_UPPER_LIMIT * 4 + 127)&~0x7F); MakeHMMBuffer_Aligned(hmm, (void*) scratchBuffer, 0x0050000, offsets); /*--------------2 - CREATE INITIAL BUFFER---------------------*/ /* This stage is where we create a small preliminary buffer that will hold enough sequences to get the SPEs started. Once the SPE threads start fetching and processing sequences, we will be populating the buffer fully in Stage 4. */ jobQueue = (spe_jobEntity*) ((unsigned long)((char*)lengthMatrix + NUM_OF_SEQS_UPPER_LIMIT * 4 + 127)&~0x7F); seqAddr = (unsigned char *)jobQueue + NUM_OF_SEQS_UPPER_LIMIT * 128; jobQueueIndex = -1; atomic_set(bufferEntries,0); //Initialize mutexes etc. mutex_init(bufferMutex); cond_init(bufferEmptyCond); //FIXME refactoring needed //FIXME use non-constant chunk size U2Region wholeSeq( 0, seqlen ); // int veryMaxChunkSize = MAX_SEQ_LENGTH - 100; // int approxChunkSize = seqlen / 24; // int maxChunkSize = qBound( hmm->M, approxChunkSize, veryMaxChunkSize ); assert( hmm->M < MAX_HMM_LENGTH ); int overlap = hmm->M * 2; int exOverlap = 0; // int chunkSize = qMax( hmm->M+2, maxChunkSize-1 - overlap ); int chunkSize = qBound( hmm->M+2, MAX_SEQ_LENGTH-100, seqlen ); if( chunkSize + overlap > MAX_SEQ_LENGTH - 100 ) { chunkSize -= overlap; } int maxChunkSize = MAX_SEQ_LENGTH-100; QVector regions; regions = SequenceWalkerTask::splitRange( wholeSeq, chunkSize, overlap, 0, 1, false ); assert( !regions.empty() ); //hack caused by splitRange behaviour if( regions.first().length > maxChunkSize ) { // assert( 1 == regions.size() ); U2Region r1st = regions.takeFirst(); assert( r1st.length < 2 * maxChunkSize ); // int len = chunkSize + overlap / 2; int len = chunkSize; int tail = r1st.length - len; int z = overlap/2 - tail; len -= qMax( 0, z ); assert( 0 == r1st.startPos ); U2Region r1( r1st.startPos, len ); U2Region r2( len - overlap/2, r1st.length-(len-overlap/2) ); regions.push_front( r2 ); regions.push_front( r1 ); } foreach( U2Region r, regions ) { assert( r.length <= MAX_SEQ_LENGTH-100 ); } // Create an "initial buffer'. This should not take too much time, and will provide us with a // safety margin so that the SPEs can not overtake the PPEs. initBufSize = qMax(1, regions.size() / 2); cushBufSize = initBufSize; // initBufSize = qMin( initBufSize, regions.size() ); assert( initBufSize <= regions.size() ); for( i = 0; i < initBufSize; ++i ){ U2Region r = regions.at(i); assert( r.length < MAX_SEQ_LENGTH ); placeSequenceIntoBufferHP( seq + r.startPos, r.length, sequencesMatrix, lengthMatrix, &jobQueueIndex, jobQueue, &seqAddr ); //Read a new sequence into the buffer. atomic_inc(bufferEntries); numSeqs++; } SPE_THREADS = qMin( regions.size(), SPE_THREADS ); /*--------------3 - START SPE SEQUENCE PROCESSING---------------------*/ for (i = 0; i < SPE_THREADS; i++) { // Smart buffering does not use initial sequences. All SPE threads will fetch initial sequences // just like the rest of the sequences. spe_contexts[i].seq_addr = 0; spe_contexts[i].seq_name = ""; spe_contexts[i].seq_length = 0; spe_contexts[i].seq_dmalength = 0; spe_contexts[i].jobqueue_atomic_addr = 0; spe_contexts[i].jobqueue_begin_addr = (unsigned int) jobQueue; spe_contexts[i].jobqueue_num_seqs = 0; // Set the mutex and flag fields spe_contexts[i].bufferMutex_addr = (unsigned int) &bufferMutex_var; spe_contexts[i].bufferEmptyCond_addr = (unsigned int) &bufferEmptyCond_var; spe_contexts[i].bufferEntries_addr = (unsigned int) &bufferEntries_var; spe_contexts[i].lastConsumed_addr = (unsigned int) &lastConsumed_var; spe_contexts[i].nomoreSeqs_addr = (unsigned int) &nomoreSeqs_var; /* Set HMM-related fields */ spe_contexts[i].hmm_M = (unsigned int) hmm->M; spe_contexts[i].hmm_buf_begin = (unsigned int) scratchBuffer; spe_contexts[i].hmm_buf_length = (unsigned int) offsets->bufferLength; spe_contexts[i].offsets.escmem_offset = (unsigned int) offsets->escmem_offset; spe_contexts[i].offsets.bscmem_offset = (unsigned int) offsets->bscmem_offset; spe_contexts[i].offsets.mscmem_offset = (unsigned int) offsets->mscmem_offset; spe_contexts[i].offsets.iscmem_offset = (unsigned int) offsets->iscmem_offset; spe_contexts[i].offsets.xscmem_offset = (unsigned int) offsets->xscmem_offset; spe_contexts[i].offsets.tscmem_offset = (unsigned int) offsets->tscmem_offset; spe_contexts[i].offsets.tsc_TMM_mem_offset = (unsigned int) offsets->tsc_TMM_mem_offset; spe_contexts[i].offsets.tsc_TMI_mem_offset = (unsigned int) offsets->tsc_TMI_mem_offset; spe_contexts[i].offsets.tsc_TMD_mem_offset = (unsigned int) offsets->tsc_TMD_mem_offset; spe_contexts[i].offsets.tsc_TIM_mem_offset = (unsigned int) offsets->tsc_TIM_mem_offset; spe_contexts[i].offsets.tsc_TII_mem_offset = (unsigned int) offsets->tsc_TII_mem_offset; spe_contexts[i].offsets.tsc_TDM_mem_offset = (unsigned int) offsets->tsc_TDM_mem_offset; spe_contexts[i].offsets.tsc_TDD_mem_offset = (unsigned int) offsets->tsc_TDD_mem_offset; #ifdef USE_SDK30 spethreads[i].cb = (unsigned long long *) &spe_contexts[i]; /* Create context */ if ((spethreads[i].speids = spe_context_create (0, NULL)) == NULL) { perror ("Failed creating context"); exit (1); } spe_ids[i] = spethreads[i].speids; /* Load program into context */ if (spe_program_load (spethreads[i].speids, &hmmercell_spu)) { perror ("Failed loading program"); exit (1); } /* Create thread for each SPE context */ if (pthread_create (&threads[i], NULL, &ppu_pthread_function, &spethreads[i])) { perror ("Failed creating thread"); exit (1); } #else /* Create SPE thread group */ spe_gid = spe_create_group(SCHED_OTHER,0,0); spe_ids[i] = spe_create_thread(spe_gid,&hmmercell_spu, &spe_contexts[i],NULL,-1,0); if (spe_ids[i]==0){ fprintf(stderr, "Failed to create SPE thread rc=%d, errno=%d\n", spe_ids[i],errno); exit(1); } #endif } /*--------------4 - READ ALL SEQUENCES---------------------*/ /* In this stage, the PPE reads the sequence database and populates the sequence buffer. Meanwhile, the SPEs are busy consuming the buffer that the PPE is filling. In order to ensure that the SPE threads never outrun the PPE thread, we use a basic synchronization mechanism with condition variables here.*/ numCushion = 0; if (seqsFinished == 0){ for( i = initBufSize; i < regions.size(); ++i ) { U2Region r = regions.at(i); placeSequenceIntoBufferHP( seq + r.startPos, r.length, sequencesMatrix, lengthMatrix, &jobQueueIndex, jobQueue, &seqAddr ); numSeqs++; mutex_lock(bufferMutex); if (atomic_read(bufferEntries)==0){ // If the buffer was empty, signal the waiting SPUs. atomic_inc(bufferEntries); // If the SPEs have overrun the PPE, it does not make sense to read only one sequence and // wake up the SPEs. The PPE should try to build a cushion before the wake-up so that // the SPEs can not catch up very quickly. numCushion++; if (numCushion == cushBufSize){ cond_broadcast(bufferEmptyCond); numCushion=0; } } else { atomic_inc(bufferEntries); } mutex_unlock(bufferMutex); } } //If we reached here, there are no more sequences left. //Send a message to all SPE threads atomic_set(nomoreSeqs,1); for( i = 0; i < SPE_THREADS; ++i ){ mutex_lock( bufferMutex ); cond_broadcast( bufferEmptyCond ); mutex_unlock( bufferMutex ); } #ifdef USE_SDK30 for( i = 0; i < SPE_THREADS; ++i ) { pthread_join( threads[i], NULL ); spe_context_destroy(spe_ids[i]); } #else for (i=0;iM, 25, 0 ); QList resultsCache; //stores indexes in dhit->unsrt int last_hit_index = 0; for( i = 0; i < numSeqs; ++i ){ assert( jobQueue[i].seqProcessed == 1 ); assert( jobQueue[i].seqTracebackStatus == TRACEBACK_UNCHECKED ); sc = jobQueue[i].seqViterbiResult; pvalue = PValue(hmm, sc); evalue = thresh->Z ? (double) thresh->Z * pvalue : (double) pvalue; if ( sc >= thresh->domT && evalue <= thresh->domE ) { numTracebacks++; float ppe_sc = 0.0f; // This sequence needs traceback computation on the PPE. if (P7ViterbiSpaceOK(jobQueue[i].seqLength, hmm->M, mx)){ ppe_sc = P7Viterbi((unsigned char *)jobQueue[i].seqAddr, jobQueue[i].seqLength, hmm, mx, &tr); }else{ int progress; ppe_sc = P7SmallViterbi((unsigned char *)jobQueue[i].seqAddr, jobQueue[i].seqLength, hmm, mx, &tr, progress); } if (do_forward) { ppe_sc = P7Forward((unsigned char *)jobQueue[i].seqAddr, jobQueue[i].seqLength, hmm, NULL); if (do_null2) { ppe_sc -= TraceScoreCorrection(hmm, tr, (unsigned char *)jobQueue[i].seqAddr); } } if( sc != ppe_sc ) { U2::log.trace( QString("BAD!: sc: %1, ppe_sc: %2, diff: %3"). arg( QString().setNum(sc), QString().setNum(ppe_sc), QString().setNum(sc - ppe_sc) ) ); } else { U2::log.trace( QString("GOOD!: sc: %1").arg(QString().setNum(sc)) ); } sc = ppe_sc; pvalue = PValue(hmm, sc); evalue = thresh->Z ? (double) thresh->Z * pvalue : pvalue; if ( sc >= thresh->domT && evalue <= thresh->domE ) { sc = PostprocessSignificantHit( ghit, dhit, tr, hmm, (unsigned char *)jobQueue[i].seqAddr, jobQueue[i].seqLength, "seq", NULL, NULL, do_forward, sc, do_null2, thresh, FALSE ); //shifting results for( int hi = last_hit_index; hi < dhit->num; ++hi ) { const U2Region & curReg = regions.at(i); int & from = dhit->unsrt[hi].sqfrom; int & to = dhit->unsrt[hi].sqto; //preparing to correct merging if( from < overlap || to > curReg.length - overlap ) { resultsCache.push_back(hi); } //shifting results to correct pos in global sequence from += curReg.startPos; to += curReg.startPos; } last_hit_index = dhit->num; } P7FreeTrace(tr); } jobQueue[i].seqTracebackStatus = TRACEBACK_DONE; jobQueue[i].seqTraceAddr = 0; AddToHistogram(histogram, sc); } //merging cached results //NOTE: results are shifted QList resultsValid; QList resultToDelete; QList resultsToSkip; for( int i = 0; i < resultsCache.size(); ++i ) { if( resultsToSkip.contains(i) ) { continue; } hit_s & hit1 = dhit->unsrt[ resultsCache.at(i) ]; U2Region r1( hit1.sqfrom, hit1.sqto - hit1.sqfrom ); int res = resultsCache.at(i); for( int j = i+1; j < resultsCache.size(); ++j ) { if( resultsToSkip.contains(j) ) { continue; } hit_s & hit2 = dhit->unsrt[ resultsCache.at(j) ]; U2Region r2( hit2.sqfrom, hit2.sqto - hit2.sqfrom ); if( r1.intersects(r2) ) { if( r1 == r2 && hit1.pvalue == hit2.pvalue && hit1.score == hit2.score || r2.contains(r1) || regions.end() != std::find_if(regions.begin(), regions.end(), GlobalRegSearcher(r1.startPos)) ) { resultToDelete.push_back(res); res = resultsCache.at(j); } else { resultToDelete.push_back( resultsCache.at(j) ); } resultsToSkip.push_back(j); break; } } resultsValid.push_back(res); } //debug info foreach( int i, resultsValid ) { assert( !resultToDelete.contains(i) ); } foreach( int i, resultToDelete ) { assert( !resultsValid.contains(i) ); hit_s & hit = dhit->unsrt[i]; FreeFancyAli( hit.ali ); hit.ali = NULL; free(hit.name); free(hit.acc); free(hit.desc); } //ugly hack: directly modifying dhit members //FIXME refactoring needed if( resultsValid.size() != dhit->num ) { //copying (a)non-cached results, (b)cached and filtered results assert( resultsCache.size() >= resultsValid.size() ); int total = dhit->num - resultsCache.size() + resultsValid.size(); hit_s * newHits = (hit_s *)MallocOrDie( total * sizeof(hit_s) ); //non-cached: int count = 0; for( int i = 0; i < dhit->num; ++i ) { if( !resultsCache.contains(i) ) { newHits[count++] = dhit->unsrt[i]; } } //cached: foreach( int vali, resultsValid ) { newHits[count++] = dhit->unsrt[vali]; } assert( count == total ); dhit->num = total; dhit->alloc = dhit->num; free( dhit->unsrt ); dhit->unsrt = newHits; assert( 0 == dhit->hit ); } FreePlan7Matrix(mx); free( mem_addr ); } } //namespace #endif //UGENE_CELL ugene-1.9.8/src/plugins_3rdparty/hmm2/src/u_search/hmmer_ppu.h0000644000175000017500000001627111651544327023021 0ustar ilyailya/***************************************************************** * Unipro UGENE - Integrated Bioinformatics Suite * * This source code is distributed under the terms of the * GNU General Public License. See the files COPYING and LICENSE * for details. * * Author: Kursad Albayraktaroglu, Jizhu Li, Ivan Efremov *****************************************************************/ #ifdef UGENE_CELL #ifndef __HMMER_PPU_H__ #define __HMMER_PPU_H__ #define NO_MORE_SEQUENCES 987654321 #define TRACEBACK_UNCHECKED 0 #define TRACEBACK_NOT_NEEDED 1 #define TRACEBACK_NEEDED 2 #define TRACEBACK_DONE 3 #define MAX_NUM_SEQUENCES 760000 #define MAX_SEQ_LENGTH 10000 #define MAX_HMM_BUFFER_SIZE 131072 #define MAX_HMM_LENGTH 600 #define INIT_BUFFER_SIZE 25 #ifdef USE_SDK30 typedef union { unsigned long long ull; unsigned int ui[2]; } addr64; #endif /* Data structure for holding HMM array offsets We need such a structure to hold all the offsets so we could send everything at once to the SPEs. 60 bytes total (15 ints) */ typedef struct { int M; unsigned int escmem_offset; unsigned int bscmem_offset; unsigned int mscmem_offset; unsigned int iscmem_offset; unsigned int xscmem_offset; unsigned int tscmem_offset; unsigned int tsc_TMM_mem_offset; unsigned int tsc_TMI_mem_offset; unsigned int tsc_TMD_mem_offset; unsigned int tsc_TIM_mem_offset; unsigned int tsc_TII_mem_offset; unsigned int tsc_TDM_mem_offset; unsigned int tsc_TDD_mem_offset; int bufferLength; } hmm_offsets; /* Data structure for specifying an SPE "job" This data structure is passed to the SPEs whenever they need a sequence to work on 128 bytes total */ typedef struct { unsigned char* seq_addr; /* Address of the initial sequence */ char* seq_name; /* Name of the initial sequence */ int seq_length; /* Length of the initial sequence */ int seq_dmalength; /* DMA len.of the initial sequence */ unsigned int bufferMutex_addr; /* Address of the buffer mutex */ unsigned int bufferEmptyCond_addr; /* "Buffer Empty" condition variable */ unsigned int bufferEntries_addr; /* Number of entries in the buffer */ unsigned int lastProduced_addr; /* Last produced sequence number */ unsigned int nomoreSeqs_addr; /* Last produced sequence number */ unsigned int buffer_length_addr; /* Address of the buffer context */ unsigned char* buffer_addr; /* Address of the sequence buffer */ unsigned int hmm_M; /* Length of the HMM in states(hmm->M)*/ unsigned int hmm_buf_begin; /* Address of the PPE HMM buffer */ unsigned int hmm_buf_length; /* Length of the PPE HMM buffer */ hmm_offsets offsets; /* HMM array offsets */ char padding[12]; /* Padding to a full cache line */ } spe_jobcontext; /* Data structure for an SPE "job entity" This data structure is passed to the SPEs whenever they need a sequence to work on 128 bytes total */ typedef struct { int seqNumber; unsigned int seqAddr; int seqLength; int seqDMALength; char seqProcessed; float seqViterbiResult; char seqTracebackStatus; unsigned int seqTraceAddr; char padding[94]; // char padding[102]; } spe_jobEntity; typedef struct { unsigned char* seq_addr; /* Address of the initial sequence */ char* seq_name; /* Name of the initial sequence */ int seq_no; /* Number of the initial sequence */ int seq_length; /* Length of the initial sequence */ int seq_dmalength; /* DMA len.of the initial sequence */ unsigned int jobqueue_atomic_addr; /* Atomic variable for job queue entry number */ unsigned int jobqueue_begin_addr; /* Address of the job queue */ unsigned int jobqueue_num_seqs; /* Number of sequences in the job queue */ unsigned int hmm_M; /* Length of the HMM in states(hmm->M)*/ unsigned int hmm_buf_begin; /* Address of the PPE HMM buffer */ unsigned int hmm_buf_length; /* Length of the PPE HMM buffer */ hmm_offsets offsets; /* HMM array offsets */ char padding[24]; /* Padding to a full cache line */ } spe_initContext; typedef struct { unsigned char* seq_addr; /* Address of the initial sequence */ char* seq_name; /* Name of the initial sequence */ int seq_length; /* Length of the initial sequence */ int seq_dmalength; /* DMA len.of the initial sequence */ unsigned int jobqueue_atomic_addr; /* Atomic variable for job queue entry number */ unsigned int jobqueue_begin_addr; /* Address of the job queue */ unsigned int jobqueue_num_seqs; /* Number of sequences in the job queue */ unsigned int bufferMutex_addr; /* Address of the buffer mutex */ unsigned int bufferEmptyCond_addr; /* "Buffer Empty" condition variable */ unsigned int bufferEntries_addr; /* Number of entries in the buffer */ unsigned int lastConsumed_addr; /* Last produced sequence number */ unsigned int nomoreSeqs_addr; /* "No more sequences" flag */ unsigned int hmm_M; /* Length of the HMM in states(hmm->M)*/ unsigned int hmm_buf_begin; /* Address of the PPE HMM buffer */ unsigned int hmm_buf_length; /* Length of the PPE HMM buffer */ hmm_offsets offsets; /* HMM array offsets */ char padding[8]; /* Padding to a full cache line */ } spe_initContextSB; int MakeHMMBuffer_Aligned(struct plan7_s* hmm, void* copyBuffer, int bufsize, hmm_offsets* offsets); void dumpPpeHMM (struct plan7_s* hmm); #endif //__HMMER_PPU_H__ #endif //UGENE_CELL ugene-1.9.8/src/plugins_3rdparty/hmm2/src/u_search/HMMSearchWorker.cpp0000644000175000017500000002256311651544327024322 0ustar ilyailya#include "HMMSearchWorker.h" #include "HMMIOWorker.h" #include "HMMSearchTask.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include /* TRANSLATOR U2::LocalWorkflow::HMMSearchWorker */ namespace U2 { namespace LocalWorkflow { /******************************* * HMMSearchWorkerFactory *******************************/ static const QString HMM_PORT("in-hmm2"); static const QString NAME_ATTR("result-name"); static const QString NSEQ_ATTR("seqs-num"); static const QString DOM_E_ATTR("e-val"); static const QString DOM_T_ATTR("score"); const QString HMMSearchWorkerFactory::ACTOR("hmm2-search"); void HMMSearchWorkerFactory::init() { QList p; QList a; { Descriptor hd(HMM_PORT, HMMSearchWorker::tr("HMM profile"), HMMSearchWorker::tr("HMM profile(s) to search with.")); Descriptor sd(BasePorts::IN_SEQ_PORT_ID(), HMMSearchWorker::tr("Input sequence"), HMMSearchWorker::tr("An input sequence (nucleotide or protein) to search in.")); Descriptor od(BasePorts::OUT_ANNOTATIONS_PORT_ID(), HMMSearchWorker::tr("HMM annotations"), HMMSearchWorker::tr("Annotations marking found similar sequence regions.")); QMap hmmM; hmmM[HMMLib::HMM2_SLOT] = HMMLib::HMM_PROFILE_TYPE(); p << new PortDescriptor(hd, DataTypePtr(new MapDataType("hmm.search.hmm", hmmM)), true /*input*/, false, IntegralBusPort::BLIND_INPUT); QMap seqM; seqM[BaseSlots::DNA_SEQUENCE_SLOT()] = BaseTypes::DNA_SEQUENCE_TYPE(); p << new PortDescriptor(sd, DataTypePtr(new MapDataType("hmm.search.sequence", seqM)), true /*input*/); QMap outM; outM[BaseSlots::ANNOTATION_TABLE_SLOT()] = BaseTypes::ANNOTATION_TABLE_TYPE(); p << new PortDescriptor(od, DataTypePtr(new MapDataType("hmm.search.out", outM)), false /*input*/, true); } { Descriptor nd(NAME_ATTR, HMMSearchWorker::tr("Result annotation"), HMMSearchWorker::tr("A name of the result annotations.")); Descriptor nsd(NSEQ_ATTR, HMMSearchWorker::tr("Number of seqs"), QApplication::translate("HMMSearchDialog", "e_value_as_nsec_tip", 0, QApplication::UnicodeUTF8)); Descriptor ded(DOM_E_ATTR, HMMSearchWorker::tr("Filter by high E-value"), QApplication::translate("HMMSearchDialog", "results_evalue_cutoff_tip", 0, QApplication::UnicodeUTF8)); Descriptor dtd(DOM_T_ATTR, HMMSearchWorker::tr("Filter by low score"), QApplication::translate("HMMSearchDialog", "results_score_cutoff_tip", 0, QApplication::UnicodeUTF8)); a << new Attribute(nd, BaseTypes::STRING_TYPE(), true, QVariant("hmm_signal")); a << new Attribute(nsd, BaseTypes::NUM_TYPE(), false, QVariant(1)); a << new Attribute(ded, BaseTypes::NUM_TYPE(), false, QVariant(-1)); a << new Attribute(dtd, BaseTypes::NUM_TYPE(), false, QVariant((double)-1e+09)); } Descriptor desc(HMMSearchWorkerFactory::ACTOR, HMMSearchWorker::tr("HMM search"), HMMSearchWorker::tr("Searches each input sequence for significantly similar sequence matches to all specified HMM profiles." " In case several profiles were supplied, searches with all profiles one by one and outputs united set of annotations for each sequence")); ActorPrototype* proto = new IntegralBusActorPrototype(desc, p, a); QMap delegates; { QVariantMap eMap; eMap["prefix"]= ("1e"); eMap["minimum"] = (-99); eMap["maximum"] = (0); delegates[DOM_E_ATTR] = new SpinBoxDelegate(eMap); } { QVariantMap nMap; nMap["maximum"] = (INT_MAX); delegates[NSEQ_ATTR] = new SpinBoxDelegate(nMap); } { QVariantMap tMap; tMap["decimals"]= (1); tMap["minimum"] = (-1e+09); tMap["maximum"] = (1e+09); tMap["singleStep"] = (0.1); delegates[DOM_T_ATTR] = new DoubleSpinBoxDelegate(tMap); } proto->setEditor(new DelegateEditor(delegates)); proto->setIconPath(":/hmm2/images/hmmer_16.png"); proto->setPrompter(new HMMSearchPrompter()); WorkflowEnv::getProtoRegistry()->registerProto(HMMLib::HMM_CATEGORY(), proto); DomainFactory* localDomain = WorkflowEnv::getDomainRegistry()->getById(LocalDomainFactory::ID); localDomain->registerEntry(new HMMSearchWorkerFactory()); } static bool isDefaultCfg(PrompterBaseImpl* actor) { return 1 == actor->getParameter(NSEQ_ATTR).toInt() && -1 == actor->getParameter(DOM_E_ATTR).toInt() && double(-1e+09) == actor->getParameter(DOM_T_ATTR).toDouble(); } /******************************* * HMMSearchPrompter *******************************/ QString HMMSearchPrompter::composeRichDoc() { Actor* hmmProducer = qobject_cast(target->getPort(HMM_PORT))->getProducer(HMM_PORT); Actor* seqProducer = qobject_cast(target->getPort(BasePorts::IN_SEQ_PORT_ID()))->getProducer(BasePorts::IN_SEQ_PORT_ID()); QString seqName = seqProducer ? tr("For each sequence from %1,").arg(seqProducer->getLabel()) : ""; QString hmmName = hmmProducer ? tr("using all profiles provided by %1,").arg(hmmProducer->getLabel()) : ""; QString resultName = getHyperlink(NAME_ATTR, getRequiredParam(NAME_ATTR)); QString cfg = isDefaultCfg(this) ? tr("Use default settings.") : tr("Use custom settings."); QString doc = tr("%1 search HMM signals %2. %3" "
    Output the list of found regions annotated as %4.") .arg(seqName) .arg(hmmName) .arg(cfg) .arg(resultName); return doc; } /******************************* * HMMSearchWorker *******************************/ HMMSearchWorker::HMMSearchWorker(Actor* a) : BaseWorker(a, false), hmmPort(NULL), seqPort(NULL), output(NULL) { } void HMMSearchWorker::init() { hmmPort = ports.value(HMM_PORT); seqPort = ports.value(BasePorts::IN_SEQ_PORT_ID()); output = ports.value(BasePorts::OUT_ANNOTATIONS_PORT_ID()); seqPort->addComplement(output); output->addComplement(seqPort); float domENum = actor->getParameter(DOM_E_ATTR)->getAttributeValue(); if(domENum > 0) { algoLog.details(tr("Power of e-value must be less or equal to zero. Using default value: 1e-1")); domENum = -1; } cfg.domE = pow(10, domENum); cfg.domT = (float)actor->getParameter(DOM_T_ATTR)->getAttributeValue(); cfg.eValueNSeqs = actor->getParameter(NSEQ_ATTR)->getAttributeValue(); resultName = actor->getParameter(NAME_ATTR)->getAttributeValue(); if(resultName.isEmpty()){ algoLog.details(tr("Value for attribute name is empty, default name used")); resultName = "hmm_signal"; } } bool HMMSearchWorker::isReady() { return hmmPort->hasMessage() || ((!hmms.isEmpty() && hmmPort->isEnded() ) && seqPort->hasMessage()); } Task* HMMSearchWorker::tick() { while (hmmPort->hasMessage()) { hmms << hmmPort->get().getData().toMap().value(HMMLib::HMM2_SLOT.getId()).value(); } if (!hmmPort->isEnded() || hmms.isEmpty() || !seqPort->hasMessage()) { return NULL; } DNASequence dnaSequence = seqPort->get().getData().toMap().value(BaseSlots::DNA_SEQUENCE_SLOT().getId()).value(); if (dnaSequence.alphabet->getType() != DNAAlphabet_RAW) { QList subtasks; foreach(plan7_s* hmm, hmms) { subtasks << new HMMSearchTask(hmm, dnaSequence, cfg); } Task* searchTask = new MultiTask(tr("Search HMM signals in %1").arg(dnaSequence.getName()), subtasks); connect(new TaskSignalMapper(searchTask), SIGNAL(si_taskFinished(Task*)), SLOT(sl_taskFinished(Task*))); return searchTask; } QString err = tr("Bad sequence supplied to input: %1").arg(dnaSequence.getName()); //if (failFast) { return new FailTask(err); /*} else { algoLog.error(err); output->put(Message(BioDataTypes::ANNOTATION_TABLE_TYPE(), QVariant())); if (seqPort->isEnded()) { output->setEnded(); } return NULL; }*/ } void HMMSearchWorker::sl_taskFinished(Task* t) { if (output) { QList list; foreach(Task* sub, t->getSubtasks()) { HMMSearchTask* hst = qobject_cast(sub); list += hst->getResultsAsAnnotations(resultName); } QVariant v = qVariantFromValue >(list); output->put(Message(BaseTypes::ANNOTATION_TABLE_TYPE(), v)); if (seqPort->isEnded()) { output->setEnded(); } algoLog.info(tr("Found %1 HMM signals").arg(list.size())); } } bool HMMSearchWorker::isDone() { return seqPort->isEnded(); } void HMMSearchWorker::cleanup() { } } //namespace LocalWorkflow } //namespace U2 ugene-1.9.8/src/plugins_3rdparty/hmm2/src/u_search/ui/0000755000175000017500000000000011651544311021253 5ustar ilyailyaugene-1.9.8/src/plugins_3rdparty/hmm2/src/u_search/ui/HMMSearchDialog.ui0000644000175000017500000002356611651544327024524 0ustar ilyailya HMMSearchDialog 0 0 500 222 0 0 500 222 hmm_search_dialog_title hmm_file ... 0 0 expert_box_title true false results_evalue_cutoff_tip results_evalue_cutoff_tip results_evalue_cutoff_tip results_evalue_cutoff Qt::Horizontal 319 20 Qt::Horizontal 319 20 results_score_cutoff_tip results_score_cutoff_tip results_score_cutoff_tip results_score_cutoff results_score_cutoff_tip results_score_cutoff_tip results_score_cutoff_tip Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter false 1 -999999999.000000000000000 999999999.000000000000000 0.100000000000000 0.000000000000000 Qt::Horizontal 319 20 100 0 e_value_as_nsec_tip e_value_as_nsec_tip e_value_as_nsec_tip Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter 2000000000 1 e_value_as_nsec_tip e_value_as_nsec_tip e_value_as_nsec_tip e_value_as_n_seq results_evalue_cutoff_tip results_evalue_cutoff_tip results_evalue_cutoff_tip Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter 1E -99 0 -1 Algorithm Qt::Horizontal 40 20 algo_combo_tip algo_combo_tip algo_combo_tip Qt::Vertical 20 3 Qt::Horizontal 40 20 ok_button close_button cancelButton clicked() HMMSearchDialog reject() 439 194 244 108 ugene-1.9.8/src/plugins_3rdparty/hmm2/src/u_search/uhmmsearch_opt.cpp0000644000175000017500000002132311651544327024370 0ustar ilyailya#include "uhmmsearch_opt.h" #include "uhmmsearch.h" #include #include #include #include #include #include #include #define SEQ_ALIGN_BASE 16 #define ALIGNED(ptr, base) ( (unsigned char*) ( (((quintptr)(ptr))+((base)-1)) &~((base-1)) ) ) #define ALIGNED_16(ptr) ( ALIGNED(ptr, 16) ) //static U2::Logger hmm_log( U2::UHMMSearch::tr("UHMMER log") ); namespace { //returns aligned pointer. unsigned char * DigitizeSequenceHP( const unsigned char * seq, int L, const unsigned char * mem, int align_base ) { //Digitized sequences should be aligned for easier DMA transfer unsigned char * dsq = ALIGNED( mem, align_base ); int i; HMMERTaskLocalData *tld = getHMMERTaskLocalData(); alphabet_s *al = &tld->al; dsq[0] = dsq[L+1] = (unsigned char) al->Alphabet_iupac; for (i = 1; i <= L+1; i++) { dsq[i] = SymbolIndex(seq[i-1]); } return dsq; } } //anonymous namespace void main_loop_opt( struct plan7_s * hmm_, const char * seq_, int seqlen, struct threshold_s *thresh, int do_forward, int do_null2, int do_xnu, struct histogram_s * histogram, struct tophit_s * ghit, struct tophit_s * dhit, int * ret_nseq, U2::TaskStateInfo & ti, hmmScoringFunction scoring_f ) { using namespace U2; Q_UNUSED( ret_nseq ); HMMERTaskLocalData *tld = getHMMERTaskLocalData(); alphabet_s *al = &tld->al; plan7_s * hmm = HMMIO::cloneHMM( hmm_ ); unsigned char * seq = (unsigned char *)seq_; unsigned char * dsq_mem = new unsigned char[seqlen + SEQ_ALIGN_BASE]; unsigned char * dsq = DigitizeSequenceHP( seq, seqlen, dsq_mem, SEQ_ALIGN_BASE ); if (do_xnu && al->Alphabet_type == hmmAMINO) { XNU(dsq, seqlen); } struct dpmatrix_s * mx; struct p7trace_s * tr; HMMSeqGranulation gr; //Scoring function splits the sequence and computes a score for each chunk. //Resulting granulation is returned in 'gr' parameter QList results = scoring_f( dsq, seqlen, hmm, &gr, ti ); mx = CreatePlan7Matrix( 1, hmm->M, 25, 0 ); const QVector & regions = gr.regions; QList resultsCache; //stores indexes in dhit->unsrt QList borderResults; //stores indexes of 'border results' int last_hit_index = 0; //index in dhit->unsrt for( int i = 0, sz = results.size(); i < sz; ++i ){ unsigned char * curSeqAddr = dsq + regions.at(i).startPos; int curSeqLen = regions.at(i).length; int overlap = gr.overlap; float sc = results.at(i); double pvalue = PValue(hmm, sc); double evalue = thresh->Z ? (double) thresh->Z * pvalue : (double) pvalue; if ( sc >= thresh->domT && evalue <= thresh->domE ) { float conservative_sc = 0.0f; // This sequence needs traceback computation. if (P7ViterbiSpaceOK(curSeqLen, hmm->M, mx)){ conservative_sc = P7Viterbi( curSeqAddr, curSeqLen, hmm, mx, &tr); } else { int progress; //stub conservative_sc = P7SmallViterbi( curSeqAddr, curSeqLen, hmm, mx, &tr, progress); } if (do_forward) { conservative_sc = P7Forward( curSeqAddr, curSeqLen, hmm, NULL); if (do_null2) { conservative_sc -= TraceScoreCorrection( hmm, tr, curSeqAddr ); } } // if( sc != conservative_sc ) { // hmm_log.trace( QString("Optimized HMMER reports error: sc: %1, ppe_sc: %2, diff: %3"). // arg( QString().setNum(sc), QString().setNum(conservative_sc), QString().setNum(sc - conservative_sc) ) ); // } else { // hmm_log.trace( QString("Optimized HMMER reports OK: sc: %1").arg(QString().setNum(sc)) ); // } sc = conservative_sc; //using more precise score pvalue = PValue(hmm, sc); evalue = thresh->Z ? (double) thresh->Z * pvalue : pvalue; if ( sc >= thresh->domT && evalue <= thresh->domE ) { // This function adds new results to dhit->unsrt. They are added right after 'last_hit_index' sc = PostprocessSignificantHit( ghit, dhit, tr, hmm, curSeqAddr, curSeqLen, "seq", 0, 0, do_forward, sc, do_null2, thresh, FALSE ); //shifting results for( int hi = last_hit_index; hi < dhit->num; ++hi ) { const U2Region & curReg = regions.at(i); int & from = dhit->unsrt[hi].sqfrom; int & to = dhit->unsrt[hi].sqto; bool leftBorderResult = (i && !from); bool rightBorderResult = ((i != sz-1) && (to == curReg.length)); bool borderResult = leftBorderResult || rightBorderResult; //preparing to correct merging if( (i && from < overlap) || ((i != sz-1) && to > curReg.length - overlap) ) { resultsCache.push_back(hi); //'border result' if( borderResult ) { borderResults.push_back(hi); } } //shifting results to correct position in global sequence from += curReg.startPos; to += curReg.startPos; } last_hit_index = dhit->num; } P7FreeTrace(tr); } AddToHistogram(histogram, sc); } //merging cached results //adopted from HMMSearchTask::report //NOTE: results are shifted int maxCommonLen = hmm->M / 2; //hust heuristic QList resultsValid; QList resultsToSkip; //Search for results which will be skipped for( int i = 0, endi = resultsCache.size(); i < endi; ++i ) { //NOTE: i, j are indexes in resulsCache, but res_i and res_j are indexes in dhit->unsrt int res_i = resultsCache.at(i); if( resultsToSkip.contains(res_i) ) { continue; } hit_s & hit1 = dhit->unsrt[ res_i ]; U2Region r1( hit1.sqfrom, hit1.sqto - hit1.sqfrom ); for( int j = i+1, endj = resultsCache.size(); j < endj; ++j ) { int res_j = resultsCache.at(j); if( resultsToSkip.contains(res_j) ) { continue; } hit_s & hit2 = dhit->unsrt[ res_j ]; U2Region r2( hit2.sqfrom, hit2.sqto - hit2.sqfrom ); if( r1.contains(r2) ) { resultsToSkip.push_back(res_j); } else if( r2.contains(r1) ) { resultsToSkip.push_back(res_i); break; } else if( r1.intersect(r2).length >= maxCommonLen ) { bool useR1 = hit2.score <= hit1.score; if (hit1.score == hit2.score && hit1.pvalue == hit2.pvalue && borderResults.contains(res_i) && !borderResults.contains(res_j) ) { useR1 = false; } if (useR1) { resultsToSkip.push_back(res_i); } else { resultsToSkip.push_back(res_j); } } } } //Skipping unneeded results foreach( int cached, resultsCache ) { if( !resultsToSkip.contains(cached) ) { resultsValid.push_back( cached ); } } //Freeing resources of unneeded results foreach( int i, resultsToSkip ) { assert( !resultsValid.contains(i) ); hit_s & hit = dhit->unsrt[i]; FreeFancyAli( hit.ali ); hit.ali = NULL; free(hit.name); free(hit.acc); free(hit.desc); } //ugly hack: directly modifying dhit members if( resultsValid.size() != dhit->num ) { //copying (a)non-cached results, (b)cached and filtered results assert( resultsCache.size() >= resultsValid.size() ); int total = dhit->num - resultsCache.size() + resultsValid.size(); hit_s * newHits = (hit_s *)MallocOrDie( total * sizeof(hit_s) ); //non-cached: int count = 0; for( int i = 0; i < dhit->num; ++i ) { if( !resultsCache.contains(i) ) { newHits[count++] = dhit->unsrt[i]; } } //cached: foreach( int vali, resultsValid ) { newHits[count++] = dhit->unsrt[vali]; } assert( count == total ); dhit->num = total; dhit->alloc = dhit->num; free( dhit->unsrt ); dhit->unsrt = newHits; assert( 0 == dhit->hit ); } FreePlan7Matrix(mx); FreePlan7( hmm ); delete[] dsq_mem; } ugene-1.9.8/src/plugins_3rdparty/hmm2/src/u_search/uhmmsearch_sse.h0000644000175000017500000000040411651544327024022 0ustar ilyailya#ifdef HMMER_BUILD_WITH_SSE2 #ifndef __HMMSEARCH_SSE_H__ #define __HMMSEARCH_SSE_H__ QList sseScoring( unsigned char * dsq, int seqlen, plan7_s* hmm, HMMSeqGranulation * gr, U2::TaskStateInfo& ti ); #endif // __HMMSEARCH_SSE_H__ #endif // HMMER_SSE ugene-1.9.8/src/plugins_3rdparty/hmm2/src/u_search/hmmer_ppu.cpp0000644000175000017500000000643311651544327023353 0ustar ilyailya/***************************************************************** * Unipro UGENE - Integrated Bioinformatics Suite * * This source code is distributed under the terms of the * GNU General Public License. See the files COPYING and LICENSE * for details. * * Author: Kursad Albayraktaroglu, Jizhu Li, Ivan Efremov *****************************************************************/ #ifdef UGENE_CELL #include #include "hmmer_ppu.h" #include #include #include #include #include int MakeHMMBuffer_Aligned( struct plan7_s * hmm, void * copyBuffer, int copyBufferSize, hmm_offsets * offsets ) { assert( NULL != hmm ); assert( NULL != copyBuffer ); int M = hmm->M; int * escMem; int * bscMem; int * xscMem; int * tscMem; int * iscMem; int * mscMem; int i = 0; int j = 0; int k = 0; unsigned long int bufStart; long bsc_s = (M+1+12); long esc_s = (M+1+12); long xsc_s = 50; long tsc_s = (7*(M+16)); long msc_s = (MAXCODE*(M+1+16)); long isc_s = (MAXCODE*(M+16)); long total = ( (bsc_s + esc_s + xsc_s + tsc_s + msc_s + isc_s)*sizeof(int) + 16*5 + 127 )&~0x7F; assert( total < copyBufferSize ); #define ALIGNED(x) ((int*)((((unsigned long)(x))+15)&~0x0F)) int * mem = (int *)memalign( 128, total ); assert( NULL != mem ); memset( mem, 0, total ); bscMem = mem; escMem = ALIGNED( bscMem + bsc_s ); xscMem = ALIGNED( escMem + esc_s ); tscMem = ALIGNED( xscMem + xsc_s ); mscMem = ALIGNED( tscMem + tsc_s ); iscMem = ALIGNED( mscMem + msc_s ); for( i = 0; i < 4; ++i ) { for( j = 0; j < 2; ++j ) { xscMem[k++] = hmm->xsc[i][j]; } } memcpy(bscMem,hmm->bsc_mem, bsc_s * sizeof(int) ); memcpy(escMem,hmm->esc_mem, esc_s * sizeof(int) ); memcpy(tscMem,hmm->tsc_mem, tsc_s * sizeof(int) ); memcpy(mscMem,hmm->msc_mem, msc_s * sizeof(int) ); memcpy(iscMem,hmm->isc_mem, isc_s * sizeof(int) ); memcpy( copyBuffer, bscMem, total ); bufStart = (unsigned long int) bscMem; offsets->bscmem_offset = (unsigned long int)bscMem - bufStart; offsets->escmem_offset = (unsigned long int)escMem - bufStart; offsets->xscmem_offset = (unsigned long int)xscMem - bufStart; offsets->tscmem_offset = (unsigned long int)tscMem - bufStart; offsets->iscmem_offset = (unsigned long int)iscMem - bufStart; offsets->mscmem_offset = (unsigned long int)mscMem - bufStart; offsets->M = M; offsets->bufferLength = total; free( mem ); return 1; } void dumpPpeHMM (struct plan7_s* hmm){ int i,j; int M; int *currentVal; printf("--START PPE HMM DUMP (M=%d)\n", hmm->M); M = hmm->M; for (i=0;iESC[%d]=%d\n",i, hmm->esc[i]); } for (i=0;iBSC[%d]=%d\n",i, hmm->bsc[i]); } for (i=0;iMSC[%d][%d]=%d\n",i,j, hmm->msc[i][j]); } } for (i=0;i<4;i++){ for (j=0;j<2;j++){ printf("HMM->XSC[%d][%d]=%d\n",i,j, hmm->xsc[i][j]); } } for (i=0;i<7;i++){ for (j=0;jTSC[%d][%d]=%d\n",i,j, hmm->tsc[i][j]); } } for (i=0;iISC[%d][%d]=%d\n",i,j, hmm->isc[i][j]); } } printf("--END PPE HMM DUMP (M=%d)\n", hmm->M); } #endif //UGENE_CELLugene-1.9.8/src/plugins_3rdparty/hmm2/src/u_search/HMMSearchTask.cpp0000644000175000017500000002174511651544327023754 0ustar ilyailya#include "HMMSearchTask.h" #include "TaskLocalStorage.h" #include "HMMIO.h" #include #include #include #include #include #include namespace U2 { HMMSearchTask::HMMSearchTask(plan7_s* _hmm, const DNASequence& _seq, const UHMMSearchSettings& s) : Task("", TaskFlag_NoRun), hmm(_hmm), seq(_seq), settings(s), complTrans(NULL), aminoTrans(NULL) { setTaskName(tr("HMM search with '%1'").arg(hmm->name)); GCOUNTER( cvar, tvar, "HMM2 Search" ); } void HMMSearchTask::prepare() { if (!checkAlphabets(hmm->atype, seq.alphabet, complTrans, aminoTrans)) { return; } SequenceWalkerConfig config; config.seq = seq.seq.data(); config.seqSize = seq.seq.size(); config.complTrans = complTrans; config.strandToWalk = complTrans == NULL ? StrandOption_DirectOnly : StrandOption_Both; config.aminoTrans = aminoTrans; config.overlapSize = 2 * hmm->M; config.chunkSize = qMax(6 * hmm->M, settings.searchChunkSize); if (settings.extraLen == -1) { config.lastChunkExtraLen = config.chunkSize / 2; } else { config.lastChunkExtraLen = settings.extraLen; } config.nThreads = MAX_PARALLEL_SUBTASKS_AUTO; addSubTask(new SequenceWalkerTask(config, this, tr("parallel_hmm_search_task"))); } void HMMSearchTask::onRegion(SequenceWalkerSubtask* t, TaskStateInfo& si) { const char* localSeq = t->getRegionSequence(); int localSeqSize = t->getRegionSequenceLen(); bool wasCompl = t->isDNAComplemented(); bool wasAmino = t->isAminoTranslated(); U2Region globalReg = t->getGlobalRegion(); //set TLS data TaskLocalData::createHMMContext(t->getTaskId(), true); QList sresults; try { sresults = UHMMSearch::search(hmm, localSeq, localSeqSize, settings, si); } catch (HMMException e) { stateInfo.setError( e.error ); } if (si.hasError()) { stateInfo.setError( si.getError() ); } if (sresults.isEmpty() || stateInfo.cancelFlag || stateInfo.hasError()) { TaskLocalData::freeHMMContext(t->getTaskId()); return; } //convert all UHMMSearchResults into HMMSearchTaskResult QMutexLocker locker( &lock ); int halfOverlap = hmm->M; foreach(const UHMMSearchResult& sr, sresults) { HMMSearchTaskResult r; r.evalue = sr.evalue; r.score = sr.score; r.onCompl = wasCompl; r.onAmino = wasAmino; int resLen = wasAmino ? sr.r.length * 3 : sr.r.length; int resStart = wasAmino ? sr.r.startPos * 3 : sr.r.startPos; if (wasCompl) { resStart = globalReg.length - resStart - resLen; } r.r.startPos = globalReg.startPos + resStart; r.r.length = resLen; if (t->intersectsWithOverlaps(r.r)) { //don't add to overlaps if it must be found in 2 regions bool add = true; if (!r.onCompl && t->hasRightOverlap()) { //check if will be found in a next chunk U2Region nextChunkRegion(globalReg.endPos() - halfOverlap, halfOverlap); add = !nextChunkRegion.contains(r.r); } else if (r.onCompl && t->hasLeftOverlap()) { //check if will found in a prev chunk U2Region prevChunkRegion(globalReg.startPos, halfOverlap); add = !prevChunkRegion.contains(r.r); } if (add) { r.borderResult = (t->hasLeftOverlap() && r.r.startPos == globalReg.startPos) || (t->hasRightOverlap() && r.r.endPos() == globalReg.endPos()); overlaps.append(r); } } else { results.append(r); } } TaskLocalData::freeHMMContext(t->getTaskId()); } static bool HMMSearchResult_LessThan(const HMMSearchTaskResult& r1, const HMMSearchTaskResult& r2) { if (r1.evalue == r2.evalue) { if (r1.r == r2.r) { if (r1.onCompl == r2.onCompl) { return &r1 < &r2; } return r2.onCompl; } return r1.r < r2.r; } return r1.evalue < r2.evalue; } Task::ReportResult HMMSearchTask::report() { if (hasError()) { return ReportResult_Finished; } //postprocess overlaps int maxCommonLen = hmm->M / 2; //if 2 results have common part of 'maxCommonLen' or greater -> select best one for(int i=0; i < overlaps.count(); i++){ HMMSearchTaskResult& r1 = overlaps[i]; if (r1.filtered) { continue; } for(int j=i+1; j < overlaps.count(); j++){ HMMSearchTaskResult& r2 = overlaps[j]; if (r2.filtered) { continue; } if (r1.onCompl != r2.onCompl) { //check both regions are on the same strand continue; } if (r1.onAmino) { //check both regions have the same amino frame int s1 = r1.onCompl ? r1.r.endPos() % 3 : r1.r.startPos % 3; int s2 = r2.onCompl ? r2.r.endPos() % 3 : r2.r.startPos % 3; if (s1 != s2) { continue; } } if (r1.r.contains(r2.r) && r1.r != r2.r) { r2.filtered = true; } else if (r2.r.contains(r1.r) && r1.r != r2.r) { r1.filtered = true; break; } else if (r1.r.intersect(r2.r).length >= maxCommonLen) { bool useR1 = r2.score <= r1.score; if (r1.score == r2.score && r1.evalue == r2.evalue && r1.borderResult && !r2.borderResult) { useR1 = false; } if (useR1) { r2.filtered = true; } else { r1.filtered = true; break; } } } } foreach(const HMMSearchTaskResult& r, overlaps) { if (!r.filtered) { results.append(r); } } // sort results by E-value qSort(results.begin(), results.end(), HMMSearchResult_LessThan); return ReportResult_Finished; } QList HMMSearchTask::getResultsAsAnnotations(const QString& name) const { QList annotations; foreach(const HMMSearchTaskResult& hmmRes, results) { AnnotationData* a = new AnnotationData(); a->name = name; a->setStrand(hmmRes.onCompl ? U2Strand::Complementary : U2Strand::Direct); a->location->regions << hmmRes.r; QString str; /*add zeros at begin of evalue exponent part, so exponent part must contains 3 numbers*/ str.sprintf("%.2g", ((double) hmmRes.evalue)); QRegExp rx("\\+|\\-.+"); int pos = rx.indexIn(str,0); if(pos!=-1){ str.insert(pos+1,"0"); } QString info = hmm->name; if (hmm->flags & PLAN7_ACC) { info += QString().sprintf("\nAccession number in PFAM : %s", hmm->acc); } if (hmm->flags & PLAN7_DESC) { info += QString().sprintf("\n%s", hmm->desc); } if (!info.isEmpty()) { a->qualifiers.append(U2Qualifier("HMM-model", info)); } //a->qualifiers.append(U2Qualifier("E-value", QString().sprintf("%.2lg", ((double) hmmRes.evalue)))); a->qualifiers.append(U2Qualifier("E-value", str)); a->qualifiers.append(U2Qualifier("Score", QString().sprintf("%.1f", hmmRes.score))); annotations.append(SharedAnnotationData(a)); } return annotations; } bool HMMSearchTask::checkAlphabets(int hmmAlType, DNAAlphabet* seqAl, DNATranslation*& complTrans, DNATranslation*& aminoTrans) { assert(stateInfo.getError().isEmpty()); DNAAlphabetType hmmAl = HMMIO::convertHMMAlphabet(hmmAlType); if (hmmAl == DNAAlphabet_RAW) { stateInfo.setError( tr("invalid_hmm_alphabet_type") ); return false; } if (seqAl->isRaw()) { stateInfo.setError( tr("invalid_sequence_alphabet_type") ); return false; } complTrans = NULL; aminoTrans = NULL; if (seqAl->isNucleic()) { DNATranslationRegistry* tr = AppContext::getDNATranslationRegistry(); QList complTs = tr->lookupTranslation(seqAl, DNATranslationType_NUCL_2_COMPLNUCL); if (!complTs.empty()) { complTrans = complTs.first(); } if (hmmAl == DNAAlphabet_AMINO) { QList aminoTs = tr->lookupTranslation(seqAl, DNATranslationType_NUCL_2_AMINO); if (!aminoTs.empty()) { aminoTrans = aminoTs.first(); } } } else { assert(seqAl->isAmino()); } // check the result; if (hmmAl == DNAAlphabet_AMINO) { if (seqAl->isAmino()) { assert(complTrans == NULL && aminoTrans == NULL); } else { if (aminoTrans == NULL) { stateInfo.setError( tr("can_t_find_amino") ); return false; } } } return true; } }//endif ugene-1.9.8/src/plugins_3rdparty/hmm2/src/u_search/HMMSearchWorker.h0000644000175000017500000000216411651544327023762 0ustar ilyailya#ifndef _U2_HMMSEARCH_WORKER_H_ #define _U2_HMMSEARCH_WORKER_H_ #include #include #include "uhmmsearch.h" namespace U2 { namespace LocalWorkflow { class HMMSearchPrompter : public PrompterBase { Q_OBJECT public: HMMSearchPrompter(Actor* p = 0) : PrompterBase(p) {} protected: QString composeRichDoc(); }; class HMMSearchWorker : public BaseWorker { Q_OBJECT public: HMMSearchWorker(Actor* a); virtual void init(); virtual bool isReady(); virtual Task* tick(); virtual bool isDone(); virtual void cleanup(); private slots: void sl_taskFinished(Task*); protected: IntegralBus *hmmPort, *seqPort, *output; QString resultName; UHMMSearchSettings cfg; QList hmms; }; class HMMSearchWorkerFactory : public DomainFactory { public: static const QString ACTOR; static void init(); HMMSearchWorkerFactory() : DomainFactory(ACTOR) {} virtual Worker* createWorker(Actor* a) {return new HMMSearchWorker(a);} }; } // Workflow namespace } // U2 namespace #endif ugene-1.9.8/src/plugins_3rdparty/hmm2/src/u_search/HMMSearchDialogController.h0000644000175000017500000000407211651544327025754 0ustar ilyailya#ifndef _U2_HMMSEARCH_DIALOG_CONTROLLER_H_ #define _U2_HMMSEARCH_DIALOG_CONTROLLER_H_ #include "uhmmsearch.h" #include #include #include #include #include #include #include struct plan7_s; namespace U2 { class CreateAnnotationWidgetController; class CreateAnnotationModel; class AnnotationTableObject; class CreateAnnotationsTask; class LoadUnloadedDocumentTask; class DNATranslation; class HMMSearchTask; class HMMSearchTaskResult; class DNASequenceObject; class HMMReadTask; class HMMSearchDialogController : public QDialog, public Ui_HMMSearchDialog { Q_OBJECT public: HMMSearchDialogController(const DNASequenceObject* obj, QWidget* p = NULL); public slots: void reject(); private slots: void sl_hmmFileClicked(); void sl_okClicked(); void sl_expSpinBoxValueChanged(int); void sl_onStateChanged(); void sl_onProgressChanged(); private: DNASequence dnaSequence; Task* searchTask; CreateAnnotationWidgetController* createController; }; ////////////////////////////////////////////////////////////////////////// // tasks class HMMSearchToAnnotationsTask : public Task { Q_OBJECT public: HMMSearchToAnnotationsTask(const QString& hmmFile, const DNASequence& s, AnnotationTableObject* aobj, const QString& group, const QString& aname, const UHMMSearchSettings& settings); virtual QList onSubTaskFinished(Task* subTask); QString generateReport() const; private: QString hmmFile; DNASequence dnaSequence; QString agroup; QString aname; UHMMSearchSettings settings; HMMReadTask* readHMMTask; HMMSearchTask* searchTask; CreateAnnotationsTask* createAnnotationsTask; QPointer aobj; }; }//namespace #endif ugene-1.9.8/src/plugins_3rdparty/hmm2/src/u_search/uhmmsearch_cell.h0000644000175000017500000000105411651544327024151 0ustar ilyailya#ifdef UGENE_CELL #ifndef __UHMMSEARCH_CELL_H__ #define __UHMMSEARCH_CELL_H__ struct plan7_s; struct threshold_s; struct histogram_s; struct tophit_s; namespace U2 { class TaskStateInfo; void main_loop_spe(struct plan7_s *hmm, const char * seq, int seqlen, struct threshold_s *thresh, int do_forward, int do_null2, int do_xnu, struct histogram_s *histogram, struct tophit_s *ghit, struct tophit_s *dhit, int *ret_nseq, U2::TaskStateInfo & ti); } //namespace #endif //__UHMMSEARCH_CELL_H__ #endif //UGENE_CELL ugene-1.9.8/src/plugins_3rdparty/hmm2/src/u_search/uhmmsearch_sse.cpp0000644000175000017500000004555211651544327024372 0ustar ilyailya#ifdef HMMER_BUILD_WITH_SSE2 #include "uhmmsearch_opt.h" #include #include #include #include #include #include using namespace U2; namespace { #define CHUNK_SIZE (10 * 1024) const int ALIGNMENT_MEM = 128; #define ALIGNED(ptr, base) ( (unsigned char*) ( (((quintptr)(ptr))+((base)-1)) &~((base-1)) ) ) struct hmm_opt{ static const int ALIGNMENT_MEM = 128; // alignment of mem static const int ALIGNMENT_SCORES = 16; //alignment of tsc, msc, etc. int M; // Length of this HMM in states int * mem; // honestly allocated memory. All pointers below are mem + some offset. int * tsc[7]; // transition scores [0..6][1..M-1] int * msc[MAXCODE]; // M state emission probs. [0..MAXCODE-1][1..M] int * isc[MAXCODE]; // I state emission probs. [0..MAXCODE-1][1..M-1] int * xsc[4]; // N,E,C,J transition scores [0..3][0..1] int * bsc; // B state transition probs. [1..M] int * esc; // E state transition probs. [1..M] hmm_opt( plan7_s * hmm ) { assert( NULL != hmm ); M = hmm->M; qint64 tsc_sz = 7 * ( M + 16 ); qint64 msc_sz = MAXCODE * ( M + 1 + 16 ); qint64 isc_sz = MAXCODE * ( M + 16 ); qint64 xsc_sz = 50; qint64 bsc_sz = M + 1 + 12; qint64 esc_sz = M + 1 + 12; qint64 bsc_real_sz = M + 1; qint64 esc_real_sz = M + 1; qint64 total_sz = ( tsc_sz + msc_sz + isc_sz + xsc_sz + bsc_sz + esc_sz ) * sizeof( int ) + ALIGNMENT_MEM + 0x10 * ( 15 + 2 * MAXCODE ) * sizeof(int); mem = (int*)malloc( total_sz ); memset( mem, 0, total_sz ); int* mem_aligned = (int*)ALIGNED( mem, ALIGNMENT_MEM ); bsc = mem_aligned; bsc += 3; memcpy( bsc, hmm->bsc_mem, bsc_real_sz * sizeof(int) ); esc = (int*)ALIGNED( bsc + 4 + bsc_sz, ALIGNMENT_SCORES ) + 0x10; esc += 3; memcpy( esc, hmm->esc_mem, esc_real_sz * sizeof(int) ); for (int i=1;i<8;i++) { esc[M+i] = -INFTY; } int* tsc_tmp = (int*)ALIGNED( esc + esc_sz, ALIGNMENT_SCORES ) + 0x10; for(int i = 0; i < 7; ++i ) { tsc[i] = tsc_tmp; tsc_tmp = (int*)ALIGNED( tsc_tmp + M, ALIGNMENT_SCORES ) + 0x10; } tsc[1] += 3; tsc[4] += 3; for(int i = 0; i < 7; ++i ) { memcpy( tsc[i], hmm->tsc[i], ( M ) * sizeof(int) ); } int* msc_tmp = (int*)ALIGNED( tsc[0] + tsc_sz, ALIGNMENT_SCORES ); for(int i = 0; i < MAXCODE; ++i ) { msc[i] = msc_tmp; msc[i] += 3; msc_tmp = (int*)ALIGNED( msc_tmp + M + 1, ALIGNMENT_SCORES )+ 0x10; memcpy( msc[i], hmm->msc[i], ( M + 1 ) * sizeof(int) ); } int* isc_tmp = (int*)ALIGNED( msc[0] + msc_sz, ALIGNMENT_SCORES )+ 0x10; for(int i = 0; i < MAXCODE; ++i ) { isc[i] = isc_tmp; isc[i] += 3; isc_tmp = (int*)ALIGNED( isc_tmp + M, ALIGNMENT_SCORES )+ 0x10; memcpy( isc[i], hmm->isc[i], ( M ) * sizeof(int) ); } int* xsc_tmp = (int*)ALIGNED( isc[0] + isc_sz, ALIGNMENT_SCORES )+ 0x10; for(int i = 0; i < 4; ++i ) { xsc[i] = xsc_tmp; xsc_tmp = (int*)ALIGNED( xsc_tmp + 2, ALIGNMENT_SCORES )+ 0x10; for( int j = 0; j < 2; ++j ) { xsc[i][j] = hmm->xsc[i][j]; } } } ~hmm_opt() { delete[] mem; } void dump() { int i = 0; int j = 0;; printf("--START HMM OPT DUMP (M=%d)\n", M); for (i=0;iESC[%d]=%d\n",i, esc[i]); } for (i=0;iBSC[%d]=%d\n",i, bsc[i]); } for (i=0;iMSC[%d][%d]=%d\n",i,j, msc[i][j]); } } for (i=0;i<4;i++){ for (j=0;j<2;j++){ printf("HMM->XSC[%d][%d]=%d\n",i,j, xsc[i][j]); } } for (i=0;i<7;i++){ for (j=0;jTSC[%d][%d]=%d\n",i,j, tsc[i][j]); } } for (i=0;iISC[%d][%d]=%d\n",i,j, isc[i][j]); } } printf("--END HMM OPT DUMP (M=%d)\n", M); } }; inline int at0( __m128i from ) { int a = _mm_extract_epi16( from, 0 ) & 0xFFFF; int b = _mm_extract_epi16( from, 1 ) & 0xFFFF; return (a | (b << 16)); } inline int at1( __m128i from ) { int a = _mm_extract_epi16( from, 2 ) & 0xFFFF; int b = _mm_extract_epi16( from, 3 ) & 0xFFFF; return (a | (b << 16)); } inline int at2( __m128i from ) { int a = _mm_extract_epi16( from, 4 ) & 0xFFFF; int b = _mm_extract_epi16( from, 5 ) & 0xFFFF; return (a | (b << 16)); } inline int at3( __m128i from ) { int a = _mm_extract_epi16( from, 6 ) & 0xFFFF; int b = _mm_extract_epi16( from, 7 ) & 0xFFFF; return (a | (b << 16)); } inline __m128i shufflePMask( __m128i a, __m128i b ) { return _mm_set_epi32( at2(a), at1(a), at0(a), at3(b) ); } inline __m128i shuffleD0Mask( const __m128i& a, const __m128i& b ) { return _mm_set_epi32( at3(b), at2(b), at1(a), at0(a) ); } inline __m128i shuffleD1Mask( const __m128i& a, const __m128i& b ) { return _mm_set_epi32( at0(b), at0(b), at0(b), at0(a) ); } inline __m128i shuffleD2Mask( const __m128i& a, const __m128i& b ) { return _mm_set_epi32( at1(b), at1(b), at1(a), at0(a) ); } inline __m128i shuffleD3Mask( const __m128i& a, const __m128i& b ) { return _mm_set_epi32( at2(b), at2(a), at1(a), at0(a) ); } inline __m128i insert0I32( const __m128i& a, int b ) { __m128i mask_a = _mm_set_epi32( 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0 ); __m128i mask_b = _mm_set_epi32( 0, 0, 0, b ); __m128i res = _mm_and_si128( a, mask_a ); res = _mm_or_si128( res, mask_b ); return res; } inline __m128i insert3I32( const __m128i& a, int b ) { __m128i mask_a = _mm_set_epi32( 0, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF ); __m128i mask_b = _mm_set_epi32( b, 0, 0, 0 ); __m128i res = _mm_and_si128( a, mask_a ); res = _mm_or_si128( res, mask_b ); return res; } inline __m128i selectBits( const __m128i& a, const __m128i& b, const __m128i& pattern ) { __m128i tmpB = _mm_and_si128( pattern, b ); __m128i tmpA = _mm_andnot_si128( pattern, a ); return _mm_or_si128( tmpA, tmpB ); } inline int maxComponent( const __m128i& a ) { int max = at0(a); int e1 = at1(a); int e2 = at2(a); int e3 = at3(a); max = max > e1 ? max : e1; max = max > e2 ? max : e2; max = max > e3 ? max : e3; return max; } void p ( const char * name, __m128i arg ) { printf( "%s: {%d, %d, %d, %d}\n", name, at0(arg), at1(arg), at2(arg), at3(arg) ); } float viterbiSSE( hmm_opt* hmm, const unsigned char * seq, int seqLength, int* mscoreC, int* mscoreP, int* iscoreC, int *iscoreP, int* dscoreC, int *dscoreP ){ assert( NULL != hmm ); assert( NULL != seq && 0 < seqLength ); assert( NULL != mscoreC && NULL != mscoreP ); assert( NULL != iscoreC && NULL != iscoreP ); assert( NULL != dscoreC && NULL != dscoreP ); __m128i itV1, itV2, itV3, itV4, itV5, itV6, itV7, itV8; __m128i ipV, ipV1, dpV, dpV1, mpV, mpV1; __m128i dt1, dt2, dt3, dt4, dt, mt1, mt2, mt3, mt4; __m128i xscXTN = _mm_set1_epi32( hmm->xsc[XTN][MOVE] ); __m128i xscPXMB = _mm_set1_epi32( hmm->xsc[XTN][MOVE] ); __m128i hmmxscXTNLOOP = _mm_set1_epi32( hmm->xsc[XTN][LOOP] ); __m128i hmmxscXTCMOVE = _mm_set1_epi32( hmm->xsc[XTC][MOVE] ); __m128i hmmxscXTCLOOP = _mm_set1_epi32( hmm->xsc[XTC][LOOP] ); __m128i hmmxscXTJMOVE = _mm_set1_epi32( hmm->xsc[XTJ][MOVE] ); __m128i hmmxscXTJLOOP = _mm_set1_epi32( hmm->xsc[XTJ][LOOP] ); __m128i hmmxscXTEMOVE = _mm_set1_epi32( hmm->xsc[XTE][MOVE] ); __m128i hmmxscXTELOOP = _mm_set1_epi32( hmm->xsc[XTE][LOOP] ); __m128i zeroVEC = _mm_set1_epi32( 0 ); __m128i INFTY_VEC = _mm_set1_epi32( -INFTY ); __m128i xscCXME = _mm_set1_epi32( -INFTY ); __m128i xscCXMC = _mm_set1_epi32( -INFTY ); __m128i xscCXMJ = _mm_set1_epi32( -INFTY ); __m128i *hmmtscTII = (__m128i*)( hmm->tsc[TII] + 1 ); __m128i *hmmtscTMM = (__m128i*) hmm->tsc[TMM]; __m128i *hmmtscTIM = (__m128i*) hmm->tsc[TIM]; __m128i *hmmtscTDM = (__m128i*) hmm->tsc[TDM]; __m128i *hmmtscTMI = (__m128i*)( hmm->tsc[TMI] + 1 ); __m128i *hmmbsc = (__m128i*)( hmm->bsc + 1 ); __m128i *hmmesc = (__m128i*)( hmm->esc + 1 ); __m128i *mscCV = (__m128i*) ( mscoreC + 1 ); __m128i *iscCV = (__m128i*) ( iscoreC + 1 ); __m128i *dscCV = (__m128i*) ( dscoreC + 1 ); __m128i *mscPV = (__m128i*) ( mscoreP + 1 ); __m128i *iscPV = (__m128i*) ( iscoreP + 1 ); __m128i *dscPV = (__m128i*) ( dscoreP + 1 ); __m128i *Mdt = (__m128i*) hmm->tsc[TMD] - 1; __m128i *mscDSQ, *iscDSQ, *tmpMV, *tmpIV, *tmpDV; __m128i cmp1, cmp2, cmp3; float result = 0; int i = 0, j = 0, k = 0, sc = 0, M4th = 0; int *tmpM = NULL, *tmpD = NULL, *hmmtscTDDip = hmm->tsc[TDD]; M4th = ( hmm->M + 3 ) >> 2; for( k = 0; k <= M4th; ++k ) { mscPV[k] = INFTY_VEC; iscPV[k] = INFTY_VEC; dscPV[k] = INFTY_VEC; } for( i = 1; i <= seqLength; ++i ) { xscCXME = INFTY_VEC; mscDSQ = (__m128i*)( hmm->msc[(int)seq[i]] + 1); iscDSQ = (__m128i*)( hmm->isc[(int)seq[i]] + 1); for( k = 1, j = 1; k <= M4th; j += 8, k += 2 ) { ipV = shufflePMask( iscPV[k-1], iscPV[k-2] ); ipV1 = shufflePMask( iscPV[k], iscPV[k-1] ); mpV = shufflePMask( mscPV[k-1],mscPV[k-2] ); mpV1 = shufflePMask( mscPV[k], mscPV[k-1] ); dpV = shufflePMask( dscPV[k-1],dscPV[k-2] ); dpV1 = shufflePMask( dscPV[k], dscPV[k-1] ); itV2 = _mm_add_epi32( ipV, hmmtscTIM[k-1] ); itV6 = _mm_add_epi32( ipV1, hmmtscTIM[k] ); itV1 = _mm_add_epi32( mpV, hmmtscTMM[k-1] ); itV5 = _mm_add_epi32( mpV1, hmmtscTMM[k] ); itV4 = _mm_add_epi32( dpV, hmmtscTDM[k-1] ); itV8 = _mm_add_epi32( dpV1, hmmtscTDM[k] ); itV3 = _mm_add_epi32( xscPXMB, hmmbsc[k-1] ); itV7 = _mm_add_epi32( xscPXMB, hmmbsc[k] ); cmp1 = _mm_cmpgt_epi32( itV1, itV2 ); itV1 = selectBits( itV2, itV1, cmp1 ); cmp2 = _mm_cmpgt_epi32( itV3, itV4 ); dt4 = insert3I32( zeroVEC, hmmtscTDDip[j+2] ); itV2 = selectBits( itV4, itV3, cmp2 ); dt3 = _mm_set1_epi32(hmmtscTDDip[j+1]); cmp1 = _mm_cmpgt_epi32( itV1, itV2 ); dt3 = _mm_add_epi32( dt3, dt4 ); itV3 = selectBits( itV2, itV1, cmp1 ); cmp2 = _mm_cmpgt_epi32( itV5, itV6 ); dt3 = shuffleD0Mask( zeroVEC, dt3 ); itV1 = selectBits( itV6, itV5, cmp2 ); cmp1 = _mm_cmpgt_epi32( itV7, itV8 ); dt2 = _mm_set1_epi32(hmmtscTDDip[j]); itV2 = selectBits( itV8, itV7, cmp1 ); dt2 = _mm_add_epi32( dt2, dt3 ); cmp2 = _mm_cmpgt_epi32( itV1, itV2 ); mscCV[k-1] = _mm_add_epi32( itV3, mscDSQ[k-1] ); itV4 = selectBits( itV2, itV1, cmp2 ); dt2 = insert0I32(dt2, 0 ); mscCV[k] = _mm_add_epi32( itV4, mscDSQ[k] ); dt1 = _mm_set1_epi32( hmmtscTDDip[j-1] ); mpV = shufflePMask( mscCV[k-1], mscCV[k-2] ); dt1 = _mm_add_epi32( dt1, dt2 ); mt1 = _mm_add_epi32( mpV, Mdt[k] ); dt = _mm_set1_epi32( dscoreC[j-1] ); mt2 = shuffleD1Mask( INFTY_VEC, mt1 ); dt1 = _mm_add_epi32( dt, dt1 ); mt3 = shuffleD2Mask( INFTY_VEC, mt1 ); dt2 = _mm_add_epi32( mt2, dt2 ); mt4 = shuffleD3Mask( INFTY_VEC, mt1 ); dt3 = _mm_add_epi32( mt3, dt3 ); cmp1 = _mm_cmpgt_epi32( dt1, mt1 ); dt4 = _mm_add_epi32( mt4, dt4 ); cmp2 = _mm_cmpgt_epi32( dt2, dt3 ); dt1 = selectBits( mt1, dt1, cmp1 ); cmp3 = _mm_cmpgt_epi32( dt1, dt4 ); dt2 = selectBits( dt3, dt2, cmp2 ); dt1 = selectBits( dt4, dt1, cmp3 ); cmp2 = _mm_cmpgt_epi32( dt1, dt2 ); dt4 = insert3I32( zeroVEC, hmmtscTDDip[j+6] ); dscCV[k-1] = selectBits( dt2, dt1, cmp2 ); dt3 = _mm_set1_epi32( hmmtscTDDip[j+5] ); itV1 = _mm_add_epi32( mscPV[k-1], hmmtscTMI[k-1] ); dt3 = _mm_add_epi32( dt3, dt4 ); dt3 = shuffleD0Mask( zeroVEC, dt3 ); dt2 = _mm_set1_epi32( hmmtscTDDip[j+4] ); itV2 = _mm_add_epi32( iscPV[k-1], hmmtscTII[k-1] ); dt2 = _mm_add_epi32( dt2, dt3 ); dt1 = _mm_set1_epi32( hmmtscTDDip[j+3] ); dt2 = insert0I32( dt2, 0 ); cmp1 = _mm_cmpgt_epi32( itV1, itV2 ); dt1 = _mm_add_epi32( dt1, dt2 ); mpV = shufflePMask( mscCV[k], mscCV[k-1] ); mt1 = _mm_add_epi32( mpV, Mdt[k+1] ); dt = _mm_set1_epi32( dscoreC[j+3] ); itV3 = selectBits( itV2, itV1, cmp1 ); dt1 = _mm_add_epi32( dt, dt1 ); mt2 = shuffleD1Mask( INFTY_VEC, mt1 ); itV1 = _mm_add_epi32( mscPV[k], hmmtscTMI[k] ); dt2 = _mm_add_epi32( mt2, dt2 ); mt3 = shuffleD2Mask( INFTY_VEC, mt1 ); itV2 = _mm_add_epi32( iscPV[k], hmmtscTII[k] ); dt3 = _mm_add_epi32( mt3, dt3 ); mt4 = shuffleD3Mask( INFTY_VEC, mt1 ); cmp3 = _mm_cmpgt_epi32( itV1, itV2 ); dt4 = _mm_add_epi32( mt4, dt4 ); cmp1 = _mm_cmpgt_epi32( dt1, mt1 ); itV4 = selectBits( itV2, itV1, cmp3 ); cmp2 = _mm_cmpgt_epi32( dt2, dt3 ); dt1 = selectBits( mt1, dt1, cmp1 ); dt2 = selectBits( dt3, dt2, cmp2 ); cmp1 = _mm_cmpgt_epi32( dt1, dt4 ); dt1 = selectBits( dt4, dt1, cmp1 ); cmp2 = _mm_cmpgt_epi32( dt1, dt2 ); iscCV[k-1] = _mm_add_epi32( itV3, iscDSQ[k-1] ); dscCV[k] = selectBits( dt2, dt1, cmp2 ); itV1 = _mm_add_epi32( mscCV[k-1], hmmesc[k-1] ); itV2 = _mm_add_epi32( mscCV[k], hmmesc[k] ); cmp1 = _mm_cmpgt_epi32( itV1, xscCXME ); cmp2 = _mm_cmpgt_epi32( itV2, xscCXME ); xscCXME = selectBits( xscCXME, itV1, cmp1 ); iscCV[k] = _mm_add_epi32( itV4, iscDSQ[k] ); xscCXME = selectBits( xscCXME, itV2, cmp2 ); } xscCXME = _mm_set1_epi32( maxComponent( xscCXME ) ); itV2 = _mm_add_epi32( xscCXMJ, hmmxscXTJLOOP ); itV3 = _mm_add_epi32( xscCXME, hmmxscXTELOOP ); itV1 = _mm_add_epi32( xscCXMJ, hmmxscXTJMOVE ); cmp1 = _mm_cmpgt_epi32( itV2, itV3 ); xscXTN = _mm_add_epi32( xscXTN, hmmxscXTNLOOP ); xscCXMJ = selectBits( itV3, itV2, cmp1 ); itV2 = _mm_add_epi32( xscCXMC, hmmxscXTCLOOP ); cmp1 = _mm_cmpgt_epi32( xscXTN, itV1 ); itV3 = _mm_add_epi32( xscCXME, hmmxscXTEMOVE ); xscPXMB = selectBits( itV1, xscXTN, cmp1 ); cmp2 = _mm_cmpgt_epi32( itV2, itV3 ); xscCXMC = selectBits( itV3, itV2, cmp2 ); tmpMV = mscCV; tmpIV = iscCV; tmpDV = dscCV; mscCV = mscPV; iscCV = iscPV; dscCV = dscPV; mscPV = tmpMV; iscPV = tmpIV; dscPV = tmpDV; tmpM = mscoreC; tmpD = dscoreC; mscoreC = mscoreP; dscoreC = dscoreP; mscoreP = tmpM; dscoreP = tmpD; } itV1 = _mm_add_epi32( xscCXMC, hmmxscXTCMOVE ); sc = at0(itV1); result = (float) sc / INTSCALE; return result; } } //anonymous namespace //assuming dsq is aligned QList sseScoring( unsigned char * dsq, int seqlen, plan7_s* hmm, HMMSeqGranulation * gr, TaskStateInfo& ti ) { assert( dsq ); assert( gr ); assert( seqlen > 0); const int M4th = ( hmm->M + 3 ) >> 2; const int memSz = 4 + (M4th+1) * 16 + 12 + ALIGNMENT_MEM; char* mscCurMem = (char*)malloc( memSz ); char* iscCurMem = (char*)malloc( memSz ); char* dscCurMem = (char*)malloc( memSz ); char* mscPrevMem = (char*)malloc( memSz ); char* iscPrevMem = (char*)malloc( memSz ); char* dscPrevMem = (char*)malloc( memSz ); memset( mscCurMem, 0, memSz ); memset( iscCurMem, 0, memSz ); memset( dscCurMem, 0, memSz ); memset( mscPrevMem, 0, memSz ); memset( iscPrevMem, 0, memSz ); memset( dscPrevMem, 0, memSz ); int* mscCur = (int*)( ALIGNED( mscCurMem, ALIGNMENT_MEM ) + 0xC ); int* iscCur = (int*)( ALIGNED( iscCurMem, ALIGNMENT_MEM ) + 0xC ); int* dscCur = (int*)( ALIGNED( dscCurMem, ALIGNMENT_MEM ) + 0xC ); int* mscPrev = (int*)( ALIGNED( mscPrevMem, ALIGNMENT_MEM ) + 0xC ); int* iscPrev = (int*)( ALIGNED( iscPrevMem, ALIGNMENT_MEM ) + 0xC ); int* dscPrev = (int*)( ALIGNED( dscPrevMem, ALIGNMENT_MEM ) + 0xC ); QList results; U2Region range( 0, seqlen ); gr->overlap = 2 * hmm->M; gr->exOverlap = 0; gr->chunksize = qBound( gr->overlap+1, CHUNK_SIZE, seqlen ); gr->regions = SequenceWalkerTask::splitRange( range, gr->chunksize, gr->overlap, gr->exOverlap, false ); const QVector & regions = gr->regions; int regionsSz = regions.size(); int regionsPassed = 0; hmm_opt hmmOpt( hmm ); foreach( U2Region chunk, regions ) { unsigned char * curSeqAddr = dsq + chunk.startPos; int curSeqLen = chunk.length; float sc = viterbiSSE( &hmmOpt, curSeqAddr, curSeqLen, mscCur, mscPrev, iscCur, iscPrev, dscCur, dscPrev ); results.push_back( sc ); ti.progress = (int)( ( 100.0 * ( regionsPassed++ ) ) / regionsSz ); if( ti.cancelFlag ) { break; } } free( mscCurMem ); free( iscCurMem ); free( dscCurMem ); free( mscPrevMem ); free( iscPrevMem ); free( dscPrevMem ); return results; } #endif // HMMER_SSE ugene-1.9.8/src/plugins_3rdparty/hmm2/src/u_search/HMMSearchDialogController.cpp0000644000175000017500000001742611651544327026316 0ustar ilyailya#include "HMMSearchDialogController.h" #include "HMMSearchTask.h" #include "TaskLocalStorage.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include namespace U2 { HMMSearchDialogController::HMMSearchDialogController(const DNASequenceObject* seqObj, QWidget* p) : QDialog(p) , dnaSequence(seqObj->getDNASequence()) { searchTask = NULL; setupUi(this); CreateAnnotationModel cm; cm.hideLocation = true; cm.sequenceObjectRef = seqObj; cm.data->name = "hmm_signal"; cm.sequenceLen = seqObj->getSequenceLen(); createController = new CreateAnnotationWidgetController(cm, this); QWidget* w = createController->getWidget(); QVBoxLayout* l = qobject_cast(layout()); l->insertWidget(1, w); setMinimumSize( layout()->totalSizeHint() ); #ifdef UGENE_CELL algoCombo->addItem( tr("Cell BE optimized"), HMMSearchAlgo_CellOptimized ); #endif if( AppResourcePool::isSSE2Enabled() ) { algoCombo->addItem( tr("SSE optimized"), HMMSearchAlgo_SSEOptimized ); } algoCombo->addItem( tr("Conservative"), HMMSearchAlgo_Conservative ); connect(hmmFileButton, SIGNAL(clicked()), SLOT(sl_hmmFileClicked())); connect(okButton, SIGNAL(clicked()), SLOT(sl_okClicked())); connect(domEvalueCuttofBox,SIGNAL(valueChanged(int)), SLOT(sl_expSpinBoxValueChanged(int))); } void HMMSearchDialogController::sl_expSpinBoxValueChanged(int i){ if(i>=0){ domEvalueCuttofBox->setPrefix("1E+"); } else { domEvalueCuttofBox->setPrefix("1E"); } } void HMMSearchDialogController::reject() { if (searchTask!=NULL) { searchTask->cancel(); } QDialog::reject(); } void HMMSearchDialogController::sl_hmmFileClicked() { LastOpenDirHelper lod(HMMIO::HMM_ID); lod.url = QFileDialog::getOpenFileName(this, tr("select_file_with_hmm_model"), lod, HMMIO::getHMMFileFilter()); if (lod.url.isEmpty()) { return; } hmmFileEdit->setText(QFileInfo(lod.url).absoluteFilePath()); } void HMMSearchDialogController::sl_okClicked() { if (searchTask!= NULL) { accept(); //go to background return; } QString errMsg; QString hmmFile = hmmFileEdit->text(); if (hmmFile.isEmpty()) { hmmFileEdit->setFocus(); errMsg = tr("hmm_file_not_set"); } UHMMSearchSettings s; if (expertOptionsBox->isChecked() && errMsg.isEmpty()) { s.domE = pow(10,(float) domEvalueCuttofBox->value()); s.domT = (float) minScoreBox->value(); s.eValueNSeqs = evalueAsNSeqBox->value(); } s.alg = HMMSearchAlgo( algoCombo->itemData( algoCombo->currentIndex() ).toInt() ); if (errMsg.isEmpty()) { errMsg = createController->validate(); } if (!errMsg.isEmpty()) { QMessageBox::critical(this, tr("error"), errMsg); return; } createController->prepareAnnotationObject(); const CreateAnnotationModel& cm = createController->getModel(); QString annotationName = cm.data->name; searchTask = new HMMSearchToAnnotationsTask(hmmFile, dnaSequence, cm.getAnnotationObject(), cm.groupName, annotationName, s); searchTask->setReportingEnabled(true); connect(searchTask, SIGNAL(si_stateChanged()), SLOT(sl_onStateChanged())); connect(searchTask, SIGNAL(si_progressChanged()), SLOT(sl_onProgressChanged())); AppContext::getTaskScheduler()->registerTopLevelTask(searchTask); statusLabel->setText(tr("starting_search_process")); //update buttons okButton->setText(tr("back_button")); cancelButton->setText(tr("cancel_button")); // new default behavior: hide dialog and use taskview to track the progress and results accept(); //go to background } void HMMSearchDialogController::sl_onStateChanged() { Task* t = qobject_cast(sender()); assert(searchTask != NULL); if (searchTask!=t || t->getState() != Task::State_Finished) { return; } searchTask->disconnect(this); const TaskStateInfo& si = searchTask->getStateInfo(); if (si.hasError()) { statusLabel->setText(tr("search_finished_with_errors_%1").arg(si.getError())); } else { statusLabel->setText(tr("search_finished_successfuly")); } okButton->setText(tr("ok_button")); cancelButton->setText(tr("close_button")); searchTask = NULL; } void HMMSearchDialogController::sl_onProgressChanged() { assert(searchTask == sender()); statusLabel->setText(tr("progress_%1%").arg(qMax(0, searchTask->getProgress()))); } ////////////////////////////////////////////////////////////////////////// // TASKS HMMSearchToAnnotationsTask::HMMSearchToAnnotationsTask(const QString& _hmmFile, const DNASequence& s, AnnotationTableObject* ao, const QString& _agroup, const QString& _aname, const UHMMSearchSettings& _settings) : Task("", TaskFlags_NR_FOSCOE | TaskFlag_ReportingIsSupported), hmmFile(_hmmFile), dnaSequence(s), agroup(_agroup), aname(_aname), settings(_settings), readHMMTask(NULL), searchTask(NULL), createAnnotationsTask(NULL), aobj(ao) { setVerboseLogMode(true); setTaskName(tr("HMM search, file '%1'").arg(QFileInfo(hmmFile).fileName())); readHMMTask = new HMMReadTask(hmmFile); readHMMTask->setSubtaskProgressWeight(0); if (dnaSequence.alphabet->isRaw()) { stateInfo.setError( tr("raw_alphabet_not_supported") ); } else { addSubTask(readHMMTask); } } QList HMMSearchToAnnotationsTask::onSubTaskFinished(Task* subTask) { Q_UNUSED(subTask); QList res; if (hasError() || isCanceled()) { return res; } if (aobj.isNull()) { stateInfo.setError( tr("annotation_obj_removed") ); return res; } if (searchTask == NULL) { assert(readHMMTask->isFinished()); plan7_s* hmm = readHMMTask->getHMM(); assert(hmm!=NULL); searchTask = new HMMSearchTask(hmm, dnaSequence, settings); res.append(searchTask); } else if (createAnnotationsTask == NULL){ assert(searchTask->isFinished() && !searchTask->hasError()); QList annotations = searchTask->getResultsAsAnnotations(aname); if (!annotations.isEmpty()) { createAnnotationsTask = new CreateAnnotationsTask(aobj, agroup, annotations); createAnnotationsTask->setSubtaskProgressWeight(0); res.append(createAnnotationsTask); } } return res; } QString HMMSearchToAnnotationsTask::generateReport() const { QString res; res+=""; res+=""; if (hasError() || isCanceled()) { res+=""; res+="
    " + tr("HMM profile used") + "" + QFileInfo(hmmFile).absoluteFilePath() + "
    " + tr("Task was not finished") + "
    "; return res; } res+="" + tr("Result annotation table") + "" + aobj->getDocument()->getName() + ""; res+="" + tr("Result annotation group") + "" + agroup + ""; res+="" + tr("Result annotation name") + "" + aname + ""; int nResults = createAnnotationsTask == NULL ? 0 : createAnnotationsTask->getAnnotations().size(); res+="" + tr("Results count") + "" + QString::number(nResults)+ ""; res+=""; return res; } }//namespace ugene-1.9.8/src/plugins_3rdparty/hmm2/src/u_search/uhmmsearch.h0000644000175000017500000000210211651544327023145 0ustar ilyailya#ifndef _U2_UHMM_SEARCH_H_ #define _U2_UHMM_SEARCH_H_ #include #include #include struct plan7_s; namespace U2 { class TaskStateInfo; enum HMMSearchAlgo { HMMSearchAlgo_Conservative, HMMSearchAlgo_SSEOptimized, HMMSearchAlgo_CellOptimized }; class UHMMSearchSettings { public: UHMMSearchSettings() : globE(10), eValueNSeqs(1), domE(0.9999999), domT(-FLT_MAX), searchChunkSize(1000000), extraLen(-1), alg(HMMSearchAlgo_Conservative) {} float globE; int eValueNSeqs; float domE; float domT; int searchChunkSize; int extraLen; //-1 -> auto HMMSearchAlgo alg; }; class UHMMSearchResult { public: UHMMSearchResult(const U2Region& _r, float sc, float eval) : r(_r), score(sc), evalue(eval){} U2Region r; float score; float evalue; }; class UHMMSearch : public QObject { Q_OBJECT public: static QList search(plan7_s* hmm, const char* seq, int seqLen, const UHMMSearchSettings& s, TaskStateInfo& si); }; } //namespace #endif ugene-1.9.8/src/plugins_3rdparty/hmm2/src/u_search/HMMSearchTask.h0000644000175000017500000000315511651544327023414 0ustar ilyailya#ifndef _U2_HMMSEARCH_TASK_H_ #define _U2_HMMSEARCH_TASK_H_ #include "uhmmsearch.h" #include #include #include #include #include #include struct plan7_s; namespace U2 { class DNATranslation; class HMMSearchTaskResult { public: HMMSearchTaskResult() : evalue(0), score(0), onCompl(false), onAmino(false), borderResult(false), filtered(false){} float evalue; float score; bool onCompl; bool onAmino; bool borderResult; bool filtered; U2Region r; }; class HMMSearchTask: public Task, SequenceWalkerCallback { Q_OBJECT public: HMMSearchTask(plan7_s* hmm, const DNASequence& seq, const UHMMSearchSettings& s); virtual void prepare(); const QList& getResults() const {return results;} virtual void onRegion(SequenceWalkerSubtask* t, TaskStateInfo& stateInfo); Task::ReportResult report(); QList getResultsAsAnnotations(const QString& name) const; private: bool checkAlphabets(int hmmAl, DNAAlphabet* seqAl, DNATranslation*& complTrans, DNATranslation*& aminoTrans); private: plan7_s* hmm; DNASequence seq; UHMMSearchSettings settings; DNATranslation* complTrans; DNATranslation* aminoTrans; QList results; QList overlaps; QMutex lock; }; }//namespace #endif ugene-1.9.8/src/plugins_3rdparty/hmm2/src/u_search/uhmmsearch_opt.h0000644000175000017500000000155611651544327024043 0ustar ilyailya#ifndef __UHMMSEARCH_OPT_H__ #define __UHMMSEARCH_OPT_H__ #include #include #include namespace U2 { class U2Region; class TaskStateInfo; } struct HMMSeqGranulation { HMMSeqGranulation() : overlap(0), chunksize(0), exOverlap(0) {}; int overlap; int chunksize; int exOverlap; QVector regions; }; typedef QList (*hmmScoringFunction)( unsigned char * dsq, int seqlen, plan7_s* hmm, HMMSeqGranulation * gr, U2::TaskStateInfo& ti ); void main_loop_opt( struct plan7_s * hmm, const char * seq_, int seqlen, struct threshold_s *thresh, int do_forward, int do_null2, int do_xnu, struct histogram_s * histogram, struct tophit_s * ghit, struct tophit_s * dhit, int * ret_nseq, U2::TaskStateInfo & ti, hmmScoringFunction scoring_f ); #endif ugene-1.9.8/src/plugins_3rdparty/hmm2/src/HMMIOWorker.h0000644000175000017500000000761411651544326021277 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_HMM_IO_WORKER_H_ #define _U2_HMM_IO_WORKER_H_ #include #include #include struct plan7_s; struct msa_struct; Q_DECLARE_METATYPE(plan7_s*); namespace U2 { namespace LocalWorkflow { class HMMLib : public QObject { Q_OBJECT public: static const Descriptor HMM_CATEGORY(); static const Descriptor HMM2_SLOT; static DataTypePtr HMM_PROFILE_TYPE(); static const QString HMM_PROFILE_TYPE_ID; static void init(); static void cleanup(); }; class HMMIOProto : public IntegralBusActorPrototype { public: HMMIOProto(const Descriptor& desc, const QList& ports, const QList& attrs = QList()); virtual bool isAcceptableDrop(const QMimeData*, QVariantMap*) const = 0; bool isAcceptableDrop(const QMimeData*, QVariantMap*, const QString&) const; }; class ReadHMMProto : public HMMIOProto { public: ReadHMMProto(const Descriptor& _desc, const QList& _ports, const QList& _attrs = QList()); virtual bool isAcceptableDrop(const QMimeData*, QVariantMap*) const; }; class WriteHMMProto : public HMMIOProto { public: WriteHMMProto(const Descriptor& _desc, const QList& _ports, const QList& _attrs = QList()); virtual bool isAcceptableDrop(const QMimeData*, QVariantMap*) const; }; class HMMReadPrompter : public PrompterBase { Q_OBJECT public: HMMReadPrompter(Actor* p = 0) : PrompterBase(p) {} protected: QString composeRichDoc(); }; class HMMWritePrompter : public PrompterBase { Q_OBJECT public: HMMWritePrompter(Actor* p = 0) : PrompterBase(p) {} protected: QString composeRichDoc(); }; class HMMReader : public BaseWorker { Q_OBJECT public: static const QString ACTOR; HMMReader(Actor* a) : BaseWorker(a), output(NULL) {} virtual void init() ; virtual bool isReady() {return !urls.isEmpty();} virtual Task* tick() ; virtual bool isDone() {return urls.isEmpty();} virtual void cleanup() {} private slots: void sl_taskFinished(); protected: CommunicationChannel *output; QStringList urls; }; class HMMWriter : public BaseWorker { Q_OBJECT public: static const QString ACTOR; HMMWriter(Actor* a) : BaseWorker(a), input(NULL), done(false), fileMode(SaveDoc_Overwrite) {} virtual void init() ; virtual bool isReady() {return input && input->hasMessage();} virtual Task* tick() ; virtual bool isDone() {return !input || input->isEnded();} virtual void cleanup() {} protected: CommunicationChannel *input; QString url; QMap counter; bool done; uint fileMode; }; class HMMIOWorkerFactory : public DomainFactory { public: static void init(); static void cleanup(); HMMIOWorkerFactory(const Descriptor& d) : DomainFactory(d) {} virtual Worker* createWorker(Actor* a); }; } // Workflow namespace } // U2 namespace #endif ugene-1.9.8/src/plugins_3rdparty/hmm2/src/HMMIO.cpp0000644000175000017500000006225211651544326020437 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "HMMIO.h" #include "hmmer2/funcs.h" #include "TaskLocalStorage.h" #include #include #include #include #include #include #include #include #include #include #include namespace U2 { /* TRANSLATOR U2::IOAdapter */ static const char * prob2ascii(float p, float null) { HMMERTaskLocalData *tld = getHMMERTaskLocalData(); //static char buffer[8]; char *buffer = tld->buffer; if (p == 0.0) { return "*"; } snprintf(buffer, 8, "%6d", Prob2Score(p, null)); return buffer; } static float ascii2prob(char *s, float null) { return (*s == '*') ? 0. : Score2Prob(atoi(s), null); } static void multiline(QString& res, const QString& prefix, const char* s) { if (s == NULL) { return; } QStringList lines = QString(s).split('\n'); foreach(const QString& line, lines) { res+= prefix + line + '\n'; } } void HMMIO::writeHMM2(IOAdapterFactory* iof, const QString& url, TaskStateInfo& si, plan7_s *hmm) { if (hmm->atype == hmmNOTSETYET) { si.setError( tr("alphabet_not_set") ); return; } //get HMMERTaskLocalData HMMERTaskLocalData *tld = getHMMERTaskLocalData(); alphabet_s &al = tld->al; SetAlphabet(hmm->atype); QString res; res+=QString().sprintf("HMMER2.0 [%s]\n", PACKAGE_VERSION); // magic header //write header information res+=QString().sprintf("NAME %s\n", hmm->name); if (hmm->flags & PLAN7_ACC) { res+=QString().sprintf("ACC %s\n", hmm->acc); } if (hmm->flags & PLAN7_DESC) { res+=QString().sprintf("DESC %s\n", hmm->desc); } res+=QString().sprintf("LENG %d\n", hmm->M); res+=QString().sprintf("ALPH %s\n", (al.Alphabet_type == hmmAMINO) ? "Amino":"Nucleic"); res+=QString().sprintf("RF %s\n", (hmm->flags & PLAN7_RF) ? "yes" : "no"); res+=QString().sprintf("CS %s\n", (hmm->flags & PLAN7_CS) ? "yes" : "no"); res+=QString().sprintf("MAP %s\n", (hmm->flags & PLAN7_MAP) ? "yes" : "no"); multiline(res, "COM ", hmm->comlog); res+=QString().sprintf("NSEQ %d\n", hmm->nseq); res+=QString().sprintf("DATE %s\n", hmm->ctime); res+=QString().sprintf("CKSUM %d\n", hmm->checksum); if (hmm->flags & PLAN7_GA) { res+=QString().sprintf("GA %.1f %.1f\n", hmm->ga1, hmm->ga2); } if (hmm->flags & PLAN7_TC) { res+=QString().sprintf("TC %.1f %.1f\n", hmm->tc1, hmm->tc2); } if (hmm->flags & PLAN7_NC) { res+=QString().sprintf("NC %.1f %.1f\n", hmm->nc1, hmm->nc2); } // Specials res+="XT "; for (int k = 0; k < 4; k++) { for (int x = 0; x < 2; x++) { res+=QString().sprintf("%6s ", prob2ascii(hmm->xt[k][x], 1.0)); } } res+="\n"; /* Save the null model first, so HMM readers can decode * log odds scores on the fly. Save as log odds probabilities * relative to 1/Alphabet_size (flat distribution) */ res+=QString().sprintf("NULT "); res+=QString().sprintf("%6s ", prob2ascii(hmm->p1, 1.0)); /* p1 */ res+=QString().sprintf("%6s\n", prob2ascii(1.0-hmm->p1, 1.0)); /* p2 */ res+="NULE "; for (int x = 0; x < al.Alphabet_size; x++) { res+=QString().sprintf("%6s ", prob2ascii(hmm->null[x], 1/(float)(al.Alphabet_size))); } res+="\n"; // EVD statistics if (hmm->flags & PLAN7_STATS) { res+=QString().sprintf("EVD %10f %10f\n", hmm->mu, hmm->lambda); } // Print header res+=QString().sprintf("HMM "); for (int x = 0; x < al.Alphabet_size; x++) { res+=QString().sprintf(" %c ", al.Alphabet[x]); } res+=QString().sprintf("\n"); res+=QString().sprintf(" %6s %6s %6s %6s %6s %6s %6s %6s %6s\n", "m->m", "m->i", "m->d", "i->m", "i->i", "d->m", "d->d", "b->m", "m->e"); //Print HMM parameters (main section of the save file) res+=QString().sprintf(" %6s %6s ", prob2ascii(1-hmm->tbd1, 1.0), "*"); res+=QString().sprintf("%6s\n", prob2ascii(hmm->tbd1, 1.0)); for (int k = 1; k <= hmm->M; k++) { /* Line 1: k, match emissions, map */ res+=QString().sprintf(" %5d ", k); for (int x = 0; x < al.Alphabet_size; x++) { res+=QString().sprintf("%6s ", prob2ascii(hmm->mat[k][x], hmm->null[x])); } if (hmm->flags & PLAN7_MAP) res+=QString().sprintf("%5d", hmm->map[k]); res+="\n"; /* Line 2: RF and insert emissions */ res+=QString().sprintf(" %5c ", hmm->flags & PLAN7_RF ? hmm->rf[k] : '-'); for (int x = 0; x < al.Alphabet_size; x++) { res+=QString().sprintf("%6s ", (k < hmm->M) ? prob2ascii(hmm->ins[k][x], hmm->null[x]) : "*"); } res+="\n"; /* Line 3: CS and transition probs */ res+=QString().sprintf(" %5c ", hmm->flags & PLAN7_CS ? hmm->cs[k] : '-'); for (int ts = 0; ts < 7; ts++) { res+=QString().sprintf("%6s ", (k < hmm->M) ? prob2ascii(hmm->t[k][ts], 1.0) : "*"); } res+=QString().sprintf("%6s ", prob2ascii(hmm->begin[k], 1.0)); res+=QString().sprintf("%6s ", prob2ascii(hmm->end[k], 1.0)); res+="\n"; } res+="//\n"; std::auto_ptr io(iof->createIOAdapter()); if (!io->open(url, IOAdapterMode_Write)) { si.setError(L10N::errorOpeningFileWrite(url)); return; } int len = io->writeBlock(res.toAscii()); if (len != res.length()) { si.setError(L10N::errorWritingFile(url)); return; } io->close(); } void HMMIO::readHMM2(IOAdapterFactory* iof, const QString& url, TaskStateInfo& si, plan7_s **ret_hmm) { #define BUFF_SIZE 512 char buffer[BUFF_SIZE+1]; char *s; int M; float p; int k, x; //get HMMERTaskLocalData HMMERTaskLocalData *tld = getHMMERTaskLocalData(); alphabet_s &al = tld->al; struct plan7_s *hmm = NULL; std::auto_ptr io(iof->createIOAdapter()); if (!io->open(url, IOAdapterMode_Read)) { si.setError(L10N::errorOpeningFileRead(url)); return; } const QByteArray& upper = TextUtils::UPPER_CASE_MAP; const QBitArray& lineBreaks = TextUtils::LINE_BREAKS; do { //use loop to be able to use 'break' out of it bool lineOk = true; int len = io->readUntil(buffer, BUFF_SIZE, lineBreaks, IOAdapter::Term_Include, &lineOk); if (!lineOk) { si.setError( tr("illegal line") ); break; } if (strncmp(buffer, "HMMER2.0", 8) != 0) { si.setError( tr("file_format_is_not_supported") ); break; } //Get the header information: tag/value pairs in any order, //ignore unknown tags, stop when "HMM" is reached (signaling start of main model) hmm = AllocPlan7Shell(); M = -1; char* next = NULL; while ((len = io->readUntil(buffer, BUFF_SIZE, lineBreaks, IOAdapter::Term_Include, &lineOk)) != 0) { if (!lineOk) { si.setError( tr("illegal line") ); break; } next = NULL; buffer[len] = '\0'; if (strncmp(buffer, "NAME ", 5) == 0) Plan7SetName(hmm, buffer+6); else if (strncmp(buffer, "ACC ", 5) == 0) Plan7SetAccession(hmm, buffer+6); else if (strncmp(buffer, "DESC ", 5) == 0) Plan7SetDescription(hmm, buffer+6); else if (strncmp(buffer, "LENG ", 5) == 0) M = atoi(buffer+6); else if (strncmp(buffer, "NSEQ ", 5) == 0) hmm->nseq = atoi(buffer+6); else if (strncmp(buffer, "ALPH ", 5) == 0) { // Alphabet type TextUtils::translate(upper, buffer+6, 7); int atype = hmmNOTSETYET; if (strncmp(buffer+6, "AMINO", 5) == 0) atype = hmmAMINO; else if (strncmp(buffer+6, "NUCLEIC", 7) == 0) atype = hmmNUCLEIC; else { si.setError( tr("value is illegal %1").arg("ALPH") ); break; }; SetAlphabet(atype); hmm->atype = atype; } else if (strncmp(buffer, "RF ", 5) == 0) { // Reference annotation present? if (upper.at(*(buffer+6)) == 'Y') { hmm->flags |= PLAN7_RF; } } else if (strncmp(buffer, "CS ", 5) == 0) { // Consensus annotation present? if (upper.at(*(buffer+6)) == 'Y') hmm->flags |= PLAN7_CS; } else if (strncmp(buffer, "MAP ", 5) == 0) { // Map annotation present? if (upper.at(*(buffer+6)) == 'Y') hmm->flags |= PLAN7_MAP; } else if (strncmp(buffer, "COM ", 5) == 0) { // Command line log StringChop(buffer+6); if (hmm->comlog == NULL) { hmm->comlog = Strdup(buffer+6); } else { int oldSize = strlen(hmm->comlog) + 1; int newSize = sizeof(char *) * (oldSize + strlen(buffer+6)); hmm->comlog = (char*)ReallocOrDie(hmm->comlog, newSize); sre_strlcat(hmm->comlog, "\n", newSize); sre_strlcat(hmm->comlog, buffer+6, newSize); } } else if (strncmp(buffer, "DATE ", 5) == 0) { // Date file created StringChop(buffer+6); hmm->ctime= Strdup(buffer+6); } else if (strncmp(buffer, "GA ", 5) == 0) { if ((s = strtok_r(buffer+6, " \t\n", &next)) == NULL) { si.setError( tr("invalid_file_structure_near_%1").arg("GA") ); break; } hmm->ga1 = atof(s); if ((s = strtok_r(NULL, " \t\n", &next)) == NULL) { si.setError( tr("invalid_file_structure_near_%1").arg("GA") ); break; } hmm->ga2 = atof(s); hmm->flags |= PLAN7_GA; } else if (strncmp(buffer, "TC ", 5) == 0) { if ((s = strtok_r(buffer+6, " \t\n", &next)) == NULL) { si.setError( tr("invalid_file_structure_near_%1").arg("TC") ); break; } hmm->tc1 = atof(s); if ((s = strtok_r(NULL, " \t\n", &next)) == NULL) { si.setError( tr("invalid_file_structure_near_%1").arg("TC") ); break; } hmm->tc2 = atof(s); hmm->flags |= PLAN7_TC; } else if (strncmp(buffer, "NC ", 5) == 0) { if ((s = strtok_r(buffer+6, " \t\n", &next)) == NULL) { si.setError( tr("invalid_file_structure_near_%1").arg("NC") ); break; } hmm->nc1 = atof(s); if ((s = strtok_r(NULL, " \t\n", &next)) == NULL) { si.setError( tr("invalid_file_structure_near_%1").arg("NC") ); break; } hmm->nc2 = atof(s); hmm->flags |= PLAN7_NC; } else if (strncmp(buffer, "XT ", 5) == 0) { // Special transition section if ((s = strtok_r(buffer+6, " \t\n", &next)) == NULL) { si.setError( tr("invalid_file_structure_near_%1").arg("XT") ); break; } for (k = 0; k < 4; k++) { for (x = 0; x < 2; x++) { if (s == NULL) { si.setError( tr("invalid_file_structure_near_%1").arg("XT") ); break; } hmm->xt[k][x] = ascii2prob(s, 1.0); s = strtok_r(NULL, " \t\n", &next); } } } else if (strncmp(buffer, "NULT ", 5) == 0) { // Null model transitions if ((s = strtok_r(buffer+6, " \t\n", &next)) == NULL) { si.setError( tr("invalid_file_structure_near_%1").arg("NULT") ); break; } hmm->p1 = ascii2prob(s, 1.); if ((s = strtok_r(NULL, " \t\n", &next)) == NULL) { si.setError( tr("invalid_file_structure_near_%1").arg("NULT") ); break; } hmm->p1 = hmm->p1 / (hmm->p1 + ascii2prob(s, 1.0)); } else if (strncmp(buffer, "NULE ", 5) == 0) { //Null model emissions if ( al.Alphabet_type == hmmNOTSETYET) { si.setError( tr("ALPH must precede NULE in HMM save files") ); break; } s = strtok_r(buffer+6, " \t\n", &next); for (x = 0; x < al.Alphabet_size; x++) { if (s == NULL) { si.setError( tr("invalid_file_structure_near_%1").arg("NULE") ); break; } hmm->null[x] = ascii2prob(s, 1./(float)al.Alphabet_size); s = strtok_r(NULL, " \t\n", &next); } } else if (strncmp(buffer, "EVD ", 5) == 0) { // EVD parameters hmm->flags |= PLAN7_STATS; if ((s = strtok_r(buffer+6, " \t\n", &next)) == NULL) { si.setError( tr("invalid_file_structure_near_%1").arg("EVD - mu") ); break; } hmm->mu = atof(s); if ((s = strtok_r(NULL, " \t\n", &next)) == NULL) { si.setError( tr("invalid_file_structure_near_%1").arg("EVD - lambda") ); break; } hmm->lambda = atof(s); } else if (strncmp(buffer, "CKSUM", 5) == 0) { hmm->checksum = atoi(buffer+6); } else if (strncmp(buffer, "HMM ", 5) == 0) { break; } } if (si.hasError()) { break; } // partial check for mandatory fields if (M < 1) { si.setError( tr("value is illegal %1").arg("M") ); break; } if (hmm->name == NULL) { si.setError( tr("value is illegal %1").arg("name") ); break; } if (al.Alphabet_type == hmmNOTSETYET) { si.setError( tr("value is not set for %1").arg("ALPH") ); break; } // Main model section. Read as integer log odds, convert to probabilities AllocPlan7Body(hmm, M); // skip an annotation line len = io->readUntil(buffer, BUFF_SIZE, lineBreaks, IOAdapter::Term_Include, &lineOk); if (!lineOk) { si.setError( tr("illegal line") ); break; } // parse tbd1 line len = io->readUntil(buffer, BUFF_SIZE, lineBreaks, IOAdapter::Term_Include, &lineOk); if (!lineOk) { si.setError( tr("illegal line") ); break; } buffer[len] = '\0'; next = NULL; if ((s = strtok_r(buffer, " \t\n", &next)) == NULL) { si.setError( tr("invalid_file_structure_near_%1").arg("tbd1") ); break; } p = ascii2prob(s, 1.0); if ((s = strtok_r(NULL, " \t\n", &next)) == NULL) { si.setError( tr("invalid_file_structure_near_%1").arg("tbd1") ); break; } if ((s = strtok_r(NULL, " \t\n", &next)) == NULL) { si.setError( tr("invalid_file_structure_near_%1").arg("tbd1") ); break; } hmm->tbd1 = ascii2prob(s, 1.0); hmm->tbd1 = hmm->tbd1 / (p + hmm->tbd1); // main model for (k = 1; k <= hmm->M; k++) { // Line 1: k, match emissions, map len = io->readUntil(buffer, BUFF_SIZE, lineBreaks, IOAdapter::Term_Include, &lineOk); if (!lineOk) { si.setError( tr("illegal line") ); break; } next = NULL; buffer[len] = '\0'; if ((s = strtok_r(buffer, " \t\n", &next)) == NULL) { si.setError( tr("invalid_file_structure_near_%1").arg("main model 1") ); break; } if (atoi(s) != k) { si.setError( tr("invalid_file_structure_near_%1").arg("main model (k)") ); break; } for (x = 0; x < al.Alphabet_size; x++) { if ((s = strtok_r(NULL, " \t\n", &next)) == NULL) { si.setError( tr("invalid_file_structure_near_%1").arg("main model (mat)") ); break; } hmm->mat[k][x] = ascii2prob(s, hmm->null[x]); } if (hmm->flags & PLAN7_MAP) { if ((s = strtok_r(NULL, " \t\n", &next)) == NULL) { si.setError( tr("invalid_file_structure_near_%1").arg("main model (map)") ); break; } hmm->map[k] = atoi(s); } // Line 2: RF and insert emissions len = io->readUntil(buffer, BUFF_SIZE, lineBreaks, IOAdapter::Term_Include, &lineOk); if (!lineOk) { si.setError( tr("illegal line") ); break; } buffer[len] = '\0'; next = NULL; if ((s = strtok_r(buffer, " \t\n", &next)) == NULL) { si.setError( tr("invalid_file_structure_near_%1").arg("main model 2") ); break; } if (hmm->flags & PLAN7_RF) { hmm->rf[k] = *s; } if (k < hmm->M) { for (x = 0; x < al.Alphabet_size; x++) { if ((s = strtok_r(NULL, " \t\n", &next)) == NULL) { si.setError( tr("invalid_file_structure_near_%1").arg("main model (ins)") ); break; } hmm->ins[k][x] = ascii2prob(s, hmm->null[x]); } } // Line 3: CS and transitions len = io->readUntil(buffer, BUFF_SIZE, lineBreaks, IOAdapter::Term_Include, &lineOk); if (!lineOk) { si.setError( tr("illegal line") ); break; } buffer[len] = '\0'; next = NULL; if ((s = strtok_r(buffer, " \t\n", &next)) == NULL) { si.setError( tr("invalid_file_structure_near_%1").arg("main model 3") ); break; } if (hmm->flags & PLAN7_CS) { hmm->cs[k] = *s; } for (x = 0; x < 7; x++) { if ((s = strtok_r(NULL, " \t\n", &next)) == NULL) { si.setError( tr("invalid_file_structure_near_%1").arg("main model (t)") ); break; } if (k < hmm->M) hmm->t[k][x] = ascii2prob(s, 1.0); } if ((s = strtok_r(NULL, " \t\n", &next)) == NULL) { si.setError( tr("invalid_file_structure_near_%1").arg("main model (begin)") ); break; } hmm->begin[k] = ascii2prob(s, 1.0); if ((s = strtok_r(NULL, " \t\n", &next)) == NULL) { si.setError( tr("invalid_file_structure_near_%1").arg("main model (end)") ); break; } hmm->end[k] = ascii2prob(s, 1.0); } // end loop over main model if (si.hasError()) { break; } // Advance to record separator do { len = io->readUntil(buffer, BUFF_SIZE, lineBreaks, IOAdapter::Term_Include, &lineOk); if (!lineOk) { si.setError( tr("no // symbol found") ); break; } } while (strncmp(buffer, "//", 2) != 0); if (si.hasError()) { break; } // Set flags and return hmm->flags |= PLAN7_HASPROB; /* probabilities are valid */ hmm->flags &= ~PLAN7_HASBITS; /* scores are not valid */ Plan7Renormalize(hmm); *ret_hmm = hmm; } while (false); io->close(); if (si.hasError()) { if (hmm != NULL) { FreePlan7(hmm); } *ret_hmm = NULL; } } const QString HMMIO::HMM_ID("hmmer"); const QString HMMIO::HMM_EXT("hmm"); plan7_s * HMMIO::cloneHMM( plan7_s * src ) { assert( src ); int M = src->M; assert( M > 0 ); plan7_s * dst = AllocPlan7( M ); //copying model annotations assert( src->name ); //name is mandatory Plan7SetName( dst, src->name ); if( src->acc ) { Plan7SetAccession( dst, src->acc ); } if( src->desc ) { Plan7SetDescription( dst, src->desc ); } if( src->rf ) { qCopy( src->rf, src->rf + M+2, &dst->rf[0] ); } if( src->cs ) { qCopy( src->cs, src->cs + M+2, &dst->cs[0] ); } if( src->ca ) { qCopy( src->ca, src->ca + M+2, &dst->ca[0] ); } if( src->comlog ) { dst->comlog = Strdup( src->comlog ); } if( src->ctime ) { dst->ctime = Strdup( src->ctime ); } if( src->map ) { qCopy( src->map, src->map + M+1, &dst->map[0] ); } dst->nseq = src->nseq; dst->checksum = src->checksum; //Pfam-specific cutoffs: dst->ga1 = src->ga1; dst->ga2 = src->ga2; dst->tc1 = src->tc1; dst->tc2 = src->tc2; dst->nc1 = src->nc1; dst->nc2 = src->nc2; //probabilities dst->M = src->M; //hack! qCopy( src->t[0], src->t[0] + M*7, dst->t[0] ); qCopy( src->mat[0], src->mat[0] + (M+1)*MAXABET, dst->mat[0] ); qCopy( src->ins[0], src->ins[0] + M*MAXABET, dst->ins[0] ); dst->tbd1 = src->tbd1; qCopy( &src->xt[0][0], &src->xt[0][0] + 8, &dst->xt[0][0] ); qCopy( src->begin, src->begin + M+1, &dst->begin[0] ); qCopy( src->end, src->end + M+1, &dst->end[0] ); qCopy( src->null, src->null + MAXABET, &dst->null[0] ); dst->p1 = src->p1; long tsc_s = (7*M); long msc_s = (MAXCODE*(M+1)); long isc_s = (MAXCODE*(M)); long bsc_s = (M+1); long esc_s = (M+1); long xsc_s = 8; qCopy( src->tsc_mem, src->tsc_mem + tsc_s, &dst->tsc_mem[0] ); qCopy( src->msc_mem, src->msc_mem + msc_s, &dst->msc_mem[0] ); qCopy( src->isc_mem, src->isc_mem + isc_s, &dst->isc_mem[0] ); qCopy( src->bsc_mem, src->bsc_mem + bsc_s, &dst->bsc_mem[0] ); qCopy( src->esc_mem, src->esc_mem + esc_s, &dst->esc_mem[0] ); qCopy( &src->xsc[0][0], &src->xsc[0][0] + xsc_s, &dst->xsc[0][0] ); //scoring parameters assert( !src->dnai && !src->dnam ); dst->dna2 = src->dna2; dst->dna4 = src->dna4; dst->mu = src->mu; dst->lambda = src->lambda; dst->flags = src->flags; dst->atype = src->atype; return dst; } QString HMMIO::getHMMFileFilter() { return DialogUtils::prepareFileFilter(tr("HMM models"), QStringList(HMM_EXT)); } DNAAlphabetType HMMIO::convertHMMAlphabet(int atype) { if (atype == hmmAMINO) { return DNAAlphabet_AMINO; } else if (atype == hmmNUCLEIC) { return DNAAlphabet_NUCL; } return DNAAlphabet_RAW; } HMMReadTask::HMMReadTask(const QString& _url) : Task("", TaskFlag_None), hmm(NULL), url(_url) { QString tn = tr("Read HMM profile '%1'").arg(QFileInfo(url).fileName()); setTaskName(tn); } HMMReadTask::~HMMReadTask() { if (hmm!=NULL) { FreePlan7(hmm); } } void HMMReadTask::run() { TaskLocalData::createHMMContext(getTaskId(), true); IOAdapterFactory* iof = AppContext::getIOAdapterRegistry()->getIOAdapterFactoryById(BaseIOAdapters::url2io(url)); HMMIO::readHMM2(iof, url, stateInfo, &hmm); TaskLocalData::freeHMMContext(getTaskId()); } HMMWriteTask::HMMWriteTask(const QString& url, plan7_s* s, uint f) : Task("", TaskFlag_None), url(url), hmm(s), fileMode(f) { QString tn = tr("Write HMM profile '%1'").arg(QFileInfo(url).fileName()); setTaskName(tn); } void HMMWriteTask::run() { TaskLocalData::createHMMContext(getTaskId(), true); IOAdapterFactory* iof = AppContext::getIOAdapterRegistry()->getIOAdapterFactoryById(BaseIOAdapters::url2io(url)); if (fileMode & SaveDoc_Roll && !GUrlUtils::renameFileWithNameRoll(url, stateInfo)) { return; } HMMIO::writeHMM2(iof, url, stateInfo, hmm); TaskLocalData::freeHMMContext(getTaskId()); } }//namespace ugene-1.9.8/src/plugins_3rdparty/hmm2/src/u_calibrate/0000755000175000017500000000000011651544311021317 5ustar ilyailyaugene-1.9.8/src/plugins_3rdparty/hmm2/src/u_calibrate/HMMCalibrateDialogController.h0000644000175000017500000000121211651544326027106 0ustar ilyailya#ifndef _U2_HMMCALIBRATE_DIALOG_CONTROLLER_H_ #define _U2_HMMCALIBRATE_DIALOG_CONTROLLER_H_ #include "uhmmcalibrate.h" #include #include namespace U2 { class Task; class HMMCalibrateDialogController : public QDialog, public Ui_HMMCalibrateDialog { Q_OBJECT public: HMMCalibrateDialogController(QWidget* w = NULL); public slots: virtual void reject(); private slots: void sl_hmmFileButtonClicked(); void sl_outFileButtonClicked(); void sl_okButtonClicked(); void sl_onStateChanged(); void sl_onProgressChanged(); private: Task* task; }; } //namespace #endif ugene-1.9.8/src/plugins_3rdparty/hmm2/src/u_calibrate/ui/0000755000175000017500000000000011651544311021734 5ustar ilyailyaugene-1.9.8/src/plugins_3rdparty/hmm2/src/u_calibrate/ui/HMMCalibrateDialog.ui0000644000175000017500000003005611651544327025656 0ustar ilyailya HMMCalibrateDialog 0 0 525 314 hmmcalibrate_dialog_title hmm_file_name ... expert_options true false fixed_tip fixed_tip fixed_tip fixed Qt::Horizontal 323 20 100 0 fixed_tip fixed_tip fixed_tip Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter 0 10000000 0 mean_tip mean_tip mean_tip mean Qt::Horizontal 323 20 100 0 mean_tip mean_tip mean_tip Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter 1 100000000 325 num_tip num_tip num_tip num Qt::Horizontal 323 20 100 0 num_tip num_tip num_tip Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter 1 1000000 5000 sd_tip sd_tip sd_tip sd Qt::Horizontal 323 20 sd_tip sd_tip sd_tip Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter 0.010000000000000 1000000.000000000000000 200.000000000000000 seed_tip seed_tip seed_tip seed Qt::Horizontal 323 20 seed_tip seed_tip seed_tip Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter 2000000000 output_file_name true false output_file_name output_file_name output_file_name ... Qt::Vertical 20 5 Qt::Horizontal 328 22 ok_button close_button cancelButton clicked() HMMCalibrateDialog reject() 630 286 339 154 ugene-1.9.8/src/plugins_3rdparty/hmm2/src/u_calibrate/HMMCalibrateTask.h0000644000175000017500000000517511651544326024561 0ustar ilyailya#ifndef _U2_HMMCALIBRATE_TASK_H_ #define _U2_HMMCALIBRATE_TASK_H_ #include "uhmmcalibrate.h" #include struct HMMERTaskLocalData; namespace U2 { class HMMCalibrateParallelSubTask; class HMMCalibrateAbstractTask; class HMMReadTask; class HMMCalibrateAbstractTask; class HMMCalibrateToFileTask : public Task { Q_OBJECT public: HMMCalibrateToFileTask(const QString& _inFile, const QString& _outFile, const UHMMCalibrateSettings& s); const plan7_s* getHMM() const {return hmm;} virtual void prepare(); virtual QList onSubTaskFinished(Task* subTask); QString generateReport() const; protected: plan7_s* hmm; QString inFile; QString outFile; UHMMCalibrateSettings settings; HMMReadTask* readTask; HMMCalibrateAbstractTask* calibrateTask; }; class HMMCalibrateAbstractTask : public Task { Q_OBJECT public: HMMCalibrateAbstractTask(const QString& _name, plan7_s* _hmm, const UHMMCalibrateSettings& s, TaskFlags fl = TaskFlag_None) :Task(_name, fl), hmm(_hmm), settings(s) {} plan7_s* getHMM(){return hmm;} const UHMMCalibrateSettings& getSettings() const {return settings;} protected: plan7_s* hmm; UHMMCalibrateSettings settings; }; class HMMCalibrateTask : public HMMCalibrateAbstractTask { Q_OBJECT public: HMMCalibrateTask(plan7_s* hmm, const UHMMCalibrateSettings& s); void run(); }; ////////////////////////////////////////////////////////////////////////// // parallel version class HMMCreateWPoolTask; // 1 creates WPOOL // runs N parallel subtasks class HMMCalibrateParallelTask : public HMMCalibrateAbstractTask { Q_OBJECT public: HMMCalibrateParallelTask(plan7_s* hmm, const UHMMCalibrateSettings& s); ~HMMCalibrateParallelTask() {cleanup();} void prepare(); QList onSubTaskFinished(Task* subTask); void run(); ReportResult report(); void cleanup(); WorkPool_s* getWorkPool() {return &wpool;} private: HMMCreateWPoolTask* initTask; WorkPool_s wpool; }; //initializes pool that will be used by parallel calibrate subtasks class HMMCreateWPoolTask : public Task { Q_OBJECT public: HMMCreateWPoolTask(HMMCalibrateParallelTask* t); ~HMMCreateWPoolTask() {cleanup();} void run(); void runUnsafe(); HMMCalibrateParallelTask* pt; }; class HMMCalibrateParallelSubTask : public Task { Q_OBJECT public: HMMCalibrateParallelSubTask(HMMCalibrateParallelTask* pt); void run(); private: HMMCalibrateParallelTask* pt; }; }//namespace #endif ugene-1.9.8/src/plugins_3rdparty/hmm2/src/u_calibrate/HMMCalibrateDialogController.cpp0000644000175000017500000001021411651544326027443 0ustar ilyailya#include "HMMCalibrateDialogController.h" #include "HMMCalibrateTask.h" #include #include #include #include #include #include #include namespace U2 { HMMCalibrateDialogController::HMMCalibrateDialogController(QWidget* w) : QDialog(w) { task = NULL; setupUi(this); connect(hmmFileButton, SIGNAL(clicked()), SLOT(sl_hmmFileButtonClicked())); connect(outFileButton, SIGNAL(clicked()), SLOT(sl_outFileButtonClicked())); connect(okButton, SIGNAL(clicked()), SLOT(sl_okButtonClicked())); } void HMMCalibrateDialogController::sl_hmmFileButtonClicked() { LastOpenDirHelper lod(HMMIO::HMM_ID); lod.url = QFileDialog::getOpenFileName(this, tr("select_file_with_hmm_model"), lod, HMMIO::getHMMFileFilter()); if (lod.url.isEmpty()) { return; } hmmFileEdit->setText(QFileInfo(lod.url).absoluteFilePath()); } void HMMCalibrateDialogController::sl_outFileButtonClicked() { LastOpenDirHelper lod(HMMIO::HMM_ID); lod.url= QFileDialog::getSaveFileName(this, tr("select_file_with_hmm_model"), lod, HMMIO::getHMMFileFilter()); if (lod.url.isEmpty()) { return; } outFileEdit->setText(QFileInfo(lod.url).absoluteFilePath()); } void HMMCalibrateDialogController::sl_okButtonClicked() { if (task != NULL) { accept(); //go to background return; } // try prepare model UHMMCalibrateSettings s; s.nThreads = AppResourcePool::instance()->getIdealThreadCount(); QString errMsg; QString inFile = hmmFileEdit->text(); QString outFile = inFile; if (inFile.isEmpty() && !QFileInfo(inFile).exists()) { errMsg = tr("illegal_in_file_name"); hmmFileEdit->setFocus(); } if (expertGroupBox->isChecked() && errMsg.isEmpty()) { if (fixedBox->value() < 0) { errMsg = tr("illegal fixed value"); fixedBox->setFocus(); } else { s.fixedlen = fixedBox->value(); } s.lenmean = meanBox->value(); s.nsample = numBox->value(); s.lensd = (float)sdBox->value(); if (seedBox->value()!=0) { s.seed = seedBox->value(); } } if (outputGroupBox->isChecked() && errMsg.isEmpty()) { outFile = outFileEdit->text(); if (outFile.isEmpty()) { errMsg = tr("illegal_out_file_name"); outFileEdit->setFocus(); } } if (!errMsg.isEmpty()) { QMessageBox::critical(this, tr("error"), errMsg); return; } // run task task = new HMMCalibrateToFileTask(inFile, outFile, s); task->setReportingEnabled(true); connect(task, SIGNAL(si_stateChanged()), SLOT(sl_onStateChanged())); connect(task, SIGNAL(si_progressChanged()), SLOT(sl_onProgressChanged())); AppContext::getTaskScheduler()->registerTopLevelTask(task); statusLabel->setText(tr("starting_calibration_process")); //update buttons okButton->setText(tr("back_button")); cancelButton->setText(tr("cancel_button")); // new default behavior: hide dialog and use taskview to track the progress and results accept(); //go to background } void HMMCalibrateDialogController::sl_onStateChanged() { Task* t = qobject_cast(sender()); assert(task!=NULL); if (task!=t || t->getState() != Task::State_Finished) { return; } task->disconnect(this); const TaskStateInfo& si = task->getStateInfo(); if (si.hasError()) { statusLabel->setText(tr("calibration_finished_with_errors_%1").arg(si.getError())); } else if (task->isCanceled()) { statusLabel->setText(tr("calibration_canceled")); } else { statusLabel->setText(tr("calibration_finished_successfuly")); } okButton->setText(tr("ok_button")); cancelButton->setText(tr("close_button")); task = NULL; } void HMMCalibrateDialogController::sl_onProgressChanged() { assert(task==sender()); statusLabel->setText(tr("progress_%1%").arg(task->getProgress())); } void HMMCalibrateDialogController::reject() { if (task!=NULL) { task->cancel(); } QDialog::reject(); } }//namespace ugene-1.9.8/src/plugins_3rdparty/hmm2/src/u_calibrate/HMMCalibrateTask.cpp0000644000175000017500000001565111651544326025114 0ustar ilyailya#include "HMMCalibrateTask.h" #include #include #include #include #include namespace U2 { HMMCalibrateTask::HMMCalibrateTask(plan7_s* hmm, const UHMMCalibrateSettings& s) : HMMCalibrateAbstractTask("", hmm, s) { GCOUNTER( cvar, tvar, "HMMCalibrateTask" ); setTaskName(tr("HMM calibrate '%1'").arg(hmm->name)); tpm = Task::Progress_Manual; } void HMMCalibrateTask::run() { TaskLocalData::createHMMContext(getTaskId(), true); try { UHMMCalibrate::calibrate(hmm, settings, stateInfo); } catch (HMMException e) { stateInfo.setError(e.error); } TaskLocalData::freeHMMContext(getTaskId()); } ////////////////////////////////////////////////////////////////////////// //top-lebel parallel calibration subtask HMMCalibrateParallelTask::HMMCalibrateParallelTask(plan7_s* _hmm, const UHMMCalibrateSettings& s) : HMMCalibrateAbstractTask(tr("HMM calibrate '%1'").arg(_hmm->name), _hmm, s), initTask(NULL) { wpool.hmm = hmm; wpool.progress = &stateInfo.progress; tpm = Task::Progress_Manual; } void HMMCalibrateParallelTask::prepare() { TaskLocalData::createHMMContext(getTaskId(), false); initTask = new HMMCreateWPoolTask(this); addSubTask(initTask); for(int i=0;i < settings.nThreads;i++){ addSubTask(new HMMCalibrateParallelSubTask(this)); } setMaxParallelSubtasks(1); } QList HMMCalibrateParallelTask::onSubTaskFinished(Task* subTask) { if (subTask == initTask) { setMaxParallelSubtasks(settings.nThreads); } return QList(); } void HMMCalibrateParallelTask::run() { if (hasError() || isCanceled()) { return; } TaskLocalData::bindToHMMContext(getTaskId()); try { histogram_s* hist = getWorkPool()->hist; if (!ExtremeValueFitHistogram(hist, TRUE, 9999.)) { stateInfo.setError("fit failed; num sequences may be set too small?\n"); } else { hmm->flags |= PLAN7_STATS; hmm->mu = hist->param[EVD_MU]; hmm->lambda = hist->param[EVD_LAMBDA]; } } catch (HMMException e) { stateInfo.setError(e.error); } TaskLocalData::detachFromHMMContext(); } Task::ReportResult HMMCalibrateParallelTask::report() { TaskLocalData::freeHMMContext(getTaskId()); return ReportResult_Finished; } void HMMCalibrateParallelTask::cleanup() { if (wpool.hist!=NULL) { FreeHistogram(wpool.hist); // exception safe function -> does not depend on hmm context wpool.hist = NULL; } } ////////////////////////////////////////////////////////////////////////// // task to init wpool state HMMCreateWPoolTask::HMMCreateWPoolTask(HMMCalibrateParallelTask* t) : Task(tr("Initialize parallel context"), TaskFlag_None), pt(t) { } void HMMCreateWPoolTask::run() { TaskLocalData::bindToHMMContext(pt->getTaskId()); try { runUnsafe(); } catch (HMMException e) { stateInfo.setError(e.error); } TaskLocalData::detachFromHMMContext(); } void HMMCreateWPoolTask::runUnsafe() { const UHMMCalibrateSettings& settings = pt->getSettings(); WorkPool_s* wpool = pt->getWorkPool(); SetAlphabet(wpool->hmm->atype); sre_srandom(settings.seed); wpool->fixedlen = settings.fixedlen; wpool->hist = AllocHistogram(-200, 200, 100); wpool->lenmean = settings.lenmean; wpool->lensd = settings.lensd; wpool->nsample = settings.nsample; wpool->nseq = 0; wpool->randomseq.resize(MAXABET); wpool->max_score = -FLT_MAX; float p1; P7Logoddsify(wpool->hmm, TRUE); P7DefaultNullModel(wpool->randomseq.data(), &p1); } ////////////////////////////////////////////////////////////////////////// //parallel calibrate subtask HMMCalibrateParallelSubTask::HMMCalibrateParallelSubTask(HMMCalibrateParallelTask* t) :Task(tr("Parallel HMM calibration subtask"), TaskFlag_None), pt(t) { tpm = Task::Progress_Manual; } void HMMCalibrateParallelSubTask::run() { TaskLocalData::bindToHMMContext(pt->getTaskId()); try { UHMMCalibrate::calibrateParallel(pt->getWorkPool(), stateInfo); } catch (HMMException e) { stateInfo.setError(e.error); } TaskLocalData::detachFromHMMContext(); } ////////////////////////////////////////////////////////////////////////// // task to save calibration results to file HMMCalibrateToFileTask::HMMCalibrateToFileTask(const QString& _inFile, const QString& _outFile, const UHMMCalibrateSettings& s) : Task("", TaskFlags_NR_FOSCOE|TaskFlag_ReportingIsSupported), hmm(NULL), inFile(_inFile), outFile(_outFile), settings(s) { setVerboseLogMode(true); QString tn = tr("HMM calibrate '%1'").arg(QFileInfo(inFile).fileName()); setTaskName(tn); readTask = NULL; calibrateTask = NULL; } void HMMCalibrateToFileTask::prepare() { readTask = new HMMReadTask(inFile); readTask->setSubtaskProgressWeight(0); addSubTask(readTask); } QList HMMCalibrateToFileTask::onSubTaskFinished(Task* subTask) { QList res; if (hasError() || isCanceled()) { return res; } if (subTask == readTask) { hmm = readTask->getHMM(); assert(hmm!=NULL); if (settings.nThreads == 1) { calibrateTask = new HMMCalibrateTask(hmm, settings); } else { calibrateTask = new HMMCalibrateParallelTask(hmm, settings); } res.append(calibrateTask); } else if (subTask == calibrateTask) { Task* t = new HMMWriteTask(outFile, hmm); t->setSubtaskProgressWeight(0); res.append(t); } return res; } QString HMMCalibrateToFileTask::generateReport() const { QString res; res+=""; res+=""; if (hasError() || isCanceled()) { res+=""; res+="
    " + tr("Source profile") + "" + QFileInfo(inFile).absoluteFilePath() + "
    " + tr("Task was not finished") + "
    "; return res; } res+="" + tr("Result profile") + "" + QFileInfo(outFile).absoluteFilePath() + ""; res+="" + tr("Expert options") + ""; res+="" + tr("Number of random sequences to sample") + ""+QString::number(settings.nsample)+""; res+="" + tr("Random number seed") + ""+QString::number(settings.seed)+""; res+="" + tr("Mean of length distribution") + ""+QString::number(settings.lenmean)+""; res+="" + tr("Standard deviation of length distribution") + ""+QString::number(settings.lensd)+""; res+="" + tr("Calculated evidence (mu , lambda)") + ""+QString::number(hmm->mu, 'f', 6) + ", " + QString::number(hmm->lambda, 'f', 6) + ""; res+=""; return res; } }//endif ugene-1.9.8/src/plugins_3rdparty/hmm2/src/u_calibrate/uhmmcalibrate.cpp0000644000175000017500000001350111651544327024647 0ustar ilyailya#include "uhmmcalibrate.h" #include #include #include #include #include #include #include namespace U2 { static void main_loop_serial(struct plan7_s *hmm, int seed, int nsample, float lenmean, float lensd, int fixedlen, struct histogram_s **ret_hist, float *ret_max, int& cancelFlag, int& progress); UHMMCalibrateSettings::UHMMCalibrateSettings() { nsample = 5000; fixedlen = 0; lenmean = 325.; lensd = 200.; seed = (int) time ((time_t *) NULL); nThreads = 1; } void UHMMCalibrate::calibrate(plan7_s* hmm, const UHMMCalibrateSettings& s, TaskStateInfo& si) { struct histogram_s *hist; // a resulting histogram float max = 0; main_loop_serial(hmm, s.seed, s.nsample, s.lenmean, s.lensd, s.fixedlen, &hist, &max, si.cancelFlag, si.progress); if (!si.cancelFlag) { // Fit an EVD to the observed histogram. // The TRUE left-censors and fits only the right slope of the histogram. // The 9999. is an arbitrary high number that means we won't trim // outliers on the right. if (! ExtremeValueFitHistogram(hist, TRUE, 9999.)) { si.setError( "fit failed; num sequences may be set too small?\n" ); } else { hmm->flags |= PLAN7_STATS; hmm->mu = hist->param[EVD_MU]; hmm->lambda = hist->param[EVD_LAMBDA]; } } FreeHistogram(hist); } // Function: main_loop_serial() // Date: SRE, Tue Aug 18 16:18:28 1998 [St. Louis] // // Purpose: Given an HMM and parameters for synthesizing random // sequences; return a histogram of scores. // (Serial version) // // Args: hmm - an HMM to calibrate. // seed - random number seed // nsample - number of seqs to synthesize // lenmean - mean length of random sequence // lensd - std dev of random seq length // fixedlen - if nonzero, override lenmean, always this len // ret_hist - RETURN: the score histogram // ret_max - RETURN: highest score seen in simulation // // Returns: (void) // hist is alloc'ed here, and must be free'd by caller. static void main_loop_serial(struct plan7_s *hmm, int seed, int nsample, float lenmean, float lensd, int fixedlen, struct histogram_s **ret_hist, float *ret_max, int& cancelFlag, int& progress) { struct histogram_s *hist; struct dpmatrix_s *mx; float randomseq[MAXABET]; float p1; float max; char *seq; unsigned char *dsq; float score; int sqlen; int idx; // Initialize. // We assume we've already set the alphabet (safe, because // HMM input sets the alphabet). sre_srandom(seed); //get HMMERTaskLocalData HMMERTaskLocalData *tls = getHMMERTaskLocalData(); alphabet_s &al = tls->al; SetAlphabet(hmm->atype); P7Logoddsify(hmm, TRUE); P7DefaultNullModel(randomseq, &p1); hist = AllocHistogram(-200, 200, 100); mx = CreatePlan7Matrix(1, hmm->M, 25, 0); max = -FLT_MAX; progress = 0; int pStub; for (idx = 0; idx < nsample && !cancelFlag; idx++) { // choose length of random sequence if (fixedlen) { sqlen = fixedlen; } else { do sqlen = (int) Gaussrandom(lenmean, lensd); while (sqlen < 1); } // generate it seq = RandomSequence(al.Alphabet, randomseq, al.Alphabet_size, sqlen); dsq = DigitizeSequence(seq, sqlen); if (P7ViterbiSpaceOK(sqlen, hmm->M, mx)) { score = P7Viterbi(dsq, sqlen, hmm, mx, NULL); } else { score = P7SmallViterbi(dsq, sqlen, hmm, mx, NULL, pStub); } AddToHistogram(hist, score); max = qMax(score, max); progress = int(100*idx/float(nsample)); free(dsq); free(seq); } FreePlan7Matrix(mx); *ret_hist = hist; *ret_max = max; } //parallel calibrate void UHMMCalibrate::calibrateParallel(WorkPool_s *wpool, TaskStateInfo& si) { HMMERTaskLocalData *tls = getHMMERTaskLocalData(); struct alphabet_s *al = &tls->al; struct plan7_s *hmm = wpool->hmm; struct dpmatrix_s *mx = CreatePlan7Matrix(1, hmm->M, 25, 0); int len; float sc; char *seq; unsigned char *dsq; while(true) { /* generate a sequence */ { QMutexLocker locker(&wpool->lockInput); wpool->nseq++; if (wpool->nseq > wpool->nsample) { /* we're done; release input lock, break loop */ break; } if (wpool->fixedlen) { len = wpool->fixedlen; } else { do { len = (int) Gaussrandom(wpool->lenmean, wpool->lensd); } while (len < 1); } seq = RandomSequence(al->Alphabet, wpool->randomseq.data(), al->Alphabet_size, len); } /* compute score */ dsq = DigitizeSequence(seq, len); if (P7ViterbiSpaceOK(len, hmm->M, mx)) { sc = P7Viterbi(dsq, len, hmm, mx, NULL); } else { int pStub; sc = P7SmallViterbi(dsq, len, hmm, mx, NULL, pStub); } free(dsq); free(seq); /* save output */ QMutexLocker locker(&wpool->lockOutput); AddToHistogram(wpool->hist, sc); wpool->max_score = qMax(wpool->max_score, sc); si.progress = int(100*wpool->nseq/float(wpool->nsample)); //TODO: update progress for all tasks? if (wpool->progress!=NULL) { *wpool->progress = si.progress; } } FreePlan7Matrix(mx); } }//namespace ugene-1.9.8/src/plugins_3rdparty/hmm2/src/u_calibrate/uhmmcalibrate.h0000644000175000017500000000355511651544327024324 0ustar ilyailya#ifndef _U2_UHMM_CALIBRATE_H_ #define _U2_UHMM_CALIBRATE_H_ struct plan7_s; struct alphabet_s; struct histogram_s; #include #include #include namespace U2 { class TaskStateInfo; class UHMMCalibrateSettings { public: UHMMCalibrateSettings(); int nsample; // number of random seqs to sample int seed; // random number seed int fixedlen; // fixed length, or 0 if unused float lenmean; // mean of length distribution float lensd; // std dev of length distribution int nThreads; }; struct WorkPool_s { WorkPool_s() { hmm = NULL; fixedlen = 0; lenmean = 0; lensd = 0; nsample = 0; nseq = 0; hist = NULL; max_score = -FLT_MAX; progress = NULL; } /* Static configuration */ plan7_s* hmm; /* ptr to single HMM to search with */ int fixedlen; /* if >0, fix random seq len to this */ float lenmean; /* mean of Gaussian for random seq len */ float lensd; /* s.d. of Gaussian for random seq len */ QVector randomseq; /* 0..Alphabet_size-1 i.i.d. probs */ int nsample; /* number of random seqs to do */ /* Shared (mutex-protected) input */ int nseq; /* current number of seqs searched */ /* Shared (mutex-protected) output */ QMutex lockInput; QMutex lockOutput; histogram_s* hist; /* histogram */ float max_score; /* maximum score seen */ int* progress; }; class UHMMCalibrate { public: static void calibrate(plan7_s* hmm, const UHMMCalibrateSettings& s, TaskStateInfo& si); static void calibrateParallel(WorkPool_s *wpool, TaskStateInfo& si); }; }//namespace #endif ugene-1.9.8/src/plugins_3rdparty/hmm2/src/HMMIOWorker.cpp0000644000175000017500000002635111651544326021631 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "HMMIOWorker.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "HMMIO.h" #include "u_search/HMMSearchDialogController.h" #include "u_build/HMMBuildWorker.h" #include "u_search/HMMSearchWorker.h" /* TRANSLATOR U2::LocalWorkflow::HMMLib */ namespace U2 { namespace LocalWorkflow { const QString HMMReader::ACTOR("hmm2-read-profile"); const QString HMMWriter::ACTOR("hmm2-write-profile"); static const QString HMM_OUT_PORT_ID("out-hmm2"); static const QString HMM_IN_PORT_ID("in-hmm2"); const QString HMMLib::HMM_PROFILE_TYPE_ID("hmm.profile"); DataTypePtr HMMLib::HMM_PROFILE_TYPE() { DataTypeRegistry* dtr = WorkflowEnv::getDataTypeRegistry(); assert(dtr); static bool startup = true; if (startup) { dtr->registerEntry(DataTypePtr(new DataType(HMM_PROFILE_TYPE_ID, tr("HMM Profile"), ""))); startup = false; } return dtr->getById(HMM_PROFILE_TYPE_ID); } const Descriptor HMMLib::HMM2_SLOT("hmm2-profile", HMMLib::tr("HMM Profile"), ""); const Descriptor HMMLib::HMM_CATEGORY() {return Descriptor("hmmer", tr("HMMER2 tools"), "");} HMMIOProto::HMMIOProto(const Descriptor& _desc, const QList& _ports, const QList& _attrs ) : IntegralBusActorPrototype(_desc, _ports, _attrs) { } bool HMMIOProto::isAcceptableDrop(const QMimeData * md, QVariantMap * params, const QString & urlAttrId ) const { if (md->hasUrls()) { QList urls = md->urls(); if (urls.size() == 1) { QString url = urls.at(0).toLocalFile(); QString ext = GUrlUtils::getUncompressedExtension(url); if (ext == HMMIO::HMM_EXT) { if (params) { params->insert(urlAttrId, url); } return true; } } } return false; } ReadHMMProto::ReadHMMProto(const Descriptor& _desc, const QList& _ports, const QList& _attrs ) : HMMIOProto( _desc, _ports, _attrs ) { attrs << new Attribute(BaseAttributes::URL_IN_ATTRIBUTE(), BaseTypes::STRING_TYPE(), true); QMap delegateMap; delegateMap[BaseAttributes::URL_IN_ATTRIBUTE().getId()] = new URLDelegate( HMMIO::getHMMFileFilter(), HMMIO::HMM_ID, true ); setEditor(new DelegateEditor(delegateMap)); setIconPath( ":/hmm2/images/hmmer_16.png" ); } bool ReadHMMProto::isAcceptableDrop(const QMimeData * md, QVariantMap * params ) const { return HMMIOProto::isAcceptableDrop( md, params, BaseAttributes::URL_IN_ATTRIBUTE().getId() ); } WriteHMMProto::WriteHMMProto(const Descriptor& _desc, const QList& _ports, const QList& _attrs ) : HMMIOProto( _desc, _ports, _attrs ) { attrs << new Attribute(BaseAttributes::URL_OUT_ATTRIBUTE(), BaseTypes::STRING_TYPE(), true ); attrs << new Attribute(BaseAttributes::FILE_MODE_ATTRIBUTE(), BaseTypes::NUM_TYPE(), false, SaveDoc_Roll); QMap delegateMap; delegateMap[BaseAttributes::URL_OUT_ATTRIBUTE().getId()] = new URLDelegate(HMMIO::getHMMFileFilter(), HMMIO::HMM_ID, false ); delegateMap[BaseAttributes::FILE_MODE_ATTRIBUTE().getId()] = new FileModeDelegate(false); setEditor(new DelegateEditor(delegateMap)); setIconPath( ":/hmm2/images/hmmer_16.png" ); setValidator(new ScreenedParamValidator(BaseAttributes::URL_OUT_ATTRIBUTE().getId(), ports.first()->getId(), BaseSlots::URL_SLOT().getId())); setPortValidator(HMM_IN_PORT_ID, new ScreenedSlotValidator(BaseSlots::URL_SLOT().getId())); } bool WriteHMMProto::isAcceptableDrop(const QMimeData * md, QVariantMap * params ) const { return HMMIOProto::isAcceptableDrop( md, params, BaseAttributes::URL_OUT_ATTRIBUTE().getId() ); } void HMMIOWorkerFactory::init() { ActorPrototypeRegistry* r = WorkflowEnv::getProtoRegistry(); assert(r); { Descriptor id(HMM_IN_PORT_ID, HMMLib::tr("HMM profile"), HMMLib::tr("Input HMM profile")); Descriptor ud(BaseSlots::URL_SLOT().getId(), HMMLib::tr("Location"), HMMLib::tr("Location hint for the target file.")); QMap m; m[ud] = BaseTypes::STRING_TYPE(); m[HMMLib::HMM2_SLOT] = HMMLib::HMM_PROFILE_TYPE(); DataTypePtr t(new MapDataType(Descriptor("write.hmm.content"), m)); QList p; QList a; p << new PortDescriptor(id, t, true /*input*/); Descriptor desc(HMMWriter::ACTOR, HMMLib::tr("Write HMM profile"), HMMLib::tr("Saves all input HMM profiles to specified location.")); IntegralBusActorPrototype* proto = new WriteHMMProto(desc, p, a); proto->setPrompter(new HMMWritePrompter()); r->registerProto(HMMLib::HMM_CATEGORY(), proto); } { Descriptor od(HMM_OUT_PORT_ID, HMMLib::tr("HMM profile"), HMMLib::tr("Loaded HMM profile")); QList p; QList a; QMap outM; outM[HMMLib::HMM2_SLOT] = HMMLib::HMM_PROFILE_TYPE(); p << new PortDescriptor(od, DataTypePtr(new MapDataType("hmm.read.out", outM)), false /*output*/, true); Descriptor desc(HMMReader::ACTOR, HMMLib::tr("Read HMM profile"), HMMLib::tr("Reads HMM profiles from file(s). The files can be local or Internet URLs.")); IntegralBusActorPrototype* proto = new ReadHMMProto(desc, p, a); proto->setPrompter(new HMMReadPrompter()); r->registerProto(HMMLib::HMM_CATEGORY(), proto); } DomainFactory* localDomain = WorkflowEnv::getDomainRegistry()->getById(LocalDomainFactory::ID); localDomain->registerEntry(new HMMIOWorkerFactory(HMMReader::ACTOR)); localDomain->registerEntry(new HMMIOWorkerFactory(HMMWriter::ACTOR)); } QString HMMReadPrompter::composeRichDoc() { return tr("Read HMM profile(s) from %1").arg(getHyperlink(BaseAttributes::URL_IN_ATTRIBUTE().getId(), getURL(BaseAttributes::URL_IN_ATTRIBUTE().getId()))); } QString HMMWritePrompter::composeRichDoc() { IntegralBusPort* input = qobject_cast(target->getPort(HMM_IN_PORT_ID)); Actor* producer = input->getProducer(HMMLib::HMM2_SLOT.getId()); QString unsetStr = ""+tr("unset")+""; QString producerStr = producer ? producer->getLabel() : unsetStr; QString url = getScreenedURL(input, BaseAttributes::URL_OUT_ATTRIBUTE().getId(), BaseSlots::URL_SLOT().getId()); url = getHyperlink(BaseAttributes::URL_OUT_ATTRIBUTE().getId(), url); QString doc = tr("Save HMM profile(s) from %1 to %2.") .arg(producerStr) .arg(url); return doc; } void HMMIOWorkerFactory::cleanup() { DomainFactory* ld = WorkflowEnv::getDomainRegistry()->getById(LocalDomainFactory::ID); DomainFactory* f = ld->unregisterEntry(HMMReader::ACTOR); delete f; f = ld->unregisterEntry(HMMWriter::ACTOR); delete f; ActorPrototypeRegistry* r = WorkflowEnv::getProtoRegistry(); ActorPrototype* p = r->unregisterProto(HMMReader::ACTOR); assert(p); delete p; p = r->unregisterProto(HMMWriter::ACTOR); assert(p); delete p; } Worker* HMMIOWorkerFactory::createWorker(Actor* a) { BaseWorker* w = NULL; if (HMMReader::ACTOR == a->getProto()->getId()) { w = new HMMReader(a); } else if (HMMWriter::ACTOR == a->getProto()->getId()) { w = new HMMWriter(a); } return w; } void HMMReader::init() { output = ports.value(HMM_OUT_PORT_ID); urls = WorkflowUtils::expandToUrls(actor->getParameter(BaseAttributes::URL_IN_ATTRIBUTE().getId())->getAttributeValue()); } Task* HMMReader::tick() { Task* t = new HMMReadTask(urls.takeFirst()); connect(t, SIGNAL(si_stateChanged()), SLOT(sl_taskFinished())); return t; } void HMMReader::sl_taskFinished() { HMMReadTask* t = qobject_cast(sender()); if (t->getState() != Task::State_Finished) return; if (output) { if (!t->hasError()) { QVariant v = qVariantFromValue(t->getHMM()); output->put(Message(HMMLib::HMM_PROFILE_TYPE(), v)); } if (urls.isEmpty()) { output->setEnded(); } ioLog.info(tr("Loaded HMM profile from %1").arg(t->getURL())); } } void HMMWriter::init() { input = ports.value(HMM_IN_PORT_ID); } Task* HMMWriter::tick() { Message inputMessage = getMessageAndSetupScriptValues(input); url = actor->getParameter(BaseAttributes::URL_OUT_ATTRIBUTE().getId())->getAttributeValue(); fileMode = actor->getParameter(BaseAttributes::FILE_MODE_ATTRIBUTE().getId())->getAttributeValue(); QVariantMap data = inputMessage.getData().toMap(); plan7_s* hmm = data.value(HMMLib::HMM2_SLOT.getId()).value(); QString anUrl = url; if (anUrl.isEmpty()) { anUrl = data.value(BaseSlots::URL_SLOT().getId()).toString(); } if (anUrl.isEmpty() || hmm == NULL) { QString err = (hmm == NULL) ? tr("Empty HMM passed for writing to %1").arg(anUrl) : tr("Unspecified URL for writing HMM"); //if (failFast) { return new FailTask(err); /*} else { ioLog.error(err); return NULL; }*/ } assert(!anUrl.isEmpty()); int count = ++counter[anUrl]; if (count != 1) { anUrl = GUrlUtils::prepareFileName(anUrl, count, QStringList(HMMIO::HMM_EXT)); } else { anUrl = GUrlUtils::ensureFileExt( anUrl, QStringList(HMMIO::HMM_EXT)).getURLString(); } ioLog.info(tr("Writing HMM profile to %1").arg(anUrl)); return new HMMWriteTask(anUrl, hmm, fileMode); } void HMMLib::init() { HMMIOWorkerFactory::init(); HMMBuildWorkerFactory::init(); HMMSearchWorkerFactory::init(); } void HMMLib::cleanup() { //FIXME need locking //HMMIOWorkerFactory::cleanup(); //HMMBuildWorkerFactory::cleanup(); //HMMSearchWorkerFactory::cleanup(); //DataTypeRegistry* dr = WorkflowEnv::getDataTypeRegistry(); //dr->unregisterEntry(HMM_PROFILE_TYPE->getId()); } } //namespace LocalWorkflow } //namespace U2 ugene-1.9.8/src/plugins_3rdparty/hmm2/src/u_spu/0000755000175000017500000000000011651544312020201 5ustar ilyailyaugene-1.9.8/src/plugins_3rdparty/hmm2/src/u_spu/hmmer_spu.h0000644000175000017500000001564211651544327022367 0ustar ilyailya/***************************************************************** * Unipro UGENE - Integrated Bioinformatics Suite * * This source code is distributed under the terms of the * GNU General Public License. See the files COPYING and LICENSE * for details. * * Author: Kursad Albayraktaroglu, Jizhu Li, Ivan Efremov *****************************************************************/ //Protection from automatically generated .pro files. //This variable is set in local, 'spu' makefile #ifdef UGENE_CELL_SPU #define TRACEBACK_UNCHECKED 0 #define TRACEBACK_NOT_NEEDED 1 #define TRACEBACK_NEEDED 2 #define TRACEBACK_DONE 3 #define INFTY 987654321 /* Matches the INFTY value defined in original HMMER code */ #define MAXCODE 24 /* Matches the (protein) MAXCODE in original HMMER code */ #define NO_MORE_SEQUENCES -1 #define WAIT_FOR_MORE_SEQUENCES -2 #define XMB 0 #define XME 1 #define XMC 2 #define XMJ 3 #define XMN 4 #define XTN 0 #define XTE 1 #define XTC 2 #define XTJ 3 #define TMM 0 #define TMI 1 #define TMD 2 #define TIM 3 #define TII 4 #define TDM 5 #define TDD 6 #define MOVE 0 #define LOOP 1 /* Data structure for holding HMM array offsets We need such a structure to hold all the offsets so we could send everything at once to the SPEs. 60 bytes total (15 ints) */ typedef struct { int M; unsigned int escmem_offset; unsigned int bscmem_offset; unsigned int mscmem_offset; unsigned int iscmem_offset; unsigned int xscmem_offset; unsigned int tscmem_offset; unsigned int tsc_TMM_mem_offset; unsigned int tsc_TMI_mem_offset; unsigned int tsc_TMD_mem_offset; unsigned int tsc_TIM_mem_offset; unsigned int tsc_TII_mem_offset; unsigned int tsc_TDM_mem_offset; unsigned int tsc_TDD_mem_offset; int bufferLength; } hmm_offsets; /* Data structure for specifying an SPE "job" This data structure is passed to the SPEs whenever they need a sequence to work on 128 bytes total */ typedef struct { unsigned char* seq_addr; /* Address of the initial sequence */ char* seq_name; /* Name of the initial sequence */ int seq_length; /* Length of the initial sequence */ int seq_dmalength; /* DMA len.of the initial sequence */ unsigned int bufferMutex_addr; /* Address of the buffer mutex */ unsigned int bufferEmptyCond_addr; /* "Buffer Empty" condition variable */ unsigned int lastConsumed_addr; /* Last consumed sequence number */ unsigned int lastProduced_addr; /* Last produced sequence number */ unsigned int buffer_length_addr; /* Address of the buffer context */ unsigned char* buffer_addr; /* Address of the sequence buffer */ unsigned int hmm_M; /* Length of the HMM in states(hmm->M)*/ unsigned int hmm_buf_begin; /* Address of the PPE HMM buffer */ unsigned int hmm_buf_length; /* Length of the PPE HMM buffer */ hmm_offsets offsets; /* HMM array offsets */ char padding[16]; /* Padding to a full cache line */ } spe_jobcontext; typedef struct { int M; /* Length of this HMM in states */ int* tsc[7]; /* transition scores [0..6][1..M-1] */ int* msc[MAXCODE]; /* M state emission probs. [0..MAXCODE-1][1..M] */ int* isc[MAXCODE]; /* I state emission probs. [0..MAXCODE-1][1..M-1] */ int xsc[4][2]; /* N,E,C,J transition scores */ int* bsc; /* B state transition probs. [1..M] */ int* esc; /* E state transition probs. [1..M] */ } spe_hmm; /* Data structure for an SPE "job entity" This data structure is passed to the SPEs whenever they need a sequence to work on 128 bytes total */ typedef struct { int seqNumber; unsigned int seqAddr; int seqLength; int seqDMALength; char seqProcessed; float seqViterbiResult; char seqTracebackStatus; unsigned int seqTraceAddr; char padding[94]; } spe_jobEntity; typedef struct { unsigned char* seq_addr; /* Address of the initial sequence */ char* seq_name; /* Name of the initial sequence */ int seq_length; /* Length of the initial sequence */ int seq_dmalength; /* DMA len.of the initial sequence */ unsigned int jobqueue_atomic_addr; /* Atomic variable for job queue entry number */ unsigned int jobqueue_begin_addr; /* Address of the job queue */ unsigned int jobqueue_num_seqs; /* Number of sequences in the job queue */ unsigned int bufferMutex_addr; /* Address of the buffer mutex */ unsigned int bufferEmptyCond_addr; /* "Buffer Empty" condition variable */ unsigned int bufferEntries_addr; /* Number of entries in the buffer */ unsigned int lastConsumed_addr; /* Last produced sequence number */ unsigned int nomoreSeqs_addr; /* "No more sequences" flag */ unsigned int hmm_M; /* Length of the HMM in states(hmm->M)*/ unsigned int hmm_buf_begin; /* Address of the PPE HMM buffer */ unsigned int hmm_buf_length; /* Length of the PPE HMM buffer */ hmm_offsets offsets; /* HMM array offsets */ char padding[8]; /* Padding to a full cache line */ } spe_initContext; float SPEViterbiSIMD( spe_hmm * hmm, char * seq, int L, int * mscoreCur, int * mscorePrev, int * iscoreCur, int * iscorePrev, int * dscoreCur, int * dscoreP ); void allocateSpeHMM( spe_hmm * hmm, unsigned long int bufr, hmm_offsets * offsets ); int getSequence(); #endif //UGENE_CELL_SPU ugene-1.9.8/src/plugins_3rdparty/hmm2/src/u_spu/hmmercell_spu.c0000644000175000017500000002702711651544327023222 0ustar ilyailya/***************************************************************** * Unipro UGENE - Integrated Bioinformatics Suite * * This source code is distributed under the terms of the * GNU General Public License. See the files COPYING and LICENSE * for details. * * Author: Kursad Albayraktaroglu, Jizhu Li, Ivan Efremov *****************************************************************/ //Protection from automatically generated .pro files. //This variable is set in local, 'spu' makefile #ifdef UGENE_CELL_SPU #include #include #include #include #include #include #include #include "hmmer_spu.h" #define SEQ_BUFFER_SIZE 10000 #define HMM_BUFFER_SIZE 150000 #define MAX_HMM 650 #define ARR_SIZE (MAX_HMM*4+12) atomic_ea_t lastConsumed __attribute__ ((aligned (128))); atomic_ea_t nomoreSeqs __attribute__ ((aligned (128))); atomic_ea_t bufferEntries __attribute__ ((aligned (128))); mutex_ea_t bufferMutex __attribute__ ((aligned (128))); cond_ea_t bufferEmptyCond __attribute__ ((aligned (128))); int mySPEID; struct dma_list_elem { union { unsigned int all32; struct { unsigned nbytes: 31; unsigned stall: 1; } bits; }size; unsigned int ea_low; }; struct dma_list_elem list[16] __attribute__((aligned (16))); void get_large_region(void* dst, unsigned int ea_low, unsigned int nbytes){ unsigned int i = 0; unsigned int tagid = 0; unsigned int listsize; if (!nbytes) return; while (nbytes > 0){ unsigned int sz; sz = (nbytes < 16384) ? nbytes : 16384; list[i].size.all32 = sz; list[i].ea_low = ea_low; nbytes -= sz; ea_low += sz; i++; } listsize = i*sizeof(struct dma_list_elem); spu_mfcdma32(dst,(unsigned int) &list[0], listsize, tagid, MFC_GETL_CMD); spu_writech(MFC_WrTagMask, 1 << tagid); (void) spu_mfcstat(2); } int main(addr64 spe_id, addr64 param) { unsigned int tag_id=0; /* DMA tag id */ int j,k; /* General purpose counters */ void* hmmAddr; /* Address for PPE HMM data buffer */ void* jobQueueBase; /* Address for the sequence job queue */ int hmmDMALength; /* Length of PPE HMM data */ volatile spe_initContext ctx __attribute__ ((aligned (128))); volatile unsigned char seqBuffer[2][SEQ_BUFFER_SIZE] __attribute__ ((aligned (128))); volatile unsigned char hmmBuffer[HMM_BUFFER_SIZE] __attribute__ ((aligned (128))) = {0}; volatile spe_jobEntity jobInfos[2] __attribute__ ((aligned (128))); /* These arrays assume a maximum HMM size of 512 states. (2060 = (512*4)+12) */ char mscCurMem[ARR_SIZE] __attribute__ ((aligned (128))) = {0}; char iscCurMem[ARR_SIZE] __attribute__ ((aligned (128))) = {0}; char dscCurMem[ARR_SIZE] __attribute__ ((aligned (128))) = {0}; char mscPrevMem[ARR_SIZE] __attribute__ ((aligned (128))) = {0}; char iscPrevMem[ARR_SIZE] __attribute__ ((aligned (128))) = {0}; char dscPrevMem[ARR_SIZE] __attribute__ ((aligned (128))) = {0}; int* mscCur = (int*) (mscCurMem + 0xC); int* iscCur = (int*) (iscCurMem + 0xC); int* dscCur = (int*) (dscCurMem + 0xC); int* mscPrev = (int*) (mscPrevMem + 0xC); int* iscPrev = (int*) (iscPrevMem + 0xC); int* dscPrev = (int*) (dscPrevMem + 0xC); spe_hmm hmmD; hmm_offsets offsetsD; spe_hmm* hmm; hmm_offsets* offsets; float viterbiScore; int entityDMAtag = 6; int entityDMAtag_back = 4; int next_idx, buf_idx = 0; unsigned int seqLength[2]; unsigned int seqAddress[2]; unsigned int entityAddress[2]; unsigned int seqDMALength[2]; memset( &hmmD, 0, sizeof(spe_hmm) ); memset( mscCurMem, 0, ARR_SIZE ); memset( iscCurMem, 0, ARR_SIZE ); memset( dscCurMem, 0, ARR_SIZE ); memset( mscPrevMem, 0, ARR_SIZE ); memset( iscPrevMem, 0, ARR_SIZE ); memset( dscPrevMem, 0, ARR_SIZE ); memset( &ctx, 0, sizeof(spe_initContext) ); memset( seqBuffer, 0, 2 * SEQ_BUFFER_SIZE ); memset( hmmBuffer, 0, HMM_BUFFER_SIZE ); memset( jobInfos, 0, 2 * sizeof(spe_jobEntity) ); /* Allocate SPE HMM and offset data structure buffers */ offsets = &offsetsD; hmm = &hmmD; /* The first thing an SPE thread does is DMA its job context information in. This data is a single 128-byte cache line and contains information about the first job, the HMM to be processed and so on. */ mySPEID = (int) spe_id.ui[1]; /* Initiate DMA for context */ spu_mfcdma32((void *)(&ctx),(unsigned int) param.ull,sizeof(spe_initContext),tag_id,MFC_GET_CMD); spu_writech(MFC_WrTagMask, 1< HMM_BUFFER_SIZE){ printf("Error: The size of this HMM(%d) exceeds the maximum buffer size(%d).\n", hmmDMALength, HMM_BUFFER_SIZE); return 0; }else{ // Transfer the HMM from the main memory to SPE LS. get_large_region((void*)hmmBuffer, (unsigned int)hmmAddr, (unsigned int)hmmDMALength); } // Set up the offsets to create SPE LS HMM profile data structure offsets->M = ctx.hmm_M; offsets->escmem_offset = ctx.offsets.escmem_offset; offsets->bscmem_offset = ctx.offsets.bscmem_offset; offsets->tscmem_offset = ctx.offsets.tscmem_offset; offsets->iscmem_offset = ctx.offsets.iscmem_offset; offsets->mscmem_offset = ctx.offsets.mscmem_offset; offsets->xscmem_offset = ctx.offsets.xscmem_offset; offsets->tsc_TMM_mem_offset = ctx.offsets.tsc_TMM_mem_offset; offsets->tsc_TMI_mem_offset = ctx.offsets.tsc_TMI_mem_offset; offsets->tsc_TMD_mem_offset = ctx.offsets.tsc_TMD_mem_offset; offsets->tsc_TIM_mem_offset = ctx.offsets.tsc_TIM_mem_offset; offsets->tsc_TII_mem_offset = ctx.offsets.tsc_TII_mem_offset; offsets->tsc_TDM_mem_offset = ctx.offsets.tsc_TDM_mem_offset; offsets->tsc_TDD_mem_offset = ctx.offsets.tsc_TDD_mem_offset; /* Allocate and populate the SPE HMM data structure*/ allocateSpeHMM (hmm,(unsigned long int)hmmBuffer,offsets); //Initiate the first sequence DMA k = getSequence(); if (k < 0) exit(0); entityAddress[buf_idx] = (unsigned int) jobQueueBase + (128 * k); spu_mfcdma32((void *)(&(jobInfos[buf_idx])),entityAddress[buf_idx], sizeof(spe_jobEntity),entityDMAtag,MFC_GET_CMD); spu_writech(MFC_WrTagMask, 1 << entityDMAtag); (void) spu_mfcstat(2); seqLength[buf_idx] = jobInfos[buf_idx].seqLength; seqAddress[buf_idx] = jobInfos[buf_idx].seqAddr; seqDMALength[buf_idx] = jobInfos[buf_idx].seqDMALength; spu_mfcdma32((void *)(seqBuffer[buf_idx]),seqAddress[buf_idx], seqDMALength[buf_idx], buf_idx, MFC_GET_CMD); // MAIN PROCESSING LOOP // Retrieve sequences into the buffer and process one by one. j=0; while(1){ // Read and increment the currently available sequence index. k = getSequence(); if (k < 0) { if (k == WAIT_FOR_MORE_SEQUENCES){ continue; } else { break; } } if (k > 0) { //DOUBLE-BUFFERED DMA OPERATION SEQUENCE // 1. Initiate and complete entity DMA transfer for the next iteration. next_idx = buf_idx ^ 1; entityAddress[next_idx] = (unsigned int) jobQueueBase + (128 * k); spu_mfcdma32((void *)(&(jobInfos[next_idx])),entityAddress[next_idx], sizeof(spe_jobEntity), entityDMAtag, MFC_GET_CMD); spu_writech(MFC_WrTagMask, 1 << entityDMAtag); (void) spu_mfcstat(2); seqLength[next_idx] = jobInfos[next_idx].seqLength; seqAddress[next_idx] = jobInfos[next_idx].seqAddr; seqDMALength[next_idx] = jobInfos[next_idx].seqDMALength; // 2. Initiate sequence DMA transfer for the next iteration. spu_mfcdma32((void *)(seqBuffer[next_idx]),seqAddress[next_idx], seqDMALength[next_idx],next_idx,MFC_GET_CMD); // 3. Wait for the last transfer to complete. spu_writech(MFC_WrTagMask, 1 << buf_idx); (void)spu_mfcstat(2); // 4. Use the data from the previous transfer viterbiScore = SPEViterbiSIMD(hmm,seqBuffer[buf_idx],seqLength[buf_idx],mscCur,mscPrev,iscCur,iscPrev,dscCur,dscPrev); j++; //DMA the result back to the PPE jobInfos[buf_idx].seqProcessed = 1; jobInfos[buf_idx].seqViterbiResult = viterbiScore; spu_mfcdma32((void *)(&(jobInfos[buf_idx])),entityAddress[buf_idx], sizeof(spe_jobEntity), entityDMAtag_back, MFC_PUT_CMD); //DMA it back... buf_idx = next_idx; } //if( k > 0 ) } //Process the final DMA spu_writech(MFC_WrTagMask, 1 << buf_idx); (void)spu_mfcstat(2); viterbiScore = SPEViterbiSIMD(hmm,seqBuffer[buf_idx],seqLength[buf_idx],mscCur,mscPrev,iscCur,iscPrev,dscCur,dscPrev); j++; //DMA the result back to the PPE jobInfos[buf_idx].seqProcessed = 1; jobInfos[buf_idx].seqViterbiResult = viterbiScore; spu_mfcdma32((void *)(&(jobInfos[buf_idx])),entityAddress[buf_idx], sizeof(spe_jobEntity), entityDMAtag_back, MFC_PUT_CMD); (void) spu_mfcstat(2); return 0; } int getSequence(){ int k; mutex_lock(bufferMutex); if (atomic_read(bufferEntries)){ //If we're here, we can fetch a sequence from the buffer. k = atomic_inc_return(lastConsumed); atomic_dec(bufferEntries); }else{ // There are no ready entries in the PPE buffer. This could happen in two situations: // 1) The SPEs have overtaken the PPE sequence file reading process. // 2) There are no sequences left to read. if (atomic_read(nomoreSeqs)==1){ //No more sequences to read. Exit. k = NO_MORE_SEQUENCES; } else { k = WAIT_FOR_MORE_SEQUENCES; //Wait until the PPE replenishes the buffer. cond_wait(bufferEmptyCond, bufferMutex); } } mutex_unlock(bufferMutex); return k; } #endif //UGENE_CELL_SPU ugene-1.9.8/src/plugins_3rdparty/hmm2/src/u_spu/hmmer_spu.c0000644000175000017500000003273411651544327022363 0ustar ilyailya/***************************************************************** * Unipro UGENE - Integrated Bioinformatics Suite * * This source code is distributed under the terms of the * GNU General Public License. See the files COPYING and LICENSE * for details. * * Author: Kursad Albayraktaroglu, Jizhu Li, Ivan Efremov *****************************************************************/ //Protection from automatically generated .pro files. //This variable is set in local, 'spu' makefile #ifdef UGENE_CELL_SPU #include "hmmer_spu.h" #include #include #include #include #define INTSCALE 1000.00 /****************************************************************** * allocateSpeHMM(spe_hmm, unsigned long int, hmm_offsets) * This function properly allocates an SPE-side HMM in the local * store and adjusts its pointers to point to the SPE buffer on * the local store, which holds the bulk HMM data transferred from * the PPE main memory. *******************************************************************/ void allocateSpeHMM( spe_hmm * hmm,unsigned long int hmmBuffer, hmm_offsets * offsets ) { int i,j,k; int M; unsigned long int escMem; unsigned long int bscMem; unsigned long int xscMem; unsigned long int tscMem; unsigned long int iscMem; unsigned long int mscMem; escMem = (unsigned long int) hmmBuffer + (unsigned long int) offsets->escmem_offset; bscMem = (unsigned long int) hmmBuffer + (unsigned long int) offsets->bscmem_offset; xscMem = (unsigned long int) hmmBuffer + (unsigned long int) offsets->xscmem_offset; mscMem = (unsigned long int) hmmBuffer + (unsigned long int) offsets->mscmem_offset; iscMem = (unsigned long int) hmmBuffer + (unsigned long int) offsets->iscmem_offset; tscMem = (unsigned long int) hmmBuffer + (unsigned long int) offsets->tscmem_offset; /* Set pointers correctly. */ /* Allocate pointers for an SPE HMM */ hmm->M = offsets->M; M = offsets->M; hmm->bsc = (int*) (((((unsigned long int) bscMem) + 15) & (~0xF)) + 12); hmm->esc = (int*) (((((unsigned long int) escMem) + 15) & (~0xF)) + 12); hmm->tsc[0] = (int*) (((((unsigned long int) tscMem) + 15) & (~0xF))); hmm->tsc[1] = (int*) (((((unsigned long int) tscMem) + (M+12) * sizeof(int)+ 15) & (~0xF)) + 12); hmm->tsc[2] = (int*) (((((unsigned long int) tscMem) + 2*(M+12)* sizeof(int)+ 15) & (~0xF))); hmm->tsc[3] = (int*) (((((unsigned long int) tscMem) + 3*(M+12)* sizeof(int)+ 15) & (~0xF))); hmm->tsc[4] = (int*) (((((unsigned long int) tscMem) + 4*(M+12)* sizeof(int)+ 15) & (~0xF)) + 12); hmm->tsc[5] = (int*) (((((unsigned long int) tscMem) + 5*(M+12)* sizeof(int)+ 15) & (~0xF))); hmm->tsc[6] = (int*) (((((unsigned long int) tscMem) + 6*(M+12)* sizeof(int)+ 15) & (~0xF))); for (i=0;imsc[i] = (int*) (((((unsigned long int) mscMem) + i*(M+1+12)*sizeof(int)+15) & (~0xF)) + 12); hmm->isc[i] = (int*) (((((unsigned long int) iscMem) + i*(M+12)*sizeof(int)+15) & (~0xF)) + 12); } k=0; for (i=0;i<4;i++) { for (j=0;j<2;j++,k++){ hmm->xsc[i][j] = *(((int*)xscMem)+k); } } for (i=1;i<8;i++) hmm->esc[M+i] = -INFTY; } void dumpSpeHMM (spe_hmm *hmm){ int i,j; int M; printf("--START SPE HMM DUMP (M=%d)\n", hmm->M); M = hmm->M; for (i=0;iESC[%d]=%d\n",i, hmm->esc[i]); } for (i=0;iBSC[%d]=%d\n",i, hmm->bsc[i]); } for (i=0;iMSC[%d][%d]=%d\n",i,j, hmm->msc[i][j]); } } for (i=0;i<4;i++){ for (j=0;j<2;j++){ printf("HMM->XSC[%d][%d]=%d\n",i,j, hmm->xsc[i][j]); } } for (i=0;i<7;i++){ for (j=0;jTSC[%d][%d]=%d\n",i,j, hmm->tsc[i][j]); } } for (i=0;iISC[%d][%d]=%d\n",i,j, hmm->isc[i][j]); } } printf("--END SPE HMM DUMP (M=%d)\n", hmm->M); } /************************************* * dumpSpeSEQ(char*, int) * * Dumps the contents of a sequence copied * to the SPE buffer. Used for debugging * purposes. *************************************/ void dumpSpeSEQ (char* seq, int L){ int i; for (i=0;ixsc[XTN][MOVE]); vector signed int xscPXMB = spu_splats(hmm->xsc[XTN][MOVE]); vector signed int hmmxscXTNLOOP = spu_splats(hmm->xsc[XTN][LOOP]); vector signed int hmmxscXTCMOVE = spu_splats(hmm->xsc[XTC][MOVE]); vector signed int hmmxscXTCLOOP = spu_splats(hmm->xsc[XTC][LOOP]); vector signed int hmmxscXTJMOVE = spu_splats(hmm->xsc[XTJ][MOVE]); vector signed int hmmxscXTJLOOP = spu_splats(hmm->xsc[XTJ][LOOP]); vector signed int hmmxscXTEMOVE = spu_splats(hmm->xsc[XTE][MOVE]); vector signed int hmmxscXTELOOP = spu_splats(hmm->xsc[XTE][LOOP]); vector signed int zeroVEC = {0, 0, 0, 0}; vector signed int INFTY_VEC = {-INFTY,-INFTY,-INFTY,-INFTY}; vector signed int xscCXME = INFTY_VEC, xscCXMC = INFTY_VEC, xscCXMJ = INFTY_VEC; vector signed int *hmmtscTII = (vector signed int*) (hmm->tsc[TII]+1); vector signed int *hmmtscTMM = (vector signed int*) hmm->tsc[TMM]; vector signed int *hmmtscTIM = (vector signed int*) hmm->tsc[TIM]; vector signed int *hmmtscTDM = (vector signed int*) hmm->tsc[TDM]; vector signed int *hmmtscTMI = (vector signed int*) (hmm->tsc[TMI]+1); vector signed int *hmmbsc = (vector signed int*) (hmm->bsc+1); vector signed int *hmmesc = (vector signed int*) (hmm->esc+1); vector signed int *mscCV = (vector signed int*) mscoreC+1; vector signed int *iscCV = (vector signed int*) iscoreC+1; vector signed int *dscCV = (vector signed int*) dscoreC+1; vector signed int *mscPV = (vector signed int*) mscoreP+1; vector signed int *iscPV = (vector signed int*) iscoreP+1; vector signed int *dscPV = (vector signed int*) dscoreP+1; vector signed int *Mdt = (vector signed int*) hmm->tsc[TMD]-1; vector signed int *mscDSQ, *iscDSQ, *tmpMV, *tmpIV, *tmpDV; vector unsigned int cmp1, cmp2, cmp3; vector unsigned char PMASK __attribute__ ((aligned (16))) = {28,29,30,31,0,1,2,3,4,5,6,7,8,9,10,11}; vector unsigned char D0MASK __attribute__ ((aligned (16))) = {0,1,2,3,4,5,6,7,24,25,26,27,28,29,30,31}; vector unsigned char D1MASK __attribute__ ((aligned (16))) = {0,1,2,3,16,17,18,19,16,17,18,19,16,17,18,19}; vector unsigned char D2MASK __attribute__ ((aligned (16))) = {0,1,2,3,4,5,6,7,20,21,22,23,20,21,22,23}; vector unsigned char D3MASK __attribute__ ((aligned (16))) = {0,1,2,3,4,5,6,7,8,9,10,11,24,25,26,27}; float result; int i, j, k, sc, M4th; int *tmpM, *tmpD, *hmmtscTDDip = hmm->tsc[TDD]; M4th = (hmm->M+3)>>2; for (k = 0; k <= M4th; k++){ mscPV[k] = INFTY_VEC; iscPV[k] = INFTY_VEC; dscPV[k] = INFTY_VEC; } for (i = 1; i <= L; i++){ xscCXME = INFTY_VEC; mscDSQ = (vector signed int*) hmm->msc[(int)seq[i]] +1; iscDSQ = (vector signed int*) hmm->isc[(int)seq[i]] +1; for (k = 1, j = 1; k <= M4th; j += 8, k += 2) { ipV = spu_shuffle(iscPV[k-1],iscPV[k-2],PMASK); ipV1 = spu_shuffle(iscPV[k], iscPV[k-1],PMASK); mpV = spu_shuffle(mscPV[k-1],mscPV[k-2],PMASK); mpV1 = spu_shuffle(mscPV[k], mscPV[k-1],PMASK); dpV = spu_shuffle(dscPV[k-1],dscPV[k-2],PMASK); dpV1 = spu_shuffle(dscPV[k], dscPV[k-1],PMASK); itV2 = spu_add(ipV, hmmtscTIM[k-1]); itV6 = spu_add(ipV1, hmmtscTIM[k]); itV1 = spu_add(mpV, hmmtscTMM[k-1]); itV5 = spu_add(mpV1, hmmtscTMM[k]); itV4 = spu_add(dpV, hmmtscTDM[k-1]); itV8 = spu_add(dpV1, hmmtscTDM[k]); itV3 = spu_add(xscPXMB, hmmbsc[k-1]); itV7 = spu_add(xscPXMB, hmmbsc[k]); cmp1 = spu_cmpgt(itV1, itV2); itV1 = spu_sel(itV2, itV1, cmp1); cmp2 = spu_cmpgt(itV3, itV4); dt4 = spu_insert(hmmtscTDDip[j+2], zeroVEC, 3); itV2 = spu_sel(itV4, itV3, cmp2); dt3 = spu_splats(hmmtscTDDip[j+1]); cmp1 = spu_cmpgt(itV1, itV2); dt3 = spu_add(dt3, dt4); itV3 = spu_sel(itV2,itV1,cmp1); cmp2 = spu_cmpgt(itV5, itV6); dt3 = spu_shuffle(zeroVEC, dt3, D0MASK); itV1 = spu_sel(itV6, itV5, cmp2); cmp1 = spu_cmpgt(itV7, itV8); dt2 = spu_splats(hmmtscTDDip[j]); itV2 = spu_sel(itV8, itV7, cmp1); dt2 = spu_add(dt2, dt3); cmp2 = spu_cmpgt(itV1, itV2); mscCV[k-1] = spu_add(itV3, mscDSQ[k-1]); itV4 = spu_sel(itV2,itV1,cmp2); dt2 = spu_insert(0, dt2, 0); mscCV[k] = spu_add(itV4, mscDSQ[k]); dt1 = spu_splats(hmmtscTDDip[j-1]); mpV = spu_shuffle(mscCV[k-1],mscCV[k-2],PMASK); dt1 = spu_add(dt1, dt2); mt1 = spu_add(mpV, Mdt[k]); dt = spu_splats(dscoreC[j-1]); mt2 = spu_shuffle(INFTY_VEC, mt1, D1MASK); dt1 = spu_add(dt, dt1); mt3 = spu_shuffle(INFTY_VEC, mt1, D2MASK); dt2 = spu_add(mt2, dt2); mt4 = spu_shuffle(INFTY_VEC, mt1, D3MASK); dt3 = spu_add(mt3, dt3); cmp1 = spu_cmpgt(dt1, mt1); dt4 = spu_add(mt4, dt4); cmp2 = spu_cmpgt(dt2, dt3); dt1 = spu_sel(mt1, dt1, cmp1); cmp3 = spu_cmpgt(dt1, dt4); dt2 = spu_sel(dt3, dt2, cmp2); dt1 = spu_sel(dt4, dt1, cmp3); cmp2 = spu_cmpgt(dt1, dt2); dt4 = spu_insert(hmmtscTDDip[j+6], zeroVEC, 3); dscCV[k-1] = spu_sel(dt2, dt1, cmp2); dt3 = spu_splats(hmmtscTDDip[j+5]); itV1 = spu_add(mscPV[k-1], hmmtscTMI[k-1]); dt3 = spu_add(dt3, dt4); dt3 = spu_shuffle(zeroVEC, dt3, D0MASK); dt2 = spu_splats(hmmtscTDDip[j+4]); itV2 = spu_add(iscPV[k-1], hmmtscTII[k-1]); dt2 = spu_add(dt2, dt3); dt1 = spu_splats(hmmtscTDDip[j+3]); dt2 = spu_insert(0, dt2, 0); cmp1 = spu_cmpgt(itV1, itV2); dt1 = spu_add(dt1, dt2); mpV = spu_shuffle(mscCV[k],mscCV[k-1],PMASK); mt1 = spu_add(mpV, Mdt[k+1]); dt = spu_splats(dscoreC[j+3]); itV3 = spu_sel(itV2, itV1, cmp1); dt1 = spu_add(dt, dt1); mt2 = spu_shuffle(INFTY_VEC, mt1, D1MASK); itV1 = spu_add(mscPV[k], hmmtscTMI[k]); dt2 = spu_add(mt2, dt2); mt3 = spu_shuffle(INFTY_VEC, mt1, D2MASK); itV2 = spu_add(iscPV[k], hmmtscTII[k]); dt3 = spu_add(mt3, dt3); mt4 = spu_shuffle(INFTY_VEC, mt1, D3MASK); cmp3 = spu_cmpgt(itV1, itV2); dt4 = spu_add(mt4, dt4); cmp1 = spu_cmpgt(dt1, mt1); itV4 = spu_sel(itV2, itV1, cmp3); cmp2 = spu_cmpgt(dt2, dt3); dt1 = spu_sel(mt1, dt1, cmp1); dt2 = spu_sel(dt3, dt2, cmp2); cmp1 = spu_cmpgt(dt1, dt4); dt1 = spu_sel(dt4, dt1, cmp1); cmp2 = spu_cmpgt(dt1, dt2); iscCV[k-1] = spu_add(itV3, iscDSQ[k-1]); dscCV[k] = spu_sel(dt2, dt1, cmp2); itV1 = spu_add(mscCV[k-1], hmmesc[k-1]); itV2 = spu_add(mscCV[k], hmmesc[k]); cmp1 = spu_cmpgt(itV1, xscCXME); cmp2 = spu_cmpgt(itV2, xscCXME); xscCXME = spu_sel(xscCXME, itV1, cmp1); iscCV[k] = spu_add(itV4, iscDSQ[k]); xscCXME = spu_sel(xscCXME, itV2, cmp2); } xscCXME = spu_splats(max_vec_int4(xscCXME)); itV2 = spu_add(xscCXMJ, hmmxscXTJLOOP); itV3 = spu_add(xscCXME, hmmxscXTELOOP); itV1 = spu_add(xscCXMJ, hmmxscXTJMOVE); cmp1 = spu_cmpgt(itV2, itV3); xscXTN = spu_add(xscXTN, hmmxscXTNLOOP); xscCXMJ = spu_sel(itV3, itV2, cmp1); itV2 = spu_add(xscCXMC, hmmxscXTCLOOP); cmp1 = spu_cmpgt(xscXTN, itV1); itV3 = spu_add(xscCXME, hmmxscXTEMOVE); xscPXMB = spu_sel(itV1, xscXTN, cmp1); cmp2 = spu_cmpgt(itV2, itV3); xscCXMC = spu_sel(itV3, itV2, cmp2); tmpMV = mscCV; tmpIV = iscCV; tmpDV = dscCV; mscCV = mscPV; iscCV = iscPV; dscCV = dscPV; mscPV = tmpMV; iscPV = tmpIV; dscPV = tmpDV; tmpM = mscoreC; tmpD = dscoreC; mscoreC = mscoreP; dscoreC = dscoreP; mscoreP = tmpM; dscoreP = tmpD; } itV1 = spu_add(xscCXMC, hmmxscXTCMOVE); sc = spu_extract(itV1, 0); result = (float) sc / INTSCALE; return result; } #endif //UGENE_CELL_SPU ugene-1.9.8/src/plugins_3rdparty/hmm2/src/uHMMPlugin.cpp0000644000175000017500000002237211651544326021552 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "uHMMPlugin.h" #include "hmmer2/funcs.h" #include "HMMIO.h" #include "TaskLocalStorage.h" #include "u_calibrate/HMMCalibrateDialogController.h" #include "u_build/HMMBuildDialogController.h" #include "u_search/HMMSearchDialogController.h" #include "u_tests/uhmmerTests.h" #include "HMMIOWorker.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include Q_DECLARE_METATYPE(QMenu*); namespace U2 { extern "C" Q_DECL_EXPORT Plugin* U2_PLUGIN_INIT_FUNC() { #ifdef HMMER_BUILD_WITH_SSE2 bool runningOnSSEProc = AppResourcePool::isSSE2Enabled(); if( !runningOnSSEProc ) { return 0; } #endif uHMMPlugin * plug = new uHMMPlugin(); return plug; } uHMMPlugin::uHMMPlugin() : Plugin(tr("uhmm_plugin"), tr("uhmm_plugin_desc")), ctxMSA(NULL), ctxADV(NULL) { if (AppContext::getMainWindow()) { QAction* buildAction = new QAction(tr("Build HMM2 profile"), this); connect(buildAction, SIGNAL(triggered()), SLOT(sl_build())); QAction* calibrateAction = new QAction(tr("Calibrate profile with HMM2"), this); connect(calibrateAction, SIGNAL(triggered()), SLOT(sl_calibrate())); QAction* searchAction = new QAction(tr("Search with HMM2"), this); connect(searchAction, SIGNAL(triggered()), SLOT(sl_search())); QMenu* toolsMenu = AppContext::getMainWindow()->getTopLevelMenu(MWMENU_TOOLS); QMenu * hmmMenu = toolsMenu->property("hmm_menu").value(); if(hmmMenu == NULL) { hmmMenu = toolsMenu->addMenu(QIcon(":/hmm2/images/hmmer_16.png"), tr("HMMER tools")); toolsMenu->setProperty("hmm_menu", qVariantFromValue(hmmMenu)); } QMenu* hmm2ToolsSub = hmmMenu->addMenu(QIcon(":/hmm2/images/hmmer_16.png"), tr("HMMER2 tools")); hmm2ToolsSub->addAction(buildAction); hmm2ToolsSub->addAction(calibrateAction); hmm2ToolsSub->addAction(searchAction); ctxMSA = new HMMMSAEditorContext(this); ctxMSA->init(); ctxADV = new HMMADVContext(this); ctxADV->init(); } LocalWorkflow::HMMLib::init(); //uHMMER Tests GTestFormatRegistry* tfr = AppContext::getTestFramework()->getTestFormatRegistry(); XMLTestFormat *xmlTestFormat = qobject_cast(tfr->findFormat("XML")); assert(xmlTestFormat!=NULL); GAutoDeleteList* l = new GAutoDeleteList(this); l->qlist = UHMMERTests::createTestFactories(); foreach(XMLTestFactory* f, l->qlist) { bool res = xmlTestFormat->registerTestFactory(f); assert(res); Q_UNUSED(res); } } uHMMPlugin::~uHMMPlugin() { LocalWorkflow::HMMLib::cleanup(); } void uHMMPlugin::sl_calibrate() { QWidget *p = (QWidget*)AppContext::getMainWindow()->getQMainWindow(); HMMCalibrateDialogController d(p); d.exec(); } void uHMMPlugin::sl_build() { MAlignment ma; //try to find alignment check that MSA Editor is active QString profileName; MWMDIWindow* w = AppContext::getMainWindow()->getMDIManager()->getActiveWindow(); if (w!=NULL) { GObjectViewWindow* ow = qobject_cast(w); if (ow!=NULL) { GObjectView* ov = ow->getObjectView(); MSAEditor* av = qobject_cast(ov); if (av!=NULL) { MAlignmentObject* maObj = av->getMSAObject(); if (maObj!=NULL) { ma = maObj->getMAlignment(); profileName = maObj->getGObjectName() == MA_OBJECT_NAME ? maObj->getDocument()->getName() : maObj->getGObjectName(); } } } } QWidget *p = (QWidget*)AppContext::getMainWindow()->getQMainWindow(); HMMBuildDialogController d(profileName, ma, p); d.exec(); } void uHMMPlugin::sl_search() { //to select a sequence //1. check that annotated DNA view is active //2. if not -> check that DNASequence object is selected in project view DNASequenceObject* obj = NULL; MWMDIWindow* w = AppContext::getMainWindow()->getMDIManager()->getActiveWindow(); if (w!=NULL) { GObjectViewWindow* ow = qobject_cast(w); if (ow!=NULL) { GObjectView* ov = ow->getObjectView(); AnnotatedDNAView* av = qobject_cast(ov); if (av!=NULL) { ADVSequenceObjectContext* seqCtx = av->getSequenceInFocus(); obj = seqCtx->getSequenceObject(); } } } if (obj == NULL) { ProjectView* pv = AppContext::getProjectView(); if (pv!=NULL) { const GObjectSelection* sel = pv->getGObjectSelection(); GObject* o = sel->getSelectedObjects().size() == 1 ? sel->getSelectedObjects().first() : NULL; obj = qobject_cast(o); } } QWidget *p = (QWidget*)AppContext::getMainWindow()->getQMainWindow(); if (obj == NULL) { QMessageBox::critical(p, tr("error"), tr("neither_annotatedview_nor_pv_selection_found")); return; } HMMSearchDialogController d(obj, p); d.exec(); } ////////////////////////////////////////////////////////////////////////// // contexts HMMMSAEditorContext::HMMMSAEditorContext(QObject* p) : GObjectViewWindowContext(p, MSAEditorFactory::ID) { } void HMMMSAEditorContext::initViewContext(GObjectView* view) { MSAEditor* msaed = qobject_cast(view); assert(msaed!=NULL); if (msaed->getMSAObject() == NULL) return; GObjectViewAction* a = new GObjectViewAction(this, view, tr("Build HMMER2 profile")); a->setIcon(QIcon(":/hmm2/images/hmmer_16.png")); connect(a, SIGNAL(triggered()), SLOT(sl_build())); addViewAction(a); } void HMMMSAEditorContext::buildMenu(GObjectView* v, QMenu* m) { MSAEditor* msaed = qobject_cast(v); assert( NULL != msaed && NULL != m ); if (msaed->getMSAObject() == NULL) return; QList list = getViewActions(v); assert(list.size()==1); GObjectViewAction* a = list.first(); QMenu* aMenu = GUIUtils::findSubMenu(m, MSAE_MENU_ADVANCED); assert(aMenu!=NULL); aMenu->addAction(a); } void HMMMSAEditorContext::sl_build() { GObjectViewAction* action = qobject_cast(sender()); assert(action!=NULL); MSAEditor* ed = qobject_cast(action->getObjectView()); assert(ed!=NULL); MAlignmentObject* obj = ed->getMSAObject(); if (obj) { QString profileName = obj->getGObjectName() == MA_OBJECT_NAME ? obj->getDocument()->getName() : obj->getGObjectName(); HMMBuildDialogController d(profileName, obj->getMAlignment()); d.exec(); } } HMMADVContext::HMMADVContext(QObject* p) : GObjectViewWindowContext(p, ANNOTATED_DNA_VIEW_FACTORY_ID) { } void HMMADVContext::initViewContext(GObjectView* view) { AnnotatedDNAView* av = qobject_cast(view); ADVGlobalAction* a = new ADVGlobalAction(av, QIcon(":/hmm2/images/hmmer_16.png"), tr("Search with HMM model..."), 70); connect(a, SIGNAL(triggered()), SLOT(sl_search())); } void HMMADVContext::sl_search() { GObjectViewAction* action = qobject_cast(sender()); assert(action!=NULL); AnnotatedDNAView* av = qobject_cast(action->getObjectView()); assert(av!=NULL); QWidget *p; if (av->getWidget()){ p = av->getWidget(); }else{ p = (QWidget*)AppContext::getMainWindow()->getQMainWindow(); } ADVSequenceObjectContext* seqCtx = av->getSequenceInFocus(); if(seqCtx == NULL) { QMessageBox::critical(p, tr("error"), tr("no_sequence_found")); return; } HMMSearchDialogController d(seqCtx->getSequenceObject(), p); d.exec(); } }//namespace ugene-1.9.8/src/plugins_3rdparty/hmm2/src/u_build/0000755000175000017500000000000011651544311020470 5ustar ilyailyaugene-1.9.8/src/plugins_3rdparty/hmm2/src/u_build/HMMBuildDialogController.cpp0000644000175000017500000002556511651544326026004 0ustar ilyailya#include "HMMBuildDialogController.h" #include "TaskLocalStorage.h" #include #include #include #include #include #include #include #include #include #include #include #include #include namespace U2 { HMMBuildDialogController::HMMBuildDialogController(const QString& _pn, const MAlignment& _ma, QWidget* p) :QDialog(p), ma(_ma), profileName(_pn) { setupUi(this); if (!ma.isEmpty()) { msaFileButton->setHidden(true); msaFileEdit->setHidden(true); msaFileLabel->setHidden(true); } connect(msaFileButton, SIGNAL(clicked()), SLOT(sl_msaFileClicked())); connect(resultFileButton, SIGNAL(clicked()), SLOT(sl_resultFileClicked())); connect(okButton, SIGNAL(clicked()), SLOT(sl_okClicked())); task = NULL; } void HMMBuildDialogController::sl_msaFileClicked() { LastOpenDirHelper lod; lod.url = QFileDialog::getOpenFileName(this, tr("select_file_with_alignment"), lod, DialogUtils::prepareDocumentsFileFilterByObjType(GObjectTypes::MULTIPLE_ALIGNMENT, true)); if (lod.url.isEmpty()) { return; } msaFileEdit->setText(QFileInfo(lod.url).absoluteFilePath()); } void HMMBuildDialogController::sl_resultFileClicked() { LastOpenDirHelper lod(HMMIO::HMM_ID); lod.url = QFileDialog::getSaveFileName(this, tr("Select file with HMM profile"), lod, HMMIO::getHMMFileFilter()); if (lod.url.isEmpty()) { return; } resultFileEdit->setText(QFileInfo(lod.url).absoluteFilePath()); } void HMMBuildDialogController::sl_okClicked() { if (task != NULL) { accept(); //go to background return; } //prepare model UHMMBuildSettings s; s.name = profileName; QString errMsg; QString inFile = msaFileEdit->text(); if (ma.isEmpty() && (inFile.isEmpty() || !QFileInfo(inFile).exists())) { errMsg = tr("incorrect_ali_file"); msaFileEdit->setFocus(); } QString outFile = resultFileEdit->text(); if (outFile.isEmpty() && errMsg.isEmpty()) { errMsg = tr("incorrect_hmm_file"); resultFileEdit->setFocus(); } if (expertGroup->isChecked() && errMsg.isEmpty()) { s.name = nameEdit->text().trimmed(); s.strategy = P7_LS_CONFIG; if (hmmfsButton->isChecked()) { s.strategy = P7_FS_CONFIG; } else if (hmmsButton->isChecked()) { s.strategy = P7_BASE_CONFIG; } else if (hmmswButton->isChecked()) { s.strategy = P7_SW_CONFIG; } } if (!errMsg.isEmpty()) { QMessageBox::critical(this, tr("error"), errMsg); return; } task = ma.isEmpty() ? new HMMBuildToFileTask(inFile, outFile, s) : new HMMBuildToFileTask(ma, outFile, s); task->setReportingEnabled(true); connect(task, SIGNAL(si_stateChanged()), SLOT(sl_onStateChanged())); connect(task, SIGNAL(si_progressChanged()), SLOT(sl_onProgressChanged())); AppContext::getTaskScheduler()->registerTopLevelTask(task); statusLabel->setText(tr("starting_build_process")); //update buttons okButton->setText(tr("back_button")); cancelButton->setText(tr("cancel_button")); // new default behavior: hide dialog and use taskview to track the progress and results accept(); //go to background } void HMMBuildDialogController::reject() { if (task!=NULL) { task->cancel(); } QDialog::reject(); } void HMMBuildDialogController::sl_onStateChanged() { Task* t = qobject_cast(sender()); assert(task!=NULL); if (task!=t || t->getState() != Task::State_Finished) { return; } task->disconnect(this); const TaskStateInfo& si = task->getStateInfo(); if (si.hasError()) { statusLabel->setText(tr("build_finished_with_errors_%1").arg(si.getError())); } else if (task->isCanceled()) { statusLabel->setText(tr("build_canceled")); } else { statusLabel->setText(tr("build_finished_successfuly")); } okButton->setText(tr("ok_button")); cancelButton->setText(tr("close_button")); AppContext::getTaskScheduler()->disconnect(this); task = NULL; } void HMMBuildDialogController::sl_onProgressChanged() { assert(task==sender()); statusLabel->setText(tr("progress_%1%").arg(task->getProgress())); } ////////////////////////////////////////////////////////////////////////// // HMMBuildTask HMMBuildToFileTask::HMMBuildToFileTask(const QString& inFile, const QString& _outFile, const UHMMBuildSettings& s) : Task("", TaskFlag_ReportingIsSupported), settings(s), outFile(_outFile), loadTask(NULL), buildTask(NULL) { setTaskName(tr("Build HMM profile '%1' -> '%2'").arg(QFileInfo(inFile).fileName()).arg(QFileInfo(outFile).fileName())); setVerboseLogMode(true); assert(!(inFile.isEmpty() || outFile.isEmpty())); //todo: support all formats with alignments! DocumentFormatConstraints c; c.checkRawData = true; c.supportedObjectTypes += GObjectTypes::MULTIPLE_ALIGNMENT; c.rawData = BaseIOAdapters::readFileHeader(inFile); QList formats = AppContext::getDocumentFormatRegistry()->selectFormats(c); if (formats.isEmpty()) { stateInfo.setError( tr("input_format_error") ); return; } DocumentFormatId alnFormat = formats.first(); loadTask = new LoadDocumentTask(alnFormat, inFile, AppContext::getIOAdapterRegistry()->getIOAdapterFactoryById(BaseIOAdapters::url2io(inFile)), QVariantMap()); addSubTask(loadTask); } HMMBuildToFileTask::HMMBuildToFileTask(const MAlignment& _ma, const QString& _outFile, const UHMMBuildSettings& s) : Task("", TaskFlags_FOSCOE | TaskFlag_ReportingIsSupported), settings(s), outFile(_outFile), ma(_ma), loadTask(NULL), buildTask(NULL) { setTaskName(tr("Build HMM profile to '%1'").arg(QFileInfo(outFile).fileName())); setVerboseLogMode(true); assert(!(outFile.isEmpty() || ma.isEmpty())); if (settings.name.isEmpty()) { QFileInfo fi(outFile); settings.name = fi.baseName(); //FIXME temporary workaround } buildTask = new HMMBuildTask(settings, ma); addSubTask(buildTask); } QList HMMBuildToFileTask::onSubTaskFinished(Task* subTask) { QList res; if (hasError() || isCanceled()) { return res; } if (subTask == loadTask) { assert(ma.isEmpty()); Document* doc = loadTask->getDocument(); //assert(doc); if(!doc) { stateInfo.setError(tr("Incorrect input file")); return res; } QList list = doc->findGObjectByType(GObjectTypes::MULTIPLE_ALIGNMENT); if (list.isEmpty()) { stateInfo.setError( tr("alignment_object_not_found") ); } else { MAlignmentObject* msa = qobject_cast(list.first()); const MAlignment& ma = msa->getMAlignment(); if (settings.name.isEmpty()) { settings.name = msa->getGObjectName() == MA_OBJECT_NAME ? doc->getName() : msa->getGObjectName(); } buildTask = new HMMBuildTask(settings, ma); res.append(buildTask); } } return res; } void HMMBuildToFileTask::run() { TaskLocalData::createHMMContext(getTaskId(), true); _run(); TaskLocalData::freeHMMContext(getTaskId()); } void HMMBuildToFileTask::_run() { if (stateInfo.hasError()) { return; } assert(buildTask!=NULL); assert(buildTask->getState() == Task::State_Finished); if (buildTask->getStateInfo().hasError()) { stateInfo.setError( buildTask->getStateInfo().getError() ); return; } plan7_s* hmm = buildTask->getHMM(); assert(hmm!=NULL); IOAdapterFactory* iof; iof = AppContext::getIOAdapterRegistry()->getIOAdapterFactoryById(BaseIOAdapters::url2io(outFile)); //todo: write command line too! HMMIO::writeHMM2(iof, outFile, stateInfo, hmm); } QString HMMBuildToFileTask::generateReport() const { QString res; res+=""; res+=""; res+=""; if (hasError()) { res+=""; res+="
    " + tr("Source alignment") + "" + (loadTask == NULL ? settings.name : loadTask->getURL().getURLString()) + "
    " + tr("Profile name") + "" + settings.name + "
    " + tr("Task was not finished") + "
    "; return res; } res+="" + tr("Profile file") + "" + outFile + ""; res+="" + tr("Expert options") + ""; switch(settings.strategy) { case P7_BASE_CONFIG: res+= "-g"; break; case P7_LS_CONFIG: res+= tr("none"); break; case P7_FS_CONFIG: res+= "-f"; break; case P7_SW_CONFIG: res+= "-s"; break; } res+=""; res+=""; return res; } HMMBuildTask::HMMBuildTask(const UHMMBuildSettings& s, const MAlignment& _ma) : Task("", TaskFlag_None), ma(_ma), settings(s), hmm(NULL) { GCOUNTER( cvar, tvar, "HMMBuildTask" ); setTaskName(tr("Build HMM profile '%1'").arg(s.name)); } HMMBuildTask::~HMMBuildTask() { if (hmm!=NULL) { FreePlan7(hmm); } } void HMMBuildTask::run() { TaskLocalData::createHMMContext(getTaskId(), true); _run(); TaskLocalData::freeHMMContext(getTaskId()); } void HMMBuildTask::_run() { if (ma.getNumRows() == 0) { stateInfo.setError( tr("multiple_alignment_is_empty") ); return; } if (ma.getLength() == 0) { stateInfo.setError( tr("multiple_alignment_is_0_len") ); return; } //todo: check HMM for RAW alphabet! if (ma.getAlphabet()->isRaw()) { stateInfo.setError( tr("only_amino_and_nucl_alphabets_are_supported") ); return; } //everything ok here: fill msa msa_struct* msa = MSAAlloc(ma.getNumRows(), ma.getLength()); if (msa == NULL) { stateInfo.setError( tr("error_creating_msa") ); return; } for (int i=0; iaseq[i]); msa->aseq[i] = sre_strdup(seq.constData(), seq.size()); QByteArray name = row.getName().toAscii(); msa->sqname[i] = sre_strdup(name.constData(), name.size()); msa->wgt[i] = 1.0; // default weights } int atype = ma.getAlphabet()->isNucleic() ? hmmNUCLEIC :hmmAMINO; try { hmm = UHMMBuild::build(msa, atype, settings, stateInfo); } catch (HMMException e) { stateInfo.setError( e.error ); } assert(hmm!=NULL || stateInfo.hasError()); MSAFree(msa); } }//namespace ugene-1.9.8/src/plugins_3rdparty/hmm2/src/u_build/HMMBuildWorker.cpp0000644000175000017500000003044011651544326023776 0ustar ilyailya#include "HMMBuildWorker.h" #include "HMMIOWorker.h" #include "HMMBuildDialogController.h" #include "u_calibrate/HMMCalibrateTask.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include /* TRANSLATOR U2::LocalWorkflow::HMMBuildWorker */ namespace U2 { namespace LocalWorkflow { /****************************** * HMMBuildWorkerFactory ******************************/ const QString HMMBuildWorkerFactory::ACTOR("hmm2-build"); static const QString OUT_HMM_PORT_ID("out-hmm2"); static const QString MODE_ATTR("strategy"); static const QString NAME_ATTR("profile-name"); // int nsample; // number of random seqs to sample // int seed; // random number seed // int fixedlen; // fixed length, or 0 if unused // float lenmean; // mean of length distribution // float lensd; // std dev of length distribution static const QString CALIBRATE_ATTR("calibrate"); static const QString THREADS_ATTR("calibration-threads"); static const QString FIXEDLEN_ATTR("fix-samples-length"); static const QString LENMEAN_ATTR("mean-samples-length"); static const QString NUM_ATTR("samples-num"); static const QString LENDEV_ATTR("deviation"); static const QString SEED_ATTR("seed"); static const QString HMM_PROFILE_DEFAULT_NAME("hmm_profile"); static bool isDefaultCfg(PrompterBaseImpl* actor) { return int(P7_LS_CONFIG) == actor->getParameter(MODE_ATTR).toInt() && 5000 == actor->getParameter(NUM_ATTR).toInt() && 0 == actor->getParameter(SEED_ATTR).toInt() && 0 == actor->getParameter(FIXEDLEN_ATTR).toInt() && 325 == actor->getParameter(LENMEAN_ATTR).toInt() && double(200) == actor->getParameter(LENDEV_ATTR).toDouble(); } void HMMBuildWorkerFactory::init() { QList p; QList a; { Descriptor id(BasePorts::IN_MSA_PORT_ID(), HMMBuildWorker::tr("Input MSA"), HMMBuildWorker::tr("Input multiple sequence alignment for building statistical model.")); Descriptor od(OUT_HMM_PORT_ID, HMMBuildWorker::tr("HMM profile"), HMMBuildWorker::tr("Produced HMM profile")); QMap inM; inM[BaseSlots::MULTIPLE_ALIGNMENT_SLOT()] = BaseTypes::MULTIPLE_ALIGNMENT_TYPE(); p << new PortDescriptor(id, DataTypePtr(new MapDataType("hmm.build.in", inM)), true /*input*/); QMap outM; outM[HMMLib::HMM2_SLOT] = HMMLib::HMM_PROFILE_TYPE(); p << new PortDescriptor(od, DataTypePtr(new MapDataType("hmm.build", outM)), false /*input*/, true /*multi*/); } Descriptor mod(MODE_ATTR, HMMBuildWorker::tr("HMM strategy"), HMMBuildWorker::tr("Specifies kind of alignments you want to allow")); Descriptor nad(NAME_ATTR, HMMBuildWorker::tr("Profile name"), HMMBuildWorker::tr("Descriptive name of the HMM profile")); // int nsample; // number of random seqs to sample // int seed; // random number seed // int fixedlen; // fixed length, or 0 if unused // float lenmean; // mean of length distribution // float lensd; // std dev of length distribution Descriptor cad(CALIBRATE_ATTR, HMMBuildWorker::tr("Calibrate profile"), HMMBuildWorker::tr("Enables/disables optional profile calibration." "

    An empirical HMM calibration costs time but it only has to be done once per model, and can greatly increase the sensitivity of a database search.")); Descriptor td(THREADS_ATTR, HMMBuildWorker::tr("Parallel calibration"), HMMBuildWorker::tr("Number of parallel threads that the calibration will run in.")); Descriptor fid(FIXEDLEN_ATTR, HMMBuildWorker::tr("Fixed length of samples"), QApplication::translate("HMMCalibrateDialog", "fixed_tip", 0, QApplication::UnicodeUTF8)); Descriptor lmd(LENMEAN_ATTR, HMMBuildWorker::tr("Mean length of samples"), QApplication::translate("HMMCalibrateDialog", "mean_tip", 0, QApplication::UnicodeUTF8)); Descriptor nud(NUM_ATTR, HMMBuildWorker::tr("Number of samples"), QApplication::translate("HMMCalibrateDialog", "num_tip", 0, QApplication::UnicodeUTF8)); Descriptor ldd(LENDEV_ATTR, HMMBuildWorker::tr("Standard deviation"), QApplication::translate("HMMCalibrateDialog", "sd_tip", 0, QApplication::UnicodeUTF8)); Descriptor sed(SEED_ATTR, HMMBuildWorker::tr("Random seed"), QApplication::translate("HMMCalibrateDialog", "seed_tip", 0, QApplication::UnicodeUTF8)); // nsample = 5000; // fixedlen = 0; // lenmean = 325.; // lensd = 200.; // seed = (int) time ((time_t *) NULL); a << new Attribute(nad, BaseTypes::STRING_TYPE(), false, QVariant(HMM_PROFILE_DEFAULT_NAME)); a << new Attribute(cad, BaseTypes::BOOL_TYPE(), false, QVariant(true)); a << new Attribute(mod, BaseTypes::NUM_TYPE(), false, QVariant(int(P7_LS_CONFIG))); a << new Attribute(nud, BaseTypes::NUM_TYPE(), false, QVariant(5000)); a << new Attribute(sed, BaseTypes::NUM_TYPE(), false, QVariant(0)); a << new Attribute(fid, BaseTypes::NUM_TYPE(), false, QVariant(0)); a << new Attribute(lmd, BaseTypes::NUM_TYPE(), false, QVariant(325)); a << new Attribute(ldd, BaseTypes::NUM_TYPE(), false, QVariant(double(200))); a << new Attribute(td, BaseTypes::NUM_TYPE(), false, QVariant(1)); Descriptor desc(HMMBuildWorkerFactory::ACTOR, HMMBuildWorker::tr("HMM build"), HMMBuildWorker::tr("Builds a HMM profile from a multiple sequence alignment." "

    The HMM profile is a statistical model which captures position-specific information" " about how conserved each column of the alignment is, and which residues are likely.")); ActorPrototype* proto = new IntegralBusActorPrototype(desc, p, a); QMap delegates; { QVariantMap lenMap; lenMap["minimum"] = 0; lenMap["maximum"] = INT_MAX; delegates[FIXEDLEN_ATTR] = new SpinBoxDelegate(lenMap); } { QVariantMap numMap; numMap["minimum"] = 1; numMap["maximum"] = INT_MAX; delegates[NUM_ATTR] = new SpinBoxDelegate(numMap); } { QVariantMap m; m["minimum"] = 0; m["maximum"] = INT_MAX; delegates[SEED_ATTR] = new SpinBoxDelegate(m); } { QVariantMap m; m["minimum"] = 1; m["maximum"] = INT_MAX; delegates[LENMEAN_ATTR] = new SpinBoxDelegate(m); } { QVariantMap m; m["minimum"] = double(.01); m["maximum"] = double(1000000.00); m["decimals"] = 2; delegates[LENDEV_ATTR] = new DoubleSpinBoxDelegate(m); } { QVariantMap m; m["minimum"] = 1; m["maximum"] = 100; delegates[THREADS_ATTR] = new SpinBoxDelegate(m); } QVariantMap modeMap; modeMap["hmms"] = QVariant(P7_BASE_CONFIG); modeMap["hmmfs"] = QVariant(P7_FS_CONFIG); modeMap[QString("hmmls (%1)").arg(HMMBuildWorker::tr("Default"))] = QVariant(P7_LS_CONFIG); modeMap["hmmsw"] = QVariant(P7_SW_CONFIG); delegates[MODE_ATTR] = new ComboBoxDelegate(modeMap); proto->setEditor(new DelegateEditor(delegates)); proto->setIconPath( ":/hmm2/images/hmmer_16.png" ); proto->setPrompter(new HMMBuildPrompter()); WorkflowEnv::getProtoRegistry()->registerProto(HMMLib::HMM_CATEGORY(), proto); DomainFactory* localDomain = WorkflowEnv::getDomainRegistry()->getById(LocalDomainFactory::ID); localDomain->registerEntry(new HMMBuildWorkerFactory()); } void HMMBuildWorkerFactory::cleanup() { delete WorkflowEnv::getProtoRegistry()->unregisterProto(ACTOR); DomainFactory* localDomain = WorkflowEnv::getDomainRegistry()->getById(LocalDomainFactory::ID); delete localDomain->unregisterEntry(ACTOR); } /****************************** * HMMBuildPrompter ******************************/ QString HMMBuildPrompter::composeRichDoc() { IntegralBusPort* input = qobject_cast(target->getPort(BasePorts::IN_MSA_PORT_ID())); Actor* msaProducer = input->getProducer(BasePorts::IN_MSA_PORT_ID()); QString msaName = msaProducer ? tr("For each MSA from %1,").arg(msaProducer->getLabel()) : ""; QString calibrate; if (getParameter(CALIBRATE_ATTR).toBool()) { calibrate = tr(" and calibrate"); } QString cfg = isDefaultCfg(this) ? tr("default") : tr("custom"); QString doc = tr("%1 build%2 HMM profile using %3 settings.") .arg(msaName) .arg(calibrate) .arg(cfg); return doc; } /****************************** * HMMBuildWorker ******************************/ HMMBuildWorker::HMMBuildWorker(Actor* a) : BaseWorker(a), input(NULL), output(NULL), nextTick(NULL), calibrate(false) { } void HMMBuildWorker::init() { input = ports.value(BasePorts::IN_MSA_PORT_ID()); output = ports.value(OUT_HMM_PORT_ID); } bool HMMBuildWorker::isReady() { return nextTick || input->hasMessage(); } Task* HMMBuildWorker::tick() { if(calSettings.seed < 0){ algoLog.error(tr("Incorrect value for seed parameter")); return new FailTask(tr("Incorrect value for seed parameter")); } if(nextTick) { // calibrate task Task* t = nextTick; nextTick = NULL; connect(t, SIGNAL(si_stateChanged()), SLOT(sl_taskFinished())); return t; } else { // hmm build task Message inputMessage = getMessageAndSetupScriptValues(input); cfg.name = actor->getParameter(NAME_ATTR)->getAttributeValue(); if(cfg.name.isEmpty()){ cfg.name = HMM_PROFILE_DEFAULT_NAME; algoLog.details(tr("Schema name not specified. Using default value: '%1'").arg(cfg.name)); } cfg.strategy = HMMBuildStrategy(actor->getParameter(MODE_ATTR)->getAttributeValue()); calSettings.fixedlen = actor->getParameter(FIXEDLEN_ATTR)->getAttributeValue(); calSettings.lenmean = actor->getParameter(LENMEAN_ATTR)->getAttributeValue(); calSettings.nsample = actor->getParameter(NUM_ATTR)->getAttributeValue(); calSettings.lensd = (float)actor->getParameter(LENDEV_ATTR)->getAttributeValue(); calSettings.seed = actor->getParameter(SEED_ATTR)->getAttributeValue(); calSettings.nThreads = actor->getParameter(THREADS_ATTR)->getAttributeValue(); calibrate = actor->getParameter(CALIBRATE_ATTR)->getAttributeValue(); const MAlignment& ma = inputMessage.getData().toMap().value(BaseSlots::MULTIPLE_ALIGNMENT_SLOT().getId()).value(); Task* t = new HMMBuildTask(cfg, ma); connect(new TaskSignalMapper(t), SIGNAL(si_taskFinished(Task*)), SLOT(sl_taskFinished(Task*))); return t; } } void HMMBuildWorker::sl_taskFinished() { Task * t = qobject_cast(sender()); assert(t != NULL); if( t->getState() != Task::State_Finished ) { return; } sl_taskFinished(t); } void HMMBuildWorker::sl_taskFinished(Task* t) { HMMBuildTask* build = qobject_cast(t); plan7_s* hmm = NULL; if (build) { assert(!nextTick); hmm = build->getHMM(); if (calibrate) { if (calSettings.nThreads == 1) { nextTick = new HMMCalibrateTask(hmm, calSettings); } else { nextTick = new HMMCalibrateParallelTask(hmm, calSettings); } } else { // do not calibrate -> put hmm to output output->put(Message(HMMLib::HMM_PROFILE_TYPE(), qVariantFromValue(hmm))); } algoLog.info(tr("Built HMM profile")); } else { HMMCalibrateAbstractTask* calibrate = qobject_cast(sender()); assert(calibrate); hmm = calibrate->getHMM(); output->put(Message(HMMLib::HMM_PROFILE_TYPE(), qVariantFromValue(hmm))); algoLog.info(tr("Calibrated HMM profile")); } if (input->isEnded()) { output->setEnded(); } } bool HMMBuildWorker::isDone() { return !input || input->isEnded(); } void HMMBuildWorker::cleanup() { } } //namespace LocalWorkflow } //namespace U2 ugene-1.9.8/src/plugins_3rdparty/hmm2/src/u_build/uhmmbuild.cpp0000644000175000017500000004574511651544326023207 0ustar ilyailya#include "uhmmbuild.h" #include #include #include #include #include namespace U2 { static void maximum_entropy(struct alphabet_s* al, struct plan7_s *hmm, unsigned char **dsq, MSA *msa, float eff_nseq, struct p7prior_s *prior, struct p7trace_s **tr); // weighting strategy enum p7_weight { WGT_NONE, WGT_GSC, WGT_BLOSUM, WGT_PB, WGT_VORONOI, WGT_ME }; plan7_s* UHMMBuild::build(msa_struct* msa, int atype, const UHMMBuildSettings& s, TaskStateInfo& si) { p7_construction c_strategy = P7_MAP_CONSTRUCTION; // construction strategy choice p7_weight w_strategy = WGT_GSC; // weighting strategy float blosumlevel = 0.62; // BLOSUM frac id filtering level [0.62] float gapmax = 0.5; // max frac gaps in mat col for -k float archpri = 0.85; // "architecture" prior on model size float swentry = 0.5; // S/W aggregate entry probability float swexit = 0.5; // S/W aggregate exit probability int do_eff = TRUE; // TRUE to set an effective seq number int pbswitch = 1000; // nseq >= this, switchover to PB weights p7trace_s **trace = NULL; // fake tracebacks for aseq's plan7_s* hmm = NULL; //result //get HMMERTaskLocalData HMMERTaskLocalData *tld = getHMMERTaskLocalData(); alphabet_s &al = tld->al; assert(atype == hmmAMINO || atype == hmmNUCLEIC); SetAlphabet(atype); // Get alignment(s), build HMMs one at a time // Do some initialization the first time through. // This code must be delayed until after we've seen the // first alignment, because we have to see the alphabet type first //Set up Dirichlet priors p7prior_s *pri = P7DefaultPrior(); // Set up the null/random seq model float randomseq[MAXABET]; // null sequence model float p1; // null sequence model p1 transition P7DefaultNullModel(randomseq, &p1); // Prepare unaligned digitized sequences for internal use unsigned char **dsq; // digitized unaligned aseq's DigitizeAlignment(msa, &dsq); // In some respects we treat DNA more crudely for now; // for example, we can't do eff seq #, because it's // calibrated for protein. if (al.Alphabet_type == hmmNUCLEIC) { do_eff = FALSE; } // Determine "effective sequence number". // The BlosumWeights() routine is now an efficient O(N) // memory clustering algorithm that doesn't blow up on, // say, Pfam's GP120 alignment (13000+ sequences) float eff_nseq = (float) msa->nseq; if (do_eff) { QVector wgt(msa->nseq, 0); BlosumWeights(msa->aseq, msa->nseq, msa->alen, blosumlevel, wgt.data()); eff_nseq = FSum(wgt.data(), msa->nseq); } // Weight the sequences (optional), if (w_strategy == WGT_GSC || w_strategy == WGT_BLOSUM || w_strategy == WGT_VORONOI || w_strategy == WGT_PB) { if (w_strategy != WGT_PB && msa->nseq >= pbswitch) { PositionBasedWeights(msa->aseq, msa->nseq, msa->alen, msa->wgt); } else if (w_strategy == WGT_GSC) { GSCWeights(msa->aseq, msa->nseq, msa->alen, msa->wgt); } else if (w_strategy == WGT_BLOSUM) { BlosumWeights(msa->aseq, msa->nseq, msa->alen, blosumlevel, msa->wgt); } else if (w_strategy == WGT_PB) { PositionBasedWeights(msa->aseq, msa->nseq, msa->alen, msa->wgt); } else if (w_strategy == WGT_VORONOI) { VoronoiWeights(msa->aseq, msa->nseq, msa->alen, msa->wgt); } } //Set the effective sequence number (if do_eff is FALSE, eff_nseq was set to nseq). FNorm(msa->wgt, msa->nseq); FScale(msa->wgt, msa->nseq, eff_nseq); // Build a model architecture. // If we're not doing MD or ME, that's all we need to do. // We get an allocated, counts-based HMM back. // Because the architecture algorithms are allowed to change // gap characters in the alignment, we have to calculate the // alignment checksum before we enter the algorithms. int checksum = GCGMultchecksum(msa->aseq, msa->nseq); // checksum of the alignment if (c_strategy == P7_FAST_CONSTRUCTION) { P7Fastmodelmaker(msa, dsq, gapmax, &hmm, &trace); } else if (c_strategy == P7_HAND_CONSTRUCTION) { P7Handmodelmaker(msa, dsq, &hmm, &trace); } else { P7Maxmodelmaker(msa, dsq, gapmax, pri, randomseq, p1, archpri, &hmm, &trace); } hmm->checksum = checksum; hmm->atype = atype; // Record the null model in the HMM; // add prior contributions in pseudocounts and renormalize. Plan7SetNullModel(hmm, randomseq, p1); P7PriorifyHMM(hmm, pri); // Model configuration, temporary. // hmmbuild assumes that it's given an alignment of single domains, // and the alignment may contain fragments. So, for the purpose of // scoring the sequences (or, optionally, MD/ME weighting), // configure the model into hmmsw mode. Later we'll // configure the model according to how the user wants to // use it. Plan7SWConfig(hmm, 0.5, 0.5); // Do model-dependent "weighting" strategies. if (w_strategy == WGT_ME) { maximum_entropy(&al, hmm, dsq, msa, eff_nseq, pri, trace); } // Give the model a name. QString name = s.name; if (name.isEmpty()) { name = msa->name; } QByteArray nameArr = name.toAscii(); Plan7SetName(hmm, nameArr.constData()); // Transfer other information from the alignment to // the HMM. This typically only works for Stockholm or SELEX format // alignments, so these things are conditional/optional. if (msa->acc != NULL) Plan7SetAccession(hmm, msa->acc); if (msa->desc != NULL) Plan7SetDescription(hmm, msa->desc); if (msa->cutoff_is_set[MSA_CUTOFF_GA1] && msa->cutoff_is_set[MSA_CUTOFF_GA2]) { hmm->flags |= PLAN7_GA; hmm->ga1 = msa->cutoff[MSA_CUTOFF_GA1]; hmm->ga2 = msa->cutoff[MSA_CUTOFF_GA2]; } if (msa->cutoff_is_set[MSA_CUTOFF_TC1] && msa->cutoff_is_set[MSA_CUTOFF_TC2]) { hmm->flags |= PLAN7_TC; hmm->tc1 = msa->cutoff[MSA_CUTOFF_TC1]; hmm->tc2 = msa->cutoff[MSA_CUTOFF_TC2]; } if (msa->cutoff_is_set[MSA_CUTOFF_NC1] && msa->cutoff_is_set[MSA_CUTOFF_NC2]) { hmm->flags |= PLAN7_NC; hmm->nc1 = msa->cutoff[MSA_CUTOFF_NC1]; hmm->nc2 = msa->cutoff[MSA_CUTOFF_NC2]; } // Record some other miscellaneous information in the HMM, // like how/when we built it. Plan7SetCtime(hmm); hmm->nseq = msa->nseq; // Configure the model for chosen algorithm switch (s.strategy) { case P7_BASE_CONFIG: Plan7GlobalConfig(hmm); break; case P7_SW_CONFIG: Plan7SWConfig(hmm, swentry, swexit); break; case P7_LS_CONFIG: Plan7LSConfig(hmm); break; case P7_FS_CONFIG: Plan7FSConfig(hmm, swentry, swexit); break; default: si.setError( tr("bogus configuration choice") ); break; } // Clean up trace for (int idx = 0; idx < msa->nseq; idx++) { P7FreeTrace(trace[idx]); } free(trace); Free2DArray((void **) dsq, msa->nseq); P7FreePrior(pri); return hmm; } // Function: position_average_score() // Date: Wed Dec 31 09:36:35 1997 [StL] // // Purpose: Calculate scores from tracebacks, keeping them // in a position specific array. The final array // is normalized position-specifically too, according // to how many sequences contributed data to this // position. Used for compensating for sequence // fragments in ME and MD score optimization. // Very much ad hoc. // // Code related to (derived from) TraceScore(). // // Args: hmm - HMM structure, scores valid // dsq - digitized unaligned sequences // wgt - weights on the sequences // nseq - number of sequences // tr - array of nseq tracebacks that aligns each dsq to hmm // pernode - RETURN: [0]1..M array of position-specific avg scores // ret_avg - RETURN: overall average full-length, one-domain score // // Return: 1 on success, 0 on failure. // pernode is MallocOrDie'ed [0]1..M by CALLER and filled here. static void position_average_score(struct plan7_s* hmm, unsigned char **dsq, float *wgt, int nseq, struct p7trace_s **tr, float *pernode, float *ret_avg) { unsigned char sym; int pos; //position in seq int tpos; // position in trace/state sequence float *counts; //counts at each position float avg; // RETURN: average overall int k; // counter for model position int idx; // counter for sequence number // Allocations counts = (float*)MallocOrDie ((hmm->M+1) * sizeof(float)); FSet(pernode, hmm->M+1, 0.); FSet(counts, hmm->M+1, 0.); // Loop over traces, accumulate weighted scores per position for (idx = 0; idx < nseq; idx++) { for (tpos = 0; tpos < tr[idx]->tlen; tpos++) { pos = tr[idx]->pos[tpos]; sym = dsq[idx][tr[idx]->pos[tpos]]; k = tr[idx]->nodeidx[tpos]; // Counts: how many times did we use this model position 1..M?(weighted) if (tr[idx]->statetype[tpos] == STM || tr[idx]->statetype[tpos] == STD) { counts[k] += wgt[idx]; } // Emission scores. if (tr[idx]->statetype[tpos] == STM) { pernode[k] += wgt[idx] * Scorify(hmm->msc[sym][k]); } else if (tr[idx]->statetype[tpos] == STI) { pernode[k] += wgt[idx] * Scorify(hmm->isc[sym][k]); } // Transition scores. if (tr[idx]->statetype[tpos] == STM || tr[idx]->statetype[tpos] == STD || tr[idx]->statetype[tpos] == STI) { pernode[k] += wgt[idx] * Scorify(TransitionScoreLookup(hmm, tr[idx]->statetype[tpos], tr[idx]->nodeidx[tpos], tr[idx]->statetype[tpos+1],tr[idx]->nodeidx[tpos+1])); } } } // Divide accumulated scores by accumulated weighted counts avg = 0.; for (k = 1; k <= hmm->M; k++) { pernode[k] /= counts[k]; avg += pernode[k]; } free(counts); *ret_avg = avg; } // Function: frag_trace_score() // Date: SRE, Wed Dec 31 10:03:47 1997 [StL] // // Purpose: Allow MD/ME optimization to be used for alignments // that include fragments and multihits -- estimate a full-length // per-domain score. // // // // Return: "corrected" score. static float frag_trace_score(struct plan7_s *hmm, unsigned char *dsq, struct p7trace_s *tr, float *pernode, float expected) { float sc; // corrected score float fragexp; // expected score for a trace like this int tpos; // position in trace */ // get uncorrected score sc = P7TraceScore(hmm, dsq, tr); // calc expected score for trace like this fragexp = 0.; for (tpos = 0; tpos < tr->tlen; tpos++) { if (tr->statetype[tpos] == STM || tr->statetype[tpos] == STD) { fragexp += pernode[tr->nodeidx[tpos]]; } } // correct for multihits fragexp /= (float) TraceDomainNumber(tr); // extrapolate to full-length, one-hit score sc = sc * expected / fragexp; return sc; } // Function: maximum_entropy() // Date: SRE, Fri Jan 2 10:56:00 1998 [StL] // // Purpose: Optimizes a model according to maximum entropy weighting. // See Krogh and Mitchison (1995). // // [Actually, we do minimum relative entropy, rather than // maximum entropy. Same thing, though we refer to "ME" // weights and models. The optimization is a steepest // descents minimization of the relative entropy.] // // Expects to be called shortly after a Maxmodelmaker() // or Handmodelmaker(), so that both a new model architecture // (with MAP parameters) and fake tracebacks are available. // // Prints a summary of optimization progress to stdout. // // Args: hmm - model. allocated, set with initial MAP parameters. // dsq - dealigned digitized seqs the model is based on // ainfo - extra info for aseqs // nseq - number of aseqs // eff_nseq- effective sequence number; weights normalize up to this. // prior - prior distributions for parameterizing model // tr - array of fake traces for each sequence // // Return: (void) // hmm changed to an ME HMM // ainfo changed, contains ME weights static void maximum_entropy(struct alphabet_s* al, struct plan7_s *hmm, unsigned char **dsq, MSA *msa, float eff_nseq, struct p7prior_s *prior, struct p7trace_s **tr) { float *wgt; // current best set of ME weights float *new_wgt; // new set of ME weights to try float *sc; // log-odds score of each sequence float *grad; // gradient float epsilon; // steepness of descent float relative_entropy; // current best relative entropy float new_entropy; // relative entropy at new weights float last_new_entropy; // last new_entropy we calc'ed float use_epsilon; // current epsilon value in use int idx; // counter over sequences int i1, i2; // counters for iterations float converge_criterion; float minw, maxw; // min, max weight int posw, highw; // number of positive weights float mins, maxs, avgs; // min, max, avg score float *pernode; // expected score per node of HMM float expscore; // expected score of complete HMM int max_iter; // bulletproof against infinite loop bugs epsilon = 0.2; // works fine max_iter = 666; // Allocations sc = (float*)MallocOrDie(sizeof(float) * msa->nseq); wgt = (float*)MallocOrDie (sizeof(float) * msa->nseq); new_wgt = (float*)MallocOrDie (sizeof(float) * msa->nseq); grad = (float*)MallocOrDie (sizeof(float) * msa->nseq); pernode = (float*)MallocOrDie (sizeof(float) * (hmm->M+1)); // Initialization. Start with all weights == 1.0. // Find relative entropy and gradient. Plan7SWConfig(hmm, 0.5, 0.5); P7Logoddsify(hmm, TRUE); FSet(wgt, msa->nseq, 1.0); position_average_score(hmm, dsq, wgt, msa->nseq, tr, pernode,&expscore); for (idx = 0; idx < msa->nseq; idx++) sc[idx] = frag_trace_score(hmm, dsq[idx], tr[idx], pernode, expscore); relative_entropy = FSum(sc, msa->nseq) / (float) msa->nseq; for (idx = 0; idx < msa->nseq; idx++) grad[idx] = relative_entropy - sc[idx]; // Steepest descents optimization; // iterate until relative entropy converges. i1 = 0; while (++i1 < max_iter) { // Gradient gives us a line of steepest descents. // (Roughly speaking, anyway. We actually have a constraint // that weights are nonnegative and normalized, and the // gradient doesn't take these into account.) // Look along this line, a distance of epsilon * gradient: // if new point is better, accept; if new point is worse, // move back along the line by half the distance and re-evaluate. use_epsilon = epsilon; new_entropy = relative_entropy + 1.0; /* just ensure new > old */ i2 = 0; while (new_entropy > relative_entropy && ++i2 < max_iter) { last_new_entropy = new_entropy; // find a new point in weight space */ for (idx = 0; idx < msa->nseq; idx++) { new_wgt[idx] = wgt[idx] + use_epsilon * grad[idx]; if (new_wgt[idx] < 0.) new_wgt[idx] = 0.0; } FNorm(new_wgt, msa->nseq); FScale(new_wgt, msa->nseq, (float) msa->nseq); // Make new HMM using these weights ZeroPlan7(hmm); for (idx = 0; idx < msa->nseq; idx++) { P7TraceCount(hmm, dsq[idx], new_wgt[idx], tr[idx]); } P7PriorifyHMM(hmm, prior); // Evaluate new point Plan7SWConfig(hmm, 0.5, 0.5); P7Logoddsify(hmm, TRUE); position_average_score(hmm, dsq, new_wgt, msa->nseq, tr, pernode, &expscore); for (idx = 0; idx < msa->nseq; idx++) { sc[idx] = frag_trace_score(hmm, dsq[idx], tr[idx], pernode, expscore); } new_entropy = FDot(sc, new_wgt, msa->nseq) / (float) msa->nseq; use_epsilon /= 2.0; // Failsafe: we're not converging. Set epsilon to zero, // do one more round. if (use_epsilon < 1e-6) use_epsilon = 0.0; if (use_epsilon == 0.0) break; // Failsafe: avoid infinite loops. Sometimes the // new entropy converges without ever being better // than the previous point, probably as a result // of minor roundoff error if (last_new_entropy == new_entropy) break; } // Evaluate convergence before accepting the new weights; // then, accept the new point and evaluate the gradient there. converge_criterion = qAbs((relative_entropy-new_entropy)/relative_entropy); relative_entropy = new_entropy; FCopy(wgt, new_wgt, msa->nseq); for (idx = 0; idx < msa->nseq; idx++) { grad[idx] = relative_entropy - sc[idx]; } // Print some statistics about this iteration mins = maxs = avgs = sc[0]; minw = maxw = wgt[0]; posw = (wgt[0] > 0.0) ? 1 : 0; highw = (wgt[0] > 1.0) ? 1 : 0; for (idx = 1; idx < msa->nseq; idx++) { if (sc[idx] < mins) mins = sc[idx]; if (sc[idx] > maxs) maxs = sc[idx]; if (wgt[idx] < minw) minw = wgt[idx]; if (wgt[idx] > maxw) maxw = wgt[idx]; if (wgt[idx] > 0.0) posw++; if (wgt[idx] > 1.0) highw++; avgs += sc[idx]; } if (converge_criterion < 1e-5) break; } // Renormalize weights to sum to eff_nseq, and save. FNorm(wgt, msa->nseq); FScale(wgt, msa->nseq, (float) eff_nseq); FCopy(msa->wgt, wgt, msa->nseq); // Make final HMM using these adjusted weights */ ZeroPlan7(hmm); for (idx = 0; idx < msa->nseq; idx++) { P7TraceCount(hmm, dsq[idx], wgt[idx], tr[idx]); } P7PriorifyHMM(hmm, prior); // Cleanup and return free(pernode); free(new_wgt); free(grad); free(wgt); free(sc); } }//namespace ugene-1.9.8/src/plugins_3rdparty/hmm2/src/u_build/ui/0000755000175000017500000000000011651544311021105 5ustar ilyailyaugene-1.9.8/src/plugins_3rdparty/hmm2/src/u_build/ui/HMMBuildDialog.ui0000644000175000017500000002337011651544326024200 0ustar ilyailya HMMBuildDialog 0 0 461 269 hmmbuild_dialog_title msa_file_label ... result_hmm_label ... expert_options true false name_tip name_tip name_tip name name_tip name_tip name_tip default_hmmls_tip default_hmmls_tip default_hmmls_tip default_hmmls Qt::Horizontal 478 20 default_hmmls_tip default_hmmls_tip default_hmmls_tip true multi_domain_hmmfs_tip multi_domain_hmmfs_tip multi_domain_hmmfs_tip multi_domain_hmmfs Qt::Horizontal 222 20 multi_domain_hmmfs_tip multi_domain_hmmfs_tip multi_domain_hmmfs_tip single_global_hmms_tip single_global_hmms_tip single_global_hmms_tip single_global_hmms Qt::Horizontal 222 20 single_global_hmms_tip single_global_hmms_tip single_global_hmms_tip single_local_hmmsw_tip single_local_hmmsw single_local_hmmsw single_local_hmmsw Qt::Horizontal 222 20 single_local_hmmsw single_local_hmmsw single_local_hmmsw Qt::Vertical 20 21 Qt::Horizontal 40 20 ok_button close_button cancelButton clicked() HMMBuildDialog reject() 543 220 296 121 ugene-1.9.8/src/plugins_3rdparty/hmm2/src/u_build/HMMBuildDialogController.h0000644000175000017500000000333611651544326025441 0ustar ilyailya#ifndef _U2_HMMBUILD_DIALOG_CONTROLLER_H_ #define _U2_HMMBUILD_DIALOG_CONTROLLER_H_ #include "uhmmbuild.h" #include #include #include #include struct plan7_s; namespace U2 { class LoadDocumentTask; class HMMBuildDialogController : public QDialog, public Ui_HMMBuildDialog { Q_OBJECT public: HMMBuildDialogController(const QString& profileName, const MAlignment& ma, QWidget* p = NULL); public slots: void reject(); private slots: void sl_msaFileClicked(); void sl_resultFileClicked(); void sl_okClicked(); void sl_onStateChanged(); void sl_onProgressChanged(); private: MAlignment ma; QString profileName; Task* task; }; ////////////////////////////////////////////////////////////////////////// // tasks class HMMBuildTask: public Task { Q_OBJECT public: HMMBuildTask(const UHMMBuildSettings& s, const MAlignment& ma); ~HMMBuildTask(); void run(); void _run(); plan7_s* getHMM() const {return hmm;} private: MAlignment ma; UHMMBuildSettings settings; plan7_s* hmm; }; class HMMBuildToFileTask : public Task { Q_OBJECT public: HMMBuildToFileTask(const QString& inFile, const QString& outFile, const UHMMBuildSettings& s); HMMBuildToFileTask(const MAlignment& ma, const QString& outFile, const UHMMBuildSettings& s); virtual QList onSubTaskFinished(Task* subTask); QString generateReport() const; void run(); void _run(); private: UHMMBuildSettings settings; QString outFile; MAlignment ma; LoadDocumentTask* loadTask; HMMBuildTask* buildTask; }; }//namespace #endif ugene-1.9.8/src/plugins_3rdparty/hmm2/src/u_build/HMMBuildWorker.h0000644000175000017500000000234511651544326023446 0ustar ilyailya#ifndef _U2_HMM_BUILD_WORKER_H_ #define _U2_HMM_BUILD_WORKER_H_ #include #include #include "uhmmbuild.h" #include "u_calibrate/uhmmcalibrate.h" namespace U2 { namespace LocalWorkflow { class HMMBuildPrompter : public PrompterBase { Q_OBJECT public: HMMBuildPrompter(Actor* p = 0) : PrompterBase(p) {} protected: QString composeRichDoc(); }; class HMMBuildWorker : public BaseWorker { Q_OBJECT public: HMMBuildWorker(Actor* a); virtual void init(); virtual bool isReady(); virtual Task* tick(); virtual bool isDone(); virtual void cleanup(); private slots: void sl_taskFinished(Task*); void sl_taskFinished(); protected: CommunicationChannel *input, *output; UHMMBuildSettings cfg; UHMMCalibrateSettings calSettings; bool calibrate; Task* nextTick; }; class HMMBuildWorkerFactory : public DomainFactory { public: static const QString ACTOR; static void init(); static void cleanup(); HMMBuildWorkerFactory() : DomainFactory(ACTOR) {} virtual Worker* createWorker(Actor* a) {return new HMMBuildWorker(a);} }; } // Workflow namespace } // U2 namespace #endif ugene-1.9.8/src/plugins_3rdparty/hmm2/src/u_build/uhmmbuild.h0000644000175000017500000000136311651544326022640 0ustar ilyailya#ifndef _U2_UHMM_BUILD_H_ #define _U2_UHMM_BUILD_H_ struct plan7_s; struct msa_struct; #include #include namespace U2 { class TaskStateInfo; // algorithm configuration strategy enum HMMBuildStrategy { P7_BASE_CONFIG, // hmmbuild -g P7_LS_CONFIG, // hmmbuild P7_FS_CONFIG, // hmmbuild -f P7_SW_CONFIG // hmmbuild -s }; class UHMMBuildSettings { public: UHMMBuildSettings() : strategy(P7_LS_CONFIG){}; HMMBuildStrategy strategy; QString name; //name of the hmm }; class UHMMBuild : public QObject { Q_OBJECT public: static plan7_s* build(msa_struct* msa, int atype, const UHMMBuildSettings& s, TaskStateInfo& si); }; }//namespace #endif ugene-1.9.8/src/plugins_3rdparty/hmm2/src/TaskLocalStorage.h0000644000175000017500000000332711651544326022433 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _TASK_LOCAL_CONTEXT_ #define _TASK_LOCAL_CONTEXT_ #include #include #include #include namespace U2 { // this struct is stored in TLS struct ContextIdContainer { ContextIdContainer(qint64 id) : contextId(id){} qint64 contextId; }; class TaskLocalData { public: static HMMERTaskLocalData* current(); // initializes HMMContext for current thread static HMMERTaskLocalData* createHMMContext(qint64 contextId, bool bindThreadToContext); static void freeHMMContext(qint64 contextId); // binds to existing HMMContext static void bindToHMMContext(qint64 contextId); static qint64 detachFromHMMContext(); private: static QHash data; static QThreadStorage tls; static QMutex mutex; }; } //namespace #endif ugene-1.9.8/src/plugins_3rdparty/hmm2/src/hmmer2/0000755000175000017500000000000011651544311020237 5ustar ilyailyaugene-1.9.8/src/plugins_3rdparty/hmm2/src/hmmer2/plan7.cpp0000644000175000017500000007647411651544326022014 0ustar ilyailya/************************************************************ * HMMER - Biological sequence analysis with profile HMMs * Copyright (C) 1992-2003 Washington University School of Medicine * All Rights Reserved * * This source code is distributed under the terms of the * GNU General Public License. See the files COPYING and LICENSE * for details. ************************************************************/ /* plan7.c * SRE, Sat Nov 16 14:19:56 1996 * * Support for Plan 7 HMM data structure, plan7_s. */ #include "funcs.h" /* Functions: AllocPlan7(), AllocPlan7Shell(), AllocPlan7Body(), FreePlan7() * * Purpose: Allocate or free a Plan7 HMM structure. * Can either allocate all at one (AllocPlan7()) or * in two steps (AllocPlan7Shell(), AllocPlan7Body()). * The two step method is used in hmmio.c where we start * parsing the header of an HMM file but don't * see the size of the model 'til partway thru the header. */ struct plan7_s * AllocPlan7(int M) { struct plan7_s *hmm; hmm = AllocPlan7Shell(); AllocPlan7Body(hmm, M); return hmm; } struct plan7_s * AllocPlan7Shell(void) { struct plan7_s *hmm; hmm = (struct plan7_s *) MallocOrDie (sizeof(struct plan7_s)); hmm->M = 0; hmm->name = NULL; hmm->acc = NULL; hmm->desc = NULL; hmm->rf = NULL; hmm->cs = NULL; hmm->ca = NULL; hmm->comlog = NULL; hmm->nseq = 0; hmm->ctime = NULL; hmm->map = NULL; hmm->checksum = 0; hmm->tpri = NULL; hmm->mpri = NULL; hmm->ipri = NULL; hmm->ga1 = hmm->ga2 = 0.0; hmm->tc1 = hmm->tc2 = 0.0; hmm->nc1 = hmm->nc2 = 0.0; hmm->t = NULL; hmm->mat = NULL; hmm->ins = NULL; hmm->tsc = hmm->msc = hmm->isc = NULL; hmm->tsc_mem = hmm->msc_mem = hmm->isc_mem = NULL; hmm->begin = NULL; hmm->end = NULL; hmm->bsc = hmm->bsc_mem = NULL; hmm->esc = hmm->esc_mem = NULL; /* DNA translation is not enabled by default */ hmm->dnam = NULL; hmm->dnai = NULL; hmm->dna2 = -INFTY; hmm->dna4 = -INFTY; /* statistical parameters set to innocuous empty values */ hmm->mu = 0.; hmm->lambda = 0.; hmm->flags = 0; hmm->atype = 0; return hmm; } #ifndef ALTIVEC void AllocPlan7Body(struct plan7_s *hmm, int M) { int k, x; hmm->M = M; hmm->rf = (char*)MallocOrDie ((M+2) * sizeof(char)); hmm->cs = (char*)MallocOrDie ((M+2) * sizeof(char)); hmm->ca = (char*)MallocOrDie ((M+2) * sizeof(char)); hmm->map = (int*)MallocOrDie ((M+1) * sizeof(int)); hmm->t = (float**)MallocOrDie (M * sizeof(float *)); hmm->mat = (float**)MallocOrDie ((M+1) * sizeof(float *)); hmm->ins = (float**)MallocOrDie (M * sizeof(float *)); hmm->t[0] = (float*)MallocOrDie ((7*M) * sizeof(float)); hmm->mat[0] = (float*)MallocOrDie ((MAXABET*(M+1)) * sizeof(float)); hmm->ins[0] = (float*)MallocOrDie ((MAXABET*M) * sizeof(float)); hmm->tsc = (int**)MallocOrDie (7 * sizeof(int *)); hmm->msc = (int**)MallocOrDie (MAXCODE * sizeof(int *)); hmm->isc = (int**)MallocOrDie (MAXCODE * sizeof(int *)); hmm->tsc_mem = (int*)MallocOrDie ((7*M) * sizeof(int)); memset( hmm->tsc_mem, 0, (7*M) * sizeof(int) ); hmm->msc_mem = (int*)MallocOrDie ((MAXCODE*(M+1)) * sizeof(int)); memset( hmm->msc_mem, 0, (MAXCODE*(M+1)) * sizeof(int)); hmm->isc_mem = (int*)MallocOrDie ((MAXCODE*M) * sizeof(int)); memset( hmm->isc_mem, 0, (MAXCODE*M) * sizeof(int)); hmm->tsc[0] = hmm->tsc_mem; hmm->msc[0] = hmm->msc_mem; hmm->isc[0] = hmm->isc_mem; /* note allocation strategy for important 2D arrays -- trying * to keep locality as much as possible, cache efficiency etc. */ for (k = 1; k <= M; k++) { hmm->mat[k] = hmm->mat[0] + k * MAXABET; if (k < M) { hmm->ins[k] = hmm->ins[0] + k * MAXABET; hmm->t[k] = hmm->t[0] + k * 7; } } for (x = 1; x < MAXCODE; x++) { hmm->msc[x] = hmm->msc[0] + x * (M+1); hmm->isc[x] = hmm->isc[0] + x * M; } for (x = 0; x < 7; x++) hmm->tsc[x] = hmm->tsc[0] + x * M; /* tsc[x][0] is used as a boundary condition sometimes [Viterbi()], * so set to -inf always. */ for (x = 0; x < 7; x++) hmm->tsc[x][0] = -INFTY; hmm->begin = (float*)MallocOrDie ((M+1) * sizeof(float)); hmm->end = (float*)MallocOrDie ((M+1) * sizeof(float)); hmm->bsc_mem = (int*)MallocOrDie ((M+1) * sizeof(int)); memset( hmm->bsc_mem, 0, (M+1) * sizeof(int) ); hmm->esc_mem = (int*)MallocOrDie ((M+1) * sizeof(int)); memset( hmm->esc_mem, 0, (M+1) * sizeof(int) ); hmm->bsc = hmm->bsc_mem; hmm->esc = hmm->esc_mem; return; } #endif //ALTIVEC void FreePlan7(struct plan7_s *hmm) { if (hmm->name != NULL) free(hmm->name); if (hmm->acc != NULL) free(hmm->acc); if (hmm->desc != NULL) free(hmm->desc); if (hmm->rf != NULL) free(hmm->rf); if (hmm->cs != NULL) free(hmm->cs); if (hmm->ca != NULL) free(hmm->ca); if (hmm->comlog != NULL) free(hmm->comlog); if (hmm->ctime != NULL) free(hmm->ctime); if (hmm->map != NULL) free(hmm->map); if (hmm->tpri != NULL) free(hmm->tpri); if (hmm->mpri != NULL) free(hmm->mpri); if (hmm->ipri != NULL) free(hmm->ipri); if (hmm->bsc_mem != NULL) free(hmm->bsc_mem); if (hmm->begin != NULL) free(hmm->begin); if (hmm->esc_mem != NULL) free(hmm->esc_mem); if (hmm->end != NULL) free(hmm->end); if (hmm->msc_mem != NULL) free(hmm->msc_mem); if (hmm->isc_mem != NULL) free(hmm->isc_mem); if (hmm->tsc_mem != NULL) free(hmm->tsc_mem); if (hmm->mat != NULL) free(hmm->mat[0]); if (hmm->ins != NULL) free(hmm->ins[0]); if (hmm->t != NULL) free(hmm->t[0]); if (hmm->msc != NULL) free(hmm->msc); if (hmm->isc != NULL) free(hmm->isc); if (hmm->tsc != NULL) free(hmm->tsc); if (hmm->mat != NULL) free(hmm->mat); if (hmm->ins != NULL) free(hmm->ins); if (hmm->t != NULL) free(hmm->t); if (hmm->dnam != NULL) free(hmm->dnam); if (hmm->dnai != NULL) free(hmm->dnai); free(hmm); } /* Function: ZeroPlan7() * * Purpose: Zeros the counts/probabilities fields in a model. * Leaves null model untouched. */ void ZeroPlan7(struct plan7_s *hmm) { //get HMMERTaskLocalData HMMERTaskLocalData *tld = getHMMERTaskLocalData(); alphabet_s *al = &tld->al; int k; for (k = 1; k < hmm->M; k++) { FSet(hmm->t[k], 7, 0.); FSet(hmm->mat[k], al->Alphabet_size, 0.); FSet(hmm->ins[k], al->Alphabet_size, 0.); } FSet(hmm->mat[hmm->M], al->Alphabet_size, 0.); hmm->tbd1 = 0.; FSet(hmm->begin+1, hmm->M, 0.); FSet(hmm->end+1, hmm->M, 0.); for (k = 0; k < 4; k++) FSet(hmm->xt[k], 2, 0.); hmm->flags &= ~PLAN7_HASBITS; /* invalidates scores */ hmm->flags &= ~PLAN7_HASPROB; /* invalidates probabilities */ } /* Function: Plan7SetName() * * Purpose: Change the name of a Plan7 HMM. Convenience function. * * Note: Trailing whitespace and \n's are chopped. */ void Plan7SetName(struct plan7_s *hmm, const char *name) { if (hmm->name != NULL) free(hmm->name); hmm->name = Strdup(name); StringChop(hmm->name); } /* Function: Plan7SetAccession() * * Purpose: Change the accession number of a Plan7 HMM. Convenience function. * * Note: Trailing whitespace and \n's are chopped. */ void Plan7SetAccession(struct plan7_s *hmm, char *acc) { if (hmm->acc != NULL) free(hmm->acc); hmm->acc = Strdup(acc); StringChop(hmm->acc); hmm->flags |= PLAN7_ACC; } /* Function: Plan7SetDescription() * * Purpose: Change the description line of a Plan7 HMM. Convenience function. * * Note: Trailing whitespace and \n's are chopped. */ void Plan7SetDescription(struct plan7_s *hmm, char *desc) { if (hmm->desc != NULL) free(hmm->desc); hmm->desc = Strdup(desc); StringChop(hmm->desc); hmm->flags |= PLAN7_DESC; } /* Function: Plan7SetCtime() * Date: SRE, Wed Oct 29 11:53:19 1997 [TWA 721 over the Atlantic] * * Purpose: Set the ctime field in a new HMM to the current time. */ void Plan7SetCtime(struct plan7_s *hmm) { time_t date = time(NULL); if (hmm->ctime != NULL) free(hmm->ctime); hmm->ctime = (char*)MallocOrDie(26); ctime_r(&date, hmm->ctime); StringChop(hmm->ctime); } /* Function: Plan7SetNullModel() * * Purpose: Set the null model section of an HMM. * Convenience function. */ void Plan7SetNullModel(struct plan7_s *hmm, float null[MAXABET], float p1) { //get HMMERTaskLocalData HMMERTaskLocalData *tld = getHMMERTaskLocalData(); alphabet_s *al = &tld->al; int x; for (x = 0; x < al->Alphabet_size; x++) hmm->null[x] = null[x]; hmm->p1 = p1; } /* Function: P7Logoddsify() * * Purpose: Take an HMM with valid probabilities, and * fill in the integer log-odds score section of the model. * * Notes on log-odds scores: * type of parameter probability score * ----------------- ----------- ------ * any emission p_x log_2 p_x/null_x * N,J,C /assume/ p_x = null_x so /always/ score zero. * transition to emitters t_x log_2 t_x/p1 * (M,I; N,C; J) * NN and CC loops are often equal to p1, so usu. score zero. * C->T transition t_x log_2 t_x/p2 * often zero, usu. C->T = p2. * all other transitions t_x log_2 t_x * (no null model counterpart, so null prob is 1) * * Notes on entry/exit scores, B->M and M->E: * The probability form model includes delete states 1 and M. * these states are removed from a search form model to * prevent B->D...D->E->J->B mute cycles, which would complicate * dynamic programming algorithms. The data-independent * S/W B->M and M->E transitions are folded together with * data-dependent B->D...D->M and M->D...D->E paths. * * This process is referred to in the code as "wing folding" * or "wing retraction"... the analogy is to a swept-wing * fighter in landing vs. high speed flight configuration. * * Note on Viterbi vs. forward flag: * Wing retraction must take forward vs. Viterbi * into account. If forward, sum two paths; if Viterbi, take * max. I tried to slide this by as a sum, without * the flag, but Alex detected it as a bug, because you can * then find cases where the Viterbi score doesn't match * the P7TraceScore(). * * Args: hmm - the hmm to calculate scores in. * viterbi_mode - TRUE to fold wings in Viterbi configuration. * * Return: (void) * hmm scores are filled in. */ void P7Logoddsify(struct plan7_s *hmm, int viterbi_mode) { //get HMMERTaskLocalData HMMERTaskLocalData *tld = getHMMERTaskLocalData(); alphabet_s *al = &tld->al; int k; /* counter for model position */ int x; /* counter for symbols */ float accum; float tbm, tme; if (hmm->flags & PLAN7_HASBITS) return; /* Symbol emission scores */ for (k = 1; k <= hmm->M; k++) { /* match/insert emissions in main model */ for (x = 0; x < al->Alphabet_size; x++) { hmm->msc[x][k] = Prob2Score(hmm->mat[k][x], hmm->null[x]); if (k < hmm->M) hmm->isc[x][k] = Prob2Score(hmm->ins[k][x], hmm->null[x]); } /* degenerate match/insert emissions */ for (x = al->Alphabet_size; x < al->Alphabet_iupac; x++) { hmm->msc[x][k] = DegenerateSymbolScore(hmm->mat[k], hmm->null, x); if (k < hmm->M) hmm->isc[x][k] = DegenerateSymbolScore(hmm->ins[k], hmm->null, x); } } /* State transitions. * * A note on "folding" of D_1 and D_M. * These two delete states are folded out of search form models * in order to prevent null cycles in the dynamic programming * algorithms (see code below). However, we use their log transitions * when we save the model! So the following log transition probs * are used *only* in save files, *never* in search algorithms: * log (tbd1), D1 -> M2, D1 -> D2 * Mm-1 -> Dm, Dm-1 -> Dm * * In a search algorithm, these have to be interpreted as -INFTY * because their contributions are folded into bsc[] and esc[] * entry/exit scores. They can't be set to -INFTY here because * we need them in save files. */ for (k = 1; k < hmm->M; k++) { hmm->tsc[TMM][k] = Prob2Score(hmm->t[k][TMM], hmm->p1); hmm->tsc[TMI][k] = Prob2Score(hmm->t[k][TMI], hmm->p1); hmm->tsc[TMD][k] = Prob2Score(hmm->t[k][TMD], 1.0); hmm->tsc[TIM][k] = Prob2Score(hmm->t[k][TIM], hmm->p1); hmm->tsc[TII][k] = Prob2Score(hmm->t[k][TII], hmm->p1); hmm->tsc[TDM][k] = Prob2Score(hmm->t[k][TDM], hmm->p1); hmm->tsc[TDD][k] = Prob2Score(hmm->t[k][TDD], 1.0); } /* B->M entry transitions. Note how D_1 is folded out. * M1 is just B->M1 * M2 is sum (or max) of B->M2 and B->D1->M2 * M_k is sum (or max) of B->M_k and B->D1...D_k-1->M_k * These have to be done in log space, else you'll get * underflow errors; and we also have to watch for log(0). * A little sloppier than it probably has to be; historically, * doing in this in log space was in response to a bug report. */ accum = hmm->tbd1 > 0.0 ? log(hmm->tbd1) : -9999.; for (k = 1; k <= hmm->M; k++) { tbm = hmm->begin[k] > 0. ? log(hmm->begin[k]) : -9999.; /* B->M_k part */ /* B->D1...D_k-1->M_k part we get from accum*/ if (k > 1 && accum > -9999.) { if (hmm->t[k-1][TDM] > 0.0) { if (viterbi_mode) tbm = MAX(tbm, accum + log(hmm->t[k-1][TDM])); else tbm = LogSum(tbm, accum + log(hmm->t[k-1][TDM])); } accum = (hmm->t[k-1][TDD] > 0.0) ? accum + log(hmm->t[k-1][TDD]) : -9999.; } /* Convert from log_e to scaled integer log_2 odds. */ if (tbm > -9999.) hmm->bsc[k] = (int) floor(0.5 + INTSCALE * 1.44269504 * (tbm - log(hmm->p1))); else hmm->bsc[k] = -INFTY; } /* M->E exit transitions. Note how D_M is folded out. * M_M is 1 by definition * M_M-1 is sum of M_M-1->E and M_M-1->D_M->E, where D_M->E is 1 by definition * M_k is sum of M_k->E and M_k->D_k+1...D_M->E * Must be done in log space to avoid underflow errors. * A little sloppier than it probably has to be; historically, * doing in this in log space was in response to a bug report. */ hmm->esc[hmm->M] = 0; accum = 0.; for (k = hmm->M-1; k >= 1; k--) { tme = hmm->end[k] > 0. ? log(hmm->end[k]) : -9999.; if (accum > -9999.) { if (hmm->t[k][TMD] > 0.0) { if (viterbi_mode) tme = MAX(tme, accum + log(hmm->t[k][TMD])); else tme = LogSum(tme, accum + log(hmm->t[k][TMD])); } accum = (hmm->t[k][TDD] > 0.0) ? accum + log(hmm->t[k][TDD]) : -9999.; } /* convert from log_e to scaled integer log odds. */ hmm->esc[k] = (tme > -9999.) ? (int) floor(0.5 + INTSCALE * 1.44269504 * tme) : -INFTY; } /* special transitions */ hmm->xsc[XTN][LOOP] = Prob2Score(hmm->xt[XTN][LOOP], hmm->p1); hmm->xsc[XTN][MOVE] = Prob2Score(hmm->xt[XTN][MOVE], 1.0); hmm->xsc[XTE][LOOP] = Prob2Score(hmm->xt[XTE][LOOP], 1.0); hmm->xsc[XTE][MOVE] = Prob2Score(hmm->xt[XTE][MOVE], 1.0); hmm->xsc[XTC][LOOP] = Prob2Score(hmm->xt[XTC][LOOP], hmm->p1); hmm->xsc[XTC][MOVE] = Prob2Score(hmm->xt[XTC][MOVE], 1.-hmm->p1); hmm->xsc[XTJ][LOOP] = Prob2Score(hmm->xt[XTJ][LOOP], hmm->p1); hmm->xsc[XTJ][MOVE] = Prob2Score(hmm->xt[XTJ][MOVE], 1.0); hmm->flags |= PLAN7_HASBITS; /* raise the log-odds ready flag */ } /* Function: Plan7Renormalize() * * Purpose: Take an HMM in counts form, and renormalize * all of its probability vectors. Also enforces * Plan7 restrictions on nonexistent transitions. * * Args: hmm - the model to renormalize. * * Return: (void) * hmm is changed. */ void Plan7Renormalize(struct plan7_s *hmm) { //get HMMERTaskLocalData HMMERTaskLocalData *tld = getHMMERTaskLocalData(); alphabet_s *al = &tld->al; int k; /* counter for model position */ int st; /* counter for special states */ float d; /* denominator */ /* match emissions */ for (k = 1; k <= hmm->M; k++) FNorm(hmm->mat[k], al->Alphabet_size); /* insert emissions */ for (k = 1; k < hmm->M; k++) FNorm(hmm->ins[k], al->Alphabet_size); /* begin transitions */ d = FSum(hmm->begin+1, hmm->M) + hmm->tbd1; FScale(hmm->begin+1, hmm->M, 1./d); hmm->tbd1 /= d; /* main model transitions */ for (k = 1; k < hmm->M; k++) { d = FSum(hmm->t[k], 3) + hmm->end[k]; FScale(hmm->t[k], 3, 1./d); hmm->end[k] /= d; FNorm(hmm->t[k]+3, 2); /* insert */ FNorm(hmm->t[k]+5, 2); /* delete */ } /* null model emissions */ FNorm(hmm->null, al->Alphabet_size); /* special transitions */ for (st = 0; st < 4; st++) FNorm(hmm->xt[st], 2); /* enforce nonexistent transitions */ /* (is this necessary?) */ hmm->t[0][TDM] = hmm->t[0][TDD] = 0.0; hmm->flags &= ~PLAN7_HASBITS; /* clear the log-odds ready flag */ hmm->flags |= PLAN7_HASPROB; /* set the probabilities OK flag */ } /* Function: Plan7RenormalizeExits() * Date: SRE, Fri Aug 14 11:22:19 1998 [St. Louis] * * Purpose: Renormalize just the match state transitions; * for instance, after a Config() function has * modified the exit distribution. * * Args: hmm - hmm to renormalize * * Returns: void */ void Plan7RenormalizeExits(struct plan7_s *hmm) { int k; float d; for (k = 1; k < hmm->M; k++) { d = FSum(hmm->t[k], 3); FScale(hmm->t[k], 3, 1./(d + d*hmm->end[k])); } } /***************************************************************** * Plan7 configuration functions * The following few functions are the Plan7 equivalent of choosing * different alignment styles (fully local, fully global, global/local, * multihit, etc.) * * There is (at least) one constraint worth noting. * If you want per-domain scores to sum up to per-sequence scores, * then one of the following two sets of conditions must be met: * * 1) t(E->J) = 0 * e.g. no multidomain hits * * 2) t(N->N) = t(C->C) = t(J->J) = hmm->p1 * e.g. unmatching sequence scores zero, and * N->B first-model score is equal to J->B another-model score. * * These constraints are obeyed in the default Config() functions below, * but in the future (when HMM editing may be allowed) we'll have * to remember this. Non-equality of the summed domain scores and * the total sequence score is a really easy "red flag" for people to * notice and report as a bug, even if it may make probabilistic * sense not to meet either constraint for certain modeling problems. ***************************************************************** */ /* Function: Plan7NakedConfig() * * Purpose: Set the alignment-independent, algorithm-dependent parameters * of a Plan7 model so that no special states (N,C,J) emit anything: * one simple, full global pass through the model. * * Args: hmm - the plan7 model * * Return: (void) * The HMM is modified; algorithm dependent parameters are set. * Previous scores are invalidated if they existed. */ void Plan7NakedConfig(struct plan7_s *hmm) { hmm->xt[XTN][MOVE] = 1.; /* disallow N-terminal tail */ hmm->xt[XTN][LOOP] = 0.; hmm->xt[XTE][MOVE] = 1.; /* only 1 domain/sequence ("global" alignment) */ hmm->xt[XTE][LOOP] = 0.; hmm->xt[XTC][MOVE] = 1.; /* disallow C-terminal tail */ hmm->xt[XTC][LOOP] = 0.; hmm->xt[XTJ][MOVE] = 0.; /* J state unused */ hmm->xt[XTJ][LOOP] = 1.; FSet(hmm->begin+2, hmm->M-1, 0.); /* disallow internal entries. */ hmm->begin[1] = 1. - hmm->tbd1; FSet(hmm->end+1, hmm->M-1, 0.); /* disallow internal exits. */ hmm->end[hmm->M] = 1.; Plan7RenormalizeExits(hmm); hmm->flags &= ~PLAN7_HASBITS; /* reconfig invalidates log-odds scores */ } /* Function: Plan7GlobalConfig() * * Purpose: Set the alignment-independent, algorithm-dependent parameters * of a Plan7 model to global (Needleman/Wunsch) configuration. * * Like a non-looping hmmls, since we actually allow flanking * N and C terminal sequence. * * Args: hmm - the plan7 model * * Return: (void) * The HMM is modified; algorithm dependent parameters are set. * Previous scores are invalidated if they existed. */ void Plan7GlobalConfig(struct plan7_s *hmm) { hmm->xt[XTN][MOVE] = 1. - hmm->p1; /* allow N-terminal tail */ hmm->xt[XTN][LOOP] = hmm->p1; hmm->xt[XTE][MOVE] = 1.; /* only 1 domain/sequence ("global" alignment) */ hmm->xt[XTE][LOOP] = 0.; hmm->xt[XTC][MOVE] = 1. - hmm->p1; /* allow C-terminal tail */ hmm->xt[XTC][LOOP] = hmm->p1; hmm->xt[XTJ][MOVE] = 0.; /* J state unused */ hmm->xt[XTJ][LOOP] = 1.; FSet(hmm->begin+2, hmm->M-1, 0.); /* disallow internal entries. */ hmm->begin[1] = 1. - hmm->tbd1; FSet(hmm->end+1, hmm->M-1, 0.); /* disallow internal exits. */ hmm->end[hmm->M] = 1.; Plan7RenormalizeExits(hmm); hmm->flags &= ~PLAN7_HASBITS; /* reconfig invalidates log-odds scores */ } /* Function: Plan7LSConfig() * * Purpose: Set the alignment independent parameters of a Plan7 model * to hmmls (global in HMM, local in sequence) configuration. * * Args: hmm - the plan7 model * * Return: (void); * the HMM probabilities are modified. */ void Plan7LSConfig(struct plan7_s *hmm) { hmm->xt[XTN][MOVE] = 1.-hmm->p1; /* allow N-terminal tail */ hmm->xt[XTN][LOOP] = hmm->p1; hmm->xt[XTE][MOVE] = 0.5; /* expectation 2 domains/seq */ hmm->xt[XTE][LOOP] = 0.5; hmm->xt[XTC][MOVE] = 1.-hmm->p1; /* allow C-terminal tail */ hmm->xt[XTC][LOOP] = hmm->p1; hmm->xt[XTJ][MOVE] = 1.-hmm->p1; /* allow J junction state */ hmm->xt[XTJ][LOOP] = hmm->p1; FSet(hmm->begin+2, hmm->M-1, 0.); /* start at M1/D1 */ hmm->begin[1] = 1. - hmm->tbd1; FSet(hmm->end+1, hmm->M-1, 0.); /* end at M_m/D_m */ hmm->end[hmm->M] = 1.; Plan7RenormalizeExits(hmm); hmm->flags &= ~PLAN7_HASBITS; /* reconfig invalidates log-odds scores */ } /* Function: Plan7SWConfig() * * Purpose: Set the alignment independent parameters of * a Plan7 model to hmmsw (Smith/Waterman) configuration. * * Notes: entry/exit is asymmetric because of the left/right * nature of the HMM/profile. Entry probability is distributed * simply by assigning p_x = pentry / (M-1) to M-1 * internal match states. However, the same approach doesn't * lead to a flat distribution over exit points. Exit p's * must be corrected for the probability of a previous exit * from the model. Requiring a flat distribution over exit * points leads to an easily solved piece of algebra, giving: * p_1 = pexit / (M-1) * p_x = p_1 / (1 - (x-1) p_1) * * Args: hmm - the Plan7 model w/ data-dep prob's valid * pentry - probability of an internal entry somewhere; * will be evenly distributed over M-1 match states * pexit - probability of an internal exit somewhere; * will be distributed over M-1 match states. * * Return: (void) * HMM probabilities are modified. */ void Plan7SWConfig(struct plan7_s *hmm, float pentry, float pexit) { float basep; /* p1 for exits: the base p */ int k; /* counter over states */ /* Configure special states. */ hmm->xt[XTN][MOVE] = 1-hmm->p1; /* allow N-terminal tail */ hmm->xt[XTN][LOOP] = hmm->p1; hmm->xt[XTE][MOVE] = 1.; /* disallow jump state */ hmm->xt[XTE][LOOP] = 0.; hmm->xt[XTC][MOVE] = 1-hmm->p1; /* allow C-terminal tail */ hmm->xt[XTC][LOOP] = hmm->p1; hmm->xt[XTJ][MOVE] = 1.; /* J is unused */ hmm->xt[XTJ][LOOP] = 0.; /* Configure entry. */ hmm->begin[1] = (1. - pentry) * (1. - hmm->tbd1); FSet(hmm->begin+2, hmm->M-1, (pentry * (1.- hmm->tbd1)) / (float)(hmm->M-1)); /* Configure exit. */ hmm->end[hmm->M] = 1.0; basep = pexit / (float) (hmm->M-1); for (k = 1; k < hmm->M; k++) hmm->end[k] = basep / (1. - basep * (float) (k-1)); Plan7RenormalizeExits(hmm); hmm->flags &= ~PLAN7_HASBITS; /* reconfig invalidates log-odds scores */ } /* Function: Plan7FSConfig() * Date: SRE, Fri Jan 2 15:34:40 1998 [StL] * * Purpose: Set the alignment independent parameters of * a Plan7 model to hmmfs (multihit Smith/Waterman) configuration. * * See comments on Plan7SWConfig() for explanation of * how pentry and pexit are used. * * Args: hmm - the Plan7 model w/ data-dep prob's valid * pentry - probability of an internal entry somewhere; * will be evenly distributed over M-1 match states * pexit - probability of an internal exit somewhere; * will be distributed over M-1 match states. * * Return: (void) * HMM probabilities are modified. */ void Plan7FSConfig(struct plan7_s *hmm, float pentry, float pexit) { float basep; /* p1 for exits: the base p */ int k; /* counter over states */ /* Configure special states. */ hmm->xt[XTN][MOVE] = 1-hmm->p1; /* allow N-terminal tail */ hmm->xt[XTN][LOOP] = hmm->p1; hmm->xt[XTE][MOVE] = 0.5; /* allow loops / multihits */ hmm->xt[XTE][LOOP] = 0.5; hmm->xt[XTC][MOVE] = 1-hmm->p1; /* allow C-terminal tail */ hmm->xt[XTC][LOOP] = hmm->p1; hmm->xt[XTJ][MOVE] = 1.-hmm->p1; /* allow J junction between domains */ hmm->xt[XTJ][LOOP] = hmm->p1; /* Configure entry. */ hmm->begin[1] = (1. - pentry) * (1. - hmm->tbd1); FSet(hmm->begin+2, hmm->M-1, (pentry * (1.-hmm->tbd1)) / (float)(hmm->M-1)); /* Configure exit. */ hmm->end[hmm->M] = 1.0; basep = pexit / (float) (hmm->M-1); for (k = 1; k < hmm->M; k++) hmm->end[k] = basep / (1. - basep * (float) (k-1)); Plan7RenormalizeExits(hmm); hmm->flags &= ~PLAN7_HASBITS; /* reconfig invalidates log-odds scores */ } /* Function: DegenerateSymbolScore() * * Purpose: Given a sequence character x and an hmm emission probability * vector, calculate the log-odds (base 2) score of * the symbol. * * Easy if x is in the emission alphabet, but not so easy * is x is a degenerate symbol. The "correct" Bayesian * philosophy is to calculate score(X) by summing over * p(x) for all x in the degenerate symbol X to get P(X), * doing the same sum over the prior to get F(X), and * doing log_2 (P(X)/F(X)). This gives an X a zero score, * for instance. * * Though this is correct in a formal Bayesian sense -- * we have no information on the sequence, so we can't * say if it's random or model, so it scores zero -- * it sucks, big time, for scoring biological sequences. * Sequences with lots of X's score near zero, while * real sequences have average scores that are negative -- * so the X-laden sequences appear to be lifted out * of the noise of a full histogram of a database search. * Correct or not, this is highly undesirable. * * So therefore we calculated the expected score of * the degenerate symbol by summing over all x in X: * e_x log_2 (p(x)/f(x)) * where the expectation of x, e_x, is calculated from * the random model. * * Empirically, this works; it also has a wooly hand-waving * probabilistic justification that I'm happy enough about. * * Args: p - probabilities of normal symbols * null - null emission model * ambig - index of the degenerate character in Alphabet[] * * Return: the integer log odds score of x given the emission * vector and the null model, scaled up by INTSCALE. */ int DegenerateSymbolScore(float *p, float *null, int ambig) { int x; float numer = 0.; float denom = 0.; //get HMMERTaskLocalData HMMERTaskLocalData *tld = getHMMERTaskLocalData(); alphabet_s &al = tld->al; for (x = 0; x < al.Alphabet_size; x++) { if (al.Degenerate[ambig][x]) { numer += null[x] * sreLOG2(p[x] / null[x]); denom += null[x]; } } return (int) (INTSCALE * numer / denom); } /* Function: SetAutocuts() * Date: SRE, Thu Jun 8 08:19:46 2000 [TW721 over Ireland] * * Purpose: Set score thresholds using the GA, TC, or NC information * in an HMM. * * Args: thresh - score threshold structure. autocut must be set * properly (CUT_GA, CUT_NC, or CUT_TC). * hmm - HMM containing appropriate score cutoff info * * Returns: 1 on success. * 0 if HMM does not have the score cutoffs available -- caller * will have to decide on a fallback plan. * Has no effect (and returns success) if autocut is * CUT_NONE. */ int SetAutocuts(struct threshold_s *thresh, struct plan7_s *hmm) { if (thresh->autocut == CUT_GA) { if (! (hmm->flags & PLAN7_GA)) return 0; thresh->globT = hmm->ga1; thresh->domT = hmm->ga2; thresh->globE = thresh->domE = FLT_MAX; } else if (thresh->autocut == CUT_NC) { if (! (hmm->flags & PLAN7_NC)) return 0; thresh->globT = hmm->nc1; thresh->domT = hmm->nc2; thresh->globE = thresh->domE = FLT_MAX; } else if (thresh->autocut == CUT_TC) { if (! (hmm->flags & PLAN7_TC)) return 0; thresh->globT = hmm->tc1; thresh->domT = hmm->tc2; thresh->globE = thresh->domE = FLT_MAX; } return 1; } /* Function: Statetype() * * Purpose: Returns the state type in text. * Example: Statetype(S) = "S" */ const char * Statetype(char st) { switch (st) { case STS: return "S"; case STN: return "N"; case STB: return "B"; case STM: return "M"; case STD: return "D"; case STI: return "I"; case STE: return "E"; case STJ: return "J"; case STC: return "C"; case STT: return "T"; default: return "BOGUS"; } } ugene-1.9.8/src/plugins_3rdparty/hmm2/src/hmmer2/masks.cpp0000644000175000017500000001777511651544326022110 0ustar ilyailya/************************************************************ * HMMER - Biological sequence analysis with profile HMMs * Copyright (C) 1992-2003 Washington University School of Medicine * All Rights Reserved * * This source code is distributed under the terms of the * GNU General Public License. See the files COPYING and LICENSE * for details. ************************************************************/ /* masks.c * SRE, Tue Nov 18 10:12:28 1997 * * Sequence masking routines; corrections for biased composition * target sequences. * * The Claverie/States XNU code is not used by default because I * consider X'ing out sequence to be too black/white and too * aggressive, but it's available as an option. * * The Wooton/Federhen SEG code was studied, but deemed too * nonportable to include; it would've suffered the same drawback * as XNU. * * The TraceScoreCorrection() code is the default. * * CVS $Id: masks.c,v 1.16 2003/10/02 16:39:41 eddy Exp $ */ #include "funcs.h" #include #include #include /* The PAM120 score matrix, in HMMER's AMINO_ALPHABET alphabetic order */ static int xpam120[23][23] = { { 3, -3, 0, 0, -4, 1, -3, -1, -2, -3, -2, -1, 1, -1, -3, 1, 1, 0, -7, -4, 1, 0, 0 }, {-3, 9, -7, -7, -6, -4, -4, -3, -7, -7, -6, -5, -4, -7, -4, 0, -3, -3, -8, -1, -4, -6, 0 }, { 0, -7, 5, 3, -7, 0, 0, -3, -1, -5, -4, 2, -3, 1, -3, 0, -1, -3, -8, -5, 5, 3, 0 }, { 0, -7, 3, 5, -7, -1, -1, -3, -1, -4, -3, 1, -2, 2, -3, -1, -2, -3, -8, -5, 3, 5, 0 }, {-4, -6, -7, -7, 8, -5, -3, 0, -7, 0, -1, -4, -5, -6, -5, -3, -4, -3, -1, 4, -4, -5, 0 }, { 1, -4, 0, -1, -5, 5, -4, -4, -3, -5, -4, 0, -2, -3, -4, 1, -1, -2, -8, -6, 1, -1, 0 }, {-3, -4, 0, -1, -3, -4, 7, -4, -2, -3, -4, 2, -1, 3, 1, -2, -3, -3, -3, -1, 2, 2, 0 }, {-1, -3, -3, -3, 0, -4, -4, 6, -3, 1, 1, -2, -3, -3, -2, -2, 0, 3, -6, -2, -2, -2, 0 }, {-2, -7, -1, -1, -7, -3, -2, -3, 5, -4, 0, 1, -2, 0, 2, -1, -1, -4, -5, -5, 1, 0, 0 }, {-3, -7, -5, -4, 0, -5, -3, 1, -4, 5, 3, -4, -3, -2, -4, -4, -3, 1, -3, -2, -3, -2, 0 }, {-2, -6, -4, -3, -1, -4, -4, 1, 0, 3, 8, -3, -3, -1, -1, -2, -1, 1, -6, -4, -3, -1, 0 }, {-1, -5, 2, 1, -4, 0, 2, -2, 1, -4, -3, 4, -2, 0, -1, 1, 0, -3, -4, -2, 4, 1, 0 }, { 1, -4, -3, -2, -5, -2, -1, -3, -2, -3, -3, -2, 6, 0, -1, 1, -1, -2, -7, -6, -1, 0, 0 }, {-1, -7, 1, 2, -6, -3, 3, -3, 0, -2, -1, 0, 0, 6, 1, -2, -2, -3, -6, -5, 1, 5, 0 }, {-3, -4, -3, -3, -5, -4, 1, -2, 2, -4, -1, -1, -1, 1, 6, -1, -2, -3, 1, -5, -1, 0, 0 }, { 1, 0, 0, -1, -3, 1, -2, -2, -1, -4, -2, 1, 1, -2, -1, 3, 2, -2, -2, -3, 1, 0, 0 }, { 1, -3, -1, -2, -4, -1, -3, 0, -1, -3, -1, 0, -1, -2, -2, 2, 4, 0, -6, -3, 1, -1, 0 }, { 0, -3, -3, -3, -3, -2, -3, 3, -4, 1, 1, -3, -2, -3, -3, -2, 0, 5, -8, -3, -2, -2, 0 }, {-7, -8, -8, -8, -1, -8, -3, -6, -5, -3, -6, -4, -7, -6, 1, -2, -6, -8, 12, -2, -5, -6, 0 }, {-4, -1, -5, -5, 4, -6, -1, -2, -5, -2, -4, -2, -6, -5, -5, -3, -3, -3, -2, 8, -2, -4, 0 }, { 1, -4, 5, 3, -4, 1, 2, -2, 1, -3, -3, 4, -1, 1, -1, 1, 1, -2, -5, -2, 6, 4, 0 }, { 0, -6, 3, 5, -5, -1, 2, -2, 0, -2, -1, 1, 0, 5, 0, 0, -1, -2, -6, -4, 4, 6, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, }; /* Function: XNU() * Date: 18 Nov 1997 [StL] * * Purpose: x-out of repetitive sequence. XNU tends to be * good at x'ing out short period tandem repeats. * * Note: Apply /only/ to protein sequence. * * Args: dsq: 1..len digitized sequence * len: length of dsq * * Return: number of characters x'ed out. */ int XNU(unsigned char *dsq, int len) { int i,k,off,sum,beg,end,top; int topcut,fallcut; double s0; int noff = 4; /* maximum search offset */ int mcut = 1; double pcut = 0.01; int *hit; double lambda = 0.346574; double K = 0.2; double H = 0.664; int xnum = 0; //get HMMERTaskLocalData HMMERTaskLocalData *tld = getHMMERTaskLocalData(); alphabet_s *al = &tld->al; if (len == 0) return 0; hit = (int*)MallocOrDie(sizeof(int) * (len+1)); for (i=1; i<=len; i++) hit[i]=0; /* ** Determine the score cutoff so that pcut will be the fraction ** of random sequence eliminated assuming lambda, K, and H are ** characteristic of the database as a whole */ s0 = - log( pcut*H / (noff*K) ) / lambda; if (s0>0) topcut = floor(s0 + log(s0)/lambda + 0.5); else topcut = 0; fallcut = (int)log(K/0.001)/lambda; for (off=mcut; off<=noff; off++) { sum=top=0; beg=off; end=0; for (i=off+1; i<=len; i++) { sum += xpam120[dsq[i]][dsq[i-off]]; if (sum>top) { top=sum; end=i; } if (top>=topcut && top-sum>fallcut) { for (k=beg; k<=end; k++) hit[k] = hit[k-off] = 1; sum=top=0; beg=end=i+1; } else if (top-sum>fallcut) { sum=top=0; beg=end=i+1; } if (sum<0) { beg=end=i+1; sum=top=0; } } if (top>=topcut) { for (k=beg; k<=end; k++) hit[k] = hit[k-off] = 1; } } /* Now mask off detected repeats */ for (i=1; i<=len; i++) if (hit[i]) { xnum++; dsq[i] = al->Alphabet_iupac-1;} /* e.g. 'X' */ free(hit); return xnum; } /* Function: TraceScoreCorrection() * Date: Sun Dec 21 12:05:47 1997 [StL] * * Purpose: Calculate a correction (in integer log_2 odds) to be * applied to a sequence, using a second null model, * based on a traceback. M/I emissions are corrected; * C/N/J are not -- as if the nonmatching part and * matching part were each generated by the best null model. * The null model is constructed /post hoc/ as the * average over all the M,I distributions used by the trace. * * Return: the log_2-odds score correction. */ float TraceScoreCorrection(struct plan7_s *hmm, struct p7trace_s *tr, unsigned char *dsq) { float p[MAXABET]; /* null model distribution */ int sc[MAXCODE]; /* null model scores */ int x; int tpos; int score; //get HMMERTaskLocalData HMMERTaskLocalData *tld = getHMMERTaskLocalData(); alphabet_s *al = &tld->al; /* Rarely, the alignment was totally impossible, and tr is NULL. */ if (tr == NULL) return 0.0; /* Set up model: average over the emission distributions of * all M, I states that appear in the trace. Ad hoc? Sure, you betcha. */ FSet(p, al->Alphabet_size, 0.0); for (tpos = 0; tpos < tr->tlen; tpos++) if (tr->statetype[tpos] == STM) FAdd(p, hmm->mat[tr->nodeidx[tpos]], al->Alphabet_size); else if (tr->statetype[tpos] == STI) FAdd(p, hmm->ins[tr->nodeidx[tpos]], al->Alphabet_size); FNorm(p, al->Alphabet_size); for (x = 0; x < al->Alphabet_size; x++) sc[x] = Prob2Score(p[x], hmm->null[x]); /* could avoid this chunk if we knew we didn't need any degenerate char scores */ for (x = al->Alphabet_size; x < al->Alphabet_iupac; x++) sc[x] = DegenerateSymbolScore(p, hmm->null, x); /* Score all the M,I state emissions that appear in the trace. */ score = 0; for (tpos = 0; tpos < tr->tlen; tpos++) if (tr->statetype[tpos] == STM || tr->statetype[tpos] == STI) score += sc[dsq[tr->pos[tpos]]]; /* Apply an ad hoc 8 bit fudge factor penalty; * interpreted as a prior, saying that the second null model is * 1/2^8 (1/256) as likely as the standard null model */ score -= 8 * INTSCALE; /* Return the correction to the bit score. */ return Scorify(ILogsum(0, score)); } ugene-1.9.8/src/plugins_3rdparty/hmm2/src/hmmer2/iupac.cpp0000644000175000017500000001217111651544326022054 0ustar ilyailya/***************************************************************** * HMMER - Biological sequence analysis with profile HMMs * Copyright (C) 1992-2003 Washington University School of Medicine * All Rights Reserved * * This source code is distributed under the terms of the * GNU General Public License. See the files COPYING and LICENSE * for details. *****************************************************************/ /* iupac.c * * Globally defines the IUPAC symbols for nucleic acid sequence * Slowly evolving into a repository of globals. Tue Apr 20 1993 * * CVS $Id: iupac.c,v 1.4 2003/04/14 16:00:16 eddy Exp $ */ #include "funcs.h" /* Default expected nucleotide occurrence frequencies, A/C/G/T. * Used (for instance) as the default distribution for * i.i.d. random nucleotide sequences. */ float dnafq[4] = { 0.25, 0.25, 0.25, 0.25 }; /* Dayhoff f(i) amino acid occurrence frequencies. * From SwissProt 34: 21,210,388 residues * In alphabetic order by single-letter code. * Used (for instance) as the default distribution for * i.i.d. random protein sequences. */ float aafq[20] = { 0.075520, /* A */ 0.016973, /* C */ 0.053029, /* D */ 0.063204, /* E */ 0.040762, /* F */ 0.068448, /* G */ 0.022406, /* H */ 0.057284, /* I */ 0.059398, /* K */ 0.093399, /* L */ 0.023569, /* M */ 0.045293, /* N */ 0.049262, /* P */ 0.040231, /* Q */ 0.051573, /* R */ 0.072214, /* S */ 0.057454, /* T */ 0.065252, /* V */ 0.012513, /* W */ 0.031985 /* Y */ }; char aa_alphabet[] = AMINO_ALPHABET; /* aa_index converts to pam's 27x27 scheme */ int aa_index[20] = { 0, 2, 3, 4, 5, 6, 7, 8, 10, 11, 12, 13, 15, 16, 17, 18, 19, 21, 22, 24 }; /* IUPAC code translations */ /* note: sequence chars are UPPER CASE */ struct iupactype iupac[] = { iupactype( 'A', 'T', NTA, NTT ), iupactype( 'C', 'G', NTC, NTG ), iupactype( 'G', 'C', NTG, NTC ), iupactype( 'T', 'A', NTT, NTA ), iupactype( 'U', 'A', NTU, NTA ), iupactype( 'N', 'N', NTN, NTN ), iupactype( ' ', ' ', NTGAP, NTGAP ), iupactype( 'R', 'Y', NTR, NTY ), iupactype( 'Y', 'R', NTY, NTR ), iupactype( 'M', 'K', NTM, NTK ), iupactype( 'K', 'M', NTK, NTM ), iupactype( 'S', 'S', NTS, NTS ), iupactype( 'W', 'W', NTW, NTW ), iupactype( 'H', 'D', NTH, NTD ), iupactype( 'B', 'V', NTB, NTV ), iupactype( 'V', 'B', NTV, NTB ), iupactype( 'D', 'H', NTD, NTH ), }; const char *stdcode1[65] = { "K", /* AAA */ "N", /* AAC */ "K", /* AAG */ "N", /* AAU */ "T", /* ACA */ "T", /* ACC */ "T", /* ACG */ "T", /* ACU */ "R", /* AGA */ "S", /* AGC */ "R", /* AGG */ "S", /* AGU */ "I", /* AUA */ "I", /* AUC */ "M", /* AUG */ "I", /* AUU */ "Q", /* CAA */ "H", /* CAC */ "Q", /* CAG */ "H", /* CAU */ "P", /* CCA */ "P", /* CCC */ "P", /* CCG */ "P", /* CCU */ "R", /* CGA */ "R", /* CGC */ "R", /* CGG */ "R", /* CGU */ "L", /* CUA */ "L", /* CUC */ "L", /* CUG */ "L", /* CUU */ "E", /* GAA */ "D", /* GAC */ "E", /* GAG */ "D", /* GAU */ "A", /* GCA */ "A", /* GCC */ "A", /* GCG */ "A", /* GCU */ "G", /* GGA */ "G", /* GGC */ "G", /* GGG */ "G", /* GGU */ "V", /* GUA */ "V", /* GUC */ "V", /* GUG */ "V", /* GUU */ "*", /* UAA */ "Y", /* UAC */ "*", /* UAG */ "Y", /* UAU */ "S", /* UCA */ "S", /* UCC */ "S", /* UCG */ "S", /* UCU */ "*", /* UGA */ "C", /* UGC */ "W", /* UGG */ "C", /* UGU */ "L", /* UUA */ "F", /* UUC */ "L", /* UUG */ "F", /* UUU */ "X", /* unknown */ }; const char *stdcode3[65] = { "Lys", /* AAA */ "Asn", /* AAC */ "Lys", /* AAG */ "Asn", /* AAU */ "Thr", /* ACA */ "Thr", /* ACC */ "Thr", /* ACG */ "Thr", /* ACU */ "Arg", /* AGA */ "Ser", /* AGC */ "Arg", /* AGG */ "Ser", /* AGU */ "Ile", /* AUA */ "Ile", /* AUC */ "Met", /* AUG */ "Ile", /* AUU */ "Gln", /* CAA */ "His", /* CAC */ "Gln", /* CAG */ "His", /* CAU */ "Pro", /* CCA */ "Pro", /* CCC */ "Pro", /* CCG */ "Pro", /* CCU */ "Arg", /* CGA */ "Arg", /* CGC */ "Arg", /* CGG */ "Arg", /* CGU */ "Leu", /* CUA */ "Leu", /* CUC */ "Leu", /* CUG */ "Leu", /* CUU */ "Glu", /* GAA */ "Asp", /* GAC */ "Glu", /* GAG */ "Asp", /* GAU */ "Ala", /* GCA */ "Ala", /* GCC */ "Ala", /* GCG */ "Ala", /* GCU */ "Gly", /* GGA */ "Gly", /* GGC */ "Gly", /* GGG */ "Gly", /* GGU */ "Val", /* GUA */ "Val", /* GUC */ "Val", /* GUG */ "Val", /* GUU */ "***", /* UAA */ "Tyr", /* UAC */ "***", /* UAG */ "Tyr", /* UAU */ "Ser", /* UCA */ "Ser", /* UCC */ "Ser", /* UCG */ "Ser", /* UCU */ "***", /* UGA */ "Cys", /* UGC */ "Trp", /* UGG */ "Cys", /* UGU */ "Leu", /* UUA */ "Phe", /* UUC */ "Leu", /* UUG */ "Trp", /* UUU */ "XXX", /* unknown */ }; ugene-1.9.8/src/plugins_3rdparty/hmm2/src/hmmer2/core_algorithms.cpp0000644000175000017500000030004611651544326024135 0ustar ilyailya/************************************************************ * HMMER - Biological sequence analysis with profile HMMs * Copyright (C) 1992-2003 Washington University School of Medicine * All Rights Reserved * * This source code is distributed under the terms of the * GNU General Public License. See the files COPYING and LICENSE * for details. ************************************************************/ /* core_algorithms.c * SRE, Mon Nov 11 15:58:52 1996 * CVS $Id: core_algorithms.c,v 1.35 2003/10/03 18:26:37 eddy Exp $ * * Simple and robust "research" implementations of Forward, Backward, * and Viterbi for Plan7. For optimized replacements for some of these functions, * see fast_algorithms.c. */ #include "funcs.h" static float get_wee_midpt(struct plan7_s *hmm, unsigned char *dsq, int L, int k1, char t1, int s1, int k3, char t3, int s3, int *ret_k2, char *ret_t2, int *ret_s2); /* Function: CreatePlan7Matrix() * * Purpose: Create a dynamic programming matrix for standard Forward, * Backward, or Viterbi, with scores kept as scaled log-odds * integers. Keeps 2D arrays compact in RAM in an attempt * to maximize cache hits. * * The mx structure can be dynamically grown, if a new * HMM or seq exceeds the currently allocated size. Dynamic * growing is more efficient than an alloc/free of a whole * matrix for every new target. The ResizePlan7Matrix() * call does this reallocation, if needed. Here, in the * creation step, we set up some pads - to inform the resizing * call how much to overallocate when it realloc's. * * Args: N - N+1 rows are allocated, for sequence. * M - size of model in nodes * padN - over-realloc in seq/row dimension, or 0 * padM - over-realloc in HMM/column dimension, or 0 * * Return: mx * mx is allocated here. Caller frees with FreePlan7Matrix(mx). */ #ifndef ALTIVEC struct dpmatrix_s * CreatePlan7Matrix(int N, int M, int padN, int padM) { struct dpmatrix_s *mx; int i; mx = (struct dpmatrix_s *) MallocOrDie (sizeof(struct dpmatrix_s)); mx->xmx = (int **) MallocOrDie (sizeof(int *) * (N+1)); mx->mmx = (int **) MallocOrDie (sizeof(int *) * (N+1)); mx->imx = (int **) MallocOrDie (sizeof(int *) * (N+1)); mx->dmx = (int **) MallocOrDie (sizeof(int *) * (N+1)); mx->xmx_mem = (void *) MallocOrDie (sizeof(int) * ((N+1)*5)); mx->mmx_mem = (void *) MallocOrDie (sizeof(int) * ((N+1)*(M+2))); mx->imx_mem = (void *) MallocOrDie (sizeof(int) * ((N+1)*(M+2))); mx->dmx_mem = (void *) MallocOrDie (sizeof(int) * ((N+1)*(M+2))); /* The indirect assignment below looks wasteful; it's actually * used for aligning data on 16-byte boundaries as a cache * optimization in the fast altivec implementation */ mx->xmx[0] = (int *) mx->xmx_mem; mx->mmx[0] = (int *) mx->mmx_mem; mx->imx[0] = (int *) mx->imx_mem; mx->dmx[0] = (int *) mx->dmx_mem; for (i = 1; i <= N; i++) { mx->xmx[i] = mx->xmx[0] + (i*5); mx->mmx[i] = mx->mmx[0] + (i*(M+2)); mx->imx[i] = mx->imx[0] + (i*(M+2)); mx->dmx[i] = mx->dmx[0] + (i*(M+2)); } mx->maxN = N; mx->maxM = M; mx->padN = padN; mx->padM = padM; return mx; } #endif //ALTIVEC /* Function: ResizePlan7Matrix() * * Purpose: Reallocate a dynamic programming matrix, if necessary, * for a problem of NxM: sequence length N, model size M. * (N=1 for small memory score-only variants; we allocate * N+1 rows in the DP matrix.) * * We know (because of the way hmmsearch and hmmpfam are coded) * that only one of the two dimensions is going to change * in size after the first call to ResizePlan7Matrix(); * that is, for hmmsearch, we have one HMM of fixed size M * and our target sequences may grow in N; for hmmpfam, * we have one sequence of fixed size N and our target models * may grow in M. What we have to watch out for is P7SmallViterbi() * working on a divide and conquer problem and passing us N < maxN, * M > maxM; we should definitely *not* reallocate a smaller N. * Since we know that only one dimension is going to grow, * we aren't scared of reallocating to maxN,maxM. (If both * M and N could grow, we would be more worried.) * * Returns individual ptrs to the four matrix components * as a convenience. * * Args: mx - an already allocated model to grow. * N - seq length to allocate for; N+1 rows * M - size of model * xmx, mmx, imx, dmx * - RETURN: ptrs to four mx components as a convenience * * Return: (void) * mx is (re)allocated here. */ #ifndef ALTIVEC void ResizePlan7Matrix(struct dpmatrix_s *mx, int N, int M, int ***xmx, int ***mmx, int ***imx, int ***dmx) { int i; if (N <= mx->maxN && M <= mx->maxM) goto DONE; if (N > mx->maxN) { N += mx->padN; mx->maxN = N; mx->xmx = (int **) ReallocOrDie (mx->xmx, sizeof(int *) * (mx->maxN+1)); mx->mmx = (int **) ReallocOrDie (mx->mmx, sizeof(int *) * (mx->maxN+1)); mx->imx = (int **) ReallocOrDie (mx->imx, sizeof(int *) * (mx->maxN+1)); mx->dmx = (int **) ReallocOrDie (mx->dmx, sizeof(int *) * (mx->maxN+1)); } if (M > mx->maxM) { M += mx->padM; mx->maxM = M; } mx->xmx_mem = (void *) ReallocOrDie (mx->xmx_mem, sizeof(int) * ((mx->maxN+1)*5)); mx->mmx_mem = (void *) ReallocOrDie (mx->mmx_mem, sizeof(int) * ((mx->maxN+1)*(mx->maxM+2))); mx->imx_mem = (void *) ReallocOrDie (mx->imx_mem, sizeof(int) * ((mx->maxN+1)*(mx->maxM+2))); mx->dmx_mem = (void *) ReallocOrDie (mx->dmx_mem, sizeof(int) * ((mx->maxN+1)*(mx->maxM+2))); mx->xmx[0] = (int *) mx->xmx_mem; mx->mmx[0] = (int *) mx->mmx_mem; mx->imx[0] = (int *) mx->imx_mem; mx->dmx[0] = (int *) mx->dmx_mem; for (i = 1; i <= mx->maxN; i++) { mx->xmx[i] = mx->xmx[0] + (i*5); mx->mmx[i] = mx->mmx[0] + (i*(mx->maxM+2)); mx->imx[i] = mx->imx[0] + (i*(mx->maxM+2)); mx->dmx[i] = mx->dmx[0] + (i*(mx->maxM+2)); } DONE: if (xmx != NULL) *xmx = mx->xmx; if (mmx != NULL) *mmx = mx->mmx; if (imx != NULL) *imx = mx->imx; if (dmx != NULL) *dmx = mx->dmx; } #endif //ALTIVEC /* Function: AllocPlan7Matrix() * Date: SRE, Tue Nov 19 07:14:47 2002 [St. Louis] * * Purpose: Used to be the main allocator for dp matrices; we used to * allocate, calculate, free. But this spent a lot of time * in malloc(). Replaced with Create..() and Resize..() to * allow matrix reuse in P7Viterbi(), the main alignment * engine. But matrices are alloc'ed by other alignment engines * too, ones that are less frequently called and less * important to optimization of cpu performance. Instead of * tracking changes through them, for now, provide * an Alloc...() call with the same API that's just a wrapper. * * Args: rows - generally L+1, or 2; # of DP rows in seq dimension to alloc * M - size of model, in nodes * xmx, mmx, imx, dmx * - RETURN: ptrs to four mx components as a convenience * * Returns: mx * Caller free's w/ FreePlan7Matrix() */ struct dpmatrix_s * AllocPlan7Matrix(int rows, int M, int ***xmx, int ***mmx, int ***imx, int ***dmx) { struct dpmatrix_s *mx; mx = CreatePlan7Matrix(rows-1, M, 0, 0); if (xmx != NULL) *xmx = mx->xmx; if (mmx != NULL) *mmx = mx->mmx; if (imx != NULL) *imx = mx->imx; if (dmx != NULL) *dmx = mx->dmx; return mx; } /* Function: FreePlan7Matrix() * * Purpose: Free a dynamic programming matrix allocated by CreatePlan7Matrix(). * * Return: (void) */ void FreePlan7Matrix(struct dpmatrix_s *mx) { free (mx->xmx_mem); free (mx->mmx_mem); free (mx->imx_mem); free (mx->dmx_mem); free (mx->xmx); free (mx->mmx); free (mx->imx); free (mx->dmx); free (mx); } /* Function: AllocShadowMatrix() * * Purpose: Allocate a dynamic programming traceback pointer matrix for * a Viterbi algorithm. * * Args: rows - number of rows to allocate; typically L+1 * M - size of model * xtb, mtb, itb, dtb * - RETURN: ptrs to four mx components as a convenience * * Return: mx * mx is allocated here. Caller frees with FreeDPMatrix(mx). */ struct dpshadow_s * AllocShadowMatrix(int rows, int M, char ***xtb, char ***mtb, char ***itb, char ***dtb) { struct dpshadow_s *tb; int i; tb = (struct dpshadow_s *) MallocOrDie (sizeof(struct dpshadow_s)); tb->xtb = (char **) MallocOrDie (sizeof(char *) * rows); tb->mtb = (char **) MallocOrDie (sizeof(char *) * rows); tb->itb = (char **) MallocOrDie (sizeof(char *) * rows); tb->dtb = (char **) MallocOrDie (sizeof(char *) * rows); tb->esrc = (int *) MallocOrDie (sizeof(int) * rows); tb->xtb[0] = (char *) MallocOrDie (sizeof(char) * (rows*5)); tb->mtb[0] = (char *) MallocOrDie (sizeof(char) * (rows*(M+2))); tb->itb[0] = (char *) MallocOrDie (sizeof(char) * (rows*(M+2))); tb->dtb[0] = (char *) MallocOrDie (sizeof(char) * (rows*(M+2))); for (i = 1; i < rows; i++) { tb->xtb[i] = tb->xtb[0] + (i*5); tb->mtb[i] = tb->mtb[0] + (i*(M+2)); tb->itb[i] = tb->itb[0] + (i*(M+2)); tb->dtb[i] = tb->dtb[0] + (i*(M+2)); } if (xtb != NULL) *xtb = tb->xtb; if (mtb != NULL) *mtb = tb->mtb; if (itb != NULL) *itb = tb->itb; if (dtb != NULL) *dtb = tb->dtb; return tb; } /* Function: FreeShadowMatrix() * * Purpose: Free a dynamic programming matrix allocated by AllocShadowMatrix(). * * Return: (void) */ void FreeShadowMatrix(struct dpshadow_s *tb) { free (tb->xtb[0]); free (tb->mtb[0]); free (tb->itb[0]); free (tb->dtb[0]); free (tb->esrc); free (tb->xtb); free (tb->mtb); free (tb->itb); free (tb->dtb); free (tb); } /* Function: P7ViterbiSpaceOK() * Incept: SRE, Wed Oct 1 12:53:13 2003 [St. Louis] * * Purpose: Returns TRUE if the existing matrix allocation * is already sufficient to hold the requested MxN, or if * the matrix can be expanded in M and/or N without * exceeding RAMLIMIT megabytes. * * This gets called anytime we're about to do P7Viterbi(). * If it returns FALSE, we switch into the appropriate * small-memory alternative: P7SmallViterbi() or * P7WeeViterbi(). * * Checking the DP problem size against P7ViterbiSize() * is not enough, because the DP matrix may be already * allocated in MxN. For example, if we're already * allocated to maxM,maxN of 1447x979, and we try to * do a problem of MxN=12x125000, P7ViterbiSize() may * think that's fine - but when we resize, we can only * grow, so we'll expand to 1447x125000, which is * likely over the RAMLIMIT. [bug#h26; xref SLT7 p.122] * * Args: * * Returns: TRUE if we can run P7Viterbi(); FALSE if we need * to use a small memory variant. * * Xref: STL7 p.122. */ int P7ViterbiSpaceOK(int L, int M, struct dpmatrix_s *mx) { int newM; int newN; if (M > mx->maxM) newM = M + mx->padM; else newM = mx->maxM; if (L > mx->maxN) newN = L + mx->padN; else newN = mx->maxN; if (P7ViterbiSize(newN, newM) <= RAMLIMIT) return TRUE; else return FALSE; } /* Function: P7ViterbiSize() * Date: SRE, Fri Mar 6 15:13:20 1998 [St. Louis] * * Purpose: Returns the ballpark predicted memory requirement for a * P7Viterbi() alignment, in MB. * * Currently L must fit in an int (< 2 GB), but we have * to deal with LM > 2 GB - e.g. watch out for overflow, do * the whole calculation in floating point. Bug here detected * in 2.1.1 by David Harper, Sanger Centre. * * Args: L - length of sequence * M - length of HMM * * Returns: # of MB */ int P7ViterbiSize(int L, int M) { float Mbytes; /* We're excessively precise here, but it doesn't cost * us anything to be pedantic. The four terms are: * 1. the matrix structure itself; * 2. the O(NM) main matrix (this dominates!) * 3. ptrs into the rows of the matrix * 4. storage for 5 special states. (xmx) */ Mbytes = (float) sizeof(struct dpmatrix_s); Mbytes += 3. * (float) (L+1) * (float) (M+2) * (float) sizeof(int); Mbytes += 4. * (float) (L+1) * (float) sizeof(int *); Mbytes += 5. * (float) (L+1) * (float) sizeof(int); Mbytes /= 1048576.; return (int) Mbytes; } /* Function: P7SmallViterbiSize() * Date: SRE, Fri Mar 6 15:20:04 1998 [St. Louis] * * Purpose: Returns the ballpark predicted memory requirement for * a P7SmallViterbi() alignment, in MB. * * P7SmallViterbi() is a wrapper, calling both P7ParsingViterbi() * and P7WeeViterbi(). P7ParsingViterbi() typically dominates * the memory requirement, so the value returned * is the P7ParsingViterbi() number. * * We don't (yet) worry about overflow issues like we did with * P7ViterbiSize(). We'll have many other 32-bit int issues in the * code if we overflow here. * * Args: L - length of sequence * M - length of HMM * * Returns: # of MB */ int P7SmallViterbiSize(int L, int M) { return ((2 * sizeof(struct dpmatrix_s) + 12 * (M+2) * sizeof(int) + /* 2 matrices w/ 2 rows */ 16 * sizeof(int *) + /* ptrs into rows of matrix */ 20 * sizeof(int) + /* 5 special states */ 2 * (L+1) * sizeof(int)) /* traceback indices */ / 1000000); } /* Function: P7WeeViterbiSize() * Date: SRE, Fri Mar 6 15:40:42 1998 [St. Louis] * * Purpose: Returns the ballpark predicted memory requirement for * a P7WeeViterbi() alignment, in MB. * * Args: L - length of sequence * M - length of HMM * * Returns: # of MB */ int P7WeeViterbiSize(int L, int M) { return ((2 * sizeof(struct dpmatrix_s) + 12 * (M+2) * sizeof(int) + /* 2 matrices w/ 2 rows */ 16 * sizeof(int *) + /* ptrs into rows of matrix */ 20 * sizeof(int) + /* 5 special states */ 2 * (L+2) * sizeof(int) + /* stacks for starts/ends (overkill) */ (L+2) * sizeof(int) + /* k assignments to seq positions */ (L+2) * sizeof(char)) /* state assignments to seq pos */ / 1000000); } /* Function: P7Forward() * * Purpose: The Forward dynamic programming algorithm. * The scaling issue is dealt with by working in log space * and calling ILogsum(); this is a slow but robust approach. * * Args: dsq - sequence in digitized form * L - length of dsq * hmm - the model * ret_mx - RETURN: dp matrix; pass NULL if it's not wanted * * Return: log P(S|M)/P(S|R), as a bit score. */ float P7Forward(unsigned char *dsq, int L, struct plan7_s *hmm, struct dpmatrix_s **ret_mx) { struct dpmatrix_s *mx; int **xmx; int **mmx; int **imx; int **dmx; int i,k; int sc; /* Allocate a DP matrix with 0..L rows, 0..M-1 columns. */ mx = AllocPlan7Matrix(L+1, hmm->M, &xmx, &mmx, &imx, &dmx); /* Initialization of the zero row. * Note that xmx[i][stN] = 0 by definition for all i, * and xmx[i][stT] = xmx[i][stC], so neither stN nor stT need * to be calculated in DP matrices. */ xmx[0][XMN] = 0; /* S->N, p=1 */ xmx[0][XMB] = hmm->xsc[XTN][MOVE]; /* S->N->B, no N-tail */ xmx[0][XME] = xmx[0][XMC] = xmx[0][XMJ] = -INFTY; /* need seq to get here */ for (k = 0; k <= hmm->M; k++) mmx[0][k] = imx[0][k] = dmx[0][k] = -INFTY; /* need seq to get here */ /* Recursion. Done as a pull. * Note some slightly wasteful boundary conditions: * tsc[0] = -INFTY for all eight transitions (no node 0) */ for (i = 1; i <= L; i++) { mmx[i][0] = imx[i][0] = dmx[i][0] = -INFTY; for (k = 1; k < hmm->M; k++) { mmx[i][k] = ILogsum(ILogsum(mmx[i-1][k-1] + hmm->tsc[TMM][k-1], imx[i-1][k-1] + hmm->tsc[TIM][k-1]), ILogsum(xmx[i-1][XMB] + hmm->bsc[k], dmx[i-1][k-1] + hmm->tsc[TDM][k-1])); mmx[i][k] += hmm->msc[dsq[i]][k]; dmx[i][k] = ILogsum(mmx[i][k-1] + hmm->tsc[TMD][k-1], dmx[i][k-1] + hmm->tsc[TDD][k-1]); imx[i][k] = ILogsum(mmx[i-1][k] + hmm->tsc[TMI][k], imx[i-1][k] + hmm->tsc[TII][k]); imx[i][k] += hmm->isc[dsq[i]][k]; } mmx[i][hmm->M] = ILogsum(ILogsum(mmx[i-1][hmm->M-1] + hmm->tsc[TMM][hmm->M-1], imx[i-1][hmm->M-1] + hmm->tsc[TIM][hmm->M-1]), ILogsum(xmx[i-1][XMB] + hmm->bsc[hmm->M], dmx[i-1][hmm->M-1] + hmm->tsc[TDM][hmm->M-1])); mmx[i][hmm->M] += hmm->msc[dsq[i]][hmm->M]; /* Now the special states. * remember, C and J emissions are zero score by definition */ xmx[i][XMN] = xmx[i-1][XMN] + hmm->xsc[XTN][LOOP]; xmx[i][XME] = -INFTY; for (k = 1; k <= hmm->M; k++) xmx[i][XME] = ILogsum(xmx[i][XME], mmx[i][k] + hmm->esc[k]); xmx[i][XMJ] = ILogsum(xmx[i-1][XMJ] + hmm->xsc[XTJ][LOOP], xmx[i][XME] + hmm->xsc[XTE][LOOP]); xmx[i][XMB] = ILogsum(xmx[i][XMN] + hmm->xsc[XTN][MOVE], xmx[i][XMJ] + hmm->xsc[XTJ][MOVE]); xmx[i][XMC] = ILogsum(xmx[i-1][XMC] + hmm->xsc[XTC][LOOP], xmx[i][XME] + hmm->xsc[XTE][MOVE]); } sc = xmx[L][XMC] + hmm->xsc[XTC][MOVE]; if (ret_mx != NULL) *ret_mx = mx; else FreePlan7Matrix(mx); return Scorify(sc); /* the total Forward score. */ } #ifdef SLOW /* Function: P7Viterbi() * * Purpose: The Viterbi dynamic programming algorithm. * Identical to Forward() except that max's * replace sum's. * * This is the slower, more understandable version * of P7Viterbi(). The default version in fast_algorithms.c * is portably optimized and more difficult to understand; * the ALTIVEC version in fast_algorithms.c is vectorized * with Altivec-specific code, and is pretty opaque. * * This function is not enabled by default; it is only * activated by -DSLOW at compile time. * * Args: dsq - sequence in digitized form * L - length of dsq * hmm - the model * mx - reused DP matrix * ret_tr - RETURN: traceback; pass NULL if it's not wanted * * Return: log P(S|M)/P(S|R), as a bit score */ float P7Viterbi(unsigned char *dsq, int L, struct plan7_s *hmm, struct dpmatrix_s *mx, struct p7trace_s **ret_tr) { struct p7trace_s *tr; int **xmx; int **mmx; int **imx; int **dmx; int i,k; int sc; /* Allocate a DP matrix with 0..L rows, 0..M-1 columns. */ ResizePlan7Matrix(mx, L, hmm->M, &xmx, &mmx, &imx, &dmx); /* Initialization of the zero row. */ xmx[0][XMN] = 0; /* S->N, p=1 */ xmx[0][XMB] = hmm->xsc[XTN][MOVE]; /* S->N->B, no N-tail */ xmx[0][XME] = xmx[0][XMC] = xmx[0][XMJ] = -INFTY; /* need seq to get here */ for (k = 0; k <= hmm->M; k++) mmx[0][k] = imx[0][k] = dmx[0][k] = -INFTY; /* need seq to get here */ /* Recursion. Done as a pull. * Note some slightly wasteful boundary conditions: * tsc[0] = -INFTY for all eight transitions (no node 0) * D_M and I_M are wastefully calculated (they don't exist) */ for (i = 1; i <= L; i++) { mmx[i][0] = imx[i][0] = dmx[i][0] = -INFTY; for (k = 1; k <= hmm->M; k++) { /* match state */ mmx[i][k] = -INFTY; if ((sc = mmx[i-1][k-1] + hmm->tsc[TMM][k-1]) > mmx[i][k]) mmx[i][k] = sc; if ((sc = imx[i-1][k-1] + hmm->tsc[TIM][k-1]) > mmx[i][k]) mmx[i][k] = sc; if ((sc = xmx[i-1][XMB] + hmm->bsc[k]) > mmx[i][k]) mmx[i][k] = sc; if ((sc = dmx[i-1][k-1] + hmm->tsc[TDM][k-1]) > mmx[i][k]) mmx[i][k] = sc; if (hmm->msc[dsq[i]][k] != -INFTY) mmx[i][k] += hmm->msc[dsq[i]][k]; else mmx[i][k] = -INFTY; /* delete state */ dmx[i][k] = -INFTY; if ((sc = mmx[i][k-1] + hmm->tsc[TMD][k-1]) > dmx[i][k]) dmx[i][k] = sc; if ((sc = dmx[i][k-1] + hmm->tsc[TDD][k-1]) > dmx[i][k]) dmx[i][k] = sc; /* insert state */ if (k < hmm->M) { imx[i][k] = -INFTY; if ((sc = mmx[i-1][k] + hmm->tsc[TMI][k]) > imx[i][k]) imx[i][k] = sc; if ((sc = imx[i-1][k] + hmm->tsc[TII][k]) > imx[i][k]) imx[i][k] = sc; if (hmm->isc[dsq[i]][k] != -INFTY) imx[i][k] += hmm->isc[dsq[i]][k]; else imx[i][k] = -INFTY; } } /* Now the special states. Order is important here. * remember, C and J emissions are zero score by definition, */ /* N state */ xmx[i][XMN] = -INFTY; if ((sc = xmx[i-1][XMN] + hmm->xsc[XTN][LOOP]) > -INFTY) xmx[i][XMN] = sc; /* E state */ xmx[i][XME] = -INFTY; for (k = 1; k <= hmm->M; k++) if ((sc = mmx[i][k] + hmm->esc[k]) > xmx[i][XME]) xmx[i][XME] = sc; /* J state */ xmx[i][XMJ] = -INFTY; if ((sc = xmx[i-1][XMJ] + hmm->xsc[XTJ][LOOP]) > -INFTY) xmx[i][XMJ] = sc; if ((sc = xmx[i][XME] + hmm->xsc[XTE][LOOP]) > xmx[i][XMJ]) xmx[i][XMJ] = sc; /* B state */ xmx[i][XMB] = -INFTY; if ((sc = xmx[i][XMN] + hmm->xsc[XTN][MOVE]) > -INFTY) xmx[i][XMB] = sc; if ((sc = xmx[i][XMJ] + hmm->xsc[XTJ][MOVE]) > xmx[i][XMB]) xmx[i][XMB] = sc; /* C state */ xmx[i][XMC] = -INFTY; if ((sc = xmx[i-1][XMC] + hmm->xsc[XTC][LOOP]) > -INFTY) xmx[i][XMC] = sc; if ((sc = xmx[i][XME] + hmm->xsc[XTE][MOVE]) > xmx[i][XMC]) xmx[i][XMC] = sc; } /* T state (not stored) */ sc = xmx[L][XMC] + hmm->xsc[XTC][MOVE]; if (ret_tr != NULL) { P7ViterbiTrace(hmm, dsq, L, mx, &tr); *ret_tr = tr; } return Scorify(sc); /* the total Viterbi score. */ } #endif /*SLOW*/ /* Function: P7ViterbiTrace() * Date: SRE, Sat Aug 23 10:30:11 1997 (St. Louis Lambert Field) * * Purpose: Traceback of a Viterbi matrix: i.e. retrieval * of optimum alignment. * * Args: hmm - hmm, log odds form, used to make mx * dsq - sequence aligned to (digital form) 1..N * N - length of seq * mx - the matrix to trace back in, N x hmm->M * ret_tr - RETURN: traceback. * * Return: (void) * ret_tr is allocated here. Free using P7FreeTrace(). */ void P7ViterbiTrace(struct plan7_s *hmm, unsigned char *dsq, int N, struct dpmatrix_s *mx, struct p7trace_s **ret_tr) { struct p7trace_s *tr; int curralloc; /* current allocated length of trace */ int tpos; /* position in trace */ int i; /* position in seq (1..N) */ int k; /* position in model (1..M) */ int **xmx, **mmx, **imx, **dmx; int sc; /* temp var for pre-emission score */ /* Overallocate for the trace. * S-N-B- ... - E-C-T : 6 states + N is minimum trace; * add N more as buffer. */ curralloc = N * 2 + 6; P7AllocTrace(curralloc, &tr); xmx = mx->xmx; mmx = mx->mmx; imx = mx->imx; dmx = mx->dmx; /* Initialization of trace * We do it back to front; ReverseTrace() is called later. */ tr->statetype[0] = STT; tr->nodeidx[0] = 0; tr->pos[0] = 0; tr->statetype[1] = STC; tr->nodeidx[1] = 0; tr->pos[1] = 0; tpos = 2; i = N; /* current i (seq pos) we're trying to assign */ /* Traceback */ while (tr->statetype[tpos-1] != STS) { switch (tr->statetype[tpos-1]) { case STM: /* M connects from i-1,k-1, or B */ sc = mmx[i+1][k+1] - hmm->msc[dsq[i+1]][k+1]; if (sc <= -INFTY) { P7FreeTrace(tr); *ret_tr = NULL; return; } else if (sc == xmx[i][XMB] + hmm->bsc[k+1]) { /* Check for wing unfolding */ if (Prob2Score(hmm->begin[k+1], hmm->p1) + 1 * INTSCALE <= hmm->bsc[k+1]) while (k > 0) { tr->statetype[tpos] = STD; tr->nodeidx[tpos] = k--; tr->pos[tpos] = 0; tpos++; if (tpos == curralloc) { /* grow trace if necessary */ curralloc += N; P7ReallocTrace(tr, curralloc); } } tr->statetype[tpos] = STB; tr->nodeidx[tpos] = 0; tr->pos[tpos] = 0; } else if (sc == mmx[i][k] + hmm->tsc[TMM][k]) { tr->statetype[tpos] = STM; tr->nodeidx[tpos] = k--; tr->pos[tpos] = i--; } else if (sc == imx[i][k] + hmm->tsc[TIM][k]) { tr->statetype[tpos] = STI; tr->nodeidx[tpos] = k; tr->pos[tpos] = i--; } else if (sc == dmx[i][k] + hmm->tsc[TDM][k]) { tr->statetype[tpos] = STD; tr->nodeidx[tpos] = k--; tr->pos[tpos] = 0; } else Die("traceback failed"); break; case STD: /* D connects from M,D */ if (dmx[i][k+1] <= -INFTY) { P7FreeTrace(tr); *ret_tr = NULL; return; } else if (dmx[i][k+1] == mmx[i][k] + hmm->tsc[TMD][k]) { tr->statetype[tpos] = STM; tr->nodeidx[tpos] = k--; tr->pos[tpos] = i--; } else if (dmx[i][k+1] == dmx[i][k] + hmm->tsc[TDD][k]) { tr->statetype[tpos] = STD; tr->nodeidx[tpos] = k--; tr->pos[tpos] = 0; } else Die("traceback failed"); break; case STI: /* I connects from M,I */ sc = imx[i+1][k] - hmm->isc[dsq[i+1]][k]; if (sc <= -INFTY) { P7FreeTrace(tr); *ret_tr = NULL; return; } else if (sc == mmx[i][k] + hmm->tsc[TMI][k]) { tr->statetype[tpos] = STM; tr->nodeidx[tpos] = k--; tr->pos[tpos] = i--; } else if (sc == imx[i][k] + hmm->tsc[TII][k]) { tr->statetype[tpos] = STI; tr->nodeidx[tpos] = k; tr->pos[tpos] = i--; } else Die("traceback failed"); break; case STN: /* N connects from S, N */ if (i == 0 && xmx[i][XMN] == 0) { tr->statetype[tpos] = STS; tr->nodeidx[tpos] = 0; tr->pos[tpos] = 0; } else if (i > 0 && xmx[i+1][XMN] == xmx[i][XMN] + hmm->xsc[XTN][LOOP]) { tr->statetype[tpos] = STN; tr->nodeidx[tpos] = 0; tr->pos[tpos] = 0; /* note convention adherence: */ tr->pos[tpos-1] = i--; /* first N doesn't emit */ } else Die("traceback failed"); break; case STB: /* B connects from N, J */ if (xmx[i][XMB] <= -INFTY) { P7FreeTrace(tr); *ret_tr = NULL; return; } else if (xmx[i][XMB] == xmx[i][XMN] + hmm->xsc[XTN][MOVE]) { tr->statetype[tpos] = STN; tr->nodeidx[tpos] = 0; tr->pos[tpos] = 0; } else if (xmx[i][XMB] == xmx[i][XMJ] + hmm->xsc[XTJ][MOVE]) { tr->statetype[tpos] = STJ; tr->nodeidx[tpos] = 0; tr->pos[tpos] = 0; } else Die("traceback failed"); break; case STE: /* E connects from any M state. k set here */ if (xmx[i][XME] <= -INFTY) { P7FreeTrace(tr); *ret_tr = NULL; return; } for (k = hmm->M; k >= 1; k--) if (xmx[i][XME] == mmx[i][k] + hmm->esc[k]) { /* check for wing unfolding */ if (Prob2Score(hmm->end[k], 1.) + 1*INTSCALE <= hmm->esc[k]) { int dk; /* need a tmp k while moving thru delete wing */ for (dk = hmm->M; dk > k; dk--) { tr->statetype[tpos] = STD; tr->nodeidx[tpos] = dk; tr->pos[tpos] = 0; tpos++; if (tpos == curralloc) { /* grow trace if necessary */ curralloc += N; P7ReallocTrace(tr, curralloc); } } } tr->statetype[tpos] = STM; tr->nodeidx[tpos] = k--; tr->pos[tpos] = i--; break; } if (k < 0) Die("traceback failed"); break; case STC: /* C comes from C, E */ if (xmx[i][XMC] <= -INFTY) { P7FreeTrace(tr); *ret_tr = NULL; return; } else if (xmx[i][XMC] == xmx[i-1][XMC] + hmm->xsc[XTC][LOOP]) { tr->statetype[tpos] = STC; tr->nodeidx[tpos] = 0; tr->pos[tpos] = 0; /* note convention adherence: */ tr->pos[tpos-1] = i--; /* first C doesn't emit */ } else if (xmx[i][XMC] == xmx[i][XME] + hmm->xsc[XTE][MOVE]) { tr->statetype[tpos] = STE; tr->nodeidx[tpos] = 0; tr->pos[tpos] = 0; /* E is a nonemitter */ } else Die("Traceback failed."); break; case STJ: /* J connects from E, J */ if (xmx[i][XMJ] <= -INFTY) { P7FreeTrace(tr); *ret_tr = NULL; return; } else if (xmx[i][XMJ] == xmx[i-1][XMJ] + hmm->xsc[XTJ][LOOP]) { tr->statetype[tpos] = STJ; tr->nodeidx[tpos] = 0; tr->pos[tpos] = 0; /* note convention adherence: */ tr->pos[tpos-1] = i--; /* first J doesn't emit */ } else if (xmx[i][XMJ] == xmx[i][XME] + hmm->xsc[XTE][LOOP]) { tr->statetype[tpos] = STE; tr->nodeidx[tpos] = 0; tr->pos[tpos] = 0; /* E is a nonemitter */ } else Die("Traceback failed."); break; default: Die("traceback failed"); } /* end switch over statetype[tpos-1] */ tpos++; if (tpos == curralloc) { /* grow trace if necessary */ curralloc += N; P7ReallocTrace(tr, curralloc); } } /* end traceback, at S state; tpos == tlen now */ tr->tlen = tpos; P7ReverseTrace(tr); *ret_tr = tr; } /* Function: P7SmallViterbi() * Date: SRE, Fri Mar 6 15:29:41 1998 [St. Louis] * * Purpose: Wrapper function, for linear memory alignment * with same arguments as P7Viterbi(). * * Calls P7ParsingViterbi to break the sequence * into fragments. Then, based on size of fragments, * calls either P7Viterbi() or P7WeeViterbi() to * get traces for them. Finally, assembles all these * traces together to produce an overall optimal * trace for the sequence. * * If the trace isn't needed for some reason, * all we do is call P7ParsingViterbi. * * Args: dsq - sequence in digitized form * L - length of dsq * hmm - the model * mx - DP matrix, growable * ret_tr - RETURN: traceback; pass NULL if it's not wanted * * Returns: Score of optimal alignment in bits. */ float P7SmallViterbi(unsigned char *dsq, int L, struct plan7_s *hmm, struct dpmatrix_s *mx, struct p7trace_s **ret_tr, int& progress) { struct p7trace_s *ctr; /* collapsed trace of optimal parse */ struct p7trace_s *tr; /* full trace of optimal alignment */ struct p7trace_s **tarr; /* trace array */ int ndom; /* number of subsequences */ int i; /* counter over domains */ int pos; /* position in sequence */ int tpos; /* position in trace */ int tlen; /* length of full trace */ int sqlen; /* length of a subsequence */ int totlen; /* length of L matched by model (as opposed to N/C/J) */ float sc; /* score of optimal alignment */ int t2; /* position in a subtrace */ /* Step 1. Call P7ParsingViterbi to calculate an optimal parse * of the sequence into single-hit subsequences; this parse * is returned in a "collapsed" trace */ sc = P7ParsingViterbi(dsq, L, hmm, &ctr, progress); /* If we don't want full trace, we're done; * also, if parsing viterbi returned a NULL trace we're done. */ if (ctr == NULL || ret_tr == NULL) { P7FreeTrace(ctr); return sc; } /* Step 2. Call either P7Viterbi or P7WeeViterbi on each subsequence * to recover a full traceback of each, collecting them in * an array. */ ndom = ctr->tlen/2 - 1; tarr = (struct p7trace_s **)MallocOrDie(sizeof(struct p7trace_s *) * ndom); tlen = totlen = 0; for (i = 0; i < ndom; i++) { sqlen = ctr->pos[i*2+2] - ctr->pos[i*2+1]; /* length of subseq */ if (P7ViterbiSpaceOK(sqlen, hmm->M, mx)) { SQD_DPRINTF1((" -- using P7Viterbi on an %dx%d subproblem\n", hmm->M, sqlen)); P7Viterbi(dsq + ctr->pos[i*2+1], sqlen, hmm, mx, &(tarr[i])); } else { SQD_DPRINTF1((" -- using P7WeeViterbi on an %dx%d subproblem\n", hmm->M, sqlen)); P7WeeViterbi(dsq + ctr->pos[i*2+1], sqlen, hmm, &(tarr[i])); } tlen += tarr[i]->tlen - 4; /* not counting S->N,...,C->T */ totlen += sqlen; } /* Step 3. Compose the subtraces into one big final trace. * This is wasteful because we're going to TraceDecompose() * it again in both hmmsearch and hmmpfam to look at * individual domains; but we do it anyway so the P7SmallViterbi * interface looks exactly like the P7Viterbi interface. Maybe * long traces shouldn't include all the N/J/C states anyway, * since they're unambiguously implied. */ /* Calculate total trace len and alloc; * nonemitting SNCT + nonemitting J's + emitting NJC */ tlen += 4 + (ndom-1) + (L-totlen); P7AllocTrace(tlen, &tr); tr->tlen = tlen; /* Add N-terminal trace framework */ tr->statetype[0] = STS; tr->nodeidx[0] = 0; tr->pos[0] = 0; tr->statetype[1] = STN; tr->nodeidx[1] = 0; tr->pos[1] = 0; tpos = 2; /* add implied N's */ for (pos = 1; pos <= ctr->pos[1]; pos++) { tr->statetype[tpos] = STN; tr->nodeidx[tpos] = 0; tr->pos[tpos] = pos; tpos++; } /* Add each subseq trace in, with its appropriate * sequence offset derived from the collapsed trace */ for (i = 0; i < ndom; i++) { /* skip SN, CT framework at ends */ for (t2 = 2; t2 < tarr[i]->tlen-2; t2++) { tr->statetype[tpos] = tarr[i]->statetype[t2]; tr->nodeidx[tpos] = tarr[i]->nodeidx[t2]; if (tarr[i]->pos[t2] > 0) tr->pos[tpos] = tarr[i]->pos[t2] + ctr->pos[i*2+1]; else tr->pos[tpos] = 0; tpos++; } /* add nonemitting J or C */ tr->statetype[tpos] = (i == ndom-1) ? STC : STJ; tr->nodeidx[tpos] = 0; tr->pos[tpos] = 0; tpos++; /* add implied emitting J's */ if (i != ndom-1) for (pos = ctr->pos[i*2+2]+1; pos <= ctr->pos[(i+1)*2+1]; pos++) { tr->statetype[tpos] = STJ; tr->nodeidx[tpos] = 0; tr->pos[tpos] = pos; tpos++; } } /* add implied C's */ for (pos = ctr->pos[ndom*2]+1; pos <= L; pos++) { tr->statetype[tpos] = STC; tr->nodeidx[tpos] = 0; tr->pos[tpos] = pos; tpos++; } /* add terminal T */ tr->statetype[tpos] = STT; tr->nodeidx[tpos] = 0; tr->pos[tpos] = 0; tpos++; for (i = 0; i < ndom; i++) P7FreeTrace(tarr[i]); free(tarr); P7FreeTrace(ctr); *ret_tr = tr; return sc; } /* Function: P7ParsingViterbi() * Date: SRE, Wed Mar 4 14:07:31 1998 [St. Louis] * * Purpose: The "hmmfs" linear-memory algorithm for finding * the optimal alignment of a very long sequence to * a looping, multihit (e.g. Plan7) model, parsing it into * a series of nonoverlapping subsequences that match * the model once. Other algorithms (e.g. P7Viterbi() * or P7WeeViterbi()) are applied subsequently to * these subsequences to recover complete alignments. * * The hmmfs algorithm appears briefly in [Durbin98], * but is otherwise unpublished. * * The traceback structure returned is special: a * "collapsed" trace S->B->E->...->B->E->T, where * stateidx is unused and pos is used to indicate the * position of B and E in the sequence. The matched * subsequence is B_pos+1...E_pos. The number of * matches in the trace is (tlen/2)-1. * * Args: dsq - sequence in digitized form * L - length of dsq * hmm - the model (log odds scores ready) * ret_tr - RETURN: a collapsed traceback. * * Returns: Score of the optimal Viterbi alignment, in bits. */ float P7ParsingViterbi(unsigned char *dsq, int L, struct plan7_s *hmm, struct p7trace_s **ret_tr, int& progress) { struct dpmatrix_s *mx; /* two rows of score matrix */ struct dpmatrix_s *tmx; /* two rows of misused score matrix: traceback ptrs */ struct p7trace_s *tr; /* RETURN: collapsed traceback */ int **xmx, **mmx, **dmx, **imx; /* convenience ptrs to score matrix */ int **xtr, **mtr, **dtr, **itr; /* convenience ptrs to traceback pointers */ int *btr, *etr; /* O(L) trace ptrs for B, E state pts in seq */ int sc; /* integer score of optimal alignment */ int i,k,tpos; /* index for seq, model, trace position */ int cur, prv; /* indices for rolling dp matrix */ int curralloc; /* size of allocation for tr */ /* Alloc a DP matrix and traceback pointers, two rows each, O(M). * Alloc two O(L) arrays to trace back through the sequence thru B and E. */ mx = AllocPlan7Matrix(2, hmm->M, &xmx, &mmx, &imx, &dmx); tmx = AllocPlan7Matrix(2, hmm->M, &xtr, &mtr, &itr, &dtr); btr = (int*)MallocOrDie(sizeof(int) * (L+1)); etr = (int*)MallocOrDie(sizeof(int) * (L+1)); /* Initialization of the zero row. */ xmx[0][XMN] = 0; /* S->N, p=1 */ xmx[0][XMB] = hmm->xsc[XTN][MOVE]; /* S->N->B, no N-tail */ btr[0] = 0; xmx[0][XME] = xmx[0][XMC] = xmx[0][XMJ] = -INFTY; /* need seq to get here */ etr[0] = -1; for (k = 0; k <= hmm->M; k++) mmx[0][k] = imx[0][k] = dmx[0][k] = -INFTY; /* need seq to get here */ /* Recursion. Done as a pull. Rolling index trick. Trace ptr propagation trick. * Note some slightly wasteful boundary conditions: * tsc[0] = -INFTY for all eight transitions (no node 0) * D_M and I_M are wastefully calculated (they don't exist) * * Notes on traceback pointer propagation. * - In the path B->E, we propagate the i that B was aligned to in the optimal * alignment, via mtr, dtr, and itr. * - When we reach an E, we record the i of the B it started from in etr. * - In a looping path E->J...->B or terminal path E->C...->T, we propagate * the i that E was aligned to in the optimal alignment via xtr[][XMC] * and xtr[][XMJ]. * - When we enter B, we record the i of the best previous E, or 0 if there * isn't one, in btr. */ for (i = 1; i <= L; i++) { cur = i % 2; prv = !cur; mmx[cur][0] = imx[cur][0] = dmx[cur][0] = -INFTY; for (k = 1; k <= hmm->M; k++) { /* match state */ mmx[cur][k] = -INFTY; if ((sc = mmx[prv][k-1] + hmm->tsc[TMM][k-1]) > -INFTY) { mmx[cur][k] = sc; mtr[cur][k] = mtr[prv][k-1]; } if ((sc = imx[prv][k-1] + hmm->tsc[TIM][k-1]) > mmx[cur][k]) { mmx[cur][k] = sc; mtr[cur][k] = itr[prv][k-1]; } if ((sc = xmx[prv][XMB] + hmm->bsc[k]) > mmx[cur][k]) { mmx[cur][k] = sc; mtr[cur][k] = i-1; } if ((sc = dmx[prv][k-1] + hmm->tsc[TDM][k-1]) > mmx[cur][k]) { mmx[cur][k] = sc; mtr[cur][k] = dtr[prv][k-1]; } if (hmm->msc[dsq[i]][k] != -INFTY) mmx[cur][k] += hmm->msc[dsq[i]][k]; else mmx[cur][k] = -INFTY; /* delete state */ dmx[cur][k] = -INFTY; if ((sc = mmx[cur][k-1] + hmm->tsc[TMD][k-1]) > -INFTY) { dmx[cur][k] = sc; dtr[cur][k] = mtr[cur][k-1]; } if ((sc = dmx[cur][k-1] + hmm->tsc[TDD][k-1]) > dmx[cur][k]) { dmx[cur][k] = sc; dtr[cur][k] = dtr[cur][k-1]; } /* insert state */ if (k < hmm->M) { imx[cur][k] = -INFTY; if ((sc = mmx[prv][k] + hmm->tsc[TMI][k]) > -INFTY) { imx[cur][k] = sc; itr[cur][k] = mtr[prv][k]; } if ((sc = imx[prv][k] + hmm->tsc[TII][k]) > imx[cur][k]) { imx[cur][k] = sc; itr[cur][k] = itr[prv][k]; } if (hmm->isc[dsq[i]][k] != -INFTY) imx[cur][k] += hmm->isc[dsq[i]][k]; else imx[cur][k] = -INFTY; } } /* Now the special states. Order is important here. * remember, C and J emissions are zero score by definition, */ /* N state */ xmx[cur][XMN] = -INFTY; if ((sc = xmx[prv][XMN] + hmm->xsc[XTN][LOOP]) > -INFTY) xmx[cur][XMN] = sc; /* E state */ xmx[cur][XME] = -INFTY; for (k = 1; k <= hmm->M; k++) if ((sc = mmx[cur][k] + hmm->esc[k]) > xmx[cur][XME]) { xmx[cur][XME] = sc; etr[i] = mtr[cur][k]; } /* J state */ xmx[cur][XMJ] = -INFTY; if ((sc = xmx[prv][XMJ] + hmm->xsc[XTJ][LOOP]) > -INFTY) { xmx[cur][XMJ] = sc; xtr[cur][XMJ] = xtr[prv][XMJ]; } if ((sc = xmx[cur][XME] + hmm->xsc[XTE][LOOP]) > xmx[cur][XMJ]) { xmx[cur][XMJ] = sc; xtr[cur][XMJ] = i; } /* B state */ xmx[cur][XMB] = -INFTY; if ((sc = xmx[cur][XMN] + hmm->xsc[XTN][MOVE]) > -INFTY) { xmx[cur][XMB] = sc; btr[i] = 0; } if ((sc = xmx[cur][XMJ] + hmm->xsc[XTJ][MOVE]) > xmx[cur][XMB]) { xmx[cur][XMB] = sc; btr[i] = xtr[cur][XMJ]; } /* C state */ xmx[cur][XMC] = -INFTY; if ((sc = xmx[prv][XMC] + hmm->xsc[XTC][LOOP]) > -INFTY) { xmx[cur][XMC] = sc; xtr[cur][XMC] = xtr[prv][XMC]; } if ((sc = xmx[cur][XME] + hmm->xsc[XTE][MOVE]) > xmx[cur][XMC]) { xmx[cur][XMC] = sc; xtr[cur][XMC] = i; } progress = int(100*float(i)/L); } /* T state (not stored) */ sc = xmx[cur][XMC] + hmm->xsc[XTC][MOVE]; /***************************************************************** * Collapsed traceback stage. * xtr[L%2][XMC] contains the position j of the previous E * etr[j] contains the position i of the previous B * btr[i] contains the position j of the previous E, or 0 * continue until btr[i] = 0. *****************************************************************/ curralloc = 2; /* minimum: no hits */ P7AllocTrace(curralloc, &tr); /* Init of collapsed trace. Back to front; we ReverseTrace() later. */ tpos = 0; tr->statetype[tpos] = STT; tr->pos[tpos] = 0; i = xtr[L%2][XMC]; while (i > 0) { curralloc += 2; P7ReallocTrace(tr, curralloc); tpos++; tr->statetype[tpos] = STE; tr->pos[tpos] = i; i = etr[i]; tpos++; tr->statetype[tpos] = STB; tr->pos[tpos] = i; i = btr[i]; } tpos++; tr->statetype[tpos] = STS; tr->pos[tpos] = 0; tr->tlen = tpos + 1; P7ReverseTrace(tr); FreePlan7Matrix(mx); FreePlan7Matrix(tmx); free(btr); free(etr); *ret_tr = tr; return Scorify(sc); } /* Function: P7WeeViterbi() * Date: SRE, Wed Mar 4 08:24:04 1998 [St. Louis] * * Purpose: Hirschberg/Myers/Miller linear memory alignment. * See [Hirschberg75,MyM-88a] for the idea of the algorithm. * Adapted to HMM implementation. * * Requires that you /know/ that there's only * one hit to the model in the sequence: either * because you're forcing single-hit, or you've * previously called P7ParsingViterbi to parse * the sequence into single-hit segments. The reason * for this is that a cyclic model (a la Plan7) * defeats the nice divide and conquer trick. * (I think some trickery with propagated trace pointers * could get around this but haven't explored it.) * This is implemented by ignoring transitions * to/from J state. * * Args: dsq - sequence in digitized form * L - length of dsq * hmm - the model * ret_tr - RETURN: traceback. * * Returns: Score of the optimal Viterbi alignment. */ float P7WeeViterbi(unsigned char *dsq, int L, struct plan7_s *hmm, struct p7trace_s **ret_tr) { struct p7trace_s *tr; /* RETURN: traceback */ int *kassign; /* 0..L+1, alignment of seq positions to model nodes */ char *tassign; /* 0..L+1, alignment of seq positions to state types */ int *endlist; /* stack of end points on sequence to work on */ int *startlist; /* stack of start points on sequence to work on */ int lpos; /* position in endlist, startlist */ int k1, k2, k3; /* start, mid, end in model */ char t1, t2, t3; /* start, mid, end in state type */ int s1, s2, s3; /* start, mid, end in sequence */ float sc; /* score of segment optimal alignment */ float ret_sc; /* optimal score over complete seq */ int tlen; /* length needed for trace */ int i, k, tpos; /* index in sequence, model, trace */ /* Initialize. */ kassign = (int*) MallocOrDie (sizeof(int) * (L+1)); tassign = (char*)MallocOrDie (sizeof(char)* (L+1)); endlist = (int*) MallocOrDie (sizeof(int) * (L+1)); startlist = (int*) MallocOrDie (sizeof(int) * (L+1)); lpos = 0; startlist[lpos] = 1; endlist[lpos] = L; kassign[1] = 1; kassign[L] = hmm->M; tassign[1] = STS; /* temporary boundary condition! will become N or M */ tassign[L] = STT; /* temporary boundary condition! will become M or C */ /* Recursive divide-and-conquer alignment. */ while (lpos >= 0) { /* Pop a segment off the stack */ s1 = startlist[lpos]; k1 = kassign[s1]; t1 = tassign[s1]; s3 = endlist[lpos]; k3 = kassign[s3]; t3 = tassign[s3]; lpos--; /* find optimal midpoint of segment */ sc = get_wee_midpt(hmm, dsq, L, k1, t1, s1, k3, t3, s3, &k2, &t2, &s2); kassign[s2] = k2; tassign[s2] = t2; /* score is valid on first pass */ if (t1 == STS && t3 == STT) ret_sc = sc; /* push N-terminal segment on stack */ if (t2 != STN && (s2 - s1 > 1 || (s2 - s1 == 1 && t1 == STS))) { lpos++; startlist[lpos] = s1; endlist[lpos] = s2; } /* push C-terminal segment on stack */ if (t2 != STC && (s3 - s2 > 1 || (s3 - s2 == 1 && t3 == STT))) { lpos++; startlist[lpos] = s2; endlist[lpos] = s3; } if (t2 == STN) { /* if we see STN midpoint, we know the whole N-term is STN */ for (; s2 >= s1; s2--) { kassign[s2] = 1; tassign[s2] = STN; } } if (t2 == STC) { /* if we see STC midpoint, we know whole C-term is STC */ for (; s2 <= s3; s2++) { kassign[s2] = hmm->M; tassign[s2] = STC; } } } /***************************************************************** * Construct a traceback structure from kassign/tassign by interpolating * necessary states. * Trace allocation is as follows. We clearly need L emitting states. * We also need nonemitting states as follows: * STS,STN,STB,STE,STC,STT = 6 * STD: count k2-k1-1 in kassign M->M's * Also, count N->M's and M->C's (potential wing unfoldings)... * ...and be careful to check wing unfoldings when there aren't * any emitting N or C flanks! (bugfix, 2.1.1b) *****************************************************************/ tlen = L + 6; for (i = 1; i < L; i++) { if (tassign[i] == STM && tassign[i+1] == STM) tlen += kassign[i+1] - kassign[i] - 1; if (tassign[i] == STN && tassign[i+1] == STM) tlen += kassign[i+1] - 1; if (tassign[i] == STM && tassign[i+1] == STC) tlen += hmm->M - kassign[i]; } if (tassign[1] == STM) tlen += kassign[1] - 1; if (tassign[L] == STM) tlen += hmm->M - kassign[L]; P7AllocTrace(tlen, &tr); tr->statetype[0] = STS; tr->nodeidx[0] = 0; tr->pos[0] = 0; tr->statetype[1] = STN; tr->nodeidx[1] = 0; tr->pos[1] = 0; tpos = 2; for (i = 1; i <= L; i++) { switch(tassign[i]) { case STM: /* check for first match state */ if (tr->statetype[tpos-1] == STN) { tr->statetype[tpos] = STB; tr->nodeidx[tpos] = 0; tr->pos[tpos] = 0; tpos++; /* check for wing unfolding */ if (Prob2Score(hmm->begin[kassign[i]], hmm->p1) + INTSCALE <= hmm->bsc[kassign[i]]) for (k = 1; k < kassign[i]; k++) { tr->statetype[tpos] = STD; tr->nodeidx[tpos] = k; tr->pos[tpos] = 0; tpos++; } } /* do the match state itself */ tr->statetype[tpos] = STM; tr->nodeidx[tpos] = kassign[i]; tr->pos[tpos] = i; tpos++; /* do any deletes necessary 'til next match */ if (i < L && tassign[i+1] == STM && kassign[i+1] - kassign[i] > 1) for (k = kassign[i] + 1; k < kassign[i+1]; k++) { tr->statetype[tpos] = STD; tr->nodeidx[tpos] = k; tr->pos[tpos] = 0; tpos++; } /* check for last match state */ if (i == L || tassign[i+1] == STC) { /* check for wing unfolding */ if (Prob2Score(hmm->end[kassign[i-1]], 1.) + INTSCALE <= hmm->esc[kassign[i-1]]) for (k = kassign[i]+1; k <= hmm->M; k++) { tr->statetype[tpos] = STD; tr->nodeidx[tpos] = k; tr->pos[tpos] = 0; tpos++; } /* add on the end state */ tr->statetype[tpos] = STE; tr->nodeidx[tpos] = 0; tr->pos[tpos] = 0; tpos++; /* and a nonemitting C state */ tr->statetype[tpos] = STC; tr->nodeidx[tpos] = 0; tr->pos[tpos] = 0; tpos++; } break; case STI: tr->statetype[tpos] = STI; tr->nodeidx[tpos] = kassign[i]; tr->pos[tpos] = i; tpos++; break; case STN: tr->statetype[tpos] = STN; tr->nodeidx[tpos] = 0; tr->pos[tpos] = i; tpos++; break; case STC: tr->statetype[tpos] = STC; tr->nodeidx[tpos] = 0; tr->pos[tpos] = i; tpos++; break; default: Die("Bogus state %s", Statetype(tassign[i])); } } /* terminate the trace */ tr->statetype[tpos] = STT; tr->nodeidx[tpos] = 0; tr->pos[tpos] = 0; tr->tlen = tpos+1; *ret_tr = tr; free(kassign); free(tassign); free(startlist); free(endlist); return ret_sc; } /* Function: Plan7ESTViterbi() * * Purpose: Frameshift-tolerant alignment of protein model to cDNA EST. * * */ float Plan7ESTViterbi(unsigned char *dsq, int L, struct plan7_s *hmm, struct dpmatrix_s **ret_mx) { struct dpmatrix_s *mx; int **xmx; int **mmx; int **imx; int **dmx; int i,k; int sc; int codon; /* Allocate a DP matrix with 0..L rows, 0..M+1 columns. */ mx = AllocPlan7Matrix(L+1, hmm->M, &xmx, &mmx, &imx, &dmx); /* Initialization of the zero row (DNA sequence of length 0) * Note that xmx[i][stN] = 0 by definition for all i, * and xmx[i][stT] = xmx[i][stC], so neither stN nor stT need * to be calculated in DP matrices. */ xmx[0][XMN] = 0; /* S->N, p=1 */ xmx[0][XMB] = hmm->xsc[XTN][MOVE]; /* S->N->B, no N-tail */ xmx[0][XME] = xmx[0][XMC] = xmx[0][XMJ] = -INFTY; /* need seq to get here */ for (k = 0; k <= hmm->M; k++) mmx[0][k] = imx[0][k] = dmx[0][k] = -INFTY; /* need seq to get here */ /* Initialization of the first row (DNA sequence of length 1); * only N state can make this nucleotide. */ xmx[1][XMN] = xmx[0][XMN] + hmm->xsc[XTN][LOOP]; xmx[1][XMB] = xmx[1][XMN] + hmm->xsc[XTN][MOVE]; xmx[0][XME] = xmx[0][XMC] = xmx[0][XMJ] = -INFTY; /* need 2 nt to get here */ for (k = 0; k <= hmm->M; k++) mmx[0][k] = imx[0][k] = dmx[0][k] = -INFTY; /* need 2 nt to get into model */ /* Recursion. Done as a pull. * Note some slightly wasteful boundary conditions: * tsc[0] = -INFTY for all eight transitions (no node 0) * D_M and I_M are wastefully calculated (they don't exist) */ for (i = 2; i <= L; i++) { mmx[i][0] = imx[i][0] = dmx[i][0] = -INFTY; /* crude calculation of lookup value for codon */ if (i > 2) { if (dsq[i-2] < 4 && dsq[i-1] < 4 && dsq[i] < 4) codon = dsq[i-2] * 16 + dsq[i-1] * 4 + dsq[i]; else codon = 64; /* ambiguous codon; punt */ } for (k = 1; k <= hmm->M; k++) { /* match state */ if (i > 2) { mmx[i][k] = mmx[i-3][k-1] + hmm->tsc[TMM][k-1]; if ((sc = imx[i-3][k-1] + hmm->tsc[TIM][k-1]) > mmx[i][k]) mmx[i][k] = sc; if ((sc = xmx[i-3][XMB] + hmm->bsc[k]) > mmx[i][k]) mmx[i][k] = sc; if ((sc = dmx[i-3][k-1] + hmm->tsc[TDM][k-1]) > mmx[i][k]) mmx[i][k] = sc; mmx[i][k] += hmm->dnam[codon][k]; } /* -1 frameshifts into match state */ if ((sc = mmx[i-2][k-1] + hmm->tsc[TMM][k-1] + hmm->dna2) > mmx[i][k]) mmx[i][k] = sc; if ((sc = imx[i-2][k-1] + hmm->tsc[TIM][k-1] + hmm->dna2) > mmx[i][k]) mmx[i][k] = sc; if ((sc = xmx[i-2][XMB] + hmm->bsc[k] + hmm->dna2) > mmx[i][k]) mmx[i][k] = sc; if ((sc = dmx[i-2][k-1] + hmm->tsc[TDM][k-1] + hmm->dna2) > mmx[i][k]) mmx[i][k] = sc; /* +1 frameshifts into match state */ if (i > 3) { if ((sc = mmx[i-4][k-1] + hmm->tsc[TMM][k-1] + hmm->dna4) > mmx[i][k]) mmx[i][k] = sc; if ((sc = imx[i-4][k-1] + hmm->tsc[TIM][k-1] + hmm->dna4) > mmx[i][k]) mmx[i][k] = sc; if ((sc = xmx[i-4][XMB] + hmm->bsc[k] + hmm->dna4) > mmx[i][k]) mmx[i][k] = sc; if ((sc = dmx[i-4][k-1] + hmm->tsc[TDM][k-1] + hmm->dna4) > mmx[i][k]) mmx[i][k] = sc; } /* delete state */ dmx[i][k] = mmx[i][k-1] + hmm->tsc[TMD][k-1]; if ((sc = dmx[i][k-1] + hmm->tsc[TDD][k-1]) > dmx[i][k]) dmx[i][k] = sc; /* insert state */ if (i > 2) { imx[i][k] = mmx[i-3][k] + hmm->tsc[TMI][k]; if ((sc = imx[i-3][k] + hmm->tsc[TII][k]) > imx[i][k]) imx[i][k] = sc; imx[i][k] += hmm->dnai[codon][k]; } /* -1 frameshifts into insert state */ if ((sc = mmx[i-2][k] + hmm->tsc[TMI][k] + hmm->dna2) > imx[i][k]) imx[i][k] = sc; if ((sc = imx[i-2][k] + hmm->tsc[TII][k] + hmm->dna2) > imx[i][k]) imx[i][k] = sc; /* +1 frameshifts into insert state */ if (i > 4) { if ((sc = mmx[i-4][k] + hmm->tsc[TMI][k] + hmm->dna4) > imx[i][k]) imx[i][k] = sc; if ((sc = imx[i-4][k] + hmm->tsc[TII][k] + hmm->dna4) > imx[i][k]) imx[i][k] = sc; } } /* Now the special states. Order is important here. * remember, C and J emissions are zero score by definition, */ /* N state: +1 nucleotide */ xmx[i][XMN] = xmx[i-1][XMN] + hmm->xsc[XTN][LOOP]; /* E state: collect from M's, and last D */ xmx[i][XME] = dmx[i][hmm->M]; /* transition prob from last D = 1.0 */ for (k = 1; k <= hmm->M; k++) if ((sc = mmx[i][k] + hmm->esc[k]) > xmx[i][XME]) xmx[i][XME] = sc; /* J state: +1 nucleotide */ xmx[i][XMJ] = xmx[i-1][XMJ] + hmm->xsc[XTJ][LOOP]; if ((sc = xmx[i][XME] + hmm->xsc[XTE][LOOP]) > xmx[i][XMJ]) xmx[i][XMJ] = sc; /* B state: collect from N,J */ xmx[i][XMB] = xmx[i][XMN] + hmm->xsc[XTN][MOVE]; if ((sc = xmx[i][XMJ] + hmm->xsc[XTJ][MOVE]) > xmx[i][XMB]) xmx[i][XMB] = sc; /* C state: +1 nucleotide */ xmx[i][XMC] = xmx[i-1][XMC] + hmm->xsc[XTC][LOOP]; if ((sc = xmx[i][XME] + hmm->xsc[XTE][MOVE]) > xmx[i][XMC]) xmx[i][XMC] = sc; } sc = xmx[L][XMC] + hmm->xsc[XTC][MOVE]; if (ret_mx != NULL) *ret_mx = mx; else FreePlan7Matrix(mx); return Scorify(sc); /* the total Viterbi score. */ } /* Function: get_wee_midpt() * Date: SRE, Wed Mar 4 08:27:11 1998 [St. Louis] * * Purpose: The heart of the divide and conquer algorithm * for P7WeeViterbi(). This function is called * recursively to find successive optimal midpoints * in the alignment matrix. See P7WeeViterbi() for * further comments on the assumptions of this algorithm. * * Args: hmm - the model, set up for integer scores * dsq - the sequence, digitized * L - length of the sequence * k1 - model node to start with, 1..M * t1 - state type to start with, STM | STI | STN | STC; STS to start * s1 - sequence position to start with, 1..L; 1 to start * k3 - model node to end with, 1..M * t3 - state type to end with, STM | STI | STN | STC; STT to start * s3 - sequence position to end with, 1..L; L to start * ret_k2 - RETURN: optimal midpoint, node position in model * ret_t2 - RETURN: optimal midpoint, state type * ret_s2 - RETURN: optimal midpoint, sequence position * * Returns: score of optimal alignment, in bits. */ static float get_wee_midpt(struct plan7_s *hmm, unsigned char *dsq, int L, int k1, char t1, int s1, int k3, char t3, int s3, int *ret_k2, char *ret_t2, int *ret_s2) { struct dpmatrix_s *fwd; struct dpmatrix_s *bck; int **xmx; /* convenience ptr into special states */ int **mmx; /* convenience ptr into match states */ int **imx; /* convenience ptr into insert states */ int **dmx; /* convenience ptr into delete states */ int k2; char t2; int s2; int cur, prv, nxt; /* current, previous, next row index (0 or 1)*/ int i,k; /* indices for seq, model */ int sc; /* integer score */ int max; /* maximum integer score */ int start; /* s1 to start at (need, for STS special case) */ /* Choose our midpoint. * Special cases: s1, s3 adjacent and t1 == STS: s2 = s1 * s1, s3 adjacent and t3 == STT: s2 = s3 * (where we must replace STS, STT eventually) */ s2 = s1 + (s3-s1) / 2; if (s3-s1 == 1 && t1 == STS) s2 = s1; if (s3-s1 == 1 && t3 == STT) s2 = s3; /* STS is a special case. STS aligns to row zero by convention, * but we'll be passed s1=1, t1=STS. We have to init on row * zero then start DP on row 1. */ start = (t1 == STS) ? 0 : s1; /* Allocate our forward two rows. * Initialize row zero. */ fwd = AllocPlan7Matrix(2, hmm->M, &xmx, &mmx, &imx, &dmx); cur = start%2; xmx[cur][XMN] = xmx[cur][XMB] = -INFTY; xmx[cur][XME] = xmx[cur][XMC] = -INFTY; for (k = k1; k <= k3; k++) mmx[cur][k] = imx[cur][k] = dmx[cur][k] = -INFTY; /* Where to put our zero for our start point... * (only possible to start on an emitting state; J disallowed) */ switch (t1) { case STM: mmx[cur][k1] = 0; break; case STI: imx[cur][k1] = 0; break; case STN: xmx[cur][XMN] = 0; break; case STC: xmx[cur][XMC] = 0; break; case STS: xmx[cur][XMN] = 0; break; default: Die("you can't init get_wee_midpt with a %s\n", Statetype(t1)); } /* Still initializing. * Deal with pulling horizontal matrix moves in initial row. * These are any transitions to nonemitters: * STM-> E, D * STI-> none * STN-> B * STC-> (T, but we never observe this in the forward pass of a d&c) * STE-> C * STS-> (N, already implied by setting xmx[cur][XMN] = 0) * STB-> M */ if (t1 == STM) { for (k = k1+1; k <= k3; k++) { /* transits into STD */ dmx[cur][k] = -INFTY; if ((sc = mmx[cur][k-1] + hmm->tsc[TMD][k-1]) > -INFTY) dmx[cur][k] = sc; if ((sc = dmx[cur][k-1] + hmm->tsc[TDD][k-1]) > dmx[cur][k]) dmx[cur][k] = sc; } /* transit into STE */ xmx[cur][XME] = -INFTY; if ((sc = mmx[cur][k1] + hmm->esc[k1]) > -INFTY) xmx[cur][XME] = sc; } /* transit into STB from STN */ xmx[cur][XMB] = -INFTY; if ((sc = xmx[cur][XMN] + hmm->xsc[XTN][MOVE]) > -INFTY) xmx[cur][XMB] = sc; /* transit into STC from STE */ xmx[cur][XMC] = -INFTY; if ((sc = xmx[cur][XME] + hmm->xsc[XTE][MOVE]) > -INFTY) xmx[cur][XMC] = sc; /* Done initializing. * Start recursive DP; sweep forward to chosen s2 midpoint. Done as a pull. */ for (i = start+1; i <= s2; i++) { cur = i % 2; prv = !cur; mmx[cur][k1] = imx[cur][k1] = dmx[cur][k1] = -INFTY; /* Insert state in column k1, and B->M transition in k1. */ if (k1 < hmm->M) { imx[cur][k1] = -INFTY; if ((sc = mmx[prv][k1] + hmm->tsc[TMI][k1]) > -INFTY) imx[cur][k1] = sc; if ((sc = imx[prv][k1] + hmm->tsc[TII][k1]) > imx[cur][k1]) imx[cur][k1] = sc; if (hmm->isc[dsq[i]][k1] != -INFTY) imx[cur][k1] += hmm->isc[dsq[i]][k1]; else imx[cur][k1] = -INFTY; } if ((sc = xmx[prv][XMB] + hmm->bsc[k1]) > -INFTY) mmx[cur][k1] = sc; if (hmm->msc[dsq[i]][k1] != -INFTY) mmx[cur][k1] += hmm->msc[dsq[i]][k1]; else mmx[cur][k1] = -INFTY; /* Main chunk of recursion across model positions */ for (k = k1+1; k <= k3; k++) { /* match state */ mmx[cur][k] = -INFTY; if ((sc = mmx[prv][k-1] + hmm->tsc[TMM][k-1]) > -INFTY) mmx[cur][k] = sc; if ((sc = imx[prv][k-1] + hmm->tsc[TIM][k-1]) > mmx[cur][k]) mmx[cur][k] = sc; if ((sc = xmx[prv][XMB] + hmm->bsc[k]) > mmx[cur][k]) mmx[cur][k] = sc; if ((sc = dmx[prv][k-1] + hmm->tsc[TDM][k-1]) > mmx[cur][k]) mmx[cur][k] = sc; if (hmm->msc[dsq[i]][k] != -INFTY) mmx[cur][k] += hmm->msc[dsq[i]][k]; else mmx[cur][k] = -INFTY; /* delete state */ dmx[cur][k] = -INFTY; if (k < hmm->M) { if ((sc = mmx[cur][k-1] + hmm->tsc[TMD][k-1]) > -INFTY) dmx[cur][k] = sc; if ((sc = dmx[cur][k-1] + hmm->tsc[TDD][k-1]) > dmx[cur][k]) dmx[cur][k] = sc; } /* insert state */ imx[cur][k] = -INFTY; if (k < hmm->M) { if ((sc = mmx[prv][k] + hmm->tsc[TMI][k]) > -INFTY) imx[cur][k] = sc; if ((sc = imx[prv][k] + hmm->tsc[TII][k]) > imx[cur][k]) imx[cur][k] = sc; if (hmm->isc[dsq[i]][k] != -INFTY) imx[cur][k] += hmm->isc[dsq[i]][k]; else imx[cur][k] = -INFTY; } } /* N state */ xmx[cur][XMN] = -INFTY; if ((sc = xmx[prv][XMN] + hmm->xsc[XTN][LOOP]) > -INFTY) xmx[cur][XMN] = sc; /* E state */ xmx[cur][XME] = -INFTY; for (k = k1; k <= k3 && k <= hmm->M; k++) if ((sc = mmx[cur][k] + hmm->esc[k]) > xmx[cur][XME]) xmx[cur][XME] = sc; /* B state */ xmx[cur][XMB] = -INFTY; if ((sc = xmx[cur][XMN] + hmm->xsc[XTN][MOVE]) > -INFTY) xmx[cur][XMB] = sc; /* C state */ xmx[cur][XMC] = -INFTY; if ((sc = xmx[prv][XMC] + hmm->xsc[XTC][LOOP]) > -INFTY) xmx[cur][XMC] = sc; if ((sc = xmx[cur][XME] + hmm->xsc[XTE][MOVE]) > xmx[cur][XMC]) xmx[cur][XMC] = sc; } /* Row s2%2 in fwd matrix now contains valid scores from s1 (start) to s2, * with J transitions disallowed (no cycles through model). */ /***************************************************************** * Backwards pass. *****************************************************************/ /* Allocate our backwards two rows. Init last row. */ bck = AllocPlan7Matrix(2, hmm->M, &xmx, &mmx, &imx, &dmx); nxt = s3%2; xmx[nxt][XMN] = xmx[nxt][XMB] = -INFTY; xmx[nxt][XME] = xmx[nxt][XMC] = -INFTY; for (k = k1; k <= k3 + 1; k++) mmx[nxt][k] = imx[nxt][k] = dmx[nxt][k] = -INFTY; cur = !nxt; mmx[cur][k3+1] = imx[cur][k3+1] = dmx[cur][k3+1] = -INFTY; /* Where to put the zero for our end point on last row. */ switch (t3) { case STM: mmx[nxt][k3] = 0; break; case STI: imx[nxt][k3] = 0; break; case STN: xmx[nxt][XMN] = 0; break; case STC: xmx[nxt][XMC] = 0; break; /* must be an emitting C */ case STT: xmx[nxt][XMC] = hmm->xsc[XTC][MOVE]; break; /* C->T implied */ default: Die("you can't init get_wee_midpt with a %s\n", Statetype(t3)); } /* Still initializing. * In the case t3==STT, there are a few horizontal moves possible * on row s3, because STT isn't an emitter. All other states are * emitters, so their connections have to be to the previous row s3-1. */ if (t3 == STT) { /* E->C */ xmx[nxt][XME] = xmx[nxt][XMC] + hmm->xsc[XTE][MOVE]; /* M->E */ for (k = k3; k >= k1; k--) { mmx[nxt][k] = xmx[nxt][XME] + hmm->esc[k]; if (s3 != s2) mmx[nxt][k] += hmm->msc[dsq[s3]][k]; } } /* Start recursive DP; sweep backwards to chosen s2 midpoint. * Done as a pull. M, I scores at current row do /not/ include * emission scores. Be careful of integer underflow. */ for (i = s3-1; i >= s2; i--) { /* note i < L, so i+1 is always a legal index */ cur = i%2; nxt = !cur; /* C pulls from C (T is special cased) */ xmx[cur][XMC] = -INFTY; if ((sc = xmx[nxt][XMC] + hmm->xsc[XTC][LOOP]) > -INFTY) xmx[cur][XMC] = sc; /* B pulls from M's */ xmx[cur][XMB] = -INFTY; for (k = k1; k <= k3; k++) if ((sc = mmx[nxt][k] + hmm->bsc[k]) > xmx[cur][XMB]) xmx[cur][XMB] = sc; /* E pulls from C (J disallowed) */ xmx[cur][XME] = -INFTY; if ((sc = xmx[cur][XMC] + hmm->xsc[XTE][MOVE]) > -INFTY) xmx[cur][XME] = sc; /* N pulls from B, N */ xmx[cur][XMN] = -INFTY; if ((sc = xmx[cur][XMB] + hmm->xsc[XTN][MOVE]) > -INFTY) xmx[cur][XMN] = sc; if ((sc = xmx[nxt][XMN] + hmm->xsc[XTN][LOOP]) > xmx[cur][XMN]) xmx[cur][XMN] = sc; /* Main recursion across model */ for (k = k3; k >= k1; k--) { /* special case k == M */ if (k == hmm->M) { mmx[cur][k] = xmx[cur][XME]; /* p=1 transition to E by definition */ dmx[cur][k] = -INFTY; /* doesn't exist */ imx[cur][k] = -INFTY; /* doesn't exist */ if (i != s2) mmx[cur][k] += hmm->msc[dsq[i]][k]; continue; } /* below this k < M, so k+1 is a legal index */ /* pull into match state */ mmx[cur][k] = -INFTY; if ((sc = xmx[cur][XME] + hmm->esc[k]) > -INFTY) mmx[cur][k] = sc; if ((sc = mmx[nxt][k+1] + hmm->tsc[TMM][k]) > mmx[cur][k]) mmx[cur][k] = sc; if ((sc = imx[nxt][k] + hmm->tsc[TMI][k]) > mmx[cur][k]) mmx[cur][k] = sc; if ((sc = dmx[cur][k+1] + hmm->tsc[TMD][k]) > mmx[cur][k]) mmx[cur][k] = sc; if (i != s2) mmx[cur][k] += hmm->msc[dsq[i]][k]; /* pull into delete state */ dmx[cur][k] = -INFTY; if ((sc = mmx[nxt][k+1] + hmm->tsc[TDM][k]) > -INFTY) dmx[cur][k] = sc; if ((sc = dmx[cur][k+1] + hmm->tsc[TDD][k]) > dmx[cur][k]) dmx[cur][k] = sc; /* pull into insert state */ imx[cur][k] = -INFTY; if ((sc = mmx[nxt][k+1] + hmm->tsc[TIM][k]) > -INFTY) imx[cur][k] = sc; if ((sc = imx[nxt][k] + hmm->tsc[TII][k]) > imx[cur][k]) imx[cur][k] = sc; if (i != s2) imx[cur][k] += hmm->isc[dsq[i]][k]; } } /***************************************************************** * DP complete; we have both forward and backward passes. Now we * look across the s2 row and find the optimal emitting state. *****************************************************************/ cur = s2%2; max = -INFTY; for (k = k1; k <= k3; k++) { if ((sc = fwd->mmx[cur][k] + bck->mmx[cur][k]) > max) { k2 = k; t2 = STM; max = sc; } if ((sc = fwd->imx[cur][k] + bck->imx[cur][k]) > max) { k2 = k; t2 = STI; max = sc; } } if ((sc = fwd->xmx[cur][XMN] + bck->xmx[cur][XMN]) > max) { k2 = 1; t2 = STN; max = sc; } if ((sc = fwd->xmx[cur][XMC] + bck->xmx[cur][XMC]) > max) { k2 = hmm->M; t2 = STC; max = sc; } /***************************************************************** * Garbage collection, return. *****************************************************************/ FreePlan7Matrix(fwd); FreePlan7Matrix(bck); *ret_k2 = k2; *ret_t2 = t2; *ret_s2 = s2; return Scorify(max); } /* Function: P7ViterbiAlignAlignment() * Date: SRE, Sat Jul 4 13:39:00 1998 [St. Louis] * * Purpose: Align a multiple alignment to an HMM without * changing the multiple alignment itself. * Adapted from P7Viterbi(). * * Heuristic; not a guaranteed optimal alignment. * Guaranteeing an optimal alignment appears difficult. * [cryptic note to myself:] In paths connecting to I* metastates, * recursion breaks down; if there is a gap in the * previous column for a given seq, we can't determine what state the * I* metastate corresponds to for this sequence, unless we * look back in the DP matrix. The lookback would either involve * recursing back to the previous M* metastate (giving a * O(MN^2) algorithm instead of O(MN)) or expanding the I* * metastate into 3^nseq separate I* metastates to keep track * of which of three states each seq is in. Since the second * option blows up exponentially w/ nseq, it is not attractive. * If the first option were used, the correct algorithm would be related to * modelmakers.c:Maxmodelmaker(), but somewhat more difficult. * * The heuristic approach here is to calculate a "consensus" * sequence from the alignment, and align the consensus to the HMM. * Some hackery is employed, weighting transitions and emissions * to make things work (re: con and mocc arrays). * * Args: aseq - aligned sequences * ainfo - info for aseqs (includes alen, nseq, wgt) * hmm - model to align to * * Returns: Traceback. Caller must free with P7FreeTrace(). * pos[] contains alignment columns, indexed 1..alen. * statetype[] contains metastates M*, etc. as STM, etc. */ struct p7trace_s * P7ViterbiAlignAlignment(MSA *msa, struct plan7_s *hmm) { struct dpmatrix_s *mx; /* Viterbi calculation lattice (two rows) */ struct dpshadow_s *tb; /* shadow matrix of traceback pointers */ struct p7trace_s *tr; /* RETURN: traceback */ int **xmx, **mmx, **imx, **dmx; char **xtb, **mtb, **itb, **dtb; float **con; /* [1..alen][0..Alphabet_size-1], consensus counts */ float *mocc; /* fractional occupancy of a column; used to weight transitions */ int i; /* counter for columns */ int k; /* counter for model positions */ int idx; /* counter for seqs */ int sym; /* counter for alphabet symbols */ int sc; /* temp variable for holding score */ float denom; /* total weight of seqs; used to "normalize" counts */ int cur, prv; //get HMMERTaskLocalData HMMERTaskLocalData *tld = getHMMERTaskLocalData(); alphabet_s *al = &tld->al; /* The "consensus" is a counts matrix, [1..alen][0..Alphabet_size-1]. * Gaps are not counted explicitly, but columns with lots of gaps get * less total weight because they have fewer counts. */ /* allocation */ con = (float**)MallocOrDie(sizeof(float *) * (msa->alen+1)); mocc = (float*)MallocOrDie(sizeof(float) * (msa->alen+1)); for (i = 1; i <= msa->alen; i++) { con[i] = (float*)MallocOrDie(sizeof(float) * al->Alphabet_size); FSet(con[i], al->Alphabet_size, 0.0); } mocc[0] = -9999.; /* initialization */ /* note: aseq is off by one, 0..alen-1 */ /* "normalized" to have a max total count of 1 per col */ denom = FSum(msa->wgt, msa->nseq); for (i = 1; i <= msa->alen; i++) { for (idx = 0; idx < msa->nseq; idx++) if (! isgap(msa->aseq[idx][i-1])) P7CountSymbol(con[i], SYMIDX(al, msa->aseq[idx][i-1]), msa->wgt[idx]); FScale(con[i], al->Alphabet_size, 1./denom); mocc[i] = FSum(con[i], al->Alphabet_size); } /* Allocate a DP matrix with 2 rows, 0..M columns, * and a shadow matrix with 0,1..alen rows, 0..M columns. */ mx = AllocPlan7Matrix(2, hmm->M, &xmx, &mmx, &imx, &dmx); tb = AllocShadowMatrix(msa->alen+1, hmm->M, &xtb, &mtb, &itb, &dtb); /* Initialization of the zero row. */ xmx[0][XMN] = 0; /* S->N, p=1 */ xtb[0][XMN] = STS; xmx[0][XMB] = hmm->xsc[XTN][MOVE]; /* S->N->B, no N-tail */ xtb[0][XMB] = STN; xmx[0][XME] = xmx[0][XMC] = xmx[0][XMJ] = -INFTY; /* need seq to get here */ tb->esrc[0] = 0; xtb[0][XMC] = xtb[0][XMJ] = STBOGUS; for (k = 0; k <= hmm->M; k++) { mmx[0][k] = imx[0][k] = dmx[0][k] = -INFTY; /* need seq to get here */ mtb[0][k] = itb[0][k] = dtb[0][k] = STBOGUS; } /* Recursion. Done as a pull. * Note some slightly wasteful boundary conditions: * tsc[0] = -INFTY for all eight transitions (no node 0) * D_M and I_M are wastefully calculated (they don't exist) */ for (i = 1; i <= msa->alen; i++) { cur = i % 2; prv = ! cur; mmx[cur][0] = imx[cur][0] = dmx[cur][0] = -INFTY; mtb[i][0] = itb[i][0] = dtb[i][0] = STBOGUS; for (k = 1; k <= hmm->M; k++) { /* match state */ mmx[cur][k] = -INFTY; mtb[i][k] = STBOGUS; if (mmx[prv][k-1] > -INFTY && hmm->tsc[TMM][k-1] > -INFTY && (sc = mmx[prv][k-1] + hmm->tsc[TMM][k-1]) > mmx[cur][k]) { mmx[cur][k] = sc; mtb[i][k] = STM; } if (imx[prv][k-1] > -INFTY && hmm->tsc[TIM][k-1] > -INFTY && (sc = imx[prv][k-1] + hmm->tsc[TIM][k-1] * mocc[i-1]) > mmx[cur][k]) { mmx[cur][k] = sc; mtb[i][k] = STI; } if ((sc = xmx[prv][XMB] + hmm->bsc[k]) > mmx[cur][k]) { mmx[cur][k] = sc; mtb[i][k] = STB; } if (dmx[prv][k-1] > -INFTY && hmm->tsc[TDM][k-1] > -INFTY && (sc = dmx[prv][k-1] + hmm->tsc[TDM][k-1]) > mmx[cur][k]) { mmx[cur][k] = sc; mtb[i][k] = STD; } /* average over "consensus" sequence */ for (sym = 0; sym < al->Alphabet_size; sym++) { if (con[i][sym] > 0 && hmm->msc[sym][k] == -INFTY) { mmx[cur][k] = -INFTY; break; } mmx[cur][k] += hmm->msc[sym][k] * con[i][sym]; } /* delete state */ dmx[cur][k] = -INFTY; dtb[i][k] = STBOGUS; if (mmx[cur][k-1] > -INFTY && hmm->tsc[TMD][k-1] > -INFTY && (sc = mmx[cur][k-1] + hmm->tsc[TMD][k-1]) > dmx[cur][k]) { dmx[cur][k] = sc; dtb[i][k] = STM; } if (dmx[cur][k-1] > -INFTY && hmm->tsc[TDD][k-1] > -INFTY && (sc = dmx[cur][k-1] + hmm->tsc[TDD][k-1]) > dmx[cur][k]) { dmx[cur][k] = sc; dtb[i][k] = STD; } /* insert state */ if (k < hmm->M) { imx[cur][k] = -INFTY; itb[i][k] = STBOGUS; if (mmx[prv][k] > -INFTY && hmm->tsc[TMI][k] > -INFTY && (sc = mmx[prv][k] + hmm->tsc[TMI][k] * mocc[i]) > imx[cur][k]) { imx[cur][k] = sc; itb[i][k] = STM; } if (imx[prv][k] > -INFTY && hmm->tsc[TII][k] > -INFTY && (sc = imx[prv][k] + hmm->tsc[TII][k] * mocc[i-1] * mocc[i]) > imx[cur][k]) { imx[cur][k] = sc; itb[i][k] = STI; } /* average over "consensus" sequence */ for (sym = 0; sym < al->Alphabet_size; sym++) { if (con[i][sym] > 0 && hmm->isc[sym][k] == -INFTY) { imx[cur][k] = -INFTY; break; } imx[cur][k] += hmm->isc[sym][k] * con[i][sym]; } } } /* Now the special states. Order is important here. * remember, N, C, and J emissions are zero score by definition. */ /* N state */ xmx[cur][XMN] = -INFTY; xtb[i][XMN] = STBOGUS; if (xmx[prv][XMN] > -INFTY && hmm->xsc[XTN][LOOP] > -INFTY && (sc = xmx[prv][XMN] + hmm->xsc[XTN][LOOP] * mocc[i]) > -INFTY) { xmx[cur][XMN] = sc; xtb[i][XMN] = STN; } /* E state */ xmx[cur][XME] = -INFTY; xtb[i][XME] = STBOGUS; for (k = 1; k <= hmm->M; k++) if (mmx[cur][k] > -INFTY && hmm->esc[k] > -INFTY && (sc = mmx[cur][k] + hmm->esc[k]) > xmx[cur][XME]) { xmx[cur][XME] = sc; tb->esrc[i] = k; } /* we don't check J state */ /* B state; don't connect from J */ xmx[cur][XMB] = -INFTY; xtb[i][XMB] = STBOGUS; if (xmx[cur][XMN] > -INFTY && hmm->xsc[XTN][MOVE] > -INFTY && (sc = xmx[cur][XMN] + hmm->xsc[XTN][MOVE]) > xmx[cur][XMB]) { xmx[cur][XMB] = sc; xtb[i][XMB] = STN; } /* C state */ xmx[cur][XMC] = -INFTY; xtb[i][XMC] = STBOGUS; if (xmx[prv][XMC] > -INFTY && hmm->xsc[XTC][LOOP] > -INFTY && (sc = xmx[prv][XMC] + hmm->xsc[XTC][LOOP] * mocc[i]) > -INFTY) { xmx[cur][XMC] = sc; xtb[i][XMC] = STC; } if (xmx[cur][XME] > -INFTY && hmm->xsc[XTE][MOVE] > -INFTY && (sc = xmx[cur][XME] + hmm->xsc[XTE][MOVE]) > xmx[cur][XMC]) { xmx[cur][XMC] = sc; xtb[i][XMC] = STE; } } /* T state (not stored in mx) */ sc = xmx[msa->alen%2][XMC] + hmm->xsc[XTC][MOVE]; /* do the traceback */ tr = ShadowTrace(tb, hmm, msa->alen); /* cleanup and return */ FreePlan7Matrix(mx); FreeShadowMatrix(tb); for (i = 1; i <= msa->alen; i++) free(con[i]); free(con); free(mocc); return tr; } /* Function: ShadowTrace() * Date: SRE, Sun Jul 5 11:38:24 1998 [St. Louis] * * Purpose: Given a shadow matrix, trace it back, and return * the trace. * * Args: tb - shadow matrix of traceback pointers * hmm - the model (needed for figuring out wing unfolding) * L - sequence length * * Returns: traceback. Caller must free w/ P7FreeTrace(). */ struct p7trace_s * ShadowTrace(struct dpshadow_s *tb, struct plan7_s *hmm, int L) { struct p7trace_s *tr; int curralloc; /* current allocated length of trace */ int tpos; /* position in trace */ int i; /* position in seq (1..N) */ int k; /* position in model (1..M) */ char nxtstate; /* next state to assign in traceback */ /* Overallocate for the trace. * S-N-B- ... - E-C-T : 6 states + L is minimum trace; * add L more as buffer. */ curralloc = L * 2 + 6; P7AllocTrace(curralloc, &tr); /* Initialization of trace * We do it back to front; ReverseTrace() is called later. */ tr->statetype[0] = STT; tr->nodeidx[0] = 0; tr->pos[0] = 0; tpos = 1; i = L; /* current i (seq pos) we're trying to assign */ k = 0; /* current k (model pos) we're trying to assign */ nxtstate = STC; /* assign the C state first, for C->T */ /* Traceback */ while (nxtstate != STS) { switch (nxtstate) { case STM: tr->statetype[tpos] = STM; nxtstate = tb->mtb[i][k]; tr->nodeidx[tpos] = k--; tr->pos[tpos] = i--; tpos++; break; case STI: tr->statetype[tpos] = STI; nxtstate = tb->itb[i][k]; tr->nodeidx[tpos] = k; tr->pos[tpos] = i--; tpos++; break; case STD: tr->statetype[tpos] = STD; nxtstate = tb->dtb[i][k]; tr->nodeidx[tpos] = k--; tr->pos[tpos] = 0; tpos++; break; case STN: tr->statetype[tpos] = STN; nxtstate = tb->xtb[i][XMN]; tr->nodeidx[tpos] = 0; tr->pos[tpos] = (nxtstate == STN) ? i-- : 0; /* N->N; 2nd one emits. */ tpos++; break; case STB: /* Check for wing unfolding */ if (Prob2Score(hmm->begin[k+1], hmm->p1) + 1 * INTSCALE <= hmm->bsc[k+1]) while (k > 0) { tr->statetype[tpos] = STD; tr->nodeidx[tpos] = k--; tr->pos[tpos] = 0; tpos++; if (tpos == curralloc) { /* grow trace if necessary */ curralloc += L; P7ReallocTrace(tr, curralloc); } } tr->statetype[tpos] = STB; nxtstate = tb->xtb[i][XMB]; tr->nodeidx[tpos] = 0; tr->pos[tpos] = 0; tpos++; break; case STJ: tr->statetype[tpos] = STJ; nxtstate = tb->xtb[i][XMJ]; tr->nodeidx[tpos] = 0; tr->pos[tpos] = (nxtstate == STJ) ? i-- : 0; /* J->J; 2nd one emits. */ tpos++; break; case STE: tr->statetype[tpos] = STE; tr->nodeidx[tpos] = 0; tr->pos[tpos] = 0; k = tb->esrc[i]; nxtstate = STM; tpos++; /* check for wing unfolding */ if (Prob2Score(hmm->end[k], 1.) + 1*INTSCALE <= hmm->esc[k]) { int dk; /* need a tmp k while moving thru delete wing */ for (dk = hmm->M; dk > k; dk--) { tr->statetype[tpos] = STD; tr->nodeidx[tpos] = dk; tr->pos[tpos] = 0; tpos++; if (tpos == curralloc) { /* grow trace if necessary */ curralloc += L; P7ReallocTrace(tr, curralloc); } } } break; case STC: tr->statetype[tpos] = STC; nxtstate = tb->xtb[i][XMC]; tr->nodeidx[tpos] = 0; tr->pos[tpos] = (nxtstate == STC) ? i-- : 0; /* C->C; 2nd one emits. */ tpos++; break; default: Die("HMMER: Bad state (%s) in ShadowTrace()\n", Statetype(nxtstate)); } /* end switch over nxtstate */ if (tpos == curralloc) { /* grow trace if necessary */ curralloc += L; P7ReallocTrace(tr, curralloc); } } /* end traceback, just before assigning S state */ tr->statetype[tpos] = STS; tr->nodeidx[tpos] = 0; tr->pos[tpos] = 0; tr->tlen = tpos + 1; P7ReverseTrace(tr); return tr; } /* Function: PostprocessSignificantHit() * Date: SRE, Wed Dec 20 12:11:01 2000 [StL] * * Purpose: Add a significant hit to per-seq and per-domain hit * lists, after postprocessing the scores appropriately, * and making sure per-domain scores add up to the per-seq * score. * * [doesn't really belong in core_algorithms.c, because * it's more of a hack than an algorithm, but on the other * hand it's now part of the core of how HMMER scores * things. Maybe there should be a core_hacks.c.] * * Given: active hit lists for per-seq and per-domain * scores (e.g. hmmpfam and hmmsearch, collating their * results), and a new hit that's significant enough * that it may need to be reported in final output. * * Breaks the traceback into individual domain traces; * scores each one of them, then applies null2 correction * for biased composition. Recalculates the per-seq score * as the sum of the per-domain scores. Stores the hits * in the lists, for eventual sorting and output by the * caller. * * Notes: In principle we've got the score, and a pvalue, and a traceback * by doing the Viterbi algorithm, right? What else is left * to do? Well, in practice, life is more complicated, because * of the trace-dependent null2 score correction. * * After a null2 score correction is carried out on * each domain (the default) the number of detected domains * with scores > 0 may have decreased. We want the * global (per-seq) hit list to have the recalculated number of * domains, not necessarily what Viterbi gave us. * * Also, since we want the global score to be the sum of * the individual domains, but the null2 correction is * applied to each domain individually, we have to calculate * an adjusted global score. (To do otherwise invites * subtle inconsistencies; xref bug 2.) * * We don't have final evalues, so we may put a few * more hits into the hit lists than we end up reporting. * The main output routine is responsible for final * enforcement of the thresholds. * * This routine is NOT THREADSAFE. When multithreaded, * with using shared ghit/dhit output buffers, calls to * PostprocessSignificantHit() need to be protected. * * Args: ghit - an active list of per-seq (global) hits * dhit - an active list of per-domain hits * tr - the significant HMM/seq traceback we'll report on * hmm - ptr to the HMM * dsq - digitized sequence (1..L) * L - length of dsq * seqname - name of sequence (same as targname, in hmmsearch) * seqacc - seq's accession (or NULL) * seqdesc - seq's description (or NULL) * do_forward - TRUE if we've already calculated final per-seq score * sc_override - per-seq score to use if do_forward is TRUE * do_null2 - TRUE to apply the null2 scoring correction * thresh - contains the threshold/cutoff information. * hmmpfam_mode - TRUE if called by hmmpfam, else assumes hmmsearch; * affects how the lists' sort keys are set. * * Returns: the recalculated per-seq score (or sc_override), * as appropriate, for subsequent storage in the histogram */ float //PostprocessSignificantHit(struct alphabet_s * al, struct tophit_s *ghit, PostprocessSignificantHit(struct tophit_s *ghit, struct tophit_s *dhit, struct p7trace_s *tr, struct plan7_s *hmm, unsigned char *dsq, int L, char *seqname, char *seqacc, char *seqdesc, int do_forward, float sc_override, int do_null2, struct threshold_s *thresh, int hmmpfam_mode) { struct p7trace_s **tarr; /* array of per-domain traces */ struct fancyali_s *ali; /* alignment of a domain */ int ntr; /* number of domain traces from Viterbi */ int tidx; /* index for traces (0..ntr-1) */ int ndom; /* # of domains accepted in sequence */ int didx; /* index for domains (1..ndom) */ int k1, k2; /* start, stop coord in model */ int i1, i2; /* start, stop in sequence */ float whole_sc; /* whole sequence score = \sum domain scores */ float *score; /* array of raw scores for each domain */ int *usedomain; /* TRUE if this domain is accepted */ double whole_pval; double pvalue; double sortkey; /* Special case: rarely, the alignment was totally impossible * and tr is NULL. */ if (tr == NULL) return sc_override; /* Break the trace into one or more individual domains. */ TraceDecompose(tr, &tarr, &ntr); if (ntr == 0) Die("TraceDecompose() screwup"); /* "can't happen" (!) */ /* Rescore each domain, apply null2 correction if asked. * Mark positive-scoring ones (we'll definitely report those), * and include their score in the whole sequence score. */ score = (float*)MallocOrDie(sizeof(float) * ntr); usedomain = (int*)MallocOrDie(sizeof(int) * ntr); ndom = 0; whole_sc = 0.; for (tidx = 0; tidx < ntr; tidx++) { score[tidx] = P7TraceScore(hmm, dsq, tarr[tidx]); if (do_null2) score[tidx] -= TraceScoreCorrection(hmm, tarr[tidx], dsq); if (score[tidx] > 0.0) { usedomain[tidx] = TRUE; ndom++; whole_sc += score[tidx]; } else usedomain[tidx] = FALSE; } /* Make sure at least one positive scoring domain is in * the trace. If not, invoke "weak single domain" rules: * we will always report at least one domain per sequence, even * if it has a negative score. (HMMER's Plan7 architecture can report * one negative scoring domain but not more.) */ if (ndom == 0) { tidx = FArgMax(score, ntr); usedomain[tidx] = TRUE; whole_sc = score[tidx]; ndom = 1; } /* Implement --do_forward: override the trace-dependent sum-of-domain * whole score, use the P7Forward() score that the called passed * us instead. This is a hack; null2 is trace-dependent and * thus undefined for P7Forward() scoring; see commentary in hmmpfam.c. */ if (do_forward) whole_sc = sc_override; /* Go through and put all the accepted domains into the hit list. */ whole_pval = PValue(hmm, whole_sc); for (tidx = 0, didx = 1; tidx < ntr; tidx++) { if (! usedomain[tidx]) continue; TraceSimpleBounds(tarr[tidx], &i1, &i2, &k1, &k2); pvalue = PValue(hmm, score[tidx]); if (pvalue <= thresh->domE && score[tidx] >= thresh->domT) { ali = CreateFancyAli(tarr[tidx], hmm, dsq, seqname); if (hmmpfam_mode) sortkey = -1.*(double)i1; /* hmmpfam: sort on position in seq */ else sortkey = score[tidx]; /* hmmsearch: sort on E (monotonic w/ sc) */ RegisterHit(dhit, sortkey, pvalue, score[tidx], whole_pval, whole_sc, hmmpfam_mode ? hmm->name : seqname, hmmpfam_mode ? hmm->acc : seqacc, hmmpfam_mode ? hmm->desc : seqdesc, i1,i2, L, k1,k2, hmm->M, didx,ndom,ali); } didx++; } /* Now register the global hit, with the domain-derived score. */ /* sorting: * hmmpfam has to worry that score and E-value are not monotonic * when multiple HMMs (with different EVD parameters) are potential * targets. Therefore in hmmpfam_mode we apply a weird hack * to sort primarily on E-value, but on score * for really good hits with E=0.0... works because we can * assume 100000. > -log(DBL_MIN). * hmmsearch simply sorts on score (which for a single HMM, we * know is monotonic with E-value). */ if (hmmpfam_mode) sortkey = (whole_pval > 0.0) ? -1.*log(whole_pval) : 100000. + whole_sc; else sortkey = whole_sc; /* Note: we've recalculated whole_sc and it may have decreased * after the null2 correction was applied. For Pfam GA, TC, * or NC cutoffs, we have to be sure that everything on the * hitlist is correct (the hmmpfam output routine assumes it, * otherwise it would have to reload each HMM to get its * cutoffs). In all other cases, though, we don't care if * the hit list has a bit too many things on it, because the * output routine in hmmsearch or hmmpfam will check against * the cutoffs. Hence we only need to check against globT * (it may be set by GA, TC, or NC) but not globE. * - SRE, CSHL genome mtg May 2001 */ if (whole_sc >= thresh->globT) { RegisterHit(ghit, sortkey, whole_pval, whole_sc, 0., 0., /* no mother seq */ hmmpfam_mode ? hmm->name : seqname, hmmpfam_mode ? hmm->acc : seqacc, hmmpfam_mode ? hmm->desc : seqdesc, 0,0,0, /* seq positions */ 0,0,0, /* HMM positions */ 0, ndom, /* # domains info */ NULL); /* alignment info */ } /* Clean up and return. */ for (tidx = 0; tidx < ntr; tidx++) P7FreeTrace(tarr[tidx]); free(tarr); free(score); free(usedomain); return whole_sc; } ugene-1.9.8/src/plugins_3rdparty/hmm2/src/hmmer2/sqerror.cpp0000644000175000017500000000320611651544326022447 0ustar ilyailya/***************************************************************** * HMMER - Biological sequence analysis with profile HMMs * Copyright (C) 1992-2003 Washington University School of Medicine * All Rights Reserved * * This source code is distributed under the terms of the * GNU General Public License. See the files COPYING and LICENSE * for details. *****************************************************************/ /* sqerror.c * * error handling for the squid library * CVS $Id: sqerror.c,v 1.6 2003/05/26 16:21:50 eddy Exp $ */ #include "funcs.h" #include int squid_errno; /* a global errno equivalent */ /* Function: Die() * * Purpose: Print an error message and die. The arguments * are formatted exactly like arguments to printf(). * * Return: None. Exits the program. */ /* VARARGS0 */ void Die(const char *format, ...) { va_list argp; /* format the error mesg */ va_start(argp, format); HMMException e(""); vsnprintf(e.error, 1024, format, argp); va_end(argp); /* exit */ throw e; } /* Function: Warn() * * Purpose: Print an error message and return. The arguments * are formatted exactly like arguments to printf(). * * Return: (void) */ /* VARARGS0 */ void Warn(const char *format, ...) { va_list argp; /* format the error mesg */ fprintf(stderr, "WARNING: "); va_start(argp, format); vfprintf(stderr, format, argp); va_end(argp); fprintf(stderr, "\n"); fflush(stderr); } HMMException::HMMException(const char *err) { sre_strlcpy(error, err, 1024); error[1023]='\0'; } ugene-1.9.8/src/plugins_3rdparty/hmm2/src/hmmer2/histogram.cpp0000644000175000017500000010520111651544326022745 0ustar ilyailya/************************************************************ * HMMER - Biological sequence analysis with profile HMMs * Copyright (C) 1992-2003 Washington University School of Medicine * All Rights Reserved * * This source code is distributed under the terms of the * GNU General Public License. See the files COPYING and LICENSE * for details. ************************************************************/ /* histogram.c * SRE, Sat Jan 20 16:16:17 1996 * * Accumulation, printing, and fitting of score histograms * from database searches. * * CVS $Id: histogram.c,v 1.18 2003/04/14 16:00:16 eddy Exp $ ************************************************************ * Basic API: * * struct histogram_s *h; * * h = AllocHistogram(min_hint, max_hint, lumpsize); * * while (getting scores x) AddToHistogram(h, x); * * ExtremeValueFitHistogram(h, high_hint); * PrintASCIIHistogram(fp, h); * FreeHistogram(h); */ #include "funcs.h" /* Function: AllocHistogram() * * Purpose: Allocate and return a histogram structure. * min and max are your best guess. They need * not be absolutely correct; the histogram * will expand dynamically to accomodate scores * that exceed these suggested bounds. The amount * that the histogram grows by is set by "lumpsize". * * Args: min: minimum score (integer) * max: maximum score (integer) * lumpsize: when reallocating histogram, pad the reallocation * by this much (saves excessive reallocation) */ struct histogram_s * AllocHistogram(int min, int max, int lumpsize) { struct histogram_s *h; int newsize; int i; newsize = max - min + 1; h = (struct histogram_s *) MallocOrDie(sizeof(struct histogram_s)); h->min = min; h->max = max; h->total = 0; h->lowscore = INT_MAX; h->highscore = INT_MIN; h->lumpsize = lumpsize; h->histogram = (int *) MallocOrDie (sizeof(int) * newsize); for (i = 0; i < newsize; i++) h->histogram[i] = 0; h->expect = NULL; h->fit_type = HISTFIT_NONE; return h; } /* Function: FreeHistogram() * * Purpose: free a histogram structure. */ void FreeHistogram(struct histogram_s *h) { free(h->histogram); if (h->expect != NULL) free(h->expect); free(h); } /* Function: UnfitHistogram() * * Purpose: Free only the theoretical fit part of a histogram. */ void UnfitHistogram(struct histogram_s *h) { if (h->expect != NULL) free(h->expect); h->expect = NULL; h->fit_type = HISTFIT_NONE; } /* Function: AddToHistogram() * * Purpose: Bump the appropriate counter in a histogram * structure, given a score. The score is * rounded off from float precision to the * next lower integer. */ void AddToHistogram(struct histogram_s *h, float sc) { int score; int moveby; int prevsize; int newsize; int i; /* Adding to a histogram conflicts with existing fit: * prohibit this. */ if (h->fit_type != HISTFIT_NONE) Die("AddToHistogram(): Can't add to a fitted histogram\n"); /* histogram bins are defined as: score >= bin value, < bin+1 * -1.9 -> -2 -0.4 -> -1 1.9 -> 1 * -2.1 -> -3 0.4 -> 0 2.1 -> 2 */ score = (int) floor(sc); /* Check to see if we must reallocate the histogram. */ if (score < h->min) { prevsize = h->max - h->min + 1; moveby = (h->min - score) + h->lumpsize; newsize = prevsize + moveby; h->min -= moveby; h->histogram = (int *) ReallocOrDie(h->histogram, sizeof(int) * newsize); memmove(h->histogram+moveby, h->histogram, sizeof(int) * prevsize); for (i = 0; i < moveby; i++) h->histogram[i] = 0; } else if (score > h->max) { prevsize = h->max - h->min + 1; h->max = h->lumpsize + score; newsize = h->max - h->min + 1; h->histogram = (int *) ReallocOrDie(h->histogram, sizeof(int) * newsize); for (i = prevsize; i < newsize; i++) h->histogram[i] = 0; } /* Bump the correct bin. * The bin number is score - h->min */ h->histogram[score - h->min]++; h->total++; if (score < h->lowscore) h->lowscore = score; if (score > h->highscore) h->highscore = score; SQD_DPRINTF3(("AddToHistogram(): added %.1f; rounded to %d; in bin %d (%d-%d)\n", sc, score, score-h->min, h->min, h->max)); return; } /* Function: EVDBasicFit() * Date: SRE, Wed Nov 12 11:02:27 1997 [St. Louis] * * Purpose: Fit a score histogram to the extreme value * distribution. Set the parameters lambda * and mu in the histogram structure. Fill in the * expected values in the histogram. Calculate * a chi-square test as a measure of goodness of fit. * * This is the basic version of ExtremeValueFitHistogram(), * in a nonrobust form: simple linear regression with no * outlier pruning. * * Methods: Uses a linear regression fitting method [Collins88,Lawless82] * * Args: h - histogram to fit * * Return: (void) */ void EVDBasicFit(struct histogram_s *h) { float *d; /* distribution P(S < x) */ float *x; /* x-axis of P(Smin */ float slope, intercept; /* m,b fit from Linefit() */ float corr; /* correlation coeff of line fit, not used */ float lambda, mu; /* slope, intercept converted to EVD params */ /* Allocations for x, y axes * distribution d runs from min..max with indices 0..max-min * i.e. score - min = index into d, x, histogram, and expect */ hsize = h->highscore - h->lowscore + 1; d = (float *) MallocOrDie(sizeof(float) * hsize); x = (float *) MallocOrDie(sizeof(float) * hsize); for (idx = 0; idx < hsize; idx++) d[idx] = x[idx] = 0.; /* Calculate P(S < x) distribution from histogram. * note off-by-one of sc, because histogram bin contains scores between * x and x+1. */ sum = 0; for (sc = h->lowscore; sc <= h->highscore; sc++) { sum += h->histogram[sc - h->min]; d[sc - h->lowscore] = (float) sum / (float) h->total; x[sc - h->lowscore] = (float) (sc + 1); } /* Do a linear regression fit to the log[-log(P(Sx))] = -lambda * x + lambda * mu * so lambda = -m and mu = b/lambda */ /* convert y axis to log[-log(P(Slowscore; sc < h->highscore; sc++) d[sc - h->lowscore] = log(-1. * log(d[sc - h->lowscore])); /* do the linear regression */ Linefit(x, d, hsize-1, &intercept, &slope, &corr); /* calc mu, lambda */ lambda = -1. * slope; mu = intercept / lambda; /* Set the EVD parameters in the histogram; * pass 2 for additional lost degrees of freedom because we fit mu, lambda. */ ExtremeValueSetHistogram(h, mu, lambda, h->lowscore, h->highscore, 2); free(x); free(d); return; } /* Function: ExtremeValueFitHistogram() * Date: SRE, Sat Nov 15 17:16:15 1997 [St. Louis] * * Purpose: Fit a score histogram to the extreme value * distribution. Set the parameters lambda * and mu in the histogram structure. Calculate * a chi-square test as a measure of goodness of fit. * * Methods: Uses a maximum likelihood method [Lawless82]. * Lower outliers are removed by censoring the data below the peak. * Upper outliers are removed iteratively using method * described by [Mott92]. * * Args: h - histogram to fit * censor - TRUE to censor data left of the peak * high_hint - score cutoff; above this are `real' hits that aren't fit * * Return: 1 if fit is judged to be valid. * else 0 if fit is invalid (too few seqs.) */ int ExtremeValueFitHistogram(struct histogram_s *h, int censor, float high_hint) { float *x; /* array of EVD samples to fit */ int *y; /* histogram counts */ int n; /* number of observed samples */ int z; /* number of censored samples */ int hsize; /* size of histogram */ float lambda, mu; /* new estimates of lambda, mu */ int sc; /* loop index for score */ int lowbound; /* lower bound of fitted region*/ int highbound; /* upper bound of fitted region*/ int new_highbound; int iteration; /* Determine lower bound on fitted region; * if we're censoring the data, choose the peak of the histogram. * if we're not, then we take the whole histogram. */ lowbound = h->lowscore; if (censor) { int max = -1; for (sc = h->lowscore; sc <= h->highscore; sc++) if (h->histogram[sc - h->min] > max) { max = h->histogram[sc - h->min]; lowbound = sc; } } /* Determine initial upper bound on fitted region. */ highbound = MIN(high_hint, h->highscore); /* Now, iteratively converge on our lambda, mu: */ for (iteration = 0; iteration < 100; iteration++) { /* Construct x, y vectors. */ x = NULL; y = NULL; hsize = highbound - lowbound + 1; if (hsize < 5) goto FITFAILED; /* require at least 5 bins or we don't fit */ x = (float*)MallocOrDie(sizeof(float) * hsize); y = (int*)MallocOrDie(sizeof(int) * hsize); n = 0; for (sc = lowbound; sc <= highbound; sc++) { x[sc-lowbound] = (float) sc + 0.5; /* crude, but tests OK */ y[sc-lowbound] = h->histogram[sc - h->min]; n += h->histogram[sc - h->min]; } if (n < 100) goto FITFAILED; /* require fitting to at least 100 points */ /* If we're censoring, estimate z, the number of censored guys * left of the bound. Our initial estimate is crudely that we're * missing e^-1 of the total distribution (which would be exact * if we censored exactly at mu; but we censored at the observed peak). * Subsequent estimates are more exact based on our current estimate of mu. */ if (censor) { if (iteration == 0) z = MIN(h->total-n, (int) (0.58198 * (float) n)); else { double psx; psx = EVDDistribution((float) lowbound, mu, lambda); z = MIN(h->total-n, (int) ((double) n * psx / (1. - psx))); } } /* Do an ML fit */ if (censor) { if (! EVDCensoredFit(x, y, hsize, z, (float) lowbound, &mu, &lambda)) goto FITFAILED; } else if (! EVDMaxLikelyFit(x, y, hsize, &mu, &lambda)) goto FITFAILED; /* Find the Eval = 1 point as a new highbound; * the total number of samples estimated to "belong" to the EVD is n+z */ new_highbound = (int) (mu - (log (-1. * log((double) (n+z-1) / (double)(n+z))) / lambda)); free(x); free(y); if (new_highbound >= highbound) break; highbound = new_highbound; } /* Set the histogram parameters; * - we fit from lowbound to highbound; thus we lose 2 degrees of freedom * for fitting mu, lambda, but we get 1 back because we're unnormalized * in this interval, hence we pass 2-1 = 1 as ndegrees. */ ExtremeValueSetHistogram(h, mu, lambda, lowbound, highbound, 1); return 1; FITFAILED: UnfitHistogram(h); if (x != NULL) free(x); if (y != NULL) free(y); return 0; } /* Function: ExtremeValueSetHistogram() * * Purpose: Instead of fitting the histogram to an EVD, * simply set the EVD parameters from an external source. * * Args: h - the histogram to set * mu - mu location parameter * lambda - lambda scale parameter * lowbound - low bound of the histogram that was fit * highbound- high bound of histogram that was fit * ndegrees - extra degrees of freedom to subtract in X^2 test: * typically 0 if mu, lambda are parametric, * else 2 if mu, lambda are estimated from data */ void ExtremeValueSetHistogram(struct histogram_s *h, float mu, float lambda, float lowbound, float highbound, int ndegrees) { int sc; int hsize, idx; int nbins; float delta; UnfitHistogram(h); h->fit_type = HISTFIT_EVD; h->param[EVD_LAMBDA] = lambda; h->param[EVD_MU] = mu; hsize = h->max - h->min + 1; h->expect = (float *) MallocOrDie(sizeof(float) * hsize); for (idx = 0; idx < hsize; idx++) h->expect[idx] = 0.; /* Calculate the expected values for the histogram. */ for (sc = h->min; sc <= h->max; sc++) h->expect[sc - h->min] = ExtremeValueE((float)(sc), h->param[EVD_MU], h->param[EVD_LAMBDA], h->total) - ExtremeValueE((float)(sc+1), h->param[EVD_MU], h->param[EVD_LAMBDA], h->total); /* Calculate the goodness-of-fit (within whole region) */ h->chisq = 0.; nbins = 0; for (sc = lowbound; sc <= highbound; sc++) if (h->expect[sc-h->min] >= 5. && h->histogram[sc-h->min] >= 5) { delta = (float) h->histogram[sc-h->min] - h->expect[sc-h->min]; h->chisq += delta * delta / h->expect[sc-h->min]; nbins++; } /* Since we fit the whole histogram, there is at least * one constraint on chi-square: the normalization to h->total. */ if (nbins > 1 + ndegrees) h->chip = (float) IncompleteGamma((double)(nbins-1-ndegrees)/2., (double) h->chisq/2.); else h->chip = 0.; } /* Function: GaussianFitHistogram() * * Purpose: Fit a score histogram to a Gaussian distribution. * Set the parameters mean and sd in the histogram * structure, as well as a chi-squared test for * goodness of fit. * * Args: h - histogram to fit * high_hint - score cutoff; above this are `real' hits that aren't fit * * Return: 1 if fit is judged to be valid. * else 0 if fit is invalid (too few seqs.) */ int GaussianFitHistogram(struct histogram_s *h, float high_hint) { float sum; float sqsum; float delta; int sc; int nbins; int hsize, idx; /* Clear any previous fitting from the histogram. */ UnfitHistogram(h); /* Determine if we have enough hits to fit the histogram; * arbitrarily require 1000. */ if (h->total < 1000) { h->fit_type = HISTFIT_NONE; return 0; } /* Simplest algorithm for mean and sd; * no outlier detection yet (not even using high_hint) * * Magic 0.5 correction is because our histogram is for * scores between x and x+1; we estimate the expectation * (roughly) as x + 0.5. */ sum = sqsum = 0.; for (sc = h->lowscore; sc <= h->highscore; sc++) { delta = (float) sc + 0.5; sum += (float) h->histogram[sc-h->min] * delta; sqsum += (float) h->histogram[sc-h->min] * delta * delta; } h->fit_type = HISTFIT_GAUSSIAN; h->param[GAUSS_MEAN] = sum / (float) h->total; h->param[GAUSS_SD] = sqrt((sqsum - (sum*sum/(float)h->total)) / (float)(h->total-1)); /* Calculate the expected values for the histogram. * Note that the magic 0.5 correction appears again. * Calculating difference between distribution functions for Gaussian * would be correct but hard. */ hsize = h->max - h->min + 1; h->expect = (float *) MallocOrDie(sizeof(float) * hsize); for (idx = 0; idx < hsize; idx++) h->expect[idx] = 0.; for (sc = h->min; sc <= h->max; sc++) { delta = (float) sc + 0.5 - h->param[GAUSS_MEAN]; h->expect[sc - h->min] = (float) h->total * ((1. / (h->param[GAUSS_SD] * sqrt(2.*3.14159))) * (exp(-1.* delta*delta / (2. * h->param[GAUSS_SD] * h->param[GAUSS_SD])))); } /* Calculate the goodness-of-fit (within region that was fitted) */ h->chisq = 0.; nbins = 0; for (sc = h->lowscore; sc <= h->highscore; sc++) if (h->expect[sc-h->min] >= 5. && h->histogram[sc-h->min] >= 5) { delta = (float) h->histogram[sc-h->min] - h->expect[sc-h->min]; h->chisq += delta * delta / h->expect[sc-h->min]; nbins++; } /* -1 d.f. for normalization; -2 d.f. for two free parameters */ if (nbins > 3) h->chip = (float) IncompleteGamma((double)(nbins-3)/2., (double) h->chisq/2.); else h->chip = 0.; return 1; } /* Function: GaussianSetHistogram() * * Purpose: Instead of fitting the histogram to a Gaussian, * simply set the Gaussian parameters from an external source. */ void GaussianSetHistogram(struct histogram_s *h, float mean, float sd) { int sc; int hsize, idx; int nbins; float delta; UnfitHistogram(h); h->fit_type = HISTFIT_GAUSSIAN; h->param[GAUSS_MEAN] = mean; h->param[GAUSS_SD] = sd; /* Calculate the expected values for the histogram. */ hsize = h->max - h->min + 1; h->expect = (float *) MallocOrDie(sizeof(float) * hsize); for (idx = 0; idx < hsize; idx++) h->expect[idx] = 0.; /* Note: ideally we'd use the Gaussian distribution function * to find the histogram occupancy in the window sc..sc+1. * However, the distribution function is hard to calculate. * Instead, estimate the histogram by taking the density at sc+0.5. */ for (sc = h->min; sc <= h->max; sc++) { delta = ((float)sc + 0.5) - h->param[GAUSS_MEAN]; h->expect[sc - h->min] = (float) h->total * ((1. / (h->param[GAUSS_SD] * sqrt(2.*3.14159))) * (exp(-1.*delta*delta / (2. * h->param[GAUSS_SD] * h->param[GAUSS_SD])))); } /* Calculate the goodness-of-fit (within whole region) */ h->chisq = 0.; nbins = 0; for (sc = h->lowscore; sc <= h->highscore; sc++) if (h->expect[sc-h->min] >= 5. && h->histogram[sc-h->min] >= 5) { delta = (float) h->histogram[sc-h->min] - h->expect[sc-h->min]; h->chisq += delta * delta / h->expect[sc-h->min]; nbins++; } /* -1 d.f. for normalization */ if (nbins > 1) h->chip = (float) IncompleteGamma((double)(nbins-1)/2., (double) h->chisq/2.); else h->chip = 0.; } /* Function: EVDDensity() * Date: SRE, Sat Nov 15 19:37:52 1997 [St. Louis] * * Purpose: Return the extreme value density P(S=x) at * a given point x, for an EVD controlled by * parameters mu and lambda. */ double EVDDensity(float x, float mu, float lambda) { return (lambda * exp(-1. * lambda * (x - mu) - exp(-1. * lambda * (x - mu)))); } /* Function: EVDDistribution() * Date: SRE, Tue Nov 18 08:02:22 1997 [St. Louis] * * Purpose: Returns the extreme value distribution P(S < x) * evaluated at x, for an EVD controlled by parameters * mu and lambda. */ double EVDDistribution(float x, float mu, float lambda) { return (exp(-1. * exp(-1. * lambda * (x - mu)))); } /* Function: ExtremeValueP() * * Purpose: Calculate P(S>x) according to an extreme * value distribution, given x and the parameters * of the distribution (characteristic * value mu, decay constant lambda). * * This function is exquisitely prone to * floating point exceptions if it isn't coded * carefully. * * Args: x = score * mu = characteristic value of extreme value distribution * lambda = decay constant of extreme value distribution * * Return: P(S>x) */ double ExtremeValueP(float x, float mu, float lambda) { double y; /* avoid exceptions near P=1.0 */ /* typical 32-bit sys: if () < -3.6, return 1.0 */ if ((lambda * (x - mu)) <= -1. * log(-1. * log(DBL_EPSILON))) return 1.0; /* avoid underflow fp exceptions near P=0.0*/ if ((lambda * (x - mu)) >= 2.3 * (double) DBL_MAX_10_EXP) return 0.0; /* a roundoff issue arises; use 1 - e^-x --> x for small x */ y = exp(-1. * lambda * (x - mu)); if (y < 1e-7) return y; else return (1.0 - exp(-1. * y)); } /* Function: ExtremeValueP2() * * Purpose: Calculate P(S>x) in a database of size N, * using P(S>x) for a single sequence, according * to a Poisson distribution. * * Args: x = score * mu = characteristic value of extreme value distribution * lambda = decay constant of extreme value distribution * N = number of trials (number of sequences) * * Return: P(S>x) for database of size N */ double ExtremeValueP2(float x, float mu, float lambda, int N) { double y; y = N * ExtremeValueP(x,mu,lambda); if (y < 1e-7) return y; else return (1.0 - exp(-1. * y)); } /* Function: ExtremeValueE() * * Purpose: Calculate E(S>x) in a database of size N, * using P(S>x) for a single sequence: simply np. * * Args: x = score * mu = characteristic value of extreme value distribution * lambda = decay constant of extreme value distribution * N = number of trials (number of sequences) * * Return: E(S>x) for database of size N */ double ExtremeValueE(float x, float mu, float lambda, int N) { return (double)N * ExtremeValueP(x,mu,lambda); } /* Function: EVDrandom() * * Purpose: Randomly sample an x from an EVD. * Trivially done by the transformation method, since * the distribution is analytical: * x = \mu - \frac{\log \left[ -\log P(S= c * lambda - a lambda to test * ret_f - RETURN: 4.2.2 evaluated at lambda * ret_df - RETURN: first derivative of 4.2.2 evaluated at lambda * * Return: (void) */ void Lawless422(float *x, int *y, int n, int z, float c, float lambda, float *ret_f, float *ret_df) { double esum; /* \sum e^(-lambda xi) + z term */ double xesum; /* \sum xi e^(-lambda xi) + z term */ double xxesum; /* \sum xi^2 e^(-lambda xi) + z term */ double xsum; /* \sum xi (no z term) */ double mult; /* histogram count multiplier */ double total; /* total samples */ int i; esum = xesum = xsum = xxesum = total = 0.; for (i = 0; i < n; i++) { mult = (y == NULL) ? 1. : (double) y[i]; xsum += mult * x[i]; esum += mult * exp(-1. * lambda * x[i]); xesum += mult * x[i] * exp(-1. * lambda * x[i]); xxesum += mult * x[i] * x[i] * exp(-1. * lambda * x[i]); total += mult; } /* Add z terms for censored data */ esum += (double) z * exp(-1. * lambda * c); xesum += (double) z * c * exp(-1. * lambda * c); xxesum += (double) z * c * c * exp(-1. * lambda * c); *ret_f = 1./lambda - xsum / total + xesum / esum; *ret_df = ((xesum / esum) * (xesum / esum)) - (xxesum / esum) - (1. / (lambda * lambda)); return; } /* Function: EVDMaxLikelyFit() * Date: SRE, Fri Nov 14 07:56:29 1997 [St. Louis] * * Purpose: Given a list or a histogram of EVD-distributed samples, * find maximum likelihood parameters lambda and * mu. * * Algorithm: Uses approach described in [Lawless82]. Solves * for lambda using Newton/Raphson iterations; * then substitutes lambda into Lawless' equation 4.1.5 * to get mu. * * Newton/Raphson algorithm developed from description in * Numerical Recipes in C [Press88]. * * Args: x - list of EVD distributed samples or x-axis of histogram * c - NULL, or y-axis of histogram * n - number of samples, or number of histogram bins * ret_mu : RETURN: ML estimate of mu * ret_lambda : RETURN: ML estimate of lambda * * Return: 1 on success; 0 on any failure */ int EVDMaxLikelyFit(float *x, int *c, int n, float *ret_mu, float *ret_lambda) { float lambda, mu; float fx; /* f(x) */ float dfx; /* f'(x) */ double esum; /* \sum e^(-lambda xi) */ double mult; double total; float tol = 1e-5; int i; /* 1. Find an initial guess at lambda: linear regression here? */ lambda = 0.2; /* 2. Use Newton/Raphson to solve Lawless 4.1.6 and find ML lambda */ for (i = 0; i < 100; i++) { Lawless416(x, c, n, lambda, &fx, &dfx); if (fabs(fx) < tol) break; /* success */ lambda = lambda - fx / dfx; /* Newton/Raphson is simple */ if (lambda <= 0.) lambda = 0.001; /* but be a little careful */ } /* 2.5: If we did 100 iterations but didn't converge, Newton/Raphson failed. * Resort to a bisection search. Worse convergence speed * but guaranteed to converge (unlike Newton/Raphson). * We assume (!?) that fx is a monotonically decreasing function of x; * i.e. fx > 0 if we are left of the root, fx < 0 if we * are right of the root. */ if (i == 100) { float left, right, mid; SQD_DPRINTF2(("EVDMaxLikelyFit(): Newton/Raphson failed; switchover to bisection")); /* First we need to bracket the root */ lambda = right = left = 0.2; Lawless416(x, c, n, lambda, &fx, &dfx); if (fx < 0.) { /* fix right; search left. */ do { left -= 0.1; if (left < 0.) { SQD_DPRINTF2(("EVDMaxLikelyFit(): failed to bracket root")); return 0; } Lawless416(x, c, n, left, &fx, &dfx); } while (fx < 0.); } else { /* fix left; search right. */ do { right += 0.1; Lawless416(x, c, n, right, &fx, &dfx); if (right > 100.) { SQD_DPRINTF2(("EVDMaxLikelyFit(): failed to bracket root")); return 0; } } while (fx > 0.); } /* now we bisection search in left/right interval */ for (i = 0; i < 100; i++) { mid = (left + right) / 2.; Lawless416(x, c, n, mid, &fx, &dfx); if (fabs(fx) < tol) break; /* success */ if (fx > 0.) left = mid; else right = mid; } if (i == 100) { SQD_DPRINTF2(("EVDMaxLikelyFit(): even the bisection search failed")); return 0; } lambda = mid; } /* 3. Substitute into Lawless 4.1.5 to find mu */ esum = 0.; total = 0.; for (i = 0; i < n; i++) { mult = (c == NULL) ? 1. : (double) c[i]; esum += mult * exp(-1 * lambda * x[i]); total += mult; } mu = -1. * log(esum / total) / lambda; *ret_lambda = lambda; *ret_mu = mu; return 1; } /* Function: EVDCensoredFit() * Date: SRE, Mon Nov 17 10:01:05 1997 [St. Louis] * * Purpose: Given a /left-censored/ list or histogram of EVD-distributed * samples, as well as the number of censored samples z and the * censoring value c, * find maximum likelihood parameters lambda and * mu. * * Algorithm: Uses approach described in [Lawless82]. Solves * for lambda using Newton/Raphson iterations; * then substitutes lambda into Lawless' equation 4.2.3 * to get mu. * * Newton/Raphson algorithm developed from description in * Numerical Recipes in C [Press88]. * * Args: x - list of EVD distributed samples or x-axis of histogram * y - NULL, or y-axis of histogram * n - number of observed samples,or number of histogram bins * z - number of censored samples * c - censoring value (all x_i >= c) * ret_mu : RETURN: ML estimate of mu * ret_lambda : RETURN: ML estimate of lambda * * Return: (void) */ int EVDCensoredFit(float *x, int *y, int n, int z, float c, float *ret_mu, float *ret_lambda) { float lambda, mu; float fx; /* f(x) */ float dfx; /* f'(x) */ double esum; /* \sum e^(-lambda xi) */ double mult; double total; float tol = 1e-5; int i; /* 1. Find an initial guess at lambda: linear regression here? */ lambda = 0.2; /* 2. Use Newton/Raphson to solve Lawless 4.2.2 and find ML lambda */ for (i = 0; i < 100; i++) { Lawless422(x, y, n, z, c, lambda, &fx, &dfx); if (fabs(fx) < tol) break; /* success */ lambda = lambda - fx / dfx; /* Newton/Raphson is simple */ if (lambda <= 0.) lambda = 0.001; /* but be a little careful */ } /* 2.5: If we did 100 iterations but didn't converge, Newton/Raphson failed. * Resort to a bisection search. Worse convergence speed * but guaranteed to converge (unlike Newton/Raphson). * We assume (!?) that fx is a monotonically decreasing function of x; * i.e. fx > 0 if we are left of the root, fx < 0 if we * are right of the root. */ if (i == 100) { float left, right, mid; /* First we need to bracket the root */ SQD_DPRINTF2(("EVDCensoredFit(): Newton/Raphson failed; switched to bisection")); lambda = right = left = 0.2; Lawless422(x, y, n, z, c, lambda, &fx, &dfx); if (fx < 0.) { /* fix right; search left. */ do { left -= 0.03; if (left < 0.) { SQD_DPRINTF2(("EVDCensoredFit(): failed to bracket root")); return 0; } Lawless422(x, y, n, z, c, left, &fx, &dfx); } while (fx < 0.); } else { /* fix left; search right. */ do { right += 0.1; Lawless422(x, y, n, z, c, left, &fx, &dfx); if (right > 100.) { SQD_DPRINTF2(("EVDCensoredFit(): failed to bracket root")); return 0; } } while (fx > 0.); } /* now we bisection search in left/right interval */ for (i = 0; i < 100; i++) { mid = (left + right) / 2.; Lawless422(x, y, n, z, c, left, &fx, &dfx); if (fabs(fx) < tol) break; /* success */ if (fx > 0.) left = mid; else right = mid; } if (i == 100) { SQD_DPRINTF2(("EVDCensoredFit(): even the bisection search failed")); return 0; } lambda = mid; } /* 3. Substitute into Lawless 4.2.3 to find mu */ esum = total = 0.; for (i = 0; i < n; i++) { mult = (y == NULL) ? 1. : (double) y[i]; esum += mult * exp(-1. * lambda * x[i]); total += mult; } esum += (double) z * exp(-1. * lambda * c); /* term from censored data */ mu = -1. * log(esum / total) / lambda; *ret_lambda = lambda; *ret_mu = mu; return 1; } ugene-1.9.8/src/plugins_3rdparty/hmm2/src/hmmer2/mathsupport.cpp0000644000175000017500000002332111651544326023340 0ustar ilyailya/************************************************************ * HMMER - Biological sequence analysis with profile HMMs * Copyright (C) 1992-2003 Washington University School of Medicine * All Rights Reserved * * This source code is distributed under the terms of the * GNU General Public License. See the files COPYING and LICENSE * for details. ************************************************************/ /* mathsupport.c * SRE, Mon Nov 11 15:07:33 1996 * * Miscellaneous mathematical functions. * General functions are in the SQUID library sre_math.c. * These functions are too HMM-specific to warrant being in the * SQUID library. * */ #include "funcs.h" /* Function: Prob2Score() * * Purpose: Convert a probability to a scaled integer log_2 odds score. * Round to nearest integer (i.e. note use of +0.5 and floor()) * Return the score. */ int Prob2Score(float p, float null) { if (p == 0.0) return -INFTY; else return (int) floor(0.5 + INTSCALE * sreLOG2(p/null)); } /* Function: Score2Prob() * * Purpose: Convert an integer log_2 odds score back to a probability; * needs the null model probability, if any, to do the conversion. */ float Score2Prob(int sc, float null) { if (sc == -INFTY) return 0.; else return (null * sreEXP2((float) sc / INTSCALE)); } /* Function: Scorify() * * Purpose: Convert a scaled integer log-odds score to a floating * point score for output. (could be a macro but who cares.) */ float Scorify(int sc) { return ((float) sc / INTSCALE); } /* Function: PValue() * Date: SRE, Mon Oct 27 12:21:02 1997 [Sanger Centre, UK] * * Purpose: Convert an HMM score to a P-value. * We know P(S>x) is bounded by 1 / (1 + exp_2^x) for a bit score of x. * We can also use EVD parameters for a tighter bound if we have * them available. * * Args: hmm - model structure, contains EVD parameters * sc - score in bits * * Returns: P value for score significance. */ double PValue(struct plan7_s *hmm, float sc) { double pval; double pval2; /* the bound from Bayes */ if (sc >= sreLOG2(DBL_MAX)) pval = 0.0; else if (sc <= -1. * sreLOG2(DBL_MAX)) pval = 1.0; else pval = 1. / (1.+sreEXP2(sc)); /* try for a better estimate from EVD fit */ if (hmm != NULL && (hmm->flags & PLAN7_STATS)) { pval2 = ExtremeValueP(sc, hmm->mu, hmm->lambda); if (pval2 < pval) pval = pval2; } return pval; } /* Function: LogSum() * * Purpose: Returns the log of the sum of two log probabilities. * log(exp(p1)+exp(p2)) = p1 + log(1 + exp(p2-p1)) for p1 > p2 * Note that this is in natural log space, not log_2. */ float LogSum(float p1, float p2) { if (p1 > p2) return (p1-p2 > 50.) ? p1 : p1 + log(1. + exp(p2-p1)); else return (p2-p1 > 50.) ? p2 : p2 + log(1. + exp(p1-p2)); } /* Function: ILogsum() * * Purpose: Return the scaled integer log probability of * the sum of two probabilities p1 and p2, where * p1 and p2 are also given as scaled log probabilities. * * log(exp(p1)+exp(p2)) = p1 + log(1 + exp(p2-p1)) for p1 > p2 * * For speed, builds a lookup table the first time it's called. * LOGSUM_TBL is set to 20000 by default, in config.h. * * Because of the one-time initialization, we have to * be careful in a multithreaded implementation... hence * the use of pthread_once(), which forces us to put * the initialization routine and the lookup table outside * ILogsum(). (Thanks to Henry Gabb at Intel for pointing * out this problem.) * * Args: p1,p2 -- scaled integer log_2 probabilities to be summed * in probability space. * * Return: scaled integer log_2 probability of the sum. */ static int ilogsum_lookup[LOGSUM_TBL]; static void init_ilogsum(void) { int i; for (i = 0; i < LOGSUM_TBL; i++) ilogsum_lookup[i] = (int) (INTSCALE * 1.44269504 * (log(1.+exp(0.69314718 * (float) -i/INTSCALE)))); } int ILogsum(int p1, int p2) { int diff; #ifdef HMMER_THREADS static pthread_once_t firsttime = PTHREAD_ONCE_INIT; pthread_once(&firsttime, init_ilogsum); #else static int firsttime = 1; if (firsttime) { init_ilogsum(); firsttime = 0; } #endif diff = p1-p2; if (diff >= LOGSUM_TBL) return p1; else if (diff <= -LOGSUM_TBL) return p2; else if (diff > 0) return p1 + ilogsum_lookup[diff]; else return p2 + ilogsum_lookup[-diff]; } /* Function: LogNorm() * * Purpose: Normalize a vector of log likelihoods, changing it * to a probability vector. Be careful of overflowing exp(). * Implementation adapted from Graeme Mitchison. * * Args: vec - vector destined to become log probabilities * n - length of vec */ void LogNorm(float *vec, int n) { int x; float max = -1.0e30; float denom = 0.; for (x = 0; x < n; x++) if (vec[x] > max) max = vec[x]; for (x = 0; x < n; x++) if (vec[x] > max - 50.) denom += exp(vec[x] - max); for (x = 0; x < n; x++) if (vec[x] > max - 50.) vec[x] = exp(vec[x] - max) / denom; else vec[x] = 0.0; } /* Function: Logp_cvec() * * Purpose: Calculates ln P(cvec|dirichlet), the log probability of a * count vector given a Dirichlet distribution. Adapted * from an implementation by Graeme Mitchison. * * Args: cvec - count vector * n - length of cvec * alpha - Dirichlet alpha terms * * Return: log P(cvec|dirichlet) */ float Logp_cvec(float *cvec, int n, float *alpha) { float lnp; /* log likelihood of P(cvec | Dirichlet) */ float sum1, sum2, sum3; int x; sum1 = sum2 = sum3 = lnp = 0.0; for (x = 0; x < n; x++) { sum1 += cvec[x] + alpha[x]; sum2 += alpha[x]; sum3 += cvec[x]; lnp += Gammln(alpha[x] + cvec[x]); lnp -= Gammln(cvec[x] + 1.); lnp -= Gammln(alpha[x]); } lnp -= Gammln(sum1); lnp += Gammln(sum2); lnp += Gammln(sum3 + 1.); return lnp; } /* Function: SampleDirichlet() * * Purpose: Given a Dirichlet distribution defined by * a vector of n alpha terms, sample of probability * distribution of dimension n. * * This code was derived from source provided * by Betty Lazareva, from Gary Churchill's group. * * Args: alpha - vector of Dirichlet alphas components * n - number of components * ret_p - RETURN: sampled probability vector. * * Return: (void) * ret_p, an n-dimensional array alloced by the caller, * is filled. */ void SampleDirichlet(float *alpha, int n, float *p) { int x; for (x = 0; x < n; x++) p[x] = SampleGamma(alpha[x]); FNorm(p, n); } /* Function: SampleGamma() * * Purpose: Return a random deviate distributed as Gamma(alpha, 1.0). * Uses two different accept/reject algorithms, one * for 0= 1.0) { /*CONSTCOND*/ while (1) { lambda = sqrt(2.0*alpha -1.0); U = sre_random(); V = U/(1-U); X = alpha * pow(V, 1/lambda); W = .25*exp(-X+alpha)*pow(float(V),float(1.0+alpha/lambda))*pow(float(1.0+1.0/V), float(2.0)); if (sre_random() <= W) return X; } } else if (alpha > 0.0) { /*CONSTCOND*/ while (1) { U = sre_random(); V = U*(1+ alpha/exp(1.0)); if (V > 1.0) { X = -log( (1-V+alpha/exp(1.0))/alpha); if (sre_random() <= pow(X, float(alpha-1.0))) return X; } else { X = pow(V, float(1.0/alpha)); if (sre_random() <= exp(-X)) return X; } } } Die("Invalid argument alpha < 0.0 to SampleGamma()"); /*NOTREACHED*/ return 0.0; } /* Function: SampleCountvector() * * Purpose: Given a probability vector p of dimensionality * n, sample c counts and store them in cvec. * cvec is n-dimensional and is alloced by the caller. */ void SampleCountvector(float *p, int n, int c, float *cvec) { int i; FSet(cvec, n, 0.0); for (i = 0; i < c; i++) cvec[FChoose(p,n)] += 1.0; } /* Function: P_PvecGivenDirichlet() * * Purpose: Calculate the log probability of a probability * vector given a single Dirichlet component, alpha. * Follows Sjolander (1996) appendix, lemma 2. * * Return: log P(p | alpha) */ float P_PvecGivenDirichlet(float *p, int n, float *alpha) { float sum; /* for Gammln(|alpha|) in Z */ float logp; /* RETURN: log P(p|alpha) */ int x; sum = logp = 0.0; for (x = 0; x < n; x++) if (p[x] > 0.0) /* any param that is == 0.0 doesn't exist */ { logp += (alpha[x]-1.0) * log(p[x]); logp -= Gammln(alpha[x]); sum += alpha[x]; } logp += Gammln(sum); return logp; } ugene-1.9.8/src/plugins_3rdparty/hmm2/src/hmmer2/config.h0000644000175000017500000000461511651544326021671 0ustar ilyailya/***************************************************************** * HMMER - Biological sequence analysis with profile HMMs * Copyright (C) 1992-2003 Washington University School of Medicine * All Rights Reserved * * This source code is distributed under the terms of the * GNU General Public License. See the files COPYING and LICENSE * for details. *****************************************************************/ #ifndef CONFIGH_INCLUDED #define CONFIGH_INCLUDED /* RAMLIMIT determines the point at which we switch from fast, * full dynamic programming to slow, linear-memory divide and conquer * dynamic programming algorithms. It is the minimum amount of available * RAM on the systems the package will run on. It can be overridden * from the Makefile. * By default, we assume we have 64 Mb RAM available (per thread). */ #ifndef RAMLIMIT #define RAMLIMIT 64 #endif /***************************************************************** * The following section probably shouldn't be edited, unless * you really know what you're doing. It controls some fundamental * parameters in HMMER that occasionally get reconfigured in * experimental versions, or for variants of HMMER that work on * non-biological alphabets. *****************************************************************/ #define INTSCALE 1000.0 /* scaling constant for floats to integer scores */ #define MAXABET 20 /* maximum size of alphabet (4 or 20) */ #define MAXCODE 24 /* maximum degenerate alphabet size (17 or 24) */ #define MAXDCHLET 200 /* maximum # Dirichlet components in mixture prior */ #define NINPUTS 4 /* number of inputs into structural prior */ #define INFTY 987654321 /* infinity for purposes of integer DP cells */ #define NXRAY 4 /* number of structural inputs */ #define LOGSUM_TBL 20000 /* controls precision of ILogsum() */ #define ALILENGTH 50 /* length of displayed alignment lines */ /* Version info - set once for whole package in configure.ac */ #define PACKAGE_NAME "HMMER" #define PACKAGE_VERSION "2.3.2" #define PACKAGE_DATE "Oct 2003" #define PACKAGE_COPYRIGHT "Copyright (C) 1992-2003 HHMI/Washington University School of Medicine" #define PACKAGE_LICENSE "Freely distributed under the GNU General Public License (GPL)" #endif /*CONFIGH_INCLUDED*/ ugene-1.9.8/src/plugins_3rdparty/hmm2/src/hmmer2/alphabet.cpp0000644000175000017500000002707711651544326022546 0ustar ilyailya/************************************************************ * HMMER - Biological sequence analysis with profile HMMs * Copyright (C) 1992-2003 Washington University School of Medicine * All Rights Reserved * * This source code is distributed under the terms of the * GNU General Public License. See the files COPYING and LICENSE * for details. ************************************************************/ /* alphabet.c * Configuration of the global symbol alphabet information. * CVS $Id: alphabet.c,v 1.13 2003/10/02 16:39:40 eddy Exp $ */ #include "funcs.h" static void set_degenerate(struct alphabet_s* al, char iupac, const char *syms); alphabet_s::alphabet_s() { Alphabet_type = hmmNOTSETYET; Alphabet_size = -1; Alphabet_iupac = - 1; } /* Function: SetAlphabet() * * Purpose: Set the alphabet globals, given an alphabet type * of either hmmAMINO or hmmNUCLEIC. */ void SetAlphabet(int type) { int x; /* Because the alphabet information is global, we must * be careful to make this a thread-safe function. The mutex * (above) takes care of that. But, indeed, it's also * just good sense (and more efficient) to simply never * allow resetting the alphabet. If type is Alphabet_type, * silently return; else die with an alphabet mismatch * warning. */ //get HMMERTaskLocalData HMMERTaskLocalData *tld = getHMMERTaskLocalData(); alphabet_s *al = &tld->al; if (al->Alphabet_type != hmmNOTSETYET) { assert(type == al->Alphabet_type); } //assert(al->Alphabet_type == 0); switch(type) { case hmmAMINO: al->Alphabet_type = type; sre_strlcpy(al->Alphabet, "ACDEFGHIKLMNPQRSTVWYUBZX", MAXCODE+1); al->Alphabet_size = 20; al->Alphabet_iupac = 24; for (x = 0; x < al->Alphabet_iupac; x++) { memset(al->Degenerate[x], 0, al->Alphabet_size); } for (x = 0; x < al->Alphabet_size; x++) { al->Degenerate[x][x] = 1; al->DegenCount[x] = 1; } set_degenerate(al, 'U', "S"); /* selenocysteine is treated as serine */ set_degenerate(al, 'B', "ND"); set_degenerate(al, 'Z', "QE"); set_degenerate(al, 'X', "ACDEFGHIKLMNPQRSTVWY"); break; case hmmNUCLEIC: al->Alphabet_type = type; sre_strlcpy(al->Alphabet, "ACGTUNRYMKSWHBVDX", MAXCODE + 1); al->Alphabet_size = 4; al->Alphabet_iupac = 17; for (x = 0; x < al->Alphabet_iupac; x++) { memset(al->Degenerate[x], 0, al->Alphabet_size); } for (x = 0; x < al->Alphabet_size; x++) { al->Degenerate[x][x] = 1; al->DegenCount[x] = 1; } set_degenerate(al, 'U', "T"); set_degenerate(al, 'N', "ACGT"); set_degenerate(al, 'X', "ACGT"); set_degenerate(al, 'R', "AG"); set_degenerate(al, 'Y', "CT"); set_degenerate(al, 'M', "AC"); set_degenerate(al, 'K', "GT"); set_degenerate(al, 'S', "CG"); set_degenerate(al, 'W', "AT"); set_degenerate(al, 'H', "ACT"); set_degenerate(al, 'B', "CGT"); set_degenerate(al, 'V', "ACG"); set_degenerate(al, 'D', "AGT"); break; default: Die("No support for non-nucleic or protein alphabets"); } } /* Function: SymbolIndex() * * Purpose: Convert a symbol to its index in Alphabet[]. * Bogus characters are converted to 'X'. * More robust than the SYMIDX() macro but * presumably slower. */ unsigned char SymbolIndex(char sym) { //get HMMERTaskLocalData HMMERTaskLocalData *tld = getHMMERTaskLocalData(); alphabet_s *al = &tld->al; char *s; return ((s = strchr(al->Alphabet, (char) toupper((int) sym))) == NULL) ? al->Alphabet_iupac-1 : s - al->Alphabet; } /* Function: DigitizeSequence() * * Purpose: Internal representation of a sequence in HMMER is * as a char array. 1..L are the indices * of seq symbols in Alphabet[]. 0,L+1 are sentinel * bytes, set to be Alphabet_iupac -- i.e. one more * than the maximum allowed index. * * Assumes that 'X', the fully degenerate character, * is the last character in the allowed alphabet. * * Args: seq - sequence to be digitized (0..L-1) * L - length of sequence * * Return: digitized sequence, dsq. * dsq is allocated here and must be free'd by caller. */ unsigned char * DigitizeSequence(const char *seq, int L) { unsigned char *dsq; int i; //get HMMERTaskLocalData HMMERTaskLocalData *tld = getHMMERTaskLocalData(); alphabet_s *al = &tld->al; dsq = (unsigned char*)MallocOrDie(sizeof(unsigned char) * (L+2)); dsq[0] = dsq[L+1] = (unsigned char) al->Alphabet_iupac; for (i = 1; i <= L; i++) dsq[i] = SymbolIndex(seq[i-1]); return dsq; } //hmmer-cell code unsigned char* DigitizeSequenceHP(const char *seq, int L, unsigned char* addr) { //Digitized sequences should be aligned for easier DMA transfer unsigned char *dsq; int i; dsq = (unsigned char*) addr; HMMERTaskLocalData *tld = getHMMERTaskLocalData(); alphabet_s *al = &tld->al; dsq[0] = dsq[L+1] = (unsigned char) al->Alphabet_iupac; for (i = 1; i <= L+1; i++) { dsq[i] = SymbolIndex(seq[i-1]); } return dsq; } /* Function: DedigitizeSequence() * Date: SRE, Tue Dec 16 10:39:19 1997 [StL] * * Purpose: Returns a 0..L-1 character string, converting the * dsq back to the real alphabet. */ char * DedigitizeSequence(unsigned char *dsq, int L) { char *seq; int i; //get HMMERTaskLocalData HMMERTaskLocalData *tld = getHMMERTaskLocalData(); alphabet_s *al = &tld->al; seq = (char*)MallocOrDie(sizeof(char) * (L+1)); for (i = 0; i < L; i++) seq[i] = al->Alphabet[dsq[i+1]]; seq[L] = '\0'; return seq; } /* Function: DigitizeAlignment() * * Purpose: Given an alignment, return digitized unaligned * sequence array. (Tracebacks are always relative * to digitized unaligned seqs, even if they are * faked from an existing alignment in modelmakers.c.) * * Args: msa - alignment to digitize * ret_dsqs - RETURN: array of digitized unaligned sequences * * Return: (void) * dsqs is alloced here. Free2DArray(dseqs, nseq). */ void DigitizeAlignment(MSA *msa, unsigned char ***ret_dsqs) { unsigned char **dsq; int idx; /* counter for sequences */ int dpos; /* position in digitized seq */ int apos; /* position in aligned seq */ //get HMMERTaskLocalData HMMERTaskLocalData *tld = getHMMERTaskLocalData(); alphabet_s *al = &tld->al; dsq = (unsigned char**)MallocOrDie(sizeof(unsigned char *) * msa->nseq); for (idx = 0; idx < msa->nseq; idx++) { dsq[idx] = (unsigned char*)MallocOrDie(sizeof(unsigned char) * (msa->alen+2)); dsq[idx][0] = (unsigned char) al->Alphabet_iupac; /* sentinel byte at start */ for (apos = 0, dpos = 1; apos < msa->alen; apos++) { if (! isgap(msa->aseq[idx][apos])) /* skip gaps */ dsq[idx][dpos++] = SymbolIndex(msa->aseq[idx][apos]); } dsq[idx][dpos] = (unsigned char) al->Alphabet_iupac; /* sentinel byte at end */ } *ret_dsqs = dsq; } /* Function: P7CountSymbol() * * Purpose: Given a possibly degenerate symbol code, increment * a symbol counter array (generally an emission * probability vector in counts form) appropriately. * * Args: counters: vector to count into. [0..Alphabet_size-1] * symidx: symbol index to count: [0..Alphabet_iupac-1] * wt: weight to use for the count; often 1.0 * * Return: (void) */ void P7CountSymbol(float *counters, unsigned char symidx, float wt) { int x; //get HMMERTaskLocalData HMMERTaskLocalData *tld = getHMMERTaskLocalData(); alphabet_s *al = &tld->al; if (symidx < al->Alphabet_size) counters[symidx] += wt; else for (x = 0; x < al->Alphabet_size; x++) { if (al->Degenerate[symidx][x]) counters[x] += wt / (float) al->DegenCount[symidx]; } } /* Function: DefaultCodonBias() * * Purpose: Configure a codonbias table, mapping triplets to * probability of using the triplet for the amino acid * it represents: P(triplet | aa). * The default is to assume codons are used equiprobably. * * Args: codebias: 0..63 array of P(triplet|aa), preallocated. * * Return: (void) */ void DefaultCodonBias(float *codebias) { codebias[0] = 1./2.; /* AAA Lys 2 */ codebias[1] = 1./2.; /* AAC Asn 2 */ codebias[2] = 1./2.; /* AAG Lys 2 */ codebias[3] = 1./2.; /* AAU Asn 2 */ codebias[4] = 1./4.; /* ACA Thr 4 */ codebias[5] = 1./4.; /* ACC Thr 4 */ codebias[6] = 1./4.; /* ACG Thr 4 */ codebias[7] = 1./4.; /* ACU Thr 4 */ codebias[8] = 1./6.; /* AGA Ser 6 */ codebias[9] = 1./6.; /* AGC Arg 6 */ codebias[10] = 1./6.; /* AGG Ser 6 */ codebias[11] = 1./6.; /* AGU Arg 6 */ codebias[12] = 1./3.; /* AUA Ile 3 */ codebias[13] = 1./3.; /* AUC Ile 3 */ codebias[14] = 1.; /* AUG Met 1 */ codebias[15] = 1./3.; /* AUU Ile 3 */ codebias[16] = 1./2.; /* CAA Gln 2 */ codebias[17] = 1./2.; /* CAC His 2 */ codebias[18] = 1./2.; /* CAG Gln 2 */ codebias[19] = 1./2.; /* CAU His 2 */ codebias[20] = 1./4.; /* CCA Pro 4 */ codebias[21] = 1./4.; /* CCC Pro 4 */ codebias[22] = 1./4.; /* CCG Pro 4 */ codebias[23] = 1./4.; /* CCU Pro 4 */ codebias[24] = 1./6.; /* CGA Arg 6 */ codebias[25] = 1./6.; /* CGC Arg 6 */ codebias[26] = 1./6.; /* CGG Arg 6 */ codebias[27] = 1./6.; /* CGU Arg 6 */ codebias[28] = 1./6.; /* CUA Leu 6 */ codebias[29] = 1./6.; /* CUC Leu 6 */ codebias[30] = 1./6.; /* CUG Leu 6 */ codebias[31] = 1./6.; /* CUU Leu 6 */ codebias[32] = 1./2.; /* GAA Glu 2 */ codebias[33] = 1./2.; /* GAC Asp 2 */ codebias[34] = 1./2.; /* GAG Glu 2 */ codebias[35] = 1./2.; /* GAU Asp 2 */ codebias[36] = 1./4.; /* GCA Ala 4 */ codebias[37] = 1./4.; /* GCC Ala 4 */ codebias[38] = 1./4.; /* GCG Ala 4 */ codebias[39] = 1./4.; /* GCU Ala 4 */ codebias[40] = 1./4.; /* GGA Gly 4 */ codebias[41] = 1./4.; /* GGC Gly 4 */ codebias[42] = 1./4.; /* GGG Gly 4 */ codebias[43] = 1./4.; /* GGU Gly 4 */ codebias[44] = 1./4.; /* GUA Val 4 */ codebias[45] = 1./4.; /* GUC Val 4 */ codebias[46] = 1./4.; /* GUG Val 4 */ codebias[47] = 1./4.; /* GUU Val 4 */ codebias[48] = 0.; /* UAA och - */ codebias[49] = 1./2.; /* UAC Tyr 2 */ codebias[50] = 0.; /* UAG amb - */ codebias[51] = 1./2.; /* UAU Tyr 2 */ codebias[52] = 1./6.; /* UCA Ser 6 */ codebias[53] = 1./6.; /* UCC Ser 6 */ codebias[54] = 1./6.; /* UCG Ser 6 */ codebias[55] = 1./6.; /* UCU Ser 6 */ codebias[56] = 0.; /* UGA opa - */ codebias[57] = 1./2.; /* UGC Cys 2 */ codebias[58] = 1.; /* UGG Trp 1 */ codebias[59] = 1./2.; /* UGU Cys 2 */ codebias[60] = 1./6.; /* UUA Leu 6 */ codebias[61] = 1./2.; /* UUC Phe 2 */ codebias[62] = 1./6.; /* UUG Leu 6 */ codebias[63] = 1./2.; /* UUU Phe 2 */ } /* Function: set_degenerate() * * Purpose: convenience function for setting up * Degenerate[][] global for the alphabet. */ static void set_degenerate(struct alphabet_s* al, char iupac, const char *syms) { al->DegenCount[strchr(al->Alphabet,iupac)-al->Alphabet] = strlen(syms); while (*syms) { al->Degenerate[strchr(al->Alphabet,iupac)-al->Alphabet] [strchr(al->Alphabet,*syms)-al->Alphabet] = 1; syms++; } } ugene-1.9.8/src/plugins_3rdparty/hmm2/src/hmmer2/modelmakers.cpp0000644000175000017500000010061311651544326023255 0ustar ilyailya/***************************************************************** * HMMER - Biological sequence analysis with profile HMMs * Copyright (C) 1992-2003 Washington University School of Medicine * All Rights Reserved * * This source code is distributed under the terms of the * GNU General Public License. See the files COPYING and LICENSE * for details. *****************************************************************/ /* modelmakers.c * SRE, Fri Nov 15 10:00:04 1996 * * Construction of models from multiple alignments. Three versions: * Handmodelmaker() -- use #=RF annotation to indicate match columns * Fastmodelmaker() -- Krogh/Haussler heuristic * Maxmodelmaker() -- MAP model construction algorithm (Eddy, * unpublished) * * The meat of the model construction code is in matassign2hmm(). * The three model construction strategies simply label which columns * are supposed to be match states, and then hand this info to * matassign2hmm(). * * Two wrinkles to watch for: * 1) The alignment is assumed to contain sequence fragments. Look in * fake_tracebacks() for how internal entry/exit points are handled. * 2) Plan7 disallows DI and ID transitions, but an alignment may * imply these. Look in trace_doctor() for how DI and ID transitions * are removed. */ #include "funcs.h" /* flags used for matassign[] arrays -- * assignment of aligned columns to match/insert states */ #define ASSIGN_MATCH (1<<0) #define FIRST_MATCH (1<<1) #define LAST_MATCH (1<<2) #define ASSIGN_INSERT (1<<3) #define EXTERNAL_INSERT_N (1<<4) #define EXTERNAL_INSERT_C (1<<5) static int build_cij(char **aseqs, int nseq, int *insopt, int i, int j, float *wgt, float *cij); static int estimate_model_length(MSA *msa); static void matassign2hmm(MSA *msa, unsigned char **dsq, int *matassign, struct plan7_s **ret_hmm, struct p7trace_s ***ret_tr); static void fake_tracebacks(char **aseq, int nseq, int alen, int *matassign, struct p7trace_s ***ret_tr); static void trace_doctor(struct p7trace_s *tr, int M, int *ret_ndi, int *ret_nid); static void annotate_model(struct plan7_s *hmm, int *matassign, MSA *msa); /* Function: P7Handmodelmaker() * * Purpose: Manual model construction: * Construct an HMM from an alignment, where the #=RF line * of a HMMER alignment file is given to indicate * the columns assigned to matches vs. inserts. * * NOTE: Handmodelmaker() will slightly revise the alignment * if necessary, if the assignment of columns implies * DI and ID transitions. * * Returns both the HMM in counts form (ready for applying * Dirichlet priors as the next step), and fake tracebacks * for each aligned sequence. * * Args: msa - multiple sequence alignment * dsq - digitized unaligned aseq's * ret_hmm - RETURN: counts-form HMM * ret_tr - RETURN: array of tracebacks for aseq's * * Return: (void) * ret_hmm and ret_tr alloc'ed here; FreeTrace(tr[i]), free(tr), * FreeHMM(hmm). */ void P7Handmodelmaker(MSA *msa, unsigned char **dsq, struct plan7_s **ret_hmm, struct p7trace_s ***ret_tr) { int *matassign; /* MAT state assignments if 1; 1..alen */ int apos; /* counter for aligned columns */ /* Make sure we have all the info about the alignment that we need */ if (msa->rf == NULL) Die("Alignment must have RF annotation to hand-build an HMM"); /* Allocation */ matassign = (int *) MallocOrDie (sizeof(int) * (msa->alen+1)); /* Determine match assignment from optional annotation */ matassign[0] = 0; for (apos = 0; apos < msa->alen; apos++) { matassign[apos+1] = 0; if (!isgap(msa->rf[apos])) matassign[apos+1] |= ASSIGN_MATCH; else matassign[apos+1] |= ASSIGN_INSERT; } /* Hand matassign off for remainder of model construction */ /* print_matassign(matassign, msa->alen); */ matassign2hmm(msa, dsq, matassign, ret_hmm, ret_tr); free(matassign); return; } /* Function: P7Fastmodelmaker() * * Purpose: Heuristic model construction: * Construct an HMM from an alignment using the original * Krogh/Haussler heuristic; any column with more * symbols in it than a given fraction is assigned to * match. * * NOTE: Fastmodelmaker() will slightly revise the * alignment if the assignment of columns implies * DI and ID transitions. * * Returns the HMM in counts form (ready for applying Dirichlet * priors as the next step). Also returns fake traceback * for each training sequence. * * Args: msa - multiple sequence alignment * dsq - digitized unaligned aseq's * maxgap - if more gaps than this, column becomes insert. * ret_hmm - RETURN: counts-form HMM * ret_tr - RETURN: array of tracebacks for aseq's * * Return: (void) * ret_hmm and ret_tr alloc'ed here; FreeTrace(tr[i]), free(tr), * FreeHMM(hmm). */ void P7Fastmodelmaker(MSA *msa, unsigned char **dsq, float maxgap, struct plan7_s **ret_hmm, struct p7trace_s ***ret_tr) { int *matassign; /* MAT state assignments if 1; 1..alen */ int idx; /* counter over sequences */ int apos; /* counter for aligned columns */ int ngap; /* number of gaps in a column */ /* Allocations: matassign is 1..alen array of bit flags */ matassign = (int *) MallocOrDie (sizeof(int) * (msa->alen+1)); /* Determine match assignment by counting symbols in columns */ matassign[0] = 0; for (apos = 0; apos < msa->alen; apos++) { matassign[apos+1] = 0; ngap = 0; for (idx = 0; idx < msa->nseq; idx++) if (isgap(msa->aseq[idx][apos])) ngap++; if ((float) ngap / (float) msa->nseq > maxgap) matassign[apos+1] |= ASSIGN_INSERT; else matassign[apos+1] |= ASSIGN_MATCH; } /* Once we have matassign calculated, all modelmakers behave * the same; matassign2hmm() does this stuff (traceback construction, * trace counting) and sets up ret_hmm and ret_tr. */ matassign2hmm(msa, dsq, matassign, ret_hmm, ret_tr); free(matassign); return; } /* Function: P7Maxmodelmaker() * * Purpose: The Unholy Beast of HMM model construction algorithms -- * maximum a posteriori construction. A tour de force and * probably overkill. MAP construction for Krogh * HMM-profiles is fairly straightforward, but MAP construction of * Plan 7 HMM-profiles is, er, intricate. * * Given a multiple alignment, construct an optimal (MAP) model * architecture. Return a counts-based HMM. * * Args: msa - multiple sequence alignment * dsq - digitized, unaligned seqs * maxgap - above this, trailing columns are assigned to C * prior - priors on parameters to use for model construction * null - random sequence model emissions * null_p1 - random sequence model p1 transition * mpri - prior on architecture: probability of new match node * ret_hmm - RETURN: new hmm (counts form) * ret_tr - RETURN: array of tracebacks for aseq's * * Return: (void) * ret_hmm and ret_tr (if !NULL) must be free'd by the caller. */ void P7Maxmodelmaker(MSA *msa, unsigned char **dsq, float maxgap, struct p7prior_s *prior, float *null, float null_p1, float mpri, struct plan7_s **ret_hmm, struct p7trace_s ***ret_tr) { int idx; /* counter for seqs */ int i, j; /* positions in alignment */ int x; /* counter for syms or transitions */ float **matc; /* count vectors: [1..alen][0..19] */ float cij[8], tij[8]; /* count and score transit vectors */ float matp[MAXABET]; /* match emission vector */ float insp[MAXABET]; /* insert score vector */ float insc[MAXABET]; /* insert count vector */ float *sc; /* DP scores [0,1..alen,alen+1] */ int *tbck; /* traceback ptrs for sc */ int *matassign; /* match assignments [1..alen] */ int *insopt; /* number of inserted chars [0..nseq-1] */ int first, last; /* positions of first and last cols [1..alen] */ float bm1, bm2; /* estimates for start,internal b->m t's */ int est_M; /* estimate for the size of the model */ float t_me; /* estimate for an internal M->E transition */ float newF, bestsc; /* new score, best score so far */ int code; /* optimization: return code from build_cij() */ int ngap; /* gap count in a column */ float wgtsum; /* sum of weights; do not assume it is nseq */ //get HMMERTaskLocalData HMMERTaskLocalData *tld = getHMMERTaskLocalData(); alphabet_s *al = &tld->al; /* Allocations */ matc = (float **) MallocOrDie (sizeof(float *) * (msa->alen+1)); sc = (float *) MallocOrDie (sizeof(float) * (msa->alen+2)); tbck = (int *) MallocOrDie (sizeof(int) * (msa->alen+2)); matassign = (int *) MallocOrDie (sizeof(int) * (msa->alen+1)); insopt = (int *) MallocOrDie (sizeof(int) * msa->nseq); for (i = 0; i < msa->alen; i++) { matc[i+1] = (float *) MallocOrDie (al->Alphabet_size * sizeof(float)); FSet(matc[i+1], al->Alphabet_size, 0.); } /* Precalculations */ for (i = 0; i < msa->alen; i++) for (idx = 0; idx < msa->nseq; idx++) if (!isgap(msa->aseq[idx][i])) P7CountSymbol(matc[i+1], SymbolIndex(msa->aseq[idx][i]), msa->wgt[idx]); mpri = sreLOG2(mpri); FCopy(insp, prior->i[0], al->Alphabet_size); FNorm(insp, al->Alphabet_size); wgtsum = FSum(msa->wgt, msa->nseq); for (x = 0; x < al->Alphabet_size; x++) insp[x] = sreLOG2(insp[x] / null[x]); /* Estimate the relevant special transitions. */ est_M = estimate_model_length(msa); t_me = 0.5 / (float) (est_M-1); bm1 = 0.5; bm2 = 0.5 / (float) (est_M-1); bm1 = sreLOG2(bm1 / null_p1); bm2 = sreLOG2(bm2 / null_p1); /* Estimate the position of the last match-assigned column * by counting gap frequencies. */ maxgap = 0.5; for (last = msa->alen; last >= 1; last--) { ngap = 0; for (idx = 0; idx < msa->nseq; idx++) if (isgap(msa->aseq[idx][last-1])) ngap++; if ((float) ngap / (float) msa->nseq <= maxgap) break; } /* Initialization */ sc[last] = 0.; tbck[last] = 0; /* Set ME gaps to '_' */ for (idx = 0; idx < msa->nseq; idx++) for (i = last; i > 0 && isgap(msa->aseq[idx][i-1]); i--) msa->aseq[idx][i-1] = '_'; /* Main recursion moves from right to left. */ for (i = last-1; i > 0; i--) { /* Calculate match emission scores for i */ FCopy(matp, matc[i], al->Alphabet_size); P7PriorifyEmissionVector(matp, prior, prior->mnum, prior->mq, prior->m, NULL); for (x = 0; x < al->Alphabet_size; x++) matp[x] = sreLOG2(matp[x] / null[x]); /* Initialize insert counters to zero */ FSet(insc, al->Alphabet_size, 0.); for (idx = 0; idx < msa->nseq; idx++) insopt[idx] = 0; sc[i] = -FLT_MAX; for (j = i+1; j <= last; j++) { /* build transition matrix for column pair i,j */ code = build_cij(msa->aseq, msa->nseq, insopt, i, j, msa->wgt, cij); if (code == -1) break; /* no j to our right can work for us */ if (code == 1) { FCopy(tij, cij, 7); P7PriorifyTransitionVector(tij, prior, prior->tq); FNorm(tij, 3); tij[TMM] = sreLOG2(tij[TMM] / null_p1); tij[TMI] = sreLOG2(tij[TMI] / null_p1); tij[TMD] = sreLOG2(tij[TMD]); tij[TIM] = sreLOG2(tij[TIM] / null_p1); tij[TII] = sreLOG2(tij[TII] / null_p1); tij[TDM] = sreLOG2(tij[TDM] / null_p1); tij[TDD] = sreLOG2(tij[TDD]); /* calculate the score of using this j. */ newF = sc[j] + FDot(tij, cij, 7) + FDot(insp, insc, al->Alphabet_size); SQD_DPRINTF2(("%3d %3d new=%6.2f scj=%6.2f m=%6.2f i=%6.2f t=%6.2f\n", i, j, new, sc[j], FDot(matp, matc[i], Alphabet_size), FDot(insp, insc, Alphabet_size), FDot(tij, cij, 7))); /* keep it if it's better */ if (newF > sc[i]) { sc[i] = newF; tbck[i] = j; } } /* bump insc, insopt insert symbol counters */ FAdd(insc, matc[j], al->Alphabet_size); for (idx = 0; idx < msa->nseq; idx++) if (!isgap(msa->aseq[idx][j-1])) insopt[idx]++; } /* add in constant contributions for col i */ /* note ad hoc scaling of mpri by wgtsum (us. nseq)*/ sc[i] += FDot(matp, matc[i], al->Alphabet_size) + mpri * wgtsum; } /* end loop over start positions i */ /* Termination: place the begin state. * log odds score for S->N->B is all zero except for NB transition, which * is a constant. So we only have to evaluate BM transitions. */ bestsc = -FLT_MAX; first = 0; for (i = 1; i <= last; i++) { newF = sc[i]; for (idx = 0; idx < msa->nseq; idx++) { if (isgap(msa->aseq[idx][i-1])) newF += bm2; /* internal B->M transition */ else newF += bm1; /* B->M1 transition */ } if (newF > bestsc) { bestsc = newF; first = i; } } /* Traceback */ matassign[0] = 0; for (i = 1; i <= msa->alen; i++) matassign[i] = ASSIGN_INSERT; for (i = first; i != 0; i = tbck[i]) { matassign[i] &= ~ASSIGN_INSERT; matassign[i] |= ASSIGN_MATCH; } /* Hand matassign off for remainder of model construction */ /* print_matassign(matassign, ainfo->alen); */ matassign2hmm(msa, dsq, matassign, ret_hmm, ret_tr); /* Clean up. */ for (i = 1; i <= msa->alen; i++) free(matc[i]); free(matc); free(sc); free(tbck); free(matassign); free(insopt); } /* Function: build_cij() * * Purpose: Construct a counts vector for transitions between * column i and column j in a multiple alignment. * * '_' gap characters indicate "external" gaps which * are to be dealt with by B->M and M->E transitions. * These characters must be placed by a preprocessor. * * insopt is an "insert optimization" -- an incrementor * which keeps track of the number of insert symbols * between i and j. * * Args: aseqs - multiple alignment. [0.nseq-1][0.alen-1] * nseq - number of seqs in aseqs * insopt - number of inserts per seq between i/j [0.nseq-1] * i - i column [1.alen], off by one from aseqs * j - j column [1.alen], off by one from aseqs * wgt - per-seq weights [0.nseq-1] * cij - transition count vectors [0..7] * * Return: -1 if an illegal transition was seen for this i/j assignment *and* * we are guaranteed that any j to the right will also * have illegal transitions. * 0 if an illegal transition was seen, but a j further to the * right may work. * 1 if all transitions were legal. */ static int build_cij(char **aseqs, int nseq, int *insopt, int i, int j, float *wgt, float *cij) { int idx; /* counter for seqs */ i--; /* make i,j relative to aseqs [0..alen-1] */ j--; FSet(cij, 8, 0.); /* zero cij */ for (idx = 0; idx < nseq; idx++) { if (insopt[idx] > 0) { if (isgap(aseqs[idx][i])) return -1; /* D->I prohibited. */ if (isgap(aseqs[idx][j])) return 0; /* I->D prohibited. */ cij[TMI] += wgt[idx]; cij[TII] += (insopt[idx]-1) * wgt[idx]; cij[TIM] += wgt[idx]; } else { if (!isgap(aseqs[idx][i])) { if (aseqs[idx][j] == '_') ; /* YO! what to do with trailer? */ else if (isgap(aseqs[idx][j])) cij[TMD] += wgt[idx]; else cij[TMM] += wgt[idx]; } else { /* ignores B->E possibility */ if (aseqs[idx][j] == '_') continue; else if (isgap(aseqs[idx][j])) cij[TDD] += wgt[idx]; else cij[TDM] += wgt[idx]; } } } return 1; } /* Function: estimate_model_length() * * Purpose: Return a decent guess about the length of the model, * based on the lengths of the sequences. * * Algorithm is dumb: use weighted average length. * * Don't assume that weights sum to nseq! */ static int estimate_model_length(MSA *msa) { int idx; float total = 0.; float wgtsum = 0.; for (idx = 0; idx < msa->nseq; idx++) { total += msa->wgt[idx] * DealignedLength(msa->aseq[idx]); wgtsum += msa->wgt[idx]; } return (int) (total / wgtsum); } /* Function: matassign2hmm() * * Purpose: Given an assignment of alignment columns to match vs. * insert, finish the final part of the model construction * calculation that is constant between model construction * algorithms. * * Args: msa - multiple sequence alignment * dsq - digitized unaligned aseq's * matassign - 1..alen bit flags for column assignments * ret_hmm - RETURN: counts-form HMM * ret_tr - RETURN: array of tracebacks for aseq's * * Return: (void) * ret_hmm and ret_tr alloc'ed here for the calling * modelmaker function. */ static void matassign2hmm(MSA *msa, unsigned char **dsq, int *matassign, struct plan7_s **ret_hmm, struct p7trace_s ***ret_tr) { struct plan7_s *hmm; /* RETURN: new hmm */ struct p7trace_s **tr; /* fake tracebacks for each seq */ int M; /* length of new model in match states */ int idx; /* counter over sequences */ int apos; /* counter for aligned columns */ /* how many match states in the HMM? */ M = 0; for (apos = 1; apos <= msa->alen; apos++) { if (matassign[apos] & ASSIGN_MATCH) M++; } if (M == 0) Die("No conserved consensus columns found; aborting construction!\n\ This is an unusual situation. Reexamine your sequence alignment. It is\n\ probably unusually full of gaps, or lots of sequence fragments. You may be\n\ able to force HMMER to model it; see the --fast (and --gapmax), or --hand\n\ options to hmmbuild."); /* delimit N-terminal tail */ for (apos=1; matassign[apos] & ASSIGN_INSERT && apos <= msa->alen; apos++) matassign[apos] |= EXTERNAL_INSERT_N; if (apos <= msa->alen) matassign[apos] |= FIRST_MATCH; /* delimit C-terminal tail */ for (apos=msa->alen; matassign[apos] & ASSIGN_INSERT && apos > 0; apos--) matassign[apos] |= EXTERNAL_INSERT_C; if (apos > 0) matassign[apos] |= LAST_MATCH; /* print_matassign(matassign, msa->alen); */ /* make fake tracebacks for each seq */ fake_tracebacks(msa->aseq, msa->nseq, msa->alen, matassign, &tr); /* build model from tracebacks */ hmm = AllocPlan7(M); ZeroPlan7(hmm); for (idx = 0; idx < msa->nseq; idx++) { /* P7PrintTrace(stdout, tr[idx], NULL, NULL); */ P7TraceCount(hmm, dsq[idx], msa->wgt[idx], tr[idx]); } /* annotate new model */ annotate_model(hmm, matassign, msa); /* Set #=RF line of alignment to reflect our assignment * of match, delete. matassign is valid from 1..alen and is off * by one from msa->rf. */ if (msa->rf != NULL) free(msa->rf); msa->rf = (char *) MallocOrDie (sizeof(char) * (msa->alen + 1)); for (apos = 0; apos < msa->alen; apos++) msa->rf[apos] = matassign[apos+1] & ASSIGN_MATCH ? 'x' : '.'; msa->rf[msa->alen] = '\0'; /* Cleanup and return. */ if (ret_tr != NULL) *ret_tr = tr; else { for (idx = 0; idx < msa->nseq; idx++) P7FreeTrace(tr[idx]); free(tr); } if (ret_hmm != NULL) *ret_hmm = hmm; else FreePlan7(hmm); return; } /* Function: fake_tracebacks() * * Purpose: From a consensus assignment of columns to MAT/INS, construct fake * tracebacks for each individual sequence. * * Note: Fragment tolerant by default. Internal entries are * B->M_x, instead of B->D1->D2->...->M_x; analogously * for internal exits. * * Args: aseqs - alignment [0..nseq-1][0..alen-1] * nseq - number of seqs in alignment * alen - length of alignment in columns * matassign - assignment of column; [1..alen] (off one from aseqs) * ret_tr - RETURN: array of tracebacks * * Return: (void) * ret_tr is alloc'ed here. Caller must free. */ static void fake_tracebacks(char **aseq, int nseq, int alen, int *matassign, struct p7trace_s ***ret_tr) { struct p7trace_s **tr; int idx; /* counter over sequences */ int i; /* position in raw sequence (1..L) */ int k; /* position in HMM */ int apos; /* position in alignment columns */ int tpos; /* position in traceback */ tr = (struct p7trace_s **) MallocOrDie (sizeof(struct p7trace_s *) * nseq); for (idx = 0; idx < nseq; idx++) { P7AllocTrace(alen+6, &tr[idx]); /* allow room for S,N,B,E,C,T */ /* all traces start with S state... */ tr[idx]->statetype[0] = STS; tr[idx]->nodeidx[0] = 0; tr[idx]->pos[0] = 0; /* ...and transit to N state; N-term tail is emitted on N->N transitions */ tr[idx]->statetype[1] = STN; tr[idx]->nodeidx[1] = 0; tr[idx]->pos[1] = 0; i = 1; k = 0; tpos = 2; for (apos = 0; apos < alen; apos++) { tr[idx]->statetype[tpos] = STBOGUS; /* bogus, deliberately, to debug */ if (matassign[apos+1] & FIRST_MATCH) { /* BEGIN */ tr[idx]->statetype[tpos] = STB; tr[idx]->nodeidx[tpos] = 0; tr[idx]->pos[tpos] = 0; tpos++; } if (matassign[apos+1] & ASSIGN_MATCH && ! isgap(aseq[idx][apos])) { /* MATCH */ k++; /* move to next model pos */ tr[idx]->statetype[tpos] = STM; tr[idx]->nodeidx[tpos] = k; tr[idx]->pos[tpos] = i; i++; tpos++; } else if (matassign[apos+1] & ASSIGN_MATCH) { /* DELETE */ /* being careful about S/W transitions; no B->D transitions */ k++; /* *always* move on model when ASSIGN_MATCH */ if (tr[idx]->statetype[tpos-1] != STB) { tr[idx]->statetype[tpos] = STD; tr[idx]->nodeidx[tpos] = k; tr[idx]->pos[tpos] = 0; tpos++; } } else if (matassign[apos+1] & EXTERNAL_INSERT_N && ! isgap(aseq[idx][apos])) { /* N-TERMINAL TAIL */ tr[idx]->statetype[tpos] = STN; tr[idx]->nodeidx[tpos] = 0; tr[idx]->pos[tpos] = i; i++; tpos++; } else if (matassign[apos+1] & EXTERNAL_INSERT_C && ! isgap(aseq[idx][apos])) { /* C-TERMINAL TAIL */ tr[idx]->statetype[tpos] = STC; tr[idx]->nodeidx[tpos] = 0; tr[idx]->pos[tpos] = i; i++; tpos++; } else if (! isgap(aseq[idx][apos])) { /* INSERT */ tr[idx]->statetype[tpos] = STI; tr[idx]->nodeidx[tpos] = k; tr[idx]->pos[tpos] = i; i++; tpos++; } if (matassign[apos+1] & LAST_MATCH) { /* END */ /* be careful about S/W transitions; may need to roll * back over some D's because there's no D->E transition */ while (tr[idx]->statetype[tpos-1] == STD) tpos--; tr[idx]->statetype[tpos] = STE; tr[idx]->nodeidx[tpos] = 0; tr[idx]->pos[tpos] = 0; tpos++; /* and then transit E->C; alignments that use J are undefined; C-term tail is emitted on C->C transitions */ tr[idx]->statetype[tpos] = STC; tr[idx]->nodeidx[tpos] = 0; tr[idx]->pos[tpos] = 0; tpos++; } } /* all traces end with T state */ tr[idx]->statetype[tpos] = STT; tr[idx]->nodeidx[tpos] = 0; tr[idx]->pos[tpos] = 0; tr[idx]->tlen = ++tpos; /* deal with DI, ID transitions */ /* k == M here */ trace_doctor(tr[idx], k, NULL, NULL); } /* end for sequence # idx */ *ret_tr = tr; return; } /* Function: trace_doctor() * * Purpose: Plan 7 disallows D->I and I->D "chatter" transitions. * However, these transitions may be implied by many * alignments for hand- or heuristic- built HMMs. * trace_doctor() collapses I->D or D->I into a * single M position in the trace. * Similarly, B->I and I->E transitions may be implied * by an alignment. * * trace_doctor does not examine any scores when it does * this. In ambiguous situations (D->I->D) the symbol * will be pulled arbitrarily to the left, regardless * of whether that's the best column to put it in or not. * * Args: tr - trace to doctor * M - length of model that traces are for * ret_ndi - number of DI transitions doctored * ret_nid - number of ID transitions doctored * * Return: (void) * tr is modified */ static void trace_doctor(struct p7trace_s *tr, int mlen, int *ret_ndi, int *ret_nid) { int opos; /* position in old trace */ int npos; /* position in new trace (<= opos) */ int ndi, nid; /* number of DI, ID transitions doctored */ /* overwrite the trace from left to right */ ndi = nid = 0; opos = npos = 0; while (opos < tr->tlen) { /* fix implied D->I transitions; D transforms to M, I pulled in */ if (tr->statetype[opos] == STD && tr->statetype[opos+1] == STI) { tr->statetype[npos] = STM; tr->nodeidx[npos] = tr->nodeidx[opos]; /* D transforms to M */ tr->pos[npos] = tr->pos[opos+1]; /* insert char moves back */ opos += 2; npos += 1; ndi++; } /* fix implied I->D transitions; D transforms to M, I is pushed in */ else if (tr->statetype[opos]== STI && tr->statetype[opos+1]== STD) { tr->statetype[npos] = STM; tr->nodeidx[npos] = tr->nodeidx[opos+1];/* D transforms to M */ tr->pos[npos] = tr->pos[opos]; /* insert char moves up */ opos += 2; npos += 1; nid++; } /* fix implied B->I transitions; pull I back to its M */ else if (tr->statetype[opos]== STI && tr->statetype[opos-1]== STB) { tr->statetype[npos] = STM; tr->nodeidx[npos] = tr->nodeidx[opos]; /* offending I transforms to M */ tr->pos[npos] = tr->pos[opos]; opos++; npos++; } /* fix implied I->E transitions; push I to next M */ else if (tr->statetype[opos]== STI && tr->statetype[opos+1]== STE) { tr->statetype[npos] = STM; tr->nodeidx[npos] = tr->nodeidx[opos]+1;/* offending I transforms to M */ tr->pos[npos] = tr->pos[opos]; opos++; npos++; } /* rare: N-N-B-E becomes N-B-M_1-E (swap B,N) */ else if (tr->statetype[opos]==STB && tr->statetype[opos+1]==STE && tr->statetype[opos-1]==STN && tr->pos[opos-1] > 0) { tr->statetype[npos] = STM; tr->nodeidx[npos] = 1; tr->pos[npos] = tr->pos[opos-1]; tr->statetype[npos-1] = STB; tr->nodeidx[npos-1] = 0; tr->pos[npos-1] = 0; opos++; npos++; } /* rare: B-E-C-C-x becomes B-M_M-E-C-x (swap E,C) */ else if (tr->statetype[opos]==STE && tr->statetype[opos-1]==STB && tr->statetype[opos+1]==STC && tr->statetype[opos+2]==STC) { tr->statetype[npos] = STM; tr->nodeidx[npos] = mlen; tr->pos[npos] = tr->pos[opos+2]; tr->statetype[npos+1] = STE; tr->nodeidx[npos+1] = 0; tr->pos[npos+1] = 0; tr->statetype[npos+2] = STC; /* first C must be a nonemitter */ tr->nodeidx[npos+2] = 0; tr->pos[npos+2] = 0; opos+=3; npos+=3; } /* everything else is just copied */ else { tr->statetype[npos] = tr->statetype[opos]; tr->nodeidx[npos] = tr->nodeidx[opos]; tr->pos[npos] = tr->pos[opos]; opos++; npos++; } } tr->tlen = npos; if (ret_ndi != NULL) *ret_ndi = ndi; if (ret_nid != NULL) *ret_nid = nid; return; } /* Function: annotate_model() * * Purpose: Add rf, cs optional annotation to a new model. * * Args: hmm - new model * matassign - which alignment columns are MAT; [1..alen] * msa - alignment, including annotation to transfer * * Return: (void) */ static void annotate_model(struct plan7_s *hmm, int *matassign, MSA *msa) { int apos; /* position in matassign, 1.alen */ int k; /* position in model, 1.M */ /* Transfer reference coord annotation from alignment, * if available */ if (msa->rf != NULL) { hmm->rf[0] = ' '; for (apos = k = 1; apos <= msa->alen; apos++) if (matassign[apos] & ASSIGN_MATCH) /* ainfo is off by one from HMM */ hmm->rf[k++] = (msa->rf[apos-1] == ' ') ? '.' : msa->rf[apos-1]; hmm->rf[k] = '\0'; hmm->flags |= PLAN7_RF; } /* Transfer consensus structure annotation from alignment, * if available */ if (msa->ss_cons != NULL) { hmm->cs[0] = ' '; for (apos = k = 1; apos <= msa->alen; apos++) if (matassign[apos] & ASSIGN_MATCH) hmm->cs[k++] = (msa->ss_cons[apos-1] == ' ') ? '.' : msa->ss_cons[apos-1]; hmm->cs[k] = '\0'; hmm->flags |= PLAN7_CS; } /* Transfer surface accessibility annotation from alignment, * if available */ if (msa->sa_cons != NULL) { hmm->ca[0] = ' '; for (apos = k = 1; apos <= msa->alen; apos++) if (matassign[apos] & ASSIGN_MATCH) hmm->ca[k++] = (msa->sa_cons[apos-1] == ' ') ? '.' : msa->sa_cons[apos-1]; hmm->ca[k] = '\0'; hmm->flags |= PLAN7_CA; } /* Store the alignment map */ for (apos = k = 1; apos <= msa->alen; apos++) if (matassign[apos] & ASSIGN_MATCH) hmm->map[k++] = apos; hmm->flags |= PLAN7_MAP; } ugene-1.9.8/src/plugins_3rdparty/hmm2/src/hmmer2/funcs.h0000644000175000017500000004241611651544326021543 0ustar ilyailya/************************************************************ * HMMER - Biological sequence analysis with profile HMMs * Copyright (C) 1992-2003 Washington University School of Medicine * All Rights Reserved * * This source code is distributed under the terms of the * GNU General Public License. See the files COPYING and LICENSE * for details. ************************************************************/ /* funcs.h * RCS $Id: funcs.h,v 1.37 2003/10/02 16:39:41 eddy Exp $ * * Declarations of external functions in HMMER. */ #ifndef FUNCSH_INCLUDED #define FUNCSH_INCLUDED #include "config.h" #include "structs.h" #include #include #include #include #include #include #include #include #include // aligneval.cpp extern float ComparePairAlignments(char *known1, char *known2, char *calc1, char *calc2); extern float CompareRefPairAlignments(int *ref, char *known1, char *known2, char *calc1, char *calc2); extern float CompareMultAlignments(char **kseqs, char **tseqs, int N); extern float CompareRefMultAlignments(int *ref, char **kseqs, char **tseqs, int N); extern float PairwiseIdentity(char *s1, char *s2); extern float AlignmentIdentityBySampling(char **aseq, int L, int N, int nsample); extern char *MajorityRuleConsensus(char **aseq, int nseq, int alen); extern int DealignedLength(char *aseq); extern int MakeAlignedString(char *aseq, int alen, char *ss, char **ret_s); // alphabet.cpp extern void SetAlphabet(int type); extern unsigned char SymbolIndex(char sym); extern unsigned char *DigitizeSequence(const char *seq, int L); extern unsigned char *DigitizeSequenceHP(const char *seq, int L, unsigned char *addr); extern char *DedigitizeSequence(unsigned char *dsq, int L); extern void DigitizeAlignment(MSA *msa, unsigned char ***ret_dsqs); extern void P7CountSymbol(float *counters, unsigned char sym, float wt); extern void DefaultGeneticCode(int *aacode); extern void DefaultCodonBias(float *codebias); // checksum.cpp extern int GCGchecksum(char *seq, int seqlen); extern int GCGMultchecksum(char **seqs, int nseq); // cluster.cpp extern int Cluster(float **mx, int N, enum clust_strategy mode, struct phylo_s **ret_tree); extern struct phylo_s *AllocPhylo(int N); extern void FreePhylo(struct phylo_s *tree, int N); extern void MakeDiffMx(char **aseqs, int num, float ***ret_dmx); extern void MakeIdentityMx(char **aseqs, int num, float ***ret_imx); //core_algorithms.cpp //Clean research/demonstration versions of basic algorithms. extern struct dpmatrix_s *CreatePlan7Matrix(int N, int M, int padN, int padM); extern void ResizePlan7Matrix(struct dpmatrix_s *mx, int N, int M, int ***xmx, int ***mmx, int ***imx, int ***dmx); struct dpmatrix_s *AllocPlan7Matrix(int rows, int M, int ***xmx, int ***mmx, int ***imx, int ***dmx); extern struct dpshadow_s *AllocShadowMatrix(int rows, int M, char ***xtb, char ***mtb, char ***itb, char ***dtb); extern void FreePlan7Matrix(struct dpmatrix_s *mx); extern void FreeShadowMatrix(struct dpshadow_s *tb); extern int P7ViterbiSpaceOK(int L, int M, struct dpmatrix_s *mx); extern int P7ViterbiSize(int L, int M); extern int P7SmallViterbiSize(int L, int M); extern int P7WeeViterbiSize(int L, int M); extern float P7Forward(unsigned char *dsq, int L, struct plan7_s *hmm, struct dpmatrix_s **ret_mx); extern float P7Viterbi(unsigned char *dsq, int L, struct plan7_s *hmm, struct dpmatrix_s *mx, struct p7trace_s **ret_tr); extern void P7ViterbiTrace(struct plan7_s *hmm, unsigned char *dsq, int L, struct dpmatrix_s *mx, struct p7trace_s **ret_tr); extern float P7SmallViterbi(unsigned char *dsq, int L, struct plan7_s *hmm, struct dpmatrix_s *mx, struct p7trace_s **ret_tr, int& progress); extern float P7ParsingViterbi(unsigned char *dsq, int L, struct plan7_s *hmm, struct p7trace_s **ret_tr, int& progress); extern float P7WeeViterbi(unsigned char *dsq, int L, struct plan7_s *hmm, struct p7trace_s **ret_tr); extern float Plan7ESTViterbi(unsigned char *dsq, int L, struct plan7_s *hmm, struct dpmatrix_s **ret_mx); extern struct p7trace_s *P7ViterbiAlignAlignment(MSA *msa, struct plan7_s *hmm); extern struct p7trace_s *ShadowTrace(struct dpshadow_s *tb, struct plan7_s *hmm, int L); extern float PostprocessSignificantHit(struct tophit_s *ghit, struct tophit_s *dhit, struct p7trace_s *tr, struct plan7_s *hmm, unsigned char *dsq, int L, char *seqname, char *seqacc, char *seqdesc, int do_forward, float sc_override, int do_null2, struct threshold_s *thresh, int hmmpfam_mode); // histogram.cpp //accumulation of scores extern struct histogram_s *AllocHistogram(int min, int max, int lumpsize); extern void FreeHistogram(struct histogram_s *h); extern void UnfitHistogram(struct histogram_s *h); extern void AddToHistogram(struct histogram_s *h, float sc); extern void EVDBasicFit(struct histogram_s *h); extern int ExtremeValueFitHistogram(struct histogram_s *h, int censor, float high_hint); extern void ExtremeValueSetHistogram(struct histogram_s *h, float mu, float lambda, float low, float high, int ndegrees); extern int GaussianFitHistogram(struct histogram_s *h, float high_hint); extern void GaussianSetHistogram(struct histogram_s *h, float mean, float sd); extern double EVDDensity(float x, float mu, float lambda); extern double EVDDistribution(float x, float mu, float lambda); extern double ExtremeValueP (float x, float mu, float lambda); extern double ExtremeValueP2(float x, float mu, float lambda, int N); extern double ExtremeValueE (float x, float mu, float lambda, int N); extern float EVDrandom(float mu, float lambda); extern int EVDMaxLikelyFit(float *x, int *y, int n, float *ret_mu, float *ret_lambda); extern int EVDCensoredFit(float *x, int *y, int n, int z, float c, float *ret_mu, float *ret_lambda); extern void Lawless416(float *x, int *y, int n, float lambda, float *ret_f, float *ret_df); extern void Lawless422(float *x, int *y, int n, int z, float c, float lambda, float *ret_f, float *ret_df); // masks.cpp // Repetitive sequence masking. extern int XNU(unsigned char *dsq, int len); extern float TraceScoreCorrection(struct plan7_s *hmm, struct p7trace_s *tr, unsigned char *dsq); // mathsupport.cpp // Much of this code deals with Dirichlet prior mathematics. extern int Prob2Score(float p, float null); extern float Score2Prob(int sc, float null); extern float Scorify(int sc); extern double PValue(struct plan7_s *hmm, float sc); extern float LogSum(float p1, float p2); extern int ILogsum(int p1, int p2); extern void LogNorm(float *vec, int n); extern float Logp_cvec(float *cvec, int n, float *alpha); extern void SampleDirichlet(float *alpha, int n, float *p); extern float SampleGamma(float alpha); extern void SampleCountvector(float *p, int n, int c, float *cvec); extern float P_PvecGivenDirichlet(float *p, int n, float *alpha); #define sreLOG2(x) ((x) > 0 ? log(x) * 1.44269504 : -9999.) #define sreEXP2(x) (exp((x) * 0.69314718 )) #define SQR(x) ((x) * (x)) // modelmakers.cpp // Model construction algorithms extern void P7Handmodelmaker(MSA *msa, unsigned char **dsq, struct plan7_s **ret_hmm, struct p7trace_s ***ret_tr); extern void P7Fastmodelmaker(MSA *msa, unsigned char **dsq, float maxgap, struct plan7_s **ret_hmm, struct p7trace_s ***ret_tr); extern void P7Maxmodelmaker(MSA *msa, unsigned char **dsq, float maxgap, struct p7prior_s *prior, float *null, float null_p1, float mpri, struct plan7_s **ret_hmm, struct p7trace_s ***ret_tr); // msa.cpp extern MSA *MSAAlloc(int nseq, int alen); extern void MSAFree(MSA *msa); extern void MSAMingap(MSA *msa); extern void MSANogap(MSA *msa); extern void MSAShorterAlignment(MSA *msa, int *useme); extern void MSASmallerAlignment(MSA *msa, int *useme, MSA **ret_new); extern void MSASetSeqAccession(MSA *msa, int seqidx, char *acc); extern void MSASetSeqDescription(MSA *msa, int seqidx, char *desc); //plan7.cpp extern struct plan7_s *AllocPlan7(int M); extern struct plan7_s *AllocPlan7Shell(void); extern void AllocPlan7Body(struct plan7_s *hmm, int M); extern void FreePlan7(struct plan7_s *hmm); extern void ZeroPlan7(struct plan7_s *hmm); extern void Plan7SetName(struct plan7_s *hmm, const char *name); extern void Plan7SetAccession(struct plan7_s *hmm, char *acc); extern void Plan7SetDescription(struct plan7_s *hmm, char *desc); extern void Plan7SetCtime(struct plan7_s *hmm); extern void Plan7SetNullModel(struct plan7_s *hmm, float null[MAXABET], float p1); extern void P7Logoddsify(struct plan7_s *hmm, int viterbi_mode); extern void Plan7Renormalize(struct plan7_s *hmm); extern void Plan7RenormalizeExits(struct plan7_s *hmm); extern void Plan7NakedConfig(struct plan7_s *hmm); extern void Plan7GlobalConfig(struct plan7_s *hmm); extern void Plan7LSConfig(struct plan7_s *hmm); extern void Plan7SWConfig(struct plan7_s *hmm, float pentry, float pexit); extern void Plan7FSConfig(struct plan7_s *hmm, float pentry, float pexit); extern int DegenerateSymbolScore(float *p, float *null, int ambig); extern int SetAutocuts(struct threshold_s *thresh, struct plan7_s *hmm); extern const char *Statetype(char st); // priors.cpp // Dirichlet priors extern struct p7prior_s *P7AllocPrior(void); extern struct p7prior_s *P7LaplacePrior(void); extern struct p7prior_s *P7DefaultPrior(void); extern void P7FreePrior(struct p7prior_s *pri); extern void P7DefaultNullModel(float *null, float *ret_p1); extern void P7PriorifyHMM(struct plan7_s *hmm, struct p7prior_s *pri); extern void P7PriorifyTransitionVector(float *t, struct p7prior_s *prior, float tq[MAXDCHLET]); extern void P7PriorifyEmissionVector(float *vec, struct p7prior_s *pri, int num, float eq[MAXDCHLET], float e[MAXDCHLET][MAXABET], float *ret_mix); // sqerror.cpp extern void Die(const char *format, ...); extern void Warn(const char *format, ...); // sre_math.cpp extern int Linefit(float *x, float *y, int N, float *ret_a, float *ret_b, float *ret_r); extern void WeightedLinefit(float *x, float *y, float *var, int N, float *ret_m, float *ret_b); extern double Gammln(double xx); extern float **FMX2Alloc(int rows, int cols); extern void FMX2Free(float **mx); extern double **DMX2Alloc(int rows, int cols); extern void DMX2Free(double **mx); extern void FMX2Multiply(float **A, float **B, float **C, int m, int p, int n); extern double IncompleteGamma(double a, double x); // sre_random.cpp extern double sre_random(void); extern void sre_srandom(int seed); extern double sre_random_positive(void); extern double ExponentialRandom(void); extern double Gaussrandom(double mean, double stddev); extern int DChoose(double *p, int N); extern int FChoose(float *p, int N); #define CHOOSE(a) ((int) (sre_random() * (a))) //sre_string.cpp #ifdef _WINDOWS #define snprintf sprintf_s #define vsnprintf vsprintf_s #define strtok_r strtok_s #define ctime_r(time, dst) ctime_s(dst, 26, time) #endif extern size_t sre_strlcpy(char *dst, const char *src, size_t siz); extern size_t sre_strlcat(char *dst, const char *src, size_t siz); extern char *Strdup(const char *s); extern void StringChop(char *s); extern int Strinsert(char *s1, char c, int pos); extern int Strdelete(char *s1, int pos); extern void s2lower(char *s); extern void s2upper(char *s); extern void *sre_malloc(const char *file, int line, size_t size); extern void *sre_realloc(const char *file, int line, void *p, size_t size); extern void Free2DArray(void **p, int dim1); extern void Free3DArray(void ***p, int dim1, int dim2); extern char *RandomSequence(char *alphabet, float *p, int n, int len); extern int sre_strcat(char **dest, int ldest, char *src, int lsrc); extern char *sre_strtok(char **s, char *delim, int *len); extern char *sre_strdup(const char *s, int n); extern char *sre_strncat(char *s1, char *s2, int n); extern int IsBlankline(char *s); extern int sre_tolower(int c); extern int sre_toupper(int c); //tophits.cpp extern struct tophit_s *AllocTophits(int lumpsize); extern void GrowTophits(struct tophit_s *h); extern void FreeTophits(struct tophit_s *h); extern struct fancyali_s *AllocFancyAli(void); extern void FreeFancyAli(struct fancyali_s *ali); extern void RegisterHit(struct tophit_s *h, double sortkey, double pvalue, float score, double motherp, float mothersc, char *name, char *acc, char *desc, int sqfrom, int sqto, int sqlen, int hmmfrom, int hmmto, int hmmlen, int domidx, int ndom, struct fancyali_s *ali); extern void GetRankedHit(struct tophit_s *h, int rank, double *r_pvalue, float *r_score, double *r_motherp, float *r_mothersc, char **r_name, char **r_acc, char **r_desc, int *r_sqfrom, int *r_sqto, int *r_sqlen, int *r_hmmfrom, int *r_hmmto, int *r_hmmlen, int *r_domidx, int *r_ndom, struct fancyali_s **r_ali); extern int TophitsMaxName(struct tophit_s *h); extern void FullSortTophits(struct tophit_s *h); // trace.cpp // Support for traceback (state path) structure extern void P7AllocTrace(int tlen, struct p7trace_s **ret_tr); extern void P7ReallocTrace(struct p7trace_s *tr, int tlen); extern void P7FreeTrace(struct p7trace_s *tr); extern void TraceSet(struct p7trace_s *tr, int tpos, char type, int idx, int pos); extern struct p7trace_s **MergeTraceArrays(struct p7trace_s **t1, int n1, struct p7trace_s **t2, int n2); extern void P7ReverseTrace(struct p7trace_s *tr); extern void P7TraceCount(struct plan7_s *hmm, unsigned char *dsq, float wt, struct p7trace_s *tr); extern float P7TraceScore(struct plan7_s *hmm, unsigned char *dsq, struct p7trace_s *tr); extern MSA *P7Traces2Alignment(unsigned char **dsq, SQINFO *sqinfo, float *wgt, int nseq, int M, struct p7trace_s **tr, int matchonly); extern int TransitionScoreLookup(struct plan7_s *hmm, char st1, int k1, char st2, int k2); extern struct fancyali_s *CreateFancyAli(struct p7trace_s *tr, struct plan7_s *hmm, unsigned char *dsq, char *name); extern void TraceDecompose(struct p7trace_s *otr, struct p7trace_s ***ret_tr, int *ret_ntr); extern int TraceDomainNumber(struct p7trace_s *tr); extern void TraceSimpleBounds(struct p7trace_s *tr, int *ret_i1, int *ret_i2, int *ret_k1, int *ret_k2); extern struct p7trace_s *MasterTraceFromMap(int *map, int M, int alen); extern void ImposeMasterTrace(char **aseq, int nseq, struct p7trace_s *mtr, struct p7trace_s ***ret_tr); //vectorops.cpp extern void DSet(double *vec, int n, double value); extern void FSet(float *vec, int n, float value); extern void DScale(double *vec, int n, double scale); extern void FScale(float *vec, int n, float scale); extern double DSum(double *vec, int n); extern float FSum(float *vec, int n); extern void DAdd(double *vec1, double *vec2, int n); extern void FAdd(float *vec1, float *vec2, int n); extern void DCopy(double *vec1, double *vec2, int n); extern void FCopy(float *vec1, float *vec2, int n); extern double DDot(double *vec1, double *vec2, int n); extern float FDot(float *vec1, float *vec2, int n); extern double DMax(double *vec, int n); extern float FMax(float *vec, int n); extern double DMin(double *vec, int n); extern float FMin(float *vec, int n); extern int DArgMax(double *vec, int n); extern int FArgMax(float *vec, int n); extern int DArgMin(double *vec, int n); extern int FArgMin(float *vec, int n); extern void DNorm(double *vec, int n); extern void FNorm(float *vec, int n); extern void DLog(double *vec, int n); extern void FLog(float *vec, int n); extern void DExp(double *vec, int n); extern void FExp(float *vec, int n); extern double DLogSum(double *vec, int n); extern float FLogSum(float *vec, int n); //weight.cpp extern void GSCWeights(char **aseq, int nseq, int alen, float *wgt); extern void VoronoiWeights(char **aseq, int nseq, int alen, float *wgt); extern void BlosumWeights(char **aseq, int nseq, int alen, float blosumlevel, float *wgt); extern void PositionBasedWeights(char **aseq, int nseq, int alen, float *wgt); extern void FilterAlignment(MSA *msa, float cutoff, MSA **ret_new); extern void SampleAlignment(MSA *msa, int sample, MSA **ret_new); extern void SingleLinkCluster(char **aseq, int nseq, int alen, float maxid, int **ret_c, int *ret_nc); //TaskLocalStorage.cpp extern struct HMMERTaskLocalData *getHMMERTaskLocalData(); // misc. defines #ifndef DEBUGLEVEL #define DEBUGLEVEL 0 #endif #if (DEBUGLEVEL >= 1) #define SQD_DPRINTF1(x) printf x #define SQD_DASSERT1(x) assert x #else #define SQD_DPRINTF1(x) #define SQD_DASSERT1(x) #endif #if (DEBUGLEVEL >= 2) #define SQD_DPRINTF2(x) printf x #define SQD_DASSERT2(x) assert x #else #define SQD_DPRINTF2(x) #define SQD_DASSERT2(x) #endif #if (DEBUGLEVEL >= 3) #define SQD_DPRINTF3(x) printf x #define SQD_DASSERT3(x) assert x #else #define SQD_DPRINTF3(x) #define SQD_DASSERT3(x) #endif #define MallocOrDie(x) sre_malloc(__FILE__, __LINE__, (x)) #define ReallocOrDie(x,y) sre_realloc(__FILE__, __LINE__, (x), (y)) #endif /*FUNCSH_INCLUDED*/ ugene-1.9.8/src/plugins_3rdparty/hmm2/src/hmmer2/aligneval.cpp0000644000175000017500000004361311651544326022722 0ustar ilyailya/***************************************************************** * HMMER - Biological sequence analysis with profile HMMs * Copyright (C) 1992-2003 Washington University School of Medicine * All Rights Reserved * * This source code is distributed under the terms of the * GNU General Public License. See the files COPYING and LICENSE * for details. *****************************************************************/ /* aligneval.c * * Comparison of multiple alignments. Three functions are * provided, using subtly different scoring schemes: * CompareMultAlignments() - basic scoring scheme * CompareRefMultAlignments() - only certain "canonical" columns * are scored * * The similarity measure is a fractional alignment identity averaged * over all sequence pairs. The score for all pairs is: * (identically aligned symbols) / (total aligned columns in * known alignment) * * A column c is identically aligned for sequences i, j if: * 1) both i,j have a symbol aligned in column c, and the * same pair of symbols is aligned somewhere in the test * alignment * 2) S[i][c] is aligned to a gap in sequence j, and that symbol * is aligned to a gap in the test alignment * 3) converse of 2) * * * The algorithm is as follows: * 1) For each known/test aligned pair of sequences (k1,k2 and t1,t2) * construct a list for each sequence, in which for every * counted symbol we record the raw index of the symbol in * the other sequence that it aligns to, or -1 if it aligns * to a gap or uncounted symbol. * * 2) Compare the list for k1 to the list for t1 and count an identity * for each correct alignment. * * 3) Repeat 2) for comparing k2 to t2. Note that this means correct sym/sym * alignments count for 2; correct sym/gap alignments count for 1. * * 4) The score is (identities from 2 + identities from 3) / * (totals from 2 + totals from 3). * * Written originally for koala's ss2 pairwise alignment package. * * Sean Eddy, Sun Nov 1 12:45:11 1992 * SRE, Thu Jul 29 16:47:18 1993: major revision: all functions replaced by new algorithm * CVS $Id: aligneval.c,v 1.9 2003/04/14 16:00:16 eddy Exp $ */ #include "funcs.h" static int make_alilist(char *s1, char *s2, int **ret_s1_list, int *ret_listlen); static int make_ref_alilist(int *refcoords, char *k1, char *k2, char *s1, char *s2, int **ret_s1_list, int *ret_listlen); static int compare_lists(int *k1, int *k2, int *t1, int *t2, int len1, int len2, float *ret_sc); /* Function: ComparePairAlignments * * Purpose: Calculate and return a number representing how well two different alignments * of a pair of sequences compare. The number is, roughly speaking, * the fraction of columns which are identically aligned. * * For all columns c in which either known1[c] or known2[c] * is a non-gap, count an identity if those same symbols are * aligned somewhere in calc1/calc2. The score is identities/total * columns examined. (i.e. fully gapped columns don't count) * * more explicitly, identities come from: * both known and test aligned pairs have the same symbol in the first sequence aligned to * a gap in the second sequence; * both known and test aligned pairs have the same symbol in the second sequence * aligned to a gap in the first sequence; * the known alignment has symbols aligned at this column, and the test * alignment aligns the same two symbols. * * Args: known1, known2: trusted alignment of two sequences * calc1, calc2: test alignment of two sequences * * Return: Returns -1.0 on internal failure. */ float ComparePairAlignments(char *known1, char *known2, char *calc1, char *calc2) { int *klist1; int *klist2; int *tlist1; int *tlist2; int len1, len2; float score; if (! make_alilist(calc1, calc2, &tlist1, &len1)) return -1.0; if (! make_alilist(calc2, calc1, &tlist2, &len2)) return -1.0; if (! make_alilist(known1, known2, &klist1, &len1)) return -1.0; if (! make_alilist(known2, known1, &klist2, &len2)) return -1.0; if (! compare_lists(klist1, klist2, tlist1, tlist2, len1, len2, &score)) return -1.0; free(klist1); free(klist2); free(tlist1); free(tlist2); return score; } /* Function: CompareRefPairAlignments() * * Same as above, but the only columns that count are the ones * with indices in *refcoord. *refcoord and the known1, known2 * pair must be in sync with each other (come from the same * multiple sequence alignment) * * Args: ref - 0..alen-1 array of 1 or 0 * known1,known2 - trusted alignment * calc1, calc2 - test alignment * * Return: the fractional alignment identity on success, -1.0 on failure. */ float CompareRefPairAlignments(int *ref, char *known1, char *known2, char *calc1, char *calc2) { int *klist1; int *klist2; int *tlist1; int *tlist2; int len1, len2; float score; if (! make_ref_alilist(ref, known1, known2, calc1, calc2, &tlist1, &len1)) return -1.0; if (! make_ref_alilist(ref, known2, known1, calc2, calc1, &tlist2, &len2)) return -1.0; if (! make_ref_alilist(ref, known1, known2, known1, known2, &klist1, &len1)) return -1.0; if (! make_ref_alilist(ref, known2, known1, known2, known1, &klist2, &len2)) return -1.0; if (! compare_lists(klist1, klist2, tlist1, tlist2, len1, len2, &score)) return -1.0; free(klist1); free(klist2); free(tlist1); free(tlist2); return score; } /* Function: make_alilist() * * Purpose: Construct a list (array) mapping the raw symbols of s1 * onto the indexes of the aligned symbols in s2 (or -1 * for gaps in s2). The list (s1_list) will be of the * length of s1's raw sequence. * * Args: s1 - sequence to construct the list for * s2 - sequence s1 is aligned to * ret_s1_list - RETURN: the constructed list (caller must free) * ret_listlen - RETURN: length of the list * * Returns: 1 on success, 0 on failure */ static int make_alilist(char *s1, char *s2, int **ret_s1_list, int *ret_listlen) { int *s1_list; int col; /* column position in alignment */ int r1, r2; /* raw symbol index at current col in s1, s2 */ /* Malloc for s1_list. It can't be longer than s1 itself; we just malloc * for that (and waste a wee bit of space) */ s1_list = (int *) MallocOrDie (sizeof(int) * strlen(s1)); r1 = r2 = 0; for (col = 0; s1[col] != '\0'; col++) { /* symbol in s1? Record what it's aligned to, and bump * the r1 counter. */ if (! isgap(s1[col])) { s1_list[r1] = isgap(s2[col]) ? -1 : r2; r1++; } /* symbol in s2? bump the r2 counter */ if (! isgap(s2[col])) r2++; } *ret_listlen = r1; *ret_s1_list = s1_list; return 1; } /* Function: make_ref_alilist() * * Purpose: Construct a list (array) mapping the raw symbols of s1 * which are under canonical columns of the ref alignment * onto the indexes of the aligned symbols in s2 (or -1 * for gaps in s2 or noncanonical symbols in s2). * * Args: ref: - array of indices of canonical coords (1 canonical, 0 non) * k1 - s1's known alignment (w/ respect to refcoords) * k2 - s2's known alignment (w/ respect to refcoords) * s1 - sequence to construct the list for * s2 - sequence s1 is aligned to * ret_s1_list - RETURN: the constructed list (caller must free) * ret_listlen - RETURN: length of the list * * Returns: 1 on success, 0 on failure */ /*ARGSUSED*/ static int make_ref_alilist(int *ref, char *k1, char *k2, char *s1, char *s2, int **ret_s1_list, int *ret_listlen) { int *s1_list; int col; /* column position in alignment */ int r1, r2; /* raw symbol index at current col in s1, s2 */ int *canons1; /* flag array, 1 if position i in s1 raw seq is canonical */ int lpos; /* position in list */ /* Allocations. No arrays can exceed the length of their * appropriate parent (s1 or s2) */ s1_list = (int *) MallocOrDie (sizeof(int) * strlen(s1)); canons1 = (int *) MallocOrDie (sizeof(int) * strlen(s1)); /* First we use refcoords and k1,k2 to construct an array of 1's * and 0's, telling us whether s1's raw symbol number i is countable. * It's countable simply if it's under a canonical column. */ r1 = 0; for (col = 0; k1[col] != '\0'; col++) { if (! isgap(k1[col])) { canons1[r1] = ref[col] ? 1 : 0; r1++; } } /* Now we can construct the list. We don't count pairs if the sym in s1 * is non-canonical. * We have to keep separate track of our position in the list (lpos) * from our positions in the raw sequences (r1,r2) */ r1 = r2 = lpos = 0; for (col = 0; s1[col] != '\0'; col++) { if (! isgap(s1[col]) && canons1[r1]) { s1_list[lpos] = isgap(s2[col]) ? -1 : r2; lpos++; } if (! isgap(s1[col])) r1++; if (! isgap(s2[col])) r2++; } free(canons1); *ret_listlen = lpos; *ret_s1_list = s1_list; return 1; } /* Function: compare_lists() * * Purpose: Given four alignment lists (k1,k2, t1,t2), calculate the * alignment score. * * Args: k1 - list of k1's alignment to k2 * k2 - list of k2's alignment to k1 * t1 - list of t1's alignment to t2 * t2 - list of t2's alignment to t2 * len1 - length of k1, t1 lists (same by definition) * len2 - length of k2, t2 lists (same by definition) * ret_sc - RETURN: identity score of alignment * * Return: 1 on success, 0 on failure. */ static int compare_lists(int *k1, int *k2, int *t1, int *t2, int len1, int len2, float *ret_sc) { float id; float tot; int i; id = tot = 0.0; for (i = 0; i < len1; i++) { tot += 1.0; if (t1[i] == k1[i]) id += 1.0; } for ( i = 0; i < len2; i++) { tot += 1.0; if (k2[i] == t2[i]) id += 1.0; } *ret_sc = id / tot; return 1; } /* Function: CompareMultAlignments * * Purpose: Invokes pairwise alignment comparison for every possible pair, * and returns the average score over all N(N-1) of them or -1.0 * on an internal failure. * * Can be slow for large N, since it's quadratic. * * Args: kseqs - trusted multiple alignment * tseqs - test multiple alignment * N - number of sequences * * Return: average identity score, or -1.0 on failure. */ float CompareMultAlignments(char **kseqs, char **tseqs, int N) { int i, j; /* counters for sequences */ float score; float tot_score = 0.0; /* do all pairwise comparisons */ for (i = 0; i < N; i++) for (j = i+1; j < N; j++) { score = ComparePairAlignments(kseqs[i], kseqs[j], tseqs[i], tseqs[j]); if (score < 0.0) return -1.0; tot_score += score; } return ((tot_score * 2.0) / ((float) N * ((float) N - 1.0))); } /* Function: CompareRefMultAlignments() * * Purpose: Same as above, except an array of reference coords for * the canonical positions of the known alignment is also * provided. * * Args: ref : 0..alen-1 array of 1/0 flags, 1 if canon * kseqs : trusted alignment * tseqs : test alignment * N : number of sequences * * Return: average identity score, or -1.0 on failure */ float CompareRefMultAlignments(int *ref, char **kseqs, char **tseqs, int N) { int i, j; /* counters for sequences */ float score; float tot_score = 0.0; /* do all pairwise comparisons */ for (i = 0; i < N; i++) for (j = i+1; j < N; j++) { score = CompareRefPairAlignments(ref, kseqs[i], kseqs[j], tseqs[i], tseqs[j]); if (score < 0.0) return -1.0; tot_score += score; } return ((tot_score * 2.0)/ ((float) N * ((float) N - 1.0))); } /* Function: PairwiseIdentity() * * Purpose: Calculate the pairwise fractional identity between * two aligned sequences s1 and s2. This is simply * (idents / MIN(len1, len2)). * * Note how many ways there are to calculate pairwise identity, * because of the variety of choices for the denominator: * idents/(idents+mismat) has the disadvantage that artifactual * gappy alignments would have high "identities". * idents/(AVG|MAX)(len1,len2) both have the disadvantage that * alignments of fragments to longer sequences would have * artifactually low "identities". * * Case sensitive; also, watch out in nucleic acid alignments; * U/T RNA/DNA alignments will be counted as mismatches! */ float PairwiseIdentity(char *s1, char *s2) { int idents; /* total identical positions */ int len1, len2; /* lengths of seqs */ int x; /* position in aligned seqs */ idents = len1 = len2 = 0; for (x = 0; s1[x] != '\0' && s2[x] != '\0'; x++) { if (!isgap(s1[x])) { len1++; if (s1[x] == s2[x]) idents++; } if (!isgap(s2[x])) len2++; } if (len2 < len1) len1 = len2; return (len1 == 0 ? 0.0 : (float) idents / (float) len1); } /* Function: AlignmentIdentityBySampling() * Date: SRE, Mon Oct 19 14:29:01 1998 [St. Louis] * * Purpose: Estimate and return the average pairwise * fractional identity of an alignment, * using sampling. * * For use when there's so many sequences that * an all vs. all rigorous calculation will * take too long. * * Case sensitive! * * Args: aseq - aligned sequences * L - length of alignment * N - number of seqs in alignment * nsample - number of samples * * Returns: average fractional identity, 0..1. */ float AlignmentIdentityBySampling(char **aseq, int L, int N, int nsample) { int x, i, j; /* counters */ float sum; if (N < 2) return 1.0; sum = 0.; for (x = 0; x < nsample; x++) { i = CHOOSE(N); do { j = CHOOSE(N); } while (j == i); /* make sure j != i */ sum += PairwiseIdentity(aseq[i], aseq[j]); } return sum / (float) nsample; } /* Function: MajorityRuleConsensus() * Date: SRE, Tue Mar 7 15:30:30 2000 [St. Louis] * * Purpose: Given a set of aligned sequences, produce a * majority rule consensus sequence. If >50% nonalphabetic * (usually meaning gaps) in the column, ignore the column. * * Args: aseq - aligned sequences, [0..nseq-1][0..alen-1] * nseq - number of sequences * alen - length of alignment * * Returns: ptr to allocated consensus sequence. * Caller is responsible for free'ing this. */ char * MajorityRuleConsensus(char **aseq, int nseq, int alen) { char *cs; /* RETURN: consensus sequence */ int count[27]; /* counts for a..z and gaps in a column */ int idx,apos; /* counters for seq, column */ int spos; /* position in cs */ int x; /* counter for characters */ int sym; int max, bestx; cs = (char*)MallocOrDie(sizeof(char) * (alen+1)); for (spos=0,apos=0; apos < alen; apos++) { for (x = 0; x < 27; x++) count[x] = 0; for (idx = 0; idx < nseq; idx++) { if (isalpha((int) aseq[idx][apos])) { sym = toupper((int) aseq[idx][apos]); count[sym-'A']++; } else { count[26]++; } } if ((float) count[26] / (float) nseq <= 0.5) { max = bestx = -1; for (x = 0; x < 26; x++) if (count[x] > max) { max = count[x]; bestx = x; } cs[spos++] = (char) ('A' + bestx); } } cs[spos] = '\0'; return cs; } /* Function: DealignedLength() * * Purpose: Count the number of non-gap symbols in seq. * (i.e. find the length of the unaligned sequence) * * Args: aseq - aligned sequence to count symbols in, \0 terminated * * Return: raw length of seq. */ int DealignedLength(char *aseq) { int rlen; for (rlen = 0; *aseq; aseq++) if (! isgap(*aseq)) rlen++; return rlen; } /* Function: MakeAlignedString() * * Purpose: Given a raw string of some type (secondary structure, say), * align it to a given aseq by putting gaps wherever the * aseq has gaps. * * Args: aseq: template for alignment * alen: length of aseq * ss: raw string to align to aseq * ret_s: RETURN: aligned ss * * Return: 1 on success, 0 on failure (and squid_errno is set.) * ret_ss is MallocOrDie'ed here and must be free'd by caller. */ int MakeAlignedString(char *aseq, int alen, char *ss, char **ret_s) { char *newS; unsigned apos, rpos; newS = (char *) MallocOrDie ((alen+1) * sizeof(char)); for (apos = rpos = 0; apos < alen; apos++) if (! isgap(aseq[apos])) { newS[apos] = ss[rpos]; rpos++; } else newS[apos] = '.'; newS[apos] = '\0'; if (rpos != strlen(ss)) { free(newS); return 0; } *ret_s = newS; return 1; } ugene-1.9.8/src/plugins_3rdparty/hmm2/src/hmmer2/weight.cpp0000644000175000017500000006171411651544326022251 0ustar ilyailya/***************************************************************** * HMMER - Biological sequence analysis with profile HMMs * Copyright (C) 1992-2003 Washington University School of Medicine * All Rights Reserved * * This source code is distributed under the terms of the * GNU General Public License. See the files COPYING and LICENSE * for details. *****************************************************************/ /* weight.c * SRE, Thu Mar 3 07:56:01 1994 * * Calculate weights for sequences in an alignment. * RCS $Id: weight.c,v 1.11 2003/04/14 16:00:16 eddy Exp $ */ #include "funcs.h" static void upweight(struct phylo_s *tree, int nseq, float *lwt, float *rwt, int node); static void downweight(struct phylo_s *tree, int nseq, float *lwt, float *rwt, float *fwt, int node); static float simple_distance(char *s1, char *s2); static int simple_diffmx(char **aseqs,int num, float ***ret_dmx); /* Function: GSCWeights() * * Purpose: Use Erik's tree-based algorithm to set weights for * sequences in an alignment. upweight() and downweight() * are derived from Graeme Mitchison's code. * * Args: aseq - array of (0..nseq-1) aligned sequences * nseq - number of seqs in alignment * alen - length of alignment * wgt - allocated [0..nseq-1] array of weights to be returned * * Return: (void) * wgt is filled in. */ void GSCWeights(char **aseq, int nseq, int alen, float *wgt) { float **dmx; /* distance (difference) matrix */ struct phylo_s *tree; float *lwt, *rwt; /* weight on left, right of this tree node */ float *fwt; /* final weight assigned to this node */ int i; /* Sanity check first */ if (nseq == 1) { wgt[0] = 1.0; return; } /* I use a simple fractional difference matrix derived by * pairwise identity. Perhaps I should include a Poisson * distance correction. */ MakeDiffMx(aseq, nseq, &dmx); if (! Cluster(dmx, nseq, CLUSTER_MIN, &tree)) Die("Cluster() failed"); /* Allocations */ lwt = (float*)MallocOrDie (sizeof(float) * (2 * nseq - 1)); rwt = (float*)MallocOrDie (sizeof(float) * (2 * nseq - 1)); fwt = (float*)MallocOrDie (sizeof(float) * (2 * nseq - 1)); /* lwt and rwt are the total branch weight to the left and * right of a node or sequence. They are 0..2N-2. 0..N-1 are * the sequences; these have weight 0. N..2N-2 are the actual * tree nodes. */ for (i = 0; i < nseq; i++) lwt[i] = rwt[i] = 0.0; /* recursively calculate rwt, lwt, starting at node nseq (the root) */ upweight(tree, nseq, lwt, rwt, nseq); /* recursively distribute weight across the tree */ fwt[nseq] = nseq; downweight(tree, nseq, lwt, rwt, fwt, nseq); /* collect the weights */ for (i = 0; i < nseq; i++) wgt[i] = fwt[i]; FMX2Free(dmx); FreePhylo(tree, nseq); free(lwt); free(rwt); free(fwt); } static void upweight(struct phylo_s *tree, int nseq, float *lwt, float *rwt, int node) { int ld,rd; ld = tree[node-nseq].left; if (ld >= nseq) upweight(tree, nseq, lwt, rwt, ld); rd = tree[node-nseq].right; if (rd >= nseq) upweight(tree, nseq, lwt, rwt, rd); lwt[node] = lwt[ld] + rwt[ld] + tree[node-nseq].lblen; rwt[node] = lwt[rd] + rwt[rd] + tree[node-nseq].rblen; } static void downweight(struct phylo_s *tree, int nseq, float *lwt, float *rwt, float *fwt, int node) { int ld,rd; float lnum, rnum; ld = tree[node-nseq].left; rd = tree[node-nseq].right; if (lwt[node] + rwt[node] > 0.0) { fwt[ld] = fwt[node] * (lwt[node] / (lwt[node] + rwt[node])); fwt[rd] = fwt[node] * (rwt[node] / (lwt[node] + rwt[node])); } else { lnum = (ld >= nseq) ? tree[ld-nseq].incnum : 1.0; rnum = (rd >= nseq) ? tree[rd-nseq].incnum : 1.0; fwt[ld] = fwt[node] * lnum / (lnum + rnum); fwt[rd] = fwt[node] * rnum / (lnum + rnum); } if (ld >= nseq) downweight(tree, nseq, lwt, rwt, fwt, ld); if (rd >= nseq) downweight(tree, nseq, lwt, rwt, fwt, rd); } /* Function: VoronoiWeights() * * Purpose: Calculate weights using the scheme of Sibbald & * Argos (JMB 216:813-818 1990). The scheme is * slightly modified because the original algorithm * actually doesn't work on gapped alignments. * The sequences are assumed to be protein. * * Args: aseq - array of (0..nseq-1) aligned sequences * nseq - number of sequences * alen - length of alignment * wgt - allocated [0..nseq-1] array of weights to be returned * * Return: void * wgt is filled in. */ void VoronoiWeights(char **aseq, int nseq, int alen, float *wgt) { float **dmx; /* distance (difference) matrix */ float *halfmin; /* 1/2 minimum distance to other seqs */ char **psym; /* symbols seen in each column */ int *nsym; /* # syms seen in each column */ int symseen[27]; /* flags for observed syms */ char *randseq; /* randomly generated sequence */ int acol; /* pos in aligned columns */ int idx; /* index in sequences */ int symidx; /* 0..25 index for symbol */ int i; /* generic counter */ float min; /* minimum distance */ float dist; /* distance between random and real */ float challenge, champion; /* for resolving ties */ int itscale; /* how many iterations per seq */ int iteration; int best; /* index of nearest real sequence */ /* Sanity check first */ if (nseq == 1) { wgt[0] = 1.0; return; } itscale = 50; /* Precalculate 1/2 minimum distance to other * sequences for each sequence */ if (! simple_diffmx(aseq, nseq, &dmx)) Die("simple_diffmx() failed"); halfmin = (float*)MallocOrDie (sizeof(float) * nseq); for (idx = 0; idx < nseq; idx++) { for (min = 1.0, i = 0; i < nseq; i++) { if (i == idx) continue; if (dmx[idx][i] < min) min = dmx[idx][i]; } halfmin[idx] = min / 2.0; } Free2DArray((void **) dmx, nseq); /* Set up the random sequence generating model. */ psym = (char**)MallocOrDie (alen * sizeof(char *)); nsym = (int*)MallocOrDie (alen * sizeof(int)); for (acol = 0; acol < alen; acol++) psym[acol] = (char*)MallocOrDie (27 * sizeof(char)); /* #ifdef ORIGINAL_SIBBALD_ALGORITHM_IS_BROKEN */ for (acol = 0; acol < alen; acol++) { memset(symseen, 0, sizeof(int) * 27); for (idx = 0; idx < nseq; idx++) if (! isgap(aseq[idx][acol])) { if (isupper((int) aseq[idx][acol])) symidx = aseq[idx][acol] - 'A'; else symidx = aseq[idx][acol] - 'a'; if (symidx >= 0 && symidx < 26) symseen[symidx] = 1; } else symseen[26] = 1; /* a gap */ for (nsym[acol] = 0, i = 0; i < 26; i++) if (symseen[i]) { psym[acol][nsym[acol]] = 'A'+i; nsym[acol]++; } if (symseen[26]) { psym[acol][nsym[acol]] = ' '; nsym[acol]++; } } /* #endif ORIGINAL_SIBBALD_ALGORITHM_IS_BROKEN */ /* Note: the original Sibbald&Argos algorithm calls for * bounding the sampled space using a template-like random * sequence generator. However, this leads to one minor * and one major problem. The minor problem is that * exceptional amino acids in a column can have a * significant effect by altering the amount of sampled * sequence space; the larger the data set, the worse * this problem becomes. The major problem is that * there is no reasonable way to deal with gaps. * Gapped sequences simply inhabit a different dimensionality * and it's pretty painful to imagine calculating Voronoi * volumes when the N in your N-space is varying. * Note that all the examples shown by Sibbald and Argos * are *ungapped* examples. * * The best way I've found to circumvent this problem is * just not to bound the sampled space; count gaps as * symbols and generate completely random sequences. */ #ifdef ALL_SEQUENCE_SPACE for (acol = 0; acol < alen; acol++) { strcpy(psym[acol], "ACDEFGHIKLMNPQRSTVWY "); nsym[acol] = 21; } #endif /* Sibbald and Argos algorithm: * 1) assign all seqs weight 0. * 2) generate a "random" sequence * 3) calculate distance to every other sequence * (if we get a distance < 1/2 minimum distance * to other real seqs, we can stop) * 4) if unique closest sequence, increment its weight 1. * if multiple closest seq, choose one randomly * 5) repeat 2-4 for lots of iterations * 6) normalize all weights to sum to nseq. */ randseq = (char*)MallocOrDie ((alen+1) * sizeof(char)); best = 42.; /* solely to silence GCC uninit warnings. */ FSet(wgt, nseq, 0.0); for (iteration = 0; iteration < itscale * nseq; iteration++) { for (acol = 0; acol < alen; acol++) randseq[acol] = (nsym[acol] == 0) ? ' ' : psym[acol][CHOOSE(nsym[acol])]; randseq[acol] = '\0'; champion = sre_random(); for (min = 1.0, idx = 0; idx < nseq; idx++) { dist = simple_distance(aseq[idx], randseq); if (dist < halfmin[idx]) { best = idx; break; } if (dist < min) { champion = sre_random(); best = idx; min = dist; } else if (dist == min) { challenge = sre_random(); if (challenge > champion) { champion = challenge; best = idx; min = dist; } } } wgt[best] += 1.0; } for (idx = 0; idx < nseq; idx++) wgt[idx] = wgt[idx] / (float) itscale; free(randseq); free(nsym); free(halfmin); Free2DArray((void **) psym, alen); } /* Function: simple_distance() * * Purpose: For two identical-length null-terminated strings, return * the fractional difference between them. (0..1) * (Gaps don't count toward anything.) */ static float simple_distance(char *s1, char *s2) { int diff = 0; int valid = 0; for (; *s1 != '\0'; s1++, s2++) { if (isgap(*s1) || isgap(*s2)) continue; if (*s1 != *s2) diff++; valid++; } return (valid > 0 ? ((float) diff / (float) valid) : 0.0); } /* Function: simple_diffmx() * * Purpose: Given a set of flushed, aligned sequences, construct * an NxN fractional difference matrix using the * simple_distance rule. * * Args: aseqs - flushed, aligned sequences * num - number of aseqs * ret_dmx - RETURN: difference matrix (caller must free) * * Return: 1 on success, 0 on failure. */ static int simple_diffmx(char **aseqs, int num, float ***ret_dmx) { float **dmx; /* RETURN: distance matrix */ int i,j; /* counters over sequences */ /* Allocate */ if ((dmx = (float **) malloc (sizeof(float *) * num)) == NULL) Die("malloc failed"); for (i = 0; i < num; i++) if ((dmx[i] = (float *) malloc (sizeof(float) * num)) == NULL) Die("malloc failed"); /* Calculate distances, symmetric matrix */ for (i = 0; i < num; i++) for (j = i; j < num; j++) dmx[i][j] = dmx[j][i] = simple_distance(aseqs[i], aseqs[j]); /* Return */ *ret_dmx = dmx; return 1; } /* Function: BlosumWeights() * Date: SRE, Fri Jul 16 17:33:59 1999 (St. Louis) * * Purpose: Assign weights to a set of aligned sequences * using the BLOSUM rule: * - do single linkage clustering at some pairwise identity * - in each cluster, give each sequence 1/clustsize * total weight. * * The clusters have no pairwise link >= maxid. * * O(N) in memory. Probably ~O(NlogN) in time; O(N^2) * in worst case, which is no links between sequences * (e.g., values of maxid near 1.0). * * Args: aseqs - alignment * nseq - number of seqs in alignment * alen - # of columns in alignment * maxid - fractional identity (e.g. 0.62 for BLOSUM62) * wgt - [0..nseq-1] array of weights to be returned */ void BlosumWeights(char **aseqs, int nseq, int alen, float maxid, float *wgt) { int *c, nc; int *nmem; /* number of seqs in each cluster */ int i; /* loop counter */ SingleLinkCluster(aseqs, nseq, alen, maxid, &c, &nc); FSet(wgt, nseq, 1.0); nmem = (int*)MallocOrDie(sizeof(int) * nc); for (i = 0; i < nc; i++) nmem[i] = 0; for (i = 0; i < nseq; i++) nmem[c[i]]++; for (i = 0; i < nseq; i++) wgt[i] = 1. / (float) nmem[c[i]]; free(nmem); free(c); return; } /* Function: PositionBasedWeights() * Date: SRE, Fri Jul 16 17:47:22 1999 [St. Louis] * * Purpose: Implementation of Henikoff and Henikoff position-based * weights (JMB 243:574-578, 1994) [Henikoff94b]. * * A significant advantage of this approach that Steve and Jorja * don't point out is that it is O(N) in memory, unlike * many other approaches like GSC weights or Voronoi. * * A potential disadvantage that they don't point out * is that in the theoretical limit of infinite sequences * in the alignment, weights go flat: eventually every * column has at least one representative of each of 20 aa (or 4 nt) * in it. * * They also don't give a rule for how to handle gaps. * The rule used here seems the obvious and sensible one * (ignore them). This means that longer sequences * initially get more weight; hence a "double * normalization" in which the weights are first divided * by sequence length (to compensate for that effect), * then normalized to sum to nseq. * * Limitations: * Implemented in a way that's alphabet-independent: * it uses the 26 upper case letters as "residues". * Any alphabetic character in aseq is interpreted as * a unique "residue" (case insensitively; lower case * mapped to upper case). All other characters are * interpreted as gaps. * * This way, we don't have to pass around any alphabet * type info (DNA vs. RNA vs. protein) and don't have * to deal with remapping IUPAC degenerate codes * probabilistically. However, on the down side, * a sequence with a lot of degenerate IUPAC characters * will get an artifactually high PB weight. * * Args: aseq - sequence alignment to weight * nseq - number of sequences in alignment * alen - length of alignment * wgt - RETURN: weights filled in (pre-allocated 0..nseq-1) * * Returns: (void) * wgt is allocated (0..nseq-1) by caller, and filled in here. */ void PositionBasedWeights(char **aseq, int nseq, int alen, float *wgt) { int rescount[26]; /* count of A-Z residues in a column */ int nres; /* number of different residues in col */ int idx, pos; /* indices into aseq */ int x; float norm; FSet(wgt, nseq, 0.0); for (pos = 0; pos < alen; pos++) { for (x = 0; x < 26; x++) rescount[x] = 0; for (idx = 0; idx < nseq; idx++) if (isalpha((int) aseq[idx][pos])) rescount[toupper((int) aseq[idx][pos]) - 'A'] ++; nres = 0; for (x = 0; x < 26; x++) if (rescount[x] > 0) nres++; for (idx = 0; idx < nseq; idx++) if (isalpha((int) aseq[idx][pos])) wgt[idx] += 1. / (float) (nres * rescount[toupper((int) aseq[idx][pos]) - 'A']); } for (idx = 0; idx < nseq; idx++) wgt[idx] /= (float) DealignedLength(aseq[idx]); norm = (float) nseq / FSum(wgt, nseq); FScale(wgt, nseq, norm); return; } /* Function: FilterAlignment() * Date: SRE, Wed Jun 30 09:19:30 1999 [St. Louis] * * Purpose: Constructs a new alignment by removing near-identical * sequences from a given alignment (where identity is * calculated *based on the alignment*). * Does not affect the given alignment. * Keeps earlier sequence, discards later one. * * Usually called as an ad hoc sequence "weighting" mechanism. * * Limitations: * Unparsed Stockholm markup is not propagated into the * new alignment. * * Args: msa -- original alignment * cutoff -- fraction identity cutoff. 0.8 removes sequences > 80% id. * ret_new -- RETURN: new MSA, usually w/ fewer sequences * * Return: (void) * ret_new must be free'd by caller: MSAFree(). */ void FilterAlignment(MSA *msa, float cutoff, MSA **ret_new) { int nnew; /* number of seqs in new alignment */ int *list; int *useme; float ident; int i,j; int remove; /* find which seqs to keep (list) */ /* diff matrix; allow ragged ends */ list = (int*) MallocOrDie(sizeof(int) * msa->nseq); useme = (int*) MallocOrDie(sizeof(int) * msa->nseq); for (i = 0; i < msa->nseq; i++) useme[i] = FALSE; nnew = 0; for (i = 0; i < msa->nseq; i++) { remove = FALSE; for (j = 0; j < nnew; j++) { ident = PairwiseIdentity(msa->aseq[i], msa->aseq[list[j]]); if (ident > cutoff) { remove = TRUE; break; } } if (remove == FALSE) { list[nnew++] = i; useme[i] = TRUE; } } MSASmallerAlignment(msa, useme, ret_new); free(list); free(useme); return; } /* Function: SampleAlignment() * Date: SRE, Wed Jun 30 10:13:56 1999 [St. Louis] * * Purpose: Constructs a new, smaller alignment by sampling a given * number of sequences at random. Does not change the * alignment nor the order of the sequences. * * If you ask for a sample that is larger than nseqs, * it silently returns the original alignment. * * Not really a weighting method, but this is as good * a place as any to keep it, since it's similar in * construction to FilterAlignment(). * * Args: msa -- original alignment * sample -- number of sequences in new alignment (0 < sample <= nseq) * ret_new -- RETURN: new MSA * * Return: (void) * ret_new must be free'd by caller: MSAFree(). */ void SampleAlignment(MSA *msa, int sample, MSA **ret_new) { int *list; /* array for random selection w/o replace */ int *useme; /* array of flags 0..nseq-1: TRUE to use */ int i, idx; int len; /* Allocations */ list = (int *) MallocOrDie(sizeof(int) * msa->nseq); useme = (int *) MallocOrDie (sizeof(int) * msa->nseq); for (i = 0; i < msa->nseq; i++) { list[i] = i; useme[i] = FALSE; } /* Sanity check. */ if (sample >= msa->nseq) sample = msa->nseq; /* random selection w/o replacement */ for (len = msa->nseq, i = 0; i < sample; i++) { idx = CHOOSE(len); useme[list[idx]] = TRUE; list[idx] = list[--len]; } MSASmallerAlignment(msa, useme, ret_new); free(list); free(useme); return; } /* Function: SingleLinkCluster() * Date: SRE, Fri Jul 16 15:02:57 1999 [St. Louis] * * Purpose: Perform simple single link clustering of seqs in a * sequence alignment. A pairwise identity threshold * defines whether two sequences are linked or not. * * Important: runs in O(N) memory, unlike standard * graph decomposition algorithms that use O(N^2) * adjacency matrices or adjacency lists. Requires * O(N^2) time in worst case (which is when you have * no links at all), O(NlogN) in "average" * case, and O(N) in best case (when there is just * one cluster in a completely connected graph. * * (Developed because hmmbuild could no longer deal * with GP120, a 16,013 sequence alignment.) * * Limitations: * CASE-SENSITIVE. Assumes aseq have been put into * either all lower or all upper case; or at least, * within a column, there's no mixed case. * * Algorithm: * I don't know if this algorithm is published. I * haven't seen it in graph theory books, but that might * be because it's so obvious that nobody's bothered. * * In brief, we're going to do a breadth-first search * of the graph, and we're going to calculate links * on the fly rather than precalculating them into * some sort of standard adjacency structure. * * While working, we keep two stacks of maximum length N: * a : list of vertices that are still unconnected. * b : list of vertices that we've connected to * in our current breadth level, but we haven't * yet tested for other connections to a. * The current length (number of elements in) a and b are * kept in na, nb. * * We store our results in an array of length N: * c : assigns each vertex to a component. for example * c[4] = 1 means that vertex 4 is in component 1. * nc is the number of components. Components * are numbered from 0 to nc-1. We return c and nc * to our caller. * * The algorithm is: * * Initialisation: * a <-- all the vertices * na <-- N * b <-- empty set * nb <-- 0 * nc <-- 0 * * Then: * while (a is not empty) * pop a vertex off a, push onto b * while (b is not empty) * pop vertex v off b * assign c[v] = nc * for each vertex w in a: * compare v,w. If w is linked to v, remove w * from a, push onto b. * nc++ * q.e.d. :) * * Args: aseq - aligned sequences * nseq - number of sequences in aseq * alen - alignment length * maxid - fractional identity threshold 0..1. if id >= maxid, seqs linked * ret_c - RETURN: 0..nseq-1 assignments of seqs to components (clusters) * ret_nc - RETURN: number of components * * Returns: void. * ret_c is allocated here. Caller free's with free(*ret_c) */ void SingleLinkCluster(char **aseq, int nseq, int alen, float maxid, int **ret_c, int *ret_nc) { int *a, na; /* stack of available vertices */ int *b, nb; /* stack of working vertices */ int *c; /* array of results */ int nc; /* total number of components */ int v,w; /* index of a working vertices */ int i; /* loop counter */ /* allocations and initializations */ a = (int*)MallocOrDie (sizeof(int) * nseq); b = (int*)MallocOrDie (sizeof(int) * nseq); c = (int*)MallocOrDie (sizeof(int) * nseq); for (i = 0; i < nseq; i++) a[i] = i; na = nseq; nb = 0; nc = 0; /* Main algorithm */ while (na > 0) { v = a[na-1]; na--; /* pop a vertex off a, */ b[nb] = v; nb++; /* and push onto b */ while (nb > 0) { v = b[nb-1]; nb--; /* pop vertex off b */ c[v] = nc; /* assign it to component nc */ for (i = na-1; i >= 0; i--)/* backwards, because of deletion/swapping we do*/ if (simple_distance(aseq[v], aseq[a[i]]) <= 1. - maxid) /* linked? */ { w = a[i]; a[i] = a[na-1]; na--; /* delete w from a (note swap) */ b[nb] = w; nb++; /* push w onto b */ } } nc++; } /* Cleanup and return */ free(a); free(b); *ret_c = c; *ret_nc = nc; return; } ugene-1.9.8/src/plugins_3rdparty/hmm2/src/hmmer2/sre_string.cpp0000644000175000017500000003627411651544326023144 0ustar ilyailya/***************************************************************** * HMMER - Biological sequence analysis with profile HMMs * Copyright (C) 1992-2003 Washington University School of Medicine * All Rights Reserved * * This source code is distributed under the terms of the * GNU General Public License. See the files COPYING and LICENSE * for details. *****************************************************************/ /* sre_string.c * * my library of extra string functions. Some for portability * across UNIXes * * CVS $Id: sre_string.c,v 1.14 2003/05/26 16:21:50 eddy Exp $ */ #include "funcs.h" /* Function: Strdup() * * Purpose: Implementation of the common (but non-ANSI) function * strdup(). Robust against being passed a NULL pointer. * */ char * Strdup(const char *s) { if (s == NULL) { return NULL; } int len = strlen(s) + 1; char *newS = (char *) MallocOrDie (len); sre_strlcpy(newS, s, len); return newS; } /* Function: StringChop() * Date: SRE, Wed Oct 29 12:10:02 1997 [TWA 721] * * Purpose: Chop trailing whitespace off of a string. */ void StringChop(char *s) { int i; i = strlen(s) - 1; /* set i at last char in string */ while (i >= 0 && isspace((int) s[i])) i--; /* i now at last non-whitespace char, or -1 */ s[i+1] = '\0'; } int Strinsert(char *s1, /* string to insert a char into */ char c, /* char to insert */ int pos) /* position in s1 to insert c at */ { char oldc; char *s; for (s = s1 + pos; c; s++) { /* swap current char for inserted one */ oldc = *s; /* pick up current */ *s = c; /* put down inserted one */ c = oldc; /* old becomes next to insert */ } *s = '\0'; return 1; } int Strdelete(char *s1, /* string to delete a char from */ int pos) /* position of char to delete 0..n-1 */ { char *s; for (s = s1 + pos; *s; s++) *s = *(s + 1); return 1; } void s2lower(char *s) { for (; *s != '\0'; s++) *s = sre_tolower((int) *s); } void s2upper(char *s) { for (; *s != '\0'; s++) *s = sre_toupper((int) *s); } void * sre_malloc(const char *file, int line, size_t size) { void *ptr; SQD_DPRINTF3(("MALLOC: %d bytes (file %s line %d)\n", size, file, line)); if ((ptr = malloc (size)) == NULL) Die("malloc of %ld bytes failed: file %s line %d", size, file, line); return ptr; } void * sre_realloc(const char *file, int line, void *p, size_t size) { void *ptr; if ((ptr = realloc(p, size)) == NULL) Die("realloc of %ld bytes failed: file %s line %d", size, file, line); return ptr; } /* Function: Free2DArray(), Free3DArray() * Date: SRE, Tue Jun 1 14:47:14 1999 [St. Louis] * * Purpose: Convenience functions for free'ing 2D * and 3D pointer arrays. Tolerates any of the * pointers being NULL, to allow "sparse" * arrays. * * Args: p - array to be freed * dim1 - n for first dimension * dim2 - n for second dimension * * e.g. a 2d array is indexed p[0..dim1-1][] * a 3D array is indexed p[0..dim1-1][0..dim2-1][] * * Returns: void * * Diagnostics: (void) * "never fails" */ void Free2DArray(void **p, int dim1) { int i; if (p != NULL) { for (i = 0; i < dim1; i++) if (p[i] != NULL) free(p[i]); free(p); } } void Free3DArray(void ***p, int dim1, int dim2) { int i, j; if (p != NULL) { for (i = 0; i < dim1; i++) if (p[i] != NULL) { for (j = 0; j < dim2; j++) if (p[i][j] != NULL) free(p[i][j]); free(p[i]); } free(p); } } /* Function: RandomSequence() * * Purpose: Generate an iid symbol sequence according * to some alphabet, alphabet_size, probability * distribution, and length. Return the * sequence. * * Args: alphabet - e.g. "ACGT" * p - probability distribution [0..n-1] * n - number of symbols in alphabet * len - length of generated sequence * * Return: ptr to random sequence, or NULL on failure. */ char * RandomSequence(char *alphabet, float *p, int n, int len) { char *s; int x; s = (char *) MallocOrDie (sizeof(char) * (len+1)); for (x = 0; x < len; x++) s[x] = alphabet[FChoose(p,n)]; s[x] = '\0'; return s; } /* Function: sre_fgets() * Date: SRE, Thu May 13 10:56:28 1999 [St. Louis] * * Purpose: Dynamic allocation version of fgets(), * capable of reading unlimited line lengths. * * Args: buf - ptr to a string (may be reallocated) * n - ptr to current allocated length of buf, * (may be changed) * fp - open file ptr for reading * * Before the first call to sre_fgets(), * buf should be initialized to NULL and n to 0. * They're a linked pair, so don't muck with the * allocation of buf or the value of n while * you're still doing sre_fgets() calls with them. * * Returns: ptr to the buffer on success. * NULL on EOF (buf isn't to be used in this case) * sre_fgets() *always* results in an allocation * in buf. * * The reason to have it return a ptr to buf * is that it makes wrapper macros easy; see * MSAFileGetLine() for an example. * * Example: char *buf; * int n; * FILE *fp; * * fp = fopen("my_file", "r"); * buf = NULL; * n = 0; * while (sre_fgets(&buf, &n, fp) != NULL) * { * do stuff with buf; * } */ char * sre_fgets(char **buf, int *n, FILE *fp) { char *s; int len; int pos; if (*n == 0) { *buf = (char*)MallocOrDie(sizeof(char) * 128); *n = 128; } /* Simple case 1. We're sitting at EOF, or there's an error. * fgets() returns NULL, so we return NULL. */ if (fgets(*buf, *n, fp) == NULL) return NULL; /* Simple case 2. fgets() got a string, and it reached EOF. * return success status, so caller can use * the last line; on the next call we'll * return the 0 for the EOF. */ if (feof(fp)) return *buf; /* Simple case 3. We got a complete string, with \n, * and don't need to extend the buffer. */ len = strlen(*buf); if ((*buf)[len-1] == '\n') return *buf; /* The case we're waiting for. We have an incomplete string, * and we have to extend the buffer one or more times. Make * sure we overwrite the previous fgets's \0 (hence +(n-1) * in first step, rather than 128, and reads of 129, not 128). */ pos = (*n)-1; while (1) { *n += 128; *buf = (char*)ReallocOrDie(*buf, sizeof(char) * (*n)); s = *buf + pos; if (fgets(s, 129, fp) == NULL) return *buf; len = strlen(s); if (s[len-1] == '\n') return *buf; pos += 128; } /*NOTREACHED*/ } /* Function: sre_strcat() * Date: SRE, Thu May 13 09:36:32 1999 [St. Louis] * * Purpose: Dynamic memory version of strcat(). * appends src to the string that dest points to, * extending allocation for dest if necessary. * * One timing experiment (100 successive appends of * 1-255 char) shows sre_strcat() has about a 20% * overhead relative to strcat(). However, if optional * length info is passed, sre_strcat() is about 30% * faster than strcat(). * * Args: dest - ptr to string (char **), '\0' terminated * ldest - length of dest, if known; or -1 if length unknown. * src - string to append to dest, '\0' terminated * lsrc - length of src, if known; or -1 if length unknown. * * dest may be NULL, in which case this is * the equivalent of dest = Strdup(src). * * src may also be NULL, in which case * dest is unmodified (but why would you want to pass * a NULL src?) * * if both dest and src are NULL, dest is * unmodified; it stays NULL. * * the length parameters are optional. If a -1 * is passed, sre_strcat() will call strlen() to * determine the length itself. Passing length * info saves the strlen() calls and can speed things * up if lots of successive appends need to be done. * * Returns: new length of dest (>=0 on success); * dest is (probably) ReallocOrDieated, and modified * to a longer string, '\0' terminated. */ int sre_strcat(char **dest, int ldest, char *src, int lsrc) { int len1, len2; if (ldest < 0) len1 = ((*dest == NULL) ? 0 : strlen(*dest)); else len1 = ldest; if (lsrc < 0) len2 = (( src == NULL) ? 0 : strlen(src)); else len2 = lsrc; if (len2 == 0) return len1; if (*dest == NULL) *dest = (char*)MallocOrDie(sizeof(char) * (len2+1)); else *dest = (char*)ReallocOrDie(*dest, sizeof(char) * (len1+len2+1)); memcpy((*dest)+len1, src, len2+1); return len1+len2; } /* Function: sre_strtok() * Date: SRE, Wed May 19 16:30:20 1999 [St. Louis] * * Purpose: Thread-safe version of strtok(). * * Returns ptr to next token in a string: skips * until it reaches a character that is not in the delim * string, and sets beginning of token. Skips to * next delim character (or '\0') to set the end; replaces that * character with '\0'. * If there's still more string left, sets s to point to next * character after the '\0' that was written, so successive * calls extract tokens in succession. If there was no string * left, s points at the terminal '\0'. * * If no token is found, returns NULL. * * Also returns the length of the token, which * may save us a strlen() call in some applications. * * Limitations: * *s can't be a constant string, since we write to it. * * Example: * char *tok; * int len; * char *s; * char buf[50] = "This is a sentence."; * * s = buf; * tok = sre_strtok(&s, " ", &len); * tok is "This"; s is "is a sentence."; len is 4. * tok = sre_strtok(&s, " ", &len); * tok is "is"; s is " a sentence."; len is 2. * tok = sre_strtok(&s, " ", &len); * tok is "a"; s is "sentence."; len is 1. * tok = sre_strtok(&s, " ", &len); * tok is "sentence."; s is "\0"; len is 9. * tok = sre_strtok(&s, " ", &len); * tok is NULL; s is "\0", len is undefined. * * Args: s - a tmp, modifiable ptr to string * delim - characters that delimits tokens * len - RETURN: length of token; pass NULL if not wanted * * Returns: ptr to next token, or NULL if there aren't any. */ char * sre_strtok(char **s, char *delim, int *len) { char *begin, *end; int n; begin = *s; begin += strspn(begin, delim); if (! *begin) return NULL; n = strcspn(begin, delim); end = begin + n; if (*end == '\0') { *s = end;} else { *end = '\0'; *s = end+1; } if (len != NULL) *len = n; return begin; } /* Function: sre_strdup() * Date: SRE, Wed May 19 17:57:28 1999 [St. Louis] * * Purpose: A version of the common but non-ANSI strdup() * function. Can pass len, if known, to save a * strlen() call. * * Args: s - string to duplicate * n - length of string, if known; -1 if unknown. * * Returns: allocated copy of string. * NULL on failure. */ char * sre_strdup(const char *s, int n) { if (s == NULL) return NULL; if (n < 0) n = strlen(s); char *newS = (char*)MallocOrDie (sizeof(char) * (n+1)); sre_strlcpy(newS, s, n+1); return newS; } /* Function: IsBlankline() * Date: SRE, Fri Jun 18 14:36:08 1999 [St. Louis] * * Purpose: Returns TRUE if string consists solely of whitespace. * * Args: s - string to check */ int IsBlankline(char *s) { for (; *s != '\0'; s++) if (! isspace((int) *s)) return FALSE; return TRUE; } int sre_tolower(int c) { if (isupper(c)) return tolower(c); else return c; } int sre_toupper(int c) { if (islower(c)) return toupper(c); else return c; } //extra string manipulations functions for cross platform compatibliity /* * Copyright (c) 1998 Todd C. Miller * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include #include /* * Copy src to string dst of size siz. At most siz-1 characters * will be copied. Always NUL terminates (unless siz == 0). * Returns strlen(src); if retval >= siz, truncation occurred. */ size_t sre_strlcpy(char *dst, const char *src, size_t siz) { char *d = dst; const char *s = src; size_t n = siz; /* Copy as many bytes as will fit */ if (n != 0) { while (--n != 0) { if ((*d++ = *s++) == '\0') break; } } /* Not enough room in dst, add NUL and traverse rest of src */ if (n == 0) { if (siz != 0) *d = '\0'; /* NUL-terminate dst */ while (*s++) ; } return(s - src - 1); /* count does not include NUL */ } /* * Appends src to string dst of size siz (unlike strncat, siz is the * full size of dst, not space left). At most siz-1 characters * will be copied. Always NUL terminates (unless siz <= strlen(dst)). * Returns strlen(src) + MIN(siz, strlen(initial dst)). * If retval >= siz, truncation occurred. */ size_t sre_strlcat(char *dst, const char *src, size_t siz) { char *d = dst; const char *s = src; size_t n = siz; size_t dlen; /* Find the end of dst and adjust bytes left but don't go past end */ while (n-- != 0 && *d != '\0') d++; dlen = d - dst; n = siz - dlen; if (n == 0) return(dlen + strlen(s)); while (*s != '\0') { if (n != 1) { *d++ = *s; n--; } s++; } *d = '\0'; return(dlen + (s - src)); /* count does not include NUL */ } ugene-1.9.8/src/plugins_3rdparty/hmm2/src/hmmer2/fast_algorithms.cpp0000644000175000017500000001517111651544326024144 0ustar ilyailya/************************************************************ * HMMER - Biological sequence analysis with profile HMMs * Copyright (C) 1992-2003 Washington University School of Medicine * All Rights Reserved * * This source code is distributed under the terms of the * GNU General Public License. See the files COPYING and LICENSE * for details. ************************************************************/ /* fast_algorithms.c * SRE, Sun Nov 10 08:54:48 2002 [AA 3080, Denver to StL] * CVS $Id: fast_algorithms.c,v 1.9 2003/10/02 16:39:41 eddy Exp $ * * Optimized routines to replace slower implementations in core_algorithms.c. * * The routines in core_algorithms.c are designed for clarity * and maintainability, not for speed. Implementations here * are designed for speed, not clarity. If you're trying to * understand the code, or optimize for a specific platform, * you are probably better off looking at core_algorithms.c. * * P7Viterbi() is the key function to target optimization to. * The implementation in core_algorithms.c is currently ifdef'ed * out of the code. The implementation that is used by default * is here, in fast_algorithms.c. A third implementation, from * Erik Lindahl at Stanford, is Mac/Altivec specific. * * Which implementation is used is controlled by ifdef's. The * default implementation uses a fast implementation of * P7Viterbi() from here. Other options (mutually exclusive): * * -DSLOW * enable original core_algorithms.c code: slower than default, * but might be easier to follow, for someone trying * to understand the DP code. */ #include "funcs.h" /* the DEFAULT P7Viterbi() is portably optimized; code follows: */ #if !defined SLOW && !defined ALTIVEC /* Function: P7Viterbi() - portably optimized version * Incept: SRE, Fri Nov 15 13:14:33 2002 [St. Louis] * * Purpose: The Viterbi dynamic programming algorithm. * Derived from core_algorithms.c:P7Viterbi(). * * Args: dsq - sequence in digitized form * L - length of dsq * hmm - the model * mx - re-used DP matrix * ret_tr - RETURN: traceback; pass NULL if it's not wanted * * Return: log P(S|M)/P(S|R), as a bit score */ float P7Viterbi(unsigned char *dsq, int L, struct plan7_s *hmm, struct dpmatrix_s *mx, struct p7trace_s **ret_tr) { struct p7trace_s *tr; int **xmx; int **mmx; int **imx; int **dmx; int i,k; int sc; int *mc, *dc, *ic; /* pointers to rows of mmx, dmx, imx */ int *ms, *is; /* pointers to msc[i], isc[i] */ int *mpp, *mpc, *ip; /* ptrs to mmx[i-1], mmx[i], imx[i-1] */ int *bp; /* ptr into bsc[] */ int *ep; /* ptr into esc[] */ int xmb; /* value of xmx[i-1][XMB] */ int xme; /* max for xmx[i][XME] */ int *dpp; /* ptr into dmx[i-1] (previous row) */ int *tpmm, *tpmi, *tpmd, *tpim, *tpii, *tpdm, *tpdd; /* ptrs into tsc */ int M; /* Make sure we have space for a DP matrix with 0..L rows, 0..M-1 columns. */ ResizePlan7Matrix(mx, L, hmm->M, &xmx, &mmx, &imx, &dmx); /* Initialization of the zero row. */ xmx[0][XMN] = 0; /* S->N, p=1 */ xmx[0][XMB] = hmm->xsc[XTN][MOVE]; /* S->N->B, no N-tail */ xmx[0][XME] = xmx[0][XMC] = xmx[0][XMJ] = -INFTY; /* need seq to get here */ for (k = 0; k <= hmm->M; k++) mmx[0][k] = imx[0][k] = dmx[0][k] = -INFTY; /* need seq to get here */ /* Initializations that help icc vectorize. */ M = hmm->M; /* Recursion. Done as a pull. * Note some slightly wasteful boundary conditions: * tsc[0] = -INFTY for all eight transitions (no node 0) * D_M and I_M are wastefully calculated (they don't exist) */ tpmm = hmm->tsc[TMM]; tpim = hmm->tsc[TIM]; tpdm = hmm->tsc[TDM]; tpmd = hmm->tsc[TMD]; tpdd = hmm->tsc[TDD]; tpmi = hmm->tsc[TMI]; tpii = hmm->tsc[TII]; bp = hmm->bsc; for (i = 1; i <= L ; i++) { mc = mmx[i]; dc = dmx[i]; ic = imx[i]; mpp = mmx[i-1]; dpp = dmx[i-1]; ip = imx[i-1]; xmb = xmx[i-1][XMB]; ms = hmm->msc[dsq[i]]; is = hmm->isc[dsq[i]]; mc[0] = -INFTY; dc[0] = -INFTY; ic[0] = -INFTY; for (k = 1; k <= M; k++) { mc[k] = mpp[k-1] + tpmm[k-1]; if ((sc = ip[k-1] + tpim[k-1]) > mc[k]) mc[k] = sc; if ((sc = dpp[k-1] + tpdm[k-1]) > mc[k]) mc[k] = sc; if ((sc = xmb + bp[k]) > mc[k]) mc[k] = sc; mc[k] += ms[k]; if (mc[k] < -INFTY) mc[k] = -INFTY; dc[k] = dc[k-1] + tpdd[k-1]; if ((sc = mc[k-1] + tpmd[k-1]) > dc[k]) dc[k] = sc; if (dc[k] < -INFTY) dc[k] = -INFTY; if (k < M) { ic[k] = mpp[k] + tpmi[k]; if ((sc = ip[k] + tpii[k]) > ic[k]) ic[k] = sc; ic[k] += is[k]; if (ic[k] < -INFTY) ic[k] = -INFTY; } } /* Now the special states. Order is important here. * remember, C and J emissions are zero score by definition, */ /* N state */ xmx[i][XMN] = -INFTY; if ((sc = xmx[i-1][XMN] + hmm->xsc[XTN][LOOP]) > -INFTY) xmx[i][XMN] = sc; /* E state */ xme = -INFTY; mpc = mmx[i]; ep = hmm->esc; for (k = 1; k <= hmm->M; k++) if ((sc = mpc[k] + ep[k]) > xme) xme = sc; xmx[i][XME] = xme; /* J state */ xmx[i][XMJ] = -INFTY; if ((sc = xmx[i-1][XMJ] + hmm->xsc[XTJ][LOOP]) > -INFTY) xmx[i][XMJ] = sc; if ((sc = xmx[i][XME] + hmm->xsc[XTE][LOOP]) > xmx[i][XMJ]) xmx[i][XMJ] = sc; /* B state */ xmx[i][XMB] = -INFTY; if ((sc = xmx[i][XMN] + hmm->xsc[XTN][MOVE]) > -INFTY) xmx[i][XMB] = sc; if ((sc = xmx[i][XMJ] + hmm->xsc[XTJ][MOVE]) > xmx[i][XMB]) xmx[i][XMB] = sc; /* C state */ xmx[i][XMC] = -INFTY; if ((sc = xmx[i-1][XMC] + hmm->xsc[XTC][LOOP]) > -INFTY) xmx[i][XMC] = sc; if ((sc = xmx[i][XME] + hmm->xsc[XTE][MOVE]) > xmx[i][XMC]) xmx[i][XMC] = sc; } /* T state (not stored) */ sc = xmx[L][XMC] + hmm->xsc[XTC][MOVE]; if (ret_tr != NULL) { P7ViterbiTrace(hmm, dsq, L, mx, &tr); *ret_tr = tr; } return Scorify(sc); /* the total Viterbi score. */ } #endif //#if !defined SLOW && !defined ALTIVEC ugene-1.9.8/src/plugins_3rdparty/hmm2/src/hmmer2/sre_random.cpp0000644000175000017500000002232311651544326023104 0ustar ilyailya/***************************************************************** * HMMER - Biological sequence analysis with profile HMMs * Copyright (C) 1992-2003 Washington University School of Medicine * All Rights Reserved * * This source code is distributed under the terms of the * GNU General Public License. See the files COPYING and LICENSE * for details. *****************************************************************/ /* sre_random.c * * Portable random number generator, and sampling routines. * * SRE, Tue Oct 1 15:24:11 2002 [St. Louis] * CVS $Id: sre_random.c,v 1.2 2003/04/14 16:00:16 eddy Exp $ */ #include "funcs.h" //static int sre_randseed = 42; /* default seed for sre_random() */ /* Function: sre_random() * * Purpose: Return a uniform deviate x, 0.0 <= x < 1.0. * * sre_randseed is a static variable, set * by sre_srandom(). When it is non-zero, * we re-seed. * * Implements L'Ecuyer's algorithm for combining output * of two linear congruential generators, plus a Bays-Durham * shuffle. This is essentially ran2() from Numerical Recipes, * sans their nonhelpful Rand/McNally-esque code obfuscation. * * Overflow errors are avoided by Schrage's algorithm: * az % m = a(z%q) - r(z/q) (+m if <0) * where q=m/a, r=m%a * * Requires that long int's have at least 32 bits. * This function uses statics and is NOT THREADSAFE. * * Reference: Press et al. Numerical Recipes in C, 1992. * * Reliable and portable, but slow. Benchmarks on wrasse, * using Linux gcc and Linux glibc rand() (see randspeed, in Testsuite): * sre_random(): 0.5 usec/call * rand(): 0.2 usec/call */ double sre_random(void) { //static long rnd1; /* random number from LCG1 */ //static long rnd2; /* random number from LCG2 */ //static long rnd; /* random number we return */ //static long tbl[64]; /* table for Bays/Durham shuffle */ HMMERTaskLocalData *td = getHMMERTaskLocalData(); long &rnd1 = td->rnd1; long &rnd2 = td->rnd2; long &rnd = td->rnd; long *tbl = td->tbl; int &sre_randseed = td->sre_randseed; long x,y; int i; /* Magic numbers a1,m1, a2,m2 from L'Ecuyer, for 2 LCGs. * q,r derive from them (q=m/a, r=m%a) and are needed for Schrage's algorithm. */ long a1 = 40014; long m1 = 2147483563; long q1 = 53668; long r1 = 12211; long a2 = 40692; long m2 = 2147483399; long q2 = 52774; long r2 = 3791; if (sre_randseed > 0) { rnd1 = sre_randseed; rnd2 = sre_randseed; rnd = 0; /* Fill the table for Bays/Durham */ for (i = 0; i < 64; i++) { x = a1*(rnd1%q1); /* LCG1 in action... */ y = r1*(rnd1/q1); rnd1 = x-y; if (rnd1 < 0) rnd1 += m1; x = a2*(rnd2%q2); /* LCG2 in action... */ y = r2*(rnd2/q2); rnd2 = x-y; if (rnd2 < 0) rnd2 += m2; tbl[i] = rnd1-rnd2; if (tbl[i] < 0) tbl[i] += m1; } sre_randseed = 0; /* drop the flag. */ }/* end of initialization*/ x = a1*(rnd1%q1); /* LCG1 in action... */ y = r1*(rnd1/q1); rnd1 = x-y; if (rnd1 < 0) rnd1 += m1; x = a2*(rnd2%q2); /* LCG2 in action... */ y = r2*(rnd2/q2); rnd2 = x-y; if (rnd2 < 0) rnd2 += m2; /* Choose our random number from the table... */ i = (int) (((double) rnd / (double) m1) * 64.); rnd = tbl[i]; /* and replace with a new number by L'Ecuyer. */ tbl[i] = rnd1-rnd2; if (tbl[i] < 0) tbl[i] += m1; return ((double) rnd / (double) m1); } /* Function: sre_srandom() * * Purpose: Initialize with a random seed. Seed must be * >= 0 to work; we silently enforce this. */ void sre_srandom(int seed) { HMMERTaskLocalData *td = getHMMERTaskLocalData(); if (seed < 0) seed = -1 * seed; if (seed == 0) seed = 42; td->sre_randseed = seed; } /* Function: sre_random_positive() * Date: SRE, Wed Apr 17 13:34:32 2002 [St. Louis] * * Purpose: Assure 0 < x < 1 (positive uniform deviate) */ double sre_random_positive(void) { double x; do { x = sre_random(); } while (x == 0.0); return x; } /* Function: ExponentialRandom() * Date: SRE, Mon Sep 6 21:24:29 1999 [St. Louis] * * Purpose: Pick an exponentially distributed random variable * 0 > x >= infinity * * Args: (void) * * Returns: x */ double ExponentialRandom(void) { double x; do x = sre_random(); while (x == 0.0); return -log(x); } /* Function: Gaussrandom() * * Pick a Gaussian-distributed random variable * with some mean and standard deviation, and * return it. * * Based on RANLIB.c public domain implementation. * Thanks to the authors, Barry W. Brown and James Lovato, * University of Texas, M.D. Anderson Cancer Center, Houston TX. * Their implementation is from Ahrens and Dieter, "Extensions * of Forsythe's method for random sampling from the normal * distribution", Math. Comput. 27:927-937 (1973). * * Impenetrability of the code is to be blamed on its FORTRAN/f2c lineage. * */ double Gaussrandom(double mean, double stddev) { static double a[32] = { 0.0,3.917609E-2,7.841241E-2,0.11777,0.1573107,0.1970991,0.2372021,0.2776904, 0.3186394,0.36013,0.4022501,0.4450965,0.4887764,0.5334097,0.5791322, 0.626099,0.6744898,0.7245144,0.7764218,0.8305109,0.8871466,0.9467818, 1.00999,1.077516,1.150349,1.229859,1.318011,1.417797,1.534121,1.67594, 1.862732,2.153875 }; static double d[31] = { 0.0,0.0,0.0,0.0,0.0,0.2636843,0.2425085,0.2255674,0.2116342,0.1999243, 0.1899108,0.1812252,0.1736014,0.1668419,0.1607967,0.1553497,0.1504094, 0.1459026,0.14177,0.1379632,0.1344418,0.1311722,0.128126,0.1252791, 0.1226109,0.1201036,0.1177417,0.1155119,0.1134023,0.1114027,0.1095039 }; static double t[31] = { 7.673828E-4,2.30687E-3,3.860618E-3,5.438454E-3,7.0507E-3,8.708396E-3, 1.042357E-2,1.220953E-2,1.408125E-2,1.605579E-2,1.81529E-2,2.039573E-2, 2.281177E-2,2.543407E-2,2.830296E-2,3.146822E-2,3.499233E-2,3.895483E-2, 4.345878E-2,4.864035E-2,5.468334E-2,6.184222E-2,7.047983E-2,8.113195E-2, 9.462444E-2,0.1123001,0.136498,0.1716886,0.2276241,0.330498,0.5847031 }; static double h[31] = { 3.920617E-2,3.932705E-2,3.951E-2,3.975703E-2,4.007093E-2,4.045533E-2, 4.091481E-2,4.145507E-2,4.208311E-2,4.280748E-2,4.363863E-2,4.458932E-2, 4.567523E-2,4.691571E-2,4.833487E-2,4.996298E-2,5.183859E-2,5.401138E-2, 5.654656E-2,5.95313E-2,6.308489E-2,6.737503E-2,7.264544E-2,7.926471E-2, 8.781922E-2,9.930398E-2,0.11556,0.1404344,0.1836142,0.2790016,0.7010474 }; HMMERTaskLocalData *td = getHMMERTaskLocalData(); //static long i; //static double snorm,u,s,ustar,aa,w,y,tt; long &i(td->i); double &snorm(td->snorm),&u(td->u),&s(td->s),&ustar(td->ustar),&aa(td->aa),&w(td->w),&y(td->y),&tt(td->tt); u = sre_random(); s = 0.0; if(u > 0.5) s = 1.0; u += (u-s); u = 32.0*u; i = (long) (u); if(i == 32) i = 31; if(i == 0) goto S100; /* * START CENTER */ ustar = u-(double)i; aa = *(a+i-1); S40: if(ustar <= *(t+i-1)) goto S60; w = (ustar-*(t+i-1))**(h+i-1); S50: /* * EXIT (BOTH CASES) */ y = aa+w; snorm = y; if(s == 1.0) snorm = -y; return (stddev*snorm + mean); S60: /* * CENTER CONTINUED */ u = sre_random(); w = u*(*(a+i)-aa); tt = (0.5*w+aa)*w; goto S80; S70: tt = u; ustar = sre_random(); S80: if(ustar > tt) goto S50; u = sre_random(); if(ustar >= u) goto S70; ustar = sre_random(); goto S40; S100: /* * START TAIL */ i = 6; aa = *(a+31); goto S120; S110: aa += *(d+i-1); i += 1; S120: u += u; if(u < 1.0) goto S110; u -= 1.0; S140: w = u**(d+i-1); tt = (0.5*w+aa)*w; goto S160; S150: tt = u; S160: ustar = sre_random(); if(ustar > tt) goto S50; u = sre_random(); if(ustar >= u) goto S150; u = sre_random(); goto S140; } /* Functions: DChoose(), FChoose() * * Purpose: Make a random choice from a normalized distribution. * DChoose() is for double-precision vectors; * FChoose() is for single-precision float vectors. * Returns the number of the choice. */ int DChoose(double *p, int N) { double roll; /* random fraction */ double sum; /* integrated prob */ int i; /* counter over the probs */ roll = sre_random(); sum = 0.0; for (i = 0; i < N; i++) { sum += p[i]; if (roll < sum) return i; } return (int) (sre_random() * N); /* bulletproof */ } int FChoose(float *p, int N) { float roll; /* random fraction */ float sum; /* integrated prob */ int i; /* counter over the probs */ roll = sre_random(); sum = 0.0; for (i = 0; i < N; i++) { sum += p[i]; if (roll < sum) return i; } return (int) (sre_random() * N); /* bulletproof */ } ugene-1.9.8/src/plugins_3rdparty/hmm2/src/hmmer2/tophits.cpp0000644000175000017500000002355711651544326022457 0ustar ilyailya/************************************************************ * HMMER - Biological sequence analysis with profile HMMs * Copyright (C) 1992-2003 Washington University School of Medicine * All Rights Reserved * * This source code is distributed under the terms of the * GNU General Public License. See the files COPYING and LICENSE * for details. ************************************************************/ /* tophits.c * * Routines for storing, sorting, displaying high scoring hits * and alignments. * ***************************************************************************** * * main API: * * AllocTophits() - allocation * FreeTophits() - free'ing * RegisterHit() - put information about a hit in the list * GetRankedHit() - recovers information about a hit * FullSortTophits() - sorts the top H hits. * ***************************************************************************** * Brief example of use: * * struct tophit_s *yourhits; // list of hits * struct fancyali_s *ali; // (optional structure) alignment of a hit * * yourhits = AllocTophits(200); * (for every hit in a search) { * if (do_alignments) * ali = Trace2FancyAli(); // You provide a function/structure here * if (score > threshold) * RegisterHit(yourhits, ...) * } * * FullSortTophits(yourhits); // Sort hits by evalue * for (i = 0; i < 100; i++) // Recover hits out in ranked order * { * GetRankedHit(yourhits, i, ...); * // Presumably you'd print here... * } * FreeTophits(yourhits); *************************************************************************** * * Estimated storage per hit: * coords: 16 bytes * scores: 8 bytes * name/acc/desc: 192 bytes * alignment: 1000 bytes total = ~1200 bytes with alignment; * = ~200 bytes without * Designed for: 10^5 hits (20 MB) or 10^4 alignments (10 MB) */ #include "funcs.h" /* Function: AllocTophits() * * Purpose: Allocate a struct tophit_s, for maintaining * a list of top-scoring hits in a database search. * * Args: lumpsize - allocation lumpsize * * Return: An allocated struct hit_s. Caller must free. */ struct tophit_s * AllocTophits(int lumpsize) { struct tophit_s *hitlist; hitlist = (struct tophit_s*)MallocOrDie (sizeof(struct tophit_s)); hitlist->hit = NULL; hitlist->unsrt = (struct hit_s*)MallocOrDie (lumpsize * sizeof(struct hit_s)); hitlist->alloc = lumpsize; hitlist->num = 0; hitlist->lump = lumpsize; return hitlist; } void GrowTophits(struct tophit_s *h) { h->unsrt = (struct hit_s*)ReallocOrDie(h->unsrt,(h->alloc + h->lump) * sizeof(struct hit_s)); h->alloc += h->lump; } void FreeTophits(struct tophit_s *h) { int pos; for (pos = 0; pos < h->num; pos++) { if (h->unsrt[pos].ali != NULL) FreeFancyAli(h->unsrt[pos].ali); if (h->unsrt[pos].name != NULL) free(h->unsrt[pos].name); if (h->unsrt[pos].acc != NULL) free(h->unsrt[pos].acc); if (h->unsrt[pos].desc != NULL) free(h->unsrt[pos].desc); } free(h->unsrt); if (h->hit != NULL) free(h->hit); free(h); } struct fancyali_s * AllocFancyAli(void) { struct fancyali_s *ali; ali = (struct fancyali_s*)MallocOrDie(sizeof(struct fancyali_s)); ali->rfline = ali->csline = ali->model = ali->mline = ali->aseq = NULL; ali->query = ali->target = NULL; ali->sqfrom = ali->sqto = 0; return ali; } void FreeFancyAli(struct fancyali_s *ali) { if (ali != NULL) { if (ali->rfline != NULL) free(ali->rfline); if (ali->csline != NULL) free(ali->csline); if (ali->model != NULL) free(ali->model); if (ali->mline != NULL) free(ali->mline); if (ali->aseq != NULL) free(ali->aseq); if (ali->query != NULL) free(ali->query); if (ali->target != NULL) free(ali->target); free(ali); } } /* Function: RegisterHit() * * Purpose: Add a new hit to a list of top hits. * * "ali", if provided, is a pointer to allocated memory * for an alignment output structure. * Management is turned over to the top hits structure. * Caller should not free them; they will be free'd by * the FreeTophits() call. * * In contrast, "name", "acc", and "desc" are copied, so caller * is still responsible for these. * * Number of args is unwieldy. * * Args: h - active top hit list * key - value to sort by: bigger is better * pvalue - P-value of this hit * score - score of this hit * motherp - P-value of parent whole sequence * mothersc - score of parent whole sequence * name - name of target * acc - accession of target (may be NULL) * desc - description of target (may be NULL) * sqfrom - 1..L pos in target seq of start * sqto - 1..L pos; sqfrom > sqto if rev comp * sqlen - length of sequence, L * hmmfrom - 0..M+1 pos in HMM of start * hmmto - 0..M+1 pos in HMM of end * hmmlen - length of HMM, M * domidx - number of this domain * ndom - total # of domains in sequence * ali - optional printable alignment info * * Return: (void) * hitlist is modified and possibly reallocated internally. */ void RegisterHit(struct tophit_s *h, double key, double pvalue, float score, double motherp, float mothersc, char *name, char *acc, char *desc, int sqfrom, int sqto, int sqlen, int hmmfrom, int hmmto, int hmmlen, int domidx, int ndom, struct fancyali_s *ali) { /* Check to see if list is full and we must realloc. */ if (h->num == h->alloc) GrowTophits(h); h->unsrt[h->num].name = Strdup(name); h->unsrt[h->num].acc = Strdup(acc); h->unsrt[h->num].desc = Strdup(desc); h->unsrt[h->num].sortkey = key; h->unsrt[h->num].pvalue = pvalue; h->unsrt[h->num].score = score; h->unsrt[h->num].motherp = motherp; h->unsrt[h->num].mothersc= mothersc; h->unsrt[h->num].sqfrom = sqfrom; h->unsrt[h->num].sqto = sqto; h->unsrt[h->num].sqlen = sqlen; h->unsrt[h->num].hmmfrom = hmmfrom; h->unsrt[h->num].hmmto = hmmto; h->unsrt[h->num].hmmlen = hmmlen; h->unsrt[h->num].domidx = domidx; h->unsrt[h->num].ndom = ndom; h->unsrt[h->num].ali = ali; h->num++; return; } /* Function: GetRankedHit() * Date: SRE, Tue Oct 28 10:06:48 1997 [Newton Institute, Cambridge UK] * * Purpose: Recover the data from the i'th ranked hit. * Any of the data ptrs may be passed as NULL for fields * you don't want. hitlist must have been sorted first. * * name, acc, desc, and ali are returned as pointers, not copies; * don't free them! */ void GetRankedHit(struct tophit_s *h, int rank, double *r_pvalue, float *r_score, double *r_motherp, float *r_mothersc, char **r_name, char **r_acc, char **r_desc, int *r_sqfrom, int *r_sqto, int *r_sqlen, int *r_hmmfrom, int *r_hmmto, int *r_hmmlen, int *r_domidx, int *r_ndom, struct fancyali_s **r_ali) { if (r_pvalue != NULL) *r_pvalue = h->hit[rank]->pvalue; if (r_score != NULL) *r_score = h->hit[rank]->score; if (r_motherp != NULL) *r_motherp = h->hit[rank]->motherp; if (r_mothersc!= NULL) *r_mothersc= h->hit[rank]->mothersc; if (r_name != NULL) *r_name = h->hit[rank]->name; if (r_acc != NULL) *r_acc = h->hit[rank]->acc; if (r_desc != NULL) *r_desc = h->hit[rank]->desc; if (r_sqfrom != NULL) *r_sqfrom = h->hit[rank]->sqfrom; if (r_sqto != NULL) *r_sqto = h->hit[rank]->sqto; if (r_sqlen != NULL) *r_sqlen = h->hit[rank]->sqlen; if (r_hmmfrom != NULL) *r_hmmfrom = h->hit[rank]->hmmfrom; if (r_hmmto != NULL) *r_hmmto = h->hit[rank]->hmmto; if (r_hmmlen != NULL) *r_hmmlen = h->hit[rank]->hmmlen; if (r_domidx != NULL) *r_domidx = h->hit[rank]->domidx; if (r_ndom != NULL) *r_ndom = h->hit[rank]->ndom; if (r_ali != NULL) *r_ali = h->hit[rank]->ali; } /* Function: TophitsMaxName() * * Purpose: Returns the maximum name length in a top hits list; * doesn't need to be sorted yet. */ int TophitsMaxName(struct tophit_s *h) { int i; int len, maxlen; maxlen = 0; for (i = 0; i < h->num; i++) { len = strlen(h->unsrt[i].name); if (len > maxlen) maxlen = len; } return maxlen; } /* Function: FullSortTophits() * * Purpose: Completely sort the top hits list. Calls * qsort() to do the sorting, and uses * hit_comparison() to do the comparison. * * Args: h - top hits structure */ int hit_comparison(const void *vh1, const void *vh2) { /* don't ask. don't change. Don't Panic. */ struct hit_s *h1 = *((struct hit_s **) vh1); struct hit_s *h2 = *((struct hit_s **) vh2); if (h1->sortkey < h2->sortkey) return 1; else if (h1->sortkey > h2->sortkey) return -1; else if (h1->sortkey == h2->sortkey) return 0; /*NOTREACHED*/ return 0; } void FullSortTophits(struct tophit_s *h) { int i; /* If we don't have /any/ hits, then don't * bother. */ if (h->num == 0) return; /* Assign the ptrs in h->hit. */ h->hit = (struct hit_s **)MallocOrDie(h->num * sizeof(struct hit_s *)); for (i = 0; i < h->num; i++) h->hit[i] = &(h->unsrt[i]); /* Sort the pointers. Don't bother if we've only got one. */ if (h->num > 1) qsort(h->hit, h->num, sizeof(struct hit_s *), hit_comparison); } ugene-1.9.8/src/plugins_3rdparty/hmm2/src/hmmer2/altivec_algorithms.cpp0000644000175000017500000012254511651544326024642 0ustar ilyailya/***************************************************************** * Unipro UGENE - Genome analysis suite * Copyright (C) 2008 Unipro, Russia (http://ugene.unipro.ru) * All Rights Reserved * * This source code is distributed under the terms of the * GNU General Public License. See the files COPYING and LICENSE * for details. *****************************************************************/ /************************************************************ * HMMER - Biological sequence analysis with profile HMMs * Copyright (C) 1992-2003 Washington University School of Medicine * All Rights Reserved * * This source code is distributed under the terms of the * GNU General Public License. See the files COPYING and LICENSE * for details. ************************************************************/ /* fast_algorithms.c * SRE, Sun Nov 10 08:54:48 2002 [AA 3080, Denver to StL] * CVS $Id: fast_algorithms.c,v 1.1.1.1 2008/01/17 02:32:19 jizhu Exp $ * * Optimized routines to replace slower implementations in core_algorithms.c. * * The routines in core_algorithms.c are designed for clarity * and maintainability, not for speed. Implementations here * are designed for speed, not clarity. If you're trying to * understand the code, or optimize for a specific platform, * you are probably better off looking at core_algorithms.c. * * P7Viterbi() is the key function to target optimization to. * The implementation in core_algorithms.c is currently ifdef'ed * out of the code. The implementation that is used by default * is here, in fast_algorithms.c. A third implementation, from * Erik Lindahl at Stanford, is Mac/Altivec specific. * * Which implementation is used is controlled by ifdef's. The * default implementation uses a fast implementation of * P7Viterbi() from here. Other options (mutually exclusive): * * -DSLOW * enable original core_algorithms.c code: slower than default, * but might be easier to follow, for someone trying * to understand the DP code. * -DALTIVEC * enable Erik Lindahl's Altivec code for Macintosh OSX */ //#if !defined ALTIVEC && !defined SLOW #ifdef ALTIVEC #include "config.h" //#include "squidconf.h" #include "structs.h" #include "funcs.h" //#include "squid.h" #include #include #include // // /* the DEFAULT P7Viterbi() is portably optimized; code follows: // */ // // /* Function: P7Viterbi() - portably optimized version // * Incept: SRE, Fri Nov 15 13:14:33 2002 [St. Louis] // * // * Purpose: The Viterbi dynamic programming algorithm. // * Derived from core_algorithms.c:P7Viterbi(). // * // * Args: dsq - sequence in digitized form // * L - length of dsq // * hmm - the model // * mx - re-used DP matrix // * ret_tr - RETURN: traceback; pass NULL if it's not wanted // * // * Return: log P(S|M)/P(S|R), as a bit score // */ // float // P7Viterbi(unsigned char *dsq, int L, struct plan7_s *hmm, struct dpmatrix_s *mx, struct p7trace_s **ret_tr) // { // struct p7trace_s *tr; // int **xmx; // int **mmx; // int **imx; // int **dmx; // int i,k; // int sc; // int *mc, *dc, *ic; /* pointers to rows of mmx, dmx, imx */ // int *ms, *is; /* pointers to msc[i], isc[i] */ // int *mpp, *mpc, *ip; /* ptrs to mmx[i-1], mmx[i], imx[i-1] */ // int *bp; /* ptr into bsc[] */ // int *ep; /* ptr into esc[] */ // int xmb; /* value of xmx[i-1][XMB] */ // int xme; /* max for xmx[i][XME] */ // int *dpp; /* ptr into dmx[i-1] (previous row) */ // int *tpmm, *tpmi, *tpmd, *tpim, *tpii, *tpdm, *tpdd; /* ptrs into tsc */ // int M; // // /* Make sure we have space for a DP matrix with 0..L rows, 0..M-1 columns. // */ // ResizePlan7Matrix(mx, L, hmm->M, &xmx, &mmx, &imx, &dmx); // // /* Initialization of the zero row. // */ // xmx[0][XMN] = 0; /* S->N, p=1 */ // xmx[0][XMB] = hmm->xsc[XTN][MOVE]; /* S->N->B, no N-tail */ // xmx[0][XME] = xmx[0][XMC] = xmx[0][XMJ] = -INFTY; /* need seq to get here */ // for (k = 0; k <= hmm->M; k++) // mmx[0][k] = imx[0][k] = dmx[0][k] = -INFTY; /* need seq to get here */ // // /* Initializations that help icc vectorize. // */ // M = hmm->M; // // /* Recursion. Done as a pull. // * Note some slightly wasteful boundary conditions: // * tsc[0] = -INFTY for all eight transitions (no node 0) // * D_M and I_M are wastefully calculated (they don't exist) // */ // // tpmm = hmm->tsc[TMM]; // tpim = hmm->tsc[TIM]; // tpdm = hmm->tsc[TDM]; // tpmd = hmm->tsc[TMD]; // tpdd = hmm->tsc[TDD]; // tpmi = hmm->tsc[TMI]; // tpii = hmm->tsc[TII]; // bp = hmm->bsc; // for (i = 1; i <= L; i++) { // mc = mmx[i]; // dc = dmx[i]; // ic = imx[i]; // mpp = mmx[i-1]; // dpp = dmx[i-1]; // ip = imx[i-1]; // xmb = xmx[i-1][XMB]; // ms = hmm->msc[dsq[i]]; // is = hmm->isc[dsq[i]]; // mc[0] = -INFTY; // dc[0] = -INFTY; // ic[0] = -INFTY; // // for (k = 1; k <= M; k++) { // mc[k] = mpp[k-1] + tpmm[k-1]; // if ((sc = ip[k-1] + tpim[k-1]) > mc[k]) mc[k] = sc; // if ((sc = dpp[k-1] + tpdm[k-1]) > mc[k]) mc[k] = sc; // if ((sc = xmb + bp[k]) > mc[k]) mc[k] = sc; // mc[k] += ms[k]; // if (mc[k] < -INFTY) mc[k] = -INFTY; // // dc[k] = dc[k-1] + tpdd[k-1]; // if ((sc = mc[k-1] + tpmd[k-1]) > dc[k]) dc[k] = sc; // if (dc[k] < -INFTY) dc[k] = -INFTY; // // if (k < M) { // ic[k] = mpp[k] + tpmi[k]; // if ((sc = ip[k] + tpii[k]) > ic[k]) ic[k] = sc; // ic[k] += is[k]; // if (ic[k] < -INFTY) ic[k] = -INFTY; // } // } // // /* Now the special states. Order is important here. // * remember, C and J emissions are zero score by definition, // */ // /* N state */ // xmx[i][XMN] = -INFTY; // if ((sc = xmx[i-1][XMN] + hmm->xsc[XTN][LOOP]) > -INFTY) // xmx[i][XMN] = sc; // // /* E state */ // xme = -INFTY; // mpc = mmx[i]; // ep = hmm->esc; // for (k = 1; k <= hmm->M; k++) // if ((sc = mpc[k] + ep[k]) > xme) xme = sc; // xmx[i][XME] = xme; // /* J state */ // xmx[i][XMJ] = -INFTY; // if ((sc = xmx[i-1][XMJ] + hmm->xsc[XTJ][LOOP]) > -INFTY) // xmx[i][XMJ] = sc; // if ((sc = xmx[i][XME] + hmm->xsc[XTE][LOOP]) > xmx[i][XMJ]) // xmx[i][XMJ] = sc; // // /* B state */ // xmx[i][XMB] = -INFTY; // if ((sc = xmx[i][XMN] + hmm->xsc[XTN][MOVE]) > -INFTY) // xmx[i][XMB] = sc; // if ((sc = xmx[i][XMJ] + hmm->xsc[XTJ][MOVE]) > xmx[i][XMB]) // xmx[i][XMB] = sc; // // /* C state */ // xmx[i][XMC] = -INFTY; // if ((sc = xmx[i-1][XMC] + hmm->xsc[XTC][LOOP]) > -INFTY) // xmx[i][XMC] = sc; // if ((sc = xmx[i][XME] + hmm->xsc[XTE][MOVE]) > xmx[i][XMC]) // xmx[i][XMC] = sc; // } // /* T state (not stored) */ // sc = xmx[L][XMC] + hmm->xsc[XTC][MOVE]; // // if (ret_tr != NULL) { // P7ViterbiTrace(hmm, dsq, L, mx, &tr); // *ret_tr = tr; // } // // return Scorify(sc); /* the total Viterbi score. */ // } // #endif /*default P7Viterbi, used when ALTIVEC and SLOW are not defined*/ //#ifdef ALTIVEC /*################################################################ * The Altivec port, for Macintosh PowerPC. * Erik Lindahl, Stanford University, 2002. * * Replaces the following functions: * AllocPlan7Body() plan7.c (data alignment on 16-byte boundaries) * CreatePlan7Matrix() core_algorithms.c (data alignment on 16-byte boundaries) * ResizePlan7Matrix() core_algorithms.c (data alignment on 16-byte boundaries) * P7Viterbi() core_algorithms.c (total recode, w/ Altivec instructions) ################################################################*/ void AllocPlan7Body(struct plan7_s *hmm, int M) { int k, x; hmm->M = M; hmm->rf = (char *)MallocOrDie ((M+2) * sizeof(char)); hmm->cs = (char *)MallocOrDie ((M+2) * sizeof(char)); hmm->ca = (char *)MallocOrDie ((M+2) * sizeof(char)); hmm->map = (int *)MallocOrDie ((M+1) * sizeof(int)); hmm->t = (float **)MallocOrDie (M * sizeof(float *)); hmm->tsc = (int **)MallocOrDie (7 * sizeof(int *)); hmm->mat = (float **)MallocOrDie ((M+1) * sizeof(float *)); hmm->ins = (float **)MallocOrDie (M * sizeof(float *)); hmm->msc = (int **)MallocOrDie (MAXCODE * sizeof(int *)); hmm->isc = (int **)MallocOrDie (MAXCODE * sizeof(int *)); hmm->t[0] = (float *)MallocOrDie ((7*M) * sizeof(float)); /* Allocate extra memory so tsc[TMM,TIM,TDM,TMD,TDD] start on the * 16-byte cache boundary, and tsc[TMI,TII] start * 12 bytes offset from the boundary. */ //hmm->tsc_mem = MallocOrDie (((7*(M+16))) * sizeof(int)); hmm->tsc_mem = (int *)memalign(16, (((7*(M+16))) * sizeof(int))); memset( hmm->tsc_mem, 0, ((7*(M+16))) * sizeof(int) ); hmm->mat[0] = (float *)MallocOrDie ((MAXABET*(M+1)) * sizeof(float)); hmm->ins[0] = (float *)MallocOrDie ((MAXABET*M) * sizeof(float)); /* Allocate extra mem. to make sure all members of msc,isc start * on 12-byte offsets from cache boundary. */ hmm->msc_mem = (int *)memalign(128,((MAXCODE*(M+1+16)) * sizeof(int))); memset( hmm->msc_mem, 0, (MAXCODE*(M+1+16)) * sizeof(int) ); hmm->isc_mem = (int *)memalign(128,(((MAXCODE*(M+16)) * sizeof(int)))); memset( hmm->isc_mem, 0, (MAXCODE*(M+16)) * sizeof(int) ); //hmm->msc_mem = (int *)MallocOrDie((MAXCODE*(M+1+16)) * sizeof(int)); //hmm->isc_mem = (int *)MallocOrDie((MAXCODE*(M+16)) * sizeof(int)); /* note allocation strategy for important 2D arrays -- trying * to keep locality as much as possible, cache efficiency etc. */ for (k = 1; k <= M; k++) { hmm->mat[k] = hmm->mat[0] + k * MAXABET; if (k < M) { hmm->ins[k] = hmm->ins[0] + k * MAXABET; hmm->t[k] = hmm->t[0] + k * 7; } } /* align tsc pointers */ hmm->tsc[TMM] = (int *) (((((unsigned long int) hmm->tsc_mem) + 15) & (~0xf))); hmm->tsc[TMI] = (int *) (((((unsigned long int) hmm->tsc_mem) + (M+12)*sizeof(int) + 15) & (~0xf)) + 12); hmm->tsc[TMD] = (int *) (((((unsigned long int) hmm->tsc_mem) + 2*(M+12)*sizeof(int) + 15) & (~0xf))); hmm->tsc[TIM] = (int *) (((((unsigned long int) hmm->tsc_mem) + 3*(M+12)*sizeof(int) + 15) & (~0xf))); hmm->tsc[TII] = (int *) (((((unsigned long int) hmm->tsc_mem) + 4*(M+12)*sizeof(int) + 15) & (~0xf)) + 12); hmm->tsc[TDM] = (int *) (((((unsigned long int) hmm->tsc_mem) + 5*(M+12)*sizeof(int) + 15) & (~0xf))); hmm->tsc[TDD] = (int *) (((((unsigned long int) hmm->tsc_mem) + 6*(M+12)*sizeof(int) + 15) & (~0xf))); for (x = 0; x < MAXCODE; x++) { hmm->msc[x] = (int *) (((((unsigned long int)hmm->msc_mem) + x*(M+1+12)*sizeof(int) + 15) & (~0xf)) + 12); hmm->isc[x] = (int *) (((((unsigned long int)hmm->isc_mem) + x*(M+12)*sizeof(int) + 15) & (~0xf)) + 12); } /* tsc[0] is used as a boundary condition sometimes [Viterbi()], * so set to -inf always. */ for (x = 0; x < 7; x++) hmm->tsc[x][0] = -INFTY; hmm->begin = (float *)MallocOrDie ((M+1) * sizeof(float)); hmm->bsc_mem= (int *)memalign(128,((M+1+12) * sizeof(int))); memset( hmm->bsc_mem, 0, (M+1+12) * sizeof(int) ); //hmm->bsc_mem= (int *)MallocOrDie ((M+1+12) * sizeof(int)); hmm->end = (float *)MallocOrDie ((M+1) * sizeof(float)); //hmm->esc_mem= (int *)MallocOrDie ((M+1+12) * sizeof(int)); hmm->esc_mem= (int *)memalign(128, ((M+1+12) * sizeof(int))); memset( hmm->esc_mem, 0, (M+1+12) * sizeof(int) ); hmm->bsc = (int *) (((((unsigned long int) hmm->bsc_mem) + 15) & (~0xf)) + 12); hmm->esc = (int *) (((((unsigned long int) hmm->esc_mem) + 15) & (~0xf)) + 12); return; } /* Function: CreatePlan7Matrix() * * Purpose: Create a dynamic programming matrix for standard Forward, * Backward, or Viterbi, with scores kept as scaled log-odds * integers. Keeps 2D arrays compact in RAM in an attempt * to maximize cache hits. * * The mx structure can be dynamically grown, if a new * HMM or seq exceeds the currently allocated size. Dynamic * growing is more efficient than an alloc/free of a whole * matrix for every new target. The ResizePlan7Matrix() * call does this reallocation, if needed. Here, in the * creation step, we set up some pads - to inform the resizing * call how much to overallocate when it realloc's. If a pad * is zero, we will not resize in that dimension. * * Args: N - N+1 rows are allocated, for sequence. * M - size of model in nodes * padN - over-realloc in seq/row dimension, or 0 * padM - over-realloc in HMM/column dimension, or 0 * * Return: mx * mx is allocated here. Caller frees with FreePlan7Matrix(mx). */ struct dpmatrix_s * CreatePlan7Matrix(int N, int M, int padN, int padM) { struct dpmatrix_s *mx; int i,n; mx = (struct dpmatrix_s *) MallocOrDie (sizeof(struct dpmatrix_s)); mx->xmx = (int **) MallocOrDie (sizeof(int *) * (N+1)); mx->mmx = (int **) MallocOrDie (sizeof(int *) * (N+1)); mx->imx = (int **) MallocOrDie (sizeof(int *) * (N+1)); mx->dmx = (int **) MallocOrDie (sizeof(int *) * (N+1)); /* For the memory accessed by the altivec routines, we want to have * accesses aligned to 16-byte boundaries as far as possible. * To accomplish this, we align extra memory and then set the first * pointer on each row to point to 4 bytes before a boundary. * This means element 1, which is the first one we work on, will be * on a 16-byte boundary. We still make sure we 'own' the three bytes * before, though, so we can load the vector with element 0 cache-aligned too. * The real pointers to memory are kept in xmx_mem,mmx_mem,imx_mem,dmx_mem. */ mx->xmx_mem = (void *) MallocOrDie (sizeof(int) * (N+1)*(5 + 16)); mx->mmx_mem = (void *) MallocOrDie (sizeof(int) * (N+1)*(M+2+16)); mx->imx_mem = (void *) MallocOrDie (sizeof(int) * (N+1)*(M+2+16)); mx->dmx_mem = (void *) MallocOrDie (sizeof(int) * (N+1)*(M+2+16)); mx->xmx[0] = (int *) (((((unsigned long int) mx->xmx_mem) + 15) & (~0xf)) + 12); mx->mmx[0] = (int *) (((((unsigned long int) mx->mmx_mem) + 15) & (~0xf)) + 12); mx->imx[0] = (int *) (((((unsigned long int) mx->imx_mem) + 15) & (~0xf)) + 12); mx->dmx[0] = (int *) (((((unsigned long int) mx->dmx_mem) + 15) & (~0xf)) + 12); /* And make sure the beginning of each row is aligned the same way */ for (i = 1; i <= N; i++) { mx->xmx[i] = mx->xmx[0] + i*(5+11) ; /* add 11 bytes per row, making it divisible by 4 */ n = 12 - (M+2)%4; mx->mmx[i] = mx->mmx[0] + i*(M+2+n); mx->imx[i] = mx->imx[0] + i*(M+2+n); mx->dmx[i] = mx->dmx[0] + i*(M+2+n); } mx->maxN = N; mx->maxM = M; mx->padN = padN; mx->padM = padM; return mx; } struct dpmatrix_s * CreatePlan7MatrixHP(int N, int M, int padN, int padM, char* memaddr){ struct dpmatrix_s *mx; int i,n; mx = (struct dpmatrix_s *) (memaddr + 0x060000); mx->xmx = (int **) (memaddr + 0x065000); mx->mmx = (int **) (memaddr + 0x070000); mx->imx = (int **) (memaddr + 0x075000); mx->dmx = (int **) (memaddr + 0x080000); mx->xmx_mem = (void *) (memaddr + 0x100000); mx->mmx_mem = (void *) (memaddr + 0x150000); mx->imx_mem = (void *) (memaddr + 0x200000); mx->dmx_mem = (void *) (memaddr + 0x250000); mx->xmx[0] = (int *) (((((unsigned long int) mx->xmx_mem) + 15) & (~0xf)) + 12); mx->mmx[0] = (int *) (((((unsigned long int) mx->mmx_mem) + 15) & (~0xf)) + 12); mx->imx[0] = (int *) (((((unsigned long int) mx->imx_mem) + 15) & (~0xf)) + 12); mx->dmx[0] = (int *) (((((unsigned long int) mx->dmx_mem) + 15) & (~0xf)) + 12); /* And make sure the beginning of each row is aligned the same way */ for (i = 1; i <= N; i++) { mx->xmx[i] = mx->xmx[0] + i*(5+11) ; /* add 11 bytes per row, making it divisible by 4 */ n = 12 - (M+2)%4; mx->mmx[i] = mx->mmx[0] + i*(M+2+n); mx->imx[i] = mx->imx[0] + i*(M+2+n); mx->dmx[i] = mx->dmx[0] + i*(M+2+n); } mx->maxN = N; mx->maxM = M; mx->padN = padN; mx->padM = padM; return mx; } /* Function: ResizePlan7Matrix() * * Purpose: Reallocate a dynamic programming matrix, if necessary, * for a problem of NxM: sequence length N, model size M. * (N=1 for small memory score-only variants; we allocate * N+1 rows in the DP matrix.) * * See additional comments in * core_algorithms.c:ResizePlan7Matrix(), the normal version * of this function. This version is only used in the * Altivec (--enable-altivec) port. * * Returns individual ptrs to the four matrix components * as a convenience. * * Args: mx - an already allocated model to grow. * N - seq length to allocate for; N+1 rows * M - size of model * xmx, mmx, imx, dmx * - RETURN: ptrs to four mx components as a convenience * * Return: (void) * mx is (re)allocated here. */ void ResizePlan7Matrix(struct dpmatrix_s *mx, int N, int M, int ***xmx, int ***mmx, int ***imx, int ***dmx) { int i,n; if (N <= mx->maxN && M <= mx->maxM) { if (xmx != NULL) *xmx = mx->xmx; if (mmx != NULL) *mmx = mx->mmx; if (imx != NULL) *imx = mx->imx; if (dmx != NULL) *dmx = mx->dmx; return; } if (N > mx->maxN) { N += mx->padN; mx->maxN = N; mx->xmx = (int **) ReallocOrDie (mx->xmx, sizeof(int *) * (mx->maxN+1)); mx->mmx = (int **) ReallocOrDie (mx->mmx, sizeof(int *) * (mx->maxN+1)); mx->imx = (int **) ReallocOrDie (mx->imx, sizeof(int *) * (mx->maxN+1)); mx->dmx = (int **) ReallocOrDie (mx->dmx, sizeof(int *) * (mx->maxN+1)); } if (M > mx->maxM) { M += mx->padM; mx->maxM = M; } mx->xmx_mem = ReallocOrDie (mx->xmx_mem, sizeof(int) * (mx->maxN+1)*(5 + 16)); mx->mmx_mem = ReallocOrDie (mx->mmx_mem, sizeof(int) * (mx->maxN+1)*(mx->maxM+2+16)); mx->imx_mem = ReallocOrDie (mx->imx_mem, sizeof(int) * (mx->maxN+1)*(mx->maxM+2+16)); mx->dmx_mem = ReallocOrDie (mx->dmx_mem, sizeof(int) * (mx->maxN+1)*(mx->maxM+2+16)); mx->xmx[0] = (int *) (((((unsigned long int) mx->xmx_mem) + 15) & (~0xf)) + 12); mx->mmx[0] = (int *) (((((unsigned long int) mx->mmx_mem) + 15) & (~0xf)) + 12); mx->imx[0] = (int *) (((((unsigned long int) mx->imx_mem) + 15) & (~0xf)) + 12); mx->dmx[0] = (int *) (((((unsigned long int) mx->dmx_mem) + 15) & (~0xf)) + 12); /* And make sure the beginning of each row is aligned the same way */ for (i = 1; i <= mx->maxN; i++) { mx->xmx[i] = mx->xmx[0] + i*(5+11) ; /* add 11 bytes per row, making it divisible by 4 */ n = 12 - (mx->maxM+2)%4; mx->mmx[i] = mx->mmx[0] + i*(mx->maxM+2+n); mx->imx[i] = mx->imx[0] + i*(mx->maxM+2+n); mx->dmx[i] = mx->dmx[0] + i*(mx->maxM+2+n); } if (xmx != NULL) *xmx = mx->xmx; if (mmx != NULL) *mmx = mx->mmx; if (imx != NULL) *imx = mx->imx; if (dmx != NULL) *dmx = mx->dmx; } /* Function: P7Viterbi() * * Purpose: The Viterbi dynamic programming algorithm; Altivec implementation * by Erik Lindahl, Stanford University, 2002. * * Args: dsq - sequence in digitized form * L - length of dsq * hmm - the model * mx - DP matrix (may get grown here) * ret_tr - RETURN: traceback; pass NULL if it's not wanted * * Return: log P(S|M)/P(S|R), as a bit score */ /* This first version of P7Viterbi has been accelerated with Altivec vectorization. * On Apple hardware, it is up to a factor 10 faster than the old non-altivec version. */ typedef union { vector signed int v; int i[4]; } ivector; void printivec(vector signed int z) { ivector q; q.v=z; printf("%d %d %d %d\n",q.i[0],q.i[1],q.i[2],q.i[3]); } float P7Viterbi(unsigned char *dsq, int L, struct plan7_s *hmm, struct dpmatrix_s *mx, struct p7trace_s **ret_tr) { struct p7trace_s *tr; int **xmx; int **mmx; int **imx; int **dmx; int *mmxi,*xmxi,*imxi,*dmxi; int *lmmxi,*lxmxi,*limxi,*ldmxi; int *p_tmm,*p_tim,*p_tdm,*p_bsc,*p_msc,*p_tmd,*p_tdd,*p_tmi,*p_tii,*p_isc,*p_esc; int i,n,k; int sc; /* gcc and motorola use different syntax for initializing vectors, * so we use a dummy variable instead to get an adress to load from... */ int t_lowscore = -INFTY; /* vector variables. We avoid the stupid gcc register spill/fill code by * limiting ourselves to 32 generic variables and making the all registers. * (This reuse is the reason for the generic variable names). */ register vector signed int v_lowscore; register vector signed int max_mmxesc; register vector signed int v_xmb; register vector unsigned int mask1; register vector unsigned int mask2; register vector unsigned int mask3; register vector unsigned int mask4; register vector signed int v_lmmx1; register vector signed int v_lmmx2; register vector signed int v_limx1; register vector signed int v_limx2; register vector signed int v_save_lmmx; register vector signed int v_save_ldmx; register vector signed int v_save_limx; register vector signed int v_save_mmx; register vector signed int v_save_dmx; register vector signed int v1; register vector signed int v2; register vector signed int v3; register vector signed int v4; register vector signed int v5; register vector signed int v6; register vector signed int v7; register vector signed int v8; register vector signed int v9; register vector signed int v10; register vector signed int v11; register vector signed int v12; register vector signed int v13; register vector signed int v14; register vector signed int v15; /* load (-infinity) to all four elements in v_lowscore */ v_lowscore = vec_lde(0, &t_lowscore ); mask1 = (vector unsigned int)vec_lvsl(0,&t_lowscore); v_lowscore = vec_perm(v_lowscore,v_lowscore,(vector unsigned char)mask1); v_lowscore = vec_splat(v_lowscore,0); v1 = vec_splat_s32(-1); v2 = vec_splat_s32(0); mask1 = (vector unsigned int)vec_sld(v1,v2,12); /* FF in first pos, rest. are 00 */ mask2 = vec_sld(mask1,mask1,12); mask3 = vec_sld(mask1,mask1,8); mask4 = vec_sld(mask1,mask1,4); /* Make sure our DP matrix has 0..L rows, 0..M columns; grow it if needed. */ ResizePlan7Matrix(mx, L, hmm->M, &xmx, &mmx, &imx, &dmx); /* Initialization of the zero row. */ xmx[0][XMN] = 0; /* S->N, p=1 */ xmx[0][XMB] = hmm->xsc[XTN][MOVE]; /* S->N->B, no N-tail */ xmx[0][XME] = xmx[0][XMC] = xmx[0][XMJ] = -INFTY; /* need seq to get here */ mmxi=mmx[0]; imxi=imx[0]; dmxi=dmx[0]; xmxi=xmx[0]; for (n = 0; n < 5+hmm->M; n+=4) { vec_st(v_lowscore, n*4, mmxi); vec_st(v_lowscore, n*4, imxi); vec_st(v_lowscore, n*4, dmxi); } /* Fill data beyound M with -INFTY, so we can take the maximum including * elements with k>M. */ for(k=1+hmm->M;k<=(3+hmm->M);k++) { hmm->esc[k]=-INFTY; hmm->bsc[k]=-INFTY; for(i=0;i<7;i++) hmm->tsc[i][k]=-INFTY; for(i=0;imsc[i][k]=-INFTY; hmm->isc[i][k]=-INFTY; } } /* Recursion. Done as a pull * Note some slightly wasteful boundary conditions: * tsc[0] = -INFTY for all eight transitions (no node 0) * D_M and I_M are wastefully calculated (they don't exist) */ for (i = 1; i <= L; i++) { /* pointers to last (i-1) row */ lmmxi=mmxi; limxi=imxi; ldmxi=dmxi; lxmxi=xmxi; /* get pointers to this row */ mmxi=mmx[i]; imxi=imx[i]; dmxi=dmx[i]; xmxi=xmx[i]; /* Set everything that doesnt depend on k here */ /* load and splat (spread to all elements) XMX[i-1][XMB] */ v13 = vec_lde(0,&(xmx[i-1][XMB])); v14 = (vector signed int)vec_lvsl(0,&(xmx[i-1][XMB])); v13 = vec_perm(v13,v13,(vector unsigned char)v14); v_xmb = vec_splat(v13,0); p_tmm = hmm->tsc[TMM]; p_tim = hmm->tsc[TIM]; p_tdm = hmm->tsc[TDM]; p_bsc = hmm->bsc; k = dsq[i]; p_msc = hmm->msc[k]; p_isc = hmm->isc[k]; p_tmd = hmm->tsc[TMD]; p_tdd = hmm->tsc[TDD]; p_tmi = hmm->tsc[TMI]; p_tii = hmm->tsc[TII]; p_esc = hmm->esc; max_mmxesc = v_lowscore; /* the 0 element of vectors are aligned 12 bytes up from the 16-byte boundary, * so we simply write the entire 16 bytes before the 16 byte boundary. */ vec_st(v_lowscore,0,mmxi); vec_st(v_lowscore,0,imxi); vec_st(v_lowscore,0,dmxi); /* Load the first (i.e. 'previous') vector on last row for mmx,imx,dmx, * and load the first vector of dmx and mmx on this row. */ v_save_lmmx = vec_ld(-12, lmmxi); v_save_limx = vec_ld(-12, limxi); v_save_ldmx = vec_ld(-12, ldmxi); v_save_mmx = vec_ld(-12, mmxi); v_save_dmx = vec_ld(-12, dmxi); /* we have allocated extra memory, so it is perfectly OK * to do the calculations for a couple of extra cells where * k>hmm->M. These cells just wont be used. */ for (n = 4, k=1; k < (hmm->M-3) ; n+=32, k+=8) { /* match state */ /* 1: check which of mmx[i-1][k-1]+TMM and imx[i-1][k-1]+TIM is better, * but do it for 8 elements in parallel. * Since we are comparing with data on the previous row but one position * earlier, we have to shift stuff. Load two new vectors each round, * and use the saved register from last round. */ /* load mmx data */ v_lmmx1 = vec_ld(n, lmmxi); v_lmmx2 = vec_ld(n+16, lmmxi); /* load imx data */ v_limx1 = vec_ld(n, limxi); v_limx2 = vec_ld(n+16, limxi); v5 = vec_ld(n, ldmxi); /* Load dmx data */ v10 = vec_ld(n+16, ldmxi); /* shift mmx, imx & dmx data */ v1 = vec_sld(v_save_lmmx,v_lmmx1,12); v3 = vec_sld(v_save_limx,v_limx1,12); v9 = vec_sld(v_save_ldmx,v5,12); /* shift mmx, imx & dmx data */ v2 = vec_sld(v_lmmx1,v_lmmx2,12); v4 = vec_sld(v_limx1,v_limx2,12); v_save_ldmx = v10; v10 = vec_sld(v5,v10,12); v_save_lmmx = v_lmmx2; v_save_limx = v_limx2; /* v1,v2 now contains 8 element with mmx[i-1][k-1], * v3,v4 contain 8 elements with imx[i-1][k-1], * and v9,v10 contain 8 elements with dmx[i-1][k-1]. */ /* load TMM, TIM & TDM entries from the HMM - these are aligned in memory */ v5 = vec_ld(n-4, p_tmm); v6 = vec_ld(n+12, p_tmm); v7 = vec_ld(n-4, p_tim); v8 = vec_ld(n+12, p_tim); v11 = vec_ld(n-4, p_tdm); v12 = vec_ld(n+12, p_tdm); /* load bsc[k] */ v14 = vec_ld(n, p_bsc); v15 = vec_ld(n+16, p_bsc); /* calc mmx+TMM, imx+TIM, dmx+TDM and XMX+bsc with saturated arithmetic, so * we don't loop if we add the large negative numbers used for -infinity. */ v1 = vec_adds(v1,v5); v2 = vec_adds(v2,v6); v3 = vec_adds(v3,v7); v4 = vec_adds(v4,v8); v9 = vec_adds(v9,v11); v10 = vec_adds(v10,v12); v14 = vec_adds(v14,v_xmb); v15 = vec_adds(v15,v_xmb); /* Select max of mmx+TMM and imx+TIM in each element */ v1 = vec_max(v1,v3); v2 = vec_max(v2,v4); /* select max of dmx+TDM and XMX+bsc */ v9 = vec_max(v9,v14); v10 = vec_max(v10,v15); /* select max of the four alternatives */ v1 = vec_max(v1,v9); v2 = vec_max(v2,v10); /* v1,v2 now contain the max values for the new mmx; * check if we should add msc. */ //printf("L=%d M=%d n=%d k=%d i=%d dsq[i]=%d p_msc=hmm->msc[dsq[i]]=%d hmm->msc[dsq[i]]=%d\n", // L,hmm->M,n,k,i,dsq[i],p_msc,hmm->msc[dsq[i]]); v3 = vec_ld(n, p_msc); v4 = vec_ld(n+16, p_msc); v5 = (vector signed int)vec_cmpgt(v3,v_lowscore); v6 = (vector signed int)vec_cmpgt(v4,v_lowscore); /* load esc[k] */ v9 = vec_ld(n, p_esc); v10 = vec_ld(n+16, p_esc); v1 = vec_adds(v1,v3); v2 = vec_adds(v2,v4); v1 = vec_sel(v3,v1,(vector unsigned int)v5); v2 = vec_sel(v4,v2,(vector unsigned int)v6); /* have final values for mmx on this row in v1,v2 - store it */ vec_st(v1, n, mmxi); vec_st(v2, n+16, mmxi); v9 = vec_adds(v9,v1); v10 = vec_adds(v10,v2); v9 = vec_max(v9,v10); max_mmxesc = vec_max(v9,max_mmxesc); /* OK. We finished the match state. Normally we could now first * do the delete and then the insertion. The problem is that the * delete is a pain in the ass to vectorize, since each element * depends on the previous one in the vector. This means I have * to write this relatively simple operation as eight independent * ones, just as we would have done in a non-vectorized code. * Since this is independent of the insertion state changes, I * try to hide the latencies by doing the delete and insert * calculations in parallel. * To make things easier I add 'del' in a comment on each * line for calculations that are on the delete state, and 'ins' * for the calculations for the insertion. Hang on... */ /* We already have the match data on this row from the previous * iteration in v_save_mmx. Rotate it so the element that used to be * is pos 4 last iteration is in position 1, and pos 2-4 contain * the the first three elements of mmx this iteration. * And do the same type of rotation for v1/v2... */ v4 = vec_sld(v1,v2,12); /* del */ v3 = vec_sld(v_save_mmx,v1,12); /* del */ v_save_mmx = v2; /* Save for next iteration */ /* Rotate last dmx data so we have the fourth element in pos 1. */ v_save_dmx = vec_sld(v_save_dmx,v_save_dmx,12); /* del */ /* load TMD & TDD data */ v5 = vec_ld(n-4, p_tmd); /* del */ v6 = vec_ld(n+12, p_tmd); /* del */ v7 = vec_ld(n-4, p_tdd); /* del */ v8 = vec_ld(n+12, p_tdd); /* del */ /* calculate mmx+TMD */ v3 = vec_adds(v3,v5); /* del */ v4 = vec_adds(v4,v6); /* del */ /* Start the ugly stuff. We have rotated last dmx data. Add TDD to * it and compare with v3/v4 (data from mmx+TMD alternative), but * we only compare & replace the first position, so we use a mask! */ /* First position: Add TDD to v_save_dmx */ v_save_dmx = vec_adds(v_save_dmx,v7); /* del */ /* Select max of this and mmx+TMD and save it temporary to v_save_dmx */ v_save_dmx = vec_max(v_save_dmx,v3); /* del */ /* use a mask to select only the first element from v_save_dmx, rest from v3. */ v3 = vec_sel(v3,v_save_dmx,mask1); /* del */ /* Start doing the insertion calculations in parallel. * Load the TMI data. */ v9 = vec_ld(n , p_tmi); /* ins */ v10 = vec_ld(n+16, p_tmi); /* ins */ /* Deletion: * Now we have an accurate pos 1 in v3. continue with pos2 the same * way. Rotate to a temporary array, add to TDD, compare and use a mask * to write back to only position 2. */ v_save_dmx = vec_sld(v3,v3,12); /* del */ v_save_dmx = vec_adds(v_save_dmx,v7); /* del */ v_save_dmx = vec_max(v_save_dmx,v3); /* del */ v3 = vec_sel(v3,v_save_dmx,mask2); /* del */ /* More insertion stuff - load TII data */ v11 = vec_ld(n , p_tii); /* ins */ v12 = vec_ld(n+16, p_tii); /* ins */ /* Deletion, position 3... */ v_save_dmx = vec_sld(v3,v3,12); /* del */ v_save_dmx = vec_adds(v_save_dmx,v7); /* del */ v_save_dmx = vec_max(v_save_dmx,v3); /* del */ v3 = vec_sel(v3,v_save_dmx,mask3); /* del */ /* insertion stuff: calculate mmx+TMI */ v9 = vec_adds(v_lmmx1,v9); /* ins */ v10 = vec_adds(v_lmmx2,v10); /* ins */ /* Deletion, position 4 */ v_save_dmx = vec_sld(v3,v3,12); /* del */ v_save_dmx = vec_adds(v_save_dmx,v7); /* del */ v_save_dmx = vec_max(v_save_dmx,v3); /* del */ v3 = vec_sel(v3,v_save_dmx,mask4); /* del */ /* insertion stuff: calculate imx+TII */ v11 = vec_adds(v_limx1,v11); /* ins */ v12 = vec_adds(v_limx2,v12); /* ins */ /* That was the first deletion vector, but we are unrolling. * The next step is position '5', i.e. the first in vector 2. * This one depends on the last position of vector 1, which we just finished. */ v_save_dmx = vec_sld(v3,v3,12); /* del */ v_save_dmx = vec_adds(v_save_dmx,v8); /* del */ v_save_dmx = vec_max(v_save_dmx,v4); /* del */ v4 = vec_sel(v4,v_save_dmx,mask1); /* del */ /* insertion stuff: select max of mmx+TMI and imx+TII */ v9 = vec_max(v9,v11); /* ins */ v10 = vec_max(v10,v12); /* ins */ /* insertion stuff: load data from hmm->isc[tmpidx] */ v11 = vec_ld(n, p_isc); /* ins */ v12 = vec_ld(n+16, p_isc); /* ins */ /* position 6 (2 in vector 2) */ v_save_dmx = vec_sld(v4,v4,12); /* del */ v_save_dmx = vec_adds(v_save_dmx,v8); /* del */ v_save_dmx = vec_max(v_save_dmx,v4); /* del */ v4 = vec_sel(v4,v_save_dmx,mask2); /* del */ /* insertion: compare max of mmx+TMI, imx+TII with hmm->isc */ v13 = (vector signed int)vec_cmpgt(v11,v_lowscore); v14 = (vector signed int)vec_cmpgt(v12,v_lowscore); /* position 7 (3 in vector 2) */ v_save_dmx = vec_sld(v4,v4,12); /* del */ v_save_dmx = vec_adds(v_save_dmx,v8); /* del */ v_save_dmx = vec_max(v_save_dmx,v4); /* del */ v4 = vec_sel(v4,v_save_dmx,mask3); /* del */ v9 = vec_adds(v9,v11); v10 = vec_adds(v10,v12); v9 = vec_sel(v11,v9,(vector unsigned int)v13); v10 = vec_sel(v12,v10,(vector unsigned int)v14); /* position 8 (4 in vector 2) */ v_save_dmx = vec_sld(v4,v4,12); /* del */ v_save_dmx = vec_adds(v_save_dmx,v8); /* del */ v_save_dmx = vec_max(v_save_dmx,v4); /* del */ v_save_dmx = vec_sel(v4,v_save_dmx,mask4); /* del */ /* Puh! that was the deletion... v3/v_save_dmx now contain the updated dmx data; * save it to memory. (v_save_dmx will be used next iteration) */ vec_st(v3, n, dmxi); /* del */ vec_st(v_save_dmx, n+16, dmxi); /* del */ /* save insertion too */ vec_st(v9, n, imxi); vec_st(v10,n+16,imxi); } /* odd loop */ if(k< (1+hmm->M)) { /* match state */ /* 1: check which of mmx[i-1][k-1]+TMM and imx[i-1][k-1]+TIM is better, * but do it for 4 elements in parallel. * Since we are comparing with data on the previous row but one position * earlier, we have to shift stuff. Load two new vectors each round, * and use the saved register from last round. */ /* load mmx data */ v_lmmx1 = vec_ld(n, lmmxi); /* load imx data */ v_limx1 = vec_ld(n, limxi); v5 = vec_ld(n, ldmxi); /* Load dmx data */ /* shift mmx, imx & dmx data */ v1 = vec_sld(v_save_lmmx,v_lmmx1,12); v3 = vec_sld(v_save_limx,v_limx1,12); v9 = vec_sld(v_save_ldmx,v5,12); /* v1,v2 now contains 8 element with mmx[i-1][k-1], * v3,v4 contain 8 elements with imx[i-1][k-1], * and v9,v10 contain 8 elements with dmx[i-1][k-1]. */ /* load TMM, TIM & TDM entries from the HMM - these are aligned in memory */ v5 = vec_ld(n-4, p_tmm); v7 = vec_ld(n-4, p_tim); v11 = vec_ld(n-4, p_tdm); /* load bsc[k] */ v14 = vec_ld(n, p_bsc); /* calc mmx+TMM, imx+TIM, dmx+TDM and XMX+bsc with saturated arithmetic, so * we don't loop if we add the large negative numbers used for -infinity. */ v1 = vec_adds(v1,v5); v3 = vec_adds(v3,v7); v9 = vec_adds(v9,v11); v14 = vec_adds(v14,v_xmb); /* Select max of mmx+TMM and imx+TIM in each element */ v1 = vec_max(v1,v3); /* select max of dmx+TDM and XMX+bsc */ v9 = vec_max(v9,v14); /* select max of the four alternatives */ v1 = vec_max(v1,v9); /* v1,v2 now contain the max values for the new mmx; * check if we should add msc. */ v3 = vec_ld(n, p_msc); v5 = (vector signed int)vec_cmpgt(v3,v_lowscore); /* load esc[k] */ v9 = vec_ld(n, p_esc); v1 = vec_adds(v1,v3); v1 = vec_sel(v3,v1,(vector unsigned int)v5); /* have final values for mmx on this row in v1,v2 - store it */ vec_st(v1, n, mmxi); v9 = vec_adds(v9,v1); max_mmxesc = vec_max(v9,max_mmxesc); /* OK. We finished the match state. Normally we could now first * do the delete and then the insertion. The problem is that the * delete is a pain in the ass to vectorize, since each element * depends on the previous one in the vector. This means I have * to write this relatively simple operation as eight independent * ones, just as we would have done in a non-vectorized code. * Since this is independent of the insertion state changes, I * try to hide the latencies by doing the delete and insert * calculations in parallel. * To make things easier I add 'del' in a comment on each * line for calculations that are on the delete state, and 'ins' * for the calculations for the insertion. Hang on... */ /* We already have the match data on this row from the previous * iteration in v_save_mmx. Rotate it so the element that used to be * is pos 4 last iteration is in position 1, and pos 2-4 contain * the the first three elements of mmx this iteration. * And do the same type of rotation for v1/v2... */ v3 = vec_sld(v_save_mmx,v1,12); /* del */ /* Rotate last dmx data so we have the fourth element in pos 1. */ v_save_dmx = vec_sld(v_save_dmx,v_save_dmx,12); /* del */ /* load TMD & TDD data */ v5 = vec_ld(n-4, p_tmd); /* del */ v7 = vec_ld(n-4, p_tdd); /* del */ /* calculate mmx+TMD */ v3 = vec_adds(v3,v5); /* del */ /* Start the ugly stuff. We have rotated last dmx data. Add TDD to * it and compare with v3/v4 (data from mmx+TMD alternative), but * we only compare & replace the first position, so we use a mask! */ /* First position: Add TDD to v_save_dmx */ v_save_dmx = vec_adds(v_save_dmx,v7); /* del */ /* Select max of this and mmx+TMD and save it temporary to v_save_dmx */ v_save_dmx = vec_max(v_save_dmx,v3); /* del */ /* use a mask to select only the first element from v_save_dmx, rest from v3. */ v3 = vec_sel(v3,v_save_dmx,mask1); /* del */ /* Start doing the insertion calculations in parallel. * Load the TMI data. */ v9 = vec_ld(n , p_tmi); /* ins */ /* Deletion: * Now we have an accurate pos 1 in v3. continue with pos2 the same * way. Rotate to a temporary array, add to TDD, compare and use a mask * to write back to only position 2. */ v_save_dmx = vec_sld(v3,v3,12); /* del */ v_save_dmx = vec_adds(v_save_dmx,v7); /* del */ v_save_dmx = vec_max(v_save_dmx,v3); /* del */ v3 = vec_sel(v3,v_save_dmx,mask2); /* del */ /* More insertion stuff - load TII data */ v11 = vec_ld(n , p_tii); /* ins */ /* Deletion, position 3... */ v_save_dmx = vec_sld(v3,v3,12); /* del */ v_save_dmx = vec_adds(v_save_dmx,v7); /* del */ v_save_dmx = vec_max(v_save_dmx,v3); /* del */ v3 = vec_sel(v3,v_save_dmx,mask3); /* del */ /* insertion stuff: calculate mmx+TMI */ v9 = vec_adds(v_lmmx1,v9); /* ins */ /* Deletion, position 4 */ v_save_dmx = vec_sld(v3,v3,12); /* del */ v_save_dmx = vec_adds(v_save_dmx,v7); /* del */ v_save_dmx = vec_max(v_save_dmx,v3); /* del */ v3 = vec_sel(v3,v_save_dmx,mask4); /* del */ /* insertion stuff: calculate imx+TII */ v11 = vec_adds(v_limx1,v11); /* ins */ /* insertion stuff: select max of mmx+TMI and imx+TII */ v9 = vec_max(v9,v11); /* ins */ /* insertion stuff: load data from hmm->isc[tmpidx] */ v11 = vec_ld(n, p_isc); /* ins */ /* insertion: compare max of mmx+TMI, imx+TII with hmm->isc */ v13 = (vector signed int)vec_cmpgt(v11,v_lowscore); v9 = vec_adds(v9,v11); v9 = vec_sel(v11,v9,(vector unsigned int)v13); /* Puh! that was the deletion... v3/v_save_dmx now contain the updated dmx data; * save it to memory. (v_save_dmx will be used next iteration) */ vec_st(v3, n, dmxi); /* del */ /* save insertion too */ vec_st(v9, n, imxi); } /* end of k loops */ /* Now the special states. Order is important here. * remember, C and J emissions are zero score by definition, */ /* N state */ xmx[i][XMN] = -INFTY; if ((sc = xmx[i-1][XMN] + hmm->xsc[XTN][LOOP]) > -INFTY) xmx[i][XMN] = sc; /* E state */ v2 = vec_sld(max_mmxesc,max_mmxesc,8); v2 = vec_max(v2,max_mmxesc); v1 = vec_sld(v2,v2,4); v1 = vec_max(v1,v2); vec_ste(v1,XME*4,xmxi); /* J state */ xmxi[XMJ] = -INFTY; if ((sc = lxmxi[XMJ] + hmm->xsc[XTJ][LOOP]) > -INFTY) xmxi[XMJ] = sc; if ((sc = xmxi[XME] + hmm->xsc[XTE][LOOP]) > xmxi[XMJ]) xmxi[XMJ] = sc; /* B state */ xmxi[XMB] = -INFTY; if ((sc = xmxi[XMN] + hmm->xsc[XTN][MOVE]) > -INFTY) xmxi[XMB] = sc; if ((sc = xmxi[XMJ] + hmm->xsc[XTJ][MOVE]) > xmxi[XMB]) xmxi[XMB] = sc; /* C state */ xmxi[XMC] = -INFTY; if ((sc = lxmxi[XMC] + hmm->xsc[XTC][LOOP]) > -INFTY) xmxi[XMC] = sc; if ((sc = xmxi[XME] + hmm->xsc[XTE][MOVE]) > xmxi[XMC]) xmxi[XMC] = sc; } /* T state (not stored) */ sc = xmx[L][XMC] + hmm->xsc[XTC][MOVE]; if (ret_tr != NULL) { P7ViterbiTrace(hmm, dsq, L, mx, &tr); *ret_tr = tr; } /* Note (Lindahl): we do NOT free the dpmatrix here anymore - the code was * spending 30% of the runtime allocating/freeing memory. * Provide a pointer to a dpmatrix_s structure to this routine, * and we try to reuse it. After the final call to P7Viterbi, * free it with FreePlan7Matrix. */ return Scorify(sc); /* the total Viterbi score. */ } #endif /*the ALTIVEC port*/ ugene-1.9.8/src/plugins_3rdparty/hmm2/src/hmmer2/structs.h0000644000175000017500000007214011651544326022131 0ustar ilyailya/************************************************************ * HMMER - Biological sequence analysis with profile HMMs * Copyright (C) 1992-2003 Washington University School of Medicine * All Rights Reserved * * This source code is distributed under the terms of the * GNU General Public License. See the files COPYING and LICENSE * for details. ************************************************************/ /* structs.h * * Data structures used in HMMER. * Also, a few miscellaneous macros and global variable declarations. * * RCS $Id: structs.h,v 1.28 2003/10/01 13:06:05 eddy Exp $ */ #ifndef STRUCTSH_INCLUDED #define STRUCTSH_INCLUDED #include "config.h" /********************************************************************** * * Plan7 * Implementation of the new Plan7 HMM architecture. * Fully probabilistic even for hmmsw, hmmls, and hmmfs; * No insert->delete or delete->insert transitions; * Improved structure layout. * * The strategy is to infiltrate plan7 code into HMMER in * an evolutionary rather than revolutionary manner. * **********************************************************************/ /* Plan 7 construction strategies. */ enum p7_construction { P7_MAP_CONSTRUCTION, /* maximum a posteriori architecture */ P7_HAND_CONSTRUCTION, /* hand specified architecture */ P7_FAST_CONSTRUCTION /* fast ad hoc architecture */ }; /* Plan 7 parameter optimization strategies */ enum p7_param { P7_MAP_PARAM, /* standard maximum a posteriori */ P7_MD_PARAM, /* maximum discrimination */ P7_MRE_PARAM, /* maximum relative entropy */ P7_WMAP_PARAM /* ad hoc weighted MAP */ }; /* Structure: plan7_s * * Declaration of a Plan 7 profile-HMM. */ struct plan7_s { /* Annotation on the model. A name is mandatory. * Other fields are optional; whether they are present is * flagged in the stateflags bit array. * * desc is only valid if PLAN7_DESC is set in flags. * acc is only valid if PLAN7_ACC is set in flags. * rf is only valid if PLAN7_RF is set in flags. * cs is only valid if PLAN7_CS is set in flags. * ca is only valid if PLAN7_CA is set in flags. * map is only valid if PLAN7_MAP is set in flags. */ char *name; /* name of the model +*/ char *acc; /* accession number of model (Pfam) +*/ char *desc; /* brief description of model +*/ char *rf; /* reference line from alignment 0..M +*/ char *cs; /* consensus structure line 0..M +*/ char *ca; /* consensus accessibility line 0..M */ char *comlog; /* command line(s) that built model +*/ int nseq; /* number of training sequences +*/ char *ctime; /* creation date +*/ int *map; /* map of alignment cols onto model 1..M+*/ int checksum; /* checksum of training sequences +*/ /* The following are annotations added to support work by Michael Asman, * CGR Stockholm. They are not stored in model files; they are only * used in model construction. * * #=GC X-PRM (PRT,PRI) annotation is picked up by hmmbuild and interpreted * as specifying which mixture Dirichlet component to use. If these flags * are non-NULL, the normal mixture Dirichlet code is bypassed, and a * single specific Dirichlet is used at each position. */ int *tpri; /* which transition mixture prior to use */ int *mpri; /* which match mixture prior to use */ int *ipri; /* which insert mixture prior to use */ /* Pfam-specific score cutoffs. * * ga1, ga2 are valid if PLAN7_GA is set in flags. * tc1, tc2 are valid if PLAN7_TC is set in flags. * nc1, nc2 are valid if PLAN7_NC is set in flags. */ float ga1, ga2; /* per-seq/per-domain gathering thresholds (bits) +*/ float tc1, tc2; /* per-seq/per-domain trusted cutoff (bits) +*/ float nc1, nc2; /* per-seq/per-domain noise cutoff (bits) +*/ /* The main model in probability form: data-dependent probabilities. * This is the core Krogh/Haussler model. * Transition probabilities are usually accessed as a * two-D array: hmm->t[k][TMM], for instance. They are allocated * such that they can also be stepped through in 1D by pointer * manipulations, for efficiency in DP algorithms. */ int M; /* length of the model (# nodes) +*/ float **t; /* transition prob's. t[1..M-1][0..6] +*/ float **mat; /* match emissions. mat[1..M][0..19] +*/ float **ins; /* insert emissions. ins[1..M-1][0..19] +*/ float tbd1; /* B->D1 prob (data dependent) +*/ /* The unique states of Plan 7 in probability form. * These are the algorithm-dependent, data-independent probabilities. * Some parts of the code may briefly use a trick of copying tbd1 * into begin[0]; this makes it easy to call FChoose() or FNorm() * on the resulting vector. However, in general begin[0] is not * a valid number. */ float xt[4][2]; /* N,E,C,J extra states: 2 transitions +*/ float *begin; /* 1..M B->M state transitions +*/ float *end; /* 1..M M->E state transitions (!= a dist!) +*/ /* The null model probabilities. */ float null[MAXABET]; /* "random sequence" emission prob's +*/ float p1; /* null model loop probability +*/ /* The model in log-odds score form. * These are created from the probabilities by LogoddsifyHMM(). * By definition, null[] emission scores are all zero. * Note that emission distributions are over 26 upper-case letters, * not just the unambiguous protein or DNA alphabet: we * precalculate the scores for all IUPAC degenerate symbols we * may see. Non-IUPAC symbols simply have a -INFTY score. * * Note the reversed indexing on msc, isc, tsc -- for efficiency reasons. * They're not probability vectors any more so we can reorder them * without wildly complicating our life. * * The _mem ptrs are where the real memory is alloc'ed and free'd, * as opposed to where it is accessed. * This came in with Erik Lindahl's altivec port; it allows alignment on * 16-byte boundaries. In the non-altivec code, this is just a little * redundancy; tsc and tsc_mem point to the same thing, for example. * * Only valid if PLAN7_HASBITS is set. */ int **tsc; /* transition scores [0.6][1.M-1] -*/ int **msc; /* match emission scores [0.MAXCODE-1][1.M] -*/ int **isc; /* ins emission scores [0.MAXCODE-1][1.M-1] -*/ int xsc[4][2]; /* N,E,C,J transitions -*/ int *bsc; /* begin transitions [1.M] -*/ int *esc; /* end transitions [1.M] -*/ int *tsc_mem, *msc_mem, *isc_mem, *bsc_mem, *esc_mem; /* DNA translation scoring parameters * For aligning protein Plan7 models to DNA sequence. * Lookup value for a codon is calculated by pos1 * 16 + pos2 * 4 + pos3, * where 'pos1' is the digitized value of the first nucleotide position; * if any of the positions are ambiguous codes, lookup value 64 is used * (which will generally have a score of zero) * * Only valid if PLAN7_HASDNA is set. */ int **dnam; /* triplet match scores [0.64][1.M] -*/ int **dnai; /* triplet insert scores [0.64][1.M] -*/ int dna2; /* -1 frameshift, doublet emission, M or I -*/ int dna4; /* +1 frameshift, doublet emission, M or I -*/ /* P-value and E-value statistical parameters * Only valid if PLAN7_STATS is set. */ float mu; /* EVD mu +*/ float lambda; /* EVD lambda +*/ int flags; // bit flags indicating state of HMM, valid data int atype; // alphabet type }; /* Flags for plan7->flags. * Note: Some models have scores but no probabilities (for instance, * after reading from an HMM save file). Other models have * probabilities but no scores (for instance, during training * or building). Since it costs time to convert either way, * I use PLAN7_HASBITS and PLAN7_HASPROB flags to defer conversion * until absolutely necessary. This means I have to be careful * about keeping these flags set properly when I fiddle a model. */ #define PLAN7_HASBITS (1<<0) /* raised if model has log-odds scores */ #define PLAN7_DESC (1<<1) /* raised if description exists */ #define PLAN7_RF (1<<2) /* raised if #RF annotation available */ #define PLAN7_CS (1<<3) /* raised if #CS annotation available */ #define PLAN7_XRAY (1<<4) /* raised if structural data available */ #define PLAN7_HASPROB (1<<5) /* raised if model has probabilities */ #define PLAN7_HASDNA (1<<6) /* raised if protein HMM->DNA seq params set*/ #define PLAN7_STATS (1<<7) /* raised if EVD parameters are available */ #define PLAN7_MAP (1<<8) /* raised if alignment map is available */ #define PLAN7_ACC (1<<9) /* raised if accession number is available */ #define PLAN7_GA (1<<10) /* raised if gathering thresholds available */ #define PLAN7_TC (1<<11) /* raised if trusted cutoffs available */ #define PLAN7_NC (1<<12) /* raised if noise cutoffs available */ #define PLAN7_CA (1<<13) /* raised if surface accessibility avail. */ /* Indices for special state types, I: used for dynamic programming xmx[][] * mnemonic: eXtra Matrix for B state = XMB */ #define XMB 0 #define XME 1 #define XMC 2 #define XMJ 3 #define XMN 4 /* Indices for special state types, II: used for hmm->xt[] indexing * mnemonic: eXtra Transition for N state = XTN */ #define XTN 0 #define XTE 1 #define XTC 2 #define XTJ 3 /* Indices for Plan7 main model state transitions. * Used for indexing hmm->t[k][] * mnemonic: Transition from Match to Match = TMM */ #define TMM 0 #define TMI 1 #define TMD 2 #define TIM 3 #define TII 4 #define TDM 5 #define TDD 6 /* Indices for extra state transitions * Used for indexing hmm->xt[][]. */ #define MOVE 0 /* trNB, trEC, trCT, trJB */ #define LOOP 1 /* trNN, trEJ, trCC, trJJ */ /* Declaration of Plan7 dynamic programming matrix structure. */ struct dpmatrix_s { int **xmx; /* special scores [0.1..N][BECJN] */ int **mmx; /* match scores [0.1..N][0.1..M] */ int **imx; /* insert scores [0.1..N][0.1..M-1.M] */ int **dmx; /* delete scores [0.1..N][0.1..M-1.M] */ /* Hidden ptrs where the real memory is kept; this trick was * introduced by Erik Lindahl with the Altivec port; it's used to * align xmx, etc. on 16-byte boundaries for cache optimization. */ void *xmx_mem, *mmx_mem, *imx_mem, *dmx_mem; /* The other trick brought in w/ the Lindahl Altivec port; dp matrix * is retained and grown, rather than ReallocOrDieated for every HMM or sequence. * Keep track of current allocated-for size in rows (sequence length N) * and columns (HMM length M). Also keep track of pad sizes: how much * we should overallocate rows or columns when we ReallocOrDieate. If pad = 0, * then we're not growable in this dimension. */ int maxN; /* alloc'ed for seq of length N; N+1 rows */ int maxM; /* alloc'ed for HMM of length M; M+1 cols */ int padN; /* extra pad in sequence length/rows */ int padM; /* extra pad in HMM length/columns */ }; /* Declaration of Plan7 shadow matrix structure. * In general, allowed values are STM, STI, etc. * However, E state has M possible sources, from 1..M match states; * hence the esrc array. */ struct dpshadow_s { char **xtb; /* special state traces [0.1..N][BECJN] */ char **mtb; /* match state traces [0.1..N][0.1..M] */ char **itb; /* insert state traces [0.1..N][0.1..M-1.M] */ char **dtb; /* delete state traces [0.1..N][0.1..M-1.M] */ int *esrc; /* E trace is special; must store a M state number 1..M */ }; /* Plan 7 model state types * used in traceback structure */ #define STBOGUS 0 #define STM 1 #define STD 2 #define STI 3 #define STS 4 #define STN 5 #define STB 6 #define STE 7 #define STC 8 #define STT 9 #define STJ 10 /* Structure: p7trace_s * * Traceback structure for alignments of model to sequence. * Each array in a trace_s is 0..tlen-1. * Element 0 is always to STATE_S. Element tlen-1 is always to STATE_T. */ struct p7trace_s { int tlen; /* length of traceback */ char *statetype; /* state type used for alignment */ int *nodeidx; /* index of aligned node, 1..M (if M,D,I), or 0 */ int *pos; /* position in dsq, 1..L, or 0 if none */ }; /********************************************************************** * Other structures, not having to do with HMMs. **********************************************************************/ /* Structure: histogram_s * * Keep a score histogram. * * The main implementation issue here is that the range of * scores is unknown, and will go negative. histogram is * a 0..max-min array that represents the range min..max. * A given score is indexed in histogram array as score-min. * The AddToHistogram() function deals with dynamically * resizing the histogram array when necessary. */ struct histogram_s { int *histogram; /* counts of hits */ int min; /* elem 0 of histogram == min */ int max; /* last elem of histogram == max */ int highscore; /* highest active elem has this score */ int lowscore; /* lowest active elem has this score */ int lumpsize; /* when resizing, overalloc by this */ int total; /* total # of hits counted */ float *expect; /* expected counts of hits */ int fit_type; /* flag indicating distribution type */ float param[3]; /* parameters used for fits */ float chisq; /* chi-squared val for goodness of fit*/ float chip; /* P value for chisquared */ }; #define HISTFIT_NONE 0 /* no fit done yet */ #define HISTFIT_EVD 1 /* fit type = extreme value dist */ #define HISTFIT_GAUSSIAN 2 /* fit type = Gaussian */ #define EVD_MU 0 /* EVD fit parameter mu */ #define EVD_LAMBDA 1 /* EVD fit parameter lambda */ #define EVD_WONKA 2 /* EVD fit fudge factor */ #define GAUSS_MEAN 0 /* Gaussian parameter mean */ #define GAUSS_SD 1 /* Gaussian parameter std. dev. */ /* Structure: fancyali_s * * Alignment of a hit to an HMM, for printing. */ struct fancyali_s { char *rfline; /* reference coord info */ char *csline; /* consensus structure info */ char *model; /* aligned query consensus sequence */ char *mline; /* "identities", conservation +'s, etc. */ char *aseq; /* aligned target sequence */ int len; /* length of strings */ char *query; /* name of query HMM */ char *target; /* name of target sequence */ int sqfrom; /* start position on sequence (1..L) */ int sqto; /* end position on sequence (1..L) */ }; /* Structure: hit_s * * Info about a high-scoring database hit. * We keep this info in memory, so we can output a * sorted list of high hits at the end. * * sqfrom and sqto are the coordinates that will be shown * in the results, not coords in arrays... therefore, reverse * complements have sqfrom > sqto */ struct hit_s { double sortkey; /* number to sort by; big is better */ float score; /* score of the hit */ double pvalue; /* P-value of the hit */ float mothersc; /* score of whole sequence */ double motherp; /* P-value of whole sequence */ char *name; /* name of the target */ char *acc; /* accession of the target */ char *desc; /* description of the target */ int sqfrom; /* start position in seq (1..N) */ int sqto; /* end position in seq (1..N) */ int sqlen; /* length of sequence (N) */ int hmmfrom; /* start position in HMM (1..M) */ int hmmto; /* end position in HMM (1..M) */ int hmmlen; /* length of HMM (M) */ int domidx; /* index of this domain */ int ndom; /* total # of domains in this seq */ struct fancyali_s *ali; /* ptr to optional alignment info */ }; /* Structure: tophit_s * * Array of high scoring hits, suitable for efficient sorting * when we prepare to output results. "hit" list is NULL and * unavailable until after we do a sort. */ struct tophit_s { struct hit_s **hit; /* array of ptrs to top scoring hits */ struct hit_s *unsrt; /* unsorted array */ int alloc; /* current allocation size */ int num; /* number of hits in list now */ int lump; /* allocation lumpsize */ }; /* struct threshold_s * Contains score/evalue threshold settings. * * made first for hmmpfam: * Since we're going to loop over all HMMs in a Pfam (or pfam-like) * database in main_loop_{serial,pvm}, and we're going to * allow autocutoffs using Pfam GA, NC, TC lines, we will need * to reset those cutoffs with each HMM in turn. Therefore the * main loops need to know whether they're supposed to be * doing autocutoff. This amount of info was unwieldy enough * to pass through the argument list that I put it * in a structure. */ enum CUT{ CUT_NONE, CUT_GA, CUT_NC, CUT_TC }; struct threshold_s { float globT; /* T parameter: keep only hits > globT bits */ double globE; /* E parameter: keep hits < globE E-value */ float domT; /* T parameter for individual domains */ double domE; /* E parameter for individual domains */ /* autosetting of cutoffs using Pfam annot: */ CUT autocut; int Z; /* nseq to base E value calculation on */ }; /**************************************************** * Single sequence information ****************************************************/ #define SQINFO_NAMELEN 64 #define SQINFO_DESCLEN 128 struct seqinfo_s { int flags; /* what extra data are available */ char name[SQINFO_NAMELEN];/* up to 63 characters of name */ char id[SQINFO_NAMELEN]; /* up to 63 char of database identifier */ char acc[SQINFO_NAMELEN]; /* up to 63 char of database accession # */ char desc[SQINFO_DESCLEN];/* up to 127 char of description */ int len; /* length of this seq */ int start; /* (1..len) start position on source seq */ int stop; /* (1..len) end position on source seq */ int olen; /* original length of source seq */ int type; /* kRNA, kDNA, kAmino, or kOther */ char *ss; /* 0..len-1 secondary structure string */ char *sa; /* 0..len-1 % side chain surface access. */ }; typedef struct seqinfo_s SQINFO; #define SQINFO_NAME (1 << 0) #define SQINFO_ID (1 << 1) #define SQINFO_ACC (1 << 2) #define SQINFO_DESC (1 << 3) #define SQINFO_START (1 << 4) #define SQINFO_STOP (1 << 5) #define SQINFO_LEN (1 << 6) #define SQINFO_TYPE (1 << 7) #define SQINFO_OLEN (1 << 8) #define SQINFO_SS (1 << 9) #define SQINFO_SA (1 << 10) //alphabet #define NUCLEOTIDES "ACGTUNRYMKSWHBVDacgtunrymkswhbvd" #define AMINO_ALPHABET "ACDEFGHIKLMNPQRSTVWY" #define DNA_ALPHABET "ACGT" #define RNA_ALPHABET "ACGU" #define WHITESPACE " \t\n" /* an idiom for determining a symbol's position in the array * by pointer arithmetic. * does no error checking, so caller must already be damned sure x is * valid in the alphabet! */ #define SYMIDX(al, x) (strchr(al->Alphabet, (x)) - al->Alphabet) /* The symbol alphabet. * Must deal with IUPAC degeneracies. Nondegenerate symbols * come first in Alphabet[], followed by degenerate symbols. * Nucleic alphabet also must deal with other common symbols * like U (in RNA) and X (often misused for N). * Example: * Nucleic: "ACGTUNRYMKSWHBVDX" size=4 iupac=17 * Amino: "ACDEFGHIKLMNPQRSTVWYBZX" size=20 iupac=23 * * Parts of the code assume that the last symbol is a * symbol for an unknown residue, i.e. 'X'. * * MAXCODE and MAXABET constants are defined in config.h */ #define hmmNOTSETYET 0 #define hmmNUCLEIC 2 /* compatibility with squid's kRNA */ #define hmmAMINO 3 /* compatibility with squid's kAmino */ struct alphabet_s { int Alphabet_type; /* hmmNUCLEIC or hmmAMINO */ int Alphabet_size; /* uniq alphabet size: 4 or 20 */ int Alphabet_iupac; /* total size of alphabet + IUPAC degen. */ char Alphabet[MAXCODE+1]; /* ACGT, for instance */ char Degenerate[MAXCODE][MAXABET]; /* 1/0 arrays, for whether IUPAC code includes a residue */ int DegenCount[MAXCODE]; alphabet_s(); }; /**************************************************** * Cluster analysis and phylogenetic tree support ****************************************************/ /* struct phylo_s - a phylogenetic tree * * For N sequences, there will generally be an array of 0..N-2 * phylo_s structures representing the nodes of a tree. * [0] is the root. The indexes of left and * right children are somewhat confusing so be careful. The * indexes can have values of 0..2N-2. If they are 0..N-1, they * represent pointers to individual sequences. If they are * >= N, they represent pointers to a phylo_s structure * at (index - N). */ struct phylo_s { int parent; /* index of parent, N..2N-2, or -1 for root */ int left; /* index of one of the branches, 0..2N-2 */ int right; /* index of other branch, 0..2N-2 */ float diff; /* difference score between seqs */ float lblen; /* left branch length */ float rblen; /* right branch length */ char *is_in; /* 0..N-1 flag array, 1 if seq included */ int incnum; /* number of seqs included at this node */ }; enum clust_strategy { CLUSTER_MEAN, CLUSTER_MAX, CLUSTER_MIN }; /* Strategies for cluster analysis; cluster by mean distance, * minimum distance, or maximum distance. */ /* Binary encoding of the IUPAC code for nucleotides * * four-bit "word", permitting rapid degenerate matching * A C G T/U * 0 0 1 0 */ #define NTA 8 #define NTC 4 #define NTG 2 #define NTT 1 #define NTU 1 #define NTN 15 /* A|C|G|T */ #define NTR 10 /* A|G */ #define NTY 5 /* C|T */ #define NTM 12 /* A|C */ #define NTK 3 /* G|T */ #define NTS 6 /* C|G */ #define NTW 9 /* A|T */ #define NTH 13 /* A|C|T */ #define NTB 7 /* C|G|T */ #define NTV 14 /* A|C|G */ #define NTD 11 /* A|G|T */ #define NTGAP 16 /* GAP */ #define NTEND 0 /* null string terminator */ /**************************************************** * Sequence alphabet: see also iupac.c ****************************************************/ /* IUPAC symbols defined globally in iupac.c */ struct iupactype { iupactype(char _sym, char _symcomp, char _code, char _comp): sym(_sym), symcomp(_symcomp), code(_code), comp(_comp) {} char sym; /* character representation */ char symcomp; /* complement (regular char */ char code; /* my binary rep */ char comp; /* binary encoded complement */ }; extern struct iupactype iupac[]; extern float dnafq[]; /* nucleotide occurrence frequencies */ extern float aafq[]; /* amino acid occurrence frequencies */ #define SQDCONST_E 2.71828182845904523536028747135 #define SQDCONST_PI 3.14159265358979323846264338328 /* must declare swapfoo to use SWAP() */ #define SWAP(a,b) {swapfoo = b; b = a; a = swapfoo;} #define ScalarsEqual(a,b) (fabs((a)-(b)) < 1e-7) #ifndef MIN #define MIN(a,b) (((a)<(b))?(a):(b)) #endif #ifndef MAX #define MAX(a,b) (((a)>(b))?(a):(b)) #endif #define isgap(c) ((c) == ' ' || (c) == '.' || (c) == '_' || (c) == '-' || (c) == '~') /* For convenience and (one hopes) clarity in boolean tests: */ #ifndef TRUE #define TRUE 1 #endif #ifndef FALSE #define FALSE 0 #endif /* The following constants define the Pfam/Rfam cutoff set we'll propagate * from msa's into HMMER and Infernal models. */ #define MSA_CUTOFF_TC1 0 #define MSA_CUTOFF_TC2 1 #define MSA_CUTOFF_GA1 2 #define MSA_CUTOFF_GA2 3 #define MSA_CUTOFF_NC1 4 #define MSA_CUTOFF_NC2 5 #define MSA_MAXCUTOFFS 6 /* Structure: MSA * SRE, Tue May 18 11:33:08 1999 * * Our object for a multiple sequence alignment. */ typedef struct msa_struct { /* Mandatory information associated with the alignment. */ char **aseq; /* the alignment itself, [0..nseq-1][0..alen-1] */ char **sqname; /* names of sequences, [0..nseq-1][0..alen-1] */ float *wgt; /* sequence weights [0..nseq-1] */ int alen; /* length of alignment (columns) */ int nseq; /* number of seqs in alignment */ /* Optional information that we understand, and might have. */ int flags; /* flags for what optional info is valid */ int type; /* kOtherSeq, kRNA/hmmNUCLEIC, or kAmino/hmmAMINO */ char *name; /* name of alignment, or NULL */ char *desc; /* description of alignment, or NULL */ char *acc; /* accession of alignment, or NULL */ char *au; /* "author" information, or NULL */ char *ss_cons; /* consensus secondary structure string, or NULL */ char *sa_cons; /* consensus surface accessibility string, or NULL */ char *rf; /* reference coordinate system, or NULL */ char **sqacc; /* accession numbers for individual sequences */ char **sqdesc; /* description lines for individual sequences */ char **ss; /* per-seq secondary structure annotation, or NULL */ char **sa; /* per-seq surface accessibility annotation, or NULL */ float cutoff[MSA_MAXCUTOFFS]; /* NC, TC, GA cutoffs propagated to Pfam/Rfam */ int cutoff_is_set[MSA_MAXCUTOFFS];/* TRUE if a cutoff is set; else FALSE */ } MSA; #define MSA_SET_WGT (1 << 0) /* track whether wgts were set, or left at default 1.0 */ /* Structure: p7prior_s * * Dirichlet priors on HMM parameters. */ struct p7prior_s { int strategy; /* PRI_DCHLET, etc. */ int tnum; /* number of transition Dirichlet mixtures */ float tq[MAXDCHLET]; /* probabilities of tnum components */ float t[MAXDCHLET][7]; /* transition terms per mix component */ int mnum; /* number of mat emission Dirichlet mixtures */ float mq[MAXDCHLET]; /* probabilities of mnum components */ float m[MAXDCHLET][MAXABET]; /* match emission terms per mix component */ int inum; /* number of insert emission Dirichlet mixes */ float iq[MAXDCHLET]; /* probabilities of inum components */ float i[MAXDCHLET][MAXABET]; /* insert emission terms */ }; #define PRI_DCHLET 0 /* simple or mixture Dirichlets */ #define PRI_PAM 1 /* PAM prior hack */ struct HMMException { HMMException(const char *err); char error[1024]; }; struct HMMERTaskLocalData { // alphabet_s al; //sre_random int sre_randseed; long rnd1; /* random number from LCG1 */ long rnd2; /* random number from LCG2 */ long rnd; /* random number we return */ long tbl[64]; /* table for Bays/Durham shuffle */ //prob2ascii char buffer[8]; //Gaussrandom long i; double snorm,u,s,ustar,aa,w,y,tt; // HMMERTaskLocalData(); }; #endif /* STRUCTSH_INCLUDED */ ugene-1.9.8/src/plugins_3rdparty/hmm2/src/hmmer2/checksum.cpp0000644000175000017500000000352611651544326022561 0ustar ilyailya/***************************************************************** * HMMER - Biological sequence analysis with profile HMMs * Copyright (C) 1992-2003 Washington University School of Medicine * All Rights Reserved * * This source code is distributed under the terms of the * GNU General Public License. See the files COPYING and LICENSE * for details. *****************************************************************/ #include "funcs.h" /* Function: GCGchecksum() * Date: SRE, Mon May 31 11:13:21 1999 [St. Louis] * * Purpose: Calculate a GCG checksum for a sequence. * Code provided by Steve Smith of Genetics * Computer Group. * * Args: seq - sequence to calculate checksum for. * may contain gap symbols. * len - length of sequence (usually known, * so save a strlen() call) * * Returns: GCG checksum. */ int GCGchecksum(char *seq, int len) { int i; /* position in sequence */ int chk = 0; /* calculated checksum */ for (i = 0; i < len; i++) chk = (chk + (i % 57 + 1) * (sre_toupper((int) seq[i]))) % 10000; return chk; } /* Function: GCGMultchecksum() * * Purpose: GCG checksum for a multiple alignment: sum of * individual sequence checksums (including their * gap characters) modulo 10000. * * Implemented using spec provided by Steve Smith of * Genetics Computer Group. * * Args: seqs - sequences to be checksummed; aligned or not * nseq - number of sequences * * Return: the checksum, a number between 0 and 9999 */ int GCGMultchecksum(char **seqs, int nseq) { int chk = 0; int idx; for (idx = 0; idx < nseq; idx++) chk = (chk + GCGchecksum(seqs[idx], strlen(seqs[idx]))) % 10000; return chk; } ugene-1.9.8/src/plugins_3rdparty/hmm2/src/hmmer2/cluster.cpp0000644000175000017500000003416411651544326022442 0ustar ilyailya/***************************************************************** * HMMER - Biological sequence analysis with profile HMMs * Copyright (C) 1992-2003 Washington University School of Medicine * All Rights Reserved * * This source code is distributed under the terms of the * GNU General Public License. See the files COPYING and LICENSE * for details. *****************************************************************/ /* cluster.c * SRE, Sun Jul 18 09:49:47 1993 * moved to squid Thu Mar 3 08:42:57 1994 * CVS $Id: cluster.c,v 1.4 2003/04/14 16:00:16 eddy Exp $ * * almost identical to bord.c, from fd * also now contains routines for constructing difference matrices * from alignments * * "branch ordering": Input a symmetric or upper-right-diagonal * NxN difference matrix (usually constructed by pairwise alignment * and similarity calculations for N sequences). Use the simple * cluster analysis part of the Fitch/Margoliash tree-building algorithm * (as described by Fitch and Margoliash 1967 as well as Feng * and Doolittle 1987) to calculate the topology of an "evolutionary * tree" consistent with the difference matrix. Returns an array * which represents the tree. * * The input difference matrix is just an NxN matrix of floats. * A good match is a small difference score (the algorithm is going * to search for minima among the difference scores). The original difference * matrix remains unchanged by the calculations. * * The output requires some explanation. A phylogenetic * tree is a binary tree, with N "leaves" and N-1 "nodes". The * topology of the tree may be completely described by N-1 structures * containing two pointers; each pointer points to either a leaf * or another node. Here, this is implemented with integer indices * rather than pointers. An array of N-1 pairs of ints is returned. * If the index is in the range (0..N-1), it is a "leaf" -- the * number of one of the sequences. If the index is in the range * (N..2N-2), it is another "node" -- (index-N) is the index * of the node in the returned array. * * If both indices of a member of the returned array point to * nodes, the tree is "compound": composed of more than one * cluster of related sequences. * * The higher-numbered elements of the returned array were the * first constructed, and hence represent the distal tips * of the tree -- the most similar sequences. The root * is node 0. ****************************************************************** * * Algorithm * * INITIALIZATIONS: * - copy the difference matrix (otherwise the caller's copy would * get destroyed by the operations of this algorithm). If * it's asymmetric, make it symmetric. * - make a (0..N-1) array of ints to keep track of the indices in * the difference matrix as they get swapped around. Initialize * this matrix to 0..N-1. * - make a (0..N-2) array of int[2] to store the results (the tree * topology). Doesn't need to be initialized. * - keep track of a "N'", the current size of the difference * matrix being operated on. * * PROCESSING THE DIFFERENCE MATRIX: * - for N' = N down to N' = 2 (N-1 steps): * - in the half-diagonal N'xN' matrix, find the indices i,j at which * there's the minimum difference score * * Store the results: * - at position N'-2 of the result array, store coords[i] and * coords[j]. * * Move i,j rows, cols to the outside edges of the matrix: * - swap row i and row N'-2 * - swap row j and row N'-1 * - swap column i and column N'-2 * - swap column j and column N'-1 * - swap indices i, N'-2 in the index array * - swap indices j, N'-1 in the index array * * Build a average difference score for differences to i,j: * - for all columns, find avg difference between rows i and j and store in row i: * row[i][col] = (row[i][col] + row[j][col]) / 2.0 * - copy the contents of row i to column i (it's a symmetric * matrix, no need to recalculate) * - store an index N'+N-2 at position N'-2 of the index array: means * that this row/column is now a node rather than a leaf, and * contains minimum values * * Continue: * - go to the next N' * * GARBAGE COLLECTION & RETURN. * ********************************************************************** * * References: * * Feng D-F and R.F. Doolittle. "Progressive sequence alignment as a * prerequisite to correct phylogenetic trees." J. Mol. Evol. * 25:351-360, 1987. * * Fitch W.M. and Margoliash E. "Construction of phylogenetic trees." * Science 155:279-284, 1967. * ********************************************************************** * * SRE, 18 March 1992 (bord.c) * SRE, Sun Jul 18 09:52:14 1993 (cluster.c) * added to squid Thu Mar 3 09:13:56 1994 ********************************************************************** * Mon May 4 09:47:02 1992: keep track of difference scores at each node */ #include "funcs.h" /* Function: Cluster() * * Purpose: Cluster analysis on a distance matrix. Constructs a * phylogenetic tree which contains the topology * and info for each node: branch lengths, how many * sequences are included under the node, and which * sequences are included under the node. * * Args: dmx - the NxN distance matrix ( >= 0.0, larger means more diverged) * N - size of mx (number of sequences) * mode - CLUSTER_MEAN, CLUSTER_MAX, or CLUSTER_MIN * ret_tree- RETURN: the tree * * Return: 1 on success, 0 on failure. * The caller is responsible for freeing the tree's memory, * by calling FreePhylo(tree, N). */ int Cluster(float **dmx, int N, enum clust_strategy mode, struct phylo_s **ret_tree) { struct phylo_s *tree; /* (0..N-2) phylogenetic tree */ float **mx; /* copy of difference matrix */ int *coord; /* (0..N-1), indices for matrix coords */ int i, j; /* coords of minimum difference */ int idx; /* counter over seqs */ int Np; /* N', a working copy of N */ int row, col; /* loop variables */ float min; /* best minimum score found */ float *trow; /* tmp pointer for swapping rows */ float tcol; /* tmp storage for swapping cols */ float *diff; /* (0..N-2) difference scores at nodes */ int swapfoo; /* for SWAP() macro */ /************************** * Initializations. **************************/ /* We destroy the matrix we work on, so make a copy of dmx. */ mx = (float**)MallocOrDie(sizeof(float *) * N); for (i = 0; i < N; i++) { mx[i] = (float*)MallocOrDie(sizeof(float) * N); for (j = 0; j < N; j++) mx[i][j] = dmx[i][j]; } /* coord array alloc, (0..N-1) */ coord = (int*)MallocOrDie(N * sizeof(int)); diff = (float*)MallocOrDie((N-1) * sizeof(float)); /* init the coord array to 0..N-1 */ for (col = 0; col < N; col++) coord[col] = col; for (i = 0; i < N-1; i++) diff[i] = 0.0; /* tree array alloc, (0..N-2) */ if ((tree = AllocPhylo(N)) == NULL) Die("AllocPhylo() failed"); /********************************* * Process the difference matrix *********************************/ /* N-prime, for an NxN down to a 2x2 diffmx */ j= 0; /* just to silence gcc uninit warnings */ for (Np = N; Np >= 2; Np--) { /* find a minimum on the N'xN' matrix*/ min = 999999.; for (row = 0; row < Np; row++) for (col = row+1; col < Np; col++) if (mx[row][col] < min) { min = mx[row][col]; i = row; j = col; } /* We're clustering row i with col j. write necessary * data into a node on the tree */ /* topology info */ tree[Np-2].left = coord[i]; tree[Np-2].right = coord[j]; if (coord[i] >= N) tree[coord[i]-N].parent = N + Np - 2; if (coord[j] >= N) tree[coord[j]-N].parent = N + Np - 2; /* keep score info */ diff[Np-2] = tree[Np-2].diff = min; /* way-simple branch length estimation */ tree[Np-2].lblen = tree[Np-2].rblen = min; if (coord[i] >= N) tree[Np-2].lblen -= diff[coord[i]-N]; if (coord[j] >= N) tree[Np-2].rblen -= diff[coord[j]-N]; /* number seqs included at node */ if (coord[i] < N) { tree[Np-2].incnum ++; tree[Np-2].is_in[coord[i]] = 1; } else { tree[Np-2].incnum += tree[coord[i]-N].incnum; for (idx = 0; idx < N; idx++) tree[Np-2].is_in[idx] |= tree[coord[i]-N].is_in[idx]; } if (coord[j] < N) { tree[Np-2].incnum ++; tree[Np-2].is_in[coord[j]] = 1; } else { tree[Np-2].incnum += tree[coord[j]-N].incnum; for (idx = 0; idx < N; idx++) tree[Np-2].is_in[idx] |= tree[coord[j]-N].is_in[idx]; } /* Now build a new matrix, by merging row i with row j and * column i with column j; see Fitch and Margoliash */ /* Row and column swapping. */ /* watch out for swapping i, j away: */ if (i == Np-1 || j == Np-2) SWAP(i,j); if (i != Np-2) { /* swap row i, row N'-2 */ trow = mx[Np-2]; mx[Np-2] = mx[i]; mx[i] = trow; /* swap col i, col N'-2 */ for (row = 0; row < Np; row++) { tcol = mx[row][Np-2]; mx[row][Np-2] = mx[row][i]; mx[row][i] = tcol; } /* swap coord i, coord N'-2 */ SWAP(coord[i], coord[Np-2]); } if (j != Np-1) { /* swap row j, row N'-1 */ trow = mx[Np-1]; mx[Np-1] = mx[j]; mx[j] = trow; /* swap col j, col N'-1 */ for (row = 0; row < Np; row++) { tcol = mx[row][Np-1]; mx[row][Np-1] = mx[row][j]; mx[row][j] = tcol; } /* swap coord j, coord N'-1 */ SWAP(coord[j], coord[Np-1]); } /* average i and j together; they're now at Np-2 and Np-1 though */ i = Np-2; j = Np-1; /* merge by saving avg of cols of row i and row j */ for (col = 0; col < Np; col++) { switch (mode) { case CLUSTER_MEAN: mx[i][col] =(mx[i][col]+ mx[j][col]) / 2.0; break; case CLUSTER_MIN: mx[i][col] = MIN(mx[i][col], mx[j][col]); break; case CLUSTER_MAX: mx[i][col] = MAX(mx[i][col], mx[j][col]); break; default: mx[i][col] =(mx[i][col]+ mx[j][col]) / 2.0; break; } } /* copy those rows to columns */ for (col = 0; col < Np; col++) mx[col][i] = mx[i][col]; /* store the node index in coords */ coord[Np-2] = Np+N-2; } /************************** * Garbage collection and return **************************/ Free2DArray((void **) mx, N); free(coord); free(diff); *ret_tree = tree; return 1; } /* Function: AllocPhylo() * * Purpose: Allocate space for a phylo_s array. N-1 structures * are allocated, one for each node; in each node, a 0..N * is_in flag array is also allocated and initialized to * all zeros. * * Args: N - size; number of sequences being clustered * * Return: pointer to the allocated array * */ struct phylo_s * AllocPhylo(int N) { struct phylo_s *tree; int i; if ((tree = (struct phylo_s *) MallocOrDie ((N-1) * sizeof(struct phylo_s))) == NULL) return NULL; for (i = 0; i < N-1; i++) { tree[i].diff = 0.0; tree[i].lblen = tree[i].rblen = 0.0; tree[i].left = tree[i].right = tree[i].parent = -1; tree[i].incnum = 0; if ((tree[i].is_in = (char *) calloc (N, sizeof(char))) == NULL) return NULL; } return tree; } /* Function: FreePhylo() * * Purpose: Free a clustree array that was built to cluster N sequences. * * Args: tree - phylogenetic tree to free * N - size of clustree; number of sequences it clustered * * Return: (void) */ void FreePhylo(struct phylo_s *tree, int N) { int idx; for (idx = 0; idx < N-1; idx++) free(tree[idx].is_in); free(tree); } /* Function: MakeDiffMx() * * Purpose: Given a set of aligned sequences, construct * an NxN fractional difference matrix. (i.e. 1.0 is * completely different, 0.0 is exactly identical). * * Args: aseqs - flushed, aligned sequences * num - number of aseqs * ret_dmx - RETURN: difference matrix * * Return: 1 on success, 0 on failure. * Caller must free diff matrix with FMX2Free(dmx) */ void MakeDiffMx(char **aseqs, int num, float ***ret_dmx) { float **dmx; /* RETURN: distance matrix */ int i,j; /* counters over sequences */ /* Allocate 2D float matrix */ dmx = FMX2Alloc(num, num); /* Calculate distances; symmetric matrix * record difference, not identity (1 - identity) */ for (i = 0; i < num; i++) for (j = i; j < num; j++) dmx[i][j] = dmx[j][i] = 1.0 - PairwiseIdentity(aseqs[i], aseqs[j]); *ret_dmx = dmx; return; } /* Function: MakeIdentityMx() * * Purpose: Given a set of aligned sequences, construct * an NxN fractional identity matrix. (i.e. 1.0 is * completely identical, 0.0 is completely different). * Virtually identical to MakeDiffMx(). It's * less confusing to have two distinct functions, I find. * * Args: aseqs - flushed, aligned sequences * num - number of aseqs * ret_imx - RETURN: identity matrix (caller must free) * * Return: 1 on success, 0 on failure. * Caller must free imx using FMX2Free(imx) */ void MakeIdentityMx(char **aseqs, int num, float ***ret_imx) { float **imx; /* RETURN: identity matrix */ int i,j; /* counters over sequences */ /* Allocate 2D float matrix */ imx = FMX2Alloc(num, num); /* Calculate distances, symmetric matrix */ for (i = 0; i < num; i++) for (j = i; j < num; j++) imx[i][j] = imx[j][i] = PairwiseIdentity(aseqs[i], aseqs[j]); *ret_imx = imx; return; } ugene-1.9.8/src/plugins_3rdparty/hmm2/src/hmmer2/prior.cpp0000644000175000017500000004336511651544326022117 0ustar ilyailya/***************************************************************** * HMMER - Biological sequence analysis with profile HMMs * Copyright (C) 1992-2003 Washington University School of Medicine * All Rights Reserved * * This source code is distributed under the terms of the * GNU General Public License. See the files COPYING and LICENSE * for details. *****************************************************************/ /* prior.c * SRE, Mon Nov 18 15:44:08 1996 * * Support for Dirichlet prior data structure, p7prior_s. */ #include "funcs.h" static struct p7prior_s *default_amino_prior(void); static struct p7prior_s *default_nucleic_prior(); /* Function: P7AllocPrior(), P7FreePrior() * * Purpose: Allocation and free'ing of a prior structure. * Very simple, but might get more complex someday. */ struct p7prior_s * P7AllocPrior(void) { return (struct p7prior_s *) MallocOrDie (sizeof(struct p7prior_s)); } void P7FreePrior(struct p7prior_s *pri) { free(pri); } /* Function: P7LaplacePrior() * * Purpose: Create a Laplace plus-one prior. (single component Dirichlets). * Global alphabet info is assumed to have been set already. * * Args: (void) * * Return: prior. Allocated here; call FreePrior() to free it. */ struct p7prior_s * P7LaplacePrior(void) { //get HMMERTaskLocalData HMMERTaskLocalData *tld = getHMMERTaskLocalData(); alphabet_s *al = &tld->al; struct p7prior_s *pri; pri = P7AllocPrior(); pri->strategy = PRI_DCHLET; pri->tnum = 1; pri->tq[0] = 1.; FSet(pri->t[0], 8, 1.); pri->mnum = 1; pri->mq[0] = 1.; FSet(pri->m[0], al->Alphabet_size, 1.); pri->inum = 1; pri->iq[0] = 1.; FSet(pri->i[0], al->Alphabet_size, 1.); return pri; } /* Function: P7DefaultPrior() * * Purpose: Set up a somewhat more realistic single component * Dirichlet prior than Laplace. */ struct p7prior_s * P7DefaultPrior(void) { //get HMMERTaskLocalData HMMERTaskLocalData *tld = getHMMERTaskLocalData(); alphabet_s *al = &tld->al; switch (al->Alphabet_type) { case hmmAMINO: return default_amino_prior(); case hmmNUCLEIC: return default_nucleic_prior(); case hmmNOTSETYET: Die("Can't set prior; alphabet type not set yet"); } /*NOTREACHED*/ return NULL; } /* Function: P7DefaultNullModel() * * Purpose: Set up a default random sequence model, using * global aafq[]'s for protein or 1/Alphabet_size for anything * else. randomseq is alloc'ed in caller. Alphabet information * must already be known. */ void P7DefaultNullModel(float *null, float *ret_p1) { //get HMMERTaskLocalData HMMERTaskLocalData *tld = getHMMERTaskLocalData(); alphabet_s *al = &tld->al; int x; if (al->Alphabet_type == hmmAMINO) { for (x = 0; x < al->Alphabet_size; x++) null[x] = aafq[x]; *ret_p1 = 350./351.; /* rationale: approx avg protein length. */ } else { for (x = 0; x < al->Alphabet_size; x++) null[x] = 1.0 / (float) al->Alphabet_size; *ret_p1 = 1000./1001.; /* rationale: approx inter-Alu distance. */ } } /* Function: P7PriorifyHMM() * * Purpose: Add pseudocounts to an HMM using Dirichlet priors, * and renormalize the HMM. * * Args: hmm -- the HMM to add counts to (counts form) * pri -- the Dirichlet prior to use * * Return: (void) * HMM returns in probability form. */ void P7PriorifyHMM(struct plan7_s *hmm, struct p7prior_s *pri) { int k; /* counter for model position */ float d; /* a denominator */ float tq[MAXDCHLET]; /* prior distribution over mixtures */ float mq[MAXDCHLET]; /* prior distribution over mixtures */ float iq[MAXDCHLET]; /* prior distribution over mixtures */ /* Model-dependent transitions are handled simply; Laplace. */ FSet(hmm->begin+2, hmm->M-1, 0.); /* wipe internal BM entries */ FSet(hmm->end+1, hmm->M-1, 0.); /* wipe internal ME exits */ d = hmm->tbd1 + hmm->begin[1] + 2.; hmm->tbd1 = (hmm->tbd1 + 1.)/ d; hmm->begin[1] = (hmm->begin[1] + 1.)/ d; hmm->end[hmm->M] = 1.0; /* Main model transitions and emissions */ for (k = 1; k < hmm->M; k++) { /* The following code chunk is experimental. * Collaboration with Michael Asman, Erik Sonnhammer, CGR Stockholm. * Only activated if X-PR* annotation has been used, in which * priors are overridden and a single Dirichlet component is * specified for each column (using structural annotation). * If X-PR* annotation is not used, which is usually the case, * the following code has no effect (observe how the real prior * distributions are copied into tq, mq, iq). */ if (hmm->tpri != NULL && hmm->tpri[k] >= 0) { if (hmm->tpri[k] >= pri->tnum) Die("X-PRT annotation out of range"); FSet(tq, pri->tnum, 0.0); tq[hmm->tpri[k]] = 1.0; } else FCopy(tq, pri->tq, pri->tnum); if (hmm->mpri != NULL && hmm->mpri[k] >= 0) { if (hmm->mpri[k] >= pri->mnum) Die("X-PRM annotation out of range"); FSet(mq, pri->mnum, 0.0); mq[hmm->mpri[k]] = 1.0; } else FCopy(mq, pri->mq, pri->mnum); if (hmm->ipri != NULL && hmm->ipri[k] >= 0) { if (hmm->ipri[k] >= pri->inum) Die("X-PRI annotation out of range"); FSet(iq, pri->inum, 0.0); iq[hmm->ipri[k]] = 1.0; } else FCopy(iq, pri->iq, pri->inum); /* This is the main line of the code: */ P7PriorifyTransitionVector(hmm->t[k], pri, tq); P7PriorifyEmissionVector(hmm->mat[k], pri, pri->mnum, mq, pri->m, NULL); P7PriorifyEmissionVector(hmm->ins[k], pri, pri->inum, iq, pri->i, NULL); } /* We repeat the above steps just for the final match state, M. */ if (hmm->mpri != NULL && hmm->mpri[hmm->M] >= 0) { if (hmm->mpri[hmm->M] >= pri->mnum) Die("X-PRM annotation out of range"); FSet(mq, pri->mnum, 0.0); mq[hmm->mpri[hmm->M]] = 1.0; } else FCopy(mq, pri->mq, pri->mnum); P7PriorifyEmissionVector(hmm->mat[hmm->M], pri, pri->mnum, mq, pri->m, NULL); /* Now we're done. Convert the counts-based HMM to probabilities. */ Plan7Renormalize(hmm); } /* Function: P7PriorifyEmissionVector() * * Purpose: Add prior pseudocounts to an observed * emission count vector and renormalize. * * Can return the posterior mixture probabilities * P(q | counts) if ret_mix[MAXDCHLET] is passed. * Else, pass NULL. * * Args: vec - the 4 or 20-long vector of counts to modify * pri - prior data structure * num - pri->mnum or pri->inum; # of mixtures * eq - pri->mq or pri->iq; prior mixture probabilities * e - pri->i or pri->m; Dirichlet components * ret_mix - filled with posterior mixture probabilities, or NULL * * Return: (void) * The counts in vec are changed and normalized to probabilities. */ void P7PriorifyEmissionVector(float *vec, struct p7prior_s *pri, int num, float eq[MAXDCHLET], float e[MAXDCHLET][MAXABET], float *ret_mix) { //get HMMERTaskLocalData HMMERTaskLocalData *tld = getHMMERTaskLocalData(); alphabet_s *al = &tld->al; int x; /* counter over vec */ int q; /* counter over mixtures */ float mix[MAXDCHLET]; /* posterior distribution over mixtures */ float totc; /* total counts */ float tota; /* total alpha terms */ float xi; /* X_i term, Sjolander eq. 41 */ /* Calculate mix[], which is the posterior probability * P(q | n) of mixture component q given the count vector n * * (side effect note: note that an insert vector in a PAM prior * is passed with num = 1, bypassing pam prior code; this means * that inserts cannot be mixture Dirichlets...) * [SRE, 12/24/00: the above comment is cryptic! what the hell does that * mean, inserts can't be mixtures? doesn't seem to be true. it * may mean that in a PAM prior, you can't have a mixture for inserts, * but I don't even understand that. The insert vectors aren't passed * with num=1!!] */ mix[0] = 1.0; if (pri->strategy == PRI_DCHLET && num > 1) { for (q = 0; q < num; q++) { mix[q] = eq[q] > 0.0 ? log(eq[q]) : -999.; mix[q] += Logp_cvec(vec, al->Alphabet_size, e[q]); } LogNorm(mix, num); /* now mix[q] is P(component_q | n) */ } else if (pri->strategy == PRI_PAM && num > 1) { /* pam prior uses aa frequencies as `P(q|n)' */ for (q = 0; q < al->Alphabet_size; q++) mix[q] = vec[q]; FNorm(mix, al->Alphabet_size); } /* Convert the counts to probabilities, following Sjolander (1996) */ totc = FSum(vec, al->Alphabet_size); for (x = 0; x < al->Alphabet_size; x++) { xi = 0.0; for (q = 0; q < num; q++) { tota = FSum(e[q], al->Alphabet_size); xi += mix[q] * (vec[x] + e[q][x]) / (totc + tota); } vec[x] = xi; } FNorm(vec, al->Alphabet_size); if (ret_mix != NULL) for (q = 0; q < num; q++) ret_mix[q] = mix[q]; } /* Function: P7PriorifyTransitionVector() * * Purpose: Add prior pseudocounts to transition vector, * which contains three different probability vectors * for m, d, and i. * * Args: t - state transitions, counts: 3 for M, 2 for I, 2 for D. * prior - Dirichlet prior information * tq - prior distribution over Dirichlet components. * (overrides prior->iq[]; used for alternative * methods of conditioning prior on structural data) * * Return: (void) * t is changed, and renormalized -- comes back as * probability vectors. */ void P7PriorifyTransitionVector(float *t, struct p7prior_s *prior, float tq[MAXDCHLET]) { int ts; int q; float mix[MAXDCHLET]; float totm, totd, toti; /* total counts in three transition vecs */ float xi; /* Sjolander's X_i term */ mix[0] = 1.0; /* default is simple one component */ if ((prior->strategy == PRI_DCHLET || prior->strategy == PRI_PAM) && prior->mnum > 1) { for (q = 0; q < prior->tnum; q++) { mix[q] = tq[q] > 0.0 ? log(tq[q]) : -999.; mix[q] += Logp_cvec(t, 3, prior->t[q]); /* 3 match */ mix[q] += Logp_cvec(t+3, 2, prior->t[q]+3); /* 2 insert */ mix[q] += Logp_cvec(t+5, 2, prior->t[q]+5); /* 2 delete */ } LogNorm(mix, prior->tnum); /* mix[q] is now P(q | counts) */ } /* precalc some denominators */ totm = FSum(t,3); toti = t[TIM] + t[TII]; totd = t[TDM] + t[TDD]; for (ts = 0; ts < 7; ts++) { xi = 0.0; for (q = 0; q < prior->tnum; q++) { switch (ts) { case TMM: case TMI: case TMD: xi += mix[q] * (t[ts] + prior->t[q][ts]) / (totm + FSum(prior->t[q], 3)); break; case TIM: case TII: xi += mix[q] * (t[ts] + prior->t[q][ts]) / (toti + prior->t[q][TIM] + prior->t[q][TII]); break; case TDM: case TDD: xi += mix[q] * (t[ts] + prior->t[q][ts]) / (totd + prior->t[q][TDM] + prior->t[q][TDD]); break; } } t[ts] = xi; } FNorm(t, 3); /* match */ FNorm(t+3, 2); /* insert */ FNorm(t+5, 2); /* delete */ } /* Function: default_amino_prior() * * Purpose: Set the default protein prior. */ static struct p7prior_s * default_amino_prior(void) { struct p7prior_s *pri; int q, x; /* default match mixture coefficients */ static float defmq[9] = { 0.178091, 0.056591, 0.0960191, 0.0781233, 0.0834977, 0.0904123, 0.114468, 0.0682132, 0.234585 }; /* default match mixture Dirichlet components */ static float defm[9][20] = { { 0.270671, 0.039848, 0.017576, 0.016415, 0.014268, 0.131916, 0.012391, 0.022599, 0.020358, 0.030727, 0.015315, 0.048298, 0.053803, 0.020662, 0.023612, 0.216147, 0.147226, 0.065438, 0.003758, 0.009621 }, { 0.021465, 0.010300, 0.011741, 0.010883, 0.385651, 0.016416, 0.076196, 0.035329, 0.013921, 0.093517, 0.022034, 0.028593, 0.013086, 0.023011, 0.018866, 0.029156, 0.018153, 0.036100, 0.071770, 0.419641 }, { 0.561459, 0.045448, 0.438366, 0.764167, 0.087364, 0.259114, 0.214940, 0.145928, 0.762204, 0.247320, 0.118662, 0.441564, 0.174822, 0.530840, 0.465529, 0.583402, 0.445586, 0.227050, 0.029510, 0.121090 }, { 0.070143, 0.011140, 0.019479, 0.094657, 0.013162, 0.048038, 0.077000, 0.032939, 0.576639, 0.072293, 0.028240, 0.080372, 0.037661, 0.185037, 0.506783, 0.073732, 0.071587, 0.042532, 0.011254, 0.028723 }, { 0.041103, 0.014794, 0.005610, 0.010216, 0.153602, 0.007797, 0.007175, 0.299635, 0.010849, 0.999446, 0.210189, 0.006127, 0.013021, 0.019798, 0.014509, 0.012049, 0.035799, 0.180085, 0.012744, 0.026466 }, { 0.115607, 0.037381, 0.012414, 0.018179, 0.051778, 0.017255, 0.004911, 0.796882, 0.017074, 0.285858, 0.075811, 0.014548, 0.015092, 0.011382, 0.012696, 0.027535, 0.088333, 0.944340, 0.004373, 0.016741 }, { 0.093461, 0.004737, 0.387252, 0.347841, 0.010822, 0.105877, 0.049776, 0.014963, 0.094276, 0.027761, 0.010040, 0.187869, 0.050018, 0.110039, 0.038668, 0.119471, 0.065802, 0.025430, 0.003215, 0.018742 }, { 0.452171, 0.114613, 0.062460, 0.115702, 0.284246, 0.140204, 0.100358, 0.550230, 0.143995, 0.700649, 0.276580, 0.118569, 0.097470, 0.126673, 0.143634, 0.278983, 0.358482, 0.661750, 0.061533, 0.199373 }, { 0.005193, 0.004039, 0.006722, 0.006121, 0.003468, 0.016931, 0.003647, 0.002184, 0.005019, 0.005990, 0.001473, 0.004158, 0.009055, 0.003630, 0.006583, 0.003172, 0.003690, 0.002967, 0.002772, 0.002686 }, }; pri = P7AllocPrior(); pri->strategy = PRI_DCHLET; /* Transition priors are subjective, but borrowed from GJM's estimations * on Pfam */ pri->tnum = 1; pri->tq[0] = 1.0; pri->t[0][TMM] = 0.7939; pri->t[0][TMI] = 0.0278; /* Markus suggests: ~10x MD: ~0.036: test! */ pri->t[0][TMD] = 0.0135; /* Markus suggests: ~0.1x MI: ~0.004 */ pri->t[0][TIM] = 0.1551; pri->t[0][TII] = 0.1331; pri->t[0][TDM] = 0.9002; pri->t[0][TDD] = 0.5630; /* Match emission priors are a mixture Dirichlet, * from Kimmen Sjolander (Blocks9) */ pri->mnum = 9; for (q = 0; q < pri->mnum; q++) { pri->mq[q] = defmq[q]; for (x = 0; x < 20; x++) pri->m[q][x] = defm[q][x]; } /* These insert emission priors are subjective. Observed frequencies * were obtained from PFAM 1.0, 10 Nov 96; * see ~/projects/plan7/InsertStatistics. * Inserts are slightly biased towards polar residues and away from * hydrophobic residues. */ pri->inum = 1; pri->iq[0] = 1.; pri->i[0][0] = 681.; /* A */ pri->i[0][1] = 120.; /* C */ pri->i[0][2] = 623.; /* D */ pri->i[0][3] = 651.; /* E */ pri->i[0][4] = 313.; /* F */ pri->i[0][5] = 902.; /* G */ pri->i[0][6] = 241.; /* H */ pri->i[0][7] = 371.; /* I */ pri->i[0][8] = 687.; /* K */ pri->i[0][9] = 676.; /* L */ pri->i[0][10] = 143.; /* M */ pri->i[0][11] = 548.; /* N */ pri->i[0][12] = 647.; /* P */ pri->i[0][13] = 415.; /* Q */ pri->i[0][14] = 551.; /* R */ pri->i[0][15] = 926.; /* S */ pri->i[0][16] = 623.; /* T */ pri->i[0][17] = 505.; /* V */ pri->i[0][18] = 102.; /* W */ pri->i[0][19] = 269.; /* Y */ return pri; } /* Function: default_nucleic_prior() * * Purpose: Set the default DNA prior. (for now, almost a Laplace) */ static struct p7prior_s * default_nucleic_prior(void) { //get HMMERTaskLocalData HMMERTaskLocalData *tld = getHMMERTaskLocalData(); alphabet_s *al = &tld->al; struct p7prior_s *pri; pri = P7AllocPrior(); pri->strategy = PRI_DCHLET; /* The use of the Pfam-trained amino acid transition priors * here is TOTALLY bogus. But it works better than a straight * Laplace, esp. for Maxmodelmaker(). For example, a Laplace * prior builds M=1 models for a single sequence GAATTC (at * one time an open "bug"). */ pri->tnum = 1; pri->tq[0] = 1.; pri->t[0][TMM] = 0.7939; pri->t[0][TMI] = 0.0278; pri->t[0][TMD] = 0.0135; pri->t[0][TIM] = 0.1551; pri->t[0][TII] = 0.1331; pri->t[0][TDM] = 0.9002; pri->t[0][TDD] = 0.5630; pri->mnum = 1; pri->mq[0] = 1.; FSet(pri->m[0], al->Alphabet_size, 1.); pri->inum = 1; pri->iq[0] = 1.; FSet(pri->i[0], al->Alphabet_size, 1.); return pri; } ugene-1.9.8/src/plugins_3rdparty/hmm2/src/hmmer2/sre_math.cpp0000644000175000017500000002202411651544326022553 0ustar ilyailya/***************************************************************** * HMMER - Biological sequence analysis with profile HMMs * Copyright (C) 1992-2003 Washington University School of Medicine * All Rights Reserved * * This source code is distributed under the terms of the * GNU General Public License. See the files COPYING and LICENSE * for details. *****************************************************************/ /* sre_math.c * * Portability for and extensions to C math library. * RCS $Id: sre_math.c,v 1.13 2003/04/14 16:00:16 eddy Exp $ */ #include "funcs.h" /* Function: Linefit() * * Purpose: Given points x[0..N-1] and y[0..N-1], fit to * a straight line y = a + bx. * a, b, and the linear correlation coefficient r * are filled in for return. * * Args: x - x values of data * y - y values of data * N - number of data points * ret_a - RETURN: intercept * ret_b - RETURN: slope * ret_r - RETURN: correlation coefficient * * Return: 1 on success, 0 on failure. */ int Linefit(float *x, float *y, int N, float *ret_a, float *ret_b, float *ret_r) { float xavg, yavg; float sxx, syy, sxy; int i; /* Calculate averages, xavg and yavg */ xavg = yavg = 0.0; for (i = 0; i < N; i++) { xavg += x[i]; yavg += y[i]; } xavg /= (float) N; yavg /= (float) N; sxx = syy = sxy = 0.0; for (i = 0; i < N; i++) { sxx += (x[i] - xavg) * (x[i] - xavg); syy += (y[i] - yavg) * (y[i] - xavg); sxy += (x[i] - xavg) * (y[i] - yavg); } *ret_b = sxy / sxx; *ret_a = yavg - xavg*(*ret_b); *ret_r = sxy / (sqrt(sxx) * sqrt(syy)); return 1; } /* Function: WeightedLinefit() * * Purpose: Given points x[0..N-1] and y[0..N-1] with * variances (measurement errors) var[0..N-1], * fit to a straight line y = mx + b. * * Method: Algorithm from Numerical Recipes in C, [Press88]. * * Return: (void) * ret_m contains slope; ret_b contains intercept */ void WeightedLinefit(float *x, float *y, float *var, int N, float *ret_m, float *ret_b) { int i; double s; double sx, sy; double sxx, sxy; double delta; double m, b; s = sx = sy = sxx = sxy = 0.; for (i = 0; i < N; i++) { s += 1./var[i]; sx += x[i] / var[i]; sy += y[i] / var[i]; sxx += x[i] * x[i] / var[i]; sxy += x[i] * y[i] / var[i]; } delta = s * sxx - (sx * sx); b = (sxx * sy - sx * sxy) / delta; m = (s * sxy - sx * sy) / delta; *ret_m = m; *ret_b = b; } /* Function: Gammln() * * Returns the natural log of the gamma function of x. * x is > 0.0. * * Adapted from a public domain implementation in the * NCBI core math library. Thanks to John Spouge and * the NCBI. (According to the NCBI, that's Dr. John * "Gammas Galore" Spouge to you, pal.) */ double Gammln(double x) { int i; double xx, tx; double tmp, value; static double cof[11] = { 4.694580336184385e+04, -1.560605207784446e+05, 2.065049568014106e+05, -1.388934775095388e+05, 5.031796415085709e+04, -9.601592329182778e+03, 8.785855930895250e+02, -3.155153906098611e+01, 2.908143421162229e-01, -2.319827630494973e-04, 1.251639670050933e-10 }; /* Protect against x=0. We see this in Dirichlet code, * for terms alpha = 0. This is a severe hack but it is effective * and (we think?) safe. (due to GJM) */ if (x <= 0.0) return 999999.; xx = x - 1.0; tx = tmp = xx + 11.0; value = 1.0; for (i = 10; i >= 0; i--) /* sum least significant terms first */ { value += cof[i] / tmp; tmp -= 1.0; } value = log(value); tx += 0.5; value += 0.918938533 + (xx+0.5)*log(tx) - tx; return value; } /* 2D matrix operations */ float ** FMX2Alloc(int rows, int cols) { float **mx; int r; mx = (float **) MallocOrDie(sizeof(float *) * rows); mx[0] = (float *) MallocOrDie(sizeof(float) * rows * cols); for (r = 1; r < rows; r++) mx[r] = mx[0] + r*cols; return mx; } void FMX2Free(float **mx) { free(mx[0]); free(mx); } double ** DMX2Alloc(int rows, int cols) { double **mx; int r; mx = (double **) MallocOrDie(sizeof(double *) * rows); mx[0] = (double *) MallocOrDie(sizeof(double) * rows * cols); for (r = 1; r < rows; r++) mx[r] = mx[0] + r*cols; return mx; } void DMX2Free(double **mx) { free(mx[0]); free(mx); } /* Function: FMX2Multiply() * * Purpose: Matrix multiplication. * Multiply an m x p matrix A by a p x n matrix B, * giving an m x n matrix C. * Matrix C must be a preallocated matrix of the right * size. */ void FMX2Multiply(float **A, float **B, float **C, int m, int p, int n) { int i, j, k; for (i = 0; i < m; i++) for (j = 0; j < n; j++) { C[i][j] = 0.; for (k = 0; k < p; k++) C[i][j] += A[i][p] * B[p][j]; } } /* Function: IncompleteGamma() * * Purpose: Returns 1 - P(a,x) where: * P(a,x) = \frac{1}{\Gamma(a)} \int_{0}^{x} t^{a-1} e^{-t} dt * = \frac{\gamma(a,x)}{\Gamma(a)} * = 1 - \frac{\Gamma(a,x)}{\Gamma(a)} * * Used in a chi-squared test: for a X^2 statistic x * with v degrees of freedom, call: * p = IncompleteGamma(v/2., x/2.) * to get the probability p that a chi-squared value * greater than x could be obtained by chance even for * a correct model. (i.e. p should be large, say * 0.95 or more). * * Method: Based on ideas from Numerical Recipes in C, Press et al., * Cambridge University Press, 1988. * * Args: a - for instance, degrees of freedom / 2 [a > 0] * x - for instance, chi-squared statistic / 2 [x >= 0] * * Return: 1 - P(a,x). */ double IncompleteGamma(double a, double x) { int iter; /* iteration counter */ if (a <= 0.) Die("IncompleteGamma(): a must be > 0"); if (x < 0.) Die("IncompleteGamma(): x must be >= 0"); /* For x > a + 1 the following gives rapid convergence; * calculate 1 - P(a,x) = \frac{\Gamma(a,x)}{\Gamma(a)}: * use a continued fraction development for \Gamma(a,x). */ if (x > a+1) { double oldp; /* previous value of p */ double nu0, nu1; /* numerators for continued fraction calc */ double de0, de1; /* denominators for continued fraction calc */ nu0 = 0.; /* A_0 = 0 */ de0 = 1.; /* B_0 = 1 */ nu1 = 1.; /* A_1 = 1 */ de1 = x; /* B_1 = x */ oldp = nu1; for (iter = 1; iter < 100; iter++) { /* Continued fraction development: * set A_j = b_j A_j-1 + a_j A_j-2 * B_j = b_j B_j-1 + a_j B_j-2 * We start with A_2, B_2. */ /* j = even: a_j = iter-a, b_j = 1 */ /* A,B_j-2 are in nu0, de0; A,B_j-1 are in nu1,de1 */ nu0 = nu1 + ((double)iter - a) * nu0; de0 = de1 + ((double)iter - a) * de0; /* j = odd: a_j = iter, b_j = x */ /* A,B_j-2 are in nu1, de1; A,B_j-1 in nu0,de0 */ nu1 = x * nu0 + (double) iter * nu1; de1 = x * de0 + (double) iter * de1; /* rescale */ if (de1 != 0.) { nu0 /= de1; de0 /= de1; nu1 /= de1; de1 = 1.; } /* check for convergence */ if (fabs((nu1-oldp)/nu1) < 1.e-7) return nu1 * exp(a * log(x) - x - Gammln(a)); oldp = nu1; } Die("IncompleteGamma(): failed to converge using continued fraction approx"); } else /* x <= a+1 */ { double p; /* current sum */ double val; /* current value used in sum */ /* For x <= a+1 we use a convergent series instead: * P(a,x) = \frac{\gamma(a,x)}{\Gamma(a)}, * where * \gamma(a,x) = e^{-x}x^a \sum_{n=0}{\infty} \frac{\Gamma{a}}{\Gamma{a+1+n}} x^n * which looks appalling but the sum is in fact rearrangeable to * a simple series without the \Gamma functions: * = \frac{1}{a} + \frac{x}{a(a+1)} + \frac{x^2}{a(a+1)(a+2)} ... * and it's obvious that this should converge nicely for x <= a+1. */ p = val = 1. / a; for (iter = 1; iter < 10000; iter++) { val *= x / (a+(double)iter); p += val; if (fabs(val/p) < 1.e-7) return 1. - p * exp(a * log(x) - x - Gammln(a)); } Die("IncompleteGamma(): failed to converge using series approx"); } /*NOTREACHED*/ return 0.; } ugene-1.9.8/src/plugins_3rdparty/hmm2/src/hmmer2/msa.cpp0000644000175000017500000002755111651544326021543 0ustar ilyailya/***************************************************************** * HMMER - Biological sequence analysis with profile HMMs * Copyright (C) 1992-2003 Washington University School of Medicine * All Rights Reserved * * This source code is distributed under the terms of the * GNU General Public License. See the files COPYING and LICENSE * for details. *****************************************************************/ /* msa.c * SRE, Mon May 17 10:48:47 1999 * * SQUID's interface for multiple sequence alignment * manipulation: access to the MSA object. * * CVS $Id: msa.c,v 1.20 2003/05/26 16:21:50 eddy Exp $ */ #include "funcs.h" #include #include /* Function: MSAAlloc() * Date: SRE, Tue May 18 10:45:47 1999 [St. Louis] * * Purpose: Allocate an MSA structure, return a pointer * to it. * * Designed to be used in three ways: * 1) We know exactly the dimensions of the alignment: * both nseq and alen. * msa = MSAAlloc(nseq, alen); * * 2) We know the number of sequences but not alen. * (We add sequences later.) * msa = MSAAlloc(nseq, 0); * * 3) We even don't know the number of sequences, so * we'll have to dynamically expand allocations. * We provide a blocksize for the allocation expansion, * and expand when needed. * msa = MSAAlloc(10, 0); * if (msa->nseq == msa->nseqalloc) MSAExpand(msa); * * Args: nseq - number of sequences, or nseq allocation blocksize * alen - length of alignment in columns, or 0 * * Returns: pointer to new MSA object, w/ all values initialized. * Note that msa->nseq is initialized to 0, though space * is allocated. * * Diagnostics: "always works". Die()'s on memory allocation failure. * */ MSA * MSAAlloc(int nseq, int alen) { assert(nseq > 0); MSA *msa; int i; msa = (MSA*)MallocOrDie(sizeof(MSA)); msa->aseq = (char**)MallocOrDie(sizeof(char *) * nseq); msa->sqname = (char**)MallocOrDie(sizeof(char *) * nseq); msa->wgt = (float*)MallocOrDie(sizeof(float) * nseq); for (i = 0; i < nseq; i++) { msa->sqname[i] = NULL; msa->wgt[i] = -1.0; if (alen != 0) msa->aseq[i] = (char*) MallocOrDie(sizeof(char) * (alen+1)); else msa->aseq[i] = NULL; } msa->alen = alen; msa->nseq = nseq; msa->flags = 0; msa->name = NULL; msa->desc = NULL; msa->acc = NULL; msa->au = NULL; msa->ss_cons = NULL; msa->sa_cons = NULL; msa->rf = NULL; msa->sqacc = NULL; msa->sqdesc = NULL; msa->ss = NULL; msa->sa = NULL; for (i = 0; i < MSA_MAXCUTOFFS; i++) { msa->cutoff[i] = 0.; msa->cutoff_is_set[i] = FALSE; } /* Done. Return the alloced, initialized structure */ return msa; } /* Function: MSAFree() * Date: SRE, Tue May 18 11:20:16 1999 [St. Louis] * * Purpose: Free a multiple sequence alignment structure. * * Args: msa - the alignment * * Returns: (void) */ void MSAFree(MSA *msa) { Free2DArray((void **) msa->aseq, msa->nseq); Free2DArray((void **) msa->sqname, msa->nseq); Free2DArray((void **) msa->sqacc, msa->nseq); Free2DArray((void **) msa->sqdesc, msa->nseq); Free2DArray((void **) msa->ss, msa->nseq); Free2DArray((void **) msa->sa, msa->nseq); if (msa->wgt != NULL) free(msa->wgt); if (msa->name != NULL) free(msa->name); if (msa->desc != NULL) free(msa->desc); if (msa->acc != NULL) free(msa->acc); if (msa->au != NULL) free(msa->au); if (msa->ss_cons != NULL) free(msa->ss_cons); if (msa->sa_cons != NULL) free(msa->sa_cons); if (msa->rf != NULL) free(msa->rf); free(msa); } /* Function: MSAMingap() * Date: SRE, Mon Jun 28 18:57:54 1999 [on jury duty, St. Louis Civil Court] * * Purpose: Remove all-gap columns from a multiple sequence alignment * and its associated per-residue data. * * Args: msa - the alignment * * Returns: (void) */ void MSAMingap(MSA *msa) { int *useme; /* array of TRUE/FALSE flags for which columns to keep */ int apos; /* position in original alignment */ int idx; /* sequence index */ useme = (int*)MallocOrDie(sizeof(int) * msa->alen); for (apos = 0; apos < msa->alen; apos++) { for (idx = 0; idx < msa->nseq; idx++) if (! isgap(msa->aseq[idx][apos])) break; if (idx == msa->nseq) useme[apos] = FALSE; else useme[apos] = TRUE; } MSAShorterAlignment(msa, useme); free(useme); return; } /* Function: MSANogap() * Date: SRE, Wed Nov 17 09:59:51 1999 [St. Louis] * * Purpose: Remove all columns from a multiple sequence alignment that * contain any gaps -- used for filtering before phylogenetic * analysis. * * Args: msa - the alignment * * Returns: (void). The alignment is modified, so if you want to keep * the original for something, make a copy. */ void MSANogap(MSA *msa) { int *useme; /* array of TRUE/FALSE flags for which columns to keep */ int apos; /* position in original alignment */ int idx; /* sequence index */ useme = (int*)MallocOrDie(sizeof(int) * msa->alen); for (apos = 0; apos < msa->alen; apos++) { for (idx = 0; idx < msa->nseq; idx++) if (isgap(msa->aseq[idx][apos])) break; if (idx == msa->nseq) useme[apos] = TRUE; else useme[apos] = FALSE; } MSAShorterAlignment(msa, useme); free(useme); return; } /* Function: MSAShorterAlignment() * Date: SRE, Wed Nov 17 09:49:32 1999 [St. Louis] * * Purpose: Given an array "useme" (0..alen-1) of TRUE/FALSE flags, * where TRUE means "keep this column in the new alignment": * Remove all columns annotated as "FALSE" in the useme * array. * * Args: msa - the alignment. The alignment is changed, so * if you don't want the original screwed up, make * a copy of it first. * useme - TRUE/FALSE flags for columns to keep: 0..alen-1 * * Returns: (void) */ void MSAShorterAlignment(MSA *msa, int *useme) { int apos; /* position in original alignment */ int mpos; /* position in new alignment */ int idx; /* sequence index */ /* Since we're minimizing, we can overwrite, using already allocated * memory. */ for (apos = 0, mpos = 0; apos < msa->alen; apos++) { if (useme[apos] == FALSE) continue; /* shift alignment and associated per-column+per-residue markup */ if (mpos != apos) { for (idx = 0; idx < msa->nseq; idx++) { msa->aseq[idx][mpos] = msa->aseq[idx][apos]; if (msa->ss != NULL && msa->ss[idx] != NULL) msa->ss[idx][mpos] = msa->ss[idx][apos]; if (msa->sa != NULL && msa->sa[idx] != NULL) msa->sa[idx][mpos] = msa->sa[idx][apos]; } if (msa->ss_cons != NULL) msa->ss_cons[mpos] = msa->ss_cons[apos]; if (msa->sa_cons != NULL) msa->sa_cons[mpos] = msa->sa_cons[apos]; if (msa->rf != NULL) msa->rf[mpos] = msa->rf[apos]; } mpos++; } msa->alen = mpos; /* set new length */ /* null terminate everything */ for (idx = 0; idx < msa->nseq; idx++) { msa->aseq[idx][mpos] = '\0'; if (msa->ss != NULL && msa->ss[idx] != NULL) msa->ss[idx][mpos] = '\0'; if (msa->sa != NULL && msa->sa[idx] != NULL) msa->sa[idx][mpos] = '\0'; } if (msa->ss_cons != NULL) msa->ss_cons[mpos] = '\0'; if (msa->sa_cons != NULL) msa->sa_cons[mpos] = '\0'; if (msa->rf != NULL) msa->rf[mpos] = '\0'; return; } /* Function: MSASmallerAlignment() * Date: SRE, Wed Jun 30 09:56:08 1999 [St. Louis] * * Purpose: Given an array "useme" of TRUE/FALSE flags for * each sequence in an alignment, construct * and return a new alignment containing only * those sequences that are flagged useme=TRUE. * * Used by routines such as MSAFilterAlignment() * and MSASampleAlignment(). * * Limitations: * Does not copy unparsed Stockholm markup. * * Does not make assumptions about meaning of wgt; * if you want the new wgt vector renormalized, do * it yourself with FNorm(new->wgt, new->nseq). * * Args: msa -- the original (larger) alignment * useme -- [0..nseq-1] array of TRUE/FALSE flags; TRUE means include * this seq in new alignment * ret_new -- RETURN: new alignment * * Returns: void * ret_new is allocated here; free with MSAFree() */ void MSASmallerAlignment(MSA *msa, int *useme, MSA **ret_new) { MSA *newMSA; /* RETURN: new alignment */ int nnew; /* number of seqs in new msa (e.g. # of TRUEs) */ int oidx, nidx; /* old, new indices */ int i; nnew = 0; for (oidx = 0; oidx < msa->nseq; oidx++) if (useme[oidx]) nnew++; if (nnew == 0) { *ret_new = NULL; return; } newMSA = MSAAlloc(nnew, 0); nidx = 0; for (oidx = 0; oidx < msa->nseq; oidx++) if (useme[oidx]) { newMSA->aseq[nidx] = sre_strdup(msa->aseq[oidx], msa->alen); newMSA->sqname[nidx] = sre_strdup(msa->sqname[oidx], msa->alen); newMSA->wgt[nidx] = msa->wgt[oidx]; if (msa->ss != NULL && msa->ss[oidx] != NULL) { if (newMSA->ss == NULL) newMSA->ss = (char**)MallocOrDie(sizeof(char *) * newMSA->nseq); newMSA->ss[nidx] = sre_strdup(msa->ss[oidx], -1); } if (msa->sa != NULL && msa->sa[oidx] != NULL) { if (newMSA->sa == NULL) newMSA->sa = (char**)MallocOrDie(sizeof(char *) * newMSA->nseq); newMSA->sa[nidx] = sre_strdup(msa->sa[oidx], -1); } nidx++; } newMSA->nseq = nnew; newMSA->alen = msa->alen; newMSA->flags = msa->flags; newMSA->type = msa->type; newMSA->name = sre_strdup(msa->name, -1); newMSA->desc = sre_strdup(msa->desc, -1); newMSA->acc = sre_strdup(msa->acc, -1); newMSA->au = sre_strdup(msa->au, -1); newMSA->ss_cons = sre_strdup(msa->ss_cons, -1); newMSA->sa_cons = sre_strdup(msa->sa_cons, -1); newMSA->rf = sre_strdup(msa->rf, -1); for (i = 0; i < MSA_MAXCUTOFFS; i++) { newMSA->cutoff[i] = msa->cutoff[i]; newMSA->cutoff_is_set[i] = msa->cutoff_is_set[i]; } MSAMingap(newMSA); *ret_new = newMSA; return; } /* Function: MSASetSeqAccession() * Date: SRE, Mon Jun 21 04:13:33 1999 [Sanger Centre] * * Purpose: Set a sequence accession in an MSA structure. * Handles some necessary allocation/initialization. * * Args: msa - multiple alignment to add accession to * seqidx - index of sequence to attach accession to * acc - accession * * Returns: void */ void MSASetSeqAccession(MSA *msa, int seqidx, char *acc) { //todo: } /* Function: MSASetSeqDescription() * Date: SRE, Mon Jun 21 04:21:09 1999 [Sanger Centre] * * Purpose: Set a sequence description in an MSA structure. * Handles some necessary allocation/initialization. * * Args: msa - multiple alignment to add accession to * seqidx - index of sequence to attach accession to * desc - description * * Returns: void */ void MSASetSeqDescription(MSA *msa, int seqidx, char *desc) { //todo: } ugene-1.9.8/src/plugins_3rdparty/hmm2/src/hmmer2/trace.cpp0000644000175000017500000011144611651544326022056 0ustar ilyailya/************************************************************ * HMMER - Biological sequence analysis with profile HMMs * Copyright (C) 1992-2003 Washington University School of Medicine * All Rights Reserved * * This source code is distributed under the terms of the * GNU General Public License. See the files COPYING and LICENSE * for details. ************************************************************/ /* trace.c * SRE, Sat Nov 16 12:34:57 1996 * RCS $Id: trace.c,v 1.20 2003/10/02 16:39:41 eddy Exp $ * * Support for Plan 7 traceback data structure, p7trace_s. */ #include "funcs.h" static void rightjustify(char *s, int n); /* Function: P7AllocTrace(), P7ReallocTrace(), P7FreeTrace() * * Purpose: allocation and freeing of traceback structures */ void P7AllocTrace(int tlen, struct p7trace_s **ret_tr) { struct p7trace_s *tr; tr = (struct p7trace_s*)MallocOrDie (sizeof(struct p7trace_s)); tr->statetype = (char*)MallocOrDie (sizeof(char) * tlen); tr->nodeidx = (int*)MallocOrDie (sizeof(int) * tlen); tr->pos = (int*)MallocOrDie (sizeof(int) * tlen); *ret_tr = tr; } void P7ReallocTrace(struct p7trace_s *tr, int tlen) { tr->statetype = (char*)ReallocOrDie(tr->statetype, tlen * sizeof(char)); tr->nodeidx = (int*) ReallocOrDie(tr->nodeidx, tlen * sizeof(int)); tr->pos = (int*) ReallocOrDie(tr->pos, tlen * sizeof(int)); } void P7FreeTrace(struct p7trace_s *tr) { if (tr == NULL) return; free(tr->pos); free(tr->nodeidx); free(tr->statetype); free(tr); } /* Function: TraceSet() * Date: SRE, Sun Mar 8 12:39:00 1998 [St. Louis] * * Purpose: Convenience function; set values at position tpos * in a trace. * * * Args: tr - trace object to write to * tpos - ptr to position in trace to set * type - statetype e.g. STS, etc. * idx - nodeidx 1..M or 0 * pos - seq position 1..L or 0 * * Returns: void */ void TraceSet(struct p7trace_s *tr, int tpos, char type, int idx, int pos) { tr->statetype[tpos] = type; tr->nodeidx[tpos] = idx; tr->pos[tpos] = pos; } /* Function: MergeTraceArrays() * Date: SRE, Sun Jul 5 15:09:10 1998 [St. Louis] * * Purpose: Combine two arrays of traces into a single array. * Used in hmmalign to merge traces from a fixed alignment * with traces from individual unaligned seqs. * * t1 traces always precede t2 traces in the resulting array. * * Args: t1 - first set of traces * n1 - number of traces in t1 * t2 - second set of traces * n2 - number of traces in t2 * * Returns: pointer to new array of traces. * Both t1 and t2 are free'd here! Do not reuse. */ struct p7trace_s ** MergeTraceArrays(struct p7trace_s **t1, int n1, struct p7trace_s **t2, int n2) { struct p7trace_s **tr; int i; /* index in traces */ tr = (struct p7trace_s **)MallocOrDie(sizeof(struct p7trace_s *) * (n1+n2)); for (i = 0; i < n1; i++) tr[i] = t1[i]; for (i = 0; i < n2; i++) tr[n1+i] = t2[i]; free(t1); free(t2); return tr; } /* Function: P7ReverseTrace() * Date: SRE, Mon Aug 25 12:57:29 1997; Denver CO. * * Purpose: Reverse the arrays in a traceback structure. * Tracebacks from Forward() and Viterbi() are * collected backwards, and call this function * when they're done. * * It's possible to reverse the arrays in place * more efficiently; but the realloc/copy strategy * has the advantage of reallocating the trace * into the right size of memory. (Tracebacks * overallocate.) * * Args: tr - the traceback to reverse. tr->tlen must be set. * * Return: (void) * tr is modified. */ void P7ReverseTrace(struct p7trace_s *tr) { char *statetype; int *nodeidx; int *pos; int opos, npos; /* Allocate */ statetype = (char*)MallocOrDie (sizeof(char)* tr->tlen); nodeidx = (int*)MallocOrDie (sizeof(int) * tr->tlen); pos = (int*)MallocOrDie (sizeof(int) * tr->tlen); /* Reverse the trace. */ for (opos = tr->tlen-1, npos = 0; npos < tr->tlen; npos++, opos--) { statetype[npos] = tr->statetype[opos]; nodeidx[npos] = tr->nodeidx[opos]; pos[npos] = tr->pos[opos]; } /* Swap old, new arrays. */ free(tr->statetype); free(tr->nodeidx); free(tr->pos); tr->statetype = statetype; tr->nodeidx = nodeidx; tr->pos = pos; } /* Function: P7TraceCount() * * Purpose: Count a traceback into a count-based HMM structure. * (Usually as part of a model parameter re-estimation.) * * Args: hmm - counts-based HMM * dsq - digitized sequence that traceback aligns to the HMM (1..L) * wt - weight on the sequence * tr - alignment of seq to HMM * * Return: (void) */ void P7TraceCount(struct plan7_s *hmm, unsigned char *dsq, float wt, struct p7trace_s *tr) { int tpos; /* position in tr */ int i; /* symbol position in seq */ for (tpos = 0; tpos < tr->tlen; tpos++) { i = tr->pos[tpos]; /* Emission counts. * Don't bother counting null states N,J,C. */ if (tr->statetype[tpos] == STM) P7CountSymbol(hmm->mat[tr->nodeidx[tpos]], dsq[i], wt); else if (tr->statetype[tpos] == STI) P7CountSymbol(hmm->ins[tr->nodeidx[tpos]], dsq[i], wt); /* State transition counts */ switch (tr->statetype[tpos]) { case STS: break; /* don't bother; P=1 */ case STN: switch (tr->statetype[tpos+1]) { case STB: hmm->xt[XTN][MOVE] += wt; break; case STN: hmm->xt[XTN][LOOP] += wt; break; default: Die("illegal state transition %s->%s in traceback", Statetype(tr->statetype[tpos]), Statetype(tr->statetype[tpos+1])); } break; case STB: switch (tr->statetype[tpos+1]) { case STM: hmm->begin[tr->nodeidx[tpos+1]] += wt; break; case STD: hmm->tbd1 += wt; break; default: Die("illegal state transition %s->%s in traceback", Statetype(tr->statetype[tpos]), Statetype(tr->statetype[tpos+1])); } break; case STM: switch (tr->statetype[tpos+1]) { case STM: hmm->t[tr->nodeidx[tpos]][TMM] += wt; break; case STI: hmm->t[tr->nodeidx[tpos]][TMI] += wt; break; case STD: hmm->t[tr->nodeidx[tpos]][TMD] += wt; break; case STE: hmm->end[tr->nodeidx[tpos]] += wt; break; default: Die("illegal state transition %s->%s in traceback", Statetype(tr->statetype[tpos]), Statetype(tr->statetype[tpos+1])); } break; case STI: switch (tr->statetype[tpos+1]) { case STM: hmm->t[tr->nodeidx[tpos]][TIM] += wt; break; case STI: hmm->t[tr->nodeidx[tpos]][TII] += wt; break; default: Die("illegal state transition %s->%s in traceback", Statetype(tr->statetype[tpos]), Statetype(tr->statetype[tpos+1])); } break; case STD: switch (tr->statetype[tpos+1]) { case STM: hmm->t[tr->nodeidx[tpos]][TDM] += wt; break; case STD: hmm->t[tr->nodeidx[tpos]][TDD] += wt; break; case STE: /* ignore; p(D->E) = 1.0 */ break; default: Die("illegal state transition %s->%s in traceback", Statetype(tr->statetype[tpos]), Statetype(tr->statetype[tpos+1])); } break; case STE: switch (tr->statetype[tpos+1]) { case STC: hmm->xt[XTE][MOVE] += wt; break; case STJ: hmm->xt[XTE][LOOP] += wt; break; default: Die("illegal state transition %s->%s in traceback", Statetype(tr->statetype[tpos]), Statetype(tr->statetype[tpos+1])); } break; case STJ: switch (tr->statetype[tpos+1]) { case STB: hmm->xt[XTJ][MOVE] += wt; break; case STJ: hmm->xt[XTJ][LOOP] += wt; break; default: Die("illegal state transition %s->%s in traceback", Statetype(tr->statetype[tpos]), Statetype(tr->statetype[tpos+1])); } break; case STC: switch (tr->statetype[tpos+1]) { case STT: hmm->xt[XTC][MOVE] += wt; break; case STC: hmm->xt[XTC][LOOP] += wt; break; default: Die("illegal state transition %s->%s in traceback", Statetype(tr->statetype[tpos]), Statetype(tr->statetype[tpos+1])); } break; case STT: break; /* T is the last. It makes no transitions. */ default: Die("illegal state %s in traceback", Statetype(tr->statetype[tpos])); } } } /* Function: P7TraceScore() * * Purpose: Score a traceback and return the score in scaled bits. * * Args: hmm - HMM with valid log odds scores. * dsq - digitized sequence that traceback aligns to the HMM (1..L) * tr - alignment of seq to HMM * * Return: (void) */ float P7TraceScore(struct plan7_s *hmm, unsigned char *dsq, struct p7trace_s *tr) { int score; /* total score as a scaled integer */ int tpos; /* position in tr */ unsigned char sym; /* digitized symbol in dsq */ /* P7PrintTrace(stdout, tr, hmm, dsq); */ score = 0; for (tpos = 0; tpos < tr->tlen-1; tpos++) { sym = dsq[tr->pos[tpos]]; /* Emissions. * Don't bother counting null states N,J,C. */ if (tr->statetype[tpos] == STM) score += hmm->msc[sym][tr->nodeidx[tpos]]; else if (tr->statetype[tpos] == STI) score += hmm->isc[sym][tr->nodeidx[tpos]]; /* State transitions. */ score += TransitionScoreLookup(hmm, tr->statetype[tpos], tr->nodeidx[tpos], tr->statetype[tpos+1], tr->nodeidx[tpos+1]); } return Scorify(score); } /* Function: P7Traces2Alignment() * * Purpose: Convert an array of traceback structures for a set * of sequences into a new multiple alignment. * * Insertions are put into lower case and * are not aligned; instead, Nterm is right-justified, * Cterm is left-justified, and internal insertions * are split in half and the halves are justified in * each direction (the objective being to increase * the chances of getting insertions aligned well enough * for them to become a match). SAM gap char conventions * are used: - in match columns, . in insert columns * * NOTE: Does not recognize J state. * * Can handle traces with D->I and I->D transitions; * though these are disallowed by Plan7, they might be * generated by aligning an alignment to a model, in * the ImposeMasterTrace() step. Thus, --withali might * generate alignments that are inconsistent with Plan7, * that would have to be trace_doctor()'ed. * xref STL6/p.117. * * Args: dsq - digitized unaligned sequences * sqinfo - array of info about the sequences * wgt - weights on seqs * nseq - number of sequences * mlen - length of model (number of match states) * tr - array of tracebacks * matchonly - TRUE if we don't print insert-generated symbols at all * Return: MSA structure; NULL on failure. * Caller responsible for freeing msa with MSAFree(msa); */ MSA * P7Traces2Alignment(unsigned char **dsq, SQINFO *sqinfo, float *wgt, int nseq, int mlen, struct p7trace_s **tr, int matchonly) { MSA *msa; /* RETURN: new alignment */ int idx; /* counter for sequences */ int alen; /* width of alignment */ int *inserts; /* array of max gaps between aligned columns */ int *matmap; /* matmap[k] = apos of match k [1..M] */ int nins; /* counter for inserts */ int apos; /* position in aligned sequence (0..alen-1)*/ int rpos; /* position in raw digital sequence (1..L)*/ int tpos; /* position counter in traceback */ int statetype; /* type of current state, e.g. STM */ int k; /* counter over states in model */ /* Here's the problem. We want to align the match states in columns, * but some sequences have inserted symbols in them; we need some * sort of overall knowledge of where the inserts are and how long * they are in order to create the alignment. * * Here's our trick. inserts[] is a 0..hmm->M array; inserts[i] stores * the maximum number of times insert substate i was used. This * is the maximum number of gaps to insert between canonical * column i and i+1. inserts[0] is the N-term tail; inserts[M] is * the C-term tail. * * Remember that N and C emit on transition, hence the check for an * N->N or C->C transition before bumping nins. */ //get HMMERTaskLocalData HMMERTaskLocalData *tld = getHMMERTaskLocalData(); alphabet_s *al = &tld->al; inserts = (int *) MallocOrDie (sizeof(int) * (mlen+1)); for (k = 0; k <= mlen; k++) inserts[k] = 0; for (idx = 0; idx < nseq; idx++) { nins = 0; for (tpos = 0; tpos < tr[idx]->tlen; tpos++) { switch (tr[idx]->statetype[tpos]) { case STI: nins++; break; case STN: if (tr[idx]->statetype[tpos-1] == STN) nins++; break; case STC: if (tr[idx]->statetype[tpos-1] == STC) nins++; break; case STM: case STD: /* M,D: record max. reset ctr. */ if (nins > inserts[tr[idx]->nodeidx[tpos]-1]) inserts[tr[idx]->nodeidx[tpos]-1] = nins; nins = 0; break; case STB: /* B; record N-tail max, reset ctr */ if (nins > inserts[0]) inserts[0] = nins; nins = 0; break; case STT: /* T: record C-tail max */ if (nins > inserts[mlen]) inserts[mlen] = nins; break; case STS: case STE: break; /* ignore other states */ case STJ: Die("yo! you don't support J in Traces2Alignment(), remember?"); default: Die("Traces2Alignment reports unrecognized statetype %c", Statetype(tr[idx]->statetype[tpos])); } } } /* Insert compression option. */ if (matchonly) for (k = 0; k <= mlen; k++) if (inserts[k] > 1) inserts[k] = 1; /*********************************************** * Construct the alignment ***********************************************/ /* calculate alignment length and matmap */ matmap= (int *) MallocOrDie(sizeof(int) * (mlen+1)); matmap[0] = -1; alen = inserts[0]; for (k = 1; k <= mlen ; k++) { matmap[k] = alen; alen += inserts[k] + 1; } /* allocation for new alignment */ msa = MSAAlloc(nseq, alen); for (idx = 0; idx < nseq; idx++) { /* blank an aseq */ for (apos = 0; apos < alen; apos++) msa->aseq[idx][apos] = '.'; for (k = 1; k <= mlen; k++) msa->aseq[idx][matmap[k]] = '-'; msa->aseq[idx][alen] = '\0'; /* align the sequence */ apos = 0; for (tpos = 0; tpos < tr[idx]->tlen; tpos++) { statetype = tr[idx]->statetype[tpos]; /* just for clarity */ rpos = tr[idx]->pos[tpos]; k = tr[idx]->nodeidx[tpos]; if (statetype == STM) { apos = matmap[k]; msa->aseq[idx][apos] = al->Alphabet[dsq[idx][rpos]]; apos++; } else if (statetype == STD) { apos = matmap[k]+1; /* need for handling D->I; xref STL6/p.117 */ } else if (statetype == STI) { if (matchonly) msa->aseq[idx][apos] = '*'; /* insert compression option */ else { msa->aseq[idx][apos] = (char) tolower((int) al->Alphabet[dsq[idx][rpos]]); apos++; } } else if ((statetype == STN || statetype == STC) && rpos > 0) { if (matchonly) msa->aseq[idx][apos] = '*'; /* insert compression option */ else { msa->aseq[idx][apos] = (char) tolower((int) al->Alphabet[dsq[idx][rpos]]); apos++; } } else if (statetype == STE) apos = matmap[mlen]+1; /* set position for C-term tail */ } /* N-terminal extension is right-justified. * Internal inserts are split in half, and C-term is right-justified. * C-terminal extension remains left-justified. */ if (! matchonly) { rightjustify(msa->aseq[idx], inserts[0]); for (k = 1; k < mlen; k++) if (inserts[k] > 1) { for (nins = 0, apos = matmap[k]+1; islower((int) (msa->aseq[idx][apos])); apos++) nins++; nins /= 2; /* split the insertion in half */ rightjustify(msa->aseq[idx]+matmap[k]+1+nins, inserts[k]-nins); } } } /*********************************************** * Build the rest of the MSA annotation. ***********************************************/ msa->nseq = nseq; msa->alen = alen; int auBufLen = sizeof(char) * (strlen(PACKAGE_VERSION)+7); msa->au = (char*)MallocOrDie(auBufLen); snprintf(msa->au, auBufLen, "HMMER %s", PACKAGE_VERSION); /* copy sqinfo array and weights */ for (idx = 0; idx < nseq; idx++) { msa->sqname[idx] = sre_strdup(sqinfo[idx].name, -1); if (sqinfo[idx].flags & SQINFO_ACC) MSASetSeqAccession(msa, idx, sqinfo[idx].acc); if (sqinfo[idx].flags & SQINFO_DESC) MSASetSeqDescription(msa, idx, sqinfo[idx].desc); if (sqinfo[idx].flags & SQINFO_SS) { if (msa->ss == NULL) msa->ss = (char**)MallocOrDie(sizeof(char *) * nseq); MakeAlignedString(msa->aseq[idx], alen, sqinfo[idx].ss, &(msa->ss[idx])); } if (sqinfo[idx].flags & SQINFO_SA) { if (msa->sa == NULL) msa->sa = (char**)MallocOrDie(sizeof(char *) * nseq); MakeAlignedString(msa->aseq[idx], alen, sqinfo[idx].sa, &(msa->sa[idx])); } msa->wgt[idx] = wgt[idx]; } /* #=RF annotation: x for match column, . for insert column */ msa->rf = (char *) MallocOrDie (sizeof(char) * (alen+1)); for (apos = 0; apos < alen; apos++) msa->rf[apos] = '.'; for (k = 1; k <= mlen; k++) msa->rf[matmap[k]] = 'x'; msa->rf[alen] = '\0'; /* Currently, we produce no consensus structure. * #=CS, generated from HMM structural annotation, would go here. */ free(inserts); free(matmap); return msa; } /* Function: TransitionScoreLookup() * * Purpose: Convenience function used in PrintTrace() and TraceScore(); * given state types and node indices for a transition, * return the integer score for that transition. */ int TransitionScoreLookup(struct plan7_s *hmm, char st1, int k1, char st2, int k2) { switch (st1) { case STS: return 0; /* S never pays */ case STN: switch (st2) { case STB: return hmm->xsc[XTN][MOVE]; case STN: return hmm->xsc[XTN][LOOP]; default: Die("illegal %s->%s transition", Statetype(st1), Statetype(st2)); } break; case STB: switch (st2) { case STM: return hmm->bsc[k2]; case STD: return Prob2Score(hmm->tbd1, 1.); default: Die("illegal %s->%s transition", Statetype(st1), Statetype(st2)); } break; case STM: switch (st2) { case STM: return hmm->tsc[TMM][k1]; case STI: return hmm->tsc[TMI][k1]; case STD: return hmm->tsc[TMD][k1]; case STE: return hmm->esc[k1]; default: Die("illegal %s->%s transition", Statetype(st1), Statetype(st2)); } break; case STI: switch (st2) { case STM: return hmm->tsc[TIM][k1]; case STI: return hmm->tsc[TII][k1]; default: Die("illegal %s->%s transition", Statetype(st1), Statetype(st2)); } break; case STD: switch (st2) { case STM: return hmm->tsc[TDM][k1]; case STD: return hmm->tsc[TDD][k1]; case STE: return 0; /* D_m->E has probability 1.0 by definition in Plan7 */ default: Die("illegal %s->%s transition", Statetype(st1), Statetype(st2)); } break; case STE: switch (st2) { case STC: return hmm->xsc[XTE][MOVE]; case STJ: return hmm->xsc[XTE][LOOP]; default: Die("illegal %s->%s transition", Statetype(st1), Statetype(st2)); } break; case STJ: switch (st2) { case STB: return hmm->xsc[XTJ][MOVE]; case STJ: return hmm->xsc[XTJ][LOOP]; default: Die("illegal %s->%s transition", Statetype(st1), Statetype(st2)); } break; case STC: switch (st2) { case STT: return hmm->xsc[XTC][MOVE]; case STC: return hmm->xsc[XTC][LOOP]; default: Die("illegal %s->%s transition", Statetype(st1), Statetype(st2)); } break; case STT: return 0; /* T makes no transitions */ default: Die("illegal state %s in traceback", Statetype(st1)); } /*NOTREACHED*/ return 0; } /* Function: CreateFancyAli() * Date: SRE, Mon Oct 27 06:49:44 1997 [Sanger Centre UK] * * Purpose: Output of an HMM/sequence alignment, using a * traceback structure. Deliberately similar to * the output of BLAST, to make it easier for * people to adapt their Perl parsers (or what have * you) from BLAST to HMMER. * * Args: tr - traceback structure that gives the alignment * hmm - the model * dsq - the sequence (digitized form) * name- name of the sequence * * Return: allocated, filled fancy alignment structure. */ struct fancyali_s * CreateFancyAli(struct p7trace_s *tr, struct plan7_s *hmm, unsigned char *dsq, char *name) { struct fancyali_s *ali; /* alignment to create */ int tpos; /* position in trace and alignment */ int bestsym; /* index of best symbol at this pos */ float mthresh; /* above this P(x), display uppercase */ //get HMMERTaskLocalData HMMERTaskLocalData *tld = getHMMERTaskLocalData(); alphabet_s *al = &tld->al; /* Allocate and initialize the five lines of display */ ali = AllocFancyAli(); ali->rfline = NULL; ali->csline = NULL; ali->model = (char*)MallocOrDie (sizeof(char) * (tr->tlen+1)); ali->mline = (char*)MallocOrDie (sizeof(char) * (tr->tlen+1)); ali->aseq = (char*)MallocOrDie (sizeof(char) * (tr->tlen+1)); memset(ali->model, ' ', tr->tlen); memset(ali->mline, ' ', tr->tlen); memset(ali->aseq, ' ', tr->tlen); if (hmm->flags & PLAN7_RF) { ali->rfline = (char *) MallocOrDie (sizeof(char) * (tr->tlen+1)); memset(ali->rfline, ' ', tr->tlen); } if (hmm->flags & PLAN7_CS) { ali->csline = (char *) MallocOrDie (sizeof(char) * (tr->tlen+1)); memset(ali->csline, ' ', tr->tlen); } ali->query = Strdup(hmm->name); ali->target = Strdup(name); if (al->Alphabet_type == hmmAMINO) mthresh = 0.5; else mthresh = 0.9; /* Find first, last seq position * HMM start/end positions currently not recorded, because there * might be multiple HMM hits per sequence. */ for (tpos = 0; tpos < tr->tlen; tpos++) if (tr->pos[tpos] > 0) { ali->sqfrom = tr->pos[tpos]; break; } for (tpos = tr->tlen-1; tpos >= 0; tpos--) if (tr->pos[tpos] > 0) { ali->sqto = tr->pos[tpos]; break; } /* Fill in the five lines of display */ for (tpos = 0; tpos < tr->tlen; tpos++) { switch (tr->statetype[tpos]) { case STS: case STT: ali->model[tpos] = '*'; break; case STN: case STJ: case STC: ali->model[tpos] = '-'; if (tr->pos[tpos] > 0) { ali->aseq[tpos] = tolower(al->Alphabet[dsq[tr->pos[tpos]]]); } break; case STB: ali->model[tpos] = '>'; break; case STE: ali->model[tpos] = '<'; break; case STM: if (hmm->flags & PLAN7_RF) ali->rfline[tpos] = hmm->rf[tr->nodeidx[tpos]]; if (hmm->flags & PLAN7_CS) ali->csline[tpos] = hmm->cs[tr->nodeidx[tpos]]; bestsym = FArgMax(hmm->mat[tr->nodeidx[tpos]], al->Alphabet_size); ali->model[tpos] = al->Alphabet[bestsym]; if (hmm->mat[tr->nodeidx[tpos]][bestsym] < mthresh) ali->model[tpos] = tolower(ali->model[tpos]); if (dsq[tr->pos[tpos]] == bestsym) { ali->mline[tpos] = al->Alphabet[dsq[tr->pos[tpos]]]; if (hmm->mat[tr->nodeidx[tpos]][bestsym] < mthresh) ali->mline[tpos] = tolower(ali->mline[tpos]); } else if (hmm->msc[dsq[tr->pos[tpos]]] [tr->nodeidx[tpos]] > 0) ali->mline[tpos] = '+'; ali->aseq[tpos] = al->Alphabet[dsq[tr->pos[tpos]]]; break; case STD: if (hmm->flags & PLAN7_RF) ali->rfline[tpos] = hmm->rf[tr->nodeidx[tpos]]; if (hmm->flags & PLAN7_CS) ali->csline[tpos] = hmm->cs[tr->nodeidx[tpos]]; bestsym = FArgMax(hmm->mat[tr->nodeidx[tpos]], al->Alphabet_size); ali->model[tpos] = al->Alphabet[bestsym]; if (hmm->mat[tr->nodeidx[tpos]][bestsym] < mthresh) ali->model[tpos] = tolower(ali->model[tpos]); ali->aseq[tpos] = '-'; break; case STI: ali->model[tpos] = '.'; if (hmm->isc[dsq[tr->pos[tpos]]] [tr->nodeidx[tpos]] > 0) ali->mline[tpos] = '+'; ali->aseq[tpos] = (char) tolower((int) al->Alphabet[dsq[tr->pos[tpos]]]); break; default: Die("bogus statetype"); } /* end switch over statetypes */ } /* end loop over tpos */ ali->len = tpos; if (hmm->flags & PLAN7_RF) ali->rfline[tpos] = '\0'; if (hmm->flags & PLAN7_CS) ali->csline[tpos] = '\0'; ali->model[tpos] = '\0'; ali->mline[tpos] = '\0'; ali->aseq[tpos] = '\0'; return ali; } /* Function: TraceDecompose() * Date: Sat Aug 30 11:18:40 1997 (Denver CO) * * Purpose: Decompose a long multi-hit trace into zero or more * traces without N,C,J transitions: for consistent * scoring and statistical evaluation of single domain * hits. * * Args: otr - original trace structure * ret_tr - RETURN: array of simpler traces * ret_ntr- RETURN: number of traces. * * Return: (void) * ret_tr alloc'ed here; free individuals with FreeTrace(). */ void TraceDecompose(struct p7trace_s *otr, struct p7trace_s ***ret_tr, int *ret_ntr) { struct p7trace_s **tr; /* array of new traces */ int ntr; /* number of traces */ int i,j; /* position counters in traces */ int idx; /* index over ntr subtraces */ /* First pass: count begin states to get ntr. */ for (ntr = 0, i = 0; i < otr->tlen; i++) if (otr->statetype[i] == STB) ntr++; /* Allocations. */ if (ntr == 0) { *ret_ntr = 0; *ret_tr = NULL; return; } tr = (struct p7trace_s **) MallocOrDie (sizeof(struct p7trace_s *) * ntr); for (idx = 0, i = 0; i < otr->tlen; i++) /* i = position in old trace */ if (otr->statetype[i] == STB) { for (j = i+1; j < otr->tlen; j++) /* j = tmp; get length of subtrace */ if (otr->statetype[j] == STE) break; /* trace = S-N-(B..E)-C-T : len + 4 : j-i+1 + 4*/ P7AllocTrace(j-i+5, &(tr[idx])); tr[idx]->tlen = j-i+5; tr[idx]->statetype[0] = STS; tr[idx]->nodeidx[0] = 0; tr[idx]->pos[0] = 0; tr[idx]->statetype[1] = STN; tr[idx]->nodeidx[1] = 0; tr[idx]->pos[1] = 0; j = 2; /* now j = position in new subtrace */ while (1) /* copy subtrace */ { tr[idx]->statetype[j] = otr->statetype[i]; tr[idx]->nodeidx[j] = otr->nodeidx[i]; tr[idx]->pos[j] = otr->pos[i]; if (otr->statetype[i] == STE) break; i++; j++; } j++; tr[idx]->statetype[j] = STC; tr[idx]->nodeidx[j] = 0; tr[idx]->pos[j] = 0; j++; tr[idx]->statetype[j] = STT; tr[idx]->nodeidx[j] = 0; tr[idx]->pos[j] = 0; idx++; } *ret_tr = tr; *ret_ntr = ntr; return; } /* Function: TraceDomainNumber() * * Purpose: Count how many times we traverse the * model in a single Plan7 trace -- equivalent * to counting the number of domains. * * (A weakness is that we might discard some of * those domains because they have low scores * below E or T threshold.) */ int TraceDomainNumber(struct p7trace_s *tr) { int i; int ndom = 0; for (i = 0; i < tr->tlen; i++) if (tr->statetype[i] == STB) ndom++; return ndom; } /* Function: TraceSimpleBounds() * * Purpose: For a trace that contains only a single * traverse of the model (i.e. something that's * come from TraceDecompose(), or a global * alignment), determine the bounds of * the match on both the sequence [1..L] and the * model [1..M]. * * Args: tr - trace to look at * i1 - RETURN: start point in sequence [1..L] * i2 - RETURN: end point in sequence [1..L] * k1 - RETURN: start point in model [1..M] * k2 - RETURN: end point in model [1..M] */ void TraceSimpleBounds(struct p7trace_s *tr, int *ret_i1, int *ret_i2, int *ret_k1, int *ret_k2) { int i1, i2, k1, k2, tpos; i1 = k1 = i2 = k2 = -1; /* Look forwards to find start of match */ for (tpos = 0; tpos < tr->tlen; tpos++) { if (k1 == -1 && (tr->statetype[tpos] == STM || tr->statetype[tpos] == STD)) k1 = tr->nodeidx[tpos]; if (tr->statetype[tpos] == STM) { i1 = tr->pos[tpos]; break; } } if (tpos == tr->tlen || i1 == -1 || k1 == -1) Die("sanity check failed: didn't find a match state in trace"); /* Look backwards to find end of match */ for (tpos = tr->tlen-1; tpos >= 0; tpos--) { if (k2 == -1 && (tr->statetype[tpos] == STM || tr->statetype[tpos] == STD)) k2 = tr->nodeidx[tpos]; if (tr->statetype[tpos] == STM) { i2 = tr->pos[tpos]; break; } } if (tpos == tr->tlen || i2 == -1 || k2 == -1) Die("sanity check failed: didn't find a match state in trace"); *ret_k1 = k1; *ret_i1 = i1; *ret_k2 = k2; *ret_i2 = i2; } /* Function: MasterTraceFromMap() * Date: SRE, Tue Jul 7 18:51:11 1998 [St. Louis] * * Purpose: Convert an alignment map (e.g. hmm->map) to * a master trace. Used for mapping an alignment * onto an HMM. Generally precedes a call to * ImposeMasterTrace(). Compare P7ViterbiAlignAlignment(), * which aligns an alignment to the model using a * Viterbi algorithm to get a master trace. * MasterTraceFromMap() only works if the alignment * is exactly the one used to train the model. * * Args: map - the map (usually hmm->map is passed) 1..M * M - length of map (model; usually hmm->M passed) * alen - length of alignment that map refers to * * Returns: ptr to master trace * Caller must free: P7FreeTrace(). */ struct p7trace_s * MasterTraceFromMap(int *map, int M, int alen) { struct p7trace_s *tr; /* RETURN: master trace */ int tpos; /* position in trace */ int apos; /* position in alignment, 1..alen */ int k; /* position in model */ /* Allocate for the trace. * S-N-B- ... - E-C-T : 6 states + alen is maximum trace, * because each of alen columns is an N*, M*, I*, or C* metastate. * No D* metastates possible. */ P7AllocTrace(alen+6, &tr); /* Initialize the trace */ tpos = 0; TraceSet(tr, tpos, STS, 0, 0); tpos++; TraceSet(tr, tpos, STN, 0, 0); tpos++; /* Leading N's */ for (apos = 1; apos < map[1]; apos++) { TraceSet(tr, tpos, STN, 0, apos); tpos++; } /* now apos == map[1] */ TraceSet(tr, tpos, STB, 0, 0); tpos++; for (k = 1; k < M; k++) { TraceSet(tr, tpos, STM, k, apos); tpos++; apos++; for (; apos < map[k+1]; apos++) { TraceSet(tr, tpos, STI, k, apos); tpos++; } } /* now apos == map[M] and k == M*/ TraceSet(tr, tpos, STM, M, apos); tpos++; apos++; /* Trailing C's */ TraceSet(tr, tpos, STE, 0, 0); tpos++; TraceSet(tr, tpos, STC, 0, 0); tpos++; for (; apos <= alen; apos++) { TraceSet(tr, tpos, STC, 0, apos); tpos++; } /* Terminate and return */ TraceSet(tr, tpos, STT, 0, 0); tpos++; tr->tlen = tpos; return tr; } /* Function: ImposeMasterTrace() * Date: SRE, Sun Jul 5 14:27:16 1998 [St. Louis] * * Purpose: Goes with P7ViterbiAlignAlignment(), which gives us * a "master trace" for a whole alignment. Now, given * the alignment and the master trace, construct individual * tracebacks for each sequence. Later we'll hand these * (and presumably other traces) to P7Traces2Alignment(). * * It is possible to generate individual traces that * are not consistent with Plan7 (e.g. D->I and I->D * transitions may be present). P7Traces2Alignment() * can handle such traces; other functions may not. * See modelmaker.c:trace_doctor() if this is a problem. * * Akin to modelmaker.c:fake_tracebacks(). * * Args: aseq - aligned seqs * nseq - number of aligned seqs * mtr - master traceback * ret_tr- RETURN: array of individual tracebacks, one for each aseq * * Returns: (void) */ void ImposeMasterTrace(char **aseq, int nseq, struct p7trace_s *mtr, struct p7trace_s ***ret_tr) { struct p7trace_s **tr; int idx; /* counter over sequences */ int i; /* position in raw sequence (1..L) */ int tpos; /* position in traceback */ int mpos; /* position in master trace */ tr = (struct p7trace_s **) MallocOrDie (sizeof(struct p7trace_s *) * nseq); for (idx = 0; idx < nseq; idx++) { P7AllocTrace(mtr->tlen, &tr[idx]); /* we're guaranteed that individuals len < master len */ tpos = 0; i = 1; for (mpos = 0; mpos < mtr->tlen; mpos++) { switch (mtr->statetype[mpos]) { case STS: /* straight copies w/ no emission: S, B, D, E, T*/ case STB: case STD: case STE: case STT: TraceSet(tr[idx], tpos, mtr->statetype[mpos], mtr->nodeidx[mpos], 0); tpos++; break; case STM: /* M* implies M or D */ if (isgap(aseq[idx][mtr->pos[mpos]-1])) TraceSet(tr[idx], tpos, STD, mtr->nodeidx[mpos], 0); else { TraceSet(tr[idx], tpos, STM, mtr->nodeidx[mpos], i); i++; } tpos++; break; case STI: /* I* implies I or nothing */ if (!isgap(aseq[idx][mtr->pos[mpos]-1])) { TraceSet(tr[idx], tpos, STI, mtr->nodeidx[mpos], i); i++; tpos++; } break; case STJ: /* N,J,C: first N* -> N. After that, N* -> N or nothing. */ case STN: case STC: if (mtr->pos[mpos] == 0) { TraceSet(tr[idx], tpos, mtr->statetype[mpos], 0, 0); tpos++; } else if (!isgap(aseq[idx][mtr->pos[mpos]-1])) { TraceSet(tr[idx], tpos, mtr->statetype[mpos], 0, i); i++; tpos++; } break; case STBOGUS: Die("never happens. Trust me."); } } tr[idx]->tlen = tpos; } *ret_tr = tr; } /* Function: rightjustify() * * Purpose: Given a gap-containing string of length n, * pull all the non-gap characters as far as * possible to the right, leaving gaps on the * left side. Used to rearrange the positions * of insertions in HMMER alignments. */ static void rightjustify(char *s, int n) { int npos; int opos; npos = n-1; opos = n-1; while (opos >= 0) { if (isgap(s[opos])) opos--; else s[npos--]=s[opos--]; } while (npos >= 0) s[npos--] = '.'; } ugene-1.9.8/src/plugins_3rdparty/hmm2/src/hmmer2/vectorops.cpp0000644000175000017500000001315711651544326023004 0ustar ilyailya/***************************************************************** * HMMER - Biological sequence analysis with profile HMMs * Copyright (C) 1992-2003 Washington University School of Medicine * All Rights Reserved * * This source code is distributed under the terms of the * GNU General Public License. See the files COPYING and LICENSE * for details. *****************************************************************/ /* vectorops.c * Operations on vectors of floats or doubles. * * DSet(), FSet() - set all items in vector to value. * DScale(), FScale() - multiply all items in vector by scale * DSum(), FSum() - return sum of values in vector * DAdd(), FAdd() - add vec2 to vec1. * DCopy(), FCopy() - set vec1 to be same as vec2. * DDot(), FDot() - return dot product of two vectors. * DMax(), FMax() - return value of maximum element in vector * DMin(), FMin() - return value of minimum element in vector * DArgMax(), FArgMax() - return index of maximum element in vector * DArgMin(), FArgMin() - return index of minimum element in vector * * DNorm(), FNorm() - normalize a probability vector of length n. * DLog(), FLog() - convert to log probabilities * DExp(), FExp() - convert log p's back to probabilities * DLogSum(), FLogSum() - given vector of log p's; return log of summed p's. * * SRE, Tue Oct 1 15:23:25 2002 [St. Louis] * CVS $Id: vectorops.c,v 1.4 2003/04/14 16:00:16 eddy Exp $ */ #include "funcs.h" void DSet(double *vec, int n, double value) { int x; for (x = 0; x < n; x++) vec[x] = value; } void FSet(float *vec, int n, float value) { int x; for (x = 0; x < n; x++) vec[x] = value; } void DScale(double *vec, int n, double scale) { int x; for (x = 0; x < n; x++) vec[x] *= scale; } void FScale(float *vec, int n, float scale) { int x; for (x = 0; x < n; x++) vec[x] *= scale; } double DSum(double *vec, int n) { double sum = 0.; int x; for (x = 0; x < n; x++) sum += vec[x]; return sum; } float FSum(float *vec, int n) { float sum = 0.; int x; for (x = 0; x < n; x++) sum += vec[x]; return sum; } void DAdd(double *vec1, double *vec2, int n) { int x; for (x = 0; x < n; x++) vec1[x] += vec2[x]; } void FAdd(float *vec1, float *vec2, int n) { int x; for (x = 0; x < n; x++) vec1[x] += vec2[x]; } void DCopy(double *vec1, double *vec2, int n) { int x; for (x = 0; x < n; x++) vec1[x] = vec2[x]; } void FCopy(float *vec1, float *vec2, int n) { int x; for (x = 0; x < n; x++) vec1[x] = vec2[x]; } double DDot(double *vec1, double *vec2, int n) { double result = 0.; int x; for (x = 0; x < n; x++) result += vec1[x] * vec2[x]; return result; } float FDot(float *vec1, float *vec2, int n) { float result = 0.; int x; for (x = 0; x < n; x++) result += vec1[x] * vec2[x]; return result; } double DMax(double *vec, int n) { int i; double best; best = vec[0]; for (i = 1; i < n; i++) if (vec[i] > best) best = vec[i]; return best; } float FMax(float *vec, int n) { int i; float best; best = vec[0]; for (i = 1; i < n; i++) if (vec[i] > best) best = vec[i]; return best; } double DMin(double *vec, int n) { int i; double best; best = vec[0]; for (i = 1; i < n; i++) if (vec[i] < best) best = vec[i]; return best; } float FMin(float *vec, int n) { int i; float best; best = vec[0]; for (i = 1; i < n; i++) if (vec[i] < best) best = vec[i]; return best; } int DArgMax(double *vec, int n) { int i; int best = 0; for (i = 1; i < n; i++) if (vec[i] > vec[best]) best = i; return best; } int FArgMax(float *vec, int n) { int i; int best = 0; for (i = 1; i < n; i++) if (vec[i] > vec[best]) best = i; return best; } int DArgMin(double *vec, int n) { int i; int best = 0; for (i = 1; i < n; i++) if (vec[i] < vec[best]) best = i; return best; } int FArgMin(float *vec, int n) { int i; int best = 0; for (i = 1; i < n; i++) if (vec[i] < vec[best]) best = i; return best; } void DNorm(double *vec, int n) { int x; double sum; sum = DSum(vec, n); if (sum != 0.0) for (x = 0; x < n; x++) vec[x] /= sum; else for (x = 0; x < n; x++) vec[x] = 1. / (double) n; } void FNorm(float *vec, int n) { int x; float sum; sum = FSum(vec, n); if (sum != 0.0) for (x = 0; x < n; x++) vec[x] /= sum; else for (x = 0; x < n; x++) vec[x] = 1. / (float) n; } void DLog(double *vec, int n) { int x; for (x = 0; x < n; x++) if (vec[x] > 0.) vec[x] = log(vec[x]); else vec[x] = -DBL_MAX; } void FLog(float *vec, int n) { int x; for (x = 0; x < n; x++) if (vec[x] > 0.) vec[x] = log(vec[x]); else vec[x] = -FLT_MAX; } void DExp(double *vec, int n) { int x; for (x = 0; x < n; x++) vec[x] = exp(vec[x]); } void FExp(float *vec, int n) { int x; for (x = 0; x < n; x++) vec[x] = exp(vec[x]); } double DLogSum(double *vec, int n) { int x; double max, sum; max = DMax(vec, n); sum = 0.0; for (x = 0; x < n; x++) if (vec[x] > max - 50.) sum += exp(vec[x] - max); sum = log(sum) + max; return sum; } float FLogSum(float *vec, int n) { int x; float max, sum; max = FMax(vec, n); sum = 0.0; for (x = 0; x < n; x++) if (vec[x] > max - 50.) sum += exp(vec[x] - max); sum = log(sum) + max; return sum; } ugene-1.9.8/src/plugins_3rdparty/hmm2/src/HMMIO.h0000644000175000017500000000415511651544326020102 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_HMMIO_H_ #define _U2_HMMIO_H_ #include #include #include #include struct plan7_s; struct msa_struct; namespace U2 { class TaskStateInfo; class IOAdapterFactory; class HMMIO : public QObject { Q_OBJECT public: static void writeHMM2(IOAdapterFactory* iof, const QString& url, TaskStateInfo& si, plan7_s *hmm); static void readHMM2(IOAdapterFactory* iof, const QString& url, TaskStateInfo& si, plan7_s **ret_hmm); static plan7_s * cloneHMM( plan7_s * src ); //utility methods, TODO: move to a separate class static const QString HMM_ID; static const QString HMM_EXT; static QString getHMMFileFilter(); static DNAAlphabetType convertHMMAlphabet(int hmmAtype); }; class HMMReadTask: public Task { Q_OBJECT public: HMMReadTask(const QString& url); ~HMMReadTask(); void run(); plan7_s* getHMM() const {return hmm;} const QString& getURL() const {return url;} private: plan7_s* hmm; QString url; }; class HMMWriteTask : public Task { Q_OBJECT public: HMMWriteTask(const QString& url, plan7_s* s, uint = 0); virtual void run(); private: QString url; plan7_s* hmm; uint fileMode; }; }//namespace #endif ugene-1.9.8/src/plugins_3rdparty/hmm2/src/uHMMPlugin.h0000644000175000017500000000356211651544326021217 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_UHMMER_PLUGIN_H_ #define _U2_UHMMER_PLUGIN_H_ #include #include #include #include namespace U2 { class XMLTestFactory; class HMMMSAEditorContext; class HMMADVContext; class uHMMPlugin : public Plugin { Q_OBJECT public: uHMMPlugin(); ~uHMMPlugin(); private slots: void sl_build(); void sl_calibrate(); void sl_search(); private: HMMMSAEditorContext* ctxMSA; HMMADVContext* ctxADV; }; class HMMMSAEditorContext: public GObjectViewWindowContext { Q_OBJECT public: HMMMSAEditorContext(QObject* p); protected slots: void sl_build(); protected: virtual void initViewContext(GObjectView* view); virtual void buildMenu(GObjectView* v, QMenu* m); }; class HMMADVContext: public GObjectViewWindowContext { Q_OBJECT public: HMMADVContext(QObject* p); protected slots: void sl_search(); protected: virtual void initViewContext(GObjectView* view); }; } //namespace #endif ugene-1.9.8/src/plugins_3rdparty/hmm2/src/u_tests/0000755000175000017500000000000011651544312020534 5ustar ilyailyaugene-1.9.8/src/plugins_3rdparty/hmm2/src/u_tests/uhmmerTests.cpp0000644000175000017500000004503711651544327023577 0ustar ilyailya#include "uhmmerTests.h" #include #include "u_search/HMMSearchDialogController.h" #include "u_calibrate/HMMCalibrateTask.h" #include "u_build/HMMBuildDialogController.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include namespace U2 { #define HMM_FILE_ATTR "hmmfile" #define SEQ_DB_DOC "seqdoc" #define OUT_DOC_NAME_ATTR "outdoc" #define EXPERT_OPT_FLAG_ATTR "expert_opt" #define E_VALUE_CUTOFF_ATTR "evalue_cutoff" #define DOM_E_VALUE_CUTOFF_ATTR "domE_cutoff" #define MIN_SCORE_CUTOFF_ATTR "min_score_cutoff" #define NUMBER_OF_SEQ_ATTR "seq_in_db" #define PARALLEL_FLAG_ATTR "parallel" #define IN_FILE_NAME_ATTR "infile" #define OUT_FILE_NAME_ATTR "outfile" #define EXP_OPT_ATTR "expert" #define HMM_NAME_ATTR "hmmname" #define IN_FILE1_NAME_ATTR "file1" #define IN_FILE2_NAME_ATTR "file2" #define DEL_TEMP_FILE_ATTR "deltemp" #define HMMSEARCH_CHUNK_ATTR "chunksize" #define NUMBER_OF_THREADS_ATTR "nthreads" #define RUN_N_CALIBRATES "ncalibrates" #define MU_ATTR "mu" #define LAMBDA_ATTR "lambda" #define SEED_ATTR "seed" #define ENV_HMMSEARCH_ALGORITHM_NAME "HMMSEARCH_ALGORITHM" #define ENV_HMMSEARCH_ALGORITHM_SSE "sse" #define ENV_HMMSEARCH_ALGORITHM_CELL "cell" class GTest_LoadDocument; class Document; class GObject; class LoadDocumentTask; //**********uHMMER Search******************** /* TRANSLATOR U2::GTest */ void GTest_uHMMERSearch::init(XMLTestFormat *tf, const QDomElement& el) { Q_UNUSED(tf); evalueCutoff = 10; number_of_seq = 1; domEvalueCutoff = 0.9999999; minScoreCutoff = -FLT_MAX; hmmFileName = el.attribute(HMM_FILE_ATTR); if (hmmFileName.isEmpty()) { failMissingValue(HMM_FILE_ATTR); return; } resultDocContextName = el.attribute("index"); seqDocCtxName = el.attribute(SEQ_DB_DOC); if (seqDocCtxName.isEmpty()) { failMissingValue(SEQ_DB_DOC); return; } resultDocName = el.attribute(OUT_DOC_NAME_ATTR); QString exp_opt_str = el.attribute(EXPERT_OPT_FLAG_ATTR); if (exp_opt_str.isEmpty()) { failMissingValue(EXPERT_OPT_FLAG_ATTR); return; } bool ok=false; expertOptions = exp_opt_str.toInt(&ok); if(!ok) { failMissingValue(EXPERT_OPT_FLAG_ATTR); return; } if(expertOptions) { QString eval_catoff_str = el.attribute(E_VALUE_CUTOFF_ATTR); if (!eval_catoff_str.isEmpty()) { ok=false; evalueCutoff = eval_catoff_str.toFloat(&ok); if(!ok) { failMissingValue(E_VALUE_CUTOFF_ATTR); return; } } QString num_of_seq_str = el.attribute(NUMBER_OF_SEQ_ATTR); if (!num_of_seq_str.isEmpty()) { ok=false; number_of_seq = num_of_seq_str.toFloat(&ok); if(!ok) { failMissingValue(NUMBER_OF_SEQ_ATTR); return; } } QString domEvalueCutoff_str = el.attribute(DOM_E_VALUE_CUTOFF_ATTR); if (!domEvalueCutoff_str.isEmpty()) { ok=false; domEvalueCutoff = domEvalueCutoff_str .toFloat(&ok); if(!ok) { failMissingValue(DOM_E_VALUE_CUTOFF_ATTR); return; } } QString minScoreCutoff_str = el.attribute(MIN_SCORE_CUTOFF_ATTR); if (!minScoreCutoff_str.isEmpty()) { ok=false; minScoreCutoff = minScoreCutoff_str.toFloat(&ok); if(!ok) { failMissingValue(MIN_SCORE_CUTOFF_ATTR); return; } } } customHmmSearchChunk = false; QString hmmSearchChunk_str = el.attribute(HMMSEARCH_CHUNK_ATTR); if (!hmmSearchChunk_str.isEmpty()) { ok=false; hmmSearchChunk = hmmSearchChunk_str.toInt(&ok); if(!ok) { failMissingValue(HMMSEARCH_CHUNK_ATTR); return; } customHmmSearchChunk = true; } parallel_flag = false; QString parallel_flag_str = el.attribute(PARALLEL_FLAG_ATTR); if (!parallel_flag_str.isEmpty()) { if(parallel_flag_str == "true") parallel_flag = true; else if(parallel_flag_str == "false") parallel_flag = false; else { failMissingValue(PARALLEL_FLAG_ATTR); return; } } searchTask = NULL; saveTask = NULL; aDoc = NULL; } void GTest_uHMMERSearch::prepare() { Document* doc = getContext(this, seqDocCtxName); if (doc == NULL) { stateInfo.setError( QString("context not found %1").arg(seqDocCtxName) ); return; } QList list = doc->findGObjectByType(GObjectTypes::SEQUENCE); if (list.size() == 0) { stateInfo.setError( QString("container of object with type \"%1\" is empty").arg(GObjectTypes::SEQUENCE) ); return; } GObject *obj = list.first(); if(obj==NULL){ stateInfo.setError( QString("object with type \"%1\" not found").arg(GObjectTypes::SEQUENCE) ); return; } assert(obj!=NULL); DNASequenceObject * mySequence = qobject_cast(obj); if(mySequence==NULL){ stateInfo.setError( QString("error can't cast to sequence from GObject") ); return; } const DNASequence& dnaSequence = mySequence->getDNASequence(); UHMMSearchSettings s; if (expertOptions){ s.globE = evalueCutoff; s.eValueNSeqs = number_of_seq; s.domE = domEvalueCutoff; s.domT = minScoreCutoff; } QString env_algo = env->getVar(ENV_HMMSEARCH_ALGORITHM_NAME); if( !env_algo.isEmpty() ) { if( ENV_HMMSEARCH_ALGORITHM_SSE == env_algo ) { #if !defined(HMMER_BUILD_WITH_SSE2) stateInfo.setError( QString("SSE2 was not enabled in this build") ); return; #endif s.alg = HMMSearchAlgo_SSEOptimized; } else if( ENV_HMMSEARCH_ALGORITHM_CELL == env_algo ) { #if !defined UGENE_CELL stateInfo.setError( QString("HMMER-Cell was not enabled in this build") ); return; #endif s.alg = HMMSearchAlgo_CellOptimized; } else { stateInfo.setError( QString("unknown hmmsearch algorithm is selected") ); return; } } if(customHmmSearchChunk) { s.searchChunkSize = hmmSearchChunk; } QString annotationName = "hmm_signal"; QString url = env->getVar("TEMP_DATA_DIR")+"/uhmmsearch/"+resultDocName; IOAdapterFactory* iof = AppContext::getIOAdapterRegistry()->getIOAdapterFactoryById(BaseIOAdapters::url2io(url)); DocumentFormat* df = AppContext::getDocumentFormatRegistry()->getFormatById(BaseDocumentFormats::PLAIN_GENBANK); assert(aDoc == NULL); aDoc = df->createNewDocument(iof, url); AnnotationTableObject* ao = new AnnotationTableObject("Annotations"); aDoc->addObject(ao); searchTask = new HMMSearchToAnnotationsTask(env->getVar("COMMON_DATA_DIR")+"/"+hmmFileName, dnaSequence, ao, annotationName, annotationName, s); addSubTask(searchTask); } QList GTest_uHMMERSearch::onSubTaskFinished(Task* subTask) { Q_UNUSED(subTask); QList res; if (hasError() || isCanceled()) { return res; } if(saveTask && saveTask->isFinished()) { if (saveTask->hasError()) { stateInfo.setError( "SaveDocumentTask: "+saveTask->getError() ); } return res; } else if(searchTask!=NULL && searchTask->isFinished()) { if (searchTask->hasError()) { stateInfo.setError( searchTask->getError() ); return res; } if(aDoc == NULL) { stateInfo.setError( QString("documet creating error") ); return res; } if(!resultDocName.isEmpty()) { QFileInfo fi(aDoc->getURLString()); fi.absoluteDir().mkpath(fi.absoluteDir().absolutePath()); saveTask = new SaveDocumentTask(aDoc); res.append(saveTask); } return res; } return res; } Task::ReportResult GTest_uHMMERSearch::report() { if (!resultDocContextName.isEmpty()) { addContext(resultDocContextName, aDoc); } return ReportResult_Finished; } GTest_uHMMERSearch::~GTest_uHMMERSearch() { //cleanup(); } void GTest_uHMMERSearch::cleanup() { if (aDoc!=NULL) { delete aDoc; aDoc = NULL; } } //***************************************************************************** //**********uHMMER Build******************************************************* //***************************************************************************** void GTest_uHMMERBuild::init(XMLTestFormat* tf, const QDomElement& el) { Q_UNUSED(tf); QString inFile = el.attribute(IN_FILE_NAME_ATTR); if (inFile.isEmpty()) { failMissingValue(IN_FILE_NAME_ATTR); return; } outFile = el.attribute(OUT_FILE_NAME_ATTR); if (outFile.isEmpty()) { failMissingValue(OUT_FILE_NAME_ATTR); return; } QString expOpt = el.attribute(EXP_OPT_ATTR); if (expOpt.isEmpty()) { failMissingValue(EXP_OPT_ATTR); return; } QString hmmName = el.attribute(HMM_NAME_ATTR); QString delTempStr = el.attribute(DEL_TEMP_FILE_ATTR); if (delTempStr .isEmpty()) { failMissingValue(DEL_TEMP_FILE_ATTR); return; } if(delTempStr=="yes") deleteTempFile = true; else if(delTempStr=="no") deleteTempFile =false; else { failMissingValue(DEL_TEMP_FILE_ATTR); return; } UHMMBuildSettings s; s.name = hmmName; if(expOpt=="LS") s.strategy = P7_LS_CONFIG; else if(expOpt=="FS") s.strategy = P7_FS_CONFIG; else if(expOpt=="BASE") s.strategy = P7_BASE_CONFIG; else if(expOpt=="SW") s.strategy = P7_SW_CONFIG; else { stateInfo.setError( QString("invalid value %1, available values: LS, FS, BASE, SW").arg(EXP_OPT_ATTR) ); return; } QFileInfo fi(env->getVar("TEMP_DATA_DIR")+"/"+outFile); fi.absoluteDir().mkpath(fi.absoluteDir().absolutePath()); QFile createFile(fi.absoluteFilePath()); createFile.open(QIODevice::WriteOnly); if(!createFile.isOpen()){ stateInfo.setError( QString("File opening error \"%1\", description: ").arg(createFile.fileName())+createFile.errorString() ); return; } else createFile.close(); buildTask = new HMMBuildToFileTask(env->getVar("COMMON_DATA_DIR")+"/"+inFile, createFile.fileName(), s); outFile = createFile.fileName(); addSubTask(buildTask); } Task::ReportResult GTest_uHMMERBuild::report() { propagateSubtaskError(); if(buildTask->hasError()) { stateInfo.setError( buildTask->getError() ); } return ReportResult_Finished; } void GTest_uHMMERBuild::cleanup(){ if(deleteTempFile){ QFile::remove(outFile); } } void GTest_hmmCompare::init(XMLTestFormat* tf, const QDomElement& el) { Q_UNUSED(tf); file1Name = el.attribute(IN_FILE1_NAME_ATTR); if (file1Name.isEmpty()) { failMissingValue(IN_FILE1_NAME_ATTR); return; } file2Name= el.attribute(IN_FILE2_NAME_ATTR); if (file2Name.isEmpty()) { failMissingValue(IN_FILE2_NAME_ATTR); return; } } Task::ReportResult GTest_hmmCompare::report() { QFileInfo fi1(env->getVar("COMMON_DATA_DIR")+"/"+file1Name); QString url1 = fi1.absoluteFilePath(); IOAdapterFactory* iof1 = AppContext::getIOAdapterRegistry()->getIOAdapterFactoryById(BaseIOAdapters::url2io(url1)); std::auto_ptr io1(iof1->createIOAdapter()); //QFile file1(fi1.absoluteFilePath()); QFileInfo fi2(env->getVar("TEMP_DATA_DIR")+"/"+file2Name); QString url2 = fi2.absoluteFilePath(); IOAdapterFactory* iof2 = AppContext::getIOAdapterRegistry()->getIOAdapterFactoryById(BaseIOAdapters::url2io(url2)); std::auto_ptr io2(iof2->createIOAdapter()); fi2.absoluteDir().mkdir(fi2.absoluteDir().absolutePath()); // ??? //QFile file2(fi2.absoluteFilePath()); if(!io1->open(url1, IOAdapterMode_Read)){ stateInfo.setError( QString("File opening error \"%1\", description: ").arg(url1) );//+file1.errorString() ); return ReportResult_Finished; } //file2.open(QIODevice::ReadOnly|QIODevice::Text); if(!io2->open(url2, IOAdapterMode_Read)){ stateInfo.setError( QString("File opening error \"%1\", description: ").arg(url2) );//+file2.errorString() ); return ReportResult_Finished; } static int READ_BUFF_SIZE = 4096; qint64 len1, len2, line1 = 0, line2 = 0; QByteArray readBuffer1(READ_BUFF_SIZE, '\0'), readBuffer2(READ_BUFF_SIZE, '\0'); char* cbuff1 = readBuffer1.data(); char* cbuff2 = readBuffer2.data(); QRegExp rx("CKSUM "); bool ok = false; while ( (len1 = io1->readUntil(cbuff1, READ_BUFF_SIZE, TextUtils::LINE_BREAKS, IOAdapter::Term_Include)) > 0 ) { line1++; if ((ok = rx.indexIn(QString(QByteArray(cbuff1, len1))) !=-1)) { break; } } if(!ok){ stateInfo.setError( QString("can't find CKSUM in file \"%1\"").arg(url1) ); return ReportResult_Finished; } ok = false; while ( (len2 = io2->readUntil(cbuff2, READ_BUFF_SIZE, TextUtils::LINE_BREAKS, IOAdapter::Term_Include)) > 0 ) { line2++; if ((ok = rx.indexIn(QString(QByteArray(cbuff2, len2))) !=-1)) { break; } } if(!ok){ stateInfo.setError( QString("can't find CKSUM in file \"%1\"").arg(url2) ); return ReportResult_Finished; } do{ len1 = io1->readUntil(cbuff1, READ_BUFF_SIZE, TextUtils::LINE_BREAKS, IOAdapter::Term_Include); len2 = io2->readUntil(cbuff2, READ_BUFF_SIZE, TextUtils::LINE_BREAKS, IOAdapter::Term_Include); if(len1 == 0 && 0 != len2){ stateInfo.setError( QString("hmm-compare: files not equal, desc: files length mismatch") ); return ReportResult_Finished; } line1++;line2++; QString s1 = QString::fromAscii(cbuff1, len1).trimmed(); QString s2 = QString::fromAscii(cbuff2, len2).trimmed(); if(s1 != s2) { stateInfo.setError( QString("hmm-compare: files not equal, desc: file1, line %1 \"%2\", expected file2, line %3 \"%4\"") .arg(line1).arg(s1).arg(line2).arg(s2) ); return ReportResult_Finished; } } while(len1 > 0); return ReportResult_Finished; } //***************************************************************************** //**********uHMMER Calibrate*************************************************** //***************************************************************************** void GTest_uHMMERCalibrate::init(XMLTestFormat* tf, const QDomElement& el) { Q_UNUSED(tf); calibrateTask = NULL; QString hmmFile = el.attribute(HMM_FILE_ATTR); if (hmmFile.isEmpty()) { failMissingValue(HMM_FILE_ATTR); return; } QString mu_str = el.attribute(MU_ATTR); if (mu_str.isEmpty()) { failMissingValue(MU_ATTR); return; } bool ok=false; mu = mu_str.toFloat(&ok); if(!ok) { failMissingValue(MU_ATTR); return; } QString lambda_str = el.attribute(LAMBDA_ATTR); if (lambda_str.isEmpty()) { failMissingValue(LAMBDA_ATTR); return; } ok=false; lambda = lambda_str.toFloat(&ok); if(!ok) { failMissingValue(LAMBDA_ATTR); return; } QString nThreads_str = el.attribute(NUMBER_OF_THREADS_ATTR); if (nThreads_str.isEmpty()) { failMissingValue(NUMBER_OF_THREADS_ATTR); return; } ok=false; int nThreads = nThreads_str.toFloat(&ok); if(!ok) { failMissingValue(NUMBER_OF_THREADS_ATTR); return; } nCalibrates = 1; QString nCalibrates_str = el.attribute(RUN_N_CALIBRATES); if (!nCalibrates_str.isEmpty()) { bool ok=false; nCalibrates = nCalibrates_str.toInt(&ok); if(!ok) { failMissingValue(RUN_N_CALIBRATES); return; } } UHMMCalibrateSettings s; QString seed_str = el.attribute(SEED_ATTR); if (!seed_str.isEmpty()) { bool ok=false; int seed = seed_str.toInt(&ok); if(!ok) { failMissingValue(SEED_ATTR); return; } s.seed = seed; } calibrateTask = new HMMCalibrateToFileTask*[nCalibrates]; s.nThreads = nThreads; //Run nCalibrates HMMCalibrate tasks simultaneously for(int i=0;igetVar("COMMON_DATA_DIR")+"/"+hmmFile,env->getVar("TEMP_DATA_DIR")+"/temp111",s); } addSubTask(new GTest_uHMMERCalibrateSubtask(calibrateTask, nCalibrates)); } Task::ReportResult GTest_uHMMERCalibrate::report() { propagateSubtaskError(); if (isCanceled() || hasError()) { return ReportResult_Finished; } for(int i=0; i < nCalibrates; i++){ float new_mu = ((::plan7_s*)calibrateTask[i]->getHMM())->mu; if (qAbs(new_mu - mu) > 0.1) { stateInfo.setError( QString("mu value %1, expected %2").arg(new_mu).arg(mu) ); break; } float new_lambda = ((::plan7_s*)calibrateTask[i]->getHMM())->lambda; if (qAbs(new_lambda - lambda) > 0.1){ stateInfo.setError( QString("lambda value %1, expected %2").arg(new_lambda).arg(lambda) ); break; } } return ReportResult_Finished; } GTest_uHMMERCalibrate::GTest_uHMMERCalibrateSubtask::GTest_uHMMERCalibrateSubtask(HMMCalibrateToFileTask **calibrateTask, int n) :Task(tr("uhmmer-calibrate-subtask"),TaskFlags_NR_FOSCOE) { assert(calibrateTask!=NULL); for(int i=0;igetVar("TEMP_DATA_DIR")+"/temp111"); delete[] calibrateTask; } QList UHMMERTests::createTestFactories() { QList res; res.append(GTest_uHMMERSearch::createFactory()); res.append(GTest_uHMMERBuild::createFactory()); res.append(GTest_hmmCompare::createFactory()); res.append(GTest_uHMMERCalibrate::createFactory()); return res; } }//namespace ugene-1.9.8/src/plugins_3rdparty/hmm2/src/u_tests/uhmmerTests.h0000644000175000017500000000364011651544327023236 0ustar ilyailya#ifndef _U2_UHMMER_TESTS_H_ #define _U2_UHMMER_TESTS_H_ #include #include #include namespace U2 { class Document; class GTest_LoadDocument; class HMMCalibrateToFileTask; class HMMBuildToFileTask; class CreateAnnotationModel; struct plan7_s; class GTest_uHMMERSearch : public GTest { Q_OBJECT public: SIMPLE_XML_TEST_BODY_WITH_FACTORY(GTest_uHMMERSearch, "uhmmer-search"); ~GTest_uHMMERSearch(); void cleanup(); ReportResult report(); void prepare(); private: Task* searchTask; Task* saveTask; QString hmmFileName; QString seqDocCtxName; QString resultDocName; QString resultDocContextName; bool expertOptions; int number_of_seq; int hmmSearchChunk; bool customHmmSearchChunk; bool parallel_flag; float evalueCutoff; float domEvalueCutoff; float minScoreCutoff; Document* aDoc; protected: virtual QList onSubTaskFinished(Task* subTask); }; class GTest_uHMMERBuild: public GTest { Q_OBJECT SIMPLE_XML_TEST_BODY_WITH_FACTORY(GTest_uHMMERBuild, "uhmmer-build"); ReportResult report(); void cleanup(); private: QString outFile; HMMBuildToFileTask *buildTask; bool deleteTempFile; }; class GTest_hmmCompare: public GTest { Q_OBJECT SIMPLE_XML_TEST_BODY_WITH_FACTORY(GTest_hmmCompare, "hmm-compare"); ReportResult report(); private: QString file1Name; QString file2Name; }; class GTest_uHMMERCalibrate: public GTest { Q_OBJECT SIMPLE_XML_TEST_BODY_WITH_FACTORY(GTest_uHMMERCalibrate, "uhmmer-calibrate"); ReportResult report(); void cleanup(); private: class GTest_uHMMERCalibrateSubtask: public Task { public: GTest_uHMMERCalibrateSubtask(HMMCalibrateToFileTask **calibrateTask, int n); }; HMMCalibrateToFileTask **calibrateTask; float mu; float lambda; int nCalibrates; }; class UHMMERTests { public: static QList createTestFactories(); }; }//namespace #endif ugene-1.9.8/src/plugins_3rdparty/hmm2/transl/0000755000175000017500000000000011651544312017562 5ustar ilyailyaugene-1.9.8/src/plugins_3rdparty/hmm2/transl/russian.ts0000644000175000017500000021242011651544327021625 0ustar ilyailya HMMBuildDialog ... hmmbuild_dialog_title Построение HMM профайла msa_file_label Файл множественного выравнивания: result_hmm_label Файл HMM профайла expert_options Экспертные настройки name Имя HMM профайла: default_hmmls Стандартное поведение (hmmls) multi_domain_hmmfs Эмуляция hmmfs single_global_hmms Эмуляция hmms single_local_hmmsw Эмуляция hmmsw ok_button Построить name_tip Удобное для человека имя профайла, не должно содержать пропусков default_hmmls_tip По умолчанию, профайл настраивается на поиск одного или более неперекрывающихся выравниваний к полной модели: множественные выравнивания глобальные относительно профайла, локальные относительно последовательности multi_domain_hmmfs_tip Профайл настраивается на поиск множественных доменов, каждый из которых может быть локальным (фрагментарным) выравниванием. Это аналог программы hmmfs пакета HMMER 1 single_global_hmms_tip Профайл настраивается на поиск единственного глобального выравнивания в целевой последовательности. Это аналог программы hmms пакета HMMER 1 single_local_hmmsw_tip Профайл настраивается на поиск единственного локального выравнивания в целевой последовательности. Это аналог стандартного алгоритма Смита-Ватермана или программы hmmsw пакета HMMER 1 close_button Закрыть HMMCalibrateDialog hmm_file_name Файл c HMM профайлом ... expert_options Экспертные настройки mean Средняя длина последовательностей num Количество последовательностей sd Стандартное отклонение seed Случайная затравка: fixed Фиксированная длина случайных последовательностей output_file_name Сохранить откалиброванный HMM профайл ok_button Калибровать hmmcalibrate_dialog_title Калибровка HMM профайла fixed_tip Фиксированная длина случайных последовательностей, положительное число разумной величины. По умолчанию, генерируются последовательности с нормальным (Гауссовым) распределением по длине. mean_tip Средняя длина синтетических последовательностей. Положительное число, 325 по умолчанию num_tip Количество синтетических последовательностей. Значение по умолчанию (5000) было эмпирически определено как компромисс между точностью и временем вычисления sd_tip Стандартное отклонение длины синтетической последовательности. Должно быть больше нуля, по умолчанию 200. seed_tip Случайная затравка положительным целым числом. По умолчанию используется текущее время в миллисекундах для каждого запуска,что приводит к небольшим и незначительным различиям при каждой калибровке одного и того же профайла. Вы можете использовать эту опцию для получения воспроизводимых результатов калибровки. close_button Закрыть HMMSearchDialog ... hmm_search_dialog_title Поиск HMM сигналов в последовательности hmm_file Файл HMM профайла expert_box_title Экспертные настройки e_value_as_n_seq Количество последовательностей в базе ok_button Искать e_value_as_nsec_tip Считать Е-величину как если бы имелась база из <n> последовательностей close_button Закрыть 1E 1e results_evalue_cutoff Отбрасывать результаты с Е-величиной более results_score_cutoff_tip Помогает исключить мало-вероятные сигналы results_score_cutoff Отбрасывать результаты с итоговой суммой меньше results_evalue_cutoff_tip Отбрасывание результатов по Е-величине помогает исключить мало-вероятные сигналы algo_combo_tip Версии алгоритма Algorithm Алгоритм U2::GTest_uHMMERCalibrate uhmmer-calibrate-subtask U2::HMMADVContext Search with HMM model... HMMER2: поиск сигналов хмм-модели... error Внимание no_sequence_found Не выбрана последовательность U2::HMMBuildDialogController incorrect_ali_file Некорректный файл выравнивания incorrect_hmm_file Укажите файл с HMM профайлом error Ошибка starting_build_process Начинается построение back_button Скрыть build_finished_with_errors_%1 Построение HMM профайла завершилось с ошибкой: %1 build_finished_successfuly HMM профайл успешно построен ok_button Построить progress_%1% Прогресс %1% cancel_button Отменить close_button Закрыть build_canceled Построение HMM профайла отменено select_file_with_alignment Выберете файл с выравниванием Select file with HMM profile Выберете файл с HMM профайлом U2::HMMBuildTask multiple_alignment_is_empty Выравнивание не содержит данных multiple_alignment_is_0_len Выравнивание длины 0 miltiple_alignment_is_not_consistent Выравнивание не нормализовано only_amino_and_nucl_alphabets_are_supported Неподдерживаемый тип алфавита error_creating_msa Недостаточно памяти для построения выравнивания Build HMM profile '%1' Построение HMM профала '%1' U2::HMMBuildToFileTask alignment_object_not_found Объект выравнивания не найден none нет input_format_error Не могу определить тип файла Build HMM profile '%1' -> '%2' Построение HMM профайла '%1'->'%2' Build HMM profile to '%1' Построение HMM профайла '%1' Incorrect input file Source alignment Исходное выравнивание Profile name Имя профайла Task was not finished Задача была не завершена Profile file Файл Expert options Дополнительные опции U2::HMMCalibrateDialogController select_file_with_hmm_model Выбор HMM профайла для калибровки illegal_in_file_name Не указан файл c исходным HMM профайлом illegal fixed value Некорректное значение фиксированной длины последовательностей illegal_out_file_name Не указан файл для сохранения результата error Ошибка starting_calibration_process Начинается калибрование back_button Скрыть calibration_finished_with_errors_%1 Калибрование завершено с ошибкой: %1 calibration_finished_successfuly Калибрование успешно завершено ok_button Калибровать progress_%1% Прогресс %1% cancel_button Отменить close_button Закрыть calibration_canceled Калибрование отменено U2::HMMCalibrateParallelSubTask Parallel HMM calibration subtask Подзадача параллельного калибрования U2::HMMCalibrateParallelTask HMM calibrate '%1' HMM калибровка '%1' U2::HMMCalibrateTask HMM calibrate '%1' HMM калибровка '%1' U2::HMMCalibrateToFileTask HMM calibrate '%1' HMM калибровка '%1' Source profile Исходный профайл Task was not finished Задача была не завершена Result profile Файл результата Expert options Дополнительные опции Number of random sequences to sample Кол-во случайных синтетических последовательностей Random number seed Затравка Mean of length distribution Средняя длина синтетических последовательностей Standard deviation of length distribution Стандартное отклонение средней длины Calculated evidence (mu , lambda) Вычисленная вероятность (мю, лямбда) U2::HMMCreateWPoolTask Initialize parallel context Инициализация контекста U2::HMMIO illegal line Ошибка формата file_format_is_not_supported Формат не поддерживается value is illegal %1 Некорректное значение: "%1" invalid_file_structure_near_%1 Некорректная структура файла вблизи "%1" value is not set for %1 Не установлено значение для "%1" no // symbol found Не найден маркер конца структуры: '//' alphabet_not_set Не установлен алфавит ALPH must precede NULE in HMM save files HMM models Профайлы HMM U2::HMMMSAEditorContext do_hmmbuild Построить HMM профайл ... Build HMMER2 profile U2::HMMReadTask Read HMM profile '%1' Чтение HMM профайла '%1' U2::HMMSearchDialogController select_file_with_hmm_model Выбор HMM профайла hmm_file_not_set Укажите файл с HMM профайлом error Внимание starting_search_process Начинается поиск back_button Скрыть search_finished_with_errors_%1 Поиск завершен с ошибкой: %1 search_finished_successfuly Поиск успешно завершен ok_button Искать progress_%1% Прогресс %1% cancel_button Отменить close_button Закрыть Cell BE optimized Оптимизирован для Cell BE SSE optimized Оптимизирован для SSE Conservative Стандартный U2::HMMSearchTask parallel_hmm_search_task Параллельный поиск HMM сигналов invalid_hmm_alphabet_type Неправильный алфавит HMM профайла invalid_sequence_alphabet_type Неправильный алфавит последовательности can_t_find_amino Не найдена таблица аминокислотной трансляции для выбранной последовательности HMM search with '%1' Поиск с HMM профайлом '%1' U2::HMMSearchToAnnotationsTask raw_alphabet_not_supported Неправильный алфавит последовательности annotation_obj_removed Объект аннотаций был удалён HMM search, file '%1' HMM поиск, файл '%1' HMM profile used Использованный HMM профайл Task was not finished Задача была не завершена Result annotation table Таблица аннотаций результата Result annotation group Группа аннотаций результата Result annotation name Имя аннотаций результата Results count Количество найденных регионов U2::HMMWriteTask Write HMM profile '%1' Запись HMM профайла '%1' U2::LocalWorkflow::HMMBuildPrompter For each MSA from <u>%1</u>, Для каждого выравнивания из <u>%1</u>, and calibrate и калибровать default настройки по умолчанию custom выбранные настройки %1 build%2 HMM profile using <u>%3</u> settings. %1 построить%2 HMM профайл используя <u>%3</u>. U2::LocalWorkflow::HMMBuildWorker Built HMM profile Построен профайл HMM Calibrated HMM profile Откалиброван профайл HMM. HMM build Построить HMM HMM profile Профайл HMM HMM strategy Стратегия HMM Profile name Имя профайла Calibrate profile Калибровать Parallel calibration Параллельная калибрация Fixed length of samples Фиксированная длина сэмплов Mean length of samples Средняя длина сэмплов Number of samples Число сэмплов Standard deviation Стандартное отклонение Random seed Затравка Incorrect value for seed parameter Schema name not specified. Using default value: '%1' Input MSA Входное выравнивание Input multiple sequence alignment for building statistical model. Множественное выравнивание последовательностей для построения статистической модели. Produced HMM profile Произведённый профайл HMM Specifies kind of alignments you want to allow Выбор типа искомого выравнивания. Descriptive name of the HMM profile Описательное имя целевого профайла HMM. Enables/disables optional profile calibration.<p>An empirical HMM calibration costs time but it only has to be done once per model, and can greatly increase the sensitivity of a database search. Включить/выключить калибрацию профайлов. <p>Однократная калибрация случайными синтетическими последовательностями занимает некоторое время, но может существенно улучшить чувствительность поиска. Number of parallel threads that the calibration will run in. Число потоков для параллельной калибрации. Builds a HMM profile from a multiple sequence alignment.<p>The HMM profile is a statistical model which captures position-specific information about how conserved each column of the alignment is, and which residues are likely. Строит профайлы HMM по входящим множественным выравниваниям. <p> Default По умолчанию U2::LocalWorkflow::HMMLib HMMER2 tools Программы HMMER2 HMM Profile Профайл HMM HMM profile Профайл HMM Location Адрес Read HMM profile Читать HMM профайл Write HMM profile Сохранить HMM профайл Location of the data file. Адрес файла данных. Input HMM profile Входной профайл HMM Location hint for the target file. Адрес файла для записи Saves all input HMM profiles to specified location. Сохраняет все входящие профайлы HMM в указанный файл. Reads HMM profiles from file(s). The files can be local or Internet URLs. Считывает профайлы HMM из одного или нескольких файлов. Файлы могут быть локальными или адресами Интернет. Loaded HMM profile Загруженный профайл HMM U2::LocalWorkflow::HMMReadPrompter Read HMM profile(s) from %1 Загрузить HMM профайл(ы) из %1 U2::LocalWorkflow::HMMReader Loaded HMM profile from %1 Загружен HMM профайл из %1 U2::LocalWorkflow::HMMSearchPrompter For each sequence from <u>%1</u>, Для каждой последовательности из <u>%1</u>, Use <u>default</u> settings. Использовать настройки <u>по умолчанию</u>. Use <u>custom</u> settings. Использовать <u>указанные</u> настройки. %1 search HMM signals %2. %3<br>Output the list of found regions annotated as <u>%4</u>. %1 искать HMM сигналы %2. %3<br>Выдать список найденных регионов аннотированных как <u>%4</u>. using all profiles provided by <u>%1</u>, со всеми профайлами из <u>%1</u>, U2::LocalWorkflow::HMMSearchWorker Bad sequence supplied to input: %1 Found %1 HMM signals Найдено %1 сигналов HMM HMM profile HMM профайл Input sequence Входная последовательность HMM annotations Аннотации Result annotation Имя аннотации Number of seqs Число последовательностей Filter by high E-value Фильтр на большие Е Filter by low score Фильтр на малые веса HMM search Поиск HMM Power of e-value must be less or equal to zero. Using default value: 1e-1 Value for attribute name is empty, default name used Search HMM signals in %1 Поиск HMM сигналов в последовательности '%1' HMM profile(s) to search with. HMM профайлы для поиска. An input sequence (nucleotide or protein) to search in. Входная последовательность для поиска (протеиновая или нуклеотидная). Annotations marking found similar sequence regions. Аннотации размечающие найденные регионы совпадения с HMM. A name of the result annotations. Имя аннотации для разметки результатов. Searches each input sequence for significantly similar sequence matches to all specified HMM profiles. In case several profiles were supplied, searches with all profiles one by one and outputs united set of annotations for each sequence Ищет значимые совпадения с указанными HMM профайлами в каждой входной последовательности и выдаёт набор аннотированных регионов. Профайлов может быть несколько, поиск отработает для каждого профайла и выдаст общий набор аннотаций для каждой последовательности. U2::LocalWorkflow::HMMWritePrompter unset Save HMM profile(s) from <u>%1</u> to <u>%2</u>. Сохранить HMM профайл(ы) из <u>%1</u> в <u>%2</u>. U2::LocalWorkflow::HMMWriter Empty HMM passed for writing to %1 Unspecified URL for writing HMM Writing HMM profile to %1 Запись HMM профайла '%1' U2::UHMMBuild bogus configuration choice U2::UHMMSearch UHMMSearch U2::uHMMPlugin uhmm_plugin HMM2 uhmm_plugin_desc Основан на пакете HMMER 2.3.2: анализ биологических последовательностей при помощи скрытых марковских моделей (HMM). Домашняя страница проекта: http://hmmer.janelia.org/. Включает в себя оригинальные оптимизированные версии алгоритмов hmmcalibrate Калибровать HMM профайл hmmbuild Построить HMM профайл hmmsearch Искать сигналы HMM Build HMM2 profile Построить профайл с помощью HMM2 Calibrate profile with HMM2 Калибровать профайл с помощью HMM2 Search with HMM2 Искать сигналы HMM2 HMMER tools HMMER (Скрытые модели Маркова) error Внимание neither_annotatedview_nor_pv_selection_found Сначала выберите последовательность HMMER2 tools HMMER2 (Скрытые Модели Маркова) ugene-1.9.8/src/plugins_3rdparty/hmm2/transl/czech.ts0000644000175000017500000016315011651544327021242 0ustar ilyailya U2::GTest_uHMMERCalibrate::GTest_uHMMERCalibrateSubtask uhmmer-calibrate-subtask U2::HMMADVContext do_hmmsearch Search with HMM model ... error Error! no_sequence_found No sequences found U2::HMMBuildDialogController incorrect_ali_file Incorrect alignment file! incorrect_hmm_file Incorrect HMM file! error Error! starting_build_process Starting build process back_button Hide build_finished_with_errors_%1 HMM build finished with errors: %1 build_finished_successfuly HMM build finished successfuly! ok_button Build progress_%1% Progress: %1% cancel_button Cancel close_button Close build_canceled HMM build canceled select_file_with_alignment Select file with alignment Select file with HMM profile U2::HMMBuildTask multiple_alignment_is_empty Multiple alignment is empty multiple_alignment_is_0_len Multiple alignment is of 0 length miltiple_alignment_is_not_consistent Multiple alignment is not consistent only_amino_and_nucl_alphabets_are_supported Invalid alphabet! Only amino and nucleic alphabets are supported error_creating_msa Error creating MSA structure Build HMM profile '%1' U2::HMMBuildToFileTask alignment_object_not_found Alignment object not found! none none input_format_error Error reading alignment file Build HMM profile '%1' -> '%2' Build HMM profile to '%1' Source alignment Profile name Task was not finished Profile file Expert options U2::HMMCalibrateDialogController select_file_with_hmm_model Select file with HMM model illegal_in_file_name Incorrect HMM file! illegal fixed value Illegal fixed length value! illegal_out_file_name Invalid output file name error Error! starting_calibration_process Starting calibration process back_button Hide calibration_finished_with_errors_%1 Calibration finished with errors: %1 calibration_finished_successfuly Calibration finished successfuly! ok_button Calibrate progress_%1% Progress: %1% cancel_button Cancel close_button Close calibration_canceled Calibration was cancelled U2::HMMCalibrateParallelSubTask Parallel HMM calibration subtask U2::HMMCalibrateParallelTask HMM calibrate '%1' U2::HMMCalibrateTask HMM calibrate '%1' U2::HMMCalibrateToFileTask HMM calibrate '%1' Source profile Task was not finished Result profile Expert options Number of random sequences to sample Random number seed Mean of length distribution Standard deviation of length distribution Calculated evidence (mu , lambda) U2::HMMCreateWPoolTask Initialize parallel context U2::HMMIO illegal line Illegal line file_format_is_not_supported File format is not supported value is illegal %1 Value is illegal: %1 invalid_file_structure_near_%1 Invalid file structure near %1 ALPH must precede NULE in HMM save files ALPH must precede NULE in HMM save files value is not set for %1 Value is not set for '%1' no // symbol found No '//' symbol found alphabet_not_set Alphabet is not set HMM models U2::HMMMSAEditorContext do_hmmbuild Build HMM model from alignment U2::HMMReadTask Read HMM profile '%1' U2::HMMSearchDialogController select_file_with_hmm_model Select file with HMM model hmm_file_not_set HMM file not set! error Error! starting_search_process Starting search process.. back_button Hide search_finished_with_errors_%1 HMM search finished with error: %1 search_finished_successfuly HMM search finished successfuly! ok_button Search progress_%1% Progress: %1% cancel_button Cancel close_button Close Cell BE optimized SSE optimized Conservative U2::HMMSearchTask parallel_hmm_search_task Parallel HMM search invalid_hmm_alphabet_type Invalid HMM alphabet! invalid_sequence_alphabet_type Invalid sequence alphabet! can_t_find_amino Amino translation is not available for the sequence alphabet! HMM search with '%1' U2::HMMSearchToAnnotationsTask raw_alphabet_not_supported RAW alphabet is not supported! annotation_obj_removed Annotation object was removed HMM search, file '%1' HMM profile used Task was not finished Result annotation table Result annotation group Result annotation name Results count U2::HMMWriteTask Write HMM profile '%1' U2::LocalWorkflow::HMMBuildPrompter For each MSA from <u>%1</u>, and calibrate default custom %1 build%2 HMM profile using <u>%3</u> settings. U2::LocalWorkflow::HMMBuildWorker Built HMM profile Calibrated HMM profile HMM build HMM profile HMM strategy Profile name Calibrate profile Parallel calibration Fixed length of samples Mean length of samples Number of samples Standard deviation Random seed Input MSA Input multiple sequence alignment for building statistical model. Produced HMM profile Specifies kind of alignments you want to allow Descriptive name of the HMM profile Enables/disables optional profile calibration.<p>An empirical HMM calibration costs time but it only has to be done once per model, and can greatly increase the sensitivity of a database search. Number of parallel threads that the calibration will run in. Builds a HMM profile from a multiple sequence alignment.<p>The HMM profile is a statistical model which captures position-specific information about how conserved each column of the alignment is, and which residues are likely. Default U2::LocalWorkflow::HMMLib HMM Profile HMMER tools HMM profile Location Read HMM profile Write HMM profile Location of the data file. Input HMM profile Location hint for the target file. Saves all input HMM profiles to specified location. Reads HMM profiles from file(s). The files can be local or Internet URLs. Loaded HMM profile U2::LocalWorkflow::HMMReadPrompter Read HMM profile(s) from %1 U2::LocalWorkflow::HMMReader Loaded HMM profile from %1 U2::LocalWorkflow::HMMSearchPrompter For each sequence from <u>%1</u>, Use <u>default</u> settings. Use <u>custom</u> settings. %1 search HMM signals %2. %3<br>Output the list of found regions annotated as <u>%4</u>. using all profiles provided by <u>%1</u>, U2::LocalWorkflow::HMMSearchWorker Bad sequence supplied to input: %1 Found %1 HMM signals HMM profile Input sequence HMM annotations Result annotation Number of seqs Filter by high E-value Filter by low score HMM search Search HMM signals in %1 HMM profile(s) to search with. An input sequence (nucleotide or protein) to search in. Annotations marking found similar sequence regions. A name of the result annotations. Searches each input sequence for significantly similar sequence matches to all specified HMM profiles. In case several profiles were supplied, searches with all profiles one by one and outputs united set of annotations for each sequence U2::LocalWorkflow::HMMWritePrompter Save HMM profile(s) from <u>%1</u> to <u>%2</u>. U2::LocalWorkflow::HMMWriter Empty HMM passed for writing to %1 Unspecified URL for writing HMM Writing HMM profile to %1 U2::UHMMBuild bogus configuration choice U2::uHMMPlugin uhmm_plugin HMM2 uhmm_plugin_desc Based on HMMER 2.3.2 package Biological sequence analysis using profile hidden Markov models hmmcalibrate HMM calibrate hmmbuild HMM build hmmsearch HMM search error Error! neither_annotatedview_nor_pv_selection_found Error! Select sequence in Project view or open sequence view HMMER2 tools HMMBuildDialog ... ... hmmbuild_dialog_title HMM build msa_file_label Multiple alignment file: result_hmm_label File to save HMM profile: expert_options Expert options name Name this HMM: default_hmmls Default (hmmls) behaviour: multi_domain_hmmfs Emulate hmmfs behaviour: single_global_hmms Emulate hmms behaviour: single_local_hmmsw Emulate hmmsw behaviour: ok_button Build name_tip Name can be any string of non-whitespace characters (e.g. one ”word”). default_hmmls_tip By default, the model is configured to find one or more nonoverlapping alignments to the complete model: multiple global alignments with respect to the model, and local with respect to the sequence multi_domain_hmmfs_tip Configure the model for finding multiple domains per sequence, where each domain can be a local (fragmentary) alignment. This is analogous to the old hmmfs program of HMMER 1. single_global_hmms_tip Configure the model for finding a single global alignment to a target sequence, analogous to the old hmms program of HMMER 1. single_local_hmmsw_tip Configure the model for finding a single local alignment per target sequence. This is analogous to the standard Smith/Waterman algorithm or the hmmsw program of HMMER 1. close_button Close HMMCalibrateDialog hmm_file_name HMM file: ... ... expert_options Expert options mean Mean length of the synthetic sequences: num Number of synthetic sequences: sd Standard deviation: seed Random seed: fixed Fix the length of the random sequences to: output_file_name Save calibrated profile to file: ok_button Calibrate hmmcalibrate_dialog_title HMM calibrate fixed_tip Fix the length of the random sequences to <n>, where <n> is a positive (and reasonably sized) integer. The default is instead to generate sequences with a variety of different lengths, controlled by a Gaussian (normal) distribution mean_tip Mean length of the synthetic sequences, positive real number. The default value is 325 num_tip Number of synthetic sequences. If <n> is less than about 1000, the fit to the EVD may fail Higher numbers of <n> will give better determined EVD parameters. The default is 5000; it was empirically chosen as a tradeoff between accuracy and computation time sd_tip Standard deviation of the synthetic sequence length. A positive number. The default is 200. Note that the Gaussian is left-truncated so that no sequences have lengths <= 0. seed_tip The random seed, where <n> is a positive integer. The default is to use time() to generate a different seed for each run, which means that two different runs of hmmcalibrate on the same HMM will give slightly different results. You can use this option to generate reproducible results for different hmmcalibrate runs on the same HMM. close_button Close HMMSearchDialog ... ... hmm_search_dialog_title HMM search hmm_file File with HMM profile: expert_box_title Expert options e_value_as_n_seq Number of sequences in dababase: ok_button Search e_value_as_nsec_tip Calculate the E-value scores as if we had seen a sequence database of <n> sequences. close_button Close 1E 1e results_evalue_cutoff Filter results with E-value greater then: results_score_cutoff_tip Score based filtering is an alternative to E-value filtering to exclude low-probability hits from result results_score_cutoff Filter results with Score lower than: results_evalue_cutoff_tip E-value filtering can be used to exclude low-probability hits from result algo_combo_tip Variants of algorithm Algorithm UHMMSearch UHMMSearch HMM2 Search ugene-1.9.8/src/plugins_3rdparty/hmm2/transl/english.ts0000644000175000017500000016667711651544327021620 0ustar ilyailya HMMBuildDialog ... ... hmmbuild_dialog_title HMM build msa_file_label Multiple alignment file: result_hmm_label File to save HMM profile: expert_options Expert options name Name this HMM: default_hmmls Default (hmmls) behaviour: multi_domain_hmmfs Emulate hmmfs behaviour: single_global_hmms Emulate hmms behaviour: single_local_hmmsw Emulate hmmsw behaviour: ok_button Build name_tip Name can be any string of non-whitespace characters (e.g. one ”word”). default_hmmls_tip By default, the model is configured to find one or more nonoverlapping alignments to the complete model: multiple global alignments with respect to the model, and local with respect to the sequence multi_domain_hmmfs_tip Configure the model for finding multiple domains per sequence, where each domain can be a local (fragmentary) alignment. This is analogous to the old hmmfs program of HMMER 1. single_global_hmms_tip Configure the model for finding a single global alignment to a target sequence, analogous to the old hmms program of HMMER 1. single_local_hmmsw_tip Configure the model for finding a single local alignment per target sequence. This is analogous to the standard Smith/Waterman algorithm or the hmmsw program of HMMER 1. close_button Close HMMCalibrateDialog hmm_file_name HMM file: ... ... expert_options Expert options mean Mean length of the synthetic sequences: num Number of synthetic sequences: sd Standard deviation: seed Random seed: fixed Fix the length of the random sequences to: output_file_name Save calibrated profile to file: ok_button Calibrate hmmcalibrate_dialog_title HMM calibrate fixed_tip Fix the length of the random sequences to <n>, where <n> is a positive (and reasonably sized) integer. The default is instead to generate sequences with a variety of different lengths, controlled by a Gaussian (normal) distribution mean_tip Mean length of the synthetic sequences, positive real number. The default value is 325 num_tip Number of synthetic sequences. If <n> is less than about 1000, the fit to the EVD may fail Higher numbers of <n> will give better determined EVD parameters. The default is 5000; it was empirically chosen as a tradeoff between accuracy and computation time sd_tip Standard deviation of the synthetic sequence length. A positive number. The default is 200. Note that the Gaussian is left-truncated so that no sequences have lengths <= 0. seed_tip The random seed, where <n> is a positive integer. The default is to use time() to generate a different seed for each run, which means that two different runs of hmmcalibrate on the same HMM will give slightly different results. You can use this option to generate reproducible results for different hmmcalibrate runs on the same HMM. close_button Close HMMSearchDialog ... ... hmm_search_dialog_title HMM search hmm_file File with HMM profile: expert_box_title Expert options e_value_as_n_seq Number of sequences in dababase: ok_button Search e_value_as_nsec_tip Calculate the E-value scores as if we had seen a sequence database of <n> sequences. close_button Close 1E 1e results_evalue_cutoff Filter results with E-value greater then: results_score_cutoff_tip Score based filtering is an alternative to E-value filtering to exclude low-probability hits from result results_score_cutoff Filter results with Score lower than: results_evalue_cutoff_tip E-value filtering can be used to exclude low-probability hits from result algo_combo_tip Variants of algorithm Algorithm U2::GTest_uHMMERCalibrate uhmmer-calibrate-subtask U2::HMMADVContext Search with HMM model... error Error! no_sequence_found No sequences found U2::HMMBuildDialogController incorrect_ali_file Incorrect alignment file! incorrect_hmm_file Incorrect HMM file! error Error! starting_build_process Starting build process back_button Hide build_finished_with_errors_%1 HMM build finished with errors: %1 build_finished_successfuly HMM build finished successfuly! ok_button Build progress_%1% Progress: %1% cancel_button Cancel close_button Close build_canceled HMM build canceled select_file_with_alignment Select file with alignment Select file with HMM profile U2::HMMBuildTask multiple_alignment_is_empty Multiple alignment is empty multiple_alignment_is_0_len Multiple alignment is of 0 length miltiple_alignment_is_not_consistent Multiple alignment is not consistent only_amino_and_nucl_alphabets_are_supported Invalid alphabet! Only amino and nucleic alphabets are supported error_creating_msa Error creating MSA structure Build HMM profile '%1' U2::HMMBuildToFileTask alignment_object_not_found Alignment object not found! none none input_format_error Error reading alignment file Build HMM profile '%1' -> '%2' Build HMM profile to '%1' Incorrect input file Source alignment Profile name Task was not finished Profile file Expert options U2::HMMCalibrateDialogController select_file_with_hmm_model Select file with HMM model illegal_in_file_name Incorrect HMM file! illegal fixed value Illegal fixed length value! illegal_out_file_name Invalid output file name error Error! starting_calibration_process Starting calibration process back_button Hide calibration_finished_with_errors_%1 Calibration finished with errors: %1 calibration_finished_successfuly Calibration finished successfuly! ok_button Calibrate progress_%1% Progress: %1% cancel_button Cancel close_button Close calibration_canceled Calibration was cancelled U2::HMMCalibrateParallelSubTask Parallel HMM calibration subtask U2::HMMCalibrateParallelTask HMM calibrate '%1' U2::HMMCalibrateTask HMM calibrate '%1' U2::HMMCalibrateToFileTask HMM calibrate '%1' Source profile Task was not finished Result profile Expert options Number of random sequences to sample Random number seed Mean of length distribution Standard deviation of length distribution Calculated evidence (mu , lambda) U2::HMMCreateWPoolTask Initialize parallel context U2::HMMIO illegal line Illegal line file_format_is_not_supported File format is not supported value is illegal %1 Value is illegal: %1 invalid_file_structure_near_%1 Invalid file structure near %1 ALPH must precede NULE in HMM save files ALPH must precede NULE in HMM save files value is not set for %1 Value is not set for '%1' no // symbol found No '//' symbol found alphabet_not_set Alphabet is not set HMM models U2::HMMMSAEditorContext do_hmmbuild Build HMM model from alignment Build HMMER2 profile U2::HMMReadTask Read HMM profile '%1' U2::HMMSearchDialogController select_file_with_hmm_model Select file with HMM model hmm_file_not_set HMM file not set! error Error! starting_search_process Starting search process.. back_button Hide search_finished_with_errors_%1 HMM search finished with error: %1 search_finished_successfuly HMM search finished successfuly! ok_button Search progress_%1% Progress: %1% cancel_button Cancel close_button Close Cell BE optimized SSE optimized Conservative U2::HMMSearchTask parallel_hmm_search_task Parallel HMM search invalid_hmm_alphabet_type Invalid HMM alphabet! invalid_sequence_alphabet_type Invalid sequence alphabet! can_t_find_amino Amino translation is not available for the sequence alphabet! HMM search with '%1' U2::HMMSearchToAnnotationsTask raw_alphabet_not_supported RAW alphabet is not supported! annotation_obj_removed Annotation object was removed HMM search, file '%1' HMM profile used Task was not finished Result annotation table Result annotation group Result annotation name Results count U2::HMMWriteTask Write HMM profile '%1' U2::LocalWorkflow::HMMBuildPrompter For each MSA from <u>%1</u>, and calibrate default custom %1 build%2 HMM profile using <u>%3</u> settings. U2::LocalWorkflow::HMMBuildWorker Built HMM profile Calibrated HMM profile HMM build HMM profile HMM strategy Profile name Calibrate profile Parallel calibration Fixed length of samples Mean length of samples Number of samples Standard deviation Random seed Incorrect value for seed parameter Schema name not specified. Using default value: '%1' Input MSA Input multiple sequence alignment for building statistical model. Produced HMM profile Specifies kind of alignments you want to allow Descriptive name of the HMM profile Enables/disables optional profile calibration.<p>An empirical HMM calibration costs time but it only has to be done once per model, and can greatly increase the sensitivity of a database search. Number of parallel threads that the calibration will run in. Builds a HMM profile from a multiple sequence alignment.<p>The HMM profile is a statistical model which captures position-specific information about how conserved each column of the alignment is, and which residues are likely. U2::LocalWorkflow::HMMLib HMM Profile HMMER2 tools HMM profile Location Read HMM profile Write HMM profile Input HMM profile Location hint for the target file. Saves all input HMM profiles to specified location. Reads HMM profiles from file(s). The files can be local or Internet URLs. Loaded HMM profile U2::LocalWorkflow::HMMReadPrompter Read HMM profile(s) from %1 U2::LocalWorkflow::HMMReader Loaded HMM profile from %1 U2::LocalWorkflow::HMMSearchPrompter For each sequence from <u>%1</u>, Use <u>default</u> settings. Use <u>custom</u> settings. %1 search HMM signals %2. %3<br>Output the list of found regions annotated as <u>%4</u>. using all profiles provided by <u>%1</u>, U2::LocalWorkflow::HMMSearchWorker Bad sequence supplied to input: %1 Found %1 HMM signals HMM profile Input sequence HMM annotations Result annotation Number of seqs Filter by high E-value Filter by low score HMM search Power of e-value must be less or equal to zero. Using default value: 1e-1 Value for attribute name is empty, default name used Search HMM signals in %1 HMM profile(s) to search with. An input sequence (nucleotide or protein) to search in. Annotations marking found similar sequence regions. A name of the result annotations. Searches each input sequence for significantly similar sequence matches to all specified HMM profiles. In case several profiles were supplied, searches with all profiles one by one and outputs united set of annotations for each sequence U2::LocalWorkflow::HMMWritePrompter unset Save HMM profile(s) from <u>%1</u> to <u>%2</u>. U2::LocalWorkflow::HMMWriter Empty HMM passed for writing to %1 Unspecified URL for writing HMM Writing HMM profile to %1 U2::UHMMBuild bogus configuration choice U2::UHMMSearch UHMMSearch HMM2 Search U2::uHMMPlugin uhmm_plugin HMM2 uhmm_plugin_desc Based on HMMER 2.3.2 package Biological sequence analysis using profile hidden Markov models hmmcalibrate HMM calibrate hmmbuild HMM build hmmsearch HMM search Build HMM2 profile Calibrate profile with HMM2 Search with HMM2 HMMER tools error Error! neither_annotatedview_nor_pv_selection_found Error! Select sequence in Project view or open sequence view HMMER2 tools UHMMSearch UHMMSearch HMM2 Search ugene-1.9.8/src/plugins_3rdparty/ball/0000755000175000017500000000000011651544310016324 5ustar ilyailyaugene-1.9.8/src/plugins_3rdparty/ball/ball.pro0000644000175000017500000001250111651544325017765 0ustar ilyailya# ------------------------------------------------- # Project created by QtCreator 2009-07-07T13:37:29 # ------------------------------------------------- include (ball.pri) SOURCES += src/BallPlugin.cpp \ src/SES.cpp \ src/SAS.cpp \ src/source/COMMON/version.cpp \ src/source/COMMON/rtti.cpp \ src/source/COMMON/logStream.cpp \ src/source/COMMON/hash.cpp \ src/source/COMMON/exception.cpp \ src/source/COMMON/constants.cpp \ src/source/CONCEPT/visitor.cpp \ src/source/CONCEPT/processor.cpp \ src/source/CONCEPT/predicate.cpp \ src/source/DATATYPE/string.cpp \ src/source/DATATYPE/hashGrid.cpp \ src/source/MATHS/vector4.cpp \ src/source/MATHS/vector3.cpp \ src/source/MATHS/surface.cpp \ src/source/MATHS/sphere3.cpp \ src/source/MATHS/simpleBox3.cpp \ src/source/MATHS/quaternion.cpp \ src/source/MATHS/plane3.cpp \ src/source/MATHS/matrix44.cpp \ src/source/MATHS/line3.cpp \ src/source/MATHS/common.cpp \ src/source/MATHS/circle3.cpp \ src/source/MATHS/angle.cpp \ src/source/MATHS/analyticalGeometry.cpp \ src/source/STRUCTURE/triangulatedSurface.cpp \ src/source/STRUCTURE/triangulatedSES.cpp \ src/source/STRUCTURE/trianglePoint.cpp \ src/source/STRUCTURE/triangleEdge.cpp \ src/source/STRUCTURE/triangle.cpp \ src/source/STRUCTURE/solventExcludedSurface.cpp \ src/source/STRUCTURE/SESVertex.cpp \ src/source/STRUCTURE/SESFace.cpp \ src/source/STRUCTURE/SESEdge.cpp \ src/source/STRUCTURE/RSVertex.cpp \ src/source/STRUCTURE/RSFace.cpp \ src/source/STRUCTURE/RSEdge.cpp \ src/source/STRUCTURE/reducedSurface.cpp \ src/source/STRUCTURE/graphVertex.cpp \ src/source/STRUCTURE/graphFace.cpp \ src/source/STRUCTURE/graphEdge.cpp \ src/source/STRUCTURE/solventAccessibleSurface.cpp \ src/source/STRUCTURE/triangulatedSAS.cpp \ src/source/STRUCTURE/SASFace.cpp \ src/source/STRUCTURE/SASVertex.cpp \ src/source/STRUCTURE/SASEdge.cpp HEADERS += src/BallPlugin.h \ src/SES.h \ src/SAS.h \ src/include/BALL/COMMON/version.h \ src/include/BALL/COMMON/rtti.h \ src/include/BALL/COMMON/macros.h \ src/include/BALL/COMMON/logStream.h \ src/include/BALL/COMMON/limits.h \ src/include/BALL/COMMON/hash.h \ src/include/BALL/COMMON/global.h \ src/include/BALL/COMMON/exception.h \ src/include/BALL/COMMON/debug.h \ src/include/BALL/COMMON/create.h \ src/include/BALL/COMMON/constants.h \ src/include/BALL/common.h \ src/include/BALL/CONCEPT/visitor.h \ src/include/BALL/CONCEPT/processor.h \ src/include/BALL/CONCEPT/predicate.h \ src/include/BALL/CONCEPT/forwardIterator.h \ src/include/BALL/CONCEPT/baseIterator.h \ src/include/BALL/CONCEPT/baseFunctor.h \ src/include/BALL/CONFIG/config.h \ src/include/BALL/DATATYPE/triple.h \ src/include/BALL/DATATYPE/stringHashMap.h \ src/include/BALL/DATATYPE/string.h \ src/include/BALL/DATATYPE/quadruple.h \ src/include/BALL/DATATYPE/list.h \ src/include/BALL/DATATYPE/hashSet.h \ src/include/BALL/DATATYPE/hashMap.h \ src/include/BALL/DATATYPE/hashGrid.h \ src/include/BALL/DATATYPE/forEach.h \ src/include/BALL/MATHS/vector4.h \ src/include/BALL/MATHS/vector3.h \ src/include/BALL/MATHS/surface.h \ src/include/BALL/MATHS/sphere3.h \ src/include/BALL/MATHS/simpleBox3.h \ src/include/BALL/MATHS/quaternion.h \ src/include/BALL/MATHS/plane3.h \ src/include/BALL/MATHS/matrix44.h \ src/include/BALL/MATHS/line3.h \ src/include/BALL/MATHS/common.h \ src/include/BALL/MATHS/circle3.h \ src/include/BALL/MATHS/angle.h \ src/include/BALL/MATHS/analyticalGeometry.h \ src/include/BALL/MATHS/vector4.h \ src/include/BALL/MATHS/vector3.h \ src/include/BALL/MATHS/surface.h \ src/include/BALL/MATHS/sphere3.h \ src/include/BALL/MATHS/simpleBox3.h \ src/include/BALL/MATHS/quaternion.h \ src/include/BALL/MATHS/plane3.h \ src/include/BALL/MATHS/matrix44.h \ src/include/BALL/MATHS/line3.h \ src/include/BALL/MATHS/common.h \ src/include/BALL/MATHS/circle3.h \ src/include/BALL/MATHS/angle.h \ src/include/BALL/MATHS/analyticalGeometry.h \ src/include/BALL/STRUCTURE/triangulatedSurface.h \ src/include/BALL/STRUCTURE/triangulatedSES.h \ src/include/BALL/STRUCTURE/trianglePoint.h \ src/include/BALL/STRUCTURE/triangleEdge.h \ src/include/BALL/STRUCTURE/triangle.h \ src/include/BALL/STRUCTURE/solventExcludedSurface.h \ src/include/BALL/STRUCTURE/SESVertex.h \ src/include/BALL/STRUCTURE/SESFace.h \ src/include/BALL/STRUCTURE/SESEdge.h \ src/include/BALL/STRUCTURE/RSVertex.h \ src/include/BALL/STRUCTURE/RSFace.h \ src/include/BALL/STRUCTURE/RSEdge.h \ src/include/BALL/STRUCTURE/reducedSurface.h \ src/include/BALL/STRUCTURE/graphVertex.h \ src/include/BALL/STRUCTURE/graphFace.h \ src/include/BALL/STRUCTURE/graphEdge.h \ src/include/BALL/STRUCTURE/solventAccessibleSurface.h \ src/include/BALL/STRUCTURE/triangulatedSAS.h \ src/include/BALL/STRUCTURE/SASVertex.h \ src/include/BALL/STRUCTURE/SASFace.h \ src/include/BALL/STRUCTURE/SASEdge.h OTHER_FILES += src/include/BALL/COMMON/logStream.iC \ src/include/BALL/DATATYPE/string.iC INCLUDEPATH += src/include TRANSLATIONS += transl/english.ts transl/russian.ts ugene-1.9.8/src/plugins_3rdparty/ball/ball.pri0000644000175000017500000000022011651544325017752 0ustar ilyailya# include (ball.pri) PLUGIN_ID=ball PLUGIN_NAME=BALL library PLUGIN_VENDOR=Unipro CONFIG += warn_off include( ../../ugene_plugin_common.pri ) ugene-1.9.8/src/plugins_3rdparty/ball/src/0000755000175000017500000000000011651544310017113 5ustar ilyailyaugene-1.9.8/src/plugins_3rdparty/ball/src/SES.h0000644000175000017500000000270411651544325017727 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef SOLVENTEXCLUDEDSURFACE_H #define SOLVENTEXCLUDEDSURFACE_H #include namespace U2 { class Surface; class SolventExcludedSurface : public MolecularSurface { public: SolventExcludedSurface(); virtual void calculate(const QList& atoms, int& progress); virtual qint64 estimateMemoryUsage(int numberOfAtoms); }; class SolventExcludedSurfaceFactory : public MolecularSurfaceFactory { public: virtual MolecularSurface *createInstance()const; bool hasConstraints(const BioStruct3D& biostruc) const; }; } // namespace #endif // SOLVENTEXCLUDEDSURFACE_H ugene-1.9.8/src/plugins_3rdparty/ball/src/SES.cpp0000644000175000017500000001251111651544325020257 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include #include #include #include "SES.h" namespace U2 { // SolventExcludedSurface SolventExcludedSurface::SolventExcludedSurface() { GCOUNTER( cvar, tvar, "SolventExcludedSurface" ); } static void calcSES( BALL::Surface& surface, const QList& atoms, double TOLERANCE ) { std::vector > spheres; foreach(const SharedAtom a, atoms) { Vector3D coord=a->coord3d; double radius = AtomConstants::getAtomCovalentRadius(a->atomicNumber)+TOLERANCE; spheres.push_back(BALL::TSphere3(BALL::TVector3(coord.x,coord.y,coord.z),radius)); } double probeRadius=1.4; double density = 1000. / atoms.size(); BALL::ReducedSurface* reduced_surface = new BALL::ReducedSurface(spheres, probeRadius); reduced_surface->compute(); { BALL::SolventExcludedSurface* ses = new BALL::SolventExcludedSurface(reduced_surface); ses->compute(); double diff = -0.01; uint i = 0; bool ok = false; while (!ok && (i < 10)) { i++; ok = ses->check(); if (!ok) { delete ses; delete reduced_surface; probeRadius += diff; reduced_surface = new BALL::ReducedSurface(spheres, probeRadius); reduced_surface->compute(); ses = new BALL::SolventExcludedSurface(reduced_surface); ses->compute(); } } int progress = 0; if (ok) { BALL::TriangulatedSES* tSurface = new BALL::TriangulatedSES(ses, density); tSurface->compute(progress); tSurface->exportSurface(surface); delete tSurface; } delete ses; } delete reduced_surface; } void SolventExcludedSurface::calculate(const QList& atoms, int& progress) { // std::vector > spheres; // foreach(const SharedAtom a, atoms) // { // Vector3D coord=a->coord3d; // double radius=PDBFormat::getAtomCovalentRadius(a->atomicNumber)+TOLERANCE; // spheres.push_back(BALL::TSphere3(BALL::TVector3(coord.x,coord.y,coord.z),radius)); // } // double probeRadius=1.4; // double density = 1000. / atoms.size(); // for(int attempt=0;attempt < 10;attempt++) // { // progress = 0; // BALL::ReducedSurface* reducedSurface = new BALL::ReducedSurface(spheres,probeRadius); // reducedSurface->compute(); // BALL::SolventExcludedSurface solventExcludedSurface(&reducedSurface); // solventExcludedSurface.compute(); // if(solventExcludedSurface.check()) // { // BALL::TriangulatedSES triangulatedSES(&solventExcludedSurface,density); // triangulatedSES.compute(progress); // triangulatedSES.exportSurface(surface); // break; // } // probeRadius+=0.01; // } // // BALL::Surface surface; calcSES(surface, atoms, TOLERANCE); progress = 100; for(unsigned int faceIndex=0;faceIndex < surface.getNumberOfTriangles();faceIndex++) { const BALL::Surface::Triangle &triangle=surface.getTriangle(faceIndex); Face face; for(int coordIndex=0;coordIndex < 3;coordIndex++) { face.v[0][coordIndex]=surface.getVertex(triangle.v1)[coordIndex]; face.v[1][coordIndex]=surface.getVertex(triangle.v2)[coordIndex]; face.v[2][coordIndex]=surface.getVertex(triangle.v3)[coordIndex]; face.n[0][coordIndex]=surface.getNormal(triangle.v1)[coordIndex]; face.n[1][coordIndex]=surface.getNormal(triangle.v2)[coordIndex]; face.n[2][coordIndex]=surface.getNormal(triangle.v3)[coordIndex]; } faces.append(face); } } qint64 SolventExcludedSurface::estimateMemoryUsage( int ) { return 0; } // SolventExcludedSurfaceFactory MolecularSurface *SolventExcludedSurfaceFactory::createInstance() const { return new SolventExcludedSurface(); } #define MAX_ATOMS_NUMBER 10000 bool SolventExcludedSurfaceFactory::hasConstraints( const BioStruct3D& biostruc ) const { if (biostruc.getNumberOfAtoms() > MAX_ATOMS_NUMBER) { return true; } else { return false; } } } // namespace ugene-1.9.8/src/plugins_3rdparty/ball/src/BallPlugin.cpp0000644000175000017500000000277511651544325021671 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include #include #include #include #include "BallPlugin.h" namespace U2 { extern "C" Q_DECL_EXPORT U2::Plugin* U2_PLUGIN_INIT_FUNC() { BallPlugin* plug = new BallPlugin(); return plug; } BallPlugin::BallPlugin() : Plugin(tr("BALL"),tr("A port of BALL framework for molecular surface calculation")) { AppContext::getMolecularSurfaceFactoryRegistry()->registerSurfaceFactory(new SolventExcludedSurfaceFactory(),QString("SES")); AppContext::getMolecularSurfaceFactoryRegistry()->registerSurfaceFactory(new SolventAccessibleSurfaceFactory(),QString("SAS")); } } // namespace ugene-1.9.8/src/plugins_3rdparty/ball/src/SAS.cpp0000644000175000017500000000610511651544325020255 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include #include #include #include "SAS.h" namespace U2 { // SolventAccessibleSurface SolventAccessibleSurface::SolventAccessibleSurface() { GCOUNTER( cvar, tvar, "SolventAccessibleSurface" ); } void SolventAccessibleSurface::calculate(const QList& atoms, int& progress) { BALL::Surface surface; { std::vector > spheres; foreach(const SharedAtom a, atoms) { Vector3D coord=a->coord3d; double radius=AtomConstants::getAtomCovalentRadius(a->atomicNumber)+TOLERANCE; spheres.push_back(BALL::TSphere3(BALL::TVector3(coord.x,coord.y,coord.z),radius)); } double probeRadius=1.4; BALL::ReducedSurface reducedSurface(spheres,probeRadius); reducedSurface.compute(); BALL::SolventAccessibleSurface solventAccessibleSurface(&reducedSurface); solventAccessibleSurface.compute(); double density = 1000/atoms.size(); BALL::TriangulatedSAS triangulatedSAS(&solventAccessibleSurface, density); triangulatedSAS.compute(progress); triangulatedSAS.exportSurface(surface); } for(unsigned int faceIndex=0;faceIndex < surface.getNumberOfTriangles();faceIndex++) { const BALL::Surface::Triangle &triangle=surface.getTriangle(faceIndex); Face face; for(int coordIndex=0;coordIndex < 3;coordIndex++) { face.v[0][coordIndex]=surface.getVertex(triangle.v1)[coordIndex]; face.v[1][coordIndex]=surface.getVertex(triangle.v2)[coordIndex]; face.v[2][coordIndex]=surface.getVertex(triangle.v3)[coordIndex]; face.n[0][coordIndex]=surface.getNormal(triangle.v1)[coordIndex]; face.n[1][coordIndex]=surface.getNormal(triangle.v2)[coordIndex]; face.n[2][coordIndex]=surface.getNormal(triangle.v3)[coordIndex]; } faces.append(face); } } qint64 SolventAccessibleSurface::estimateMemoryUsage( int ) { return 0; } // SolventAccessibleSurfaceFactory MolecularSurface *SolventAccessibleSurfaceFactory::createInstance() const { return new SolventAccessibleSurface(); } } // namespace ugene-1.9.8/src/plugins_3rdparty/ball/src/SAS.h0000644000175000017500000000250511651544325017722 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef SAS_H #define SAS_H #include namespace U2 { class SolventAccessibleSurface : public MolecularSurface { public: SolventAccessibleSurface(); virtual qint64 estimateMemoryUsage(int numberOfAtoms); virtual void calculate(const QList& atoms, int& progress); }; class SolventAccessibleSurfaceFactory : public MolecularSurfaceFactory { public: virtual MolecularSurface *createInstance()const; }; } // namespace #endif // SAS_H ugene-1.9.8/src/plugins_3rdparty/ball/src/include/0000755000175000017500000000000011651544310020536 5ustar ilyailyaugene-1.9.8/src/plugins_3rdparty/ball/src/include/BALL/0000755000175000017500000000000011651544310021250 5ustar ilyailyaugene-1.9.8/src/plugins_3rdparty/ball/src/include/BALL/COMMON/0000755000175000017500000000000011651544310022240 5ustar ilyailyaugene-1.9.8/src/plugins_3rdparty/ball/src/include/BALL/COMMON/global.h0000644000175000017500000001547411651544325023672 0ustar ilyailya// -*- Mode: C++; tab-width: 2; -*- // vi: set ts=2: // // $Id: global.h,v 1.24 2005-12-23 17:01:39 amoll Exp $ // #ifndef BALL_COMMON_GLOBAL_H #define BALL_COMMON_GLOBAL_H #ifndef BALL_CONFIG_CONFIG_H # include #endif #include #include #if defined(BALL_LOG_MEMORY) && !defined(BALL_COMMON_MEMORY_H) # include #endif #ifdef BALL_HAS_BASETSD_H # include #endif // If possible use the ISO C99-compliant header stdint.h // to define the portable integer types. #ifdef BALL_HAS_STDINT_H # include #endif // Added to avoid warnings with MS Visual Studio .NET #ifdef BALL_COMPILER_MSVC # pragma warning( disable : 4290 ) #endif //#ifdef BALL_COMPILER_MSVC //# ifdef BALL_BUILD_DLL //# define BALL_EXPORT __declspec(dllexport) //# else //# define BALL_EXPORT __declspec(dllimport) //# endif //# ifdef BALL_VIEW_BUILD_DLL //# define BALL_VIEW_EXPORT __declspec(dllexport) //# else //# define BALL_VIEW_EXPORT __declspec(dllimport) //# endif //#else # define BALL_EXPORT # define BALL_VIEW_EXPORT //#endif namespace BALL { typedef int (*ComparatorType)(const void *, const void *); #ifndef BALL_HAS_STDINT_H /** @name Type aliases defined by BALL. These predefined types are used in BALL for portability and comprehensibility. \ingroup Common */ //@{ /** Distance type. Use this type to represent distances in indices. Signed. \par Size: 32 bit \par persistent */ typedef BALL_INDEX_TYPE Distance; /** Handle type. Use this type to represent handles. Handles are used for the non-ambiguous identification of objects (e.g. object derived from \link Object Object \endlink ). Handles are unsigned. \par Size: 32 bit \par persistent */ typedef BALL_SIZE_TYPE Handle; /** Index type. Use this type to represent indices (e.g. in strings or other sequences). Theses indices may be signed, contrary to the \link ::Size Size \endlink type. \par Size: 32 bit \par persistent */ typedef BALL_INDEX_TYPE Index; /** Size type. Use this type to represent sizes of containers, sequences or alike. Variables of type Size are unsigned. \par Size: 32 bit \par persistent */ typedef BALL_SIZE_TYPE Size; /** Long index type. Use this type to represent very long (64 bit) indices. Theses indices may be signed, contrary to the \link ::LongSize LongSize \endlink type. \par Size: 64 bit \par persistent */ typedef BALL_LONG64_TYPE LongIndex; /** Long size type. Use this type to represent sizes of containers, sequences or alike. Variables of type LongSize are unsigned. \par Size: 64 bit \par persistent */ typedef BALL_ULONG64_TYPE LongSize; /** Time type. Use this type to represent a point in time (as a replaecement for time_t). \par Size: platform dependent \par not persistent */ typedef time_t Time; /** HashIndex type. Use this type to access the result of a hash functions. HashIndex is unsigned. \par Size: 32 bit \par persistent */ typedef BALL_SIZE_TYPE HashIndex; /** Position type. Use this type to represent positions (e.g. in a container) that cannot be negative (contrary to \link ::Index Index \endlink ). \par Size: 32 bit \par persistent */ typedef BALL_SIZE_TYPE Position; /** Real type. Use this type to represent standard floating point numbers. \par Size: 32 bit \par persistent */ typedef float Real; /** Double-precision real type. Use this type to represent double precision floating point numbers. \par Size: 64 bit \par persistent */ typedef double DoubleReal; /** Unnamed property type. Use this type to represent (unnamed) properties. \par Size: 32 bit \par persistent @see PropertyManager */ typedef BALL_SIZE_TYPE Property; /** Error code property type. Use this type to represent (signed) error codes. \par Size: 32 bit \par persistent @see PropertyManager */ typedef BALL_INDEX_TYPE ErrorCode; /** Byte type. Use this type to represent byte data (8 bit length). A Byte is always unsigned. \par Size: 8 bit \par persistent */ typedef unsigned char Byte; /** Long unsigned int type. This type holds unsigned 64 bit integer numbers and is used to store pointers in a portable fashion (for both 32-bit and 64-bit systems). \par Size: 64 bit \par persistent */ typedef BALL_ULONG64_TYPE LongSize; /** Long signed int type. This type holds unsigned 64 bit numbers and is used to store pointers in a portable fashion (for both 32-bit and 64-bit systems). \par Size: 64 bit \par persistent */ typedef BALL_LONG64_TYPE LongIndex; /** Unsigned int with the same size as a pointer. Used for internal conversion issues mostly. Size: 32/64 bit (platform dependent)\par */ typedef BALL_POINTERSIZEUINT_TYPE PointerSizeUInt; #else // the ISO C99 definitions typedef int32_t Distance; typedef uint32_t Handle; typedef int32_t Index; typedef uint32_t Size; typedef uint64_t LongSize; typedef int64_t LongIndex; typedef time_t Time; typedef uint32_t HashIndex; typedef uint32_t Position; typedef float Real; typedef double DoubleReal; typedef uint32_t Property; typedef int32_t ErrorCode; typedef uint8_t Byte; typedef uint64_t LongIndex; typedef int64_t LongSize; #endif //@} enum ASCII { ASCII__BACKSPACE = '\b', ASCII__BELL = '\a', ASCII__CARRIAGE_RETURN = '\r', ASCII__HORIZONTAL_TAB = '\t', ASCII__NEWLINE = '\n', ASCII__RETURN = ASCII__NEWLINE, ASCII__SPACE = ' ', ASCII__TAB = ASCII__HORIZONTAL_TAB, ASCII__VERTICAL_TAB = '\v', ASCII__COLON = ':', ASCII__COMMA = ',', ASCII__EXCLAMATION_MARK = '!', ASCII__POINT = '.', ASCII__QUESTION_MARK = '?', ASCII__SEMICOLON = ';' }; static const Distance INVALID_DISTANCE = INT_MIN; static const Distance DISTANCE_MIN = (INT_MIN + 1); static const Distance DISTANCE_MAX = INT_MAX; static const Handle INVALID_HANDLE = INT_MAX; static const Handle HANDLE_MIN = 0 ; static const Handle HANDLE_MAX = INT_MAX - 1; static const Index INVALID_INDEX = -1; static const Index INDEX_MIN = 0; static const Index INDEX_MAX = INT_MAX; static const Position INVALID_POSITION = INT_MAX; static const Position POSITION_MIN = 0; static const Position POSITION_MAX = INT_MAX - 1; # undef SIZE_MAX static const Size INVALID_SIZE = INT_MAX; static const Size SIZE_MIN = 0; static const Size SIZE_MAX = INT_MAX - 1; } #endif // BALL_COMMON_GLOBAL_H ugene-1.9.8/src/plugins_3rdparty/ball/src/include/BALL/COMMON/macros.h0000644000175000017500000001217411651544325023710 0ustar ilyailya// -*- Mode: C++; tab-width: 2; -*- // vi: set ts=2: // // $Id: macros.h,v 1.9 2003-08-26 08:04:05 oliver Exp $ // #ifndef BALL_COMMON_MACROS_H #define BALL_COMMON_MACROS_H #ifndef BALL_CONFIG_CONFIG_H # include #endif #ifndef BALL_COMMON_CONSTANTS_H # include #endif #ifndef BALL_COMMON_RTTI_H # include #endif #include // needed for fabs #include // needed for typeid #define BALL_MAX(a, b) (((a) < (b)) ? (b) : (a)) #define BALL_MAX3(x, y, z) ((x) > (y) ? BALL_MAX(x, z) : BALL_MAX(y, z)) #define BALL_MIN(a, b) (((a) > (b)) ? (b) : (a)) #define BALL_MIN3(x, y, z) ((x) < (y) ? BALL_MIN(x, z) : BALL_MIN(y, z)) #define BALL_ABS(x) (((x) >= 0) ? (x) : -(x)) #define BALL_SGN(x) (((x) < 0) ? -1 : ((x) == 0) ? 0 : 1) #define BALL_ODD(x) (((x) % 2)!=0) #define BALL_INT_ODD(x) (((x) & 0x1) == 1) #define BALL_INT_EVEN(x) (((x) & 0x1) == 0) #define BALL_REAL_ROUND BALL::Maths::round #define BALL_REAL_EQUAL(x, y, e) (fabs((x) - (y)) <= e) #define BALL_REAL_NOT_EQUAL(x, y, e) (fabs((x) - (y)) > e) #define BALL_REAL_LESS(x, y, e) (((x) - (y)) < -e) #define BALL_REAL_LESS_OR_EQUAL(x, y, e) (((x) - (y)) <= e) #define BALL_REAL_GREATER(x, y, e) (((x) - (y)) > e) #define BALL_REAL_GREATER_OR_EQUAL(x, y, e) (((x) - (y)) >= -e) #define BALL_REAL_ABS(x) fabs(x) #define BALL_REAL_SGN(x) BALL_SGN(x) #define BALL_REAL_ODD(x) (((x) % 2) != 0) #define BALL_REAL_EVEN(x) (((x) % 2) == 0) #define BALL_REAL_FLOOR(x) (long)((x) > 0 ? (x): ((x) == (long)(x) ? (x) : (x) - 1)) #define BALL_REAL_CEILING(x) (long)((x) < 0 ? (x): ((x) == (long)(x) ? (x) : (x) + 1)) #define BALL_REAL_ROUND_INT(x) ((x) > 0 ? (int)(x + 0.5) : -(int)(0.5 - x)) // The following macros assume BALL_CHAR_BITS is one of either 8, 16, or 32 #define BALL_CHAR_BITS BALL_CHAR_SIZE * 8 #define BALL_CHAR_MASK BALL_CHAR_BITS - 1 #define BALL_CHAR_SHIFT ((BALL_CHAR_BITS == 8) ? 3 : (BALL_CHAR_BITS == 16) ? 4 : 5) #define BALL_CHAR_ALL_BITS_SET ((BALL_CHAR_BITS == 8) ? 0xFF : (BALL_CHAR_BITS == 16) ? 0xFFFF : 0xFFFFFFFF) #define BALL_CHAR_ALL_BITS_CLEARED ((BALL_CHAR_BITS == 8) ? 0x00 : (BALL_CHAR_BITS == 16) ? 0x0000 : 0x00000000) #define BALL_NUMBER_OF_BYTES(bits) (((bits) + BALL_CHAR_MASK) >> BALL_CHAR_SHIFT) #define BALL_SIZEOF_ARRAY(a) (sizeof(a) / sizeof(*(a))) #define BALL_BITARRAY_SIZE(number_of_bits) (((number_of_bits - 1) >> BALL_CHAR_SHIFT) + 1) #define BALL_BITARRAY_CLEAR_BIT(array, x) ((array)[(x) >> BALL_CHAR_SHIFT] &= ~(1 << ((x) & BALL_CHAR_MASK))) #define BALL_BITARRAY_SET_BIT(array, x) ((array)[(x) >> BALL_CHAR_SHIFT] |= (1 << ((x) & BALL_CHAR_MASK))) #define BALL_BITARRAY_TOGGLE_BIT(array, x) ((array)[(x) >> BALL_CHAR_SHIFT] ^= (1 << ((x) & BALL_CHAR_MASK))) #define BALL_BITARRAY_IS_BIT_SET(array, x) (((array)[(x) >> BALL_CHAR_SHIFT] & (1 << ((x) & BALL_CHAR_MASK))) != 0) #define BALL_BIT(bit) (1 << (bit)) #define BALL_BIT_SET(bitset, bit) ((bitset) |= (1 << (bit))) #define BALL_BIT_SET_ALL(bitset) ((bitset) = -1) #define BALL_BIT_SET_ALL_TO(bitset, bit) ((bitset) |= ~(-1 << (bit + 1))) #define BALL_BIT_SET_ALL_FROM(bitset, bit) ((bitset) |= (-1 << (bit))) #define BALL_BIT_CLEAR(bitset, bit) ((bitset) &= ~(1 << (bit))) #define BALL_BIT_CLEAR_ALL(bitset) ((bitset) = 0) #define BALL_BIT_CLEAR_ALL_TO(bitset, bit) ((bitset) &= (-1 << (bit + 1))) #define BALL_BIT_CLEAR_ALL_FROM(bitset, bit) ((bitset) &= ~(-1 << (bit))) #define BALL_BIT_IS_SET(bitset, bit) ((bitset) & (1 << (bit))) #define BALL_BIT_IS_CLEARED(bitset, bit) !((bitset) & (1 << (bit))) #define BALL_ANGLE_RADIAN_TO_DEGREE(rad_angle) (180.0 / ::BALL::Constants::PI * (rad_angle)) #define BALL_ANGLE_DEGREE_TO_RADIAN(deg_angle) (::BALL::Constants::PI / 180.0 * (deg_angle)) #define BALL_OFFSET_OF(struct_name, struct_var_name) ((long)&(((struct_name*)0)->struct_var_name)) #define BALL_DUMP_DEPTH(os, depth) for (dump_indent_depth_ = 0; dump_indent_depth_ < depth; ++dump_indent_depth_) { os << " "; } #define BALL_DUMP_STREAM_PREFIX(os) Size dump_indent_depth_ = 0; #define BALL_DUMP_HEADER(os,cl,ob) os << "Object: " << (void *)ob << " is instance of class: " << streamClassName(typeid(*ob)) << std::endl; #define BALL_DUMP_CLASS_HEADER(os,cl,ob) os << "Object: " << (void *)ob << " is instance of class: " << #cl << ::std::endl; #define BALL_DUMP_STREAM_SUFFIX(os) #endif // BALL_COMMON_MACROS_H ugene-1.9.8/src/plugins_3rdparty/ball/src/include/BALL/COMMON/constants.h0000644000175000017500000001107211651544325024434 0ustar ilyailya// -*- Mode: C++; tab-width: 2; -*- // vi: set ts=2: // // $Id: constants.h,v 1.15 2005-12-23 17:01:38 amoll Exp $ // #ifndef BALL_COMMON_CONSTANTS_H #define BALL_COMMON_CONSTANTS_H #ifndef BALL_COMMON_GLOBAL_H # include #endif namespace BALL { /** The constants namespace. This namespace contains definitions for some basic mathematical and physical constants. All constants are double precision. \par There are basically two ways of accessing these constants: - specify all namespaces: \par float my_pi = BALL::Constants::PI - shortcut via the using directive: \par using namespace BALL::Constants; \par float my_pi = PI; \ingroup Common */ namespace Constants { /** @name Mathematical constants. */ //@{ /// PI BALL_EXPORT extern const double PI; /// Euler's number - base of the natural logarithm BALL_EXPORT extern const double E; /** Internal theshold for equality comparisons. Default value is 1e-6. */ BALL_EXPORT extern double EPSILON; //@} /** @name Chemical/physical constants. */ //@{ /** Elementary charge. In units of C (\f$1.60217738 \cdot 10^{-19} C\f$). */ BALL_EXPORT extern const double ELEMENTARY_CHARGE; // C /// Elementary charge (alias) BALL_EXPORT extern const double e0; /** Electron mass. In units of kg (\f$9.1093897 \cdot 10^{-31}\f$ kg). */ BALL_EXPORT extern const double ELECTRON_MASS ; // kg /** Proton mass. In units of kg (\f$1.6726230 \cdot 10^{-27}\f$ kg). */ BALL_EXPORT extern const double PROTON_MASS ; // kg /** Neutron mass. In units of kg (\f$1.6749286 \cdot 10^{-27}\f$ kg). */ BALL_EXPORT extern const double NEUTRON_MASS ; // kg /** Avogadro constant. In units of \f$mol^{-1}\f$ (\f$6.0221367 \cdot 10^{23} mol^{-1}\f$). */ BALL_EXPORT extern const double AVOGADRO; /** Avogadro constant (alias) */ BALL_EXPORT extern const double NA; /** Avogadro constant (alias) */ BALL_EXPORT extern const double MOL; /** Boltzmann constant. In units of J/K (\f$1.380657 \cdot 10^{-23}\f$ J/K). */ BALL_EXPORT extern const double BOLTZMANN; /** Boltzmann constant (alias) */ BALL_EXPORT extern const double k; /** Planck constant. In units of Js (\f$6.6260754 \cdot 10^{-34}\f$ Js). */ BALL_EXPORT extern const double PLANCK; /** Planck constant (alias) */ BALL_EXPORT extern const double h; /** Gas constant (= NA * k) */ BALL_EXPORT extern const double GAS_CONSTANT; /** Gas constant (alias) */ BALL_EXPORT extern const double R; /** Faraday constant (= NA * e0) */ BALL_EXPORT extern const double FARADAY; /** Faraday constant (alias) */ BALL_EXPORT extern const double F; /** Bohr radius. In units m (\f$5.29177249 \cdot 10^{-11}\f$ m). */ BALL_EXPORT extern const double BOHR_RADIUS; /** Bohr radius (alias) */ BALL_EXPORT extern const double a0; // the following values from: // P.W.Atkins: Physical Chemistry, 5th ed., Oxford University Press, 1995 /** Vacuum permittivity. In units of \f$C^2J^{-1}m^{-1}\f$ (\f$8.85419 \cdot 10^{-12} C^2J^{-1}m^{-1}\f$). */ BALL_EXPORT extern const double VACUUM_PERMITTIVITY; /** Vacuum permeability. In units of \f$Js^2C^{-2}m^{-1}\f$ (\f$4\pi \cdot 10^{-7} Js^2C^{-2}m^{-1}\f$). */ BALL_EXPORT extern const double VACUUM_PERMEABILITY; /** Speed of light. In units of m/s (\f$2.99792458 \cdot 10^8 ms^{-1}\f$). */ BALL_EXPORT extern const double SPEED_OF_LIGHT; /** Speed of Light (alias) */ BALL_EXPORT extern const double c; /** Gravitational constant. In units of \f$Nm^2kg^{-2}\f$ (\f$6.67259 \cdot 10^{-11} Nm^2kg^{-2}\f$). */ BALL_EXPORT extern const double GRAVITATIONAL_CONSTANT; /** Fine structure constant. Without unit (\f$7.29735 \cdot 10^{-3}\f$). */ BALL_EXPORT extern const double FINE_STRUCTURE_CONSTANT; //@} /** @name Conversion factors */ //@{ /** Degree per rad. 57.2957795130823209 */ BALL_EXPORT extern const double DEG_PER_RAD; /** Rad per degree. 0.0174532925199432957 */ BALL_EXPORT extern const double RAD_PER_DEG; /** mm per inch. 25.4 */ BALL_EXPORT extern const double MM_PER_INCH ; /** m per foot. 3.048 */ BALL_EXPORT extern const double M_PER_FOOT ; /** Joules per calorie. 4.184 */ BALL_EXPORT extern const double JOULE_PER_CAL; /** Calories per Joule. 1/JOULE_PER_CAL */ BALL_EXPORT extern const double CAL_PER_JOULE; //@} } } #endif // BALL_COMMON_CONSTANTS_H ugene-1.9.8/src/plugins_3rdparty/ball/src/include/BALL/COMMON/logStream.iC0000644000175000017500000000331611651544325024463 0ustar ilyailya// -*- Mode: C++; tab-width: 2; -*- // vi: set ts=2: // // $Id: logStream.iC,v 1.11 2005-01-18 21:21:53 amoll Exp $ // BALL_INLINE int LogStreamBuf::overflow(int c) { sync(); return ::std::streambuf::overflow(c); } BALL_INLINE LogStreamBuf* LogStream::rdbuf() { return (LogStreamBuf*)std::ios::rdbuf(); } BALL_INLINE LogStreamBuf* LogStream::operator -> () { return rdbuf(); } BALL_INLINE void LogStream::setLevel(int level) { if (rdbuf() == 0) { return; } // set the new level rdbuf()->level_ = level; // set tmp_level_, too - to otherwise the // new level would take effect in the line after // the next! rdbuf()->tmp_level_ = level; } BALL_INLINE int LogStream::getLevel() { if (rdbuf() != 0) { return rdbuf()->level_; } else { return 0; } } BALL_INLINE LogStream& LogStream::level(int level) { // set the temporary level // will be reset by sync(), i.e. at the end of the next line if (rdbuf() != 0) { rdbuf()->tmp_level_ = level; } return *this; } BALL_INLINE LogStream& LogStream::error(int level) { // set the temporary level to ERROR // will be reset by sync(), i.e. at the end of the next line if (rdbuf() != 0) { rdbuf()->tmp_level_ = ERROR_LEVEL + level; } return *this; } BALL_INLINE LogStream& LogStream::warn(int level) { // set the temporary level to WARNING // will be reset by sync(), i.e. at the end of the next line if (rdbuf() != 0) { rdbuf()->tmp_level_ = WARNING_LEVEL + level; } return *this; } BALL_INLINE LogStream& LogStream::info(int level) { // set the temporary level to INFORMATION // will be reset by sync(), i.e. at the end of the next line if (rdbuf() != 0) { rdbuf()->tmp_level_ = INFORMATION_LEVEL + level; } return *this; } ugene-1.9.8/src/plugins_3rdparty/ball/src/include/BALL/COMMON/create.h0000644000175000017500000000626511651544325023673 0ustar ilyailya// -*- Mode: C++; tab-width: 2; -*- // vi: set ts=2: // // $Id: create.h,v 1.11 2004-02-18 23:24:02 oliver Exp $ // #ifndef BALL_COMMON_CREATE_H #define BALL_COMMON_CREATE_H //@{ /** Virtual construction macro. This macro is used to define the virtual create method. On inclusion of this macro in the public interface of a class, the virtual creation method becomes available. The create method's signature is as follows: virtual void* create(bool deep = true, bool empty = false) const \par The create method either creates an empty default object of the class (empty == true) or a copy of the object. The copy is either deep (deep == true) or shallow (deep == false). By default, the create methods returns a pointer to a deep copy of the object. The use of the create method requires a (public) default constructor (when creating an empty copy) or a copy constructor. \par The macro also implements a static method createDefault that returns a void pointer to a new instance of name. @param name the class name \ingroup Common */ #define BALL_CREATE_DEEP(name)\ \ virtual void* create(bool deep = true, bool empty = false) const\ {\ void* ptr;\ if (empty == true)\ {\ ptr = (void*)new name;\ }\ else\ {\ ptr = (void*)new name(*this, deep);\ }\ \ return ptr;\ }\ \ static void* createDefault()\ {\ return static_cast(new name);\ } /** Virtual construction macro. This macro is used to define the virtual create method for classes that do not define a copy constructor taking a second argument (boolean, deep or shallow copy). On inclusion of this macro in the public interface of a class, the virtual creation method becomes available. The create method's signature is as follows: virtual void* create(bool deep = true, bool empty = false) const \par The create method either creates an empty default object of the class (empty == true) or a copy of the object. The use of the create method requires a (public) default constructor (when creating an empty copy) and a copy constructor taking a reference to an object. The macro also implements a static method createDefault that returns a void pointer to a new instance of name. @param name the class name */ #define BALL_CREATE(name)\ \ virtual void* create(bool /* deep */ = true, bool empty = false) const\ {\ void* ptr;\ if (empty == true)\ {\ ptr = (void*)new name;\ }\ else\ {\ ptr = (void*)new name(*this);\ }\ \ return ptr;\ }\ \ static void* createDefault()\ {\ return static_cast(new name);\ } /** Virtual cloning method definition macro. If the create method has to be implemented by the user, this macro just defines the create method and the createDefault method. The function signatures are: \verbatim virtual void* create(bool deep = true, bool empty = false) const; static void* createDefault(); \endverbatim */ #define BALL_DEFINE_CREATE(name)\ \ virtual void* create(bool deep = true, bool empty = false) const;\ static void* createDefault(); //@} #endif // BALL_COMMON_CREATE_H ugene-1.9.8/src/plugins_3rdparty/ball/src/include/BALL/COMMON/debug.h0000644000175000017500000000215511651544325023510 0ustar ilyailya// -*- Mode: C++; tab-width: 2; -*- // vi: set ts=2: // // $Id: debug.h,v 1.10 2004-02-23 21:35:17 anhi Exp $ // #ifndef BALL_COMMON_DEBUG_H #define BALL_COMMON_DEBUG_H #ifndef BALL_CONFIG_CONFIG_H # include #endif #ifdef BALL_NO_INLINE_FUNCTIONS # define BALL_INLINE #else # define BALL_INLINE inline #endif #include #ifdef BALL_DEBUG # define BALL_PRECONDITION_EXCEPTION(condition, message)\ if (!(condition))\ {\ Exception::Precondition e(__FILE__, __LINE__, #condition);\ if (message != "")\ {\ ::std::string tmp(e.getMessage());\ tmp += ::std::string(message);\ e.setMessage(tmp);\ }\ throw e;\ }\ # define BALL_POSTCONDITION_EXCEPTION(condition, message)\ if (!(condition))\ {\ Exception::Postcondition e(__FILE__, __LINE__, #condition);\ if (message != "")\ {\ std::string tmp(e.getMessage());\ tmp += std::string(message);\ e.setMessage(tmp);\ }\ throw e;\ }\ #else # define BALL_PRECONDITION_EXCEPTION(condition, message) # define BALL_POSTCONDITION_EXCEPTION(condition, message) #endif // BALL_DEBUG #endif // BALL_COMMON_DEBUG_H ugene-1.9.8/src/plugins_3rdparty/ball/src/include/BALL/COMMON/hash.h0000644000175000017500000000525111651544325023345 0ustar ilyailya// -*- Mode: C++; tab-width: 2; -*- // vi: set ts=2: // // $Id: hash.h,v 1.23 2005-12-23 17:01:39 amoll Exp $ // #ifndef BALL_COMMON_HASH_H #define BALL_COMMON_HASH_H #ifndef BALL_COMMON_H # include #endif #ifndef BALL_DATATYPE_STRING_H # include #endif namespace BALL { /** General Hash Function Template. This template function provides a simple wrapper for the specialized hash functions. It facilitates their use in STL hash associative containers which expect a Hasher class as template parameter. \ingroup Common */ template class HashFunction { public: HashIndex operator () (const T& t) const throw() { return Hash(t); } }; /** @name Specialized Hash Functions. */ //@{ /** */ BALL_EXPORT extern HashIndex hashPointer(void *const ptr) throw(); /** */ BALL_EXPORT extern HashIndex hashString(const char* str) throw(); /** */ BALL_EXPORT extern HashIndex hashPJWString(const char* str) throw(); /** */ BALL_EXPORT extern HashIndex hashElfString(const char* str) throw(); /** General default hash function. This method converts a given key to a \link HashIndex HashIndex \endlink by calling (HashIndex)key. If the key type T is not convertible to \link HashIndex HashIndex \endlink by default, a converter should be defined (operator HashIndex). @param key the key to be hashed @return HashIndex the hash index */ template inline HashIndex Hash(const T& key) throw() { return static_cast((PointerSizeUInt)key); } /** String hash function. This method is optimized for the hashing of STL strings. In fact, it is only an inline wrapper around \link hashString hashString \endlink . */ BALL_EXPORT inline HashIndex Hash(const string& s) throw() { return hashString(s.c_str()); } /** String hash function. This method is optimized for the hashing of BALL strings. In fact, it is only an inline wrapper around \link hashString hashString \endlink . */ BALL_EXPORT inline HashIndex Hash(const String& s) throw() { return hashString(s.c_str()); } /** Pointer hash function. Use this function to hash pointers to objects. */ BALL_EXPORT inline HashIndex Hash(void *const& ptr) throw() { return hashPointer(ptr); } //@} //@{ /** Calculate the next prime number. This method returns the first prime number that is greater or equal to the number given as the argument. Only odd prime numbers are returned, the lowest number returned is 3. */ BALL_EXPORT HashIndex getNextPrime(HashIndex l) throw(); //@} } // namespace BALL #endif // BALL_COMMON_HASH_H ugene-1.9.8/src/plugins_3rdparty/ball/src/include/BALL/COMMON/rtti.h0000644000175000017500000001421211651544325023401 0ustar ilyailya// -*- Mode: C++; tab-width: 2; -*- // vi: set ts=2: // // $Id: rtti.h,v 1.27 2005-12-23 17:01:39 amoll Exp $ // #ifndef BALL_COMMON_RTTI_H #define BALL_COMMON_RTTI_H #ifndef BALL_CONFIG_CONFIG_H # include #endif #ifndef BALL_COMMON_H # include #endif #include #include using std::string; namespace BALL { # ifdef __GNUC__ // EGCS produces a nearly unreadable name mangling that requires // further interpretation namespace GNUDemangling { BALL_EXPORT string demangle(string s); } # endif /** Returns a unique name for a class. This name contains no blanks. It is usually derived by substituting all blanks in the name (as returned by RTTI::getName()) with underscores ("_"). In the case of gcc, however a name demangling decodes the string first. This function is needed for object persistence. @param t the type_info structure as returned by typeid @return string the coverted class name \ingroup Common */ BALL_EXPORT string streamClassName(const std::type_info& t); /** Simplified RunTime Type Identification. ANSI C++ provides support for runtime type identification (RTTI). However, the support is very basic. The template functions of the RTTI namespace provide a more readable support for RTTI. It defines predicates such as \link BALL::RTTI::isKindOf isKindOf \endlink that simplify tests on the hereditary relationship of different objects. \par To use the RTTI template functions, parametrize it with the type you are interested in. For example, to find out whether a given molecule is a protein, the following code can be used: \par \code Molecule& m =...; ... if (RTTI::isKindOf(m)) { // perform some protein specific operations } else { // this is only a molecule... } \endcode \ingroup Common */ namespace RTTI { /** Return a reference to a static default instance of the corresponding class. This method is basically intended to provide a default object for certain operations that require an instance of a certain class without really using this instance. It is mainly used inside the RTTI class. */ template const T& getDefault() { static T t; return t; } /** Return a void pointer to a new instance of the class. Use this method to provide an easy factory for objects of a certain class. The main use of this function lies in object persistence. The \link PersistenceManager PersistenceManager \endlink needs a function for the dynamic creation of objects. */ template void* getNew() { return static_cast(new T); } /** Return the name of the class. This method returns the name of the class as given by typeid(\.name()). No additional name demangling and whitespace substitution are performed. */ template const char* getName() { return typeid(getDefault()).name(); } /** Return a void pointer that is unique for each class. */ template void* getClassID() { static char dummy; return (void*)&dummy; } /** Return the demangled class name. The class name is demangled (as far as possible) and in the resulting string blanks are substituted by underscores, so the name can be read from a stream as one string. The typical usage is something like \code String class_name = RTTI::getStreamName(); ... \endcode */ template const char* getStreamName() { // define portable names for the portable // types (some platforms use Size, some unsigned int, // SUN CC even unsigned for the Size type) if ((typeid(T) == typeid(Size)) || (typeid(T) == typeid(Position)) || (typeid(T) == typeid(HashIndex)) || (typeid(T) == typeid(Property)) || (typeid(T) == typeid(Handle))) { return "BALL::Size"; } if ((typeid(T) == typeid(Index)) || (typeid(T) == typeid(ErrorCode)) || (typeid(T) == typeid(Distance))) { return "BALL::Index"; } if (typeid(T) == typeid(::std::string)) { return "::std::string"; } if (typeid(T) == typeid(LongSize)) { return "BALL::LongSize"; } if (typeid(T) == typeid(bool)) { return "bool"; } if (typeid(T) == typeid(float)) { return "float"; } if (typeid(T) == typeid(char)) { return "char"; } if (typeid(T) == typeid(unsigned char)) { return "unsigned_char"; } if (typeid(T) == typeid(double)) { return "double"; } static string s(""); static bool is_set = false; if (!is_set) { is_set = true; s = streamClassName(typeid(getDefault())); } return s.c_str(); } /** Return true if u is a kind of T. If u is an instance of a class derived from T, this predicate returns true: \par \code Protein p; // return true, since Protein is derived from Molecule bool is_molecule = RTTI::isKindOf(p); \endcode */ template bool isKindOf(const U& u) { return (0 != dynamic_cast(&u)); } /** Cast an object to a specialized class. Example: \par \code Composite* composite = ...; ... // check whether the composite is also an atom if (RTTI::isKindOf(composite)) { // perform some atom specific actions Atom* atom = RTTI::castTo(*composite); ... atom->setCharge(0); ... } \endcode */ template T* castTo(const U& u) { return const_cast(dynamic_cast(&u)); } /** Return true if a given object is an instance of a given class. If u is an instance of T, this predicate returns true. If u is an instance of a class that is derived from T or a base class of T, it returns false. */ template bool isInstanceOf(const U& u) { T t; return (typeid(u) == typeid(t)); } } // namespace RTTI } // namespace BALL #endif // BALL_COMMON_RTTI_H ugene-1.9.8/src/plugins_3rdparty/ball/src/include/BALL/COMMON/version.h0000644000175000017500000000362111651544325024106 0ustar ilyailya// -*- Mode: C++; tab-width: 2; -*- // vi: set ts=2: // // $Id: version.h,v 1.32.20.2 2007-08-03 03:27:07 oliver Exp $ // #ifndef BALL_COMMON_VERSION_H #define BALL_COMMON_VERSION_H #ifndef BALL_COMMON_EXCEPTION_H # include #endif #ifndef BALL_COMMON_GLOBAL_H # include #endif // // master data for all revisions is stored in this define! // #define BALL_RELEASE_STRING "1.2" namespace BALL { /** Version information class. The BALL release, release data and related version can be retrieved by these methods. \par Stable releases are designated with numbers only. \par Alpha, beta, nonpublic, or prereleases are suffixed as "alpha", "beta", "nonpublic", and "pre", respectively.\par The VersionInfo class contains only static methods that can be used to retrieve the desired information. \par \ingroup Common */ class BALL_EXPORT VersionInfo { public: /** Enumeration of all possible release types. */ enum Type { STABLE, ALPHA, BETA, NONPUBLIC, PRERELEASE, PATCHLVL, // this can't be PATCHLEVEL due to a collision with historic Python versions (< 2.2). UNKNOWN }; /** Return the version number, which is defined in BALL_RELEASE_STRING */ static const char* getVersion() throw(); /** Return the major revision number. (The part of the release number before the point) */ static int getMajorRevision() throw(Exception::InvalidFormat); /** Return the minor revision number. (The part of the release number after the point) */ static int getMinorRevision() throw(Exception::InvalidFormat); /** Return the type of release: ALPHA, BETA, NONPUPLIC, STABLE, PRERELEASE, PATCHLVL, UNKNOWN. */ static Type getType() throw(); protected: static const char* RELEASE_DATE_AND_TIME; static const char* RELEASE_WHAT_STRING; }; } #endif // BALL_COMMON_VERSION_H ugene-1.9.8/src/plugins_3rdparty/ball/src/include/BALL/COMMON/limits.h0000644000175000017500000000775111651544325023732 0ustar ilyailya// -*- Mode: C++; tab-width: 2; -*- // vi: set ts=2: // // $Id: limits.h,v 1.19 2005-12-23 17:01:39 amoll Exp $ // #ifndef BALL_COMMON_LIMITS_H #define BALL_COMMON_LIMITS_H #ifndef BALL_CONFIG_CONFIG_H # include #endif #ifndef BALL_COMMON_GLOBAL_H # include #endif #ifdef BALL_HAS_NUMERIC_LIMITS # include #else # ifdef BALL_HAS_LIMITS_H # include # endif # ifdef BALL_HAS_VALUES_H # include # endif # ifdef BALL_HAS_FLOAT_H # include # endif #endif namespace BALL { /** Numeric limits class. This template class describes the minimum and maximum values for the differnet data types. It a substitute for the numeric_limits class described in the ISO/ANSI standard (chapter 18.2.1.1), as most compiler still do not support this feature (or more precisely: the header file \ is not implemented). If \ exists, Limits is just a wrapper around the numeric_limits class, otherwise it returns the value from the standard C header \. \par \ingroup Common */ template class BALL_EXPORT Limits { public: #ifdef BALL_HAVE_NUMERIC_LIMITS /** Return the minimum value. @return T the minimum value for this datatype */ static T min() throw() { return std::numeric_limits::min(); } /** Return the maximum value. @return T the maximum value for this datatype */ static T max() throw() { return std::numeric_limits::max(); } #else static T min() throw() { return (T)0; } static T max() throw() { return (T)0; } #endif }; #ifndef BALL_HAVE_NUMERIC_LIMITS template <> class BALL_EXPORT Limits { public: static float min() throw() { return FLT_MIN; } static float max() throw() { return FLT_MAX; } }; template <> class BALL_EXPORT Limits { public: static double min() throw() { return DBL_MIN; } static double max() throw() { return DBL_MAX; } }; template <> class BALL_EXPORT Limits { public: static bool min() throw() { return false; } static bool max() throw() { return true; } }; template <> class BALL_EXPORT Limits { public: static char min() throw() { return CHAR_MIN; } static char max() throw() { return CHAR_MAX; } }; template <> class BALL_EXPORT Limits { public: static signed char min() throw() { return SCHAR_MIN; } static signed char max() throw() { return SCHAR_MAX; } }; template <> class BALL_EXPORT Limits { public: static unsigned char min() throw() { return 0; } static unsigned char max() throw() { return UCHAR_MAX; } }; template <> class BALL_EXPORT Limits { public: static short min() throw() { return SHRT_MIN; } static short max() throw() { return SHRT_MAX; } }; template <> class BALL_EXPORT Limits { public: static unsigned short min() throw() { return 0; } static unsigned short max() throw() { return USHRT_MAX; } }; template <> class BALL_EXPORT Limits { public: static int min() throw() { return INT_MIN; } static int max() throw() { return INT_MAX; } }; template <> class BALL_EXPORT Limits { public: static unsigned int min() throw() { return 0; } static unsigned int max() throw() { return UINT_MAX; } }; template <> class BALL_EXPORT Limits { public: static long min() throw() { return LONG_MIN; } static long max() throw() { return LONG_MAX; } }; template <> class BALL_EXPORT Limits { public: static unsigned long min() throw() { return 0; } static unsigned long max() throw() { return ULONG_MAX; } }; #endif // BALL_HAVE_NUMERIC_LIMITS } // namespace BALL #endif // BALL_COMMON_LIMITS_H ugene-1.9.8/src/plugins_3rdparty/ball/src/include/BALL/COMMON/logStream.h0000644000175000017500000003700511651544325024361 0ustar ilyailya// -*- Mode: C++; tab-width: 2; -*- // vi: set ts=2: // // $Id: logStream.h,v 1.32 2005-12-23 17:01:39 amoll Exp $ // #ifndef BALL_COMMON_LOGSTREAM_H #define BALL_COMMON_LOGSTREAM_H #ifndef BALL_CONFIG_CONFIG_H # include #endif #ifndef BALL_COMMON_GLOBAL_H # include #endif #ifndef BALL_COMMON_DEBUG_H # include #endif #ifdef BALL_HAS_SYS_TIME_H # include #endif #ifdef BALL_HAS_TIME_H # include #endif #ifdef BALL_HAS_SSTREAM # include #else # include #endif #include #include #include #include using std::list; using std::vector; using std::string; namespace BALL { /** @name Log streams Logging, filtering, and storing messages. Many programs emit warning messages, error messages, or simply informations and remarks to their users. The \link LogStream LogStream \endlink class provides a convenient and straight-forward interface to classify these messages according to their importance (via the loglevel), filter and store them in files or write them to streams. \par As the LogStream class is derived from ostream, it behaves as any ostream object. Additionally you may associate streams with each LogStream object that catch only messages of certain loglevels. So the user might decide to redirect all error messages to cerr, all warning messages to cout and all informations to a file. \par Along with each message its time of creation and its loglevel is stored. So the user might also decide to store all errors he got in the last two hours or alike. \par The \link LogStream LogStream \endlink class heavily relies on the \link LogStreamBuf LogStreamBuf \endlink class, which does the actual buffering and storing, but is only of interest if you want to implement a derived class, as the actual user interface is implemented in the LogStream class. * \ingroup Common */ //@{ // forward declarations class LogStream; class LogStreamNotifier; /** Stream buffer used by LogStream. This class implements the low level behaviour of \link LogStream LogStream \endlink . It takes care of the buffers and stores the lines written into the \link LogStream LogStream \endlink object. It also contains a list of streams that are associated with the LogStream object. This list contains pointers to the streams and their minimum and maximum log level. Each line entered in the \link LogStream LogStream \endlink is marked with its time (in fact, the time \link LogStreamBuf::sync sync \endlink was called) and its loglevel. The loglevel is determined by either the current loglevel (as set by \link LogStream::setLevel LogStream::setLevel \endlink or a temporary level (as set by \link LogStream::level LogStream::level \endlink for a single line only). For each line stored, the list of associated streams is checked whether the loglevel falls into the range declared by the stream's minimum and maximum level. If this condition is met, the logline (with its prefix, see \link LogStream::setPrefix LogStream::setPrefix \endlink ) is also copied to the associated stream and this stream is flushed, too. */ class BALL_EXPORT LogStreamBuf : public std::streambuf { friend class LogStream; public: /** @name Constants */ //@{ static const int MAX_LEVEL; static const int MIN_LEVEL; static const Time MAX_TIME; //@} /** @name Constructors and Destructors */ //@{ /** Default constructor. Create a new LogStreamBuf object. */ LogStreamBuf(); /** Destructor. Destruct the buffer and free all stored messages strings. */ virtual ~LogStreamBuf(); //@} /** @name Debugging and Diagnostics */ //@{ /** Dump method. Dumps the contents of the whole message buffer including time and log level. */ virtual void dump(std::ostream& s); //@} /** @name Stream methods */ //@{ /** Sync method. This method is called as soon as the ostream is flushed (especially this method is called by flush or endl). It transfers the contents of the streambufs putbuffer into a logline if a newline or linefeed character is found in the buffer ("\n" or "\r" resp.). The line is then removed from the putbuffer. Incomplete lines (not terminated by "\n" / "\r" are stored in incomplete_line_. */ virtual int sync(); /** Overflow method. This method calls sync and streambuf::overflow(c) to prevent a buffer overflow. */ virtual int overflow(int c = -1); //@} BALL_EXPORT struct StreamStruct { std::ostream* stream; string prefix; int min_level; int max_level; LogStreamNotifier* target; StreamStruct() : stream(0), min_level(MIN_LEVEL), max_level(MAX_LEVEL), target(0) { } // Delete the notification target. ~StreamStruct() { } }; protected: struct LoglineStruct { int level; string text; Time time; LoglineStruct() : level(0), text(""), time(0) {} }; typedef struct LoglineStruct Logline; // interpret the prefix format string and return the expanded prefix string expandPrefix_(const string& prefix, int level, Time time) const; char* pbuf_; vector loglines_; int level_; int tmp_level_; list stream_list_; string incomplete_line_; }; /// class BALL_EXPORT LogStreamNotifier { public: /// LogStreamNotifier(); /// virtual ~LogStreamNotifier(); /// virtual void logNotify(); /// void registerAt(LogStream& log_stream, int min_level = LogStreamBuf::MIN_LEVEL, int max_level = LogStreamBuf::MAX_LEVEL); /// void unregister(); protected: std::stringstream stream_; LogStream* registered_at_; }; /** Log Stream Class. \par \par */ class BALL_EXPORT LogStream : public std::ostream { public: /** @name Enums */ //@{ /** Log levels. Constants for the different predefined log levels. Use \link LogStream::ERROR ERROR \endlink to indicate a severe error, \link LogStream::WARNING WARNING \endlink to indicate a problem that could be fixed or is of minor importance, and \link LogStream::INFORMATION INFORMATION \endlink for messages that do not indicate any problem (e.g. progress messages). */ enum LogStreamLevel { /** Loglevels >= ERROR should be used to indicate errors */ ERROR_LEVEL = 2000 , /** Loglevels >= WARNING should be used to indicate warnings */ WARNING_LEVEL = 1000, /** Loglevels >= INFORMATION indicate information messages */ INFORMATION_LEVEL = 0 }; //@} /** @name Constructors and Destructors */ //@{ /** Constructor. Creates a new LogStream object that is not associated with any stream. If the argument associate_stdio is set to true, cout is associated with all messages of levels \link LogStream::INFORMATION INFORMATION \endlink and \link LogStream::WARNING WARNING \endlink , and cerr is associated with all messages of level \link LogStream::ERROR ERROR \endlink . @param buf @param delete_buf @param associate_stdio bool, default is false */ LogStream(LogStreamBuf* buf = 0, bool delete_buf = true, bool associate_stdio = false); /** Destructor. Clears all message buffers. */ virtual ~LogStream(); //@} /** @name Stream Methods */ //@{ /** rdbuf method of ostream. This method is needed to access the LogStreamBuf object. */ LogStreamBuf* rdbuf(); /** Arrow operator. */ LogStreamBuf* operator -> (); //@} /** @name Loglevel management */ //@{ /** Assign a new log level. This method assigns a new loglevel which will be used for all messages sent to the LogStream after that call (except for messages which use the temporary loglevel set by \link LogStream::level level \endlink ). */ void setLevel(int level); /** Return the current log level. The LogStreamBuf object has an internal current log level (level_). It is set to 0 by the LogStreamBuf default constructor. This method returns rdbuf()->level_ if rdbuf() does not return a null pointer, 0 otherwise. @return int the current log level */ int getLevel(); /** Set a temporary log level. Using level, a temporary loglevel may be defined. It is valid unly until the next flush or endl is issued. \par Use this command to log a single line with a certain log level. \par Example: log << "log message 1" << endl; \par log.level(4) << "log message 2" << endl; \par log << "log message 3" << endl; \par In this example, only the second message will be logged using level 4. @return LogStream the log stream @param level the temporary log level */ LogStream& level(int level); /** Log an information message. This method is equivalent to \link LogStream::level level \endlink (LogStream::INFORMATION + n). @param n the channel */ LogStream& info(int n = 0); /** Log an error message. This method is equivalent to \link LogStream::level level \endlink (LogStream::ERROR + n). @param n the channel */ LogStream& error(int n = 0); /** Log an information message. This method is equivalent to \link LogStream::level level \endlink (LogStream::WARNING + n). @param n the channel */ LogStream& warn(int n = 0); //@} /** @name Associating Streams */ //@{ /** Associate a new stream with this logstream. This method inserts a new stream into the list of associated streams and sets the corresponding minimum and maximum log levels. Any message that is subsequently logged, will be copied to this stream if its log level is between min_level and max_level. If min_level and max_level are omitted, all messages are copied to this stream. If min_level and max_level are equal, this function can be used to listen to a specified channel. @param s a reference to the stream to be associated @param MIN_LEVEL the minimum level of messages copied to this stream @param MAX_LEVEL the maximum level of messages copied to this stream */ void insert (std::ostream& s, int min_level = LogStreamBuf::MIN_LEVEL, int max_level = LogStreamBuf::MAX_LEVEL); /** Remove an association with a stream. Remove a stream from the stream list and avoid the copying of new messages to this stream. \par If the stream was not in the list of associated streams nothing will happen. @param s the stream to be removed */ void remove(std::ostream& s); /** Add a notification target */ void insertNotification(std::ostream& s, LogStreamNotifier& target, int min_level = LogStreamBuf::MIN_LEVEL, int max_level = LogStreamBuf::MAX_LEVEL); /** Set the minimum log level of an associated stream. This method changes the minimum log level of an already associated stream. However, if the stream is not associated, nothing will happen. @param s the associated stream @param min_level the new minimum level */ void setMinLevel(const std::ostream& s, int min_level); /** Set the maximum log level of an associated stream. This method changes the maximum log level of an already associated stream. However, if the stream is not associated, nothing will happen. @param s the associated stream @param max_level the new minimum level */ void setMaxLevel(const std::ostream& s, int max_level); /** Set prefix for output to this stream. Each line written to the stream will be prefixed by this string. The string may also contain trivial format specifiers to include loglevel and time/date of the logged message. \par The following format tags are recognized: - %l loglevel - %y message type ("Error", "Warning", "Information", "-") - %T time (HH:MM:SS) - %t time in short format (HH:MM) - %D date (DD.MM.YYYY) - %d date in short format (DD.MM.) - %S time and date (DD.MM.YYYY, HH:MM:SS) - %s time and date in short format (DD.MM., HH:MM) - %% percent sign (escape sequence) */ void setPrefix(const std::ostream& s, const string& prefix); /// Disable all output void disableOutput() throw(); /// Enable all output void enableOutput() throw(); /// Is Output enabled? bool outputEnabled() const throw(); /// void flush() throw(); //@} /** @name Message Buffer Management */ //@{ /** Clear the message buffer. This method removes all stored messages from the message buffer. */ void clear(); /** Return the number of lines. This method retruns the number of lines in the buffer for a given range of levels. \par If the range is omitted, the total number of messages is returned. @return Size the number of lines matching the log level range @param min_level the minimum log level for the counted messages @param max_level the maximum log level for the counted messages */ Size getNumberOfLines (int min_level = LogStreamBuf::MIN_LEVEL, int max_level = LogStreamBuf::MAX_LEVEL) const; /** Return the text of a specific line. This method returns the content of a specific message without time and level. @return string the text of the message @param index the index of the line */ string getLineText(const Index& index) const; /** Return the log time of a specific line @param index the index of the messages @return Time the time of the message */ Time getLineTime(const Index& index) const; /** Return the log level of a specific line. If the given line does not exists, {\em -1} is returned. @param index the index of the message @return int the level */ int getLineLevel(const Index& index) const; /** Retrieve a list of indices of lines that match certain criteria. If a criterion is left empty, it is not used. @param min_level the minimum level of messages @param max_level the maximum level of messages @param earliest (long) the time of messages to start filtering @param latest (long) the time of messages to stop filtering @param s a string to look for */ list filterLines (int min_level = LogStreamBuf::MIN_LEVEL, int max_level = LogStreamBuf::MAX_LEVEL, Time earliest = 0, Time latest = LogStreamBuf::MAX_TIME, const string& s = "") const; //@} private: typedef std::list::iterator StreamIterator; StreamIterator findStream_(const std::ostream& stream); bool hasStream_(std::ostream& stream); bool bound_() const; // flag needed by the destructor to decide whether the streambuf // has to be deleted. If the default ctor is used to create // the LogStreamBuf, delete_buffer_ is set to true and the ctor // also deletes the buffer. bool delete_buffer_; bool disable_output_; }; /** Global static instance of a logstream. This instance of LogStream is by default bound to cout cerr by calling the default constructor. */ BALL_EXPORT extern LogStream Log; //@} # ifndef BALL_NO_INLINE_FUNCTIONS # include # endif } // namespace BALL #endif // BALL_COMMON_LOGSTREAM_H ugene-1.9.8/src/plugins_3rdparty/ball/src/include/BALL/COMMON/exception.h0000644000175000017500000003370711651544325024427 0ustar ilyailya// -*- Mode: C++; tab-width: 2; -*- // vi: set ts=2: // // $Id: exception.h,v 1.51 2005-12-23 17:01:39 amoll Exp $ // #ifndef BALL_COMMON_EXCEPTION_H #define BALL_COMMON_EXCEPTION_H #ifndef BALL_CONFIG_CONFIG_H # include #endif #ifndef BALL_COMMON_GLOBAL_H # include #endif #include #include namespace BALL { class String; /** Exception \ingroup Common */ namespace Exception { /** General exception class. This class is intended as a base class for all other exceptions. Each exception class should define a constructor taking a string and an int as parameters. These two values are interpreted as the current filename and line number and is usually printed in case of an uncaught exception. To support this feature, each throw directive should look as follows: \par throw Exception::GeneralException(__FILE__, __LINE__); \par __FILE__ and __LINE__ are built-in preprocessor macros that hold the desired information. \par BALL provides its own \link BALL::Exception::GlobalExceptionHandler::terminate terminate \endlink handler. This handler extracts as much information as possible from the exception, prints it to cerr and \link BALL::LogStream Log \endlink , and finally calls exits the program cleanly (with exit code 1). This can be rather inconvenient for debugging, since you are told where the exception was thrown, but in general you do not know anything about the context. Therefore terminate can also create a core dump. Using a debugger (e.g. dbx or gdb) you can then create a stack traceback. To create a core dump, you should set the environment variable BALL_DUMP_CORE to any (non empty) value. \ingroup Common */ class BALL_EXPORT GeneralException : public std::exception { public: /** @name Constructors and Destructors */ //@{ /// Default constructor GeneralException() throw(); /// Constructor GeneralException(const char* file, int line) throw(); /// Constructor GeneralException (const char* file, int line, const String& name , const String& message) throw(); /// Copy constructor GeneralException(const GeneralException& exception) throw(); /// Destructor virtual ~GeneralException() throw(); //@} /** @name Accessors */ //@{ /// Returns the name of the exception const char* getName() const throw(); /// Returns the error message of the exception const char* getMessage() const throw(); /// Modify the exception's error message void setMessage(const std::string& message) throw(); /// Returns the line number where it occured int getLine() const throw(); /// Returns the file where it occured const char* getFile() const throw(); //@} protected: const char* file_; int line_; std::string name_; std::string message_; }; /** Index underflow. Throw this exception to indicate an index that was smaller than allowed. The constructor has two additional arguments, the values of which should be set to the index that caused the failure and the smallest allowed value to simplify debugging. @param index the value of the index causing the problem @param size smallest value allowed for index */ class BALL_EXPORT IndexUnderflow : public GeneralException { public: IndexUnderflow(const char* file, int line, Index index = 0, Size size = 0) throw(); protected: Size size_; Index index_; }; /** Size underflow. Throw this exception to indicate a size was smaller than allowed. The constructor has an additional argument: the value of of the requested size. This exception is thrown, if buffer sizes are insufficient. @param size the size causing the problem */ class BALL_EXPORT SizeUnderflow : public GeneralException { public: SizeUnderflow(const char* file, int line, Size size = 0) throw(); protected: Size size_; }; /** Index overflow. Throw this exception to indicate an index that was larger than allowed. The constructor has two additional arguments, the values of which should be set to the index that caused the failure and the largest allowed value to simplify debugging. @param index the value of the index causing the problem @param size largest value allowed for index */ class BALL_EXPORT IndexOverflow : public GeneralException { public: IndexOverflow(const char* file, int line, Index index = 0, Size size = 0) throw(); protected: Size size_; Index index_; }; /** Invalid range. Use this exception to indicate a general range problems. */ class BALL_EXPORT InvalidRange : public GeneralException { public: InvalidRange(const char* file, int line, float value) throw(); }; /** Invalid Size Throw this exception to indicate that a size was unexpected. The constructor has an additional argument: the value of of the requested size. @param size the size causing the problem */ class BALL_EXPORT InvalidSize : public GeneralException { public: InvalidSize(const char* file, int line, Size size = 0) throw(); protected: Size size_; }; /** Out of range. Use this exception to indicate that a given value is out of a defined range, i. e. not within the domain of a function. */ class BALL_EXPORT OutOfRange : public GeneralException { public: OutOfRange(const char* file, int line) throw(); }; /** Invalid format. This exception indicates a conversion problem when converting from one type to another. It is thrown, if a conversion from ascii to numeric formats or vice versa failed. */ class BALL_EXPORT InvalidFormat : public GeneralException { public: InvalidFormat(const char* file, int line, const String& s) throw(); ~InvalidFormat() throw(); protected: std::string format_; }; /** Illegal self operation. Throw this excpetion to indicate an invalid operation on the object itself. In general these operations are self assignments or related methods. */ class BALL_EXPORT IllegalSelfOperation : public GeneralException { public: IllegalSelfOperation(const char* file, int line) throw(); }; /** Null pointer argument is invalid. Use this exception to indicate a failure due to an argument not containing a pointer to a valid object, but a null pointer. */ class BALL_EXPORT NullPointer : public GeneralException { public: NullPointer(const char* file, int line) throw(); }; /** Invalid iterator. The iterator on which an operation should be performed was invalid. */ class BALL_EXPORT InvalidIterator : public GeneralException { public: InvalidIterator(const char* file, int line) throw(); }; /** Incompatible iterator. The iterators could not be assigned because they are bound to different containers. */ class BALL_EXPORT IncompatibleIterators : public GeneralException { public: IncompatibleIterators(const char* file, int line) throw(); }; /** Not implemented exception. This exception should be thrown to indicate not yet inplemented methods. If you take the time to use the detailed constructor instead of the default constructor, identification of the concerned source will get much easier! */ class BALL_EXPORT NotImplemented : public GeneralException { public: NotImplemented(const char* file, int line) throw(); }; /** Illegal tree operation. This exception is thrown to indicate that an illegal tree operation i.e. node->setLeftChild(node) was requested. */ class BALL_EXPORT IllegalTreeOperation : public GeneralException { public: IllegalTreeOperation(const char* file, int line) throw(); }; /** Out of memory. Throw this exception to indicate that an allocation failed. This exception is thrown in the BALL new handler. @param size the number of bytes that should have been allocated @see GlobalException::newHandler */ class BALL_EXPORT OutOfMemory : public GeneralException, public std::bad_alloc { public: OutOfMemory(const char* file, int line, Size size = 0) throw(); virtual ~OutOfMemory() throw(); protected: Size size_; }; /** Buffer overflow exception. */ class BALL_EXPORT BufferOverflow : public GeneralException { public: BufferOverflow(const char* file, int line) throw(); }; /** Division by zero error. */ class BALL_EXPORT DivisionByZero : public GeneralException { public: DivisionByZero(const char* file, int line) throw(); }; /** Out of grid error. */ class BALL_EXPORT OutOfGrid : public GeneralException { public: OutOfGrid(const char* file, int line) throw(); }; /** File not found. A given file could not be found. */ class BALL_EXPORT FileNotFound : public GeneralException { public: FileNotFound(const char* file, int line, const String& filename) throw(); ~FileNotFound() throw(); String getFilename() const throw(); protected: std::string filename_; }; /** Invalid Position. A given position in three dimensional is invalid. */ class BALL_EXPORT IllegalPosition : public GeneralException { public: IllegalPosition(const char* file, int line, float x, float y, float z) throw(); }; /** Parse Error. A given expression could not be parsed. */ class BALL_EXPORT ParseError : public GeneralException { public: /// ParseError(const char* file, int line, const String& expression, const String& message) throw(); }; /** Precondition failed. A precondition (as defined by BALL_PRECONDITION_EXCEPTION) has failed. */ class BALL_EXPORT Precondition : public GeneralException { public: /// Precondition(const char* file, int line, const char* condition) throw(); }; /** Postcondition failed. A postcondition (as defined by BALL_POSTCONDITION_EXCEPTION) has failed. */ class BALL_EXPORT Postcondition : public GeneralException { public: /// Postcondition(const char* file, int line, const char* condition) throw(); }; /// Exception to be thrown if an invalid option is given class BALL_EXPORT InvalidOption: public Exception::GeneralException { public: /// InvalidOption(const char* file, int line, String option) throw(); }; /// Exception to be thrown if too many errors occur, e.g. in ForceField class BALL_EXPORT TooManyErrors : public Exception::GeneralException { public: /// TooManyErrors(const char* file, int line) throw(); }; /// Exception to be thrown if too many bonds for one atom class BALL_EXPORT TooManyBonds : public Exception::GeneralException { public: /// TooManyBonds(const char* file, int line, const String& error) throw(); }; /** Class handling uncaught exception globally. */ class BALL_EXPORT GlobalExceptionHandler { public: /** @name Constructors */ //@{ /** Default constructor. This constructor installs the BALL specific handlers for terminate, unexpected, and new_handler. terminate or unexpected are called to abort a program if an exception was not caught or a function exits via an exception that is not allowed by its exception specification. Both functions are replaced by a function of GlobalExceptionHandler that tries to determine the last exception thrown. This mechanism only works, if all exceptions are defrived from \link GeneralException GeneralException \endlink . \par The default new_handler is replaced by \link newHandler newHandler \endlink and throws an exception of type \link OutOfMemory OutOfMemory \endlink instead of bad_alloc (the default behaviour defined in the ANSI C++ standard). */ GlobalExceptionHandler() throw(); //@} /** @name Accessors */ //@{ /// Assign the name of the exception. This should agree with the class name. static void setName(const String& name) throw(); /// Set the error message static void setMessage(const String& message) throw(); /// Set the line number the exception was thrown. Should be set to __LINE__ in most cases. static void setLine(int line) throw(); /// The source file name where the exception was thrown static void setFile(const String& file) throw(); /// Set all exception attributes static void set (const String& file, int line, const String& name, const String& message) throw(); //@} protected: /// The BALL replacement for terminate static void terminate() throw(); /// The BALL new handler static void newHandler() throw(Exception::OutOfMemory); static std::string file_; static int line_; static std::string name_; static std::string message_; }; /** Global static instance of GlobalExceptionHandler */ BALL_EXPORT extern GlobalExceptionHandler globalHandler; } /** Output operator for exceptions. All BALL exceptions can be printed to an arbitrary output stream. Information written contains the exception class, the error message, and the location (file, line number). The following code block can thus be used to catch any BALL exceptions and convert them to human readable information: \verbatim try { .... // some code which potentially throws an exception } catch (Exception::GeneralException e) { Log.error() << "caught exception: " << e << std::endl; } \endverbatim \ingroup Common */ BALL_EXPORT std::ostream& operator << (std::ostream& os, const Exception::GeneralException& e); } // namespace BALL #endif // BALL_COMMON_EXCEPTION_H ugene-1.9.8/src/plugins_3rdparty/ball/src/include/BALL/common.h0000644000175000017500000000127611651544326022726 0ustar ilyailya// -*- Mode: C++; tab-width: 2; -*- // vi: set ts=2: // // $Id: common.h,v 1.3 2002-02-27 12:18:17 sturm Exp $ // common BALL includes #ifndef BALL_COMMON_H #define BALL_COMMON_H #ifndef BALL_CONFIG_CONFIG_H # include #endif #ifndef BALL_COMMON_DEBUG_H # include #endif #ifndef BALL_COMMON_CREATE_H # include #endif #ifndef BALL_COMMON_VERSION_H # include #endif #ifndef BALL_COMMON_MACROS_H # include #endif #ifndef BALL_COMMON_GLOBAL_H # include #endif #ifndef BALL_COMMON_LOGSTREAM_H # include #endif #endif // BALL_COMMON_H ugene-1.9.8/src/plugins_3rdparty/ball/src/include/BALL/STRUCTURE/0000755000175000017500000000000011651544310022650 5ustar ilyailyaugene-1.9.8/src/plugins_3rdparty/ball/src/include/BALL/STRUCTURE/triangleEdge.h0000644000175000017500000000746011651544326025431 0ustar ilyailya// -*- Mode: C++; tab-width: 2; -*- // vi: set ts=2: // // $Id: triangleEdge.h,v 1.11.18.1 2007-03-25 21:25:33 oliver Exp $ // #ifndef BALL_STRUCTURE_TRIANGLEEDGE_H #define BALL_STRUCTURE_TRIANGLEEDGE_H #ifndef BALL_STRUCTURE_GRAPHEDGE_H # include #endif #ifndef BALL_STRUCTURE_GRAPHFACE_H # include #endif #ifndef BALL_STRUCTURE_GRAPHVERTEX_H # include #endif namespace BALL { class Triangle; class TrianglePoint; class TriangulatedSurface; class TriangulatedSphere; class TriangulatedSES; class TriangulatedSAS; class SESTriangulator; class SASTriangulator; /** Generic TriangleEdge Class. \ingroup Surface */ class BALL_EXPORT TriangleEdge : public GraphEdge< TrianglePoint,TriangleEdge,Triangle > { public: /** @name Class friends - class Triangle - class TriangleEdge - class TriangulatedSurface - class TriangulatedSphere - class TriangulatedSES - class TriangulatedSAS - class SESTriangulator - class SASTriangulator */ friend class Triangle; friend class TrianglePoint; friend class TriangulatedSurface; friend class TriangulatedSphere; friend class TriangulatedSES; friend class TriangulatedSAS; friend class SESTriangulator; friend class SASTriangulator; BALL_CREATE(TriangleEdge) /** @name Constructors and Destructors */ //@{ /** Default constructor. This method creates a new TriangleEdge object. */ TriangleEdge() throw(); /** Copy constructor. Create a new TriangleEdge object from another. @param edge the TriangleEdge object to be copied @param deep if deep = false, all pointers are set to NULL (default). Otherwise the new TriangleEdge object is linked to the neighbours of the old TriangleEdge object. */ TriangleEdge(const TriangleEdge& edge, bool deep = false) throw(); /** Destructor. Destructs the TriangleEdge object. */ virtual ~TriangleEdge() throw(); //@} /** @name Accessors */ //@{ /** Set one of the two points of the TriangleEdge. @param i the first point is changed if i = 0, the second otherwise @param point a pointer to the new point */ void setPoint(Position i, TrianglePoint* point) throw(); /** Return one of the two points of the TriangleEdge. @param i @return TrianglePoint* a pointer to the first point if i = 0, a pointer to the second point otherwise */ TrianglePoint* getPoint(Position i) const throw(); /** Set one of the two triangles of the TriangleEdge. @param i change the first triangle, if i = 0, the second otherwise @param triangle a pointer to the new triangle */ void setTriangle(Position i, Triangle* triangle) throw(); /** Return one of the two triangles of the TriangleEdge. @param i @return Triangle* a pointer to the first triangle if i = 0, a pointer to the second triangle otherwise */ Triangle* getTriangle(Position i) const throw(); //@} /** @name Predicates */ //@{ /** Equality operator @return bool true if the vertices are similar, false otherwise. */ virtual bool operator == (const TriangleEdge&) const throw(); /** Inequality operator @return bool false if the vertices are similar, true otherwise. */ virtual bool operator != (const TriangleEdge&) const throw(); /** Similarity operator @return bool true */ virtual bool operator *= (const TriangleEdge&) const throw(); //@} }; /** @name Storers */ //@{ /** Output- Operator */ BALL_EXPORT std::ostream& operator << (std::ostream& s, const TriangleEdge& edge); //@} } // namespace BALL #endif // BALL_STRUCTURE_TRIANGLEEDGE_H ugene-1.9.8/src/plugins_3rdparty/ball/src/include/BALL/STRUCTURE/RSEdge.h0000644000175000017500000002615111651544325024145 0ustar ilyailya// -*- Mode: C++; tab-width: 2; -*- // vi: set ts=2: // // $Id: RSEdge.h,v 1.33.18.1 2007-03-25 21:25:22 oliver Exp $ // #ifndef BALL_STRUCTURE_RSEDGE_H #define BALL_STRUCTURE_RSEDGE_H #ifndef BALL_STRUCTURE_GRAPHEDGE_H # include #endif #ifndef BALL_MATHS_ANGLE_H # include #endif #ifndef BALL_MATHS_CIRCLE3_H # include #endif #ifndef BALL_MATHS_VECTOR3_H # include #endif namespace BALL { class RSFace; class RSVertex; class ReducedSurface; class RSComputer; class SESEdge; class SESFace; class SESVertex; class SolventExcludedSurface; class SESComputer; class SESSingularityCleaner; class TriangulatedSES; class SESTriangulator; class SASEdge; class SASFace; class SASVertex; class SolventAccessibleSurface; class TriangulatedSAS; class SASTriangulator; /** Generic RSEdge Class. \ingroup Surface */ class BALL_EXPORT RSEdge : public GraphEdge< RSVertex,RSEdge,RSFace > { public: /** @name Class friends - class RSFace - class RSVertex - class ReducedSurface - class RSComputer - class SESEdge - class SESFace - class SESVertex - class SolventExcludedSurface - class SESComputer - class TSESSingularityCleaner - class TriangulatedSES - class SESTriangulator - class SASEdge - class SASFace - class SASVertex \itme class SolventAccessibleSurface - class TriangulatedSAS - class SASTriangulator */ friend class RSFace; friend class RSVertex; friend class ReducedSurface; friend class RSComputer; friend class SESEdge; friend class SESFace; friend class SESVertex; friend class SolventExcludedSurface; friend class SESComputer; friend class SESSingularityCleaner; friend class TriangulatedSES; friend class SESTriangulator; friend class SASEdge; friend class SASFace; friend class SolventAccessibleSurface; friend class SASVertex; friend class TriangulatedSAS; friend class SASTriangulator; BALL_CREATE(RSEdge) /** @name Constructors and Destructors */ //@{ /** Default constructor. This method creates a new RSEdge object. */ RSEdge() throw(); /** Copy constructor. Create a new RSEdge object from another. @param rsedge the RSEdge object to be copied @param deep if deep = false, all pointers are set to NULL (default). Otherwise the new RSEdge object is linked to the neighbours of the old RSEdge object. */ RSEdge(const RSEdge& rsedge, bool deep = false) throw(); /** Detailled constructor. Create a new RSEdge object from a lot of nice objects @param vertex1 assigned to the first vertex @param vertex2 assigned to the second vertex @param face1 assigned to the first face @param face2 assigned to the second face @param center_of_torus assigned to the center of the torus @param radius_of_torus assigned to the radius of the torus @param angle assigned to th angle @param circle1 assigned to the first contact circle @param circle2 assigned to the second contact circle @param intersection_point1 assigned to the first intersection point (in singular case) @param intersection_point2 assigned to the second intersection point (in singular case) @param singular @param index assigned to the index */ RSEdge(RSVertex* vertex1, RSVertex* vertex2, RSFace* face1, RSFace* face2, const TVector3& center_of_torus, const double& radius_of_torus, const TAngle& angle, const TCircle3& circle1, const TCircle3& circle2, const TVector3& intersection_point1, const TVector3& intersection_point2, bool singular, Index index) throw(); /** Destructor. Destructs the RSEdge object. The neighboured faces and vertices are {/bf not} destructed. */ virtual ~RSEdge() throw(); //@} /** @name Assignment */ //@{ /** Assign from another RSEdge. @param rsedge the RSEdge object to assign from @param deep if deep = false, all pointers are set to NULL (default). Otherwise the RSEdge object is linked to the neighbours of the RSEdge object to assign from. */ void set(const RSEdge& rsedge, bool deep = false) throw(); /** Assign from another RSEdge. The RSEdge object is linked to the neighbours of the RSEdge object to assign from. @param rsedge the RSEdge object to assign from */ RSEdge& operator = (const RSEdge& rsedge) throw(); /** Assign from a lot of nice objects @param vertex0 assigned to the first vertex @param vertex1 assigned to the second vertex @param face0 assigned to the first face @param face1 assigned to the second face @param center_of_torus assigned to the center of the torus @param radius_of_torus assigned to the radius of the torus @param angle assigned to th angle @param circle0 assigned to the first contact circle @param circle1 assigned to the second contact circle @param intersection_point0 assigned to the first intersection point (in singular case) @param intersection_point1 assigned to the second intersection point (in singular case) @param singular @param index assigned to the index */ void set(RSVertex* vertex0, RSVertex* vertex1, RSFace* face0, RSFace* face1, const TVector3& center_of_torus, const double& radius_of_torus, const TAngle& angle, const TCircle3& circle0, const TCircle3& circle1, const TVector3& intersection_point0, const TVector3& intersection_point1, bool singular, Index index) throw(); //@} /** @name Accessors */ //@{ /** Set the center of the torus. Set the center of the torus described by the probe sphere when it rolls over the RSEdge. @param center the new center */ void setCenterOfTorus(const TVector3& center) throw(); /** Return the center of the torus. Return the center of the torus described by the probe sphere when it rolls over the RSEdge. @return TVector3 the center of the torus */ TVector3 getCenterOfTorus() const throw(); /** Set the major radius of the torus. Set the major radius of the torus described by the probe sphere when it rolls over the RSEdge. @param radius the new radius */ void setMajorRadiusOfTorus(const double& radius) throw(); /** Return the major radius of the torus. Return the major radius of the torus described by the probe sphere when it rolls over the RSEdge. @return TVector3 the major radius of the torus */ double getMajorRadiusOfTorus() const throw(); /** Set the rotation angle. Set the rotation angle between the starting and ending position of the probe sphere when it rolls over the RSEdge. @param angle the new rotation angle */ void setAngle(const TAngle& angle) throw(); /** Return the rotation angle. Return the rotation angle between the starting and ending position of the probe sphere when it rolls over the RSEdge. @return TAngle the rotation angle */ TAngle getAngle() const throw(); /** Set one of the two contact circles. Set one of the two contact circles of the probe sphere with the two RSVertices. @param i the first contact circle is changed if i = 0, the second otherwise @param circle the new contact circle */ void setContactCircle(Position i, const TCircle3& circle) throw(); /** Return one of the the contact circles. Return one of the the contact circles of the probe sphere with the two RSVertices @param i @return TCircle3 the contact circle with the first RSVertex if i = 0, the contact circle with the second RSVertex otherwise */ TCircle3 getContactCircle(Position i) const throw(); /** Set one of the intersection points. Set one of the intersection points of the probe sphere with the RSEdge. @param i the first intersection point is changed if i = 0, the second otherwise @param point the new intersection point */ void setIntersectionPoint(Position i, const TVector3& point) throw(); /** Return one of the intersection points. Return one of the intersection points of the probe sphere with the RSEdge. If the RSEdge not is singular, an exception is thrown. @return TVector3 the intersection point near to the first RSVertex if i = 0, the intersection point near to the second RSVertex otherwise */ TVector3 getIntersectionPoint(Position i) const throw(Exception::GeneralException); /** Set singular */ void setSingular(bool singular) throw(); //@} /** @name Predicates */ //@{ /** Equality operator. @return bool, true if all vertices and all faces are equal modulo order, false otherwise */ virtual bool operator == (const RSEdge& rsedge) const throw(); /** Inequality operator. @return bool false if all vertices and all faces are equal modulo order, true otherwise */ virtual bool operator != (const RSEdge& rsedge) const throw(); /** Similarity operator. @return bool true if all vertices are similar modulo order, false otherwise */ virtual bool operator *=(const RSEdge& rsedge) const throw(); /** isSingular @return bool true if the RSEdge is singular, false otherwise */ bool isSingular() const throw(); /** isFree @return bool true if the RSEdge is free, false otherwise */ bool isFree() const throw(); //@} protected: /*_ @name Attributes */ //@{ /*_ The center of the torus described by the probe when ir rolls over the RSEdge */ TVector3 center_of_torus_; /*_ The major radius of the torus described by the probe when ir rolls over the RSEdge */ double radius_of_torus_; /*_ The rotation angle between the starting and ending position of the probe sphere when it rolls over the RSEdge */ TAngle angle_; /*_ The contact circle of the probe sphere with the first RSVertex */ TCircle3 circle0_; /*_ The contact circle of the probe sphere with the second RSVertex */ TCircle3 circle1_; /*_ The intersection point of the probe sphere with the RSEdge near to the first RSVertex (in singular case). */ TVector3 intersection_point0_; /*_ The intersection point of the probe sphere with the RSEdge near to the second RSVertex (in singular case). */ TVector3 intersection_point1_; /*_ singular */ bool singular_; //@} }; /** @name Storers */ //@{ /** Output- Operator */ BALL_EXPORT std::ostream& operator << (std::ostream& s, const RSEdge& rsedge); //@} } // namespace BALL #endif // BALL_STRUCTURE_RSEDGE_H ugene-1.9.8/src/plugins_3rdparty/ball/src/include/BALL/STRUCTURE/SESVertex.h0000644000175000017500000001220011651544325024652 0ustar ilyailya// -*- Mode: C++; tab-width: 2; -*- // vi: set ts=2: // // $Id: SESVertex.h,v 1.22 2005-12-23 17:02:02 amoll Exp $ // #ifndef BALL_STRUCTURE_SESVERTEX_H #define BALL_STRUCTURE_SESVERTEX_H #ifndef BALL_STRUCTURE_GRAPHVERTEX_H # include #endif #ifndef BALL_MATHS_VECTOR3_H # include #endif namespace BALL { class SESEdge; class SESFace; class SolventExcludedSurface; class SESComputer; class SESSingularityCleaner; class TriangulatedSES; class SESTriangulator; /** Generic SESVertex Class. \ingroup Surface */ class BALL_EXPORT SESVertex : public GraphVertex< SESVertex,SESEdge,SESFace > { public: /** @name Class friends - class SESEdge - class SESFace - class SolventExcludedSurface - class SESComputer - class TSESSingulatityCleaner - class TriangulatedSES - class SESTriangulator */ friend class SESEdge; friend class SESFace; friend class SolventExcludedSurface; friend class SESComputer; friend class SESSingularityCleaner; friend class TriangulatedSES; friend class SESTriangulator; BALL_CREATE(SESVertex) /** @name Constructors and Destructors */ //@{ /** Default constructor. This method creates a new SESVertex object. */ SESVertex() throw(); /** Copy constructor. Create a new SESVertex object from another. @param sesvertex the SESVertex object to be copied @param deep if deep = false, all pointers are set to NULL (default). Otherwise the new SESVertex object is linked to the neighbours of the old SESVertex object. */ SESVertex(const SESVertex& sesvertex, bool deep = false) throw(); /** Detailled constructor. Create a new SESVertex object from some nice objects. @param point assigned to the point representet by the vertex @param normal assigned to the normal vector of the vertex @param atom assigned to the index of the closest atom @param index assigned to the index of the vertex */ SESVertex (const TVector3& point, const TVector3& normal, Index atom, Index index) throw(); /** Destructor. Destructs the RSVertex object. */ virtual ~SESVertex() throw(); //@} /** @name Assignment */ //@{ /** Assign from another SESVertex. @param sesvertex the SESVertex object to assign from @param deep if deep = false, all pointers are set to NULL (default). Otherwise the new SESVertex object is linked to the neighbours of the SESVertex object to assign from. */ void set(const SESVertex& sesvertex, bool deep = false) throw(); /** Assign from another SESVertex. The new SESVertex object is linked to the neighbours of the SESVertex object to assign from. @param sesvertex the SESVertex object to assign from */ SESVertex& operator = (const SESVertex& sesvertex) throw(); /** Assign to two TVector3's and two indices. @param point assigned to the point represented by the vertex @param normal assigned to the normal vector of th vertex @param atom assigned to the index of the closest atom @param index assigned to the index of the vertex */ void set(const TVector3 point, const TVector3& normal, Index atom, Index index) throw(); /** Set the point represented by the SESVertex. @param point the new point */ void setPoint(const TVector3& point) throw(); /** Return the point represented by the SESVertex. @return TVector3 the point represented by the vertex */ TVector3 getPoint() const throw(); /** Set the normal vector of the SESVertex. @param normal the new normal vector */ void setNormal(const TVector3& normal) throw(Exception::DivisionByZero); /** Return the normal vector of the SESVertex. @return TVector3 the normal vector of the vertex */ TVector3 getNormal() const throw(); /** Set the index of the closest atom of the SESVertex. @param atom the index of the closest atom */ void setAtom(Index atom) throw(); /** Return the index of the closest atom. @return Index the index of the closest atom */ Index getAtom() const throw(); //@} /** @name Predicates */ //@{ /** Equality operator. @return bool true */ virtual bool operator == (const SESVertex&) const throw(); /** Inequality operator. @return bool false */ virtual bool operator != (const SESVertex&) const throw(); /** Similarity operator. @return bool true */ virtual bool operator *= (const SESVertex&) const throw(); //@} protected: /** @name Attributes */ //@{ /*_ The coordinates of the vertex. */ TVector3 point_; /*_ The normal vector of the vertex. */ TVector3 normal_; /*_ The index of the closest atom. */ Index atom_; //@} }; /** @name Storers */ //@{ /** Output- Operator */ BALL_EXPORT std::ostream& operator << (std::ostream& s, const SESVertex& sesvertex); //@} } // namespace BALL #endif // BALL_SES_SESVERTEX_H ugene-1.9.8/src/plugins_3rdparty/ball/src/include/BALL/STRUCTURE/triangulatedSES.h0000644000175000017500000001614411651544326026074 0ustar ilyailya// -*- Mode: C++; tab-width: 2; -*- // vi: set ts=2: // // $Id: triangulatedSES.h,v 1.19.18.1 2007-03-25 21:25:34 oliver Exp $ // #ifndef BALL_STRUCTURE_TRIANGULATEDSES_H #define BALL_STRUCTURE_TRIANGULATEDSES_H #ifndef BALL_TRUCTURE_SOLVENTEXCLUDEDSURFACE_H # include #endif #ifndef BALL_STRUCTURE_TRIANGLE_H # include #endif #ifndef BALL_STRUCTURE_TRIANGLEEDGE_H # include #endif #ifndef BALL_STRUCTURE_TRIANGLEPOINT_H # include #endif #ifndef BALL_STRUCTURE_TRIANGULATEDSURFACE_H # include #endif #ifndef BALL_MATHS_ANGLE_H # include #endif #ifndef BALL_MATHS_CIRCLE3_H # include #endif #ifndef BALL_MATHS_SPHERE3_H # include #endif #ifndef BALL_MATHS_VECTOR3_H # include #endif #include #include namespace BALL { class SESTriangulator; /** Generic TriangulatedSES Class. \ingroup Surface */ class BALL_EXPORT TriangulatedSES : public TriangulatedSurface { public: /** @name Class friends - class SESTriangulator */ friend class SESTriangulator; BALL_CREATE(TriangulatedSES) /** @name Constructors and Destructors */ //@{ /** Default constructor. This method creates a new TriangulatedSES object. */ TriangulatedSES() throw(); /** Copy constructor. Create a new TriangulatedSES object from another. @param surface the TriangulatedSES object to be copied @param bool ignored - just for interface consistency */ TriangulatedSES(const TriangulatedSES& surface, bool = true) throw(); /** Detailed constructor. Create a new empty TriangulatedSES object and set its SES. @param ses a pointer to the corresponding SES @param density the density to use by triangulation */ TriangulatedSES(SolventExcludedSurface* ses, const double& density) throw(); /** Destructor. Destructs the TriangulatedSES object. */ virtual ~TriangulatedSES() throw(); //@} /** @name Assignment */ //@{ /** Assign from another TriangulatedSES. @param surface the TriangulatedSES object to assign from @param bool ignored - just for interface consistency */ void set(const TriangulatedSES& surface, bool = true) throw(); /** Assign from another TriangulatedSES. @param surface the TriangulatedSES object to assign from */ TriangulatedSES& operator = (const TriangulatedSES& surface) throw(); /** Set the density used by triangulation. */ void setDensity(const double& density) throw(); /** Get the density used by triangulation. */ double getDensity() const throw(); //@} /** @name Accessors */ //@{ void compute(int& progress) throw(Exception::GeneralException,Exception::DivisionByZero); //@} protected: /*_ @name Attributes */ //@{ SolventExcludedSurface* ses_; double density_; //@} }; /** Generic SESTriangulator Class. \par \par \ingroup Surface */ class BALL_EXPORT SESTriangulator { public: BALL_CREATE(SESTriangulator) /** @name Constructors and Destructors */ //@{ /** Default constructor. This method creates a new SESTriangulator object. */ SESTriangulator() throw(); /** Detailed constructor. @param tses a pointer to the TriangulatedSES to compute */ SESTriangulator(TriangulatedSES* tses) throw(); /** Destructor. Destructs the SESTriangulator object. */ virtual ~SESTriangulator() throw(); //@} /** @name Accessors */ //@{ void run(int& progress) throw(Exception::GeneralException,Exception::DivisionByZero); private: void preProcessing() throw(); void triangulateToricFaces() throw(); void partitionSingularEdges() throw(); void triangulateContactFaces() throw(); void triangulateSphericFaces() throw(); void triangulateToricFace (SESFace* face, const double& probe_radius) throw(); void triangulateFreeToricFace (SESFace* face, const double& probe_radius) throw(); void triangulateSingularToricFace (SESFace* face, const double& probe_radius) throw(); void triangulateNonSingularToricFace (SESFace* face, const double& probe_radius) throw(); void partitionSingularEdge(SESEdge* singular_edge) throw(); void partitionFreeSingularEdge(SESEdge* singular_edge) throw(); void partitionNonFreeSingularEdge(SESEdge* singular_edge) throw(); void triangulateContactFace (SESFace* face, const TSphere3& sphere) throw(); bool triangulateSphericFace (SESFace* face, const TSphere3& sphere) throw(); bool buildSphericTriangles (SESFace* face, TriangulatedSES& part, const TSphere3& sphere, bool convex = true) throw(); bool buildFirstTriangle (SESFace* face, TriangulatedSES& part, std::list& border, const TSphere3& sphere, const HashSet& points, bool convex) throw(); SESEdge* firstSESEdge(const std::list& sesedge) throw(); void buildUnambiguousTriangle (TriangleEdge* edge, TrianglePoint* point, std::list& border, const TSphere3& sphere, TriangulatedSES& part, bool convex ) throw(); void buildAmbiguousTriangles (TriangleEdge* edge, std::list points, std::list& border, const TSphere3& sphere, TriangulatedSES& part, bool convex ) throw(); void createTriangleAndEdges (TriangleEdge* edge, TrianglePoint* point, const TSphere3& sphere, TriangleEdge*& edge1, bool& old1, TriangleEdge*& edge2, bool& old2, Triangle*& triangle, bool convex ) throw(); void partitionOfCircle (const TCircle3& circle, const TVector3& p0, const TAngle& phi, Size number_of_segments, vector< TVector3 >& partition, bool on_surface = true) throw(); Size numberOfRefinements(const double& density, const double& radius) throw(); void buildTemplateSpheres() throw(); void buildTriangles (SESEdge* edge0, SESEdge* edge1, SESEdge* edge2, SESEdge* edge3, const std::vector< TVector3 >& centers, const std::vector< TVector3 >& edge1_points, const std::vector< TVector3 >& edge3_points, const double& probe_radius) throw(); //@} protected: /*_ @name Attributes */ //@{ TriangulatedSES* tses_; std::vector point_; std::vector > edge_; HashMap > template_spheres_; double sqrt_density_; //@} }; } // namespace BALL #endif // BALL_STRUCTURE_TRIANGULATEDSES_H ugene-1.9.8/src/plugins_3rdparty/ball/src/include/BALL/STRUCTURE/triangle.h0000644000175000017500000001014611651544326024637 0ustar ilyailya// -*- Mode: C++; tab-width: 2; -*- // vi: set ts=2: // // $Id: triangle.h,v 1.10.18.1 2007-03-25 21:25:32 oliver Exp $ // #ifndef BALL_STRUCTURE_TRIANGLE_H #define BALL_STRUCTURE_TRIANGLE_H #ifndef BALL_STRUCTURE_GRAPHEDGE_H # include #endif #ifndef BALL_STRUCTURE_GRAPHFACE_H # include #endif #ifndef BALL_STRUCTURE_GRAPHVERTEX_H # include #endif namespace BALL { class TriangleEdge; class TrianglePoint; class TriangulatedSurface; class TriangulatedSphere; class TriangulatedSES; class TriangulatedSAS; class SESTriangulator; class SASTriangulator; /** Generic TriangleEdge Class. \ingroup Surface */ class BALL_EXPORT Triangle : public GraphTriangle< TrianglePoint,TriangleEdge,Triangle > { public: /** @name Class friends - class TriangleEdge - class TrianglePoint - class TriangulatedSurface - class TriangulatedSphere - class TriangulatedSES - class TriangulatedSAS - class SESTriangulator - class SASTriangulator */ friend class TriangleEdge; friend class TrianglePoint; friend class TriangulatedSurface; friend class TriangulatedSphere; friend class TriangulatedSES; friend class TriangulatedSAS; friend class SESTriangulator; friend class SASTriangulator; BALL_CREATE(Triangle) /** @name Constructors and Destructors */ //@{ /** Default constructor. This method creates a new Triangle object. */ Triangle() throw(); /** Copy constructor. Create a new Triangle object from another. @param triangle the Triangle object to be copied @param deep if deep = false, all pointers are set to NULL (default). Otherwise the new Triangle object is linked to the neighbours of the old Triangle object. */ Triangle(const Triangle& triangle, bool deep = false) throw(); /** Destructor. Destructs the Triangle object. */ virtual ~Triangle() throw(); //@} /** @name Assignments */ //@{ /** Assign from another Triangle. @param triangle the Triangle object to assign from @param deep if deep = false, all pointers are set to NULL (default). Otherwise the Triangle object is linked to the neighbours of the Triangle object to assign from */ void set(const Triangle& triangle, bool deep = false) throw(); /** Assign from another Triangle. The Triangle object is linked to the neighbours of the Triangle object to assign from @param triangle the Triangle object to assign from */ Triangle& operator = (const Triangle& triangle) throw(); //@} /** @name Accessors */ //@{ /** Set one of the three points of the Triangle. @param i the relative index of the point which should be set. If i is greater three, an exception is thrown. @param point a pointer to the new point */ void setPoint(Position i, TrianglePoint* point) throw(Exception::IndexOverflow); /** Return one of the three points of the Triangle. @param i the relative index of the point which should be given back. If i is greater three, an exception is thrown. @return TrianglePoint* a pointer to the asked point */ TrianglePoint* getPoint(Position i) const throw(Exception::IndexOverflow); /** Remove an edge from the Triangle. The edge is set to NULL. @param edge the edge to delete */ void remove(TriangleEdge* edge) throw(); //@} /** @name Predicates */ //@{ /** Equality operator. @return true */ virtual bool operator == (const Triangle&) const throw(); /** Inequality operator. @return false */ virtual bool operator != (const Triangle&) const throw(); /** Similarity operator. @return true */ virtual bool operator *= (const Triangle&) const throw(); //@} }; /** @name Storers */ //@{ /** Output- Operator */ BALL_EXPORT std::ostream& operator << (std::ostream& s, const Triangle& triangle); //@} } // namespace BALL #endif // BALL_STRUCTURE_TRIANGLE_H ugene-1.9.8/src/plugins_3rdparty/ball/src/include/BALL/STRUCTURE/SESFace.h0000644000175000017500000001465611651544325024254 0ustar ilyailya// -*- Mode: C++; tab-width: 2; -*- // vi: set ts=2: // // $Id: SESFace.h,v 1.28 2005-12-23 17:02:02 amoll Exp $ // #ifndef BALL_STRUCTURE_SESFACE_H #define BALL_STRUCTURE_SESFACE_H #ifndef BALL_STRUCTURE_GRAPHFACE_H # include #endif #ifndef BALL_STRUCTURE_RSEDGE_H # include #endif #ifndef BALL_STRUCTURE_RSFACE_H # include #endif #ifndef BALL_STRUCTURE_RSVERTEX_H # include #endif namespace BALL { class SESEdge; class SESVertex; class SolventExcludedSurface; class TriangulatedSES; class SESComputer; class SESSingularityCleaner; class SESTriangulator; /** Generic SESFace Class. \ingroup Surface */ class BALL_EXPORT SESFace : public GraphFace< SESVertex,SESEdge,SESFace > { public: /** @name Class friends - class SESEdge - class SESVertex - class SolventExcludedSurface - class SESComputer - class TSESSingularityCleaner - class TriangulatedSES - class SESTriangulator */ friend class SESEdge; friend class SESVertex; friend class SolventExcludedSurface; friend class SESComputer; friend class SESSingularityCleaner; friend class TriangulatedSES; friend class SESTriangulator; BALL_CREATE(SESFace) /** @name Enums */ //@{ /** type of SESFace: 0 spheric reentrant face 1 toric reentrant face 2 contact face 3 singular toric reentrant face */ enum Type { TYPE_SPHERIC = 0, TYPE_TORIC = 1, TYPE_CONTACT = 2, TYPE_TORIC_SINGULAR = 3 }; //@} /** @name Constructors and Destructors */ //@{ /** Default constructor. This method creates a new SESFace object. */ SESFace() throw(); /** Copy constructor. Create a new SESFace object from another. @param sesface the SESFace object to be copied @param deep if deep = false, all pointers are set to NULL (default). Otherwise the new SESFace object is linked to the neighbours of the old SESFace object. */ SESFace(const SESFace& sesface, bool deep = false) throw(); /** Detailled constructor. Create a new SESFace object @param type assigned the type @param rsvertex assigned to the rsvertex @param rsedge assigned to the rsedge @param rsface assigned to the rsface */ SESFace (Type type, RSVertex* rsvertex, RSEdge* rsedge, RSFace* rsface) throw(); /** Destructor. Destructs the SESFace object. */ virtual ~SESFace() throw(); //@} /** @name Assignments */ //@{ /** Assign from another SESFace. @param sesface the SESFace object to assign from @param deep if deep = false, all pointers are set to NULL (default). Otherwise the SESFace object is linked to the neighbours of the SESFace object to assign from. */ void set(const SESFace& sesface, bool deep = false) throw(); /** Assign from another SESFace. The SESFace object is linked to the neighbours of the SESFace object to assign from. @param sesface the SESFace object to assign from */ SESFace& operator = (const SESFace& sesface) throw(); /** Set the type of the SESFace. @param type the new type */ void setType(Type type) throw(); /** Get the type of the SESFace @return SESFace::Type the type of the SESFace */ Type getType() const throw(); /** Set the corresponding RSVertex of the SESFace. @param rsvertex a pointer to the new RSVertex */ void setRSVertex(RSVertex* rsvertex) throw(); /** Get the corresponding RSVertex of the SESFace. @return RSVertex* a pointer to the corresponding RSVertex */ RSVertex* getRSVertex() const throw(); /** Set the corresponding RSEdge of the SESFace. @param rsedge a pointer to the new RSFace */ void setRSEdge(RSEdge* rsedge) throw(); /** Get the corresponding RSEdge of the SESFace. @return RSEdge* a pointer to the corresponding RSEdge */ RSEdge* getRSEdge() const throw(); /** Set the corresponding RSFace of the SESFace. @param rsface a pointer to the new RSFace */ void setRSFace(RSFace* rsface) throw(); /** Get the corresponding RSFace of the SESFace. @return RSFace* a pointer to the corresponding RSFace */ RSFace* getRSFace() const throw(); //@} /** @name Accessors */ //@{ /** Normalize the SESFace. */ void normalize(bool singular) throw(); //@} /** @name Predicates */ //@{ /** Equality operator. @return bool true */ virtual bool operator == (const SESFace&) const throw(); /** Inequality operator. @return bool false */ virtual bool operator != (const SESFace&) const throw(); /** Similarity operator. @return bool true */ virtual bool operator *= (const SESFace&) const throw(); /** Test whether two faces are neighboured. Two faces are neighboured if they have a common edge. @param face the face to be tested @return bool true if the faces are neighboured, false otherwise */ bool isNeighbouredTo(SESFace* face) const throw(); /** Test whether a toric face is free ore not. @return bool true if the face is toric and free, false otherwise */ bool isFree() const throw(); /** Test whether a face has singular edges. @return bool true if the face has singular edges, false otherwise */ bool hasSingularEdges() const throw(); //@} private: void normalizeNonSingularToricFace_() throw(); void normalizeSingularToricFace_() throw(); void findTriangle_ (bool first, SESEdge*& edge0, SESEdge*& edge1, SESEdge*& edge2, SESVertex*& vertex0, SESVertex*& vertex1, SESVertex*& vertex2) throw(); protected: /** @name Attributes */ //@{ /*_ The type of the face. */ Type type_; /*_ A pointer to the corresponding RSVertex (if type_ is TYPE_CONTACT). */ RSVertex* rsvertex_; /*_ A pointer to the corresponding RSEdge (if type_ is TYPE_TORIC or TYPE_TORIC_SINGULAR). */ RSEdge* rsedge_; /*_ A pointer to the corresponding RSFace (if type_ is TYPE_SPHERIC). */ RSFace* rsface_; //@} }; /** @name Storers */ //@{ /** Output- Operator */ BALL_EXPORT std::ostream& operator << (std::ostream& s, const SESFace& sesface); //@} } // namespace BALL #endif // BALL_STRUCTURE_SESFACE_H ugene-1.9.8/src/plugins_3rdparty/ball/src/include/BALL/STRUCTURE/graphVertex.h0000644000175000017500000003133211651544325025330 0ustar ilyailya// -*- Mode: C++; tab-width: 2; -*- // vi: set ts=2: // // $Id: graphVertex.h,v 1.15.18.1 2007-03-25 21:25:27 oliver Exp $ // #ifndef BALL_STRUCTURE_GRAPHVERTEX_H #define BALL_STRUCTURE_GRAPHVERTEX_H #ifndef BALL_COMMON_H # include #endif #ifndef BALL_DATATYPE_HASHSET_H # include #endif namespace BALL { template class GraphEdge; template class GraphFace; template class GraphTriangle; /** Generic GraphVertex Class. \ingroup Surface */ template class GraphVertex { public: /** @name Class friends - class GraphEdge; - class GraphFace; - class GraphTriangle; */ friend class GraphEdge; friend class GraphFace; friend class GraphTriangle; BALL_CREATE(GraphVertex) /** @name Type definitions */ //@{ typedef typename HashSet::Iterator EdgeIterator; typedef typename HashSet::ConstIterator ConstEdgeIterator; typedef typename HashSet::Iterator FaceIterator; typedef typename HashSet::ConstIterator ConstFaceIterator; //@} /** @name Constructors and Destructors */ //@{ /** Default constructor. This method creates a new GraphVertex object. */ GraphVertex() throw(); /** Copy constructor. Create a new GraphVertex object from another. @param vertex the GraphVertex object to be copied @param deep if deep = false, all pointers are set to NULL (default). Otherwise the new GraphVertex object is linked to the neighbours of the old GraphVertex object. */ GraphVertex(const GraphVertex& vertex, bool deep = false) throw(); /** Destructor. Destructs the GraphVertex object. */ virtual ~GraphVertex() throw(); //@} /** @name Assignment */ //@{ /** Assign from another GraphVertex. @param vertex the GraphVertex object to assign from @param deep if deep = false, all pointers are set to NULL (default). Otherwise the GraphVertex object is linked to the neighbours of the GraphVertex object to assign from. */ void set(const GraphVertex& vertex, bool deep = false) throw(); /** Assign from another GraphVertex. The GraphVertex object is linked to the neighbours of the GraphVertex object to assign from. @param vertex the GraphVertex object to assign from */ GraphVertex& operator = (const GraphVertex& vertex) throw(); //@} /** @name Accessors */ //@{ /** Insert a new edge into the HashSet of edges the GraphVertex belongs to. @param edge a pointer to the new edge */ void insert(Edge* edge) throw(); /** Insert a new face into the HashSet of faces the GraphVertex belongs to. @param face a pointer to the new face */ void insert(Face* face) throw(); /** Remove an edge from the HashSet of edges the GraphVertex belongs to. @param edge a pointer to the edge to remove */ void remove(Edge* edge) throw(); /** Remove a face from the HashSet of faces the GraphVertex belongs to. @param face a pointer to the face to remove */ void remove(Face* face) throw(); /** Return the number of edges the GraphVertex belongs to. @return Position the number of edges the GraphVertex belongs to */ Position numberOfEdges() const throw(); /** Return the number of faces the GraphVertex belongs to. @return Position the number of faces the GraphVertex belongs to */ Position numberOfFaces() const throw(); /** Set the index of the vertex. @param index the new index */ void setIndex(Index index) throw(); /** Return the index of the vertex. @return Index the index of the vertex */ Index getIndex() const throw(); /** Join two GraphVertices if they are similar. All edges and faces of the given Vertex are inserted. @param vertex the Vertex to join with @return bool true if the vertices can be joined, false otherwise */ bool join(const Vertex& vertex) throw(); /** Subsitute the GraphVertex by a similar one. The GraphVertex is substituted in all his Edges and Faces. @param vertex a pointer to the vertex to substitute @return bool true if the vertex can be substituted, false otherwise */ bool substitute(Vertex* vertex) throw(); //@} /** @name Predicates */ //@{ /** Equality operator. @return bool true */ virtual bool operator == (const Vertex&) const throw(); /** Inequality operator. @return bool false */ virtual bool operator != (const Vertex&) const throw(); /** Similarity operator. @return bool true */ virtual bool operator *= (const Vertex&) const throw(); /** Test whether the vertex is meber of a given face. @param face a pointer to the the face to be tested @return Face* a pointer to the face if it exists, otherwise NULL */ Face* has(Face* face) const throw(); /** Test whether the vertex is meber of a given edge. @param edge a pointer to the edge to be tested @return Edge* a pointer to the edge if it exists, otherwise NULL */ Edge* has(Edge* edge) const throw(); /** Test whether the vertex has edges. */ bool hasEdges() const throw(); /** Test whether the vertex has faces. */ bool hasFaces() const throw(); //@} /** @name External Iterators */ //@{ EdgeIterator beginEdge() throw(); ConstEdgeIterator beginEdge() const throw(); EdgeIterator endEdge() throw(); ConstEdgeIterator endEdge() const throw(); FaceIterator beginFace() throw(); ConstFaceIterator beginFace() const throw(); FaceIterator endFace() throw(); ConstFaceIterator endFace() const throw(); //@} protected: /*_ @name Attributes */ //@{ /*_ The RSEdges the RSVetex belongs to */ HashSet edges_; /*_ The RSFaces the RSVetex belongs to */ HashSet faces_; /*_ The index of the GraphVertex */ Index index_; //@} }; template GraphVertex::GraphVertex() throw() : edges_(), faces_(), index_(-1) { } template GraphVertex::GraphVertex (const GraphVertex& vertex, bool deep) throw() : edges_(), faces_(), index_(vertex.index_) { if (deep) { edges_ = vertex.edges_; faces_ = vertex.faces_; } } template GraphVertex::~GraphVertex() throw() { } template void GraphVertex::set (const GraphVertex& vertex, bool deep) throw() { if (this != &vertex) { if (deep) { edges_ = vertex.edges_; faces_ = vertex.faces_; } index_ = vertex.index_; } } template GraphVertex& GraphVertex::operator = (const GraphVertex& vertex) throw() { if (this != &vertex) { edges_ = vertex.edges_; faces_ = vertex.faces_; index_ = vertex.index_; } return *this; } template void GraphVertex::insert(Edge* edge) throw() { edges_.insert(edge); } template void GraphVertex::insert(Face* face) throw() { faces_.insert(face); } template void GraphVertex::remove(Edge* edge) throw() { edges_.erase(edge); } template void GraphVertex::remove(Face* face) throw() { faces_.erase(face); } template Position GraphVertex::numberOfEdges() const throw() { return edges_.size(); } template Position GraphVertex::numberOfFaces() const throw() { return faces_.size(); } template void GraphVertex::setIndex(Index index) throw() { index_ = index; } template Index GraphVertex::getIndex() const throw() { return index_; } template bool GraphVertex::substitute(Vertex* vertex) throw() { if (*this *= *vertex) { typename HashSet::Iterator e; for (e = edges_.begin(); e != edges_.end(); e++) { (*e)->substitute((Vertex*)this,vertex); } typename HashSet::Iterator f; for (f = faces_.begin(); f != faces_.end(); f++) { (*f)->substitute((Vertex*)this,vertex); } return true; } return false; } template bool GraphVertex::join(const Vertex& vertex) throw() { if (*this *= vertex) { typename HashSet::ConstIterator e; for (e = vertex.edges_.begin(); e != vertex.edges_.end(); e++) { edges_.insert(*e); } typename HashSet::ConstIterator f; for (f = vertex.faces_.begin(); f != vertex.faces_.end(); f++) { faces_.insert(*f); } return true; } else { return false; } } template Face* GraphVertex::has(Face* face) const throw() { typename HashSet::ConstIterator f; for (f = faces_.begin(); f != faces_.end(); f++) { if (*(*f) == *face) { return *f; } } return NULL; } template Edge* GraphVertex::has(Edge* edge) const throw() { typename HashSet::ConstIterator e; for (e = edges_.begin(); e != edges_.end(); e++) { if (*(*e) == *edge) { return *e; } } return NULL; } template bool GraphVertex::hasEdges() const throw() { return !edges_.isEmpty(); } template bool GraphVertex::hasFaces() const throw() { return !faces_.isEmpty(); } template typename GraphVertex::EdgeIterator GraphVertex::beginEdge() throw() { return edges_.begin(); } template typename GraphVertex::ConstEdgeIterator GraphVertex::beginEdge() const throw() { return edges_.begin(); } template typename GraphVertex::EdgeIterator GraphVertex::endEdge() throw() { return edges_.end(); } template typename GraphVertex::ConstEdgeIterator GraphVertex::endEdge() const throw() { return edges_.end(); } template typename GraphVertex::FaceIterator GraphVertex::beginFace() throw() { return faces_.begin(); } template typename GraphVertex::ConstFaceIterator GraphVertex::beginFace() const throw() { return faces_.begin(); } template typename GraphVertex::FaceIterator GraphVertex::endFace() throw() { return faces_.end(); } template typename GraphVertex::ConstFaceIterator GraphVertex::endFace() const throw() { return faces_.end(); } template bool GraphVertex::operator == (const Vertex&) const throw() { return true; } template bool GraphVertex::operator != (const Vertex&) const throw() { return false; } template bool GraphVertex::operator *= (const Vertex&) const throw() { return true; } } // namespace BALL #endif // BALL_STRUCTURE_GRAPHVERTEX_H ugene-1.9.8/src/plugins_3rdparty/ball/src/include/BALL/STRUCTURE/SASVertex.h0000644000175000017500000000771311651544325024663 0ustar ilyailya// -*- Mode: C++; tab-width: 2; -*- // vi: set ts=2: // // $Id: SASVertex.h,v 1.8 2005-12-23 17:02:02 amoll Exp $ // #ifndef BALL_STRUCTURE_SASVERTEX_H #define BALL_STRUCTURE_SASVERTEX_H #ifndef BALL_STRUCTURE_GRAPHVERTEX_H # include #endif #ifndef BALL_MATHS_VECTOR3_H # include #endif namespace BALL { class SASEdge; class SASFace; class SolventAccessibleSurface; class TriangulatedSAS; class SASTriangulator; /** Generic SASVertex Class. \ingroup Surface */ class BALL_EXPORT SASVertex : public GraphVertex< SASVertex,SASEdge,SASFace > { public: /** @name Class friends - class SASEdge - class SASFace - class SolventAccessibleSurface - class TriangulatedSAS - class SASTriangulator */ friend class SASEdge; friend class SASFace; friend class SolventAccessibleSurface; friend class TriangulatedSAS; friend class SASTriangulator; BALL_CREATE(SASVertex) /** @name Constructors and Destructors */ //@{ /** Default constructor. This method creates a new SASVertex object. */ SASVertex() throw(); /** Copy constructor. Create a new SASVertex object from another. @param sasvertex the SASVertex object to be copied @param deep if deep = false, all pointers are set to NULL (default). Otherwise the new SASVertex object is linked to the neighbours of the old SASVertex object. */ SASVertex(const SASVertex& sasvertex, bool deep = false) throw(); /** Detailled constructor. Create a new SASVertex object from some nice objects. @param point assigned to the point representet by the vertex @param index assigned to the index of the vertex */ SASVertex(const TVector3& point, Index index) throw(); /** Destructor. Destructs the RSVertex object. */ virtual ~SASVertex() throw(); //@} /** @name Assignment */ //@{ /** Assign from another SASVertex. @param sasvertex the SASVertex object to assign from @param deep if deep = false, all pointers are set to NULL (default). Otherwise the new SASVertex object is linked to the neighbours of the SASVertex object to assign from. */ void set(const SASVertex& sasvertex, bool deep = false) throw(); /** Assign from another SASVertex. The new SASVertex object is linked to the neighbours of the SASVertex object to assign from. @param sasvertex the SASVertex object to assign from */ SASVertex& operator = (const SASVertex& sasvertex) throw(); /** Assign to a TVector3 and an Index. @param point assigned to the point represented by the vertex @param index assigned to the index of the vertex */ void set(const TVector3 point, Index index) throw(); /** Set the point represented by the SASVertex. @param point the new point */ void setPoint(const TVector3& point) throw(); /** Return the point represented by the SASVertex. @return TVector3 the point represented by the vertex */ TVector3 getPoint() const throw(); //@} /** @name Predicates */ //@{ /** Equality operator. @return bool true */ virtual bool operator == (const SASVertex&) const throw(); /** Inequality operator. @return bool false */ virtual bool operator != (const SASVertex&) const throw(); /** Similarity operator. @return bool true if the points the SASVertices lie on are equal, false otherwise */ virtual bool operator *= (const SASVertex&) const throw(); //@} protected: /*_ @name Attributes */ //@{ /*_ The coordinates of the vertex. */ TVector3 point_; //@} }; /** @name Storers */ //@{ /** Output- Operator */ BALL_EXPORT std::ostream& operator << (std::ostream& s, const SASVertex& sasvertex); //@} } // namespace BALL #endif // BALL_STRUCTURE_SASVERTEX_H ugene-1.9.8/src/plugins_3rdparty/ball/src/include/BALL/STRUCTURE/reducedSurface.h0000644000175000017500000005255711651544326025772 0ustar ilyailya// -*- Mode: C++; tab-width: 2; -*- // vi: set ts=2: // // $Id: reducedSurface.h,v 1.47.18.1 2007-03-25 21:25:29 oliver Exp $ // #ifndef BALL_STRUCTURE_REDUCEDSURFACE_H #define BALL_STRUCTURE_REDUCEDSURFACE_H #ifndef BALL_MATHC_COMMON_H # include #endif #ifndef BALL_MATHS_SIMPLEBOX3_H # include #endif #ifndef BALL_MATHS_CIRCLE3_H # include #endif #ifndef BALL_MATHS_SPHERE_H # include #endif #ifndef BALL_MATHS_VECTOR3_H # include #endif #ifndef BALL_DATATYPE_HASHMAP_H # include #endif #ifndef BALL_DATATYPE_HASHSET_H # include #endif #ifndef BALL_COMMON_EXCEPTION_H # include #endif #ifndef BALL_STRUCTURE_RSEDGE_H # include #endif #ifndef BALL_STRUCTURE_RSFACE_H # include #endif #ifndef BALL_STRUCTURE_RSVERTEX_H # include #endif #include #include namespace BALL { class RSComputer; class SolventExcludedSurface; class SESComputer; class SESSingularityCleaner; class TriangulatedSES; class SolventAccessibleSurface; class TriangulatedSAS; class SESTriangulator; /** Generic ReducedSurface Class. \ingroup Surface */ class BALL_EXPORT ReducedSurface { public: /** @name Class friends - class RSComputer - class SolventExcludedSurface - class TriangulatedSES - class SESComputer - class SESSingularityCleaner - class SolventAccessibleSurface - class TriangulatedSAS - class SESTriangulator */ friend class RSComputer; friend class SolventExcludedSurface; friend class SESComputer; friend class SESSingularityCleaner; friend class SolventAccessibleSurface; friend class TriangulatedSES; friend class TriangulatedSAS; friend class SESTriangulator; BALL_CREATE(ReducedSurface) /** @name Constructors and Destructors */ //@{ /** Default constructor. All components are initialized to (T)0 or NULL, respectivly. */ ReducedSurface() throw(); /** Copy constructor. @param reduced_surface the ReducedSurface object to be copied @param bool ignored - just for interface consistency */ ReducedSurface(const ReducedSurface& reduced_surface, bool = true) throw(); /** Detailed constructor. Create a new ReducedSurface object from a list of spheres. */ ReducedSurface (const std::vector< TSphere3 >& spheres, const double& probe_radius) throw(); /** Destructor. */ virtual ~ReducedSurface() throw(); //@} /** @name Assignment */ //@{ /** Assign from another ReducedSurface. @param reduced_surface the ReducedSurface object to assign from */ void operator=(const ReducedSurface& reduced_surface) throw(); /** Assign from another ReducedSurface. @param reduced_surface the ReducedSurface object to assign from */ void set(const ReducedSurface& reduced_surface) throw(); /** Delete all vertices, edges and faces. */ void clear() throw(); /** Remove all NULL-pointers */ void clean() throw(); //@} /** @name Accessors */ //@{ /** Return the number of atoms. @return Size the number of atoms */ Size numberOfAtoms() const throw(); /** Return the number of rsvertices. @return Size the number of rsvertices */ Size numberOfVertices() const throw(); /** Return the number of rsedges. @return Size the number of rsedges */ Size numberOfEdges() const throw(); /** Return the number of rsfaces. @return Size the number of rsfaces */ Size numberOfFaces() const throw(); /** Return the probe radius. @return double the radius of the used probe sphere */ double getProbeRadius() const throw(); /** Return the i'th sphere. @param i the index of the sphere that should be given back @return TSphere3, the i'th sphere */ TSphere3 getSphere(Position i) const throw(Exception::IndexOverflow); /** Return the i'th rsvertex. @param i the index of the rsvertex that should be given back @return RSVertex, the i'th rsvertex */ RSVertex* getVertex(Position i) const throw(Exception::IndexOverflow); /** Return the i'th rsedge. @param i the index of the rsedge that should be given back @return RSEdge, the i'th rsedge */ RSEdge* getEdge(Position i) const throw(Exception::IndexOverflow); /** Return the i'th rsface. @param i the index of the rsface that should be given back @return RSFace, the i'th rsface */ RSFace* getFace(Position i) const throw(Exception::IndexOverflow); /** Insert a new RSVertex. @param rsvertex a pointer to the RSVertex to insert */ void insert(RSVertex* rsvertex) throw(); /** Insert a new RSEdge. @param rsedge a pointer to the RSEdge to insert */ void insert(RSEdge* rsedge) throw(); /** Insert a new RSFace. @param rsface a pointer to the RSFace to insert */ void insert(RSFace* rsface) throw(); /** Return the maximal radius of te atoms of te molecule @return double the maximal radius */ double getMaximalRadius() const throw(); /** Return the bounding box of the centers of te atoms of te molecule @return TSimpleBox3 the bounding box */ TSimpleBox3 getBoundingBox() const throw(); /** Delete a pair of similar faces. @param face1 a pointer to the first face @param face2 a pointer to the second face */ void deleteSimilarFaces(RSFace* face1, RSFace* face2) throw(); /** Get the angle between two RSFaces. @param face1 a pointer to the first face @param face2 a pointer to the second face @param vertex1 a pointer to the first vertex to roll over @param vertex2 a pointer to the second vertex to roll over @param angle the computed angle @param check you kan ask to check whether the angle can be computed */ bool getAngle (RSFace* face1, RSFace* face2, RSVertex* vertex1, RSVertex* vertex2, TAngle& angle, bool check = false) const throw(); /** Compute the reduced surface. */ void compute() throw(Exception::GeneralException, Exception::DivisionByZero, Exception::IndexOverflow); //@} private: /*_ Test whether a ReducedSurface object can be copied. */ bool canBeCopied(const ReducedSurface& reduced_surface) throw(); /*_ Copy a ReducedSurface object. */ void copy(const ReducedSurface& reduced_surface) throw(); /*_ */ void correctEdges (RSFace* face1, RSFace* face2, RSEdge* edge1, RSEdge* edge2) throw(); /*_ */ void joinVertices (RSFace* face1, RSFace* face2, RSVertex* vertex1, RSVertex* vertex2) throw(); /*_ */ void findSimilarVertices (RSFace* face1, RSFace* face2, std::vector& rsvertex1, std::vector& rsvertex2) throw(); /*_ */ void findSimilarEdges (RSFace* face1, RSFace* face2, std::vector& rsedge1, std::vector& rsedge2) throw(); protected: /*_ the number of atoms of the reduced surface */ Size number_of_atoms_; /*_ the atoms of the molecule */ std::vector< TSphere3 > atom_; /*_ probe radius */ double probe_radius_; /*_ the number of vertices of the reduced surface */ Size number_of_vertices_; /*_ the vertices of the reduced surface */ std::vector< RSVertex* > vertices_; /*_ the number of edges of the reduced surface */ Size number_of_edges_; /*_ the edges of the reduced surface */ std::vector< RSEdge* > edges_; /*_ the number of faces of the reduced surface */ Size number_of_faces_; /*_ the faces of the reduced surface */ std::vector< RSFace* > faces_; /*_ maximal radius of all atoms */ double r_max_; /*_ bounding SimpleBox of the atom centers of the molecule */ TSimpleBox3 bounding_box_; }; /** @name Storers */ //@{ /** Output- Operator. Prints out a ReducedSurface */ BALL_EXPORT std::ostream& operator << (std::ostream& s, const ReducedSurface& rs); //@} /** Generic RSComputer Class. \ingroup Surface */ class BALL_EXPORT RSComputer { public: BALL_CREATE(RSComputer) /** @name Enums */ //@{ /** status of the probe positions of three atoms: 0 ok 1 not ok 2 not tested */ enum ProbeStatus { STATUS_OK = 0, STATUS_NOT_OK = 1, STATUS_NOT_TESTED = 2 }; /** status of an atom 0 on surface 1 inside 2 outside */ enum AtomStatus { STATUS_ON_SURFACE = 0, STATUS_INSIDE = 1, STATUS_UNKNOWN = 2 }; //@} struct ProbePosition { ProbeStatus status[2]; TVector3 point[2]; }; /** @name Constructors and Destructors */ //@{ /** Default constructor. All components are initialized to (T)0 or NULL, respectivly. */ RSComputer() throw(); /** Detiled constructor. */ RSComputer(ReducedSurface* rs) throw(); /** Destructor. */ virtual ~RSComputer() throw(); //@} /** @name Accessors */ //@{ /** Compute the reduced surface */ void run() throw(Exception::GeneralException, Exception::DivisionByZero, Exception::IndexOverflow); //@} private: /*_ @name Computing reduced surface */ //@{ /*_ */ void preProcessing() throw(); /*_ Compute a RSComponent. */ void getRSComponent() throw(Exception::GeneralException, Exception::DivisionByZero, Exception::IndexOverflow); /*_ Treat all edges of a face. @param face the RSFace to be treated */ bool treatFace(RSFace* face) throw(Exception::GeneralException, Exception::DivisionByZero, Exception::IndexOverflow); /*_ Roll over an edge that belongs to only one face and find the other one. @param edge the RSEdge to be treated */ bool treatEdge(RSEdge* edge) throw(Exception::GeneralException, Exception::DivisionByZero, Exception::IndexOverflow); /*_ Treat an ambiguous situation. All vertices on an ambiguous atom are deleted with all its edges and faces. The radius of the atom is decreased by 10 EPSILON. @param atom the index of the atom */ void correct(Index atom) throw(); /*_ Check all new created vertices for extensions */ void extendComponent() throw(Exception::GeneralException, Exception::DivisionByZero, Exception::IndexOverflow); /*_ Find a third atom rolling over two vertices starting on a face. From all atoms which can be touced by the probe sphere when it touches the given two vertices this one is chosen, for which is the rotation angle the smalest. If the rotation angle equals zero, the probe sphere can touch four atoms an an exception is thrown. If no atom can be found an exception is thrown. @param vertex1 the first vertex @param vertex2 the second vertex @param face the starting face @param probe the new probe sphere @param phi the rotation angle @return Index index of the found atom */ Index thirdAtom (RSVertex* vertex1, RSVertex* vertex2, RSFace* face, TSphere3& probe, TAngle& phi) throw(Exception::GeneralException, Exception::DivisionByZero, Exception::IndexOverflow); //@} /*_ @name Finding a start position */ //@{ /*_ Find a start position @param vertex a pointer to the found vertex, if only a vertex can be found @param edge a pointer to the found edge, if only an edge can be found @param face a pointer to the found face, if a face can be found @return Position 0, if no start position is found, 1, if a single vertex is found, 2, if an edge is found, 3, if a face is found */ Position getStartPosition() throw(Exception::DivisionByZero); //@} /*_ @name Finding a first face */ //@{ /*_ Try to find a starting face @return RSFace* a pointer to the found face, if a face can be found, NULL otherwise */ RSFace* findFirstFace() throw(Exception::DivisionByZero); /*_ Try to find a starting face in a given direction @param direction search in x-direction, if direction is 0, search in y-direction, if direction is 1, search in z-direction, if direction is 2 @param extrem search in min direction, if extrem is 0, search in max direction, if extrem is 1 @return RSFace* a pointer to the found face, if a face can be found, NULL otherwise */ RSFace* findFace(Position direction, Position extrem) throw(Exception::DivisionByZero); //@} /*_ @name Finding a first edge */ //@{ /*_ Try to find a starting edge @return RSEdge* a pointer to the found edge, if a face can be found, NULL otherwise */ RSEdge* findFirstEdge() throw(); /*_ Try to find a starting edge in a given direction @param direction search in x-direction, if direction is 0, search in y-direction, if direction is 1, search in z-direction, if direction is 2 @param extrem search in min direction, if extrem is 0, search in max direction, if extrem is 1 @return RSEdge* a pointer to the found edge, if a face can be found, NULL otherwise */ RSEdge* findEdge(Position direction, Position extrem) throw(); //@} /*_ @name Finding a first vertex */ //@{ /*_ Try to find a single atom @return RSVertex* a pointer to the found vertex, if a vertex can be found, NULL otherwise */ RSVertex* findFirstVertex() throw(); /*_ Find a single atom in a given direction @param direction search in x-direction, if direction is 0, search in y-direction, if direction is 1, search in z-direction, if direction is 2 @param extrem search in min direction, if extrem is 0, search in max direction, if extrem is 1 @return Index the index of the found atom */ Index findFirstAtom(Position direction, Position extrem) throw(); /*_ Find a second atom close enougth to the first atom in a given direction @param atom1 the index of the first atom @param direction search in x-direction, if direction is 0, search in y-direction, if direction is 1, search in z-direction, if direction is 2 @param extrem search in min direction, if extrem is 0, search in max direction, if extrem is 1 @return Index the index of the found atom */ Index findSecondAtom(Index atom, Position direction, Position extrem) throw(); /*_ Find a second atom close enougth to the first two atoms @param atom1 the index of the first atom @param atom2 the index of the second atom @param atom_list a HashSet of the indices of all candidate atoms @return ::std::list< ::std::pair< Index,TSphere3 > > a list of all candidates with their probe spheres */ void findThirdAtom (Index atom1, Index atom2, const std::list& third, std::list< std::pair< Index,TSphere3 > >& atoms) throw(); //@} /*_ @name Some utilities */ //@{ /*_ Find all atoms close enougth to two given atoms. The indices of all atoms which can be touched by the probe sphere when it touches the given atoms are computed. @param atom1 the index of the first given atom @param atom2 the index of the second given atom @param output_list list of all atoms close enougth to the given atoms */ void neighboursOfTwoAtoms(Index atom1, Index atom2) throw(); /*_ Find all atoms close enougth to three given atoms. The indices of all atoms which can be touched by the probe sphere when it touches the given atoms are computed. @param atom1 the index of the first given atom @param atom2 the index of the second given atom @param atom3 the index of the third given atom @param output_list list of all atoms close enougth to the given atoms */ void neighboursOfThreeAtoms (Index atom1, Index atom2, Index atom3, std::list& output_list) throw(); /*_ Get the extrem coordinate of a circle in a given direction @param circle the circle @param direction search in x-direction, if direction is 0, search in y-direction, if direction is 1, search in z-direction, if direction is 2 @param extrem search in min direction, if extrem is 0, search in max direction, if extrem is 1 @return double the extrem coordinate */ double getCircleExtremum (const TCircle3& circle, Position direction, Position extrem) throw(); //@} /*_ @name Creating / updating edges / faces */ //@{ /*_ Create a free edge from two vertices if it is a free edge @param vertex1 a pointer to the first vertex @param vertex2 a pointer to the second vertex @return RSEdge* a pointer to the created free edge, if there is one, NULL otherwise */ RSEdge* createFreeEdge(RSVertex* vertex1, RSVertex* vertex2) throw(); /*_ Get the circle described by the center of the probe sphere and the two contact circles with the atoms when the probe sphere rolls over two atoms @param atom1 the index of the first atom @param atom2 the index of the second atom @param circle1 the circle described by the center of the probe sphere @param circle2 the contact circle with atom1 @param circle3 the contact circle with atom2 @return bool true, if the probe sphere can touch both atoms, false, otherwise */ bool getCircles (Index atom1, Index atom2, TCircle3& circle1, TCircle3& circle2, TCircle3& circle3) throw(); /*_ Get the normal vector of the face described by three atoms and a probe @param atom1 the index of the first atom @param atom2 the index of the second atom @param atom3 the index of the third atom @param probe the probe sphere lying on atom1, atom2, atom3 @return TVector3 the normal vector */ TVector3 getFaceNormal (const TSphere3& atom1, const TSphere3& atom2, const TSphere3& atom3, const TSphere3& probe) throw(); /*_ Update a face and it's edges @param v1 the first vertex of the face @param v2 the second vertex of the face @param v3 the third vertex of the face @param e1 the first edge @param e2 the second edge @param e3 the third edge @param f the face @param probe the probe sphere of the face */ void updateFaceAndEdges (RSVertex* v1, RSVertex* v2, RSVertex* v3, RSEdge* e1, RSEdge* e2, RSEdge* e3, RSFace* f, const TSphere3& probe) throw(); /*_ Test, weather a face exists or not @param face a pointer to the face to be tested @return RSFace* a pointer to the face, if it exists, otherwise NULL */ RSFace* faceExists (RSFace* face, const std::list< RSVertex* >& vertices) throw(); //@} /*_ @name Finding a probe sphere */ //@{ /*_ Get the centers of the probe sphere when it lies on three atoms @param a1 the first atom @param a2 the second atom @param a3 the third atom @param c1 the first center @param c2 the second center @return bool true, if the probe sphere can touch the three atoms, false, otherwise */ bool centerOfProbe (Index a1, Index a2, Index a3, TVector3& c1, TVector3& c2) throw(); /*_ Check,weather a probe sphere is inside an atom @param probe the probe sphere to be tested @return bool true, if the probe sphere is not intersecting any atom false, otherwise */ bool checkProbe (const TSphere3& probe, Index atom1, Index atom2, Index atom3) throw(); /*_ */ void correctProbePosition(Position atom) throw(); /*_ */ void sort (Index u1, Index u2, Index u3, Index& s1, Index& s2, Index& s3) throw(); /*_ */ void correctProbePosition(Position a1, Position a2, Position a3) throw(); /*_ */ void insert(RSVertex* vertex) throw(); /*_ */ void insert(RSEdge* edge) throw(); /*_ */ void insert(RSFace* face) throw(); //@} protected: /*_ a pointer to the reduced surface to compute */ ReducedSurface* rs_; /*_ for each atom a list of its neighbours */ std::vector< std::list > neighbours_; /*_ for each atom a status */ std::vector< AtomStatus > atom_status_; /*_ for each pair of atoms a list of its neighbours */ HashMap< Position, HashMap< Position, std::list > > neighbours_of_two_; /*_ for each triple of atoms its probe positions */ HashMap< Position, HashMap< Position, HashMap< Position, ProbePosition* > > > probe_positions_; /*_ all new created vertices which are not yet checked for extensions */ HashSet new_vertices_; /*_ all new created faces which are not completely treated yet */ HashSet new_faces_; /*_ for each atom a list of the rsvertices of the atom */ std::vector< std::list > vertices_; }; } // namespace BALL #endif // BALL_STRUCTURE_REDUCEDSURFACE_H ugene-1.9.8/src/plugins_3rdparty/ball/src/include/BALL/STRUCTURE/trianglePoint.h0000644000175000017500000001037711651544326025657 0ustar ilyailya// -*- Mode: C++; tab-width: 2; -*- // vi: set ts=2: // // $Id: trianglePoint.h,v 1.12.18.1 2007-03-25 21:25:33 oliver Exp $ // #ifndef BALL_STRUCTURE_TRIANGLEPOINT_H #define BALL_STRUCTURE_TRIANGLEPOINT_H #ifndef BALL_MATHS_VECTOR3_H # include #endif #ifndef BALL_STRUCTURE_GRAPHEDGE_H # include #endif #ifndef BALL_STRUCTURE_GRAPHFACE_H # include #endif #ifndef BALL_STRUCTURE_GRAPHVERTEX_H # include #endif namespace BALL { class TriangleEdge; class Triangle; class TriangulatedSurface; class TriangulatedSphere; class TriangulatedSES; class SESTriangulator; class TriangulatedSAS; class SASTriangulator; /** Generic TriangleEdge Class. \ingroup Surface */ class BALL_EXPORT TrianglePoint : public GraphVertex< TrianglePoint,TriangleEdge,Triangle > { public: /** @name Class friends - class Triangle - class TriangleEdge - class TriangulatedSurface - class TriangulatedSphere - class TriangulatedSES - class SESTriangulator - class TriangulatedSAS - class SASTriangulator */ friend class Triangle; friend class TriangleEdge; friend class TriangulatedSurface; friend class TriangulatedSphere; friend class TriangulatedSES; friend class SESTriangulator; friend class TriangulatedSAS; friend class SASTriangulator; BALL_CREATE(TrianglePoint) /** @name Constructors and Destructors */ //@{ /** Default constructor. This method creates a new TrianglePoint object. */ TrianglePoint() throw(); /** Copy constructor. Create a new TrianglePoint object from another. @param point the TrianglePoint object to be copied @param deep if deep = false, all pointers are set to NULL (default). Otherwise the new TrianglePoint object is linked to the neighbours of the old TrianglePoint object. */ TrianglePoint(const TrianglePoint& point, bool deep = false) throw(); /** Destructor. Destructs the TrianglePoint object. */ virtual ~TrianglePoint() throw(); //@} /** @name Assignments */ //@{ /** Assign from another TrianglePoint. @param point the TrianglePoint object to assign from @param deep if deep = false, all pointers are set to NULL (default). Otherwise the new TrianglePoint object is linked to the neighbours of the TrianglePoint object to assign from. */ void set(const TrianglePoint& point, bool deep = false) throw(); /** Assign from another TrianglePoint. The new TrianglePoint object is linked to the neighbours of the TrianglePoint object to assign from. @param point the TrianglePoint object to assign from */ TrianglePoint& operator = (const TrianglePoint& point) throw(); //@} /** @name Accessors */ //@{ /** Get the point */ TVector3 getPoint() const throw(); /** Set the point */ void setPoint(const TVector3& point) throw(); /** Get the normal of the TrianglePoint */ TVector3 getNormal() const throw(); /** Set the normal of the TrianglePoint */ void setNormal(const TVector3& normal) throw(Exception::DivisionByZero); //@} /** @name Predicates */ //@{ /** Equality operator @return bool true if the TrianglePoints lie on the same point, false otherwise. */ virtual bool operator == (const TrianglePoint& point) const throw(); /** Inequality operator @return bool false if the TrianglePoints lie on the same point, true otherwise. */ virtual bool operator != (const TrianglePoint& point) const throw(); /** Similarity operator @return bool true if the TrianglePoints lie on the same point, false otherwise. */ virtual bool operator *= (const TrianglePoint& point) const throw(); //@} protected: /*_ The point itselfe */ TVector3 point_; /*_ The normal vector of the point */ TVector3 normal_; }; /** @name Storers */ //@{ /** Output- Operator */ BALL_EXPORT std::ostream& operator << (std::ostream& s, const TrianglePoint& point); //@} } // namespace BALL #endif // BALL_STRUCTURE_TRIANGLEPOINT_H ugene-1.9.8/src/plugins_3rdparty/ball/src/include/BALL/STRUCTURE/RSFace.h0000644000175000017500000001657111651544325024144 0ustar ilyailya// -*- Mode: C++; tab-width: 2; -*- // vi: set ts=2: // // $Id: RSFace.h,v 1.33 2005-12-23 17:02:01 amoll Exp $ // #ifndef BALL_STRUCTURE_RSFACE_H #define BALL_STRUCTURE_RSFACE_H #ifndef BALL_STRUCTURE_GRAPHFACE_H # include #endif #ifndef BALL_MATHS_VECTOR3_H # include #endif #ifndef BALL_DATATYPE_HASHSET_H # include #endif namespace BALL { class RSVertex; class RSEdge; class ReducedSurface; class RSComputer; class SolventExcludedSurface; class SESComputer; class SESSingularityCleaner; class SESEdge; class SESFace; class SESVertex; class TriangulatedSES; class SASTriangulator; class SolventAccessibleSurface; class SASEdge; class SASFace; class SASVertex; class TriangulatedSAS; class SESTriangulator; /** Generic RSFace Class. \ingroup Surface */ class BALL_EXPORT RSFace : public GraphTriangle< RSVertex,RSEdge,RSFace > { public: /** @name Class friends - class RSEdge - class RSVertex - class ReducedSurface - class RSComputer - class SESEdge - class SESFace - class SESVertex - class SolventExcludedSurface - class SESComputer - class TSESSingularityCleaner - class TriangulatedSES - class SESTriangulator - class SASEdge - class SASFace - class SASVertex - class SolventAccessibleSurface; - class TriangulatedSAS - class SASTriangulator */ friend class RSEdge; friend class RSVertex; friend class ReducedSurface; friend class RSComputer; friend class SESEdge; friend class SESFace; friend class SESVertex; friend class SolventExcludedSurface; friend class SESComputer; friend class SESSingularityCleaner; friend class TriangulatedSES; friend class SESTriangulator; friend class SASEdge; friend class SASFace; friend class SASVertex; friend class SolventAccessibleSurface; friend class TriangulatedSAS; friend class SASTriangulator; BALL_CREATE(RSFace) /** @name Constructors and Destructors */ //@{ /** Default constructor. This method creates a new RSFace object. */ RSFace() throw(); /** Copy constructor. Create a new RSFace object from another. @param rsface the RSFace object to be copied @param deep if deep = false, all pointers are set to NULL (default). Otherwise the new RSFace object is linked to the neighbours of the old RSFace object. */ RSFace(const RSFace& rsface, bool deep = false) throw(); /** Detailled constructor. Create a new RSFace object from a lot of nice objects @param vertex1 assigned to the first vertex @param vertex2 assigned to the second vertex @param vertex3 assigned to the third vertex @param edge1 assigned to the first edge @param edge2 assigned to the second edge @param edge3 assigned to the third edge @param center assigned to the center @param normal assigned to the normal vector @param singular @param index assigned to the index */ RSFace(RSVertex* vertex1, RSVertex* vertex2, RSVertex* vertex3, RSEdge* edge1, RSEdge* edge2, RSEdge* edge3, const TVector3& center, const TVector3& normal, bool singular, Index index) throw(Exception::DivisionByZero); /** Destructor. Destructs the RSFace object. */ virtual ~RSFace() throw(); //@} /** @name Assignment */ //@{ /** Assign from another RSFace. @param rsface the RSFace object to assign from @param deep if deep = false, all pointers are set to NULL (default). Otherwise the RSFace object is linked to the neighbours of the RSFace object to assign from. */ void set(const RSFace& rsface, bool deep = false) throw(); /** Assign from another RSFace. The RSFace object is linked to the neighbours of the RSFace object to assign from. @param rsface the RSFace object to assign from */ RSFace& operator = (const RSFace& rsface) throw(); /** Assign to a lot of nice objects @param vertex1 assigned to the first vertex @param vertex2 assigned to the second vertex @param vertex3 assigned to the third vertex @param edge1 assigned to the first edge @param edge2 assigned to the second edge @param edge3 assigned to the third edge @param center assigned to the center @param normal assigned to the normal vector @param singular @param index assigned to the index */ void set(RSVertex* vertex1, RSVertex* vertex2, RSVertex* vertex3, RSEdge* edge1, RSEdge* edge2, RSEdge* edge3, const TVector3& center, const TVector3& normal, bool singular, Index index) throw(Exception::DivisionByZero); //@} /** @name Predicates */ //@{ /** Equality operator. @return bool true if all vertices are similar modulo order and the centers are equal, false otherwise */ virtual bool operator == (const RSFace& rsface) const throw(); /** Inequality operator. @return bool false if all vertices are similar modulo order and the centers are equal, true otherwise */ virtual bool operator != (const RSFace& rsface) const throw(); /** Similarity operator. @return bool true if all vertices are similar modulo order, false otherwise */ virtual bool operator *=(const RSFace& rsface) const throw(); /** isSingular @return bool true if the RSFace is singular, false otherwise */ bool isSingular() const throw(); //@} /** @name Accessors */ //@{ /** Set the center of the probe sphere defining the RSFace. @param center the new center */ void setCenter(const TVector3& center) throw(); /** Return the center of the probe sphere defining the RSFace. @return TVector3 the center of the probe sphere */ TVector3 getCenter() const throw(); /** Set the vector orthogonal to the RSFace. @param normal the new normal */ void setNormal(const TVector3& normal) throw(Exception::DivisionByZero); /** Return the vector orthogonal to the RSFace. @return TVector3 the vector orthogonal to the RSFace. */ TVector3 getNormal() const throw(); /** Set singular */ void setSingular(bool singular) throw(); /** Remove a RSFace from a ReducedSurface graph structure. @param edges In this HashSet all edges are pushed which do not belong to any face after this remove step. @param vertices In this HashSet all vertices are pushed which possibliy are isolated after this remove step. @param faces In this HashSet all faces are pushed which have lost a neighbour face during this remove step. */ void remove (HashSet& edges, HashSet& vertices, HashSet& faces) throw(); //@} protected: /*_ @name Attributes */ //@{ /*_ The center of the probe sphere defining the RSFace */ TVector3 center_; /*_ The vector orthogonal to the RSFace */ TVector3 normal_; /*_ singular */ bool singular_; //@} }; /** @name Storers */ //@{ /** Output- Operator */ BALL_EXPORT std::ostream& operator << (std::ostream& s, const RSFace& rsface); //@} } // namespace BALL #endif // BALL_STRUCTURE_RSFACE_H ugene-1.9.8/src/plugins_3rdparty/ball/src/include/BALL/STRUCTURE/graphEdge.h0000644000175000017500000003104511651544325024720 0ustar ilyailya// -*- Mode: C++; tab-width: 2; -*- // vi: set ts=2: // // $Id: graphEdge.h,v 1.12.26.1 2007-03-25 21:25:26 oliver Exp $ // #ifndef BALL_STRUCTURE_GRAPHEDGE_H #define BALL_STRUCTURE_GRAPHEDGE_H #ifndef BALL_COMMON_H # include #endif #include namespace BALL { template class GraphVertex; template class GraphFace; template class GraphTriangle; /** Generic GraphEdge Class. \ingroup Surface */ template class GraphEdge { public: /** @name Class friends - class GraphVertex; - class GraphFace; - class GraphTriangle; */ friend class GraphVertex; friend class GraphFace; friend class GraphTriangle; BALL_CREATE(GraphEdge) /** @name Constructors and Destructors */ //@{ /** Default constructor. This method creates a new GraphEdge object. */ GraphEdge() throw(); /** Copy constructor. Create a new GraphEdge object from another. @param edge the GraphEdge object to be copied @param deep if deep = false, all pointers are set to NULL (default). Otherwise the new GraphEdge object is linked to the neighbours of the old GraphEdge object. */ GraphEdge(const GraphEdge& edge, bool deep = false) throw(); /** Detailled constructor. Create a new GraphEdge object from a lot of nice objects @param vertex1 assigned to the first vertex @param vertex2 assigned to the second vertex @param face1 assigned to the first face @param face2 assigned to the second face @param index assigned to the index */ GraphEdge(Vertex* vertex1, Vertex* vertex2, Face* face1, Face* face2, Index index) throw(); /** Destructor. Destructs the GraphEdge object. The neighboured faces and vertices are {/bf not} destructed. */ virtual ~GraphEdge() throw(); //@} /** @name Assignment */ //@{ /** Assign from another GraphEdge. @param edge the GraphEdge object to assign from @param deep if deep = false, all pointers are set to NULL (default). Otherwise the GraphEdge object is linked to the neighbours of the GraphEdge object to assign from. */ void set(const GraphEdge& edge, bool deep = false) throw(); /** Assign from another GraphEdge. The GraphEdge object is linked to the neighbours of the GraphEdge object to assign from. @param edge the GraphEdge object to assign from */ GraphEdge& operator = (const GraphEdge& edge) throw(); /** Assign from a lot of nice objects @param vertex0 assigned to the first vertex @param vertex1 assigned to the second vertex @param face0 assigned to the first face @param face1 assigned to the second face @param index assigned to the index */ void set(Vertex* vertex0, Vertex* vertex1, Face* face0, Face* face1, Index index) throw(); //@} /** @name Accessors */ //@{ /** Set one of the two vertices of the GraphEdge. @param i the first vertex is changed if i = 0, the second otherwise @param vertex a pointer to the new vertex */ void setVertex(Position i, Vertex* vertex) throw(); /** Return one of the two vertices of the GraphEdge. @param i @return Vertex* a pointer to the first vertex if i = 0, a pointer to the second vertex otherwise */ Vertex* getVertex(Position i) const throw(); /** Set one of the two faces of the GraphEdge. @param i change the first face, if i = 0, the second otherwise @param face a pointer to the new face */ void setFace(Position i, Face* face) throw(); /** Return one of the two faces of the GraphEdge. @param i @return Face* a pointer to the first face if i = 0, a pointer to the second face otherwise */ Face* getFace(Position i) const throw(); /** Set the index of the GraphEdge. @param index the new index */ void setIndex(Index index) throw(); /** Return the index of the GraphEdge. @return Index the index of the GraphEdge */ Index getIndex() const throw(); /** Return a pointer to the other vertex of the GraphEdge. If the given vertex is not incident to the GraphEdge, an exception is thrown. @param vertex one of the vertices of the GraphEdge @return Vertex* the other vertex */ Vertex* other(const Vertex* vertex) const throw(Exception::GeneralException); /** Return a pointer to the other face of the GraphEdge. If the given face is not neighboured to the GraphEdge, an exception is thrown. @param face one of the faces of the GraphEdge @return Face* the other face */ Face* other(const Face* face) const throw(Exception::GeneralException); /** Substitute a vertex by an other one. @param old_vertex the vertex that has to be substituted @param new_vertex the new vertex @return bool true, if the vertex can be substituted, false otherwise */ bool substitute(const Vertex* old_vertex, Vertex* new_vertex) throw(); /** Substitute a face by an other one. @param old_vertex the face that has to be substituted @param new_vertex the new face @return bool true, if the face can be substituted, false otherwise */ bool substitute(const Face* old_vertex, Face* new_vertex) throw(); /** Delete a face of the GraphEdge. If the second face of the GraphEdge should be deleted, it is set to NULL. If the first one should be deleted, the second one is copied to first position and then set to NULL. @param face the face to delete @return Face* a pointer to the other face */ Face* remove(const Face* face) throw(); /* Swap the two vertices of the GraphEdge */ void revert() throw(); //@} /** @name Predicates */ //@{ /** Equality operator. @return bool, true */ virtual bool operator == (const Edge&) const throw(); /** Inequality operator. @return bool false */ virtual bool operator != (const Edge&) const throw(); /** Similarity operator. @return bool true */ virtual bool operator *= (const Edge&) const throw(); //@} protected: /*_ @name Attributes */ //@{ /*_ The vertices of the GraphEdge */ Vertex* vertex_[2]; /*_ The faces of the GraphEdge */ Face* face_[2]; /*_ The index of the GraphEdge */ Index index_; //@} }; template GraphEdge::GraphEdge() throw() : index_(-1) { vertex_[0] = NULL; vertex_[1] = NULL; face_[0] = NULL; face_[1] = NULL; } template GraphEdge:: GraphEdge(const GraphEdge& edge, bool deep) throw() : index_(edge.index_) { if (deep) { vertex_[0] = edge.vertex_[0]; vertex_[1] = edge.vertex_[1]; face_[0] = edge.face_[0]; face_[1] = edge.face_[1]; } else { vertex_[0] = NULL; vertex_[1] = NULL; face_[0] = NULL; face_[1] = NULL; } } template GraphEdge::GraphEdge (Vertex* vertex1, Vertex* vertex2, Face* face1, Face* face2, Index index) throw() : index_(index) { vertex_[0] = vertex1; vertex_[1] = vertex2; face_[0] = face1; face_[1] = face2; } template GraphEdge::~GraphEdge() throw() { } template void GraphEdge::set (const GraphEdge& edge, bool deep) throw() { if (this != &edge) { if (deep) { vertex_[0] = edge.vertex_[0]; vertex_[1] = edge.vertex_[1]; face_[0] = edge.face_[0]; face_[1] = edge.face_[1]; } else { vertex_[0] = NULL; vertex_[1] = NULL; face_[0] = NULL; face_[1] = NULL; } index_ = edge.index_; } } template GraphEdge& GraphEdge::operator = (const GraphEdge& edge) throw() { if (this != &edge) { vertex_[0] = edge.vertex_[0]; vertex_[1] = edge.vertex_[1]; face_[0] = edge.face_[0]; face_[1] = edge.face_[1]; index_ = edge.index_; } return *this; } template void GraphEdge::set (Vertex* vertex0, Vertex* vertex1, Face* face0, Face* face1, Index index) throw() { vertex_[0] = vertex0; vertex_[1] = vertex1; face_[0] = face0; face_[1] = face1; index_ = index; } template void GraphEdge::setVertex(Position i, Vertex* vertex) throw() { if (i == 0) { vertex_[0] = vertex; } else { vertex_[1] = vertex; } } template Vertex* GraphEdge::getVertex(Position i) const throw() { if (i == 0) { return vertex_[0]; } else { return vertex_[1]; } } template void GraphEdge::setFace(Position i, Face* face) throw() { if (i == 0) { face_[0] = face; } else { face_[1] = face; } } template Face* GraphEdge::getFace(Position i) const throw() { if (i == 0) { return face_[0]; } else { return face_[1]; } } template void GraphEdge::setIndex(Index index) throw() { index_ = index; } template Index GraphEdge::getIndex() const throw() { return index_; } template Vertex* GraphEdge::other(const Vertex* vertex) const throw(Exception::GeneralException) { if (vertex_[0] == vertex) { return vertex_[1]; } else { if (vertex_[1] == vertex) { return vertex_[0]; } else { throw Exception::GeneralException(__FILE__, __LINE__); } } } template Face* GraphEdge::other(const Face* face) const throw(Exception::GeneralException) { if (face_[0] == face) { return face_[1]; } else { if (face_[1] == face) { return face_[0]; } else { throw Exception::GeneralException(__FILE__, __LINE__); } } } template bool GraphEdge::substitute (const Vertex* old_vertex, Vertex* new_vertex) throw() { if (vertex_[0] == old_vertex) { vertex_[0] = new_vertex; } else { if (vertex_[1] == old_vertex) { vertex_[1] = new_vertex; } else { return false; } } return true; } template bool GraphEdge::substitute (const Face* old_face, Face* new_face) throw() { if (face_[0] == old_face) { face_[0] = new_face; } else { if (face_[1] == old_face) { face_[1] = new_face; } else { return false; } } return true; } template Face* GraphEdge::remove(const Face* face) throw() { if (face_[1] == face) { face_[1] = NULL; } else { if (face_[0] == face) { face_[0] = face_[1]; face_[1] = NULL; } } return face_[0]; } template void GraphEdge::revert() throw() { Vertex* tmp = vertex_[0]; vertex_[0] = vertex_[1]; vertex_[1] = tmp; } template bool GraphEdge::operator == (const Edge&) const throw() { return true; } template bool GraphEdge::operator != (const Edge&) const throw() { return false; } template bool GraphEdge::operator *= (const Edge&) const throw() { return true; } } // namespace BALL #endif // BALL_STRUCTURE_GRAPHEDGE_H ugene-1.9.8/src/plugins_3rdparty/ball/src/include/BALL/STRUCTURE/triangulatedSurface.h0000644000175000017500000002600711651544326027031 0ustar ilyailya// -*- Mode: C++; tab-width: 2; -*- // vi: set ts=2: // // $Id: triangulatedSurface.h,v 1.40.18.1 2007-03-25 21:25:34 oliver Exp $ #ifndef BALL_STRUCTURE_TRIANGULATEDSURFACE_H #define BALL_STRUCTURE_TRIANGULATEDSURFACE_H #ifndef BALL_STRUCTURE_TRIANGLE_H # include #endif #ifndef BALL_STRUCTURE_TRIANGLEEDGE_H # include #endif #ifndef BALL_STRUCTURE_TRIANGLEPOINT_H # include #endif #ifndef BALL_MATHS_PLANE3_H # include #endif #ifndef BALL_MATHS_SURFACE_H # include #endif #ifndef BALL_MATHS_VECTOR3_H # include #endif #include #include namespace BALL { /** Generic TriangulatedSurface Class. \ingroup Surface */ class BALL_EXPORT TriangulatedSurface { public: BALL_CREATE(TriangulatedSurface) /** @name Type definitions */ //@{ typedef std::list::iterator PointIterator; typedef std::list::const_iterator ConstPointIterator; typedef std::list::iterator EdgeIterator; typedef std::list::const_iterator ConstEdgeIterator; typedef std::list::iterator TriangleIterator; typedef std::list::const_iterator ConstTriangleIterator; //@} /** @name Constructors and Destructors */ //@{ /** Default constructor. This method creates a new TriangulatedSurface object. */ TriangulatedSurface() throw(); /** Copy constructor. Create a new TriangulatedSurface object from another. @param surface the TriangulatedSurface object to be copied @param bool ignored - just for interface consistency */ TriangulatedSurface(const TriangulatedSurface& surface, bool = true) throw(); /** Destructor. Destructs the TriangulatedSurface object. */ virtual ~TriangulatedSurface() throw(); //@} /** @name Assignment */ //@{ /** Delete all points, edges and triangles. */ void clear() throw(); /** Assign from another TriangulatedSurface. @param surface the TriangulatedSurface object to assign from @param bool ignored - just for interface consistency */ void set(const TriangulatedSurface& surface, bool = true) throw(); /** Assign from another TriangulatedSurface. @param surface the TriangulatedSurface object to assign from */ TriangulatedSurface& operator = (const TriangulatedSurface& surface) throw(); //@} /** @name Accessors */ //@{ /** Insert a new point to the TriangulatedSurface. @param point a pointer to the new point */ void insert(TrianglePoint* point) throw(); /** Insert a new edge to the TriangulatedSurface. @param edge a pointer to the new edge */ void insert(TriangleEdge* edge) throw(); /** Insert a new triangle to the TriangulatedSurface. @param triangle a pointer to the new triangle */ void insert(Triangle* triangle) throw(); /** Get the number of points of the TriangulatedSurface. */ Size numberOfPoints() const throw(); /** Get the number of edges of the TriangulatedSurface. */ Size numberOfEdges() const throw(); /** Get the number of triangles of the TriangulatedSurface. */ Size numberOfTriangles() const throw(); /** Remove a point from the TriangulatedSurface. If deep is true (default) the incidence-structure will be updated. @param point a pointer to the point to delete @param deep look above */ void remove(TrianglePoint* point, bool deep = true) throw(); /** Remove a point from the TriangulatedSurface. If deep is true (default) the incidence-structure will be updated. @param p an iterator into the list of points of the TriangulatedSurface which indicates the point to delete @param deep look above */ void remove(PointIterator p, bool deep = true) throw(); /** Remove an edge from the TriangulatedSurface. If deep is true (not default) the incidence-structure will be updated. @param edge a pointer to the edge to delete @param deep look above */ void remove(TriangleEdge* edge, bool deep = true) throw(); /** Remove an edge from the TriangulatedSurface. If deep is true (not default) the incidence-structure will be updated. @param e an iterator into the list of edges of the TriangulatedSurface which indicates the edge to delete @param deep look above */ void remove(EdgeIterator e, bool deep = true) throw(); /** Remove a triangle from the TriangulatedSurface. If deep is true (not default) the incidence-structure will be updated. @param triangle a pointer to the triangle to delete @param deep look above */ void remove(Triangle* triangle, bool deep = true) throw(); /** Remove a triangle from the TriangulatedSurface. If deep is true (not default) the incidence-structure will be updated. @param t an iterator into the list of triangles of the TriangulatedSurface which indicates the triangle to delete @param deep look above */ void remove(TriangleIterator t, bool deep = true) throw(); /** Create a Surface object from the TriangulatedeSurface. @param surface the created Surface object */ void exportSurface(Surface& surface) throw(); /** Add a TriangulatedSurface object. The lists of points, edges and triangles of the given TriangulatedSurface objact are appended. The given TriangulatedSurface objact will be unchanged. @param surface the TriangulatedSurface object to add */ TriangulatedSurface& operator += (const TriangulatedSurface& surface) throw(); /** Add a TriangulatedSurface object. The lists of points, edges and triangles of the given TriangulatedSurface objact are appended. After this operation, the given TriangulatedSurface objact will be empty! @param source the TriangulatedSurface object to add */ void join(TriangulatedSurface& source) throw(); /** Shift the TriangulatedSurface. All points are shifted by a vector c. @param c the shift vector */ void shift(const TVector3& c); /** Blow up th TriangulatedSurface. All points are multiplied by a scalar r. @param r the blow up factor */ void blowUp(const double& r); /** Set the indices of al points, edges and triangles. */ void setIndices(); /** Cut the TriangulatedSurface on a plane. @param plane the plane to cut on @param fuzzy */ void cut(const TPlane3& plane, const double& fuzzy = 0); /** Delete all triangles on the border of the TriangulatedSurface */ void shrink(); /** Delete all isolated edges of the TriangulatedSurface */ void deleteIsolatedEdges() throw(); /** Delete all isolated points of the TriangulatedSurface */ void deleteIsolatedPoints() throw(); /** Get the border edges of the TriangulatedSurface. Border edges are the edges with only one triangle. @param border a list of the border edges */ void getBorder(std::list& border); //@} /** @name External Iterators */ //@{ PointIterator beginPoint() throw(); ConstPointIterator beginPoint() const throw(); PointIterator endPoint() throw(); ConstPointIterator endPoint() const throw(); EdgeIterator beginEdge() throw(); ConstEdgeIterator beginEdge() const throw(); EdgeIterator endEdge() throw(); ConstEdgeIterator endEdge() const throw(); TriangleIterator beginTriangle() throw(); ConstTriangleIterator beginTriangle() const throw(); TriangleIterator endTriangle() throw(); ConstTriangleIterator endTriangle() const throw(); //@} /*_ @name protected help functions */ //@{ protected: /*_ Test whether a TriangulatedSurface object can be copied */ bool canBeCopied() const throw(); /*_ Copy a TriangulatedSurface object */ void copy(const TriangulatedSurface& surface) throw(); //@} protected: /*_ @name Attributes */ //@{ /*_ the number of points of the triangulated surface */ Size number_of_points_; /*_ the points of the surface. */ std::list points_; /*_ the number of edges of the triangulated surface */ Size number_of_edges_; /*_ the edges of the surface. */ std::list edges_; /*_ the number of triangles of the triangulated surface */ Size number_of_triangles_; /*_ the triangles of the surface. */ std::list triangles_; //@} }; /** @name Storers \ingroup Surface */ //@{ /** Output- Operator */ BALL_EXPORT std::ostream& operator << (std::ostream& s, const TriangulatedSurface& surface); //@} /** Generic TriangulatedSphere Class. \par \par \ingroup Surface */ class BALL_EXPORT TriangulatedSphere : public TriangulatedSurface { public: BALL_CREATE(TriangulatedSphere) struct Face { TrianglePoint* p[6]; TriangleEdge* e[9]; Position pcount; Position ecount; }; /** @name Constructors and Destructors */ //@{ /** Default constructor. This method creates a new TriangulatedSphere object. */ TriangulatedSphere() throw(); /** Copy constructor. Create a new TriangulatedSphere object from another. @param sphere the TriangulatedSphere object to be copied @param bool ignored - just for interface consistency */ TriangulatedSphere(const TriangulatedSphere& sphere, bool = true) throw(); /** Destructor. Destructs the TriangulatedSphere object. */ virtual ~TriangulatedSphere() throw(); //@} /** @name Assignment */ //@{ /** Assign from another TriangulatedSphere. @param sphere the TriangulatedSphere object to assign from @param bool ignored - just for interface consistency */ void set(const TriangulatedSphere& sphere, bool = true) throw(); /** Assign from another TriangulatedSphere. @param sphere the TriangulatedSphere object to assign from */ TriangulatedSphere& operator = (const TriangulatedSphere& sphere) throw(); //@} /** @name Accessors */ //@{ /** Build an icosaeder. If the TriangulatedSphere is not empty, it will be cleared first. The center of the icosaeder will be the origin, the radius will be 1. @param out if out = true the normal vectors will be oriented outside, otherwise they will be oriented inside */ void icosaeder(bool out = true); /** Refine a triangulated sphere. The center of the sphere must be the origin, the radius must be 1. @param iterations the number of refinement iterations @param out the orientation of the normal vectors */ void refine(Position iterations, bool out = true); private: /*_ Refine a triangulated sphere once. */ void refine(bool out); void buildFourTriangles (Face face, Triangle* face0, Triangle* face1, Triangle* face2, Triangle* face3) throw(); /*_ Set the incidences of a refined triangulated sphere. */ void setIncidences(); //@} }; } // namespace BALL #endif // BALL_STRUCTURE_TRIANGULATEDSURFACE_H ugene-1.9.8/src/plugins_3rdparty/ball/src/include/BALL/STRUCTURE/SESEdge.h0000644000175000017500000001371711651544325024257 0ustar ilyailya// -*- Mode: C++; tab-width: 2; -*- // vi: set ts=2: // // $Id: SESEdge.h,v 1.25 2005-12-23 17:02:02 amoll Exp $ // #ifndef BALL_STRUCTURE_SESEDGE_H #define BALL_STRUCTURE_SESEDGE_H #ifndef BALL_STRUCTURE_GRAPHEDGE_H # include #endif #ifndef BALL_STRUCTURE_RSEDGE_H # include #endif #ifndef BALL_MATHS_CIRCLE3_H # include #endif namespace BALL { class SESFace; class SESVertex; class SolventExcludedSurface; class TriangulatedSES; class SESComputer; class SESSingularityCleaner; class SESTriangulator; /** Generic SESEdge Class. \ingroup Surface */ class BALL_EXPORT SESEdge : public GraphEdge< SESVertex,SESEdge,SESFace > { public: /** @name Class friends - class SESFace - class SESVertex - class SolventExcludedSurface - class SESComputer - class TSESSingularityCleaner - class TriangulatedSES - class SESTriangulator */ friend class SESFace; friend class SESVertex; friend class SolventExcludedSurface; friend class SESComputer; friend class SESSingularityCleaner; friend class TriangulatedSES; friend class SESTriangulator; BALL_CREATE(SESEdge) /** @name Enums */ //@{ /** type of SESEdge: 0 concave 1 convex 2 singular */ enum Type { TYPE_CONCAVE = 0, TYPE_CONVEX = 1, TYPE_SINGULAR = 2 }; //@} /** @name Constructors and Destructors */ //@{ /** Default constructor. This method creates a new SESEdge object. */ SESEdge() throw(); /** Copy constructor. Create a new SESEdge object from another. @param sesedge the SESEdge object to be copied @param deep if deep = false, all pointers are set to NULL (default). Otherwise the new SESEdge object is linked to the neighbours of the old SESEdge object. */ SESEdge(const SESEdge& sesedge, bool deep = false) throw(); /** Detailled constructor. Create a new SESEdge object from some nice objects. @param vertex0 assigned to the first vertex @param vertex1 assigned to the second vertex @param face0 assigned to the first face @param face1 assigned to the second face @param circle assigned to the circle @param rsedge assigned to the RSEdge @param type assigned to the type of the SESEdge @param index assigned to the index */ SESEdge (SESVertex* vertex0, SESVertex* vertex1, SESFace* face0, SESFace* face1, const TCircle3& circle, RSEdge* rsedge, Type type, Index index) throw(); /** Destructor. Destructs the SESEdge object. */ virtual ~SESEdge() throw(); //@} /** @name Assignment */ //@{ /** Assign from another SESEdge. @param sesedge the SESEdge object to assign from @param deep if deep = false, all pointers are set to NULL (default). Otherwise the SESEdge object is linked to the neighbours of the SESEdge object to assign from. */ void set(const SESEdge& sesedge, bool deep = false) throw(); /** Assign from another SESEdge. The SESEdge object is linked to the neighbours of the SESEdge object to assign from. @param sesedge the SESEdge object to assign from */ SESEdge& operator = (const SESEdge& sesedge) throw(); /** Assign from some nice objects. @param vertex0 assigned to the first vertex @param vertex1 assigned to the second vertex @param face0 assigned to the first face @param face1 assigned to the second face @param circle assigned to the circle @param rsedge assigned to the RSEdge @param type assigned to the type of the SESEdge @param index assigned to the index */ void set(SESVertex* vertex0, SESVertex* vertex1, SESFace* face0, SESFace* face1, const TCircle3& circle, RSEdge* rsedge, Type type, Index index) throw(); //@} /** @name Accessors */ //@{ /** Set the circle on wich the SESEdge lies. @param center the new circle */ void setCircle(const TCircle3& center) throw(); /** Return the circle on wich the SESEdge lies. @return TCircle3 the circle of The SESEdge */ TCircle3 getCircle() const throw(); /** Set the corresponding RSEdge. @param rsedge a pointer to the new RSEdge */ void setRSEdge(RSEdge* rsedge) throw(); /** Return the corresponding RSEdge. @return RSEdge* a pointer to th correwsponding RSEdge */ RSEdge* getRSEdge() const throw(); /** Set the type of the SESEdge. @param type the new type of the SESEdge */ void setType(Type type) throw(); /** Get the type of the SESEdge. @return Type the type of the SESEdge */ Type getType() const throw(); //@} /** @name Predicates */ //@{ /** Equality operator. @return bool true if all vertices are equal modulo order, false otherwise */ virtual bool operator == (const SESEdge& sesedge) const throw(); /** Inequality operator. @return bool false if all vertices are equal modulo order, true otherwise */ virtual bool operator != (const SESEdge& sesedge) const throw(); /** similarity operator. @return bool true */ virtual bool operator *= (const SESEdge&) const throw(); /** isFree. @return bool true if the RSEdge of the SESEdge is free, false otherwise */ bool isFree() const throw(); //@} protected: /*_ @name Attributes */ //@{ /*_ The circle on which the SESEdge lies. */ TCircle3 circle_; /*_ A pointer to the corresponding RSEdge. */ RSEdge* rsedge_; /*_ The type of the SESEdge. */ //int type; Type type_; //@} }; /** @name Storers */ //@{ /** Output- Operator */ BALL_EXPORT std::ostream& operator << (std::ostream& s, const SESEdge& sesedge); //@} } // namespace BALL #endif // BALL_STRUCTURE_SESEDGE_H ugene-1.9.8/src/plugins_3rdparty/ball/src/include/BALL/STRUCTURE/solventAccessibleSurface.h0000644000175000017500000000675111651544326030022 0ustar ilyailya// -*- Mode: C++; tab-width: 2; -*- // vi: set ts=2: // // $Id: solventAccessibleSurface.h,v 1.12 2005-12-23 17:02:04 amoll Exp $ #ifndef BALL_STRUCTURE_SOLVENTACCESSIBLESURFACE_H #define BALL_STRUCTURE_SOLVENTACCESSIBLESURFACE_H #ifndef BALL_STRUCTURE_SASEDGE_H # include #endif #ifndef BALL_STRUCTURE_SASFACE_H # include #endif #ifndef BALL_STRUCTURE_SASVERTEX_H # include #endif #ifndef BALL_STRUCTURE_REDUCEDSURFACE_H # include #endif #ifndef BALL_MATHS_SPHERE3_H # include #endif #include namespace BALL { class TriangulatedSAS; class SASTriangulator; /** Generic SolventAccessibleSurface Class. \ingroup Surface */ class BALL_EXPORT SolventAccessibleSurface { public: /** @name Class friends - class TriangulatedSAS - class SASTriangulator */ friend class TriangulatedSAS; friend class SASTriangulator; BALL_CREATE(SolventAccessibleSurface) /** @name Constructors and Destructors */ //@{ /** Default constructor. This method creates a new SolventAccessibleSurface object. */ SolventAccessibleSurface() throw(); /** Copy constructor. Create a new SolventAccessibleSurface object from another. @param sas the SolventAccessibleSurface object to be copied @param bool ignored - just for interface consistency */ SolventAccessibleSurface(const SolventAccessibleSurface& sas, bool = false) throw(); /** Detailed constructor */ SolventAccessibleSurface(ReducedSurface* reduced_surface) throw(); /** Destructor. As there are no dynamic data structures, nothing happens. */ virtual ~SolventAccessibleSurface() throw(); //@} /** @name Accessors */ //@{ /** */ void setVertex(SASVertex* vertex, Position i) throw(Exception::IndexOverflow); /** */ SASVertex* getVertex(Position i) const throw(Exception::IndexOverflow); /** */ Size numberOfVertices() const throw(); /** */ void setEdge(SASEdge* edge, Position i) throw(Exception::IndexOverflow); /** */ SASEdge* getEdge(Position i) const throw(Exception::IndexOverflow); /** */ Size numberOfEdges() const throw(); /** */ void setFace(SASFace* face, Position i) throw(Exception::IndexOverflow); /** */ SASFace* getFace(Position i) const throw(Exception::IndexOverflow); /** */ Size numberOfFaces() const throw(); /** */ void setRS(ReducedSurface* rs) throw(); /** */ ReducedSurface* getRS() const throw(); /** */ void clear(); /** Computes the solvent excluded surface from a ReducedSurface object */ void compute() throw(); //@} private: /*_ @name SAS computation (private) */ //@{ void preProcessing() throw(); void get() throw(); void createFace(Position j) throw(); void createVertex(Position j) throw(); void createEdge(Position j) throw(); //@} protected: Position number_of_vertices_; ::std::vector vertices_; Position number_of_edges_; ::std::vector edges_; Position number_of_faces_; ::std::vector faces_; ReducedSurface* reduced_surface_; }; /** @name Storers */ //@{ /** Output- Operator */ BALL_EXPORT std::ostream& operator << (std::ostream& s, const SolventAccessibleSurface& sas); //@} } // namespace BALL #endif // BALL_STRUCTURE_SOLVENTACCESSIBLESURFACE_H ugene-1.9.8/src/plugins_3rdparty/ball/src/include/BALL/STRUCTURE/graphFace.h0000644000175000017500000010157111651544325024714 0ustar ilyailya// -*- Mode: C++; tab-width: 2; -*- // vi: set ts=2: // // $Id: graphFace.h,v 1.14.26.2 2007-06-17 07:02:20 oliver Exp $ // // Author: // // #ifndef BALL_STRUCTURE_GRAPHFACE_H #define BALL_STRUCTURE_GRAPHFACE_H #ifndef BALL_COMMON_H # include #endif #include #include namespace BALL { template class GraphVertex; template class GraphEdge; /** Generic GraphFace Class. \ingroup Surface */ template class GraphFace { public: /** @name Class friends - class GraphVertex; - class GraphEdge; */ friend class GraphVertex; friend class GraphEdge; BALL_CREATE(GraphFace) /** @name Type definitions */ //@{ typedef typename std::list::iterator VertexIterator; typedef typename std::list::const_iterator ConstVertexIterator; typedef typename std::list::iterator EdgeIterator; typedef typename std::list::const_iterator ConstEdgeIterator; //@} /** @name Constructors and Destructors */ //@{ /** Default constructor. This method creates a new GraphFace object. */ GraphFace() throw(); /** Copy constructor. Create a new GraphFace object from another. @param face the GraphFace object to be copied @param deep if deep = false, all pointers are set to NULL (default). Otherwise the new GraphFace object is linked to the neighbours of the old GraphFace object. */ GraphFace(const GraphFace& face, bool deep = false) throw(); /** Destructor. Destructs the GraphFace object. */ virtual ~GraphFace() throw(); //@} /** @name Assignments */ //@{ /** Assign from another GraphFace. @param face the GraphFacee object to assign from @param deep if deep = false, all pointers are set to NULL (default). Otherwise the GraphFace object is linked to the neighbours of the GraphFace object to assign from. */ void set(const GraphFace& face, bool deep = false) throw(); /** Assign from another GraphFace. The GraphFace object is linked to the neighbours of the GraphFace object to assign from. @param face the GraphFace object to assign from */ GraphFace& operator = (const GraphFace& face) throw(); //@} /** @name Accessors */ //@{ /** Insert a new vertex to the GraphFace. @param vertex a pointer to the new vertex */ void insert(Vertex* vertex) throw(); /** Insert a new edge to the GraphFace. @param edge a pointer to the new edge */ void insert(Edge* edge) throw(); /** Remove a vertex from the GraphFace. @param vertex a pointer to the vertex to remove */ void remove(Vertex* vertex) throw(); /** Remove an edge from the GraphFace. @param edge a pointer to the edge to remove */ void remove(Edge* edge) throw(); /** Return the number of vertices of the GraphFace. @return Position the number of vertices of the GraphFace */ Position numberOfVertices() const throw(); /** Return the number of edges of the GraphFace. @return Position the number of edges of the GraphFace */ Position numberOfEdges() const throw(); /** Set the index of the GraphFace. @param index the new index */ void setIndex(Index index) throw(); /** Return the index of the GraphFace. @return Index the index of the GraphFace */ Index getIndex() const throw(); /** Find the two edges of the GraphFace that belong to the given vertex @param vertex a pointer to the given vertex @param edge1 a pointer to the first found edge @param edge2 a pointer to the second found edge @return bool true if the edges can be found, false otherwise */ bool getEdges(const Vertex* vertex, Edge*& edge1, Edge*& edge2) const throw(); /** Find the edge of the GraphFace that belongs to the two given vertices @param vertex1 a pointer to the first given vertex @param vertex2 a pointer to the second given vertex @param edge a pointer to the found edge @return bool true if the edge can be found, false otherwise */ bool getEdge (const Vertex* vertex1, const Vertex* vertex2, Edge*& edge) const throw(); /** Find the edge of the GraphFace that is similar to the given edge. @param edge a pointer to the given edge @return Edge* a pointer to the similar edge of te GraphFace if it can be found, otherwise NULL */ Edge* getSimilarEdge(const Edge* edge) const throw(); /** Substitute a vertex by an other one. @param old_vertex the vertex that has to be substituted @param new_vertex the new vertex @return bool true, if the vertex can be substituted, false otherwise */ bool substitute(const Vertex* old_vertex, Vertex* new_vertex) throw(); /** Substitute an edge by an other one. @param old_edge the edge that has to be substituted @param new_edge the new edge @return bool true, if the edge can be substituted, false otherwise */ bool substitute(const Edge* old_edge, Edge* new_edge) throw(); //@} /** @name Predicates */ //@{ /** Equality operator. @return bool true */ virtual bool operator == (const Face& face) const throw(); /** Inequality operator. @return bool false */ virtual bool operator != (const Face& face) const throw(); /** Similarity operator. @return bool true */ virtual bool operator *= (const Face& face) const throw(); /** Test whether a vertex is meber of the face. @param vertex a pointer to the the vertex to test @return Vertex* a pointer to the vertex if it exists, otherwise NULL */ Vertex* has(Vertex* vertex) const throw(); /** Test whether an edge is meber of the face. @param edge a pointer to the edge to test @return Edge* a pointer to the edge if it exists, otherwise NULL */ Edge* has(Edge* edge) const throw(); //@} /** @name External Iterators */ //@{ VertexIterator beginVertex() throw(); ConstVertexIterator beginVertex() const throw(); VertexIterator endVertex() throw(); ConstVertexIterator endVertex() const throw(); EdgeIterator beginEdge() throw(); ConstEdgeIterator beginEdge() const throw(); EdgeIterator endEdge() throw(); ConstEdgeIterator endEdge() const throw(); //@} protected: /*_ @name Attributes */ //@{ /*_ The vertices of the GraphFace */ std::list vertex_; /*_ The edges of the GraphFace */ std::list edge_; /* The index of the GraphFace */ Index index_; //@} }; template GraphFace::GraphFace() throw() : vertex_(), edge_(), index_(-1) { } template GraphFace::GraphFace (const GraphFace& face, bool deep) throw() : vertex_(), edge_(), index_(face.index_) { if (deep) { vertex_ = face.vertex_; edge_ = face.edge_; } } template GraphFace::~GraphFace() throw() { } template void GraphFace::set (const GraphFace& face, bool deep) throw() { if (this != &face) { if (deep) { vertex_ = face.vertex_; edge_ = face.edge_; } index_ = face.index_; } } template GraphFace& GraphFace::operator = (const GraphFace& face) throw() { if (this != &face) { vertex_ = face.vertex_; edge_ = face.edge_; index_ = face.index_; } return *this; } template void GraphFace::insert(Vertex* vertex) throw() { typename std::list::iterator v = vertex_.begin(); bool found = false; while ((!found) && (v != vertex_.end())) { found = (*v == vertex); v++; } if (!found) { vertex_.push_back(vertex); } } template void GraphFace::insert(Edge* edge) throw() { typename std::list::iterator e = edge_.begin(); bool found = false; while ((!found) && (e != edge_.end())) { found = (*e == edge); e++; } if (!found) { edge_.push_back(edge); } } template void GraphFace::remove(Vertex* vertex) throw() { vertex_.remove(vertex); } template void GraphFace::remove(Edge* edge) throw() { edge_.remove(edge); } template Position GraphFace::numberOfVertices() const throw() { return vertex_.size(); } template Position GraphFace::numberOfEdges() const throw() { return edge_.size(); } template void GraphFace::setIndex(Index index) throw() { index_ = index; } template Index GraphFace::getIndex() const throw() { return index_; } template bool GraphFace::getEdges (const Vertex* vertex, Edge*& edge1, Edge*& edge2) const throw() { bool found1 = false; bool found2 = false; typename std::list::const_iterator e = edge_.begin(); while ((!found1) && (e != edge_.end())) { if (((*e)->vertex_[0] == vertex) || ((*e)->vertex_[1] == vertex)) { edge1 = *e; found1 = true; } e++; } if (found1) { while ((!found2) && (e != edge_.end())) { if (((*e)->vertex_[0] == vertex) || ((*e)->vertex_[1] == vertex)) { edge2 = *e; found2 = true; } e++; } } return (found1 && found2); } template bool GraphFace::getEdge (const Vertex* vertex1, const Vertex* vertex2, Edge*& edge) const throw() { typename std::list::const_iterator e = edge_.begin(); bool found = false; while ((!found) && (e != edge_.end())) { if ((((*e)->vertex_[0] == vertex1) && ((*e)->vertex_[1] == vertex2)) || (((*e)->vertex_[0] == vertex2) && ((*e)->vertex_[1] == vertex1)) ) { edge = *e; found = true; } e++; } return found; } template Edge* GraphFace::getSimilarEdge(const Edge* edge) const throw() { typename std::list::const_iterator e = edge_.begin(); while (e != edge_.end()) { if (**e *= *edge) { return *e; } e++; } return NULL; } template bool GraphFace::substitute (const Vertex* old_vertex, Vertex* new_vertex) throw() { typename std::list::iterator v = vertex_.begin(); while (v != vertex_.end()) { if (*v == old_vertex) { *v = new_vertex; return true; } v++; } return false; } template bool GraphFace::substitute (const Edge* old_edge, Edge* new_edge) throw() { typename std::list::iterator e = edge_.begin(); while (e != edge_.end()) { if (*e == old_edge) { *e = new_edge; return true; } e++; } return false; } template bool GraphFace::operator == (const Face&) const throw() { return true; } template bool GraphFace::operator != (const Face&) const throw() { return false; } template bool GraphFace::operator *= (const Face&) const throw() { return true; } template Vertex* GraphFace::has(Vertex* vertex) const throw() { typename std::list::const_iterator v = vertex_.begin(); while (v != vertex_.end()) { if (*v == vertex) { return *v; } v++; } return NULL; } template Edge* GraphFace::has(Edge* edge) const throw() { typename std::list::const_iterator e = edge_.begin(); while (e != edge_.end()) { if (*e == edge) { return *e; } e++; } return NULL; } template typename GraphFace::VertexIterator GraphFace::beginVertex() throw() { return vertex_.begin(); } template typename GraphFace::ConstVertexIterator GraphFace::beginVertex() const throw() { return vertex_.begin(); } template typename GraphFace::VertexIterator GraphFace::endVertex() throw() { return vertex_.end(); } template typename GraphFace::ConstVertexIterator GraphFace::endVertex() const throw() { return vertex_.end(); } template typename GraphFace::EdgeIterator GraphFace::beginEdge() throw() { return edge_.begin(); } template typename GraphFace::ConstEdgeIterator GraphFace::beginEdge() const throw() { return edge_.begin(); } template typename GraphFace::EdgeIterator GraphFace::endEdge() throw() { return edge_.end(); } template typename GraphFace::ConstEdgeIterator GraphFace::endEdge() const throw() { return edge_.end(); } /** Generic GraphTriangle Class. \ingroup Surface */ template class GraphTriangle { public: /** @name Class friends - class GraphVertex; - class GraphEdge; */ friend class GraphVertex; friend class GraphEdge; /** @name Constructors and Destructors */ //@{ BALL_CREATE(GraphTriangle) /** Default constructor. This method creates a new GraphTriangle object. */ GraphTriangle() throw(); /** Copy constructor. Create a new GraphTriangle object from another. @param face the GraphTriangle object to be copied @param deep if deep = false, all pointers are set to NULL (default). Otherwise the new GraphTriangle object is linked to the neighbours of the old GraphTriangle object. */ GraphTriangle (const GraphTriangle& face, bool deep = false) throw(); /** Detailled constructor. Create a new GraphTriangle object from some nice objects @param vertex1 assigned to the first vertex @param vertex2 assigned to the second vertex @param vertex3 assigned to the third vertex @param edge1 assigned to the first edge @param edge2 assigned to the second edge @param edge3 assigned to the third edge @param index assigned to the index */ GraphTriangle (Vertex* vertex1, Vertex* vertex2, Vertex* vertex3, Edge* edge1, Edge* edge2, Edge* edge3, Index index) throw(); /** Destructor. Destructs the GraphTriangle object. */ virtual ~GraphTriangle() throw(); //@} /** @name Assignment */ //@{ /** Assign from another GraphTriangle. @param face the GraphTriangle object to assign from @param deep if deep = false, all pointers are set to NULL (default). Otherwise the GraphTriangle object is linked to the neighbours of the GraphTriangle object to assign from. */ void set(const GraphTriangle& face, bool deep = false) throw(); /** Assign from another GraphTriangle. The GraphTriangle object is linked to the neighbours of the GraphTriangle object to assifgn from. @param face the GraphTriangle object to assign from */ GraphTriangle& operator = (const GraphTriangle& face) throw(); /** Assign to a lot of nice objects @param vertex1 assigned to the first vertex @param vertex2 assigned to the second vertex @param vertex3 assigned to the third vertex @param edge1 assigned to the first edge @param edge2 assigned to the second edge @param edge3 assigned to the third edge @param index assigned to the index */ void set (Vertex* vertex1, Vertex* vertex2, Vertex* vertex3, Edge* edge1, Edge* edge2, Edge* edge3, Index index) throw(); //@} /** @name Accessors */ //@{ /** Set one of the vertices of the GraphTriangle. @param i the relative index of the vertex which should be set. If i is greater three, an exception is thrown. @param vertex a pointer to the new vertex */ void setVertex(Position i, Vertex* vertex) throw(Exception::IndexOverflow); /** Return one of the vertices of the GraphTriangle. @param i the relative index of the vertex which should be given back. If i is greater than three, an exception is thrown. @return Vertex* a pointer to the asked vertex */ Vertex* getVertex(Position i) const throw(Exception::IndexOverflow); /** Set one of the edges of the GraphTriangle. @param i the relative index of the edge which should be set. If i is greater than three, an exception is thrown. @param edge a pointer to the new edge */ void setEdge(Position i, Edge* edge) throw(Exception::IndexOverflow); /** Return one of the edges of the GraphTriangle. @param i the relative index of the edge which should be given back. If i is greater than three, an exception is thrown. @return Edge* a pointer to the asked vertex */ Edge* getEdge(Position i) const throw(Exception::IndexOverflow); /** Set the index of the GraphTriangle. @param index the new index */ void setIndex(Index index) throw(); /** Return the index of the GraphTriangle. @return Index the index of the GraphTriangle */ Index getIndex() const throw(); /** Find the two edges of the GraphTriangle that belong to the given vertex. @param vertex a pointer to the given vertex @param edge1 a pointer to the first found edge @param edge2 a pointer to the second found edge @return bool true if the edges can be found, false otherwise */ bool getEdges(const Vertex* vertex, Edge*& edge1, Edge*& edge2) const throw(); /** Find the edge of the GraphTriangle that belongs to the two given vertices. @param vertex1 a pointer to the first given vertex @param vertex2 a pointer to the second given vertex @param edge a pointer to the found edge @return bool true if the edge can be found, false otherwise */ bool getEdge (const Vertex* vertex1, const Vertex* vertex2, Edge*& edge) const throw(); /** Find the edge of the GraphFace that is similar to the given edge. @param edge a pointer to the given edge @param similar_edge a pointer to the similar edge of te GraphFace if it can be found, otherwise NULL @return Index the relative index of the similar edge if it can be found, otherwise -1 */ Index getSimilarEdge(const Edge* edge, Edge*& similar_edge) const throw(); /** Return the relative index of a vertex in the GraphTriangle. @return Index the relative index of the vertex */ Index getRelativeIndex(const Vertex* vertex) const throw(); /** Return the relative index of an edge in the GraphTriangle. @return Index the relative index of the edge */ Index getRelativeIndex(const Edge* edge) const throw(); /** Return a pointer to the third vertex of the GraphTriangle. @param v1 a pointer to the first vertex @param v2 a pointer to the second vertex @return Vertex* a pointer to the third vertex */ Vertex* third(const Vertex* v1, const Vertex* v2) const throw(); /** Return a pointer to the third edge of the GraphTriangle. @param e1 a pointer to the first edge @param e2 a pointer to the second edge @return Edge* a pointer to the third edge */ Edge* third(const Edge* e1, const Edge* e2) const throw(); /** Get the edge of the GraphFace which lies on the opposite side of the given vertex. @param vertex a pointer to a vertex of the GraphTriangle @return Edge* a pointer to the opposite Edge */ Edge* getOppositeEdge(const Vertex* vertex) const throw(); /** Get the vertex of the GraphFace which lies on the opposite side of the given edge. @param edge a pointer to an edge of the GraphTriangle @return Vertex* a pointer to the opposite vertex */ Vertex* getOppositeVertex(const Edge* edge) const throw(); /** Substitute a vertex by an other one. @param old_vertex the vertex that has to be substituted @param new_vertex the new vertex @return bool true, if the vertex can be substituted, false otherwise */ bool substitute(const Vertex* old_vertex, Vertex* new_vertex) throw(); /** Substitute an edge by an other one. @param old_edge the edge that has to be substituted @param new_edge the new edge @return bool true, if the edge can be substituted, false otherwise */ bool substitute(const Edge* old_edge, Edge* new_edge) throw(); //@} /** @name Predicates */ //@{ /** Equality operator. @return bool true */ virtual bool operator == (const Face&) const throw(); /** Inequality operator. @return bool false */ virtual bool operator != (const Face&) const throw(); /** Similarity operator. @return bool true */ virtual bool operator *= (const Face&) const throw(); /** Test whether a vertex is meber of the face. @param vertex a pointer to the the vertex to test @return Vertex* a pointer to the vertex if it exists, otherwise NULL */ Vertex* has(Vertex* vertex) const throw(); /** Test whether an edge is meber of the face. @param edge a pointer to the edge to test @return Edge* a pointer to the edge if it exists, otherwise NULL */ Edge* has(Edge* edge) const throw(); //@} protected: /*_ The vertices of the GraphTriangle */ Vertex* vertex_[3]; /*_ The edges of the GraphTriangle */ Edge* edge_[3]; /* The index of the GraphTriangle */ Index index_; }; template GraphTriangle::GraphTriangle() throw() : index_(-1) { vertex_[0] = NULL; vertex_[1] = NULL; vertex_[2] = NULL; edge_[0] = NULL; edge_[1] = NULL; edge_[2] = NULL; } template GraphTriangle::GraphTriangle (const GraphTriangle& face, bool deep) throw() : index_(face.index_) { if (deep) { vertex_[0] = face.vertex_[0]; vertex_[1] = face.vertex_[1]; vertex_[2] = face.vertex_[2]; edge_[0] = face.edge_[0]; edge_[1] = face.edge_[1]; edge_[2] = face.edge_[2]; } else { vertex_[0] = NULL; vertex_[1] = NULL; vertex_[2] = NULL; edge_[0] = NULL; edge_[1] = NULL; edge_[2] = NULL; } } template GraphTriangle::GraphTriangle (Vertex* vertex1, Vertex* vertex2, Vertex* vertex3, Edge* edge1, Edge* edge2, Edge* edge3, Index index) throw() : index_(index) { vertex_[0] = vertex1; vertex_[1] = vertex2; vertex_[2] = vertex3; edge_[0] = edge1; edge_[1] = edge2; edge_[2] = edge3; } template GraphTriangle::~GraphTriangle() throw() { } template void GraphTriangle::set (const GraphTriangle& face, bool deep) throw() { if (this != &face) { if (deep) { vertex_[0] = face.vertex_[0]; vertex_[1] = face.vertex_[1]; vertex_[2] = face.vertex_[2]; edge_[0] = face.edge_[0]; edge_[1] = face.edge_[1]; edge_[2] = face.edge_[2]; } else { vertex_[0] = NULL; vertex_[1] = NULL; vertex_[2] = NULL; edge_[0] = NULL; edge_[1] = NULL; edge_[2] = NULL; } index_ = face.index_; } } template GraphTriangle& GraphTriangle::operator = (const GraphTriangle& face) throw() { if (this != &face) { vertex_[0] = face.vertex_[0]; vertex_[1] = face.vertex_[1]; vertex_[2] = face.vertex_[2]; edge_[0] = face.edge_[0]; edge_[1] = face.edge_[1]; edge_[2] = face.edge_[2]; index_ = face.index_; } return *this; } template void GraphTriangle::set (Vertex* vertex1, Vertex* vertex2, Vertex* vertex3, Edge* edge1, Edge* edge2, Edge* edge3, Index index) throw() { vertex_[0] = vertex1; vertex_[1] = vertex2; vertex_[2] = vertex3; edge_[0] = edge1; edge_[1] = edge2; edge_[2] = edge3; index_ = index; } template void GraphTriangle::setVertex(Position i, Vertex* vertex) throw(Exception::IndexOverflow) { if (i > 2) { throw Exception::IndexOverflow(__FILE__,__LINE__,i,2); } else { vertex_[i] = vertex; } } template Vertex* GraphTriangle::getVertex(Position i) const throw(Exception::IndexOverflow) { if (i > 2) { throw Exception::IndexOverflow(__FILE__,__LINE__,i,2); } else { return vertex_[i]; } } template void GraphTriangle::setEdge(Position i, Edge* edge) throw(Exception::IndexOverflow) { if (i > 2) { throw Exception::IndexOverflow(__FILE__,__LINE__,i,2); } else { edge_[i] = edge; } } template Edge* GraphTriangle::getEdge(Position i) const throw(Exception::IndexOverflow) { if (i > 2) { throw Exception::IndexOverflow(__FILE__,__LINE__,i,2); } else { return edge_[i]; } } template void GraphTriangle::setIndex(Index index) throw() { index_ = index; } template Index GraphTriangle::getIndex() const throw() { return index_; } template bool GraphTriangle::getEdges (const Vertex* vertex, Edge*& edge1, Edge*& edge2) const throw() { Position i = 0; bool found1 = false; bool found2 = false; while ((!found1) && (i < 3)) { if (edge_[i] != NULL) { if ((edge_[i]->vertex_[0] == vertex) || (edge_[i]->vertex_[1] == vertex) ) { edge1 = edge_[i]; found1 = true; } } i++; } if (found1) { while ((!found2) && (i < 3)) { if (edge_[i] != NULL) { if ((edge_[i]->vertex_[0] == vertex) || (edge_[i]->vertex_[1] == vertex) ) { edge2 = edge_[i]; found2 = true; } } i++; } } return (found1 && found2); } template bool GraphTriangle::getEdge (const Vertex* vertex1, const Vertex* vertex2, Edge*& edge) const throw() { Position i = 0; bool found = false; while ((!found) && (i < 3)) { if (edge_[i] != NULL) { if (((edge_[i]->vertex_[0] == vertex1) && (edge_[i]->vertex_[1] == vertex2) ) || ((edge_[i]->vertex_[0] == vertex2) && (edge_[i]->vertex_[1] == vertex1) ) ) { edge = edge_[i]; found = true; } } i++; } return found; } template Index GraphTriangle::getSimilarEdge (const Edge* edge, Edge*& similar_edge) const throw() { if (*edge_[0] *= *edge) { similar_edge = edge_[0]; return 0; } if (*edge_[1] *= *edge) { similar_edge = edge_[1]; return 1; } if (*edge_[2] *= *edge) { similar_edge = edge_[2]; return 2; } similar_edge = NULL; return -1; } template Index GraphTriangle::getRelativeIndex (const Vertex* vertex) const throw() { for (Position i = 0; i < 3; i++) { if (vertex_[i] == vertex) { return i; } } return -1; } template Index GraphTriangle::getRelativeIndex (const Edge* edge) const throw() { for (Position i = 0; i < 3; i++) { if (edge_[i] == edge) { return i; } } return -1; } template Vertex* GraphTriangle::third (const Vertex* v1, const Vertex* v2) const throw() { if ((vertex_[0] == v1) || (vertex_[0] == v2)) { if ((vertex_[1] == v1) || (vertex_[1] == v2)) { return vertex_[2]; } else { return vertex_[1]; } } else { return vertex_[0]; } } template Edge* GraphTriangle::third (const Edge* e1, const Edge* e2) const throw() { if ((edge_[0] == e1) || (edge_[0] == e2)) { if ((edge_[1] == e1) || (edge_[1] == e2)) { return edge_[2]; } else { return edge_[1]; } } else { return edge_[0]; } } template Edge* GraphTriangle::getOppositeEdge (const Vertex* vertex) const throw() { for (Position i = 0; i < 3; i++) { if ((edge_[i]->vertex_[0] != vertex) && (edge_[i]->vertex_[1] != vertex) ) { return edge_[i]; } } return NULL; } template Vertex* GraphTriangle::getOppositeVertex (const Edge* edge) const throw() { for (Position i = 0; i < 3; i++) { if ((vertex_[i] != edge->vertex_[0]) && (vertex_[i] != edge->vertex_[1]) ) { return vertex_[i]; } } return NULL; } template bool GraphTriangle::substitute (const Vertex* old_vertex, Vertex* new_vertex) throw() { for (Position i = 0; i < 3; i++) { if (vertex_[i] == old_vertex) { vertex_[i] = new_vertex; return true; } } return false; } template bool GraphTriangle::substitute (const Edge* old_edge, Edge* new_edge) throw() { for (Position i = 0; i < 3; i++) { if (edge_[i] == old_edge) { edge_[i] = new_edge; return true; } } return false; } template bool GraphTriangle::operator == (const Face&) const throw() { return true; } template bool GraphTriangle::operator != (const Face&) const throw() { return false; } template bool GraphTriangle::operator *= (const Face&) const throw() { return true; } template Vertex* GraphTriangle::has(Vertex* vertex) const throw() { if (vertex_[0] == vertex) { return vertex_[0]; } if (vertex_[1] == vertex) { return vertex_[1]; } if (vertex_[2] == vertex) { return vertex_[2]; } return NULL; } template Edge* GraphTriangle::has(Edge* edge) const throw() { if (edge_[0] == edge) { return edge_[0]; } if (edge_[1] == edge) { return edge_[1]; } if (edge_[2] == edge) { return edge_[2]; } return NULL; } } // namespace BALL #endif // BALL_STRUCTURE_RSFACE_H ugene-1.9.8/src/plugins_3rdparty/ball/src/include/BALL/STRUCTURE/triangulatedSAS.h0000644000175000017500000001364211651544326026070 0ustar ilyailya// -*- Mode: C++; tab-width: 2; -*- // vi: set ts=2: // // $Id: triangulatedSAS.h,v 1.12.18.1 2007-03-25 21:25:33 oliver Exp $ #ifndef BALL_STRUCTURE_TRIANGULATEDSAS_H #define BALL_STRUCTURE_TRIANGULATEDSAS_H //#define with_indices //#define debug_triangulation #ifdef debug_triangulation # define with_bonds //# define with_normals #endif #ifdef with_indices # define print_debug_info #endif #ifndef BALL_STRUCTURE_SASEDGE_H # include #endif #ifndef BALL_STRUCTURE_SASFACE_H # include #endif #ifndef BALL_TRUCTURE_SOLVENTEXCLUDEDSURFACE_H # include #endif #ifndef BALL_STRUCTURE_TRIANGULATEDSURFACE_H # include #endif #ifndef BALL_STRUCTURE_TRIANGLE_H # include #endif #ifndef BALL_STRUCTURE_TRIANGLEEDGE_H # include #endif #ifndef BALL_STRUCTURE_TRIANGLEPOINT_H # include #endif #ifndef BALL_MATHS_ANGLE_H # include #endif #ifndef BALL_MATHS_CIRCLE3_H # include #endif #ifndef BALL_MATHS_VECTOR3_H # include #endif #ifndef BALL_DATATYPE_HASHGRID_H # include #endif #include #include namespace BALL { class SASTriangulator; /** Generic TriangulatedSAS Class. \ingroup Surface */ class BALL_EXPORT TriangulatedSAS : public TriangulatedSurface { public: #ifdef debug_triangulation void printToHINFile(string filename); #endif /** @name Class friends - class SASTriangulator */ friend class SASTriangulator; BALL_CREATE(TriangulatedSAS) /** @name Constructors and Destructors */ //@{ /** Default constructor. This method creates a new TriangulatedSAS object. */ TriangulatedSAS() throw(); /** Copy constructor. Create a new TriangulatedSAS object from another. @param surface the TriangulatedSAS object to be copied @param bool ignored - just for interface consistency */ TriangulatedSAS(const TriangulatedSAS& surface, bool = true) throw(); /** Detailed constructor. Create a new empty TriangulatedSAS object and set its SAS. @param sas a pointer to the corresponding SAS @param density the density to use by triangulation */ TriangulatedSAS(SolventAccessibleSurface* sas, const double& density) throw(); /** Destructor. Destructs the TriangulatedSAS object. */ virtual ~TriangulatedSAS() throw(); //@} /** @name Assignment */ //@{ /** Assign from another TriangulatedSAS. @param surface the TriangulatedSAS object to assign from @param bool ignored - just for interface consistency */ void set(const TriangulatedSAS& surface, bool = true) throw(); /** Assign from another TriangulatedSAS. @param surface the TriangulatedSAS object to assign from */ TriangulatedSAS& operator = (const TriangulatedSAS& surface) throw(); //@} /** @name Accessors */ //@{ /** Set the density used by triangulation. */ void setDensity(const double& density) throw(); /** Get the density used by triangulation. */ double getDensity() const throw(); /** Compute the solvent-accessible surface */ void compute(int& progress) throw(); //@} protected: /*_ @name Attributes */ //@{ SolventAccessibleSurface* sas_; double density_; //@} }; /** Generic SASTriangulator Class. \par \par \ingroup Surface */ class BALL_EXPORT SASTriangulator { public: #ifdef debug_triangulation void printToHINFile(string filename); void Contour2HIN(const std::list& contour, const string& file); void SASEdge2HIN(SASEdge* edge, const string& file); #endif BALL_CREATE(SASTriangulator) /** @name Constructors and Destructors */ //@{ /** Default constructor. This method creates a new SASTriangulator object. */ SASTriangulator() throw(); /** Detailed constructor. Create a new empty SASTriangulator object and set its SAS. @param tsas a pointer to the corresponding SAS */ SASTriangulator(TriangulatedSAS* tsas) throw(); /** Destructor. Destructs the SASTriangulator object. */ virtual ~SASTriangulator() throw(); //@} /** @name Accessors */ //@{ void run(int& progress) throw(); private: void triangulateFace(SASFace* face) throw(); void createPlanes (SASFace* face, std::list< std::pair,double> >& planes) throw(); void tagPoints (TriangulatedSurface& part, const std::list< std::pair,double> >& planes) throw(); void removeInsideTriangles(TriangulatedSurface& part) throw(); HashGrid3 createHashGrid(const TriangulatedSurface& part) throw(); void createPoints (TriangulatedSurface& part, const std::list< std::pair,double> >& planes, HashGrid3& grid) throw(); void createNewTriangles (TriangulatedSurface& part, HashGrid3& grid) throw(); void onePointOutside (Index outside, Triangle* t, TriangulatedSurface& part, HashGrid3& grid) throw(); void twoPointsOutside (Position outside1, Position outside2, Triangle* t, TriangulatedSurface& part, HashGrid3& grid) throw(); TrianglePoint* vertexExists (const TVector3& point, HashGrid3& grid) throw(); Size numberOfRefinements(const double& density, const double& radius) throw(); void buildTemplateSpheres() throw(); //@} protected: /** @name Attributes */ //@{ TriangulatedSAS* tsas_; double sqrt_density_; std::vector< std::list< TVector3 > > edge_; HashMap template_spheres_; //@} }; } // namespace BALL #endif // BALL_STRUCTURE_TRIANGULATEDSAS_H ugene-1.9.8/src/plugins_3rdparty/ball/src/include/BALL/STRUCTURE/RSVertex.h0000644000175000017500000001120111651544325024544 0ustar ilyailya// -*- Mode: C++; tab-width: 2; -*- // vi: set ts=2: // // $Id: RSVertex.h,v 1.33 2005-12-23 17:02:01 amoll Exp $ // #ifndef BALL_STRUCTURE_RSVERTEX_H #define BALL_STRUCTURE_RSVERTEX_H #ifndef BALL_STRUCTURE_GRAPHVERTEX_H # include #endif namespace BALL { class RSEdge; class RSFace; class ReducedSurface; class RSComputer; class SESEdge; class SESFace; class SESVertex; class SolventExcludedSurface; class SESComputer; class SESSingularityCleaner; class TriangulatedSES; class SESTriangulator; class SASEdge; class SASFace; class SASVertex; class SolventAccessibleSurface; class TriangulatedSAS; class SASTriangulator; /** Generic RSVertex Class. \ingroup Surface */ class BALL_EXPORT RSVertex : public GraphVertex< RSVertex,RSEdge,RSFace > { public: /** @name Class friends - class RSEdge - class RSFace - class ReducedSurface - class RSComputer - class SESEdge - class SESFace - class SESVertex - class SolventExcludedSurface - class SESComputer - class SESSingularityCleaner - class TriangulatedSES - class SESTriangulator - class SASEdge - class SASFace - class SASVertex - class SolventAccessibleSurface - class TriangulatedSAS - class SASTriangulator */ friend class RSEdge; friend class RSFace; friend class ReducedSurface; friend class RSComputer; friend class SESEdge; friend class SESFace; friend class SESVertex; friend class SolventExcludedSurface; friend class SESComputer; friend class SESSingularityCleaner; friend class TriangulatedSES; friend class SESTriangulator; friend class SASEdge; friend class SASFace; friend class SASVertex; friend class SolventAccessibleSurface; friend class TriangulatedSAS; friend class SASTriangulator; BALL_CREATE(RSVertex) /** @name Constructors and Destructors */ //@{ /** Default constructor. This method creates a new RSVertex object. */ RSVertex() throw(); /** Copy constructor. Create a new RSVertex object from another. @param rsvertex the RSVertex object to be copied @param deep if deep = false, all pointers are set to NULL (default). Otherwise the new RSVertex object is linked to the neighbours of the old RSVertex object. */ RSVertex(const RSVertex& rsvertex, bool deep = false) throw(); /** Detailled constructor. Create a new RSVertex object from an index. @param atom assigned to the index of the atom */ RSVertex(Index atom) throw(); /** Destructor. Destructs the RSVertex object. */ virtual ~RSVertex() throw(); //@} /** @name Assignment */ //@{ /** Assign from another RSVertex. @param rsvertex the RSVertex object to assign from @param deep if deep = false, all pointers are set to NULL (default). Otherwise the RSVertex object is linked to the neighbours of the RSVertex object to assign from. */ void set(const RSVertex& rsvertex, bool deep = false) throw(); /** Assign from another RSVertex. The RSVertex object is linked to the neighbours of the RSVertex object to assign from. @param rsvertex the RSVertex object to assign from */ RSVertex& operator = (const RSVertex& rsvertex) throw(); //@} /** @name Accessors */ //@{ /** Set the index of the atom represented by the vertex. @param atom the new index */ void setAtom(Index atom) throw(); /** Return the index of the atom represented by the vertex. @return Index the index of the atom represented by the vertex */ Index getAtom() const throw(); //@} /** @name Predicates */ //@{ /** Equality operator. @return bool true if the vertices are equal in all components, false otherwise */ virtual bool operator == (const RSVertex& rsvertex) const throw(); /** Inequality operator. @return bool false if the vertices are equal in all components, true otherwise */ virtual bool operator != (const RSVertex& rsvertex) const throw(); /** Similarity operator. @return bool true if the atoms are equal, false otherwise */ virtual bool operator *= (const RSVertex& rsvertex) const throw(); //@} protected: /*_ @name Attributes */ //@{ /*_ The index of the atom represented by the RSVertex */ Index atom_; //@} }; /** @name Storers */ //@{ /** Output- Operator prints out a rsvertex */ BALL_EXPORT std::ostream& operator << (std::ostream& s, const RSVertex& rsvertex); //@} } // namespace BALL #endif // BALL_STRUCTURE_RSVERTEX_H ugene-1.9.8/src/plugins_3rdparty/ball/src/include/BALL/STRUCTURE/SASEdge.h0000644000175000017500000001173611651544325024252 0ustar ilyailya// -*- Mode: C++; tab-width: 2; -*- // vi: set ts=2: // // $Id: SASEdge.h,v 1.9 2005-12-23 17:02:01 amoll Exp $ // #ifndef BALL_STRUCTURE_SASEDGE_H #define BALL_STRUCTURE_SASEDGE_H #ifndef BALL_STRUCTURE_GRAPHEDGE_H # include #endif #ifndef BALL_MATHS_ANGLE_H # include #endif #ifndef BALL_MATHS_CIRCLE3_H # include #endif namespace BALL { class SolventAccessibleSurface; class SASFace; class SASVertex; class RSEdge; class TriangulatedSAS; class SASTriangulator; /** Generic SASEdge Class. \ingroup Surface */ class BALL_EXPORT SASEdge : public GraphEdge< SASVertex,SASEdge,SASFace > { public: /** @name Class friends - class SASFace - class SASVertex - class SolventAccessibleSurface - class TriangulatedSAS - class SASTriangulator */ friend class SASVertex; friend class SASFace; friend class SolventAccessibleSurface; friend class TriangulatedSAS; friend class SASTriangulator; BALL_CREATE(SASEdge) /** @name Constructors and Destructors */ //@{ /** Default constructor. This method creates a new SASEdge object. */ SASEdge() throw(); /** Copy constructor. Create a new SASEdge object from another. @param sasedge the SASEdge object to be copied @param deep if deep = false, all pointers are set to NULL (default). Otherwise the new SASEdge object is linked to the neighbours of the old SASEdge object. */ SASEdge(const SASEdge& sasedge, bool deep = false) throw(); /** Detailled constructor. Create a new SASEdge object from some nice objects. @param vertex0 assigned to the first vertex @param vertex1 assigned to the second vertex @param face0 assigned to the first face @param face1 assigned to the second face @param circle assigned to the circle @param angle assigned to the angle @param index assigned to the index */ SASEdge(SASVertex* vertex0, SASVertex* vertex1, SASFace* face0, SASFace* face1, const TCircle3& circle, const TAngle& angle, Index index) throw(); /** Destructor. Destructs the SASEdge object. */ virtual ~SASEdge() throw(); //@} /** @name Assignment */ //@{ /** Assign from another SASEdge object. @param sasedge the SASEdge object to assign from @param deep if deep = false, all pointers are set to NULL (default). Otherwise the SASEdge object is linked to the neighbours of the SASEdge object to assign from. */ void set(const SASEdge& sasedge, bool deep = false) throw(); /** Assign from another SASEdge object. The SASEdge object is linked to the neighbours of the SASEdge object to assign from. @param sasedge the SASEdge object to assign from */ SASEdge& operator = (const SASEdge& sasedge) throw(); /** Assign from some nice objects. @param vertex0 assigned to the first vertex @param vertex1 assigned to the second vertex @param face0 assigned to the first face @param face1 assigned to the second face @param circle assigned to the circle @param angle assigned to the angle @param index assigned to the index */ void set(SASVertex* vertex0, SASVertex* vertex1, SASFace* face0, SASFace* face1, const TCircle3& circle, const TAngle& angle, Index index) throw(); //@} /** @name Accessors */ //@{ /** Set the circle on which the SASEdge lies. @param center the new circle */ void setCircle(const TCircle3& center) throw(); /** Return the circle on which the SASEdge lies. @return TCircle3 the circle of the SASEdge */ TCircle3 getCircle() const throw(); /** Set the angle of the SASEdge. @param angle the new angle */ void setAngle(const TAngle& angle) throw(); /** Return the angle of the SASEdge. @return TAngle the angle of the SASEdge */ TAngle getAngle() const throw(); //@} /** @name Predicates */ //@{ /** Equality operator. @return bool true */ virtual bool operator == (const SASEdge&) const throw(); /** Inequality operator. @return bool false */ virtual bool operator != (const SASEdge&) const throw(); /** Similarity operator. @return bool true */ virtual bool operator *= (const SASEdge&) const throw(); /** isFree. @return bool true if the RSEdge of the SASEdge is free, false otherwise */ bool isFree() const throw(); //@} protected: /*_ @name Attributes */ //@{ /*_ The circle on which the SASEdge lies. */ TCircle3 circle_; /*_ The angle of the SASEdge. */ TAngle angle_; //@} }; /** @name Storers */ //@{ /** Output- Operator */ BALL_EXPORT std::ostream& operator << (std::ostream& s, const SASEdge& sasedge); //@} } // namespace BALL #endif // BALL_STRUCTURE_SASEDGE_H ugene-1.9.8/src/plugins_3rdparty/ball/src/include/BALL/STRUCTURE/solventExcludedSurface.h0000644000175000017500000003245711651544326027524 0ustar ilyailya// -*- Mode: C++; tab-width: 2; -*- // vi: set ts=2: // // $Id: solventExcludedSurface.h,v 1.39 2005-12-23 17:02:05 amoll Exp $ // #ifndef BALL_STRUCTURE_SOLVENTEXCLUDEDSURFACE_H #define BALL_STRUCTURE_SOLVENTEXCLUDEDSURFACE_H #ifndef BALL_STRUCTURE_SESEDGE_H # include #endif #ifndef BALL_STRUCTURE_SESFACE_H # include #endif #ifndef BALL_STRUCTURE_SESVERTEX_H # include #endif #ifndef BALL_STRUCTURE_REDUCEDSURFACE_H # include #endif #ifndef BALL_MATHS_ANGLE_H # include #endif #ifndef BALL_MATHS_CIRCLE3_H # include #endif #ifndef BALL_MATHS_SPHERE3_H # include #endif #ifndef BALL_MATHS_VECTOR3_H # include #endif #ifndef BALL_MATHS_VECTOR4_H # include #endif #ifndef BALL_DATATYPE_HASHGRID_H # include #endif #ifndef BALL_DATATYPE_HASHMAP_H # include #endif #include #include namespace BALL { class SESComputer; class SESSingularityCleaner; class TriangulatedSES; class SESTriangulator; /** Generic SolventExcludedSurface Class. \ingroup Surface */ class BALL_EXPORT SolventExcludedSurface { public: /** @name Class friends - class SESComputer - class SESSingularityCleaner - class TriangulatedSES - class SESTriangulator */ friend class SESComputer; friend class SESSingularityCleaner; friend class TriangulatedSES; friend class SESTriangulator; BALL_CREATE(SolventExcludedSurface) /** @name Type definitions */ //@{ typedef std::vector::iterator VertexIterator; typedef std::vector::const_iterator ConstVertexIterator; typedef std::vector::iterator EdgeIterator; typedef std::vector::const_iterator ConstEdgeIterator; typedef std::list::iterator SingularEdgeIterator; typedef std::list::const_iterator ConstSingularEdgeIterator; typedef std::vector::iterator ContactFaceIterator; typedef std::vector::const_iterator ConstContactFaceIterator; typedef std::vector::iterator SphericFaceIterator; typedef std::vector::const_iterator ConstSphericFaceIterator; typedef std::vector::iterator ToricFaceIterator; typedef std::vector::const_iterator ConstToricFaceIterator; //@} /** @name Constructors and Destructors */ //@{ /** Default constructor. This method creates a new SolventExcludedSurface object. */ SolventExcludedSurface() throw(); /** Copy constructor. Create a new SolventExcludedSurface object from another. @param ses the SolventExcludedSurface object to be copied @param bool ignored - just for interface consistency */ SolventExcludedSurface (const SolventExcludedSurface& ses, bool = false) throw(); /** Detailed constructor */ SolventExcludedSurface(ReducedSurface* reduced_surface) throw(); /** Destructor. As there are no dynamic data structures, nothing happens. */ virtual ~SolventExcludedSurface() throw(); //@} /** @name Accessors */ //@{ void clear(); void clean(const double& density); /** Computes the solvent excluded surface from a ReducedSurface object */ void compute() throw(Exception::GeneralException); void splitSphericFaces() throw(); bool check() throw(); //@} /** @name External Iterators */ //@{ VertexIterator beginVertex() throw(); ConstVertexIterator beginVertex() const throw(); VertexIterator endVertex() throw(); ConstVertexIterator endVertex() const throw(); EdgeIterator beginEdge() throw(); ConstEdgeIterator beginEdge() const throw(); EdgeIterator endEdge() throw(); ConstEdgeIterator endEdge() const throw(); SingularEdgeIterator beginSingularEdge() throw(); ConstSingularEdgeIterator beginSingularEdge() const throw(); SingularEdgeIterator endSingularEdge() throw(); ConstSingularEdgeIterator endSingularEdge() const throw(); ContactFaceIterator beginContactFace() throw(); ConstContactFaceIterator beginContactFace() const throw(); ContactFaceIterator endContactFace() throw(); ConstContactFaceIterator endContactFace() const throw(); SphericFaceIterator beginSphericFace() throw(); ConstSphericFaceIterator beginSphericFace() const throw(); SphericFaceIterator endSphericFace() throw(); ConstSphericFaceIterator endSphericFace() const throw(); ToricFaceIterator beginToricFace() throw(); ConstToricFaceIterator beginToricFace() const throw(); ToricFaceIterator endToricFace() throw(); ConstToricFaceIterator endToricFace() const throw(); //@} private: void splitSphericFace(Position i) throw(); void deleteSmallToricFace(SESFace* face) throw(); void deleteSmallSingularToricFace(SESFace* face) throw(); bool cleanToricFace(SESFace* face, const double& sqrt_density) throw(); bool cleanSingularToricFace(SESFace* face, const double& sqrt_density) throw(); void cleanVertices() throw(); void cleanEdges() throw(); void cleanContactFaces() throw(); void cleanToricFaces() throw(); void cleanSphericFaces() throw(); protected: /*_ the number of vertices of the solvent exluded surface */ Position number_of_vertices_; /*_ the vertices of the solvent exluded surface */ ::std::vector vertices_; /*_ the number of edges of the solvent exluded surface */ Position number_of_edges_; /*_ the edges of the solvent exluded surface */ ::std::vector edges_; /*_ the number of singular edges of the solvent exluded surface */ Position number_of_singular_edges_; /*_ the singular edges of the solvent exluded surface */ ::std::list singular_edges_; /*_ the number of contact faces of the solvent exluded surface */ Position number_of_contact_faces_; /*_ the contact faces of the solvent exluded surface */ ::std::vector contact_faces_; /*_ the number of toric reentrant faces of the solvent exluded surface */ Position number_of_toric_faces_; /*_ the toric reentrant faces of the solvent exluded surface */ ::std::vector toric_faces_; /*_ the number of spheric reentrant faces of the solvent exluded surface */ Position number_of_spheric_faces_; /*_ the spheric reentrant faces of the solvent exluded surface */ ::std::vector spheric_faces_; /*_ the corresponding reduced surface */ ReducedSurface* reduced_surface_; }; /** @name Storers */ //@{ /** Output- Operator */ BALL_EXPORT std::ostream& operator << (std::ostream& s, const SolventExcludedSurface& ses); //@} /** Generic SESComputer Class. \ingroup Surface */ class BALL_EXPORT SESComputer { public: BALL_CREATE(SESComputer) /** @name Constructors and Destructors */ //@{ /** Default constructor. This method creates a new SESComputer object. */ SESComputer() throw(); /** Detailed constructor */ SESComputer(SolventExcludedSurface* ses) throw(); /** Destructor. As there are no dynamic data structures, nothing happens. */ virtual ~SESComputer() throw(); //@} /** @name Accessors */ //@{ /** Computes the solvent excluded surface */ void run() throw(Exception::GeneralException); //@} private: /*_ @name SES computation (private) */ //@{ void preProcessing() throw(); void get() throw(); void createSphericFace(Position j) throw(); SESVertex* createVertex (const TVector3& probe_center, Index index) throw(); void pushVertex (SESFace* face, const TSphere3& probe, RSVertex* rsvertex) throw(); SESEdge* createConcaveEdge (SESFace* spheric_face, Position p1, Position p2, Index index, const double& radius_of_probe) throw(); void pushConcaveEdge (SESFace* face, Position p1, Position p2, const double& radius_of_probe) throw(); SESEdge* createConvexEdge (SESFace* toric_face, RSVertex* rsvertex) throw(); void createToricFace(Position i) throw(); void treatSingularToricFace(Position i) throw(); void createFreeToricFace(Position i) throw(); SESVertex* createSingularVertex (Position ip, const TVector3& dir, SESFace* face0, SESFace* face1, SESFace* face2, SESEdge* edge0, SESEdge* edge1, SESEdge* edge2) throw(); void updateEdge (SESEdge* edge, SESVertex* vertex1, SESVertex* vertex2, bool is_new) throw(); void getPoint (const TVector3& p1, const TVector3& p2, const double& dist, TVector3& result) throw(); Index vertexExists(const TVector3& point) throw(); //@} protected: /*_ a pointer to the solvent excluded surface to compute */ SolventExcludedSurface* ses_; /*_ a HashGrid to store and find the vertices in an efficient way */ HashGrid3 vertex_grid_; }; /** Generic SESComputer Class. \ingroup Surface */ class BALL_EXPORT SESSingularityCleaner { public: BALL_CREATE(SESSingularityCleaner) typedef std::pair< std::pair,Index>,TVector3 > Intersection; struct ProbeIntersection { TVector3 point[2]; }; friend class SESComputer; /** @name Constructors and Destructors */ //@{ /** Default constructor. This method creates a new SESComputer object. */ SESSingularityCleaner() throw(); /** Detailed constructor */ SESSingularityCleaner (SolventExcludedSurface* ses, HashGrid3* vertex_grid_) throw(); /** Destructor. As there are no dynamic data structures, nothing happens. */ virtual ~SESSingularityCleaner() throw(); //@} /** @name Accessors */ //@{ /** Solves the singularities */ bool run() throw(Exception::GeneralException); //@} private: /** @name Treatment of singularities (private) */ //@{ Index vertexExists(TVector3 point) throw(); void treatSingularities() throw(); void getSingularFaces(std::list& faces) throw(); bool treatFirstCategory() throw(); void treatSecondCategory() throw(); void getFirstCategoryFaces(std::list& first_category_faces) throw(); void noCut(SESFace* face1, SESFace* face2) throw(); void twoCuts(SESFace* face1, SESFace* face2) throw(); void treatSingularEdge (SESEdge* edge, HashGrid3& grid, ::std::list& deletable_edges) throw(); void getIntersectionsOfSingularEdge (SESEdge* edge, const TAngle& phi, HashGrid3& grid, std::list& intersections) throw(); bool getIntersectionPointsAndAngles (const TCircle3& circle, const TVector3& point, Position index1, Position index2, Position probe_index, TAngle& phi1, TVector3& point1, TAngle& phi2, TVector3& point2) throw(); bool isIntersection (const TAngle& min_phi, const TAngle& max_phi, const TAngle& phi, const TVector3& middle, const TSphere3& probe) throw(); void buildEndEdges (SESEdge* edge, const std::list& min, const std::list& max, SESVertex*& vertex1, SESVertex*& vertex2, Index& actual_min, Index& actual_max) throw(); void buildEdge (SESEdge* edge, Index face1, Index& face2, Index end, SESVertex*& vertex, const HashSet& indices, bool minimum) throw(); void getExtrema (const std::list& intersections, std::list& min, std::list& max) throw(); void buildEndEdge (SESEdge* edge, const std::list& extrema, SESVertex*& vertex, Index& actual_extremum, bool min) throw(); bool probeIntersection (Index face1, Index face2, Index face3, TVector3& point1, TVector3& point2) throw(); void sort (SESFace* face1, SESFace* face2, std::vector& sesedge1, std::vector& sesedge2, std::vector& sesvertex1, std::vector& sesvertex2) throw(); void sort (Index u1, Index u2, Index u3, Index& s1, Index& s2, Index& s3) throw(); //@} protected: /*_ a pointer to the solvent excluded surface to compute */ SolventExcludedSurface* ses_; /*_ a pointer to a HashGrid to store and find the vertices in an efficient way */ HashGrid3* vertex_grid_; /*_ for each triple of probe spheres its intersections */ HashMap< Position, HashMap< Position, HashMap< Position, ProbeIntersection* > > > probe_intersections_; }; } // namespace BALL #endif // BALL_STRUCTURE_SOLVENTEXCLUDEDSURFACE_H ugene-1.9.8/src/plugins_3rdparty/ball/src/include/BALL/STRUCTURE/SASFace.h0000644000175000017500000000755111651544325024244 0ustar ilyailya// -*- Mode: C++; tab-width: 2; -*- // vi: set ts=2: // // $Id: SASFace.h,v 1.9 2005-12-23 17:02:02 amoll Exp $ // #ifndef BALL_STRUCTURE_SASFACE_H #define BALL_STRUCTURE_SASFACE_H #ifndef BALL_STRUCTURE_GRAPHFACE_H # include #endif #ifndef BALL_STRUCTURE_SPHERE3_H # include #endif #include namespace BALL { class SolventAccessibleSurface; class SASEdge; class SASVertex; class TriangulatedSAS; class SASTriangulator; /** Generic SASFace Class. \ingroup Surface */ class BALL_EXPORT SASFace : public GraphFace< SASVertex,SASEdge,SASFace > { public: /** @name Class friends - class SASEdge - class SASVertex - class SolventAccessibleSurface - class TriangulatedSAS - class SASTriangulator */ friend class SASEdge; friend class SASVertex; friend class SolventAccessibleSurface; friend class TriangulatedSAS; friend class SASTriangulator; BALL_CREATE(SASFace) /** @name Type definitions */ //@{ typedef std::list::iterator OrientationIterator; typedef std::list::const_iterator ConstOrientationIterator; //@} /** @name Constructors and Destructors */ //@{ /** Default constructor. This method creates a new SASFace object. */ SASFace() throw(); /** Copy constructor. Create a new SASFace object from another. @param sasface the SASFace object to be copied @param deep if deep = false, all pointers are set to NULL (default). Otherwise the new SASFace object is linked to the neighbours of the old SASFace object. */ SASFace(const SASFace& sasface, bool deep = false) throw(); /** Destructor. Destructs the SASFace object. */ virtual ~SASFace() throw(); //@} /** @name Assignments */ //@{ /** Assign from another SASFace. @param sasface the SASFace object to assign from @param deep if deep = false, all pointers are set to NULL (default). Otherwise the new SASFace object is linked to the neighbours of the SASFace object to assign from. */ void set(const SASFace& sasface, bool deep = false) throw(); /** Assign from another SASFace. The new SASFace object is linked to the neighbours of the SASFace object to assign from. @param sasface the SASFace object to assign from */ SASFace& operator = (const SASFace& sasface) throw(); //@} /** @name Accessors */ //@{ /** Set the sphere the GraphFace lies on. @param sphere the new sphere */ void setSphere(const TSphere3& sphere) throw(); /** Return the sphere the GraphFace lies on. @return TSphere the sphere the GraphFace lies on */ TSphere3 getSphere() const throw(); //@} /** @name Predicates */ //@{ /** Equality operator. @return bool true */ virtual bool operator == (const SASFace&) const throw(); /** Inequality operator. @return bool false */ virtual bool operator != (const SASFace&) const throw(); /** Similarity operator. @return bool true */ virtual bool operator *= (const SASFace&) const throw(); //@} /** @name External Iterators */ //@{ OrientationIterator beginOrientation() throw(); ConstOrientationIterator beginOrientation() const throw(); OrientationIterator endOrientation() throw(); ConstOrientationIterator endOrientation() const throw(); //@} protected: /** @name Attributes */ //@{ /*_ A list of booleans to indicate the orientation of each sasedge. */ std::list orientation_; /*_ The sphere on which the face lies. */ TSphere3 sphere_; //@} }; /** @name Storers */ //@{ /** Output- Operator */ BALL_EXPORT std::ostream& operator << (std::ostream& s, const SASFace& sasface); //@} } // namespace BALL #endif // BALL_STRUCTURE_SASFACE_H ugene-1.9.8/src/plugins_3rdparty/ball/src/include/BALL/DATATYPE/0000755000175000017500000000000011651544310022463 5ustar ilyailyaugene-1.9.8/src/plugins_3rdparty/ball/src/include/BALL/DATATYPE/string.h0000644000175000017500000010732611651544325024161 0ustar ilyailya// -*- Mode: C++; tab-width: 2; -*- // vi: set ts=2: // // $Id: string.h,v 1.56 2005-12-23 17:01:43 amoll Exp $ // #ifndef BALL_DATATYPE_STRING_H #define BALL_DATATYPE_STRING_H #ifndef BALL_CONFIG_CONFIG_H # include #endif #ifndef BALL_COMMON_GLOBAL_H # include #endif #ifndef BALL_COMMON_CREATE_H # include #endif #ifndef BALL_COMMON_MACROS_H # include #endif #ifndef BALL_COMMON_EXCEPTION_H # include #endif #ifndef BALL_COMMON_DEBUG_H # include #endif #include #include #include #include #include #include #include #ifdef BALL_HAS_SSTREAM # include #else # include #endif using std::string; namespace BALL { // forward declaration class Substring; /** \defgroup String String An improved version of STL string. \ingroup DatatypeMiscellaneous */ //@{ /** Extended String class. \ingroup String */ class BALL_EXPORT String : public string { /// friend class Substring; public: // String has no copy constructor taking String&, bool as arguments. // the compiler would confuse it with another copy constructor, // cast true to 1 and copy only the string from the second character // on! We could use BALL_CREATE_NODEEP, but this leads to trouble with // inline constructors, so we code it by hand (here and in string.C) virtual void* create(bool /* deep */ = true, bool empty = false) const throw(); /** @name Enums and Constants */ //@{ /** Constants to set the compare mode. Use one of these constants to set the mode you need. These modes affect all \link compare compare \endlink methods. As these methods are also used in the implementation of comparison operators, all comparison operations will get affected from a change. \par You may change the comparison mode by invoking setCompareMode. \par */ enum CompareMode { /// Constant to set to case sensitive comparisons (default) CASE_SENSITIVE = 0, /// Constant to set to case insensitive comparisons CASE_INSENSITIVE = 1 }; /** Constant indicating the end of the string. Use this constant instead of string::npos to indicate an invalid position inside the string or the end of the string in those methods requiring indices. */ static const Size EndPos; //@} /** @name Predefined character classes There exist several predefined character classes, that may be used in several functions (e.g. trim methods) to represent a set of characters. */ //@{ /// Character class containing all letters (lower and upper case) static const char* CHARACTER_CLASS__ASCII_ALPHA; /// Character class containing all letters and digits static const char* CHARACTER_CLASS__ASCII_ALPHANUMERIC; /// Character class containing all lower case letters static const char* CHARACTER_CLASS__ASCII_LOWER; /// Character class containing all upper case letters static const char* CHARACTER_CLASS__ASCII_UPPER; /// Character class containing the digits from 0 to 9 static const char* CHARACTER_CLASS__ASCII_NUMERIC; /// Character class containing the digits from 0 to 9 and a dot static const char* CHARACTER_CLASS__ASCII_FLOAT; /** Character class containing all whitespace characters. Whitespace characters are: \par - blank " " - horizontal tab $ "\backslash t" $ - new-line $ "\backslash n" $ - line-feed $ "\backslash r" $ - vertical tab $ "\backslash v" $ - form-feed $ "\backslash f" $ */ static const char* CHARACTER_CLASS__WHITESPACE; /** Character class containing double quotes. */ static const char* CHARACTER_CLASS__QUOTES; //@} /** @name Constructors and Destructors */ //@{ /// Default Constructor String() throw(); /// Copy constructor String(const String& string) throw(); /// STL string copy constructor String(const string& string) throw(); /** Creates a new string from a given range of another string. @see String:Indices @exception Exception::IndexUnderflow if from < 0 @exception Exception::IndexOverflow if from >= size() */ String(const String& s, Index from, Size len = EndPos) throw(Exception::IndexUnderflow, Exception::IndexOverflow); /** Creates a new string from a C type string. The new string contains the contents of s until it has reached a length of len or contains a zero character (whichever comes first). Default value for len is EndPos, meaning as long as possible. */ String(const char* char_ptr, Index from = 0, Size len = EndPos) throw(Exception::NullPointer, Exception::IndexUnderflow, Exception::IndexOverflow); /** Creates a string using sprintf. This constructor creates a new string and sets its content to the result of a call to sprintf using format as a format string and all additional parameters as arguments. \par The result of the sprintf call is intermediately written to a buffer of a maximum size of buffer_size characters, so choose an appropriate size for this variables. \par @exception IndexUnderflow, if the buffer size specified is not larger than 0 @exception NullPointer, if format == 0 */ String(Size buffer_size, const char* format, ... ) throw(Exception::IndexUnderflow, Exception::NullPointer); /** Create a new string from the contents of a stringstream. The contents of the stringstream are not modified, i.e. successive construction of multiple strings from the same stringstream object leads to identical copies. */ #ifdef BALL_HAS_SSTREAM String(std::stringstream& s) throw(); #else String(std::strstream& s) throw(); #endif /** Creates a new string from len copies of c. */ String(const char c, Size len = 1) throw(); /// Creates a string just containing an unsigned character String(const unsigned char uc) throw(); /// Construct a String from a short String(short s) throw(); /// Construct a String from an unsigned short String(unsigned short us) throw(); /// Construct a String from an int String(int i) throw(); /// Construct a String from an unsigned int String(unsigned int ui) throw(); /// Construct a String from a long String(long l) throw(); /// Construct a String from an unsigned long String(unsigned long) throw(); /// Construct a String from a float value String(float f) throw(); /// Construct a String from a double value String(double d) throw(); /// Destructor virtual ~String() throw(); /// Clear the string (reset to the empty string) void destroy() throw(); /// Clears the string (same as destroy) virtual void clear() throw(); //@} /** @name Assignment methods */ //@{ /** Assign a string */ void set(const String& s); /** Assign a String from a range of another string @exception Exception::IndexOverflow if from < 0 @exception Exception::IndexUnderflow if from >= size() */ void set(const String& string, Index from, Size len = EndPos) throw(Exception::IndexUnderflow, Exception::IndexOverflow); /** Assign a String from a C type string @exception Exception::IndexUnderflow if from < 0 @exception Exception::IndexOverflow if from >= size() */ void set(const char* char_ptr, Index from = 0, Size len = EndPos) throw(Exception::NullPointer, Exception::IndexUnderflow, Exception::IndexOverflow); /** Assign a string to the result of a sprintf call @exception Exception::IndexUnderflow, if the buffer size is zero @exception Exception::NullPointer, format is a NULL pointer */ void set(Size buffer_size, const char *format, ...) throw(Exception::IndexUnderflow, Exception::NullPointer); /** Assign a String from a stringstream. The contents of the stringstream object are not modified. */ #ifdef BALL_HAS_SSTREAM void set(std::stringstream& s) throw(); #else void set(std::strstream& s) throw(); #endif /// Assign a String from the result of repeating c len times void set(char c, Size len = 1) throw(); /// Assign a String from an unsigned char void set(unsigned char uc) throw(); /// Assign a String from a short void set(short s) throw(); /// Assign a String from an unsigned short void set(unsigned short us) throw(); /// Assign a String from an int void set(int i) throw(); /// Assign a String from an unsigned int void set(unsigned int ui) throw(); /// Assign a String from a long void set(long l) throw(); /// Assign a String from an unsigned long void set(unsigned long ul) throw(); /// Assign a String from a float value void set(float f) throw(); /// Assign a String from a double value void set(double d) throw(); /// Assign to a C type string void get(char* char_ptr, Index from = 0, Size len = EndPos) const throw(Exception::NullPointer, Exception::IndexUnderflow, Exception::IndexOverflow); /// Assign a String from another String const String& operator = (const String& s) throw(); /// Assign a String from a C type string const String& operator = (const char* pc) throw(Exception::NullPointer); /** Assign a string from a stringstream. The contents of the stringstream object are not modified. */ #ifdef BALL_HAS_SSTREAM const String& operator = (std::stringstream& s) throw(); #else const String& operator = (std::strstream& s) throw(); #endif /// Assign a String from a single char const String& operator = (char c) throw(); /// Assign a String from an unsigned char const String& operator = (unsigned char uc) throw(); /// Assign a String from a short const String& operator = (short s) throw(); /// Assign a String from an unsigned short const String& operator = (unsigned short us) throw(); /// Assign a String from an int const String& operator = (int i) throw(); /// Assign a String from an unsigned int const String& operator = (unsigned int ui) throw(); /// Assign a String from a long const String& operator = (long l) throw(); /// Assign a String from an unsigned long const String& operator = (unsigned long ul) throw(); /// Assign a String from a float const String& operator = (float f) throw(); /// Assign a String from a double const String& operator = (double d) throw(); //@} /** @name Compare mode-related methods. All string comparisons can be made case-sensitive or case insensitive. The behavior can be toggled globally for all strings. */ //@{ /// Set the compareison mode for all string comparisons static void setCompareMode(CompareMode compare_mode) throw(); /// Return the current comparison mode static CompareMode getCompareMode() throw(); //@} /** @name Converters */ //@{ /** Converts the string to a bool value. This method returns false, if the string contains the string false (may be surrounded by whitespaces), or true otherwise. */ bool toBool() const throw(); /// Return the first character of the string char toChar() const throw(); /// Return the first character of the string converted to an unsigned char unsigned char toUnsignedChar() const throw(); /// Convert the string to a short short toShort() const throw(Exception::InvalidFormat); /// Convert the string to an unsigned short unsigned short toUnsignedShort() const throw(Exception::InvalidFormat); /// Convert the string to an int int toInt() const throw(Exception::InvalidFormat); /// Convert the string to an unsigned int unsigned int toUnsignedInt() const throw(Exception::InvalidFormat); /// Convert the string to a long long toLong() const throw(Exception::InvalidFormat); /// Convert the string to an unsigned long unsigned long toUnsignedLong() const throw(Exception::InvalidFormat); /// Convert the string to a float float toFloat() const throw(Exception::InvalidFormat); /// Convert the string to a double double toDouble() const throw(Exception::InvalidFormat); //@} /** @name Case Conversion */ //@{ /// Convert all characters in the given range to lower case void toLower(Index from = 0, Size len = EndPos) throw(Exception::IndexUnderflow, Exception::IndexOverflow); /// Convert all characters in the given range to upper case void toUpper(Index from = 0, Size len = EndPos) throw(Exception::IndexUnderflow, Exception::IndexOverflow); //@} /** @name Substring Definition */ //@{ /// Return a substring Substring getSubstring(Index from = 0, Size len = EndPos) const throw(Exception::IndexUnderflow, Exception::IndexOverflow); /// Return a substring Substring operator () (Index from, Size len = EndPos) const throw(Exception::IndexUnderflow, Exception::IndexOverflow); /** Return a substring containing the string before the first occurence of s */ Substring before(const String& s, Index from = 0) const throw(); /** Return a substring containing the beginning of the string including the first occurence of s */ Substring through(const String& s, Index from = 0) const throw(); /** Return a substring containing the string from the first occurence of s on */ Substring from(const String& s, Index from = 0) const throw(); /** Return a substring containing the string after the first occurence of s. */ Substring after(const String& s, Index from = 0) const throw(); //@} /** @name AWK style field operations */ //@{ /// Count the fields that are separated by a defined set of delimiters Size countFields(const char* delimiters = CHARACTER_CLASS__WHITESPACE) const throw(Exception::NullPointer); /// Count the fields and respect quote characters. Size countFieldsQuoted(const char* delimiters = CHARACTER_CLASS__WHITESPACE, const char* quotes = CHARACTER_CLASS__QUOTES) const throw(Exception::NullPointer); /// Return a given field as a substring String getField(Index index, const char* delimiters = CHARACTER_CLASS__WHITESPACE, Index* from = 0) const throw(Exception::IndexUnderflow, Exception::NullPointer); /// Return a given field and respect quote characters. String getFieldQuoted(Index index, const char* delimiters = CHARACTER_CLASS__WHITESPACE, const char* quotes = CHARACTER_CLASS__QUOTES, Index* from = 0) const throw(Exception::IndexUnderflow, Exception::NullPointer); /** Split the string into fields and assign these field to an array of strings */ Size split(String string_array[], Size array_size, const char* delimiters = CHARACTER_CLASS__WHITESPACE, Index from = 0) const throw(Exception::IndexUnderflow, Exception::NullPointer); /** Split the string into fields and assign these field to a vector of strings. The vector of strings is cleared in any case. Its final size is returned. @exception IndexOverflow if from < 0 @exception NullPointer if delimiters == 0 */ Size split(std::vector& strings, const char* delimiters = CHARACTER_CLASS__WHITESPACE, Index from = 0) const throw(Exception::IndexUnderflow, Exception::NullPointer); /** Split the string into fields and respect quote characters. Similar to \link split split \endlink , but delimiters that are inside quote characters (default is \link CHARACTER_CLASS__QUOTES CHARACTER_CLASS__QUOTES \endlink ) are not considered to split the string. The vector of strings is cleared in any case. Its final size is returned. @exception IndexOverflow if from < 0 @exception NullPointer if delimiters == 0 */ Size splitQuoted(std::vector& strings, const char* delimiters = CHARACTER_CLASS__WHITESPACE, const char* quotes = CHARACTER_CLASS__QUOTES, Index from = 0) const throw(Exception::IndexUnderflow, Exception::NullPointer); //@} /** @name BASIC style string operations */ //@{ /** Strips all characters in trimmed from the left of the string. trimLeft stops at the first character encountered that is not in trimmed. Using its default parameter CHARACTER_CLASS__WHITESPACE, it is usually handy to remove blanks from the beginning of a string. Strings consisting of character from trimmed only yield an empty string. */ String& trimLeft(const char* trimmed = CHARACTER_CLASS__WHITESPACE) throw(); /** Strips all characters in trimmed from the right of the string. trimRight stops at the first character encountered that is not in trimmed. Using its default parameter CHARACTER_CLASS__WHITESPACE, it is usually handy to remove blanks from the end of a string. Strings consisting of character from trimmed only yield an empty string. */ String& trimRight(const char* trimmed = CHARACTER_CLASS__WHITESPACE) throw(); /** Strips all characters in trimmed from both sides of the string. trim calls trimRight(trimmed).trimLeft(trimmed). */ String& trim(const char* trimmed = CHARACTER_CLASS__WHITESPACE) throw(); // ????? /** Strips all characters in trimmed from both sides of the string. trim calls trimRight(trimmed).trimLeft(trimmed). */ String trim(const char* trimmed = CHARACTER_CLASS__WHITESPACE) const throw(); /// Truncate the string to length size String& truncate(Size size) throw(); /// Return a substring containing the len leftmost characters of the string Substring left(Size len) const throw(); /// Return a substring containing the len rightmost characters of the string Substring right(Size len) const throw(); /** Return a substring containing the first occurence of pattern in the string. If the pattern is not contained in the string, an empty Substring is returned. The search for the pattern may also start from an index different from zero, allowing incremental search. @return Substring containing the search pattern, empty if not found @param pattern the search pattern @param from the index in the string to start the search from */ Substring instr(const String& pattern, Index from = 0) const throw(); //@} /** @name String Operations */ //@{ /// Concatenates two strings String operator + (const string& string) const throw(); /// Concatenates a string and a C type string String operator + (const char* char_ptr) const throw(); /// Concatenates a string and a character String operator + (char c) const throw(); /// Concatenates a C type string and a string BALL_EXPORT friend String operator + (const char* char_ptr, const String& s) throw(); /// Concatenates a character and a string BALL_EXPORT friend String operator + (char c, const String& s) throw(); /// Swaps the contents with another String void swap(String& s) throw(); /** Reverses the string. If called without arguments, this method simply reverses the character sequence of the string. By giving arguments for the indices, only a subsequence of the string may be reversed. @param from first index of the sequence to be reversed @param to last index of the sequence to be reversed @see String:Indices */ String& reverse(Index from = 0, Size len = EndPos) throw(Exception::IndexUnderflow, Exception::IndexOverflow); /** Substitute the first occurence of to_replace by the content of replacing. @return the first position of the substitution or \link EndPos EndPos \endlink if to_replace is not found */ Size substitute(const String& to_replace, const String& replacing) throw(); //@} /** @name Predicates */ //@{ /// True, if the string contains character c bool has(char c) const throw(); /// True, if the string contains the substring s after index from bool hasSubstring(const String& s, Index from = 0) const throw(); /// True, if the string starts with s bool hasPrefix(const String& s) const throw(); /// True, if the string ends with s bool hasSuffix(const String& s) const throw(); /// True, if the string has size 0 bool isEmpty() const throw(); /** True, if the string only contains letters (any case). It returns also true, if called for an empty string. */ bool isAlpha() const throw(); /** True, if the string only contains letters and digits. It returns also true, if called for an empty string. */ bool isAlnum() const throw(); /** True, if the string only contains digits. It returns also true, if called for an empty string. */ bool isDigit() const throw(); /** True, if the string is a floating number. (It contains only numbers and maybe a dot). It returns also true, if called for an empty string. */ bool isFloat() const throw(); /** True, if the string only contains spaces. It returns also true, if called for an empty string. */ bool isSpace() const throw(); /** True, if the string only contains whitespace characters. Whitespaces are defined in CHARACTER_CLASS__WHITESPACE. It returns also true, if called for an empty string. */ bool isWhitespace() const throw(); /// True, if the character is a letter (any case) static bool isAlpha(char c) throw(); /// True, if the character is a letter or a digit static bool isAlnum(char c) throw(); /// True, if the character is a digit static bool isDigit(char c) throw(); /// True, if the character is a space static bool isSpace(char c) throw(); /** True, if the character is any whitespace character. Whitespaces are defined in CHARACTER_CLASS__WHITESPACE */ static bool isWhitespace(char c) throw(); //@} /** @name Base64 String methods */ //@{ /// Convert a string to a base 64 string String encodeBase64() throw(); /** Decode a base 64 string. Return an empty string, if base64 string is not right encoded. */ String decodeBase64() throw(); //@} /** @name Comparators */ //@{ /// int compare(const String& string, Index from = 0) const throw(Exception::IndexUnderflow, Exception::IndexOverflow); /// int compare(const String& string, Index from, Size len) const throw(Exception::IndexUnderflow, Exception::IndexOverflow); /// int compare(const char* char_ptr, Index from = 0) const throw(Exception::NullPointer, Exception::IndexUnderflow, Exception::IndexOverflow); /// int compare(const char* char_ptr, Index from, Size len) const throw(Exception::NullPointer, Exception::IndexUnderflow, Exception::IndexOverflow); /// int compare(char c, Index from = 0) const throw(Exception::IndexUnderflow, Exception::IndexOverflow); /// bool operator == (const String& string) const throw(); /// bool operator != (const String& string) const throw(); /// bool operator < (const String& string) const throw(); /// bool operator <= (const String& string) const throw(); /// bool operator >= (const String& string) const throw(); /// bool operator > (const String& string) const throw(); /// BALL_EXPORT friend bool operator == (const char* char_ptr, const String& string) throw(Exception::NullPointer); /// BALL_EXPORT friend bool operator != (const char* char_ptr, const String& string) throw(Exception::NullPointer); /// BALL_EXPORT friend bool operator < (const char* char_ptr, const String& string) throw(Exception::NullPointer); /// BALL_EXPORT friend bool operator <= (const char* char_ptr, const String& string) throw(Exception::NullPointer); /// BALL_EXPORT friend bool operator > (const char* char_ptr, const String& string) throw(Exception::NullPointer); /// BALL_EXPORT friend bool operator >= (const char* char_ptr, const String& string) throw(Exception::NullPointer); /// bool operator == (const char* char_ptr) const throw(Exception::NullPointer); /// bool operator != (const char* char_ptr) const throw(Exception::NullPointer); /// bool operator < (const char* char_ptr) const throw(Exception::NullPointer); /// bool operator <= (const char* char_ptr) const throw(Exception::NullPointer); /// bool operator > (const char* char_ptr) const throw(Exception::NullPointer); /// bool operator >= (const char* char_ptr) const throw(Exception::NullPointer); /// BALL_EXPORT friend bool operator == (char c, const String& string) throw(); /// BALL_EXPORT friend bool operator != (char c, const String& string) throw(); /// BALL_EXPORT friend bool operator < (char c, const String& string) throw(); /// BALL_EXPORT friend bool operator <= (char c, const String& string) throw(); /// BALL_EXPORT friend bool operator > (char c, const String& string) throw(); /// friend bool operator >= (char c, const String& string) throw(); /// bool operator == (char c) const throw(); /// bool operator != (char c) const throw(); /// bool operator < (char c) const throw(); /// bool operator <= (char c) const throw(); /// bool operator > (char c) const throw(); /// bool operator >= (char c) const throw(); //@} /** @name Debugging and Diagnostics */ //@{ /// bool isValid() const throw(); /// void dump(std::ostream& s = std::cout, Size depth = 0) const throw(); //@} /** @name Stream Operations */ //@{ /// std::istream& getline(std::istream& s = std::cin, char delimiter = '\n') throw(); /// friend std::istream& getline(std::istream& s, String& string, char delimiter = '\n') throw(); //@} /// Constant empty string. static const String EMPTY; protected: // the validate... methods check perform a thorough // index checking and an index translation // Indices below zero are interpreted as indices // relative to the end of the string // All methods throw IndexUnder|Overflow exceptions // void validateIndex_(Index& index) const throw(Exception::IndexUnderflow, Exception::IndexOverflow); void validateRange_(Index& from, Size& len) const throw(Exception::IndexUnderflow, Exception::IndexOverflow); static void validateCharPtrRange_(Index& from, Size& len, const char* char_ptr) throw(Exception::NullPointer, Exception::IndexUnderflow, Exception::IndexOverflow); static void valudateCharPtrIndex_(Index& index) throw(); private: static int compareAscendingly_(const char* a, const char* b) throw(); static int compareDescendingly_(const char* a, const char* b) throw(); static CompareMode compare_mode_; static char B64Chars_[64]; static int Index_64_[128]; }; /** A substring class. The Substring class represents an efficient way to deal with substrings of \link String String \endlink . Each Substring is bound to an instance of String and is defined by a start and end index. It can be used like a String (with several restrictions) but only affects the given range of the string it is bount to. \par \ingroup String */ class BALL_EXPORT Substring { friend class String; public: BALL_CREATE_DEEP(Substring) /** @name Exceptions */ //@{ /** Exception thrown if an unbound substring is accessed. This exception is thrown by most accessors and predicates of Substring if the substring is not bound to a string. */ class BALL_EXPORT UnboundSubstring : public Exception::GeneralException { public: UnboundSubstring(const char* file, int line); }; /** Exception thrown if an invalid substring is accessed. This exception is thrown if an invalid substring is to be used. @see isValid */ class BALL_EXPORT InvalidSubstring : public Exception::GeneralException { public: InvalidSubstring(const char* file, int line); }; //@} /** @name Constructors and Destructors */ //@{ /** Default constructor. Create an empty string. */ Substring() throw(); /** Copy constructor. Create a substring from another substring. @param substring the substring to be copied @param deep ignored */ Substring(const Substring& substring, bool deep = true) throw(); /** Create a substring from a string and two indices. @param string the string the substring is bound to. @param from the start index of the substring @param len the length of the substring (default EndPos: to the end of the string) */ Substring(const String& string, Index from = 0, Size len = String::EndPos) throw(Exception::IndexUnderflow, Exception::IndexOverflow); /** Destructor. Destruct the substring. */ virtual ~Substring() throw(); /** Clear the substrings contents. Unbind the substring from its string and set the start and the end position to 0. */ void destroy() throw(); /** Clear the substrings contents. Unbind the substring from its string and set the start and the end position to 0. */ virtual void clear() throw(); //@} /** @name Converters */ //@{ /** Convert a substring to a string. Return a copy of the substring's contents. */ operator String() const throw(Substring::UnboundSubstring); /** Convert a substring to a string. Return a copy of the substring's contents. */ String toString() const throw(Substring::UnboundSubstring); //@} /** @name Binding and Unbinding Substrings */ //@{ /** Bind the substring to a string. @param string the string to bind to @param from the start position in the string (default is the beginning of the string) @param len the substring's length (default is to the end of the string) */ Substring& bind(const String& string, Index from = 0, Size len = String::EndPos) throw(Exception::IndexUnderflow, Exception::IndexOverflow); /** Bind the substring to the same string another substring is bound to. @param substring the substring that is bound to a string */ Substring& bind(const Substring& substring, Index from = 0, Size len = String::EndPos) throw(Exception::IndexUnderflow, Exception::IndexOverflow); /// unbinds the substring from the string it is bound to void unbind() throw(); /// Return a pointer to the bound String String* getBoundString() throw(); /// Retunrs a const pointer to the bound String const String* getBoundString() const throw(); //@} /** @name Assignment */ //@{ /** Sets the substring to a certain string */ void set(const String& string) throw(Substring::UnboundSubstring); /** Copies a substring from another substring */ void set(const Substring& s) throw(Substring::UnboundSubstring); /// Assigns a substring from a char pointer void set(const char* char_ptr, Size size = String::EndPos) throw(Substring::UnboundSubstring, Exception::NullPointer, Exception::SizeUnderflow); /// String assignment operator const Substring& operator = (const String& string) throw(Substring::UnboundSubstring); /// Substring assignment operator const Substring& operator = (const Substring& substring) throw(Substring::UnboundSubstring); /// char pointer assignment operator const Substring& operator = (const char* char_ptr) throw(Substring::UnboundSubstring, Exception::NullPointer); //@} /** @name Accessors and Mutators */ //@{ /// Return a pointer to the substring's contents char* c_str() throw(Substring::UnboundSubstring); /// Return a const pointer to the substring's contents const char* c_str() const throw(Substring::UnboundSubstring); /** Return the first index of the substring. This means the starting point in the bound string. */ Index getFirstIndex() const throw(Substring::UnboundSubstring); /** Return the last index of the substring This means the end point in the bound string. */ Index getLastIndex() const throw(Substring::UnboundSubstring); /// Return the substring size Size size() const throw(); /// Mutable random access to a character of the substring char& operator [] (Index index) throw(Substring::UnboundSubstring, Exception::IndexUnderflow, Exception::IndexOverflow); /// Random access to a character of the substring (const method). char operator [] (Index index) const throw(Substring::UnboundSubstring, Exception::IndexUnderflow, Exception::IndexOverflow); /// Converts the substring to lower case characters Substring& toLower() throw(Substring::UnboundSubstring); /// Converts the substring to lower case characters Substring& toUpper() throw(Substring::UnboundSubstring); //@} /** @name Predicates */ //@{ /// Return true, if the substring is bound to a String bool isBound() const throw(); /// Return true, if the substring is empty or unbound bool isEmpty() const throw(); //@} /** @name Comparison Operators */ //@{ /// returns true, if the contents of the two substrings are equal bool operator == (const Substring& substring) const throw(Substring::UnboundSubstring); /// Return true, if the contents of the two substrings are not equal bool operator != (const Substring& substring) const throw(Substring::UnboundSubstring); /// Return true, if the contents of the substring and the string are equal bool operator == (const String& string) const throw(Substring::UnboundSubstring); /// Return true, if the contents of the substring and the string are not equal bool operator != (const String& string) const throw(Substring::UnboundSubstring); /// Return true, if the contents of the substring and the string are equal BALL_EXPORT friend bool operator == (const String& string, const Substring& substring) throw(Substring::UnboundSubstring); /// Return true, if the contents of the substring and the string are not equal BALL_EXPORT friend bool operator != (const String& string, const Substring& substring) throw(Substring::UnboundSubstring); /// Return true, if the contents of the substring are equal to the contents of the C-string bool operator == (const char* char_ptr) const throw(Substring::UnboundSubstring, Exception::NullPointer); /// Return true, if the contents of the substring are not equal to the contents of the C-string bool operator != (const char* char_ptr) const throw(Substring::UnboundSubstring, Exception::NullPointer); /// Return true, if the substring has length 1 and contains the given char bool operator == (char c) const throw(Substring::UnboundSubstring); /// Return true, if the substring is differnet from the given char bool operator != (char c) const throw(Substring::UnboundSubstring); //@} /** @name Stream I/O */ //@{ /// Writes the substring to a stream BALL_EXPORT friend std::ostream& operator << (std::ostream& s, const Substring& substring) throw(); //@} /** @name Debugging and Diagnostics */ //@{ /** Return true, if the string is bound to a string and its indices are valid. Valid indices means that the first index is not greater than the last index, both indices are non-negative and lesser than the size of the bound string. */ bool isValid() const throw(); /// Dumps the substring object (including the values of its private members) void dump(std::ostream& s = std::cout, Size depth = 0) const throw(Substring::UnboundSubstring); //@} protected: void validateRange_(Index& from, Size& len) const throw(Exception::IndexUnderflow, Exception::IndexOverflow); private: /*_ @name Attributes */ //_@{ //_ pointer to the bound String String* bound_; //_ start index in the bound String Index from_; //_ end index in the bound String Index to_; //_@} }; //@} # ifndef BALL_NO_INLINE_FUNCTIONS # include # endif } // namespace BALL #endif // BALL_DATATYPE_STRING_H ugene-1.9.8/src/plugins_3rdparty/ball/src/include/BALL/DATATYPE/list.h0000644000175000017500000001164011651544325023617 0ustar ilyailya// -*- Mode: C++; tab-width: 2; -*- // vi: set ts=2: // // $Id: list.h,v 1.23 2004-04-22 10:08:19 oliver Exp $ // #ifndef BALL_DATATYPE_LIST_H #define BALL_DATATYPE_LIST_H #ifndef BALL_COMMON_H # include #endif #ifndef BALL_CONCEPT_VISITOR_H # include #endif #ifndef BALL_CONCEPT_PROCESSOR_H # include #endif #include namespace BALL { /** Extended list object. This object is an improved version of the STL list class \ingroup DatatypeMiscellaneous */ template class List : public std::list { public: /** @name Type Definitions */ //@{ /** Iterator type. */ typedef typename std::list::iterator Iterator; // for STL compatibility typedef typename std::list::iterator iterator; /** Constant iterator type. */ typedef typename std::list::const_iterator ConstIterator; // for STL compatibility typedef typename std::list::const_iterator const_iterator; //@} /** @name Constructors and Destructors */ //@{ BALL_CREATE_DEEP(List) /** Default constructor. Create an empty list. */ List() throw() : std::list() { } /** Copy constructor. Create a copy of an existing list. @param map the list to be copied @param deep ignored */ List(const List& new_list, bool /* deep = true */) throw() : std::list(new_list) { } /** Clear the list */ void destroy() throw() { std::list::clear(); } /** Destructor */ virtual ~List() throw() { std::list::clear(); } //@} /** @name Assignment */ //@{ /** Assign a list from another. @param list the map to be copied @param deep ignored */ void set(const List& list, bool /* deep */ = true) throw() { std::list::clear(); ConstIterator it = list.begin(); for ( ; it != list.end(); ++it) { std::list::push_back(const_cast(*it)); } } /** Assign a list from another. */ const List& operator = (const List& list) throw() { set(list); return *this; } /// Assign the content of a list to another void get(List& list, bool deep = true) const throw() { list.set(*this, deep); } /// Swaps the contents of two lists void swap(List& list) throw() { List temp; temp.set(*this); (*this).set(list); list.set(temp); } //@} /** @name Accessors */ //@{ /** Return the size of the list. */ Size getSize() const throw() { return (Size)std::list::size(); } /** Remove an item from the list. The first item that matches item will be removed. @param item the item to be removed @return bool true if the item was removed */ bool remove(const Value& item) throw() { Iterator it = std::list::begin(); for (; it != std::list::end(); ++it) { if (*it == item) { std::list::erase(it); return true; } } return false; } //@} /** @name Predicates */ //@{ /** Return true if the list is empty. This method return true if the list does not contain any entries. */ bool isEmpty() const throw() { return (std::list::size() == 0); } //@} /** @name DatatypeMiscellaneous */ //@{ /** Visitor host method. Lists may be visited. @param visitor the visitor */ virtual void host(Visitor >& visitor) throw(); //@} /** @name Internal Iterators */ //@{ /** Processor application method. Applies the processor to each entry of the list. @param processor the processor to be applied */ bool apply(UnaryProcessor& processor) throw() { if (!processor.start()) return false; for (Iterator it = std::list::begin(); it != std::list::end(); ++it) { Processor::Result result = processor(*it); if (result <= Processor::BREAK) { return (result == Processor::BREAK); } } return processor.finish(); } //@} /** Equality operator. Test if two instances have the same size and same items at the same positions. */ bool operator == (const List& list) const throw() { if (std::list::size() != list.size()) { return false; } typename List::ConstIterator this_it = std::list::begin(); typename List::ConstIterator list_it = list.begin(); for (; this_it != std::list::end(); ++this_it) { if (!(*this_it == *list_it)) { return false; } ++list_it; } return true; } /** Inequality operator. Test if two instances differ in at least one element. */ bool operator != (const List& list) const throw() { return !(*this == list); } }; template void List::host(Visitor >& visitor) throw() { visitor.visit(*this); } } // namespace BALL #endif // BALL_DATATYPE_LIST_H ugene-1.9.8/src/plugins_3rdparty/ball/src/include/BALL/DATATYPE/hashSet.h0000644000175000017500000006466511651544325024262 0ustar ilyailya// -*- Mode: C++; tab-width: 2; -*- // vi: set ts=2: // // $Id: hashSet.h,v 1.43 2004-04-22 10:08:19 oliver Exp $ // #ifndef BALL_DATATYPE_HASHSET_H #define BALL_DATATYPE_HASHSET_H #ifndef BALL_COMMON_H # include #endif #ifndef BALL_COMMON_HASH_H # include #endif #ifndef BALL_CONCEPT_FORWARDITERATOR_H # include #endif #ifndef BALL_CONCEPT_VISITOR_H # include #endif #ifndef BALL_DATATYPE_FOREACH_H # include #endif #ifndef BALL_CONCEPT_PREDICATE_H # include #endif #ifndef BALL_CONCEPT_PROCESSOR_H # include #endif #include namespace BALL { /** Generic Hash Set Class. \ingroup GenericHash */ template class HashSet { public: /** */ typedef Key ValueType; /** */ typedef Key KeyType; /** */ typedef Key* PointerType; // --- EXTERNAL ITERATORS struct Node { Node* next; ValueType value; Node(const KeyType& my_key, const Node* my_next) throw() : next(const_cast(my_next)), value(const_cast(my_key)) { } }; typedef Node* IteratorPosition; class IteratorTraits { friend class HashSet; public: IteratorTraits() throw() : bound_(0), position_(0), bucket_(0) { } IteratorTraits(const HashSet& hash_set) throw() : bound_(const_cast(&hash_set)), position_(0), bucket_(0) { } IteratorTraits(const IteratorTraits& traits) throw() : bound_(traits.bound_), position_(traits.position_), bucket_(traits.bucket_) { } IteratorTraits& operator = (const IteratorTraits& traits) throw() { bound_ = traits.bound_; position_ = traits.position_; bucket_ = traits.bucket_; return *this; } HashSet* getContainer() throw() { return bound_; } const HashSet* getContainer() const throw() { return bound_; } bool isSingular() const throw() { return (bound_ == 0); } IteratorPosition& getPosition() throw() { return position_; } const IteratorPosition& getPosition() const throw() { return position_; } bool operator == (const IteratorTraits& traits) const throw() { return (position_ == traits.position_); } bool operator != (const IteratorTraits& traits) const throw() { return (position_ != traits.position_); } bool isValid() const throw() { return ((bound_ != 0) && (position_ != 0) && (bucket_ < (Position)bound_->bucket_.size())); } void invalidate() throw() { bound_ = 0; position_ = 0; bucket_ = INVALID_POSITION; } void toBegin() throw() { for (bucket_ = 0; bucket_ < (Position)bound_->bucket_.size(); ++bucket_) { position_ = bound_->bucket_[bucket_]; if (position_ != 0) { return; } } } bool isBegin() const throw() { for (Position bucket = 0; bucket < (Position)bound_->bucket_.size(); ++bucket) { if (bound_->bucket_[bucket_] != 0) { if (position_ == bound_->bucket_[bucket_]) { return true; } else { return false; } } } return false; } void toEnd() throw() { position_ = 0; } bool isEnd() const throw() { return (position_ == 0); } ValueType& getData() throw() { return position_->value; } const ValueType& getData() const throw() { return position_->value; } void forward() throw() { position_ = position_->next; if (position_ != 0) { return; } for (++bucket_; bucket_ < (Position)bound_->bucket_.size(); ++bucket_) { position_ = bound_->bucket_[bucket_]; if (position_ != 0) { return; } } } protected: HashSet* bound_; IteratorPosition position_; Position bucket_; }; friend class IteratorTraits; /** @name Enums */ //@{ enum { /// Initial capacity of the hash set INITIAL_CAPACITY = 4, /// Initial number of buckets INITIAL_NUMBER_OF_BUCKETS = 3 }; //@} /** @name Exceptions */ //@{ /** Illegal key exception. Thrown if access to a non-existent key is required by the constant version of \link operator [] operator [] \endlink . */ class IllegalKey : public Exception::GeneralException { public: IllegalKey(const char* file, int line) : Exception::GeneralException(file, line) { } }; //@} /** @name Type definitions */ //@{ /// typedef ForwardIterator, ValueType, PointerType, IteratorTraits> Iterator; /// typedef ConstForwardIterator , ValueType, PointerType, IteratorTraits> ConstIterator; // STL compatibility stuff /// typedef Iterator iterator; /// typedef ConstIterator const_iterator; /// typedef Key value_type; /// typedef Key key_type; /// typedef Key* pointer; /// typedef const Key* const_pointer; /// typedef Key& reference; /// typedef const Key& const_reference; /// typedef Size size_type; /// typedef Index difference_type; //@} /** @name Constructors and Destructors */ //@{ /** Default Constructor. */ HashSet(Size initial_capacity = INITIAL_CAPACITY, Size number_of_buckets = INITIAL_NUMBER_OF_BUCKETS) throw(); /** Copy Constructor. */ HashSet(const HashSet& hash_set) throw(); /** Destructor. */ virtual ~HashSet() throw() { destroy(); deleteBuckets_(); } /** Clear the hash set. Remove all nodes from all buckets. The capacity and the number of buckets remain unchanged. */ virtual void clear() throw(); /** Clear the hash set. Remove all nodes from all buckets. The capacity and the number of buckets remain unchanged. Simply calls clear; */ void destroy() throw(); //@} /** @name Assignment */ //@{ /** Assign this HashSet with the contents of another HashSet @param hash_set the HashSet to assign from */ void set(const HashSet& hash_set) throw(); /** Assign this HashSet with the contents of another HashSet @param rhs the HashSet to assign from */ const HashSet& operator = (const HashSet& rhs) throw(); /** Assign another HashSet with the contents of this HashSet @param hash_set the HashSet to assign to */ void get(HashSet& hash_set) const throw(); /** Swap the contents of two hash sets. */ void swap(HashSet& hash_set) throw(); //@} /** @name Accessors */ //@{ /** Return the number of buckets. */ Size getBucketSize() const throw(); /** Return the capcacity of the hash set. */ Size getCapacity() const throw(); /** Return the number of elements in the hash set. */ Size getSize() const throw(); /** Return the number of elements in the hash set. */ Size size() const throw(); /** Find the element whose key is key. */ Iterator find(const Key& key) throw(); /** Find the element whose key is key. */ ConstIterator find(const Key& key) const throw(); /** Insert a new entry into the hash set. */ std::pair insert(const ValueType& item) throw(); /** Insert a new entry into the hash set. For STL compatibility. The value of pos is ignored. */ Iterator insert(Iterator pos, const ValueType& item) throw(); /** Erase element with key key. @return Size the number of elements erased (0 or 1) */ Size erase(const KeyType& key) throw(); /** Erase element at a given position. @param pos an iterator pointing to the element to delete */ void erase(Iterator pos) throw(Exception::IncompatibleIterators, Exception::InvalidIterator); /** Erase a range of elements. Erase all elements in the range f - l. */ void erase(Iterator f, Iterator l) throw(Exception::IncompatibleIterators); //@} /** @name Operators */ //@{ /** Intersection operator. Replace the contents of the current hash set by its intersection with rhs. */ const HashSet& operator &= (const HashSet& rhs) throw(); /** Union operator. Replace the contents of the current hash set by its union with rhs. */ const HashSet& operator |= (const HashSet& rhs) throw(); /** Intersection operator. Compute the intersection of the two hash sets. The left-hand set is not modified. */ HashSet operator & (const HashSet& rhs) const throw(); /** Union operator. Compute the union of the two hash sets. The left-hand set is not modified. */ HashSet operator | (const HashSet& rhs) const throw(); /** Union operator. @see operator| */ HashSet operator + (const HashSet& rhs) const throw(); /** Difference operator. Computes the difference of the two sets, i.e. constructs a set containing the the elements of this set that are not contained in rhs. */ HashSet operator - (const HashSet& rhs) const throw(); /** Union operator. @see operator|= */ const HashSet& operator += (const HashSet& rhs) throw(); /** Difference operator. Remove all elements contained in rhs from the set. */ const HashSet& operator -= (const HashSet& rhs) throw(); //@} /** @name Miscellaneous */ //@{ /** Host a visitor for all set entries. */ virtual void host(Visitor >& visitor) throw(); //@} /** @name Predicates */ //@{ /** Test whether the set contains the key key. */ bool has(const Key& key) const throw(); /** Test whether the set is empty. */ bool isEmpty() const throw(); /** Compare two hash sets. */ bool operator == (const HashSet& hash_set) const throw(); /** Compare two hash sets. */ bool operator != (const HashSet& hash_set) const throw(); //@} /** @name Debugging and Diagnostics */ //@{ /** Return true if the hash set is consistent. Condition: the number of entries in all buckets has to be equal the stored number of entries (getSize()). */ bool isValid() const throw(); /** Dump the constent of this instance to an ostream. */ virtual void dump(std::ostream& s = std::cout, Size depth = 0) const throw(); //@} // --- INTERNAL ITERATORS /** @name Iteration */ //@{ /** Apply a processor to all keys in this instance. @return true if the processor could be applied. */ bool apply(UnaryProcessor& processor) throw(); //@} /** */ Iterator begin() throw() { return Iterator::begin(*this); } /** */ Iterator end() throw() { return Iterator::end(*this); } /** */ ConstIterator begin() const throw() { return ConstIterator::begin(*this); } /** */ ConstIterator end() const throw() { return ConstIterator::end(*this); } protected: virtual Node* newNode_(const ValueType& value, Node* next) const throw(); virtual void deleteNode_(Node* node) const throw(); virtual HashIndex hash(const Key& key) const throw(); virtual bool needRehashing_() const throw(); virtual void rehash() throw(); private: void deleteBuckets_() throw(); Position hashBucket_(const Key& key) const throw(); void rehash_() throw(); // --- ATTRIBUTES /*_ The number of elements in the hash set */ Size size_; /*_ The capacity - usually the number of buckets */ Size capacity_; /*_ Buckets are stored as a vector of linked lists of Nodes */ vector bucket_; }; template HashSet::HashSet(Size initial_capacity, Size number_of_buckets) throw() : size_(0), capacity_(initial_capacity), bucket_(number_of_buckets) { for (Position bucket = 0; bucket < (Position)bucket_.size(); ++bucket) { bucket_[bucket] = 0; } } template HashSet::HashSet(const HashSet& hash_set) throw() : size_(hash_set.size_), capacity_(hash_set.capacity_), bucket_(hash_set.bucket_.size()) { Node* item = 0; for (Position bucket = 0; bucket < (Position)bucket_.size(); ++bucket) { bucket_[bucket] = 0; for (item = hash_set.bucket_[bucket]; item != 0; item = item->next) { bucket_[bucket] = newNode_(item->value, bucket_[bucket]); } } } template void HashSet::set(const HashSet& hash_set) throw() { if (&hash_set == this) { return; } destroy(); deleteBuckets_(); size_ = hash_set.size_; capacity_ = hash_set.capacity_; bucket_.resize(hash_set.bucket_.size()); Node* item = 0; for (Position bucket = 0; bucket < (Position)bucket_.size(); ++bucket) { bucket_[bucket] = 0; for (item = hash_set.bucket_[bucket]; item != 0; item = item->next) { bucket_[bucket] = newNode_(item->value, bucket_[bucket]); } } } template void HashSet::clear() throw() { Node* node = 0; Node* next_node = 0; for (Position bucket = 0; bucket < (Position)bucket_.size(); ++bucket) { for (node = bucket_[bucket]; node != 0; node = next_node) { next_node = node->next; deleteNode_(node); } bucket_[bucket] = 0; } size_ = 0; } template BALL_INLINE void HashSet::destroy() throw() { clear(); } template BALL_INLINE const HashSet& HashSet::operator = (const HashSet& hash_set) throw() { set(hash_set); return *this; } template BALL_INLINE void HashSet::get(HashSet& hash_set) const throw() { hash_set.set(*this); } template BALL_INLINE void HashSet::swap(HashSet& hash_set) throw() { std::swap(size_, hash_set.size_); std::swap(capacity_, hash_set.capacity_); std::swap(bucket_, hash_set.bucket_); } template BALL_INLINE const HashSet& HashSet::operator &= (const HashSet& rhs) throw() { // Store all elements that are not part of the intersection // in a list for subsequent deletion. std::list erase_list; for (Iterator it = begin(); it != end(); ++it) { if (!rhs.has(*it)) { erase_list.push_back(*it); } } // erase all elements not part of the intersection typename list::iterator list_it = erase_list.begin(); for (; list_it != erase_list.end(); ++list_it) { erase(*list_it); } return *this; } template BALL_INLINE const HashSet& HashSet::operator |= (const HashSet& rhs) throw() { // Compute the union of both sets by inserting every element of the // rhs set. for (ConstIterator it = rhs.begin(); it != rhs.end(); ++it) { insert(*it); } return *this; } template BALL_INLINE const HashSet& HashSet::operator += (const HashSet& rhs) throw() { return operator |= (rhs); } template BALL_INLINE HashSet HashSet::operator & (const HashSet& rhs) const throw() { // Create an empty hash set... HashSet tmp; ConstIterator it = begin(); // ...and copy all the elements contained in the rhs hash set. for (; +it; ++it) { if (rhs.has(*it)) { tmp.insert(*it); } } return tmp; } template BALL_INLINE HashSet HashSet::operator - (const HashSet& rhs) const throw() { // Create an empty hash set... HashSet tmp; ConstIterator it = begin(); // ...and copy all the elements contained in this set and not in the rhs hash set. for (; +it; ++it) { if (!rhs.has(*it)) { tmp.insert(*it); } } return tmp; } template BALL_INLINE const HashSet& HashSet::operator -= (const HashSet& hash_set) throw() { // avoid memory corruption caused by iterating over freed space when // deleting myself if (this == &hash_set) { clear(); } else { // erase all elements which are contained in this and hash_set typename HashSet::ConstIterator it = hash_set.begin(); for (; it != hash_set.end(); ++it) { if (has(*it)) { erase(*it); } } } return *this; } template BALL_INLINE HashSet HashSet::operator | (const HashSet& rhs) const throw() { HashSet tmp(*this); tmp |= rhs; return tmp; } template BALL_INLINE HashSet HashSet::operator + (const HashSet& rhs) const throw() { return operator | (rhs); } template BALL_INLINE Size HashSet::getBucketSize() const throw() { return (Size)bucket_.size(); } template BALL_INLINE Size HashSet::getCapacity() const throw() { return capacity_; } template BALL_INLINE Size HashSet::getSize() const throw() { return size_; } template BALL_INLINE Size HashSet::size() const throw() { return size_; } template typename HashSet::Iterator HashSet::find(const Key& key) throw() { Iterator it = end(); Position bucket = hashBucket_(key); Node* node_ptr = bucket_[bucket]; while (node_ptr != 0) { if (node_ptr->value == key) { it.getTraits().position_ = node_ptr; it.getTraits().bucket_ = bucket; break; } node_ptr = node_ptr->next; } return it; } template BALL_INLINE typename HashSet::ConstIterator HashSet::find(const Key& key) const throw() { return (const_cast(this))->find(key); } template std::pair::Iterator, bool> HashSet::insert (const ValueType& item) throw() { Iterator it = find(item); if (it == end()) { if (needRehashing_() == true) { rehash_(); } Position bucket = hashBucket_(item); Node* next = bucket_[bucket]; bucket_[bucket] = newNode_(item, next); ++size_; it.getTraits().position_ = bucket_[bucket]; it.getTraits().bucket_ = bucket; } return std::pair(it, true); } template typename HashSet::Iterator HashSet::insert (typename HashSet::Iterator /* pos */, const ValueType& item) throw() { return insert(item).first; } template Size HashSet::erase(const KeyType& key) throw() { Position bucket = hashBucket_(key); Node* previous = 0; Node* node_ptr = bucket_[bucket]; while (node_ptr != 0 && node_ptr->value != key) { previous = node_ptr; node_ptr = node_ptr->next; } if (node_ptr == 0) { return false; } if (node_ptr == bucket_[bucket]) { bucket_[bucket] = node_ptr->next; } else { previous->next = node_ptr->next; } deleteNode_(node_ptr); --size_; return 1; } template void HashSet::erase(Iterator pos) throw(Exception::IncompatibleIterators, Exception::InvalidIterator) { if (pos.getTraits().bound_ != this) { throw Exception::IncompatibleIterators(__FILE__, __LINE__); } if ((pos == end()) || (size_ == 0)) { return; } if (pos.getTraits().position_ == bucket_[pos.getTraits().bucket_]) { bucket_[pos.getTraits().bucket_] = pos.getTraits().position_->next; } else { // walk over all nodes in this bucket and identify the predecessor // of the node refered to by the iterator pos Node* prev = bucket_[pos.getTraits().bucket_]; for (; (prev != 0) && (prev->next != pos.getTraits().position_); prev = prev->next); if (prev != 0) { // remove the node and reconnect the list prev->next = pos.getTraits().position_->next; } else { throw Exception::InvalidIterator(__FILE__, __LINE__); } } // delete the node and decrement the set size deleteNode_(pos.getTraits().position_); --size_; } template void HashSet::erase(Iterator f, Iterator l) throw(Exception::IncompatibleIterators) { if (f.getTraits().bound_ != this || l.getTraits().bound_ != this) { throw Exception::IncompatibleIterators(__FILE__, __LINE__); } if (f == end()) { return; } Position last_bucket = l.getTraits().bucket_; if (l == end()) { last_bucket = (Position)(bucket_.size() - 1); } if (f.getTraits().bucket_ > last_bucket) { // empty range - l < f return; } // count the deleted entries to correct the set size Size no_deletions = 0; Position bucket = f.getTraits().bucket_; for (; bucket <= last_bucket; bucket++) { if (bucket_[bucket] == 0) { // skip all empty buckets continue; } if ((bucket == f.getTraits().bucket_) && (bucket_[bucket] != f.getTraits().position_)) { // find the predecessor of f Node* n = bucket_[bucket]; Node* next; for (; (n->next != f.getTraits().position_) && (n->next != 0); n = n->next); if (bucket == last_bucket) { // delete everything from f to l in this bucket next = n->next; n->next = l.getTraits().position_; for (n = next; (n != 0) && (n != l.getTraits().position_); n = next) { next = n->next; deleteNode_(n); no_deletions++; } } else { // delete everything from f to the end in this bucket if (n != 0) { // mark the end of the list next = n->next; n->next = 0; // delete all remaining nodes for (n = next; n != 0; n = next) { next = n->next; deleteNode_(n); no_deletions++; } } } } // if the current bucket lies between the first and the last bucket... else if (bucket < last_bucket) { // ...delete the whole bucket Node* next; for (Node* n = bucket_[bucket]; n != 0; n = next) { next = n->next; deleteNode_(n); no_deletions++; } bucket_[bucket] = 0; } else if (bucket == last_bucket) { // we delete everything in this bucket up to the iterator l // find the predecessor of l Node* n = bucket_[bucket]; Node* next; for (; (n != 0) && (n != l.getTraits().position_); n = next) { next = n->next; deleteNode_(n); no_deletions++; } bucket_[bucket] = l.getTraits().position_; } } // correct the set size size_ -= no_deletions; } template BALL_INLINE void HashSet::host(Visitor >& visitor) throw() { visitor.visit(*this); } template BALL_INLINE bool HashSet::has(const Key& key) const throw() { return (find(key) != end()); } template BALL_INLINE bool HashSet::isEmpty() const throw() { return (size_ == 0); } template bool HashSet::operator == (const HashSet& hash_set) const throw() { if (size_ != hash_set.size_) { return false; } ConstIterator it1 = begin(); ConstIterator it2 = hash_set.begin(); while (it1 != end()) { if (*it1 != *it2) { return false; } it1++; it2++; } return true; } template BALL_INLINE bool HashSet::operator != (const HashSet& hash_set) const throw() { return !(*this == hash_set); } template bool HashSet::isValid() const throw() { Size size = 0; Node* node = 0; for (Position bucket = 0; bucket < (Position)bucket_.size(); ++bucket) { for (node = bucket_[bucket]; node != 0; node = node->next) { ++size; if (node->next == 0) { break; } } } return (size_ == size); } template void HashSet::dump(std::ostream& s, Size depth) const throw() { BALL_DUMP_STREAM_PREFIX(s); BALL_DUMP_DEPTH(s, depth); BALL_DUMP_DEPTH(s, depth); s << " size: " << getSize() << std::endl; BALL_DUMP_DEPTH(s, depth); s << " # buckets: " << getBucketSize() << std::endl; BALL_DUMP_DEPTH(s, depth); s << " capacity: " << getCapacity() << std::endl; BALL_DUMP_DEPTH(s, depth); s << " load factor: " << (float)size_ / (float)bucket_.size() << std::endl; for (Position bucket = 0; bucket < (Position)bucket_.size(); ++bucket) { BALL_DUMP_DEPTH(s, depth); s << " bucket " << bucket << ": "; for (Node* ptr = bucket_[bucket]; ptr != 0; ptr = ptr->next) { s << "(" << (void*)ptr << ") "; } s << "(0)" << std::endl; } BALL_DUMP_STREAM_SUFFIX(s); } template bool HashSet::apply(UnaryProcessor& processor) throw() { if (processor.start() == false) { return false; } Processor::Result result; Iterator it = begin(); while (it != end()) { result = processor(*it); if (result <= Processor::BREAK) { return (result == Processor::BREAK); } it++; } return processor.finish(); } template BALL_INLINE HashIndex HashSet::hash(const Key& key) const throw() { return (HashIndex)Hash(key); } template BALL_INLINE void HashSet::rehash() throw() { capacity_ = (Size)getNextPrime((Size)bucket_.size() << 1); } template void HashSet::deleteBuckets_() throw() { Size i = 0; Node* node = 0; Node* next_node = 0; for (i = 0; i < bucket_.size(); i++) { node = bucket_[i]; while (node != 0) { next_node = node->next; delete node; node = next_node; } bucket_[i] = 0; } } template BALL_INLINE typename HashSet::Node* HashSet::newNode_ (const ValueType& value, typename HashSet::Node* next) const throw() { return new Node(value, next); } template BALL_INLINE void HashSet::deleteNode_(typename HashSet::Node* node) const throw() { delete node; } template BALL_INLINE bool HashSet::needRehashing_() const throw() { return (size_ >= capacity_); } template BALL_INLINE HashIndex HashSet::hashBucket_(const Key& key) const throw() { return (Position)((HashIndex)hash(key) % (HashIndex)bucket_.size()); } template void HashSet::rehash_() throw() { // calculate the new number of buckets (in capacity_) rehash(); // save the old contents vector old_buckets(bucket_); // resize the bucket vector and initialize it with zero bucket_.clear(); bucket_.resize(capacity_); Position i; for (i = 0; i < capacity_; i++) { bucket_[i] = 0; } // rehash the old contents into the new buckets Node* node; Node* next_node; for (Position i = 0; i < (Position)old_buckets.size(); ++i) { for (node = old_buckets[i]; node != 0; node = next_node) { next_node = node->next; Position new_bucket = hashBucket_(node->value); node->next = bucket_[new_bucket]; bucket_[new_bucket] = node; } } } } // namespace BALL #endif // BALL_DATATYPE_HASHSET_H ugene-1.9.8/src/plugins_3rdparty/ball/src/include/BALL/DATATYPE/quadruple.h0000644000175000017500000001722611651544325024654 0ustar ilyailya// -*- Mode: C++; tab-width: 2; -*- // vi: set ts=2: // // $Id: quadruple.h,v 1.13 2003-08-26 08:04:11 oliver Exp $ // #ifndef BALL_DATATYPE_QUADRUPLE_H #define BALL_DATATYPE_QUADRUPLE_H #ifndef BALL_COMMON_H # include #endif namespace BALL { /** Quadruple Class. This template class is used to represent quadruples of arbitrary types (like the STL type pair). \ingroup DatatypeMiscellaneous */ template class Quadruple { public: /** @name Constructors and Destructors */ //@{ BALL_CREATE(Quadruple) /** Default constructor. Creates a new Quadruple object. */ Quadruple() throw(); /** Copy constructor. Creates a new Quadruple object from another. @param quadruple the Quadruple object to be copied @param deep not used (needed for a consistent interface only) */ Quadruple(const Quadruple& quadruple, bool deep = true) throw(); /** Detailled constructor. Creates a new Quadruple object from the quadruple's four members. @param new_first the first quadruple member @param new_second the second quadruple member @param new_third the third quadruple member @param new_fourth the fourth quadruple member */ Quadruple(const T1& new_first, const T2& new_second, const T3& new_third, const T4& new_fourth) throw(); /** Destructor. Destructs the Quadruple object. */ virtual ~Quadruple() throw(); //@} /** Clear method. */ virtual void clear() throw(); /** @name Assignment */ //@{ /** Assignment operator. Assigns the contents of a quadruple to another. @param quadruple the quadruple to be copied */ const Quadruple& operator = (const Quadruple& quadruple) throw(); /** */ void set(const T1& t1, const T2& t2, const T3& t3, const T4& t4) throw(); /** */ void get(T1& first, T2& second, T3& third, T4& fourth) const throw(); //@} /** @name Predicates */ //@{ /** Equality operator Two instances are equal if they have the same members. */ bool operator == (const Quadruple& quadruple) const throw(); /** Inequality operator */ bool operator != (const Quadruple& quadruple) const throw(); /** Lesser than operator. One instance is lesser than an other if all members from first to third are equal or less than the members of the other instance and at least fourth is less. */ bool operator < (const Quadruple& quadruple) const throw(); /** Lesser or equal than operator. */ bool operator <= (const Quadruple& quadruple) const throw(); /** Greater or equal than operator. */ bool operator >= (const Quadruple& quadruple) const throw(); /** Greater than operator. */ bool operator > (const Quadruple& quadruple) const throw(); //@} /** @name Attributes */ //@{ /** The first quadruple member */ T1 first; /** The second quadruple member */ T2 second; /** The third quadruple member */ T3 third; /** The fourth quadruple member */ T4 fourth; //@} }; template Quadruple::Quadruple() throw() { } template Quadruple::Quadruple (const Quadruple& quadruple, bool /* deep */) throw() : first(quadruple.first), second(quadruple.second), third(quadruple.third), fourth(quadruple.fourth) { } template Quadruple::Quadruple (const T1& new_first, const T2& new_second, const T3& new_third, const T4& fourth) throw() : first(new_first), second(new_second), third(new_third), fourth(fourth) { } template Quadruple::~Quadruple() throw() { } template BALL_INLINE void Quadruple::set(const T1& new_first, const T2& new_second, const T3& new_third, const T4& new_fourth) throw() { first = new_first; second = new_second; third = new_third; fourth = new_fourth; } template BALL_INLINE const Quadruple& Quadruple::operator = (const Quadruple& quadruple) throw() { first = quadruple.first; second = quadruple.second; third = quadruple.third; fourth = quadruple.fourth; return *this; } template BALL_INLINE void Quadruple::get(T1& t1, T2& t2, T3& t3, T4& t4) const throw() { t1 = first; t2 = second; t3 = third; t4 = fourth; } template BALL_INLINE bool Quadruple::operator == (const Quadruple& quadruple) const throw() { return (first == quadruple.first && second == quadruple.second && third == quadruple.third && fourth == quadruple.fourth); } template BALL_INLINE bool Quadruple::operator != (const Quadruple& quadruple) const throw() { return (first != quadruple.first || second != quadruple.second || third != quadruple.third || fourth != quadruple.fourth); } template BALL_INLINE void Quadruple::clear() throw() { first = T1(); second = T2(); third = T3(); fourth = T4(); } template BALL_INLINE bool Quadruple::operator < (const Quadruple& quadruple) const throw() { return (first < quadruple.first || (first == quadruple.first && second < quadruple.second) || (first == quadruple.first && second == quadruple.second && third < quadruple.third) || (first == quadruple.first && second == quadruple.second && third == quadruple.third && fourth < quadruple.fourth)); } template BALL_INLINE bool Quadruple::operator <= (const Quadruple& quadruple) const throw() { return (first < quadruple.first || (first == quadruple.first && second < quadruple.second) || (first == quadruple.first && second == quadruple.second && third < quadruple.third) || (first == quadruple.first && second == quadruple.second && third == quadruple.third && fourth <= quadruple.fourth)); } template BALL_INLINE bool Quadruple::operator >= (const Quadruple& quadruple) const throw() { return (first > quadruple.first || (first == quadruple.first && second > quadruple.second) || (first == quadruple.first && second == quadruple.second && third > quadruple.third) || (first == quadruple.first && second == quadruple.second && third == quadruple.third && fourth >= quadruple.fourth)); } template BALL_INLINE bool Quadruple::operator > (const Quadruple& quadruple) const throw() { return (first > quadruple.first || (first == quadruple.first && second > quadruple.second) || (first == quadruple.first && second == quadruple.second && third > quadruple.third) || (first == quadruple.first && second == quadruple.second && third == quadruple.third && fourth > quadruple.fourth)); } } // namespace BALL #endif // BALL_DATATYPE_QUADRUPLE_H ugene-1.9.8/src/plugins_3rdparty/ball/src/include/BALL/DATATYPE/string.iC0000644000175000017500000003544211651544325024264 0ustar ilyailya// -*- Mode: C++; tab-width: 2; -*- // vi: set ts=2: // // $Id: string.iC,v 1.44 2003-08-26 08:04:12 oliver Exp $ // BALL_INLINE String::String() throw() : string() { } BALL_INLINE String::String(const String& s) throw() : string(s.c_str()) { } BALL_INLINE String::String(const unsigned char c) throw() : string(1, (char)c) { } BALL_INLINE String::String(const char c, Size len) throw() : string(len, c) { } BALL_INLINE String::String(const string& s) throw() : string(s) { } BALL_INLINE String::String(const String& s, Index from, Size len) throw(Exception::IndexUnderflow, Exception::IndexOverflow) : string("") { s.validateRange_(from, len); if (len > 0) { assign(s.c_str() + from, len); } } BALL_INLINE #ifdef BALL_HAS_SSTREAM void String::set(std::stringstream& s) #else void String::set(std::strstream& s) #endif throw() { s >> (*this); } BALL_INLINE void String::set(char c, Size len) throw() { assign(len, c); } BALL_INLINE void String::set(unsigned char c) throw() { assign(1, (char)c); } BALL_INLINE bool String::operator == (const char* char_ptr) const throw(Exception::NullPointer) { return (compare(char_ptr) == 0); } BALL_INLINE bool String::operator != (const char* char_ptr) const throw(Exception::NullPointer) { return (compare(char_ptr) != 0); } BALL_INLINE bool Substring::operator == (const String& s) const throw(Substring::UnboundSubstring) { if (bound_ == 0) { throw UnboundSubstring(__FILE__, __LINE__); } return (s.compare(bound_->c_str() + from_, 0, to_ - from_ + 1) == 0); } BALL_INLINE bool Substring::operator != (const String& s) const throw(Substring::UnboundSubstring) { if (bound_ == 0) { throw UnboundSubstring(__FILE__, __LINE__); } return (s.compare(bound_->c_str() + from_, 0, to_ - from_ + 1) != 0); } BALL_INLINE Size Substring::size() const throw() { if (bound_ == 0) { return 0; } return (to_ - from_ + 1); } BALL_INLINE Substring::operator String() const throw(Substring::UnboundSubstring) { if (bound_ == 0) { throw UnboundSubstring(__FILE__, __LINE__); } return String(bound_->c_str(), from_, to_ - from_ + 1); } BALL_INLINE void Substring::unbind() throw() { bound_ = 0; from_ = to_ = (Index)String::EndPos; } BALL_INLINE void Substring::destroy() throw() { if (bound_ != 0) { bound_->erase(from_, to_ - from_ + 1); } unbind(); } BALL_INLINE void Substring::clear() throw() { destroy(); } BALL_INLINE String Substring::toString() const throw(Substring::UnboundSubstring) { if (bound_ == 0) { throw UnboundSubstring(__FILE__, __LINE__); } return String(bound_->c_str(), from_, to_ - from_ + 1); } BALL_INLINE Substring& Substring::bind(const String& s, Index from, Size len) throw(Exception::IndexUnderflow, Exception::IndexOverflow) { s.validateRange_(from, len); bound_ = (String *)&s; from_ = from; to_ = from + (Index)len - 1; return *this; } BALL_INLINE void Substring::set(const String& s) throw(Substring::UnboundSubstring) { if (bound_ == 0) { throw Substring::UnboundSubstring(__FILE__, __LINE__); } bound_->replace(from_, to_ - from_ + 1, s); } BALL_INLINE void Substring::set(const Substring& s) throw(Substring::UnboundSubstring) { if (bound_ == 0 || s.bound_ == 0) { throw Substring::UnboundSubstring(__FILE__, __LINE__); } bound_->replace(from_, to_ - from_ + 1, s.bound_->c_str() + s.from_, s.size()); } BALL_INLINE const Substring& Substring::operator = (const String& s) throw(Substring::UnboundSubstring) { set(s); return *this; } BALL_INLINE const Substring& Substring::operator = (const Substring& s) throw(Substring::UnboundSubstring) { set(s); return *this; } BALL_INLINE const Substring& Substring::operator = (const char* char_ptr) throw(Substring::UnboundSubstring, Exception::NullPointer) { set(char_ptr); return *this; } BALL_INLINE String* Substring::getBoundString() throw() { return bound_; } BALL_INLINE const String* Substring::getBoundString() const throw() { return bound_; } BALL_INLINE char* Substring::c_str() throw(Substring::UnboundSubstring) { if (bound_ == 0) { throw UnboundSubstring(__FILE__, __LINE__); } return (char*)&(bound_->c_str()[from_]); } BALL_INLINE const char* Substring::c_str() const throw(Substring::UnboundSubstring) { if (bound_ == 0) { throw UnboundSubstring(__FILE__, __LINE__); } return &(bound_->c_str()[from_]); } BALL_INLINE Index Substring::getFirstIndex() const throw(Substring::UnboundSubstring) { if (bound_ == 0) { throw UnboundSubstring(__FILE__, __LINE__); } return from_; } BALL_INLINE Index Substring::getLastIndex() const throw(Substring::UnboundSubstring) { if (bound_ == 0) { throw UnboundSubstring(__FILE__, __LINE__); } return to_; } BALL_INLINE char& Substring::operator [] (Index index) throw(Substring::UnboundSubstring, Exception::IndexUnderflow, Exception::IndexOverflow) { if (bound_ == 0) { throw UnboundSubstring(__FILE__, __LINE__); } Size len = String::EndPos; validateRange_(index, len); return (*bound_)[from_ + index]; } BALL_INLINE char Substring::operator [] (Index index) const throw(Substring::UnboundSubstring, Exception::IndexUnderflow, Exception::IndexOverflow) { if (bound_ == 0) { throw UnboundSubstring(__FILE__, __LINE__); } Size len = String::EndPos; validateRange_(index, len); return (*bound_)[from_ + index]; } BALL_INLINE bool Substring::isBound() const throw() { return (bound_ != 0); } BALL_INLINE bool Substring::isEmpty() const throw() { return (bound_ == 0); } BALL_INLINE int String::compare(char c, Index from) const throw(Exception::IndexUnderflow, Exception::IndexOverflow) { validateIndex_(from); return (c_str()[from] - c); } BALL_INLINE bool Substring::operator == (char c) const throw(Substring::UnboundSubstring) { if (bound_ == 0) { throw UnboundSubstring(__FILE__, __LINE__); } return (bound_->compare(c, from_, to_ - from_ + 1) == 0); } BALL_INLINE bool Substring::operator != (char c) const throw(Substring::UnboundSubstring) { if (bound_ == 0) { throw UnboundSubstring(__FILE__, __LINE__); } return (bound_->compare(c, from_, to_ - from_ + 1) != 0); } BALL_INLINE bool Substring::isValid() const throw() { return (bound_ != 0 && from_ >= 0 && from_ <= to_ && to_ < (Index)bound_->size()) ; } BALL_INLINE Substring& Substring::toLower() throw(Substring::UnboundSubstring) { if (bound_ == 0) { throw UnboundSubstring(__FILE__, __LINE__); } (*bound_).toLower(from_, to_ - from_); return *this; } BALL_INLINE Substring& Substring::toUpper() throw(Substring::UnboundSubstring) { if (bound_ == 0) { throw UnboundSubstring(__FILE__, __LINE__); } (*bound_).toUpper(from_, to_ - from_); return *this; } BALL_INLINE const String& String::operator = (const String& s) throw() { set(s); return *this; } BALL_INLINE const String& String::operator = (const char* char_ptr) throw(Exception::NullPointer) { set(char_ptr, 0); return *this; } BALL_INLINE #ifdef BALL_HAS_SSTREAM const String& String::operator = (std::stringstream& s) #else const String& String::operator = (std::strstream& s) #endif throw() { set(s); return *this; } #define BALL_STRING_DEFINE_ASSIGNMENT_METHOD(Type) \ BALL_INLINE \ const String& String::operator = (Type t) throw()\ { \ set(t); \ \ return *this; \ } BALL_STRING_DEFINE_ASSIGNMENT_METHOD(char) BALL_STRING_DEFINE_ASSIGNMENT_METHOD(unsigned char) BALL_STRING_DEFINE_ASSIGNMENT_METHOD(short) BALL_STRING_DEFINE_ASSIGNMENT_METHOD(unsigned short) BALL_STRING_DEFINE_ASSIGNMENT_METHOD(int) BALL_STRING_DEFINE_ASSIGNMENT_METHOD(unsigned int) BALL_STRING_DEFINE_ASSIGNMENT_METHOD(long) BALL_STRING_DEFINE_ASSIGNMENT_METHOD(unsigned long) BALL_STRING_DEFINE_ASSIGNMENT_METHOD(float) BALL_STRING_DEFINE_ASSIGNMENT_METHOD(double) #undef BALL_STRING_DEFINE_ASSIGNMENT_METHOD BALL_INLINE void String::setCompareMode(CompareMode mode) throw() { compare_mode_ = mode; } BALL_INLINE String::CompareMode String::getCompareMode() throw() { return compare_mode_; } BALL_INLINE char String::toChar() const throw() { return *c_str(); } BALL_INLINE unsigned char String::toUnsignedChar() const throw() { return (unsigned char)*c_str(); } BALL_INLINE Substring String::getSubstring(Index from, Size len) const throw(Exception::IndexUnderflow, Exception::IndexOverflow) { validateRange_(from, len); return Substring(*this, from, len); } BALL_INLINE Substring String::operator () (Index from, Size len) const throw(Exception::IndexUnderflow, Exception::IndexOverflow) { return getSubstring(from, len); } BALL_INLINE String& String::trim(const char* trimmed) throw() { return trimRight(trimmed).trimLeft(trimmed); } BALL_INLINE String String::trim(const char* trimmed) const throw() { String tmp(*this); tmp.trimRight(trimmed); tmp.trimLeft(trimmed); return tmp; } BALL_INLINE String& String::truncate(Size max_size) throw() { if (max_size < (Size) size()) { resize(max_size); } return *this; } BALL_INLINE Substring String::left(Size len) const throw() { if (len > (Size)size()) { len = (Size)size(); } return Substring(*this, 0, len); } BALL_INLINE Substring String::instr(const String& patterns, Index from) const throw() { string::size_type found = find(patterns, from); return (found == string::npos) ? Substring(*this, 0, 0) : Substring(*this, (Index)found, (Size)patterns.size()); } BALL_INLINE String String::operator + (const string& s) const throw() { String result(*this); result.append(s); return result; } BALL_INLINE String String::operator +(const char* char_ptr) const throw() { String result(*this); result.append(char_ptr); return result; } BALL_INLINE String String::operator + (char c) const throw() { String result(*this); result.append(1, c); return result; } BALL_INLINE void String::destroy() throw() { assign(""); } BALL_INLINE void String::clear() throw() { assign(""); } BALL_INLINE bool String::has(char c) const throw() { return ((c != (char)0) && (find(c, 0) != string::npos)); } BALL_INLINE bool String::hasSubstring(const String& s, Index from) const throw() { if (s.size() == 0) { return true; } return (find(s, from) != string::npos); } BALL_INLINE bool String::isEmpty() const throw() { return (size() == 0); } BALL_INLINE bool String::isAlpha(char c) throw() { return ((c != 0) && ((char*)strchr(CHARACTER_CLASS__ASCII_ALPHA, c) != 0)); } BALL_INLINE bool String::isAlnum(char c) throw() { return ((c != 0) && ((char*)strchr(CHARACTER_CLASS__ASCII_ALPHANUMERIC, c) != 0)); } BALL_INLINE bool String::isDigit(char c) throw() { return ((c != 0) && ((char*)strchr(CHARACTER_CLASS__ASCII_NUMERIC, c) != 0)); } BALL_INLINE bool String::isFloat() const throw() { char* test; char* str = const_cast(c_str()); errno = 0; strtod(str, &test); return (errno == 0 && strlen(test) == 0); } BALL_INLINE bool String::isSpace(char c) throw() { return (c == ' '); } BALL_INLINE bool String::isWhitespace(char c) throw() { return ((c != 0) && ((char*)strchr(CHARACTER_CLASS__WHITESPACE, c) != 0)); } BALL_INLINE bool String::operator != (const String& s) const throw() { return (compare(s) != 0); } BALL_INLINE bool String::operator < (const String& s) const throw() { return (compare(s) < 0); } BALL_INLINE bool String::operator <= (const String& s) const throw() { return (compare(s) <= 0); } BALL_INLINE bool String::operator >= (const String& s) const throw() { return (compare(s) >= 0); } BALL_INLINE bool String::operator > (const String& s) const throw() { return (compare(s) > 0); } BALL_INLINE bool String::operator == (const String& string) const throw() { return (compare(string.c_str()) == 0); } BALL_INLINE bool String::operator < (const char* char_ptr) const throw(Exception::NullPointer) { return (compare(char_ptr) < 0); } BALL_INLINE bool String::operator <= (const char* char_ptr) const throw(Exception::NullPointer) { return (compare(char_ptr) <= 0); } BALL_INLINE bool String::operator >= (const char* char_ptr) const throw(Exception::NullPointer) { return (compare(char_ptr) >= 0); } BALL_INLINE bool String::operator > (const char* char_ptr) const throw(Exception::NullPointer) { return (compare(char_ptr) > 0); } BALL_INLINE bool String::operator == (char c) const throw() { return (compare(c) == 0); } BALL_INLINE bool String::operator != (char c) const throw() { return (compare(c) != 0); } BALL_INLINE bool String::operator < (char c) const throw() { return (compare(c) < 0); } BALL_INLINE bool String::operator <= (char c) const throw() { return (compare(c) <= 0); } BALL_INLINE bool String::operator >= (char c) const throw() { return (compare(c) >= 0); } BALL_INLINE bool String::operator > (char c) const throw() { return (compare(c) > 0); } BALL_INLINE bool String::isValid() const throw() { return (c_str() != 0 && size() <= capacity()); } BALL_INLINE std::istream& String::getline(std::istream& s, char delimiter) throw() { static char line_buffer[8192]; s.getline(line_buffer, 8191, delimiter); set(line_buffer); return s; } BALL_INLINE bool operator != (const String& s, const Substring& substring) throw(Substring::UnboundSubstring) { return (substring != s); } BALL_INLINE bool operator == (const String& s, const Substring& substring) throw(Substring::UnboundSubstring) { return (substring == s); } BALL_INLINE void String::swap(String& s) throw() { string::swap(s); } BALL_INLINE bool operator == (const char* char_ptr, const String &s) throw(Exception::NullPointer) { return (s.compare(char_ptr) == 0); } BALL_INLINE bool operator != (const char* char_ptr, const String &s) throw(Exception::NullPointer) { return (s.compare(char_ptr) != 0); } BALL_INLINE bool operator < (const char* char_ptr, const String& s) throw(Exception::NullPointer) { return (s.compare(char_ptr) > 0); } BALL_INLINE bool operator <= (const char* char_ptr, const String &s) throw(Exception::NullPointer) { return (s.compare(char_ptr) >= 0); } BALL_INLINE bool operator >= (const char* char_ptr, const String& s) throw(Exception::NullPointer) { return (s.compare(char_ptr) <= 0); } BALL_INLINE bool operator > (const char* char_ptr, const String& s) throw(Exception::NullPointer) { return (s.compare(char_ptr) < 0); } BALL_INLINE bool operator == (char c, const String& s) throw() { return (s.compare(c) == 0); } BALL_INLINE bool operator != (char c, const String &s) throw() { return (s.compare(c) != 0); } BALL_INLINE bool operator < (char c, const String& s) throw() { return (s.compare(c) > 0); } BALL_INLINE bool operator <= (char c, const String &s) throw() { return (s.compare(c) >= 0); } BALL_INLINE bool operator >= (char c, const String &s) throw() { return (s.compare(c) <= 0); } BALL_INLINE bool operator > (char c, const String &s) throw() { return (s.compare(c) < 0); } ugene-1.9.8/src/plugins_3rdparty/ball/src/include/BALL/DATATYPE/hashMap.h0000644000175000017500000006016211651544325024230 0ustar ilyailya// -*- Mode: C++; tab-width: 2; -*- // vi: set ts=2: // // $Id: hashMap.h,v 1.41 2005-12-23 17:01:42 amoll Exp $ // #ifndef BALL_DATATYPE_HASHMAP_H #define BALL_DATATYPE_HASHMAP_H #ifndef BALL_COMMON_H # include #endif #ifndef BALL_COMMON_HASH_H # include #endif #ifndef BALL_CONCEPT_FORWARDITERATOR_H # include #endif #ifndef BALL_CONCEPT_VISITOR_H # include #endif #ifndef BALL_DATATYPE_FOREACH_H # include #endif #ifndef BALL_CONCEPT_PREDICATE_H # include #endif #ifndef BALL_CONCEPT_PROCESSOR_H # include #endif #ifndef BALL_COMMON_EXCEPTION_H # include #endif #include #include namespace BALL { /** Generic Hash Map Class. \ingroup GenericHash */ template class HashMap { public: /** */ typedef ::std::pair ValueType; /** */ typedef Key KeyType; /** */ typedef ::std::pair* PointerType; // --- EXTERNAL ITERATORS struct Node { Node* next; ValueType value; Node(const ValueType& my_value, const Node* my_next) throw() : next(const_cast(my_next)), value(const_cast(my_value)) { } }; typedef Node* IteratorPosition; class IteratorTraits_ { friend class HashMap; public: IteratorTraits_() throw() : bound_(0), position_(0), bucket_(0) { } IteratorTraits_(const HashMap& hash_map) throw() : bound_(const_cast(&hash_map)), position_(0), bucket_(0) { } IteratorTraits_(const IteratorTraits_& traits) throw() : bound_(traits.bound_), position_(traits.position_), bucket_(traits.bucket_) { } const IteratorTraits_& operator = (const IteratorTraits_& traits) throw() { bound_ = traits.bound_; position_ = traits.position_; bucket_ = traits.bucket_; return *this; } HashMap* getContainer() throw() { return bound_; } const HashMap* getContainer() const throw() { return bound_; } bool isSingular() const throw() { return (bound_ == 0); } IteratorPosition& getPosition() throw() { return position_; } const IteratorPosition& getPosition() const throw() { return position_; } bool operator == (const IteratorTraits_& traits) const throw() { return (position_ == traits.position_); } bool operator != (const IteratorTraits_& traits) const throw() { return (position_ != traits.position_); } bool isValid() const throw() { return ((bound_ != 0) && (position_ != 0) && (bucket_ < (Position)bound_->bucket_.size())); } void invalidate() throw() { bound_ = 0; position_ = 0; bucket_ = INVALID_POSITION; } void toBegin() throw() { for (bucket_ = 0; bucket_ < (Position)bound_->bucket_.size(); ++bucket_) { position_ = bound_->bucket_[bucket_]; if (position_ != 0) { return; } } } bool isBegin() const throw() { for (Position bucket = 0; bucket < (Position)bound_->bucket_.size(); ++bucket) { if (bound_->bucket_[bucket_] != 0) { if (position_ == bound_->bucket_[bucket_]) { return true; } else { return false; } } } return false; } void toEnd() throw() { position_ = 0; } bool isEnd() const throw() { return (position_ == 0); } ValueType& getData() throw() { return position_->value; } const ValueType& getData() const throw() { return position_->value; } void forward() throw() { position_ = position_->next; if (position_ != 0) { return; } for (++bucket_; bucket_ < (Position)bound_->bucket_.size(); ++bucket_) { position_ = bound_->bucket_[bucket_]; if (position_ != 0) { return; } } } protected: HashMap* bound_; IteratorPosition position_; Position bucket_; }; /** @name Enums and Constants */ //@{ enum { /// Initial capacity of the empty hash map INITIAL_CAPACITY = 4, /// Initial number of buckets of the empty hash map INITIAL_NUMBER_OF_BUCKETS = 3 }; //@} /** @name Exceptions */ //@{ /** IllegalKey exception */ class IllegalKey : public Exception::GeneralException { public: IllegalKey(const char* file, int line) : Exception::GeneralException(file, line) {} }; //@} /** @name Type definitions */ //@{ /** */ typedef ForwardIterator, ValueType, PointerType, IteratorTraits_> Iterator; /** */ typedef ConstForwardIterator , ValueType, PointerType, IteratorTraits_> ConstIterator; //@} /** @name Constructors and Destructors */ //@{ BALL_CREATE(HashMap) /** Default constructor. Create a new and empty hash map. @param initial_capacity the capacity of the hash map @param number_of_buckets the number of buckets to create */ HashMap(Size initial_capacity = INITIAL_CAPACITY, Size number_of_buckets = INITIAL_NUMBER_OF_BUCKETS) throw(); /** Copy Constructor. */ HashMap(const HashMap& hash_map) throw(); /** Destructor. */ BALL_INLINE virtual ~HashMap() throw() { destroy(); deleteBuckets_(); } /** Clear the hash map. Remove all nodes from all buckets. The capacity and the number of buckets remain unchanged. */ virtual void clear() throw(); /** Clear the hash map. Remove all nodes from all buckets. The capacity and the number of buckets remain unchanged. Simply calls clear. */ void destroy() throw(); //@} /** @name Assignment */ //@{ /** Assignment from another hash map. @param hash_map the hash map to assign from */ void set(const HashMap& hash_map) throw(); /** Assignment operator. Assign the contents of a hash map to another. @param hash_map the hash map to assign from */ const HashMap& operator = (const HashMap& hash_map) throw(); /** Assign the contents of this hash map to another map. */ void get(HashMap& hash_map) const throw(); /** Swap the contents of two hash maps. */ void swap(HashMap& hash_map) throw(); //@} /** @name Accessors */ //@{ /** Return the number of buckets */ Size getBucketSize() const throw(); /** Return the capcacity of the hash map. */ Size getCapacity() const throw(); /** Return the number of entries in the map. */ Size getSize() const throw(); /** Return the number of entries in the map. */ Size size() const throw(); /** Find the element whose key is key. */ Iterator find(const Key& key) throw(); /** Find the element whose key is key. */ ConstIterator find(const Key& key) const throw(); /** Return a mutable reference to the element whose key is key. If an element with the key key does not exist, it is inserted. @param key the key */ T& operator [] (const Key& key) throw(); /** Return a constant reference to the element whose key is key. @exception IllegalKey if the given key does not exist @param key the key */ const T& operator [] (const Key& key) const throw(typename HashMap::IllegalKey); /** Insert a new entry into the hash map. */ ::std::pair insert(const ValueType& entry) throw(); /** Insert a new entry into the hash map. For STL compatibility. The value of pos is ignored. */ Iterator insert(Iterator pos, const ValueType& entry) throw(); /** Erase element with key key. @return Size the number of elements erased (0 or 1) */ Size erase(const Key& key) throw(); /** Erase element at a given position. @param pos an iterator pointing to the element to delete */ void erase(Iterator pos) throw(Exception::IncompatibleIterators, Exception::InvalidIterator); /** Erase a range of elements. Erase all elements in the range first - last. */ void erase(Iterator first, Iterator last) throw(Exception::IncompatibleIterators); //@} /** @name Miscellaneous */ //@{ /** Host a visitor for all map entries. */ void host(Visitor >& visitor) throw(); //@} /** @name Predicates */ //@{ /** Test whether the map contains the given key. */ bool has(const Key& key) const throw(); /** Test whether the map is empty. */ bool isEmpty() const throw(); /** Compare two hash maps. */ bool operator == (const HashMap& hash_map) const throw(); /** Compare two hash maps. */ bool operator != (const HashMap& hash_map) const throw(); //@} /** @name Debugging and Diagnostics */ //@{ /** Return true if the hash map is consistent. Condition: the number of entries in all buckets has to be equal the stored number of entries (getSize()). */ bool isValid() const throw(); /** Dump the constent of this instance to an ostream. */ virtual void dump(::std::ostream& s = ::std::cout, Size depth = 0) const throw(); //@} /** @name Iternal iterators */ //@{ /** Apply a processor to the hashmap. @return true if the processor could be applied. */ bool apply(UnaryProcessor& processor) throw(); //@} friend class IteratorTraits_; BALL_INLINE Iterator begin() throw() { return Iterator::begin(*this); } BALL_INLINE Iterator end() throw() { return Iterator::end(*this); } BALL_INLINE ConstIterator begin() const throw() { return ConstIterator::begin(*this); } BALL_INLINE ConstIterator end() const throw() { return ConstIterator::end(*this); } protected: virtual Node* newNode_(const ValueType& value, Node* next) const throw(); virtual void deleteNode_(Node* node) const throw(); virtual HashIndex hash(const Key& key) const throw(); virtual bool needRehashing_() const throw(); virtual void rehash() throw(); void deleteBuckets_() throw(); HashIndex hash_(const Key& key) const throw(); void rehash_() throw(); /** @name Attributes */ //@{ /** The number of entries in the map */ Size size_; /** The maximum number of entries before a resize operation is required */ Size capacity_; /** Buckets are stored as a vector of linked lists of Nodes */ vector bucket_; //@} }; template BALL_INLINE HashMap::HashMap(Size initial_capacity, Size number_of_buckets) throw() : size_(0), capacity_(initial_capacity), bucket_(number_of_buckets) { for (Position bucket = 0; bucket < (Position)bucket_.size(); ++bucket) { bucket_[bucket] = 0; } } template BALL_INLINE HashMap::HashMap(const HashMap& hash_map) throw() : size_(hash_map.size_), capacity_(hash_map.capacity_), bucket_((Size)hash_map.bucket_.size()) { Node* node = 0; for (Position bucket = 0; bucket < (Position)bucket_.size(); ++bucket) { bucket_[bucket] = 0; for (node = hash_map.bucket_[bucket]; node != 0; node = node->next) { bucket_[bucket] = newNode_(node->value, bucket_[bucket]); } } } template void HashMap::clear() throw() { Node* node = 0; Node* next_node = 0; for (Position bucket = 0; bucket < (Position)bucket_.size(); ++bucket) { for (node = bucket_[bucket]; node != 0; node = next_node) { next_node = node->next; deleteNode_(node); } bucket_[bucket] = 0; } size_ = 0; } template BALL_INLINE void HashMap::destroy() throw() { clear(); } template void HashMap::set(const HashMap& hash_map) throw() { if (&hash_map == this) { return; } destroy(); deleteBuckets_(); size_ = hash_map.size_; capacity_ = hash_map.capacity_; bucket_.resize(hash_map.bucket_.size()); Node* node = 0; for (Position bucket = 0; bucket < (Position)bucket_.size(); ++bucket) { bucket_[bucket] = 0; for (node = hash_map.bucket_[bucket]; node != 0; node = node->next) { bucket_[bucket] = newNode_(node->value, bucket_[bucket]); } } } template BALL_INLINE const HashMap& HashMap::operator = (const HashMap& hash_map) throw() { set(hash_map); return *this; } template BALL_INLINE void HashMap::get(HashMap& hash_map) const throw() { hash_map.set(*this); } template BALL_INLINE void HashMap::swap(HashMap& hash_map) throw() { ::std::swap(size_, hash_map.size_); ::std::swap(capacity_, hash_map.capacity_); ::std::swap(bucket_, hash_map.bucket_); } template BALL_INLINE Size HashMap::getBucketSize() const throw() { return (Size)bucket_.size(); } template BALL_INLINE Size HashMap::getCapacity() const throw() { return capacity_; } template BALL_INLINE Size HashMap::getSize() const throw() { return size_; } template BALL_INLINE Size HashMap::size() const throw() { return size_; } template typename HashMap::Iterator HashMap::find(const Key& key) throw() { Iterator it = end(); HashIndex bucket = hash_(key); Node* node_ptr = bucket_[hash_(key)]; for (; node_ptr != 0; node_ptr = node_ptr->next) { if (node_ptr->value.first == key) { it.getTraits().bound_ = this; it.getTraits().position_ = node_ptr; it.getTraits().bucket_ = bucket; break; } } return it; } template BALL_INLINE typename HashMap::ConstIterator HashMap::find(const Key& key) const throw() { return (const_cast(this))->find(key); } template BALL_INLINE T& HashMap::operator [] (const Key& key) throw() { Iterator it = find(key); if (it == end()) { T value; std::pair result = insert(ValueType(key, value)); it = result.first; } return it->second; } template BALL_INLINE const T& HashMap::operator [] (const Key& key) const throw(typename HashMap::IllegalKey) { ConstIterator it = find(key); if (it == end()) { throw IllegalKey(__FILE__, __LINE__); } else { return it->second; } } template ::std::pair::Iterator, bool> HashMap::insert (const ValueType& item) throw() { Iterator it = find(item.first); if (it == end()) { if (needRehashing_() == true) { rehash_(); } HashIndex bucket = hash_(item.first); Node* node_ptr = bucket_[bucket]; bucket_[bucket] = newNode_(item, node_ptr); ++size_; it.getTraits().bound_ = this; it.getTraits().position_ = bucket_[bucket]; it.getTraits().bucket_ = bucket; return ::std::pair(it, true); } else { // replace the existing value it->second = item.second; return ::std::pair(it, false); } } template BALL_INLINE typename HashMap::Iterator HashMap::insert (typename HashMap::Iterator /* pos */, const ValueType& entry) throw() { return insert(entry).first; } template Size HashMap::erase(const Key& key) throw() { Node* previous = 0; HashIndex bucket = hash_(key); Node* node_ptr = bucket_[bucket]; while (node_ptr != 0 && node_ptr->value.first != key) { previous = node_ptr; node_ptr = node_ptr->next; } if (node_ptr == 0) { return false; } if (node_ptr == bucket_[bucket]) { bucket_[bucket] = node_ptr->next; } else { previous->next = node_ptr->next; } deleteNode_(node_ptr); --size_; return true; } template void HashMap::erase(Iterator pos) throw(Exception::IncompatibleIterators, Exception::InvalidIterator) { if (pos.getTraits().bound_ != this) { throw Exception::IncompatibleIterators(__FILE__, __LINE__); } if ((pos == end()) || (size_ == 0)) { return; } if (pos.getTraits().position_ == bucket_[pos.getTraits().bucket_]) { bucket_[pos.getTraits().bucket_] = pos.getTraits().position_->next; } else { // walk over all nodes in this bucket and identify the predecessor // of the node refered to by the iterator pos Node* prev = bucket_[pos.getTraits().bucket_]; for (; (prev != 0) && (prev->next != pos.getTraits().position_); prev = prev->next); if (prev != 0) { // remove the node and reconnect the list prev->next = pos.getTraits().position_->next; } else { throw Exception::InvalidIterator(__FILE__, __LINE__); } } // delete the node and decrement the set size deleteNode_(pos.getTraits().position_); --size_; } template void HashMap::erase(Iterator f, Iterator l) throw(Exception::IncompatibleIterators) { if (f.getTraits().bound_ != this || l.getTraits().bound_ != this) { throw Exception::IncompatibleIterators(__FILE__, __LINE__); } if (f == end()) { return; } Position last_bucket = l.getTraits().bucket_; if (l == end()) { last_bucket = (Position)bucket_.size() - 1; } if (f.getTraits().bucket_ > last_bucket) { // empty range - l < f return; } // count the deleted entries to correct the set size Size no_deletions = 0; Position bucket = f.getTraits().bucket_; for (; bucket <= last_bucket; bucket++) { if (bucket_[bucket] == 0) { // skip all empty buckets continue; } if ((bucket == f.getTraits().bucket_) && (bucket_[bucket] != f.getTraits().position_)) { // find the predecessor of f Node* n = bucket_[bucket]; Node* next; for (; (n->next != f.getTraits().position_) && (n->next != 0); n = n->next); if (bucket == last_bucket) { // delete everything from f to l in this bucket next = n->next; n->next = l.getTraits().position_; for (n = next; (n != 0) && (n != l.getTraits().position_); n = next) { next = n->next; deleteNode_(n); no_deletions++; } } else { // delete everything from f to the end in this bucket if (n != 0) { // mark the end of the list next = n->next; n->next = 0; // delete all remaining nodes for (n = next; n != 0; n = next) { next = n->next; deleteNode_(n); no_deletions++; } } } } // if the current bucket lies between the first and the last bucket... else if (bucket < last_bucket) { // ...delete the whole bucket Node* next; for (Node* n = bucket_[bucket]; n != 0; n = next) { next = n->next; deleteNode_(n); no_deletions++; } bucket_[bucket] = 0; } else if (bucket == last_bucket) { // we delete everything in this bucket up to the iterator l // find the predecessor of l Node* n = bucket_[bucket]; Node* next; for (; (n != 0) && (n != l.getTraits().position_); n = next) { next = n->next; deleteNode_(n); no_deletions++; } bucket_[bucket] = l.getTraits().position_; } } // correct the set size size_ -= no_deletions; } template bool HashMap::apply(UnaryProcessor& processor) throw() { if (processor.start() == false) { return false; } Processor::Result result; Iterator it = begin(); while (it != end()) { result = processor(*it); if (result <= Processor::BREAK) { return (result == Processor::BREAK); } it++; } return processor.finish(); } template void HashMap::host(Visitor >& visitor) throw() { visitor.visit(*this); } template BALL_INLINE bool HashMap::has(const Key& key) const throw() { return (find(key) != end()); } template BALL_INLINE bool HashMap::isEmpty() const throw() { return (size_ == 0); } template bool HashMap::operator == (const HashMap& hash_map) const throw() { if (size_ != hash_map.size_) { return false; } for (ConstIterator it(begin()); it != end(); ++it) { ConstIterator hash_map_it(hash_map.find(it->first)); if ((hash_map_it == hash_map.end()) || (hash_map_it->second != it->second)) { return false; } } return true; } template BALL_INLINE bool HashMap::operator != (const HashMap& hash_map) const throw() { return !(*this == hash_map); } template bool HashMap::isValid() const throw() { Size size = 0; Node* node = 0; for (Position bucket = 0; bucket < (Position)bucket_.size(); ++bucket) { for (node = bucket_[bucket]; node != 0; node = node->next) { ++size; if (node->next == 0) { break; } } } return (size_ == size); } template void HashMap::dump(::std::ostream& s, Size depth) const throw() { BALL_DUMP_STREAM_PREFIX(s); BALL_DUMP_DEPTH(s, depth); BALL_DUMP_DEPTH(s, depth); s << " size: " << getSize() << ::std::endl; BALL_DUMP_DEPTH(s, depth); s << " bucket size: " << getBucketSize() << ::std::endl; BALL_DUMP_DEPTH(s, depth); s << " capacity: " << getCapacity() << ::std::endl; BALL_DUMP_DEPTH(s, depth); if (bucket_.size() != 0) { s << " load factor: " << (float)size_ / (float)bucket_.size() << ::std::endl; } for (Position bucket = 0; bucket < (Position)bucket_.size(); ++bucket) { BALL_DUMP_DEPTH(s, depth); s << " bucket " << bucket << " (" << (void*)bucket_[bucket] << "):" << ::std::endl; } BALL_DUMP_STREAM_SUFFIX(s); } template BALL_INLINE HashIndex HashMap::hash(const Key& key) const throw() { return Hash(key); } template BALL_INLINE void HashMap::rehash() throw() { capacity_ = (Size)getNextPrime((Size)bucket_.size() * 2); } template void HashMap::deleteBuckets_() throw() { Node* node = 0; Node* next_node = 0; for (Position i = 0; i < (Position)bucket_.size(); i++) { node = bucket_[i]; while (node != 0) { next_node = node->next; deleteNode_(node); node = next_node; } bucket_[i] = 0; } } template BALL_INLINE typename HashMap::Node* HashMap::newNode_ (const ValueType& value, typename HashMap::Node* next) const throw() { return new Node(value, next); } template BALL_INLINE void HashMap::deleteNode_(typename HashMap::Node* node) const throw() { delete node; } template BALL_INLINE bool HashMap::needRehashing_() const throw() { return (size_ >= capacity_); } template BALL_INLINE HashIndex HashMap::hash_(const Key& key) const throw() { return (HashIndex)(hash(key) % bucket_.size()); } template void HashMap::rehash_() throw() { // calculate the new number of buckets (in capacity_) rehash(); // save the old contents vector old_buckets(bucket_); // resize the bucket vector and initialize it with zero bucket_.clear(); bucket_.resize(capacity_); Position i; for (i = 0; i < capacity_; i++) { bucket_[i] = 0; } // rehash the old contents into the new buckets Node* node; Node* next_node; for (Position i = 0; i < (Position)old_buckets.size(); ++i) { for (node = old_buckets[i]; node != 0; node = next_node) { next_node = node->next; Position new_bucket = (Position)hash_(node->value.first); node->next = bucket_[new_bucket]; bucket_[new_bucket] = node; } } } } // namespace BALL #endif // BALL_DATATYPE_HASHMAP_H ugene-1.9.8/src/plugins_3rdparty/ball/src/include/BALL/DATATYPE/hashGrid.h0000644000175000017500000013175011651544325024402 0ustar ilyailya// -*- Mode: C++; tab-width: 2; -*- // vi: set ts=2: // // $Id: hashGrid.h,v 1.47 2005-12-23 17:01:42 amoll Exp $ // #ifndef BALL_DATATYPE_HASHGRID_H #define BALL_DATATYPE_HASHGRID_H #ifndef BALL_COMMON_H # include #endif #ifndef BALL_CONCEPT_FORWARDITERATOR_H # include #endif #ifndef BALL_CONCEPT_VISITOR_H # include #endif #ifndef BALL_CONCEPT_PROCESSOR_H # include #endif #ifndef BALL_MATHS_VECTOR3_H # include #endif #ifndef BALL_DATATYPE_LIST_H # include #endif namespace BALL { /** \defgroup GenericHash3D Three-dimensional Hash Grid \ingroup GenericHash */ //@{ /** Grid Box Class. These boxes represent the buckets of a threedimensional hash grid. Every such box contains a linear list of the objects that are contained in this box. This list is accessible through a DataIterator. \par \ingroup GenericHash3D */ template class HashGridBox3 { public: /** @name Constructors and Destructors */ //@{ /// Default constructor HashGridBox3() throw(); /// Copy constructor HashGridBox3(const HashGridBox3& grid_box, bool deep = true) throw(); /// Destructor ~HashGridBox3() throw(); /// Clears the grid box void clear() throw(); /** Clears the grid box. Same as clear. */ void destroy() throw(); //@} /** @name Assignment */ //@{ /// void set(const HashGridBox3& box,bool /* deep */ = true) throw(Exception::NotImplemented); /// const HashGridBox3& operator = (const HashGridBox3& box) throw(Exception::NotImplemented); //@} /** @name Accessors */ //@{ /** Find an item in the item list of this grid box. @param item the item to be searched for @return a pointer to the desired item or a NULL pointer, if the item could not be found. */ Item* find(const Item &item) throw(); /// The const version of find() const Item* find(const Item& item) const throw(); /** Counts all items in the data item list. @return the size of the data item list. */ Size getSize() const throw(); /** Insert an item into the data item list of a grid box. @param item the item to be inserted */ void insert(const Item& item) throw(); /** Remove the first occurrence of a certain item from the data item list. @param item the item to be removed @return bool - true, if the item could be removed, false otherwise. */ bool remove(const Item& item) throw(); /** Remove all occurences of a certain item from the data item list. @param item the item to be removed @return bool - true, if the item could be removed, false otherwise. */ bool removeAll(const Item& item) throw(); //@} /** @name Miscellaneous */ //@{ /// Host method void host(Visitor &visitor) throw(); //@} /** @name Predicates */ //@{ /// Equality operator bool operator == (const HashGridBox3& box) const throw(); /// Inequality operator bool operator != (const HashGridBox3& box) const throw(); /** Test whether an item is in the data item list @param item @return bool - true if instance has item, false otherwise. */ bool has(const Item& item) const throw(); /** Test, whether this box is empty, i. e. the data item list contains nothing @return bool - true, if this is empty. false otherwise. */ bool isEmpty() const throw(); //@} /** @name Debugging and Diagnostics */ //@{ /// bool isValid() const throw(); /// void dump(std::ostream& s = std::cout, Size depth = 0) const throw(); //@} /** @name Internal Iterators */ //@{ /// bool apply(UnaryProcessor& processor) throw(); /// bool apply(UnaryProcessor< HashGridBox3 >& processor) throw(); //@} /** @name External Iterators */ //@{ /// ????? class DataItem { public: DataItem(const Item& item, DataItem* next) throw() : item_(item), previous_(0), next_(next) { if (next_ != 0) { next_->previous_ = this; } } Item item_; DataItem* previous_; DataItem* next_; }; /// ????? class NeighborBoxItem { public: NeighborBoxItem(HashGridBox3* box, NeighborBoxItem* next) throw() : box_(box), previous_(0), next_(next) { if (next_ != 0) { next_->previous_ = this; } } HashGridBox3* box_; NeighborBoxItem* previous_; NeighborBoxItem* next_; }; typedef NeighborBoxItem* BoxIteratorPosition; class BoxIteratorTraits { public: BALL_CREATE_DEEP(BoxIteratorTraits) virtual ~BoxIteratorTraits() throw () {} BoxIteratorTraits() throw() : bound_(0), position_(0) { } BoxIteratorTraits(const HashGridBox3& box) throw() : bound_((HashGridBox3 *)&box), position_(0) { } BoxIteratorTraits(const BoxIteratorTraits& traits, bool /* deep */ = true) throw() : bound_(traits.bound_), position_(traits.position_) { } const BoxIteratorTraits& operator = (const BoxIteratorTraits& traits) throw() { bound_ = traits.bound_; position_ = traits.position_; return *this; } HashGridBox3* getContainer() throw() { return bound_; } const HashGridBox3* getContainer() const throw() { return bound_; } bool isSingular() const throw() { return (bound_ == 0); } BoxIteratorPosition& getPosition() throw() { return position_; } const BoxIteratorPosition& getPosition() const throw() { return position_; } bool operator == (const BoxIteratorTraits& traits) const throw() { return (position_ == traits.position_); } bool operator != (const BoxIteratorTraits& traits) const throw() { return (position_ != traits.position_); } bool isValid() const throw() { return (bound_ != 0 && position_ != 0); } void invalidate() throw() { bound_ = 0; position_ = 0; } void toBegin() throw() { position_ = bound_->first_neighbor_; } bool isBegin() const throw() { return (position_ == bound_->first_neighbor_); } void toEnd() throw() { position_ = 0; } bool isEnd() const throw() { return (position_ == 0); } HashGridBox3& getData() throw() { return *(position_->box_); } const HashGridBox3& getData() const throw() { return *(position_->box_); } void forward() throw() { position_ = position_->next_; } private: HashGridBox3 *bound_; BoxIteratorPosition position_; }; friend class BoxIteratorTraits; /** BoxIterators iterate over all non-empty boxes that lie in the direct neighborhood to a box. Such an iterator traverses at most 26 boxes. */ typedef ForwardIterator , HashGridBox3, BoxIteratorPosition, BoxIteratorTraits> BoxIterator; /// get the first non-empty box BoxIterator beginBox() throw() { return BoxIterator::begin(*this); } /// get the last non-empty box BoxIterator endBox() throw() { return BoxIterator::end(*this); } /// This is the const version of \link BoxIterator BoxIterator \endlink typedef ConstForwardIterator , HashGridBox3, BoxIteratorPosition, BoxIteratorTraits> ConstBoxIterator; /// get the first non-empty box ConstBoxIterator beginBox() const throw() { return ConstBoxIterator::begin(*this); } /// get the last non-empty box ConstBoxIterator endBox() const throw() { return ConstBoxIterator::end(*this); } typedef DataItem* DataIteratorPosition; class DataIteratorTraits { public: BALL_CREATE_DEEP(DataIteratorTraits) virtual ~DataIteratorTraits() throw() {} DataIteratorTraits() throw() : bound_(0), position_(0) { } DataIteratorTraits(const HashGridBox3& box) throw() : bound_((HashGridBox3 *)&box), position_(0) { } DataIteratorTraits(const DataIteratorTraits& traits, bool /* deep */ = true) throw() : bound_(traits.bound_), position_(traits.position_) { } const DataIteratorTraits& operator = (const DataIteratorTraits &traits) throw() { bound_ = traits.bound_; position_ = traits.position_; return *this; } HashGridBox3* getContainer() throw() { return bound_; } const HashGridBox3* getContainer() const throw() { return bound_; } bool isSingular() const throw() { return (bound_ == 0); } DataIteratorPosition& getPosition() throw() { return position_; } const DataIteratorPosition& getPosition() const throw() { return position_; } bool operator == (const DataIteratorTraits &traits) const throw() { return (position_ == traits.position_); } bool operator != (const DataIteratorTraits &traits) const throw() { return (position_ != traits.position_); } bool isValid() const throw() { return (bound_ != 0 && position_ != 0); } void invalidate() throw() { bound_ = 0; position_ = 0; } void toBegin() throw() { position_ = bound_->first_item_; } bool isBegin() const throw() { return (position_ == bound_->first_item_); } void toEnd() throw() { position_ = 0; } bool isEnd() const throw() { return (position_ == 0); } Item& getData() throw() { return position_->item_; } const Item& getData() const throw() { return position_->item_; } void forward() throw() { position_ = position_->next_; } private: HashGridBox3* bound_; DataIteratorPosition position_; }; friend class DataIteratorTraits; /** Data iterator for grid boxes. This iterator traverses the list of data items store in a \link HashGridBox3 HashGridBox3 \endlink . */ typedef ForwardIterator , Item, DataIteratorPosition, DataIteratorTraits> DataIterator; /// DataIterator beginData() throw() { return DataIterator::begin(*this); } /// DataIterator endData() throw() { return DataIterator::end(*this); } /** Const data iterator for grid boxes. This is the const version of \link DataIterator DataIterator \endlink */ typedef ConstForwardIterator , Item, DataIteratorPosition, DataIteratorTraits> ConstDataIterator; /// ConstDataIterator beginData() const throw() { return ConstDataIterator::begin(*this); } /// ConstDataIterator endData() const throw() { return ConstDataIterator::end(*this); } //@} //_ HashGridBox3 *previous_; //_ HashGridBox3 *next_; // private: void insert_(HashGridBox3 *box) throw(); bool remove_(HashGridBox3 *box) throw(); NeighborBoxItem* first_neighbor_; DataItem* first_item_; }; template HashGridBox3::HashGridBox3() throw() : previous_(0), next_(0), first_neighbor_(0), first_item_(0) { } template HashGridBox3::HashGridBox3(const HashGridBox3& box, bool deep) throw() : previous_(0), next_(0), first_neighbor_(0), first_item_(0) { set(box, deep); } template HashGridBox3::~HashGridBox3() throw() { clear(); } template void HashGridBox3::clear() throw() { for (NeighborBoxItem* next = 0; first_neighbor_ != 0; first_neighbor_ = next) { next = first_neighbor_->next_; delete first_neighbor_; } for (DataItem* next_item = 0; first_item_ != 0; first_item_ = next_item) { next_item = first_item_->next_; delete first_item_; } } template BALL_INLINE void HashGridBox3::destroy() throw() { clear(); } template void HashGridBox3::set(const HashGridBox3& box, bool deep) throw(Exception::NotImplemented) { // ????? - not implemented throw Exception::NotImplemented(__FILE__, __LINE__); } template BALL_INLINE const HashGridBox3& HashGridBox3::operator = (const HashGridBox3& box) throw(Exception::NotImplemented) { set(box); return *this; } template Item* HashGridBox3::find(const Item& item) throw() { for (DataItem* item_ptr= first_item_; item_ptr != 0; item_ptr = item_ptr->next_) { if (item_ptr->item_ == item) { return &(item_ptr->item_); } } return 0; } template BALL_INLINE const Item* HashGridBox3::find(const Item& item) const throw() { return const_cast(this)->find(item); } template Size HashGridBox3::getSize() const throw() { Size size = 0; // count all items in the box for (const DataItem* item = first_item_; item != 0; item = item->next_, size++); return size; } template BALL_INLINE void HashGridBox3::insert(const Item& item) throw() { first_item_ = new DataItem(item, first_item_); } template bool HashGridBox3::remove(const Item& item) throw() { for (DataItem* item_ptr = first_item_; item_ptr != 0; item_ptr = item_ptr->next_) { if (item_ptr->item_ == item) { if (item_ptr == first_item_) { first_item_ = first_item_->next_; } if (item_ptr->next_ != 0) { item_ptr->next_->previous_ = item_ptr->previous_; } if (item_ptr->previous_ != 0) { item_ptr->previous_->next_ = item_ptr->next_; } delete item_ptr; return true; } } return false; } template bool HashGridBox3::removeAll(const Item& item) throw() { bool found = false; DataItem* next_item = 0; DataItem* item_ptr = first_item_; while(item_ptr != 0) { next_item = item_ptr->next_; if (item_ptr->item_ == item) { if (item_ptr == first_item_) { first_item_ = first_item_->next_; } if (item_ptr->next_ != 0) { item_ptr->next_->previous_ = item_ptr->previous_; } if (item_ptr->previous_ != 0) { item_ptr->previous_->next_ = item_ptr->next_; } delete item_ptr; found = true; } item_ptr = next_item; } return found; } template BALL_INLINE void HashGridBox3::host(Visitor< HashGridBox3 >& visitor) throw() { visitor.visit(*this); } template bool HashGridBox3::operator == (const HashGridBox3& box) const throw() { const DataItem* a = first_item_; const DataItem* b = box.first_item_; for (; a != 0 && b != 0; a = a->next_, b = b->next_) { if (a->item_ != b->item_) { return false; } } return (a == b); } template BALL_INLINE bool HashGridBox3::operator != (const HashGridBox3& box) const throw() { return !(*this == box); } template BALL_INLINE bool HashGridBox3::has(const Item& item) const throw() { return (find(item) != 0); } template BALL_INLINE bool HashGridBox3::isEmpty() const throw() { return (first_item_ == 0); } template bool HashGridBox3::isValid() const throw() { Size size = 0; NeighborBoxItem* item_ptr_ = 0; for (item_ptr_ = first_neighbor_; item_ptr_ != 0; item_ptr_ = item_ptr_->next_) { ++size; if (item_ptr_->next_ == 0) { break; } } for (; item_ptr_ != 0; item_ptr_ = item_ptr_->previous_, --size); if (size != 0) { return false; } size = 0; DataItem* item = 0; for (item = first_item_; item != 0; item = item->next_) { ++size; if (item->next_ == 0) { break; } } for (; item != 0; item = item->previous_, --size); return (size == 0); } template void HashGridBox3::dump(std::ostream& s, Size depth) const throw() { BALL_DUMP_STREAM_PREFIX(s); BALL_DUMP_DEPTH(s, depth); BALL_DUMP_DEPTH(s, depth); s << " size: " << getSize() << std::endl; BALL_DUMP_DEPTH(s, depth); s << " data:" << std::endl; for (DataItem *item = first_item_; item != 0; item = item->next_) { BALL_DUMP_DEPTH(s, depth); s << " " << item->item_ << std::endl; } BALL_DUMP_DEPTH(s, depth); s << " neighbor boxes:" << std::endl; for (NeighborBoxItem *item_ptr_ = first_neighbor_; item_ptr_ != 0; item_ptr_ = item_ptr_->next_) { BALL_DUMP_DEPTH(s, depth); s << " " << item_ptr_->box_ << std::endl; } BALL_DUMP_STREAM_SUFFIX(s); } template bool HashGridBox3::apply(UnaryProcessor& processor) throw() { if (processor.start() == false) { return false; } Processor::Result result; for (DataItem *item = first_item_; item != 0; item = item->next_) { result = processor(item->item_); if (result <= Processor::BREAK) { return (result == Processor::BREAK) ? true : false; } } return processor.finish(); } template bool HashGridBox3::apply(UnaryProcessor< HashGridBox3 >& processor) throw() { if (processor.start() == false) { return false; } Processor::Result result; for (NeighborBoxItem* neighbor_item = first_neighbor_; neighbor_item != 0; neighbor_item = neighbor_item->next_) { result = processor(*(neighbor_item->box_)); if (result <= Processor::BREAK) { return (result == Processor::BREAK) ? true : false; } } return processor.finish(); } template BALL_INLINE void HashGridBox3::insert_(HashGridBox3* box) throw() { first_neighbor_ = new NeighborBoxItem(box, first_neighbor_); } template bool HashGridBox3::remove_(HashGridBox3* box) throw() { for (NeighborBoxItem* neighbor_item = first_neighbor_; neighbor_item != 0; neighbor_item = neighbor_item->next_) { if (neighbor_item->box_ == box) { if (neighbor_item == first_neighbor_) { first_neighbor_ = first_neighbor_->next_; } if (neighbor_item->next_ != 0) { neighbor_item->next_->previous_ = neighbor_item->previous_; } if (neighbor_item->previous_ != 0) { neighbor_item->previous_->next_ = neighbor_item->next_; } delete neighbor_item; return true; } } return false; } /** Three-dimensional Hash Grid Class. ????? \par */ template class HashGrid3 { public: BALL_CREATE(HashGrid3) /** @name Constructors and destructor */ //@{ /// Default constructor HashGrid3() throw(); /** Constructor using origin, dimensions, and spacings of the grid. It creates a hashgrid at origin with axis-dependant spacings. @param origin @param dimension_x @param dimension_y @param dimension_z @param spacing_x @param spacing_y @param spacing_z */ HashGrid3(const Vector3& origin, Size dimension_x, Size dimension_y, Size dimension_z, float spacing_x, float spacing_y, float spacing_z) throw(); /** Constructor using origin, dimensions, and a single spacing (only cubic grids) */ HashGrid3(const Vector3& origin, Size dimension_x, Size dimension_y, Size dimension_z, float spacing) throw(); /** Constructor using two vectors and a single spacing. This constructor creates a hash grid at origin with spacing spacing. The vector size has to be relative to origin and defines the opposite corner of the grid, thereby setting the size of the grid. @param origin a vector defining the origin of our cubic hash grid @param size a vector defining the opposite corner of the cubic grid @param spacing this float will be used as spacing in all three dimensions */ HashGrid3(const Vector3& origin, const Vector3& size, float spacing) throw(); /// Copy constructor HashGrid3(const HashGrid3& grid, bool deep = true) throw(); /// Destructor virtual ~HashGrid3() throw(); /// Clears the whole grid virtual void clear() throw(); /// Clears the HashGridBox3 at position (x, y, z) void clear(Position x, Position y, Position z) throw(); /// Clears the HashGridBox3 at position vector void clear(const Vector3 &vector) throw(); /// Destroys the grid (obsolete, only calls clear()) void destroy() throw(); /// Destroys a box of the grid (obsolete, only calls clear()) void destroy(Position x, Position y, Position z) throw(); /// Destroys a box of the grid (obsolete, only calls clear()) void destroy(const Vector3& vector) throw(); //@} /** @name Assignment */ //@{ /// assigns the content of a hash grid (obsolete) void set(const Vector3& origin, const Vector3& unit, Size dimension_x, Size dimension_y, Size dimension_z) throw(); /// assigns the content of a hash grid (obsolete) void set(const Vector3& origin, float unit, Size size) throw(); /// assigns the content of a hash grid (obsolete) void set(const HashGrid3& grid, bool deep = true) throw(); /// Assignment operator const HashGrid3& operator = (const HashGrid3& grid) throw(); /// void get(Vector3& origin, Vector3& unit, Size& dimension_x, Size& dimension_y, Size& dimension_z) const throw(); /// void get(HashGrid3& grid, bool deep = true) const throw(); //@} /** @name Accessors */ //@{ /// Counts the non-empty boxes of a grid. Size countNonEmptyBoxes() const throw(); /// Returns the size of a grid, i. e. ????? Size getSize() const throw(); /// Returns the origin of the grid Vector3& getOrigin() throw(); /// Returns a const reference of the grid origin const Vector3& getOrigin() const throw(); /// Returns the unit of the grid Vector3& getUnit() throw(); /// Returns the unit of the grid (const version) const Vector3& getUnit() const throw(); /// Get the x dimension of the grid Size getSizeX() const throw(); /// Get the y dimension of the grid Size getSizeY() const throw(); /// Get the z dimension of the grid Size getSizeZ() const throw(); /// Return the HashGridBox3 at position (x, y, z) HashGridBox3* getBox(Position x, Position y, Position z) throw(); /// Return the HashGridBox3 at position (x, y, z) (const version) const HashGridBox3* getBox(Position x, Position y, Position z) const throw(); /// Return the HashGridBox3 at position vector HashGridBox3* getBox(const Vector3& vector) throw(); /// Return the HashGridBox3 at position vector (const version) const HashGridBox3* getBox(const Vector3 &vector) const throw(); /// Get the position indices of a HashGridBox3 bool getIndices(const HashGridBox3& box, Position& x, Position& y, Position& z) const throw(); /// Insert an item at position (x, y, z) void insert(Position x, Position y, Position z, const Item& item) throw(); /// Insert an item at position vector void insert(const Vector3& vector, const Item& item) throw(); /// Remove an item from position (x, y ,z) bool remove(Position x, Position y, Position z, const Item& item) throw(); /// Remove an item from position vector bool remove(const Vector3& vector, const Item& item) throw(); //@} /** @name Miscellaneous */ //@{ /// void host(Visitor& visitor) throw(); //@} /** @name Predicates */ //@{ /// Equality operator bool operator == (const HashGrid3& grid) const throw(); /// Inequality operator bool operator != (const HashGrid3& grid) const throw(); /// Tests, whether this is empty bool isEmpty() const throw(); //@} /** @name Debugging and Diagnostics */ //@{ /// Validity check virtual bool isValid() const throw(); /// Dump the contents of a HashGrid3 to a stream virtual void dump(std::ostream& s = std::cout, Size depth = 0) const throw(); //@} /** @name Internal Iterators */ //@{ /// bool apply(UnaryProcessor &processor) throw(); /// bool apply(UnaryProcessor< HashGridBox3 > &processor) throw(); /** Get the nearest item for a point @param distance number of adjacted boxes in each direction to search in */ const Item* getClosestItem(const Vector3& point, Size distance) const throw(); /** Calculate the minimum required spacing to build a HashGrid3 with the given size and less than the given memory consumption. @param memory the amount of memory in bytes @param size the diagonal of the grid @return the minimal needed spacing */ static float calculateMinSpacing(LongIndex memory, const Vector3& size) throw(); //@} /** @name External Iterators */ //@{ typedef HashGridBox3* BoxIteratorPosition; class BoxIteratorTraits { public: BALL_CREATE_DEEP(BoxIteratorTraits) virtual ~BoxIteratorTraits() throw() {} BoxIteratorTraits() throw() : bound_(0), position_(0) { } BoxIteratorTraits(const HashGrid3 &grid) throw() : bound_((HashGrid3 *)&grid), position_(0) { } BoxIteratorTraits(const BoxIteratorTraits& traits, bool /* deep */ = true) throw() : bound_(traits.bound_), position_(traits.position_) { } const BoxIteratorTraits& operator = (const BoxIteratorTraits& traits) throw() { bound_ = traits.bound_; position_ = traits.position_; return *this; } HashGrid3* getContainer() throw() { return bound_; } const HashGrid3* getContainer() const throw() { return bound_; } bool isSingular() const throw() { return (bound_ == 0); } BoxIteratorPosition& getPosition() throw() { return position_; } const BoxIteratorPosition& getPosition() const throw() { return position_; } bool operator == (const BoxIteratorTraits& traits) const throw() { return (position_ == traits.position_); } bool operator != (const BoxIteratorTraits& traits) const throw() { return (position_ != traits.position_); } bool isValid() const throw() { return (bound_ != 0 && position_ != 0); } void invalidate() throw() { bound_ = 0; position_ = 0; } void toBegin() throw() { position_ = bound_->first_nonempty_; } bool isBegin() const throw() { return (position_ == bound_->first_nonempty_); } void toEnd() throw() { position_ = 0; } bool isEnd() const throw() { return (position_ == 0); } HashGridBox3& getData() throw() { return *position_; } const HashGridBox3& getData() const throw() { return *position_; } void forward() throw() { position_ = position_->next_; } private: HashGrid3* bound_; BoxIteratorPosition position_; }; friend class BoxIteratorTraits; /// typedef ForwardIterator , HashGridBox3, BoxIteratorPosition, BoxIteratorTraits> BoxIterator; /// BoxIterator beginBox() throw() { return BoxIterator::begin(*this); } /// BoxIterator endBox() throw() { return BoxIterator::end(*this); } /// typedef ConstForwardIterator , HashGridBox3, BoxIteratorPosition, BoxIteratorTraits> ConstBoxIterator; /// ConstBoxIterator beginBox() const throw() { return ConstBoxIterator::begin(*this); } /// ConstBoxIterator endBox() const throw() { return ConstBoxIterator::end(*this); } //@} private: //_ Index getIndex_(const HashGridBox3& box) const throw(); //_ void insert_(HashGridBox3* box, const Item& item) throw(); //_ bool remove_(HashGridBox3* box, const Item& item) throw(); //_ HashGridBox3* box_; //_ HashGridBox3* first_nonempty_; //_ Vector3 origin_; //_ Vector3 unit_; //_ Size dimension_x_; //_ Size dimension_y_; //_ Size dimension_z_; }; //@} template HashGrid3::HashGrid3() throw() : box_(0), first_nonempty_(0), origin_(0,0,0), unit_(0,0,0), dimension_x_(0), dimension_y_(0), dimension_z_(0) { } template HashGrid3::HashGrid3 (const Vector3 &originvector, Size dimension_x, Size dimension_y, Size dimension_z, float spacing_x, float spacing_y, float spacing_z) throw() : box_(0), first_nonempty_(0), origin_(originvector), unit_(spacing_x, spacing_y, spacing_z), dimension_x_(dimension_x), dimension_y_(dimension_y), dimension_z_(dimension_z) { box_ = new HashGridBox3[dimension_x * dimension_y * dimension_z]; } template HashGrid3::HashGrid3 (const Vector3& origin, Size dimension_x, Size dimension_y, Size dimension_z, float spacing) throw() : box_(0), first_nonempty_(0), origin_(origin), unit_(spacing, spacing, spacing), dimension_x_(dimension_x), dimension_y_(dimension_y), dimension_z_(dimension_z) { box_ = new HashGridBox3[dimension_x * dimension_y * dimension_z]; } // this constructor creates a linear array of HashGridBox3 objects. template HashGrid3::HashGrid3(const Vector3& origin, const Vector3& size, float spacing) throw() : box_(0), first_nonempty_(0), origin_(origin), unit_(spacing, spacing, spacing), dimension_x_((Size)(size.x / spacing + 1.0)), dimension_y_((Size)(size.y / spacing + 1.0)), dimension_z_((Size)(size.z / spacing + 1.0)) { box_ = new HashGridBox3[dimension_x_ * dimension_y_ * dimension_z_]; } template HashGrid3::HashGrid3(const HashGrid3& grid, bool deep) throw() : box_(0), first_nonempty_(0), origin_(), unit_() { set(grid, deep); } template HashGrid3::~HashGrid3() throw() { clear(); delete [] box_; } template void HashGrid3::clear() throw() { if (box_ != 0) { for(HashGridBox3* nextbox = 0; first_nonempty_ != 0; first_nonempty_ = nextbox) { nextbox = first_nonempty_->next_; first_nonempty_->previous_ = first_nonempty_->next_ = 0; } Size size = dimension_x_ * dimension_y_ * dimension_z_; for (Position index = 0; index < (Position)size; ++index) { box_[index].clear(); } } } template BALL_INLINE void HashGrid3::clear(Position x, Position y, Position z) throw() { HashGridBox3* box = getBox(x, y, z); if (box != 0) { box->clear(); if (box->previous_ != 0) { box->previous_->next_ = box->next_; } else { first_nonempty_ = box->next_; } if (box->next_ != 0) { box->next_->previous_ = box->previous_; } box->previous_ = box->next_ = 0; } } template BALL_INLINE void HashGrid3::clear(const Vector3& vector) throw() { HashGridBox3* box = getBox(vector); if (box != 0) { box->clear(); if (box->previous_ != 0) { box->previous_->next_ = box->next_; } else { first_nonempty_ = box->next_; } if (box->next_ != 0) { box->next_->previous_ = box->previous_; } box->previous_ = box->next_ = 0; } } template BALL_INLINE void HashGrid3::destroy() throw() { clear(); } template BALL_INLINE void HashGrid3::destroy(Position x, Position y, Position z) throw() { clear(x, y, z); } template BALL_INLINE void HashGrid3::destroy(const Vector3 &vector) throw() { clear(vector); } template void HashGrid3::set (const Vector3& origin, const Vector3& unit, Size dimension_x, Size dimension_y, Size dimension_z) throw() { clear(); if (box_ != 0) { delete [] box_; } origin_.set(origin); unit_.set(unit); dimension_x_ = dimension_x; dimension_y_ = dimension_y; dimension_z_ = dimension_z; Size n = getSize(); box_ = new HashGridBox3 [n]; } template void HashGrid3::set(const Vector3& origin, float unit, Size size) throw() { clear(); if (box_ != 0) { delete [] box_; } origin_.set(origin); unit_.set(unit, unit, unit); dimension_x_ = size; dimension_y_ = size; dimension_z_ = size; box_ = new HashGridBox3[getSize()]; } template void HashGrid3::set(const HashGrid3& grid, bool /* deep */) throw() { set(grid.origin_, grid.unit_, grid.dimension_x_, grid.dimension_y_, grid.dimension_z_); const HashGridBox3* sourcebox = grid.box_; HashGridBox3* targetbox = box_; const HashGridBox3* endbox = &grid.box_[grid.getSize()]; for (; sourcebox < endbox; ++sourcebox, ++targetbox) { if (sourcebox->isEmpty() == false) { for (typename HashGridBox3::DataItem* item = sourcebox->first_item_; item != 0; item = item->next_) { insert_(targetbox, item->item_); } } } } template BALL_INLINE const HashGrid3& HashGrid3::operator = (const HashGrid3 &grid) throw() { set(grid); return *this; } template BALL_INLINE void HashGrid3::get(Vector3 &origin, Vector3 &unit, Size& dimension_x, Size& dimension_y, Size& dimension_z) const throw() { origin.set(origin_); unit.set(unit_); dimension_x = dimension_x_; dimension_y = dimension_y_; dimension_z = dimension_z_; } template BALL_INLINE void HashGrid3::get(HashGrid3 &grid, bool deep) const throw() { grid.set(*this, deep); } template Size HashGrid3::countNonEmptyBoxes() const throw() { Size size = 0; for(HashGridBox3* box = first_nonempty_; box != 0; box = box->next_) { ++size; } return size; } template BALL_INLINE Size HashGrid3::getSize() const throw() { return (dimension_x_ * dimension_y_ * dimension_z_); } template BALL_INLINE Vector3& HashGrid3::getOrigin() throw() { return origin_; } template BALL_INLINE const Vector3& HashGrid3::getOrigin() const throw() { return origin_; } template BALL_INLINE Vector3& HashGrid3::getUnit() throw() { return unit_; } template BALL_INLINE const Vector3& HashGrid3::getUnit() const throw() { return unit_; } template BALL_INLINE Size HashGrid3::getSizeX() const throw() { return dimension_x_; } template BALL_INLINE Size HashGrid3::getSizeY() const throw() { return dimension_y_; } template BALL_INLINE Size HashGrid3::getSizeZ() const throw() { return dimension_z_; } template const Item* HashGrid3::getClosestItem(const Vector3& point, Size dist) const throw() { const HashGridBox3* box = getBox(point); if (!box) return 0; Position x, y, z; getIndices(*box, x, y, z); const Item* item = 0; float distance = FLT_MAX; // iterator over neighbour boxes for (Index xi = -(Index)dist; xi <= (Index)dist; xi++) { const Index xn = x + xi; for (Index yi = -(Index)dist; yi <= (Index)dist; yi++) { const Index yn = y + yi; for (Index zi = -(Index)dist; zi <= (Index)dist; zi++) { // iterate over all data items const HashGridBox3* const box_ptr = getBox(xn, yn, z+zi); if (box_ptr != 0 && !box_ptr->isEmpty()) { typename HashGridBox3::ConstDataIterator hit = box_ptr->beginData(); for (;hit != box_ptr->endData(); hit++) { const float new_dist = ((*hit)->getPosition() - point).getSquareLength(); if (new_dist < distance) { item = &*hit; distance = new_dist; } } } } } } return item; } template BALL_INLINE float HashGrid3::calculateMinSpacing(LongIndex memory, const Vector3& size) throw() { LongSize memory_for_box = sizeof(HashGridBox3) + sizeof(HashGridBox3*); LongSize nr_boxes =(LongSize)floor((float)(memory / memory_for_box)); return pow((double)((size.x * size.y * size.z) / nr_boxes), (double)(1.0 / 3.0)); } template BALL_INLINE HashGridBox3* HashGrid3::getBox(Position x, Position y, Position z) throw() { if (x >= (Position)dimension_x_ || y >= (Position)dimension_y_ || z >= (Position)dimension_z_) { return 0; } else { return &(box_[x * dimension_y_ * dimension_z_ + y * dimension_z_ + z]); } } template BALL_INLINE const HashGridBox3* HashGrid3::getBox(Position x, Position y, Position z) const throw() { return ((HashGrid3*)this)->getBox(x, y, z); } template BALL_INLINE HashGridBox3* HashGrid3::getBox(const Vector3& vector) throw() { float x = (vector.x - origin_.x) / unit_.x; float y = (vector.y - origin_.y) / unit_.y; float z = (vector.z - origin_.z) / unit_.z; // workaround for MSVC 7, dont change this !!! Index x1 = (Index) Maths::floor(x); Index y1 = (Index) Maths::floor(y); Index z1 = (Index) Maths::floor(z); return getBox(x1, y1, z1); } template BALL_INLINE const HashGridBox3* HashGrid3::getBox(const Vector3& vector) const throw() { return ((HashGrid3 *)this)->getBox(vector); } template BALL_INLINE bool HashGrid3::getIndices (const HashGridBox3& box, Position& x, Position& y, Position& z) const throw() { Index index = getIndex_(box); if (index == INVALID_INDEX) { x = y = z = INVALID_POSITION; return false; } x = index / (dimension_y_ * dimension_z_); index -= x * dimension_y_ * dimension_z_; y = index / dimension_z_; z = index - y * dimension_z_; return true; } template BALL_INLINE void HashGrid3::insert (Position x, Position y, Position z, const Item& item) throw() { HashGridBox3* box = getBox(x, y, z); if (box != 0) { insert_(box, item); } } template BALL_INLINE void HashGrid3::insert(const Vector3& vector, const Item& item) throw() { HashGridBox3 *box = getBox(vector); if (box != 0) { insert_(box, item); } } template BALL_INLINE bool HashGrid3::remove(Position x, Position y, Position z, const Item& item) throw() { HashGridBox3* box = getBox(x, y, z); if (box != 0) { return remove_(box, item); } return false; } template BALL_INLINE bool HashGrid3::remove(const Vector3& vector, const Item& item) throw() { HashGridBox3* box = getBox(vector); if (box != 0) { return remove_(box, item); } return false; } template BALL_INLINE void HashGrid3::host(Visitor< HashGrid3 >& visitor) throw() { visitor.visit(*this); } template BALL_INLINE bool HashGrid3::operator == (const HashGrid3& grid) const throw() { if (getSize() != grid.getSize() || origin_ != grid.origin_ || unit_ != grid.unit_ || dimension_x_ != grid.dimension_x_ || dimension_y_ != grid.dimension_y_ || dimension_z_ != grid.dimension_z_) { return false; } const HashGridBox3* abox = box_; const HashGridBox3* bbox = grid.box_; const HashGridBox3* endbox = &box_[getSize()]; while (abox < endbox) { if (*abox++ != *bbox++) { return false; } } return true; } template BALL_INLINE bool HashGrid3::operator != (const HashGrid3& grid) const throw() { return !(*this == grid); } template BALL_INLINE bool HashGrid3::isEmpty() const throw() { return (getSize() == 0); } template bool HashGrid3::isValid() const throw() { Size size = getSize(); for (Position index = 0; index < (Position)size; ++index) { if (box_[index].isValid() == false) { return false; } } const HashGridBox3* box = box_; Size nonempty_boxes = 0; for (; box < &box_[size]; ++box) { if (box->isEmpty() == false) { ++nonempty_boxes; } } if (nonempty_boxes != countNonEmptyBoxes()) { return false; } for (box = first_nonempty_; box != 0; box = box->next_) { if (box->next_ == 0) { break; } } for (; box != 0; box = box->previous_) { if (box->previous_ == 0) { break; } } return (box == first_nonempty_); } template void HashGrid3::dump(std::ostream& s, Size depth) const throw() { BALL_DUMP_STREAM_PREFIX(s); BALL_DUMP_DEPTH(s, depth); BALL_DUMP_DEPTH(s, depth); s << " origin: " << origin_ << std::endl; BALL_DUMP_DEPTH(s, depth); s << " unit: " << unit_.z << std::endl; BALL_DUMP_DEPTH(s, depth); s << " dimension: " << dimension_x_ << " " << dimension_y_ << " " << dimension_z_ << std::endl; Size size = getSize(); BALL_DUMP_DEPTH(s, depth); s << " size: " << size << std::endl; BALL_DUMP_DEPTH(s, depth); s << " non empty boxes: " << countNonEmptyBoxes() << std::endl; BALL_DUMP_DEPTH(s, depth); s << " boxes:" << std::endl; Position x, y, z; for (Position index = 0; index < (Position)size; ++index) { BALL_DUMP_DEPTH(s, depth); getIndices(box_[index], x, y, z); s << " " << index << ". box: (" << x << ',' << y << ',' << z << ')' << std::endl; box_[index].dump(s, 1); } BALL_DUMP_DEPTH(s, depth); s << " non-empty boxes:" << std::endl; for (const HashGridBox3* box = first_nonempty_; box != 0; box = box->next_) { s << " " << getIndex_(*box) << std::endl; } BALL_DUMP_STREAM_SUFFIX(s); } template bool HashGrid3::apply(UnaryProcessor& processor) throw() { if (processor.start() == false) { return false; } Processor::Result result; for (HashGridBox3* box = first_nonempty_; box != 0; box = box->next_) { for (typename HashGridBox3::DataItem *item = box->first_item_; item != 0; item = item->next_) { result = processor(item->item_); if (result <= Processor::BREAK) { return (result == Processor::BREAK) ? true : false; } } } return processor->finish(); } template bool HashGrid3::apply(UnaryProcessor< HashGridBox3 >& processor) throw() { if (processor.start() == false) { return false; } Processor::Result result; for (HashGridBox3* box = first_nonempty_; box != 0; box = box->next_) { result = processor(*box); if (result <= Processor::BREAK) { return (result == Processor::BREAK) ? true : false; } } return processor->finish(); } template BALL_INLINE Index HashGrid3::getIndex_(const HashGridBox3& box) const throw() { if (&box < box_ ||& box >= &box_[getSize()]) { return INVALID_INDEX; } else { return (Index)(&box - box_); } } template BALL_INLINE void HashGrid3::insert_(HashGridBox3* box, const Item& item) throw() { if (box->isEmpty() == true) { box->previous_ = 0; box->next_ = first_nonempty_; if (first_nonempty_ != 0) { first_nonempty_->previous_ = box; } first_nonempty_ = box; Position end_x, end_y, end_z; getIndices(*box, end_x, end_y, end_z); ++end_x; ++end_y; ++end_z; HashGridBox3* neighborbox = 0; for (Position x = end_x - 2; x <= end_x; ++x) { for (Position y = end_y - 2; y <= end_y; ++y) { for (Position z = end_z - 2; z <= end_z; ++z) { neighborbox = getBox(x, y, z); if (neighborbox != 0) neighborbox->insert_(box); } } } } box->insert(item); } template BALL_INLINE bool HashGrid3::remove_(HashGridBox3* box, const Item& item) throw() { bool result = box->remove(item); if (result == true && box->isEmpty() == true) { if (box->previous_ != 0) { box->previous_->next_ = box->next_; } else { first_nonempty_ = box->next_; } if (box->next_ != 0) { box->next_->previous_ = box->previous_; } Position end_x, end_y, end_z; getIndices(*box, end_x, end_y, end_z); ++end_x; ++end_y; ++end_z; HashGridBox3 *neighborbox = 0; for (Index x = end_x - 2; x <= end_x; ++x) { for (Index y = end_y - 2; y <= end_y; ++y) { for (Index z = end_z - 2; z <= end_z; ++z) { neighborbox = getBox(x, y, z); if (neighborbox != 0) { neighborbox->remove_(box); } } } } } return result; } } // namespace BALL #endif // BALL_DATATYPE_HASHGRID_H ugene-1.9.8/src/plugins_3rdparty/ball/src/include/BALL/DATATYPE/stringHashMap.h0000644000175000017500000001200511651544325025410 0ustar ilyailya// -*- Mode: C++; tab-width: 2; -*- // vi: set ts=2: // // $Id: stringHashMap.h,v 1.25 2004-05-06 21:39:37 oliver Exp $ // #ifndef BALL_DATATYPE_STRINGHASHMAP_H #define BALL_DATATYPE_STRINGHASHMAP_H #ifndef BALL_COMMON_H # include #endif #ifndef BALL_COMMON_HASH_H # include #endif #ifndef BALL_CONCEPT_VISITOR_H # include #endif #ifndef BALL_CONCEPT_PROCESSOR_H # include #endif #ifndef BALL_DATATYPE_HASHMAP_H # include #endif #include namespace BALL { /** StringHashMap \ingroup GenericHash */ template class StringHashMap : public HashMap { public: BALL_CREATE(StringHashMap) /** @name Type Definitions */ //@{ /** Iterator type */ typedef typename HashMap::Iterator Iterator; /** Const iterator type */ typedef typename HashMap::ConstIterator ConstIterator; /** Value type */ typedef typename HashMap::ValueType ValueType; //@} /** @name Constructors and Destructors */ //@{ /** Default constructor. Create an empty hash map. */ StringHashMap() throw() : HashMap() { } /** Copy constructor. Create a copy of an existing hash map. @param map the hash map to be copied */ StringHashMap(const StringHashMap& map) throw() : HashMap(map) { } /** Destructor. Destruct the hash map and free all used memory. */ virtual ~StringHashMap() throw() { } /** Clear the hash map. Remove all contents from the hash map. */ void destroy() throw() { HashMap::clear(); } //@} /** @name Assignment */ //@{ /** Assign a hash map from another. Create a copy of a hash map. @param hash_map the map to be copied */ void set(const StringHashMap& hash_map) throw() { HashMap::clear(); ConstIterator it = hash_map.begin(); for ( ; it != hash_map.end(); ++it) { insert(*it); } } /// Assign a hash map from another const StringHashMap& operator = (const StringHashMap& hash_map) throw() { set(hash_map); return *this; } /// Assigns the content of a hash map to another void get(StringHashMap& hash_map) const throw() { hash_map.set(*this); } /// Swaps the contents of two hash maps void swap(StringHashMap& hash_map) throw() { std::swap(*this, hash_map); } //@} /** @name Accessors */ //@{ /** Insert a pair of key and value. */ std::pair insert(const ValueType& obj) throw() { return HashMap::insert(obj); } /** Insert a given value and key. @param value the value to be inserted @param key the value`s key */ ::std::pair insert(const String& key, const Value& value) throw() { return HashMap::insert(::std::pair(key, value)); } /** Remove the entry key from the map. @param key the key of the entry to be removed @return bool true if the key was removed */ bool remove(const String& key) throw() { // search the key Iterator it = HashMap::find(key); if (it == HashMap::end()) { // we didn't find it.. return false; } // found it: delete it HashMap::erase(it); return true; } /** Return the size of the hash map. */ Size getSize() const throw() { return HashMap::size(); } /** Return the load factor of the hash map. The load factor is defined as the quotient of the hash map size (the number of entries) and the number of buckets. */ float getLoadFactor() const throw() { return (float)HashMap::size() / (float)HashMap::getBucketSize(); } //@} /** @name Predicates */ //@{ /** Compare two string hash maps. */ bool operator == (const StringHashMap& hash_map) const throw() { return HashMap::operator == (hash_map); } /** Compare two string hash maps. */ bool operator != (const StringHashMap& hash_map) const throw() { return HashMap::operator != (hash_map); } /** Decide whether the hash map contains a given key. */ bool has(const String& key) const throw() { return !(HashMap::find(key) == HashMap::end()); } /** Return true if the hash map is empty. This method return true if the hash map does not contain any entries. */ bool isEmpty() const throw() { return (HashMap::size() == 0); } //@} /** @name Miscellaneous */ //@{ /** Visitor host method. StringHashMaps may be visited. @param visitor the visitor */ void host(Visitor >& visitor) throw() { visitor.visit(*this); } //@} }; }// namespace BALL #endif // BALL_DATATYPE_HASHMAP_H ugene-1.9.8/src/plugins_3rdparty/ball/src/include/BALL/DATATYPE/forEach.h0000644000175000017500000000153511651544325024215 0ustar ilyailya// -*- Mode: C++; tab-width: 2; -*- // vi: set ts=2: // // $Id: forEach.h,v 1.11 2004-02-18 23:24:03 oliver Exp $ // #ifndef BALL_DATATYPE_FOREACH_H #define BALL_DATATYPE_FOREACH_H #ifndef BALL_COMMON_H # include #endif /** Container Iteration Macro. Use this macro for convenient iteration over BALL container classes. \par Example: \par \verbatim HashMap hm; HashMap::Iterator it; BALL_FOREACH(p,it) { cout << it->first << endl; } \endverbatim @param container an instance of a BALL container class @param element_iterator an iterator of the container class \ingroup DatatypeMiscellaneous */ #define BALL_FOREACH(container, element_iterator) \ for (element_iterator = container.begin(); \ !element_iterator.isEnd(); \ ++element_iterator) #endif // BALL_DATATYPE_FOREACH_H ugene-1.9.8/src/plugins_3rdparty/ball/src/include/BALL/DATATYPE/triple.h0000644000175000017500000001450611651544325024147 0ustar ilyailya// -*- Mode: C++; tab-width: 2; -*- // vi: set ts=2: // // $Id: triple.h,v 1.9 2003-08-26 08:04:12 oliver Exp $ // #ifndef BALL_DATATYPE_TRIPLE_H #define BALL_DATATYPE_TRIPLE_H #ifndef BALL_COMMON_H # include #endif namespace BALL { /** Triple Class. This template class is used to represent triples of arbitrary types (like the STL type pair). @see Quadruple \ingroup DatatypeMiscellaneous */ template class Triple { public: /** @name Constructors and Destructors */ //@{ BALL_CREATE(Triple) /** Default constructor. Creates a new Triple object. */ Triple() throw(); /** Copy constructor. Creates a new Triple object from another. @param triple the Triple object to be copied @param deep not used (needed for a consistent interface only) */ Triple(const Triple& triple, bool deep = true) throw(); /** Detailed constructor. Creates a new Triple object from the triple's three members. @param new_first the first triple member @param new_second the second triple member @param new_third the third triple member */ Triple(const T1& new_first, const T2& new_second, const T3& new_third) throw(); /** Destructor. Destructs the Triple object. */ virtual ~Triple() throw(); //@} /** Clear method. */ virtual void clear() throw(); /** @name Assignment */ //@{ /** Assignment operator. Assigns the contents of a triple to another. @param triple the triple to be copied */ const Triple& operator = (const Triple& triple) throw(); /** */ void set(const T1& t1, const T2& t2, const T3& t3) throw(); /** */ void get(T1& first, T2& second, T3& third) const throw(); //@} /** @name Predicates */ //@{ /** Equality operator Two instances are equal if they have the same members. */ bool operator == (const Triple& triple) const throw(); /** Inequality operator */ bool operator != (const Triple& triple) const throw(); /** Lesser than operator. One instance is lesser than an other if all members from first to third are equal or less than the members of the other instance and at least threeth is less. */ bool operator < (const Triple& triple) const throw(); /** Lesser or equal than operator. */ bool operator <= (const Triple& triple) const throw(); /** Greater or equal than operator. */ bool operator >= (const Triple& triple) const throw(); /** Greater than operator. */ bool operator > (const Triple& triple) const throw(); //@} /** @name Attributes */ //@{ /** The first triple member */ T1 first; /** The second triple member */ T2 second; /** The third triple member */ T3 third; //@} }; template Triple::Triple() throw() { } template Triple::Triple (const Triple& triple, bool /* deep */) throw() : first(triple.first), second(triple.second), third(triple.third) { } template Triple::Triple (const T1& new_first, const T2& new_second, const T3& new_third) throw() : first(new_first), second(new_second), third(new_third) { } template Triple::~Triple() throw() { } template BALL_INLINE void Triple::set(const T1& new_first, const T2& new_second, const T3& new_third) throw() { first = new_first; second = new_second; third = new_third; } template BALL_INLINE const Triple& Triple::operator = (const Triple& triple) throw() { first = triple.first; second = triple.second; third = triple.third; return *this; } template BALL_INLINE void Triple::get(T1& t1, T2& t2, T3& t3) const throw() { t1 = first; t2 = second; t3 = third; } template BALL_INLINE bool Triple::operator == (const Triple& triple) const throw() { return (first == triple.first && second == triple.second && third == triple.third); } template BALL_INLINE bool Triple::operator != (const Triple& triple) const throw() { return (first != triple.first || second != triple.second || third != triple.third); } template BALL_INLINE void Triple::clear() throw() { first = T1(); second = T2(); third = T3(); } template BALL_INLINE bool Triple::operator < (const Triple& triple) const throw() { return ((first < triple.first) || ((first == triple.first) && (second < triple.second)) || ((first == triple.first) && (second == triple.second) && (third < triple.third))); } template BALL_INLINE bool Triple::operator <= (const Triple& triple) const throw() { return ((first < triple.first) || ((first == triple.first) && (second < triple.second)) || ((first == triple.first) && (second == triple.second) && (third < triple.third)) || ((first == triple.first) && (second == triple.second) && (third == triple.third))); } template BALL_INLINE bool Triple::operator >= (const Triple& triple) const throw() { return ((first > triple.first) || ((first == triple.first) && (second > triple.second)) || ((first == triple.first) && (second == triple.second) && (third > triple.third)) || ((first == triple.first) && (second == triple.second) && (third == triple.third))); } template BALL_INLINE bool Triple::operator > (const Triple& triple) const throw() { return ((first > triple.first) || ((first == triple.first) && (second > triple.second)) || ((first == triple.first) && (second == triple.second) && (third > triple.third))); } } // namespace BALL #endif // BALL_DATATYPE_TRIPLE_H ugene-1.9.8/src/plugins_3rdparty/ball/src/include/BALL/CONCEPT/0000755000175000017500000000000011651544310022343 5ustar ilyailyaugene-1.9.8/src/plugins_3rdparty/ball/src/include/BALL/CONCEPT/forwardIterator.h0000644000175000017500000002052411651544325025703 0ustar ilyailya// -*- Mode: C++; tab-width: 2; -*- // vi: set ts=2: // // $Id: forwardIterator.h,v 1.28 2004-02-26 15:04:02 sneumann Exp $ // #ifndef BALL_CONCEPT_FORWARDITERATOR_H #define BALL_CONCEPT_FORWARDITERATOR_H #ifndef BALL_CONCEPT_BASEITERATOR_H # include #endif namespace BALL { /** @name Generic forward iterator classes \ingroup ConceptsIterators */ //@{ /** Generic non-mutable forward itterator */ template class ConstForwardIterator : public BaseIterator { public: /** @name Typedefs */ //@{ /// typedef std::forward_iterator_tag iterator_category; // convenience typedef typedef BaseIterator Base; //@} /** @name Constructors and Destructors */ //@{ /// Default constructor BALL_INLINE ConstForwardIterator() throw() {} /// Copy constructor BALL_INLINE ConstForwardIterator(const ConstForwardIterator& iterator) throw() : BaseIterator(iterator) { } /// BALL_INLINE ~ConstForwardIterator() throw() {} //@} /** @name Assignment */ //@{ /// BALL_INLINE ConstForwardIterator& operator = (const ConstForwardIterator& iterator) throw() { BaseIterator::operator = (iterator); return *this; } /// BALL_INLINE void swap(ConstForwardIterator& iterator) throw() { std::swap(ConstForwardIterator::getTraits(), iterator.getTraits()); } //@} /** @name Iterator methods */ //@{ /// Move the iterator to the item at the beginning of the container BALL_INLINE void toBegin() throw(Exception::Precondition); /// Check whether the iterator points to the first item of the container BALL_INLINE bool isBegin() const throw(); /// Move the iterator behind the last item of the container BALL_INLINE void toEnd() throw(Exception::Precondition); /// Check whether the iterator points behind the last item of the container BALL_INLINE bool isEnd() const throw(); /// Return an iterator pointing to the beginning of the container static ConstForwardIterator begin(const Container& container) throw(Exception::Precondition); /// Return an iterator pointing at the end of the container static ConstForwardIterator end(const Container& container) throw(Exception::Precondition); /// Increment operator BALL_INLINE ConstForwardIterator& operator ++ () throw(Exception::Precondition) { BALL_PRECONDITION_EXCEPTION(Base::isValid(), "cannot increment invalid iterator") Base::getTraits().forward(); return *this; } /// Postfix increment operator BALL_INLINE ConstForwardIterator operator ++ (int) throw(Exception::Precondition) { BALL_PRECONDITION_EXCEPTION(Base::isValid(), "cannot increment invalid iterator") ConstForwardIterator tmp(*this); ++(*this); return tmp; } //@} protected: /// BALL_INLINE ConstForwardIterator(const Container& container) throw() : BaseIterator(container) { } }; //@} template BALL_INLINE void ConstForwardIterator::toBegin() throw(Exception::Precondition) { BALL_PRECONDITION_EXCEPTION(!Base::isSingular(), "cannot move singular iterator to begin") Base::getTraits().toBegin(); } template BALL_INLINE ConstForwardIterator ConstForwardIterator::begin(const Container& container) throw(Exception::Precondition) { ConstForwardIterator iterator(container); iterator.toBegin(); return iterator; } template BALL_INLINE bool ConstForwardIterator::isBegin() const throw() { if (Base::getTraits().isSingular()) { return false; } return Base::getTraits().isBegin(); } template BALL_INLINE void ConstForwardIterator::toEnd() throw(Exception::Precondition) { BALL_PRECONDITION_EXCEPTION(!Base::isSingular(), "cannot move singular iterator to end") Base::getTraits().toEnd(); } template BALL_INLINE ConstForwardIterator ConstForwardIterator::end(const Container& container) throw(Exception::Precondition) { ConstForwardIterator iterator(container); iterator.toEnd(); return iterator; } template BALL_INLINE bool ConstForwardIterator::isEnd() const throw() { if (Base::isSingular()) { return false; } return Base::getTraits().isEnd(); } /** Generic mutable forward iterator class */ template class ForwardIterator : public ConstForwardIterator { public: /** @name Typedefs */ //@{ /// typedef DataType& reference; /// typedef DataType* pointer; // convenience typedef typedef ConstForwardIterator Base; //@} /** @name Constructors and Destructors */ //@{ /// BALL_INLINE ForwardIterator() throw() {} /// BALL_INLINE ForwardIterator(const ForwardIterator& iterator) throw() : ConstForwardIterator(iterator) { } /// BALL_INLINE ~ForwardIterator() throw() {} //@} /** @name Assignemnt */ //@{ /// BALL_INLINE ForwardIterator& operator = (const ForwardIterator& iterator) throw() { ConstForwardIterator::operator = (iterator); return *this; } /// BALL_INLINE void swap(ForwardIterator& iterator) throw() { std::swap(Base::getTraits(), iterator.getTraits()); } //@} /** @name Iterator methods */ //@{ /// Return an iterator pointing to the beginning of the container static ForwardIterator begin(const Container& container) throw(Exception::Precondition); /// Return an iterator pointing at the end of the container static ForwardIterator end(const Container& container) throw(Exception::Precondition); /// BALL_INLINE reference operator * () const throw() { return (reference)Base::getTraits().getData(); } /// BALL_INLINE pointer operator -> () const throw() { return (pointer)&Base::getTraits().getData(); } /// Increment operator BALL_INLINE ForwardIterator& operator ++ () throw(Exception::Precondition) { BALL_PRECONDITION_EXCEPTION(Base::isValid(), "cannot increment invalid iterator") Base::getTraits().forward(); return *this; } /// Postfix increment operator BALL_INLINE ForwardIterator operator ++ (int) throw(Exception::Precondition) { BALL_PRECONDITION_EXCEPTION(Base::isValid(), "cannot increment invalid iterator") ForwardIterator tmp(*this); ++(*this); return tmp; } //@} protected: /// BALL_INLINE ForwardIterator(const Container& container) throw() : Base(container) { } }; template BALL_INLINE ForwardIterator ForwardIterator::begin(const Container& container) throw(Exception::Precondition) { ForwardIterator iterator(container); iterator.toBegin(); return iterator; } template BALL_INLINE ForwardIterator ForwardIterator::end(const Container& container) throw(Exception::Precondition) { ForwardIterator iterator(container); iterator.toEnd(); return iterator; } } // namespace BALL #endif // BALL_CONCEPT_FORWARDITERATOR_H ugene-1.9.8/src/plugins_3rdparty/ball/src/include/BALL/CONCEPT/processor.h0000644000175000017500000000456411651544325024552 0ustar ilyailya// -*- Mode: C++; tab-width: 2; -*- // vi: set ts=2: // // $Id: processor.h,v 1.18 2005-12-23 17:01:41 amoll Exp $ // #ifndef BALL_CONCEPT_PROCESSOR_H #define BALL_CONCEPT_PROCESSOR_H #ifndef BALL_COMMON_H # include #endif #ifndef BALL_CONCEPT_BASEFUNCTOR_H # include #endif #ifndef BALL_COMMON_GLOBAL_H # include #endif namespace BALL { /** @name Processor Concept \ingroup ConceptsMiscellaneous */ //@{ /** Global Types and Enums for Processors */ class BALL_EXPORT Processor { public: /** Result type */ typedef int Result; /** Result codes */ enum { /** Abort */ ABORT = 0, /** Break */ BREAK = 1, /** Continue */ CONTINUE = 2 }; }; /** Generic Unary Processor Class */ template class UnaryProcessor : public UnaryFunctor { public: /** @name Constructors and Destructors */ //@{ BALL_CREATE(UnaryProcessor) /** Default constructor */ UnaryProcessor() { } /** Copy constructor */ UnaryProcessor (const UnaryProcessor& /* processor */) { } /** Destructor */ virtual ~UnaryProcessor() { } //@} /** @name Processor specific methods */ //@{ /** start method */ virtual bool start() { return true; } /** finish method */ virtual bool finish() { return true; } /** operator () */ virtual Processor::Result operator () (T &) { return Processor::CONTINUE; } //@} }; /** Generic Binary Processor Class */ template class BinaryProcessor : public BinaryFunctor { public: /** @name Constructors and Destructors */ //@{ BALL_CREATE(BinaryProcessor) /** Default constructor */ BinaryProcessor() { } /** Copy constructor */ BinaryProcessor (const BinaryProcessor& /* processor */) { } /** Destructor */ virtual ~BinaryProcessor() { } //@} /** @name Processor-specific methods */ //@{ /** start method */ virtual bool start() { return true; } /** finish method */ virtual bool finish() { return true; } /** operator () */ virtual Processor::Result operator () (T1&, T2&) { return Processor::CONTINUE; } //@} }; //@} } // namespace BALL #endif // BALL_CONCEPT_PROCESSOR_H ugene-1.9.8/src/plugins_3rdparty/ball/src/include/BALL/CONCEPT/visitor.h0000644000175000017500000000233111651544325024220 0ustar ilyailya// -*- Mode: C++; tab-width: 2; -*- // vi: set ts=2: // // $Id: visitor.h,v 1.14 2004-02-23 15:19:58 anhi Exp $ // #ifndef BALL_CONCEPT_VISITOR_H #define BALL_CONCEPT_VISITOR_H #ifndef BALL_COMMON_H # include #endif namespace BALL { /** Generic Visitor Class. This class implements the visitor design pattern. \ingroup ConceptsMiscellaneous */ //@{ template class Visitor { public: /** @name Constructors and destructors */ //@{ /** Default constructor */ Visitor() throw(); /** Copy constructor */ Visitor(const Visitor& visitor) throw(); /** Destructor */ virtual ~Visitor() throw(); //@} /** Visit method. The visit method is an abstract method defining an interface between the visitor object and its host. */ virtual void visit(Host &) = 0; virtual void dummy(); }; //@} template void Visitor::dummy(){} template BALL_INLINE Visitor::Visitor() throw() { } template BALL_INLINE Visitor::Visitor(const Visitor& /* visitor */) throw() { } template Visitor::~Visitor() throw() { } } #endif // BALL_CONCEPT_VISITOR_H ugene-1.9.8/src/plugins_3rdparty/ball/src/include/BALL/CONCEPT/baseIterator.h0000644000175000017500000001340711651544325025153 0ustar ilyailya// -*- Mode: C++; tab-width: 2; -*- // vi: set ts=2: // // $Id: baseIterator.h,v 1.33 2003-08-26 08:04:06 oliver Exp $ // #ifndef BALL_CONCEPT_BASEITERATOR_H #define BALL_CONCEPT_BASEITERATOR_H #ifndef BALL_CONFIG_CONFIG_H # include #endif #ifndef BALL_COMMON_GLOBAL_H # include #endif #ifndef BALL_COMMON_EXCEPTION_H # include #endif namespace BALL { /** Generic Iterator Class. This template class implements the basic behaviour of an iterator. Iterators are basically STL-like iterators. They provide the full STL iterator interface, but also offer additional features. \par BaseIterator itself is a base class to the other iterator classes only and should not be used by itself. \par An important difference exists for the iterators of the kernel objects. For most kernel objects, multiple iterators exist. Therefore, we could not simply use begin() and end() like in STL, but we introduced specialized methods like \link AtomContainer::beginAtom AtomContainer::beginAtom \endlink and \link AtomContainer::endAtom AtomContainer::endAtom \endlink. For similar reasons, the iterators for kernel classes are not implemented as nested classes of the respective kernel classes, but as independent classes to avoid code replication. An exception is \link Atom::BondIterator Atom::BondIterator \endlink , which is relevant to \link Atom Atom \endlink alone. \par Each BALL iterator can be bound to a container, so once the iteration has started, it "knows" about the end() of the container. Therefore, BALL iterators additionally implement the unary plus operator to check for the validity of the iterator. this allows the convenient implementation of for loops, e.g. as follows: \par \code AtomIterator atom_it = system.beginAtom(); for (; +atom_it; ++atom_it) { .... } \endcode \ingroup ConceptsIterators */ template class BaseIterator { public: /** @name Typedefs. The names of these typedefs deviate from the usual BALL class names due to restrictions imposed by STL compliance. */ //@{ /// typedef DataType value_type; /// typedef Position difference_type; /// typedef const DataType* pointer; /// typedef const DataType& reference; /// typedef std::input_iterator_tag iterator_category; //@} /** @name Constructors and Destructors */ //@{ /// Default constructor BALL_INLINE BaseIterator() throw() {} /// Copy constructor BALL_INLINE BaseIterator(const BaseIterator& iterator) throw() : traits_(iterator.traits_) { } /// Destructor. BALL_INLINE ~BaseIterator() throw() {} //@} /** @name Assignment */ //@{ /** Assignment operator. Assigns the contents of an iterator to another iterator. @param iterator the iterator to be copied */ BALL_INLINE BaseIterator& operator = (const BaseIterator& iterator) throw() { traits_ = iterator.traits_; return *this; } /// Swap two iterators BALL_INLINE void swap(BaseIterator& iterator) throw() { std::swap(traits_, iterator.traits_); } //@} /** @name Accessors */ //@{ /// Invalidate the iterator. BALL_INLINE void invalidate() throw() { traits_.invalidate(); } /// Set the traits BALL_INLINE void setTraits(const Traits& traits) throw() { traits_ = traits; } /// Get a constant reference to the traits of this iterator. BALL_INLINE const Traits& getTraits() const throw() { return traits_; } /// Get a constant reference to the traits of this iterator. BALL_INLINE Traits& getTraits() throw() { return traits_; } /// Get a constant pointer to the container of this iterator. BALL_INLINE const Container* getContainer() const throw() { return traits_.getContainer(); } //@} /** @name Converters */ //@{ /** Convert an iterator to Position. This method returns the position of the iterator. Note that Position is a template within this context and not the BALL datatype. */ BALL_INLINE operator const Position& () const throw() { return traits_.getPosition(); } /// Convert an iterator to its Datatype by returning a reference to the current data. BALL_INLINE reference operator * () const throw() { return (reference)traits_.getData(); } /// Return a pointer to the current data. BALL_INLINE pointer operator -> () const throw() { return (pointer)&traits_.getData(); } //@} /** @name Predicates */ //@{ /// Equality operator BALL_INLINE bool operator == (const BaseIterator& iterator) const throw() { return (traits_ == iterator.traits_); } /// Inequality operator BALL_INLINE bool operator != (const BaseIterator& iterator) const throw() { return !(traits_ == iterator.traits_); } /** Singularity predicate. This method returns true if the iterator is singular, i.e., not associated with a container. */ BALL_INLINE bool isSingular() const throw() { return traits_.isSingular(); } /** Validity predicate @return true if the iterator is valid (pointing at an element in a container) */ BALL_INLINE bool isValid() const throw() { return traits_.isValid(); } /// Validity predicate BALL_INLINE bool operator + () const throw() { return traits_.isValid(); } /// Invalidity perdicate BALL_INLINE bool operator - () const throw() { return !traits_.isValid(); } //@} protected: /** Constructor. Protected to allow instantiation and use in derived classes only. */ BALL_INLINE BaseIterator(const Container& container) throw() : traits_(container) { } private: /// The instance of the iterator's traits Traits traits_; }; } // namespace BALL #endif // BALL_CONCEPT_BASEITERATOR_H ugene-1.9.8/src/plugins_3rdparty/ball/src/include/BALL/CONCEPT/predicate.h0000644000175000017500000000237511651544325024471 0ustar ilyailya// -*- Mode: C++; tab-width: 2; -*- // vi: set ts=2: // // $Id: predicate.h,v 1.15 2005-12-23 17:01:41 amoll Exp $ // #ifndef BALL_CONCEPT_PREDICATE_H #define BALL_CONCEPT_PREDICATE_H #ifndef BALL_COMMON_GLOBAL_H # include #endif #include namespace BALL { using std::unary_function; using std::binary_function; /** @name Predicates \ingroup ConceptsMiscellaneous */ //@{ /** Generic Unary Predicate Class */ template class UnaryPredicate : public unary_function { public: /// virtual ~UnaryPredicate() {} /// virtual bool operator() (const T& /* x */) const throw(); }; /** Generic Binary Predicate Class */ template class BinaryPredicate : public binary_function { public: /// virtual bool operator() (const T1& x, const T2& y) const throw(); /// virtual ~BinaryPredicate() {} }; template bool UnaryPredicate::operator() (const T& /* x */) const throw() { return true; } template bool BinaryPredicate::operator() (const T1&, const T2&) const throw() { return true; } //@} } // namespace BALL #endif // BALL_CONCEPT_PREDICATE_H ugene-1.9.8/src/plugins_3rdparty/ball/src/include/BALL/CONCEPT/baseFunctor.h0000644000175000017500000000376711651544325025012 0ustar ilyailya// -*- Mode: C++; tab-width: 2; -*- // vi: set ts=2: // // $Id: baseFunctor.h,v 1.11 2005-12-23 17:01:40 amoll Exp $ // #ifndef BALL_CONCEPT_BASEFUNCTOR_H #define BALL_CONCEPT_BASEFUNCTOR_H #ifndef BALL_COMMON_GLOBAL_H # include #endif namespace BALL { /** @name Generic Functors. * \ingroup ConceptsMiscellaneous */ //@{ /** Generic Unary Functor Class. */ template class BALL_EXPORT UnaryFunctor { public: /** @name Type Definitions */ //@{ /** */ typedef ResultType result_type; /** */ typedef ArgumentType argument_type; /** */ typedef ArgumentType& argument_reference; /** */ typedef const ArgumentType& const_argument_reference; /** */ typedef ArgumentType* argument_pointer; /** */ typedef const ArgumentType* const_argument_pointer; //@} }; /** Generic Binary Functor Class. */ template class BALL_EXPORT BinaryFunctor { public: /** @name Type Definitions */ //@{ /** */ typedef ResultType result_type; /** */ typedef FirstArgumentType first_argument_type; /** */ typedef FirstArgumentType & first_argument_reference; /** */ typedef const FirstArgumentType & const_first_argument_reference; /** */ typedef FirstArgumentType * first_argument_pointer; /** */ typedef const FirstArgumentType * const_first_argument_pointer; /** */ typedef SecondArgumentType second_argument_type; /** */ typedef SecondArgumentType & second_argument_reference; /** */ typedef const SecondArgumentType & const_second_argument_reference; /** */ typedef SecondArgumentType * second_argument_pointer; /** */ typedef const SecondArgumentType * const_second_argument_pointer; //@} }; //@} } // namespace BALL #endif // BALL_CONCEPT_BASEFUNCTOR_H ugene-1.9.8/src/plugins_3rdparty/ball/src/include/BALL/MATHS/0000755000175000017500000000000011651544310022124 5ustar ilyailyaugene-1.9.8/src/plugins_3rdparty/ball/src/include/BALL/MATHS/matrix44.h0000644000175000017500000016224211651544325023766 0ustar ilyailya// -*- Mode: C++; tab-width: 2; -*- // vi: set ts=2: // // $Id: matrix44.h,v 1.55.14.1 2007-03-25 21:23:45 oliver Exp $ // #ifndef BALL_MATHS_MATRIX44_H #define BALL_MATHS_MATRIX44_H #ifndef BALL_COMMON_EXCEPTION_H # include #endif #include #include #include #include #ifndef BALL_MATHS_ANGLE_H # include #endif #ifndef BALL_MATHS_VECTOR3_H # include #endif #ifndef BALL_MATHS_VECTOR4_H # include #endif namespace BALL { /** \defgroup Matrix44 4x4 Matrix Matrix representing transformations: class \link TMatrix4x4 TMatrix4x4 \endlink and class \link Matrix4x4 Matrix4x4 \endlink \ingroup Primitives */ //@{ /// Default Type template class TMatrix4x4; /** @name Storers */ //@{ /** Input Operator. Read sixteen values of type T from an input stream. @param s the input stream @param m the matrix to read */ template std::istream& operator >> (std::istream& s, TMatrix4x4& m) throw(); /** Output Operator Writes sixteen values of type T to an output stream. @param s the output stream @param m the matrix to write */ template std::ostream& operator << (std::ostream& s, const TMatrix4x4& m) throw(); //@} /** Generic 4x4 Matrix Class. */ template class TMatrix4x4 { public: BALL_CREATE(TMatrix4x4) /** @name Constructors and Destructors */ //@{ /** Default constructor. This method creates a new TMatrix4x4 object. The components are initialized to 0. */ TMatrix4x4() throw(); /** Array constructor. This constructor creates a TMatrix4x4 object from the first sixteen elements pointed to by ptr. @param ptr the array to construct from @exception NullPointer if ptr == 0 */ TMatrix4x4(const T* ptr) throw(Exception::NullPointer); /** Array constructor. This constructor creates a TMatrix4x4 object from the sixteen elements in the array assigned by ptr. @param ptr the array to construct from @exception NullPointer if ptr == 0 */ TMatrix4x4(const T ptr[4][4]) throw(Exception::NullPointer); /** Copy constructor. Create a new TMatrix4x4 object from another. @param TMatrix4x4 the TMatrix4x4 object to be copied @param bool ignored (just for interface consistency) */ TMatrix4x4(const TMatrix4x4& m) throw(); /** Detailed constructor. Create a new TMatrix4x4 object from four TVector4. @param col1 assigned to the first column @param col2 assigned to the second column @param col3 assigned to the third column @param col4 assigned to the fourth column */ TMatrix4x4 (const TVector4& col1, const TVector4& col2, const TVector4& col3, const TVector4& col4) throw(); /** Detailed constructor. Create a new TMatrix4x4 object from sixteen T values. @param m11 - m44 assigned to the components */ TMatrix4x4 (const T& m11, const T& m12, const T& m13, const T& m14, const T& m21, const T& m22, const T& m23, const T& m24, const T& m31, const T& m32, const T& m33, const T& m34, const T& m41, const T& m42, const T& m43, const T& m44) throw(); /** Destructor. Destructs the TMatrix4x4 object. As there are no dynamic data structures, nothing happens. */ virtual ~TMatrix4x4() throw() { } /** Clear method. The values are set to 0. */ virtual void clear() throw(); //@} /** @name Assignment */ //@{ /** Assign from array-ptr. Assign from the first sixteen elements pointed to by ptr. @param ptr the array to construct from @exception NullPointer if ptr == 0 */ void set(const T* ptr) throw(Exception::NullPointer); /** Assign from the first sixteen elements. pointed to by the array assigned by ptr. @param ptr the array to construct from @exception NullPointer if ptr == 0 */ void set(const T ptr[4][4]) throw(Exception::NullPointer); /** Assign from another instance. @param TMatrix4x4 the TMatrix4x4 object to assign from */ void set(const TMatrix4x4& m) throw(); /** Assign from four TVector4. @param col1 assigned to the first column @param col2 assigned to the second column @param col3 assigned to the third column @param col4 assigned to the fourth column */ void set (const TVector4& col1, const TVector4& col2, const TVector4& col3, const TVector4& col4) throw(); /** Assign from sixteen values of type T. @param m11 - m44 assigned to the components */ void set (const T& m11, const T& m12, const T& m13, const T& m14, const T& m21, const T& m22, const T& m23, const T& m24, const T& m31, const T& m32, const T& m33, const T& m34, const T& m41, const T& m42, const T& m43, const T& m44) throw(); /** Assignment operator. Assign the components from the first 16 values assigned by ptr. @param ptr the array to construct from **/ TMatrix4x4& operator = (const T* ptr) throw(Exception::NullPointer); /** Assignment operator. Assign the components from the first 16 values assigned by ptr. @param ptr the array to construct from **/ TMatrix4x4& operator = (const T ptr[4][4]) throw(Exception::NullPointer); /** Assignment operator. Assign the components from another instance of TMatrix4x4. @param TMatrix4x4 the TMatrix4x4 to assign from **/ TMatrix4x4& operator = (const TMatrix4x4& m) throw(); /** Assign to an array. Assigns the components to a pointer of an array of sixteen values of type T. @exception NullPointer if ptr == 0 @param ptr the pointer to assign to */ void get(T* ptr) const throw(Exception::NullPointer); /** Assign to an array. Assigns the components to an array of sixteen values of type T. @exception NullPointer if ptr == 0 @param ptr the array to assign to */ void get(T ptr[4][4]) const throw(Exception::NullPointer); /** Assign to another instance. Assigns the components to another TMatrix4x4. @param TMatrix4x4 the TMatrix4x4 to be assigned to */ void get(TMatrix4x4& m) const throw(); /** Assign to four variables of type TVector4 . @param col1 the TVector4 to obtain the values of the first column @param col2 the TVector4 to obtain the values of the second column @param col3 the TVector4 to obtain the values of the third column @param col4 the TVector4 to obtain the values of the fourth column */ void get (TVector4& col1, TVector4& col2, TVector4& col3, TVector4& col4) const throw(); /** Assign to sixteen variables of type T. @param m11 - m44 the variables to assign to */ void get (T& m11, T& m12, T& m13, T& m14, T& m21, T& m22, T& m23, T& m24, T& m31, T& m32, T& m33, T& m34, T& m41, T& m42, T& m43, T& m44) const throw(); /** Swap the contents of two instances of TMatrix4x4. @param TMatrix4x4 the TMatrix4x4 to swap contents with */ void swap(TMatrix4x4& m) throw(); //@} /** @name Accessors */ //@{ /** Compute the trace. Get the sum of the diagonal elements (m11 + m22 + m33 + m44). @return T the trace */ T getTrace() const throw(); /** Create a zero matrix. A new matrix object is created and all elements set to 0. */ static const TMatrix4x4& getZero() throw(); /** Create an identity matrix. A new matrix object is created and all elements but the diagonal are set to zero. The diagonal elements are set to 1. */ static const TMatrix4x4& getIdentity() throw(); /** Set to an identity matrix. m11, m22, m33, m44 = 1; the other cells have the value 0; */ void setIdentity() throw(); /** Set the diagonal elements to the given value. All other elements are set to 0. @param T the value to fill with (default: 1) */ void set(const T& t = (T)1) throw(); /** Mirror the Matrix at the diagonal. All values are swaped by the mirrored value. (I.e. m12 <=> m21 , m13 <=> m31 , ...) */ void transpose() throw(); /** Get a row of the matrix. @param row the number of the row (0-3) @exception IndexOverflow if row > 3 @return TVector4 the row */ TVector4 getRow(Position row) const throw(Exception::IndexOverflow); /** Get a column of the matrix. @param col the number of the column (0-3) @exception IndexOverflow if col > 3 @return TVector4 the column */ TVector4 getColumn(Position col) const throw(Exception::IndexOverflow); /** Set a row of the matrix. @param row the number of the row (0-3) @param row_value the new value of the row @exception IndexOverflow if row > 3 */ void setRow(Position row, const TVector4& row_value) throw(Exception::IndexOverflow); /** Set a column of the matrix. @param col the number of the column (0-3) @param col_value the new value of the col @exception IndexOverflow if col > 3 */ void setColumn(Position col, const TVector4& col_value) throw(Exception::IndexOverflow); /** Test whether two matrices are equal. Two matrices are considered equal, if \link Maths::isEqual Maths::isEqual \endlink returns true for each pair of corresponding elements. @param m the matrix to compare with @return bool, true if all components are equal, false otherwise */ bool isEqual(const TMatrix4x4& m) const throw(); /** Get the diagonal of the matrix. @return TVector4 the diagonal */ TVector4 getDiagonal() const throw(); /** Access operator of a cell. @param row the number of the row (0-3) @param col the number of the column (0-3) @exception IndexOverflow if col >3 || row > 3 @return T& a reference to the cell */ T& operator () (Position row, Position col) throw(Exception::IndexOverflow); /** Constant access operator of a cell. @param row the number of the row (0-3) @param col the number of the column (0-3) @exception IndexOverflow if col ||row > 3 @return T& a const reference to the cell */ const T& operator () (Position row, Position col) const throw(Exception::IndexOverflow); /** Constant random access operator. Access single elements of the matrix. index may assume values in the range of 0 - 15. The elements of the matrix are returned rows first, i.e., in the following order: m11, m12, m13... */ const T& operator [] (Position position) const throw(Exception::IndexOverflow); /** Mutable random access operator. @see operator[] */ T& operator [] (Position position) throw(Exception::IndexOverflow); /** Positive sign. */ TMatrix4x4 operator + () const throw(); /** Negative sign. */ TMatrix4x4 operator - () const throw(); /** Addition operator. Adds another matrix to this matrix and return the result. @param m the matrix to add @return TMatrix4x4 the result */ TMatrix4x4 operator + (const TMatrix4x4& m) const throw(); /** Addition operator. Adds another matrix to this matrix. @param m the matrix to add @return TMatrix4x4&, {\em *this} */ TMatrix4x4& operator += (const TMatrix4x4& m) throw(); /** Subtraction operator. Subtract another matrix from this matrix and return the result @param m the matrix to subtract @return TMatrix4x4 the result */ TMatrix4x4 operator - (const TMatrix4x4& m) const throw(); /** Subtraction operator. Subtract another matrix from this matrix. @param m the matrix to subtract @return TMatrix4x4&, {\em *this} */ TMatrix4x4& operator -= (const TMatrix4x4& m) throw(); /** Multiply by a scalar. Operator for multiplying every cell value with a scalar value. @return TMatrix4x4 the result */ TMatrix4x4 operator * (const T& scalar) const throw(); /** Multiply by a scalar. Operator for multiplying every cell value with a scalar value. @return TMatrix4x4&, {\em *this} */ TMatrix4x4& operator *= (const T& scalar) throw(); /** Divide by a scalar. Operator for dividing every cell value by a scalar value. @exception DivisionByZero if scalar == 0 @return TMatrix4x4 the result */ TMatrix4x4 operator / (const T& scalar) const throw(Exception::DivisionByZero); /** Divide by a scalar. Operator for dividing every cell value by a scalar value. @exception DivisionByZero if scalar == 0 @return TMatrix4x4&, {\em *this} */ TMatrix4x4& operator /= (const T& scalar) throw(Exception::DivisionByZero); /** Multiply two matrices. @return TMatrix4x4 the result */ TMatrix4x4 operator * (const TMatrix4x4& m) const throw(); /** Multiply two matrices @return TMatrix4x4&, {\em *this} */ TMatrix4x4& operator *= (const TMatrix4x4& m) throw(); /** Multiplication by an instance of type TVector4 . @return TMatrix4x4&, {\em *this} */ TVector4 operator * (const TVector4& vector) const throw(); /** Invert the matrix. Tests if the matrix can be inverted. If possible, the result will be inverted and the result returned in inverse . @param inverse is assigned the inverse matrix @return bool true if the inverse matrix could be calculated, otherwise false. */ bool invert(TMatrix4x4& inverse) const throw(); /** Invert the matrix. Tests if the matrix can be inverted. If this is possible, the result is stored in the matrix. @return bool true if the inverse matrix could be calculated, otherwise false. */ bool invert() throw(); /** Compute the determinant. @return T the determinant. */ T getDeterminant() const throw(); /** Translate the matrix. @param x the x-component of the translation @param y the y-component of the translation @param z the z-component of the translation */ void translate(const T &x, const T &y, const T &z) throw(); /** Translate the matrix. @param v the vector to translate with */ void translate(const TVector3& v) throw(); /** Set the matrix to a translation matrix. @param x the x-component of the translation @param y the y-component of the translation @param z the z-component of the translation */ void setTranslation(const T& x, const T& y, const T& z) throw(); /** Set the matrix to a translation matrix. @param v the vector to translate with */ void setTranslation(const TVector3& v) throw(); /** Scale the matrix. @param x_scale the x scale factor @param y_scale the y scale factor @param z_scale the z scale factor */ void scale(const T& x_scale, const T& y_scale, const T& z_scale) throw(); /** Scale the matrix. @param scale the scale factor */ void scale(const T& scale) throw(); /** Scale the matrix. @param v the vector with the scale factor */ void scale(const TVector3& v) throw(); /** Set the matrix to a scalation matrix. @param x_scale the x scale factor @param y_scale the y scale factor @param z_scale the z scale factor */ void setScale(const T& x_scale, const T& y_scale, const T& z_scale) throw(); /** Set the matrix to a scalation matrix. @param scale the scale factor */ void setScale(const T& scale) throw(); /** Set the matrix to a scalation matrix. @param v the vector with the scale factor */ void setScale(const TVector3& v) throw(); /** Rotate the matrix around the x axis. @param phi the rotation angle */ void rotateX(const TAngle& phi) throw(); /** Set the matrix to a x rotation matrix. @param phi the rotation angle */ void setRotationX(const TAngle& phi) throw(); /** Rotate the matrix around the y axis. @param phi the rotation angle */ void rotateY(const TAngle& phi) throw(); /** Set the matrix to a y rotation matrix. @param phi the rotation angle */ void setRotationY(const TAngle& phi) throw(); /** Rotate the matrix around the z axis. @param phi the rotation angle */ void rotateZ(const TAngle& phi) throw(); /** Set the matrix to a z rotation matrix. @param phi the rotation angle */ void setRotationZ(const TAngle& phi) throw(); /** Rotate the matrix around a given axis. @param phi the rotation angle @param axis_x the x component of the axis @param axis_y the y component of the axis @param axis_z the z component of the axis */ void rotate(const TAngle& phi, const T& axis_x, const T& axis_y, const T& axis_z) throw(); /** Rotate the matrix around a given axis. @param phi the rotation angle @param axis the axis vector */ void rotate(const TAngle& phi, const TVector3& axis) throw(); /** Rotate the matrix around a given axis. @param phi the rotation angle @param axis the axis vector, the fourth component of the vector is ignored */ void rotate(const TAngle& phi, const TVector4& axis) throw(); /** Set the matrix to a rotation matrix. @param phi the rotation angle @param axis_x the x component of the axis @param axis_y the y component of the axis @param axis_z the z component of the axis */ void setRotation(const TAngle& phi, const T& axis_x, const T& axis_y, const T& axis_z) throw(); /** Set the matrix to a rotation matrix. @param phi the rotation angle @param axis the axis vector */ void setRotation(const TAngle& phi, const TVector3& axis) throw(); /** Set the matrix to a rotation matrix. @param phi the rotation angle @param axis the axis vector, the fourth component of the vector is ignored */ void setRotation(const TAngle& phi, const TVector4& axis) throw(); //@} /** @name Predicates */ //@{ /** Equality operator. Instead of this operator isEqual should be used. \link isEqual isEqual \endlink @return bool, true if all components are equal, false otherwise */ bool operator == (const TMatrix4x4& m) const throw(); /** Inequality operator. Instead of this operator isEqual should be used. \link isEqual isEqual \endlink @return bool, true if the two TMatrix4x4 differ in at least one component, false otherwise */ bool operator != (const TMatrix4x4& m) const throw(); /** Test whether this matrix is an identity matrix. (I.e. m11, m22, m33, m44 = 1 and the other cells have the value 0) @return bool, true if identity matrix, false otherwise */ bool isIdentity() const throw(); /** Test whether this matrix is regular. @return bool, true if (Determinant != 0), false otherwise */ bool isRegular() const throw(); /** Test whether this matrix is singular. @return bool, true if (Determinant == 0), false otherwise */ bool isSingular() const throw(); /** Test whether this matrix is symmetric. (m12 = m21, m31 = m13, ...) @return bool, true if symmatric, false otherwise */ bool isSymmetric() const throw(); /** Test whether the lower triangular is zero. @return bool, true if (m12 = m13 = m14 = m23 = m24 = m34 = 0), false otherwise */ bool isLowerTriangular() const throw(); /** Test whether the upper triangular is zero. @return bool, true if (m21 = m31 = m32 = m41 = m42 = m43 = 0), false otherwise */ bool isUpperTriangular() const throw(); /** Test whether all cells but the diagonal are zero. @return bool, true or false */ bool isDiagonal() const throw(); //@} /** @name Debugging and Diagnostics */ //@{ /** Test whether instance is valid. Always returns true. @return bool true */ bool isValid() const throw(); /** Internal state dump. Dump the current internal state of {\em *this} to the output ostream s with dumping depth depth . @param s - output stream where to output the internal state of {\em *this} @param depth - the dumping depth */ void dump(std::ostream& s = std::cout, Size depth = 0) const throw(); //@} /** @name Attributes */ //@{ /// 1st cell in the 1st row T m11; /// 2nd cell in the 1st row T m12; /// 3rd cell in the 1st row T m13; /// 4th cell in the 1st row T m14; /// 1st cell in the 2nd row T m21; /// 2nd cell in the 2nd row T m22; /// 3rd cell in the 2nd row T m23; /// 4th cell in the 2nd row T m24; /// 1st cell in the 3rd row T m31; /// 2nd cell in the 3rd row T m32; /// 3rd cell in the 3rd row T m33; /// 4th cell in the 3rd row T m34; /// 1st cell in the 4th row T m41; /// 2nd cell in the 4th row T m42; /// 3rd cell in the 4th row T m43; /// 4th cell in the 4th row T m44; //@} private: void initializeComponentPointers_() throw() { T **ptr = (T **)comp_ptr_; *ptr++ = &m11; *ptr++ = &m12; *ptr++ = &m13; *ptr++ = &m14; *ptr++ = &m21; *ptr++ = &m22; *ptr++ = &m23; *ptr++ = &m24; *ptr++ = &m31; *ptr++ = &m32; *ptr++ = &m33; *ptr++ = &m34; *ptr++ = &m41; *ptr++ = &m42; *ptr++ = &m43; *ptr = &m44; } // pointers to the components of the matrix T* comp_ptr_[16]; }; //@} template TMatrix4x4::TMatrix4x4() throw() : m11(0), m12(0), m13(0), m14(0), m21(0), m22(0), m23(0), m24(0), m31(0), m32(0), m33(0), m34(0), m41(0), m42(0), m43(0), m44(0) { initializeComponentPointers_(); } template TMatrix4x4::TMatrix4x4( const T* ptr) throw(Exception::NullPointer) { if (ptr == 0) { throw Exception::NullPointer(__FILE__, __LINE__); } m11 = *ptr++; m12 = *ptr++; m13 = *ptr++; m14 = *ptr++; m21 = *ptr++; m22 = *ptr++; m23 = *ptr++; m24 = *ptr++; m31 = *ptr++; m32 = *ptr++; m33 = *ptr++; m34 = *ptr++; m41 = *ptr++; m42 = *ptr++; m43 = *ptr++; m44 = *ptr; initializeComponentPointers_(); } template TMatrix4x4::TMatrix4x4(const T array_ptr[4][4]) throw(Exception::NullPointer) { if (array_ptr == 0) { throw Exception::NullPointer(__FILE__, __LINE__); } const T *ptr = *array_ptr; m11 = *ptr++; m12 = *ptr++; m13 = *ptr++; m14 = *ptr++; m21 = *ptr++; m22 = *ptr++; m23 = *ptr++; m24 = *ptr++; m31 = *ptr++; m32 = *ptr++; m33 = *ptr++; m34 = *ptr++; m41 = *ptr++; m42 = *ptr++; m43 = *ptr++; m44 = *ptr; initializeComponentPointers_(); } template TMatrix4x4::TMatrix4x4(const TMatrix4x4& m) throw() : m11(m.m11), m12(m.m12), m13(m.m13), m14(m.m14), m21(m.m21), m22(m.m22), m23(m.m23), m24(m.m24), m31(m.m31), m32(m.m32), m33(m.m33), m34(m.m34), m41(m.m41), m42(m.m42), m43(m.m43), m44(m.m44) { initializeComponentPointers_(); } template TMatrix4x4::TMatrix4x4 (const TVector4& col1, const TVector4& col2, const TVector4& col3,const TVector4& col4) throw() : m11(col1.x), m12(col1.y), m13(col1.z), m14(col1.h), m21(col2.x), m22(col2.y), m23(col2.z), m24(col2.h), m31(col3.x), m32(col3.y), m33(col3.z), m34(col3.h), m41(col4.x), m42(col4.y), m43(col4.z), m44(col4.h) { initializeComponentPointers_(); } template TMatrix4x4::TMatrix4x4 (const T& m11, const T& m12, const T& m13, const T& m14, const T& m21, const T& m22, const T& m23, const T& m24, const T& m31, const T& m32, const T& m33, const T& m34, const T& m41, const T& m42, const T& m43, const T& m44) throw() : m11(m11), m12(m12), m13(m13), m14(m14), m21(m21), m22(m22), m23(m23), m24(m24), m31(m31), m32(m32), m33(m33), m34(m34), m41(m41), m42(m42), m43(m43), m44(m44) { initializeComponentPointers_(); } template void TMatrix4x4::clear() throw() { set((T)0); } template void TMatrix4x4::set(const T* ptr) throw(Exception::NullPointer) { if (ptr == 0) { throw Exception::NullPointer(__FILE__, __LINE__); } m11 = *ptr++; m12 = *ptr++; m13 = *ptr++; m14 = *ptr++; m21 = *ptr++; m22 = *ptr++; m23 = *ptr++; m24 = *ptr++; m31 = *ptr++; m32 = *ptr++; m33 = *ptr++; m34 = *ptr++; m41 = *ptr++; m42 = *ptr++; m43 = *ptr++; m44 = *ptr; } template void TMatrix4x4::set(const T array_ptr[4][4]) throw(Exception::NullPointer) { if (array_ptr == 0) { throw Exception::NullPointer(__FILE__, __LINE__); } const T *ptr = *array_ptr; m11 = *ptr++; m12 = *ptr++; m13 = *ptr++; m14 = *ptr++; m21 = *ptr++; m22 = *ptr++; m23 = *ptr++; m24 = *ptr++; m31 = *ptr++; m32 = *ptr++; m33 = *ptr++; m34 = *ptr++; m41 = *ptr++; m42 = *ptr++; m43 = *ptr++; m44 = *ptr; } template void TMatrix4x4::set(const TMatrix4x4& m) throw() { m11 = m.m11; m12 = m.m12; m13 = m.m13; m14 = m.m14; m21 = m.m21; m22 = m.m22; m23 = m.m23; m24 = m.m24; m31 = m.m31; m32 = m.m32; m33 = m.m33; m34 = m.m34; m41 = m.m41; m42 = m.m42; m43 = m.m43; m44 = m.m44; } template void TMatrix4x4::set (const TVector4& col1, const TVector4& col2, const TVector4& col3, const TVector4& col4) throw() { m11 = col1.x; m12 = col1.y; m13 = col1.z; m14 = col1.h; m21 = col2.x; m22 = col2.y; m23 = col2.z; m24 = col2.h; m31 = col3.x; m32 = col3.y; m33 = col3.z; m34 = col3.h; m41 = col4.x; m42 = col4.y; m43 = col4.z; m44 = col4.h; } template void TMatrix4x4::set (const T& c11, const T& c12, const T& c13, const T& c14, const T& c21, const T& c22, const T& c23, const T& c24, const T& c31, const T& c32, const T& c33, const T& c34, const T& c41, const T& c42, const T& c43, const T& c44) throw() { m11 = c11; m12 = c12; m13 = c13; m14 = c14; m21 = c21; m22 = c22; m23 = c23; m24 = c24; m31 = c31; m32 = c32; m33 = c33; m34 = c34; m41 = c41; m42 = c42; m43 = c43; m44 = c44; } template BALL_INLINE TMatrix4x4& TMatrix4x4::operator = (const T* ptr) throw(Exception::NullPointer) { set(ptr); return *this; } template BALL_INLINE TMatrix4x4& TMatrix4x4::operator = (const T array_ptr[4][4]) throw(Exception::NullPointer) { set(array_ptr); return *this; } template BALL_INLINE TMatrix4x4& TMatrix4x4::operator = (const TMatrix4x4& m) throw() { set(m); return *this; } template void TMatrix4x4::get(T* ptr) const throw(Exception::NullPointer) { if (ptr == 0) { throw Exception::NullPointer(__FILE__, __LINE__); } *ptr++ = m11; *ptr++ = m12; *ptr++ = m13; *ptr++ = m14; *ptr++ = m21; *ptr++ = m22; *ptr++ = m23; *ptr++ = m24; *ptr++ = m31; *ptr++ = m32; *ptr++ = m33; *ptr++ = m34; *ptr++ = m41; *ptr++ = m42; *ptr++ = m43; *ptr = m44; } template void TMatrix4x4::get(T array_ptr[4][4]) const throw(Exception::NullPointer) { if (array_ptr == 0) { throw Exception::NullPointer(__FILE__, __LINE__); } T *ptr = *array_ptr; *ptr++ = m11; *ptr++ = m12; *ptr++ = m13; *ptr++ = m14; *ptr++ = m21; *ptr++ = m22; *ptr++ = m23; *ptr++ = m24; *ptr++ = m31; *ptr++ = m32; *ptr++ = m33; *ptr++ = m34; *ptr++ = m41; *ptr++ = m42; *ptr++ = m43; *ptr = m44; } template void TMatrix4x4::get(TMatrix4x4& m) const throw() { m.set(*this); } template void TMatrix4x4::get (TVector4& col1, TVector4& col2, TVector4& col3, TVector4& col4) const throw() { col1.x = m11; col1.y = m12; col1.z = m13; col1.h = m14; col2.x = m21; col2.y = m22; col2.z = m23; col2.h = m24; col3.x = m31; col3.y = m32; col3.z = m33; col3.h = m34; col4.x = m41; col4.y = m42; col4.z = m43; col4.h = m44; } template void TMatrix4x4::get (T& c11, T& c12, T& c13, T& c14, T& c21, T& c22, T& c23, T& c24, T& c31, T& c32, T& c33, T& c34, T& c41, T& c42, T& c43, T& c44) const throw() { c11 = m11; c12 = m12; c13 = m13; c14 = m14; c21 = m21; c22 = m22; c23 = m23; c24 = m24; c31 = m31; c32 = m32; c33 = m33; c34 = m34; c41 = m41; c42 = m42; c43 = m43; c44 = m44; } template BALL_INLINE T TMatrix4x4::getTrace() const throw() { return (m11 + m22 + m33 + m44); } template BALL_INLINE const TMatrix4x4& TMatrix4x4::getZero() throw() { static TMatrix4x4 null_matrix (0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); return null_matrix; } template BALL_INLINE void TMatrix4x4::setIdentity() throw() { m12 = m13 = m14 = m21 = m23 = m24 = m31 = m32 = m34 = m41 = m42 = m43 = 0; m11 = m22 = m33 = m44 = (T)1; } template BALL_INLINE const TMatrix4x4& TMatrix4x4::getIdentity() throw() { static TMatrix4x4 identity (1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1); return identity; } template void TMatrix4x4::set(const T& t) throw() { m11 = m12 = m13 = m14 = m21 = m22 = m23 = m24 = m31 = m32 = m33 = m34 = m41 = m42 = m43 = m44 = t; } template void TMatrix4x4::swap(TMatrix4x4& m) throw() { T tmp = m11; m11 = m.m11; m.m11 = tmp; tmp = m12; m12 = m.m12; m.m12 = tmp; tmp = m13; m13 = m.m13; m.m13 = tmp; tmp = m14; m14 = m.m14; m.m14 = tmp; tmp = m21; m21 = m.m21; m.m21 = tmp; tmp = m22; m22 = m.m22; m.m22 = tmp; tmp = m23; m23 = m.m23; m.m23 = tmp; tmp = m24; m24 = m.m24; m.m24 = tmp; tmp = m31; m31 = m.m31; m.m31 = tmp; tmp = m32; m32 = m.m32; m.m32 = tmp; tmp = m33; m33 = m.m33; m.m33 = tmp; tmp = m34; m34 = m.m34; m.m34 = tmp; tmp = m41; m41 = m.m41; m.m41 = tmp; tmp = m42; m42 = m.m42; m.m42 = tmp; tmp = m43; m43 = m.m43; m.m43 = tmp; tmp = m44; m44 = m.m44; m.m44 = tmp; } template void TMatrix4x4::transpose() throw() { T tmp = m12; m12 = m21; m21 = tmp; tmp = m13; m13 = m31; m31 = tmp; tmp = m14; m14 = m41; m41 = tmp; tmp = m23; m23 = m32; m32 = tmp; tmp = m24; m24 = m42; m42 = tmp; tmp = m34; m34 = m43; m43 = tmp; } template TVector4 TMatrix4x4::getRow(Position row) const throw(Exception::IndexOverflow) { if (row > 3) { throw Exception::IndexOverflow(__FILE__, __LINE__, row, 3); } // calculate the start of the row in the array const T* ptr = comp_ptr_[4 * row]; return TVector4 (ptr[0], ptr[1], ptr[2], ptr[3]); } template TVector4 TMatrix4x4::getColumn(Position col) const throw(Exception::IndexOverflow) { if (col > 3) { throw Exception::IndexOverflow(__FILE__, __LINE__, col, 3); } const T* ptr = comp_ptr_[col]; return TVector4 (ptr[0], ptr[4], ptr[8], ptr[12]); } template void TMatrix4x4::setRow(Position row, const TVector4& row_value) throw(Exception::IndexOverflow) { if (row > 3) { throw Exception::IndexOverflow(__FILE__, __LINE__, row, 3); } // calculate a pointer to the start of the row T* ptr = comp_ptr_[4 * row]; ptr[0] = row_value.x; ptr[1] = row_value.y; ptr[2] = row_value.z; ptr[3] = row_value.h; } template void TMatrix4x4::setColumn(Position col, const TVector4& col_value) throw(Exception::IndexOverflow) { if (col > 3) { throw Exception::IndexOverflow(__FILE__, __LINE__, col, 3); } // calculate a pointer to the start of the column T* ptr = comp_ptr_[col]; ptr[0] = col_value.x; ptr[4] = col_value.y; ptr[8] = col_value.z; ptr[12] = col_value.h; } template bool TMatrix4x4::isEqual(const TMatrix4x4& m) const throw() { // iterate over all component pointers // and compare the elements for approximate equality for (Position i = 0; i < 16; i++) { if (Maths::isEqual(*comp_ptr_[i], *m.comp_ptr_[i]) == false) { return false; } } return true; } template TVector4TMatrix4x4::getDiagonal() const throw() { return TVector4(m11, m22, m33, m44); } template BALL_INLINE T& TMatrix4x4::operator () (Position row, Position col) throw(Exception::IndexOverflow) { if ((row > 3) || (col > 3)) { throw Exception::IndexOverflow(__FILE__, __LINE__, row + col, 3); } return *comp_ptr_[4 * row + col]; } template BALL_INLINE const T& TMatrix4x4::operator () (Position row, Position col) const throw(Exception::IndexOverflow) { if ((row > 3) || (col > 3)) { throw Exception::IndexOverflow(__FILE__, __LINE__, row + col, 3); } return *comp_ptr_[4 * row + col]; } template BALL_INLINE const T& TMatrix4x4::operator [] (Position position) const throw(Exception::IndexOverflow) { if (position > 15) { throw Exception::IndexOverflow(__FILE__, __LINE__, position, 15); } return *comp_ptr_[position]; } template BALL_INLINE T& TMatrix4x4::operator [] (Position position) throw(Exception::IndexOverflow) { if (position > 15) { throw Exception::IndexOverflow(__FILE__, __LINE__, position, 15); } return *comp_ptr_[position]; } template BALL_INLINE TMatrix4x4 TMatrix4x4::operator + () const throw() { return *this; } template BALL_INLINE TMatrix4x4 TMatrix4x4::operator - () const throw() { return TMatrix4x4 (-m11, -m12, -m13, -m14, -m21, -m22, -m23, -m24, -m31, -m32, -m33, -m34, -m41, -m42, -m43, -m44); } template TMatrix4x4 TMatrix4x4::operator + (const TMatrix4x4& m) const throw() { return TMatrix4x4 (m11 + m.m11, m12 + m.m12, m13 + m.m13, m14 + m.m14, m21 + m.m21, m22 + m.m22, m23 + m.m23, m24 + m.m24, m31 + m.m31, m32 + m.m32, m33 + m.m33, m34 + m.m34, m41 + m.m41, m42 + m.m42, m43 + m.m43, m44 + m.m44); } template TMatrix4x4& TMatrix4x4::operator += (const TMatrix4x4& m) throw() { m11 += m.m11; m12 += m.m12; m13 += m.m13; m14 += m.m14; m21 += m.m21; m22 += m.m22; m23 += m.m23; m24 += m.m24; m31 += m.m31; m32 += m.m32; m33 += m.m33; m34 += m.m34; m41 += m.m41; m42 += m.m42; m43 += m.m43; m44 += m.m44; return *this; } template TMatrix4x4 TMatrix4x4::operator - (const TMatrix4x4& m) const throw() { return TMatrix4x4 (m11 - m.m11, m12 - m.m12, m13 - m.m13, m14 - m.m14, m21 - m.m21, m22 - m.m22, m23 - m.m23, m24 - m.m24, m31 - m.m31, m32 - m.m32, m33 - m.m33, m34 - m.m34, m41 - m.m41, m42 - m.m42, m43 - m.m43, m44 - m.m44); } template TMatrix4x4& TMatrix4x4::operator -= (const TMatrix4x4& m) throw() { m11 -= m.m11; m12 -= m.m12; m13 -= m.m13; m14 -= m.m14; m21 -= m.m21; m22 -= m.m22; m23 -= m.m23; m24 -= m.m24; m31 -= m.m31; m32 -= m.m32; m33 -= m.m33; m34 -= m.m34; m41 -= m.m41; m42 -= m.m42; m43 -= m.m43; m44 -= m.m44; return *this; } template TMatrix4x4 TMatrix4x4::operator * (const T& scalar) const throw() { return TMatrix4x4 (m11 * scalar, m12 * scalar, m13 * scalar, m14 * scalar, m21 * scalar, m22 * scalar, m23 * scalar, m24 * scalar, m31 * scalar, m32 * scalar, m33 * scalar, m34 * scalar, m41 * scalar, m42 * scalar, m43 * scalar, m44 * scalar); } template TMatrix4x4 operator * (const T& scalar, const TMatrix4x4& m) throw() { return TMatrix4x4 (scalar * m.m11, scalar * m.m12, scalar * m.m13, scalar * m.m14, scalar * m.m21, scalar * m.m22, scalar * m.m23, scalar * m.m24, scalar * m.m31, scalar * m.m32, scalar * m.m33, scalar * m.m34, scalar * m.m41, scalar * m.m42, scalar * m.m43, scalar * m.m44); } template TMatrix4x4& TMatrix4x4::operator *= (const T& scalar) throw() { m11 *= scalar; m12 *= scalar; m13 *= scalar; m14 *= scalar; m21 *= scalar; m22 *= scalar; m23 *= scalar; m24 *= scalar; m31 *= scalar; m32 *= scalar; m33 *= scalar; m34 *= scalar; m41 *= scalar; m42 *= scalar; m43 *= scalar; m44 *= scalar; return *this; } template TVector3 operator *(const TMatrix4x4& matrix, const TVector3& vector) throw() { return TVector3 (matrix.m11 * vector.x + matrix.m12 * vector.y + matrix.m13 * vector.z + matrix.m14, matrix.m21 * vector.x + matrix.m22 * vector.y + matrix.m23 * vector.z + matrix.m24, matrix.m31 * vector.x + matrix.m32 * vector.y + matrix.m33 * vector.z + matrix.m34); } template BALL_INLINE TMatrix4x4TMatrix4x4::operator / (const T& scalar) const throw(Exception::DivisionByZero) { if (scalar == (T)0) { throw Exception::DivisionByZero(__FILE__, __LINE__); } return (*this * ((T)1 / scalar)); } template BALL_INLINE TMatrix4x4& TMatrix4x4::operator /= (const T& scalar) throw(Exception::DivisionByZero) { if (scalar == (T)0) { throw Exception::DivisionByZero(__FILE__, __LINE__); } return (*this *= (T)1 / scalar); } template TMatrix4x4 TMatrix4x4::operator * (const TMatrix4x4& m) const throw() { return TMatrix4x4 (m11 * m.m11 + m12 * m.m21 + m13 * m.m31 + m14 * m.m41, m11 * m.m12 + m12 * m.m22 + m13 * m.m32 + m14 * m.m42, m11 * m.m13 + m12 * m.m23 + m13 * m.m33 + m14 * m.m43, m11 * m.m14 + m12 * m.m24 + m13 * m.m34 + m14 * m.m44, m21 * m.m11 + m22 * m.m21 + m23 * m.m31 + m24 * m.m41, m21 * m.m12 + m22 * m.m22 + m23 * m.m32 + m24 * m.m42, m21 * m.m13 + m22 * m.m23 + m23 * m.m33 + m24 * m.m43, m21 * m.m14 + m22 * m.m24 + m23 * m.m34 + m24 * m.m44, m31 * m.m11 + m32 * m.m21 + m33 * m.m31 + m34 * m.m41, m31 * m.m12 + m32 * m.m22 + m33 * m.m32 + m34 * m.m42, m31 * m.m13 + m32 * m.m23 + m33 * m.m33 + m34 * m.m43, m31 * m.m14 + m32 * m.m24 + m33 * m.m34 + m34 * m.m44, m41 * m.m11 + m42 * m.m21 + m43 * m.m31 + m44 * m.m41, m41 * m.m12 + m42 * m.m22 + m43 * m.m32 + m44 * m.m42, m41 * m.m13 + m42 * m.m23 + m43 * m.m33 + m44 * m.m43, m41 * m.m14 + m42 * m.m24 + m43 * m.m34 + m44 * m.m44); } template TMatrix4x4& TMatrix4x4::operator *= (const TMatrix4x4& m) throw() { set(m11 * m.m11 + m12 * m.m21 + m13 * m.m31 + m14 * m.m41, m11 * m.m12 + m12 * m.m22 + m13 * m.m32 + m14 * m.m42, m11 * m.m13 + m12 * m.m23 + m13 * m.m33 + m14 * m.m43, m11 * m.m14 + m12 * m.m24 + m13 * m.m34 + m14 * m.m44, m21 * m.m11 + m22 * m.m21 + m23 * m.m31 + m24 * m.m41, m21 * m.m12 + m22 * m.m22 + m23 * m.m32 + m24 * m.m42, m21 * m.m13 + m22 * m.m23 + m23 * m.m33 + m24 * m.m43, m21 * m.m14 + m22 * m.m24 + m23 * m.m34 + m24 * m.m44, m31 * m.m11 + m32 * m.m21 + m33 * m.m31 + m34 * m.m41, m31 * m.m12 + m32 * m.m22 + m33 * m.m32 + m34 * m.m42, m31 * m.m13 + m32 * m.m23 + m33 * m.m33 + m34 * m.m43, m31 * m.m14 + m32 * m.m24 + m33 * m.m34 + m34 * m.m44, m41 * m.m11 + m42 * m.m21 + m43 * m.m31 + m44 * m.m41, m41 * m.m12 + m42 * m.m22 + m43 * m.m32 + m44 * m.m42, m41 * m.m13 + m42 * m.m23 + m43 * m.m33 + m44 * m.m43, m41 * m.m14 + m42 * m.m24 + m43 * m.m34 + m44 * m.m44); return *this; } template TVector4 TMatrix4x4::operator * (const TVector4& v) const throw() { return TVector4 (m11 * v.x + m12 * v.y + m13 * v.z + m14 * v.h, m21 * v.x + m22 * v.y + m23 * v.z + m24 * v.h, m31 * v.x + m32 * v.y + m33 * v.z + m34 * v.h, m41 * v.x + m42 * v.y + m43 * v.z + m44 * v.h); } template bool TMatrix4x4::invert(TMatrix4x4& inverse) const throw() { /** First, we compute a QR decomposition, then we use it to solve * the system A*A^-1 = I <=> R * A^-1 = Q^t, where R is upper * triangular. * * This is based on the Householder transform algorithm given in * the Numerical Recipes. */ Index i, j, k; T a[4][4] = // holds the matrix we want to invert { { m11, m12, m13, m14 }, { m21, m22, m23, m24 }, { m31, m32, m33, m34 }, { m41, m42, m43, m44 } }; // holds the maximum in the part of A we still have to work with T scale, sum_of_squares, sigma, tau; T c[4], d[4]; for (k=0; k<3; k++) { scale = (T)0; // find the maximum in a for (i=k; i<4; i++) scale = Maths::max((T)fabs(a[i][k]), scale); // is the matrix singular? if (scale == (T)0) return false; // nope. we can normalize the remaining rows for (i=k; i<4; i++) a[i][k] /= scale; sum_of_squares = (T)0; for (i=k; i<4; i++) sum_of_squares += a[i][k]*a[i][k]; // shift the diagonal element sigma = (a[k][k] >= 0) ? sqrt(sum_of_squares) : -sqrt(sum_of_squares); a[k][k] += sigma; c[k] = sigma*a[k][k]; d[k] = -scale*sigma; for (j = k+1; j<4; j++) { // store the scalar product of a_[k] and a_[j] sum_of_squares = (T)0; for (i = k; i<4; i++) sum_of_squares += a[i][k] * a[i][j]; tau = sum_of_squares / c[k]; // prepare the matrix for (i=k; i<4; i++) a[i][j] -= tau*a[i][k]; } } d[3] = a[3][3]; // is the matrix singular? if (d[3] == (T)0) return 1; // now we have the QR decomposition. The upper triangle of A contains // R, except for the diagonal elements, which are stored in d. c contains // the values needed to compute the Householder matrices Q, and the vectors // u needed for the determination of the Qs are stored in the lower triangle // of A // // now we need to solve four linear systems of equations, one for each column // of the resulting matrix T result[4][4]; result[0][0] = 1; result[0][1] = 0; result[0][2] = 0; result[0][3] = 0; result[1][0] = 0; result[1][1] = 1; result[1][2] = 0; result[1][3] = 0; result[2][0] = 0; result[2][1] = 0; result[2][2] = 1; result[2][3] = 0; result[3][0] = 0; result[3][1] = 0; result[3][2] = 0; result[3][3] = 1; for (k=0; k<4; k++) // k generates the k-th column of the inverse { // form the vector Q^t * b, which is simple, since b = e_k for (j=0; j<3; j++) { sum_of_squares = (T)0; for (i=j; i<4; i++) sum_of_squares += a[i][j]*result[i][k]; tau = sum_of_squares / c[j]; for (i=j; i<4; i++) result[i][k] -= tau*a[i][j]; } // and solve the resulting system result[3][k] /= d[3]; for (i=2; i>=0; i--) { sum_of_squares = (T)0; for (j=i+1; j<4; j++) sum_of_squares += a[i][j] * result[j][k]; result[i][k] = (result[i][k] - sum_of_squares) / d[i]; } } T* k_ptr = *result; inverse.m11 = *k_ptr++; inverse.m12 = *k_ptr++; inverse.m13 = *k_ptr++; inverse.m14 = *k_ptr++; inverse.m21 = *k_ptr++; inverse.m22 = *k_ptr++; inverse.m23 = *k_ptr++; inverse.m24 = *k_ptr++; inverse.m31 = *k_ptr++; inverse.m32 = *k_ptr++; inverse.m33 = *k_ptr++; inverse.m34 = *k_ptr++; inverse.m41 = *k_ptr++; inverse.m42 = *k_ptr++; inverse.m43 = *k_ptr++; inverse.m44 = *k_ptr; return true; } template BALL_INLINE bool TMatrix4x4::invert() throw() { return invert(*this); } template T TMatrix4x4::getDeterminant() const throw() { Position i; Position j; Position k; T submatrix[3][3]; T matrix[4][4] = { { m11, m12, m13, m14 }, { m21, m22, m23, m24 }, { m31, m32, m33, m34 }, { m41, m42, m43, m44 } }; T determinant = 0; for (i = 0; i < 4; i++) { for (j = 0; j < 3; j++) { for (k = 0; k < 3; k++) { submatrix[j][k] = matrix[j + 1][(k < i) ? k : k + 1]; } } determinant += matrix[0][i] * (T)(i / 2.0 == (i >> 1) ? 1 : -1) * (submatrix[0][0] * submatrix[1][1] * submatrix[2][2] + submatrix[0][1] * submatrix[1][2] * submatrix[2][0] + submatrix[0][2] * submatrix[1][0] * submatrix[2][1] - submatrix[0][2] * submatrix[1][1] * submatrix[2][0] - submatrix[0][0] * submatrix[1][2] * submatrix[2][1] - submatrix[0][1] * submatrix[1][0] * submatrix[2][2]); } return determinant; } template void TMatrix4x4::translate(const T& x, const T& y, const T& z) throw() { m14 += m11 * x + m12 * y + m13 * z; m24 += m21 * x + m22 * y + m23 * z; m34 += m31 * x + m32 * y + m33 * z; m44 += m41 * x + m42 * y + m43 * z; } template void TMatrix4x4::translate(const TVector3& v) throw() { m14 += m11 * v.x + m12 * v.y + m13 * v.z; m24 += m21 * v.x + m22 * v.y + m23 * v.z; m34 += m31 * v.x + m32 * v.y + m33 * v.z; m44 += m41 * v.x + m42 * v.y + m43 * v.z; } template void TMatrix4x4::setTranslation(const T& x, const T& y, const T& z) throw() { m11 = m22 = m33 = m44 = 1; m12 = m13 = m21 = m23 = m31 = m32 = m41 = m42 = m43 = 0; m14 = x; m24 = y; m34 = z; } template void TMatrix4x4::setTranslation(const TVector3& v) throw() { m11 = m22 = m33 = m44 = 1; m12 = m13 = m21 = m23 = m31 = m32 = m41 = m42 = m43 = 0; m14 = v.x; m24 = v.y; m34 = v.z; } template void TMatrix4x4::scale(const T& x_scale, const T& y_scale, const T& z_scale) throw() { m11 *= x_scale; m21 *= x_scale; m31 *= x_scale; m41 *= x_scale; m12 *= y_scale; m22 *= y_scale; m32 *= y_scale; m42 *= y_scale; m13 *= z_scale; m23 *= z_scale; m33 *= z_scale; m43 *= z_scale; } template void TMatrix4x4::scale(const T& scale) throw() { m11 *= scale; m21 *= scale; m31 *= scale; m41 *= scale; m12 *= scale; m22 *= scale; m32 *= scale; m42 *= scale; m13 *= scale; m23 *= scale; m33 *= scale; m43 *= scale; } template void TMatrix4x4::scale(const TVector3& v) throw() { m11 *= v.x; m21 *= v.x; m31 *= v.x; m41 *= v.x; m12 *= v.y; m22 *= v.y; m32 *= v.y; m42 *= v.y; m13 *= v.z; m23 *= v.z; m33 *= v.z; m43 *= v.z; } template void TMatrix4x4::setScale(const T& x_scale, const T& y_scale, const T& z_scale) throw() { m11 = x_scale; m22 = y_scale; m33 = z_scale; m44 = 1; m12 = m13 = m14 = m21 = m23 = m24 = m31 = m32 = m34 = m41 = m42 = m43 = 0; } template void TMatrix4x4::setScale(const T& scale) throw() { m11 = scale; m22 = scale; m33 = scale; m44 = 1; m12 = m13 = m14 = m21 = m23 = m24 = m31 = m32 = m34 = m41 = m42 = m43 = 0; } template void TMatrix4x4::setScale(const TVector3& v) throw() { m11 = v.x; m22 = v.y; m33 = v.z; m44 = 1; m12 = m13 = m14 = m21 = m23 = m24 = m31 = m32 = m34 = m41 = m42 = m43 = 0; } template BALL_INLINE void TMatrix4x4::rotateX(const TAngle& phi) throw() { TMatrix4x4 rotation; rotation.setRotationX(phi); *this *= rotation; } template void TMatrix4x4::setRotationX(const TAngle& phi) throw() { m11 = m44 = 1; m12 = m13 = m14 = m21 = m24 = m31 = m34 = m41 = m42 = m43 = 0; m22 = m33 = cos(phi); m23 = -(m32 = sin(phi)); } template BALL_INLINE void TMatrix4x4::rotateY(const TAngle& phi) throw() { TMatrix4x4 rotation; rotation.setRotationY(phi); *this *= rotation; } template void TMatrix4x4::setRotationY(const TAngle& phi) throw() { m22 = m44 = 1; m12 = m14 = m21 = m23 = m24 = m32 = m34 = m41 = m42 = m43 = 0; m11 = m33 = cos(phi); m31 = -(m13 = sin(phi)); } template BALL_INLINE void TMatrix4x4::rotateZ(const TAngle& phi) throw() { TMatrix4x4 rotation; rotation.setRotationZ(phi); *this *= rotation; } template void TMatrix4x4::setRotationZ(const TAngle& phi) throw() { m33 = m44 = 1; m13 = m14 = m23 = m24 = m31 = m32 = m34 = m41 = m42 = m43 = 0; m11 = m22 = cos(phi); m12 = -(m21 = sin(phi)); } template BALL_INLINE void TMatrix4x4::rotate(const TAngle& phi, const TVector3& v) throw() { rotate(phi, v.x, v.y, v.z); } template BALL_INLINE void TMatrix4x4::rotate(const TAngle& phi, const TVector4& v) throw() { rotate(phi, v.x, v.y, v.z); } // // Arbitrary axis rotation matrix. // // [Taken from the MESA-Library. But modified for additional Speed-Up.] // // This function was contributed by Erich Boleyn (erich@uruk.org). // // This is composed of 5 matrices, Rz, Ry, T, Ry', Rz', multiplied // like so: Rz * Ry * T * Ry' * Rz'. T is the final rotation // (which is about the X-axis), and the two composite transforms // Ry' * Rz' and Rz * Ry are (respectively) the rotations necessary // from the arbitrary axis to the X-axis then back. They are // all elementary rotations. // // Rz' is a rotation about the Z-axis, to bring the axis vector // into the x-z plane. Then Ry' is applied, rotating about the // Y-axis to bring the axis vector parallel with the X-axis. The // rotation about the X-axis is then performed. Ry and Rz are // simply the respective inverse transforms to bring the arbitrary // axis back to it's original orientation. The first transforms // Rz' and Ry' are considered inverses, since the data from the // arbitrary axis gives you info on how to get to it, not how // to get away from it, and an inverse must be applied. // // The basic calculation used is to recognize that the arbitrary // axis vector (x, y, z), since it is of unit length, actually // represents the sines and cosines of the angles to rotate the // X-axis to the same orientation, with theta being the angle about // Z and phi the angle about Y (in the order described above) // as follows: // // cos ( theta ) = x / sqrt ( 1 - z^2 ) // sin ( theta ) = y / sqrt ( 1 - z^2 ) // // cos ( phi ) = sqrt ( 1 - z^2 ) // sin ( phi ) = z // // Note that cos ( phi ) can further be inserted to the above // formulas: // // cos ( theta ) = x / cos ( phi ) // sin ( theta ) = y / sin ( phi ) // // ...etc. Because of those relations and the standard trigonometric // relations, it is pssible to reduce the transforms down to what // is used below. It may be that any primary axis chosen will give the // same results (modulo a sign convention) using thie method. // // Particularly nice is to notice that all divisions that might // have caused trouble when parallel to certain planes or // axis go away with care paid to reducing the expressions. // After checking, it does perform correctly under all cases, since // in all the cases of division where the denominator would have // been zero, the numerator would have been zero as well, giving // the expected result. template void TMatrix4x4::rotate(const TAngle& phi, const T& ax, const T& ay, const T& az) throw() { T xx, yy, zz, xy, yz, zx, xs, ys, zs, one_c; T x = ax; T y = ay; T z = az; double sin_angle = sin(phi); double cos_angle = cos(phi); xx = x * x; yy = y * y; zz = z * z; T mag = sqrt(xx + yy + zz); if (mag == (T)0) { m12 = m13 = m14 = m21 = m23 = m24 = m31 = m32 = m34 = m41 = m42 = m43 = 0; m11 = m22 = m33 = m44 = (T)1; } x /= mag; y /= mag; z /= mag; // we need to recalculate xx, yy, zz due to the // normalization. recalculation is probably faster // than normalizing xx, yy, zz xx = x*x; yy = y*y; zz = z*z; xy = x * y; yz = y * z; zx = z * x; xs = (T) (x * sin_angle); ys = (T) (y * sin_angle); zs = (T) (z * sin_angle); one_c = (T) (1 - cos_angle); m11 = (T)( (one_c * xx) + cos_angle ); m12 = (one_c * xy) - zs; m13 = (one_c * zx) + ys; m14 = 0; m21 = (one_c * xy) + zs; m22 = (T) ((one_c * yy) + cos_angle); m23 = (one_c * yz) - xs; m24 = 0; m31 = (one_c * zx) - ys; m32 = (one_c * yz) + xs; m33 = (T) ((one_c * zz) + cos_angle); m34 = 0; m41 = 0; m42 = 0; m43 = 0; m44 = 1; } template void TMatrix4x4::setRotation(const TAngle& phi, const T& x, const T& y, const T& z) throw() { m12 = m13 = m14 = m21 = m23 = m24 = m31 = m32 = m34 = m41 = m42 = m43 = 0; m11 = m22 = m33 = m44 = (T)1; rotate(phi, x, y, z); } template BALL_INLINE void TMatrix4x4::setRotation(const TAngle& phi, const TVector3& v) throw() { m12 = m13 = m14 = m21 = m23 = m24 = m31 = m32 = m34 = m41 = m42 = m43 = 0; m11 = m22 = m33 = m44 = (T)1; rotate(phi, v.x, v.y, v.z); } template BALL_INLINE void TMatrix4x4::setRotation(const TAngle& phi, const TVector4& v) throw() { m12 = m13 = m14 = m21 = m23 = m24 = m31 = m32 = m34 = m41 = m42 = m43 = 0; m11 = m22 = m33 = m44 = (T)1; rotate(phi, v.x, v.y, v.z); } template bool TMatrix4x4::operator == (const TMatrix4x4& m) const throw() { return ( m11 == m.m11 && m12 == m.m12 && m13 == m.m13 && m14 == m.m14 && m21 == m.m21 && m22 == m.m22 && m23 == m.m23 && m24 == m.m24 && m31 == m.m31 && m32 == m.m32 && m33 == m.m33 && m34 == m.m34 && m41 == m.m41 && m42 == m.m42 && m43 == m.m43 && m44 == m.m44); } template bool TMatrix4x4::operator != (const TMatrix4x4& m) const throw() { return ( m11 != m.m11 || m12 != m.m12 || m13 != m.m13 || m14 != m.m14 || m21 != m.m21 || m22 != m.m22 || m23 != m.m23 || m24 != m.m24 || m31 != m.m31 || m32 != m.m32 || m33 != m.m33 || m34 != m.m34 || m41 != m.m41 || m42 != m.m42 || m43 != m.m43 || m44 != m.m44); } template bool TMatrix4x4::isIdentity() const throw() { return ( m11 == (T)1 && m12 == (T)0 && m13 == (T)0 && m14 == (T)0 && m21 == (T)0 && m22 == (T)1 && m23 == (T)0 && m24 == (T)0 && m31 == (T)0 && m32 == (T)0 && m33 == (T)1 && m34 == (T)0 && m41 == (T)0 && m42 == (T)0 && m43 == (T)0 && m44 == (T)1); } template BALL_INLINE bool TMatrix4x4::isRegular() const throw() { return (getDeterminant() != (T)0); } template BALL_INLINE bool TMatrix4x4::isSingular() const throw() { return (getDeterminant() == (T)0); } template bool TMatrix4x4::isSymmetric() const throw() { return ( m12 == m21 && m13 == m31 && m14 == m41 && m23 == m32 && m24 == m42 && m34 == m43); } template bool TMatrix4x4::isLowerTriangular() const throw() { return ( m12 == (T)0 && m13 == (T)0 && m14 == (T)0 && m23 == (T)0 && m24 == (T)0 && m34 == (T)0); } template bool TMatrix4x4::isUpperTriangular() const throw() { return ( m21 == (T)0 && m31 == (T)0 && m32 == (T)0 && m41 == (T)0 && m42 == (T)0 && m43 == (T)0); } template BALL_INLINE bool TMatrix4x4::isDiagonal() const throw() { return ( m12 == (T)0 && m13 == (T)0 && m14 == (T)0 && m21 == (T)0 && m23 == (T)0 && m24 == (T)0 && m31 == (T)0 && m32 == (T)0 && m34 == (T)0 && m41 == (T)0 && m42 == (T)0 && m43 == (T)0); } template bool TMatrix4x4::isValid() const throw() { T **ptr = (T **)comp_ptr_; return ( *ptr++ == &m11 && *ptr++ == &m12 && *ptr++ == &m13 && *ptr++ == &m14 && *ptr++ == &m21 && *ptr++ == &m22 && *ptr++ == &m23 && *ptr++ == &m24 && *ptr++ == &m31 && *ptr++ == &m32 && *ptr++ == &m33 && *ptr++ == &m34 && *ptr++ == &m41 && *ptr++ == &m42 && *ptr++ == &m43 && *ptr == &m44); } template std::istream& operator >> (std::istream& s, TMatrix4x4& m) throw() { char c; s >> c >> m.m11 >> m.m12 >> m.m13 >> m.m14 >> c >> c >> m.m21 >> m.m22 >> m.m23 >> m.m24 >> c >> c >> m.m31 >> m.m32 >> m.m33 >> m.m34 >> c >> c >> m.m41 >> m.m42 >> m.m43 >> m.m44 >> c; return s; } template std::ostream& operator << (std::ostream& s, const TMatrix4x4& m) throw() { s << '/' << std::setw(14) << m.m11 << ' ' << std::setw(14) << m.m12 << ' ' << std::setw(14) << m.m13 << ' ' << std::setw(14) << m.m14 << " \\" << std::endl << '|' << std::setw(14) << m.m21 << ' ' << std::setw(14) << m.m22 << ' ' << std::setw(14) << m.m23 << ' ' << std::setw(14) << m.m24 << " |" << std::endl << '|' << std::setw(14) << m.m31 << ' ' << std::setw(14) << m.m32 << ' ' << std::setw(14) << m.m33 << ' ' << std::setw(14) << m.m34 << " |" << std::endl << '\\' << std::setw(14) << m.m41 << ' ' << std::setw(14) << m.m42 << ' ' << std::setw(14) << m.m43 << ' ' << std::setw(14) << m.m44 << " /" << std::endl; return s; } template void TMatrix4x4::dump(std::ostream& s, Size depth) const throw() { BALL_DUMP_STREAM_PREFIX(s); BALL_DUMP_HEADER(s, this, this); BALL_DUMP_DEPTH(s, depth); s << m11 << " " << m12 << " " << m13 << " " << m14 << std::endl; BALL_DUMP_DEPTH(s, depth); s << m21 << " " << m22 << " " << m23 << " " << m24 << std::endl; BALL_DUMP_DEPTH(s, depth); s << m31 << " " << m32 << " " << m33 << " " << m34 << std::endl; BALL_DUMP_DEPTH(s, depth); s << m41 << " " << m42 << " " << m43 << " " << m44 << std::endl; BALL_DUMP_STREAM_SUFFIX(s); } /// template TMatrix4x4 operator * (const T& scalar, const TMatrix4x4& m) throw(); /// template TVector3 operator * (const TMatrix4x4& matrix, const TVector3& vector) throw(); /** The Default TMatrix4x4 Type. This default is predefined for convenience for those cases where single precision is sufficient. \ingroup Matrix44 */ typedef TMatrix4x4 Matrix4x4; } // namespace BALL #endif // BALL_MATHS_MATRIX44_H ugene-1.9.8/src/plugins_3rdparty/ball/src/include/BALL/MATHS/circle3.h0000644000175000017500000001603211651544325023631 0ustar ilyailya// -*- Mode: C++; tab-width: 2; -*- // vi: set ts=2: // // $Id: circle3.h,v 1.42 2004-07-05 20:57:28 oliver Exp $ // #ifndef BALL_MATHS_CIRCLE3_H #define BALL_MATHS_CIRCLE3_H #ifndef BALL_COMMON_EXCEPTION_H # include #endif #ifndef BALL_MATHS_VECTOR3_H # include #endif namespace BALL { /** \defgroup Circle Generic three-dimensional circle. \ingroup GeometricObjects */ //@{ template class TCircle3; /** @name Storers \ingroup Circle */ //@{ /// template std::istream& operator >> (std::istream& s, TCircle3& circle) throw(); /// template std::ostream& operator << (std::ostream& s, const TCircle3& circle) throw(); //@} /** Generic Circle in Three-Dimensional Space. */ template class TCircle3 { public: BALL_CREATE(TCircle3) /** @name Constructors and Destructors */ //@{ /** Default constructor. This method creates a new TCircle3 object. The three components are initialized to 0. */ TCircle3() throw() : p(), n(), radius(0) { } /** Copy constructor. Create a new TCircle3 object from another. @param circle the TCircle3 object to be copied */ TCircle3(const TCircle3& circle) throw() : p(circle.p), n(circle.n), radius(circle.radius) { } /** Detailed constructor. Create a new TCircle3 object from the central point, the normal and a radius. @param point assigned to the point @param normal assigned to the normal @param radius assigned tp the radius */ TCircle3(const TVector3& point, const TVector3& normal, const T& radius) throw() : p(point), n(normal), radius(radius) { } /** Destructor. Destructs the TCircle3 object. As there are no dynamic data structures, nothing happens. */ virtual ~TCircle3() throw() { } /** Clear method. The values are set to 0. */ virtual void clear() throw() { p.clear(); n.clear(); radius = (T)0; } //@} /** @name Assignment */ //@{ /** Swap the contents of two circles. @param circle the circle to swap contents with */ void swap(TCircle3& circle) throw() { TVector3 temp_vector(p); p = circle.p; circle.p = temp_vector; temp_vector = n; n = circle.n; circle.n = temp_vector; T temp = radius; radius = circle.radius; circle.radius = temp; } /** Assign from another TCircle3. @param circle the TCirce3 object to assign from */ void set(const TCircle3& circle) throw() { p = circle.p; n = circle.n; radius = circle.radius; } /** Assign the circle components. @param point assigned to the point @param normal assigned to the normal @param rad assigned to the radius */ void set(const TVector3& point, const TVector3& normal, const T& rad) throw() { p = point; n = normal; radius = rad; } /** Assignment operator. Assign the components from another circle. @param circle the circle to assign from **/ TCircle3& operator = (const TCircle3& circle) throw() { p = circle.p; n = circle.n; radius = circle.radius; return *this; } /** Assign to another TCircle3. Assigns the components to another circle. @param circle the circle to be assigned to */ void get(TCircle3& circle) const throw() { circle.p = p; circle.n = n; circle.radius = radius; } /** Assign to two variables of type TVector3 and one T value. @param point the center point @param normal the circle normal @param rhs the radius */ void get(TVector3& point, TVector3& normal, T& rhs) const throw() { point = p; normal = n; rhs = radius; } //@} /** @name Predicates */ //@{ /** Equality operator. @return bool, true if all components are equal, false otherwise */ bool operator == (const TCircle3& circle) const throw() { return (p == circle.p && n == circle.n && Maths::isEqual(radius, circle.radius)); } /** Inequality operator. @return bool, false if all components are equal, true otherwise */ bool operator != (const TCircle3& circle) const throw() { return (p != circle.p || n != circle.n || Maths::isNotEqual(radius, circle.radius)); } /** Test if a given point is a member of the circle. Optional it can be testet, if the point lies on the surface. @param point the point to be tested @param on_surface true to test the surface (default = false) @return bool, true or false */ bool has(const TVector3& point, bool on_surface = false) const throw() { if (on_surface) { return (Maths::isZero(n * (point - p)) && Maths::isEqual(p.getDistance(point), radius)); } else { return (Maths::isZero(n * (point - p)) && Maths::isLessOrEqual(p.getDistance(point), radius)); } } //@} /** @name Debugging and Diagnostics */ //@{ /** Test if instance is valid. Always returns true @return bool true */ bool isValid() const throw() { return true; } /** Internal state dump. Dump the current internal state of {\em *this} to the output ostream s with dumping depth depth . @param s - output stream where to output the internal state of {\em *this} @param depth - the dumping depth */ void dump(std::ostream& s = std::cout, Size depth = 0) const throw() { BALL_DUMP_STREAM_PREFIX(s); BALL_DUMP_HEADER(s, this, this); BALL_DUMP_DEPTH(s, depth); s << " position: " << p << std::endl; BALL_DUMP_DEPTH(s, depth); s << " normal: " << n << std::endl; BALL_DUMP_DEPTH(s, depth); s << " radius: " << radius << std::endl; BALL_DUMP_STREAM_SUFFIX(s); } //@} /** @name Attributes */ //@{ /** Circle Center. This point describes the center of the circle. */ TVector3 p; /** Normal vector. This vector is orthogonal to the circle's plane. */ TVector3 n; /** Radius. The radius of the circle. */ T radius; //@} }; //@} /** Default three-dimensional circle class of type float \ingroup Circle */ typedef TCircle3 Circle3; /** Input operator. Reads in two TVector3 and a T value: p, n, radius */ template std::istream& operator >> (std::istream& s, TCircle3& circle) throw() { char c; s >> c; s >> circle.p >> circle.n >> circle.radius; s >> c; return s; } /** Output Operator. Writes the values of p, n, and radius to an output stream. The three values are separated by spaces and enclosed in brackets. \par Example: \par ((0 0 0) (1 2 1) 3.5) @see TVector3::operator<< */ template std::ostream& operator << (std::ostream& s, const TCircle3& circle) throw() { return s << '(' << circle.p << ' ' << circle.n << ' ' << circle.radius << ')'; } } // namespace BALL #endif // BALL_MATHS_CIRCLE3_H ugene-1.9.8/src/plugins_3rdparty/ball/src/include/BALL/MATHS/plane3.h0000644000175000017500000001773511651544325023502 0ustar ilyailya// -*- Mode: C++; tab-width: 2; -*- // vi: set ts=2: // // $Id: plane3.h,v 1.38 2004-05-27 19:49:42 oliver Exp $ // #ifndef BALL_MATHS_PLANE3_H #define BALL_MATHS_PLANE3_H #ifdef BALL_HAS_IEEEFP_H # include #endif #include #include #ifndef BALL_MATHS_LINE3_H # include #endif #ifndef BALL_MATHS_VECTOR3_H # include #endif #ifndef BALL_MATHS_COMMON_H # include #endif namespace BALL { /** \defgroup Plane Plane in three-dimensional space. \ingroup GeometricObjects */ //@{ template class TPlane3; /** @name Storers Stream operators for class TPlane3 */ //@{ template std::istream& operator >> (std::istream& s, TPlane3& plane) throw(); template std::ostream& operator << (std::ostream& s, const TPlane3& plane) throw(); //@} /** Threedimensional plane. A plane is defined by a point and its normal. */ template class TPlane3 { public: BALL_CREATE(TPlane3) /** @name Constructors and Destructors */ //@{ /** Default constructor. This method creates a new TPlane3 object. The two components are initialized to (T)0. */ TPlane3() throw() : p(), n() { } /** Copy constructor. Create a new TPlane3 object from another. @param plane the TPlane3 object to be copied */ TPlane3(const TPlane3& plane) throw() : p(plane.p), n(plane.n) { } /** Detailed constructor. Create a new instances of TPlane3 from a point and the normal. @param point assigned to p @param normal assigned to n */ TPlane3(const TVector3& point, const TVector3& normal) throw() : p(point), n(normal) { } /** Detailed constructor. Create a new instance of TPlane3 from three points. @param a assigned to p @param a, b, c are used to calculate the normal n */ TPlane3(const TVector3& a, const TVector3& b, const TVector3& c) throw() : p(a), n((a - b) % (b - c)) { } /** Constructor. Create a new TPlane3 object from four T values. Form: COORDINATE (ax + by + cz + d = 0) @param a, b, c are used to calculate the normal n and the point p */ TPlane3(const T& a, const T& b, const T& c, const T& d) throw(Exception::DivisionByZero) { n = TVector3(a, b, c); if (a == 0 && b == 0 && c == 0) { throw Exception::DivisionByZero(__FILE__, __LINE__); } if (!Maths::isZero(a)) { p.set(-d / a, 0, 0); } else if (!Maths::isZero(b)) { p.set(0, -d / b, 0); } else if (!Maths::isZero(c)) { p.set(0, 0, -d / c); } } /** Destructor. Destructs the TPlane3 object. As there are no dynamic data structures, nothing happens. */ virtual ~TPlane3() throw() { } /** Clear method. The values are set to 0. */ virtual void clear() throw() { n.clear(); p.clear(); } //@} /** @name Assignment */ //@{ /// void swap(TPlane3& plane) throw() { TVector3 temp_point(p); p = plane.p; plane.p = temp_point; temp_point = n; n = plane.n; plane.n = temp_point; } /** Swap the contents of two instances of planes. @param vector the plane to swap contents with @param bool ignored - just for interface consistency */ void set(const TPlane3& plane) throw() { p = plane.p; n = plane.n; } /** Assign from a point and a normal. @param point the new point @param normal the new normal */ void set(const TVector3& point, const TVector3& normal) throw() { p = point; n = normal; } /** Assign from three points. @param a the first point @param b the second point @param c the third point */ void set(const TVector3& a, const TVector3& b, const TVector3& c) throw() { p = a; n = (a - b) % (b - c); } /** Assignment operator. Assign the components from another instance of plane. @param plane the plane to assign from **/ TPlane3& operator = (const TPlane3& plane) throw() { p = plane.p; n = plane.n; return *this; } /** Assign to another instance of Plane3. Assigns the components to another plane. @param plane the plane to be assigned to */ void get(TPlane3& plane) const throw() { plane.p = p; plane.n = n; } /** Assign to a point and a normal. @param point the point to be assigned to @param normal the normal to be assigned to */ void get(TVector3& point, TVector3& normal) const throw() { point = p; normal = n; } //@} /** @name Accessors */ //@{ /** Normalize the the normal of the plane. The normal is scaled with its length: \f$\{x|y|z\} *= \sqrt{x^2 + y^2 + z^2}\f$. @exception DivisionByZero if the length of the normal is 0 */ void normalize() throw(Exception::DivisionByZero) { T length = n.getLength(); // throw an exception on zero length normal if (length == 0.0) { throw Exception::DivisionByZero(__FILE__, __LINE__); } n /= length; } /** Hessify the plane. The normal is scaled with its length: \f$\{x|y|z\} *= \sqrt{x^2 + y^2 + z^2}\f$. If the dot product of the point with the normal is less then zero, the normal is negated. */ void hessify() throw() { normalize(); if (Maths::isLess(n * p, 0)) { n.negate(); } } //@} /** @name Predicates */ //@{ /** Equality operator. @return bool, true if all components are equal, false otherwise */ bool operator == (const TPlane3& plane) const throw() { return (p == plane.p && n == plane.n); } /** Inequality operator. @return bool, false if all components are equal, true otherwise */ bool operator != (const TPlane3& plane) const throw() { return (p != plane.p || n != plane.n); } /** Test whether a given point is a member of the plane. @param point the point to be tested @return bool, true or false */ bool has(const TVector3& point) const throw() { return Maths::isZero(n * (point - p)); } /** Test whether a given line is a member of the plane. @param line the line to be tested @return bool, true or false */ bool has(const TLine3& line) const throw() { return (Maths::isZero(n * line.d) && has(line.p)); } //@} /** @name Debugging and Diagnostics */ //@{ /** Test whether instance is valid. always retruns true @return bool true */ bool isValid() const throw() { return true; } /** Internal state dump. Dump the current internal state of {\em *this} to the output ostream s with dumping depth depth . @param s - output stream where to output the internal state of {\em *this} @param depth - the dumping depth */ void dump(std::ostream& s = std::cout, Size depth = 0) const throw() { BALL_DUMP_STREAM_PREFIX(s); BALL_DUMP_HEADER(s, this, this); BALL_DUMP_DEPTH(s, depth); s << " position: " << p << std::endl; BALL_DUMP_DEPTH(s, depth); s << " normal: " << n << std::endl; BALL_DUMP_STREAM_SUFFIX(s); } //@} /** @name Attributes */ //@{ /** The point */ TVector3 p; /** The normal */ TVector3 n; //@} }; //@} /** Input operator reads in two instances of TVector3: p, n */ template std::istream& operator >> (std::istream& s, TPlane3& plane) throw() { char c; s >> c >> plane.p >> plane.n >> c; return s; } /** Output operator Prints two instances of TVector3: p, n */ template std::ostream& operator << (std::ostream& s, const TPlane3& plane) throw() { return (s << '(' << plane.p << ' ' << plane.n << ')'); } /** Default plane class of type float \ingroup Plane */ typedef TPlane3 Plane3; } // namespace BALL #endif // BALL_MATHS_PLANE3_H ugene-1.9.8/src/plugins_3rdparty/ball/src/include/BALL/MATHS/quaternion.h0000644000175000017500000003141511651544325024474 0ustar ilyailya// -*- Mode: C++; tab-width: 2; -*- // vi: set ts=2: // // $Id: quaternion.h,v 1.43 2004-10-22 20:18:05 amoll Exp $ // #ifndef BALL_MATHS_QUATERNION_H #define BALL_MATHS_QUATERNION_H #ifndef BALL_MATHS_MATRIX44_H # include #endif #ifndef BALL_MATHS_VECTOR3_H # include #endif #include namespace BALL { /** \defgroup Quaternions Quaternion \ingroup Primitives */ //@{ /** Generic Quaternion Class. Representing a rotation in three dimensional space. */ template class TQuaternion { public: BALL_CREATE(TQuaternion) /** @name Constructors and Destructors */ //@{ /** Default constructor. This method creates a new TQuaternion object. The axis-components are initialized to 0, the angle is set to 1. */ TQuaternion() throw(); /** Copy constructor. Create a new TQuaternion object from another. @param TQuaternion the TQuaternion object to be copied */ TQuaternion(const TQuaternion& q) throw(); /** Detailed constructor. Create a new TQuaternion object from a variable of type TVector3 and an angle. @param axis assigned to the axis @param new_angle assigned to the angle */ TQuaternion(const TVector3& axis, const T& new_angle) throw(); /** Detailed constructor. Create a new TQuaternion object from three values of type T and an angle. @param x assigned to the x-component of the axis @param y assigned to the y-component of the axis @param z assigned to the z-component of the axis @param new_angle assigned to the angle */ TQuaternion(const T& x, const T& y, const T& z, const T& new_angle) throw(); /** Destructor. Destructs the TQuaternion object. As there are no dynamic data structures, nothing happens. */ virtual ~TQuaternion() throw(); /** Clear method. The values are set to 0. */ virtual void clear() throw(); //@} /** @name Assignment */ //@{ /// void set(const TQuaternion& q) throw(); /** Assign the TQuaternion components. @param axis the new axis component @param new_angle the new angle component */ void set(const TVector3& axis, const T& new_angle) throw(); /** Assign the TQuaternion components. @param x assigned to the x-component of the axis @param y assigned to the y-component of the axis @param z assigned to the z-component of the axis @param new_angle assigned to the angle */ void set(const T& x, const T& y, const T& z, const T& new_angle) throw(); /** Assign from another TQuaternion. @param q the TQuaternion object to assign from */ TQuaternion& operator = (const TQuaternion& q) throw(); /** Assign to another TQuaternion. Assigns the components to another TQuaternion. @param q the TQuaternion to be assigned to */ void get(TQuaternion& q) const throw(); /** Assign the components to the standard values. The axis-components are set to 0, the angle is set to 1. */ void setIdentity() throw(); /** Swap the contents of two TQuaternion. @param q the TQuaternion to swap contents with */ void swap(TQuaternion& q) throw(); //@} /** @name Accessors */ //@{ /** Get the positive angle rotation. @return T the angle value */ T getAngle() const throw(); /** Get the normalized direction vector of the rotation axis. @return TVector3 the axis */ TVector3 getAxis() throw(Exception::DivisionByZero); /** Get the rotation matrix. @param m the matrix to compute from @return TMatrix4x4 the rotation matrix */ TMatrix4x4& getRotationMatrix(TMatrix4x4& m) const throw(); /** Negative sign. */ TQuaternion operator - () const throw(); /** Get the inverse TQuaternion. @return TQuaternion the inverse TQuaternion */ TQuaternion getInverse() const throw(); /** Return the conjugate TQuaternion. (The axis components are negated.) @return TQuaternion the conjugate TQuaternion */ TQuaternion getConjugate() const throw(); /** Add a TQuaternion to this TQuaternion. @param q the TQuaternion to add @return TQuaternion& {\em *this} */ TQuaternion& operator += (const TQuaternion& q) throw(); /** Substract a TQuaternion from this TQuaternion. @param q the TQuaternion to substract @return TQuaternion& {\em *this} */ TQuaternion& operator -= (const TQuaternion& q) throw(); //@} /** @name Predicates */ //@{ /** Equality operator. @return bool, true if all components are equal, false otherwise */ bool operator == (const TQuaternion& q) const throw(); /** Inequality operator. @return bool, true if the two TQuaternion differ in at least one component, false otherwise */ bool operator != (const TQuaternion& q) const throw(); //@} /** @name Debugging and Diagnostics */ //@{ /** Internal state dump. Dump the current internal state of {\em *this} to the output ostream s with dumping depth depth . @param s - output stream where to output the internal state of {\em *this} @param depth - the dumping depth */ void dump(std::ostream& s = std::cout, Size depth = 0) const throw(); //@} /** @name Attributes */ //@{ /** x component of the axis. */ T i; /** y component of the axis. */ T j; /** z component of the axis. */ T k; /** Angle component. */ T angle; //@} }; //@} template TQuaternion::TQuaternion() throw() : i((T)0), j((T)0), k((T)0), angle((T)1) { } template TQuaternion::TQuaternion(const TQuaternion& q) throw() : i(q.i), j(q.j), k(q.k), angle(q.angle) { } template TQuaternion::TQuaternion(const TVector3& axis, const T& new_angle) throw() { set(axis.x, axis.y, axis.z, new_angle); } template TQuaternion::TQuaternion(const T& x, const T& y, const T& z, const T& new_angle) throw() { set(x, y, z, new_angle); } template void TQuaternion::clear() throw() { i = j = k = (T)0; angle = (T)1; } template TQuaternion::~TQuaternion() throw() { } template void TQuaternion::set(const TQuaternion& q) throw() { if (this != &q) { i = q.i; j = q.j; k = q.k; angle = q.angle; } } template BALL_INLINE void TQuaternion::set(const TVector3& axis, const T& new_angle) throw() { set(axis.x, axis.y, axis.z, new_angle); } template void TQuaternion::set(const T& x, const T& y, const T& z, const T& new_angle) throw() { T length = (T)sqrt(x * x + y * y + z * z); if (Maths::isEqual(length, (T)0)) { i = j = k = (T)0; angle = (T)1; } else { T omega = (T) (new_angle * 0.5); T sin_omega = (T)::sin(omega); i = x * sin_omega / length; j = y * sin_omega / length; k = z * sin_omega / length; angle = (T)::cos(omega); } } template BALL_INLINE TQuaternion& TQuaternion::operator = (const TQuaternion& q) throw() { set(q); return *this; } template BALL_INLINE void TQuaternion::get(TQuaternion& q) const throw() { q.set(*this); } template BALL_INLINE void TQuaternion::setIdentity() throw() { i = j = k = (T)0; angle = (T)1; } template T TQuaternion::getAngle() const throw() { return (T)(2.0 * atan2(sqrt(i * i + j * j + k * k), angle)); } template TVector3 TQuaternion::getAxis() throw(Exception::DivisionByZero) { TVector3 vector(i, j, k); T length = vector.getLength(); if (length == (T)0) { throw Exception::DivisionByZero(__FILE__, __LINE__); } vector.x /= length; vector.y /= length; vector.z /= length; return vector; } template TMatrix4x4& TQuaternion::getRotationMatrix(TMatrix4x4& m) const throw() { m.set ((T)(1.0 - 2.0 * (j * j + k * k)), (T)(2.0 * (i * j - k * angle)), (T)(2.0 * (k * i + j * angle)), (T)0, (T)(2.0 * (i * j + k * angle)), (T)(1.0 - 2.0 * (k * k + i * i)), (T)(2.0 * (j * k - i * angle)), (T)0, (T)(2.0 * (k * i - j * angle)), (T)(2.0 * (j * k + i * angle)), (T)(1.0 - 2.0 * (j * j + i * i)), (T)0, (T)0, (T)0, (T)0, (T)1); return m; } template TQuaternion TQuaternion::operator - () const throw() { T tmp = ::sqrt(angle * angle + i * i + j * j + k * k); if (tmp > (T)0) { tmp = (T)1 / tmp; return TQuaternion(-i * tmp, -j * tmp, -k * tmp, angle * tmp); } else { return TQuaternion(-i, -j, -k, angle); } } template BALL_INLINE TQuaternion TQuaternion::getInverse() const throw() { return -TQuaternion(*this); } template BALL_INLINE TQuaternion TQuaternion::getConjugate() const throw() { TQuaternion tmp; tmp.i = -i; tmp.j = -j; tmp.k = -k; tmp.angle = angle; return tmp; } template TQuaternion& TQuaternion::operator += (const TQuaternion& q) throw() { T tmp_angle = angle * q.angle - i * q.i - j * q.j - k * q.k; T tmp_i = angle * q.i + i * q.angle + j * q.k - k * q.j; T tmp_j = angle * q.j + j * q.angle + k * q.i - i * q.k; T tmp_k = angle * q.k + k * q.angle + i * q.j - j * q.i; T tmp = tmp_i * tmp_i + tmp_j * tmp_j + tmp_k * tmp_k + tmp_angle * tmp_angle; if (Maths::isNotEqual(tmp, (T)0)) { tmp = 1 / tmp; i = tmp_i * tmp; j = tmp_j * tmp; k = tmp_k * tmp; angle = tmp_angle * tmp; } else { i = j = k = (T)0; angle = (T)1; } return *this; } template BALL_INLINE TQuaternion& TQuaternion::operator -= (const TQuaternion& q) throw() { return (*this += -q); } /** Addition operator for two Quaternions @return TQuaternion - the new Quaternion */ template BALL_INLINE TQuaternion operator + (const TQuaternion& a, const TQuaternion& b) throw() { TQuaternion q(a); q += b; return q; } /** Substraction operator for two Quaternions @return TQuaternion - the new Quaternion */ template BALL_INLINE TQuaternion operator - (const TQuaternion& a, const TQuaternion& b) throw() { TQuaternion q(a); q += -b; return q; } template void TQuaternion::swap(TQuaternion& q) throw() { T tmp = q.i; q.i = i; i = tmp; tmp = q.j; q.j = j; j = tmp; tmp = q.k; q.k = k; k = tmp; tmp = q.angle; q.angle = angle; angle = tmp; } template BALL_INLINE bool TQuaternion::operator == (const TQuaternion& q) const throw() { return (i == q.i && j == q.j && k == q.k && angle == q.angle); } template BALL_INLINE bool TQuaternion::operator != (const TQuaternion& q) const throw() { return (i != q.i || j != q.j || k != q.k || angle != q.angle); } /** @name Storers Stream operators for class Quaternion */ //@{ /** Input Operator. Read the values of the quaternion from an input stream. @param s the input stream @param q the quaternion to read \ingroup Quaternions */ template std::istream& operator >>(std::istream& s, TQuaternion& q) throw() { char c; s >> c >> q.i >> q.j >> q.k >> q.angle >> c; return s; } /** Output Operator. Write the values of the quaternion to an output stream. The values of i, j, k, and angle are written to an output stream. They are enclosed in brackets. \par Example: \par (0.32 0.45 0.12 1.0) @param s the output stream @param q the quaternion to write \ingroup Quaternions */ template std::ostream& operator << (std::ostream& s, const TQuaternion& q) throw() { s << '(' << q.i << ' ' << q.j << ' ' << q.k << ' ' << q.angle << ')'; return s; } //@} template void TQuaternion::dump(std::ostream& s, Size depth) const throw() { BALL_DUMP_STREAM_PREFIX(s); BALL_DUMP_HEADER(s, this, this); BALL_DUMP_DEPTH(s, depth); s << " angle (real): " << angle << std::endl; BALL_DUMP_DEPTH(s, depth); s << " i: " << i << std::endl; BALL_DUMP_DEPTH(s, depth); s << " j: " << j << std::endl; BALL_DUMP_DEPTH(s, depth); s << " k: " << k << std::endl; BALL_DUMP_STREAM_SUFFIX(s); } /** The Default TQuaternion Type. If double precision is not needed, TQuaternion should be used. It is predefined as Quaternion for convenience. \ingroup Quaternions */ typedef TQuaternion Quaternion; } // namespace BALL #endif // BALL_MATHS_QUATERNION_H ugene-1.9.8/src/plugins_3rdparty/ball/src/include/BALL/MATHS/common.h0000644000175000017500000002011111651544325023566 0ustar ilyailya// -*- Mode: C++; tab-width: 2; -*- // vi: set ts=2: // // $Id: common.h,v 1.29.16.1 2007-03-25 21:23:45 oliver Exp $ // #ifndef BALL_MATHS_COMMON_H #define BALL_MATHS_COMMON_H #ifndef BALL_CONFIG_CONFIG_H # include #endif #include #ifdef BALL_HAS_IEEEFP_H # include #endif #ifdef BALL_HAS_FLOAT_H # include #endif #ifndef BALL_COMMON_CONSTANTS_H # include #endif #ifndef BALL_COMMON_GLOBAL_H # include #endif #ifndef BALL_COMMON_MACROS_H # include #endif namespace BALL { namespace Maths { /** \defgroup MathsCommon Common Mathematical Functions Namespace: BALL::Maths \par */ //@{ /** Return the absolute value of a number. @param t the number @return T the absolute value */ template inline T abs(const T& t) throw() { return BALL_ABS(t); } /** Return the fraction of a number. @param t the number @return T the fraction */ template inline T frac(const T& t) throw() { long tmp = (long)t; return (t - (T)tmp); } #ifndef max /** Return the greater of two numbers. @param a the first number @param b the second number @return T the greatest number */ template inline T max(const T& a, const T& b) throw() { return BALL_MAX(a, b); } /** Return the greatest of three numbers. @param a the first number @param b the second number @param ct the third number @return T the greatest number */ template inline T max(const T& a, const T& b, const T &ct) throw() { return BALL_MAX3(a, b, ct); } #endif #ifndef min /** Return the smallest of two numbers. @param a the first number @param b the second number @return T the smallest number */ template inline T min(const T& a, const T& b) throw() { return BALL_MIN(a, b); } /** Return the smallest of three numbers. @param a the first number @param b the second number @param ct the third number @return T the smallest number */ template inline T min(const T& a, const T& b, const T &ct) throw() { return BALL_MIN3(a, b, ct); } #endif /** Round a number and return the result. @param t the number @return T the result */ template inline T round(const T& t) throw() { return (T)(t > 0 ? long(t + 0.5) : long(t - 0.5)); } /** Return the sign of a number. @param t the number @return Index -1 t < 0; 0 t = 0; 1 t > 0 */ template inline T sgn(const T& t) throw() { return BALL_SGN(t); } /** Test whether a number is finite. @param t the number @return bool, true if t is finite */ template inline bool isFinite(const T& t) throw() { #ifdef BALL_COMPILER_MSVC return ::_finite(t); #else return finite(t); #endif } /** Test whether a value is not a number. @param t the number @return bool, true if t equals nan */ template inline bool isNan(const T& t) throw() { #ifdef BALL_COMPILER_MSVC return (_isnan(t) != 0); #else return (isnan(t) != 0); #endif } /** Test whether a number is infinite. @param t the number @return bool, true if t equals inf or -inf */ template inline bool isInfinite(const T& t) throw() { return (!Maths::isFinite(t) && !Maths::isNan(t)); } /** Test whether a number is zero. @param t the number @return bool, true if the absolute value of t is below \link Constants::EPSILON Constants::EPSILON \endlink */ template inline bool isZero(const T& t) throw() { return (abs(t) < Constants::EPSILON); } /** Test whether a number is not zero. @param t the number @return bool, true, if the absolute value of t is at least \link Constants::EPSILON Constants::EPSILON \endlink */ template inline bool isNotZero(const T& t) throw() { return (abs(t) >= Constants::EPSILON); } /** Test whether a number is equal to another. @param a the first number @param b the second number @return bool, true if the absolute distance of a and b is below \link Constants::EPSILON Constants::EPSILON \endlink */ template inline bool isEqual(const T1& a, const T2& b) throw() { return (abs(a - b) < Constants::EPSILON); } /** Test whether a number is not equal to another. @param a the first number @param b the second number @return bool, true if the absolute distance of a and b is at least \link Constants::EPSILON Constants::EPSILON \endlink */ template inline bool isNotEqual(const T1& a, const T2& b) throw() { return (abs(a - b) >= Constants::EPSILON); } /** Test whether a number is less compared to another. @param a the first number @param b the second number @return bool, true if a is smaller than b */ template inline bool isLess(const T1& a, const T2& b) throw() { return ((a - b) <= -Constants::EPSILON); } /** Test whether a number is less or equal compared to another. @param a the first number @param b the second number @return bool, true if a is less or equal b */ template inline bool isLessOrEqual(const T1& a, const T2& b) throw() { return ((a - b) < Constants::EPSILON); } /** Test whether a number is greater or equal compared to another. @param a the first number @param b the second number @return bool, true if a is greater or equal than b */ template inline bool isGreaterOrEqual(const T1& a, const T2& b) throw() { return ((a - b) > -Constants::EPSILON); } /** Test whether a number is greater compared to another. @param a the first number @param b the second number @return bool, true if a is greater than b */ template inline bool isGreater(const T1& a, const T2& b) throw() { return (a - b >= Constants::EPSILON); } /** Return the floor of a number. @param t the number @return T the floor */ template inline long floor(const T& t) throw() { return (long)(Maths::isGreater(t, 0) ? t: (Maths::isEqual(t, (T)(long)t) ? t : t - 1)); } /** Return the ceiling of a number. @param t the number @return T the ceiling */ template inline long ceiling(const T& t) throw() { return (long)(Maths::isLess(t, 0) ? t: (Maths::isEqual(t, (T)(long)t) ? t : t + 1)); } /** Compare two numbers to each other. @param a the first number @param b the second number @return Index -1 a < b; 0 a = b; 1 a > b */ template inline Index compare(const T1& a, const T2& b) throw() { return (Maths::isLess(a, b) ? -1 : Maths::isEqual(a, b) ? 0 : 1); } /** Test whether two numbers are close to each other. @param a the first number @param b the second number @param max_diff the maximum allowed difference between the two numbers @return bool, true if the absolute distance between a and b is below max_diff */ template inline bool isNear(const T& a, const T& b, const T& max_diff) throw() { return (abs((double)a - (double)b) < abs((double)max_diff)); } /// round to integral value in floating-point format inline double rint(double x) { if (x < 0.0) return (double)(int)(x - 0.5); else return (double)(int)(x + 0.5); } //@} } // namespace Maths } // namespace BALL #endif // BALL_MATHS_COMMON_H ugene-1.9.8/src/plugins_3rdparty/ball/src/include/BALL/MATHS/angle.h0000644000175000017500000004332411651544325023377 0ustar ilyailya// -*- Mode: C++; tab-width: 2; -*- // vi: set ts=2: // // $Id: angle.h,v 1.48.18.1 2007-03-25 21:23:44 oliver Exp $ // #ifndef BALL_MATHS_ANGLE_H #define BALL_MATHS_ANGLE_H #ifndef BALL_COMMON_EXCEPTION_H # include #endif #ifndef BALL_COMMON_DEBUG_H # include #endif #ifndef BALL_COMMON_CREATE_H # include #endif #ifndef BALL_MATHS_COMMON_H # include #endif namespace BALL { /** \defgroup Angle Representation of angles. class \link BALL::TAngle TAngle \endlink and class \link Angle Angle \endlink \ingroup Primitives */ //@{ template class TAngle; template BALL_INLINE TAngle operator * (const T& val, const TAngle& angle) throw(); template BALL_INLINE TAngle operator + (const T& val, const TAngle& angle) throw(); template BALL_INLINE TAngle operator - (const T& val, const TAngle& angle) throw(); /** Generic Angle Class. Use this class to describe angles. The TAngle class permits the conversion from degree to radians and is the return type of all functions used to calculate angles. */ template class TAngle { public: BALL_CREATE(TAngle) /** @name Enums */ //@{ /** form of the angle range: RANGE__UNLIMITED = 0 no limitations RANGE__UNSIGNED = 1 0 <= angle <= 360, 0 <= angle <= PI * 2 RANGE__SIGNED = 2 -180 <= angle <= 180, -PI <= angle <= PI */ enum Range { // no limitations RANGE__UNLIMITED = 0, // 0 <= angle <= 360, 0 <= angle <= (Constants::PI * 2) RANGE__UNSIGNED = 1, // -180 <= angle <= 180, -Constants::PI <= angle <= Constants::PI RANGE__SIGNED = 2 }; //@} /** @name Constructors and Destructors */ //@{ /** Default constructor. Creates a new angle object. Its value is set to 0. */ TAngle() throw(); /** Copy constructor. Create a copy of a TAngle object. Copies are always shallow. @param angle the object to be copied */ TAngle(const TAngle& angle) throw(); /** Detailed constructor. Create a new angle object and set its value to new_value. radian determines whether new_value is in radians or in degrees. @param new_value the value of the angle object @param radian true if new_value is in radians, false otherwise */ explicit TAngle(const T& new_value, bool radian = true) throw(); /** Destructor. */ virtual ~TAngle() throw() { } /** Clear method The value is set to 0. */ virtual void clear() throw() { value = (T)0; } //@} /** @name Assignment */ //@{ /** Swap the contents of two angles. */ void swap(TAngle& angle) throw(); /** Assign a new value to the angle. radian determines whether new_value is in radians or in degrees. @param new_value the value of the angle object @param radian true if new_value is in radians, false otherwise */ void set(const T& new_value, bool radian = true) throw(); /** Assign an Angle object from another. @param angle the angle object to be assigned from */ void set(const TAngle& angle) throw(); /** Assignment operator */ TAngle& operator = (const TAngle& angle) throw(); /** Assignment operator for floats. Assign a float value to the angle. The assigned value has to be in radians! @param new_value the new value */ TAngle& operator = (const T& new_value) throw(); /** Assign the value to another angle. @param angle the angle to assign the value to */ void get(TAngle& angle) const throw(); /** Assign the value to a variable of type T. @param val the variable to assign the value to @param radian if set to true assigns the value in radians (default). */ void get(T& val, bool radian = true) const throw(); //@} /** @name Accessors */ //@{ /** Cast operator @return value in radians */ operator T () const throw(); /** Return the value of the angle @return value in radians */ T toRadian() const throw(); /** Calculate radians from degrees @param degree the value in degrees @return T the value in radians */ static T toRadian(const T& degree) throw(); /** Return the value of the angle @return value in degrees */ T toDegree() const throw(); /** Calculate degrees from radians @param radian the value in radians @return T the value in degrees */ static T toDegree(const T& radian) throw(); /** Normalize the angle over a given range. RANGE__UNLIMITED = 0 no limitations. RANGE__UNSIGNED = 1 \f$0 \le \mathtt{angle} \le 360, 0 \le angle \le 2 \pi\f$. RANGE__SIGNED = 2 \f$-180 \le \mathtt{angle} \le 180, -\pi \le \mathtt{angle} \le \pi\f$. @param range the range of the angle */ void normalize(Range range) throw(); /** Negate the angle */ void negate() throw(); /** Positive sign. */ TAngle operator + () const throw(); /** Negative sign. */ TAngle operator - () const throw(); /** Addition operator. @param angle the angle to add @return TAngle, {\em *this} */ TAngle& operator += (const TAngle& angle) throw(); /** Add a value to this angle. @param val the value to add @return TAngle, {\em *this} */ TAngle& operator += (const T& val) throw(); /** Addition operator. @param angle the angle to add @return TAngle, the new angle */ TAngle operator + (const TAngle& angle) throw(); /** Substraction operator. @param angle the angle to substract @return TAngle, {\em *this} */ TAngle& operator -= (const TAngle& angle) throw(); /** Substract a value from this angle. @param val the value to substract @return TAngle, {\em *this} */ TAngle& operator -= (const T& val) throw(); /** Subtraction an angle from this angle. @param angle the angle to substract @return TAngle, the new angle */ TAngle operator - (const TAngle& angle) throw(); /** Multiply an angle with this angle. @param angle the angle to multiply by @return TAngle, {\em *this} */ TAngle& operator *= (const TAngle& angle) throw(); /** Multiply a value with this angle. @param val the value to multiply by @return TAngle, {\em *this} */ TAngle& operator *= (const T& val) throw(); /** Division operator. @param angle the angle to divide by @return TAngle, {\em *this} */ TAngle& operator /= (const TAngle& angle) throw(Exception::DivisionByZero); /** Divide this angle by a value. @param val the angle to divide by @return TAngle, {\em *this} */ TAngle& operator /= (const T& val) throw(Exception::DivisionByZero); /** Divide this angle by a value. @param val the angle to divide by @return TAngle, the new angle */ TAngle operator / (const TAngle& val) throw(Exception::DivisionByZero); //@} /** @name Predicates */ //@{ /** Equality operator. This test uses Maths::isEqual instead of comparing the values directly. @param angle the angle to compare with @return bool, true if the two angles are equal */ bool operator == (const TAngle& angle) const throw(); /** Inequality operator This test uses Maths::isNotEqual instead of comparing the values directly. @param angle the angle to compare with @return bool, true if the two angles are not equal */ bool operator != (const TAngle& angle) const throw(); /** Is less operator. This test uses Maths::isLess instead of comparing the values directly. @param angle the angle to compare with @return bool, true if {\em *this} angle is smaller than value */ bool operator < (const TAngle& angle) const throw(); /** Is less operator. This test uses Maths::isLess instead of comparing the values directly. @param val the value to compare with @return bool, true if {\em *this} angle is smaller than value */ bool operator < (const T& val) const throw(); /** Is less or equal operator. This test uses Maths::isLessOrEqual instead of comparing the values directly. @param angle the angle to compare with @return bool, true if {\em *this} angle is smaller or equal than value */ bool operator <= (const TAngle& angle) const throw(); /** Is greater or equal operator. This test uses Maths::isGreaterOrEqual instead of comparing the values directly. @param angle the angle to compare with @return bool, true if {\em *this} angle is greater or equal than value */ bool operator >= (const TAngle& angle) const throw(); /** Is greater operator. This test uses Maths::isGreater instead of comparing the values directly. @param angle the angle to compare with @return bool, true if {\em *this} angle is greater than value */ bool operator > (const TAngle& angle) const throw(); /** Test whether two angles are equivalent. Both angles are normalized and afterwards compared with Maths::isEqual instead of comparing the values directly. @param angle the angle to compare with @return bool, true if {\em *this} angle is equal to value */ bool isEquivalent(TAngle angle) const throw(); //@} /** @name Debugging and Diagnostics */ //@{ /** Test whether instance is valid. Always returns true @return bool true */ bool isValid () const throw(); /** Internal state dump. Dump the current internal state of {\em *this} to the output ostream s with dumping depth depth . @param s - output stream where to output the internal state of {\em *this} @param depth - the dumping depth */ void dump(std::ostream& s = std::cout, Size depth = 0) const throw(); //@} /** @name Attributes */ //@{ /** The value */ T value; //@} }; //@} template TAngle::TAngle() throw() : value((T)0) { } template TAngle::TAngle(const TAngle& angle) throw() : value((T)angle.value) { } template TAngle::TAngle(const T& new_value, bool radian) throw() : value((radian == true) ? (T)new_value : (T)BALL_ANGLE_DEGREE_TO_RADIAN((double)new_value)) { } template void TAngle::swap(TAngle& angle) throw() { T temp = value; value = angle.value; angle.value = temp; } template void TAngle::set(const TAngle& angle) throw() { value = angle.value; } template void TAngle::set(const T& new_value, bool radian) throw() { value = (radian == true) ? new_value : BALL_ANGLE_DEGREE_TO_RADIAN(new_value); } template TAngle& TAngle::operator = (const TAngle& angle) throw() { value = angle.value; return *this; } template TAngle& TAngle::operator = (const T& new_value) throw() { value = new_value; return *this; } template void TAngle::get(TAngle& angle) const throw() { angle.value = value; } template void TAngle::get(T& val, bool radian) const throw() { val = (radian == true) ? value : BALL_ANGLE_RADIAN_TO_DEGREE(value); } template TAngle::operator T () const throw() { return value; } template T TAngle::toRadian() const throw() { return value; } template T TAngle::toRadian(const T& degree) throw() { return BALL_ANGLE_DEGREE_TO_RADIAN(degree); } template T TAngle::toDegree() const throw() { if (value == (T) 0.0) return (T) 0.0; return BALL_ANGLE_RADIAN_TO_DEGREE(value); } template T TAngle::toDegree(const T& radian) throw() { if (radian == (T) 0.0) return (T) 0.0; return BALL_ANGLE_RADIAN_TO_DEGREE(radian); } template void TAngle::normalize(Range range) throw() { if (range == RANGE__UNLIMITED) { return; } long mod_factor = (long)(value / (2 * Constants::PI)); value -= mod_factor * (Constants::PI * 2); while (Maths::isGreater(value, (Constants::PI * 2))) { value -= (Constants::PI * 2); } while (Maths::isLess(value, -(Constants::PI * 2))) { value += (Constants::PI * 2); } if (range == RANGE__SIGNED) // invariant: -180 to 180: { if (Maths::isGreater(value, Constants::PI)) { value -= (Constants::PI * 2); } } else { // invariant: 0 to 360: if (Maths::isLess(value, 0)) { value += (Constants::PI * 2); } } } template void TAngle::negate() throw() { value = -value; } template TAngle TAngle::operator + () const throw() { return *this; } template TAngle TAngle::operator - () const throw() { return TAngle(-value); } template TAngle& TAngle::operator += (const TAngle& angle) throw() { value += angle.value; return *this; } template TAngle& TAngle::operator += (const T& val) throw() { value += val; return *this; } template TAngle TAngle::operator + (const TAngle& angle) throw() { return TAngle(value + angle.value); } template TAngle& TAngle::operator -= (const TAngle& angle) throw() { value -= angle.value; return *this; } template TAngle& TAngle::operator -= (const T& val) throw() { value -= val; return *this; } template TAngle TAngle::operator - (const TAngle& angle) throw() { return TAngle(value - angle.value); } template TAngle& TAngle::operator *= (const TAngle& angle) throw() { value *= angle.value; return *this; } template TAngle& TAngle::operator *= (const T& val) throw() { value *= val; return *this; } template TAngle& TAngle::operator /= (const TAngle& angle) throw(Exception::DivisionByZero) { if (angle.value == 0) { throw Exception::DivisionByZero(__FILE__, __LINE__); } value /= angle.value; return *this; } template TAngle& TAngle::operator /= (const T& val) throw(Exception::DivisionByZero) { if (val == 0) { throw Exception::DivisionByZero(__FILE__, __LINE__); } value /= val; return *this; } template TAngle TAngle::operator / (const TAngle& val) throw(Exception::DivisionByZero) { if (val.value == 0) { throw Exception::DivisionByZero(__FILE__, __LINE__); } return TAngle(value / val.value); } template bool TAngle::operator == (const TAngle& angle) const throw() { return Maths::isEqual(value, angle.value); } template bool TAngle::operator != (const TAngle& angle) const throw() { return Maths::isNotEqual(value, angle.value); } template bool TAngle::operator < (const TAngle& angle) const throw() { return Maths::isLess(value, angle.value); } template bool TAngle::operator < (const T& val) const throw() { return Maths::isLess(value, val); } template bool TAngle::operator <= (const TAngle& angle) const throw() { return Maths::isLessOrEqual(value, angle.value); } template bool TAngle::operator >= (const TAngle& angle) const throw() { return Maths::isGreaterOrEqual(value, angle.value); } template bool TAngle::operator > (const TAngle& angle) const throw() { return Maths::isGreater(value, angle.value); } template bool TAngle::isEquivalent(TAngle angle) const throw() { TAngle this_angle(*this); this_angle.normalize(RANGE__UNSIGNED); angle.normalize(RANGE__UNSIGNED); return (this_angle == angle); } template bool TAngle::isValid() const throw() { return true; } template void TAngle::dump(std::ostream& s, Size depth) const throw() { BALL_DUMP_STREAM_PREFIX(s); BALL_DUMP_HEADER(s, this, this); BALL_DUMP_DEPTH(s, depth); s << " value: " << value << std::endl; BALL_DUMP_STREAM_SUFFIX(s); } /** The Default Angle Type. If double precision is not needed, TAngle should be used. It is predefined as Angle for convenience. */ typedef TAngle Angle; /** Multiplication operator. Multiplies a number with an angle. */ template BALL_INLINE TAngle operator * (const T& val, const TAngle& angle) throw() { return TAngle(val * angle.value); } /** Plus operator. Adds a number with an angle (in rad!) */ template BALL_INLINE TAngle operator + (const T& val, const TAngle& angle) throw() { return TAngle(val + angle.value); } /** Minus operator. Subtracts the value of an angle (in rad!) from a number. */ template BALL_INLINE TAngle operator - (const T& val, const TAngle& angle) throw() { return TAngle(val - angle.value); } /** Input Operator. Reads the value (in radians) of an angle from an instream using T::operator >> */ template std::istream& operator >> (std::istream& s, TAngle& angle) throw() { char c; s >> c >> angle.value >> c; return s; } /** Output Operator. Writes the value of the angle to an output stream. The stream operator operator << has to be defined for the template parameter T. */ template std::ostream& operator << (std::ostream& s, const TAngle& angle) throw() { s << '(' << angle.value << ')'; return s; } } // namespace BALL #endif // BALL_MATHS_ANGLE_H ugene-1.9.8/src/plugins_3rdparty/ball/src/include/BALL/MATHS/sphere3.h0000644000175000017500000001440511651544325023660 0ustar ilyailya// -*- Mode: C++; tab-width: 2; -*- // vi: set ts=2: // // $Id: sphere3.h,v 1.39 2004-05-27 19:49:42 oliver Exp $ // #ifndef BALL_MATHS_SPHERE3_H #define BALL_MATHS_SPHERE3_H #ifdef BALL_HAS_IEEEFP_H # include #endif #include #ifndef BALL_MATHS_PLANE3_H # include #endif #ifndef BALL_MATHS_VECTOR3_H # include #endif namespace BALL { /** \defgroup Sphere Sphere \ingroup GeometricObjects */ //@{ /** Generic Sphere Class. */ template class TSphere3 { public: BALL_CREATE(TSphere3) /** @name Constructors and Destructors */ //@{ /** Default constructor. This method creates a new TSphere3 object. The three components are initialized to (T)0. */ TSphere3() throw() : p(), radius(0) { } /** Copy constructor. Create a new Sphere3 object from another. @param sphere the Sphere3 object to be copied */ TSphere3(const TSphere3& sphere) throw() : p(sphere.p), radius(sphere.radius) { } /** Detailed constructor. Create a new Sphere3 object from a point and a radius. @param point assigned to the point @param radius assigned to the radius */ TSphere3(const TVector3& point, const T& radius) throw() : p(point), radius(radius) { } /** Destructor. As there are no dynamic data structures, nothing happens. */ virtual ~TSphere3() throw() { } /** Default initialisation */ virtual void clear() throw() { p.clear(); radius = (T) 0; } //@} /** @name Assignment */ //@{ /** Swap the contents of two instances of Sphere3. @param sphere the Sphere3 to swap contents with */ void swap(TSphere3& sphere) throw() { TVector3 temp_point(p); p = sphere.p; sphere.p = temp_point; T temp = radius; radius = sphere.radius; sphere.radius = temp; } /** Assign from another instance of Sphere3. @param sphere the Sphere3 object to assign from */ void set(const TSphere3& sphere) throw() { p = sphere.p; radius = sphere.radius; } /** Assign from a point and a radius. @param point the point to assign from @param r the radius to assign from */ void set(const TVector3& point, const T& r) throw() { p = point; radius = r; } /** Assignment operator. Assign the components from another instance of Sphere. @param sphere the sphere to assign from **/ TSphere3& operator = (const TSphere3& sphere) throw() { p = sphere.p; radius = sphere.radius; return *this; } /** Assign to another instance of Sphere. Assigns the components to another Sphere. @param sphere the sphere to be assigned to */ void get(TSphere3& sphere) const throw() { sphere.p = p; sphere.radius = radius; } /** Assign to an instance of Vector3 and a variable of type T. @param point the point component @param r the radius component */ void get(TVector3& point, T& r) const throw() { point = p; r = radius; } //@} /** @name Predicates */ //@{ /** Equality operator. @return bool, true if all components are equal, false otherwise */ bool operator == (const TSphere3& sphere) const throw() { return (p == sphere.p && Maths::isEqual(radius, sphere.radius)); } /** Inequality operator. @return bool, true if the two Sphere3 differ in at least one component, false otherwise */ bool operator != (const TSphere3& sphere) const throw() { return (p != sphere.p || Maths::isNotEqual(radius, sphere.radius)); } /** Test whether a given point is a member of the Sphere. Optional it can be testet, if the point lies on the surface. @param point the point to be tested @param on_surface true to test the surface (default = false) @return bool, true or false */ bool has(const TVector3& point, bool on_surface = false) const throw() { if (on_surface) { return Maths::isEqual(p.getDistance(point), radius); } else { return Maths::isLessOrEqual(p.getDistance(point), radius); } } /** Test whether the Sphere is empty (radius = 0). @return bool, true or false */ bool isEmpty() const throw() { return Maths::isZero(radius); } //@} /** @name Debugging and Diagnostics */ //@{ /** Test whether instance is valid. Always returns true @return bool true */ bool isValid() const throw() { return true; } /** Internal state dump. Dump the current internal state of {\em *this} to the output ostream s with dumping depth depth . @param s - output stream where to output the internal state of {\em *this} @param depth - the dumping depth */ void dump(std::ostream& s = std::cout, Size depth = 0) const throw() { BALL_DUMP_STREAM_PREFIX(s); BALL_DUMP_HEADER(s, this, this); BALL_DUMP_DEPTH(s, depth); s << " position: " << p << std::endl; BALL_DUMP_DEPTH(s, depth); s << " radius: " << radius << std::endl; BALL_DUMP_STREAM_SUFFIX(s); } //@} /** @name Attributes */ //@{ /** The midpoint of the sphere. */ TVector3 p; /** The radius of the sphere. */ T radius; //@} }; //@} /** @name Storers Stream operators for the class Sphere \ingroup Sphere */ //@{ /** Input operator. Reads in an instance of TVector3 and a T value : p, radius. */ template std::istream& operator >> (std::istream& s, TSphere3& sphere) throw() { char c; s >> c >> sphere.p >> sphere.radius >> c; return s; } /** Output Operator. Write the contents of p and radius to an output stream. The values are enclose in brackets. \par Example: \par ((0 1 1.5) 0.4) */ template std::ostream& operator << (std::ostream& s, const TSphere3& sphere) throw() { s << '(' << sphere.p << ' ' << sphere.radius << ')'; return s; } //@} /** Default sphere type. If double precision is not needed, TSphere3 should be used. It is predefined as Sphere3 for convenience. \ingroup Sphere */ typedef TSphere3 Sphere3; } // namespace BALL #endif // BALL_MATHS_SPHERE3_H ugene-1.9.8/src/plugins_3rdparty/ball/src/include/BALL/MATHS/vector3.h0000644000175000017500000006451611651544325023704 0ustar ilyailya// -*- Mode: C++; tab-width: 2; -*- // vi: set ts=2: // // $Id: vector3.h,v 1.77 2006-01-09 20:14:59 oliver Exp $ // #ifndef BALL_MATHS_VECTOR3_H #define BALL_MATHS_VECTOR3_H #ifndef BALL_COMMON_EXCEPTION_H # include #endif //#ifndef BALL_CONCEPT_PERSISTENCEMANAGER_H //# include //#endif #ifndef BALL_MATHS_ANGLE_H # include #endif #ifndef BALL_MATHS_COMMON_H # include #endif #ifdef BALL_HAS_IEEEFP_H # include #endif namespace BALL { /** \defgroup Vector3 Three-dimensional vector. Representation of points and vectors in three-dimensional space: class \link TVector3 TVector3 \endlink and class \link Vector3 Vector3 \endlink \ingroup Primitives */ //@{ template class TVector3; /** @name Global binary operators for three-dimensional vectors. */ //@{ /** Multiply a vector with a scalar. The symmetric case is a member of the vector class. */ template BALL_INLINE TVector3 operator * (const T& a, const TVector3& b) throw(); /** Input operator. Reads the values of three vector components of type T from an istream. The components are read in the order of x, y, z. */ template std::istream& operator >> (std::istream& s, TVector3& vector) throw(); /** Output operator. Writes the values of three vector components of type T to an ostream. The components are writen in the order of x, y, z. */ template std::ostream& operator << (std::ostream& s, const TVector3& vector) throw(); //@} /** Generic Three-Dimensional Vector. */ template class TVector3 { public: /** @name Constructors and Destructors */ //@{ /** Default constructor. This method creates a new TVector3 object. The three components are initialized to (T)0. */ TVector3() throw(); /** Array constructor. This constructor creates a TVector3 object from the first three elements pointed to by ptr. @param ptr the array to construct from @exception NullPointer if ptr == 0 */ TVector3(const T* ptr) throw(Exception::NullPointer); /** Scalar constructor. Create a new vector with all components set to the same value. @param value the value of all components */ explicit TVector3(const T& value) throw(); /** Detailed constructor. Create a new TVector3 object from three variables of type T. @param vx assigned to x @param vy assigned to y @param vz assigned to z */ TVector3(const T& vx, const T& vy, const T& vz) throw(); /** Copy constructor. Create a new TVector3 object from another. @param vector the TVector3 object to be copied */ TVector3(const TVector3& vector) throw(); /** Spherical polar coordinate constructor. Create a TVector3 object and set its coordinates to the point described by the three spherical polar coordinates r (radius), phi (azimuth), and theta (co-latitude). @see set(const T& r, const TAngle& phi, const TAngle& theta) @param r the radius @param phi the azimuth @param theta the co-latitude */ TVector3(const T& r, const TAngle& phi, const TAngle& theta) throw(); /** Destructor. Destructs the TVector3 object. As there are no dynamic data structures, nothing happens. */ ~TVector3() throw(); /** Clear method The values are set to 0. */ void clear() throw(); //@} /** @name Assignment */ //@{ /** Assign from an array. Assign the three components x, y, and z from the first three elements of the array pointed to by ptr. @param ptr an array @exception Nullpointer if ptr == 0 */ void set(const T* ptr) throw(Exception::NullPointer); /** Assign from a scalar. Assign value to the three vector components. @param value the new value of the components */ void set(const T& value) throw(); /** Assign the vector components. @param vx the new x component @param vy the new y component @param vz the new z component */ void set(const T& vx, const T& vy, const T& vz) throw(); /** Assign from another TVector3. @param vector the TVector3 object to assign from */ void set(const TVector3& vector) throw(); /** Assign from spherical polar coordinates. The radius describes the distance of the point from the origin. \par phi ranges from 0 to \f$2 \pi\f$, theta ranges from 0 (north pole, positive z-axis) to \f$\pi\f$ (south pole, negative z-axis). \par Coordinates are calculated according to the following formulae: \par \f[ x = r \sin \theta \cos \phi \f] \par \f[ y = r \sin \theta \sin \phi \f] \par \f[ z = r \cos \theta \f] @param r the radius @param phi the azimuth @param theta the co-latitude */ void set(const T& r, const TAngle& phi, const TAngle& theta) throw(); /** Assignment operator. Assign the vector components from another vector. @param v the vector to assign from **/ TVector3& operator = (const TVector3& v) throw(); /** Assignment operator. Assign a constant value to all three vector components. @param value the constant to assign to x, y, z **/ TVector3& operator = (T value) throw(); /** Array assignment operator. Assigns the first three elements of an array to the vector components. @param ptr the array @exception NullPointer if ptr == 0 */ TVector3& operator = (const T* ptr) throw(Exception::NullPointer); /** Assign to an array. Sets the first three array elements pointed to by ptr to the values of the three vector components. @param ptr the array @exception NullPointer if ptr == 0 */ void get(T* ptr) const throw(Exception::NullPointer); /** Assign to three variables of type T. @param x the x component @param y the y component @param z the z component */ void get(T& x, T& y, T& z) const throw(); /** Assign to another Vector3. Assigns the vector components to another vector. @param vector the vector to be assigned to */ void get(TVector3& vector) const throw(); /** Assign to polar coordinates. Sets r, phi, and theta to the coordinates of the vector in spherical polar coordinates. @param r the radius (returned) @param phi the azimuth (returned) @param theta the co-latitude (returned) */ void get(T& r, TAngle& phi, TAngle& theta) const throw(); /** Swap the contents of two vectors. @param vector the vector to swap contents with */ void swap(TVector3& vector) throw(); /** Return the length of the vector. The length of the vector is calculated as \f$\sqrt{x^2 + y^2 + z^2}\f$. @return T, the vector length */ T getLength() const throw(); /** Return the squared length of the vector. This method avoids the square root needed in getLength, so this method is preferred if possible. @return T, \f$x^2 + y^2 + z^2\f$ */ T getSquareLength() const throw(); /** Normalize the vector. The vector is scaled with its length: \f$\{x|y|z\} *= \sqrt{x^2 + y^2 + z^2}\f$. @return T, a reference to the normalized vector @exception DivisionByZero if the length of the vector is 0 */ TVector3& normalize() throw(Exception::DivisionByZero); /** Negate the vector. Negate the three components of the vector @return T, a reference to {\em *this} vector */ TVector3& negate() throw(); /** Return a vector with all components 0. */ static const TVector3& getZero() throw(); /** Return a vector with all components 1. @return: TVector4(1, 1, 1, 1) */ static const TVector3& getUnit() throw(); /** Mutable array-like access to the components. @exception Exception::IndexOverflow if index > 2 */ T& operator [] (Position position) throw(Exception::IndexOverflow); /** Constant array-like access to the components. @exception Exception::IndexOverflow if index > 2 */ const T& operator [] (Position position) const throw(Exception::IndexOverflow); //@} /** @name Arithmetic operators */ //@{ /** Positive sign. */ const TVector3& operator + () const throw(); /** Negative sign. */ TVector3 operator - () const throw(); /** Addition. */ TVector3 operator + (const TVector3& b) const throw(); /** Subtraction. */ TVector3 operator - (const TVector3& b) const throw(); /** Add a vector to this vector. Add the components of vector to this vector. @param vector the vector to add @return TVector3&, {\em *this} */ TVector3& operator += (const TVector3& vector) throw(); /** Subtract a vector from this vector. @param vector the vector to subtract @return TVector3&, {\em *this} */ TVector3& operator -= (const TVector3& vector) throw(); /** Scalar product. Return TVector3(x * scalar, y * scalar, z * scalar). @param scalar, the scalar to multiply by @return TVector3 the scalar product of this vector and scalar */ TVector3 operator * (const T& scalar) const throw(); /** Multiply by a scalar. Multiply all components of the vector by a scalar value. @param scalar the to multiply by @return TVector3&, {\em *this} */ TVector3& operator *= (const T& scalar) throw(); /** Fraction of a vector. Return TVector3(x / lambda, y / lambda, z / lambda). @param lambda the scalar value to divide by @return TVector3& @exception Exception::DivisionByZero if lambda == (T)0 */ TVector3 operator / (const T& lambda) const throw(Exception::DivisionByZero); /** Divide a vector by a scalar. @param lambda the scalar value to divide by @return TVector3&, {\em *this} @exception Exception::DivisionByZero if lambda == (T)0 */ TVector3& operator /= (const T& lambda) throw(Exception::DivisionByZero); /** Dot product. Return the dot product of this vector and vector. */ T operator * (const TVector3& vector) const throw(); /** Cross product. Return the cross product of this vector and vector. */ TVector3 operator % (const TVector3& vector) const throw(); /** Assign to the cross product. Assign the vector to its cross product with another vector. */ TVector3& operator %= (const TVector3& vector) throw(); //@} /** @name Geometric properties */ //@{ /** Return the distance to another vector. */ T getDistance(const TVector3& vector) const throw(); /** Return the squared distance to another vector. */ T getSquareDistance(const TVector3& vector) const throw(); /** Return the enclosed angle of two vectors. @exception Exception::DivisionByZero if the product of the squared lengths of the two vectors equals (T)0 */ TAngle getAngle(const TVector3& vector) const throw(Exception::DivisionByZero); /** Return the orthogonal projection of this vector onto another. @param direction the vector to project onto */ TVector3 getOrthogonalProjection(const TVector3& direction) const throw(); /** Return the perpendicular normalization of the vector @param a 1st vector @param b 2nd vector @param c 3rd vector @return TVector3 the perpendicular normalization */ static TVector3 getPerpendicularNormalization (const TVector3& a, const TVector3& b, const TVector3& c) throw(); /** Triple product of three vectors. Calculate the parallelepipedal product of three vectors. @param a first vector @param b second vector @param v third vector @return T the triple product */ static T getTripleProduct (const TVector3& a, const TVector3& b, const TVector3& c) throw(); //@} /** @name Predicates */ //@{ /** Equality operator. The function Maths::isEqual is used to compare the values. \link Maths::isEqual Maths::isEqual \endlink @return bool, true if all three vector components are equal, false otherwise */ bool operator == (const TVector3& vector) const throw(); /** Inequality operator. The function Maths::isEqual is used to compare the values. \link Maths::isEqual Maths::isEqual \endlink @return bool, true if the two vectors differ in at least one component, false otherwise */ bool operator != (const TVector3& vector) const throw(); /// Needed for MSVC bool operator < (const TVector3& vector) const throw(); /** Zero predicate. The function Maths::isZero is used to compare the values with zero. \link Maths::isZero Maths::isZero \endlink */ bool isZero() const throw(); /** Orthogonality predicate. */ bool isOrthogonalTo(const TVector3& vector) const throw(); //@} /** @name Storable Interface */ //@{ // /** Persistent stream writing. // */ // void write(PersistenceManager& pm) const // throw(); // // /** Persistent stream reading. // */ // bool read(PersistenceManager& pm) // throw(); //@} /** @name Debugging and Diagnostics */ //@{ /** Internal state dump. Dump the current internal state of {\em *this} to the output ostream s with dumping depth depth . @param s - output stream where to output the internal state of {\em *this} @param depth - the dumping depth */ void dump(std::ostream& s = std::cout, Size depth = 0) const throw(); /** Test if instance is valid. Always returns true. @return bool true */ bool isValid() const throw(); //@} /** @name Vector components For easier access, the three components of the vector are public members. */ //@{ /** x component of the vector */ T x; /** y component of the vector */ T y; /** z component of the vector */ T z; //@} private: TAngle getAngle_(const T& a, const T& b) const throw() { TAngle angle; if (Maths::isNotZero(a)) { angle = atan(b / a); } else { angle = BALL_SGN(b) * Constants::PI / 2; } if (Maths::isLess(a, 0)) { angle += Constants::PI; } if (Maths::isLess(angle.value, 0)) { return (Angle)(angle.value += 2.0 * Constants::PI); } else { return angle; } } }; //@} template BALL_INLINE TVector3::TVector3() throw() : x(0), y(0), z(0) { } template BALL_INLINE TVector3::TVector3(const T* ptr) throw(Exception::NullPointer) { if (ptr == 0) { throw Exception::NullPointer(__FILE__, __LINE__); } x = *ptr++; y = *ptr++; z = *ptr; } template BALL_INLINE TVector3::TVector3(const T& value) throw() : x(value), y(value), z(value) { } template BALL_INLINE TVector3::TVector3(const T& vx, const T& vy, const T& vz) throw() : x(vx), y(vy), z(vz) { } template BALL_INLINE TVector3::TVector3(const TVector3& vector) throw() : x(vector.x), y(vector.y), z(vector.z) { } template BALL_INLINE TVector3::TVector3(const T& r, const TAngle& phi, const TAngle& theta) throw() : x(r * cos(phi) * sin(theta)), y(r * sin(phi) * sin(theta)), z(r * cos(theta)) { } template BALL_INLINE TVector3::~TVector3() throw() { } template BALL_INLINE void TVector3::clear() throw() { x = y = z = (T)0; } template BALL_INLINE void TVector3::set(const T* ptr) throw(Exception::NullPointer) { if (ptr == 0) throw Exception::NullPointer(__FILE__, __LINE__); x = *ptr++; y = *ptr++; z = *ptr; } template BALL_INLINE void TVector3::set(const T& value) throw() { x = value; y = value; z = value; } template BALL_INLINE void TVector3::set(const T& vx, const T& vy, const T& vz) throw() { x = vx; y = vy; z = vz; } template BALL_INLINE void TVector3::set(const TVector3& vector) throw() { x = vector.x; y = vector.y; z = vector.z; } template BALL_INLINE void TVector3::set(const T& r, const TAngle &phi, const TAngle &theta) throw() { x = r * cos(phi) * sin(theta); y = r * sin(phi) * sin(theta); z = r * cos(theta); } template BALL_INLINE TVector3& TVector3::operator = (const T* ptr) throw(Exception::NullPointer) { if (ptr == 0) { throw Exception::NullPointer(__FILE__, __LINE__); } x = *ptr++; y = *ptr++; z = *ptr; return *this; } template BALL_INLINE TVector3& TVector3::operator = (const TVector3& vector) throw() { x = vector.x; y = vector.y; z = vector.z; return *this; } template BALL_INLINE TVector3& TVector3::operator = (T value) throw() { x = y = z = value; return *this; } template BALL_INLINE void TVector3::get(T* ptr) const throw(Exception::NullPointer) { if (ptr == 0) { throw Exception::NullPointer(__FILE__, __LINE__); } *ptr++ = x; *ptr++ = y; *ptr = z; } template BALL_INLINE void TVector3::get(T& new_x, T& new_y, T& new_z) const throw() { new_x = x; new_y = y; new_z = z; } template BALL_INLINE void TVector3::get(TVector3& vector) const throw() { vector.x = x; vector.y = y; vector.z = z; } template BALL_INLINE void TVector3::get(T& r, TAngle& phi, TAngle& theta) const throw() { r = sqrt(x * x + y * y + z * z); phi = (Angle)getAngle_(x, y); theta = getAngle_(z, sqrt(x * x + y * y)); } template BALL_INLINE void TVector3::swap(TVector3& vector) throw() { T temp = x; x = vector.x; vector.x = temp; temp = y; y = vector.y; vector.y = temp; temp = z; z = vector.z; vector.z = temp; } template BALL_INLINE T TVector3::getLength() const throw() { return (T)sqrt(x * x + y * y + z * z); } template BALL_INLINE T TVector3::getSquareLength() const throw() { return (x * x + y * y + z * z); } template TVector3& TVector3::normalize() throw(Exception::DivisionByZero) { T len = sqrt(x * x + y * y + z * z); if (Maths::isZero(len)) { throw Exception::DivisionByZero(__FILE__, __LINE__); } x /= len; y /= len; z /= len; return *this; } template BALL_INLINE TVector3& TVector3::negate() throw() { x *= -1; y *= -1; z *= -1; return *this; } template BALL_INLINE const TVector3& TVector3::getZero() throw() { static TVector3 null_vector(0, 0, 0); return null_vector; } template BALL_INLINE const TVector3& TVector3::getUnit() throw() { static TVector3 unit_vector(1, 1, 1); return unit_vector; } template BALL_INLINE T& TVector3::operator [] (Position position) throw(Exception::IndexOverflow) { if (position > 2) { throw Exception::IndexOverflow(__FILE__, __LINE__, position); } switch (position) { case 0: return x; case 1: return y; case 2: default: return z; } } template BALL_INLINE const T& TVector3::operator [] (Position position) const throw(Exception::IndexOverflow) { if (position > 2) { throw Exception::IndexOverflow(__FILE__, __LINE__); } switch (position) { case 0: return x; case 1: return y; case 2: default: return z; } } template BALL_INLINE const TVector3& TVector3::operator + () const throw() { return *this; } template BALL_INLINE TVector3 TVector3::operator - () const throw() { return TVector3(-x, -y, -z); } template BALL_INLINE TVector3& TVector3::operator += (const TVector3& vector) throw() { x += vector.x; y += vector.y; z += vector.z; return *this; } template BALL_INLINE TVector3& TVector3::operator -= (const TVector3& vector) throw() { x -= vector.x; y -= vector.y; z -= vector.z; return *this; } template BALL_INLINE TVector3 TVector3::operator * (const T& scalar) const throw() { return TVector3(x * scalar, y * scalar, z * scalar); } template BALL_INLINE TVector3& TVector3::operator *= (const T &scalar) throw() { x *= scalar; y *= scalar; z *= scalar; return *this; } template TVector3 TVector3::operator / (const T& lambda) const throw(Exception::DivisionByZero) { if (lambda == (T)0) { throw Exception::DivisionByZero(__FILE__, __LINE__); } return TVector3(x / lambda, y / lambda, z / lambda); } template TVector3& TVector3::operator /= (const T& lambda) throw(Exception::DivisionByZero) { if (lambda == (T)0) { throw Exception::DivisionByZero(__FILE__, __LINE__); } x /= lambda; y /= lambda; z /= lambda; return *this; } template BALL_INLINE T TVector3::operator * (const TVector3& vector) const throw() { return (x * vector.x + y * vector.y + z * vector.z); } template TVector3 TVector3::operator % (const TVector3& v) const throw() { return TVector3(y * v.z - z * v.y, z * v.x - x * v.z, x * v.y - y * v.x); } template BALL_INLINE TVector3& TVector3::operator %= (const TVector3& v) throw() { set(y * v.z - z * v.y, z * v.x - x * v.z, x * v.y - y * v.x); return *this; } template BALL_INLINE T TVector3::getDistance(const TVector3& v) const throw() { T dx = x - v.x; T dy = y - v.y; T dz = z - v.z; return (T)sqrt(dx * dx + dy * dy + dz * dz); } template BALL_INLINE T TVector3::getSquareDistance(const TVector3& v) const throw() { T dx = x - v.x; T dy = y - v.y; T dz = z - v.z; return (dx * dx + dy * dy + dz * dz); } template BALL_INLINE TAngle TVector3::getAngle(const TVector3& vector) const throw(Exception::DivisionByZero) { T length_product = getSquareLength() * vector.getSquareLength(); if (length_product == (T)0) { throw Exception::DivisionByZero(__FILE__, __LINE__); } T acos_arg = ((*this) * vector) / sqrt(length_product); // ensure that the argument of acos is in the correct range // (might happen if the angle between the two vectors is // very close to zero) if (fabs(acos_arg) > 1.0) { return (TAngle)0.0; } return (TAngle)acos(acos_arg); } template BALL_INLINE TVector3 TVector3::getOrthogonalProjection(const TVector3& direction) const throw() { return ((direction * (*this)) / (direction * direction) * direction); } template TVector3 TVector3::getPerpendicularNormalization (const TVector3 &a, const TVector3 &b, const TVector3 &c) throw() { TVector3 diff1(b.x - a.x, b.y - a.y, b.z - a.z); TVector3 diff2(b.x - c.x, b.y - c.y, b.z - c.z); return TVector3 (diff1.y * diff2.z - diff1.z * diff2.y, diff1.z * diff2.x - diff1.x * diff2.z, diff1.x * diff2.y - diff1.y * diff2.x); } template BALL_INLINE T TVector3::getTripleProduct (const TVector3& a, const TVector3& b, const TVector3& c) throw() { return ( a.x * (b.y * c.z - b.z * c.y) + a.y * (b.z * c.x - b.x * c.z) + a.z * (b.x * c.y - b.y * c.x)); } template BALL_INLINE bool TVector3::operator == (const TVector3& v) const throw() { return (Maths::isEqual(x, v.x) && Maths::isEqual(y, v.y) && Maths::isEqual(z, v.z)); } template BALL_INLINE bool TVector3::operator < (const TVector3& v) const throw() { return (x < v.x || y < v.y || z < v.z); } template BALL_INLINE bool TVector3::operator != (const TVector3& v) const throw() { return (Maths::isNotEqual(x, v.x) || Maths::isNotEqual(y, v.y) || Maths::isNotEqual(z, v.z)); } template BALL_INLINE bool TVector3::isOrthogonalTo(const TVector3& v) const throw() { return Maths::isZero((*this) * v); } template BALL_INLINE bool TVector3::isValid() const throw() { return true; } template BALL_INLINE bool TVector3::isZero() const throw() { return (Maths::isZero(x) && Maths::isZero(y) && Maths::isZero(z)); } template void TVector3::dump(std::ostream& s, Size depth) const throw() { BALL_DUMP_STREAM_PREFIX(s); BALL_DUMP_HEADER(s, this, this); BALL_DUMP_DEPTH(s, depth); s << " (x = " << x << ", y = " << y << ", z = " << z << ")" << std::endl; BALL_DUMP_STREAM_SUFFIX(s); } /** Default three-dimensional vector class. This is the class used in BALL kernel to represent points, coordinates. */ typedef TVector3 Vector3; template BALL_INLINE TVector3 TVector3::operator + (const TVector3& b) const throw() { return TVector3(x + b.x, y + b.y, z + b.z); } template BALL_INLINE TVector3 TVector3::operator - (const TVector3& b) const throw() { return TVector3(x - b.x, y - b.y, z - b.z); } // template // void TVector3::write(PersistenceManager& pm) const // throw() // { // pm.writePrimitive(x, "x"); // pm.writePrimitive(y, "y"); // pm.writePrimitive(z, "z"); // } // // template // bool TVector3::read(PersistenceManager& pm) // throw() // { // pm.readPrimitive(x, "x"); // pm.readPrimitive(y, "y"); // pm.readPrimitive(z, "z"); // // return true; // } template BALL_INLINE TVector3 operator * (const T& scalar, const TVector3& vector) throw() { return TVector3(scalar * vector.x, scalar * vector.y, scalar * vector.z); } template std::istream& operator >> (std::istream& s, TVector3& v) throw() { char c; s >> c >> v.x >> v.y >> v.z >> c; return s; } template std::ostream& operator << (std::ostream& s, const TVector3& v) throw() { s << "(" << v.x << ' ' << v.y << ' ' << v.z << ')'; return s; } }// namespace BALL #endif // BALL_MATHS_VECTOR3_H ugene-1.9.8/src/plugins_3rdparty/ball/src/include/BALL/MATHS/vector4.h0000644000175000017500000005021411651544325023673 0ustar ilyailya// -*- Mode: C++; tab-width: 2; -*- // vi: set ts=2: // // $Id: vector4.h,v 1.53 2004-07-05 20:57:29 oliver Exp $ // #ifndef BALL_MATHS_VECTOR4_H #define BALL_MATHS_VECTOR4_H #ifndef BALL_COMMON_EXCEPTION_H # include #endif #ifndef BALL_MATHS_ANGLE_H # include #endif #ifdef BALL_HAS_IEEEFP_H # include #endif namespace BALL { /** \defgroup Vector4 Four-dimensional vector. \ingroup Primitives */ //@{ template class TVector4; /** @name Global binary operators for three-dimensional vectors. */ //@{ template BALL_INLINE TVector4 operator + (const TVector4& a, const TVector4& b) throw(); template BALL_INLINE TVector4 operator - (const TVector4& a, const TVector4& b) throw(); template std::istream& operator >> (std::istream& s, TVector4& vector) throw(); template std::ostream& operator << (std::ostream& s, const TVector4& vector) throw(); /** Generic Four-Dimensional Vector. Representation of points and vectors in four-dimensional space. */ template class TVector4 { public: BALL_CREATE(TVector4) /** @name Constructors and Destructors */ //@{ /** Default constructor. This method creates a new TVector4 object. The four components are initialized to (T)0. */ TVector4() throw(); /** Array constructor. This constructor creates a TVector4 object from the first four elements pointed by ptr. @param ptr the array to construct from @exception NullPointer if ptr == 0 */ TVector4(const T* ptr) throw(Exception::NullPointer); /** Scalar constructor. Create a new vector with all components set to the same value. @param value the value of all components */ explicit TVector4(const T& value) throw(); /** Detailed constructor. Create a new TVector4 object from three or four values of type T. @param x assigned to x @param y assigned to y @param z assigned to z @param h assigned to h, default: 1 ; */ TVector4(const T& x, const T& y, const T& z, const T& h = (T)1) throw(); /** Copy constructor. Create a new TVector4 object from another. @param vector the TVector4 object to be copied */ TVector4(const TVector4& vector) throw(); /** Destructor. Destructs the TVector4 object. As there are no dynamic data structures, nothing happens. */ virtual ~TVector4() throw(); /** Clear method The values are set to 0. */ virtual void clear() throw() { x = y = z = h = (T)0; } //@} /** @name Assignment */ //@{ /** Assign from an array. Assign the four components x, y, z and h from the first four elements of the array pointed to by ptr. @param ptr an array @exception Nullpointer if ptr == 0 */ void set(const T* ptr) throw(Exception::NullPointer); /** Assign the vector components. @param rx the new x component @param ry the new y component @param rz the new z component @param rh the new h component, default: 1 */ void set(const T& rx, const T& ry, const T& rz, const T& rh = (T)1) throw(); /** Assign from another TVector4. @param vector the TVector4 object to assign from */ void set(const TVector4& vector) throw(); /** Array assignment operator. Assigns the first four elements of an array to the vector components x, y, z and h. @param ptr the array @exception NullPointer if ptr == 0 */ TVector4& operator = (const T* ptr) throw(Exception::NullPointer); /** Assignment operator. Assign the vector components from another vector. @param vector the vector to assign from **/ TVector4& operator = (const TVector4& vector) throw(); /** Assignment operator. Assign a constant value to all four vector components. @param value the constant to assign to x, y, z, h */ TVector4& operator = (T value) throw(); /** Assign to an array. Sets the first four array elements pointed of array ptr to the values of the four vector components. @param ptr the array @exception NullPointer if ptr == 0 */ void get(T* ptr) const throw(Exception::NullPointer); /** Assign to four variables of type T. @param rx the x component @param ry the y component @param rz the z component @param rh the h component */ void get(T& rx, T& ry, T& rz, T& rh) const throw(); /** Assign to another Vector4. Assigns the vector components to another vector. @param vector the vector to be assigned to */ void get(TVector4& vector) const throw(); /** Swap the contents of two vectors. @param vector the vector to swap contents with */ void swap(TVector4& vector) throw(); //@} /** @name Accessors */ //@{ /** Return the length of the vector. The length of the vector is calculated as \f$\sqrt{x^2 + y^2 + z^2 + h^2}\f$. @return T, the vector length */ T getLength() const throw(); /** Return the squared length of the vector. This method avoids the square root needed in getLength, so this method should be preferred if possible. @return T, \f$x^2 + y^2 + z^2 + h^2\f$ */ T getSquareLength() const throw(); /** Normalize the vector. The vector is scaled with its length: \f$\{x|y|z|h\} *= \sqrt{x^2 + y^2 + z^2 + h^2}\f$. @return T, a reference to {\em *this} vector @exception DivisionByZero if the length of the vector is 0 */ TVector4& normalize() throw(Exception::DivisionByZero); /** Return a vector with all components 0. */ static const TVector4& getZero() throw(); /** Return a vector with all components 1. */ static const TVector4& getUnit() throw(); /** Assign one value to all vector components. @param value the value to be assigned to, default: 1 */ void set(const T& value = (T)1) throw(); /** Mutable array-like access to the components. @exception Exception::IndexOverflow if index > 3 */ T& operator [] (Position position) throw(Exception::IndexOverflow); /** Constant array-like access to the components. @exception Exception::IndexOverflow if index > 3 */ const T& operator [] (Position position) const throw(Exception::IndexOverflow); //@} /** @name Arithmetic operators */ //@{ /** Positive sign. */ TVector4 operator + () const throw(); /** Negative sign. */ TVector4 operator - () const throw(); /** Add a vector to this vector. @param vector the vector to add @return TVector4, {\em *this} */ TVector4& operator += (const TVector4& vector) throw(); /** Subtract a vector from this vector. @param vector the vector to subtract @return TVector4 {\em *this} */ TVector4& operator -= (const TVector4& vector) throw(); /** Scalar product. Return TVector4(x * scalar, y * scalar, z * scalar, h * scalar). @param scalar the scalar to multiply by @return TVector4 the scalar product of this vector and scalar */ TVector4 operator * (const T& scalar) throw(); /** Multiply by a scalar. Multiply all components of the vector with a scalar. @param scalar the scalar to multiply by @return TVector4& {\em *this} */ TVector4& operator *= (const T& scalar) throw(); /** Fraction of a vector. Return TVector4(x / scalar, y / scalar, z / scalar, h / scalar). @param scalar the scalar to divide by @return TVector4 @exception Exception::DivisionByZero if scalar == (T)0 */ TVector4 operator / (const T& scalar) throw(Exception::DivisionByZero); /** Divide a vector by a scalar. @param scalar the scalar to divide by @return TVector4&, {\em *this} @exception Exception::DivisionByZero if scalar == (T)0 */ TVector4& operator /= (const T& scalar) throw(Exception::DivisionByZero); /** Dot product. @param vector the vector to multiply by @return T the dot product of this vector with vector. */ T operator * (const TVector4& vector) const throw(); /** Return the distance to another vector @param vector the reference vector @return T, the distance */ T getDistance(const TVector4& vector) const throw(); /** Return the squared distance to another vector. This method avoids the square root needed in getDistance, so this method should be preferred if possible. @param vector the reference vector @return T, the squared distance */ T getSquareDistance(const TVector4& vector) const throw(); //@} /** @name Predicates */ //@{ /** Equality operator. The function Maths::isEqual is used to compare the values. \link isEqual Maths::isEqual \endlink @return bool, true if all four vector components are equal, false otherwise */ bool operator == (const TVector4& vector) const throw(); /** Inequality operator. The function Maths::isEqual is used to compare the values. \link Maths::isEqual Maths::isEqual \endlink @return bool, true if the two vectors differ in at least one component, false otherwise */ bool operator != (const TVector4& vector) const throw(); /** Orthogonality predicate. */ bool isOrthogonalTo(const TVector4& vector) const throw(); //@} /** @name Debugging and Diagnostics */ //@{ /** Test whether instance is valid. Always returns true @return bool true */ bool isValid() const throw(); /** Internal state dump. Dump the current internal state of {\em *this} to the output ostream s with dumping depth depth . @param s - output stream where to output the internal state of {\em *this} @param depth - the dumping depth */ void dump(std::ostream& s = std::cout, Size depth = 0) const throw(); //@} /** @name Attributes All vector components are public members for convenience. */ //@{ /** x component of the vector */ T x; /** y component of the vector */ T y; /** z component of the vector */ T z; /** height component of the vector */ T h; //@} }; //@} template TVector4::TVector4() throw() : x(0), y(0), z(0), h(0) { } template TVector4::TVector4(const T* ptr) throw(Exception::NullPointer) { if (ptr == 0) { throw Exception::NullPointer(__FILE__, __LINE__); } x = *ptr++; y = *ptr++; z = *ptr++; h = *ptr; } template TVector4::TVector4(const T& value) throw() : x(value), y(value), z(value), h(value) { } template TVector4::TVector4(const T& x, const T& y, const T& z, const T& h) throw() : x(x), y(y), z(z), h(h) { } template TVector4::TVector4(const TVector4& v) throw() : x(v.x), y(v.y), z(v.z), h(v.h) { } template TVector4::~TVector4() throw() { } template BALL_INLINE void TVector4::set(const T* ptr) throw(Exception::NullPointer) { if (ptr == 0) { throw Exception::NullPointer(__FILE__, __LINE__); } x = *ptr++; y = *ptr++; z = *ptr++; h = *ptr; } template BALL_INLINE void TVector4::set(const T& rx, const T& ry, const T& rz, const T& rh) throw() { x = rx; y = ry; z = rz; h = rh; } template BALL_INLINE void TVector4::set(const TVector4& v) throw() { x = v.x; y = v.y; z = v.z; h = v.h; } template BALL_INLINE TVector4& TVector4::operator = (const T* ptr) throw(Exception::NullPointer) { if (ptr == 0) { throw Exception::NullPointer(__FILE__, __LINE__); } x = *ptr++; y = *ptr++; z = *ptr++; h = *ptr; return *this; } template BALL_INLINE TVector4& TVector4::operator = (const TVector4& v) throw() { x = v.x; y = v.y; z = v.z; h = v.h; return *this; } template BALL_INLINE TVector4& TVector4::operator = (T value) throw() { x = value; y = value; z = value; h = value; return *this; } template BALL_INLINE void TVector4::get(T* ptr) const throw(Exception::NullPointer) { if (ptr == 0) { throw Exception::NullPointer(__FILE__, __LINE__); } *ptr++ = x; *ptr++ = y; *ptr++ = z; *ptr = h; } template BALL_INLINE void TVector4::get(T& rx, T& ry, T& rz, T& rh) const throw() { rx = x; ry = y; rz = z; rh = h; } template BALL_INLINE void TVector4::get(TVector4& v) const throw() { v.x = x; v.y = y; v.z = z; v.h = h; } template void TVector4::swap(TVector4& v) throw() { T temp = x; x = v.x; v.x = temp; temp = y; y = v.y; v.y = temp; temp = z; z = v.z; v.z = temp; temp = h; h = v.h; v.h = temp; } template BALL_INLINE T TVector4::getLength() const throw() { return (T)sqrt(x * x + y * y + z * z + h * h); } template BALL_INLINE T TVector4::getSquareLength() const throw() { return (T)(x * x + y * y + z * z + h * h); } template BALL_INLINE TVector4& TVector4::normalize() throw(Exception::DivisionByZero) { T len = (T)sqrt(x * x + y * y + z * z + h * h); if (Maths::isZero(len)) { throw Exception::DivisionByZero(__FILE__, __LINE__); } x /= len; y /= len; z /= len; h /= len; return *this; } template BALL_INLINE const TVector4& TVector4::getZero() throw() { static const TVector4 null4(0, 0, 0, 0); return null4; } template BALL_INLINE const TVector4& TVector4::getUnit() throw() { static const TVector4 unit_vector(1, 1, 1, 1); return unit_vector; } template BALL_INLINE void TVector4::set(const T& value) throw() { x = y = z = h = value; } template BALL_INLINE T& TVector4::operator [] (Position pos) throw(Exception::IndexOverflow) { if (pos > 3) { throw Exception::IndexOverflow(__FILE__, __LINE__); } switch (pos) { case 0: return x; case 1: return y; case 2: return z; case 3: default: return h; } } template BALL_INLINE const T& TVector4::operator [] (Position pos) const throw(Exception::IndexOverflow) { if (pos > 3) { throw Exception::IndexOverflow(__FILE__, __LINE__); } switch (pos) { case 0: return x; case 1: return y; case 2: return z; case 3: default: return h; } } template BALL_INLINE TVector4 TVector4::operator + () const throw() { return *this; } template BALL_INLINE TVector4 TVector4::operator - () const throw() { return TVector4(-x, -y, -z, -h); } template BALL_INLINE TVector4& TVector4::operator += (const TVector4& v) throw() { x += v.x; y += v.y; z += v.z; h += v.h; return *this; } template BALL_INLINE TVector4& TVector4::operator -= (const TVector4 &v) throw() { x -= v.x; y -= v.y; z -= v.z; h -= v.h; return *this; } template BALL_INLINE TVector4 TVector4::operator * (const T& scalar) throw() { return TVector4(x * scalar, y * scalar, z * scalar, h * scalar); } template BALL_INLINE TVector4& TVector4::operator *= (const T &scalar) throw() { x *= scalar; y *= scalar; z *= scalar; h *= scalar; return *this; } template TVector4TVector4::operator / (const T &scalar) throw(Exception::DivisionByZero) { if (Maths::isZero(scalar)) { throw Exception::DivisionByZero(__FILE__, __LINE__); } return TVector4(x / scalar, y / scalar, z / scalar, h / scalar); } template TVector4& TVector4::operator /= (const T& scalar) throw(Exception::DivisionByZero) { if (Maths::isZero(scalar)) { throw Exception::DivisionByZero(__FILE__, __LINE__); } x /= scalar; y /= scalar; z /= scalar; h /= scalar; return *this; } template BALL_INLINE T TVector4::operator * (const TVector4& v) const throw() { return (x * v.x + y * v.y + z * v.z + h * v.h); } template BALL_INLINE T TVector4::getDistance(const TVector4 &v) const throw() { T da = x - v.x; T db = y - v.y; T dc = z - v.z; T dd = h - v.h; return (T)sqrt(da * da + db * db + dc * dc + dd * dd); } template BALL_INLINE T TVector4::getSquareDistance(const TVector4 &v) const throw() { T da = x - v.x; T db = y - v.y; T dc = z - v.z; T dd = h - v.h; return (da * da + db * db + dc * dc + dd * dd); } template BALL_INLINE bool TVector4::operator == (const TVector4& v) const throw() { return (Maths::isEqual(x, v.x) && Maths::isEqual(y, v.y) && Maths::isEqual(z, v.z) && Maths::isEqual(h, v.h)); } template BALL_INLINE bool TVector4::operator != (const TVector4& v) const throw() { return (Maths::isNotEqual(x, v.x) || Maths::isNotEqual(y, v.y) || Maths::isNotEqual(z, v.z) || Maths::isNotEqual(h, v.h)); } template BALL_INLINE bool TVector4::isOrthogonalTo(const TVector4& v) const throw() { return Maths::isZero(*this * v); } template BALL_INLINE bool TVector4::isValid() const throw() { return true; } template void TVector4::dump(std::ostream& s, Size depth) const throw() { BALL_DUMP_STREAM_PREFIX(s); BALL_DUMP_HEADER(s, this, this); BALL_DUMP_DEPTH(s, depth); s << "x= " << x << ", y = " << y << ", z = " << z << ", h = " << h << std::endl; BALL_DUMP_STREAM_SUFFIX(s); } /** Default four-dimensional vector type */ typedef TVector4 Vector4; /** Addition operator for two vectors */ template BALL_INLINE TVector4 operator + (const TVector4& a, const TVector4& b) throw() { return TVector4(a.x + b.x, a.y + b.y, a.z + b.z, a.h + b.h); } /** Subtraction operator for two vectors @return TVector4 the new vector */ template BALL_INLINE TVector4 operator - (const TVector4& a, const TVector4& b) throw() { return TVector4(a.x - b.x, a.y - b.y, a.z - b.z, a.h - b.h); } /** Multiplication operator for a scalar and a vector @return TVector4 the new vector */ template BALL_INLINE TVector4 operator * (const T& scalar, const TVector4& v) throw() { return TVector4(scalar * v.x, scalar * v.y, scalar * v.z, scalar * v.h); } /** Multiplication operator for a vector and a scalar @return TVector4 the new vector */ template BALL_INLINE TVector4 operator * (const TVector4& v, const T& scalar) throw() { return TVector4(scalar * v.x, scalar * v.y, scalar * v.z, scalar * v.h); } /** Input operator Reads four values of type T from an input stream and assigns them to the components x, y, z and h of the vector. */ template std::istream& operator >> (std::istream& s, TVector4& v) throw() { char c; s >> c >> v.x >> v.y >> v.z >> v.h >>c; return s; } /** Output Operator. Write the four components of the vector to an output stream. The values are enclosed by brackets. \par Example: \par (0.1 2.0 0 1) */ template std::ostream& operator << (std::ostream& s, const TVector4& v) throw() { s << '(' < #endif #ifndef BALL_MATHS_VECTOR3_H # include #endif namespace BALL { /** \defgroup SimpleBox Box \ingroup GeometricObjects */ //@{ /** Generic three-dimensional Box. This class describes a three-dimensional box with edges parallel to the coordinate system. Hence, a box is given by the coordinates of the lower left front corner and ther upper right back corner.\\ */ template class TSimpleBox3 { public: BALL_CREATE(TSimpleBox3) /** @name Constructors and Destructors */ //@{ /** Default constructor. This method creates a new TSimpleBox3 object. The three components of the two TVector3 are initialized to {\tt (T)0}. */ TSimpleBox3() throw(); /** Copy constructor. Create a new TSimpleBox3 object from another. @param box the TSimpleBox3 object to be copied */ TSimpleBox3(const TSimpleBox3& box) throw(); /** Detailed constructor. Create a new TSimpleBox3 object from two instances of TVector3. @param a assigned to a @param b assigned to b */ TSimpleBox3(const TVector3& a, const TVector3& b) throw(); /** Detailed constructor. Create a new TSimpleBox3 object from six variables of type T . @param ax assigned to a.x @param ay assigned to a.y @param az assigned to a.z @param bx assigned to b.x @param by assigned to b.y @param bz assigned to b.z */ TSimpleBox3(const T& ax, const T& ay, const T& az, const T& bx, const T& by, const T& bz) throw(); /** Destructor. Destructs the TSimpleBox3 object. As there are no dynamic data structures, nothing happens. */ virtual ~TSimpleBox3() throw() { } /** Clear method. The values are set to 0. */ virtual void clear() throw(); //@} /** @name Assignment */ //@{ /** Assign from another instance of TSimpleBox3. @param box the TSimpleBox3 object to assign from */ void set(const TSimpleBox3& box) throw(); /** Assign from two points. @param lower the lower corner of the box @param upper the upper corner of the box */ void set(const TVector3& lower, const TVector3& upper) throw(); /** Assign from six values of type T . @param ax assigned to a.x @param ay assigned to a.y @param az assigned to a.z @param bx assigned to b.x @param by assigned to b.y @param bz assigned to b.z */ void set(const T& ax, const T& ay, const T& az, const T& bx, const T& by, const T& bz) throw(); /** Assignment operator. Assign the box components from another instance of TSimpleBox3. @param box the TSimpleBox3 to assign from **/ const TSimpleBox3& operator = (const TSimpleBox3& box) throw(); /** Assign to another instance of TSimpleBox3. Assigns the box components to another box. @param box the box to be assigned to */ void get(TSimpleBox3& box) const throw(); /** Assign to two variables of type TVector3 . @param lower the lower corner of the box @param upper the upper corner of the box */ void get(TVector3& lower, TVector3& upper) const throw(); /** Assign to six variables of type T . @param ax is assigned a.x @param ay is assigned a.y @param az is assigned a.z @param bx is assigned b.x @param by is assigned b.y @param bz is assigned b.z */ void get(T& ax, T& ay, T& az, T& bx, T& by, T& bz) const throw(); /** Swap the contents of two instances. @param box the box to swap contents with */ void swap(TSimpleBox3& box) throw(); //@} /** @name Accessors */ //@{ /** Calculate the surface area. @return T the surface */ T getSurface() const throw(); /** Calculate the volume. @return T the volume */ T getVolume() const throw(); /** Return the width of the box. @return T the width */ T getWidth() const throw(); /** Return the height of the box. @return T the height */ T getHeight() const throw(); /** Return the depth of the box. @return T the depth */ T getDepth() const throw(); /** Join the box with an other. Instance is set to the box containing both, this box and a given box. @param box the box to join with */ void join(const TSimpleBox3& box) throw(); //@} /** @name Predicates */ //@{ /** Equality operator. @return bool, true if all box components are equal, false otherwise */ bool operator == (const TSimpleBox3& box) const throw(); /** Inequality operator. @return bool, true if the two boxes differ in at least one component, false otherwise */ bool operator != (const TSimpleBox3& box) const throw(); /** Test if a given point is a member of the box. Optional it can be testet, if the point lies on the surface. @param point the point to be tested @param on_surface true to test the surface (default = false) @return bool, true or false */ bool has(const TVector3& point, bool on_surface = false) const throw(); /** Test if two boxes intersect. @param box the box to be tested @return bool, true if the two boxes are intersecting, false otherwise */ bool isIntersecting(const TSimpleBox3& box) const throw(); //@} /** @name Debugging and Diagnostics */ //@{ /** Test whether instance is valid. Always returns true. @return bool true */ bool isValid() const throw(); /** Internal state dump. Dump the current internal state of {\em *this} to the output ostream s with dumping depth depth . @param s - output stream where to output the internal state of {\em *this} @param depth - the dumping depth */ void dump(std::ostream& s = std::cout, Size depth = 0) const throw(); //@} /** @name Public members */ //@{ /** First point of the box. */ TVector3 a; /** Second point of the box. */ TVector3 b; //@} }; //@} template TSimpleBox3::TSimpleBox3() throw() : a(), b() { } template TSimpleBox3::TSimpleBox3(const TSimpleBox3& box) throw() : a(box.a), b(box.b) { } template TSimpleBox3::TSimpleBox3(const TVector3& lower, const TVector3& upper) throw() : a(lower), b(upper) { } template TSimpleBox3::TSimpleBox3(const T& ax, const T& ay, const T& az, const T& bx, const T& by, const T& bz) throw() : a(ax, ay, az), b(bx, by, bz) { } template BALL_INLINE void TSimpleBox3::set(const TSimpleBox3& box) throw() { a.set(box.a); b.set(box.b); } template BALL_INLINE void TSimpleBox3::set(const TVector3& lower, const TVector3& upper) throw() { a.set(lower); b.set(upper); } template BALL_INLINE void TSimpleBox3::set(const T& ax, const T& ay, const T& az, const T& bx, const T& by, const T& bz) throw() { a.set(ax, ay, az); b.set(bx, by, bz); } template BALL_INLINE const TSimpleBox3& TSimpleBox3::operator = (const TSimpleBox3 &box) throw() { set(box); return *this; } template BALL_INLINE void TSimpleBox3::get(TSimpleBox3& box) const throw() { box.set(*this); } template BALL_INLINE void TSimpleBox3::get(TVector3& lower, TVector3& upper) const throw() { lower.set(a); upper.set(b); } template BALL_INLINE void TSimpleBox3::get(T& ax, T& ay, T& az, T& bx, T& by, T& bz) const throw() { a.get(ax, ay, az); b.get(bx, by, bz); } template BALL_INLINE void TSimpleBox3::swap(TSimpleBox3& box) throw() { a.swap(box.a); b.swap(box.b); } template BALL_INLINE void TSimpleBox3::clear() throw() { a.set((T)0, (T)0, (T)0); b.set((T)0, (T)0, (T)0); } template BALL_INLINE T TSimpleBox3::getSurface() const throw() { T width = Maths::abs(b.x - a.x); T height = Maths::abs(b.y - a.y); T depth = Maths::abs(b.z - a.z); return ((width * height + width * depth + height * depth) * 2); } template BALL_INLINE T TSimpleBox3::getVolume() const throw() { T width = Maths::abs(b.x - a.x); T height = Maths::abs(b.y - a.y); T depth = Maths::abs(b.z - a.z); return (width * height * depth); } template BALL_INLINE T TSimpleBox3::getWidth() const throw() { return Maths::abs(b.x - a.x); } template BALL_INLINE T TSimpleBox3::getHeight() const throw() { return Maths::abs(b.y - a.y); } template BALL_INLINE T TSimpleBox3::getDepth() const throw() { return Maths::abs(b.z - a.z); } template void TSimpleBox3::join(const TSimpleBox3& box) throw() { T minimum = a.x; minimum = Maths::min(minimum, b.x); minimum = Maths::min(minimum, box.a.x); minimum = Maths::min(minimum, box.b.x); T maximum = a.x; maximum = Maths::max(maximum, b.x); maximum = Maths::max(maximum, box.a.x); maximum = Maths::max(maximum, box.b.x); a.x = minimum; b.x = maximum; minimum = a.y; minimum = Maths::min(minimum, b.y); minimum = Maths::min(minimum, box.a.y); minimum = Maths::min(minimum, box.b.y); maximum = a.y; maximum = Maths::max(maximum, b.y); maximum = Maths::max(maximum, box.a.y); maximum = Maths::max(maximum, box.b.y); a.y = minimum; b.y = maximum; minimum = a.z; minimum = Maths::min(minimum, b.z); minimum = Maths::min(minimum, box.a.z); minimum = Maths::min(minimum, box.b.z); maximum = a.z; maximum = Maths::max(maximum, b.z); maximum = Maths::max(maximum, box.a.z); maximum = Maths::max(maximum, box.b.z); a.z = minimum; b.z = maximum; } template BALL_INLINE bool TSimpleBox3::operator == (const TSimpleBox3& box) const throw() { return (a == box.a && b == box.b); } template BALL_INLINE bool TSimpleBox3::operator != (const TSimpleBox3 &box) const throw() { return !(*this == box); } template BALL_INLINE bool TSimpleBox3::isValid() const throw() { return (a.isValid() && b.isValid()); } template bool TSimpleBox3::has(const TVector3& point, bool on_surface) const throw() { if (!on_surface) { if (Maths::isLess(b[0],a[0]) || Maths::isLess(b[1],a[1]) || Maths::isLess(b[2],a[2])) { for (int i = 0; i < 3; i++) { if (Maths::isLess(point[i],b[i]) || Maths::isLess(a[i],point[i])) { return false; } } } else { for (int i = 0; i < 3; i++) { if (Maths::isLess(point[i],a[i]) || Maths::isLess(b[i],point[i])) { return false; } } } return true; } bool temp = false; for (int i = 0; i < 3; i++) { if (Maths::isEqual(point[i],a[i]) || Maths::isEqual(point[i],b[i])) { temp = true; break; } } return (temp && has(point, false)); } template bool TSimpleBox3::isIntersecting(const TSimpleBox3& box) const throw() { const TVector3* lower; const TVector3* higher; const TVector3* box_lower; const TVector3* box_higher; if (Maths::isLess(b[0],a[0]) || Maths::isLess(b[1],a[1]) || Maths::isLess(b[2],a[2])) { lower = &b; higher = &a; } else { lower = &a; higher = &b; } if (Maths::isLess(box.b[0],box.a[0]) || Maths::isLess(box.b[1],box.a[1]) || Maths::isLess(box.b[2],box.a[2])) { box_lower = &box.b; box_higher = &box.a; } else { box_lower = &box.a; box_higher = &box.b;; } for (int i = 0; i < 3; i++) { if (Maths::isLess((*box_higher)[i],(*lower)[i]) || Maths::isLess((*higher)[i],(*box_lower)[i])) { return false; } } return true; } template void TSimpleBox3::dump(std::ostream& s, Size depth) const throw() { BALL_DUMP_STREAM_PREFIX(s); BALL_DUMP_HEADER(s, this, this); BALL_DUMP_DEPTH(s, depth); s << " a: " << a << std::endl; BALL_DUMP_DEPTH(s, depth); s << " b: " << b << std::endl; BALL_DUMP_STREAM_SUFFIX(s); } /** @name Storers */ //@{ /** Input operator. Reads in two objects of type TVector3 a and b \ingroup SimpleBox */ template std::istream& operator >> (std::istream& s, TSimpleBox3& box) throw() { char c; s >> c >> box.a >> box.b >> c; return s; } /** Output Operator. Writes the two coordinates of the box to an output stream. The vectors are enclosed by brackets.\par Example \par ((0 1 2) (7.5 3.4 10)) \par @see TVector3::operator<< \ingroup SimpleBox */ template std::ostream& operator << (std::ostream& s, const TSimpleBox3& box) throw() { return s << "(" << box.a << ' ' << box.b << ')'; } /** Default three-dimensional box class of type float \ingroup SimpleBox */ typedef TSimpleBox3 SimpleBox3; } // namespace BALL #endif // BALL_MATHS_SimpleBox3_H ugene-1.9.8/src/plugins_3rdparty/ball/src/include/BALL/MATHS/line3.h0000644000175000017500000001705611651544325023326 0ustar ilyailya// -*- Mode: C++; tab-width: 2; -*- // vi: set ts=2: // // $Id: line3.h,v 1.48 2004-07-05 20:57:28 oliver Exp $ // #ifndef BALL_MATHS_LINE3_H #define BALL_MATHS_LINE3_H #ifndef BALL_COMMON_EXCEPTION_H # include #endif #ifndef BALL_MATHS_VECTOR3_H # include #endif namespace BALL { /** \defgroup Line Generic Line in Three-Dimensional Space. \ingroup GeometricObjects */ //@{ template class TLine3; /** @name Storers Stream operators of Line3 */ //@{ template std::ostream& operator << (std::ostream& s, const TLine3& line) throw(); template std::istream& operator >> (std::istream& s, TLine3& line) throw(); //@} /** Generic Line in Three-Dimensional Space. */ template class TLine3 { public: BALL_CREATE(TLine3) /** @name Enums */ //@{ /** form of parameter to describe the line: 0 one Point and one Vector. 1 two Points */ enum Form { FORM__PARAMETER = 0, FORM__TWO_POINTS = 1 }; //@} /** @name Constructors and Destructors */ //@{ /** Default constructor */ TLine3() throw() : p(), d() { } /** Copy constructor. @param TLine3 the TLine3 object to be copied @param bool ignored - just for interface consistency */ TLine3(const TLine3& line) throw() : p(line.p), d(line.d) { } // form: PARAMETER (default) or TWO_POINTS /** Detailed constructor. Depending on form, create a new TLine3 object from a point and a vector or from two points. @param point assigned to p @param vector assigned to d @param form assigns form of parameter 0 one Point and one Vector \par 1 two Points */ TLine3(const TVector3& point, const TVector3& vector, Form form = FORM__PARAMETER) throw() : p(point), d((form == FORM__PARAMETER) ? vector : vector - point) { } /** Destructor. Destructs the TLine3 object. As there are no dynamic data structures, nothing happens. */ virtual ~TLine3() throw() { } /** Clear method. The values are set to 0. */ virtual void clear() throw() { p.clear(); d.clear(); } //@} /** @name Assignment */ //@{ /** Swap the contents of two instances of lines. @param line the TLine3 to swap contents with */ void swap(TLine3& line) throw() { TVector3 temp_point(p); p = line.p; line.p = temp_point; TVector3 temp_vector(d); d = line.d; line.d = temp_vector; } /** Assign from another instance of TLine3. @param line the TLine3 object to assign from */ void set(const TLine3& line) throw() { p = line.p; d = line.d; } /** Assign from one point and a vector or from two points, depending on form. @param point assigned to p @param vector assigned to d @param form assigns form of parameter */ void set(const TVector3& point, const TVector3& vector, Form form = FORM__PARAMETER) throw() { p = point; if (form == FORM__PARAMETER) { d = vector; } else { d = vector - point; } } /** Assignment operator. Assign the components from another instance of line. @param line the vector to assign from **/ TLine3& operator = (const TLine3& line) throw() { p = line.p; d = line.d; return *this; } /** Assign to another instance of TLine3. Assigns the vector components to another vector. @param line the line to be assigned to */ void get(TLine3& line) const throw() { line.p = p; line.d = d; } /** Assign to two instances of TVector3. Type of components depends on form. @param point the first point @param vector the second point or the vector component @param form assigns form of parameter \par 0 one Point and one Vector \par 1 two Points */ void get(TVector3& point,TVector3& vector, Form form = FORM__PARAMETER) const throw() { point = p; if (form == FORM__PARAMETER) { vector = d; } else { vector - point = d; } } //@} /** @name Accessors */ //@{ /** Normalize the vector component. The vector is scaled with its length: \f$\{x|y|z|\} *= \sqrt{x^2 + y^2 + z^2}\f$. @exception DivisionByZero if the length of the vector is 0 */ void normalize() throw() { d.normalize(); } //@} /** @name Predicates */ //@{ /** Equality operator. @return bool, true if both components are equal, false otherwise */ bool operator == (const TLine3& line) const throw() { return (p == line.p && d == line.d); } /** Inequality operator. @return bool, true if the two lines differ in at least one component, false otherwise */ bool operator != (const TLine3& line) const throw() { return (p != line.p || d != line.d); } /** Test whether a given point is a member of the line. @return bool, true or false */ bool has(const TVector3& point) const throw() { if (Maths::isNotZero(d.x)) { T c = (point.x - p.x) / d.x; return (Maths::isEqual(p.y + c * d.y, point.y) && Maths::isEqual(p.z + c * d.z, point.z)); } else { if (Maths::isNotZero(d.y)) { T c = (point.y - p.y) / d.y; return (Maths::isEqual(p.x, point.x) // invariant: d.x == 0 && Maths::isEqual(p.z + c * d.z, point.z)); } else { if (Maths::isNotZero(d.z)) { return (Maths::isEqual(p.x, point.x) // invariant: d.x == 0 && Maths::isEqual(p.y, point.y)); // invariant: d.y == 0 } else { return false; } } } } //@} /** @name Debugging and Diagnostics */ //@{ /** Test whether instance is valid. Always returns true. @return bool true */ bool isValid() const throw() { return true; } /** Internal state dump. Dump the current internal state of {\em *this} to the output ostream s with dumping depth depth . @param s - output stream where to output the internal state of {\em *this} @param depth - the dumping depth */ void dump(std::ostream& s = std::cout, Size depth = 0) const throw() { BALL_DUMP_STREAM_PREFIX(s); BALL_DUMP_HEADER(s, this, this); BALL_DUMP_DEPTH(s, depth); s << " position: " << p << std::endl; BALL_DUMP_DEPTH(s, depth); s << " direction: " << d << std::endl; BALL_DUMP_STREAM_SUFFIX(s); } //@} /** @name Attributes */ //@{ /** Point Component. */ TVector3 p; /** Vector Component. */ TVector3 d; //@} }; //@} /** Default line of type float. \ingroup Line */ typedef TLine3 Line3; /** Input operator. Reads two objcts of type TVector3 from an istream and assigns them to d and p. */ template std::istream& operator >> (std::istream& s, TLine3& line) throw() { char c; s >> c >> line.p >> line.d >> c; return s; } /** Output operator. Writes the two public attributes d and p to an output stream. The values of the two vectors are enclosed in brackets. \par Example: \par ((0 0 0) (1 2 1)) @see TVector3::operator<< */ template std::ostream& operator << (std::ostream& s, const TLine3& line) throw() { s << '(' << line.p << ' ' << line.d << ')'; return s; } } // namespace BALL #endif // BALL_MATHS_LINE3_H ugene-1.9.8/src/plugins_3rdparty/ball/src/include/BALL/MATHS/surface.h0000644000175000017500000002442311651544325023740 0ustar ilyailya// -*- Mode: C++; tab-width: 2; -*- // vi: set ts=2: // // $Id: surface.h,v 1.29 2004-10-22 20:11:54 amoll Exp $ // #ifndef BALL_MATHS_SURFACE_H #define BALL_MATHS_SURFACE_H #ifndef BALL_MATHS_VECTOR3_H # include #endif namespace BALL { /** \defgroup GeometricSurface Surface in three-dimensional space. \ingroup GeometricObjects */ //@{ /** Generic Three-dimensional Surface class. This class describes a three-dimensional triangulated surface. Each triangle is represented by three indices to vertices (as described by the \link TSurface::Triangle TSurface::Triangle \endlink ). Each of the vertices has a position and possibly a normal vector associated. */ template class TSurface { public: BALL_CREATE(TSurface) /** @name Type definitions */ //@{ /** */ class Triangle { public: Index v1; Index v2; Index v3; bool operator == (const Triangle& triangle) const throw() { return (v1 == triangle.v1) && (v2 == triangle.v2) && (v3 == triangle.v3); } bool operator != (const Triangle& triangle) const throw() { return !(v1 == triangle.v1) && (v2 == triangle.v2) && (v3 == triangle.v3); } }; /// A vertex typedef TVector3 Vertex; /// A normal typedef TVector3 Normal; //@} /** @name Constructors and Destructors */ //@{ /// TSurface() throw(); /// TSurface(const TSurface& surface) throw(); /// virtual ~TSurface() throw(); //@} /** @name Assignment */ //@{ /// void set(const TSurface& surface) throw(); /// TSurface& operator = (const TSurface& surface) throw(); /// void get(TSurface& surface) const throw(); /// void clear() throw(); /** Read from MSMS file. Read the contents of the vertex and faces file created by Michael Sanners software MSMS. */ // void readMSMSFile(const String& vert_filename, const String& face_filename) // throw(Exception::FileNotFound); //@} /** @name Accessors */ //@{ /** Compute the surface area. The area is computed as the sum of the areas of all triangles. */ float getArea() const throw(); /// Return the number of triangles Size getNumberOfTriangles() const throw(); /// Return the number of vertices Size getNumberOfVertices() const throw(); /// Return the number of normals Size getNumberOfNormals() const throw(); /// Return a triangle with a given index Triangle& getTriangle(Position index) throw(); /// Return a triangle with a given index const Triangle& getTriangle(Position index) const throw(); /// Clear all triangles void clearTriangles(); /// Resize the triangle array void resizeTriangles(Size size); /// Add a triangle void pushBackTriangle(const Triangle& triangle) throw(); /// Return the position of a vertex Vertex& getVertex(Position index) throw(); /// Return the position of a vertex const Vertex& getVertex(Position index) const throw(); /// Clear all vertices void clearVertices(); /// Resize the vertex array void resizeVertices(Size size); /// Add a vertex void pushBackVertex(const Vertex& vertex) throw(); /// Return the position of a normal Normal& getNormal(Position index) throw(); /// Return the position of a normal const Normal& getNormal(Position index) const throw(); /// Clear all normals void clearNormals(); /// Resize the normal array void resizeNormals(Size size); /// Add a normal void pushBackNormal(const Normal& n) throw(); //@} /** @name Predicates */ //@{ /// bool operator == (const TSurface& surface) const throw(); /// bool operator != (const TSurface& surface) const throw(); //@} /** @name Attributes */ //@{ /// the vertices vector vertex; /// the normals for each vertex vector normal; /// the triangles vector triangle; //@} }; //@} template TSurface::TSurface() throw() { } template TSurface::TSurface(const TSurface& surface) throw() : vertex(surface.vertex), normal(surface.normal), triangle(surface.triangle) { } template TSurface::~TSurface() throw() { } template void TSurface::clear() throw() { vertex.clear(); normal.clear(); triangle.clear(); } template void TSurface::set(const TSurface& surface) throw() { vertex = surface.vertex; normal = surface.normal; triangle = surface.triangle; } template TSurface& TSurface::operator = (const TSurface& surface) throw() { vertex = surface.vertex; normal = surface.normal; triangle = surface.triangle; return *this; } template void TSurface::get(TSurface& surface) const throw() { surface.vertex = vertex; surface.normal = normal; surface.triangle = triangle; } // template // void TSurface::readMSMSFile(const String& vert_filename, const String& face_filename) // throw(Exception::FileNotFound) // { // // delete old contents // normal.clear(); // vertex.clear(); // triangle.clear(); // // std::ifstream file(vert_filename.c_str()); // if (!file) // { // throw Exception::FileNotFound(__FILE__, __LINE__, vert_filename); // } // // // there are two formats: one with three lines of // // header and one without // String line; // while ((line.countFields() != 9) && file) // { // line.getline(file); // } // // String s[6]; // while (file && (line.countFields() == 9)) // { // // read the vertex coordinates and the normal vector // line.split(s, 6); // vertex.push_back(Vertex(s[0].toFloat(), s[1].toFloat(), s[2].toFloat())); // normal.push_back(Normal(s[3].toFloat(), s[4].toFloat(), s[5].toFloat())); // // // read the next line // line.getline(file); // } // file.close(); // // workaround for trouble in File // file.clear(); // // // now read the faces file: // file.open(face_filename.c_str()); // if (!file) // { // throw Exception::FileNotFound(__FILE__, __LINE__, face_filename); // } // // // there are two formats: one with three lines of // // header and one without // while ((line.countFields() != 5) && file) // { // line.getline(file); // } // // Triangle t; // Size number_of_vertices = (Size)vertex.size(); // while (file && (line.countFields() == 5)) // { // // read the vertex indices // line.split(s, 5); // t.v1 = (Index)s[0].toInt() - 1; // t.v2 = (Index)s[1].toInt() - 1; // t.v3 = (Index)s[2].toInt() - 1; // // // if all three vertex indices are valid, insert the triangle // if ((t.v1 < (Index)number_of_vertices) && (t.v1 >= 0) // && (t.v1 < (Index)number_of_vertices) && (t.v1 >= 0) // && (t.v1 < (Index)number_of_vertices) && (t.v1 >= 0)) // { // triangle.push_back(t); // } // // // read the next line // line.getline(file); // } // file.close(); // } template float TSurface::getArea() const throw() { // add the areas of all triangles double area = 0; for (Size i = 0; i < triangle.size(); i++) { // add the length of the vector products of two sides of each triangle // this is equivalent to the surface area of the parallelogram, and thus to twice the triangle area area += ((vertex[triangle[i].v2] - vertex[triangle[i].v1]) % (vertex[triangle[i].v3] - vertex[triangle[i].v1])).getLength(); } // A = 1/2 \sum |r1 x r2| return (float)( area * 0.5 ); } template bool TSurface::operator == (const TSurface& surface) const throw() { return ((surface.vertex == vertex) && (surface.normal == normal) && (surface.triangle == triangle)); } template BALL_INLINE Size TSurface::getNumberOfTriangles() const throw() { return (Size)triangle.size(); } template BALL_INLINE Size TSurface::getNumberOfVertices() const throw() { return (Size)vertex.size(); } template BALL_INLINE Size TSurface::getNumberOfNormals() const throw() { return (Size)normal.size(); } template BALL_INLINE typename TSurface::Triangle& TSurface::getTriangle(Position index) throw() { return triangle[index]; } template BALL_INLINE const typename TSurface::Triangle& TSurface::getTriangle(Position index) const throw() { return triangle[index]; } template BALL_INLINE void TSurface::clearTriangles() { triangle.clear(); } template BALL_INLINE void TSurface::resizeTriangles(Size size) { triangle.resize(size); } template BALL_INLINE void TSurface::pushBackTriangle(const Triangle& t) throw() { triangle.push_back(t); } template BALL_INLINE typename TSurface::Vertex& TSurface::getVertex(Position index) throw() { return vertex[index]; } template BALL_INLINE const typename TSurface::Vertex& TSurface::getVertex(Position index) const throw() { return vertex[index]; } template BALL_INLINE void TSurface::clearVertices() { vertex.clear(); } template BALL_INLINE void TSurface::resizeVertices(Size size) { vertex.resize(size); } template BALL_INLINE void TSurface::pushBackVertex(const typename TSurface::Vertex& position) throw() { vertex.push_back(position); } template BALL_INLINE typename TSurface::Normal& TSurface::getNormal(Position index) throw() { return normal[index]; } template BALL_INLINE const typename TSurface::Normal& TSurface::getNormal(Position index) const throw() { return normal[index]; } template BALL_INLINE void TSurface::clearNormals() { normal.clear(); } template BALL_INLINE void TSurface::resizeNormals(Size size) { normal.resize(size); } template BALL_INLINE void TSurface::pushBackNormal(const typename TSurface::Normal& n) throw() { normal.push_back(n); } template bool TSurface::operator != (const TSurface& surface) const throw() { return !(*this == surface); } /** Default surface type. \ingroup GeometricSurface */ typedef TSurface Surface; } // namespace BALL #endif // BALL_MATHS_SURFACE_H ugene-1.9.8/src/plugins_3rdparty/ball/src/include/BALL/MATHS/analyticalGeometry.h0000644000175000017500000011156711651544325026153 0ustar ilyailya// -*- Mode: C++; tab-width: 2; -*- // vi: set ts=2: // // $Id: analyticalGeometry.h,v 1.63 2004-02-23 17:26:02 anhi Exp $ // #ifndef BALL_MATHS_ANALYTICALGEOMETRY_H #define BALL_MATHS_ANALYTICALGEOMETRY_H #ifndef BALL_COMMON_EXCEPTION_H # include #endif #ifndef BALL_MATHS_ANGLE_H # include #endif #ifndef BALL_MATHS_CIRCLE3_H # include #endif #ifndef BALL_MATHS_LINE3_H # include #endif #ifndef BALL_MATHS_PLANE3_H # include #endif #ifndef BALL_MATHS_SPHERE3_H # include #endif #ifndef BALL_MATHS_VECTOR3_H # include #endif #define BALL_MATRIX_CELL(m, dim, row, col) *((m) + (row) * (dim) + (col)) #define BALL_CELL(x, y) *((m) + (y) * (dim) + (x)) namespace BALL { /** \defgroup AnalyticalGeometry Analytical Geometry representation of analytical geometry functions, using the classes: TAngle, TCircle3, TLine3, TPlane3, TSphere3, TVector3. \ingroup Mathematics */ //@{ /** Subroutine to get the determinant of any matrix. Direct usage of this function should be avoided. Instead use T getDeterminant(const T* m, Size dim) @param m pointer to matrix @param dim dimension of the matrix */ template BALL_INLINE T getDeterminant_(const T* m, Size dim) throw() { T determinant = 0; Index dim1 = dim - 1; if (dim > 1) { T* submatrix = new T[dim1 * dim1]; for (Index i = 0; i < (Index)dim; ++i) { for (Index j = 0; j < dim1; ++j) { for (Index k = 0; k < dim1; ++k) { *(submatrix + j * dim1 + k) = *(m + (j + 1) * dim + (k < i ? k : k + 1)); } } determinant += *(m + i) * (i / 2.0 == i / 2 ? 1 : -1) * getDeterminant_(submatrix, dim1); } delete [] submatrix; } else { determinant = *m; } return determinant; } /** Get the determinant of any matrix. @param m pointer to matrix @param dim dimension of the matrix */ template T getDeterminant(const T* m, Size dim) throw() { if (dim == 2) { return (BALL_CELL(0,0) * BALL_CELL(1,1) - BALL_CELL(0,1) * BALL_CELL(1,0)); } else if (dim == 3) { return ( BALL_CELL(0,0) * BALL_CELL(1,1) * BALL_CELL(2,2) + BALL_CELL(0,1) * BALL_CELL(1,2) * BALL_CELL(2,0) + BALL_CELL(0,2) * BALL_CELL(1,0) * BALL_CELL(2,1) - BALL_CELL(0,2) * BALL_CELL(1,1) * BALL_CELL(2,0) - BALL_CELL(0,0) * BALL_CELL(1,2) * BALL_CELL(2,1) - BALL_CELL(0,1) * BALL_CELL(1,0) * BALL_CELL(2,2)); } else { return getDeterminant_(m, dim); } } /** Get the determinant of an 2x2 matrix. @param m pointer to matrix */ template BALL_INLINE T getDeterminant2(const T* m) throw() { Size dim = 2; return (BALL_CELL(0,0) * BALL_CELL(1,1) - BALL_CELL(0,1) * BALL_CELL(1,0)); } /** Get the determinant of an 2x2 matrix. @param m00 first value of the matrix @param m01 second value of the matrix @param m10 third value of the matrix @param m11 fourth value of the matrix */ template BALL_INLINE T getDeterminant2(const T& m00, const T& m01, const T& m10, const T& m11) throw() { return (m00 * m11 - m01 * m10); } /** Get the determinant of an 3x3 matrix. @param m pointer to matrix */ template BALL_INLINE T getDeterminant3(const T *m) throw() { Size dim = 3; return ( BALL_CELL(0,0) * BALL_CELL(1,1) * BALL_CELL(2,2) + BALL_CELL(0,1) * BALL_CELL(1,2) * BALL_CELL(2,0) + BALL_CELL(0,2) * BALL_CELL(1,0) * BALL_CELL(2,1) - BALL_CELL(0,2) * BALL_CELL(1,1) * BALL_CELL(2,0) - BALL_CELL(0,0) * BALL_CELL(1,2) * BALL_CELL(2,1) - BALL_CELL(0,1) * BALL_CELL(1,0) * BALL_CELL(2,2)); } /** Get the determinant of an 3x3 matrix. @param m00, m01, m02, m10, m11, m12, m20, m21, m22 the elements of the matrix */ template BALL_INLINE T getDeterminant3(const T& m00, const T& m01, const T& m02, const T& m10, const T& m11, const T& m12, const T& m20, const T& m21, const T& m22) throw() { return ( m00 * m11 * m22 + m01 * m12 * m20 + m02 * m10 * m21 - m02 * m11 * m20 - m00 * m12 * m21 - m01 * m10 * m22); } /** Solve a system of linear equations. Given a system of linear equations \par \par \f$ \begin{array}{ccccccccc} a_{1,1} x_1 & + & a_{1,2} x_2 & + & \ldots & + & a_{1,n} x_n & = & a_{1,(n+1)} \\ a_{2,1} x_1 & + & a_{2,2} x_2 & + & \ldots & + & a_{2,n} x_n & = & a_{2,(n+1)} \\ \vdots & & \vdots & & \ddots & & \vdots & & \vdots \\ a_{n,1} x_1 & + & a_{n,2} x_2 & + & \ldots & + & a_{n,n} x_n & = & a_{n,(n+1)} \\ \end{array} \f$ \par in matrix form, identify the solution \f$x = (x_1, x_2,\ldots x_N)\f$. \par m should point to a C-style array containing the \f$n\times(n+1)\f$ matrix A. \par The elements of A are row-ordered, i.e., they are ordered like this: \par \f$ a_{1,1}, a_{1,2}, \cdot, a_{1,(n+1)}, a_{2,1}, \ldots a_{n,(n+1)} \f$ \par x points to a C-style array that will contain the solution vector x upon successful termination of the function. \par If there is no solution or the system is under-determined, return false. @param m pointer to the factors in the equations @param x pointer in which the results are stored @param dim the dimension of the equation system (number of variables) @return bool true if a solution is found */ template bool SolveSystem(const T* m, T* x, const Size dim) throw() { T pivot; Index i, j, k, p; // the column dimension of the matrix const Size col_dim = dim + 1; T* matrix = new T[dim * (dim + 1)]; const T* source = m; T* target = (T*)matrix; T* end = (T*)&BALL_MATRIX_CELL(matrix, col_dim, dim - 1, dim); while (target <= end) { *target++ = *source++; } for (i = 0; i < (Index)dim; ++i) { pivot = BALL_MATRIX_CELL(matrix, col_dim, i, i); p = i; for (j = i + 1; j < (Index)dim; ++j) { if (Maths::isLess(pivot, BALL_MATRIX_CELL(matrix, col_dim, j, i))) { pivot = BALL_MATRIX_CELL(matrix, col_dim, j, i); p = j; } } if (p != i) { T tmp; for (k = i; k < (Index)dim + 1; ++k) { tmp = BALL_MATRIX_CELL(matrix, dim, i, k); BALL_MATRIX_CELL(matrix, col_dim, i, k) = BALL_MATRIX_CELL(matrix, col_dim, p, k); BALL_MATRIX_CELL(matrix, col_dim, p, k) = tmp; } } else if (Maths::isZero(pivot) || Maths::isNan(pivot)) { // invariant: matrix m is singular delete [] matrix; return false; } for (j = dim; j >= i; --j) { BALL_MATRIX_CELL(matrix, col_dim, i, j) /= pivot; } for (j = i + 1; j < (Index)dim; ++j) { pivot = BALL_MATRIX_CELL(matrix, col_dim, j, i); for (k = dim; k>= i; --k) { BALL_MATRIX_CELL(matrix, col_dim, j, k) -= pivot * BALL_MATRIX_CELL(matrix, col_dim, i, k); } } } x[dim - 1] = BALL_MATRIX_CELL(matrix, col_dim, dim - 1, dim); for (i = dim - 2; i >= 0; --i) { x[i] = BALL_MATRIX_CELL(matrix, col_dim, i, dim); for (j = i + 1; j < (Index)dim; ++j) { x[i] -= BALL_MATRIX_CELL(matrix, col_dim, i, j) * x[j]; } } delete [] matrix; return true; } #undef BALL_CELL #undef BALL_MATRIX_CELL /** Solve a system of two equations of the form \f$a_1 x_1 + b_1 x_2 = c_1\f$ and \f$a_2 x_1 + b_2 x_2 = c_2\f$. @param a1, b1, c1, a2, b2, c2 constants of the system @param x1 the first solution @param x2 the second solution @return bool true if a solution is found */ template BALL_INLINE bool SolveSystem2(const T& a1, const T& b1, const T& c1, const T& a2, const T& b2, const T& c2, T& x1, T& x2) throw() { T quot = (a1 * b2 - a2 * b1); if (Maths::isZero(quot)) { return false; } x1 = (c1 * b2 - c2 * b1) / quot; x2 = (a1 * c2 - a2 * c1) / quot; return true; } /** Solve a quadratic equation of the form a \f$x^2 + b x + c = 0\f$. @param a @param b @param c @param x1 the first solution @param x2 the second solution @return short the number of solutions (0 - 2) */ template short SolveQuadraticEquation(const T& a, const T& b, const T &c, T &x1, T &x2) throw() { if (a == 0) { if (b == 0) { return 0; } x1 = x2 = c / b; return 1; } T discriminant = b * b - 4 * a * c; if (Maths::isLess(discriminant, 0)) { return 0; } T sqrt_discriminant = sqrt(discriminant); if (Maths::isZero(sqrt_discriminant)) { x1 = x2 = -b / (2 * a); return 1; } else { x1 = (-b + sqrt_discriminant) / (2 * a); x2 = (-b - sqrt_discriminant) / (2 * a); return 2; } } /** Get the partition of two vectors. @param a the first vector @param b the second vector @return TVector3 the partition */ template BALL_INLINE TVector3 GetPartition(const TVector3& a, const TVector3& b) throw() { return TVector3((b.x + a.x) / 2, (b.y + a.y) / 2, (b.z + a.z) / 2); } /** Get the partition of two vectors, calculated with two ratio factors. @param a the first vector @param b the second vector @param r the ratio factor of the first vector @param s the ratio factor of the second vector @return TVector3 the partition */ template BALL_INLINE TVector3 GetPartition(const TVector3& a, const TVector3& b, const T& r, const T& s) throw(Exception::DivisionByZero) { T sum = r + s; if (sum == (T)0) { throw Exception::DivisionByZero(__FILE__, __LINE__); } return TVector3 ((s * a.x + r * b.x) / sum, (s * a.y + r * b.y) / sum, (s * a.z + r * b.z) / sum); } /** Get the distance between two points. @param a the first point @param b the second point @return T the distance */ template BALL_INLINE T GetDistance(const TVector3& a, const TVector3& b) throw() { T dx = a.x - b.x; T dy = a.y - b.y; T dz = a.z - b.z; return sqrt(dx * dx + dy * dy + dz * dz); } /** Get the distance between a line and a point. @param line the line @param point the point @return T the distance */ template BALL_INLINE T GetDistance(const TLine3& line, const TVector3& point) throw(Exception::DivisionByZero) { if (line.d.getLength() == (T)0) { throw Exception::DivisionByZero(__FILE__, __LINE__); } return ((line.d % (point - line.p)).getLength() / line.d.getLength()); } /** Get the distance between a point and a line. @param point the point @param line the line @return T the distance */ template BALL_INLINE T GetDistance(const TVector3& point, const TLine3& line) throw(Exception::DivisionByZero) { return GetDistance(line, point); } /** Get the distance between two lines. @param a the first line @param b the second line @return T the distance */ template T GetDistance(const TLine3& a, const TLine3& b) throw(Exception::DivisionByZero) { T cross_product_length = (a.d % b.d).getLength(); if (Maths::isZero(cross_product_length)) { // invariant: parallel lines if (a.d.getLength() == (T)0) { throw Exception::DivisionByZero(__FILE__, __LINE__); } return ((a.d % (b.p - a.p)).getLength() / a.d.getLength()); } else { T spat_product = TVector3::getTripleProduct(a.d, b.d, b.p - a.p); if (Maths::isNotZero(spat_product)) { // invariant: windschiefe lines return (Maths::abs(spat_product) / cross_product_length); } else { // invariant: intersecting lines return 0; } } } /** Get the distance between a point and a plane. @param point the point @param plane the plane @return T the distance */ template BALL_INLINE T GetDistance(const TVector3& point, const TPlane3& plane) throw(Exception::DivisionByZero) { T length = plane.n.getLength(); if (length == (T)0) { throw Exception::DivisionByZero(__FILE__, __LINE__); } return (Maths::abs(plane.n * (point - plane.p)) / length); } /** Get the distance between a plane and a point. @param plane the plane @param point the point @return T the distance */ template BALL_INLINE T GetDistance(const TPlane3& plane, const TVector3& point) throw(Exception::DivisionByZero) { return GetDistance(point, plane); } /** Get the distance between a line and a plane. @param line the line @param plane the plane @return T the distance */ template BALL_INLINE T GetDistance(const TLine3& line, const TPlane3& plane) throw(Exception::DivisionByZero) { T length = plane.n.getLength(); if (length == (T)0) { throw Exception::DivisionByZero(__FILE__, __LINE__); } return (Maths::abs(plane.n * (line.p - plane.p)) / length); } /** Get the distance between a plane and a line. @param plane the plane @param line the line @return T the distance */ template BALL_INLINE T GetDistance(const TPlane3& plane, const TLine3& line) throw(Exception::DivisionByZero) { return GetDistance(line, plane); } /** Get the distance between two planes. @param a the first plane @param b the second plane @return T the distance */ template BALL_INLINE T GetDistance(const TPlane3& a, const TPlane3& b) throw(Exception::DivisionByZero) { T length = a.n.getLength(); if (length == (T)0) { throw Exception::DivisionByZero(__FILE__, __LINE__); } return (Maths::abs(a.n * (a.p - b.p)) / length); } /** Get the angle between two Vector3. @param a the first vector @param b the second vector @param intersection_angle the resulting angle @return bool, always true */ template BALL_INLINE bool GetAngle(const TVector3& a, const TVector3& b, TAngle &intersection_angle) { T length_product = a.getSquareLength() * b.getSquareLength(); if(Maths::isZero(length_product)) { return false; } intersection_angle = a.getAngle(b); return true; } /** Get the angle between two lines. @param a the first line @param b the second line @param intersection_angle the resulting angle @return bool, true if an angle can be calculated, otherwise false */ template BALL_INLINE bool GetAngle(const TLine3& a, const TLine3& b, TAngle& intersection_angle) throw() { T length_product = a.d.getSquareLength() * b.d.getSquareLength(); if(Maths::isZero(length_product)) { return false; } intersection_angle = acos(Maths::abs(a.d * b.d) / sqrt(length_product)); return true; } /** Get the angle between a plane and a Vector3. @param plane the plane @param vector the Vector3 @param intersection_angle the resulting angle @return bool, true if an angle can be calculated, otherwise false */ template BALL_INLINE bool GetAngle(const TPlane3& plane, const TVector3& vector, TAngle& intersection_angle) throw() { T length_product = plane.n.getSquareLength() * vector.getSquareLength(); if (Maths::isZero(length_product)) { return false; } else { intersection_angle = asin(Maths::abs(plane.n * vector) / sqrt(length_product)); return true; } } /** Get the angle between a vector3 and a plane. @param vector the vector3 @param plane the plane @param intersection_angle the resulting angle @return bool, true if an angle can be calculated, otherwise false */ template BALL_INLINE bool GetAngle(const TVector3& vector ,const TPlane3& plane, TAngle &intersection_angle) throw() { return GetAngle(plane, vector, intersection_angle); } /** Get the angle between a plane and a line. @param plane the plane @param line the line @param intersection_angle the resulting angle @return bool, true if an angle can be calculated, otherwise false */ template BALL_INLINE bool GetAngle(const TPlane3& plane,const TLine3& line, TAngle& intersection_angle) throw() { T length_product = plane.n.getSquareLength() * line.d.getSquareLength(); if (Maths::isZero(length_product)) { return false; } intersection_angle = asin(Maths::abs(plane.n * line.d) / sqrt(length_product)); return true; } /** Get the angle between a line and a plane. @param line the line @param plane the plane @param intersection_angle the resulting angle @return bool, true if an angle can be calculated, otherwise false */ template BALL_INLINE bool GetAngle(const TLine3& line, const TPlane3& plane, TAngle& intersection_angle) throw() { return GetAngle(plane, line, intersection_angle); } /** Get the angle between two planes. @param a the first plane @param b the second plane @param intersection_angle the resulting angle @return bool, true if an angle can be calculated, otherwise false */ template BALL_INLINE bool GetAngle(const TPlane3& a, const TPlane3& b, TAngle& intersection_angle) throw() { T length_product = a.n.getSquareLength() * b.n.getSquareLength(); if(Maths::isZero(length_product)) { return false; } intersection_angle = acos(Maths::abs(a.n * b.n) / sqrt(length_product)); return true; } /** Get the intersection point between two lines. @param a the first line @param b the second line @param point the resulting intersection @return bool, true if an intersection can be calculated, otherwise false */ template bool GetIntersection(const TLine3& a, const TLine3& b, TVector3& point) throw() { T c1, c2; if ((SolveSystem2(a.d.x, -b.d.x, b.p.x - a.p.x, a.d.y, -b.d.y, b.p.y - a.p.y, c1, c2) == true && Maths::isEqual(a.p.z + a.d.z * c1, b.p.z + b.d.z * c2)) || (SolveSystem2(a.d.x, -b.d.x, b.p.x - a.p.x, a.d.z, -b.d.z, b.p.z - a.p.z, c1, c2) == true && Maths::isEqual(a.p.y + a.d.y * c1, b.p.y + b.d.y * c2)) || (SolveSystem2(a.d.y, -b.d.y, b.p.y - a.p.y, a.d.z, -b.d.z, b.p.z - a.p.z, c1, c2) == true && Maths::isEqual(a.p.x + a.d.x * c1, b.p.x + b.d.x * c2))) { point.set(a.p.x + a.d.x * c1, a.p.y + a.d.y * c1, a.p.z + a.d.z * c1); return true; } return false; } /** Get the intersection point between a plane and a line. @param plane the plane @param line the line @param intersection_point the resulting intersection @return bool, true if an intersection can be calculated, otherwise false */ template BALL_INLINE bool GetIntersection(const TPlane3& plane, const TLine3& line, TVector3& intersection_point) throw() { T dot_product = plane.n * line.d; if (Maths::isZero(dot_product)) { return false; } intersection_point.set(line.p + (plane.n * (plane.p - line.p)) * line.d / dot_product); return true; } /** Get the intersection point between a line and a plane. @param line the line @param plane the plane @param intersection_point the resulting intersection @return bool, true if an intersection can be calculated, otherwise false */ template BALL_INLINE bool GetIntersection(const TLine3& line, const TPlane3& plane, TVector3& intersection_point) throw() { return GetIntersection(plane, line, intersection_point); } /** Get the intersection line between two planes. @param plane1 the first plane @param plane2 the second plane @param line the resulting intersection @return bool, true if an intersection can be calculated, otherwise false */ template bool GetIntersection(const TPlane3& plane1, const TPlane3& plane2, TLine3& line) throw() { T u = plane1.p*plane1.n; T v = plane2.p*plane2.n; T det = plane1.n.x*plane2.n.y-plane1.n.y*plane2.n.x; if (Maths::isZero(det)) { det = plane1.n.x*plane2.n.z-plane1.n.z*plane2.n.x; if (Maths::isZero(det)) { det = plane1.n.y*plane2.n.z-plane1.n.z*plane2.n.y; if (Maths::isZero(det)) { return false; } else { T a = plane2.n.z/det; T b = -plane1.n.z/det; T c = -plane2.n.y/det; T d = plane1.n.y/det; line.p.x = 0; line.p.y = a*u+b*v; line.p.z = c*u+d*v; line.d.x = -1; line.d.y = a*plane1.n.x+b*plane2.n.x; line.d.z = c*plane1.n.x+d*plane2.n.x; } } else { T a = plane2.n.z/det; T b = -plane1.n.z/det; T c = -plane2.n.x/det; T d = plane1.n.x/det; line.p.x = a*u+b*v; line.p.y = 0; line.p.z = c*u+d*v; line.d.x = a*plane1.n.y+b*plane2.n.y; line.d.y = -1; line.d.z = c*plane1.n.y+d*plane2.n.y; } } else { T a = plane2.n.y/det; T b = -plane1.n.y/det; T c = -plane2.n.x/det; T d = plane1.n.x/det; line.p.x = a*u+b*v; line.p.y = c*u+d*v; line.p.z = 0; line.d.x = a*plane1.n.z+b*plane2.n.z; line.d.y = c*plane1.n.z+d*plane2.n.z; line.d.z = -1; } return true; } /** Get the intersection point between a sphere and a line. @param sphere the sphere @param line the line @param intersection_point1 the first intersection point @param intersection_point2 the second intersection point @return bool, true if an intersection can be calculated, otherwise false */ template bool GetIntersection(const TSphere3& sphere, const TLine3& line, TVector3& intersection_point1, TVector3& intersection_point2) throw() { T x1, x2; short number_of_solutions = SolveQuadraticEquation (line.d * line.d, (line.p - sphere.p) * line.d * 2, (line.p - sphere.p) * (line.p - sphere.p) - sphere.radius * sphere.radius, x1, x2); if (number_of_solutions == 0) { return false; } intersection_point1 = line.p + x1 * line.d; intersection_point2 = line.p + x2 * line.d; return true; } /** Get the intersection point between a line and a sphere. @param line the line @param sphere the sphere @param intersection_point1 the first intersection point @param intersection_point2 the second intersection point @return bool, true if an intersection can be calculated, otherwise false */ template BALL_INLINE bool GetIntersection(const TLine3& line, const TSphere3& sphere, TVector3& intersection_point1, TVector3& intersection_point2) throw() { return GetIntersection(sphere, line, intersection_point1, intersection_point2); } /** Get the intersection circle between a sphere and a plane. @param sphere the sphere @param plane the plane @param intersection_circle the intersection circle @return bool, true if an intersection can be calculated, otherwise false */ template bool GetIntersection(const TSphere3& sphere, const TPlane3& plane, TCircle3& intersection_circle) throw() { T distance = GetDistance(sphere.p, plane); if (Maths::isGreater(distance, sphere.radius)) { return false; } TVector3 Vector3(plane.n); Vector3.normalize(); if (Maths::isEqual(distance, sphere.radius)) { intersection_circle.set(sphere.p + sphere.radius * Vector3, plane.n, 0); } else { intersection_circle.set (sphere.p + distance * Vector3, plane.n, sqrt(sphere.radius * sphere.radius - distance * distance)); } return true; } /** Get the intersection circle between a plane and a sphere. @param plane the plane @param sphere the sphere @param intersection_circle the intersection circle @return bool, true if an intersection can be calculated, otherwise false */ template BALL_INLINE bool GetIntersection(const TPlane3& plane, const TSphere3& sphere, TCircle3& intersection_circle) throw() { return GetIntersection(sphere, plane, intersection_circle); } /** Get the intersection circle between two spheres. This methods returns false, if the two spheres are identical, since then no intersection circle exists. @param a the first sphere @param b the second sphere @param intersection_circle the intersection circle @return bool, true if an intersection can be calculated, otherwise false */ template bool GetIntersection(const TSphere3& a, const TSphere3& b, TCircle3& intersection_circle) throw() { TVector3 norm = b.p - a.p; T square_dist = norm * norm; if (Maths::isZero(square_dist)) { return false; } T dist = sqrt(square_dist); if (Maths::isLess(a.radius + b.radius, dist)) { return false; } if (Maths::isGreaterOrEqual(Maths::abs(a.radius - b.radius), dist)) { return false; } T radius1_square = a.radius * a.radius; T radius2_square = b.radius * b.radius; T u = radius1_square - radius2_square + square_dist; T length = u / (2 * square_dist); T square_radius = radius1_square - u * length / 2; if (square_radius < 0) { return false; } intersection_circle.p = a.p + (norm * length); intersection_circle.radius = sqrt(square_radius); intersection_circle.n = norm / dist; return true; } /** Get the intersection points between three spheres. @param s1 the first sphere @param s2 the second sphere @param s3 the third sphere @param p1 the first intersection point @param p2 the second intersection point @param test @return bool, true if an intersection can be calculated, otherwise false */ template bool GetIntersection(const TSphere3& s1, const TSphere3& s2, const TSphere3& s3, TVector3& p1, TVector3& p2, bool test = true) throw() { T r1_square = s1.radius*s1.radius; T r2_square = s2.radius*s2.radius; T r3_square = s3.radius*s3.radius; T p1_square_length = s1.p*s1.p; T p2_square_length = s2.p*s2.p; T p3_square_length = s3.p*s3.p; T u = (r2_square-r1_square-p2_square_length+p1_square_length)/2; T v = (r3_square-r1_square-p3_square_length+p1_square_length)/2; TPlane3 plane1; TPlane3 plane2; try { plane1 = TPlane3(s2.p.x-s1.p.x,s2.p.y-s1.p.y,s2.p.z-s1.p.z,u); plane2 = TPlane3(s3.p.x-s1.p.x,s3.p.y-s1.p.y,s3.p.z-s1.p.z,v); } catch (Exception::DivisionByZero) { return false; } TLine3 line; if (GetIntersection(plane1,plane2,line)) { TVector3 diff(s1.p-line.p); T x1, x2; if (SolveQuadraticEquation(line.d*line.d, -diff*line.d*2, diff*diff-r1_square, x1,x2) > 0) { p1 = line.p+x1*line.d; p2 = line.p+x2*line.d; if (test) { TVector3 test = s1.p-p1; if (Maths::isNotEqual(test*test,r1_square)) { return false; } test = s1.p-p2; if (Maths::isNotEqual(test*test,r1_square)) { return false; } test = s2.p-p1; if (Maths::isNotEqual(test*test,r2_square)) { return false; } test = s2.p-p2; if (Maths::isNotEqual(test*test,r2_square)) { return false; } test = s3.p-p1; if (Maths::isNotEqual(test*test,r3_square)) { return false; } test = s3.p-p2; if (Maths::isNotEqual(test*test,r3_square)) { return false; } } return true; } } return false; } /** Test whether two vector3 are collinear @param a the first vector3 @param b the second vector3 @return bool, true or false */ template BALL_INLINE bool isCollinear(const TVector3& a, const TVector3& b) throw() { return (a % b).isZero(); } /** Test whether three vector3 are complanar @param a the first vector3 @param b the second vector3 @param c the third vector3 @return bool, true or false */ template BALL_INLINE bool isComplanar(const TVector3& a, const TVector3& b, const TVector3& c) throw() { return Maths::isZero(TVector3::getTripleProduct(a, b, c)); } /** Test whether four vector3 are complanar @param a the first vector3 @param b the second vector3 @param c the third vector3 @param d the fourth vector3 @return bool, true or false */ template BALL_INLINE bool isComplanar(const TVector3& a, const TVector3& b, const TVector3& c, const TVector3& d) throw() { return isComplanar(a - b, a - c, a - d); } /** Test whether two vector3 are orthogonal @param a the first vector3 @param b the second vector3 @return bool, true or false */ template BALL_INLINE bool isOrthogonal(const TVector3& a, const TVector3& b) throw() { return Maths::isZero(a * b); } /** Test whether a vector3 and a line are orthogonal @param vector the vector @param line the line @return bool, true or false */ template BALL_INLINE bool isOrthogonal(const TVector3& vector, const TLine3& line) throw() { return Maths::isZero(vector * line.d); } /** Test whether a line and a vector3 are orthogonal @param line the line @param vector the vector @return bool, true or false */ template BALL_INLINE bool isOrthogonal(const TLine3& line, const TVector3& vector) throw() { return isOrthogonal(vector, line); } /** Test whether two lines are orthogonal. @param a the first line @param b the second line @return bool, true or false */ template BALL_INLINE bool isOrthogonal(const TLine3& a, const TLine3& b) throw() { return Maths::isZero(a.d * b.d); } /** Test whether a vector3 and a plane are orthogonal. @param vector the vector3 @param plane the plane @return bool, true or false */ template BALL_INLINE bool isOrthogonal(const TVector3& vector, const TPlane3& plane) throw() { return isCollinear(vector, plane.n); } /** Test whether a plane and a vector3 are orthogonal. @param plane the plane @param vector the vector3 @return bool, true or false */ template BALL_INLINE bool isOrthogonal(const TPlane3& plane, const TVector3& vector) throw() { return isOrthogonal(vector, plane); } /** Test whether two planes are orthogonal. @param a the first plane @param b the second plane @return bool, true or false */ template BALL_INLINE bool isOrthogonal(const TPlane3& a, const TPlane3& b) throw() { return Maths::isZero(a.n * b.n); } /** Test whether a line is intersecting a point. @param point the point @param line the line @return bool, true or false */ template BALL_INLINE bool isIntersecting(const TVector3& point, const TLine3& line) throw() { return Maths::isZero(GetDistance(point, line)); } /** Test whether a line is intersecting a point. @param line the line @param point the point @return bool, true or false */ template BALL_INLINE bool isIntersecting(const TLine3& line, const TVector3& point) throw() { return isIntersecting(point, line); } /** Test whether two lines are intersecting. @param a the first line @param b the second line @return bool, true or false */ template BALL_INLINE bool isIntersecting(const TLine3& a, const TLine3& b) throw() { return Maths::isZero(GetDistance(a, b)); } /** Test whether a point lies in a plane. @param point the point @param plane the plane @return bool, true or false */ template BALL_INLINE bool isIntersecting(const TVector3& point, const TPlane3& plane) throw() { return Maths::isZero(GetDistance(point, plane)); } /** Test whether a point lies in a plane. @param plane the plane @param point the point @return bool, true or false */ template BALL_INLINE bool isIntersecting(const TPlane3& plane, const TVector3& point) throw() { return isIntersecting(point, plane); } /** Test whether a line is intersecting a plane. @param line the line @param plane the plane @return bool, true or false */ template BALL_INLINE bool isIntersecting(const TLine3& line, const TPlane3& plane) throw() { return Maths::isZero(GetDistance(line, plane)); } /** Test whether a plane is intersecting a line. @param plane the plane @param line the line @return bool, true or false */ template BALL_INLINE bool isIntersecting(const TPlane3& plane, const TLine3& line) throw() { return isIntersecting(line, plane); } /** Test whether two planes are intersecting. @param a the first plane @param b the second plane @return bool, true or false */ template BALL_INLINE bool isIntersecting(const TPlane3& a, const TPlane3& b) throw() { return Maths::isZero(GetDistance(a, b)); } /** Test whether a line and a plane are parallel. @param line the line @param plane the plane @return bool, true or false */ template BALL_INLINE bool isParallel(const TLine3& line, const TPlane3& plane) throw() { return isOrthogonal(line.d, plane.n); } /** Test whether a plane and a line are parallel. @param plane the plane @param line the line @return bool, true or false */ template BALL_INLINE bool isParallel(const TPlane3& plane, const TLine3& line) throw() { return isParallel(line, plane); } /** Test whether two planes are parallel. @param a the first plane @param b the second plane @return bool, true or false */ template BALL_INLINE bool isParallel(const TPlane3& a, const TPlane3& b) throw() { return isCollinear(a.n, b.n); } /** Return the oriented angle of two vectors with a normal vector. */ template TAngle getOrientedAngle (const T& ax, const T& ay, const T& az, const T& bx, const T& by, const T& bz, const T& nx, const T& ny, const T& nz) throw(Exception::DivisionByZero) { // Calculate the length of the two normals T bl = (T) sqrt((double)ax * ax + ay * ay + az * az); T el = (T) sqrt((double)bx * bx + by * by + bz * bz); T bel = (T) (ax * bx + ay * by + az * bz); // if one or both planes are degenerated if (bl * el == 0) { throw Exception::DivisionByZero(__FILE__, __LINE__); } bel /= (bl * el); if (bel > 1.0) { bel = 1; } else if (bel < -1.0) { bel = -1; } T acosbel = (T) acos(bel); // >= 0 if (( nx * (az * by - ay * bz) + ny * (ax * bz - az * bx) + nz * (ay * bx - ax * by)) > 0) { acosbel = Constants::PI+Constants::PI-acosbel; } return TAngle(acosbel); } /** Return the oriented angle of two vectors with a normal vector. */ template BALL_INLINE TAnglegetOrientedAngle(const TVector3& a, const TVector3& b, const TVector3& normal) throw(Exception::DivisionByZero) { return getOrientedAngle(a.x, a.y, a.z, b.x, b.y, b.z, normal.x, normal.y, normal.z); } /** Return the torsion angle of four points to each other. @param ax 1. vector x component @param ay 1. vector y component @param az 1. vector z component @param bx 2. vector x component @param by 2. vector y component @param bz 2. vector z component @param cx 3. vector x component @param cy 3. vector y component @param cz 3. vector z component @param dx 4. vector x component @param dy 4. vector y component @param dz 4. vector z component @return TAngle the torsion angle */ template TAngle getTorsionAngle (const T& ax, const T& ay, const T& az, const T& bx, const T& by, const T& bz, const T& cx, const T& cy, const T& cz, const T& dx, const T& dy, const T& dz) throw(Exception::DivisionByZero) { T abx = ax - bx; T aby = ay - by; T abz = az - bz; T cbx = cx - bx; T cby = cy - by; T cbz = cz - bz; T cdx = cx - dx; T cdy = cy - dy; T cdz = cz - dz; // Calculate the normals to the two planes n1 and n2 // this is given as the cross products: // AB x BC // --------- = n1 // |AB x BC| // // BC x CD // --------- = n2 // |BC x CD| // Normal to plane 1 T ndax = aby * cbz - abz * cby; T nday = abz * cbx - abx * cbz; T ndaz = abx * cby - aby * cbx; // Normal to plane 2 T neax = cbz * cdy - cby * cdz; T neay = cbx * cdz - cbz * cdx; T neaz = cby * cdx - cbx * cdy; // Calculate the length of the two normals T bl = (T) sqrt((double)ndax * ndax + nday * nday + ndaz * ndaz); T el = (T) sqrt((double)neax * neax + neay * neay + neaz * neaz); T bel = (T) (ndax * neax + nday * neay + ndaz * neaz); // if one or both planes are degenerated if (bl * el == 0) { throw Exception::DivisionByZero(__FILE__, __LINE__); } bel /= (bl * el); if (bel > 1.0) { bel = 1; } else if (bel < -1.0) { bel = -1; } T acosbel = (T) acos(bel); if ((cbx * (ndaz * neay - nday * neaz) + cby * (ndax * neaz - ndaz * neax) + cbz * (nday * neax - ndax * neay)) < 0) { acosbel = -acosbel; } acosbel = (acosbel > 0.0) ? Constants::PI - acosbel : -(Constants::PI + acosbel); return TAngle(acosbel); } //@} } // namespace BALL #endif // BALL_MATHS_ANALYTICALGEOMETRY_H ugene-1.9.8/src/plugins_3rdparty/ball/src/include/BALL/CONFIG/0000755000175000017500000000000011651544310022215 5ustar ilyailyaugene-1.9.8/src/plugins_3rdparty/ball/src/include/BALL/CONFIG/config.h0000644000175000017500000001723211651544325023646 0ustar ilyailya// -*- Mode: C++; tab-width: 2; -*- // vi: set ts=2: // /* config.h. Generated by configure. */ // $Id: config.h,v 1.12.16.1 2007-03-25 22:03:12 oliver Exp $ #ifndef BALL_CONFIG_CONFIG_H #define BALL_CONFIG_CONFIG_H #include // here are some global configuration flags for BALL // the path to the directory where BALL is installed //#define BALL_PATH "C:\\BALL\\" // this flag is used by GenericPDBFile // if it is not set, the length of each line has // to be meet the PDB spcifications exactly. // As virtually no existing PDB file fulfills // this requirement, we disencourage its usage. // Nevertheless, it can be quite useful for debugging. /* #undef BALL_STRICT_PDB_LINE_IMPORT */ // BALL_DEBUG enables some debugging methods // change the DEBUG entry in configure to define this flag. // If in debug mode, inline functions won't be compiled // as inline by defining BALL_NO_INLINE_FUNCTIONS // This facilitates debugging, as the debugger can always // find the corresponding source code line. // See also COMMON/debug.h for these symbols. // #define BALL_DEBUG // #define BALL_NO_INLINE_FUNCTIONS // this define is used to determine // wheter BALL shall try to close a socket conection // via shutdown or close // (see socket.C) //#define BALL_USE_SOCKET_SHUTDOWN // this idefine is used in string.C and enables a workaround // on on of these ppor systems that do not define vsnprintf /* #undef BALL_HAVE_VSNPRINTF */ // these two flags are set by configure according to // the OS and compiler found. HAS_BOOL_TYPE and // _CC_BOOL_DEF_ are required for compatibility // reasons with QT. // the string describing the binary format //#define BALL_BINFMT "Windows-i386-VC++_7" // used in COMMON/namespace.h to cause the inclusion of COMMON/memory.h /* #undef BALL_LOG_MEMORY */ //#define BALL_LOG_MEMORY_FILE "memory.log" // define architecture /* #undef BALL_ARCH_SPARC */ /* #undef BALL_ARCH_MIPS */ //#define BALL_ARCH_I386 I386 /* #undef BALL_ARCH_ALPHA */ //define OS /* #undef BALL_OS_LINUX */ /* #undef BALL_OS_SOLARIS */ /* #undef BALL_OS_SUNOS */ /* #undef BALL_OS_IRIX */ /* #undef BALL_OS_IRIX32 */ /* #undef BALL_OS_IRIX64 */ /* #undef BALL_OS_FREEBSD */ //#define BALL_OS_WINDOWS // define if gethostname is supported //#define BALL_HAVE_GETHOSTNAME 1 // define if sysinfo(SI_HOSTNAME,) has to be used instead of // gethostname (older Solaris variants) /* #undef BALL_HAVE_SYSINFO */ // define if gethostname is not in the unistd.h header /* #undef BALL_DEFINE_GETHOSTNAME */ // Define if you have the inet_aton function. // Note: inet_aton is a marginally improved version of inet_addr // If configure finds inet_aton, HAVE_INET_ATON is set and used // in SYSTEM/socket.C. //#define HAVE_INET_ATON // Define the type needed for getsockname, getpeername, and accept // This type is probably one of socklen_t, size_t, or int // Refer to /usr/include/sys/socket.h in case of doubt //#define BALL_SOCKLEN_TYPE int // define some symbols for the (bit)size of some builtin types //#define BALL_INT_SIZE 4 //#define BALL_CHAR_SIZE 1 //#define BALL_LONG_SIZE 4 //#define BALL_SIZE_T_SIZE 4 //#define BALL_POINTER_SIZE 8 // define symbols for the endianness of the system //#define BALL_LITTLE_ENDIAN true /* #undef BALL_BIG_ENDIAN */ // on some systems (e.g. Solaris) we need to include /usr/include/ieeefp.h // for some floating point functions /* #undef BALL_HAS_IEEEFP_H */ // on some systems (e.g. Solaris) we need to include /usr/include/values.h // for some floating point functions // #undef BALL_HAS_VALUES_H // the signature of the function arguments used in xdrrec_create differs // from platform to platform, so we define some symbols describing the // correct arguments: (void*, char*, int), (char*, char*, int), or (void) // take arguments of type (void*, char*, int) /* #undef BALL_XDRREC_CREATE_VOID_CHAR_INT */ //#define BALL_XDRREC_CREATE_CHAR_CHAR_INT 1 /* #undef BALL_XDRREC_CREATE_VOID */ // some platforms (e.g. Debian 2.1) do not provide xdr_u_hyper, so we // need a workaround for this // #undef BALL_HAS_XDR_U_HYPER 1 // on some systems, we do not have regex.h, so we have to use regexp.h /* #undef BALL_HAS_REGEXP_H */ //#define BALL_HAS_REGEX_H // Define to `int' if doesn't define. /* #undef pid_t */ // Define to `unsigned' if doesn't define. /* #undef size_t */ // Define if you have the ANSI C header files. #define STDC_HEADERS 1 // Define if numeric_limits is defined in //#define BALL_HAS_NUMERIC_LIMITS 1 // Define whether float.h has to be included along with limits.h /* #undef BALL_HAS_FLOAT_H */ // Define the argument type for xdr_u_hyper (64 bit) //#define BALL_XDR_UINT64_TYPE unsigned __int64 // Define on 64 bit architectures to avoid the use of long long // which is required on 32 bit machines for comatibility /* #undef BALL_64BIT_ARCHITECTURE */ // Define an unsigned numeric type of 64 bit length (used for // platform independent persistence: stores pointers) // this usually defaults to unsigned long on 64 bit architectures // and unsigned long long on 32 bit machines #define BALL_ULONG64_TYPE unsigned long long #define BALL_LONG64_TYPE long long // Defines an unsigned type that has the same length as size_t #define BALL_SIZE_TYPE unsigned long // Defines a signed type that has the same length as size_t #define BALL_INDEX_TYPE long // Defines an unsigned integer type of the same size as void* #define BALL_POINTERSIZEINT_TYPE long #define BALL_POINTERSIZEUINT_TYPE unsigned long // Define the template argument for friends of template classes: // either "" or "<>" #define BALL_NULL_TEMPLATE_ARGS <> // Define whether the compiler provides an ANSI-compliant implementation // of . This is required in COMMON/socket.h/C since we need // the correct initialisation of the base classes. These base classes are // either something like std::basic_ios etc., or ios, istream etc. #define BALL_HAS_ANSI_IOSTREAM 1 // Define the precision for the BALL Complex type (has to be consistent // with the FFTW precision, if included). //#define BALL_COMPLEX_PRECISION float //#define BALL_HAS_FFTW //#define BALL_HAS_FFTW_FLOAT //#define BALL_FFTW_DEFAULT_TRAITS FloatTraits // Define whether to use the ARM style or ANSI style access modifications // ARM style: BaseClass::foo; // ANSI style: using BaseClass::foo; #define BALL_CFG_USING_METHOD_DIRECTIVE 1 // Define for activated PYTHON support //#define BALL_PYTHON_SUPPORT // Maximum line length for reading from files (see source/FORMAT) #define BALL_MAX_LINE_LENGTH 65535 // #undef BALL_HAS_UNISTD_H //#define BALL_HAS_PROCESS_H // #undef BALL_HAS_KILL // #undef BALL_HAS_SYS_TIME_H #define BALL_HAS_TIME_H // #undef BALL_HAS_SYSCONF // #undef BALL_HAS_SYS_PARAM_H // #undef BALL_HAS_DIRENT_H #define BALL_HAS_DIRECT_H // #undef BALL_HAS_PWD_H #define BALL_HAS_FLOAT_H // #undef BALL_HAS_SYS_SOCKET_H // #undef BALL_HAS_NETINET_IN_H // #undef BALL_HAS_NETDB_H // #undef BALL_HAS_ARPA_INET_H #define BALL_HAS_SSTREAM #ifdef Q_CC_MSVC #define BALL_COMPILER_MSVC #endif // Q_CC_MSVC #ifdef Q_OS_WINDOWS #define BALL_PLATFORM_WINDOWS //#define BALL_HAS_CLOCKS_PER_SEC //#define BALL_HAS_WINDOWS_PERFORMANCE_COUNTER //#define BALL_USE_WINSOCK //#define mode_t int //#define BALL_MUST_CAST_TEMPLATE_FUNCTION_ARGS #define NOMINMAX #define _USE_MATH_DEFINES #endif // Q_OS_WINDOWS // MS VC++ doesn't define all required symbols in // math.h if this symbol isn't defined *before* including // math.h for the first time! // Keep Windows from defining min/max, ERROR,... as preprocesor symbols! // May he how thought of defining these by default rot in hell! //#define NOMINMAX //#define NOGDI //#define NOWINRES //#define WINDOWS_LEAN_AND_MEAN //#define BALL_USE_GLEW #endif // BALL_CONFIG_CONFIG_H ugene-1.9.8/src/plugins_3rdparty/ball/src/source/0000755000175000017500000000000011651544310020413 5ustar ilyailyaugene-1.9.8/src/plugins_3rdparty/ball/src/source/COMMON/0000755000175000017500000000000011651544310021403 5ustar ilyailyaugene-1.9.8/src/plugins_3rdparty/ball/src/source/COMMON/logStream.cpp0000644000175000017500000002751611651544326024066 0ustar ilyailya// -*- Mode: C++; tab-width: 2; -*- // vi: set ts=2: // // $Id: logStream.C,v 1.42.18.1 2007-03-25 22:00:03 oliver Exp $ // #include #include #include #include #include #define BUFFER_LENGTH 32768 #ifdef BALL_HAS_ANSI_IOSTREAM # define BALL_IOS std::basic_ios # define BALL_OSTREAM std::ostream #else # define BALL_IOS std::ios # define BALL_OSTREAM std::ostream #endif namespace BALL { // at this point, it is not yet possible to // include BALL/COMMON/limits.h (which were a // much nicer solution...). Ugly header dependencies... const int LogStreamBuf::MIN_LEVEL = INT_MIN; const int LogStreamBuf::MAX_LEVEL = INT_MAX; const Time LogStreamBuf::MAX_TIME = INT_MAX; LogStreamBuf::LogStreamBuf() : std::streambuf(), pbuf_(0), loglines_(), level_(0), tmp_level_(0), stream_list_(), incomplete_line_() { pbuf_ = new char [BUFFER_LENGTH]; std::streambuf::setp(pbuf_, pbuf_ + BUFFER_LENGTH - 1); } LogStreamBuf::~LogStreamBuf() { sync(); delete [] pbuf_; } void LogStreamBuf::dump(std::ostream& stream) { char buf[BUFFER_LENGTH]; Size line; for (line = (Size)loglines_.size(); line > 0; --line) { strftime(&(buf[0]), BUFFER_LENGTH - 1, "%d.%m.%Y %H:%M:%S ", localtime(&(loglines_[line - 1].time))); stream << buf << "[" << loglines_[line - 1].level << "]:" << loglines_[line - 1].text.c_str() << std::endl; } } int LogStreamBuf::sync() { static char buf[BUFFER_LENGTH]; // sync our streambuffer... if (pptr() != pbase()) { char* line_start = pbase(); char* line_end = pbase(); while (line_end <= pptr()) { // search for the first end of line for (; line_end < pptr() && *line_end != '\n'; line_end++); if (line_end >= pptr()) { // Copy the incomplete line to the incomplete_line_ buffer size_t length = line_end - line_start + 1; length = std::max(length, (size_t)(BUFFER_LENGTH - 1)); strncpy(&(buf[0]), line_start, length); buf[line_end - line_start] = '\0'; incomplete_line_ += &(buf[0]); // mark everything as read line_end = pptr() + 1; } else { memcpy(&(buf[0]), line_start, line_end - line_start + 1); buf[line_end - line_start] = '\0'; // assemble the string to be written // (consider leftovers of the last buffer from incomplete_line_) string outstring = incomplete_line_; incomplete_line_ = ""; outstring += &(buf[0]); // if there are any streams in our list, we // copy the line into that streams, too and flush them std::list::iterator list_it = stream_list_.begin(); for (; list_it != stream_list_.end(); ++list_it) { // if the stream is open for that level, write to it... if ((list_it->min_level <= tmp_level_) && (list_it->max_level >= tmp_level_)) { *(list_it->stream) << expandPrefix_(list_it->prefix, tmp_level_, time(0)).c_str() << outstring.c_str() << std::endl; if (list_it->target != 0) { list_it->target->logNotify(); } } } // update the line pointers (increment both) line_start = ++line_end; // remove cr/lf from the end of the line while (outstring.size() && (outstring[outstring.size() - 1] == 10 || outstring[outstring.size() - 1] == 13)) { std::string::iterator p = outstring.end(); p--; outstring.erase(p); } // store the line Logline logline; logline.text = outstring; logline.level = tmp_level_; logline.time = time(0); // store the new line loglines_.push_back(logline); // reset tmp_level_ to the previous level // (needed for LogStream::level() only) tmp_level_ = level_; } } // remove all processed lines from the buffer pbump((int)(pbase() - pptr())); } return 0; } string LogStreamBuf::expandPrefix_ (const string& prefix, int level, Time time) const { string::size_type index = 0; Size copied_index = 0; string result(""); while ((index = prefix.find("%", index)) != string::npos) { // append any constant parts of the string to the result if (copied_index < index) { result.append(prefix.substr(copied_index, index - copied_index)); copied_index = (Index)index; } if (index < prefix.size()) { char buffer[64]; char* buf = &(buffer[0]); switch (prefix[index + 1]) { case '%': // append a '%' (escape sequence) result.append("%"); break; case 'l': // append the loglevel sprintf(buf, "%d", level); result.append(buf); break; case 'y': // append the message type (error/warning/information) if (level >= LogStream::ERROR_LEVEL) { result.append("ERROR"); } else { if (level >= LogStream::WARNING_LEVEL) { result.append("WARNING"); } else { if (level >= LogStream::INFORMATION_LEVEL) { result.append("INFORMATION"); } else { result.append("LOG"); } } } break; case 'T': // time: HH:MM:SS strftime(buf, BUFFER_LENGTH - 1, "%H:%M:%S", localtime(&time)); result.append(buf); break; case 't': // time: HH:MM strftime(buf, BUFFER_LENGTH - 1, "%H:%M", localtime(&time)); result.append(buf); break; case 'D': // date: DD.MM.YYYY strftime(buf, BUFFER_LENGTH - 1, "%d.%m.%Y", localtime(&time)); result.append(buf); break; case 'd': // date: DD.MM. strftime(buf, BUFFER_LENGTH - 1, "%d.%m.", localtime(&time)); result.append(buf); break; case 'S': // time+date: DD.MM.YYYY, HH:MM:SS strftime(buf, BUFFER_LENGTH - 1, "%d.%m.%Y, %H:%M:%S", localtime(&time)); result.append(buf); break; case 's': // time+date: DD.MM., HH:MM strftime(buf, BUFFER_LENGTH - 1, "%d.%m., %H:%M", localtime(&time)); result.append(buf); break; default: break; } index += 2; copied_index += 2; } } if (copied_index < prefix.size()) { result.append(prefix.substr(copied_index, prefix.size() - copied_index)); } return result; } LogStreamNotifier::LogStreamNotifier() : registered_at_(0) { } LogStreamNotifier::~LogStreamNotifier() { unregister(); } void LogStreamNotifier::logNotify() { } void LogStreamNotifier::unregister() { if (registered_at_ == 0) return; registered_at_->remove(stream_); registered_at_ = 0; } void LogStreamNotifier::registerAt(LogStream& log, int min_level, int max_level) { unregister(); registered_at_ = &log; log.insertNotification(stream_, *this, min_level, max_level); } // keep the given buffer LogStream::LogStream(LogStreamBuf* buf, bool delete_buf, bool associate_stdio) : BALL_IOS(buf), BALL_OSTREAM(buf), delete_buffer_(delete_buf), disable_output_(false) { if (associate_stdio) { // associate cout to informations and warnings, // cerr to errors by default insert(std::cout, INFORMATION_LEVEL, ERROR_LEVEL - 1); insert(std::cerr, ERROR_LEVEL); } } LogStream::~LogStream() { if (delete_buffer_) { // remove the streambuffer delete rdbuf(); } } void LogStream::clear() { rdbuf()->loglines_.clear(); } void LogStream::insert(std::ostream& stream, int min_level, int max_level) { if (!bound_() || hasStream_(stream)) { return; } // we didn`t find it - create a new entry in the list LogStreamBuf::StreamStruct s_struct; s_struct.min_level = min_level; s_struct.max_level = max_level; s_struct.stream = &stream; rdbuf()->stream_list_.push_back(s_struct); } void LogStream::remove(std::ostream& stream) { if (!bound_()) return; StreamIterator it = findStream_(stream); if (it != rdbuf()->stream_list_.end()) { rdbuf()->stream_list_.erase(it); } } void LogStream::insertNotification(std::ostream& s, LogStreamNotifier& target, int min_level, int max_level) { if (!bound_()) return; insert(s, min_level, max_level); StreamIterator it = findStream_(s); (*it).target = ⌖ } LogStream::StreamIterator LogStream::findStream_(const std::ostream& s) { StreamIterator list_it = rdbuf()->stream_list_.begin(); for (; list_it != rdbuf()->stream_list_.end(); ++list_it) { if (list_it->stream == &s) { return list_it; } } return list_it; } bool LogStream::hasStream_(std::ostream& stream) { if (!bound_()) return false; return findStream_(stream) != rdbuf()->stream_list_.end(); } void LogStream::setMinLevel(const std::ostream& stream, int level) { if (!bound_()) return; StreamIterator it = findStream_(stream); if (it != rdbuf()->stream_list_.end()) { (*it).min_level = level; } } void LogStream::setMaxLevel(const std::ostream& stream, int level) { if (!bound_()) return; StreamIterator it = findStream_(stream); if (it != rdbuf()->stream_list_.end()) { (*it).max_level = level; } } void LogStream::setPrefix(const std::ostream& s, const string& prefix) { if (!bound_()) return; StreamIterator it = findStream_(s); if (it != rdbuf()->stream_list_.end()) { (*it).prefix = prefix; } } Size LogStream::getNumberOfLines(int min_level, int max_level) const { if (!bound_()) return 0; // iterate over all loglines and count the lines of interest LogStream* non_const_this = const_cast(this); vector::iterator it = non_const_this->rdbuf()->loglines_.begin(); Size count = 0; for (; it != non_const_this->rdbuf()->loglines_.end(); ++it) { if ((*it).level >= min_level && (*it).level <= max_level) { count++; } } return count; } string LogStream::getLineText(const Index& index) const { if ((signed)getNumberOfLines() < index) { return ""; } if (!bound_()) return ""; return const_cast(this)->rdbuf()->loglines_[index].text; } int LogStream::getLineLevel(const Index& index) const { if ((signed)getNumberOfLines() < index) { return -1; } if (!bound_()) return -1; return const_cast(this)->rdbuf()->loglines_[index].level; } time_t LogStream::getLineTime(const Index& index) const { if ((signed)getNumberOfLines() < index) { return 0; } if (!bound_()) return 0; return const_cast(this)->rdbuf()->loglines_[index].time; } std::list LogStream::filterLines (int min_level, int max_level, Time earliest, Time latest, const string& s) const { std::list list_indices; Position pos = 0; LogStreamBuf* log = const_cast(this)->rdbuf(); while (pos < log->loglines_.size() && log->loglines_[pos].time < earliest) { pos++; } while (pos < log->loglines_.size() && log->loglines_[pos].time <= latest) { if (log->loglines_[pos].level >= min_level && log->loglines_[pos].level <= max_level) { if (s.length() > 0) { if (log->loglines_[pos].text.find(s, 0) != string::npos) { list_indices.push_back((int)pos); } } else { list_indices.push_back((int)pos); } } pos++; } return list_indices; } void LogStream::disableOutput() throw() { disable_output_ = true; } void LogStream::enableOutput() throw() { disable_output_ = false; std::ostream::flush(); } bool LogStream::outputEnabled() const throw() { return disable_output_; } void LogStream::flush() throw() { if (disable_output_) return; std::ostream::flush(); } bool LogStream::bound_() const { LogStream* non_const_this = const_cast(this); return (non_const_this->rdbuf() != 0); } // global default logstream BALL_EXPORT LogStream Log(new LogStreamBuf, true, true); # ifdef BALL_NO_INLINE_FUNCTIONS # include # endif } // namespace BALL ugene-1.9.8/src/plugins_3rdparty/ball/src/source/COMMON/constants.cpp0000644000175000017500000000555511651544326024144 0ustar ilyailya// -*- Mode: C++; tab-width: 2; -*- // vi: set ts=2: // // $Id: constants.C,v 1.6 2002-02-27 12:20:33 sturm Exp $ #include namespace BALL { namespace Constants { // EPSILON (used fr comparisons) double EPSILON = 1e-6; // PI const double PI = 3.14159265358979323846L; // Euler's number - base of the natural logarithm const double E = 2.718281828459045235L; // Elementary charge. const double ELEMENTARY_CHARGE = 1.60217738E-19L; // C /// Elementary charge (alias) const double e0 = ELEMENTARY_CHARGE; // Electron mass. const double ELECTRON_MASS = 9.1093897E-31L; // kg // Proton mass. const double PROTON_MASS = 1.6726230E-27L; // kg // Neutron mass. const double NEUTRON_MASS = 1.6749286E-27L; // kg // Avogadro constant. const double AVOGADRO = 6.0221367E+23L; // 1 / mol // Avogadro constant (alias) const double NA = AVOGADRO; // Avogadro constant (alias) const double MOL = AVOGADRO; // Boltzmann constant. const double BOLTZMANN = 1.380657E-23L; // J / K // Boltzmann constant (alias) const double k = BOLTZMANN; // Planck constant. const double PLANCK = 6.6260754E-34L; // J * sec // Planck constant (alias) const double h = PLANCK; // Gas constant (= NA * k) const double GAS_CONSTANT = NA * k; // Gas constant (alias) const double R = GAS_CONSTANT; // Faraday constant (= NA * e0) const double FARADAY = NA * e0; // Faraday constant (alias) const double F = FARADAY; // Bohr radius. const double BOHR_RADIUS = 5.29177249E-11L; // m // Bohr radius (alias) const double a0 = BOHR_RADIUS; // the following values from: // P.W.Atkins: Physical Chemistry, 5th ed., Oxford University Press, 1995 // Vacuum permittivity. const double VACUUM_PERMITTIVITY = 8.85419E-12L; // C^2 / (J * m) // Vacuum permeability. const double VACUUM_PERMEABILITY = (4 * PI * 1E-7L); // J s^2 / (C^2 * m) // Speed of light. const double SPEED_OF_LIGHT = 2.99792458E+8L; // m / s // Speed of Light (alias) const double c = SPEED_OF_LIGHT; // Gravitational constant. const double GRAVITATIONAL_CONSTANT = 6.67259E-11L; // N m^2 / kg^2 // Fine structure constant. const double FINE_STRUCTURE_CONSTANT = 7.29735E-3L; // 1 // Degree per rad. const double DEG_PER_RAD = 57.2957795130823209L; // Rad per degree. const double RAD_PER_DEG = 0.0174532925199432957L; // mm per inch. const double MM_PER_INCH = 25.4L; // m per foot. const double M_PER_FOOT = 3.048L; // Joule per calorie const double JOULE_PER_CAL = 4.184; // Calories per Joule. const double CAL_PER_JOULE = (1 / 4.184); } } ugene-1.9.8/src/plugins_3rdparty/ball/src/source/COMMON/hash.cpp0000644000175000017500000000776211651544326023055 0ustar ilyailya// -*- Mode: C++; tab-width: 2; -*- // vi: set ts=2: // // $Id: hash.C,v 1.13 2003-08-26 09:17:44 oliver Exp $ // #include namespace BALL { /* Summary: Algorithm to do fast hashing of a pointer * The result of the hash function is a number in the range * [0..(number_of_slots-1)]. */ HashIndex hashPointer(void *const void_ptr) throw() { double d = ((double)((unsigned long)void_ptr)) * 0.6180339887; Index index = (Index)(5832641097.37287 * (d - (double)((unsigned long)d))); return ((index < 0) ? -index : index); } /* Summary: Algorithm to do fast hashing of variable length text * strings. The result of the hash function is a number in the range * [0..255]. This algorithm was published by P. K. Pearson, * Comm. ACM, 33:6(1990), 677 */ HashIndex hashString(const char *s) throw() { if (s == 0) { return (HashIndex)0; } static const unsigned char pseudo_random_permuted_key[256] = { 1 ,87 ,49 ,12 ,176,178,102,166,121,193,6 ,84 ,249,230,44 ,163, 14 ,197,213,181,161,85 ,218,80 ,64 ,239,24 ,226,236,142,38 ,200, 110,177,104,103,141,253,255,50 ,77 ,101,81 ,18 ,45 ,96 ,31 ,222, 25 ,107,190,70 ,86 ,237,240,34 ,72 ,242,20 ,214,244,227,149,235, 97 ,234,57 ,22 ,60 ,250,82 ,175,208,5 ,127,199,111,62 ,135,248, 174,169,211,58 ,66 ,154,106,195,245,171,17 ,187,182,179,0 ,243, 132,56 ,148,75 ,128,133,158,100,130,126,91 ,13 ,153,246,216,219, 119,68 ,223,78 ,83 ,88 ,201,99 ,122,11 ,92 ,32 ,136,114,52 ,10 , 138,30 ,48 ,183,156,35 ,61 ,26 ,143,74 ,251,94 ,129,162,63 ,152, 170,7 ,115,167,241,206,3 ,150,55 ,59 ,151,220,90 ,53 ,23 ,131, 125,173,15 ,238,79 ,95 ,89 ,16 ,105,137,225,224,217,160,37 ,123, 118,73 ,2 ,157,46 ,116,9 ,145,134,228,207,212,202,215,69 ,229, 27 ,188,67 ,124,168,252,42 ,4 ,29 ,108,21 ,247,19 ,205,39 ,203, 233,40 ,186,147,198,192,155,33 ,164,191,98 ,204,165,180,117,76 , 140,36 ,210,172,41 ,54 ,159,8 ,185,232,113,196,231,47 ,146,120, 51 ,65 ,28 ,144,254,221,93 ,189,194,139,112,43 ,71 ,109,184,209 }; unsigned char hash = 0; for(; *s != '\0'; s++) { hash = pseudo_random_permuted_key[hash ^ *s]; } return (HashIndex)hash; } /* Summary: A portable adaptation of Peter Weinberger's (PJW) (AT&T Bell Labs) * generic hashing algorithm based on Allen Holub's version. Accepts a pointer * to a string to be hashed. * Taken from: Dr. Dobb's Journal, April 1996, p.26 */ HashIndex hashPJWString(const char *s) throw() { Index index = 0; Index temp_index; # define BALL_BITS_IN_HASHVALUE_ (sizeof(Index) * CHAR_BIT) # define BALL_THREE_QUARTERS_ ((Index)((BALL_BITS_IN_HASHVALUE_ * 3) / 4)) # define BALL_ONE_EIGHTH_ ((Index)(BALL_BITS_IN_HASHVALUE_ / 8)) # define BALL_HIGH_BITS_ (~((Index)(~0) >> BALL_ONE_EIGHTH_)) for (; *s; s++) { index = (index << BALL_ONE_EIGHTH_) + *s; if ((temp_index = index & BALL_HIGH_BITS_) != 0) { index = (index ^ (temp_index >> BALL_THREE_QUARTERS_)) & ~BALL_HIGH_BITS_; } } # undef BALL_BITS_IN_HASHVALUE_ # undef BALL_THREE_QUARTERS_ # undef BALL_ONE_EIGHTH_ # undef BALL_HIGH_BITS_ return index; } /* Summary: The published hash algorithm used in the UNIX ELF format for * object files. Accepts a pointer to a string to be hashed. * Assumes a long pointer to have 4 bytes of 8 bits. * Taken from: Dr. Dobb's Journal, April 1996, p.26 */ HashIndex hashElfString(const char *s) throw() { unsigned long l = 0; unsigned long temp; while(*s) { l = (l << 4) + *s++; if ((temp = l & 0xF0000000L)) { l ^= temp >> 24; } l &= ~temp; } return (Index)l; } HashIndex getNextPrime(HashIndex l) throw() { if (l <= 3) { return 3; } if ((l & 0x1L) == 0) { l++; } HashIndex sqr = (HashIndex)sqrt((double)l) + 1; HashIndex div = 0; for (;;) { for (div = 3; (div <= sqr) && ((l % div) != 0); div += 2); if (div > sqr) { return l; } l += 2; } } } // namespace BALL ugene-1.9.8/src/plugins_3rdparty/ball/src/source/COMMON/exception.cpp0000644000175000017500000002564611651544326024131 0ustar ilyailya// -*- Mode: C++; tab-width: 2; -*- // vi: set ts=2: // // $Id: exception.C,v 1.39 2005-12-23 17:02:32 amoll Exp $ // #include #include #include #include #include #include #include #include // for getenv in terminate() #include #include // for SIGSEGV and kill #ifdef BALL_HAS_UNISTD_H # include // fot getpid #endif #ifdef BALL_HAS_PROCESS_H # include #endif #define BALL_CORE_DUMP_ENVNAME "BALL_DUMP_CORE" #define DEF_EXCEPTION(a,b) \ a :: a (const char* file, int line) throw()\ : GeneralException(file, line, #a, b)\ {\ }\ using std::string; using std::endl; namespace BALL { namespace Exception { GeneralException::GeneralException() throw() : file_("?"), line_(-1), name_("GeneralException"), message_("unspecified error") { globalHandler.set(file_, line_, String(name_), String(message_)); } GeneralException::GeneralException(const char* file, int line, const String& name, const String& message) throw() : file_(file), line_(line), name_(name), message_(message) { globalHandler.set(file_, line_, name_, message_); } GeneralException::GeneralException(const char* file, int line) throw() : file_(file), line_(line), name_("GeneralException"), message_("unknown error") { globalHandler.set(file_, line_, name_, message_); } GeneralException::GeneralException(const GeneralException& exception) throw() : std::exception(exception), file_(exception.file_), line_(exception.line_), name_(exception.name_), message_(exception.message_) { } GeneralException::~GeneralException() throw() { } const char* GeneralException::getName() const throw() { return name_.c_str(); } const char* GeneralException::getMessage() const throw() { return message_.c_str(); } void GeneralException::setMessage(const std::string& message) throw() { message_ = message; } const char* GeneralException::getFile() const throw() { return file_; } int GeneralException::getLine() const throw() { return line_; } IndexUnderflow::IndexUnderflow(const char* file, int line, Index index, Size size) throw() : GeneralException(file, line, "IndexUnderflow", ""), size_(size), index_(index) { message_ = "the given index was too small: "; char buf[40]; sprintf(buf, "%ld", (long)index); message_ += buf; message_ += " (size = "; sprintf(buf, "%ld", (long)size); message_ += buf; message_ += ")"; globalHandler.setMessage(message_); } IndexOverflow::IndexOverflow(const char* file, int line, Index index, Size size) throw() : GeneralException(file, line, "IndexOverflow", "an index was too large"), size_(size), index_(index) { message_ = "the given index was too large: "; char buf[40]; sprintf(buf, "%ld", (long)index); message_ += buf; message_ += " (size = "; sprintf(buf, "%ld", (long)size); message_ += buf; message_ += ")"; globalHandler.setMessage(message_); } OutOfMemory::OutOfMemory(const char* file, int line, Size size) throw() : GeneralException(file, line, "OutOfMemory", "a memory allocation failed"), size_(size) { message_ = "unable to allocate enough memory (size = "; char buf[40]; sprintf(buf, "%ld", (long)size_); message_ += buf; message_ += " bytes) "; globalHandler.setMessage(message_); } OutOfMemory::~OutOfMemory() throw() { } SizeUnderflow::SizeUnderflow(const char* file, int line, Size size) throw() : GeneralException(file, line, "SizeUnderflow", ""), size_(size) { message_ = "the given size was too small: "; char buf[40]; sprintf(buf, "%ld", (long)size); message_ += buf; globalHandler.setMessage(message_); } InvalidSize::InvalidSize(const char* file, int line, Size size) throw() : GeneralException(file, line, "InvalidSize", ""), size_(size) { message_ = "the given size was not expected: "; char buf[40]; sprintf(buf, "%ld", (long)size); message_ += buf; globalHandler.setMessage(message_); } IllegalPosition::IllegalPosition(const char* file, int line, float x, float y, float z) throw() : GeneralException(file, line, "IllegalPosition:", "") { char buf1[40]; sprintf(buf1, "%f", x); char buf2[40]; sprintf(buf2, "%f", y); char buf3[40]; sprintf(buf3, "%f", z); message_ += "("; message_ += buf1; message_ += ","; message_ += buf2; message_ += ","; message_ += buf3; message_ += ")"; globalHandler.setMessage(message_); } ParseError::ParseError(const char* file, int line, const String& expression, const String& message) throw() : GeneralException(file, line, "Parse Error", "") { message_ += message; message_ += " in "; message_ += expression; globalHandler.setMessage(message_); } Precondition::Precondition(const char* file, int line, const char* condition) throw() : GeneralException(file, line, "Precondition failed", "") { message_ += std::string(condition); globalHandler.setMessage(message_); } Postcondition::Postcondition(const char* file, int line, const char* condition) throw() : GeneralException(file, line, "Postcondition failed", "") { message_ += std::string(condition); globalHandler.setMessage(message_); } FileNotFound::FileNotFound(const char* file, int line, const String& filename) throw() : GeneralException(file, line, "FileNotFound", ""), filename_(filename) { message_ = "the file " + filename + " could not be found"; globalHandler.setMessage(message_); } FileNotFound::~FileNotFound() throw() { } String FileNotFound::getFilename() const throw() { return filename_; } InvalidFormat::InvalidFormat(const char* file, int line, const String& s) throw() : GeneralException(file, line, "InvalidFormat", ""), format_(s) { message_ = "problem converting '"; message_.append(s + "' to a number."); globalHandler.setMessage(message_); } InvalidFormat::~InvalidFormat() throw() { } InvalidOption::InvalidOption(const char* file, int line, String option) throw() : GeneralException(file, line, "Invalid option: ", option) { } TooManyErrors::TooManyErrors(const char* file, int line) throw() : GeneralException(file, line, "Too many errors", "") { } TooManyBonds::TooManyBonds(const char* file, int line, const String& error) throw() : GeneralException(file, line, String("Unable to create additional bond between ") + error, "") { } InvalidRange::InvalidRange(const char* file, int line, float value) throw() : GeneralException(file, line, "The argument was out of range: ", String(value)) { } DEF_EXCEPTION(OutOfRange, "the range of the operation was invalid") DEF_EXCEPTION(DivisionByZero, "a division by zero was requested") DEF_EXCEPTION(NullPointer, "a null pointer was specified") DEF_EXCEPTION(InvalidIterator, "the iterator is invalid - probably it is not bound to a container") DEF_EXCEPTION(IncompatibleIterators, "the iterator could not be assigned because it is bound to a different container") DEF_EXCEPTION(NotImplemented, "this method has not been implemented yet. Feel free to complain about it!") DEF_EXCEPTION(IllegalSelfOperation, "cannot perform operation on the same object") DEF_EXCEPTION(IllegalTreeOperation, "an illegal tree operation was requested") DEF_EXCEPTION(BufferOverflow, "the maximum buffersize has been reached") DEF_EXCEPTION(OutOfGrid, "a point was outside a grid") GlobalExceptionHandler::GlobalExceptionHandler() throw() { //std::set_terminate(terminate); //std::set_unexpected(terminate); //std::set_new_handler(newHandler); } void GlobalExceptionHandler::newHandler() throw(Exception::OutOfMemory) { throw Exception::OutOfMemory(__FILE__, __LINE__); } void GlobalExceptionHandler::terminate() throw() { // add cerr to the log stream // and write all available information on // the exception to the log stream (potentially with an assigned file!) // and cerr Log.insert(std::cerr); Log.error() << endl; Log.error() << "---------------------------------------------------" << endl; Log.error() << "FATAL: uncaught exception!" << endl; Log.error() << "---------------------------------------------------" << endl; if ((line_ != -1) && (name_ != "unknown")) { Log.error() << "last entry in the exception handler: " << endl; Log.error() << "exception of type " << name_.c_str() << " occured in line " << line_ << " of " << file_.c_str() << endl; Log.error() << "error message: " << message_.c_str() << endl; } Log.error() << "---------------------------------------------------" << endl; // if the environment variable declared in BALL_CORE_DUMP_ENVNAME // is set, provoke a core dump (this is helpful to get s stack traceback) if (getenv(BALL_CORE_DUMP_ENVNAME) != 0) { #ifdef BALL_HAS_KILL Log.error() << "dumping core file.... (to avoid this, unset " << BALL_CORE_DUMP_ENVNAME << " in your environment)" << endl; // provoke a core dump kill(getpid(), SIGSEGV); #endif } // otherwise exit cleanly exit(1); } void GlobalExceptionHandler::set (const String& file, int line, const String& name, const String& message) throw() { name_ = name; line_ = line; message_ = message; file_ = file; } void GlobalExceptionHandler::setName(const String& name) throw() { name_ = name; } void GlobalExceptionHandler::setMessage(const String& message) throw() { message_ = message; } void GlobalExceptionHandler::setFile(const String& file) throw() { file_ = file; } void GlobalExceptionHandler::setLine(int line) throw() { line_ = line; } std::string GlobalExceptionHandler::name_ = "unknown exception"; int GlobalExceptionHandler::line_ = -1; std::string GlobalExceptionHandler::message_ = " - "; std::string GlobalExceptionHandler::file_ = "unknown"; // create a global instance of the exception handler BALL_EXPORT GlobalExceptionHandler globalHandler; } // namespace Exception std::ostream& operator << (std::ostream& os, const Exception::GeneralException& e) { os << e.getName() << " @ " << e.getFile() << ":" << e.getLine() << ": " << e.getMessage(); return os; } } // namespace BALL ugene-1.9.8/src/plugins_3rdparty/ball/src/source/COMMON/version.cpp0000644000175000017500000000421511651544326023605 0ustar ilyailya// -*- Mode: C++; tab-width: 2; -*- // vi: set ts=2: // // $Id: version.C,v 1.14 2004-02-19 12:24:33 oliver Exp $ // #include #include #include namespace BALL { const char* VersionInfo::getVersion() throw() { return BALL_RELEASE_STRING " ("__DATE__", " __TIME__ ")"; } int VersionInfo::getMinorRevision() throw(Exception::InvalidFormat) { static String release(BALL_RELEASE_STRING); String minor = release.getField(1, "."); String tmp = minor; tmp.trimRight(String::CHARACTER_CLASS__ASCII_NUMERIC); if (tmp.size() > 0) { minor.trimRight(String::CHARACTER_CLASS__ASCII_NUMERIC); } minor.trimRight(String::CHARACTER_CLASS__ASCII_ALPHA); return minor.toInt(); } int VersionInfo::getMajorRevision() throw(Exception::InvalidFormat) { static String release(BALL_RELEASE_STRING); return release.getField(0, ". ").toInt(); } VersionInfo::Type VersionInfo::getType() throw() { StringHashMap type_mapper; type_mapper.insert(std::pair("alpha", ALPHA)); type_mapper.insert(std::pair("beta", BETA)); type_mapper.insert(std::pair("nonpublic", NONPUBLIC)); type_mapper.insert(std::pair("pre", PRERELEASE)); type_mapper.insert(std::pair("patch", PATCHLVL)); static String release(BALL_RELEASE_STRING); // check for the suffix of the release string // a = alpha, b = beta, n = nonpublic, no letter = stable if (release.size() == 0) { return UNKNOWN; } String minor = release.getField(1, "."); String tmp = minor; tmp.trimLeft(String::CHARACTER_CLASS__ASCII_NUMERIC); if (tmp.size() == 0) { return STABLE; } String type = tmp.trimRight("0123456789."); if (type_mapper.has(type)) { return(type_mapper[type]); } else { return(UNKNOWN); } } const char* VersionInfo::RELEASE_DATE_AND_TIME = "@(#)BALL kernel compiled on: " __DATE__ ", " __TIME__; const char* VersionInfo::RELEASE_WHAT_STRING = "@(#)BALL kernel version: V." BALL_RELEASE_STRING; } ugene-1.9.8/src/plugins_3rdparty/ball/src/source/COMMON/rtti.cpp0000644000175000017500000001074011651544326023102 0ustar ilyailya// -*- Mode: C++; tab-width: 2; -*- // vi: set ts=2: // // $Id: rtti.C,v 1.14 2003-08-26 09:17:44 oliver Exp $ // #include #include #include #include // Nasty hacks to demangle the stupid name mangling schemes // of diverse compilers. // GNU g++: // Starting V3.0 we use __cxa_demangle to demangle the names, // which is declared in . #ifdef BALL_COMPILER_GXX # if (BALL_COMPILER_VERSION_MAJOR > 2) #include # endif #endif #ifdef BALL_COMPILER_INTEL // Declare the __cxa_demangle method for Intel's C++ compiler. // Intel does not provide the cxxabi.h header G++ provides, so // this hack is somewhat rough. namespace abi { extern "C" char* __cxa_demangle(const char*, char*, unsigned int*, int*); } #endif namespace BALL { string streamClassName(const std::type_info& t) { #if (defined(BALL_COMPILER_GXX) || defined(BALL_COMPILER_INTEL)) #if (BALL_COMPILER_VERSION_MAJOR < 3) string s(t.name()); s = GNUDemangling::demangle(s); #else char buf[BALL_MAX_LINE_LENGTH]; std::size_t length = BALL_MAX_LINE_LENGTH - 1; int status = 0; string s("_Z"); s += t.name(); char* name = abi::__cxa_demangle(s.c_str(), buf, &length, &status); if (name != 0) { s = name; } #endif #else string s(t.name()); #ifdef BALL_COMPILER_MSVC // MSVC prefixes all class names with "class " -- delete it! while (s.find("class ") != string::npos) s.erase(s.find("class "), 6); #endif #endif for (unsigned int i = 0; i < s.size(); i++) { if (s[i] == ' ') { s[i] = '_'; } } if (string(s, 0, 6) == "const_") { s.erase(0, 6); } return s; } #ifdef BALL_COMPILER_GXX # if (BALL_COMPILER_VERSION_MAJOR < 3) namespace GNUDemangling { string decode_mangling(string& s) { string tmp; int i,len; if (s.size() == 0) return ""; if (!isdigit(s[0])) { // decode GNU shortcuts for built-in types char c = s[0]; s.erase(0, 1); switch (c) { case 'Q': // start of class name len = atoi(string(s,1,1).c_str()); s.erase(0, 1); for (i = 0; i < len; i++) { tmp.append(decode_mangling(s)); tmp.append("::"); } tmp.erase(tmp.end() - 2, tmp.end()); break; case 'Z': // template parameter return decode_mangling(s); break; case 'i': return "int"; break; case 'l': return "long"; break; case 's': return "short"; break; case 'c': return "char"; break; case 'x': return "long long"; break; case 'f': return "float"; break; case 'd': return "double"; break; case 'b': return "bool"; break; case 'w': return "wchar_t"; break; case 'U': // unsigned variants tmp = "unsigned "; tmp.append(decode_mangling(s)); break; case 'C': // const tmp = "const "; tmp.append(decode_mangling(s)); break; case 'P': // pointer tmp = decode_mangling(s); tmp.append("*"); break; case 'R': // reference tmp = decode_mangling(s); tmp.append("&"); break; case 't': tmp = decode_mangling(s); tmp.append("<"); len = atoi(string(1, s[0]).c_str()); s.erase(0,1); for (i = 0; i < len; i++) { tmp.append(decode_mangling(s)); tmp.append(","); } // remove last ',' tmp.erase(tmp.end() - 1, tmp.end()); tmp.append(">"); break; default: tmp = "?"; } return tmp; } else { i = s.find_first_not_of("0123456789"); len = atol(string(s, 0, i).c_str()); if (len == 0) { s.erase(0,1); if (s.size() > 0) { return decode_mangling(s); } else { return ""; } } else { string h(s, i, len); s.erase(0, i + len); return h; } } } string demangle(string s) { string tmp = decode_mangling(s); while (tmp[tmp.size() - 1] == ':') { tmp.erase(tmp.end() - 1, tmp.end()); } while (tmp[0] == ':') { tmp.erase(0, 1); } return tmp; } } // namespace GNUDemangling # endif // (BALL_COMPILER_VERSION_MAJOR < 3) #endif // BALL_COMPILER_GXX } // namespace BALL ugene-1.9.8/src/plugins_3rdparty/ball/src/source/STRUCTURE/0000755000175000017500000000000011651544310022013 5ustar ilyailyaugene-1.9.8/src/plugins_3rdparty/ball/src/source/STRUCTURE/triangulatedSES.cpp0000644000175000017500000014776111651544326025604 0ustar ilyailya// -*- Mode: C++; tab-width: 2; -*- // vi: set ts=2: // // $Id: triangulatedSES.C,v 1.9.28.1 2007-03-22 11:48:22 oliver Exp $ // #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include namespace BALL { TriangulatedSES::TriangulatedSES() throw() : TriangulatedSurface(), ses_(NULL), density_(4.5) { } TriangulatedSES::TriangulatedSES (const TriangulatedSES& surface, bool deep) throw() : TriangulatedSurface(surface,deep), ses_(surface.ses_), density_(surface.density_) { } TriangulatedSES::TriangulatedSES (SolventExcludedSurface* ses, const double& density) throw() : TriangulatedSurface(), ses_(ses), density_(density) { } TriangulatedSES::~TriangulatedSES() throw() { } void TriangulatedSES::set(const TriangulatedSES& surface, bool) throw() { if (this != &surface) { TriangulatedSurface::set(surface); ses_ = surface.ses_; density_ = surface.density_; } } TriangulatedSES& TriangulatedSES::operator = (const TriangulatedSES& surface) throw() { if (this != &surface) { TriangulatedSurface::operator = (surface); ses_ = surface.ses_; density_ = surface.density_; } return *this; } void TriangulatedSES::setDensity(const double& density) throw() { density_ = density; } double TriangulatedSES::getDensity() const throw() { return density_; } void TriangulatedSES::compute( int& progress ) throw(Exception::GeneralException,Exception::DivisionByZero) { SESTriangulator sest(this); sest.run(progress); } SESTriangulator::SESTriangulator() throw() : tses_(0), point_(), edge_(), template_spheres_(), sqrt_density_(0.0) { } SESTriangulator::SESTriangulator(TriangulatedSES* tses) throw() : tses_(tses), point_(tses->ses_->number_of_vertices_), edge_(tses->ses_->number_of_edges_), template_spheres_(), sqrt_density_(sqrt(tses_->density_)) { } SESTriangulator::~SESTriangulator() throw() { std::list::iterator i; for (i = template_spheres_[0].begin(); i != template_spheres_[0].end(); i++) { delete *i; } for (i = template_spheres_[1].begin(); i != template_spheres_[1].end(); i++) { delete *i; } for (i = template_spheres_[2].begin(); i != template_spheres_[2].end(); i++) { delete *i; } for (i = template_spheres_[3].begin(); i != template_spheres_[3].end(); i++) { delete *i; } } void SESTriangulator::run( int& progress ) throw(Exception::GeneralException,Exception::DivisionByZero) { preProcessing(); progress = 20; triangulateToricFaces(); progress = 40; partitionSingularEdges(); progress = 60; triangulateContactFaces(); progress = 80; triangulateSphericFaces(); progress = 100; //std::list::iterator p; //for (p = tses_->points_.begin(); p != tses_->points_.end(); p++) //{ // (*p)->normal_.normalize(); //} } void SESTriangulator::preProcessing() throw() { tses_->ses_->clean(tses_->density_); tses_->ses_->splitSphericFaces(); for (Position i = 0; i < tses_->ses_->number_of_vertices_; i++) { point_[i] = new TrianglePoint; point_[i]->point_ = tses_->ses_->vertices_[i]->point_; point_[i]->normal_ = tses_->ses_->vertices_[i]->normal_; tses_->points_.push_back(point_[i]); tses_->number_of_points_++; } buildTemplateSpheres(); } void SESTriangulator::triangulateToricFaces() throw() { double epsilon = Constants::EPSILON; Constants::EPSILON = 1e-4; double probe_radius(tses_->ses_->reduced_surface_->probe_radius_); for (Position i = 0; i < tses_->ses_->number_of_toric_faces_; i++) { triangulateToricFace(tses_->ses_->toric_faces_[i],probe_radius); } Constants::EPSILON = epsilon; } void SESTriangulator::partitionSingularEdges() throw() { std::list::iterator e; for (e = tses_->ses_->singular_edges_.begin(); e != tses_->ses_->singular_edges_.end(); e++) { partitionSingularEdge(*e); } } void SESTriangulator::triangulateContactFaces() throw() { SESFace* current_face; TSphere3 sphere; for (Position i = 0; i < tses_->ses_->number_of_contact_faces_; i++) { current_face = tses_->ses_->contact_faces_[i]; sphere.set(tses_->ses_->reduced_surface_ ->atom_[current_face->rsvertex_->atom_]); triangulateContactFace(current_face,sphere); } } void SESTriangulator::triangulateSphericFaces() throw() { SESFace* current_face; TSphere3 sphere; sphere.radius = tses_->ses_->reduced_surface_->probe_radius_; std::list not_triangulated_faces; for (Position i = 0; i < tses_->ses_->number_of_spheric_faces_; i++) { current_face = tses_->ses_->spheric_faces_[i]; sphere.p.set(current_face->rsface_->center_); if (!triangulateSphericFace(current_face,sphere)) { not_triangulated_faces.push_back(current_face); } } Position end = not_triangulated_faces.size(); Position counter = 0; while ((!not_triangulated_faces.empty()) && (counter < end)) { current_face = not_triangulated_faces.front(); not_triangulated_faces.pop_front(); bool ok = false; std::list::iterator e = current_face->edge_.begin(); while (!ok && (e != current_face->edge_.end())) { if (edge_[(*e)->index_].front()->face_[0] != NULL) { sphere.p.set(current_face->rsface_->center_); SESEdge::Type type = (*e)->type_; (*e)->type_ = SESEdge::TYPE_CONCAVE; ok = triangulateSphericFace(current_face,sphere); (*e)->type_ = type; } e++; } if (ok) { end--; counter = 0; } else { not_triangulated_faces.push_back(current_face); counter++; } } } void SESTriangulator::triangulateToricFace (SESFace* face, const double& probe_radius) throw() { if (face->isFree()) { triangulateFreeToricFace(face,probe_radius); } else { if (face->rsedge_->isSingular()) { triangulateSingularToricFace(face,probe_radius); } else { triangulateNonSingularToricFace(face,probe_radius); } } } void SESTriangulator::triangulateNonSingularToricFace (SESFace* face, const double& probe_radius) throw() { std::list::iterator e = face->edge_.begin(); SESEdge* edge0 = *e; e++; SESEdge* edge1 = *e; e++; SESEdge* edge2 = *e; e++; SESEdge* edge3 = *e; std::list::iterator v = face->vertex_.begin(); SESVertex* p0 = *v; v++; SESVertex* p1 = *v; // In how much segments the edge should be triangulated? This depends on the angle of the // corresponding RSEdge and the density. Size number_of_segments = (Size)Maths::round(face->rsedge_->angle_.value*edge3->circle_.radius*sqrt_density_); if (number_of_segments == 0) { number_of_segments++; } TAngle psi(face->rsedge_->angle_.value/number_of_segments,true); // Get the normal vector of the rotation used to partition the SESEdges of the SESFace ... TCircle3 circle3(edge3->circle_); TCircle3 circle1(edge1->circle_); TVector3 normal(circle3.n); // ... and now partition the SESEdges ... vector< TVector3 > edge3_segments; vector< TVector3 > edge1_segments; partitionOfCircle(circle3,edge3->vertex_[0]->point_,psi,number_of_segments,edge3_segments); edge3_segments.pop_back(); edge3_segments.push_back(edge3->vertex_[1]->point_); if (edge3->vertex_[0] != p0) { TVector3 tmp; for (Position i = 0; i < (number_of_segments+1)/2; i++) { tmp = edge3_segments[i]; edge3_segments[i] = edge3_segments[number_of_segments-i]; edge3_segments[number_of_segments-i] = tmp; } normal.negate(); } partitionOfCircle(circle1,edge1->vertex_[0]->point_,psi,number_of_segments,edge1_segments); edge1_segments.pop_back(); edge1_segments.push_back(edge1->vertex_[1]->point_); if (edge1->vertex_[0] != p1) { TVector3 tmp; for (Position i = 0; i < (number_of_segments+1)/2; i++) { tmp = edge1_segments[i]; edge1_segments[i] = edge1_segments[number_of_segments-i]; edge1_segments[number_of_segments-i] = tmp; } } TCircle3 center_circle(face->rsedge_->center_of_torus_, normal, face->rsedge_->radius_of_torus_); // ... and the "center_circle". This is the circle on which the centers oft the circle lie which // define the segments of the face. vector< TVector3 > centers; partitionOfCircle(center_circle,edge0->circle_.p,psi,number_of_segments,centers); centers.pop_back(); centers.push_back(edge2->circle_.p); // save an iterator to the last triangle // // workaround for MSVC from Andreas Moll: 22.07.06 std::list::iterator last_triangle = tses_->triangles_.end(); bool at_start = false; if (tses_->triangles_.size() == 0) { at_start = true; } else { last_triangle--; } buildTriangles(edge0,edge1,edge2,edge3,centers,edge1_segments,edge3_segments, probe_radius); if (at_start) { last_triangle = tses_->triangles_.begin(); } else { last_triangle++; } Triangle* test_triangle = *last_triangle; // swap the triangles if necessary TVector3 orth( (test_triangle->vertex_[1]->point_-test_triangle->vertex_[0]->point_) % (test_triangle->vertex_[2]->point_-test_triangle->vertex_[0]->point_)); if (Maths::isGreater(orth*test_triangle->vertex_[0]->point_,orth*centers[0])) { std::list::iterator t; for (t = last_triangle; t != tses_->triangles_.end(); t++) { TrianglePoint* temp = (*t)->vertex_[0]; (*t)->vertex_[0] = (*t)->vertex_[1]; (*t)->vertex_[1] = temp; } } /*SESEdge* edge[4]; Position i = 0; std::list::iterator e; for (e = face->edge_.begin(); e != face->edge_.end(); e++) { edge[i] = *e; i++; } SESVertex* p[4]; i = 0; std::list::iterator v; for (v = face->vertex_.begin(); v != face->vertex_.end(); v++) { p[i] = *v; i++; } // In how much segments the edge should be triangulated? // This depends on the angle of the corresponding RSEdge and the density. TCircle3* circle3 = &(edge[3]->circle_); TCircle3* circle1 = &(edge[1]->circle_); Size number_of_segments = (Size)Maths::round(face->rsedge_->angle_.value* circle3->radius* sqrt_density_); number_of_segments = (number_of_segments == 0 ? 1 : number_of_segments); TAngle psi(face->rsedge_->angle_.value/number_of_segments,true); // Get the normal vector of the rotation used to partition the SESEdges // of the SESFace ... TVector3 normal(circle3->n); // ... and now partition the SESEdges ... std::vector< TVector3 > edge3_segments; std::vector< TVector3 > edge1_segments; partitionOfCircle(*circle3,edge[3]->vertex_[0]->point_,psi, number_of_segments,edge3_segments); edge3_segments.pop_back(); edge3_segments.push_back(edge[3]->vertex_[1]->point_); if (edge[3]->vertex_[0] != p[0]) { // revert edge3_segments TVector3 tmp; for (Position i = 0; i < (number_of_segments+1)/2; i++) { tmp = edge3_segments[i]; edge3_segments[i] = edge3_segments[number_of_segments-i]; edge3_segments[number_of_segments-i] = tmp; } normal.negate(); } partitionOfCircle(*circle1,edge[1]->vertex_[0]->point_,psi, number_of_segments,edge1_segments); edge1_segments.pop_back(); edge1_segments.push_back(edge[1]->vertex_[1]->point_); if (edge[1]->vertex_[0] != p[1]) { // revert edge1_segments TVector3 tmp; for (Position i = 0; i < (number_of_segments+1)/2; i++) { tmp = edge1_segments[i]; edge1_segments[i] = edge1_segments[number_of_segments-i]; edge1_segments[number_of_segments-i] = tmp; } } TCircle3 center_circle(face->rsedge_->center_of_torus_, normal, face->rsedge_->radius_of_torus_); // ... and the "center_circle". This is the circle on which the centers of // the circle lie which define the segments of the face. vector< TVector3 > centers; partitionOfCircle(center_circle,edge[0]->circle_.p,psi,number_of_segments, centers); centers.pop_back(); centers.push_back(edge[2]->circle_.p); // save an iterator to the last triangle of the TriangulatedSES std::list::iterator last_triangle = tses_->triangles_.end(); last_triangle--; buildTriangles(edge[0],edge[1],edge[2],edge[3],centers, edge1_segments,edge3_segments, probe_radius); last_triangle++; Triangle* test_triangle = *last_triangle; // swap the triangles if necessary TVector3 orth((test_triangle->vertex_[1]->point_- test_triangle->vertex_[0]->point_ ) % (test_triangle->vertex_[2]->point_- test_triangle->vertex_[0]->point_ ) ); if (Maths::isGreater(orth*test_triangle->vertex_[0]->point_, orth*centers[0])) { std::list::iterator t; for (t = last_triangle; t != tses_->triangles_.end(); t++) { TrianglePoint* temp = (*t)->vertex_[0]; (*t)->vertex_[0] = (*t)->vertex_[1]; (*t)->vertex_[1] = temp; } }*/ } void SESTriangulator::triangulateFreeToricFace (SESFace* face, const double& probe_radius) throw() { TVector3 normal(face->edge_.front()->circle_.n); TCircle3 circle1(face->edge_.front()->circle_); TCircle3 circle2(face->edge_.back()->circle_.p, normal, face->edge_.back()->circle_.radius); TCircle3 circle3(face->rsedge_->center_of_torus_, normal, face->rsedge_->radius_of_torus_); TVector3 orth(normal.y,-normal.x,0.0); if (orth == TVector3::getZero()) { orth.set(normal.z,0.0,-normal.x); } orth.normalize(); TVector3 p1(circle1.p+(orth*circle1.radius)); TVector3 p2(circle2.p+(orth*circle2.radius)); TVector3 p3(circle3.p+(orth*circle3.radius)); Size number_of_points = (Size)Maths::round(2*Constants::PI*circle1.radius*sqrt_density_); if (number_of_points == 0) { number_of_points++; } TAngle phi(2*Constants::PI/number_of_points,true); std::vector< TVector3 > points1; std::vector< TVector3 > points2; std::vector< TVector3 > centers; partitionOfCircle(circle1,p1,phi,number_of_points,points1); partitionOfCircle(circle2,p2,phi,number_of_points,points2); partitionOfCircle(circle3,p3,phi,number_of_points,centers); points1.pop_back(); points2.pop_back(); centers.pop_back(); SESEdge* dummy(NULL); buildTriangles(dummy,face->edge_.front(),dummy,face->edge_.back(), centers,points1,points2,probe_radius); } void SESTriangulator::triangulateSingularToricFace (SESFace* face, const double& probe_radius) throw() { face->normalize(true); std::list::iterator e = face->edge_.begin(); //std::vector edge(6); SESEdge* edge[6]; edge[0] = *e; e++; edge[1] = *e; e++; edge[2] = *e; e++; edge[3] = *e; e++; edge[4] = *e; e++; edge[5] = *e; std::list::iterator v = face->vertex_.begin(); //std::vector vertex(6); SESVertex* vertex[6]; vertex[0] = *v; v++; vertex[1] = *v; v++; vertex[2] = *v; v++; vertex[3] = *v; v++; vertex[4] = *v; v++; vertex[5] = *v; Size number_of_segments = (Size)Maths::round(face->rsedge_->angle_.value* edge[1]->circle_.radius*sqrt_density_); if (number_of_segments == 0) { number_of_segments++; } TAngle psi(face->rsedge_->angle_.value/number_of_segments,true); Position offset = 0; std::list::iterator last = tses_->triangles_.end(); last--; for (Position counter = 0; counter < 2; counter++) { std::vector< TVector3 > edge_segments; partitionOfCircle(edge[0+offset]->circle_, edge[0+offset]->vertex_[0]->point_, psi, number_of_segments, edge_segments); edge_segments.pop_back(); edge_segments.push_back(edge[0+offset]->vertex_[1]->point_); TVector3 axis(edge[0+offset]->circle_.n); if (edge[0+offset]->vertex_[0] != vertex[0+offset]) { TVector3 tmp; for (Position i = 0; i < (number_of_segments+1)/2; i++) { tmp = edge_segments[i]; edge_segments[i] = edge_segments[number_of_segments-i]; edge_segments[number_of_segments-i] = tmp; } axis.negate(); } std::vector< TVector3 > point; for (Position i = 0; i < number_of_segments+1; i++) { point.push_back(vertex[1+offset]->point_); } TCircle3 center_circle(face->rsedge_->center_of_torus_, axis, face->rsedge_->radius_of_torus_); vector< TVector3 > centers; partitionOfCircle(center_circle,edge[1+offset]->circle_.p,psi, number_of_segments,centers); centers.pop_back(); centers.push_back(edge[2+offset]->circle_.p); SESEdge* dummy(NULL); buildTriangles(edge[1+offset],edge[0+offset],edge[2+offset], dummy,centers,edge_segments,point,probe_radius); offset += 3; Triangle* test_triangle; std::list::iterator start; last++; test_triangle = *last; start = last; last = tses_->triangles_.end(); last--; TVector3 orth( (test_triangle->vertex_[1]->point_- test_triangle->vertex_[0]->point_) % (test_triangle->vertex_[2]->point_- test_triangle->vertex_[0]->point_)); if (Maths::isGreater(orth*(test_triangle->vertex_[0]->point_-centers[0]), 0.0)) { std::list::iterator t; TrianglePoint* temp; for (t = start; t != tses_->triangles_.end(); t++) { temp = (*t)->vertex_[0]; (*t)->vertex_[0] = (*t)->vertex_[1]; (*t)->vertex_[1] = temp; } } } } void SESTriangulator::partitionSingularEdge(SESEdge* singular_edge) throw() { if (singular_edge->vertex_[0] == NULL) { partitionFreeSingularEdge(singular_edge); } else { partitionNonFreeSingularEdge(singular_edge); } } void SESTriangulator::partitionFreeSingularEdge (SESEdge* singular_edge) throw() { TAngle phi; phi.value = 2*Constants::PI; Size number_of_segments = (Size)Maths::round(phi.value* singular_edge->circle_.radius* sqrt_density_); if (number_of_segments == 0) { number_of_segments++; } TAngle psi(phi.value/number_of_segments,true); std::vector< TVector3 > points; partitionOfCircle(singular_edge->circle_, TVector3::getZero(),psi, number_of_segments,points,false); points.pop_back(); TrianglePoint* p0; TrianglePoint* p1; TrianglePoint* p2; TriangleEdge* e; p1 = new TrianglePoint; p1->point_ = points[0]; p1->normal_ = singular_edge->circle_.p-p1->point_; tses_->points_.push_back(p1); tses_->number_of_points_++; p0 = p1; for (Position k = 1; k < points.size(); k++) { p2 = new TrianglePoint; p2->point_ = points[k]; p2->normal_ = singular_edge->circle_.p-p2->point_; tses_->points_.push_back(p2); tses_->number_of_points_++; e = new TriangleEdge; e->vertex_[0] = p1; e->vertex_[1] = p2; tses_->edges_.push_back(e); tses_->number_of_edges_++; edge_[singular_edge->index_].push_back(e); p1->edges_.insert(e); p2->edges_.insert(e); p1 = p2; } e = new TriangleEdge; e->vertex_[0] = p1; e->vertex_[1] = p0; tses_->edges_.push_back(e); tses_->number_of_edges_++; edge_[singular_edge->index_].push_back(e); p1->edges_.insert(e); p0->edges_.insert(e); } void SESTriangulator::partitionNonFreeSingularEdge (SESEdge* singular_edge) throw() { TAngle phi(getOrientedAngle(singular_edge->vertex_[0]->point_- singular_edge->circle_.p, singular_edge->vertex_[1]->point_- singular_edge->circle_.p, singular_edge->circle_.n)); Size number_of_segments = (Size)Maths::round(phi.value* singular_edge->circle_.radius* sqrt_density_); if (number_of_segments == 0) { number_of_segments++; } TAngle psi(phi.value/number_of_segments,true); std::vector< TVector3 > points; partitionOfCircle(singular_edge->circle_, singular_edge->vertex_[0]->point_,psi, number_of_segments,points); points.pop_back(); points.push_back(singular_edge->vertex_[1]->point_); TrianglePoint* p1; TrianglePoint* p2; TriangleEdge* e; p1 = point_[singular_edge->vertex_[0]->index_]; p1->normal_ = singular_edge->circle_.p-p1->point_; for (Position k = 1; k < points.size()-1; k++) { p2 = new TrianglePoint; p2->point_ = points[k]; p2->normal_ = singular_edge->circle_.p-p2->point_; tses_->points_.push_back(p2); tses_->number_of_points_++; e = new TriangleEdge; e->vertex_[0] = p1; e->vertex_[1] = p2; tses_->edges_.push_back(e); tses_->number_of_edges_++; edge_[singular_edge->index_].push_back(e); p1->edges_.insert(e); p2->edges_.insert(e); p1 = p2; } p2 = point_[singular_edge->vertex_[1]->index_]; p2->normal_ = singular_edge->circle_.p-p2->point_; e = new TriangleEdge; e->vertex_[0] = p1; e->vertex_[1] = p2; tses_->edges_.push_back(e); tses_->number_of_edges_++; edge_[singular_edge->index_].push_back(e); p1->edges_.insert(e); p2->edges_.insert(e); } void SESTriangulator::triangulateContactFace (SESFace* face, const TSphere3& sphere) throw() { Position number_of_edges = face->edge_.size(); if (number_of_edges > 0) { // the face does not come from a free vertex if ((number_of_edges == 2) && (edge_[face->edge_.front()->index_].size() == 1) && (edge_[face->edge_.back()->index_].size() == 1) ) { return; } if ((number_of_edges == 3) && (edge_[face->edge_.front()->index_].size() == 1) && (edge_[(*(face->edge_.begin())++)->index_].size() == 1) && (edge_[face->edge_.back()->index_].size() == 1) ) { Triangle* triangle = new Triangle; HashSet points; points.insert(point_[face->edge_.front()->vertex_[0]->index_]); points.insert(point_[face->edge_.front()->vertex_[1]->index_]); points.insert(point_[face->edge_.back()->vertex_[0]->index_]); points.insert(point_[face->edge_.back()->vertex_[1]->index_]); HashSet::Iterator p = points.begin(); for (Position i = 0; i < 3; i++) { triangle->vertex_[i] = *p; p++; } TVector3 normal((triangle->vertex_[0]->point_- triangle->vertex_[1]->point_ )% (triangle->vertex_[0]->point_- triangle->vertex_[2]->point_ ) ); if (Maths::isGreater(normal*(sphere.p-triangle->vertex_[1]->point_), 0.0)) { TrianglePoint* tmp = triangle->vertex_[0]; triangle->vertex_[0] = triangle->vertex_[1]; triangle->vertex_[1] = tmp; } tses_->triangles_.push_back(triangle); tses_->number_of_triangles_++; return; } // get a template sphere for the face to triangulate HashMap >::ConstIterator s = template_spheres_.find(numberOfRefinements(tses_->density_, sphere.radius)); std::list::const_iterator p; TrianglePoint* point; TriangulatedSES part; for (p = s->second.begin(); p != s->second.end(); p++) { point = new TrianglePoint; point->point_ = (*p)->point_; point->normal_ = (*p)->normal_; part.points_.push_back(point); part.number_of_points_++; } part.blowUp(sphere.radius); // cut the face with all its edges TPlane3 plane; std::list::iterator edge; for (edge = face->edge_.begin(); edge != face->edge_.end(); edge++) { plane.p = (*edge)->circle_.p-sphere.p; plane.n = (*edge)->circle_.n; part.cut(plane, 0.05); } part.shift(sphere.p); buildSphericTriangles(face,part,sphere); part.deleteIsolatedPoints(); tses_->join(part); } else { // the face comes from a free vertex TriangulatedSphere part; part.icosaeder(); part.refine(numberOfRefinements(tses_->density_,sphere.radius)); part.blowUp(sphere.radius); part.shift(sphere.p); tses_->join(part); } } bool SESTriangulator::triangulateSphericFace (SESFace* face, const TSphere3& sphere) throw() { TriangulatedSES part; bool ok = buildSphericTriangles(face,part,sphere,false); if (ok) { tses_->join(part); return true; } else { return false; } } bool SESTriangulator::buildSphericTriangles (SESFace* face, TriangulatedSES& part, const TSphere3& sphere, bool convex) throw() { HashSet points; std::list::iterator p; for (p = part.points_.begin(); p != part.points_.end(); p++) { points.insert(*p); } std::list::const_iterator c; std::list::const_iterator e; for (e = face->edge_.begin(); e != face->edge_.end(); e++) { for (c = edge_[(*e)->index_].begin(); c != edge_[(*e)->index_].end(); c++) { points.insert((*c)->vertex_[0]); points.insert((*c)->vertex_[1]); } } std::list border; if (!buildFirstTriangle(face,part,border,sphere,points,convex)) { return false; } while (border.size() > 0) { TriangleEdge* edge = border.front(); border.pop_front(); Triangle* start_triangle = edge->face_[0]; TrianglePoint* third_point = start_triangle->third(edge->vertex_[0],edge->vertex_[1]); TVector3 normal((third_point->point_-edge->vertex_[0]->point_) % (third_point->point_-edge->vertex_[1]->point_) ); double test_value = normal*third_point->point_; Index p0 = start_triangle->getRelativeIndex(edge->vertex_[0]); Index p1 = start_triangle->getRelativeIndex(edge->vertex_[1]); Index diff = p1-p0; if ((convex && ((diff == -1) || (diff == 2))) || (!convex && ((diff == 1) || (diff == -2))) ) { TrianglePoint* tmp = edge->vertex_[0]; edge->vertex_[0] = edge->vertex_[1]; edge->vertex_[1] = tmp; } HashSet::Iterator next = points.begin(); for (; +next; ++next) { TrianglePoint* tpoint = *next; if (tpoint != edge->vertex_[0] && tpoint != edge->vertex_[1] && tpoint != third_point) { break; } } if (!+next) continue; std::list third; third.push_back(*next); normal.set(((*next)->point_-edge->vertex_[1]->point_) % ((*next)->point_-edge->vertex_[0]->point_) ); test_value = normal*edge->vertex_[0]->point_; next++; while (+next) { if ((*next != edge->vertex_[0]) && (*next != edge->vertex_[1]) && (*next != third_point)) { double this_value = normal*(*next)->point_; if (Maths::isGreater(this_value,test_value)) { third.clear(); third.push_back(*next); normal.set(((*next)->point_-edge->vertex_[1]->point_) % ((*next)->point_-edge->vertex_[0]->point_) ); test_value = normal*edge->vertex_[0]->point_; } else { if (Maths::isEqual(this_value,test_value)) { third.push_back(*next); } } } next++; } switch (third.size()) { case 0 : break; case 1 : buildUnambiguousTriangle(edge,third.front(),border, sphere,part,convex); break; default : buildAmbiguousTriangles(edge,third,border, sphere,part,convex); break; } } return true; } bool SESTriangulator::buildFirstTriangle (SESFace* face, TriangulatedSES& part, std::list& border, const TSphere3& sphere, const HashSet& points, bool convex) throw() { SESEdge* first_sesedge = firstSESEdge(face->edge_); if (first_sesedge == NULL) { return false; } TriangleEdge* edge = edge_[first_sesedge->index_].front(); HashSet same_edge; std::list::const_iterator e; for (e = edge_[first_sesedge->index_].begin(); e != edge_[first_sesedge->index_].end(); e++) { same_edge.insert((*e)->vertex_[0]); same_edge.insert((*e)->vertex_[1]); } // orientiere die edge so, wie sie im existierenden Dreieck NICHT // orientiert ist (so soll sie im neuen Dreieck orientiert sein) TVector3 edge_vector(edge->vertex_[0]->point_-edge->vertex_[1]->point_); Triangle* triangle = edge->face_[0]; Index p0 = triangle->getRelativeIndex(edge->vertex_[0]); Index p1 = triangle->getRelativeIndex(edge->vertex_[1]); Index diff = p1-p0; if ((diff == 1) || (diff == -2)) { TrianglePoint* tmp = edge->vertex_[0]; edge->vertex_[0] = edge->vertex_[1]; edge->vertex_[1] = tmp; edge_vector = -edge_vector; } HashSet::ConstIterator next = points.begin(); HashSet::ConstIterator test; std::list third; TVector3 normal; while (next != points.end()) { if (!same_edge.has(*next)) { normal.set(edge_vector % (edge->vertex_[0]->point_-(*next)->point_)); double test_value = normal*edge->vertex_[0]->point_; bool is_convex = true; test = points.begin(); while (test != points.end()) { if ((*test != *next) && (*test != edge->vertex_[0]) && (*test != edge->vertex_[1])) { double this_value = normal*(*test)->point_; if ((Maths::isGreater(this_value,test_value) && convex) || (Maths::isLess(this_value,test_value) && !convex)) { is_convex = false; } } test++; } if (is_convex) { third.push_back(*next); } } next++; } std::list real_third; if (third.size() == 1) { real_third.push_back(third.front()); } else { // normal vector of the old triangle (shows out of the molecule) normal.set((triangle->vertex_[0]->point_-triangle->vertex_[1]->point_) % (triangle->vertex_[0]->point_-triangle->vertex_[2]->point_) ); TAngle min(3*Constants::PI,true); std::list::iterator p = third.begin(); TVector3 new_normal; TAngle angle; while (p != third.end()) { new_normal.set(edge_vector % (edge->vertex_[0]->point_-(*p)->point_)); angle = getOrientedAngle(normal,new_normal,edge_vector); if (angle <= min) { if (angle < min) { real_third.clear(); min = angle; } real_third.push_back(*p); } p++; } } switch (real_third.size()) { case 0 : break; case 1 : buildUnambiguousTriangle(edge,real_third.front(),border, sphere,part,convex); break; default : buildAmbiguousTriangles(edge,real_third,border, sphere,part,convex); break; } return true; } SESEdge* SESTriangulator::firstSESEdge (const std::list& sesedge) throw() { bool found = false; std::list::const_iterator e = sesedge.begin(); while (e != sesedge.end()) { found = false; while ((found == false) && (e != sesedge.end())) { if ((*e)->type_ == SESEdge::TYPE_SINGULAR) { e++; } else { found = true; } } if (found) { if (edge_[(*e)->index_].size() == 1) { TriangleEdge* edge = edge_[(*e)->index_].front(); TVector3 diff(edge->vertex_[0]->point_-edge->vertex_[1]->point_); if (diff*diff < 0.01) { e++; } else { return *e; } } else { return *e; } } } return NULL; } void SESTriangulator::buildUnambiguousTriangle (TriangleEdge* edge, TrianglePoint* point, std::list& border, const TSphere3& sphere, TriangulatedSES& part, bool convex ) throw() { TriangleEdge* edge1; TriangleEdge* edge2; Triangle* triangle; bool old1, old2; createTriangleAndEdges(edge,point,sphere, edge1,old1,edge2,old2,triangle,convex); if (old1 == true) { if (edge1->face_[0] == NULL) { edge1->face_[0] = triangle; } else { edge1->face_[1] = triangle; } border.remove(edge1); } else { edge1->vertex_[0]->edges_.insert(edge1); edge1->vertex_[1]->edges_.insert(edge1); edge1->face_[0] = triangle; part.edges_.push_back(edge1); part.number_of_edges_++; border.push_back(edge1); } if (old2 == true) { if (edge2->face_[0] == NULL) { edge2->face_[0] = triangle; } else { edge2->face_[1] = triangle; } border.remove(edge2); } else { edge2->vertex_[0]->edges_.insert(edge2); edge2->vertex_[1]->edges_.insert(edge2); edge2->face_[0] = triangle; part.edges_.push_back(edge2); part.number_of_edges_++; border.push_back(edge2); } edge->face_[1] = triangle; triangle->vertex_[0]->faces_.insert(triangle); triangle->vertex_[1]->faces_.insert(triangle); triangle->vertex_[2]->faces_.insert(triangle); part.triangles_.push_back(triangle); part.number_of_triangles_++; } void SESTriangulator::buildAmbiguousTriangles (TriangleEdge* edge, std::list points, std::list& border, const TSphere3& sphere, TriangulatedSES& part, bool convex ) throw() { std::list::iterator p; points.push_back(edge->vertex_[0]); points.push_back(edge->vertex_[1]); std::list planar_edges; planar_edges.push_back(edge); TriangleEdge* edge0; TriangleEdge* edge1; TriangleEdge* edge2; Triangle* triangle; bool old1, old2; while (planar_edges.size() > 0) { edge0 = planar_edges.front(); planar_edges.pop_front(); p = points.begin(); bool built = false; while ((p != points.end()) && (built == false)) { if ((*p == edge0->vertex_[0]) || (*p == edge0->vertex_[1])) { p++; } else { createTriangleAndEdges(edge0,*p,sphere,edge1,old1,edge2,old2,triangle,convex); if (edge0 == edge) { // the first triangle has not to be tested built = true; } else { Triangle* old_triangle = edge0->face_[0]; Index i1 = old_triangle->getRelativeIndex(edge0->vertex_[0]); Index i2 = old_triangle->getRelativeIndex(edge0->vertex_[1]); bool back = false; if ((i1-i2 == 1) || (i1-i2 == -2)) { back = true; } i1 = triangle->getRelativeIndex(edge0->vertex_[0]); i2 = triangle->getRelativeIndex(edge0->vertex_[1]); if (back) { if ((i1-i2 == -1) || (i1-i2 == 2)) { built = true; } } else { if ((i1-i2 == 1) || (i1-i2 == -2)) { built = true; } } } if (built) { edge0->face_[1] = triangle; triangle->vertex_[0]->faces_.insert(triangle); triangle->vertex_[1]->faces_.insert(triangle); triangle->vertex_[2]->faces_.insert(triangle); if (old1 == true) { if (edge1->face_[0] == NULL) { edge1->face_[0] = triangle; } else { edge1->face_[1] = triangle; } border.remove(edge1); planar_edges.remove(edge1); } else { edge1->face_[0] = triangle; border.push_back(edge1); planar_edges.push_back(edge1); edge1->vertex_[0]->edges_.insert(edge1); edge1->vertex_[1]->edges_.insert(edge1); part.edges_.push_back(edge1); part.number_of_edges_++; } if (old2 == true) { if (edge2->face_[0] == NULL) { edge2->face_[0] = triangle; } else { edge2->face_[1] = triangle; } border.remove(edge2); planar_edges.remove(edge2); } else { edge2->face_[0] = triangle; border.push_back(edge2); planar_edges.push_back(edge2); edge2->vertex_[0]->edges_.insert(edge2); edge2->vertex_[1]->edges_.insert(edge2); part.edges_.push_back(edge2); part.number_of_edges_++; } border.remove(edge0); part.triangles_.push_back(triangle); part.number_of_triangles_++; } else { p++; delete triangle; if (old1 == false) { delete edge1; } if (old2 == false) { delete edge2; } } } } } } void SESTriangulator::createTriangleAndEdges (TriangleEdge* edge, TrianglePoint* point, const TSphere3& sphere, TriangleEdge*& edge1, bool& old1, TriangleEdge*& edge2, bool& old2, Triangle*& triangle, bool convex ) throw() { // build two new edges edge1 = new TriangleEdge; edge1->vertex_[0] = edge->vertex_[0]; edge1->vertex_[1] = point; edge2 = new TriangleEdge; edge2->vertex_[0] = point; edge2->vertex_[1] = edge->vertex_[1]; // do the edges exist ? TriangleEdge* test = edge->vertex_[0]->has(edge1); if (test != NULL) { delete edge1; edge1 = test; old1 = true; } else { old1 = false; } test = edge->vertex_[1]->has(edge2); if (test != NULL) { delete edge2; edge2 = test; old2 = true; } else { old2 = false; } // build the new triangle triangle = new Triangle; triangle->vertex_[0] = edge->vertex_[1]; triangle->vertex_[1] = edge->vertex_[0]; triangle->vertex_[2] = point; triangle->edge_[0] = edge; triangle->edge_[1] = edge1; triangle->edge_[2] = edge2; // swap triangle if necessary TVector3 test_vector((triangle->vertex_[1]->point_- triangle->vertex_[0]->point_)% (triangle->vertex_[2]->point_- triangle->vertex_[0]->point_) ); double test_value = test_vector*(sphere.p-triangle->vertex_[0]->point_); if ((Maths::isGreater(test_value,0) && convex) || (Maths::isLess(test_value,0) && !convex) ) { TrianglePoint* temp = triangle->vertex_[0]; triangle->vertex_[0] = triangle->vertex_[1]; triangle->vertex_[1] = temp; } } void SESTriangulator::partitionOfCircle (const TCircle3& circle, const TVector3& p0, const TAngle& phi, Size number_of_segments, vector< TVector3 >& partition, bool on_surface) throw() { TVector4 p; if (on_surface) { TVector3 p_(p0-circle.p); p.set(p_.x,p_.y,p_.z,0.0); } else { p.set(circle.n.y,-circle.n.x,0.0,0.0); if (p == TVector4::getZero()) { p.set(circle.n.z,0.0,-circle.n.x,0.0); } p.normalize(); p *= circle.radius; } TQuaternion rotate(circle.n,phi); TMatrix4x4 rotation; rotate.getRotationMatrix(rotation); partition.push_back(TVector3(p.x,p.y,p.z)+circle.p); for (Size i = 0; i < number_of_segments; i++) { p = rotation*p; partition.push_back(TVector3(p.x,p.y,p.z)+circle.p); } } Size SESTriangulator::numberOfRefinements(const double& density, const double& radius) throw() { double test0 = (4.0*density*Constants::PI*radius*radius-12.0)/30.0; Size n = 0; if (Maths::isGreaterOrEqual(test0,0.0)) { double test1 = 1; double test2 = 1; while (Maths::isLess(test2,test0)) { test1 = test2; test2 *= 4; n++; } if (Maths::isLess(test2-test0,test0-test1)) { n++; } } if (n > 3) { n = 3; } return n; } void SESTriangulator::buildTemplateSpheres() throw() { TriangulatedSphere::ConstPointIterator p; TrianglePoint* point; TriangulatedSphere sphere; sphere.icosaeder(true); for (p = sphere.beginPoint(); p != sphere.endPoint(); p++) { point = new TrianglePoint(**p); template_spheres_[0].push_back(point); } sphere.refine(1,true); for (p = sphere.beginPoint(); p != sphere.endPoint(); p++) { point = new TrianglePoint(**p); template_spheres_[1].push_back(point); } sphere.refine(1,true); for (p = sphere.beginPoint(); p != sphere.endPoint(); p++) { point = new TrianglePoint(**p); template_spheres_[2].push_back(point); } sphere.refine(1,true); for (p = sphere.beginPoint(); p != sphere.endPoint(); p++) { point = new TrianglePoint(**p); template_spheres_[3].push_back(point); } } void SESTriangulator::buildTriangles (SESEdge* edge0, SESEdge* edge1, SESEdge* edge2, SESEdge* edge3, const std::vector< TVector3 >& centers, const std::vector< TVector3 >& edge1_points, const std::vector< TVector3 >& edge3_points, const double& probe_radius) throw() { TAngle pi(Constants::PI,true); TAngle psi; // How much triangles should be built in each segment of the face? // Attention: number_of_triangles is the half of the number of triangles // for each segment. GetAngle(edge1_points[0]-centers[0],edge3_points[0]-centers[0],psi); Size number_of_triangles = (Size)Maths::round(psi.value*probe_radius*sqrt_density_); if (number_of_triangles == 0) { number_of_triangles++; } TAngle phi(psi/number_of_triangles,true); Size number_of_segments = centers.size()-1; // How much TrianglePoints lie on the face? // Remark: edge3 == NULL iff the face is singular Size number_of_points = ((edge3 != NULL) ? (number_of_segments+1)*(number_of_triangles+1) : (number_of_segments+1)* number_of_triangles + 1); std::vector points(number_of_points); if (edge3 == NULL) { // singular face // get the index of the SESVertex on the top of the face // (remember: singular faces are two triangles) Index index; if (edge0->vertex_[0]->point_ == edge3_points[0]) { index = edge0->vertex_[0]->index_; } else { index = edge0->vertex_[1]->index_; } TrianglePoint* top = point_[index]; top->normal_ = centers[number_of_segments]-top->point_; points[(number_of_segments+1)*number_of_triangles] = top; } Position end = ((edge3 != NULL) ? number_of_triangles+1 : number_of_triangles); for (Position i = 0; i <= number_of_segments; i++) { TCircle3 circle(centers[i], (edge1_points[i]-centers[i])% (edge3_points[i]-centers[i]), probe_radius); std::vector< TVector3 > line; line.clear(); partitionOfCircle(circle,edge1_points[i],phi,number_of_triangles,line); for (Position j = 0; j < end; j++) { // get the index of the point if it just exists (point on the corner) Index index = -1; if (edge0 != NULL) { // not free face if ((i == 0) && (j == 0)) { double dist1 = line[0].getSquareDistance(edge0->vertex_[0]->point_); double dist2 = line[0].getSquareDistance(edge0->vertex_[1]->point_); index = ((dist1 < dist2) ? edge0->vertex_[0]->index_ : edge0->vertex_[1]->index_); } if ((i == 0) && (j == number_of_triangles) && (edge3 != NULL)) { double dist1 = line[number_of_triangles].getSquareDistance(edge0->vertex_[0]->point_); double dist2 = line[number_of_triangles].getSquareDistance(edge0->vertex_[1]->point_); index = ((dist1 < dist2) ? edge0->vertex_[0]->index_ : edge0->vertex_[1]->index_); } if ((i == number_of_segments) && (j == 0)) { double dist1 = line[0].getSquareDistance(edge2->vertex_[0]->point_); double dist2 = line[0].getSquareDistance(edge2->vertex_[1]->point_); index = ((dist1 < dist2) ? edge2->vertex_[0]->index_ : edge2->vertex_[1]->index_); } if ((i == number_of_segments) && (j == number_of_triangles) && (edge3 != NULL)) { double dist1 = line[number_of_triangles].getSquareDistance(edge2->vertex_[0]->point_); double dist2 = line[number_of_triangles].getSquareDistance(edge2->vertex_[1]->point_); index = ((dist1 < dist2) ? edge2->vertex_[0]->index_ : edge2->vertex_[1]->index_); } } TrianglePoint* point; if (index == -1) { // create a new point if it not exists yet point = new TrianglePoint; tses_->points_.push_back(point); tses_->number_of_points_++; point->point_ = line[j]; point->normal_ = centers[i]-line[j]; } else { point = point_[index]; } points[i*end+j] = point; } } // number of edges to create Size edge_number = ((edge3 != NULL) ? 3*number_of_segments*number_of_triangles + number_of_segments+number_of_triangles : 3*number_of_segments*number_of_triangles- 2*number_of_segments+number_of_triangles-1 ); std::vector edges(edge_number); // build the vertical edges Position offset; Position offset2; TriangleEdge* new_edge; for (Position j = 0; j <= number_of_segments; j++) { offset = j*end; for (Position i = 0; i < end-1; i++) { offset2 = offset+i; new_edge = new TriangleEdge; tses_->edges_.push_back(new_edge); tses_->number_of_edges_++; new_edge->vertex_[0] = points[offset2]; new_edge->vertex_[0]->edges_.insert(new_edge); new_edge->vertex_[1] = points[offset2+1]; new_edge->vertex_[1]->edges_.insert(new_edge); if ((j == 0) && (edge0 != 0)) { edge_[edge0->index_].push_back(new_edge); } else { if ((j == number_of_segments) && (edge0 != 0)) { edge_[edge2->index_].push_back(new_edge); } } edges[offset2-j] = new_edge; } } // build the horizontal edges Position add1 = (end-1)*(number_of_segments+1); for (Position j = 0; j < number_of_segments; j++) { offset = j*end; for (Position i = 0; i < end; i++) { offset2 = offset+i; new_edge = new TriangleEdge; tses_->edges_.push_back(new_edge); tses_->number_of_edges_++; new_edge->vertex_[0] = points[offset2]; new_edge->vertex_[0]->edges_.insert(new_edge); new_edge->vertex_[1] = points[offset2+end]; new_edge->vertex_[1]->edges_.insert(new_edge); if ((i == 0) && (edge1 != 0)) { edge_[edge1->index_].push_back(new_edge); } else { if ((i == end-1) && (edge3 != 0)) { edge_[edge3->index_].push_back(new_edge); } } edges[offset2+add1] = new_edge; } } // buid the diagonal edges Position add2 = add1+end*number_of_segments; for (Position j = 0; j < number_of_segments; j++) { offset = j*end-j; for (Position i = 0; i < end-1; i++) { offset2 = offset+i; new_edge = new TriangleEdge; tses_->edges_.push_back(new_edge); tses_->number_of_edges_++; new_edge->vertex_[0] = points[offset2+j]; new_edge->vertex_[0]->edges_.insert(new_edge); new_edge->vertex_[1] = points[offset2+j+end+1]; new_edge->vertex_[1]->edges_.insert(new_edge); edges[offset2+add2] = new_edge; } } // number of triangles to build Size triangle_number = 2*number_of_segments*(end-1); std::vector triangles(triangle_number); // build the triangles for (Position i = 0; i < end-1; i++) { for (Position j = 0; j < number_of_segments; j++) { offset2 = j*end+i; Triangle* t1 = new Triangle; tses_->triangles_.push_back(t1); tses_->number_of_triangles_++; t1->vertex_[0] = points[offset2]; t1->vertex_[1] = points[offset2+1]; t1->vertex_[2] = points[offset2+1+end]; t1->edge_[0] = edges[offset2-j]; t1->edge_[1] = edges[offset2+add1+1]; t1->edge_[2] = edges[offset2-j+add2]; t1->vertex_[0]->faces_.insert(t1); t1->vertex_[1]->faces_.insert(t1); t1->vertex_[2]->faces_.insert(t1); t1->edge_[0]->face_[0] = t1; t1->edge_[1]->face_[0] = t1; t1->edge_[2]->face_[0] = t1; triangles[2*(number_of_segments*i+j)] = t1; Triangle* t2 = new Triangle; tses_->triangles_.push_back(t2); tses_->number_of_triangles_++; t2->vertex_[0] = points[offset2]; t2->vertex_[1] = points[offset2+1+end]; t2->vertex_[2] = points[offset2+end]; t2->edge_[0] = edges[offset2-j+end-1]; t2->edge_[1] = edges[offset2+add1]; t2->edge_[2] = edges[offset2-j+add2]; t2->vertex_[0]->faces_.insert(t2); t2->vertex_[1]->faces_.insert(t2); t2->vertex_[2]->faces_.insert(t2); t2->edge_[0]->face_[0] = t2; t2->edge_[1]->face_[0] = t2; t2->edge_[2]->face_[0] = t2; triangles[2*(number_of_segments*i+j)+1] = t2; } } // close free faces if (edge0 == NULL) { offset = number_of_segments*end; TriangleEdge* edge = new TriangleEdge; tses_->edges_.push_back(edge); tses_->number_of_edges_++; edge->vertex_[0] = points[offset]; edge->vertex_[1] = points[0]; points[offset]->edges_.insert(edge); points[0]->edges_.insert(edge); edge_[edge1->index_].push_back(edge); for (Position i = 0; i < number_of_triangles; i++) { offset2 = offset+i; Triangle* t1 = new Triangle; tses_->triangles_.push_back(t1); tses_->number_of_triangles_++; t1->vertex_[0] = points[offset2]; t1->vertex_[1] = points[i+1]; t1->vertex_[2] = points[i]; t1->edge_[0] = edge; edge = new TriangleEdge; tses_->edges_.push_back(edge); tses_->number_of_edges_++; edge->vertex_[0] = points[offset2]; edge->vertex_[1] = points[i+1]; points[offset2]->edges_.insert(edge); points[i+1]->edges_.insert(edge); t1->edge_[1] = edge; t1->edge_[2] = edges[i]; t1->vertex_[0]->faces_.insert(t1); t1->vertex_[1]->faces_.insert(t1); t1->vertex_[2]->faces_.insert(t1); t1->edge_[0]->face_[0] = t1; t1->edge_[1]->face_[0] = t1; t1->edge_[2]->face_[0] = t1; triangles.push_back(t1); Triangle* t2 = new Triangle; tses_->triangles_.push_back(t2); tses_->number_of_triangles_++; t2->vertex_[0] = points[offset2]; t2->vertex_[1] = points[offset2+1]; t2->vertex_[2] = points[i+1]; t2->edge_[0] = edge; t2->edge_[1] = edges[offset2-number_of_segments]; edge = new TriangleEdge; tses_->edges_.push_back(edge); tses_->number_of_edges_++; edge->vertex_[0] = points[offset2+1]; edge->vertex_[1] = points[i+1]; points[offset2+1]->edges_.insert(edge); points[i+1]->edges_.insert(edge); t2->edge_[2] = edge; t2->vertex_[0]->faces_.insert(t2); t2->vertex_[1]->faces_.insert(t2); t2->vertex_[2]->faces_.insert(t2); t2->edge_[0]->face_[0] = t2; t2->edge_[1]->face_[0] = t2; t2->edge_[2]->face_[0] = t2; triangles.push_back(t2); } edge_[edge3->index_].push_back(edge); } // get the top of a singular face if (edge3 == NULL) { Position last = (number_of_segments+1)*number_of_triangles; offset = (end-1)*(number_of_segments+2); TriangleEdge* edge = new TriangleEdge; tses_->edges_.push_back(edge); tses_->number_of_edges_++; edge->vertex_[0] = points[number_of_triangles-1]; edge->vertex_[1] = points[last]; edge->vertex_[0]->edges_.insert(edge); edge->vertex_[1]->edges_.insert(edge); edge_[edge0->index_].push_back(edge); for (Position i = 0; i < number_of_segments; i++) { Triangle* t = new Triangle; tses_->triangles_.push_back(t); tses_->number_of_triangles_++; t->vertex_[0] = points[number_of_triangles*(i+1)-1]; t->vertex_[1] = points[last]; t->vertex_[2] = points[number_of_triangles*(i+2)-1]; t->edge_[0] = edge; t->edge_[1] = edges[offset+i*end]; edge = new TriangleEdge; tses_->edges_.push_back(edge); tses_->number_of_edges_++; edge->vertex_[0] = points[number_of_triangles*(i+2)-1]; edge->vertex_[1] = points[last]; edge->vertex_[0]->edges_.insert(edge); edge->vertex_[1]->edges_.insert(edge); if (i == number_of_segments-1) { edge_[edge2->index_].push_back(edge); } t->edge_[2] = edge; t->vertex_[0]->faces_.insert(t); t->vertex_[1]->faces_.insert(t); t->vertex_[2]->faces_.insert(t); t->edge_[0]->face_[0] = t; t->edge_[1]->face_[0] = t; t->edge_[2]->face_[0] = t; triangles.push_back(t); } } } } // namespace BALL ugene-1.9.8/src/plugins_3rdparty/ball/src/source/STRUCTURE/RSEdge.cpp0000644000175000017500000001567311651544326023653 0ustar ilyailya// -*- Mode: C++; tab-width: 2; -*- // vi: set ts=2: // // $Id: RSEdge.C,v 1.4 2002-12-17 14:13:19 anker Exp $ #include #include #include #include #include #include namespace BALL { RSEdge::RSEdge() throw() : GraphEdge< RSVertex,RSEdge,RSFace >(), center_of_torus_(), radius_of_torus_(0.0), angle_(), circle0_(), circle1_(), intersection_point0_(), intersection_point1_(), singular_(false) { } RSEdge::RSEdge(const RSEdge& rsedge, bool deep) throw() : GraphEdge< RSVertex,RSEdge,RSFace >(rsedge,deep), center_of_torus_(rsedge.center_of_torus_), radius_of_torus_(rsedge.radius_of_torus_), angle_(rsedge.angle_), circle0_(rsedge.circle0_), circle1_(rsedge.circle1_), intersection_point0_(rsedge.intersection_point0_), intersection_point1_(rsedge.intersection_point1_), singular_(rsedge.singular_) { } RSEdge::RSEdge(RSVertex* vertex1, RSVertex* vertex2, RSFace* face1, RSFace* face2, const TVector3& center_of_torus, const double& radius_of_torus, const TAngle& angle, const TCircle3& circle1, const TCircle3& circle2, const TVector3& intersection_point1, const TVector3& intersection_point2, bool singular, Index index) throw() : GraphEdge< RSVertex,RSEdge,RSFace > (vertex1,vertex2,face1,face2,index), center_of_torus_(center_of_torus), radius_of_torus_(radius_of_torus), angle_(angle), circle0_(circle1), circle1_(circle2), intersection_point0_(intersection_point1), intersection_point1_(intersection_point2), singular_(singular) { } RSEdge::~RSEdge() throw() { } void RSEdge::set(const RSEdge& rsedge, bool deep) throw() { if (this != &rsedge) { GraphEdge< RSVertex,RSEdge,RSFace >::set(rsedge,deep); center_of_torus_ = rsedge.center_of_torus_; radius_of_torus_ = rsedge.radius_of_torus_; angle_ = rsedge.angle_; circle0_ = rsedge.circle0_; circle1_ = rsedge.circle1_; intersection_point0_ = rsedge.intersection_point0_; intersection_point1_ = rsedge.intersection_point1_; singular_ = rsedge.singular_; } } RSEdge& RSEdge::operator = (const RSEdge& rsedge) throw() { if (this != &rsedge) { GraphEdge< RSVertex,RSEdge,RSFace >::operator = (rsedge); center_of_torus_ = rsedge.center_of_torus_; radius_of_torus_ = rsedge.radius_of_torus_; angle_ = rsedge.angle_; circle0_ = rsedge.circle0_; circle1_ = rsedge.circle1_; intersection_point0_ = rsedge.intersection_point0_; intersection_point1_ = rsedge.intersection_point1_; singular_ = rsedge.singular_; } return *this; } void RSEdge::set(RSVertex* vertex0, RSVertex* vertex1, RSFace* face0, RSFace* face1, const TVector3& center_of_torus, const double& radius_of_torus, const TAngle& angle, const TCircle3& circle0, const TCircle3& circle1, const TVector3& intersection_point0, const TVector3& intersection_point1, bool singular, Index index) throw() { GraphEdge< RSVertex,RSEdge,RSFace >::set (vertex0,vertex1,face0,face1,index); center_of_torus_ = center_of_torus; radius_of_torus_ = radius_of_torus; angle_ = angle; circle0_ = circle0; circle1_ = circle1; intersection_point0_ = intersection_point0; intersection_point1_ = intersection_point1; singular_ = singular; } void RSEdge::setCenterOfTorus(const TVector3& center) throw() { center_of_torus_ = center; } TVector3 RSEdge::getCenterOfTorus() const throw() { return center_of_torus_; } void RSEdge::setMajorRadiusOfTorus(const double& radius) throw() { radius_of_torus_ = radius; } double RSEdge::getMajorRadiusOfTorus() const throw() { return radius_of_torus_; } void RSEdge::setAngle(const TAngle& angle) throw() { angle_ = angle; } TAngle RSEdge::getAngle() const throw() { return angle_; } void RSEdge::setContactCircle(Position i, const TCircle3& circle) throw() { if (i == 0) { circle0_ = circle; } else { circle1_ = circle; } } TCircle3 RSEdge::getContactCircle(Position i) const throw() { if (i == 0) { return circle0_; } else { return circle1_; } } void RSEdge::setIntersectionPoint(Position i, const TVector3& point) throw() { if (i == 0) { intersection_point0_ = point; } else { intersection_point1_ = point; } } TVector3 RSEdge::getIntersectionPoint(Position i) const throw(Exception::GeneralException) { if (singular_ == false) { throw Exception::GeneralException(__FILE__, __LINE__); } if (i == 0) { return intersection_point0_; } else { return intersection_point1_; } } void RSEdge::setSingular(bool singular) throw() { singular_ = singular; } bool RSEdge::operator == (const RSEdge& rsedge) const throw() { return (( ((vertex_[0] == rsedge.vertex_[0]) && (vertex_[1] == rsedge.vertex_[1]) ) || ((vertex_[0] == rsedge.vertex_[1]) && (vertex_[1] == rsedge.vertex_[0]) ) ) && (((face_[0] == rsedge.face_[0]) && (face_[1] == rsedge.face_[1]) ) || ((face_[0] == rsedge.face_[1]) && (face_[1] == rsedge.face_[0]) ) ) ); } bool RSEdge::operator != (const RSEdge& rsedge) const throw() { return ( ! (*this == rsedge) ); } bool RSEdge::operator *= (const RSEdge& rsedge) const throw() { return ( ((vertex_[0]->atom_ == rsedge.vertex_[0]->atom_) && (vertex_[1]->atom_ == rsedge.vertex_[1]->atom_) ) || ((vertex_[0]->atom_ == rsedge.vertex_[1]->atom_) && (vertex_[1]->atom_ == rsedge.vertex_[0]->atom_) ) ); } bool RSEdge::isSingular() const throw() { return singular_; } bool RSEdge::isFree() const throw() { return (face_[0] == NULL); } std::ostream& operator << (std::ostream& s, const RSEdge& rsedge) { s << "RSEDGE" << rsedge.getIndex() << "([" << (rsedge.getVertex(0) == NULL ? -2 : rsedge.getVertex(0)->getIndex()) << ' ' << (rsedge.getVertex(1) == NULL ? -2 : rsedge.getVertex(1)->getIndex()) << "] [" << (rsedge.getFace(0) == NULL ? -2 : rsedge.getFace(0)->getIndex()) << ' ' << (rsedge.getFace(1) == NULL ? -2 : rsedge.getFace(1)->getIndex()) << "] " << rsedge.getCenterOfTorus() << ' ' << rsedge.getMajorRadiusOfTorus() << ' ' << rsedge.getAngle() << ' ' << rsedge.getContactCircle(0) << ' ' << rsedge.getContactCircle(1) << ' '; bool singular(rsedge.isSingular()); if (singular) { s << rsedge.getIntersectionPoint(0) << ' ' << rsedge.getIntersectionPoint(1) << " true)"; } else { s << TVector3::getZero() << ' ' << TVector3::getZero() << " false)"; } return s; } } // namespace BALL ugene-1.9.8/src/plugins_3rdparty/ball/src/source/STRUCTURE/triangleEdge.cpp0000644000175000017500000000431611651544326025124 0ustar ilyailya// -*- Mode: C++; tab-width: 2; -*- // vi: set ts=2: // // $Id: triangleEdge.C,v 1.3 2002-12-17 14:13:21 anker Exp $ #include #include #include namespace BALL { TriangleEdge::TriangleEdge() throw() : GraphEdge< TrianglePoint,TriangleEdge,Triangle >() { } TriangleEdge::TriangleEdge(const TriangleEdge& edge, bool deep) throw() : GraphEdge< TrianglePoint,TriangleEdge,Triangle >(edge,deep) { } TriangleEdge::~TriangleEdge() throw() { } void TriangleEdge::setPoint(Position i, TrianglePoint* point) throw() { if (i == 0) { vertex_[0] = point; } else { vertex_[1] = point; } } TrianglePoint* TriangleEdge::getPoint(Position i) const throw() { if (i == 0) { return vertex_[0]; } else { return vertex_[1]; } } void TriangleEdge::setTriangle(Position i, Triangle* triangle) throw() { if (i == 0) { face_[0] = triangle; } else { face_[1] = triangle; } } Triangle* TriangleEdge::getTriangle(Position i) const throw() { if (i == 0) { return face_[0]; } else { return face_[1]; } } bool TriangleEdge::operator == (const TriangleEdge& edge) const throw() { return ( ((vertex_[0]->point_ == edge.vertex_[0]->point_) && (vertex_[1]->point_ == edge.vertex_[1]->point_)) || ((vertex_[0]->point_ == edge.vertex_[1]->point_) && (vertex_[1]->point_ == edge.vertex_[0]->point_)) ); } bool TriangleEdge::operator != (const TriangleEdge& edge) const throw() { return ( !(*this == edge) ); } bool TriangleEdge::operator *= (const TriangleEdge&) const throw() { return true; } std::ostream& operator << (std::ostream& s, const TriangleEdge& edge) { s << "EDGE" << edge.getIndex() << "(" << (edge.getVertex(0) == NULL ? -2 : edge.getVertex(0)->getIndex()) << "-" << (edge.getVertex(1) == NULL ? -2 : edge.getVertex(1)->getIndex()) << " " << (edge.getFace(0) == NULL ? -2 : edge.getFace(0)->getIndex()) << "|" << (edge.getFace(1) == NULL ? -2 : edge.getFace(1)->getIndex()) << ")"; return s; } } // namespace BALL ugene-1.9.8/src/plugins_3rdparty/ball/src/source/STRUCTURE/SASFace.cpp0000644000175000017500000000521311651544326023734 0ustar ilyailya// -*- Mode: C++; tab-width: 2; -*- // vi: set ts=2: // // $Id: SASFace.C,v 1.1 2002-12-17 17:14:22 anker Exp $ #include #include #include #include #include namespace BALL { SASFace::SASFace() throw() : GraphFace< SASVertex,SASEdge,SASFace >(), orientation_(), sphere_() { } SASFace::SASFace(const SASFace& sasface, bool deep) throw() : GraphFace< SASVertex,SASEdge,SASFace >(sasface,deep), orientation_(), sphere_(sasface.sphere_) { if (deep) { orientation_ = sasface.orientation_; } } SASFace::~SASFace() throw() { } void SASFace::set(const SASFace& sasface, bool deep) throw() { if (this != &sasface) { GraphFace< SASVertex,SASEdge,SASFace >::set(sasface,deep); if (deep) { orientation_ = sasface.orientation_; } sphere_.set(sasface.sphere_); } } SASFace& SASFace::operator = (const SASFace& sasface) throw() { if (this != &sasface) { GraphFace< SASVertex,SASEdge,SASFace >::operator = (sasface); orientation_ = sasface.orientation_; sphere_.set(sasface.sphere_); } return *this; } void SASFace::setSphere(const TSphere3& sphere) throw() { sphere_ = sphere; } TSphere3 SASFace::getSphere() const throw() { return sphere_; } bool SASFace::operator == (const SASFace&) const throw() { return true; } bool SASFace::operator != (const SASFace&) const throw() { return false; } bool SASFace::operator *= (const SASFace&) const throw() { return true; } SASFace::OrientationIterator SASFace::beginOrientation() throw() { return orientation_.begin(); } SASFace::ConstOrientationIterator SASFace::beginOrientation() const throw() { return orientation_.begin(); } SASFace::OrientationIterator SASFace::endOrientation() throw() { return orientation_.end(); } SASFace::ConstOrientationIterator SASFace::endOrientation() const throw() { return orientation_.end(); } std::ostream& operator << (std::ostream& s, const SASFace& sasface) { s << "SASFACE" << sasface.getIndex() << "("; SASFace::ConstVertexIterator v = sasface.beginVertex(); while (v != sasface.endVertex()) { s << (*v)->getIndex() << ' '; v++; } s << "] ["; SASFace::ConstEdgeIterator e = sasface.beginEdge(); while (e != sasface.endEdge()) { s << (*e)->getIndex() << ' '; e++; } s << "] ["; SASFace::ConstOrientationIterator o = sasface.beginOrientation(); while (o != sasface.endOrientation()) { s << (*o ? "+ " : "- "); o++; } s << "])"; return s; } } // namespace BALL ugene-1.9.8/src/plugins_3rdparty/ball/src/source/STRUCTURE/SESVertex.cpp0000644000175000017500000000605411651544326024363 0ustar ilyailya// -*- Mode: C++; tab-width: 2; -*- // vi: set ts=2: // // $Id: SESVertex.C,v 1.4 2002-12-17 14:13:20 anker Exp $ #include #include #include #include namespace BALL { SESVertex::SESVertex() throw() : GraphVertex< SESVertex,SESEdge,SESFace >(), point_(), normal_(), atom_(0) { } SESVertex::SESVertex(const SESVertex& sesvertex, bool deep) throw() : GraphVertex< SESVertex,SESEdge,SESFace >(sesvertex,deep), point_(sesvertex.point_), normal_(sesvertex.normal_), atom_(sesvertex.atom_) { } SESVertex::SESVertex (const TVector3& point, const TVector3& normal, Index atom, Index index) throw() : GraphVertex< SESVertex,SESEdge,SESFace >(), point_(point), normal_(normal), atom_(atom) { index_ = index; } SESVertex::~SESVertex() throw() { } void SESVertex::set(const SESVertex& sesvertex, bool deep) throw() { if (this != &sesvertex) { GraphVertex< SESVertex,SESEdge,SESFace >::set (sesvertex,deep); point_.set(sesvertex.point_); normal_.set(sesvertex.normal_); atom_ = sesvertex.atom_; } } SESVertex& SESVertex::operator = (const SESVertex& sesvertex) throw() { if (this != &sesvertex) { GraphVertex< SESVertex,SESEdge,SESFace >::operator = (sesvertex); point_.set(sesvertex.point_); normal_.set(sesvertex.normal_); atom_ = sesvertex.atom_; } return *this; } void SESVertex::set(const TVector3 point, const TVector3& normal, Index atom, Index index) throw() { point_ = point; normal_ = normal; atom_ = atom; index_ = index; } void SESVertex::setPoint(const TVector3& point) throw() { point_ = point; } TVector3 SESVertex::getPoint() const throw() { return point_; } void SESVertex::setNormal(const TVector3& normal) throw(Exception::DivisionByZero) { normal_ = normal; normal_.normalize(); } TVector3 SESVertex::getNormal() const throw() { return normal_; } void SESVertex::setAtom(Index atom) throw() { atom_ = atom; } Index SESVertex::getAtom() const throw() { return atom_; } bool SESVertex::operator == (const SESVertex&) const throw() { return true; } bool SESVertex::operator != (const SESVertex&) const throw() { return false; } bool SESVertex::operator *= (const SESVertex&) const throw() { return true; } std::ostream& operator << (std::ostream& s, const SESVertex& sesvertex) { s << "SESVERTEX" << sesvertex.getIndex() << "(" << sesvertex.getPoint() << " " << sesvertex.getNormal() << " ["; SESVertex::ConstEdgeIterator e; for (e = sesvertex.beginEdge(); e != sesvertex.endEdge(); e++) { s << (*e)->getIndex() << ' '; } s << "] ["; SESVertex::ConstFaceIterator f; for (f = sesvertex.beginFace(); f != sesvertex.endFace(); f++) { s << (*f)->getIndex() << ' '; } s << "] " << sesvertex.getAtom() << ")"; return s; } } // namespace BALL ugene-1.9.8/src/plugins_3rdparty/ball/src/source/STRUCTURE/solventExcludedSurface.cpp0000644000175000017500000020432211651544326027212 0ustar ilyailya// -*- Mode: C++; tab-width: 2; -*- // vi: set ts=2: // // $Id: solventExcludedSurface.C,v 1.3.32.1 2007-04-03 13:29:31 bertsch Exp $ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include namespace BALL { SolventExcludedSurface::SolventExcludedSurface() throw() : number_of_vertices_(0), vertices_(), number_of_edges_(0), edges_(), number_of_singular_edges_(0), singular_edges_(), number_of_contact_faces_(0), contact_faces_(), number_of_toric_faces_(0), toric_faces_(), number_of_spheric_faces_(0), spheric_faces_(), reduced_surface_(NULL) { } SolventExcludedSurface::SolventExcludedSurface (const SolventExcludedSurface& ses, bool) throw() : number_of_vertices_(ses.vertices_.size()), vertices_(number_of_vertices_), number_of_edges_(ses.edges_.size()), edges_(number_of_edges_), number_of_singular_edges_(0), singular_edges_(), number_of_contact_faces_(ses.contact_faces_.size()), contact_faces_(number_of_contact_faces_), number_of_toric_faces_(ses.toric_faces_.size()), toric_faces_(number_of_toric_faces_), number_of_spheric_faces_(ses.spheric_faces_.size()), spheric_faces_(number_of_spheric_faces_), reduced_surface_(NULL) { //for (Position i = 0; i < number_of_vertices_; i++) //{ // vertices_[i] = new SESVertex(*ses.vertices_[i],false); //} //for (Position i = 0; i < number_of_edges_; i++) //{ // edges_[i] = new SESVertex(*ses.edges_[i],false); //} //::std::list::const_iterator se; //for (se = ses.singular_edges_.begin(); se != ses.singular_edges_.end(); se++) //{ // singular_edges_.push_back(edges_[(*se)->index_]); //} //for (Position i = 0; i < number_of_contact_faces_; i++) //{ // contact_faces_[i] = new SESFace(*ses.contact_faces_[i],false); //} //for (Position i = 0; i < number_of_toric_faces_; i++) //{ // toric_faces_[i] = new SESFace(*ses.toric_faces_[i],false); //} //for (Position i = 0; i < number_of_spheric_faces_; i++) //{ // spheric_faces_[i] = new SESFace(*ses.spheric_faces_[i],false); //} } SolventExcludedSurface::SolventExcludedSurface (ReducedSurface* reduced_surface) throw() : number_of_vertices_(0), vertices_(), number_of_edges_(0), edges_(), number_of_singular_edges_(0), singular_edges_(), number_of_contact_faces_(0), contact_faces_(), number_of_toric_faces_(0), toric_faces_(), number_of_spheric_faces_(0), spheric_faces_(), reduced_surface_(reduced_surface) { } SolventExcludedSurface::~SolventExcludedSurface() throw() { clear(); } void SolventExcludedSurface::clear() { Position i; for (i = 0; i < number_of_vertices_; i++) { delete vertices_[i]; } for (i = 0; i < number_of_edges_; i++) { delete edges_[i]; } for (i = 0; i < number_of_contact_faces_; i++) { delete contact_faces_[i]; } for (i = 0; i < number_of_toric_faces_; i++) { delete toric_faces_[i]; } for (i = 0; i < number_of_spheric_faces_; i++) { delete spheric_faces_[i]; } vertices_.clear(); edges_.clear(); singular_edges_.clear(); contact_faces_.clear(); toric_faces_.clear(); spheric_faces_.clear(); number_of_vertices_ = 0; number_of_edges_ = 0; number_of_singular_edges_ = 0; number_of_contact_faces_ = 0; number_of_toric_faces_ = 0; number_of_spheric_faces_ = 0; } void SolventExcludedSurface::clean(const double& density) { SESFace* face(0); bool done = false; double sqrt_density = sqrt(density); while (!done) { done = true; for (Position i = 0; i < toric_faces_.size(); i++) { face = toric_faces_[i]; if (face != NULL) { if (!face->isFree()) { if (face->type_ == SESFace::TYPE_TORIC_SINGULAR) { if (cleanSingularToricFace(face,sqrt_density) == false) { done = false; } } else { if (cleanToricFace(face,sqrt_density) == false) { done = false; } } } } } } cleanVertices(); cleanEdges(); cleanContactFaces(); cleanToricFaces(); cleanSphericFaces(); } bool SolventExcludedSurface::cleanSingularToricFace (SESFace* face, const double& sqrt_density) throw() { face->normalize(true); std::list::iterator e = face->edge_.begin(); SESEdge* edge0 = *e; e++; e++; e++; SESEdge* edge3 = *e; std::list::iterator v = face->vertex_.begin(); SESVertex* v0 = *v; v++; v++; SESVertex* v2 = *v; v++; SESVertex* v3 = *v; v++; v++; SESVertex* v5 = *v; bool del = false; bool set = false; SESEdge* edge = NULL; if (v0 == v2) { del = (edge0->rsedge_->angle_.value < Constants::PI); set = !del; edge = edge0; } else { if (v3 == v5) { del = (edge3->rsedge_->angle_.value < Constants::PI); set = !del; edge = edge3; } else { double exact_number_of_segments(face->rsedge_->angle_.value* edge3->circle_.radius* sqrt_density); del = (Maths::isLess(exact_number_of_segments,0.1)); } } if (del) { deleteSmallSingularToricFace(face); } if (set) { edge->rsedge_->angle_.value = 2*Constants::PI; } return !del; } bool SolventExcludedSurface::cleanToricFace (SESFace* face, const double& sqrt_density) throw() { face->normalize(false); std::list::iterator e = face->edge_.begin(); e++; SESEdge* edge1 = *e; e++; e++; SESEdge* edge3 = *e; std::list::iterator v = face->vertex_.begin(); SESVertex* v0 = *v; v++; SESVertex* v1 = *v; v++; SESVertex* v2 = *v; v++; SESVertex* v3 = *v; bool del = false; bool set = false; SESEdge* edge = NULL; if (v0 == v3) { del = (edge3->rsedge_->angle_.value < Constants::PI); set = !del; edge = edge3; } else { if (v1 == v2) { del = (edge1->rsedge_->angle_.value < Constants::PI); set = !del; edge = edge1; } else { double exact_number_of_segments(face->rsedge_->angle_.value* edge3->circle_.radius* sqrt_density); del = (Maths::isLess(exact_number_of_segments,0.1)); } } if (del) { deleteSmallToricFace(face); } if (set) { edge->rsedge_->angle_.value = 2*Constants::PI; } return !del; } void SolventExcludedSurface::cleanVertices() throw() { while ((number_of_vertices_ > 0) && (vertices_[number_of_vertices_-1] == NULL)) { vertices_.pop_back(); number_of_vertices_--; } for (Position i = 0; i < number_of_vertices_; i++) { if (vertices_[i] == NULL) { vertices_[i] = vertices_[number_of_vertices_-1]; vertices_[i]->index_ = i; vertices_.pop_back(); number_of_vertices_--; while (vertices_[number_of_vertices_-1] == NULL) { vertices_.pop_back(); number_of_vertices_--; } } } } void SolventExcludedSurface::cleanEdges() throw() { while ((number_of_edges_ > 0) && (edges_[number_of_edges_-1] == NULL)) { edges_.pop_back(); number_of_edges_--; } for (Position i = 0; i < number_of_edges_; i++) { if (edges_[i] == NULL) { edges_[i] = edges_[number_of_edges_-1]; edges_[i]->index_ = i; edges_.pop_back(); number_of_edges_--; while (edges_[number_of_edges_-1] == NULL) { edges_.pop_back(); number_of_edges_--; } } } } void SolventExcludedSurface::cleanContactFaces() throw() { while ((number_of_contact_faces_ > 0) && (contact_faces_[number_of_contact_faces_-1] == NULL)) { contact_faces_.pop_back(); number_of_contact_faces_--; } for (Position i = 0; i < number_of_contact_faces_; i++) { if (contact_faces_[i] == NULL) { contact_faces_[i] = contact_faces_[number_of_contact_faces_-1]; contact_faces_[i]->index_ = i; contact_faces_.pop_back(); number_of_contact_faces_--; while (contact_faces_[number_of_contact_faces_-1] == NULL) { contact_faces_.pop_back(); number_of_contact_faces_--; } } } } void SolventExcludedSurface::cleanToricFaces() throw() { while ((number_of_toric_faces_ > 0) && (toric_faces_[number_of_toric_faces_-1] == NULL)) { toric_faces_.pop_back(); number_of_toric_faces_--; } for (Position i = 0; i < number_of_toric_faces_; i++) { if (toric_faces_[i] == NULL) { toric_faces_[i] = toric_faces_[number_of_toric_faces_-1]; toric_faces_[i]->index_ = i; toric_faces_.pop_back(); number_of_toric_faces_--; while (toric_faces_[number_of_toric_faces_-1] == NULL) { toric_faces_.pop_back(); number_of_toric_faces_--; } } } } void SolventExcludedSurface::cleanSphericFaces() throw() { while ((number_of_spheric_faces_ > 0) && (spheric_faces_[number_of_spheric_faces_-1] == NULL)) { spheric_faces_.pop_back(); number_of_spheric_faces_--; } for (Position i = 0; i < number_of_spheric_faces_; i++) { if (spheric_faces_[i] == NULL) { spheric_faces_[i] = spheric_faces_[number_of_spheric_faces_-1]; spheric_faces_[i]->index_ = i; spheric_faces_.pop_back(); number_of_spheric_faces_--; while (spheric_faces_[number_of_spheric_faces_-1] == NULL) { spheric_faces_.pop_back(); number_of_spheric_faces_--; } } } } void SolventExcludedSurface::deleteSmallToricFace(SESFace* face) throw() { SESEdge* edge[4]; std::list::iterator e = face->edge_.begin(); for (Position i = 0; i < 4; i++) { edge[i] = *e; e++; } SESVertex* p[4]; std::list::iterator v = face->vertex_.begin(); for (Position i = 0; i < 4; i++) { p[i] = *v; v++; } SESFace* neighbour1 = edge[1]->other(face); SESFace* neighbour2 = edge[2]->other(face); SESFace* neighbour3 = edge[3]->other(face); if (p[0] != p[3]) { p[0]->join(*p[3]); neighbour3->vertex_.remove(p[3]); p[3]->substitute(p[0]); } if (p[1] != p[2]) { p[1]->join(*p[2]); neighbour1->vertex_.remove(p[2]); p[2]->substitute(p[1]); } p[0]->edges_.erase(edge[2]); p[0]->edges_.erase(edge[3]); p[1]->edges_.erase(edge[2]); p[1]->edges_.erase(edge[1]); p[0]->faces_.erase(face); p[1]->faces_.erase(face); edge[0]->substitute(face,neighbour2); neighbour2->substitute(edge[2],edge[0]); if (p[2] != p[1]) { vertices_[p[2]->index_] = NULL; neighbour1->edge_.remove(edge[1]); delete p[2]; } else { p[1]->faces_.erase(neighbour1); contact_faces_[neighbour1->index_] = NULL; delete neighbour1; } if (p[3] != p[0]) { vertices_[p[3]->index_] = NULL; neighbour3->edge_.remove(edge[3]); delete p[3]; } else { p[0]->faces_.erase(neighbour3); contact_faces_[neighbour3->index_] = NULL; delete neighbour3; } edges_[edge[1]->index_] = NULL; delete edge[1]; edges_[edge[2]->index_] = NULL; delete edge[2]; edges_[edge[3]->index_] = NULL; delete edge[3]; toric_faces_[face->index_] = NULL; delete face; edge[0]->type_ = SESEdge::TYPE_SINGULAR; TAngle phi (getOrientedAngle(edge[0]->vertex_[0]->point_-edge[0]->circle_.p, edge[0]->vertex_[1]->point_-edge[0]->circle_.p, edge[0]->circle_.n)); if (phi.value > Constants::PI) { edge[0]->circle_.n.negate(); } singular_edges_.push_back(edge[0]); } void SolventExcludedSurface::deleteSmallSingularToricFace (SESFace* face) throw() { SESEdge* edge[6]; std::list::iterator e = face->edge_.begin(); for (Position i = 0; i < 6; i++) { edge[i] = *e; e++; } SESVertex* p[6]; std::list::iterator v = face->vertex_.begin(); for (Position i = 0; i < 6; i++) { p[i] = *v; v++; } SESFace* neighbour0 = edge[0]->other(face); SESFace* neighbour2 = edge[2]->other(face); SESFace* neighbour3 = edge[3]->other(face); SESFace* neighbour5 = edge[5]->other(face); if (p[0] != p[2]) { p[0]->join(*p[2]); neighbour0->vertex_.remove(p[2]); p[2]->substitute(p[0]); } if (p[3] != p[5]) { p[3]->join(*p[5]); neighbour3->vertex_.remove(p[5]); p[5]->substitute(p[3]); } p[0]->edges_.erase(edge[0]); p[0]->edges_.erase(edge[2]); p[1]->edges_.erase(edge[2]); p[3]->edges_.erase(edge[3]); p[3]->edges_.erase(edge[5]); p[4]->edges_.erase(edge[5]); p[0]->faces_.erase(face); p[1]->faces_.erase(face); p[3]->faces_.erase(face); p[4]->faces_.erase(face); edge[1]->substitute(face,neighbour2); edge[4]->substitute(face,neighbour5); neighbour2->substitute(edge[2],edge[1]); neighbour5->substitute(edge[5],edge[4]); if (p[2] != p[0]) { vertices_[p[2]->index_] = NULL; neighbour0->edge_.remove(edge[0]); delete p[2]; } else { p[0]->faces_.erase(neighbour0); contact_faces_[neighbour0->index_] = NULL; delete neighbour0; } if (p[3] != p[5]) { vertices_[p[5]->index_] = NULL; neighbour3->edge_.remove(edge[3]); delete p[5]; } else { p[3]->faces_.erase(neighbour3); contact_faces_[neighbour3->index_] = NULL; delete neighbour3; } edges_[edge[0]->index_] = NULL; delete edge[0]; edges_[edge[2]->index_] = NULL; delete edge[2]; edges_[edge[3]->index_] = NULL; delete edge[3]; edges_[edge[5]->index_] = NULL; delete edge[5]; toric_faces_[face->index_] = NULL; delete face; edge[1]->type_ = SESEdge::TYPE_SINGULAR; TAngle phi (getOrientedAngle(edge[1]->vertex_[0]->point_-edge[1]->circle_.p, edge[1]->vertex_[1]->point_-edge[1]->circle_.p, edge[1]->circle_.n)); if (phi.value > Constants::PI) { edge[1]->circle_.n.negate(); } edge[4]->type_ = SESEdge::TYPE_SINGULAR; phi = getOrientedAngle(edge[4]->vertex_[0]->point_-edge[4]->circle_.p, edge[4]->vertex_[1]->point_-edge[4]->circle_.p, edge[4]->circle_.n); if (phi.value > Constants::PI) { edge[4]->circle_.n.negate(); } singular_edges_.push_back(edge[1]); singular_edges_.push_back(edge[4]); } void SolventExcludedSurface::compute() throw(Exception::GeneralException) { SESComputer sesc(this); sesc.run(); } void SolventExcludedSurface::splitSphericFaces() throw() { for (Position i = 0; i < number_of_spheric_faces_; i++) { splitSphericFace(i); } } void SolventExcludedSurface::splitSphericFace(Position i) throw() { SESFace* face = spheric_faces_[i]; std::list::iterator e = face->edge_.begin(); while (e != face->edge_.end()) { if ((*e)->vertex_[0] == NULL) { return; } e++; } std::list contour; std::list vertices; e = face->edge_.begin(); SESVertex* start = (*e)->vertex_[0]; SESVertex* next = (*e)->vertex_[1]; SESEdge* current = *e; contour.push_back(current); vertices.push_back(next); while (next != start) { for (e = face->edge_.begin(); e != face->edge_.end(); e++) { if (*e != current) { if ((*e)->vertex_[0] == next) { contour.push_back(*e); next = (*e)->vertex_[1]; vertices.push_back(next); current = *e; } else { if ((*e)->vertex_[1] == next) { contour.push_back(*e); next = (*e)->vertex_[0]; vertices.push_back(next); current = *e; } } } } } if (contour.size() != face->edge_.size()) { SESFace* new_face = new SESFace(*face,true); for (e = contour.begin(); e != contour.end(); e++) { new_face->edge_.remove(*e); } std::list::iterator v; for (v = vertices.begin(); v != vertices.end(); v++) { new_face->vertex_.remove(*v); } new_face->index_ = number_of_spheric_faces_; spheric_faces_.push_back(new_face); number_of_spheric_faces_++; face->edge_ = contour; face->vertex_ = vertices; } } bool SolventExcludedSurface::check() throw() { for (Position i = 0; i < number_of_vertices_; i++) { if (vertices_[i]->edges_.size() != vertices_[i]->faces_.size()) { return false; } } for (Position i = 0; i < number_of_spheric_faces_; i++) { if (spheric_faces_[i]->edge_.size() != spheric_faces_[i]->vertex_.size()) { Index test = spheric_faces_[i]->edge_.size()- spheric_faces_[i]->vertex_.size(); std::list::iterator e = spheric_faces_[i]->edge_.begin(); while (e != spheric_faces_[i]->edge_.end()) { if ((*e)->vertex_[0] == NULL) { test--; } e++; } if (test != 0) { return false; } } } return true; } SolventExcludedSurface::VertexIterator SolventExcludedSurface::beginVertex() throw() { return vertices_.begin(); } SolventExcludedSurface::ConstVertexIterator SolventExcludedSurface::beginVertex() const throw() { return vertices_.begin(); } SolventExcludedSurface::VertexIterator SolventExcludedSurface::endVertex() throw() { return vertices_.end(); } SolventExcludedSurface::ConstVertexIterator SolventExcludedSurface::endVertex() const throw() { return vertices_.end(); } SolventExcludedSurface::EdgeIterator SolventExcludedSurface::beginEdge() throw() { return edges_.begin(); } SolventExcludedSurface::ConstEdgeIterator SolventExcludedSurface::beginEdge() const throw() { return edges_.begin(); } SolventExcludedSurface::EdgeIterator SolventExcludedSurface::endEdge() throw() { return edges_.end(); } SolventExcludedSurface::ConstEdgeIterator SolventExcludedSurface::endEdge() const throw() { return edges_.end(); } SolventExcludedSurface::SingularEdgeIterator SolventExcludedSurface::beginSingularEdge() throw() { return singular_edges_.begin(); } SolventExcludedSurface::ConstSingularEdgeIterator SolventExcludedSurface::beginSingularEdge() const throw() { return singular_edges_.begin(); } SolventExcludedSurface::SingularEdgeIterator SolventExcludedSurface::endSingularEdge() throw() { return singular_edges_.end(); } SolventExcludedSurface::ConstSingularEdgeIterator SolventExcludedSurface::endSingularEdge() const throw() { return singular_edges_.end(); } SolventExcludedSurface::ContactFaceIterator SolventExcludedSurface::beginContactFace() throw() { return contact_faces_.begin(); } SolventExcludedSurface::ConstContactFaceIterator SolventExcludedSurface::beginContactFace() const throw() { return contact_faces_.begin(); } SolventExcludedSurface::ContactFaceIterator SolventExcludedSurface::endContactFace() throw() { return contact_faces_.end(); } SolventExcludedSurface::ConstContactFaceIterator SolventExcludedSurface::endContactFace() const throw() { return contact_faces_.end(); } SolventExcludedSurface::SphericFaceIterator SolventExcludedSurface::beginSphericFace() throw() { return spheric_faces_.begin(); } SolventExcludedSurface::ConstSphericFaceIterator SolventExcludedSurface::beginSphericFace() const throw() { return spheric_faces_.begin(); } SolventExcludedSurface::SphericFaceIterator SolventExcludedSurface::endSphericFace() throw() { return spheric_faces_.end(); } SolventExcludedSurface::ConstSphericFaceIterator SolventExcludedSurface::endSphericFace() const throw() { return spheric_faces_.end(); } SolventExcludedSurface::ToricFaceIterator SolventExcludedSurface::beginToricFace() throw() { return toric_faces_.begin(); } SolventExcludedSurface::ConstToricFaceIterator SolventExcludedSurface::beginToricFace() const throw() { return toric_faces_.begin(); } SolventExcludedSurface::ToricFaceIterator SolventExcludedSurface::endToricFace() throw() { return toric_faces_.end(); } SolventExcludedSurface::ConstToricFaceIterator SolventExcludedSurface::endToricFace() const throw() { return toric_faces_.end(); } std::ostream& operator << (std::ostream& s, const SolventExcludedSurface& ses) { s << "Vertices:\n"; SolventExcludedSurface::ConstVertexIterator v; for (v = ses.beginVertex(); v != ses.endVertex(); v++) { if (*v != NULL) { s << " " << **v << "\n"; } else { s << " --\n"; } } s << "Edges:\n"; SolventExcludedSurface::ConstEdgeIterator e; for (e = ses.beginEdge(); e != ses.endEdge(); e++) { if (*e != NULL) { s << " " << **e << "\n"; } else { s << " --\n"; } } s << "singular Edges:\n"; SolventExcludedSurface::ConstSingularEdgeIterator se; for (se = ses.beginSingularEdge(); se != ses.endSingularEdge(); se++) { if (*se != NULL) { s << " " << **se << "\n"; } else { s << " --\n"; } } s << "contact Faces:\n"; SolventExcludedSurface::ConstContactFaceIterator cf; for (cf = ses.beginContactFace(); cf != ses.endContactFace(); cf++) { if (*cf != NULL) { s << " " << **cf << "\n"; } else { s << " --\n"; } } s << "toric Faces:\n"; SolventExcludedSurface::ConstToricFaceIterator tf; for (tf = ses.beginToricFace(); tf != ses.endToricFace(); tf++) { if (*tf != NULL) { s << " " << **tf << "\n"; } else { s << " --\n"; } } s << "spheric Faces:\n"; SolventExcludedSurface::ConstSphericFaceIterator sf; for (sf = ses.beginSphericFace(); sf != ses.endSphericFace(); sf++) { if (*sf != NULL) { s << " " << **sf << "\n"; } else { s << " --\n"; } } return s; } /////////////////////////////// SESComputer::SESComputer() throw() : ses_(), vertex_grid_() { } SESComputer::SESComputer(SolventExcludedSurface* ses) throw() : ses_(ses), vertex_grid_() { } SESComputer::~SESComputer() throw() { } void SESComputer::run() throw(Exception::GeneralException) { preProcessing(); get(); SESSingularityCleaner sessc(ses_,&vertex_grid_); while (!sessc.run()) { ses_->clear(); vertex_grid_.clear(); preProcessing(); get(); sessc.vertex_grid_ = &vertex_grid_; } } void SESComputer::preProcessing() throw() { ses_->clear(); ses_->number_of_contact_faces_ = ses_->reduced_surface_->number_of_vertices_; ses_->number_of_toric_faces_ = ses_->reduced_surface_->number_of_edges_; ses_->number_of_spheric_faces_ = ses_->reduced_surface_->number_of_faces_; SESFace* face; Position i; for (i = 0; i < ses_->number_of_contact_faces_; i++) { face = new SESFace; face->type_ = SESFace::TYPE_CONTACT; face->rsvertex_ = ses_->reduced_surface_->vertices_[i]; face->rsedge_ = NULL; face->rsface_ = NULL; face->index_ = i; ses_->contact_faces_.push_back(face); } for (i = 0; i < ses_->number_of_toric_faces_; i++) { face = new SESFace; face->type_ = SESFace::TYPE_TORIC; face->rsvertex_ = NULL; face->rsedge_ = ses_->reduced_surface_->edges_[i]; face->rsface_ = NULL; face->index_ = i; ses_->toric_faces_.push_back(face); } for (i = 0; i < ses_->number_of_spheric_faces_; i++) { face = new SESFace; face->type_ = SESFace::TYPE_SPHERIC; face->rsvertex_ = NULL; face->rsedge_ = NULL; face->rsface_ = ses_->reduced_surface_->faces_[i]; face->index_ = i; ses_->spheric_faces_.push_back(face); } double x_min = ses_->reduced_surface_->bounding_box_.a.x; double y_min = ses_->reduced_surface_->bounding_box_.a.y; double z_min = ses_->reduced_surface_->bounding_box_.a.z; double x_max = ses_->reduced_surface_->bounding_box_.b.x; double y_max = ses_->reduced_surface_->bounding_box_.b.y; double z_max = ses_->reduced_surface_->bounding_box_.b.z; double dist = ses_->reduced_surface_->r_max_/3; Position nx = (Position)((x_max-x_min)/dist+5); Position ny = (Position)((y_max-y_min)/dist+5); Position nz = (Position)((z_max-z_min)/dist+5); Vector3 origin(x_min-2*dist,y_min-2*dist,z_min-2*dist); vertex_grid_ = HashGrid3(origin,nx,ny,nz,dist); } void SESComputer::get() throw() { for (Position i = 0; i < ses_->number_of_spheric_faces_; i++) { createSphericFace(i); } for (Position i = 0; i < ses_->number_of_toric_faces_; i++) { createToricFace(i); } } void SESComputer::createSphericFace(Position j) throw() { SESFace* face = ses_->spheric_faces_[j]; RSFace* rsface = face->rsface_; double probe_radius = ses_->reduced_surface_->probe_radius_; TSphere3 probe(rsface->center_,probe_radius); // create three vertices and push them to their faces // and in the list of vertices pushVertex(face,probe,rsface->vertex_[0]); pushVertex(face,probe,rsface->vertex_[1]); pushVertex(face,probe,rsface->vertex_[2]); // create three concace edges and push them to their faces // and in the list of edges pushConcaveEdge(face,0,1,probe_radius); pushConcaveEdge(face,1,2,probe_radius); pushConcaveEdge(face,2,0,probe_radius); } void SESComputer::pushVertex (SESFace* face, const TSphere3& probe, RSVertex* rsvertex) throw() { // Create a new vertex on the correct position ... SESVertex* vertex(createVertex(probe.p,rsvertex->atom_)); // ... and push it to the face's vertices. face->vertex_.push_back(vertex); vertex->faces_.insert(face); // Get the RSEdges of the corresponding RSVertex ... RSEdge* tf1(0); RSEdge* tf2(0); face->rsface_->getEdges(rsvertex,tf1,tf2); // ... and push the vertex to these toric faces. ses_->toric_faces_[tf1->index_]->vertex_.push_back(vertex); vertex->faces_.insert(ses_->toric_faces_[tf1->index_]); ses_->toric_faces_[tf2->index_]->vertex_.push_back(vertex); vertex->faces_.insert(ses_->toric_faces_[tf2->index_]); // Push the vertex to the contact face of the corresponding RSVertex ... ses_->contact_faces_[rsvertex->index_]->vertex_.push_back(vertex); vertex->faces_.insert(ses_->contact_faces_[rsvertex->index_]); // ... and to the vertices of the SES. ses_->vertices_.push_back(vertex); Vector3 pos(vertex->point_.x, vertex->point_.y, vertex->point_.z); vertex_grid_.insert(pos,vertex->index_); ses_->number_of_vertices_++; } void SESComputer::pushConcaveEdge (SESFace* face, Position p1, Position p2, const double& radius_of_probe) throw() { RSFace* rsface = face->rsface_; RSEdge* rsedge(0); // get the corresponding RSEdge rsface->getEdge(rsface->getVertex(p1),rsface->getVertex(p2),rsedge); Index index = rsedge->index_; // create a new SESEdge SESEdge* edge(createConcaveEdge(face,p1,p2,index,radius_of_probe)); // and push it to all it's places face->edge_.push_back(edge); ses_->toric_faces_[index]->edge_.push_back(edge); edge->vertex_[0]->edges_.insert(edge); edge->vertex_[1]->edges_.insert(edge); ses_->edges_.push_back(edge); ses_->number_of_edges_++; } SESVertex* SESComputer::createVertex (const TVector3& probe_center, Index index) throw() { SESVertex* vertex = new SESVertex; TSphere3* atom = &(ses_->reduced_surface_->atom_[index]); // get the position of the new vertex getPoint(atom->p,probe_center,atom->radius,vertex->point_); vertex->normal_.set(probe_center-vertex->point_); vertex->atom_ = index; vertex->index_ = ses_->number_of_vertices_; return vertex; } SESEdge* SESComputer::createConcaveEdge (SESFace* face, Position p1, Position p2, Index index, const double& radius_of_probe) throw() { SESEdge* edge = new SESEdge; // set the vertices of the edge std::list::iterator v = face->vertex_.begin(); for (Position i = 0; i < p1; i++) { v++; } edge->vertex_[0] = *v; v = face->vertex_.begin(); for (Position i = 0; i < p2; i++) { v++; } edge->vertex_[1] = *v; // set the faces of the edge edge->face_[0] = face; edge->face_[1] = ses_->toric_faces_[index]; // edge->rsedge_ = NULL; edge->type_ = SESEdge::TYPE_CONCAVE; edge->index_ = ses_->number_of_edges_; // compute the circle on which the edge lies RSFace* rsface = face->rsface_; TVector3 normal = (edge->vertex_[0]->point_-rsface->center_)% (edge->vertex_[1]->point_-rsface->center_); edge->circle_.set(rsface->center_,normal,radius_of_probe); return edge; } void SESComputer::createToricFace(Position i) throw() { SESFace* face = ses_->toric_faces_[i]; if (face->isFree()) { createFreeToricFace(i); } else { SESEdge* edge1 = createConvexEdge(face,face->rsedge_->vertex_[0]); SESEdge* edge2 = createConvexEdge(face,face->rsedge_->vertex_[1]); if (Maths::isEqual(face->rsedge_->angle_.value,Constants::PI)) { RSFace* rsface1 = face->rsedge_->face_[0]; RSFace* rsface2 = face->rsedge_->face_[1]; RSVertex* rsvertex1 = face->rsedge_->vertex_[0]; RSVertex* rsvertex2 = face->rsedge_->vertex_[1]; RSVertex* rsvertex3 = rsface1->third(rsvertex1,rsvertex2); RSVertex* rsvertex4 = rsface2->third(rsvertex1,rsvertex2); TVector3 point1(ses_->reduced_surface_->atom_[rsvertex1->atom_].p); TVector3 point2(ses_->reduced_surface_->atom_[rsvertex2->atom_].p); TVector3 point3(ses_->reduced_surface_->atom_[rsvertex3->atom_].p); TVector3 point4(ses_->reduced_surface_->atom_[rsvertex4->atom_].p); TVector3 middle(edge1->circle_.n% (edge1->vertex_[0]->point_-edge1->circle_.p)); middle.normalize(); middle *= edge1->circle_.radius; middle += edge1->circle_.p; TPlane3 plane(point1,point2,rsface1->center_); double test = plane.n*(point3-plane.p); if (test*(plane.n*(middle-plane.p)) > 0) { edge1->revert(); } middle.set(edge2->circle_.n% (edge2->vertex_[0]->point_-edge2->circle_.p)); middle.normalize(); middle *= edge2->circle_.radius; middle += edge2->circle_.p; if (test*(plane.n*(middle-plane.p)) > 0) { edge2->revert(); } } if (face->rsedge_->singular_) { treatSingularToricFace(i); } } } SESEdge* SESComputer::createConvexEdge (SESFace* face, RSVertex* rsvertex) throw() { SESEdge* edge = new SESEdge; Index atom = rsvertex->atom_; Index index = rsvertex->index_; // find the first vertex of the toric face // which lies on the surface of the rsvertex std::list::iterator v = face->vertex_.begin(); while ((*v)->atom_ != atom) { v++; } edge->vertex_[0] = *v; // find the second vertex of the toric face // which lies on the surface of the rsvertex v++; while ((*v)->atom_ != atom) { v++; } edge->vertex_[1] = *v; // set the faces of the edge edge->face_[0] = face; edge->face_[1] = ses_->contact_faces_[index]; // set the rsedge, type and index of the edge edge->rsedge_ = face->rsedge_; edge->type_ = SESEdge::TYPE_CONVEX; edge->index_ = ses_->number_of_edges_; // compute the circle on which the edge lies TCircle3 circle0(edge->rsedge_->circle0_); TCircle3 circle1(edge->rsedge_->circle1_); if (edge->rsedge_->vertex_[0]->index_ == index) { edge->circle_.set(circle0.p,circle0.p-circle1.p,circle0.radius); } else { edge->circle_.set(circle1.p,circle1.p-circle0.p,circle1.radius); } TVector3 v1(edge->vertex_[0]->point_-edge->circle_.p); TVector3 v2(edge->vertex_[1]->point_-edge->circle_.p); TVector3 n(edge->circle_.n); TAngle test_phi(getOrientedAngle(v1,v2,n)); if ((test_phi.value-Constants::PI)* (edge->rsedge_->angle_.value-Constants::PI) < 0) { // test_phi smaller than PI, but expected to be greater or // test_phi greater than PI, but expected to be smaller edge->revert(); } face->edge_.push_back(edge); ses_->contact_faces_[index]->edge_.push_back(edge); edge->vertex_[0]->edges_.insert(edge); edge->vertex_[1]->edges_.insert(edge); ses_->edges_.push_back(edge); ses_->number_of_edges_++; return edge; } void SESComputer::treatSingularToricFace(Position i) throw() { SESFace* face = ses_->toric_faces_[i]; face->normalize(false); SESEdge* edge[4]; std::list::iterator e = face->edge_.begin(); for (Position i = 0; i < 4; i++) { edge[i] = *e; e++; } SESVertex* p[4]; std::list::iterator v = face->vertex_.begin(); for (Position i = 0; i < 4; i++) { p[i] = *v; v++; } // compute the circle on which the singular edge lies SESFace* neighbour0 = edge[0]->other(face); SESFace* neighbour2 = edge[2]->other(face); double probe_radius = ses_->reduced_surface_->probe_radius_; TSphere3 probe1(neighbour0->rsface_->center_,probe_radius); TSphere3 probe2(neighbour2->rsface_->center_,probe_radius); TCircle3 intersection_circle; GetIntersection(probe1,probe2,intersection_circle); // create the new edges SESEdge* new_edge0 = new SESEdge(*edge[0],true); SESEdge* new_edge2 = new SESEdge(*edge[2],true); SESEdge* new_edge = new SESEdge(NULL,NULL,neighbour0,neighbour2, intersection_circle,face->rsedge_, SESEdge::TYPE_SINGULAR,-1); // create the new points Position ip1 = ((p[1]->atom_ == face->rsedge_->vertex_[0]->atom_) ? 0 : 1); Position ip3 = 1-ip1; SESVertex* new_point1 = createSingularVertex(ip3,intersection_circle.p, face,neighbour0,neighbour2, edge[0],edge[2],new_edge); SESVertex* new_point3 = createSingularVertex(ip1,intersection_circle.p, face,neighbour0,neighbour2, new_edge0,new_edge2,new_edge); // update the new edges updateEdge(edge[0],p[0],new_point1,false); updateEdge(edge[2],p[3],new_point1,false); updateEdge(new_edge0,p[1],new_point3,true); updateEdge(new_edge2,p[2],new_point3,true); // update the singular edge updateEdge(new_edge,new_point3,new_point1,true); ses_->singular_edges_.push_back(new_edge); ses_->number_of_singular_edges_++; // swap normal of new edge if necessary TAngle phi(getOrientedAngle(new_point1->point_-intersection_circle.p, new_point3->point_-intersection_circle.p, intersection_circle.n)); if ((face->rsedge_->angle_.value-Constants::PI)* (phi.value -Constants::PI) < 0) { new_edge->circle_.n.negate(); } // update the neighbour faces neighbour0->edge_.push_back(new_edge0); neighbour0->edge_.push_back(new_edge); neighbour0->vertex_.push_back(new_point1); neighbour0->vertex_.push_back(new_point3); neighbour2->edge_.push_back(new_edge2); neighbour2->edge_.push_back(new_edge); neighbour2->vertex_.push_back(new_point1); neighbour2->vertex_.push_back(new_point3); // update the toric face face->type_ = SESFace::TYPE_TORIC_SINGULAR; face->vertex_.push_back(new_point1); face->vertex_.push_back(new_point3); face->edge_.push_back(new_edge0); face->edge_.push_back(new_edge2); // update the vertices p[1]->edges_.erase(edge[0]); p[1]->edges_.insert(new_edge0); p[2]->edges_.erase(edge[2]); p[2]->edges_.insert(new_edge2); } SESVertex* SESComputer::createSingularVertex (Position ip, const TVector3& dir, SESFace* face0, SESFace* face1, SESFace* face2, SESEdge* edge0, SESEdge* edge1, SESEdge* edge2) throw() { SESVertex* vertex(0); TVector3 intersection_point(face0->rsedge_->getIntersectionPoint(ip)); Index test = vertexExists(intersection_point); if (test == -1) { vertex = new SESVertex(intersection_point, dir-intersection_point, face0->rsedge_->getVertex(ip)->atom_, ses_->number_of_vertices_); ses_->vertices_.push_back(vertex); Vector3 pos(vertex->point_.x, vertex->point_.y, vertex->point_.z); vertex_grid_.insert(pos,vertex->index_); ses_->number_of_vertices_++; } else { vertex = ses_->vertices_[test]; } vertex->edges_.insert(edge0); vertex->edges_.insert(edge1); vertex->edges_.insert(edge2); vertex->faces_.insert(face0); vertex->faces_.insert(face1); vertex->faces_.insert(face2); return vertex; } void SESComputer::updateEdge (SESEdge* edge, SESVertex* vertex1, SESVertex* vertex2, bool is_new) throw() { if (edge->vertex_[0] == vertex1) { edge->vertex_[0] = vertex1; edge->vertex_[1] = vertex2; } else { edge->vertex_[0] = vertex2; edge->vertex_[1] = vertex1; } if (is_new) { edge->index_ = ses_->number_of_edges_; ses_->edges_.push_back(edge); ses_->number_of_edges_++; } } void SESComputer::createFreeToricFace(Position i) throw() { SESFace* face(ses_->toric_faces_[i]); TCircle3 circle1(face->rsedge_->circle0_); TCircle3 circle2(face->rsedge_->circle1_); Index index1(face->rsedge_->vertex_[0]->index_); Index index2(face->rsedge_->vertex_[1]->index_); SESEdge* edge = new SESEdge; edge->type_ = SESEdge::TYPE_CONVEX; edge->vertex_[0] = NULL; edge->vertex_[1] = NULL; edge->rsedge_ = face->rsedge_; edge->face_[0] = face; edge->face_[1] = ses_->contact_faces_[index1]; edge->circle_.set(circle1.p,circle1.p-circle2.p,circle1.radius); edge->index_ = ses_->number_of_edges_; face->edge_.push_back(edge); ses_->contact_faces_[index1]->edge_.push_back(edge); ses_->edges_.push_back(edge); ses_->number_of_edges_++; edge = new SESEdge; edge->type_ = SESEdge::TYPE_CONVEX; edge->vertex_[0] = NULL; edge->vertex_[1] = NULL; edge->rsedge_ = face->rsedge_; edge->face_[0] = face; edge->face_[1] = ses_->contact_faces_[index2]; edge->circle_.set(circle2.p,circle2.p-circle1.p,circle2.radius); edge->index_ = ses_->number_of_edges_; face->edge_.push_back(edge); ses_->contact_faces_[index2]->edge_.push_back(edge); ses_->edges_.push_back(edge); ses_->number_of_edges_++; } void SESComputer::getPoint (const TVector3& p1, const TVector3& p2, const double& dist, TVector3& result) throw() { result.set(p2-p1); result.normalize(); result *= dist; result += p1; } Index SESComputer::vertexExists(const TVector3& point) throw() { double epsilon = Constants::EPSILON; Constants::EPSILON = 0.001; Vector3 p(point.x,point.y,point.z); HashGridBox3* box = vertex_grid_.getBox(p); HashGridBox3::ConstBoxIterator b; HashGridBox3::ConstDataIterator d; if (box != NULL) { for (b = box->beginBox(); b != box->endBox(); b++) { for (d = b->beginData(); d != b->endData(); d++) { if (ses_->vertices_[*d]->point_ == point) { Constants::EPSILON = epsilon; return *d; } } } } Constants::EPSILON = epsilon; return -1; } /////////////////////////////// SESSingularityCleaner::SESSingularityCleaner() throw() : ses_(), vertex_grid_(), probe_intersections_() { } SESSingularityCleaner::SESSingularityCleaner (SolventExcludedSurface* ses, HashGrid3* vertex_grid) throw() : ses_(ses), vertex_grid_(vertex_grid), probe_intersections_() { } SESSingularityCleaner::~SESSingularityCleaner() throw() { // delete probe_intersections HashMap< Position, HashMap< Position, HashMap< Position, ProbeIntersection* > > >::Iterator pi1; HashMap< Position, HashMap< Position, ProbeIntersection* > >::Iterator pi2; HashMap< Position,ProbeIntersection* >::Iterator pi3; for (pi1 = probe_intersections_.begin(); pi1 != probe_intersections_.end(); pi1++) { for (pi2 = pi1->second.begin(); pi2 != pi1->second.end(); pi2++) { for (pi3 = pi2->second.begin(); pi3 != pi2->second.end(); pi3++) { delete pi3->second; } } } } bool SESSingularityCleaner::run() throw(Exception::GeneralException) { if (!treatFirstCategory()) { return false; } if (ses_->number_of_singular_edges_ > 0) { treatSecondCategory(); } return true; } bool SESSingularityCleaner::treatFirstCategory() throw() { std::list first_category_faces; getFirstCategoryFaces(first_category_faces); SESFace* face1(0); SESFace* face2(0); bool modified = false; std::list::iterator f = first_category_faces.begin(); while (f != first_category_faces.end()) { face1 = *f; f++; face2 = *f; f++; switch (face1->edge_.size()) { case 3 : noCut(face1,face2); break; case 5 : break; case 7 : twoCuts(face1,face2); break; case 9 : ses_->reduced_surface_->deleteSimilarFaces(face1->rsface_, face2->rsface_); modified = true; break; } } if (modified) { ses_->reduced_surface_->clean(); return false; } else { return true; } } void SESSingularityCleaner::getFirstCategoryFaces (std::list& first_category_faces) throw() { std::list singular_faces; getSingularFaces(singular_faces); while (!singular_faces.empty()) { SESFace* current = singular_faces.front(); singular_faces.pop_front(); std::list::iterator i = singular_faces.begin(); while (i != singular_faces.end()) { if (*current->rsface_ *= *((*i)->rsface_)) { first_category_faces.push_back(current); first_category_faces.push_back(*i); singular_faces.erase(i); i = singular_faces.end(); } else { i++; } } } } void SESSingularityCleaner::getSingularFaces (std::list& faces) throw() { for (Position i = 0; i < ses_->number_of_spheric_faces_; i++) { if (ses_->spheric_faces_[i]->rsface_->singular_ == true) { faces.push_back(ses_->spheric_faces_[i]); } } } void SESSingularityCleaner::noCut (SESFace* face1, SESFace* face2) throw() { TCircle3 circle; double probe_radius = ses_->reduced_surface_->probe_radius_; TSphere3 s1(face1->rsface_->center_,probe_radius); TSphere3 s2(face2->rsface_->center_,probe_radius); GetIntersection(s1,s2,circle); // test whether the circle is really an edge TVector3 normal(face1->rsface_->normal_); TVector3 point1(ses_->reduced_surface_ ->atom_[face1->rsface_->vertex_[0]->atom_].p); TVector3 point2(ses_->reduced_surface_ ->atom_[face1->rsface_->vertex_[1]->atom_].p); TVector3 point3(ses_->reduced_surface_ ->atom_[face1->rsface_->vertex_[2]->atom_].p); TVector3 u(normal%(point1-point2)); TVector3 v(normal%(point2-point3)); TVector3 w(normal%(point3-point1)); TVector3 diff1(point1-circle.p); TVector3 diff2(point2-circle.p); double test1 = u*diff1; double test2 = v*diff2; double test3 = w*diff1; if ((Maths::isLess(test1,0.0) && Maths::isLess(test2,0.0) && Maths::isLess(test3,0.0) ) || (Maths::isGreater(test1,0.0) && Maths::isGreater(test2,0.0) && Maths::isGreater(test3,0.0) ) ) { SESEdge* edge = new SESEdge(NULL,NULL,face1,face2,circle,NULL, SESEdge::TYPE_SINGULAR, ses_->number_of_edges_); ses_->edges_.push_back(edge); ses_->singular_edges_.push_back(edge); ses_->number_of_edges_++; face1->edge_.push_back(edge); face2->edge_.push_back(edge); } } void SESSingularityCleaner::twoCuts (SESFace* face1, SESFace* face2) throw() { std::vector sesedge1(7); std::vector sesedge2(7); std::vector sesvertex1(7); std::vector sesvertex2(7); sort(face1,face2,sesedge1,sesedge2,sesvertex1,sesvertex2); TCircle3 circle; TSphere3 sphere1(face1->rsface_->center_, ses_->reduced_surface_->probe_radius_); TSphere3 sphere2(face2->rsface_->center_, ses_->reduced_surface_->probe_radius_); GetIntersection(sphere1,sphere2,circle); TAngle phi(getOrientedAngle(sesvertex1[0]->point_-circle.p, sesvertex1[2]->point_-circle.p, circle.n)); if (phi.value > Constants::PI) { circle.n.negate(); } SESEdge* new_edge1 = new SESEdge(sesvertex1[0],sesvertex1[2],face1,face2, circle,NULL,SESEdge::TYPE_SINGULAR, ses_->number_of_edges_); ses_->edges_.push_back(new_edge1); ses_->singular_edges_.push_back(new_edge1); face1->edge_.push_back(new_edge1); face2->edge_.push_back(new_edge1); sesvertex1[0]->edges_.insert(new_edge1); sesvertex1[2]->edges_.insert(new_edge1); ses_->number_of_edges_++; ses_->number_of_singular_edges_++; SESEdge* new_edge2 = new SESEdge(sesvertex1[3],sesvertex1[6],face1,face2, circle,NULL,SESEdge::TYPE_SINGULAR, ses_->number_of_edges_); ses_->edges_.push_back(new_edge2); ses_->singular_edges_.push_back(new_edge2); face1->edge_.push_back(new_edge2); face2->edge_.push_back(new_edge2); sesvertex1[3]->edges_.insert(new_edge2); sesvertex1[6]->edges_.insert(new_edge2); ses_->number_of_edges_++; ses_->number_of_singular_edges_++; if (sesedge1[2] == sesedge2[2]) { ses_->edges_[sesedge1[2]->index_] = NULL; ses_->singular_edges_.remove(sesedge1[2]); sesvertex1[2]->edges_.erase(sesedge1[2]); sesvertex1[3]->edges_.erase(sesedge1[2]); face1->edge_.remove(sesedge1[2]); face2->edge_.remove(sesedge1[2]); delete sesedge1[2]; } if (sesedge1[6] == sesedge2[6]) { ses_->edges_[sesedge1[6]->index_] = NULL; ses_->singular_edges_.remove(sesedge1[6]); sesvertex1[6]->edges_.erase(sesedge1[6]); sesvertex1[0]->edges_.erase(sesedge1[6]); face1->edge_.remove(sesedge1[6]); face2->edge_.remove(sesedge1[6]); delete sesedge1[6]; } } void SESSingularityCleaner::sort (SESFace* face1, SESFace* face2, std::vector& sesedge1, std::vector& sesedge2, std::vector& sesvertex1, std::vector& sesvertex2) throw() { // find two equal vertices std::list::iterator v1 = face1->vertex_.begin(); std::list::iterator v2; bool found = false; while (!found) { v2 = face2->vertex_.begin(); while (!found && (v2 != face2->vertex_.end())) { if (*v2 == *v1) { sesvertex1[0] = *v1; sesvertex2[0] = *v2; found = true; } v2++; } v1++; } // find first corresponding edges face1->getEdges(sesvertex1[0],sesedge1[0],sesedge1[1]); face2->getEdges(sesvertex2[0],sesedge2[0],sesedge2[1]); if (*sesedge1[0] == *sesedge2[1]) { sesedge1[0] = sesedge1[1]; } else { if (*sesedge1[1] == *sesedge2[0]) { sesedge2[0] = sesedge2[1]; } else { if (*sesedge1[0] == *sesedge2[0]) { sesedge1[0] = sesedge1[1]; sesedge2[0] = sesedge2[1]; } } } // find remaining edges and vertices SESEdge* sesedge(0); sesvertex1[1] = sesedge1[0]->other(sesvertex1[0]); sesvertex2[1] = sesedge2[0]->other(sesvertex2[0]); for (Position i = 1; i < 6; i++) { face1->getEdges(sesvertex1[i],sesedge1[i],sesedge); if (sesedge != sesedge1[i-1]) { sesedge1[i] = sesedge; } face2->getEdges(sesvertex2[i],sesedge2[i],sesedge); if (sesedge != sesedge2[i-1]) { sesedge2[i] = sesedge; } sesvertex1[i+1] = sesedge1[i]->other(sesvertex1[i]); sesvertex2[i+1] = sesedge2[i]->other(sesvertex2[i]); } face1->getEdge(sesvertex1[0],sesvertex1[6],sesedge1[6]); face2->getEdge(sesvertex2[0],sesvertex2[6],sesedge2[6]); // SESVertex* sesvertex(0); if (sesvertex1[2] != sesvertex2[2]) { for (Position i = 0; i < 3; i++) { sesvertex = sesvertex1[i]; sesvertex1[i] = sesvertex1[6-i]; sesvertex1[6-i] = sesvertex; sesvertex = sesvertex2[i]; sesvertex2[i] = sesvertex2[6-i]; sesvertex2[6-i] = sesvertex; sesedge = sesedge1[i]; sesedge1[i] = sesedge1[5-i]; sesedge1[5-i] = sesedge; sesedge = sesedge2[i]; sesedge2[i] = sesedge2[5-i]; sesedge2[5-i] = sesedge; } } } void SESSingularityCleaner::treatSecondCategory() throw() { double x_min = ses_->spheric_faces_[0]->rsface_->center_.x; double y_min = ses_->spheric_faces_[0]->rsface_->center_.y; double z_min = ses_->spheric_faces_[0]->rsface_->center_.z; double x_max = ses_->spheric_faces_[0]->rsface_->center_.x; double y_max = ses_->spheric_faces_[0]->rsface_->center_.y; double z_max = ses_->spheric_faces_[0]->rsface_->center_.z; for (Position i = 1; i != ses_->number_of_spheric_faces_; i++) { x_min = ((x_min > ses_->spheric_faces_[i]->rsface_->center_.x) ? ses_->spheric_faces_[i]->rsface_->center_.x : x_min); y_min = ((y_min > ses_->spheric_faces_[i]->rsface_->center_.y) ? ses_->spheric_faces_[i]->rsface_->center_.y : y_min); z_min = ((z_min > ses_->spheric_faces_[i]->rsface_->center_.z) ? ses_->spheric_faces_[i]->rsface_->center_.z : z_min); x_max = ((x_max < ses_->spheric_faces_[i]->rsface_->center_.x) ? ses_->spheric_faces_[i]->rsface_->center_.x : x_max); y_max = ((y_max < ses_->spheric_faces_[i]->rsface_->center_.y) ? ses_->spheric_faces_[i]->rsface_->center_.y : y_max); z_max = ((z_max < ses_->spheric_faces_[i]->rsface_->center_.z) ? ses_->spheric_faces_[i]->rsface_->center_.z : z_max); } double dist = 2*ses_->reduced_surface_->probe_radius_; Position nx = (Position)((x_max-x_min)/dist+5); Position ny = (Position)((y_max-y_min)/dist+5); Position nz = (Position)((z_max-z_min)/dist+5); Vector3 origin(x_min-2*dist,y_min-2*dist,z_min-2*dist); HashGrid3 grid(origin,nx,ny,nz,dist); Vector3 pos; for (Position i = 0; i != ses_->number_of_spheric_faces_; i++) { pos.set(ses_->spheric_faces_[i]->rsface_->center_.x, ses_->spheric_faces_[i]->rsface_->center_.y, ses_->spheric_faces_[i]->rsface_->center_.z); grid.insert(pos,i); } std::list::iterator edge; std::list deletable_edges; for (edge = ses_->singular_edges_.begin(); edge != ses_->singular_edges_.end(); edge++) { treatSingularEdge(*edge,grid,deletable_edges); } for (edge = deletable_edges.begin(); edge != deletable_edges.end(); edge++) { (*edge)->face_[0]->edge_.remove(*edge); (*edge)->face_[1]->edge_.remove(*edge); (*edge)->vertex_[0]->edges_.erase(*edge); (*edge)->vertex_[1]->edges_.erase(*edge); ses_->edges_[(*edge)->index_] = NULL; ses_->singular_edges_.remove(*edge); delete *edge; } } void SESSingularityCleaner::treatSingularEdge (SESEdge* edge, HashGrid3& grid, std::list& deletable_edges) throw() { if (edge->vertex_[0] == NULL) { return; } TAngle phi = getOrientedAngle(edge->vertex_[0]->point_-edge->circle_.p, edge->vertex_[1]->point_-edge->circle_.p, edge->circle_.n); std::list intersections; getIntersectionsOfSingularEdge(edge,phi,grid,intersections); if (!intersections.empty()) { std::list min; std::list max; getExtrema(intersections,min,max); HashSet indices; std::list::const_iterator i; for (i = min.begin(); i != min.end(); i++) { indices.insert(i->first.second); } for (i = max.begin(); i != max.end(); i++) { indices.insert(i->first.second); } Index face1 = edge->face_[0]->index_; Index face2 = edge->face_[1]->index_; indices.insert(face1); indices.insert(face2); SESVertex* end_vertex1(0); SESVertex* end_vertex2(0); Index actual_min(0); Index actual_max(0); buildEndEdges(edge,min,max,end_vertex1,end_vertex2, actual_min,actual_max); Index next_face = actual_min; SESVertex* vertex = end_vertex1; while ((next_face != face2) && (vertex != NULL)) { buildEdge(edge,face1,next_face,face2,vertex,indices,true); } if (next_face != face2) { next_face = actual_max; vertex = end_vertex2; while ((next_face != face2) && (vertex != NULL)) { buildEdge(edge,face1,next_face,face2,vertex,indices,false); } } face2 = face1; face1 = edge->face_[1]->index_; next_face = actual_min; vertex = end_vertex1; while ((next_face != face2) && (vertex != NULL)) { buildEdge(edge,face1,next_face,face2,vertex,indices,true); } if (next_face != face2) { next_face = actual_max; vertex = end_vertex2; while ((next_face != face2) && (vertex != NULL)) { buildEdge(edge,face1,next_face,face2,vertex,indices,false); } } deletable_edges.push_back(edge); } } void SESSingularityCleaner::getExtrema (const std::list& intersections, std::list& min, std::list& max) throw() { TAngle min_phi(2*Constants::PI); TAngle max_phi(0,true); std::list::const_iterator i; double epsilon = Constants::EPSILON; Constants::EPSILON = 0.0001; for (i = intersections.begin(); i != intersections.end(); i++) { if (i->first.first <= min_phi) { if (i->first.first < min_phi) { min.clear(); min_phi = i->first.first; } min.push_back(*i); } if (i->first.first >= max_phi) { if (i->first.first > max_phi) { max.clear(); max_phi = i->first.first; } max.push_back(*i); } } Constants::EPSILON = epsilon; } void SESSingularityCleaner::getIntersectionsOfSingularEdge (SESEdge* edge, const TAngle& phi, HashGrid3& grid, std::list& intersections) throw() { TQuaternion rotate(edge->circle_.n,phi/2); TMatrix4x4 rotation; rotate.getRotationMatrix(rotation); TVector4 middle_(edge->vertex_[0]->point_.x-edge->circle_.p.x, edge->vertex_[0]->point_.y-edge->circle_.p.y, edge->vertex_[0]->point_.z-edge->circle_.p.z, 0); middle_ = rotation*middle_; TVector3 middle(middle_.x+edge->circle_.p.x, middle_.y+edge->circle_.p.y, middle_.z+edge->circle_.p.z); Index face1 = edge->face_[0]->index_; Index face2 = edge->face_[1]->index_; TAngle phi1; TAngle phi2; TVector3 point1; TVector3 point2; TSphere3 probe; probe.radius = ses_->reduced_surface_->probe_radius_; Intersection intersection; HashGridBox3* box(0); HashGridBox3::ConstBoxIterator b; HashGridBox3::ConstDataIterator d; Vector3 pos(edge->circle_.p.x, edge->circle_.p.y, edge->circle_.p.z); box = grid.getBox(pos); if (box != NULL) { for (b = box->beginBox(); b != box->endBox(); b++) { for (d = b->beginData(); d != b->endData(); d++) { if (((Index)*d != face1) && ((Index)*d != face2)) { if (getIntersectionPointsAndAngles (edge->circle_,edge->vertex_[0]->point_, edge->face_[0]->index_,edge->face_[1]->index_, ses_->spheric_faces_[*d]->index_, phi1,point1,phi2,point2)) { probe.p = ses_->spheric_faces_[*d]->rsface_->center_; if (isIntersection(phi1,phi2,phi,middle,probe)) { intersection.first.second = *d; intersection.first.first = phi1; intersection.second = point1; intersections.push_back(intersection); intersection.first.first = phi2; intersection.second = point2; intersections.push_back(intersection); } } } } } } } bool SESSingularityCleaner::getIntersectionPointsAndAngles (const TCircle3& circle, const TVector3& point, Position index1, Position index2, Position probe_index, TAngle& phi1, TVector3& point1, TAngle& phi2, TVector3& point2) throw() { if (probeIntersection(index1, index2, probe_index, point1, point2)) { phi1 = getOrientedAngle(point-circle.p, point1-circle.p, circle.n); phi2 = getOrientedAngle(point-circle.p, point2-circle.p, circle.n); double epsilon = Constants::EPSILON; Constants::EPSILON = 0.001; if (Maths::isEqual(phi1.value,2*Constants::PI)) { phi1.value = 0.0; } if (Maths::isEqual(phi2.value,2*Constants::PI)) { phi2.value = 0.0; } Constants::EPSILON = epsilon; if (phi2 < phi1) { phi1.swap(phi2); point1.swap(point2); } return true; } else { return false; } } bool SESSingularityCleaner::isIntersection (const TAngle& min_phi, const TAngle& max_phi, const TAngle& phi, const TVector3& middle, const TSphere3& probe) throw() { double epsilon = Constants::EPSILON; Constants::EPSILON = 0.001; bool back; if (max_phi > phi) { back = false; } else { if (Maths::isNotZero(min_phi.value) || (max_phi < phi)) { back = true; } else { double epsilon = Constants::EPSILON; Constants::EPSILON = 1e-6; if (Maths::isGreater(probe.p.getSquareDistance(middle), probe.radius*probe.radius)) { back = false; } else { back = true; } Constants::EPSILON = epsilon; } } Constants::EPSILON = epsilon; return back; } void SESSingularityCleaner::buildEndEdges (SESEdge* edge, const std::list& min, const std::list& max, SESVertex*& vertex1, SESVertex*& vertex2, Index& actual_min, Index& actual_max) throw() { buildEndEdge(edge,min,vertex1,actual_min,true); buildEndEdge(edge,max,vertex2,actual_max,false); } void SESSingularityCleaner::buildEndEdge (SESEdge* edge, const std::list& extrema, SESVertex*& vertex, Index& actual_extremum, bool min) throw() { vertex = NULL; std::list::const_iterator m; for (m = extrema.begin(); m != extrema.end(); m++) { Index test = vertexExists(m->second); if (test != -1) { vertex = ses_->vertices_[test]; actual_extremum = m->first.second; } } if (vertex == NULL) { Intersection absolute_extremum = extrema.front(); if (min) { for (m = extrema.begin(); m != extrema.end(); m++) { if (m->first.first.value < absolute_extremum.first.first.value) { absolute_extremum = *m; } } } else { for (m = extrema.begin(); m != extrema.end(); m++) { if (m->first.first.value > absolute_extremum.first.first.value) { absolute_extremum = *m; } } } actual_extremum = absolute_extremum.first.second; vertex = new SESVertex(absolute_extremum.second, edge->circle_.p-absolute_extremum.second, -2,ses_->number_of_vertices_); ses_->vertices_.push_back(vertex); Vector3 pos(vertex->point_.x, vertex->point_.y, vertex->point_.z); vertex_grid_->insert(pos,vertex->index_); ses_->number_of_vertices_++; } Position v = (min ? 0 : 1); if (vertex != edge->vertex_[v]) { SESEdge* new_edge(0); new_edge = new SESEdge(*edge,true); new_edge->vertex_[1-v] = vertex; new_edge->rsedge_ = NULL; new_edge->index_ = ses_->number_of_edges_; ses_->edges_.push_back(new_edge); ses_->number_of_edges_++; ses_->singular_edges_.push_front(new_edge); ses_->number_of_singular_edges_++; new_edge->vertex_[0]->edges_.insert(new_edge); new_edge->vertex_[1]->edges_.insert(new_edge); new_edge->face_[0]->edge_.push_back(new_edge); new_edge->face_[1]->edge_.push_back(new_edge); new_edge->face_[0]->insert(new_edge->vertex_[1-v]); new_edge->face_[1]->insert(new_edge->vertex_[1-v]); vertex->faces_.insert(new_edge->face_[0]); vertex->faces_.insert(new_edge->face_[1]); } } void SESSingularityCleaner::buildEdge (SESEdge* edge, Index face1, Index& face2, Index end, SESVertex*& vertex, const HashSet& indices, bool minimum) throw() { SESFace* spheric_face1 = ses_->spheric_faces_[face1]; SESFace* spheric_face2 = ses_->spheric_faces_[face2]; TSphere3 probe1(spheric_face1->rsface_->center_, ses_->reduced_surface_->probe_radius_); TSphere3 probe2(spheric_face2->rsface_->center_, ses_->reduced_surface_->probe_radius_); TCircle3 circle; GetIntersection(probe1,probe2,circle); Index sign = (minimum ? -1 : 1); if (((probe1.p-edge->circle_.p)*edge->circle_.n)* ((probe1.p-circle.p)*circle.n)*sign > 0) { circle.n.negate(); } TVector3 point(vertex->point_); TVector3 point1; TVector3 point2; TAngle phi1; TAngle phi2; std::list< std::pair,Index> > min; TAngle min_phi(2*Constants::PI,true); std::pair,Index> new_min; double epsilon = Constants::EPSILON; Constants::EPSILON = 0.001; HashSet::ConstIterator i; for (i = indices.begin(); i != indices.end(); i++) { if ((*i != face1) && (*i != face2)) { if (getIntersectionPointsAndAngles(circle,point,face1,face2,*i, phi1,point1,phi2,point2)) { if ((phi1 <= min_phi) && Maths::isGreater(phi1.value,0.0)) { if (phi1 < min_phi) { min.clear(); } min_phi = phi1; new_min.first = point1; new_min.second = *i; min.push_back(new_min); } if ((phi2 <= min_phi) && Maths::isGreater(phi2.value,0.0)) { if (phi2 < min_phi) { min.clear(); } min_phi = phi2; new_min.first = point2; new_min.second = *i; min.push_back(new_min); } } } } Constants::EPSILON = epsilon; SESVertex* new_vertex = NULL; std::list< std::pair,Index> >::iterator m = min.begin(); bool not_found = true; while (not_found && (m != min.end())) { if (m->second == end) { point2 = m->first; face2 = end; Index index = vertexExists(point2); if (index != -1) { new_vertex = ses_->vertices_[index]; } not_found = false; } m++; } if (not_found) { Index index = -1; m = min.begin(); while ((index == -1) && (m != min.end())) { point2 = m->first; face2 = m->second; index = vertexExists(point2); if (index != -1) { new_vertex = ses_->vertices_[index]; } m++; } } if (spheric_face1->isNeighbouredTo(spheric_face2) == false) { point1.set(vertex->point_); if (new_vertex == NULL) { new_vertex = new SESVertex(point2,circle.p-point2,-2, ses_->number_of_vertices_); ses_->vertices_.push_back(new_vertex); Vector3 pos(new_vertex->point_.x, new_vertex->point_.y, new_vertex->point_.z); vertex_grid_->insert(pos,new_vertex->index_); ses_->number_of_vertices_++; } SESEdge* new_edge = new SESEdge; new_edge->vertex_[0] = vertex; new_edge->vertex_[1] = new_vertex; new_edge->face_[0] = spheric_face1; new_edge->face_[1] = spheric_face2; new_edge->type_ = SESEdge::TYPE_SINGULAR; new_edge->circle_ = circle; new_edge->rsedge_ = NULL; new_edge->index_ = ses_->number_of_edges_; ses_->edges_.push_back(new_edge); ses_->number_of_edges_++; ses_->singular_edges_.push_back(new_edge); ses_->number_of_singular_edges_++; spheric_face1->edge_.push_back(new_edge); spheric_face2->edge_.push_back(new_edge); vertex->edges_.insert(new_edge); new_vertex->edges_.insert(new_edge); spheric_face1->insert(vertex); spheric_face2->insert(vertex); spheric_face1->insert(new_vertex); spheric_face2->insert(new_vertex); vertex->faces_.insert(spheric_face1); vertex->faces_.insert(spheric_face2); new_vertex->faces_.insert(spheric_face1); new_vertex->faces_.insert(spheric_face2); vertex = new_vertex; } else { vertex = NULL; } } bool SESSingularityCleaner::probeIntersection (Index face1, Index face2, Index face3, TVector3& point1, TVector3& point2) throw() { // sort the indices of the spheric faces sort(face1,face2,face3,face1,face2,face3); // try to find the intersection points HashMap< Position, HashMap< Position, HashMap< Position, ProbeIntersection* > > >::Iterator i1; HashMap< Position, HashMap< Position, ProbeIntersection* > >::Iterator i2; HashMap< Position,ProbeIntersection* >::Iterator i3; bool back = false; bool found = false; i1 = probe_intersections_.find(face1); if (i1 != probe_intersections_.end()) { i2 = i1->second.find(face2); if (i2 != i1->second.end()) { i3 = i2->second.find(face3); if (i3 != i2->second.end()) { found = true; if (i3->second == NULL) { back = false; } else { point1 = i3->second->point[0]; point2 = i3->second->point[1]; back = true; } } } } // if the intersection points are not computed yet, compute them now if (found == false) { TSphere3 s1(ses_->spheric_faces_[face1]->rsface_->center_, ses_->reduced_surface_->probe_radius_); TSphere3 s2(ses_->spheric_faces_[face2]->rsface_->center_, ses_->reduced_surface_->probe_radius_); TSphere3 s3(ses_->spheric_faces_[face3]->rsface_->center_, ses_->reduced_surface_->probe_radius_); if (GetIntersection(s1,s2,s3,point1,point2,false)) { ProbeIntersection* intersection = new ProbeIntersection; intersection->point[0] = point1; intersection->point[1] = point2; probe_intersections_[face1][face2][face3] = intersection; back = true; } else { probe_intersections_[face1][face2][face3] = NULL; back = false; } } return back; } void SESSingularityCleaner::sort (Index u1, Index u2, Index u3, Index& s1, Index& s2, Index& s3) throw() { s1 = u1; s2 = u2; s3 = u3; Index tmp; if (s1 > s2) { tmp = s1; s1 = s2; s2 = tmp; } if (s1 > s3) { tmp = s1; s1 = s3; s3 = tmp; } if (s2 > s3) { tmp = s2; s2 = s3; s3 = tmp; } } Index SESSingularityCleaner::vertexExists(TVector3 point) throw() { double epsilon = Constants::EPSILON; Constants::EPSILON = 0.001; Vector3 p(point.x,point.y,point.z); HashGridBox3* box = vertex_grid_->getBox(p); HashGridBox3::ConstBoxIterator b; HashGridBox3::ConstDataIterator d; if (box != NULL) { for (b = box->beginBox(); b != box->endBox(); b++) { for (d = b->beginData(); d != b->endData(); d++) { if (ses_->vertices_[*d]->point_ == point) { Constants::EPSILON = epsilon; return *d; } } } } Constants::EPSILON = epsilon; return -1; } } // namespace BALL ugene-1.9.8/src/plugins_3rdparty/ball/src/source/STRUCTURE/RSFace.cpp0000644000175000017500000001632011651544326023633 0ustar ilyailya// -*- Mode: C++; tab-width: 2; -*- // vi: set ts=2: // // $Id: RSFace.C,v 1.4 2002-12-17 14:13:19 anker Exp $ #include #include #include #include namespace BALL { RSFace::RSFace() throw() : GraphTriangle< RSVertex,RSEdge,RSFace >(), center_(), normal_(), singular_(false) { } RSFace::RSFace(const RSFace& rsface, bool deep) throw() : GraphTriangle< RSVertex,RSEdge,RSFace >(rsface,deep), center_(rsface.center_), normal_(rsface.normal_), singular_(rsface.singular_) { } RSFace::RSFace(RSVertex* vertex1, RSVertex* vertex2, RSVertex* vertex3, RSEdge* edge1, RSEdge* edge2, RSEdge* edge3, const TVector3& center, const TVector3& normal, bool singular, Index index) throw(Exception::DivisionByZero) : GraphTriangle< RSVertex,RSEdge,RSFace > (vertex1,vertex2,vertex3,edge1,edge2,edge3,index), center_(center), normal_(normal), singular_(singular) { normal_.normalize(); } RSFace::~RSFace() throw() { } void RSFace::set(const RSFace& rsface, bool deep) throw() { if (this != &rsface) { GraphTriangle< RSVertex,RSEdge,RSFace >::set(rsface,deep); center_.set(rsface.center_); normal_.set(rsface.normal_); singular_ = rsface.singular_; } } RSFace& RSFace::operator = (const RSFace& rsface) throw() { if (this != &rsface) { GraphTriangle< RSVertex,RSEdge,RSFace >::operator = (rsface); center_.set(rsface.center_); normal_.set(rsface.normal_); singular_ = rsface.singular_; } return *this; } void RSFace::set(RSVertex* vertex1, RSVertex* vertex2, RSVertex* vertex3, RSEdge* edge1, RSEdge* edge2, RSEdge* edge3, const TVector3& center, const TVector3& normal, bool singular, Index index) throw(Exception::DivisionByZero) { GraphTriangle< RSVertex,RSEdge,RSFace >::set (vertex1,vertex2,vertex3,edge1,edge2,edge3,index); center_.set(center); normal_.set(normal); singular_ = singular; normal_.normalize(); } bool RSFace::operator == (const RSFace& rsface) const throw() { return ( (center_ == rsface.center_) && (((vertex_[0]->atom_ == rsface.vertex_[0]->atom_) && (vertex_[1]->atom_ == rsface.vertex_[1]->atom_) && (vertex_[2]->atom_ == rsface.vertex_[2]->atom_) ) || ((vertex_[0]->atom_ == rsface.vertex_[0]->atom_) && (vertex_[1]->atom_ == rsface.vertex_[2]->atom_) && (vertex_[2]->atom_ == rsface.vertex_[1]->atom_) ) || ((vertex_[0]->atom_ == rsface.vertex_[1]->atom_) && (vertex_[1]->atom_ == rsface.vertex_[0]->atom_) && (vertex_[2]->atom_ == rsface.vertex_[2]->atom_) ) || ((vertex_[0]->atom_ == rsface.vertex_[1]->atom_) && (vertex_[1]->atom_ == rsface.vertex_[2]->atom_) && (vertex_[2]->atom_ == rsface.vertex_[0]->atom_) ) || ((vertex_[0]->atom_ == rsface.vertex_[2]->atom_) && (vertex_[1]->atom_ == rsface.vertex_[0]->atom_) && (vertex_[2]->atom_ == rsface.vertex_[1]->atom_) ) || ((vertex_[0]->atom_ == rsface.vertex_[2]->atom_) && (vertex_[1]->atom_ == rsface.vertex_[1]->atom_) && (vertex_[2]->atom_ == rsface.vertex_[0]->atom_) ) ) ); } bool RSFace::operator != (const RSFace& rsface) const throw() { return ( ! (*this == rsface) ); } bool RSFace::operator *= (const RSFace& rsface) const throw() { return ( ((vertex_[0]->atom_ == rsface.vertex_[0]->atom_) && (vertex_[1]->atom_ == rsface.vertex_[1]->atom_) && (vertex_[2]->atom_ == rsface.vertex_[2]->atom_) ) || ((vertex_[0]->atom_ == rsface.vertex_[0]->atom_) && (vertex_[1]->atom_ == rsface.vertex_[2]->atom_) && (vertex_[2]->atom_ == rsface.vertex_[1]->atom_) ) || ((vertex_[0]->atom_ == rsface.vertex_[1]->atom_) && (vertex_[1]->atom_ == rsface.vertex_[0]->atom_) && (vertex_[2]->atom_ == rsface.vertex_[2]->atom_) ) || ((vertex_[0]->atom_ == rsface.vertex_[1]->atom_) && (vertex_[1]->atom_ == rsface.vertex_[2]->atom_) && (vertex_[2]->atom_ == rsface.vertex_[0]->atom_) ) || ((vertex_[0]->atom_ == rsface.vertex_[2]->atom_) && (vertex_[1]->atom_ == rsface.vertex_[0]->atom_) && (vertex_[2]->atom_ == rsface.vertex_[1]->atom_) ) || ((vertex_[0]->atom_ == rsface.vertex_[2]->atom_) && (vertex_[1]->atom_ == rsface.vertex_[1]->atom_) && (vertex_[2]->atom_ == rsface.vertex_[0]->atom_) ) ); } bool RSFace::isSingular() const throw() { return singular_; } void RSFace::setCenter(const TVector3& center) throw() { center_ = center; } TVector3 RSFace::getCenter() const throw() { return center_; } void RSFace::setNormal(const TVector3& normal) throw(Exception::DivisionByZero) { normal_ = normal; normal_.normalize(); } TVector3 RSFace::getNormal() const throw() { return normal_; } void RSFace::setSingular(bool singular) throw() { singular_ = singular; } void RSFace::remove (HashSet& edges, HashSet& vertices, HashSet& faces) throw() { vertex_[0]->faces_.erase(this); vertex_[1]->faces_.erase(this); vertex_[2]->faces_.erase(this); if (edge_[0] != NULL) { if (edge_[0]->face_[1] == NULL) { edge_[0]->vertex_[0]->edges_.erase(edge_[0]); edge_[0]->vertex_[1]->edges_.erase(edge_[0]); vertices.insert(edge_[0]->vertex_[0]); vertices.insert(edge_[0]->vertex_[1]); edges.insert(edge_[0]); edge_[0] = NULL; } else { faces.insert(edge_[0]->remove(this)); } } if (edge_[1] != NULL) { if (edge_[1]->face_[1] == NULL) { edge_[1]->vertex_[0]->edges_.erase(edge_[1]); edge_[1]->vertex_[1]->edges_.erase(edge_[1]); vertices.insert(edge_[1]->vertex_[0]); vertices.insert(edge_[1]->vertex_[1]); edges.insert(edge_[1]); edge_[1] = NULL; } else { faces.insert(edge_[1]->remove(this)); } } if (edge_[2] != NULL) { if (edge_[2]->face_[1] == NULL) { edge_[2]->vertex_[0]->edges_.erase(edge_[2]); edge_[2]->vertex_[1]->edges_.erase(edge_[2]); vertices.insert(edge_[2]->vertex_[0]); vertices.insert(edge_[2]->vertex_[1]); edges.insert(edge_[2]); edge_[2] = NULL; } else { faces.insert(edge_[2]->remove(this)); } } } std::ostream& operator << (std::ostream& s, const RSFace& rsface) { s << "RSFACE" << rsface.getIndex() << "([" << (rsface.getVertex(0) == NULL ? -2 : rsface.getVertex(0)->getIndex()) << ' ' << (rsface.getVertex(1) == NULL ? -2 : rsface.getVertex(1)->getIndex()) << ' ' << (rsface.getVertex(2) == NULL ? -2 : rsface.getVertex(2)->getIndex()) << "] [" << (rsface.getEdge(0) == NULL ? -2 : rsface.getEdge(0)->getIndex()) << ' ' << (rsface.getEdge(1) == NULL ? -2 : rsface.getEdge(1)->getIndex()) << ' ' << (rsface.getEdge(2) == NULL ? -2 : rsface.getEdge(2)->getIndex()) << "] " << rsface.getCenter() << ' ' << rsface.getNormal() << ' ' << (rsface.isSingular() ? "true" : "false") << ")"; return s; } } // namespace BALL ugene-1.9.8/src/plugins_3rdparty/ball/src/source/STRUCTURE/triangle.cpp0000644000175000017500000000523411651544326024337 0ustar ilyailya// -*- Mode: C++; tab-width: 2; -*- // vi: set ts=2: // // $Id: triangle.C,v 1.3 2002-12-17 14:13:21 anker Exp $ #include #include #include namespace BALL { Triangle::Triangle() throw() : GraphTriangle< TrianglePoint,TriangleEdge,Triangle >() { } Triangle::Triangle(const Triangle& triangle, bool deep) throw() : GraphTriangle< TrianglePoint,TriangleEdge,Triangle > (triangle,deep) { } Triangle::~Triangle() throw() { } void Triangle::set(const Triangle& triangle, bool deep) throw() { if (this != &triangle) { GraphTriangle< TrianglePoint,TriangleEdge,Triangle >::set (triangle,deep); } } Triangle& Triangle::operator = (const Triangle& triangle) throw() { if (this != &triangle) { GraphTriangle< TrianglePoint,TriangleEdge,Triangle >:: operator = (triangle); } return *this; } void Triangle::setPoint(Position i, TrianglePoint* vertex) throw(Exception::IndexOverflow) { switch (i) { case 0 : vertex_[0] = vertex; break; case 1 : vertex_[1] = vertex; break; case 2 : vertex_[2] = vertex; break; default : throw Exception::IndexOverflow(__FILE__,__LINE__,i,2); } } TrianglePoint* Triangle::getPoint(Position i) const throw(Exception::IndexOverflow) { switch (i) { case 0 : return vertex_[0]; case 1 : return vertex_[1]; case 2 : return vertex_[2]; default : throw Exception::IndexOverflow(__FILE__,__LINE__,i,2); } } void Triangle::remove(TriangleEdge* edge) throw() { for (Position i = 0; i < 3; i++) { if (edge_[i] == edge) { edge_[i] = NULL; } } } bool Triangle::operator == (const Triangle&) const throw() { return true; } bool Triangle::operator != (const Triangle&) const throw() { return false; } bool Triangle::operator *= (const Triangle&) const throw() { return true; } std::ostream& operator << (std::ostream& s, const Triangle& triangle) { s << "TRIANGLE" << triangle.getIndex() << "([" << (triangle.getVertex(0) == NULL ? -2 : triangle.getVertex(0)->getIndex()) << ' ' << (triangle.getVertex(1) == NULL ? -2 : triangle.getVertex(1)->getIndex()) << ' ' << (triangle.getVertex(2) == NULL ? -2 : triangle.getVertex(2)->getIndex()) << "] [" << (triangle.getEdge(0) == NULL ? -2 : triangle.getEdge(0)->getIndex()) << ' ' << (triangle.getEdge(1) == NULL ? -2 : triangle.getEdge(1)->getIndex()) << ' ' << (triangle.getEdge(2) == NULL ? -2 : triangle.getEdge(2)->getIndex()) << "])"; return s; } } // namespace BALL ugene-1.9.8/src/plugins_3rdparty/ball/src/source/STRUCTURE/SASEdge.cpp0000644000175000017500000000601611651544326023744 0ustar ilyailya// -*- Mode: C++; tab-width: 2; -*- // vi: set ts=2: // // $Id: SASEdge.C,v 1.1 2002-12-17 17:14:22 anker Exp $ #include #include #include #include #include namespace BALL { SASEdge::SASEdge() throw() : GraphEdge< SASVertex,SASEdge,SASFace >(), circle_(), angle_() { } SASEdge::SASEdge(const SASEdge& sasedge, bool deep) throw() : GraphEdge< SASVertex,SASEdge,SASFace >(sasedge,deep), circle_(sasedge.circle_), angle_(sasedge.angle_) { } SASEdge::SASEdge(SASVertex* vertex0, SASVertex* vertex1, SASFace* face0, SASFace* face1, const TCircle3& circle, const TAngle& angle, Index index) throw() : GraphEdge< SASVertex,SASEdge,SASFace > (vertex0,vertex1,face0,face1,index), circle_(circle), angle_(angle) { } SASEdge::~SASEdge() throw() { } void SASEdge::set(const SASEdge& sasedge, bool deep) throw() { if (this != &sasedge) { GraphEdge< SASVertex,SASEdge,SASFace >::set(sasedge,deep); circle_.set(sasedge.circle_); angle_.set(sasedge.angle_); } } SASEdge& SASEdge::operator = (const SASEdge& sasedge) throw() { if (this != &sasedge) { GraphEdge< SASVertex,SASEdge,SASFace >::operator = (sasedge); circle_.set(sasedge.circle_); angle_.set(sasedge.angle_); } return *this; } void SASEdge::set (SASVertex* vertex0, SASVertex* vertex1, SASFace* face0, SASFace* face1, const TCircle3& circle, const TAngle& angle, Index index) throw() { GraphEdge< SASVertex,SASEdge,SASFace >::set (vertex0,vertex1,face0,face1,index); circle_.set(circle); angle_.set(angle); } void SASEdge::setCircle(const TCircle3& circle) throw() { circle_ = circle; } TCircle3 SASEdge::getCircle() const throw() { return circle_; } void SASEdge::setAngle(const TAngle& angle) throw() { angle_ = angle; } TAngle SASEdge::getAngle() const throw() { return angle_; } bool SASEdge::operator == (const SASEdge&) const throw() { return true; } bool SASEdge::operator != (const SASEdge&) const throw() { return false; } bool SASEdge::operator *= (const SASEdge&) const throw() { return true; } bool SASEdge::isFree() const throw() { return (vertex_[0] == NULL); } std::ostream& operator << (std::ostream& s, const SASEdge& sasedge) { return (s << "SASEDGE" << sasedge.getIndex() << "([" << ((sasedge.getVertex(0) == NULL) ? -2 : sasedge.getVertex(0)->getIndex()) << ' ' << ((sasedge.getVertex(1) == NULL) ? -2 : sasedge.getVertex(1)->getIndex()) << "] [" << ((sasedge.getFace(0) == NULL) ? -2 : sasedge.getFace(0)->getIndex()) << ' ' << ((sasedge.getFace(1) == NULL) ? -2 : sasedge.getFace(1)->getIndex()) << "] " << sasedge.getCircle() ); } } // namespave BALL ugene-1.9.8/src/plugins_3rdparty/ball/src/source/STRUCTURE/triangulatedSurface.cpp0000644000175000017500000011742211651544326026531 0ustar ilyailya// -*- Mode: C++; tab-width: 2; -*- // vi: set ts=2: // // $Id: triangulatedSurface.C,v 1.5.28.1 2007-03-22 11:48:23 oliver Exp $ #include namespace BALL { TriangulatedSurface::TriangulatedSurface() throw() : number_of_points_(0), points_(), number_of_edges_(0), edges_(), number_of_triangles_(0), triangles_() { } TriangulatedSurface::TriangulatedSurface (const TriangulatedSurface& surface, bool) throw() : number_of_points_(0), points_(), number_of_edges_(0), edges_(), number_of_triangles_(0), triangles_() { copy(surface); } TriangulatedSurface::~TriangulatedSurface() throw() { clear(); } void TriangulatedSurface::clear() throw() { std::list::iterator p; for (p = points_.begin(); p != points_.end(); p++) { delete *p; } std::list::iterator e; for (e = edges_.begin(); e != edges_.end(); e++) { delete *e; } std::list::iterator t; for (t = triangles_.begin(); t != triangles_.end(); t++) { delete *t; } points_.clear(); edges_.clear(); triangles_.clear(); number_of_points_ = 0; number_of_edges_ = 0; number_of_triangles_ = 0; } void TriangulatedSurface::set (const TriangulatedSurface& surface, bool) throw() { if (this != &surface) { copy(surface); } } TriangulatedSurface& TriangulatedSurface::operator = (const TriangulatedSurface& surface) throw() { if (this != &surface) { copy(surface); } return *this; } void TriangulatedSurface::insert(TrianglePoint* p) throw() { points_.push_back(p); number_of_points_++; } void TriangulatedSurface::insert(TriangleEdge* e) throw() { edges_.push_back(e); number_of_edges_++; } void TriangulatedSurface::insert(Triangle* t) throw() { triangles_.push_back(t); number_of_triangles_++; } Size TriangulatedSurface::numberOfPoints() const throw() { return number_of_points_; } Size TriangulatedSurface::numberOfEdges() const throw() { return number_of_edges_; } Size TriangulatedSurface::numberOfTriangles() const throw() { return number_of_triangles_; } void TriangulatedSurface::remove(TrianglePoint* point, bool deep) throw() { if (deep) { HashSet delete_triangles = point->faces_; HashSet::Iterator t; for (t = delete_triangles.begin(); t != delete_triangles.end(); t++) { (*t)->vertex_[0]->faces_.erase(*t); (*t)->vertex_[1]->faces_.erase(*t); (*t)->vertex_[2]->faces_.erase(*t); (*t)->edge_[0]->remove(*t); (*t)->edge_[1]->remove(*t); (*t)->edge_[2]->remove(*t); triangles_.remove(*t); number_of_triangles_--; delete *t; } HashSet delete_edges = point->edges_; HashSet::Iterator e; for (e = delete_edges.begin(); e != delete_edges.end(); e++) { (*e)->vertex_[0]->edges_.erase(*e); (*e)->vertex_[1]->edges_.erase(*e); edges_.remove(*e); number_of_edges_--; delete *e; } } points_.remove(point); number_of_points_--; delete point; } void TriangulatedSurface::remove(PointIterator point, bool deep) throw() { if (deep) { HashSet delete_triangles = (*point)->faces_; HashSet::Iterator t; for (t = delete_triangles.begin(); t != delete_triangles.end(); t++) { (*t)->vertex_[0]->faces_.erase(*t); (*t)->vertex_[1]->faces_.erase(*t); (*t)->vertex_[2]->faces_.erase(*t); (*t)->edge_[0]->remove(*t); (*t)->edge_[1]->remove(*t); (*t)->edge_[2]->remove(*t); triangles_.remove(*t); number_of_triangles_--; delete *t; } HashSet delete_edges = (*point)->edges_; HashSet::Iterator e; for (e = delete_edges.begin(); e != delete_edges.end(); e++) { (*e)->vertex_[0]->edges_.erase(*e); (*e)->vertex_[1]->edges_.erase(*e); edges_.remove(*e); number_of_edges_--; delete *e; } } points_.erase(point); number_of_points_--; delete *point; } void TriangulatedSurface::remove(TriangleEdge* edge, bool deep) throw() { if (deep) { if (edge->face_[0] != NULL) { remove(edge->face_[0],true); } if (edge->face_[0] != NULL) { remove(edge->face_[0],true); } edge->vertex_[0]->edges_.erase(edge); edge->vertex_[1]->edges_.erase(edge); } edges_.remove(edge); number_of_edges_--; delete edge; } void TriangulatedSurface::remove(EdgeIterator e, bool deep) throw() { TriangleEdge& edge = **e; if (deep) { if (edge.face_[0] != NULL) { remove(edge.face_[0],true); } if (edge.face_[0] != NULL) { remove(edge.face_[0],true); } edge.vertex_[0]->edges_.erase(*e); edge.vertex_[1]->edges_.erase(*e); } edges_.erase(e); number_of_edges_--; delete &edge; } void TriangulatedSurface::remove(Triangle* triangle, bool deep) throw() { if (deep) { triangle->vertex_[0]->faces_.erase(triangle); triangle->vertex_[1]->faces_.erase(triangle); triangle->vertex_[2]->faces_.erase(triangle); triangle->edge_[0]->remove(triangle); triangle->edge_[1]->remove(triangle); triangle->edge_[2]->remove(triangle); } triangles_.remove(triangle); number_of_triangles_--; delete triangle; } void TriangulatedSurface::remove(TriangleIterator t, bool deep) throw() { Triangle& tri = **t; if (deep) { tri.vertex_[0]->faces_.erase(*t); tri.vertex_[1]->faces_.erase(*t); tri.vertex_[2]->faces_.erase(*t); tri.edge_[0]->remove(*t); tri.edge_[1]->remove(*t); tri.edge_[2]->remove(*t); } triangles_.erase(t); number_of_triangles_--; delete &tri; } void TriangulatedSurface::exportSurface(Surface& surface) throw() { std::list::iterator p; Index i = 0; Vector3 point; Vector3 normal; for (p = points_.begin(); p != points_.end(); p++) { TrianglePoint& tri_point = **p; point.set((float)tri_point.point_.x, (float)tri_point.point_.y, (float)tri_point.point_.z); normal.set((float)tri_point.normal_.x, (float)tri_point.normal_.y, (float)tri_point.normal_.z); surface.vertex.push_back(point); surface.normal.push_back(normal); tri_point.index_ = i; i++; } std::list::iterator t; for (t = triangles_.begin(); t != triangles_.end(); t++) { Surface::Triangle triangle; triangle.v1 = (*t)->vertex_[0]->index_; triangle.v2 = (*t)->vertex_[1]->index_; triangle.v3 = (*t)->vertex_[2]->index_; surface.triangle.push_back(triangle); } } TriangulatedSurface& TriangulatedSurface::operator += (const TriangulatedSurface& surface) throw() { std::list::const_iterator p; for (p = surface.points_.begin(); p != surface.points_.end(); p++) { points_.push_back(*p); } std::list::const_iterator e; for (e = surface.edges_.begin(); e != surface.edges_.end(); e++) { edges_.push_back(*e); } std::list::const_iterator t; for (t = surface.triangles_.begin(); t != surface.triangles_.end(); t++) { triangles_.push_back(*t); } number_of_points_ += surface.number_of_points_; number_of_edges_ += surface.number_of_edges_; number_of_triangles_ += surface.number_of_triangles_; return *this; } void TriangulatedSurface::join(TriangulatedSurface& source) throw() { points_.splice(points_.end(),source.points_); edges_.splice(edges_.end(),source.edges_); triangles_.splice(triangles_.end(),source.triangles_); number_of_points_ += source.number_of_points_; number_of_edges_ += source.number_of_edges_; number_of_triangles_ += source.number_of_triangles_; source.number_of_points_ = 0; source.number_of_edges_ = 0; source.number_of_triangles_ = 0; } void TriangulatedSurface::shift(const TVector3& c) { std::list::iterator i; for (i = points_.begin(); i != points_.end(); i++) { (*i)->point_ += c; } } void TriangulatedSurface::blowUp(const double& r) { std::list::iterator i; for (i = points_.begin(); i != points_.end(); i++) { (*i)->point_ *= r; } } void TriangulatedSurface::setIndices() { Index i = 0; std::list::iterator p; for (p = points_.begin(); p != points_.end(); p++) { (*p)->index_ = i; i++; } i = 0; std::list::iterator e; for (e = edges_.begin(); e != edges_.end(); e++) { (*e)->index_ = i; i++; } i = 0; std::list::iterator t; for (t = triangles_.begin(); t != triangles_.end(); t++) { (*t)->index_ = i; i++; } } void TriangulatedSurface::cut(const TPlane3& plane, const double& fuzzy) { // delete all points on the wrong side of the plane std::list::iterator p; std::list::iterator next_point; double test_value; test_value = plane.n*plane.p+fuzzy; p = points_.begin(); while (p != points_.end()) { if (Maths::isLessOrEqual(plane.n*(*p)->point_,test_value)) { next_point = p; next_point++; delete *p; if (next_point == points_.end()) { points_.erase(p); p = points_.end(); } else { points_.erase(p); p = next_point; } number_of_points_--; } else { p++; } } } void TriangulatedSurface::shrink() { // delete all border triangles std::list delete_triangles; std::list::iterator t; for (t = triangles_.begin(); t != triangles_.end(); t++) { if (((*t)->edge_[0]->face_[0] == NULL) || ((*t)->edge_[0]->face_[1] == NULL) || ((*t)->edge_[1]->face_[0] == NULL) || ((*t)->edge_[1]->face_[1] == NULL) || ((*t)->edge_[2]->face_[0] == NULL) || ((*t)->edge_[2]->face_[1] == NULL) ) { delete_triangles.push_back(*t); } } for (t = delete_triangles.begin(); t != delete_triangles.end(); t++) { remove(*t,true); } // delete all "isolated" edges (edges with no triangles) std::list::iterator e = edges_.begin(); std::list::iterator next_edge; while (e != edges_.end()) { if (((*e)->face_[0] == NULL) && ((*e)->face_[1] == NULL)) { next_edge = e; next_edge++; (*e)->vertex_[0]->edges_.erase(*e); (*e)->vertex_[1]->edges_.erase(*e); delete *e; if (next_edge == edges_.end()) { edges_.erase(e); e = edges_.end(); } else { edges_.erase(e); e = next_edge; } number_of_edges_--; } else { e++; } } } void TriangulatedSurface::deleteIsolatedEdges() throw() { std::list::iterator e1; std::list::iterator e2; e1 = edges_.begin(); while (e1 != edges_.end()) { if ((*e1)->face_[0] == NULL) { e2 = e1; e2++; if (e2 == edges_.end()) { remove(e1); e1 = edges_.end(); } else { remove(e1); e1 = e2; } } else { e1++; } } } void TriangulatedSurface::deleteIsolatedPoints() throw() { std::list::iterator p1; std::list::iterator p2; p1 = points_.begin(); while (p1 != points_.end()) { if ((*p1)->faces_.size() == 0) { p2 = p1; p2++; if (p2 == points_.end()) { points_.erase(p1); p1 = points_.end(); } else { points_.erase(p1); p1 = p2; } number_of_points_--; } else { p1++; } } } void TriangulatedSurface::getBorder(std::list& border) { std::list::iterator e; for (e = edges_.begin(); e != edges_.end(); e++) { if (((*e)->face_[0] == NULL) || ((*e)->face_[1] == NULL)) { border.push_back(*e); } } } TriangulatedSurface::PointIterator TriangulatedSurface::beginPoint() throw() { return points_.begin(); } TriangulatedSurface::ConstPointIterator TriangulatedSurface::beginPoint() const throw() { return points_.begin(); } TriangulatedSurface::PointIterator TriangulatedSurface::endPoint() throw() { return points_.end(); } TriangulatedSurface::ConstPointIterator TriangulatedSurface::endPoint() const throw() { return points_.end(); } TriangulatedSurface::EdgeIterator TriangulatedSurface::beginEdge() throw() { return edges_.begin(); } TriangulatedSurface::ConstEdgeIterator TriangulatedSurface::beginEdge() const throw() { return edges_.begin(); } TriangulatedSurface::EdgeIterator TriangulatedSurface::endEdge() throw() { return edges_.end(); } TriangulatedSurface::ConstEdgeIterator TriangulatedSurface::endEdge() const throw() { return edges_.end(); } TriangulatedSurface::TriangleIterator TriangulatedSurface::beginTriangle() throw() { return triangles_.begin(); } TriangulatedSurface::ConstTriangleIterator TriangulatedSurface::beginTriangle() const throw() { return triangles_.begin(); } TriangulatedSurface::TriangleIterator TriangulatedSurface::endTriangle() throw() { return triangles_.end(); } TriangulatedSurface::ConstTriangleIterator TriangulatedSurface::endTriangle() const throw() { return triangles_.end(); } bool TriangulatedSurface::canBeCopied() const throw() { std::list::const_iterator p; Index i = 0; for (p = points_.begin(); p != points_.end(); p++) { if (*p == NULL) { return false; } if ((*p)->index_ != i) { return false; } i++; } std::list::const_iterator e; i = 0; for (e = edges_.begin(); e != edges_.end(); e++) { if (*e == NULL) { return false; } if ((*e)->index_ != i) { return false; } i++; } std::list::const_iterator t; i = 0; for (t = triangles_.begin(); t != triangles_.end(); t++) { if (*t == NULL) { return false; } if ((*t)->index_ != i) { return false; } i++; } return true; } void TriangulatedSurface::copy(const TriangulatedSurface& surface) throw() { if (surface.canBeCopied()) { number_of_points_ = surface.number_of_points_; number_of_edges_ = surface.number_of_edges_; number_of_triangles_ = surface.number_of_triangles_; std::vector point_vector(number_of_points_); std::list::const_iterator p; Position i = 0; for (p = surface.points_.begin(); p != surface.points_.end(); p++) { point_vector[i] = new TrianglePoint(**p,false); points_.push_back(point_vector[i]); i++; } std::vector edge_vector(number_of_edges_); std::list::const_iterator e; i = 0; for (e = surface.edges_.begin(); e != surface.edges_.end(); e++) { edge_vector[i] = new TriangleEdge(**e,false); edges_.push_back(edge_vector[i]); i++; } std::vector triangle_vector(number_of_triangles_); std::list::const_iterator t; i = 0; for (t = surface.triangles_.begin(); t != surface.triangles_.end(); t++) { triangle_vector[i] = new Triangle(**t,false); triangles_.push_back(triangle_vector[i]); i++; } HashSet::ConstIterator he; HashSet::ConstIterator ht; i = 0; for (p = surface.points_.begin(); p != surface.points_.end(); p++) { for (he = (*p)->edges_.begin(); he != (*p)->edges_.end(); he++) { point_vector[i]->edges_.insert(edge_vector[(*he)->index_]); } for (ht = (*p)->faces_.begin(); ht != (*p)->faces_.end(); ht++) { point_vector[i]->faces_.insert(triangle_vector[(*ht)->index_]); } i++; } i = 0; for (e = surface.edges_.begin(); e != surface.edges_.end(); e++) { edge_vector[i]->vertex_[0] = point_vector[(*e)->vertex_[0]->index_]; edge_vector[i]->vertex_[1] = point_vector[(*e)->vertex_[1]->index_]; if ((*e)->face_[0] != NULL) { edge_vector[i]->face_[0] = triangle_vector[(*e)->face_[0]->index_]; } if ((*e)->face_[1] != NULL) { edge_vector[i]->face_[1] = triangle_vector[(*e)->face_[1]->index_]; } i++; } i = 0; for (t = surface.triangles_.begin(); t != surface.triangles_.end(); t++) { triangle_vector[i]->vertex_[0] = point_vector[(*t)->vertex_[0]->index_]; triangle_vector[i]->vertex_[1] = point_vector[(*t)->vertex_[1]->index_]; triangle_vector[i]->vertex_[2] = point_vector[(*t)->vertex_[2]->index_]; triangle_vector[i]->edge_[0] = edge_vector[(*t)->edge_[0]->index_]; triangle_vector[i]->edge_[1] = edge_vector[(*t)->edge_[1]->index_]; triangle_vector[i]->edge_[2] = edge_vector[(*t)->edge_[2]->index_]; i++; } } } /////////////////////////////////////////////////////////////////////////////// TriangulatedSphere::TriangulatedSphere() throw() : TriangulatedSurface() { } TriangulatedSphere::TriangulatedSphere (const TriangulatedSphere& sphere, bool) throw() : TriangulatedSurface(sphere) { } TriangulatedSphere::~TriangulatedSphere() throw() { } void TriangulatedSphere::set(const TriangulatedSphere& sphere, bool) throw() { if (this != &sphere) { copy(sphere); } } TriangulatedSphere& TriangulatedSphere::operator = (const TriangulatedSphere& sphere) throw() { if (this != &sphere) { copy(sphere); } return *this; } void TriangulatedSphere::refine(Position iterations, bool out) { for (Position i = 0; i < iterations; i++) { refine(out); } std::list::iterator t; for (t = triangles_.begin(); t != triangles_.end(); t++) { TVector3 norm(((*t)->vertex_[1]->point_-(*t)->vertex_[0]->point_) % ((*t)->vertex_[2]->point_-(*t)->vertex_[0]->point_) ); if ((Maths::isGreater(norm*(*t)->vertex_[0]->point_,0) && (out == false) ) || (Maths::isLess(norm*(*t)->vertex_[0]->point_,0) && (out == true) ) ) { TrianglePoint* temp = (*t)->vertex_[1]; (*t)->vertex_[1] = (*t)->vertex_[2]; (*t)->vertex_[2] = temp; } } setIncidences(); } void TriangulatedSphere::refine(bool out) { std::vector faces(number_of_triangles_); std::list::iterator t; Position i = 0; for (t = triangles_.begin(); t != triangles_.end(); t++) { (*t)->index_ = i; faces[i].p[0] = (*t)->vertex_[0]; faces[i].p[1] = (*t)->vertex_[1]; faces[i].p[2] = (*t)->vertex_[2]; faces[i].pcount = 3; faces[i].ecount = 0; i++; } std::list new_edges; std::list::iterator e; for (e = edges_.begin(); e != edges_.end(); e++) { TrianglePoint* point1 = (*e)->vertex_[0]; TrianglePoint* point2 = (*e)->vertex_[1]; TrianglePoint* new_point = new TrianglePoint; new_point->point_ = (point1->point_+point2->point_).normalize(); if (out == true) { new_point->normal_ = new_point->point_; } else { new_point->normal_ = -new_point->point_; } TriangleEdge* new_edge1 = *e; new_edge1->vertex_[0] = point1; new_edge1->vertex_[1] = new_point; TriangleEdge* new_edge2 = new TriangleEdge; new_edge2->vertex_[0] = point2; new_edge2->vertex_[1] = new_point; i = (*e)->face_[0]->index_; faces[i].p[faces[i].pcount] = new_point; faces[i].pcount++; faces[i].e[faces[i].ecount] = new_edge1; faces[i].e[faces[i].ecount+1] = new_edge2; faces[i].ecount += 2; i = (*e)->face_[1]->index_; faces[i].p[faces[i].pcount] = new_point; faces[i].pcount++; faces[i].e[faces[i].ecount] = new_edge1; faces[i].e[faces[i].ecount+1] = new_edge2; faces[i].ecount += 2; new_edge1->face_[0] = NULL; new_edge1->face_[1] = NULL; new_edge2->face_[0] = NULL; new_edge2->face_[1] = NULL; points_.push_back(new_point); new_edges.push_back(new_edge2); } edges_.splice(edges_.end(),new_edges); i = 0; std::list new_triangles; for (t = triangles_.begin(); t != triangles_.end(); t++) { // create four new triangles Triangle* triangle[3]; for (Position k = 0; k < 3; k++) { triangle[k] = new Triangle; } // create three new edges for (Position k = 6; k < 9; k++) { faces[i].e[k] = new TriangleEdge; faces[i].e[k]->vertex_[0] = faces[i].p[k-3]; faces[i].e[k]->vertex_[1] = faces[i].p[(k-5)%3+3]; faces[i].e[k]->face_[0] = NULL; faces[i].e[k]->face_[1] = NULL; edges_.push_back(faces[i].e[k]); } // build the four triangles replacing the old one buildFourTriangles(faces[i], triangle[0],triangle[1], triangle[2],*t); new_triangles.push_back(triangle[0]); new_triangles.push_back(triangle[1]); new_triangles.push_back(triangle[2]); i++; } triangles_.splice(triangles_.end(),new_triangles); number_of_points_ += number_of_edges_; number_of_edges_ *= 4; number_of_triangles_ *= 4; } void TriangulatedSphere::buildFourTriangles (Face face, Triangle* face0, Triangle* face1, Triangle* face2, Triangle* face3) throw() { Triangle* triangle[3]; triangle[0] = face0; triangle[1] = face1; triangle[2] = face2; TriangleEdge* edge[3]; edge[0] = NULL; edge[1] = NULL; edge[2] = NULL; for (Position k = 0; k < 3; k++) { // create a smaller triangle containing face.p[k] TriangleEdge* first = NULL; TriangleEdge* second = NULL; TrianglePoint* p1 = NULL; TrianglePoint* p2 = NULL; TrianglePoint* p3 = face.p[k]; Position i = 0; while (first == NULL) { if (face.e[i]->vertex_[0] == p3) { first = face.e[i]; p1 = face.e[i]->vertex_[1]; } else { if (face.e[i]->vertex_[1] == p3) { first = face.e[i]; p1 = face.e[i]->vertex_[0]; } } i++; } while (second == NULL) { if (face.e[i]->vertex_[0] == p3) { second = face.e[i]; p2 = face.e[i]->vertex_[1]; } else { if (face.e[i]->vertex_[1] == p3) { second = face.e[i]; p2 = face.e[i]->vertex_[0]; } } i++; } i = 6; while (edge[k] == NULL) { if (((face.e[i]->vertex_[0] == p1) && (face.e[i]->vertex_[1] == p2) ) || ((face.e[i]->vertex_[0] == p2) && (face.e[i]->vertex_[1] == p1) ) ) { edge[k] = face.e[i]; } i++; } triangle[k]->vertex_[0] = p1; triangle[k]->vertex_[1] = p2; triangle[k]->vertex_[2] = p3; triangle[k]->edge_[0] = first; triangle[k]->edge_[1] = second; triangle[k]->edge_[2] = edge[k]; if (first->face_[0] == NULL) { first->face_[0] = triangle[k]; } else { first->face_[1] = triangle[k]; } if (second->face_[0] == NULL) { second->face_[0] = triangle[k]; } else { second->face_[1] = triangle[k]; } edge[k]->face_[0] = triangle[k]; edge[k]->face_[1] = face3; } face3->vertex_[0] = face.p[3]; face3->vertex_[1] = face.p[4]; face3->vertex_[2] = face.p[5]; face3->edge_[0] = edge[0]; face3->edge_[1] = edge[1]; face3->edge_[2] = edge[2]; } void TriangulatedSphere::setIncidences() { std::list::iterator p; for (p = points_.begin(); p != points_.end(); p++) { (*p)->edges_.clear(); (*p)->faces_.clear(); } std::list::iterator e; for (e = edges_.begin(); e != edges_.end(); e++) { (*e)->vertex_[0]->edges_.insert(*e); (*e)->vertex_[0]->faces_.insert((*e)->face_[0]); (*e)->vertex_[0]->faces_.insert((*e)->face_[1]); (*e)->vertex_[1]->edges_.insert(*e); (*e)->vertex_[1]->faces_.insert((*e)->face_[0]); (*e)->vertex_[1]->faces_.insert((*e)->face_[1]); } } void TriangulatedSphere::icosaeder(bool out) { clear(); TrianglePoint* point0 = new TrianglePoint; TrianglePoint* point1 = new TrianglePoint; TrianglePoint* point2 = new TrianglePoint; TrianglePoint* point3 = new TrianglePoint; TrianglePoint* point4 = new TrianglePoint; TrianglePoint* point5 = new TrianglePoint; TrianglePoint* point6 = new TrianglePoint; TrianglePoint* point7 = new TrianglePoint; TrianglePoint* point8 = new TrianglePoint; TrianglePoint* point9 = new TrianglePoint; TrianglePoint* point10 = new TrianglePoint; TrianglePoint* point11 = new TrianglePoint; TriangleEdge* edge0 = new TriangleEdge; TriangleEdge* edge1 = new TriangleEdge; TriangleEdge* edge2 = new TriangleEdge; TriangleEdge* edge3 = new TriangleEdge; TriangleEdge* edge4 = new TriangleEdge; TriangleEdge* edge5 = new TriangleEdge; TriangleEdge* edge6 = new TriangleEdge; TriangleEdge* edge7 = new TriangleEdge; TriangleEdge* edge8 = new TriangleEdge; TriangleEdge* edge9 = new TriangleEdge; TriangleEdge* edge10 = new TriangleEdge; TriangleEdge* edge11 = new TriangleEdge; TriangleEdge* edge12 = new TriangleEdge; TriangleEdge* edge13 = new TriangleEdge; TriangleEdge* edge14 = new TriangleEdge; TriangleEdge* edge15 = new TriangleEdge; TriangleEdge* edge16 = new TriangleEdge; TriangleEdge* edge17 = new TriangleEdge; TriangleEdge* edge18 = new TriangleEdge; TriangleEdge* edge19 = new TriangleEdge; TriangleEdge* edge20 = new TriangleEdge; TriangleEdge* edge21 = new TriangleEdge; TriangleEdge* edge22 = new TriangleEdge; TriangleEdge* edge23 = new TriangleEdge; TriangleEdge* edge24 = new TriangleEdge; TriangleEdge* edge25 = new TriangleEdge; TriangleEdge* edge26 = new TriangleEdge; TriangleEdge* edge27 = new TriangleEdge; TriangleEdge* edge28 = new TriangleEdge; TriangleEdge* edge29 = new TriangleEdge; Triangle* t0 = new Triangle; Triangle* t1 = new Triangle; Triangle* t2 = new Triangle; Triangle* t3 = new Triangle; Triangle* t4 = new Triangle; Triangle* t5 = new Triangle; Triangle* t6 = new Triangle; Triangle* t7 = new Triangle; Triangle* t8 = new Triangle; Triangle* t9 = new Triangle; Triangle* t10 = new Triangle; Triangle* t11 = new Triangle; Triangle* t12 = new Triangle; Triangle* t13 = new Triangle; Triangle* t14 = new Triangle; Triangle* t15 = new Triangle; Triangle* t16 = new Triangle; Triangle* t17 = new Triangle; Triangle* t18 = new Triangle; Triangle* t19 = new Triangle; number_of_points_ =12; number_of_edges_ = 30; number_of_triangles_ = 20; point0->point_ = TVector3( 0.0 , 0.0 , 1.0 ); point1->point_ = TVector3( 0.894427, 0.0 , 0.4472135); point2->point_ = TVector3( 0.276393, 0.850651, 0.4472135); point3->point_ = TVector3(-0.723607, 0.525731, 0.4472135); point4->point_ = TVector3(-0.723607,-0.525731, 0.4472135); point5->point_ = TVector3( 0.276393,-0.850651, 0.4472135); point6->point_ = TVector3( 0.723607, 0.525731,-0.4472135); point7->point_ = TVector3(-0.276393, 0.850651,-0.4472135); point8->point_ = TVector3(-0.894427, 0.0 ,-0.4472135); point9->point_ = TVector3(-0.276393,-0.850651,-0.4472135); point10->point_ = TVector3( 0.723607,-0.525731,-0.4472135); point11->point_ = TVector3( 0.0 , 0.0 ,-1.0 ); if (out == true) { point0->normal_ = point0->point_; point1->normal_ = point1->point_; point2->normal_ = point2->point_; point3->normal_ = point3->point_; point4->normal_ = point4->point_; point5->normal_ = point5->point_; point6->normal_ = point6->point_; point7->normal_ = point7->point_; point8->normal_ = point8->point_; point9->normal_ = point9->point_; point10->normal_ = point10->point_; point11->normal_ = point11->point_; } else { point0->normal_ = -point0->point_; point1->normal_ = -point1->point_; point2->normal_ = -point2->point_; point3->normal_ = -point3->point_; point4->normal_ = -point4->point_; point5->normal_ = -point5->point_; point6->normal_ = -point6->point_; point7->normal_ = -point7->point_; point8->normal_ = -point8->point_; point9->normal_ = -point9->point_; point10->normal_ = -point10->point_; point11->normal_ = -point11->point_; } point0->faces_.insert(t0); point0->faces_.insert(t1); point0->faces_.insert(t2); point0->faces_.insert(t3); point0->faces_.insert(t4); point1->faces_.insert(t0); point1->faces_.insert(t4); point1->faces_.insert(t5); point1->faces_.insert(t13); point1->faces_.insert(t14); point2->faces_.insert(t0); point2->faces_.insert(t1); point2->faces_.insert(t6); point2->faces_.insert(t7); point2->faces_.insert(t5); point3->faces_.insert(t1); point3->faces_.insert(t2); point3->faces_.insert(t7); point3->faces_.insert(t8); point3->faces_.insert(t9); point4->faces_.insert(t2); point4->faces_.insert(t3); point4->faces_.insert(t9); point4->faces_.insert(t10); point4->faces_.insert(t11); point5->faces_.insert(t4); point5->faces_.insert(t11); point5->faces_.insert(t12); point5->faces_.insert(t3); point5->faces_.insert(t14); point6->faces_.insert(t5); point6->faces_.insert(t6); point6->faces_.insert(t13); point6->faces_.insert(t15); point6->faces_.insert(t19); point7->faces_.insert(t6); point7->faces_.insert(t7); point7->faces_.insert(t8); point7->faces_.insert(t15); point7->faces_.insert(t16); point8->faces_.insert(t8); point8->faces_.insert(t9); point8->faces_.insert(t10); point8->faces_.insert(t16); point8->faces_.insert(t17); point9->faces_.insert(t10); point9->faces_.insert(t11); point9->faces_.insert(t12); point9->faces_.insert(t17); point9->faces_.insert(t18); point10->faces_.insert(t12); point10->faces_.insert(t13); point10->faces_.insert(t14); point10->faces_.insert(t18); point10->faces_.insert(t19); point11->faces_.insert(t15); point11->faces_.insert(t16); point11->faces_.insert(t17); point11->faces_.insert(t18); point11->faces_.insert(t19); point0->edges_.insert(edge0); point0->edges_.insert(edge1); point0->edges_.insert(edge3); point0->edges_.insert(edge5); point0->edges_.insert(edge7); point1->edges_.insert(edge1); point1->edges_.insert(edge2); point1->edges_.insert(edge9); point1->edges_.insert(edge10); point1->edges_.insert(edge23); point2->edges_.insert(edge0); point2->edges_.insert(edge2); point2->edges_.insert(edge4); point2->edges_.insert(edge11); point2->edges_.insert(edge12); point3->edges_.insert(edge3); point3->edges_.insert(edge4); point3->edges_.insert(edge6); point3->edges_.insert(edge14); point3->edges_.insert(edge15); point4->edges_.insert(edge5); point4->edges_.insert(edge6); point4->edges_.insert(edge8); point4->edges_.insert(edge17); point4->edges_.insert(edge18); point5->edges_.insert(edge7); point5->edges_.insert(edge8); point5->edges_.insert(edge9); point5->edges_.insert(edge20); point5->edges_.insert(edge21); point6->edges_.insert(edge10); point6->edges_.insert(edge11); point6->edges_.insert(edge13); point6->edges_.insert(edge24); point6->edges_.insert(edge25); point7->edges_.insert(edge12); point7->edges_.insert(edge13); point7->edges_.insert(edge14); point7->edges_.insert(edge16); point7->edges_.insert(edge26); point8->edges_.insert(edge15); point8->edges_.insert(edge16); point8->edges_.insert(edge17); point8->edges_.insert(edge19); point8->edges_.insert(edge27); point9->edges_.insert(edge18); point9->edges_.insert(edge19); point9->edges_.insert(edge20); point9->edges_.insert(edge22); point9->edges_.insert(edge28); point10->edges_.insert(edge21); point10->edges_.insert(edge22); point10->edges_.insert(edge23); point10->edges_.insert(edge24); point10->edges_.insert(edge29); point11->edges_.insert(edge25); point11->edges_.insert(edge26); point11->edges_.insert(edge27); point11->edges_.insert(edge28); point11->edges_.insert(edge29); points_.push_back(point0); points_.push_back(point1); points_.push_back(point2); points_.push_back(point3); points_.push_back(point4); points_.push_back(point5); points_.push_back(point6); points_.push_back(point7); points_.push_back(point8); points_.push_back(point9); points_.push_back(point10); points_.push_back(point11); edge0->vertex_[0] = point2; edge0->vertex_[1] = point0; edge1->vertex_[0] = point0; edge1->vertex_[1] = point1; edge2->vertex_[0] = point1; edge2->vertex_[1] = point2; edge3->vertex_[0] = point3; edge3->vertex_[1] = point0; edge4->vertex_[0] = point2; edge4->vertex_[1] = point3; edge5->vertex_[0] = point4; edge5->vertex_[1] = point0; edge6->vertex_[0] = point3; edge6->vertex_[1] = point4; edge7->vertex_[0] = point5; edge7->vertex_[1] = point0; edge8->vertex_[0] = point4; edge8->vertex_[1] = point5; edge9->vertex_[0] = point5; edge9->vertex_[1] = point1; edge10->vertex_[0] = point1; edge10->vertex_[1] = point6; edge11->vertex_[0] = point6; edge11->vertex_[1] = point2; edge12->vertex_[0] = point7; edge12->vertex_[1] = point2; edge13->vertex_[0] = point6; edge13->vertex_[1] = point7; edge14->vertex_[0] = point7; edge14->vertex_[1] = point3; edge15->vertex_[0] = point8; edge15->vertex_[1] = point3; edge16->vertex_[0] = point7; edge16->vertex_[1] = point8; edge17->vertex_[0] = point8; edge17->vertex_[1] = point4; edge18->vertex_[0] = point9; edge18->vertex_[1] = point4; edge19->vertex_[0] = point8; edge19->vertex_[1] = point9; edge20->vertex_[0] = point9; edge20->vertex_[1] = point5; edge21->vertex_[0] = point10; edge21->vertex_[1] = point5; edge22->vertex_[0] = point9; edge22->vertex_[1] = point10; edge23->vertex_[0] = point1; edge23->vertex_[1] = point10; edge24->vertex_[0] = point10; edge24->vertex_[1] = point6; edge25->vertex_[0] = point6; edge25->vertex_[1] = point11; edge26->vertex_[0] = point11; edge26->vertex_[1] = point7; edge27->vertex_[0] = point11; edge27->vertex_[1] = point8; edge28->vertex_[0] = point11; edge28->vertex_[1] = point9; edge29->vertex_[0] = point11; edge29->vertex_[1] = point10; edge0->face_[0] = t0; edge0->face_[1] = t1; edge1->face_[0] = t0; edge1->face_[1] = t4; edge2->face_[0] = t0; edge2->face_[1] = t5; edge3->face_[0] = t1; edge3->face_[1] = t2; edge4->face_[0] = t1; edge4->face_[1] = t7; edge5->face_[0] = t2; edge5->face_[1] = t3; edge6->face_[0] = t2; edge6->face_[1] = t9; edge7->face_[0] = t3; edge7->face_[1] = t4; edge8->face_[0] = t3; edge8->face_[1] = t11; edge9->face_[0] = t4; edge9->face_[1] = t14; edge10->face_[0] = t5; edge10->face_[1] = t13; edge11->face_[0] = t5; edge11->face_[1] = t6; edge12->face_[0] = t6; edge12->face_[1] = t7; edge13->face_[0] = t6; edge13->face_[1] = t15; edge14->face_[0] = t7; edge14->face_[1] = t8; edge15->face_[0] = t8; edge15->face_[1] = t9; edge16->face_[0] = t8; edge16->face_[1] = t16; edge17->face_[0] = t9; edge17->face_[1] = t10; edge18->face_[0] = t10; edge18->face_[1] = t11; edge19->face_[0] = t10; edge19->face_[1] = t17; edge20->face_[0] = t11; edge20->face_[1] = t12; edge21->face_[0] = t12; edge21->face_[1] = t14; edge22->face_[0] = t12; edge22->face_[1] = t18; edge23->face_[0] = t13; edge23->face_[1] = t14; edge24->face_[0] = t13; edge24->face_[1] = t19; edge25->face_[0] = t15; edge25->face_[1] = t19; edge26->face_[0] = t15; edge26->face_[1] = t16; edge27->face_[0] = t16; edge27->face_[1] = t17; edge28->face_[0] = t17; edge28->face_[1] = t18; edge29->face_[0] = t18; edge29->face_[1] = t19; edges_.push_back(edge0); edges_.push_back(edge1); edges_.push_back(edge2); edges_.push_back(edge3); edges_.push_back(edge4); edges_.push_back(edge5); edges_.push_back(edge6); edges_.push_back(edge7); edges_.push_back(edge8); edges_.push_back(edge9); edges_.push_back(edge10); edges_.push_back(edge11); edges_.push_back(edge12); edges_.push_back(edge13); edges_.push_back(edge14); edges_.push_back(edge15); edges_.push_back(edge16); edges_.push_back(edge17); edges_.push_back(edge18); edges_.push_back(edge19); edges_.push_back(edge20); edges_.push_back(edge21); edges_.push_back(edge22); edges_.push_back(edge23); edges_.push_back(edge24); edges_.push_back(edge25); edges_.push_back(edge26); edges_.push_back(edge27); edges_.push_back(edge28); edges_.push_back(edge29); t0->vertex_[0] = point2; t0->vertex_[1] = point0; t0->vertex_[2] = point1; t1->vertex_[0] = point3; t1->vertex_[1] = point0; t1->vertex_[2] = point2; t2->vertex_[0] = point4; t2->vertex_[1] = point0; t2->vertex_[2] = point3; t3->vertex_[0] = point5; t3->vertex_[1] = point0; t3->vertex_[2] = point4; t4->vertex_[0] = point1; t4->vertex_[1] = point0; t4->vertex_[2] = point5; t5->vertex_[0] = point2; t5->vertex_[1] = point1; t5->vertex_[2] = point6; t6->vertex_[0] = point7; t6->vertex_[1] = point2; t6->vertex_[2] = point6; t7->vertex_[0] = point3; t7->vertex_[1] = point2; t7->vertex_[2] = point7; t8->vertex_[0] = point8; t8->vertex_[1] = point3; t8->vertex_[2] = point7; t9->vertex_[0] = point4; t9->vertex_[1] = point3; t9->vertex_[2] = point8; t10->vertex_[0] = point9; t10->vertex_[1] = point4; t10->vertex_[2] = point8; t11->vertex_[0] = point5; t11->vertex_[1] = point4; t11->vertex_[2] = point9; t12->vertex_[0] = point10; t12->vertex_[1] = point5; t12->vertex_[2] = point9; t13->vertex_[0] = point6; t13->vertex_[1] = point1; t13->vertex_[2] = point10; t14->vertex_[0] = point1; t14->vertex_[1] = point5; t14->vertex_[2] = point10; t15->vertex_[0] = point6; t15->vertex_[1] = point11; t15->vertex_[2] = point7; t16->vertex_[0] = point7; t16->vertex_[1] = point11; t16->vertex_[2] = point8; t17->vertex_[0] = point8; t17->vertex_[1] = point11; t17->vertex_[2] = point9; t18->vertex_[0] = point9; t18->vertex_[1] = point11; t18->vertex_[2] = point10; t19->vertex_[0] = point10; t19->vertex_[1] = point11; t19->vertex_[2] = point6; t0->edge_[0] = edge0; t0->edge_[1] = edge1; t0->edge_[2] = edge2; t1->edge_[0] = edge0; t1->edge_[1] = edge3; t1->edge_[2] = edge4; t2->edge_[0] = edge3; t2->edge_[1] = edge5; t2->edge_[2] = edge6; t3->edge_[0] = edge5; t3->edge_[1] = edge7; t3->edge_[2] = edge8; t4->edge_[0] = edge1; t4->edge_[1] = edge7; t4->edge_[2] = edge9; t5->edge_[0] = edge2; t5->edge_[1] = edge10; t5->edge_[2] = edge11; t6->edge_[0] = edge11; t6->edge_[1] = edge12; t6->edge_[2] = edge13; t7->edge_[0] = edge4; t7->edge_[1] = edge12; t7->edge_[2] = edge14; t8->edge_[0] = edge14; t8->edge_[1] = edge15; t8->edge_[2] = edge16; t9->edge_[0] = edge6; t9->edge_[1] = edge15; t9->edge_[2] = edge17; t10->edge_[0] = edge17; t10->edge_[1] = edge18; t10->edge_[2] = edge19; t11->edge_[0] = edge8; t11->edge_[1] = edge18; t11->edge_[2] = edge20; t12->edge_[0] = edge20; t12->edge_[1] = edge21; t12->edge_[2] = edge22; t13->edge_[0] = edge10; t13->edge_[1] = edge23; t13->edge_[2] = edge24; t14->edge_[0] = edge9; t14->edge_[1] = edge21; t14->edge_[2] = edge23; t15->edge_[0] = edge13; t15->edge_[1] = edge25; t15->edge_[2] = edge26; t16->edge_[0] = edge16; t16->edge_[1] = edge26; t16->edge_[2] = edge27; t17->edge_[0] = edge19; t17->edge_[1] = edge27; t17->edge_[2] = edge28; t18->edge_[0] = edge22; t18->edge_[1] = edge28; t18->edge_[2] = edge29; t19->edge_[0] = edge24; t19->edge_[1] = edge25; t19->edge_[2] = edge29; triangles_.push_back(t0); triangles_.push_back(t1); triangles_.push_back(t2); triangles_.push_back(t3); triangles_.push_back(t4); triangles_.push_back(t5); triangles_.push_back(t6); triangles_.push_back(t7); triangles_.push_back(t8); triangles_.push_back(t9); triangles_.push_back(t10); triangles_.push_back(t11); triangles_.push_back(t12); triangles_.push_back(t13); triangles_.push_back(t14); triangles_.push_back(t15); triangles_.push_back(t16); triangles_.push_back(t17); triangles_.push_back(t18); triangles_.push_back(t19); } std::ostream& operator << (std::ostream& s, const TriangulatedSurface& surface) { s << "Points: " << surface.numberOfPoints() << "\n"; TriangulatedSurface::ConstPointIterator p; for (p = surface.beginPoint(); p != surface.endPoint(); p++) { s << **p << "\n"; } s << "Edges: " << surface.numberOfEdges() << "\n"; TriangulatedSurface::ConstEdgeIterator e; for (e = surface.beginEdge(); e != surface.endEdge(); e++) { s << **e << "\n"; } s << "Triangles: " << surface.numberOfTriangles() << "\n"; TriangulatedSurface::ConstTriangleIterator t; for (t = surface.beginTriangle(); t != surface.endTriangle(); t++) { s << **t << "\n"; } return s; } } // namespace BALL ugene-1.9.8/src/plugins_3rdparty/ball/src/source/STRUCTURE/RSVertex.cpp0000644000175000017500000000516511651544326024257 0ustar ilyailya// -*- Mode: C++; tab-width: 2; -*- // vi: set ts=2: // // $Id: RSVertex.C,v 1.4 2002-12-17 14:13:19 anker Exp $ #include #include #include namespace BALL { RSVertex::RSVertex() throw() : GraphVertex< RSVertex,RSEdge,RSFace >(), atom_(-1) { } RSVertex::RSVertex(const RSVertex& rsvertex, bool deep) throw() : GraphVertex< RSVertex,RSEdge,RSFace >(rsvertex,deep), atom_(rsvertex.atom_) { } RSVertex::RSVertex(Index atom) throw() : GraphVertex< RSVertex,RSEdge,RSFace >(), atom_(atom) { } RSVertex::~RSVertex() throw() { } void RSVertex::set(const RSVertex& rsvertex, bool deep) throw() { if (this != &rsvertex) { GraphVertex< RSVertex,RSEdge,RSFace >::set(rsvertex,deep); atom_ = rsvertex.atom_; } } RSVertex& RSVertex::operator = (const RSVertex& rsvertex) throw() { if (this != &rsvertex) { GraphVertex< RSVertex,RSEdge,RSFace >::operator = (rsvertex); atom_ = rsvertex.atom_; } return *this; } void RSVertex::setAtom(Index atom) throw() { atom_ = atom; } Index RSVertex::getAtom() const throw() { return atom_; } bool RSVertex::operator == (const RSVertex& rsvertex) const throw() { if (atom_ != rsvertex.atom_) { return false; } HashSet::ConstIterator e; for (e = edges_.begin(); e != edges_.end(); e++) { if (rsvertex.edges_.has(*e) == false) { return false; } } for (e = rsvertex.edges_.begin(); e != rsvertex.edges_.end(); e++) { if (edges_.has(*e) == false) { return false; } } HashSet::ConstIterator f; for (f = faces_.begin(); f != faces_.end(); f++) { if (rsvertex.faces_.has(*f) == false) { return false; } } for (f = rsvertex.faces_.begin(); f != rsvertex.faces_.end(); f++) { if (faces_.has(*f) == false) { return false; } } return true; } bool RSVertex::operator != (const RSVertex& rsvertex) const throw() { return ( ! (*this == rsvertex) ); } bool RSVertex::operator *= (const RSVertex& rsvertex) const throw() { return (atom_ == rsvertex.atom_); } std::ostream& operator << (std::ostream& s, const RSVertex& rsvertex) { s << "RSVERTEX" << rsvertex.getIndex() << "(" << rsvertex.getAtom() << " ["; RSVertex::ConstEdgeIterator e; for (e = rsvertex.beginEdge(); e != rsvertex.endEdge(); e++) { s << (*e)->getIndex() << ' '; } s << "] ["; RSVertex::ConstFaceIterator f; for (f = rsvertex.beginFace(); f != rsvertex.endFace(); f++) { s << (*f)->getIndex() << ' '; } s << "])"; return s; } } // namespace BALL ugene-1.9.8/src/plugins_3rdparty/ball/src/source/STRUCTURE/solventAccessibleSurface.cpp0000644000175000017500000002036311651544326027513 0ustar ilyailya// -*- Mode: C++; tab-width: 2; -*- // vi: set ts=2: // // $Id: solventAccessibleSurface.C,v 1.1 2002-12-17 17:14:22 anker Exp $ #include #include #include #include #include #include #include namespace BALL { SolventAccessibleSurface::SolventAccessibleSurface() throw() : number_of_vertices_(0), vertices_(), number_of_edges_(0), edges_(), number_of_faces_(0), faces_(), reduced_surface_(NULL) { } SolventAccessibleSurface::SolventAccessibleSurface (const SolventAccessibleSurface& ,bool)//sas, bool) throw() : number_of_vertices_(0), vertices_(), number_of_edges_(0), edges_(), number_of_faces_(0), faces_(), reduced_surface_(NULL) { // ????? !!! //for (Position i = 0; i < number_of_vertices_; i++) //{ // vertices_[i] = new SASVertex(*ses.vertices_[i],false); //} //for (Position i = 0; i < number_of_edges_; i++) //{ // edges_[i] = new SASVertex(*ses.edges_[i],false); //} // ::std::list::const_iterator se; //for (se = ses.singular_edges_.begin(); se != ses.singular_edges_.end(); se++) //{ // singular_edges_.push_back(edges_[(*se)->index_]); //} //for (Position i = 0; i < number_of_contact_faces_; i++) //{ // contact_faces_[i] = new SASFace(*ses.contact_faces_[i],false); //} //for (Position i = 0; i < number_of_toric_faces_; i++) //{ // toric_faces_[i] = new SASFace(*ses.toric_faces_[i],false); //} //for (Position i = 0; i < number_of_spheric_faces_; i++) //{ // spheric_faces_[i] = new SASFace(*ses.spheric_faces_[i],false); //} } SolventAccessibleSurface::SolventAccessibleSurface(ReducedSurface* reduced_surface) throw() : number_of_vertices_(0), vertices_(), number_of_edges_(0), edges_(), number_of_faces_(0), faces_(), reduced_surface_(reduced_surface) { } SolventAccessibleSurface::~SolventAccessibleSurface() throw() { clear(); } void SolventAccessibleSurface::setVertex(SASVertex* vertex, Position i) throw(Exception::IndexOverflow) { if (i < number_of_vertices_) { vertices_[i] = vertex; } else { throw Exception::IndexOverflow(__FILE__,__LINE__, i,number_of_vertices_+1); } } SASVertex* SolventAccessibleSurface::getVertex(Position i) const throw(Exception::IndexOverflow) { if (i < number_of_vertices_) { return vertices_[i]; } else { throw Exception::IndexOverflow(__FILE__,__LINE__, i,number_of_vertices_+1); } } Size SolventAccessibleSurface::numberOfVertices() const throw() { return number_of_vertices_; } void SolventAccessibleSurface::setEdge(SASEdge* edge, Position i) throw(Exception::IndexOverflow) { if (i < number_of_edges_) { edges_[i] = edge; } else { throw Exception::IndexOverflow(__FILE__,__LINE__,i,number_of_edges_+1); } } SASEdge* SolventAccessibleSurface::getEdge(Position i) const throw(Exception::IndexOverflow) { if (i < number_of_edges_) { return edges_[i]; } else { throw Exception::IndexOverflow(__FILE__,__LINE__,i,number_of_edges_+1); } } Size SolventAccessibleSurface::numberOfEdges() const throw() { return number_of_edges_; } void SolventAccessibleSurface::setFace(SASFace* face, Position i) throw(Exception::IndexOverflow) { if (i < number_of_faces_) { faces_[i] = face; } else { throw Exception::IndexOverflow(__FILE__,__LINE__,i,number_of_faces_+1); } } SASFace* SolventAccessibleSurface::getFace(Position i) const throw(Exception::IndexOverflow) { if (i < number_of_faces_) { return faces_[i]; } else { throw Exception::IndexOverflow(__FILE__,__LINE__,i,number_of_faces_+1); } } Size SolventAccessibleSurface::numberOfFaces() const throw() { return number_of_faces_; } void SolventAccessibleSurface::setRS(ReducedSurface* rs) throw() { reduced_surface_ = rs; } ReducedSurface* SolventAccessibleSurface::getRS() const throw() { return reduced_surface_; } void SolventAccessibleSurface::clear() { Position i; for (i = 0; i < number_of_vertices_; i++) { delete vertices_[i]; } for (i = 0; i < number_of_edges_; i++) { delete edges_[i]; } for (i = 0; i < number_of_faces_; i++) { delete faces_[i]; } vertices_.clear(); edges_.clear(); faces_.clear(); number_of_vertices_ = 0; number_of_edges_ = 0; number_of_faces_ = 0; } void SolventAccessibleSurface::compute() throw() { preProcessing(); get(); } void SolventAccessibleSurface::preProcessing() throw() { number_of_vertices_ = reduced_surface_->number_of_faces_; number_of_edges_ = reduced_surface_->number_of_edges_; number_of_faces_ = reduced_surface_->number_of_vertices_; SASVertex* vertex; for (Position i = 0; i < number_of_vertices_; i++) { vertex = new SASVertex; vertex->index_ = i; vertices_.push_back(vertex); } SASEdge* edge; for (Position i = 0; i < number_of_edges_; i++) { edge = new SASEdge; edge->index_ = i; edges_.push_back(edge); } SASFace* face; for (Position i = 0; i < number_of_faces_; i++) { face = new SASFace; face->index_ = i; faces_.push_back(face); } } void SolventAccessibleSurface::get() throw() { for (Position i = 0; i < number_of_vertices_; i++) { createVertex(i); } for (Position i = 0; i < number_of_edges_; i++) { createEdge(i); } for (Position i = 0; i < number_of_faces_; i++) { createFace(i); } } void SolventAccessibleSurface::createVertex(Position j) throw() { SASVertex* vertex = vertices_[j]; vertex->index_ = j; RSFace* rsface = reduced_surface_->faces_[j]; vertex->point_ = rsface->center_; for (Position i = 0; i < 3; i++) { vertex->edges_.insert(edges_[rsface->edge_[i]->index_]); vertex->faces_.insert(faces_[rsface->vertex_[i]->index_]); } } void SolventAccessibleSurface::createEdge(Position j) throw() { SASEdge* edge = edges_[j]; edge->index_ = j; RSEdge* rsedge = reduced_surface_->edges_[j]; if (rsedge->face_[0] != NULL) { edge->vertex_[0] = vertices_[rsedge->face_[0]->index_]; edge->vertex_[1] = vertices_[rsedge->face_[1]->index_]; } else { edge->vertex_[0] = NULL; edge->vertex_[1] = NULL; } edge->face_[0] = faces_[rsedge->vertex_[0]->index_]; edge->face_[1] = faces_[rsedge->vertex_[1]->index_]; edge->angle_ = rsedge->angle_; edge->circle_.p = rsedge->center_of_torus_; edge->circle_.radius = rsedge->radius_of_torus_; TSphere3 atom1(reduced_surface_->atom_[rsedge->vertex_[0]->atom_]); TSphere3 atom2(reduced_surface_->atom_[rsedge->vertex_[1]->atom_]); edge->circle_.n = atom1.p-atom2.p; } void SolventAccessibleSurface::createFace(Position j) throw() { SASFace* face = faces_[j]; face->index_ = j; RSVertex* rsvertex = reduced_surface_->vertices_[j]; HashSet::Iterator e; for (e = rsvertex->edges_.begin(); e != rsvertex->edges_.end(); e++) { face->edge_.push_back(edges_[(*e)->index_]); if ((*e)->vertex_[0]->index_ == face->index_) { face->orientation_.push_back(true); } else { face->orientation_.push_back(false); } } HashSet::Iterator f; for (f = rsvertex->faces_.begin(); f != rsvertex->faces_.end(); f++) { face->vertex_.push_back(vertices_[(*f)->index_]); } face->sphere_ = reduced_surface_->atom_[rsvertex->atom_]; face->sphere_.radius += reduced_surface_->probe_radius_; } std::ostream& operator << (std::ostream& s, const SolventAccessibleSurface& sas) { s << "Vertices:\n"; for (Position i = 0; i < sas.numberOfVertices(); i++) { if (sas.getVertex(i) != NULL) { s << " " << *(sas.getVertex(i)) << "\n"; } else { s << " --\n"; } } s << "Edges:\n"; for (Position i = 0; i < sas.numberOfEdges(); i++) { if (sas.getEdge(i) != NULL) { s << " " << *(sas.getEdge(i)) << "\n"; } else { s << " --\n"; } } s << "Faces:\n"; for (Position i = 0; i < sas.numberOfFaces(); i++) { if (sas.getFace(i) != NULL) { s << " " << *(sas.getFace(i)) << "\n"; } else { s << " --\n"; } } return s; } } // namespace BALL ugene-1.9.8/src/plugins_3rdparty/ball/src/source/STRUCTURE/SESEdge.cpp0000644000175000017500000001025611651544326023751 0ustar ilyailya// -*- Mode: C++; tab-width: 2; -*- // vi: set ts=2: // // $Id: SESEdge.C,v 1.4 2002-12-17 14:13:20 anker Exp $ #include #include #include #include #include namespace BALL { SESEdge::SESEdge() throw() : GraphEdge< SESVertex,SESEdge,SESFace >(), circle_(), rsedge_(NULL), type_(SESEdge::TYPE_CONCAVE) { } SESEdge::SESEdge(const SESEdge& sesedge, bool deep) throw() : GraphEdge< SESVertex,SESEdge,SESFace >(sesedge,deep), circle_(sesedge.circle_), rsedge_(NULL), type_(sesedge.type_) { if (deep) { rsedge_ = sesedge.rsedge_; } } SESEdge::SESEdge(SESVertex* vertex0, SESVertex* vertex1, SESFace* face0, SESFace* face1, const TCircle3& circle, RSEdge* rsedge, Type type, Index index) throw() : GraphEdge< SESVertex,SESEdge,SESFace > (vertex0,vertex1,face0,face1,index), circle_(circle), rsedge_(rsedge), type_(type) { } SESEdge::~SESEdge() throw() { } void SESEdge::set(const SESEdge& sesedge, bool deep) throw() { if (this != &sesedge) { GraphEdge< SESVertex,SESEdge,SESFace >::set(sesedge,deep); if (deep) { rsedge_ = sesedge.rsedge_; } else { rsedge_ = NULL; } circle_.set(sesedge.circle_); type_ = sesedge.type_; } } SESEdge& SESEdge::operator = (const SESEdge& sesedge) throw() { if (this != &sesedge) { GraphEdge< SESVertex,SESEdge,SESFace >::operator = (sesedge); rsedge_ = sesedge.rsedge_; circle_.set(sesedge.circle_); type_ = sesedge.type_; } return *this; } void SESEdge::set (SESVertex* vertex0, SESVertex* vertex1, SESFace* face0, SESFace* face1, const TCircle3& circle, RSEdge* rsedge, Type type, Index index) throw() { GraphEdge< SESVertex,SESEdge,SESFace >::set (vertex0,vertex1,face0,face1,index); circle_.set(circle); rsedge_ = rsedge; type_ = type; } void SESEdge::setCircle(const TCircle3& circle) throw() { circle_ = circle; } TCircle3 SESEdge::getCircle() const throw() { return circle_; } void SESEdge::setRSEdge(RSEdge* rsedge) throw() { rsedge_ = rsedge; } RSEdge* SESEdge::getRSEdge() const throw() { return rsedge_; } void SESEdge::setType(SESEdge::Type type) throw() { type_ = type; } SESEdge::Type SESEdge::getType() const throw() { return type_; } bool SESEdge::operator == (const SESEdge& sesedge) const throw() { return (((vertex_[0] == sesedge.vertex_[0]) && (vertex_[1] == sesedge.vertex_[1]) ) || ((vertex_[1] == sesedge.vertex_[0]) && (vertex_[0] == sesedge.vertex_[1]) ) ); } bool SESEdge::operator != (const SESEdge& sesedge) const throw() { return (((vertex_[0] != sesedge.vertex_[0]) || (vertex_[1] != sesedge.vertex_[1]) ) && ((vertex_[1] != sesedge.vertex_[0]) || (vertex_[0] != sesedge.vertex_[1]) ) ); } bool SESEdge::operator *= (const SESEdge&) const throw() { return true; } bool SESEdge::isFree() const throw() { if (rsedge_ == NULL) { return false; } else { return rsedge_->isFree(); } } std::ostream& operator << (std::ostream& s, const SESEdge& sesedge) { return (s << "SESEDGE" << sesedge.getIndex() << "([" << ((sesedge.getVertex(0) == NULL) ? -2 : sesedge.getVertex(0)->getIndex()) << ' ' << ((sesedge.getVertex(1) == NULL) ? -2 : sesedge.getVertex(1)->getIndex()) << "] [" << ((sesedge.getFace(0) == NULL) ? -2 : sesedge.getFace(0)->getIndex()) << ' ' << ((sesedge.getFace(1) == NULL) ? -2 : sesedge.getFace(1)->getIndex()) << "] " << sesedge.getCircle() << ' ' << ((sesedge.getRSEdge() == NULL) ? -2 : sesedge.getRSEdge()->getIndex()) << ((sesedge.getType() == SESEdge::TYPE_CONCAVE) ? " concave)" : ((sesedge.getType() == SESEdge::TYPE_CONVEX) ? " convex)" : " singular)")) ); } } // namespace BALL ugene-1.9.8/src/plugins_3rdparty/ball/src/source/STRUCTURE/SESFace.cpp0000644000175000017500000002062611651544326023745 0ustar ilyailya// -*- Mode: C++; tab-width: 2; -*- // vi: set ts=2: // // $Id: SESFace.C,v 1.4.32.1 2007-04-03 13:29:39 bertsch Exp $ #include #include #include #include #include #include namespace BALL { SESFace::SESFace() throw() : GraphFace< SESVertex,SESEdge,SESFace >(), type_(SESFace::TYPE_SPHERIC), rsvertex_(NULL), rsedge_(NULL), rsface_(NULL) { } SESFace::SESFace(const SESFace& sesface, bool deep) throw() : GraphFace< SESVertex,SESEdge,SESFace >(sesface,deep), type_(sesface.type_), rsvertex_(NULL), rsedge_(NULL), rsface_(NULL) { if (deep) { rsvertex_ = sesface.rsvertex_; rsedge_ = sesface.rsedge_; rsface_ = sesface.rsface_; } } SESFace::SESFace(Type type, RSVertex* rsvertex, RSEdge* rsedge, RSFace* rsface) throw() : GraphFace< SESVertex,SESEdge,SESFace >(), type_(type), rsvertex_(rsvertex), rsedge_(rsedge), rsface_(rsface) { } SESFace::~SESFace() throw() { } void SESFace::set(const SESFace& sesface, bool deep) throw() { if (this != &sesface) { GraphFace< SESVertex,SESEdge,SESFace >::set(sesface,deep); if (deep) { rsvertex_ = sesface.rsvertex_; rsedge_ = sesface.rsedge_; rsface_ = sesface.rsface_; } type_ = sesface.type_; } } SESFace& SESFace::operator = (const SESFace& sesface) throw() { if (this != &sesface) { GraphFace< SESVertex,SESEdge,SESFace >::operator = (sesface); rsvertex_ = sesface.rsvertex_; rsedge_ = sesface.rsedge_; rsface_ = sesface.rsface_; type_ = sesface.type_; } return *this; } void SESFace::setType(SESFace::Type type) throw() { type_ = type; } SESFace::Type SESFace::getType() const throw() { return type_; } void SESFace::setRSVertex(RSVertex* rsvertex) throw() { rsvertex_ = rsvertex; } RSVertex* SESFace::getRSVertex() const throw() { return rsvertex_; } void SESFace::setRSEdge(RSEdge* rsedge) throw() { rsedge_ = rsedge; } RSEdge* SESFace::getRSEdge() const throw() { return rsedge_; } void SESFace::setRSFace(RSFace* rsface) throw() { rsface_ = rsface; } RSFace* SESFace::getRSFace() const throw() { return rsface_; } void SESFace::normalize(bool singular) throw() { if ((type_ != SESFace::TYPE_TORIC) && (type_ != SESFace::TYPE_TORIC_SINGULAR)) { return; } if (rsedge_->isFree()) { return; } if (singular == false) { normalizeNonSingularToricFace_(); } else { normalizeSingularToricFace_(); } } void SESFace::normalizeNonSingularToricFace_() throw() { HashSet points; std::list::iterator v; for (v = vertex_.begin(); v != vertex_.end(); v++) { points.insert(*v); } SESEdge* edge0(0); SESEdge* edge1(0); SESEdge* edge2(0); SESEdge* edge3(0); SESVertex* p0(0); SESVertex* p1(0); SESVertex* p2(0); SESVertex* p3(0); std::list::iterator e = edge_.begin(); while ((*e)->type_ != SESEdge::TYPE_CONCAVE) { e++; } edge0 = *e; // edge0 = first concave edge e++; while ((*e)->type_ != SESEdge::TYPE_CONCAVE) { e++; } edge2 = *e; // edge2 = second concave edge p0 = edge0->vertex_[0]; p1 = edge0->vertex_[1]; Size number_of_vertices = points.size(); if (number_of_vertices == 4) { if (getEdge(p1,edge2->vertex_[0],edge1)) { p2 = edge2->vertex_[0]; p3 = edge2->vertex_[1]; } else // p0 ____e3____ p3 { // | | getEdge(p1,edge2->vertex_[1],edge1); // | | p2 = edge2->vertex_[1]; // e0| |e2 p3 = edge2->vertex_[0]; // | | } // |________| getEdge(p0,p3,edge3); // p1 e1 p2 } else { if ((p0 == edge2->vertex_[0]) || (p1 == edge2->vertex_[1])) { p2 = edge2->vertex_[1]; p3 = edge2->vertex_[0]; } else { p2 = edge2->vertex_[0]; p3 = edge2->vertex_[1]; } getEdge(p1,p2,edge1); getEdge(p0,p3,edge3); } edge_.clear(); edge_.push_back(edge0); edge_.push_back(edge1); edge_.push_back(edge2); edge_.push_back(edge3); vertex_.clear(); vertex_.push_back(p0); vertex_.push_back(p1); vertex_.push_back(p2); vertex_.push_back(p3); } void SESFace::normalizeSingularToricFace_() throw() { SESEdge* edge0(0); SESEdge* edge1(0); SESEdge* edge2(0); SESEdge* edge3(0); SESEdge* edge4(0); SESEdge* edge5(0); SESVertex* p0(0); SESVertex* p1(0); SESVertex* p2(0); SESVertex* p3(0); SESVertex* p4(0); SESVertex* p5(0); findTriangle_(true,edge0,edge1,edge2,p0,p1,p2); findTriangle_(false,edge3,edge4,edge5,p3,p4,p5); if (edge1->circle_ != edge4->circle_) { SESEdge* temp = edge5; edge5 = edge4; edge4 = temp; SESVertex* tmp = p5; p5 = p3; p3 = tmp; } edge_.clear(); edge_.push_back(edge0); edge_.push_back(edge1); edge_.push_back(edge2); edge_.push_back(edge3); edge_.push_back(edge4); edge_.push_back(edge5); vertex_.clear(); vertex_.push_back(p0); vertex_.push_back(p1); vertex_.push_back(p2); vertex_.push_back(p3); vertex_.push_back(p4); vertex_.push_back(p5); } void SESFace::findTriangle_ (bool first, SESEdge*& edge0, SESEdge*& edge1, SESEdge*& edge2, SESVertex*& vertex0, SESVertex*& vertex1, SESVertex*& vertex2) throw() { std::list::iterator e; if (first) { // find first convex edge e = edge_.begin(); while ((*e)->type_ != SESEdge::TYPE_CONVEX) { e++; } } else { // find second (last) convex edge e = edge_.end(); do { e--; } while ((*e)->type_ != SESEdge::TYPE_CONVEX); } edge0 = *e; vertex0 = edge0->vertex_[0]; vertex2 = edge0->vertex_[1]; e = edge_.begin(); while (e != edge_.end()) { if (((*e)->vertex_[0] == vertex0) && ((*e) != edge0)) { edge1 = *e; vertex1 = edge1->vertex_[1]; } else { if (((*e)->vertex_[1] == vertex0) && ((*e) != edge0)) { edge1 = *e; vertex1 = edge1->vertex_[0]; } } e++; } while (e != edge_.begin()) { e--; if ((((*e)->vertex_[0] == vertex1) && ((*e)->vertex_[1] == vertex2)) || (((*e)->vertex_[1] == vertex1) && ((*e)->vertex_[0] == vertex2)) ) { edge2 = *e; } } } bool SESFace::operator == (const SESFace&) const throw() { return true; } bool SESFace::operator != (const SESFace&) const throw() { return false; } bool SESFace::operator *= (const SESFace&) const throw() { return true; } bool SESFace::isNeighbouredTo(SESFace* face) const throw() { std::list::const_iterator e; for (e = edge_.begin(); e != edge_.end(); e++) { if ((*e)->face_[0] == face) { return true; } if ((*e)->face_[1] == face) { return true; } } return false; } bool SESFace::isFree() const throw() { if (type_ != TYPE_TORIC) { return false; } return rsedge_->isFree(); } bool SESFace::hasSingularEdges() const throw() { SESFace::ConstEdgeIterator e; for (e = beginEdge(); e != endEdge(); e++) { if (*e != NULL) { if ((*e)->type_ == SESEdge::TYPE_SINGULAR) { return true; } } } return false; } std::ostream& operator << (std::ostream& s, const SESFace& sesface) { s << "SESFACE" << sesface.getIndex() << "(" << (sesface.getType() == SESFace::TYPE_CONTACT ? "contact " : (sesface.getType() == SESFace::TYPE_SPHERIC ? "spheric " : (sesface.getType() == SESFace::TYPE_TORIC ? "toric " : "toric singular "))); if (sesface.getRSVertex() == NULL) { s << "(nil) "; } else { s << "(" << sesface.getRSVertex()->getIndex() << ") "; } if (sesface.getRSEdge() == NULL) { s << "(nil) "; } else { s << "(" << sesface.getRSEdge()->getIndex() << ") "; } if (sesface.getRSFace() == NULL) { s << "(nil) ["; } else { s << "(" << sesface.getRSFace()->getIndex() << ") ["; } SESFace::ConstVertexIterator v = sesface.beginVertex(); while (v != sesface.endVertex()) { s << (*v)->getIndex() << ' '; v++; } s << "] ["; SESFace::ConstEdgeIterator e = sesface.beginEdge(); while (e != sesface.endEdge()) { s << (*e)->getIndex() << ' '; e++; } s << "])"; return s; } } // namespace BALL ugene-1.9.8/src/plugins_3rdparty/ball/src/source/STRUCTURE/trianglePoint.cpp0000644000175000017500000000466611651544326025361 0ustar ilyailya// -*- Mode: C++; tab-width: 2; -*- // vi: set ts=2: // // $Id: trianglePoint.C,v 1.3 2002-12-17 14:13:21 anker Exp $ #include #include #include namespace BALL { TrianglePoint::TrianglePoint() throw() : GraphVertex< TrianglePoint,TriangleEdge,Triangle >(), point_(), normal_() { } TrianglePoint::TrianglePoint(const TrianglePoint& point, bool deep) throw() : GraphVertex< TrianglePoint,TriangleEdge,Triangle > (point,deep), point_(point.point_), normal_(point.normal_) { } TrianglePoint::~TrianglePoint() throw() { } void TrianglePoint::set(const TrianglePoint& point, bool deep) throw() { if (this != &point) { GraphVertex< TrianglePoint,TriangleEdge,Triangle >::set (point,deep); point_.set(point.point_); normal_.set(point.normal_); } } TrianglePoint& TrianglePoint:: operator = (const TrianglePoint& point) throw() { if (this != &point) { GraphVertex< TrianglePoint,TriangleEdge,Triangle >::operator= (point); point_.set(point.point_); normal_.set(point.normal_); } return *this; } TVector3 TrianglePoint::getPoint() const throw() { return point_; } void TrianglePoint::setPoint(const TVector3& point) throw() { point_ = point; } TVector3 TrianglePoint::getNormal() const throw() { return normal_; } void TrianglePoint::setNormal(const TVector3& normal) throw(Exception::DivisionByZero) { normal_ = normal; normal_.normalize(); } bool TrianglePoint::operator == (const TrianglePoint& point) const throw() { return (point_ == point.point_); } bool TrianglePoint::operator != (const TrianglePoint& point) const throw() { return (point_ != point.point_); } bool TrianglePoint::operator *= (const TrianglePoint& point) const throw() { return (point_ == point.point_); } std::ostream& operator << (std::ostream& s, const TrianglePoint& point) { s << "POINT"; s << point.getIndex(); s << "( " << point.getPoint() << " " << point.getNormal() << " {"; TrianglePoint::ConstEdgeIterator e; for (e = point.beginEdge(); e != point.endEdge(); e++) { s << (*e)->getIndex() << " "; } s << "} ["; TrianglePoint::ConstFaceIterator f; for (f = point.beginFace(); f != point.endFace(); f++) { s << (*f)->getIndex() << " "; } s << "] )"; return s; } } // namespace BALL ugene-1.9.8/src/plugins_3rdparty/ball/src/source/STRUCTURE/SASVertex.cpp0000644000175000017500000000433611651544326024360 0ustar ilyailya// -*- Mode: C++; tab-width: 2; -*- // vi: set ts=2: // // $Id: SASVertex.C,v 1.1 2002-12-17 17:14:22 anker Exp $ #include #include #include #include namespace BALL { SASVertex::SASVertex() throw() : GraphVertex< SASVertex,SASEdge,SASFace >(), point_() { } SASVertex::SASVertex(const SASVertex& sasvertex, bool deep) throw() : GraphVertex< SASVertex,SASEdge,SASFace >(sasvertex,deep), point_(sasvertex.point_) { } SASVertex::SASVertex(const TVector3& point, Index index) throw() : GraphVertex< SASVertex,SASEdge,SASFace >(), point_(point) { index_ = index; } SASVertex::~SASVertex() throw() { } void SASVertex::set(const SASVertex& sasvertex, bool deep) throw() { if (this != &sasvertex) { GraphVertex< SASVertex,SASEdge,SASFace >::set(sasvertex,deep); point_ = sasvertex.point_; } } SASVertex& SASVertex::operator = (const SASVertex& sasvertex) throw() { if (this != &sasvertex) { GraphVertex< SASVertex,SASEdge,SASFace >::operator = (sasvertex); point_ = sasvertex.point_; } return *this; } void SASVertex::set(const TVector3 point, Index index) throw() { point_ = point; index_ = index; } void SASVertex::setPoint(const TVector3& point) throw() { point_ = point; } TVector3 SASVertex::getPoint() const throw() { return point_; } bool SASVertex::operator == (const SASVertex&) const throw() { return true; } bool SASVertex::operator != (const SASVertex&) const throw() { return false; } bool SASVertex::operator *= (const SASVertex&) const throw() { return true; } std::ostream& operator << (std::ostream& s, const SASVertex& sasvertex) { s << "SASVERTEX" << sasvertex.getIndex() << "(" << sasvertex.getPoint() << " ["; SASVertex::ConstEdgeIterator e; for (e = sasvertex.beginEdge(); e != sasvertex.endEdge(); e++) { s << (*e)->getIndex() << ' '; } s << "] ["; SASVertex::ConstFaceIterator f; for (f = sasvertex.beginFace(); f != sasvertex.endFace(); f++) { s << (*f)->getIndex() << ' '; } s << "] )"; return s; } } // namespace BALL ugene-1.9.8/src/plugins_3rdparty/ball/src/source/STRUCTURE/graphEdge.cpp0000644000175000017500000000014711651544326024416 0ustar ilyailya// -*- Mode: C++; tab-width: 2; -*- // vi: set ts=2: // // $Id: #include ugene-1.9.8/src/plugins_3rdparty/ball/src/source/STRUCTURE/reducedSurface.cpp0000644000175000017500000014620311651544326025460 0ustar ilyailya// -*- Mode: C++; tab-width: 2; -*- // vi: set ts=2: // // $Id: reducedSurface.C,v 1.9.28.1 2007-03-22 11:48:19 oliver Exp $ // #include #include #include namespace BALL { ReducedSurface::ReducedSurface() throw() : number_of_atoms_(0), atom_(), probe_radius_(0.0), number_of_vertices_(0), vertices_(), number_of_edges_(0), edges_(), number_of_faces_(0), faces_(), r_max_(0), bounding_box_() { } ReducedSurface::ReducedSurface (const ReducedSurface& reduced_surface, bool) throw() : number_of_atoms_(0), atom_(), probe_radius_(0.0), number_of_vertices_(0), vertices_(), number_of_edges_(0), edges_(), number_of_faces_(0), faces_(), r_max_(0), bounding_box_() { copy(reduced_surface); } ReducedSurface::ReducedSurface (const std::vector< TSphere3 >& spheres, const double& probe_radius) throw() : number_of_atoms_(spheres.size()), atom_(spheres), probe_radius_(probe_radius), number_of_vertices_(0), vertices_(), number_of_edges_(0), edges_(), number_of_faces_(0), faces_(), r_max_(0), bounding_box_() { } ReducedSurface::~ReducedSurface() throw() { clear(); } void ReducedSurface::set(const ReducedSurface& reduced_surface) throw() { copy(reduced_surface); } void ReducedSurface::operator=(const ReducedSurface& reduced_surface) throw() { copy(reduced_surface); } void ReducedSurface::clear() throw() { for (Position i = 0; i < number_of_vertices_; i++) { delete vertices_[i]; } for (Position i = 0; i < number_of_edges_; i++) { delete edges_[i]; } for (Position i = 0; i < number_of_faces_; i++) { delete faces_[i]; } vertices_.clear(); edges_.clear(); faces_.clear(); number_of_vertices_ = 0; number_of_edges_ = 0; number_of_faces_ = 0; } void ReducedSurface::clean() throw() { while ((number_of_vertices_ > 0) && (vertices_[number_of_vertices_-1] == NULL)) { vertices_.pop_back(); number_of_vertices_--; } for (Position i = 0; i < number_of_vertices_; i++) { if (vertices_[i] == NULL) { vertices_[i] = vertices_[number_of_vertices_-1]; vertices_[i]->index_ = i; vertices_.pop_back(); number_of_vertices_--; while (vertices_[number_of_vertices_-1] == NULL) { vertices_.pop_back(); number_of_vertices_--; } } } while ((number_of_edges_ > 0) && (edges_[number_of_edges_-1] == NULL)) { edges_.pop_back(); number_of_edges_--; } for (Position i = 0; i < number_of_edges_; i++) { if (edges_[i] == NULL) { edges_[i] = edges_[number_of_edges_-1]; edges_[i]->index_ = i; edges_.pop_back(); number_of_edges_--; while (edges_[number_of_edges_-1] == NULL) { edges_.pop_back(); number_of_edges_--; } } } while ((number_of_faces_ > 0) && (faces_[number_of_faces_-1] == NULL)) { faces_.pop_back(); number_of_faces_--; } for (Position i = 0; i < number_of_faces_; i++) { if (faces_[i] == NULL) { faces_[i] = faces_[number_of_faces_-1]; faces_[i]->index_ = i; faces_.pop_back(); number_of_faces_--; while (faces_[number_of_faces_-1] == NULL) { faces_.pop_back(); number_of_faces_--; } } } } Size ReducedSurface::numberOfAtoms() const throw() { return number_of_atoms_; } Size ReducedSurface::numberOfVertices() const throw() { return number_of_vertices_; } Size ReducedSurface::numberOfEdges() const throw() { return number_of_edges_; } Size ReducedSurface::numberOfFaces() const throw() { return number_of_faces_; } double ReducedSurface::getProbeRadius() const throw() { return probe_radius_; } TSphere3 ReducedSurface::getSphere(Position i) const throw(Exception::IndexOverflow) { if (i < number_of_atoms_) { return atom_[i]; } else { throw Exception::IndexOverflow(__FILE__, __LINE__, i,number_of_atoms_-1); } } RSVertex* ReducedSurface::getVertex(Position i) const throw(Exception::IndexOverflow) { if (i < number_of_vertices_) { return vertices_[i]; } else { throw Exception::IndexOverflow(__FILE__, __LINE__, i,number_of_vertices_-1); } } RSEdge* ReducedSurface::getEdge(Position i) const throw(Exception::IndexOverflow) { if (i < number_of_edges_) { return edges_[i]; } else { throw Exception::IndexOverflow(__FILE__, __LINE__, i,number_of_edges_-1); } } RSFace* ReducedSurface::getFace(Position i) const throw(Exception::IndexOverflow) { if (i < number_of_faces_) { return faces_[i]; } else { throw Exception::IndexOverflow(__FILE__, __LINE__, i,number_of_faces_-1); } } void ReducedSurface::insert(RSVertex* rsvertex) throw() { rsvertex->index_ = number_of_vertices_; vertices_.push_back(rsvertex); number_of_vertices_++; } void ReducedSurface::insert(RSEdge* rsedge) throw() { rsedge->index_ = number_of_edges_; edges_.push_back(rsedge); number_of_edges_++; } void ReducedSurface::insert(RSFace* rsface) throw() { rsface->index_ = number_of_faces_; faces_.push_back(rsface); number_of_faces_++; } double ReducedSurface::getMaximalRadius() const throw() { return r_max_; } TSimpleBox3 ReducedSurface::getBoundingBox() const throw() { return bounding_box_; } void ReducedSurface::deleteSimilarFaces (RSFace* face1, RSFace* face2) throw() { if ((*face1) *= (*face2)) { // find the similar edges std::vector rsedge1(3); std::vector rsedge2(3); //RSEdge* rsedge1[3]; //RSEdge* rsedge2[3]; findSimilarEdges(face1,face2,rsedge1,rsedge2); // find the similar vertices std::vector rsvertex1(3); std::vector rsvertex2(3); //RSVertex* rsvertex1[3]; //RSVertex* rsvertex2[3]; findSimilarVertices(face1,face2,rsvertex1,rsvertex2); // join the similar vertices and delete the faces in their face lists for (Position i = 0; i < 3; i++) { joinVertices(face1,face2,rsvertex1[i],rsvertex2[i]); } // correct the edges for (Position i = 0; i < 3; i++) { correctEdges(face1,face2,rsedge1[i],rsedge2[i]); } faces_[face1->index_] = NULL; faces_[face2->index_] = NULL; delete face1; delete face2; } } void ReducedSurface::findSimilarEdges (RSFace* face1, RSFace* face2, std::vector& rsedge1, std::vector& rsedge2) //RSEdge*& rsedge1[3], //RSEdge*& rsedge2[3]) throw() { rsedge1[0] = face1->edge_[0]; rsedge1[1] = face1->edge_[1]; rsedge1[2] = face1->edge_[2]; RSEdge* edge; for (Position j = 0; j < 3; j++) { for (Position i = 0; i < 3; i++) { edge = face2->getEdge(i); if (*edge *= *rsedge1[j]) { rsedge2[j] = edge; } } } } void ReducedSurface::findSimilarVertices (RSFace* face1, RSFace* face2, std::vector& rsvertex1, std::vector& rsvertex2) //RSVertex*& rsvertex1[3], //RSVertex*& rsvertex2[3]) throw() { rsvertex1[0] = face1->vertex_[0]; rsvertex1[1] = face1->vertex_[1]; rsvertex1[2] = face1->vertex_[2]; RSVertex* vertex; for (Position j = 0; j < 3; j++) { for (Position i = 0; i < 3; i++) { vertex = face2->getVertex(i); if (vertex->atom_ == rsvertex1[j]->atom_) { rsvertex2[j] = vertex; } } } } void ReducedSurface::joinVertices (RSFace* face1, RSFace* face2, RSVertex* vertex1, RSVertex* vertex2) throw() { if (vertex1 != vertex2) { vertex1->join(*vertex2); vertex2->substitute(vertex1); vertices_[vertex2->index_] = NULL; delete vertex2; } vertex1->faces_.erase(face1); vertex1->faces_.erase(face2); } void ReducedSurface::correctEdges (RSFace* face1, RSFace* face2, RSEdge* edge1, RSEdge* edge2) throw() { if (edge1 == edge2) { if (edge1->singular_) { edge1->vertex_[0]->edges_.erase(edge1); edge1->vertex_[1]->edges_.erase(edge1); edges_[edge1->index_] = NULL; delete edge1; } else { edge1->face_[0] = NULL; edge1->face_[1] = NULL; edge1->angle_.value = 2*Constants::PI; } } else { RSFace* neighbour2 = edge2->other(face2); if (edge1->face_[0] == face1) { edge1->face_[0] = neighbour2; } else { edge1->face_[1] = neighbour2; } for (Position j = 0; j < 3; j++) { if (neighbour2->getEdge(j) == edge2) { neighbour2->setEdge(j,edge1); } } edge2->vertex_[0]->edges_.erase(edge2); edge2->vertex_[1]->edges_.erase(edge2); edges_[edge2->index_] = NULL; delete edge2; // recomputation of rsedge1[i]->angle_ RSFace* neighbour1 = edge1->face_[0]; neighbour2 = edge1->face_[1]; getAngle(neighbour1,neighbour2,edge1->vertex_[0], edge1->vertex_[1],edge1->angle_,false); } } bool ReducedSurface::getAngle (RSFace* face1, RSFace* face2, RSVertex* vertex1, RSVertex* vertex2, TAngle& angle, bool check) const throw() { if (check) { if (!(face1->has(vertex1) && face1->has(vertex2) && face2->has(vertex1) && face2->has(vertex2))) { return false; } } RSVertex* vertex3(face1->third(vertex1,vertex2)); TSphere3 atom1(atom_[vertex1->atom_]); TSphere3 atom2(atom_[vertex2->atom_]); TSphere3 atom3(atom_[vertex3->atom_]); TVector3 axis(atom1.p - atom2.p); TVector3 test(axis % face1->normal_); if (Maths::isLess(test*(atom1.p - atom3.p), 0.0)) { axis.negate(); } atom1.radius += probe_radius_; atom2.radius += probe_radius_; TCircle3 circle; GetIntersection(atom1, atom2, circle); TVector3 v1 = face1->center_ - circle.p; TVector3 v2 = face2->center_ - circle.p; angle = getOrientedAngle(v1, v2, axis); return true; } void ReducedSurface::copy(const ReducedSurface& reduced_surface) throw() { if (canBeCopied(reduced_surface)) { number_of_atoms_ = reduced_surface.number_of_atoms_; atom_ = reduced_surface.atom_; probe_radius_ = reduced_surface.probe_radius_; number_of_vertices_ = reduced_surface.number_of_vertices_; number_of_edges_ = reduced_surface.number_of_edges_; number_of_faces_ = reduced_surface.number_of_faces_; RSVertex* vertex; RSEdge* edge; RSFace* face; for (Position i = 0; i < number_of_vertices_; i++) { vertex = new RSVertex(*reduced_surface.vertices_[i],false); vertices_.push_back(vertex); } for (Position i = 0; i < number_of_edges_; i++) { edge = new RSEdge(*reduced_surface.edges_[i],false); edges_.push_back(edge); } for (Position i = 0; i < number_of_faces_; i++) { face = new RSFace(*reduced_surface.faces_[i],false); faces_.push_back(face); } HashSet::ConstIterator e; HashSet::ConstIterator f; for (Position i = 0; i < number_of_vertices_; i++) { for (e = reduced_surface.vertices_[i]->edges_.begin(); e != reduced_surface.vertices_[i]->edges_.end(); e++) { vertices_[i]->edges_.insert(edges_[(*e)->index_]); } for (f = reduced_surface.vertices_[i]->faces_.begin(); f != reduced_surface.vertices_[i]->faces_.end(); f++) { vertices_[i]->faces_.insert(faces_[(*f)->index_]); } } for (Position i = 0; i < number_of_edges_; i++) { edge = reduced_surface.edges_[i]; edges_[i]->vertex_[0] = vertices_[edge->vertex_[0]->index_]; edges_[i]->vertex_[1] = vertices_[edge->vertex_[1]->index_]; edges_[i]->face_[0] = faces_[edge->face_[0]->index_]; edges_[i]->face_[1] = faces_[edge->face_[1]->index_]; } for (Position i = 0; i < number_of_faces_; i++) { face = reduced_surface.faces_[i]; faces_[i]->vertex_[0] = vertices_[face->vertex_[0]->index_]; faces_[i]->vertex_[1] = vertices_[face->vertex_[1]->index_]; faces_[i]->vertex_[2] = vertices_[face->vertex_[2]->index_]; faces_[i]->edge_[0] = edges_[face->edge_[0]->index_]; faces_[i]->edge_[1] = edges_[face->edge_[1]->index_]; faces_[i]->edge_[2] = edges_[face->edge_[2]->index_]; } } } bool ReducedSurface::canBeCopied (const ReducedSurface& reduced_surface) throw() { for (Position i = 0; i < number_of_vertices_; i++) { if (reduced_surface.vertices_[i] == NULL) { return false; } if (reduced_surface.vertices_[i]->index_ < 0) { return false; } } for (Position i = 0; i < number_of_edges_; i++) { if (reduced_surface.edges_[i] == NULL) { return false; } if (reduced_surface.edges_[i]->index_ < 0) { return false; } } for (Position i = 0; i < number_of_faces_; i++) { if (reduced_surface.faces_[i] == NULL) { return false; } if (reduced_surface.faces_[i]->index_ < 0) { return false; } } return true; } void ReducedSurface::compute() throw(Exception::GeneralException, Exception::DivisionByZero, Exception::IndexOverflow) { RSComputer rsc(this); rsc.run(); } std::ostream& operator << (std::ostream& s, const ReducedSurface& rs) { s << "Spheres:\n"; for (Position i = 0; i < rs.numberOfAtoms(); i++) { s << " " << rs.getSphere(i) << "\n"; } s << "RSVertices:\n"; for (Position i = 0; i < rs.numberOfVertices(); i++) { if (rs.getVertex(i) == NULL) { s << " --\n"; } else { s << " " << rs.getVertex(i) << " " << *(rs.getVertex(i)) << "\n"; } } s << "RSEdges:\n"; for (Position i = 0; i < rs.numberOfEdges(); i++) { if (rs.getEdge(i) == NULL) { s << " --\n"; } else { s << " " << rs.getEdge(i) << " " << *(rs.getEdge(i)) << "\n"; } } s << "RSFaces:\n"; for (Position i = 0; i < rs.numberOfFaces(); i++) { if (rs.getFace(i) == NULL) { s << " --\n"; } else { s << " " << rs.getFace(i) << " " << *(rs.getFace(i)) << "\n"; } } return s; } //////////////////////////////////// RSComputer::RSComputer() throw() : rs_(NULL), neighbours_(), atom_status_(), neighbours_of_two_(), probe_positions_(), new_vertices_(), new_faces_(), vertices_() { } RSComputer::RSComputer(ReducedSurface* rs) throw() : rs_(rs), neighbours_(rs->number_of_atoms_), atom_status_(rs->number_of_atoms_,STATUS_UNKNOWN), neighbours_of_two_(), probe_positions_(), new_vertices_(), new_faces_(), vertices_(rs->number_of_atoms_) { } RSComputer::~RSComputer() throw() { // delete probe_positions HashMap< Position, HashMap< Position, HashMap< Position,ProbePosition* > > >::Iterator pp1; HashMap< Position,HashMap< Position,ProbePosition* > >::Iterator pp2; HashMap< Position,ProbePosition* >::Iterator pp3; for (pp1 = probe_positions_.begin(); pp1 != probe_positions_.end(); pp1++) { for (pp2 = pp1->second.begin(); pp2 != pp1->second.end(); pp2++) { for (pp3 = pp2->second.begin(); pp3 != pp2->second.end(); pp3++) { delete pp3->second; } } } } void RSComputer::run() throw(Exception::GeneralException, Exception::DivisionByZero, Exception::IndexOverflow) { double epsilon = Constants::EPSILON; Constants::EPSILON = 1e-4; // find for each atom its neighbours preProcessing(); // start the computation Position start = 1; while (start != 0) { start = getStartPosition(); switch (start) { case 2 : extendComponent(); break; case 3 : getRSComponent(); break; default : break; } } rs_->clean(); Constants::EPSILON = epsilon; } void RSComputer::getRSComponent() throw(Exception::GeneralException, Exception::DivisionByZero, Exception::IndexOverflow) { Position i = 0; while (i < rs_->number_of_faces_) { if (rs_->faces_[i] != NULL) { if (treatFace(rs_->faces_[i]) == false) { i = 0; } else { i++; } } else { i++; } } extendComponent(); //while (new_faces_.size() > 0) //{ // treatFace(*new_faces_.begin()); //} //extendComponent(); } bool RSComputer::treatFace(RSFace* face) throw(Exception::GeneralException, Exception::DivisionByZero, Exception::IndexOverflow) { if (face->edge_[0]->face_[1] == NULL) { if (!treatEdge(face->edge_[0])) { return false; } } if (face->edge_[1]->face_[1] == NULL) { if (!treatEdge(face->edge_[1])) { return false; } } if (face->edge_[2]->face_[1] == NULL) { if (!treatEdge(face->edge_[2])) { return false; } } new_faces_.erase(face); return true; } bool RSComputer::treatEdge(RSEdge* edge) throw(Exception::GeneralException, Exception::DivisionByZero, Exception::IndexOverflow) { // This function rolls the probe sphere over a RSEdge. // From all atoms that can be touced by the probe sphere when it touches // the two atoms of the edge is this one selected for which the rotation // angle is the smallest. A new face is found. // If this face already exists the edge exists twice, too. These two // edges and their vertices are joined. // If the face does not exist yet, it will be created. A new vertex and // two new edges will be created, too. // In both cases the treated edge will be updated. It has not to be // considerd again. // find third atom TAngle phi; TSphere3 probe; RSFace* start_face(edge->face_[0]); // the edge already knows the RSVertex* vertex1(edge->vertex_[0]); // starting face and their RSVertex* vertex2(edge->vertex_[1]); // two vertices RSVertex* vertex3(NULL); Index atom1(vertex1->atom_); Index atom2(vertex2->atom_); Index atom3; try { atom3 = thirdAtom(vertex1,vertex2,start_face,probe,phi); } catch (Exception::GeneralException e) { String message = e.getMessage(); String test_message = "PROBE SPHERE TOUCHES FOUR ATOMS"; if (message == test_message) { return false; } else { throw; } } TSphere3 sphere1(rs_->atom_[atom1]); TSphere3 sphere2(rs_->atom_[atom2]); TSphere3 sphere3(rs_->atom_[atom3]); // build a new face and two new edges vertex3 = new RSVertex(atom3); RSEdge* edge1; RSEdge* edge2; RSFace* new_face // provisorial new face = new RSFace(vertex1,vertex2,vertex3,NULL,NULL,NULL, probe.p,getFaceNormal(sphere1,sphere2,sphere3,probe), false,-1); RSFace* test = faceExists(new_face,vertices_[vertex1->atom_]); if (test == NULL) { // built face doesn't exist yet // The new vertex has to be created since we don't know at this time // whether it is a new vertex or not. // Attention: one atom can build more than one vertex! insert(vertex3); edge1 = new RSEdge; edge1->vertex_[0] = vertex2; edge1->vertex_[1] = vertex3; edge1->face_[0] = new_face; edge2 = new RSEdge; edge2->vertex_[0] = vertex3; edge2->vertex_[1] = vertex1; edge2->face_[0] = new_face; new_face->edge_[0] = edge; new_face->edge_[1] = edge1; new_face->edge_[2] = edge2; TPlane3 plane(sphere1.p,sphere2.p,sphere3.p); new_face->singular_ = Maths::isLess(GetDistance(probe.p,plane), rs_->probe_radius_); insert(new_face); } else { // built face exitsts already // the corresponding edge in the existing face has to be found RSEdge* test_edge; Index i = test->getSimilarEdge(edge,test_edge); // Now the corresponding vertices of the corresponding edges have to be // joined and one of them has to be deleted (if they are not equal). This // is neccessary since creating a new face always creates a new vertex. RSVertex* test_vertex1 = test_edge->vertex_[0]; RSVertex* test_vertex2 = test_edge->vertex_[1]; if (test_vertex1->atom_ == vertex2->atom_) { RSVertex* tmp = test_vertex1; test_vertex1 = test_vertex2; test_vertex2 = tmp; } // now we know which vertices are corresponding if (*vertex1 != *test_vertex1) { // the vertices only have to be joined if they are not equal vertex1->join(*test_vertex1); test_vertex1->substitute(vertex1); rs_->vertices_[test_vertex1->index_] = NULL; new_vertices_.erase(test_vertex1); vertices_[test_vertex1->atom_].remove(test_vertex1); delete test_vertex1; } if (*vertex2 != *test_vertex2) { // the vertices only have to be joined if they are not equal vertex2->join(*test_vertex2); test_vertex2->substitute(vertex2); rs_->vertices_[test_vertex2->index_] = NULL; new_vertices_.erase(test_vertex2); vertices_[test_vertex2->atom_].remove(test_vertex2); delete test_vertex2; } // The vertices should have only one of the two corresponding edges. // The other will be deleted later. vertex1->edges_.erase(test_edge); vertex2->edges_.erase(test_edge); // The face should have only one of the two corresponding edges, too. test->setEdge(i,edge); // Now can we delete the build face and vertex and the double edge. delete new_face; if (test_edge->index_ != -1) // this can happens after a correct step { rs_->edges_[test_edge->index_] = NULL; } delete test_edge; delete vertex3; new_face = test; } // face exitsts test // update edge TCircle3 circle1; TCircle3 circle2; TCircle3 circle3; getCircles(atom1,atom2,circle1,circle2,circle3); TVector3 ip1; // intersection points between TVector3 ip2; // the edge and the probe sphere TLine3 line(sphere1.p,sphere2.p,TLine3::FORM__TWO_POINTS); bool singular(GetIntersection(probe,line,ip1,ip2)); if (singular && Maths::isLess(ip1.getSquareDistance(sphere2.p), ip2.getSquareDistance(sphere2.p))) { // ip1 is the intersection point next to the first ip1.swap(ip2); // vertex of the edge } edge->face_[1] = new_face; edge->center_of_torus_ = circle1.p; edge->radius_of_torus_ = circle1.radius; edge->angle_ = phi; edge->circle0_ = circle2; edge->circle1_ = circle3; edge->intersection_point0_ = ip1; edge->intersection_point1_ = ip2; edge->singular_ = singular; if (edge->index_ == -1) { rs_->insert(edge); } return true; } void RSComputer::correct(Index atom) throw() { std::list::iterator v; RSVertex* vertex; HashSet faces; HashSet treat_faces; HashSet::Iterator f; HashSet test_vertices; HashSet delete_edges; v = vertices_[atom].begin(); while (v != vertices_[atom].end()) { treat_faces.clear(); test_vertices.clear(); delete_edges.clear(); vertex = *v; v++; faces = vertex->faces_; for (f = faces.begin(); f != faces.end(); f++) { (*f)->remove(delete_edges,test_vertices,treat_faces); } for (f = faces.begin(); f != faces.end(); f++) { treat_faces.erase(*f); new_faces_.erase(*f); rs_->faces_[(*f)->index_] = NULL; delete *f; } for (f = treat_faces.begin(); f != treat_faces.end(); f++) { rs_->faces_[(*f)->index_] = NULL; rs_->faces_.push_back(*f); (*f)->index_ = rs_->number_of_faces_; rs_->number_of_faces_++; } HashSet::Iterator edge; for (edge = delete_edges.begin(); edge != delete_edges.end(); edge++) { Index index = (*edge)->index_; if (index != -1) { rs_->edges_[index] = NULL; } delete *edge; } test_vertices.erase(vertex); HashSet::Iterator test; for (test = test_vertices.begin(); test != test_vertices.end(); test++) { if ((*test)->hasEdges() == false) { rs_->vertices_[(*test)->index_] = NULL; vertices_[(*test)->atom_].remove(*test); new_vertices_.erase(*test); delete *test; } } rs_->vertices_[vertex->index_] = NULL; vertices_[atom].remove(vertex); new_vertices_.erase(vertex); delete vertex; } rs_->atom_[atom].radius -= 10*Constants::EPSILON; atom_status_[atom] = STATUS_UNKNOWN; correctProbePosition(atom); } void RSComputer::extendComponent() throw(Exception::GeneralException, Exception::DivisionByZero, Exception::IndexOverflow) { while (new_vertices_.size() > 0) { RSFace* face = NULL; RSVertex* vertex1 = *new_vertices_.begin(); new_vertices_.erase(new_vertices_.begin()); Index atom1(vertex1->atom_); std::list::const_iterator i; i = neighbours_[atom1].begin(); bool stop = false; while (!stop && i != neighbours_[atom1].end()) { if (atom_status_[*i] == STATUS_UNKNOWN) { Index atom2 = *i; neighboursOfTwoAtoms(atom1,atom2); std::list< std::pair< Index,TSphere3 > > candidates; findThirdAtom(atom1,atom2,neighbours_of_two_[atom1][atom2], candidates); if (candidates.size() == 0) { RSVertex* vertex2 = new RSVertex(atom2); RSEdge* edge = createFreeEdge(vertex1,vertex2); if (edge != NULL) { insert(edge); insert(vertex2); new_vertices_.insert(vertex1); // i = neighbours_[atom1].end()--; ??? break; } else { delete vertex2; } } else { std::list< std::pair< Index,TSphere3 > >::iterator j = candidates.begin(); while (j != candidates.end()) { if (atom_status_[j->first] == STATUS_UNKNOWN) { Index atom3 = j->first; TSphere3 probe = j->second; if (checkProbe(probe,atom1,atom2,atom3) == true) { face = new RSFace; RSEdge* edge1 = new RSEdge; RSEdge* edge2 = new RSEdge; RSEdge* edge3 = new RSEdge; RSVertex* vertex2 = new RSVertex(atom2); RSVertex* vertex3 = new RSVertex(atom3); updateFaceAndEdges(vertex1,vertex2,vertex3, edge1,edge2,edge3, face,probe); insert(face); insert(vertex2); insert(vertex3); new_vertices_.insert(vertex1); // i = neighbours_[atom1].end()--; // j = candidates.end()--; // ???? stop = true; break; } } j++; } // while j } } i++; } // while i if (face != NULL) { getRSComponent(); } } } Index RSComputer::thirdAtom (RSVertex* vertex1, RSVertex* vertex2, RSFace* face, TSphere3& probe, TAngle& phi) throw(Exception::GeneralException, Exception::DivisionByZero, Exception::IndexOverflow) { // This function chooses from all atoms which can be touced by the probe // sphere when it touches the given two vertices this one, for which is // the rotation angle the smalest. // If the rotation angle equals zero, the probe sphere can touch four or // more atoms an an exception is thrown. // If no atom can be found an exception is thrown. Index atom1(vertex1->atom_); Index atom2(vertex2->atom_); neighboursOfTwoAtoms(atom1,atom2); std::list > > candidates; findThirdAtom(atom1,atom2,neighbours_of_two_[atom1][atom2],candidates); std::list > >::iterator k; TAngle old_angle(3*Constants::PI,true); TAngle new_angle; TAngle two_pi(2*Constants::PI,true); TVector3 axis = rs_->atom_[atom1].p-rs_->atom_[atom2].p; TVector3 test_vector = face->normal_%axis; Index third_face_atom = face->third(vertex1,vertex2)->atom_; if (Maths::isLess(test_vector*rs_->atom_[third_face_atom].p, test_vector*rs_->atom_[atom1].p) ) { axis.negate(); } TSphere3 sphere1(rs_->atom_[atom1]); TSphere3 sphere2(rs_->atom_[atom2]); sphere1.radius += rs_->probe_radius_; sphere2.radius += rs_->probe_radius_; TCircle3 circle; GetIntersection(sphere1,sphere2,circle); TVector3 start_probe = face->center_; TVector3 v1 = start_probe-circle.p; TVector3 face_normal = face->normal_; std::list > > third; for (k = candidates.begin(); k != candidates.end(); k++) { if ((k->first != third_face_atom) || (k->second.p != start_probe)) // not found the starting face { TVector3 v2(k->second.p-circle.p); new_angle = getOrientedAngle(v1,v2,axis); if (Maths::isZero(new_angle.value) || (new_angle == two_pi)) { correct(k->first); throw Exception::GeneralException (__FILE__,__LINE__,"CAN'T COMPUTE RS", "PROBE SPHERE TOUCHES FOUR ATOMS"); } if (new_angle <= old_angle) { if (new_angle < old_angle) { old_angle = new_angle; std::list > >::iterator t; for (t = third.begin(); t != third.end(); t++) { if (atom_status_[t->first] == STATUS_UNKNOWN) { atom_status_[t->first] = STATUS_INSIDE; } } third.clear(); } third.push_back(*k); } else { if (atom_status_[k->first] == STATUS_UNKNOWN) { atom_status_[k->first] = STATUS_INSIDE; } } } } if (third.size() > 1) { k = third.begin(); k++; while (k != third.end()) { correct(k->first); k++; } throw Exception::GeneralException (__FILE__,__LINE__,"CAN'T COMPUTE RS", "PROBE SPHERE TOUCHES FOUR ATOMS"); } probe = third.front().second; phi.set(old_angle.value,true); atom_status_[third.front().first] = STATUS_ON_SURFACE; return third.front().first; } Position RSComputer::getStartPosition() throw(Exception::DivisionByZero) { if (findFirstFace() != NULL) { return 3; } if (findFirstEdge() != NULL) { return 2; } if (findFirstVertex() != NULL) { return 1; } return 0; } RSFace* RSComputer::findFirstFace() throw(Exception::DivisionByZero) { for (Position direction = 0; direction < 3; direction++) { for (Position extrem = 0; extrem < 1; extrem++) { RSFace* face = findFace(direction,extrem); if (face != NULL) { return face; } } } return NULL; } RSEdge* RSComputer::findFirstEdge() throw() { for (Position direction = 0; direction < 3; direction++) { for (Position extrem = 0; extrem < 1; extrem++) { RSEdge* edge = findEdge(direction,extrem); if (edge != NULL) { return edge; } } } return NULL; } RSVertex* RSComputer::findFirstVertex() throw() { for (Position i = 0; i < rs_->number_of_atoms_; i++) { if (atom_status_[i] == STATUS_UNKNOWN) { if (neighbours_[i].size() == 0) { RSVertex* vertex = new RSVertex(i); insert(vertex); return vertex; } } } return NULL; } RSFace* RSComputer::findFace(Position direction, Position extrem) throw(Exception::DivisionByZero) { Index a1 = findFirstAtom(direction,extrem); if (a1 == -1) { return NULL; } Index a2 = findSecondAtom(a1,direction,extrem); if (a2 == -1) { return NULL; } neighboursOfTwoAtoms(a1,a2); std::list > > candidates; findThirdAtom(a1,a2,neighbours_of_two_[a1][a2],candidates); if (candidates.size() == 0) { return NULL; } std::list > >::iterator i = candidates.begin(); Index a3 = -1; TSphere3 probe; bool found = false; while ((found == false) && (i != candidates.end())) { a3 = i->first; probe = i->second; found = (atom_status_[a3] == STATUS_UNKNOWN) && checkProbe(probe,a1,a2,a3); i++; } if (found) { RSVertex* vertex1 = new RSVertex(a1); RSVertex* vertex2 = new RSVertex(a2); RSVertex* vertex3 = new RSVertex(a3); RSEdge* e1 = new RSEdge; RSEdge* e2 = new RSEdge; RSEdge* e3 = new RSEdge; RSFace* face = new RSFace; updateFaceAndEdges(vertex1,vertex2,vertex3,e1,e2,e3,face,probe); insert(face); insert(vertex1); insert(vertex2); insert(vertex3); return face; } else { atom_status_[a1] = STATUS_INSIDE; atom_status_[a2] = STATUS_INSIDE; return NULL; } } RSEdge* RSComputer::findEdge(Position direction, Position extrem) throw() { Index a1 = findFirstAtom(direction,extrem); if (a1 == -1) { return NULL; } Index a2 = findSecondAtom(a1,direction,extrem); if (a2 == -1) { return NULL; } RSVertex* vertex1 = new RSVertex(a1); RSVertex* vertex2 = new RSVertex(a2); neighboursOfTwoAtoms(a1,a2); RSEdge* edge = createFreeEdge(vertex1,vertex2); if (edge != NULL) { insert(edge); insert(vertex1); insert(vertex2); return edge; } else { delete vertex1; delete vertex2; neighbours_[a1].remove(a2); neighbours_[a2].remove(a1); return NULL; } } Index RSComputer::findFirstAtom(Position direction, Position extrem) throw() { Index extrem_atom = -1; // find the first atom of unknown status Index i = 0; bool found = false; while ((found == false) && (i < (Index)rs_->number_of_atoms_)) { if (atom_status_[i] == STATUS_UNKNOWN) { found = true; } else { i++; } } if (found) { extrem_atom = i; TSphere3* next_atom = &(rs_->atom_[i]); double extrem_value = ((extrem == 0) ? next_atom->p[direction]-next_atom->radius : next_atom->p[direction]+next_atom->radius); i++; // find the atom of unknown status lying on the extrem position while (i < (Index)rs_->number_of_atoms_) { if (atom_status_[i] == STATUS_UNKNOWN) { next_atom = &(rs_->atom_[i]); double extremum = ((extrem == 0) ? next_atom->p[direction]-next_atom->radius : next_atom->p[direction]+next_atom->radius); if (((extrem == 0) && Maths::isLess(extremum,extrem_value)) || ((extrem != 0) && Maths::isGreater(extremum,extrem_value))) { extrem_value = extremum; extrem_atom = i; } } i++; } } return extrem_atom; } Index RSComputer::findSecondAtom (Index atom, Position direction, Position extrem) throw() { Index second_atom = -1; // find the first neighbour atom of unknown status std::list::const_iterator i = neighbours_[atom].begin(); bool found = false; while ((found == false) && (i != neighbours_[atom].end())) { if (atom_status_[*i] == STATUS_UNKNOWN) { found = true; } else { i++; } } if (found) { second_atom = *i; TSphere3 first_atom(rs_->atom_[atom]); first_atom.radius += rs_->probe_radius_; double extrem_value = ((extrem == 0) ? first_atom.p[direction]+first_atom.radius : first_atom.p[direction]-first_atom.radius); TSphere3 next_atom; TCircle3 intersection_circle; // find the neighbour atom of unknown status lying on the extrem position while (i != neighbours_[atom].end()) { if (atom_status_[*i] == STATUS_UNKNOWN) { next_atom = rs_->atom_[*i]; next_atom.radius += rs_->probe_radius_; if (GetIntersection(first_atom,next_atom,intersection_circle)) { double next_extrem = getCircleExtremum(intersection_circle,direction,extrem); if (((extrem == 0) && Maths::isLess(next_extrem,extrem_value)) || ((extrem != 0) && Maths::isGreater(next_extrem,extrem_value))) { extrem_value = next_extrem; second_atom = *i; } } } i++; } } return second_atom; } void RSComputer::findThirdAtom (Index atom1, Index atom2, const std::list& third, std::list > >& atoms) throw() { // This function computes a list of all atoms (with its probe positions) // which can be touched by the probe sphere when it touches the two given // atoms std::pair > candidate; std::list::const_iterator i = third.begin(); TVector3 center1, center2; TSphere3 probe; probe.radius = rs_->probe_radius_; while (i != third.end()) { if (centerOfProbe(atom1,atom2,*i,center1,center2)) { if ((Maths::isNan(center1.x) || Maths::isNan(center1.y) || Maths::isNan(center1.z) ) == false) { probe.p.set(center1); candidate.first = *i; candidate.second = probe; atoms.push_back(candidate); } if ((Maths::isNan(center2.x) || Maths::isNan(center2.y) || Maths::isNan(center2.z) ) == false) { probe.p.set(center2); candidate.first = *i; candidate.second = probe; atoms.push_back(candidate); } } i++; } } void RSComputer::neighboursOfTwoAtoms(Index atom1, Index atom2) throw() { bool found = false; HashMap > >::Iterator n1 = neighbours_of_two_.find(atom1); if (n1 != neighbours_of_two_.end()) { HashMap >::Iterator n2 = n1->second.find(atom2); found = (n2 != n1->second.end()); } if (found == false) { std::list empty; neighbours_of_two_[atom1][atom2] = empty; neighbours_of_two_[atom2][atom1] = empty; std::list::iterator i1 = neighbours_[atom1].begin(); std::list::iterator i2 = neighbours_[atom2].begin(); while ((i1 != neighbours_[atom1].end()) && (i2 != neighbours_[atom2].end())) { if (*i1 == *i2) { neighbours_of_two_[atom1][atom2].push_back(*i1); neighbours_of_two_[atom2][atom1].push_back(*i1); i1++; i2++; } else { if (*i1 < *i2) { i1++; } else { i2++; } } } } } void RSComputer::neighboursOfThreeAtoms (Index atom1, Index atom2, Index atom3, ::std::list& output_list) throw() { neighboursOfTwoAtoms(atom1,atom2); neighboursOfTwoAtoms(atom1,atom3); HashMap > >::Iterator n1 = neighbours_of_two_.find(atom1); HashMap >::Iterator n2 = n1->second.find(atom2); HashMap >::Iterator n3 = n1->second.find(atom3); std::list::iterator i2 = n2->second.begin(); // fixed by Andreas Moll, 19.7.06: i3 used to work on n2->second.begin() std::list::iterator i3 = n3->second.begin(); while ((i2 != n2->second.end()) && (i3 != n3->second.end())) { if (*i2 == *i3) { output_list.push_back(*i2); i2++; i3++; } else { if (*i2 < *i3) { i2++; } else { i3++; } } } } double RSComputer::getCircleExtremum (const TCircle3& circle, Position direction, Position extrem) throw() { double min = 0; double max = 0; TVector3 norm2(circle.n.x * circle.n.x, circle.n.y * circle.n.y, circle.n.z * circle.n.z); switch (direction) { case 0 : if (Maths::isZero(circle.n.y) && Maths::isZero(circle.n.z)) { min = max = circle.p.x; } else { double x_norm = norm2.y + norm2.z; x_norm /= norm2.x+x_norm; x_norm = circle.radius * sqrt(x_norm); min = (circle.p.x) - x_norm; max = (circle.p.x) + x_norm; } break; case 1 : if (Maths::isZero(circle.n.x) && Maths::isZero(circle.n.z)) { min = max = circle.p.y; } else { double y_norm = norm2.x + norm2.z; y_norm /= norm2.y + y_norm; y_norm = circle.radius * sqrt(y_norm); min = (circle.p.y)-y_norm; max = (circle.p.y)+y_norm; } break; case 2 : if (Maths::isZero(circle.n.x) && Maths::isZero(circle.n.y)) { min = max = circle.p.z; } else { double z_norm = norm2.x + norm2.y; z_norm /= norm2.z + z_norm; z_norm = circle.radius * sqrt(z_norm); min = circle.p.z - z_norm; max = circle.p.z + z_norm; } break; } if (extrem == 0) { return min; } else { return max; } } RSEdge* RSComputer::createFreeEdge (RSVertex* vertex1, RSVertex* vertex2) throw() { Index atom1 = vertex1->atom_; Index atom2 = vertex2->atom_; TCircle3 circle1; TCircle3 circle2; TCircle3 circle3; if (getCircles(atom1, atom2, circle1, circle2, circle3) && Maths::isGreater(circle1.radius,rs_->probe_radius_)) { TPlane3 plane(circle1.p,circle1.n); ::std::list::const_iterator i; TCircle3 test_circle; TSphere3 sphere; double dist; for (i = neighbours_of_two_[atom1][atom2].begin(); i != neighbours_of_two_[atom1][atom2].end(); i++) { sphere.set(rs_->atom_[*i].p,rs_->atom_[*i].radius+rs_->probe_radius_); if (GetIntersection(sphere,plane,test_circle)) { dist = test_circle.radius-circle1.radius; if (Maths::isLessOrEqual(dist*dist, test_circle.p.getSquareDistance(circle1.p))) { return NULL; } } } TVector3 vector(0,0,0); RSEdge* edge = new RSEdge(vertex1,vertex2,NULL,NULL, circle1.p,circle1.radius, TAngle(2*Constants::PI,true), circle2,circle3, vector,vector,false,-1); return edge; } return NULL; } bool RSComputer::getCircles (Index atom1, Index atom2, TCircle3& circle1, TCircle3& circle2, TCircle3& circle3) throw() { TSphere3 sphere1(rs_->atom_[atom1]); TSphere3 sphere2(rs_->atom_[atom2]); sphere1.radius += rs_->probe_radius_; sphere2.radius += rs_->probe_radius_; if (GetIntersection(sphere1,sphere2,circle1)) { double ratio = rs_->atom_[atom1].radius/sphere1.radius; circle2.radius = circle1.radius*ratio; circle2.p = sphere1.p+(circle1.p-sphere1.p)*ratio; ratio = rs_->atom_[atom2].radius/sphere2.radius; circle3.radius = circle1.radius*ratio; circle3.p = sphere2.p+(circle1.p-sphere2.p)*ratio; return true; } return false; } TVector3 RSComputer::getFaceNormal (const TSphere3& atom1, const TSphere3& atom2, const TSphere3& atom3, const TSphere3& probe) throw() { TPlane3 plane(atom1.p,atom2.p,atom3.p); TVector3 norm(plane.n); if (Maths::isLess(norm*probe.p,norm*atom1.p)) { norm.negate(); } return norm; } void RSComputer::updateFaceAndEdges (RSVertex* v1, RSVertex* v2, RSVertex* v3, RSEdge* e1, RSEdge* e2, RSEdge* e3, RSFace* f, const TSphere3& probe) throw() { e1->vertex_[0] = v1; e1->vertex_[1] = v2; e1->face_[0] = f; e2->vertex_[0] = v2; e2->vertex_[1] = v3; e2->face_[0] = f; e3->vertex_[0] = v3; e3->vertex_[1] = v1; e3->face_[0] = f; f->vertex_[0] = v1; f->vertex_[1] = v2; f->vertex_[2] = v3; f->edge_[0] = e1; f->edge_[1] = e2; f->edge_[2] = e3; f->center_ = probe.p; TPlane3 plane(rs_->atom_[v1->atom_].p, rs_->atom_[v2->atom_].p, rs_->atom_[v3->atom_].p); f->normal_ = plane.n; if (Maths::isLess(f->normal_*probe.p,f->normal_*rs_->atom_[v1->atom_].p)) { f->normal_.negate(); } f->singular_ = Maths::isLess(GetDistance(probe.p,plane),probe.radius); } RSFace* RSComputer::faceExists (RSFace* face, const std::list& vertices) throw() { std::list::const_iterator v; RSFace* f; for (v = vertices.begin(); v != vertices.end(); v++) { f = (*v)->has(face); if (f != NULL) { return f; } } return NULL; } bool RSComputer::centerOfProbe (Index a1, Index a2, Index a3, TVector3& c1, TVector3& c2) throw() { sort(a1,a2,a3,a1,a2,a3); HashMap > >::Iterator pp1; HashMap >::Iterator pp2; HashMap::Iterator pp3; bool back = false; bool found = false; pp1 = probe_positions_.find(a1); if (pp1 != probe_positions_.end()) { pp2 = pp1->second.find(a2); if (pp2 != pp1->second.end()) { pp3 = pp2->second.find(a3); if (pp3 != pp2->second.end()) { found = true; if (pp3->second == NULL) { back = false; } else { c1 = pp3->second->point[0]; c2 = pp3->second->point[1]; back = true; } } } } if (found == false) { TSphere3 s1(rs_->atom_[a1]); TSphere3 s2(rs_->atom_[a2]); TSphere3 s3(rs_->atom_[a3]); s1.radius += rs_->probe_radius_; s2.radius += rs_->probe_radius_; s3.radius += rs_->probe_radius_; if (GetIntersection(s1,s2,s3,c1,c2,false)) { ProbePosition* position = new ProbePosition; position->status[0] = STATUS_NOT_TESTED; position->status[1] = STATUS_NOT_TESTED; position->point[0] = c1; position->point[1] = c2; probe_positions_[a1][a2][a3] = position; back = true; } else { probe_positions_[a1][a2][a3] = NULL; back = false; } } return back; } bool RSComputer::checkProbe (const TSphere3& probe, Index atom1, Index atom2, Index atom3) throw() { sort(atom1,atom2,atom3,atom1,atom2,atom3); Position index; ProbePosition* position = probe_positions_[atom1][atom2][atom3]; if (probe.p == position->point[0]) { index = 0; } else { index = 1; } if (position->status[index] == STATUS_NOT_TESTED) { bool ok = true; std::list atom_list; neighboursOfThreeAtoms(atom1,atom2,atom3,atom_list); double dist; std::list::iterator i = atom_list.begin(); while (ok && (i != atom_list.end())) { dist = probe.radius+rs_->atom_[*i].radius; if (Maths::isLess(probe.p.getSquareDistance(rs_->atom_[*i].p), dist*dist)) { position->status[index] = STATUS_NOT_OK; ok = false; } i++; } if (ok) { position->status[index] = STATUS_OK; } } return (position->status[index] == STATUS_OK); } void RSComputer::correctProbePosition(Position atom) throw() { HashMap > >::Iterator pp1; HashMap >::Iterator pp2; HashMap::Iterator pp3; for (pp1 = probe_positions_.begin(); pp1 != probe_positions_.end(); pp1++) { if (pp1->first < atom) { for (pp2 = pp1->second.begin(); pp2 != pp1->second.end(); pp2++) { if (pp2->first < atom) { if (pp2->second.has(atom)) { correctProbePosition(pp1->first,pp2->first,atom); } } else { if (pp2->first == atom) { for (pp3 = pp2->second.begin(); pp3 != pp2->second.end(); pp3++) { correctProbePosition(pp1->first,atom,pp3->first); } } } } } else { if (pp1->first == atom) { for (pp2 = pp1->second.begin(); pp2 != pp1->second.end(); pp2++) { for (pp3 = pp2->second.begin(); pp3 != pp2->second.end(); pp3++) { correctProbePosition(atom,pp2->first,pp3->first); } } } } } } void RSComputer::correctProbePosition (Position a1, Position a2, Position a3) throw() { Index ai1 = (Index)a1; Index ai2 = (Index)a2; Index ai3 = (Index)a3; sort(ai1, ai2, ai3, ai1, ai2, ai3); TSphere3 s1(rs_->atom_[ai1]); TSphere3 s2(rs_->atom_[ai2]); TSphere3 s3(rs_->atom_[ai3]); s1.radius += rs_->probe_radius_; s2.radius += rs_->probe_radius_; s3.radius += rs_->probe_radius_; TVector3 c1; TVector3 c2; if (GetIntersection(s1,s2,s3,c1,c2)) { ProbePosition* position = probe_positions_[ai1][ai2][ai3]; if (position == NULL) { probe_positions_[ai1][ai2][ai3] = new ProbePosition; position = probe_positions_[ai1][ai2][ai3]; } position->status[0] = STATUS_NOT_TESTED; position->status[1] = STATUS_NOT_TESTED; position->point[0] = c1; position->point[1] = c2; } else { delete probe_positions_[ai1][ai2][ai3]; probe_positions_[ai1][ai2][ai3] = NULL; } } void RSComputer::preProcessing() throw() { rs_->r_max_ = rs_->atom_[0].radius; double x_min = rs_->atom_[0].p.x; double y_min = rs_->atom_[0].p.y; double z_min = rs_->atom_[0].p.z; double x_max = x_min; double y_max = y_min; double z_max = z_min; for (Position i = 1; i < rs_->number_of_atoms_; i++) { rs_->r_max_ = ((rs_->r_max_ < rs_->atom_[i].radius) ? rs_->atom_[i].radius : rs_->r_max_); x_min = ((x_min > rs_->atom_[i].p.x) ? rs_->atom_[i].p.x : x_min); y_min = ((y_min > rs_->atom_[i].p.y) ? rs_->atom_[i].p.y : y_min); z_min = ((z_min > rs_->atom_[i].p.z) ? rs_->atom_[i].p.z : z_min); x_max = ((x_max < rs_->atom_[i].p.x) ? rs_->atom_[i].p.x : x_max); y_max = ((y_max < rs_->atom_[i].p.y) ? rs_->atom_[i].p.y : y_max); z_max = ((z_max < rs_->atom_[i].p.z) ? rs_->atom_[i].p.z : z_max); } rs_->bounding_box_.set(x_min,y_min,z_min,x_max,y_max,z_max); double dist = 2*(rs_->r_max_+rs_->probe_radius_); Position nx = (Position)((x_max-x_min)/dist+5); Position ny = (Position)((y_max-y_min)/dist+5); Position nz = (Position)((z_max-z_min)/dist+5); Vector3 origin(x_min-2*dist,y_min-2*dist,z_min-2*dist); HashGrid3 grid(origin,nx,ny,nz,dist); Vector3 pos; for (Position i = 0; i < rs_->number_of_atoms_; i++) { pos.set(rs_->atom_[i].p.x,rs_->atom_[i].p.y,rs_->atom_[i].p.z); grid.insert(pos,i); } TSphere3 next_atom; double offset; HashGridBox3* box; HashGridBox3::ConstBoxIterator b; HashGridBox3::ConstDataIterator d; for (Position i = 0; i < rs_->number_of_atoms_-1; i++) { offset = rs_->atom_[i].radius+2*rs_->probe_radius_; pos.set(rs_->atom_[i].p.x,rs_->atom_[i].p.y,rs_->atom_[i].p.z); box = grid.getBox(pos); for (b = box->beginBox(); b != box->endBox(); b++) { for (d = b->beginData(); d != b->endData(); d++) { if (*d > i) { next_atom = rs_->atom_[*d]; double dist = next_atom.p.getSquareDistance(rs_->atom_[i].p); double max_dist = next_atom.radius+offset; max_dist *= max_dist; if (Maths::isLess(dist,max_dist)) { neighbours_[i].push_back(*d); neighbours_[*d].push_back(i); } } } } neighbours_[i].sort(); } } void RSComputer::insert(RSVertex* vertex) throw() { rs_->insert(vertex); new_vertices_.insert(vertex); vertices_[vertex->atom_].push_back(vertex); atom_status_[vertex->atom_] = STATUS_ON_SURFACE; } void RSComputer::insert(RSEdge* edge) throw() { rs_->insert(edge); edge->vertex_[0]->edges_.insert(edge); edge->vertex_[1]->edges_.insert(edge); } void RSComputer::insert(RSFace* face) throw() { rs_->insert(face); new_faces_.insert(face); face->vertex_[0]->faces_.insert(face); face->vertex_[1]->faces_.insert(face); face->vertex_[2]->faces_.insert(face); RSEdge* edge = face->edge_[0]; edge->vertex_[0]->edges_.insert(edge); edge->vertex_[1]->edges_.insert(edge); edge = face->edge_[1]; edge->vertex_[0]->edges_.insert(edge); edge->vertex_[1]->edges_.insert(edge); edge = face->edge_[2]; edge->vertex_[0]->edges_.insert(edge); edge->vertex_[1]->edges_.insert(edge); } void RSComputer::sort (Index u1, Index u2, Index u3, Index& s1, Index& s2, Index& s3) throw() { s1 = u1; s2 = u2; s3 = u3; Index tmp; if (s1 > s2) { tmp = s1; s1 = s2; s2 = tmp; } if (s1 > s3) { tmp = s1; s1 = s3; s3 = tmp; } if (s2 > s3) { tmp = s2; s2 = s3; s3 = tmp; } } } // namespace BALL ugene-1.9.8/src/plugins_3rdparty/ball/src/source/STRUCTURE/triangulatedSAS.cpp0000644000175000017500000006633211651544326025572 0ustar ilyailya// -*- Mode: C++; tab-width: 2; -*- // vi: set ts=2: // // $Id: triangulatedSAS.C,v 1.5 2004-02-18 19:03:30 oliver Exp $ //# include //# include //# include //# include //# include //# include #include #include #include #include #include #include #include #include #include #include #include #include #include #include namespace BALL { void PartitionOfCircle(const TCircle3& circle, std::list& partition) { Size density = 64; Vector3 center(circle.p.x,circle.p.y,circle.p.z); Vector3 normal(circle.n.x,circle.n.y,circle.n.z); Vector4 p; p.set(normal.y,-normal.x,0.0,0.0); if (p == Vector4::getZero()) { p.set(normal.z,0.0,-normal.x,0.0); } p.normalize(); p *= circle.radius; Quaternion rotate(normal,Angle(Constants::PI/density,true)); Matrix4x4 rotation; rotate.getRotationMatrix(rotation); partition.push_back(Vector3(p.x,p.y,p.z)+center); for (Size i = 0; i < 2*density+1; i++) { p = rotation*p; partition.push_back(Vector3(p.x,p.y,p.z)+center); } } //void Circle2HIN(const TCircle3& circle, const String& file) //{ // std::list points; // PartitionOfCircle(circle,points); // Molecule* molecule = new Molecule; // Atom* a1; // Atom* a2; // a1 = new Atom; // a1->setPosition(points.front()); // a1->setElement(PTE[Element::H]); // molecule->insert(*a1); // std::list::iterator p; // for (p = points.begin(); p != points.end(); p++) // { // a2 = new Atom; // a2->setPosition(*p); // a2->setElement(PTE[Element::H]); // a1->createBond(*a2); // a1 = a2; // molecule->insert(*a1); // } // a1 = new Atom; // a1->setPosition(Vector3(circle.p.x,circle.p.y,circle.p.z)); // a1->setElement(PTE[Element::H]); // a2 = new Atom; // a2->setPosition(Vector3(circle.p.x,circle.p.y,circle.p.z)+Vector3(circle.n.x,circle.n.y,circle.n.z)); // a2->setElement(PTE[Element::H]); // a1->createBond(*a2); // molecule->insert(*a1); // molecule->insert(*a2); // System* system = new System; // system->insert(*molecule); // HINFile output(file,std::ios::out); // output << *system; // output.close(); // delete system; //} // //void Plane2HIN(const TPlane3& plane, const String& file, Position size = 20) //{ // std::vector atom; // Vector3 d1; // Vector3 d2; // Vector3 origin(plane.p.x,plane.p.y,plane.p.z); // if (Maths::isZero(plane.n.x)) // { // d1.set(0,plane.n.z,-plane.n.y); // } // else // { // d1.set(plane.n.y,-plane.n.x,0); // } // d2 = Vector3(plane.n.x,plane.n.y,plane.n.z)%d1; // d1.normalize(); // d2.normalize(); // origin -= d1*(size/2); // origin -= d2*(size/2); // Molecule* molecule = new Molecule; // for (Position i = 0; i < size; i++) // { // for (Position j = 0; j < size; j++) // { // Atom* a = new Atom; // a->setPosition(origin+(d1*i)+(d2*j)); // a->setElement(PTE[Element::H]); // atom.push_back(a); // molecule->insert(*a); // } // } // for (Position i = 0; i < size*(size-1); i++) // { // atom[i]->createBond(*atom[i+size]); // } // for (Position i = 0; i < size*size; i++) // { // if ((i%size) != 0) // { // atom[i]->createBond(*atom[i-1]); // } // } // origin += d1*(size/2); // origin += d2*(size/2); // Vector3 normal(plane.n.x,plane.n.y,plane.n.z); // normal.normalize(); // Atom* a1 = new Atom; // a1->setPosition(origin+normal); // a1->setElement(PTE[Element::H]); // Atom* a2 = new Atom; // a2->setPosition(origin); // a2->setElement(PTE[Element::H]); // a2->createBond(*a1); // molecule->insert(*a1); // molecule->insert(*a2); // System* system = new System; // system->insert(*molecule); // HINFile hinfile(file,std::ios::out); // hinfile << *system; // hinfile.close(); // delete system; //} TriangulatedSAS::TriangulatedSAS() throw() : TriangulatedSurface(), sas_(NULL), density_(4.5) { } TriangulatedSAS::TriangulatedSAS(const TriangulatedSAS& surface, bool deep) throw() : TriangulatedSurface(surface,deep), sas_(surface.sas_), density_(surface.density_) { } TriangulatedSAS::TriangulatedSAS (SolventAccessibleSurface* sas, const double& density) throw() : TriangulatedSurface(), sas_(sas), density_(density) { } TriangulatedSAS::~TriangulatedSAS() throw() { } void TriangulatedSAS::set(const TriangulatedSAS& surface, bool) throw() { if (this != &surface) { TriangulatedSurface::set(surface); sas_ = surface.sas_; density_ = surface.density_; } } TriangulatedSAS& TriangulatedSAS::operator = (const TriangulatedSAS& surface) throw() { if (this != &surface) { TriangulatedSurface::operator = (surface); sas_ = surface.sas_; density_ = surface.density_; } return *this; } void TriangulatedSAS::setDensity(const double& density) throw() { density_ = density; } double TriangulatedSAS::getDensity() const throw() { return density_; } void TriangulatedSAS::compute(int& progress) throw() { SASTriangulator sast(this); sast.run(progress); } #ifdef debug_triangulation void TriangulatedSAS::printToHIN(const string& filename) throw() { Molecule* molecule = new Molecule; std::list::iterator t; for (t = triangles_.begin(); t != triangles_.end(); t++) { TVector3 norm(((*t)->vertex_[0]->point_-(*t)->vertex_[1]->point_) % ((*t)->vertex_[0]->point_-(*t)->vertex_[2]->point_) ); norm.normalize(); norm /= 4; Atom* atom1 = new Atom; Atom* atom2 = new Atom; Atom* atom3 = new Atom; Atom* atom4 = new Atom; Atom* atom5 = new Atom; Atom* atom6 = new Atom; atom1->setElement(PTE[Element::H]); atom2->setElement(PTE[Element::H]); atom3->setElement(PTE[Element::H]); atom4->setElement(PTE[Element::H]); atom5->setElement(PTE[Element::H]); atom6->setElement(PTE[Element::H]); atom1->setPosition((*t)->vertex_[0]->point_); atom2->setPosition((*t)->vertex_[1]->point_); atom3->setPosition((*t)->vertex_[2]->point_); atom4->setPosition((*t)->vertex_[0]->point_+norm); atom5->setPosition((*t)->vertex_[1]->point_+norm); atom6->setPosition((*t)->vertex_[2]->point_+norm); #ifdef with_bonds atom1->createBond(*atom2); atom2->createBond(*atom3); atom3->createBond(*atom1); atom1->createBond(*atom4); atom2->createBond(*atom5); atom3->createBond(*atom6); #endif molecule->insert(*atom1); molecule->insert(*atom2); molecule->insert(*atom3); molecule->insert(*atom4); molecule->insert(*atom5); molecule->insert(*atom6); } System* system = new System; system->insert(*molecule); HINFile hinfile(filename,ios::out); hinfile << *system; hinfile.close(); delete system; } #endif ////////////////////////////////////////////////// SASTriangulator::SASTriangulator() throw() : tsas_(NULL), sqrt_density_(0.0), edge_(), template_spheres_() { } SASTriangulator::SASTriangulator(TriangulatedSAS* tsas) throw() : tsas_(tsas), sqrt_density_(sqrt(tsas->density_)), edge_(tsas_->sas_->number_of_edges_), template_spheres_() { } SASTriangulator::~SASTriangulator() throw() { } void SASTriangulator::run(int& progress) throw() { // build template spheres with different densities and outside normal vectors buildTemplateSpheres(); // use tese to triangulete the sas faces uint numFaces = tsas_->sas_->number_of_faces_; for (Position i = 0; i < numFaces; i++) { triangulateFace(tsas_->sas_->faces_[i]); progress = (i + 1) * 100 / numFaces; } } void SASTriangulator::triangulateFace(SASFace* face) throw() { // store the planes of the SAS edges std::list< std::pair,double> > planes; createPlanes(face,planes); // get template sphere TSphere3* sphere = &face->sphere_; HashMap::ConstIterator s = template_spheres_.find(numberOfRefinements(tsas_->density_, sphere->radius)); TriangulatedSurface part = s->second; part.blowUp(sphere->radius); part.shift(sphere->p); // tag inside points tagPoints(part,planes); // remove inside triangles and then isolated edges and points removeInsideTriangles(part); part.deleteIsolatedEdges(); part.deleteIsolatedPoints(); // create HashGrid of triangle points // HashGrid3 point_grid(createHashGrid(part)); // create points on the cutting planes // createPoints(part,planes,point_grid); // create new triangles // createNewTriangles(part,point_grid); // remove isolated edges and points // part.deleteIsolatedEdges(); // part.deleteIsolatedPoints(); // join the triangulation of this sas face with the sas tsas_->join(part); } void SASTriangulator::createPlanes (SASFace* face, std::list< std::pair,double> >& planes) throw() { std::pair,double> plane; std::list::iterator edge; std::list::iterator o = face->orientation_.begin(); for (edge = face->edge_.begin(); edge != face->edge_.end(); edge++) { plane.first.p = (*edge)->circle_.p; if (*o) { plane.first.n = (*edge)->circle_.n; } else { plane.first.n = -(*edge)->circle_.n; } plane.second = plane.first.n*plane.first.p; planes.push_back(plane); o++; } } void SASTriangulator::tagPoints (TriangulatedSurface& part, const std::list< std::pair,double> >& planes) throw() { TriangulatedSurface::PointIterator p; std::list< std::pair,double> >::const_iterator plane; for (p = part.beginPoint(); p != part.endPoint(); p++) { (*p)->index_ = 0; plane = planes.begin(); while (plane != planes.end()) { if (Maths::isLessOrEqual(plane->first.n*(*p)->point_,plane->second)) { (*p)->index_ = 1; plane = planes.end(); } else { plane++; } } } } void SASTriangulator::removeInsideTriangles(TriangulatedSurface& part) throw() { TriangulatedSurface::TriangleIterator t1; TriangulatedSurface::TriangleIterator t2; t1 = part.beginTriangle(); while (t1 != part.endTriangle()) { if ((*t1)->vertex_[0]->index_+ (*t1)->vertex_[1]->index_+ (*t1)->vertex_[2]->index_ == 3) { t2 = t1; t2++; if (t2 == part.endTriangle()) { part.remove(t1); t1 = part.endTriangle(); } else { part.remove(t1); t1 = t2; } } else { t1++; } } } HashGrid3 SASTriangulator::createHashGrid(const TriangulatedSurface& part) throw() { double x_min = (*(part.beginPoint()))->point_.x; double y_min = (*(part.beginPoint()))->point_.y; double z_min = (*(part.beginPoint()))->point_.z; double x_max = (*(part.beginPoint()))->point_.x; double y_max = (*(part.beginPoint()))->point_.y; double z_max = (*(part.beginPoint()))->point_.z; TriangulatedSurface::ConstPointIterator p = part.beginPoint()++; while (p != part.endPoint()) { x_min = Maths::min(x_min,(*p)->point_.x); y_min = Maths::min(y_min,(*p)->point_.y); z_min = Maths::min(z_min,(*p)->point_.z); x_max = Maths::max(x_min,(*p)->point_.x); y_max = Maths::max(y_max,(*p)->point_.y); z_max = Maths::max(z_max,(*p)->point_.z); p++; } //double dist = ses_->reduced_surface_->r_max_/3; double dist = 1.0; Position nx = (Position)((x_max-x_min)/dist+5); Position ny = (Position)((y_max-y_min)/dist+5); Position nz = (Position)((z_max-z_min)/dist+5); Vector3 origin(x_min-2*dist,y_min-2*dist,z_min-2*dist); HashGrid3 grid = HashGrid3(origin,nx,ny,nz,dist); p = part.beginPoint()++; while (p != part.endPoint()) { grid.insert(Vector3((*p)->point_.x,(*p)->point_.y,(*p)->point_.z),*p); p++; } return grid; } void SASTriangulator::createPoints (TriangulatedSurface& part, const std::list< std::pair,double> >& planes, HashGrid3& grid) throw() { TriangulatedSurface::EdgeIterator edge = part.beginEdge(); std::list< std::pair,double> >::const_iterator plane; while (edge != part.endEdge()) { if ((*edge)->vertex_[0]->index_+(*edge)->vertex_[1]->index_ == 1) { // edge intersects one of the cutting planes TrianglePoint* v1; TrianglePoint* v2; if ((*edge)->vertex_[0]->index_ == 0) { v1 = (*edge)->vertex_[0]; v2 = (*edge)->vertex_[1]; } else { v1 = (*edge)->vertex_[1]; v2 = (*edge)->vertex_[0]; } TVector3 diff(v2->point_-v1->point_); TVector3 point(v2->point_); double min = 1.0; double div; Size counter = 0; for (plane = planes.begin(); plane != planes.end(); plane++) { // intersecting point = v1 + lambda * (v2-v1) div = plane->first.n*diff; if (Maths::isNotZero(div)) { double lambda = (plane->second-(plane->first.n*v1->point_))/div; if (Maths::isGreaterOrEqual(lambda,0) && (Maths::isLessOrEqual(lambda,min))) { min = lambda; point.set(v1->point_+(lambda*diff)); (*edge)->index_ = counter; } } counter++; } v2->edges_.erase(*edge); TrianglePoint* new_point = vertexExists(point,grid); if (new_point == NULL) { new_point = new TrianglePoint; new_point->point_ = point; new_point->index_ = -1; new_point->edges_.insert(*edge), part.insert(new_point); grid.insert(Vector3(point.x,point.y,point.z),new_point); } if ((*edge)->vertex_[0] == v1) { (*edge)->vertex_[1] = new_point; } else { (*edge)->vertex_[0] = new_point; } } else { (*edge)->index_ = -1; } edge++; } } void SASTriangulator::createNewTriangles (TriangulatedSurface& part, HashGrid3& grid) throw() { TriangulatedSurface::TriangleIterator t = part.beginTriangle(); while (t != part.endTriangle()) { Position type = 0; if ((*t)->vertex_[0]->index_ == 1) { type++; } if ((*t)->vertex_[1]->index_ == 1) { type += 2; } if ((*t)->vertex_[2]->index_ == 1) { type += 4; } switch (type) { case 0 : break; // triangle not intersected case 1 : onePointOutside(0,*t,part,grid); break; case 2 : onePointOutside(1,*t,part,grid); break; case 3 : twoPointsOutside(0,1,*t,part,grid); break; case 4 : onePointOutside(2,*t,part,grid); break; case 5 : twoPointsOutside(2,0,*t,part,grid); break; case 6 : twoPointsOutside(1,2,*t,part,grid); break; case 7 : break; // should never happen } t++; } } void SASTriangulator::onePointOutside (Index outside, Triangle* t, TriangulatedSurface& part, HashGrid3& grid) throw() { std::cout << "onePointOutside ...\n"; // get the relative indices of the intersected edges Position edge[3]; Position i = 0; for (Position j = 0; j < 3; j++) { if (t->edge_[j]->index_ != -1) { edge[i] = j; i++; } else { edge[2] = j; } } // v1 = new vertex of the first intersected edge // v2 = old vertex of the first intersected edge // v3 = new vertex of the second intersected edge // v4 = old vertex of the second intersected edge TrianglePoint* v1; TrianglePoint* v2; TrianglePoint* v3; TrianglePoint* v4; Position test = ((t->edge_[edge[0]]->vertex_[0]->index_ == -1) ? 0 : 1); v1 = t->edge_[edge[0]]->vertex_[test]; v2 = t->edge_[edge[0]]->vertex_[1-test]; test = ((t->edge_[edge[1]]->vertex_[0]->index_ == -1) ? 0 : 1); v3 = t->edge_[edge[1]]->vertex_[test]; v4 = t->edge_[edge[1]]->vertex_[1-test]; // get the relative index of v4 which is needed // to compute the correct orientation of the first new triangle Index index = 0; for (Position j = 0; j < 3; j++) { if (t->vertex_[j] == v4) { index = j; } } // resize the original triangle t->vertex_[outside]->faces_.erase(t); t->vertex_[outside] = v1; v1->faces_.insert(t); // create a new triangle Triangle* new_triangle = new Triangle; new_triangle->vertex_[0] = v1; if ((outside-index == 1) || (outside-index == -2)) { new_triangle->vertex_[1] = v4; new_triangle->vertex_[2] = v3; } else { new_triangle->vertex_[1] = v3; new_triangle->vertex_[2] = v4; } v1->faces_.insert(new_triangle); v3->faces_.insert(new_triangle); v4->faces_.insert(new_triangle); part.insert(new_triangle); // does the triangle intersect two different SAS edges? if (t->edge_[edge[0]]->index_ != t->edge_[edge[1]]->index_) { // ACHTUNG: pos MUSS NOCH BERECHNET WERDEN !!! TVector3 pos(v1->point_); TrianglePoint* new_point = vertexExists(pos,grid); if (new_point == NULL) { new_point = new TrianglePoint; new_point->point_ = pos; new_point->index_ = -1; part.insert(new_point); grid.insert(Vector3(pos.x,pos.y,pos.z),new_point); } Triangle* third_triangle = new Triangle; third_triangle->vertex_[0] = v1; if ((outside-index == 1) || (outside-index == -2)) { third_triangle->vertex_[1] = v3; third_triangle->vertex_[2] = new_point; } else { third_triangle->vertex_[1] = new_point; third_triangle->vertex_[2] = v3; } v1->faces_.insert(third_triangle); v3->faces_.insert(third_triangle); new_point->faces_.insert(third_triangle); part.insert(third_triangle); } std::cout << "... ok\n"; } void SASTriangulator::twoPointsOutside (Position outside1, Position outside2, Triangle* t, TriangulatedSurface& part, HashGrid3& grid) throw() { std::cout << "twoPointsOutside ...\n"; // get the relative indices of the intersected edges Position edge[3]; Position i = 0; for (Position j = 0; j < 3; j++) { if (t->edge_[j]->index_ != -1) { edge[i] = j; i++; } else { edge[2] = j; } } // v1 = new vertex of the first intersected edge // v2 = old vertex of the first intersected edge // v3 = new vertex of the second intersected edge TrianglePoint* v1; TrianglePoint* v2; TrianglePoint* v3; Position test = ((t->edge_[edge[0]]->vertex_[0]->index_ == -1) ? 0 : 1); v1 = t->edge_[edge[0]]->vertex_[test]; v2 = t->edge_[edge[0]]->vertex_[1-test]; test = ((t->edge_[edge[1]]->vertex_[0]->index_ == -1) ? 0 : 1); v3 = t->edge_[edge[1]]->vertex_[test]; // resize the original triangle t->vertex_[outside1]->faces_.erase(t); t->vertex_[outside2]->faces_.erase(t); TLine3 line(v1->point_,v2->point_,TLine3::FORM__TWO_POINTS); bool one = line.has(t->vertex_[outside1]->point_); if (one) { t->vertex_[outside1] = v1; t->vertex_[outside2] = v3; } else { t->vertex_[outside1] = v3; t->vertex_[outside2] = v1; } v1->faces_.insert(t); v2->faces_.insert(t); // does the triangle intersect two different SAS edges? if (t->edge_[edge[0]]->index_ != t->edge_[edge[1]]->index_) { // ACHTUNG: pos MUSS NOCH BERECHNET WERDEN !!! TVector3 pos(v1->point_); TrianglePoint* new_point = vertexExists(pos,grid); if (new_point == NULL) { new_point = new TrianglePoint; new_point->point_ = pos; new_point->index_ = -1; part.insert(new_point); grid.insert(Vector3(pos.x,pos.y,pos.z),new_point); } Triangle* new_triangle = new Triangle; new_triangle->vertex_[0] = t->vertex_[outside2]; new_triangle->vertex_[1] = t->vertex_[outside1]; new_triangle->vertex_[2] = new_point; v1->faces_.insert(new_triangle); v3->faces_.insert(new_triangle); new_point->faces_.insert(new_triangle); part.insert(new_triangle); } std::cout << "... ok\n"; } TrianglePoint* SASTriangulator::vertexExists (const TVector3& point, HashGrid3& grid) throw() { double epsilon = Constants::EPSILON; Constants::EPSILON = 0.001; Vector3 p(point.x,point.y,point.z); HashGridBox3* box = grid.getBox(p); HashGridBox3::ConstBoxIterator b; HashGridBox3::ConstDataIterator d; if (box != NULL) { for (b = box->beginBox(); b != box->endBox(); b++) { for (d = b->beginData(); d != b->endData(); d++) { if ((*d)->point_ == point) { Constants::EPSILON = epsilon; return *d; } } } } Constants::EPSILON = epsilon; return NULL; } Size SASTriangulator::numberOfRefinements(const double& density, const double& radius) throw() { double test0 = (4.0*density*Constants::PI*radius*radius-12.0)/30.0; Size n = 0; if (Maths::isGreaterOrEqual(test0,0.0)) { double test1 = 1; double test2 = 1; while (Maths::isLess(test2,test0)) { test1 = test2; test2 *= 4; n++; } if (Maths::isLess(test2-test0,test0-test1)) { n++; } } if (n > 4) { n = 4; } return n; } void SASTriangulator::buildTemplateSpheres() throw() { TriangulatedSphere sphere; sphere.icosaeder(true); sphere.setIndices(); template_spheres_[0] = sphere; sphere.refine(1,true); sphere.setIndices(); template_spheres_[1] = sphere; sphere.refine(1,true); sphere.setIndices(); template_spheres_[2] = sphere; sphere.refine(1,true); sphere.setIndices(); template_spheres_[3] = sphere; sphere.refine(1,true); sphere.setIndices(); template_spheres_[4] = sphere; } #ifdef debug_triangulation void SASTriangulator::printToHINFile(string filename) { Molecule* molecule = new Molecule; #ifdef with_bonds std::list::iterator t; for (t = triangles_.begin(); t != triangles_.end(); t++) { Atom* atom1 = new Atom; atom1->setPosition((*t)->vertex_[0]->point_); atom1->setElement(PTE[Element::H]); molecule->insert(*atom1); #ifdef with_normals Atom* normal1 = new Atom; normal1->setPosition((*t)->vertex_[0]->point_+(*t)->vertex_[0]->normal_); normal1->createBond(*atom1); normal1->setElement(PTE[Element::O]); molecule->insert(*normal1); #endif Atom* atom2 = new Atom; atom2->setPosition((*t)->vertex_[1]->point_); atom2->setElement(PTE[Element::H]); molecule->insert(*atom2); #ifdef with_normals Atom* normal2 = new Atom; normal2->setPosition((*t)->vertex_[1]->point_+(*t)->vertex_[1]->normal_); normal2->createBond(*atom2); normal2->setElement(PTE[Element::O]); molecule->insert(*normal1); #endif Atom* atom3 = new Atom; atom3->setPosition((*t)->vertex_[2]->point_); atom3->setElement(PTE[Element::H]); molecule->insert(*atom3); #ifdef with_normals Atom* normal3 = new Atom; normal3->setPosition((*t)->vertex_[2]->point_+(*t)->vertex_[2]->normal_); normal3->createBond(*atom3); normal3->setElement(PTE[Element::O]); molecule->insert(*normal1); #endif atom1->createBond(*atom3); atom1->createBond(*atom2); atom3->createBond(*atom2); } #else std::list::iterator p; for (p = points_.begin(); p != points_.end(); p++) { Atom* new_atom = new Atom; new_atom->setPosition((*p)->point_); new_atom->setElement(PTE[Element::H]); atom.push_back(new_atom); molecule->insert(*new_atom); #ifdef with_normals Atom* normal = new Atom; normal->setPosition((*p)->point_+(*p)->normal_); normal->createBond(*new_atom); normal->setElement(PTE[Element::O]); molecule->insert(*normal); #endif } #endif System* system = new System; system->insert(*molecule); HINFile hinfile(filename,std::ios::out); hinfile << *system; hinfile.close(); delete system; } void SASTriangulator::Contour2HIN(const std::list& contour, const string& file) { HashSet points; std::list::const_iterator c; for (c = contour.begin(); c != contour.end(); c++) { points.insert((*c)->vertex_[0]); points.insert((*c)->vertex_[1]); } Molecule* molecule = new Molecule; for (c = contour.begin(); c != contour.end(); c++) { Atom* atom1 = new Atom; atom1->setPosition((*c)->vertex_[0]->point_); atom1->setElement(PTE[Element::H]); Atom* atom2 = new Atom; atom2->setPosition((*c)->vertex_[1]->point_); atom2->setElement(PTE[Element::H]); atom1->createBond(*atom2); molecule->insert(*atom1); molecule->insert(*atom2); } System* system = new System; system->insert(*molecule); HINFile hinfile(file,std::ios::out); hinfile << *system; hinfile.close(); delete system; } void SASTriangulator::SASEdge2HIN(SASEdge* edge, const string& file) { std::list contour; std::list contour_points; if (edge->vertex_[0] == NULL) { TAngle phi(2*Constants::PI,true); Size number_of_segments = (Size)Maths::round(phi.value*edge->circle_.radius*2.12); if (number_of_segments == 0) { number_of_segments++; } TAngle psi(phi.value/number_of_segments,true); std::vector< TVector3 > points; partitionOfCircle(edge->circle_,TVector3::getZero(),psi,number_of_segments,points,false); points.pop_back(); TrianglePoint* p0; TrianglePoint* p1; TrianglePoint* p2; TriangleEdge* e; p1 = new TrianglePoint; p1->point_ = points[0]; p1->normal_ = edge->circle_.p-p1->point_; contour_points.push_back(p1); p0 = p1; for (Position k = 1; k < points.size(); k++) { p2 = new TrianglePoint; p2->point_ = points[k]; p2->normal_ = edge->circle_.p-p2->point_; contour_points.push_back(p2); e = new TriangleEdge; e->vertex_[0] = p1; e->vertex_[1] = p2; contour.push_back(e); p1->edges_.insert(e); p2->edges_.insert(e); p1 = p2; } e = new TriangleEdge; e->vertex_[0] = p1; e->vertex_[1] = p0; contour.push_back(e); p1->edges_.insert(e); p0->edges_.insert(e); } else { TAngle phi; GetTAngle(edge->vertex_[0]->point_-edge->circle_.p, edge->vertex_[1]->point_-edge->circle_.p, phi); Size number_of_segments = (Size)Maths::round(phi.value*edge->circle_.radius*2.12); if (number_of_segments == 0) { number_of_segments++; } TAngle psi(phi.value/number_of_segments,true); TVector3 normal((edge->vertex_[0]->point_-edge->circle_.p)% (edge->vertex_[1]->point_-edge->circle_.p)); edge->circle_.n = normal; std::vector< TVector3 > points; partitionOfCircle(edge->circle_,edge->vertex_[0]->point_,psi,number_of_segments, points); points.pop_back(); points.push_back(edge->vertex_[1]->point_); TrianglePoint* p1; TrianglePoint* p2; TriangleEdge* e; p1 = new TrianglePoint; p1->point_ = points[0]; p1->normal_ = edge->circle_.p-p1->point_; contour_points.push_back(p1); for (Position k = 1; k < points.size(); k++) { p2 = new TrianglePoint; p2->point_ = points[k]; p2->normal_ = edge->circle_.p-p2->point_; contour_points.push_back(p2); e = new TriangleEdge; e->vertex_[0] = p1; e->vertex_[1] = p2; contour.push_back(e); p1->edges_.insert(e); p2->edges_.insert(e); p1 = p2; } } Contour2HIN(contour,file); std::list::iterator e; for (e = contour.begin(); e != contour.end(); e++) { delete *e; } std::list::iterator p; for (p = contour_points.begin(); p != contour_points.end(); p++) { delete *p; } } #endif } //namespace BALL ugene-1.9.8/src/plugins_3rdparty/ball/src/source/STRUCTURE/graphVertex.cpp0000644000175000017500000000015111651544326025022 0ustar ilyailya// -*- Mode: C++; tab-width: 2; -*- // vi: set ts=2: // // $Id: #include ugene-1.9.8/src/plugins_3rdparty/ball/src/source/STRUCTURE/graphFace.cpp0000644000175000017500000000014711651544326024410 0ustar ilyailya// -*- Mode: C++; tab-width: 2; -*- // vi: set ts=2: // // $Id: #include ugene-1.9.8/src/plugins_3rdparty/ball/src/source/DATATYPE/0000755000175000017500000000000011651544310021626 5ustar ilyailyaugene-1.9.8/src/plugins_3rdparty/ball/src/source/DATATYPE/hashGrid.cpp0000644000175000017500000000022711651544326024073 0ustar ilyailya// -*- Mode: C++; tab-width: 2; -*- // vi: set ts=2: // // $Id: hashGrid.C,v 1.2 2002-02-27 12:21:11 sturm Exp $ #include ugene-1.9.8/src/plugins_3rdparty/ball/src/source/DATATYPE/string.cpp0000644000175000017500000011337511651544326023661 0ustar ilyailya// -*- Mode: C++; tab-width: 2; -*- // vi: set ts=2: // // $Id: string.C,v 1.53 2005-02-15 19:18:41 oliver Exp $ // #include #include #include #include #include using std::ostream; using std::istream; using std::stringstream; using std::endl; using std::ends; using std::vector; namespace BALL { #ifndef BALL_HAVE_VSNPRINTF int BALLString_vsnprintf(char* s, size_t n, const char* format, va_list ap) { // this is an ugly hack - this is safe only up to // the static buffer size - no time to implement // something more sophisticated... OK char* tmp = new char[65536]; vsprintf(tmp, format, ap); if (n > 65535) { n = 65535; } strncpy(s, tmp, n - 1); s[n - 1] = (char)0; delete [] tmp; return (int)strlen(s); } # define vsnprintf BALLString_vsnprintf #endif const char* String::CHARACTER_CLASS__ASCII_ALPHA = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; const char* String::CHARACTER_CLASS__ASCII_ALPHANUMERIC = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; const char* String::CHARACTER_CLASS__ASCII_LOWER = "abcdefghijklmnopqrstuvwxyz"; const char* String::CHARACTER_CLASS__ASCII_NUMERIC = "0123456789"; const char* String::CHARACTER_CLASS__ASCII_UPPER = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; const char* String::CHARACTER_CLASS__WHITESPACE = " \n\t\r\f\v"; const char* String::CHARACTER_CLASS__QUOTES = "\""; const Size String::EndPos = Limits::max(); const String String::EMPTY(""); String::CompareMode String::compare_mode_ = String::CASE_SENSITIVE; Substring::UnboundSubstring::UnboundSubstring(const char* file, int line) : Exception::GeneralException(file, line, "UnboundSubstring", "trying to use a substring that was not bound to a string.") { } Substring::InvalidSubstring::InvalidSubstring(const char* file, int line) : Exception::GeneralException(file, line, "InvalidSubstring", "the substring is not valid") { } Substring::Substring() throw() : bound_(0), from_((Index)String::EndPos), to_((Index)String::EndPos) { } Substring::Substring(const Substring& substring, bool /* deep */) throw() : bound_(substring.bound_), from_(substring.from_), to_(substring.to_) { } Substring::Substring(const String& s, Index from, Size len) throw(Exception::IndexUnderflow, Exception::IndexOverflow) { s.validateRange_(from, len); bound_ = (String *)& s; from_ = from; to_ = from + (Index)len - 1; } Substring::~Substring() throw() { } void Substring::dump(ostream& s, Size depth) const throw(Substring::UnboundSubstring) { if (bound_ == 0) { throw UnboundSubstring(__FILE__, __LINE__); } BALL_DUMP_STREAM_PREFIX(s); BALL_DUMP_DEPTH(s, depth); s << " bound String: " << (void *)bound_ << endl; BALL_DUMP_DEPTH(s, depth); s << " from index: " << from_ << endl; BALL_DUMP_DEPTH(s, depth); s << " to index: " << to_ << endl; BALL_DUMP_DEPTH(s, depth); s << " string: "; const char *end_of_string = bound_->c_str() + to_; for (const char* ptr = bound_->c_str() + from_; ptr <= end_of_string; ptr++) s << *ptr; s << endl; BALL_DUMP_STREAM_SUFFIX(s); } ostream& operator << (ostream &s, const Substring& substring) throw() { if (substring.isBound() == false) { return s; } const char* char_ptr = substring.bound_->c_str() + substring.from_; const char* end_of_string = substring.bound_->c_str() + substring.to_; while (char_ptr <= end_of_string) { s.put(*char_ptr++); } return s; } String::String(const char* char_ptr, Index from, Size len) throw(Exception::NullPointer, Exception::IndexUnderflow, Exception::IndexOverflow) : string() { validateCharPtrRange_(from, len, char_ptr); if (len > 0) { assign(char_ptr + from, len); } } // hand-coded create method void* String::create(bool /* deep */, bool empty) const throw() { void* ptr; if (empty == true) { ptr = (void*)new String; } else { ptr = (void*)new String(*this); } return ptr; } String::String(Size buffer_size, const char* format, ... ) throw(Exception::IndexUnderflow, Exception::NullPointer) : string() { if (buffer_size <= 0) { throw Exception::IndexUnderflow(__FILE__, __LINE__); } if (format == 0) { throw Exception::NullPointer(__FILE__, __LINE__); } char* buffer = new char[buffer_size]; va_list var_arg_list; va_start(var_arg_list, format); vsnprintf(buffer, (Size)buffer_size, format, var_arg_list); va_end(var_arg_list); assign(buffer); delete [] buffer; } #ifdef BALL_HAS_SSTREAM String::String(std::stringstream& s) throw() #else String::String(std::strstream& s) throw() #endif : string("") { s >> (*this); } # define BALL_STRING_DEFINE_CONSTRUCTOR_METHOD(type, format_string) \ String::String(type t) throw()\ { \ char buffer[128]; \ \ sprintf(buffer, format_string, t); \ assign(buffer);\ }\ BALL_STRING_DEFINE_CONSTRUCTOR_METHOD(short, "%hd") BALL_STRING_DEFINE_CONSTRUCTOR_METHOD(unsigned short, "%hu") BALL_STRING_DEFINE_CONSTRUCTOR_METHOD(int, "%d") BALL_STRING_DEFINE_CONSTRUCTOR_METHOD(unsigned int, "%u") BALL_STRING_DEFINE_CONSTRUCTOR_METHOD(long, "%ld") BALL_STRING_DEFINE_CONSTRUCTOR_METHOD(unsigned long, "%lu") BALL_STRING_DEFINE_CONSTRUCTOR_METHOD(float, "%f") BALL_STRING_DEFINE_CONSTRUCTOR_METHOD(double, "%f") #undef BALL_STRING_DEFINE_CONSTRUCTOR_METHOD String::~String() throw() { erase(); } void String::set(const String& s) { std::string::operator = (s); } void String::set(const String& s, Index from, Size len) throw(Exception::IndexUnderflow, Exception::IndexOverflow) { s.validateRange_(from, len); if (len == 0) { erase(); } else { assign(s.c_str() + from, len); } } void String::set(const char* s, Index from, Size len) throw(Exception::NullPointer, Exception::IndexUnderflow, Exception::IndexOverflow) { validateCharPtrRange_(from, len, s); if (len == 0) { erase(); } else { assign(s + from, len); } } void String::set(Size buffer_size, const char *format, ... ) throw(Exception::IndexUnderflow, Exception::NullPointer) { if (buffer_size <= 0) { throw Exception::IndexUnderflow(__FILE__, __LINE__); } if (format == 0) { throw Exception::NullPointer(__FILE__, __LINE__); } char* buffer = new char[buffer_size]; va_list var_arg_list; va_start(var_arg_list, format); vsnprintf(buffer, (Size)buffer_size, format, var_arg_list); va_end(var_arg_list); assign(buffer); delete [] buffer; } # define BALL_STRING_DEFINE_SET_METHOD(type, format_string) \ void String::set(type t) throw()\ { \ char buffer[128]; \ \ sprintf(buffer, format_string, t); \ \ assign(buffer);\ } BALL_STRING_DEFINE_SET_METHOD(short, "%hd") BALL_STRING_DEFINE_SET_METHOD(unsigned short, "%hu") BALL_STRING_DEFINE_SET_METHOD(int, "%d") BALL_STRING_DEFINE_SET_METHOD(unsigned int, "%u") BALL_STRING_DEFINE_SET_METHOD(long, "%ld") BALL_STRING_DEFINE_SET_METHOD(unsigned long, "%lu") BALL_STRING_DEFINE_SET_METHOD(float, "%f") BALL_STRING_DEFINE_SET_METHOD(double, "%f") #undef BALL_STRING_DEFINE_SET_METHOD void String::get(char* char_ptr, Index from, Size max_len) const throw(Exception::NullPointer, Exception::IndexUnderflow, Exception::IndexOverflow) { validateIndex_(from); if (max_len == 0) { return; } Size len = std::min(max_len, (Size)(size() - from)); const char* string_ptr = &(c_str()[from]); Size i = 0; while (i < len) { *char_ptr = *string_ptr; char_ptr++; string_ptr++; i++; } *char_ptr = '\0'; } bool String::toBool() const throw() { string::size_type str_index = find_first_not_of(CHARACTER_CLASS__WHITESPACE); if (size() == 0) { return true; } if (str_index != string::npos) { Size index = (Index)str_index; if (!(c_str()[index] == '0' && (isWhitespace(c_str()[index + 1]) == true || c_str()[index + 1] == '\0')) && !(c_str()[index++] == 'f' && c_str()[index++] == 'a' && c_str()[index++] == 'l' && c_str()[index++] == 's' && c_str()[index++] == 'e' && (isWhitespace(c_str()[index]) == true || c_str()[index] == '\0'))) { return true; } } return false; } short String::toShort() const throw(Exception::InvalidFormat) { if (!isFloat()) { throw Exception::InvalidFormat(__FILE__, __LINE__, string(c_str())); } errno = 0; int i = atoi(c_str()); if ((errno == ERANGE) || (i < (int)Limits::min()) || (i > (int)Limits::max())) { errno = 0; throw Exception::InvalidFormat(__FILE__, __LINE__, string("out of range: ") + c_str()); } errno = 0; return (short)i; } unsigned short String::toUnsignedShort() const throw(Exception::InvalidFormat) { if (!isFloat()) { throw Exception::InvalidFormat(__FILE__, __LINE__, string(c_str())); } errno = 0; int i = atoi(c_str()); if ((errno == ERANGE) || (i < (int)0) || (i > (int)Limits::max())) { errno = 0; throw Exception::InvalidFormat(__FILE__, __LINE__, string("out of range: ") + c_str()); } errno = 0; return (unsigned short)i; } int String::toInt() const throw(Exception::InvalidFormat) { if (!isFloat()) { throw Exception::InvalidFormat(__FILE__, __LINE__, string(c_str())); } errno = 0; int i = atoi(c_str()); if (errno == ERANGE) { throw Exception::InvalidFormat(__FILE__, __LINE__, string("out of range: ") + string(c_str())); } return i; } unsigned int String::toUnsignedInt() const throw(Exception::InvalidFormat) { if (!isFloat()) { throw Exception::InvalidFormat(__FILE__, __LINE__, string(c_str())); } errno = 0; unsigned int ui = (unsigned int)strtoul(c_str(), (char **)0, 10); if (errno == ERANGE) { throw Exception::InvalidFormat(__FILE__, __LINE__, string(c_str())); } return ui; } long String::toLong() const throw(Exception::InvalidFormat) { if (!isFloat()) { throw Exception::InvalidFormat(__FILE__, __LINE__, string(c_str())); } errno = 0; long l = atol(c_str()); if (errno == ERANGE) { throw Exception::InvalidFormat(__FILE__, __LINE__, string(c_str())); } return l; } unsigned long String::toUnsignedLong() const throw(Exception::InvalidFormat) { if (!isFloat()) { throw Exception::InvalidFormat(__FILE__, __LINE__, string(c_str())); } errno = 0; unsigned long ul = strtoul(c_str(), (char **)0, 10); if (errno == ERANGE) { throw Exception::InvalidFormat(__FILE__, __LINE__, string(c_str())); } return ul; } float String::toFloat() const throw(Exception::InvalidFormat) { if (!isFloat()) { throw Exception::InvalidFormat(__FILE__, __LINE__, string(c_str())); } errno = 0; float f = (float)atof(c_str()); if (errno == ERANGE) { throw Exception::InvalidFormat(__FILE__, __LINE__, string(c_str())); } return f; } double String::toDouble() const throw(Exception::InvalidFormat) { if (!isFloat()) { throw Exception::InvalidFormat(__FILE__, __LINE__, string(c_str())); } errno = 0; double d = atof(c_str()); if (errno == ERANGE) { throw Exception::InvalidFormat(__FILE__, __LINE__, string(c_str())); } return d; } void String::toLower(Index from, Size len) throw(Exception::IndexUnderflow, Exception::IndexOverflow) { validateRange_(from, len); Index index = from; char* char_ptr = const_cast(c_str()) + from; for (; index < (Index)(from + len); index++, char_ptr++) { *char_ptr = tolower(*char_ptr); } } void String::toUpper(Index from, Size len) throw(Exception::IndexUnderflow, Exception::IndexOverflow) { validateRange_(from, len); Index index = from; char *char_ptr = const_cast(c_str()) + from; for(; index < (Index)(from + len); index++, char_ptr++) { *char_ptr = toupper(*char_ptr); } } Size String::countFields(const char* delimiters) const throw(Exception::NullPointer) { if (delimiters == 0) { throw Exception::NullPointer(__FILE__, __LINE__); } Size number_of_fields = 0; const char* end_char = &c_str()[size()]; const char* current_delimiter = 0; const char* current_char = c_str(); while (current_char < end_char) { for (; current_char < end_char; ++current_char) { current_delimiter = (char*)strchr(delimiters, *current_char); if (current_delimiter == 0) { break; } } if (current_char < end_char) { ++number_of_fields; ++current_char; } for (; current_char < end_char; ++current_char) { current_delimiter = (char*)strchr(delimiters, *current_char); if (current_delimiter != 0) { break; } } } return number_of_fields; } Size String::countFieldsQuoted(const char* delimiters, const char* quotes) const throw(Exception::NullPointer) { if ((delimiters == 0) || (quotes == 0)) { throw Exception::NullPointer(__FILE__, __LINE__); } Size number_of_fields = 0; const char* end_char = &c_str()[size()]; const char* current_delimiter = 0; const char* current_char = c_str(); const char* current_quote = 0; const char* last_quote = 0; while (current_char < end_char) { for (; current_char < end_char; ++current_char) { current_quote = (char*)strchr(quotes, *current_char); if (current_quote != 0) { if (last_quote == 0) { last_quote = current_char; } else { // if the same quote character is used again, // it is a closing quote if (*last_quote == *current_quote) { last_quote = 0; } } } if ((last_quote == 0) && (current_quote != current_char)) { current_delimiter = (char*)strchr(delimiters, *current_char); if (current_delimiter == 0) { break; } } } if (current_char < end_char) { ++number_of_fields; ++current_char; } for (; current_char < end_char; ++current_char) { current_quote = (char*)strchr(quotes, *current_char); if (current_quote != 0) { if (last_quote == 0) { last_quote = current_char; } else { // if the same quote character is used again, // it is a closing quote if (*last_quote == *current_quote) { last_quote = 0; } } } if (last_quote == 0) { current_delimiter = (char*)strchr(delimiters, *current_char); if (current_delimiter != 0) { break; } } } } return number_of_fields; } String String::getField(Index index, const char* delimiters, Index* from_and_next_field) const throw(Exception::IndexUnderflow, Exception::NullPointer) { if ((from_and_next_field != 0) && (*from_and_next_field < 0)) { throw Exception::IndexUnderflow(__FILE__, __LINE__, *from_and_next_field, 0); } if (delimiters == 0) { throw Exception::NullPointer(__FILE__, __LINE__); } // allow also negative indices (last field == -1) if (index < 0) { index = (Index)countFields(delimiters) + index; if (index < 0) { throw Exception::IndexUnderflow(__FILE__, __LINE__, index); } } const char *end = &c_str()[size()]; Index current_index = 0; const char *current_delimiter = 0; const char *current_char = &c_str()[from_and_next_field == 0 ? 0 : *from_and_next_field]; const char *field_begin = 0; while (current_char < end) { for (; current_char < end; ++current_char) { current_delimiter = (char*)strchr(delimiters, *current_char); if (current_delimiter == 0) { break; } } if (current_index == index) { field_begin = current_char; for (++current_char; current_char < end; ++current_char) { current_delimiter = (char*)strchr(delimiters, *current_char); if (current_delimiter != 0) { break; } } if (from_and_next_field != 0) { if (current_char >= end) { *from_and_next_field = (Index)EndPos; } else { *from_and_next_field = (Index)(current_char - c_str()); } } if (field_begin < end) { return String(field_begin, 0, (Size)(current_char - field_begin)); } } ++current_index; for (; current_char < end; ++current_char) { current_delimiter = (char*)strchr(delimiters, *current_char); if (current_delimiter != 0) { break; } } } if (from_and_next_field != 0) { *from_and_next_field = (Index)EndPos; } return String(); } const char* eatDelimiters_(const char* start, const char* end, const char* delimiters) throw() { const char* current_delimiter = (char*)strchr(delimiters, *start); while ((current_delimiter != 0) && (start < end)) { start++; current_delimiter = (char*)strchr(delimiters, *start); } return start; } String String::getFieldQuoted(Index index, const char* delimiters, const char* quotes, Index* from_and_next_field) const throw(Exception::IndexUnderflow, Exception::NullPointer) { if ((from_and_next_field != 0) && (*from_and_next_field < 0)) { throw Exception::IndexUnderflow(__FILE__, __LINE__, *from_and_next_field, 0); } if ((delimiters == 0) || (quotes == 0)) { throw Exception::NullPointer(__FILE__, __LINE__); } // allow also negative indices (last field == -1) if (index < 0) { index = (Index)countFieldsQuoted(delimiters) + index; if (index < 0) { throw Exception::IndexUnderflow(__FILE__, __LINE__, index); } } String field; const char* end = &c_str()[size()]; Index current_index = -1; const char* current_delimiter = 0; const char* current_quote = 0; const char* last_quote = 0; const char* current_char = &c_str()[from_and_next_field == 0 ? 0 : *from_and_next_field]; do { current_char = eatDelimiters_(current_char, end, delimiters); current_index++; // we are at the start of a new field while (current_char < end) { current_quote = (char*)strchr(quotes, *current_char); if (current_quote != 0) { if (last_quote != 0) { // reached the terminating quote if (*last_quote == *current_quote) { last_quote = 0; } else { // just another quote character which doesn't matter if (index == current_index) { field += *current_char; } } } else { // this is a new quote last_quote = current_quote; } } else { if (last_quote == 0) { current_delimiter = (char*)strchr(delimiters, *current_char); if (current_delimiter != 0) { // we found a delimiter // continue with the outer loop -> eat these delimiters! break; } } if (current_index == index) { field += *current_char; } } current_char++; } if (current_index == index) { break; } } while ((current_char < end) && (current_index < index)); if (from_and_next_field != 0) { *from_and_next_field = (Index)(current_char - &(c_str()[0])); if (current_char >= end) { *from_and_next_field = (Index)EndPos; } } return field; } Size String::split(String string_array[], Size array_size, const char* delimiters, Index from) const throw(Exception::IndexUnderflow, Exception::NullPointer) { Size array_index = 0; if (array_size < 1) { return 0; } while(from != (Index)EndPos) { string_array[array_index] = getField(0, delimiters, &from); if (string_array[array_index] != "") { array_index++; } if (array_index == array_size) { return array_index; } } return array_index; } Size String::split(vector& strings, const char* delimiters, Index from) const throw(Exception::IndexUnderflow, Exception::NullPointer) { // clear the vector anyway strings.clear(); while(from != (Index)EndPos) { String field = getField(0, delimiters, &from); if (field != "") { strings.push_back(field); } } return (Size)strings.size(); } Size String::splitQuoted(vector& strings, const char* delimiters, const char* quotes, Index from) const throw(Exception::IndexUnderflow, Exception::NullPointer) { // clear the vector anyway strings.clear(); while (from != (Index)EndPos) { String field = getFieldQuoted(0, delimiters, quotes, &from); if (field != "") { strings.push_back(field); } } return (Size)strings.size(); } String& String::trimLeft(const char* trimmed_chars) throw() { if ((trimmed_chars == 0) || (size() == 0)) { return *this; } string::size_type index = find_first_not_of(trimmed_chars); if (index != string::npos) { // erase the whitespace characters on the left erase(0, index); } else { // if nothing was found, the string might contain only whitespaces! String trimmed(trimmed_chars); if (trimmed.has((*this)[0])) { assign(""); } } return *this; } String& String::trimRight(const char* trimmed_chars) throw() { if (trimmed_chars == 0 || size() == 0) { return *this; } string::size_type index = find_last_not_of(trimmed_chars); if (index != string::npos) { // delete the whitespace characters on the right hand side erase(index + 1); } else { // if nothing was found, the string might contain only whitespaces! String trimmed(trimmed_chars); if (trimmed.has((*this)[size() - 1])) { assign(""); } } return *this; } String operator + (const char* char_ptr, const String& s) throw() { String result(char_ptr); result.append(s); return result; } String operator + (char c, const String& s) throw() { String result(c); result.append(s); return result; } bool String::hasPrefix(const String& s) const throw() { if (s.size() > size()) { return false; } if (s.size() == 0) { return true; } return (memcmp(c_str(), s.c_str(), s.size()) == 0); } bool String::hasSuffix(const String& s) const throw() { if (s.size() > size()) { return false; } if (s.size() == 0) { return true; } int result = memcmp(c_str() + size() - s.size(), s.c_str(), s.size()); return (result == 0); } #define BALL_STRING_DEFINE_IS_CLASS_METHOD(func, isclass) \ bool func() const throw()\ { \ const char* end = &c_str()[size()]; \ \ for (const char* ptr = c_str(); ptr < end; ptr++) \ if (!isclass(*ptr)) \ return false; \ \ return true; \ } BALL_STRING_DEFINE_IS_CLASS_METHOD(String::isAlpha, isAlpha) BALL_STRING_DEFINE_IS_CLASS_METHOD(String::isAlnum, isAlnum) BALL_STRING_DEFINE_IS_CLASS_METHOD(String::isDigit, isDigit) BALL_STRING_DEFINE_IS_CLASS_METHOD(String::isWhitespace, isWhitespace) BALL_STRING_DEFINE_IS_CLASS_METHOD(String::isSpace, isSpace) #undef BALL_STRING_DEFINE_IS_CLASS_METHOD String& String::reverse(Index from, Size len) throw(Exception::IndexUnderflow, Exception::IndexOverflow) { validateRange_(from, len); if (len > 1) { char* forward_ptr = const_cast(c_str()) + from; char* backward_ptr = const_cast(c_str()) + from + len - 1; char temp = 0; for (; forward_ptr < backward_ptr; ++forward_ptr, --backward_ptr) { temp = *forward_ptr; *forward_ptr = *backward_ptr; *backward_ptr = temp; } } return *this; } int String::compare(const String& s, Index from, Size len) const throw(Exception::IndexUnderflow, Exception::IndexOverflow) { validateRange_(from, len); if ((this == &s) && (from == 0)) { return 0; } Size newlen = std::min((Size)s.size(), len); int result = 0; if (compare_mode_ == CASE_INSENSITIVE) { const char* s1 = c_str() + from; const char* s2 = s.c_str(); for (; newlen > 0; s1++, s2++, newlen--) { result = tolower(*s1) - tolower(*s2); if (result != 0) { break; } } } else { result = strncmp(c_str() + from, s.c_str(), newlen); } if ((result == 0) && (len != newlen)) { result = (int)len - (int)s.size(); } return result; } int String::compare(const String& s, Index from) const throw(Exception::IndexUnderflow, Exception::IndexOverflow) { validateIndex_(from); if ((this == &s) && (from == 0)) { return 0; } Size len = (Size)(size() - from); Size newlen = std::min((Size)s.size(), len); int result = 0; if (compare_mode_ == CASE_INSENSITIVE) { const char* s1 = c_str() + from; const char* s2 = s.c_str(); for (; newlen > 0; s1++, s2++, newlen--) { result = tolower(*s1) - tolower(*s2); if (result != 0) { break; } } } else { result = strncmp(c_str() + from, s.c_str(), newlen); } if (result == 0) { result = (int)len - (int)s.size(); } return result; } int String::compare(const char* char_ptr, Index from, Size len) const throw(Exception::NullPointer, Exception::IndexUnderflow, Exception::IndexOverflow) { if (char_ptr == 0) { throw Exception::NullPointer(__FILE__, __LINE__); } validateRange_(from, len); if ((c_str() + from) == char_ptr) { return 0; } Size newlen = (Size)strlen(char_ptr); newlen = std::min(len, newlen); int result = 0; if (compare_mode_ == CASE_INSENSITIVE) { const char* ptr1 = c_str() + from; const char* ptr2 = char_ptr; for (; newlen > 0; ptr1++, ptr2++) { newlen--; result = tolower(*ptr1) - tolower(*ptr2); if (result != 0) { break; } } } else { result = strncmp(c_str() + from, char_ptr, newlen); } if ((result == 0) && (len != newlen)) { result = (int)size() - (int)from - (int)strlen(char_ptr); } return result; } int String::compare(const char* char_ptr, Index from) const throw(Exception::NullPointer, Exception::IndexUnderflow, Exception::IndexOverflow) { if (char_ptr == 0) { throw Exception::NullPointer(__FILE__, __LINE__); } // indices may be given as negative arguments: start from the end // -1 therefore means the last bit. Size string_size = (Size)size(); if (from < 0) { from = (Index)string_size + from; // if the value is out of bounds - throw an exception // and leave it... if (from < 0) { throw Exception::IndexUnderflow(__FILE__, __LINE__, from, string_size); } } if ((Size)from > string_size) { throw Exception::IndexOverflow(__FILE__, __LINE__, from, string_size); } Size len = string_size - from; if ((c_str() + from) == char_ptr) { return 0; } Size newlen = std::min((Size)strlen(char_ptr), len); newlen = len; int result = 0; if (compare_mode_ == CASE_INSENSITIVE) { const char* ptr1 = c_str() + from; const char* ptr2 = char_ptr; for (; newlen > 0; ptr1++, ptr2++) { newlen--; result = tolower(*ptr1) - tolower(*ptr2); if (result != 0) { break; } } } else { result = strncmp(c_str() + from, char_ptr, newlen); } if ((result == 0) && (len == newlen)) { return (int)string_size - (int)from - (int)strlen(char_ptr); } return result; } istream& getline(istream& s, String& str, char delimiter) throw() { char c; str.destroy(); while (s.get(c)) { if (c == delimiter) { break; } str.append(1, c); } return s; } void String::dump(ostream &s, Size depth) const throw() { BALL_DUMP_STREAM_PREFIX(s); BALL_DUMP_DEPTH(s, depth); s << " capacity: " << capacity() << endl; BALL_DUMP_DEPTH(s, depth); s << " size: " << size() << endl; BALL_DUMP_DEPTH(s, depth); s << " string: "; const char* end_ptr = &c_str()[size()]; for (const char *char_ptr = c_str(); char_ptr < end_ptr; char_ptr++) s << *char_ptr; s << endl; BALL_DUMP_STREAM_SUFFIX(s); } Size String::substitute(const String& to_replace, const String& replacing) throw() { Size replaced_size = (Size)to_replace.size(); string::size_type found = 0; if (to_replace != "") { found = find(to_replace); } if (found != string::npos) { replace(found, replaced_size, replacing); } return ((found == string::npos) ? EndPos : (Size)found); } void String::validateIndex_(Index& index) const throw (Exception::IndexUnderflow, Exception::IndexOverflow) { // indices may be given as negative arguments: start from the end // -1 therefore means the last bit. Size string_size = (Size)size(); if (index < 0) { index = (Index)string_size + index; // if the value is out of bounds - throw an exception // and leave it... if (index < 0) { throw Exception::IndexUnderflow(__FILE__, __LINE__, index, string_size); } } if ((Size)index > string_size) { throw Exception::IndexOverflow(__FILE__, __LINE__, index, string_size); } } void String::validateRange_(Index& from, Size& len) const throw (Exception::IndexUnderflow, Exception::IndexOverflow) { Size string_size = (Size)size(); // indices may be given as negative arguments: start from the end // -1 therefore means the last character of the string. if (from < 0) { from = (Index)string_size + from; // if the values are out of bounds - throw an exception // and leave it... if (from < 0) { throw Exception::IndexUnderflow(__FILE__, __LINE__, from, string_size); } } if (((Size)from > string_size) || ((string_size > 0) && ((Size)from == string_size) && (len != 0))) { throw Exception::IndexOverflow(__FILE__, __LINE__, from, string_size); } if (len == EndPos) { len = string_size - from; } if (len > (string_size - from)) { throw Exception::IndexOverflow(__FILE__, __LINE__, (Index)len, string_size); } } void Substring::validateRange_(Index& from, Size& len) const throw(Exception::IndexUnderflow, Exception::IndexOverflow) { Size size = to_ - from_ + 1; // indices may be given as negative arguments: start from the end // -1 therefore means the to bit. if (from < 0) { from = (Index)size + from; // if the values are out of bounds - throw an exception // and leave it... if (from < 0) { throw Exception::IndexUnderflow(__FILE__, __LINE__, from, size); } } if (((Size)from > size) || ((size > 0) && ((Size)from == size))) { throw Exception::IndexOverflow(__FILE__, __LINE__, from, size); } if (len == String::EndPos) { len = size - from; } if (len > (size - from)) { throw Exception::IndexOverflow(__FILE__, __LINE__, (Index)len, size); } } void String::validateCharPtrRange_(Index& from, Size& len, const char* char_ptr) throw(Exception::NullPointer, Exception::IndexUnderflow, Exception::IndexOverflow) { if (char_ptr == 0) { throw Exception::NullPointer(__FILE__, __LINE__); } Size total_len = (Size)strlen(char_ptr); // indices may be given as negative arguments: start from the end // -1 therefore means the to bit. if (from < 0) { from = (Index)total_len + from; // if the values are out of bounds - throw an exception // and leave it... if (from < 0) { throw Exception::IndexUnderflow(__FILE__, __LINE__, from, len); } } if (((Size)from > total_len) || ((total_len > 0) && ((Size)from == total_len))) { throw Exception::IndexOverflow(__FILE__, __LINE__, from, len); } if (len == EndPos) { len = total_len - from; } if (len > (total_len - from)) { throw Exception::IndexOverflow(__FILE__, __LINE__, (Index)len, total_len); } } bool Substring::operator == (const char* char_ptr) const throw(Substring::UnboundSubstring, Exception::NullPointer) { if (bound_ == 0) { throw UnboundSubstring(__FILE__, __LINE__); } if (char_ptr == 0) { throw Exception::NullPointer(__FILE__, __LINE__); } // to prevent compiler warning: if ((signed)strlen(char_ptr) != (to_ - from_ +1)) { return false; } return (bound_->compare(char_ptr, from_, to_ - from_ + 1) == 0); } bool Substring::operator != (const char* char_ptr) const throw(Substring::UnboundSubstring, Exception::NullPointer) { if (bound_ == 0) { throw UnboundSubstring(__FILE__, __LINE__); } if (char_ptr == 0) { throw Exception::NullPointer(__FILE__, __LINE__); } // to prevent compiler warning: if ((signed)strlen(char_ptr) != (to_ - from_ +1)) { return true; } return (bound_->compare(char_ptr, from_, to_ - from_ + 1) != 0); } Substring& Substring::bind(const Substring& s, Index from, Size len) throw(Exception::IndexUnderflow, Exception::IndexOverflow) { s.validateRange_(from, len); bound_ = s.bound_; from += s.from_; to_ = s.from_ + (Index)len - 1; from_ = from; return *this; } void Substring::set(const char* char_ptr, Size size) throw(Substring::UnboundSubstring, Exception::NullPointer, Exception::SizeUnderflow) { if (bound_ == 0) { throw UnboundSubstring(__FILE__, __LINE__); } if (char_ptr == 0) { throw Exception::NullPointer(__FILE__, __LINE__); } if (size == 0) { throw Exception::SizeUnderflow(__FILE__, __LINE__); } if (size == String::EndPos) { bound_->replace(from_, to_ - from_ + 1, string(char_ptr)); } else { bound_->replace(from_, to_ - from_ + 1, char_ptr, size); } } bool Substring::operator == (const Substring& s) const throw(Substring::UnboundSubstring) { if (bound_ == 0 || s.bound_ == 0) { throw UnboundSubstring(__FILE__, __LINE__); } if ((s.to_ - s.from_) != (to_ - from_)) { return false; } return (bound_->compare(s.c_str() + from_, from_, to_ - from_ + 1) == 0); } bool Substring::operator != (const Substring& s) const throw(Substring::UnboundSubstring) { if (bound_ == 0 || s.bound_ == 0) { throw UnboundSubstring(__FILE__, __LINE__); } if ((s.to_ - s.from_) != (to_ - from_)) { return true; } return (bound_->compare(s.c_str() + from_, from_, to_ - from_ + 1) != 0); } Substring String::before(const String& s, Index from) const throw() { Position found = EndPos; if (s != "") { found = (Position)find(s, from); } if (found == 0 || found == EndPos) { return Substring(*this, 0, 0); } return getSubstring(0, found); } Substring String::through (const String& s, Index from) const throw() { Position found = EndPos; if (s != "") { found = (Position)find(s, from); } if (found == EndPos) { return Substring(*this, 0, 0); } return getSubstring(0, found + (Size)s.size()); } Substring String::from(const String& s, Index from) const throw() { if (s == "") { return getSubstring(0); } Size found = (Size)find(s, from); if (found == EndPos) { return Substring(*this, -1, 0); } return getSubstring((Index)found); } Substring String::after(const String& s, Index from) const throw() { if (s == "") { return getSubstring(0); } Position found = (Position)find(s, from); if ((found == EndPos) || (found + s.size() >= size())) { return Substring(*this, -1, 0); } return getSubstring((Index)found + (Index)s.size()); } Substring String::right(Size len) const throw() { // to save calls to size() Size s = (Size)size(); if (len > s) { len = s; } Index from = (Index)s - (Index)len; if (len > 0) { from = (Index)s - (Index)len; } else { if (s > 0) { from = (Index)s - 1; } else { from = 0; } } return Substring(*this, from, len); } // ================================================== Base64 methods char String::B64Chars_[64] = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/' }; int String::Index_64_[128] = { -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,62, -1,-1,-1,63, 52,53,54,55, 56,57,58,59, 60,61,-1,-1, -1,-1,-1,-1, -1, 0, 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,-1, -1,-1,-1,-1, -1,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,-1, -1,-1,-1,-1 }; #define base64val_(c) Index_64_[(unsigned int)(c)] String String::encodeBase64() throw() { Size in_length((Size)this->size()); const char* in = this->c_str(); String out; while (in_length >= 3) { out += B64Chars_[in[0] >> 2]; out += B64Chars_[((in[0] << 4) & 0x30) | (in[1] >> 4)]; out += B64Chars_[((in[1] << 2) & 0x3c) | (in[2] >> 6)]; out += B64Chars_[in[2] & 0x3f]; in_length -= 3; in += 3; } if (in_length > 0) { unsigned char fragment; out += B64Chars_[in[0] >> 2]; fragment = (in[0] << 4) & 0x30; if (in_length > 1) { fragment |= in[1] >> 4; } out += B64Chars_[fragment]; out += (in_length < 2) ? '=' : B64Chars_[(in[1] << 2) & 0x3c]; out += '='; } return out; } String String::decodeBase64() throw() { const char* in = this->c_str(); String out; unsigned char digit4; do { unsigned char digit1 = in[0]; if (digit1 > 127 || base64val_ (digit1) == -1) //-1 == BAD { return String::EMPTY; } unsigned char digit2 = in[1]; if (digit2 > 127 || base64val_ (digit2) == -1) { return String::EMPTY; } unsigned char digit3 = in[2]; if (digit3 > 127 || ((digit3 != '=') && (base64val_ (digit3) == -1))) { return String::EMPTY; } digit4 = in[3]; if (digit4 > 127 || ((digit4 != '=') && (base64val_ (digit4) == -1))) { return String::EMPTY; } in += 4; // digits are already sanity-checked out += (base64val_(digit1) << 2) | (base64val_(digit2) >> 4); if (digit3 != '=') { out += ((base64val_(digit2) << 4) & 0xf0) | (base64val_(digit3) >> 2); if (digit4 != '=') { out += ((base64val_(digit3) << 6) & 0xc0) | base64val_(digit4); } } } while (*in && digit4 != '='); return out; } # ifdef BALL_NO_INLINE_FUNCTIONS # include # endif } // namespace BALL ugene-1.9.8/src/plugins_3rdparty/ball/src/source/CONCEPT/0000755000175000017500000000000011651544310021506 5ustar ilyailyaugene-1.9.8/src/plugins_3rdparty/ball/src/source/CONCEPT/processor.cpp0000644000175000017500000000022711651544326024241 0ustar ilyailya// -*- Mode: C++; tab-width: 2; -*- // vi: set ts=2: // // $Id: processor.C,v 1.2 2002-02-27 12:21:10 sturm Exp $ #include ugene-1.9.8/src/plugins_3rdparty/ball/src/source/CONCEPT/visitor.cpp0000644000175000017500000000022311651544326023715 0ustar ilyailya// -*- Mode: C++; tab-width: 2; -*- // vi: set ts=2: // // $Id: visitor.C,v 1.2 2002-02-27 12:21:11 sturm Exp $ #include ugene-1.9.8/src/plugins_3rdparty/ball/src/source/CONCEPT/predicate.cpp0000644000175000017500000000023311651544326024157 0ustar ilyailya// -*- Mode: C++; tab-width: 2; -*- // vi: set ts=2: // // $Id: predicate.C,v 1.2 2005-10-23 12:02:28 oliver Exp $ // #include ugene-1.9.8/src/plugins_3rdparty/ball/src/source/MATHS/0000755000175000017500000000000011651544310021267 5ustar ilyailyaugene-1.9.8/src/plugins_3rdparty/ball/src/source/MATHS/simpleBox3.cpp0000644000175000017500000000022711651544326024030 0ustar ilyailya// -*- Mode: C++; tab-width: 2; -*- // vi: set ts=2: // // $Id: simpleBox3.C,v 1.2 2003-08-19 16:34:51 amoll Exp $ #include ugene-1.9.8/src/plugins_3rdparty/ball/src/source/MATHS/matrix44.cpp0000644000175000017500000000022411651544326023454 0ustar ilyailya// -*- Mode: C++; tab-width: 2; -*- // vi: set ts=2: // // $Id: matrix44.C,v 1.2 2002-02-27 12:21:27 sturm Exp $ #include ugene-1.9.8/src/plugins_3rdparty/ball/src/source/MATHS/vector4.cpp0000644000175000017500000000022111651544326023363 0ustar ilyailya// -*- Mode: C++; tab-width: 2; -*- // vi: set ts=2: // // $Id: vector4.C,v 1.2 2002-02-27 12:21:29 sturm Exp $ #include ugene-1.9.8/src/plugins_3rdparty/ball/src/source/MATHS/quaternion.cpp0000644000175000017500000000023111651544326024163 0ustar ilyailya// -*- Mode: C++; tab-width: 2; -*- // vi: set ts=2: // // $Id: quaternion.C,v 1.2 2002-02-27 12:21:28 sturm Exp $ #include ugene-1.9.8/src/plugins_3rdparty/ball/src/source/MATHS/surface.cpp0000644000175000017500000000022211651544326023426 0ustar ilyailya// -*- Mode: C++; tab-width: 2; -*- // vi: set ts=2: // // $Id: surface.C,v 1.10 2002-02-27 12:21:28 sturm Exp $ #include ugene-1.9.8/src/plugins_3rdparty/ball/src/source/MATHS/circle3.cpp0000644000175000017500000000022111651544326023321 0ustar ilyailya// -*- Mode: C++; tab-width: 2; -*- // vi: set ts=2: // // $Id: circle3.C,v 1.2 2002-02-27 12:21:26 sturm Exp $ #include ugene-1.9.8/src/plugins_3rdparty/ball/src/source/MATHS/line3.cpp0000644000175000017500000000021511651544326023012 0ustar ilyailya// -*- Mode: C++; tab-width: 2; -*- // vi: set ts=2: // // $Id: line3.C,v 1.2 2002-02-27 12:21:27 sturm Exp $ #include ugene-1.9.8/src/plugins_3rdparty/ball/src/source/MATHS/plane3.cpp0000644000175000017500000000021711651544326023164 0ustar ilyailya// -*- Mode: C++; tab-width: 2; -*- // vi: set ts=2: // // $Id: plane3.C,v 1.2 2002-02-27 12:21:28 sturm Exp $ #include ugene-1.9.8/src/plugins_3rdparty/ball/src/source/MATHS/sphere3.cpp0000644000175000017500000000022111651544326023346 0ustar ilyailya// -*- Mode: C++; tab-width: 2; -*- // vi: set ts=2: // // $Id: sphere3.C,v 1.2 2002-02-27 12:21:28 sturm Exp $ #include ugene-1.9.8/src/plugins_3rdparty/ball/src/source/MATHS/analyticalGeometry.cpp0000644000175000017500000000024711651544326025642 0ustar ilyailya// -*- Mode: C++; tab-width: 2; -*- // vi: set ts=2: // // $Id: analyticalGeometry.C,v 1.2 2002-02-27 12:21:26 sturm Exp $ #include ugene-1.9.8/src/plugins_3rdparty/ball/src/source/MATHS/angle.cpp0000644000175000017500000000021511651544326023066 0ustar ilyailya// -*- Mode: C++; tab-width: 2; -*- // vi: set ts=2: // // $Id: angle.C,v 1.2 2002-02-27 12:21:26 sturm Exp $ #include ugene-1.9.8/src/plugins_3rdparty/ball/src/source/MATHS/vector3.cpp0000644000175000017500000000022111651544326023362 0ustar ilyailya// -*- Mode: C++; tab-width: 2; -*- // vi: set ts=2: // // $Id: vector3.C,v 1.2 2002-02-27 12:21:29 sturm Exp $ #include ugene-1.9.8/src/plugins_3rdparty/ball/src/source/MATHS/common.cpp0000644000175000017500000000021711651544326023272 0ustar ilyailya// -*- Mode: C++; tab-width: 2; -*- // vi: set ts=2: // // $Id: common.C,v 1.2 2005-12-23 17:02:42 amoll Exp $ #include ugene-1.9.8/src/plugins_3rdparty/ball/src/BallPlugin.h0000644000175000017500000000204711651544325021326 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef BALLPLUGIN_H #define BALLPLUGIN_H #include namespace U2 { class BallPlugin : public Plugin { Q_OBJECT public: BallPlugin(); }; } // namespace #endif // BALLPLUGIN_H ugene-1.9.8/src/plugins_3rdparty/ball/transl/0000755000175000017500000000000011651544310017627 5ustar ilyailyaugene-1.9.8/src/plugins_3rdparty/ball/transl/russian.ts0000644000175000017500000000124611651544326021675 0ustar ilyailya U2::BallPlugin BALL A port of BALL framework for molecular surface calculation Перенесённый фреймворк BALL для вычисления молекулярной поверхности ugene-1.9.8/src/plugins_3rdparty/ball/transl/czech.ts0000644000175000017500000000100311651544326021274 0ustar ilyailya U2::BallPlugin BALL A port of BALL framework for molecular surface calculation ugene-1.9.8/src/plugins_3rdparty/ball/transl/english.ts0000644000175000017500000000100311651544326021631 0ustar ilyailya U2::BallPlugin BALL A port of BALL framework for molecular surface calculation ugene-1.9.8/src/plugins_3rdparty/bowtie/0000755000175000017500000000000011651544311016704 5ustar ilyailyaugene-1.9.8/src/plugins_3rdparty/bowtie/bowtie.pri0000644000175000017500000000033711651544326020722 0ustar ilyailya# include (bowtie.pri) DEFINES+= QT_DLL "BOWTIE_VERSION=\"\"0.12.7\"\" PLUGIN_ID=bowtie PLUGIN_NAME=Bowtie aligner PLUGIN_VENDOR=Unipro CONFIG += warn_off include( ../../ugene_plugin_common.pri ) ugene-1.9.8/src/plugins_3rdparty/bowtie/src/0000755000175000017500000000000011651544311017473 5ustar ilyailyaugene-1.9.8/src/plugins_3rdparty/bowtie/src/BowtieConstants.h0000644000175000017500000000165611651544326023010 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _BOWTIE_CONSTANTS_H_ #define _BOWTIE_CONSTANTS_H_ #endif //_BOWTIE_CONSTANTS_H_ugene-1.9.8/src/plugins_3rdparty/bowtie/src/BowtieAdapter.h0000644000175000017500000000266311651544326022413 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_BOWTIE_ADAPTER_H_ #define _U2_BOWTIE_ADAPTER_H_ #include #include namespace U2 { class MAlignment; class TaskStateInfo; class BowtieReadsReader; class BowtieReadsWriter; class BowtieAdapter : public QObject { Q_OBJECT public: static void doBowtie(const QString& ebwtFileName, BowtieReadsReader* reader, BowtieReadsWriter* writer, const U2::GUrl& resultUrl, TaskStateInfo& ti); static void doBowtieWorker(int id, TaskStateInfo& ti); static void doBowtieBuild(const QString& infile, const QString& outfile, TaskStateInfo& ti ); }; }//namespace #endif ugene-1.9.8/src/plugins_3rdparty/bowtie/src/BowtieIOAdapter.cpp0000644000175000017500000002175511651544326023201 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "stdint.h" #include #include #include #include #include #include "BowtieIOAdapter.h" #include "BowtieContext.h" #include /************************************************************************/ /* BowtieUrlReadsReader */ /************************************************************************/ BowtieUrlReadsReader::BowtieUrlReadsReader(const QList& dnaList) { initOk = this->reader.init(dnaList); } bool BowtieUrlReadsReader::isEnd() { if (!initOk) { return true; } return !reader.hasNext(); } U2::DNASequence *BowtieUrlReadsReader::read() { BowtieContext::getContext()->ti.progress = reader.getProgress(); return reader.getNextSequenceObject(); } /************************************************************************/ /* BowtieUrlReadsWriter */ /************************************************************************/ BowtieUrlReadsWriter::BowtieUrlReadsWriter(const U2::GUrl& resultFile, const QString& refName, int refLength) :seqWriter(resultFile, refName, refLength) { //do nothing } void BowtieUrlReadsWriter::setRefSeqLength(int refLength) { seqWriter.setRefSeqLength(refLength); } void BowtieUrlReadsWriter::write(const U2::DNASequence& seq, int offset) { seqWriter.writeNextAlignedRead(offset, seq); } void BowtieUrlReadsWriter::close() { seqWriter.close(); } /************************************************************************/ /* BowtieDbiReadsWriter */ /************************************************************************/ const qint64 BowtieDbiReadsWriter::readBunchSize = 10000; inline void checkOperationStatus(const U2::U2OpStatus &status) { if (status.hasError()) { throw status.getError(); } } BowtieDbiReadsWriter::BowtieDbiReadsWriter(const U2::GUrl& dbiFilePath, const QString& refName) { //TODO: support several assemblies. dbiHandle = QSharedPointer(new U2::DbiHandle("SQLiteDbi", dbiFilePath.getURLString(), true, status)); checkOperationStatus(status); sqliteDbi = dbiHandle->dbi; wDbi = sqliteDbi->getAssemblyDbi(); sqliteDbi->getObjectDbi()->createFolder("/", status); checkOperationStatus(status); assembly.visualName = refName; U2::U2AssemblyReadsImportInfo importInfo; wDbi->createAssemblyObject(assembly, "/", NULL, importInfo, status); checkOperationStatus(status); } void BowtieDbiReadsWriter::write(const U2::DNASequence& seq, int offset) { U2::U2AssemblyRead read(new U2::U2AssemblyReadData()); read->name = seq.getName().toAscii(); read->leftmostPos = offset; read->effectiveLen = seq.length(); read->readSequence = seq.constSequence(); read->quality = seq.hasQualityScores() ? seq.quality.qualCodes : ""; read->flags = U2::None; read->cigar.append(U2::U2CigarToken(U2::U2CigarOp_M, seq.length())); reads.append(read); if (reads.size() >= readBunchSize) { U2::BufferedDbiIterator readsIterator(reads); wDbi->addReads(assembly.id, &readsIterator, status); checkOperationStatus(status); reads.clear(); } } void BowtieDbiReadsWriter::close() { if (reads.size() > 0) { U2::BufferedDbiIterator readsIterator(reads); wDbi->addReads(assembly.id, &readsIterator, status); checkOperationStatus(status); reads.clear(); } U2::U2AssemblyPackStat packStatus; wDbi->pack(assembly.id, packStatus, status); checkOperationStatus(status); } /************************************************************************/ /* DNASequencesPatternSource */ /************************************************************************/ DNASequencesPatternSource::DNASequencesPatternSource( uint32_t seed, U2::BowtieReadsReader* reader ) : PatternSource(seed) { this->reader = reader; } void DNASequencesPatternSource::nextReadImpl( ReadBuf& r, uint32_t& patid ) { U2::DNASequence *dna; { QMutexLocker lock(&mutex); patid = readCnt_; if (reader->isEnd()) { return; } ++readCnt_; dna = new U2::DNASequence(*reader->read()); } r.clearAll(); BowtieContext::Search* ctx = BowtieContext::getSearchContext(); bool doquals = false; //TODO: quals int nameLen = dna->getName().length(); strcpy(r.nameBuf, dna->getName().toAscii().constData()); _setBegin(r.name, r.nameBuf); _setLength(r.name, nameLen); if(nameLen == 0) { itoa10(readCnt_, r.nameBuf); _setBegin(r.name, r.nameBuf); nameLen = strlen(r.nameBuf); _setLength(r.name, nameLen); } const char* row = dna->seq.constData(); const int seqLen = dna->length(); if(seqLen+1 > 1024) { tooManySeqChars(r.name); } //TODO: trim; r.trimmed3 = 0; r.trimmed5 = 0; r.color = ctx->color; //TODO: if(color) ... for(int i=0;iquality.isEmpty()) { switch(dna->quality.type) { case U2::DnaQualityType_Solexa: for(int i=0;iquality.getValue(i)+33); break; case U2::DNAQualityType_Sanger: for(int i=0;iquality.getValue(i)+33; break; default: for(int i=0;i* refnames /*= NULL*/ ) :HitSink(out, PASS_HIT_DUMPS, onePairFile, sampleMax, table, refnames), writer(_writer) { //do nothing } void MAlignmentHitSink::append( ostream& o, const Hit& h ) { Q_UNUSED(o); QMutexLocker lock(&mutex); QByteArray name(h.patName.data_begin, length(h.patName)); QByteArray sequence; QByteArray quality; const int seqLen = length(h.patSeq); for(int i=0; i < seqLen; i++) { char qryChar = (h.fw ? h.patSeq[i] : h.patSeq[seqLen-i-1]); char qualChar = (h.fw ? h.quals[i] : h.quals[seqLen-i-1]); sequence.append(qryChar); quality.append(qualChar); } if(!h.fw) { U2::DNAAlphabet *al = U2::AppContext::getDNAAlphabetRegistry()->findAlphabet(sequence); if(al == NULL) { throw new BowtieException("Can't find alphabet for sequence"); } U2::DNATranslation* tr = U2::AppContext::getDNATranslationRegistry()->lookupComplementTranslation(al); if(tr == NULL) { throw new BowtieException("Can't translation for alphabet"); } U2::TextUtils::translate(tr->getOne2OneMapper(), sequence.data(), sequence.length()); } U2::DNASequence dna(name, sequence); int offset = h.h.second; dna.quality.qualCodes = quality; writer->write(dna, offset); (*BowtieContext::getContext()->numHitsOverall)++; // if(BowtieContext::getSearchContext()->sortAlignment) { // int count = rowList.count(); // bool indexFound = false; // for(int i=0;i row.getCoreStart()) { // rowList.insert(i, row); // indexFound = true; // break; // } // } // if(!indexFound) rowList.append(row); // } else { // rowList.append(row); // } } void MAlignmentHitSink::commitResultMA() { writer->close(); // for(int i=0;i * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _BOWTIE_CONTEXT_H_ #define _BOWTIE_CONTEXT_H_ #include #include #include #include #include "alphabet.h" #include "formats.h" #include "bitset.h" #include "hit.h" #include "log.h" #ifdef _CRTDBG_MAP_ALLOC //tested only on windows #define _CRTDBG_MAPALLOC #include #include #include #ifdef _DEBUG #define DEBUG_NEW new(_NORMAL_BLOCK, __FILE__, __LINE__) #define new DEBUG_NEW #endif #endif using namespace std; using namespace seqan; #define BOWTIE_CONTEXT_ID "bowtie" class BowtieContext; class BitPairReference; class PartialAlignmentManager; template class Ebwt; class BowtieException: public std::exception { public: BowtieException(std::string str) {msg = str;} ~BowtieException() throw() {}; virtual const char* what() const throw() { return msg.c_str(); } private: std::string msg; }; class BowtieContext : public U2::TLSContext { public: struct Search { Search() : suppressOuts(64) {} void resetOptions(); vector mates1; // mated reads (first mate) vector mates2; // mated reads (second mate) vector mates12; // mated reads (1st/2nd interleaved in 1 file) string adjustedEbwtFileBase; bool verbose; // be talkative bool startVerbose; // be talkative at startup bool quiet; // print nothing but the alignments int sanityCheck; // enable expensive sanity checks int format; // default read format is FASTQ string origString; // reference text, or filename(s) int seed; // srandom() seed int timing; // whether to report basic timing data bool allHits; // for multihits, report just one bool rangeMode; // report BWT ranges instead of ref locs int showVersion; // just print version and quit? int ipause; // pause before maching? uint32_t qUpto; // max # of queries to read int trim5; // amount to trim from 5' end int trim3; // amount to trim from 3' end int reportOpps; // whether to report # of other mappings int offRate; // keep default offRate int isaRate; // keep default isaRate int mismatches; // allow 0 mismatches by default char *patDumpfile; // filename to dump patterns to bool solexaQuals; // quality strings are solexa quals, not phred, and subtract 64 (not 33) bool phred64Quals; // quality chars are phred, but must subtract 64 (not 33) bool integerQuals; // quality strings are space-separated strings of integers, not ASCII int maqLike; // do maq-like searching int seedLen; // seed length (changed in Maq 0.6.4 from 24) int seedMms; // # mismatches allowed in seed (maq's -n) int qualThresh; // max qual-weighted hamming dist (maq's -e) int maxBtsBetter; // max # backtracks allowed in half-and-half mode int maxBts; // max # backtracks allowed in half-and-half mode int nthreads; // number of pthreads operating concurrently output_types outType; // style of output bool randReadsNoSync; // true -> generate reads from per-thread random source int numRandomReads; // # random reads (see Random*PatternSource in pat.h) int lenRandomReads; // len of random reads (see Random*PatternSource in pat.h) bool noRefNames; // true -> print reference indexes; not names string dumpAlBase; // basename of same-format files to dump aligned reads to string dumpUnalBase; // basename of same-format files to dump unaligned reads to string dumpMaxBase; // basename of same-format files to dump reads with more than -m valid alignments to uint32_t khits; // number of hits per read; >1 is much slower uint32_t mhits; // don't report any hits if there are > mhits bool better; // true -> guarantee alignments from best possible stratum bool strata; // true -> don't stop at stratum boundaries bool refOut; // if true, alignments go to per-ref files int partitionSz; // output a partitioning key in first field bool noMaqRound; // true -> don't round quals to nearest 10 like maq bool useSpinlock; // false -> don't use of spinlocks even if they're #defines bool fileParallel; // separate threads read separate input files in parallel bool useShmem; // use shared memory to hold the index bool useMm; // use memory-mapped files to hold the index bool mmSweep; // sweep through memory-mapped files immediately after mapping bool stateful; // use stateful aligners uint32_t prefetchWidth; // number of reads to process in parallel w/ --stateful uint32_t minInsert; // minimum insert size (Maq = 0, SOAP = 400) uint32_t maxInsert; // maximum insert size (Maq = 250, SOAP = 600) bool mate1fw; // -1 mate aligns in fw orientation on fw strand bool mate2fw; // -2 mate aligns in rc orientation on fw strand bool mateFwSet; // true -> user set --ff/--fr/--rf uint32_t mixedThresh; // threshold for when to switch to paired-end mixed mode (see aligner.h) uint32_t mixedAttemptLim; // number of attempts to make in "mixed mode" before giving up on orientation bool dontReconcileMates; // suppress pairwise all-versus-all way of resolving mates uint32_t cacheLimit; // ranges w/ size > limit will be cached uint32_t cacheSize; // # words per range cache int offBase; // offsets are 0-based by default, but configurable bool tryHard; // set very high maxBts, mixedAttemptLim uint32_t skipReads; // # reads/read pairs to skip bool nofw; // don't align fw orientation of read bool norc; // don't align rc orientation of read bool strandFix; // attempt to fix strand bias bool randomizeQuals; // randomize quality values bool stats; // print performance stats int chunkPoolMegabytes; // max MB to dedicate to best-first search frames per thread int chunkSz; // size of single chunk disbursed by ChunkPool bool chunkVerbose; // have chunk allocator output status messages? bool recal; int recalMaxCycle; int recalMaxQual; int recalQualShift; bool useV1; bool reportSe; const char * refMapFile; // file containing a map from index coordinates to another coordinate system const char * annotMapFile; // file containing a map from reference coordinates to annotations size_t fastaContLen; size_t fastaContFreq; bool hadoopOut; // print Hadoop status and summary messages bool fuzzy; bool fullRef; bool samNoHead; // don't print any header lines in SAM output bool samNoSQ; // don't print @SQ header lines bool color; // true -> inputs are colorspace bool colorExEnds; // true -> nucleotides on either end of decoded cspace alignment should be excluded string rgs; // SAM outputs for @RG header line int snpPhred; // probability of SNP, for scoring colorspace alignments Bitset suppressOuts; // output fields to suppress bool sampleMax; // whether to report a random alignment when maxed-out via -m/-M int defaultMapq; // default mapping quality to print in SAM mode bool colorSeq; // true -> show colorspace alignments as colors, not decoded bases bool colorQual; // true -> show colorspace qualities as original quals, not decoded quals bool printCost; // true -> print stratum and cost bool showSeed; vector qualities; vector qualities1; vector qualities2; MUTEX_T gLock; PairedPatternSource* exactSearch_patsrc; HitSink* exactSearch_sink; Ebwt >* exactSearch_ebwt; vector >* exactSearch_os; BitPairReference* exactSearch_refs; PairedPatternSource* mismatchSearch_patsrc; HitSink* mismatchSearch_sink; Ebwt >* mismatchSearch_ebwtFw; Ebwt >* mismatchSearch_ebwtBw; vector >* mismatchSearch_os; SyncBitset* mismatchSearch_doneMask; SyncBitset* mismatchSearch_hitMask; BitPairReference* mismatchSearch_refs; PairedPatternSource* seededQualSearch_patsrc; HitSink* seededQualSearch_sink; Ebwt >* seededQualSearch_ebwtFw; Ebwt >* seededQualSearch_ebwtBw; vector >* seededQualSearch_os; SyncBitset* seededQualSearch_doneMask; SyncBitset* seededQualSearch_hitMask; PartialAlignmentManager* seededQualSearch_pamFw; PartialAlignmentManager* seededQualSearch_pamRc; int seededQualSearch_qualCutoff; BitPairReference* seededQualSearch_refs; PairedPatternSource* twoOrThreeMismatchSearch_patsrc; HitSink* twoOrThreeMismatchSearch_sink; Ebwt >* twoOrThreeMismatchSearch_ebwtFw; Ebwt >* twoOrThreeMismatchSearch_ebwtBw; vector >* twoOrThreeMismatchSearch_os; SyncBitset* twoOrThreeMismatchSearch_doneMask; SyncBitset* twoOrThreeMismatchSearch_hitMask; bool twoOrThreeMismatchSearch_two; BitPairReference* twoOrThreeMismatchSearch_refs; string refName; int refLength; bool sortAlignment; //Sort result alignment by offset } search; // Build struct Build { void resetOptions(); bool verbose; int sanityCheck; int format; uint32_t bmax; uint32_t bmaxMultSqrt; uint32_t bmaxDivN; int dcv; int noDc; int entireSA; int seed; int showVersion; bool doubleEbwt; // Ebwt parameters int32_t lineRate; int32_t linesPerSide; int32_t offRate; int32_t ftabChars; int bigEndian; bool nsToAs; bool autoMem; bool packed; bool writeRef; bool justRef; int reverseType; bool color; bool secondEbwtRound; /// Array of Colbourn and Ling calculated difference covers up to /// r = 16 (maxV = 5953) struct sampleEntry { uint32_t maxV; uint32_t numSamples; uint32_t samples[128]; }; sampleEntry clDCs[16]; bool clDCs_calced; /// have clDCs been calculated? } build; struct BowtieWorkerArg { int id; void *(*start_routine) (void *); void *arg; }; struct Worker { QSemaphore start; QSemaphore stop; }; // 5 64-element buckets for bucket-sorting A, C, G, T, $ uint32_t bkts[4][4 * 1024 * 1024]; SyncLogger glog; U2::TaskStateInfo &ti; int* numHitsOverall; QList jobList; QList workerList; volatile bool hasError; void runWorker(int* id, void *(*start_routine) (void *), void *arg); void joinWorker(int id); BowtieContext(U2::TaskStateInfo& stateInfo, int nThreads); ~BowtieContext(); static BowtieContext* getContext(); static BowtieContext::Search* getSearchContext(); static BowtieContext::Build* getBuildContext(); static bool isCanceled(); static void verbose(const std::string& s); }; #endif //_BOWTIE_CONTEXT_H_ ugene-1.9.8/src/plugins_3rdparty/bowtie/src/BowtieReadsIOUtils.h0000644000175000017500000000430411651544326023334 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _BOWTIE_IO_READS_READER_H_ #define _BOWTIE_IO_READS_READER_H_ #include #include namespace U2 { /************************************************************************/ /* Abstract short reads reader and writer */ /************************************************************************/ class BowtieReadsReader { public: virtual DNASequence *read()=0; virtual bool isEnd()=0; }; class BowtieReadsWriter { public: virtual void write(const DNASequence& seq, int offset)=0; virtual void close()=0; }; /************************************************************************/ /* Abstract container for store in QVartiant */ /************************************************************************/ class BowtieReadsReaderContainer { public: BowtieReadsReaderContainer() : reader(NULL) { } BowtieReadsReaderContainer(BowtieReadsReader* reader) { this->reader = reader; } BowtieReadsReader* reader; }; class BowtieReadsWriterContainer { public: BowtieReadsWriterContainer() : writer(NULL) {} BowtieReadsWriterContainer(BowtieReadsWriter* writer) { this->writer = writer; } BowtieReadsWriter* writer; }; } //namespace Q_DECLARE_METATYPE( U2::BowtieReadsReaderContainer ) Q_DECLARE_METATYPE( U2::BowtieReadsWriterContainer ) #endif //_BOWTIE_IO_READS_READER_H_ugene-1.9.8/src/plugins_3rdparty/bowtie/src/BowtieSettingsWidget.cpp0000644000175000017500000000476711651544326024341 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "BowtieSettingsWidget.h" #include "BowtieTask.h" namespace U2 { BowtieSettingsWidget::BowtieSettingsWidget(QWidget* parent) : DnaAssemblyAlgorithmMainWidget(parent) { setupUi(this); layout()->setContentsMargins(0,0,0,0); } QMap BowtieSettingsWidget::getDnaAssemblyCustomSettings() { QMap settings; switch(mismatchesComboBox->currentIndex()) { case 0: settings.insert(BowtieTask::OPTION_N_MISMATCHES, mismatchesSpinBox->value()); break; case 1: settings.insert(BowtieTask::OPTION_V_MISMATCHES, mismatchesSpinBox->value()); break; } if(maqerrCheckBox->isChecked()) { settings.insert(BowtieTask::OPTION_MAQERR, maqerrSpinBox->value()); } if(maxbtsCheckBox->isChecked()) { settings.insert(BowtieTask::OPTION_MAXBTS, maxbtsSpinBox->value()); } if(seedlenCheckBox->isChecked()) { settings.insert(BowtieTask::OPTION_SEED_LEN, seedlenSpinBox->value()); } if(chunckmbsCheckBox->isChecked()) { settings.insert(BowtieTask::OPTION_CHUNKMBS, chunkmbsSpinBox->value()); } if(seedCheckBox->isChecked()) { settings.insert(BowtieTask::OPTION_SEED, seedlenSpinBox->value()); } settings.insert(BowtieTask::OPTION_NOFW, nofwCheckBox->isChecked()); settings.insert(BowtieTask::OPTION_NORC, norcCheckBox->isChecked()); settings.insert(BowtieTask::OPTION_TRYHARD, tryhardCheckBox->isChecked()); settings.insert(BowtieTask::OPTION_BEST, bestCheckBox->isChecked()); settings.insert(BowtieTask::OPTION_ALL, allCheckBox->isChecked()); settings.insert(BowtieTask::OPTION_NOMAQROUND, nomaqroundCheckBox->isChecked()); return settings; } } //namespace ugene-1.9.8/src/plugins_3rdparty/bowtie/src/BowtieWorker.h0000644000175000017500000001127511651544326022303 0ustar ilyailya/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2011 UniPro * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_BOWTIE_WORKER_H_ #define _U2_BOWTIE_WORKER_H_ #include #include #include "BowtieTask.h" #include "BowtieReadsIOUtils.h" namespace U2 { namespace LocalWorkflow { class BowtieCommunicationChanelReader : public BowtieReadsReader { public: BowtieCommunicationChanelReader(CommunicationChannel* reads); DNASequence *read(); bool isEnd(); private: CommunicationChannel* reads; }; class BowtieMAlignmentWriter : public BowtieReadsWriter { public: BowtieMAlignmentWriter(); void write(const DNASequence& seq, int offset); void close(); MAlignment& getResult(); private: MAlignment result; }; class BowtiePrompter : public PrompterBase { Q_OBJECT public: BowtiePrompter(Actor* p = 0) : PrompterBase(p) {} protected: QString composeRichDoc(); }; class BowtieWorker : public BaseWorker { Q_OBJECT public: BowtieWorker(Actor* a) : BaseWorker(a, false), reads(NULL), ebwt(NULL), output(NULL), reader(NULL), writer(NULL) {} virtual void init() ; virtual bool isReady(); virtual Task* tick() ; virtual bool isDone() ; virtual void cleanup(); private slots: void sl_taskFinished(); protected: CommunicationChannel *reads, *ebwt, *output; BowtieReadsReader* reader; BowtieReadsWriter* writer; QString resultName,transId; DnaAssemblyToRefTaskSettings settings; }; class BowtieWorkerFactory : public DomainFactory { public: static const QString ACTOR_ID; static void init(); BowtieWorkerFactory() : DomainFactory(ACTOR_ID) {} virtual Worker* createWorker(Actor* a) {return new BowtieWorker(a);} }; /************************************************************************/ /* Bowtie build */ /************************************************************************/ class BowtieBuildPrompter : public PrompterBase { Q_OBJECT public: BowtieBuildPrompter(Actor* p = 0) : PrompterBase(p) {} protected: QString composeRichDoc(); }; class BowtieBuildWorker : public BaseWorker { Q_OBJECT public: BowtieBuildWorker(Actor* a) : BaseWorker(a), output(NULL), done(false) {} virtual void init() ; virtual bool isReady(); virtual Task* tick() ; virtual bool isDone() ; virtual void cleanup() {} private slots: void sl_taskFinished(); protected: CommunicationChannel *output; QString resultName,transId; GUrl refSeqUrl; GUrl ebwtUrl; bool done; }; class BowtieBuildWorkerFactory : public DomainFactory { public: static const QString ACTOR_ID; static void init(); BowtieBuildWorkerFactory() : DomainFactory(ACTOR_ID) {} virtual Worker* createWorker(Actor* a) {return new BowtieBuildWorker(a);} }; /************************************************************************/ /* Bowtie index reader */ /************************************************************************/ class BowtieIndexReaderPrompter : public PrompterBase { Q_OBJECT public: BowtieIndexReaderPrompter(Actor* p = 0) : PrompterBase(p) {} protected: QString composeRichDoc(); }; class BowtieIndexReaderWorker : public BaseWorker { Q_OBJECT public: BowtieIndexReaderWorker(Actor* a) : BaseWorker(a), output(NULL), done(false) {} virtual void init() ; virtual bool isReady(); virtual Task* tick() ; virtual bool isDone() ; virtual void cleanup() {} private slots: void sl_taskFinished(); protected: CommunicationChannel *output; QString resultName,transId; GUrl ebwtUrl; bool done; }; class BowtieIndexReaderWorkerFactory : public DomainFactory { public: static const QString ACTOR_ID; static void init(); BowtieIndexReaderWorkerFactory() : DomainFactory(ACTOR_ID) {} virtual Worker* createWorker(Actor* a) {return new BowtieIndexReaderWorker(a);} }; } // Workflow namespace } // U2 namespace #endif // BOWTIE_WORKER ugene-1.9.8/src/plugins_3rdparty/bowtie/src/bowtie/0000755000175000017500000000000011651544311020764 5ustar ilyailyaugene-1.9.8/src/plugins_3rdparty/bowtie/src/bowtie/binary_sa_search.h0000644000175000017500000000520511651544326024441 0ustar ilyailya#ifndef BINARY_SA_SEARCH_H_ #define BINARY_SA_SEARCH_H_ #include #include #include #include "alphabet.h" #include "assert_helpers.h" /** * Do a binary search using the suffix of 'host' beginning at offset * 'qry' as the query and 'sa' as an already-lexicographically-sorted * list of suffixes of host. 'sa' may be all suffixes of host or just * a subset. Returns the index in sa of the smallest suffix of host * that is larger than qry, or length(sa) if all suffixes of host are * less than qry. * * We use the Manber and Myers optimization of maintaining a pair of * counters for the longest lcp observed so far on the left- and right- * hand sides and using the min of the two as a way of skipping over * characters at the beginning of a new round. * * Returns 0xffffffff if the query suffix matches an element of sa. */ template inline uint32_t binarySASearch(const TStr& host, uint32_t qry, const String& sa) { uint32_t lLcp = 0, rLcp = 0; // greatest observed LCPs on left and right uint32_t l = 0, r = length(sa)+1; // binary-search window uint32_t hostLen = length(host); while(true) { assert_gt(r, l); uint32_t m = (l+r) >> 1; if(m == l) { // Binary-search window has closed: we have an answer if(m > 0 && sa[m-1] == qry) return 0xffffffff; // qry matches assert_leq(m, length(sa)); return m; // Return index of right-hand suffix } assert_gt(m, 0); uint32_t suf = sa[m-1]; if(suf == qry) return 0xffffffff; // query matches an elt of sa uint32_t lcp = min(lLcp, rLcp); #ifndef NDEBUG if(prefix(suffix(host, qry), lcp) != prefix(suffix(host, suf), lcp)) { assert(0); } #endif // Keep advancing lcp, but stop when query mismatches host or // when the counter falls off either the query or the suffix while(suf+lcp < hostLen && qry+lcp < hostLen && host[suf+lcp] == host[qry+lcp]) { lcp++; } // Fell off the end of either the query or the sa elt? bool fell = (suf+lcp == hostLen || qry+lcp == hostLen); if((fell && qry+lcp == hostLen) || (!fell && host[suf+lcp] < host[qry+lcp])) { // Query is greater than sa elt l = m; // update left bound lLcp = max(lLcp, lcp); // update left lcp } else if((fell && suf+lcp == hostLen) || (!fell && host[suf+lcp] > host[qry+lcp])) { // Query is less than sa elt r = m; // update right bound rLcp = max(rLcp, lcp); // update right lcp } else { assert(false); // Must be one or the other! } } // Shouldn't get here assert(false); return 0xffffffff; } #endif /*BINARY_SA_SEARCH_H_*/ ugene-1.9.8/src/plugins_3rdparty/bowtie/src/bowtie/ebwt_search.cpp0000644000175000017500000017705211651544326024000 0ustar ilyailya#include "BowtieConstants.h" #include "BowtieAdapter.h" #include "BowtieIOAdapter.h" #include "BowtieContext.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "alphabet.h" #include "assert_helpers.h" #include "endian_swap.h" #include "ebwt.h" #include "formats.h" #include "sequence_io.h" #include "tokenize.h" #include "hit.h" #include "pat.h" #include "bitset.h" #include "threading.h" #include "range_cache.h" #include "refmap.h" #include "annot.h" #include "aligner.h" #include "aligner_0mm.h" #include "aligner_1mm.h" #include "aligner_23mm.h" #include "aligner_seed_mm.h" #include "aligner_metrics.h" #include "sam.h" #ifdef CHUD_PROFILING #include #endif using namespace std; using namespace seqan; void prepareSearchOptions() { BowtieContext::Search* ctx = BowtieContext::getSearchContext(); //ctx->resetOptions(); bool paired = ctx->mates1.size() > 0 || ctx->mates2.size() > 0 || ctx->mates12.size() > 0; if(ctx->rangeMode) { // Tell the Ebwt loader to ignore the suffix-array portion of // the index. We don't need it because the user isn't asking // for bowtie to report reference positions (just matrix // ranges). ctx->offRate = 32; } if(!ctx->maqLike && ctx->mismatches == 3) { // Much faster than normal 3-mismatch mode ctx->stateful = true; } // if(ctx->mates1.size() != ctx->mates2.size()) { // ostringstream err; // err << "Error: " << mates1.size() << " mate files/sequences were specified with -1, but " << mates2.size() << endl // << "mate files/sequences were specified with -2. The same number of mate files/" << endl // << "sequences must be specified with -1 and -2." << endl; // throw BowtieException(err.str()); // } // if(ctx->qualities.size() && ctx->format != FASTA) { // ostringstream err; // err << "Error: one or more quality files were specified with -Q but -f was not" << endl // << "enabled. -Q works only in combination with -f and -C." << endl; // throw BowtieException(err.str()); // } // if(qualities.size() && !color) { // ostringstream err; // err << "Error: one or more quality files were specified with -Q but -C was not" << endl // << "enabled. -Q works only in combination with -f and -C." << endl; // throw BowtieException(err.str()); // } // if(qualities1.size() && format != FASTA) { // ostringstream err; // err << "Error: one or more quality files were specified with --Q1 but -f was not" << endl // << "enabled. --Q1 works only in combination with -f and -C." << endl; // throw BowtieException(err.str()); // } // if(qualities1.size() && !color) { // ostringstream err; // err << "Error: one or more quality files were specified with --Q1 but -C was not" << endl // << "enabled. --Q1 works only in combination with -f and -C." << endl; // throw BowtieException(err.str()); // } // if(qualities2.size() && format != FASTA) { // ostringstream err; // err << "Error: one or more quality files were specified with --Q2 but -f was not" << endl // << "enabled. --Q2 works only in combination with -f and -C." << endl; // throw BowtieException(err.str()); // } // if(qualities2.size() && !color) { // ostringstream err; // err << "Error: one or more quality files were specified with --Q2 but -C was not" << endl // << "enabled. --Q2 works only in combination with -f and -C." << endl; // throw BowtieException(err.str()); // } // if(qualities1.size() > 0 && mates1.size() != qualities1.size()) { // ostringstream err; // err << "Error: " << mates1.size() << " mate files/sequences were specified with -1, but " << qualities1.size() << endl // << "quality files were specified with --Q1. The same number of mate and quality" << endl // << "files must sequences must be specified with -1 and --Q1." << endl; // throw BowtieException(err.str()); // } // if(qualities2.size() > 0 && mates2.size() != qualities2.size()) { // ostringstream err; err << "Error: " << mates2.size() << " mate files/sequences were specified with -2, but " << qualities2.size() << endl // << "quality files were specified with --Q2. The same number of mate and quality" << endl // << "files must sequences must be specified with -2 and --Q2." << endl; // throw BowtieException(err.str()); // } // Check for duplicate mate input files // if(format != CMDLINE) { // ostringstream err; // for(size_t i = 0; i < mates1.size(); i++) { // for(size_t j = 0; j < mates2.size(); j++) { // if(mates1[i] == mates2[j] && !quiet) { // err << "Warning: Same mate file \"" << mates1[i] << "\" appears as argument to both -1 and -2" << endl; // } // } // } // } if(ctx->tryHard) { // Increase backtracking limit to huge number ctx->maxBts = ctx->maxBtsBetter = INT_MAX; // Increase number of paired-end scan attempts to huge number ctx->mixedAttemptLim = UINT_MAX; } if(!ctx->stateful && ctx->sampleMax) { ctx->stateful = true; } if(ctx->strata && !ctx->stateful) { ostringstream err; err << "--strata must be combined with --best" << endl; throw BowtieException(err.str()); } if(ctx->strata && !ctx->allHits && ctx->khits == 1 && ctx->mhits == 0xffffffff) { ostringstream err; err << "--strata has no effect unless combined with -k, -m or -a" << endl; throw BowtieException(err.str()); } if(ctx->fuzzy && (!ctx->stateful && !paired)) { ostringstream err; err << "--fuzzy must be combined with --best or paired-end alignment" << endl; throw BowtieException(err.str()); } // If both -s and -u are used, we need to adjust qUpto accordingly // since it uses patid to know if we've reached the -u limit (and // patids are all shifted up by skipReads characters) if(ctx->qUpto + ctx->skipReads > ctx->qUpto) { ctx->qUpto += ctx->skipReads; } if(ctx->useShmem && ctx->useMm && !ctx->quiet) { //cerr << "Warning: --shmem overrides --mm..." << endl; ctx->useMm = false; } if(ctx->snpPhred <= 10 && ctx->color && !ctx->quiet) { //cerr << "Warning: the colorspace SNP penalty (--snpphred) is very low: " << ctx->snpPhred << endl; } // if(format == INPUT_CHAIN) { // bool error = false; // ostringstream err; // if(!stateful) { // err << "Error: --chainin must be combined with --best; aborting..." << endl; // error = true; // } // if(paired) { // err << "Error: --chainin cannot be combined with paired-end alignment; aborting..." << endl; // error = true; // } // if(error) throw BowtieException(err.str()); // } // if(ctx->outType == OUTPUT_CHAIN) { // bool error = false; // ostringstream err; // if(refOut) { // err << "Error: --chainout is not compatible with --refout; aborting..." << endl; // error = true; // } // if(!stateful) { // err << "Error: --chainout must be combined with --best; aborting..." << endl; // error = true; // } // if(paired) { // err << "Error: --chainout cannot be combined with paired-end alignment; aborting..." << endl; // error = true; // } // if(error) throw BowtieException(err.str()); // } // if(outType == OUTPUT_SAM && refOut) { // ostringstream err; err << "Error: --refout cannot be combined with -S/--sam" << endl; // throw BowtieException(err.str()); // } if(!ctx->mateFwSet) { if(ctx->color) { // Set colorspace default (--ff) ctx->mate1fw = true; ctx->mate2fw = true; } else { // Set nucleotide space default (--fr) ctx->mate1fw = true; ctx->mate2fw = false; } } // if(outType != OUTPUT_FULL && suppressOuts.count() > 0 && !quiet) { // cerr << "Warning: Ignoring --suppress because output type is not default." << endl; // cerr << " --suppress is only available for the default output type." << endl; // suppressOuts.clear(); // } } static const char *argv0 = NULL; #define FINISH_READ(p) \ /* Don't do finishRead if the read isn't legit or if the read was skipped by the doneMask */ \ if(!p->empty()) { \ sink->finishRead(*p, true, !skipped); \ } \ skipped = false; static inline void finishReadWithHitmask(PatternSourcePerThread* p, HitSinkPerThread* sink, SyncBitset& hitMask, bool r, bool& skipped) { /* Don't do finishRead if the read isn't legit */ if(!p->empty()) { /* r = whether to consider reporting the read as unaligned */ bool reportUnAl = r; if(reportUnAl) { /* If the done-mask already shows the read as done, */ /* then we already reported the unaligned read and */ /* should refrain from re-reporting*/ reportUnAl = !skipped; if(reportUnAl) { /* If there hasn't been a hit reported, then report */ /* read as unaligned */ reportUnAl = !hitMask.test(p->patid()); } } if(sink->finishRead(*p, true, reportUnAl) > 0) { /* We reported a hit for the read, so we set the */ /* appropriate bit in the hitMask to prevent it from */ /* being reported as unaligned. */ if(!reportUnAl && sink->dumpsReads()) { hitMask.setOver(p->patid()); } } } skipped = false; } /// Macro for getting the next read, possibly aborting depending on /// whether the result is empty or the patid exceeds the limit, and /// marshaling the read into convenient variables. #define GET_READ(p) \ p->nextReadPair(); \ if(p->empty() || p->patid() >= ctx->qUpto) { \ p->bufa().clearAll(); \ break; \ } \ assert(!empty(p->bufa().patFw)); \ String& patFw = p->bufa().patFw; \ patFw.data_begin += 0; /* suppress "unused" compiler warning */ \ String& patRc = p->bufa().patRc; \ patRc.data_begin += 0; /* suppress "unused" compiler warning */ \ String& qual = p->bufa().qual; \ qual.data_begin += 0; /* suppress "unused" compiler warning */ \ String& qualRev = p->bufa().qualRev; \ qualRev.data_begin += 0; /* suppress "unused" compiler warning */ \ String& patFwRev = p->bufa().patFwRev; \ patFwRev.data_begin += 0; /* suppress "unused" compiler warning */ \ String& patRcRev = p->bufa().patRcRev; \ patRcRev.data_begin += 0; /* suppress "unused" compiler warning */ \ String& name = p->bufa().name; \ name.data_begin += 0; /* suppress "unused" compiler warning */ \ uint32_t patid = p->patid(); \ params.setPatId(patid); /// Macro for getting the forward oriented version of next read, /// possibly aborting depending on whether the result is empty or the /// patid exceeds the limit, and marshaling the read into convenient /// variables. #define GET_READ_FW(p) \ p->nextReadPair(); \ if(p->empty() || p->patid() >= qUpto) { \ p->bufa().clearAll(); \ break; \ } \ params.setPatId(p->patid()); \ assert(!empty(p->bufa().patFw)); \ String& patFw = p->bufa().patFw; \ patFw.data_begin += 0; /* suppress "unused" compiler warning */ \ String& qual = p->bufa().qual; \ qual.data_begin += 0; /* suppress "unused" compiler warning */ \ String& patFwRev = p->bufa().patFwRev; \ patFwRev.data_begin += 0; /* suppress "unused" compiler warning */ \ String& qualRev = p->bufa().qualRev; \ qualRev.data_begin += 0; /* suppress "unused" compiler warning */ \ String& name = p->bufa().name; \ name.data_begin += 0; /* suppress "unused" compiler warning */ \ uint32_t patid = p->patid(); #ifdef BOWTIE_PTHREADS #define WORKER_EXIT() \ patsrcFact->destroy(patsrc); \ delete patsrcFact; \ sinkFact->destroy(sink); \ delete sinkFact; \ if(tid > 0) { \ exitThread(NULL); \ } \ return NULL; #else #define WORKER_EXIT() \ patsrcFact->destroy(patsrc); \ delete patsrcFact; \ sinkFact->destroy(sink); \ delete sinkFact; \ return NULL; #endif #ifdef CHUD_PROFILING #define CHUD_START() chudStartRemotePerfMonitor("Bowtie"); #define CHUD_STOP() chudStopRemotePerfMonitor(); #else #define CHUD_START() #define CHUD_STOP() #endif /// Create a PatternSourcePerThread for the current thread according /// to the global params and return a pointer to it static PatternSourcePerThreadFactory* createPatsrcFactory(PairedPatternSource& _patsrc, int tid) { PatternSourcePerThreadFactory *patsrcFact; BowtieContext::Search* ctx = BowtieContext::getSearchContext(); if(ctx->randReadsNoSync) { patsrcFact = new RandomPatternSourcePerThreadFactory(ctx->numRandomReads, ctx->lenRandomReads, ctx->nthreads, tid); } else { patsrcFact = new WrappedPatternSourcePerThreadFactory(_patsrc); } assert(patsrcFact != NULL); return patsrcFact; } /** * Allocate a HitSinkPerThreadFactory on the heap according to the * global params and return a pointer to it. */ static HitSinkPerThreadFactory* createSinkFactory(HitSink& _sink) { BowtieContext::Search* ctx = BowtieContext::getSearchContext(); bool &nofw = ctx->nofw; bool &norc = ctx->norc; HitSinkPerThreadFactory *sink = NULL; if(ctx->format == INPUT_CHAIN) { assert(ctx->stateful); sink = new ChainingHitSinkPerThreadFactory(_sink, ctx->allHits ? 0xffffffff : ctx->khits, ctx->mhits, ctx->strata); } else if(!ctx->strata) { // Unstratified if(!ctx->allHits) { // First N good; "good" inherently ignores strata sink = new NGoodHitSinkPerThreadFactory(_sink, ctx->khits, ctx->mhits); } else { // All hits, spanning strata sink = new AllHitSinkPerThreadFactory(_sink, ctx->mhits); } } else { // Stratified assert(ctx->stateful); if(!ctx->allHits) { assert(ctx->stateful); // Buffer best hits, assuming they're arriving in best- // to-worst order sink = new NBestFirstStratHitSinkPerThreadFactory(_sink, ctx->khits, ctx->mhits); } else { assert(ctx->stateful); // Buffer best hits, assuming they're arriving in best- // to-worst order sink = new NBestFirstStratHitSinkPerThreadFactory(_sink, 0xffffffff/2, ctx->mhits); } } assert(sink != NULL); return sink; } /** * Search through a single (forward) Ebwt index for exact end-to-end * hits. Assumes that index is already loaded into memory. */ static void *exactSearchWorker(void *vp) { BowtieContext::Search* ctx = BowtieContext::getSearchContext(); bool &nofw = ctx->nofw; bool &norc = ctx->norc; int tid = *((int*)vp); PairedPatternSource& _patsrc = *(ctx->exactSearch_patsrc); HitSink& _sink = *(ctx->exactSearch_sink); Ebwt >& ebwt = *(ctx->exactSearch_ebwt); vector >& os = *(ctx->exactSearch_os); const BitPairReference* refs = ctx->exactSearch_refs; // Per-thread initialization PatternSourcePerThreadFactory *patsrcFact = createPatsrcFactory(_patsrc, tid); PatternSourcePerThread *patsrc = patsrcFact->create(); HitSinkPerThreadFactory* sinkFact = createSinkFactory(_sink); HitSinkPerThread* sink = sinkFact->create(); EbwtSearchParams > params( *(sink), // HitSink os, // reference sequences true, // read is forward true); // index is forward GreedyDFSRangeSource bt( &ebwt, params, refs, // reference sequence (for colorspace) 0xffffffff, // qualThresh 0xffffffff, // max backtracks (no max) 0, // reportPartials (don't) true, // reportExacts ctx->rangeMode, // reportRanges NULL, // seedlings NULL, // mutations ctx->verbose, // verbose &os, false); // considerQuals bool skipped = false; while(true) { if(BowtieContext::isCanceled()) { break; } FINISH_READ(patsrc); GET_READ(patsrc); #include "search_exact.c" } FINISH_READ(patsrc); WORKER_EXIT(); } /** * A statefulness-aware worker driver. Uses UnpairedExactAlignerV1. */ static void *exactSearchWorkerStateful(void *vp) { BowtieContext::Search* ctx = BowtieContext::getSearchContext(); bool &nofw = ctx->nofw; bool &norc = ctx->norc; int tid = *((int*)vp); PairedPatternSource& _patsrc = *(ctx->exactSearch_patsrc); HitSink& _sink = *(ctx->exactSearch_sink); Ebwt >& ebwt = *(ctx->exactSearch_ebwt); vector >& os = *(ctx->exactSearch_os); BitPairReference* refs = ctx->exactSearch_refs; // Global initialization PatternSourcePerThreadFactory* patsrcFact = createPatsrcFactory(_patsrc, tid); HitSinkPerThreadFactory* sinkFact = createSinkFactory(_sink); ChunkPool *pool = new ChunkPool(ctx->chunkSz * 1024, ctx->chunkPoolMegabytes * 1024 * 1024, ctx->chunkVerbose); UnpairedExactAlignerV1Factory alSEfact( ebwt, NULL, !nofw, !norc, _sink, *sinkFact, NULL, //&cacheFw, NULL, //&cacheBw, ctx->cacheLimit, pool, refs, os, !ctx->noMaqRound, !ctx->better, ctx->strandFix, ctx->rangeMode, ctx->verbose, ctx->quiet, ctx->seed); PairedExactAlignerV1Factory alPEfact( ebwt, NULL, ctx->color, !nofw, !norc, ctx->useV1, _sink, *sinkFact, ctx->mate1fw, ctx->mate2fw, ctx->minInsert, ctx->maxInsert, ctx->dontReconcileMates, ctx->mhits, // for symCeiling ctx->mixedThresh, ctx->mixedAttemptLim, NULL, //&cacheFw, NULL, //&cacheBw, ctx->cacheLimit, pool, refs, os, ctx->reportSe, !ctx->noMaqRound, ctx->strandFix, !ctx->better, ctx->rangeMode, ctx->verbose, ctx->quiet, ctx->seed); { MixedMultiAligner multi( ctx->prefetchWidth, ctx->qUpto, alSEfact, alPEfact, *patsrcFact); // Run that mother multi.run(); // MultiAligner must be destroyed before patsrcFact } delete patsrcFact; delete sinkFact; delete pool; #ifdef BOWTIE_PTHREADS if(tid > 0) exitThread(NULL); #endif return NULL; } #define SET_A_FW(bt, p, params) \ bt.setQuery(&p->bufa().patFw, &p->bufa().qual, &p->bufa().name); \ params.setFw(true); #define SET_A_RC(bt, p, params) \ bt.setQuery(&p->bufa().patRc, &p->bufa().qualRev, &p->bufa().name); \ params.setFw(false); #define SET_B_FW(bt, p, params) \ bt.setQuery(&p->bufb().patFw, &p->bufb().qual, &p->bufb().name); \ params.setFw(true); #define SET_B_RC(bt, p, params) \ bt.setQuery(&p->bufb().patRc, &p->bufb().qualRev, &p->bufb().name); \ params.setFw(false); #ifdef BOWTIE_PTHREADS #define PTHREAD_ATTRS (PTHREAD_CREATE_JOINABLE | PTHREAD_CREATE_DETACHED) #endif /** * Search through a single (forward) Ebwt index for exact end-to-end * hits. Assumes that index is already loaded into memory. */ static void exactSearch(PairedPatternSource& _patsrc, HitSink& _sink, Ebwt >& ebwt, vector >& os) { BowtieContext::Search* ctx = BowtieContext::getSearchContext(); bool &color = ctx->color; ctx->exactSearch_patsrc = &_patsrc; ctx->exactSearch_sink = &_sink; ctx->exactSearch_ebwt = &ebwt; ctx->exactSearch_os = &os; assert(!ebwt.isInMemory()); { // Load the rest of (vast majority of) the backward Ebwt into // memory Timer _t(cerr, "Time loading forward index: ", ctx->timing); ebwt.loadIntoMemory(color ? 1 : 0, -1, !ctx->noRefNames, ctx->startVerbose); } BitPairReference *refs = NULL; bool pair = ctx->mates1.size() > 0 || ctx->mates12.size() > 0; if(color || (pair && ctx->mixedThresh < 0xffffffff)) { Timer _t(cerr, "Time loading reference: ", ctx->timing); refs = new BitPairReference(ctx->adjustedEbwtFileBase, color, ctx->sanityCheck, NULL, &os, false, true, ctx->useMm, ctx->useShmem, ctx->mmSweep, ctx->verbose, ctx->startVerbose); if(!refs->loaded()) throw BowtieException("Bit pair reference not loaded"); } ctx->exactSearch_refs = refs; #ifdef BOWTIE_PTHREADS AutoArray threads(ctx->nthreads-1); AutoArray tids(ctx->nthreads-1); #endif CHUD_START(); { Timer _t(cerr, "Time for 0-mismatch search: ", ctx->timing); #ifdef BOWTIE_PTHREADS for(int i = 0; i < ctx->nthreads-1; i++) { tids[i] = i+1; if(ctx->stateful) { createThread(&threads[i], exactSearchWorkerStateful, (void *)&tids[i]); } else { createThread(&threads[i], exactSearchWorker, (void *)&tids[i]); } } #endif int tmp = 0; if(ctx->stateful) exactSearchWorkerStateful((void*)&tmp); else exactSearchWorker((void*)&tmp); #ifdef BOWTIE_PTHREADS for(int i = 0; i < ctx->nthreads-1; i++) joinThread(threads[i]); #endif } if(refs != NULL) delete refs; } /** * Search through a pair of Ebwt indexes, one for the forward direction * and one for the backward direction, for exact end-to-end hits and 1- * mismatch end-to-end hits. In my experience, this is slightly faster * than Maq (default) mode with the -n 1 option. * * Forward Ebwt (ebwtFw) is already loaded into memory and backward * Ebwt (ebwtBw) is not loaded into memory. */ /** * A statefulness-aware worker driver. Uses Unpaired/Paired1mmAlignerV1. */ static void *mismatchSearchWorkerFullStateful(void *vp) { BowtieContext::Search* ctx = BowtieContext::getSearchContext(); bool &color = ctx->color; int tid = *((int*)vp); PairedPatternSource& _patsrc = *(ctx->mismatchSearch_patsrc); HitSink& _sink = *(ctx->mismatchSearch_sink); Ebwt >& ebwtFw = *(ctx->mismatchSearch_ebwtFw); Ebwt >& ebwtBw = *(ctx->mismatchSearch_ebwtBw); vector >& os = *(ctx->mismatchSearch_os); BitPairReference* refs = ctx->mismatchSearch_refs; // Global initialization PatternSourcePerThreadFactory* patsrcFact = createPatsrcFactory(_patsrc, tid); HitSinkPerThreadFactory* sinkFact = createSinkFactory(_sink); ChunkPool *pool = new ChunkPool(ctx->chunkSz * 1024, ctx->chunkPoolMegabytes * 1024 * 1024, ctx->chunkVerbose); Unpaired1mmAlignerV1Factory alSEfact( ebwtFw, &ebwtBw, !ctx->nofw, !ctx->norc, _sink, *sinkFact, NULL, //&cacheFw, NULL, //&cacheBw, ctx->cacheLimit, pool, refs, os, !ctx->noMaqRound, !ctx->better, ctx->strandFix, ctx->rangeMode, ctx->verbose, ctx->quiet, ctx->seed); Paired1mmAlignerV1Factory alPEfact( ebwtFw, &ebwtBw, color, !ctx->nofw, !ctx->norc, ctx->useV1, _sink, *sinkFact, ctx->mate1fw, ctx->mate2fw, ctx->minInsert, ctx->maxInsert, ctx->dontReconcileMates, ctx->mhits, // for symCeiling ctx->mixedThresh, ctx->mixedAttemptLim, NULL, //&cacheFw, NULL, //&cacheBw, ctx->cacheLimit, pool, refs, os, ctx->reportSe, !ctx->noMaqRound, !ctx->better, ctx->strandFix, ctx->rangeMode, ctx->verbose, ctx->quiet, ctx->seed); { MixedMultiAligner multi( ctx->prefetchWidth, ctx->qUpto, alSEfact, alPEfact, *patsrcFact); // Run that mother multi.run(); // MultiAligner must be destroyed before patsrcFact } delete patsrcFact; delete sinkFact; delete pool; #ifdef BOWTIE_PTHREADS if(tid > 0) exitThread(NULL); #endif return NULL; } static void* mismatchSearchWorkerFull(void *vp){ BowtieContext::Search* ctx = BowtieContext::getSearchContext(); bool &nofw = ctx->nofw; bool &norc = ctx->norc; int tid = *((int*)vp); PairedPatternSource& _patsrc = *(ctx->mismatchSearch_patsrc); HitSink& _sink = *(ctx->mismatchSearch_sink); Ebwt >& ebwtFw = *(ctx->mismatchSearch_ebwtFw); Ebwt >& ebwtBw = *(ctx->mismatchSearch_ebwtBw); vector >& os = *(ctx->mismatchSearch_os); const BitPairReference* refs = ctx->mismatchSearch_refs; // Per-thread initialization PatternSourcePerThreadFactory* patsrcFact = createPatsrcFactory(_patsrc, tid); PatternSourcePerThread* patsrc = patsrcFact->create(); HitSinkPerThreadFactory* sinkFact = createSinkFactory(_sink); HitSinkPerThread* sink = sinkFact->create(); EbwtSearchParams > params( *sink, // HitSinkPerThread os, // reference sequences true, // read is forward false); // index is mirror index GreedyDFSRangeSource bt( &ebwtFw, params, refs, // reference sequence (for colorspace) 0xffffffff, // qualThresh 0xffffffff, // max backtracks (no max) 0, // reportPartials (don't) true, // reportExacts ctx->rangeMode, // reportRanges NULL, // seedlings NULL, // mutations ctx->verbose, // verbose &os, false); // considerQuals bool skipped = false; while(true) { if(BowtieContext::isCanceled()) { break; } FINISH_READ(patsrc); GET_READ(patsrc); uint32_t plen = length(patFw); uint32_t s = plen; uint32_t s3 = s >> 1; // length of 3' half of seed uint32_t s5 = (s >> 1) + (s & 1); // length of 5' half of seed #define DONEMASK_SET(p) #include "search_1mm_phase1.c" #include "search_1mm_phase2.c" #undef DONEMASK_SET } // End read loop FINISH_READ(patsrc); WORKER_EXIT(); } /** * Search through a single (forward) Ebwt index for exact end-to-end * hits. Assumes that index is already loaded into memory. */ static void mismatchSearchFull(PairedPatternSource& _patsrc, HitSink& _sink, Ebwt >& ebwtFw, Ebwt >& ebwtBw, vector >& os) { BowtieContext::Search* ctx = BowtieContext::getSearchContext(); ctx->mismatchSearch_patsrc = &_patsrc; ctx->mismatchSearch_sink = &_sink; ctx->mismatchSearch_ebwtFw = &ebwtFw; ctx->mismatchSearch_ebwtBw = &ebwtBw; ctx->mismatchSearch_doneMask = NULL; ctx->mismatchSearch_hitMask = NULL; ctx->mismatchSearch_os = &os; assert(!ebwtFw.isInMemory()); assert(!ebwtBw.isInMemory()); { // Load the other half of the index into memory Timer _t(cerr, "Time loading forward index: ", ctx->timing); ebwtFw.loadIntoMemory(ctx->color ? 1 : 0, -1, !ctx->noRefNames, ctx->startVerbose); } { // Load the other half of the index into memory Timer _t(cerr, "Time loading mirror index: ", ctx->timing); ebwtBw.loadIntoMemory(ctx->color ? 1 : 0, -1, !ctx->noRefNames, ctx->startVerbose); } // Create range caches, which are shared among all aligners BitPairReference *refs = NULL; bool pair = ctx->mates1.size() > 0 || ctx->mates12.size() > 0; if(ctx->color || (pair && ctx->mixedThresh < 0xffffffff)) { Timer _t(cerr, "Time loading reference: ", ctx->timing); refs = new BitPairReference(ctx->adjustedEbwtFileBase, ctx->color, ctx->sanityCheck, NULL, &os, false, true, ctx->useMm, ctx->useShmem, ctx->mmSweep, ctx->verbose, ctx->startVerbose); if(!refs->loaded()) throw BowtieException("Bit pair reference not loaded"); } ctx->mismatchSearch_refs = refs; #ifdef BOWTIE_PTHREADS // Allocate structures for threads AutoArray threads(ctx->nthreads-1); AutoArray tids(ctx->nthreads-1); #endif CHUD_START(); { Timer _t(cerr, "Time for 1-mismatch full-index search: ", ctx->timing); #ifdef BOWTIE_PTHREADS for(int i = 0; i < ctx->nthreads-1; i++) { tids[i] = i+1; if(ctx->stateful) createThread(&threads[i], mismatchSearchWorkerFullStateful, (void *)&tids[i]); else createThread(&threads[i], mismatchSearchWorkerFull, (void *)&tids[i]); } #endif // Go to town int tmp = 0; if(ctx->stateful) mismatchSearchWorkerFullStateful((void*)&tmp); else mismatchSearchWorkerFull((void*)&tmp); #ifdef BOWTIE_PTHREADS for(int i = 0; i < ctx->nthreads-1; i++) joinThread(threads[i]); #endif } if(refs != NULL) delete refs; } #define SWITCH_TO_FW_INDEX() { \ /* Evict the mirror index from memory if necessary */ \ if(ebwtBw.isInMemory()) ebwtBw.evictFromMemory(); \ assert(!ebwtBw.isInMemory()); \ /* Load the forward index into memory if necessary */ \ if(!ebwtFw.isInMemory()) { \ Timer _t(cerr, "Time loading forward index: ", ctx->timing); \ ebwtFw.loadIntoMemory(ctx->color ? 1 : 0, -1, !ctx->noRefNames, ctx->startVerbose); \ } \ assert(ebwtFw.isInMemory()); \ _patsrc.reset(); /* rewind pattern source to first pattern */ \ } #define SWITCH_TO_BW_INDEX() { \ /* Evict the forward index from memory if necessary */ \ if(ebwtFw.isInMemory()) ebwtFw.evictFromMemory(); \ assert(!ebwtFw.isInMemory()); \ /* Load the forward index into memory if necessary */ \ if(!ebwtBw.isInMemory()) { \ Timer _t(cerr, "Time loading mirror index: ", timing); \ ebwtBw.loadIntoMemory(ctx->color ? 1 : 0, !noRefNames, startVerbose); \ } \ assert(ebwtBw.isInMemory()); \ _patsrc.reset(); /* rewind pattern source to first pattern */ \ } #define ASSERT_NO_HITS_FW(ebwtfw) \ if(sanityCheck && os.size() > 0) { \ vector hits; \ uint32_t threeRevOff = (seedMms <= 3) ? s : 0; \ uint32_t twoRevOff = (seedMms <= 2) ? s : 0; \ uint32_t oneRevOff = (seedMms <= 1) ? s : 0; \ uint32_t unrevOff = (seedMms == 0) ? s : 0; \ if(hits.size() > 0) { \ /* Print offending hit obtained by oracle */ \ ::printHit( \ os, \ hits[0], \ patFw, \ plen, \ unrevOff, \ oneRevOff, \ twoRevOff, \ threeRevOff, \ ebwtfw); /* ebwtFw */ \ } \ assert_eq(0, hits.size()); \ } #define ASSERT_NO_HITS_RC(ebwtfw) \ if(sanityCheck && os.size() > 0) { \ vector hits; \ uint32_t threeRevOff = (seedMms <= 3) ? s : 0; \ uint32_t twoRevOff = (seedMms <= 2) ? s : 0; \ uint32_t oneRevOff = (seedMms <= 1) ? s : 0; \ uint32_t unrevOff = (seedMms == 0) ? s : 0; \ if(hits.size() > 0) { \ /* Print offending hit obtained by oracle */ \ ::printHit( \ os, \ hits[0], \ patRc, \ plen, \ unrevOff, \ oneRevOff, \ twoRevOff, \ threeRevOff, \ ebwtfw); /* ebwtFw */ \ } \ assert_eq(0, hits.size()); \ } #define TWOTHREE_WORKER_SETUP() \ int tid = *((int*)vp); \ PairedPatternSource& _patsrc = *(ctx->twoOrThreeMismatchSearch_patsrc); \ HitSink& _sink = *(ctx->twoOrThreeMismatchSearch_sink); \ vector >& os = *(ctx->twoOrThreeMismatchSearch_os); \ bool two = ctx->twoOrThreeMismatchSearch_two; \ PatternSourcePerThreadFactory* patsrcFact = createPatsrcFactory(_patsrc, tid); \ PatternSourcePerThread* patsrc = patsrcFact->create(); \ HitSinkPerThreadFactory* sinkFact = createSinkFactory(_sink); \ HitSinkPerThread* sink = sinkFact->create(); \ /* Per-thread initialization */ \ EbwtSearchParams > params( \ *sink, /* HitSink */ \ os, /* reference sequences */ \ true, /* read is forward */ \ true); /* index is forward */ /** * A statefulness-aware worker driver. Uses UnpairedExactAlignerV1. */ static void *twoOrThreeMismatchSearchWorkerStateful(void *vp) { BowtieContext::Search* ctx = BowtieContext::getSearchContext(); int tid = *((int*)vp); PairedPatternSource& _patsrc = *(ctx->twoOrThreeMismatchSearch_patsrc); HitSink& _sink = *(ctx->twoOrThreeMismatchSearch_sink); Ebwt >& ebwtFw = *(ctx->twoOrThreeMismatchSearch_ebwtFw); Ebwt >& ebwtBw = *(ctx->twoOrThreeMismatchSearch_ebwtBw); vector >& os = *(ctx->twoOrThreeMismatchSearch_os); BitPairReference* refs = ctx->twoOrThreeMismatchSearch_refs; static bool two = ctx->twoOrThreeMismatchSearch_two; // Global initialization PatternSourcePerThreadFactory* patsrcFact = createPatsrcFactory(_patsrc, tid); HitSinkPerThreadFactory* sinkFact = createSinkFactory(_sink); ChunkPool *pool = new ChunkPool(ctx->chunkSz * 1024, ctx->chunkPoolMegabytes * 1024 * 1024, ctx->chunkVerbose); Unpaired23mmAlignerV1Factory alSEfact( ebwtFw, &ebwtBw, two, !ctx->nofw, !ctx->norc, _sink, *sinkFact, NULL, //&cacheFw, NULL, //&cacheBw, ctx->cacheLimit, pool, refs, os, !ctx->noMaqRound, !ctx->better, ctx->strandFix, ctx->rangeMode, ctx->verbose, ctx->quiet, ctx->seed); Paired23mmAlignerV1Factory alPEfact( ebwtFw, &ebwtBw, ctx->color, !ctx->nofw, !ctx->norc, ctx->useV1, two, _sink, *sinkFact, ctx->mate1fw, ctx->mate2fw, ctx->minInsert, ctx->maxInsert, ctx->dontReconcileMates, ctx->mhits, // for symCeiling ctx->mixedThresh, ctx->mixedAttemptLim, NULL, //&cacheFw, NULL, //&cacheBw, ctx->cacheLimit, pool, refs, os, ctx->reportSe, !ctx->noMaqRound, !ctx->better, ctx->strandFix, ctx->rangeMode, ctx->verbose, ctx->quiet, ctx->seed); { MixedMultiAligner multi( ctx->prefetchWidth, ctx->qUpto, alSEfact, alPEfact, *patsrcFact); // Run that mother multi.run(); // MultiAligner must be destroyed before patsrcFact } delete patsrcFact; delete sinkFact; delete pool; #ifdef BOWTIE_PTHREADS if(tid > 0) exitThread(NULL); #endif return NULL; } static void* twoOrThreeMismatchSearchWorkerFull(void *vp) { BowtieContext::Search* ctx = BowtieContext::getSearchContext(); bool &nofw = ctx->nofw; bool &norc = ctx->norc; TWOTHREE_WORKER_SETUP(); Ebwt >& ebwtFw = *(ctx->twoOrThreeMismatchSearch_ebwtFw); Ebwt >& ebwtBw = *(ctx->twoOrThreeMismatchSearch_ebwtBw); const BitPairReference* refs = ctx->twoOrThreeMismatchSearch_refs; GreedyDFSRangeSource btr1( &ebwtFw, params, refs, // reference sequence (for colorspace) 0xffffffff, // qualThresh // Do not impose maximums in 2/3-mismatch mode 0xffffffff, // max backtracks (no limit) 0, // reportPartials (don't) true, // reportExacts ctx->rangeMode, // reportRanges NULL, // seedlings NULL, // mutations ctx->verbose, // verbose &os, false); // considerQuals GreedyDFSRangeSource bt2( &ebwtBw, params, refs, // reference sequence (for colorspace) 0xffffffff, // qualThresh // Do not impose maximums in 2/3-mismatch mode 0xffffffff, // max backtracks (no limit) 0, // reportPartials (no) true, // reportExacts ctx->rangeMode, // reportRanges NULL, // seedlings NULL, // mutations ctx->verbose, // verbose &os, false); // considerQuals GreedyDFSRangeSource bt3( &ebwtFw, params, refs, // reference sequence (for colorspace) 0xffffffff, // qualThresh (none) // Do not impose maximums in 2/3-mismatch mode 0xffffffff, // max backtracks (no limit) 0, // reportPartials (don't) true, // reportExacts ctx->rangeMode, // reportRanges NULL, // seedlings NULL, // mutations ctx->verbose, // verbose &os, false); // considerQuals GreedyDFSRangeSource bthh3( &ebwtFw, params, refs, // reference sequence (for colorspace) 0xffffffff, // qualThresh // Do not impose maximums in 2/3-mismatch mode 0xffffffff, // max backtracks (no limit) 0, // reportPartials (don't) true, // reportExacts ctx->rangeMode, // reportRanges NULL, // seedlings NULL, // mutations ctx->verbose, // verbose &os, false, // considerQuals true); // halfAndHalf bool skipped = false; while(true) { // Read read-in loop if(BowtieContext::isCanceled()) { break; } FINISH_READ(patsrc); GET_READ(patsrc); patid += 0; // kill unused variable warning uint32_t plen = length(patFw); uint32_t s = plen; uint32_t s3 = s >> 1; // length of 3' half of seed uint32_t s5 = (s >> 1) + (s & 1); // length of 5' half of seed #define DONEMASK_SET(p) #include "search_23mm_phase1.c" #include "search_23mm_phase2.c" #include "search_23mm_phase3.c" #undef DONEMASK_SET } FINISH_READ(patsrc); // Threads join at end of Phase 1 WORKER_EXIT(); } template static void twoOrThreeMismatchSearchFull( PairedPatternSource& _patsrc, /// pattern source HitSink& _sink, /// hit sink Ebwt& ebwtFw, /// index of original text Ebwt& ebwtBw, /// index of mirror text vector >& os, /// text strings, if available (empty otherwise) bool two = true) /// true -> 2, false -> 3 { BowtieContext::Search* ctx = BowtieContext::getSearchContext(); // Global initialization assert(!ebwtFw.isInMemory()); assert(!ebwtBw.isInMemory()); { // Load the other half of the index into memory Timer _t(cerr, "Time loading forward index: ", ctx->timing); ebwtFw.loadIntoMemory(ctx->color ? 1 : 0, -1, !ctx->noRefNames, ctx->startVerbose); } { // Load the other half of the index into memory Timer _t(cerr, "Time loading mirror index: ", ctx->timing); ebwtBw.loadIntoMemory(ctx->color ? 1 : 0, -1, !ctx->noRefNames, ctx->startVerbose); } // Create range caches, which are shared among all aligners BitPairReference *refs = NULL; bool pair = ctx->mates1.size() > 0 || ctx->mates12.size() > 0; if(ctx->color || (pair && ctx->mixedThresh < 0xffffffff)) { Timer _t(cerr, "Time loading reference: ", ctx->timing); refs = new BitPairReference(ctx->adjustedEbwtFileBase, ctx->color, ctx->sanityCheck, NULL, &os, false, true, ctx->useMm, ctx->useShmem, ctx->mmSweep, ctx->verbose, ctx->startVerbose); if(!refs->loaded()) BowtieException("Bit pair reference not loaded"); } ctx->twoOrThreeMismatchSearch_refs = refs; ctx->twoOrThreeMismatchSearch_patsrc = &_patsrc; ctx->twoOrThreeMismatchSearch_sink = &_sink; ctx->twoOrThreeMismatchSearch_ebwtFw = &ebwtFw; ctx->twoOrThreeMismatchSearch_ebwtBw = &ebwtBw; ctx->twoOrThreeMismatchSearch_os = &os; ctx->twoOrThreeMismatchSearch_doneMask = NULL; ctx->twoOrThreeMismatchSearch_hitMask = NULL; ctx->twoOrThreeMismatchSearch_two = two; #ifdef BOWTIE_PTHREADS AutoArray threads(ctx->nthreads-1); AutoArray tids(ctx->nthreads-1); #endif CHUD_START(); { Timer _t(cerr, "End-to-end 2/3-mismatch full-index search: ", ctx->timing); #ifdef BOWTIE_PTHREADS for(int i = 0; i < ctx->nthreads-1; i++) { tids[i] = i+1; if(ctx->stateful) createThread(&threads[i], twoOrThreeMismatchSearchWorkerStateful, (void *)&tids[i]); else createThread(&threads[i], twoOrThreeMismatchSearchWorkerFull, (void *)&tids[i]); } #endif int tmp = 0; if(ctx->stateful) twoOrThreeMismatchSearchWorkerStateful((void*)&tmp); else twoOrThreeMismatchSearchWorkerFull((void*)&tmp); #ifdef BOWTIE_PTHREADS for(int i = 0; i < ctx->nthreads-1; i++) joinThread(threads[i]); #endif } if(refs != NULL) delete refs; return; } #define SEEDEDQUAL_WORKER_SETUP() \ int tid = *((int*)vp); \ PairedPatternSource& _patsrc = *(ctx->seededQualSearch_patsrc); \ HitSink& _sink = *(ctx->seededQualSearch_sink); \ vector >& os = *(ctx->seededQualSearch_os); \ int qualCutoff = ctx->seededQualSearch_qualCutoff; \ PatternSourcePerThreadFactory* patsrcFact = createPatsrcFactory(_patsrc, tid); \ PatternSourcePerThread* patsrc = patsrcFact->create(); \ HitSinkPerThreadFactory* sinkFact = createSinkFactory(_sink); \ HitSinkPerThread* sink = sinkFact->create(); \ /* Per-thread initialization */ \ EbwtSearchParams > params( \ *sink, /* HitSink */ \ os, /* reference sequences */ \ true, /* read is forward */ \ true); /* index is forward */ static void* seededQualSearchWorkerFull(void *vp) { BowtieContext::Search* ctx = BowtieContext::getSearchContext(); SEEDEDQUAL_WORKER_SETUP(); bool &nofw = ctx->nofw; bool &norc = ctx->norc; bool &verbose = ctx->verbose; int &seedLen = ctx->seedLen; int &seedMms = ctx->seedMms; int &sanityCheck = ctx->sanityCheck; bool &noMaqRound = ctx->noMaqRound; int &qualThresh = ctx->qualThresh; bool &quiet = ctx->quiet; Ebwt >& ebwtFw = *(ctx->seededQualSearch_ebwtFw); Ebwt >& ebwtBw = *(ctx->seededQualSearch_ebwtBw); PartialAlignmentManager * pamRc = NULL; PartialAlignmentManager * pamFw = NULL; if(seedMms > 0) { pamRc = new PartialAlignmentManager(64); pamFw = new PartialAlignmentManager(64); } vector pals; const BitPairReference* refs = ctx->seededQualSearch_refs; // GreedyDFSRangeSource for finding exact hits for the forward- // oriented read GreedyDFSRangeSource btf1( &ebwtFw, params, refs, // reference sequence (for colorspace) qualCutoff, // qualThresh ctx->maxBtsBetter, // max backtracks 0, // reportPartials (don't) true, // reportExacts ctx->rangeMode, // reportRanges NULL, // seedlings NULL, // mutations verbose, // verbose &os, false); // considerQuals GreedyDFSRangeSource bt1( &ebwtFw, params, refs, // reference sequence (for colorspace) qualCutoff, // qualThresh ctx->maxBtsBetter, // max backtracks 0, // reportPartials (don't) true, // reportExacts ctx->rangeMode, // reportRanges NULL, // seedlings NULL, // mutations ctx->verbose, // verbose &os, // reference sequences true, // considerQuals false, !ctx->noMaqRound); // GreedyDFSRangeSource to search for hits for cases 1F, 2F, 3F GreedyDFSRangeSource btf2( &ebwtBw, params, refs, // reference sequence (for colorspace) qualCutoff, // qualThresh ctx->maxBtsBetter, // max backtracks 0, // reportPartials (no) true, // reportExacts ctx->rangeMode, // reportRanges NULL, // partial alignment manager NULL, // mutations ctx->verbose, // verbose &os, // reference sequences true, // considerQuals false, !noMaqRound); // GreedyDFSRangeSource to search for partial alignments for case 4R GreedyDFSRangeSource btr2( &ebwtBw, params, refs, // reference sequence (for colorspace) qualCutoff, // qualThresh (none) ctx->maxBtsBetter, // max backtracks seedMms, // report partials (up to seedMms mms) true, // reportExacts ctx->rangeMode, // reportRanges pamRc, // partial alignment manager NULL, // mutations verbose, // verbose &os, // reference sequences true, // considerQuals false, !noMaqRound); // GreedyDFSRangeSource to search for seedlings for case 4F GreedyDFSRangeSource btf3( &ebwtFw, params, refs, // reference sequence (for colorspace) qualCutoff, // qualThresh (none) ctx->maxBtsBetter, // max backtracks seedMms, // reportPartials (do) true, // reportExacts ctx->rangeMode, // reportRanges pamFw, // seedlings NULL, // mutations verbose, // verbose &os, // reference sequences true, // considerQuals false, !noMaqRound); // GreedyDFSRangeSource to search for hits for case 4R by extending // the partial alignments found in Phase 2 GreedyDFSRangeSource btr3( &ebwtFw, params, refs, // reference sequence (for colorspace) qualCutoff, // qualThresh ctx->maxBtsBetter, // max backtracks 0, // reportPartials (don't) true, // reportExacts ctx->rangeMode,// reportRanges NULL, // seedlings NULL, // mutations verbose, // verbose &os, // reference sequences true, // considerQuals false, !noMaqRound); // The half-and-half GreedyDFSRangeSource GreedyDFSRangeSource btr23( &ebwtFw, params, refs, // reference sequence (for colorspace) qualCutoff, // qualThresh ctx->maxBtsBetter, // max backtracks 0, // reportPartials (don't) true, // reportExacts ctx->rangeMode,// reportRanges NULL, // seedlings NULL, // mutations verbose, // verbose &os, true, // considerQuals true, // halfAndHalf !noMaqRound); // GreedyDFSRangeSource to search for hits for case 4F by extending // the partial alignments found in Phase 3 GreedyDFSRangeSource btf4( &ebwtBw, params, refs, // reference sequence (for colorspace) qualCutoff, // qualThresh ctx->maxBtsBetter, // max backtracks 0, // reportPartials (don't) true, // reportExacts ctx->rangeMode,// reportRanges NULL, // seedlings NULL, // mutations verbose, // verbose &os, // reference sequences true, // considerQuals false, !noMaqRound); // Half-and-half GreedyDFSRangeSource for forward read GreedyDFSRangeSource btf24( &ebwtBw, params, refs, // reference sequence (for colorspace) qualCutoff, // qualThresh ctx->maxBtsBetter, // max backtracks 0, // reportPartials (don't) true, // reportExacts ctx->rangeMode,// reportRanges NULL, // seedlings NULL, // mutations verbose, // verbose &os, true, // considerQuals true, // halfAndHalf !noMaqRound); String muts; bool skipped = false; while(true) { if(BowtieContext::isCanceled()) { break; } FINISH_READ(patsrc); GET_READ(patsrc); size_t plen = length(patFw); uint32_t s = seedLen; uint32_t s3 = (s >> 1); /* length of 3' half of seed */ uint32_t s5 = (s >> 1) + (s & 1); /* length of 5' half of seed */ uint32_t qs = min(plen, s); uint32_t qs3 = qs >> 1; uint32_t qs5 = (qs >> 1) + (qs & 1); #define DONEMASK_SET(p) #include "search_seeded_phase1.c" #include "search_seeded_phase2.c" #include "search_seeded_phase3.c" #include "search_seeded_phase4.c" #undef DONEMASK_SET } FINISH_READ(patsrc); if(seedMms > 0) { delete pamRc; delete pamFw; } WORKER_EXIT(); } static void* seededQualSearchWorkerFullStateful(void *vp) { BowtieContext::Search* ctx = BowtieContext::getSearchContext(); int tid = *((int*)vp); PairedPatternSource& _patsrc = *(ctx->seededQualSearch_patsrc); HitSink& _sink = *(ctx->seededQualSearch_sink); Ebwt >& ebwtFw = *(ctx->seededQualSearch_ebwtFw); Ebwt >& ebwtBw = *(ctx->seededQualSearch_ebwtBw); vector >& os = *(ctx->seededQualSearch_os); int qualCutoff = ctx->seededQualSearch_qualCutoff; BitPairReference* refs = ctx->seededQualSearch_refs; // Global initialization PatternSourcePerThreadFactory* patsrcFact = createPatsrcFactory(_patsrc, tid); HitSinkPerThreadFactory* sinkFact = createSinkFactory(_sink); ChunkPool *pool = new ChunkPool(ctx->chunkSz * 1024, ctx->chunkPoolMegabytes * 1024 * 1024, ctx->chunkVerbose); AlignerMetrics *metrics = NULL; if(ctx->stats) { metrics = new AlignerMetrics(); } UnpairedSeedAlignerFactory alSEfact( ebwtFw, &ebwtBw, !ctx->nofw, !ctx->norc, ctx->seedMms, ctx->seedLen, qualCutoff, ctx->maxBts, _sink, *sinkFact, NULL, //&cacheFw, NULL, //&cacheBw, ctx->cacheLimit, pool, refs, os, !ctx->noMaqRound, !ctx->better, ctx->strandFix, ctx->rangeMode, ctx->verbose, ctx->quiet, ctx->seed, metrics); PairedSeedAlignerFactory alPEfact( ebwtFw, &ebwtBw, ctx->color, ctx->useV1, !ctx->nofw, !ctx->norc, ctx->seedMms, ctx->seedLen, qualCutoff, ctx->maxBts, _sink, *sinkFact, ctx->mate1fw, ctx->mate2fw, ctx->minInsert, ctx->maxInsert, ctx->dontReconcileMates, ctx->mhits, // for symCeiling ctx->mixedThresh, ctx->mixedAttemptLim, NULL, //&cacheFw, NULL, //&cacheBw, ctx->cacheLimit, pool, refs, os, ctx->reportSe, !ctx->noMaqRound, !ctx->better, ctx->strandFix, ctx->rangeMode, ctx->verbose, ctx->quiet, ctx->seed); { MixedMultiAligner multi( ctx->prefetchWidth, ctx->qUpto, alSEfact, alPEfact, *patsrcFact); // Run that mother multi.run(); // MultiAligner must be destroyed before patsrcFact } if(metrics != NULL) { metrics->printSummary(); delete metrics; } delete patsrcFact; delete sinkFact; delete pool; #ifdef BOWTIE_PTHREADS if(tid > 0) { exitThread(NULL); } #endif return NULL; } /** * Search for a good alignments for each read using criteria that * correspond somewhat faithfully to Maq's. Search is aided by a pair * of Ebwt indexes, one for the original references, and one for the * transpose of the references. Neither index should be loaded upon * entry to this function. * * Like Maq, we treat the first 24 base pairs of the read (those * closest to the 5' end) differently from the remainder of the read. * We call the first 24 base pairs the "seed." */ template static void seededQualCutoffSearchFull( int seedLen, /// length of seed (not a maq option) int qualCutoff, /// maximum sum of mismatch qualities /// like maq map's -e option /// default: 70 int seedMms, /// max # mismatches allowed in seed /// (like maq map's -n option) /// Can only be 1 or 2, default: 1 PairedPatternSource& _patsrc, /// pattern source HitSink& _sink, /// hit sink Ebwt& ebwtFw, /// index of original text Ebwt& ebwtBw, /// index of mirror text vector >& os) /// text strings, if available (empty otherwise) { BowtieContext::Search* ctx = BowtieContext::getSearchContext(); // Global intialization assert_leq(seedMms, 3); ctx->seededQualSearch_patsrc = &_patsrc; ctx->seededQualSearch_sink = &_sink; ctx->seededQualSearch_ebwtFw = &ebwtFw; ctx->seededQualSearch_ebwtBw = &ebwtBw; ctx->seededQualSearch_os = &os; ctx->seededQualSearch_doneMask = NULL; ctx->seededQualSearch_hitMask = NULL; ctx->seededQualSearch_pamFw = NULL; ctx->seededQualSearch_pamRc = NULL; ctx->seededQualSearch_qualCutoff = qualCutoff; // Create range caches, which are shared among all aligners BitPairReference *refs = NULL; bool pair = ctx->mates1.size() > 0 || ctx->mates12.size() > 0; if(ctx->color || (pair && ctx->mixedThresh < 0xffffffff)) { Timer _t(cerr, "Time loading reference: ", ctx->timing); refs = new BitPairReference(ctx->adjustedEbwtFileBase, ctx->color, ctx->sanityCheck, NULL, &os, false, true, ctx->useMm, ctx->useShmem, ctx->mmSweep, ctx->verbose, ctx->startVerbose); if(!refs->loaded()) BowtieException("Bit pair reference not loaded"); } ctx->seededQualSearch_refs = refs; #ifdef BOWTIE_PTHREADS AutoArray threads(ctx->nthreads-1); AutoArray tids(ctx->nthreads-1); #endif SWITCH_TO_FW_INDEX(); assert(!ebwtBw.isInMemory()); { // Load the other half of the index into memory Timer _t(cerr, "Time loading mirror index: ", ctx->timing); ebwtBw.loadIntoMemory(ctx->color ? 1 : 0, -1, !ctx->noRefNames, ctx->startVerbose); } CHUD_START(); { // Phase 1: Consider cases 1R and 2R Timer _t(cerr, "Seeded quality full-index search: ", ctx->timing); #ifdef BOWTIE_PTHREADS for(int i = 0; i < ctx->nthreads-1; i++) { tids[i] = i+1; if(ctx->stateful) createThread(&threads[i], seededQualSearchWorkerFullStateful, (void*)&tids[i]); else createThread(&threads[i], seededQualSearchWorkerFull, (void*)&tids[i]); } #endif int tmp = 0; if(ctx->stateful) seededQualSearchWorkerFullStateful((void*)&tmp); else seededQualSearchWorkerFull((void*)&tmp); #ifdef BOWTIE_PTHREADS for(int i = 0; i < ctx->nthreads-1; i++) joinThread(threads[i]); #endif } if(refs != NULL) { delete refs; } ebwtBw.evictFromMemory(); } /** * Return a new dynamically allocated PatternSource for the given * format, using the given list of strings as the filenames to read * from or as the sequences themselves (i.e. if -c was used). */ static PatternSource* patsrcFromStrings(int format, const vector& reads, const vector* quals) { BowtieContext::Search* ctx = BowtieContext::getSearchContext(); switch(format) { case FASTA: return new FastaPatternSource (ctx->seed, reads, quals, ctx->color, ctx->randomizeQuals, ctx->useSpinlock, ctx->patDumpfile, ctx->verbose, ctx->trim3, ctx->trim5, ctx->solexaQuals, ctx->phred64Quals, ctx->integerQuals, ctx->skipReads); case FASTA_CONT: return new FastaContinuousPatternSource ( ctx->seed, reads, ctx->fastaContLen, ctx->fastaContFreq, ctx->useSpinlock, ctx->patDumpfile, ctx->verbose, ctx->skipReads); case RAW: return new RawPatternSource (ctx->seed, reads, ctx->color, ctx->randomizeQuals, ctx->useSpinlock, ctx->patDumpfile, ctx->verbose, ctx->trim3, ctx->trim5, ctx->skipReads); case FASTQ: return new FastqPatternSource (ctx->seed, reads, ctx->color, ctx->randomizeQuals, ctx->useSpinlock, ctx->patDumpfile, ctx->verbose, ctx->trim3, ctx->trim5, ctx->solexaQuals, ctx->phred64Quals, ctx->integerQuals, ctx->fuzzy, ctx->skipReads); case TAB_MATE: return new TabbedPatternSource(ctx->seed, reads, ctx->color, ctx->randomizeQuals, ctx->useSpinlock, ctx->patDumpfile, ctx->verbose, ctx->trim3, ctx->trim5, ctx->skipReads); case CMDLINE: return new VectorPatternSource(ctx->seed, reads, ctx->color, ctx->randomizeQuals, ctx->useSpinlock, ctx->patDumpfile, ctx->verbose, ctx->trim3, ctx->trim5, ctx->skipReads); case INPUT_CHAIN: return new ChainPatternSource (ctx->seed, reads, ctx->useSpinlock, ctx->patDumpfile, ctx->verbose, ctx->skipReads); case RANDOM: return new RandomPatternSource(ctx->seed, 2000000, ctx->lenRandomReads, ctx->useSpinlock, ctx->patDumpfile, ctx->verbose); default: { cerr << "Internal error; bad patsrc format: " << format << endl; throw 1; } } } #define PASS_DUMP_FILES ctx->dumpAlBase, ctx->dumpUnalBase, ctx->dumpMaxBase static string argstr; template static void driver(U2::BowtieReadsReader* reader, U2::BowtieReadsWriter* writer, const U2::GUrl& resultFileUrl, const char * type, const string& ebwtFileBase, const string& query, const vector& queries, const vector& qualities, const string& outfile) { BowtieContext::Search* ctx = BowtieContext::getSearchContext(); if(ctx->verbose || ctx->startVerbose) { cerr << "Entered driver(): "; logTime(cerr, true); } // Vector of the reference sequences; used for sanity-checking vector > os; // Read reference sequences from the command-line or from a FASTA file // Adjust ctx->adjustedEbwtFileBase = adjustEbwtBase("", ebwtFileBase, ctx->verbose); vector patsrcs_a; vector patsrcs_b; vector patsrcs_ab; // If there were any first-mates specified, we will operate in // stateful mode bool paired = ctx->mates1.size() > 0 || ctx->mates12.size() > 0; if(paired) ctx->stateful = true; // Create list of pattern sources for paired reads appearing // interleaved in a single file if(ctx->verbose || ctx->startVerbose) { cerr << "Creating paired-end patsrcs: "; logTime(cerr, true); } for(size_t i = 0; i < ctx->mates12.size(); i++) { const vector* qs = &(ctx->mates12); vector tmp; if(ctx->fileParallel) { // Feed query files one to each PatternSource qs = &tmp; tmp.push_back(ctx->mates12[i]); assert_eq(1, tmp.size()); } patsrcs_ab.push_back(patsrcFromStrings(ctx->format, *qs, NULL)); if(!ctx->fileParallel) { break; } } // Create list of pattern sources for paired reads for(size_t i = 0; i < ctx->mates1.size(); i++) { const vector* qs = &(ctx->mates1); const vector* quals = &(ctx->qualities1); vector tmpSeq; vector tmpQual; if(ctx->fileParallel) { // Feed query files one to each PatternSource qs = &tmpSeq; tmpSeq.push_back(ctx->mates1[i]); quals = &tmpSeq; tmpQual.push_back(ctx->qualities1[i]); assert_eq(1, tmpSeq.size()); } if(quals->empty()) quals = NULL; patsrcs_a.push_back(patsrcFromStrings(ctx->format, *qs, quals)); if(!ctx->fileParallel) { break; } } // Create list of pattern sources for paired reads for(size_t i = 0; i < ctx->mates2.size(); i++) { const vector* qs = &(ctx->mates2); const vector* quals = &(ctx->qualities2); vector tmpSeq; vector tmpQual; if(ctx->fileParallel) { // Feed query files one to each PatternSource qs = &tmpSeq; tmpSeq.push_back(ctx->mates2[i]); quals = &tmpQual; tmpQual.push_back(ctx->qualities2[i]); assert_eq(1, tmpSeq.size()); } if(quals->empty()) quals = NULL; patsrcs_b.push_back(patsrcFromStrings(ctx->format, *qs, quals)); if(!ctx->fileParallel) { break; } } // All mates/mate files must be paired assert_eq(patsrcs_a.size(), patsrcs_b.size()); // Create list of pattern sources for the unpaired reads if(ctx->verbose || ctx->startVerbose) { cerr << "Creating single-end patsrcs: "; logTime(cerr, true); } for(size_t i = 0; i < queries.size(); i++) { const vector* qs = &queries; const vector* quals = &qualities; PatternSource* patsrc = NULL; vector tmpSeq; vector tmpQual; if(ctx->fileParallel) { // Feed query files one to each PatternSource qs = &tmpSeq; tmpSeq.push_back(queries[i]); quals = &tmpQual; tmpQual.push_back(qualities[i]); assert_eq(1, tmpSeq.size()); } if(quals->empty()) quals = NULL; patsrc = new DNASequencesPatternSource(ctx->seed, reader); assert(patsrc != NULL); patsrcs_a.push_back(patsrc); patsrcs_b.push_back(NULL); if(!ctx->fileParallel) { break; } } if(ctx->verbose || ctx->startVerbose) { cerr << "Creating PatternSource: "; logTime(cerr, true); } PairedPatternSource *patsrc = NULL; if(ctx->mates12.size() > 0) { patsrc = new PairedSoloPatternSource(patsrcs_ab, ctx->seed); } else { patsrc = new PairedDualPatternSource(patsrcs_a, patsrcs_b, ctx->seed); } // Open hit output file if(ctx->verbose || ctx->startVerbose) { cerr << "Opening hit output file: "; logTime(cerr, true); } OutFileBuf *fout; if(!outfile.empty()) { if(ctx->refOut) { fout = NULL; if(!ctx->quiet) { cerr << "Warning: ignoring alignment output file " << outfile << " because --refout was specified" << endl; } } else { fout = new OutFileBuf(outfile.c_str(), false); } } else { if(ctx->outType == OUTPUT_CHAIN && !ctx->refOut) { cerr << "Error: Must specify an output file when output mode is --chain" << endl; throw 1; } fout = new OutFileBuf(); } ReferenceMap* rmap = NULL; if(ctx->refMapFile != NULL) { if(ctx->verbose || ctx->startVerbose) { cerr << "About to load in a reference map file with name " << ctx->refMapFile << ": "; logTime(cerr, true); } rmap = new ReferenceMap(ctx->refMapFile, !ctx->noRefNames); } AnnotationMap* amap = NULL; if(ctx->annotMapFile != NULL) { if(ctx->verbose || ctx->startVerbose) { cerr << "About to load in an annotation map file with name " << ctx->annotMapFile << ": "; logTime(cerr, true); } amap = new AnnotationMap(ctx->annotMapFile); } // Initialize Ebwt object and read in header if(ctx->verbose || ctx->startVerbose) { cerr << "About to initialize fw Ebwt: "; logTime(cerr, true); } Ebwt ebwt(ctx->adjustedEbwtFileBase, ctx->color, // index is colorspace -1, // don't care about entireReverse true, // index is for the forward direction /* overriding: */ ctx->offRate, /* overriding: */ ctx->isaRate, ctx->useMm, // whether to use memory-mapped files ctx->useShmem, // whether to use shared memory ctx->mmSweep, // sweep memory-mapped files !ctx->noRefNames, // load names? rmap, // reference map, or NULL if none is needed ctx->verbose, // whether to be talkative ctx->startVerbose, // talkative during initialization false /*passMemExc*/, ctx->sanityCheck); ctx->refLength = ebwt.plen()[0]; { BowtieUrlReadsWriter *urlWriter = dynamic_cast(writer); if(NULL != urlWriter) { urlWriter->setRefSeqLength(ctx->refLength); } } Ebwt* ebwtBw = NULL; // We need the mirror index if mismatches are allowed if(ctx->mismatches > 0 || ctx->maqLike) { if(ctx->verbose || ctx->startVerbose) { cerr << "About to initialize rev Ebwt: "; logTime(cerr, true); } ebwtBw = new Ebwt(ctx->adjustedEbwtFileBase + ".rev", ctx->color, // index is colorspace -1, // don't care about entireReverse false, // index is for the reverse direction /* overriding: */ ctx->offRate, /* overriding: */ ctx->isaRate, ctx->useMm, // whether to use memory-mapped files ctx->useShmem, // whether to use shared memory ctx->mmSweep, // sweep memory-mapped files !ctx->noRefNames, // load names? rmap, // reference map, or NULL if none is needed ctx->verbose, // whether to be talkative ctx->startVerbose, // talkative during initialization false /*passMemExc*/, ctx->sanityCheck); } if(!os.empty()) { for(size_t i = 0; i < os.size(); i++) { size_t olen = seqan::length(os[i]); int longestStretch = 0; int curStretch = 0; for(size_t j = 0; j < olen; j++) { if((int)os[i][j] < 4) { curStretch++; if(curStretch > longestStretch) longestStretch = curStretch; } else { curStretch = 0; } } if(longestStretch < (ctx->color ? 2 : 1)) { os.erase(os.begin() + i); i--; } } } if(ctx->sanityCheck && !os.empty()) { // Sanity check number of patterns and pattern lengths in Ebwt // against original strings assert_eq(os.size(), ebwt.nPat()); for(size_t i = 0; i < os.size(); i++) { assert_eq(length(os[i]), ebwt.plen()[i] + (ctx->color ? 1 : 0)); } ebwt.loadIntoMemory(ctx->color ? 1 : 0, -1, !ctx->noRefNames, ctx->startVerbose); ebwt.checkOrigs(os, ctx->color, false); ebwt.evictFromMemory(); } { Timer _t(cerr, "Time searching: ", ctx->timing); if(ctx->verbose || ctx->startVerbose) { cerr << "Creating HitSink: "; logTime(cerr, true); } // Set up hit sink; if sanityCheck && !os.empty() is true, // then instruct the sink to "retain" hits in a vector in // memory so that we can easily sanity check them later on HitSink *sink; RecalTable *table = NULL; if(ctx->recal) { table = new RecalTable(ctx->recalMaxCycle, ctx->recalMaxQual, ctx->recalQualShift); } vector* refnames = &ebwt.refnames(); if(ctx->noRefNames) refnames = NULL; sink = new MAlignmentHitSink(writer, fout, PASS_DUMP_FILES, false, ctx->sampleMax, table, refnames); if(ctx->verbose || ctx->startVerbose) { cerr << "Dispatching to search driver: "; logTime(cerr, true); } if(ctx->maqLike) { seededQualCutoffSearchFull(ctx->seedLen, ctx->qualThresh, ctx->seedMms, *patsrc, *sink, ebwt, // forward index *ebwtBw, // mirror index (not optional) os); // references, if available } else if(ctx->mismatches > 0) { if(ctx->mismatches == 1) { assert(ebwtBw != NULL); mismatchSearchFull(*patsrc, *sink, ebwt, *ebwtBw, os); } else if(ctx->mismatches == 2 || ctx->mismatches == 3) { twoOrThreeMismatchSearchFull(*patsrc, *sink, ebwt, *ebwtBw, os, ctx->mismatches == 2); } else { cerr << "Error: " << ctx->mismatches << " is not a supported number of mismatches" << endl; throw 1; } } else { // Search without mismatches // Note that --fast doesn't make a difference here because // we're only loading half of the index anyway exactSearch(*patsrc, *sink, ebwt, os); } // Evict any loaded indexes from memory if(ebwt.isInMemory()) { ebwt.evictFromMemory(); } if(ebwtBw != NULL) { delete ebwtBw; } if(!ctx->quiet) { sink->finish(ctx->hadoopOut); // end the hits section of the hit file } for(size_t i = 0; i < patsrcs_a.size(); i++) { assert(patsrcs_a[i] != NULL); delete patsrcs_a[i]; } for(size_t i = 0; i < patsrcs_b.size(); i++) { if(patsrcs_b[i] != NULL) { delete patsrcs_b[i]; } } for(size_t i = 0; i < patsrcs_ab.size(); i++) { if(patsrcs_ab[i] != NULL) { delete patsrcs_ab[i]; } } static_cast(sink)->commitResultMA(); delete patsrc; delete sink; delete amap; delete rmap; if(fout != NULL) delete fout; } } void driverAdapter(U2::BowtieReadsReader* reader, U2::BowtieReadsWriter* writer, const U2::GUrl& resultUrl, const char * type, const string& ebwtFileBase, const string& query, const vector& queries, const vector& qualities, const string& outfile) { driver > >(reader, writer, resultUrl, type, ebwtFileBase, query, queries, qualities, outfile); } ugene-1.9.8/src/plugins_3rdparty/bowtie/src/bowtie/formats.h0000644000175000017500000000172611651544326022624 0ustar ilyailya#ifndef FORMATS_H_ #define FORMATS_H_ #include #include /** * File-format constants and names */ enum file_format { FASTA = 1, FASTA_CONT, FASTQ, TAB_MATE, RAW, CMDLINE, INPUT_CHAIN, RANDOM }; static const std::string file_format_names[] = { "Invalid!", "FASTA", "FASTA sampling", "FASTQ", "Tabbed mated", "Raw", "Command line", "Chained", "Random" }; /** * Print the given read information as a FASTA record. */ static inline void printFastaRecord( std::ostream& o, const seqan::String& name, const seqan::String& seq) { //o << ">" << name << endl << seq << endl; } /** * Print the given read information as a FASTQ record. */ static inline void printFastqRecord( std::ostream& o, const seqan::String& name, const seqan::String& seq, const seqan::String& qual) { //o << "@" << name << endl << seq << endl << "+" << endl << qual << endl; } #endif /*FORMATS_H_*/ ugene-1.9.8/src/plugins_3rdparty/bowtie/src/bowtie/bitpack.h0000644000175000017500000000142111651544326022556 0ustar ilyailya#ifndef BITPACK_H_ #define BITPACK_H_ #include #include "assert_helpers.h" /** * Routines for marshalling 2-bit values into and out of 8-bit or * 32-bit hosts */ static inline void pack_2b_in_8b(const int two, uint8_t& eight, const int off) { assert_lt(two, 4); assert_lt(off, 4); eight |= (two << (off*2)); } static inline int unpack_2b_from_8b(const uint8_t eight, const int off) { assert_lt(off, 4); return ((eight >> (off*2)) & 0x3); } static inline void pack_2b_in_32b(const int two, uint32_t& thirty2, const int off) { assert_lt(two, 4); assert_lt(off, 16); thirty2 |= (two << (off*2)); } static inline int unpack_2b_from_32b(const uint32_t thirty2, const int off) { assert_lt(off, 16); return ((thirty2 >> (off*2)) & 0x3); } #endif /*BITPACK_H_*/ ugene-1.9.8/src/plugins_3rdparty/bowtie/src/bowtie/hit.cpp0000644000175000017500000002372411651544326022272 0ustar ilyailya#include "BowtieContext.h" #include "hit.h" #include "hit_set.h" #include "search_globals.h" using namespace std; using namespace seqan; /// Sort by text-id then by text-offset bool operator< (const Hit& a, const Hit& b) { return a.h < b.h; } /** * Report a batch of hits to a chaining file. */ void ChainingHitSink::reportHits(vector& hs) { size_t hssz = hs.size(); assert_gt(hssz, 0); assert_eq(0, hs[0].mate); // Convert vector into HitSet { // Critical section for output stream 0 HitSet s; Hit::toHitSet(hs, s, amap_); lock(0); s.serialize(out(0)); unlock(0); } { // Global critical section mainlock(); commitHits(hs); // Commit to recalibration table first_ = false; numReported_ += hssz; numAligned_++; mainunlock(); } } /** * Report a maxed-out read. Typically we do nothing, but we might * want to print a placeholder when output is chained. */ void ChainingHitSink::reportMaxed(vector& hs, PatternSourcePerThread& p) { HitSink::reportMaxed(hs, p); assert(!hs.empty()); int8_t loStrat = (strata_ ? hs.front().stratum : 0); HitSet s; p.bufa().toHitSet(s); s.maxedStratum = loStrat; lock(0); s.serialize(out(0)); unlock(0); } /** * Report an unaligned read. Typically we do nothing, but we might * want to print a placeholder when output is chained. */ void ChainingHitSink::reportUnaligned(PatternSourcePerThread& p) { HitSink::reportUnaligned(p); // Read is unaligned; just report a huge starting stratum HitSet s; p.bufa().toHitSet(s); lock(0); s.serialize(out(0)); unlock(0); } /** * Report a maxed-out read. */ void VerboseHitSink::reportMaxed(vector& hs, PatternSourcePerThread& p) { HitSink::reportMaxed(hs, p); if(sampleMax_) { RandomSource rand; rand.init(p.bufa().seed); assert_gt(hs.size(), 0); bool paired = hs.front().mate > 0; size_t num = 1; if(paired) { num = 0; int bestStratum = 999; for(size_t i = 0; i < hs.size()-1; i += 2) { int strat = min(hs[i].stratum, hs[i+1].stratum); if(strat < bestStratum) { bestStratum = strat; num = 1; } else if(strat == bestStratum) { num++; } } assert_leq(num, hs.size()); uint32_t r = rand.nextU32() % num; num = 0; for(size_t i = 0; i < hs.size()-1; i += 2) { int strat = min(hs[i].stratum, hs[i+1].stratum); if(strat == bestStratum) { if(num == r) { hs[i].oms = hs[i+1].oms = hs.size()/2; reportHits(hs, i, i+2); break; } num++; } } assert_eq(num, r); } else { for(size_t i = 1; i < hs.size(); i++) { assert_geq(hs[i].stratum, hs[i-1].stratum); if(hs[i].stratum == hs[i-1].stratum) num++; else break; } assert_leq(num, hs.size()); uint32_t r = rand.nextU32() % num; Hit& h = hs[r]; h.oms = hs.size(); reportHit(h, false); } } } /** * Append a verbose, readable hit to the given output stream. */ void VerboseHitSink::append(ostream& ss, const Hit& h, const vector* refnames, ReferenceMap *rmap, AnnotationMap *amap, bool fullRef, int partition, int offBase, bool colorSeq, bool colorQual, bool cost, const Bitset& suppress) { bool spill = false; int spillAmt = 0; uint32_t pdiv = 0xffffffff; uint32_t pmod = 0xffffffff; do { bool dospill = false; if(spill) { // The read spilled over a partition boundary and so // needs to be printed more than once spill = false; dospill = true; spillAmt++; } assert(!spill); size_t field = 0; bool firstfield = true; if(partition != 0) { int pospart = abs(partition); if(!suppress.test(field++)) { if(firstfield) firstfield = false; else ss << '\t'; // Output a partitioning key // First component of the key is the reference index if(refnames != NULL && rmap != NULL) { printUptoWs(ss, rmap->getName(h.h.first), !fullRef); } else if(refnames != NULL && h.h.first < refnames->size()) { printUptoWs(ss, (*refnames)[h.h.first], !fullRef); } else { ss << h.h.first; } } ostringstream ss2, ss3; // Next component of the key is the partition id if(!dospill) { pdiv = (h.h.second + offBase) / pospart; pmod = (h.h.second + offBase) % pospart; } assert_neq(0xffffffff, pdiv); assert_neq(0xffffffff, pmod); if(dospill) assert_gt(spillAmt, 0); ss2 << (pdiv + (dospill ? spillAmt : 0)); if(partition > 0 && (pmod + h.length()) >= ((uint32_t)pospart * (spillAmt + 1))) { // Spills into the next partition so we need to // output another alignment for that partition spill = true; } if(!suppress.test(field++)) { if(firstfield) firstfield = false; else ss << '\t'; // Print partition id with leading 0s so that Hadoop // can do lexicographical sort (modern Hadoop versions // seen to support numeric) string s2 = ss2.str(); size_t partDigits = 1; if(pospart >= 10) partDigits++; if(pospart >= 100) partDigits++; if(pospart >= 1000) partDigits++; if(pospart >= 10000) partDigits++; if(pospart >= 100000) partDigits++; for(size_t i = s2.length(); i < (10-partDigits); i++) { ss << "0"; } ss << s2.c_str(); } if(!suppress.test(field++)) { if(firstfield) firstfield = false; else ss << '\t'; // Print offset with leading 0s ss3 << (h.h.second + offBase); string s3 = ss3.str(); for(size_t i = s3.length(); i < 9; i++) { ss << "0"; } ss << s3; } if(!suppress.test(field++)) { if(firstfield) firstfield = false; else ss << '\t'; ss << (h.fw? "+":"-"); } // end if(partition != 0) } else { assert(!dospill); if(!suppress.test(field++)) { if(firstfield) firstfield = false; else ss << '\t'; ss << h.patName; } if(!suppress.test(field++)) { if(firstfield) firstfield = false; else ss << '\t'; ss << (h.fw? '+' : '-'); } if(!suppress.test(field++)) { if(firstfield) firstfield = false; else ss << '\t'; // .first is text id, .second is offset if(refnames != NULL && rmap != NULL) { printUptoWs(ss, rmap->getName(h.h.first), !fullRef); } else if(refnames != NULL && h.h.first < refnames->size()) { printUptoWs(ss, (*refnames)[h.h.first], !fullRef); } else { ss << h.h.first; } } if(!suppress.test(field++)) { if(firstfield) firstfield = false; else ss << '\t'; ss << (h.h.second + offBase); } // end else clause of if(partition != 0) } if(!suppress.test(field++)) { if(firstfield) firstfield = false; else ss << '\t'; const String* pat = &h.patSeq; if(h.color && colorSeq) pat = &h.colSeq; ss << *pat; } if(!suppress.test(field++)) { if(firstfield) firstfield = false; else ss << '\t'; const String* qual = &h.quals; if(h.color && colorQual) qual = &h.colQuals; ss << *qual; } if(!suppress.test(field++)) { if(firstfield) firstfield = false; else ss << '\t'; ss << h.oms; } if(!suppress.test(field++)) { if(firstfield) firstfield = false; else ss << '\t'; // Look for SNP annotations falling within the alignment map snpAnnots; const size_t len = length(h.patSeq); if(amap != NULL) { AnnotationMap::Iter ai = amap->lower_bound(h.h); for(; ai != amap->end(); ai++) { assert_geq(ai->first.first, h.h.first); if(ai->first.first != h.h.first) { // Different chromosome break; } if(ai->first.second >= h.h.second + len) { // Doesn't fall into alignment break; } if(ai->second.first != 'S') { // Not a SNP annotation continue; } size_t off = ai->first.second - h.h.second; if(!h.fw) off = len - off - 1; snpAnnots[off] = ai->second.second; } } // Output mismatch column bool firstmm = true; for (unsigned int i = 0; i < len; ++ i) { if(h.mms.test(i)) { // There's a mismatch at this position if (!firstmm) ss << ","; ss << i; // position assert_gt(h.refcs.size(), i); char refChar = toupper(h.refcs[i]); char qryChar = (h.fw ? h.patSeq[i] : h.patSeq[length(h.patSeq)-i-1]); assert_neq(refChar, qryChar); ss << ":" << refChar << ">" << qryChar; firstmm = false; } else if(snpAnnots.find(i) != snpAnnots.end()) { if (!firstmm) ss << ","; ss << i; // position char qryChar = (h.fw ? h.patSeq[i] : h.patSeq[length(h.patSeq)-i-1]); ss << "S:" << snpAnnots[i] << ">" << qryChar; firstmm = false; } } if(partition != 0 && firstmm) ss << '-'; } if(partition != 0) { // Fields addded as of Crossbow 0.1.4 if(!suppress.test(field++)) { if(firstfield) firstfield = false; else ss << '\t'; ss << (int)h.mate; } // Print label, or whole read name if label isn't found if(!suppress.test(field++)) { if(firstfield) firstfield = false; else ss << '\t'; int labelOff = -1; // If LB: field is present, print its value for(int i = 0; i < (int)seqan::length(h.patName)-3; i++) { if(h.patName[i] == 'L' && h.patName[i+1] == 'B' && h.patName[i+2] == ':' && ((i == 0) || h.patName[i-1] == ';')) { labelOff = i+3; for(int j = labelOff; j < (int)seqan::length(h.patName); j++) { if(h.patName[j] != ';') { ss << h.patName[j]; } else { break; } } } } // Otherwise, print the whole read name if(labelOff == -1) ss << h.patName; } } if(cost) { // Stratum if(!suppress.test(field++)) { if(firstfield) firstfield = false; else ss << '\t'; ss << (int)h.stratum; } // Cost if(!suppress.test(field++)) { if(firstfield) firstfield = false; else ss << '\t'; ss << (int)h.cost; } } if(BowtieContext::getSearchContext()->showSeed) { // Seed if(!suppress.test(field++)) { if(firstfield) firstfield = false; else ss << '\t'; ss << h.seed; } } ss << endl; } while(spill); } ugene-1.9.8/src/plugins_3rdparty/bowtie/src/bowtie/random_test.cpp0000644000175000017500000000164511651544326024023 0ustar ilyailya/* * random_test.cpp * * Created on: Dec 11, 2009 * Author: Ben Langmead */ #include #include #include "random_source.h" using namespace std; int main(void) { RandomSource rand; rand.init(0); uint32_t ts[32]; memset(ts, 0, 32*sizeof(uint32_t)); uint32_t r = rand.nextU32(); cout << "Without reseeding:" << endl; for(int i = 0; i < 10000; i++) { uint32_t nr = rand.nextU32(); for(int j = 0; j < 32; j++) { if(((r >> j) & 1) != ((nr >> j) & 1)) { ts[j]++; } } } for(int j = 0; j < 32; j++) { cout << ts[j] << endl; } memset(ts, 0, 32*sizeof(uint32_t)); rand.init(0); r = rand.nextU32(); cout << "With reseeding:" << endl; for(int i = 0; i < 10000; i++) { rand.init(i+1); uint32_t nr = rand.nextU32(); for(int j = 0; j < 32; j++) { if(((r >> j) & 1) != ((nr >> j) & 1)) { ts[j]++; } } } for(int j = 0; j < 32; j++) { cout << ts[j] << endl; } } ugene-1.9.8/src/plugins_3rdparty/bowtie/src/bowtie/tokenize.h0000644000175000017500000000214411651544326022774 0ustar ilyailya/* * tokenize.h * * Created on: Jul 21, 2009 * Author: Ben Langmead */ #ifndef TOKENIZE_H_ #define TOKENIZE_H_ #include #include #include using namespace std; /** * Split string s according to given delimiters. Mostly borrowed * from C++ Programming HOWTO 7.3. */ static inline void tokenize(const string& s, const string& delims, vector& ss, size_t max = 9999) { string::size_type lastPos = s.find_first_not_of(delims, 0); string::size_type pos = s.find_first_of(delims, lastPos); while (string::npos != pos || string::npos != lastPos) { ss.push_back(s.substr(lastPos, pos - lastPos)); lastPos = s.find_first_not_of(delims, pos); pos = s.find_first_of(delims, lastPos); if(ss.size() == (max - 1)) { pos = string::npos; } } } static inline void tokenize( const std::string& s, char delim, std::vector& ss) { std::string token; std::istringstream iss(s); while(getline(iss, token, delim)) { ss.push_back(token); } } #endif /*TOKENIZE_H_*/ ugene-1.9.8/src/plugins_3rdparty/bowtie/src/bowtie/pat.cpp0000644000175000017500000001007211651544326022262 0ustar ilyailya#include #include #include #include #include #include #include "pat.h" #include "filebuf.h" #include "BowtieContext.h" using namespace std; using namespace seqan; /** * Parse a single quality string from fb and store qualities in r. * Assume the next character obtained via fb.get() is the first * character of the quality string. When returning, the next * character returned by fb.peek() or fb.get() should be the first * character of the following line. */ int parseQuals(ReadBuf& r, FileBuf& fb, int readLen, int trim3, int trim5, bool intQuals, bool phred64, bool solexa64) { int qualsRead = 0; int c = 0; assert(fb.peek() != '\n' && fb.peek() != '\r'); _setBegin (r.qual, (char*)r.qualBuf); _setLength(r.qual, 0); if (intQuals) { while (c != '\r' && c != '\n' && c != -1) { bool neg = false; int num = 0; while(!isspace(c = fb.peek()) && !fb.eof()) { if(c == '-') { neg = true; assert_eq(num, 0); } else { if(!isdigit(c)) { char buf[2048]; cerr << "Warning: could not parse quality line:" << endl; fb.getPastNewline(); cerr << fb.copyLastN(buf); buf[2047] = '\0'; cerr << buf; throw 1; } assert(isdigit(c)); num *= 10; num += (c - '0'); } fb.get(); } if(neg) num = 0; // Phred-33 ASCII encode it and add it to the back of the // quality string r.qualBuf[qualsRead++] = ('!' + num); // Skip over next stretch of whitespace c = fb.peek(); while(c != '\r' && c != '\n' && isspace(c) && !fb.eof()) { fb.get(); c = fb.peek(); } } } else { while (c != '\r' && c != '\n' && c != -1) { c = fb.get(); r.qualBuf[qualsRead++] = charToPhred33(c, solexa64, phred64); c = fb.peek(); while(c != '\r' && c != '\n' && isspace(c) && !fb.eof()) { fb.get(); c = fb.peek(); } } } if (qualsRead < readLen-1 || (qualsRead < readLen && !r.color)) { tooFewQualities(r.name); } qualsRead -= trim3; if(qualsRead <= 0) return 0; int trimmedReadLen = readLen-trim3-trim5; if(trimmedReadLen < 0) trimmedReadLen = 0; if(qualsRead > trimmedReadLen) { // Shift everybody left for(int i = 0; i < readLen; i++) { r.qualBuf[i] = r.qualBuf[i+qualsRead-trimmedReadLen]; } } _setLength(r.qual, trimmedReadLen); while(fb.peek() == '\n' || fb.peek() == '\r') fb.get(); return qualsRead; } void wrongQualityFormat(const String& read_name) { cerr << "Encountered a space parsing the quality string for read " << read_name << endl << "If this is a FASTQ file with integer (non-ASCII-encoded) qualities, please" << endl << "re-run Bowtie with the --integer-quals option. If this is a FASTQ file with" << endl << "alternate basecall information, please re-run Bowtie with the --fuzzy option." << endl; throw 1; } void tooFewQualities(const String& read_name) { cerr << "Too few quality values for read: " << read_name << endl << "\tare you sure this is a FASTQ-int file?" << endl; throw 1; } void tooManyQualities(const String& read_name) { cerr << "Reads file contained a pattern with more than 1024 quality values." << endl << "Please truncate reads and quality values and and re-run Bowtie" << endl; throw 1; } void tooManySeqChars(const String& read_name) { ostringstream ss; ss << "Reads file contained a pattern with more than 1024 sequence characters." << endl << "Please truncate reads and quality values and and re-run Bowtie." << endl << "Offending read: " << read_name << endl; throw BowtieException(ss.str()); } /** * C++ version char* style "itoa": */ char* itoa10(int value, char* result) { // Check that base is valid char* out = result; int quotient = value; do { *out = "0123456789"[ std::abs( quotient % 10 ) ]; ++out; quotient /= 10; } while ( quotient ); // Only apply negative sign for base 10 if (value < 0) *out++ = '-'; std::reverse( result, out ); *out = 0; // terminator return out; } ugene-1.9.8/src/plugins_3rdparty/bowtie/src/bowtie/pool.h0000644000175000017500000002137411651544326022123 0ustar ilyailya/* * pool.h */ #ifndef POOL_H_ #define POOL_H_ #include #include #include #include #include #include "bitset.h" #include "log.h" #include "search_globals.h" //#include "BowtieContext.h" /** * Very simple allocator for fixed-size chunks of memory. Chunk size * is set at construction time. Heap memory is only allocated at * construction and deallocated at destruction. */ class ChunkPool { public: /** * Initialize a new pool with an initial size of about 'bytes' * bytes. Exit with an error message if we can't allocate it. */ ChunkPool(uint32_t chunkSz, uint32_t totSz, bool verbose_) : verbose(verbose_), patid(0), pool_(NULL), cur_(0), chunkSz_(chunkSz), totSz_(totSz), lim_(totSz/chunkSz), bits_(lim_), exhaustCrash_(false), lastSkippedRead_(0xffffffff), readName_(NULL) { assert_gt(lim_, 0); try { if((pool_ = new int8_t[totSz_]) == NULL) { throw std::bad_alloc(); } } catch(std::bad_alloc& e) { ThreadSafe _ts(&(BowtieContext::getSearchContext()->gLock)); std::cerr << "Error: Could not allocate ChunkPool of " << totSz << " bytes" << std::endl; exhausted(); throw 1; // Exit if we haven't already } } /** * Delete all the pools. */ ~ChunkPool() { if(pool_ != NULL) delete[] pool_; } /** * Reset the pool, freeing all arrays that had been given out. */ void reset(String* name, uint32_t patid_) { patid = patid_; readName_ = name; cur_ = 0; bits_.clear(); assert_eq(0, bits_.test(0)); } /** * Return our current position. */ uint32_t pos() { return cur_; } /** * Return our current position. */ uint32_t remaining() { assert_geq(lim_, cur_); return lim_ - cur_; } /** * Allocate a single T from the pool. */ void* alloc() { assert_lt(cur_, lim_); uint32_t cur = cur_; while(bits_.test(cur)) { cur++; if(cur >= lim_) { cur = 0; } if(cur == cur_) { // Wrapped all the way around without finding a free // chunk return NULL; } } void * ptr = (void *)(&pool_[cur * chunkSz_]); assert(!bits_.test(cur)); bits_.set(cur); assert(bits_.test(cur)); if(verbose) { stringstream ss; ss << patid << ": Allocating chunk with offset: " << cur; BowtieContext::getContext()->glog.msg(ss.str()); } cur_ = cur; return ptr; } /** * */ void free(void *ptr) { uint32_t off = (uint32_t)((int8_t*)ptr - pool_); assert_eq(0, off % chunkSz_); off /= chunkSz_; if(verbose) { stringstream ss; ss << patid << ": Freeing chunk with offset: " << cur_; BowtieContext::getContext()->glog.msg(ss.str()); } bits_.clear(off); } /** * */ uint32_t chunkSize() const { return chunkSz_; } /** * */ uint32_t totalSize() const { return totSz_; } /** * Utility function to call when memory has been exhausted. * Currently just prints a friendly message and quits. */ void exhausted() { bool &quiet = (BowtieContext::getSearchContext()->quiet); if(patid != lastSkippedRead_) { if(!exhaustCrash_ && !quiet) std::cerr << "Warning: "; if(!quiet) { std::cerr << "Exhausted best-first chunk memory for read " << (*readName_) << " (patid " << patid << "); skipping read" << std::endl; } if(exhaustCrash_) { if(!quiet) { std::cerr << "Please try specifying a larger --chunkmbs (default is 32)" << std::endl; } throw 1; } } lastSkippedRead_ = patid; } bool verbose; uint32_t patid; protected: int8_t* pool_; /// the memory pools uint32_t cur_; /// index of next free element of pool_ const uint32_t chunkSz_; const uint32_t totSz_; uint32_t lim_; /// # elements held in pool_ FixedBitset2 bits_; bool exhaustCrash_; /// abort hard when memory's exhausted? uint32_t lastSkippedRead_; String* readName_; }; /** * Class for managing a pool of memory from which items of type T * (which must have a default constructor) are allocated. Does not * support freeing or resizing individual items - just allocation and * then freeing all items at once. */ template class AllocOnlyPool { typedef std::pair U32Pair; public: /** * Initialize a new pool with an initial size of about 'bytes' * bytes. Exit with an error message if we can't allocate it. */ AllocOnlyPool(ChunkPool* pool, const char *name) : pool_(pool), name_(name), curPool_(0), cur_(0) { assert(pool != NULL); lim_ = pool->chunkSize() / sizeof(T); assert_gt(lim_, 0); assert_gt(lim_, 1024); } /** * Reset the pool, freeing all arrays that had been given out. */ void reset() { pools_.clear(); lastCurInPool_.clear(); cur_ = 0; curPool_ = 0; } /** * Allocate a single T from the pool. */ T* alloc() { if(!lazyInit()) return NULL; if(cur_ + 1 >= lim_) { if(!allocNextPool()) return NULL; } cur_ ++; return &pools_[curPool_][cur_ - 1]; } /** * Allocate a single T from the pool and clear it. */ T* allocC() { T* t = alloc(); if(t != NULL) { memset(t, 0, sizeof(T)); } return t; } /** * Allocate an array of Ts from the pool. */ T* alloc(uint32_t num) { if(!lazyInit()) return NULL; if(cur_ + num >= lim_) { if(!allocNextPool()) return NULL; assert_eq(0, cur_); } assert_leq(num, lim_); cur_ += num; return &pools_[curPool_][cur_ - num]; } /** * Allocate an array of Ts and clear them. */ T* allocC(uint32_t num) { T* t = alloc(num); if(t != NULL) { memset(t, 0, sizeof(T) * num); } return t; } /** * Return the current pool. */ uint32_t curPool() const { return curPool_; } /** * Return the current position within the current pool. */ uint32_t cur() const { return cur_; } /** * Free a pointer allocated from this pool. Fow, we only know how * to free the topmost element. */ void free(T* t) { assert(t != NULL); if(pool_->verbose) { stringstream ss; ss << pool_->patid << ": Freeing a " << name_; BowtieContext::getContext()->glog.msg(ss.str()); } if(cur_ > 0 && t == &pools_[curPool_][cur_-1]) { cur_--; ASSERT_ONLY(memset(&pools_[curPool_][cur_], 0, sizeof(T))); if(cur_ == 0 && curPool_ > 0) { rewindPool(); } } } /** * Free an array of pointers allocated from this pool. For now, we * only know how to free the topmost array. */ bool free(T* t, uint32_t num) { assert(t != NULL); if(pool_->verbose) { stringstream ss; ss << pool_->patid << ": Freeing " << num << " " << name_ << "s"; BowtieContext::getContext()->glog.msg(ss.str()); } if(num <= cur_ && t == &pools_[curPool_][cur_ - num]) { cur_ -= num; ASSERT_ONLY(memset(&pools_[curPool_][cur_], 0, num * sizeof(T))); if(cur_ == 0 && curPool_ > 0) { rewindPool(); } return true; // deallocated } return false; // didn't deallocate } /** * Return a unique (with respect to every other object allocated * from this pool) identifier for the last object that was just * allocated. */ uint32_t lastId() const { return (curPool_ << 16) | cur_; } #ifndef NDEBUG bool empty() const { assert(pools_.empty()); assert_eq(0, cur_); assert_eq(0, curPool_); return true; } #endif protected: bool allocNextPool() { assert_eq(curPool_+1, pools_.size()); T *pool; try { if((pool = (T*)pool_->alloc()) == NULL) { throw std::bad_alloc(); } } catch(std::bad_alloc& e) { ThreadSafe _ts(&(BowtieContext::getSearchContext()->gLock)); pool_->exhausted(); return false; } ASSERT_ONLY(memset(pool, 0, lim_ * sizeof(T))); pools_.push_back(pool); lastCurInPool_.push_back(cur_); curPool_++; cur_ = 0; return true; } bool lazyInit() { if(cur_ == 0 && pools_.empty()) { T *pool; try { if((pool = (T*)pool_->alloc()) == NULL) { throw std::bad_alloc(); } } catch(std::bad_alloc& e) { ThreadSafe _ts(&(BowtieContext::getSearchContext()->gLock)); pool_->exhausted(); return false; } ASSERT_ONLY(memset(pool, 0, lim_ * sizeof(T))); pools_.push_back(pool); assert_eq(1, pools_.size()); } assert(!pools_.empty()); return true; } void rewindPool() { assert_eq(curPool_+1, pools_.size()); assert_eq(curPool_, lastCurInPool_.size()); if(pool_->verbose) { stringstream ss; ss << pool_->patid << ": Freeing a " << name_ << " pool"; BowtieContext::getContext()->glog.msg(ss.str()); } pool_->free(pools_.back()); pools_.pop_back(); curPool_--; assert_gt(lastCurInPool_.size(), 0); cur_ = lastCurInPool_.back(); lastCurInPool_.pop_back(); } ChunkPool* pool_; const char *name_; std::vector pools_; /// the memory pools uint32_t curPool_; /// pool we're current allocating from std::vector lastCurInPool_; uint32_t lim_; /// # elements held in pool_ uint32_t cur_; /// index of next free element of pool_ }; #endif /* POOL_H_ */ ugene-1.9.8/src/plugins_3rdparty/bowtie/src/bowtie/diff_sample.h0000644000175000017500000007353511651544326023431 0ustar ilyailya#ifndef DIFF_SAMPLE_H_ #define DIFF_SAMPLE_H_ #include #include #include // for LarssonSadakane #include "assert_helpers.h" #include "multikey_qsort.h" #include "timer.h" #include "auto_array.h" #include "BowtieContext.h" using namespace std; using namespace seqan; #ifdef _MSC_VER #ifndef VMSG_NL #define VMSG_NL(args, ...) \ if(this->verbose()) { \ stringstream tmp; \ tmp << args << endl; \ BowtieContext::verbose(tmp.str()); \ } #endif #ifndef VMSG #define VMSG(args, ...) \ if(this->verbose()) { \ stringstream tmp; \ tmp << args; \ BowtieContext::verbose(tmp.str()); \ } #endif #else #ifndef VMSG_NL #define VMSG_NL(args...) \ if(this->verbose()) { \ stringstream tmp; \ tmp << args << endl; \ BowtieContext::verbose(tmp.str()); \ } #endif #ifndef VMSG #define VMSG(args...) \ if(this->verbose()) { \ stringstream tmp; \ tmp << args; \ BowtieContext::verbose(tmp.str()); \ } #endif #endif /** * Routines for calculating, sanity-checking, and dispensing difference * cover samples to clients. */ /** * */ /*struct sampleEntry { uint32_t maxV; uint32_t numSamples; uint32_t samples[128]; };*/ typedef BowtieContext::Build::sampleEntry sampleEntry; /// Array of Colbourn and Ling calculated difference covers up to /// r = 16 (maxV = 5953) /** * Check that the given difference cover 'ds' actually covers all * differences for a periodicity of v. */ template static bool dcRepOk(T v, String& ds) { // diffs[] records all the differences observed bool *covered = new bool[v]; for(T i = 1; i < v; i++) { covered[i] = false; } for(T di = T(); di < length(ds); di++) { for(T dj = di+1; dj < length(ds); dj++) { assert_lt(ds[di], ds[dj]); T d1 = (ds[dj] - ds[di]); T d2 = (ds[di] + v - ds[dj]); assert_lt(d1, v); assert_lt(d2, v); covered[d1] = true; covered[d2] = true; } } bool ok = true; for(T i = 1; i < v; i++) { if(covered[i] == false) { ok = false; break; } } delete[] covered; return ok; } /** * Return true iff each element of ts (with length 'limit') is greater * than the last. */ template static bool increasing(T* ts, size_t limit) { for(size_t i = 0; i < limit-1; i++) { if(ts[i+1] <= ts[i]) return false; } return true; } /** * Return true iff the given difference cover covers difference 'diff' * mod 'v'. */ template static inline bool hasDifference(T *ds, T d, T v, T diff) { // diffs[] records all the differences observed for(T di = T(); di < d; di++) { for(T dj = di+1; dj < d; dj++) { assert_lt(ds[di], ds[dj]); T d1 = (ds[dj] - ds[di]); T d2 = (ds[di] + v - ds[dj]); assert_lt(d1, v); assert_lt(d2, v); if(d1 == diff || d2 == diff) return true; } } return false; } /** * Exhaustively calculate optimal difference cover samples for v = 4, * 8, 16, 32, 64, 128, 256 and store results in p2DCs[] */ template void calcExhaustiveDC(T i, bool verbose = false, bool sanityCheck = false) { T v = i; bool *diffs = new bool[v]; // v is the target period T ld = (T)ceil(sqrt(v)); // ud is the upper bound on |D| T ud = v / 2; // for all possible |D|s bool ok = true; T *ds = NULL; T d; for(d = ld; d <= ud+1; d++) { // for all possible |D| samples ds = new T[d]; for(T j = 0; j < d; j++) { ds[j] = j; } assert(increasing(ds, d)); while(true) { // reset diffs[] for(T t = 1; t < v; t++) { diffs[t] = false; } T diffCnt = 0; // diffs[] records all the differences observed for(T di = 0; di < d; di++) { for(T dj = di+1; dj < d; dj++) { assert_lt(ds[di], ds[dj]); T d1 = (ds[dj] - ds[di]); T d2 = (ds[di] + v - ds[dj]); assert_lt(d1, v); assert_lt(d2, v); assert_gt(d1, 0); assert_gt(d2, 0); if(!diffs[d1]) diffCnt++; diffs[d1] = true; if(!diffs[d2]) diffCnt++; diffs[d2] = true; } } // Do we observe all possible differences (except 0) ok = diffCnt == v-1; if(ok) { // Yes, all differences are covered break; } else { // Advance ds // (Following is commented out because it turns out // it's slow) // Find a missing difference //uint32_t missing = 0xffffffff; //for(uint32_t t = 1; t < v; t++) { // if(diffs[t] == false) { // missing = diffs[t]; // break; // } //} //assert_neq(missing, 0xffffffff); assert(increasing(ds, d)); bool advanced = false; bool keepGoing = false; do { keepGoing = false; for(T bd = d-1; bd > 1; bd--) { T dif = (d-1)-bd; if(ds[bd] < v-1-dif) { ds[bd]++; assert_neq(0, ds[bd]); // Reset subsequent ones for(T bdi = bd+1; bdi < d; bdi++) { assert_eq(0, ds[bdi]); ds[bdi] = ds[bdi-1]+1; assert_gt(ds[bdi], ds[bdi-1]); } assert(increasing(ds, d)); // (Following is commented out because // it turns out it's slow) // See if the new DC has the missing value //if(!hasDifference(ds, d, v, missing)) { // keepGoing = true; // break; //} advanced = true; break; } else { ds[bd] = 0; // keep going } } } while(keepGoing); // No solution for this |D| if(!advanced) break; assert(increasing(ds, d)); } } // next sample assignment if(ok) { break; } delete[] ds; } // next |D| assert(ok); delete[] diffs; cout << "Did exhaustive v=" << v << " |D|=" << d << endl; cout << " "; for(T i = 0; i < d; i++) { cout << ds[i]; if(i < d-1) cout << ","; } cout << endl; delete[] ds; } /** * Routune for calculating the elements of clDCs up to r = 16 using the * technique of Colbourn and Ling. * * See http://citeseer.ist.psu.edu/211575.html */ template void calcColbournAndLingDCs(bool verbose = false, bool sanityCheck = false) { BowtieContext::Build* ctx = BowtieContext::getBuildContext(); bool &clDCs_calced = ctx->clDCs_calced; sampleEntry (&clDCs)[16] = ctx->clDCs; for(T r = 0; r < 16; r++) { T maxv = 24*r*r + 36*r + 13; // Corollary 2.3 T numsamp = 6*r + 4; clDCs[r].maxV = maxv; clDCs[r].numSamples = numsamp; memset(clDCs[r].samples, 0, 4 * 128); T i; // clDCs[r].samples[0] = 0; // Fill in the 1^r part of the B series for(i = 1; i < r+1; i++) { clDCs[r].samples[i] = clDCs[r].samples[i-1] + 1; } // Fill in the (r + 1)^1 part clDCs[r].samples[r+1] = clDCs[r].samples[r] + r + 1; // Fill in the (2r + 1)^r part for(i = r+2; i < r+2+r; i++) { clDCs[r].samples[i] = clDCs[r].samples[i-1] + 2*r + 1; } // Fill in the (4r + 3)^(2r + 1) part for(i = r+2+r; i < r+2+r+2*r+1; i++) { clDCs[r].samples[i] = clDCs[r].samples[i-1] + 4*r + 3; } // Fill in the (2r + 2)^(r + 1) part for(i = r+2+r+2*r+1; i < r+2+r+2*r+1+r+1; i++) { clDCs[r].samples[i] = clDCs[r].samples[i-1] + 2*r + 2; } // Fill in the last 1^r part for(i = r+2+r+2*r+1+r+1; i < r+2+r+2*r+1+r+1+r; i++) { clDCs[r].samples[i] = clDCs[r].samples[i-1] + 1; } assert_eq(i, numsamp); assert_lt(i, 128); if(sanityCheck) { // diffs[] records all the differences observed bool *diffs = new bool[maxv]; for(T i = 0; i < numsamp; i++) { for(T j = i+1; j < numsamp; j++) { T d1 = (clDCs[r].samples[j] - clDCs[r].samples[i]); T d2 = (clDCs[r].samples[i] + maxv - clDCs[r].samples[j]); assert_lt(d1, maxv); assert_lt(d2, maxv); diffs[d1] = true; diffs[d2] = true; } } // Should have observed all possible differences (except 0) for(T i = 1; i < maxv; i++) { if(diffs[i] == false) cout << r << ", " << i << endl; assert(diffs[i] == true); } delete[] diffs; } } clDCs_calced = true; } /** * Entries 4-57 are transcribed from page 6 of Luk and Wong's paper * "Two New Quorum Based Algorithms for Distributed Mutual Exclusion", * which is also used and cited in the Burkhardt and Karkkainen's * papers on difference covers for sorting. These samples are optimal * according to Luk and Wong. * * All other entries are generated via the exhaustive algorithm in * calcExhaustiveDC(). * * The 0 is stored at the end of the sample as an end-of-list marker, * but 0 is also an element of each. * * Note that every difference cover has a 0 and a 1. Intuitively, * any optimal difference cover sample can be oriented (i.e. rotated) * such that it includes 0 and 1 as elements. * * All samples in this list have been verified to be complete covers. * * A value of 0xffffffff in the first column indicates that there is no * sample for that value of v. We do not keep samples for values of v * less than 3, since they are trivial (and the caller probably didn't * mean to ask for it). */ static uint32_t dc0to64[65][10] = { {0xffffffff}, // 0 {0xffffffff}, // 1 {0xffffffff}, // 2 {1, 0}, // 3 {1, 2, 0}, // 4 {1, 2, 0}, // 5 {1, 3, 0}, // 6 {1, 3, 0}, // 7 {1, 2, 4, 0}, // 8 {1, 2, 4, 0}, // 9 {1, 2, 5, 0}, // 10 {1, 2, 5, 0}, // 11 {1, 3, 7, 0}, // 12 {1, 3, 9, 0}, // 13 {1, 2, 3, 7, 0}, // 14 {1, 2, 3, 7, 0}, // 15 {1, 2, 5, 8, 0}, // 16 {1, 2, 4, 12, 0}, // 17 {1, 2, 5, 11, 0}, // 18 {1, 2, 6, 9, 0}, // 19 {1, 2, 3, 6, 10, 0}, // 20 {1, 4, 14, 16, 0}, // 21 {1, 2, 3, 7, 11, 0}, // 22 {1, 2, 3, 7, 11, 0}, // 23 {1, 2, 3, 7, 15, 0}, // 24 {1, 2, 3, 8, 12, 0}, // 25 {1, 2, 5, 9, 15, 0}, // 26 {1, 2, 5, 13, 22, 0}, // 27 {1, 4, 15, 20, 22, 0}, // 28 {1, 2, 3, 4, 9, 14, 0}, // 29 {1, 2, 3, 4, 9, 19, 0}, // 30 {1, 3, 8, 12, 18, 0}, // 31 {1, 2, 3, 7, 11, 19, 0}, // 32 {1, 2, 3, 6, 16, 27, 0}, // 33 {1, 2, 3, 7, 12, 20, 0}, // 34 {1, 2, 3, 8, 12, 21, 0}, // 35 {1, 2, 5, 12, 14, 20, 0}, // 36 {1, 2, 4, 10, 15, 22, 0}, // 37 {1, 2, 3, 4, 8, 14, 23, 0}, // 38 {1, 2, 4, 13, 18, 33, 0}, // 39 {1, 2, 3, 4, 9, 14, 24, 0}, // 40 {1, 2, 3, 4, 9, 15, 25, 0}, // 41 {1, 2, 3, 4, 9, 15, 25, 0}, // 42 {1, 2, 3, 4, 10, 15, 26, 0}, // 43 {1, 2, 3, 6, 16, 27, 38, 0}, // 44 {1, 2, 3, 5, 12, 18, 26, 0}, // 45 {1, 2, 3, 6, 18, 25, 38, 0}, // 46 {1, 2, 3, 5, 16, 22, 40, 0}, // 47 {1, 2, 5, 9, 20, 26, 36, 0}, // 48 {1, 2, 5, 24, 33, 36, 44, 0}, // 49 {1, 3, 8, 17, 28, 32, 38, 0}, // 50 {1, 2, 5, 11, 18, 30, 38, 0}, // 51 {1, 2, 3, 4, 6, 14, 21, 30, 0}, // 52 {1, 2, 3, 4, 7, 21, 29, 44, 0}, // 53 {1, 2, 3, 4, 9, 15, 21, 31, 0}, // 54 {1, 2, 3, 4, 6, 19, 26, 47, 0}, // 55 {1, 2, 3, 4, 11, 16, 33, 39, 0}, // 56 {1, 3, 13, 32, 36, 43, 52, 0}, // 57 // Generated by calcExhaustiveDC() {1, 2, 3, 7, 21, 33, 37, 50, 0}, // 58 {1, 2, 3, 6, 13, 21, 35, 44, 0}, // 59 {1, 2, 4, 9, 15, 25, 30, 42, 0}, // 60 {1, 2, 3, 7, 15, 25, 36, 45, 0}, // 61 {1, 2, 4, 10, 32, 39, 46, 51, 0}, // 62 {1, 2, 6, 8, 20, 38, 41, 54, 0}, // 63 {1, 2, 5, 14, 16, 34, 42, 59, 0} // 64 }; /** * Get a difference cover for the requested periodicity v. */ template static String getDiffCover(T v, bool verbose = false, bool sanityCheck = false) { BowtieContext::Build* ctx = BowtieContext::getBuildContext(); bool &clDCs_calced = ctx->clDCs_calced; sampleEntry (&clDCs)[16] = ctx->clDCs; assert_gt(v, 2); String ret; // Can we look it up in our hardcoded array? if(v <= 64 && dc0to64[v][0] == 0xffffffff) { if(verbose) cout << "v in hardcoded area, but hardcoded entry was all-fs" << endl; return ret; } else if(v <= 64) { append(ret, 0); for(size_t i = 0; i < 10; i++) { if(dc0to64[v][i] == 0) break; append(ret, dc0to64[v][i]); } if(sanityCheck) assert(dcRepOk(v, ret)); return ret; } // Can we look it up in our calcColbournAndLingDCs array? if(!clDCs_calced) { calcColbournAndLingDCs(verbose, sanityCheck); assert(clDCs_calced); } for(size_t i = 0; i < 16; i++) { if(v <= clDCs[i].maxV) { for(size_t j = 0; j < clDCs[i].numSamples; j++) { T s = clDCs[i].samples[j]; if(s >= v) { s %= v; for(size_t k = 0; k < length(ret); k++) { if(s == ret[k]) break; if(s < ret[k]) { insertValue(ret, k, s); break; } } } else { append(ret, s % v); } } if(sanityCheck) assert(dcRepOk(v, ret)); return ret; } } cerr << "Error: Could not find a difference cover sample for v=" << v << endl; throw 1; } /** * Calculate and return a delta map based on the given difference cover * and periodicity v. */ template static String getDeltaMap(T v, const String& dc) { // Declare anchor-map-related items String amap; size_t amapEnts = 1; fill(amap, v, 0xffffffff, Exact()); amap[0] = 0; // Print out difference cover (and optionally calculate // anchor map) for(size_t i = 0; i < length(dc); i++) { for(size_t j = i+1; j < length(dc); j++) { assert_gt(dc[j], dc[i]); T diffLeft = dc[j] - dc[i]; T diffRight = dc[i] + v - dc[j]; assert_lt(diffLeft, v); assert_lt(diffRight, v); if(amap[diffLeft] == 0xffffffff) { amap[diffLeft] = dc[i]; amapEnts++; } if(amap[diffRight] == 0xffffffff) { amap[diffRight] = dc[j]; amapEnts++; } } } return amap; } /** * Return population count (count of all bits set to 1) of i. */ template static unsigned int popCount(T i) { unsigned int cnt = 0; for(size_t j = 0; j < sizeof(T)*8; j++) { if(i & 1) cnt++; i >>= 1; } return cnt; } /** * Calculate log-base-2 of i */ template static unsigned int myLog2(T i) { assert_eq(1, popCount(i)); // must be power of 2 for(size_t j = 0; j < sizeof(T)*8; j++) { if(i & 1) return j; i >>= 1; } assert(false); return 0xffffffff; } /** * */ template class DifferenceCoverSample { public: DifferenceCoverSample(const TStr& __text, uint32_t __v, bool __verbose = false, bool __sanity = false, ostream& __logger = cout) : _text(__text), _v(__v), _verbose(__verbose), _sanity(__sanity), _ds(getDiffCover(_v, _verbose, _sanity)), _dmap(getDeltaMap(_v, _ds)), _d(length(_ds)), _doffs(), _isaPrime(), _dInv(), _log2v(myLog2(_v)), _vmask(0xffffffff << _log2v), _logger(__logger) { assert_gt(_d, 0); assert_eq(1, popCount(_v)); // must be power of 2 // Build map from d's to idx's fill(_dInv, _v, 0xffffffff, Exact()); for(size_t i = 0; i < length(_ds); i++) _dInv[_ds[i]] = i; } /** * Allocate an amount of memory that simulates the peak memory * usage of the DifferenceCoverSample with the given text and v. * Throws bad_alloc if it's not going to fit in memory. Returns * the approximate number of bytes the Cover takes at all times. */ static size_t simulateAllocs(const TStr& text, uint32_t v) { String ds = getDiffCover(v, false /*verbose*/, false /*sanity*/); size_t len = length(text); size_t sPrimeSz = (len / v) * length(ds); // sPrime, sPrimeOrder, _isaPrime all exist in memory at // once and that's the peak AutoArray aa(sPrimeSz * 3 + (1024 * 1024 /*out of caution*/)); return sPrimeSz * 4; // sPrime array } uint32_t v() const { return _v; } uint32_t log2v() const { return _log2v; } uint32_t vmask() const { return _vmask; } uint32_t modv(uint32_t i) const { return i & ~_vmask; } uint32_t divv(uint32_t i) const { return i >> _log2v; } uint32_t d() const { return _d; } bool verbose() const { return _verbose; } bool sanityCheck() const { return _sanity; } const TStr& text() const { return _text; } const String& ds() const { return _ds; } const String& dmap() const { return _dmap; } ostream& log() const { return _logger; } void build(); uint32_t tieBreakOff(uint32_t i, uint32_t j) const; int64_t breakTie(uint32_t i, uint32_t j) const; bool isCovered(uint32_t i) const; uint32_t rank(uint32_t i) const; /** * Print out the suffix array such that every sample offset has its * rank filled in and every non-sample offset is shown as '-'. */ void print(ostream& out) { for(size_t i = 0; i < length(_text); i++) { if(isCovered(i)) { out << rank(i); } else { out << "-"; } if(i < length(_text)-1) { out << ","; } } out << endl; } private: void doBuiltSanityCheck() const; void buildSPrime(String& sPrime); bool built() const { return length(_isaPrime) > 0; } void verbose(const string& s) const { if(this->verbose()) { this->log() << s; this->log().flush(); } } const TStr& _text; // text to sample uint32_t _v; // periodicity of sample bool _verbose; // bool _sanity; // String _ds; // samples: idx -> d String _dmap; // delta map uint32_t _d; // |D| - size of sample String _doffs; // offsets into sPrime/isaPrime for each d idx String _isaPrime; // ISA' array String _dInv; // Map from d -> idx uint32_t _log2v; uint32_t _vmask; ostream& _logger; }; /** * Return true iff suffixes with offsets suf1 and suf2 out of host * string 'host' are identical up to depth 'v'. */ template static inline bool suffixLt(const TStr& host, uint32_t suf1, uint32_t suf2) { uint32_t hlen = length(host); assert_neq(suf1, suf2); uint32_t i = 0; while(suf1 + i < hlen && suf2 + i < hlen) { if(host[suf1+i] < host[suf2+i]) return true; if(host[suf1+i] > host[suf2+i]) return false; i++; } if(suf1 + i == hlen) { assert_lt(suf2 + i, hlen); return false; } assert_eq(suf2 + i, hlen); return true; } /** * Sanity-check the difference cover by first inverting _isaPrime then * checking that each successive suffix really is less than the next. */ template void DifferenceCoverSample::doBuiltSanityCheck() const { uint32_t v = this->v(); assert(built()); VMSG_NL(" Doing sanity check"); uint32_t added = 0; String sorted; fill(sorted, length(_isaPrime), 0xffffffff, Exact()); for(size_t di = 0; di < this->d(); di++) { uint32_t d = _ds[di]; size_t i = 0; for(size_t doi = _doffs[di]; doi < _doffs[di+1]; doi++, i++) { assert_eq(0xffffffff, sorted[_isaPrime[doi]]); // Maps the offset of the suffix to its rank sorted[_isaPrime[doi]] = v*i + d; added++; } } assert_eq(added, length(_isaPrime)); for(size_t i = 0; i < length(sorted)-1; i++) { assert(suffixLt(this->text(), sorted[i], sorted[i+1])); } } /** * Build the s' array by sampling suffixes (suffix offsets, actually) * from t according to the difference-cover sample and pack them into * an array of machine words in the order dictated by the "mu" mapping * described in Burkhardt. * * Also builds _doffs map. */ template void DifferenceCoverSample::buildSPrime(String& sPrime) { const TStr& t = this->text(); const String& ds = this->ds(); uint32_t tlen = length(t); uint32_t v = this->v(); uint32_t d = this->d(); assert_gt(v, 2); assert_lt(d, v); // Record where each d section should begin in sPrime uint32_t tlenDivV = this->divv(tlen); uint32_t tlenModV = this->modv(tlen); uint32_t sPrimeSz = 0; assert(empty(_doffs)); reserve(_doffs, d+1, Exact()); assert_eq(capacity(_doffs), d+1); for(uint32_t di = 0; di < d; di++) { // mu mapping uint32_t sz = tlenDivV + ((ds[di] <= tlenModV) ? 1 : 0); assert_geq(sz, 0); appendValue(_doffs, sPrimeSz); sPrimeSz += sz; } appendValue(_doffs, sPrimeSz); #ifndef NDEBUG if(tlenDivV > 0) { for(size_t i = 0; i < d; i++) { assert_gt(_doffs[i+1], _doffs[i]); uint32_t diff = _doffs[i+1] - _doffs[i]; assert(diff == tlenDivV || diff == tlenDivV+1); } } #endif assert_eq(length(_doffs), d+1); // Size sPrime appropriately reserve(sPrime, sPrimeSz+1, Exact()); // reserve extra slot for LS fill(sPrime, sPrimeSz, 0xffffffff, Exact()); // Slot suffixes from text into sPrime according to the mu // mapping; where the mapping would leave a blank, insert a 0 uint32_t added = 0; uint32_t i = 0; for(uint32_t ti = 0; ti <= tlen; ti += v) { for(uint32_t di = 0; di < d; di++) { uint32_t tti = ti + ds[di]; if(tti > tlen) break; uint32_t spi = _doffs[di] + i; assert_lt(spi, _doffs[di+1]); assert_leq(tti, tlen); assert_lt(spi, sPrimeSz); assert_eq(0xffffffff, sPrime[spi]); sPrime[spi] = tti; added++; } i++; } assert_eq(added, sPrimeSz); } /** * Return true iff suffixes with offsets suf1 and suf2 out of host * string 'host' are identical up to depth 'v'. */ template static inline bool suffixSameUpTo(const TStr& host, uint32_t suf1, uint32_t suf2, uint32_t v) { for(uint32_t i = 0; i < v; i++) { bool endSuf1 = suf1+i >= length(host); bool endSuf2 = suf2+i >= length(host); if((endSuf1 && !endSuf2) || (!endSuf1 && endSuf2)) return false; if(endSuf1 && endSuf2) return true; if(host[suf1+i] != host[suf2+i]) return false; } return true; } /** * Calculates a ranking of all suffixes in the sample and stores them, * packed according to the mu mapping, in _isaPrime. */ template void DifferenceCoverSample::build() { // Local names for relevant types typedef typename Value::Type TAlphabet; VMSG_NL("Building DifferenceCoverSample"); // Local names for relevant data const TStr& t = this->text(); uint32_t v = this->v(); assert_gt(v, 2); // Build s' String sPrime; VMSG_NL(" Building sPrime"); buildSPrime(sPrime); assert_gt(length(sPrime), 0); assert_leq(length(sPrime), length(t)+1); // +1 is because of the end-cap uint32_t nextRank = 0; { VMSG_NL(" Building sPrimeOrder"); String sPrimeOrder; reserve(sPrimeOrder, length(sPrime)+1, Exact()); // reserve extra slot for LS resize(sPrimeOrder, length(sPrime), Exact()); for(size_t i = 0; i < length(sPrimeOrder); i++) { sPrimeOrder[i] = i; } // sPrime now holds suffix-offsets for DC samples. { Timer timer(cout, " V-Sorting samples time: ", this->verbose()); VMSG_NL(" V-Sorting samples"); // Extract backing-store array from sPrime and sPrimeOrder; // the mkeyQSortSuf2 routine works on the array for maximum // efficiency uint32_t *sPrimeArr = (uint32_t*)begin(sPrime); size_t slen = length(sPrime); assert_eq(sPrimeArr[0], sPrime[0]); assert_eq(sPrimeArr[slen-1], sPrime[slen-1]); uint32_t *sPrimeOrderArr = (uint32_t*)begin(sPrimeOrder); assert_eq(sPrimeOrderArr[0], sPrimeOrder[0]); assert_eq(sPrimeOrderArr[slen-1], sPrimeOrder[slen-1]); // Sort sample suffixes up to the vth character using a // multikey quicksort. Sort time is proportional to the // number of samples times v. It isn't quadratic. // sPrimeOrder is passed in as a swapping partner for // sPrimeArr, i.e., every time the multikey qsort swaps // elements in sPrime, it swaps the same elements in // sPrimeOrder too. This allows us to easily reconstruct // what the sort did. mkeyQSortSuf2(t, sPrimeArr, slen, sPrimeOrderArr, ValueSize::VALUE, this->verbose(), this->sanityCheck(), v); // Make sure sPrime and sPrimeOrder are consistent with // their respective backing-store arrays assert_eq(sPrimeArr[0], sPrime[0]); assert_eq(sPrimeArr[slen-1], sPrime[slen-1]); assert_eq(sPrimeOrderArr[0], sPrimeOrder[0]); assert_eq(sPrimeOrderArr[slen-1], sPrimeOrder[slen-1]); } // Now assign the ranking implied by the sorted sPrime/sPrimeOrder // arrays back into sPrime. VMSG_NL(" Allocating rank array"); reserve(_isaPrime, length(sPrime)+1, Exact()); fill(_isaPrime, length(sPrime), 0xffffffff, Exact()); assert_gt(length(_isaPrime), 0); { Timer timer(cout, " Ranking v-sort output time: ", this->verbose()); VMSG_NL(" Ranking v-sort output"); for(size_t i = 0; i < length(sPrime)-1; i++) { // Place the appropriate ranking _isaPrime[sPrimeOrder[i]] = nextRank; // If sPrime[i] and sPrime[i+1] are identical up to v, then we // should give the next suffix the same rank if(!suffixSameUpTo(t, sPrime[i], sPrime[i+1], v)) nextRank++; } _isaPrime[sPrimeOrder[length(sPrime)-1]] = nextRank; // finish off } // sPrimeOrder is destroyed // All the information we need is now in _isaPrime } #ifndef NDEBUG // Check that all ranks are sane for(size_t i = 0; i < length(_isaPrime); i++) { assert_neq(_isaPrime[i], 0xffffffff); assert_lt(_isaPrime[i], length(_isaPrime)); } #endif // Now pass the sPrimeRanks[] array to LarssonSadakane (in SeqAn). append(_isaPrime, length(_isaPrime)); append(sPrime, length(sPrime)); { Timer timer(cout, " Invoking Larsson-Sadakane on ranks time: ", this->verbose()); VMSG_NL(" Invoking Larsson-Sadakane on ranks"); createSuffixArray(sPrime, _isaPrime, LarssonSadakane(), length(_isaPrime)); } // sPrime now contains the suffix array (which we ignore) assert_eq(length(_isaPrime), length(sPrime)); assert_gt(length(_isaPrime), 0); // chop off final character of _isaPrime resize(_isaPrime, length(_isaPrime)-1); // Subtract 1 from each isaPrime (to adjust for LarssonSadakane // always ranking the final suffix as lexicographically first) for(size_t i = 0; i < length(_isaPrime); i++) { _isaPrime[i]--; } VMSG_NL(" Sanity-checking and returning"); // done! //if(this->verbose()) print(cout); if(this->sanityCheck()) doBuiltSanityCheck(); } /** * Return true iff index i within the text is covered by the difference * cover sample. Allow i to be off the end of the text; simplifies * logic elsewhere. */ template bool DifferenceCoverSample::isCovered(uint32_t i) const { assert(built()); uint32_t modi = this->modv(i); assert_lt(modi, length(_dInv)); return _dInv[modi] != 0xffffffff; } /** * Given a text offset that's covered, return its lexicographical rank * among the sample suffixes. */ template uint32_t DifferenceCoverSample::rank(uint32_t i) const { assert(built()); assert_lt(i, length(this->text())); uint32_t imodv = this->modv(i); assert_neq(0xffffffff, _dInv[imodv]); // must be in the sample uint32_t ioff = this->divv(i); assert_lt(ioff, _doffs[_dInv[imodv]+1] - _doffs[_dInv[imodv]]); uint32_t isaIIdx = _doffs[_dInv[imodv]] + ioff; assert_lt(isaIIdx, length(_isaPrime)); uint32_t isaPrimeI = _isaPrime[isaIIdx]; assert_leq(isaPrimeI, length(_isaPrime)); return isaPrimeI; } /** * Return: < 0 if suffix i is lexicographically less than suffix j; > 0 * if suffix j is lexicographically greater. */ template int64_t DifferenceCoverSample::breakTie(uint32_t i, uint32_t j) const { assert(built()); assert_neq(i, j); assert_lt(i, length(this->text())); assert_lt(j, length(this->text())); uint32_t imodv = this->modv(i); uint32_t jmodv = this->modv(j); assert_neq(0xffffffff, _dInv[imodv]); // must be in the sample assert_neq(0xffffffff, _dInv[jmodv]); // must be in the sample uint32_t dimodv = _dInv[imodv]; uint32_t djmodv = _dInv[jmodv]; uint32_t ioff = this->divv(i); uint32_t joff = this->divv(j); assert_lt(dimodv+1, length(_doffs)); assert_lt(djmodv+1, length(_doffs)); // assert_lt: expected (32024) < (0) assert_lt(ioff, _doffs[dimodv+1] - _doffs[dimodv]); assert_lt(joff, _doffs[djmodv+1] - _doffs[djmodv]); uint32_t isaIIdx = _doffs[dimodv] + ioff; uint32_t isaJIdx = _doffs[djmodv] + joff; assert_lt(isaIIdx, length(_isaPrime)); assert_lt(isaJIdx, length(_isaPrime)); assert_neq(isaIIdx, isaJIdx); // ranks must be unique uint32_t isaPrimeI = _isaPrime[isaIIdx]; uint32_t isaPrimeJ = _isaPrime[isaJIdx]; assert_neq(isaPrimeI, isaPrimeJ); // ranks must be unique assert_leq(isaPrimeI, length(_isaPrime)); assert_leq(isaPrimeJ, length(_isaPrime)); return (int64_t)isaPrimeI - (int64_t)isaPrimeJ; } /** * Given i, j, return the number of additional characters that need to * be compared before the difference cover can break the tie. */ template uint32_t DifferenceCoverSample::tieBreakOff(uint32_t i, uint32_t j) const { const TStr& t = this->text(); const String& dmap = this->dmap(); assert(built()); // It's actually convenient to allow this, but we're permitted to // return nonsense in that case if(t[i] != t[j]) return 0xffffffff; //assert_eq(t[i], t[j]); // if they're unequal, there's no tie to break uint32_t v = this->v(); assert_neq(i, j); assert_lt(i, length(t)); assert_lt(j, length(t)); uint32_t imod = this->modv(i); uint32_t jmod = this->modv(j); uint32_t diffLeft = (jmod >= imod)? (jmod - imod) : (jmod + v - imod); uint32_t diffRight = (imod >= jmod)? (imod - jmod) : (imod + v - jmod); assert_lt(diffLeft, length(dmap)); assert_lt(diffRight, length(dmap)); uint32_t destLeft = dmap[diffLeft]; // offset where i needs to be uint32_t destRight = dmap[diffRight]; // offset where i needs to be assert(isCovered(destLeft)); assert(isCovered(destLeft+diffLeft)); assert(isCovered(destRight)); assert(isCovered(destRight+diffRight)); assert_lt(destLeft, v); assert_lt(destRight, v); uint32_t deltaLeft = (destLeft >= imod)? (destLeft - imod) : (destLeft + v - imod); if(deltaLeft == v) deltaLeft = 0; uint32_t deltaRight = (destRight >= jmod)? (destRight - jmod) : (destRight + v - jmod); if(deltaRight == v) deltaRight = 0; assert_lt(deltaLeft, v); assert_lt(deltaRight, v); assert(isCovered(i+deltaLeft)); assert(isCovered(j+deltaLeft)); assert(isCovered(i+deltaRight)); assert(isCovered(j+deltaRight)); return min(deltaLeft, deltaRight); } #endif /*DIFF_SAMPLE_H_*/ ugene-1.9.8/src/plugins_3rdparty/bowtie/src/bowtie/sequence_io.h0000644000175000017500000001242511651544326023446 0ustar ilyailya#ifndef SEQUENCE_IO_H_ #define SEQUENCE_IO_H_ #include #include #include #include #include #include #include #include "assert_helpers.h" #include "pat.h" /** * Read a sequence file of the given format and alphabet type. Store * all of the extracted sequences in vector ss. Note that SeqAn's * policy for when it encounters characters not from the specified * alphabet is to convert them to the lexicographically smallest * character in the alphabet. */ template static void readSequenceFile(const std::string& infile, std::vector& ss, int64_t& baseCutoff, // limit for total bases int seqCutoff = -1, // limit for sequences bool reverse = false) { typedef typename Value::Type TVal; static char buf[256 * 1024]; // fairly large input buffer if(baseCutoff <= 0) return; FILE *in = fopen(infile.c_str(), "r"); if(in == NULL) { cerr << "Could not open sequence file" << endl; throw 1; } // Associate large input buffer with FILE *in if(setvbuf(in, buf, _IOFBF, 256 * 1024) != 0) { cerr << "Could not create input buffer for sequence file" << endl; throw 1; } // Read entries using SeqAn int cnt = 0; while(!feof(in)) { while(true) { ss.push_back(TStr()); // add a new empty string to the end // Fill the new empty string with the next sequence from // the file. SeqAn allocates just enough mem for it (at // the expense of lots of file seeks, which can add up) seqan::read(in, ss.back(), TFile()); if(seqan::empty(ss.back())) { ss.pop_back(); break; } // Enforce the base cutoff if((int64_t)length(ss.back()) > baseCutoff) { resize(ss.back(), baseCutoff); baseCutoff = 0; } else { baseCutoff -= length(ss.back()); } // Reverse the newly-read sequence in-place if desired if(reverse) { size_t len = length(ss.back()); for(size_t i = 0; i < len/2; i++) { TVal t = ss.back()[i]; ss.back()[i] = ss.back()[len-i-1]; ss.back()[len-i-1] = t; } } #ifndef NDEBUG // Sanity check that all (int) values are in range for(size_t i = 0; i < length(ss.back()); i++) { assert_lt(ss.back()[i], (int)(ValueSize::VALUE)); assert_geq(ss.back()[i], 0); } #endif cnt++; // Enforce the sequence cutoff if(seqCutoff != -1 && cnt >= seqCutoff) { fclose(in); return; } } } fclose(in); } /** * Read a set of sequence files of the given format and alphabet type. * Store all of the extracted sequences in vector ss. */ template static void readSequenceFiles(const std::vector& infiles, std::vector& ss, int64_t& baseCutoff, int seqCutoff = -1, bool reverse = false) { for(size_t i = 0; i < infiles.size() && baseCutoff > 0; i++) { readSequenceFile(infiles[i], ss, baseCutoff, seqCutoff, reverse); if(baseCutoff <= 0) break; } } /** * Read a set of sequence files of the given format and alphabet type. * Store all of the extracted sequences in vector ss. */ template static void readSequenceFiles(const std::vector& infiles, std::vector& ss, int seqCutoff = -1, bool reverse = false) { int64_t i = 0xffffffffll; readSequenceFiles(infiles, ss, i, seqCutoff, reverse); } /** * Parse a comma-delimited list of strings of type T into a vector. */ template void readSequenceString(const std::string& s, std::vector& ss, int64_t& baseCutoff, int seqCutoff = -1, bool reverse = false) { // Split string s using comma as a delimiter. Borrowed from C++ // Programming HOWTO 7.3 std::string::size_type lastPos = s.find_first_not_of(",", 0); std::string::size_type pos = s.find_first_of(",", lastPos); while (baseCutoff > 0 && (std::string::npos != pos || std::string::npos != lastPos)) { string stmp = s.substr(lastPos, pos - lastPos); if((int64_t)stmp.length() < baseCutoff) { baseCutoff -= stmp.length(); } else { stmp = stmp.substr(0, baseCutoff); baseCutoff = 0; } if(reverse) { size_t len = stmp.length(); for(size_t i = 0; i < len/2; i++) { char tmp = stmp[i]; stmp[i] = stmp[len-i-1]; stmp[len-i-1] = tmp; } ss.push_back(T(stmp.c_str())); } else { ss.push_back(T(stmp.c_str())); } if(seqCutoff != -1 && ss.size() >= (size_t)seqCutoff) { return; } lastPos = s.find_first_not_of(",", pos); pos = s.find_first_of(",", lastPos); } } /** * Parse a comma-delimited list of strings of type T into a vector. * Doesn't require callee to supply a baseCutoff. */ template void readSequenceString(const std::string& s, std::vector& ss, int seqCutoff = -1, bool reverse = false) { int64_t i = 0xffffffffll; readSequenceString(s, ss, i, seqCutoff, reverse); } #endif /*SEQUENCE_IO_H_*/ ugene-1.9.8/src/plugins_3rdparty/bowtie/src/bowtie/chaincat.cpp0000644000175000017500000000117611651544326023255 0ustar ilyailya/* * chaincat.cpp * * Print out a chained-hit file. * * Created on: Jul 31, 2009 * Author: Ben Langmead */ #include #include #include "hit_set.h" #include "filebuf.h" using namespace std; int main(int argc, char **argv) { try { if(argc <= 1) { cerr << "Error: must specify chain file as first argument" << endl; return 1; } FILE *in = fopen(argv[1], "rb"); if(in == NULL) { cerr << "Could not open " << argv[1] << endl; return 1; } FileBuf fb(in); while(!fb.eof()) { HitSet s(fb); s.reportUpTo(cout); } fb.close(); } catch(std::exception& e) { return 1; } } ugene-1.9.8/src/plugins_3rdparty/bowtie/src/bowtie/aligner_0mm.h0000644000175000017500000002575011651544326023346 0ustar ilyailya/* * aligner_0mm.h */ #ifndef ALIGNER_0MM_H_ #define ALIGNER_0MM_H_ #include #include #include "aligner.h" #include "hit.h" #include "row_chaser.h" #include "range_chaser.h" /** * Concrete factory class for constructing unpaired exact aligners. */ class UnpairedExactAlignerV1Factory : public AlignerFactory { typedef RangeSourceDriver TRangeSrcDr; typedef std::vector TRangeSrcDrPtrVec; typedef CostAwareRangeSourceDriver TCostAwareRangeSrcDr; public: UnpairedExactAlignerV1Factory( Ebwt >& ebwtFw, Ebwt >* ebwtBw, bool doFw, bool doRc, HitSink& sink, const HitSinkPerThreadFactory& sinkPtFactory, RangeCache* cacheFw, RangeCache* cacheBw, uint32_t cacheLimit, ChunkPool *pool, BitPairReference* refs, vector >& os, bool maqPenalty, bool qualOrder, bool strandFix, bool rangeMode, bool verbose, bool quiet, uint32_t seed) : ebwtFw_(ebwtFw), ebwtBw_(ebwtBw), doFw_(doFw), doRc_(doRc), sink_(sink), sinkPtFactory_(sinkPtFactory), cacheFw_(cacheFw), cacheBw_(cacheBw), cacheLimit_(cacheLimit), pool_(pool), refs_(refs), os_(os), maqPenalty_(maqPenalty), qualOrder_(qualOrder), strandFix_(strandFix), rangeMode_(rangeMode), verbose_(verbose), quiet_(quiet), seed_(seed) { assert(ebwtFw.isInMemory()); } /** * Create a new UnpairedExactAlignerV1s. */ virtual Aligner* create() const { HitSinkPerThread* sinkPt = sinkPtFactory_.create(); EbwtSearchParams >* params = new EbwtSearchParams >(*sinkPt, os_, true, true); const int halfAndHalf = 0; const bool seeded = false; EbwtRangeSource *rFw = new EbwtRangeSource( &ebwtFw_, true, 0xffffffff, true, verbose_, quiet_, halfAndHalf, seeded, maqPenalty_, qualOrder_); EbwtRangeSource *rRc = new EbwtRangeSource( &ebwtFw_, false, 0xffffffff, true, verbose_, quiet_, halfAndHalf, seeded, maqPenalty_, qualOrder_); EbwtRangeSourceDriver * driverFw = new EbwtRangeSourceDriver( *params, rFw, true, false, maqPenalty_, qualOrder_, sink_, sinkPt, 0, // seedLen true, // nudgeLeft (not applicable) PIN_TO_LEN, // whole alignment is unrevisitable PIN_TO_LEN, // " PIN_TO_LEN, // " PIN_TO_LEN, // " os_, verbose_, quiet_, true, pool_, NULL); EbwtRangeSourceDriver * driverRc = new EbwtRangeSourceDriver( *params, rRc, false, false, maqPenalty_, qualOrder_, sink_, sinkPt, 0, // seedLen true, // nudgeLeft (not applicable) PIN_TO_LEN, // whole alignment is unrevisitable PIN_TO_LEN, // " PIN_TO_LEN, // " PIN_TO_LEN, // " os_, verbose_, quiet_, true, pool_, NULL); TRangeSrcDrPtrVec *drVec = new TRangeSrcDrPtrVec(); if(doFw_) drVec->push_back(driverFw); if(doRc_) drVec->push_back(driverRc); TCostAwareRangeSrcDr* dr = new TCostAwareRangeSrcDr(strandFix_, drVec, verbose_, quiet_, false); delete drVec; // Set up a RangeChaser RangeChaser > *rchase = new RangeChaser >(cacheLimit_, cacheFw_, cacheBw_); return new UnpairedAlignerV2( params, dr, rchase, sink_, sinkPtFactory_, sinkPt, os_, refs_, rangeMode_, verbose_, quiet_, INT_MAX, pool_, NULL, NULL); } private: Ebwt >& ebwtFw_; Ebwt >* ebwtBw_; bool doFw_; bool doRc_; HitSink& sink_; const HitSinkPerThreadFactory& sinkPtFactory_; RangeCache *cacheFw_; RangeCache *cacheBw_; const uint32_t cacheLimit_; ChunkPool *pool_; BitPairReference* refs_; vector >& os_; bool maqPenalty_; bool qualOrder_; bool strandFix_; bool rangeMode_; bool verbose_; bool quiet_; uint32_t seed_; }; /** * Concrete factory class for constructing unpaired exact aligners. */ class PairedExactAlignerV1Factory : public AlignerFactory { typedef RangeSourceDriver TRangeSrcDr; typedef CostAwareRangeSourceDriver TCostAwareRangeSrcDr; typedef std::vector TRangeSrcDrPtrVec; public: PairedExactAlignerV1Factory( Ebwt >& ebwtFw, Ebwt >* ebwtBw, bool color, bool doFw, bool doRc, bool v1, HitSink& sink, const HitSinkPerThreadFactory& sinkPtFactory, bool mate1fw, bool mate2fw, uint32_t peInner, uint32_t peOuter, bool dontReconcile, uint32_t symCeil, uint32_t mixedThresh, uint32_t mixedAttemptLim, RangeCache* cacheFw, RangeCache* cacheBw, uint32_t cacheLimit, ChunkPool *pool, BitPairReference* refs, vector >& os, bool reportSe, bool maqPenalty, bool strandFix, bool qualOrder, bool rangeMode, bool verbose, bool quiet, uint32_t seed) : ebwtFw_(ebwtFw), color_(color), doFw_(doFw), doRc_(doRc), v1_(v1), sink_(sink), sinkPtFactory_(sinkPtFactory), mate1fw_(mate1fw), mate2fw_(mate2fw), peInner_(peInner), peOuter_(peOuter), dontReconcile_(dontReconcile), symCeil_(symCeil), mixedThresh_(mixedThresh), mixedAttemptLim_(mixedAttemptLim), cacheFw_(cacheFw), cacheBw_(cacheBw), cacheLimit_(cacheLimit), pool_(pool), refs_(refs), os_(os), reportSe_(reportSe), maqPenalty_(maqPenalty), qualOrder_(qualOrder), strandFix_(strandFix), rangeMode_(rangeMode), verbose_(verbose), quiet_(quiet), seed_(seed) { assert(ebwtFw.isInMemory()); } /** * Create a new UnpairedExactAlignerV1s. */ virtual Aligner* create() const { HitSinkPerThread* sinkPt = sinkPtFactory_.createMult(2); HitSinkPerThread* sinkPtSe1 = NULL, * sinkPtSe2 = NULL; EbwtSearchParams >* params = new EbwtSearchParams >(*sinkPt, os_, true, true); EbwtSearchParams >* paramsSe1 = NULL, * paramsSe2 = NULL; if(reportSe_) { sinkPtSe1 = sinkPtFactory_.create(); sinkPtSe2 = sinkPtFactory_.create(); paramsSe1 = new EbwtSearchParams >(*sinkPtSe1, os_, true, true); paramsSe2 = new EbwtSearchParams >(*sinkPtSe2, os_, true, true); } const int halfAndHalf = 0; const bool seeded = false; bool do1Fw = true; bool do1Rc = true; bool do2Fw = true; bool do2Rc = true; if(!doFw_) { if(mate1fw_) do1Fw = false; else do1Rc = false; if(mate2fw_) do2Fw = false; else do2Rc = false; } if(!doRc_) { if(mate1fw_) do1Rc = false; else do1Fw = false; if(mate2fw_) do2Rc = false; else do2Fw = false; } EbwtRangeSource *r1Fw = NULL; EbwtRangeSource *r1Rc = NULL; TRangeSrcDr * driver1Fw = NULL; TRangeSrcDr * driver1Rc = NULL; EbwtRangeSource *r2Fw = NULL; EbwtRangeSource *r2Rc = NULL; TRangeSrcDr * driver2Fw = NULL; TRangeSrcDr * driver2Rc = NULL; if(do1Fw) { r1Fw = new EbwtRangeSource( &ebwtFw_, true, 0xffffffff, true, verbose_, quiet_, halfAndHalf, seeded, maqPenalty_, qualOrder_); driver1Fw = new EbwtRangeSourceDriver( *params, r1Fw, true, false, maqPenalty_, qualOrder_, sink_, sinkPt, 0, // seedLen true, // nudgeLeft (not applicable) PIN_TO_LEN, // whole alignment is unrevisitable PIN_TO_LEN, // " PIN_TO_LEN, // " PIN_TO_LEN, // " os_, verbose_, quiet_, true, pool_, NULL); } if(do2Fw) { r2Fw = new EbwtRangeSource( &ebwtFw_, true, 0xffffffff, true, verbose_, quiet_, halfAndHalf, seeded, maqPenalty_, qualOrder_); driver2Fw = new EbwtRangeSourceDriver( *params, r2Fw, true, false, maqPenalty_, qualOrder_, sink_, sinkPt, 0, // seedLen true, // nudgeLeft (not applicable) PIN_TO_LEN, // whole alignment is unrevisitable PIN_TO_LEN, // " PIN_TO_LEN, // " PIN_TO_LEN, // " os_, verbose_, quiet_, false, pool_, NULL); } if(do1Rc) { r1Rc = new EbwtRangeSource( &ebwtFw_, false, 0xffffffff, true, verbose_, quiet_, halfAndHalf, seeded, maqPenalty_, qualOrder_); driver1Rc = new EbwtRangeSourceDriver( *params, r1Rc, false, false, maqPenalty_, qualOrder_, sink_, sinkPt, 0, // seedLen true, // nudgeLeft (not applicable) PIN_TO_LEN, // whole alignment is unrevisitable PIN_TO_LEN, // " PIN_TO_LEN, // " PIN_TO_LEN, // " os_, verbose_, quiet_, true, pool_, NULL); } if(do2Rc) { r2Rc = new EbwtRangeSource( &ebwtFw_, false, 0xffffffff, true, verbose_, quiet_, halfAndHalf, seeded, maqPenalty_, qualOrder_); driver2Rc = new EbwtRangeSourceDriver( *params, r2Rc, false, false, maqPenalty_, qualOrder_, sink_, sinkPt, 0, // seedLen true, // nudgeLeft (not applicable) PIN_TO_LEN, // whole alignment is unrevisitable PIN_TO_LEN, // " PIN_TO_LEN, // " PIN_TO_LEN, // " os_, verbose_, quiet_, false, pool_, NULL); } RefAligner >* refAligner = new ExactRefAligner >(color_, verbose_, quiet_); // Set up a RangeChaser RangeChaser > *rchase = new RangeChaser >(cacheLimit_, cacheFw_, cacheBw_); if(v1_) { PairedBWAlignerV1* al = new PairedBWAlignerV1( params, driver1Fw == NULL ? (new StubRangeSourceDriver()) : driver1Fw, driver1Rc == NULL ? (new StubRangeSourceDriver()) : driver1Rc, driver2Fw == NULL ? (new StubRangeSourceDriver()) : driver2Fw, driver2Rc == NULL ? (new StubRangeSourceDriver()) : driver2Rc, refAligner, rchase, sink_, sinkPtFactory_, sinkPt, mate1fw_, mate2fw_, peInner_, peOuter_, dontReconcile_, symCeil_, mixedThresh_, mixedAttemptLim_, refs_, rangeMode_, verbose_, quiet_, INT_MAX, pool_, NULL); return al; } else { TRangeSrcDrPtrVec *drVec = new TRangeSrcDrPtrVec(); if(driver1Fw != NULL) drVec->push_back(driver1Fw); if(driver1Rc != NULL) drVec->push_back(driver1Rc); if(driver2Fw != NULL) drVec->push_back(driver2Fw); if(driver2Rc != NULL) drVec->push_back(driver2Rc); PairedBWAlignerV2* al = new PairedBWAlignerV2( params, paramsSe1, paramsSe2, new TCostAwareRangeSrcDr(strandFix_, drVec, verbose_, quiet_, true), refAligner, rchase, sink_, sinkPtFactory_, sinkPt, sinkPtSe1, sinkPtSe2, mate1fw_, mate2fw_, peInner_, peOuter_, mixedAttemptLim_, refs_, rangeMode_, verbose_, quiet_, INT_MAX, pool_, NULL); delete drVec; return al; } } private: Ebwt >& ebwtFw_; Ebwt >* ebwtBw_; bool color_; bool doFw_; bool doRc_; bool v1_; HitSink& sink_; const HitSinkPerThreadFactory& sinkPtFactory_; const bool mate1fw_; const bool mate2fw_; const uint32_t peInner_; const uint32_t peOuter_; const bool dontReconcile_; const uint32_t symCeil_; const uint32_t mixedThresh_; const uint32_t mixedAttemptLim_; RangeCache *cacheFw_; RangeCache *cacheBw_; const uint32_t cacheLimit_; ChunkPool *pool_; BitPairReference* refs_; vector >& os_; const bool reportSe_; const bool maqPenalty_; const bool qualOrder_; const bool strandFix_; const bool rangeMode_; const bool verbose_; const bool quiet_; const uint32_t seed_; }; #endif /* ALIGNER_0MM_H_ */ ugene-1.9.8/src/plugins_3rdparty/bowtie/src/bowtie/filebuf.h0000644000175000017500000002675111651544326022572 0ustar ilyailya/* * filebuf.h * * Author: Ben Langmead */ #ifndef FILEBUF_H_ #define FILEBUF_H_ #include #include #include #include #include #include #include #include "assert_helpers.h" /** * Simple wrapper for a FILE*, istream or ifstream that reads it in * chunks (with fread) and keeps those chunks in a buffer. It also * services calls to get(), peek() and gets() from the buffer, reading * in additional chunks when necessary. */ class FileBuf { public: FileBuf() { init(); } FileBuf(FILE *in) { init(); _in = in; assert(_in != NULL); } FileBuf(std::ifstream *inf) { init(); _inf = inf; assert(_inf != NULL); } FileBuf(std::istream *ins) { init(); _ins = ins; assert(_ins != NULL); } bool isOpen() { return _in != NULL || _inf != NULL || _ins != NULL; } /** * Close the input stream (if that's possible) */ void close() { if(_in != NULL && _in != stdin) { fclose(_in); } else if(_inf != NULL) { _inf->close(); } else { // can't close _ins } } /** * Get the next character of input and advance. */ int get() { assert(_in != NULL || _inf != NULL || _ins != NULL); int c = peek(); if(c != -1) { _cur++; if(_lastn_cur < LASTN_BUF_SZ) _lastn_buf[_lastn_cur++] = c; } return c; } /** * Return true iff all input is exhausted. */ bool eof() { return (_cur == _buf_sz) && _done; } /** * Initialize the buffer with a new C-style file. */ void newFile(FILE *in) { _in = in; _inf = NULL; _ins = NULL; _cur = BUF_SZ; _buf_sz = BUF_SZ; _done = false; } /** * Initialize the buffer with a new ifstream. */ void newFile(std::ifstream *__inf) { _in = NULL; _inf = __inf; _ins = NULL; _cur = BUF_SZ; _buf_sz = BUF_SZ; _done = false; } /** * Initialize the buffer with a new istream. */ void newFile(std::istream *__ins) { _in = NULL; _inf = NULL; _ins = __ins; _cur = BUF_SZ; _buf_sz = BUF_SZ; _done = false; } /** * Restore state as though we just started reading the input * stream. */ void reset() { if(_inf != NULL) { _inf->clear(); _inf->seekg(0, std::ios::beg); } else if(_ins != NULL) { _ins->clear(); _ins->seekg(0, std::ios::beg); } else { rewind(_in); } _cur = BUF_SZ; _buf_sz = BUF_SZ; _done = false; } /** * Peek at the next character of the input stream without * advancing. Typically we can simple read it from the buffer. * Occasionally we'll need to read in a new buffer's worth of data. */ int peek() { assert(_in != NULL || _inf != NULL || _ins != NULL); assert_leq(_cur, _buf_sz); if(_cur == _buf_sz) { if(_done) { // We already exhausted the input stream return -1; } // Read a new buffer's worth of data else { // Get the next chunk if(_inf != NULL) { _inf->read((char*)_buf, BUF_SZ); _buf_sz = _inf->gcount(); } else if(_ins != NULL) { _ins->read((char*)_buf, BUF_SZ); _buf_sz = _ins->gcount(); } else { assert(_in != NULL); _buf_sz = fread(_buf, 1, BUF_SZ, _in); } _cur = 0; if(_buf_sz == 0) { // Exhausted, and we have nothing to return to the // caller _done = true; return -1; } else if(_buf_sz < BUF_SZ) { // Exhausted _done = true; } } } return (int)_buf[_cur]; } /** * Store a string of characters from the input file into 'buf', * until we see a newline, EOF, or until 'len' characters have been * read. */ size_t gets(char *buf, size_t len) { size_t stored = 0; while(true) { int c = get(); if(c == -1) { // End-of-file buf[stored] = '\0'; return stored; } if(stored == len-1 || c == '\n' || c == '\r') { // End of string buf[stored] = '\0'; // Skip over all end-of-line characters int pc = peek(); while(pc == '\n' || pc == '\r') { get(); // discard pc = peek(); } // Next get() will be after all newline characters return stored; } buf[stored++] = (char)c; } } /** * Store a string of characters from the input file into 'buf', * until we see a newline, EOF, or until 'len' characters have been * read. */ size_t get(char *buf, size_t len) { size_t stored = 0; for(size_t i = 0; i < len; i++) { int c = get(); if(c == -1) return i; buf[stored++] = (char)c; } return len; } static const size_t LASTN_BUF_SZ = 8 * 1024; /** * Keep get()ing characters until a non-whitespace character (or * -1) is reached, and return it. */ int getPastWhitespace() { int c; while(isspace(c = get()) && c != -1); return c; } /** * Keep get()ing characters until a we've passed over the next * string of newline characters (\r's and \n's) or -1 is reached, * and return it. */ int getPastNewline() { int c = get(); while(c != '\r' && c != '\n' && c != -1) c = get(); while(c == '\r' || c == '\n') c = get(); assert_neq(c, '\r'); assert_neq(c, '\n'); return c; } /** * Keep get()ing characters until a we've passed over the next * string of newline characters (\r's and \n's) or -1 is reached, * and return it. */ int peekPastNewline() { int c = peek(); while(c != '\r' && c != '\n' && c != -1) c = get(); while(c == '\r' || c == '\n') c = get(); assert_neq(c, '\r'); assert_neq(c, '\n'); return c; } /** * Keep peek()ing then get()ing characters until the next return * from peek() is just after the last newline of the line. */ int peekUptoNewline() { int c = peek(); while(c != '\r' && c != '\n' && c != -1) { get(); c = peek(); } while(c == '\r' || c == '\n') { get(); c = peek(); } assert_neq(c, '\r'); assert_neq(c, '\n'); return c; } size_t lastNCur() const { return _lastn_cur; } /** * Reset to the beginning of the last-N-chars buffer. */ void resetLastN() { _lastn_cur = 0; } /** * Copy the last several characters in the last-N-chars buffer * (since the last reset) into the provided buffer. */ size_t copyLastN(char *buf) { memcpy(buf, _lastn_buf, _lastn_cur); return _lastn_cur; } /** * Get const pointer to the last-N-chars buffer. */ const char *lastN() const { return _lastn_buf; } /** * Get current size of the last-N-chars buffer. */ const size_t lastNLen() const { return _lastn_cur; } private: void init() { _in = NULL; _inf = NULL; _ins = NULL; _cur = _buf_sz = BUF_SZ; _done = false; _lastn_cur = 0; // no need to clear _buf[] } static const size_t BUF_SZ = 256 * 1024; FILE *_in; std::ifstream *_inf; std::istream *_ins; size_t _cur; size_t _buf_sz; bool _done; uint8_t _buf[BUF_SZ]; // (large) input buffer size_t _lastn_cur; char _lastn_buf[LASTN_BUF_SZ]; // buffer of the last N chars dispensed }; /** * Wrapper for a buffered output stream that writes bitpairs. */ class BitpairOutFileBuf { public: /** * Open a new output stream to a file with given name. */ BitpairOutFileBuf(const char *in) : bpPtr_(0), cur_(0) { assert(in != NULL); out_ = fopen(in, "wb"); if(out_ == NULL) { std::cerr << "Error: Could not open bitpair-output file " << in << std::endl; throw 1; } memset(buf_, 0, BUF_SZ); } /** * Write a single bitpair into the buf. Flush the buffer if it's * full. */ void write(int bp) { assert_lt(bp, 4); assert_geq(bp, 0); buf_[cur_] |= (bp << bpPtr_); if(bpPtr_ == 6) { bpPtr_ = 0; cur_++; if(cur_ == BUF_SZ) { // Flush the buffer if(!fwrite((const void *)buf_, BUF_SZ, 1, out_)) { std::cerr << "Error writing to the reference index file (.4.ebwt)" << std::endl; throw 1; } // Reset to beginning of the buffer cur_ = 0; } // Initialize next octet to 0 buf_[cur_] = 0; } else { bpPtr_ += 2; } } /** * Write any remaining bitpairs and then close the input */ void close() { if(cur_ > 0 || bpPtr_ > 0) { if(bpPtr_ == 0) cur_--; if(!fwrite((const void *)buf_, cur_ + 1, 1, out_)) { std::cerr << "Error writing to the reference index file (.4.ebwt)" << std::endl; throw 1; } } fclose(out_); } private: static const size_t BUF_SZ = 128 * 1024; FILE *out_; int bpPtr_; uint32_t cur_; char buf_[BUF_SZ]; // (large) input buffer }; /** * Wrapper for a buffered output stream that writes characters and * other data types. This class is *not* synchronized; the caller is * responsible for synchronization. */ class OutFileBuf { public: /** * Open a new output stream to a file with given name. */ OutFileBuf(const char *out, bool binary = false) : name_(out), cur_(0), closed_(false) { assert(out != NULL); out_ = fopen(out, binary ? "wb" : "w"); if(out_ == NULL) { std::cerr << "Error: Could not open alignment output file " << out << std::endl; throw 1; } } /** * Open a new output stream to standard out. */ OutFileBuf() : name_("cout"), cur_(0), closed_(false) { out_ = stdout; } /** * Open a new output stream to a file with given name. */ void setFile(const char *out, bool binary = false) { assert(out != NULL); out_ = fopen(out, binary ? "wb" : "w"); if(out_ == NULL) { std::cerr << "Error: Could not open alignment output file " << out << std::endl; throw 1; } reset(); } /** * Write a single character into the write buffer and, if * necessary, flush. */ void write(char c) { assert(!closed_); if(cur_ == BUF_SZ) flush(); buf_[cur_++] = c; } /** * Write a c++ string to the write buffer and, if necessary, flush. */ void writeString(const std::string& s) { assert(!closed_); size_t slen = s.length(); if(cur_ + slen > BUF_SZ) { if(cur_ > 0) flush(); if(slen >= BUF_SZ) { size_t wlen = fwrite(s.c_str(), 1, slen, out_); if(wlen != slen) { std::cerr << "Error while writing string output; " << slen << " characters in string, " << wlen << " written" << std::endl; throw 1; } } else { memcpy(&buf_[cur_], s.data(), slen); assert_eq(0, cur_); cur_ = slen; } } else { memcpy(&buf_[cur_], s.data(), slen); cur_ += slen; } assert_leq(cur_, BUF_SZ); } /** * Write a c++ string to the write buffer and, if necessary, flush. */ void writeChars(const char * s, size_t len) { assert(!closed_); if(cur_ + len > BUF_SZ) { if(cur_ > 0) flush(); if(len >= BUF_SZ) { size_t wlen = fwrite(s, 1, len, out_); if(wlen != len) { std::cerr << "Error while writing string output; " << len << " characters in string, " << wlen << " written" << std::endl; throw 1; } } else { memcpy(&buf_[cur_], s, len); assert_eq(0, cur_); cur_ = len; } } else { memcpy(&buf_[cur_], s, len); cur_ += len; } assert_leq(cur_, BUF_SZ); } /** * Write any remaining bitpairs and then close the input */ void close() { if(closed_) return; if(cur_ > 0) flush(); closed_ = true; if(out_ != stdout) { fclose(out_); } } /** * Reset so that the next write is as though it's the first. */ void reset() { cur_ = 0; closed_ = false; } void flush() { if(!fwrite((const void *)buf_, cur_, 1, out_)) { std::cerr << "Error while flushing and closing output" << std::endl; throw 1; } cur_ = 0; } /** * Return true iff this stream is closed. */ bool closed() const { return closed_; } /** * Return the filename. */ const char *name() { return name_; } private: static const size_t BUF_SZ = 16 * 1024; const char *name_; FILE *out_; uint32_t cur_; char buf_[BUF_SZ]; // (large) input buffer bool closed_; }; #endif /*ndef FILEBUF_H_*/ ugene-1.9.8/src/plugins_3rdparty/bowtie/src/bowtie/edit.cpp0000644000175000017500000000035411651544326022425 0ustar ilyailya/* * edit.cpp * * Created on: Jul 14, 2009 * Author: Ben Langmead */ #include #include "edit.h" using namespace std; ostream& operator<< (ostream& os, const Edit& e) { os << e.pos << (char)e.chr; return os; } ugene-1.9.8/src/plugins_3rdparty/bowtie/src/bowtie/bowtie_build_main.cpp0000644000175000017500000000260211651544326025152 0ustar ilyailya/* * bowtie_build_main.cpp * * Created on: Sep 16, 2009 * Author: Ben Langmead */ #include #include #include #include #include #include "tokenize.h" using namespace std; extern "C" { int bowtie_build(int argc, const char **argv); } /** * bowtie-build main function. It is placed in a separate source file * to make it slightly easier to compile as a library. * * If the user specifies -A as the first two arguments, main * will interpret that file as having one set of command-line arguments * per line, and will dispatch each batch of arguments one at a time to * bowtie-build. */ int main(int argc, const char **argv) { if(argc > 2 && strcmp(argv[1], "-A") == 0) { const char *file = argv[2]; ifstream in; in.open(file); char buf[4096]; int lastret = -1; while(in.getline(buf, 4095)) { vector args; args.push_back(string(argv[0])); tokenize(buf, " \t", args); const char **myargs = (const char**)malloc(sizeof(char*)*args.size()); for(size_t i = 0; i < args.size(); i++) { myargs[i] = args[i].c_str(); } if(args.size() == 1) continue; lastret = bowtie_build(args.size(), myargs); free(myargs); } if(lastret == -1) { cerr << "Warning: No arg strings parsed from " << file << endl; return 0; } return lastret; } else { return bowtie_build(argc, argv); } } ugene-1.9.8/src/plugins_3rdparty/bowtie/src/bowtie/search_seeded_phase2.c0000644000175000017500000000564011651544326025163 0ustar ilyailya/* * This is a fragment, included from multiple places in ebwt_search.cpp. * It implements the logic of the second phase of the seeded, quality- * aware search routine. It is implemented as a code fragment so that * it can be reused in both the half-index-in-memory and full-index-in- * memory situations. */ { if(!nofw) { // If we reach here, then cases 1R, 2R, and 3R have been // eliminated. The next most likely cases are 1F, 2F and // 3F... params.setFw(true); // looking at forward strand btf2.setReportExacts(false); btr2.setReportExacts(false); btf2.setQuery(patsrc->bufa()); // Set up seed bounds if(qs < s) { btf2.setOffs(0, 0, (seedMms > 0)? qs5 : qs, (seedMms > 1)? qs5 : qs, (seedMms > 2)? qs5 : qs, (seedMms > 3)? qs5 : qs); } else { btf2.setOffs(0, 0, (seedMms > 0)? s5 : s, (seedMms > 1)? s5 : s, (seedMms > 2)? s5 : s, (seedMms > 3)? s5 : s); } // Do a 12/24 backtrack on the forward-strand read using // the mirror index. This will find all case 1F, 2F // and 3F hits. if(btf2.backtrack()) { // The reverse complement hit, so we're done with this // read DONEMASK_SET(patid); continue; } if(sink->finishedWithStratum(0)) { // no more exact hits are possible DONEMASK_SET(patid); continue; } } // No need to collect partial alignments if we're not // allowing mismatches in the 5' seed half if(seedMms == 0) continue; if(!norc) { // If we reach here, then cases 1F, 2F, 3F, 1R, 2R, and 3R // have been eliminated, leaving us with cases 4F and 4R // (the cases with 1 mismatch in the 5' half of the seed) params.setFw(false); // looking at reverse-comp strand // Set up seed bounds if(qs < s) { btr2.setOffs(0, 0, qs3, (seedMms > 1)? qs3 : qs, (seedMms > 2)? qs3 : qs, (seedMms > 3)? qs3 : qs); } else { btr2.setOffs(0, 0, s3, (seedMms > 1)? s3 : s, (seedMms > 2)? s3 : s, (seedMms > 3)? s3 : s); } btr2.setQuery(patsrc->bufa()); btr2.setQlen(s); // just look at the seed // Find partial alignments for case 4R ASSERT_ONLY(bool done =) btr2.backtrack(); #ifndef NDEBUG vector partials; assert(pamRc != NULL); pamRc->getPartials(patid, partials); if(done) assert_gt(partials.size(), 0); for(size_t i = 0; i < partials.size(); i++) { uint32_t pos0 = partials[i].entry.pos0; assert_lt(pos0, s5); uint8_t oldChar = (uint8_t)patRcRev[pos0]; assert_neq(oldChar, partials[i].entry.char0); if(partials[i].entry.pos1 != 0xffff) { uint32_t pos1 = partials[i].entry.pos1; assert_lt(pos1, s5); oldChar = (uint8_t)patRcRev[pos1]; assert_neq(oldChar, partials[i].entry.char1); if(partials[i].entry.pos2 != 0xffff) { uint32_t pos2 = partials[i].entry.pos2; assert_lt(pos2, s5); oldChar = (uint8_t)patRcRev[pos2]; assert_neq(oldChar, partials[i].entry.char2); } } } #endif } } ugene-1.9.8/src/plugins_3rdparty/bowtie/src/bowtie/search_1mm_phase1.c0000644000175000017500000000320311651544326024414 0ustar ilyailya/* * This is a fragment, included from multiple places in ebwt_search.cpp. * It implements the logic of the first phase of the 1-mismatch search * routine. It is implemented as a code fragment so that it can be * reused in both the half-index-in-memory and full-index-in-memory * situations. */ { bt.setEbwt(&ebwtFw); bt.setReportExacts(true); if(plen < 2) { cerr << "Error: Reads must be at least 2 characters long in 1-mismatch mode" << endl; throw 1; } if(!nofw) { // First, try exact hits for the forward-oriented read params.setFw(true); bt.setQuery(patsrc->bufa()); bt.setOffs(0, 0, s, s, s, s); if(bt.backtrack()) { DONEMASK_SET(patid); continue; } } if(!norc) { params.setFw(false); // Next, try exact hits for the reverse-complement read bt.setQuery(patsrc->bufa()); bt.setOffs(0, 0, s, s, s, s); if(bt.backtrack()) { DONEMASK_SET(patid); continue; } } if(sink->finishedWithStratum(0)) { // no more exact hits are possible // the sink tells us we needn't try 1-mismatch alignments DONEMASK_SET(patid); continue; } bt.setReportExacts(false); if(!norc) { // Next, try hits with one mismatch on the 3' end for the reverse-complement read bt.setQuery(patsrc->bufa()); bt.setOffs(0, 0, s5, s, s, s); // 1 mismatch allowed in 3' half if(bt.backtrack()) { DONEMASK_SET(patid); continue; } } if(!nofw) { params.setFw(true); // Next, try hits with one mismatch on the 3' end for the reverse-complement read bt.setQuery(patsrc->bufa()); bt.setOffs(0, 0, s5, s, s, s); // 1 mismatch allowed in 3' half if(bt.backtrack()) { DONEMASK_SET(patid); continue; } } } ugene-1.9.8/src/plugins_3rdparty/bowtie/src/bowtie/str_util.h0000644000175000017500000000063611651544326023015 0ustar ilyailya#ifndef STR_UTIL_H_ #define STR_UTIL_H_ #include /** * Given a string, return an int hash for it. */ static inline int hash_string(const std::string& s) { int ret = 0; int a = 63689; int b = 378551; for(size_t i = 0; i < s.length(); i++) { ret = (ret * a) + (int)s[i]; if(a == 0) { a += b; } else { a *= b; } if(a == 0) { a += b; } } return ret; } #endif /* STR_UTIL_H_ */ ugene-1.9.8/src/plugins_3rdparty/bowtie/src/bowtie/search_23mm_phase3.c0000644000175000017500000000323211651544326024504 0ustar ilyailya/* * This is a fragment, included from multiple places in ebwt_search.cpp. * It implements the logic of the third phase of the 2/3-mismatch * search routine. It is implemented as a code fragment so that it can * be reused in both the half-index-in-memory and full-index-in-memory * situations. */ { if(!nofw) { // Try 2/3 backtracks in the 3' half of the forward read params.setFw(true); bt3.setReportExacts(false); bt3.setQuery(patsrc->bufa()); bt3.setOffs(0, 0, s3, s3, two? s : s3, s); bool done = bt3.backtrack(); if(done) continue; // no more 1-mismatch hits are possible after this point if(sink->finishedWithStratum(1)) { continue; } // Try a half-and-half on the forward read bool gaveUp = false; bthh3.setQuery(patsrc->bufa()); // Processing the forward pattern with the forward index; // s3 ("lo") half is on the right bthh3.setOffs(s3, s, 0, two ? s3 : 0, two ? s : s3, s); done = bthh3.backtrack(); if(bthh3.numBacktracks() == bthh3.maxBacktracks()) { gaveUp = true; } bthh3.resetNumBacktracks(); if(done) { continue; } } if(!norc) { // Try a half-and-half on the reverse complement read bool gaveUp = false; params.setFw(false); bthh3.setQuery(patsrc->bufa()); // Processing the forward pattern with the forward index; // s5 ("hi") half is on the right bthh3.setOffs(s5, s, 0, two ? s5 : 0, two ? s : s5, s); bool done = bthh3.backtrack(); if(bthh3.numBacktracks() == bthh3.maxBacktracks()) { gaveUp = true; } bthh3.resetNumBacktracks(); if(done) { continue; } } } ugene-1.9.8/src/plugins_3rdparty/bowtie/src/bowtie/visualstudio/0000755000175000017500000000000011651544311023517 5ustar ilyailyaugene-1.9.8/src/plugins_3rdparty/bowtie/src/bowtie/visualstudio/inttypes.h0000644000175000017500000001750411651544326025564 0ustar ilyailya// ISO C9x compliant inttypes.h for Microsoft Visual Studio // Based on ISO/IEC 9899:TC2 Committee draft (May 6, 2005) WG14/N1124 // // Copyright (c) 2006 Alexander Chemeris // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // 3. The name of the author may be used to endorse or promote products // derived from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED // WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF // MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO // EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; // OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, // WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR // OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF // ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // /////////////////////////////////////////////////////////////////////////////// #ifndef _MSC_VER // [ #error "Use this header only with Microsoft Visual C++ compilers!" #endif // _MSC_VER ] #ifndef _MSC_INTTYPES_H_ // [ #define _MSC_INTTYPES_H_ #if _MSC_VER > 1000 #pragma once #endif #include "stdint.h" // 7.8 Format conversion of integer types typedef struct { intmax_t quot; intmax_t rem; } imaxdiv_t; // 7.8.1 Macros for format specifiers #if !defined(__cplusplus) || defined(__STDC_FORMAT_MACROS) // [ See footnote 185 at page 198 // The fprintf macros for signed integers are: #define PRId8 "d" #define PRIi8 "i" #define PRIdLEAST8 "d" #define PRIiLEAST8 "i" #define PRIdFAST8 "d" #define PRIiFAST8 "i" #define PRId16 "hd" #define PRIi16 "hi" #define PRIdLEAST16 "hd" #define PRIiLEAST16 "hi" #define PRIdFAST16 "hd" #define PRIiFAST16 "hi" #define PRId32 "I32d" #define PRIi32 "I32i" #define PRIdLEAST32 "I32d" #define PRIiLEAST32 "I32i" #define PRIdFAST32 "I32d" #define PRIiFAST32 "I32i" #define PRId64 "I64d" #define PRIi64 "I64i" #define PRIdLEAST64 "I64d" #define PRIiLEAST64 "I64i" #define PRIdFAST64 "I64d" #define PRIiFAST64 "I64i" #define PRIdMAX "I64d" #define PRIiMAX "I64i" #define PRIdPTR "Id" #define PRIiPTR "Ii" // The fprintf macros for unsigned integers are: #define PRIo8 "o" #define PRIu8 "u" #define PRIx8 "x" #define PRIX8 "X" #define PRIoLEAST8 "o" #define PRIuLEAST8 "u" #define PRIxLEAST8 "x" #define PRIXLEAST8 "X" #define PRIoFAST8 "o" #define PRIuFAST8 "u" #define PRIxFAST8 "x" #define PRIXFAST8 "X" #define PRIo16 "ho" #define PRIu16 "hu" #define PRIx16 "hx" #define PRIX16 "hX" #define PRIoLEAST16 "ho" #define PRIuLEAST16 "hu" #define PRIxLEAST16 "hx" #define PRIXLEAST16 "hX" #define PRIoFAST16 "ho" #define PRIuFAST16 "hu" #define PRIxFAST16 "hx" #define PRIXFAST16 "hX" #define PRIo32 "I32o" #define PRIu32 "I32u" #define PRIx32 "I32x" #define PRIX32 "I32X" #define PRIoLEAST32 "I32o" #define PRIuLEAST32 "I32u" #define PRIxLEAST32 "I32x" #define PRIXLEAST32 "I32X" #define PRIoFAST32 "I32o" #define PRIuFAST32 "I32u" #define PRIxFAST32 "I32x" #define PRIXFAST32 "I32X" #define PRIo64 "I64o" #define PRIu64 "I64u" #define PRIx64 "I64x" #define PRIX64 "I64X" #define PRIoLEAST64 "I64o" #define PRIuLEAST64 "I64u" #define PRIxLEAST64 "I64x" #define PRIXLEAST64 "I64X" #define PRIoFAST64 "I64o" #define PRIuFAST64 "I64u" #define PRIxFAST64 "I64x" #define PRIXFAST64 "I64X" #define PRIoMAX "I64o" #define PRIuMAX "I64u" #define PRIxMAX "I64x" #define PRIXMAX "I64X" #define PRIoPTR "Io" #define PRIuPTR "Iu" #define PRIxPTR "Ix" #define PRIXPTR "IX" // The fscanf macros for signed integers are: #define SCNd8 "d" #define SCNi8 "i" #define SCNdLEAST8 "d" #define SCNiLEAST8 "i" #define SCNdFAST8 "d" #define SCNiFAST8 "i" #define SCNd16 "hd" #define SCNi16 "hi" #define SCNdLEAST16 "hd" #define SCNiLEAST16 "hi" #define SCNdFAST16 "hd" #define SCNiFAST16 "hi" #define SCNd32 "ld" #define SCNi32 "li" #define SCNdLEAST32 "ld" #define SCNiLEAST32 "li" #define SCNdFAST32 "ld" #define SCNiFAST32 "li" #define SCNd64 "I64d" #define SCNi64 "I64i" #define SCNdLEAST64 "I64d" #define SCNiLEAST64 "I64i" #define SCNdFAST64 "I64d" #define SCNiFAST64 "I64i" #define SCNdMAX "I64d" #define SCNiMAX "I64i" #ifdef _WIN64 // [ # define SCNdPTR "I64d" # define SCNiPTR "I64i" #else // _WIN64 ][ # define SCNdPTR "ld" # define SCNiPTR "li" #endif // _WIN64 ] // The fscanf macros for unsigned integers are: #define SCNo8 "o" #define SCNu8 "u" #define SCNx8 "x" #define SCNX8 "X" #define SCNoLEAST8 "o" #define SCNuLEAST8 "u" #define SCNxLEAST8 "x" #define SCNXLEAST8 "X" #define SCNoFAST8 "o" #define SCNuFAST8 "u" #define SCNxFAST8 "x" #define SCNXFAST8 "X" #define SCNo16 "ho" #define SCNu16 "hu" #define SCNx16 "hx" #define SCNX16 "hX" #define SCNoLEAST16 "ho" #define SCNuLEAST16 "hu" #define SCNxLEAST16 "hx" #define SCNXLEAST16 "hX" #define SCNoFAST16 "ho" #define SCNuFAST16 "hu" #define SCNxFAST16 "hx" #define SCNXFAST16 "hX" #define SCNo32 "lo" #define SCNu32 "lu" #define SCNx32 "lx" #define SCNX32 "lX" #define SCNoLEAST32 "lo" #define SCNuLEAST32 "lu" #define SCNxLEAST32 "lx" #define SCNXLEAST32 "lX" #define SCNoFAST32 "lo" #define SCNuFAST32 "lu" #define SCNxFAST32 "lx" #define SCNXFAST32 "lX" #define SCNo64 "I64o" #define SCNu64 "I64u" #define SCNx64 "I64x" #define SCNX64 "I64X" #define SCNoLEAST64 "I64o" #define SCNuLEAST64 "I64u" #define SCNxLEAST64 "I64x" #define SCNXLEAST64 "I64X" #define SCNoFAST64 "I64o" #define SCNuFAST64 "I64u" #define SCNxFAST64 "I64x" #define SCNXFAST64 "I64X" #define SCNoMAX "I64o" #define SCNuMAX "I64u" #define SCNxMAX "I64x" #define SCNXMAX "I64X" #ifdef _WIN64 // [ # define SCNoPTR "I64o" # define SCNuPTR "I64u" # define SCNxPTR "I64x" # define SCNXPTR "I64X" #else // _WIN64 ][ # define SCNoPTR "lo" # define SCNuPTR "lu" # define SCNxPTR "lx" # define SCNXPTR "lX" #endif // _WIN64 ] #endif // __STDC_FORMAT_MACROS ] // 7.8.2 Functions for greatest-width integer types // 7.8.2.1 The imaxabs function #define imaxabs _abs64 // 7.8.2.2 The imaxdiv function // This is modified version of div() function from Microsoft's div.c found // in %MSVC.NET%\crt\src\div.c #ifdef STATIC_IMAXDIV // [ static #else // STATIC_IMAXDIV ][ _inline #endif // STATIC_IMAXDIV ] imaxdiv_t __cdecl imaxdiv(intmax_t numer, intmax_t denom) { imaxdiv_t result; result.quot = numer / denom; result.rem = numer % denom; if (numer < 0 && result.rem > 0) { // did division wrong; must fix up ++result.quot; result.rem -= denom; } return result; } // 7.8.2.3 The strtoimax and strtoumax functions #define strtoimax _strtoi64 #define strtoumax _strtoui64 // 7.8.2.4 The wcstoimax and wcstoumax functions #define wcstoimax _wcstoi64 #define wcstoumax _wcstoui64 #endif // _MSC_INTTYPES_H_ ] ugene-1.9.8/src/plugins_3rdparty/bowtie/src/bowtie/visualstudio/unistd.h0000644000175000017500000000071211651544326025204 0ustar ilyailya#ifndef _UNISTD_H #define _UNISTD_H 1 /* This file intended to serve as a drop-in replacement for * unistd.h on Windows * Please add functionality as neeeded */ #include #include #include /* getopt from: http://www.pwilson.net/sample.html. */ #define srandom srand #define random rand const W_OK = 2; const R_OK = 4; #define access _access #define ftruncate _chsize #define ssize_t int #endif /* unistd.h */ugene-1.9.8/src/plugins_3rdparty/bowtie/src/bowtie/visualstudio/stdint.h0000644000175000017500000001706011651544326025207 0ustar ilyailya// ISO C9x compliant stdint.h for Microsoft Visual Studio // Based on ISO/IEC 9899:TC2 Committee draft (May 6, 2005) WG14/N1124 // // Copyright (c) 2006-2008 Alexander Chemeris // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // 3. The name of the author may be used to endorse or promote products // derived from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED // WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF // MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO // EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; // OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, // WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR // OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF // ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // /////////////////////////////////////////////////////////////////////////////// #ifndef _MSC_VER // [ #error "Use this header only with Microsoft Visual C++ compilers!" #endif // _MSC_VER ] #ifndef _MSC_STDINT_H_ // [ #define _MSC_STDINT_H_ #if _MSC_VER > 1000 #pragma once #endif #include // For Visual Studio 6 in C++ mode and for many Visual Studio versions when // compiling for ARM we should wrap include with 'extern "C++" {}' // or compiler give many errors like this: // error C2733: second C linkage of overloaded function 'wmemchr' not allowed #ifdef __cplusplus extern "C" { #endif # include #ifdef __cplusplus } #endif // Define _W64 macros to mark types changing their size, like intptr_t. #ifndef _W64 # if !defined(__midl) && (defined(_X86_) || defined(_M_IX86)) && _MSC_VER >= 1300 # define _W64 __w64 # else # define _W64 # endif #endif // 7.18.1 Integer types // 7.18.1.1 Exact-width integer types // Visual Studio 6 and Embedded Visual C++ 4 doesn't // realize that, e.g. char has the same size as __int8 // so we give up on __intX for them. #if (_MSC_VER < 1300) typedef signed char int8_t; typedef signed short int16_t; typedef signed int int32_t; typedef unsigned char uint8_t; typedef unsigned short uint16_t; typedef unsigned int uint32_t; #else typedef signed __int8 int8_t; typedef signed __int16 int16_t; typedef signed __int32 int32_t; typedef unsigned __int8 uint8_t; typedef unsigned __int16 uint16_t; typedef unsigned __int32 uint32_t; #endif typedef signed __int64 int64_t; typedef unsigned __int64 uint64_t; // 7.18.1.2 Minimum-width integer types typedef int8_t int_least8_t; typedef int16_t int_least16_t; typedef int32_t int_least32_t; typedef int64_t int_least64_t; typedef uint8_t uint_least8_t; typedef uint16_t uint_least16_t; typedef uint32_t uint_least32_t; typedef uint64_t uint_least64_t; // 7.18.1.3 Fastest minimum-width integer types typedef int8_t int_fast8_t; typedef int16_t int_fast16_t; typedef int32_t int_fast32_t; typedef int64_t int_fast64_t; typedef uint8_t uint_fast8_t; typedef uint16_t uint_fast16_t; typedef uint32_t uint_fast32_t; typedef uint64_t uint_fast64_t; // 7.18.1.4 Integer types capable of holding object pointers #ifdef _WIN64 // [ typedef signed __int64 intptr_t; typedef unsigned __int64 uintptr_t; #else // _WIN64 ][ typedef _W64 signed int intptr_t; typedef _W64 unsigned int uintptr_t; #endif // _WIN64 ] // 7.18.1.5 Greatest-width integer types typedef int64_t intmax_t; typedef uint64_t uintmax_t; // 7.18.2 Limits of specified-width integer types #if !defined(__cplusplus) || defined(__STDC_LIMIT_MACROS) // [ See footnote 220 at page 257 and footnote 221 at page 259 // 7.18.2.1 Limits of exact-width integer types #define INT8_MIN ((int8_t)_I8_MIN) #define INT8_MAX _I8_MAX #define INT16_MIN ((int16_t)_I16_MIN) #define INT16_MAX _I16_MAX #define INT32_MIN ((int32_t)_I32_MIN) #define INT32_MAX _I32_MAX #define INT64_MIN ((int64_t)_I64_MIN) #define INT64_MAX _I64_MAX #define UINT8_MAX _UI8_MAX #define UINT16_MAX _UI16_MAX #define UINT32_MAX _UI32_MAX #define UINT64_MAX _UI64_MAX // 7.18.2.2 Limits of minimum-width integer types #define INT_LEAST8_MIN INT8_MIN #define INT_LEAST8_MAX INT8_MAX #define INT_LEAST16_MIN INT16_MIN #define INT_LEAST16_MAX INT16_MAX #define INT_LEAST32_MIN INT32_MIN #define INT_LEAST32_MAX INT32_MAX #define INT_LEAST64_MIN INT64_MIN #define INT_LEAST64_MAX INT64_MAX #define UINT_LEAST8_MAX UINT8_MAX #define UINT_LEAST16_MAX UINT16_MAX #define UINT_LEAST32_MAX UINT32_MAX #define UINT_LEAST64_MAX UINT64_MAX // 7.18.2.3 Limits of fastest minimum-width integer types #define INT_FAST8_MIN INT8_MIN #define INT_FAST8_MAX INT8_MAX #define INT_FAST16_MIN INT16_MIN #define INT_FAST16_MAX INT16_MAX #define INT_FAST32_MIN INT32_MIN #define INT_FAST32_MAX INT32_MAX #define INT_FAST64_MIN INT64_MIN #define INT_FAST64_MAX INT64_MAX #define UINT_FAST8_MAX UINT8_MAX #define UINT_FAST16_MAX UINT16_MAX #define UINT_FAST32_MAX UINT32_MAX #define UINT_FAST64_MAX UINT64_MAX // 7.18.2.4 Limits of integer types capable of holding object pointers #ifdef _WIN64 // [ # define INTPTR_MIN INT64_MIN # define INTPTR_MAX INT64_MAX # define UINTPTR_MAX UINT64_MAX #else // _WIN64 ][ # define INTPTR_MIN INT32_MIN # define INTPTR_MAX INT32_MAX # define UINTPTR_MAX UINT32_MAX #endif // _WIN64 ] // 7.18.2.5 Limits of greatest-width integer types #define INTMAX_MIN INT64_MIN #define INTMAX_MAX INT64_MAX #define UINTMAX_MAX UINT64_MAX // 7.18.3 Limits of other integer types #ifdef _WIN64 // [ # define PTRDIFF_MIN _I64_MIN # define PTRDIFF_MAX _I64_MAX #else // _WIN64 ][ # define PTRDIFF_MIN _I32_MIN # define PTRDIFF_MAX _I32_MAX #endif // _WIN64 ] #define SIG_ATOMIC_MIN INT_MIN #define SIG_ATOMIC_MAX INT_MAX #ifndef SIZE_MAX // [ # ifdef _WIN64 // [ # define SIZE_MAX _UI64_MAX # else // _WIN64 ][ # define SIZE_MAX _UI32_MAX # endif // _WIN64 ] #endif // SIZE_MAX ] // WCHAR_MIN and WCHAR_MAX are also defined in #ifndef WCHAR_MIN // [ # define WCHAR_MIN 0 #endif // WCHAR_MIN ] #ifndef WCHAR_MAX // [ # define WCHAR_MAX _UI16_MAX #endif // WCHAR_MAX ] #define WINT_MIN 0 #define WINT_MAX _UI16_MAX #endif // __STDC_LIMIT_MACROS ] // 7.18.4 Limits of other integer types #if !defined(__cplusplus) || defined(__STDC_CONSTANT_MACROS) // [ See footnote 224 at page 260 // 7.18.4.1 Macros for minimum-width integer constants #define INT8_C(val) val##i8 #define INT16_C(val) val##i16 #define INT32_C(val) val##i32 #define INT64_C(val) val##i64 #define UINT8_C(val) val##ui8 #define UINT16_C(val) val##ui16 #define UINT32_C(val) val##ui32 #define UINT64_C(val) val##ui64 // 7.18.4.2 Macros for greatest-width integer constants #define INTMAX_C INT64_C #define UINTMAX_C UINT64_C #endif // __STDC_CONSTANT_MACROS ] #endif // _MSC_STDINT_H_ ] ugene-1.9.8/src/plugins_3rdparty/bowtie/src/bowtie/auto_array.h0000644000175000017500000000113511651544326023311 0ustar ilyailya/* * auto_array.h * * Created on: Oct 12, 2009 * Author: Ben Langmead */ #include #ifndef AUTO_ARRAY_H_ #define AUTO_ARRAY_H_ /** * A simple fixed-length array of type T, automatically freed in the * destructor. */ template class AutoArray { public: AutoArray(size_t sz) { t_ = NULL; t_ = new T[sz]; memset(t_, 0, sz*sizeof(T)); sz_ = sz; } ~AutoArray() { if(t_ != NULL) delete[] t_; } T& operator[](size_t sz) { return t_[sz]; } const T& operator[](size_t sz) const { return t_[sz]; } private: T *t_; size_t sz_; }; #endif /* AUTO_ARRAY_H_ */ ugene-1.9.8/src/plugins_3rdparty/bowtie/src/bowtie/refmap.h0000644000175000017500000000214611651544326022420 0ustar ilyailya/* * refmap.h * * Created on: Aug 3, 2009 * Author: Ben Langmead */ #ifndef REFMAP_H_ #define REFMAP_H_ #include #include #include #include #include class ReferenceMap { typedef std::pair U32Pair; public: ReferenceMap(const char *fname, bool parseNames) { fname_ = fname; parseNames_ = parseNames; parse(); } /** * Give a reference coordinate in the index, translate it into a * new reference coordinate via the reference map supplied by the * user. */ void map(U32Pair& h) const; /** * Return true iff we have a name for reference with id 'i'. */ bool hasName(size_t i) const { if(!parseNames_) return false; return !names_[i].empty(); } /** * Get the name for reference with id 'i'. */ const std::string& getName(size_t i) const { assert(parseNames_); assert(hasName(i)); return names_[i]; } protected: /** * Parse a reference-map file. */ void parse(); const char *fname_; std::vector map_; bool parseNames_; std::vector names_; }; #endif /* REFMAP_H_ */ ugene-1.9.8/src/plugins_3rdparty/bowtie/src/bowtie/ebwt_search_backtrack.h0000644000175000017500000031320511651544326025442 0ustar ilyailya#ifndef EBWT_SEARCH_BACKTRACK_H_ #define EBWT_SEARCH_BACKTRACK_H_ #include "u64.h" #include #include #include "pat.h" #include "qual.h" #include "ebwt_search_util.h" #include "range.h" #include "range_source.h" #include "aligner_metrics.h" #include "search_globals.h" //#include "BowtieContext.h" /** * Class that coordinates quality- and quantity-aware backtracking over * some range of a read sequence. * * The creator can configure the BacktrackManager to treat different * stretches of the read differently. */ class GreedyDFSRangeSource { typedef std::pair TIntPair; typedef seqan::String DnaString; public: GreedyDFSRangeSource( const Ebwt* ebwt, const EbwtSearchParams& params, const BitPairReference* refs, uint32_t qualThresh, /// max acceptable q-distance const int maxBts, /// maximum # backtracks allowed uint32_t reportPartials = 0, bool reportExacts = true, bool reportRanges = false, PartialAlignmentManager* partials = NULL, String* muts = NULL, bool verbose = true, vector >* os = NULL, bool considerQuals = true, // whether to consider quality values when making backtracking decisions bool halfAndHalf = false, // hacky way of supporting separate revisitable regions bool maqPenalty = true) : _refs(refs), _qry(NULL), _qlen(0), _qual(NULL), _name(NULL), _ebwt(ebwt), _params(params), _unrevOff(0), _1revOff(0), _2revOff(0), _3revOff(0), _maqPenalty(maqPenalty), _qualThresh(qualThresh), _pairs(NULL), _elims(NULL), _mms(), _refcs(), _chars(NULL), _reportPartials(reportPartials), _reportExacts(reportExacts), _reportRanges(reportRanges), _partials(partials), _muts(muts), _os(os), _sanity(_os != NULL && _os->size() > 0), _considerQuals(considerQuals), _halfAndHalf(halfAndHalf), _5depth(0), _3depth(0), _numBts(0), _totNumBts(0), _maxBts(maxBts), _precalcedSideLocus(false), _preLtop(), _preLbot(), _verbose(verbose), _ihits(U64(0)) { } ~GreedyDFSRangeSource() { if(_pairs != NULL) delete[] _pairs; if(_elims != NULL) delete[] _elims; if(_chars != NULL) delete[] _chars; } /** * Set a new query read. */ void setQuery(ReadBuf& r) { const bool fw = _params.fw(); const bool ebwtFw = _ebwt->fw(); if(ebwtFw) { _qry = fw ? &r.patFw : &r.patRc; _qual = fw ? &r.qual : &r.qualRev; } else { _qry = fw ? &r.patFwRev : &r.patRcRev; _qual = fw ? &r.qualRev : &r.qual; } _name = &r.name; // Reset _qlen if(length(*_qry) > _qlen) { try { _qlen = length(*_qry); // Resize _pairs if(_pairs != NULL) { delete[] _pairs; } _pairs = new uint32_t[_qlen*_qlen*8]; // Resize _elims if(_elims != NULL) { delete[] _elims; } _elims = new uint8_t[_qlen*_qlen]; memset(_elims, 0, _qlen*_qlen); // Resize _chars if(_chars != NULL) { delete[] _chars; } _chars = new char[_qlen]; assert(_pairs != NULL && _elims != NULL && _chars != NULL); } catch(std::bad_alloc& e) { ThreadSafe _ts(&(BowtieContext::getSearchContext()->gLock)); cerr << "Unable to allocate memory for depth-first " << "backtracking search; new length = " << length(*_qry) << endl; throw 1; } } else { // New length is less than old length, so there's no need // to resize any data structures. assert(_pairs != NULL && _elims != NULL && _chars != NULL); _qlen = length(*_qry); } _mms.clear(); _refcs.clear(); assert_geq(length(*_qual), _qlen); if(_verbose) { cout << "setQuery(_qry=" << (*_qry) << ", _qual=" << (*_qual) << ")" << endl; } // Initialize the random source using new read as part of the // seed. _color = r.color; _seed = r.seed; _patid = r.patid; _rand.init(r.seed); } /** * Apply a batch of mutations to this read, possibly displacing a * previous batch of mutations. */ void setMuts(String* muts) { if(_muts != NULL) { // Undo previous mutations assert_gt(length(*_muts), 0); undoPartialMutations(); } _muts = muts; if(_muts != NULL) { assert_gt(length(*_muts), 0); applyPartialMutations(); } } /** * Set backtracking constraints. */ void setOffs(uint32_t depth5, // depth of far edge of hi-half uint32_t depth3, // depth of far edge of lo-half uint32_t unrevOff, // depth above which we cannot backtrack uint32_t revOff1, // depth above which we may backtrack just once uint32_t revOff2, // depth above which we may backtrack just twice uint32_t revOff3) // depth above which we may backtrack just three times { _5depth = depth5; _3depth = depth3; assert_geq(depth3, depth5); _unrevOff = unrevOff; _1revOff = revOff1; _2revOff = revOff2; _3revOff = revOff3; } /** * Reset number of backtracks to 0. */ void resetNumBacktracks() { _totNumBts = 0; } /** * Return number of backtracks since the last time the count was * reset. */ uint32_t numBacktracks() { return _totNumBts; } /** * Set whether to report exact hits. */ void setReportExacts(int stratum) { _reportExacts = stratum; } /** * Set the Bowtie index to search against. */ void setEbwt(const Ebwt >* ebwt) { _ebwt = ebwt; } /** * Return the current range */ Range& range() { return _curRange; } /** * Set _qlen. Don't let it exceed length of query. */ void setQlen(uint32_t qlen) { assert(_qry != NULL); _qlen = min(length(*_qry), qlen); } /// Return the maximum number of allowed backtracks in a given call /// to backtrack() uint32_t maxBacktracks() { return _maxBts; } /** * Initiate the recursive backtracking routine starting at the * extreme right-hand side of the pattern. Use the ftab to match * the first several characters in one chomp, as long as doing so * does not "jump over" any legal backtracking targets. * * Return true iff the HitSink has indicated that we're done with * this read. */ bool backtrack(uint32_t ham = 0) { assert_gt(length(*_qry), 0); assert_leq(_qlen, length(*_qry)); assert_geq(length(*_qual), length(*_qry)); const Ebwt >& ebwt = *_ebwt; int ftabChars = ebwt._eh._ftabChars; int nsInSeed = 0; int nsInFtab = 0; if(!tallyNs(nsInSeed, nsInFtab)) { // No alignments are possible because of the distribution // of Ns in the read in combination with the backtracking // constraints. return false; } bool ret; // m = depth beyond which ftab must not extend or else we might // miss some legitimate paths uint32_t m = min(_unrevOff, _qlen); if(nsInFtab == 0 && m >= (uint32_t)ftabChars) { uint32_t ftabOff = calcFtabOff(); uint32_t top = ebwt.ftabHi(ftabOff); uint32_t bot = ebwt.ftabLo(ftabOff+1); if(_qlen == (uint32_t)ftabChars && bot > top) { // We have a match! if(_reportPartials > 0) { // Oops - we're trying to find seedlings, so we've // gone too far; start again ret = backtrack(0, // depth 0, // top 0, // bot ham, nsInFtab > 0); } else { // We have a match! ret = reportAlignment(0, top, bot, ham); } } else if (bot > top) { // We have an arrow pair from which we can backtrack ret = backtrack(ftabChars, // depth top, // top bot, // bot ham, nsInFtab > 0); } else { // The arrows are already closed; give up ret = false; } } else { // The ftab *does* extend past the unrevisitable portion; // we can't use it in this case, because we might jump past // a legitimate mismatch ret = backtrack(0, // depth 0, // top 0, // bot ham, // disable ftab jumping if there is more // than 1 N in it nsInFtab > 0); } if(finalize()) ret = true; return ret; } /** * If there are any buffered results that have yet to be committed, * commit them. This happens when looking for partial alignments. */ bool finalize() { bool ret = false; if(_reportPartials > 0) { // We're in partial alignment mode; take elements of the // _partialBuf and install them in the _partials database assert(_partials != NULL); if(_partialsBuf.size() > 0) { #ifndef NDEBUG for(size_t i = 0; i < _partialsBuf.size(); i++) { assert(_partialsBuf[i].repOk(_qualThresh, _qlen, (*_qual), _maqPenalty)); } #endif _partials->addPartials(_params.patId(), _partialsBuf); _partialsBuf.clear(); ret = true; } else { assert(!ret); } } assert_eq(0, _partialsBuf.size()); return ret; } /** * Starting at the given "depth" relative to the 5' end, and the * given top and bot indexes (where top=0 and bot=0 means it's up * to us to calculate the initial range), and initial weighted * hamming distance iham, find a hit using randomized, quality- * aware backtracking. */ bool backtrack(uint32_t depth, uint32_t top, uint32_t bot, uint32_t iham = 0, bool disableFtab = false) { HitSinkPerThread& sink = _params.sink(); _ihits = sink.retainedHits().size(); // Initiate the recursive, randomized quality-aware backtracker // with a stack depth of 0 (no backtracks so far) _bailedOnBacktracks = false; bool done = backtrack(0, depth, _unrevOff, _1revOff, _2revOff, _3revOff, top, bot, iham, iham, _pairs, _elims, disableFtab); _totNumBts += _numBts; _numBts = 0; _precalcedSideLocus = false; _bailedOnBacktracks = false; return done; } /** * Recursive routine for progressing to the next backtracking * decision given some initial conditions. If a hit is found, it * is recorded and true is returned. Otherwise, if there are more * backtracking opportunities, the function will call itself * recursively and return the result. As soon as there is a * mismatch and no backtracking opportunities, false is returned. */ bool backtrack(uint32_t stackDepth, // depth of the recursion stack; = # mismatches so far uint32_t depth, // next depth where a post-pair needs to be calculated uint32_t unrevOff, // depths < unrevOff are unrevisitable uint32_t oneRevOff,// depths < oneRevOff are 1-revisitable uint32_t twoRevOff,// depths < twoRevOff are 2-revisitable uint32_t threeRevOff,// depths < threeRevOff are 3-revisitable uint32_t top, // top arrow in pair prior to 'depth' uint32_t bot, // bottom arrow in pair prior to 'depth' uint32_t ham, // weighted hamming distance so far uint32_t iham, // initial weighted hamming distance uint32_t* pairs, // portion of pairs array to be used for this backtrack frame uint8_t* elims, // portion of elims array to be used for this backtrack frame bool disableFtab = false) { // Can't have already exceeded weighted hamming distance threshold assert_leq(stackDepth, depth); assert_gt(length(*_qry), 0); assert_leq(_qlen, length(*_qry)); assert_geq(length(*_qual), length(*_qry)); assert(_qry != NULL); assert(_qual != NULL); assert(_name != NULL); assert(_qlen != 0); assert_leq(ham, _qualThresh); assert_lt(depth, _qlen); // can't have run off the end of qry assert_geq(bot, top); // could be that both are 0 assert(pairs != NULL); assert(elims != NULL); assert_leq(stackDepth, _qlen); const Ebwt >& ebwt = *_ebwt; HitSinkPerThread& sink = _params.sink(); uint64_t prehits = sink.numValidHits(); if(_halfAndHalf) { assert_eq(0, _reportPartials); assert_gt(_3depth, _5depth); } if(_reportPartials) { assert(!_halfAndHalf); } if(_verbose) { cout << " backtrack(stackDepth=" << stackDepth << ", " << "depth=" << depth << ", " << "top=" << top << ", " << "bot=" << bot << ", " << "ham=" << ham << ", " << "iham=" << iham << ", " << "pairs=" << pairs << ", " << "elims=" << (void*)elims << "): \""; for(int i = (int)depth - 1; i >= 0; i--) { cout << _chars[i]; } cout << "\"" << endl; } // Do this early on so that we can clear _precalcedSideLocus // before we have too many opportunities to bail and leave it // 'true' SideLocus ltop, lbot; if(_precalcedSideLocus) { ltop = _preLtop; lbot = _preLbot; _precalcedSideLocus = false; } else if(top != 0 || bot != 0) { SideLocus::initFromTopBot(top, bot, ebwt._eh, ebwt._ebwt, ltop, lbot); } // Check whether we've exceeded any backtracking limit if(_halfAndHalf) { if(_maxBts > 0 && _numBts == _maxBts) { _bailedOnBacktracks = true; return false; } _numBts++; } // # positions with at least one legal outgoing path uint32_t altNum = 0; // # positions tied for "best" outgoing qual uint32_t eligibleNum = 0; // total range-size for all eligibles uint32_t eligibleSz = 0; // If there is just one eligible slot at the moment (a common // case), these are its parameters uint32_t eli = 0; bool elignore = true; // ignore the el values because they didn't come from a recent override uint32_t eltop = 0; uint32_t elbot = 0; uint32_t elham = ham; char elchar = 0; int elcint = 0; // The lowest quality value associated with any alternative // ranges; all alternative ranges with this quality are // eligible uint8_t lowAltQual = 0xff; uint32_t d = depth; uint32_t cur = _qlen - d - 1; // current offset into _qry while(cur < _qlen) { // Try to advance further given that if(_verbose) { cout << " cur=" << cur << " \""; for(int i = (int)d - 1; i >= 0; i--) { cout << _chars[i]; } cout << "\""; } // If we're searching for a half-and-half solution, then // enforce the boundary-crossing constraints here. if(_halfAndHalf && !hhCheckTop(stackDepth, d, iham, _mms, prehits)) { return false; } bool curIsEligible = false; // Reset eligibleNum and eligibleSz if there are any // eligible pairs discovered at this spot bool curOverridesEligible = false; // Determine whether ranges at this location are // candidates for backtracking int c = (int)(*_qry)[cur]; assert_leq(c, 4); uint8_t q = qualAt(cur); // The current query position is a legit alternative if it a) is // not in the unrevisitable region, and b) the quality ceiling (if // one exists) is not exceeded bool curIsAlternative = (d >= unrevOff) && (!_considerQuals || (ham + mmPenalty(_maqPenalty, q) <= _qualThresh)); if(curIsAlternative) { if(_considerQuals) { // Is it the best alternative? if(q < lowAltQual) { // Ranges at this depth in this backtracking frame are // eligible, unless we learn otherwise. Ranges previously // thought to be eligible are not any longer. curIsEligible = true; curOverridesEligible = true; } else if(q == lowAltQual) { // Ranges at this depth in this backtracking frame // are eligible, unless we learn otherwise curIsEligible = true; } } else { // When quality values are not considered, all positions // are eligible curIsEligible = true; } } if(curIsEligible) assert(curIsAlternative); if(curOverridesEligible) assert(curIsEligible); if(curIsAlternative && !curIsEligible) { assert_gt(eligibleSz, 0); assert_gt(eligibleNum, 0); } if(_verbose) { cout << " alternative: " << curIsAlternative; cout << ", eligible: " << curIsEligible; if(curOverridesEligible) cout << "(overrides)"; cout << endl; } // If c is 'N', then it's guaranteed to be a mismatch if(c == 4 && d > 0) { // Force the 'else if(curIsAlternative)' branch below top = bot = 1; } else if(c == 4) { // We'll take the 'if(top == 0 && bot == 0)' branch below assert_eq(0, top); assert_eq(0, bot); } // Calculate the ranges for this position if(top == 0 && bot == 0) { // Calculate first quartet of ranges using the _fchr[] // array pairs[0 + 0] = ebwt._fchr[0]; pairs[0 + 4] = pairs[1 + 0] = ebwt._fchr[1]; pairs[1 + 4] = pairs[2 + 0] = ebwt._fchr[2]; pairs[2 + 4] = pairs[3 + 0] = ebwt._fchr[3]; pairs[3 + 4] = ebwt._fchr[4]; // Update top and bot if(c < 4) { top = pairTop(pairs, d, c); bot = pairBot(pairs, d, c); assert_geq(bot, top); } } else if(curIsAlternative) { // Clear pairs memset(&pairs[d*8], 0, 8 * 4); // Calculate next quartet of ranges ebwt.mapLFEx(ltop, lbot, &pairs[d*8], &pairs[(d*8)+4]); // Update top and bot if(c < 4) { top = pairTop(pairs, d, c); bot = pairBot(pairs, d, c); assert_geq(bot, top); } } else { // This query character is not even a legitimate // alternative (because backtracking here would blow // our mismatch quality budget), so no need to do the // bookkeeping for the entire quartet, just do c if(c < 4) { if(top+1 == bot) { bot = top = ebwt.mapLF1(top, ltop, c); if(bot != 0xffffffff) bot++; } else { top = ebwt.mapLF(ltop, c); bot = ebwt.mapLF(lbot, c); assert_geq(bot, top); } } } if(top != bot) { // Calculate loci from row indices; do it now so that // those prefetches are fired off as soon as possible. // This eventually calls SideLocus.initfromRow(). SideLocus::initFromTopBot(top, bot, ebwt._eh, ebwt._ebwt, ltop, lbot); } // Update the elim array eliminate(elims, d, c); if(curIsAlternative) { // Given the just-calculated range quartet, update // elims, altNum, eligibleNum, eligibleSz for(int i = 0; i < 4; i++) { if(i == c) continue; assert_leq(pairTop(pairs, d, i), pairBot(pairs, d, i)); uint32_t spread = pairSpread(pairs, d, i); if(spread == 0) { // Indicate this char at this position is // eliminated as far as this backtracking frame is // concerned, since its range is empty elims[d] |= (1 << i); assert_lt(elims[d], 16); } if(spread > 0 && ((elims[d] & (1 << i)) == 0)) { // This char at this position is an alternative if(curIsEligible) { if(curOverridesEligible) { // Only now that we know there is at least // one potential backtrack target at this // most-eligible position should we reset // these eligibility parameters lowAltQual = q; eligibleNum = 0; eligibleSz = 0; curOverridesEligible = false; // Remember these parameters in case // this turns out to be the only // eligible target eli = d; eltop = pairTop(pairs, d, i); elbot = pairBot(pairs, d, i); assert_eq(elbot-eltop, spread); elham = mmPenalty(_maqPenalty, q); elchar = "acgt"[i]; elcint = i; elignore = false; } eligibleSz += spread; eligibleNum++; } assert_gt(eligibleSz, 0); assert_gt(eligibleNum, 0); altNum++; } } } if(altNum > 0) { assert_gt(eligibleSz, 0); assert_gt(eligibleNum, 0); } assert_leq(eligibleNum, eligibleSz); assert_leq(eligibleNum, altNum); assert_lt(elims[d], 16); assert(sanityCheckEligibility(depth, d, unrevOff, lowAltQual, eligibleSz, eligibleNum, pairs, elims)); // Achieved a match, but need to keep going bool backtrackDespiteMatch = false; bool reportedPartial = false; if(cur == 0 && // we've consumed the entire pattern top < bot && // there's a hit to report stackDepth < _reportPartials && // not yet used up our mismatches _reportPartials > 0) // there are still legel backtracking targets { assert(!_halfAndHalf); if(altNum > 0) backtrackDespiteMatch = true; if(stackDepth > 0) { // This is a legit seedling; report it reportPartial(stackDepth); reportedPartial = true; } // Now continue on to find legitimate seedlings with // more mismatches than this one } // Check whether we've obtained an exact alignment when // we've been instructed not to report exact alignments bool invalidExact = false; if(cur == 0 && stackDepth == 0 && bot > top && !_reportExacts) { invalidExact = true; backtrackDespiteMatch = true; } // Set this to true if the only way to make legal progress // is via one or more additional backtracks. This is // helpful in half-and-half mode. bool mustBacktrack = false; bool invalidHalfAndHalf = false; if(_halfAndHalf) { ASSERT_ONLY(uint32_t lim = (_3revOff == _2revOff)? 2 : 3); if((d == (_5depth-1)) && top < bot) { // We're crossing the boundary separating the hi-half // from the non-seed portion of the read. // We should induce a mismatch if we haven't mismatched // yet, so that we don't waste time pursuing a match // that was covered by a previous phase assert_eq(0, _reportPartials); assert_leq(stackDepth, lim-1); invalidHalfAndHalf = (stackDepth == 0); if(stackDepth == 0 && altNum > 0) { backtrackDespiteMatch = true; mustBacktrack = true; } else if(stackDepth == 0) { // We're returning from the bottommost frame // without having found any hits; let's // sanity-check that there really aren't any return false; } } else if((d == (_3depth-1)) && top < bot) { // We're crossing the boundary separating the lo-half // from the non-seed portion of the read assert_eq(0, _reportPartials); assert_leq(stackDepth, lim); assert_gt(stackDepth, 0); // Count the mismatches in the lo and hi halves uint32_t loHalfMms = 0, hiHalfMms = 0; assert_geq(_mms.size(), stackDepth); for(size_t i = 0; i < stackDepth; i++) { uint32_t d = _qlen - _mms[i] - 1; if (d < _5depth) hiHalfMms++; else if(d < _3depth) loHalfMms++; else assert(false); } assert_leq(loHalfMms + hiHalfMms, lim); invalidHalfAndHalf = (loHalfMms == 0 || hiHalfMms == 0); if((stackDepth < 2 || invalidHalfAndHalf) && altNum > 0) { // We backtracked fewer times than necessary; // force a backtrack mustBacktrack = true; backtrackDespiteMatch = true; } else if(stackDepth < 2) { return false; } } if(d < _5depth-1) { assert_leq(stackDepth, lim-1); } else if(d >= _5depth && d < _3depth-1) { assert_gt(stackDepth, 0); assert_leq(stackDepth, lim); } } // This is necessary for the rare case where we're about // to declare success because bot > top and we've consumed // the final character, but all hits between top and bot // are spurious. This check ensures that we keep looking // for non-spurious hits in that case. if(cur == 0 && // we made it to the left-hand-side of the read bot > top && // there are alignments to report !invalidHalfAndHalf && // alignment isn't disqualified by half-and-half requirement !invalidExact && // alignment isn't disqualified by no-exact-hits setting !reportedPartial) // for when it's a partial alignment we've already reported { bool ret = reportAlignment(stackDepth, top, bot, ham); if(!ret) { // reportAlignment returned false, so enter the // backtrack loop and keep going top = bot; } else { // reportAlignment returned true, so stop return true; } } // // Mismatch with alternatives // while((top == bot || backtrackDespiteMatch) && altNum > 0) { if(_verbose) cout << " top (" << top << "), bot (" << bot << ") with " << altNum << " alternatives, eligible: " << eligibleNum << ", " << eligibleSz << endl; assert_gt(eligibleSz, 0); assert_gt(eligibleNum, 0); // Mismatch! Must now choose where we are going to // take our quality penalty. We can only look as far // back as our last decision point. assert(sanityCheckEligibility(depth, d, unrevOff, lowAltQual, eligibleSz, eligibleNum, pairs, elims)); // Pick out the arrow pair we selected and target it // for backtracking ASSERT_ONLY(uint32_t eligiblesVisited = 0); size_t i = d, j = 0; assert_geq(i, depth); uint32_t bttop = 0; uint32_t btbot = 0; uint32_t btham = ham; char btchar = 0; int btcint = 0; uint32_t icur = 0; // The common case is that eligibleSz == 1 if(eligibleNum > 1 || elignore) { bool foundTarget = false; // Walk from left to right for(; i >= depth; i--) { assert_geq(i, unrevOff); icur = _qlen - i - 1; // current offset into _qry uint8_t qi = qualAt(icur); assert_lt(elims[i], 16); if((qi == lowAltQual || !_considerQuals) && elims[i] != 15) { // This is the leftmost eligible position with at // least one remaining backtrack target uint32_t posSz = 0; // Add up the spreads for A, C, G, T for(j = 0; j < 4; j++) { if((elims[i] & (1 << j)) == 0) { assert_gt(pairSpread(pairs, i, j), 0); posSz += pairSpread(pairs, i, j); } } // Generate a random number assert_gt(posSz, 0); uint32_t r = _rand.nextU32() % posSz; for(j = 0; j < 4; j++) { if((elims[i] & (1 << j)) == 0) { // This range has not been eliminated ASSERT_ONLY(eligiblesVisited++); uint32_t spread = pairSpread(pairs, i, j); if(r < spread) { // This is our randomly-selected // backtrack target foundTarget = true; bttop = pairTop(pairs, i, j); btbot = pairBot(pairs, i, j); btham += mmPenalty(_maqPenalty, qi); btcint = j; btchar = "acgt"[j]; assert_leq(btham, _qualThresh); break; // found our target; we can stop } r -= spread; } } assert(foundTarget); break; // escape left-to-right walk } } assert_leq(i, d); assert_lt(j, 4); assert_leq(eligiblesVisited, eligibleNum); assert(foundTarget); assert_neq(0, btchar); assert_gt(btbot, bttop); assert_leq(btbot-bttop, eligibleSz); } else { // There was only one eligible target; we can just // copy its parameters assert_eq(1, eligibleNum); assert(!elignore); i = eli; bttop = eltop; btbot = elbot; btham += elham; j = btcint = elcint; btchar = elchar; assert_neq(0, btchar); assert_gt(btbot, bttop); assert_leq(btbot-bttop, eligibleSz); } // This is the earliest that we know what the next top/ // bot combo is going to be SideLocus::initFromTopBot(bttop, btbot, ebwt._eh, ebwt._ebwt, _preLtop, _preLbot); icur = _qlen - i - 1; // current offset into _qry // Slide over to the next backtacking frame within // pairs and elims; won't interfere with our frame or // any of our parents' frames uint32_t *newPairs = pairs + (_qlen*8); uint8_t *newElims = elims + (_qlen); // If we've selected a backtracking target that's in // the 1-revisitable region, then we ask the recursive // callee to consider the 1-revisitable region as also // being unrevisitable (since we just "used up" all of // our visits) uint32_t btUnrevOff = unrevOff; uint32_t btOneRevOff = oneRevOff; uint32_t btTwoRevOff = twoRevOff; uint32_t btThreeRevOff = threeRevOff; assert_geq(i, unrevOff); assert_geq(oneRevOff, unrevOff); assert_geq(twoRevOff, oneRevOff); assert_geq(threeRevOff, twoRevOff); if(i < oneRevOff) { // Extend unrevisitable region to include former 1- // revisitable region btUnrevOff = oneRevOff; // Extend 1-revisitable region to include former 2- // revisitable region btOneRevOff = twoRevOff; // Extend 2-revisitable region to include former 3- // revisitable region btTwoRevOff = threeRevOff; } else if(i < twoRevOff) { // Extend 1-revisitable region to include former 2- // revisitable region btOneRevOff = twoRevOff; // Extend 2-revisitable region to include former 3- // revisitable region btTwoRevOff = threeRevOff; } else if(i < threeRevOff) { // Extend 2-revisitable region to include former 3- // revisitable region btTwoRevOff = threeRevOff; } // Note the character that we're backtracking on in the // mm array: if(_mms.size() <= stackDepth) { assert_eq(_mms.size(), stackDepth); _mms.push_back(icur); } else { _mms[stackDepth] = icur; } assert_eq(1, dna4Cat[(int)btchar]); if(_refcs.size() <= stackDepth) { assert_eq(_refcs.size(), stackDepth); _refcs.push_back(btchar); } else { _refcs[stackDepth] = btchar; } #ifndef NDEBUG for(uint32_t j = 0; j < stackDepth; j++) { assert_neq(_mms[j], icur); } #endif _chars[i] = btchar; assert_leq(i+1, _qlen); bool ret; if(i+1 == _qlen) { ret = reportAlignment(stackDepth+1, bttop, btbot, btham); } else if(_halfAndHalf && !disableFtab && _2revOff == _3revOff && i+1 < (uint32_t)ebwt._eh._ftabChars && (uint32_t)ebwt._eh._ftabChars <= _5depth) { // The ftab doesn't extend past the unrevisitable portion, // so we can go ahead and use it // Rightmost char gets least significant bit-pairs int ftabChars = ebwt._eh._ftabChars; uint32_t ftabOff = (*_qry)[_qlen - ftabChars]; assert_lt(ftabOff, 4); assert_lt(ftabOff, ebwt._eh._ftabLen-1); for(int j = ftabChars - 1; j > 0; j--) { ftabOff <<= 2; if(_qlen-j == icur) { ftabOff |= btcint; } else { assert_lt((uint32_t)(*_qry)[_qlen-j], 4); ftabOff |= (uint32_t)(*_qry)[_qlen-j]; } assert_lt(ftabOff, ebwt._eh._ftabLen-1); } assert_lt(ftabOff, ebwt._eh._ftabLen-1); uint32_t ftabTop = ebwt.ftabHi(ftabOff); uint32_t ftabBot = ebwt.ftabLo(ftabOff+1); assert_geq(ftabBot, ftabTop); if(ftabTop == ftabBot) { ret = false; } else { assert(!_precalcedSideLocus); assert_leq(iham, _qualThresh); ret = backtrack(stackDepth+1, ebwt._eh._ftabChars, btUnrevOff, // new unrevisitable boundary btOneRevOff, // new 1-revisitable boundary btTwoRevOff, // new 2-revisitable boundary btThreeRevOff, // new 3-revisitable boundary ftabTop, // top arrow in range prior to 'depth' ftabBot, // bottom arrow in range prior to 'depth' btham, // weighted hamming distance so far iham, // initial weighted hamming distance newPairs, newElims); } } else { // We already called initFromTopBot for the range // we're going to continue from _precalcedSideLocus = true; assert_leq(iham, _qualThresh); // Continue from selected alternative range ret = backtrack(stackDepth+1,// added 1 mismatch to alignment i+1, // start from next position after btUnrevOff, // new unrevisitable boundary btOneRevOff, // new 1-revisitable boundary btTwoRevOff, // new 2-revisitable boundary btThreeRevOff, // new 3-revisitable boundary bttop, // top arrow in range prior to 'depth' btbot, // bottom arrow in range prior to 'depth' btham, // weighted hamming distance so far iham, // initial weighted hamming distance newPairs, newElims); } if(ret) { assert_gt(sink.numValidHits(), prehits); return true; // return, signaling that we're done } if(_bailedOnBacktracks || (_halfAndHalf && (_maxBts > 0) && (_numBts >= _maxBts))) { _bailedOnBacktracks = true; return false; } // No hit was reported; update elims[], eligibleSz, // eligibleNum, altNum _chars[i] = (*_qry)[icur]; assert_neq(15, elims[i]); ASSERT_ONLY(uint8_t oldElim = elims[i]); elims[i] |= (1 << j); assert_lt(elims[i], 16); assert_gt(elims[i], oldElim); eligibleSz -= (btbot-bttop); eligibleNum--; elignore = true; assert_geq(eligibleNum, 0); altNum--; assert_geq(altNum, 0); if(altNum == 0) { // No alternative backtracking points; all legal // backtracking targets have been exhausted assert_eq(0, altNum); assert_eq(0, eligibleSz); assert_eq(0, eligibleNum); return false; } else if(eligibleNum == 0 && _considerQuals) { // Find the next set of eligible backtrack points // by re-scanning this backtracking frame (from // 'depth' up to 'd') lowAltQual = 0xff; for(size_t k = d; k >= depth && k <= _qlen; k--) { uint32_t kcur = _qlen - k - 1; // current offset into _qry uint8_t kq = qualAt(kcur); if(k < unrevOff) break; // already visited all revisitable positions bool kCurIsAlternative = (ham + mmPenalty(_maqPenalty, kq) <= _qualThresh); bool kCurOverridesEligible = false; if(kCurIsAlternative) { if(kq < lowAltQual) { // This target is more eligible than // any targets that came before, so we // set it to supplant/override them kCurOverridesEligible = true; } if(kq <= lowAltQual) { // Position is eligible for(int l = 0; l < 4; l++) { if((elims[k] & (1 << l)) == 0) { // Not yet eliminated uint32_t spread = pairSpread(pairs, k, l); if(kCurOverridesEligible) { // Clear previous eligible results; // this one's better lowAltQual = kq; kCurOverridesEligible = false; // Keep these parameters in // case this target turns // out to be the only // eligible target and we // can avoid having to // recalculate them eligibleNum = 0; eligibleSz = 0; eli = k; eltop = pairTop(pairs, k, l); elbot = pairBot(pairs, k, l); assert_eq(elbot-eltop, spread); elham = mmPenalty(_maqPenalty, kq); elchar = "acgt"[l]; elcint = l; elignore = false; } eligibleNum++; assert_gt(spread, 0); eligibleSz += spread; } } } } } } assert_gt(eligibleNum, 0); assert_leq(eligibleNum, altNum); assert_gt(eligibleSz, 0); assert_geq(eligibleSz, eligibleNum); assert(sanityCheckEligibility(depth, d, unrevOff, lowAltQual, eligibleSz, eligibleNum, pairs, elims)); // Try again } // while(top == bot && altNum > 0) if(mustBacktrack || invalidHalfAndHalf || invalidExact) { return false; } // Mismatch with no alternatives if(top == bot && altNum == 0) { assert_eq(0, altNum); assert_eq(0, eligibleSz); assert_eq(0, eligibleNum); return false; } // Match! _chars[d] = (*_qry)[cur]; d++; cur--; } // while(cur < _qlen) assert_eq(0xffffffff, cur); assert_gt(bot, top); if(_reportPartials > 0) { // Stack depth should not exceed given hamming distance assert_leq(stackDepth, _reportPartials); } bool ret = false; if(stackDepth >= _reportPartials) { ret = reportAlignment(stackDepth, top, bot, ham); } return ret; } /** * Pretty print a hit along with the backtracking constraints. */ void printHit(const Hit& h) { ::printHit(*_os, h, *_qry, _qlen, _unrevOff, _1revOff, _2revOff, _3revOff, _ebwt->fw()); } /** * Return true iff we're enforcing a half-and-half constraint * (forced edits in both seed halves). */ bool halfAndHalf() const { return _halfAndHalf; } protected: /** * Return true iff we're OK to continue after considering which * half-seed boundary we're passing through, together with the * number of mismatches accumulated so far. Return false if we * should stop because a half-and-half constraint is violated. If * we're not currently passing a half-seed boundary, just return * true. */ bool hhCheck(uint32_t stackDepth, uint32_t depth, const std::vector& mms, bool empty) { ASSERT_ONLY(uint32_t lim = (_3revOff == _2revOff)? 2 : 3); if((depth == (_5depth-1)) && !empty) { // We're crossing the boundary separating the hi-half // from the non-seed portion of the read. // We should induce a mismatch if we haven't mismatched // yet, so that we don't waste time pursuing a match // that was covered by a previous phase assert_eq(0, _reportPartials); assert_leq(stackDepth, lim-1); return stackDepth > 0; } else if((depth == (_3depth-1)) && !empty) { // We're crossing the boundary separating the lo-half // from the non-seed portion of the read assert_eq(0, _reportPartials); assert_leq(stackDepth, lim); assert_gt(stackDepth, 0); // Count the mismatches in the lo and hi halves uint32_t loHalfMms = 0, hiHalfMms = 0; for(size_t i = 0; i < stackDepth; i++) { uint32_t depth = _qlen - mms[i] - 1; if (depth < _5depth) hiHalfMms++; else if(depth < _3depth) loHalfMms++; else assert(false); } assert_leq(loHalfMms + hiHalfMms, lim); bool invalidHalfAndHalf = (loHalfMms == 0 || hiHalfMms == 0); return (stackDepth >= 2 && !invalidHalfAndHalf); } if(depth < _5depth-1) { assert_leq(stackDepth, lim-1); } else if(depth >= _5depth && depth < _3depth-1) { assert_gt(stackDepth, 0); assert_leq(stackDepth, lim); } return true; } /** * Calculate the stratum of the partial (or full) alignment * currently under consideration. Stratum is equal to the number * of mismatches in the seed portion of the alignment. */ int calcStratum(const std::vector& mms, uint32_t stackDepth) { int stratum = 0; for(size_t i = 0; i < stackDepth; i++) { if(mms[i] >= (_qlen - _3revOff)) { // This mismatch falls within the seed; count it // toward the stratum to report stratum++; // Don't currently support more than 3 // mismatches in the seed assert_leq(stratum, 3); } } return stratum; } /** * Mark character c at depth d as being eliminated with respect to * future backtracks. */ void eliminate(uint8_t *elims, uint32_t d, int c) { if(c < 4) { elims[d] = (1 << c); assert_gt(elims[d], 0); assert_lt(elims[d], 16); } else { elims[d] = 0; } assert_lt(elims[d], 16); } /** * Return true iff the state of the backtracker as encoded by * stackDepth, d and iham is compatible with the current half-and- * half alignment mode. prehits is for sanity checking when * bailing. */ bool hhCheckTop(uint32_t stackDepth, uint32_t d, uint32_t iham, const std::vector& mms, uint64_t prehits = U64(0xffffffffffffffff)) { assert_eq(0, _reportPartials); // Crossing from the hi-half into the lo-half if(d == _5depth) { if(_3revOff == _2revOff) { // Total of 2 mismatches allowed: 1 hi, 1 lo // The backtracking logic should have prevented us from // backtracking more than once into this region assert_leq(stackDepth, 1); // Reject if we haven't encountered mismatch by this point if(stackDepth == 0) { return false; } } else { // if(_3revOff != _2revOff) // Total of 3 mismatches allowed: 1 hi, 1 or 2 lo // The backtracking logic should have prevented us from // backtracking more than twice into this region assert_leq(stackDepth, 2); // Reject if we haven't encountered mismatch by this point if(stackDepth < 1) { return false; } } } else if(d == _3depth) { // Crossing from lo-half to outside of the seed if(_3revOff == _2revOff) { // Total of 2 mismatches allowed: 1 hi, 1 lo // The backtracking logic should have prevented us from // backtracking more than twice within this region assert_leq(stackDepth, 2); // Must have encountered two mismatches by this point if(stackDepth < 2) { // We're returning from the bottommost frame // without having found any hits; let's // sanity-check that there really aren't any return false; } } else { // if(_3revOff != _2revOff) // Total of 3 mismatches allowed: 1 hi, 1 or 2 lo // Count the mismatches in the lo and hi halves int loHalfMms = 0, hiHalfMms = 0; assert_geq(mms.size(), stackDepth); for(size_t i = 0; i < stackDepth; i++) { uint32_t d = _qlen - mms[i] - 1; if (d < _5depth) hiHalfMms++; else if(d < _3depth) loHalfMms++; else assert(false); } assert_leq(loHalfMms + hiHalfMms, 3); assert_gt(hiHalfMms, 0); if(loHalfMms == 0) { // We're returning from the bottommost frame // without having found any hits; let's // sanity-check that there really aren't any return false; } assert_geq(stackDepth, 2); // The backtracking logic should have prevented us from // backtracking more than twice within this region assert_leq(stackDepth, 3); } } else { // We didn't just cross a boundary, so do an in-between check if(d >= _5depth) { assert_geq(stackDepth, 1); } else if(d >= _3depth) { assert_geq(stackDepth, 2); } } return true; } /** * Return the Phred quality value for the most likely base at * offset 'off' in the read. */ inline uint8_t qualAt(size_t off) { return phredCharToPhredQual((*_qual)[off]); } /// Get the top offset for character c at depth d inline uint32_t pairTop(uint32_t* pairs, size_t d, size_t c) { return pairs[d*8 + c + 0]; } /// Get the bot offset for character c at depth d inline uint32_t pairBot(uint32_t* pairs, size_t d, size_t c) { return pairs[d*8 + c + 4]; } /// Get the spread between the bot and top offsets for character c /// at depth d inline uint32_t pairSpread(uint32_t* pairs, size_t d, size_t c) { assert_geq(pairBot(pairs, d, c), pairTop(pairs, d, c)); return pairBot(pairs, d, c) - pairTop(pairs, d, c); } /** * Tally how many Ns occur in the seed region and in the ftab- * jumpable region of the read. Check whether the mismatches * induced by the Ns already violates the current policy. Return * false if the policy is already violated, true otherwise. */ bool tallyNs(int& nsInSeed, int& nsInFtab) { const Ebwt >& ebwt = *_ebwt; int ftabChars = ebwt._eh._ftabChars; // Count Ns in the seed region of the read and short-circuit if // the configuration of Ns guarantees that there will be no // valid alignments given the backtracking constraints. for(size_t i = 0; i < _3revOff; i++) { if((int)(*_qry)[_qlen-i-1] == 4) { nsInSeed++; if(nsInSeed == 1) { if(i < _unrevOff) { return false; // Exceeded mm budget on Ns alone } } else if(nsInSeed == 2) { if(i < _1revOff) { return false; // Exceeded mm budget on Ns alone } } else if(nsInSeed == 3) { if(i < _2revOff) { return false; // Exceeded mm budget on Ns alone } } else { assert_gt(nsInSeed, 3); return false; // Exceeded mm budget on Ns alone } } } // Calculate the number of Ns there are in the region that // would get jumped over if the ftab were used. for(size_t i = 0; i < (size_t)ftabChars && i < _qlen; i++) { if((int)(*_qry)[_qlen-i-1] == 4) nsInFtab++; } return true; } /** * Calculate the offset into the ftab for the rightmost 'ftabChars' * characters of the current query. Rightmost char gets least * significant bit-pair. */ uint32_t calcFtabOff() { const Ebwt >& ebwt = *_ebwt; int ftabChars = ebwt._eh._ftabChars; uint32_t ftabOff = (*_qry)[_qlen - ftabChars]; assert_lt(ftabOff, 4); assert_lt(ftabOff, ebwt._eh._ftabLen-1); for(int i = ftabChars - 1; i > 0; i--) { ftabOff <<= 2; assert_lt((uint32_t)(*_qry)[_qlen-i], 4); ftabOff |= (uint32_t)(*_qry)[_qlen-i]; assert_lt(ftabOff, ebwt._eh._ftabLen-1); } assert_lt(ftabOff, ebwt._eh._ftabLen-1); return ftabOff; } /** * Mutate the _qry string according to the contents of the _muts * array, which represents a partial alignment. */ void applyPartialMutations() { if(_muts == NULL) { // No mutations to apply return; } for(size_t i = 0; i < length(*_muts); i++) { const QueryMutation& m = (*_muts)[i]; assert_lt(m.pos, _qlen); assert_leq(m.oldBase, 4); assert_lt(m.newBase, 4); assert_neq(m.oldBase, m.newBase); assert_eq((uint32_t)((*_qry)[m.pos]), (uint32_t)m.oldBase); (*_qry)[m.pos] = (Dna5)(int)m.newBase; // apply it } } /** * Take partial-alignment mutations present in the _muts list and * place them on the _mm list so that they become part of the * reported alignment. */ void promotePartialMutations(int stackDepth) { if(_muts == NULL) { // No mutations to undo return; } size_t numMuts = length(*_muts); assert_leq(numMuts, _qlen); for(size_t i = 0; i < numMuts; i++) { // Entries in _mms[] are in terms of offset into // _qry - not in terms of offset from 3' or 5' end assert_lt(stackDepth + i, _qlen); // All partial-alignment mutations should fall // within bounds assert_lt((*_muts)[i].pos, _qlen); // All partial-alignment mutations should fall // within unrevisitable region assert_lt(_qlen - (*_muts)[i].pos - 1, _unrevOff); #ifndef NDEBUG // Shouldn't be any overlap between mismatched positions // and positions that mismatched in the partial alignment. for(size_t j = 0; j < stackDepth + i; j++) { assert_neq(_mms[j], (uint32_t)(*_muts)[i].pos); } #endif if(_mms.size() <= stackDepth + i) { assert_eq(_mms.size(), stackDepth + i); _mms.push_back((*_muts)[i].pos); } else { _mms[stackDepth + i] = (*_muts)[i].pos; } if(_refcs.size() <= stackDepth + i) { assert_eq(_refcs.size(), stackDepth + i); _refcs.push_back("ACGT"[(*_muts)[i].newBase]); } else { _refcs[stackDepth + i] = "ACGT"[(*_muts)[i].newBase]; } } } /** * Undo mutations to the _qry string, returning it to the original * read. */ void undoPartialMutations() { if(_muts == NULL) { // No mutations to undo return; } for(size_t i = 0; i < length(*_muts); i++) { const QueryMutation& m = (*_muts)[i]; assert_lt(m.pos, _qlen); assert_leq(m.oldBase, 4); assert_lt(m.newBase, 4); assert_neq(m.oldBase, m.newBase); assert_eq((uint32_t)((*_qry)[m.pos]), (uint32_t)m.newBase); (*_qry)[m.pos] = (Dna5)(int)m.oldBase; // undo it } } /** * Report a range of alignments with # mismatches = stackDepth and * with the mutations (also mismatches) contained in _muts. The * range is delimited by top and bot. Returns true iff one or more * full alignments were successfully reported and the caller can * stop searching. */ bool reportAlignment(uint32_t stackDepth, uint32_t top, uint32_t bot, uint16_t cost) { #ifndef NDEBUG // No two elements of _mms[] should be the same assert_geq(_mms.size(), stackDepth); for(size_t i = 0; i < stackDepth; i++) { for(size_t j = i+1; j < stackDepth; j++) { assert_neq(_mms[j], _mms[i]); } // All elements of _mms[] should fall within bounds assert_lt(_mms[i], _qlen); } #endif if(_reportPartials) { assert_leq(stackDepth, _reportPartials); if(stackDepth > 0) { // Report this partial alignment. A partial alignment // is defined purely by its mismatches; top and bot are // ignored. reportPartial(stackDepth); } return false; // keep going - we want to find all partial alignments } int stratum = 0; if(stackDepth > 0) { stratum = calcStratum(_mms, stackDepth); } assert_lt(stratum, 4); assert_geq(stratum, 0); bool hit; // If _muts != NULL then this alignment extends a partial // alignment, so we have to account for the differences present // in the partial. if(_muts != NULL) { // Undo partial-alignment mutations to get original _qry ASSERT_ONLY(String tmp = (*_qry)); undoPartialMutations(); assert_neq(tmp, (*_qry)); // Add the partial-alignment mutations to the _mms[] array promotePartialMutations(stackDepth); // All muts are in the seed, so they count toward the stratum size_t numMuts = length(*_muts); stratum += numMuts; cost |= (stratum << 14); assert_geq(cost, (uint32_t)(stratum << 14)); // Report the range of full alignments hit = reportFullAlignment(stackDepth + numMuts, top, bot, stratum, cost); // Re-apply partial-alignment mutations applyPartialMutations(); assert_eq(tmp, (*_qry)); } else { // Report the range of full alignments cost |= (stratum << 14); assert_geq(cost, (uint32_t)(stratum << 14)); hit = reportFullAlignment(stackDepth, top, bot, stratum, cost); } return hit; } /** * Report a range of full alignments with # mismatches = stackDepth. * The range is delimited by top and bot. Returns true if one or * more alignments were successfully reported. Returns true iff * one or more full alignments were successfully reported and the * caller can stop searching. */ bool reportFullAlignment(uint32_t stackDepth, uint32_t top, uint32_t bot, int stratum, uint16_t cost) { BowtieContext::Search* ctx = BowtieContext::getSearchContext(); assert_gt(bot, top); if(stackDepth == 0 && !_reportExacts) { // We are not reporting exact hits (usually because we've // already reported them as part of a previous invocation // of the backtracker) return false; } assert(!_reportRanges); uint32_t spread = bot - top; // Pick a random spot in the range to begin report uint32_t r = top + (_rand.nextU32() % spread); for(uint32_t i = 0; i < spread; i++) { uint32_t ri = r + i; if(ri >= bot) ri -= spread; // reportChaseOne takes the _mms[] list in terms of // their indices into the query string; not in terms // of their offset from the 3' or 5' end. assert_geq(cost, (uint32_t)(stratum << 14)); if(_ebwt->reportChaseOne((*_qry), _qual, _name, _color, ctx->colorExEnds, ctx->snpPhred, _refs, _mms, _refcs, stackDepth, ri, top, bot, _qlen, stratum, cost, _patid, _seed, _params)) { // Return value of true means that we can stop return true; } // Return value of false means that we should continue // searching. This could happen if we the call to // reportChaseOne() reported a hit, but the user asked for // multiple hits and we haven't reached the ceiling yet. // This might also happen if the call to reportChaseOne() // didn't report a hit because the alignment was spurious // (i.e. overlapped some padding). } // All range elements were examined and we should keep going return false; } /** * Report the partial alignment represented by the current stack * state (_mms[] and stackDepth). */ bool reportPartial(uint32_t stackDepth) { // Sanity-check stack depth if(_3revOff != _2revOff) { assert_leq(stackDepth, 3); } else if(_2revOff != _1revOff) { assert_leq(stackDepth, 2); } else { assert_leq(stackDepth, 1); } // Possibly report assert_gt(_reportPartials, 0); assert(_partials != NULL); ASSERT_ONLY(uint32_t qualTot = 0); PartialAlignment al; al.u64.u64 = U64(0xffffffffffffffff); assert_leq(stackDepth, 3); assert_gt(stackDepth, 0); // First mismatch assert_gt(_mms.size(), 0); assert_lt(_mms[0], _qlen); // First, append the mismatch position in the read al.entry.pos0 = (uint16_t)_mms[0]; // pos ASSERT_ONLY(uint8_t qual0 = mmPenalty(_maqPenalty, phredCharToPhredQual((*_qual)[_mms[0]]))); ASSERT_ONLY(qualTot += qual0); uint32_t ci = _qlen - _mms[0] - 1; // _chars[] is index in terms of RHS-relative depth int c = (int)(Dna5)_chars[ci]; assert_lt(c, 4); assert_neq(c, (int)(*_qry)[_mms[0]]); // Second, append the substituted character for the position al.entry.char0 = c; if(stackDepth > 1) { assert_gt(_mms.size(), 1); // Second mismatch assert_lt(_mms[1], _qlen); // First, append the mismatch position in the read al.entry.pos1 = (uint16_t)_mms[1]; // pos ASSERT_ONLY(uint8_t qual1 = mmPenalty(_maqPenalty, phredCharToPhredQual((*_qual)[_mms[1]]))); ASSERT_ONLY(qualTot += qual1); ci = _qlen - _mms[1] - 1; // _chars[] is index in terms of RHS-relative depth c = (int)(Dna5)_chars[ci]; assert_lt(c, 4); assert_neq(c, (int)(*_qry)[_mms[1]]); // Second, append the substituted character for the position al.entry.char1 = c; if(stackDepth > 2) { assert_gt(_mms.size(), 2); // Second mismatch assert_lt(_mms[2], _qlen); // First, append the mismatch position in the read al.entry.pos2 = (uint16_t)_mms[2]; // pos ASSERT_ONLY(uint8_t qual2 = mmPenalty(_maqPenalty, phredCharToPhredQual((*_qual)[_mms[2]]))); ASSERT_ONLY(qualTot += qual2); ci = _qlen - _mms[2] - 1; // _chars[] is index in terms of RHS-relative depth c = (int)(Dna5)_chars[ci]; assert_lt(c, 4); assert_neq(c, (int)(*_qry)[_mms[2]]); // Second, append the substituted character for the position al.entry.char2 = c; } else { // Signal that the '2' slot is empty al.entry.pos2 = 0xffff; } } else { // Signal that the '1' slot is empty al.entry.pos1 = 0xffff; } assert_leq(qualTot, _qualThresh); assert(validPartialAlignment(al)); #ifndef NDEBUG assert(al.repOk(_qualThresh, _qlen, (*_qual), _maqPenalty)); for(size_t i = 0; i < _partialsBuf.size(); i++) { assert(validPartialAlignment(_partialsBuf[i])); assert(!samePartialAlignment(_partialsBuf[i], al)); } #endif _partialsBuf.push_back(al); return true; } /** * Check that the given eligibility parameters (lowAltQual, * eligibleSz, eligibleNum) are correct, given the appropriate * inputs (pairs, elims, depth, d, unrevOff) */ bool sanityCheckEligibility(uint32_t depth, uint32_t d, uint32_t unrevOff, uint32_t lowAltQual, uint32_t eligibleSz, uint32_t eligibleNum, uint32_t* pairs, uint8_t* elims) { // Sanity check that the lay of the land is as we // expect given eligibleNum and eligibleSz size_t i = max(depth, unrevOff), j = 0; uint32_t cumSz = 0; uint32_t eligiblesVisited = 0; for(; i <= d; i++) { uint32_t icur = _qlen - i - 1; // current offset into _qry uint8_t qi = qualAt(icur); assert_lt(elims[i], 16); if((qi == lowAltQual || !_considerQuals) && elims[i] != 15) { // This is an eligible position with at least // one remaining backtrack target for(j = 0; j < 4; j++) { if((elims[i] & (1 << j)) == 0) { // This pair has not been eliminated assert_gt(pairBot(pairs, i, j), pairTop(pairs, i, j)); cumSz += pairSpread(pairs, i, j); eligiblesVisited++; } } } } assert_eq(cumSz, eligibleSz); assert_eq(eligiblesVisited, eligibleNum); return true; } const BitPairReference* _refs; // reference sequences (or NULL if not colorspace) String* _qry; // query (read) sequence size_t _qlen; // length of _qry String* _qual; // quality values for _qry String* _name; // name of _qry bool _color; // whether read is colorspace const Ebwt >* _ebwt; // Ebwt to search in const EbwtSearchParams >& _params; // Ebwt to search in uint32_t _unrevOff; // unrevisitable chunk uint32_t _1revOff; // 1-revisitable chunk uint32_t _2revOff; // 2-revisitable chunk uint32_t _3revOff; // 3-revisitable chunk /// Whether to round qualities off Maq-style when calculating penalties bool _maqPenalty; uint32_t _qualThresh; // only accept hits with weighted // hamming distance <= _qualThresh uint32_t *_pairs; // ranges, leveled in parallel // with decision stack uint8_t *_elims; // which ranges have been // eliminated, leveled in parallel // with decision stack std::vector _mms; // array for holding mismatches std::vector _refcs; // array for holding mismatches // Entries in _mms[] are in terms of offset into // _qry - not in terms of offset from 3' or 5' end char *_chars; // characters selected so far // If > 0, report partial alignments up to this many mismatches uint32_t _reportPartials; /// Do not report alignments with stratum < this limit bool _reportExacts; /// When reporting a full alignment, report top/bot; don't chase /// any of the results bool _reportRanges; /// Append partial alignments here PartialAlignmentManager *_partials; /// Set of mutations that apply for a partial alignment String *_muts; /// Reference texts (NULL if they are unavailable vector >* _os; /// Whether to use the _os array together with a naive matching /// algorithm to double-check reported alignments (or the lack /// thereof) bool _sanity; /// Whether to consider quality values when deciding where to /// backtrack bool _considerQuals; bool _halfAndHalf; /// Depth of 5'-seed-half border uint32_t _5depth; /// Depth of 3'-seed-half border uint32_t _3depth; /// Default quals String _qualDefault; /// Number of backtracks in last call to backtrack() uint32_t _numBts; /// Number of backtracks since last reset uint32_t _totNumBts; /// Max # of backtracks to allow before giving up uint32_t _maxBts; /// Whether we precalcualted the Ebwt locus information for the /// next top/bot pair bool _precalcedSideLocus; /// Precalculated top locus SideLocus _preLtop; /// Precalculated bot locus SideLocus _preLbot; /// Flag to record whether a 'false' return from backtracker is due /// to having exceeded one or more backrtacking limits bool _bailedOnBacktracks; /// Source of pseudo-random numbers RandomSource _rand; /// Be talkative bool _verbose; uint64_t _ihits; // Holding area for partial alignments vector _partialsBuf; // Current range to expose to consumers Range _curRange; uint32_t _patid; uint32_t _seed; #ifndef NDEBUG std::set allTops_; #endif }; /** * Class that coordinates quality- and quantity-aware backtracking over * some range of a read sequence. * * The creator can configure the BacktrackManager to treat different * stretches of the read differently. */ class EbwtRangeSource : public RangeSource { typedef Ebwt > TEbwt; typedef std::pair TIntPair; public: EbwtRangeSource( const TEbwt* ebwt, bool fw, uint32_t qualLim, bool reportExacts, bool verbose, bool quiet, int halfAndHalf, bool partial, bool maqPenalty, bool qualOrder, AlignerMetrics *metrics = NULL) : RangeSource(), qry_(NULL), qlen_(0), qual_(NULL), name_(NULL), altQry_(NULL), altQual_(NULL), alts_(0), fuzzy_(false), ebwt_(ebwt), fw_(fw), offRev0_(0), offRev1_(0), offRev2_(0), offRev3_(0), maqPenalty_(maqPenalty), qualOrder_(qualOrder), qualLim_(qualLim), reportExacts_(reportExacts), halfAndHalf_(halfAndHalf), partial_(partial), depth5_(0), depth3_(0), verbose_(verbose), quiet_(quiet), skippingThisRead_(false), metrics_(metrics) { curEbwt_ = ebwt_; } /** * Set a new query read. */ virtual void setQuery(ReadBuf& r, Range *seedRange) { const bool ebwtFw = ebwt_->fw(); if(ebwtFw) { qry_ = fw_ ? &r.patFw : &r.patRc; qual_ = fw_ ? &r.qual : &r.qualRev; altQry_ = (String*)(fw_ ? r.altPatFw : r.altPatRc); altQual_ = (String*)(fw_ ? r.altQual : r.altQualRev); } else { qry_ = fw_ ? &r.patFwRev : &r.patRcRev; qual_ = fw_ ? &r.qualRev : &r.qual; altQry_ = (String*)(fw_ ? r.altPatFwRev : r.altPatRcRev); altQual_ = (String*)(fw_ ? r.altQualRev : r.altQual); } alts_ = r.alts; name_ = &r.name; fuzzy_ = r.fuzzy; if(seedRange != NULL) seedRange_ = *seedRange; else seedRange_.invalidate(); qlen_ = length(*qry_); skippingThisRead_ = false; // Apply edits from the partial alignment to the query pattern if(seedRange_.valid()) { qryBuf_ = *qry_; const size_t srSz = seedRange_.mms.size(); assert_gt(srSz, 0); assert_eq(srSz, seedRange_.refcs.size()); for(size_t i = 0; i < srSz; i++) { assert_lt(seedRange_.mms[i], qlen_); char rc = (char)seedRange_.refcs[i]; assert(rc == 'A' || rc == 'C' || rc == 'G' || rc == 'T'); ASSERT_ONLY(char oc = (char)qryBuf_[qlen_ - seedRange_.mms[i] - 1]); assert_neq(rc, oc); qryBuf_[qlen_ - seedRange_.mms[i] - 1] = (Dna5)rc; assert_neq((Dna5)rc, (*qry_)[qlen_ - seedRange_.mms[i] - 1]); } qry_ = &qryBuf_; } // Make sure every qual is a valid qual ASCII character (>= 33) for(size_t i = 0; i < length(*qual_); i++) { assert_geq((*qual_)[i], 33); for(int j = 0; j < alts_; j++) { assert_geq(altQual_[j][i], 33); } } assert_geq(length(*qual_), qlen_); this->done = false; this->foundRange = false; color_ = r.color; rand_.init(r.seed); } /** * Set backtracking constraints. */ void setOffs(uint32_t depth5, // depth of far edge of hi-half uint32_t depth3, // depth of far edge of lo-half uint32_t unrevOff, // depth above which we cannot backtrack uint32_t revOff1, // depth above which we may backtrack just once uint32_t revOff2, // depth above which we may backtrack just twice uint32_t revOff3) // depth above which we may backtrack just three times { depth5_ = depth5; depth3_ = depth3; assert_geq(depth3_, depth5_); offRev0_ = unrevOff; offRev1_ = revOff1; offRev2_ = revOff2; offRev3_ = revOff3; } /** * Return true iff this RangeSource is allowed to report exact * alignments (exact = no edits). */ bool reportExacts() const { return reportExacts_; } /// Return the current range virtual Range& range() { return curRange_; } /** * Set qlen_ according to parameter, except don't let it fall below * the length of the query. */ void setQlen(uint32_t qlen) { assert(qry_ != NULL); qlen_ = min(length(*qry_), qlen); } /** * Initiate continuations so that the next call to advance() begins * a new search. Note that contMan is empty upon return if there * are no valid continuations to begin with. Also note that * calling initConts() may result in finding a range (i.e., if we * immediately jump to a valid range using the ftab). */ virtual void initBranch(PathManager& pm) { assert(curEbwt_ != NULL); assert_gt(length(*qry_), 0); assert_leq(qlen_, length(*qry_)); assert_geq(length(*qual_), length(*qry_)); const Ebwt >& ebwt = *ebwt_; int ftabChars = ebwt._eh._ftabChars; this->foundRange = false; int nsInSeed = 0; int nsInFtab = 0; ASSERT_ONLY(allTops_.clear()); if(skippingThisRead_) { this->done = true; return; } if(qlen_ < 4) { uint32_t maxmms = 0; if(offRev0_ != offRev1_) maxmms = 1; if(offRev1_ != offRev2_) maxmms = 2; if(offRev2_ != offRev3_) maxmms = 3; if(qlen_ <= maxmms) { if(!quiet_) { ThreadSafe _ts(&(BowtieContext::getSearchContext()->gLock)); cerr << "Warning: Read (" << (*name_) << ") is less than " << (maxmms+1) << " characters long; skipping..." << endl; } this->done = true; skippingThisRead_ = true; return; } } if(!tallyNs(nsInSeed, nsInFtab)) { // No alignments are possible because of the distribution // of Ns in the read in combination with the backtracking // constraints. return; } // icost = total cost penalty (major bits = stratum, minor bits = // quality penalty) incurred so far by partial alignment uint16_t icost = (seedRange_.valid()) ? seedRange_.cost : 0; // iham = total quality penalty incurred so far by partial alignment uint16_t iham = (seedRange_.valid() && qualOrder_) ? (seedRange_.cost & ~0xc000): 0; assert_leq(iham, qualLim_); // m = depth beyond which ftab must not extend or else we might // miss some legitimate paths uint32_t m = min(offRev0_, qlen_); // Let skipInvalidExact = true if using the ftab would be a // waste because it would jump directly to an alignment we // couldn't use. bool ftabSkipsToEnd = (qlen_ == (uint32_t)ftabChars); bool skipInvalidExact = (!reportExacts_ && ftabSkipsToEnd); // If it's OK to use the ftab... if(nsInFtab == 0 && m >= (uint32_t)ftabChars && !skipInvalidExact) { // Use the ftab to jump 'ftabChars' chars into the read // from the right uint32_t ftabOff = calcFtabOff(); uint32_t top = ebwt.ftabHi(ftabOff); uint32_t bot = ebwt.ftabLo(ftabOff+1); if(qlen_ == (uint32_t)ftabChars && bot > top) { // We found a range with 0 mismatches immediately. Set // fields to indicate we found a range. assert(reportExacts_); curRange_.top = top; curRange_.bot = bot; curRange_.stratum = (icost >> 14); curRange_.cost = icost; curRange_.numMms = 0; curRange_.ebwt = ebwt_; curRange_.fw = fw_; curRange_.mms.clear(); // no mismatches curRange_.refcs.clear(); // no mismatches // Lump in the edits from the partial alignment addPartialEdits(); assert(curRange_.repOk()); // no need to do anything with curRange_.refcs this->foundRange = true; //this->done = true; return; } else if (bot > top) { // We have a range to extend assert_leq(top, ebwt._eh._len); assert_leq(bot, ebwt._eh._len); Branch *b = pm.bpool.alloc(); if(b == NULL) { assert(pm.empty()); return; } if(!b->init( pm.rpool, pm.epool, pm.bpool.lastId(), qlen_, offRev0_, offRev1_, offRev2_, offRev3_, 0, ftabChars, icost, iham, top, bot, ebwt._eh, ebwt._ebwt)) { // Negative result from b->init() indicates we ran // out of best-first chunk memory assert(pm.empty()); return; } assert(!b->curtailed_); assert(!b->exhausted_); assert_gt(b->depth3_, 0); pm.push(b); // insert into priority queue assert(!pm.empty()); } else { // The arrows are already closed within the // unrevisitable region; give up } } else { // We can't use the ftab, so we start from the rightmost // position and use _fchr Branch *b = pm.bpool.alloc(); if(b == NULL) { assert(pm.empty()); return; } if(!b->init(pm.rpool, pm.epool, pm.bpool.lastId(), qlen_, offRev0_, offRev1_, offRev2_, offRev3_, 0, 0, icost, iham, 0, 0, ebwt._eh, ebwt._ebwt)) { // Negative result from b->init() indicates we ran // out of best-first chunk memory assert(pm.empty()); return; } assert(!b->curtailed_); assert(!b->exhausted_); assert_gt(b->depth3_, 0); pm.push(b); // insert into priority queue assert(!pm.empty()); } return; } /** * Advance along the lowest-cost branch managed by the given * PathManager. Keep advancing until condition 'until' is * satisfied. Typically, the stopping condition 'until' is * set to stop whenever pm's minCost changes. */ virtual void advanceBranch(int until, uint16_t minCost, PathManager& pm) { assert(curEbwt_ != NULL); // Let this->foundRange = false; we'll set it to true iff this call // to advance yielded a new valid-alignment range. this->foundRange = false; // Can't have already exceeded weighted hamming distance threshold assert_gt(length(*qry_), 0); assert_leq(qlen_, length(*qry_)); assert_geq(length(*qual_), length(*qry_)); assert(!pm.empty()); do { assert(pm.repOk()); // Get the highest-priority branch according to the priority // queue in 'pm' Branch* br = pm.front(); // Shouldn't be curtailed or exhausted assert(!br->exhausted_); assert(!br->curtailed_); assert_gt(br->depth3_, 0); assert_leq(br->ham_, qualLim_); if(verbose_) { br->print((*qry_), (*qual_), minCost, cout, (halfAndHalf_>0), partial_, fw_, ebwt_->fw()); if(!br->edits_.empty()) { cout << "Edit: "; for(size_t i = 0; i < br->edits_.size(); i++) { Edit e = br->edits_.get(i); cout << (curEbwt_->fw() ? (qlen_ - e.pos - 1) : e.pos) << (char)e.chr; if(i < br->edits_.size()-1) cout << " "; } cout << endl; } } assert(br->repOk(qlen_)); ASSERT_ONLY(int stratum = br->cost_ >> 14); // shift the stratum over assert_lt(stratum, 4); // Not necessarily true with rounding uint32_t depth = br->tipDepth(); const Ebwt >& ebwt = *ebwt_; if(halfAndHalf_ > 0) assert_gt(depth3_, depth5_); bool reportedPartial = false; bool invalidExact = false; bool empty = false; bool hit = false; uint16_t cost = br->cost_; uint32_t cur = 0; uint32_t nedits = 0; if(halfAndHalf_ && !hhCheckTop(br, depth, 0)) { // Stop extending this branch because it violates a half- // and-half constraint if(metrics_ != NULL) metrics_->curBacktracks_++; pm.curtail(br, qlen_, depth3_, qualOrder_); goto bail; } cur = qlen_ - depth - 1; // current offset into qry_ if(depth < qlen_) { // Determine whether ranges at this location are candidates // for backtracking int c = (int)(*qry_)[cur]; // get char at this position int nextc = -1; if(cur < qlen_-1) nextc = (int)(*qry_)[cur+1]; assert_leq(c, 4); // If any uncalled base's penalty is still under // the ceiling, then this position is an alternative uint8_t q[4] = {'!', '!', '!', '!'}; uint8_t bestq; // get unrounded penalties at this position if(fuzzy_) { bestq = penaltiesAt(cur, q, alts_, *qual_, altQry_, altQual_); } else { bestq = q[0] = q[1] = q[2] = q[3] = mmPenalty(maqPenalty_, qualAt(cur)); } // The current query position is a legit alternative if it a) is // not in the unrevisitable region, and b) its selection would // not necessarily cause the quality ceiling (if one exists) to // be exceeded bool curIsAlternative = (depth >= br->depth0_) && (br->ham_ + bestq <= qualLim_); ASSERT_ONLY(uint32_t obot = br->bot_); uint32_t otop = br->top_; // If c is 'N', then it's a mismatch if(c == 4 && depth > 0) { // Force the 'else if(curIsAlternative)' or 'else' // branches below br->top_ = br->bot_ = 1; } else if(c == 4) { // We'll take the 'if(br->top == 0 && br->bot == 0)' // branch below assert_eq(0, br->top_); assert_eq(0, br->bot_); } // Get the range state for the current position RangeState *rs = br->rangeState(); assert(rs != NULL); // Calculate the ranges for this position if(br->top_ == 0 && br->bot_ == 0) { // Calculate first quartet of ranges using the _fchr[] // array rs->tops[0] = ebwt._fchr[0]; rs->bots[0] = rs->tops[1] = ebwt._fchr[1]; rs->bots[1] = rs->tops[2] = ebwt._fchr[2]; rs->bots[2] = rs->tops[3] = ebwt._fchr[3]; rs->bots[3] = ebwt._fchr[4]; ASSERT_ONLY(int r =) br->installRanges(c, nextc, fuzzy_, qualLim_ - br->ham_, q); assert(r < 4 || c == 4); // Update top and bot if(c < 4) { br->top_ = rs->tops[c]; br->bot_ = rs->bots[c]; } } else if(curIsAlternative && (br->bot_ > br->top_ || c == 4)) { // Calculate next quartet of ranges. We hope that the // appropriate cache lines are prefetched. assert(br->ltop_.valid()); rs->tops[0] = rs->bots[0] = rs->tops[1] = rs->bots[1] = rs->tops[2] = rs->bots[2] = rs->tops[3] = rs->bots[3] = 0; if(br->lbot_.valid()) { if(metrics_ != NULL) metrics_->curBwtOps_++; ebwt.mapLFEx(br->ltop_, br->lbot_, rs->tops, rs->bots); } else { #ifndef NDEBUG uint32_t tmptops[] = {0, 0, 0, 0}; uint32_t tmpbots[] = {0, 0, 0, 0}; SideLocus ltop, lbot; ltop.initFromRow(otop, ebwt_->_eh, ebwt_->_ebwt); lbot.initFromRow(obot, ebwt_->_eh, ebwt_->_ebwt); ebwt.mapLFEx(ltop, lbot, tmptops, tmpbots); #endif if(metrics_ != NULL) metrics_->curBwtOps_++; int cc = ebwt.mapLF1(otop, br->ltop_); br->top_ = otop; assert(cc == -1 || (cc >= 0 && cc < 4)); if(cc >= 0) { assert_lt(cc, 4); rs->tops[cc] = br->top_; rs->bots[cc] = (br->top_ + 1); } #ifndef NDEBUG for(int i = 0; i < 4; i++) { assert_eq(tmpbots[i] - tmptops[i], rs->bots[i] - rs->tops[i]); } #endif } ASSERT_ONLY(int r =) br->installRanges(c, nextc, fuzzy_, qualLim_ - br->ham_, q); assert(r < 4 || c == 4); // Update top and bot if(c < 4) { br->top_ = rs->tops[c]; br->bot_ = rs->bots[c]; } else { br->top_ = br->bot_ = 1; } } else if(br->bot_ > br->top_) { // This read position is not a legitimate backtracking // alternative. No need to do the bookkeeping for the // entire quartet, just do c. We hope that the // appropriate cache lines are prefetched before now; // otherwise, we're about to take an expensive cache // miss. assert(br->ltop_.valid()); rs->eliminated_ = true; // eliminate all alternatives leaving this node assert(br->eliminated(br->len_)); if(c < 4) { if(br->top_ + 1 == br->bot_) { if(metrics_ != NULL) metrics_->curBwtOps_++; br->bot_ = br->top_ = ebwt.mapLF1(br->top_, br->ltop_, c); if(br->bot_ != 0xffffffff) br->bot_++; } else { if(metrics_ != NULL) metrics_->curBwtOps_++; br->top_ = ebwt.mapLF(br->ltop_, c); assert(br->lbot_.valid()); if(metrics_ != NULL) metrics_->curBwtOps_++; br->bot_ = ebwt.mapLF(br->lbot_, c); } } } else { rs->eliminated_ = true; } assert(rs->repOk()); // br->top_ and br->bot_ now contain the next top and bot } else { // The continuation had already processed the whole read assert_eq(qlen_, depth); cur = 0; } empty = (br->top_ == br->bot_); hit = (cur == 0 && !empty); // Check whether we've obtained an exact alignment when // we've been instructed not to report exact alignments nedits = br->edits_.size(); invalidExact = (hit && nedits == 0 && !reportExacts_); assert_leq(br->ham_, qualLim_); // Set this to true if the only way to make legal progress // is via one or more additional backtracks. if(halfAndHalf_ && !hhCheck(br, depth, empty)) { // This alignment doesn't satisfy the half-and-half // requirements; reject it if(metrics_ != NULL) metrics_->curBacktracks_++; pm.curtail(br, qlen_, depth3_, qualOrder_); goto bail; } if(hit && // there is a range to report !invalidExact && // not disqualified by no-exact-hits setting !reportedPartial) // not an already-reported partial alignment { if(verbose_) { if(partial_) { cout << " Partial alignment:" << endl; } else { cout << " Final alignment:" << endl; } br->len_++; br->print((*qry_), (*qual_), minCost, cout, halfAndHalf_ > 0, partial_, fw_, ebwt_->fw()); br->len_--; cout << endl; } assert_gt(br->bot_, br->top_); assert_leq(br->ham_, qualLim_); assert_leq((uint32_t)(br->cost_ & ~0xc000), qualLim_); if(metrics_ != NULL) metrics_->setReadHasRange(); curRange_.top = br->top_; curRange_.bot = br->bot_; curRange_.cost = br->cost_; curRange_.stratum = (br->cost_ >> 14); curRange_.numMms = nedits; curRange_.fw = fw_; curRange_.mms.clear(); curRange_.refcs.clear(); for(size_t i = 0; i < nedits; i++) { curRange_.mms.push_back(qlen_ - br->edits_.get(i).pos - 1); curRange_.refcs.push_back((char)br->edits_.get(i).chr); } addPartialEdits(); curRange_.ebwt = ebwt_; this->foundRange = true; #ifndef NDEBUG int64_t top2 = (int64_t)br->top_; top2++; // ensure it's not 0 if(ebwt_->fw()) top2 = -top2; assert(allTops_.find(top2) == allTops_.end()); allTops_.insert(top2); #endif assert(curRange_.repOk()); // Must curtail because we've consumed the whole pattern if(metrics_ != NULL) metrics_->curBacktracks_++; pm.curtail(br, qlen_, depth3_, qualOrder_); } else if(empty || cur == 0) { // The branch couldn't be extended further if(metrics_ != NULL) metrics_->curBacktracks_++; pm.curtail(br, qlen_, depth3_, qualOrder_); } else { // Extend the branch by one position; no change to its cost // so there's no need to reconsider where it lies in the // priority queue assert_neq(0, cur); br->extend(); } bail: // Make sure the front element of the priority queue is // extendable (i.e. not curtailed) and then prep it. if(!pm.splitAndPrep(rand_, qlen_, qualLim_, depth3_, qualOrder_, fuzzy_, ebwt_->_eh, ebwt_->_ebwt, ebwt_->_fw)) { pm.reset(0); assert(pm.empty()); } if(pm.empty()) { // No more branches break; } assert(!pm.front()->curtailed_); assert(!pm.front()->exhausted_); if(until == ADV_COST_CHANGES && pm.front()->cost_ != cost) break; else if(until == ADV_STEP) break; } while(!this->foundRange); if(!pm.empty()) { assert(!pm.front()->curtailed_); assert(!pm.front()->exhausted_); } } /** * Return true iff we're enforcing a half-and-half constraint * (forced edits in both seed halves). */ int halfAndHalf() const { return halfAndHalf_; } protected: /** * Lump all the seed-alignment edits from the seedRange_ range * found previously to the curRange_ range just found. */ void addPartialEdits() { // Lump in the edits from the partial alignment if(seedRange_.valid()) { const size_t srSz = seedRange_.mms.size(); for(size_t i = 0; i < srSz; i++) { curRange_.mms.push_back(qlen_ - seedRange_.mms[i] - 1); curRange_.refcs.push_back(seedRange_.refcs[i]); } curRange_.numMms += srSz; } } /** * Return true iff we're OK to continue after considering which * half-seed boundary we're passing through, together with the * number of mismatches accumulated so far. Return false if we * should stop because a half-and-half constraint is violated. If * we're not currently passing a half-seed boundary, just return * true. */ bool hhCheck(Branch *b, uint32_t depth, bool empty) { const uint32_t nedits = b->edits_.size(); ASSERT_ONLY(uint32_t lim3 = (offRev3_ == offRev2_)? 2 : 3); ASSERT_ONLY(uint32_t lim5 = (offRev1_ == offRev0_)? 2 : 1); if((depth == (depth5_-1)) && !empty) { // We're crossing the boundary separating the hi-half // from the non-seed portion of the read. // We should induce a mismatch if we haven't mismatched // yet, so that we don't waste time pursuing a match // that was covered by a previous phase assert_leq(nedits, lim5); return nedits > 0; } else if((depth == (depth3_-1)) && !empty) { // We're crossing the boundary separating the lo-half // from the non-seed portion of the read assert_leq(nedits, lim3); assert_gt(nedits, 0); // Count the mismatches in the lo and hi halves uint32_t loHalfMms = 0, hiHalfMms = 0; for(size_t i = 0; i < nedits; i++) { uint32_t depth = b->edits_.get(i).pos; if (depth < depth5_) hiHalfMms++; else if(depth < depth3_) loHalfMms++; else assert(false); } assert_leq(loHalfMms + hiHalfMms, lim3); bool invalidHalfAndHalf = (loHalfMms == 0 || hiHalfMms == 0); return (nedits >= (uint32_t)halfAndHalf_ && !invalidHalfAndHalf); } #ifndef NDEBUG if(depth < depth5_-1) { assert_leq(nedits, lim5); } else if(depth >= depth5_ && depth < depth3_-1) { assert_gt(nedits, 0); assert_leq(nedits, lim3); } #endif return true; } /** * Return true iff the state of the backtracker as encoded by * stackDepth, d and iham is compatible with the current half-and- * half alignment mode. prehits is for sanity checking when * bailing. */ bool hhCheckTop(Branch* b, uint32_t d, uint32_t iham, uint64_t prehits = U64(0xffffffffffffffff)) { // Crossing from the hi-half into the lo-half ASSERT_ONLY(uint32_t lim3 = (offRev3_ == offRev2_)? 2 : 3); ASSERT_ONLY(uint32_t lim5 = (offRev1_ == offRev0_)? 2 : 1); const uint32_t nedits = b->edits_.size(); if(d == depth5_) { assert_leq(nedits, lim5); if(nedits == 0) { return false; } } else if(d == depth3_) { assert_leq(nedits, lim3); if(nedits < (uint32_t)halfAndHalf_) { return false; } } #ifndef NDEBUG else { // We didn't just cross a boundary, so do an in-between check if(d >= depth5_) { assert_geq(nedits, 1); } else if(d >= depth3_) { assert_geq(nedits, lim3); } } #endif return true; } /** * Return the Phred-scale quality value at position 'off' */ inline uint8_t qualAt(size_t off) { return phredCharToPhredQual((*qual_)[off]); } /** * Tally how many Ns occur in the seed region and in the ftab- * jumpable region of the read. Check whether the mismatches * induced by the Ns already violates the current policy. Return * false if the policy is already violated, true otherwise. */ bool tallyNs(int& nsInSeed, int& nsInFtab) { const Ebwt >& ebwt = *ebwt_; int ftabChars = ebwt._eh._ftabChars; // Count Ns in the seed region of the read and short-circuit if // the configuration of Ns guarantees that there will be no // valid alignments given the backtracking constraints. for(size_t i = 0; i < offRev3_; i++) { if((int)(*qry_)[qlen_-i-1] == 4) { nsInSeed++; if(nsInSeed == 1) { if(i < offRev0_) { return false; // Exceeded mm budget on Ns alone } } else if(nsInSeed == 2) { if(i < offRev1_) { return false; // Exceeded mm budget on Ns alone } } else if(nsInSeed == 3) { if(i < offRev2_) { return false; // Exceeded mm budget on Ns alone } } else { assert_gt(nsInSeed, 3); return false; // Exceeded mm budget on Ns alone } } } // Calculate the number of Ns there are in the region that // would get jumped over if the ftab were used. for(size_t i = 0; i < (size_t)ftabChars && i < qlen_; i++) { if((int)(*qry_)[qlen_-i-1] == 4) nsInFtab++; } return true; } /** * Calculate the offset into the ftab for the rightmost 'ftabChars' * characters of the current query. Rightmost char gets least * significant bit-pair. */ uint32_t calcFtabOff() { const Ebwt >& ebwt = *ebwt_; int ftabChars = ebwt._eh._ftabChars; uint32_t ftabOff = (*qry_)[qlen_ - ftabChars]; assert_lt(ftabOff, 4); assert_lt(ftabOff, ebwt._eh._ftabLen-1); for(int i = ftabChars - 1; i > 0; i--) { ftabOff <<= 2; assert_lt((uint32_t)(*qry_)[qlen_-i], 4); ftabOff |= (uint32_t)(*qry_)[qlen_-i]; assert_lt(ftabOff, ebwt._eh._ftabLen-1); } assert_lt(ftabOff, ebwt._eh._ftabLen-1); return ftabOff; } String* qry_; // query (read) sequence String qryBuf_; // for composing modified qry_ strings size_t qlen_; // length of _qry String* qual_; // quality values for _qry String* name_; // name of _qry bool color_; // true -> read is colorspace String* altQry_; // alternate basecalls String* altQual_; // quality values for alternate basecalls int alts_; // max # alternatives bool fuzzy_; // alternate scoring scheme? const Ebwt >* ebwt_; // Ebwt to search in bool fw_; uint32_t offRev0_; // unrevisitable chunk uint32_t offRev1_; // 1-revisitable chunk uint32_t offRev2_; // 2-revisitable chunk uint32_t offRev3_; // 3-revisitable chunk /// Whether to round qualities off Maq-style when calculating penalties bool maqPenalty_; /// Whether to order paths on our search in a way that takes /// qualities into account. If this is false, the effect is that /// the first path reported is guaranteed to be in the best /// stratum, but it's not guaranteed to have the best quals. bool qualOrder_; /// Reject alignments where sum of qualities at mismatched /// positions is greater than qualLim_ uint32_t qualLim_; /// Report exact alignments iff this is true bool reportExacts_; /// Whether to use the _os array together with a naive matching /// algorithm to double-check reported alignments (or the lack /// thereof) int halfAndHalf_; /// Whether we're generating partial alignments for a longer /// alignment in the opposite index. bool partial_; /// Depth of 5'-seed-half border uint32_t depth5_; /// Depth of 3'-seed-half border uint32_t depth3_; /// Source of pseudo-random numbers RandomSource rand_; /// Be talkative bool verbose_; /// Suppress unnecessary output bool quiet_; // Current range to expose to consumers Range curRange_; // Range for the partial alignment we're extending (NULL if we // aren't extending a partial) Range seedRange_; // Starts as false; set to true as soon as we know we want to skip // all further processing of this read bool skippingThisRead_; // Object encapsulating metrics AlignerMetrics* metrics_; #ifndef NDEBUG std::set allTops_; #endif }; /** * Concrete factory for EbwtRangeSource objects. */ class EbwtRangeSourceFactory { typedef Ebwt > TEbwt; public: EbwtRangeSourceFactory( const TEbwt* ebwt, bool fw, uint32_t qualThresh, bool reportExacts, bool verbose, bool quiet, bool halfAndHalf, bool seeded, bool maqPenalty, bool qualOrder, AlignerMetrics *metrics = NULL) : ebwt_(ebwt), fw_(fw), qualThresh_(qualThresh), reportExacts_(reportExacts), verbose_(verbose), quiet_(quiet), halfAndHalf_(halfAndHalf), seeded_(seeded), maqPenalty_(maqPenalty), qualOrder_(qualOrder), metrics_(metrics) { } /** * Return new EbwtRangeSource with predefined params.s */ EbwtRangeSource *create() { return new EbwtRangeSource(ebwt_, fw_, qualThresh_, reportExacts_, verbose_, quiet_, halfAndHalf_, seeded_, maqPenalty_, qualOrder_, metrics_); } protected: const TEbwt* ebwt_; bool fw_; uint32_t qualThresh_; bool reportExacts_; bool verbose_; bool quiet_; bool halfAndHalf_; bool seeded_; bool maqPenalty_; bool qualOrder_; AlignerMetrics *metrics_; }; /** * What boundary within the alignment to "pin" a particular * backtracking constraint to. */ enum SearchConstraintExtent { PIN_TO_BEGINNING = 1, // depth 0; i.e., constraint is inactive PIN_TO_LEN, // constraint applies to while alignment PIN_TO_HI_HALF_EDGE, // constraint applies to hi-half of seed region PIN_TO_SEED_EDGE // constraint applies to entire seed region }; /** * Concrete RangeSourceDriver that deals properly with * GreedyDFSRangeSource by calling setOffs() with the appropriate * parameters when initializing it; */ class EbwtRangeSourceDriver : public SingleRangeSourceDriver { public: EbwtRangeSourceDriver( EbwtSearchParams >& params, EbwtRangeSource* rs, bool fw, bool seed, bool maqPenalty, bool qualOrder, HitSink& sink, HitSinkPerThread* sinkPt, uint32_t seedLen, bool nudgeLeft, SearchConstraintExtent rev0Off, SearchConstraintExtent rev1Off, SearchConstraintExtent rev2Off, SearchConstraintExtent rev3Off, vector >& os, bool verbose, bool quiet, bool mate1, ChunkPool* pool, int *btCnt) : SingleRangeSourceDriver( params, rs, fw, sink, sinkPt, os, verbose, quiet, mate1, 0, pool, btCnt), seed_(seed), maqPenalty_(maqPenalty), qualOrder_(qualOrder), rs_(rs), seedLen_(seedLen), nudgeLeft_(nudgeLeft), rev0Off_(rev0Off), rev1Off_(rev1Off), rev2Off_(rev2Off), rev3Off_(rev3Off), verbose_(verbose), quiet_(quiet) { if(seed_) assert_gt(seedLen, 0); } virtual ~EbwtRangeSourceDriver() { } bool seed() const { return seed_; } bool ebwtFw() const { return rs_->curEbwt()->fw(); } /** * Called every time setQuery() is called in the parent class, * after setQuery() has been called on the RangeSource but before * initConts() has been called. */ virtual void initRangeSource(const String& qual, bool fuzzy, int alts, const String* altQuals) { // If seedLen_ is huge, then it will always cover the whole // alignment assert_eq(len_, seqan::length(qual)); uint32_t s = (seedLen_ > 0 ? min(seedLen_, len_) : len_); uint32_t sLeft = s >> 1; uint32_t sRight = s >> 1; // If seed has odd length, then nudge appropriate half up by 1 if((s & 1) != 0) { if(nudgeLeft_) sLeft++; else sRight++; } uint32_t rev0Off = cextToDepth(rev0Off_, sRight, s, len_); uint32_t rev1Off = cextToDepth(rev1Off_, sRight, s, len_); uint32_t rev2Off = cextToDepth(rev2Off_, sRight, s, len_); uint32_t rev3Off = cextToDepth(rev3Off_, sRight, s, len_); // Truncate the pattern if necessary uint32_t qlen = seqan::length(qual); if(seed_) { if(len_ > s) { rs_->setQlen(s); qlen = s; } assert(!rs_->reportExacts()); } // If there are any Ns in the unrevisitable region, then this // driver is guaranteed to yield no fruit. uint16_t minCost = 0; if(rs_->reportExacts()) { // Keep minCost at 0 } else if (!rs_->halfAndHalf() && rev0Off < s) { // Exacts not allowed, so there must be at least 1 mismatch // outside of the unrevisitable area minCost = 1 << 14; if(qualOrder_) { uint8_t lowQual = 0xff; for(uint32_t d = rev0Off; d < s; d++) { uint8_t lowAtPos; if(fuzzy) { lowAtPos = loPenaltyAt(qlen-d-1, alts, qual, altQuals); } else { lowAtPos = qual[qlen - d - 1]; } if(lowAtPos < lowQual) lowQual = lowAtPos; } assert_lt(lowQual, 0xff); if(fuzzy) { minCost += lowQual; } else { minCost += mmPenalty(maqPenalty_, phredCharToPhredQual(lowQual)); } } } else if(rs_->halfAndHalf() && sRight > 0 && sRight < (s-1)) { // Half-and-half constraints are active, so there must be // at least 1 mismatch in both halves of the seed assert(rs_->halfAndHalf()); minCost = (seed_ ? 3 : 2) << 14; if(qualOrder_) { assert(rs_->halfAndHalf() == 2 || rs_->halfAndHalf() == 3); uint8_t lowQual1 = 0xff; for(uint32_t d = 0; d < sRight; d++) { uint8_t lowAtPos; if(fuzzy) { lowAtPos = loPenaltyAt(qlen-d-1, alts, qual, altQuals); } else { lowAtPos = qual[qlen - d - 1]; } if(lowAtPos < lowQual1) lowQual1 = lowAtPos; } assert_lt(lowQual1, 0xff); if(fuzzy) { minCost += lowQual1; } else { minCost += mmPenalty(maqPenalty_, phredCharToPhredQual(lowQual1)); } uint8_t lowQual2_1 = 0xff; uint8_t lowQual2_2 = 0xff; for(uint32_t d = sRight; d < s; d++) { uint8_t lowAtPos; if(fuzzy) { lowAtPos = loPenaltyAt(qlen-d-1, alts, qual, altQuals); } else { lowAtPos = qual[qlen - d - 1]; } if(lowAtPos < lowQual2_1) { if(lowQual2_1 != 0xff) { lowQual2_2 = lowQual2_1; } lowQual2_1 = lowAtPos; } else if(lowAtPos < lowQual2_2) { lowQual2_2 = lowAtPos; } } assert_lt(lowQual2_1, 0xff); if(fuzzy) { minCost += lowQual2_1; if(rs_->halfAndHalf() > 2 && lowQual2_2 != 0xff) { minCost += lowQual2_2; } } else { minCost += mmPenalty(maqPenalty_, phredCharToPhredQual(lowQual2_1)); if(rs_->halfAndHalf() > 2 && lowQual2_2 != 0xff) { minCost += mmPenalty(maqPenalty_, phredCharToPhredQual(lowQual2_2)); } } } } if(verbose_) cout << "initRangeSource minCost: " << minCost << endl; this->minCostAdjustment_ = minCost; rs_->setOffs(sRight, // depth of far edge of hi-half (only matters where half-and-half is possible) s, // depth of far edge of lo-half (only matters where half-and-half is possible) rev0Off, // depth above which we cannot backtrack rev1Off, // depth above which we may backtrack just once rev2Off, // depth above which we may backtrack just twice rev3Off); // depth above which we may backtrack just three times } protected: /** * Convert a search constraint extent to an actual depth into the * read. */ inline uint32_t cextToDepth(SearchConstraintExtent cext, uint32_t sRight, uint32_t s, uint32_t len) { if(cext == PIN_TO_SEED_EDGE) return s; if(cext == PIN_TO_HI_HALF_EDGE) return sRight; if(cext == PIN_TO_BEGINNING) return 0; if(cext == PIN_TO_LEN) return len; cerr << "Bad SearchConstraintExtent: " << cext; throw 1; } bool seed_; bool maqPenalty_; bool qualOrder_; EbwtRangeSource* rs_; uint32_t seedLen_; bool nudgeLeft_; SearchConstraintExtent rev0Off_; SearchConstraintExtent rev1Off_; SearchConstraintExtent rev2Off_; SearchConstraintExtent rev3Off_; bool verbose_; bool quiet_; }; /** * Concrete RangeSourceDriver that deals properly with * GreedyDFSRangeSource by calling setOffs() with the appropriate * parameters when initializing it; */ class EbwtRangeSourceDriverFactory { public: EbwtRangeSourceDriverFactory( EbwtSearchParams >& params, EbwtRangeSourceFactory* rs, bool fw, bool seed, bool maqPenalty, bool qualOrder, HitSink& sink, HitSinkPerThread* sinkPt, uint32_t seedLen, bool nudgeLeft, SearchConstraintExtent rev0Off, SearchConstraintExtent rev1Off, SearchConstraintExtent rev2Off, SearchConstraintExtent rev3Off, vector >& os, bool verbose, bool quiet, bool mate1, ChunkPool* pool, int *btCnt = NULL) : params_(params), rs_(rs), fw_(fw), seed_(seed), maqPenalty_(maqPenalty), qualOrder_(qualOrder), sink_(sink), sinkPt_(sinkPt), seedLen_(seedLen), nudgeLeft_(nudgeLeft), rev0Off_(rev0Off), rev1Off_(rev1Off), rev2Off_(rev2Off), rev3Off_(rev3Off), os_(os), verbose_(verbose), quiet_(quiet), mate1_(mate1), pool_(pool), btCnt_(btCnt) { } ~EbwtRangeSourceDriverFactory() { delete rs_; rs_ = NULL; } /** * Return a newly-allocated EbwtRangeSourceDriver with the given * parameters. */ EbwtRangeSourceDriver *create() const { return new EbwtRangeSourceDriver( params_, rs_->create(), fw_, seed_, maqPenalty_, qualOrder_, sink_, sinkPt_, seedLen_, nudgeLeft_, rev0Off_, rev1Off_, rev2Off_, rev3Off_, os_, verbose_, quiet_, mate1_, pool_, btCnt_); } protected: EbwtSearchParams >& params_; EbwtRangeSourceFactory* rs_; bool fw_; bool seed_; bool maqPenalty_; bool qualOrder_; HitSink& sink_; HitSinkPerThread* sinkPt_; uint32_t seedLen_; bool nudgeLeft_; SearchConstraintExtent rev0Off_; SearchConstraintExtent rev1Off_; SearchConstraintExtent rev2Off_; SearchConstraintExtent rev3Off_; vector >& os_; bool verbose_; bool quiet_; bool mate1_; ChunkPool* pool_; int *btCnt_; }; /** * A RangeSourceDriver that manages two child EbwtRangeSourceDrivers, * one for searching for seed strings with mismatches in the hi-half, * and one for extending those seed strings toward the 3' end. */ class EbwtSeededRangeSourceDriver : public RangeSourceDriver { typedef RangeSourceDriver* TRangeSrcDrPtr; typedef CostAwareRangeSourceDriver TCostAwareRangeSrcDr; public: EbwtSeededRangeSourceDriver( EbwtRangeSourceDriverFactory* rsFact, EbwtRangeSourceDriver* rsSeed, bool fw, uint32_t seedLen, bool verbose, bool quiet, bool mate1) : RangeSourceDriver(true, 0), rsFact_(rsFact), rsFull_(false, NULL, verbose, quiet, true), rsSeed_(rsSeed), patsrc_(NULL), seedLen_(seedLen), fw_(fw), mate1_(mate1), seedRange_(0) { assert(rsSeed_->seed()); } virtual ~EbwtSeededRangeSourceDriver() { delete rsFact_; rsFact_ = NULL; delete rsSeed_; rsSeed_ = NULL; } /** * Prepare this aligner for the next read. */ virtual void setQueryImpl(PatternSourcePerThread* patsrc, Range *partial) { this->done = false; rsSeed_->setQuery(patsrc, partial); this->minCostAdjustment_ = max(rsSeed_->minCostAdjustment_, rsSeed_->minCost); this->minCost = this->minCostAdjustment_; rsFull_.clearSources(); rsFull_.setQuery(patsrc, partial); rsFull_.minCost = this->minCost; assert_gt(rsFull_.minCost, 0); patsrc_ = patsrc; // The minCostAdjustment comes from the seed range source // driver, based on Ns and quals in the hi-half this->foundRange = false; ASSERT_ONLY(allTops_.clear()); assert_eq(this->minCost, min(rsSeed_->minCost, rsFull_.minCost)); } /** * Advance the aligner by one memory op. Return true iff we're * done with this read. */ virtual void advance(int until) { assert(!this->foundRange); until = max(until, ADV_COST_CHANGES); ASSERT_ONLY(uint16_t preCost = this->minCost); advanceImpl(until); if(this->foundRange) { assert_eq(range().cost, preCost); } #ifndef NDEBUG if(this->foundRange) { // Assert that we have not yet dished out a range with this // top offset assert_gt(range().bot, range().top); assert(range().ebwt != NULL); int64_t top = (int64_t)range().top; top++; // ensure it's not 0 if(!range().ebwt->fw()) top = -top; assert(allTops_.find(top) == allTops_.end()); allTops_.insert(top); } #endif } /** * Advance the aligner by one memory op. Return true iff we're * done with this read. */ virtual void advanceImpl(int until) { assert(!this->done); assert(!this->foundRange); assert_gt(rsFull_.minCost, 0); // Advance the seed range source if(rsSeed_->done && rsFull_.done && !rsSeed_->foundRange && !rsFull_.foundRange) { this->done = true; return; } if(rsSeed_->done && !rsSeed_->foundRange) { rsSeed_->minCost = 0xffff; if(rsFull_.minCost > this->minCost) { this->minCost = rsFull_.minCost; // Cost changed, so return return; } } if(rsFull_.done && !rsFull_.foundRange) { rsFull_.minCost = 0xffff; if(rsSeed_->minCost > this->minCost) { this->minCost = rsSeed_->minCost; // Cost changed, so return return; } } assert(rsSeed_->minCost != 0xffff || rsFull_.minCost != 0xffff); // Extend a partial alignment ASSERT_ONLY(uint16_t oldMinCost = this->minCost); assert_eq(this->minCost, min(rsSeed_->minCost, rsFull_.minCost)); bool doFull = rsFull_.minCost <= rsSeed_->minCost; if(!doFull) { // Advance the partial-alignment generator assert_eq(rsSeed_->minCost, this->minCost); if(!rsSeed_->foundRange) { rsSeed_->advance(until); } if(rsSeed_->foundRange) { assert_eq(this->minCost, rsSeed_->range().cost); assert_eq(oldMinCost, rsSeed_->range().cost); seedRange_ = &rsSeed_->range(); rsSeed_->foundRange = false; assert_geq(seedRange_->cost, this->minCostAdjustment_); this->minCostAdjustment_ = seedRange_->cost; assert_gt(seedRange_->numMms, 0); // Keep the range for the hi-half partial alignment so // that the driver can (a) modify the pattern string // and (b) modify results from the RangeSource to // include these edits. EbwtRangeSourceDriver *partial = rsFact_->create(); partial->minCost = seedRange_->cost; rsFull_.minCost = seedRange_->cost; rsFull_.addSource(partial, seedRange_); if(rsFull_.foundRange) { this->foundRange = true; rsFull_.foundRange = false; assert(rsFull_.range().repOk()); assert_eq(range().cost, oldMinCost); } } if(rsSeed_->minCost > this->minCost) { this->minCost = rsSeed_->minCost; if(!rsFull_.done) { this->minCost = min(this->minCost, rsFull_.minCost); assert_eq(this->minCost, min(rsSeed_->minCost, rsFull_.minCost)); } } } else { // Extend a full alignment assert(!rsFull_.done); assert(!rsFull_.foundRange); uint16_t oldFullCost = rsFull_.minCost; if(!rsFull_.foundRange) { rsFull_.advance(until); } // Found a minimum-cost range if(rsFull_.foundRange) { this->foundRange = true; rsFull_.foundRange = false; assert(rsFull_.range().repOk()); assert_eq(range().cost, oldMinCost); } assert_geq(rsFull_.minCost, oldFullCost); // Did the min cost change? if(rsFull_.minCost > oldFullCost) { // If a range was found, hold on to it and save it for // later. Update the minCost. assert(!rsSeed_->done || rsSeed_->minCost == 0xffff); this->minCost = min(rsFull_.minCost, rsSeed_->minCost); } } } /** * Return the range found. */ virtual Range& range() { Range& r = rsFull_.range(); r.fw = fw_; r.mate1 = mate1_; return r; } /** * Return whether we're generating ranges for the first or the * second mate. */ virtual bool mate1() const { return mate1_; } /** * Return true iff current pattern is forward-oriented. */ virtual bool fw() const { return fw_; } protected: EbwtRangeSourceDriverFactory* rsFact_; TCostAwareRangeSrcDr rsFull_; EbwtRangeSourceDriver* rsSeed_; PatternSourcePerThread* patsrc_; uint32_t seedLen_; bool fw_; bool mate1_; bool generating_; Range *seedRange_; }; #endif /*EBWT_SEARCH_BACKTRACK_H_*/ ugene-1.9.8/src/plugins_3rdparty/bowtie/src/bowtie/aligner.h0000644000175000017500000017454211651544326022601 0ustar ilyailya/** * aligner.h * * A generic class providing a stateful way to find alignments. */ #ifndef ALIGNER_H_ #define ALIGNER_H_ #include #include #include #include "seqan/sequence.h" #include "assert_helpers.h" #include "ebwt.h" #include "pat.h" #include "range.h" #include "range_source.h" #include "range_chaser.h" #include "ref_aligner.h" #include "reference.h" #include "aligner_metrics.h" #include "search_globals.h" /** * State machine for carrying out an alignment, which usually consists * of a series of phases that conduct different alignments using * different backtracking constraints. * * Each Aligner should have a dedicated PatternSourcePerThread. */ class Aligner { public: Aligner(bool _done, bool rangeMode) : done(_done), patsrc_(NULL), bufa_(NULL), bufb_(NULL), rangeMode_(rangeMode) { } virtual ~Aligner() { } /// Advance the range search by one memory op virtual bool advance() = 0; /// Prepare Aligner for the next read virtual void setQuery(PatternSourcePerThread *patsrc) { assert(patsrc != NULL); patsrc_ = patsrc; bufa_ = &patsrc->bufa(); assert(bufa_ != NULL); bufb_ = &patsrc->bufb(); alen_ = bufa_->length(); blen_ = (bufb_ != NULL) ? bufb_->length() : 0; rand_.init(bufa_->seed); } /** * Set to true if all searching w/r/t the current query is * finished or if there is no current query. */ bool done; protected: // Current read pair PatternSourcePerThread* patsrc_; ReadBuf* bufa_; uint32_t alen_; ReadBuf* bufb_; uint32_t blen_; bool rangeMode_; RandomSource rand_; }; /** * Abstract parent factory class for constructing aligners of all kinds. */ class AlignerFactory { public: virtual ~AlignerFactory() { } virtual Aligner* create() const = 0; /** * Allocate a vector of n Aligners; use destroy(std::vector...) to * free the memory. */ virtual std::vector* create(uint32_t n) const { std::vector* v = new std::vector; for(uint32_t i = 0; i < n; i++) { v->push_back(create()); assert(v->back() != NULL); } return v; } /// Free memory associated with the aligner virtual void destroy(Aligner* al) const { assert(al != NULL); // Free the Aligner delete al; } /// Free memory associated with an aligner list virtual void destroy(std::vector* als) const { assert(als != NULL); // Free all of the Aligners for(size_t i = 0; i < als->size(); i++) { if((*als)[i] != NULL) { delete (*als)[i]; (*als)[i] = NULL; } } // Free the vector delete als; } }; /** * Coordinates multiple aligners of the same type (i.e. either all * single-end or all paired-end). */ class MultiAligner { public: MultiAligner( uint32_t n, uint32_t qUpto, const AlignerFactory& alignFact, const PatternSourcePerThreadFactory& patsrcFact) : n_(n), qUpto_(qUpto), alignFact_(alignFact), patsrcFact_(patsrcFact), aligners_(NULL), patsrcs_(NULL) { aligners_ = alignFact_.create(n_); assert(aligners_ != NULL); patsrcs_ = patsrcFact_.create(n_); assert(patsrcs_ != NULL); } /// Free memory associated with the aligners and their pattern sources. virtual ~MultiAligner() { alignFact_.destroy(aligners_); patsrcFact_.destroy(patsrcs_); } /** * Advance an array of aligners in parallel, using prefetches to * try to hide all the latency. */ void run() { bool done = false; while(!done) { done = true; for(uint32_t i = 0; i < n_; i++) { if(!(*aligners_)[i]->done) { // Advance an aligner already in progress done = false; (*aligners_)[i]->advance(); } else { // Get a new read and initialize an aligner with it (*patsrcs_)[i]->nextReadPair(); if(!(*patsrcs_)[i]->empty() && (*patsrcs_)[i]->patid() < qUpto_) { (*aligners_)[i]->setQuery((*patsrcs_)[i]); assert(!(*aligners_)[i]->done); done = false; } else { // No more reads; if done == true, it remains // true } } } } } protected: uint32_t n_; /// Number of aligners uint32_t qUpto_; /// Number of reads to align before stopping const AlignerFactory& alignFact_; const PatternSourcePerThreadFactory& patsrcFact_; std::vector* aligners_; std::vector* patsrcs_; }; /** * Coordinates multiple single-end and paired-end aligners, routing * reads to one or the other type as appropriate. */ class MixedMultiAligner { public: MixedMultiAligner( uint32_t n, uint32_t qUpto, const AlignerFactory& alignSEFact, const AlignerFactory& alignPEFact, const PatternSourcePerThreadFactory& patsrcFact) : n_(n), qUpto_(qUpto), alignSEFact_(alignSEFact), alignPEFact_(alignPEFact), patsrcFact_(patsrcFact), alignersSE_(NULL), alignersPE_(NULL), seOrPe_(NULL), patsrcs_(NULL) { // Instantiate all single-end aligners alignersSE_ = alignSEFact_.create(n_); assert(alignersSE_ != NULL); // Instantiate all paired-end aligners alignersPE_ = alignPEFact_.create(n_); assert(alignersPE_ != NULL); // Allocate array of boolean flags indicating whether each of // the slots is currently using the single-end or paired-end // aligner seOrPe_ = new bool[n_]; for(uint32_t i = 0; i < n_; i++) { seOrPe_[i] = true; } // Instantiate all read sources patsrcs_ = patsrcFact_.create(n_); assert(patsrcs_ != NULL); } /// Free memory associated with the aligners and their pattern sources. virtual ~MixedMultiAligner() { alignSEFact_.destroy(alignersSE_); alignPEFact_.destroy(alignersPE_); patsrcFact_.destroy(patsrcs_); delete[] seOrPe_; } /** * Advance an array of aligners in parallel, using prefetches to * try to hide all the latency. */ void run(bool verbose = false) { bool done = false; bool first = true; if(n_ == 1) { Aligner *al = seOrPe_[0] ? (*alignersSE_)[0] : (*alignersPE_)[0]; PatternSourcePerThread *ps = (*patsrcs_)[0]; while(!done) { done = true; if(!first && !al->done) { // Advance an aligner already in progress; this is // the common case done = false; al->advance(); } else { // Get a new read ps->nextReadPair(); if(ps->patid() < qUpto_ && !ps->empty()) { if(ps->paired()) { // Read currently in buffer is paired-end (*alignersPE_)[0]->setQuery(ps); al = (*alignersPE_)[0]; seOrPe_[0] = false; // false -> paired } else { // Read currently in buffer is single-end (*alignersSE_)[0]->setQuery(ps); al = (*alignersSE_)[0]; seOrPe_[0] = true; // true = unpaired } done = false; } else { // No more reads; if done == true, it remains // true } } first = false; } } else { while(!done) { done = true; for(uint32_t i = 0; i < n_; i++) { Aligner *al = seOrPe_[i] ? (*alignersSE_)[i] : (*alignersPE_)[i]; if(!first && !al->done) { // Advance an aligner already in progress; this is // the common case done = false; al->advance(); } else { // Feed a new read to a vacant aligner PatternSourcePerThread *ps = (*patsrcs_)[i]; // Get a new read ps->nextReadPair(); if(ps->patid() < qUpto_ && !ps->empty()) { if(ps->paired()) { // Read currently in buffer is paired-end (*alignersPE_)[i]->setQuery(ps); seOrPe_[i] = false; // false -> paired } else { // Read currently in buffer is single-end (*alignersSE_)[i]->setQuery(ps); seOrPe_[i] = true; // true = unpaired } done = false; } else { // No more reads; if done == true, it remains // true } } } first = false; } } } protected: uint32_t n_; /// Number of aligners uint32_t qUpto_; /// Number of reads to align before stopping const AlignerFactory& alignSEFact_; const AlignerFactory& alignPEFact_; const PatternSourcePerThreadFactory& patsrcFact_; std::vector* alignersSE_; std::vector* alignersPE_; bool * seOrPe_; std::vector* patsrcs_; }; /** * An aligner for finding exact matches of unpaired reads. Always * tries the forward-oriented version of the read before the reverse- * oriented read. */ template class UnpairedAlignerV2 : public Aligner { typedef RangeSourceDriver TDriver; public: UnpairedAlignerV2( EbwtSearchParams >* params, TDriver* driver, RangeChaser >* rchase, HitSink& sink, const HitSinkPerThreadFactory& sinkPtFactory, HitSinkPerThread* sinkPt, vector >& os, const BitPairReference* refs, bool rangeMode, bool verbose, bool quiet, int maxBts, ChunkPool *pool, int *btCnt = NULL, AlignerMetrics *metrics = NULL) : Aligner(true, rangeMode), refs_(refs), doneFirst_(true), firstIsFw_(true), chase_(false), sinkPtFactory_(sinkPtFactory), sinkPt_(sinkPt), params_(params), rchase_(rchase), driver_(driver), verbose_(verbose), quiet_(quiet), maxBts_(maxBts), pool_(pool), btCnt_(btCnt), metrics_(metrics) { assert(pool_ != NULL); assert(sinkPt_ != NULL); assert(params_ != NULL); assert(driver_ != NULL); } virtual ~UnpairedAlignerV2() { delete driver_; driver_ = NULL; delete params_; params_ = NULL; delete rchase_; rchase_ = NULL; delete[] btCnt_; btCnt_ = NULL; sinkPtFactory_.destroy(sinkPt_); sinkPt_ = NULL; } /** * Prepare this aligner for the next read. */ virtual void setQuery(PatternSourcePerThread* patsrc) { Aligner::setQuery(patsrc); // set fields & random seed if(metrics_ != NULL) { metrics_->nextRead(patsrc->bufa().patFw); } pool_->reset(&patsrc->bufa().name, patsrc->patid()); if(patsrc->bufa().length() < 4) { if(!quiet_) { cerr << "Warning: Skipping read " << patsrc->bufa().name << " because it is less than 4 characters long" << endl; } this->done = true; sinkPt_->finishRead(*patsrc_, true, true); return; } driver_->setQuery(patsrc, NULL); this->done = driver_->done; doneFirst_ = false; // Reset #-backtrack countdown if(btCnt_ != NULL) *btCnt_ = maxBts_; if(sinkPt_->setHits(patsrc->bufa().hitset)) { this->done = true; sinkPt_->finishRead(*patsrc_, true, true); } // Grab a bit from the pseudo-random seed to determine whether // to start with forward or reverse complement firstIsFw_ = ((patsrc->bufa().seed & 0x10) == 0); chase_ = false; } /** * Helper for reporting an alignment. */ inline bool report(const Range& ra, uint32_t first, uint32_t second, uint32_t tlen) { BowtieContext::Search* ctx = BowtieContext::getSearchContext(); bool ebwtFw = ra.ebwt->fw(); params_->setFw(ra.fw); assert_eq(bufa_->color, (ctx->color)); return params_->reportHit( ra.fw ? (ebwtFw? bufa_->patFw : bufa_->patFwRev) : (ebwtFw? bufa_->patRc : bufa_->patRcRev), ra.fw ? (ebwtFw? &bufa_->qual : &bufa_->qualRev) : (ebwtFw? &bufa_->qualRev : &bufa_->qual), &bufa_->name, bufa_->color, ctx->colorExEnds, ctx->snpPhred, refs_, ra.ebwt->rmap(), ebwtFw, ra.mms, // mismatch positions ra.refcs, // reference characters for mms ra.numMms, // # mismatches make_pair(first, second), // position make_pair(0, 0), // (bogus) mate position true, // (bogus) mate orientation 0, // (bogus) mate length make_pair(ra.top, ra.bot),// arrows tlen, // textlen alen_, // qlen ra.stratum, // alignment stratum ra.cost, // cost, including qual penalty ra.bot - ra.top - 1, // # other hits patsrc_->patid(), // pattern id bufa_->seed, // pseudo-random seed 0); // mate (0 = unpaired) } /** * Advance the aligner. Return true iff we're * done with this read. */ virtual bool advance() { assert(!this->done); if(chase_) { assert(!rangeMode_); assert(driver_->foundRange); assert(!sinkPt_->irrelevantCost(driver_->range().cost)); if(!rchase_->foundOff() && !rchase_->done) { rchase_->advance(); return false; } if(rchase_->foundOff()) { this->done = report(driver_->range(), rchase_->off().first, rchase_->off().second, rchase_->tlen()); rchase_->reset(); } else { assert(rchase_->done); // Forget this range; keep looking for ranges chase_ = false; driver_->foundRange = false; this->done = driver_->done; } } // Still advancing a if(!this->done && !chase_) { assert(!driver_->done || driver_->foundRange); if(driver_->foundRange) { const Range& ra = driver_->range(); assert(!sinkPt_->irrelevantCost(ra.cost)); assert(ra.repOk()); if(rangeMode_) { this->done = report(ra, ra.top, ra.bot, 0); driver_->foundRange = false; } else { rchase_->setTopBot(ra.top, ra.bot, alen_, rand_, ra.ebwt); if(rchase_->foundOff()) { this->done = report( ra, rchase_->off().first, rchase_->off().second, rchase_->tlen()); rchase_->reset(); } if(!rchase_->done && !sinkPt_->irrelevantCost(ra.cost)) { // Keep chasing this range chase_ = true; } else { driver_->foundRange = false; } } } else { this->done = sinkPt_->irrelevantCost(driver_->minCost); if(!this->done) { driver_->advance(ADV_COST_CHANGES); } else { // No longer necessarily true with chain input //assert(!sinkPt_->spanStrata()); } } if(driver_->done && !driver_->foundRange && !chase_) { this->done = true; } } if(this->done) { sinkPt_->finishRead(*patsrc_, true, true); } return this->done; } protected: // Reference sequences (needed for colorspace decoding) const BitPairReference* refs_; // Progress state bool doneFirst_; bool firstIsFw_; bool chase_; // Temporary HitSink; to be deleted const HitSinkPerThreadFactory& sinkPtFactory_; HitSinkPerThread* sinkPt_; // State for alignment EbwtSearchParams >* params_; // State for getting alignments from ranges statefully RangeChaser >* rchase_; // Range-finding state TDriver* driver_; bool verbose_; // be talkative bool quiet_; // don't print informational/warning info const int maxBts_; ChunkPool *pool_; int *btCnt_; AlignerMetrics *metrics_; }; /** * An aligner for finding paired alignments while operating entirely * within the Burrows-Wheeler domain. */ template class PairedBWAlignerV1 : public Aligner { typedef std::pair U32Pair; typedef std::vector U32PairVec; typedef std::vector TRangeVec; typedef RangeSourceDriver TDriver; typedef std::pair TU64Pair; typedef std::set TSetPairs; public: PairedBWAlignerV1( EbwtSearchParams >* params, TDriver* driver1Fw, TDriver* driver1Rc, TDriver* driver2Fw, TDriver* driver2Rc, RefAligner >* refAligner, RangeChaser >* rchase, HitSink& sink, const HitSinkPerThreadFactory& sinkPtFactory, HitSinkPerThread* sinkPt, bool fw1, bool fw2, uint32_t minInsert, uint32_t maxInsert, bool dontReconcile, uint32_t symCeiling, uint32_t mixedThresh, uint32_t mixedAttemptLim, const BitPairReference* refs, bool rangeMode, bool verbose, bool quiet, int maxBts, ChunkPool *pool, int *btCnt) : Aligner(true, rangeMode), refs_(refs), patsrc_(NULL), qlen1_(0), qlen2_(0), doneFw_(true), doneFwFirst_(true), chase1Fw_(false), chase1Rc_(false), chase2Fw_(false), chase2Rc_(false), delayedChase1Fw_(false), delayedChase1Rc_(false), delayedChase2Fw_(false), delayedChase2Rc_(false), refAligner_(refAligner), sinkPtFactory_(sinkPtFactory), sinkPt_(sinkPt), params_(params), minInsert_(minInsert), maxInsert_(maxInsert), dontReconcile_(dontReconcile), symCeiling_(symCeiling), mixedThresh_(mixedThresh), mixedAttemptLim_(mixedAttemptLim), mixedAttempts_(0), fw1_(fw1), fw2_(fw2), rchase_(rchase), verbose_(verbose), quiet_(quiet), maxBts_(maxBts), pool_(pool), btCnt_(btCnt), driver1Fw_(driver1Fw), driver1Rc_(driver1Rc), offs1FwSz_(0), offs1RcSz_(0), driver2Fw_(driver2Fw), driver2Rc_(driver2Rc), offs2FwSz_(0), offs2RcSz_(0), chaseL_fw_ (fw1_ ? chase1Fw_ : chase1Rc_), chaseR_fw_ (fw2_ ? chase2Fw_ : chase2Rc_), delayedchaseL_fw_(fw1_ ? delayedChase1Fw_ : delayedChase1Rc_), delayedchaseR_fw_(fw2_ ? delayedChase2Fw_ : delayedChase2Rc_), drL_fw_ (fw1_ ? *driver1Fw_ : *driver1Rc_), drR_fw_ (fw2_ ? *driver2Fw_ : *driver2Rc_), offsLarr_fw_ (fw1_ ? offs1FwArr_ : offs1RcArr_), offsRarr_fw_ (fw2_ ? offs2FwArr_ : offs2RcArr_), rangesLarr_fw_ (fw1_ ? ranges1FwArr_ : ranges1RcArr_), rangesRarr_fw_ (fw2_ ? ranges2FwArr_ : ranges2RcArr_), offsLsz_fw_ (fw1_ ? offs1FwSz_ : offs1RcSz_), offsRsz_fw_ (fw2_ ? offs2FwSz_ : offs2RcSz_), chaseL_rc_ (fw2_ ? chase2Rc_ : chase2Fw_), chaseR_rc_ (fw1_ ? chase1Rc_ : chase1Fw_), delayedchaseL_rc_(fw2_ ? delayedChase2Rc_ : delayedChase2Fw_), delayedchaseR_rc_(fw1_ ? delayedChase1Rc_ : delayedChase1Fw_), drL_rc_ (fw2_ ? *driver2Rc_ : *driver2Fw_), drR_rc_ (fw1_ ? *driver1Rc_ : *driver1Fw_), offsLarr_rc_ (fw2_ ? offs2RcArr_ : offs2FwArr_), offsRarr_rc_ (fw1_ ? offs1RcArr_ : offs1FwArr_), rangesLarr_rc_ (fw2_ ? ranges2RcArr_ : ranges2FwArr_), rangesRarr_rc_ (fw1_ ? ranges1RcArr_ : ranges1FwArr_), offsLsz_rc_ (fw2_ ? offs2RcSz_ : offs2FwSz_), offsRsz_rc_ (fw1_ ? offs1RcSz_ : offs1FwSz_), chaseL_ (&chaseL_fw_), chaseR_ (&chaseR_fw_), delayedchaseL_(&delayedchaseL_fw_), delayedchaseR_(&delayedchaseR_fw_), drL_ (&drL_fw_), drR_ (&drR_fw_), offsLarr_ (offsLarr_fw_), offsRarr_ (offsRarr_fw_), rangesLarr_ (rangesLarr_fw_), rangesRarr_ (rangesRarr_fw_), offsLsz_ (&offsLsz_fw_), offsRsz_ (&offsRsz_fw_), donePair_ (&doneFw_), fwL_(fw1), fwR_(fw2), verbose2_(false) { assert(pool_ != NULL); assert(sinkPt_ != NULL); assert(params_ != NULL); assert(driver1Fw_ != NULL); assert(driver1Rc_ != NULL); assert(driver2Fw_ != NULL); assert(driver2Rc_ != NULL); } virtual ~PairedBWAlignerV1() { delete driver1Fw_; driver1Fw_ = NULL; delete driver1Rc_; driver1Rc_ = NULL; delete driver2Fw_; driver2Fw_ = NULL; delete driver2Rc_; driver2Rc_ = NULL; delete params_; params_ = NULL; delete rchase_; rchase_ = NULL; delete[] btCnt_; btCnt_ = NULL; delete refAligner_; refAligner_ = NULL; sinkPtFactory_.destroy(sinkPt_); sinkPt_ = NULL; } /** * Prepare this aligner for the next read. */ virtual void setQuery(PatternSourcePerThread* patsrc) { assert(!patsrc->bufa().empty()); Aligner::setQuery(patsrc); // set fields & random seed assert(!patsrc->bufb().empty()); // Give all of the drivers pointers to the relevant read info patsrc_ = patsrc; pool_->reset(&patsrc->bufa().name, patsrc->patid()); if(patsrc->bufa().length() < 4 || patsrc->bufb().length() < 4) { if(!quiet_) { cerr << "Warning: Skipping pair " << patsrc->bufa().name << " because a mate is less than 4 characters long" << endl; } this->done = true; sinkPt_->finishRead(*patsrc_, true, true); return; } driver1Fw_->setQuery(patsrc, NULL); driver1Rc_->setQuery(patsrc, NULL); driver2Fw_->setQuery(patsrc, NULL); driver2Rc_->setQuery(patsrc, NULL); qlen1_ = patsrc_->bufa().length(); qlen2_ = patsrc_->bufb().length(); if(btCnt_ != NULL) (*btCnt_) = maxBts_; // Neither orientation is done doneFw_ = false; doneFwFirst_ = true; this->done = false; // No ranges are being chased yet chase1Fw_ = false; chase1Rc_ = false; chase2Fw_ = false; chase2Rc_ = false; delayedChase1Fw_ = false; delayedChase1Rc_ = false; delayedChase2Fw_ = false; delayedChase2Rc_ = false; // Clear all intermediate ranges for(size_t i = 0; i < 32; i++) { offs1FwArr_[i].clear(); offs1RcArr_[i].clear(); offs2FwArr_[i].clear(); offs2RcArr_[i].clear(); ranges1FwArr_[i].clear(); ranges1RcArr_[i].clear(); ranges2FwArr_[i].clear(); ranges2RcArr_[i].clear(); } offs1FwSz_ = offs1RcSz_ = offs2FwSz_ = offs2RcSz_ = 0; chaseL_ = &chaseL_fw_; chaseR_ = &chaseR_fw_; delayedchaseL_ = &delayedchaseL_fw_; delayedchaseR_ = &delayedchaseR_fw_; drL_ = &drL_fw_; drR_ = &drR_fw_; offsLarr_ = offsLarr_fw_; offsRarr_ = offsRarr_fw_; rangesLarr_ = rangesLarr_fw_; rangesRarr_ = rangesRarr_fw_; offsLsz_ = &offsLsz_fw_; offsRsz_ = &offsRsz_fw_; donePair_ = &doneFw_; fwL_ = fw1_; fwR_ = fw2_; mixedAttempts_ = 0; pairs_fw_.clear(); pairs_rc_.clear(); #ifndef NDEBUG allTopsL_fw_.clear(); allTopsR_fw_.clear(); allTopsL_rc_.clear(); allTopsR_rc_.clear(); #endif } /** * Advance the aligner by one memory op. Return true iff we're * done with this read. * * A call to this function does one of many things: * 1. Advance a RangeSourceDriver and check if it found a new range * 2. Advance a RowChaseDriver and check if it found a reference * offset for a an alignment in a range */ virtual bool advance() { assert(!this->done); if(doneFw_ && doneFwFirst_) { if(verbose2_) cout << "--" << endl; chaseL_ = &chaseL_rc_; chaseR_ = &chaseR_rc_; delayedchaseL_ = &delayedchaseL_rc_; delayedchaseR_ = &delayedchaseR_rc_; drL_ = &drL_rc_; drR_ = &drR_rc_; offsLarr_ = offsLarr_rc_; offsRarr_ = offsRarr_rc_; rangesLarr_ = rangesLarr_rc_; rangesRarr_ = rangesRarr_rc_; offsLsz_ = &offsLsz_rc_; offsRsz_ = &offsRsz_rc_; donePair_ = &this->done; fwL_ = !fw2_; fwR_ = !fw1_; doneFwFirst_ = false; mixedAttempts_ = 0; } bool chasing = *chaseL_ || *chaseR_; if(chasing && !rchase_->foundOff() && !rchase_->done) { rchase_->advance(); return false; } advanceOrientation(!doneFw_); if(this->done) { if(verbose2_) cout << "----" << endl; sinkPt_->finishRead(*patsrc_, true, true); } return this->done; } protected: /** * Helper for reporting a pair of alignments. As of now, we report * a paired alignment by reporting two consecutive alignments, one * for each mate. */ bool report(const Range& rL, // range for upstream mate const Range& rR, // range for downstream mate uint32_t first, // ref idx uint32_t upstreamOff, // offset for upstream mate uint32_t dnstreamOff, // offset for downstream mate uint32_t tlen, // length of ref bool pairFw, // whether the pair is being mapped to fw strand bool ebwtFwL, bool ebwtFwR, const ReferenceMap* rmap) { BowtieContext::Search* ctx = BowtieContext::getSearchContext(); assert_lt(upstreamOff, dnstreamOff); uint32_t spreadL = rL.bot - rL.top; uint32_t spreadR = rR.bot - rR.top; uint32_t oms = min(spreadL, spreadR) - 1; ReadBuf* bufL = pairFw ? bufa_ : bufb_; ReadBuf* bufR = pairFw ? bufb_ : bufa_; uint32_t lenL = pairFw ? alen_ : blen_; uint32_t lenR = pairFw ? blen_ : alen_; bool ret; assert(!params_->sink().exceededOverThresh()); params_->setFw(rL.fw); assert_eq(bufL->color, ctx->color); // Print upstream mate first ret = params_->reportHit( rL.fw ? (ebwtFwL? bufL->patFw : bufL->patFwRev) : (ebwtFwL? bufL->patRc : bufL->patRcRev), rL.fw ? (ebwtFwL? &bufL->qual : &bufL->qualRev) : (ebwtFwL? &bufL->qualRev : &bufL->qual), &bufL->name, bufL->color, ctx->colorExEnds, ctx->snpPhred, refs_, rmap, ebwtFwL, rL.mms, // mismatch positions rL.refcs, // reference characters for mms rL.numMms, // # mismatches make_pair(first, upstreamOff),// position make_pair(first, dnstreamOff),// mate position rR.fw, // mate orientation lenR, // mate length make_pair(rL.top, rL.bot), // arrows tlen, // textlen lenL, // qlen rL.stratum, // alignment stratum rL.cost, // cost, including quality penalty oms, // # other hits bufL->patid, bufL->seed, pairFw ? 1 : 2); if(ret) { return true; // can happen when -m is set } params_->setFw(rR.fw); assert_eq(bufR->color, ctx->color); ret = params_->reportHit( rR.fw ? (ebwtFwR? bufR->patFw : bufR->patFwRev) : (ebwtFwR? bufR->patRc : bufR->patRcRev), rR.fw ? (ebwtFwR? &bufR->qual : &bufR->qualRev) : (ebwtFwR? &bufR->qualRev : &bufR->qual), &bufR->name, bufR->color, ctx->colorExEnds, ctx->snpPhred, refs_, rmap, ebwtFwR, rR.mms, // mismatch positions rR.refcs, // reference characters for mms rR.numMms, // # mismatches make_pair(first, dnstreamOff),// position make_pair(first, upstreamOff),// mate position rL.fw, // mate orientation lenL, // mate length make_pair(rR.top, rR.bot), // arrows tlen, // textlen lenR, // qlen rR.stratum, // alignment stratum rR.cost, // cost, including quality penalty oms, // # other hits bufR->patid, bufR->seed, pairFw ? 2 : 1); return ret; } bool report(const Range& rL, // range for upstream mate const Range& rR, // range for downstream mate uint32_t first, // ref idx uint32_t upstreamOff, // offset for upstream mate uint32_t dnstreamOff, // offset for downstream mate uint32_t tlen, // length of ref bool pairFw, // whether the pair is being mapped to fw strand const ReferenceMap* rmap) { return report(rL, rR, first, upstreamOff, dnstreamOff, tlen, pairFw, rL.ebwt->fw(), rR.ebwt->fw(), rmap); } /** * Given a vector of reference positions where one of the two mates * (the "anchor" mate) has aligned, look directly at the reference * sequence for instances where the other mate (the "outstanding" * mate) aligns such that mating constraint is satisfied. * * This function picks up to 'pick' anchors at random from the * 'offs' array. It returns the number that it actually picked. */ bool resolveOutstandingInRef(const bool off1, const U32Pair& off, const uint32_t tlen, const Range& range) { assert(refs_->loaded()); assert_lt(off.first, refs_->numRefs()); // If matchRight is true, then we're trying to align the other // mate to the right of the already-aligned mate. Otherwise, // to the left. bool matchRight = (off1 ? !doneFw_ : doneFw_); // Sequence and quals for mate to be matched bool fw = off1 ? fw2_ : fw1_; // whether outstanding mate is fw/rc if(doneFw_) fw = !fw; // 'seq' gets sequence of outstanding mate w/r/t the forward // reference strand const String& seq = fw ? (off1 ? patsrc_->bufb().patFw : patsrc_->bufa().patFw) : (off1 ? patsrc_->bufb().patRc : patsrc_->bufa().patRc); // 'seq' gets qualities of outstanding mate w/r/t the forward // reference strand const String& qual = fw ? (off1 ? patsrc_->bufb().qual : patsrc_->bufa().qual) : (off1 ? patsrc_->bufb().qualRev : patsrc_->bufa().qualRev); uint32_t qlen = seqan::length(seq); // length of outstanding mate uint32_t alen = (off1 ? patsrc_->bufa().length() : patsrc_->bufb().length()); int minins = minInsert_; int maxins = maxInsert_; if(fw1_) { minins = max(0, minins - patsrc_->bufa().trimmed5); maxins = max(0, maxins - patsrc_->bufa().trimmed5); } else { minins = max(0, minins - patsrc_->bufa().trimmed3); maxins = max(0, maxins - patsrc_->bufa().trimmed3); } if(fw2_) { minins = max(0, minins - patsrc_->bufb().trimmed3); maxins = max(0, maxins - patsrc_->bufb().trimmed3); } else { minins = max(0, minins - patsrc_->bufb().trimmed5); maxins = max(0, maxins - patsrc_->bufb().trimmed5); } assert_geq(minins, 0); assert_geq(maxins, 0); // Don't even try if either of the mates is longer than the // maximum insert size. if((uint32_t)maxins <= max(qlen, alen)) { return false; } const uint32_t tidx = off.first; const uint32_t toff = off.second; // Set begin/end to be a range of all reference // positions that are legally permitted to be involved in // the alignment of the outstanding mate. It's up to the // callee to worry about how to scan these positions. uint32_t begin, end; assert_geq(maxins, minins); uint32_t insDiff = maxins - minins; if(matchRight) { end = toff + maxins; begin = toff + 1; if(qlen < alen) begin += alen-qlen; if(end > insDiff + qlen) { begin = max(begin, end - insDiff - qlen); } end = min(refs_->approxLen(tidx), end); begin = min(refs_->approxLen(tidx), begin); } else { if(toff + alen < (uint32_t)maxins) { begin = 0; } else { begin = toff + alen - maxins; } uint32_t mi = min(alen, qlen); end = toff + mi - 1; end = min(end, toff + alen - minins + qlen - 1); if(toff + alen + qlen < (uint32_t)minins + 1) end = 0; } // Check if there's not enough space in the range to fit an // alignment for the outstanding mate. if(end - begin < qlen) return false; std::vector ranges; std::vector offs; refAligner_->find(1, tidx, refs_, seq, qual, begin, end, ranges, offs, doneFw_ ? &pairs_rc_ : &pairs_fw_, toff, fw); assert_eq(ranges.size(), offs.size()); for(size_t i = 0; i < ranges.size(); i++) { Range& r = ranges[i]; r.fw = fw; r.cost |= (r.stratum << 14); r.mate1 = !off1; const uint32_t result = offs[i]; // Just copy the known range's top and bot for now r.top = range.top; r.bot = range.bot; bool ebwtLFw = matchRight ? range.ebwt->fw() : true; bool ebwtRFw = matchRight ? true : range.ebwt->fw(); if(report( matchRight ? range : r, // range for upstream mate matchRight ? r : range, // range for downstream mate tidx, // ref idx matchRight ? toff : result, // upstream offset matchRight ? result : toff, // downstream offset tlen, // length of ref !doneFw_, // whether the pair is being mapped to fw strand ebwtLFw, ebwtRFw, range.ebwt->rmap())) return true; } return false; } /** * Advance paired-end alignment. */ void advanceOrientation(bool pairFw) { assert(!this->done); assert(!*donePair_); assert(!*chaseL_ || !*chaseR_); if(*chaseL_) { assert(!rangeMode_); assert(!*delayedchaseL_); assert(drL_->foundRange); assert(rchase_->foundOff() || rchase_->done); if(rchase_->foundOff()) { // Resolve this against the reference loci // determined for the other mate const bool overThresh = (*offsLsz_ + *offsRsz_) > mixedThresh_; if(!this->done && (overThresh || dontReconcile_)) { // Because the total size of both ranges exceeds // our threshold, we're now operating in "mixed // mode" const Range& r = drL_->range(); assert(r.repOk()); if(verbose_) cout << "Making an attempt to find the outstanding mate" << endl; this->done = resolveOutstandingInRef( pairFw, rchase_->off(), r.ebwt->_plen[rchase_->off().first], r); if(++mixedAttempts_ > mixedAttemptLim_) { // Give up on this pair *donePair_ = true; return; } } rchase_->reset(); } else { assert(rchase_->done); // Forget this range; keep looking for ranges *chaseL_ = false; drL_->foundRange = false; if(verbose_) cout << "Done with chase for first mate" << endl; if(*delayedchaseR_) { // Start chasing the delayed range if(verbose_) cout << "Resuming delayed chase for second mate" << endl; assert(drR_->foundRange); const Range& r = drR_->range(); assert(r.repOk()); uint32_t top = r.top; uint32_t bot = r.bot; uint32_t qlen = doneFw_? qlen1_ : qlen2_; rchase_->setTopBot(top, bot, qlen, rand_, r.ebwt); *chaseR_ = true; *delayedchaseR_ = false; } } } else if(*chaseR_) { assert(!rangeMode_); assert(!*delayedchaseR_); assert(drR_->foundRange); assert(rchase_->foundOff() || rchase_->done); if(rchase_->foundOff()) { // Resolve this against the reference loci // determined for the other mate const bool overThresh = (*offsLsz_ + *offsRsz_) > mixedThresh_; if(!this->done && (overThresh || dontReconcile_)) { // Because the total size of both ranges exceeds // our threshold, we're now operating in "mixed // mode" const Range& r = drR_->range(); if(verbose_) cout << "Making an attempt to find the outstanding mate" << endl; this->done = resolveOutstandingInRef( !pairFw, rchase_->off(), r.ebwt->_plen[rchase_->off().first], r); if(++mixedAttempts_ > mixedAttemptLim_) { // Give up on this pair *donePair_ = true; return; } } rchase_->reset(); } else { assert(rchase_->done); // Forget this range; keep looking for ranges *chaseR_ = false; drR_->foundRange = false; if(verbose_) cout << "Done with chase for second mate" << endl; if(*delayedchaseL_) { // Start chasing the delayed range if(verbose_) cout << "Resuming delayed chase for first mate" << endl; assert(drL_->foundRange); const Range& r = drL_->range(); assert(r.repOk()); uint32_t top = r.top; uint32_t bot = r.bot; uint32_t qlen = doneFw_? qlen2_ : qlen1_; rchase_->setTopBot(top, bot, qlen, rand_, r.ebwt); *chaseL_ = true; *delayedchaseL_ = false; } } } if(!this->done && !*donePair_ && !*chaseL_ && !*chaseR_) { // Search for more ranges for whichever mate currently has // fewer candidate alignments if((*offsLsz_ < *offsRsz_ || drR_->done) && !drL_->done) { // If there are no more ranges for the other mate and // there are no candidate alignments either, then we're // not going to find a paired alignment in this // orientation. if(drR_->done && *offsRsz_ == 0) { // Give up on this orientation if(verbose_) cout << "Giving up on paired orientation " << (pairFw? "fw" : "rc") << " in mate 1" << endl; *donePair_ = true; if(verbose2_) cout << *offsLsz_ << " " << *offsRsz_ << endl; return; } assert(!*delayedchaseL_); if(!drL_->foundRange) drL_->advance(ADV_FOUND_RANGE); if(drL_->foundRange) { #ifndef NDEBUG { std::set& s = (pairFw ? allTopsL_fw_ : allTopsL_rc_); int64_t t = drL_->range().top + 1; // add 1 to avoid 0 if(!drL_->range().ebwt->fw()) t = -t; // invert for bw index assert(s.find(t) == s.end()); s.insert(t); } #endif // Add the size of this range to the total for this mate *offsLsz_ += (drL_->range().bot - drL_->range().top); if(*offsRsz_ == 0 && (!dontReconcile_ || *offsLsz_ > 3)) { // Delay chasing this range; we delay to avoid // needlessly chasing rows in this range when // the other mate doesn't end up aligning // anywhere if(verbose_) cout << "Delaying a chase for first mate" << endl; *delayedchaseL_ = true; } else { // Start chasing this range if(verbose2_) cout << *offsLsz_ << " " << *offsRsz_ << " " << drL_->range().top << endl; if(verbose_) cout << "Chasing a range for first mate" << endl; if(*offsLsz_ > symCeiling_ && *offsRsz_ > symCeiling_) { // Too many candidates for both mates; abort // without any more searching *donePair_ = true; return; } // If this is the first range for both mates, // choose the smaller range to chase down first if(*delayedchaseR_ && (*offsRsz_ < *offsLsz_)) { assert(drR_->foundRange); *delayedchaseR_ = false; *delayedchaseL_ = true; *chaseR_ = true; const Range& r = drR_->range(); assert(r.repOk()); uint32_t qlen = doneFw_? qlen1_ : qlen2_; rchase_->setTopBot(r.top, r.bot, qlen, rand_, r.ebwt); } else { // Use Burrows-Wheeler for this pair (as // usual) *chaseL_ = true; const Range& r = drL_->range(); uint32_t qlen = doneFw_? qlen2_ : qlen1_; rchase_->setTopBot(r.top, r.bot, qlen, rand_, r.ebwt); } } } } else if(!drR_->done) { // If there are no more ranges for the other mate and // there are no candidate alignments either, then we're // not going to find a paired alignment in this // orientation. if(drL_->done && *offsLsz_ == 0) { // Give up on this orientation if(verbose_) cout << "Giving up on paired orientation " << (pairFw? "fw" : "rc") << " in mate 2" << endl; if(verbose2_) cout << *offsLsz_ << " " << *offsRsz_ << endl; *donePair_ = true; return; } assert(!*delayedchaseR_); if(!drR_->foundRange) drR_->advance(ADV_FOUND_RANGE); if(drR_->foundRange) { #ifndef NDEBUG { std::set& s = (pairFw ? allTopsR_fw_ : allTopsR_rc_); int64_t t = drR_->range().top + 1; // add 1 to avoid 0 if(!drR_->range().ebwt->fw()) t = -t; // invert for bw index assert(s.find(t) == s.end()); s.insert(t); } #endif // Add the size of this range to the total for this mate *offsRsz_ += (drR_->range().bot - drR_->range().top); if(*offsLsz_ == 0 && (!dontReconcile_ || *offsRsz_ > 3)) { // Delay chasing this range; we delay to avoid // needlessly chasing rows in this range when // the other mate doesn't end up aligning // anywhere if(verbose_) cout << "Delaying a chase for second mate" << endl; *delayedchaseR_ = true; } else { // Start chasing this range if(verbose2_) cout << *offsLsz_ << " " << *offsRsz_ << " " << drR_->range().top << endl; if(verbose_) cout << "Chasing a range for second mate" << endl; if(*offsLsz_ > symCeiling_ && *offsRsz_ > symCeiling_) { // Too many candidates for both mates; abort // without any more searching *donePair_ = true; return; } // If this is the first range for both mates, // choose the smaller range to chase down first if(*delayedchaseL_ && *offsLsz_ < *offsRsz_) { assert(drL_->foundRange); *delayedchaseL_ = false; *delayedchaseR_ = true; *chaseL_ = true; const Range& r = drL_->range(); assert(r.repOk()); uint32_t qlen = doneFw_? qlen2_ : qlen1_; rchase_->setTopBot(r.top, r.bot, qlen, rand_, r.ebwt); } else { // Use Burrows-Wheeler for this pair (as // usual) *chaseR_ = true; const Range& r = drR_->range(); assert(r.repOk()); uint32_t qlen = doneFw_? qlen1_ : qlen2_; rchase_->setTopBot(r.top, r.bot, qlen, rand_, r.ebwt); } } } } else { // Finished processing ranges for both mates assert(drL_->done && drR_->done); *donePair_ = true; } } } const BitPairReference* refs_; PatternSourcePerThread *patsrc_; uint32_t qlen1_; uint32_t qlen2_; // Progress state bool doneFw_; // finished with forward orientation of both mates? bool doneFwFirst_; bool chase1Fw_; bool chase1Rc_; bool chase2Fw_; bool chase2Rc_; bool delayedChase1Fw_; bool delayedChase1Rc_; bool delayedChase2Fw_; bool delayedChase2Rc_; // For searching for outstanding mates RefAligner >* refAligner_; // Temporary HitSink; to be deleted const HitSinkPerThreadFactory& sinkPtFactory_; HitSinkPerThread* sinkPt_; // State for alignment EbwtSearchParams >* params_; // Paired-end boundaries const uint32_t minInsert_; const uint32_t maxInsert_; // Don't attempt pairwise all-versus-all style of mate // reconciliation; just rely on mixed mode const bool dontReconcile_; // If both mates in a given orientation align >= symCeiling times, // then immediately give up const uint32_t symCeiling_; // If the total number of alignments for both mates in a given // orientation exceeds mixedThresh, then switch to mixed mode const uint32_t mixedThresh_; const uint32_t mixedAttemptLim_; uint32_t mixedAttempts_; // Orientation of upstream/downstream mates when aligning to // forward strand const bool fw1_; const bool fw2_; // State for getting alignments from ranges statefully RangeChaser >* rchase_; // true -> be talkative bool verbose_; // true -> suppress warnings bool quiet_; int maxBts_; ChunkPool *pool_; int *btCnt_; // Range-finding state for first mate TDriver* driver1Fw_; TDriver* driver1Rc_; U32PairVec offs1FwArr_[32]; TRangeVec ranges1FwArr_[32]; uint32_t offs1FwSz_; // total size of all ranges found in this category U32PairVec offs1RcArr_[32]; TRangeVec ranges1RcArr_[32]; uint32_t offs1RcSz_; // total size of all ranges found in this category // Range-finding state for second mate TDriver* driver2Fw_; TDriver* driver2Rc_; U32PairVec offs2FwArr_[32]; TRangeVec ranges2FwArr_[32]; uint32_t offs2FwSz_; // total size of all ranges found in this category U32PairVec offs2RcArr_[32]; TRangeVec ranges2RcArr_[32]; uint32_t offs2RcSz_; // total size of all ranges found in this category bool& chaseL_fw_; bool& chaseR_fw_; bool& delayedchaseL_fw_; bool& delayedchaseR_fw_; TDriver& drL_fw_; TDriver& drR_fw_; U32PairVec* offsLarr_fw_; U32PairVec* offsRarr_fw_; TRangeVec* rangesLarr_fw_; TRangeVec* rangesRarr_fw_; uint32_t& offsLsz_fw_; uint32_t& offsRsz_fw_; bool& chaseL_rc_; bool& chaseR_rc_; bool& delayedchaseL_rc_; bool& delayedchaseR_rc_; TDriver& drL_rc_; TDriver& drR_rc_; U32PairVec* offsLarr_rc_; U32PairVec* offsRarr_rc_; TRangeVec* rangesLarr_rc_; TRangeVec* rangesRarr_rc_; uint32_t& offsLsz_rc_; uint32_t& offsRsz_rc_; bool* chaseL_; bool* chaseR_; bool* delayedchaseL_; bool* delayedchaseR_; TDriver* drL_; TDriver* drR_; U32PairVec* offsLarr_; U32PairVec* offsRarr_; TRangeVec* rangesLarr_; TRangeVec* rangesRarr_; uint32_t* offsLsz_; uint32_t* offsRsz_; bool* donePair_; bool fwL_; bool fwR_; /// For keeping track of paired alignments that have already been /// found for the forward and reverse-comp pair orientations TSetPairs pairs_fw_; TSetPairs pairs_rc_; #ifndef NDEBUG std::set allTopsL_fw_; std::set allTopsR_fw_; std::set allTopsL_rc_; std::set allTopsR_rc_; #endif bool verbose2_; }; /** * Helper struct that holds a Range together with the coordinates where it al */ struct RangeWithCoords { Range r; U32Pair h; }; /** * An aligner for finding paired alignments while operating entirely * within the Burrows-Wheeler domain. */ template class PairedBWAlignerV2 : public Aligner { typedef std::pair U32Pair; typedef std::vector U32PairVec; typedef std::vector TRangeVec; typedef RangeSourceDriver TDriver; typedef std::pair TU64Pair; typedef std::set TSetPairs; public: PairedBWAlignerV2( EbwtSearchParams >* params, EbwtSearchParams >* paramsSe1, EbwtSearchParams >* paramsSe2, TDriver* driver, RefAligner >* refAligner, RangeChaser >* rchase, HitSink& sink, const HitSinkPerThreadFactory& sinkPtFactory, HitSinkPerThread* sinkPt, HitSinkPerThread* sinkPtSe1, HitSinkPerThread* sinkPtSe2, bool fw1, bool fw2, uint32_t minInsert, uint32_t maxInsert, uint32_t mixedAttemptLim, const BitPairReference* refs, bool rangeMode, bool verbose, bool quiet, int maxBts, ChunkPool *pool, int *btCnt) : Aligner(true, rangeMode), refs_(refs), patsrc_(NULL), qlen1_(0), qlen2_(0), chase_(false), donePe_(false), doneSe1_(false), doneSe2_(false), refAligner_(refAligner), sinkPtFactory_(sinkPtFactory), sinkPt_(sinkPt), sinkPtSe1_(sinkPtSe1), sinkPtSe2_(sinkPtSe2), params_(params), paramsSe1_(paramsSe1), paramsSe2_(paramsSe2), minInsert_(minInsert), maxInsert_(maxInsert), mixedAttemptLim_(mixedAttemptLim), mixedAttempts_(0), fw1_(fw1), fw2_(fw2), rchase_(rchase), driver_(driver), pool_(pool), verbose_(verbose), quiet_(quiet), maxBts_(maxBts), btCnt_(btCnt) { assert(sinkPt_ != NULL); assert(params_ != NULL); assert(driver_ != NULL); } virtual ~PairedBWAlignerV2() { delete driver_; driver_ = NULL; delete params_; params_ = NULL; if(paramsSe1_ != NULL) { delete paramsSe1_; paramsSe1_ = NULL; delete paramsSe2_; paramsSe2_ = NULL; } delete rchase_; rchase_ = NULL; delete[] btCnt_; btCnt_ = NULL; delete refAligner_; refAligner_ = NULL; sinkPtFactory_.destroy(sinkPt_); sinkPt_ = NULL; if(sinkPtSe1_ != NULL) { sinkPtFactory_.destroy(sinkPtSe1_); sinkPtSe1_ = NULL; sinkPtFactory_.destroy(sinkPtSe2_); sinkPtSe2_ = NULL; } } /** * Prepare this aligner for the next read. */ virtual void setQuery(PatternSourcePerThread* patsrc) { assert(!patsrc->bufa().empty()); Aligner::setQuery(patsrc); // set fields & random seed assert(!patsrc->bufb().empty()); // Give all of the drivers pointers to the relevant read info patsrc_ = patsrc; pool_->reset(&patsrc->bufa().name, patsrc->patid()); if(patsrc->bufa().length() < 4 || patsrc->bufb().length() < 4) { if(!quiet_) { cerr << "Warning: Skipping pair " << patsrc->bufa().name << " because a mate is less than 4 characters long" << endl; } this->done = true; sinkPt_->finishRead(*patsrc_, true, true); return; } driver_->setQuery(patsrc, NULL); qlen1_ = patsrc_->bufa().length(); qlen2_ = patsrc_->bufb().length(); if(btCnt_ != NULL) (*btCnt_) = maxBts_; mixedAttempts_ = 0; // Neither orientation is done this->done = false; // No ranges are being chased yet chase_ = false; donePe_ = doneSe1_ = doneSe2_ = false; pairs_fw_.clear(); pairs_rc_.clear(); } /** * Advance the aligner by one memory op. Return true iff we're * done with this read. * * A call to this function does one of many things: * 1. Advance a RangeSourceDriver and check if it found a new range * 2. Advance a RowChaseDriver and check if it found a reference * offset for a an alignment in a range */ virtual bool advance() { assert(!this->done); if(chase_) { assert(!rangeMode_); // chasing ranges if(!rchase_->foundOff() && !rchase_->done) { rchase_->advance(); return false; } assert(rchase_->foundOff() || rchase_->done); if(rchase_->foundOff()) { const Range& r = driver_->range(); assert(r.repOk()); resolveOutstanding( rchase_->off(), r.ebwt->_plen[rchase_->off().first], r); rchase_->reset(); } else { assert(rchase_->done); // Forget this range; keep looking for ranges chase_ = false; this->done = driver_->done; } } if(!this->done && !chase_) { // Search for more ranges for whichever mate currently has // fewer candidate alignments if(!driver_->done) { if(!this->done) { // // Check whether any of the PE/SE possibilities // have become impossible due to the minCost // if(!donePe_) { assert(!this->done); donePe_ = sinkPt_->irrelevantCost(driver_->minCost); if(donePe_ && (!sinkPt_->empty() || sinkPtSe1_ == NULL)) { // Paired-end alignment(s) were found, no // more will be found, and no unpaired // alignments are requested, so stop this->done = true; } if(donePe_ && sinkPtSe1_ != NULL) { // Note: removeMate affects minCost if(doneSe1_) driver_->removeMate(1); if(doneSe2_) driver_->removeMate(2); } } if(!this->done && sinkPtSe1_ != NULL) { if(!doneSe1_) { doneSe1_ = sinkPtSe1_->irrelevantCost(driver_->minCost); if(doneSe1_ && donePe_) driver_->removeMate(1); } if(!doneSe2_) { doneSe2_ = sinkPtSe2_->irrelevantCost(driver_->minCost); if(doneSe2_ && donePe_) driver_->removeMate(2); } // Do Se1 again, because removing Se2 may have // nudged minCost over the threshold if(!doneSe1_) { doneSe1_ = sinkPtSe1_->irrelevantCost(driver_->minCost); if(doneSe1_ && donePe_) driver_->removeMate(1); } if(doneSe1_ && doneSe2_) assert(donePe_); this->done = donePe_ && doneSe1_ && doneSe2_; } if(!this->done) { if(sinkPtSe1_ != NULL) { assert(doneSe1_ || !sinkPtSe1_->irrelevantCost(driver_->minCost)); assert(doneSe2_ || !sinkPtSe2_->irrelevantCost(driver_->minCost)); } assert(donePe_ || !sinkPt_->irrelevantCost(driver_->minCost)); driver_->advance(ADV_COST_CHANGES); } } if(driver_->foundRange) { // Use Burrows-Wheeler for this pair (as usual) chase_ = true; driver_->foundRange = false; const Range& r = driver_->range(); assert(r.repOk()); rchase_->setTopBot(r.top, r.bot, r.mate1 ? qlen1_ : qlen2_, rand_, r.ebwt); } } else { this->done = true; } } if(this->done) { bool reportedPe = (sinkPt_->finishRead(*patsrc_, true, true) > 0); if(sinkPtSe1_ != NULL) { sinkPtSe1_->finishRead(*patsrc_, !reportedPe, false); sinkPtSe2_->finishRead(*patsrc_, !reportedPe, false); } } return this->done; } protected: /** * Helper for reporting a pair of alignments. As of now, we report * a paired alignment by reporting two consecutive alignments, one * for each mate. */ bool report(const Range& rL, // range for upstream mate const Range& rR, // range for downstream mate uint32_t first, // ref idx uint32_t upstreamOff, // offset for upstream mate uint32_t dnstreamOff, // offset for downstream mate uint32_t tlen, // length of ref bool pairFw, // whether the pair is being mapped to fw strand bool ebwtFwL, bool ebwtFwR, const ReferenceMap *rmap) { BowtieContext::Search* ctx = BowtieContext::getSearchContext(); assert_lt(upstreamOff, dnstreamOff); uint32_t spreadL = rL.bot - rL.top; uint32_t spreadR = rR.bot - rR.top; uint32_t oms = min(spreadL, spreadR) - 1; ReadBuf* bufL = pairFw ? bufa_ : bufb_; ReadBuf* bufR = pairFw ? bufb_ : bufa_; uint32_t lenL = pairFw ? alen_ : blen_; uint32_t lenR = pairFw ? blen_ : alen_; bool ret; assert(!params_->sink().exceededOverThresh()); params_->setFw(rL.fw); assert_eq(bufL->color, ctx->color); // Print upstream mate first ret = params_->reportHit( rL.fw ? (ebwtFwL? bufL->patFw : bufL->patFwRev) : (ebwtFwL? bufL->patRc : bufL->patRcRev), rL.fw ? (ebwtFwL? &bufL->qual : &bufL->qualRev) : (ebwtFwL? &bufL->qualRev : &bufL->qual), &bufL->name, bufL->color, ctx->colorExEnds, ctx->snpPhred, refs_, rmap, ebwtFwL, rL.mms, // mismatch positions rL.refcs, // reference characters for mms rL.numMms, // # mismatches make_pair(first, upstreamOff),// position make_pair(first, dnstreamOff),// mate position rR.fw, // mate orientation lenR, // mate length make_pair(rL.top, rL.bot), // arrows tlen, // textlen lenL, // qlen rL.stratum, // alignment stratum rL.cost, // cost, including quality penalty oms, // # other hits bufL->patid, bufL->seed, pairFw ? 1 : 2); if(ret) { return true; // can happen when -m is set } params_->setFw(rR.fw); assert_eq(bufR->color, ctx->color); ret = params_->reportHit( rR.fw ? (ebwtFwR? bufR->patFw : bufR->patFwRev) : (ebwtFwR? bufR->patRc : bufR->patRcRev), rR.fw ? (ebwtFwR? &bufR->qual : &bufR->qualRev) : (ebwtFwR? &bufR->qualRev : &bufR->qual), &bufR->name, bufR->color, ctx->colorExEnds, ctx->snpPhred, refs_, rmap, ebwtFwR, rR.mms, // mismatch positions rR.refcs, // reference characters for mms rR.numMms, // # mismatches make_pair(first, dnstreamOff),// position make_pair(first, upstreamOff),// mate position rL.fw, // mate orientation lenL, // mate length make_pair(rR.top, rR.bot), // arrows tlen, // textlen lenR, // qlen rR.stratum, // alignment stratum rR.cost, // cost, including quality penalty oms, // # other hits bufR->patid, bufR->seed, pairFw ? 2 : 1); return ret; } /** * Helper for reporting a pair of alignments. As of now, we report * a paired alignment by reporting two consecutive alignments, one * for each mate. */ void reportSe(const Range& r, U32Pair h, uint32_t tlen) { BowtieContext::Search* ctx = BowtieContext::getSearchContext(); EbwtSearchParams >*params = (r.mate1 ? paramsSe1_ : paramsSe2_); assert(!(r.mate1 ? doneSe1_ : doneSe2_)); params->setFw(r.fw); ReadBuf* buf = r.mate1 ? bufa_ : bufb_; bool ebwtFw = r.ebwt->fw(); uint32_t len = r.mate1 ? alen_ : blen_; assert_eq(buf->color, ctx->color); // Print upstream mate first if(params->reportHit( r.fw ? (ebwtFw? buf->patFw : buf->patFwRev) : (ebwtFw? buf->patRc : buf->patRcRev), r.fw ? (ebwtFw? &buf->qual : &buf->qualRev) : (ebwtFw? &buf->qualRev : &buf->qual), &buf->name, buf->color, ctx->colorExEnds, ctx->snpPhred, refs_, r.ebwt->rmap(), ebwtFw, r.mms, // mismatch positions r.refcs, // reference characters for mms r.numMms, // # mismatches h, // position make_pair(0, 0), // (bogus) mate coords true, // (bogus) mate orientation 0, // (bogus) mate length make_pair(r.top, r.bot), // arrows tlen, // textlen len, // qlen r.stratum, // alignment stratum r.cost, // cost, including quality penalty r.bot - r.top - 1, // # other hits buf->patid, buf->seed, 0)) { if(r.mate1) doneSe1_ = true; else doneSe2_ = true; if(donePe_) driver_->removeMate(r.mate1 ? 1 : 2); } } void resolveOutstanding(const U32Pair& off, const uint32_t tlen, const Range& range) { assert(!this->done); if(!donePe_) { bool ret = resolveOutstandingInRef(off, tlen, range); if(++mixedAttempts_ > mixedAttemptLim_ || ret) { // Give up on this pair donePe_ = true; if(sinkPtSe1_ != NULL) { if(doneSe1_) driver_->removeMate(1); if(doneSe2_) driver_->removeMate(2); } } this->done = (donePe_ && (!sinkPt_->empty() || sinkPtSe1_ == NULL || (doneSe1_ && doneSe2_))); } if(!this->done && sinkPtSe1_ != NULL) { bool doneSe = (range.mate1 ? doneSe1_ : doneSe2_); if(!doneSe) { // Hold onto this single-end alignment in case we don't // find any paired alignments reportSe(range, off, tlen); } this->done = doneSe1_ && doneSe2_ && donePe_; } } /** * Given a vector of reference positions where one of the two mates * (the "anchor" mate) has aligned, look directly at the reference * sequence for instances where the other mate (the "outstanding" * mate) aligns such that mating constraint is satisfied. * * This function picks up to 'pick' anchors at random from the * 'offs' array. It returns the number that it actually picked. */ bool resolveOutstandingInRef(const U32Pair& off, const uint32_t tlen, const Range& range) { assert(!donePe_); assert(refs_->loaded()); assert_lt(off.first, refs_->numRefs()); // pairFw = true if the anchor indicates that the pair will // align in its forward orientation (i.e. with mate1 to the // left of mate2) bool pairFw = (range.mate1)? (range.fw == fw1_) : (range.fw == fw2_); // matchRight = true, if the opposite mate will be to the right // of the anchor mate bool matchRight = (pairFw ? range.mate1 : !range.mate1); // fw = orientation of the opposite mate bool fw = range.mate1 ? fw2_ : fw1_; // whether outstanding mate is fw/rc if(!pairFw) fw = !fw; // 'seq' = sequence for opposite mate const String& seq = fw ? (range.mate1 ? patsrc_->bufb().patFw : patsrc_->bufa().patFw) : (range.mate1 ? patsrc_->bufb().patRc : patsrc_->bufa().patRc); // 'qual' = qualities for opposite mate const String& qual = fw ? (range.mate1 ? patsrc_->bufb().qual : patsrc_->bufa().qual) : (range.mate1 ? patsrc_->bufb().qualRev : patsrc_->bufa().qualRev); uint32_t qlen = seqan::length(seq); // length of outstanding mate uint32_t alen = (range.mate1 ? patsrc_->bufa().length() : patsrc_->bufb().length()); int minins = minInsert_; int maxins = maxInsert_; if(fw1_) { minins = max(0, minins - patsrc_->bufa().trimmed5); maxins = max(0, maxins - patsrc_->bufa().trimmed5); } else { minins = max(0, minins - patsrc_->bufa().trimmed3); maxins = max(0, maxins - patsrc_->bufa().trimmed3); } if(fw2_) { minins = max(0, minins - patsrc_->bufb().trimmed3); maxins = max(0, maxins - patsrc_->bufb().trimmed3); } else { minins = max(0, minins - patsrc_->bufb().trimmed5); maxins = max(0, maxins - patsrc_->bufb().trimmed5); } assert_geq(minins, 0); assert_geq(maxins, 0); // Don't even try if either of the mates is longer than the // maximum insert size. if((uint32_t)maxins <= max(qlen, alen)) { return false; } const uint32_t tidx = off.first; // text id where anchor mate hit const uint32_t toff = off.second; // offset where anchor mate hit // Set begin/end to the range of reference positions where // outstanding mate may align while fulfilling insert-length // constraints. uint32_t begin, end; assert_geq(maxins, minins); uint32_t insDiff = maxins - minins; if(matchRight) { end = toff + maxins; begin = toff + 1; if(qlen < alen) begin += alen-qlen; if(end > insDiff + qlen) { begin = max(begin, end - insDiff - qlen); } end = min(refs_->approxLen(tidx), end); begin = min(refs_->approxLen(tidx), begin); } else { if(toff + alen < (uint32_t)maxins) { begin = 0; } else { begin = toff + alen - maxins; } uint32_t mi = min(alen, qlen); end = toff + mi - 1; end = min(end, toff + alen - minins + qlen - 1); if(toff + alen + qlen < (uint32_t)(minins + 1)) end = 0; } // Check if there's not enough space in the range to fit an // alignment for the outstanding mate. if(end - begin < qlen) return false; std::vector ranges; std::vector offs; refAligner_->find(1, tidx, refs_, seq, qual, begin, end, ranges, offs, pairFw ? &pairs_fw_ : &pairs_rc_, toff, fw); assert_eq(ranges.size(), offs.size()); for(size_t i = 0; i < ranges.size(); i++) { Range& r = ranges[i]; r.fw = fw; r.cost |= (r.stratum << 14); r.mate1 = !range.mate1; const uint32_t result = offs[i]; // Just copy the known range's top and bot for now r.top = range.top; r.bot = range.bot; bool ebwtLFw = matchRight ? range.ebwt->fw() : true; bool ebwtRFw = matchRight ? true : range.ebwt->fw(); if(report( matchRight ? range : r, // range for upstream mate matchRight ? r : range, // range for downstream mate tidx, // ref idx matchRight ? toff : result, // upstream offset matchRight ? result : toff, // downstream offset tlen, // length of ref pairFw, // whether the pair is being mapped to fw strand ebwtLFw, ebwtRFw, range.ebwt->rmap())) return true; } return false; } const BitPairReference* refs_; PatternSourcePerThread *patsrc_; uint32_t qlen1_, qlen2_; bool chase_; // true -> we're no longer shooting for paired-end alignments; // just collecting single-end ones bool donePe_, doneSe1_, doneSe2_; // For searching for outstanding mates RefAligner >* refAligner_; // Temporary HitSink; to be deleted const HitSinkPerThreadFactory& sinkPtFactory_; HitSinkPerThread* sinkPt_; HitSinkPerThread* sinkPtSe1_, * sinkPtSe2_; // State for alignment EbwtSearchParams >* params_; // for single-end: EbwtSearchParams >* paramsSe1_, * paramsSe2_; // Paired-end boundaries const uint32_t minInsert_; const uint32_t maxInsert_; const uint32_t mixedAttemptLim_; uint32_t mixedAttempts_; // Orientation of upstream/downstream mates when aligning to // forward strand const bool fw1_, fw2_; // State for getting alignments from ranges statefully RangeChaser >* rchase_; // Range-finding state for first mate TDriver* driver_; // Pool for distributing chunks of best-first path descriptor memory ChunkPool *pool_; bool verbose_; bool quiet_; int maxBts_; // maximum allowed # backtracks int *btCnt_; // current backtrack count /// For keeping track of paired alignments that have already been /// found for the forward and reverse-comp pair orientations TSetPairs pairs_fw_, pairs_rc_; }; #endif /* ALIGNER_H_ */ ugene-1.9.8/src/plugins_3rdparty/bowtie/src/bowtie/color_dec.h0000644000175000017500000000176411651544326023104 0ustar ilyailya/* * color_dec.h * * Created on: Oct 14, 2009 * Author: Ben Langmead */ #ifndef COLOR_DEC_H_ #define COLOR_DEC_H_ #include #include #include #include "alphabet.h" void decodeHit( const char *read, // ASCII colors, '0', '1', '2', '3', '.' const char *qual, // ASCII quals, Phred+33 encoded size_t readi, // offset of first character within 'read' to consider size_t readf, // offset of last char (exclusive) in 'read' to consider const char *ref, // reference sequence, as masks size_t refi, // offset of first character within 'ref' to consider size_t reff, // offset of last char (exclusive) in 'ref' to consider int snpPhred, // penalty incurred by a SNP char *ns, // decoded nucleotides are appended here char *cmm, // where the color mismatches are in the string char *nmm, // where nucleotide mismatches are in the string int& cmms, // number of color mismatches int& nmms);// number of nucleotide mismatches #endif /* COLOR_DEC_H_ */ ugene-1.9.8/src/plugins_3rdparty/bowtie/src/bowtie/search_globals.h0000644000175000017500000000065211651544326024116 0ustar ilyailya/* * search_globals.h * * Created on: Dec 5, 2009 * Author: Ben Langmead */ #ifndef SEARCH_GLOBALS_H_ #define SEARCH_GLOBALS_H_ #include "threading.h" // declared in ebwt_search.cpp // extern bool color; // extern bool colorExEnds; // extern bool colorSeq; // extern bool colorQual; // extern int snpPhred; // extern bool showSeed; // extern bool quiet; //extern MUTEX_T gLock; #endif /* SEARCH_GLOBALS_H_ */ ugene-1.9.8/src/plugins_3rdparty/bowtie/src/bowtie/alphabet.h0000644000175000017500000001316111651544326022725 0ustar ilyailya#ifndef ALPHABETS_H_ #define ALPHABETS_H_ #include #include #include #include #include #include #include "assert_helpers.h" using namespace std; using namespace seqan; /** * Return a new TStr containing the reverse-complement of s. Ns go to * Ns. */ template static inline TStr reverseComplement(const TStr& s, bool color) { typedef typename Value::Type TVal; TStr s_rc; size_t slen = length(s); resize(s_rc, slen); if(color) { for(size_t i = 0; i < slen; i++) { s_rc[i] = s[slen-i-1]; } } else { for(size_t i = 0; i < slen; i++) { int sv = (int)s[slen-i-1]; if(sv == 4) { s_rc[i] = (TVal)4; } else { s_rc[i] = (TVal)(sv ^ 3); } } } return s_rc; } /** * Reverse-complement s in-place. Ns go to Ns. */ template static inline void reverseComplementInPlace(TStr& s, bool color) { typedef typename Value::Type TVal; if(color) { reverseInPlace(s); return; } size_t len = length(s); size_t i; for(i = 0; i < (len>>1); i++) { int sv = (int)s[len-i-1]; int sf = (int)s[i]; if(sv == 4) { s[i] = (TVal)4; } else { s[i] = (TVal)(sv ^ 3); } if(sf == 4) { s[len-i-1] = (TVal)4; } else { s[len-i-1] = (TVal)(sf ^ 3); } } if((len & 1) != 0 && (int)s[len >> 1] != 4) { s[len >> 1] = (TVal)((int)s[len >> 1] ^ 3); } } /// Reverse a string in-place template static inline void reverseInPlace(TStr& s) { typedef typename Value::Type TVal; size_t len = length(s); for(size_t i = 0; i < (len>>1); i++) { TVal tmp = s[i]; s[i] = s[len-i-1]; s[len-i-1] = tmp; } } /** * Return the reverse-complement of s. */ template static inline TStr reverseCopy(const TStr& s) { typedef typename Value::Type TVal; TStr s_rc; size_t slen = length(s); resize(s_rc, slen); for(size_t i = 0; i < slen; i++) { s_rc[i] = (TVal)((int)s[slen-i-1]); } return s_rc; } /** * Return true iff the first string is dollar-less-than the second. * This means that we pretend that a 'dollar sign' character, * lexicographically larger than all other characters, exists at the * end of both strings. */ template static inline bool dollarLt(const TStr& l, const TStr& r) { return isPrefix(r, l) || (l < r && !isPrefix(l, r)); } /** * Return true iff the first string is dollar-greater-than the second. * This means that we pretend that a 'dollar sign' character, * lexicographically larger than all other characters, exists at the * end of both strings. */ template static inline bool dollarGt(const TStr& l, const TStr& r) { return !dollarLt(l, r); } /** * Return a copy of the suffix of l starting at 'off'. */ template static inline std::string suffixStr(const TStr& l, size_t off) { typedef typename Value::Type TVal; std::string ret; size_t len = seqan::length(l); for(size_t i = off; i < len; i++) { ret.push_back((char)(TVal)l[i]); } return ret; } /** * Calculate the entropy of the given read. Handle Ns by charging them * to the most frequent non-N character. */ static inline float entropyDna5(const String& read) { size_t cs[5] = {0, 0, 0, 0, 0}; size_t readLen = seqan::length(read); for(size_t i = 0; i < readLen; i++) { int c = (int)read[i]; assert_lt(c, 5); assert_geq(c, 0); cs[c]++; } if(cs[4] > 0) { // Charge the Ns to the non-N character with maximal count and // then exclude them from the entropy calculation (i.e., // penalize Ns as much as possible) if(cs[0] >= cs[1] && cs[0] >= cs[2] && cs[0] >= cs[3]) { // Charge Ns to As cs[0] += cs[4]; } else if(cs[1] >= cs[2] && cs[1] >= cs[3]) { // Charge Ns to Cs cs[1] += cs[4]; } else if(cs[2] >= cs[3]) { // Charge Ns to Gs cs[2] += cs[4]; } else { // Charge Ns to Ts cs[3] += cs[4]; } } float ent = 0.0; for(int i = 0; i < 4; i++) { if(cs[i] > 0) { float frac = (float)cs[i] / (float)readLen; ent += (frac * log(frac)); } } ent = -ent; assert_geq(ent, 0.0); return ent; } /** * Return the DNA complement of the given ASCII char. */ static inline char comp(char c) { switch(c) { case 'a': return 't'; case 'A': return 'T'; case 'c': return 'g'; case 'C': return 'G'; case 'g': return 'c'; case 'G': return 'C'; case 't': return 'a'; case 'T': return 'A'; default: return c; } } extern uint8_t dna4Cat[]; extern uint8_t charToDna5[]; extern uint8_t asc2col[]; extern uint8_t rcCharToDna5[]; /// Convert an ascii char to a DNA category. Categories are: /// 0 -> invalid /// 1 -> unambiguous a, c, g or t /// 2 -> ambiguous /// 3 -> unmatchable extern uint8_t asc2dnacat[]; /// Convert an ascii char to a color category. Categories are: /// 0 -> invalid /// 1 -> unambiguous 0, 1, 2 or 3 /// 2 -> ambiguous (not applicable for colors) /// 3 -> unmatchable extern uint8_t asc2colcat[]; /// Convert a 2-bit nucleotide (and 4=N) and a color to the /// corresponding 2-bit nucleotide extern uint8_t nuccol2nuc[5][5]; /** * Return true iff c is an unambiguous Dna character. */ static inline bool isUnambigDna(char c) { return asc2dnacat[(int)c] == 1; } /** * Return true iff c is a Dna character. */ static inline bool isDna(char c) { return asc2dnacat[(int)c] > 0; } /** * Return true iff c is an unambiguous color character (0,1,2,3). */ static inline bool isUnambigColor(char c) { return asc2colcat[(int)c] == 1; } /** * Return true iff c is a color character. */ static inline bool isColor(char c) { return asc2colcat[(int)c] > 0; } /// Convert a pair of 2-bit (and 4=N) encoded DNA bases to a color extern uint8_t dinuc2color[5][5]; #endif /*ALPHABETS_H_*/ ugene-1.9.8/src/plugins_3rdparty/bowtie/src/bowtie/ebwt_search_util.cpp0000644000175000017500000000213011651544326025015 0ustar ilyailya#include "ebwt_search_util.h" #include "seqan/file.h" using namespace std; using namespace seqan; /** * Print a hit along with information about the backtracking * regions constraining the hit. */ void printHit(const vector >& os, const Hit& h, const String& qry, size_t qlen, uint32_t unrevOff, uint32_t oneRevOff, uint32_t twoRevOff, uint32_t threeRevOff, bool ebwtFw) { // Print pattern sequence cout << " Pat: " << qry << endl; // Print text sequence cout << " Tseg: "; if(ebwtFw) { for(size_t i = 0; i < qlen; i++) { cout << os[h.h.first][h.h.second + i]; } } else { for(int i = (int)qlen-1; i >= 0; i--) { cout << os[h.h.first][h.h.second + i]; } } cout << endl; cout << " Bt: "; for(int i = (int)qlen-1; i >= 0; i--) { if (i < (int)unrevOff) cout << "0"; else if(i < (int)oneRevOff) cout << "1"; else if(i < (int)twoRevOff) cout << "2"; else if(i < (int)threeRevOff) cout << "3"; else cout << "X"; } cout << endl; } ugene-1.9.8/src/plugins_3rdparty/bowtie/src/bowtie/ebwt.h0000644000175000017500000044543711651544326022125 0ustar ilyailya#ifndef EBWT_H_ #define EBWT_H_ #ifdef _CRTDBG_MAP_ALLOC //tested only on windows #define _CRTDBG_MAPALLOC #include #include #include #ifdef _DEBUG #define DEBUG_NEW new(_NORMAL_BLOCK, __FILE__, __LINE__) #define new DEBUG_NEW #endif #endif #include "u64.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #ifdef BOWTIE_MM #include #include #endif #include "auto_array.h" #include "shmem.h" #include "alphabet.h" #include "assert_helpers.h" #include "bitpack.h" #include "blockwise_sa.h" #include "endian_swap.h" #include "word_io.h" #include "random_source.h" #include "hit.h" #include "ref_read.h" #include "threading.h" #include "bitset.h" #include "str_util.h" #include "mm.h" #include "timer.h" #include "refmap.h" #include "color_dec.h" #include "reference.h" using namespace std; using namespace seqan; #ifndef PREFETCH_LOCALITY // No locality by default #define PREFETCH_LOCALITY 2 #endif // From ccnt_lut.cpp, automatically generated by gen_lookup_tables.pl extern uint8_t cCntLUT_4[4][4][256]; #ifndef VMSG_NL #define VMSG_NL(args...) \ if(this->verbose()) { \ stringstream tmp; \ tmp << args << endl; \ this->verbose(tmp.str()); \ } #endif #ifndef VMSG #define VMSG(args...) \ if(this->verbose()) { \ stringstream tmp; \ tmp << args; \ this->verbose(tmp.str()); \ } #endif /** * Flags describing type of Ebwt. */ enum EBWT_FLAGS { EBWT_COLOR = 2, // true -> Ebwt is colorspace EBWT_ENTIRE_REV = 4 // true -> reverse Ebwt is the whole // concatenated string reversed, rather than // each stretch reversed }; /** * Extended Burrows-Wheeler transform header. This together with the * actual data arrays and other text-specific parameters defined in * class Ebwt constitute the entire Ebwt. */ class EbwtParams { public: EbwtParams() { } EbwtParams(uint32_t len, int32_t lineRate, int32_t linesPerSide, int32_t offRate, int32_t isaRate, int32_t ftabChars, bool color, bool entireReverse) { init(len, lineRate, linesPerSide, offRate, isaRate, ftabChars, color, entireReverse); } EbwtParams(const EbwtParams& eh) { init(eh._len, eh._lineRate, eh._linesPerSide, eh._offRate, eh._isaRate, eh._ftabChars, eh._color, eh._entireReverse); } void init(uint32_t len, int32_t lineRate, int32_t linesPerSide, int32_t offRate, int32_t isaRate, int32_t ftabChars, bool color, bool entireReverse) { _color = color; _entireReverse = entireReverse; _len = len; _bwtLen = _len + 1; _sz = (len+3)/4; _bwtSz = (len/4 + 1); _lineRate = lineRate; _linesPerSide = linesPerSide; _origOffRate = offRate; _offRate = offRate; _offMask = 0xffffffff << _offRate; _isaRate = isaRate; _isaMask = 0xffffffff << ((_isaRate >= 0) ? _isaRate : 0); _ftabChars = ftabChars; _eftabLen = _ftabChars*2; _eftabSz = _eftabLen*4; _ftabLen = (1 << (_ftabChars*2))+1; _ftabSz = _ftabLen*4; _offsLen = (_bwtLen + (1 << _offRate) - 1) >> _offRate; _offsSz = _offsLen*4; _isaLen = (_isaRate == -1)? 0 : ((_bwtLen + (1 << _isaRate) - 1) >> _isaRate); _isaSz = _isaLen*4; _lineSz = 1 << _lineRate; _sideSz = _lineSz * _linesPerSide; _sideBwtSz = _sideSz - 8; _sideBwtLen = _sideBwtSz*4; _numSidePairs = (_bwtSz+(2*_sideBwtSz)-1)/(2*_sideBwtSz); _numSides = _numSidePairs*2; _numLines = _numSides * _linesPerSide; _ebwtTotLen = _numSidePairs * (2*_sideSz); _ebwtTotSz = _ebwtTotLen; assert(repOk()); } uint32_t len() const { return _len; } uint32_t bwtLen() const { return _bwtLen; } uint32_t sz() const { return _sz; } uint32_t bwtSz() const { return _bwtSz; } int32_t lineRate() const { return _lineRate; } int32_t linesPerSide() const { return _linesPerSide; } int32_t origOffRate() const { return _origOffRate; } int32_t offRate() const { return _offRate; } uint32_t offMask() const { return _offMask; } int32_t isaRate() const { return _isaRate; } uint32_t isaMask() const { return _isaMask; } int32_t ftabChars() const { return _ftabChars; } uint32_t eftabLen() const { return _eftabLen; } uint32_t eftabSz() const { return _eftabSz; } uint32_t ftabLen() const { return _ftabLen; } uint32_t ftabSz() const { return _ftabSz; } uint32_t offsLen() const { return _offsLen; } uint32_t offsSz() const { return _offsSz; } uint32_t isaLen() const { return _isaLen; } uint32_t isaSz() const { return _isaSz; } uint32_t lineSz() const { return _lineSz; } uint32_t sideSz() const { return _sideSz; } uint32_t sideBwtSz() const { return _sideBwtSz; } uint32_t sideBwtLen() const { return _sideBwtLen; } uint32_t numSidePairs() const { return _numSidePairs; } uint32_t numSides() const { return _numSides; } uint32_t numLines() const { return _numLines; } uint32_t ebwtTotLen() const { return _ebwtTotLen; } uint32_t ebwtTotSz() const { return _ebwtTotSz; } bool color() const { return _color; } bool entireReverse() const { return _entireReverse; } /** * Set a new suffix-array sampling rate, which involves updating * rate, mask, sample length, and sample size. */ void setOffRate(int __offRate) { _offRate = __offRate; _offMask = 0xffffffff << _offRate; _offsLen = (_bwtLen + (1 << _offRate) - 1) >> _offRate; _offsSz = _offsLen*4; } /** * Set a new inverse suffix-array sampling rate, which involves * updating rate, mask, sample length, and sample size. */ void setIsaRate(int __isaRate) { _isaRate = __isaRate; _isaMask = 0xffffffff << _isaRate; _isaLen = (_bwtLen + (1 << _isaRate) - 1) >> _isaRate; _isaSz = _isaLen*4; } /// Check that this EbwtParams is internally consistent bool repOk() const { assert_gt(_len, 0); assert_gt(_lineRate, 3); assert_geq(_offRate, 0); assert_leq(_ftabChars, 16); assert_geq(_ftabChars, 1); assert_lt(_lineRate, 32); assert_lt(_linesPerSide, 32); assert_lt(_ftabChars, 32); assert_eq(0, _ebwtTotSz % (2*_lineSz)); return true; } /** * Pretty-print the header contents to the given output stream. */ void print(ostream& out) const { return; // out << "Headers:" << endl // << " len: " << _len << endl // << " bwtLen: " << _bwtLen << endl // << " sz: " << _sz << endl // << " bwtSz: " << _bwtSz << endl // << " lineRate: " << _lineRate << endl // << " linesPerSide: " << _linesPerSide << endl // << " offRate: " << _offRate << endl // << " offMask: 0x" << hex << _offMask << dec << endl // << " isaRate: " << _isaRate << endl // << " isaMask: 0x" << hex << _isaMask << dec << endl // << " ftabChars: " << _ftabChars << endl // << " eftabLen: " << _eftabLen << endl // << " eftabSz: " << _eftabSz << endl // << " ftabLen: " << _ftabLen << endl // << " ftabSz: " << _ftabSz << endl // << " offsLen: " << _offsLen << endl // << " offsSz: " << _offsSz << endl // << " isaLen: " << _isaLen << endl // << " isaSz: " << _isaSz << endl // << " lineSz: " << _lineSz << endl // << " sideSz: " << _sideSz << endl // << " sideBwtSz: " << _sideBwtSz << endl // << " sideBwtLen: " << _sideBwtLen << endl // << " numSidePairs: " << _numSidePairs << endl // << " numSides: " << _numSides << endl // << " numLines: " << _numLines << endl // << " ebwtTotLen: " << _ebwtTotLen << endl // << " ebwtTotSz: " << _ebwtTotSz << endl // << " reverse: " << _entireReverse << endl; } uint32_t _len; uint32_t _bwtLen; uint32_t _sz; uint32_t _bwtSz; int32_t _lineRate; int32_t _linesPerSide; int32_t _origOffRate; int32_t _offRate; uint32_t _offMask; int32_t _isaRate; uint32_t _isaMask; int32_t _ftabChars; uint32_t _eftabLen; uint32_t _eftabSz; uint32_t _ftabLen; uint32_t _ftabSz; uint32_t _offsLen; uint32_t _offsSz; uint32_t _isaLen; uint32_t _isaSz; uint32_t _lineSz; uint32_t _sideSz; uint32_t _sideBwtSz; uint32_t _sideBwtLen; uint32_t _numSidePairs; uint32_t _numSides; uint32_t _numLines; uint32_t _ebwtTotLen; uint32_t _ebwtTotSz; bool _color; bool _entireReverse; }; /** * Exception to throw when a file-realted error occurs. */ class EbwtFileOpenException : public std::runtime_error { public: EbwtFileOpenException(const std::string& msg = "") : std::runtime_error(msg) { } }; /** * Calculate size of file with given name. */ static inline int64_t fileSize(const char* name) { std::ifstream f; f.open(name, std::ios_base::binary | std::ios_base::in); if (!f.good() || f.eof() || !f.is_open()) { return 0; } f.seekg(0, std::ios_base::beg); std::ifstream::pos_type begin_pos = f.tellg(); f.seekg(0, std::ios_base::end); return static_cast(f.tellg() - begin_pos); } // Forward declarations for Ebwt class class SideLocus; template class EbwtSearchParams; /** * Extended Burrows-Wheeler transform data. * * An Ebwt may be transferred to and from RAM with calls to * evictFromMemory() and loadIntoMemory(). By default, a newly-created * Ebwt is not loaded into memory; if the user would like to use a * newly-created Ebwt to answer queries, they must first call * loadIntoMemory(). */ template class Ebwt { public: typedef typename Value::Type TAlphabet; #define Ebwt_INITS \ _toBigEndian(currentlyBigEndian()), \ _overrideOffRate(__overrideOffRate), \ _overrideIsaRate(__overrideIsaRate), \ _verbose(verbose), \ _passMemExc(passMemExc), \ _sanity(sanityCheck), \ _fw(__fw), \ _in1(MM_FILE_INIT), \ _in2(MM_FILE_INIT), \ _zOff(0xffffffff), \ _zEbwtByteOff(0xffffffff), \ _zEbwtBpOff(-1), \ _nPat(0), \ _nFrag(0), \ _plen(NULL), \ _rstarts(NULL), \ _fchr(NULL), \ _ftab(NULL), \ _eftab(NULL), \ _offs(NULL), \ _isa(NULL), \ _ebwt(NULL), \ _useMm(false), \ useShmem_(false), \ _refnames(), \ rmap_(NULL), \ mmFile1_(NULL), \ mmFile2_(NULL) #ifdef EBWT_STATS #define Ebwt_STAT_INITS \ ,mapLFExs_(U64(0)), \ mapLFs_(U64(0)), \ mapLFcs_(U64(0)), \ mapLF1cs_(U64(0)), \ mapLF1s_(U64(0)) #else #define Ebwt_STAT_INITS #endif /// Construct an Ebwt from the given input file Ebwt(const string& in, int color, int needEntireReverse, bool __fw, int32_t __overrideOffRate = -1, int32_t __overrideIsaRate = -1, bool useMm = false, bool useShmem = false, bool mmSweep = false, bool loadNames = false, const ReferenceMap* rmap = NULL, bool verbose = false, bool startVerbose = false, bool passMemExc = false, bool sanityCheck = false) : Ebwt_INITS Ebwt_STAT_INITS { assert(!useMm || !useShmem); rmap_ = rmap; _useMm = useMm; useShmem_ = useShmem; _in1Str = in + ".1.ebwt"; _in2Str = in + ".2.ebwt"; readIntoMemory( color, // expect colorspace reference? __fw ? -1 : needEntireReverse, // need REF_READ_REVERSE true, // stop after loading the header portion? &_eh, // params structure to fill in mmSweep, // mmSweep loadNames, // loadNames startVerbose); // startVerbose // If the offRate has been overridden, reflect that in the // _eh._offRate field if(_overrideOffRate > _eh._offRate) { _eh.setOffRate(_overrideOffRate); assert_eq(_overrideOffRate, _eh._offRate); } // Same with isaRate if(_overrideIsaRate > _eh._isaRate) { _eh.setIsaRate(_overrideIsaRate); assert_eq(_overrideIsaRate, _eh._isaRate); } assert(repOk()); } /// Construct an Ebwt from the given header parameters and string /// vector, optionally using a blockwise suffix sorter with the /// given 'bmax' and 'dcv' parameters. The string vector is /// ultimately joined and the joined string is passed to buildToDisk(). Ebwt(int color, int32_t lineRate, int32_t linesPerSide, int32_t offRate, int32_t isaRate, int32_t ftabChars, const string& file, // base filename for EBWT files bool __fw, bool useBlockwise, uint32_t bmax, uint32_t bmaxSqrtMult, uint32_t bmaxDivN, int dcv, vector& is, vector& szs, vector& plens, uint32_t sztot, const RefReadInParams& refparams, uint32_t seed, int32_t __overrideOffRate = -1, int32_t __overrideIsaRate = -1, bool verbose = false, bool passMemExc = false, bool sanityCheck = false) : Ebwt_INITS Ebwt_STAT_INITS, _eh(joinedLen(szs), lineRate, linesPerSide, offRate, isaRate, ftabChars, color, refparams.reverse == REF_READ_REVERSE) { _in1Str = file + ".1.ebwt"; _in2Str = file + ".2.ebwt"; // Open output files ofstream fout1(_in1Str.c_str(), ios::binary); if(!fout1.good()) { cerr << "Could not open index file for writing: \"" << _in1Str << "\"" << endl << "Please make sure the directory exists and that permissions allow writing by" << endl << "Bowtie." << endl; throw 1; } ofstream fout2(_in2Str.c_str(), ios::binary); if(!fout2.good()) { cerr << "Could not open index file for writing: \"" << _in2Str << "\"" << endl << "Please make sure the directory exists and that permissions allow writing by" << endl << "Bowtie." << endl; throw 1; } // Build initFromVector( is, szs, plens, sztot, refparams, fout1, fout2, useBlockwise, bmax, bmaxSqrtMult, bmaxDivN, dcv, seed); // Close output files fout1.flush(); int64_t tellpSz1 = (int64_t)fout1.tellp(); VMSG_NL("Wrote " << fout1.tellp() << " bytes to primary EBWT file: " << _in1Str); fout1.close(); bool err = false; if(tellpSz1 > fileSize(_in1Str.c_str())) { err = true; cerr << "Index is corrupt: File size for " << _in1Str << " should have been " << tellpSz1 << " but is actually " << fileSize(_in1Str.c_str()) << "." << endl; } fout2.flush(); int64_t tellpSz2 = (int64_t)fout2.tellp(); VMSG_NL("Wrote " << fout2.tellp() << " bytes to secondary EBWT file: " << _in2Str); fout2.close(); if(tellpSz2 > fileSize(_in2Str.c_str())) { err = true; cerr << "Index is corrupt: File size for " << _in2Str << " should have been " << tellpSz2 << " but is actually " << fileSize(_in2Str.c_str()) << "." << endl; } if(err) { cerr << "Please check if there is a problem with the disk or if disk is full." << endl; throw 1; } // Reopen as input streams VMSG_NL("Re-opening _in1 and _in2 as input streams"); if(_sanity) { VMSG_NL("Sanity-checking Ebwt"); assert(!isInMemory()); readIntoMemory( color, __fw ? -1 : refparams.reverse == REF_READ_REVERSE, false, NULL, false, true, false); sanityCheckAll(refparams.reverse); evictFromMemory(); assert(!isInMemory()); } VMSG_NL("Returning from Ebwt constructor"); } bool isPacked(); /** * Write the rstarts array given the szs array for the reference. */ void szsToDisk(const vector& szs, ostream& os, int reverse) { size_t seq = 0; uint32_t off = 0; uint32_t totlen = 0; for(unsigned int i = 0; i < szs.size(); i++) { if(szs[i].len == 0) continue; if(szs[i].first) off = 0; off += szs[i].off; #ifdef ACCOUNT_FOR_ALL_GAP_REFS if(szs[i].first && szs[i].len > 0) seq++; #else if(szs[i].first) seq++; #endif size_t seqm1 = seq-1; assert_lt(seqm1, _nPat); size_t fwoff = off; if(reverse == REF_READ_REVERSE) { // Invert pattern idxs seqm1 = _nPat - seqm1 - 1; // Invert pattern idxs assert_leq(off + szs[i].len, _plen[seqm1]); fwoff = _plen[seqm1] - (off + szs[i].len); } writeU32(os, totlen, this->toBe()); // offset from beginning of joined string writeU32(os, seqm1, this->toBe()); // sequence id writeU32(os, fwoff, this->toBe()); // offset into sequence totlen += szs[i].len; off += szs[i].len; } } /** * Helper for the constructors above. Takes a vector of text * strings and joins them into a single string with a call to * joinToDisk, which does a join (with padding) and writes some of * the resulting data directly to disk rather than keep it in * memory. It then constructs a suffix-array producer (what kind * depends on 'useBlockwise') for the resulting sequence. The * suffix-array producer can then be used to obtain chunks of the * joined string's suffix array. */ void initFromVector( vector& is, vector& szs, vector& plens, uint32_t sztot, const RefReadInParams& refparams, ofstream& out1, ofstream& out2, bool useBlockwise, uint32_t bmax, uint32_t bmaxSqrtMult, uint32_t bmaxDivN, int dcv, uint32_t seed) { // Compose text strings into single string VMSG_NL("Calculating joined length"); TStr s; // holds the entire joined reference after call to joinToDisk uint32_t jlen; jlen = joinedLen(szs); assert_geq(jlen, sztot); VMSG_NL("Writing header"); writeFromMemory(true, out1, out2); try { VMSG_NL("Reserving space for joined string"); seqan::reserve(s, jlen, Exact()); VMSG_NL("Joining reference sequences"); if(refparams.reverse == REF_READ_REVERSE) { { Timer timer(cout, " Time to join reference sequences: ", _verbose); joinToDisk(is, szs, plens, sztot, refparams, s, out1, out2, seed); } { Timer timer(cout, " Time to reverse reference sequence: ", _verbose); vector tmp; reverseInPlace(s); reverseRefRecords(szs, tmp, false, false); szsToDisk(tmp, out1, refparams.reverse); } } else { Timer timer(cout, " Time to join reference sequences: ", _verbose); joinToDisk(is, szs, plens, sztot, refparams, s, out1, out2, seed); szsToDisk(szs, out1, refparams.reverse); } // Joined reference sequence now in 's' } catch(bad_alloc& e) { // If we throw an allocation exception in the try block, // that means that the joined version of the reference // string itself is too larger to fit in memory. The only // alternatives are to tell the user to give us more memory // or to try again with a packed representation of the // reference (if we haven't tried that already). cerr << "Could not allocate space for a joined string of " << jlen << " elements." << endl; if(!isPacked() && _passMemExc) { // Pass the exception up so that we can retry using a // packed string representation throw e; } // There's no point passing this exception on. The fact // that we couldn't allocate the joined string means that // --bmax is irrelevant - the user should re-run with // ebwt-build-packed if(isPacked()) { cerr << "Please try running bowtie-build on a computer with more memory." << endl; } else { cerr << "Please try running bowtie-build in packed mode (-p/--packed) or in automatic" << endl << "mode (-a/--auto), or try again on a computer with more memory." << endl; } if(sizeof(void*) == 4) { cerr << "If this computer has more than 4 GB of memory, try using a 64-bit executable;" << endl << "this executable is 32-bit." << endl; } throw 1; } // Succesfully obtained joined reference string assert_geq(length(s), jlen); if(bmax != 0xffffffff) { VMSG_NL("bmax according to bmax setting: " << bmax); } else if(bmaxSqrtMult != 0xffffffff) { bmax *= bmaxSqrtMult; VMSG_NL("bmax according to bmaxSqrtMult setting: " << bmax); } else if(bmaxDivN != 0xffffffff) { bmax = max(jlen / bmaxDivN, 1); VMSG_NL("bmax according to bmaxDivN setting: " << bmax); } else { bmax = (uint32_t)sqrt((double)length(s)); VMSG_NL("bmax defaulted to: " << bmax); } int iter = 0; bool first = true; // Look for bmax/dcv parameters that work. while(true) { if(!first && bmax < 40 && _passMemExc) { cerr << "Could not find approrpiate bmax/dcv settings for building this index." << endl; if(!isPacked()) { // Throw an exception exception so that we can // retry using a packed string representation throw bad_alloc(); } else { cerr << "Already tried a packed string representation." << endl; } cerr << "Please try indexing this reference on a computer with more memory." << endl; if(sizeof(void*) == 4) { cerr << "If this computer has more than 4 GB of memory, try using a 64-bit executable;" << endl << "this executable is 32-bit." << endl; } throw 1; } if(dcv > 4096) dcv = 4096; if((iter % 6) == 5 && dcv < 4096 && dcv != 0) { dcv <<= 1; // double difference-cover period } else { bmax -= (bmax >> 2); // reduce by 25% } VMSG("Using parameters --bmax " << bmax); if(dcv == 0) { VMSG_NL(" and *no difference cover*"); } else { VMSG_NL(" --dcv " << dcv); } iter++; try { { VMSG_NL(" Doing ahead-of-time memory usage test"); // Make a quick-and-dirty attempt to force a bad_alloc iff // we would have thrown one eventually as part of // constructing the DifferenceCoverSample dcv <<= 1; size_t sz = DifferenceCoverSample::simulateAllocs(s, dcv >> 1); AutoArray tmp(sz); dcv >>= 1; // Likewise with the KarkkainenBlockwiseSA sz = KarkkainenBlockwiseSA::simulateAllocs(s, bmax); AutoArray tmp2(sz); // Now throw in the 'ftab' and 'isaSample' structures // that we'll eventually allocate in buildToDisk AutoArray ftab(_eh._ftabLen * 2); AutoArray side(_eh._sideSz); // Grab another 20 MB out of caution AutoArray extra(20*1024*1024); // If we made it here without throwing bad_alloc, then we // passed the memory-usage stress test VMSG(" Passed! Constructing with these parameters: --bmax " << bmax << " --dcv " << dcv); if(isPacked()) { VMSG(" --packed"); } VMSG_NL(""); } VMSG_NL("Constructing suffix-array element generator"); //binary sorting into buckets KarkkainenBlockwiseSA bsa(s, bmax, dcv, seed, _sanity, _passMemExc, _verbose); assert(bsa.suffixItrIsReset()); assert_eq(bsa.size(), length(s)+1); VMSG_NL("Converting suffix-array elements to index image"); buildToDisk(bsa, s, out1, out2); out1.flush(); out2.flush(); if(out1.fail() || out2.fail()) { cerr << "An error occurred writing the index to disk. Please check if the disk is full." << endl; throw 1; } break; } catch(bad_alloc& e) { if(_passMemExc) { VMSG_NL(" Ran out of memory; automatically trying more memory-economical parameters."); } else { cerr << "Out of memory while constructing suffix array. Please try using a smaller" << endl << "number of blocks by specifying a smaller --bmax or a larger --bmaxdivn" << endl; throw 1; } } first = false; } assert(repOk()); // Now write reference sequence names on the end #ifdef ACCOUNT_FOR_ALL_GAP_REFS assert_geq(this->_refnames.size(), this->_nPat); #else assert_eq(this->_refnames.size(), this->_nPat); #endif for(size_t i = 0; i < this->_refnames.size(); i++) { out1 << this->_refnames[i] << endl; } out1 << '\0'; out1.flush(); out2.flush(); if(out1.fail() || out2.fail()) { cerr << "An error occurred writing the index to disk. Please check if the disk is full." << endl; throw 1; } VMSG_NL("Returning from initFromVector"); } /** * Return the length that the joined string of the given string * list will have. Note that this is indifferent to how the text * fragments correspond to input sequences - it just cares about * the lengths of the fragments. */ uint32_t joinedLen(vector& szs) { uint32_t ret = 0; for(unsigned int i = 0; i < szs.size(); i++) { ret += szs[i].len; } return ret; } /// Destruct an Ebwt ~Ebwt() { // Only free buffers if we're *not* using memory-mapped files if(!_useMm) { // Delete everything that was allocated in read(false, ...) if(_fchr != NULL) delete[] _fchr; _fchr = NULL; if(_ftab != NULL) delete[] _ftab; _ftab = NULL; if(_eftab != NULL) delete[] _eftab; _eftab = NULL; if(_offs != NULL && !useShmem_) { delete[] _offs; _offs = NULL; } else if(_offs != NULL && useShmem_) { FREE_SHARED(_offs); } if(_isa != NULL) delete[] _isa; _isa = NULL; if(_plen != NULL) delete[] _plen; _plen = NULL; if(_rstarts != NULL) delete[] _rstarts; _rstarts = NULL; if(_ebwt != NULL && !useShmem_) { delete[] _ebwt; _ebwt = NULL; } else if(_ebwt != NULL && useShmem_) { FREE_SHARED(_ebwt); } } MM_FILE_CLOSE(_in1); MM_FILE_CLOSE(_in2); #ifdef EBWT_STATS cout << (_fw ? "Forward index:" : "Mirror index:") << endl; cout << " mapLFEx: " << mapLFExs_ << endl; cout << " mapLF: " << mapLFs_ << endl; cout << " mapLF(c): " << mapLFcs_ << endl; cout << " mapLF1(c): " << mapLF1cs_ << endl; cout << " mapLF(c): " << mapLF1s_ << endl; #endif } /// Accessors const EbwtParams& eh() const { return _eh; } uint32_t zOff() const { return _zOff; } uint32_t zEbwtByteOff() const { return _zEbwtByteOff; } int zEbwtBpOff() const { return _zEbwtBpOff; } uint32_t nPat() const { return _nPat; } uint32_t nFrag() const { return _nFrag; } uint32_t* fchr() const { return _fchr; } uint32_t* ftab() const { return _ftab; } uint32_t* eftab() const { return _eftab; } uint32_t* offs() const { return _offs; } uint32_t* isa() const { return _isa; } uint32_t* plen() const { return _plen; } uint32_t* rstarts() const { return _rstarts; } uint8_t* ebwt() const { return _ebwt; } const ReferenceMap* rmap() const { return rmap_; } bool toBe() const { return _toBigEndian; } bool verbose() const { return _verbose; } bool sanityCheck() const { return _sanity; } vector& refnames() { return _refnames; } bool fw() const { return _fw; } /// Return true iff the Ebwt is currently in memory bool isInMemory() const { if(_ebwt != NULL) { assert(_eh.repOk()); assert(_ftab != NULL); assert(_eftab != NULL); assert(_fchr != NULL); assert(_offs != NULL); assert(_isa != NULL); assert(_rstarts != NULL); assert_neq(_zEbwtByteOff, 0xffffffff); assert_neq(_zEbwtBpOff, -1); return true; } else { assert(_ftab == NULL); assert(_eftab == NULL); assert(_fchr == NULL); assert(_offs == NULL); assert(_rstarts == NULL); assert_eq(_zEbwtByteOff, 0xffffffff); assert_eq(_zEbwtBpOff, -1); return false; } } /// Return true iff the Ebwt is currently stored on disk bool isEvicted() const { return !isInMemory(); } /** * Load this Ebwt into memory by reading it in from the _in1 and * _in2 streams. */ void loadIntoMemory( int color, int needEntireReverse, bool loadNames, bool verbose) { readIntoMemory( color, // expect index to be colorspace? needEntireReverse, // require reverse index to be concatenated reference reversed false, // stop after loading the header portion? NULL, // params false, // mmSweep loadNames, // loadNames verbose); // startVerbose } /** * Frees memory associated with the Ebwt. */ void evictFromMemory() { assert(isInMemory()); if(!_useMm) { delete[] _fchr; delete[] _ftab; delete[] _eftab; if(!useShmem_) delete[] _offs; delete[] _isa; // Keep plen; it's small and the client may want to query it // even when the others are evicted. //delete[] _plen; delete[] _rstarts; if(!useShmem_) delete[] _ebwt; } _fchr = NULL; _ftab = NULL; _eftab = NULL; _offs = NULL; _isa = NULL; // Keep plen; it's small and the client may want to query it // even when the others are evicted. //_plen = NULL; _rstarts = NULL; _ebwt = NULL; _zEbwtByteOff = 0xffffffff; _zEbwtBpOff = -1; } /** * Non-static facade for static function ftabHi. */ uint32_t ftabHi(uint32_t i) const { return Ebwt::ftabHi(_ftab, _eftab, _eh._len, _eh._ftabLen, _eh._eftabLen, i); } /** * Get "high interpretation" of ftab entry at index i. The high * interpretation of a regular ftab entry is just the entry * itself. The high interpretation of an extended entry is the * second correpsonding ui32 in the eftab. * * It's a static member because it's convenient to ask this * question before the Ebwt is fully initialized. */ static uint32_t ftabHi(uint32_t *ftab, uint32_t *eftab, uint32_t len, uint32_t ftabLen, uint32_t eftabLen, uint32_t i) { assert_lt(i, ftabLen); if(ftab[i] <= len) { return ftab[i]; } else { uint32_t efIdx = ftab[i] ^ 0xffffffff; assert_lt(efIdx*2+1, eftabLen); return eftab[efIdx*2+1]; } } /** * Non-static facade for static function ftabLo. */ uint32_t ftabLo(uint32_t i) const { return Ebwt::ftabLo(_ftab, _eftab, _eh._len, _eh._ftabLen, _eh._eftabLen, i); } /** * Get "low interpretation" of ftab entry at index i. The low * interpretation of a regular ftab entry is just the entry * itself. The low interpretation of an extended entry is the * first correpsonding ui32 in the eftab. * * It's a static member because it's convenient to ask this * question before the Ebwt is fully initialized. */ static uint32_t ftabLo(uint32_t *ftab, uint32_t *eftab, uint32_t len, uint32_t ftabLen, uint32_t eftabLen, uint32_t i) { assert_lt(i, ftabLen); if(ftab[i] <= len) { return ftab[i]; } else { uint32_t efIdx = ftab[i] ^ 0xffffffff; assert_lt(efIdx*2+1, eftabLen); return eftab[efIdx*2]; } } /** * When using read() to create an Ebwt, we have to set a couple of * additional fields in the Ebwt object that aren't part of the * parameter list and are not stored explicitly in the file. Right * now, this just involves initializing _zEbwtByteOff and * _zEbwtBpOff from _zOff. */ void postReadInit(EbwtParams& eh) { uint32_t sideNum = _zOff / eh._sideBwtLen; uint32_t sideCharOff = _zOff % eh._sideBwtLen; uint32_t sideByteOff = sideNum * eh._sideSz; _zEbwtByteOff = sideCharOff >> 2; assert_lt(_zEbwtByteOff, eh._sideBwtSz); _zEbwtBpOff = sideCharOff & 3; assert_lt(_zEbwtBpOff, 4); if((sideNum & 1) == 0) { // This is an even (backward) side _zEbwtByteOff = eh._sideBwtSz - _zEbwtByteOff - 1; _zEbwtBpOff = 3 - _zEbwtBpOff; assert_lt(_zEbwtBpOff, 4); } _zEbwtByteOff += sideByteOff; assert(repOk(eh)); // Ebwt should be fully initialized now } /** * Pretty-print the Ebwt to the given output stream. */ void print(ostream& out) const { print(out, _eh); } /** * Pretty-print the Ebwt and given EbwtParams to the given output * stream. */ void print(ostream& out, const EbwtParams& eh) const { return; // eh.print(out); // print params // out << "Ebwt (" << (isInMemory()? "memory" : "disk") << "):" << endl // << " zOff: " << _zOff << endl // << " zEbwtByteOff: " << _zEbwtByteOff << endl // << " zEbwtBpOff: " << _zEbwtBpOff << endl // << " nPat: " << _nPat << endl // << " plen: "; // if(_plen == NULL) { // out << "NULL" << endl; // } else { // out << "non-NULL, [0] = " << _plen[0] << endl; // } // out << " rstarts: "; // if(_rstarts == NULL) { // out << "NULL" << endl; // } else { // out << "non-NULL, [0] = " << _rstarts[0] << endl; // } // out << " ebwt: "; // if(_ebwt == NULL) { // out << "NULL" << endl; // } else { // out << "non-NULL, [0] = " << _ebwt[0] << endl; // } // out << " fchr: "; // if(_fchr == NULL) { // out << "NULL" << endl; // } else { // out << "non-NULL, [0] = " << _fchr[0] << endl; // } // out << " ftab: "; // if(_ftab == NULL) { // out << "NULL" << endl; // } else { // out << "non-NULL, [0] = " << _ftab[0] << endl; // } // out << " eftab: "; // if(_eftab == NULL) { // out << "NULL" << endl; // } else { // out << "non-NULL, [0] = " << _eftab[0] << endl; // } // out << " offs: "; // if(_offs == NULL) { // out << "NULL" << endl; // } else { // out << "non-NULL, [0] = " << _offs[0] << endl; // } } // Building static TStr join(vector& l, uint32_t seed); static TStr join(vector& l, vector& szs, uint32_t sztot, const RefReadInParams& refparams, uint32_t seed); void joinToDisk(vector& l, vector& szs, vector& plens, uint32_t sztot, const RefReadInParams& refparams, TStr& ret, ostream& out1, ostream& out2, uint32_t seed); void buildToDisk(InorderBlockwiseSA& sa, const TStr& s, ostream& out1, ostream& out2); // I/O void readIntoMemory(int color, int needEntireReverse, bool justHeader, EbwtParams *params, bool mmSweep, bool loadNames, bool startVerbose); void writeFromMemory(bool justHeader, ostream& out1, ostream& out2) const; void writeFromMemory(bool justHeader, const string& out1, const string& out2) const; // Sanity checking void printRangeFw(uint32_t begin, uint32_t end) const; void printRangeBw(uint32_t begin, uint32_t end) const; void sanityCheckUpToSide(int upToSide) const; void sanityCheckAll(int reverse) const; void restore(TStr& s) const; void checkOrigs(const vector >& os, bool color, bool mirror) const; // Searching and reporting void joinedToTextOff(uint32_t qlen, uint32_t off, uint32_t& tidx, uint32_t& textoff, uint32_t& tlen) const; inline bool report(const String& query, String* quals, String* name, bool color, bool colExEnds, int snpPhred, const BitPairReference* ref, const std::vector& mmui32, const std::vector& refcs, size_t numMms, uint32_t off, uint32_t top, uint32_t bot, uint32_t qlen, int stratum, uint16_t cost, uint32_t patid, uint32_t seed, const EbwtSearchParams& params) const; inline bool reportChaseOne(const String& query, String* quals, String* name, bool color, bool colExEnds, int snpPhred, const BitPairReference* ref, const std::vector& mmui32, const std::vector& refcs, size_t numMms, uint32_t i, uint32_t top, uint32_t bot, uint32_t qlen, int stratum, uint16_t cost, uint32_t patid, uint32_t seed, const EbwtSearchParams& params, SideLocus *l = NULL) const; inline bool reportReconstruct(const String& query, String* quals, String* name, String& lbuf, String& rbuf, const uint32_t *mmui32, const char* refcs, size_t numMms, uint32_t i, uint32_t top, uint32_t bot, uint32_t qlen, int stratum, const EbwtSearchParams& params, SideLocus *l = NULL) const; inline int rowL(const SideLocus& l) const; inline uint32_t countUpTo(const SideLocus& l, int c) const; inline void countUpToEx(const SideLocus& l, uint32_t* pairs) const; inline uint32_t countFwSide(const SideLocus& l, int c) const; inline void countFwSideEx(const SideLocus& l, uint32_t *pairs) const; inline uint32_t countBwSide(const SideLocus& l, int c) const; inline void countBwSideEx(const SideLocus& l, uint32_t *pairs) const; inline uint32_t mapLF(const SideLocus& l ASSERT_ONLY(, bool overrideSanity = false)) const; inline void mapLFEx(const SideLocus& l, uint32_t *pairs ASSERT_ONLY(, bool overrideSanity = false)) const; inline void mapLFEx(const SideLocus& ltop, const SideLocus& lbot, uint32_t *tops, uint32_t *bots ASSERT_ONLY(, bool overrideSanity = false)) const; inline uint32_t mapLF(const SideLocus& l, int c ASSERT_ONLY(, bool overrideSanity = false)) const; inline uint32_t mapLF1(uint32_t row, const SideLocus& l, int c ASSERT_ONLY(, bool overrideSanity = false)) const; inline int mapLF1(uint32_t& row, const SideLocus& l ASSERT_ONLY(, bool overrideSanity = false)) const; /// Check that in-memory Ebwt is internally consistent with respect /// to given EbwtParams; assert if not bool inMemoryRepOk(const EbwtParams& eh) const { assert_leq(ValueSize::VALUE, 4); assert_geq(_zEbwtBpOff, 0); assert_lt(_zEbwtBpOff, 4); assert_lt(_zEbwtByteOff, eh._ebwtTotSz); assert_lt(_zOff, eh._bwtLen); assert(_rstarts != NULL); assert_geq(_nFrag, _nPat); return true; } /// Check that in-memory Ebwt is internally consistent; assert if /// not bool inMemoryRepOk() const { return repOk(_eh); } /// Check that Ebwt is internally consistent with respect to given /// EbwtParams; assert if not bool repOk(const EbwtParams& eh) const { assert(_eh.repOk()); if(isInMemory()) { return inMemoryRepOk(eh); } return true; } /// Check that Ebwt is internally consistent; assert if not bool repOk() const { return repOk(_eh); } bool _toBigEndian; int32_t _overrideOffRate; int32_t _overrideIsaRate; bool _verbose; bool _passMemExc; bool _sanity; bool _fw; // true iff this is a forward index MM_FILE _in1; // input fd for primary index file MM_FILE _in2; // input fd for secondary index file string _in1Str; // filename for primary index file string _in2Str; // filename for secondary index file uint32_t _zOff; uint32_t _zEbwtByteOff; int _zEbwtBpOff; uint32_t _nPat; /// number of reference texts uint32_t _nFrag; /// number of fragments uint32_t* _plen; uint32_t* _rstarts; // starting offset of fragments / text indexes // _fchr, _ftab and _eftab are expected to be relatively small // (usually < 1MB, perhaps a few MB if _fchr is particularly large // - like, say, 11). For this reason, we don't bother with writing // them to disk through separate output streams; we uint32_t* _fchr; uint32_t* _ftab; uint32_t* _eftab; // "extended" entries for _ftab // _offs may be extremely large. E.g. for DNA w/ offRate=4 (one // offset every 16 rows), the total size of _offs is the same as // the total size of the input sequence uint32_t* _offs; uint32_t* _isa; // _ebwt is the Extended Burrows-Wheeler Transform itself, and thus // is at least as large as the input sequence. uint8_t* _ebwt; bool _useMm; /// use memory-mapped files to hold the index bool useShmem_; /// use shared memory to hold large parts of the index vector _refnames; /// names of the reference sequences const ReferenceMap* rmap_; /// mapping into another reference coordinate space char *mmFile1_; char *mmFile2_; EbwtParams _eh; #ifdef EBWT_STATS uint64_t mapLFExs_; uint64_t mapLFs_; uint64_t mapLFcs_; #endif private: ostream& log() const { return cout; // TODO: turn this into a parameter } /// Print a verbose message and flush (flushing is helpful for /// debugging) void verbose(const string& s) const { if(this->verbose()) { this->log() << s; this->log().flush(); } } }; /// Specialization for packed Ebwts - return true #ifdef _MSC_VER extern template #else template<> #endif bool Ebwt > >::isPacked(); /// By default, Ebwts are not packed template bool Ebwt::isPacked() { // if(template TYPE IS Ebwt>) return false; } /** * Structure encapsulating search parameters, such as whether and how * to backtrack and how to deal with multiple equally-good hits. */ template class EbwtSearchParams { public: EbwtSearchParams(HitSinkPerThread& sink, const vector >& texts, bool fw = true, bool ebwtFw = true) : _sink(sink), _texts(texts), _patid(0xffffffff), _fw(fw) { } HitSinkPerThread& sink() const { return _sink; } void setPatId(uint32_t patid) { _patid = patid; } uint32_t patId() const { return _patid; } void setFw(bool fw) { _fw = fw; } bool fw() const { return _fw; } /** * Report a hit. Returns true iff caller can call off the search. */ bool reportHit(const String& query, // read sequence String* quals, // read quality values String* name, // read name bool color, // true -> read is colorspace bool colExEnds, // true -> exclude nucleotides at extreme ends after decoding int snpPhred, // penalty for a SNP const BitPairReference* ref, // reference (= NULL if not necessary) const ReferenceMap* rmap, // map to another reference coordinate system bool ebwtFw, // whether index is forward (true) or mirror (false) const std::vector& mmui32, // mismatch list const std::vector& refcs, // reference characters size_t numMms, // # mismatches U32Pair h, // ref coords U32Pair mh, // mate's ref coords bool mfw, // mate's orientation uint16_t mlen, // mate length U32Pair a, // arrow pair uint32_t tlen, // length of text uint32_t qlen, // length of query int stratum, // alignment stratum uint16_t cost, // cost of alignment uint32_t oms, // approx. # other valid alignments uint32_t patid, uint32_t seed, uint8_t mate) const { #ifndef NDEBUG // Check that no two elements of the mms array are the same for(size_t i = 0; i < numMms; i++) { for(size_t j = i+1; j < numMms; j++) { assert_neq(mmui32[i], mmui32[j]); } } #endif // If ebwtFw is true, then 'query' and 'quals' are reversed // If _fw is false, then 'query' and 'quals' are reverse complemented assert(!color || ref != NULL); assert(quals != NULL); assert(name != NULL); assert_eq(mmui32.size(), refcs.size()); assert_leq(numMms, mmui32.size()); assert_gt(qlen, 0); Hit hit; hit.stratum = stratum; hit.cost = cost; hit.patSeq = query; hit.quals = *quals; if(!ebwtFw) { // Re-reverse the pattern and the quals back to how they // appeared in the read file ::reverseInPlace(hit.patSeq); ::reverseInPlace(hit.quals); } if(color) { hit.colSeq = hit.patSeq; hit.colQuals = hit.quals; hit.crefcs.resize(qlen, 0); // Turn the mmui32 and refcs arrays into the mm FixedBitset and // the refc vector for(size_t i = 0; i < numMms; i++) { if (ebwtFw != _fw) { // The 3' end is on the left but the mm vector encodes // mismatches w/r/t the 5' end, so we flip uint32_t off = qlen - mmui32[i] - 1; hit.cmms.set(off); hit.crefcs[off] = refcs[i]; } else { hit.cmms.set(mmui32[i]); hit.crefcs[i] = refcs[i]; } } assert(ref != NULL); char read[1024]; uint32_t rfbuf[(1024+16)/4]; ASSERT_ONLY(char rfbuf2[1024]); char qual[1024]; char ns[1024]; char cmm[1024]; char nmm[1024]; int cmms = 0; int nmms = 0; // TODO: account for indels when calculating these bounds size_t readi = 0; size_t readf = seqan::length(hit.patSeq); size_t refi = 0; size_t reff = readf + 1; bool maqRound = false; for(size_t i = 0; i < qlen + 1; i++) { if(i < qlen) { read[i] = (int)hit.patSeq[i]; qual[i] = mmPenalty(maqRound, phredCharToPhredQual(hit.quals[i])); } ASSERT_ONLY(rfbuf2[i] = ref->getBase(h.first, h.second + i)); } int offset = ref->getStretch(rfbuf, h.first, h.second, qlen + 1); char *rf = (char*)rfbuf + offset; for(size_t i = 0; i < qlen + 1; i++) { assert_eq(rf[i], rfbuf2[i]); rf[i] = (1 << rf[i]); } decodeHit( read, // ASCII colors, '0', '1', '2', '3', '.' qual, // ASCII quals, Phred+33 encoded readi, // offset of first character within 'read' to consider readf, // offset of last char (exclusive) in 'read' to consider rf, // reference sequence, as masks refi, // offset of first character within 'ref' to consider reff, // offset of last char (exclusive) in 'ref' to consider snpPhred, // penalty incurred by a SNP ns, // decoded nucleotides are appended here cmm, // where the color mismatches are in the string nmm, // where nucleotide mismatches are in the string cmms, // number of color mismatches nmms);// number of nucleotide mismatches size_t nqlen = qlen + (colExEnds ? -1 : 1); seqan::resize(hit.patSeq, nqlen); seqan::resize(hit.quals, nqlen); hit.refcs.resize(nqlen); size_t lo = colExEnds ? 1 : 0; size_t hi = colExEnds ? qlen : qlen+1; size_t destpos = 0; for(size_t i = lo; i < hi; i++, destpos++) { // Set sequence character assert_leq(ns[i], 4); assert_geq(ns[i], 0); hit.patSeq[destpos] = (Dna5)(int)ns[i]; // Set initial quality hit.quals[destpos] = '!'; // Color mismatches penalize quality if(i > 0) { if(cmm[i-1] == 'M') { if((int)hit.quals[destpos] + (int)qual[i-1] > 126) { hit.quals[destpos] = 126; } else { hit.quals[destpos] += qual[i-1]; } } else if((int)hit.colSeq[i-1] != 4) { hit.quals[destpos] -= qual[i-1]; } } if(i < qlen) { if(cmm[i] == 'M') { if((int)hit.quals[destpos] + (int)qual[i] > 126) { hit.quals[destpos] = 126; } else { hit.quals[destpos] += qual[i]; } } else if((int)hit.patSeq[i] != 4) { hit.quals[destpos] -= qual[i]; } } if(hit.quals[destpos] < '!') { hit.quals[destpos] = '!'; } if(nmm[i] != 'M') { uint32_t off = i - (colExEnds? 1:0); if(!_fw) off = nqlen - off - 1; assert_lt(off, nqlen); hit.mms.set(off); hit.refcs[off] = "ACGT"[ref->getBase(h.first, h.second+i)]; } } if(colExEnds) { // Extreme bases have been removed; that makes the // nucleotide alignment one character shorter than the // color alignment qlen--; mlen--; // It also shifts the alignment's offset up by 1 h.second++; } else { // Extreme bases are included; that makes the // nucleotide alignment one character longer than the // color alignment qlen++; mlen++; } } else { // Turn the mmui32 and refcs arrays into the mm FixedBitset and // the refc vector hit.refcs.resize(qlen, 0); for(size_t i = 0; i < numMms; i++) { if (ebwtFw != _fw) { // The 3' end is on the left but the mm vector encodes // mismatches w/r/t the 5' end, so we flip uint32_t off = qlen - mmui32[i] - 1; hit.mms.set(off); hit.refcs[off] = refcs[i]; } else { hit.mms.set(mmui32[i]); hit.refcs[mmui32[i]] = refcs[i]; } } } // Check the hit against the original text, if it's available if(_texts.size() > 0) { assert_lt(h.first, _texts.size()); FixedBitset<1024> diffs; // This type of check assumes that only mismatches are // possible. If indels are possible, then we either need // the caller to provide information about indel locations, // or we need to extend this to a more complicated check. assert_leq(h.second + qlen, length(_texts[h.first])); for(size_t i = 0; i < qlen; i++) { assert_neq(4, (int)_texts[h.first][h.second + i]); // Forward pattern appears at h if((int)hit.patSeq[i] != (int)_texts[h.first][h.second + i]) { uint32_t qoff = i; // if ebwtFw != _fw the 3' end is on on the // left end of the pattern, but the diff vector // should encode mismatches w/r/t the 5' end, // so we flip if (_fw) diffs.set(qoff); else diffs.set(qlen - qoff - 1); } } if(diffs != hit.mms) { // Oops, mismatches were not where we expected them; // print a diagnostic message before asserting cerr << "Expected " << hit.mms.str() << " mismatches, got " << diffs.str() << endl; cerr << " Pat: " << hit.patSeq << endl; cerr << " Tseg: "; for(size_t i = 0; i < qlen; i++) { cerr << _texts[h.first][h.second + i]; } cerr << endl; cerr << " mmui32: "; for(size_t i = 0; i < numMms; i++) { cerr << mmui32[i] << " "; } cerr << endl; cerr << " FW: " << _fw << endl; cerr << " Ebwt FW: " << ebwtFw << endl; } if(diffs != hit.mms) assert(false); } hit.h = h; if(rmap != NULL) rmap->map(hit.h); hit.patId = ((patid == 0xffffffff) ? _patid : patid); hit.patName = *name; hit.mh = mh; hit.fw = _fw; hit.mfw = mfw; hit.mlen = mlen; hit.oms = oms; hit.mate = mate; hit.color = color; hit.seed = seed; assert(hit.repOk()); return sink().reportHit(hit, stratum); } private: HitSinkPerThread& _sink; const vector >& _texts; // original texts, if available (if not // available, _texts.size() == 0) uint32_t _patid; // id of current read bool _fw; // current read is forward-oriented }; /** * Encapsulates a location in the bwt text in terms of the side it * occurs in and its offset within the side. */ struct SideLocus { SideLocus() : _sideByteOff(0), _sideNum(0), _charOff(0), _fw(true), _by(-1), _bp(-1) { } /** * Construct from row and other relevant information about the Ebwt. */ SideLocus(uint32_t row, const EbwtParams& ep, const uint8_t* ebwt) { initFromRow(row, ep, ebwt); } /** * Init two SideLocus objects from a top/bot pair, using the result * from one call to initFromRow to possibly avoid a second call. */ static void initFromTopBot(uint32_t top, uint32_t bot, const EbwtParams& ep, const uint8_t* ebwt, SideLocus& ltop, SideLocus& lbot) { const uint32_t sideBwtLen = ep._sideBwtLen; const uint32_t sideBwtSz = ep._sideBwtSz; assert_gt(bot, top); ltop.initFromRow(top, ep, ebwt); uint32_t spread = bot - top; if(ltop._charOff + spread < sideBwtLen) { lbot._charOff = ltop._charOff + spread; lbot._sideNum = ltop._sideNum; lbot._sideByteOff = ltop._sideByteOff; lbot._fw = ltop._fw; lbot._by = lbot._charOff >> 2; assert_lt(lbot._by, (int)sideBwtSz); if(!lbot._fw) lbot._by = sideBwtSz - lbot._by - 1; lbot._bp = lbot._charOff & 3; if(!lbot._fw) lbot._bp ^= 3; } else { lbot.initFromRow(bot, ep, ebwt); } } /** * Calculate SideLocus based on a row and other relevant * information about the shape of the Ebwt. */ void initFromRow(uint32_t row, const EbwtParams& ep, const uint8_t* ebwt) { const uint32_t sideSz = ep._sideSz; // Side length is hard-coded for now; this allows the compiler // to do clever things to accelerate / and %. _sideNum = row / 224; _charOff = row % 224; _sideByteOff = _sideNum * sideSz; assert_leq(row, ep._len); assert_leq(_sideByteOff + sideSz, ep._ebwtTotSz); #ifndef _MSC_VER #ifndef NO_PREFETCH __builtin_prefetch((const void *)(ebwt + _sideByteOff), 0 /* prepare for read */, PREFETCH_LOCALITY); #endif #endif // prefetch tjside too _fw = (_sideNum & 1) != 0; // odd-numbered sides are forward _by = _charOff >> 2; // byte within side assert_lt(_by, (int)ep._sideBwtSz); _bp = _charOff & 3; // bit-pair within byte if(!_fw) { _by = ep._sideBwtSz - _by - 1; _bp ^= 3; } } /// Return true iff this is an initialized SideLocus bool valid() { return _bp != -1; } /// Make this look like an invalid SideLocus void invalidate() { _bp = -1; } const uint8_t *side(const uint8_t* ebwt) const { return ebwt + _sideByteOff; } const uint8_t *oside(const uint8_t* ebwt) const { return ebwt + _sideByteOff + (_fw? (-128) : (128)); } uint32_t _sideByteOff; // offset of top side within ebwt[] uint32_t _sideNum; // index of side uint16_t _charOff; // character offset within side bool _fw; // side is forward or backward? int16_t _by; // byte within side (not adjusted for bw sides) int8_t _bp; // bitpair within byte (not adjusted for bw sides) }; #include "ebwt_search_backtrack.h" /////////////////////////////////////////////////////////////////////// // // Functions for printing and sanity-checking Ebwts // /////////////////////////////////////////////////////////////////////// /** * Given a range of positions in the EBWT array within the BWT portion * of a forward side, print the characters at those positions along * with a summary occ[] array. */ template void Ebwt::printRangeFw(uint32_t begin, uint32_t end) const { assert(isInMemory()); uint32_t occ[] = {0, 0, 0, 0}; assert_gt(end, begin); for(uint32_t i = begin; i < end; i++) { uint8_t by = this->_ebwt[i]; for(int j = 0; j < 4; j++) { // Unpack from lowest to highest bit pair int twoBit = unpack_2b_from_8b(by, j); occ[twoBit]++; cout << "ACGT"[twoBit]; } assert_eq(0, (occ[0] + occ[1] + occ[2] + occ[3]) & 3); } cout << ":{" << occ[0] << "," << occ[1] << "," << occ[2] << "," << occ[3] << "}" << endl; } /** * Given a range of positions in the EBWT array within the BWT portion * of a backward side, print the characters at those positions along * with a summary occ[] array. */ template void Ebwt::printRangeBw(uint32_t begin, uint32_t end) const { assert(isInMemory()); uint32_t occ[] = {0, 0, 0, 0}; assert_gt(end, begin); for(uint32_t i = end-1; i >= begin; i--) { uint8_t by = this->_ebwt[i]; for(int j = 3; j >= 0; j--) { // Unpack from lowest to highest bit pair int twoBit = unpack_2b_from_8b(by, j); occ[twoBit]++; cout << "ACGT"[twoBit]; } assert_eq(0, (occ[0] + occ[1] + occ[2] + occ[3]) & 3); if(i == 0) break; } cout << ":{" << occ[0] << "," << occ[1] << "," << occ[2] << "," << occ[3] << "}" << endl; } /** * Check that the ebwt array is internally consistent up to (and not * including) the given side index by re-counting the chars and * comparing against the embedded occ[] arrays. */ template void Ebwt::sanityCheckUpToSide(int upToSide) const { assert(isInMemory()); uint32_t occ[] = {0, 0, 0, 0}; uint32_t occ_save[] = {0, 0}; uint32_t cur = 0; // byte pointer const EbwtParams& eh = this->_eh; bool fw = false; while(cur < (upToSide * eh._sideSz)) { assert_leq(cur + eh._sideSz, eh._ebwtTotLen); for(uint32_t i = 0; i < eh._sideBwtSz; i++) { uint8_t by = this->_ebwt[cur + (fw ? i : eh._sideBwtSz-i-1)]; for(int j = 0; j < 4; j++) { // Unpack from lowest to highest bit pair int twoBit = unpack_2b_from_8b(by, fw ? j : 3-j); occ[twoBit]++; //if(_verbose) cout << "ACGT"[twoBit]; } assert_eq(0, (occ[0] + occ[1] + occ[2] + occ[3]) % 4); } assert_eq(0, (occ[0] + occ[1] + occ[2] + occ[3]) % eh._sideBwtLen); if(fw) { // Finished forward bucket; check saved [G] and [T] // against the two uint32_ts encoded here ASSERT_ONLY(uint32_t *u32ebwt = reinterpret_cast(&this->_ebwt[cur + eh._sideBwtSz])); ASSERT_ONLY(uint32_t gs = u32ebwt[0]); ASSERT_ONLY(uint32_t ts = u32ebwt[1]); assert_eq(gs, occ_save[0]); assert_eq(ts, occ_save[1]); fw = false; } else { // Finished backward bucket; check current [A] and [C] // against the two uint32_ts encoded here ASSERT_ONLY(uint32_t *u32ebwt = reinterpret_cast(&this->_ebwt[cur + eh._sideBwtSz])); ASSERT_ONLY(uint32_t as = u32ebwt[0]); ASSERT_ONLY(uint32_t cs = u32ebwt[1]); assert(as == occ[0] || as == occ[0]-1); // one 'a' is a skipped '$' and doesn't count toward occ[] assert_eq(cs, occ[1]); occ_save[0] = occ[2]; // save gs occ_save[1] = occ[3]; // save ts fw = true; } cur += eh._sideSz; } } /** * Sanity-check various pieces of the Ebwt */ template void Ebwt::sanityCheckAll(int reverse) const { const EbwtParams& eh = this->_eh; assert(isInMemory()); // Check ftab for(uint32_t i = 1; i < eh._ftabLen; i++) { assert_geq(this->ftabHi(i), this->ftabLo(i-1)); assert_geq(this->ftabLo(i), this->ftabHi(i-1)); assert_leq(this->ftabHi(i), eh._bwtLen+1); } assert_eq(this->ftabHi(eh._ftabLen-1), eh._bwtLen); // Check offs int seenLen = (eh._bwtLen + 31) >> 5; uint32_t *seen; try { seen = new uint32_t[seenLen]; // bitvector marking seen offsets } catch(bad_alloc& e) { cerr << "Out of memory allocating seen[] at " << __FILE__ << ":" << __LINE__ << endl; throw e; } memset(seen, 0, 4 * seenLen); uint32_t offsLen = eh._offsLen; for(uint32_t i = 0; i < offsLen; i++) { assert_lt(this->_offs[i], eh._bwtLen); int w = this->_offs[i] >> 5; int r = this->_offs[i] & 31; assert_eq(0, (seen[w] >> r) & 1); // shouldn't have been seen before seen[w] |= (1 << r); } delete[] seen; // Check nPat assert_gt(this->_nPat, 0); // Check plen, flen for(uint32_t i = 0; i < this->_nPat; i++) { assert_geq(this->_plen[i], 0); } // Check rstarts for(uint32_t i = 0; i < this->_nFrag-1; i++) { assert_gt(this->_rstarts[(i+1)*3], this->_rstarts[i*3]); if(reverse == REF_READ_REVERSE) { assert(this->_rstarts[(i*3)+1] >= this->_rstarts[((i+1)*3)+1]); } else { assert(this->_rstarts[(i*3)+1] <= this->_rstarts[((i+1)*3)+1]); } } // Check ebwt sanityCheckUpToSide(eh._numSides); VMSG_NL("Ebwt::sanityCheck passed"); } /////////////////////////////////////////////////////////////////////// // // Functions for searching Ebwts // /////////////////////////////////////////////////////////////////////// /** * Return the final character in row i (i.e. the i'th character in the * BWT transform). Note that the 'L' in the name of the function * stands for 'last', as in the literature. */ template inline int Ebwt::rowL(const SideLocus& l) const { // Extract and return appropriate bit-pair #ifdef SIXTY4_FORMAT return (((uint64_t*)l.side(this->_ebwt))[l._by >> 3] >> ((((l._by & 7) << 2) + l._bp) << 1)) & 3; #else return unpack_2b_from_8b(l.side(this->_ebwt)[l._by], l._bp); #endif } /** * Inline-function version of the above. This does not always seem to * be inlined */ #if 0 // Use gcc's intrinsic popcountll. I don't recommend it because it // seems to be somewhat slower than the bit-bashing pop64 routine both // on an AMD server and on an Intel workstation. On the other hand, // perhaps when the builtin is used GCC is smart enough to insert a // pop-count instruction on architectures that have one (e.g. Itanium). // For now, it's disabled. #define pop64(x) __builtin_popcountll(x) #elif 0 __declspec naked int __stdcall pop64 (uint64_t v) { static const uint64_t C55 = 0x5555555555555555ll; static const uint64_t C33 = 0x3333333333333333ll; static const uint64_t C0F = 0x0F0F0F0F0F0F0F0Fll; __asm { MOVD MM0, [ESP+4] ;v_low PUNPCKLDQ MM0, [ESP+8] ;v MOVQ MM1, MM0 ;v PSRLD MM0, 1 ;v >> 1 PAND MM0, [C55] ;(v >> 1) & 0x55555555 PSUBD MM1, MM0 ;w = v - ((v >> 1) & 0x55555555) MOVQ MM0, MM1 ;w PSRLD MM1, 2 ;w >> 2 PAND MM0, [C33] ;w & 0x33333333 PAND MM1, [C33] ;(w >> 2) & 0x33333333 PADDD MM0, MM1 ;x = (w & 0x33333333) + ; ((w >> 2) & 0x33333333) MOVQ MM1, MM0 ;x PSRLD MM0, 4 ;x >> 4 PADDD MM0, MM1 ;x + (x >> 4) PAND MM0, [C0F] ;y = (x + (x >> 4) & 0x0F0F0F0F) PXOR MM1, MM1 ;0 PSADBW (MM0, MM1) ;sum across all 8 bytes MOVD EAX, MM0 ;result in EAX per calling ; convention EMMS ;clear MMX state RET 8 ;pop 8-byte argument off stack ; and return } } #elif 0 // Use a bytewise LUT version of popcount. This is slower than the // bit-bashing pop64 routine both on an AMD server and on an Intel // workstation. It seems to be about the same speed as the GCC builtin // on Intel, and a bit faster than it on AMD. For now, it's disabled. const int popcntU8Table[256] = { 0,1,1,2,1,2,2,3,1,2,2,3,2,3,3,4,1,2,2,3,2,3,3,4,2,3,3,4,3,4,4,5, 1,2,2,3,2,3,3,4,2,3,3,4,3,4,4,5,2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6, 1,2,2,3,2,3,3,4,2,3,3,4,3,4,4,5,2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6, 2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6,3,4,4,5,4,5,5,6,4,5,5,6,5,6,6,7, 1,2,2,3,2,3,3,4,2,3,3,4,3,4,4,5,2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6, 2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6,3,4,4,5,4,5,5,6,4,5,5,6,5,6,6,7, 2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6,3,4,4,5,4,5,5,6,4,5,5,6,5,6,6,7, 3,4,4,5,4,5,5,6,4,5,5,6,5,6,6,7,4,5,5,6,5,6,6,7,5,6,6,7,6,7,7,8 }; // Use this bytewise population count table inline static int pop64(uint64_t x) { const unsigned char * p = (const unsigned char *) &x; return popcntU8Table[p[0]] + popcntU8Table[p[1]] + popcntU8Table[p[2]] + popcntU8Table[p[3]] + popcntU8Table[p[4]] + popcntU8Table[p[5]] + popcntU8Table[p[6]] + popcntU8Table[p[7]]; } #else // Use this standard bit-bashing population count inline static int pop64(uint64_t x) { x = x - ((x >> 1) & U64(0x5555555555555555)); x = (x & U64(0x3333333333333333)) + ((x >> 2) & U64(0x3333333333333333)); x = (x + (x >> 4)) & U64(0x0F0F0F0F0F0F0F0F); x = x + (x >> 8); x = x + (x >> 16); x = x + (x >> 32); return x & 0x3F; } #endif /** * Tricky-bit-bashing bitpair counting for given two-bit value (0-3) * within a 64-bit argument. */ inline static int countInU64(int c, uint64_t dw) { uint64_t dwA = dw & U64(0xAAAAAAAAAAAAAAAA); uint64_t dwNA = dw & U64(~0xAAAAAAAAAAAAAAAA); uint64_t tmp; switch(c) { case 0: tmp = (dwA >> 1) | dwNA; break; case 1: tmp = ~(dwA >> 1) & dwNA; break; case 2: tmp = (dwA >> 1) & ~dwNA; break; case 3: tmp = (dwA >> 1) & dwNA; break; default: throw; } tmp = pop64(tmp); // Gets 7.62% in profile if(c == 0) { tmp = 32 - tmp; } assert_leq(tmp, 32); assert_geq(tmp, 0); return (int)tmp; } /** * Tricky-bit-bashing bitpair counting for given two-bit value (0-3) * within a 64-bit argument. * * Function gets 2.32% in profile */ inline static void countInU64Ex(uint64_t dw, uint32_t* arrs) { uint64_t dwA = dw & U64(0xAAAAAAAAAAAAAAAA); uint64_t dwNA = dw & U64(~0xAAAAAAAAAAAAAAAA); arrs[0] += (32 - pop64((dwA >> 1) | dwNA)); arrs[1] += pop64(~(dwA >> 1) & dwNA); arrs[2] += pop64((dwA >> 1) & ~dwNA); arrs[3] += pop64((dwA >> 1) & dwNA); } /** * Counts the number of occurrences of character 'c' in the given Ebwt * side up to (but not including) the given byte/bitpair (by/bp). * * This is a performance-critical function. This is the top search- * related hit in the time profile. * * Function gets 11.09% in profile */ template inline uint32_t Ebwt::countUpTo(const SideLocus& l, int c) const { // Count occurrences of c in each 64-bit (using bit trickery); // Someday countInU64() and pop() functions should be // vectorized/SSE-ized in case that helps. uint32_t cCnt = 0; const uint8_t *side = l.side(this->_ebwt); int i = 0; #if 1 for(; i + 7 < l._by; i += 8) { cCnt += countInU64(c, *(uint64_t*)&side[i]); } #else for(; i + 2 < l._by; i += 2) { cCnt += cCntLUT_16b_4[c][*(uint16_t*)&side[i]]; } #endif #ifdef SIXTY4_FORMAT // Calculate number of bit pairs to shift off the end const int bpShiftoff = 32 - (((l._by & 7) << 2) + l._bp); if(bpShiftoff < 32) { assert_lt(bpShiftoff, 32); const uint64_t sw = (*(uint64_t*)&side[i]) << (bpShiftoff << 1); cCnt += countInU64(c, sw); if(c == 0) cCnt -= bpShiftoff; // we turned these into As } #else // Count occurences of c in the rest of the side (using LUT) for(; i < l._by; i++) { cCnt += cCntLUT_4[0][c][side[i]]; } // Count occurences of c in the rest of the byte if(l._bp > 0) { cCnt += cCntLUT_4[(int)l._bp][c][side[i]]; } #endif return cCnt; } /** * Counts the number of occurrences of character 'c' in the given Ebwt * side up to (but not including) the given byte/bitpair (by/bp). */ template inline void Ebwt::countUpToEx(const SideLocus& l, uint32_t* arrs) const { int i = 0; // Count occurrences of c in each 64-bit (using bit trickery); // note: this seems does not seem to lend a significant boost to // performance. If you comment out this whole loop (which won't // affect correctness - it will just cause the following loop to // take up the slack) then runtime does not change noticeably. // Someday the countInU64() and pop() functions should be // vectorized/SSE-ized in case that helps. const uint8_t *side = l.side(this->_ebwt); for(; i+7 < l._by; i += 8) { countInU64Ex(*(uint64_t*)&side[i], arrs); } #ifdef SIXTY4_FORMAT // Calculate number of bit pairs to shift off the end const int bpShiftoff = 32 - (((l._by & 7) << 2) + l._bp); assert_leq(bpShiftoff, 32); if(bpShiftoff < 32) { const uint64_t sw = (*(uint64_t*)&l.side(this->_ebwt)[i]) << (bpShiftoff << 1); countInU64Ex(sw, arrs); arrs[0] -= bpShiftoff; } #else // Count occurences of c in the rest of the side (using LUT) for(; i < l._by; i++) { arrs[0] += cCntLUT_4[0][0][side[i]]; arrs[1] += cCntLUT_4[0][1][side[i]]; arrs[2] += cCntLUT_4[0][2][side[i]]; arrs[3] += cCntLUT_4[0][3][side[i]]; } // Count occurences of c in the rest of the byte if(l._bp > 0) { arrs[0] += cCntLUT_4[(int)l._bp][0][side[i]]; arrs[1] += cCntLUT_4[(int)l._bp][1][side[i]]; arrs[2] += cCntLUT_4[(int)l._bp][2][side[i]]; arrs[3] += cCntLUT_4[(int)l._bp][3][side[i]]; } #endif } /** * Count all occurrences of character c from the beginning of the * forward side to and add in the occ[] count up to the side * break just prior to the side. */ template inline uint32_t Ebwt::countFwSide(const SideLocus& l, int c) const { assert_lt(c, 4); assert_geq(c, 0); assert_lt(l._by, (int)this->_eh._sideBwtSz); assert_geq(l._by, 0); assert_lt(l._bp, 4); assert_geq(l._bp, 0); const uint8_t *side = l.side(this->_ebwt); uint32_t cCnt = countUpTo(l, c); assert_leq(cCnt, this->_eh._sideBwtLen); if(c == 0 && l._sideByteOff <= _zEbwtByteOff && l._sideByteOff + l._by >= _zEbwtByteOff) { // Adjust for the fact that we represented $ with an 'A', but // shouldn't count it as an 'A' here if((l._sideByteOff + l._by > _zEbwtByteOff) || (l._sideByteOff + l._by == _zEbwtByteOff && l._bp > _zEbwtBpOff)) { cCnt--; // Adjust for '$' looking like an 'A' } } uint32_t ret; // Now factor in the occ[] count at the side break if(c < 2) { const uint32_t *ac = reinterpret_cast(side - 8); assert_leq(ac[0], this->_eh._numSides * this->_eh._sideBwtLen); // b/c it's used as padding assert_leq(ac[1], this->_eh._len); ret = ac[c] + cCnt + this->_fchr[c]; } else { const uint32_t *gt = reinterpret_cast(side + this->_eh._sideSz - 8); // next assert_leq(gt[0], this->_eh._len); assert_leq(gt[1], this->_eh._len); ret = gt[c-2] + cCnt + this->_fchr[c]; } #ifndef NDEBUG assert_leq(ret, this->_fchr[c+1]); // can't have jumpded into next char's section if(c == 0) { assert_leq(cCnt, this->_eh._sideBwtLen); } else { assert_leq(ret, this->_eh._bwtLen); } #endif return ret; } /** * Count all occurrences of character c from the beginning of the * forward side to and add in the occ[] count up to the side * break just prior to the side. */ template inline void Ebwt::countFwSideEx(const SideLocus& l, uint32_t* arrs) const { assert_lt(l._by, (int)this->_eh._sideBwtSz); assert_geq(l._by, 0); assert_lt(l._bp, 4); assert_geq(l._bp, 0); countUpToEx(l, arrs); #ifndef NDEBUG assert_leq(arrs[0], this->_fchr[1]); // can't have jumped into next char's section assert_leq(arrs[1], this->_fchr[2]); // can't have jumped into next char's section assert_leq(arrs[2], this->_fchr[3]); // can't have jumped into next char's section assert_leq(arrs[3], this->_fchr[4]); // can't have jumped into next char's section #endif assert_leq(arrs[0], this->_eh._sideBwtLen); assert_leq(arrs[1], this->_eh._sideBwtLen); assert_leq(arrs[2], this->_eh._sideBwtLen); assert_leq(arrs[3], this->_eh._sideBwtLen); const uint8_t *side = l.side(this->_ebwt); if(l._sideByteOff <= _zEbwtByteOff && l._sideByteOff + l._by >= _zEbwtByteOff) { // Adjust for the fact that we represented $ with an 'A', but // shouldn't count it as an 'A' here if((l._sideByteOff + l._by > _zEbwtByteOff) || (l._sideByteOff + l._by == _zEbwtByteOff && l._bp > _zEbwtBpOff)) { arrs[0]--; // Adjust for '$' looking like an 'A' } } // Now factor in the occ[] count at the side break const uint32_t *ac = reinterpret_cast(side - 8); const uint32_t *gt = reinterpret_cast(side + this->_eh._sideSz - 8); #ifndef NDEBUG assert_leq(ac[0], this->_fchr[1] + this->_eh.sideBwtLen()); assert_leq(ac[1], this->_fchr[2]-this->_fchr[1]); assert_leq(gt[0], this->_fchr[3]-this->_fchr[2]); assert_leq(gt[1], this->_fchr[4]-this->_fchr[3]); #endif assert_leq(ac[0], this->_eh._len + this->_eh.sideBwtLen()); assert_leq(ac[1], this->_eh._len); assert_leq(gt[0], this->_eh._len); assert_leq(gt[1], this->_eh._len); arrs[0] += (ac[0] + this->_fchr[0]); arrs[1] += (ac[1] + this->_fchr[1]); arrs[2] += (gt[0] + this->_fchr[2]); arrs[3] += (gt[1] + this->_fchr[3]); #ifndef NDEBUG assert_leq(arrs[0], this->_fchr[1]); // can't have jumpded into next char's section assert_leq(arrs[1], this->_fchr[2]); // can't have jumpded into next char's section assert_leq(arrs[2], this->_fchr[3]); // can't have jumpded into next char's section assert_leq(arrs[3], this->_fchr[4]); // can't have jumpded into next char's section #endif } /** * Count all instances of character c from to the logical end * (actual beginning) of the backward side, and subtract that from the * occ[] count up to the side break. */ template inline uint32_t Ebwt::countBwSide(const SideLocus& l, int c) const { assert_lt(c, 4); assert_geq(c, 0); assert_lt(l._by, (int)this->_eh._sideBwtSz); assert_geq(l._by, 0); assert_lt(l._bp, 4); assert_geq(l._bp, 0); const uint8_t *side = l.side(this->_ebwt); uint32_t cCnt = countUpTo(l, c); if(rowL(l) == c) cCnt++; assert_leq(cCnt, this->_eh._sideBwtLen); if(c == 0 && l._sideByteOff <= _zEbwtByteOff && l._sideByteOff + l._by >= _zEbwtByteOff) { // Adjust for the fact that we represented $ with an 'A', but // shouldn't count it as an 'A' here if((l._sideByteOff + l._by > _zEbwtByteOff) || (l._sideByteOff + l._by == _zEbwtByteOff && l._bp >= _zEbwtBpOff)) { cCnt--; } } uint32_t ret; // Now factor in the occ[] count at the side break if(c < 2) { const uint32_t *ac = reinterpret_cast(side + this->_eh._sideSz - 8); assert_leq(ac[0], this->_eh._numSides * this->_eh._sideBwtLen); // b/c it's used as padding assert_leq(ac[1], this->_eh._len); ret = ac[c] - cCnt + this->_fchr[c]; } else { const uint32_t *gt = reinterpret_cast(side + (2*this->_eh._sideSz) - 8); // next assert_leq(gt[0], this->_eh._len); assert_leq(gt[1], this->_eh._len); ret = gt[c-2] - cCnt + this->_fchr[c]; } #ifndef NDEBUG assert_leq(ret, this->_fchr[c+1]); // can't have jumped into next char's section if(c == 0) { assert_leq(cCnt, this->_eh._sideBwtLen); } else { assert_lt(ret, this->_eh._bwtLen); } #endif return ret; } /** * Count all instances of character c from to the logical end * (actual beginning) of the backward side, and subtract that from the * occ[] count up to the side break. */ template inline void Ebwt::countBwSideEx(const SideLocus& l, uint32_t* arrs) const { assert_lt(l._by, (int)this->_eh._sideBwtSz); assert_geq(l._by, 0); assert_lt(l._bp, 4); assert_geq(l._bp, 0); const uint8_t *side = l.side(this->_ebwt); countUpToEx(l, arrs); arrs[rowL(l)]++; assert_leq(arrs[0], this->_eh._sideBwtLen); assert_leq(arrs[1], this->_eh._sideBwtLen); assert_leq(arrs[2], this->_eh._sideBwtLen); assert_leq(arrs[3], this->_eh._sideBwtLen); if(l._sideByteOff <= _zEbwtByteOff && l._sideByteOff + l._by >= _zEbwtByteOff) { // Adjust for the fact that we represented $ with an 'A', but // shouldn't count it as an 'A' here if((l._sideByteOff + l._by > _zEbwtByteOff) || (l._sideByteOff + l._by == _zEbwtByteOff && l._bp >= _zEbwtBpOff)) { arrs[0]--; // Adjust for '$' looking like an 'A' } } // Now factor in the occ[] count at the side break const uint32_t *ac = reinterpret_cast(side + this->_eh._sideSz - 8); const uint32_t *gt = reinterpret_cast(side + (2*this->_eh._sideSz) - 8); #ifndef NDEBUG assert_leq(ac[0], this->_fchr[1] + this->_eh.sideBwtLen()); assert_leq(ac[1], this->_fchr[2]-this->_fchr[1]); assert_leq(gt[0], this->_fchr[3]-this->_fchr[2]); assert_leq(gt[1], this->_fchr[4]-this->_fchr[3]); #endif assert_leq(ac[0], this->_eh._len + this->_eh.sideBwtLen()); assert_leq(ac[1], this->_eh._len); assert_leq(gt[0], this->_eh._len); assert_leq(gt[1], this->_eh._len); arrs[0] = (ac[0] - arrs[0] + this->_fchr[0]); arrs[1] = (ac[1] - arrs[1] + this->_fchr[1]); arrs[2] = (gt[0] - arrs[2] + this->_fchr[2]); arrs[3] = (gt[1] - arrs[3] + this->_fchr[3]); #ifndef NDEBUG assert_leq(arrs[0], this->_fchr[1]); // can't have jumped into next char's section assert_leq(arrs[1], this->_fchr[2]); // can't have jumped into next char's section assert_leq(arrs[2], this->_fchr[3]); // can't have jumped into next char's section assert_leq(arrs[3], this->_fchr[4]); // can't have jumped into next char's section #endif } /** * Given top and bot loci, calculate counts of all four DNA chars up to * those loci. Used for more advanced backtracking-search. */ template inline void Ebwt::mapLFEx(const SideLocus& ltop, const SideLocus& lbot, uint32_t *tops, uint32_t *bots ASSERT_ONLY(, bool overrideSanity) ) const { // TODO: Where there's overlap, reuse the count for the overlapping // portion #ifdef EBWT_STATS const_cast*>(this)->mapLFExs_++; #endif assert_eq(0, tops[0]); assert_eq(0, bots[0]); assert_eq(0, tops[1]); assert_eq(0, bots[1]); assert_eq(0, tops[2]); assert_eq(0, bots[2]); assert_eq(0, tops[3]); assert_eq(0, bots[3]); if(ltop._fw) countFwSideEx(ltop, tops); // Forward side else countBwSideEx(ltop, tops); // Backward side if(lbot._fw) countFwSideEx(lbot, bots); // Forward side else countBwSideEx(lbot, bots); // Backward side #ifndef NDEBUG if(_sanity && !overrideSanity) { // Make sure results match up with individual calls to mapLF; // be sure to override sanity-checking in the callee, or we'll // have infinite recursion assert_eq(mapLF(ltop, 0, true), tops[0]); assert_eq(mapLF(ltop, 1, true), tops[1]); assert_eq(mapLF(ltop, 2, true), tops[2]); assert_eq(mapLF(ltop, 3, true), tops[3]); assert_eq(mapLF(lbot, 0, true), bots[0]); assert_eq(mapLF(lbot, 1, true), bots[1]); assert_eq(mapLF(lbot, 2, true), bots[2]); assert_eq(mapLF(lbot, 3, true), bots[3]); } #endif } #ifndef NDEBUG /** * Given top and bot loci, calculate counts of all four DNA chars up to * those loci. Used for more advanced backtracking-search. */ template inline void Ebwt::mapLFEx(const SideLocus& l, uint32_t *arrs ASSERT_ONLY(, bool overrideSanity) ) const { assert_eq(0, arrs[0]); assert_eq(0, arrs[1]); assert_eq(0, arrs[2]); assert_eq(0, arrs[3]); if(l._fw) countFwSideEx(l, arrs); // Forward side else countBwSideEx(l, arrs); // Backward side #ifndef NDEBUG if(_sanity && !overrideSanity) { // Make sure results match up with individual calls to mapLF; // be sure to override sanity-checking in the callee, or we'll // have infinite recursion assert_eq(mapLF(l, 0, true), arrs[0]); assert_eq(mapLF(l, 1, true), arrs[1]); assert_eq(mapLF(l, 2, true), arrs[2]); assert_eq(mapLF(l, 3, true), arrs[3]); } #endif } #endif /** * Given row i, return the row that the LF mapping maps i to. */ template inline uint32_t Ebwt::mapLF(const SideLocus& l ASSERT_ONLY(, bool overrideSanity) ) const { #ifdef EBWT_STATS const_cast*>(this)->mapLFs_++; #endif uint32_t ret; assert(l.side(this->_ebwt) != NULL); int c = rowL(l); assert_lt(c, 4); assert_geq(c, 0); if(l._fw) ret = countFwSide(l, c); // Forward side else ret = countBwSide(l, c); // Backward side assert_lt(ret, this->_eh._bwtLen); #ifndef NDEBUG if(_sanity && !overrideSanity) { // Make sure results match up with results from mapLFEx; // be sure to override sanity-checking in the callee, or we'll // have infinite recursion uint32_t arrs[] = { 0, 0, 0, 0 }; mapLFEx(l, arrs, true); assert_eq(arrs[c], ret); } #endif return ret; } /** * Given row i and character c, return the row that the LF mapping maps * i to on character c. */ template inline uint32_t Ebwt::mapLF(const SideLocus& l, int c ASSERT_ONLY(, bool overrideSanity) ) const { #ifdef EBWT_STATS const_cast*>(this)->mapLFcs_++; #endif uint32_t ret; assert_lt(c, 4); assert_geq(c, 0); if(l._fw) ret = countFwSide(l, c); // Forward side else ret = countBwSide(l, c); // Backward side assert_lt(ret, this->_eh._bwtLen); #ifndef NDEBUG if(_sanity && !overrideSanity) { // Make sure results match up with results from mapLFEx; // be sure to override sanity-checking in the callee, or we'll // have infinite recursion uint32_t arrs[] = { 0, 0, 0, 0 }; mapLFEx(l, arrs, true); assert_eq(arrs[c], ret); } #endif return ret; } /** * Given row i and character c, return the row that the LF mapping maps * i to on character c. */ template inline uint32_t Ebwt::mapLF1(uint32_t row, const SideLocus& l, int c ASSERT_ONLY(, bool overrideSanity) ) const { #ifdef EBWT_STATS const_cast*>(this)->mapLF1cs_++; #endif if(rowL(l) != c || row == _zOff) return 0xffffffff; uint32_t ret; assert_lt(c, 4); assert_geq(c, 0); if(l._fw) ret = countFwSide(l, c); // Forward side else ret = countBwSide(l, c); // Backward side assert_lt(ret, this->_eh._bwtLen); #ifndef NDEBUG if(_sanity && !overrideSanity) { // Make sure results match up with results from mapLFEx; // be sure to override sanity-checking in the callee, or we'll // have infinite recursion uint32_t arrs[] = { 0, 0, 0, 0 }; mapLFEx(l, arrs, true); assert_eq(arrs[c], ret); } #endif return ret; } /** * Given row i and character c, return the row that the LF mapping maps * i to on character c. */ template inline int Ebwt::mapLF1(uint32_t& row, const SideLocus& l ASSERT_ONLY(, bool overrideSanity) ) const { #ifdef EBWT_STATS const_cast*>(this)->mapLF1s_++; #endif if(row == _zOff) return -1; int c = rowL(l); assert_lt(c, 4); assert_geq(c, 0); if(l._fw) row = countFwSide(l, c); // Forward side else row = countBwSide(l, c); // Backward side assert_lt(row, this->_eh._bwtLen); #ifndef NDEBUG if(_sanity && !overrideSanity) { // Make sure results match up with results from mapLFEx; // be sure to override sanity-checking in the callee, or we'll // have infinite recursion uint32_t arrs[] = { 0, 0, 0, 0 }; mapLFEx(l, arrs, true); assert_eq(arrs[c], row); } #endif return c; } /** * Take an offset into the joined text and translate it into the * reference of the index it falls on, the offset into the reference, * and the length of the reference. Use a binary search through the * sorted list of reference fragment ranges t */ template void Ebwt::joinedToTextOff(uint32_t qlen, uint32_t off, uint32_t& tidx, uint32_t& textoff, uint32_t& tlen) const { uint32_t top = 0; uint32_t bot = _nFrag; // 1 greater than largest addressable element uint32_t elt = 0xffffffff; // Begin binary search while(true) { ASSERT_ONLY(uint32_t oldelt = elt); elt = top + ((bot - top) >> 1); assert_neq(oldelt, elt); // must have made progress uint32_t lower = _rstarts[elt*3]; uint32_t upper; if(elt == _nFrag-1) { upper = _eh._len; } else { upper = _rstarts[((elt+1)*3)]; } assert_gt(upper, lower); uint32_t fraglen = upper - lower; if(lower <= off) { if(upper > off) { // not last element, but it's within // off is in this range; check if it falls off if(off + qlen > upper) { // it falls off; signal no-go and return tidx = 0xffffffff; assert_lt(elt, _nFrag-1); return; } tidx = _rstarts[(elt*3)+1]; assert_lt(tidx, this->_nPat); assert_leq(fraglen, this->_plen[tidx]); // it doesn't fall off; now calculate textoff. // Initially it's the number of characters that precede // the alignment in the fragment uint32_t fragoff = off - _rstarts[(elt*3)]; if(!this->_fw) { fragoff = fraglen - fragoff - 1; fragoff -= (qlen-1); } // Add the alignment's offset into the fragment // ('fragoff') to the fragment's offset within the text textoff = fragoff + _rstarts[(elt*3)+2]; assert_lt(textoff, this->_plen[tidx]); break; // done with binary search } else { // 'off' belongs somewhere in the region between elt // and bot top = elt; } } else { // 'off' belongs somewhere in the region between top and // elt bot = elt; } // continue with binary search } tlen = this->_plen[tidx]; } /** * Report a potential match at offset 'off' with pattern length * 'qlen'. Filter out spurious matches that span texts. */ template inline bool Ebwt::report(const String& query, String* quals, String* name, bool color, bool colExEnds, int snpPhred, const BitPairReference* ref, const std::vector& mmui32, const std::vector& refcs, size_t numMms, uint32_t off, uint32_t top, uint32_t bot, uint32_t qlen, int stratum, uint16_t cost, uint32_t patid, uint32_t seed, const EbwtSearchParams& params) const { VMSG_NL("In report"); assert_geq(cost, (uint32_t)(stratum << 14)); assert_lt(off, this->_eh._len); uint32_t tidx; uint32_t textoff; uint32_t tlen; joinedToTextOff(qlen, off, tidx, textoff, tlen); if(tidx == 0xffffffff) { return false; } return params.reportHit( query, // read sequence quals, // read quality values name, // read name color, // true -> read is colorspace colExEnds, // true -> exclude nucleotides on ends snpPhred, // phred probability of SNP ref, // reference sequence rmap_, // map to another reference coordinate system _fw, // true = index is forward; false = mirror mmui32, // mismatch positions refcs, // reference characters for mms numMms, // # mismatches make_pair(tidx, textoff), // position make_pair(0, 0), // (bogus) mate position true, // (bogus) mate orientation 0, // (bogus) mate length make_pair(top, bot), // arrows tlen, // textlen qlen, // qlen stratum, // alignment stratum cost, // cost, including stratum & quality penalty bot-top-1, // # other hits patid, // pattern id seed, // pseudo-random seed 0); // mate (0 = unpaired) } #include "row_chaser.h" /** * Report a result. Involves walking backwards along the original * string by way of the LF-mapping until we reach a marked SA row or * the row corresponding to the 0th suffix. A marked row's offset * into the original string can be read directly from the this->_offs[] * array. */ template inline bool Ebwt::reportChaseOne(const String& query, String* quals, String* name, bool color, bool colExEnds, int snpPhred, const BitPairReference* ref, const std::vector& mmui32, const std::vector& refcs, size_t numMms, uint32_t i, uint32_t top, uint32_t bot, uint32_t qlen, int stratum, uint16_t cost, uint32_t patid, uint32_t seed, const EbwtSearchParams& params, SideLocus *l) const { VMSG_NL("In reportChaseOne"); uint32_t off; uint32_t jumps = 0; ASSERT_ONLY(uint32_t origi = i); SideLocus myl; const uint32_t offMask = this->_eh._offMask; const uint32_t offRate = this->_eh._offRate; const uint32_t* offs = this->_offs; // If the caller didn't give us a pre-calculated (and prefetched) // locus, then we have to do that now if(l == NULL) { l = &myl; l->initFromRow(i, this->_eh, this->_ebwt); } assert(l != NULL); assert(l->valid()); // Walk along until we reach the next marked row to the left while(((i & offMask) != i) && i != _zOff) { // Not a marked row; walk left one more char uint32_t newi = mapLF(*l); // calc next row assert_neq(newi, i); i = newi; // update row l->initFromRow(i, this->_eh, this->_ebwt); // update locus jumps++; } // This is a marked row if(i == _zOff) { // Special case: it's the row corresponding to the // lexicographically smallest suffix, which is implicitly // marked 0 off = jumps; VMSG_NL("reportChaseOne found zoff off=" << off << " (jumps=" << jumps << ")"); } else { // Normal marked row, calculate offset of row i off = offs[i >> offRate] + jumps; VMSG_NL("reportChaseOne found off=" << off << " (jumps=" << jumps << ")"); } #ifndef NDEBUG { uint32_t rcoff = RowChaser::toFlatRefOff(this, qlen, origi); assert_eq(rcoff, off); } #endif return report(query, quals, name, color, colExEnds, snpPhred, ref, mmui32, refcs, numMms, off, top, bot, qlen, stratum, cost, patid, seed, params); } /** * Report a result. Involves walking backwards along the original * string by way of the LF-mapping until we reach a marked SA row or * the row corresponding to the 0th suffix. A marked row's offset * into the original string can be read directly from the this->_offs[] * array. */ template inline bool Ebwt::reportReconstruct(const String& query, String* quals, String* name, String& lbuf, String& rbuf, const uint32_t *mmui32, const char* refcs, size_t numMms, uint32_t i, uint32_t top, uint32_t bot, uint32_t qlen, int stratum, const EbwtSearchParams& params, SideLocus *l) const { VMSG_NL("In reportReconstruct"); assert_gt(_eh._isaLen, 0); // Must have inverse suffix array to reconstruct uint32_t off; uint32_t jumps = 0; SideLocus myl; const uint32_t offMask = this->_eh._offMask; const uint32_t offRate = this->_eh._offRate; const uint32_t* offs = this->_offs; const uint32_t* isa = this->_isa; assert(isa != NULL); if(l == NULL) { l = &myl; myl.initFromRow(i, this->_eh, this->_ebwt); } assert(l != NULL); clear(lbuf); clear(rbuf); // Walk along until we reach the next marked row to the left while(((i & offMask) != i) && i != _zOff) { // Not a marked row; walk left one more char int c = rowL(*l); appendValue(lbuf, (Dna5)c); uint32_t newi; assert_lt(c, 4); assert_geq(c, 0); if(l->_fw) newi = countFwSide(*l, c); // Forward side else newi = countBwSide(*l, c); // Backward side assert_lt(newi, this->_eh._bwtLen); assert_neq(newi, i); i = newi; // update row l->initFromRow(i, this->_eh, this->_ebwt); // update locus jumps++; } // This is a marked row if(i == _zOff) { // Special case: it's the row corresponding to the // lexicographically smallest suffix, which is implicitly // marked 0 off = jumps; VMSG_NL("reportChaseOne found zoff off=" << off << " (jumps=" << jumps << ")"); } else { // Normal marked row, calculate offset of row i off = offs[i >> offRate] + jumps; VMSG_NL("reportChaseOne found off=" << off << " (jumps=" << jumps << ")"); } // 'off' now holds the text offset of the first (leftmost) position // involved in the alignment. Next we call joinedToTextOff to // check whether the seed is valid (i.e., does not straddle a // boundary between two reference seuqences) and to obtain its // extents uint32_t tidx; // the index (id) of the reference we hit in uint32_t textoff; // the offset of the alignment within the reference uint32_t tlen; // length of reference seed hit in joinedToTextOff(qlen, off, tidx, textoff, tlen); if(tidx == 0xffffffff) { // The seed straddled a reference boundary, and so is spurious. // Return false, indicating that we shouldn't stop. return false; } if(jumps > textoff) { // In our progress toward a marked row, we passed the boundary // between the reference sequence containing the seed and the // reference sequence to the left of it. That's OK, we just // need to knock off the extra characters we added to 'lbuf'. assert_eq(jumps, length(lbuf)); _setLength(lbuf, textoff); jumps = textoff; assert_eq(textoff, length(lbuf)); } else if(jumps < textoff) { // Keep walking until we reach the end of the reference assert_neq(i, _zOff); uint32_t diff = textoff-jumps; for(size_t j = 0; j < diff; j++) { // Not a marked row; walk left one more char int c = rowL(*l); appendValue(lbuf, (Dna5)c); uint32_t newi; assert_lt(c, 4); assert_geq(c, 0); if(l->_fw) newi = countFwSide(*l, c); // Forward side else newi = countBwSide(*l, c); // Backward side assert_lt(newi, this->_eh._bwtLen); assert_neq(newi, i); i = newi; // update row assert_neq(i, _zOff); l->initFromRow(i, this->_eh, this->_ebwt); // update locus jumps++; } assert_eq(textoff, jumps); assert_eq(textoff, length(lbuf)); } assert_eq(textoff, jumps); assert_eq(textoff, length(lbuf)); // Calculate the right-hand extent of the reference uint32_t ref_right = off - textoff + tlen; // Round the right-hand extent to the nearest ISA element that maps // to it or a character to its right uint32_t ref_right_rounded = ref_right; if((ref_right_rounded & _eh._isaMask) != ref_right_rounded) { ref_right_rounded = ((ref_right_rounded >> _eh._isaRate)+1) << _eh._isaRate; } // TODO: handle case where ref_right_rounded is off the end of _isa // Let the current suffix-array elt be determined by the ISA if((ref_right_rounded >> _eh._isaRate) >= _eh._isaLen) { i = _eh._len; ref_right_rounded = _eh._len; } else { i = isa[ref_right_rounded >> _eh._isaRate]; } uint32_t right_steps_rounded = ref_right_rounded - (off + qlen); uint32_t right_steps = ref_right - (off + qlen); l->initFromRow(i, this->_eh, this->_ebwt); // update locus for(size_t j = 0; j < right_steps_rounded; j++) { // Not a marked row; walk left one more char int c = rowL(*l); appendValue(rbuf, (Dna5)c); uint32_t newi; assert_lt(c, 4); assert_geq(c, 0); if(l->_fw) newi = countFwSide(*l, c); // Forward side else newi = countBwSide(*l, c); // Backward side assert_lt(newi, this->_eh._bwtLen); assert_neq(newi, i); i = newi; // update row assert_neq(i, _zOff); l->initFromRow(i, this->_eh, this->_ebwt); // update locus jumps++; } if(right_steps_rounded > right_steps) { jumps -= (right_steps_rounded - right_steps); _setLength(rbuf, right_steps); } assert_eq(right_steps, length(rbuf)); assert_eq(tlen, jumps + qlen); ::reverseInPlace(lbuf); ::reverseInPlace(rbuf); { cout << "reportReconstruct:" << endl << " " << lbuf << query << rbuf << endl; cout << " "; for(size_t i = 0; i < length(lbuf); i++) cout << " "; cout << query << endl; } // Now we've reconstructed the return false; } /** * Transform this Ebwt into the original string in linear time by using * the LF mapping to walk backwards starting at the row correpsonding * to the end of the string. The result is written to s. The Ebwt * must be in memory. */ template void Ebwt::restore(TStr& s) const { assert(isInMemory()); resize(s, this->_eh._len, Exact()); uint32_t jumps = 0; uint32_t i = this->_eh._len; // should point to final SA elt (starting with '$') SideLocus l(i, this->_eh, this->_ebwt); while(i != _zOff) { assert_lt(jumps, this->_eh._len); //if(_verbose) cout << "restore: i: " << i << endl; // Not a marked row; go back a char in the original string uint32_t newi = mapLF(l); assert_neq(newi, i); s[this->_eh._len - jumps - 1] = rowL(l); i = newi; l.initFromRow(i, this->_eh, this->_ebwt); jumps++; } assert_eq(jumps, this->_eh._len); } /** * Check that this Ebwt, when restored via restore(), matches up with * the given array of reference sequences. For sanity checking. */ template void Ebwt::checkOrigs(const vector >& os, bool color, bool mirror) const { TStr rest; restore(rest); uint32_t restOff = 0; size_t i = 0, j = 0; if(mirror) { // TODO: FIXME return; } while(i < os.size()) { size_t olen = length(os[i]); int lastorig = -1; for(; j < olen; j++) { size_t joff = j; if(mirror) joff = olen - j - 1; if((int)os[i][joff] == 4) { // Skip over Ns lastorig = -1; if(!mirror) { while(j < olen && (int)os[i][j] == 4) j++; } else { while(j < olen && (int)os[i][olen-j-1] == 4) j++; } j--; continue; } if(lastorig == -1 && color) { lastorig = os[i][joff]; continue; } if(color) { assert_neq(-1, lastorig); assert_eq(dinuc2color[(int)os[i][joff]][lastorig], rest[restOff]); } else { assert_eq(os[i][joff], rest[restOff]); } lastorig = (int)os[i][joff]; restOff++; } if(j == length(os[i])) { // Moved to next sequence i++; j = 0; } else { // Just jumped over a gap } } } /////////////////////////////////////////////////////////////////////// // // Functions for reading and writing Ebwts // /////////////////////////////////////////////////////////////////////// /** * Read an Ebwt from file with given filename. */ template void Ebwt::readIntoMemory( int color, int needEntireRev, bool justHeader, EbwtParams *params, bool mmSweep, bool loadNames, bool startVerbose) { bool switchEndian; // dummy; caller doesn't care #ifdef BOWTIE_MM char *mmFile[] = { NULL, NULL }; #endif if(_in1Str.length() > 0) { if(_verbose || startVerbose) { cerr << " About to open input files: "; logTime(cerr); } #ifdef BOWTIE_MM // Initialize our primary and secondary input-stream fields if(_in1 != -1) close(_in1); if(_verbose || startVerbose) { cerr << "Opening \"" << _in1Str << "\"" << endl; } if((_in1 = open(_in1Str.c_str(), O_RDONLY)) < 0) { cerr << "Could not open index file " << _in1Str << endl; } if(_in2 != -1) close(_in2); if(_verbose || startVerbose) { cerr << "Opening \"" << _in2Str << "\"" << endl; } if((_in2 = open(_in2Str.c_str(), O_RDONLY)) < 0) { cerr << "Could not open index file " << _in2Str << endl; } #else // Initialize our primary and secondary input-stream fields if(_in1 != NULL) fclose(_in1); if(_verbose || startVerbose) cerr << "Opening \"" << _in1Str << "\"" << endl; if((_in1 = fopen(_in1Str.c_str(), "rb")) == NULL) { cerr << "Could not open index file " << _in1Str << endl; } if(_in2 != NULL) fclose(_in2); if(_verbose || startVerbose) cerr << "Opening \"" << _in2Str << "\"" << endl; if((_in2 = fopen(_in2Str.c_str(), "rb")) == NULL) { cerr << "Could not open index file " << _in2Str << endl; } #endif if(_verbose || startVerbose) { cerr << " Finished opening input files: "; logTime(cerr); } #ifdef BOWTIE_MM if(_useMm && !justHeader) { const char *names[] = {_in1Str.c_str(), _in2Str.c_str()}; int fds[] = { _in1, _in2 }; for(int i = 0; i < 2; i++) { if(_verbose || startVerbose) { cerr << " Memory-mapping input file " << (i+1) << ": "; logTime(cerr); } struct stat sbuf; if (stat(names[i], &sbuf) == -1) { perror("stat"); cerr << "Error: Could not stat index file " << names[i] << " prior to memory-mapping" << endl; throw 1; } mmFile[i] = (char*)mmap((void *)0, sbuf.st_size, PROT_READ, MAP_SHARED, fds[i], 0); if(mmFile == (void *)(-1)) { perror("mmap"); cerr << "Error: Could not memory-map the index file " << names[i] << endl; throw 1; } if(mmSweep) { int sum = 0; for(off_t j = 0; j < sbuf.st_size; j += 1024) { sum += (int) mmFile[i][j]; } if(startVerbose) { cerr << " Swept the memory-mapped ebwt index file 1; checksum: " << sum << ": "; logTime(cerr); } } } mmFile1_ = mmFile[0]; mmFile2_ = mmFile[1]; } #endif } #ifdef BOWTIE_MM else if(_useMm && !justHeader) { mmFile[0] = mmFile1_; mmFile[1] = mmFile2_; } if(_useMm && !justHeader) { assert(mmFile[0] == mmFile1_); assert(mmFile[1] == mmFile2_); } #endif if(_verbose || startVerbose) { cerr << " Reading header: "; logTime(cerr); } // Read endianness hints from both streams size_t bytesRead = 0; switchEndian = false; uint32_t one = readU32(_in1, switchEndian); // 1st word of primary stream bytesRead += 4; #ifndef NDEBUG assert_eq(one, readU32(_in2, switchEndian)); // should match! #else readU32(_in2, switchEndian); #endif if(one != 1) { assert_eq((1u<<24), one); assert_eq(1, endianSwapU32(one)); switchEndian = true; } // Can't switch endianness and use memory-mapped files; in order to // support this, someone has to modify the file to switch // endiannesses appropriately, and we can't do this inside Bowtie // or we might be setting up a race condition with other processes. if(switchEndian && _useMm) { cerr << "Error: Can't use memory-mapped files when the index is the opposite endianness" << endl; throw 1; } // Reads header entries one by one from primary stream uint32_t len = readU32(_in1, switchEndian); bytesRead += 4; int32_t lineRate = readI32(_in1, switchEndian); bytesRead += 4; int32_t linesPerSide = readI32(_in1, switchEndian); bytesRead += 4; int32_t offRate = readI32(_in1, switchEndian); bytesRead += 4; // TODO: add isaRate to the actual file format (right now, the // user has to tell us whether there's an ISA sample and what the // sampling rate is. int32_t isaRate = _overrideIsaRate; int32_t ftabChars = readI32(_in1, switchEndian); bytesRead += 4; // chunkRate was deprecated in an earlier version of Bowtie; now // we use it to hold flags. int32_t flags = readI32(_in1, switchEndian); bool entireRev = false; if(flags < 0 && (((-flags) & EBWT_COLOR) != 0)) { if(color != -1 && !color) { cerr << "Error: -C was not specified when running bowtie, but index is in colorspace. If" << endl << "your reads are in colorspace, please use the -C option. If your reads are not" << endl << "in colorspace, please use a normal index (one built without specifying -C to" << endl << "bowtie-build)." << endl; throw 1; } color = 1; } else if(flags < 0) { if(color != -1 && color) { cerr << "Error: -C was specified when running bowtie, but index is not in colorspace. If" << endl << "your reads are in colorspace, please use a colorspace index (one built using" << endl << "bowtie-build -C). If your reads are not in colorspace, don't specify -C when" << endl << "running bowtie." << endl; throw 1; } color = 0; } if(flags < 0 && (((-flags) & EBWT_ENTIRE_REV) == 0)) { if(needEntireRev != -1 && needEntireRev != 0) { cerr << "Error: This index is not compatible with this version of bowtie. Please use a" << endl << "current version of bowtie-build." << endl; throw 1; } } else entireRev = true; bytesRead += 4; // Create a new EbwtParams from the entries read from primary stream EbwtParams *eh; bool deleteEh = false; if(params != NULL) { params->init(len, lineRate, linesPerSide, offRate, isaRate, ftabChars, color, entireRev); if(_verbose || startVerbose) params->print(cerr); eh = params; } else { eh = new EbwtParams(len, lineRate, linesPerSide, offRate, isaRate, ftabChars, color, entireRev); deleteEh = true; } // Set up overridden suffix-array-sample parameters uint32_t offsLen = eh->_offsLen; uint32_t offRateDiff = 0; uint32_t offsLenSampled = offsLen; if(_overrideOffRate > offRate) { offRateDiff = _overrideOffRate - offRate; } if(offRateDiff > 0) { offsLenSampled >>= offRateDiff; if((offsLen & ~(0xffffffff << offRateDiff)) != 0) { offsLenSampled++; } } // Set up overridden inverted-suffix-array-sample parameters uint32_t isaLen = eh->_isaLen; uint32_t isaRateDiff = 0; uint32_t isaLenSampled = isaLen; if(_overrideIsaRate > isaRate) { isaRateDiff = _overrideIsaRate - isaRate; } if(isaRateDiff > 0) { isaLenSampled >>= isaRateDiff; if((isaLen & ~(0xffffffff << isaRateDiff)) != 0) { isaLenSampled++; } } // Can't override the offrate or isarate and use memory-mapped // files; ultimately, all processes need to copy the sparser sample // into their own memory spaces. if(_useMm && (offRateDiff || isaRateDiff)) { cerr << "Error: Can't use memory-mapped files when the offrate or isarate is overridden" << endl; throw 1; } // Read nPat from primary stream this->_nPat = readI32(_in1, switchEndian); bytesRead += 4; if(this->_plen != NULL && !_useMm) { // Delete it so that we can re-read it delete[] this->_plen; this->_plen = NULL; } // Read plen from primary stream if(_useMm) { #ifdef BOWTIE_MM this->_plen = (uint32_t*)(mmFile[0] + bytesRead); bytesRead += this->_nPat*4; lseek(_in1, this->_nPat*4, SEEK_CUR); #endif } else { try { if(_verbose || startVerbose) { cerr << "Reading plen (" << this->_nPat << "): "; logTime(cerr); } this->_plen = new uint32_t[this->_nPat]; if(switchEndian) { for(uint32_t i = 0; i < this->_nPat; i++) { this->_plen[i] = readU32(_in1, switchEndian); } } else { MM_READ_RET r = MM_READ(_in1, (void*)this->_plen, this->_nPat*4); if(r != (MM_READ_RET)(this->_nPat*4)) { cerr << "Error reading _plen[] array: " << r << ", " << (this->_nPat*4) << endl; throw 1; } } } catch(bad_alloc& e) { cerr << "Out of memory allocating plen[] in Ebwt::read()" << " at " << __FILE__ << ":" << __LINE__ << endl; throw e; } } bool shmemLeader; // TODO: I'm not consistent on what "header" means. Here I'm using // "header" to mean everything that would exist in memory if we // started to build the Ebwt but stopped short of the build*() step // (i.e. everything up to and including join()). if(justHeader) goto done; this->_nFrag = readU32(_in1, switchEndian); bytesRead += 4; if(_verbose || startVerbose) { cerr << "Reading rstarts (" << this->_nFrag*3 << "): "; logTime(cerr); } assert_geq(this->_nFrag, this->_nPat); if(_useMm) { #ifdef BOWTIE_MM this->_rstarts = (uint32_t*)(mmFile[0] + bytesRead); bytesRead += this->_nFrag*4*3; lseek(_in1, this->_nFrag*4*3, SEEK_CUR); #endif } else { this->_rstarts = new uint32_t[this->_nFrag*3]; if(switchEndian) { for(uint32_t i = 0; i < this->_nFrag*3; i += 3) { // fragment starting position in joined reference // string, text id, and fragment offset within text this->_rstarts[i] = readU32(_in1, switchEndian); this->_rstarts[i+1] = readU32(_in1, switchEndian); this->_rstarts[i+2] = readU32(_in1, switchEndian); } } else { MM_READ_RET r = MM_READ(_in1, (void *)this->_rstarts, this->_nFrag*4*3); if(r != (MM_READ_RET)(this->_nFrag*4*3)) { cerr << "Error reading _rstarts[] array: " << r << ", " << (this->_nFrag*4*3) << endl; throw 1; } } } if(_useMm) { #ifdef BOWTIE_MM this->_ebwt = (uint8_t*)(mmFile[0] + bytesRead); bytesRead += eh->_ebwtTotLen; lseek(_in1, eh->_ebwtTotLen, SEEK_CUR); #endif } else { // Allocate ebwt (big allocation) if(_verbose || startVerbose) { cerr << "Reading ebwt (" << eh->_ebwtTotLen << "): "; logTime(cerr); } bool shmemLeader = true; if(useShmem_) { shmemLeader = ALLOC_SHARED_U8( (_in1Str + "[ebwt]"), eh->_ebwtTotLen, &this->_ebwt, "ebwt[]", (_verbose || startVerbose)); if(_verbose || startVerbose) { cerr << " shared-mem " << (shmemLeader ? "leader" : "follower") << endl; } } else { try { this->_ebwt = new uint8_t[eh->_ebwtTotLen]; } catch(bad_alloc& e) { cerr << "Out of memory allocating the ebwt[] array for the Bowtie index. Please try" << endl << "again on a computer with more memory." << endl; throw 1; } } if(shmemLeader) { // Read ebwt from primary stream MM_READ_RET r = MM_READ(_in1, (void *)this->_ebwt, eh->_ebwtTotLen); if(r != (MM_READ_RET)eh->_ebwtTotLen) { cerr << "Error reading ebwt array: returned " << r << ", length was " << (eh->_ebwtTotLen) << endl << "Your index files may be corrupt; please try re-building or re-downloading." << endl << "A complete index consists of 6 files: XYZ.1.ebwt, XYZ.2.ebwt, XYZ.3.ebwt," << endl << "XYZ.4.ebwt, XYZ.rev.1.ebwt, and XYZ.rev.2.ebwt. The XYZ.1.ebwt and " << endl << "XYZ.rev.1.ebwt files should have the same size, as should the XYZ.2.ebwt and" << endl << "XYZ.rev.2.ebwt files." << endl; throw 1; } if(switchEndian) { uint8_t *side = this->_ebwt; for(size_t i = 0; i < eh->_numSides; i++) { uint32_t *cums = reinterpret_cast(side + eh->_sideSz - 8); cums[0] = endianSwapU32(cums[0]); cums[1] = endianSwapU32(cums[1]); side += this->_eh._sideSz; } } if(useShmem_) NOTIFY_SHARED(this->_ebwt, eh->_ebwtTotLen); } else { // Seek past the data and wait until master is finished MM_SEEK(_in1, eh->_ebwtTotLen, SEEK_CUR); if(useShmem_) WAIT_SHARED(this->_ebwt, eh->_ebwtTotLen); } } // Read zOff from primary stream _zOff = readU32(_in1, switchEndian); bytesRead += 4; assert_lt(_zOff, len); try { // Read fchr from primary stream if(_verbose || startVerbose) cerr << "Reading fchr (5)" << endl; if(_useMm) { #ifdef BOWTIE_MM this->_fchr = (uint32_t*)(mmFile[0] + bytesRead); bytesRead += 5*4; lseek(_in1, 5*4, SEEK_CUR); #endif } else { this->_fchr = new uint32_t[5]; for(int i = 0; i < 5; i++) { this->_fchr[i] = readU32(_in1, switchEndian); assert_leq(this->_fchr[i], len); if(i > 0) assert_geq(this->_fchr[i], this->_fchr[i-1]); } } assert_gt(this->_fchr[4], this->_fchr[0]); // Read ftab from primary stream if(_verbose || startVerbose) { cerr << "Reading ftab (" << eh->_ftabLen << "): "; logTime(cerr); } if(_useMm) { #ifdef BOWTIE_MM this->_ftab = (uint32_t*)(mmFile[0] + bytesRead); bytesRead += eh->_ftabLen*4; lseek(_in1, eh->_ftabLen*4, SEEK_CUR); #endif } else { this->_ftab = new uint32_t[eh->_ftabLen]; if(switchEndian) { for(uint32_t i = 0; i < eh->_ftabLen; i++) this->_ftab[i] = readU32(_in1, switchEndian); } else { MM_READ_RET r = MM_READ(_in1, (void *)this->_ftab, eh->_ftabLen*4); if(r != (MM_READ_RET)(eh->_ftabLen*4)) { cerr << "Error reading _ftab[] array: " << r << ", " << (eh->_ftabLen*4) << endl; throw 1; } } } // Read etab from primary stream if(_verbose || startVerbose) { cerr << "Reading eftab (" << eh->_eftabLen << "): "; logTime(cerr); } if(_useMm) { #ifdef BOWTIE_MM this->_eftab = (uint32_t*)(mmFile[0] + bytesRead); bytesRead += eh->_eftabLen*4; lseek(_in1, eh->_eftabLen*4, SEEK_CUR); #endif } else { this->_eftab = new uint32_t[eh->_eftabLen]; if(switchEndian) { for(uint32_t i = 0; i < eh->_eftabLen; i++) this->_eftab[i] = readU32(_in1, switchEndian); } else { MM_READ_RET r = MM_READ(_in1, (void *)this->_eftab, eh->_eftabLen*4); if(r != (MM_READ_RET)(eh->_eftabLen*4)) { cerr << "Error reading _eftab[] array: " << r << ", " << (eh->_eftabLen*4) << endl; throw 1; } } } for(uint32_t i = 0; i < eh->_eftabLen; i++) { if(i > 0 && this->_eftab[i] > 0) { assert_geq(this->_eftab[i], this->_eftab[i-1]); } else if(i > 0 && this->_eftab[i-1] == 0) { assert_eq(0, this->_eftab[i]); } } } catch(bad_alloc& e) { cerr << "Out of memory allocating fchr[], ftab[] or eftab[] arrays for the Bowtie index." << endl << "Please try again on a computer with more memory." << endl; throw 1; } // Read reference sequence names from primary index file (or not, // if --refidx is specified) if(loadNames) { while(true) { char c = '\0'; if(MM_READ(_in1, (void *)(&c), (size_t)1) != (MM_READ_RET)1) break; bytesRead++; if(c == '\0') break; else if(c == '\n') { this->_refnames.push_back(""); } else { if(this->_refnames.size() == 0) { this->_refnames.push_back(""); } this->_refnames.back().push_back(c); } } } bytesRead = 4; // reset for secondary index file (already read 1-sentinel) shmemLeader = true; if(_verbose || startVerbose) { cerr << "Reading offs (" << offsLenSampled << " 32-bit words): "; logTime(cerr); } if(!_useMm) { if(!useShmem_) { // Allocate offs_ try { this->_offs = new uint32_t[offsLenSampled]; } catch(bad_alloc& e) { cerr << "Out of memory allocating the offs[] array for the Bowtie index." << endl << "Please try again on a computer with more memory." << endl; throw 1; } } else { shmemLeader = ALLOC_SHARED_U32( (_in2Str + "[offs]"), offsLenSampled*4, &this->_offs, "offs", (_verbose || startVerbose)); } } if(_overrideOffRate < 32) { if(shmemLeader) { // Allocate offs (big allocation) if(switchEndian || offRateDiff > 0) { assert(!_useMm); const uint32_t blockMaxSz = (2 * 1024 * 1024); // 2 MB block size const uint32_t blockMaxSzU32 = (blockMaxSz >> 2); // # U32s per block char *buf = new char[blockMaxSz]; for(uint32_t i = 0; i < offsLen; i += blockMaxSzU32) { uint32_t block = min(blockMaxSzU32, offsLen - i); MM_READ_RET r = MM_READ(_in2, (void *)buf, block << 2); if(r != (MM_READ_RET)(block << 2)) { cerr << "Error reading block of offs array: " << r << ", " << (block << 2) << endl << "Your index files may be corrupt; please try re-building or re-downloading." << endl << "A complete index consists of 6 files: XYZ.1.ebwt, XYZ.2.ebwt, XYZ.3.ebwt," << endl << "XYZ.4.ebwt, XYZ.rev.1.ebwt, and XYZ.rev.2.ebwt. The XYZ.1.ebwt and " << endl << "XYZ.rev.1.ebwt files should have the same size, as should the XYZ.2.ebwt and" << endl << "XYZ.rev.2.ebwt files." << endl; throw 1; } uint32_t idx = i >> offRateDiff; for(uint32_t j = 0; j < block; j += (1 << offRateDiff)) { assert_lt(idx, offsLenSampled); this->_offs[idx] = ((uint32_t*)buf)[j]; if(switchEndian) { this->_offs[idx] = endianSwapU32(this->_offs[idx]); } idx++; } } delete[] buf; } else { if(_useMm) { #ifdef BOWTIE_MM this->_offs = (uint32_t*)(mmFile[1] + bytesRead); bytesRead += (offsLen << 2); lseek(_in2, (offsLen << 2), SEEK_CUR); #endif } else { // If any of the high two bits are set if((offsLen & 0xf0000000) != 0) { if(sizeof(char *) <= 4) { cerr << "Sanity error: sizeof(char *) <= 4 but offsLen is " << hex << offsLen << endl; throw 1; } // offsLen << 4 overflows sometimes, so do it in four reads char *offs = (char *)this->_offs; for(int i = 0; i < 16; i++) { MM_READ_RET r = MM_READ(_in2, (void*)offs, offsLen >> 2); if(r != (MM_READ_RET)(offsLen >> 2)) { cerr << "Error reading block of _offs[] array: " << r << ", " << (offsLen >> 2) << endl; throw 1; } offs += (offsLen >> 2); } } else { // Do it all in one read MM_READ_RET r = MM_READ(_in2, (void*)this->_offs, offsLen << 2); if(r != (MM_READ_RET)(offsLen << 2)) { cerr << "Error reading _offs[] array: " << r << ", " << (offsLen << 2) << endl; throw 1; } } } } { ASSERT_ONLY(Bitset offsSeen(len+1)); for(uint32_t i = 0; i < offsLenSampled; i++) { assert(!offsSeen.test(this->_offs[i])); ASSERT_ONLY(offsSeen.set(this->_offs[i])); assert_leq(this->_offs[i], len); } } if(useShmem_) NOTIFY_SHARED(this->_offs, offsLenSampled*4); } else { // Not the shmem leader MM_SEEK(_in2, offsLenSampled*4, SEEK_CUR); if(useShmem_) WAIT_SHARED(this->_offs, offsLenSampled*4); } } // Allocate _isa[] (big allocation) if(_verbose || startVerbose) { cerr << "Reading isa (" << isaLenSampled << "): "; logTime(cerr); } if(!_useMm) { try { this->_isa = new uint32_t[isaLenSampled]; } catch(bad_alloc& e) { cerr << "Out of memory allocating the isa[] array for the Bowtie index." << endl << "Please try again on a computer with more memory." << endl; throw 1; } } // Read _isa[] if(switchEndian || isaRateDiff > 0) { assert(!_useMm); for(uint32_t i = 0; i < isaLen; i++) { if((i & ~(0xffffffff << isaRateDiff)) != 0) { char tmp[4]; MM_READ_RET r = MM_READ(_in2, (void *)tmp, 4); if(r != (MM_READ_RET)4) { cerr << "Error reading a word of the _isa[] array: " << r << ", 4" << endl; throw 1; } } else { uint32_t idx = i >> isaRateDiff; assert_lt(idx, isaLenSampled); this->_isa[idx] = readU32(_in2, switchEndian); } } } else { if(_useMm) { #ifdef BOWTIE_MM this->_isa = (uint32_t*)(mmFile[1] + bytesRead); bytesRead += (isaLen << 2); lseek(_in2, (isaLen << 2), SEEK_CUR); #endif } else { MM_READ_RET r = MM_READ(_in2, (void *)this->_isa, isaLen*4); if(r != (MM_READ_RET)(isaLen*4)) { cerr << "Error reading _isa[] array: " << r << ", " << (isaLen*4) << endl; throw 1; } } } { ASSERT_ONLY(Bitset isasSeen(len+1)); for(uint32_t i = 0; i < isaLenSampled; i++) { assert(!isasSeen.test(this->_isa[i])); ASSERT_ONLY(isasSeen.set(this->_isa[i])); assert_leq(this->_isa[i], len); } } this->postReadInit(*eh); // Initialize fields of Ebwt not read from file if(_verbose || startVerbose) print(cerr, *eh); // The fact that _ebwt and friends actually point to something // (other than NULL) now signals to other member functions that the // Ebwt is loaded into memory. done: // Exit hatch for both justHeader and !justHeader // Be kind if(deleteEh) delete eh; #ifdef BOWTIE_MM lseek(_in1, 0, SEEK_SET); lseek(_in2, 0, SEEK_SET); #else rewind(_in1); rewind(_in2); #endif } /** * Read reference names from an input stream 'in' for an Ebwt primary * file and store them in 'refnames'. */ static inline void readEbwtRefnames(istream& in, vector& refnames) { // _in1 must already be open with the get cursor at the // beginning and no error flags set. assert(in.good()); assert_eq((streamoff)in.tellg(), ios::beg); // Read endianness hints from both streams bool switchEndian = false; uint32_t one = readU32(in, switchEndian); // 1st word of primary stream if(one != 1) { assert_eq((1u<<24), one); switchEndian = true; } // Reads header entries one by one from primary stream uint32_t len = readU32(in, switchEndian); int32_t lineRate = readI32(in, switchEndian); int32_t linesPerSide = readI32(in, switchEndian); int32_t offRate = readI32(in, switchEndian); int32_t ftabChars = readI32(in, switchEndian); // BTL: chunkRate is now deprecated int32_t flags = readI32(in, switchEndian); bool color = false; bool entireReverse = false; if(flags < 0) { color = (((-flags) & EBWT_COLOR) != 0); entireReverse = (((-flags) & EBWT_ENTIRE_REV) != 0); } // Create a new EbwtParams from the entries read from primary stream EbwtParams eh(len, lineRate, linesPerSide, offRate, -1, ftabChars, color, entireReverse); uint32_t nPat = readI32(in, switchEndian); // nPat in.seekg(nPat*4, ios_base::cur); // skip plen // Skip rstarts uint32_t nFrag = readU32(in, switchEndian); in.seekg(nFrag*4*3, ios_base::cur); // Skip ebwt in.seekg(eh._ebwtTotLen, ios_base::cur); // Skip zOff from primary stream readU32(in, switchEndian); // Skip fchr in.seekg(5 * 4, ios_base::cur); // Skip ftab in.seekg(eh._ftabLen*4, ios_base::cur); // Skip eftab in.seekg(eh._eftabLen*4, ios_base::cur); // Read reference sequence names from primary index file while(true) { char c = '\0'; in.read(&c, 1); if(in.eof()) break; if(c == '\0') break; else if(c == '\n') { refnames.push_back(""); } else { if(refnames.size() == 0) { refnames.push_back(""); } refnames.back().push_back(c); } } if(refnames.back().empty()) { refnames.pop_back(); } // Be kind in.clear(); in.seekg(0, ios::beg); assert(in.good()); } /** * Read reference names from the index with basename 'in' and store * them in 'refnames'. */ static inline void readEbwtRefnames(const string& instr, vector& refnames) { ifstream in; // Initialize our primary and secondary input-stream fields in.open((instr + ".1.ebwt").c_str(), ios_base::in | ios::binary); if(!in.is_open()) { throw EbwtFileOpenException("Cannot open file " + instr); } assert(in.is_open()); assert(in.good()); assert_eq((streamoff)in.tellg(), ios::beg); readEbwtRefnames(in, refnames); } /** * Read just enough of the Ebwt's header to get its flags */ static inline int32_t readFlags(const string& instr) { ifstream in; // Initialize our primary and secondary input-stream fields in.open((instr + ".1.ebwt").c_str(), ios_base::in | ios::binary); if(!in.is_open()) { throw EbwtFileOpenException("Cannot open file " + instr); } assert(in.is_open()); assert(in.good()); bool switchEndian = false; uint32_t one = readU32(in, switchEndian); // 1st word of primary stream if(one != 1) { assert_eq((1u<<24), one); assert_eq(1, endianSwapU32(one)); switchEndian = true; } readU32(in, switchEndian); readI32(in, switchEndian); readI32(in, switchEndian); readI32(in, switchEndian); readI32(in, switchEndian); int32_t flags = readI32(in, switchEndian); return flags; } /** * Read just enough of the Ebwt's header to determine whether it's * colorspace. */ static inline bool readEbwtColor(const string& instr) { int32_t flags = readFlags(instr); if(flags < 0 && (((-flags) & EBWT_COLOR) != 0)) { return true; } else { return false; } } /** * Read just enough of the Ebwt's header to determine whether it's * entirely reversed. */ static inline bool readEntireReverse(const string& instr) { int32_t flags = readFlags(instr); if(flags < 0 && (((-flags) & EBWT_ENTIRE_REV) != 0)) { return true; } else { return false; } } /** * Write an extended Burrows-Wheeler transform to a pair of output * streams. * * @param out1 output stream to primary file * @param out2 output stream to secondary file * @param be write in big endian? */ template void Ebwt::writeFromMemory(bool justHeader, ostream& out1, ostream& out2) const { const EbwtParams& eh = this->_eh; assert(eh.repOk()); uint32_t be = this->toBe(); assert(out1.good()); assert(out2.good()); // When building an Ebwt, these header parameters are known // "up-front", i.e., they can be written to disk immediately, // before we join() or buildToDisk() writeI32(out1, 1, be); // endian hint for priamry stream writeI32(out2, 1, be); // endian hint for secondary stream writeU32(out1, eh._len, be); // length of string (and bwt and suffix array) writeI32(out1, eh._lineRate, be); // 2^lineRate = size in bytes of 1 line writeI32(out1, eh._linesPerSide, be); // not used writeI32(out1, eh._offRate, be); // every 2^offRate chars is "marked" writeI32(out1, eh._ftabChars, be); // number of 2-bit chars used to address ftab int32_t flags = 1; if(eh._color) flags |= EBWT_COLOR; if(eh._entireReverse) flags |= EBWT_ENTIRE_REV; writeI32(out1, -flags, be); // BTL: chunkRate is now deprecated if(!justHeader) { assert(isInMemory()); // These Ebwt parameters are known after the inputs strings have // been joined() but before they have been built(). These can // written to the disk next and then discarded from memory. writeU32(out1, this->_nPat, be); for(uint32_t i = 0; i < this->_nPat; i++) writeU32(out1, this->_plen[i], be); assert_geq(this->_nFrag, this->_nPat); writeU32(out1, this->_nFrag, be); for(uint32_t i = 0; i < this->_nFrag*3; i++) writeU32(out1, this->_rstarts[i], be); // These Ebwt parameters are discovered only as the Ebwt is being // built (in buildToDisk()). Of these, only 'offs' and 'ebwt' are // terribly large. 'ebwt' is written to the primary file and then // discarded from memory as it is built; 'offs' is similarly // written to the secondary file and discarded. out1.write((const char *)this->ebwt(), eh._ebwtTotLen); writeU32(out1, this->zOff(), be); uint32_t offsLen = eh._offsLen; for(uint32_t i = 0; i < offsLen; i++) writeU32(out2, this->_offs[i], be); uint32_t isaLen = eh._isaLen; for(uint32_t i = 0; i < isaLen; i++) writeU32(out2, this->_isa[i], be); // 'fchr', 'ftab' and 'eftab' are not fully determined until the // loop is finished, so they are written to the primary file after // all of 'ebwt' has already been written and only then discarded // from memory. for(int i = 0; i < 5; i++) writeU32(out1, this->_fchr[i], be); for(uint32_t i = 0; i < eh._ftabLen; i++) writeU32(out1, this->ftab()[i], be); for(uint32_t i = 0; i < eh._eftabLen; i++) writeU32(out1, this->eftab()[i], be); } } /** * Given a pair of strings representing output filenames, and assuming * this Ebwt object is currently in memory, write out this Ebwt to the * specified files. * * If sanity-checking is enabled, then once the streams have been * fully written and closed, we reopen them and read them into a * (hopefully) exact copy of this Ebwt. We then assert that the * current Ebwt and the copy match in all of their fields. */ template void Ebwt::writeFromMemory(bool justHeader, const string& out1, const string& out2) const { const EbwtParams& eh = this->_eh; assert(isInMemory()); assert(eh.repOk()); ofstream fout1(out1.c_str(), ios::binary); ofstream fout2(out2.c_str(), ios::binary); writeFromMemory(justHeader, fout1, fout2); fout1.close(); fout2.close(); // Read the file back in and assert that all components match if(_sanity) { if(_verbose) cout << "Re-reading \"" << out1 << "\"/\"" << out2 << "\" for sanity check" << endl; Ebwt copy(out1, out2, _verbose, _sanity); assert(!isInMemory()); copy.loadIntoMemory(eh._color ? 1 : 0, false, false); assert(isInMemory()); assert_eq(eh._lineRate, copy.eh()._lineRate); assert_eq(eh._linesPerSide, copy.eh()._linesPerSide); assert_eq(eh._offRate, copy.eh()._offRate); assert_eq(eh._isaRate, copy.eh()._isaRate); assert_eq(eh._ftabChars, copy.eh()._ftabChars); assert_eq(eh._len, copy.eh()._len); assert_eq(_zOff, copy.zOff()); assert_eq(_zEbwtBpOff, copy.zEbwtBpOff()); assert_eq(_zEbwtByteOff, copy.zEbwtByteOff()); assert_eq(_nPat, copy.nPat()); for(uint32_t i = 0; i < _nPat; i++) assert_eq(this->_plen[i], copy.plen()[i]); assert_eq(this->_nFrag, copy.nFrag()); for(uint32_t i = 0; i < this->nFrag*3; i++) { assert_eq(this->_rstarts[i], copy.rstarts()[i]); } for(uint32_t i = 0; i < 5; i++) assert_eq(this->_fchr[i], copy.fchr()[i]); for(uint32_t i = 0; i < eh._ftabLen; i++) assert_eq(this->ftab()[i], copy.ftab()[i]); for(uint32_t i = 0; i < eh._eftabLen; i++) assert_eq(this->eftab()[i], copy.eftab()[i]); for(uint32_t i = 0; i < eh._offsLen; i++) assert_eq(this->_offs[i], copy.offs()[i]); for(uint32_t i = 0; i < eh._isaLen; i++) assert_eq(this->_isa[i], copy.isa()[i]); for(uint32_t i = 0; i < eh._ebwtTotLen; i++) assert_eq(this->ebwt()[i], copy.ebwt()[i]); copy.sanityCheckAll(); if(_verbose) cout << "Read-in check passed for \"" << out1 << "\"/\"" << out2 << "\"" << endl; } } /////////////////////////////////////////////////////////////////////// // // Functions for building Ebwts // /////////////////////////////////////////////////////////////////////// /** * Join several text strings together in a way that's compatible with * the text-chunking scheme dictated by chunkRate parameter. * * The non-static member Ebwt::join additionally builds auxilliary * arrays that maintain a mapping between chunks in the joined string * and the original text strings. */ template TStr Ebwt::join(vector& l, uint32_t seed) { RandomSource rand; // reproducible given same seed rand.init(seed); TStr ret; size_t guessLen = 0; for(size_t i = 0; i < l.size(); i++) { guessLen += length(l[i]); } reserve(ret, guessLen, Exact()); for(size_t i = 0; i < l.size(); i++) { TStr& s = l[i]; assert_gt(length(s), 0); append(ret, s); } return ret; } /** * Join several text strings together in a way that's compatible with * the text-chunking scheme dictated by chunkRate parameter. * * The non-static member Ebwt::join additionally builds auxilliary * arrays that maintain a mapping between chunks in the joined string * and the original text strings. */ template TStr Ebwt::join(vector& l, vector& szs, uint32_t sztot, const RefReadInParams& refparams, uint32_t seed) { RandomSource rand; // reproducible given same seed rand.init(seed); RefReadInParams rpcp = refparams; TStr ret; size_t guessLen = sztot; reserve(ret, guessLen, Exact()); ASSERT_ONLY(size_t szsi = 0); for(size_t i = 0; i < l.size(); i++) { // For each sequence we can pull out of istream l[i]... assert(!l[i]->eof()); bool first = true; while(!l[i]->eof()) { RefRecord rec = fastaRefReadAppend(*l[i], first, ret, rpcp); #ifndef ACCOUNT_FOR_ALL_GAP_REFS if(rec.first && rec.len == 0) rec.first = false; #endif first = false; size_t bases = rec.len; assert_eq(rec.off, szs[szsi].off); assert_eq(rec.len, szs[szsi].len); assert_eq(rec.first, szs[szsi].first); ASSERT_ONLY(szsi++); if(bases == 0) continue; } } return ret; } /** * Join several text strings together according to the text-chunking * scheme specified in the EbwtParams. Ebwt fields calculated in this * function are written directly to disk. * * It is assumed, but not required, that the header values have already * been written to 'out1' before this function is called. * * The static member Ebwt::join just returns a joined version of a * list of strings without building any of the auxiliary arrays. * Because the pseudo-random number generator is the same, we expect * this function and the static function to give the same result given * the same seed. */ template void Ebwt::joinToDisk( vector& l, vector& szs, vector& plens, uint32_t sztot, const RefReadInParams& refparams, TStr& ret, ostream& out1, ostream& out2, uint32_t seed = 0) { BowtieContext* ctx = BowtieContext::getContext(); RandomSource rand; // reproducible given same seed rand.init(seed); RefReadInParams rpcp = refparams; assert_gt(szs.size(), 0); assert_gt(l.size(), 0); assert_gt(sztot, 0); // Not every fragment represents a distinct sequence - many // fragments may correspond to a single sequence. Count the // number of sequences here by counting the number of "first" // fragments. this->_nPat = 0; this->_nFrag = 0; #ifdef ACCOUNT_FOR_ALL_GAP_REFS int nGapFrag = 0; #endif for(size_t i = 0; i < szs.size(); i++) { if(szs[i].len > 0) this->_nFrag++; #ifdef ACCOUNT_FOR_ALL_GAP_REFS if(szs[i].len == 0 && szs[i].off > 0) nGapFrag++; if(szs[i].first && szs[i].len > 0) this->_nPat++; #else // For all records where len=0 and first=1, set first=0 assert(szs[i].len > 0 || !szs[i].first); if(szs[i].first) this->_nPat++; #endif } assert_gt(this->_nPat, 0); assert_geq(this->_nFrag, this->_nPat); this->_rstarts = NULL; writeU32(out1, this->_nPat, this->toBe()); assert_eq(plens.size(), this->_nPat); // Allocate plen[] try { this->_plen = new uint32_t[this->_nPat]; } catch(bad_alloc& e) { cerr << "Out of memory allocating plen[] in Ebwt::join()" << " at " << __FILE__ << ":" << __LINE__ << endl; throw e; } // For each pattern, set plen for(size_t i = 0; i < plens.size(); i++) { this->_plen[i] = plens[i]; writeU32(out1, this->_plen[i], this->toBe()); } // Write the number of fragments writeU32(out1, this->_nFrag, this->toBe()); size_t seqsRead = 0; ASSERT_ONLY(uint32_t szsi = 0); ASSERT_ONLY(uint32_t entsWritten = 0); // For each filebuf for(unsigned int i = 0; i < l.size(); i++) { if(ctx->isCanceled()) throw BowtieException("Canceled"); ctx->ti.progress = (ctx->build.secondEbwtRound ? 50.0:0.0) + (ctx->build.doubleEbwt ? 5.0 : 10.0) * (float)i / (float)l.size(); assert(!l[i]->eof()); bool first = true; uint32_t patoff = 0; // For each *fragment* (not necessary an entire sequence) we // can pull out of istream l[i]... while(!l[i]->eof()) { string name; // Push a new name onto our vector _refnames.push_back(""); //uint32_t oldRetLen = length(ret); RefRecord rec = fastaRefReadAppend(*l[i], first, ret, rpcp, &_refnames.back()); #ifndef ACCOUNT_FOR_ALL_GAP_REFS if(rec.first && rec.len == 0) rec.first = false; #endif first = false; if(rec.first) { if(_refnames.back().length() == 0) { // If name was empty, replace with an index ostringstream stm; stm << (_refnames.size()-1); _refnames.back() = stm.str(); } } else { // This record didn't actually start a new sequence so // no need to add a name //assert_eq(0, _refnames.back().length()); _refnames.pop_back(); } assert_lt(szsi, szs.size()); assert(szs[szsi].first == 0 || szs[szsi].first == 1); assert_eq(rec.off, szs[szsi].off); assert_eq(rec.len, szs[szsi].len); // szs[szsi].first == 2 sometimes?!?! g++ is unable to do // the following correctly, regardless of how I write it //assert((rec.first == 0) == (szs[szsi].first == 0)); assert(rec.first || rec.off > 0); ASSERT_ONLY(szsi++); #ifdef ACCOUNT_FOR_ALL_GAP_REFS if(rec.len == 0) continue; if(rec.first && rec.len > 0) seqsRead++; assert_leq(rec.len, this->_plen[seqsRead-1]); #else if(rec.first) seqsRead++; if(rec.len == 0) continue; assert_leq(rec.len, this->_plen[seqsRead-1]); #endif // Reset the patoff if this is the first fragment if(rec.first) patoff = 0; patoff += rec.off; // add fragment's offset from end of last frag. // Adjust rpcps //uint32_t seq = seqsRead-1; ASSERT_ONLY(entsWritten++); // This is where rstarts elements are written to the output stream //writeU32(out1, oldRetLen, this->toBe()); // offset from beginning of joined string //writeU32(out1, seq, this->toBe()); // sequence id //writeU32(out1, patoff, this->toBe()); // offset into sequence patoff += rec.len; } assert_gt(szsi, 0); l[i]->reset(); assert(!l[i]->eof()); #ifndef NDEBUG int c = l[i]->get(); assert_eq('>', c); assert(!l[i]->eof()); l[i]->reset(); assert(!l[i]->eof()); #endif } assert_eq(entsWritten, this->_nFrag); } /** * Build an Ebwt from a string 's' and its suffix array 'sa' (which * might actually be a suffix array *builder* that builds blocks of the * array on demand). The bulk of the Ebwt, i.e. the ebwt and offs * arrays, is written directly to disk. This is by design: keeping * those arrays in memory needlessly increases the footprint of the * building process. Instead, we prefer to build the Ebwt directly * "to disk" and then read it back into memory later as necessary. * * It is assumed that the header values and join-related values (nPat, * plen) have already been written to 'out1' before this function * is called. When this function is finished, it will have * additionally written ebwt, zOff, fchr, ftab and eftab to the primary * file and offs to the secondary file. * * Assume DNA/RNA/any alphabet with 4 or fewer elements. * Assume occ array entries are 32 bits each. * * @param sa the suffix array to convert to a Ebwt * @param buildISA whether to output an ISA sample into out2 after * the SA sample * @param s the original string * @param out */ template void Ebwt::buildToDisk(InorderBlockwiseSA& sa, const TStr& s, ostream& out1, ostream& out2) { BowtieContext *ctx = BowtieContext::getContext(); const EbwtParams& eh = this->_eh; assert(eh.repOk()); assert_eq(length(s)+1, sa.size()); assert_eq(length(s), eh._len); assert_gt(eh._lineRate, 3); assert(sa.suffixItrIsReset()); assert_leq((int)ValueSize::VALUE, 4); uint32_t len = eh._len; uint32_t ftabLen = eh._ftabLen; uint32_t sideSz = eh._sideSz; uint32_t ebwtTotSz = eh._ebwtTotSz; uint32_t fchr[] = {0, 0, 0, 0, 0}; uint32_t* ftab = NULL; uint32_t zOff = 0xffffffff; auto_ptr ftab_helper(NULL); // Save # of occurrences of each character as we walk along the bwt uint32_t occ[4] = {0, 0, 0, 0}; // Save 'G' and 'T' occurrences between backward and forward buckets uint32_t occSave[2] = {0, 0}; // Record rows that should "absorb" adjacent rows in the ftab. // The absorbed rows represent suffixes shorter than the ftabChars // cutoff. uint8_t absorbCnt = 0; uint8_t *absorbFtab; auto_ptr absorbFtab_helper(NULL); try { VMSG_NL("Allocating ftab, absorbFtab"); ftab = new uint32_t[ftabLen]; ftab_helper = auto_ptr(ftab); memset(ftab, 0, 4 * ftabLen); absorbFtab = new uint8_t[ftabLen]; absorbFtab_helper = auto_ptr(absorbFtab); memset(absorbFtab, 0, ftabLen); } catch(bad_alloc &e) { cerr << "Out of memory allocating ftab[] or absorbFtab[] " << "in Ebwt::buildToDisk() at " << __FILE__ << ":" << __LINE__ << endl; throw e; } assert(ftab != NULL); assert(absorbFtab != NULL); // Allocate the side buffer; holds a single side as its being // constructed and then written to disk. Reused across all sides. #ifdef SIXTY4_FORMAT auto_ptr ebwtSide_helper(NULL); uint64_t *ebwtSide = NULL; #else auto_ptr ebwtSide_helper(NULL); uint8_t *ebwtSide = NULL; #endif try { #ifdef SIXTY4_FORMAT ebwtSide = new uint64_t[sideSz >> 3]; ebwtSide_helper = auto_ptr(ebwtSide); #else ebwtSide = new uint8_t[sideSz]; ebwtSide_helper = auto_ptr(ebwtSide); #endif } catch(bad_alloc &e) { cerr << "Out of memory allocating ebwtSide[] in " << "Ebwt::buildToDisk() at " << __FILE__ << ":" << __LINE__ << endl; throw e; } assert(ebwtSide != NULL); // Allocate a buffer to hold the ISA sample, which we accumulate in // the loop and then output at the end. We can't write output the // ISA right away because the order in which we calculate its // elements is based on the suffix array, which we only see bit by // bit uint32_t *isaSample = NULL; if(eh._isaRate >= 0) { try { isaSample = new uint32_t[eh._isaLen]; } catch(bad_alloc &e) { cerr << "Out of memory allocating isaSample[] in " << "Ebwt::buildToDisk() at " << __FILE__ << ":" << __LINE__ << endl; throw e; } assert(isaSample != NULL); } // Points to the base offset within ebwt for the side currently // being written uint32_t side = 0; // Points to a byte offset from 'side' within ebwt[] where next // char should be written #ifdef SIXTY4_FORMAT int sideCur = (eh._sideBwtSz >> 3) - 1; #else int sideCur = eh._sideBwtSz - 1; #endif // Whether we're assembling a forward or a reverse bucket bool fw = false; // Did we just finish writing a forward bucket? (Must be true when // we exit the loop.) bool wroteFwBucket = false; // Have we skipped the '$' in the last column yet? ASSERT_ONLY(bool dollarSkipped = false); uint32_t si = 0; // string offset (chars) ASSERT_ONLY(uint32_t lastSufInt = 0); ASSERT_ONLY(bool inSA = true); // true iff saI still points inside suffix // array (as opposed to the padding at the // end) // Iterate over packed bwt bytes VMSG_NL("Entering Ebwt loop"); ASSERT_ONLY(uint32_t beforeEbwtOff = (uint32_t)out1.tellp()); while(side < ebwtTotSz) { wroteFwBucket = false; // Sanity-check our cursor into the side buffer assert_geq(sideCur, 0); assert_lt(sideCur, (int)eh._sideBwtSz); assert_eq(0, side % sideSz); // 'side' must be on side boundary ebwtSide[sideCur] = 0; // clear assert_lt(side + sideCur, ebwtTotSz); // Iterate over bit-pairs in the si'th character of the BWT #ifdef SIXTY4_FORMAT for(int bpi = 0; bpi < 32; bpi++, si++) #else for(int bpi = 0; bpi < 4; bpi++, si++) #endif { int bwtChar; bool count = true; if(si <= len) { // Still in the SA; extract the bwtChar uint32_t saElt = sa.nextSuffix(); // (that might have triggered sa to calc next suf block) if(isaSample != NULL && (saElt & eh._isaMask) == saElt) { // This element belongs in the ISA sample. Add // an entry mapping the text offset to the offset // into the suffix array that holds the suffix // beginning with the character at that text offset assert_lt((saElt >> eh._isaRate), eh._isaLen); isaSample[saElt >> eh._isaRate] = si; } if(saElt == 0) { // Don't add the '$' in the last column to the BWT // transform; we can't encode a $ (only A C T or G) // and counting it as, say, an A, will mess up the // LR mapping bwtChar = 0; count = false; ASSERT_ONLY(dollarSkipped = true); zOff = si; // remember the SA row that // corresponds to the 0th suffix } else { bwtChar = (int)(Dna)(s[saElt-1]); assert_lt(bwtChar, 4); // Update the fchr fchr[bwtChar]++; } // Update ftab if((len-saElt) >= (uint32_t)eh._ftabChars) { // Turn the first ftabChars characters of the // suffix into an integer index into ftab uint32_t sufInt = 0; for(int i = 0; i < eh._ftabChars; i++) { sufInt <<= 2; assert_lt(i, (int)(len-saElt)); sufInt |= (unsigned char)(Dna)(s[saElt+i]); } // Assert that this prefix-of-suffix is greater // than or equal to the last one (true b/c the // suffix array is sorted) #ifndef NDEBUG if(lastSufInt > 0) assert_geq(sufInt, lastSufInt); lastSufInt = sufInt; #endif // Update ftab assert_lt(sufInt+1, ftabLen); ftab[sufInt+1]++; if(absorbCnt > 0) { // Absorb all short suffixes since the last // transition into this transition absorbFtab[sufInt] = absorbCnt; absorbCnt = 0; } } else { // Otherwise if suffix is fewer than ftabChars // characters long, then add it to the 'absorbCnt'; // it will be absorbed into the next transition assert_lt(absorbCnt, 255); absorbCnt++; } // Suffix array offset boundary? - update offset array if((si & eh._offMask) == si) { assert_lt((si >> eh._offRate), eh._offsLen); // Write offsets directly to the secondary output // stream, thereby avoiding keeping them in memory writeU32(out2, saElt, this->toBe()); } } else { // Strayed off the end of the SA, now we're just // padding out a bucket #ifndef NDEBUG if(inSA) { // Assert that we wrote all the characters in the // string before now assert_eq(si, len+1); inSA = false; } #endif // 'A' used for padding; important that padding be // counted in the occ[] array bwtChar = 0; } if(count) occ[bwtChar]++; // Append BWT char to bwt section of current side if(fw) { // Forward bucket: fill from least to most #ifdef SIXTY4_FORMAT ebwtSide[sideCur] |= ((uint64_t)bwtChar << (bpi << 1)); if(bwtChar > 0) assert_gt(ebwtSide[sideCur], 0); #else pack_2b_in_8b(bwtChar, ebwtSide[sideCur], bpi); assert_eq((ebwtSide[sideCur] >> (bpi*2)) & 3, bwtChar); #endif } else { // Backward bucket: fill from most to least #ifdef SIXTY4_FORMAT ebwtSide[sideCur] |= ((uint64_t)bwtChar << ((31 - bpi) << 1)); if(bwtChar > 0) assert_gt(ebwtSide[sideCur], 0); #else pack_2b_in_8b(bwtChar, ebwtSide[sideCur], 3-bpi); assert_eq((ebwtSide[sideCur] >> ((3-bpi)*2)) & 3, bwtChar); #endif } } // end loop over bit-pairs assert_eq(dollarSkipped ? 3 : 0, (occ[0] + occ[1] + occ[2] + occ[3]) & 3); #ifdef SIXTY4_FORMAT assert_eq(0, si & 31); #else assert_eq(0, si & 3); #endif if(fw) sideCur++; else sideCur--; #ifdef SIXTY4_FORMAT if(sideCur == (int)eh._sideBwtSz >> 3) #else if(sideCur == (int)eh._sideBwtSz) #endif { // Forward side boundary assert_eq(0, si % eh._sideBwtLen); #ifdef SIXTY4_FORMAT sideCur = (eh._sideBwtSz >> 3) - 1; #else sideCur = eh._sideBwtSz - 1; #endif assert(fw); fw = false; wroteFwBucket = true; // Write 'G' and 'T' assert_leq(occSave[0], occ[2]); assert_leq(occSave[1], occ[3]); uint32_t *u32side = reinterpret_cast(ebwtSide); side += sideSz; assert_leq(side, eh._ebwtTotSz); u32side[(sideSz >> 2)-2] = endianizeU32(occSave[0], this->toBe()); u32side[(sideSz >> 2)-1] = endianizeU32(occSave[1], this->toBe()); // Write forward side to primary file out1.write((const char *)ebwtSide, sideSz); } else if (sideCur == -1) { // Backward side boundary assert_eq(0, si % eh._sideBwtLen); sideCur = 0; assert(!fw); fw = true; // Write 'A' and 'C' uint32_t *u32side = reinterpret_cast(ebwtSide); side += sideSz; assert_leq(side, eh._ebwtTotSz); u32side[(sideSz >> 2)-2] = endianizeU32(occ[0], this->toBe()); u32side[(sideSz >> 2)-1] = endianizeU32(occ[1], this->toBe()); occSave[0] = occ[2]; // save 'G' count occSave[1] = occ[3]; // save 'T' count // Write backward side to primary file out1.write((const char *)ebwtSide, sideSz); } } VMSG_NL("Exited Ebwt loop"); ctx->ti.progress = (ctx->build.secondEbwtRound ? 50.0:0.0) + ( ctx->build.doubleEbwt ? 50 : 100 ); assert(ftab != NULL); assert_neq(zOff, 0xffffffff); // if(absorbCnt > 0) { // // Absorb any trailing, as-yet-unabsorbed short suffixes into // // the last element of ftab // absorbFtab[ftabLen-1] = absorbCnt; // } // Assert that our loop counter got incremented right to the end assert_eq(side, eh._ebwtTotSz); // Assert that we wrote the expected amount to out1 assert_eq(((uint32_t)out1.tellp() - beforeEbwtOff), eh._ebwtTotSz); // assert that the last thing we did was write a forward bucket assert(wroteFwBucket); // // Write zOff to primary stream // writeU32(out1, zOff, this->toBe()); // // Finish building fchr // // Exclusive prefix sum on fchr for(int i = 1; i < 4; i++) { fchr[i] += fchr[i-1]; } assert_eq(fchr[3], len); // Shift everybody up by one for(int i = 4; i >= 1; i--) { fchr[i] = fchr[i-1]; } fchr[0] = 0; if(_verbose) { for(int i = 0; i < 5; i++) cout << "fchr[" << "ACGT$"[i] << "]: " << fchr[i] << endl; } // Write fchr to primary file for(int i = 0; i < 5; i++) { writeU32(out1, fchr[i], this->toBe()); } // // Finish building ftab and build eftab // // Prefix sum on ftable uint32_t eftabLen = 0; assert_eq(0, absorbFtab[0]); for(uint32_t i = 1; i < ftabLen; i++) { if(absorbFtab[i] > 0) eftabLen += 2; } assert_leq(eftabLen, (uint32_t)eh._ftabChars*2); eftabLen = eh._ftabChars*2; auto_ptr eftab_helper(NULL); uint32_t *eftab = NULL; try { eftab = new uint32_t[eftabLen]; eftab_helper = auto_ptr(eftab); memset(eftab, 0, 4 * eftabLen); } catch(bad_alloc &e) { cerr << "Out of memory allocating eftab[] " << "in Ebwt::buildToDisk() at " << __FILE__ << ":" << __LINE__ << endl; throw e; } assert(eftab != NULL); uint32_t eftabCur = 0; for(uint32_t i = 1; i < ftabLen; i++) { uint32_t lo = ftab[i] + Ebwt::ftabHi(ftab, eftab, len, ftabLen, eftabLen, i-1); if(absorbFtab[i] > 0) { // Skip a number of short pattern indicated by absorbFtab[i] uint32_t hi = lo + absorbFtab[i]; assert_lt(eftabCur*2+1, eftabLen); eftab[eftabCur*2] = lo; eftab[eftabCur*2+1] = hi; ftab[i] = (eftabCur++) ^ 0xffffffff; // insert pointer into eftab assert_eq(lo, Ebwt::ftabLo(ftab, eftab, len, ftabLen, eftabLen, i)); assert_eq(hi, Ebwt::ftabHi(ftab, eftab, len, ftabLen, eftabLen, i)); } else { ftab[i] = lo; } } //this assert doesn't work: //assert_eq(Ebwt::ftabHi(ftab, eftab, len, ftabLen, eftabLen, ftabLen-1), len+1); // Write ftab to primary file for(uint32_t i = 0; i < ftabLen; i++) { writeU32(out1, ftab[i], this->toBe()); } // Write eftab to primary file for(uint32_t i = 0; i < eftabLen; i++) { writeU32(out1, eftab[i], this->toBe()); } // Write isa to primary file if(isaSample != NULL) { ASSERT_ONLY(Bitset sawISA(eh._len+1)); for(uint32_t i = 0; i < eh._isaLen; i++) { uint32_t s = isaSample[i]; assert_leq(s, eh._len); assert(!sawISA.test(s)); ASSERT_ONLY(sawISA.set(s)); writeU32(out2, s, this->toBe()); } delete[] isaSample; } //delete[] ftab; //delete[] eftab; //delete[] absorbFtab; // Note: if you'd like to sanity-check the Ebwt, you'll have to // read it back into memory first! assert(!isInMemory()); VMSG_NL("Exiting Ebwt::buildToDisk()"); } /** * Try to find the Bowtie index specified by the user. First try the * exact path given by the user. Then try the user-provided string * appended onto the path of the "indexes" subdirectory below this * executable, then try the provided string appended onto * "$BOWTIE_INDEXES/". */ string adjustEbwtBase(const string& cmdline, const string& ebwtFileBase, bool verbose = false); #endif /*EBWT_H_*/ ugene-1.9.8/src/plugins_3rdparty/bowtie/src/bowtie/COPYING0000644000175000017500000001212711651544326022030 0ustar ilyailyaThe Artistic License Preamble The intent of this document is to state the conditions under which a Package may be copied, such that the Copyright Holder maintains some semblance of artistic control over the development of the package, while giving the users of the package the right to use and distribute the Package in a more-or-less customary fashion, plus the right to make reasonable modifications. Definitions: * "Package" refers to the collection of files distributed by the Copyright Holder, and derivatives of that collection of files created through textual modification. * "Standard Version" refers to such a Package if it has not been modified, or has been modified in accordance with the wishes of the Copyright Holder. * "Copyright Holder" is whoever is named in the copyright or copyrights for the package. * "You" is you, if you're thinking about copying or distributing this Package. * "Reasonable copying fee" is whatever you can justify on the basis of media cost, duplication charges, time of people involved, and so on. (You will not be required to justify it to the Copyright Holder, but only to the computing community at large as a market that must bear the fee.) * "Freely Available" means that no fee is charged for the item itself, though there may be fees involved in handling the item. It also means that recipients of the item may redistribute it under the same conditions they received it. 1. You may make and give away verbatim copies of the source form of the Standard Version of this Package without restriction, provided that you duplicate all of the original copyright notices and associated disclaimers. 2. You may apply bug fixes, portability fixes and other modifications derived from the Public Domain or from the Copyright Holder. A Package modified in such a way shall still be considered the Standard Version. 3. You may otherwise modify your copy of this Package in any way, provided that you insert a prominent notice in each changed file stating how and when you changed that file, and provided that you do at least ONE of the following: a) place your modifications in the Public Domain or otherwise make them Freely Available, such as by posting said modifications to Usenet or an equivalent medium, or placing the modifications on a major archive site such as ftp.uu.net, or by allowing the Copyright Holder to include your modifications in the Standard Version of the Package. b) use the modified Package only within your corporation or organization. c) rename any non-standard executables so the names do not conflict with standard executables, which must also be provided, and provide a separate manual page for each non-standard executable that clearly documents how it differs from the Standard Version. d) make other distribution arrangements with the Copyright Holder. 4. You may distribute the programs of this Package in object code or executable form, provided that you do at least ONE of the following: a) distribute a Standard Version of the executables and library files, together with instructions (in the manual page or equivalent) on where to get the Standard Version. b) accompany the distribution with the machine-readable source of the Package with your modifications. c) accompany any non-standard executables with their corresponding Standard Version executables, giving the non-standard executables non-standard names, and clearly documenting the differences in manual pages (or equivalent), together with instructions on where to get the Standard Version. d) make other distribution arrangements with the Copyright Holder. 5. You may charge a reasonable copying fee for any distribution of this Package. You may charge any fee you choose for support of this Package. You may not charge a fee for this Package itself. However, you may distribute this Package in aggregate with other (possibly commercial) programs as part of a larger (possibly commercial) software distribution provided that you do not advertise this Package as a product of your own. 6. The scripts and library files supplied as input to or produced as output from the programs of this Package do not automatically fall under the copyright of this Package, but belong to whomever generated them, and may be sold commercially, and may be aggregated with this Package. 7. C or perl subroutines supplied by you and linked into this Package shall not be considered part of this Package. 8. The name of the Copyright Holder may not be used to endorse or promote products derived from this software without specific prior written permission. 9. THIS PACKAGE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. The End This license is approved by the Open Source Initiative (www.opensource.org) for certifying software as OSI Certified Open Source. ugene-1.9.8/src/plugins_3rdparty/bowtie/src/bowtie/search_1mm_phase2.c0000644000175000017500000000155611651544326024426 0ustar ilyailya/* * This is a fragment, included from multiple places in ebwt_search.cpp. * It implements the logic of the second phase of the 1-mismatch search * routine. It is implemented as a code fragment so that it can be * reused in both the half-index-in-memory and full-index-in-memory * situations. */ { bt.setEbwt(&ebwtBw); bt.setReportExacts(false); if(!norc) { params.setFw(false); // Next, try hits with one mismatch on the 3' end for the reverse-complement read bt.setQuery(patsrc->bufa()); bt.setOffs(0, 0, s3, s, s, s); // 1 mismatch allowed in 3' half if(bt.backtrack()) { continue; } } if(!nofw) { params.setFw(true); // Next, try hits with one mismatch on the 3' end for the reverse-complement read bt.setQuery(patsrc->bufa()); bt.setOffs(0, 0, s3, s, s, s); // 1 mismatch allowed in 3' half if(bt.backtrack()) { continue; } } } ugene-1.9.8/src/plugins_3rdparty/bowtie/src/bowtie/zbox.h0000644000175000017500000000365011651544326022131 0ustar ilyailya#ifndef ZBOX_H_ #define ZBOX_H_ /** * Fill z with Z-box information for s. String z will not be resized * and will only be filled up to its size cap. This is the linear-time * algorithm from Gusfield. An optional sanity-check uses a naive * algorithm to double-check results. */ template void calcZ(const T& s, uint32_t off, String& z, bool verbose = false, bool sanityCheck = false) { size_t lCur = 0, rCur = 0; size_t zlen = length(z); size_t slen = length(s); assert_gt(zlen, 0); assert_eq(z[0], 0); //assert_leq(zlen, slen); for (size_t k = 1; k < zlen && k+off < slen; k++) { assert_lt(lCur, k); assert(z[lCur] == 0 || z[lCur] == rCur - lCur + 1); if(k > rCur) { // compare starting at k with prefix starting at 0 size_t ki = k; while(off+ki < length(s) && s[off+ki] == s[off+ki-k]) ki++; z[k] = ki - k; assert_lt(off+z[k], slen); if(z[k] > 0) { lCur = k; rCur = k + z[k] - 1; } } else { // position k is contained in a Z-box size_t betaLen = rCur - k + 1; size_t kPrime = k - lCur; assert_eq(s[off+k], s[off+kPrime]); if(z[kPrime] < betaLen) { z[k] = z[kPrime]; assert_lt(off+z[k], slen); // lCur, rCur unchanged } else if (z[kPrime] > 0) { int q = 0; while (off+q+rCur+1 < length(s) && s[off+q+rCur+1] == s[off+betaLen+q]) q++; z[k] = betaLen + q; assert_lt(off+z[k], slen); rCur = rCur + q; assert_geq(k, lCur); lCur = k; } else { z[k] = 0; assert_lt(off+z[k], slen); // lCur, rCur unchanged } } } #ifndef NDEBUG if(sanityCheck) { // Recalculate Z-boxes using naive quadratic-time algorithm and // compare to linear-time result assert_eq(0, z[0]); for(size_t i = 1; i < length(z); i++) { size_t j; for(j = i; off+j < length(s); j++) { if(s[off+j] != s[off+j-i]) break; } assert_eq(j-i, z[i]); } } #endif } #endif /*ZBOX_H_*/ ugene-1.9.8/src/plugins_3rdparty/bowtie/src/bowtie/ref_aligner.h0000644000175000017500000047006011651544326023427 0ustar ilyailya/* * ref_aligner.h */ #ifndef REF_ALIGNER_H_ #define REF_ALIGNER_H_ #include "u64.h" #include #include #include #include #include "seqan/sequence.h" #include "alphabet.h" #include "range.h" #include "reference.h" // Let the reference-aligner buffer size be 16K by default. If more // room is required, a new buffer must be allocated from the heap. const static int REF_ALIGNER_BUFSZ = 16 * 1024; /** * Abstract parent class for classes that look for alignments by * matching against the reference sequence directly. This is useful * both for sanity-checking results from the Bowtie index and for * finding mates when the reference location of the opposite mate is * known. */ template class RefAligner { typedef seqan::String TDna5Str; typedef seqan::String TCharStr; typedef std::vector TU32Vec; typedef std::vector TRangeVec; typedef std::pair TU64Pair; typedef std::set TSetPairs; public: RefAligner(bool color, bool verbose = false, bool quiet = false, uint32_t seedLen = 0, uint32_t qualMax = 0xffffffff, bool maqPenalty = false) : color_(color), verbose_(verbose), seedLen_(seedLen), qualMax_(qualMax), maqPenalty_(maqPenalty), refbuf_(buf_), refbufSz_(REF_ALIGNER_BUFSZ), freeRefbuf_(false) { } /** * Free the reference-space alignment buffer if this object * allocated it. */ virtual ~RefAligner() { if(freeRefbuf_) { delete[] refbuf_; } } /** * Find one alignment of qry:quals in the range begin-end in * reference string ref. Store the alignment details in range. */ virtual void find(uint32_t numToFind, const uint32_t tidx, const BitPairReference *refs, const TDna5Str& qry, const TCharStr& quals, uint32_t begin, uint32_t end, TRangeVec& ranges, TU32Vec& results, TSetPairs* pairs = NULL, uint32_t aoff = 0xffffffff, bool seedOnLeft = false) { assert_gt(numToFind, 0); assert_gt(end, begin); uint32_t spread = end - begin + (color_ ? 1 : 0); uint32_t spreadPlus = spread + 12; // Make sure the buffer is large enough to accommodate the spread if(spreadPlus > this->refbufSz_) { this->newBuf(spreadPlus); } // Read in the relevant stretch of the reference string int offset = refs->getStretch(this->refbuf_, tidx, begin, spread); uint8_t *buf = ((uint8_t*)this->refbuf_) + offset; if(color_) { // Colorize buffer for(size_t i = 0; i < (end-begin); i++) { assert_leq((int)buf[i], 4); buf[i] = dinuc2color[(int)buf[i]][(int)buf[i+1]]; } } // Look for alignments ASSERT_ONLY(uint32_t irsz = ranges.size()); anchor64Find(numToFind, tidx, buf, qry, quals, begin, end, ranges, results, pairs, aoff, seedOnLeft); #ifndef NDEBUG for(size_t i = irsz; i < results.size(); i++) { assert_eq(ranges[i].numMms, ranges[i].mms.size()); assert_eq(ranges[i].numMms, ranges[i].refcs.size()); } #endif } /** * Find one alignment of qry:quals in the range begin-end in * reference string ref. Store the alignment details in range. * Uses a combination of the anchor bases and 64-bit arithmetic to * find anchors quickly. */ virtual void anchor64Find(uint32_t numToFind, uint32_t tidx, uint8_t* ref, const TDna5Str& qry, const TCharStr& quals, uint32_t begin, uint32_t end, TRangeVec& ranges, TU32Vec& results, TSetPairs* pairs = NULL, uint32_t aoff = 0xffffffff, bool seedOnLeft = false) const = 0; /** * Set a new reference-sequence buffer. */ void setBuf(uint32_t *newbuf, uint32_t newsz) { if(freeRefbuf_) { delete[] refbuf_; freeRefbuf_ = false; } refbuf_ = newbuf; refbufSz_ = newsz; } /** * Set a new reference-sequence buffer. */ void newBuf(uint32_t newsz) { if(freeRefbuf_) { delete[] refbuf_; } try { refbuf_ = new uint32_t[(newsz + 3) / 4]; if(refbuf_ == NULL) throw std::bad_alloc(); } catch(std::bad_alloc& e) { cerr << "Error: Could not allocate reference-space alignment buffer of " << newsz << "B" << endl; throw 1; } refbufSz_ = newsz; freeRefbuf_ = true; } protected: bool color_; /// whether to colorize reference buffers before handing off bool verbose_; /// be talkative uint32_t seedLen_; /// length of seed region for read uint32_t qualMax_; /// maximum sum of quality penalties bool maqPenalty_;/// whether to round as in Maq uint32_t *refbuf_; /// pointer to current reference buffer uint32_t refbufSz_; /// size of current reference buffer uint32_t buf_[REF_ALIGNER_BUFSZ / 4]; /// built-in reference buffer (may be superseded) bool freeRefbuf_; /// whether refbuf_ points to something we should delete }; /** * Concrete RefAligner for finding nearby exact hits given an anchor * hit. */ template class ExactRefAligner : public RefAligner { typedef seqan::String TDna5Str; typedef seqan::String TCharStr; typedef std::vector TU32Vec; typedef std::vector TRangeVec; typedef std::pair TU64Pair; typedef std::set TSetPairs; public: ExactRefAligner(bool color, bool verbose, bool quiet) : RefAligner(color, verbose, quiet) { } virtual ~ExactRefAligner() { } protected: /** * Because we're doing end-to-end exact, we don't care which end of * 'qry' is the 5' end. */ void naiveFind(uint32_t numToFind, uint32_t tidx, uint8_t* ref, const TDna5Str& qry, const TCharStr& quals, uint32_t begin, uint32_t end, TRangeVec& ranges, TU32Vec& results, TSetPairs* pairs, uint32_t aoff, bool seedOnLeft) const { assert_gt(numToFind, 0); const uint32_t qlen = seqan::length(qry); assert_geq(end - begin, qlen); // caller should have checked this assert_gt(end, begin); assert_gt(qlen, 0); uint32_t qend = end - qlen; uint32_t lim = qend - begin; uint32_t halfway = begin + (lim >> 1); bool hi = false; for(uint32_t i = 1; i <= lim+1; i++) { uint32_t ri; // leftmost position in candidate alignment uint32_t rir; // same, minus begin; for indexing into ref[] if(hi) { ri = halfway + (i >> 1); rir = ri - begin; assert_leq(ri, qend); } else { ri = halfway - (i >> 1); rir = ri - begin; assert_geq(ri, begin); } hi = !hi; // Do the naive comparison bool match = true; for(uint32_t j = 0; j < qlen; j++) { #if 0 // Count Ns in the reference as mismatches const int q = (int)qry[j]; const int r = (int)ref[rir + j]; assert_leq(q, 4); assert_leq(r, 4); if(q == 4 || r == 4 || q != r) { // Mismatch match = false; break; } // Match; continue #else // Disallow alignments that involve an N in the // reference const int r = (int)ref[rir + j]; if(r & 4) { // N in reference; bail match = false; break; } const int q = (int)qry[j]; assert_leq(q, 4); assert_lt(r, 4); if(q != r) { // Mismatch match = false; break; } // Match; continue #endif } if(match) { ranges.resize(ranges.size()+1); Range& range = ranges.back(); range.stratum = 0; range.numMms = 0; assert_eq(0, range.mms.size()); assert_eq(0, range.refcs.size()); results.push_back(ri); } } return; // no match } /** * Because we're doing end-to-end exact, we don't care which end of * 'qry' is the 5' end. */ virtual void anchor64Find(uint32_t numToFind, uint32_t tidx, uint8_t *ref, const TDna5Str& qry, const TCharStr& quals, uint32_t begin, uint32_t end, TRangeVec& ranges, TU32Vec& results, TSetPairs* pairs, uint32_t aoff, // offset of anchor mate bool seedOnLeft) const { assert_gt(numToFind, 0); ASSERT_ONLY(const uint32_t rangesInitSz = ranges.size()); ASSERT_ONLY(uint32_t duplicates = 0); ASSERT_ONLY(uint32_t r2i = 0); const uint32_t qlen = seqan::length(qry); assert_geq(end - begin, qlen); // caller should have checked this assert_gt(end, begin); assert_gt(qlen, 0); #ifndef NDEBUG // Get all naive hits TRangeVec r2; TU32Vec re2; naiveFind(numToFind, tidx, ref, qry, quals, begin, end, r2, re2, pairs, aoff, seedOnLeft); #endif const uint32_t anchorBitPairs = min(qlen, 32); // anchorOverhang = # read bases not included in the anchor const uint32_t anchorOverhang = qlen <= 32 ? 0 : qlen - 32; const uint32_t lim = end - qlen - begin; const uint32_t halfway = begin + (lim >> 1); uint64_t anchor = U64(0); uint64_t buffw = U64(0); // Set up a mask that we'll apply to the two bufs every round // to discard bits that were rotated out of the anchor area uint64_t clearMask = U64(0xffffffffffffffff); bool useMask = false; if(anchorBitPairs < 32) { clearMask >>= ((32-anchorBitPairs) << 1); useMask = true; } const int lhsShift = ((anchorBitPairs - 1) << 1); // Build the contents of the 'anchor' dword and the initial // contents of the 'buffw' dword. If there are fewer than 32 // anchorBitPairs, the content will be packed into the least // significant bits of the word. uint32_t skipLeftToRights = 0; uint32_t skipRightToLefts = 0; for(uint32_t i = 0; i < anchorBitPairs; i++) { int c = (int)qry[i]; // next query character assert_leq(c, 4); if(c & 4) { assert_eq(r2.size(), ranges.size() - rangesInitSz); return; // can't match if query has Ns } int r = (int)ref[halfway - begin + i]; // next reference character if(r & 4) { r = 0; // The right-to-left direction absorbs the candidate // alignment based at 'halfway'; so skipLeftToRights is // i, not i+1 skipLeftToRights = max(skipLeftToRights, i); skipRightToLefts = max(skipRightToLefts, anchorBitPairs - i); } assert_lt(r, 4); assert_lt(c, 4); anchor = ((anchor << U64(2)) | c); buffw = ((buffw << U64(2)) | r); } // Check whether read is disqualified by Ns outside of the anchor // region for(uint32_t i = anchorBitPairs; i < qlen; i++) { if((int)qry[i] == 4) { assert_eq(r2.size(), ranges.size() - rangesInitSz); return; // can't match if query has Ns } } uint64_t bufbw = buffw; // We're moving the right-hand edge of the anchor along until // it's 'anchorOverhang' chars from the end of the target region. // Note that we're not making a 3'/5' distinction here; if we // were, we might need to make the 'anchorOverhang' adjustment on // the left end of the range rather than the right. bool hi = false; uint32_t riHi = halfway; uint32_t rirHi = halfway - begin; uint32_t rirHiAnchor = rirHi + anchorBitPairs - 1; uint32_t riLo = halfway + 1; uint32_t rirLo = halfway - begin + 1; for(uint32_t i = 1; i <= lim + 1; i++) { int r; // new reference char assert_lt(skipLeftToRights, qlen); assert_leq(skipRightToLefts, qlen); if(hi) { hi = false; // Moving left-to-right riHi++; rirHi++; rirHiAnchor++; r = (int)ref[rirHiAnchor]; if(r & 4) { r = 0; skipLeftToRights = anchorBitPairs; } assert_lt(r, 4); // Bring in new base pair at the least significant // position buffw = ((buffw << U64(2)) | r); if(useMask) buffw &= clearMask; if(skipLeftToRights > 0) { skipLeftToRights--; continue; } if(buffw != anchor) { continue; } } else { hi = true; // Moving right-to-left riLo--; rirLo--; r = (int)ref[rirLo]; if(r & 4) { r = 0; skipRightToLefts = qlen; } assert_lt(r, 4); if(i >= 2) { bufbw >>= U64(2); // Bring in new base pair at the most significant // position bufbw |= ((uint64_t)r << lhsShift); } if(skipRightToLefts > 0) { skipRightToLefts--; continue; } if(bufbw != anchor) { continue; } } // Seed hit! bool foundHit = true; uint32_t ri = hi ? riLo : riHi; uint32_t rir = hi ? rirLo : rirHi; if(anchorOverhang > 0) { // Does the non-anchor part of the alignment (the // "overhang") ruin it? bool skipCandidate = false; for(uint32_t j = 0; j < anchorOverhang; j++) { assert_lt(ri + anchorBitPairs + j, end); int rc = (int)ref[rir + anchorBitPairs + j]; if(rc == 4) { // Oops, encountered an N in the reference in // the overhang portion of the candidate // alignment // (Note that we inverted hi earlier) if(hi) { // Right-to-left skipRightToLefts = anchorOverhang - j - 1; } else { // Left-to-right skipLeftToRights = anchorBitPairs + j; } skipCandidate = true; break; // Skip this candidate } if((int)qry[32 + j] != rc) { // Yes, overhang ruins it foundHit = false; break; } } if(skipCandidate) continue; } if(foundHit) { if(pairs != NULL) { TU64Pair p; if(ri < aoff) { // By convention, the upstream mate's // coordinates go in the 'first' field p.first = ((uint64_t)tidx << 32) | (uint64_t)ri; p.second = ((uint64_t)tidx << 32) | (uint64_t)aoff; } else { p.first = ((uint64_t)tidx << 32) | (uint64_t)aoff; p.second = ((uint64_t)tidx << 32) | (uint64_t)ri; } if(pairs->find(p) != pairs->end()) { // We already found this hit! Continue. ASSERT_ONLY(duplicates++); ASSERT_ONLY(r2i++); continue; } else { // Record this hit pairs->insert(p); } } assert_lt(r2i, r2.size()); assert_eq(re2[r2i], ri); ranges.resize(ranges.size()+1); Range& range = ranges.back(); range.stratum = 0; range.numMms = 0; assert_eq(0, range.mms.size()); assert_eq(0, range.refcs.size()); ASSERT_ONLY(r2i++); results.push_back(ri); if(--numToFind == 0) return; } else { // Keep scanning } } assert_leq(duplicates, r2.size()); assert_geq(r2.size() - duplicates, ranges.size() - rangesInitSz); return; // no hit } }; /** * Defined in ref_aligner.cpp. Maps an octet representing the XOR of * two two-bit-per-base-encoded DNA sequences to the number of bases * that mismatch between the two. */ extern unsigned char u8toMms[]; /** * Concrete RefAligner for finding nearby 1-mismatch hits given an * anchor hit. */ template class OneMMRefAligner : public RefAligner { typedef seqan::String TDna5Str; typedef seqan::String TCharStr; typedef std::vector TRangeVec; typedef std::vector TU32Vec; typedef std::pair TU64Pair; typedef std::set TSetPairs; public: OneMMRefAligner(bool color, bool verbose, bool quiet) : RefAligner(color, verbose, quiet) { } virtual ~OneMMRefAligner() { } protected: /** * Because we're doing end-to-end exact, we don't care which end of * 'qry' is the 5' end. */ void naiveFind(uint32_t numToFind, uint32_t tidx, uint8_t* ref, const TDna5Str& qry, const TCharStr& quals, uint32_t begin, uint32_t end, TRangeVec& ranges, TU32Vec& results, TSetPairs* pairs, uint32_t aoff, bool seedOnLeft) const { assert_gt(numToFind, 0); const uint32_t qlen = seqan::length(qry); assert_geq(end - begin, qlen); // caller should have checked this assert_gt(end, begin); assert_gt(qlen, 0); uint32_t qend = end - qlen; uint32_t lim = qend - begin; uint32_t halfway = begin + (lim >> 1); bool hi = false; for(uint32_t i = 1; i <= lim+1; i++) { uint32_t ri; // leftmost position in candidate alignment uint32_t rir; // same, minus begin; for indexing into ref[] if(hi) { ri = halfway + (i >> 1); rir = ri - begin; assert_leq(ri, qend); } else { ri = halfway - (i >> 1); rir = ri - begin; assert_geq(ri, begin); } hi = !hi; // Do the naive comparison bool match = true; int refc = -1; uint32_t mmOff = 0xffffffff; int mms = 0; for(uint32_t j = 0; j < qlen; j++) { #if 0 // Count Ns in the reference as mismatches const int q = (int)qry[j]; const int r = (int)ref[rir + j]; assert_leq(q, 4); assert_leq(r, 4); if(q == 4 || r == 4 || q != r) { #else // Disallow alignments that involve an N in the // reference const int r = (int)ref[rir + j]; if(r & 4) { // N in reference; bail match = false; break; } const int q = (int)qry[j]; assert_leq(q, 4); assert_lt(r, 4); if(q != r) { #endif // Mismatch! if(++mms > 1) { // Too many; reject this alignment match = false; break; } else { // First one; remember offset and ref char refc = "ACGTN"[r]; mmOff = j; } } } if(match) { assert_leq(mms, 1); ranges.resize(ranges.size()+1); Range& range = ranges.back(); range.stratum = mms; range.numMms = mms; assert_eq(0, range.mms.size()); assert_eq(0, range.refcs.size()); if(mms == 1) { assert_lt(mmOff, qlen); range.mms.push_back(mmOff); range.refcs.push_back(refc); } results.push_back(ri); } } return; } /** * Because we're doing end-to-end exact, we don't care which end of * 'qry' is the 5' end. */ virtual void anchor64Find(uint32_t numToFind, uint32_t tidx, uint8_t* ref, const TDna5Str& qry, const TCharStr& quals, uint32_t begin, uint32_t end, TRangeVec& ranges, TU32Vec& results, TSetPairs* pairs = NULL, uint32_t aoff = 0xffffffff, bool seedOnLeft = false) const { assert_gt(numToFind, 0); ASSERT_ONLY(const uint32_t rangesInitSz = ranges.size()); ASSERT_ONLY(uint32_t duplicates = 0); ASSERT_ONLY(uint32_t r2i = 0); const uint32_t qlen = seqan::length(qry); assert_geq(end - begin, qlen); // caller should have checked this assert_gt(end, begin); assert_gt(qlen, 0); #ifndef NDEBUG // Get results from the naive matcher for sanity-checking TRangeVec r2; TU32Vec re2; naiveFind(numToFind, tidx, ref, qry, quals, begin, end, r2, re2, pairs, aoff, seedOnLeft); #endif const uint32_t anchorBitPairs = min(qlen, 32); const int lhsShift = ((anchorBitPairs - 1) << 1); const uint32_t anchorCushion = 32 - anchorBitPairs; // anchorOverhang = # read bases not included in the anchor const uint32_t anchorOverhang = (qlen <= 32 ? 0 : (qlen - 32)); const uint32_t lim = end - qlen - begin; const uint32_t halfway = begin + (lim >> 1); uint64_t anchor = U64(0); uint64_t buffw = U64(0); // rotating ref sequence buffer // OR the 'diff' buffer with this so that we can always count // 'N's as mismatches uint64_t diffMask = U64(0); // Set up a mask that we'll apply to the two bufs every round // to discard bits that were rotated out of the anchor area uint64_t clearMask = U64(0xffffffffffffffff); bool useMask = false; if(anchorBitPairs < 32) { clearMask >>= ((32-anchorBitPairs) << 1); useMask = true; } int nsInAnchor = 0; int nPos = -1; uint32_t skipLeftToRights = 0; uint32_t skipRightToLefts = 0; // Construct the 'anchor' 64-bit buffer so that it holds all of // the first 'anchorBitPairs' bit pairs of the query. for(uint32_t i = 0; i < anchorBitPairs; i++) { int c = (int)qry[i]; // next query character int r = (int)ref[halfway - begin + i]; // next reference character if(r & 4) { r = 0; // The right-to-left direction absorbs the candidate // alignment based at 'halfway'; so skipLeftToRights is // i, not i+1 skipLeftToRights = max(skipLeftToRights, i); skipRightToLefts = max(skipRightToLefts, anchorBitPairs - i); } assert_leq(c, 4); assert_lt(r, 4); // Special case: query has an 'N' if(c == 4) { if(++nsInAnchor > 1) { // More than one 'N' in the anchor region; can't // possibly have a 1-mismatch hit anywhere assert_eq(r2.size(), ranges.size() - rangesInitSz); return; // can't match if query has Ns } nPos = (int)i; // Make it look like an 'A' in the anchor c = 0; diffMask = (diffMask << U64(2)) | U64(1); } else { diffMask <<= U64(2); } anchor = ((anchor << U64(2)) | c); buffw = ((buffw << U64(2)) | r); } // Check whether read is disqualified by Ns outside of the anchor // region for(uint32_t i = anchorBitPairs; i < qlen; i++) { if((int)qry[i] == 4) { if(++nsInAnchor > 1) { assert_eq(r2.size(), ranges.size() - rangesInitSz); return; // can't match if query has Ns } } } uint64_t bufbw = buffw; // We're moving the right-hand edge of the anchor along until // it's 'anchorOverhang' chars from the end of the target region. // Note that we're not making a 3'/5' distinction here; if we // were, we might need to make the 'anchorOverhang' adjustment on // the left end of the range rather than the right. bool hi = false; uint32_t riHi = halfway; uint32_t rirHi = halfway - begin; uint32_t rirHiAnchor = rirHi + anchorBitPairs - 1; uint32_t riLo = halfway + 1; uint32_t rirLo = halfway - begin + 1; for(uint32_t i = 1; i <= lim + 1; i++) { int r; // new reference char uint64_t diff; assert_lt(skipLeftToRights, qlen); assert_leq(skipRightToLefts, qlen); if(hi) { hi = false; // Moving left-to-right riHi++; rirHi++; rirHiAnchor++; r = (int)ref[rirHiAnchor]; if(r & 4) { r = 0; skipLeftToRights = anchorBitPairs; } assert_lt(r, 4); // Bring in new base pair at the least significant // position buffw = ((buffw << U64(2)) | r); if(useMask) buffw &= clearMask; if(skipLeftToRights > 0) { skipLeftToRights--; continue; } diff = (buffw ^ anchor) | diffMask; } else { hi = true; // Moving right-to-left riLo--; rirLo--; r = (int)ref[rirLo]; if(r & 4) { r = 0; skipRightToLefts = qlen; } assert_lt(r, 4); if(i >= 2) { bufbw >>= U64(2); // Bring in new base pair at the most significant // position bufbw |= ((uint64_t)r << lhsShift); } if(skipRightToLefts > 0) { skipRightToLefts--; continue; } diff = (bufbw ^ anchor) | diffMask; } if((diff & U64(0xffffffff00000000)) && (diff & U64(0x00000000ffffffff))) continue; uint32_t ri = hi ? riLo : riHi; uint32_t rir = hi ? rirLo : rirHi; // Could use pop count uint8_t *diff8 = reinterpret_cast(&diff); // As a first cut, see if there are too many mismatches in // the first and last parts of the anchor uint32_t diffs = u8toMms[(int)diff8[0]] + u8toMms[(int)diff8[7]]; if(diffs > 1) continue; diffs += u8toMms[(int)diff8[1]] + u8toMms[(int)diff8[2]] + u8toMms[(int)diff8[3]] + u8toMms[(int)diff8[4]] + u8toMms[(int)diff8[5]] + u8toMms[(int)diff8[6]]; uint32_t mmpos = 0xffffffff; int refc = -1; if(diffs > 1) { // Too many differences continue; } else if(diffs == 1 && nPos != -1) { // There was one difference, but there was also one N, // so we already know where the difference is mmpos = nPos; refc = "ACGT"[(int)ref[rir + nPos]]; } else if(diffs == 1) { // Figure out which position mismatched mmpos = 31; if((diff & U64(0xffffffff)) == 0) { diff >>= U64(32); mmpos -= 16; } assert_neq(0, diff); if((diff & U64(0xffff)) == 0) { diff >>= U64(16); mmpos -= 8; } assert_neq(0, diff); if((diff & U64(0xff)) == 0) { diff >>= U64(8); mmpos -= 4; } assert_neq(0, diff); if((diff & U64(0xf)) == 0) { diff >>= U64(4); mmpos -= 2; } assert_neq(0, diff); if((diff & U64(0x3)) == 0) { mmpos--; } assert_neq(0, diff); assert_geq(mmpos, 0); assert_lt(mmpos, 32); mmpos -= anchorCushion; refc = "ACGT"[(int)ref[rir + mmpos]]; } // Now extend the anchor into a longer alignment bool foundHit = true; if(anchorOverhang > 0) { assert_leq(ri + anchorBitPairs + anchorOverhang, end); bool skipCandidate = false; for(uint32_t j = 0; j < anchorOverhang; j++) { int rc = (int)ref[rir + 32 + j]; if(rc == 4) { // Oops, encountered an N in the reference in // the overhang portion of the candidate // alignment // (Note that we inverted hi earlier) if(hi) { // Right-to-left skipRightToLefts = anchorOverhang - j - 1; } else { // Left-to-right skipLeftToRights = anchorBitPairs + j; } skipCandidate = true; // Skip this candidate break; } if((int)qry[32 + j] != rc) { if(++diffs > 1) { foundHit = false; break; } else { mmpos = 32 + j; refc = "ACGT"[(int)ref[rir + 32 + j]]; } } } if(skipCandidate) continue; } if(!foundHit) continue; if(pairs != NULL) { TU64Pair p; if(ri < aoff) { // By convention, the upstream mate's // coordinates go in the 'first' field p.first = ((uint64_t)tidx << 32) | (uint64_t)ri; p.second = ((uint64_t)tidx << 32) | (uint64_t)aoff; } else { p.second = ((uint64_t)tidx << 32) | (uint64_t)ri; p.first = ((uint64_t)tidx << 32) | (uint64_t)aoff; } if(pairs->find(p) != pairs->end()) { // We already found this hit! Continue. ASSERT_ONLY(duplicates++); ASSERT_ONLY(r2i++); continue; } else { // Record this hit pairs->insert(p); } } assert_leq(diffs, 1); assert_lt(r2i, r2.size()); assert_eq(re2[r2i], ri); ranges.resize(ranges.size()+1); Range& range = ranges.back(); assert_eq(diffs, r2[r2i].numMms); range.stratum = diffs; range.numMms = diffs; assert_eq(0, range.mms.size()); assert_eq(0, range.refcs.size()); if(diffs == 1) { assert_neq(mmpos, 0xffffffff); assert_eq(mmpos, r2[r2i].mms[0]); assert_neq(-1, refc); assert_eq(refc, r2[r2i].refcs[0]); range.mms.push_back(mmpos); range.refcs.push_back(refc); } ASSERT_ONLY(r2i++); results.push_back(ri); if(--numToFind == 0) return; } assert_leq(duplicates, r2.size()); assert_geq(r2.size() - duplicates, ranges.size() - rangesInitSz); return; // no hit } }; /** * Concrete RefAligner for finding nearby 2-mismatch hits given an * anchor hit. */ template class TwoMMRefAligner : public RefAligner { typedef seqan::String TDna5Str; typedef seqan::String TCharStr; typedef std::vector TRangeVec; typedef std::vector TU32Vec; typedef std::pair TU64Pair; typedef std::set TSetPairs; public: TwoMMRefAligner(bool color, bool verbose, bool quiet) : RefAligner(color, verbose, quiet) { } virtual ~TwoMMRefAligner() { } protected: /** * Because we're doing end-to-end exact, we don't care which end of * 'qry' is the 5' end. */ void naiveFind(uint32_t numToFind, uint32_t tidx, uint8_t* ref, const TDna5Str& qry, const TCharStr& quals, uint32_t begin, uint32_t end, TRangeVec& ranges, TU32Vec& results, TSetPairs* pairs, uint32_t aoff, bool seedOnLeft) const { assert_gt(numToFind, 0); const uint32_t qlen = seqan::length(qry); assert_geq(end - begin, qlen); // caller should have checked this assert_gt(end, begin); assert_gt(qlen, 0); uint32_t qend = end - qlen; uint32_t lim = qend - begin; uint32_t halfway = begin + (lim >> 1); bool hi = false; for(uint32_t i = 1; i <= lim+1; i++) { uint32_t ri; // leftmost position in candidate alignment uint32_t rir; // same, minus begin; for indexing into ref[] if(hi) { ri = halfway + (i >> 1); rir = ri - begin; assert_leq(ri, qend); } else { ri = halfway - (i >> 1); rir = ri - begin; assert_geq(ri, begin); } hi = !hi; // Do the naive comparison bool match = true; int refc1 = -1; uint32_t mmOff1 = 0xffffffff; int refc2 = -1; uint32_t mmOff2 = 0xffffffff; int mms = 0; for(uint32_t j = 0; j < qlen; j++) { #if 0 // Count Ns in the reference as mismatches const int q = (int)qry[j]; const int r = (int)ref[rir + j]; assert_leq(q, 4); assert_leq(r, 4); if(q == 4 || r == 4 || q != r) { #else // Disallow alignments that involve an N in the // reference const int r = (int)ref[rir + j]; if(r & 4) { // N in reference; bail match = false; break; } const int q = (int)qry[j]; assert_leq(q, 4); assert_lt(r, 4); if(q != r) { #endif // Mismatch! if(++mms > 2) { // Too many; reject this alignment match = false; break; } else if(mms == 2) { // Second one; remember offset and ref char refc2 = "ACGTN"[r]; mmOff2 = j; } else { assert_eq(1, mms); // First one; remember offset and ref char refc1 = "ACGTN"[r]; mmOff1 = j; } } } if(match) { assert_leq(mms, 2); ranges.resize(ranges.size()+1); Range& range = ranges.back(); range.stratum = mms; range.numMms = mms; assert_eq(0, range.mms.size()); assert_eq(0, range.refcs.size()); if(mms > 0) { assert_lt(mmOff1, qlen); assert(refc1 == 'A' || refc1 == 'C' || refc1 == 'G' || refc1 == 'T'); range.mms.push_back(mmOff1); range.refcs.push_back(refc1); if(mms > 1) { assert_eq(2, mms); assert_lt(mmOff2, qlen); assert(refc2 == 'A' || refc2 == 'C' || refc2 == 'G' || refc2 == 'T'); range.mms.push_back(mmOff2); range.refcs.push_back(refc2); } } results.push_back(ri); } } return; } /** * Because we're doing end-to-end exact, we don't care which end of * 'qry' is the 5' end. */ virtual void anchor64Find(uint32_t numToFind, uint32_t tidx, uint8_t* ref, const TDna5Str& qry, const TCharStr& quals, uint32_t begin, uint32_t end, TRangeVec& ranges, TU32Vec& results, TSetPairs* pairs = NULL, uint32_t aoff = 0xffffffff, bool seedOnLeft = false) const { assert_gt(numToFind, 0); ASSERT_ONLY(const uint32_t rangesInitSz = ranges.size()); ASSERT_ONLY(uint32_t duplicates = 0); ASSERT_ONLY(uint32_t r2i = 0); const uint32_t qlen = seqan::length(qry); assert_geq(end - begin, qlen); // caller should have checked this assert_gt(end, begin); assert_gt(qlen, 0); #ifndef NDEBUG // Get results from the naive matcher for sanity-checking TRangeVec r2; TU32Vec re2; naiveFind(numToFind, tidx, ref, qry, quals, begin, end, r2, re2, pairs, aoff, seedOnLeft); #endif const uint32_t anchorBitPairs = min(qlen, 32); const int lhsShift = ((anchorBitPairs - 1) << 1); const uint32_t anchorCushion = 32 - anchorBitPairs; // anchorOverhang = # read bases not included in the anchor const uint32_t anchorOverhang = (qlen <= 32 ? 0 : (qlen - 32)); const uint32_t lim = end - qlen - begin; const uint32_t halfway = begin + (lim >> 1); uint64_t anchor = U64(0); uint64_t buffw = U64(0); // rotating ref sequence buffer // OR the 'diff' buffer with this so that we can always count // 'N's as mismatches uint64_t diffMask = U64(0); // Set up a mask that we'll apply to the two bufs every round // to discard bits that were rotated out of the anchor area uint64_t clearMask = U64(0xffffffffffffffff); bool useMask = false; if(anchorBitPairs < 32) { clearMask >>= ((32-anchorBitPairs) << 1); useMask = true; } int nsInAnchor = 0; uint32_t nPoss = 0; int nPos1 = -1; int nPos2 = -1; uint32_t skipLeftToRights = 0; uint32_t skipRightToLefts = 0; // Construct the 'anchor' 64-bit buffer so that it holds all of // the first 'anchorBitPairs' bit pairs of the query. for(uint32_t i = 0; i < anchorBitPairs; i++) { int c = (int)qry[i]; // next query character int r = (int)ref[halfway - begin + i]; // next reference character if(r & 4) { r = 0; // The right-to-left direction absorbs the candidate // alignment based at 'halfway'; so skipLeftToRights is // i, not i+1 skipLeftToRights = max(skipLeftToRights, i); skipRightToLefts = max(skipRightToLefts, anchorBitPairs - i); } assert_leq(c, 4); assert_lt(r, 4); // Special case: query has an 'N' if(c == 4) { if(++nsInAnchor > 2) { // More than two 'N's in the anchor region; can't // possibly have a 2-mismatch hit anywhere return; // can't match if query has Ns } else if(nsInAnchor == 2) { nPos2 = (int)i; nPoss++; } else { assert_eq(1, nsInAnchor); nPos1 = (int)i; nPoss++; } // Make it look like an 'A' in the anchor c = 0; diffMask = (diffMask << U64(2)) | U64(1); } else { diffMask <<= U64(2); } anchor = ((anchor << U64(2)) | c); buffw = ((buffw << U64(2)) | r); } assert_leq(nPoss, 2); // Check whether read is disqualified by Ns outside of the anchor // region for(uint32_t i = anchorBitPairs; i < qlen; i++) { if((int)qry[i] == 4) { if(++nsInAnchor > 2) { return; // can't match if query has Ns } } } uint64_t bufbw = buffw; // We're moving the right-hand edge of the anchor along until // it's 'anchorOverhang' chars from the end of the target region. // Note that we're not making a 3'/5' distinction here; if we // were, we might need to make the 'anchorOverhang' adjustment on // the left end of the range rather than the right. bool hi = false; uint32_t riHi = halfway; uint32_t rirHi = halfway - begin; uint32_t rirHiAnchor = rirHi + anchorBitPairs - 1; uint32_t riLo = halfway + 1; uint32_t rirLo = halfway - begin + 1; uint32_t i; for(i = 1; i <= lim + 1; i++) { int r; // new reference char uint64_t diff; assert_lt(skipLeftToRights, qlen); assert_leq(skipRightToLefts, qlen); if(hi) { hi = false; // Moving left-to-right riHi++; rirHi++; rirHiAnchor++; r = (int)ref[rirHiAnchor]; if(r & 4) { r = 0; skipLeftToRights = anchorBitPairs; } assert_lt(r, 4); // Bring in new base pair at the least significant // position buffw = ((buffw << U64(2)) | r); if(useMask) buffw &= clearMask; if(skipLeftToRights > 0) { skipLeftToRights--; continue; } diff = (buffw ^ anchor) | diffMask; } else { hi = true; // Moving right-to-left riLo--; rirLo--; r = (int)ref[rirLo]; if(r & 4) { r = 0; skipRightToLefts = qlen; } assert_lt(r, 4); if(i >= 2) { bufbw >>= U64(2); // Bring in new base pair at the most significant // position bufbw |= ((uint64_t)r << lhsShift); } if(skipRightToLefts > 0) { skipRightToLefts--; continue; } diff = (bufbw ^ anchor) | diffMask; } if((diff & U64(0xfffff00000000000)) && (diff & U64(0x00000ffffff00000)) && (diff & U64(0x00000000000fffff))) continue; uint32_t ri = hi ? riLo : riHi; uint32_t rir = hi ? rirLo : rirHi; // Could use pop count uint8_t *diff8 = reinterpret_cast(&diff); // As a first cut, see if there are too many mismatches in // the first and last parts of the anchor uint32_t diffs = u8toMms[(int)diff8[0]] + u8toMms[(int)diff8[7]]; if(diffs > 2) continue; diffs += u8toMms[(int)diff8[1]] + u8toMms[(int)diff8[2]] + u8toMms[(int)diff8[3]] + u8toMms[(int)diff8[4]] + u8toMms[(int)diff8[5]] + u8toMms[(int)diff8[6]]; uint32_t mmpos1 = 0xffffffff; int refc1 = -1; uint32_t mmpos2 = 0xffffffff; int refc2 = -1; if(diffs > 2) { // Too many differences continue; } else if(nPoss > 1 && diffs == nPoss) { // There was one difference, but there was also one N, // so we already know where the difference is mmpos1 = nPos1; refc1 = "ACGT"[(int)ref[rir + nPos1]]; if(nPoss == 2) { mmpos2 = nPos2; refc2 = "ACGT"[(int)ref[rir + nPos2]]; } } else if(diffs > 0) { // Figure out which position mismatched uint64_t diff2 = diff; mmpos1 = 31; if((diff & U64(0xffffffff)) == 0) { diff >>= U64(32); mmpos1 -= 16; } assert_neq(0, diff); if((diff & U64(0xffff)) == 0) { diff >>= U64(16); mmpos1 -= 8; } assert_neq(0, diff); if((diff & U64(0xff)) == 0) { diff >>= U64(8); mmpos1 -= 4; } assert_neq(0, diff); if((diff & U64(0xf)) == 0) { diff >>= U64(4); mmpos1 -= 2; } assert_neq(0, diff); if((diff & U64(0x3)) == 0) { mmpos1--; } assert_neq(0, diff); assert_geq(mmpos1, 0); assert_lt(mmpos1, 32); mmpos1 -= anchorCushion; refc1 = "ACGT"[(int)ref[rir + mmpos1]]; if(diffs > 1) { // Figure out the second mismatched position ASSERT_ONLY(uint64_t origDiff2 = diff2); diff2 &= ~(U64(0xc000000000000000) >> (uint64_t)((mmpos1+anchorCushion) << 1)); assert_neq(diff2, origDiff2); mmpos2 = 31; if((diff2 & U64(0xffffffff)) == 0) { diff2 >>= U64(32); mmpos2 -= 16; } assert_neq(0, diff2); if((diff2 & U64(0xffff)) == 0) { diff2 >>= U64(16); mmpos2 -= 8; } assert_neq(0, diff2); if((diff2 & U64(0xff)) == 0) { diff2 >>= U64(8); mmpos2 -= 4; } assert_neq(0, diff2); if((diff2 & U64(0xf)) == 0) { diff2 >>= U64(4); mmpos2 -= 2; } assert_neq(0, diff2); if((diff2 & U64(0x3)) == 0) { mmpos2--; } assert_neq(0, diff2); assert_geq(mmpos2, 0); assert_lt(mmpos2, 32); mmpos2 -= anchorCushion; assert_neq(mmpos1, mmpos2); refc2 = "ACGT"[(int)ref[rir + mmpos2]]; if(mmpos2 < mmpos1) { uint32_t mmtmp = mmpos1; mmpos1 = mmpos2; mmpos2 = mmtmp; int refctmp = refc1; refc1 = refc2; refc2 = refctmp; } assert_lt(mmpos1, mmpos2); } } // Now extend the anchor into a longer alignment bool foundHit = true; if(anchorOverhang > 0) { assert_leq(ri + anchorBitPairs + anchorOverhang, end); bool skipCandidate = false; for(uint32_t j = 0; j < anchorOverhang; j++) { int rc = (int)ref[rir + 32 + j]; if(rc == 4) { // Oops, encountered an N in the reference in // the overhang portion of the candidate // alignment // (Note that we inverted hi earlier) if(hi) { // Right-to-left skipRightToLefts = anchorOverhang - j - 1; } else { // Left-to-right skipLeftToRights = anchorBitPairs + j; } skipCandidate = true; // Skip this candidate break; } if((int)qry[32 + j] != rc) { if(++diffs > 2) { foundHit = false; break; } else if(diffs == 2) { mmpos2 = 32 + j; refc2 = "ACGT"[(int)ref[rir + 32 + j]]; } else { assert_eq(1, diffs); mmpos1 = 32 + j; refc1 = "ACGT"[(int)ref[rir + 32 + j]]; } } } if(skipCandidate) continue; } if(!foundHit) continue; if(pairs != NULL) { TU64Pair p; if(ri < aoff) { // By convention, the upstream mate's // coordinates go in the 'first' field p.first = ((uint64_t)tidx << 32) | (uint64_t)ri; p.second = ((uint64_t)tidx << 32) | (uint64_t)aoff; } else { p.second = ((uint64_t)tidx << 32) | (uint64_t)ri; p.first = ((uint64_t)tidx << 32) | (uint64_t)aoff; } if(pairs->find(p) != pairs->end()) { // We already found this hit! Continue. ASSERT_ONLY(duplicates++); ASSERT_ONLY(r2i++); continue; } else { // Record this hit pairs->insert(p); } } assert_leq(diffs, 2); assert_lt(r2i, r2.size()); assert_eq(re2[r2i], ri); ranges.resize(ranges.size()+1); Range& range = ranges.back(); assert_eq(diffs, r2[r2i].numMms); range.stratum = diffs; range.numMms = diffs; assert_eq(0, range.mms.size()); assert_eq(0, range.refcs.size()); if(diffs > 0) { assert_neq(mmpos1, 0xffffffff); assert_eq(mmpos1, r2[r2i].mms[0]); assert_neq(-1, refc1); assert_eq(refc1, r2[r2i].refcs[0]); range.mms.push_back(mmpos1); range.refcs.push_back(refc1); if(diffs > 1) { assert_neq(mmpos2, 0xffffffff); assert_eq(mmpos2, r2[r2i].mms[1]); assert_neq(-1, refc2); assert_eq(refc2, r2[r2i].refcs[1]); range.mms.push_back(mmpos2); range.refcs.push_back(refc2); } } ASSERT_ONLY(r2i++); results.push_back(ri); if(--numToFind == 0) return; } assert_leq(duplicates, r2.size()); assert_geq(r2.size() - duplicates, ranges.size() - rangesInitSz); return; // no hit } }; /** * Concrete RefAligner for finding nearby 2-mismatch hits given an * anchor hit. */ template class ThreeMMRefAligner : public RefAligner { typedef seqan::String TDna5Str; typedef seqan::String TCharStr; typedef std::vector TRangeVec; typedef std::vector TU32Vec; typedef std::pair TU64Pair; typedef std::set TSetPairs; public: ThreeMMRefAligner(bool color, bool verbose, bool quiet) : RefAligner(color, verbose, quiet) { } virtual ~ThreeMMRefAligner() { } protected: /** * Because we're doing end-to-end exact, we don't care which end of * 'qry' is the 5' end. */ void naiveFind(uint32_t numToFind, uint32_t tidx, uint8_t* ref, const TDna5Str& qry, const TCharStr& quals, uint32_t begin, uint32_t end, TRangeVec& ranges, TU32Vec& results, TSetPairs* pairs, uint32_t aoff, bool seedOnLeft) const { assert_gt(numToFind, 0); const uint32_t qlen = seqan::length(qry); assert_geq(end - begin, qlen); // caller should have checked this assert_gt(end, begin); assert_gt(qlen, 0); uint32_t qend = end - qlen; uint32_t lim = qend - begin; uint32_t halfway = begin + (lim >> 1); bool hi = false; for(uint32_t i = 1; i <= lim+1; i++) { uint32_t ri; // leftmost position in candidate alignment uint32_t rir; // same, minus begin; for indexing into ref[] if(hi) { ri = halfway + (i >> 1); rir = ri - begin; assert_leq(ri, qend); } else { ri = halfway - (i >> 1); rir = ri - begin; assert_geq(ri, begin); } hi = !hi; // Do the naive comparison bool match = true; int refc1 = -1; uint32_t mmOff1 = 0xffffffff; int refc2 = -1; uint32_t mmOff2 = 0xffffffff; int refc3 = -1; uint32_t mmOff3 = 0xffffffff; int mms = 0; for(uint32_t j = 0; j < qlen; j++) { #if 0 // Count Ns in the reference as mismatches const int q = (int)qry[j]; const int r = (int)ref[rir + j]; assert_leq(q, 4); assert_leq(r, 4); if(q == 4 || r == 4 || q != r) { #else // Disallow alignments that involve an N in the // reference const int r = (int)ref[rir + j]; if(r & 4) { // N in reference; bail match = false; break; } const int q = (int)qry[j]; assert_leq(q, 4); assert_lt(r, 4); if(q != r) { #endif // Mismatch! if(++mms > 3) { // Too many; reject this alignment match = false; break; } else if(mms == 3) { // Second one; remember offset and ref char refc3 = "ACGTN"[r]; mmOff3 = j; } else if(mms == 2) { // Second one; remember offset and ref char refc2 = "ACGTN"[r]; mmOff2 = j; } else { assert_eq(1, mms); // First one; remember offset and ref char refc1 = "ACGTN"[r]; mmOff1 = j; } } } if(match) { assert_leq(mms, 3); ranges.resize(ranges.size()+1); Range& range = ranges.back(); range.stratum = mms; range.numMms = mms; assert_eq(0, range.mms.size()); assert_eq(0, range.refcs.size()); if(mms > 0) { assert_lt(mmOff1, qlen); assert(refc1 == 'A' || refc1 == 'C' || refc1 == 'G' || refc1 == 'T'); range.mms.push_back(mmOff1); range.refcs.push_back(refc1); if(mms > 1) { assert_lt(mmOff2, qlen); assert(refc2 == 'A' || refc2 == 'C' || refc2 == 'G' || refc2 == 'T'); range.mms.push_back(mmOff2); range.refcs.push_back(refc2); if(mms > 2) { assert_eq(3, mms); assert_lt(mmOff3, qlen); assert(refc3 == 'A' || refc3 == 'C' || refc3 == 'G' || refc3 == 'T'); range.mms.push_back(mmOff3); range.refcs.push_back(refc3); } } } results.push_back(ri); } } return; } /** * Because we're doing end-to-end exact, we don't care which end of * 'qry' is the 5' end. */ virtual void anchor64Find(uint32_t numToFind, uint32_t tidx, uint8_t* ref, const TDna5Str& qry, const TCharStr& quals, uint32_t begin, uint32_t end, TRangeVec& ranges, TU32Vec& results, TSetPairs* pairs = NULL, uint32_t aoff = 0xffffffff, bool seedOnLeft = false) const { assert_gt(numToFind, 0); ASSERT_ONLY(const uint32_t rangesInitSz = ranges.size()); ASSERT_ONLY(uint32_t duplicates = 0); ASSERT_ONLY(uint32_t r2i = 0); const uint32_t qlen = seqan::length(qry); assert_geq(end - begin, qlen); // caller should have checked this assert_gt(end, begin); assert_gt(qlen, 0); #ifndef NDEBUG // Get results from the naive matcher for sanity-checking TRangeVec r2; TU32Vec re2; naiveFind(numToFind, tidx, ref, qry, quals, begin, end, r2, re2, pairs, aoff, seedOnLeft); #endif const uint32_t anchorBitPairs = min(qlen, 32); const int lhsShift = ((anchorBitPairs - 1) << 1); const uint32_t anchorCushion = 32 - anchorBitPairs; // anchorOverhang = # read bases not included in the anchor const uint32_t anchorOverhang = (qlen <= 32 ? 0 : (qlen - 32)); const uint32_t lim = end - qlen - begin; const uint32_t halfway = begin + (lim >> 1); uint64_t anchor = U64(0); uint64_t buffw = U64(0); // rotating ref sequence buffer // OR the 'diff' buffer with this so that we can always count // 'N's as mismatches uint64_t diffMask = U64(0); // Set up a mask that we'll apply to the two bufs every round // to discard bits that were rotated out of the anchor area uint64_t clearMask = U64(0xffffffffffffffff); bool useMask = false; if(anchorBitPairs < 32) { clearMask >>= ((32-anchorBitPairs) << 1); useMask = true; } int nsInAnchor = 0; uint32_t nPoss = 0; int nPos1 = -1; int nPos2 = -1; int nPos3 = -1; uint32_t skipLeftToRights = 0; uint32_t skipRightToLefts = 0; // Construct the 'anchor' 64-bit buffer so that it holds all of // the first 'anchorBitPairs' bit pairs of the query. for(uint32_t i = 0; i < anchorBitPairs; i++) { int c = (int)qry[i]; // next query character int r = (int)ref[halfway - begin + i]; // next reference character if(r & 4) { r = 0; // The right-to-left direction absorbs the candidate // alignment based at 'halfway'; so skipLeftToRights is // i, not i+1 skipLeftToRights = max(skipLeftToRights, i); skipRightToLefts = max(skipRightToLefts, anchorBitPairs - i); } assert_leq(c, 4); assert_lt(r, 4); // Special case: query has an 'N' if(c == 4) { if(++nsInAnchor > 3) { // More than two 'N's in the anchor region; can't // possibly have a 2-mismatch hit anywhere assert_eq(r2.size(), ranges.size() - rangesInitSz); return; // can't match if query has Ns } else if(nsInAnchor == 3) { nPos3 = (int)i; nPoss++; } else if(nsInAnchor == 2) { nPos2 = (int)i; nPoss++; } else { assert_eq(1, nsInAnchor); nPos1 = (int)i; nPoss++; } // Make it look like an 'A' in the anchor c = 0; diffMask = (diffMask << U64(2)) | U64(1); } else { diffMask <<= U64(2); } anchor = ((anchor << U64(2)) | c); buffw = ((buffw << U64(2)) | r); } assert_leq(nPoss, 3); // Check whether read is disqualified by Ns outside of the anchor // region for(uint32_t i = anchorBitPairs; i < qlen; i++) { if((int)qry[i] == 4) { if(++nsInAnchor > 3) { assert_eq(r2.size(), ranges.size() - rangesInitSz); return; // can't match if query has Ns } } } uint64_t bufbw = buffw; // We're moving the right-hand edge of the anchor along until // it's 'anchorOverhang' chars from the end of the target region. // Note that we're not making a 3'/5' distinction here; if we // were, we might need to make the 'anchorOverhang' adjustment on // the left end of the range rather than the right. bool hi = false; uint32_t riHi = halfway; uint32_t rirHi = halfway - begin; uint32_t rirHiAnchor = rirHi + anchorBitPairs - 1; uint32_t riLo = halfway + 1; uint32_t rirLo = halfway - begin + 1; for(uint32_t i = 1; i <= lim + 1; i++) { int r; // new reference char uint64_t diff; assert_lt(skipLeftToRights, qlen); assert_leq(skipRightToLefts, qlen); if(hi) { hi = false; // Moving left-to-right riHi++; rirHi++; rirHiAnchor++; r = (int)ref[rirHiAnchor]; if(r & 4) { r = 0; skipLeftToRights = anchorBitPairs; } assert_lt(r, 4); // Bring in new base pair at the least significant // position buffw = ((buffw << U64(2)) | r); if(useMask) buffw &= clearMask; if(skipLeftToRights > 0) { skipLeftToRights--; continue; } diff = (buffw ^ anchor) | diffMask; } else { hi = true; // Moving right-to-left riLo--; rirLo--; r = (int)ref[rirLo]; if(r & 4) { r = 0; skipRightToLefts = qlen; } assert_lt(r, 4); if(i >= 2) { bufbw >>= U64(2); // Bring in new base pair at the most significant // position bufbw |= ((uint64_t)r << lhsShift); } if(skipRightToLefts > 0) { skipRightToLefts--; continue; } diff = (bufbw ^ anchor) | diffMask; } if((diff & U64(0xffff000000000000)) && (diff & U64(0x0000ffff00000000)) && (diff & U64(0x00000000ffff0000)) && (diff & U64(0x000000000000ffff))) continue; uint32_t ri = hi ? riLo : riHi; uint32_t rir = hi ? rirLo : rirHi; // Could use pop count uint8_t *diff8 = reinterpret_cast(&diff); // As a first cut, see if there are too many mismatches in // the first and last parts of the anchor uint32_t diffs = u8toMms[(int)diff8[0]] + u8toMms[(int)diff8[7]]; if(diffs > 3) continue; diffs += u8toMms[(int)diff8[1]] + u8toMms[(int)diff8[2]] + u8toMms[(int)diff8[3]] + u8toMms[(int)diff8[4]] + u8toMms[(int)diff8[5]] + u8toMms[(int)diff8[6]]; uint32_t mmpos1 = 0xffffffff; int refc1 = -1; uint32_t mmpos2 = 0xffffffff; int refc2 = -1; uint32_t mmpos3 = 0xffffffff; int refc3 = -1; if(diffs > 3) { // Too many differences continue; } else if(nPoss > 1 && diffs == nPoss) { // There was one difference, but there was also one N, // so we already know where the difference is mmpos1 = nPos1; refc1 = "ACGT"[(int)ref[rir + nPos1]]; if(nPoss > 1) { mmpos2 = nPos2; refc2 = "ACGT"[(int)ref[rir + nPos2]]; if(nPoss > 2) { mmpos3 = nPos3; refc3 = "ACGT"[(int)ref[rir + nPos3]]; } } } else if(diffs > 0) { // Figure out which position mismatched uint64_t diff2 = diff; mmpos1 = 31; if((diff & U64(0xffffffff)) == 0) { diff >>= U64(32); mmpos1 -= 16; } assert_neq(0, diff); if((diff & U64(0xffff)) == 0) { diff >>= U64(16); mmpos1 -= 8; } assert_neq(0, diff); if((diff & U64(0xff)) == 0) { diff >>= U64(8); mmpos1 -= 4; } assert_neq(0, diff); if((diff & U64(0xf)) == 0) { diff >>= U64(4); mmpos1 -= 2; } assert_neq(0, diff); if((diff & U64(0x3)) == 0) { mmpos1--; } assert_neq(0, diff); assert_geq(mmpos1, 0); assert_lt(mmpos1, 32); mmpos1 -= anchorCushion; refc1 = "ACGT"[(int)ref[rir + mmpos1]]; if(diffs > 1) { // Figure out the second mismatched position diff2 &= ~(U64(0xc000000000000000) >> (uint64_t)((mmpos1 + anchorCushion) << 1)); uint64_t diff3 = diff2; mmpos2 = 31; if((diff2 & U64(0xffffffff)) == 0) { diff2 >>= U64(32); mmpos2 -= 16; } assert_neq(0, diff2); if((diff2 & U64(0xffff)) == 0) { diff2 >>= U64(16); mmpos2 -= 8; } assert_neq(0, diff2); if((diff2 & U64(0xff)) == 0) { diff2 >>= U64(8); mmpos2 -= 4; } assert_neq(0, diff2); if((diff2 & U64(0xf)) == 0) { diff2 >>= U64(4); mmpos2 -= 2; } assert_neq(0, diff2); if((diff2 & U64(0x3)) == 0) { mmpos2--; } assert_neq(0, diff2); mmpos2 -= anchorCushion; assert_geq(mmpos2, 0); assert_lt(mmpos2, 32); assert_neq(mmpos1, mmpos2); refc2 = "ACGT"[(int)ref[rir + mmpos2]]; uint32_t mmpos2orig = mmpos2; if(mmpos2 < mmpos1) { uint32_t mmtmp = mmpos1; mmpos1 = mmpos2; mmpos2 = mmtmp; int refctmp = refc1; refc1 = refc2; refc2 = refctmp; } assert_lt(mmpos1, mmpos2); if(diffs > 2) { // Figure out the second mismatched position diff3 &= ~(U64(0xc000000000000000) >> (uint64_t)((mmpos2orig + anchorCushion) << 1)); mmpos3 = 31; if((diff3 & U64(0xffffffff)) == 0) { diff3 >>= U64(32); mmpos3 -= 16; } assert_neq(0, diff3); if((diff3 & U64(0xffff)) == 0) { diff3 >>= U64(16); mmpos3 -= 8; } assert_neq(0, diff3); if((diff3 & U64(0xff)) == 0) { diff3 >>= U64(8); mmpos3 -= 4; } assert_neq(0, diff3); if((diff3 & U64(0xf)) == 0) { diff3 >>= U64(4); mmpos3 -= 2; } assert_neq(0, diff3); if((diff3 & U64(0x3)) == 0) { mmpos3--; } assert_neq(0, diff3); mmpos3 -= anchorCushion; assert_geq(mmpos3, 0); assert_lt(mmpos3, 32); assert_neq(mmpos1, mmpos3); assert_neq(mmpos2, mmpos3); refc3 = "ACGT"[(int)ref[rir + mmpos3]]; if(mmpos3 < mmpos1) { uint32_t mmtmp = mmpos1; mmpos1 = mmpos3; mmpos3 = mmpos2; mmpos2 = mmtmp; int refctmp = refc1; refc1 = refc3; refc3 = refc2; refc2 = refctmp; } else if(mmpos3 < mmpos2) { uint32_t mmtmp = mmpos2; mmpos2 = mmpos3; mmpos3 = mmtmp; int refctmp = refc2; refc2 = refc3; refc3 = refctmp; } assert_lt(mmpos1, mmpos2); assert_lt(mmpos2, mmpos3); } } } // Now extend the anchor into a longer alignment bool foundHit = true; if(anchorOverhang > 0) { assert_leq(ri + anchorBitPairs + anchorOverhang, end); bool skipCandidate = false; for(uint32_t j = 0; j < anchorOverhang; j++) { int rc = (int)ref[rir + 32 + j]; if(rc == 4) { // Oops, encountered an N in the reference in // the overhang portion of the candidate // alignment // (Note that we inverted hi earlier) if(hi) { // Right-to-left skipRightToLefts = anchorOverhang - j - 1; } else { // Left-to-right skipLeftToRights = anchorBitPairs + j; } skipCandidate = true; // Skip this candidate break; } if((int)qry[32 + j] != rc) { if(++diffs > 3) { foundHit = false; break; } else if(diffs == 3) { mmpos3 = 32 + j; refc3 = "ACGT"[(int)ref[rir + 32 + j]]; } else if(diffs == 2) { mmpos2 = 32 + j; refc2 = "ACGT"[(int)ref[rir + 32 + j]]; } else { assert_eq(1, diffs); mmpos1 = 32 + j; refc1 = "ACGT"[(int)ref[rir + 32 + j]]; } } } if(skipCandidate) continue; } if(!foundHit) continue; if(pairs != NULL) { TU64Pair p; if(ri < aoff) { // By convention, the upstream mate's // coordinates go in the 'first' field p.first = ((uint64_t)tidx << 32) | (uint64_t)ri; p.second = ((uint64_t)tidx << 32) | (uint64_t)aoff; } else { p.second = ((uint64_t)tidx << 32) | (uint64_t)ri; p.first = ((uint64_t)tidx << 32) | (uint64_t)aoff; } if(pairs->find(p) != pairs->end()) { // We already found this hit! Continue. ASSERT_ONLY(duplicates++); ASSERT_ONLY(r2i++); continue; } else { // Record this hit pairs->insert(p); } } assert_leq(diffs, 3); assert_lt(r2i, r2.size()); assert_eq(re2[r2i], ri); ranges.resize(ranges.size()+1); Range& range = ranges.back(); assert_eq(diffs, r2[r2i].numMms); range.stratum = diffs; range.numMms = diffs; assert_eq(0, range.mms.size()); assert_eq(0, range.refcs.size()); if(diffs > 0) { assert_neq(mmpos1, 0xffffffff); assert_eq(mmpos1, r2[r2i].mms[0]); assert_neq(-1, refc1); assert_eq(refc1, r2[r2i].refcs[0]); range.mms.push_back(mmpos1); range.refcs.push_back(refc1); if(diffs > 1) { assert_neq(mmpos2, 0xffffffff); assert_eq(mmpos2, r2[r2i].mms[1]); assert_neq(-1, refc2); assert_eq(refc2, r2[r2i].refcs[1]); range.mms.push_back(mmpos2); range.refcs.push_back(refc2); if(diffs > 2) { assert_neq(mmpos3, 0xffffffff); assert_eq(mmpos3, r2[r2i].mms[2]); assert_neq(-1, refc3); assert_eq(refc3, r2[r2i].refcs[2]); range.mms.push_back(mmpos3); range.refcs.push_back(refc3); } } } ASSERT_ONLY(r2i++); results.push_back(ri); if(--numToFind == 0) return; } assert_leq(duplicates, r2.size()); assert_geq(r2.size() - duplicates, ranges.size() - rangesInitSz); return; // no hit } }; /** * Concrete RefAligner for finding nearby 1-mismatch hits given an * anchor hit. */ template class Seed0RefAligner : public RefAligner { typedef seqan::String TDna5Str; typedef seqan::String TCharStr; typedef std::vector TRangeVec; typedef std::vector TU32Vec; typedef std::pair TU64Pair; typedef std::set TSetPairs; public: Seed0RefAligner(bool color, bool verbose, bool quiet, uint32_t seedLen, uint32_t qualMax, bool maqPenalty) : RefAligner(color, verbose, quiet, seedLen, qualMax, maqPenalty) { } virtual ~Seed0RefAligner() { } protected: /** * This schematic shows the roles played by the begin, qbegin, end, * qend, halfway, slen, qlen, and lim variables: * * seedOnLeft == true: * * |< lim >|< qlen >| * -------------------------------------------------------------- * | | slen | qlen-slen | | slen | qlen-slen | * -------------------------------------------------------------- * ^ ^ ^ ^ * begin & qbegin halfway qend end * * seedOnLeft == false: * * |< qlen >|< lim >| * -------------------------------------------------------------- * | qlen-slen | slen | | qlen-slen | slen | | * -------------------------------------------------------------- * ^ ^ ^ ^ * begin qbegin halfway qend & end * * Note that, for seeds longer than 32 base-pairs, the seed is * further subdivided into a 32-bit anchor and a seed overhang of * length > 0. */ void naiveFind(uint32_t numToFind, uint32_t tidx, uint8_t* ref, const TDna5Str& qry, const TCharStr& quals, uint32_t begin, uint32_t end, TRangeVec& ranges, TU32Vec& results, TSetPairs* pairs, uint32_t aoff, bool seedOnLeft) const { assert_gt(numToFind, 0); assert_gt(end, begin); const uint32_t qlen = seqan::length(qry); assert_gt(qlen, 0); assert_geq(end - begin, qlen); // caller should have checked this assert_gt(this->seedLen_, 0); const uint32_t slen = min(qlen, this->seedLen_); uint32_t qend = end; uint32_t qbegin = begin; // If the seed is on the left-hand side of the alignment, then // leave a gap at the right-hand side of the interval; // otherwise, do the opposite if(seedOnLeft) { // Leave gap on right-hand side of the interval qend -= qlen; } else { // Leave gap on left-hand side of the interval qbegin += qlen; } // lim = number of alignments to try const uint32_t lim = qend - qbegin; // halfway = position in the reference to start at (and then // we work our way out to the right and to the left). const uint32_t halfway = qbegin + (lim >> 1); // Vectors for holding edit information std::vector nonSeedMms; std::vector nonSeedRefcs; bool hi = false; for(uint32_t i = 1; i <= lim+1; i++) { uint32_t ri; // leftmost position in candidate alignment uint32_t rir; // same, minus begin; for indexing into ref[] if(hi) { ri = halfway + (i >> 1); rir = ri - begin; assert_leq(ri, qend); } else { ri = halfway - (i >> 1); rir = ri - begin; assert_geq(ri, begin); } hi = !hi; // Do the naive comparison bool match = true; int mms = 0; unsigned int ham = 0; nonSeedMms.clear(); nonSeedRefcs.clear(); // Walk through each position of the alignment for(uint32_t jj = 0; jj < qlen; jj++) { uint32_t j = jj; if(!seedOnLeft) { // If seed is on the right, scan right-to-left j = qlen - jj - 1; } else { // Go left-to-right } uint32_t rirj = rir + j; if(!seedOnLeft) { assert_geq(rir, jj); rirj = rir - jj - 1; } #if 0 // Count Ns in the reference as mismatches const int q = (int)qry[j]; const int r = (int)ref[rirj]; assert_leq(q, 4); assert_leq(r, 4); if(q == 4 || r == 4 || q != r) { #else // Disallow alignments that involve an N in the // reference const int r = (int)ref[rirj]; if(r & 4) { // N in reference; bail on this alignment match = false; break; } const int q = (int)qry[j]; assert_leq(q, 4); assert_lt(r, 4); if(q != r) { #endif // Mismatch! if(jj < slen) { // More than one mismatch in the anchor; reject match = false; break; } uint8_t qual = phredCharToPhredQual(quals[j]); ham += mmPenalty(this->maqPenalty_, qual); if(ham > this->qualMax_) { // Exceeded quality ceiling; reject match = false; break; } else { // Legal mismatch outside of the anchor; record it mms++; nonSeedMms.push_back(j); assert_leq(nonSeedMms.size(), (size_t)mms); nonSeedRefcs.push_back("ACGTN"[r]); } } } if(match) { ranges.resize(ranges.size()+1); Range& range = ranges.back(); range.stratum = 0; range.numMms = mms; assert_eq(0, range.mms.size()); assert_eq(0, range.refcs.size()); if(mms >= 1) { // Be careful to add edits in left-to-right order // with respect to the read/alignment const size_t nonSeedMmsSz = nonSeedMms.size(); if(nonSeedMmsSz > 0) { if(seedOnLeft) { for(size_t k = 0; k < nonSeedMmsSz; k++) { range.mms.push_back(nonSeedMms[k]); range.refcs.push_back(nonSeedRefcs[k]); } } else { for(size_t k = nonSeedMmsSz; k > 0; k--) { range.mms.push_back(nonSeedMms[k-1]); range.refcs.push_back(nonSeedRefcs[k-1]); } } } } assert_eq((size_t)mms, range.mms.size()); assert_eq((size_t)mms, range.refcs.size()); if(seedOnLeft) { results.push_back(ri); } else { results.push_back(ri - qlen); } } } return; } /** * This schematic shows the roles played by the begin, qbegin, end, * qend, halfway, slen, qlen, and lim variables: * * seedOnLeft == true: * * |< lim >|< qlen >| * -------------------------------------------------------------- * | | slen | qlen-slen | | slen | qlen-slen | * -------------------------------------------------------------- * ^ ^ ^ ^ * begin & qbegin halfway qend end * * seedOnLeft == false: * * |< lim >| * -------------------------------------------------------------- * | qlen-slen | | qlen-slen | slen | | slen | * -------------------------------------------------------------- * ^ ^ ^ ^ ^ * begin qbegin halfway qend end * * Note that, for seeds longer than 32 base-pairs, the seed is * further subdivided into a 32-bit anchor and a seed overhang of * length > 0. */ virtual void anchor64Find(uint32_t numToFind, uint32_t tidx, uint8_t* ref, const TDna5Str& qry, const TCharStr& quals, uint32_t begin, uint32_t end, TRangeVec& ranges, TU32Vec& results, TSetPairs* pairs = NULL, uint32_t aoff = 0xffffffff, bool seedOnLeft = false) const { assert_gt(numToFind, 0); ASSERT_ONLY(const uint32_t rangesInitSz = ranges.size()); ASSERT_ONLY(uint32_t duplicates = 0); ASSERT_ONLY(uint32_t r2i = 0); const uint32_t qlen = seqan::length(qry); assert_gt(qlen, 0); assert_gt(end, begin); assert_geq(end - begin, qlen); // caller should have checked this assert_gt(this->seedLen_, 0); uint32_t slen = min(qlen, this->seedLen_); #ifndef NDEBUG // Get results from the naive matcher for sanity-checking TRangeVec r2; TU32Vec re2; naiveFind(numToFind, tidx, ref, qry, quals, begin, end, r2, re2, pairs, aoff, seedOnLeft); #endif const uint32_t anchorBitPairs = min(slen, 32); const int lhsShift = ((anchorBitPairs - 1) << 1); ASSERT_ONLY(const uint32_t anchorCushion = 32 - anchorBitPairs); // seedAnchorOverhang = # seed bases not included in the anchor const uint32_t seedAnchorOverhang = (slen <= anchorBitPairs ? 0 : (slen - anchorBitPairs)); // seedAnchorOverhang = # seed bases not included in the anchor const uint32_t readSeedOverhang = (slen == qlen ? 0 : (qlen - slen)); assert(anchorCushion == 0 || seedAnchorOverhang == 0); assert_eq(qlen, readSeedOverhang + slen); uint32_t qend = end; uint32_t qbegin = begin; if(seedOnLeft) { // Leave read-sized gap on right-hand side of the interval qend -= qlen; } else { // Leave seed-sized gap on right-hand side and // non-seed-sized gap on the left-hand side qbegin += readSeedOverhang; qend -= slen; } // lim = # possible alignments in the range const uint32_t lim = qend - qbegin; // halfway = point on the genome to radiate out from const uint32_t halfway = qbegin + (lim >> 1); uint64_t anchor = U64(0); uint64_t buffw = U64(0); // rotating ref sequence buffer // Set up a mask that we'll apply to the two bufs every round // to discard bits that were rotated out of the anchor area uint64_t clearMask = U64(0xffffffffffffffff); bool useMask = false; if(anchorBitPairs < 32) { clearMask >>= ((32-anchorBitPairs) << 1); useMask = true; } uint32_t skipLeftToRights = 0; uint32_t skipRightToLefts = 0; const uint32_t halfwayRi = halfway - begin; // Construct the 'anchor' 64-bit buffer so that it holds all of // the first 'anchorBitPairs' bit pairs of the query. for(uint32_t ii = 0; ii < anchorBitPairs; ii++) { uint32_t i = ii; if(!seedOnLeft) { // Fill in the anchor using characters from the right- // hand side of the query (but take the characters in // left-to-right order) i = qlen - slen + ii; } int c = (int)qry[i]; // next query character int r = (int)ref[halfwayRi + ii]; // next reference character if(r & 4) { // The reference character is an N; to mimic the // behavior of BW alignment, we have to skip all // alignments that involve an N in the reference. Set // the skip* variables accordingly. r = 0; uint32_t lrSkips = ii; uint32_t rlSkips = qlen - ii; if(!seedOnLeft && readSeedOverhang) { lrSkips += readSeedOverhang; assert_geq(rlSkips, readSeedOverhang); rlSkips -= readSeedOverhang; } // The right-to-left direction absorbs the candidate // alignment based at 'halfway' skipLeftToRights = max(skipLeftToRights, lrSkips); skipRightToLefts = max(skipRightToLefts, rlSkips); assert_leq(skipLeftToRights, qlen); assert_leq(skipRightToLefts, qlen); } assert_leq(c, 4); assert_lt(r, 4); // Special case: query has an 'N' if(c == 4) { // One or more 'N's in the anchor region; can't // possibly have a 0-mismatch hit anywhere assert_eq(r2.size(), ranges.size() - rangesInitSz); return; // can't match if query has Ns } anchor = ((anchor << U64(2)) | c); buffw = ((buffw << U64(2)) | r); } // Check whether read is disqualified by Ns inside the seed // region but outside the anchor region if(seedAnchorOverhang) { assert_lt(anchorBitPairs, slen); for(uint32_t ii = anchorBitPairs; ii < slen; ii++) { uint32_t i = ii; if(!seedOnLeft) { i = qlen - slen + ii; } if((int)qry[i] == 4) { assert_eq(r2.size(), ranges.size() - rangesInitSz); return; // can't match if query has Ns } } } else { assert_eq(anchorBitPairs, slen); } uint64_t bufbw = buffw; // Slide the anchor out in either direction, alternating // between right-to-left and left-to-right shifts, until all of // the positions from qbegin to qend have been covered. bool hi = false; uint32_t riHi = halfway; uint32_t rirHi = halfway - begin; uint32_t rirHiAnchor = rirHi + anchorBitPairs - 1; uint32_t riLo = halfway + 1; uint32_t rirLo = halfway - begin + 1; uint32_t lrSkips = anchorBitPairs; uint32_t rlSkips = qlen; if(!seedOnLeft && readSeedOverhang) { lrSkips += readSeedOverhang; assert_geq(rlSkips, readSeedOverhang); rlSkips -= readSeedOverhang; } for(uint32_t i = 1; i <= lim + 1; i++) { int r; // new reference char uint64_t diff; assert_leq(skipLeftToRights, qlen); assert_leq(skipRightToLefts, qlen); if(hi) { hi = false; // Moving left-to-right riHi++; rirHi++; rirHiAnchor++; r = (int)ref[rirHiAnchor]; if(r & 4) { r = 0; skipLeftToRights = lrSkips; } assert_lt(r, 4); // Bring in new base pair at the least significant // position buffw = ((buffw << U64(2)) | r); if(useMask) buffw &= clearMask; if(skipLeftToRights > 0) { skipLeftToRights--; continue; } diff = buffw ^ anchor; } else { hi = true; // Moving right-to-left riLo--; rirLo--; r = (int)ref[rirLo]; if(r & 4) { r = 0; skipRightToLefts = rlSkips; } assert_lt(r, 4); if(i >= 2) { bufbw >>= U64(2); // Bring in new base pair at the most significant // position bufbw |= ((uint64_t)r << lhsShift); } if(skipRightToLefts > 0) { skipRightToLefts--; continue; } diff = bufbw ^ anchor; } if(diff) continue; uint32_t ri = hi ? riLo : riHi; uint32_t rir = hi ? rirLo : rirHi; unsigned int ham = 0; // If the seed is longer than the anchor, then scan the // rest of the seed characters bool foundHit = true; if(seedAnchorOverhang) { for(uint32_t j = 0; j < seedAnchorOverhang; j++) { int rc = (int)ref[rir + anchorBitPairs + j]; if(rc == 4) { // Oops, encountered an N in the reference in // the overhang portion of the candidate // alignment // (Note that we inverted hi earlier) if(hi) { // Right-to-left // Skip out of the seedAnchorOverhang assert_eq(0, skipRightToLefts); skipRightToLefts = seedAnchorOverhang - j - 1; if(seedOnLeft) { // ...and skip out of the rest of the read skipRightToLefts += readSeedOverhang; } } else { // Left-to-right // Skip out of the seedAnchorOverhang assert_eq(0, skipLeftToRights); skipLeftToRights = anchorBitPairs + j; if(!seedOnLeft) { // ...and skip out of the rest of the read skipLeftToRights += readSeedOverhang; } } foundHit = false; // Skip this candidate break; } uint32_t qoff = anchorBitPairs + j; if(!seedOnLeft) { qoff += readSeedOverhang; } assert_lt(qoff, qlen); if((int)qry[qoff] != rc) { foundHit = false; break; } } if(!foundHit) continue; } // If the read is longer than the seed, then scan the rest // of the read characters; mismatches no longer count // toward the stratum or the 1-mm limit. // Vectors for holding edit information std::vector nonSeedMms; std::vector nonSeedRefcs; int mms = 0; // start counting total mismatches if((qlen - slen) > 0) { // Going left-to-right for(uint32_t j = 0; j < readSeedOverhang; j++) { uint32_t roff = rir + slen + j; uint32_t qoff = slen + j; if(!seedOnLeft) { assert_geq(roff, qlen); roff -= qlen; qoff = j; } int rc = (int)ref[roff]; if(rc == 4) { // Oops, encountered an N in the reference in // the overhang portion of the candidate // alignment // (Note that we inverted hi earlier) if(hi) { // Right-to-left // Skip what's left of the readSeedOverhang skipRightToLefts = readSeedOverhang - j - 1; if(!seedOnLeft) { // ...and skip the seed if it's on the right skipRightToLefts += slen; } } else { // Left-to-right // Skip what we've matched of the overhang skipLeftToRights = j; if(seedOnLeft) { // ...and skip the seed if it's on the left skipLeftToRights += slen; } } foundHit = false; // Skip this candidate break; } if((int)qry[qoff] != rc) { // Calculate quality of mismatched base char q = phredCharToPhredQual(quals[qoff]); ham += mmPenalty(this->maqPenalty_, q); if(ham > this->qualMax_) { // Exceeded quality limit foundHit = false; break; } // Legal mismatch outside of the anchor; record it mms++; nonSeedMms.push_back(qoff); assert_leq(nonSeedMms.size(), (size_t)mms); nonSeedRefcs.push_back("ACGTN"[rc]); } } if(!foundHit) continue; } assert(foundHit); // Adjust ri if seed is on the right-hand side if(!seedOnLeft) { ri -= readSeedOverhang; rir -= readSeedOverhang; } if(pairs != NULL) { TU64Pair p; if(ri < aoff) { // By convention, the upstream mate's // coordinates go in the 'first' field p.first = ((uint64_t)tidx << 32) | (uint64_t)ri; p.second = ((uint64_t)tidx << 32) | (uint64_t)aoff; } else { p.second = ((uint64_t)tidx << 32) | (uint64_t)ri; p.first = ((uint64_t)tidx << 32) | (uint64_t)aoff; } if(pairs->find(p) != pairs->end()) { // We already found this hit! Continue. ASSERT_ONLY(duplicates++); ASSERT_ONLY(r2i++); continue; } else { // Record this hit pairs->insert(p); } } if(this->verbose_) { cout << "About to report seed0:" << endl; cout << " "; for(size_t i = 0; i < qlen; i++) { cout << (char)qry[i]; } cout << endl; cout << " "; for(size_t i = 0; i < qlen; i++) { cout << "ACGT"[ref[rir+i]]; } cout << endl; } assert_lt(r2i, r2.size()); assert_eq(re2[r2i], ri); ranges.resize(ranges.size()+1); Range& range = ranges.back(); assert_eq((size_t)mms, r2[r2i].numMms); range.stratum = 0; range.numMms = mms; assert_eq(0, range.mms.size()); assert_eq(0, range.refcs.size()); if(mms > 0) { ASSERT_ONLY(size_t mmcur = 0); const size_t nonSeedMmsSz = nonSeedMms.size(); for(size_t i = 0; i < nonSeedMmsSz; i++) { assert_neq(0xffffffff, nonSeedMms[i]); assert_lt(mmcur, (size_t)mms); assert_eq(nonSeedMms[i], r2[r2i].mms[mmcur]); range.mms.push_back(nonSeedMms[i]); assert_eq(nonSeedRefcs[i], r2[r2i].refcs[mmcur]); ASSERT_ONLY(mmcur++); range.refcs.push_back(nonSeedRefcs[i]); } assert_eq(mmcur, r2[r2i].mms.size()); } assert_eq((size_t)mms, range.mms.size()); assert_eq((size_t)mms, range.refcs.size()); ASSERT_ONLY(r2i++); results.push_back(ri); if(--numToFind == 0) return; } assert_leq(duplicates, r2.size()); assert_geq(r2.size() - duplicates, ranges.size() - rangesInitSz); return; // no hit } }; /** * Concrete RefAligner for finding nearby 1-mismatch hits given an * anchor hit. */ template class Seed1RefAligner : public RefAligner { typedef seqan::String TDna5Str; typedef seqan::String TCharStr; typedef std::vector TRangeVec; typedef std::vector TU32Vec; typedef std::pair TU64Pair; typedef std::set TSetPairs; public: Seed1RefAligner(bool color, bool verbose, bool quiet, uint32_t seedLen, uint32_t qualMax, bool maqPenalty) : RefAligner(color, verbose, quiet, seedLen, qualMax, maqPenalty) { } virtual ~Seed1RefAligner() { } protected: /** * This schematic shows the roles played by the begin, qbegin, end, * qend, halfway, slen, qlen, and lim variables: * * seedOnLeft == true: * * |< lim >|< qlen >| * -------------------------------------------------------------- * | | slen | qlen-slen | | slen | qlen-slen | * -------------------------------------------------------------- * ^ ^ ^ ^ * begin & qbegin halfway qend end * * seedOnLeft == false: * * |< qlen >|< lim >| * -------------------------------------------------------------- * | qlen-slen | slen | | qlen-slen | slen | | * -------------------------------------------------------------- * ^ ^ ^ ^ * begin qbegin halfway qend & end * * Note that, for seeds longer than 32 base-pairs, the seed is * further subdivided into a 32-bit anchor and a seed overhang of * length > 0. */ void naiveFind(uint32_t numToFind, uint32_t tidx, uint8_t* ref, const TDna5Str& qry, const TCharStr& quals, uint32_t begin, uint32_t end, TRangeVec& ranges, TU32Vec& results, TSetPairs* pairs, uint32_t aoff, bool seedOnLeft) const { assert_gt(numToFind, 0); assert_gt(end, begin); const uint32_t qlen = seqan::length(qry); assert_gt(qlen, 0); assert_geq(end - begin, qlen); // caller should have checked this assert_gt(this->seedLen_, 0); const uint32_t slen = min(qlen, this->seedLen_); uint32_t qend = end; uint32_t qbegin = begin; // If the seed is on the left-hand side of the alignment, then // leave a gap at the right-hand side of the interval; // otherwise, do the opposite if(seedOnLeft) { // Leave gap on right-hand side of the interval qend -= qlen; } else { // Leave gap on left-hand side of the interval qbegin += qlen; } // lim = number of alignments to try const uint32_t lim = qend - qbegin; // halfway = position in the reference to start at (and then // we work our way out to the right and to the left). const uint32_t halfway = qbegin + (lim >> 1); // Vectors for holding edit information std::vector nonSeedMms; assert_eq(0, nonSeedMms.size()); std::vector nonSeedRefcs; assert_eq(0, nonSeedRefcs.size()); bool hi = false; for(uint32_t i = 1; i <= lim+1; i++) { uint32_t ri; // leftmost position in candidate alignment uint32_t rir; // same, minus begin; for indexing into ref[] if(hi) { ri = halfway + (i >> 1); rir = ri - begin; assert_leq(ri, qend); } else { ri = halfway - (i >> 1); rir = ri - begin; assert_geq(ri, begin); } hi = !hi; // Do the naive comparison bool match = true; int refc = -1; uint32_t mmOff = 0xffffffff; int mms = 0; int seedMms = 0; unsigned int ham = 0; nonSeedMms.clear(); nonSeedRefcs.clear(); // Walk through each position of the alignment for(uint32_t jj = 0; jj < qlen; jj++) { uint32_t j = jj; if(!seedOnLeft) { // If seed is on the right, scan right-to-left j = qlen - jj - 1; } else { // Go left-to-right } uint32_t rirj = rir + j; if(!seedOnLeft) { assert_geq(rir, jj); rirj = rir - jj - 1; } #if 0 // Count Ns in the reference as mismatches const int q = (int)qry[j]; const int r = (int)ref[rirj]; assert_leq(q, 4); assert_leq(r, 4); if(q == 4 || r == 4 || q != r) { #else // Disallow alignments that involve an N in the // reference const int r = (int)ref[rirj]; if(r & 4) { // N in reference; bail on this alignment match = false; break; } const int q = (int)qry[j]; assert_leq(q, 4); assert_lt(r, 4); if(q != r) { #endif // Mismatch! mms++; if(mms > 1 && jj < slen) { // More than one mismatch in the anchor; reject match = false; break; } uint8_t qual = phredCharToPhredQual(quals[j]); ham += mmPenalty(this->maqPenalty_, qual); if(ham > this->qualMax_) { // Exceeded quality ceiling; reject match = false; break; } else if(jj < slen) { // First mismatch in the anchor; remember offset // and ref char refc = "ACGTN"[r]; mmOff = j; seedMms = 1; } else { // Legal mismatch outside of the anchor; record it nonSeedMms.push_back(j); assert_leq(nonSeedMms.size(), (size_t)mms); nonSeedRefcs.push_back("ACGTN"[r]); } } } if(match) { ranges.resize(ranges.size()+1); Range& range = ranges.back(); assert_leq(seedMms, mms); range.stratum = seedMms; range.numMms = mms; assert_eq(0, range.mms.size()); assert_eq(0, range.refcs.size()); if(mms >= 1) { // Be careful to add edits in left-to-right order // with respect to the read/alignment if(seedOnLeft && seedMms) { assert_lt(mmOff, qlen); range.mms.push_back(mmOff); range.refcs.push_back(refc); } const size_t nonSeedMmsSz = nonSeedMms.size(); if(nonSeedMmsSz > 0) { if(seedOnLeft) { for(size_t k = 0; k < nonSeedMmsSz; k++) { range.mms.push_back(nonSeedMms[k]); range.refcs.push_back(nonSeedRefcs[k]); } } else { for(size_t k = nonSeedMmsSz; k > 0; k--) { range.mms.push_back(nonSeedMms[k-1]); range.refcs.push_back(nonSeedRefcs[k-1]); } } } if(!seedOnLeft && seedMms) { assert_lt(mmOff, qlen); range.mms.push_back(mmOff); range.refcs.push_back(refc); } } assert_eq((size_t)mms, range.mms.size()); assert_eq((size_t)mms, range.refcs.size()); if(seedOnLeft) { results.push_back(ri); } else { results.push_back(ri - qlen); } } } return; } /** * This schematic shows the roles played by the begin, qbegin, end, * qend, halfway, slen, qlen, and lim variables: * * seedOnLeft == true: * * |< lim >|< qlen >| * -------------------------------------------------------------- * | | slen | qlen-slen | | slen | qlen-slen | * -------------------------------------------------------------- * ^ ^ ^ ^ * begin & qbegin halfway qend end * * seedOnLeft == false: * * |< lim >| * -------------------------------------------------------------- * | qlen-slen | | qlen-slen | slen | | slen | * -------------------------------------------------------------- * ^ ^ ^ ^ ^ * begin qbegin halfway qend end * * Note that, for seeds longer than 32 base-pairs, the seed is * further subdivided into a 32-bit anchor and a seed overhang of * length > 0. */ virtual void anchor64Find(uint32_t numToFind, uint32_t tidx, uint8_t* ref, const TDna5Str& qry, const TCharStr& quals, uint32_t begin, uint32_t end, TRangeVec& ranges, TU32Vec& results, TSetPairs* pairs = NULL, uint32_t aoff = 0xffffffff, bool seedOnLeft = false) const { assert_gt(numToFind, 0); ASSERT_ONLY(const uint32_t rangesInitSz = ranges.size()); ASSERT_ONLY(uint32_t duplicates = 0); ASSERT_ONLY(uint32_t r2i = 0); const uint32_t qlen = seqan::length(qry); assert_gt(qlen, 0); assert_gt(end, begin); assert_geq(end - begin, qlen); // caller should have checked this assert_gt(this->seedLen_, 0); uint32_t slen = min(qlen, this->seedLen_); #ifndef NDEBUG // Get results from the naive matcher for sanity-checking TRangeVec r2; TU32Vec re2; naiveFind(numToFind, tidx, ref, qry, quals, begin, end, r2, re2, pairs, aoff, seedOnLeft); #endif const uint32_t anchorBitPairs = min(slen, 32); const int lhsShift = ((anchorBitPairs - 1) << 1); const uint32_t anchorCushion = 32 - anchorBitPairs; // seedAnchorOverhang = # seed bases not included in the anchor const uint32_t seedAnchorOverhang = (slen <= anchorBitPairs ? 0 : (slen - anchorBitPairs)); // seedAnchorOverhang = # seed bases not included in the anchor const uint32_t readSeedOverhang = (slen == qlen ? 0 : (qlen - slen)); assert(anchorCushion == 0 || seedAnchorOverhang == 0); assert_eq(qlen, readSeedOverhang + slen); uint32_t qend = end; uint32_t qbegin = begin; if(seedOnLeft) { // Leave read-sized gap on right-hand side of the interval qend -= qlen; } else { // Leave seed-sized gap on right-hand side and // non-seed-sized gap on the left-hand side qbegin += readSeedOverhang; qend -= slen; } // lim = # possible alignments in the range const uint32_t lim = qend - qbegin; // halfway = point on the genome to radiate out from const uint32_t halfway = qbegin + (lim >> 1); uint64_t anchor = U64(0); uint64_t buffw = U64(0); // rotating ref sequence buffer // OR the 'diff' buffer with this so that we can always count // 'N's as mismatches uint64_t diffMask = U64(0); // Set up a mask that we'll apply to the two bufs every round // to discard bits that were rotated out of the anchor area uint64_t clearMask = U64(0xffffffffffffffff); bool useMask = false; if(anchorBitPairs < 32) { clearMask >>= ((32-anchorBitPairs) << 1); useMask = true; } int nsInSeed = 0; int nPos = -1; uint32_t skipLeftToRights = 0; uint32_t skipRightToLefts = 0; const uint32_t halfwayRi = halfway - begin; // Construct the 'anchor' 64-bit buffer so that it holds all of // the first 'anchorBitPairs' bit pairs of the query. for(uint32_t ii = 0; ii < anchorBitPairs; ii++) { uint32_t i = ii; if(!seedOnLeft) { // Fill in the anchor using characters from the right- // hand side of the query (but take the characters in // left-to-right order) i = qlen - slen + ii; } int c = (int)qry[i]; // next query character int r = (int)ref[halfwayRi + ii]; // next reference character if(r & 4) { // The reference character is an N; to mimic the // behavior of BW alignment, we have to skip all // alignments that involve an N in the reference. Set // the skip* variables accordingly. r = 0; uint32_t lrSkips = ii; uint32_t rlSkips = qlen - ii; if(!seedOnLeft && readSeedOverhang) { lrSkips += readSeedOverhang; assert_geq(rlSkips, readSeedOverhang); rlSkips -= readSeedOverhang; } // The right-to-left direction absorbs the candidate // alignment based at 'halfway' skipLeftToRights = max(skipLeftToRights, lrSkips); skipRightToLefts = max(skipRightToLefts, rlSkips); assert_leq(skipLeftToRights, qlen); assert_leq(skipRightToLefts, qlen); } assert_leq(c, 4); assert_lt(r, 4); // Special case: query has an 'N' if(c == 4) { if(++nsInSeed > 1) { // More than one 'N' in the anchor region; can't // possibly have a 1-mismatch hit anywhere assert_eq(r2.size(), ranges.size() - rangesInitSz); return; // can't match if query has Ns } nPos = (int)ii; // w/r/t LHS of anchor // Make it look like an 'A' in the anchor c = 0; diffMask = (diffMask << U64(2)) | U64(1); } else { diffMask <<= U64(2); } anchor = ((anchor << U64(2)) | c); buffw = ((buffw << U64(2)) | r); } // Check whether read is disqualified by Ns inside the seed // region but outside the anchor region if(seedAnchorOverhang) { assert_lt(anchorBitPairs, slen); for(uint32_t ii = anchorBitPairs; ii < slen; ii++) { uint32_t i = ii; if(!seedOnLeft) { i = qlen - slen + ii; } if((int)qry[i] == 4) { if(++nsInSeed > 1) { assert_eq(r2.size(), ranges.size() - rangesInitSz); return; // can't match if query has Ns } } } } else { assert_eq(anchorBitPairs, slen); } uint64_t bufbw = buffw; // Slide the anchor out in either direction, alternating // between right-to-left and left-to-right shifts, until all of // the positions from qbegin to qend have been covered. bool hi = false; uint32_t riHi = halfway; uint32_t rirHi = halfway - begin; uint32_t rirHiAnchor = rirHi + anchorBitPairs - 1; uint32_t riLo = halfway + 1; uint32_t rirLo = halfway - begin + 1; uint32_t lrSkips = anchorBitPairs; uint32_t rlSkips = qlen; if(!seedOnLeft && readSeedOverhang) { lrSkips += readSeedOverhang; assert_geq(rlSkips, readSeedOverhang); rlSkips -= readSeedOverhang; } for(uint32_t i = 1; i <= lim + 1; i++) { int r; // new reference char uint64_t diff; assert_leq(skipLeftToRights, qlen); assert_leq(skipRightToLefts, qlen); if(hi) { hi = false; // Moving left-to-right riHi++; rirHi++; rirHiAnchor++; r = (int)ref[rirHiAnchor]; if(r & 4) { r = 0; skipLeftToRights = lrSkips; } assert_lt(r, 4); // Bring in new base pair at the least significant // position buffw = ((buffw << U64(2)) | r); if(useMask) buffw &= clearMask; if(skipLeftToRights > 0) { skipLeftToRights--; continue; } diff = (buffw ^ anchor) | diffMask; } else { hi = true; // Moving right-to-left riLo--; rirLo--; r = (int)ref[rirLo]; if(r & 4) { r = 0; skipRightToLefts = rlSkips; } assert_lt(r, 4); if(i >= 2) { bufbw >>= U64(2); // Bring in new base pair at the most significant // position bufbw |= ((uint64_t)r << lhsShift); } if(skipRightToLefts > 0) { skipRightToLefts--; continue; } diff = (bufbw ^ anchor) | diffMask; } if((diff & U64(0xffffffff00000000)) && (diff & U64(0x00000000ffffffff))) continue; uint32_t ri = hi ? riLo : riHi; uint32_t rir = hi ? rirLo : rirHi; // Could use pop count uint8_t *diff8 = reinterpret_cast(&diff); // As a first cut, see if there are too many mismatches in // the first and last parts of the anchor uint32_t diffs = u8toMms[(int)diff8[0]] + u8toMms[(int)diff8[7]]; if(diffs > 1) continue; diffs += u8toMms[(int)diff8[1]] + u8toMms[(int)diff8[2]] + u8toMms[(int)diff8[3]] + u8toMms[(int)diff8[4]] + u8toMms[(int)diff8[5]] + u8toMms[(int)diff8[6]]; uint32_t mmpos = 0xffffffff; int refc = -1; unsigned int ham = 0; if(diffs > 1) { // Too many differences in the seed; stop continue; } else if(diffs == 1 && nPos != -1) { // There was one difference, but there was also one N, // so we already know where the difference is mmpos = nPos; assert_lt(mmpos, anchorBitPairs); refc = "ACGT"[(int)ref[rir + nPos]]; if(!seedOnLeft) { mmpos += readSeedOverhang; } char q = quals[mmpos]; ham += mmPenalty(this->maqPenalty_, phredCharToPhredQual(q)); if(ham > this->qualMax_) { // Exceeded quality limit continue; } } else if(diffs == 1) { // Figure out which position mismatched mmpos = 31; if((diff & U64(0xffffffff)) == 0) { diff >>= U64(32); mmpos -= 16; } assert_neq(0, diff); if((diff & U64(0xffff)) == 0) { diff >>= U64(16); mmpos -= 8; } assert_neq(0, diff); if((diff & U64(0xff)) == 0) { diff >>= U64(8); mmpos -= 4; } assert_neq(0, diff); if((diff & U64(0xf)) == 0) { diff >>= U64(4); mmpos -= 2; } assert_neq(0, diff); if((diff & U64(0x3)) == 0) { mmpos--; } assert_neq(0, diff); assert_geq(mmpos, 0); assert_lt(mmpos, 32); mmpos -= anchorCushion; assert_lt(mmpos, anchorBitPairs); refc = "ACGT"[(int)ref[rir + mmpos]]; if(!seedOnLeft) { mmpos += readSeedOverhang; } char q = quals[mmpos]; ham += mmPenalty(this->maqPenalty_, phredCharToPhredQual(q)); if(ham > this->qualMax_) { // Exceeded quality limit continue; } } // If the seed is longer than the anchor, then scan the // rest of the seed characters bool foundHit = true; if(seedAnchorOverhang) { for(uint32_t j = 0; j < seedAnchorOverhang; j++) { int rc = (int)ref[rir + anchorBitPairs + j]; if(rc == 4) { // Oops, encountered an N in the reference in // the overhang portion of the candidate // alignment // (Note that we inverted hi earlier) if(hi) { // Right-to-left // Skip out of the seedAnchorOverhang assert_eq(0, skipRightToLefts); skipRightToLefts = seedAnchorOverhang - j - 1; if(seedOnLeft) { // ...and skip out of the rest of the read skipRightToLefts += readSeedOverhang; } } else { // Left-to-right // Skip out of the seedAnchorOverhang assert_eq(0, skipLeftToRights); skipLeftToRights = anchorBitPairs + j; if(!seedOnLeft) { // ...and skip out of the rest of the read skipLeftToRights += readSeedOverhang; } } foundHit = false; // Skip this candidate break; } uint32_t qoff = anchorBitPairs + j; if(!seedOnLeft) { qoff += readSeedOverhang; } assert_lt(qoff, qlen); if((int)qry[qoff] != rc) { if(++diffs > 1) { foundHit = false; break; } else { assert_eq(0xffffffff, mmpos); mmpos = qoff; assert_eq(-1, refc); refc = "ACGT"[(int)ref[rir + anchorBitPairs + j]]; char q = phredCharToPhredQual(quals[qoff]); ham += mmPenalty(this->maqPenalty_, q); if(ham > this->qualMax_) { // Exceeded quality limit foundHit = false; break; } } } } if(!foundHit) continue; } // If the read is longer than the seed, then scan the rest // of the read characters; mismatches no longer count // toward the stratum or the 1-mm limit. // Vectors for holding edit information std::vector nonSeedMms; std::vector nonSeedRefcs; int mms = diffs; // start counting total mismatches if((qlen - slen) > 0) { // Going left-to-right for(uint32_t j = 0; j < readSeedOverhang; j++) { uint32_t roff = rir + slen + j; uint32_t qoff = slen + j; if(!seedOnLeft) { assert_geq(roff, qlen); roff -= qlen; qoff = j; } int rc = (int)ref[roff]; if(rc == 4) { // Oops, encountered an N in the reference in // the overhang portion of the candidate // alignment // (Note that we inverted hi earlier) if(hi) { // Right-to-left // Skip what's left of the readSeedOverhang skipRightToLefts = readSeedOverhang - j - 1; if(!seedOnLeft) { // ...and skip the seed if it's on the right skipRightToLefts += slen; } } else { // Left-to-right // Skip what we've matched of the overhang skipLeftToRights = j; if(seedOnLeft) { // ...and skip the seed if it's on the left skipLeftToRights += slen; } } foundHit = false; // Skip this candidate break; } if((int)qry[qoff] != rc) { // Calculate quality of mismatched base char q = phredCharToPhredQual(quals[qoff]); ham += mmPenalty(this->maqPenalty_, q); if(ham > this->qualMax_) { // Exceeded quality limit foundHit = false; break; } // Legal mismatch outside of the anchor; record it mms++; nonSeedMms.push_back(qoff); assert_leq(nonSeedMms.size(), (size_t)mms); nonSeedRefcs.push_back("ACGTN"[rc]); } } if(!foundHit) continue; } assert(foundHit); // Adjust ri if seed is on the right-hand side if(!seedOnLeft) { ri -= readSeedOverhang; rir -= readSeedOverhang; } if(pairs != NULL) { TU64Pair p; if(ri < aoff) { // By convention, the upstream mate's // coordinates go in the 'first' field p.first = ((uint64_t)tidx << 32) | (uint64_t)ri; p.second = ((uint64_t)tidx << 32) | (uint64_t)aoff; } else { p.second = ((uint64_t)tidx << 32) | (uint64_t)ri; p.first = ((uint64_t)tidx << 32) | (uint64_t)aoff; } if(pairs->find(p) != pairs->end()) { // We already found this hit! Continue. ASSERT_ONLY(duplicates++); ASSERT_ONLY(r2i++); continue; } else { // Record this hit pairs->insert(p); } } if(this->verbose_) { cout << "About to report:" << endl; cout << " "; for(size_t i = 0; i < qlen; i++) { cout << (char)qry[i]; } cout << endl; cout << " "; for(size_t i = 0; i < qlen; i++) { cout << "ACGT"[ref[rir+i]]; } cout << endl; } assert_leq(diffs, 1); assert_geq((size_t)mms, diffs); assert_lt(r2i, r2.size()); assert_eq(re2[r2i], ri); ranges.resize(ranges.size()+1); Range& range = ranges.back(); assert_eq((size_t)mms, r2[r2i].numMms); range.stratum = diffs; range.numMms = mms; assert_eq(0, range.mms.size()); assert_eq(0, range.refcs.size()); if(mms > 0) { ASSERT_ONLY(size_t mmcur = 0); if(seedOnLeft && diffs > 0) { assert_neq(mmpos, 0xffffffff); assert_lt(mmpos, qlen); assert_lt(mmcur, (size_t)mms); assert_eq(mmpos, r2[r2i].mms[mmcur]); assert_neq(-1, refc); assert_eq(refc, r2[r2i].refcs[mmcur]); ASSERT_ONLY(mmcur++); range.mms.push_back(mmpos); range.refcs.push_back(refc); } const size_t nonSeedMmsSz = nonSeedMms.size(); for(size_t i = 0; i < nonSeedMmsSz; i++) { assert_neq(0xffffffff, nonSeedMms[i]); assert_lt(mmcur, (size_t)mms); assert_eq(nonSeedMms[i], r2[r2i].mms[mmcur]); range.mms.push_back(nonSeedMms[i]); assert_eq(nonSeedRefcs[i], r2[r2i].refcs[mmcur]); ASSERT_ONLY(mmcur++); range.refcs.push_back(nonSeedRefcs[i]); } if(!seedOnLeft && diffs > 0) { assert_neq(mmpos, 0xffffffff); assert_lt(mmpos, qlen); assert_lt(mmcur, (size_t)mms); assert_eq(mmpos, r2[r2i].mms[mmcur]); assert_neq(-1, refc); assert_eq(refc, r2[r2i].refcs[mmcur]); ASSERT_ONLY(mmcur++); range.mms.push_back(mmpos); range.refcs.push_back(refc); } assert_eq(mmcur, r2[r2i].mms.size()); } assert_eq((size_t)mms, range.mms.size()); assert_eq((size_t)mms, range.refcs.size()); ASSERT_ONLY(r2i++); results.push_back(ri); if(--numToFind == 0) return; } assert_leq(duplicates, r2.size()); assert_geq(r2.size() - duplicates, ranges.size() - rangesInitSz); return; // no hit } }; /** * Concrete RefAligner for finding nearby 2-mismatch hits given an * anchor hit. */ template class Seed2RefAligner : public RefAligner { typedef seqan::String TDna5Str; typedef seqan::String TCharStr; typedef std::vector TRangeVec; typedef std::vector TU32Vec; typedef std::pair TU64Pair; typedef std::set TSetPairs; public: Seed2RefAligner(bool color, bool verbose, bool quiet, uint32_t seedLen, uint32_t qualMax, bool maqPenalty) : RefAligner(color, verbose, quiet, seedLen, qualMax, maqPenalty) { } virtual ~Seed2RefAligner() { } protected: /** * This schematic shows the roles played by the begin, qbegin, end, * qend, halfway, slen, qlen, and lim variables: * * seedOnLeft == true: * * |< lim >|< qlen >| * -------------------------------------------------------------- * | | slen | qlen-slen | | slen | qlen-slen | * -------------------------------------------------------------- * ^ ^ ^ ^ * begin & qbegin halfway qend end * * seedOnLeft == false: * * |< qlen >|< lim >| * -------------------------------------------------------------- * | qlen-slen | slen | | qlen-slen | slen | | * -------------------------------------------------------------- * ^ ^ ^ ^ * begin qbegin halfway qend & end * * Note that, for seeds longer than 32 base-pairs, the seed is * further subdivided into a 32-bit anchor and a seed overhang of * length > 0. */ void naiveFind(uint32_t numToFind, uint32_t tidx, uint8_t* ref, const TDna5Str& qry, const TCharStr& quals, uint32_t begin, uint32_t end, TRangeVec& ranges, TU32Vec& results, TSetPairs* pairs, uint32_t aoff, bool seedOnLeft) const { assert_gt(numToFind, 0); assert_gt(end, begin); const uint32_t qlen = seqan::length(qry); assert_gt(qlen, 0); assert_geq(end - begin, qlen); // caller should have checked this assert_gt(this->seedLen_, 0); const uint32_t slen = min(qlen, this->seedLen_); uint32_t qend = end; uint32_t qbegin = begin; // If the seed is on the left-hand side of the alignment, then // leave a gap at the right-hand side of the interval; // otherwise, do the opposite if(seedOnLeft) { // Leave gap on right-hand side of the interval qend -= qlen; } else { // Leave gap on left-hand side of the interval qbegin += qlen; } // lim = number of alignments to try const uint32_t lim = qend - qbegin; // halfway = position in the reference to start at (and then // we work our way out to the right and to the left). const uint32_t halfway = qbegin + (lim >> 1); // Vectors for holding edit information std::vector nonSeedMms; std::vector nonSeedRefcs; bool hi = false; for(uint32_t i = 1; i <= lim+1; i++) { uint32_t ri; // leftmost position in candidate alignment uint32_t rir; // same, minus begin; for indexing into ref[] if(hi) { ri = halfway + (i >> 1); rir = ri - begin; assert_leq(ri, qend); } else { ri = halfway - (i >> 1); rir = ri - begin; assert_geq(ri, begin); } hi = !hi; // Do the naive comparison bool match = true; int refc1 = -1; uint32_t mmOff1 = 0xffffffff; int refc2 = -1; uint32_t mmOff2 = 0xffffffff; int mms = 0; int seedMms = 0; unsigned int ham = 0; nonSeedMms.clear(); nonSeedRefcs.clear(); // Walk through each position of the alignment for(uint32_t jj = 0; jj < qlen; jj++) { uint32_t j = jj; if(!seedOnLeft) { // If seed is on the right, scan right-to-left j = qlen - jj - 1; } else { // Go left-to-right } uint32_t rirj = rir + j; if(!seedOnLeft) { assert_geq(rir, jj); rirj = rir - jj - 1; } #if 0 // Count Ns in the reference as mismatches const int q = (int)qry[j]; const int r = (int)ref[rirj]; assert_leq(q, 4); assert_leq(r, 4); if(q == 4 || r == 4 || q != r) { #else // Disallow alignments that involve an N in the // reference const int r = (int)ref[rirj]; if(r & 4) { // N in reference; bail on this alignment match = false; break; } const int q = (int)qry[j]; assert_leq(q, 4); assert_lt(r, 4); if(q != r) { #endif // Mismatch! mms++; if(mms > 2 && jj < slen) { // More than one mismatch in the anchor; reject match = false; break; } uint8_t qual = phredCharToPhredQual(quals[j]); ham += mmPenalty(this->maqPenalty_, qual); if(ham > this->qualMax_) { // Exceeded quality ceiling; reject match = false; break; } else if(mms == 1 && jj < slen) { // First mismatch in the anchor; remember offset // and ref char refc1 = "ACGTN"[r]; mmOff1 = j; seedMms = 1; } else if(mms == 2 && jj < slen) { // Second mismatch in the anchor; remember offset // and ref char refc2 = "ACGTN"[r]; mmOff2 = j; seedMms = 2; } else { // Legal mismatch outside of the anchor; record it nonSeedMms.push_back(j); assert_leq(nonSeedMms.size(), (size_t)mms); nonSeedRefcs.push_back("ACGTN"[r]); } } } if(match) { ranges.resize(ranges.size()+1); Range& range = ranges.back(); assert_leq(seedMms, mms); range.stratum = seedMms; range.numMms = mms; assert_eq(0, range.mms.size()); assert_eq(0, range.refcs.size()); if(mms >= 1) { // Be careful to add edits in left-to-right order // with respect to the read/alignment if(seedOnLeft && seedMms) { assert_lt(mmOff1, qlen); range.mms.push_back(mmOff1); range.refcs.push_back(refc1); if(seedMms > 1) { assert_lt(mmOff1, mmOff2); assert_lt(mmOff2, qlen); range.mms.push_back(mmOff2); range.refcs.push_back(refc2); } } const size_t nonSeedMmsSz = nonSeedMms.size(); if(nonSeedMmsSz > 0) { if(seedOnLeft) { for(size_t k = 0; k < nonSeedMmsSz; k++) { range.mms.push_back(nonSeedMms[k]); range.refcs.push_back(nonSeedRefcs[k]); } } else { for(size_t k = nonSeedMmsSz; k > 0; k--) { range.mms.push_back(nonSeedMms[k-1]); range.refcs.push_back(nonSeedRefcs[k-1]); } } } if(!seedOnLeft && seedMms) { if(seedMms > 1) { assert_lt(mmOff2, mmOff1); assert_lt(mmOff2, qlen); range.mms.push_back(mmOff2); range.refcs.push_back(refc2); } assert_lt(mmOff1, qlen); range.mms.push_back(mmOff1); range.refcs.push_back(refc1); } } assert_eq((size_t)mms, range.mms.size()); assert_eq((size_t)mms, range.refcs.size()); if(seedOnLeft) { results.push_back(ri); } else { results.push_back(ri - qlen); } } } return; } /** * This schematic shows the roles played by the begin, qbegin, end, * qend, halfway, slen, qlen, and lim variables: * * seedOnLeft == true: * * |< lim >|< qlen >| * -------------------------------------------------------------- * | | slen | qlen-slen | | slen | qlen-slen | * -------------------------------------------------------------- * ^ ^ ^ ^ * begin & qbegin halfway qend end * * seedOnLeft == false: * * |< lim >| * -------------------------------------------------------------- * | qlen-slen | | qlen-slen | slen | | slen | * -------------------------------------------------------------- * ^ ^ ^ ^ ^ * begin qbegin halfway qend end * * Note that, for seeds longer than 32 base-pairs, the seed is * further subdivided into a 32-bit anchor and a seed overhang of * length > 0. */ virtual void anchor64Find(uint32_t numToFind, uint32_t tidx, uint8_t* ref, const TDna5Str& qry, const TCharStr& quals, uint32_t begin, uint32_t end, TRangeVec& ranges, TU32Vec& results, TSetPairs* pairs = NULL, uint32_t aoff = 0xffffffff, bool seedOnLeft = false) const { assert_gt(numToFind, 0); ASSERT_ONLY(const uint32_t rangesInitSz = ranges.size()); ASSERT_ONLY(uint32_t duplicates = 0); ASSERT_ONLY(uint32_t r2i = 0); const uint32_t qlen = seqan::length(qry); assert_gt(qlen, 0); assert_gt(end, begin); assert_geq(end - begin, qlen); // caller should have checked this assert_gt(this->seedLen_, 0); uint32_t slen = min(qlen, this->seedLen_); #ifndef NDEBUG // Get results from the naive matcher for sanity-checking TRangeVec r2; TU32Vec re2; naiveFind(numToFind, tidx, ref, qry, quals, begin, end, r2, re2, pairs, aoff, seedOnLeft); #endif const uint32_t anchorBitPairs = min(slen, 32); const int lhsShift = ((anchorBitPairs - 1) << 1); const uint32_t anchorCushion = 32 - anchorBitPairs; // seedAnchorOverhang = # seed bases not included in the anchor const uint32_t seedAnchorOverhang = (slen <= anchorBitPairs ? 0 : (slen - anchorBitPairs)); // seedAnchorOverhang = # seed bases not included in the anchor const uint32_t readSeedOverhang = (slen == qlen ? 0 : (qlen - slen)); assert(anchorCushion == 0 || seedAnchorOverhang == 0); assert_eq(qlen, readSeedOverhang + slen); uint32_t qend = end; uint32_t qbegin = begin; if(seedOnLeft) { // Leave read-sized gap on right-hand side of the interval qend -= qlen; } else { // Leave seed-sized gap on right-hand side and // non-seed-sized gap on the left-hand side qbegin += readSeedOverhang; qend -= slen; } // lim = # possible alignments in the range const uint32_t lim = qend - qbegin; // halfway = point on the genome to radiate out from const uint32_t halfway = qbegin + (lim >> 1); uint64_t anchor = U64(0); uint64_t buffw = U64(0); // rotating ref sequence buffer // OR the 'diff' buffer with this so that we can always count // 'N's as mismatches uint64_t diffMask = U64(0); // Set up a mask that we'll apply to the two bufs every round // to discard bits that were rotated out of the anchor area uint64_t clearMask = U64(0xffffffffffffffff); bool useMask = false; if(anchorBitPairs < 32) { clearMask >>= ((32-anchorBitPairs) << 1); useMask = true; } int nsInSeed = 0; uint32_t nPoss = 0; int nPos1 = -1; int nPos2 = -1; uint32_t skipLeftToRights = 0; uint32_t skipRightToLefts = 0; const uint32_t halfwayRi = halfway - begin; assert_leq(anchorBitPairs, slen); // Construct the 'anchor' 64-bit buffer so that it holds all of // the first 'anchorBitPairs' bit pairs of the query. for(uint32_t ii = 0; ii < anchorBitPairs; ii++) { uint32_t i = ii; if(!seedOnLeft) { // Fill in the anchor using characters from the seed // portion of the read, starting at the left. Note // that we're subtracting by slen rather than // anchorBitPairs because we want the seed anchor // overhang to be on the right-hand side i = qlen - slen + ii; } int c = (int)qry[i]; // next query character int r = (int)ref[halfwayRi + ii]; // next reference character if(r & 4) { // The reference character is an N; to mimic the // behavior of BW alignment, we have to skip all // alignments that involve an N in the reference. Set // the skip* variables accordingly. r = 0; uint32_t lrSkips = ii; uint32_t rlSkips = qlen - ii; if(!seedOnLeft && readSeedOverhang) { lrSkips += readSeedOverhang; assert_geq(rlSkips, readSeedOverhang); rlSkips -= readSeedOverhang; } // The right-to-left direction absorbs the candidate // alignment based at 'halfway' skipLeftToRights = max(skipLeftToRights, lrSkips); skipRightToLefts = max(skipRightToLefts, rlSkips); assert_leq(skipLeftToRights, qlen); assert_leq(skipRightToLefts, qlen); } assert_leq(c, 4); assert_lt(r, 4); // Special case: query has an 'N' if(c == 4) { if(++nsInSeed > 2) { // More than one 'N' in the anchor region; can't // possibly have a 1-mismatch hit anywhere assert_eq(r2.size(), ranges.size() - rangesInitSz); return; // can't match if query has Ns } if(nsInSeed == 1) { nPos1 = (int)ii; // w/r/t LHS of anchor } else { assert_eq(2, nsInSeed); nPos2 = (int)ii; // w/r/t LHS of anchor assert_gt(nPos2, nPos1); } // Make it look like an 'A' in the anchor c = 0; diffMask = (diffMask << U64(2)) | U64(1); } else { diffMask <<= U64(2); } anchor = ((anchor << U64(2)) | c); buffw = ((buffw << U64(2)) | r); } // Check whether read is disqualified by Ns inside the seed // region but outside the anchor region if(seedAnchorOverhang) { assert_lt(anchorBitPairs, slen); for(uint32_t ii = anchorBitPairs; ii < slen; ii++) { uint32_t i = ii; if(!seedOnLeft) { i = qlen - slen + ii; } if((int)qry[i] == 4) { if(++nsInSeed > 2) { assert_eq(r2.size(), ranges.size() - rangesInitSz); return; // can't match if query has Ns } } } } else { assert_eq(anchorBitPairs, slen); } uint64_t bufbw = buffw; // Slide the anchor out in either direction, alternating // between right-to-left and left-to-right shifts, until all of // the positions from qbegin to qend have been covered. bool hi = false; uint32_t riHi = halfway; uint32_t rirHi = halfway - begin; uint32_t rirHiAnchor = rirHi + anchorBitPairs - 1; uint32_t riLo = halfway + 1; uint32_t rirLo = halfway - begin + 1; uint32_t lrSkips = anchorBitPairs; uint32_t rlSkips = qlen; if(!seedOnLeft && readSeedOverhang) { lrSkips += readSeedOverhang; assert_geq(rlSkips, readSeedOverhang); rlSkips -= readSeedOverhang; } for(uint32_t i = 1; i <= lim + 1; i++) { int r; // new reference char uint64_t diff; assert_leq(skipLeftToRights, qlen); assert_leq(skipRightToLefts, qlen); if(hi) { hi = false; // Moving left-to-right riHi++; rirHi++; rirHiAnchor++; r = (int)ref[rirHiAnchor]; if(r & 4) { r = 0; skipLeftToRights = lrSkips; } assert_lt(r, 4); // Bring in new base pair at the least significant // position buffw = ((buffw << U64(2)) | r); if(useMask) buffw &= clearMask; if(skipLeftToRights > 0) { skipLeftToRights--; continue; } diff = (buffw ^ anchor) | diffMask; } else { hi = true; // Moving right-to-left riLo--; rirLo--; r = (int)ref[rirLo]; if(r & 4) { r = 0; skipRightToLefts = rlSkips; } assert_lt(r, 4); if(i >= 2) { bufbw >>= U64(2); // Bring in new base pair at the most significant // position bufbw |= ((uint64_t)r << lhsShift); } if(skipRightToLefts > 0) { skipRightToLefts--; continue; } diff = (bufbw ^ anchor) | diffMask; } if((diff & U64(0xf00f00f00f00f00f)) && (diff & U64(0x0f00f00f00f00f00)) && (diff & U64(0x00f00f00f00f00f0))) continue; if((diff & U64(0xc30c30c30c30c30c)) && (diff & U64(0x30c30c30c30c30c3)) && (diff & U64(0x0c30c30c30c30c30))) continue; uint32_t ri = hi ? riLo : riHi; uint32_t rir = hi ? rirLo : rirHi; // Could use pop count uint8_t *diff8 = reinterpret_cast(&diff); // As a first cut, see if there are too many mismatches in // the first and last parts of the anchor uint32_t diffs = u8toMms[(int)diff8[0]] + u8toMms[(int)diff8[7]]; if(diffs > 2) continue; diffs += u8toMms[(int)diff8[1]] + u8toMms[(int)diff8[2]] + u8toMms[(int)diff8[3]] + u8toMms[(int)diff8[4]] + u8toMms[(int)diff8[5]] + u8toMms[(int)diff8[6]]; uint32_t mmpos1 = 0xffffffff; int refc1 = -1; uint32_t mmpos2 = 0xffffffff; int refc2 = -1; unsigned int ham = 0; if(diffs > 2) { // Too many differences in the seed; stop continue; } else if(nPoss > 1 && diffs == nPoss) { // There was one difference, but there was also one N, // so we already know where the difference is mmpos1 = nPos1; refc1 = "ACGT"[(int)ref[rir + nPos1]]; if(!seedOnLeft) { mmpos1 += readSeedOverhang; } char q = quals[mmpos1]; ham += mmPenalty(this->maqPenalty_, phredCharToPhredQual(q)); if(ham > this->qualMax_) { // Exceeded quality limit continue; } if(nPoss == 2) { mmpos2 = nPos2; refc2 = "ACGT"[(int)ref[rir + nPos2]]; if(!seedOnLeft) { mmpos2 += readSeedOverhang; } q = quals[mmpos2]; ham += mmPenalty(this->maqPenalty_, phredCharToPhredQual(q)); if(ham > this->qualMax_) { // Exceeded quality limit continue; } } } else if(diffs > 0) { // Figure out which position mismatched uint64_t diff2 = diff; mmpos1 = 31; if((diff & U64(0xffffffff)) == 0) { diff >>= U64(32); mmpos1 -= 16; } assert_neq(0, diff); if((diff & U64(0xffff)) == 0) { diff >>= U64(16); mmpos1 -= 8; } assert_neq(0, diff); if((diff & U64(0xff)) == 0) { diff >>= U64(8); mmpos1 -= 4; } assert_neq(0, diff); if((diff & U64(0xf)) == 0) { diff >>= U64(4); mmpos1 -= 2; } assert_neq(0, diff); if((diff & U64(0x3)) == 0) { mmpos1--; } assert_neq(0, diff); assert_geq(mmpos1, 0); assert_lt(mmpos1, 32); uint32_t savedMmpos1 = mmpos1; mmpos1 -= anchorCushion; assert_lt(mmpos1, anchorBitPairs); refc1 = "ACGT"[(int)ref[rir + mmpos1]]; if(!seedOnLeft) { mmpos1 += readSeedOverhang; } char q = quals[mmpos1]; ham += mmPenalty(this->maqPenalty_, phredCharToPhredQual(q)); if(ham > this->qualMax_) { // Exceeded quality limit continue; } if(diffs > 1) { // Figure out the second mismatched position ASSERT_ONLY(uint64_t origDiff2 = diff2); diff2 &= ~(U64(0xc000000000000000) >> (uint64_t)((savedMmpos1) << 1)); assert_neq(diff2, origDiff2); mmpos2 = 31; if((diff2 & U64(0xffffffff)) == 0) { diff2 >>= U64(32); mmpos2 -= 16; } assert_neq(0, diff2); if((diff2 & U64(0xffff)) == 0) { diff2 >>= U64(16); mmpos2 -= 8; } assert_neq(0, diff2); if((diff2 & U64(0xff)) == 0) { diff2 >>= U64(8); mmpos2 -= 4; } assert_neq(0, diff2); if((diff2 & U64(0xf)) == 0) { diff2 >>= U64(4); mmpos2 -= 2; } assert_neq(0, diff2); if((diff2 & U64(0x3)) == 0) { mmpos2--; } assert_neq(0, diff2); assert_geq(mmpos2, 0); assert_lt(mmpos2, 32); mmpos2 -= anchorCushion; assert_neq(mmpos1, mmpos2); refc2 = "ACGT"[(int)ref[rir + mmpos2]]; if(!seedOnLeft) { mmpos2 += readSeedOverhang; } q = quals[mmpos2]; ham += mmPenalty(this->maqPenalty_, phredCharToPhredQual(q)); if(ham > this->qualMax_) { // Exceeded quality limit continue; } if(mmpos2 < mmpos1) { uint32_t mmtmp = mmpos1; mmpos1 = mmpos2; mmpos2 = mmtmp; int refctmp = refc1; refc1 = refc2; refc2 = refctmp; } assert_lt(mmpos1, mmpos2); } } // If the seed is longer than the anchor, then scan the // rest of the seed characters bool foundHit = true; if(seedAnchorOverhang) { for(uint32_t j = 0; j < seedAnchorOverhang; j++) { int rc = (int)ref[rir + anchorBitPairs + j]; if(rc == 4) { // Oops, encountered an N in the reference in // the overhang portion of the candidate // alignment // (Note that we inverted hi earlier) if(hi) { // Right-to-left // Skip out of the seedAnchorOverhang assert_eq(0, skipRightToLefts); skipRightToLefts = seedAnchorOverhang - j - 1; if(seedOnLeft) { // ...and skip out of the rest of the read skipRightToLefts += readSeedOverhang; } } else { // Left-to-right // Skip out of the seedAnchorOverhang assert_eq(0, skipLeftToRights); skipLeftToRights = anchorBitPairs + j; if(!seedOnLeft) { // ...and skip out of the rest of the read skipLeftToRights += readSeedOverhang; } } foundHit = false; // Skip this candidate break; } uint32_t qoff = anchorBitPairs + j; if(!seedOnLeft) { qoff += readSeedOverhang; } assert_lt(qoff, qlen); if((int)qry[qoff] != rc) { diffs++; if(diffs > 2) { foundHit = false; break; } else if(diffs == 2) { assert_eq(0xffffffff, mmpos2); mmpos2 = qoff; assert_eq(-1, refc2); refc2 = "ACGT"[(int)ref[rir + anchorBitPairs + j]]; } else { assert_eq(1, diffs); assert_eq(0xffffffff, mmpos1); mmpos1 = qoff; assert_eq(-1, refc1); refc1 = "ACGT"[(int)ref[rir + anchorBitPairs + j]]; } char q = phredCharToPhredQual(quals[qoff]); ham += mmPenalty(this->maqPenalty_, q); if(ham > this->qualMax_) { // Exceeded quality limit foundHit = false; break; } } } if(!foundHit) continue; } // If the read is longer than the seed, then scan the rest // of the read characters; mismatches no longer count // toward the stratum or the 1-mm limit. // Vectors for holding edit information std::vector nonSeedMms; std::vector nonSeedRefcs; int mms = diffs; // start counting total mismatches if((qlen - slen) > 0) { // Going left-to-right for(uint32_t j = 0; j < readSeedOverhang; j++) { uint32_t roff = rir + slen + j; uint32_t qoff = slen + j; if(!seedOnLeft) { assert_geq(roff, qlen); roff -= qlen; qoff = j; } int rc = (int)ref[roff]; if(rc == 4) { // Oops, encountered an N in the reference in // the overhang portion of the candidate // alignment // (Note that we inverted hi earlier) if(hi) { // Right-to-left // Skip what's left of the readSeedOverhang skipRightToLefts = readSeedOverhang - j - 1; if(!seedOnLeft) { // ...and skip the seed if it's on the right skipRightToLefts += slen; } } else { // Left-to-right // Skip what we've matched of the overhang skipLeftToRights = j; if(seedOnLeft) { // ...and skip the seed if it's on the left skipLeftToRights += slen; } } foundHit = false; // Skip this candidate break; } if((int)qry[qoff] != rc) { // Calculate quality of mismatched base char q = phredCharToPhredQual(quals[qoff]); ham += mmPenalty(this->maqPenalty_, q); if(ham > this->qualMax_) { // Exceeded quality limit foundHit = false; break; } // Legal mismatch outside of the anchor; record it mms++; nonSeedMms.push_back(qoff); assert_leq(nonSeedMms.size(), (size_t)mms); nonSeedRefcs.push_back("ACGTN"[rc]); } } if(!foundHit) continue; } assert(foundHit); // Adjust ri if seed is on the right-hand side if(!seedOnLeft) { ri -= readSeedOverhang; rir -= readSeedOverhang; } if(pairs != NULL) { TU64Pair p; if(ri < aoff) { // By convention, the upstream mate's // coordinates go in the 'first' field p.first = ((uint64_t)tidx << 32) | (uint64_t)ri; p.second = ((uint64_t)tidx << 32) | (uint64_t)aoff; } else { p.second = ((uint64_t)tidx << 32) | (uint64_t)ri; p.first = ((uint64_t)tidx << 32) | (uint64_t)aoff; } if(pairs->find(p) != pairs->end()) { // We already found this hit! Continue. ASSERT_ONLY(duplicates++); ASSERT_ONLY(r2i++); continue; } else { // Record this hit pairs->insert(p); } } if(this->verbose_) { cout << "About to report:" << endl; cout << " "; for(size_t i = 0; i < qlen; i++) { cout << (char)qry[i]; } cout << endl; cout << " "; for(size_t i = 0; i < qlen; i++) { cout << "ACGT"[ref[rir+i]]; } cout << endl; } assert_leq(diffs, 2); assert_geq((size_t)mms, diffs); assert_lt(r2i, r2.size()); assert_eq(re2[r2i], ri); ranges.resize(ranges.size()+1); Range& range = ranges.back(); assert_eq((size_t)mms, r2[r2i].numMms); range.stratum = diffs; range.numMms = mms; assert_eq(0, range.mms.size()); assert_eq(0, range.refcs.size()); if(mms > 0) { ASSERT_ONLY(size_t mmcur = 0); if(seedOnLeft && diffs > 0) { assert_neq(mmpos1, 0xffffffff); assert_lt(mmpos1, qlen); assert_lt(mmcur, (size_t)mms); assert_eq(mmpos1, r2[r2i].mms[mmcur]); assert_neq(-1, refc1); assert_eq(refc1, r2[r2i].refcs[mmcur]); ASSERT_ONLY(mmcur++); range.mms.push_back(mmpos1); range.refcs.push_back(refc1); if(diffs > 1) { assert_eq(2, diffs); assert_neq(mmpos2, 0xffffffff); assert_lt(mmpos2, qlen); assert_lt(mmcur, (size_t)mms); assert_eq(mmpos2, r2[r2i].mms[mmcur]); assert_neq(-1, refc2); assert_eq(refc2, r2[r2i].refcs[mmcur]); ASSERT_ONLY(mmcur++); range.mms.push_back(mmpos2); range.refcs.push_back(refc2); } } const size_t nonSeedMmsSz = nonSeedMms.size(); for(size_t i = 0; i < nonSeedMmsSz; i++) { assert_neq(0xffffffff, nonSeedMms[i]); assert_lt(mmcur, (size_t)mms); assert_eq(nonSeedMms[i], r2[r2i].mms[mmcur]); range.mms.push_back(nonSeedMms[i]); assert_eq(nonSeedRefcs[i], r2[r2i].refcs[mmcur]); ASSERT_ONLY(mmcur++); range.refcs.push_back(nonSeedRefcs[i]); } if(!seedOnLeft && diffs > 0) { assert_neq(mmpos1, 0xffffffff); assert_lt(mmpos1, qlen); assert_lt(mmcur, (size_t)mms); assert_eq(mmpos1, r2[r2i].mms[mmcur]); assert_neq(-1, refc1); assert_eq(refc1, r2[r2i].refcs[mmcur]); ASSERT_ONLY(mmcur++); range.mms.push_back(mmpos1); range.refcs.push_back(refc1); if(diffs > 1) { assert_eq(2, diffs); assert_neq(mmpos2, 0xffffffff); assert_lt(mmpos2, qlen); assert_lt(mmcur, (size_t)mms); assert_eq(mmpos2, r2[r2i].mms[mmcur]); assert_neq(-1, refc2); assert_eq(refc2, r2[r2i].refcs[mmcur]); ASSERT_ONLY(mmcur++); range.mms.push_back(mmpos2); range.refcs.push_back(refc2); } } assert_eq(mmcur, r2[r2i].mms.size()); } assert_eq((size_t)mms, range.mms.size()); assert_eq((size_t)mms, range.refcs.size()); ASSERT_ONLY(r2i++); results.push_back(ri); if(--numToFind == 0) return; } assert_leq(duplicates, r2.size()); assert_geq(r2.size() - duplicates, ranges.size() - rangesInitSz); return; // no hit } }; /** * Concrete RefAligner for finding nearby 3-mismatch hits given an * anchor hit. */ template class Seed3RefAligner : public RefAligner { typedef seqan::String TDna5Str; typedef seqan::String TCharStr; typedef std::vector TRangeVec; typedef std::vector TU32Vec; typedef std::pair TU64Pair; typedef std::set TSetPairs; public: Seed3RefAligner(bool color, bool verbose, bool quiet, uint32_t seedLen, uint32_t qualMax, bool maqPenalty) : RefAligner(color, verbose, quiet, seedLen, qualMax, maqPenalty) { } virtual ~Seed3RefAligner() { } protected: /** * This schematic shows the roles played by the begin, qbegin, end, * qend, halfway, slen, qlen, and lim variables: * * seedOnLeft == true: * * |< lim >|< qlen >| * -------------------------------------------------------------- * | | slen | qlen-slen | | slen | qlen-slen | * -------------------------------------------------------------- * ^ ^ ^ ^ * begin & qbegin halfway qend end * * seedOnLeft == false: * * |< qlen >|< lim >| * -------------------------------------------------------------- * | qlen-slen | slen | | qlen-slen | slen | | * -------------------------------------------------------------- * ^ ^ ^ ^ * begin qbegin halfway qend & end * * Note that, for seeds longer than 32 base-pairs, the seed is * further subdivided into a 32-bit anchor and a seed overhang of * length > 0. */ void naiveFind(uint32_t numToFind, uint32_t tidx, uint8_t* ref, const TDna5Str& qry, const TCharStr& quals, uint32_t begin, uint32_t end, TRangeVec& ranges, TU32Vec& results, TSetPairs* pairs, uint32_t aoff, bool seedOnLeft) const { assert_gt(numToFind, 0); assert_gt(end, begin); const uint32_t qlen = seqan::length(qry); assert_gt(qlen, 0); assert_geq(end - begin, qlen); // caller should have checked this assert_gt(this->seedLen_, 0); const uint32_t slen = min(qlen, this->seedLen_); uint32_t qend = end; uint32_t qbegin = begin; // If the seed is on the left-hand side of the alignment, then // leave a gap at the right-hand side of the interval; // otherwise, do the opposite if(seedOnLeft) { // Leave gap on right-hand side of the interval qend -= qlen; } else { // Leave gap on left-hand side of the interval qbegin += qlen; } // lim = number of alignments to try const uint32_t lim = qend - qbegin; // halfway = position in the reference to start at (and then // we work our way out to the right and to the left). const uint32_t halfway = qbegin + (lim >> 1); // Vectors for holding edit information std::vector nonSeedMms; std::vector nonSeedRefcs; bool hi = false; for(uint32_t i = 1; i <= lim+1; i++) { uint32_t ri; // leftmost position in candidate alignment uint32_t rir; // same, minus begin; for indexing into ref[] if(hi) { ri = halfway + (i >> 1); rir = ri - begin; assert_leq(ri, qend); } else { ri = halfway - (i >> 1); rir = ri - begin; assert_geq(ri, begin); } hi = !hi; // Do the naive comparison bool match = true; int refc1 = -1; uint32_t mmOff1 = 0xffffffff; int refc2 = -1; uint32_t mmOff2 = 0xffffffff; int refc3 = -1; uint32_t mmOff3 = 0xffffffff; int mms = 0; int seedMms = 0; unsigned int ham = 0; nonSeedMms.clear(); nonSeedRefcs.clear(); // Walk through each position of the alignment for(uint32_t jj = 0; jj < qlen; jj++) { uint32_t j = jj; if(!seedOnLeft) { // If seed is on the right, scan right-to-left j = qlen - jj - 1; } else { // Go left-to-right } uint32_t rirj = rir + j; if(!seedOnLeft) { assert_geq(rir, jj); rirj = rir - jj - 1; } #if 0 // Count Ns in the reference as mismatches const int q = (int)qry[j]; const int r = (int)ref[rirj]; assert_leq(q, 4); assert_leq(r, 4); if(q == 4 || r == 4 || q != r) { #else // Disallow alignments that involve an N in the // reference const int r = (int)ref[rirj]; if(r & 4) { // N in reference; bail on this alignment match = false; break; } const int q = (int)qry[j]; assert_leq(q, 4); assert_lt(r, 4); if(q != r) { #endif // Mismatch! mms++; if(mms > 3 && jj < slen) { // More than one mismatch in the anchor; reject match = false; break; } uint8_t qual = phredCharToPhredQual(quals[j]); ham += mmPenalty(this->maqPenalty_, qual); if(ham > this->qualMax_) { // Exceeded quality ceiling; reject match = false; break; } else if(mms == 1 && jj < slen) { // First mismatch in the anchor; remember offset // and ref char refc1 = "ACGTN"[r]; mmOff1 = j; seedMms = 1; } else if(mms == 2 && jj < slen) { // Second mismatch in the anchor; remember offset // and ref char refc2 = "ACGTN"[r]; mmOff2 = j; seedMms = 2; } else if(mms == 3 && jj < slen) { // Third mismatch in the anchor; remember offset // and ref char refc3 = "ACGTN"[r]; mmOff3 = j; seedMms = 3; } else { // Legal mismatch outside of the anchor; record it nonSeedMms.push_back(j); assert_leq(nonSeedMms.size(), (size_t)mms); nonSeedRefcs.push_back("ACGTN"[r]); } } } if(match) { ranges.resize(ranges.size()+1); Range& range = ranges.back(); assert_leq(seedMms, mms); range.stratum = seedMms; range.numMms = mms; assert_eq(0, range.mms.size()); assert_eq(0, range.refcs.size()); if(mms >= 1) { // Be careful to add edits in left-to-right order // with respect to the read/alignment if(seedOnLeft && seedMms) { assert_lt(mmOff1, qlen); range.mms.push_back(mmOff1); range.refcs.push_back(refc1); if(seedMms > 1) { assert_lt(mmOff1, mmOff2); assert_lt(mmOff2, qlen); range.mms.push_back(mmOff2); range.refcs.push_back(refc2); if(seedMms > 2) { assert_lt(mmOff2, mmOff3); assert_lt(mmOff3, qlen); range.mms.push_back(mmOff3); range.refcs.push_back(refc3); } } } const size_t nonSeedMmsSz = nonSeedMms.size(); if(nonSeedMmsSz > 0) { if(seedOnLeft) { for(size_t k = 0; k < nonSeedMmsSz; k++) { range.mms.push_back(nonSeedMms[k]); range.refcs.push_back(nonSeedRefcs[k]); } } else { for(size_t k = nonSeedMmsSz; k > 0; k--) { range.mms.push_back(nonSeedMms[k-1]); range.refcs.push_back(nonSeedRefcs[k-1]); } } } if(!seedOnLeft && seedMms) { if(seedMms > 1) { if(seedMms > 2) { assert_lt(mmOff3, mmOff2); assert_lt(mmOff3, qlen); range.mms.push_back(mmOff3); range.refcs.push_back(refc3); } assert_lt(mmOff2, mmOff1); assert_lt(mmOff2, qlen); range.mms.push_back(mmOff2); range.refcs.push_back(refc2); } assert_lt(mmOff1, qlen); range.mms.push_back(mmOff1); range.refcs.push_back(refc1); } } assert_eq((size_t)mms, range.mms.size()); assert_eq((size_t)mms, range.refcs.size()); if(seedOnLeft) { results.push_back(ri); } else { results.push_back(ri - qlen); } } } return; } /** * This schematic shows the roles played by the begin, qbegin, end, * qend, halfway, slen, qlen, and lim variables: * * seedOnLeft == true: * * |< lim >|< qlen >| * -------------------------------------------------------------- * | | slen | qlen-slen | | slen | qlen-slen | * -------------------------------------------------------------- * ^ ^ ^ ^ * begin & qbegin halfway qend end * * seedOnLeft == false: * * |< lim >| * -------------------------------------------------------------- * | qlen-slen | | qlen-slen | slen | | slen | * -------------------------------------------------------------- * ^ ^ ^ ^ ^ * begin qbegin halfway qend end * * Note that, for seeds longer than 32 base-pairs, the seed is * further subdivided into a 32-bit anchor and a seed overhang of * length > 0. */ virtual void anchor64Find(uint32_t numToFind, uint32_t tidx, uint8_t* ref, const TDna5Str& qry, const TCharStr& quals, uint32_t begin, uint32_t end, TRangeVec& ranges, TU32Vec& results, TSetPairs* pairs = NULL, uint32_t aoff = 0xffffffff, bool seedOnLeft = false) const { assert_gt(numToFind, 0); ASSERT_ONLY(const uint32_t rangesInitSz = ranges.size()); ASSERT_ONLY(uint32_t duplicates = 0); ASSERT_ONLY(uint32_t r2i = 0); const uint32_t qlen = seqan::length(qry); assert_gt(qlen, 0); assert_gt(end, begin); assert_geq(end - begin, qlen); // caller should have checked this assert_gt(this->seedLen_, 0); uint32_t slen = min(qlen, this->seedLen_); #ifndef NDEBUG // Get results from the naive matcher for sanity-checking TRangeVec r2; TU32Vec re2; naiveFind(numToFind, tidx, ref, qry, quals, begin, end, r2, re2, pairs, aoff, seedOnLeft); #endif const uint32_t anchorBitPairs = min(slen, 32); const int lhsShift = ((anchorBitPairs - 1) << 1); const uint32_t anchorCushion = 32 - anchorBitPairs; // seedAnchorOverhang = # seed bases not included in the anchor const uint32_t seedAnchorOverhang = (slen <= anchorBitPairs ? 0 : (slen - anchorBitPairs)); // seedAnchorOverhang = # seed bases not included in the anchor const uint32_t readSeedOverhang = (slen == qlen ? 0 : (qlen - slen)); assert(anchorCushion == 0 || seedAnchorOverhang == 0); assert_eq(qlen, readSeedOverhang + slen); uint32_t qend = end; uint32_t qbegin = begin; if(seedOnLeft) { // Leave read-sized gap on right-hand side of the interval qend -= qlen; } else { // Leave seed-sized gap on right-hand side and // non-seed-sized gap on the left-hand side qbegin += readSeedOverhang; qend -= slen; } // lim = # possible alignments in the range const uint32_t lim = qend - qbegin; // halfway = point on the genome to radiate out from const uint32_t halfway = qbegin + (lim >> 1); uint64_t anchor = U64(0); uint64_t buffw = U64(0); // rotating ref sequence buffer // OR the 'diff' buffer with this so that we can always count // 'N's as mismatches uint64_t diffMask = U64(0); // Set up a mask that we'll apply to the two bufs every round // to discard bits that were rotated out of the anchor area uint64_t clearMask = U64(0xffffffffffffffff); bool useMask = false; if(anchorBitPairs < 32) { clearMask >>= ((32-anchorBitPairs) << 1); useMask = true; } int nsInSeed = 0; uint32_t nPoss = 0; int nPos1 = -1; int nPos2 = -1; int nPos3 = -1; uint32_t skipLeftToRights = 0; uint32_t skipRightToLefts = 0; const uint32_t halfwayRi = halfway - begin; // Construct the 'anchor' 64-bit buffer so that it holds all of // the first 'anchorBitPairs' bit pairs of the query. for(uint32_t ii = 0; ii < anchorBitPairs; ii++) { uint32_t i = ii; if(!seedOnLeft) { // Fill in the anchor using characters from the right- // hand side of the query (but take the characters in // left-to-right order). Be sure to subtract slen from // qlen; not anchorBitPairs from qlen. We want the // characters in the seedAnchorOverhang region to be to // the right of the characters in the anchor. i = qlen - slen + ii; } int c = (int)qry[i]; // next query character int r = (int)ref[halfwayRi + ii]; // next reference character if(r & 4) { // The reference character is an N; to mimic the // behavior of BW alignment, we have to skip all // alignments that involve an N in the reference. Set // the skip* variables accordingly. r = 0; uint32_t lrSkips = ii; uint32_t rlSkips = qlen - ii; if(!seedOnLeft && readSeedOverhang) { lrSkips += readSeedOverhang; assert_geq(rlSkips, readSeedOverhang); rlSkips -= readSeedOverhang; } // The right-to-left direction absorbs the candidate // alignment based at 'halfway' skipLeftToRights = max(skipLeftToRights, lrSkips); skipRightToLefts = max(skipRightToLefts, rlSkips); assert_leq(skipLeftToRights, qlen); assert_leq(skipRightToLefts, qlen); } assert_leq(c, 4); assert_lt(r, 4); // Special case: query has an 'N' if(c == 4) { if(++nsInSeed > 3) { // More than one 'N' in the anchor region; can't // possibly have a 1-mismatch hit anywhere assert_eq(r2.size(), ranges.size() - rangesInitSz); return; // can't match if query has Ns } if(nsInSeed == 1) { nPos1 = (int)ii; // w/r/t LHS of anchor } else if(nsInSeed == 2) { nPos2 = (int)ii; // w/r/t LHS of anchor assert_gt(nPos2, nPos1); } else { assert_eq(3, nsInSeed); nPos3 = (int)ii; // w/r/t LHS of anchor assert_gt(nPos3, nPos2); } // Make it look like an 'A' in the anchor c = 0; diffMask = (diffMask << U64(2)) | U64(1); } else { diffMask <<= U64(2); } anchor = ((anchor << U64(2)) | c); buffw = ((buffw << U64(2)) | r); } // Check whether read is disqualified by Ns inside the seed // region but outside the anchor region if(seedAnchorOverhang) { assert_lt(anchorBitPairs, slen); for(uint32_t ii = anchorBitPairs; ii < slen; ii++) { uint32_t i = ii; if(!seedOnLeft) { i = qlen - slen + ii; } if((int)qry[i] == 4) { if(++nsInSeed > 3) { assert_eq(r2.size(), ranges.size() - rangesInitSz); return; // can't match if query has Ns } } } } else { assert_eq(anchorBitPairs, slen); } uint64_t bufbw = buffw; // Slide the anchor out in either direction, alternating // between right-to-left and left-to-right shifts, until all of // the positions from qbegin to qend have been covered. bool hi = false; uint32_t riHi = halfway; uint32_t rirHi = halfway - begin; uint32_t rirHiAnchor = rirHi + anchorBitPairs - 1; uint32_t riLo = halfway + 1; uint32_t rirLo = halfway - begin + 1; uint32_t lrSkips = anchorBitPairs; uint32_t rlSkips = qlen; if(!seedOnLeft && readSeedOverhang) { lrSkips += readSeedOverhang; assert_geq(rlSkips, readSeedOverhang); rlSkips -= readSeedOverhang; } for(uint32_t i = 1; i <= lim + 1; i++) { int r; // new reference char uint64_t diff; assert_leq(skipLeftToRights, qlen); assert_leq(skipRightToLefts, qlen); if(hi) { hi = false; // Moving left-to-right riHi++; rirHi++; rirHiAnchor++; r = (int)ref[rirHiAnchor]; if(r & 4) { r = 0; skipLeftToRights = lrSkips; } assert_lt(r, 4); // Bring in new base pair at the least significant // position buffw = ((buffw << U64(2)) | r); if(useMask) buffw &= clearMask; if(skipLeftToRights > 0) { skipLeftToRights--; continue; } diff = (buffw ^ anchor) | diffMask; } else { hi = true; // Moving right-to-left riLo--; rirLo--; r = (int)ref[rirLo]; if(r & 4) { r = 0; skipRightToLefts = rlSkips; } assert_lt(r, 4); if(i >= 2) { bufbw >>= U64(2); // Bring in new base pair at the most significant // position bufbw |= ((uint64_t)r << lhsShift); } if(skipRightToLefts > 0) { skipRightToLefts--; continue; } diff = (bufbw ^ anchor) | diffMask; } if((diff & U64(0xf000f000f000f000)) && (diff & U64(0x0f000f000f000f00)) && (diff & U64(0x00f000f000f000f0)) && (diff & U64(0x000f000f000f000f))) continue; if((diff & U64(0xc003c003c003c003)) && (diff & U64(0x3c003c003c003c00)) && (diff & U64(0x03c003c003c003c0)) && (diff & U64(0x003c003c003c003c))) continue; uint32_t ri = hi ? riLo : riHi; uint32_t rir = hi ? rirLo : rirHi; // Could use pop count uint8_t *diff8 = reinterpret_cast(&diff); // As a first cut, see if there are too many mismatches in // the first and last parts of the anchor uint32_t diffs = u8toMms[(int)diff8[0]] + u8toMms[(int)diff8[7]]; if(diffs > 3) continue; diffs += u8toMms[(int)diff8[1]] + u8toMms[(int)diff8[2]] + u8toMms[(int)diff8[3]] + u8toMms[(int)diff8[4]] + u8toMms[(int)diff8[5]] + u8toMms[(int)diff8[6]]; uint32_t mmpos1 = 0xffffffff; int refc1 = -1; uint32_t mmpos2 = 0xffffffff; int refc2 = -1; uint32_t mmpos3 = 0xffffffff; int refc3 = -1; unsigned int ham = 0; if(diffs > 3) { // Too many differences in the seed; stop continue; } else if(nPoss > 1 && diffs == nPoss) { // There was one difference, but there was also one N, // so we already know where the difference is mmpos1 = nPos1; refc1 = "ACGT"[(int)ref[rir + nPos1]]; if(!seedOnLeft) { mmpos1 += readSeedOverhang; } char q = quals[mmpos1]; ham += mmPenalty(this->maqPenalty_, phredCharToPhredQual(q)); if(ham > this->qualMax_) { // Exceeded quality limit continue; } if(nPoss > 1) { mmpos2 = nPos2; refc2 = "ACGT"[(int)ref[rir + nPos2]]; if(!seedOnLeft) { mmpos2 += readSeedOverhang; } q = quals[mmpos2]; ham += mmPenalty(this->maqPenalty_, phredCharToPhredQual(q)); if(ham > this->qualMax_) { // Exceeded quality limit continue; } if(nPoss > 3) { mmpos3 = nPos3; refc3 = "ACGT"[(int)ref[rir + nPos3]]; if(!seedOnLeft) { mmpos3 += readSeedOverhang; } q = quals[mmpos3]; ham += mmPenalty(this->maqPenalty_, phredCharToPhredQual(q)); if(ham > this->qualMax_) { // Exceeded quality limit continue; } } } } else if(diffs > 0) { // Figure out which position mismatched uint64_t diff2 = diff; mmpos1 = 31; if((diff & U64(0xffffffff)) == 0) { diff >>= U64(32); mmpos1 -= 16; } assert_neq(0, diff); if((diff & U64(0xffff)) == 0) { diff >>= U64(16); mmpos1 -= 8; } assert_neq(0, diff); if((diff & U64(0xff)) == 0) { diff >>= U64(8); mmpos1 -= 4; } assert_neq(0, diff); if((diff & U64(0xf)) == 0) { diff >>= U64(4); mmpos1 -= 2; } assert_neq(0, diff); if((diff & U64(0x3)) == 0) { mmpos1--; } assert_neq(0, diff); assert_geq(mmpos1, 0); assert_lt(mmpos1, 32); uint32_t savedMmpos1 = mmpos1; mmpos1 -= anchorCushion; assert_lt(mmpos1, anchorBitPairs); refc1 = "ACGT"[(int)ref[rir + mmpos1]]; if(!seedOnLeft) { mmpos1 += readSeedOverhang; } char q = quals[mmpos1]; ham += mmPenalty(this->maqPenalty_, phredCharToPhredQual(q)); if(ham > this->qualMax_) { // Exceeded quality limit continue; } if(diffs > 1) { // Figure out the second mismatched position ASSERT_ONLY(uint64_t origDiff2 = diff2); diff2 &= ~(U64(0xc000000000000000) >> (uint64_t)((savedMmpos1) << 1)); uint64_t diff3 = diff2; assert_neq(diff2, origDiff2); mmpos2 = 31; if((diff2 & U64(0xffffffff)) == 0) { diff2 >>= U64(32); mmpos2 -= 16; } assert_neq(0, diff2); if((diff2 & U64(0xffff)) == 0) { diff2 >>= U64(16); mmpos2 -= 8; } assert_neq(0, diff2); if((diff2 & U64(0xff)) == 0) { diff2 >>= U64(8); mmpos2 -= 4; } assert_neq(0, diff2); if((diff2 & U64(0xf)) == 0) { diff2 >>= U64(4); mmpos2 -= 2; } assert_neq(0, diff2); if((diff2 & U64(0x3)) == 0) { mmpos2--; } assert_neq(0, diff2); assert_geq(mmpos2, 0); assert_lt(mmpos2, 32); uint32_t savedMmpos2 = mmpos2; mmpos2 -= anchorCushion; assert_neq(mmpos1, mmpos2); refc2 = "ACGT"[(int)ref[rir + mmpos2]]; if(!seedOnLeft) { mmpos2 += readSeedOverhang; } q = quals[mmpos2]; ham += mmPenalty(this->maqPenalty_, phredCharToPhredQual(q)); if(ham > this->qualMax_) { // Exceeded quality limit continue; } if(mmpos2 < mmpos1) { uint32_t mmtmp = mmpos1; mmpos1 = mmpos2; mmpos2 = mmtmp; int refctmp = refc1; refc1 = refc2; refc2 = refctmp; } assert_lt(mmpos1, mmpos2); if(diffs > 2) { // Figure out the second mismatched position ASSERT_ONLY(uint32_t origDiff3 = diff3); diff3 &= ~(U64(0xc000000000000000) >> (uint64_t)((savedMmpos2) << 1)); assert_neq(diff3, origDiff3); mmpos3 = 31; if((diff3 & U64(0xffffffff)) == 0) { diff3 >>= U64(32); mmpos3 -= 16; } assert_neq(0, diff3); if((diff3 & U64(0xffff)) == 0) { diff3 >>= U64(16); mmpos3 -= 8; } assert_neq(0, diff3); if((diff3 & U64(0xff)) == 0) { diff3 >>= U64(8); mmpos3 -= 4; } assert_neq(0, diff3); if((diff3 & U64(0xf)) == 0) { diff3 >>= U64(4); mmpos3 -= 2; } assert_neq(0, diff3); if((diff3 & U64(0x3)) == 0) { mmpos3--; } assert_neq(0, diff3); assert_geq(mmpos3, 0); assert_lt(mmpos3, 32); mmpos3 -= anchorCushion; assert_neq(mmpos2, mmpos3); assert_neq(mmpos1, mmpos3); refc3 = "ACGT"[(int)ref[rir + mmpos3]]; if(!seedOnLeft) { mmpos3 += readSeedOverhang; } q = quals[mmpos3]; ham += mmPenalty(this->maqPenalty_, phredCharToPhredQual(q)); if(ham > this->qualMax_) { // Exceeded quality limit continue; } if(mmpos3 < mmpos1) { uint32_t mmtmp = mmpos1; mmpos1 = mmpos3; mmpos3 = mmpos2; mmpos2 = mmtmp; int refctmp = refc1; refc1 = refc3; refc3 = refc2; refc2 = refctmp; } else if(mmpos3 < mmpos2) { uint32_t mmtmp = mmpos2; mmpos2 = mmpos3; mmpos3 = mmtmp; int refctmp = refc2; refc2 = refc3; refc3 = refctmp; } assert_lt(mmpos1, mmpos2); assert_lt(mmpos2, mmpos3); } } } // If the seed is longer than the anchor, then scan the // rest of the seed characters bool foundHit = true; if(seedAnchorOverhang) { for(uint32_t j = 0; j < seedAnchorOverhang; j++) { int rc = (int)ref[rir + anchorBitPairs + j]; if(rc == 4) { // Oops, encountered an N in the reference in // the overhang portion of the candidate // alignment // (Note that we inverted hi earlier) if(hi) { // Right-to-left // Skip out of the seedAnchorOverhang assert_eq(0, skipRightToLefts); skipRightToLefts = seedAnchorOverhang - j - 1; if(seedOnLeft) { // ...and skip out of the rest of the read skipRightToLefts += readSeedOverhang; } } else { // Left-to-right // Skip out of the seedAnchorOverhang assert_eq(0, skipLeftToRights); skipLeftToRights = anchorBitPairs + j; if(!seedOnLeft) { // ...and skip out of the rest of the read skipLeftToRights += readSeedOverhang; } } foundHit = false; // Skip this candidate break; } uint32_t qoff = anchorBitPairs + j; if(!seedOnLeft) { qoff += readSeedOverhang; } assert_lt(qoff, qlen); if((int)qry[qoff] != rc) { diffs++; if(diffs > 3) { foundHit = false; break; } else if(diffs == 3) { assert_eq(0xffffffff, mmpos3); mmpos3 = qoff; assert_eq(-1, refc3); refc3 = "ACGT"[(int)ref[rir + anchorBitPairs + j]]; } else if(diffs == 2) { assert_eq(0xffffffff, mmpos2); mmpos2 = qoff; assert_eq(-1, refc2); refc2 = "ACGT"[(int)ref[rir + anchorBitPairs + j]]; } else { assert_eq(1, diffs); assert_eq(0xffffffff, mmpos1); mmpos1 = qoff; assert_eq(-1, refc1); refc1 = "ACGT"[(int)ref[rir + anchorBitPairs + j]]; } char q = phredCharToPhredQual(quals[qoff]); ham += mmPenalty(this->maqPenalty_, q); if(ham > this->qualMax_) { // Exceeded quality limit foundHit = false; break; } } } if(!foundHit) continue; } // If the read is longer than the seed, then scan the rest // of the read characters; mismatches no longer count // toward the stratum or the 1-mm limit. // Vectors for holding edit information std::vector nonSeedMms; std::vector nonSeedRefcs; int mms = diffs; // start counting total mismatches if((qlen - slen) > 0) { // Going left-to-right for(uint32_t j = 0; j < readSeedOverhang; j++) { uint32_t roff = rir + slen + j; uint32_t qoff = slen + j; if(!seedOnLeft) { assert_geq(roff, qlen); roff -= qlen; qoff = j; } int rc = (int)ref[roff]; if(rc == 4) { // Oops, encountered an N in the reference in // the overhang portion of the candidate // alignment // (Note that we inverted hi earlier) if(hi) { // Right-to-left // Skip what's left of the readSeedOverhang skipRightToLefts = readSeedOverhang - j - 1; if(!seedOnLeft) { // ...and skip the seed if it's on the right skipRightToLefts += slen; } } else { // Left-to-right // Skip what we've matched of the overhang skipLeftToRights = j; if(seedOnLeft) { // ...and skip the seed if it's on the left skipLeftToRights += slen; } } foundHit = false; // Skip this candidate break; } if((int)qry[qoff] != rc) { // Calculate quality of mismatched base char q = phredCharToPhredQual(quals[qoff]); ham += mmPenalty(this->maqPenalty_, q); if(ham > this->qualMax_) { // Exceeded quality limit foundHit = false; break; } // Legal mismatch outside of the anchor; record it mms++; nonSeedMms.push_back(qoff); assert_leq(nonSeedMms.size(), (size_t)mms); nonSeedRefcs.push_back("ACGTN"[rc]); } } if(!foundHit) continue; } assert(foundHit); // Adjust ri if seed is on the right-hand side if(!seedOnLeft) { ri -= readSeedOverhang; rir -= readSeedOverhang; } if(pairs != NULL) { TU64Pair p; if(ri < aoff) { // By convention, the upstream mate's // coordinates go in the 'first' field p.first = ((uint64_t)tidx << 32) | (uint64_t)ri; p.second = ((uint64_t)tidx << 32) | (uint64_t)aoff; } else { p.second = ((uint64_t)tidx << 32) | (uint64_t)ri; p.first = ((uint64_t)tidx << 32) | (uint64_t)aoff; } if(pairs->find(p) != pairs->end()) { // We already found this hit! Continue. ASSERT_ONLY(duplicates++); ASSERT_ONLY(r2i++); continue; } else { // Record this hit pairs->insert(p); } } if(this->verbose_) { cout << "About to report:" << endl; cout << " "; for(size_t i = 0; i < qlen; i++) { cout << (char)qry[i]; } cout << endl; cout << " "; for(size_t i = 0; i < qlen; i++) { cout << "ACGT"[ref[rir+i]]; } cout << endl; } assert_leq(diffs, 3); assert_geq((size_t)mms, diffs); assert_lt(r2i, r2.size()); assert_eq(re2[r2i], ri); ranges.resize(ranges.size()+1); Range& range = ranges.back(); assert_eq((size_t)mms, r2[r2i].numMms); range.stratum = diffs; range.numMms = mms; assert_eq(0, range.mms.size()); assert_eq(0, range.refcs.size()); if(mms > 0) { ASSERT_ONLY(size_t mmcur = 0); if(seedOnLeft && diffs > 0) { assert_neq(mmpos1, 0xffffffff); assert_lt(mmpos1, qlen); assert_lt(mmcur, (size_t)mms); assert_eq(mmpos1, r2[r2i].mms[mmcur]); assert_neq(-1, refc1); assert_eq(refc1, r2[r2i].refcs[mmcur]); ASSERT_ONLY(mmcur++); range.mms.push_back(mmpos1); range.refcs.push_back(refc1); if(diffs > 1) { assert_neq(mmpos2, 0xffffffff); assert_lt(mmpos2, qlen); assert_lt(mmcur, (size_t)mms); assert_eq(mmpos2, r2[r2i].mms[mmcur]); assert_neq(-1, refc2); assert_eq(refc2, r2[r2i].refcs[mmcur]); ASSERT_ONLY(mmcur++); range.mms.push_back(mmpos2); range.refcs.push_back(refc2); if(diffs > 2) { assert_eq(3, diffs); assert_neq(mmpos3, 0xffffffff); assert_lt(mmpos3, qlen); assert_lt(mmcur, (size_t)mms); assert_eq(mmpos3, r2[r2i].mms[mmcur]); assert_neq(-1, refc3); assert_eq(refc3, r2[r2i].refcs[mmcur]); ASSERT_ONLY(mmcur++); range.mms.push_back(mmpos3); range.refcs.push_back(refc3); } } } const size_t nonSeedMmsSz = nonSeedMms.size(); for(size_t i = 0; i < nonSeedMmsSz; i++) { assert_neq(0xffffffff, nonSeedMms[i]); assert_lt(mmcur, (size_t)mms); assert_eq(nonSeedMms[i], r2[r2i].mms[mmcur]); range.mms.push_back(nonSeedMms[i]); assert_eq(nonSeedRefcs[i], r2[r2i].refcs[mmcur]); ASSERT_ONLY(mmcur++); range.refcs.push_back(nonSeedRefcs[i]); } if(!seedOnLeft && diffs > 0) { assert_neq(mmpos1, 0xffffffff); assert_lt(mmpos1, qlen); assert_lt(mmcur, (size_t)mms); assert_eq(mmpos1, r2[r2i].mms[mmcur]); assert_neq(-1, refc1); assert_eq(refc1, r2[r2i].refcs[mmcur]); ASSERT_ONLY(mmcur++); range.mms.push_back(mmpos1); range.refcs.push_back(refc1); if(diffs > 1) { assert_neq(mmpos2, 0xffffffff); assert_lt(mmpos2, qlen); assert_lt(mmcur, (size_t)mms); assert_eq(mmpos2, r2[r2i].mms[mmcur]); assert_neq(-1, refc2); assert_eq(refc2, r2[r2i].refcs[mmcur]); ASSERT_ONLY(mmcur++); range.mms.push_back(mmpos2); range.refcs.push_back(refc2); if(diffs > 2) { assert_eq(3, diffs); assert_neq(mmpos3, 0xffffffff); assert_lt(mmpos3, qlen); assert_lt(mmcur, (size_t)mms); assert_eq(mmpos3, r2[r2i].mms[mmcur]); assert_neq(-1, refc3); assert_eq(refc3, r2[r2i].refcs[mmcur]); ASSERT_ONLY(mmcur++); range.mms.push_back(mmpos3); range.refcs.push_back(refc3); } } } assert_eq(mmcur, r2[r2i].mms.size()); } assert_eq((size_t)mms, range.mms.size()); assert_eq((size_t)mms, range.refcs.size()); ASSERT_ONLY(r2i++); results.push_back(ri); if(--numToFind == 0) return; } assert_leq(duplicates, r2.size()); assert_geq(r2.size() - duplicates, ranges.size() - rangesInitSz); return; // no hit } }; #endif /* REF_ALIGNER_H_ */ ugene-1.9.8/src/plugins_3rdparty/bowtie/src/bowtie/bitset.h0000644000175000017500000002621711651544326022445 0ustar ilyailya#ifndef BITSET_H_ #define BITSET_H_ #include #include #include #include #include #include "assert_helpers.h" #include "threading.h" /** * Given a words array and a size, allocate a new, larger array, moving * data from the old to the new array, and set all newly-allocated * words to 0. Return the new, larger array, which can be substituted * for the old one. The new array is larger than the old by about 50%. */ static inline uint32_t* bitsetRealloc(uint32_t& sz, uint32_t* words, const char *errmsg = NULL) { uint32_t oldsz = sz; if(sz > 0) { sz += (sz >> 1) + 31; // Add 50% more elements, plus a bit sz &= ~31; // Make sure it's 32-aligned } else { sz = 1024; // Start off at 1024 bits to avoid many expansions } assert_gt(sz, oldsz); assert_eq(0, (sz & 31)); uint32_t *newwords; try { newwords = new uint32_t[sz >> 5 /* convert to words */]; } catch(std::bad_alloc& ba) { if(errmsg != NULL) { // Output given error message std::cerr << errmsg; } throw 1; } if(oldsz > 0) { // Move old values into new array memcpy(newwords, words, oldsz >> 3 /* convert to bytes */); } // Initialize all new words to 0 memset(newwords + (oldsz >> 5 /*convert to words*/), 0, (sz - oldsz) >> 3 /* convert to bytes */); return newwords; // return new array } /** * A simple synchronized bitset class. */ class SyncBitset { public: /** * Allocate enough words to accommodate 'sz' bits. Output the given * error message and quit if allocation fails. */ SyncBitset(uint32_t sz, const char *errmsg = NULL) : _errmsg(errmsg) { MUTEX_INIT(_lock); uint32_t nwords = (sz >> 5)+1; // divide by 32 and add 1 try { _words = new uint32_t[nwords]; } catch(std::bad_alloc& ba) { if(_errmsg != NULL) { std::cerr << _errmsg; } throw 1; } assert(_words != NULL); memset(_words, 0, nwords * 4 /* words to bytes */); _sz = nwords << 5 /* words to bits */; } /** * Free memory for words. */ ~SyncBitset() { delete[] _words; } /** * Test whether the given bit is set in an unsynchronized manner. */ bool testUnsync(uint32_t i) { if(i < _sz) { return ((_words[i >> 5] >> (i & 0x1f)) & 1) != 0; } return false; } /** * Test whether the given bit is set in a synchronized manner. */ bool test(uint32_t i) { bool ret; MUTEX_LOCK(_lock); ret = testUnsync(i); MUTEX_UNLOCK(_lock); return ret; } /** * Set a bit in the vector that hasn't been set before. Assert if * it has been set. Uses synchronization. */ void set(uint32_t i) { MUTEX_LOCK(_lock); while(i >= _sz) { // Slow path: bitset needs to be expanded before the // specified bit can be set ASSERT_ONLY(uint32_t oldsz = _sz); expand(); assert_gt(_sz, oldsz); } // Fast path assert_lt(i, _sz); assert(((_words[i >> 5] >> (i & 0x1f)) & 1) == 0); _words[i >> 5] |= (1 << (i & 0x1f)); assert(((_words[i >> 5] >> (i & 0x1f)) & 1) == 1); MUTEX_UNLOCK(_lock); } /** * Set a bit in the vector that might have already been set. Uses * synchronization. */ void setOver(uint32_t i) { MUTEX_LOCK(_lock); while(i >= _sz) { // Slow path: bitset needs to be expanded before the // specified bit can be set ASSERT_ONLY(uint32_t oldsz = _sz); expand(); assert_gt(_sz, oldsz); } // Fast path assert_lt(i, _sz); _words[i >> 5] |= (1 << (i & 0x1f)); assert(((_words[i >> 5] >> (i & 0x1f)) & 1) == 1); MUTEX_UNLOCK(_lock); } private: /** * Expand the size of the _words array by 50% to accommodate more * bits. */ void expand() { uint32_t *newwords = bitsetRealloc(_sz, _words, _errmsg); delete[] _words; // delete old array _words = newwords; // install new array } const char *_errmsg; // error message if an allocation fails uint32_t _sz; // size as # of bits MUTEX_T _lock; // mutex uint32_t *_words; // storage }; /** * A simple unsynchronized bitset class. */ class Bitset { public: Bitset(uint32_t sz, const char *errmsg = NULL) : _errmsg(errmsg) { uint32_t nwords = (sz >> 5)+1; try { _words = new uint32_t[nwords]; } catch(std::bad_alloc& ba) { if(_errmsg != NULL) { std::cerr << _errmsg; } throw 1; } assert(_words != NULL); memset(_words, 0, nwords * 4); _sz = nwords << 5; _cnt = 0; } Bitset(const Bitset& o) : _words(NULL) { this->operator=(o); } ~Bitset() { delete[] _words; } /** * Test whether the given bit is set. */ bool test(uint32_t i) const { bool ret = false; if(i < _sz) { ret = ((_words[i >> 5] >> (i & 0x1f)) & 1) != 0; } return ret; } /** * Set a bit in the vector that hasn't been set before. Assert if * it has been set. */ void set(uint32_t i) { while(i >= _sz) { // Slow path: bitset needs to be expanded before the // specified bit can be set ASSERT_ONLY(uint32_t oldsz = _sz); expand(); assert_gt(_sz, oldsz); } // Fast path assert(((_words[i >> 5] >> (i & 0x1f)) & 1) == 0); _cnt++; _words[i >> 5] |= (1 << (i & 0x1f)); assert(((_words[i >> 5] >> (i & 0x1f)) & 1) == 1); } /** * Set a bit in the vector that might have already been set. */ void setOver(uint32_t i) { while(i >= _sz) { // Slow path: bitset needs to be expanded before the // specified bit can be set ASSERT_ONLY(uint32_t oldsz = _sz); expand(); assert_gt(_sz, oldsz); } // Fast path if(((_words[i >> 5] >> (i & 0x1f)) & 1) == 0) _cnt++; _words[i >> 5] |= (1 << (i & 0x1f)); assert(((_words[i >> 5] >> (i & 0x1f)) & 1) == 1); } /** * Unset all entries. Don't adjust size. */ void clear() { for(size_t i = 0; i < ((_sz+31)>>5); i++) { _words[i] = 0; } _cnt = 0; } /** * Return the number of set bits. */ uint32_t count() const { return _cnt; } /** * Return true iff no bits are set. */ bool empty() const { return _cnt == 0; } /** * Deep copy from given Bitset to this one. */ Bitset& operator=(const Bitset& o) { _errmsg = o._errmsg; _sz = o._sz; _cnt = o._cnt; if(_words != NULL) delete[] _words; _words = new uint32_t[(_sz+31)>>5]; for(size_t i = 0; i < (_sz+31)>>5; i++) { _words[i] = o._words[i]; } return *this; } private: /** * Expand the size of the _words array by 50% to accommodate more * bits. */ void expand() { uint32_t *newwords = bitsetRealloc(_sz, _words, _errmsg); delete[] _words; // delete old array _words = newwords; // install new array } uint32_t _cnt; // number of set bits const char *_errmsg; // error message if an allocation fails uint32_t _sz; // size as # of bits uint32_t *_words; // storage }; /** * A simple fixed-length unsynchronized bitset class. */ template class FixedBitset { public: FixedBitset() : _cnt(0), _size(0) { memset(_words, 0, ((LEN>>5)+1) * 4); } /** * Unset all bits. */ void clear() { memset(_words, 0, ((LEN>>5)+1) * 4); } /** * Return true iff the bit at offset i has been set. */ bool test(uint32_t i) const { bool ret = false; assert_lt(i, LEN); ret = ((_words[i >> 5] >> (i & 0x1f)) & 1) != 0; return ret; } /** * Set the bit at offset i. Assert if the bit was already set. */ void set(uint32_t i) { // Fast path assert_lt(i, LEN); assert(((_words[i >> 5] >> (i & 0x1f)) & 1) == 0); _words[i >> 5] |= (1 << (i & 0x1f)); _cnt++; if(i >= _size) { _size = i+1; } assert(((_words[i >> 5] >> (i & 0x1f)) & 1) == 1); } /** * Set the bit at offset i. Do not assert if the bit was already * set. */ void setOver(uint32_t i) { // Fast path assert_lt(i, LEN); _words[i >> 5] |= (1 << (i & 0x1f)); _cnt++; if(i >= _size) { _size = i+1; } assert(((_words[i >> 5] >> (i & 0x1f)) & 1) == 1); } uint32_t count() const { return _cnt; } uint32_t size() const { return _size; } /** * Return true iff this FixedBitset has the same bits set as * FixedBitset 'that'. */ bool operator== (const FixedBitset& that) const { for(uint32_t i = 0; i < (LEN>>5)+1; i++) { if(_words[i] != that._words[i]) { return false; } } return true; } /** * Return true iff this FixedBitset does not have the same bits set * as FixedBitset 'that'. */ bool operator!= (const FixedBitset& that) const { for(uint32_t i = 0; i < (LEN>>5)+1; i++) { if(_words[i] != that._words[i]) { return true; } } return false; } /** * Return a string-ized version of this FixedBitset. */ std::string str() const { std::ostringstream oss; for(int i = (int)size()-1; i >= 0; i--) { oss << (test(i)? "1" : "0"); } return oss.str(); } private: uint32_t _cnt; uint32_t _size; uint32_t _words[(LEN>>5)+1]; // storage }; /** * A simple fixed-length unsynchronized bitset class. */ class FixedBitset2 { public: FixedBitset2(uint32_t len) : len_(len), _cnt(0), _size(0) { _words = new uint32_t[((len_ >> 5)+1)]; memset(_words, 0, ((len_ >> 5)+1) * 4); } ~FixedBitset2() { delete[] _words; } /** * Unset all bits. */ void clear() { memset(_words, 0, ((len_ >> 5)+1) * 4); _cnt = 0; _size = 0; } /** * Return true iff the bit at offset i has been set. */ bool test(uint32_t i) const { bool ret = false; assert_lt(i, len_); ret = ((_words[i >> 5] >> (i & 0x1f)) & 1) != 0; return ret; } /** * Set the bit at offset i. Assert if the bit was already set. */ void set(uint32_t i) { // Fast path assert_lt(i, len_); assert(((_words[i >> 5] >> (i & 0x1f)) & 1) == 0); _words[i >> 5] |= (1 << (i & 0x1f)); _cnt++; if(i >= _size) { _size = i+1; } assert(((_words[i >> 5] >> (i & 0x1f)) & 1) == 1); } /** * Clear the bit at offset i. Assert if the bit was not already set. */ void clear(uint32_t i) { // Fast path assert_lt(i, len_); assert(((_words[i >> 5] >> (i & 0x1f)) & 1) == 1); _words[i >> 5] &= ~(1 << (i & 0x1f)); _cnt--; if(i >= _size) { _size = i+1; } assert(((_words[i >> 5] >> (i & 0x1f)) & 1) == 0); } /** * Set the bit at offset i. Do not assert if the bit was already * set. */ void setOver(uint32_t i) { // Fast path assert_lt(i, len_); if(((_words[i >> 5] >> (i & 0x1f)) & 1) == 0) { _words[i >> 5] |= (1 << (i & 0x1f)); _cnt++; } if(i >= _size) { _size = i+1; } assert(((_words[i >> 5] >> (i & 0x1f)) & 1) == 1); } uint32_t count() const { return _cnt; } uint32_t size() const { return _size; } /** * Return true iff this FixedBitset has the same bits set as * FixedBitset 'that'. */ bool operator== (const FixedBitset2& that) const { for(uint32_t i = 0; i < (len_>>5)+1; i++) { if(_words[i] != that._words[i]) { return false; } } return true; } /** * Return true iff this FixedBitset does not have the same bits set * as FixedBitset 'that'. */ bool operator!= (const FixedBitset2& that) const { for(uint32_t i = 0; i < (len_>>5)+1; i++) { if(_words[i] != that._words[i]) { return true; } } return false; } /** * Return a string-ized version of this FixedBitset. */ std::string str() const { std::ostringstream oss; for(int i = (int)size()-1; i >= 0; i--) { oss << (test(i)? "1" : "0"); } return oss.str(); } private: const uint32_t len_; uint32_t _cnt; uint32_t _size; uint32_t *_words; // storage }; #endif /* BITSET_H_ */ ugene-1.9.8/src/plugins_3rdparty/bowtie/src/bowtie/ebwt.cpp0000644000175000017500000000335511651544326022445 0ustar ilyailya/* * ebwt.cpp * * Created on: Sep 23, 2009 * Author: Ben Langmead */ #include #include #include #include #include using namespace std; /** * Try to find the Bowtie index specified by the user. First try the * exact path given by the user. Then try the user-provided string * appended onto the path of the "indexes" subdirectory below this * executable, then try the provided string appended onto * "$BOWTIE_INDEXES/". */ string adjustEbwtBase(const string& cmdline, const string& ebwtFileBase, bool verbose = false) { string str = ebwtFileBase; ifstream in; if(verbose) cout << "Trying " << str << endl; in.open((str + ".1.ebwt").c_str(), ios_base::in | ios::binary); if(!in.is_open()) { if(verbose) cout << " didn't work" << endl; in.close(); str = cmdline; size_t st = str.find_last_of("/\\"); if(st != string::npos) { str.erase(st); str += "/indexes/"; } else { str = "indexes/"; } str += ebwtFileBase; if(verbose) cout << "Trying " << str << endl; in.open((str + ".1.ebwt").c_str(), ios_base::in | ios::binary); if(!in.is_open()) { if(verbose) cout << " didn't work" << endl; in.close(); if(getenv("BOWTIE_INDEXES") != NULL) { str = string(getenv("BOWTIE_INDEXES")) + "/" + ebwtFileBase; if(verbose) cout << "Trying " << str << endl; in.open((str + ".1.ebwt").c_str(), ios_base::in | ios::binary); if(!in.is_open()) { if(verbose) cout << " didn't work" << endl; in.close(); } else { if(verbose) cout << " worked" << endl; } } } } if(!in.is_open()) { cerr << "Could not locate a Bowtie index corresponding to basename \"" << ebwtFileBase << "\"" << endl; throw 1; } return str; } ugene-1.9.8/src/plugins_3rdparty/bowtie/src/bowtie/color.h0000644000175000017500000000062411651544326022263 0ustar ilyailya/* * color.h * * Created on: Oct 18, 2009 * Author: Ben Langmead */ #ifndef COLOR_H_ #define COLOR_H_ #include enum { COLOR_RED = 1, COLOR_GREEN, COLOR_YELLOW, COLOR_BLUE, COLOR_WHITE = 7 }; void appendConsoleColor(std::string& s, int color); void setConsoleColor(int color); void appendColor(std::string& s, char color); void printColor(char color); #endif /* COLOR_H_ */ ugene-1.9.8/src/plugins_3rdparty/bowtie/src/bowtie/sam.h0000644000175000017500000001134611651544326021730 0ustar ilyailya/* * sam.h * * Created on: Sep 23, 2009 * Author: Ben Langmead */ #ifndef SAM_H_ #define SAM_H_ #include "refmap.h" #include "annot.h" #include "pat.h" #include "random_source.h" class ReferenceMap; class AnnotationMap; class PatternSourcePerThread; enum { SAM_FLAG_PAIRED = 1, SAM_FLAG_MAPPED_PAIRED = 2, SAM_FLAG_UNMAPPED = 4, SAM_FLAG_MATE_UNMAPPED = 8, SAM_FLAG_QUERY_STRAND = 16, SAM_FLAG_MATE_STRAND = 32, SAM_FLAG_FIRST_IN_PAIR = 64, SAM_FLAG_SECOND_IN_PAIR = 128, SAM_FLAG_NOT_PRIMARY = 256, SAM_FLAG_FAILS_CHECKS = 512, SAM_FLAG_DUPLICATE = 1024 }; /** * Sink that prints lines in SAM format: */ class SAMHitSink : public HitSink { public: /** * Construct a single-stream VerboseHitSink (default) */ SAMHitSink(OutFileBuf* out, int offBase, ReferenceMap *rmap, AnnotationMap *amap, bool fullRef, int defaultMapq, DECL_HIT_DUMPS2) : HitSink(out, PASS_HIT_DUMPS2), offBase_(offBase), defaultMapq_(defaultMapq), rmap_(rmap), amap_(amap), fullRef_(fullRef) { } /** * Construct a multi-stream VerboseHitSink with one stream per * reference string (see --refout) */ SAMHitSink(size_t numOuts, int offBase, ReferenceMap *rmap, AnnotationMap *amap, bool fullRef, int defaultMapq, DECL_HIT_DUMPS2) : HitSink(numOuts, PASS_HIT_DUMPS2), offBase_(offBase), defaultMapq_(defaultMapq), rmap_(rmap), amap_(amap), fullRef_(fullRef) { } /** * Append a SAM alignment to the given output stream. */ static void append(ostream& ss, const Hit& h, int mapq, int xms, const vector* refnames, ReferenceMap *rmap, AnnotationMap *amap, bool fullRef, int offBase); /** * Append a SAM alignment for an aligned read to the given output * stream. */ static void appendAligned(ostream& ss, const Hit& h, int mapq, int xms, const vector* refnames, ReferenceMap *rmap, AnnotationMap *amap, bool fullRef, int offBase); /** * Append a verbose, readable hit to the output stream * corresponding to the hit. */ virtual void append(ostream& ss, const Hit& h) { SAMHitSink::append(ss, h, defaultMapq_, 0, _refnames, rmap_, amap_, fullRef_, offBase_); } /** * Append a verbose, readable hit to the output stream * corresponding to the hit. */ virtual void append(ostream& ss, const Hit& h, int mapq, int xms) { SAMHitSink::append(ss, h, mapq, xms, _refnames, rmap_, amap_, fullRef_, offBase_); } /** * Write the SAM header lines. */ void appendHeaders(OutFileBuf& os, size_t numRefs, const vector& refnames, bool color, bool nosq, ReferenceMap *rmap, const uint32_t* plen, bool fullRef, const char *cmdline, const char *rgline); protected: /** * */ void reportUnOrMax(PatternSourcePerThread& p, vector* hs, bool un); /** * Report a verbose, human-readable alignment to the appropriate * output stream. */ virtual void reportHit(const Hit& h) { reportHit(h, defaultMapq_, 0); } /** * Report a SAM alignment with the given mapping quality and XM * field. */ virtual void reportHit(const Hit& h, int mapq, int xms); /** * Report a batch of SAM alignments (e.g. two mates that should be * printed together) with the given mapping quality and XM field. */ virtual void reportHits(vector& hs, size_t start, size_t end, int mapq, int xms); /** * See sam.cpp */ virtual void reportMaxed(vector& hs, PatternSourcePerThread& p); /** * See sam.cpp */ virtual void reportUnaligned(PatternSourcePerThread& p) { reportUnOrMax(p, NULL, true); } private: int offBase_; /// Add this to reference offsets before outputting. /// (An easy way to make things 1-based instead of /// 0-based) int defaultMapq_; /// Default mapping quality to report when one is /// not specified ReferenceMap *rmap_; /// mapping to reference coordinate system. AnnotationMap *amap_; /// bool fullRef_; /// print full reference name, not just up to whitespace }; #endif /* SAM_H_ */ ugene-1.9.8/src/plugins_3rdparty/bowtie/src/bowtie/spinlock.h0000644000175000017500000000620211651544326022765 0ustar ilyailya#ifndef SPINLOCK_H_ #define SPINLOCK_H_ /** * This non-reentrant spinlock implementation for i386 and x86_64 is * based on free code by Gert Boddaert: * * http://www.codeproject.com/KB/threads/spinlocks.aspx * * Using spinlocks instead of the heavier pthreads mutexes can, in some * cases, help Bowtie perform better for large numbers of threads. */ // (If the user hasn't specified this, then there's no need for any // kind of locking, so we skip this header) #ifdef BOWTIE_PTHREADS #if defined(__GNUC__) #if defined(__x86_64__) || defined(__i386__) #define USE_SPINLOCK #endif #endif #ifdef USE_SPINLOCK #if defined(__x86_64__) #define SPINLOCK_WORD long #else #define SPINLOCK_WORD int #endif class SpinLock { public: // inlined constructor // inlined NON-virtual destructor inline SpinLock() : m_s(1) {} inline ~SpinLock() {} // enter the lock, spinlocks (with/without Sleep) // when mutex is already locked inline void Enter(void) { SPINLOCK_WORD prev_s; do { prev_s = TestAndSet(&m_s, 0); if (m_s == 0 && prev_s == 1) { // The lock and was unlocked and we grabbed it break; } // reluinquish current timeslice (can only // be used when OS available and // we do NOT want to 'spin') // HWSleep(0); } while (true); } // Tries to enter the lock, returns 0 // when mutex is already locked, // returns != 0 when success inline int TryEnter(void) { SPINLOCK_WORD prev_s = TestAndSet(&m_s, 0); if (m_s == 0 && prev_s == 1) { return 1; } return 0; } // Leaves or unlocks the mutex // (should only be called by lock owner) inline void Leave(void) { TestAndSet(&m_s, 1); } protected: // sets BIT value and returns previous // value.in 1 atomic un-interruptable operation SPINLOCK_WORD TestAndSet(SPINLOCK_WORD* pTargetAddress, SPINLOCK_WORD nValue); private: SPINLOCK_WORD m_s; }; // This part is Platform dependent! /* The following piece of code can be found in function AtomicExchange of file atomicops-internals-x86.h under http://google-perftools.googlecode.com/svn/trunk/src/base/ */ #if defined(__x86_64__) #define TAS(_lw, _res) \ asm volatile("xchgq %1,%0":"=r"(_res):"m"(*_lw),"0"(_res):"memory") #elif defined(__i386__) #define TAS(_lw, _res) \ asm volatile("xchgl %1,%0":"=r"(_res):"m"(*_lw),"0"(_res):"memory") #else #error "Architecture is neither x86_64 nor i386 (see spinlock.h)" #endif /* TAS is only defined for GNUC on x86_64 and i386, that is where GNUC x86 inline assembly can be used */ inline SPINLOCK_WORD SpinLock::TestAndSet(SPINLOCK_WORD* pTargetAddress, SPINLOCK_WORD nValue) { #if 0 __asm { mov edx, dword ptr [pTargetAddress] mov eax, nValue lock xchg eax, dword ptr [edx] } #else TAS(pTargetAddress, nValue); return nValue; #endif // mov = 1 CPU cycle // lock = 1 CPU cycle // xchg = 3 CPU cycles } #endif /*USE_SPINLOCK*/ #endif /*BOWTIE_PTHREADS*/ #endif /*SPINLOCK_H_*/ ugene-1.9.8/src/plugins_3rdparty/bowtie/src/bowtie/assert_helpers.h0000644000175000017500000002132611651544326024172 0ustar ilyailya#ifndef ASSERT_HELPERS_H_ #define ASSERT_HELPERS_H_ #include #include #include /** * Assertion for release-enabled assertions */ class ReleaseAssertException : public std::runtime_error { public: ReleaseAssertException(const std::string& msg = "") : std::runtime_error(msg) {} }; /** * Macros for release-enabled assertions, and helper macros to make * all assertion error messages more helpful. */ #ifdef _MSC_VER #ifndef NDEBUG #define ASSERT_ONLY(x, ...) x, __VA_ARGS__ #else #define ASSERT_ONLY(x, ...) #endif #else #ifndef NDEBUG #define ASSERT_ONLY(x...) x #else #define ASSERT_ONLY(x...) #endif #endif #define rt_assert(b) \ if(!(b)) { \ std::cout << "rt_assert at " << __FILE__ << ":" << __LINE__ << std::endl; \ throw ReleaseAssertException(); \ } #define rt_assert_msg(b,msg) \ if(!(b)) { \ std::cout << msg << " at " << __FILE__ << ":" << __LINE__ << std::endl; \ throw ReleaseAssertException(msg); \ } #define rt_assert_eq(ex,ac) \ if(!((ex) == (ac))) { \ std::cout << "rt_assert_eq: expected (" << (ex) << ", 0x" << std::hex << (ex) << std::dec << ") got (" << (ac) << ", 0x" << std::hex << (ac) << std::dec << ")" << std::endl; \ std::cout << __FILE__ << ":" << __LINE__ << std::endl; \ throw ReleaseAssertException(); \ } #define rt_assert_eq_msg(ex,ac,msg) \ if(!((ex) == (ac))) { \ std::cout << "rt_assert_eq: " << msg << ": (" << (ex) << ", 0x" << std::hex << (ex) << std::dec << ") got (" << (ac) << ", 0x" << std::hex << (ac) << std::dec << ")" << std::endl; \ std::cout << __FILE__ << ":" << __LINE__ << std::endl; \ throw ReleaseAssertException(msg); \ } #ifndef NDEBUG #define assert_eq(ex,ac) \ if(!((ex) == (ac))) { \ std::cout << "assert_eq: expected (" << (ex) << ", 0x" << std::hex << (ex) << std::dec << ") got (" << (ac) << ", 0x" << std::hex << (ac) << std::dec << ")" << std::endl; \ std::cout << __FILE__ << ":" << __LINE__ << std::endl; \ assert(0); \ } #define assert_eq_msg(ex,ac,msg) \ if(!((ex) == (ac))) { \ std::cout << "assert_eq: " << msg << ": (" << (ex) << ", 0x" << std::hex << (ex) << std::dec << ") got (" << (ac) << ", 0x" << std::hex << (ac) << std::dec << ")" << std::endl; \ std::cout << __FILE__ << ":" << __LINE__ << std::endl; \ assert(0); \ } #else #define assert_eq(ex,ac) #define assert_eq_msg(ex,ac,msg) #endif #define rt_assert_neq(ex,ac) \ if(!((ex) != (ac))) { \ std::cout << "rt_assert_neq: expected not (" << (ex) << ", 0x" << std::hex << (ex) << std::dec << ") got (" << (ac) << ", 0x" << std::hex << (ac) << std::dec << ")" << std::endl; \ std::cout << __FILE__ << ":" << __LINE__ << std::endl; \ throw ReleaseAssertException(); \ } #define rt_assert_neq_msg(ex,ac,msg) \ if(!((ex) != (ac))) { \ std::cout << "rt_assert_neq: " << msg << ": (" << (ex) << ", 0x" << std::hex << (ex) << std::dec << ") got (" << (ac) << ", 0x" << std::hex << (ac) << std::dec << ")" << std::endl; \ std::cout << __FILE__ << ":" << __LINE__ << std::endl; \ throw ReleaseAssertException(msg); \ } #ifndef NDEBUG #define assert_neq(ex,ac) \ if(!((ex) != (ac))) { \ std::cout << "assert_neq: expected not (" << (ex) << ", 0x" << std::hex << (ex) << std::dec << ") got (" << (ac) << ", 0x" << std::hex << (ac) << std::dec << ")" << std::endl; \ std::cout << __FILE__ << ":" << __LINE__ << std::endl; \ assert(0); \ } #define assert_neq_msg(ex,ac,msg) \ if(!((ex) != (ac))) { \ std::cout << "assert_neq: " << msg << ": (" << (ex) << ", 0x" << std::hex << (ex) << std::dec << ") got (" << (ac) << ", 0x" << std::hex << (ac) << std::dec << ")" << std::endl; \ std::cout << __FILE__ << ":" << __LINE__ << std::endl; \ assert(0); \ } #else #define assert_neq(ex,ac) #define assert_neq_msg(ex,ac,msg) #endif #define rt_assert_gt(a,b) \ if(!((a) > (b))) { \ std::cout << "rt_assert_gt: expected (" << (a) << ") > (" << (b) << ")" << std::endl; \ std::cout << __FILE__ << ":" << __LINE__ << std::endl; \ throw ReleaseAssertException(); \ } #define rt_assert_gt_msg(a,b,msg) \ if(!((a) > (b))) { \ std::cout << "rt_assert_gt: " << msg << ": (" << (a) << ") > (" << (b) << ")" << std::endl; \ std::cout << __FILE__ << ":" << __LINE__ << std::endl; \ throw ReleaseAssertException(msg); \ } #ifndef NDEBUG #define assert_gt(a,b) \ if(!((a) > (b))) { \ std::cout << "assert_gt: expected (" << (a) << ") > (" << (b) << ")" << std::endl; \ std::cout << __FILE__ << ":" << __LINE__ << std::endl; \ assert(0); \ } #define assert_gt_msg(a,b,msg) \ if(!((a) > (b))) { \ std::cout << "assert_gt: " << msg << ": (" << (a) << ") > (" << (b) << ")" << std::endl; \ std::cout << __FILE__ << ":" << __LINE__ << std::endl; \ assert(0); \ } #else #define assert_gt(a,b) #define assert_gt_msg(a,b,msg) #endif #define rt_assert_geq(a,b) \ if(!((a) >= (b))) { \ std::cout << "rt_assert_geq: expected (" << (a) << ") >= (" << (b) << ")" << std::endl; \ std::cout << __FILE__ << ":" << __LINE__ << std::endl; \ throw ReleaseAssertException(); \ } #define rt_assert_geq_msg(a,b,msg) \ if(!((a) >= (b))) { \ std::cout << "rt_assert_geq: " << msg << ": (" << (a) << ") >= (" << (b) << ")" << std::endl; \ std::cout << __FILE__ << ":" << __LINE__ << std::endl; \ throw ReleaseAssertException(msg); \ } #ifndef NDEBUG #define assert_geq(a,b) \ if(!((a) >= (b))) { \ std::cout << "assert_geq: expected (" << (a) << ") >= (" << (b) << ")" << std::endl; \ std::cout << __FILE__ << ":" << __LINE__ << std::endl; \ assert(0); \ } #define assert_geq_msg(a,b,msg) \ if(!((a) >= (b))) { \ std::cout << "assert_geq: " << msg << ": (" << (a) << ") >= (" << (b) << ")" << std::endl; \ std::cout << __FILE__ << ":" << __LINE__ << std::endl; \ assert(0); \ } #else #define assert_geq(a,b) #define assert_geq_msg(a,b,msg) #endif #define rt_assert_lt(a,b) \ if(!(a < b)) { \ std::cout << "rt_assert_lt: expected (" << a << ") < (" << b << ")" << std::endl; \ std::cout << __FILE__ << ":" << __LINE__ << std::endl; \ throw ReleaseAssertException(); \ } #define rt_assert_lt_msg(a,b,msg) \ if(!(a < b)) { \ std::cout << "rt_assert_lt: " << msg << ": (" << a << ") < (" << b << ")" << std::endl; \ std::cout << __FILE__ << ":" << __LINE__ << std::endl; \ throw ReleaseAssertException(msg); \ } #ifndef NDEBUG #define assert_lt(a,b) \ if(!(a < b)) { \ std::cout << "assert_lt: expected (" << a << ") < (" << b << ")" << std::endl; \ std::cout << __FILE__ << ":" << __LINE__ << std::endl; \ assert(0); \ } #define assert_lt_msg(a,b,msg) \ if(!(a < b)) { \ std::cout << "assert_lt: " << msg << ": (" << a << ") < (" << b << ")" << std::endl; \ std::cout << __FILE__ << ":" << __LINE__ << std::endl; \ assert(0); \ } #else #define assert_lt(a,b) #define assert_lt_msg(a,b,msg) #endif #define rt_assert_leq(a,b) \ if(!((a) <= (b))) { \ std::cout << "rt_assert_leq: expected (" << (a) << ") <= (" << (b) << ")" << std::endl; \ std::cout << __FILE__ << ":" << __LINE__ << std::endl; \ throw ReleaseAssertException(); \ } #define rt_assert_leq_msg(a,b,msg) \ if(!((a) <= (b))) { \ std::cout << "rt_assert_leq: " << msg << ": (" << (a) << ") <= (" << (b) << ")" << std::endl; \ std::cout << __FILE__ << ":" << __LINE__ << std::endl; \ throw ReleaseAssertException(msg); \ } #ifndef NDEBUG #define assert_leq(a,b) \ if(!((a) <= (b))) { \ std::cout << "assert_leq: expected (" << (a) << ") <= (" << (b) << ")" << std::endl; \ std::cout << __FILE__ << ":" << __LINE__ << std::endl; \ assert(0); \ } #define assert_leq_msg(a,b,msg) \ if(!((a) <= (b))) { \ std::cout << "assert_leq: " << msg << ": (" << (a) << ") <= (" << (b) << ")" << std::endl; \ std::cout << __FILE__ << ":" << __LINE__ << std::endl; \ assert(0); \ } #else #define assert_leq(a,b) #define assert_leq_msg(a,b,msg) #endif #ifndef NDEBUG #define assert_in(c, s) assert_in2(c, s, __FILE__, __LINE__) static inline void assert_in2(char c, const char *str, const char *file, int line) { const char *s = str; while(*s != '\0') { if(c == *s) return; s++; } std::cout << "assert_in: (" << c << ") not in (" << str << ")" << std::endl; std::cout << file << ":" << line << std::endl; assert(0); } #else #define assert_in(c, s) #endif #ifndef NDEBUG #define assert_range(b, e, v) assert_range_helper(b, e, v, __FILE__, __LINE__) template inline static void assert_range_helper(const T& begin, const T& end, const T& val, const char *file, int line) { if(val < begin || val > end) { std::cout << "assert_range: (" << val << ") not in [" << begin << ", " << end << "]" << std::endl; std::cout << file << ":" << line << std::endl; assert(0); } } #else #define assert_range(b, e, v) #endif #endif /*ASSERT_HELPERS_H_*/ ugene-1.9.8/src/plugins_3rdparty/bowtie/src/bowtie/search_23mm_phase2.c0000644000175000017500000000216211651544326024504 0ustar ilyailya/* * This is a fragment, included from multiple places in ebwt_search.cpp. * It implements the logic of the second phase of the 2/3-mismatch * search routine. It is implemented as a code fragment so that it can * be reused in both the half-index-in-memory and full-index-in-memory * situations. */ { bt2.setReportExacts(false); if(!nofw) { // Set up the revisitability of the halves params.setFw(true); bt2.setQuery(patsrc->bufa()); bt2.setOffs(0, 0, s5, s5, two? s : s5, s); if(bt2.backtrack()) { DONEMASK_SET(patid); continue; } // if nofw is true, then we already did this if(sink->finishedWithStratum(0)) { // no more exact hits are possible DONEMASK_SET(patid); continue; } } if(!norc) { // Try 2/3 backtracks in the 3' half of the reverse complement read params.setFw(false); // looking at reverse complement // Set up the revisitability of the halves bt2.setQuery(patsrc->bufa()); bt2.setOffs(0, 0, s3, s3, two? s : s3, s); if(bt2.backtrack()) { DONEMASK_SET(patid); continue; } } if(nofw && sink->finishedWithStratum(1)) { DONEMASK_SET(patid); continue; } } ugene-1.9.8/src/plugins_3rdparty/bowtie/src/bowtie/ebwt_build.cpp0000644000175000017500000002407411651544326023625 0ustar ilyailya#include "BowtieContext.h" #include #include #include #include #include #include #include #include "assert_helpers.h" #include "endian_swap.h" #include "ebwt.h" #include "formats.h" #include "sequence_io.h" #include "tokenize.h" #include "timer.h" #include "ref_read.h" #include "filebuf.h" #include "reference.h" /** * \file Driver for the bowtie-build indexing tool. */ static void resetOptions() { BowtieContext::getBuildContext()->resetOptions(); } /** * Drive the Ebwt construction process and optionally sanity-check the * result. */ template static void driver(const string& infile, vector& infiles, const string& outfile, bool reverse = false) { struct FileBufHelper { ~FileBufHelper() {for(size_t i = 0; i < v.size(); i++) delete v[i];} vector v; } is_helper; vector &is = is_helper.v; BowtieContext::Build* ctx = BowtieContext::getBuildContext(); bool bisulfite = false; RefReadInParams refparams(ctx->color, reverse ? ctx->reverseType : REF_READ_FORWARD, ctx->nsToAs, bisulfite); assert_gt(infiles.size(), 0); if(ctx->format == CMDLINE) { // Adapt sequence strings to stringstreams open for input stringstream *ss = new stringstream(); for(size_t i = 0; i < infiles.size(); i++) { (*ss) << ">" << i << endl << infiles[i] << endl; } FileBuf *fb = new FileBuf(ss); bool check = (fb != NULL) && (!fb->eof()) && (fb->get() == '>') && (!fb->eof()); ASSERT_ONLY(fb->reset()); if(!check) { throw new BowtieException("invalid reference sequence file"); } is.push_back(fb); } else { // Adapt sequence files to ifstreams for(size_t i = 0; i < infiles.size(); i++) { FILE *f = fopen(infiles[i].c_str(), "r"); if (f == NULL) { ostringstream err; err << "Error: could not open "<< infiles[i] << endl; throw BowtieException(err.str()); } FileBuf *fb = new FileBuf(f); bool check = (fb != NULL) && (!fb->eof()) && (fb->get() == '>') && (!fb->eof()); ASSERT_ONLY(fb->reset()); if(!check) { throw new BowtieException("invalid reference sequence file"); } is.push_back(fb); } } // Vector for the ordered list of "records" comprising the input // sequences. A record represents a stretch of unambiguous // characters in one of the input sequences. vector szs; vector plens; std::pair sztot; { if(ctx->verbose) BowtieContext::verbose("Reading reference sizes"); Timer _t(cout, " Time reading reference sizes: ", ctx->verbose); if(!reverse && (ctx->writeRef || ctx->justRef)) { // For forward reference, dump it to .3.ebwt and .4.ebwt // files string file3 = outfile + ".3.ebwt"; string file4 = outfile + ".4.ebwt"; // Open output stream for the '.3.ebwt' file which will // hold the size records. ofstream fout3(file3.c_str(), ios::binary); if(!fout3.good()) { ostringstream err; err << "Could not open index file for writing: \"" << file3 << "\"" << endl << "Please make sure the directory exists and that permissions allow writing by" << endl << "Bowtie." << endl; throw BowtieException(err.str()); } BitpairOutFileBuf bpout(file4.c_str()); // Read in the sizes of all the unambiguous stretches of // the genome into a vector of RefRecords. The input // streams are reset once it's done. writeU32(fout3, 1, ctx->bigEndian); // endianness sentinel if(ctx->color) { refparams.color = false; // Make sure the .3.ebwt and .4.ebwt files contain // nucleotides; not colors int numSeqs = 0; std::pair sztot2 = fastaRefReadSizes(is, szs, plens, refparams, &bpout, numSeqs); refparams.color = true; writeU32(fout3, szs.size(), ctx->bigEndian); // write # records for(size_t i = 0; i < szs.size(); i++) { szs[i].write(fout3, ctx->bigEndian); } szs.clear(); plens.clear(); // Now read in the colorspace size records; these are // the ones that were indexed int numSeqs2 = 0; sztot = fastaRefReadSizes(is, szs, plens, refparams, NULL, numSeqs2); assert_geq(numSeqs, numSeqs2); //assert_eq(sztot2.second, sztot.second + numSeqs); } else { int numSeqs = 0; sztot = fastaRefReadSizes(is, szs, plens, refparams, &bpout, numSeqs); writeU32(fout3, szs.size(), ctx->bigEndian); // write # records for(size_t i = 0; i < szs.size(); i++) szs[i].write(fout3, ctx->bigEndian); } if(sztot.first == 0) { ostringstream err; err << "Error: No unambiguous stretches of characters in the input. Aborting..." << endl; throw BowtieException(err.str()); } assert_gt(sztot.first, 0); assert_gt(sztot.second, 0); bpout.close(); fout3.close(); #ifndef NDEBUG if(ctx->sanityCheck) { BitPairReference bpr( outfile, // ebwt basename ctx->color, // expect color? true, // sanity check? &infiles,// files to check against NULL, // sequences to check against ctx->format == CMDLINE, // whether infiles contains strings true, // load sequence? false, // use memory-mapped files false, // use shared memory false, // sweep through memory-mapped memory false, // be talkative false); // be talkative } #endif } else { // Read in the sizes of all the unambiguous stretches of the // genome into a vector of RefRecords int numSeqs = 0; sztot = fastaRefReadSizes(is, szs, plens, refparams, NULL, numSeqs); #ifndef NDEBUG if(refparams.color) { refparams.color = false; vector szs2; vector plens2; int numSeqs2 = 0; std::pair sztot2 = fastaRefReadSizes(is, szs2, plens2, refparams, NULL, numSeqs2); assert_leq(numSeqs, numSeqs2); // One less color than base //assert_geq(sztot2.second, sztot.second + numSeqs); refparams.color = true; } #endif } } if(ctx->justRef) return; assert_gt(sztot.first, 0); assert_gt(sztot.second, 0); assert_gt(szs.size(), 0); // Construct Ebwt from input strings and parameters Ebwt ebwt(refparams.color ? 1 : 0, ctx->lineRate, ctx->linesPerSide, ctx->offRate, // suffix-array sampling rate -1, // ISA sampling rate ctx->ftabChars, // number of chars in initial arrow-pair calc outfile, // basename for .?.ebwt files !reverse, // fw !ctx->entireSA, // useBlockwise ctx->bmax, // block size for blockwise SA builder ctx->bmaxMultSqrt, // block size as multiplier of sqrt(len) ctx->bmaxDivN, // block size as divisor of len ctx->noDc? 0 : ctx->dcv,// difference-cover period is, // list of input streams szs, // list of reference sizes plens, // list of not-all-gap reference sequence lengths sztot.first, // total size of all unambiguous ref chars refparams, // reference read-in parameters ctx->seed, // pseudo-random number generator seed -1, // override offRate -1, // override isaRate ctx->verbose, // be talkative ctx->autoMem, // pass exceptions up to the toplevel so that we can adjust memory settings automatically ctx->sanityCheck); // verify results and internal consistency // Note that the Ebwt is *not* resident in memory at this time. To // load it into memory, call ebwt.loadIntoMemory() if(ctx->verbose) { // Print Ebwt's vital stats ebwt.eh().print(cout); } if(ctx->sanityCheck) { // Try restoring the original string (if there were // multiple texts, what we'll get back is the joined, // padded string, not a list) ebwt.loadIntoMemory( refparams.color ? 1 : 0, -1, false, false); TStr s2; ebwt.restore(s2); ebwt.evictFromMemory(); { TStr joinedss = Ebwt::join( is, // list of input streams szs, // list of reference sizes sztot.first, // total size of all unambiguous ref chars refparams, // reference read-in parameters ctx->seed); // pseudo-random number generator seed if(refparams.reverse == REF_READ_REVERSE) { reverseInPlace(joinedss); } assert_eq(length(joinedss), length(s2)); assert_eq(joinedss, s2); } if(ctx->verbose) { if(length(s2) < 1000) { cout << "Passed restore check: " << s2 << endl; } else { cout << "Passed restore check: (" << length(s2) << " chars)" << endl; } } } } static const char *argv0 = NULL; /** * main function. Parses command-line arguments. */ int bowtieBuildAdapter(const string& infile, const string& outfile) { BowtieContext::Build* ctx = BowtieContext::getBuildContext(); resetOptions(); vector infiles; tokenize(infile, ",", infiles); if(infiles.size() < 1) { cerr << "Tokenized input file list was empty!" << endl; return 1; } // Seed random number generator srand(ctx->seed); { if(!ctx->packed) { try { driver > >(infile, infiles, outfile); } catch(bad_alloc& e) { if(ctx->autoMem) { cerr << "Switching to a packed string representation." << endl; ctx->packed = true; } else { throw e; } } } if(ctx->packed) { driver > > >(infile, infiles, outfile); } } if(ctx->doubleEbwt) { ctx->secondEbwtRound = true; srand(ctx->seed); Timer timer(cout, "Total time for backward call to driver() for mirror index: ", ctx->verbose); if(!ctx->packed) { try { driver > >(infile, infiles, outfile + ".rev", true); } catch(bad_alloc& e) { if(ctx->autoMem) { cerr << "Switching to a packed string representation." << endl; ctx->packed = true; } else { throw e; } } } if(ctx->packed) { driver > > >(infile, infiles, outfile + ".rev", true); } } return 0; } ugene-1.9.8/src/plugins_3rdparty/bowtie/src/bowtie/alphabet.cpp0000644000175000017500000002542011651544326023261 0ustar ilyailya#include uint8_t dna4Cat[] = { /* 0 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 16 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 32 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, /* - */ /* 48 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 64 */ 0, 1, 2, 1, 2, 0, 0, 1, 2, 0, 0, 2, 0, 2, 2, 0, /* A B C D G H K M N */ /* 80 */ 0, 0, 2, 2, 1, 0, 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, /* R S T V W X Y */ /* 96 */ 0, 1, 2, 1, 2, 0, 0, 1, 2, 0, 0, 2, 0, 2, 2, 0, /* a b c d g h k m n */ /* 112 */ 0, 0, 2, 2, 1, 0, 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, /* r s t v w x y */ /* 128 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 144 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 160 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 176 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 192 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 208 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 224 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 240 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, }; /// For converting from ASCII to the Dna5 code where A=0, C=1, G=2, /// T=3, N=4 uint8_t charToDna5[] = { /* 0 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 16 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 32 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 48 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 64 */ 0, 0, 0, 1, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 4, 0, /* A C G N */ /* 80 */ 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* T */ /* 96 */ 0, 0, 0, 1, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 4, 0, /* a c g n */ /* 112 */ 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* t */ /* 128 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 144 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 160 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 176 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 192 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 208 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 224 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 240 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, }; /// For converting from ASCII to the reverse-complement Dna5 code where /// A=3, C=2, G=1, T=0, N=4 uint8_t rcCharToDna5[] = { /* 0 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 16 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 32 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 48 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 64 */ 0, 3, 0, 2, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 4, 0, /* A C G N */ /* 80 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* T */ /* 96 */ 0, 3, 0, 2, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 4, 0, /* a c g n */ /* 112 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* t */ /* 128 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 144 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 160 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 176 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 192 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 208 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 224 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 240 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, }; /// For converting from ASCII to the Dna5 code where A=0, C=1, G=2, /// T=3, N=4 uint8_t asc2col[] = { /* 0 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 16 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 32 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 0, /* - . */ /* 48 */ 0, 1, 2, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0 1 2 3 */ /* 64 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 80 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 96 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 112 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 128 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 144 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 160 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 176 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 192 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 208 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 224 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 240 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, }; /** * Mapping from ASCII characters to DNA categories: * * 0 = invalid - error * 1 = DNA * 2 = IUPAC (ambiguous DNA) * 3 = not an error, but unmatchable; alignments containing this * character are invalid */ uint8_t asc2dnacat[] = { /* 0 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 16 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 32 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, /* - */ /* 48 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 64 */ 0, 1, 2, 1, 2, 0, 0, 1, 2, 0, 0, 2, 0, 2, 2, 0, /* A B C D G H K M N */ /* 80 */ 0, 0, 2, 2, 1, 0, 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, /* R S T V W X Y */ /* 96 */ 0, 1, 2, 1, 2, 0, 0, 1, 2, 0, 0, 2, 0, 2, 2, 0, /* a b c d g h k m n */ /* 112 */ 0, 0, 2, 2, 1, 0, 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, /* r s t v w x y */ /* 128 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 144 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 160 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 176 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 192 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 208 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 224 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 240 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, }; /** * Mapping from ASCII characters for ambiguous nucleotides into masks: */ uint8_t asc2dnamask[] = { /* 0 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 16 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 32 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 48 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 64 */ 0, 1,14, 2,13, 0, 0, 4,11, 0, 0,12, 0, 3,15, 0, /* A B C D G H K M N */ /* 80 */ 0, 0, 5, 6, 8, 0, 7, 9, 0,10, 0, 0, 0, 0, 0, 0, /* R S T V W Y */ /* 96 */ 0, 1,14, 2,13, 0, 0, 4,11, 0, 0,12, 0, 3,15, 0, /* a b c d g h k m n */ /* 112 */ 0, 0, 5, 6, 8, 0, 7, 9, 0,10, 0, 0, 0, 0, 0, 0, /* r s t v w y */ /* 128 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 144 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 160 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 176 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 192 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 208 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 224 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 240 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, }; /** * Mapping from ASCII characters for ambiguous nucleotides into masks: */ char asc2dnacomp[] = { /* 0 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 16 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 32 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,'-', 0, 0, /* 48 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 64 */ 0,'T','V','G','H', 0, 0,'C','D', 0, 0,'M', 0,'K','N', 0, /* A B C D G H K M N */ /* 80 */ 0, 0,'Y','S','A', 0,'B','W', 0,'R', 0, 0, 0, 0, 0, 0, /* R S T V W Y */ /* 96 */ 0,'T','V','G','H', 0, 0,'C','D', 0, 0,'M', 0,'K','N', 0, /* a b c d g h k m n */ /* 112 */ 0, 0,'Y','S','A', 0,'B','W', 0,'R', 0, 0, 0, 0, 0, 0, /* r s t v w y */ /* 128 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 144 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 160 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 176 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 192 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 208 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 224 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 240 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; /** * Mapping from ASCII characters to color categories: * * 0 = invalid - error * 1 = valid color * 2 = IUPAC (ambiguous DNA) - there is no such thing for colors to my * knowledge * 3 = not an error, but unmatchable; alignments containing this * character are invalid */ uint8_t asc2colcat[] = { /* 0 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 16 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 32 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 0, /* - . */ /* 48 */ 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0 1 2 3 */ /* 64 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 80 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 96 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 112 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 128 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 144 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 160 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 176 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 192 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 208 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 224 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 240 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, }; /** * Convert a nucleotide and a color to the paired nucleotide. Indexed * first by nucleotide then by color. Note that this is exactly the * same as the dinuc2color array. */ uint8_t nuccol2nuc[5][5] = { /* B G O R . */ /* A */ {0, 1, 2, 3, 4}, /* C */ {1, 0, 3, 2, 4}, /* G */ {2, 3, 0, 1, 4}, /* T */ {3, 2, 1, 0, 4}, /* N */ {4, 4, 4, 4, 4} }; /** * Convert a pair of nucleotides to a color. */ uint8_t dinuc2color[5][5] = { /* A */ {0, 1, 2, 3, 4}, /* C */ {1, 0, 3, 2, 4}, /* G */ {2, 3, 0, 1, 4}, /* T */ {3, 2, 1, 0, 4}, /* N */ {4, 4, 4, 4, 4} }; ugene-1.9.8/src/plugins_3rdparty/bowtie/src/bowtie/shmem.cpp0000644000175000017500000000126311651544326022611 0ustar ilyailya/* * shmem.cpp * * Created on: August 13, 2009 * Author: Ben Langmead */ #ifdef BOWTIE_SHARED_MEM #include #include #include #include #include #include "shmem.h" using namespace std; /** * Notify other users of a shared-memory chunk that the leader has * finished initializing it. */ void notifySharedMem(void *mem, size_t len) { ((volatile uint32_t*)((char*)mem + len))[0] = SHMEM_INIT; } /** * Wait until the leader of a shared-memory chunk has finished * initializing it. */ void waitSharedMem(void *mem, size_t len) { while(((volatile uint32_t*)((char*)mem + len))[0] != SHMEM_INIT) { sleep(1); } } #endif ugene-1.9.8/src/plugins_3rdparty/bowtie/src/bowtie/search_exact.c0000644000175000017500000000134011651544326023565 0ustar ilyailya/* * This is a fragment, included from multiple places in ebwt_search.cpp. * It implements the logic of the exact-search routine. It is * implemented as a code fragment so that it can be reused in both * paired and unpaired alignment. */ { uint32_t plen = length(patsrc->bufa().patFw); if(!nofw) { // Match against forward strand params.setFw(true); bt.setQuery(patsrc->bufa()); bt.setOffs(0, 0, plen, plen, plen, plen); // If we matched on the forward strand, ignore the reverse- // complement strand if(bt.backtrack()) { continue; } } if(!norc) { // Process reverse-complement read params.setFw(false); bt.setQuery(patsrc->bufa()); bt.setOffs(0, 0, plen, plen, plen, plen); bt.backtrack(); } } ugene-1.9.8/src/plugins_3rdparty/bowtie/src/bowtie/ccnt_lut.cpp0000644000175000017500000003243211651544326023315 0ustar ilyailya#include /* Generated by gen_lookup_tables.pl */ uint8_t cCntLUT_4[4][4][256] = { /* All 4 bit pairs */ { /* As */ { 4, 3, 3, 3, 3, 2, 2, 2, 3, 2, 2, 2, 3, 2, 2, 2, 3, 2, 2, 2, 2, 1, 1, 1, 2, 1, 1, 1, 2, 1, 1, 1, 3, 2, 2, 2, 2, 1, 1, 1, 2, 1, 1, 1, 2, 1, 1, 1, 3, 2, 2, 2, 2, 1, 1, 1, 2, 1, 1, 1, 2, 1, 1, 1, 3, 2, 2, 2, 2, 1, 1, 1, 2, 1, 1, 1, 2, 1, 1, 1, 2, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 2, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 2, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 3, 2, 2, 2, 2, 1, 1, 1, 2, 1, 1, 1, 2, 1, 1, 1, 2, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 2, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 2, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 3, 2, 2, 2, 2, 1, 1, 1, 2, 1, 1, 1, 2, 1, 1, 1, 2, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 2, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 2, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, }, /* Cs */ { 0, 1, 0, 0, 1, 2, 1, 1, 0, 1, 0, 0, 0, 1, 0, 0, 1, 2, 1, 1, 2, 3, 2, 2, 1, 2, 1, 1, 1, 2, 1, 1, 0, 1, 0, 0, 1, 2, 1, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 2, 1, 1, 0, 1, 0, 0, 0, 1, 0, 0, 1, 2, 1, 1, 2, 3, 2, 2, 1, 2, 1, 1, 1, 2, 1, 1, 2, 3, 2, 2, 3, 4, 3, 3, 2, 3, 2, 2, 2, 3, 2, 2, 1, 2, 1, 1, 2, 3, 2, 2, 1, 2, 1, 1, 1, 2, 1, 1, 1, 2, 1, 1, 2, 3, 2, 2, 1, 2, 1, 1, 1, 2, 1, 1, 0, 1, 0, 0, 1, 2, 1, 1, 0, 1, 0, 0, 0, 1, 0, 0, 1, 2, 1, 1, 2, 3, 2, 2, 1, 2, 1, 1, 1, 2, 1, 1, 0, 1, 0, 0, 1, 2, 1, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 2, 1, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 2, 1, 1, 0, 1, 0, 0, 0, 1, 0, 0, 1, 2, 1, 1, 2, 3, 2, 2, 1, 2, 1, 1, 1, 2, 1, 1, 0, 1, 0, 0, 1, 2, 1, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 2, 1, 1, 0, 1, 0, 0, 0, 1, 0, 0, }, /* Gs */ { 0, 0, 1, 0, 0, 0, 1, 0, 1, 1, 2, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 1, 2, 1, 0, 0, 1, 0, 1, 1, 2, 1, 1, 1, 2, 1, 2, 2, 3, 2, 1, 1, 2, 1, 0, 0, 1, 0, 0, 0, 1, 0, 1, 1, 2, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 1, 2, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 1, 2, 1, 0, 0, 1, 0, 1, 1, 2, 1, 1, 1, 2, 1, 2, 2, 3, 2, 1, 1, 2, 1, 0, 0, 1, 0, 0, 0, 1, 0, 1, 1, 2, 1, 0, 0, 1, 0, 1, 1, 2, 1, 1, 1, 2, 1, 2, 2, 3, 2, 1, 1, 2, 1, 1, 1, 2, 1, 1, 1, 2, 1, 2, 2, 3, 2, 1, 1, 2, 1, 2, 2, 3, 2, 2, 2, 3, 2, 3, 3, 4, 3, 2, 2, 3, 2, 1, 1, 2, 1, 1, 1, 2, 1, 2, 2, 3, 2, 1, 1, 2, 1, 0, 0, 1, 0, 0, 0, 1, 0, 1, 1, 2, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 1, 2, 1, 0, 0, 1, 0, 1, 1, 2, 1, 1, 1, 2, 1, 2, 2, 3, 2, 1, 1, 2, 1, 0, 0, 1, 0, 0, 0, 1, 0, 1, 1, 2, 1, 0, 0, 1, 0, }, /* Ts */ { 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 1, 2, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 1, 2, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 1, 2, 1, 1, 1, 2, 1, 1, 1, 2, 1, 1, 1, 2, 2, 2, 2, 3, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 1, 2, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 1, 2, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 1, 2, 1, 1, 1, 2, 1, 1, 1, 2, 1, 1, 1, 2, 2, 2, 2, 3, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 1, 2, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 1, 2, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 1, 2, 1, 1, 1, 2, 1, 1, 1, 2, 1, 1, 1, 2, 2, 2, 2, 3, 1, 1, 1, 2, 1, 1, 1, 2, 1, 1, 1, 2, 2, 2, 2, 3, 1, 1, 1, 2, 1, 1, 1, 2, 1, 1, 1, 2, 2, 2, 2, 3, 1, 1, 1, 2, 1, 1, 1, 2, 1, 1, 1, 2, 2, 2, 2, 3, 2, 2, 2, 3, 2, 2, 2, 3, 2, 2, 2, 3, 3, 3, 3, 4, } }, /* Least significant 1 bit pair */ { /* As */ { 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, }, /* Cs */ { 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, }, /* Gs */ { 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, }, /* Ts */ { 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, } }, /* Least significant 2 bit pairs */ { /* As */ { 2, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 2, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 2, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 2, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 2, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 2, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 2, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 2, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 2, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 2, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 2, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 2, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 2, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 2, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 2, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 2, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, }, /* Cs */ { 0, 1, 0, 0, 1, 2, 1, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 2, 1, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 2, 1, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 2, 1, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 2, 1, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 2, 1, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 2, 1, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 2, 1, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 2, 1, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 2, 1, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 2, 1, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 2, 1, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 2, 1, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 2, 1, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 2, 1, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 2, 1, 1, 0, 1, 0, 0, 0, 1, 0, 0, }, /* Gs */ { 0, 0, 1, 0, 0, 0, 1, 0, 1, 1, 2, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 1, 2, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 1, 2, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 1, 2, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 1, 2, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 1, 2, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 1, 2, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 1, 2, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 1, 2, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 1, 2, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 1, 2, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 1, 2, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 1, 2, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 1, 2, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 1, 2, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 1, 2, 1, 0, 0, 1, 0, }, /* Ts */ { 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 1, 2, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 1, 2, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 1, 2, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 1, 2, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 1, 2, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 1, 2, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 1, 2, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 1, 2, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 1, 2, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 1, 2, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 1, 2, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 1, 2, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 1, 2, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 1, 2, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 1, 2, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 1, 2, } }, /* Least significant 3 bit pairs */ { /* As */ { 3, 2, 2, 2, 2, 1, 1, 1, 2, 1, 1, 1, 2, 1, 1, 1, 2, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 2, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 2, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 3, 2, 2, 2, 2, 1, 1, 1, 2, 1, 1, 1, 2, 1, 1, 1, 2, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 2, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 2, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 3, 2, 2, 2, 2, 1, 1, 1, 2, 1, 1, 1, 2, 1, 1, 1, 2, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 2, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 2, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 3, 2, 2, 2, 2, 1, 1, 1, 2, 1, 1, 1, 2, 1, 1, 1, 2, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 2, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 2, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, }, /* Cs */ { 0, 1, 0, 0, 1, 2, 1, 1, 0, 1, 0, 0, 0, 1, 0, 0, 1, 2, 1, 1, 2, 3, 2, 2, 1, 2, 1, 1, 1, 2, 1, 1, 0, 1, 0, 0, 1, 2, 1, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 2, 1, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 2, 1, 1, 0, 1, 0, 0, 0, 1, 0, 0, 1, 2, 1, 1, 2, 3, 2, 2, 1, 2, 1, 1, 1, 2, 1, 1, 0, 1, 0, 0, 1, 2, 1, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 2, 1, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 2, 1, 1, 0, 1, 0, 0, 0, 1, 0, 0, 1, 2, 1, 1, 2, 3, 2, 2, 1, 2, 1, 1, 1, 2, 1, 1, 0, 1, 0, 0, 1, 2, 1, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 2, 1, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 2, 1, 1, 0, 1, 0, 0, 0, 1, 0, 0, 1, 2, 1, 1, 2, 3, 2, 2, 1, 2, 1, 1, 1, 2, 1, 1, 0, 1, 0, 0, 1, 2, 1, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 2, 1, 1, 0, 1, 0, 0, 0, 1, 0, 0, }, /* Gs */ { 0, 0, 1, 0, 0, 0, 1, 0, 1, 1, 2, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 1, 2, 1, 0, 0, 1, 0, 1, 1, 2, 1, 1, 1, 2, 1, 2, 2, 3, 2, 1, 1, 2, 1, 0, 0, 1, 0, 0, 0, 1, 0, 1, 1, 2, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 1, 2, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 1, 2, 1, 0, 0, 1, 0, 1, 1, 2, 1, 1, 1, 2, 1, 2, 2, 3, 2, 1, 1, 2, 1, 0, 0, 1, 0, 0, 0, 1, 0, 1, 1, 2, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 1, 2, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 1, 2, 1, 0, 0, 1, 0, 1, 1, 2, 1, 1, 1, 2, 1, 2, 2, 3, 2, 1, 1, 2, 1, 0, 0, 1, 0, 0, 0, 1, 0, 1, 1, 2, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 1, 2, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 1, 2, 1, 0, 0, 1, 0, 1, 1, 2, 1, 1, 1, 2, 1, 2, 2, 3, 2, 1, 1, 2, 1, 0, 0, 1, 0, 0, 0, 1, 0, 1, 1, 2, 1, 0, 0, 1, 0, }, /* Ts */ { 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 1, 2, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 1, 2, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 1, 2, 1, 1, 1, 2, 1, 1, 1, 2, 1, 1, 1, 2, 2, 2, 2, 3, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 1, 2, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 1, 2, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 1, 2, 1, 1, 1, 2, 1, 1, 1, 2, 1, 1, 1, 2, 2, 2, 2, 3, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 1, 2, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 1, 2, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 1, 2, 1, 1, 1, 2, 1, 1, 1, 2, 1, 1, 1, 2, 2, 2, 2, 3, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 1, 2, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 1, 2, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 1, 2, 1, 1, 1, 2, 1, 1, 1, 2, 1, 1, 1, 2, 2, 2, 2, 3, } } }; ugene-1.9.8/src/plugins_3rdparty/bowtie/src/bowtie/annot.h0000644000175000017500000000220711651544326022263 0ustar ilyailya/* * annot.h * * Created on: Aug 3, 2009 * Author: Ben Langmead */ #ifndef ANNOT_H_ #define ANNOT_H_ #include #include #include #include /** * Encapsulates a sorted list of reference positions that are annotated * somehow (e.g. as a SNP). */ class AnnotationMap { public: typedef std::pair U32Pair; typedef std::pair CharPair; typedef std::map AnnotMap; typedef std::map::const_iterator Iter; AnnotationMap(const char *fname) { fname_ = fname; parse(); } /** * Give a reference coordinate in the index, translate it into a * new reference coordinate via the reference map supplied by the * user. */ Iter lower_bound(const U32Pair& h) const { return map_.lower_bound(h); } Iter begin() const { return map_.begin(); } Iter end() const { return map_.end(); } protected: /** * Parse an annotation-map file. */ void parse(); /// filename of file containing the annotation map const char *fname_; /// maps reference positions to character annotations AnnotMap map_; }; #endif /* ANNOT_H_ */ ugene-1.9.8/src/plugins_3rdparty/bowtie/src/bowtie/annot.cpp0000644000175000017500000000103111651544326022610 0ustar ilyailya/* * annot.cpp * * Created on: Aug 3, 2009 * Author: Ben Langmead */ #include #include "annot.h" using namespace std; /** * Parse an annotation-map file. */ void AnnotationMap::parse() { ifstream in(fname_); if(!in.good() && in.is_open()) { cerr << "Could not open annotation file " << fname_ << endl; throw 1; } while(in.peek() != EOF) { U32Pair pos; CharPair an; in >> pos.first >> pos.second >> an.first >> an.second; map_[pos] = an; while(isspace(in.peek())) in.get(); } in.close(); } ugene-1.9.8/src/plugins_3rdparty/bowtie/src/bowtie/aligner_metrics.h0000644000175000017500000002445611651544326024325 0ustar ilyailya/* * aligner_metrics.h */ #ifndef ALIGNER_METRICS_H_ #define ALIGNER_METRICS_H_ #include #include #include #include "alphabet.h" #include "timer.h" using namespace std; /** * Borrowed from http://www.johndcook.com/standard_deviation.html, * which in turn is borrowed from Knuth. */ class RunningStat { public: RunningStat() : m_n(0), m_tot(0.0) { } void clear() { m_n = 0; m_tot = 0.0; } void push(float x) { m_n++; m_tot += x; // See Knuth TAOCP vol 2, 3rd edition, page 232 if (m_n == 1) { m_oldM = m_newM = x; m_oldS = 0.0; } else { m_newM = m_oldM + (x - m_oldM)/m_n; m_newS = m_oldS + (x - m_oldM)*(x - m_newM); // set up for next iteration m_oldM = m_newM; m_oldS = m_newS; } } int num() const { return m_n; } double tot() const { return m_tot; } double mean() const { return (m_n > 0) ? m_newM : 0.0; } double variance() const { return ( (m_n > 1) ? m_newS/(m_n - 1) : 0.0 ); } double stddev() const { return sqrt(variance()); } private: int m_n; double m_tot; double m_oldM, m_newM, m_oldS, m_newS; }; /** * Encapsulates a set of metrics that we would like an aligner to keep * track of, so that we can possibly use it to diagnose performance * issues. */ class AlignerMetrics { public: AlignerMetrics() : curBacktracks_(0), curBwtOps_(0), first_(true), curIsLowEntropy_(false), curIsHomoPoly_(false), curHadRanges_(false), curNumNs_(0), reads_(0), homoReads_(0), lowEntReads_(0), hiEntReads_(0), alignedReads_(0), unalignedReads_(0), threeOrMoreNReads_(0), lessThanThreeNRreads_(0), bwtOpsPerRead_(), backtracksPerRead_(), bwtOpsPerHomoRead_(), backtracksPerHomoRead_(), bwtOpsPerLoEntRead_(), backtracksPerLoEntRead_(), bwtOpsPerHiEntRead_(), backtracksPerHiEntRead_(), bwtOpsPerAlignedRead_(), backtracksPerAlignedRead_(), bwtOpsPerUnalignedRead_(), backtracksPerUnalignedRead_(), bwtOpsPer0nRead_(), backtracksPer0nRead_(), bwtOpsPer1nRead_(), backtracksPer1nRead_(), bwtOpsPer2nRead_(), backtracksPer2nRead_(), bwtOpsPer3orMoreNRead_(), backtracksPer3orMoreNRead_(), timer_(cout, "", false) { } void printSummary() { if(!first_) { finishRead(); } cout << "AlignerMetrics:" << endl; cout << " # Reads: " << reads_ << endl; float hopct = (reads_ > 0) ? (((float)homoReads_)/((float)reads_)) : (0.0); hopct *= 100.0; cout << " % homo-polymeric: " << (hopct) << endl; float lopct = (reads_ > 0) ? ((float)lowEntReads_/(float)(reads_)) : (0.0); lopct *= 100.0; cout << " % low-entropy: " << (lopct) << endl; float unpct = (reads_ > 0) ? ((float)unalignedReads_/(float)(reads_)) : (0.0); unpct *= 100.0; cout << " % unaligned: " << (unpct) << endl; float npct = (reads_ > 0) ? ((float)threeOrMoreNReads_/(float)(reads_)) : (0.0); npct *= 100.0; cout << " % with 3 or more Ns: " << (npct) << endl; cout << endl; cout << " Total BWT ops: avg: " << bwtOpsPerRead_.mean() << ", stddev: " << bwtOpsPerRead_.stddev() << endl; cout << " Total Backtracks: avg: " << backtracksPerRead_.mean() << ", stddev: " << backtracksPerRead_.stddev() << endl; time_t elapsed = timer_.elapsed(); cout << " BWT ops per second: " << (bwtOpsPerRead_.tot()/elapsed) << endl; cout << " Backtracks per second: " << (backtracksPerRead_.tot()/elapsed) << endl; cout << endl; cout << " Homo-poly:" << endl; cout << " BWT ops: avg: " << bwtOpsPerHomoRead_.mean() << ", stddev: " << bwtOpsPerHomoRead_.stddev() << endl; cout << " Backtracks: avg: " << backtracksPerHomoRead_.mean() << ", stddev: " << backtracksPerHomoRead_.stddev() << endl; cout << " Low-entropy:" << endl; cout << " BWT ops: avg: " << bwtOpsPerLoEntRead_.mean() << ", stddev: " << bwtOpsPerLoEntRead_.stddev() << endl; cout << " Backtracks: avg: " << backtracksPerLoEntRead_.mean() << ", stddev: " << backtracksPerLoEntRead_.stddev() << endl; cout << " High-entropy:" << endl; cout << " BWT ops: avg: " << bwtOpsPerHiEntRead_.mean() << ", stddev: " << bwtOpsPerHiEntRead_.stddev() << endl; cout << " Backtracks: avg: " << backtracksPerHiEntRead_.mean() << ", stddev: " << backtracksPerHiEntRead_.stddev() << endl; cout << endl; cout << " Unaligned:" << endl; cout << " BWT ops: avg: " << bwtOpsPerUnalignedRead_.mean() << ", stddev: " << bwtOpsPerUnalignedRead_.stddev() << endl; cout << " Backtracks: avg: " << backtracksPerUnalignedRead_.mean() << ", stddev: " << backtracksPerUnalignedRead_.stddev() << endl; cout << " Aligned:" << endl; cout << " BWT ops: avg: " << bwtOpsPerAlignedRead_.mean() << ", stddev: " << bwtOpsPerAlignedRead_.stddev() << endl; cout << " Backtracks: avg: " << backtracksPerAlignedRead_.mean() << ", stddev: " << backtracksPerAlignedRead_.stddev() << endl; cout << endl; cout << " 0 Ns:" << endl; cout << " BWT ops: avg: " << bwtOpsPer0nRead_.mean() << ", stddev: " << bwtOpsPer0nRead_.stddev() << endl; cout << " Backtracks: avg: " << backtracksPer0nRead_.mean() << ", stddev: " << backtracksPer0nRead_.stddev() << endl; cout << " 1 N:" << endl; cout << " BWT ops: avg: " << bwtOpsPer1nRead_.mean() << ", stddev: " << bwtOpsPer1nRead_.stddev() << endl; cout << " Backtracks: avg: " << backtracksPer1nRead_.mean() << ", stddev: " << backtracksPer1nRead_.stddev() << endl; cout << " 2 Ns:" << endl; cout << " BWT ops: avg: " << bwtOpsPer2nRead_.mean() << ", stddev: " << bwtOpsPer2nRead_.stddev() << endl; cout << " Backtracks: avg: " << backtracksPer2nRead_.mean() << ", stddev: " << backtracksPer2nRead_.stddev() << endl; cout << " >2 Ns:" << endl; cout << " BWT ops: avg: " << bwtOpsPer3orMoreNRead_.mean() << ", stddev: " << bwtOpsPer3orMoreNRead_.stddev() << endl; cout << " Backtracks: avg: " << backtracksPer3orMoreNRead_.mean() << ", stddev: " << backtracksPer3orMoreNRead_.stddev() << endl; cout << endl; } /** * */ void nextRead(const seqan::String& read) { if(!first_) { finishRead(); } first_ = false; float ent = entropyDna5(read); curIsLowEntropy_ = (ent < 0.75f); curIsHomoPoly_ = (ent < 0.001f); curHadRanges_ = false; curBwtOps_ = 0; curBacktracks_ = 0; // Count Ns curNumNs_ = 0; const size_t len = seqan::length(read); for(size_t i = 0; i < len; i++) { if((int)read[i] == 4) curNumNs_++; } } /** * */ void setReadHasRange() { curHadRanges_ = true; } /** * Commit the running statistics for this read to */ void finishRead() { reads_++; if(curIsHomoPoly_) homoReads_++; else if(curIsLowEntropy_) lowEntReads_++; else hiEntReads_++; if(curHadRanges_) alignedReads_++; else unalignedReads_++; bwtOpsPerRead_.push((float)curBwtOps_); backtracksPerRead_.push((float)curBacktracks_); // Drill down by entropy if(curIsHomoPoly_) { bwtOpsPerHomoRead_.push((float)curBwtOps_); backtracksPerHomoRead_.push((float)curBacktracks_); } else if(curIsLowEntropy_) { bwtOpsPerLoEntRead_.push((float)curBwtOps_); backtracksPerLoEntRead_.push((float)curBacktracks_); } else { bwtOpsPerHiEntRead_.push((float)curBwtOps_); backtracksPerHiEntRead_.push((float)curBacktracks_); } // Drill down by whether it aligned if(curHadRanges_) { bwtOpsPerAlignedRead_.push((float)curBwtOps_); backtracksPerAlignedRead_.push((float)curBacktracks_); } else { bwtOpsPerUnalignedRead_.push((float)curBwtOps_); backtracksPerUnalignedRead_.push((float)curBacktracks_); } if(curNumNs_ == 0) { lessThanThreeNRreads_++; bwtOpsPer0nRead_.push((float)curBwtOps_); backtracksPer0nRead_.push((float)curBacktracks_); } else if(curNumNs_ == 1) { lessThanThreeNRreads_++; bwtOpsPer1nRead_.push((float)curBwtOps_); backtracksPer1nRead_.push((float)curBacktracks_); } else if(curNumNs_ == 2) { lessThanThreeNRreads_++; bwtOpsPer2nRead_.push((float)curBwtOps_); backtracksPer2nRead_.push((float)curBacktracks_); } else { threeOrMoreNReads_++; bwtOpsPer3orMoreNRead_.push((float)curBwtOps_); backtracksPer3orMoreNRead_.push((float)curBacktracks_); } } // Running-total of the number of backtracks and BWT ops for the // current read uint32_t curBacktracks_; uint32_t curBwtOps_; protected: bool first_; // true iff the current read is low entropy bool curIsLowEntropy_; // true if current read is all 1 char (or very close) bool curIsHomoPoly_; // true iff the current read has had one or more ranges reported bool curHadRanges_; // number of Ns in current read int curNumNs_; // # reads uint32_t reads_; // # homo-poly reads uint32_t homoReads_; // # low-entropy reads uint32_t lowEntReads_; // # high-entropy reads uint32_t hiEntReads_; // # reads with alignments uint32_t alignedReads_; // # reads without alignments uint32_t unalignedReads_; // # reads with 3 or more Ns uint32_t threeOrMoreNReads_; // # reads with < 3 Ns uint32_t lessThanThreeNRreads_; // Distribution of BWT operations per read RunningStat bwtOpsPerRead_; RunningStat backtracksPerRead_; // Distribution of BWT operations per homo-poly read RunningStat bwtOpsPerHomoRead_; RunningStat backtracksPerHomoRead_; // Distribution of BWT operations per low-entropy read RunningStat bwtOpsPerLoEntRead_; RunningStat backtracksPerLoEntRead_; // Distribution of BWT operations per high-entropy read RunningStat bwtOpsPerHiEntRead_; RunningStat backtracksPerHiEntRead_; // Distribution of BWT operations per read that "aligned" (for // which a range was arrived at - range may not have necessarily // lead to an alignment) RunningStat bwtOpsPerAlignedRead_; RunningStat backtracksPerAlignedRead_; // Distribution of BWT operations per read that didn't align RunningStat bwtOpsPerUnalignedRead_; RunningStat backtracksPerUnalignedRead_; // Distribution of BWT operations/backtracks per read with no Ns RunningStat bwtOpsPer0nRead_; RunningStat backtracksPer0nRead_; // Distribution of BWT operations/backtracks per read with one N RunningStat bwtOpsPer1nRead_; RunningStat backtracksPer1nRead_; // Distribution of BWT operations/backtracks per read with two Ns RunningStat bwtOpsPer2nRead_; RunningStat backtracksPer2nRead_; // Distribution of BWT operations/backtracks per read with three or // more Ns RunningStat bwtOpsPer3orMoreNRead_; RunningStat backtracksPer3orMoreNRead_; Timer timer_; }; #endif /* ALIGNER_METRICS_H_ */ ugene-1.9.8/src/plugins_3rdparty/bowtie/src/bowtie/timer.h0000644000175000017500000000320011651544326022256 0ustar ilyailya#ifndef TIMER_H_ #define TIMER_H_ #include #include #include using namespace std; /** * Use time() call to keep track of elapsed time between creation and * destruction. If verbose is true, Timer will print a message showing * elapsed time to the given output stream upon destruction. */ class Timer { public: Timer(ostream& out = cout, const char *msg = "", bool verbose = true) : _t(time(0)), _out(out), _msg(msg), _verbose(verbose) { } /// Optionally print message ~Timer() { if(_verbose) write(_out); } /// Return elapsed time since Timer object was created time_t elapsed() const { return time(0) - _t; } void write(ostream& out) { time_t passed = elapsed(); // Print the message supplied at construction time followed // by time elapsed formatted HH:MM:SS unsigned int hours = (passed / 60) / 60; unsigned int minutes = (passed / 60) % 60; unsigned int seconds = (passed % 60); ostringstream _out; _out << _msg << setfill ('0') << setw (2) << hours << ":" << setfill ('0') << setw (2) << minutes << ":" << setfill ('0') << setw (2) << seconds << endl; BowtieContext::verbose(_out.str()); } private: time_t _t; ostream& _out; const char *_msg; bool _verbose; }; static inline void logTime(std::ostream& os, bool nl = true) { struct tm *current; time_t now; time(&now); current = localtime(&now); os << setfill('0') << setw(2) << current->tm_hour << ":" << setfill('0') << setw(2) << current->tm_min << ":" << setfill('0') << setw(2) << current->tm_sec; if(nl) os << std::endl; } #endif /*TIMER_H_*/ ugene-1.9.8/src/plugins_3rdparty/bowtie/src/bowtie/refmap.cpp0000644000175000017500000000257611651544326022762 0ustar ilyailya/* * refmap.cpp * * Created on: Aug 3, 2009 * Author: Ben Langmead */ #include #include "refmap.h" #include "assert_helpers.h" using namespace std; /** * Given a refid,offset pair in the index space, transform it into the * reference coordinate space according to the reference mappings * provided by the user. */ void ReferenceMap::map(U32Pair& h) const { if(h.first >= map_.size()) { cerr << "Could not find a reference-map entry for reference " << h.first << " in map file \"" << fname_ << "\"" << endl; throw 1; } h.second += map_[h.first].second; h.first = map_[h.first].first; } /** * Parse a reference-map file. */ void ReferenceMap::parse() { ifstream in(fname_); if(!in.good() || !in.is_open()) { cerr << "Could not open reference map file " << fname_ << endl; throw 1; } int c; while((c = in.peek()) != EOF) { if(c == '>') { // This appears to be a name line in.get(); // chop off the initial '>' uint32_t off; in >> off; in.get(); // chop off tab char buf[1024]; in.getline(buf, 1023); if(parseNames_) { if(names_.size() <= off) names_.resize(off+1); names_[off] = string(buf); } continue; } uint32_t id, off; in >> id >> off; map_.resize(map_.size()+1); map_.back().first = id; map_.back().second = off; while(isspace(in.peek())) in.get(); } assert_eq(EOF, c); in.close(); } ugene-1.9.8/src/plugins_3rdparty/bowtie/src/bowtie/bowtie_inspect.cpp0000644000175000017500000003561711651544326024530 0ustar ilyailya#include #include #include #include #include #include #include "assert_helpers.h" #include "endian_swap.h" #include "ebwt.h" #include "reference.h" using namespace std; using namespace seqan; static bool showVersion = false; // just print version and quit? int verbose = 0; // be talkative static int names_only = 0; // just print the sequence names in the index static int summarize_only = 0; // just print summary of index and quit static int across = 60; // number of characters across in FASTA output static bool extra = false; // print extra summary info static bool exclAllGaps = false; // print extra summary info static bool refFromEbwt = false; // true -> when printing reference, decode it from Ebwt instead of reading it from BitPairReference static const char *short_options = "vhnsea:"; enum { ARG_VERSION = 256, ARG_USAGE, ARG_EXTRA, ARG_EXCL_AMBIG }; static struct option long_options[] = { {(char*)"verbose", no_argument, 0, 'v'}, {(char*)"version", no_argument, 0, ARG_VERSION}, {(char*)"usage", no_argument, 0, ARG_USAGE}, {(char*)"extra", no_argument, 0, ARG_EXTRA}, {(char*)"excl-ambig",no_argument, 0, ARG_EXCL_AMBIG}, {(char*)"names", no_argument, 0, 'n'}, {(char*)"summary", no_argument, 0, 's'}, {(char*)"help", no_argument, 0, 'h'}, {(char*)"across", required_argument, 0, 'a'}, {(char*)"ebwt-ref", no_argument, 0, 'e'}, {(char*)0, 0, 0, 0} // terminator }; /** * Print a summary usage message to the provided output stream. */ static void printUsage(ostream& out) { out << "Usage: bowtie-inspect [options]* " << endl << " ebwt filename minus trailing .1.ebwt/.2.ebwt" << endl << endl << " By default, prints FASTA records of the indexed nucleotide sequences to" << endl << " standard out. With -n, just prints names. With -s, just prints a summary of" << endl << " the index parameters and sequences. With -e, preserves colors if applicable." << endl << endl << "Options:" << endl << " -a/--across Number of characters across in FASTA output (default: 60)" << endl << " -n/--names Print reference sequence names only" << endl << " -s/--summary Print summary incl. ref names, lengths, index properties" << endl << " -e/--ebwt-ref Reconstruct reference from ebwt (slow, preserves colors)" << endl << " -v/--verbose Verbose output (for debugging)" << endl << " -h/--help print detailed description of tool and its options" << endl << " --help print this usage message" << endl ; } /** * Parse an int out of optarg and enforce that it be at least 'lower'; * if it is less than 'lower', than output the given error message and * exit with an error and a usage message. */ static int parseInt(int lower, const char *errmsg) { long l; char *endPtr= NULL; l = strtol(optarg, &endPtr, 10); if (endPtr != NULL) { if (l < lower) { cerr << errmsg << endl; printUsage(cerr); throw 1; } return (int32_t)l; } cerr << errmsg << endl; printUsage(cerr); throw 1; return -1; } /** * Read command-line arguments */ static void parseOptions(int argc, char **argv) { int option_index = 0; int next_option; do { next_option = getopt_long(argc, argv, short_options, long_options, &option_index); switch (next_option) { case ARG_USAGE: case 'h': printUsage(cout); throw 0; break; case 'v': verbose = true; break; case ARG_VERSION: showVersion = true; break; case ARG_EXCL_AMBIG: exclAllGaps = true; break; case ARG_EXTRA: extra = true; break; case 'e': refFromEbwt = true; break; case 'n': names_only = true; break; case 's': summarize_only = true; break; case 'a': across = parseInt(-1, "-a/--across arg must be at least 1"); break; case -1: break; /* Done with options. */ case 0: if (long_options[option_index].flag != 0) break; default: printUsage(cerr); throw 1; } } while(next_option != -1); } void print_fasta_record(ostream& fout, const string& defline, const string& seq) { fout << ">"; fout << defline << endl; if(across > 0) { size_t i = 0; while (i + across < seq.length()) { fout << seq.substr(i, across) << endl; i += across; } if (i < seq.length()) fout << seq.substr(i) << endl; } else { fout << seq << endl; } } /** * Given output stream, name and length, print a string of Ns with the * appropriate number of columns. */ void print_alln_ref_sequence( ostream& fout, const string& name, size_t len) { fout << ">" << name << "\n"; size_t j = 0; for(size_t i = 0; i < len; i += across) { while(j < len && j < i+across) { fout << 'N'; j++; } fout << "\n"; } } /** * Given output stream, BitPairReference, reference index, name and * length, print the whole nucleotide reference with the appropriate * number of columns. */ void print_ref_sequence( ostream& fout, BitPairReference& ref, const string& name, size_t refi, size_t len) { bool newlines = across > 0; int myacross = across > 0 ? across : 60; size_t incr = myacross * 1000; uint32_t *buf = new uint32_t[(incr + 128)/4]; fout << ">" << name << "\n"; for(size_t i = 0; i < len; i += incr) { size_t amt = min(incr, len-i); assert_leq(amt, incr); int off = ref.getStretch(buf, refi, i, amt); uint8_t *cb = ((uint8_t*)buf) + off; for(size_t j = 0; j < amt; j++) { if(newlines && j > 0 && (j % myacross) == 0) fout << "\n"; assert_range(0, 4, (int)cb[j]); fout << "ACGTN"[(int)cb[j]]; } fout << "\n"; } delete[] buf; } /** * Create a BitPairReference encapsulating the reference portion of the * index at the given basename. Iterate through the reference * sequences, sending each one to print_ref_sequence to print. */ void print_ref_sequences( ostream& fout, bool color, const vector& refnames, const uint32_t* plen, const string& adjustedEbwtFileBase) { BitPairReference ref( adjustedEbwtFileBase, // input basename color, // true -> expect colorspace reference false, // sanity-check reference NULL, // infiles NULL, // originals false, // infiles are sequences true, // load sequence false, // memory-map false, // use shared memory false, // sweep mm-mapped ref verbose, // be talkative verbose); // be talkative at startup #ifdef ACCOUNT_FOR_ALL_GAP_REFS for(size_t i = 0; i < ref.numRefs(); i++) { if(ref.isAllGaps(i) && !exclAllGaps) { print_alln_ref_sequence( fout, refnames[i], ref.len(i)); } else { print_ref_sequence( fout, ref, refnames[i], ref.shrinkIdx(i), ref.len(i)); } } #else assert_eq(refnames.size(), ref.numNonGapRefs()); for(size_t i = 0; i < ref.numNonGapRefs(); i++) { print_ref_sequence( fout, ref, refnames[i], i, plen[i] + (color ? 1 : 0)); } #endif } /** * Given an index, reconstruct the reference by LF mapping through the * entire thing. */ template void print_index_sequences( ostream& fout, Ebwt& ebwt, const BitPairReference& refs) { vector* refnames = &(ebwt.refnames()); TStr cat_ref; ebwt.restore(cat_ref); uint32_t curr_ref = 0xffffffff; string curr_ref_seq = ""; uint32_t curr_ref_len = 0xffffffff; uint32_t last_text_off = 0; size_t orig_len = seqan::length(cat_ref); uint32_t tlen = 0xffffffff; bool first = true; for(size_t i = 0; i < orig_len; i++) { uint32_t tidx = 0xffffffff; uint32_t textoff = 0xffffffff; tlen = 0xffffffff; ebwt.joinedToTextOff(1 /* qlen */, i, tidx, textoff, tlen); if (tidx != 0xffffffff && textoff < tlen) { if (curr_ref != tidx) { if (curr_ref != 0xffffffff) { // Add trailing gaps, if any exist if(curr_ref_seq.length() < curr_ref_len) { curr_ref_seq += string(curr_ref_len - curr_ref_seq.length(), 'N'); } print_fasta_record(fout, (*refnames)[curr_ref], curr_ref_seq); } curr_ref = tidx; curr_ref_seq = ""; curr_ref_len = tlen; last_text_off = 0; first = true; } uint32_t textoff_adj = textoff; if(first && textoff > 0) textoff_adj++; if (textoff_adj - last_text_off > 1) curr_ref_seq += string(textoff_adj - last_text_off - 1, 'N'); curr_ref_seq.push_back(getValue(cat_ref,i)); last_text_off = textoff; first = false; } } if (curr_ref < refnames->size()) { // Add trailing gaps, if any exist if(curr_ref_seq.length() < curr_ref_len) { curr_ref_seq += string(curr_ref_len - curr_ref_seq.length(), 'N'); } print_fasta_record(fout, (*refnames)[curr_ref], curr_ref_seq); } } static char *argv0 = NULL; void print_index_sequence_names(const string& fname, ostream& fout) { vector p_refnames; readEbwtRefnames(fname, p_refnames); for(size_t i = 0; i < p_refnames.size(); i++) { cout << p_refnames[i] << endl; } } typedef Ebwt > > > TPackedEbwt; /** * Print a short summary of what's in the index and its flags. */ void print_index_summary( const string& fname, ostream& fout, const BitPairReference& refs) { int32_t flags = readFlags(fname); int32_t flagsr = readFlags(fname + ".rev"); bool color = readEbwtColor(fname); bool entireReverse = readEntireReverse(fname + ".rev"); TPackedEbwt ebwt( fname, color, // index is colorspace -1, // don't require entire reverse true, // index is for the forward direction -1, // offrate (-1 = index default) -1, false, // use memory-mapped IO false, // use shared memory false, // sweep memory-mapped memory true, // load names? //false, // load SA sample? NULL, // no reference map verbose, // be talkative? verbose, // be talkative at startup? false, // pass up memory exceptions? false); // sanity check? vector p_refnames; readEbwtRefnames(fname, p_refnames); if(extra) { cout << "Flags" << '\t' << (-flags) << endl; cout << "Reverse flags" << '\t' << (-flagsr) << endl; } cout << "Colorspace" << '\t' << (color ? "1" : "0") << endl; if(extra) { cout << "Concat then reverse" << '\t' << (entireReverse ? "1" : "0") << endl; cout << "Reverse then concat" << '\t' << (entireReverse ? "0" : "1") << endl; cout << "nPat" << '\t' << ebwt.nPat() << endl; cout << "refnames.size()" << '\t' << p_refnames.size() << endl; cout << "refs.numRefs()" << '\t' << refs.numRefs() << endl; cout << "refs.numNonGapRefs()" << '\t' << refs.numNonGapRefs() << endl; } cout << "SA-Sample" << "\t1 in " << (1 << ebwt.eh().offRate()) << endl; cout << "FTab-Chars" << '\t' << ebwt.eh().ftabChars() << endl; for(size_t i = 0; i < ebwt.nPat(); i++) { cout << "Sequence-" << (i+1) << '\t' << p_refnames[refs.expandIdx(i)] << '\t' << (ebwt.plen()[i] + (color ? 1 : 0)) << endl; } if(extra) { cout << "RefRecords:\n"; for(size_t i = 0; i < refs.refRecords().size(); i++) { RefRecord r = refs.refRecords()[i]; cout << r.first << "\t(" << r.off << ", " << r.len << ")" << endl; } } } static void driver( const string& ebwtFileBase, const string& query) { // Adjust string adjustedEbwtFileBase = adjustEbwtBase(argv0, ebwtFileBase, verbose); if (names_only) { print_index_sequence_names(adjustedEbwtFileBase, cout); return; } bool color = readEbwtColor(adjustedEbwtFileBase); BitPairReference refs( adjustedEbwtFileBase, color, false, NULL, NULL, false, false, // don't load sequence (yet) false, false, false, // mmSweep verbose, verbose); if(summarize_only) { print_index_summary(adjustedEbwtFileBase, cout, refs); } else { // Initialize Ebwt object TPackedEbwt ebwt( adjustedEbwtFileBase, color, // index is colorspace -1, // don't care about entire-reverse true, // index is for the forward direction -1, // offrate (-1 = index default) -1, false, // use memory-mapped IO false, // use shared memory false, // sweep memory-mapped memory true, // load names? //true, // load SA sample? NULL, // no reference map verbose, // be talkative? verbose, // be talkative at startup? false, // pass up memory exceptions? false); // sanity check? // Load whole index into memory if(refFromEbwt) { ebwt.loadIntoMemory(-1, -1, true, false); print_index_sequences(cout, ebwt, refs); } else { vector refnames; readEbwtRefnames(adjustedEbwtFileBase, refnames); print_ref_sequences( cout, readEbwtColor(ebwtFileBase), refnames, ebwt.plen(), adjustedEbwtFileBase); } // Evict any loaded indexes from memory if(ebwt.isInMemory()) { ebwt.evictFromMemory(); } } } /** * main function. Parses command-line arguments. */ int main(int argc, char **argv) { try { string ebwtFile; // read serialized Ebwt from this file string query; // read query string(s) from this file vector queries; string outfile; // write query results to this file argv0 = argv[0]; parseOptions(argc, argv); if(showVersion) { cout << argv0 << " version " << BOWTIE_VERSION << endl; if(sizeof(void*) == 4) { cout << "32-bit" << endl; } else if(sizeof(void*) == 8) { cout << "64-bit" << endl; } else { cout << "Neither 32- nor 64-bit: sizeof(void*) = " << sizeof(void*) << endl; } cout << "Built on " << BUILD_HOST << endl; cout << BUILD_TIME << endl; cout << "Compiler: " << COMPILER_VERSION << endl; cout << "Options: " << COMPILER_OPTIONS << endl; cout << "Sizeof {int, long, long long, void*, size_t, off_t}: {" << sizeof(int) << ", " << sizeof(long) << ", " << sizeof(long long) << ", " << sizeof(void *) << ", " << sizeof(size_t) << ", " << sizeof(off_t) << "}" << endl; return 0; } // Get input filename if(optind >= argc) { cerr << "No index name given!" << endl; printUsage(cerr); return 1; } ebwtFile = argv[optind++]; // Optionally summarize if(verbose) { cout << "Input ebwt file: \"" << ebwtFile << "\"" << endl; cout << "Output file: \"" << outfile << "\"" << endl; cout << "Local endianness: " << (currentlyBigEndian()? "big":"little") << endl; #ifdef NDEBUG cout << "Assertions: disabled" << endl; #else cout << "Assertions: enabled" << endl; #endif } driver(ebwtFile, query); return 0; } catch(std::exception& e) { cerr << "Command: "; for(int i = 0; i < argc; i++) cerr << argv[i] << " "; cerr << endl; return 1; } catch(int e) { if(e != 0) { cerr << "Command: "; for(int i = 0; i < argc; i++) cerr << argv[i] << " "; cerr << endl; } return e; } } ugene-1.9.8/src/plugins_3rdparty/bowtie/src/bowtie/color_dec.cpp0000644000175000017500000002177211651544326023440 0ustar ilyailya/* * color_dec.cpp * * Created on: October 15, 2009 * Author: Ben Langmead */ #include #include #include #include "alphabet.h" #include "color_dec.h" #include "color.h" #include "qual.h" using namespace std; // 4-bit pop count static int alts[] = { -1, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4 }; static int firsts[] = { -1, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0 }; /** * Given a nucleotide mask, pick one matching nucleotide at random. */ static int randFromMask(int mask) { assert_gt(mask, 0); if(alts[mask] == 1) return firsts[mask]; assert_gt(mask, 0); assert_lt(mask, 16); int r = rand() % alts[mask]; assert_geq(r, 0); assert_lt(r, alts[mask]); for(int i = 0; i < 4; i++) { if((mask & (1 << i)) != 0) { if(r == 0) return i; r--; } } cerr << "Shouldn't get here" << endl; throw 1; return -1; } /** * Does a 2-bit-encoded base match any bit in a mask? */ static inline bool matches(int i, int j) { return ((1 << i) & j) != 0; } /** * Given the dynamic programming table, trace backwards from the last * column and populate the 's' and 'cmm' strings accordingly. Whenever * there are multiple equally good ways of backtracking, choose one at * random. */ static void backtrack(int table[4][6][1025], // filled-in table const char *read, size_t readi, size_t readf, const char *ref, size_t refi, size_t reff, char *s, // final nucleotide string char *cmm, // color mismatches char *nmm, // nucleotide mismatches int& cmms, // # color mismatches int& nmms) // # nucleotide mismatches { const size_t len = reff-refi; cmms = nmms = 0; int min = INT_MAX; int bests = 0; // Determine best base in final column of table for(int i = 0; i < 4; i++) { // Install minimum and backtrack info int m = table[i][4][len-1]; if(m < min) { min = m; bests = (1 << i); } else if(m == min) { bests |= (1 << i); } } // i <- position of rightmost nucleotide int i = (int)len-1; // to <- rightmost nucleotide int to = randFromMask(bests); while(true) { bests = table[to][5][i]; // get next best mask s[i--] = to; // install best nucleotide if(i < 0) break; // done assert_gt(bests, 0); assert_lt(bests, 16); to = randFromMask(bests); // select } // Determine what reference nucleotides were matched against for(size_t i = 0; i < len; i++) { if(matches(s[i], ref[refi+i])) { assert_eq(1, alts[(int)ref[refi+i]]); // Just plain matched nmm[i] = 'M'; } else { // If ref is ambiguous here, does it matter which one we // choose? I don't think so. assert_eq(1, alts[(int)ref[refi+i]]); // SNP here nmm[i] = 'S'; nmms++; } } for(size_t i = 0; i < len-1; i++) { int c1 = (int)read[readi+i]; // actual int c2 = dinuc2color[(int)s[i]][(int)s[i+1]]; // decoded assert_leq(c1, 4); assert_geq(c1, 0); if(c1 != c2 || c1 == 4) { // Actual != decoded assert_lt(c2, 4); assert_geq(c2, 0); cmm[i] = "0123."[c2]; cmms++; } else { cmm[i] = 'M'; } } // done } /** * Decode the colorspace read 'read' as aligned against the reference * string 'ref', assuming that it's a hit. */ void decodeHit( const char *read, // ASCII colors, '0', '1', '2', '3', '.' const char *qual, // ASCII quals, Phred+33 encoded size_t readi, // offset of first character within 'read' to consider size_t readf, // offset of last char (exclusive) in 'read' to consider const char *ref, // reference sequence, as masks size_t refi, // offset of first character within 'ref' to consider size_t reff, // offset of last char (exclusive) in 'ref' to consider int snpPhred, // penalty incurred by a SNP char *ns, // decoded nucleotides are appended here char *cmm, // where the color mismatches are in the string char *nmm, // where nucleotide mismatches are in the string int& cmms, // number of color mismatches int& nmms) // number of nucleotide mismatches { assert_lt(refi, reff); assert_lt(readi, readf); assert_eq(reff-refi-1, readf-readi); // // Dynamic programming table; good for colorspace reads up to 1024 // colors in length. // int table[4][6][1025]; // 0 -> A, 1 -> C, 2 -> G, 3 -> T, 4 -> min(A, C, G, T), // 5 -> backtrack mask, 6 -> min mismatches // The first column of the table just considers the first // nucleotide and whether it matches the ref nucleotide. for(int to = 0; to < 4; to++) { if(matches(to, ref[refi])) { // The assigned subject nucleotide matches the reference; // no penalty table[to][0][0] = 0; table[to][1][0] = 0; table[to][2][0] = 0; table[to][3][0] = 0; table[to][4][0] = 0; table[to][5][0] = 15; } else { // The assigned subject nucleotide does not match the // reference nucleotide, so we add a SNP penalty table[to][0][0] = snpPhred; table[to][1][0] = snpPhred; table[to][2][0] = snpPhred; table[to][3][0] = snpPhred; table[to][4][0] = snpPhred; table[to][5][0] = 15; } } // Successive columns examine successive alignment positions int omin = INT_MAX, t = 0; int lastOmin = INT_MAX; for(size_t c = readi; c < readf; c++) { const int readc = (int)read[c]; assert_leq(readc, 4); assert_geq(readc, 0); lastOmin = omin; omin = INT_MAX; // t <- index of column in dynamic programming table t = c - readi + 1; const int refc = ref[refi + t]; int from[] = { table[0][4][t-1], table[1][4][t-1], table[2][4][t-1], table[3][4][t-1] }; // For each downstream nucleotide for(int to = 0; to < 4; to++) { // For each upstream nucleotide int min = INT_MAX; const int goodfrom = nuccol2nuc[to][readc]; int q = qual[c]; // Reward the preceding position if(goodfrom < 4) from[goodfrom] -= q; min = from[0]; table[to][5][t] = 1; if(from[1] < min) { min = from[1]; table[to][5][t] = 2; } else if(from[1] == min) { table[to][5][t] |= 2; } if(from[2] < min) { min = from[2]; table[to][5][t] = 4; } else if(from[2] == min) { table[to][5][t] |= 4; } if(from[3] < min) { min = from[3]; table[to][5][t] = 8; } else if(from[3] == min) { table[to][5][t] |= 8; } min += q; if(!matches(to, refc)) { min += snpPhred; } table[to][4][t] = min; if(min < omin) omin = min; if(goodfrom < 4) from[goodfrom] += q; } } t++; assert_eq(t, (int)(reff - refi)); // Install the best backward path into ns, cmm, nmm backtrack(table, read, readi, readi + t - 1, ref, refi, refi + t, ns, cmm, nmm, cmms, nmms); } #ifdef MAIN_COLOR_DEC #include #include static const char *short_opts = "s:m:r:e:"; static struct option long_opts[] = { {(char*)"snppen", required_argument, 0, 's'}, {(char*)"misspen", required_argument, 0, 'm'}, {(char*)"seed", required_argument, 0, 'r'}, {(char*)"maxpen", required_argument, 0, 'e'} }; template T parse(const char *s) { T tmp; stringstream ss(s); ss >> tmp; return tmp; } int main(int argc, char **argv) { int option_index = 0; int next_option; int snppen = 30; int misspen = 20; int maxPenalty = 70; unsigned seed = 0; do { next_option = getopt_long(argc, argv, short_opts, long_opts, &option_index); switch (next_option) { case 's': snppen = parse(optarg); break; case 'm': misspen = parse(optarg); break; case 'r': seed = parse(optarg); break; case 'e': maxPenalty = parse(optarg); break; case -1: break; default: { cerr << "Unknown option: " << (char)next_option << endl; exit(1); } } } while(next_option != -1); srand(seed); if(argc - optind < 2) { cerr << "Not enough options" << endl; exit(1); } string read, ref; read = argv[optind]; for(size_t i = 0; i < read.length(); i++) { read[i] = asc2col[(int)read[i]]; assert_leq(read[i], 4); assert_geq(read[i], 0); } ref = argv[optind+1]; for(size_t i = 0; i < ref.length(); i++) { int num = 0; int alts[] = {4, 4, 4, 4}; decodeNuc(toupper(ref[i]), num, alts); assert_leq(num, 4); assert_gt(num, 0); ref[i] = 0; for(int j = 0; j < num; j++) { ref[i] |= (1 << alts[j]); } } string ns; string quals; quals.resize(read.length(), misspen); string cmm, nmm; int score = decode(read, quals, 0, read.length(), ref, 0, ref.length(), maxPenalty, snppen, ns, cmm, nmm); cout << " Score: " << score << " (max: " << maxPenalty << ")" << endl; cout << " MMs: "; for(size_t i = 0; i < cmm.length(); i++) { cout << cmm[i] << " "; } cout << endl; cout << "Colors: "; for(size_t i = 0; i < read.length(); i++) { printColor((int)read[i]); cout << " "; } cout << endl; cout << " Bases: "; for(size_t i = 0; i < ns.length(); i++) { cout << "ACGTN"[(int)ns[i]] << " "; } cout << endl; cout << " Ref: "; for(size_t i = 0; i < ref.length(); i++) { cout << mask2iupac[(int)ref[i]] << " "; } cout << endl; cout << " MMs: "; for(size_t i = 0; i < ref.length(); i++) { cout << nmm[i] << " "; } cout << endl; } #endif ugene-1.9.8/src/plugins_3rdparty/bowtie/src/bowtie/aligner_seed_mm.h0000644000175000017500000015065611651544326024272 0ustar ilyailya/* * aligner_seed_mm.h */ #ifndef ALIGNER_SEED_MM_H_ #define ALIGNER_SEED_MM_H_ #include #include #include "aligner.h" #include "hit.h" #include "row_chaser.h" #include "range_chaser.h" #include "aligner_metrics.h" /** * Concrete factory class for constructing unpaired exact aligners. */ class UnpairedSeedAlignerFactory : public AlignerFactory { typedef RangeSourceDriver TRangeSrcDr; typedef std::vector TRangeSrcDrPtrVec; typedef CostAwareRangeSourceDriver TCostAwareRangeSrcDr; public: UnpairedSeedAlignerFactory( Ebwt >& ebwtFw, Ebwt >* ebwtBw, bool doFw, bool doRc, uint32_t seedMms, uint32_t seedLen, int qualCutoff, int maxBts, HitSink& sink, const HitSinkPerThreadFactory& sinkPtFactory, RangeCache* cacheFw, RangeCache* cacheBw, uint32_t cacheLimit, ChunkPool *pool, BitPairReference* refs, vector >& os, bool maqPenalty, bool qualOrder, bool strandFix, bool rangeMode, bool verbose, bool quiet, uint32_t seed, AlignerMetrics *metrics) : ebwtFw_(ebwtFw), ebwtBw_(ebwtBw), doFw_(doFw), doRc_(doRc), seedMms_(seedMms), seedLen_(seedLen), qualCutoff_(qualCutoff), maxBts_(maxBts), sink_(sink), sinkPtFactory_(sinkPtFactory), cacheFw_(cacheFw), cacheBw_(cacheBw), cacheLimit_(cacheLimit), pool_(pool), refs_(refs), os_(os), strandFix_(strandFix), maqPenalty_(maqPenalty), qualOrder_(qualOrder), rangeMode_(rangeMode), verbose_(verbose), quiet_(quiet), metrics_(metrics) { assert(ebwtFw.isInMemory()); } /** * Create a new UnpairedExactAlignerV1s. */ virtual Aligner* create() const { HitSinkPerThread* sinkPt = sinkPtFactory_.create(); EbwtSearchParams >* params = new EbwtSearchParams >(*sinkPt, os_); int *btCnt = new int[1]; *btCnt = maxBts_; TRangeSrcDrPtrVec *drVec = new TRangeSrcDrPtrVec(); if(seedMms_ == 0) { const int halfAndHalf = 0; bool mate1 = true; EbwtRangeSource *rFw_Bw = new EbwtRangeSource( ebwtBw_, true, qualCutoff_, true, verbose_, quiet_, halfAndHalf, false, maqPenalty_, qualOrder_, metrics_); EbwtRangeSource *rRc_Fw = new EbwtRangeSource( &ebwtFw_, false, qualCutoff_, true, verbose_, quiet_, halfAndHalf, false, maqPenalty_, qualOrder_, metrics_); EbwtRangeSourceDriver * driverFw = new EbwtRangeSourceDriver( *params, rFw_Bw, true, false, maqPenalty_, qualOrder_, sink_, sinkPt, seedLen_, // seedLen true, // nudgeLeft (not applicable) PIN_TO_SEED_EDGE, // whole alignment is unrevisitable PIN_TO_SEED_EDGE, // " PIN_TO_SEED_EDGE, // " PIN_TO_SEED_EDGE, // " os_, verbose_, quiet_, mate1, pool_, NULL); // no backtrack limit for -n 1/2 EbwtRangeSourceDriver * driverRc = new EbwtRangeSourceDriver( *params, rRc_Fw, false, false, maqPenalty_, qualOrder_, sink_, sinkPt, seedLen_, // seedLen true, // nudgeLeft (not applicable) PIN_TO_SEED_EDGE, // whole alignment is unrevisitable PIN_TO_SEED_EDGE, // " PIN_TO_SEED_EDGE, // " PIN_TO_SEED_EDGE, // " os_, verbose_, quiet_, mate1, pool_, NULL); // no backtrack limit for -n 1/2 if(doFw_) drVec->push_back(driverFw); if(doRc_) drVec->push_back(driverRc); } else if(seedMms_ == 1) { const int halfAndHalf = 0; bool fw = true; bool mate1 = true; EbwtRangeSource *rFw_Bw = new EbwtRangeSource( ebwtBw_, fw, qualCutoff_, true, verbose_, quiet_, halfAndHalf, false, maqPenalty_, qualOrder_, metrics_); EbwtRangeSourceFactory *rFw_BwSeed = new EbwtRangeSourceFactory( ebwtBw_, fw, qualCutoff_, true, verbose_, quiet_, halfAndHalf, false, maqPenalty_, qualOrder_, metrics_); EbwtRangeSource *rFw_FwSeedGen = new EbwtRangeSource( &ebwtFw_, fw, qualCutoff_, false, verbose_, quiet_, halfAndHalf, true, maqPenalty_, qualOrder_, metrics_); EbwtRangeSourceDriver * drFw_Bw = new EbwtRangeSourceDriver( *params, rFw_Bw, fw, false, maqPenalty_, qualOrder_, sink_, sinkPt, seedLen_, true, // nudgeLeft PIN_TO_HI_HALF_EDGE, PIN_TO_SEED_EDGE, PIN_TO_SEED_EDGE, PIN_TO_SEED_EDGE, os_, verbose_, quiet_, mate1, pool_, NULL); // no backtrack limit for -n 1/2 EbwtRangeSourceDriverFactory * drFw_BwSeed = new EbwtRangeSourceDriverFactory( *params, rFw_BwSeed, fw, false, maqPenalty_, qualOrder_, sink_, sinkPt, seedLen_, true, // nudgeLeft PIN_TO_SEED_EDGE, PIN_TO_SEED_EDGE, PIN_TO_SEED_EDGE, PIN_TO_SEED_EDGE, os_, verbose_, quiet_, mate1, pool_, NULL); // no backtrack limit for -n 1/2 EbwtRangeSourceDriver * drFw_FwSeedGen = new EbwtRangeSourceDriver( *params, rFw_FwSeedGen, fw, true, maqPenalty_, qualOrder_, sink_, sinkPt, seedLen_, false, // nudgeLeft PIN_TO_HI_HALF_EDGE, PIN_TO_SEED_EDGE, PIN_TO_SEED_EDGE, PIN_TO_SEED_EDGE, os_, verbose_, quiet_, mate1, pool_, NULL); // no backtrack limit for -n 1/2 EbwtSeededRangeSourceDriver * drFw_Seed = new EbwtSeededRangeSourceDriver( drFw_BwSeed, drFw_FwSeedGen, fw, seedLen_, verbose_, quiet_, mate1); fw = false; EbwtRangeSource *rRc_Fw = new EbwtRangeSource( &ebwtFw_, fw, qualCutoff_, true, verbose_, quiet_, halfAndHalf, false, maqPenalty_, qualOrder_, metrics_); EbwtRangeSourceFactory *rRc_FwSeed = new EbwtRangeSourceFactory( &ebwtFw_, fw, qualCutoff_, true, verbose_, quiet_, halfAndHalf, false, maqPenalty_, qualOrder_, metrics_); EbwtRangeSource *rRc_BwSeedGen = new EbwtRangeSource( ebwtBw_, fw, qualCutoff_, false, verbose_, quiet_, halfAndHalf, true, maqPenalty_, qualOrder_, metrics_); EbwtRangeSourceDriver * drRc_Fw = new EbwtRangeSourceDriver( *params, rRc_Fw, fw, false, maqPenalty_, qualOrder_, sink_, sinkPt, seedLen_, // seedLen true, // nudgeLeft PIN_TO_HI_HALF_EDGE, PIN_TO_SEED_EDGE, PIN_TO_SEED_EDGE, PIN_TO_SEED_EDGE, os_, verbose_, quiet_, mate1, pool_, NULL); // no backtrack limit for -n 1/2 EbwtRangeSourceDriverFactory * drRc_FwSeed = new EbwtRangeSourceDriverFactory( *params, rRc_FwSeed, fw, false, maqPenalty_, qualOrder_, sink_, sinkPt, seedLen_, // seedLen true, // nudgeLeft PIN_TO_SEED_EDGE, PIN_TO_SEED_EDGE, PIN_TO_SEED_EDGE, PIN_TO_SEED_EDGE, os_, verbose_, quiet_, mate1, pool_, NULL); // no backtrack limit for -n 1/2 EbwtRangeSourceDriver * drRc_BwSeedGen = new EbwtRangeSourceDriver( *params, rRc_BwSeedGen, fw, true, maqPenalty_, qualOrder_, sink_, sinkPt, seedLen_, // seedLen false, // nudgeLeft PIN_TO_HI_HALF_EDGE, PIN_TO_SEED_EDGE, PIN_TO_SEED_EDGE, PIN_TO_SEED_EDGE, os_, verbose_, quiet_, mate1, pool_, NULL); // no backtrack limit for -n 1/2 EbwtSeededRangeSourceDriver * drRc_Seed = new EbwtSeededRangeSourceDriver( drRc_FwSeed, drRc_BwSeedGen, fw, seedLen_, verbose_, quiet_, true); if(doFw_) { drVec->push_back(drFw_Bw); drVec->push_back(drFw_Seed); } if(doRc_) { drVec->push_back(drRc_Fw); drVec->push_back(drRc_Seed); } } else if(seedMms_ == 2) { bool fw = true; bool mate1 = true; EbwtRangeSource *rFw_Bw = new EbwtRangeSource( ebwtBw_, fw, qualCutoff_, true, verbose_, quiet_, 0, false, maqPenalty_, qualOrder_, metrics_); EbwtRangeSourceFactory *rFw_BwSeed = new EbwtRangeSourceFactory( ebwtBw_, fw, qualCutoff_, true, verbose_, quiet_, 0, false, maqPenalty_, qualOrder_, metrics_); EbwtRangeSource *rFw_FwSeedGen = new EbwtRangeSource( &ebwtFw_, fw, qualCutoff_, false, verbose_, quiet_, 0, true, maqPenalty_, qualOrder_, metrics_); EbwtRangeSource *rFw_BwHalf = new EbwtRangeSource( ebwtBw_, fw, qualCutoff_, false, verbose_, quiet_, 2, false, maqPenalty_, qualOrder_, metrics_); EbwtRangeSourceDriver * drFw_Bw = new EbwtRangeSourceDriver( *params, rFw_Bw, fw, false, maqPenalty_, qualOrder_, sink_, sinkPt, seedLen_, // seedLen true, // nudgeLeft PIN_TO_HI_HALF_EDGE, PIN_TO_HI_HALF_EDGE, PIN_TO_SEED_EDGE, PIN_TO_SEED_EDGE, os_, verbose_, quiet_, mate1, pool_, btCnt); EbwtRangeSourceDriverFactory * drFw_BwSeed = new EbwtRangeSourceDriverFactory( *params, rFw_BwSeed, fw, false, maqPenalty_, qualOrder_, sink_, sinkPt, seedLen_, // seedLen true, // nudgeLeft PIN_TO_SEED_EDGE, PIN_TO_SEED_EDGE, PIN_TO_SEED_EDGE, PIN_TO_SEED_EDGE, os_, verbose_, quiet_, mate1, pool_, btCnt); EbwtRangeSourceDriver * drFw_FwSeedGen = new EbwtRangeSourceDriver( *params, rFw_FwSeedGen, fw, true, maqPenalty_, qualOrder_, sink_, sinkPt, seedLen_, // seedLen false, // nudgeLeft PIN_TO_HI_HALF_EDGE, PIN_TO_HI_HALF_EDGE, PIN_TO_SEED_EDGE, PIN_TO_SEED_EDGE, os_, verbose_, quiet_, mate1, pool_, btCnt); EbwtSeededRangeSourceDriver * drFw_Seed = new EbwtSeededRangeSourceDriver( drFw_BwSeed, drFw_FwSeedGen, fw, seedLen_, verbose_, quiet_, mate1); EbwtRangeSourceDriver * drFw_BwHalf = new EbwtRangeSourceDriver( *params, rFw_BwHalf, fw, false, maqPenalty_, qualOrder_, sink_, sinkPt, seedLen_, // seedLen true, // nudgeLeft PIN_TO_BEGINNING, // nothing's unrevisitable PIN_TO_HI_HALF_EDGE, PIN_TO_SEED_EDGE, PIN_TO_SEED_EDGE, os_, verbose_, quiet_, mate1, pool_, btCnt); fw = false; EbwtRangeSource *rRc_Fw = new EbwtRangeSource( &ebwtFw_, fw, qualCutoff_, true, verbose_, quiet_, 0, false, maqPenalty_, qualOrder_, metrics_); EbwtRangeSourceFactory *rRc_FwSeed = new EbwtRangeSourceFactory( &ebwtFw_, fw, qualCutoff_, true, verbose_, quiet_, 0, false, maqPenalty_, qualOrder_, metrics_); EbwtRangeSource *rRc_BwSeedGen = new EbwtRangeSource( ebwtBw_, fw, qualCutoff_, false, verbose_, quiet_, 0, true, maqPenalty_, qualOrder_, metrics_); EbwtRangeSource *rRc_FwHalf = new EbwtRangeSource( &ebwtFw_, fw, qualCutoff_, false, verbose_, quiet_, 2, false, maqPenalty_, qualOrder_, metrics_); EbwtRangeSourceDriver * drRc_Fw = new EbwtRangeSourceDriver( *params, rRc_Fw, fw, false, maqPenalty_, qualOrder_, sink_, sinkPt, seedLen_, // seedLen true, // nudgeLeft PIN_TO_HI_HALF_EDGE, // no mismatches in hi half PIN_TO_HI_HALF_EDGE, PIN_TO_SEED_EDGE, // up to 2 in lo half PIN_TO_SEED_EDGE, os_, verbose_, quiet_, mate1, pool_, btCnt); EbwtRangeSourceDriverFactory * drRc_FwSeed = new EbwtRangeSourceDriverFactory( *params, rRc_FwSeed, fw, false, maqPenalty_, qualOrder_, sink_, sinkPt, seedLen_, // seedLen true, // nudgeLeft PIN_TO_SEED_EDGE, PIN_TO_SEED_EDGE, PIN_TO_SEED_EDGE, PIN_TO_SEED_EDGE, os_, verbose_, quiet_, mate1, pool_, btCnt); EbwtRangeSourceDriver * drRc_BwSeedGen = new EbwtRangeSourceDriver( *params, rRc_BwSeedGen, fw, true, maqPenalty_, qualOrder_, sink_, sinkPt, seedLen_, // seedLen false, // nudgeLeft PIN_TO_HI_HALF_EDGE, // no mismatches in lo half PIN_TO_HI_HALF_EDGE, PIN_TO_SEED_EDGE, // up to 2 in hi half PIN_TO_SEED_EDGE, os_, verbose_, quiet_, mate1, pool_, btCnt); EbwtSeededRangeSourceDriver * drRc_Seed = new EbwtSeededRangeSourceDriver( drRc_FwSeed, drRc_BwSeedGen, fw, seedLen_, verbose_, quiet_, true); EbwtRangeSourceDriver * drRc_FwHalf = new EbwtRangeSourceDriver( *params, rRc_FwHalf, fw, false, maqPenalty_, qualOrder_, sink_, sinkPt, seedLen_, // seedLen true, // nudgeLeft PIN_TO_BEGINNING, // nothing's unrevisitable PIN_TO_HI_HALF_EDGE, PIN_TO_SEED_EDGE, PIN_TO_SEED_EDGE, os_, verbose_, quiet_, mate1, pool_, btCnt); if(doFw_) { drVec->push_back(drFw_Bw); drVec->push_back(drFw_Seed); drVec->push_back(drFw_BwHalf); } if(doRc_) { drVec->push_back(drRc_Fw); drVec->push_back(drRc_Seed); drVec->push_back(drRc_FwHalf); } } else if(seedMms_ > 2) { bool fw = true; bool mate1 = true; EbwtRangeSource *rFw_Bw = new EbwtRangeSource( ebwtBw_, fw, qualCutoff_, true, verbose_, quiet_, 0, false, maqPenalty_, qualOrder_, metrics_); // Partial and full aligners for alignments with 0 // mismatches in the lo-half and up to 3 mismatches in the // hi-half EbwtRangeSourceFactory *rFw_BwSeed03 = new EbwtRangeSourceFactory( ebwtBw_, fw, qualCutoff_, true, verbose_, quiet_, 0, false, maqPenalty_, qualOrder_, metrics_); EbwtRangeSource *rFw_FwSeedGen03 = new EbwtRangeSource( &ebwtFw_, fw, qualCutoff_, false, verbose_, quiet_, 0, true, maqPenalty_, qualOrder_, metrics_); // Partial and full aligners for alignments with 1 // mismatch in the lo-half and up to 2 mismatches in the // hi-half EbwtRangeSourceFactory *rFw_BwSeed12 = new EbwtRangeSourceFactory( ebwtBw_, fw, qualCutoff_, true, verbose_, quiet_, 0, false, maqPenalty_, qualOrder_, metrics_); // Note: the following is half-and-half (unlike the 03 version) EbwtRangeSource *rFw_FwSeedGen12 = new EbwtRangeSource( &ebwtFw_, fw, qualCutoff_, false, verbose_, quiet_, 3, true, maqPenalty_, qualOrder_, metrics_); EbwtRangeSource *rFw_BwHalf12 = new EbwtRangeSource( ebwtBw_, fw, qualCutoff_, false, verbose_, quiet_, 2, false, maqPenalty_, qualOrder_, metrics_); EbwtRangeSourceDriver * drFw_Bw = new EbwtRangeSourceDriver( *params, rFw_Bw, fw, false, maqPenalty_, qualOrder_, sink_, sinkPt, seedLen_, true, // nudgeLeft PIN_TO_HI_HALF_EDGE, // 0 mismatches in hi-half PIN_TO_HI_HALF_EDGE, PIN_TO_HI_HALF_EDGE, PIN_TO_SEED_EDGE, // up to 3 mismatches in lo-half os_, verbose_, quiet_, mate1, pool_, btCnt); EbwtRangeSourceDriverFactory * drFw_BwSeed03 = new EbwtRangeSourceDriverFactory( *params, rFw_BwSeed03, fw, false, maqPenalty_, qualOrder_, sink_, sinkPt, seedLen_, true, // nudgeLeft PIN_TO_SEED_EDGE, PIN_TO_SEED_EDGE, PIN_TO_SEED_EDGE, PIN_TO_SEED_EDGE, os_, verbose_, quiet_, mate1, pool_, btCnt); EbwtRangeSourceDriver * drFw_FwSeedGen03 = new EbwtRangeSourceDriver( *params, rFw_FwSeedGen03, fw, true, maqPenalty_, qualOrder_, sink_, sinkPt, seedLen_, false, // nudgeLeft PIN_TO_HI_HALF_EDGE, PIN_TO_HI_HALF_EDGE, PIN_TO_HI_HALF_EDGE, PIN_TO_SEED_EDGE, os_, verbose_, quiet_, mate1, pool_, btCnt); EbwtSeededRangeSourceDriver * drFw_Seed03 = new EbwtSeededRangeSourceDriver( drFw_BwSeed03, drFw_FwSeedGen03, fw, seedLen_, verbose_, quiet_, mate1); EbwtRangeSourceDriverFactory * drFw_BwSeed12 = new EbwtRangeSourceDriverFactory( *params, rFw_BwSeed12, fw, false, maqPenalty_, qualOrder_, sink_, sinkPt, seedLen_, true, // nudgeLeft PIN_TO_SEED_EDGE, PIN_TO_SEED_EDGE, PIN_TO_SEED_EDGE, PIN_TO_SEED_EDGE, os_, verbose_, quiet_, mate1, pool_, btCnt); EbwtRangeSourceDriver * drFw_FwSeedGen12 = new EbwtRangeSourceDriver( *params, rFw_FwSeedGen12, fw, true, maqPenalty_, qualOrder_, sink_, sinkPt, seedLen_, false, // nudgeLeft PIN_TO_BEGINNING, PIN_TO_HI_HALF_EDGE, // 1-mismatch in lo-half PIN_TO_HI_HALF_EDGE, PIN_TO_SEED_EDGE, // 1 or 2 mismatches in hi-half os_, verbose_, quiet_, mate1, pool_, btCnt); EbwtSeededRangeSourceDriver * drFw_Seed12 = new EbwtSeededRangeSourceDriver( drFw_BwSeed12, drFw_FwSeedGen12, fw, seedLen_, verbose_, quiet_, mate1); EbwtRangeSourceDriver * drFw_BwHalf12 = new EbwtRangeSourceDriver( *params, rFw_BwHalf12, fw, false, maqPenalty_, qualOrder_, sink_, sinkPt, seedLen_, // seedLen true, // nudgeLeft PIN_TO_BEGINNING, // nothing's unrevisitable PIN_TO_HI_HALF_EDGE, PIN_TO_HI_HALF_EDGE, PIN_TO_SEED_EDGE, os_, verbose_, quiet_, mate1, pool_, btCnt); fw = false; EbwtRangeSource *rRc_Fw = new EbwtRangeSource( &ebwtFw_, fw, qualCutoff_, true, verbose_, quiet_, 0, false, maqPenalty_, qualOrder_, metrics_); // Partial and full aligners for alignments with 0 // mismatches in the lo-half and up to 3 mismatches in the // hi-half EbwtRangeSourceFactory *rRc_FwSeed03 = new EbwtRangeSourceFactory( &ebwtFw_, fw, qualCutoff_, true, verbose_, quiet_, 0, false, maqPenalty_, qualOrder_, metrics_); EbwtRangeSource *rRc_BwSeedGen03 = new EbwtRangeSource( ebwtBw_, fw, qualCutoff_, false, verbose_, quiet_, 0, true, maqPenalty_, qualOrder_, metrics_); // Partial and full aligners for alignments with 1 // mismatch in the lo-half and up to 2 mismatches in the // hi-half EbwtRangeSourceFactory *rRc_FwSeed12 = new EbwtRangeSourceFactory( &ebwtFw_, fw, qualCutoff_, true, verbose_, quiet_, 0, false, maqPenalty_, qualOrder_, metrics_); EbwtRangeSource *rRc_BwSeedGen12 = new EbwtRangeSource( ebwtBw_, fw, qualCutoff_, false, verbose_, quiet_, 3, true, maqPenalty_, qualOrder_, metrics_); EbwtRangeSource *rRc_FwHalf12 = new EbwtRangeSource( &ebwtFw_, fw, qualCutoff_, false, verbose_, quiet_, 2, false, maqPenalty_, qualOrder_, metrics_); EbwtRangeSourceDriver * drRc_Fw = new EbwtRangeSourceDriver( *params, rRc_Fw, fw, false, maqPenalty_, qualOrder_, sink_, sinkPt, seedLen_, // seedLen true, // nudgeLeft PIN_TO_HI_HALF_EDGE, PIN_TO_HI_HALF_EDGE, PIN_TO_HI_HALF_EDGE, PIN_TO_SEED_EDGE, os_, verbose_, quiet_, mate1, pool_, btCnt); EbwtRangeSourceDriverFactory * drRc_FwSeed03 = new EbwtRangeSourceDriverFactory( *params, rRc_FwSeed03, fw, false, maqPenalty_, qualOrder_, sink_, sinkPt, seedLen_, // seedLen true, // nudgeLeft PIN_TO_SEED_EDGE, PIN_TO_SEED_EDGE, PIN_TO_SEED_EDGE, PIN_TO_SEED_EDGE, os_, verbose_, quiet_, mate1, pool_, btCnt); EbwtRangeSourceDriver * drRc_BwSeedGen03 = new EbwtRangeSourceDriver( *params, rRc_BwSeedGen03, fw, true, maqPenalty_, qualOrder_, sink_, sinkPt, seedLen_, // seedLen false, // nudgeLeft PIN_TO_HI_HALF_EDGE, PIN_TO_HI_HALF_EDGE, PIN_TO_HI_HALF_EDGE, PIN_TO_SEED_EDGE, os_, verbose_, quiet_, mate1, pool_, btCnt); EbwtSeededRangeSourceDriver * drRc_Seed03 = new EbwtSeededRangeSourceDriver( drRc_FwSeed03, drRc_BwSeedGen03, fw, seedLen_, verbose_, quiet_, mate1); EbwtRangeSourceDriverFactory * drRc_FwSeed12 = new EbwtRangeSourceDriverFactory( *params, rRc_FwSeed12, fw, false, maqPenalty_, qualOrder_, sink_, sinkPt, seedLen_, // seedLen true, // nudgeLeft PIN_TO_SEED_EDGE, PIN_TO_SEED_EDGE, PIN_TO_SEED_EDGE, PIN_TO_SEED_EDGE, os_, verbose_, quiet_, mate1, pool_, btCnt); EbwtRangeSourceDriver * drRc_BwSeedGen12 = new EbwtRangeSourceDriver( *params, rRc_BwSeedGen12, fw, true, maqPenalty_, qualOrder_, sink_, sinkPt, seedLen_, // seedLen false, // nudgeLeft PIN_TO_BEGINNING, PIN_TO_HI_HALF_EDGE, PIN_TO_HI_HALF_EDGE, PIN_TO_SEED_EDGE, os_, verbose_, quiet_, mate1, pool_, btCnt); EbwtSeededRangeSourceDriver * drRc_Seed12 = new EbwtSeededRangeSourceDriver( drRc_FwSeed12, drRc_BwSeedGen12, fw, seedLen_, verbose_, quiet_, mate1); EbwtRangeSourceDriver * drRc_FwHalf12 = new EbwtRangeSourceDriver( *params, rRc_FwHalf12, fw, false, maqPenalty_, qualOrder_, sink_, sinkPt, seedLen_, // seedLen true, // nudgeLeft PIN_TO_BEGINNING, // nothing's unrevisitable PIN_TO_HI_HALF_EDGE, PIN_TO_HI_HALF_EDGE, PIN_TO_SEED_EDGE, os_, verbose_, quiet_, mate1, pool_, btCnt); if(doFw_) { drVec->push_back(drFw_Bw); drVec->push_back(drFw_Seed03); drVec->push_back(drFw_Seed12); drVec->push_back(drFw_BwHalf12); } if(doRc_) { drVec->push_back(drRc_Fw); drVec->push_back(drRc_Seed03); drVec->push_back(drRc_Seed12); drVec->push_back(drRc_FwHalf12); } } else { cerr << "Unsupported --stateful mode: " << seedMms_ << endl; } TCostAwareRangeSrcDr* dr = new TCostAwareRangeSrcDr(strandFix_, drVec, verbose_, quiet_, false); delete drVec; // Set up a RangeChaser RangeChaser > *rchase = new RangeChaser >(cacheLimit_, cacheFw_, cacheBw_, metrics_); return new UnpairedAlignerV2( params, dr, rchase, sink_, sinkPtFactory_, sinkPt, os_, refs_, rangeMode_, verbose_, quiet_, maxBts_, pool_, btCnt, metrics_); } private: Ebwt >& ebwtFw_; Ebwt >* ebwtBw_; bool doFw_; bool doRc_; const uint32_t seedMms_; const uint32_t seedLen_; const int qualCutoff_; const int maxBts_; HitSink& sink_; const HitSinkPerThreadFactory& sinkPtFactory_; RangeCache *cacheFw_; RangeCache *cacheBw_; const uint32_t cacheLimit_; ChunkPool *pool_; BitPairReference* refs_; vector >& os_; bool strandFix_; bool maqPenalty_; bool qualOrder_; bool rangeMode_; bool verbose_; bool quiet_; AlignerMetrics *metrics_; }; /** * Concrete factory class for constructing unpaired exact aligners. */ class PairedSeedAlignerFactory : public AlignerFactory { typedef RangeSourceDriver TRangeSrcDr; typedef std::vector TRangeSrcDrPtrVec; typedef CostAwareRangeSourceDriver TCostAwareRangeSrcDr; public: PairedSeedAlignerFactory( Ebwt >& ebwtFw, Ebwt >* ebwtBw, bool color, bool v1, bool doFw, bool doRc, uint32_t seedMms, uint32_t seedLen, int qualCutoff, int maxBts, HitSink& sink, const HitSinkPerThreadFactory& sinkPtFactory, bool mate1fw, bool mate2fw, uint32_t peInner, uint32_t peOuter, bool dontReconcile, uint32_t symCeil, uint32_t mixedThresh, uint32_t mixedAttemptLim, RangeCache* cacheFw, RangeCache* cacheBw, uint32_t cacheLimit, ChunkPool *pool, BitPairReference* refs, vector >& os, bool reportSe, bool maqPenalty, bool qualOrder, bool strandFix, bool rangeMode, bool verbose, bool quiet, uint32_t seed) : ebwtFw_(ebwtFw), ebwtBw_(ebwtBw), color_(color), v1_(v1), doFw_(doFw), doRc_(doRc), seedMms_(seedMms), seedLen_(seedLen), qualCutoff_(qualCutoff), maxBts_(maxBts), sink_(sink), sinkPtFactory_(sinkPtFactory), mate1fw_(mate1fw), mate2fw_(mate2fw), peInner_(peInner), peOuter_(peOuter), dontReconcile_(dontReconcile), symCeil_(symCeil), mixedThresh_(mixedThresh), mixedAttemptLim_(mixedAttemptLim), cacheFw_(cacheFw), cacheBw_(cacheBw), cacheLimit_(cacheLimit), pool_(pool), refs_(refs), os_(os), reportSe_(reportSe), maqPenalty_(maqPenalty), qualOrder_(qualOrder), strandFix_(strandFix), rangeMode_(rangeMode), verbose_(verbose), quiet_(quiet) { assert(ebwtFw.isInMemory()); assert(ebwtBw->isInMemory()); } /** * Create a new UnpairedExactAlignerV1s. */ virtual Aligner* create() const { HitSinkPerThread* sinkPt = sinkPtFactory_.createMult(2); HitSinkPerThread* sinkPtSe1 = NULL, * sinkPtSe2 = NULL; EbwtSearchParams >* params = new EbwtSearchParams >(*sinkPt, os_); EbwtSearchParams >* paramsSe1 = NULL, * paramsSe2 = NULL; if(reportSe_) { sinkPtSe1 = sinkPtFactory_.create(); sinkPtSe2 = sinkPtFactory_.create(); paramsSe1 = new EbwtSearchParams >(*sinkPtSe1, os_); paramsSe2 = new EbwtSearchParams >(*sinkPtSe2, os_); } RefAligner >* refAligner = NULL; int *btCnt = new int[1]; *btCnt = maxBts_; if(seedMms_ == 0) { refAligner = new Seed0RefAligner >(color_, verbose_, quiet_, seedLen_, qualCutoff_, maqPenalty_); } else if(seedMms_ == 1) { refAligner = new Seed1RefAligner >(color_, verbose_, quiet_, seedLen_, qualCutoff_, maqPenalty_); } else if(seedMms_ == 2) { refAligner = new Seed2RefAligner >(color_, verbose_, quiet_, seedLen_, qualCutoff_, maqPenalty_); } else { refAligner = new Seed3RefAligner >(color_, verbose_, quiet_, seedLen_, qualCutoff_, maqPenalty_); } bool do1Fw = true; bool do1Rc = true; bool do2Fw = true; bool do2Rc = true; if(!doFw_) { if(mate1fw_) do1Fw = false; else do1Rc = false; if(mate2fw_) do2Fw = false; else do2Rc = false; } if(!doRc_) { if(mate1fw_) do1Rc = false; else do1Fw = false; if(mate2fw_) do2Rc = false; else do2Fw = false; } TRangeSrcDrPtrVec *dr1FwVec = new TRangeSrcDrPtrVec(); TRangeSrcDrPtrVec *dr1RcVec; TRangeSrcDrPtrVec *dr2FwVec; TRangeSrcDrPtrVec *dr2RcVec; if(v1_) { dr1RcVec = new TRangeSrcDrPtrVec(); dr2FwVec = new TRangeSrcDrPtrVec(); dr2RcVec = new TRangeSrcDrPtrVec(); } else { dr1RcVec = dr1FwVec; dr2FwVec = dr1FwVec; dr2RcVec = dr1FwVec; } if(seedMms_ == 0) { const int halfAndHalf = 0; if(do1Fw) { bool mate1 = true; bool fw = true; EbwtRangeSource *r1Fw_Bw = new EbwtRangeSource( ebwtBw_, fw, qualCutoff_, true, verbose_, quiet_, halfAndHalf, false, maqPenalty_, qualOrder_); EbwtRangeSourceDriver *dr1Fw_Bw = new EbwtRangeSourceDriver( *params, r1Fw_Bw, fw, false, maqPenalty_, qualOrder_, sink_, sinkPt, seedLen_, // seedLen true, // nudgeLeft (not applicable) PIN_TO_SEED_EDGE, // whole alignment is unrevisitable PIN_TO_SEED_EDGE, // " PIN_TO_SEED_EDGE, // " PIN_TO_SEED_EDGE, // " os_, verbose_, quiet_, mate1, pool_, NULL); // no backtrack limit for -n 1/2 dr1FwVec->push_back(dr1Fw_Bw); } if(do2Fw) { bool mate1 = false; bool fw = true; EbwtRangeSource *r2Fw_Bw = new EbwtRangeSource( ebwtBw_, fw, qualCutoff_, true, verbose_, quiet_, halfAndHalf, false, maqPenalty_, qualOrder_); EbwtRangeSourceDriver *dr2Fw_Bw = new EbwtRangeSourceDriver( *params, r2Fw_Bw, fw, false, maqPenalty_, qualOrder_, sink_, sinkPt, seedLen_, // seedLen true, // nudgeLeft (not applicable) PIN_TO_SEED_EDGE, // whole alignment is unrevisitable PIN_TO_SEED_EDGE, // " PIN_TO_SEED_EDGE, // " PIN_TO_SEED_EDGE, // " os_, verbose_, quiet_, mate1, pool_, NULL); // no backtrack limit for -n 1/2 dr2FwVec->push_back(dr2Fw_Bw); } if(do1Rc) { bool mate1 = true; bool fw = false; EbwtRangeSource *r1Rc_Fw = new EbwtRangeSource( &ebwtFw_, fw, qualCutoff_, true, verbose_, quiet_, halfAndHalf, false, maqPenalty_, qualOrder_); EbwtRangeSourceDriver *dr1Rc_Fw = new EbwtRangeSourceDriver( *params, r1Rc_Fw, fw, false, maqPenalty_, qualOrder_, sink_, sinkPt, seedLen_, // seedLen true, // nudgeLeft (not applicable) PIN_TO_SEED_EDGE, // whole alignment is unrevisitable PIN_TO_SEED_EDGE, // " PIN_TO_SEED_EDGE, // " PIN_TO_SEED_EDGE, // " os_, verbose_, quiet_, mate1, pool_, NULL); // no backtrack limit for -n 1/2 dr1RcVec->push_back(dr1Rc_Fw); } if(do2Rc) { bool mate1 = false; bool fw = false; EbwtRangeSource *r2Rc_Fw = new EbwtRangeSource( &ebwtFw_, fw, qualCutoff_, true, verbose_, quiet_, halfAndHalf, false, maqPenalty_, qualOrder_); EbwtRangeSourceDriver *dr2Rc_Fw = new EbwtRangeSourceDriver( *params, r2Rc_Fw, fw, false, maqPenalty_, qualOrder_, sink_, sinkPt, seedLen_, // seedLen true, // nudgeLeft (not applicable) PIN_TO_SEED_EDGE, // whole alignment is unrevisitable PIN_TO_SEED_EDGE, // " PIN_TO_SEED_EDGE, // " PIN_TO_SEED_EDGE, // " os_, verbose_, quiet_, mate1, pool_, NULL); // no backtrack limit for -n 1/2 dr2RcVec->push_back(dr2Rc_Fw); } } else if(seedMms_ == 1) { const int halfAndHalf = 0; if(do1Fw) { bool mate1 = true; bool fw = true; EbwtRangeSource *rFw_Bw = new EbwtRangeSource( ebwtBw_, fw, qualCutoff_, true, verbose_, quiet_, halfAndHalf, false, maqPenalty_, qualOrder_); EbwtRangeSourceFactory *rFw_BwSeed = new EbwtRangeSourceFactory( ebwtBw_, fw, qualCutoff_, true, verbose_, quiet_, halfAndHalf, false, maqPenalty_, qualOrder_); EbwtRangeSource *rFw_FwSeedGen = new EbwtRangeSource( &ebwtFw_, fw, qualCutoff_, false, verbose_, quiet_, halfAndHalf, true, maqPenalty_, qualOrder_); EbwtRangeSourceDriver * drFw_Bw = new EbwtRangeSourceDriver( *params, rFw_Bw, fw, false, maqPenalty_, qualOrder_, sink_, sinkPt, seedLen_, // seedLen true, // nudgeLeft PIN_TO_HI_HALF_EDGE, PIN_TO_SEED_EDGE, PIN_TO_SEED_EDGE, PIN_TO_SEED_EDGE, os_, verbose_, quiet_, mate1, pool_, NULL); // no backtrack limit for -n 1/2 EbwtRangeSourceDriverFactory * drFw_BwSeed = new EbwtRangeSourceDriverFactory( *params, rFw_BwSeed, fw, false, maqPenalty_, qualOrder_, sink_, sinkPt, seedLen_, // seedLen true, // nudgeLeft PIN_TO_SEED_EDGE, PIN_TO_SEED_EDGE, PIN_TO_SEED_EDGE, PIN_TO_SEED_EDGE, os_, verbose_, quiet_, mate1, pool_, NULL); // no backtrack limit for -n 1/2 EbwtRangeSourceDriver * drFw_FwSeedGen = new EbwtRangeSourceDriver( *params, rFw_FwSeedGen, fw, true, maqPenalty_, qualOrder_, sink_, sinkPt, seedLen_, // seedLen false, // nudgeLeft PIN_TO_HI_HALF_EDGE, PIN_TO_SEED_EDGE, PIN_TO_SEED_EDGE, PIN_TO_SEED_EDGE, os_, verbose_, quiet_, mate1, pool_, NULL); // no backtrack limit for -n 1/2 EbwtSeededRangeSourceDriver * drFw_Seed = new EbwtSeededRangeSourceDriver( drFw_BwSeed, drFw_FwSeedGen, fw, seedLen_, verbose_, quiet_, mate1); dr1FwVec->push_back(drFw_Bw); dr1FwVec->push_back(drFw_Seed); } if(do2Fw) { bool mate1 = false; bool fw = true; EbwtRangeSource *rFw_Bw = new EbwtRangeSource( ebwtBw_, fw, qualCutoff_, true, verbose_, quiet_, halfAndHalf, false, maqPenalty_, qualOrder_); EbwtRangeSourceFactory *rFw_BwSeed = new EbwtRangeSourceFactory( ebwtBw_, fw, qualCutoff_, true, verbose_, quiet_, halfAndHalf, false, maqPenalty_, qualOrder_); EbwtRangeSource *rFw_FwSeedGen = new EbwtRangeSource( &ebwtFw_, fw, qualCutoff_, false, verbose_, quiet_, halfAndHalf, true, maqPenalty_, qualOrder_); EbwtRangeSourceDriver * drFw_Bw = new EbwtRangeSourceDriver( *params, rFw_Bw, fw, false, maqPenalty_, qualOrder_, sink_, sinkPt, seedLen_, // seedLen true, // nudgeLeft PIN_TO_HI_HALF_EDGE, PIN_TO_SEED_EDGE, PIN_TO_SEED_EDGE, PIN_TO_SEED_EDGE, os_, verbose_, quiet_, mate1, pool_, NULL); // no backtrack limit for -n 1/2 EbwtRangeSourceDriverFactory * drFw_BwSeed = new EbwtRangeSourceDriverFactory( *params, rFw_BwSeed, fw, false, maqPenalty_, qualOrder_, sink_, sinkPt, seedLen_, // seedLen true, // nudgeLeft PIN_TO_SEED_EDGE, PIN_TO_SEED_EDGE, PIN_TO_SEED_EDGE, PIN_TO_SEED_EDGE, os_, verbose_, quiet_, mate1, pool_, NULL); // no backtrack limit for -n 1/2 EbwtRangeSourceDriver * drFw_FwSeedGen = new EbwtRangeSourceDriver( *params, rFw_FwSeedGen, fw, true, maqPenalty_, qualOrder_, sink_, sinkPt, seedLen_, // seedLen false, // nudgeLeft PIN_TO_HI_HALF_EDGE, PIN_TO_SEED_EDGE, PIN_TO_SEED_EDGE, PIN_TO_SEED_EDGE, os_, verbose_, quiet_, mate1, pool_, NULL); // no backtrack limit for -n 1/2 EbwtSeededRangeSourceDriver * drFw_Seed = new EbwtSeededRangeSourceDriver( drFw_BwSeed, drFw_FwSeedGen, fw, seedLen_, verbose_, quiet_, mate1); dr2FwVec->push_back(drFw_Bw); dr2FwVec->push_back(drFw_Seed); } if(do1Rc) { bool mate1 = true; bool fw = false; EbwtRangeSource *rRc_Fw = new EbwtRangeSource( &ebwtFw_, fw, qualCutoff_, true, verbose_, quiet_, halfAndHalf, false, maqPenalty_, qualOrder_); EbwtRangeSourceFactory *rRc_FwSeed = new EbwtRangeSourceFactory( &ebwtFw_, fw, qualCutoff_, true, verbose_, quiet_, halfAndHalf, false, maqPenalty_, qualOrder_); EbwtRangeSource *rRc_BwSeedGen = new EbwtRangeSource( ebwtBw_, fw, qualCutoff_, false, verbose_, quiet_, halfAndHalf, true, maqPenalty_, qualOrder_); EbwtRangeSourceDriver * drRc_Fw = new EbwtRangeSourceDriver( *params, rRc_Fw, fw, false, maqPenalty_, qualOrder_, sink_, sinkPt, seedLen_, // seedLen true, // nudgeLeft PIN_TO_HI_HALF_EDGE, PIN_TO_SEED_EDGE, PIN_TO_SEED_EDGE, PIN_TO_SEED_EDGE, os_, verbose_, quiet_, mate1, pool_, NULL); // no backtrack limit for -n 1/2 EbwtRangeSourceDriverFactory * drRc_FwSeed = new EbwtRangeSourceDriverFactory( *params, rRc_FwSeed, fw, false, maqPenalty_, qualOrder_, sink_, sinkPt, seedLen_, // seedLen true, // nudgeLeft PIN_TO_SEED_EDGE, PIN_TO_SEED_EDGE, PIN_TO_SEED_EDGE, PIN_TO_SEED_EDGE, os_, verbose_, quiet_, mate1, pool_, NULL); // no backtrack limit for -n 1/2 EbwtRangeSourceDriver * drRc_BwSeedGen = new EbwtRangeSourceDriver( *params, rRc_BwSeedGen, fw, true, maqPenalty_, qualOrder_, sink_, sinkPt, seedLen_, // seedLen false, // nudgeLeft PIN_TO_HI_HALF_EDGE, PIN_TO_SEED_EDGE, PIN_TO_SEED_EDGE, PIN_TO_SEED_EDGE, os_, verbose_, quiet_, mate1, pool_, NULL); // no backtrack limit for -n 1/2 EbwtSeededRangeSourceDriver * drRc_Seed = new EbwtSeededRangeSourceDriver( drRc_FwSeed, drRc_BwSeedGen, fw, seedLen_, verbose_, quiet_, mate1); dr1RcVec->push_back(drRc_Fw); dr1RcVec->push_back(drRc_Seed); } if(do2Rc) { bool mate1 = false; bool fw = false; EbwtRangeSource *rRc_Fw = new EbwtRangeSource( &ebwtFw_, fw, qualCutoff_, true, verbose_, quiet_, halfAndHalf, false, maqPenalty_, qualOrder_); EbwtRangeSourceFactory *rRc_FwSeed = new EbwtRangeSourceFactory( &ebwtFw_, fw, qualCutoff_, true, verbose_, quiet_, halfAndHalf, false, maqPenalty_, qualOrder_); EbwtRangeSource *rRc_BwSeedGen = new EbwtRangeSource( ebwtBw_, fw, qualCutoff_, false, verbose_, quiet_, halfAndHalf, true, maqPenalty_, qualOrder_); EbwtRangeSourceDriver * drRc_Fw = new EbwtRangeSourceDriver( *params, rRc_Fw, fw, false, maqPenalty_, qualOrder_, sink_, sinkPt, seedLen_, // seedLen true, // nudgeLeft PIN_TO_HI_HALF_EDGE, PIN_TO_SEED_EDGE, PIN_TO_SEED_EDGE, PIN_TO_SEED_EDGE, os_, verbose_, quiet_, mate1, pool_, NULL); // no backtrack limit for -n 1/2 EbwtRangeSourceDriverFactory * drRc_FwSeed = new EbwtRangeSourceDriverFactory( *params, rRc_FwSeed, fw, false, maqPenalty_, qualOrder_, sink_, sinkPt, seedLen_, // seedLen true, // nudgeLeft PIN_TO_SEED_EDGE, PIN_TO_SEED_EDGE, PIN_TO_SEED_EDGE, PIN_TO_SEED_EDGE, os_, verbose_, quiet_, mate1, pool_, NULL); // no backtrack limit for -n 1/2 EbwtRangeSourceDriver * drRc_BwSeedGen = new EbwtRangeSourceDriver( *params, rRc_BwSeedGen, fw, true, maqPenalty_, qualOrder_, sink_, sinkPt, seedLen_, // seedLen false, // nudgeLeft PIN_TO_HI_HALF_EDGE, PIN_TO_SEED_EDGE, PIN_TO_SEED_EDGE, PIN_TO_SEED_EDGE, os_, verbose_, quiet_, mate1, pool_, NULL); // no backtrack limit for -n 1/2 EbwtSeededRangeSourceDriver * drRc_Seed = new EbwtSeededRangeSourceDriver( drRc_FwSeed, drRc_BwSeedGen, fw, seedLen_, verbose_, quiet_, mate1); dr2RcVec->push_back(drRc_Fw); dr2RcVec->push_back(drRc_Seed); } } else if(seedMms_ > 1) { bool two = seedMms_ == 2; if(do1Fw) { bool mate1 = true; bool fw = true; EbwtRangeSource *rFw_Bw = new EbwtRangeSource( ebwtBw_, fw, qualCutoff_, true, verbose_, quiet_, 0, false, maqPenalty_, qualOrder_); EbwtRangeSourceFactory *rFw_BwSeed = new EbwtRangeSourceFactory( ebwtBw_, fw, qualCutoff_, true, verbose_, quiet_, 0, false, maqPenalty_, qualOrder_); EbwtRangeSource *rFw_FwSeedGen = new EbwtRangeSource( &ebwtFw_, fw, qualCutoff_, false, verbose_, quiet_, 0, true, maqPenalty_, qualOrder_); EbwtRangeSource *rFw_BwHalf = new EbwtRangeSource( ebwtBw_, fw, qualCutoff_, false, verbose_, quiet_, 2, false, maqPenalty_, qualOrder_); EbwtRangeSourceDriver * drFw_Bw = new EbwtRangeSourceDriver( *params, rFw_Bw, fw, false, maqPenalty_, qualOrder_, sink_, sinkPt, seedLen_, // seedLen true, // nudgeLeft PIN_TO_HI_HALF_EDGE, PIN_TO_HI_HALF_EDGE, two ? PIN_TO_SEED_EDGE : PIN_TO_HI_HALF_EDGE, PIN_TO_SEED_EDGE, os_, verbose_, quiet_, mate1, pool_, btCnt); EbwtRangeSourceDriverFactory * drFw_BwSeed = new EbwtRangeSourceDriverFactory( *params, rFw_BwSeed, fw, false, maqPenalty_, qualOrder_, sink_, sinkPt, seedLen_, // seedLen true, // nudgeLeft PIN_TO_SEED_EDGE, PIN_TO_SEED_EDGE, PIN_TO_SEED_EDGE, PIN_TO_SEED_EDGE, os_, verbose_, quiet_, mate1, pool_, btCnt); EbwtRangeSourceDriver * drFw_FwSeedGen = new EbwtRangeSourceDriver( *params, rFw_FwSeedGen, fw, true, maqPenalty_, qualOrder_, sink_, sinkPt, seedLen_, // seedLen false, // nudgeLeft PIN_TO_HI_HALF_EDGE, PIN_TO_HI_HALF_EDGE, two ? PIN_TO_SEED_EDGE : PIN_TO_HI_HALF_EDGE, PIN_TO_SEED_EDGE, os_, verbose_, quiet_, mate1, pool_, btCnt); EbwtSeededRangeSourceDriver * drFw_Seed = new EbwtSeededRangeSourceDriver( drFw_BwSeed, drFw_FwSeedGen, fw, seedLen_, verbose_, quiet_, mate1); EbwtRangeSourceDriverFactory * drFw_BwSeed12 = NULL; if(!two) { EbwtRangeSourceFactory *rFw_BwSeed12 = new EbwtRangeSourceFactory( ebwtBw_, fw, qualCutoff_, true, verbose_, quiet_, 0, false, maqPenalty_, qualOrder_); drFw_BwSeed12 = new EbwtRangeSourceDriverFactory( *params, rFw_BwSeed12, fw, false, maqPenalty_, qualOrder_, sink_, sinkPt, seedLen_, // seedLen true, // nudgeLeft PIN_TO_SEED_EDGE, PIN_TO_SEED_EDGE, PIN_TO_SEED_EDGE, PIN_TO_SEED_EDGE, os_, verbose_, quiet_, mate1, pool_, btCnt); } EbwtRangeSourceDriver * drFw_FwSeedGen12 = NULL; if(!two) { EbwtRangeSource *rFw_FwSeedGen12 = new EbwtRangeSource( &ebwtFw_, fw, qualCutoff_, false, verbose_, quiet_, 3, true, maqPenalty_, qualOrder_); drFw_FwSeedGen12 = new EbwtRangeSourceDriver( *params, rFw_FwSeedGen12, fw, true, maqPenalty_, qualOrder_, sink_, sinkPt, seedLen_, // seedLen false, // nudgeLeft PIN_TO_BEGINNING, PIN_TO_HI_HALF_EDGE, PIN_TO_HI_HALF_EDGE, PIN_TO_SEED_EDGE, os_, verbose_, quiet_, mate1, pool_, btCnt); } EbwtSeededRangeSourceDriver * drFw_Seed12 = NULL; if(!two) { drFw_Seed12 = new EbwtSeededRangeSourceDriver( drFw_BwSeed12, drFw_FwSeedGen12, fw, seedLen_, verbose_, quiet_, mate1); } EbwtRangeSourceDriver * drFw_BwHalf = new EbwtRangeSourceDriver( *params, rFw_BwHalf, fw, false, maqPenalty_, qualOrder_, sink_, sinkPt, seedLen_, // seedLen true, // nudgeLeft PIN_TO_BEGINNING, // nothing's unrevisitable PIN_TO_HI_HALF_EDGE, two ? PIN_TO_SEED_EDGE : PIN_TO_HI_HALF_EDGE, PIN_TO_SEED_EDGE, os_, verbose_, quiet_, mate1, pool_, btCnt); dr1FwVec->push_back(drFw_Bw); dr1FwVec->push_back(drFw_Seed); if(drFw_Seed12 != NULL) { dr1FwVec->push_back(drFw_Seed12); } dr1FwVec->push_back(drFw_BwHalf); } if(do2Fw) { bool mate1 = false; bool fw = true; EbwtRangeSource *rFw_Bw = new EbwtRangeSource( ebwtBw_, fw, qualCutoff_, true, verbose_, quiet_, 0, false, maqPenalty_, qualOrder_); EbwtRangeSourceFactory *rFw_BwSeed = new EbwtRangeSourceFactory( ebwtBw_, fw, qualCutoff_, true, verbose_, quiet_, 0, false, maqPenalty_, qualOrder_); EbwtRangeSource *rFw_FwSeedGen = new EbwtRangeSource( &ebwtFw_, fw, qualCutoff_, false, verbose_, quiet_, 0, true, maqPenalty_, qualOrder_); EbwtRangeSource *rFw_BwHalf = new EbwtRangeSource( ebwtBw_, fw, qualCutoff_, false, verbose_, quiet_, 2, false, maqPenalty_, qualOrder_); EbwtRangeSourceDriver * drFw_Bw = new EbwtRangeSourceDriver( *params, rFw_Bw, fw, false, maqPenalty_, qualOrder_, sink_, sinkPt, seedLen_, // seedLen true, // nudgeLeft PIN_TO_HI_HALF_EDGE, PIN_TO_HI_HALF_EDGE, two ? PIN_TO_SEED_EDGE : PIN_TO_HI_HALF_EDGE, PIN_TO_SEED_EDGE, os_, verbose_, quiet_, mate1, pool_, btCnt); EbwtRangeSourceDriverFactory * drFw_BwSeed = new EbwtRangeSourceDriverFactory( *params, rFw_BwSeed, fw, false, maqPenalty_, qualOrder_, sink_, sinkPt, seedLen_, // seedLen true, // nudgeLeft PIN_TO_SEED_EDGE, PIN_TO_SEED_EDGE, PIN_TO_SEED_EDGE, PIN_TO_SEED_EDGE, os_, verbose_, quiet_, mate1, pool_, btCnt); EbwtRangeSourceDriver * drFw_FwSeedGen = new EbwtRangeSourceDriver( *params, rFw_FwSeedGen, fw, true, maqPenalty_, qualOrder_, sink_, sinkPt, seedLen_, // seedLen false, // nudgeLeft PIN_TO_HI_HALF_EDGE, PIN_TO_HI_HALF_EDGE, two ? PIN_TO_SEED_EDGE : PIN_TO_HI_HALF_EDGE, PIN_TO_SEED_EDGE, os_, verbose_, quiet_, mate1, pool_, btCnt); EbwtSeededRangeSourceDriver * drFw_Seed = new EbwtSeededRangeSourceDriver( drFw_BwSeed, drFw_FwSeedGen, fw, seedLen_, verbose_, quiet_, mate1); EbwtRangeSourceDriverFactory * drFw_BwSeed12 = NULL; if(!two) { EbwtRangeSourceFactory *rFw_BwSeed12 = new EbwtRangeSourceFactory( ebwtBw_, fw, qualCutoff_, true, verbose_, quiet_, 0, false, maqPenalty_, qualOrder_); drFw_BwSeed12 = new EbwtRangeSourceDriverFactory( *params, rFw_BwSeed12, fw, false, maqPenalty_, qualOrder_, sink_, sinkPt, seedLen_, // seedLen true, // nudgeLeft PIN_TO_SEED_EDGE, PIN_TO_SEED_EDGE, PIN_TO_SEED_EDGE, PIN_TO_SEED_EDGE, os_, verbose_, quiet_, mate1, pool_, btCnt); } EbwtRangeSourceDriver * drFw_FwSeedGen12 = NULL; if(!two) { EbwtRangeSource *rFw_FwSeedGen12 = new EbwtRangeSource( &ebwtFw_, fw, qualCutoff_, false, verbose_, quiet_, 3, true, maqPenalty_, qualOrder_); drFw_FwSeedGen12 = new EbwtRangeSourceDriver( *params, rFw_FwSeedGen12, fw, true, maqPenalty_, qualOrder_, sink_, sinkPt, seedLen_, // seedLen false, // nudgeLeft PIN_TO_BEGINNING, PIN_TO_HI_HALF_EDGE, PIN_TO_HI_HALF_EDGE, PIN_TO_SEED_EDGE, os_, verbose_, quiet_, mate1, pool_, btCnt); } EbwtSeededRangeSourceDriver * drFw_Seed12 = NULL; if(!two) { drFw_Seed12 = new EbwtSeededRangeSourceDriver( drFw_BwSeed12, drFw_FwSeedGen12, fw, seedLen_, verbose_, quiet_, mate1); } EbwtRangeSourceDriver * drFw_BwHalf = new EbwtRangeSourceDriver( *params, rFw_BwHalf, fw, false, maqPenalty_, qualOrder_, sink_, sinkPt, seedLen_, // seedLen true, // nudgeLeft PIN_TO_BEGINNING, // nothing's unrevisitable PIN_TO_HI_HALF_EDGE, two ? PIN_TO_SEED_EDGE : PIN_TO_HI_HALF_EDGE, PIN_TO_SEED_EDGE, os_, verbose_, quiet_, mate1, pool_, btCnt); dr2FwVec->push_back(drFw_Bw); dr2FwVec->push_back(drFw_Seed); if(drFw_Seed12 != NULL) { dr2FwVec->push_back(drFw_Seed12); } dr2FwVec->push_back(drFw_BwHalf); } if(do1Rc) { bool mate1 = true; bool fw = false; EbwtRangeSource *rRc_Fw = new EbwtRangeSource( &ebwtFw_, fw, qualCutoff_, true, verbose_, quiet_, 0, false, maqPenalty_, qualOrder_); EbwtRangeSourceFactory *rRc_FwSeed = new EbwtRangeSourceFactory( &ebwtFw_, fw, qualCutoff_, true, verbose_, quiet_, 0, false, maqPenalty_, qualOrder_); EbwtRangeSource *rRc_BwSeedGen = new EbwtRangeSource( ebwtBw_, fw, qualCutoff_, false, verbose_, quiet_, 0, true, maqPenalty_, qualOrder_); EbwtRangeSource *rRc_FwHalf = new EbwtRangeSource( &ebwtFw_, fw, qualCutoff_, false, verbose_, quiet_, 2, false, maqPenalty_, qualOrder_); EbwtRangeSourceDriver * drRc_Fw = new EbwtRangeSourceDriver( *params, rRc_Fw, fw, false, maqPenalty_, qualOrder_, sink_, sinkPt, seedLen_, // seedLen true, // nudgeLeft PIN_TO_HI_HALF_EDGE, PIN_TO_HI_HALF_EDGE, two ? PIN_TO_SEED_EDGE : PIN_TO_HI_HALF_EDGE, PIN_TO_SEED_EDGE, os_, verbose_, quiet_, mate1, pool_, btCnt); EbwtRangeSourceDriverFactory * drRc_FwSeed = new EbwtRangeSourceDriverFactory( *params, rRc_FwSeed, fw, false, maqPenalty_, qualOrder_, sink_, sinkPt, seedLen_, // seedLen true, // nudgeLeft PIN_TO_SEED_EDGE, PIN_TO_SEED_EDGE, PIN_TO_SEED_EDGE, PIN_TO_SEED_EDGE, os_, verbose_, quiet_, mate1, pool_, btCnt); EbwtRangeSourceDriver * drRc_BwSeedGen = new EbwtRangeSourceDriver( *params, rRc_BwSeedGen, fw, true, maqPenalty_, qualOrder_, sink_, sinkPt, seedLen_, // seedLen false, // nudgeLeft PIN_TO_HI_HALF_EDGE, PIN_TO_HI_HALF_EDGE, two ? PIN_TO_SEED_EDGE : PIN_TO_HI_HALF_EDGE, PIN_TO_SEED_EDGE, os_, verbose_, quiet_, mate1, pool_, btCnt); EbwtSeededRangeSourceDriver * drRc_Seed = new EbwtSeededRangeSourceDriver( drRc_FwSeed, drRc_BwSeedGen, fw, seedLen_, verbose_, quiet_, mate1); EbwtRangeSourceDriverFactory * drRc_FwSeed12 = NULL; if(!two) { EbwtRangeSourceFactory *rRc_FwSeed12 = new EbwtRangeSourceFactory( &ebwtFw_, fw, qualCutoff_, true, verbose_, quiet_, 0, false, maqPenalty_, qualOrder_); drRc_FwSeed12 = new EbwtRangeSourceDriverFactory( *params, rRc_FwSeed12, fw, false, maqPenalty_, qualOrder_, sink_, sinkPt, seedLen_, // seedLen true, // nudgeLeft PIN_TO_SEED_EDGE, PIN_TO_SEED_EDGE, PIN_TO_SEED_EDGE, PIN_TO_SEED_EDGE, os_, verbose_, quiet_, mate1, pool_, btCnt); } EbwtRangeSourceDriver * drRc_BwSeedGen12 = NULL; if(!two) { EbwtRangeSource *rRc_BwSeedGen12 = new EbwtRangeSource( ebwtBw_, fw, qualCutoff_, false, verbose_, quiet_, 3, true, maqPenalty_, qualOrder_); drRc_BwSeedGen12 = new EbwtRangeSourceDriver( *params, rRc_BwSeedGen12, fw, true, maqPenalty_, qualOrder_, sink_, sinkPt, seedLen_, // seedLen false, // nudgeLeft PIN_TO_BEGINNING, PIN_TO_HI_HALF_EDGE, PIN_TO_HI_HALF_EDGE, PIN_TO_SEED_EDGE, os_, verbose_, quiet_, mate1, pool_, btCnt); } EbwtSeededRangeSourceDriver * drRc_Seed12 = NULL; if(!two) { drRc_Seed12 = new EbwtSeededRangeSourceDriver( drRc_FwSeed12, drRc_BwSeedGen12, fw, seedLen_, verbose_, quiet_, mate1); } EbwtRangeSourceDriver * drRc_FwHalf = new EbwtRangeSourceDriver( *params, rRc_FwHalf, fw, false, maqPenalty_, qualOrder_, sink_, sinkPt, seedLen_, // seedLen true, // nudgeLeft PIN_TO_BEGINNING, // nothing's unrevisitable PIN_TO_HI_HALF_EDGE, two ? PIN_TO_SEED_EDGE : PIN_TO_HI_HALF_EDGE, PIN_TO_SEED_EDGE, os_, verbose_, quiet_, mate1, pool_, btCnt); dr1RcVec->push_back(drRc_Fw); dr1RcVec->push_back(drRc_Seed); if(drRc_Seed12 != NULL) { dr1RcVec->push_back(drRc_Seed12); } dr1RcVec->push_back(drRc_FwHalf); } if(do2Rc) { bool mate1 = false; bool fw = false; EbwtRangeSource *rRc_Fw = new EbwtRangeSource( &ebwtFw_, fw, qualCutoff_, true, verbose_, quiet_, 0, false, maqPenalty_, qualOrder_); EbwtRangeSourceFactory *rRc_FwSeed = new EbwtRangeSourceFactory( &ebwtFw_, fw, qualCutoff_, true, verbose_, quiet_, 0, false, maqPenalty_, qualOrder_); EbwtRangeSource *rRc_BwSeedGen = new EbwtRangeSource( ebwtBw_, fw, qualCutoff_, false, verbose_, quiet_, 0, true, maqPenalty_, qualOrder_); EbwtRangeSource *rRc_FwHalf = new EbwtRangeSource( &ebwtFw_, fw, qualCutoff_, false, verbose_, quiet_, 2, false, maqPenalty_, qualOrder_); EbwtRangeSourceDriver * drRc_Fw = new EbwtRangeSourceDriver( *params, rRc_Fw, fw, false, maqPenalty_, qualOrder_, sink_, sinkPt, seedLen_, // seedLen true, // nudgeLeft PIN_TO_HI_HALF_EDGE, PIN_TO_HI_HALF_EDGE, two ? PIN_TO_SEED_EDGE : PIN_TO_HI_HALF_EDGE, PIN_TO_SEED_EDGE, os_, verbose_, quiet_, mate1, pool_, btCnt); EbwtRangeSourceDriverFactory * drRc_FwSeed = new EbwtRangeSourceDriverFactory( *params, rRc_FwSeed, fw, false, maqPenalty_, qualOrder_, sink_, sinkPt, seedLen_, // seedLen true, // nudgeLeft PIN_TO_SEED_EDGE, PIN_TO_SEED_EDGE, PIN_TO_SEED_EDGE, PIN_TO_SEED_EDGE, os_, verbose_, quiet_, mate1, pool_, btCnt); EbwtRangeSourceDriver * drRc_BwSeedGen = new EbwtRangeSourceDriver( *params, rRc_BwSeedGen, fw, true, maqPenalty_, qualOrder_, sink_, sinkPt, seedLen_, // seedLen false, // nudgeLeft PIN_TO_HI_HALF_EDGE, PIN_TO_HI_HALF_EDGE, two ? PIN_TO_SEED_EDGE : PIN_TO_HI_HALF_EDGE, PIN_TO_SEED_EDGE, os_, verbose_, quiet_, mate1, pool_, btCnt); EbwtSeededRangeSourceDriver * drRc_Seed = new EbwtSeededRangeSourceDriver( drRc_FwSeed, drRc_BwSeedGen, fw, seedLen_, verbose_, quiet_, mate1); EbwtRangeSourceDriverFactory * drRc_FwSeed12 = NULL; if(!two) { EbwtRangeSourceFactory *rRc_FwSeed12 = new EbwtRangeSourceFactory( &ebwtFw_, fw, qualCutoff_, true, verbose_, quiet_, 0, false, maqPenalty_, qualOrder_); drRc_FwSeed12 = new EbwtRangeSourceDriverFactory( *params, rRc_FwSeed12, fw, false, maqPenalty_, qualOrder_, sink_, sinkPt, seedLen_, // seedLen true, // nudgeLeft PIN_TO_SEED_EDGE, PIN_TO_SEED_EDGE, PIN_TO_SEED_EDGE, PIN_TO_SEED_EDGE, os_, verbose_, quiet_, mate1, pool_, btCnt); } EbwtRangeSourceDriver * drRc_BwSeedGen12 = NULL; if(!two) { EbwtRangeSource *rRc_BwSeedGen12 = new EbwtRangeSource( ebwtBw_, fw, qualCutoff_, false, verbose_, quiet_, 3, true, maqPenalty_, qualOrder_); drRc_BwSeedGen12 = new EbwtRangeSourceDriver( *params, rRc_BwSeedGen12, fw, true, maqPenalty_, qualOrder_, sink_, sinkPt, seedLen_, // seedLen false, // nudgeLeft PIN_TO_BEGINNING, PIN_TO_HI_HALF_EDGE, PIN_TO_HI_HALF_EDGE, PIN_TO_SEED_EDGE, os_, verbose_, quiet_, mate1, pool_, btCnt); } EbwtSeededRangeSourceDriver * drRc_Seed12 = NULL; if(!two) { drRc_Seed12 = new EbwtSeededRangeSourceDriver( drRc_FwSeed12, drRc_BwSeedGen12, fw, seedLen_, verbose_, quiet_, mate1); } EbwtRangeSourceDriver * drRc_FwHalf = new EbwtRangeSourceDriver( *params, rRc_FwHalf, fw, false, maqPenalty_, qualOrder_, sink_, sinkPt, seedLen_, // seedLen true, // nudgeLeft PIN_TO_BEGINNING, // nothing's unrevisitable PIN_TO_HI_HALF_EDGE, two ? PIN_TO_SEED_EDGE : PIN_TO_HI_HALF_EDGE, PIN_TO_SEED_EDGE, os_, verbose_, quiet_, mate1, pool_, btCnt); dr2RcVec->push_back(drRc_Fw); dr2RcVec->push_back(drRc_Seed); if(drRc_Seed12 != NULL) { dr2RcVec->push_back(drRc_Seed12); } dr2RcVec->push_back(drRc_FwHalf); } } else { cerr << "Unsupported --stateful mode: " << seedMms_ << endl; } // Set up a RangeChaser RangeChaser > *rchase = new RangeChaser >(cacheLimit_, cacheFw_, cacheBw_); if(v1_) { PairedBWAlignerV1* al = new PairedBWAlignerV1( params, new TCostAwareRangeSrcDr(strandFix_, dr1FwVec, verbose_, quiet_, false), new TCostAwareRangeSrcDr(strandFix_, dr1RcVec, verbose_, quiet_, false), new TCostAwareRangeSrcDr(strandFix_, dr2FwVec, verbose_, quiet_, false), new TCostAwareRangeSrcDr(strandFix_, dr2RcVec, verbose_, quiet_, false), refAligner, rchase, sink_, sinkPtFactory_, sinkPt, mate1fw_, mate2fw_, peInner_, peOuter_, dontReconcile_, symCeil_, mixedThresh_, mixedAttemptLim_, refs_, rangeMode_, verbose_, quiet_, maxBts_, pool_, btCnt); delete dr1FwVec; delete dr1RcVec; delete dr2FwVec; delete dr2RcVec; return al; } else { // We dumped all the drivers into dr1FwVec PairedBWAlignerV2* al = new PairedBWAlignerV2( params, paramsSe1, paramsSe2, new TCostAwareRangeSrcDr(strandFix_, dr1FwVec, verbose_, quiet_, true), refAligner, rchase, sink_, sinkPtFactory_, sinkPt, sinkPtSe1, sinkPtSe2, mate1fw_, mate2fw_, peInner_, peOuter_, mixedAttemptLim_, refs_, rangeMode_, verbose_, quiet_, maxBts_, pool_, btCnt); delete dr1FwVec; return al; } } private: Ebwt >& ebwtFw_; Ebwt >* ebwtBw_; bool color_; const bool v1_; // whether to use V1 PairedAligner const bool doFw_; const bool doRc_; const uint32_t seedMms_; const uint32_t seedLen_; const int qualCutoff_; const int maxBts_; HitSink& sink_; const HitSinkPerThreadFactory& sinkPtFactory_; const bool mate1fw_; const bool mate2fw_; const uint32_t peInner_; const uint32_t peOuter_; const bool dontReconcile_; const uint32_t symCeil_; const uint32_t mixedThresh_; const uint32_t mixedAttemptLim_; RangeCache *cacheFw_; RangeCache *cacheBw_; const uint32_t cacheLimit_; ChunkPool *pool_; BitPairReference* refs_; vector >& os_; const bool reportSe_; const bool maqPenalty_; const bool qualOrder_; const bool strandFix_; const bool rangeMode_; const bool verbose_; const bool quiet_; }; #endif /* ALIGNER_SEED_MM_H_ */ ugene-1.9.8/src/plugins_3rdparty/bowtie/src/bowtie/threading.h0000644000175000017500000000350411651544326023112 0ustar ilyailya#ifndef THREADING_H_ #define THREADING_H_ #include #include "spinlock.h" #include // Note that USE_SPINLOCK trumps BOWTIE_PTHREADS #define BOWTIE_PTHREADS 1 #ifdef BOWTIE_PTHREADS #define pthread_t int #endif #ifdef USE_SPINLOCK # include "spinlock.h" # define MUTEX_T SpinLock # define MUTEX_INIT(l) # define MUTEX_LOCK(l) (l).Enter() # define MUTEX_UNLOCK(l) (l).Leave() #else # ifdef BOWTIE_PTHREADS struct QMutextContainer { struct Data { Data() {count = 0; m = new QMutex(); } QMutex* m; int count; }; QMutextContainer(): d(NULL) {} QMutextContainer(const QMutextContainer &c) { if(c.d==NULL) { d=NULL; return; } d = c.d; d->count++; } QMutextContainer &operator = (const QMutextContainer &c) { if(c.d==NULL) { d=NULL; return *this; } d = c.d; d->count++; return *this; } ~QMutextContainer() { if(d==NULL) return; d->count--; if(d->count == 0) delete d; d = NULL; } Data* d; void init() {d = new Data(); d->count++;} void lock() {d->m->lock();} void unlock() {d->m->unlock();} }; # define MUTEX_T QMutextContainer # define MUTEX_INIT(l) (l).init() # define MUTEX_LOCK(l) (l).lock() # define MUTEX_UNLOCK(l) (l).unlock() # else # define MUTEX_T int # define MUTEX_INIT(l) l = 0 # define MUTEX_LOCK(l) l = 1 # define MUTEX_UNLOCK(l) l = 0 # endif /* UGENE_THREADS */ #endif /* USE_SPINLOCK */ #ifdef BOWTIE_PTHREADS static inline void exitThread(void* v) { throw 2; } extern void joinThread(pthread_t th); extern void createThread(pthread_t* th, void *(*start_routine) (void *), void *arg); #endif /** * Wrap a lock; obtain lock upon construction, release upon destruction. */ class ThreadSafe { public: ThreadSafe(MUTEX_T* lock) { lock_ = lock; MUTEX_LOCK(*lock_); } ~ThreadSafe() { MUTEX_UNLOCK(*lock_); } private: MUTEX_T *lock_; }; #endif ugene-1.9.8/src/plugins_3rdparty/bowtie/src/bowtie/reference.h0000644000175000017500000005502211651544326023105 0ustar ilyailya#ifndef REFERENCE_H_ #define REFERENCE_H_ #include #include "endian_swap.h" #include "mm.h" #include "shmem.h" #include "timer.h" /** * Concrete reference representation that bulk-loads the reference from * the bit-pair-compacted binary file and stores it in memory also in * bit-pair-compacted format. The user may request reference * characters either on a per-character bases or by "stretch" using * getBase(...) and getStretch(...) respectively. * * Most of the complexity in this class is due to the fact that we want * to represent references with ambiguous (non-A/C/G/T) characters but * we don't want to use more than two bits per base. This means we * need a way to encode the ambiguous stretches of the reference in a * way that is external to the bitpair sequence. To accomplish this, * we use the RefRecords vector, which is stored in the .3.ebwt index * file. The bitpairs themselves are stored in the .4.ebwt index file. * * Once it has been loaded, a BitPairReference is read-only, and is * safe for many threads to access at once. */ class BitPairReference { public: /** * Load from .3.ebwt/.4.ebwt Bowtie index files. */ BitPairReference(const string& in, bool color, bool sanity, std::vector* infiles, std::vector >* origs, bool infilesSeq, bool loadSequence, // as opposed to just records bool useMm, bool useShmem, bool mmSweep, bool verbose, bool startVerbose) : buf_(NULL), sanityBuf_(NULL), loaded_(true), sanity_(sanity), useMm_(useMm), useShmem_(useShmem), verbose_(verbose) { string s3 = in + ".3.ebwt"; string s4 = in + ".4.ebwt"; #ifdef BOWTIE_MM int f3, f4; if((f3 = open(s3.c_str(), O_RDONLY)) < 0) { cerr << "Could not open reference-string index file " << s3 << " for reading." << endl; cerr << "This is most likely because your index was built with an older version" << endl << "(<= 0.9.8.1) of bowtie-build. Please re-run bowtie-build to generate a new" << endl << "index (or download one from the Bowtie website) and try again." << endl; loaded_ = false; return; } if((f4 = open(s4.c_str(), O_RDONLY)) < 0) { cerr << "Could not open reference-string index file " << s4 << " for reading." << endl; loaded_ = false; return; } char *mmFile = NULL; if(useMm_) { if(verbose_ || startVerbose) { cerr << " Memory-mapping reference index file " << s4 << ": "; logTime(cerr); } struct stat sbuf; if (stat(s4.c_str(), &sbuf) == -1) { perror("stat"); cerr << "Error: Could not stat index file " << s4.c_str() << " prior to memory-mapping" << endl; throw 1; } mmFile = (char*)mmap((void *)0, sbuf.st_size, PROT_READ, MAP_SHARED, f4, 0); if(mmFile == (void *)(-1) || mmFile == NULL) { perror("mmap"); cerr << "Error: Could not memory-map the index file " << s4.c_str() << endl; throw 1; } if(mmSweep) { int sum = 0; for(off_t i = 0; i < sbuf.st_size; i += 1024) { sum += (int) mmFile[i]; } if(startVerbose) { cerr << " Swept the memory-mapped ref index file; checksum: " << sum << ": "; logTime(cerr); } } } #else FILE *f3, *f4; if((f3 = fopen(s3.c_str(), "rb")) == NULL) { cerr << "Could not open reference-string index file " << s3 << " for reading." << endl; cerr << "This is most likely because your index was built with an older version" << endl << "(<= 0.9.8.1) of bowtie-build. Please re-run bowtie-build to generate a new" << endl << "index (or download one from the Bowtie website) and try again." << endl; loaded_ = false; return; } if((f4 = fopen(s4.c_str(), "rb")) == NULL) { cerr << "Could not open reference-string index file " << s4 << " for reading." << endl; loaded_ = false; return; } #endif // Read endianness sentinel, set 'swap' uint32_t one; bool swap = false; one = readU32(f3, swap); if(one != 1) { if(useMm_) { cerr << "Error: Can't use memory-mapped files when the index is the opposite endianness" << endl; throw 1; } assert_eq(0x1000000, one); swap = true; // have to endian swap U32s } // Read # records uint32_t sz; sz = readU32(f3, swap); if(sz == 0) { cerr << "Error: number of reference records is 0 in " << s3 << endl; throw 1; } // Read records nrefs_ = 0; nNoGapRefs_ = 0; // Cumulative count of all unambiguous characters on a per- // stretch 8-bit alignment (i.e. count of bytes we need to // allocate in buf_) uint32_t cumsz = 0; uint32_t cumlen = 0; uint32_t unambiglen = 0; uint32_t maxlen = 0; // For each unambiguous stretch... for(uint32_t i = 0; i < sz; i++) { recs_.push_back(RefRecord(f3, swap)); } for(uint32_t i = 0; i < sz; i++) { if(recs_[i].first) { if(nrefs_ > 0) { refLens_.push_back(cumlen); } // Stupid hack to get around the fact that, for // colorspace Ebwts, not only do we omit reference // sequences that are *all* gaps from // nPat/plen/refnames, but we also omit reference // sequences that never have a stretch of more than 1 // unambiguous character. if(unambiglen > 0 && (!color || maxlen > 1)) { refApproxLens_.push_back(cumlen); } // More hackery to detect references that won't be // in the Ebwt even though they have non-zero length bool willBeInEbwt = true; if(recs_[i].len > 0 && color) { // Omit until we prove it should be kept willBeInEbwt = false; for(uint32_t j = i; j < sz; j++) { if(j > i && recs_[j].first) break; if(recs_[j].len >= 2) { willBeInEbwt = true; break; } } } if(recs_[i].len > 0 && willBeInEbwt) { // Remember that this is the first record for this // reference sequence (and the last record for the one // before) refRecOffs_.push_back(i); refOffs_.push_back(cumsz); expandIdx_.push_back(nrefs_); shrinkIdx_.push_back(nNoGapRefs_); nNoGapRefs_++; isGaps_.push_back(false); } else { shrinkIdx_.push_back(nNoGapRefs_); isGaps_.push_back(true); } cumlen = 0; unambiglen = 0; maxlen = 0; nrefs_++; assert_eq(nNoGapRefs_, expandIdx_.size()); assert_eq(nrefs_, shrinkIdx_.size()); } else if(i == 0) { //cerr << "First record in reference index file was not marked as 'first'" << endl; //throw 1; } cumsz += recs_[i].len; #ifdef ACCOUNT_FOR_ALL_GAP_REFS cumlen += recs_[i].off; cumlen += recs_[i].len; #else if(recs_[i].len > 0) { cumlen += recs_[i].off; cumlen += recs_[i].len; } #endif unambiglen += recs_[i].len; if(recs_[i].len > maxlen) maxlen = recs_[i].len; } if(verbose_ || startVerbose) { cerr << "Read " << nrefs_ << " reference strings (" << nNoGapRefs_ << " non-empty) from " << sz << " records: "; logTime(cerr); } // Store a cap entry for the end of the last reference seq refRecOffs_.push_back(recs_.size()); refOffs_.push_back(cumsz); if(unambiglen > 0 && (!color || maxlen > 1)) { refApproxLens_.push_back(cumlen); } refLens_.push_back(cumlen); bufSz_ = cumsz; assert_eq(nNoGapRefs_, refApproxLens_.size()); assert_eq(sz, recs_.size()); MM_FILE_CLOSE(f3); // done with .3.ebwt file // Round cumsz up to nearest byte boundary if((cumsz & 3) != 0) { cumsz += (4 - (cumsz & 3)); } bufAllocSz_ = cumsz >> 2; assert_eq(0, cumsz & 3); // should be rounded up to nearest 4 if(!loadSequence) return; if(useMm_) { #ifdef BOWTIE_MM buf_ = (uint8_t*)mmFile; if(sanity_) { FILE *ftmp = fopen(s4.c_str(), "rb"); sanityBuf_ = new uint8_t[cumsz >> 2]; size_t ret = fread(sanityBuf_, 1, cumsz >> 2, ftmp); if(ret != (cumsz >> 2)) { cerr << "Only read " << ret << " bytes (out of " << (cumsz >> 2) << ") from reference index file " << s4 << endl; throw 1; } fclose(ftmp); for(size_t i = 0; i < (cumsz >> 2); i++) { assert_eq(sanityBuf_[i], buf_[i]); } } #else cerr << "Shouldn't be at " << __FILE__ << ":" << __LINE__ << " without BOWTIE_MM defined" << endl; throw 1; #endif } else { bool shmemLeader = true; if(!useShmem_) { // Allocate a buffer to hold the reference string try { buf_ = new uint8_t[cumsz >> 2]; if(buf_ == NULL) throw std::bad_alloc(); } catch(std::bad_alloc& e) { cerr << "Error: Ran out of memory allocating space for the bitpacked reference. Please" << endl << "re-run on a computer with more memory." << endl; throw 1; } } else { shmemLeader = ALLOC_SHARED_U8( (s4 + "[ref]"), (cumsz >> 2), &buf_, "ref", (verbose_ || startVerbose)); } if(shmemLeader) { // Open the bitpair-encoded reference file FILE *f4 = fopen(s4.c_str(), "rb"); if(f4 == NULL) { cerr << "Could not open reference-string index file " << s4 << " for reading." << endl; cerr << "This is most likely because your index was built with an older version" << endl << "(<= 0.9.8.1) of bowtie-build. Please re-run bowtie-build to generate a new" << endl << "index (or download one from the Bowtie website) and try again." << endl; loaded_ = false; return; } // Read the whole thing in size_t ret = fread(buf_, 1, cumsz >> 2, f4); // Didn't read all of it? if(ret != (cumsz >> 2)) { cerr << "Only read " << ret << " bytes (out of " << (cumsz >> 2) << ") from reference index file " << s4 << endl; throw 1; } // Make sure there's no more char c; ret = fread(&c, 1, 1, f4); assert_eq(0, ret); // should have failed fclose(f4); if(useShmem_) NOTIFY_SHARED(buf_, (cumsz >> 2)); } else { if(useShmem_) WAIT_SHARED(buf_, (cumsz >> 2)); } } // Populate byteToU32_ bool big = currentlyBigEndian(); for(int i = 0; i < 256; i++) { uint32_t word = 0; if(big) { word |= ((i >> 0) & 3) << 24; word |= ((i >> 2) & 3) << 16; word |= ((i >> 4) & 3) << 8; word |= ((i >> 6) & 3) << 0; } else { word |= ((i >> 0) & 3) << 0; word |= ((i >> 2) & 3) << 8; word |= ((i >> 4) & 3) << 16; word |= ((i >> 6) & 3) << 24; } byteToU32_[i] = word; } #ifndef NDEBUG if(sanity_) { // Compare the sequence we just read from the compact index // file to the true reference sequence. std::vector > *os; // for holding references std::vector > osv; // for holding references if(infiles != NULL) { if(infilesSeq) { for(size_t i = 0; i < infiles->size(); i++) { // Remove initial backslash; that's almost // certainly being used to protect the first // character of the sequence from getopts (e.g., // when the first char is -) if((*infiles)[i].at(0) == '\\') { (*infiles)[i].erase(0, 1); } osv.push_back(String((*infiles)[i])); } } else { readSequenceFiles, seqan::Fasta>(*infiles, osv); } os = &osv; } else { assert(origs != NULL); os = origs; } // Never mind; reference is always letters, even if index // and alignment run are colorspace // If we're building a colorspace index, we need to convert // osv to colors first // if(color) { // for(size_t i = 0; i < os->size(); i++) { // size_t olen = seqan::length((*os)[i]); // for(size_t j = 0; j < olen-1; j++) { // int b1 = (int)(*os)[i][j]; // assert_geq(b1, 0); assert_leq(b1, 4); // int b2 = (int)(*os)[i][j+1]; // assert_geq(b2, 0); assert_leq(b2, 4); // (*os)[i][j] = (Dna5)dinuc2color[b1][b2]; // assert((b1 != 4 && b2 != 4) || (int)(*os)[i][j] == 4); // } // seqan::resize((*os)[i], olen-1); // } // } // Go through the loaded reference files base-by-base and // sanity check against what we get by calling getBase and // getStretch size_t refi = 0; int longestStretch = 0; int curStretch = 0; for(size_t i = 0; i < os->size(); i++) { size_t olen = seqan::length((*os)[i]); for(size_t j = 0; j < olen; j++) { if((int)(*os)[i][j] < 4) { curStretch++; if(curStretch > longestStretch) longestStretch = curStretch; } else { curStretch = 0; } } if(longestStretch == 0 || (color && longestStretch == 1)) { continue; } longestStretch = 0; size_t olenU32 = (olen + 12) / 4; uint32_t *buf = new uint32_t[olenU32]; uint8_t *bufadj = (uint8_t*)buf; bufadj += getStretch(buf, refi, 0, olen); for(size_t j = 0; j < olen; j++) { assert_eq((int)(*os)[i][j], (int)bufadj[j]); assert_eq((int)(*os)[i][j], (int)getBase(refi, j)); } refi++; delete[] buf; } } #endif } ~BitPairReference() { if(buf_ != NULL && !useMm_ && !useShmem_) delete[] buf_; if(sanityBuf_ != NULL) delete[] sanityBuf_; } /** * Return a single base of the reference. Calling this repeatedly * is not an efficient way to retrieve bases from the reference; * use loadStretch() instead. * * This implementation scans linearly through the records for the * unambiguous stretches of the target reference sequence. When * there are many records, binary search would be more appropriate. */ int getBase(uint32_t tidx, uint32_t toff) const { uint32_t reci = refRecOffs_[tidx]; // first record for target reference sequence uint32_t recf = refRecOffs_[tidx+1]; // last record (exclusive) for target seq assert_gt(recf, reci); uint32_t bufOff = refOffs_[tidx]; uint32_t off = 0; // For all records pertaining to the target reference sequence... for(uint32_t i = reci; i < recf; i++) { assert_geq(toff, off); off += recs_[i].off; if(toff < off) { return 4; } assert_geq(toff, off); uint32_t recOff = off + recs_[i].len; if(toff < recOff) { toff -= off; bufOff += toff; assert_lt(bufOff, bufSz_); const uint32_t bufElt = (bufOff) >> 2; const uint32_t shift = (bufOff & 3) << 1; return ((buf_[bufElt] >> shift) & 3); } bufOff += recs_[i].len; off = recOff; assert_geq(toff, off); } // end for loop over records return 4; } /** * Load a stretch of the reference string into memory at 'dest'. * * This implementation scans linearly through the records for the * unambiguous stretches of the target reference sequence. When * there are many records, binary search would be more appropriate. */ int getStretchNaive(uint32_t *destU32, uint32_t tidx, uint32_t toff, uint32_t count) const { uint8_t *dest = (uint8_t*)destU32; uint32_t reci = refRecOffs_[tidx]; // first record for target reference sequence uint32_t recf = refRecOffs_[tidx+1]; // last record (exclusive) for target seq assert_gt(recf, reci); uint32_t cur = 0; uint32_t bufOff = refOffs_[tidx]; uint32_t off = 0; // For all records pertaining to the target reference sequence... for(uint32_t i = reci; i < recf; i++) { assert_geq(toff, off); off += recs_[i].off; for(; toff < off && count > 0; toff++) { dest[cur++] = 4; count--; } if(count == 0) break; assert_geq(toff, off); if(toff < off + recs_[i].len) { bufOff += (toff - off); // move bufOff pointer forward } else { bufOff += recs_[i].len; } off += recs_[i].len; for(; toff < off && count > 0; toff++) { assert_lt(bufOff, bufSz_); const uint32_t bufElt = (bufOff) >> 2; const uint32_t shift = (bufOff & 3) << 1; dest[cur++] = (buf_[bufElt] >> shift) & 3; bufOff++; count--; } if(count == 0) break; assert_geq(toff, off); } // end for loop over records // In any chars are left after scanning all the records, // they must be ambiguous while(count > 0) { count--; dest[cur++] = 4; } assert_eq(0, count); return 0; } /** * Load a stretch of the reference string into memory at 'dest'. * * This implementation scans linearly through the records for the * unambiguous stretches of the target reference sequence. When * there are many records, binary search would be more appropriate. */ int getStretch(uint32_t *destU32, uint32_t tidx, uint32_t toff, uint32_t count) const { ASSERT_ONLY(uint32_t origCount = count); ASSERT_ONLY(uint32_t origToff = toff); if(count == 0) return 0; uint8_t *dest = (uint8_t*)destU32; #ifndef NDEBUG uint32_t *destU32_2 = new uint32_t[(origCount >> 2) + 2]; int off2 = getStretchNaive(destU32_2, tidx, origToff, origCount); uint8_t *dest_2 = ((uint8_t*)destU32_2) + off2; #endif destU32[0] = 0x04040404; // Add Ns, which we might end up using later uint32_t reci = refRecOffs_[tidx]; // first record for target reference sequence uint32_t recf = refRecOffs_[tidx+1]; // last record (exclusive) for target seq assert_gt(recf, reci); uint32_t cur = 4; // keep a cushion of 4 bases at the beginning uint32_t bufOff = refOffs_[tidx]; uint32_t off = 0; int offset = 4; bool firstStretch = true; // For all records pertaining to the target reference sequence... for(uint32_t i = reci; i < recf; i++) { ASSERT_ONLY(uint32_t origBufOff = bufOff); assert_geq(toff, off); off += recs_[i].off; assert_gt(count, 0); if(toff < off) { uint32_t cpycnt = min(off - toff, count); memset(&dest[cur], 4, cpycnt); count -= cpycnt; toff += cpycnt; cur += cpycnt; if(count == 0) break; } assert_geq(toff, off); if(toff < off + recs_[i].len) { bufOff += (toff - off); // move bufOff pointer forward } else { bufOff += recs_[i].len; } off += recs_[i].len; if(toff < off) { if(firstStretch) { if(toff + 8 < off && count > 8) { // We already added some Ns, so we have to do // a fixup at the beginning of the buffer so // that we can start clobbering at cur >> 2 if(cur & 3) { offset -= (cur & 3); } uint32_t curU32 = cur >> 2; // Do the initial few bases if(bufOff & 3) { const uint32_t bufElt = (bufOff) >> 2; const int low2 = bufOff & 3; destU32[curU32] = byteToU32_[buf_[bufElt]]; for(int j = 0; j < low2; j++) { ((char *)(&destU32[curU32]))[j] = 4; } curU32++; offset += low2; const int chars = 4 - low2; count -= chars; bufOff += chars; toff += chars; } assert_eq(0, bufOff & 3); uint32_t bufOffU32 = bufOff >> 2; uint32_t countLim = count >> 2; uint32_t offLim = (off - (toff + 4)) >> 2; uint32_t lim = min(countLim, offLim); // Do the fast thing for as far as possible for(uint32_t j = 0; j < lim; j++) { destU32[curU32] = byteToU32_[buf_[bufOffU32++]]; assert_eq(dest[(curU32 << 2) + 0], dest_2[(curU32 << 2) - offset + 0]); assert_eq(dest[(curU32 << 2) + 1], dest_2[(curU32 << 2) - offset + 1]); assert_eq(dest[(curU32 << 2) + 2], dest_2[(curU32 << 2) - offset + 2]); assert_eq(dest[(curU32 << 2) + 3], dest_2[(curU32 << 2) - offset + 3]); curU32++; } toff += (lim << 2); assert_leq(toff, off); assert_leq((lim << 2), count); count -= (lim << 2); bufOff = bufOffU32 << 2; cur = curU32 << 2; } // Do the slow thing for the rest for(; toff < off && count > 0; toff++) { assert_lt(bufOff, bufSz_); const uint32_t bufElt = (bufOff) >> 2; const uint32_t shift = (bufOff & 3) << 1; dest[cur++] = (buf_[bufElt] >> shift) & 3; bufOff++; count--; } firstStretch = false; } else { // Do the slow thing for(; toff < off && count > 0; toff++) { assert_lt(bufOff, bufSz_); const uint32_t bufElt = (bufOff) >> 2; const uint32_t shift = (bufOff & 3) << 1; dest[cur++] = (buf_[bufElt] >> shift) & 3; bufOff++; count--; } } } if(count == 0) break; assert_eq(recs_[i].len, bufOff - origBufOff); assert_geq(toff, off); } // end for loop over records // In any chars are left after scanning all the records, // they must be ambiguous while(count > 0) { count--; dest[cur++] = 4; } assert_eq(0, count); #ifndef NDEBUG delete[] destU32_2; #endif return offset; } /// Return the number of reference sequences. uint32_t numRefs() const { return nrefs_; } /// Return the number of reference sequences that don't consist /// entirely of stretches of ambiguous characters. uint32_t numNonGapRefs() const { return nNoGapRefs_; } /** * */ uint32_t shrinkIdx(uint32_t idx) const { assert_lt(idx, shrinkIdx_.size()); return shrinkIdx_[idx]; } /** * */ uint32_t expandIdx(uint32_t idx) const { assert_lt(idx, expandIdx_.size()); return expandIdx_[idx]; } /// Return the lengths of reference sequences. uint32_t approxLen(uint32_t elt) const { assert_lt(elt, nrefs_); return refApproxLens_[elt]; } /// Return the lengths of reference sequences. uint32_t len(uint32_t elt) const { assert_lt(elt, nrefs_); return refLens_[elt]; } /// Return true iff ref 'elt' is all gaps bool isAllGaps(uint32_t elt) const { assert_lt(elt, nrefs_); assert_eq(isGaps_.size(), nrefs_); return isGaps_[elt]; } /// Return true iff buf_ and all the vectors are populated. bool loaded() const { return loaded_; } /** * Return constant reference to the RefRecord list. */ const std::vector& refRecords() const { return recs_; } protected: uint32_t byteToU32_[256]; std::vector recs_; /// records describing unambiguous stretches std::vector refApproxLens_; /// approx lens of ref seqs (excludes trailing ambig chars) std::vector refLens_; /// approx lens of ref seqs (excludes trailing ambig chars) std::vector refOffs_; /// buf_ begin offsets per ref seq std::vector refRecOffs_; /// record begin/end offsets per ref seq std::vector expandIdx_; /// map from small idxs (e.g. w/r/t plen) to large ones (w/r/t refnames) std::vector shrinkIdx_; /// map from large idxs to small std::vector isGaps_; /// ref i is all gaps? uint8_t *buf_; /// the whole reference as a big bitpacked byte array uint8_t *sanityBuf_;/// for sanity-checking buf_ uint32_t bufSz_; /// size of buf_ uint32_t bufAllocSz_; uint32_t nrefs_; /// the number of reference sequences uint32_t nNoGapRefs_; /// the number of reference sequences that aren't totally ambiguous bool loaded_; /// whether it's loaded bool sanity_; /// do sanity checking bool useMm_; /// load the reference as a memory-mapped file bool useShmem_; /// load the reference into shared memory bool verbose_; }; #endif ugene-1.9.8/src/plugins_3rdparty/bowtie/src/bowtie/range_chaser.h0000644000175000017500000001662311651544326023574 0ustar ilyailya/* * range_chaser.h */ #ifndef RANGE_CHASER_H_ #define RANGE_CHASER_H_ #include #include "ebwt.h" #include "random_source.h" #include "row_chaser.h" #include "range_cache.h" #include "aligner_metrics.h" /** * A class that statefully processes a range by picking one row * randomly and then linearly scanning forward through the range, * reporting reference offsets as we go. */ template class RangeChaser { typedef Ebwt TEbwt; typedef std::pair U32Pair; typedef std::vector U32PairVec; typedef RowChaser TRowChaser; public: RangeChaser(uint32_t cacheThresh, RangeCache* cacheFw, RangeCache* cacheBw, AlignerMetrics *metrics = NULL) : done(false), ebwt_(NULL), qlen_(0), cacheThresh_(cacheThresh), top_(0xffffffff), bot_(0xffffffff), irow_(0xffffffff), row_(0xffffffff), off_(make_pair(0xffffffff, 0)), tlen_(0), chaser_(metrics), cached_(false), cacheFw_(cacheFw), cacheBw_(cacheBw), metrics_(metrics) { } ~RangeChaser() { } /** * Convert a range to a vector of reference loci, where a locus is * a u32 pair of . */ static void toOffs(const TEbwt& ebwt, uint32_t qlen, RandomSource& rand, uint32_t top, uint32_t bot, U32PairVec& dest) { RangeChaser rc(ebwt, rand); rc.setTopBot(top, bot, qlen); rc.prep(); while(!rc.done) { rc.advance(); if(rc.foundOff()) { dest.push_back(rc.off()); rc.reset(); assert(!rc.foundOff()); } rc.prep(); } } /** * Set the row to chase */ void setRow(uint32_t row) { // Must be within bounds of range assert_lt(row, bot_); assert_geq(row, top_); row_ = row; while(true) { // First thing to try is the cache if(cached_) { assert(cacheEnt_.valid()); uint32_t cached = cacheEnt_.get(row_ - top_); assert(cacheEnt_.valid()); if(cached != RANGE_NOT_SET) { // Assert that it matches what we would have got... ASSERT_ONLY(uint32_t sanity = TRowChaser::toFlatRefOff(ebwt_, 1, row_)); assert_eq(sanity, cached); // We have a cached result. Cached result is in the // form of an offset into the joined reference string, // so now we have to convert it to a tidx/toff pair. ebwt_->joinedToTextOff(qlen_, cached, off_.first, off_.second, tlen_); // Note: tidx may be 0xffffffff, if alignment overlaps a // reference boundary if(off_.first != 0xffffffff) { // Bingo, we found a valid result using the cache assert(foundOff()); return; } } else { // Wasn't in the cache; use the RowChaser } } // Second thing to try is the chaser chaser_.setRow(row_, qlen_, ebwt_); assert(chaser_.prepped_ || chaser_.done); // It might be done immediately... if(chaser_.done) { // We're done immediately off_ = chaser_.off(); if(off_.first != 0xffffffff) { // This is a valid result if(cached_) { // Install the result in the cache assert(cacheEnt_.valid()); cacheEnt_.install(row_ - top_, chaser_.flatOff()); //if(ebwt_->fw()) assert(cacheFw_->repOk()); //else assert(cacheBw_->repOk()); } tlen_ = chaser_.tlen(); assert(foundOff()); return; // found result } } else { // Pursue this row break; } // That row didn't have a valid result, move to the next row_++; if(row_ == bot_) { // Wrap back to top_ row_ = top_; } if(row_ == irow_) { // Exhausted all possible rows done = true; assert_eq(0xffffffff, off_.first); return; } } assert(chaser_.prepped_); } /** * Set the next range for us to "chase" (i.e. convert row-by-row * to reference loci). */ void setTopBot(uint32_t top, uint32_t bot, uint32_t qlen, RandomSource& rand, const TEbwt* ebwt) { assert_neq(0xffffffff, top); assert_neq(0xffffffff, bot); assert_gt(bot, top); assert_gt(qlen, 0); assert(ebwt != NULL); ebwt_ = ebwt; qlen_ = qlen; top_ = top; bot_ = bot; uint32_t spread = bot - top; irow_ = top + (rand.nextU32() % spread); // initial row done = false; cached_ = false; reset(); if(cacheFw_ != NULL || cacheBw_ != NULL) { if(spread > cacheThresh_) { bool ret = false; if(ebwt->fw() && cacheFw_ != NULL) { ret = cacheFw_->lookup(top, bot, cacheEnt_); if(ret) assert(cacheEnt_.ebwt()->fw()); } else if(!ebwt->fw() && cacheBw_ != NULL) { ret = cacheBw_->lookup(top, bot, cacheEnt_); if(ret) assert(!cacheEnt_.ebwt()->fw()); } else { cacheEnt_.reset(); } assert_eq(cacheEnt_.valid(), ret); cached_ = ret; } else { cacheEnt_.reset(); } } setRow(irow_); assert(chaser_.prepped_ || foundOff() || done); } /** * Advance the step-left process by one step. Check if we're done. */ void advance() { assert(!done); assert(chaser_.prepped_ || chaser_.done); reset(); if(chaser_.done) { // chaser finished with this row row_++; if(row_ == bot_) { row_ = top_; } if(row_ == irow_) { // Exhausted all possible rows done = true; assert_eq(0xffffffff, off_.first); return; } setRow(row_); assert(chaser_.prepped_ || foundOff() || done); } else { chaser_.advance(); assert(chaser_.prepped_ || chaser_.done); if(chaser_.done) { // We're done immediately off_ = chaser_.off(); if(off_.first != 0xffffffff) { if(cached_) { // Install the result in the cache assert(cacheEnt_.valid()); cacheEnt_.install(row_ - top_, chaser_.flatOff()); //if(ebwt_->fw()) assert(cacheFw_->repOk()); //else assert(cacheBw_->repOk()); } // Found a reference position tlen_ = chaser_.tlen(); assert(foundOff()); } } } } /** * Prepare for the next call to advance() by prefetching relevant * data. In this case, 'chaser_' is doing this for us. */ void prep() { // nothing } /** * Return true iff off_ contains a valid reference location for * this range. */ bool foundOff() const { return off_.first != 0xffffffff; } /** * Reset the chaser so that 'off_' does not hold a valid offset and * foundOff() returns false. */ void reset() { off_.first = 0xffffffff; } /** * Get the calculated offset. */ U32Pair off() const { return off_; } /** * Get the length of the hit reference. */ uint32_t tlen() const { return tlen_; } bool done; /// true = chase is done & answer is in off_ protected: const TEbwt* ebwt_; /// index to resolve row in uint32_t qlen_; /// length of read; needed to convert to ref. coordinates uint32_t cacheThresh_; /// ranges wider than thresh use cacheing uint32_t top_; /// range top uint32_t bot_; /// range bottom uint32_t irow_; /// initial randomly-chosen row within range uint32_t row_; /// current row within range U32Pair off_; /// calculated offset (0xffffffff if not done) uint32_t tlen_; /// length of text hit TRowChaser chaser_; /// stateful row chaser RangeCacheEntry cacheEnt_; /// current cache entry bool cached_; /// cacheEnt is active for current range? RangeCache* cacheFw_; /// cache for the forward index RangeCache* cacheBw_; /// cache for the backward index AlignerMetrics *metrics_; }; #endif /* RANGE_CHASER_H_ */ ugene-1.9.8/src/plugins_3rdparty/bowtie/src/bowtie/sam.cpp0000644000175000017500000002270711651544326022266 0ustar ilyailya/* * sam.cpp * * Created on: Sep 23, 2009 * Author: Ben Langmead */ #ifdef _MSC_VER #include #endif #include #include #include #include "pat.h" #include "hit.h" #include "sam.h" using namespace std; /** * Write the SAM header lines. */ void SAMHitSink::appendHeaders(OutFileBuf& os, size_t numRefs, const vector& refnames, bool color, bool nosq, ReferenceMap *rmap, const uint32_t* plen, bool fullRef, const char *cmdline, const char *rgline) { ostringstream ss; ss << "@HD\tVN:1.0\tSO:unsorted" << endl; if(!nosq) { for(size_t i = 0; i < numRefs; i++) { // RNAME ss << "@SQ\tSN:"; if(!refnames.empty() && rmap != NULL) { printUptoWs(ss, rmap->getName(i), !fullRef); } else if(i < refnames.size()) { printUptoWs(ss, refnames[i], !fullRef); } else { ss << i; } ss << "\tLN:" << (plen[i] + (color ? 1 : 0)) << endl; } } if(rgline != NULL) { ss << "@RG\t" << rgline << endl; } //ss << "@PG\tID:Bowtie\tVN:" << BOWTIE_VERSION << "\tCL:\"" << cmdline << "\"" << endl; os.writeString(ss.str()); } /** * Append a SAM output record for an unaligned read. */ void SAMHitSink::appendAligned(ostream& ss, const Hit& h, int mapq, int xms, // value for XM:I field const vector* refnames, ReferenceMap *rmap, AnnotationMap *amap, bool fullRef, int offBase) { // QNAME if(h.mate > 0) { // truncate final 2 chars for(int i = 0; i < (int)seqan::length(h.patName)-2; i++) { if(isspace(h.patName[i])) break; ss << h.patName[i]; } } else { for(int i = 0; i < (int)seqan::length(h.patName); i++) { if(isspace(h.patName[i])) break; ss << h.patName[i]; } } ss << '\t'; // FLAG int flags = 0; if(h.mate == 1) { flags |= SAM_FLAG_PAIRED | SAM_FLAG_FIRST_IN_PAIR | SAM_FLAG_MAPPED_PAIRED; } else if(h.mate == 2) { flags |= SAM_FLAG_PAIRED | SAM_FLAG_SECOND_IN_PAIR | SAM_FLAG_MAPPED_PAIRED; } if(!h.fw) flags |= SAM_FLAG_QUERY_STRAND; if(h.mate > 0 && !h.mfw) flags |= SAM_FLAG_MATE_STRAND; ss << flags << "\t"; // RNAME if(refnames != NULL && rmap != NULL) { printUptoWs(ss, rmap->getName(h.h.first), !fullRef); } else if(refnames != NULL && h.h.first < refnames->size()) { printUptoWs(ss, (*refnames)[h.h.first], !fullRef); } else { ss << h.h.first; } // POS ss << '\t' << (h.h.second + 1); // MAPQ ss << "\t" << mapq; // CIGAR ss << '\t' << h.length() << 'M'; // MRNM if(h.mate > 0) { ss << "\t="; } else { ss << "\t*"; } // MPOS if(h.mate > 0) { ss << '\t' << (h.mh.second + 1); } else { ss << "\t0"; } // ISIZE ss << '\t'; if(h.mate > 0) { assert_eq(h.h.first, h.mh.first); int64_t inslen = 0; if(h.h.second > h.mh.second) { inslen = (int64_t)h.h.second - (int64_t)h.mh.second + (int64_t)h.length(); inslen = -inslen; } else { inslen = (int64_t)h.mh.second - (int64_t)h.h.second + (int64_t)h.mlen; } ss << inslen; } else { ss << '0'; } // SEQ ss << '\t' << h.patSeq; // QUAL ss << '\t' << h.quals; // // Optional fields // // Always output stratum ss << "\tXA:i:" << (int)h.stratum; // Always output cost //ss << "\tXC:i:" << (int)h.cost; // Look for SNP annotations falling within the alignment // Output MD field size_t len = length(h.patSeq); int nm = 0; int run = 0; ss << "\tMD:Z:"; const FixedBitset<1024> *mms = &h.mms; const String* pat = &h.patSeq; const vector* refcs = &h.refcs; if(h.color && false) { // Disabled: print MD:Z string w/r/t to colors, not letters mms = &h.cmms; pat = &h.colSeq; assert_eq(length(h.colSeq), len+1); len = length(h.colSeq); refcs = &h.crefcs; } if(h.fw) { for (int i = 0; i < (int)len; ++ i) { if(mms->test(i)) { nm++; // There's a mismatch at this position assert_gt((int)refcs->size(), i); char refChar = toupper((*refcs)[i]); ASSERT_ONLY(char qryChar = (h.fw ? (*pat)[i] : (*pat)[len-i-1])); assert_neq(refChar, qryChar); ss << run << refChar; run = 0; } else { run++; } } } else { for (int i = len-1; i >= 0; -- i) { if(mms->test(i)) { nm++; // There's a mismatch at this position assert_gt((int)refcs->size(), i); char refChar = toupper((*refcs)[i]); ASSERT_ONLY(char qryChar = (h.fw ? (*pat)[i] : (*pat)[len-i-1])); assert_neq(refChar, qryChar); ss << run << refChar; run = 0; } else { run++; } } } ss << run; // Add optional edit distance field ss << "\tNM:i:" << nm; if(h.color) ss << "\tCM:i:" << h.cmms.count(); if(xms > 0) ss << "\tXM:i:" << xms; ss << endl; } /** * Report a verbose, human-readable alignment to the appropriate * output stream. */ void SAMHitSink::reportHit(const Hit& h, int mapq, int xms) { if(xms == 0) { // Otherwise, this is actually a sampled read and belongs in // the same category as maxed reads HitSink::reportHit(h); } ostringstream ss; append(ss, h, mapq, xms); // Make sure to grab lock before writing to output stream lock(h.h.first); out(h.h.first).writeString(ss.str()); unlock(h.h.first); } /** * Report a batch of hits from a vector, perhaps subsetting it. */ void SAMHitSink::reportHits(vector& hs, size_t start, size_t end, int mapq, int xms) { assert_geq(end, start); if(end-start == 0) return; assert_gt(hs[start].mate, 0); char buf[4096]; lock(0); for(size_t i = start; i < end; i++) { #ifndef _MSC_VER ostringstream ss(ssmode_); ss.rdbuf()->pubsetbuf(buf, 4096); #else ostrstream ss(buf, 4096); #endif append(ss, hs[i], mapq, xms); out(0).writeChars(buf, ss.tellp()); } unlock(0); mainlock(); commitHits(hs); first_ = false; numAligned_++; numReportedPaired_ += (end-start); mainunlock(); } /** * Report either an unaligned read or a read that exceeded the -m * ceiling. We output placeholders for most of the fields in this * case. */ void SAMHitSink::reportUnOrMax(PatternSourcePerThread& p, vector* hs, bool un) // lower bound on number of other hits { if(un) HitSink::reportUnaligned(p); else HitSink::reportMaxed(*hs, p); ostringstream ss; bool paired = !p.bufb().empty(); assert(paired || p.bufa().mate == 0); assert(!paired || p.bufa().mate > 0); assert(un || hs->size() > 0); assert(!un || hs == NULL || hs->size() == 0); size_t hssz = 0; if(hs != NULL) hssz = hs->size(); if(paired) { // truncate final 2 chars for(int i = 0; i < (int)seqan::length(p.bufa().name)-2; i++) { ss << p.bufa().name[i]; } } else { ss << p.bufa().name; } ss << "\t" << (SAM_FLAG_UNMAPPED | (paired ? (SAM_FLAG_PAIRED | SAM_FLAG_FIRST_IN_PAIR | SAM_FLAG_MATE_UNMAPPED) : 0)) << "\t*" << "\t0\t0\t*\t*\t0\t0\t" << p.bufa().patFw << "\t" << p.bufa().qual << "\tXM:i:" << (paired ? (hssz+1)/2 : hssz) << endl; if(paired) { // truncate final 2 chars for(int i = 0; i < (int)seqan::length(p.bufb().name)-2; i++) { ss << p.bufb().name[i]; } ss << "\t" << (SAM_FLAG_UNMAPPED | (paired ? (SAM_FLAG_PAIRED | SAM_FLAG_SECOND_IN_PAIR | SAM_FLAG_MATE_UNMAPPED) : 0)) << "\t*" << "\t0\t0\t*\t*\t0\t0\t" << p.bufb().patFw << "\t" << p.bufb().qual << "\tXM:i:" << (hssz+1)/2 << endl; } lock(0); out(0).writeString(ss.str()); unlock(0); } /** * Append a SAM alignment to the given output stream. */ void SAMHitSink::append(ostream& ss, const Hit& h, int mapq, int xms, const vector* refnames, ReferenceMap *rmap, AnnotationMap *amap, bool fullRef, int offBase) { appendAligned(ss, h, mapq, xms, refnames, rmap, amap, fullRef, offBase); } /** * Report maxed-out read; if sampleMax_ is set, then report 1 alignment * at random. */ void SAMHitSink::reportMaxed(vector& hs, PatternSourcePerThread& p) { if(sampleMax_) { HitSink::reportMaxed(hs, p); RandomSource rand; rand.init(p.bufa().seed); assert_gt(hs.size(), 0); bool paired = hs.front().mate > 0; size_t num = 1; if(paired) { num = 0; int bestStratum = 999; for(size_t i = 0; i < hs.size()-1; i += 2) { int strat = min(hs[i].stratum, hs[i+1].stratum); if(strat < bestStratum) { bestStratum = strat; num = 1; } else if(strat == bestStratum) { num++; } } assert_leq(num, hs.size()); uint32_t r = rand.nextU32() % num; num = 0; for(size_t i = 0; i < hs.size()-1; i += 2) { int strat = min(hs[i].stratum, hs[i+1].stratum); if(strat == bestStratum) { if(num == r) { reportHits(hs, i, i+2, 0, hs.size()/2+1); break; } num++; } } assert_eq(num, r); } else { for(size_t i = 1; i < hs.size(); i++) { assert_geq(hs[i].stratum, hs[i-1].stratum); if(hs[i].stratum == hs[i-1].stratum) num++; else break; } assert_leq(num, hs.size()); uint32_t r = rand.nextU32() % num; reportHit(hs[r], /*MAPQ*/0, /*XM:I*/hs.size()+1); } } else { reportUnOrMax(p, &hs, false); } } ugene-1.9.8/src/plugins_3rdparty/bowtie/src/bowtie/word_io.h0000644000175000017500000000567711651544326022624 0ustar ilyailya#ifndef WORD_IO_H_ #define WORD_IO_H_ #include #include #include #include "assert_helpers.h" #include "endian_swap.h" /** * Write a 32-bit unsigned to an output stream being careful to * re-endianize if caller-requested endianness differs from current * host. */ static inline void writeU32(std::ostream& out, uint32_t x, bool toBigEndian) { uint32_t y = endianizeU32(x, toBigEndian); out.write((const char*)&y, 4); } /** * Write a 32-bit unsigned to an output stream using the native * endianness. */ static inline void writeU32(std::ostream& out, uint32_t x) { out.write((const char*)&x, 4); } /** * Write a 32-bit signed int to an output stream being careful to * re-endianize if caller-requested endianness differs from current * host. */ static inline void writeI32(std::ostream& out, int32_t x, bool toBigEndian) { int32_t y = endianizeI32(x, toBigEndian); out.write((const char*)&y, 4); } /** * Write a 32-bit unsigned to an output stream using the native * endianness. */ static inline void writeI32(std::ostream& out, int32_t x) { out.write((const char*)&x, 4); } /** * Read a 32-bit unsigned from an input stream, inverting endianness * if necessary. */ static inline uint32_t readU32(std::istream& in, bool swap) { uint32_t x; in.read((char *)&x, 4); assert_eq(4, in.gcount()); if(swap) { return endianSwapU32(x); } else { return x; } } /** * Read a 32-bit unsigned from a file descriptor, optionally inverting * endianness. */ static inline uint32_t readU32(int in, bool swap) { uint32_t x; #ifdef _MSC_VER if(read((std::FILE*)in, (void *)&x, 4) != 4) { #else if(read(in, (void *)&x, 4) != 4) { #endif assert(false); } if(swap) { return endianSwapU32(x); } else { return x; } } /** * Read a 32-bit unsigned from a FILE*, optionally inverting * endianness. */ static inline uint32_t readU32(FILE* in, bool swap) { uint32_t x; if(fread((void *)&x, 1, 4, in) != 4) { assert(false); } if(swap) { return endianSwapU32(x); } else { return x; } } /** * Read a 32-bit signed from an input stream, inverting endianness * if necessary. */ static inline int32_t readI32(std::istream& in, bool swap) { int32_t x; in.read((char *)&x, 4); assert_eq(4, in.gcount()); if(swap) { return endianSwapI32(x); } else { return x; } } /** * Read a 32-bit unsigned from a file descriptor, optionally inverting * endianness. */ static inline uint32_t readI32(int in, bool swap) { int32_t x; #ifdef _MSC_VER if(read((std::FILE*)in, (void *)&x, 4) != 4) { #else if(read(in, (void *)&x, 4) != 4) { #endif assert(false); } if(swap) { return endianSwapI32(x); } else { return x; } } /** * Read a 32-bit unsigned from a FILE*, optionally inverting * endianness. */ static inline uint32_t readI32(FILE* in, bool swap) { int32_t x; if(fread((void *)&x, 1, 4, in) != 4) { assert(false); } if(swap) { return endianSwapI32(x); } else { return x; } } #endif /*WORD_IO_H_*/ ugene-1.9.8/src/plugins_3rdparty/bowtie/src/bowtie/blockwise_sa.h0000644000175000017500000007461311651544326023623 0ustar ilyailya#ifndef BLOCKWISE_SA_H_ #define BLOCKWISE_SA_H_ #include #include #include #include #include #include #include #include #include "assert_helpers.h" #include "diff_sample.h" #include "multikey_qsort.h" #include "random_source.h" #include "binary_sa_search.h" #include "zbox.h" #include "alphabet.h" #include "timer.h" #include "auto_array.h" #include "BowtieContext.h" using namespace std; using namespace seqan; // Helpers for printing verbose messages #ifdef _MSC_VER #ifndef VMSG_NL #define VMSG_NL(args, ...) \ if(this->verbose()) { \ stringstream tmp; \ tmp << args << endl; \ BowtieContext::verbose(tmp.str()); \ } #endif #ifndef VMSG #define VMSG(args, ...) \ if(this->verbose()) { \ stringstream tmp; \ tmp << args; \ BowtieContext::verbose(tmp.str()); \ } #endif #else #ifndef VMSG_NL #define VMSG_NL(args...) \ if(this->verbose()) { \ stringstream tmp; \ tmp << args << endl; \ BowtieContext::verbose(tmp.str()); \ } #endif #ifndef VMSG #define VMSG(args...) \ if(this->verbose()) { \ stringstream tmp; \ tmp << args; \ BowtieContext::verbose(tmp.str()); \ } #endif #endif /** * Abstract parent class for blockwise suffix-array building schemes. */ template class BlockwiseSA { public: BlockwiseSA(const TStr& __text, uint32_t __bucketSz, bool __sanityCheck = false, bool __passMemExc = false, bool __verbose = false, ostream& __logger = cout) : _text(__text), _bucketSz(max(__bucketSz, 2u)), _sanityCheck(__sanityCheck), _passMemExc(__passMemExc), _verbose(__verbose), _itrBucket(), _itrBucketPos(0xffffffff), _itrPushedBackSuffix(0xffffffff), _logger(__logger) { } virtual ~BlockwiseSA() { } /** * Get the next suffix; compute the next bucket if necessary. */ uint32_t nextSuffix() { if(_itrPushedBackSuffix != 0xffffffff) { uint32_t tmp = _itrPushedBackSuffix; _itrPushedBackSuffix = 0xffffffff; return tmp; } while(_itrBucketPos >= length(_itrBucket) || length(_itrBucket) == 0) { if(!hasMoreBlocks()) { throw out_of_range("No more suffixes"); } nextBlock(); _itrBucketPos = 0; } return _itrBucket[_itrBucketPos++]; } /** * Return true iff the next call to nextSuffix will succeed. */ bool hasMoreSuffixes() { if(_itrPushedBackSuffix != 0xffffffff) return true; try { _itrPushedBackSuffix = nextSuffix(); } catch(out_of_range& e) { assert_eq(0xffffffff, _itrPushedBackSuffix); return false; } return true; } /** * Reset the suffix iterator so that the next call to nextSuffix() * returns the lexicographically-first suffix. */ void resetSuffixItr() { clear(_itrBucket); _itrBucketPos = 0xffffffff; _itrPushedBackSuffix = 0xffffffff; reset(); assert(suffixItrIsReset()); } /** * Returns true iff the next call to nextSuffix() returns the * lexicographically-first suffix. */ bool suffixItrIsReset() { return length(_itrBucket) == 0 && _itrBucketPos == 0xffffffff && _itrPushedBackSuffix == 0xffffffff && isReset(); } const TStr& text() const { return _text; } uint32_t bucketSz() const { return _bucketSz; } bool sanityCheck() const { return _sanityCheck; } bool verbose() const { return _verbose; } ostream& log() const { return _logger; } uint32_t size() const { return length(_text)+1; } protected: /// Reset back to the first block virtual void reset() = 0; /// Return true iff reset to the first block virtual bool isReset() = 0; /** * Grab the next block of sorted suffixes. The block is guaranteed * to have at most _bucketSz elements. */ virtual void nextBlock() = 0; /// Return true iff more blocks are available virtual bool hasMoreBlocks() const = 0; /// Optionally output a verbose message void verbose(const string& s) const { if(this->verbose()) { this->log() << s; this->log().flush(); } } const TStr& _text; /// original string const uint32_t _bucketSz; /// target maximum bucket size const bool _sanityCheck; /// whether to perform sanity checks const bool _passMemExc; /// true -> pass on memory exceptions const bool _verbose; /// be talkative String _itrBucket; /// current bucket uint32_t _itrBucketPos;/// offset into current bucket uint32_t _itrPushedBackSuffix; /// temporary slot for lookahead ostream& _logger; /// write log messages here }; /** * Abstract parent class for a blockwise suffix array builder that * always doles out blocks in lexicographical order. */ template class InorderBlockwiseSA : public BlockwiseSA { public: InorderBlockwiseSA(const TStr& __text, uint32_t __bucketSz, bool __sanityCheck = false, bool __passMemExc = false, bool __verbose = false, ostream& __logger = cout) : BlockwiseSA(__text, __bucketSz, __sanityCheck, __passMemExc, __verbose, __logger) { } }; /** * Build the SA a block at a time according to the scheme outlined in * Karkkainen's "Fast BWT" paper. */ template class KarkkainenBlockwiseSA : public InorderBlockwiseSA { public: typedef DifferenceCoverSample TDC; KarkkainenBlockwiseSA(const TStr& __text, uint32_t __bucketSz, uint32_t __dcV, uint32_t __seed = 0, bool __sanityCheck = false, bool __passMemExc = false, bool __verbose = false, ostream& __logger = cout) : InorderBlockwiseSA(__text, __bucketSz, __sanityCheck, __passMemExc, __verbose, __logger), _sampleSuffs(), _cur(0), _dcV(__dcV), _dc(NULL), _built(false) { _randomSrc.init(__seed); reset(); } ~KarkkainenBlockwiseSA() { if(_dc != NULL) delete _dc; _dc = NULL; // difference cover sample } /** * Allocate an amount of memory that simulates the peak memory * usage of the DifferenceCoverSample with the given text and v. * Throws bad_alloc if it's not going to fit in memory. Returns * the approximate number of bytes the Cover takes at all times. */ static size_t simulateAllocs(const TStr& text, uint32_t bucketSz) { size_t len = length(text); // _sampleSuffs and _itrBucket are in memory at the peak size_t bsz = bucketSz; size_t sssz = len / max(bucketSz-1, 1); AutoArray tmp(bsz + sssz + (1024 * 1024 /*out of caution*/)); return bsz; } /// Defined in blockwise_sa.cpp virtual void nextBlock(); /// Defined in blockwise_sa.cpp virtual void qsort(String& bucket); /// Return true iff more blocks are available virtual bool hasMoreBlocks() const { return _cur <= length(_sampleSuffs); } /// Return the difference-cover period uint32_t dcV() const { return _dcV; } protected: /** * Initialize the state of the blockwise suffix sort. If the * difference cover sample and the sample set have not yet been * built, build them. Then reset the block cursor to point to * the first block. */ virtual void reset() { if(!_built) { build(); } assert(_built); _cur = 0; } /// Return true iff we're about to dole out the first bucket virtual bool isReset() { return _cur == 0; } private: /** * Calculate the difference-cover sample and sample suffixes. */ void build() { // Calculate difference-cover sample assert(_dc == NULL); if(_dcV != 0) { _dc = new TDC(this->text(), _dcV, this->verbose(), this->sanityCheck()); _dc->build(); } // Calculate sample suffixes if(this->bucketSz() <= length(this->text())) { VMSG_NL("Building samples"); buildSamples(); } else { VMSG_NL("Skipping building samples since text length " << length(this->text()) << " is less than bucket size: " << this->bucketSz()); } _built = true; } /** * Calculate the lcp between two suffixes using the difference * cover as a tie-breaker. If the tie-breaker is employed, then * the calculated lcp may be an underestimate. * * Defined in blockwise_sa.cpp */ inline bool tieBreakingLcp(uint32_t aOff, uint32_t bOff, uint32_t& lcp, bool& lcpIsSoft); /** * Compare two suffixes using the difference-cover sample. */ inline bool suffixCmp(uint32_t cmp, uint32_t i, int64_t& j, int64_t& k, bool& kSoft, const String& z); void buildSamples(); String _sampleSuffs; /// sample suffixes uint32_t _cur; /// offset to 1st elt of next block const uint32_t _dcV; /// difference-cover periodicity TDC* _dc; /// queryable difference-cover data bool _built; /// whether samples/DC have been built RandomSource _randomSrc; /// source of pseudo-randoms }; /** * Qsort the set of suffixes whose offsets are in 'bucket'. */ template void KarkkainenBlockwiseSA::qsort(String& bucket) { typedef typename Value::Type TAlphabet; const TStr& t = this->text(); uint32_t *s = begin(bucket); uint32_t slen = seqan::length(bucket); uint32_t len = seqan::length(t); if(_dc != NULL) { // Use the difference cover as a tie-breaker if we have it VMSG_NL(" (Using difference cover)"); // Extract the 'host' array because it's faster to work // with than the String<> container uint8_t *host = (uint8_t*)t.data_begin; mkeyQSortSufDcU8(t, host, len, s, slen, *_dc, ValueSize::VALUE, this->verbose(), this->sanityCheck()); } else { VMSG_NL(" (Not using difference cover)"); // We don't have a difference cover - just do a normal // suffix sort mkeyQSortSuf(t, s, slen, ValueSize::VALUE, this->verbose(), this->sanityCheck()); } } /** * Qsort the set of suffixes whose offsets are in 'bucket'. This * specialization for packed strings does not attempt to extract and * operate directly on the host string; the fact that the string is * packed means that the array cannot be sorted directly. */ #ifdef _MSC_VER extern template #else template<> #endif void KarkkainenBlockwiseSA > >::qsort(String& bucket); /*{ const String >& t = this->text(); uint32_t *s = begin(bucket); uint32_t slen = seqan::length(bucket); uint32_t len = seqan::length(t); if(_dc != NULL) { // Use the difference cover as a tie-breaker if we have it VMSG_NL(" (Using difference cover)"); // Can't use the text's 'host' array because the backing // store for the packed string is not one-char-per-elt. mkeyQSortSufDcU8(t, t, len, s, slen, *_dc, ValueSize::VALUE, this->verbose(), this->sanityCheck()); } else { VMSG_NL(" (Not using difference cover)"); // We don't have a difference cover - just do a normal // suffix sort mkeyQSortSuf(t, s, slen, ValueSize::VALUE, this->verbose(), this->sanityCheck()); } }*/ /** * Select a set of bucket-delineating sample suffixes such that no * bucket is greater than the requested upper limit. Some care is * taken to make each bucket's size close to the limit without * going over. */ template void KarkkainenBlockwiseSA::buildSamples() { BowtieContext* ctx = BowtieContext::getContext(); typedef typename Value::Type TAlphabet; const TStr& t = this->text(); uint32_t bsz = this->bucketSz()-1; // subtract 1 to leave room for sample uint32_t len = length(this->text()); // Prepare _sampleSuffs array clear(_sampleSuffs); uint32_t numSamples = ((len/bsz)+1)<<1; // ~len/bsz x 2 assert_gt(numSamples, 0); VMSG_NL("Reserving space for " << numSamples << " sample suffixes"); if(this->_passMemExc) { reserve(_sampleSuffs, numSamples, Exact()); // Randomly generate samples. Allow duplicates for now. VMSG_NL("Generating random suffixes"); for(size_t i = 0; i < numSamples; i++) { appendValue(_sampleSuffs, _randomSrc.nextU32() % len); } } else { try { reserve(_sampleSuffs, numSamples, Exact()); // Randomly generate samples. Allow duplicates for now. VMSG_NL("Generating random suffixes"); for(size_t i = 0; i < numSamples; i++) { appendValue(_sampleSuffs, _randomSrc.nextU32() % len); } } catch(bad_alloc &e) { if(this->_passMemExc) { throw e; // rethrow immediately } else { cerr << "Could not allocate sample suffix container of " << (numSamples * 4) << " bytes." << endl << "Please try using a smaller number of blocks by specifying a larger --bmax or" << endl << "a smaller --bmaxdivn" << endl; throw 1; } } } // Remove duplicates; very important to do this before the call to // mkeyQSortSuf so that it doesn't try to calculate lexicographical // relationships between very long, identical strings, which takes // an extremely long time in general, and causes the stack to grow // linearly with the size of the input { Timer timer(cout, "QSorting sample offsets, eliminating duplicates time: ", this->verbose()); VMSG_NL("QSorting " << length(_sampleSuffs) << " sample offsets, eliminating duplicates"); sort(begin(_sampleSuffs), end(_sampleSuffs)); size_t sslen = length(_sampleSuffs); for(size_t i = 0; i < sslen-1; i++) { if(_sampleSuffs[i] == _sampleSuffs[i+1]) { erase(_sampleSuffs, i--); sslen--; } } } // Multikey quicksort the samples { Timer timer(cout, " Multikey QSorting samples time: ", this->verbose()); VMSG_NL("Multikey QSorting " << length(_sampleSuffs) << " samples"); this->qsort(_sampleSuffs); } // Calculate bucket sizes VMSG_NL("Calculating bucket sizes"); int limit = 5; float localProgress = 0 ; // Iterate until all buckets are less than while(--limit >= 0) { // Calculate bucket sizes by doing a binary search for each // suffix and noting where it lands uint32_t numBuckets = length(_sampleSuffs)+1; String bucketSzs; // holds computed bucket sizes String bucketReps; // holds 1 member of each bucket (for splitting) try { // Allocate and initialize containers for holding bucket // sizes and representatives. fill(bucketSzs, numBuckets, 0, Exact()); fill(bucketReps, numBuckets, 0xffffffff, Exact()); } catch(bad_alloc &e) { if(this->_passMemExc) { throw e; // rethrow immediately } else { cerr << "Could not allocate sizes, representatives (" << ((numBuckets*8)>>10) << " KB) for blocks." << endl << "Please try using a smaller number of blocks by specifying a larger --bmax or a" << endl << "smaller --bmaxdivn." << endl; throw 1; } } // Iterate through every suffix in the text, determine which // bucket it falls into by doing a binary search across the // sorted list of samples, and increment a counter associated // with that bucket. Also, keep one representative for each // bucket so that we can split it later. We loop in ten // stretches so that we can print out a helpful progress // message. (This step can take a long time.) { VMSG_NL(" Binary sorting into buckets"); Timer timer(cout, " Binary sorting into buckets time: ", this->verbose()); uint32_t lenDiv10 = (len + 9) / 10; for(uint32_t iten = 0, ten = 0; iten < len; iten += lenDiv10, ten++) { uint32_t itenNext = iten + lenDiv10; if(ten > 0) VMSG_NL(" " << (ten * 10) << "%"); if(ctx->isCanceled()) { clear(_sampleSuffs); throw BowtieException("Canceled"); } localProgress = (4 - limit + ten/10.0) / 5.0; ctx->ti.progress = (ctx->build.secondEbwtRound ? 50.0:0.0) + ((ctx->build.doubleEbwt) ? 0.5:1.0 ) * (10 + 30 * localProgress); ctx->ti.setDescription(QString("Binary sorting into buckets: %1%").arg(ten*10)); for(uint32_t i = iten; i < itenNext && i < len; i++) { uint32_t r = binarySASearch(t, i, _sampleSuffs); if(r == 0xffffffff) continue; // r was one of the samples assert_lt(r, numBuckets); bucketSzs[r]++; assert_lt(bucketSzs[r], len); if(bucketReps[r] == 0xffffffff || (_randomSrc.nextU32() & 100) == 0) { bucketReps[r] = i; // clobbers previous one, but that's OK } } } ctx->ti.setDescription(QString("Binary sorting into buckets: 100%")); VMSG_NL(" 100%"); } // Check for large buckets and mergeable pairs of small buckets // and split/merge as necessary int added = 0; int merged = 0; assert_eq(length(bucketSzs), numBuckets); assert_eq(length(bucketReps), numBuckets); { Timer timer(cout, " Splitting and merging time: ", this->verbose()); VMSG_NL("Splitting and merging"); ctx->ti.setDescription(QString("Splitting and merging")); for(int64_t i = 0; i < numBuckets; i++) { uint32_t mergedSz = bsz + 1; assert(bucketSzs[i] == 0 || bucketReps[i] != 0xffffffff); if(i < (int64_t)numBuckets-1) { mergedSz = bucketSzs[i] + bucketSzs[i+1] + 1; } // Merge? if(mergedSz <= bsz) { bucketSzs[i+1] += (bucketSzs[i]+1); // The following may look strange, but it's necessary // to ensure that the merged bucket has a representative bucketReps[i+1] = _sampleSuffs[i+added]; erase(_sampleSuffs, i+added); erase(bucketSzs, i); erase(bucketReps, i); i--; // might go to -1 but ++ will overflow back to 0 numBuckets--; merged++; assert_eq(numBuckets, length(_sampleSuffs)+1-added); assert_eq(numBuckets, length(bucketSzs)); } // Split? else if(bucketSzs[i] > bsz) { // Add an additional sample from the bucketReps[] // set accumulated in the binarySASearch loop; this // effectively splits the bucket insertValue(_sampleSuffs, i + (added++), bucketReps[i]); } } } if(added == 0) { //if(this->verbose()) { // cout << "Final bucket sizes:" << endl; // cout << " (begin): " << bucketSzs[0] << " (" << (int)(bsz - bucketSzs[0]) << ")" << endl; // for(uint32_t i = 1; i < numBuckets; i++) { // cout << " " << bucketSzs[i] << " (" << (int)(bsz - bucketSzs[i]) << ")" << endl; // } //} break; } // Otherwise, continue until no more buckets need to be // split ctx->ti.setDescription(QString("Split %1, merged %2; iterating...").arg(added).arg(merged)); VMSG_NL("Split " << added << ", merged " << merged << "; iterating..."); } ctx->ti.progress = (ctx->build.secondEbwtRound ? 50.0:0.0) + ( ctx->build.doubleEbwt ? 0.5:1.0 ) * 30; // Do *not* force a do-over // if(limit == 0) { // VMSG_NL("Iterated too many times; trying again..."); // buildSamples(); // } VMSG_NL("Avg bucket size: " << ((float)(len-length(_sampleSuffs)) / (length(_sampleSuffs)+1)) << " (target: " << bsz << ")"); } /** * Do a simple LCP calculation on two strings. */ template inline static uint32_t suffixLcp(const T& t, uint32_t aOff, uint32_t bOff) { uint32_t c = 0; size_t len = length(t); assert_leq(aOff, len); assert_leq(bOff, len); while(aOff + c < len && bOff + c < len && t[aOff + c] == t[bOff + c]) c++; return c; } /** * Calculate the lcp between two suffixes using the difference * cover as a tie-breaker. If the tie-breaker is employed, then * the calculated lcp may be an underestimate. If the tie-breaker is * employed, lcpIsSoft will be set to true (otherwise, false). */ template inline bool KarkkainenBlockwiseSA::tieBreakingLcp(uint32_t aOff, uint32_t bOff, uint32_t& lcp, bool& lcpIsSoft) { const TStr& t = this->text(); uint32_t c = 0; uint32_t tlen = length(t); assert_leq(aOff, tlen); assert_leq(bOff, tlen); assert(_dc != NULL); uint32_t dcDist = _dc->tieBreakOff(aOff, bOff); lcpIsSoft = false; // hard until proven soft while(c < dcDist && // we haven't hit the tie breaker c < tlen-aOff && // we haven't fallen off of LHS suffix c < tlen-bOff && // we haven't fallen off of RHS suffix t[aOff+c] == t[bOff+c]) // we haven't hit a mismatch c++; lcp = c; if(c == tlen-aOff) { // Fell off LHS (a), a is greater return false; } else if(c == tlen-bOff) { // Fell off RHS (b), b is greater return true; } else if(c == dcDist) { // Hit a tie-breaker element lcpIsSoft = true; assert_neq(dcDist, 0xffffffff); return _dc->breakTie(aOff+c, bOff+c) < 0; } else { assert_neq(t[aOff+c], t[bOff+c]); return t[aOff+c] < t[bOff+c]; } } /** * Lookup a suffix LCP in the given z array; if the element is not * filled in then calculate it from scratch. */ template static uint32_t lookupSuffixZ(const T& t, uint32_t zOff, uint32_t off, const String& z) { if(zOff < length(z)) { uint32_t ret = z[zOff]; assert_eq(ret, suffixLcp(t, off + zOff, off)); return ret; } assert_leq(off + zOff, length(t)); return suffixLcp(t, off + zOff, off); } /** * true -> i < cmp * false -> i > cmp */ template inline bool KarkkainenBlockwiseSA::suffixCmp(uint32_t cmp, uint32_t i, int64_t& j, int64_t& k, bool& kSoft, const String& z) { const TStr& t = this->text(); uint32_t len = length(t); // i is not covered by any previous match uint32_t l; if(i > k) { k = i; // so that i + lHi == kHi l = 0; // erase any previous l kSoft = false; // To be extended } // i is covered by a previous match else /* i <= k */ { assert_gt((int64_t)i, j); uint32_t zIdx = i-j; assert_leq(zIdx, len-cmp); if(zIdx < _dcV || _dc == NULL) { // Go as far as the Z-box says l = lookupSuffixZ(t, zIdx, cmp, z); if(i + l > len) { l = len-i; } assert_leq(i + l, len); // Possibly to be extended } else { // But we're past the point of no-more-Z-boxes bool ret = tieBreakingLcp(i, cmp, l, kSoft); // Sanity-check tie-breaker if(this->sanityCheck()) { if(ret) assert(dollarLt(suffix(t, i), suffix(t, cmp))); else assert(dollarGt(suffix(t, i), suffix(t, cmp))); } j = i; k = i + l; if(this->sanityCheck()) { if(kSoft) { assert_leq(l, suffixLcp(t, i, cmp)); } else { assert_eq (l, suffixLcp(t, i, cmp)); } } return ret; } } // Z box extends exactly as far as previous match (or there // is neither a Z box nor a previous match) if(i + l == k) { // Extend while(l < len-cmp && k < len && t[cmp+l] == t[k]) { k++; l++; } j = i; // update furthest-extending LHS kSoft = false; assert_eq(l, suffixLcp(t, i, cmp)); } // Z box extends further than previous match else if(i + l > k) { l = k - i; // point to just after previous match j = i; // update furthest-extending LHS if(kSoft) { while(l < len-cmp && k < len && t[cmp+l] == t[k]) { k++; l++; } kSoft = false; assert_eq(l, suffixLcp(t, i, cmp)); } else assert_eq(l, suffixLcp(t, i, cmp)); } // Check that calculated lcp matches actual lcp if(this->sanityCheck()) { if(!kSoft) { // l should exactly match lcp assert_eq(l, suffixLcp(t, i, cmp)); } else { // l is an underestimate of LCP assert_leq(l, suffixLcp(t, i, cmp)); } } assert_leq(l+i, len); assert_leq(l, len-cmp); // i and cmp should not be the same suffix assert(l != len-cmp || i+l != len); // Now we're ready to do a comparison on the next char if(l+i != len && ( l == len-cmp || // departure from paper algorithm: // falling off pattern implies // pattern is *greater* in our case t[i + l] < t[cmp + l])) { // Case 2: Text suffix is less than upper sample suffix if(this->sanityCheck()) assert(dollarLt(suffix(t, i), suffix(t, cmp))); return true; // suffix at i is less than suffix at cmp } else { // Case 3: Text suffix is greater than upper sample suffix if(this->sanityCheck()) assert(dollarGt(suffix(t, i), suffix(t, cmp))); return false; // suffix at i is less than suffix at cmp } } /** * Retrieve the next block. This is the most performance-critical part * of the blockwise suffix sorting process. */ template void KarkkainenBlockwiseSA::nextBlock() { typedef typename Value::Type TAlphabet; String& bucket = this->_itrBucket; BowtieContext* ctx = BowtieContext::getContext(); ctx->ti.setDescription(QString("Getting block %1 of %2").arg(_cur+1).arg(length(_sampleSuffs)+1)); VMSG_NL("Getting block " << (_cur+1) << " of " << length(_sampleSuffs)+1); assert(_built); assert_gt(_dcV, 3); assert_leq(_cur, length(_sampleSuffs)); const TStr& t = this->text(); uint32_t len = length(t); // Set up the bucket clear(bucket); uint32_t lo = 0xffffffff, hi = 0xffffffff; if(length(_sampleSuffs) == 0) { // Special case: if _sampleSuffs is 0, then multikey-quicksort // everything VMSG_NL(" No samples; assembling all-inclusive block"); assert_eq(0, _cur); try { if(capacity(bucket) < this->bucketSz()) { reserve(bucket, len+1, Exact()); } for(uint32_t i = 0; i < len; i++) append(bucket, i); } catch(bad_alloc &e) { if(this->_passMemExc) { throw e; // rethrow immediately } else { cerr << "Could not allocate a master suffix-array block of " << ((len+1) * 4) << " bytes" << endl << "Please try using a larger number of blocks by specifying a smaller --bmax or" << endl << "a larger --bmaxdivn" << endl; throw 1; } } } else { try { VMSG_NL(" Reserving size (" << this->bucketSz() << ") for bucket"); // BTL: Add a +100 fudge factor; there seem to be instances // where a bucket ends up having one more elt than bucketSz() if(capacity(bucket) < this->bucketSz()+100) { reserve(bucket, this->bucketSz()+100, Exact()); } } catch(bad_alloc &e) { if(this->_passMemExc) { throw e; // rethrow immediately } else { ostringstream err; err << "Could not allocate a suffix-array block of " << ((this->bucketSz()+1) * 4) << " bytes" << endl; err << "Please try using a larger number of blocks by specifying a smaller --bmax or" << endl << "a larger --bmaxdivn" << endl; throw BowtieException(err.str()); } } // Select upper and lower bounds from _sampleSuffs[] and // calculate the Z array up to the difference-cover periodicity // for both. Be careful about first/last buckets. String zLo, zHi; assert_geq(_cur, 0); assert_leq(_cur, length(_sampleSuffs)); bool first = (_cur == 0); bool last = (_cur == length(_sampleSuffs)); try { Timer timer(cout, " Calculating Z arrays time: ", this->verbose()); VMSG_NL(" Calculating Z arrays"); if(!last) { // Not the last bucket assert_lt(_cur, length(_sampleSuffs)); hi = _sampleSuffs[_cur]; fill(zHi, _dcV, 0, Exact()); assert_eq(zHi[0], 0); calcZ(t, hi, zHi, this->verbose(), this->sanityCheck()); } if(!first) { // Not the first bucket assert_gt(_cur, 0); assert_leq(_cur, length(_sampleSuffs)); lo = _sampleSuffs[_cur-1]; fill(zLo, _dcV, 0, Exact()); assert_gt(_dcV, 3); assert_eq(zLo[0], 0); calcZ(t, lo, zLo, this->verbose(), this->sanityCheck()); } } catch(bad_alloc &e) { if(this->_passMemExc) { throw e; // rethrow immediately } else { ostringstream err; err << "Could not allocate a z-array of " << (_dcV * 4) << " bytes" << endl; err << "Please try using a larger number of blocks by specifying a smaller --bmax or" << endl << "a larger --bmaxdivn" << endl; throw BowtieException(err.str()); } } // This is the most critical loop in the algorithm; this is where // we iterate over all suffixes in the text and pick out those that // fall into the current bucket. // // This loop is based on the SMALLERSUFFIXES function outlined on // p7 of the "Fast BWT" paper // int64_t kHi = -1, kLo = -1; int64_t jHi = -1, jLo = -1; bool kHiSoft = false, kLoSoft = false; assert_eq(0, length(bucket)); { Timer timer(cout, " Block accumulator loop time: ", this->verbose()); VMSG_NL(" Entering block accumulator loop:"); uint32_t lenDiv10 = (len + 9) / 10; for(uint32_t iten = 0, ten = 0; iten < len; iten += lenDiv10, ten++) { uint32_t itenNext = iten + lenDiv10; float localProgress = (_cur + ten/10.0) / ((float)length(_sampleSuffs)+1) ; ctx->ti.progress = (ctx->build.secondEbwtRound ? 50.0:0.0) + (ctx->build.doubleEbwt ? 0.5 : 1.0) * (40.0 + 60.0 * localProgress); if(ctx->isCanceled()) { throw BowtieException("Canceled"); } if(ten > 0) VMSG_NL(" " << (ten * 10) << "%"); for(uint32_t i = iten; i < itenNext && i < len; i++) { assert_lt(jLo, i); assert_lt(jHi, i); // Advance the upper-bound comparison by one character if(i == hi || i == lo) continue; // equal to one of the bookends if(hi != 0xffffffff && !suffixCmp(hi, i, jHi, kHi, kHiSoft, zHi)) { continue; // not in the bucket } if(lo != 0xffffffff && suffixCmp(lo, i, jLo, kLo, kLoSoft, zLo)) { continue; // not in the bucket } // In the bucket! - add it assert_lt(i, len); try { appendValue(bucket, i); } catch(bad_alloc &e) { if(this->_passMemExc) { throw e; // rethrow immediately } else { ostringstream err; err << "Could not append element to block of " << ((length(bucket)) * 4) << " bytes" << endl; err << "Please try using a larger number of blocks by specifying a smaller --bmax or" << endl << "a larger --bmaxdivn" << endl; throw BowtieException(err.str()); } } // Not necessarily true; we allow overflowing buckets // since we can't guarantee that a good set of sample // suffixes can be found in a reasonable amount of time //assert_lt(length(bucket), this->bucketSz()); } } // end loop over all suffixes of t VMSG_NL(" 100%"); } } // end else clause of if(length(_sampleSuffs) == 0) // Sort the bucket if(length(bucket) > 0) { Timer timer(cout, " Sorting block time: ", this->verbose()); VMSG_NL(" Sorting block of length " << length(bucket)); this->qsort(bucket); } if(hi != 0xffffffff) { // Not the final bucket; throw in the sample on the RHS appendValue(bucket, hi); } else { // Final bucket; throw in $ suffix appendValue(bucket, len); } VMSG_NL("Returning block of " << length(bucket)); _cur++; // advance to next bucket } #endif /*BLOCKWISE_SA_H_*/ ugene-1.9.8/src/plugins_3rdparty/bowtie/src/bowtie/row_chaser.h0000644000175000017500000001104711651544326023302 0ustar ilyailya/* * row_chaser.h */ #ifndef ROW_CHASER_H_ #define ROW_CHASER_H_ #include #include "seqan/sequence.h" #include "ebwt.h" #include "aligner_metrics.h" /** * A class that statefully converts a row index to a reference * location. There is a large memory-latency penalty usually * associated with calling the Ebwt object's mapLF method, which this * object does repeatedly in order to resolve the reference offset. * The "statefulness" in how the computation is organized here allows * some or all of that penalty to be hidden using prefetching. */ template class RowChaser { typedef std::pair U32Pair; typedef Ebwt TEbwt; public: RowChaser(AlignerMetrics *metrics = NULL) : done(false), prepped_(false), ebwt_(NULL), qlen_(0), eh_(NULL), row_(0xffffffff), jumps_(0), sideloc_(), off_(0xffffffff), tlen_(0), metrics_(metrics) { } /** * Convert a row to a joined reference offset. This has to be * converted to understand where it is w/r/t the reference hit and * offset within it. */ static uint32_t toFlatRefOff(const TEbwt* ebwt, uint32_t qlen, uint32_t row) { RowChaser rc; rc.setRow(row, qlen, ebwt); while(!rc.done) { rc.advance(); } return rc.flatOff(); } /** * Convert a row to a reference offset. */ static U32Pair toRefOff(const TEbwt* ebwt, uint32_t qlen, uint32_t row) { RowChaser rc; rc.setRow(row, qlen, ebwt); while(!rc.done) { rc.advance(); } return rc.off(); } /** * Set the next row for us to "chase" (i.e. map to a reference * location using the BWT step-left operation). */ void setRow(uint32_t row, uint32_t qlen, const TEbwt* ebwt) { assert_neq(0xffffffff, row); assert_gt(qlen, 0); assert(ebwt != NULL); ebwt_ = ebwt; eh_ = &ebwt->_eh; row_ = row; qlen_ = qlen; ASSERT_ONLY(sideloc_.invalidate()); if(row_ == ebwt_->_zOff) { // We arrived at the extreme left-hand end of the reference off_ = 0; done = true; return; } else if((row_ & eh_->_offMask) == row_) { // We arrived at a marked row off_ = ebwt_->_offs[row_ >> eh_->_offRate]; done = true; return; } done = false; jumps_ = 0; off_ = 0xffffffff; prepped_ = false; prep(); } /** * Advance the step-left process by one step. Check if we're done. */ void advance() { // Advance by 1 assert(!done); while(!done) { assert(prepped_); prepped_ = false; if(metrics_ != NULL) metrics_->curBwtOps_++; uint32_t newrow = ebwt_->mapLF(sideloc_); ASSERT_ONLY(sideloc_.invalidate()); jumps_++; assert_neq(newrow, row_); // Update row_ field row_ = newrow; if(row_ == ebwt_->_zOff) { // We arrived at the extreme left-hand end of the reference off_ = jumps_; done = true; } else if((row_ & eh_->_offMask) == row_) { // We arrived at a marked row off_ = ebwt_->_offs[row_ >> eh_->_offRate] + jumps_; done = true; } prep(); } } /** * Prepare for the next call to advance() by prefetching the * appropriate portions of the index. The caller should make sure * that the */ void prep() { if(!done) { assert(!prepped_); assert(!sideloc_.valid()); assert_leq(row_, eh_->_len); sideloc_.initFromRow(row_, *eh_, (const uint8_t*)ebwt_->_ebwt); assert(sideloc_.valid()); } prepped_ = true; } /** * Get the calculated offset. This has to be converted with a call * to Ebwt::joinedToTextOff() to understand where it is w/r/t the * reference hit and offset within it. */ uint32_t flatOff() const { return off_; } /** * Get the calculated offset. */ U32Pair off() { uint32_t off = flatOff(); assert_neq(0xffffffff, off); uint32_t tidx; uint32_t textoff = 0xffffffff; ebwt_->joinedToTextOff(qlen_, off, tidx, textoff, tlen_); // Note: tidx may be 0xffffffff, if alignment overlaps a // reference boundary return make_pair(tidx, textoff); } uint32_t tlen() const { return tlen_; } bool done; /// true = chase is done & answer is in off_ bool prepped_; /// true = prefetch is issued and it's OK to call advance() protected: const TEbwt* ebwt_; /// index to resolve row in uint32_t qlen_; /// length of read; needed to convert to ref. coordinates const EbwtParams* eh_; /// eh field from index uint32_t row_; /// current row uint32_t jumps_; /// # steps so far SideLocus sideloc_; /// current side locus uint32_t off_; /// calculated offset (0xffffffff if not done) uint32_t tlen_; /// hit text length AlignerMetrics *metrics_; }; #endif /* ROW_CHASER_H_ */ ugene-1.9.8/src/plugins_3rdparty/bowtie/src/bowtie/random_source.h0000644000175000017500000000212311651544326024001 0ustar ilyailya#ifndef RANDOM_GEN_H_ #define RANDOM_GEN_H_ #include "assert_helpers.h" /** * Simple pseudo-random linear congruential generator, a la Numerical * Recipes. */ class RandomSource { public: static const uint32_t DEFUALT_A = 1664525; static const uint32_t DEFUALT_C = 1013904223; RandomSource() : a(DEFUALT_A), c(DEFUALT_C), inited_(false) { } RandomSource(uint32_t _a, uint32_t _c) : a(_a), c(_c), inited_(false) { } void init(uint32_t seed = 0) { last = seed; inited_ = true; } uint32_t nextU32() { assert(inited_); uint32_t ret; last = a * last + c; ret = last >> 16; last = a * last + c; ret ^= last; lastOff = 0; return ret; } uint32_t nextU2() { assert(inited_); if(lastOff > 30) { nextU32(); } uint32_t ret = (last >> lastOff) & 3; lastOff += 2; return ret; } static uint32_t nextU32(uint32_t last, uint32_t a = DEFUALT_A, uint32_t c = DEFUALT_C) { return (a * last) + c; } private: uint32_t a; uint32_t c; uint32_t last; uint32_t lastOff; bool inited_; }; #endif /*RANDOM_GEN_H_*/ ugene-1.9.8/src/plugins_3rdparty/bowtie/src/bowtie/search_23mm_phase1.c0000644000175000017500000000247411651544326024511 0ustar ilyailya/* * This is a fragment, included from multiple places in ebwt_search.cpp. * It implements the logic of the first phase of the 2/3-mismatch search * routine. It is implemented as a code fragment so that it can be * reused in both the half-index-in-memory and full-index-in-memory * situations. */ { // If requested, check that this read has the same length // as all the previous ones btr1.setReportExacts(true); if(plen < 3 && two) { cerr << "Error: Read (" << name << ") is less than 3 characters long" << endl; throw 1; } else if(plen < 4) { cerr << "Error: Read (" << name << ") is less than 4 characters long" << endl; throw 1; } if(!nofw) { // Do an exact-match search on the forward pattern, just in // case we can pick it off early here params.setFw(true); btr1.setQuery(patsrc->bufa()); btr1.setOffs(0, 0, plen, plen, plen, plen); if(btr1.backtrack()) { DONEMASK_SET(patid); continue; } } if(!norc) { // Set up backtracker with reverse complement params.setFw(false); // Set up the revisitability of the halves btr1.setQuery(patsrc->bufa()); btr1.setOffs(0, 0, s5, s5, two ? s : s5, s); if(btr1.backtrack()) { DONEMASK_SET(patid); continue; } } if(nofw && sink->finishedWithStratum(0)) { // no more exact hits are possible DONEMASK_SET(patid); continue; } } ugene-1.9.8/src/plugins_3rdparty/bowtie/src/bowtie/SeqAn-1.1/0000755000175000017500000000000011651544310022267 5ustar ilyailyaugene-1.9.8/src/plugins_3rdparty/bowtie/src/bowtie/SeqAn-1.1/platform_linux_gcc.h0000644000175000017500000000072011651544326026325 0ustar ilyailya#define PLATFORM "gcc" #ifndef PLATFORM_GCC #define PLATFORM_GCC #endif // should be set before including anything #ifndef _FILE_OFFSET_BITS #define _FILE_OFFSET_BITS 64 #endif #ifndef _LARGEFILE_SOURCE #define _LARGEFILE_SOURCE #endif //#include #include #define finline __inline__ // default 64bit type typedef int64_t __int64; //define SEQAN_SWITCH_USE_FORWARDS to use generated forwards #define SEQAN_SWITCH_USE_FORWARDS ugene-1.9.8/src/plugins_3rdparty/bowtie/src/bowtie/SeqAn-1.1/platform_windows_mingw.h0000644000175000017500000000032611651544326027247 0ustar ilyailya#define PLATFORM "windows" #ifndef PLATFORM_WINDOWS #define PLATFORM_WINDOWS #endif #define finline __inline__ //define SEQAN_SWITCH_USE_FORWARDS to use generated forwards //#define SEQAN_SWITCH_USE_FORWARDS ugene-1.9.8/src/plugins_3rdparty/bowtie/src/bowtie/SeqAn-1.1/README.txt0000644000175000017500000000133511651544326023776 0ustar ilyailyaThis is SeqAn, the C++ template library for sequence analysis See http://www.seqan.de for more information Read "docs/Page_Installation.html" for detailed installation instructions. Folders: ======== "seqan": SeqAn library (add the folder that contains "seqan" to your include path) "demos": SeqAn demos, see also "docs/INDEXPAGE_Demo.html" "apps": SeqAn applications "docs": HTML-Documentation Files: ====== "Makefile": make file for Linux/Darwin/Solaris "*_7.sln", "*_7.vcproj": Visual Studio .net 2003 solution and project files "*_8.sln", "*_8.vcproj": Visual Studio .net 2005 solution and project files "*_9.sln", "*_9.vcproj": Visual Studio .net 2008 solution and project files Have fun! Your SeqAn Team ugene-1.9.8/src/plugins_3rdparty/bowtie/src/bowtie/SeqAn-1.1/seqan/0000755000175000017500000000000011651544311023377 5ustar ilyailyaugene-1.9.8/src/plugins_3rdparty/bowtie/src/bowtie/SeqAn-1.1/seqan/sequence.h0000644000175000017500000000450611651544326025373 0ustar ilyailya /*========================================================================== SeqAn - The Library for Sequence Analysis http://www.seqan.de ============================================================================ Copyright (C) 2007 This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. ============================================================================ $Id: sequence.h,v 1.1 2008/08/25 16:20:06 langmead Exp $ ==========================================================================*/ #ifndef SEQAN_HEADER_SEQUENCE_H #define SEQAN_HEADER_SEQUENCE_H //____________________________________________________________________________ // prerequisites #include //____________________________________________________________________________ #include #ifdef SEQAN_SWITCH_USE_FORWARDS #include #endif #include #include //____________________________________________________________________________ // segments (suffix, ...) #include #include #include #include //____________________________________________________________________________ // strings #include #include #include #include #include #include #include #include #include #include #include #endif //#ifndef SEQAN_HEADER_... ugene-1.9.8/src/plugins_3rdparty/bowtie/src/bowtie/SeqAn-1.1/seqan/basic.h0000644000175000017500000000730711651544326024646 0ustar ilyailya /*========================================================================== SeqAn - The Library for Sequence Analysis http://www.seqan.de ============================================================================ Copyright (C) 2007 This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. ============================================================================ $Id: basic.h,v 1.2 2009/05/06 20:32:59 langmead Exp $ ==========================================================================*/ #ifndef SEQAN_HEADER_BASIC_H #define SEQAN_HEADER_BASIC_H //____________________________________________________________________________ // prerequisites #include //#include #ifdef PLATFORM_WINDOWS #include // limits include file exists only for g++ >= 3.0 #endif #include // size_t #include // FILE, basic_debug #include #include #include #include // memset #include // basic_profile #define SEQAN_NAMESPACE_MAIN seqan //____________________________________________________________________________ #include #ifdef SEQAN_SWITCH_USE_FORWARDS #include #endif #include #include #include #include #include #include //____________________________________________________________________________ // allocators #include #include #include #include #include #include //#include //____________________________________________________________________________ #include #include #include #include //____________________________________________________________________________ // iterators #include #include #include #include #include #include #include //#include #include #include //____________________________________________________________________________ // alphabets #include #include #include #include #include //____________________________________________________________________________ //#include #include #include #endif //#ifndef SEQAN_HEADER_... ugene-1.9.8/src/plugins_3rdparty/bowtie/src/bowtie/SeqAn-1.1/seqan/index.h0000644000175000017500000000720111651544326024665 0ustar ilyailya /*========================================================================== SeqAn - The Library for Sequence Analysis http://www.seqan.de ============================================================================ Copyright (C) 2007 This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. ============================================================================ $Id: index.h,v 1.6 2009/03/13 14:46:42 langmead Exp $ ==========================================================================*/ #ifndef SEQAN_HEADER_INDEX_H #define SEQAN_HEADER_INDEX_H //____________________________________________________________________________ // prerequisites #include //#include //#include #include //#include #include #include #include #include #include #include #include #include #include // memset ////////////////////////////////////////////////////////////////////////////// // INDEX CONSTRUCTION ////////////////////////////////////////////////////////////////////////////// #ifdef SEQAN_SWITCH_USE_FORWARDS #include #include #endif #include //____________________________________________________________________________ // suffix array creators //#include //#include #include //#include //#include // //#include //#include // //#include //#include //#include //____________________________________________________________________________ // enhanced table creators //#include //____________________________________________________________________________ // q-gram index creator #include #include #include //#include //#include ////////////////////////////////////////////////////////////////////////////// // INDEX USAGE ////////////////////////////////////////////////////////////////////////////// #include #include //____________________________________________________________________________ // (virtual) suffix trees //____________________________________________________________________________ // suffix tree algorithms //____________________________________________________________________________ // Pizza & Chili interface (compressed indices) //#include //#include //____________________________________________________________________________ // Shawarma interface (suffix array creators) //#include #endif //#ifndef SEQAN_HEADER_... ugene-1.9.8/src/plugins_3rdparty/bowtie/src/bowtie/SeqAn-1.1/seqan/index/0000755000175000017500000000000011651544311024506 5ustar ilyailyaugene-1.9.8/src/plugins_3rdparty/bowtie/src/bowtie/SeqAn-1.1/seqan/index/index_qgram_find.h0000644000175000017500000000574311651544326030174 0ustar ilyailya /*========================================================================== SeqAn - The Library for Sequence Analysis http://www.seqan.de ============================================================================ Copyright (C) 2007 This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. ============================================================================ $Id: index_qgram_find.h,v 1.1 2008/08/25 16:20:05 langmead Exp $ ==========================================================================*/ #ifndef SEQAN_HEADER_INDEX_QGRAM_FIND_H #define SEQAN_HEADER_INDEX_QGRAM_FIND_H namespace SEQAN_NAMESPACE_MAIN { ////////////////////////////////////////////////////////////////////////////// // QGram finders struct _Finder_QGramLookup; //Finder that simply looks up the q-gram in the hash table /** .Tag.Index Find Algorithm ..tag.QGram_FIND_Lookup:q-gram search. Finds q-grams in a @Spec.Index_QGram@ index using the hash table. */ typedef Tag<_Finder_QGramLookup> const QGram_FIND_Lookup; //____________________________________________________________________________ template < typename TText, typename TShapeSpec, typename TSpec > struct DefaultFinder > > { typedef QGram_FIND_Lookup Type; }; ////////////////////////////////////////////////////////////////////////////// // _findFirstIndex implementation template < typename TText, typename TSpec, typename TSpecFinder, typename TPattern > inline void _findFirstIndex( Finder< Index, TSpecFinder > &finder, TPattern const &pattern, QGram_FIND_Lookup const) { typedef Index TIndex; typedef typename Fibre::Type TSA; typedef typename Fibre::Type TShape; typedef typename Fibre::Type TDir; typedef typename Iterator::Type TSAIterator; typedef typename Iterator::Type TPatternIterator; TIndex &index = haystack(finder); indexRequire(index, QGram_SADir()); TSAIterator saIt = begin(indexSA(index), Standard()); TPatternIterator pIt = begin(pattern, Standard()); TDir const &dir = indexDir(index); TShape &shape = indexShape(index); finder.range.i1 = saIt + dir[hash(shape, pIt, length(pattern))]; finder.range.i2 = saIt + dir[hashUpper(shape, pIt, length(pattern))]; } ////////////////////////////////////////////////////////////////////////////// } //namespace SEQAN_NAMESPACE_MAIN #endif //#ifndef SEQAN_HEADER_ ugene-1.9.8/src/plugins_3rdparty/bowtie/src/bowtie/SeqAn-1.1/seqan/index/shape_predefined.h0000644000175000017500000000602011651544326030150 0ustar ilyailya /*========================================================================== SeqAn - The Library for Sequence Analysis http://www.seqan.de ============================================================================ Copyright (C) 2007 This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. ============================================================================ $Id: shape_predefined.h,v 1.1 2008/08/25 16:20:05 langmead Exp $ ==========================================================================*/ #ifndef SEQAN_HEADER_SHAPE_PREDEFINED_H #define SEQAN_HEADER_SHAPE_PREDEFINED_H //SEQAN_NO_GENERATED_FORWARDS: no forwards are generated for this file namespace SEQAN_NAMESPACE_MAIN { ////////////////////////////////////////////////////////////////////////////// // some predefined gapped shapes ////////////////////////////////////////////////////////////////////////////// // Single seed of // B.Ma and J.Tromp and M.Li, // "PatternHunter: faster and more sensitive homology search" // Bioinformatics 18, 2002 // // weight:11 // length:18 // // shape: // 111010010100110111 typedef FixedGappedShape< HardwiredShape< 1, 1, 2, 3, 2, 3, 1, 2, 1, 1 > > ShapePatternHunter; ////////////////////////////////////////////////////////////////////////////// // Multiple seeds of // L.Ilie and S.Ilie, "Fast Computation of Good Multiple Spaced Seeds" // WABI, 2007 // // weight:9 // length:15 // // shapes: // 111010100100111 // 110100110011101 // 111010001011011 // // sensitivity: // 65% 0.747975 70% 0.897741 // 75% 0.973134 80% 0.996226 typedef FixedGappedShape< HardwiredShape< 1, 1, 2, 2, 3, 3, 1, 1 > > ShapeIlie_9_15_1; typedef FixedGappedShape< HardwiredShape< 1, 2, 3, 1, 3, 1, 1, 2 > > ShapeIlie_9_15_2; typedef FixedGappedShape< HardwiredShape< 1, 1, 2, 4, 2, 1, 2, 1 > > ShapeIlie_9_15_3; ////////////////////////////////////////////////////////////////////////////// // Multiple seeds of // L.Ilie and S.Ilie, "Fast Computation of Good Multiple Spaced Seeds" // WABI 2007 // // weight:9 // length:13..23 // // shapes: // 1110110100111 // 11010000110010111 // 11100010010000101011 // // sensitivity: // 65% 0.767413 70% 0.910949 // 75% 0.978558 80% 0.997357 typedef FixedGappedShape< HardwiredShape< 1, 1, 2, 1, 2, 3, 1, 1 > > ShapeIlie_9_1323_1; typedef FixedGappedShape< HardwiredShape< 1, 2, 5, 1, 3, 2, 1, 1 > > ShapeIlie_9_1323_2; typedef FixedGappedShape< HardwiredShape< 1, 1, 4, 3, 5, 2, 2, 1 > > ShapeIlie_9_1323_3; } // namespace seqan #endif ugene-1.9.8/src/plugins_3rdparty/bowtie/src/bowtie/SeqAn-1.1/seqan/index/index_base.h0000644000175000017500000010703611651544326026775 0ustar ilyailya /*========================================================================== SeqAn - The Library for Sequence Analysis http://www.seqan.de ============================================================================ Copyright (C) 2007 This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. ============================================================================ $Id: index_base.h,v 1.3 2009/03/13 14:34:32 langmead Exp $ ==========================================================================*/ #ifndef SEQAN_HEADER_INDEX_BASE_H #define SEQAN_HEADER_INDEX_BASE_H //#define SEQAN_TEST_INDEX namespace SEQAN_NAMESPACE_MAIN { ////////////////////////////////////////////////////////////////////////////// // needful forward declarations // suffix array construction specs struct Skew3; struct Skew7; struct LarssonSadakane; struct ManberMyers; struct SAQSort; struct QGram_Alg; // lcp table construction algorithms struct Kasai; struct KasaiOriginal; // original, but more space-consuming algorithm // enhanced suffix array construction algorithms struct ChildTab; struct BWT; template struct Index_ESA; ////////////////////////////////////////////////////////////////////////////// /** .Metafunction.DefaultIndexSpec: ..cat:Index ..summary:Default @Class.Index@ specialization type. ..signature:DefaultIndexSpec::Type ..param.TText:The given text type. ..returns:Can be @Spec.Index_ESA@ or $Index_QGram$, etc. ..remarks:Currently @Spec.Index_ESA@ is default if $TText$ is a @Class.String@. */ template < typename TObject > struct DefaultIndexSpec { typedef Index_ESA<> Type; }; ////////////////////////////////////////////////////////////////////////////// /** .Metafunction.DefaultIndexStringSpec: ..cat:Index ..summary:Default @Class.String@ specialization type of the @Metafunction.Fibre@ of an @Class.Index@. ..signature:DefaultIndexStringSpec::Type ..param.TIndex:An @Class.Index@ Type. ..returns:If the underlying text is a @Class.String@ or a set of Strings (see @Class.StringSet@) the String's spec. type is returned. ..remarks:Most of the @Class.Index@ fibres are strings. The @Class.String@ specialization type is chosen by this meta-function. */ template < typename TIndex > struct DefaultIndexStringSpec { typedef Alloc<> Type; }; // template < typename TValue, typename TSpec > // struct DefaultIndexStringSpec< String > > { // typedef External Type; // }; template < typename TString, typename TSpec > struct DefaultIndexStringSpec< StringSet >: DefaultIndexStringSpec {}; ////////////////////////////////////////////////////////////////////////////// /** .Class.Index: ..summary:Contains preprocessing data of a fixed text. Allows fast dictionary look-up and advanced computations. ..cat:Index ..signature:Index ..param.TText:The text type. ...type:Class.String ...metafunction:Metafunction.Host ..param.TSpec:The index type. ...default:The result of @Metafunction.DefaultIndexSpec@ ...metafunction:Metafunction.Spec ..remarks:An index contains various arrays or objects, also called fibres (see @Metafunction.Fibre@). ..remarks:These fibres are created on demand depending on the requirements of an algorithm. */ ///.Function.setHaystack.param.haystack.type:Class.Index // index as a haystack template < typename TObject, typename TSpec = typename DefaultIndexSpec::Type > class Index; template struct Host< Index > { typedef TObject Type; }; template struct Spec< Index > { typedef TSpec Type; }; ////////////////////////////////////////////////////////////////////////////// /** .Metafunction.Fibre: ..summary:Type of a specific bundle member (fibre). ..signature:Fibre::Type ..cat:Index ..param.TIndex:The fibre container type. ..param.TSpec:Type to specify the fibre. ..returns:Fibre type. ..remarks:An @Class.Index@ can be seen as a bundle consisting of various fibres. In most cases this type is $String::Type>$. ..remarks:A @Metafunction.Fibre@ need not to be a real container. It can also be view (see @Tag.ESA Index Fibres.ESA_RawText@). */ // meta function to get the type of a bundle fibre template < typename TIndex, typename TSpec > struct Fibre { typedef String< typename Size::Type > Type; }; template < typename TIndex, typename TSpec > struct Fibre { typedef typename Fibre::Type const Type; }; struct FibreRecord { unsigned id; void* ptr; bool owner; }; // less function to search in sorted list for fibre id struct FibreLess: public ::std::binary_function { // functor for operator> inline bool operator()(FibreRecord const & _Left, unsigned const _Right) const { // apply operator> to operands return (_Left.id < _Right); } }; ////////////////////////////////////////////////////////////////////////////// /** .Metafunction.DefaultIndexCreator: ..cat:Index ..summary:Default algorithm to create a demanded and not yet existing @Metafunction.Fibre@. ..signature:DefaultIndexCreator::Type ..param.TIndex:An @Class.Index@ Type. ..param.TFibre:A tag specifying the fibre (e.g. @Tag.ESA Index Fibres.ESA_SA@). ..returns:A tag specifying the default algorithm to create the fibre with. */ // standard algorithm for indices creation template < typename TIndex, typename TFibre > struct DefaultIndexCreator { typedef Default Type; }; ////////////////////////////////////////////////////////////////////////////// /** .Class.Bundle: ..summary:General purpose container of various members. ..signature:Bundle ..param.TValue:The value type, that is the type of the items/characters stored in the string. ...remarks:Use @Metafunction.Value@ to get the value type for a given class. ..param.TSpec:The specializing type. ...default:$Alloc<>$, see @Spec.Alloc String@. */ /* template < typename TSpec = void > struct Bundle { typedef ::std::vector TFibreRecords; TFibreRecords fibres; }; template < typename TBundleSpec, typename TFibreSpec > inline FibreRecord& getRecord(Bundle &bundle, TFibreSpec const) { unsigned id = (unsigned)_ClassIdentifier::getID(); typename Bundle::TFibreRecords::iterator first = lower_bound(bundle.fibres.begin(), bundle.fibres.end(), id, FibreLess()); if (!first->id != id) { FibreRecord rec; rec.id = id; rec.ptr = NULL; rec.owner = true; bundle.fibres.insert(first, rec); } else return *first; } template < typename TBundleSpec, typename TFibreSpec > inline typename Fibre, TFibreSpec>::Type & getFibre(Bundle &bundle, TFibreSpec const) { typedef typename Fibre, TFibreSpec>::Type Type; unsigned id = (unsigned)_ClassIdentifier::getID(); FibreRecord &rec = getRecord(bundle, TFibreSpec()); if (!rec.ptr) rec.ptr = new Type(); return *reinterpret_cast(rec.ptr); } template < typename TBundleSpec, typename TFibreSpec > inline typename Fibre, TFibreSpec>::Type const & getFibre(Bundle const &bundle, TFibreSpec const) { typedef typename Fibre, TFibreSpec>::Type Type; unsigned id = (unsigned)_ClassIdentifier::getID(); FibreRecord &rec = getRecord(bundle, TFibreSpec()); return *reinterpret_cast(rec.ptr); } */ ////////////////////////////////////////////////////////////////////////////// // various fibre specs for enhanced suffix arrays struct _Fibre_Text; // Original text. Can be a String or a StringSet struct _Fibre_RawText; // Concatenation of the strings above struct _Fibre_SA; // suffix array (of raw text with virtual $-delimiters) with Pair entries struct _Fibre_RawSA; // suffix array with integer entries struct _Fibre_SAE; // suffix array reordered in a b-tree struct _Fibre_LCP; // lcp table of raw text struct _Fibre_LCPE; // lcp interval tree struct _Fibre_ChildTab; // childtab (Kurtz et al.) of raw text struct _Fibre_BWT; // burrows wheeler table of raw text typedef Tag<_Fibre_Text> const Fibre_Text; typedef Tag<_Fibre_RawText> const Fibre_RawText; typedef Tag<_Fibre_SA> const Fibre_SA; typedef Tag<_Fibre_RawSA> const Fibre_RawSA; typedef Tag<_Fibre_SAE> const Fibre_SAE; typedef Tag<_Fibre_LCP> const Fibre_LCP; typedef Tag<_Fibre_LCPE> const Fibre_LCPE; typedef Tag<_Fibre_ChildTab> const Fibre_ChildTab; typedef Tag<_Fibre_BWT> const Fibre_BWT; ////////////////////////////////////////////////////////////////////////////// /** .Metafunction.SAValue: ..cat:Index ..summary:The default alphabet type of a suffix array, i.e. the type to store a position of a string or string set. ..signature:SAValue::Type ..param.TObject:A string, string set, or index type. ...type:Class.String ...type:Class.StringSet ...type:Class.Index ..returns:A type to store a position. ...text:If $TObject$ is a @Class.String@, it is a single integer value. By default this is the @Metafunction.Size@ type of $TObject$. ...text:If $TObject$ is a @Class.StringSet@, it could be a single integer too (called global position, see @Spec.ConcatDirect@) or a @Class.Pair@ (called local position, see @Spec.Owner@). Currently SeqAn defaults to a local position for @Class.StringSet@ classes (index_base.h): ...code:template < typename TString, typename TSpec > struct SAValue< StringSet > { typedef Pair< typename Size< StringSet >::Type, typename SAValue::Type, Compressed > Type; }; ..note:SAValue is the return type of various function, e.g. @Function.position@ for the @Class.Index@ @Class.Finder@ class, @Function.getOccurrence@, @Function.getOccurrences@ etc. You should always use the type of this meta-function to store the return values. If you want to write algorithms for both variants (local and global positions) you should use the functions @Function.posLocalize@, @Function.posGlobalize@, @Function.getSeqNo@ and @Function.getSeqOffset@. ..note:If $TObject$ is an @Class.Index@, @Metafunction.Position@ returns the same value as $SAValue$. You can change the position type of an index by overloading $SAValue$, not @Metafunction.Position@. */ template struct SAValue: Size {}; template struct SAValue: SAValue {}; // to speed up sequence number computation // we use a pair of seqNo and localPosition template < typename TString, typename TSpec > struct SAValue< StringSet > { typedef Pair< typename Size< StringSet >::Type, typename SAValue::Type, Compressed > Type; }; /* template < typename TString, typename TSpec > struct SAValue< StringSet > { typedef Pair< typename Size< StringSet >::Type, typename SAValue::Type, CutCompressed<4> // max. 4 sequences > Type; // max. 2^30 characters each }; */ template < typename TText, typename TSpec > struct SAValue< Index >: SAValue {}; template < typename TObject, typename TSpec > struct DefaultIndexStringSpec< Index >: DefaultIndexStringSpec {}; ////////////////////////////////////////////////////////////////////////////// // value and size type of an index template < typename TText, typename TSpec > struct Value< Index > { typedef typename Value< typename Fibre< Index, Fibre_RawText>::Type >::Type Type; }; template < typename TText, typename TSpec > struct Size< Index > { typedef typename Size< typename Fibre< Index, Fibre_RawText>::Type >::Type Type; }; template < typename TText, typename TSpec > struct Position< Index >: SAValue< Index > {}; ////////////////////////////////////////////////////////////////////////////// // default table type template < typename TObject, typename TSpec, typename TFibre > struct Fibre< Index, Tag const > { typedef String< typename Size< Index >::Type, typename DefaultIndexStringSpec< Index >::Type > Type; }; ////////////////////////////////////////////////////////////////////////////// // original text template < typename TText, typename TSpec > struct Fibre< Index, Fibre_Text> { typedef TText Type; }; ////////////////////////////////////////////////////////////////////////////// // concatenated text template < typename TText, typename TSpec > struct Fibre< Index, Fibre_RawText> { typedef typename Concatenator::Type Type; }; ////////////////////////////////////////////////////////////////////////////// // suffix array type template < typename TText, typename TSpec > struct Fibre< Index, Fibre_SA> { typedef String< typename SAValue< Index >::Type, typename DefaultIndexStringSpec< Index >::Type > Type; }; ////////////////////////////////////////////////////////////////////////////// // globalize functor template ::Type> struct FunctorGlobalize : public ::std::unary_function { TLimitsString const *limits; FunctorGlobalize() {} FunctorGlobalize(TLimitsString const &_limits) : limits(&_limits) {} inline Result operator()(const InType& x) const { return posGlobalize(x, *limits); } }; ////////////////////////////////////////////////////////////////////////////// // raw suffix array contains integer offsets relative to raw text template < typename TString, typename TSSetSpec, typename TSpec > struct Fibre< Index, TSpec>, Fibre_RawSA> { typedef Index< StringSet, TSpec> TIndex; // typedef ModifiedString< // typename Fibre::Type, // ModView< FunctorGlobalize< // typename Value< typename Fibre::Type >::Type, // typename StringSetLimits >::Type > // > // > Type; }; ////////////////////////////////////////////////////////////////////////////// // default burrows-wheeler table template < typename TText, typename TSpec > struct Fibre< Index, Fibre_BWT> { typedef String < typename Value< Index >::Type, typename DefaultIndexStringSpec< Index >::Type > Type; }; ////////////////////////////////////////////////////////////////////////////// // default fibre creators template < typename TText, typename TSpec > struct DefaultIndexCreator, Fibre_SA> { typedef Skew7 Type; // standard suffix array creator is skew7 }; template < typename TText, typename TSpec > struct DefaultIndexCreator, Fibre_LCP> { typedef Kasai Type; }; template < typename TText, typename TSpec > struct DefaultIndexCreator, Fibre_BWT> { typedef BWT Type; }; template < typename TText, typename TSpec > struct DefaultIndexCreator, Fibre_ChildTab> { typedef ChildTab Type; }; ////////////////////////////////////////////////////////////////////////////// // fibre interface to access the enhanced suffix array tables /** .Function.getFibre: ..summary:Returns a specific @Metafunction.Fibre@ of an @Class.Index@ object. ..cat:Index ..signature:getFibre(index, fibre_tag) ..param.index:The @Class.Index@ object holding the fibre. ...type:Class.Index ..param.fibre_tag:A tag that identifies the @Metafunction.Fibre@ (e.g. @Tag.ESA Index Fibres.ESA_SA@). ..returns:A reference to the @Metafunction.Fibre@ object. */ template inline Holder & _dataHost(Index &index) { return index.text; } template inline Holder const & _dataHost(Index const &index) { return index.text; } ////////////////////////////////////////////////////////////////////////////// template inline typename Fibre, Fibre_Text>::Type & getFibre(Index &index, Fibre_Text) { return value(index.text); } template inline typename Fibre const, Fibre_Text>::Type & getFibre(Index const &index, Fibre_Text) { return value(index.text); } ////////////////////////////////////////////////////////////////////////////// template inline typename Fibre, Fibre_RawText>::Type & getFibre(Index &index, Fibre_RawText) { return concat(value(index.text)); } template inline typename Fibre const, Fibre_RawText>::Type & getFibre(Index const &index, Fibre_RawText) { return concat(value(index.text)); } ////////////////////////////////////////////////////////////////////////////// template inline typename Fibre, Fibre_SA>::Type & getFibre(Index &index, Fibre_SA) { return index.sa; } template inline typename Fibre const, Fibre_SA>::Type & getFibre(Index const &index, Fibre_SA) { return index.sa; } ////////////////////////////////////////////////////////////////////////////// template inline typename Fibre const, Fibre_SA>::Type & getFibre(Index &index, Fibre_RawSA) { return indexSA(index); } /* template inline typename Fibre const, Fibre_SA>::Type & getFibre(Index const &index, Fibre_RawSA) { return indexSA(index); } */ template inline typename Fibre, TSpec>, Fibre_RawSA>::Type getFibre(Index, TSpec> &index, Fibre_RawSA) { typedef Index< StringSet, TSpec> TIndex; typedef FunctorGlobalize< typename Value< typename Fibre::Type >::Type, typename StringSetLimits >::Type > TFunctor; // typedef ModifiedString< // typename Fibre, TSpec>, Fibre_SA>::Type, // ModView< TFunctor > // > ModString; return ModString(indexSA(index), TFunctor(stringSetLimits(indexText(index)))); } ////////////////////////////////////////////////////////////////////////////// template inline typename Fibre, Fibre_LCP>::Type & getFibre(Index &index, Fibre_LCP) { return index.lcp; } template inline typename Fibre const, Fibre_LCP>::Type & getFibre(Index const &index, Fibre_LCP) { return index.lcp; } ////////////////////////////////////////////////////////////////////////////// template inline typename Fibre, Fibre_LCPE>::Type & getFibre(Index &index, Fibre_LCPE) { return index.lcpe; } template inline typename Fibre const, Fibre_LCPE>::Type & getFibre(Index const &index, Fibre_LCPE) { return index.lcpe; } ////////////////////////////////////////////////////////////////////////////// template inline typename Fibre, Fibre_ChildTab>::Type & getFibre(Index &index, Fibre_ChildTab) { return index.childtab; } template inline typename Fibre const, Fibre_ChildTab>::Type & getFibre(Index const &index, Fibre_ChildTab) { return index.childtab; } ////////////////////////////////////////////////////////////////////////////// template inline typename Fibre, Fibre_BWT>::Type & getFibre(Index &index, Fibre_BWT) { return index.bwt; } template inline typename Fibre const, Fibre_BWT>::Type & getFibre(Index const &index, Fibre_BWT) { return index.bwt; } ////////////////////////////////////////////////////////////////////////////// ///.Function.length.param.object.type:Class.Index template inline typename Size >::Type length(Index const &index) { return length(indexRawText(index)); } ////////////////////////////////////////////////////////////////////////////// template inline typename Size::Type countSequences(Index const &index) { return countSequences(indexText(index)); } ////////////////////////////////////////////////////////////////////////////// template inline typename Size >::Type sequenceLength(TSeqNo seqNo, Index const &index) { return sequenceLength(seqNo, indexText(index)); } ////////////////////////////////////////////////////////////////////////////// template inline typename Size >::Type suffixLength(TPos pos, Index const &index) { return sequenceLength(getSeqNo(pos, stringSetLimits(index)), index) - getSeqOffset(pos, stringSetLimits(index)); } ////////////////////////////////////////////////////////////////////////////// // unified textAt interface template inline typename Reference::Type>::Type textAt(TPos i, TIndex &index) { return value(getFibre(index, Fibre_RawText()), i); } template inline typename Reference, TSpec>, Fibre_RawText>::Type>::Type textAt(TPos i, Index< StringSet, TSpec> &index) { return value(getFibre(index, Fibre_RawText()), posGlobalize(i, stringSetLimits(index))); } template inline typename Reference >, TSpec>, Fibre_RawText>::Type>::Type textAt(TPos i, Index< StringSet >, TSpec> &index) { Pair < typename Size< StringSet > >::Type, typename Size< TString >::Type > locPos; posLocalize(locPos, i, stringSetLimits(index)); return value(value(getFibre(index, Fibre_Text()), getValueI1(locPos)), getValueI2(locPos)); } ////////////////////////////////////////////////////////////////////////////// /** .Function.rawtextAt: ..summary:Shortcut for $value(indexRawText(..), ..)$. ..cat:Index ..signature:rawtextAt(position, index) ..param.position:A position in the array on which the value should be accessed. ..param.index:The @Class.Index@ object holding the fibre. ...type:Spec.Index_ESA ..returns:A reference or proxy to the value. */ template inline typename Reference::Type>::Type rawtextAt(TPos i, TIndex &index) { return value(getFibre(index, Fibre_RawText()), i); } template inline typename Reference::Type>::Type rawtextAt(TPos i, TIndex const &index) { return value(getFibre(index, Fibre_RawText()), i); } ////////////////////////////////////////////////////////////////////////////// /** .Function.saAt: ..summary:Shortcut for $value(indexSA(..), ..)$. ..cat:Index ..signature:saAt(position, index) ..param.position:A position in the array on which the value should be accessed. ..param.index:The @Class.Index@ object holding the fibre. ...type:Spec.Index_ESA ..returns:A reference or proxy to the value. */ template inline typename Reference::Type>::Type saAt(TPos i, TIndex &index) { return value(getFibre(index, Fibre_SA()), i); } template inline typename Reference::Type>::Type saAt(TPos i, TIndex const &index) { return value(getFibre(index, Fibre_SA()), i); } template inline typename Value::Type>::Type rawsaAt(TPos i, TIndex const &index) { return posGlobalize(saAt(i, index), stringSetLimits(indexText(index))); } ////////////////////////////////////////////////////////////////////////////// /** .Function.lcpAt: ..summary:Shortcut for $value(indexLCP(..), ..)$. ..cat:Index ..signature:lcpAt(position, index) ..param.position:A position in the array on which the value should be accessed. ..param.index:The @Class.Index@ object holding the fibre. ...type:Spec.Index_ESA ..returns:A reference or proxy to the value. */ template inline typename Reference::Type>::Type lcpAt(TPos i, TIndex &index) { return value(getFibre(index, Fibre_LCP()), i); } template inline typename Reference::Type>::Type lcpAt(TPos i, TIndex const &index) { return value(getFibre(index, Fibre_LCP()), i); } ////////////////////////////////////////////////////////////////////////////// /** .Function.lcpeAt: ..summary:Shortcut for $value(indexLCPE(..), ..)$. ..cat:Index ..signature:lcpeAt(position, index) ..param.position:A position in the array on which the value should be accessed. ..param.index:The @Class.Index@ object holding the fibre. ...type:Spec.Index_ESA ..returns:A reference or proxy to the value. */ template inline typename Reference::Type>::Type lcpeAt(TPos i, TIndex &index) { return value(getFibre(index, Fibre_LCPE()), i); } template inline typename Reference::Type>::Type lcpeAt(TPos i, TIndex const &index) { return value(getFibre(index, Fibre_LCPE()), i); } ////////////////////////////////////////////////////////////////////////////// /** .Function.childAt: ..summary:Shortcut for $value(indexChildTab(..), ..)$. ..cat:Index ..signature:childAt(position, index) ..param.position:A position in the array on which the value should be accessed. ..param.index:The @Class.Index@ object holding the fibre. ...type:Spec.Index_ESA ..returns:A reference or proxy to the value. */ template inline typename Reference::Type>::Type childAt(TPos i, TIndex &index) { return value(getFibre(index, Fibre_ChildTab()), i); } template inline typename Reference::Type>::Type childAt(TPos i, TIndex const &index) { return value(getFibre(index, Fibre_ChildTab()), i); } ////////////////////////////////////////////////////////////////////////////// /** .Function.bwtAt: ..summary:Shortcut for $value(indexBWT(..), ..)$. ..cat:Index ..signature:bwtAt(position, index) ..param.position:A position in the array on which the value should be accessed. ..param.index:The @Class.Index@ object holding the fibre. ...type:Spec.Index_ESA ..returns:A reference or proxy to the value. */ template inline typename Reference::Type>::Type bwtAt(TPos i, TIndex &index) { return value(getFibre(index, Fibre_BWT()), i); } template inline typename Reference::Type>::Type bwtAt(TPos i, TIndex const &index) { return value(getFibre(index, Fibre_BWT()), i); } ////////////////////////////////////////////////////////////////////////////// // interface for infinity/invalid values template inline void _setSizeInval(TValue &v) { v = SupremumValue::VALUE; } template inline bool _isSizeInval(TValue const &v) { return v == SupremumValue::VALUE; } ////////////////////////////////////////////////////////////////////////////// /** .Function.indexText: ..summary:Shortcut for $getFibre(.., ESA_Text)$. ..cat:Index ..signature:indexText(index) ..param.index:The @Class.Index@ object holding the fibre. ...type:Spec.Index_ESA ..returns:A reference to the @Tag.ESA Index Fibres.ESA_Text@ fibre (original text). */ template inline typename Fibre, Fibre_Text>::Type & indexText(Index &index) { return getFibre(index, Fibre_Text()); } template inline typename Fibre const, Fibre_Text>::Type & indexText(Index const &index) { return getFibre(index, Fibre_Text()); } ////////////////////////////////////////////////////////////////////////////// template inline typename StringSetLimits::Type stringSetLimits(Index &) { return Nothing(); } template inline typename StringSetLimits::Type stringSetLimits(Index const &) { return Nothing(); } template inline typename StringSetLimits< StringSet const >::Type & stringSetLimits(Index, TSpec> &index) { return stringSetLimits(indexText(index)); } template inline typename StringSetLimits< StringSet const >::Type & stringSetLimits(Index, TSpec> const &index) { return stringSetLimits(indexText(index)); } ////////////////////////////////////////////////////////////////////////////// /** .Function.indexRawText: ..summary:Shortcut for $getFibre(.., ESA_RawText)$. ..cat:Index ..signature:indexRawText(index) ..param.index:The @Class.Index@ object holding the fibre. ...type:Spec.Index_ESA ..returns:A reference to the @Tag.ESA Index Fibres.ESA_RawText@ fibre (concatenated input text). */ template inline typename Fibre, Fibre_RawText>::Type & indexRawText(Index &index) { return getFibre(index, Fibre_RawText()); } template inline typename Fibre const, Fibre_RawText>::Type & indexRawText(Index const &index) { return getFibre(index, Fibre_RawText()); } ////////////////////////////////////////////////////////////////////////////// /** .Function.indexSA: ..summary:Shortcut for $getFibre(.., ESA_SA)$. ..cat:Index ..signature:indexSA(index) ..param.index:The @Class.Index@ object holding the fibre. ...type:Spec.Index_ESA ..returns:A reference to the @Tag.ESA Index Fibres.ESA_SA@ fibre (suffix array). */ template inline typename Fibre, Fibre_SA>::Type & indexSA(Index &index) { return getFibre(index, Fibre_SA()); } template inline typename Fibre const, Fibre_SA>::Type & indexSA(Index const &index) { return getFibre(index, Fibre_SA()); } ////////////////////////////////////////////////////////////////////////////// /** .Function.indexRawSA: ..summary:Shortcut for $getFibre(.., ESA_RawSA)$. ..cat:Index ..signature:indexRawSA(index) ..param.index:The @Class.Index@ object holding the fibre. ...type:Spec.Index_ESA ..returns:A reference to the @Tag.ESA Index Fibres.ESA_RawSA@ fibre (suffix array). */ template inline typename Fibre, Fibre_RawSA>::Type indexRawSA(Index &index) { return getFibre(index, Fibre_RawSA()); } template inline typename Fibre const, Fibre_RawSA>::Type indexRawSA(Index const &index) { return getFibre(index, Fibre_RawSA()); } ////////////////////////////////////////////////////////////////////////////// /** .Function.indexLCP: ..summary:Shortcut for $getFibre(.., ESA_LCP)$. ..cat:Index ..signature:indexLCP(index) ..param.index:The @Class.Index@ object holding the fibre. ...type:Spec.Index_ESA ..returns:A reference to the @Tag.ESA Index Fibres.ESA_LCP@ fibre (lcp table). */ template inline typename Fibre, Fibre_LCP>::Type & indexLCP(Index &index) { return getFibre(index, Fibre_LCP()); } template inline typename Fibre const, Fibre_LCP>::Type & indexLCP(Index const &index) { return getFibre(index, Fibre_LCP()); } ////////////////////////////////////////////////////////////////////////////// /** .Function.indexLCPE: ..summary:Shortcut for $getFibre(.., ESA_LCPE)$. ..cat:Index ..signature:indexLCPE(index) ..param.index:The @Class.Index@ object holding the fibre. ...type:Spec.Index_ESA ..returns:A reference to the @Tag.ESA Index Fibres.ESA_LCPE@ fibre (enhanced lcp table). */ template inline typename Fibre, Fibre_LCPE>::Type & indexLCPE(Index &index) { return getFibre(index, Fibre_LCPE()); } template inline typename Fibre const, Fibre_LCPE>::Type & indexLCPE(Index const &index) { return getFibre(index, Fibre_LCPE()); } ////////////////////////////////////////////////////////////////////////////// /** .Function.indexBWT: ..summary:Shortcut for $getFibre(.., ESA_BWT)$. ..cat:Index ..signature:indexBWT(index) ..param.index:The @Class.Index@ object holding the fibre. ...type:Spec.Index_ESA ..returns:A reference to the @Tag.ESA Index Fibres.ESA_BWT@ fibre (Burrows-Wheeler table). */ template inline typename Fibre, Fibre_BWT>::Type & indexBWT(Index &index) { return getFibre(index, Fibre_BWT()); } template inline typename Fibre const, Fibre_BWT>::Type & indexBWT(Index const &index) { return getFibre(index, Fibre_BWT()); } ////////////////////////////////////////////////////////////////////////////// /** .Function.indexChildTab: ..summary:Shortcut for $getFibre(.., ESA_ChildTab)$. ..cat:Index ..signature:indexChildTab(index) ..param.index:The @Class.Index@ object holding the fibre. ...type:Spec.Index_ESA ..returns:A reference to the @Tag.ESA Index Fibres.ESA_ChildTab@ fibre (child table). */ template inline typename Fibre, Fibre_ChildTab>::Type & indexChildTab(Index &index) { return getFibre(index, Fibre_ChildTab()); } template inline typename Fibre const, Fibre_ChildTab>::Type & indexChildTab(Index const &index) { return getFibre(index, Fibre_ChildTab()); } } #endif ugene-1.9.8/src/plugins_3rdparty/bowtie/src/bowtie/SeqAn-1.1/seqan/index/index_sa_lss.h0000644000175000017500000003430511651544326027345 0ustar ilyailya/* * index_sa_lss.h * SeqAn * * Created by David Weese on 18.04.07. * * This file contains the suffix array algorithm implementation * by Larsson and Sadakane with the following modifications. * * MODIFICATIONS: * - a context is used for reentrance * - a generic TValue is used instead of int * - functions are surrounded by SeqAn's namespace to omit namespace pollution * * David Weese, 2007 * */ /* qsufsort.c Copyright 1999, N. Jesper Larsson, all rights reserved. This file contains an implementation of the algorithm presented in "Faster Suffix Sorting" by N. Jesper Larsson (jesper@cs.lth.se) and Kunihiko Sadakane (sada@is.s.u-tokyo.ac.jp). This software may be used freely for any purpose. However, when distributed, the original source must be clearly stated, and, when the source code is distributed, the copyright notice must be retained and any alterations in the code must be clearly marked. No warranty is given regarding the quality of this software.*/ #ifndef SEQAN_HEADER_INDEX_SA_LSS_H #define SEQAN_HEADER_INDEX_SA_LSS_H namespace SEQAN_NAMESPACE_MAIN { template struct _Context_LSS { TValue *I, /* group array, ultimately suffix array.*/ *V, /* inverse array, ultimately inverse of I.*/ r, /* number of symbols aggregated by transform.*/ h; /* length of already-sorted prefixes.*/ // MODIFIED: renamed defines according to SeqAn's naming conventions #define SEQAN_LSSKEY(p) (V[*(p)+(h)]) #define SEQAN_LSSSWAP(p, q) (tmp=*(p), *(p)=*(q), *(q)=tmp) #define SEQAN_LSSMED3(a, b, c) (SEQAN_LSSKEY(a)SEQAN_LSSKEY(c) ? (b) : SEQAN_LSSKEY(a)>SEQAN_LSSKEY(c) ? (c) : (a))) /* Subroutine for select_sort_split and sort_split. Sets group numbers for a group whose lowest position in I is pl and highest position is pm.*/ inline void update_group(TValue *pl, TValue *pm) { TValue g; g=pm-I; /* group number.*/ V[*pl]=g; /* update group number of first position.*/ if (pl==pm) *pl=-1; /* one element, sorted group.*/ else do /* more than one element, unsorted group.*/ V[*++pl]=g; /* update group numbers.*/ while (pl>1); /* small arrays, middle element.*/ if (n>7) { pl=p; pn=p+n-1; if (n>40) { /* big arrays, pseudomedian of 9.*/ s=n>>3; pl=SEQAN_LSSMED3(pl, pl+s, pl+s+s); pm=SEQAN_LSSMED3(pm-s, pm, pm+s); pn=SEQAN_LSSMED3(pn-s-s, pn-s, pn); } pm=SEQAN_LSSMED3(pl, pm, pn); /* midsize arrays, median of 3.*/ } return SEQAN_LSSKEY(pm); } /* Sorting routine called for each unsorted group. Sorts the array of integers (suffix numbers) of length n starting at p. The algorithm is a ternary-split quicksort taken from Bentley & McIlroy, "Engineering a Sort Function", Software -- Practice and Experience 23(11), 1249-1265 (November 1993). This function is based on Program 7.*/ inline void sort_split(TValue *p, TValue n) { TValue *pa, *pb, *pc, *pd, *pl, *pm, *pn; TValue f, v, s, t, tmp; if (n<7) { /* multi-selection sort smallest arrays.*/ select_sort_split(p, n); return; } v=choose_pivot(p, n); pa=pb=p; pc=pd=p+n-1; while (1) { /* split-end partition.*/ while (pb<=pc && (f=SEQAN_LSSKEY(pb))<=v) { if (f==v) { SEQAN_LSSSWAP(pa, pb); ++pa; } ++pb; } while (pc>=pb && (f=SEQAN_LSSKEY(pc))>=v) { if (f==v) { SEQAN_LSSSWAP(pc, pd); --pd; } --pc; } if (pb>pc) break; SEQAN_LSSSWAP(pb, pc); ++pb; --pc; } pn=p+n; if ((s=pa-p)>(t=pb-pa)) s=t; for (pl=p, pm=pb-s; s; --s, ++pl, ++pm) SEQAN_LSSSWAP(pl, pm); if ((s=pd-pc)>(t=pn-pd-1)) s=t; for (pl=pb, pm=pn-s; s; --s, ++pl, ++pm) SEQAN_LSSSWAP(pl, pm); s=pb-pa; t=pd-pc; if (s>0) sort_split(p, s); update_group(p+s, p+n-t-1); if (t>0) sort_split(p+n-t, t); } /* Bucketsort for first iteration. Input: x[0...n-1] holds integers in the range 1...k-1, all of which appear at least once. x[n] is 0. (This is the corresponding output of transform.) k must be at most n+1. p is array of size n+1 whose contents are disregarded. Output: x is V and p is I after the initial sorting stage of the refined suffix sorting algorithm.*/ inline void bucketsort(TValue *x, TValue *p, TValue n, TValue k) { TValue *pi, i, c, d, g; for (pi=p; pi=p; --pi) { d=x[c=*pi]; /* c is position, d is next in list.*/ x[c]=g=i; /* last position equals group number.*/ if (d>=0) { /* if more than one element in group.*/ p[i--]=c; /* p is permutation for the sorted x.*/ do { d=x[c=d]; /* next in linked list.*/ x[c]=g; /* group number in x.*/ p[i--]=c; /* permutation in p.*/ } while (d>=0); } else p[i--]=-1; /* one element, sorted group.*/ } } /* Transforms the alphabet of x by attempting to aggregate several symbols into one, while preserving the suffix order of x. The alphabet may also be compacted, so that x on output comprises all integers of the new alphabet with no skipped numbers. Input: x is an array of size n+1 whose first n elements are positive integers in the range l...k-1. p is array of size n+1, used for temporary storage. q controls aggregation and compaction by defining the maximum value for any symbol during transformation: q must be at least k-l; if q<=n, compaction is guaranteed; if k-l>n, compaction is never done; if q is INT_MAX, the maximum number of symbols are aggregated into one. Output: Returns an integer j in the range 1...q representing the size of the new alphabet. If j<=n+1, the alphabet is compacted. The global variable r is set to the number of old symbols grouped into one. Only x[n] is 0.*/ inline TValue transform(TValue *x, TValue *p, TValue n, TValue k, TValue l, TValue q) { TValue b, c, d, e, i, j, m, s; TValue *pi, *pj; for (s=0, i=k-l; i; i>>=1) ++s; /* s is number of bits in old symbol.*/ e=SupremumValue::VALUE>>s; /* e is for overflow checking.*/ for (b=d=r=0; r=k-l) { /* if bucketing possible,*/ j=transform(V, I, n, k, l, n); bucketsort(V, I, n, j); /* bucketsort on first r positions.*/ } else { transform(V, I, n, k, l, SupremumValue::VALUE); for (i=0; i<=n; ++i) I[i]=i; /* initialize I with suffix numbers.*/ h=0; sort_split(I, n+1); /* quicksort on first r positions.*/ } h=r; /* number of symbols aggregated by transform.*/ while (*I>=-n) { pi=I; /* pi is first position of group.*/ sl=0; /* sl is negated length of sorted groups.*/ do { if ((s=*pi)<0) { pi-=s; /* skip over sorted group.*/ sl+=s; /* add negated length to sl.*/ } else { if (sl) { *(pi+sl)=sl; /* combine sorted groups before pi.*/ sl=0; } pk=I+V[s]+1; /* pk-1 is last position of unsorted group.*/ sort_split(pi, pk-pi); pi=pk; /* next group.*/ } } while (pi<=I+n); if (sl) /* if the array ends with a sorted group.*/ *(pi+sl)=sl; /* combine sorted groups at end of I.*/ h=2*h; /* double sorted-depth.*/ } for (i=0; i<=n; ++i) /* reconstruct suffix array from inverse.*/ I[V[i]]=i; } }; ////////////////////////////////////////////////////////////////////////////// // SeqAn interface struct LarssonSadakane {}; // WARNING: // 1. the content of s will be destroyed // 2. s and SA have to have size n+1 // 3. s[n] must be unique and less than any other character in s // // better use LarssonSadakane as a pipe (look down) template < typename TSA, typename TText > void createSuffixArray( TSA &SA, TText &s, LarssonSadakane const &, unsigned K) { typedef typename Value::Type TValue; typedef typename _MakeSigned::Type TSValue; // LarssonSadakane expects signed values _Context_LSS c; c.suffixsort( (TSValue*)begin(s, Standard()), // text (TSValue*)begin(SA, Standard()), // SA length(s) - 1, // n K, // text[i] < K 0); // text[i] >= 0 } ////////////////////////////////////////////////////////////////////////////// // qsufsort pipe // template < typename TInput > // struct Pipe< TInput, LarssonSadakane > // { // typedef typename SAValue::Type TValue; // typedef String > TText; // typedef String > TSA; // typedef Pipe > TSource; // // TSA sa; // TSource in; // // Pipe(TInput &_textIn): // in(sa) // { // typedef typename Iterator::Type TIter; // // TValue len = length(_textIn); // TText text; // resize(text, len + 1, Exact()); // // TIter it = begin(text); // TIter itEnd = begin(text) + len; // TValue maxChar = 0; // // beginRead(_textIn); // for(; it != itEnd; ++it, ++_textIn) { // TValue val = (*it = 1 + (TValue)*_textIn); // if (val > maxChar) // maxChar = val; // } // endRead(_textIn); // // resize(sa, len + 1, Exact()); // createSuffixArray(sa, text, LarssonSadakane(), maxChar + 1); // } // // inline typename Value::Type const & operator*() { // return *in; // } // // inline Pipe& operator++() { // ++in; // return *this; // } // }; // template < typename TInput > // inline bool control(Pipe< TInput, LarssonSadakane > &me, ControlBeginRead const &command) { // control(me.in, command); // ++me.in; // return true; // } // template < typename TInput > // inline typename Size< Pipe< TInput, LarssonSadakane > >::Type // length(Pipe< TInput, LarssonSadakane > const &me) { // return length(me.in) - 1; // } } #endif ugene-1.9.8/src/plugins_3rdparty/bowtie/src/bowtie/SeqAn-1.1/seqan/index/index_find.h0000644000175000017500000002014611651544326026777 0ustar ilyailya /*========================================================================== SeqAn - The Library for Sequence Analysis http://www.seqan.de ============================================================================ Copyright (C) 2007 This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. ============================================================================ $Id: index_find.h,v 1.1 2008/08/25 16:20:05 langmead Exp $ ==========================================================================*/ #ifndef SEQAN_HEADER_INDEX_FIND_H #define SEQAN_HEADER_INDEX_FIND_H namespace SEQAN_NAMESPACE_MAIN { ////////////////////////////////////////////////////////////////////////////// template < typename TText, typename TSpec, typename TSpecFinder > struct Position< Finder< Index, TSpecFinder > >: SAValue< Index > {}; ////////////////////////////////////////////////////////////////////////////// // generic Finder class for all indices containing a suffix array or // similar table, where a query result is an interval in this table // // your index must specialize the function _findFirstIndex and set // finder.range to the interval containing the query hits. See: // // template < typename TText, typename TSpec, typename TSpecFinder, typename TPattern > // inline void _findFirstIndex( // Finder< Index, TSpecFinder > &finder, // TPattern const &pattern, // ESA_FIND_MLR const) // { // Index &index = haystack(finder); // indexRequire(index, ESA_SA()); // finder.range = equalRangeSAIterator(indexText(index), indexSA(index), pattern); // } template < typename TText, typename TSpec, typename TSpecFinder > class Finder< Index, TSpecFinder > { protected: typedef Index TIndex; typedef typename Fibre::Type TSA; typedef typename Iterator::Type TIterator; public: Holder index; Pair range; TIterator data_iterator; Finder() { clear(*this); } Finder(TIndex &_index): index(_index) { clear(*this); } Finder(TIndex const &_index): index(_index) { clear(*this); } }; //____________________________________________________________________________ template < typename TText, typename TSpec, typename TSpecFinder > inline typename _Parameter< Index >::Type host(Finder< Index, TSpecFinder > & me) { SEQAN_CHECKPOINT return value(me.index); } template < typename TText, typename TSpec, typename TSpecFinder > inline typename _Parameter< Index >::Type host(Finder< Index, TSpecFinder > const & me) { SEQAN_CHECKPOINT return value(me.index); } template < typename TText, typename TSpec, typename TSpecFinder > inline typename _Parameter< Index >::Type container(Finder< Index, TSpecFinder > & me) { SEQAN_CHECKPOINT return value(me.index); } template < typename TText, typename TSpec, typename TSpecFinder > inline typename _Parameter< Index >::Type container(Finder< Index, TSpecFinder > const & me) { SEQAN_CHECKPOINT return value(me.index); } //____________________________________________________________________________ template < typename TText, typename TSpec, typename TSpecFinder > inline void setHost( Finder< Index, TSpecFinder > & me, typename _Parameter >::Type container_) { SEQAN_CHECKPOINT me.index = container; } template < typename TText, typename TSpec, typename TSpecFinder > inline void setContainer( Finder< Index, TSpecFinder > & me, typename _Parameter >::Type container_) { SEQAN_CHECKPOINT me.index = container; } //____________________________________________________________________________ template < typename TText, typename TSpec, typename TSpecFinder > inline typename Iterator< typename Fibre, Fibre_SA>::Type, Standard>::Type & hostIterator(Finder< Index, TSpecFinder > & me) { SEQAN_CHECKPOINT return me.data_iterator; } template < typename TText, typename TSpec, typename TSpecFinder > inline typename Iterator< typename Fibre, Fibre_SA>::Type, Standard>::Type const & hostIterator(Finder< Index, TSpecFinder > const & me) { SEQAN_CHECKPOINT return me.data_iterator; } //____________________________________________________________________________ template < typename TText, typename TSpec, typename TSpecFinder > inline bool empty(Finder< Index, TSpecFinder > & me) { SEQAN_CHECKPOINT return me.range.i1 == me.range.i2; } template < typename TText, typename TSpec, typename TSpecFinder > inline void clear(Finder< Index, TSpecFinder > & me) { SEQAN_CHECKPOINT typedef Index TIndex; typedef typename Fibre::Type TSA; typedef typename Iterator::Type TIterator; me.range.i1 = me.range.i2 = TIterator(); } //____________________________________________________________________________ template < typename TText, typename TSpec, typename TSpecFinder > inline bool atBegin(Finder< Index, TSpecFinder > & me) { SEQAN_CHECKPOINT return (empty(me) || hostIterator(me) == me.range.i1); } template < typename TText, typename TSpec, typename TSpecFinder > inline bool atEnd(Finder< Index, TSpecFinder > & me) { SEQAN_CHECKPOINT return (empty(me) || hostIterator(me) == me.range.i2); } //____________________________________________________________________________ template < typename TText, typename TSpec, typename TSpecFinder > inline void goBegin(Finder< Index, TSpecFinder > & me) { SEQAN_CHECKPOINT hostIterator(me) = me.range.i1; } template < typename TText, typename TSpec, typename TSpecFinder > inline void goEnd(Finder< Index, TSpecFinder > & me) { SEQAN_CHECKPOINT hostIterator(me) = me.range.i2; } //____________________________________________________________________________ /* template < typename TText, typename TSpec, typename TSpecFinder, typename TPosition > inline void setPosition(Finder< Index, TSpecFinder > & me, TPosition pos_) { SEQAN_CHECKPOINT hostIterator(me) = me.range.i1 + pos_; } */ //____________________________________________________________________________ template < typename TText, typename TSpec, typename TSpecFinder > inline typename Position< Finder< Index, TSpecFinder > >::Type position(Finder< Index, TSpecFinder > & me) { SEQAN_CHECKPOINT SEQAN_ASSERT(!empty(me)) return *me.data_iterator; } template < typename TText, typename TSpec, typename TSpecFinder > inline typename Position< Finder< Index, TSpecFinder > >::Type position(Finder< Index, TSpecFinder > const & me) { SEQAN_CHECKPOINT SEQAN_ASSERT(!empty(me)) return hostIterator(me) - begin(container(me), Rooted()); } ////////////////////////////////////////////////////////////////////////////// // find template < typename TText, typename TSpec, typename TSpecFinder, typename TPattern > inline bool find( Finder, TSpecFinder> &finder, TPattern const &pattern) { if (empty(finder)) { _findFirstIndex(finder, needle(pattern), TSpecFinder()); hostIterator(finder) = finder.range.i1; } else ++hostIterator(finder); return !atEnd(finder); } template < typename TText, typename TSpec, typename TSpecFinder > inline bool find(Finder, TSpecFinder> &finder) { if (empty(finder)) return false; ++hostIterator(finder); return !atEnd(finder); } } #endif ugene-1.9.8/src/plugins_3rdparty/bowtie/src/bowtie/SeqAn-1.1/seqan/index/shape_gapped.h0000644000175000017500000004065211651544326027314 0ustar ilyailya /*========================================================================== SeqAn - The Library for Sequence Analysis http://www.seqan.de ============================================================================ Copyright (C) 2007 This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. ============================================================================ $Id: shape_gapped.h,v 1.1 2008/08/25 16:20:05 langmead Exp $ ==========================================================================*/ #ifndef SEQAN_HEADER_SHAPE_GAPPED_H #define SEQAN_HEADER_SHAPE_GAPPED_H namespace SEQAN_NAMESPACE_MAIN { ////////////////////////////////////////////////////////////////////////////// // HardwiredShape allows compiler-time defined gapped shape /** .Class.HardwiredShape: ..cat:Index ..summary:A structure to define a fixed gapped shape. ..signature:HardwiredShape ..param.P1, P2, ..., Pn:Px is the distance of the x'th '1' to the next '1' in the shape. ...remarks:At most 20 parameters are allowed, so the maximal shape weight is 21. ..remarks:You can use this structure to define your one gapped shapes in conjunction with @Spec.FixedGappedShape@. ..note:The shape $1100101$ corresponds to $HardwiredShape<1,3,2>$. ..note:The following predefined shapes are already available in $seqan/index/shape_predefined.h$: ..file:../projects/library/seqan/index/shape_predefined.h */ // Pxx = spaces between '1's template < int P00 = 0, int P01 = 0, int P02 = 0, int P03 = 0, int P04 = 0, int P05 = 0, int P06 = 0, int P07 = 0, int P08 = 0, int P09 = 0, int P10 = 0, int P11 = 0, int P12 = 0, int P13 = 0, int P14 = 0, int P15 = 0, int P16 = 0, int P17 = 0, int P18 = 0, int P19 = 0 > struct HardwiredShape { static const int DIFFS[]; }; template < int P00, int P01, int P02, int P03, int P04, int P05, int P06, int P07, int P08, int P09, int P10, int P11, int P12, int P13, int P14, int P15, int P16, int P17, int P18, int P19 > const int HardwiredShape< P00,P01,P02,P03,P04, P05,P06,P07,P08,P09, P10,P11,P12,P13,P14, P15,P16,P17,P18,P19 >::DIFFS[] = { P00,P01,P02,P03,P04, P05,P06,P07,P08,P09, P10,P11,P12,P13,P14, P15,P16,P17,P18,P19, 0 }; ////////////////////////////////////////////////////////////////////////////// // LENGTH meta-function for fixed gapped shapes template <> struct LENGTH< HardwiredShape< 0,0,0,0,0, 0,0,0,0,0, 0,0,0,0,0, 0,0,0,0,0> > { enum { VALUE = 1 }; }; template < int P00, int P01, int P02, int P03, int P04, int P05, int P06, int P07, int P08, int P09, int P10, int P11, int P12, int P13, int P14, int P15, int P16, int P17, int P18, int P19 > struct LENGTH< HardwiredShape< P00,P01,P02,P03,P04, P05,P06,P07,P08,P09, P10,P11,P12,P13,P14, P15,P16,P17,P18,P19> > { enum { VALUE = LENGTH< HardwiredShape< P01,P02,P03,P04,P05, P06,P07,P08,P09,P10, P11,P12,P13,P14,P15, P16,P17,P18,P19, 0 > >::VALUE + P00 }; }; template < typename TValue, int P00, int P01, int P02, int P03, int P04, int P05, int P06, int P07, int P08, int P09, int P10, int P11, int P12, int P13, int P14, int P15, int P16, int P17, int P18, int P19 > struct LENGTH< Shape > > >: LENGTH< HardwiredShape< P00,P01,P02,P03,P04, P05,P06,P07,P08,P09, P10,P11,P12,P13,P14, P15,P16,P17,P18,P19 > > {}; ////////////////////////////////////////////////////////////////////////////// // WEIGHT meta-function for fixed gapped shapes template <> struct WEIGHT< HardwiredShape< 0,0,0,0,0, 0,0,0,0,0, 0,0,0,0,0, 0,0,0,0,0> > { enum { VALUE = 1 }; }; template < int P00, int P01, int P02, int P03, int P04, int P05, int P06, int P07, int P08, int P09, int P10, int P11, int P12, int P13, int P14, int P15, int P16, int P17, int P18, int P19 > struct WEIGHT< HardwiredShape< P00,P01,P02,P03,P04, P05,P06,P07,P08,P09, P10,P11,P12,P13,P14, P15,P16,P17,P18,P19> > { enum { VALUE = WEIGHT< HardwiredShape< P01,P02,P03,P04,P05, P06,P07,P08,P09,P10, P11,P12,P13,P14,P15, P16,P17,P18,P19, 0 > >::VALUE + 1 }; }; template < typename TValue, int P00, int P01, int P02, int P03, int P04, int P05, int P06, int P07, int P08, int P09, int P10, int P11, int P12, int P13, int P14, int P15, int P16, int P17, int P18, int P19 > struct WEIGHT< Shape > > >: WEIGHT< HardwiredShape< P00,P01,P02,P03,P04, P05,P06,P07,P08,P09, P10,P11,P12,P13,P14, P15,P16,P17,P18,P19 > > {}; ////////////////////////////////////////////////////////////////////////////// /** .Spec.GappedShape: ..cat:Index ..summary:A variable gapped shape. ..general:Class.Shape ..signature:Shape ..param.TValue:The @Metafunction.Value@ type of the string the shape is applied to (e.g. $Dna$). ..remarks:A GappedShape must be initialized first with a valid shape. To do so, call @Function.stringToShape@. ..see:Spec.FixedGappedShape */ ////////////////////////////////////////////////////////////////////////////// // variable gapped shape ////////////////////////////////////////////////////////////////////////////// template class Shape { public: //____________________________________________________________________________ unsigned span; unsigned weight; String diffs; typename Value::Type hValue; // current hash value //____________________________________________________________________________ /** .Memfunc.GappedShape#Shape: ..class:Spec.GappedShape ..summary:Constructor ..signature:Shape () ..signature:Shape (q) ..signature:Shape (shape) ..signature:Shape (predefined) ..param.q:Creates an ungapped q-gram. ..param.shape:Any other gapped/ungapped shape. ..param.predefined:Any instance of a predefined shape spec (e.g. $ShapePatternHunter$). ..see:Class.HardwiredShape */ Shape() {} // c'tor for ungapped shapes Shape(unsigned _span): span(_span), weight(_span) { SEQAN_CHECKPOINT resize(diffs, _span); for(unsigned i = 0; i < _span; ++i) diffs[i] = 1; } Shape(Shape const &other): span(other.span), weight(other.weight), diffs(other.diffs), hValue(other.hValue) {} template Shape(Shape const &other) { *this = other; } template Shape(FixedGappedShape const &other) { *this = other; } template Shape(String const &bitmap) { *this = bitmap; } //____________________________________________________________________________ template inline Shape & operator=(Shape > const &other) { span = length(other); weight = weight(other); resize(diffs, weight); for(unsigned i = 1; i < weight; ++i) diffs[i] = 1; hValue = other.hValue; return *this; } template inline Shape & operator=(Shape > const &other) { span = other.span; weight = other.weight; diffs = other.diffs; hValue = other.hValue; return *this; } template inline Shape & operator=(FixedGappedShape const) { typedef Shape > TShape; return *this = TShape(); } template inline Shape & operator=(String const &bitmap) { stringToShape(*this, bitmap); return *this; } }; ////////////////////////////////////////////////////////////////////////////// /** .Spec.FixedGappedShape: ..cat:Index ..summary:A fixed gapped shape. ..general:Class.Shape ..signature:Shape > ..param.TValue:The @Metafunction.Value@ type of the string the shape is applied to (e.g. $Dna$). ..param.TSpec:A structure to store the shape at compile-time. ...type:Class.HardwiredShape ..remarks:There are predefined shapes in $index/shape_predefined.h$. You can simply use them with $Shape$ for example. ..see:Class.HardwiredShape */ ////////////////////////////////////////////////////////////////////////////// // fixed gapped shape ////////////////////////////////////////////////////////////////////////////// template class Shape > { public: //____________________________________________________________________________ typedef FixedGappedShape TShapeSpec; enum { span = LENGTH::VALUE }; enum { weight = WEIGHT::VALUE }; const int *diffs; typename Value::Type hValue; // current hash value //____________________________________________________________________________ Shape(): diffs(TSpec::DIFFS) {} Shape(Shape const &other): diffs(other.diffs), hValue(other.hValue) {} //____________________________________________________________________________ inline Shape & operator=(Shape const &other) { hValue = other.hValue; } }; ////////////////////////////////////////////////////////////////////////////// template inline typename Size< Shape > >::Type weight(Shape > const & me) { SEQAN_CHECKPOINT return me.weight; } //____________________________________________________________________________ template inline typename Value< Shape >::Type hash(Shape &me, TIter it) { SEQAN_CHECKPOINT typedef typename Value< Shape >::Type THValue; typedef typename Size< Shape >::Type TSize; me.hValue = ordValue((TValue)*it); TSize iEnd = me.weight - 1; for(TSize i = 0; i < iEnd; ++i) { goFurther(it, me.diffs[i]); me.hValue = me.hValue * ValueSize::VALUE + ordValue((TValue)*it); } return me.hValue; } template inline typename Value< Shape > >::Type hash(Shape > &me, TIter it, TSize charsLeft) { SEQAN_CHECKPOINT typedef typename Value< Shape > >::Type THValue; TSize iEnd = me.weight; if (iEnd > charsLeft) iEnd = charsLeft; TSize i = 0; if (iEnd > 0) { me.hValue = ordValue((TValue)*it); --iEnd; for(; i < iEnd; ++i) { goFurther(it, me.diffs[i]); me.hValue = me.hValue * ValueSize::VALUE + ordValue((TValue)*it); } ++i; } else return me.hValue = 0; // fill shape with zeros for(; i < (TSize)me.weight; ++i) me.hValue *= ValueSize::VALUE; return me.hValue; } template inline typename Value< Shape > >::Type hashUpper(Shape > &me, TIter it, TSize charsLeft) { SEQAN_CHECKPOINT typedef typename Value< Shape > >::Type THValue; TSize iEnd = me.weight; if (iEnd > charsLeft) iEnd = charsLeft; TSize i = 0; if (iEnd > 0) { me.hValue = ordValue((TValue)*it); --iEnd; for(; i < iEnd; ++i) { goFurther(it, me.diffs[i]); me.hValue = me.hValue * ValueSize::VALUE + ordValue((TValue)*it); } ++i; ++me.hValue; } else return me.hValue = 1; // fill shape with zeros for(; i < (TSize)me.weight; ++i) me.hValue *= ValueSize::VALUE; return me.hValue; } //____________________________________________________________________________ template inline THValue _hashHardwiredShape(THValue hash, TIter &, TValue const, HardwiredShape< 0,0,0,0,0, 0,0,0,0,0, 0,0,0,0,0, 0,0,0,0,0 > const) { return hash; } template < int P01, int P02, int P03, int P04, int P05, int P06, int P07, int P08, int P09, int P10, int P11, int P12, int P13, int P14, int P15, int P16, int P17, int P18, int P19, typename THValue, typename TValue, typename TIter > inline THValue _hashHardwiredShape(THValue hash, TIter &it, TValue const, HardwiredShape< 1 ,P01,P02,P03,P04, P05,P06,P07,P08,P09, P10,P11,P12,P13,P14, P15,P16,P17,P18,P19 > const) { ++it; return _hashHardwiredShape(hash * ValueSize::VALUE + ordValue((TValue)*it), it, TValue(), HardwiredShape< P01,P02,P03,P04,P05, P06,P07,P08,P09,P10, P11,P12,P13,P14,P15, P16,P17,P18,P19, 0 >()); } template < int P00, int P01, int P02, int P03, int P04, int P05, int P06, int P07, int P08, int P09, int P10, int P11, int P12, int P13, int P14, int P15, int P16, int P17, int P18, int P19, typename THValue, typename TValue, typename TIter > inline THValue _hashHardwiredShape(THValue hash, TIter &it, TValue const, HardwiredShape< P00,P01,P02,P03,P04, P05,P06,P07,P08,P09, P10,P11,P12,P13,P14, P15,P16,P17,P18,P19 > const) { it += P00; return _hashHardwiredShape(hash * ValueSize::VALUE + ordValue((TValue)*it), it, TValue(), HardwiredShape< P01,P02,P03,P04,P05, P06,P07,P08,P09,P10, P11,P12,P13,P14,P15, P16,P17,P18,P19, 0 >()); } template < int P00, int P01, int P02, int P03, int P04, int P05, int P06, int P07, int P08, int P09, int P10, int P11, int P12, int P13, int P14, int P15, int P16, int P17, int P18, int P19, typename TValue, typename TIter > inline typename Value< Shape > > >::Type hash(Shape > > &me, TIter it) { SEQAN_CHECKPOINT typedef HardwiredShape< P00,P01,P02,P03,P04, P05,P06,P07,P08,P09, P10,P11,P12,P13,P14, P15,P16,P17,P18,P19 > TSpec; typedef FixedGappedShape TShape; typedef typename Value< Shape >::Type THValue; me.hValue = (THValue)ordValue((TValue)*it); return me.hValue = _hashHardwiredShape(me.hValue, it, TValue(), TSpec()); } //____________________________________________________________________________ template inline typename Value< Shape > >::Type hashNext(Shape > &me, TIter it) { SEQAN_CHECKPOINT return hash(me, it); } //____________________________________________________________________________ /**.Function.stringToShape: ..cat:Index ..summary:Takes a shape given as a string of '1' (relevant position) and '0' (irrelevant position) and converts it into a Shape object. ..signature:stringToShape(shape, bitmap) ..param.shape:Shape object that is manipulated. ...type:Spec.GappedShape ..param.bitmap:A character string of '1' and '0' representing relevant and irrelevant positions (blanks) respectively. ...remarks:This string must begin with a '1'. ...type:Class.String */ template inline void stringToShape( Shape > &me, TShapeString const &bitmap) { SEQAN_CHECKPOINT typedef typename Iterator::Type TIter; typedef typename Iterator >::Type TShapeIter; me.span = length(bitmap); unsigned oneCount = 0; TIter it = begin(bitmap, Standard()); TIter itEnd = end(bitmap, Standard()); for(; it != itEnd; ++it) if (*it == '1') ++oneCount; me.weight = oneCount; resize(me.diffs, oneCount); unsigned diff = 0; it = begin(bitmap, Standard()); TShapeIter itS = begin(me.diffs, Standard()); for(; it != itEnd; ++it) { if (*it == '1') { *itS = diff; ++itS; diff = 0; } ++diff; } } } // namespace seqan #endif ugene-1.9.8/src/plugins_3rdparty/bowtie/src/bowtie/SeqAn-1.1/seqan/index/index_generated_forwards.h0000644000175000017500000057244611651544326031743 0ustar ilyailya /*========================================================================== SeqAn - The Library for Sequence Analysis http://www.seqan.de ============================================================================ Copyright (C) 2007 This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. ==========================================================================*/ #ifndef SEQAN_HEADER_INDEX_GENERATED_FORWARDS_H #define SEQAN_HEADER_INDEX_GENERATED_FORWARDS_H ////////////////////////////////////////////////////////////////////////////// // NOTE: This file is automatically generated by build_forwards.py // Do not edit this file manually! ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// // CLASSES ////////////////////////////////////////////////////////////////////////////// namespace SEQAN_NAMESPACE_MAIN { namespace impl { //____________________________________________________________________________ // substringHelperPizzaChili template struct substringHelperPizzaChili; // "projects/library/seqan/index/index_pizzachili_string.h"(520) } //namespace impl } //namespace SEQAN_NAMESPACE_MAIN ////////////////////////////////////////////////////////////////////////////// namespace SEQAN_NAMESPACE_MAIN { //____________________________________________________________________________ // Align template class Align; // "projects/library/seqan/index/index_esa_base.h"(189) //____________________________________________________________________________ // ArrayGaps struct ArrayGaps; // "projects/library/seqan/index/index_esa_base.h"(186) //____________________________________________________________________________ // BTree template struct BTree; // "projects/library/seqan/index/index_esa_find.h"(70) //____________________________________________________________________________ // BWT struct BWT; // "projects/library/seqan/index/index_base.h"(46) struct BWT; // "projects/library/seqan/index/index_bwt.h"(30) //____________________________________________________________________________ // BottomUp template struct BottomUp; // "projects/library/seqan/index/index_esa_base.h"(125) //____________________________________________________________________________ // ChildTab struct ChildTab; // "projects/library/seqan/index/index_childtab.h"(30) struct ChildTab; // "projects/library/seqan/index/index_base.h"(45) //____________________________________________________________________________ // CompareSkewDCStream template struct CompareSkewDCStream; // "projects/library/seqan/index/pipe_merger7.h"(95) //____________________________________________________________________________ // DeepShallow struct DeepShallow; // "projects/library/seqan/index/index_shawarma.h"(42) //____________________________________________________________________________ // DefaultIndexCreator template struct DefaultIndexCreator; // "projects/library/seqan/index/index_base.h"(177) //____________________________________________________________________________ // DefaultIndexSpec template struct DefaultIndexSpec; // "projects/library/seqan/index/index_base.h"(63) //____________________________________________________________________________ // DefaultIndexStringSpec template struct DefaultIndexStringSpec; // "projects/library/seqan/index/index_base.h"(78) //____________________________________________________________________________ // DivSufSort struct DivSufSort; // "projects/library/seqan/index/index_shawarma.h"(41) //____________________________________________________________________________ // EmptyEdges struct EmptyEdges; // "projects/library/seqan/index/index_esa_base.h"(102) //____________________________________________________________________________ // Extender3 struct Extender3; // "projects/library/seqan/index/pump_extender3.h"(30) //____________________________________________________________________________ // Extender7 template struct Extender7; // "projects/library/seqan/index/pump_extender7.h"(33) //____________________________________________________________________________ // Extender7Multi template struct Extender7Multi; // "projects/library/seqan/index/pump_extender7.h"(228) //____________________________________________________________________________ // Fibre template struct Fibre; // "projects/library/seqan/index/index_base.h"(141) //____________________________________________________________________________ // FibreLess struct FibreLess; // "projects/library/seqan/index/index_base.h"(158) //____________________________________________________________________________ // FibreRecord struct FibreRecord; // "projects/library/seqan/index/index_base.h"(150) //____________________________________________________________________________ // FixedGappedShape template struct FixedGappedShape; // "projects/library/seqan/index/shape_base.h"(32) //____________________________________________________________________________ // FixedShape template struct FixedShape; // "projects/library/seqan/index/shape_base.h"(28) //____________________________________________________________________________ // FunctorGlobalize template struct FunctorGlobalize; // "projects/library/seqan/index/index_base.h"(386) //____________________________________________________________________________ // GetVSTreeIteratorTraits template struct GetVSTreeIteratorTraits; // "projects/library/seqan/index/index_esa_base.h"(148) //____________________________________________________________________________ // HardwiredShape template struct HardwiredShape; // "projects/library/seqan/index/shape_gapped.h"(50) //____________________________________________________________________________ // HideEmptyEdges struct HideEmptyEdges; // "projects/library/seqan/index/index_esa_base.h"(101) //____________________________________________________________________________ // Index template class Index; // "projects/library/seqan/index/index_base.h"(114) //____________________________________________________________________________ // Index_ESA template struct Index_ESA; // "projects/library/seqan/index/index_base.h"(49) //____________________________________________________________________________ // Index_QGram template struct Index_QGram; // "projects/library/seqan/index/index_qgram.h"(100) //____________________________________________________________________________ // Index_Wotd template struct Index_Wotd; // "projects/library/seqan/index/index_wotd.h"(56) //____________________________________________________________________________ // InvalidPizzaChiliSpec struct InvalidPizzaChiliSpec; // "projects/library/seqan/index/pizzachili_api.h"(37) //____________________________________________________________________________ // Kasai struct Kasai; // "projects/library/seqan/index/index_base.h"(41) struct Kasai; // "projects/library/seqan/index/index_lcp.h"(30) //____________________________________________________________________________ // KasaiOriginal struct KasaiOriginal; // "projects/library/seqan/index/index_base.h"(42) struct KasaiOriginal; // "projects/library/seqan/index/index_lcp.h"(31) //____________________________________________________________________________ // LarssonSadakane struct LarssonSadakane; // "projects/library/seqan/index/index_sa_lss.h"(336) struct LarssonSadakane; // "projects/library/seqan/index/index_base.h"(35) //____________________________________________________________________________ // LcpConfig struct LcpConfig; // "projects/library/seqan/index/pump_lcp_core.h"(31) //____________________________________________________________________________ // LeftCompleteTree struct LeftCompleteTree; // "projects/library/seqan/index/index_esa_find.h"(67) //____________________________________________________________________________ // MSufSort struct MSufSort; // "projects/library/seqan/index/index_shawarma.h"(40) //____________________________________________________________________________ // MUMs struct MUMs; // "projects/library/seqan/index/index_esa_base.h"(129) //____________________________________________________________________________ // ManberMyers struct ManberMyers; // "projects/library/seqan/index/index_sa_mm.h"(27) struct ManberMyers; // "projects/library/seqan/index/index_base.h"(36) //____________________________________________________________________________ // MaxRepeat template struct MaxRepeat; // "projects/library/seqan/index/index_esa_algs.h"(602) //____________________________________________________________________________ // MaxRepeatOccurrences struct MaxRepeatOccurrences; // "projects/library/seqan/index/index_esa_base.h"(132) //____________________________________________________________________________ // Merger3 struct Merger3; // "projects/library/seqan/index/pipe_merger3.h"(30) //____________________________________________________________________________ // Merger7 struct Merger7; // "projects/library/seqan/index/pipe_merger7.h"(178) //____________________________________________________________________________ // Merger7Multi template struct Merger7Multi; // "projects/library/seqan/index/pipe_merger7.h"(187) //____________________________________________________________________________ // MultiMEM template struct MultiMEM; // "projects/library/seqan/index/index_esa_algs_multi.h"(385) //____________________________________________________________________________ // MultiMEMOccurences struct MultiMEMOccurences; // "projects/library/seqan/index/index_esa_base.h"(134) //____________________________________________________________________________ // ParentLinks template struct ParentLinks; // "projects/library/seqan/index/index_esa_base.h"(121) //____________________________________________________________________________ // PizzaChili template struct PizzaChili; // "projects/library/seqan/index/index_pizzachili_string.h"(47) //____________________________________________________________________________ // PizzaChiliCodeProvider template struct PizzaChiliCodeProvider; // "projects/library/seqan/index/pizzachili_api.h"(40) //____________________________________________________________________________ // Postorder struct Postorder; // "projects/library/seqan/index/index_esa_base.h"(96) //____________________________________________________________________________ // PostorderEmptyEdges struct PostorderEmptyEdges; // "projects/library/seqan/index/index_esa_base.h"(98) //____________________________________________________________________________ // Preorder struct Preorder; // "projects/library/seqan/index/index_esa_base.h"(95) //____________________________________________________________________________ // PreorderEmptyEdges struct PreorderEmptyEdges; // "projects/library/seqan/index/index_esa_base.h"(97) //____________________________________________________________________________ // QGram_Alg struct QGram_Alg; // "projects/library/seqan/index/index_base.h"(38) //____________________________________________________________________________ // QSufSort struct QSufSort; // "projects/library/seqan/index/index_shawarma.h"(43) //____________________________________________________________________________ // Repeat template struct Repeat; // "projects/library/seqan/index/repeat_base.h"(28) //____________________________________________________________________________ // RepeatFinderParams template struct RepeatFinderParams; // "projects/library/seqan/index/repeat_base.h"(47) //____________________________________________________________________________ // SAQSort struct SAQSort; // "projects/library/seqan/index/index_base.h"(37) struct SAQSort; // "projects/library/seqan/index/index_sa_qsort.h"(27) //____________________________________________________________________________ // SAValue template struct SAValue; // "projects/library/seqan/index/index_base.h"(288) //____________________________________________________________________________ // SearchTreeIterator template class SearchTreeIterator; // "projects/library/seqan/index/index_esa_find.h"(73) //____________________________________________________________________________ // Shape template class Shape; // "projects/library/seqan/index/shape_base.h"(54) //____________________________________________________________________________ // Shawarma template struct Shawarma; // "projects/library/seqan/index/index_shawarma.h"(38) //____________________________________________________________________________ // Skew3 struct Skew3; // "projects/library/seqan/index/index_base.h"(33) struct Skew3; // "projects/library/seqan/index/index_skew3.h"(30) //____________________________________________________________________________ // Skew7 struct Skew7; // "projects/library/seqan/index/index_base.h"(34) struct Skew7; // "projects/library/seqan/index/index_skew7.h"(30) //____________________________________________________________________________ // SkewDCStream template struct SkewDCStream; // "projects/library/seqan/index/pipe_merger7.h"(71) //____________________________________________________________________________ // SortedList struct SortedList; // "projects/library/seqan/index/index_esa_find.h"(66) //____________________________________________________________________________ // SuperMaxRepeats struct SuperMaxRepeats; // "projects/library/seqan/index/index_esa_base.h"(127) //____________________________________________________________________________ // SuperMaxRepeatsFast struct SuperMaxRepeatsFast; // "projects/library/seqan/index/index_esa_base.h"(128) //____________________________________________________________________________ // TRepeatFinder struct TRepeatFinder; // "projects/library/seqan/index/repeat_base.h"(53) //____________________________________________________________________________ // TopDown template struct TopDown; // "projects/library/seqan/index/index_esa_base.h"(117) //____________________________________________________________________________ // VSTree template struct VSTree; // "projects/library/seqan/index/index_esa_base.h"(113) //____________________________________________________________________________ // VSTreeIteratorTraits template struct VSTreeIteratorTraits; // "projects/library/seqan/index/index_esa_base.h"(32) //____________________________________________________________________________ // VertexESA template struct VertexESA; // "projects/library/seqan/index/index_esa_base.h"(153) //____________________________________________________________________________ // WotdDFI template struct WotdDFI; // "projects/library/seqan/index/index_dfi.h"(74) //____________________________________________________________________________ // WotdOriginal_ struct WotdOriginal_; // "projects/library/seqan/index/index_wotd.h"(52) //____________________________________________________________________________ // _AllocHelper template struct _AllocHelper; // "projects/library/seqan/index/index_pizzachili_string.h"(283) //____________________________________________________________________________ // _Context_LSS template struct _Context_LSS; // "projects/library/seqan/index/index_sa_lss.h"(40) //____________________________________________________________________________ // _DFIEntry struct _DFIEntry; // "projects/library/seqan/index/index_dfi.h"(32) //____________________________________________________________________________ // _DFIPredDefault template struct _DFIPredDefault; // "projects/library/seqan/index/index_dfi.h"(44) //____________________________________________________________________________ // _Fibre_BWT struct _Fibre_BWT; // "projects/library/seqan/index/index_base.h"(245) //____________________________________________________________________________ // _Fibre_ChildTab struct _Fibre_ChildTab; // "projects/library/seqan/index/index_base.h"(244) //____________________________________________________________________________ // _Fibre_Counts struct _Fibre_Counts; // "projects/library/seqan/index/index_qgram.h"(64) //____________________________________________________________________________ // _Fibre_CountsDir struct _Fibre_CountsDir; // "projects/library/seqan/index/index_qgram.h"(65) //____________________________________________________________________________ // _Fibre_Dir struct _Fibre_Dir; // "projects/library/seqan/index/index_qgram.h"(61) //____________________________________________________________________________ // _Fibre_LCP struct _Fibre_LCP; // "projects/library/seqan/index/index_base.h"(242) //____________________________________________________________________________ // _Fibre_LCPE struct _Fibre_LCPE; // "projects/library/seqan/index/index_base.h"(243) //____________________________________________________________________________ // _Fibre_PizzaChili_Compressed struct _Fibre_PizzaChili_Compressed; // "projects/library/seqan/index/index_pizzachili.h"(41) //____________________________________________________________________________ // _Fibre_RawSA struct _Fibre_RawSA; // "projects/library/seqan/index/index_base.h"(240) //____________________________________________________________________________ // _Fibre_RawText struct _Fibre_RawText; // "projects/library/seqan/index/index_base.h"(238) //____________________________________________________________________________ // _Fibre_SA struct _Fibre_SA; // "projects/library/seqan/index/index_base.h"(239) //____________________________________________________________________________ // _Fibre_SADir struct _Fibre_SADir; // "projects/library/seqan/index/index_qgram.h"(62) //____________________________________________________________________________ // _Fibre_SAE struct _Fibre_SAE; // "projects/library/seqan/index/index_base.h"(241) //____________________________________________________________________________ // _Fibre_Shape struct _Fibre_Shape; // "projects/library/seqan/index/index_qgram.h"(63) //____________________________________________________________________________ // _Fibre_Text struct _Fibre_Text; // "projects/library/seqan/index/index_base.h"(237) //____________________________________________________________________________ // _Finder_LCPE struct _Finder_LCPE; // "projects/library/seqan/index/index_esa_find.h"(49) //____________________________________________________________________________ // _Finder_MLR struct _Finder_MLR; // "projects/library/seqan/index/index_esa_find.h"(48) //____________________________________________________________________________ // _Finder_QGramLookup struct _Finder_QGramLookup; // "projects/library/seqan/index/index_qgram_find.h"(30) //____________________________________________________________________________ // _FractionCompound template struct _FractionCompound; // "projects/library/seqan/index/index_esa_algs.h"(250) //____________________________________________________________________________ // _FractionHeader template struct _FractionHeader; // "projects/library/seqan/index/index_esa_algs.h"(239) //____________________________________________________________________________ // _FractionMultiCompound template struct _FractionMultiCompound; // "projects/library/seqan/index/index_esa_algs_multi.h"(132) //____________________________________________________________________________ // _HistoryStackEntry template struct _HistoryStackEntry; // "projects/library/seqan/index/index_esa_stree.h"(125) //____________________________________________________________________________ // _HistoryStackWotdModified template struct _HistoryStackWotdModified; // "projects/library/seqan/index/index_wotd.h"(209) //____________________________________________________________________________ // _HistoryStackWotdOriginal template struct _HistoryStackWotdOriginal; // "projects/library/seqan/index/index_wotd.h"(202) //____________________________________________________________________________ // _MaxRepeats template struct _MaxRepeats; // "projects/library/seqan/index/index_esa_base.h"(106) //____________________________________________________________________________ // _MultiMEMs struct _MultiMEMs; // "projects/library/seqan/index/index_esa_base.h"(107) //____________________________________________________________________________ // _PizzaChiliFinder struct _PizzaChiliFinder; // "projects/library/seqan/index/index_pizzachili_find.h"(26) //____________________________________________________________________________ // _PizzaChili_AF struct _PizzaChili_AF; // "projects/library/seqan/index/pizzachili_api.h"(67) //____________________________________________________________________________ // _PizzaChili_CCSA struct _PizzaChili_CCSA; // "projects/library/seqan/index/pizzachili_api.h"(70) //____________________________________________________________________________ // _PizzaChili_FM struct _PizzaChili_FM; // "projects/library/seqan/index/pizzachili_api.h"(73) //____________________________________________________________________________ // _PizzaChili_LZ struct _PizzaChili_LZ; // "projects/library/seqan/index/pizzachili_api.h"(76) //____________________________________________________________________________ // _PizzaChili_RLFM struct _PizzaChili_RLFM; // "projects/library/seqan/index/pizzachili_api.h"(82) //____________________________________________________________________________ // _PizzaChili_RSA struct _PizzaChili_RSA; // "projects/library/seqan/index/pizzachili_api.h"(79) //____________________________________________________________________________ // _PizzaChili_SA struct _PizzaChili_SA; // "projects/library/seqan/index/pizzachili_api.h"(85) //____________________________________________________________________________ // _PizzaChili_SADA struct _PizzaChili_SADA; // "projects/library/seqan/index/pizzachili_api.h"(88) //____________________________________________________________________________ // _PizzaChili_SSA struct _PizzaChili_SSA; // "projects/library/seqan/index/pizzachili_api.h"(91) //____________________________________________________________________________ // _PizzaChili_Test struct _PizzaChili_Test; // "projects/library/seqan/index/pizzachili_api.h"(94) //____________________________________________________________________________ // _Postorder struct _Postorder; // "projects/library/seqan/index/index_esa_base.h"(29) //____________________________________________________________________________ // _Preorder struct _Preorder; // "projects/library/seqan/index/index_esa_base.h"(28) //____________________________________________________________________________ // _QGramLess template struct _QGramLess; // "projects/library/seqan/index/index_qgram.h"(347) //____________________________________________________________________________ // _QGramLessNoCheck template struct _QGramLessNoCheck; // "projects/library/seqan/index/index_qgram.h"(506) //____________________________________________________________________________ // _QGramLessNoCheckOffset template struct _QGramLessNoCheckOffset; // "projects/library/seqan/index/index_qgram.h"(588) //____________________________________________________________________________ // _QGramLessOffset template struct _QGramLessOffset; // "projects/library/seqan/index/index_qgram.h"(442) //____________________________________________________________________________ // _RepeatLess template struct _RepeatLess; // "projects/library/seqan/index/repeat_base.h"(82) //____________________________________________________________________________ // _SAValueLess template struct _SAValueLess; // "projects/library/seqan/index/index_shims.h"(449) //____________________________________________________________________________ // _SkewNIndx template struct _SkewNIndx; // "projects/library/seqan/index/pipe_merger7.h"(34) //____________________________________________________________________________ // _SkewShift template struct _SkewShift; // "projects/library/seqan/index/pipe_merger7.h"(31) //____________________________________________________________________________ // _SuffixLess template struct _SuffixLess; // "projects/library/seqan/index/index_sa_qsort.h"(33) //____________________________________________________________________________ // _SuffixLessOffset template struct _SuffixLessOffset; // "projects/library/seqan/index/index_sa_qsort.h"(71) //____________________________________________________________________________ // _VertexWotdModified template struct _VertexWotdModified; // "projects/library/seqan/index/index_wotd.h"(163) //____________________________________________________________________________ // _VertexWotdOriginal template struct _VertexWotdOriginal; // "projects/library/seqan/index/index_wotd.h"(148) //____________________________________________________________________________ // _qgram_comp template struct _qgram_comp; // "projects/library/seqan/index/index_qgram.h"(1227) //____________________________________________________________________________ // _qgram_hash template struct _qgram_hash; // "projects/library/seqan/index/index_qgram.h"(1262) //____________________________________________________________________________ // filter_globalizer template struct filter_globalizer; // "projects/library/seqan/index/index_bwt.h"(130) //____________________________________________________________________________ // map_inverse template struct map_inverse; // "projects/library/seqan/index/index_lcp.h"(45) //____________________________________________________________________________ // map_inverse_multi template struct map_inverse_multi; // "projects/library/seqan/index/index_lcp.h"(148) //____________________________________________________________________________ // skew3_extend_comp template struct skew3_extend_comp; // "projects/library/seqan/index/index_skew3.h"(107) //____________________________________________________________________________ // skew3_ncomp template struct skew3_ncomp; // "projects/library/seqan/index/index_skew3.h"(49) //____________________________________________________________________________ // skew3_nmap_extended template struct skew3_nmap_extended; // "projects/library/seqan/index/index_skew3.h"(101) //____________________________________________________________________________ // skew3_nmap_linear template struct skew3_nmap_linear; // "projects/library/seqan/index/index_skew3.h"(72) //____________________________________________________________________________ // skew3_nmap_sliced template struct skew3_nmap_sliced; // "projects/library/seqan/index/index_skew3.h"(80) //____________________________________________________________________________ // skew3_unslicer_func template struct skew3_unslicer_func; // "projects/library/seqan/index/index_skew3.h"(89) //____________________________________________________________________________ // skew7_extend_comp template struct skew7_extend_comp; // "projects/library/seqan/index/index_skew7.h"(137) //____________________________________________________________________________ // skew7_global_sliced_multi template struct skew7_global_sliced_multi; // "projects/library/seqan/index/index_skew7_multi.h"(109) //____________________________________________________________________________ // skew7_ncomp template struct skew7_ncomp; // "projects/library/seqan/index/index_skew7.h"(49) //____________________________________________________________________________ // skew7_ncomp_multi template struct skew7_ncomp_multi; // "projects/library/seqan/index/index_skew7_multi.h"(42) //____________________________________________________________________________ // skew7_nmap_extended template struct skew7_nmap_extended; // "projects/library/seqan/index/index_skew7.h"(131) //____________________________________________________________________________ // skew7_nmap_linear template struct skew7_nmap_linear; // "projects/library/seqan/index/index_skew7.h"(91) //____________________________________________________________________________ // skew7_nmap_sliced template struct skew7_nmap_sliced; // "projects/library/seqan/index/index_skew7.h"(99) //____________________________________________________________________________ // skew7_unslicer_func template struct skew7_unslicer_func; // "projects/library/seqan/index/index_skew7.h"(115) } //namespace SEQAN_NAMESPACE_MAIN ////////////////////////////////////////////////////////////////////////////// // TYPEDEFS ////////////////////////////////////////////////////////////////////////////// namespace SEQAN_NAMESPACE_MAIN { namespace impl { //____________________________________________________________________________ // error_t typedef int error_t; // "projects/library/seqan/index/pizzachili_api.h"(34) //____________________________________________________________________________ // index_t typedef void* index_t; // "projects/library/seqan/index/pizzachili_api.h"(33) //____________________________________________________________________________ // uchar_t typedef unsigned char uchar_t; // "projects/library/seqan/index/pizzachili_api.h"(31) //____________________________________________________________________________ // ulong_t typedef unsigned long ulong_t; // "projects/library/seqan/index/pizzachili_api.h"(32) } //namespace impl } //namespace SEQAN_NAMESPACE_MAIN ////////////////////////////////////////////////////////////////////////////// namespace SEQAN_NAMESPACE_MAIN { //____________________________________________________________________________ // ESA_BWT typedef Fibre_BWT ESA_BWT; // "projects/library/seqan/index/index_esa_base.h"(239) //____________________________________________________________________________ // ESA_ChildTab typedef Fibre_ChildTab ESA_ChildTab; // "projects/library/seqan/index/index_esa_base.h"(238) //____________________________________________________________________________ // ESA_FIND_LCPE typedef Tag<_Finder_LCPE> const ESA_FIND_LCPE; // "projects/library/seqan/index/index_esa_find.h"(52) //____________________________________________________________________________ // ESA_FIND_MLR typedef Tag<_Finder_MLR> const ESA_FIND_MLR; // "projects/library/seqan/index/index_esa_find.h"(51) //____________________________________________________________________________ // ESA_LCP typedef Fibre_LCP ESA_LCP; // "projects/library/seqan/index/index_esa_base.h"(236) //____________________________________________________________________________ // ESA_LCPE typedef Fibre_LCPE ESA_LCPE; // "projects/library/seqan/index/index_esa_base.h"(237) //____________________________________________________________________________ // ESA_RawSA typedef Fibre_RawSA ESA_RawSA; // "projects/library/seqan/index/index_esa_base.h"(234) //____________________________________________________________________________ // ESA_RawText typedef Fibre_RawText ESA_RawText; // "projects/library/seqan/index/index_esa_base.h"(232) //____________________________________________________________________________ // ESA_SA typedef Fibre_SA ESA_SA; // "projects/library/seqan/index/index_esa_base.h"(233) //____________________________________________________________________________ // ESA_SAE typedef Fibre_SAE ESA_SAE; // "projects/library/seqan/index/index_esa_base.h"(235) //____________________________________________________________________________ // ESA_Text typedef Fibre_Text ESA_Text; // "projects/library/seqan/index/index_esa_base.h"(231) //____________________________________________________________________________ // Fibre_BWT typedef Tag<_Fibre_BWT> const Fibre_BWT; // "projects/library/seqan/index/index_base.h"(255) //____________________________________________________________________________ // Fibre_ChildTab typedef Tag<_Fibre_ChildTab> const Fibre_ChildTab; // "projects/library/seqan/index/index_base.h"(254) //____________________________________________________________________________ // Fibre_Counts typedef Tag<_Fibre_Counts> const Fibre_Counts; // "projects/library/seqan/index/index_qgram.h"(70) //____________________________________________________________________________ // Fibre_CountsDir typedef Tag<_Fibre_CountsDir> const Fibre_CountsDir; // "projects/library/seqan/index/index_qgram.h"(71) //____________________________________________________________________________ // Fibre_Dir typedef Tag<_Fibre_Dir> const Fibre_Dir; // "projects/library/seqan/index/index_qgram.h"(67) //____________________________________________________________________________ // Fibre_LCP typedef Tag<_Fibre_LCP> const Fibre_LCP; // "projects/library/seqan/index/index_base.h"(252) //____________________________________________________________________________ // Fibre_LCPE typedef Tag<_Fibre_LCPE> const Fibre_LCPE; // "projects/library/seqan/index/index_base.h"(253) //____________________________________________________________________________ // Fibre_PizzaChili_Compressed typedef Tag<_Fibre_PizzaChili_Compressed> const Fibre_PizzaChili_Compressed; // "projects/library/seqan/index/index_pizzachili.h"(44) //____________________________________________________________________________ // Fibre_PizzaChili_Text typedef Tag<_Fibre_Text> const Fibre_PizzaChili_Text; // "projects/library/seqan/index/index_pizzachili.h"(43) //____________________________________________________________________________ // Fibre_RawSA typedef Tag<_Fibre_RawSA> const Fibre_RawSA; // "projects/library/seqan/index/index_base.h"(250) //____________________________________________________________________________ // Fibre_RawText typedef Tag<_Fibre_RawText> const Fibre_RawText; // "projects/library/seqan/index/index_base.h"(248) //____________________________________________________________________________ // Fibre_SA typedef Tag<_Fibre_SA> const Fibre_SA; // "projects/library/seqan/index/index_base.h"(249) //____________________________________________________________________________ // Fibre_SADir typedef Tag<_Fibre_SADir> const Fibre_SADir; // "projects/library/seqan/index/index_qgram.h"(68) //____________________________________________________________________________ // Fibre_SAE typedef Tag<_Fibre_SAE> const Fibre_SAE; // "projects/library/seqan/index/index_base.h"(251) //____________________________________________________________________________ // Fibre_Shape typedef Tag<_Fibre_Shape> const Fibre_Shape; // "projects/library/seqan/index/index_qgram.h"(69) //____________________________________________________________________________ // Fibre_Text typedef Tag<_Fibre_Text> const Fibre_Text; // "projects/library/seqan/index/index_base.h"(247) //____________________________________________________________________________ // GappedShape typedef FixedGappedShape GappedShape; // "projects/library/seqan/index/shape_base.h"(33) //____________________________________________________________________________ // MaxRepeats typedef _MaxRepeats MaxRepeats; // "projects/library/seqan/index/index_esa_base.h"(131) //____________________________________________________________________________ // MultiMEMs typedef _MaxRepeats<_MultiMEMs> MultiMEMs; // "projects/library/seqan/index/index_esa_base.h"(133) //____________________________________________________________________________ // PizzaChiliFinder typedef Tag<_PizzaChiliFinder> const PizzaChiliFinder; // "projects/library/seqan/index/index_pizzachili_find.h"(36) //____________________________________________________________________________ // PizzaChili_AF typedef Tag<_PizzaChili_AF> const PizzaChili_AF; // "projects/library/seqan/index/pizzachili_api.h"(68) //____________________________________________________________________________ // PizzaChili_CCSA typedef Tag<_PizzaChili_CCSA> const PizzaChili_CCSA; // "projects/library/seqan/index/pizzachili_api.h"(71) //____________________________________________________________________________ // PizzaChili_Compressed typedef Fibre_PizzaChili_Compressed PizzaChili_Compressed; // "projects/library/seqan/index/index_pizzachili.h"(47) //____________________________________________________________________________ // PizzaChili_FM typedef Tag<_PizzaChili_FM> const PizzaChili_FM; // "projects/library/seqan/index/pizzachili_api.h"(74) //____________________________________________________________________________ // PizzaChili_LZ typedef Tag<_PizzaChili_LZ> const PizzaChili_LZ; // "projects/library/seqan/index/pizzachili_api.h"(77) //____________________________________________________________________________ // PizzaChili_RLFM typedef Tag<_PizzaChili_RLFM> const PizzaChili_RLFM; // "projects/library/seqan/index/pizzachili_api.h"(83) //____________________________________________________________________________ // PizzaChili_RSA typedef Tag<_PizzaChili_RSA> const PizzaChili_RSA; // "projects/library/seqan/index/pizzachili_api.h"(80) //____________________________________________________________________________ // PizzaChili_SA typedef Tag<_PizzaChili_SA> const PizzaChili_SA; // "projects/library/seqan/index/pizzachili_api.h"(86) //____________________________________________________________________________ // PizzaChili_SADA typedef Tag<_PizzaChili_SADA> const PizzaChili_SADA; // "projects/library/seqan/index/pizzachili_api.h"(89) //____________________________________________________________________________ // PizzaChili_SSA typedef Tag<_PizzaChili_SSA> const PizzaChili_SSA; // "projects/library/seqan/index/pizzachili_api.h"(92) //____________________________________________________________________________ // PizzaChili_Test typedef Tag<_PizzaChili_Test> const PizzaChili_Test; // "projects/library/seqan/index/pizzachili_api.h"(95) //____________________________________________________________________________ // PizzaChili_Text typedef Fibre_PizzaChili_Text PizzaChili_Text; // "projects/library/seqan/index/index_pizzachili.h"(46) //____________________________________________________________________________ // QGram_Counts typedef Fibre_Counts QGram_Counts; // "projects/library/seqan/index/index_qgram.h"(82) //____________________________________________________________________________ // QGram_CountsDir typedef Fibre_CountsDir QGram_CountsDir; // "projects/library/seqan/index/index_qgram.h"(83) //____________________________________________________________________________ // QGram_Dir typedef Fibre_Dir QGram_Dir; // "projects/library/seqan/index/index_qgram.h"(79) //____________________________________________________________________________ // QGram_FIND_Lookup typedef Tag<_Finder_QGramLookup> const QGram_FIND_Lookup; // "projects/library/seqan/index/index_qgram_find.h"(38) //____________________________________________________________________________ // QGram_RawSA typedef Fibre_RawSA QGram_RawSA; // "projects/library/seqan/index/index_qgram.h"(78) //____________________________________________________________________________ // QGram_RawText typedef Fibre_RawText QGram_RawText; // "projects/library/seqan/index/index_qgram.h"(76) //____________________________________________________________________________ // QGram_SA typedef Fibre_SA QGram_SA; // "projects/library/seqan/index/index_qgram.h"(77) //____________________________________________________________________________ // QGram_SADir typedef Fibre_SADir QGram_SADir; // "projects/library/seqan/index/index_qgram.h"(80) //____________________________________________________________________________ // QGram_Shape typedef Fibre_Shape QGram_Shape; // "projects/library/seqan/index/index_qgram.h"(81) //____________________________________________________________________________ // QGram_Text typedef Fibre_Text QGram_Text; // "projects/library/seqan/index/index_qgram.h"(75) //____________________________________________________________________________ // SimpleShape typedef FixedShape<0> SimpleShape; // "projects/library/seqan/index/shape_base.h"(29) //____________________________________________________________________________ // WotdOriginal typedef Tag const WotdOriginal; // "projects/library/seqan/index/index_wotd.h"(53) //____________________________________________________________________________ // Wotd_Dir typedef Fibre_Dir Wotd_Dir; // "projects/library/seqan/index/index_wotd.h"(35) //____________________________________________________________________________ // Wotd_RawSA typedef Fibre_RawSA Wotd_RawSA; // "projects/library/seqan/index/index_wotd.h"(34) //____________________________________________________________________________ // Wotd_RawText typedef Fibre_RawText Wotd_RawText; // "projects/library/seqan/index/index_wotd.h"(32) //____________________________________________________________________________ // Wotd_SA typedef Fibre_SA Wotd_SA; // "projects/library/seqan/index/index_wotd.h"(33) //____________________________________________________________________________ // Wotd_Text typedef Fibre_Text Wotd_Text; // "projects/library/seqan/index/index_wotd.h"(31) } //namespace SEQAN_NAMESPACE_MAIN ////////////////////////////////////////////////////////////////////////////// // FUNCTIONS ////////////////////////////////////////////////////////////////////////////// namespace SEQAN_NAMESPACE_MAIN { namespace impl { //____________________________________________________________________________ // clearIndex template inline void clearIndex(Index >& me); // "projects/library/seqan/index/index_pizzachili.h"(132) //____________________________________________________________________________ // createPizzaChiliIndex template inline bool createPizzaChiliIndex( Index >& me, uchar_t* textstart, ulong_t textlength ); // "projects/library/seqan/index/index_pizzachili.h"(256) //____________________________________________________________________________ // getOptionsString template inline char const* getOptionsString(Index >& ); // "projects/library/seqan/index/index_pizzachili.h"(162) template inline char const* getOptionsString(Index >& ); // "projects/library/seqan/index/index_pizzachili.h"(169) template inline char const* getOptionsString(Index >& ); // "projects/library/seqan/index/index_pizzachili.h"(176) template inline char const* getOptionsString(Index >& ); // "projects/library/seqan/index/index_pizzachili.h"(183) //____________________________________________________________________________ // getPizzaChiliString template inline uchar_t* getPizzaChiliString(TPattern const& pattern); // "projects/library/seqan/index/index_pizzachili_find.h"(92) inline uchar_t* getPizzaChiliString(char const* pattern); // "projects/library/seqan/index/index_pizzachili_find.h"(110) //____________________________________________________________________________ // queryText template inline void queryText(String > const& me); // "projects/library/seqan/index/index_pizzachili_string.h"(419) } //namespace impl } //namespace SEQAN_NAMESPACE_MAIN ////////////////////////////////////////////////////////////////////////////// namespace SEQAN_NAMESPACE_MAIN { //____________________________________________________________________________ // __cp_ template static finline Src const __cp_(Dest &dst, Ofs const ofs, Src const src); // "projects/library/seqan/index/pump_extender7.h"(67) //____________________________________________________________________________ // _adjustRightBorder template inline void _adjustRightBorder( Iter< Index >, VSTree< TopDown > > &); // "projects/library/seqan/index/index_wotd.h"(493) template inline void _adjustRightBorder( Iter< Index >, VSTree< TopDown > > &it); // "projects/library/seqan/index/index_wotd.h"(499) //____________________________________________________________________________ // _bucketLCP template typename Size::Type _bucketLCP(TSA const &sa, TText const &text); // "projects/library/seqan/index/index_wotd.h"(1249) template typename Size::Type _bucketLCP(TSA const &sa, TText const &text, TSize prefixLen); // "projects/library/seqan/index/index_wotd.h"(1283) template typename Size::Type _bucketLCP(TSA const &sa, StringSet const &stringSet, TSize prefixLen); // "projects/library/seqan/index/index_wotd.h"(1315) //____________________________________________________________________________ // _createBWTableWrapper template inline void _createBWTableWrapper(TBWT &bwt, TText const &s, TSA const &sa, _TTextRandom const); // "projects/library/seqan/index/index_shims.h"(424) template inline void _createBWTableWrapper(TBWT &bwt, TText const &s, TSA const &sa, True const); // "projects/library/seqan/index/index_shims.h"(432) //____________________________________________________________________________ // _dataHost template inline Holder & _dataHost(Index &index); // "projects/library/seqan/index/index_base.h"(464) template inline Holder const & _dataHost(Index const &index); // "projects/library/seqan/index/index_base.h"(468) //____________________________________________________________________________ // _deallocateStorage template inline void _deallocateStorage( String >& , TValue* begin, typename Size > >::Type ); // "projects/library/seqan/index/index_pizzachili_string.h"(370) //____________________________________________________________________________ // _dfsClear template inline void _dfsClear(Iter > &it); // "projects/library/seqan/index/index_esa_stree.h"(1393) //____________________________________________________________________________ // _dfsLCP template inline typename Size::Type & _dfsLCP(Iter< TIndex, VSTree< BottomUp > > &it); // "projects/library/seqan/index/index_esa_stree.h"(1860) template inline typename Size::Type _dfsLCP(Iter< TIndex, VSTree< BottomUp > > const &it); // "projects/library/seqan/index/index_esa_stree.h"(1866) //____________________________________________________________________________ // _dfsOnLeaf template inline void _dfsOnLeaf(Iter > > &it); // "projects/library/seqan/index/index_esa_stree.h"(274) template inline void _dfsOnLeaf(Iter > > > &it); // "projects/library/seqan/index/index_esa_algs.h"(496) template inline void _dfsOnLeaf(Iter > > &it); // "projects/library/seqan/index/index_esa_algs_multi.h"(338) //____________________________________________________________________________ // _dfsOnPop template inline void _dfsOnPop(Iter > > &it, TSize const); // "projects/library/seqan/index/index_esa_stree.h"(262) //____________________________________________________________________________ // _dfsOnPush template inline void _dfsOnPush(Iter > > &it, TElement const &e); // "projects/library/seqan/index/index_esa_stree.h"(269) template inline void _dfsOnPush(Iter > > > &it, TElement const &e); // "projects/library/seqan/index/index_esa_algs.h"(482) //____________________________________________________________________________ // _dfsRange template inline Pair::Type> & _dfsRange(Iter< TIndex, VSTree< BottomUp > > &it); // "projects/library/seqan/index/index_esa_stree.h"(1847) template inline Pair::Type> const & _dfsRange(Iter< TIndex, VSTree< BottomUp > > const &it); // "projects/library/seqan/index/index_esa_stree.h"(1854) //____________________________________________________________________________ // _dfsReversedOrder template inline bool _dfsReversedOrder(Iter > > &it); // "projects/library/seqan/index/index_esa_stree.h"(256) //____________________________________________________________________________ // _dump template inline void _dump(Index > > &index); // "projects/library/seqan/index/index_dfi.h"(470) template inline void _dump(Index > &index); // "projects/library/seqan/index/index_wotd.h"(1580) template inline void _dump(Index > &index); // "projects/library/seqan/index/index_esa_stree.h"(238) //____________________________________________________________________________ // _dumpFreq template inline void _dumpFreq(Index > > &index); // "projects/library/seqan/index/index_dfi.h"(497) //____________________________________________________________________________ // _dumpHistoryStack template inline void _dumpHistoryStack(Iter > &it); // "projects/library/seqan/index/index_esa_stree.h"(229) //____________________________________________________________________________ // _equalRangeLCPE template inline Pair< typename Iterator::Type > _equalRangeLCPE( TText &text, TSA &sa, SearchTreeIterator< TLCP, TSpec > treeIter, TQuery &query); // "projects/library/seqan/index/index_esa_find.h"(1362) template inline Pair< typename Iterator::Type > _equalRangeLCPE( TText &text, TSA &sa, TLCP &lcp, TQuery &query); // "projects/library/seqan/index/index_esa_find.h"(1514) //____________________________________________________________________________ // _equalRangeSA template inline Pair< typename Iterator::Type > _equalRangeSA( TText &text, SearchTreeIterator< TSA, TSpec > treeIter, TQuery &query); // "projects/library/seqan/index/index_esa_find.h"(632) //____________________________________________________________________________ // _findFirstIndex template inline void _findFirstIndex( Finder >, TSpecFinder>& finder, TPattern const& pattern, PizzaChiliFinder const ); // "projects/library/seqan/index/index_pizzachili_find.h"(123) template inline void _findFirstIndex( Finder< Index, TSpecFinder > &finder, TPattern const &pattern, QGram_FIND_Lookup const); // "projects/library/seqan/index/index_qgram_find.h"(57) template inline void _findFirstIndex( Finder< Index, TSpecFinder > &finder, TPattern const &pattern, ESA_FIND_MLR const); // "projects/library/seqan/index/index_esa_find.h"(1742) template inline void _findFirstIndex( Finder< Index, TSpecFinder > &finder, TPattern const &pattern, ESA_FIND_LCPE const); // "projects/library/seqan/index/index_esa_find.h"(1754) //____________________________________________________________________________ // _fractionMerge template inline void _fractionMerge( Iter > > &it, _FractionCompound &parent, _FractionCompound &child); // "projects/library/seqan/index/index_esa_algs.h"(451) template inline void _fractionMerge( Iter > > &it, _FractionMultiCompound &parent, _FractionMultiCompound &child); // "projects/library/seqan/index/index_esa_algs_multi.h"(317) //____________________________________________________________________________ // _fullDir2Length template inline int _fullDir2Length(TIndex const &index); // "projects/library/seqan/index/index_qgram.h"(330) //____________________________________________________________________________ // _fullDirLength template inline int _fullDirLength(TIndex const &index); // "projects/library/seqan/index/index_qgram.h"(322) //____________________________________________________________________________ // _getDown template inline TSize _getDown(TSize i, TIndex const &index); // "projects/library/seqan/index/index_esa_stree.h"(1836) //____________________________________________________________________________ // _getNextl template inline TSize _getNextl(TSize i, TIndex const &index); // "projects/library/seqan/index/index_esa_stree.h"(1821) //____________________________________________________________________________ // _getNodeByChar template inline bool _getNodeByChar( Iter< Index >, VSTree > const &it, TValue c, typename VertexDescriptor< Index > >::Type &childDesc); // "projects/library/seqan/index/index_esa_stree.h"(787) //____________________________________________________________________________ // _getNodeLP template inline TPos _getNodeLP( Index > const &index, TPos pos); // "projects/library/seqan/index/index_wotd.h"(1366) //____________________________________________________________________________ // _getUp template inline TSize _getUp(TSize i, TIndex const &index); // "projects/library/seqan/index/index_esa_stree.h"(1827) //____________________________________________________________________________ // _goDown template inline bool _goDown( Iter< Index >, VSTree< TopDown > > &it, VSTreeIteratorTraits const); // "projects/library/seqan/index/index_wotd.h"(524) template inline bool _goDown( Iter< Index >, VSTree< TopDown > > &it, VSTreeIteratorTraits const); // "projects/library/seqan/index/index_wotd.h"(560) template inline bool _goDown( Iter< Index >, VSTree< TopDown > > &it, VSTreeIteratorTraits const); // "projects/library/seqan/index/index_esa_stree.h"(1035) template inline bool _goDown( Iter< Index >, VSTree< TopDown > > &it, VSTreeIteratorTraits const); // "projects/library/seqan/index/index_esa_stree.h"(1055) //____________________________________________________________________________ // _goDownChar template inline bool _goDownChar( Iter >, VSTree< TopDown > > &it, TValue c); // "projects/library/seqan/index/index_wotd.h"(1609) template inline bool _goDownChar( Iter >, VSTree< TopDown > > &it, TValue c); // "projects/library/seqan/index/index_wotd.h"(1631) template inline bool _goDownChar(Iter< TIndex, VSTree< TopDown > > &it, TValue c); // "projects/library/seqan/index/index_esa_stree.h"(1100) //____________________________________________________________________________ // _goDownObject template inline bool _goDownObject( Iter< TIndex, VSTree< TopDown > > &it, TObject const &obj, False); // "projects/library/seqan/index/index_esa_stree.h"(1168) template inline bool _goDownObject( Iter< TIndex, VSTree< TopDown > > &it, TObject const &obj, True); // "projects/library/seqan/index/index_esa_stree.h"(1178) //____________________________________________________________________________ // _goDownString template inline bool _goDownString( Iter< TIndex, VSTree< TopDown > > &node, TString const &pattern, TSize &lcp); // "projects/library/seqan/index/index_esa_stree.h"(1118) //____________________________________________________________________________ // _goRight template inline bool _goRight( Iter< Index >, VSTree< TopDown > > &it, VSTreeIteratorTraits const); // "projects/library/seqan/index/index_wotd.h"(596) template inline bool _goRight( Iter< Index >, VSTree< TopDown > > &it, VSTreeIteratorTraits const); // "projects/library/seqan/index/index_wotd.h"(620) template inline bool _goRight( Iter< Index >, VSTree< TopDown > > &it, VSTreeIteratorTraits const); // "projects/library/seqan/index/index_esa_stree.h"(1289) //____________________________________________________________________________ // _goUp template inline bool _goUp(Iter< Index >, VSTree< TopDown > > &it); // "projects/library/seqan/index/index_wotd.h"(645) template inline bool _goUp(Iter< Index >, VSTree< TopDown< ParentLinks > > > &it); // "projects/library/seqan/index/index_wotd.h"(657) template inline bool _goUp(Iter< Index >, VSTree< TopDown< ParentLinks > > > &it); // "projects/library/seqan/index/index_wotd.h"(674) template inline bool _goUp(Iter< TIndex, VSTree< TopDown > > &it); // "projects/library/seqan/index/index_esa_stree.h"(1219) template inline bool _goUp(Iter< TIndex, VSTree< TopDown< ParentLinks > > > &it); // "projects/library/seqan/index/index_esa_stree.h"(1231) //____________________________________________________________________________ // _hashFixedShape template inline THValue _hashFixedShape(THValue hash, TIter &, TValue const, FixedShape<1> const); // "projects/library/seqan/index/shape_base.h"(290) template inline THValue _hashFixedShape(THValue hash, TIter &it, TValue const, FixedShape const); // "projects/library/seqan/index/shape_base.h"(296) //____________________________________________________________________________ // _hashHardwiredShape template inline THValue _hashHardwiredShape(THValue hash, TIter &, TValue const, HardwiredShape< 0,0,0,0,0, 0,0,0,0,0, 0,0,0,0,0, 0,0,0,0,0 > const); // "projects/library/seqan/index/shape_gapped.h"(448) template inline THValue _hashHardwiredShape(THValue hash, TIter &it, TValue const, HardwiredShape< 1 ,P01,P02,P03,P04, P05,P06,P07,P08,P09, P10,P11,P12,P13,P14, P15,P16,P17,P18,P19 > const); // "projects/library/seqan/index/shape_gapped.h"(465) template inline THValue _hashHardwiredShape(THValue hash, TIter &it, TValue const, HardwiredShape< P00,P01,P02,P03,P04, P05,P06,P07,P08,P09, P10,P11,P12,P13,P14, P15,P16,P17,P18,P19 > const); // "projects/library/seqan/index/shape_gapped.h"(488) //____________________________________________________________________________ // _hashTuple2FixedShape template inline THValue _hashTuple2FixedShape( THValue const, Tuple const &tuple, TValue const, FixedShape<1> const); // "projects/library/seqan/index/shape_base.h"(353) template inline THValue _hashTuple2FixedShape( THValue const, Tuple const &tuple, TValue const, FixedShape const); // "projects/library/seqan/index/shape_base.h"(364) //____________________________________________________________________________ // _haveMaximalRepeats template int _haveMaximalRepeats( _FractionCompound const &a, _FractionCompound const &b); // "projects/library/seqan/index/index_esa_algs.h"(268) template int _haveMaximalRepeats( _FractionCompound const &a, _FractionCompound const &b, TValue &equalKey); // "projects/library/seqan/index/index_esa_algs.h"(289) //____________________________________________________________________________ // _historyClear template inline void _historyClear(Iter< TIndex, VSTree > &); // "projects/library/seqan/index/index_esa_stree.h"(989) template inline void _historyClear(Iter< TIndex, VSTree< TopDown< ParentLinks > > > &it); // "projects/library/seqan/index/index_esa_stree.h"(993) //____________________________________________________________________________ // _historyPush template inline void _historyPush(Iter< Index >, VSTree< TopDown > > &it); // "projects/library/seqan/index/index_wotd.h"(235) template inline void _historyPush(Iter< Index >, VSTree< TopDown< ParentLinks > > > &it); // "projects/library/seqan/index/index_wotd.h"(244) template inline void _historyPush(Iter< Index >, VSTree< TopDown< ParentLinks > > > &it); // "projects/library/seqan/index/index_wotd.h"(255) template inline void _historyPush(Iter< Index >, VSTree< TopDown > > &it); // "projects/library/seqan/index/index_esa_stree.h"(1004) template inline void _historyPush(Iter< Index >, VSTree< TopDown< ParentLinks > > > &it); // "projects/library/seqan/index/index_esa_stree.h"(1010) //____________________________________________________________________________ // _indexRequireBottomUpIteration template void _indexRequireBottomUpIteration(Index > &index); // "projects/library/seqan/index/index_esa_base.h"(298) //____________________________________________________________________________ // _indexRequireTopDownIteration template void _indexRequireTopDownIteration(Index > &index); // "projects/library/seqan/index/index_esa_base.h"(290) template void _indexRequireTopDownIteration(Index > &index); // "projects/library/seqan/index/index_wotd.h"(193) //____________________________________________________________________________ // _isLeaf template inline bool _isLeaf( Iter< Index >, VSTree > const &it, VSTreeIteratorTraits const); // "projects/library/seqan/index/index_wotd.h"(281) template inline bool _isLeaf( Iter< Index >, VSTree > const &it, VSTreeIteratorTraits const); // "projects/library/seqan/index/index_wotd.h"(292) template inline bool _isLeaf(VertexESA const &vDesc); // "projects/library/seqan/index/index_esa_stree.h"(1750) template inline bool _isLeaf( Iter > const &it, VSTreeIteratorTraits const); // "projects/library/seqan/index/index_esa_stree.h"(1760) template inline bool _isLeaf( Iter > const &it, VSTreeIteratorTraits const); // "projects/library/seqan/index/index_esa_stree.h"(1769) //____________________________________________________________________________ // _isNextl template inline bool _isNextl(TSize i, TIndex const &index); // "projects/library/seqan/index/index_esa_stree.h"(1805) //____________________________________________________________________________ // _isRoot template inline bool _isRoot(_VertexWotdOriginal const &value); // "projects/library/seqan/index/index_wotd.h"(267) template inline bool _isRoot(_VertexWotdModified const &value); // "projects/library/seqan/index/index_wotd.h"(272) template inline bool _isRoot(VertexESA const &value); // "projects/library/seqan/index/index_esa_stree.h"(1501) //____________________________________________________________________________ // _isSizeInval template inline bool _isSizeInval(TValue const &v); // "projects/library/seqan/index/index_base.h"(794) //____________________________________________________________________________ // _isUp template inline bool _isUp(TSize i, TIndex const &index); // "projects/library/seqan/index/index_esa_stree.h"(1813) //____________________________________________________________________________ // _leqSkew3 template inline bool _leqSkew3(T a1, ST a2, T b1, ST b2); // "projects/library/seqan/index/index_skew3.h"(313) template inline bool _leqSkew3(T a1, T a2, ST a3, T b1, T b2, ST b3); // "projects/library/seqan/index/index_skew3.h"(319) //____________________________________________________________________________ // _leqSkew7 template inline bool _leqSkew7(TTextIter a1, TSize a2, TTextIter b1, TSize b2, TSize n); // "projects/library/seqan/index/index_skew7.h"(414) template inline bool _leqSkew7(TTextIter a, TTextIter b, TSize n); // "projects/library/seqan/index/index_skew7.h"(425) template inline bool _leqSkew7(unsigned a, unsigned b, TTextIter spos[], const TSize tpos[], const bool islast[], const TString &s124, const long adjust[7][7]); // "projects/library/seqan/index/index_skew7.h"(436) //____________________________________________________________________________ // _lowerBoundLCPE template inline typename Iterator::Type _lowerBoundLCPE( TText &text, TSA &sa, SearchTreeIterator< TLCP, TSpec > treeIter, TQuery &query, TDiff_ lcpLower, TDiff_ lcpUpper); // "projects/library/seqan/index/index_esa_find.h"(992) template inline typename Iterator::Type _lowerBoundLCPE( TText &text, TSA &sa, SearchTreeIterator< TLCP, TSpec > &treeIter, TQuery &query); // "projects/library/seqan/index/index_esa_find.h"(1169) //____________________________________________________________________________ // _lowerBoundSA template inline typename Iterator::Type _lowerBoundSA( TText &text, SearchTreeIterator< TSA, TSpec > treeIter, TQuery &query); // "projects/library/seqan/index/index_esa_find.h"(524) //____________________________________________________________________________ // _onGoDown template inline void _onGoDown(Iter > > &); // "projects/library/seqan/index/index_esa_stree.h"(1018) //____________________________________________________________________________ // _onGoRight template inline void _onGoRight(Iter > > &); // "projects/library/seqan/index/index_esa_stree.h"(1021) //____________________________________________________________________________ // _onGoUp template inline void _onGoUp(Iter > > > &); // "projects/library/seqan/index/index_esa_stree.h"(1024) //____________________________________________________________________________ // _pizzaChiliDeallocate template inline void _pizzaChiliDeallocate(TValue* begin); // "projects/library/seqan/index/index_pizzachili_string.h"(276) //____________________________________________________________________________ // _pizzaChiliReallocate template inline typename Value > >::Type* _pizzaChiliReallocate( String >& me, typename Size > >::Type new_capacity ); // "projects/library/seqan/index/index_pizzachili_string.h"(259) //____________________________________________________________________________ // _qgramCountQGrams template inline void _qgramCountQGrams(TDir &dir, TText const &text, TShape &shape); // "projects/library/seqan/index/index_qgram.h"(640) template inline void _qgramCountQGrams(TDir &dir, StringSet const &stringSet, TShape &shape); // "projects/library/seqan/index/index_qgram.h"(660) //____________________________________________________________________________ // _qgramCummulativeSum template inline typename Value::Type _qgramCummulativeSum(TDir &dir, TWithConstraints); // "projects/library/seqan/index/index_qgram.h"(690) //____________________________________________________________________________ // _qgramCummulativeSumAlt template inline typename Value::Type _qgramCummulativeSumAlt(TDir &dir, TWithConstraints const); // "projects/library/seqan/index/index_qgram.h"(722) //____________________________________________________________________________ // _qgramDisableBuckets template inline bool _qgramDisableBuckets(TIndex &); // "projects/library/seqan/index/index_qgram.h"(863) //____________________________________________________________________________ // _qgramFillSuffixArray template inline void _qgramFillSuffixArray(TSA &sa, TText const &text, TShape &shape, TDir &dir, TWithConstraints const); // "projects/library/seqan/index/index_qgram.h"(748) template inline void _qgramFillSuffixArray( TSA &sa, StringSet const &stringSet, TShape &shape, TDir &dir, TWithConstraints const); // "projects/library/seqan/index/index_qgram.h"(790) //____________________________________________________________________________ // _qgramPostprocessBuckets template inline void _qgramPostprocessBuckets(TDir &dir); // "projects/library/seqan/index/index_qgram.h"(831) //____________________________________________________________________________ // _reallocateStorage template inline typename Value > >::Type* _reallocateStorage( String >& me, typename Size > >::Type new_capacity, Exact ); // "projects/library/seqan/index/index_pizzachili_string.h"(359) //____________________________________________________________________________ // _refineQGramIndex template void _refineQGramIndex( TSA &sa, TDir &dir, TText const &text, TSize1 oldQ, TSize2 newQ); // "projects/library/seqan/index/index_qgram.h"(1033) //____________________________________________________________________________ // _setLength template inline void _setLength( String >& me, size_t new_length ); // "projects/library/seqan/index/index_pizzachili_string.h"(409) //____________________________________________________________________________ // _setSizeInval template inline void _setSizeInval(TValue &v); // "projects/library/seqan/index/index_base.h"(789) //____________________________________________________________________________ // _sortBucketQuickSort template void _sortBucketQuickSort( TSA &sa, TText &text, TSize lcp); // "projects/library/seqan/index/index_sa_qsort.h"(87) //____________________________________________________________________________ // _sortFirstWotdBucket template typename Size< Index, Index_Wotd > > >::Type _sortFirstWotdBucket(Index, Index_Wotd > > &index); // "projects/library/seqan/index/index_dfi.h"(171) template typename Size::Type _sortFirstWotdBucket(TIndex &index); // "projects/library/seqan/index/index_wotd.h"(890) template typename Size< Index, TIndexSpec> >::Type _sortFirstWotdBucket(Index, TIndexSpec> &index); // "projects/library/seqan/index/index_wotd.h"(935) //____________________________________________________________________________ // _sortWotdBucket template TSize _sortWotdBucket( Index, Index_Wotd > > &index, TSize left, TSize right, TSize prefixLen); // "projects/library/seqan/index/index_dfi.h"(260) template TSize _sortWotdBucket( Index > &index, TSize left, TSize right, TSize prefixLen); // "projects/library/seqan/index/index_wotd.h"(999) template TSize _sortWotdBucket( TIndex &index, TSize left, TSize right, TSize prefixLen); // "projects/library/seqan/index/index_wotd.h"(1108) template TSize _sortWotdBucket( Index, TIndexSpec> &index, TSize left, TSize right, TSize prefixLen); // "projects/library/seqan/index/index_wotd.h"(1171) //____________________________________________________________________________ // _storeWotdChildren template inline void _storeWotdChildren( Index > > &index, TSize dirOfs, TSize lcp); // "projects/library/seqan/index/index_dfi.h"(397) template inline void _storeWotdChildren( Index > &index, TPos dirOfs); // "projects/library/seqan/index/index_wotd.h"(1385) template inline void _storeWotdChildren( Index > &index, TSize dirOfs, TSize lcp); // "projects/library/seqan/index/index_wotd.h"(1441) //____________________________________________________________________________ // _treeLevels template inline unsigned _treeLevels(TSize lcpSize); // "projects/library/seqan/index/index_lcp_tree.h"(146) //____________________________________________________________________________ // _upperBoundLCPE template inline typename Iterator::Type _upperBoundLCPE( TText &text, TSA &sa, SearchTreeIterator< TLCP, TSpec > treeIter, TQuery &query, TDiff_ lcpLower, TDiff_ lcpUpper); // "projects/library/seqan/index/index_esa_find.h"(1192) template inline typename Iterator::Type _upperBoundLCPE( TText &text, TSA &sa, SearchTreeIterator< TLCP, TSpec > &treeIter, TQuery &query); // "projects/library/seqan/index/index_esa_find.h"(1342) //____________________________________________________________________________ // _upperBoundSA template inline typename Iterator::Type _upperBoundSA( TText &text, SearchTreeIterator< TSA, TSpec > treeIter, TQuery &query); // "projects/library/seqan/index/index_esa_find.h"(578) //____________________________________________________________________________ // _wotdCountChars template inline void _wotdCountChars(TBuckets &buckets, TText const &text); // "projects/library/seqan/index/index_wotd.h"(700) template inline void _wotdCountChars(TBuckets &buckets, StringSet const &stringSet); // "projects/library/seqan/index/index_wotd.h"(714) template inline typename Size::Type _wotdCountChars( TBuckets &buckets, TText const &text, TSA const &sa, TSize prefixLen); // "projects/library/seqan/index/index_wotd.h"(767) template inline typename Size::Type _wotdCountChars( TBuckets &buckets, StringSet const &stringSet, TSA const &sa, TSize prefixLen); // "projects/library/seqan/index/index_wotd.h"(803) //____________________________________________________________________________ // _wotdCountCharsWotdOriginal template inline typename Size::Type _wotdCountCharsWotdOriginal( TBuckets &buckets, TText const &text, TSA &sa, TSize prefixLen); // "projects/library/seqan/index/index_wotd.h"(736) //____________________________________________________________________________ // _wotdCreateFirstLevel template inline void _wotdCreateFirstLevel(Index > &index); // "projects/library/seqan/index/index_wotd.h"(1681) //____________________________________________________________________________ // _wotdCummulativeSum template inline typename Size::Type _wotdCummulativeSum(TBounds &bounds, TBuckets const &buckets, TSize offset); // "projects/library/seqan/index/index_wotd.h"(844) template inline typename Size::Type _wotdCummulativeSum(TBounds &bounds, TBuckets const &buckets); // "projects/library/seqan/index/index_wotd.h"(870) //____________________________________________________________________________ // _wotdEvaluate template inline typename Size< Index > >::Type _wotdEvaluate(Iter< Index >, VSTree > const &it); // "projects/library/seqan/index/index_wotd.h"(1497) template inline typename Size< Index > >::Type _wotdEvaluate(Iter< Index >, VSTree > const &it); // "projects/library/seqan/index/index_wotd.h"(1538) //____________________________________________________________________________ // alignment template inline Align alignment(Iter< Index< StringSet, TIndexSpec >, VSTree > &it); // "projects/library/seqan/index/index_esa_stree.h"(643) template inline Align alignment(Iter< Index< StringSet > >, TIndexSpec >, VSTree > &it); // "projects/library/seqan/index/index_esa_stree.h"(689) //____________________________________________________________________________ // assign template inline void assign( String >& target, TSource const& source, Tag const ); // "projects/library/seqan/index/index_pizzachili_string.h"(196) template inline void assign( String >& target, TSource const* source, Tag const ); // "projects/library/seqan/index/index_pizzachili_string.h"(210) template inline void assign( String >& target, String > const& source, Tag const ); // "projects/library/seqan/index/index_pizzachili_string.h"(224) //____________________________________________________________________________ // atBegin template inline bool atBegin(Finder< Index, TSpecFinder > & me); // "projects/library/seqan/index/index_find.h"(180) //____________________________________________________________________________ // atEnd template inline bool atEnd(Iter >, VSTree > &it); // "projects/library/seqan/index/index_wotd.h"(477) template inline bool atEnd(Iter >, VSTree > const &it); // "projects/library/seqan/index/index_wotd.h"(483) template inline bool atEnd(Finder< Index, TSpecFinder > & me); // "projects/library/seqan/index/index_find.h"(188) template inline bool atEnd(Iter > &it); // "projects/library/seqan/index/index_esa_stree.h"(1467) template inline bool atEnd(Iter > const &it); // "projects/library/seqan/index/index_esa_stree.h"(1473) template inline bool atEnd(Iter const &it); // "projects/library/seqan/index/index_esa_algs.h"(824) template inline bool atEnd(Iter &it); // "projects/library/seqan/index/index_esa_algs.h"(829) template inline bool atEnd(Iter const &it); // "projects/library/seqan/index/index_esa_algs_multi.h"(644) template inline bool atEnd(Iter &it); // "projects/library/seqan/index/index_esa_algs_multi.h"(649) //____________________________________________________________________________ // begin template inline typename Iterator >, Tag const>::Type begin( String >& me, Tag const ); // "projects/library/seqan/index/index_pizzachili_string.h"(464) template inline typename Iterator > const, Tag const>::Type begin( String > const& me, Tag const ); // "projects/library/seqan/index/index_pizzachili_string.h"(475) template inline typename Iterator, TSpec >::Type begin(Index &index, TSpec const); // "projects/library/seqan/index/index_esa_stree.h"(877) template inline typename Iterator< Iter< TSTree, VSTree< BottomUp<_MaxRepeats > > > >::Type begin(Iter< TSTree, VSTree< BottomUp<_MaxRepeats > > > &it); // "projects/library/seqan/index/index_esa_algs.h"(579) //____________________________________________________________________________ // bwtAt template inline typename Reference::Type>::Type bwtAt(TPos i, TIndex &index); // "projects/library/seqan/index/index_base.h"(777) template inline typename Reference::Type>::Type bwtAt(TPos i, TIndex const &index); // "projects/library/seqan/index/index_base.h"(781) //____________________________________________________________________________ // cargo template inline typename Reference< typename Cargo >::Type >::Type cargo(Index & me); // "projects/library/seqan/index/index_shims.h"(595) template inline typename Reference< typename Cargo const>::Type >::Type cargo(Index const & me); // "projects/library/seqan/index/index_shims.h"(603) //____________________________________________________________________________ // childAt template inline typename Reference::Type>::Type childAt(TPos i, TIndex &index); // "projects/library/seqan/index/index_base.h"(756) template inline typename Reference::Type>::Type childAt(TPos i, TIndex const &index); // "projects/library/seqan/index/index_base.h"(760) //____________________________________________________________________________ // childrenAreLeaves template inline bool childrenAreLeaves(Iter > const &it); // "projects/library/seqan/index/index_esa_stree.h"(1734) //____________________________________________________________________________ // childtab_process template inline void childtab_process(TLCPInput &lcpIn, TDest &dest); // "projects/library/seqan/index/index_childtab.h"(44) //____________________________________________________________________________ // clear template inline void clear(Index > &index); // "projects/library/seqan/index/index_esa_base.h"(307) template inline void clear(Index >& me); // "projects/library/seqan/index/index_pizzachili.h"(150) template inline void clear(Finder< Index, TSpecFinder > & me); // "projects/library/seqan/index/index_find.h"(167) template inline void clear(String >& me); // "projects/library/seqan/index/index_pizzachili_string.h"(178) template inline void clear(Iter > &it); // "projects/library/seqan/index/index_esa_stree.h"(1387) //____________________________________________________________________________ // container template inline typename _Parameter< Index >::Type container(Finder< Index, TSpecFinder > & me); // "projects/library/seqan/index/index_find.h"(100) template inline typename _Parameter< Index >::Type container(Finder< Index, TSpecFinder > const & me); // "projects/library/seqan/index/index_find.h"(108) template inline TIndex const & container(Iter< TIndex, VSTree > const &it); // "projects/library/seqan/index/index_esa_stree.h"(543) template inline TIndex & container(Iter< TIndex, VSTree > &it); // "projects/library/seqan/index/index_esa_stree.h"(548) //____________________________________________________________________________ // control //template inline bool control(Pipe< TInput, LarssonSadakane > &me, ControlBeginRead const &command); // "projects/library/seqan/index/index_sa_lss.h"(413) //template inline bool control(Pipe< TInput, Merger3 > &me, ControlBeginRead const &command); // "projects/library/seqan/index/pipe_merger3.h"(134) //template inline bool control(Pipe< TInput, Merger7 > &me, ControlBeginRead const &command); // "projects/library/seqan/index/pipe_merger7.h"(475) //template inline bool control(Pipe< TInput, Merger7 > &me, ControlEof const &); // "projects/library/seqan/index/pipe_merger7.h"(483) //template inline bool control(Pipe< TInput, Merger7 > &me, ControlEos const &); // "projects/library/seqan/index/pipe_merger7.h"(488) //template inline bool control(Pipe< TInput, Merger7Multi > &me, ControlBeginRead const &command); // "projects/library/seqan/index/pipe_merger7.h"(506) //template inline bool control(Pipe< TInput, Merger7Multi > &me, ControlEof const &); // "projects/library/seqan/index/pipe_merger7.h"(513) //template inline bool control(Pipe< TInput, Merger7Multi > &me, ControlEos const &); // "projects/library/seqan/index/pipe_merger7.h"(518) //____________________________________________________________________________ // countChildren template inline typename Size::Type countChildren(Iter< TIndex, VSTree > const &it); // "projects/library/seqan/index/index_esa_stree.h"(763) //____________________________________________________________________________ // countOccurrences template inline typename Size::Type countOccurrences(Iter< TIndex, VSTree > const &it); // "projects/library/seqan/index/index_esa_stree.h"(600) //____________________________________________________________________________ // countSequences template inline typename Size::Type countSequences(Index const &index); // "projects/library/seqan/index/index_base.h"(609) //____________________________________________________________________________ // createBWTable template inline void createBWTable(TBWT &bwt, TText const &s, TSA const &sa); // "projects/library/seqan/index/index_shims.h"(439) //____________________________________________________________________________ // createBWTableExt template void createBWTableExt( TBWT &bwt, TText const &s, TSA const &SA); // "projects/library/seqan/index/index_shims.h"(394) //____________________________________________________________________________ // createBWTableInt template void createBWTableInt( TBWT &bwt, TText const &s, TSA const &SA); // "projects/library/seqan/index/index_bwt.h"(247) template void createBWTableInt( TBWT &bwt, StringSet const &s, TSA const &SA); // "projects/library/seqan/index/index_bwt.h"(275) //____________________________________________________________________________ // createChildTable //template inline void createChildTable( String > &childtab, TLCPTable &lcp); // "projects/library/seqan/index/index_childtab.h"(197) template inline void createChildTable(TDest &dest, TLCPInput const &lcpIn); // "projects/library/seqan/index/index_childtab.h"(209) //____________________________________________________________________________ // createChildTableExt template void createChildTableExt( TChildTable &childtab, TLCPTable &lcp); // "projects/library/seqan/index/index_childtab.h"(171) //____________________________________________________________________________ // createCountsArray template void createCountsArray( TCounts &counts, TDir &dir, StringSet const &stringSet, TShape &shape); // "projects/library/seqan/index/index_qgram.h"(1150) //____________________________________________________________________________ // createLCPBinTree template inline FlatOutIt createLCPBinTree( LCPFwdIt _First, LCPFwdIt _Last, FlatOutIt _Dest); // "projects/library/seqan/index/index_lcp_tree.h"(33) template inline void createLCPBinTree(TLCPE &lcp_enhanced, TLCP &lcp); // "projects/library/seqan/index/index_lcp_tree.h"(139) //template inline void createLCPBinTree(String > &lcp_enhanced, TLCP &lcp); // "projects/library/seqan/index/index_lcp_tree.h"(155) //____________________________________________________________________________ // createLCPETable template void createLCPETable( String< TValue, TSpec > &LCPE, TText const &s, TSA const &SA, TAlgSpec const alg); // "projects/library/seqan/index/index_shims.h"(334) //template void createLCPETable( String< TValue, External > &LCPE, TText const &s, TSA const &SA, TAlgSpec const alg); // "projects/library/seqan/index/index_shims.h"(359) template inline void createLCPETable( String< TValue, TSpec > &LCPE, TText &s, TSA &SA); // "projects/library/seqan/index/index_shims.h"(373) //____________________________________________________________________________ // createLCPETableExt template void createLCPETableExt( String< TValue, TSpec > &LCPE, TObject const &text, TSA const &suffixArray, TAlgSpec const); // "projects/library/seqan/index/index_shims.h"(301) //____________________________________________________________________________ // createLCPTable //template void createLCPTable( TLCPTable &LCP, TText const &s, TSA const &SA, KasaiOriginal const); // "projects/library/seqan/index/index_lcp.h"(253) //template void createLCPTable( TLCPTable &LCP, TText const &s, TSA const &SA, Kasai const); // "projects/library/seqan/index/index_lcp.h"(315) template void createLCPTable( TLCPTable &LCP, StringSet const &sset, TSA const &SA, Kasai const); // "projects/library/seqan/index/index_lcp.h"(398) //____________________________________________________________________________ // createLCPTableExt template void createLCPTableExt( TLCPTable &LCP, TObject const &text, TSA const &suffixArray, TAlgSpec const); // "projects/library/seqan/index/index_shims.h"(179) template void createLCPTableExt( TLCPTable &LCP, StringSet const &stringSet, TSA const &suffixArray, TAlgSpec const); // "projects/library/seqan/index/index_shims.h"(210) //____________________________________________________________________________ // createQGramIndex template void createQGramIndex(TIndex &index); // "projects/library/seqan/index/index_qgram.h"(869) template void createQGramIndex( TSA &sa, TDir &dir, TText const &text, TShape &shape); // "projects/library/seqan/index/index_qgram.h"(915) //____________________________________________________________________________ // createQGramIndexDirOnly template void createQGramIndexDirOnly( TDir &dir, TText const &text, TShape &shape); // "projects/library/seqan/index/index_qgram.h"(1089) template void createQGramIndexDirOnly( TDir &dir, StringSet const &stringSet, TShape &shape); // "projects/library/seqan/index/index_qgram.h"(1111) //____________________________________________________________________________ // createQGramIndexExt template void createQGramIndexExt( TSA &suffixArray, TDir &dir, TText &text, TShape &shape); // "projects/library/seqan/index/index_qgram.h"(1287) template void createQGramIndexExt( TSA &suffixArray, TDir &dir, StringSet const &stringSet, TShape &shape, TLimitsString &limits); // "projects/library/seqan/index/index_qgram.h"(1374) //____________________________________________________________________________ // createQGramIndexSAOnly template void createQGramIndexSAOnly( TSA &sa, TText const &text, TShape &shape); // "projects/library/seqan/index/index_qgram.h"(951) template void createQGramIndexSAOnly( TSA &sa, StringSet const &stringSet, TShape &shape); // "projects/library/seqan/index/index_qgram.h"(986) //____________________________________________________________________________ // createSABTree template inline FlatOutIt createSABTree( SAFwdIt _First, SAFwdIt _Last, FlatOutIt _Dest, unsigned BlockSize); // "projects/library/seqan/index/index_sa_btree.h"(33) template inline void createSABTree(TSAB &sa_btree, TSA &sa, unsigned BlockSize); // "projects/library/seqan/index/index_sa_btree.h"(96) //template inline void createSABTree(String > &sa_btree, TSA &sa, unsigned BlockSize); // "projects/library/seqan/index/index_sa_btree.h"(110) //____________________________________________________________________________ // createSuffixArray template void createSuffixArray( TSA &SA, TText &s, Shawarma const); // "projects/library/seqan/index/index_shawarma.h"(58) template inline void createSuffixArray( TSA &SA, TText const &s, TAlgSpec const &alg); // "projects/library/seqan/index/index_shims.h"(121) //template inline void createSuffixArray( TSA &SA, String< TValue, External > const &s, TAlgSpec const alg); // "projects/library/seqan/index/index_shims.h"(139) template inline void createSuffixArray( TSA &SA, StringSet< String, TSSetSpec > const &s, TAlgSpec const); // "projects/library/seqan/index/index_shims.h"(155) template void createSuffixArray( TSA &SA, TText &s, LarssonSadakane const &, unsigned K); // "projects/library/seqan/index/index_sa_lss.h"(352) template void createSuffixArray( TSA &SA, TText &s, ManberMyers const &, unsigned K, unsigned maxdepth); // "projects/library/seqan/index/index_sa_mm.h"(42) template inline void createSuffixArray( TSA &SA, TText &s, SAQSort const &); // "projects/library/seqan/index/index_sa_qsort.h"(102) //template inline void createSuffixArray( TSA &SA, String< TValue, External > &s, Skew3 const &spec, unsigned K, unsigned maxdepth); // "projects/library/seqan/index/index_skew3.h"(299) template void createSuffixArray( TSA &SA, TText &s, Skew3 const &, unsigned K, unsigned maxdepth, unsigned depth); // "projects/library/seqan/index/index_skew3.h"(342) template inline void createSuffixArray( TSA &SA, TText &s, Skew3 const &alg, unsigned K, unsigned maxdepth); // "projects/library/seqan/index/index_skew3.h"(494) //template inline void createSuffixArray( TSA &SA, String< TValue, External > &s, Skew7 const &spec, unsigned K, unsigned maxdepth); // "projects/library/seqan/index/index_skew7.h"(399) template void createSuffixArray( TSA &SA, TText &s, Skew7 const &, unsigned K, unsigned maxdepth, unsigned depth); // "projects/library/seqan/index/index_skew7.h"(472) template inline void createSuffixArray( TSA &SA, TText &s, Skew7 const &alg, unsigned K, unsigned maxdepth); // "projects/library/seqan/index/index_skew7.h"(795) //____________________________________________________________________________ // createSuffixArrayExt template void createSuffixArrayExt( TSA &suffixArray, TObject const &text, TAlgSpec const); // "projects/library/seqan/index/index_shims.h"(40) template void createSuffixArrayExt( TSA &suffixArray, StringSet const &stringSet, TAlgSpec const); // "projects/library/seqan/index/index_shims.h"(74) //____________________________________________________________________________ // createSuffixArrayPart template inline void createSuffixArrayPart( TSA &SA, TText &s, ManberMyers const &alg, TSize maxLCP, unsigned K ); // "projects/library/seqan/index/index_sa_mm.h"(167) template inline void createSuffixArrayPart( TSA &SA, TText &s, Skew3 const &_dummy, TSize maxLCP, unsigned K ); // "projects/library/seqan/index/index_skew3.h"(508) template inline void createSuffixArrayPart( TSA &SA, TText &s, Skew7 const &_dummy, TSize maxLCP, unsigned K ); // "projects/library/seqan/index/index_skew7.h"(809) //____________________________________________________________________________ // dirAt template inline typename Reference::Type>::Type dirAt(TPos i, TIndex &index); // "projects/library/seqan/index/index_qgram.h"(265) template inline typename Reference::Type>::Type dirAt(TPos i, TIndex const &index); // "projects/library/seqan/index/index_qgram.h"(269) //____________________________________________________________________________ // empty template inline bool empty(Finder< Index, TSpecFinder > & me); // "projects/library/seqan/index/index_find.h"(159) template inline bool empty(Iter > &it); // "projects/library/seqan/index/index_esa_stree.h"(1452) template inline bool empty(Iter > const &it); // "projects/library/seqan/index/index_esa_stree.h"(1458) //____________________________________________________________________________ // emptyParentEdge template inline bool emptyParentEdge(Iter< Index >, VSTree > > const &it); // "projects/library/seqan/index/index_wotd.h"(425) template inline bool emptyParentEdge(Iter< Index >, VSTree > > > const &it); // "projects/library/seqan/index/index_wotd.h"(438) template inline bool emptyParentEdge(Iter< TIndex, VSTree > > const &it); // "projects/library/seqan/index/index_esa_stree.h"(427) //____________________________________________________________________________ // end template inline typename Iterator >, Tag const>::Type end( String >& me, Tag const ); // "projects/library/seqan/index/index_pizzachili_string.h"(486) template inline typename Iterator > const, Tag const>::Type end( String > const& me, Tag const ); // "projects/library/seqan/index/index_pizzachili_string.h"(497) template inline typename Iterator, TSpec >::Type end(Index &index, TSpec const); // "projects/library/seqan/index/index_esa_stree.h"(927) template inline typename Iterator< Iter< TSTree, VSTree< BottomUp<_MaxRepeats > > > >::Type end(Iter< TSTree, VSTree< BottomUp<_MaxRepeats > > > &it); // "projects/library/seqan/index/index_esa_algs.h"(589) //____________________________________________________________________________ // eof template inline bool eof(Iter > &it); // "projects/library/seqan/index/index_esa_stree.h"(1440) template inline bool eof(Iter > const &it); // "projects/library/seqan/index/index_esa_stree.h"(1446) //____________________________________________________________________________ // equalRangeLCPE template inline Pair< typename Position::Type > equalRangeLCPE( TText const &text, TSA const &sa, TLCPE const &lcpe, TQuery const &query); // "projects/library/seqan/index/index_esa_find.h"(1586) template inline Pair< typename Position::Type > equalRangeLCPE( TText const &text, TSA const &sa, TLCPE const &lcpe, TQuery *query); // "projects/library/seqan/index/index_esa_find.h"(1688) //____________________________________________________________________________ // equalRangeLCPEIterator template inline Pair< typename Iterator::Type > equalRangeLCPEIterator( TText const &text, TSA const &sa, TLCPE const &lcpe, TQuery const &query); // "projects/library/seqan/index/index_esa_find.h"(1637) template inline Pair< typename Iterator::Type > equalRangeLCPEIterator( TText const &text, TSA const &sa, TLCPE const &lcpe, TQuery *query); // "projects/library/seqan/index/index_esa_find.h"(1707) //____________________________________________________________________________ // equalRangeSA template inline Pair< typename Position::Type > equalRangeSA( TText const &text, TSA const &sa, TQuery const &query, TFlatTreeSpec const); // "projects/library/seqan/index/index_esa_find.h"(853) template inline Pair< typename Position::Type > equalRangeSA( TText const &text, TSA const &sa, TQuery const &query); // "projects/library/seqan/index/index_esa_find.h"(870) template inline Pair< typename Position::Type > equalRangeSA( TText const &text, TSA const &sa, TQuery *query, TFlatTreeSpec const); // "projects/library/seqan/index/index_esa_find.h"(950) template inline Pair< typename Position::Type > equalRangeSA( TText const &text, TSA const &sa, TQuery *query); // "projects/library/seqan/index/index_esa_find.h"(967) //____________________________________________________________________________ // equalRangeSAIterator template inline Pair< typename Iterator::Type > equalRangeSAIterator( TText const &text, TSA const &sa, TQuery const &query); // "projects/library/seqan/index/index_esa_find.h"(727) template inline Pair< typename Iterator::Type > equalRangeSAIterator( TText const &text, TSA const &sa, TQuery *query); // "projects/library/seqan/index/index_esa_find.h"(773) //____________________________________________________________________________ // find template inline bool find( Finder, TSpecFinder> &finder, TPattern const &pattern); // "projects/library/seqan/index/index_find.h"(249) template inline bool find(Finder, TSpecFinder> &finder); // "projects/library/seqan/index/index_find.h"(260) //____________________________________________________________________________ // findRepeats template void findRepeats(TRepeatStore &repString, TText const &text, TRepeatSize minRepeatLen, TPeriodSize maxPeriod); // "projects/library/seqan/index/repeat_base.h"(92) template void findRepeats(TRepeatStore &repString, StringSet const &text, TRepeatSize minRepeatLen); // "projects/library/seqan/index/repeat_base.h"(189) //____________________________________________________________________________ // getFibre template inline typename Fibre > const, PizzaChili_Text>::Type getFibre(Index > const& me, PizzaChili_Text const); // "projects/library/seqan/index/index_pizzachili.h"(210) template inline typename Fibre >, PizzaChili_Text>::Type getFibre(Index >& me, PizzaChili_Text const); // "projects/library/seqan/index/index_pizzachili.h"(217) template inline typename Fibre, Fibre_Dir>::Type & getFibre(Index &index, Fibre_Dir); // "projects/library/seqan/index/index_qgram.h"(188) template inline typename Fibre const, Fibre_Dir>::Type & getFibre(Index const &index, Fibre_Dir); // "projects/library/seqan/index/index_qgram.h"(193) template inline typename Fibre, Fibre_Counts>::Type & getFibre(Index &index, Fibre_Counts); // "projects/library/seqan/index/index_qgram.h"(199) template inline typename Fibre const, Fibre_Counts>::Type & getFibre(Index const &index, Fibre_Counts); // "projects/library/seqan/index/index_qgram.h"(204) template inline typename Fibre, Fibre_CountsDir>::Type & getFibre(Index &index, Fibre_CountsDir); // "projects/library/seqan/index/index_qgram.h"(210) template inline typename Fibre const, Fibre_CountsDir>::Type & getFibre(Index const &index, Fibre_CountsDir); // "projects/library/seqan/index/index_qgram.h"(215) template inline typename Fibre, Fibre_Shape>::Type & getFibre(Index &index, Fibre_Shape); // "projects/library/seqan/index/index_qgram.h"(221) template inline typename Fibre const, Fibre_Shape>::Type & getFibre(Index const &index, Fibre_Shape); // "projects/library/seqan/index/index_qgram.h"(226) template inline typename Fibre, Fibre_Text>::Type & getFibre(Index &index, Fibre_Text); // "projects/library/seqan/index/index_base.h"(476) template inline typename Fibre const, Fibre_Text>::Type & getFibre(Index const &index, Fibre_Text); // "projects/library/seqan/index/index_base.h"(481) template inline typename Fibre, Fibre_RawText>::Type & getFibre(Index &index, Fibre_RawText); // "projects/library/seqan/index/index_base.h"(489) template inline typename Fibre const, Fibre_RawText>::Type & getFibre(Index const &index, Fibre_RawText); // "projects/library/seqan/index/index_base.h"(494) template inline typename Fibre, Fibre_SA>::Type & getFibre(Index &index, Fibre_SA); // "projects/library/seqan/index/index_base.h"(502) template inline typename Fibre const, Fibre_SA>::Type & getFibre(Index const &index, Fibre_SA); // "projects/library/seqan/index/index_base.h"(507) template inline typename Fibre const, Fibre_SA>::Type & getFibre(Index &index, Fibre_RawSA); // "projects/library/seqan/index/index_base.h"(515) template inline typename Fibre, TSpec>, Fibre_RawSA>::Type getFibre(Index, TSpec> &index, Fibre_RawSA); // "projects/library/seqan/index/index_base.h"(528) template inline typename Fibre, Fibre_LCP>::Type & getFibre(Index &index, Fibre_LCP); // "projects/library/seqan/index/index_base.h"(548) template inline typename Fibre const, Fibre_LCP>::Type & getFibre(Index const &index, Fibre_LCP); // "projects/library/seqan/index/index_base.h"(553) template inline typename Fibre, Fibre_LCPE>::Type & getFibre(Index &index, Fibre_LCPE); // "projects/library/seqan/index/index_base.h"(561) template inline typename Fibre const, Fibre_LCPE>::Type & getFibre(Index const &index, Fibre_LCPE); // "projects/library/seqan/index/index_base.h"(566) template inline typename Fibre, Fibre_ChildTab>::Type & getFibre(Index &index, Fibre_ChildTab); // "projects/library/seqan/index/index_base.h"(574) template inline typename Fibre const, Fibre_ChildTab>::Type & getFibre(Index const &index, Fibre_ChildTab); // "projects/library/seqan/index/index_base.h"(579) template inline typename Fibre, Fibre_BWT>::Type & getFibre(Index &index, Fibre_BWT); // "projects/library/seqan/index/index_base.h"(587) template inline typename Fibre const, Fibre_BWT>::Type & getFibre(Index const &index, Fibre_BWT); // "projects/library/seqan/index/index_base.h"(592) //____________________________________________________________________________ // getFrequency template inline typename Size::Type getFrequency(Iter > const &it, TSet &set); // "projects/library/seqan/index/index_esa_stree.h"(1686) template inline typename Size::Type getFrequency(Iter > const &it); // "projects/library/seqan/index/index_esa_stree.h"(1714) //____________________________________________________________________________ // getKmerSimilarityMatrix template inline void getKmerSimilarityMatrix( Index< TObject, Index_QGram > &index, TDistMatrix &distMat); // "projects/library/seqan/index/index_qgram.h"(1538) template inline void getKmerSimilarityMatrix( Index< TObject, Index_QGram > &index, TDistMatrix &distMat, TSeqNoString const &seqNo); // "projects/library/seqan/index/index_qgram.h"(1638) //____________________________________________________________________________ // getOccurrence template inline typename SAValue > >::Type getOccurrence(Iter< Index >, VSTree > const &it); // "projects/library/seqan/index/index_wotd.h"(418) template inline typename SAValue::Type getOccurrence(Iter< TIndex, VSTree > const &it); // "projects/library/seqan/index/index_esa_stree.h"(581) //____________________________________________________________________________ // getOccurrences template inline typename Infix< typename Fibre::Type const >::Type getOccurrences(Iter< TIndex, VSTree > const &it); // "projects/library/seqan/index/index_esa_stree.h"(621) //____________________________________________________________________________ // getOccurrencesBWT template inline typename Infix< typename Fibre::Type const >::Type getOccurrencesBWT(Iter< TIndex, VSTree > const &it); // "projects/library/seqan/index/index_esa_stree.h"(723) //____________________________________________________________________________ // goBegin template inline void goBegin(Finder< Index, TSpecFinder > & me); // "projects/library/seqan/index/index_find.h"(198) template inline void goBegin(Iter, VSTree > &it); // "projects/library/seqan/index/index_esa_stree.h"(887) template inline void goBegin(Iter >, VSTree< BottomUp > > &it); // "projects/library/seqan/index/index_esa_stree.h"(906) template inline Iter & goBegin(Iter &it); // "projects/library/seqan/index/index_esa_algs.h"(810) //____________________________________________________________________________ // goDown template inline bool goDown(Iter< TIndex, VSTree< TopDown > > &it); // "projects/library/seqan/index/index_esa_stree.h"(1085) template inline bool goDown( Iter< TIndex, VSTree< TopDown > > &it, TObject const &obj); // "projects/library/seqan/index/index_esa_stree.h"(1190) template inline bool goDown( Iter< TIndex, VSTree< TopDown > > &it, TString const &pattern, TSize &lcp); // "projects/library/seqan/index/index_esa_stree.h"(1200) //____________________________________________________________________________ // goEnd template inline void goEnd(Finder< Index, TSpecFinder > & me); // "projects/library/seqan/index/index_find.h"(206) template inline void goEnd(Iter >, VSTree > &it); // "projects/library/seqan/index/index_esa_stree.h"(938) template inline void goEnd(Iter >, VSTree< BottomUp > > &it); // "projects/library/seqan/index/index_esa_stree.h"(945) template inline Iter & goEnd(Iter &it); // "projects/library/seqan/index/index_esa_algs.h"(819) //____________________________________________________________________________ // goNext template inline void goNext(Iter > &it); // "projects/library/seqan/index/index_esa_stree.h"(956) template inline void goNext(Iter > &it, TTraits const traits); // "projects/library/seqan/index/index_esa_stree.h"(961) template inline void goNext(Iter< TSTree, VSTree< BottomUp > > &it); // "projects/library/seqan/index/index_esa_algs.h"(96) template inline void goNext(Iter< Index >, VSTree< BottomUp > > &it); // "projects/library/seqan/index/index_esa_algs.h"(187) template inline void goNext(Iter< TSTree, VSTree< BottomUp<_MaxRepeats > > > &it); // "projects/library/seqan/index/index_esa_algs.h"(533) template inline Iter & goNext(Iter &it); // "projects/library/seqan/index/index_esa_algs.h"(793) template inline void goNext(Iter< TSTree, VSTree< BottomUp > > &it); // "projects/library/seqan/index/index_esa_algs_multi.h"(100) template inline Iter & goNext(Iter &it); // "projects/library/seqan/index/index_esa_algs_multi.h"(630) //____________________________________________________________________________ // goNextImpl template inline void goNextImpl( Iter > > &it, VSTreeIteratorTraits<_Postorder, THideEmptyEdges> const); // "projects/library/seqan/index/index_esa_stree.h"(284) template inline void goNextImpl( Iter< TIndex, VSTree< TopDown< ParentLinks > > > &it, VSTreeIteratorTraits<_Preorder, THideEmptyEdges> const); // "projects/library/seqan/index/index_esa_stree.h"(1405) template inline void goNextImpl( Iter< TIndex, VSTree< TopDown< ParentLinks > > > &it, VSTreeIteratorTraits<_Postorder, THideEmptyEdges> const); // "projects/library/seqan/index/index_esa_stree.h"(1421) //____________________________________________________________________________ // goRight template inline bool goRight(Iter< TIndex, VSTree< TopDown > > &it); // "projects/library/seqan/index/index_esa_stree.h"(1316) //____________________________________________________________________________ // goRoot template inline void goRoot(Iter< Index >, VSTree > &it); // "projects/library/seqan/index/index_wotd.h"(454) template inline void goRoot(Iter< Index >, VSTree > &it); // "projects/library/seqan/index/index_wotd.h"(466) template inline void goRoot(Iter, VSTree > &it); // "projects/library/seqan/index/index_esa_stree.h"(865) //____________________________________________________________________________ // goUp template inline bool goUp(Iter< TIndex, VSTree< TopDown< ParentLinks > > > &it); // "projects/library/seqan/index/index_esa_stree.h"(1244) //____________________________________________________________________________ // hash template inline typename Value< Shape >::Type hash(Shape &me, TIter it); // "projects/library/seqan/index/shape_gapped.h"(368) template inline typename Value< Shape > >::Type hash(Shape > &me, TIter it, TSize charsLeft); // "projects/library/seqan/index/shape_gapped.h"(385) template inline typename Value< Shape > > >::Type hash(Shape > > &me, TIter it); // "projects/library/seqan/index/shape_gapped.h"(517) template typename Value< Shape >::Type hash(Shape &me, TIter it); // "projects/library/seqan/index/shape_base.h"(271) template inline typename Value< Shape > >::Type hash(Shape > &me, TIter it); // "projects/library/seqan/index/shape_base.h"(307) template inline typename Value< Shape >::Type hash(Shape &me, TIter it, TSize charsLeft); // "projects/library/seqan/index/shape_base.h"(320) template typename Value< Shape > >::Type hash( Shape > &me, Tuple const &tuple); // "projects/library/seqan/index/shape_base.h"(379) template typename Value< Shape > >::Type hash( Shape > &me, Tuple const &tuple); // "projects/library/seqan/index/shape_base.h"(400) //____________________________________________________________________________ // hash2 template inline typename Value< Shape >::Type hash2(Shape &me, TIter it, TSize charsLeft); // "projects/library/seqan/index/shape_base.h"(490) //____________________________________________________________________________ // hash2Next template inline typename Value< Shape >::Type hash2Next(Shape &me, TIter &it, TSize charsLeft); // "projects/library/seqan/index/shape_base.h"(568) //____________________________________________________________________________ // hash2Upper template inline typename Value< Shape >::Type hash2Upper(Shape &me, TIter it, TSize charsLeft); // "projects/library/seqan/index/shape_base.h"(519) //____________________________________________________________________________ // hashNext template inline typename Value< Shape > >::Type hashNext(Shape > &me, TIter it); // "projects/library/seqan/index/shape_gapped.h"(536) template inline typename Value< Shape >::Type hashNext(Shape &me, TIter &it); // "projects/library/seqan/index/shape_base.h"(463) //____________________________________________________________________________ // hashUpper template inline typename Value< Shape > >::Type hashUpper(Shape > &me, TIter it, TSize charsLeft); // "projects/library/seqan/index/shape_gapped.h"(413) template inline typename Value< Shape >::Type hashUpper(Shape &me, TIter it, TSize charsLeft); // "projects/library/seqan/index/shape_base.h"(422) //____________________________________________________________________________ // host template inline typename _Parameter< Index >::Type host(Finder< Index, TSpecFinder > & me); // "projects/library/seqan/index/index_find.h"(84) template inline typename _Parameter< Index >::Type host(Finder< Index, TSpecFinder > const & me); // "projects/library/seqan/index/index_find.h"(92) //____________________________________________________________________________ // hostIterator template inline typename Iterator< typename Fibre, Fibre_SA>::Type, Standard>::Type & hostIterator(Finder< Index, TSpecFinder > & me); // "projects/library/seqan/index/index_find.h"(140) template inline typename Iterator< typename Fibre, Fibre_SA>::Type, Standard>::Type const & hostIterator(Finder< Index, TSpecFinder > const & me); // "projects/library/seqan/index/index_find.h"(148) //____________________________________________________________________________ // indexBWT template inline typename Fibre, Fibre_BWT>::Type & indexBWT(Index &index); // "projects/library/seqan/index/index_base.h"(932) template inline typename Fibre const, Fibre_BWT>::Type & indexBWT(Index const &index); // "projects/library/seqan/index/index_base.h"(934) //____________________________________________________________________________ // indexChildTab template inline typename Fibre, Fibre_ChildTab>::Type & indexChildTab(Index &index); // "projects/library/seqan/index/index_base.h"(948) template inline typename Fibre const, Fibre_ChildTab>::Type & indexChildTab(Index const &index); // "projects/library/seqan/index/index_base.h"(950) //____________________________________________________________________________ // indexCounts template inline typename Fibre, Fibre_Counts>::Type & indexCounts(Index &index); // "projects/library/seqan/index/index_qgram.h"(289) template inline typename Fibre const, Fibre_Counts>::Type & indexCounts(Index const &index); // "projects/library/seqan/index/index_qgram.h"(294) //____________________________________________________________________________ // indexCountsDir template inline typename Fibre, Fibre_CountsDir>::Type & indexCountsDir(Index &index); // "projects/library/seqan/index/index_qgram.h"(300) template inline typename Fibre const, Fibre_CountsDir>::Type & indexCountsDir(Index const &index); // "projects/library/seqan/index/index_qgram.h"(305) //____________________________________________________________________________ // indexCreate template inline bool indexCreate(Index > > &index, Wotd_SA const, Default const); // "projects/library/seqan/index/index_dfi.h"(518) template inline bool indexCreate(Index >& me, PizzaChili_Compressed const); // "projects/library/seqan/index/index_pizzachili.h"(278) template inline bool indexCreate(Index > &index, Wotd_SA const, Default const); // "projects/library/seqan/index/index_wotd.h"(1712) template inline bool indexCreate(Index &index, Fibre_SA, TSpecAlg const alg); // "projects/library/seqan/index/index_shims.h"(498) template inline bool indexCreate(Index &index, Fibre_LCP, TSpecAlg const alg); // "projects/library/seqan/index/index_shims.h"(506) template inline bool indexCreate(Index &index, Fibre_LCPE, TSpecAlg const alg); // "projects/library/seqan/index/index_shims.h"(514) template inline bool indexCreate(Index &index, Fibre_BWT, BWT const); // "projects/library/seqan/index/index_shims.h"(523) template inline bool indexCreate(Index &index, Fibre_ChildTab, ChildTab const); // "projects/library/seqan/index/index_shims.h"(531) template inline bool indexCreate(Index &index, Tag const fibre); // "projects/library/seqan/index/index_shims.h"(539) template inline bool indexCreate( Index > &index, Fibre_SADir, Default const); // "projects/library/seqan/index/index_qgram.h"(1459) template inline bool indexCreate( Index > &index, Fibre_SA, Default const alg); // "projects/library/seqan/index/index_qgram.h"(1487) template inline bool indexCreate( Index > &index, Fibre_Counts, Default const); // "projects/library/seqan/index/index_qgram.h"(1509) //____________________________________________________________________________ // indexDir template inline typename Fibre, Fibre_Dir>::Type & indexDir(Index &index); // "projects/library/seqan/index/index_qgram.h"(243) template inline typename Fibre const, Fibre_Dir>::Type & indexDir(Index const &index); // "projects/library/seqan/index/index_qgram.h"(248) //____________________________________________________________________________ // indexLCP template inline typename Fibre, Fibre_LCP>::Type & indexLCP(Index &index); // "projects/library/seqan/index/index_base.h"(900) template inline typename Fibre const, Fibre_LCP>::Type & indexLCP(Index const &index); // "projects/library/seqan/index/index_base.h"(902) //____________________________________________________________________________ // indexLCPE template inline typename Fibre, Fibre_LCPE>::Type & indexLCPE(Index &index); // "projects/library/seqan/index/index_base.h"(916) template inline typename Fibre const, Fibre_LCPE>::Type & indexLCPE(Index const &index); // "projects/library/seqan/index/index_base.h"(918) //____________________________________________________________________________ // indexRawSA template inline typename Fibre, Fibre_RawSA>::Type indexRawSA(Index &index); // "projects/library/seqan/index/index_base.h"(884) template inline typename Fibre const, Fibre_RawSA>::Type indexRawSA(Index const &index); // "projects/library/seqan/index/index_base.h"(886) //____________________________________________________________________________ // indexRawText template inline typename Fibre, Fibre_RawText>::Type & indexRawText(Index &index); // "projects/library/seqan/index/index_base.h"(852) template inline typename Fibre const, Fibre_RawText>::Type & indexRawText(Index const &index); // "projects/library/seqan/index/index_base.h"(854) //____________________________________________________________________________ // indexRequire template inline bool indexRequire(Index &index, Tag const fibre); // "projects/library/seqan/index/index_shims.h"(581) //____________________________________________________________________________ // indexSA template inline typename Fibre, Fibre_SA>::Type & indexSA(Index &index); // "projects/library/seqan/index/index_base.h"(868) template inline typename Fibre const, Fibre_SA>::Type & indexSA(Index const &index); // "projects/library/seqan/index/index_base.h"(870) //____________________________________________________________________________ // indexShape template inline typename Fibre, Fibre_Shape>::Type & indexShape(Index &index); // "projects/library/seqan/index/index_qgram.h"(311) template inline typename Fibre const, Fibre_Shape>::Type & indexShape(Index const &index); // "projects/library/seqan/index/index_qgram.h"(316) //____________________________________________________________________________ // indexSolveDependencies template inline bool indexSolveDependencies(Index >& me, PizzaChili_Compressed const); // "projects/library/seqan/index/index_pizzachili.h"(242) template inline bool indexSolveDependencies(Index &, Tag const); // "projects/library/seqan/index/index_shims.h"(612) template inline bool indexSolveDependencies(Index &index, Fibre_LCP); // "projects/library/seqan/index/index_shims.h"(618) template inline bool indexSolveDependencies(Index &index, Fibre_LCPE); // "projects/library/seqan/index/index_shims.h"(624) template inline bool indexSolveDependencies(Index &index, Fibre_ChildTab); // "projects/library/seqan/index/index_shims.h"(630) template inline bool indexSolveDependencies(Index &index, Fibre_BWT); // "projects/library/seqan/index/index_shims.h"(636) //____________________________________________________________________________ // indexSupplied template inline bool indexSupplied(Index >& me, PizzaChili_Compressed const); // "projects/library/seqan/index/index_pizzachili.h"(226) template inline bool indexSupplied(Index >& me, PizzaChili_Text const); // "projects/library/seqan/index/index_pizzachili.h"(233) template inline bool indexSupplied(Index &index, Tag const fibre); // "projects/library/seqan/index/index_shims.h"(560) template inline bool indexSupplied(Index &index, Fibre_SADir); // "projects/library/seqan/index/index_qgram.h"(1478) //____________________________________________________________________________ // indexText template inline typename Fibre >, PizzaChili_Text>::Type indexText(Index >& me); // "projects/library/seqan/index/index_pizzachili.h"(194) template inline typename Fibre > const, PizzaChili_Text>::Type indexText(Index > const& me); // "projects/library/seqan/index/index_pizzachili.h"(201) template inline typename Fibre, Fibre_Text>::Type & indexText(Index &index); // "projects/library/seqan/index/index_base.h"(810) template inline typename Fibre const, Fibre_Text>::Type & indexText(Index const &index); // "projects/library/seqan/index/index_base.h"(812) //____________________________________________________________________________ // infix template inline typename Infix > >::Type infix( String > const& me, TPosBegin begin, TPosEnd end ); // "projects/library/seqan/index/index_pizzachili_string.h"(724) template inline typename Infix > >::Type infix( String >& me, TPosBegin begin, TPosEnd end ); // "projects/library/seqan/index/index_pizzachili_string.h"(735) //____________________________________________________________________________ // isLeaf template inline bool isLeaf(Iter > const &it); // "projects/library/seqan/index/index_esa_stree.h"(1795) //____________________________________________________________________________ // isLeftMaximal template inline bool isLeftMaximal(Iter > const &it); // "projects/library/seqan/index/index_esa_stree.h"(1541) //____________________________________________________________________________ // isPartiallyLeftExtensible template inline bool isPartiallyLeftExtensible(Iter > const &it, TSet &charSet); // "projects/library/seqan/index/index_esa_stree.h"(1589) template inline bool isPartiallyLeftExtensible(Iter > const &it); // "projects/library/seqan/index/index_esa_stree.h"(1623) //____________________________________________________________________________ // isRightTerminal template inline bool isRightTerminal(Iter > const &it); // "projects/library/seqan/index/index_esa_stree.h"(1518) //____________________________________________________________________________ // isRoot template inline bool isRoot(Iter > > const &it); // "projects/library/seqan/index/index_esa_stree.h"(1489) template inline bool isRoot(Iter > const &it); // "projects/library/seqan/index/index_esa_stree.h"(1495) //____________________________________________________________________________ // isUnique template inline bool isUnique(Iter > const &it, TSet &set); // "projects/library/seqan/index/index_esa_stree.h"(1641) template inline bool isUnique(Iter > const &it); // "projects/library/seqan/index/index_esa_stree.h"(1664) //____________________________________________________________________________ // lca template inline bool lca( Iter > > > &a, Iter > > > &b, Iter > > > &_lca); // "projects/library/seqan/index/index_esa_stree.h"(456) //____________________________________________________________________________ // lcp template inline typename Size::Type lcp( Iter > > > &a, Iter > > > &b); // "projects/library/seqan/index/index_esa_stree.h"(507) //____________________________________________________________________________ // lcpAt template inline typename Reference::Type>::Type lcpAt(TPos i, TIndex &index); // "projects/library/seqan/index/index_base.h"(714) template inline typename Reference::Type>::Type lcpAt(TPos i, TIndex const &index); // "projects/library/seqan/index/index_base.h"(718) //____________________________________________________________________________ // lcp_process template static void lcp_process(TTextInput &textIn, TInvertedSAInput &invertedSAIn, TDest &dest, LcpConfig conf); // "projects/library/seqan/index/pump_lcp_core.h"(56) template static inline void lcp_process(TTextInput &textIn, TInvertedSAInput &invertedSAIn, TDest &dest); // "projects/library/seqan/index/pump_lcp_core.h"(196) //____________________________________________________________________________ // lcp_process_multi template static void lcp_process_multi( TTextInput &textIn, TLimitsString const &limits, TInvertedSAInput &invertedSAIn, TDest &dest, LcpConfig conf); // "projects/library/seqan/index/pump_lcp_core.h"(208) template static void lcp_process_multi( TTextInput &textIn, TLimitsString const &limits, TInvertedSAInput &invertedSAIn, TDest &dest); // "projects/library/seqan/index/pump_lcp_core.h"(367) //____________________________________________________________________________ // lcpeAt template inline typename Reference::Type>::Type lcpeAt(TPos i, TIndex &index); // "projects/library/seqan/index/index_base.h"(735) template inline typename Reference::Type>::Type lcpeAt(TPos i, TIndex const &index); // "projects/library/seqan/index/index_base.h"(739) //____________________________________________________________________________ // length //template inline typename Size< Pipe< TInput, LarssonSadakane > >::Type length(Pipe< TInput, LarssonSadakane > const &me); // "projects/library/seqan/index/index_sa_lss.h"(421) template inline typename Size > >::Type length(String > const& me); // "projects/library/seqan/index/index_pizzachili_string.h"(379) template inline typename Size< Shape >::Type length(Shape const &me); // "projects/library/seqan/index/shape_base.h"(215) template inline typename Size >::Type length(Index const &index); // "projects/library/seqan/index/index_base.h"(601) template inline typename Size::Type length(Iter< TSTree, VSTree< BottomUp<_MaxRepeats > > > const &it); // "projects/library/seqan/index/index_esa_algs.h"(570) template inline typename Size< MaxRepeat >::Type length(MaxRepeat const &repeat); // "projects/library/seqan/index/index_esa_algs.h"(619) template inline typename Size< MultiMEM >::Type length(MultiMEM const &repeat); // "projects/library/seqan/index/index_esa_algs_multi.h"(402) //template inline typename Size< Pipe< TInput, Merger3 > >::Type length(Pipe< TInput, Merger3 > const &me); // "projects/library/seqan/index/pipe_merger3.h"(145) //template inline typename Size< Pipe< TInput, Merger7 > >::Type length(Pipe< TInput, Merger7 > const &me); // "projects/library/seqan/index/pipe_merger7.h"(494) //template inline typename Size< Pipe< TInput, Merger7Multi > >::Type length(Pipe< TInput, Merger7Multi > const &me); // "projects/library/seqan/index/pipe_merger7.h"(524) //____________________________________________________________________________ // lowerBoundLCPE template inline typename Position::Type lowerBoundLCPE( TText const &text, TSA const &sa, TLCPE const &lcpe, TQuery const &query); // "projects/library/seqan/index/index_esa_find.h"(1554) template inline typename Position::Type lowerBoundLCPE( TText const &text, TSA const &sa, TLCPE const &lcpe, TQuery *query); // "projects/library/seqan/index/index_esa_find.h"(1656) //____________________________________________________________________________ // lowerBoundLCPEIterator template inline typename Iterator::Type lowerBoundLCPEIterator( TText const &text, TSA const &sa, TLCPE const &lcpe, TQuery const &query); // "projects/library/seqan/index/index_esa_find.h"(1605) //____________________________________________________________________________ // lowerBoundSA template inline typename Position::Type lowerBoundSA( TText const &text, TSA const &sa, TQuery const &query, TFlatTreeSpec const); // "projects/library/seqan/index/index_esa_find.h"(793) template inline typename Position::Type lowerBoundSA( TText const &text, TSA const &sa, TQuery const &query); // "projects/library/seqan/index/index_esa_find.h"(807) template inline typename Position::Type lowerBoundSA( TText const &text, TSA const &sa, TQuery *query, TFlatTreeSpec const); // "projects/library/seqan/index/index_esa_find.h"(890) template inline typename Position::Type lowerBoundSA( TText const &text, TSA const &sa, TQuery *query); // "projects/library/seqan/index/index_esa_find.h"(904) //____________________________________________________________________________ // lowerBoundSAIterator template inline typename Iterator::Type lowerBoundSAIterator( TText const &text, TSA const &sa, TQuery const &query); // "projects/library/seqan/index/index_esa_find.h"(699) template inline typename Iterator::Type lowerBoundSAIterator( TText const &text, TSA const &sa, TQuery *query); // "projects/library/seqan/index/index_esa_find.h"(745) //____________________________________________________________________________ // nodeDepth template inline typename Size::Type nodeDepth(Iter< TIndex, VSTree > > > const &it); // "projects/library/seqan/index/index_esa_stree.h"(390) //____________________________________________________________________________ // nodeHullPredicate template inline bool nodeHullPredicate( Iter > >, TSpec> const &it); // "projects/library/seqan/index/index_dfi.h"(158) template inline bool nodeHullPredicate(Iter &); // "projects/library/seqan/index/index_esa_stree.h"(857) template bool nodeHullPredicate(Iter >, TSpec> &it); // "projects/library/seqan/index/repeat_base.h"(75) //____________________________________________________________________________ // nodePredicate template inline bool nodePredicate( Iter > >, TSpec> const &it); // "projects/library/seqan/index/index_dfi.h"(145) template inline bool nodePredicate(Iter &); // "projects/library/seqan/index/index_esa_stree.h"(839) template bool nodePredicate(Iter >, TSpec> &it); // "projects/library/seqan/index/repeat_base.h"(67) //____________________________________________________________________________ // nodeUp template inline typename VertexDescriptor::Type nodeUp(Iter< TIndex, VSTree< TopDown< ParentLinks > > > const &it); // "projects/library/seqan/index/index_esa_stree.h"(1256) template inline typename VertexDescriptor::Type const & nodeUp(Iter< TIndex, VSTree< TopDown > > const &it); // "projects/library/seqan/index/index_esa_stree.h"(1271) //____________________________________________________________________________ // open template inline bool open( Index< TObject, Index_ESA > &index, const char *fileName, int openMode); // "projects/library/seqan/index/index_esa_base.h"(324) template inline bool open( Index< TObject, Index_ESA > &index, const char *fileName); // "projects/library/seqan/index/index_esa_base.h"(340) template inline bool open( Index >& me, char const* filename ); // "projects/library/seqan/index/index_pizzachili.h"(334) template inline bool open(String &string, const char *fileName, int openMode); // "projects/library/seqan/index/index_shims.h"(646) template inline bool open(String &string, const char *fileName); // "projects/library/seqan/index/index_shims.h"(654) template inline bool open(Segment &string, const char *fileName, int openMode); // "projects/library/seqan/index/index_shims.h"(660) template inline bool open(Segment &string, const char *fileName); // "projects/library/seqan/index/index_shims.h"(668) template inline bool open(StringSet, TSSSpec> &multi, const char *fileName, int openMode); // "projects/library/seqan/index/index_shims.h"(674) template inline bool open(StringSet, TSSSpec> &multi, const char *fileName); // "projects/library/seqan/index/index_shims.h"(694) template inline bool open( Index< TObject, Index_QGram > &index, const char *fileName, int openMode); // "projects/library/seqan/index/index_qgram.h"(1755) template inline bool open( Index< TObject, Index_QGram > &index, const char *fileName); // "projects/library/seqan/index/index_qgram.h"(1769) //____________________________________________________________________________ // operator!= template inline bool operator!= ( Iter const &itA, Iter const &itB); // "projects/library/seqan/index/index_esa_algs.h"(851) //____________________________________________________________________________ // operator<< //template inline bool operator<<(Pipe< TInput, Multi > &me, TObject &textIn); // "projects/library/seqan/index/index_skew7_multi.h"(404) //template inline bool operator<<(Pipe< TInput, ChildTab > &me, _TLCPInput const &in); // "projects/library/seqan/index/index_childtab.h"(162) //template inline bool operator<<(Pipe< TInput, Kasai > &me, Bundle2< _TTextInput, _TSuffixArrayInput > const &bundleIn); // "projects/library/seqan/index/index_lcp.h"(131) //template inline bool operator<<(Pipe< TInput, Multi > &me, Bundle2< _TTextInput, _TSuffixArrayInput > const &bundleIn); // "projects/library/seqan/index/index_lcp.h"(234) //template inline bool operator<<(Pipe< TInput, Skew3 > &me, TObject &textIn); // "projects/library/seqan/index/index_skew3.h"(285) //template inline bool operator<<(Pipe< TInput, BWT > &me, Bundle2< _TTextInput, _TSuffixArrayInput > const &bundleIn); // "projects/library/seqan/index/index_bwt.h"(113) //template inline bool operator<<(Pipe< TInput, Multi > &me, Bundle2< _TTextInput, _TSuffixArrayInput > const &bundleIn); // "projects/library/seqan/index/index_bwt.h"(229) //template std::ostream& operator<<(std::ostream &out, const SkewDCStream &s); // "projects/library/seqan/index/pipe_merger7.h"(77) //template inline bool operator<<(Pipe< TInput, Skew7 > &me, TObject &textIn); // "projects/library/seqan/index/index_skew7.h"(385) //____________________________________________________________________________ // operator== template inline bool operator== ( Iter const &itA, Iter const &itB); // "projects/library/seqan/index/index_esa_algs.h"(840) //____________________________________________________________________________ // orderOccurrences template inline void orderOccurrences(String &occString); // "projects/library/seqan/index/index_shims.h"(474) //____________________________________________________________________________ // parentEdgeFirstChar template inline typename Value::Type parentEdgeFirstChar(Iter< TIndex, VSTree > const &it); // "projects/library/seqan/index/index_esa_stree.h"(1377) //____________________________________________________________________________ // parentEdgeLabel template inline typename Infix< typename Fibre >, ESA_RawText>::Type const >::Type parentEdgeLabel(Iter< Index >, VSTree< TopDown > > const &it); // "projects/library/seqan/index/index_wotd.h"(401) template inline typename Infix< typename Fibre::Type const >::Type parentEdgeLabel(Iter< TIndex, VSTree< TopDown > > const &it); // "projects/library/seqan/index/index_esa_stree.h"(1357) //____________________________________________________________________________ // parentEdgeLength template inline typename Size::Type parentEdgeLength(TIndex const &index, _VertexWotdOriginal &vDesc); // "projects/library/seqan/index/index_wotd.h"(309) template inline typename Size::Type parentEdgeLength(TIndex const &index, _VertexWotdModified &vDesc); // "projects/library/seqan/index/index_wotd.h"(332) template inline typename Size< Index > >::Type parentEdgeLength(Iter< Index >, VSTree< TopDown > > const &it); // "projects/library/seqan/index/index_wotd.h"(364) template inline typename Size< Index > >::Type parentEdgeLength(Iter< Index >, VSTree< TopDown< ParentLinks > > > const &it); // "projects/library/seqan/index/index_esa_stree.h"(1339) //____________________________________________________________________________ // parentRepLength template inline typename Size< Index > >::Type parentRepLength(Iter< Index >, VSTree< TopDown > > const &it); // "projects/library/seqan/index/index_wotd.h"(374) template inline typename Size< Index > >::Type parentRepLength(Iter< Index >, VSTree< TopDown< ParentLinks > > > const &it); // "projects/library/seqan/index/index_wotd.h"(383) template inline typename Size::Type parentRepLength(Iter< TIndex, VSTree > > const &it); // "projects/library/seqan/index/index_esa_stree.h"(408) //____________________________________________________________________________ // position template inline typename Position< Finder< Index, TSpecFinder > >::Type position(Finder< Index, TSpecFinder > & me); // "projects/library/seqan/index/index_find.h"(226) template inline typename Position< Finder< Index, TSpecFinder > >::Type position(Finder< Index, TSpecFinder > const & me); // "projects/library/seqan/index/index_find.h"(235) //____________________________________________________________________________ // prefix template inline typename Prefix > >::Type prefix( String > const& me, TPos end ); // "projects/library/seqan/index/index_pizzachili_string.h"(747) template inline typename Prefix > >::Type prefix( String >& me, TPos end ); // "projects/library/seqan/index/index_pizzachili_string.h"(757) //____________________________________________________________________________ // radixExtend template void radixExtend( TSortedArray &b, TUnsortedArray const &a, TText const &r, TCountArray &c, unsigned K); // "projects/library/seqan/index/radix.h"(118) //____________________________________________________________________________ // radixExtendClip template void radixExtendClip( TSortedArray &b, TUnsortedArray const &a, TText const &r, TCountArray &c, unsigned K); // "projects/library/seqan/index/radix.h"(153) //____________________________________________________________________________ // radixPass template void radixPass( TSortedArray &b, TUnsortedArray const &a, TText const &r, TCountArray &c, unsigned K); // "projects/library/seqan/index/radix.h"(39) template void radixPass( TSortedArray &b, TUnsortedArray const &a, TText const &r, TCountArray &c, unsigned K, TShift shift); // "projects/library/seqan/index/radix.h"(75) //____________________________________________________________________________ // rawsaAt template inline typename Value::Type>::Type rawsaAt(TPos i, TIndex const &index); // "projects/library/seqan/index/index_base.h"(696) //____________________________________________________________________________ // rawtextAt template inline typename Reference::Type>::Type rawtextAt(TPos i, TIndex &index); // "projects/library/seqan/index/index_base.h"(666) template inline typename Reference::Type>::Type rawtextAt(TPos i, TIndex const &index); // "projects/library/seqan/index/index_base.h"(670) //____________________________________________________________________________ // repLength template inline typename Size< Index > >::Type repLength(Iter< Index >, VSTree< TopDown > > const &it); // "projects/library/seqan/index/index_wotd.h"(392) template inline typename Size::Type repLength(Iter< TIndex, VSTree > > const &it); // "projects/library/seqan/index/index_esa_stree.h"(355) template inline typename Size::Type repLength(TIndex const &index, VertexESA const &vDesc); // "projects/library/seqan/index/index_esa_stree.h"(367) template inline typename Size::Type repLength(Iter< TIndex, VSTree > > const &it); // "projects/library/seqan/index/index_esa_stree.h"(383) template inline typename Size::Type repLength(Iter< TSTree, VSTree< BottomUp<_MaxRepeats > > > const &it); // "projects/library/seqan/index/index_esa_algs.h"(562) //____________________________________________________________________________ // representative template inline typename Infix< typename Fibre::Type const >::Type representative(Iter< TIndex, VSTree > const &it); // "projects/library/seqan/index/index_esa_stree.h"(744) //____________________________________________________________________________ // resize template inline typename Size< Shape >::Type resize(Shape & me, TSize new_length); // "projects/library/seqan/index/shape_base.h"(246) //____________________________________________________________________________ // saAt template inline typename Reference::Type>::Type saAt(TPos i, TIndex &index); // "projects/library/seqan/index/index_base.h"(687) template inline typename Reference::Type>::Type saAt(TPos i, TIndex const &index); // "projects/library/seqan/index/index_base.h"(691) //____________________________________________________________________________ // save template inline bool save( Index< TObject, Index_ESA > &index, const char *fileName, int openMode); // "projects/library/seqan/index/index_esa_base.h"(353) template inline bool save( Index< TObject, Index_ESA > &index, const char *fileName); // "projects/library/seqan/index/index_esa_base.h"(369) template inline bool save( Index >& me, char const* filename ); // "projects/library/seqan/index/index_pizzachili.h"(352) template inline bool save(String const &string, const char *fileName, int openMode); // "projects/library/seqan/index/index_shims.h"(704) template inline bool save(String &string, const char *fileName); // "projects/library/seqan/index/index_shims.h"(714) template inline bool save(Segment const &string, const char *fileName, int openMode); // "projects/library/seqan/index/index_shims.h"(720) template inline bool save(Segment const &string, const char *fileName); // "projects/library/seqan/index/index_shims.h"(729) template inline bool save(StringSet, TSSSpec> const &multi, const char *fileName, int openMode); // "projects/library/seqan/index/index_shims.h"(735) template inline bool save(StringSet, TSSSpec> const &multi, const char *fileName); // "projects/library/seqan/index/index_shims.h"(750) template inline bool save( Index< TObject, Index_QGram > &index, const char *fileName, int openMode); // "projects/library/seqan/index/index_qgram.h"(1782) template inline bool save( Index< TObject, Index_QGram > &index, const char *fileName); // "projects/library/seqan/index/index_qgram.h"(1796) //____________________________________________________________________________ // sequenceLength template inline typename Size >::Type sequenceLength(TSeqNo seqNo, Index const &index); // "projects/library/seqan/index/index_base.h"(617) //____________________________________________________________________________ // setContainer template inline void setContainer( Finder< Index, TSpecFinder > & me, typename _Parameter >::Type container_); // "projects/library/seqan/index/index_find.h"(130) //____________________________________________________________________________ // setHost template inline void setHost( Finder< Index, TSpecFinder > & me, typename _Parameter >::Type container_); // "projects/library/seqan/index/index_find.h"(120) //____________________________________________________________________________ // setIndexText template inline void setIndexText(Index >& me, TOtherText& text); // "projects/library/seqan/index/index_pizzachili.h"(303) //____________________________________________________________________________ // sizeofLCPE template inline TSize sizeofLCPE(TSize n); // "projects/library/seqan/index/index_lcp_tree.h"(105) template inline void sizeofLCPE(LCPFwdIt _First, LCPFwdIt _Last, TSize &_Size); // "projects/library/seqan/index/index_lcp_tree.h"(124) //____________________________________________________________________________ // sizeofLCPH template inline TSize sizeofLCPH(TSize n); // "projects/library/seqan/index/index_lcp_tree.h"(116) template inline void sizeofLCPH(LCPFwdIt _First, LCPFwdIt _Last, TSize &_Size); // "projects/library/seqan/index/index_lcp_tree.h"(132) //____________________________________________________________________________ // sizeofSAB template inline TSize sizeofSAB(TSize n, unsigned BlockSize); // "projects/library/seqan/index/index_sa_btree.h"(79) template inline void sizeofSAB(SAFwdIt _First, SAFwdIt _Last, TSize &_Size, unsigned BlockSize); // "projects/library/seqan/index/index_sa_btree.h"(90) //____________________________________________________________________________ // skew3_extend template static bool skew3_extend(TTextInput &textIn, TNameInput &nameIn, TOut0 &out0, TOut12 &out12); // "projects/library/seqan/index/pump_extender3.h"(54) //____________________________________________________________________________ // skew7_extend template static bool skew7_extend(TTextInput &textIn, TNameInput &nameIn, TOut0 &out0, TOut3 &out3, TOut5 &out5, TOut6 &out6, TOut124 &out124); // "projects/library/seqan/index/pump_extender7.h"(75) //____________________________________________________________________________ // skew7_extend_multi template static bool skew7_extend_multi( TTextInput &textIn, TLimitsString const &limits, TNameInput &nameIn1, TNameInput &nameIn2, TNameInput &nameIn4, TOut0 &out0, TOut3 &out3, TOut5 &out5, TOut6 &out6, TOut124 &out124); // "projects/library/seqan/index/pump_extender7.h"(265) //____________________________________________________________________________ // skew7_separate_slices template static void skew7_separate_slices( TInput &in, TFunctor const &funcSlice, TOut1 &out1, TOut2 &out2, TOut4 &out4); // "projects/library/seqan/index/pump_separator7.h"(35) //____________________________________________________________________________ // stringSetLimits template inline typename StringSetLimits::Type stringSetLimits(Index &); // "projects/library/seqan/index/index_base.h"(818) template inline typename StringSetLimits::Type stringSetLimits(Index const &); // "projects/library/seqan/index/index_base.h"(824) template inline typename StringSetLimits< StringSet const >::Type & stringSetLimits(Index, TSpec> &index); // "projects/library/seqan/index/index_base.h"(830) template inline typename StringSetLimits< StringSet const >::Type & stringSetLimits(Index, TSpec> const &index); // "projects/library/seqan/index/index_base.h"(836) //____________________________________________________________________________ // stringToShape template inline void stringToShape( Shape > &me, TShapeString const &bitmap); // "projects/library/seqan/index/shape_gapped.h"(561) //____________________________________________________________________________ // suffix template inline typename Suffix > >::Type suffix( String > const& me, TPos begin ); // "projects/library/seqan/index/index_pizzachili_string.h"(769) template inline typename Suffix > >::Type suffix( String >& me, TPos begin ); // "projects/library/seqan/index/index_pizzachili_string.h"(779) //____________________________________________________________________________ // suffixLength template inline typename Size >::Type suffixLength(TPos pos, Index const &index); // "projects/library/seqan/index/index_base.h"(625) //____________________________________________________________________________ // textAt template inline typename Reference::Type>::Type textAt(TPos i, TIndex &index); // "projects/library/seqan/index/index_base.h"(635) template inline typename Reference, TSpec>, Fibre_RawText>::Type>::Type textAt(TPos i, Index< StringSet, TSpec> &index); // "projects/library/seqan/index/index_base.h"(640) template inline typename Reference >, TSpec>, Fibre_RawText>::Type>::Type textAt(TPos i, Index< StringSet >, TSpec> &index); // "projects/library/seqan/index/index_base.h"(645) //____________________________________________________________________________ // treeLevelsSAB template inline unsigned treeLevelsSAB(TSize saSize, unsigned BlockSize); // "projects/library/seqan/index/index_sa_btree.h"(103) //____________________________________________________________________________ // unhash template inline void unhash(TString &result, THash hash, unsigned q); // "projects/library/seqan/index/shape_base.h"(593) //____________________________________________________________________________ // upperBoundLCPE template inline typename Position::Type upperBoundLCPE( TText const &text, TSA const &sa, TLCPE const &lcpe, TQuery const &query); // "projects/library/seqan/index/index_esa_find.h"(1570) template inline typename Position::Type upperBoundLCPE( TText const &text, TSA const &sa, TLCPE const &lcpe, TQuery *query); // "projects/library/seqan/index/index_esa_find.h"(1672) //____________________________________________________________________________ // upperBoundLCPEIterator template inline typename Iterator::Type upperBoundLCPEIterator( TText const &text, TSA const &sa, TLCPE const &lcpe, TQuery const &query); // "projects/library/seqan/index/index_esa_find.h"(1621) //____________________________________________________________________________ // upperBoundSA template inline typename Position::Type upperBoundSA( TText const &text, TSA const &sa, TQuery const &query, TFlatTreeSpec const); // "projects/library/seqan/index/index_esa_find.h"(823) template inline typename Position::Type upperBoundSA( TText const &text, TSA const &sa, TQuery const &query); // "projects/library/seqan/index/index_esa_find.h"(837) template inline typename Position::Type upperBoundSA( TText const &text, TSA const &sa, TQuery *query, TFlatTreeSpec const); // "projects/library/seqan/index/index_esa_find.h"(920) template inline typename Position::Type upperBoundSA( TText const &text, TSA const &sa, TQuery *query); // "projects/library/seqan/index/index_esa_find.h"(934) //____________________________________________________________________________ // upperBoundSAIterator template inline typename Iterator::Type upperBoundSAIterator( TText const &text, TSA const &sa, TQuery const &query); // "projects/library/seqan/index/index_esa_find.h"(713) template inline typename Iterator::Type upperBoundSAIterator( TText const &text, TSA const &sa, TQuery *query); // "projects/library/seqan/index/index_esa_find.h"(759) //____________________________________________________________________________ // value template inline typename Value< Shape >::Type value(Shape &me); // "projects/library/seqan/index/shape_base.h"(205) template inline typename VertexDescriptor::Type & value(Iter< TIndex, VSTree > &it); // "projects/library/seqan/index/index_esa_stree.h"(557) template inline typename VertexDescriptor::Type const & value(Iter< TIndex, VSTree > const &it); // "projects/library/seqan/index/index_esa_stree.h"(563) template inline typename VertexDescriptor::Type value(Iter< TSTree, VSTree< BottomUp<_MaxRepeats > > > const &it); // "projects/library/seqan/index/index_esa_algs.h"(551) template inline typename Value< Iter >::Type & value(Iter const &it); // "projects/library/seqan/index/index_esa_algs.h"(780) template inline typename Value< Iter >::Type & value(Iter &it); // "projects/library/seqan/index/index_esa_algs.h"(786) //____________________________________________________________________________ // weight template inline typename Size< Shape > >::Type weight(Shape > const & me); // "projects/library/seqan/index/shape_gapped.h"(358) template inline typename Size< Shape >::Type weight(Shape const &me); // "projects/library/seqan/index/shape_base.h"(235) //____________________________________________________________________________ // write template void write(TFile & file, Index > & stree, DotDrawing); // "projects/library/seqan/index/index_esa_drawing.h"(31) } //namespace SEQAN_NAMESPACE_MAIN #endif ugene-1.9.8/src/plugins_3rdparty/bowtie/src/bowtie/SeqAn-1.1/seqan/index/index_manual_forwards.h0000644000175000017500000000447411651544326031251 0ustar ilyailya /*========================================================================== SeqAn - The Library for Sequence Analysis http://www.seqan.de ============================================================================ Copyright (C) 2007 This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. ============================================================================ $Id: index_manual_forwards.h,v 1.1 2008/08/25 16:20:05 langmead Exp $ ==========================================================================*/ #ifndef SEQAN_HEADER_INDEX_MANUAL_FORWARDS_H #define SEQAN_HEADER_INDEX_MANUAL_FORWARDS_H //SEQAN_NO_GENERATED_FORWARDS: no forwards are generated for this file ////////////////////////////////////////////////////////////////////////////// // CLASSES ////////////////////////////////////////////////////////////////////////////// namespace SEQAN_NAMESPACE_MAIN { struct _Fibre_Text; // Original text. Can be a String or a StringSet struct _Fibre_RawText; // Concatenation of the strings above struct _Fibre_SA; // suffix array (of raw text with virtual $-delimiters) with Pair entries struct _Fibre_RawSA; // suffix array with integer entries struct _Fibre_SAE; // suffix array reordered in a b-tree struct _Fibre_LCP; // lcp table of raw text struct _Fibre_LCPE; // lcp interval tree struct _Fibre_ChildTab; // childtab (Kurtz et al.) of raw text struct _Fibre_BWT; // burrows wheeler table of raw text typedef Tag<_Fibre_Text> const Fibre_Text; typedef Tag<_Fibre_RawText> const Fibre_RawText; typedef Tag<_Fibre_SA> const Fibre_SA; typedef Tag<_Fibre_RawSA> const Fibre_RawSA; typedef Tag<_Fibre_SAE> const Fibre_SAE; typedef Tag<_Fibre_LCP> const Fibre_LCP; typedef Tag<_Fibre_LCPE> const Fibre_LCPE; typedef Tag<_Fibre_ChildTab> const Fibre_ChildTab; typedef Tag<_Fibre_BWT> const Fibre_BWT; } #endif ugene-1.9.8/src/plugins_3rdparty/bowtie/src/bowtie/SeqAn-1.1/seqan/index/shape_base.h0000644000175000017500000004521311651544326026764 0ustar ilyailya /*========================================================================== SeqAn - The Library for Sequence Analysis http://www.seqan.de ============================================================================ Copyright (C) 2007 This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. ============================================================================ $Id: shape_base.h,v 1.1 2008/08/25 16:20:05 langmead Exp $ ==========================================================================*/ #ifndef SEQAN_HEADER_SHAPE_BASE_H #define SEQAN_HEADER_SHAPE_BASE_H namespace SEQAN_NAMESPACE_MAIN { template struct FixedShape {}; typedef FixedShape<0> SimpleShape; template struct FixedGappedShape {}; typedef FixedGappedShape GappedShape; /** .Class.Shape: ..cat:Index ..summary:Stores hash value and shape for an ungapped or gapped q-gram. ..signature:Shape ..param.TValue:The @Metafunction.Value@ type of the string the shape is applied to (e.g. $Dna$). ..param.TSpec:The specializing type. ...default:@Spec.SimpleShape@, for ungapped q-grams. ..remarks:The @Metafunction.ValueSize@ of Shape is the ValueSize of TValue which is the alphabet size. ..remarks:To get the span or the weight of a shape call @Function.length@ or @Function.weight@. .Memfunc.Shape#Shape: ..class:Class.Shape ..summary:Constructor ..signature:Shape () ..signature:Shape (shape) ..param.shape:Other Shape object. (copy constructor) */ template class Shape; ////////////////////////////////////////////////////////////////////////////// ///.Metafunction.Value.param.T.type:Class.Shape template struct Value > { typedef unsigned Type; }; ///.Metafunction.Size.param.T.type:Class.Shape template struct Size > { typedef unsigned Type; }; ///.Metafunction.LENGTH.param.T.type:Class.Shape template struct LENGTH< Shape > > { enum { VALUE = q }; }; ///.Metafunction.WEIGHT.param.T.type:Class.Shape template struct WEIGHT< Shape > > { enum { VALUE = q }; }; ///.Metafunction.ValueSize.param.T.type:Class.Shape template struct ValueSize< Shape > { enum { VALUE = Power< ValueSize::VALUE, WEIGHT< Shape >::VALUE >::VALUE }; }; ////////////////////////////////////////////////////////////////////////////// /** .Spec.SimpleShape: ..cat:Index ..summary:A variable length ungapped shape (also called q-gram or k-mer). ..general:Class.Shape ..signature:Shape ..param.TValue:The @Metafunction.Value@ type of the string the shape is applied to (e.g. $Dna$). ..remarks:A SimpleShape must be resized first to a valid length. To do so, call @Function.resize@. ..see:Spec.FixedShape */ ////////////////////////////////////////////////////////////////////////////// // ungapped shape with variable length ////////////////////////////////////////////////////////////////////////////// template class Shape { public: //____________________________________________________________________________ unsigned span; typename Value::Type hValue; typename Value::Type XValue; typename Value::Type leftFactor; typename Value::Type leftFactor2; TValue leftChar; //____________________________________________________________________________ /** .Memfunc.SimpleShape#Shape: ..class:Spec.SimpleShape ..summary:Constructor ..signature:Shape () ..signature:Shape (shape) ..signature:Shape (q) ..param.shape:Other Shape object. (copy constructor) ..param.q:Length of the ungapped q-gram. */ Shape() {} Shape(unsigned _span) { resize(*this, _span); } template Shape(Shape > const &other) { *this = other; } //____________________________________________________________________________ template inline Shape & operator=(Shape > const &other) { span = other.span; hValue = other.hValue; XValue = other.XValue; leftFactor = other.leftFactor; leftFactor2 = other.leftFactor2; leftChar = other.leftChar; return *this; } }; ////////////////////////////////////////////////////////////////////////////// // ungapped shape with fixed length q ////////////////////////////////////////////////////////////////////////////// /** .Spec.FixedShape: ..cat:Index ..summary:A fixed length ungapped shape (also called q-gram or k-mer). ..general:Class.Shape ..signature:Shape > ..param.TValue:The @Metafunction.Value@ type of the sequence the shape is applied to (e.g. $Dna$). ..param.q:The length of the shape. */ template class Shape > { public: //____________________________________________________________________________ enum { span = q }; enum { leftFactor = Power::VALUE, q - 1>::VALUE }; enum { leftFactor2 = (Power::VALUE, q>::VALUE - 1) / (ValueSize::VALUE - 1) }; // Sigma^(q-1) + Sigma^(q-2) + ... + Sigma + 1 typename Value::Type hValue; // current hash value typename Value::Type XValue; // Sum_{i=0..q-1} (x_i + 1) TValue leftChar; // left-most character //____________________________________________________________________________ }; ////////////////////////////////////////////////////////////////////////////// ///.Function.value.param.object.type:Class.Shape template inline typename Value< Shape >::Type value(Shape &me) { return me.hValue; } //____________________________________________________________________________ ///.Function.length.param.object.type:Class.Shape template inline typename Size< Shape >::Type length(Shape const &me) { SEQAN_CHECKPOINT return me.span; } //____________________________________________________________________________ /**.Function.weight: ..cat:Index ..summary:Number of relevant positions in a shape. ..signature:weight(shape) ..param.shape:Shape object for which the number of relevant positions is determined. ...type:Class.Shape ..returns:Number of relevant positions. ..remarks.text:For ungapped shapes the return value is the result of the @Function.length@ function. For gapped shapes this is the number of '1's. */ template inline typename Size< Shape >::Type weight(Shape const &me) { SEQAN_CHECKPOINT return length(me); } //____________________________________________________________________________ ///.Function.resize.param.object.type:Spec.SimpleShape template inline typename Size< Shape >::Type resize(Shape & me, TSize new_length) { SEQAN_CHECKPOINT me.leftFactor = _intPow((unsigned)ValueSize::VALUE, new_length - 1); me.leftFactor2 = (_intPow((unsigned)ValueSize::VALUE, new_length) - 1) / (ValueSize::VALUE - 1); return me.span = new_length; } //____________________________________________________________________________ /**.Function.hash: ..cat:Index ..summary:Computes a (lower) hash value for a shape applied to a sequence. ..signature:hash(shape, it) ..signature:hash(shape, it, charsLeft) ..param.shape:Shape to be used for hashing. ...type:Class.Shape ..param.it:Sequence iterator pointing to the first character of the shape. ..param.charsLeft:The distance of $it$ to the string end. If $charsLeft$ is smaller than the shape's span, the hash value corresponds to the smallest shape beginning with $charsLeft$ characters. ..returns:Hash value of the shape. */ template typename Value< Shape >::Type hash(Shape &me, TIter it) { SEQAN_CHECKPOINT typedef typename Value< Shape >::Type THValue; typedef typename Size< Shape >::Type TSize; me.hValue = ordValue(me.leftChar = *it); for(TSize i = 1; i < me.span; ++i) { ++it; me.hValue = me.hValue * ValueSize::VALUE + ordValue((TValue)*it); } return me.hValue; } //____________________________________________________________________________ // fixed ungapped shapes // loop unrolling ... template inline THValue _hashFixedShape(THValue hash, TIter &, TValue const, FixedShape<1> const) { return hash; } template inline THValue _hashFixedShape(THValue hash, TIter &it, TValue const, FixedShape const) { ++it; return _hashFixedShape( hash * ValueSize::VALUE + ordValue((TValue)*it), it, TValue(), FixedShape()); } // ... for fixed ungapped shapes template inline typename Value< Shape > >::Type hash(Shape > &me, TIter it) { SEQAN_CHECKPOINT typedef typename Value< Shape > >::Type THValue; typedef typename Size< Shape > >::Type TSize; me.hValue = ordValue(me.leftChar = *it); return me.hValue = _hashFixedShape(me.hValue, it, TValue(), FixedShape()); } template inline typename Value< Shape >::Type hash(Shape &me, TIter it, TSize charsLeft) { SEQAN_CHECKPOINT typedef typename Value< Shape >::Type THValue; TSize iEnd = me.span; if (iEnd > charsLeft) iEnd = charsLeft; TSize i = 0; if (iEnd > 0) { me.hValue = ordValue(me.leftChar = *it); for(i = 1; i < iEnd; ++i) { ++it; me.hValue = me.hValue * ValueSize::VALUE + ordValue((TValue)*it); } } else return me.hValue = 0; // fill shape with zeros for(; i < (TSize)me.span; ++i) me.hValue *= ValueSize::VALUE; return me.hValue; } //____________________________________________________________________________ // Tuple -> fixed ungapped shapes template inline THValue _hashTuple2FixedShape( THValue const, Tuple const &tuple, TValue const, FixedShape<1> const) { return ordValue(tuple[0]); } template inline THValue _hashTuple2FixedShape( THValue const, Tuple const &tuple, TValue const, FixedShape const) { return _hashTuple2FixedShape(THValue(), tuple, TValue(), FixedShape()) * ValueSize::VALUE + ordValue(tuple[q-1]); } // ... for fixed ungapped shapes template < typename TValue, typename TTValue, unsigned SIZE, unsigned q> typename Value< Shape > >::Type hash( Shape > &me, Tuple const &tuple) { SEQAN_CHECKPOINT if (ValueSize::VALUE == (1 << BitsPerValue::VALUE)) if (q == SIZE) return tuple.i; else return tuple >> (q - SIZE); else return me.hValue = _hashTuple2FixedShape(me.hValue, tuple, TValue(), FixedShape()); } template < typename TValue, typename TTValue, unsigned SIZE, typename TCompressed, unsigned q> typename Value< Shape > >::Type hash( Shape > &me, Tuple const &tuple) { SEQAN_CHECKPOINT return me.hValue = _hashTuple2FixedShape(me.hValue, tuple, TValue(), FixedShape()); } //____________________________________________________________________________ /**.Function.hashUpper: ..cat:Index ..summary:Computes an upper hash value for a shape applied to a sequence. ..signature:hashUpper(shape, it, charsLeft) ..param.shape:Shape to be used for hashing. ...type:Class.Shape ..param.it:Sequence iterator pointing to the first character of the shape. ..param.charsLeft:The distance of $it$ to the string end. If $charsLeft$ is smaller than the shape's span, the hash value corresponds to the biggest shape beginning with $charsLeft$ characters + 1. ..returns:Upper hash value of the shape. */ template inline typename Value< Shape >::Type hashUpper(Shape &me, TIter it, TSize charsLeft) { SEQAN_CHECKPOINT typedef typename Value< Shape >::Type THValue; TSize iEnd = me.span; if (iEnd > charsLeft) iEnd = charsLeft; TSize i = 0; if (iEnd > 0) { me.hValue = ordValue(me.leftChar = *it); for(i = 1; i < iEnd; ++i) { ++it; me.hValue = me.hValue * ValueSize::VALUE + ordValue((TValue)*it); } ++me.hValue; } else me.hValue = 1; // fill shape with zeros for(; i < (TSize)me.span; ++i) me.hValue *= ValueSize::VALUE; return me.hValue; } //____________________________________________________________________________ /** .Function.hashNext: ..cat:Index ..summary:Computes the hash value for the adjacent shape. ..signature:hashNext(shape, it) ..param.shape:Shape to be used for hashing. ...type:Class.Shape ..param.it:Sequence iterator pointing to the first character of the adjacent shape. ..returns:Hash value of the q-gram. ..remarks:@Function.hash@ has to be called before. */ template inline typename Value< Shape >::Type hashNext(Shape &me, TIter &it) { SEQAN_CHECKPOINT // remove first, shift left, and add next character typedef typename Value< Shape >::Type THValue; me.hValue = (me.hValue - ordValue(me.leftChar) * (THValue)me.leftFactor) * ValueSize::VALUE + ordValue((TValue)*(it + (THValue)me.span - 1)); me.leftChar = *it; return me.hValue; } //____________________________________________________________________________ /**.Function.hash2: ..cat:Index ..summary:Computes a unique hash value of a shape, even if it is shorter than its span. ..signature:hash2(shape, it, charsLeft) ..param.shape:Shape to be used for hashing. ...type:Class.Shape ..param.it:Sequence iterator pointing to the first character of the shape. ..param.charsLeft:The distance of $it$ to the string end. ..returns:Hash value of the shape. */ template inline typename Value< Shape >::Type hash2(Shape &me, TIter it, TSize charsLeft) { SEQAN_CHECKPOINT typedef typename Value< Shape >::Type THValue; TSize iEnd = me.span; if (iEnd > charsLeft) iEnd = charsLeft; TSize i = 0; if (iEnd > 0) { me.hValue = me.XValue = ordValue(me.leftChar = *it); for(i = 1; i < iEnd; ++i) { ++it; // update sum of x_i me.XValue += ordValue((TValue)*it); // shift hash me.hValue = me.hValue * ValueSize::VALUE + me.XValue; } } else return me.hValue = me.XValue = 0; // fill shape with zeros for(; i < (TSize)me.span; ++i) me.hValue = me.hValue * ValueSize::VALUE + me.XValue; return me.hValue += iEnd; } template inline typename Value< Shape >::Type hash2Upper(Shape &me, TIter it, TSize charsLeft) { SEQAN_CHECKPOINT typedef typename Value< Shape >::Type THValue; TSize iEnd = me.span; if (iEnd > charsLeft) iEnd = charsLeft; THValue hValue, XValue; TSize i = 0; if (iEnd > 0) { hValue = XValue = ordValue((TValue)*it); for(i = 1; i < iEnd; ++i) { ++it; // update sum of x_i XValue += ordValue((TValue)*it); // shift hash hValue = hValue * ValueSize::VALUE + XValue; } } else hValue = XValue = 0; if (charsLeft <= me.span) { ++XValue; ++hValue; } // fill shape with zeros for(; i < (TSize)me.span; ++i) hValue = hValue * ValueSize::VALUE + XValue; return hValue += iEnd; } //____________________________________________________________________________ /** .Function.hash2Next: ..cat:Index ..summary:Computes a unique hash value for the adjacent shape, even if it is shorter than q. ..signature:hash2Next(shape, it) ..param.shape:Shape to be used for hashing the q-gram. ...type:Class.Shape ..param.it:Sequence iterator pointing to the first character of the adjacent shape. ..returns:Hash value of the shape. ..remarks:@Function.hash@ has to be called before with $shape$ on the left adjacent q-gram. */ template inline typename Value< Shape >::Type hash2Next(Shape &me, TIter &it, TSize charsLeft) { SEQAN_CHECKPOINT // remove first, shift left, and add next character typedef typename Value< Shape >::Type THValue; if (charsLeft >= me.span) { // update sum of x_i me.XValue = me.XValue + ordValue((TValue)*(it + me.span - 1)) - ordValue(me.leftChar); // shift hash me.hValue = (me.hValue - ordValue(me.leftChar) * (THValue)me.leftFactor2) * ValueSize::VALUE + me.XValue - me.span * (ValueSize::VALUE - 1); } else { // update sum of x_i me.XValue -= ordValue(me.leftChar); // shift hash me.hValue = (me.hValue - ordValue(me.leftChar) * (THValue)me.leftFactor2) * ValueSize::VALUE + me.XValue - charsLeft * (ValueSize::VALUE - 1) - ValueSize::VALUE; } me.leftChar = *it; return me.hValue; } template inline void unhash(TString &result, THash hash, unsigned q) { SEQAN_CHECKPOINT typedef typename Value::Type TValue; resize(result, q); for (unsigned i = q; i > 0; ) { result[--i] = (TValue)(hash % ValueSize::VALUE); hash /= ValueSize::VALUE; } } } // namespace seqan #endif ugene-1.9.8/src/plugins_3rdparty/bowtie/src/bowtie/SeqAn-1.1/seqan/platform.h0000644000175000017500000000142111651544326025400 0ustar ilyailya#ifdef _MSC_VER #define PLATFORM "windows" #ifndef PLATFORM_WINDOWS #define PLATFORM_WINDOWS #endif #pragma warning( disable : 4675 ) #pragma warning( disable : 4503 ) #define finline __forceinline //define SEQAN_SWITCH_USE_FORWARDS to use generated forwards #define SEQAN_SWITCH_USE_FORWARDS #else #define PLATFORM "gcc" #ifndef PLATFORM_GCC #define PLATFORM_GCC #endif // should be set before including anything #ifndef _FILE_OFFSET_BITS #define _FILE_OFFSET_BITS 64 #endif #ifndef _LARGEFILE_SOURCE #define _LARGEFILE_SOURCE #endif //#include #include #define finline __inline__ // default 64bit type typedef int64_t __int64; //define SEQAN_SWITCH_USE_FORWARDS to use generated forwards #define SEQAN_SWITCH_USE_FORWARDS #endif // _MSC_VERugene-1.9.8/src/plugins_3rdparty/bowtie/src/bowtie/SeqAn-1.1/seqan/file/0000755000175000017500000000000011651544310024315 5ustar ilyailyaugene-1.9.8/src/plugins_3rdparty/bowtie/src/bowtie/SeqAn-1.1/seqan/file/file_format_fasta_align.h0000644000175000017500000002167011651544326031322 0ustar ilyailya /*========================================================================== SeqAn - The Library for Sequence Analysis http://www.seqan.de ============================================================================ Copyright (C) 2007 This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. ============================================================================ $Id: file_format_fasta_align.h,v 1.1 2008/08/25 16:20:03 langmead Exp $ ==========================================================================*/ #ifndef SEQAN_HEADER_FILE_FASTA_ALIGN_H #define SEQAN_HEADER_FILE_FASTA_ALIGN_H namespace SEQAN_NAMESPACE_MAIN { ////////////////////////////////////////////////////////////////////////////// // File Formats - Fasta alignment format ////////////////////////////////////////////////////////////////////////////// //forward declarations template struct Row; template struct Rows; ////////////////////////////////////////////////////////////////////////////// /** .Tag.File Format.tag.Fasta alignment: FASTA alignment file format for sequences. */ struct TagFastaAlign_; typedef Tag const FastaAlign; ///////////////////////////////////////////////////////////////////////// template void _fasta_align_scan_line(TFile & file, TSize & count) { SEQAN_CHECKPOINT SEQAN_ASSERT(!_streamEOF(file)) while (true) { typename Value::Type c = _streamGet(file); if (_streamEOF(file)) return; if (c == '\n') return; if ((c != '\r') && (c!='-')) { ++count; } } } ////////////////////////////////////////////////////////////////////////////// // read ////////////////////////////////////////////////////////////////////////////// template void read(TFile & file, Align & align, FastaAlign) { SEQAN_CHECKPOINT SEQAN_ASSERT(!_streamEOF(file)) typedef typename Value::Type TSourceValue; typedef typename Size::Type TSize; TSize limit = supremumValue(); //Determine begin position, end position and length of each sequence String beg_end_length; typename Position::Type begin_pos; typename Position::Type end_pos; typename Value::Type c; TSize count; while (!_streamEOF(file)) { begin_pos = _streamTellG(file); count = 0; SEQAN_ASSERT(!_streamEOF(file)) c = _streamGet(file); // Skip id if (c == '>') { _fasta_align_scan_line(file, count); begin_pos = _streamTellG(file); count = 0; } else { //If no id first letter belongs to sequence count = 1; } // Count letters while (true) { _fasta_align_scan_line(file, count); typename Value::Type c = _streamGet(file); if (c == '>') { _streamSeek2G(file, -1); end_pos = _streamTellG(file); break; } if (_streamEOF(file)) { end_pos = _streamTellG(file); break; } if ((c != '\n') && (c != '\r') && (c!='-')) { ++count; } } if (count > limit) { count = limit; } append(beg_end_length, begin_pos); append(beg_end_length, end_pos); append(beg_end_length, count); } // Resize alignment data structure TSize numRows=length(beg_end_length) / 3; resize(rows(align), numRows); //rows typedef Align TAlign; typedef typename Row::Type TRow; for(TSize i=0;i::Type pos; for (pos = 0; pos < count; ) { c = _streamGet(file); if ((c != '\n') && (c != '\r') && (c != '-')) { source(row(align,i))[pos] = c; ++pos; } if (c=='-') { insertGap(row(align,i), toViewPosition(row(align,i), pos)); } } } _streamSeekG(file, 0); } ////////////////////////////////////////////////////////////////////////////// // readIDs ////////////////////////////////////////////////////////////////////////////// template void readIDs(TFile& file, TStringContainer& ids, FastaAlign) { SEQAN_CHECKPOINT SEQAN_ASSERT(!_streamEOF(file)) typedef typename Value::Type TString; typename Position::Type start_pos; typename Value::Type c; TString id; while(true) { c = _streamGet(file); while ((!_streamEOF(file)) && (c != '>')) c = _streamGet(file); if (!_streamEOF(file)) { start_pos = _streamTellG(file); typename Size::Type count = 0; _fasta_align_scan_line(file, count); if (! count) clear(id); else { resize(id, count); if (length(id) < count) { count = length(id); } _streamSeekG(file, start_pos); for (typename Position::Type pos = 0; pos void readMeta(TFile & file, TMeta & meta, FastaAlign) { SEQAN_CHECKPOINT clear(meta); } ////////////////////////////////////////////////////////////////////////////// // goNext ////////////////////////////////////////////////////////////////////////////// template void goNext(TFile & file, FastaAlign) { SEQAN_CHECKPOINT SEQAN_ASSERT(!_streamEOF(file)) return; } ////////////////////////////////////////////////////////////////////////////// // write ////////////////////////////////////////////////////////////////////////////// template void _write_impl(TFile& file, Align& align, TStringContainer& ids, FastaAlign) { SEQAN_CHECKPOINT typedef Align const TAlign; typedef typename Row::Type TRow; typedef typename Position::Type>::Type TRowsPosition; typedef typename Position::Type TPosition; TRowsPosition row_count = length(rows(align)); for(TRowsPosition i=0;i::Type const, Standard>::Type TIter; TIter begin_ = iter(row_, beginPosition(cols(align))); TIter end_ = iter(row_, endPosition(cols(align))); _streamPut(file, '>'); _streamWrite(file, getValue(ids,i)); _streamPut(file, '\n'); int chars=0; while(begin_ != end_) { if (chars == 60) { _streamPut(file, '\n'); chars = 0; } if (isGap(begin_)) _streamPut(file, gapValue()); else _streamPut(file, getValue(source(begin_))); chars++; ++begin_; } _streamPut(file, '\n'); } } //____________________________________________________________________________ template void write(TFile & file, Align& align, FastaAlign) { SEQAN_CHECKPOINT _write_impl(file, align, String >(), FastaAlign()); } //____________________________________________________________________________ template void write(TFile & file, Align & align, TStringContainer& ids, FastaAlign) { SEQAN_CHECKPOINT _write_impl(file, align, ids, FastaAlign()); } //VisualC++ const array bug workaround template void write(TFile & file, Align* align, TStringContainer & ids, FastaAlign) { SEQAN_CHECKPOINT _write_impl(file, align, ids, FastaAlign()); } //____________________________________________________________________________ template void write(TFile & file, Align & align, TStringContainer& ids, TMeta &, FastaAlign) { SEQAN_CHECKPOINT _write_impl(file, align, ids, FastaAlign()); } ////////////////////////////////////////////////////////////////////////////// } //namespace SEQAN_NAMESPACE_MAIN ////////////////////////////////////////////////////////////////////////////// #endif //#ifndef SEQAN_HEADER_... ugene-1.9.8/src/plugins_3rdparty/bowtie/src/bowtie/SeqAn-1.1/seqan/file/meta.h0000644000175000017500000000246611651544326025433 0ustar ilyailya /*========================================================================== SeqAn - The Library for Sequence Analysis http://www.seqan.de ============================================================================ Copyright (C) 2007 This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. ============================================================================ $Id: meta.h,v 1.1 2008/08/25 16:20:03 langmead Exp $ ==========================================================================*/ #ifndef SEQAN_HEADER_FILE_META_H #define SEQAN_HEADER_FILE_META_H namespace SEQAN_NAMESPACE_MAIN { ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// } //namespace SEQAN_NAMESPACE_MAIN #endif //#ifndef SEQAN_HEADER_... ugene-1.9.8/src/plugins_3rdparty/bowtie/src/bowtie/SeqAn-1.1/seqan/file/chunk_collector.h0000644000175000017500000004043611651544326027662 0ustar ilyailya /*========================================================================== SeqAn - The Library for Sequence Analysis http://www.seqan.de ============================================================================ Copyright (C) 2007 This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. ============================================================================ $Id: chunk_collector.h,v 1.1 2008/08/25 16:20:04 langmead Exp $ ==========================================================================*/ #ifndef SEQAN_HEADER_CHUNK_COLLECTOR_H #define SEQAN_HEADER_CHUNK_COLLECTOR_H namespace SEQAN_NAMESPACE_MAIN { ////////////////////////////////////////////////////////////////////////////// /** .Internal._ChunkCollector: ..cat:Classes ..summary:Reads piecewise from stream, collects pieces (chunks) in a vector. ..signature:_ChunkCollector ..param.Host:Type of host object that is used as allocator. */ ////////////////////////////////////////////////////////////////////////////// template struct ChunkLength { enum { VALUE = 1024 }; }; ////////////////////////////////////////////////////////////////////////////// // _StreamChunkCollector class: collects content of a stream in chunks ////////////////////////////////////////////////////////////////////////////// template class _ChunkCollector { protected: THost * data_host; typename Size::Type data_length; typedef ::std::vector::Type *, ToStdAllocator::Type *> > Chunk_Holder; Chunk_Holder data_chunks; public: static int const CHUNK_LENGTH = ChunkLength<_ChunkCollector>::VALUE; public: _ChunkCollector(THost & _host): data_host(& _host), data_length(0), data_chunks(typename Chunk_Holder::allocator_type(_host)) { } ~_ChunkCollector() { clear(*this); } public: friend inline void clear(_ChunkCollector & me) { typename Chunk_Holder::iterator it = me.data_chunks.begin(); typename Chunk_Holder::iterator it_end = me.data_chunks.end(); for (; it != it_end; ++it) { deallocate(me.data_host, *it, CHUNK_LENGTH); } me.data_chunks.clear(); me.data_length = 0; } friend inline typename Size::Type length(_ChunkCollector const & me) { return me.data_length; } friend inline void _setLength(_ChunkCollector & me, typename Size::Type new_length) { me.data_length = new_length; } friend inline int chunkCount(_ChunkCollector const & me) { return me.data_chunks.size(); } friend inline typename Value::Type * getChunk(_ChunkCollector const & me, int chunk_number) { return me.data_chunks[chunk_number]; } friend inline typename Value::Type * createChunk(_ChunkCollector & me) { typename Value::Type * new_chunk; allocate(me.data_host, new_chunk, CHUNK_LENGTH); me.data_chunks.push_back(new_chunk); return new_chunk; } }; ////////////////////////////////////////////////////////////////////////////// template struct Host<_ChunkCollector > { typedef THost Type; }; template struct Host<_ChunkCollector const > { typedef THost Type; }; ////////////////////////////////////////////////////////////////////////////// template struct Value<_ChunkCollector > { typedef typename Value::Type Type; }; template struct Value<_ChunkCollector const > { typedef typename Value::Type Type; }; ////////////////////////////////////////////////////////////////////////////// template struct GetValue<_ChunkCollector > { typedef typename GetValue::Type Type; }; template struct GetValue<_ChunkCollector const > { typedef typename GetValue::Type Type; }; ////////////////////////////////////////////////////////////////////////////// template struct Size<_ChunkCollector > { typedef typename Size::Type Type; }; template struct Size<_ChunkCollector const > { typedef typename Size::Type Type; }; ////////////////////////////////////////////////////////////////////////////// struct _Assign_Stream_2_ChunkCollector { template static inline void assign_(_ChunkCollector & target, TSource & source) { clear(target); while (!_streamEOF(source)) { typename Value::Type * chunk = createChunk(target); typename Size::Type count = _streamRead(chunk, source, ChunkLength< _ChunkCollector >::VALUE); _setLength(target, length(target) + count); } } template static inline void assign_(_ChunkCollector & target, TSource & source, typename Size< _ChunkCollector >::Type limit) { clear(target); while (!_streamEOF(source)) { typename Value::Type * chunk = createChunk(target); typename Size::Type count = _streamRead(chunk, source, ChunkLength< _ChunkCollector >::VALUE); _setLength(target, length(target) + count); if (length(target) >= limit) { _setLength(target, limit); break; } } } }; ////////////////////////////////////////////////////////////////////////////// template inline void assign(_ChunkCollector & target, TSource & source) { _Assign_Stream_2_ChunkCollector::assign_(target, source); } template inline void assign(_ChunkCollector & target, TSource const & source) { _Assign_Stream_2_ChunkCollector::assign_(target, source); } template inline void assign(_ChunkCollector & target, TSource & source, TSize limit) { _Assign_Stream_2_ChunkCollector::assign_(target, source, limit); } template inline void assign(_ChunkCollector & target, TSource const & source, TSize limit) { _Assign_Stream_2_ChunkCollector::assign_(target, source, limit); } ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// template struct _Assign_ChunkCollector_2_String { template static void assign_( TTarget & target, TSource & source) { typename Size::Type part_length = _clearSpace(target, length(source), TExpand()); int i_end = chunkCount(source); typename Value::Type * pos = begin(target); for (int i = 0; i < i_end; ++i) { bool is_last_chunk = ( part_length <= ChunkLength::VALUE); typename Size::Type chunk_length = (is_last_chunk) ? part_length : ChunkLength::VALUE; typename Value::Type * chunk = getChunk(source, i); arrayConstructCopy(chunk, chunk + chunk_length, pos); if (is_last_chunk) break; pos += chunk_length; } } template static void assign_( TTarget & target, TSource & source, typename Size::Type limit) { typename Size::Type part_length = _clearSpace(target, length(source), limit, TExpand()); int i_end = chunkCount(source); typename Value::Type * pos = begin(target); for (int i = 0; i < i_end; ++i) { bool is_last_chunk = ( part_length <= ChunkLength::VALUE); typename Size::Type chunk_length = (is_last_chunk) ? part_length : ChunkLength::VALUE; typename Value::Type * chunk = getChunk(source, i); arrayConstructCopy(chunk, chunk + chunk_length, pos); if (is_last_chunk) break; pos += chunk_length; } } }; ////////////////////////////////////////////////////////////////////////////// template inline void assign(String & target, _ChunkCollector const & source, Tag const tag) { _Assign_ChunkCollector_2_String const>::assign_(target, source); } template inline void assign(String & target, _ChunkCollector const & source, typename Size< String >::Type limit, Tag const tag) { _Assign_ChunkCollector_2_String const>::assign_(target, source, limit); } ////////////////////////////////////////////////////////////////////////////// template struct _Append_ChunkCollector_2_String { template static void append_( TTarget & target, TSource & source) { typedef typename Size::Type TSize; TSize target_length_old = length(target); TSize part_length = _clearSpace(target, length(source), target_length_old, target_length_old, TExpand()); int i_end = chunkCount(source); typename Value::Type * pos = begin(target) + target_length_old; //begin(target) was possibly changed by _clearSpace for (int i = 0; i < i_end; ++i) { bool is_last_chunk = ( part_length <= ChunkLength::VALUE); typename Size::Type chunk_length = (is_last_chunk) ? part_length : (TSize) ChunkLength::VALUE; typename Value::Type * chunk = getChunk(source, i); arrayConstructCopy(chunk, chunk + chunk_length, pos); if (is_last_chunk) break; pos += chunk_length; } } template static void append_( TTarget & target, TSource & source, typename Size::Type limit) { typedef typename Size::Type TSize; TSize target_length_old = length(target); TSize part_length = _clearSpace(target, length(source), target_length_old, target_length_old, limit, TExpand()); int i_end = chunkCount(source); typename Value::Type * pos = begin(target) + target_length_old; //begin(target) was possibly changed by _clearSpace for (int i = 0; i < i_end; ++i) { bool is_last_chunk = ( part_length <= ChunkLength::VALUE); typename Size::Type chunk_length = (is_last_chunk) ? part_length : (TSize) ChunkLength::VALUE; typename Value::Type * chunk = getChunk(source, i); arrayConstructCopy(chunk, chunk + chunk_length, pos); if (is_last_chunk) break; pos += chunk_length; } } }; ////////////////////////////////////////////////////////////////////////////// template inline void append(String & target, _ChunkCollector const & source, Tag const ) { _Append_ChunkCollector_2_String const>::append_(target, source); } template inline void append(String & target, _ChunkCollector const & source, typename Size< String >::Type limit, Tag const ) { _Append_ChunkCollector_2_String const>::append_(target, source, limit); } ////////////////////////////////////////////////////////////////////////////// template struct _Replace_ChunkCollector_2_String { template static void replace_( TTarget & target, typename Size::Type pos_begin, typename Size::Type pos_end, TSource & source) { typename Size::Type part_length = _clearSpace(target, length(source), pos_begin, pos_end, TExpand()); int i_end = chunkCount(source); typename Value::Type * pos = begin(target) + pos_begin; for (int i = 0; i < i_end; ++i) { bool is_last_chunk = ( part_length <= ChunkLength::VALUE); typename Size::Type chunk_length = (is_last_chunk) ? part_length : ChunkLength::VALUE; typename Value::Type * chunk = getChunk(source, i); arrayConstructCopy(chunk, chunk + chunk_length, pos); if (is_last_chunk) break; pos += chunk_length; } } template static void replace_( TTarget & target, typename Size::Type pos_begin, typename Size::Type pos_end, TSource & source, typename Size::Type limit) { typename Size::Type part_length = _clearSpace(target, length(source), pos_begin, pos_end, limit, TExpand()); int i_end = chunkCount(source); typename Value::Type * pos = begin(target) + pos_begin; for (int i = 0; i < i_end; ++i) { bool is_last_chunk = ( part_length <= ChunkLength::VALUE); typename Size::Type chunk_length = (is_last_chunk) ? part_length : ChunkLength::VALUE; typename Value::Type * chunk = getChunk(source, i); arrayConstructCopy(chunk, chunk + chunk_length, pos); if (is_last_chunk) break; pos += chunk_length; } } }; ////////////////////////////////////////////////////////////////////////////// template inline void replace(String & target, typename Size< String >::Type pos_begin, typename Size< String >::Type pos_end, _ChunkCollector const & source, Tag const tag) { _Replace_ChunkCollector_2_String const>::replace_(target, pos_begin, pos_end, source); } template inline void replace(String & target, typename Size< String >::Type pos_begin, typename Size< String >::Type pos_end, _ChunkCollector const & source, typename Size< String >::Type limit, Tag const tag) { _Replace_ChunkCollector_2_String const>::replace_(target, pos_begin, pos_end, source, limit); } ////////////////////////////////////////////////////////////////////////////// template inline void replace(TTargetValue * target, size_t pos_begin, size_t pos_end, _ChunkCollector const & source, Tag const tag) { _Replace_ChunkCollector_2_String const>::replace_(target, pos_begin, pos_end, source); } template inline void replace(TTargetValue * target, size_t pos_begin, size_t pos_end, _ChunkCollector const & source, size_t limit, Tag const tag) { _Replace_ChunkCollector_2_String const>::replace_(target, pos_begin, pos_end, source, limit); } //____________________________________________________________________________ /* template inline void replace(TTargetValue * target, size_t pos_begin, size_t pos_end, _ChunkCollector const & source, Tag const tag) { _Replace_ChunkCollector_2_String const>::replace_(target, pos_begin, pos_end, source); } template inline void replace(String & target, typename Size< String >::Type pos_begin, typename Size< String >::Type pos_end, _ChunkCollector const & source, typename Size< String >::Type limit, Tag const tag) { _Replace_ChunkCollector_2_String const>::replace_(target, pos_begin, pos_end, source, limit); } */ ////////////////////////////////////////////////////////////////////////////// } //namespace SEQAN_NAMESPACE_MAIN #endif //#ifndef SEQAN_HEADER_... ugene-1.9.8/src/plugins_3rdparty/bowtie/src/bowtie/SeqAn-1.1/seqan/file/file_generated_forwards.h0000644000175000017500000026426411651544326031357 0ustar ilyailya /*========================================================================== SeqAn - The Library for Sequence Analysis http://www.seqan.de ============================================================================ Copyright (C) 2007 This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. ==========================================================================*/ #ifndef SEQAN_HEADER_FILE_GENERATED_FORWARDS_H #define SEQAN_HEADER_FILE_GENERATED_FORWARDS_H ////////////////////////////////////////////////////////////////////////////// // NOTE: This file is automatically generated by build_forwards.py // Do not edit this file manually! ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// // CLASSES ////////////////////////////////////////////////////////////////////////////// namespace SEQAN_NAMESPACE_MAIN { //____________________________________________________________________________ // Async template struct Async; // "projects/library/seqan/file/file_base.h"(58) //____________________________________________________________________________ // Chained template <__int64 _FileSize , typename TFile > struct Chained; // "projects/library/seqan/file/file_base.h"(90) //____________________________________________________________________________ // ChunkLength template struct ChunkLength; // "projects/library/seqan/file/chunk_collector.h"(41) //____________________________________________________________________________ // DefaultOpenMode template struct DefaultOpenMode; // "projects/library/seqan/file/file_base.h"(122) //____________________________________________________________________________ // DefaultOpenTempMode template struct DefaultOpenTempMode; // "projects/library/seqan/file/file_base.h"(127) //____________________________________________________________________________ // Dynamic template struct Dynamic; // "projects/library/seqan/file/file_page.h"(185) //____________________________________________________________________________ // External template struct External; // "projects/library/seqan/file/string_external.h"(158) //____________________________________________________________________________ // ExternalConfig template struct ExternalConfig; // "projects/library/seqan/file/string_external.h"(83) //____________________________________________________________________________ // ExternalConfigLarge template struct ExternalConfigLarge; // "projects/library/seqan/file/string_external.h"(118) //____________________________________________________________________________ // ExternalConfigSize template struct ExternalConfigSize; // "projects/library/seqan/file/string_external.h"(150) //____________________________________________________________________________ // File template class File; // "projects/library/seqan/file/file_base.h"(71) //____________________________________________________________________________ // FileFormat template struct FileFormat; // "projects/library/seqan/file/file_format.h"(60) //____________________________________________________________________________ // FileReader template struct FileReader; // "projects/library/seqan/file/file_filereaderiterator.h"(30) //____________________________________________________________________________ // FileReaderIterator struct FileReaderIterator; // "projects/library/seqan/file/file_filereader.h"(402) //____________________________________________________________________________ // Fixed template struct Fixed; // "projects/library/seqan/file/file_page.h"(228) //____________________________________________________________________________ // PageBucket template struct PageBucket; // "projects/library/seqan/file/file_page.h"(159) //____________________________________________________________________________ // PageBucketExtended template struct PageBucketExtended; // "projects/library/seqan/file/file_page.h"(165) //____________________________________________________________________________ // PageChain template struct PageChain; // "projects/library/seqan/file/file_page.h"(189) template struct PageChain; // "projects/library/seqan/file/file_page.h"(509) //____________________________________________________________________________ // PageContainer template struct PageContainer; // "projects/library/seqan/file/file_page.h"(723) //____________________________________________________________________________ // PageFrame template struct PageFrame; // "projects/library/seqan/file/file_page.h"(178) //____________________________________________________________________________ // Row template struct Row; // "projects/library/seqan/file/file_format_fasta_align.h"(33) //____________________________________________________________________________ // Rows template struct Rows; // "projects/library/seqan/file/file_format_fasta_align.h"(36) //____________________________________________________________________________ // SimpleBuffer template struct SimpleBuffer; // "projects/library/seqan/file/file_page.h"(35) //____________________________________________________________________________ // Striped template struct Striped; // "projects/library/seqan/file/file_base.h"(107) //____________________________________________________________________________ // Sync template struct Sync; // "projects/library/seqan/file/file_base.h"(47) //____________________________________________________________________________ // TagCGViz_ struct TagCGViz_; // "projects/library/seqan/file/file_format_cgviz.h"(36) //____________________________________________________________________________ // TagEmbl_ struct TagEmbl_; // "projects/library/seqan/file/file_format_embl.h"(34) //____________________________________________________________________________ // TagFastaAlign_ struct TagFastaAlign_; // "projects/library/seqan/file/file_format_fasta_align.h"(44) //____________________________________________________________________________ // TagFasta_ struct TagFasta_; // "projects/library/seqan/file/file_format_fasta.h"(35) //____________________________________________________________________________ // TagGenbank_ struct TagGenbank_; // "projects/library/seqan/file/file_format_genbank.h"(35) //____________________________________________________________________________ // TagRaw_ struct TagRaw_; // "projects/library/seqan/file/file_format_raw.h"(37) //____________________________________________________________________________ // VectorConstIterator template struct VectorConstIterator; // "projects/library/seqan/file/string_external.h"(275) //____________________________________________________________________________ // VectorFwdConstIterator template struct VectorFwdConstIterator; // "projects/library/seqan/file/string_external.h"(641) //____________________________________________________________________________ // VectorFwdIterator template struct VectorFwdIterator; // "projects/library/seqan/file/string_external.h"(392) //____________________________________________________________________________ // VectorIterator template struct VectorIterator; // "projects/library/seqan/file/string_external.h"(165) //____________________________________________________________________________ // _Append_ChunkCollector_2_String template struct _Append_ChunkCollector_2_String; // "projects/library/seqan/file/chunk_collector.h"(334) //____________________________________________________________________________ // _Assign_ChunkCollector_2_String template struct _Assign_ChunkCollector_2_String; // "projects/library/seqan/file/chunk_collector.h"(264) //____________________________________________________________________________ // _Assign_Stream_2_ChunkCollector struct _Assign_Stream_2_ChunkCollector; // "projects/library/seqan/file/chunk_collector.h"(186) //____________________________________________________________________________ // _ChunkCollector template class _ChunkCollector; // "projects/library/seqan/file/chunk_collector.h"(51) //____________________________________________________________________________ // _FileReader_Types template struct _FileReader_Types; // "projects/library/seqan/file/file_filereader.h"(410) //____________________________________________________________________________ // _IsTellSeekStream template struct _IsTellSeekStream; // "projects/library/seqan/file/stream.h"(179) template struct _IsTellSeekStream; // "projects/library/seqan/file/cstream.h"(63) //____________________________________________________________________________ // _Read_Raw template struct _Read_Raw; // "projects/library/seqan/file/file_format_raw.h"(47) //____________________________________________________________________________ // _Replace_ChunkCollector_2_String template struct _Replace_ChunkCollector_2_String; // "projects/library/seqan/file/chunk_collector.h"(407) //____________________________________________________________________________ // aDummyRequest struct aDummyRequest; // "projects/library/seqan/file/file_base.h"(143) //____________________________________________________________________________ // aRequest template struct aRequest; // "projects/library/seqan/file/file_base.h"(156) } //namespace SEQAN_NAMESPACE_MAIN ////////////////////////////////////////////////////////////////////////////// // TYPEDEFS ////////////////////////////////////////////////////////////////////////////// namespace SEQAN_NAMESPACE_MAIN { //____________________________________________________________________________ // CGViz typedef Tag const CGViz; // "projects/library/seqan/file/file_format_cgviz.h"(37) //____________________________________________________________________________ // Embl typedef Tag const Embl; // "projects/library/seqan/file/file_format_embl.h"(35) //____________________________________________________________________________ // Fasta typedef Tag const Fasta; // "projects/library/seqan/file/file_format_fasta.h"(36) //____________________________________________________________________________ // FastaAlign typedef Tag const FastaAlign; // "projects/library/seqan/file/file_format_fasta_align.h"(45) //____________________________________________________________________________ // Genbank typedef Tag const Genbank; // "projects/library/seqan/file/file_format_genbank.h"(36) //____________________________________________________________________________ // Raw typedef Tag const Raw; // "projects/library/seqan/file/file_format_raw.h"(38) } //namespace SEQAN_NAMESPACE_MAIN ////////////////////////////////////////////////////////////////////////////// // FUNCTIONS ////////////////////////////////////////////////////////////////////////////// namespace SEQAN_NAMESPACE_MAIN { //____________________________________________________________________________ // _FileReaderString_construct template inline void _FileReaderString_construct(String > & me); // "projects/library/seqan/file/file_filereader.h"(254) //____________________________________________________________________________ // _FileReaderString_findblock template inline unsigned int _FileReaderString_findblock(String > & me, TPosition pos); // "projects/library/seqan/file/file_filereader.h"(233) //____________________________________________________________________________ // _FileReaderString_isValidBlock template inline bool _FileReaderString_isValidBlock(String > & me, TUint block_number); // "projects/library/seqan/file/file_filereader.h"(271) //____________________________________________________________________________ // _FileReaderString_loadComplete template inline void _FileReaderString_loadComplete(String > & me); // "projects/library/seqan/file/file_filereader.h"(288) //____________________________________________________________________________ // _FileReaderString_loadblock template inline void _FileReaderString_loadblock(String > & me, TPosition blocknum); // "projects/library/seqan/file/file_filereader.h"(167) //____________________________________________________________________________ // _cancelFArray template inline bool _cancelFArray(TFileArray &me, TRequest &request); // "projects/library/seqan/file/file_array.h"(272) //____________________________________________________________________________ // _closeFArray template inline bool _closeFArray(TFileArray &me); // "projects/library/seqan/file/file_array.h"(242) //____________________________________________________________________________ // _dataFile template inline TFile & _dataFile(String > & me); // "projects/library/seqan/file/file_filereader.h"(156) //____________________________________________________________________________ // _fasta_align_scan_line template void _fasta_align_scan_line(TFile & file, TSize & count); // "projects/library/seqan/file/file_format_fasta_align.h"(51) //____________________________________________________________________________ // _fasta_scan_line template inline typename Value::Type _fasta_scan_line(TFile & file, TSize & count_valid, TSize & count_all); // "projects/library/seqan/file/file_format_fasta.h"(145) //____________________________________________________________________________ // _flushFArray template inline bool _flushFArray(TFileArray &me); // "projects/library/seqan/file/file_array.h"(264) //____________________________________________________________________________ // _getCStyleOpenMode inline const char * _getCStyleOpenMode(int openMode); // "projects/library/seqan/file/file_cstyle.h"(66) //____________________________________________________________________________ // _openTempFArray template inline bool _openTempFArray(TFileArray &me, int openMode); // "projects/library/seqan/file/file_array.h"(221) template inline bool _openTempFArray(TFileArray &me); // "projects/library/seqan/file/file_array.h"(229) //____________________________________________________________________________ // _read_n_chars_from_file template inline void _read_n_chars_from_file(TFile & file, TSize count); // "projects/library/seqan/file/file_format_fasta.h"(187) //____________________________________________________________________________ // _reopenFArray template inline bool _reopenFArray(TFileArray &me, int openMode); // "projects/library/seqan/file/file_array.h"(234) //____________________________________________________________________________ // _sectorSizeFArray template inline unsigned _sectorSizeFArray(TFileArray &me, int openMode); // "projects/library/seqan/file/file_array.h"(250) //____________________________________________________________________________ // _sizeFArray template inline typename Size::Type _sizeFArray(TFileArray &me); // "projects/library/seqan/file/file_array.h"(256) //____________________________________________________________________________ // _streamClose inline void _streamClose(::std::FILE * & me); // "projects/library/seqan/file/cstream.h"(93) //____________________________________________________________________________ // _streamEOF template inline bool _streamEOF(::std::basic_ios const & me); // "projects/library/seqan/file/stream.h"(209) inline bool _streamEOF(::std::FILE * me); // "projects/library/seqan/file/cstream.h"(108) //____________________________________________________________________________ // _streamGet template inline TValue _streamGet(::std::basic_istream & source); // "projects/library/seqan/file/stream.h"(253) inline char _streamGet(::std::FILE * source); // "projects/library/seqan/file/cstream.h"(133) //____________________________________________________________________________ // _streamOpen inline bool _streamOpen(::std::FILE * & me, String path, bool for_read ); // "projects/library/seqan/file/cstream.h"(75) //____________________________________________________________________________ // _streamPeek template inline TValue _streamPeek(::std::basic_istream & source); // "projects/library/seqan/file/stream.h"(273) //____________________________________________________________________________ // _streamPut template inline void _streamPut(::std::basic_ostream & target, TChar character); // "projects/library/seqan/file/stream.h"(313) inline void _streamPut(::std::FILE * target, char character); // "projects/library/seqan/file/cstream.h"(145) //____________________________________________________________________________ // _streamPutFloat template inline void _streamPutFloat(TStream & target, float number, char const * format_string); // "projects/library/seqan/file/stream_algorithms.h"(73) template inline void _streamPutFloat(TStream & target, float number); // "projects/library/seqan/file/stream_algorithms.h"(83) //____________________________________________________________________________ // _streamPutInt template inline void _streamPutInt(TStream & target, int number, char const * format_string); // "projects/library/seqan/file/stream_algorithms.h"(44) template inline void _streamPutInt(TStream & target, int number); // "projects/library/seqan/file/stream_algorithms.h"(54) //____________________________________________________________________________ // _streamRead template inline ::std::streamsize _streamRead(TValue * target, ::std::basic_istream & source, ::std::streamsize limit); // "projects/library/seqan/file/stream.h"(232) template inline size_t _streamRead(TValue * target, ::std::FILE * source, size_t limit); // "projects/library/seqan/file/cstream.h"(122) //____________________________________________________________________________ // _streamSeek2G template inline void _streamSeek2G(::std::basic_istream & me, int off); // "projects/library/seqan/file/stream.h"(420) inline void _streamSeek2G(FILE * me, int off); // "projects/library/seqan/file/cstream.h"(208) //____________________________________________________________________________ // _streamSeekG template inline void _streamSeekG(::std::basic_istream & me, typename Position< ::std::basic_istream >::Type pos); // "projects/library/seqan/file/stream.h"(373) inline void _streamSeekG(FILE * me, Position::Type pos); // "projects/library/seqan/file/cstream.h"(184) //____________________________________________________________________________ // _streamSeekP template inline void _streamSeekP(::std::basic_ostream & me, typename Position< ::std::basic_ostream >::Type pos); // "projects/library/seqan/file/stream.h"(397) inline void _streamSeekP(FILE * me, Position::Type pos); // "projects/library/seqan/file/cstream.h"(196) //____________________________________________________________________________ // _streamTellG template inline typename Position< ::std::basic_istream >::Type _streamTellG(::std::basic_istream & me); // "projects/library/seqan/file/stream.h"(332) inline Position::Type _streamTellG(FILE * me); // "projects/library/seqan/file/cstream.h"(161) //____________________________________________________________________________ // _streamTellP template inline typename Position< ::std::basic_ostream >::Type _streamTellP(::std::basic_ostream & me); // "projects/library/seqan/file/stream.h"(351) inline Position::Type _streamTellP(FILE * me); // "projects/library/seqan/file/cstream.h"(172) //____________________________________________________________________________ // _streamUnget template inline void _streamUnget(::std::basic_istream & source); // "projects/library/seqan/file/stream.h"(292) inline void _streamUnget(::std::FILE * stream); // "projects/library/seqan/file/cstream.h"(219) //____________________________________________________________________________ // _streamWrite template inline void _streamWrite(TTarget & target, Pair const & source); // "projects/library/seqan/file/stream_algorithms.h"(94) template inline void _streamWrite(TTarget & target, Triple const & source); // "projects/library/seqan/file/stream_algorithms.h"(104) template inline void _streamWrite(TTarget & target, TSource const & source); // "projects/library/seqan/file/stream_algorithms.h"(128) //____________________________________________________________________________ // _streamWriteRange template inline void _streamWriteRange(TTarget & target, TIterator begin_, TIterator end_); // "projects/library/seqan/file/stream_algorithms.h"(193) //____________________________________________________________________________ // _streamWriteSeq template inline void _streamWriteSeq(TTarget & target, TSource const & source, False const); // "projects/library/seqan/file/stream_algorithms.h"(140) template inline void _streamWriteSeq(TTarget & target, TSource const & source, True const); // "projects/library/seqan/file/stream_algorithms.h"(151) template inline void _streamWriteSeq(TTarget & target, TSourceValue const * source, True const); // "projects/library/seqan/file/stream_algorithms.h"(168) //____________________________________________________________________________ // _stream_appendLine template inline void _stream_appendLine(TFile & file, TString & str, TChar & c); // "projects/library/seqan/file/file_format.h"(432) //____________________________________________________________________________ // _stream_countLine template inline void _stream_countLine(TFile & file, TChar & c); // "projects/library/seqan/file/file_format.h"(464) //____________________________________________________________________________ // _stream_isLetter template inline bool _stream_isLetter(TChar const c); // "projects/library/seqan/file/file_format.h"(564) //____________________________________________________________________________ // _stream_readWord template inline String _stream_readWord(TFile & file, TChar& c); // "projects/library/seqan/file/file_format.h"(548) //____________________________________________________________________________ // _stream_skipLine template inline typename Size::Type _stream_skipLine(TFile & file, TChar & c); // "projects/library/seqan/file/file_format.h"(495) //____________________________________________________________________________ // _stream_skipWhitespace template inline void _stream_skipWhitespace(TFile& file, TChar& c); // "projects/library/seqan/file/file_format.h"(534) //____________________________________________________________________________ // _string_appendLine template inline void _string_appendLine(TString1 & str, TString2 & a_str, TIter & it); // "projects/library/seqan/file/file_format.h"(624) //____________________________________________________________________________ // _string_readNumber template inline int _string_readNumber(TString & str, TIter& it); // "projects/library/seqan/file/file_format.h"(668) //____________________________________________________________________________ // _string_skipLine template inline typename Size::Type _string_skipLine(TString & str, TIter & it); // "projects/library/seqan/file/file_format.h"(588) //____________________________________________________________________________ // _string_skipWhitespace template inline void _string_skipWhitespace(TString& str, TIter& it); // "projects/library/seqan/file/file_format.h"(655) //____________________________________________________________________________ // _write_impl template void _write_impl(TFile& target, Align& align, TStringContainer& ids, CGViz); // "projects/library/seqan/file/file_format_cgviz.h"(62) template void _write_impl(TFile & file, TData & data, TString & id, Fasta); // "projects/library/seqan/file/file_format_fasta.h"(434) template void _write_impl(TFile& file, Align& align, TStringContainer& ids, FastaAlign); // "projects/library/seqan/file/file_format_fasta_align.h"(246) //____________________________________________________________________________ // alignSize template inline T1 alignSize(T1 _size, T2 _aligning); // "projects/library/seqan/file/file_base.h"(688) //____________________________________________________________________________ // allocPage template inline void allocPage(SimpleBuffer &pf, TSize size, T const & me); // "projects/library/seqan/file/file_page.h"(119) template inline void allocPage(PageFrame &pf, T const & me); // "projects/library/seqan/file/file_page.h"(334) //____________________________________________________________________________ // allocate template <__int64 _FileSize, typename TFile, typename TValue, typename TSize > inline void allocate(File< Chained<_FileSize, TFile> > const &me, TValue* &data, TSize count); // "projects/library/seqan/file/file_array.h"(340) template inline void allocate(File< Striped<_FileCount, TFile> > const &me, TValue* &data, TSize count); // "projects/library/seqan/file/file_array.h"(350) //____________________________________________________________________________ // append template inline void append(String > &me, TString const &string, Tag const expand); // "projects/library/seqan/file/string_external.h"(1895) template inline void append(String & target, _ChunkCollector const & source, Tag const ); // "projects/library/seqan/file/chunk_collector.h"(390) template inline void append(String & target, _ChunkCollector const & source, typename Size< String >::Type limit, Tag const ); // "projects/library/seqan/file/chunk_collector.h"(399) //____________________________________________________________________________ // appendValue template inline void appendValue(String > &me, TValue const &_Val, Tag const); // "projects/library/seqan/file/string_external.h"(1886) //____________________________________________________________________________ // areadAt template inline bool areadAt(File & me, TValue *memPtr, TSize const count, TPos const fileOfs, aRequest &request); // "projects/library/seqan/file/file_base.h"(588) template <__int64 _FileSize, typename TFile, typename TValue, typename TSize, typename TOffset, typename TRequest > inline bool areadAt(File< Chained<_FileSize, TFile> > &me, TValue *memPtr, TSize count, TOffset offset, TRequest &req); // "projects/library/seqan/file/file_array.h"(392) //____________________________________________________________________________ // assign template inline void assign( String > &target, TSource const &source, Tag const); // "projects/library/seqan/file/string_external.h"(1937) template inline void assign(_ChunkCollector & target, TSource & source); // "projects/library/seqan/file/chunk_collector.h"(231) template inline void assign(_ChunkCollector & target, TSource const & source); // "projects/library/seqan/file/chunk_collector.h"(238) template inline void assign(_ChunkCollector & target, TSource & source, TSize limit); // "projects/library/seqan/file/chunk_collector.h"(247) template inline void assign(_ChunkCollector & target, TSource const & source, TSize limit); // "projects/library/seqan/file/chunk_collector.h"(255) template inline void assign(String & target, _ChunkCollector const & source, Tag const tag); // "projects/library/seqan/file/chunk_collector.h"(316) template inline void assign(String & target, _ChunkCollector const & source, typename Size< String >::Type limit, Tag const tag); // "projects/library/seqan/file/chunk_collector.h"(325) //____________________________________________________________________________ // atBegin template inline bool atBegin(Iter & it); // "projects/library/seqan/file/file_filereader.h"(760) template inline bool atBegin(Iter const & it); // "projects/library/seqan/file/file_filereader.h"(766) template inline bool atBegin(VectorIterator &it); // "projects/library/seqan/file/string_external.h"(1650) template inline bool atBegin(VectorIterator const &it); // "projects/library/seqan/file/string_external.h"(1652) template inline bool atBegin(VectorConstIterator &it); // "projects/library/seqan/file/string_external.h"(1655) template inline bool atBegin(VectorConstIterator const &it); // "projects/library/seqan/file/string_external.h"(1657) template inline bool atBegin(VectorFwdIterator &it); // "projects/library/seqan/file/string_external.h"(1660) template inline bool atBegin(VectorFwdIterator const &it); // "projects/library/seqan/file/string_external.h"(1664) template inline bool atBegin(VectorFwdConstIterator &it); // "projects/library/seqan/file/string_external.h"(1669) template inline bool atBegin(VectorFwdConstIterator const &it); // "projects/library/seqan/file/string_external.h"(1673) //____________________________________________________________________________ // atEnd template inline bool atEnd(Iter & it); // "projects/library/seqan/file/file_filereader.h"(745) template inline bool atEnd(Iter const & it); // "projects/library/seqan/file/file_filereader.h"(751) template inline bool atEnd(VectorIterator &it); // "projects/library/seqan/file/string_external.h"(1679) template inline bool atEnd(VectorIterator const &it); // "projects/library/seqan/file/string_external.h"(1681) template inline bool atEnd(VectorConstIterator &it); // "projects/library/seqan/file/string_external.h"(1684) template inline bool atEnd(VectorConstIterator const &it); // "projects/library/seqan/file/string_external.h"(1686) template inline bool atEnd(VectorFwdIterator &it); // "projects/library/seqan/file/string_external.h"(1689) template inline bool atEnd(VectorFwdIterator const &it); // "projects/library/seqan/file/string_external.h"(1693) template inline bool atEnd(VectorFwdConstIterator &it); // "projects/library/seqan/file/string_external.h"(1698) template inline bool atEnd(VectorFwdConstIterator const &it); // "projects/library/seqan/file/string_external.h"(1702) template inline bool atEnd(Iter > & it); // "projects/library/seqan/file/file_filereaderiterator.h"(127) //____________________________________________________________________________ // awriteAt template inline bool awriteAt(File & me, TValue const *memPtr, TSize const count, TPos const fileOfs, aRequest &request); // "projects/library/seqan/file/file_base.h"(612) template <__int64 _FileSize, typename TFile, typename TValue, typename TSize, typename TOffset, typename TRequest > inline bool awriteAt(File< Chained<_FileSize, TFile> > &me, TValue const *memPtr, TSize count, TOffset offset, TRequest &req); // "projects/library/seqan/file/file_array.h"(409) //____________________________________________________________________________ // begin template inline typename Iterator< String >, TIteratorSpec >::Type begin(String > & me, Tag const); // "projects/library/seqan/file/file_filereader.h"(340) template inline typename Iterator< String > const, TIteratorSpec >::Type begin(String > const & me, Tag const); // "projects/library/seqan/file/file_filereader.h"(348) template inline typename Iterator >, Tag const>::Type begin(String > &me, Tag const); // "projects/library/seqan/file/string_external.h"(1834) template inline typename Iterator > const, Tag const>::Type begin(String > const &me, Tag const); // "projects/library/seqan/file/string_external.h"(1840) template inline TValue* begin(SimpleBuffer &pf, Standard); // "projects/library/seqan/file/file_page.h"(134) template inline TValue const * begin(SimpleBuffer const &pf, Standard); // "projects/library/seqan/file/file_page.h"(139) //____________________________________________________________________________ // cancel template inline bool cancel(File &, aRequest &); // "projects/library/seqan/file/file_base.h"(675) template inline bool cancel(PageFrame &pf, TFile &file); // "projects/library/seqan/file/file_page.h"(427) //____________________________________________________________________________ // clear template inline void clear(String > &me); // "projects/library/seqan/file/string_external.h"(1710) //____________________________________________________________________________ // close inline bool close(FILE* me); // "projects/library/seqan/file/file_cstyle.h"(103) template inline bool close(String > &me); // "projects/library/seqan/file/string_external.h"(1795) template inline bool close(File & me); // "projects/library/seqan/file/file_base.h"(261) template <__int64 _FileSize, typename TFile > inline bool close(File< Chained<_FileSize, TFile> > &me); // "projects/library/seqan/file/file_array.h"(315) template inline bool close(File< Striped<_FileCount, TFile> > &me); // "projects/library/seqan/file/file_array.h"(322) //____________________________________________________________________________ // container template inline TContainer & container(Iter & it); // "projects/library/seqan/file/file_filereader.h"(573) template inline TContainer & container(Iter const & it); // "projects/library/seqan/file/file_filereader.h"(579) template inline TExtString & container(VectorIterator &it); // "projects/library/seqan/file/string_external.h"(1629) template inline TExtString & container(VectorIterator const &it); // "projects/library/seqan/file/string_external.h"(1631) template inline TExtString & container(VectorConstIterator &it); // "projects/library/seqan/file/string_external.h"(1634) template inline TExtString & container(VectorConstIterator const &it); // "projects/library/seqan/file/string_external.h"(1636) template inline TExtString & container(VectorFwdIterator &it); // "projects/library/seqan/file/string_external.h"(1639) template inline TExtString & container(VectorFwdIterator const &it); // "projects/library/seqan/file/string_external.h"(1641) template inline TExtString & container(VectorFwdConstIterator &it); // "projects/library/seqan/file/string_external.h"(1644) template inline TExtString & container(VectorFwdConstIterator const &it); // "projects/library/seqan/file/string_external.h"(1646) //____________________________________________________________________________ // deallocate template <__int64 _FileSize, typename TFile, typename TValue, typename TSize > inline void deallocate(File< Chained<_FileSize, TFile> > const &me, TValue* &data, TSize count); // "projects/library/seqan/file/file_array.h"(345) template inline void deallocate(File< Striped<_FileCount, TFile> > const &me, TValue* &data, TSize count); // "projects/library/seqan/file/file_array.h"(355) //____________________________________________________________________________ // enclosingBlocks template inline T1 enclosingBlocks(T1 _size, T2 _blockSize); // "projects/library/seqan/file/file_base.h"(683) //____________________________________________________________________________ // end template inline typename Iterator< String >, TIteratorSpec >::Type end(String > & me, Tag const); // "projects/library/seqan/file/file_filereader.h"(360) template inline typename Iterator< String > const, TIteratorSpec >::Type end(String > const & me, Tag const); // "projects/library/seqan/file/file_filereader.h"(368) template inline typename Iterator >, Tag const>::Type end(String > &me, Tag const); // "projects/library/seqan/file/string_external.h"(1846) template inline typename Iterator > const, Tag const>::Type end(String > const &me, Tag const); // "projects/library/seqan/file/string_external.h"(1853) template inline TValue * end(SimpleBuffer &pf, Standard); // "projects/library/seqan/file/file_page.h"(144) template inline TValue const * end(SimpleBuffer const &pf, Standard); // "projects/library/seqan/file/file_page.h"(149) //____________________________________________________________________________ // equiDistantAlignedDistribution template inline unsigned equiDistantAlignedDistribution( SimpleBuffer &_clusterBuffer, unsigned aligning, unsigned _bufferSize, T const &me, TSize _size, unsigned _pageSize, Function const &_Func); // "projects/library/seqan/file/file_page.h"(934) //____________________________________________________________________________ // equiDistantDistribution template inline bool equiDistantDistribution( SimpleBuffer &_clusterBuffer, unsigned _bufferSize, T const &me, TSize _size, unsigned _pageSize, Function const &_Func); // "projects/library/seqan/file/file_page.h"(872) //____________________________________________________________________________ // flush inline bool flush(FILE*); // "projects/library/seqan/file/file_cstyle.h"(182) template inline void flush(String > &me); // "projects/library/seqan/file/string_external.h"(1722) template inline void flush(File &); // "projects/library/seqan/file/file_base.h"(631) //____________________________________________________________________________ // formatID template inline void * formatID(FileFormat const & file_format); // "projects/library/seqan/file/file_format.h"(171) //____________________________________________________________________________ // freePage template inline void freePage(SimpleBuffer &pf, T const & me); // "projects/library/seqan/file/file_page.h"(126) template inline void freePage(PageFrame &pf, T const & me); // "projects/library/seqan/file/file_page.h"(344) //____________________________________________________________________________ // getValue template inline typename GetValue >::Type getValue(Iter & it); // "projects/library/seqan/file/file_filereader.h"(533) template inline typename GetValue >::Type getValue(Iter const & it); // "projects/library/seqan/file/file_filereader.h"(544) template inline typename GetValue > >::Type getValue(Iter > & it); // "projects/library/seqan/file/file_filereaderiterator.h"(120) //____________________________________________________________________________ // goBegin template inline void goBegin(Iter & it); // "projects/library/seqan/file/file_filereader.h"(711) template inline void goBegin(Iter > & it, bool skip_meta); // "projects/library/seqan/file/file_format_fasta.h"(45) template inline void goBegin(Iter > & it); // "projects/library/seqan/file/file_format_fasta.h"(82) template inline void goBegin(Iter > & it, bool skip_meta ); // "projects/library/seqan/file/file_format_genbank.h"(46) template inline void goBegin(Iter > & it, bool skip_meta ); // "projects/library/seqan/file/file_format_embl.h"(47) //____________________________________________________________________________ // goEnd template inline void goEnd(Iter & it); // "projects/library/seqan/file/file_filereader.h"(733) //____________________________________________________________________________ // goNext template void goNext(TFile & file, CGViz); // "projects/library/seqan/file/file_format_cgviz.h"(48) template void goNext(TFile & file, Raw); // "projects/library/seqan/file/file_format_raw.h"(247) template inline void goNext(Iter & it); // "projects/library/seqan/file/file_filereader.h"(645) template inline void goNext(Iter > & it); // "projects/library/seqan/file/file_format_fasta.h"(90) template void goNext(TFile & file, Fasta); // "projects/library/seqan/file/file_format_fasta.h"(390) template inline void goNext(Iter > & it); // "projects/library/seqan/file/file_format_genbank.h"(124) template inline void goNext(TFile & file, Genbank); // "projects/library/seqan/file/file_format_genbank.h"(254) template void goNext(TFile & file, FastaAlign); // "projects/library/seqan/file/file_format_fasta_align.h"(233) template inline void goNext(TFile & file, FileFormat const & file_format); // "projects/library/seqan/file/file_format.h"(251) template inline void goNext(Iter > & it); // "projects/library/seqan/file/file_format_embl.h"(108) template inline void goNext(TFile & file, Embl); // "projects/library/seqan/file/file_format_embl.h"(427) //____________________________________________________________________________ // goPrevious template inline void goPrevious(Iter & it); // "projects/library/seqan/file/file_filereader.h"(677) //____________________________________________________________________________ // guessFileFormat template inline FileFormat & guessFileFormat(TFile & file, TData & data); // "projects/library/seqan/file/file_format_guess.h"(52) //____________________________________________________________________________ // host template inline TFile & host(Iter > & it); // "projects/library/seqan/file/file_filereaderiterator.h"(105) //____________________________________________________________________________ // id template inline void const * id(String > const & me); // "projects/library/seqan/file/file_filereader.h"(301) template inline void const * id(String > const &me); // "projects/library/seqan/file/string_external.h"(1958) //____________________________________________________________________________ // iterator template inline typename Iterator< String >, TIteratorSpec >::Type iterator(String > & me, TPosition pos, Tag const); // "projects/library/seqan/file/file_filereader.h"(381) template inline typename Iterator< String > const, TIteratorSpec >::Type iterator(String > const & me, TPosition pos, Tag const); // "projects/library/seqan/file/file_filereader.h"(390) //____________________________________________________________________________ // length template inline typename Size< String > >::Type length(String > & me); // "projects/library/seqan/file/file_filereader.h"(328) template inline typename Size< String > >::Type length(String > const &me); // "projects/library/seqan/file/string_external.h"(1803) template inline typename Size >::Type length(SimpleBuffer const &me); // "projects/library/seqan/file/file_page.h"(109) template inline typename Size > >::Type length(PageFrame > const & ); // "projects/library/seqan/file/file_page.h"(286) template <__int64 _FileSize, typename TFile > inline unsigned length(File< Chained<_FileSize, TFile> > const &me); // "projects/library/seqan/file/file_array.h"(284) template inline unsigned length(File< Striped<_FileCount, TFile> > const &me); // "projects/library/seqan/file/file_array.h"(289) template inline void length(TFile & file, FileFormat const & file_format); // "projects/library/seqan/file/file_format.h"(267) //____________________________________________________________________________ // open inline bool open(FILE* &me, const char *fileName, int openMode); // "projects/library/seqan/file/file_cstyle.h"(89) inline bool open(FILE* &me, const char *fileName); // "projects/library/seqan/file/file_cstyle.h"(94) template inline bool open(String > &me, const char *fileName, int openMode); // "projects/library/seqan/file/string_external.h"(1734) template inline bool open(String > &me, const char *fileName); // "projects/library/seqan/file/string_external.h"(1740) template inline bool open(String > &me, typename TConfig::TFile file); // "projects/library/seqan/file/string_external.h"(1746) template inline bool open(File &me, const char *fileName, int openMode); // "projects/library/seqan/file/file_base.h"(215) template inline bool open(File &me, const char *fileName); // "projects/library/seqan/file/file_base.h"(220) template <__int64 _FileSize, typename TFile > inline bool open(File< Chained<_FileSize, TFile> > &me, const char *fileName, int openMode); // "projects/library/seqan/file/file_array.h"(294) //____________________________________________________________________________ // openTemp inline bool openTemp(FILE* &me); // "projects/library/seqan/file/file_cstyle.h"(98) template inline bool openTemp(String > &me); // "projects/library/seqan/file/string_external.h"(1758) template inline bool openTemp(File &me); // "projects/library/seqan/file/file_base.h"(237) template inline bool openTemp(File &me, int openMode); // "projects/library/seqan/file/file_base.h"(242) template <__int64 _FileSize, typename TFile > inline bool openTemp(File< Chained<_FileSize, TFile> > &me, int openMode); // "projects/library/seqan/file/file_array.h"(303) template inline bool openTemp(File< Striped<_FileCount, TFile> > &me, int openMode); // "projects/library/seqan/file/file_array.h"(310) //____________________________________________________________________________ // operator!= template inline bool operator!= (Iter const & left, Iter const & right); // "projects/library/seqan/file/file_filereader.h"(791) template inline bool operator!= (FileFormat const & left, FileFormat const & right); // "projects/library/seqan/file/file_format.h"(348) template inline bool operator!= (FileFormat const & left, Tag const); // "projects/library/seqan/file/file_format.h"(357) template inline bool operator!= (Tag const, FileFormat const & right); // "projects/library/seqan/file/file_format.h"(366) //____________________________________________________________________________ // operator+ template inline Iter operator+ (Iter const & left, TIntegral right); // "projects/library/seqan/file/file_filereader.h"(848) template inline Iter operator+ (TIntegral left, Iter const & right); // "projects/library/seqan/file/file_filereader.h"(856) //____________________________________________________________________________ // operator+= template inline Iter & operator+= (Iter & left, TIntegral right); // "projects/library/seqan/file/file_filereader.h"(869) //____________________________________________________________________________ // operator- template inline Iter operator- (Iter const & left, TIntegral right); // "projects/library/seqan/file/file_filereader.h"(887) template inline typename Difference >::Type operator- (Iter const & left, Iter const & right); // "projects/library/seqan/file/file_filereader.h"(898) //____________________________________________________________________________ // operator-= template inline Iter & operator-= (Iter & left, TIntegral right); // "projects/library/seqan/file/file_filereader.h"(911) //____________________________________________________________________________ // operator< template inline bool operator< (Iter const & left, Iter const & right); // "projects/library/seqan/file/file_filereader.h"(804) //____________________________________________________________________________ // operator<< template ::std::ostream& operator<<(::std::ostream &out, const PageBucketExtended &pb); // "projects/library/seqan/file/file_page.h"(170) template ::std::ostream& operator<<(::std::ostream &out, const PageFrame &pf); // "projects/library/seqan/file/file_page.h"(304) //____________________________________________________________________________ // operator<= template inline bool operator<= (Iter const & left, Iter const & right); // "projects/library/seqan/file/file_filereader.h"(826) //____________________________________________________________________________ // operator== template inline bool operator== (Iter const & left, Iter const & right); // "projects/library/seqan/file/file_filereader.h"(778) template inline bool operator== (FileFormat const & left, FileFormat const & right); // "projects/library/seqan/file/file_format.h"(319) template inline bool operator== (FileFormat const & left, Tag const); // "projects/library/seqan/file/file_format.h"(328) template inline bool operator== (Tag const, FileFormat const & right); // "projects/library/seqan/file/file_format.h"(337) //____________________________________________________________________________ // operator> template inline bool operator> (Iter const & left, Iter const & right); // "projects/library/seqan/file/file_filereader.h"(813) //____________________________________________________________________________ // operator>= template inline bool operator>= (Iter const & left, Iter const & right); // "projects/library/seqan/file/file_filereader.h"(835) //____________________________________________________________________________ // pageSize template inline typename Size >::Type pageSize(SimpleBuffer &me); // "projects/library/seqan/file/file_page.h"(92) template inline typename Size > >::Type pageSize(PageFrame > & ); // "projects/library/seqan/file/file_page.h"(292) //____________________________________________________________________________ // position template inline typename Position >::Type position(Iter const & it); // "projects/library/seqan/file/file_filereader.h"(588) //____________________________________________________________________________ // push_back template inline void push_back(String > &me, TValue const &_Val); // "projects/library/seqan/file/string_external.h"(1877) //____________________________________________________________________________ // read template void read(TFile & file, TData & data, Raw); // "projects/library/seqan/file/file_format_raw.h"(191) template void read(TFile & file, TData & data, TSize limit, Raw); // "projects/library/seqan/file/file_format_raw.h"(204) template void read(TFile & file, TData & data); // "projects/library/seqan/file/file_format_raw.h"(307) template void read(TFile & file, TData & data, TSize limit); // "projects/library/seqan/file/file_format_raw.h"(316) template inline bool read(FILE* me, TValue *memPtr, TSize const count); // "projects/library/seqan/file/file_cstyle.h"(127) template void read(TFile & file, TData & data, TSize limit, Fasta); // "projects/library/seqan/file/file_format_fasta.h"(206) template void read(TFile & file, TData & data, Fasta tag); // "projects/library/seqan/file/file_format_fasta.h"(306) template inline bool read(File & me, TValue *memPtr, TSize const count); // "projects/library/seqan/file/file_base.h"(288) template inline void read(TFile & file, TData & data, Genbank); // "projects/library/seqan/file/file_format_genbank.h"(170) template inline void read(TFile & file, TData & data, TSize limit, Genbank); // "projects/library/seqan/file/file_format_genbank.h"(188) template void read(TFile & file, Align & align, FastaAlign); // "projects/library/seqan/file/file_format_fasta_align.h"(72) template inline void read(TFile & file, TData & data, FileFormat const & file_format); // "projects/library/seqan/file/file_format.h"(200) template inline void read(TFile & file, TData & data, TSize limit, FileFormat const & file_format); // "projects/library/seqan/file/file_format.h"(211) template inline void read(TFile & file, TData & data, Embl); // "projects/library/seqan/file/file_format_embl.h"(153) template inline void read(TFile & file, TData & data, TSize limit, Embl); // "projects/library/seqan/file/file_format_embl.h"(171) //____________________________________________________________________________ // readAt template inline bool readAt(FILE* me, TValue *memPtr, TSize const count, TPos const fileOfs); // "projects/library/seqan/file/file_cstyle.h"(145) template inline bool readAt(TFile & me, TValue *memPtr, TSize const count, TPos const fileOfs); // "projects/library/seqan/file/file_base.h"(324) template <__int64 _FileSize, typename TFile, typename TValue, typename TSize, typename TOffset > inline bool readAt(File< Chained<_FileSize, TFile> > &me, TValue *memPtr, TSize count, TOffset offset); // "projects/library/seqan/file/file_array.h"(364) //____________________________________________________________________________ // readBucket template inline unsigned readBucket( PageBucket &b, int pageNo, unsigned pageSize, unsigned dataSize, File< Striped<_FileCount, TFile> > &file); // "projects/library/seqan/file/file_page_raid0.h"(134) template inline unsigned readBucket(PageBucket &b, int pageNo, unsigned pageSize, unsigned dataSize, TFile &file); // "projects/library/seqan/file/file_page.h"(456) //____________________________________________________________________________ // readFeature template inline typename Position::Type readFeature(TString & str, typename Position::Type start_pos, TData & data, TKey key, Embl); // "projects/library/seqan/file/file_format_embl.h"(372) //____________________________________________________________________________ // readID template void readID(TFile & , TString & id, Raw); // "projects/library/seqan/file/file_format_raw.h"(219) template void readID(TFile & file, TString & id, Fasta); // "projects/library/seqan/file/file_format_fasta.h"(324) //____________________________________________________________________________ // readIDs template void readIDs(TFile& file, TStringContainer& ids, FastaAlign); // "projects/library/seqan/file/file_format_fasta_align.h"(178) //____________________________________________________________________________ // readLastPage template inline bool readLastPage( int pageNo, PageFrame >, TSpec> &pf, File< Striped<_FileCount, TFile> > &file, TSize size); // "projects/library/seqan/file/file_page_raid0.h"(84) template inline bool readLastPage(int pageNo, PageFrame &pf, TFile &file, TSize size); // "projects/library/seqan/file/file_page.h"(381) //____________________________________________________________________________ // readLineType template inline void readLineType(TFile & file, TData & data, TKey key, Embl); // "projects/library/seqan/file/file_format_embl.h"(248) template inline void readLineType(String & meta, TData & data, TKey key, Embl); // "projects/library/seqan/file/file_format_embl.h"(305) //____________________________________________________________________________ // readMeta template void readMeta(TFile & file, TMeta & meta, Raw); // "projects/library/seqan/file/file_format_raw.h"(233) template void readMeta(TFile & file, TMeta & meta, Fasta); // "projects/library/seqan/file/file_format_fasta.h"(376) template inline void readMeta(TFile & file, TMeta & meta, Genbank); // "projects/library/seqan/file/file_format_genbank.h"(212) template void readMeta(TFile & file, TMeta & meta, FastaAlign); // "projects/library/seqan/file/file_format_fasta_align.h"(223) template inline void readMeta(TFile & file, TMeta & meta, FileFormat const & file_format); // "projects/library/seqan/file/file_format.h"(235) template inline void readMeta(TFile & file, TMeta & meta, Embl); // "projects/library/seqan/file/file_format_embl.h"(194) //____________________________________________________________________________ // readPage template inline bool readPage( int pageNo, PageFrame >, TSpec> &pf, File< Striped<_FileCount, TFile> > &file); // "projects/library/seqan/file/file_page_raid0.h"(40) template inline bool readPage(int pageNo, PageFrame &pf, TFile &file); // "projects/library/seqan/file/file_page.h"(356) template inline bool readPage(PageFrame > &pf, TFile &file); // "projects/library/seqan/file/file_page.h"(440) //____________________________________________________________________________ // release template inline void release(FILE*, aRequest &); // "projects/library/seqan/file/file_cstyle.h"(187) template inline void release(File &, aRequest &); // "projects/library/seqan/file/file_base.h"(659) //____________________________________________________________________________ // reopen template inline void reopen(File &, int); // "projects/library/seqan/file/file_base.h"(247) //____________________________________________________________________________ // replace template inline void replace(String & target, typename Size< String >::Type pos_begin, typename Size< String >::Type pos_end, _ChunkCollector const & source, Tag const tag); // "projects/library/seqan/file/chunk_collector.h"(465) template inline void replace(String & target, typename Size< String >::Type pos_begin, typename Size< String >::Type pos_end, _ChunkCollector const & source, typename Size< String >::Type limit, Tag const tag); // "projects/library/seqan/file/chunk_collector.h"(477) template inline void replace(TTargetValue * target, size_t pos_begin, size_t pos_end, _ChunkCollector const & source, Tag const tag); // "projects/library/seqan/file/chunk_collector.h"(490) template inline void replace(TTargetValue * target, size_t pos_begin, size_t pos_end, _ChunkCollector const & source, size_t limit, Tag const tag); // "projects/library/seqan/file/chunk_collector.h"(502) //____________________________________________________________________________ // reserve template inline typename Size< String > >::Type reserve( String > &me, TSize new_capacity, Tag const); // "projects/library/seqan/file/string_external.h"(1826) //____________________________________________________________________________ // resize template inline void resize(FILE* me, TSize new_length); // "projects/library/seqan/file/file_cstyle.h"(176) template inline typename Size< String > >::Type resize( String > &me, TSize new_length, Tag const); // "projects/library/seqan/file/string_external.h"(1814) template inline void resize(File &me, TSize new_length); // "projects/library/seqan/file/file_base.h"(443) template inline void resize(SimpleBuffer &me, TSize size); // "projects/library/seqan/file/file_page.h"(114) template inline void resize(PageFrame > &me, TSize size); // "projects/library/seqan/file/file_page.h"(274) template inline void resize(PageFrame > & , TSize ); // "projects/library/seqan/file/file_page.h"(297) template <__int64 _FileSize, typename TFile, typename TSize > inline void resize(File< Chained<_FileSize, TFile> > &me, TSize new_length); // "projects/library/seqan/file/file_array.h"(335) //____________________________________________________________________________ // rewind template inline void rewind(File &me); // "projects/library/seqan/file/file_base.h"(411) //____________________________________________________________________________ // save template inline bool save(String > const &me, const char *fileName, int openMode); // "projects/library/seqan/file/string_external.h"(1765) template inline bool save(String > const &me, const char *fileName); // "projects/library/seqan/file/string_external.h"(1773) template inline bool save(String > const &me, typename TConfig::TFile file); // "projects/library/seqan/file/string_external.h"(1781) //____________________________________________________________________________ // sectorSize inline unsigned sectorSize(FILE* const &); // "projects/library/seqan/file/file_cstyle.h"(108) template inline unsigned sectorSize(File const & ); // "projects/library/seqan/file/file_base.h"(266) //____________________________________________________________________________ // seek template inline Size::Type seek(FILE* me, TPos const fileOfs, int origin); // "projects/library/seqan/file/file_cstyle.h"(113) template inline Size::Type seek(FILE* me, TPos const fileOfs); // "projects/library/seqan/file/file_cstyle.h"(118) template inline typename Position< File >::Type seek(File &me, TPos const fileOfs, int origin); // "projects/library/seqan/file/file_base.h"(370) template inline typename Position< File >::Type seek(File &me, TPos const fileOfs); // "projects/library/seqan/file/file_base.h"(382) //____________________________________________________________________________ // setEOF template inline bool setEOF(File & ); // "projects/library/seqan/file/file_base.h"(460) //____________________________________________________________________________ // setPageSize template inline void setPageSize(SimpleBuffer &me, TSize size); // "projects/library/seqan/file/file_page.h"(97) //____________________________________________________________________________ // setPosition template inline void setPosition(Iter & it, TPos pos); // "projects/library/seqan/file/file_filereader.h"(613) //____________________________________________________________________________ // size inline Size::Type size(FILE* me); // "projects/library/seqan/file/file_cstyle.h"(166) template inline typename Size >::Type size(File &me); // "projects/library/seqan/file/file_base.h"(426) template inline typename Size >::Type size(SimpleBuffer const &me); // "projects/library/seqan/file/file_page.h"(103) template inline typename Size > >::Type size(PageFrame > & ); // "projects/library/seqan/file/file_page.h"(280) template <__int64 _FileSize, typename TFile > __int64 size(File< Chained<_FileSize, TFile> > &me); // "projects/library/seqan/file/file_array.h"(325) template __int64 size(File< Striped<_FileCount, TFile> > &me); // "projects/library/seqan/file/file_array.h"(330) //____________________________________________________________________________ // tell inline Size::Type tell(FILE* me); // "projects/library/seqan/file/file_cstyle.h"(122) template inline typename Position< File >::Type tell(File &me); // "projects/library/seqan/file/file_base.h"(396) //____________________________________________________________________________ // value template inline TValue value(String > & me, TPos pos); // "projects/library/seqan/file/file_filereader.h"(312) template inline typename Reference >::Type value(Iter & it); // "projects/library/seqan/file/file_filereader.h"(558) template inline typename Reference >::Type value(Iter const & it); // "projects/library/seqan/file/file_filereader.h"(564) template inline typename Reference > >::Type value(String > &me, TPos pos); // "projects/library/seqan/file/string_external.h"(1861) template inline typename Reference > const>::Type value(String > const &me, TPos pos); // "projects/library/seqan/file/string_external.h"(1868) template inline typename Reference > >::Type value(Iter > & it); // "projects/library/seqan/file/file_filereaderiterator.h"(113) //____________________________________________________________________________ // waitFor inline bool waitFor(aDummyRequest &); // "projects/library/seqan/file/file_base.h"(648) template inline bool waitFor(aDummyRequest &, TTime); // "projects/library/seqan/file/file_base.h"(653) template inline bool waitFor(PageFrame &pf); // "projects/library/seqan/file/file_page.h"(407) template inline bool waitFor(PageFrame &pf, TTime timeOut); // "projects/library/seqan/file/file_page.h"(417) //____________________________________________________________________________ // write template void write(TFile & file, Align& align, CGViz); // "projects/library/seqan/file/file_format_cgviz.h"(190) template void write(TFile & file, Align & align, TStringContainer& ids, CGViz); // "projects/library/seqan/file/file_format_cgviz.h"(198) template void write(TFile & file, Align* align, TStringContainer & ids, CGViz); // "projects/library/seqan/file/file_format_cgviz.h"(206) template void write(TFile & file, Align & align, TStringContainer& ids, TMeta &, CGViz); // "projects/library/seqan/file/file_format_cgviz.h"(214) template void write(TFile & file, TData const & data, Raw); // "projects/library/seqan/file/file_format_raw.h"(266) template void write(TFile & file, TData const & data, TString const &, Raw); // "projects/library/seqan/file/file_format_raw.h"(279) template void write(TFile & file, TData const & data, TString const &, TMeta const &, Raw); // "projects/library/seqan/file/file_format_raw.h"(293) template void write(TFile & file, TData & data); // "projects/library/seqan/file/file_format_raw.h"(327) template void write(TFile & file, TData const & data); // "projects/library/seqan/file/file_format_raw.h"(335) template inline bool write(FILE* me, TValue const *memPtr, TSize const count); // "projects/library/seqan/file/file_cstyle.h"(136) template void write(TFile & file, TData & data, Fasta); // "projects/library/seqan/file/file_format_fasta.h"(468) template void write(TFile & file, TData & data, TString & id, Fasta); // "projects/library/seqan/file/file_format_fasta.h"(481) template void write(TFile & file, TDataValue * data, TString & id, Fasta); // "projects/library/seqan/file/file_format_fasta.h"(494) template void write(TFile & file, TData & data, TString & id, TMeta &, Fasta); // "projects/library/seqan/file/file_format_fasta.h"(509) template inline bool write(File & me, TValue const *memPtr, TSize const count); // "projects/library/seqan/file/file_base.h"(306) template inline void write(TFile & file, TData & data, Genbank); // "projects/library/seqan/file/file_format_genbank.h"(292) template inline void write(TFile & file, TData & data, TMeta & meta, Genbank); // "projects/library/seqan/file/file_format_genbank.h"(348) template void write(TFile & file, Align& align, FastaAlign); // "projects/library/seqan/file/file_format_fasta_align.h"(284) template void write(TFile & file, Align & align, TStringContainer& ids, FastaAlign); // "projects/library/seqan/file/file_format_fasta_align.h"(292) template void write(TFile & file, Align* align, TStringContainer & ids, FastaAlign); // "projects/library/seqan/file/file_format_fasta_align.h"(300) template void write(TFile & file, Align & align, TStringContainer& ids, TMeta &, FastaAlign); // "projects/library/seqan/file/file_format_fasta_align.h"(308) template inline void write(TFile & file, TData & data, FileFormat const & file_format); // "projects/library/seqan/file/file_format.h"(293) template inline void write(TFile & file, TData & data, TMeta & meta, FileFormat const & file_format); // "projects/library/seqan/file/file_format.h"(303) template inline void write(TFile & file, TData & data, Embl); // "projects/library/seqan/file/file_format_embl.h"(465) template inline void write(TFile & file, TData & data, TMeta & meta, Embl); // "projects/library/seqan/file/file_format_embl.h"(531) //____________________________________________________________________________ // writeAt template inline bool writeAt(FILE* me, TValue const *memPtr, TSize const count, TPos const fileOfs); // "projects/library/seqan/file/file_cstyle.h"(156) template inline bool writeAt(TFile & me, TValue const *memPtr, TSize const count, TPos const fileOfs); // "projects/library/seqan/file/file_base.h"(344) template <__int64 _FileSize, typename TFile, typename TValue, typename TSize, typename TOffset > inline bool writeAt(File< Chained<_FileSize, TFile> > &me, TValue const *memPtr, TSize count, TOffset offset); // "projects/library/seqan/file/file_array.h"(378) //____________________________________________________________________________ // writeBucket template inline bool writeBucket( PageBucket &b, int pageNo, unsigned pageSize, File< Striped<_FileCount, TFile> > &file); // "projects/library/seqan/file/file_page_raid0.h"(158) template inline bool writeBucket( PageFrame >, Dynamic > &pf, unsigned &pageOfs, File< Striped<_FileCount, TFile> > &file); // "projects/library/seqan/file/file_page_raid0.h"(179) template inline bool writeBucket(PageBucket &b, int pageNo, unsigned pageSize, TFile &file); // "projects/library/seqan/file/file_page.h"(474) template inline bool writeBucket(PageFrame > &pf, unsigned &pageOfs, TFile &file); // "projects/library/seqan/file/file_page.h"(490) //____________________________________________________________________________ // writeLastPage template inline bool writeLastPage( PageFrame >, TSpec> &pf, int pageNo, File< Striped<_FileCount, TFile> > &file, TSize size); // "projects/library/seqan/file/file_page_raid0.h"(106) template inline bool writeLastPage(PageFrame &pf, int pageNo, TFile &file, TSize size); // "projects/library/seqan/file/file_page.h"(394) //____________________________________________________________________________ // writePage template inline bool writePage( PageFrame >, TSpec> &pf, int pageNo, File< Striped<_FileCount, TFile> > &file); // "projects/library/seqan/file/file_page_raid0.h"(62) template inline bool writePage(PageFrame &pf, int pageNo, TFile &file); // "projects/library/seqan/file/file_page.h"(369) template inline bool writePage(PageFrame > &pf, TFile &file); // "projects/library/seqan/file/file_page.h"(448) } //namespace SEQAN_NAMESPACE_MAIN #endif ugene-1.9.8/src/plugins_3rdparty/bowtie/src/bowtie/SeqAn-1.1/seqan/file/stream.h0000644000175000017500000003141511651544326025774 0ustar ilyailya /*========================================================================== SeqAn - The Library for Sequence Analysis http://www.seqan.de ============================================================================ Copyright (C) 2007 This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. ============================================================================ $Id: stream.h,v 1.1 2008/08/25 16:20:04 langmead Exp $ ==========================================================================*/ #ifndef SEQAN_HEADER_STREAM_H #define SEQAN_HEADER_STREAM_H #include namespace SEQAN_NAMESPACE_MAIN { ////////////////////////////////////////////////////////////////////////////// /** .Adaption."std::iostream": ..summary:Standard library stream classes. */ ////////////////////////////////////////////////////////////////////////////// template struct Position< ::std::basic_ios > { typedef typename ::std::basic_ios::pos_type Type; }; template struct Position< ::std::basic_streambuf > { typedef typename ::std::basic_streambuf::pos_type Type; }; template struct Position< ::std::basic_istream > { typedef typename ::std::basic_istream::pos_type Type; }; template struct Position< ::std::basic_ostream > { typedef typename ::std::basic_ostream::pos_type Type; }; template struct Position< ::std::basic_iostream > { typedef typename ::std::basic_iostream::pos_type Type; }; template struct Position< ::std::basic_stringbuf > { typedef typename ::std::basic_stringbuf::pos_type Type; }; template struct Position< ::std::basic_istringstream > { typedef typename ::std::basic_istringstream::pos_type Type; }; template struct Position< ::std::basic_ostringstream > { typedef typename ::std::basic_ostringstream::pos_type Type; }; template struct Position< ::std::basic_stringstream > { typedef typename ::std::basic_stringstream::pos_type Type; }; template struct Position< ::std::basic_filebuf > { typedef typename ::std::basic_filebuf::pos_type Type; }; template struct Position< ::std::basic_ifstream > { typedef typename ::std::basic_ifstream::pos_type Type; }; template struct Position< ::std::basic_ofstream > { typedef typename ::std::basic_ofstream::pos_type Type; }; template struct Position< ::std::basic_fstream > { typedef typename ::std::basic_fstream::pos_type Type; }; ////////////////////////////////////////////////////////////////////////////// template struct Value< ::std::basic_ios > { typedef typename ::std::basic_ios::char_type Type; }; template struct Value< ::std::basic_streambuf > { typedef typename ::std::basic_streambuf::char_type Type; }; template struct Value< ::std::basic_istream > { typedef typename ::std::basic_istream::char_type Type; }; template struct Value< ::std::basic_ostream > { typedef typename ::std::basic_ostream::char_type Type; }; template struct Value< ::std::basic_iostream > { typedef typename ::std::basic_iostream::char_type Type; }; template struct Value< ::std::basic_stringbuf > { typedef typename ::std::basic_stringbuf::char_type Type; }; template struct Value< ::std::basic_istringstream > { typedef typename ::std::basic_istringstream::char_type Type; }; template struct Value< ::std::basic_ostringstream > { typedef typename ::std::basic_ostringstream::char_type Type; }; template struct Value< ::std::basic_stringstream > { typedef typename ::std::basic_stringstream::char_type Type; }; template struct Value< ::std::basic_filebuf > { typedef typename ::std::basic_filebuf::char_type Type; }; template struct Value< ::std::basic_ifstream > { typedef typename ::std::basic_ifstream::char_type Type; }; template struct Value< ::std::basic_ofstream > { typedef typename ::std::basic_ofstream::char_type Type; }; template struct Value< ::std::basic_fstream > { typedef typename ::std::basic_fstream::char_type Type; }; ////////////////////////////////////////////////////////////////////////////// /**.interal._IsTellSeekStream: ..summary:Determines whether stream supports tell and seek functions. ..cat:Metafunction */ template struct _IsTellSeekStream { typedef False Type; }; template struct _IsTellSeekStream< ::std::basic_ifstream > { typedef True Type; }; template struct _IsTellSeekStream< ::std::basic_fstream > { typedef True Type; }; ////////////////////////////////////////////////////////////////////////////// /** .Internal._streamEOF: ..summary:Test stream for being in eof or error state. ..cat:Streams ..signature:_streamEOF(stream) ..param.stream:A stream object. ...type:Adaption."std::iostream" ..returns:$true$, if stream is at end of file or was set to error state, $false$ otherwise. */ template inline bool _streamEOF(::std::basic_ios const & me) { SEQAN_CHECKPOINT return me.eof() || me.fail(); } ////////////////////////////////////////////////////////////////////////////// /** .Internal._streamRead: ..summary:Read some characters from stream into a buffer. ..cat:Streams ..signature:_streamRead(target, stream, limit) ..param.target:A buffer that is filled. ..param.stream:An input stream. ...type:Adaption."std::iostream" ..param.limit:The maximal number of characters that is read from $stream$. ..returns:The number of characters read from $stream$. */ template inline ::std::streamsize _streamRead(TValue * target, ::std::basic_istream & source, ::std::streamsize limit) { SEQAN_CHECKPOINT source.read(target, limit); return source.gcount(); } ////////////////////////////////////////////////////////////////////////////// /** .Internal._streamGet: ..summary:Read one character from stream. ..cat:Streams ..signature:_streamGet(stream) ..param.stream:An input stream. ...type:Adaption."std::iostream" ..returns:The character read. */ template inline TValue _streamGet(::std::basic_istream & source) { SEQAN_CHECKPOINT return source.get(); } ////////////////////////////////////////////////////////////////////////////// /** .Internal._streamPeek: ..summary:Return the next character to be read from stream. ..cat:Streams ..signature:_streamPeek(stream) ..param.stream:An input stream. ...type:Adaption."std::iostream" ..returns:The character to be read. */ template inline TValue _streamPeek(::std::basic_istream & source) { SEQAN_CHECKPOINT return source.peek(); } ////////////////////////////////////////////////////////////////////////////// /** .Internal._streamUnget: ..summary:Put the last read character back into stream. ..cat:Streams ..signature:_streamUnget(stream) ..param.stream:An input stream. ...type:Adaption."std::iostream" */ template inline void _streamUnget(::std::basic_istream & source) { SEQAN_CHECKPOINT source.unget(); } ////////////////////////////////////////////////////////////////////////////// /** .Internal._streamPut: ..summary:Writes one character to stream. ..cat:Streams ..signature:_streamPut(stream, character) ..param.stream:An input stream. ...type:Adaption."std::iostream" ..param.character:A character that is written to $stream$. */ template inline void _streamPut(::std::basic_ostream & target, TChar character) { SEQAN_CHECKPOINT target.put(convert(character)); } ////////////////////////////////////////////////////////////////////////////// /** .Internal._streamTellG: ..cat:Streams ..summary:Gets current position of input stream. ..signature:_streamTellG(stream) ..param.stream:An input stream. ...type:Adaption."std::iostream" ..returns:The current position in $stream$. */ template inline typename Position< ::std::basic_istream >::Type _streamTellG(::std::basic_istream & me) { SEQAN_CHECKPOINT return me.tellg(); } ////////////////////////////////////////////////////////////////////////////// /** .Internal._streamTellP: ..cat:Streams ..summary:Gets current position of output stream. ..signature:_streamTellP(stream) ..param.stream:An ouput stream. ...type:Adaption."std::iostream" ..returns:The current position in $stream$. ..see:Internal._streamTellG */ template inline typename Position< ::std::basic_ostream >::Type _streamTellP(::std::basic_ostream & me) { SEQAN_CHECKPOINT return me.tellp(); } ////////////////////////////////////////////////////////////////////////////// /** .Internal._streamSeekG: ..summary:Moves input stream to a position. ..cat:Streams ..signature:_streamSeekG(stream, position) ..param.stream:An input stream. ...type:Adaption."std::iostream" ..param.position:A position within the stream. ...remarks:Use @Function._streamTellG@ to get valid stream positions. ..see:Internal._streamTellG */ template inline void _streamSeekG(::std::basic_istream & me, typename Position< ::std::basic_istream >::Type pos) { SEQAN_CHECKPOINT me.clear(); me.seekg(pos); } ////////////////////////////////////////////////////////////////////////////// /** .Internal._streamSeekP: ..summary:Moves output stream to a position. ..cat:Streams ..signature:_streamSeekP(stream, position) ..param.stream:An output stream. ...type:Adaption."std::iostream" ..param.position:A position within the stream. ...remarks:Use @Function._streamTellP@ to get valid stream positions. ..see:Internal._streamTellP ..see:Internal._streamSeekG */ template inline void _streamSeekP(::std::basic_ostream & me, typename Position< ::std::basic_ostream >::Type pos) { SEQAN_CHECKPOINT me.clear(); me.seekp(pos); } ////////////////////////////////////////////////////////////////////////////// /** .Internal._streamSeek2G: ..summary:Moves input stream position relative to current position. ..cat:Streams ..signature:_streamSeek2G(stream, offset) ..param.stream:An input stream. ...type:Adaption."std::iostream" ..param.offset:The amout the position is changed. ...remarks:If this value is negative. ..see:Internal._streamSeekG */ template inline void _streamSeek2G(::std::basic_istream & me, int off) { SEQAN_CHECKPOINT me.seekg(off, ::std::ios_base::cur); } ////////////////////////////////////////////////////////////////////////////// } //namespace SEQAN_NAMESPACE_MAIN #endif //#ifndef SEQAN_HEADER_... ugene-1.9.8/src/plugins_3rdparty/bowtie/src/bowtie/SeqAn-1.1/seqan/file/file_format_cgviz.h0000644000175000017500000001644111651544326030174 0ustar ilyailya /*========================================================================== SeqAn - The Library for Sequence Analysis http://www.seqan.de ============================================================================ Copyright (C) 2007 This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. ============================================================================ $Id: file_format_cgviz.h,v 1.1 2008/08/25 16:20:03 langmead Exp $ ==========================================================================*/ #ifndef SEQAN_HEADER_FILE_CGVIZ_H #define SEQAN_HEADER_FILE_CGVIZ_H namespace SEQAN_NAMESPACE_MAIN { ////////////////////////////////////////////////////////////////////////////// // File Formats - CGViz ////////////////////////////////////////////////////////////////////////////// /** .Tag.File Format.tag.CGViz: CGViz file format for sequences. Only output. */ struct TagCGViz_; typedef Tag const CGViz; ///////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// // goNext ////////////////////////////////////////////////////////////////////////////// template void goNext(TFile & file, CGViz) { SEQAN_CHECKPOINT SEQAN_ASSERT(!_streamEOF(file)) return; } ////////////////////////////////////////////////////////////////////////////// // write ////////////////////////////////////////////////////////////////////////////// template void _write_impl(TFile& target, Align& align, TStringContainer& ids, CGViz) { SEQAN_CHECKPOINT typedef Align const TAlign; typedef typename Row::Type TRow; typedef typename Position::Type>::Type TRowsPosition; typedef typename Position::Type TPosition; TRowsPosition row_count = length(rows(align)); if (row_count < 2) return; unsigned int pair=1; unsigned int count=0; for(TRowsPosition i=0;i'); _streamPut(target, ' '); _streamPutInt(target, count); _streamPut(target, ' '); _streamPutInt(target, count+1); _streamPut(target, '\n'); _streamPut(target, '}'); _streamPut(target, '\n'); ++count; _streamWrite(target, "{THREADER Threader<"); _streamPutInt(target, pair); _streamPut(target, '>'); _streamPut(target, ' '); _streamPutInt(target, count); _streamPut(target, ' '); _streamPutInt(target, count+1); _streamPut(target, '\n'); _streamPut(target, '}'); _streamPut(target, '\n'); ++count; _streamWrite(target, "{ANCHOR Anchor<"); _streamPutInt(target, pair); _streamPut(target, '>'); _streamPut(target, ' '); _streamPutInt(target, count); _streamPut(target, ' '); _streamPutInt(target, count+1); _streamPut(target, '\n'); _streamPut(target, '}'); _streamPut(target, '\n'); count+=2; ++pair; } } } //____________________________________________________________________________ template void write(TFile & file, Align& align, CGViz) { SEQAN_CHECKPOINT _write_impl(file, align, String >(), CGViz()); } //____________________________________________________________________________ template void write(TFile & file, Align & align, TStringContainer& ids, CGViz) { SEQAN_CHECKPOINT _write_impl(file, align, ids, CGViz()); } //VisualC++ const array bug workaround template void write(TFile & file, Align* align, TStringContainer & ids, CGViz) { SEQAN_CHECKPOINT _write_impl(file, align, ids, CGViz()); } //____________________________________________________________________________ template void write(TFile & file, Align & align, TStringContainer& ids, TMeta &, CGViz) { SEQAN_CHECKPOINT _write_impl(file, align, ids, CGViz()); } ////////////////////////////////////////////////////////////////////////////// } //namespace SEQAN_NAMESPACE_MAIN ////////////////////////////////////////////////////////////////////////////// #endif //#ifndef SEQAN_HEADER_... ugene-1.9.8/src/plugins_3rdparty/bowtie/src/bowtie/SeqAn-1.1/seqan/file/file_forwards.h0000644000175000017500000000312411651544326027323 0ustar ilyailya /*========================================================================== SeqAn - The Library for Sequence Analysis http://www.seqan.de ============================================================================ Copyright (C) 2007 This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. ============================================================================ $Id: file_forwards.h,v 1.1 2008/08/25 16:20:03 langmead Exp $ ==========================================================================*/ #ifndef SEQAN_HEADER_FILE_FORWARDS_H #define SEQAN_HEADER_FILE_FORWARDS_H //SEQAN_NO_GENERATED_FORWARDS: no forwards are generated for this file ////////////////////////////////////////////////////////////////////////////// namespace SEQAN_NAMESPACE_MAIN { ////////////////////////////////////////////////////////////////////////////// template class Align; ////////////////////////////////////////////////////////////////////////////// } //namespace SEQAN_NAMESPACE_MAIN ////////////////////////////////////////////////////////////////////////////// #endif ugene-1.9.8/src/plugins_3rdparty/bowtie/src/bowtie/SeqAn-1.1/seqan/file/file_format_guess.h0000644000175000017500000000636311651544326030202 0ustar ilyailya /*========================================================================== SeqAn - The Library for Sequence Analysis http://www.seqan.de ============================================================================ Copyright (C) 2007 This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. ============================================================================ $Id: file_format_guess.h,v 1.1 2008/08/25 16:20:04 langmead Exp $ ==========================================================================*/ #ifndef SEQAN_HEADER_FILE_GUESS_H #define SEQAN_HEADER_FILE_GUESS_H namespace SEQAN_NAMESPACE_MAIN { ////////////////////////////////////////////////////////////////////////////// // guessFileFormat ////////////////////////////////////////////////////////////////////////////// //guessFileFormat braucht auch data, weil die FileFormat-Klasse von TData //abhaengig, und das ist so, weil sonst die Kombination von Templates mit //virtuellen Funktionen nicht funktionieren wuerde. /** .Function.guessFileFormat: ..cat:Input/Output ..summary:Tries to determine the format of a file. ..signature:guessFileFormat(file, data) ..param.file: An input file. ..param.data: The target container. ...remarks:This container is not modified by this function. ..returns:A file format object instance that represents the determined file format. ...type:Class.FileFormat ..remarks:The $data$-argument is used here as a tag to determine the type of the target. ..see:Function.Fileformat#read ..see:Tag.File Format */ template inline FileFormat & guessFileFormat(TFile & file, TData & data) { SEQAN_CHECKPOINT typename Position::Type old_pos = _streamTellG(file); typename Value::Type c; _streamSeekG(file, 0); /// move to beginning of file c = _streamGet(file); if (c=='>') { _streamSeekG(file, old_pos); return getFileFormatInstance(); } if (c=='L') { _streamSeekG(file, old_pos); return getFileFormatInstance(); } if (c=='I') { _streamSeekG(file, old_pos); return getFileFormatInstance(); } else { _streamSeekG(file, old_pos); return getFileFormatInstance(); } } ////////////////////////////////////////////////////////////////////////////// /* DOCH NICHT: template inline void read(TTarget & target, TSource & source) { SEQAN_CHECKPOINT read(target, source, guessFileFormat(target, source)); } */ ////////////////////////////////////////////////////////////////////////////// } //namespace SEQAN_NAMESPACE_MAIN ////////////////////////////////////////////////////////////////////////////// #endif //#ifndef SEQAN_HEADER_... ugene-1.9.8/src/plugins_3rdparty/bowtie/src/bowtie/SeqAn-1.1/seqan/file/file_format_raw.h0000644000175000017500000001715611651544326027647 0ustar ilyailya /*========================================================================== SeqAn - The Library for Sequence Analysis http://www.seqan.de ============================================================================ Copyright (C) 2007 This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. ============================================================================ $Id: file_format_raw.h,v 1.1 2008/08/25 16:20:03 langmead Exp $ ==========================================================================*/ #ifndef SEQAN_HEADER_FILE_RAW_H #define SEQAN_HEADER_FILE_RAW_H namespace SEQAN_NAMESPACE_MAIN { ////////////////////////////////////////////////////////////////////////////// // File Formats - Raw ////////////////////////////////////////////////////////////////////////////// /** .Tag.File Format.tag.Raw: The file contains data in a raw format. ..remark:It is supposed that the file contains one single piece of data, that is the file cannot store multiple records. */ struct TagRaw_; typedef Tag const Raw; ////////////////////////////////////////////////////////////////////////////// // read ////////////////////////////////////////////////////////////////////////////// template struct _Read_Raw; //____________________________________________________________________________ template struct _Read_Raw { static void read_(TFile & file, TData & data) { SEQAN_CHECKPOINT SEQAN_ASSERT(!_streamEOF(file)) //determine length typename Position::Type begin_pos = _streamTellG(file); typename Size::Type count = 0; typename Value::Type c = _streamGet(file); while (!_streamEOF(file)) { c = _streamGet(file); ++count; } //reserve space resize(data, count); if (!count) return; if (length(data) < count) { count = length(data); } //read sequence _streamSeekG(file, begin_pos); typename Position::Type pos; for (pos = 0; pos < count; ) { c = _streamGet(file); assignValue(data, pos, c); ++pos; } } //____________________________________________________________________________ template static void read_(TFile & file, TData & data, TSize _limit) { SEQAN_CHECKPOINT SEQAN_ASSERT(!_streamEOF(file)) typename Size::Type limit = _limit; //determine length typename Position::Type begin_pos = _streamTellG(file); typename Size::Type count = 0; typename Value::Type c = _streamGet(file); while (!_streamEOF(file)) { c = _streamGet(file); ++count; if (count == limit) break; } //reserve space resize(data, count); if (!count) return; if (length(data) < count) { count = length(data); } //read sequence _streamSeekG(file, begin_pos); typename Position::Type pos; for (pos = 0; pos < count; ) { c = _streamGet(file); assignValue(data, pos, c); ++pos; } } }; //____________________________________________________________________________ template struct _Read_Raw { static void read_(TFile & file, TData & data) { SEQAN_CHECKPOINT clear(data); if (!_streamEOF(file)) { SEQAN_CHECKPOINT _ChunkCollector chunk_collector(data); assign(chunk_collector, file); append(data, chunk_collector); } } //____________________________________________________________________________ template static void read_(TFile & file, TData & data, TSize limit) { SEQAN_CHECKPOINT clear(data); if (!_streamEOF(file)) { SEQAN_CHECKPOINT _ChunkCollector chunk_collector(data); assign(chunk_collector, file, limit); append(data, chunk_collector, limit); } } }; ////////////////////////////////////////////////////////////////////////////// template void read(TFile & file, TData & data, Raw) { SEQAN_CHECKPOINT _Read_Raw::Type>::read_(file, data); } //____________________________________________________________________________ template void read(TFile & file, TData & data, TSize limit, Raw) { SEQAN_CHECKPOINT _Read_Raw::Type>::read_(file, data, limit); } ////////////////////////////////////////////////////////////////////////////// // readID ////////////////////////////////////////////////////////////////////////////// template void readID(TFile & /*file*/, TString & id, Raw) { SEQAN_CHECKPOINT clear(id); } ////////////////////////////////////////////////////////////////////////////// // readMeta ////////////////////////////////////////////////////////////////////////////// template void readMeta(TFile & file, TMeta & meta, Raw) { SEQAN_CHECKPOINT clear(meta); } ////////////////////////////////////////////////////////////////////////////// // goNext ////////////////////////////////////////////////////////////////////////////// template void goNext(TFile & file, Raw) { SEQAN_CHECKPOINT SEQAN_ASSERT(!_streamEOF(file)) //??? TODO: set file to eof } ////////////////////////////////////////////////////////////////////////////// // write ////////////////////////////////////////////////////////////////////////////// template void write(TFile & file, TData const & data, Raw) { SEQAN_CHECKPOINT _streamWrite(file, data); } //____________________________________________________________________________ template void write(TFile & file, TData const & data, TString const &, Raw) { SEQAN_CHECKPOINT _streamWrite(file, data); } //____________________________________________________________________________ template void write(TFile & file, TData const & data, TString const &, TMeta const &, Raw) { SEQAN_CHECKPOINT _streamWrite(file, data); } ////////////////////////////////////////////////////////////////////////////// // default functions ////////////////////////////////////////////////////////////////////////////// template void read(TFile & file, TData & data) { read(file, data, Raw()); } template void read(TFile & file, TData & data, TSize limit) { SEQAN_CHECKPOINT read(file, data, limit, Raw()); } //____________________________________________________________________________ template void write(TFile & file, TData & data) { SEQAN_CHECKPOINT write(file, data, "", Raw()); } template void write(TFile & file, TData const & data) { SEQAN_CHECKPOINT write(file, data, "", Raw()); } ////////////////////////////////////////////////////////////////////////////// } //namespace SEQAN_NAMESPACE_MAIN ////////////////////////////////////////////////////////////////////////////// #endif //#ifndef SEQAN_HEADER_... ugene-1.9.8/src/plugins_3rdparty/bowtie/src/bowtie/SeqAn-1.1/seqan/file/file_base.h0000644000175000017500000005165111651544326026416 0ustar ilyailya /*========================================================================== SeqAn - The Library for Sequence Analysis http://www.seqan.de ============================================================================ Copyright (C) 2007 This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. ============================================================================ $Id: file_base.h,v 1.2 2009/02/19 01:51:23 langmead Exp $ ==========================================================================*/ #ifndef SEQAN_HEADER_FILE_BASE_H #define SEQAN_HEADER_FILE_BASE_H ////////////////////////////////////////////////////////////////////////////// namespace SEQAN_NAMESPACE_MAIN { // To override the system's default temporary directory use the following: //#define SEQAN_DEFAULT_TMPDIR "/var/tmp" // To use direct I/O access define SEQAN_DIRECTIO (not completely tested yet) //#define SEQAN_DIRECTIO /** .Spec.Sync: ..cat:Files ..general:Class.File ..summary:File structure supporting synchronous input/output access. ..signature:File > ..remarks:This class suports pseudo-asynchronous access methods, i.e. the methods to initiate a I/O request return after request completion. */ template struct Sync; /** .Spec.Async: ..cat:Files ..general:Class.File ..summary:File structure supporting synchronous and asynchronous input/output access. ..signature:File > */ template struct Async; /** .Class.File: ..cat:Input/Output ..summary:Represents a file. ..signature:File ..param.TSpec:The specializing type. ...default:$Async<>$, see @Spec.Async@. */ template > class File; /** .Spec.Chained: ..cat:Files ..general:Class.File ..summary:Splits a large file into a chain of smaller files. ..signature:File > ..param.FileSize:The maximal split file size in byte. ...default:2^31-1 (~2GB) ..param.TFile:Underlying @Class.File@ type. ...default:$File<>$, see @Class.File@. ..remarks:This file type uses a chain of $TFile$ files, whose file sizes are at most $FileSize$ bytes. Chained Files should be used for file systems or $TFile$ types that don't support large files (e.g. FAT32, C-style FILE*). ..remarks:The chain can be used as if it were one contiguous file. */ // chained file's default filesize is 2gb-1byte (fat16 filesize limitation) template < __int64 _FileSize = ~(((__int64)1) << 63), typename TFile = File<> > struct Chained; /** .Spec.Striped: ..cat:Files ..general:Class.File ..summary:Stripes a file across multiple files. ..signature:File > ..param.FileCount:The number of files used for striping. ...default:2 ..param.TFile:Underlying @Class.File@ type. ...default:$File<>$, see @Class.File@. ..remarks:This file type uses a software striping without redundance (see RAID0) to accelerate I/O access when using more than one disks. ..remarks:Striped files should only be used in @Class.Pool@s or external Strings as they only support block operations and no random accesses. */ template < unsigned _FileCount = 2, typename TFile = File<> > struct Striped; enum FileOpenMode { OPEN_RDONLY = 1, OPEN_WRONLY = 2, OPEN_RDWR = 3, OPEN_MASK = 3, OPEN_CREATE = 4, OPEN_APPEND = 8, OPEN_ASYNC = 16, OPEN_TEMPORARY = 32, OPEN_QUIET = 128 }; template struct DefaultOpenMode { enum { VALUE = (OPEN_RDWR + OPEN_CREATE) | OPEN_APPEND }; }; template struct DefaultOpenTempMode { enum { VALUE = OPEN_RDWR + OPEN_CREATE }; }; enum FileSeekMode { SEEK_BEGIN = 0, SEEK_CURRENT = 1 #ifndef SEEK_END , SEEK_END = 2 #endif }; ////////////////////////////////////////////////////////////////////////////// // result type of asynch. functions // you have to call release(aRequest) after a finished *event based* transfer struct aDummyRequest {}; /** .Class.aRequest: ..cat:Input/Output ..summary:Associated with an asynchronous I/O request. ..signature:aRequest ..param.TFile:A File type. ..remarks:This structure is used to identify asynchronous requests after their initiation. */ template < typename T > struct aRequest { typedef aDummyRequest Type; }; /* ////////////////////////////////////////////////////////////////////////////// // event to represent asynchronous transfers // you can wait for it or test it template < typename T > struct aEvent { typedef DummyEvent Type; }; //////////////////////////////////////////////////////////////////////////////// // callback hint parameter type // hint lets you recognize the finished asynch. transfer in your own callback routine template < typename T > struct aHint { typedef void Type; }; ////////////////////////////////////////////////////////////////////////////// // callback function interface template < typename T > struct aCallback { typedef void Type(aHint *); }; ////////////////////////////////////////////////////////////////////////////// // file queue interface template < typename T > struct aQueue { typedef Nothing Type; }; */ ////////////////////////////////////////////////////////////////////////////// // generic open/close interface /** .Function.open: ..summary:Opens a file. ..cat:Input/Output ..signature:open(file, fileName[, openMode]) ..param.file:A File object. ...type:Class.File ..param.fileName:C-style character string containing the file name. ..param.openMode:The combination of flags defining how the file should be opened. ...remarks:To open a file read-only, write-only or to read and write use $OPEN_RDONLY$, $OPEN_WRONLY$, or $OPEN_RDWR$. ...remarks:To create or overwrite a file add $OPEN_CREATE$. ...remarks:To append a file if existing add $OPEN_APPEND$. ...default:$OPEN_RDWR | OPEN_CREATE | OPEN_APPEND$ ..returns:A $bool$ which is $true$ on success. */ template < typename TSpec > inline bool open(File &me, const char *fileName, int openMode) { return me.open(fileName, openMode); } template < typename TSpec > inline bool open(File &me, const char *fileName) { return open(me, fileName, DefaultOpenMode >::VALUE); } /** .Function.openTemp: ..summary:Opens a temporary file. ..cat:Input/Output ..signature:openTemp(file) ..param.file:A File object. ...type:Class.File ..remarks:After closing this file will automatically be deleted. ..remarks:The openmode (see @Function.open@) is $OPEN_RDWR | OPEN_CREATE$. ..returns:A $bool$ which is $true$ on success. */ template < typename TSpec > inline bool openTemp(File &me) { return me.openTemp(); } template < typename TSpec > inline bool openTemp(File &me, int openMode) { return me.openTemp(openMode); } template < typename File > inline void reopen(File &, int) { } /** .Function.close: ..cat:Input/Output ..summary:Closes a file. ..signature:close(file) ..param.file:A File object. ...type:Class.File ..returns:A $bool$ which is $true$ on success. */ template < typename TSpec > inline bool close(File & me) { return me.close(); } template < typename TSpec > inline unsigned sectorSize(File const & /*me*/) { return 4096; } ////////////////////////////////////////////////////////////////////////////// // generic read(At)/write(At) interface /** .Function.read: ..cat:Input/Output ..summary:Loads records from a file. ..signature:read(file, memPtr, count) ..param.file:A File object. ...type:Class.File ..param.memPtr:A pointer to the first destination record in memory. ..param.count:The amount of records to be read. ..returns:A $bool$ which is $true$ on success. ..remarks:The records are read from the position pointed by the current file pointer (see @Function.seek@). */ template < typename TSpec, typename TValue, typename TSize > inline bool read(File & me, TValue *memPtr, TSize const count) { return me.read(memPtr, count * sizeof(TValue)); } /** .Function.write: ..cat:Input/Output ..summary:Saves records to a file. ..signature:write(file, memPtr, count) ..param.file:A File object. ...type:Class.File ..param.memPtr:A pointer to the first source record in memory. ..param.count:The amount of records to be written. ..returns:A $bool$ which is $true$ on success. ..remarks:The records are written at the position pointed by the current file pointer (see @Function.seek@). */ template < typename TSpec, typename TValue, typename TSize > inline bool write(File & me, TValue const *memPtr, TSize const count) { return me.write(memPtr, count * sizeof(TValue)); } /** .Function.readAt: ..summary:Loads records from a specific position in a file. ..cat:Input/Output ..signature:readAt(file, memPtr, count, fileOfs) ..param.file:A File object. ...type:Class.File ..param.memPtr:A pointer to the first destination record in memory. ..param.count:The amount of records to be read. ..param.fileOfs:The absolute file position in bytes measured from the beginning. ..returns:A $bool$ which is $true$ on success. */ template < typename TFile, typename TValue, typename TSize, typename TPos > inline bool readAt(TFile & me, TValue *memPtr, TSize const count, TPos const fileOfs) { typedef typename Position::Type pos_t; seek(me, (pos_t)fileOfs * (pos_t)sizeof(TValue)); return read(me, memPtr, count); } /** .Function.writeAt: ..summary:Saves records to a specific position in a file. ..cat:Input/Output ..signature:writeAt(file, memPtr, count, fileOfs) ..param.file:A File object. ...type:Class.File ..param.memPtr:A pointer to the first source record in memory. ..param.count:The amount of records to be written. ..param.fileOfs:The absolute file position in bytes measured from the beginning. ..returns:A $bool$ which is $true$ on success. */ template < typename TFile, typename TValue, typename TSize, typename TPos > inline bool writeAt(TFile & me, TValue const *memPtr, TSize const count, TPos const fileOfs) { typedef typename Position::Type pos_t; seek(me, (pos_t)fileOfs * (pos_t)sizeof(TValue)); return write(me, memPtr, count); } ////////////////////////////////////////////////////////////////////////////// // generic seek/tell/size/resize interface /** .Function.seek: ..summary:Changes the current file pointer. ..cat:Input/Output ..signature:seek(file, fileOfs[, origin]) ..param.file:A File object. ...type:Class.File ..param.fileOfs:A file offset measured in bytes relative to $origin$. ..param.origin:Selects the origin from where to calculate the new position. ...default:$SEEK_BEGIN$ ...remarks:For $SEEK_BEGIN$, $SEEK_CURRENT$, or $SEEK_END$ the origin is the beginning, the current pointer, or the end of the file. ..returns:The new file position measured in bytes from the beginning. */ template < typename TSpec, typename TPos > inline typename Position< File >::Type seek(File &me, TPos const fileOfs, int origin) { typedef typename Position< File >::Type TFilePos; TFilePos newOfs = me.seek(fileOfs, origin); #ifdef SEQAN_DEBUG_OR_TEST_ if (origin == SEEK_BEGIN && newOfs != (TFilePos)fileOfs) { ::std::cerr << "seek returned " << ::std::hex << newOfs << " instead of " << fileOfs << ::std::dec << ::std::endl; } #endif return newOfs; } template < typename TSpec, typename TPos > inline typename Position< File >::Type seek(File &me, TPos const fileOfs) { return seek(me, fileOfs, SEEK_BEGIN); } /** .Function.tell: ..summary:Gets the current file pointer. ..cat:Input/Output ..signature:tell(file) ..param.file:A File object. ...type:Class.File ..returns:The current file position measured in bytes from the beginning. */ template < typename TSpec > inline typename Position< File >::Type tell(File &me) { return me.tell(); } /** .Function.rewind: ..summary:Sets the current file pointer to the beginning. ..cat:Input/Output ..signature:rewind(file) ..param.file:A File object. ...type:Class.File ..remarks:Calls @Function.seek@$(file, 0)$ by default. */ template < typename File > inline void rewind(File &me) { seek(me, 0); } /** .Function.size: ..summary:Gets the file size. ..cat:Input/Output ..signature:size(file) ..param.file:A File object. ...type:Class.File ..returns:The file size measured in bytes. */ template < typename TSpec > inline typename Size >::Type size(File &me) { typename Size >::Type old_pos = tell(me); typename Size >::Type result = seek(me, 0, SEEK_END); seek(me, old_pos, SEEK_BEGIN); return result; } /** .Function.resize: ..cat:Input/Output ..signature:resize(file, new_length) ..param.file:A File object. ...type:Class.File ..param.new_length:The new file size measured in bytes. */ template < typename TSpec, typename TSize > inline void resize(File &me, TSize new_length) { typename Size >::Type old_pos = tell(me); seek(me, new_length, SEEK_BEGIN); setEOF(me); seek(me, old_pos, SEEK_BEGIN); } /** .Function.setEOF: ..summary:Sets the file end to the current pointer. ..cat:Input/Output ..signature:setEOF(file) ..param.file:A File object. ...type:Class.File */ template < typename TSpec > inline bool setEOF(File &/*me*/) { return true; } ////////////////////////////////////////////////////////////////////// // Pseudo asynchronous Methods ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// // callback based read/write /* template < typename File, typename TValue, typename TSize, typename aCallback, typename aHint > inline typename aRequest::Type aread(File & me, TValue *memPtr, TSize const count, aCallback* cb, aHint* hint) { result = read(me, memPtr, count); cb(hint); return NULL; } template < typename File, typename TValue, typename TSize, typename aCallback, typename aHint > inline typename aRequest::Type awrite(File & me, TValue const *memPtr, TSize const count, aCallback* cb, aHint* hint) { write(me, memPtr, count); cb(hint); return NULL; } template < typename File, typename TValue, typename TSize, typename TPos, typename aCallback, typename aHint > inline typename aRequest::Type areadAt(File & me, TValue *memPtr, TSize const count, TPos const fileOfs, aCallback* cb, aHint* hint) { readAt(me, memPtr, count, fileOfs); cb(hint); return NULL; } template < typename File, typename TValue, typename TSize, typename TPos, typename aCallback, typename aHint > inline typename aRequest::Type awriteAt(File & me, TValue const *memPtr, TSize const count, TPos const fileOfs, aCallback* cb, aHint* hint) { result = writeAt(me, memPtr, count, fileOfs); cb(hint); return NULL; } ////////////////////////////////////////////////////////////////////// // event based read/write template < typename File, typename TValue, typename TSize, typename aEvent > inline typename aRequest::Type aread(File & me, TValue *memPtr, TSize const count, aEvent &event) { read(me, memPtr, count); event.signal(); return NULL; } template < typename File, typename TValue, typename TSize, typename aEvent > inline typename aRequest::Type awrite(File & me, TValue const *memPtr, TSize const count, aEvent &event) { write(me, memPtr, count); event.signal(); return NULL; } template < typename File, typename TValue, typename TSize, typename TPos, typename aEvent > inline typename aRequest::Type areadAt(File & me, TValue *memPtr, TSize const count, TPos const fileOfs, aEvent &event) { readAt(me, memPtr, count, fileOfs); event.signal(); return NULL; } template < typename File, typename TValue, typename TSize, typename TPos, typename aEvent > inline typename aRequest::Type awriteAt(File & me, TValue const *memPtr, TSize const count, TPos const fileOfs, aEvent &event) { writeAt(me, memPtr, count, fileOfs); event.signal(); return NULL; } */ ////////////////////////////////////////////////////////////////////// // queue-less request based pseudo asychronous read/write /** .Function.areadAt: ..summary:Asynchronously loads records from a specific position in a file. ..cat:Input/Output ..signature:areadAt(file, memPtr, count, fileOfs, request) ..param.file:A File object. ...type:Class.File ..param.memPtr:A pointer to the first destination record in memory. ..param.count:The amount of records to be read. ..param.fileOfs:The absolute file position in bytes measured from the beginning. ..param.request:Reference to a structure that will be associated with this asynchronous request. ...type:Class.aRequest ..returns:A $bool$ which is $true$ on success. */ template < typename File, typename TValue, typename TSize, typename TPos, typename aRequest > inline bool areadAt(File & me, TValue *memPtr, TSize const count, TPos const fileOfs, aRequest &request) { return readAt(me, memPtr, count, fileOfs); } /** .Function.awriteAt: ..summary:Asynchronously saves records to a specific position in a file. ..cat:Input/Output ..signature:awriteAt(file, memPtr, count, fileOfs, request) ..param.file:A File object. ...type:Class.File ..param.memPtr:A pointer to the first source record in memory. ..param.count:The amount of records to be written. ..param.fileOfs:The absolute file position in bytes measured from the beginning. ..param.request:Reference to a structure that will be associated with this asynchronous request. ...type:Class.aRequest ..returns:A $bool$ which is $true$ on success. */ template < typename File, typename TValue, typename TSize, typename TPos, typename aRequest > inline bool awriteAt(File & me, TValue const *memPtr, TSize const count, TPos const fileOfs, aRequest &request) { return writeAt(me, memPtr, count, fileOfs); } ////////////////////////////////////////////////////////////////////// // pseudo queue specific functions /** .Function.flush: ..summary:Waits for all open requests to complete. ..cat:Input/Output ..signature:flush(file) ..param.file:A File object. ...type:Class.File ..remarks:$flush$ returns after all pending requests are completed. */ template < typename TSpec > inline void flush(File &) { } /** .Function.waitFor: ..summary:Waits for an asynchronous request to complete. ..cat:Input/Output ..signature:waitFor(request[, timeout_millis]) ..param.request:Reference to an aRequest object. ...type:Class.aRequest ..param.timeout_millis:Timout value in milliseconds. ...remarks:A value of 0 can be used to test for completion without waiting. ...default:Infinity. ..returns:A $bool$ which is $true$ on completion and $false$ on timeout. ..remarks:$waitFor$ suspends the calling process until $request$ is completed or after $timeout_millis$ milliseconds. */ inline bool waitFor(aDummyRequest &) { return true; } template < typename TTime > inline bool waitFor(aDummyRequest &, TTime) { return true; } // deprecated template < typename TSpec, typename aRequest > inline void release(File &, aRequest &) { } /** .Function.cancel: ..summary:Cancels an asynchronous request. ..cat:Input/Output ..signature:cancel(file, request) ..param.file:A File object. ...type:Class.File ..param.request:Reference to an aRequest object. ...type:Class.aRequest ..returns:A $bool$ which is $true$ on success. */ template < typename TSpec, typename aRequest > inline bool cancel(File &, aRequest &) { return true; } // little helpers template inline T1 enclosingBlocks(T1 _size, T2 _blockSize) { return (_size + _blockSize - 1) / _blockSize; } template inline T1 alignSize(T1 _size, T2 _aligning) { if (_size < _aligning) return _aligning; else return (_size / _aligning) * (T1)_aligning; } } #endif ugene-1.9.8/src/plugins_3rdparty/bowtie/src/bowtie/SeqAn-1.1/seqan/file/file_array.h0000644000175000017500000003205511651544326026617 0ustar ilyailya /*========================================================================== SeqAn - The Library for Sequence Analysis http://www.seqan.de ============================================================================ Copyright (C) 2007 This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. ============================================================================ $Id: file_array.h,v 1.1 2008/08/25 16:20:03 langmead Exp $ ==========================================================================*/ #ifndef SEQAN_HEADER_FILE_ARRAY_H #define SEQAN_HEADER_FILE_ARRAY_H #include #include ////////////////////////////////////////////////////////////////////////////// namespace SEQAN_NAMESPACE_MAIN { //template < __int64 _FileSize = 2*1024*1024*1024-1, typename TFile = File<> > //struct Chained; //template < unsigned _FileCount = 2, typename TFile = File<> > //struct Striped; template < __int64 _FileSize, typename TFile > struct Size< File< Chained<_FileSize, TFile> > > { typedef __int64 Type; }; template < __int64 _FileSize, typename TFile > struct Position< File< Chained<_FileSize, TFile> > > { typedef __int64 Type; }; template < __int64 _FileSize, typename TFile > struct Difference< File< Chained<_FileSize, TFile> > > { typedef __int64 Type; }; template < __int64 _FileSize, typename TFile > struct aRequest< File< Chained<_FileSize, TFile> > > { typedef typename aRequest::Type Type; }; template < unsigned _FileCount, typename TFile > struct Size< File< Striped<_FileCount, TFile> > > { typedef __int64 Type; }; template < unsigned _FileCount, typename TFile > struct Position< File< Striped<_FileCount, TFile> > > { typedef __int64 Type; }; template < unsigned _FileCount, typename TFile > struct Difference< File< Striped<_FileCount, TFile> > > { typedef __int64 Type; }; template < unsigned _FileCount, typename TFile > struct aRequest< File< Striped<_FileCount, TFile> > > { typedef typename aRequest::Type Type; }; template < unsigned _FileCount, typename TFile > class File< Striped<_FileCount, TFile> >: public Tuple< TFile, _FileCount > { File(void *dummy = NULL) {} // to be compatible with the FILE*(NULL) constructor operator bool() const { return (*this)[0]; } }; template < __int64 _FileSize, typename TFile > class File< Chained<_FileSize, TFile> >: public String< TFile > { typedef String< TFile > Base; ::std::string baseName; int openMode; __int64 fileSize; bool temporary; File(void *dummy = NULL) : // to be compatible with the FILE*(NULL) constructor fileSize(0), _realign(false) {} private: bool _realign; template < typename TSize, typename TValue > inline void _alignFloor(TSize _size, TValue const *) { __int64 alignment = sizeof(TValue) * sectorSize(TFile()); fileSize = (_size / alignment) * alignment; } template < typename TSize, typename TValue > inline void _alignCeil(TSize _size, TValue const *) { __int64 alignment = sizeof(TValue) * sectorSize(TFile()); fileSize = ((_size + alignment - 1) / alignment) * alignment; } public: inline ::std::string getFileName(int i) const { ::std::stringstream strm; strm << baseName << '.' << ::std::setfill('0') << ::std::setw(3) << i; return strm.str(); } inline operator bool() const { return (*this)[0]; } inline unsigned fileCount() const { return length(*(Base*)this); } inline TFile& getFile(int fileNo) { unsigned _oldFileCount = fileCount(); if (fileNo >= _oldFileCount) { resize(*(Base*)this, fileNo + 1); for(unsigned i = _oldFileCount; i <= fileNo; ++i) if (temporary) openTemp((*this)[i], openMode); else open((*this)[i], getFileName(i).c_str(), openMode); } return (*this)[fileNo]; } inline void tryOpen() { unsigned fileCount = 0; while (fileExists(getFileName(fileCount).c_str())) ++fileCount; if (fileCount) { fileSize = size(getFile(0)); _realign = (fileCount == 1); getFile(fileCount - 1); } } // fileSize dependent functions template < typename TValue > inline void adjustFileSize(TValue const *dummy) { if (_realign) { _alignCeil(fileSize, dummy); _realign = false; if (fileSize < _FileSize) fileSize = 0; } if (!fileSize) _alignFloor(_FileSize, dummy); } template < typename TPos, typename TOffset, typename TValue > inline TFile& getFileAndOffset(TPos offset, TOffset &fileOffset, TValue const *dummy) { adjustFileSize(dummy); offset *= sizeof(TValue); fileOffset = (offset % fileSize) / sizeof(TValue); return getFile(offset / fileSize); } template < typename TOffset, typename TValue > inline __int64 restAt(TOffset fileOffset, TValue const *dummy) { adjustFileSize(dummy); __int64 restBytes = fileSize; restBytes -= fileOffset * sizeof(TValue); return restBytes / sizeof(TValue); } inline void resizeArray(__int64 _newSize) { if (fileSize) { unsigned _oldFileCount = fileCount(); unsigned _newFileCount = enclosingBlocks(_newSize, fileSize); for(unsigned i = _newFileCount; i < _oldFileCount; ++i) { close((*this)[i]); if (!temporary) fileUnlink(getFileName(i).c_str()); } resize(*(Base*)this, _newFileCount); if (_newFileCount) { typename Size::Type lastFileSize = _newSize % fileSize; if (fileSize) resize((*this)[_newFileCount - 1], lastFileSize); } } } inline void clearInternals() { clear(*(Base*)this); fileSize = 0; _realign = false; } }; ////////////////////////////////////////////////////////////////////////////// // generic open/close interface template < typename TFileArray > inline bool _openTempFArray(TFileArray &me, int openMode) { bool result = true; for(int i = 0; i < length(me); ++i) result &= openTemp(me[i], openMode); return result; } template < typename TFileArray > inline bool _openTempFArray(TFileArray &me) { return _openTempFArray(me, DefaultOpenTempMode::VALUE); } template < typename TFileArray > inline bool _reopenFArray(TFileArray &me, int openMode) { bool result = true; for(int i = 0; i < length(me); ++i) result &= reopen(me[i], openMode); return result; } template < typename TFileArray > inline bool _closeFArray(TFileArray &me) { bool result = true; for(int i = 0; i < length(me); ++i) if (me[i]) result &= close(me[i]); return result; } template < typename TFileArray > inline unsigned _sectorSizeFArray(TFileArray &me, int openMode) { return sectorSize(me[0]); } template < typename TFileArray > inline typename Size::Type _sizeFArray(TFileArray &me) { typename Size::Type sum = 0; for(int i = 0; i < length(me); ++i) sum += size(me[i]); return sum; } template < typename TFileArray > inline bool _flushFArray(TFileArray &me) { bool result = true; for(int i = 0; i < length(me); ++i) result &= flush(me[i]); return result; } template < typename TFileArray, typename TRequest > inline bool _cancelFArray(TFileArray &me, TRequest &request) { bool result = true; for(int i = 0; i < length(me); ++i) result &= cancel(me[i], &request); return result; } ////////////////////////////////////////////////////////////////////////////// // standard file array wrappers template < __int64 _FileSize, typename TFile > inline unsigned length(File< Chained<_FileSize, TFile> > const &me) { return me.fileCount(); } template < unsigned _FileCount, typename TFile > inline unsigned length(File< Striped<_FileCount, TFile> > const &me) { return _FileCount; } template < __int64 _FileSize, typename TFile > inline bool open(File< Chained<_FileSize, TFile> > &me, const char *fileName, int openMode) { me.baseName = fileName; me.openMode = openMode; me.temporary = false; me.tryOpen(); return true; } template < __int64 _FileSize, typename TFile > inline bool openTemp(File< Chained<_FileSize, TFile> > &me, int openMode) { me.openMode = openMode; me.temporary = true; return true; } template < unsigned _FileCount, typename TFile > inline bool openTemp(File< Striped<_FileCount, TFile> > &me, int openMode) { return _openTempFArray(me, openMode); } template < __int64 _FileSize, typename TFile > inline bool close(File< Chained<_FileSize, TFile> > &me) { _closeFArray(me); me.clearInternals(); return true; } template < unsigned _FileCount, typename TFile > inline bool close(File< Striped<_FileCount, TFile> > &me) { return _closeFArray(me); } template < __int64 _FileSize, typename TFile > __int64 size(File< Chained<_FileSize, TFile> > &me) { return _sizeFArray(me); } template < unsigned _FileCount, typename TFile > __int64 size(File< Striped<_FileCount, TFile> > &me) { return _sizeFArray(me); } template < __int64 _FileSize, typename TFile, typename TSize > inline void resize(File< Chained<_FileSize, TFile> > &me, TSize new_length) { me.resizeArray(new_length); } template < __int64 _FileSize, typename TFile, typename TValue, typename TSize > inline void allocate(File< Chained<_FileSize, TFile> > const &me, TValue* &data, TSize count) { allocate(me[0], data, count); } template < __int64 _FileSize, typename TFile, typename TValue, typename TSize > inline void deallocate(File< Chained<_FileSize, TFile> > const &me, TValue* &data, TSize count) { deallocate(me[0], data, count); } template < unsigned _FileCount, typename TFile, typename TValue, typename TSize > inline void allocate(File< Striped<_FileCount, TFile> > const &me, TValue* &data, TSize count) { allocate(me[0], data, count); } template < unsigned _FileCount, typename TFile, typename TValue, typename TSize > inline void deallocate(File< Striped<_FileCount, TFile> > const &me, TValue* &data, TSize count) { deallocate(me[0], data, count); } ////////////////////////////////////////////////////////////////////////////// // read/write wrappers template < __int64 _FileSize, typename TFile, typename TValue, typename TSize, typename TOffset > inline bool readAt(File< Chained<_FileSize, TFile> > &me, TValue *memPtr, TSize count, TOffset offset) { TOffset fileOfs = 0; while (count) { TFile &file = me.getFileAndOffset(offset, fileOfs, memPtr); TSize xmitSize = _min(me.restAt(fileOfs, memPtr), (__int64)count); if (!readAt(file, memPtr, xmitSize, fileOfs)) return false; count -= xmitSize; offset += xmitSize; memPtr += xmitSize; } return true; } template < __int64 _FileSize, typename TFile, typename TValue, typename TSize, typename TOffset > inline bool writeAt(File< Chained<_FileSize, TFile> > &me, TValue const *memPtr, TSize count, TOffset offset) { TOffset fileOfs = 0; while (count) { TFile &file = me.getFileAndOffset(offset, fileOfs, memPtr); TSize xmitSize = _min(me.restAt(fileOfs, memPtr), (__int64)count); if (!writeAt(file, memPtr, xmitSize, fileOfs)) return false; count -= xmitSize; offset += xmitSize; memPtr += xmitSize; } return true; } template < __int64 _FileSize, typename TFile, typename TValue, typename TSize, typename TOffset, typename TRequest > inline bool areadAt(File< Chained<_FileSize, TFile> > &me, TValue *memPtr, TSize count, TOffset offset, TRequest &req) { TOffset fileOfs = 0; while (count) { TFile &file = me.getFileAndOffset(offset, fileOfs, memPtr); TSize xmitSize = _min(me.restAt(fileOfs, memPtr), (__int64)count); if (count != xmitSize) { if (!readAt(file, memPtr, xmitSize, fileOfs)) return false; } else if (!areadAt(file, memPtr, xmitSize, fileOfs, req)) return false; count -= xmitSize; offset += xmitSize; memPtr += xmitSize; } return true; } template < __int64 _FileSize, typename TFile, typename TValue, typename TSize, typename TOffset, typename TRequest > inline bool awriteAt(File< Chained<_FileSize, TFile> > &me, TValue const *memPtr, TSize count, TOffset offset, TRequest &req) { TOffset fileOfs = 0; while (count) { TFile &file = me.getFileAndOffset(offset, fileOfs, memPtr); TSize xmitSize = _min(me.restAt(fileOfs, memPtr), (__int64)count); if (count != xmitSize) { if (!writeAt(file, memPtr, xmitSize, fileOfs)) return false; } else if (!awriteAt(file, memPtr, xmitSize, fileOfs, req)) return false; count -= xmitSize; offset += xmitSize; memPtr += xmitSize; } return true; } } #endif ugene-1.9.8/src/plugins_3rdparty/bowtie/src/bowtie/SeqAn-1.1/seqan/file/file_format_fasta.h0000644000175000017500000002612411651544326030147 0ustar ilyailya /*========================================================================== SeqAn - The Library for Sequence Analysis http://www.seqan.de ============================================================================ Copyright (C) 2007 This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. ============================================================================ $Id: file_format_fasta.h,v 1.1 2008/08/25 16:20:03 langmead Exp $ ==========================================================================*/ #ifndef SEQAN_HEADER_FILE_FASTA_H #define SEQAN_HEADER_FILE_FASTA_H namespace SEQAN_NAMESPACE_MAIN { ////////////////////////////////////////////////////////////////////////////// // File Formats - Fasta ////////////////////////////////////////////////////////////////////////////// /** .Tag.File Format.tag.Fasta: FASTA file format for sequences. */ struct TagFasta_; typedef Tag const Fasta; ////////////////////////////////////////////////////////////////////////////// // Filereader ////////////////////////////////////////////////////////////////////////////// template inline void goBegin(Iter > & it, bool skip_meta) { if (_streamEOF(host(it))) { it.data_eof = true; return; } if (skip_meta && (it.data_char == '>')) { //skip meta line _stream_skipLine(host(it), it.data_char); } //eliminate linebreaks while ((it.data_char == '\n') || (it.data_char == '\r')) { if (_streamEOF(host(it))) { it.data_eof = true; return; } it.data_char = _streamGet(host(it)); } if (it.data_char == '>') {//end of record it.data_eof = true; _streamUnget(host(it)); return; } it.data_file_pos = _streamTellG(host(it)) - 1; it.data_eof = _streamEOF(host(it)); } template inline void goBegin(Iter > & it) { goBegin(it, true); } template inline void goNext(Iter > & it) { /* if (_streamEOF(host(it))) { it.data_eof = true; return; } */ it.data_char = _streamGet(host(it)); ++it.data_file_pos; if (_streamEOF(host(it))) { it.data_eof = true; return; } if ((it.data_char == '\n') || (it.data_char == '\r')) {//linebreak detected: find begin of next line do { it.data_char = _streamGet(host(it)); if (_streamEOF(host(it))) { it.data_eof = true; return; } ++it.data_file_pos; } while ((it.data_char == '\n') || (it.data_char == '\r')); if (it.data_char == '>') {//end of record _streamUnget(host(it)); it.data_eof = true; } } } ////////////////////////////////////////////////////////////////////////////// // FileFormat Interface ////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////// //count_valid: zaehlt die nicht-Zeilenumbrueche (input/output) //count_all: zaehlt alle Zeichen incl. Zeilenumbrueche (input/output) //returns: zuletzt gelesenes Zeichen = das erste hinter dem Zeilenumbruch bzw. eof //the last read char is not counted! //count_valid and count_all are not resetted but counted up template inline typename Value::Type _fasta_scan_line(TFile & file, TSize & count_valid, TSize & count_all) { SEQAN_CHECKPOINT SEQAN_ASSERT(!_streamEOF(file)) TSize count = 0; while (true) { typename Value::Type c = _streamGet(file); if (_streamEOF(file)) { count_valid += count; count_all += count; return c; } if ((c == '\n') || (c == '\r')) { do { ++count_all; c = _streamGet(file); } while ((c == '\n') || (c == '\r')); count_valid += count; count_all += count; return c; } if (c != '\r') { ++count; } } } ///////////////////////////////////////////////////////////////////////// template inline void _read_n_chars_from_file(TFile & file, TSize count) { SEQAN_CHECKPOINT for (TSize i = 0; i < count; ++i) { _streamGet(file); } } ////////////////////////////////////////////////////////////////////////////// // read ////////////////////////////////////////////////////////////////////////////// template void read(TFile & file, TData & data, TSize limit, Fasta) { SEQAN_CHECKPOINT SEQAN_ASSERT(!_streamEOF(file)) clear(data); //determine begin position typename Value::Type c_first = _streamGet(file); SEQAN_ASSERT(!_streamEOF(file)) typename Position::Type begin_pos = _streamTellG(file); typename Size::Type count_valid = 1; //"valid" characters read (without line breaks) typename Size::Type count_all = 1; //all characters read (with line breaks) if (_streamEOF(file)) { return; } if (c_first == '>') {//there is an id line: skip it c_first = _fasta_scan_line(file, count_valid, count_all); } if ((c_first == '>') || _streamEOF(file)) {//another id line = empty entry _streamSeekG(file, begin_pos); _read_n_chars_from_file(file, count_all); return; } begin_pos = _streamTellG(file); count_valid = 1; count_all = 1; typename Value::Type c; bool eof_reached = false; //determine length while (true) { c = _fasta_scan_line(file, count_valid, count_all); if (_streamEOF(file)) {//end of file: stop searching eof_reached = true; break; } if (c == '>') {//next entry found: stop seaching break; } if ((c != '\n') && (c != '\r')) { ++count_valid; //count c } ++count_all; } //reserve space typename Size::Type count = count_valid; if (count > limit) { count = limit; } resize(data, count); if (length(data) < count) { count = length(data); } //read sequence _streamSeekG(file, begin_pos); typename Position::Type pos = 0; c = c_first; while (true) { if ((c != '\n') && (c != '\r')) { data[pos] = c; ++pos; } if (pos >= count) break; c = _streamGet(file); --count_all; } //move file ptr to next entry _read_n_chars_from_file(file, count_all - 1); if(eof_reached) _streamGet(file); } //____________________________________________________________________________ template void read(TFile & file, TData & data, Fasta tag) { SEQAN_CHECKPOINT typedef typename Size::Type TSize; read(file, data, supremumValue(), tag); } ////////////////////////////////////////////////////////////////////////////// // readID ////////////////////////////////////////////////////////////////////////////// //the ID is the complete first line (without the leading '>'-sign) template void readID(TFile & file, TString & id, Fasta) { SEQAN_CHECKPOINT SEQAN_ASSERT(!_streamEOF(file)) typename Position::Type start_pos = _streamTellG(file); typename Value::Type c = _streamGet(file); if (c != '>') { clear(id); } else { typename Size::Type count_valid = 0; typename Size::Type count_all = 0; _fasta_scan_line(file, count_valid, count_all); if (! count_valid) { clear(id); } else { resize(id, count_valid); if (length(id) < count_valid) { count_valid = length(id); } _streamSeekG(file, start_pos); c = _streamGet(file); //pop the '>' character for (typename Position::Type pos = 0; count_valid; --count_valid) { id[pos] = _streamGet(file); ++pos; } } } _streamSeekG(file, start_pos); } ////////////////////////////////////////////////////////////////////////////// // readMeta ////////////////////////////////////////////////////////////////////////////// //Fasta file records have no meta data template void readMeta(TFile & file, TMeta & meta, Fasta) { SEQAN_CHECKPOINT readID(file, meta, Fasta()); } ////////////////////////////////////////////////////////////////////////////// // goNext ////////////////////////////////////////////////////////////////////////////// template void goNext(TFile & file, Fasta) { SEQAN_CHECKPOINT SEQAN_ASSERT(!_streamEOF(file)) bool found_data = false; while (true) { typename Value::Type c = _streamGet(file); if (_streamEOF(file)) return; if (c == '\n' || c == '\r') { do { c = _streamGet(file); if (_streamEOF(file)) return; } while (c == '\n' || c == '\r'); if (c != '>') { found_data = true; } else if (found_data) { _streamUnget(file); return; } } } } ////////////////////////////////////////////////////////////////////////////// // write ////////////////////////////////////////////////////////////////////////////// template void _write_impl(TFile & file, TData & data, TString & id, Fasta) { SEQAN_CHECKPOINT _streamPut(file, '>'); _streamWrite(file, id); _streamPut(file, '\n'); //typename Iterator::Type it = begin(data, Standard()); //typename Iterator::Type it_end = end(data, Standard()); typename Iterator::Type it = begin(data); typename Iterator::Type it_end = end(data); int i = 0; for (; it < it_end; ++it) { if (i == 60) { _streamPut(file, '\n'); i = 0; } ++i; _streamPut(file, *it); } _streamPut(file, '\n'); } //____________________________________________________________________________ template void write(TFile & file, TData & data, Fasta) { SEQAN_CHECKPOINT _write_impl(file, data, "", Fasta()); } //____________________________________________________________________________ template void write(TFile & file, TData & data, TString & id, Fasta) { SEQAN_CHECKPOINT _write_impl(file, data, id, Fasta()); } //VisualC++ const array bug workaround template void write(TFile & file, TDataValue * data, TString & id, Fasta) { SEQAN_CHECKPOINT _write_impl(file, data, id, Fasta()); } //____________________________________________________________________________ template void write(TFile & file, TData & data, TString & id, TMeta &, Fasta) { SEQAN_CHECKPOINT _write_impl(file, data, id, Fasta()); } ////////////////////////////////////////////////////////////////////////////// } //namespace SEQAN_NAMESPACE_MAIN ////////////////////////////////////////////////////////////////////////////// #endif //#ifndef SEQAN_HEADER_... ugene-1.9.8/src/plugins_3rdparty/bowtie/src/bowtie/SeqAn-1.1/seqan/file/stream_algorithms.h0000644000175000017500000001266011651544326030226 0ustar ilyailya /*========================================================================== SeqAn - The Library for Sequence Analysis http://www.seqan.de ============================================================================ Copyright (C) 2007 This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. ============================================================================ $Id: stream_algorithms.h,v 1.1 2008/08/25 16:20:04 langmead Exp $ ==========================================================================*/ #ifndef SEQAN_HEADER_STREAM_ALGORITHMS_H #define SEQAN_HEADER_STREAM_ALGORITHMS_H namespace SEQAN_NAMESPACE_MAIN { ////////////////////////////////////////////////////////////////////////////// /** .Internal._streamPutInt: ..summary:Converts an integer to a character and writes it to stream. ..cat:Streams ..signature:_streamPutInt(stream, number [, format_string]) ..param.target:An output stream. ...type:Adaption."std::iostream" ..param.number:A number that is written to $stream$. */ template inline void _streamPutInt(TStream & target, int number, char const * format_string) { SEQAN_CHECKPOINT char str[BitsPerValue::VALUE]; sprintf(str, format_string, number); _streamWrite(target, str); } template inline void _streamPutInt(TStream & target, int number) { SEQAN_CHECKPOINT _streamPutInt(target, number, "%d"); } /** .Internal._streamPutFloat: ..summary:Converts a float to a character and writes it to stream. ..cat:Streams ..signature:_streamPutFloat(stream, number [, format_string]) ..param.target:An output stream. ...type:Adaption."std::iostream" ..param.number:A number that is written to $stream$. */ template inline void _streamPutFloat(TStream & target, float number, char const * format_string) { SEQAN_CHECKPOINT char str[BitsPerValue::VALUE]; sprintf(str, format_string, number); _streamWrite(target, str); } template inline void _streamPutFloat(TStream & target, float number) { SEQAN_CHECKPOINT _streamPutFloat(target, number, "%f"); } ////////////////////////////////////////////////////////////////////////////// template inline void _streamWrite(TTarget & target, Pair const & source) { SEQAN_CHECKPOINT _streamWrite(target, getValueI1(source)); _streamWrite(target, getValueI2(source)); } template inline void _streamWrite(TTarget & target, Triple const & source) { SEQAN_CHECKPOINT _streamWrite(target, getValueI1(source)); _streamWrite(target, getValueI2(source)); _streamWrite(target, getValueI3(source)); } ////////////////////////////////////////////////////////////////////////////// /** .Internal._streamWrite: ..summary:Writes a sequence to stream. ..cat:Streams ..signature:_streamWrite(stream, sequence) ..param.stream:An input stream. ..param.sequence:A sequence that is written to $stream$. */ template inline void _streamWrite(TTarget & target, TSource const & source) { SEQAN_CHECKPOINT _streamWriteSeq(target, source, typename IsSequence::Type()); } //____________________________________________________________________________ template inline void _streamWriteSeq(TTarget & target, TSource const & source, False const) { _streamPut(target, source); } //____________________________________________________________________________ template inline void _streamWriteSeq(TTarget & target, TSource const & source, True const) { SEQAN_CHECKPOINT typename Iterator::Type it = begin(source, Standard()); typename Iterator::Type it_end = end(source, Standard()); for (; it < it_end; ++it) { typename GetValue::Type val_ = getValue(it); _streamWrite(target, val_); } } template inline void _streamWriteSeq(TTarget & target, TSourceValue const * source, True const) { SEQAN_CHECKPOINT for (; !atEnd(source); ++source) { _streamWrite(target, *source); } } ////////////////////////////////////////////////////////////////////////////// /** .Internal._streamWriteRange: ..summary:Writes a range to stream. ..cat:Streams ..signature:_streamWriteRange(stream, begin_iterator, end_iterator) ..param.stream:An input stream. ..param.sequence:A sequence that is written to $stream$. */ template inline void _streamWriteRange(TTarget & target, TIterator begin_, TIterator end_) { SEQAN_CHECKPOINT for (; begin_ != end_; ++begin_) { _streamPut(target, *begin_); } } ////////////////////////////////////////////////////////////////////////////// } //namespace SEQAN_NAMESPACE_MAIN #endif //#ifndef SEQAN_HEADER_... ugene-1.9.8/src/plugins_3rdparty/bowtie/src/bowtie/SeqAn-1.1/seqan/file/file_format.h0000644000175000017500000004120511651544326026766 0ustar ilyailya /*========================================================================== SeqAn - The Library for Sequence Analysis http://www.seqan.de ============================================================================ Copyright (C) 2007 This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. ============================================================================ $Id: file_format.h,v 1.1 2008/08/25 16:20:03 langmead Exp $ ==========================================================================*/ #ifndef SEQAN_HEADER_FILE_FORMAT_H #define SEQAN_HEADER_FILE_FORMAT_H namespace SEQAN_NAMESPACE_MAIN { ////////////////////////////////////////////////////////////////////////////// /** .Tag.File Format: ..summary:A file format. */ ////////////////////////////////////////////////////////////////////////////// // Metafunctions ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// //Base Class for all FileFormat classes ////////////////////////////////////////////////////////////////////////////// /** .Class.FileFormat: ..cat:Input/Output ..summary:Object that stores a file format. ..signature:FileFormat ..see:Tag.File Format */ template < typename TFile, typename TData, typename TMeta, typename TFormat = void > struct FileFormat: public FileFormat { public: typedef typename Size::Type TSize; FileFormat() {} FileFormat(FileFormat const &) {} ~FileFormat() {} FileFormat const & operator =(FileFormat const &) {} inline void * formatID_() const { SEQAN_CHECKPOINT return _ClassIdentifier::getID(); } virtual void read_(TFile & file, TData & data) const { SEQAN_CHECKPOINT read(file, data, TFormat()); } virtual void read_(TFile & file, TData & data, TSize limit) const { SEQAN_CHECKPOINT read(file, data, limit, TFormat()); } virtual void readMeta_(TFile & file, TMeta & meta) const { SEQAN_CHECKPOINT readMeta(file, meta, TFormat()); } virtual void goNext_(TFile & file) const { SEQAN_CHECKPOINT goNext(file, TFormat()); } virtual TSize length_(TFile & file) const { SEQAN_CHECKPOINT length(file, TFormat()); } virtual void write_(TFile & file, TData & data) const { SEQAN_CHECKPOINT write(file, data, TFormat()); } virtual void write_(TFile & file, TData & data, TMeta & meta) const { SEQAN_CHECKPOINT write(file, data, meta, TFormat()); } }; //____________________________________________________________________________ //base class for all file format classes template struct FileFormat { public: typedef typename Size::Type TSize; FileFormat() {} FileFormat(FileFormat const &) {} ~FileFormat() {}; FileFormat const & operator =(FileFormat const &) {} virtual void * formatID_() const = 0; virtual void read_(TFile & file, TData & data) const = 0; virtual void read_(TFile & file, TData & data, TSize limit) const = 0; virtual void readMeta_(TFile & file, TMeta & meta) const = 0; virtual void goNext_(TFile & file) const = 0; virtual TSize length_(TFile & file) const = 0; virtual void write_(TFile & file, TData & data) const = 0; virtual void write_(TFile & file, TData & data, TMeta & meta) const = 0; }; ////////////////////////////////////////////////////////////////////////////// // Wrapper for functions to virtuals ////////////////////////////////////////////////////////////////////////////// template inline void * formatID(FileFormat const & file_format) { SEQAN_CHECKPOINT return file_format.formatID_(); } ////////////////////////////////////////////////////////////////////////////// /** .Function.Fileformat#read: ..cat:Input/Output ..summary:Loads a record from file. ..signature:read(file, data [, meta], format) ..signature:read(file, data [, meta], tag) ..param.file:An input file. ..param.data:A container that gets the data read from $file$. ..param.meta:A container that gets meta data from $file$. (optional) ..param.format:A file format object. ...type:Class.FileFormat.File Format object ..param.tag:A file format tag. ...type:Tag.File Format.File Format tag ..remarks:The result of this operation is stored in $data$. ..remarks:The function leaves $file$ at the position for reading the next record. ..see:Function.assign */ template inline void read(TFile & file, TData & data, FileFormat const & file_format) { SEQAN_CHECKPOINT file_format.read_(file, data); } template inline void read(TFile & file, TData & data, TSize limit, FileFormat const & file_format) { SEQAN_CHECKPOINT file_format.read_(file, data, limit); } ////////////////////////////////////////////////////////////////////////////// /** .Function.readMeta: ..cat:Input/Output ..summary:Read meta information from file. ..signature:readMeta(file, meta, file_format) ..param.file:A file that contains data in the format specified by $file_format$. ..param.meta:A data structure that is able to store meta informations stored in $file$. ..param.file_format:A file format. ..returns.param.meta:The meta data read from $file$. ...type:Tag.File Format */ template inline void readMeta(TFile & file, TMeta & meta, FileFormat const & file_format) { SEQAN_CHECKPOINT file_format.readMeta_(file, meta); } ////////////////////////////////////////////////////////////////////////////// /** .Function.goNext: ..cat:Input/Output */ template inline void goNext(TFile & file, FileFormat const & file_format) { SEQAN_CHECKPOINT file_format.goNext_(file); } ////////////////////////////////////////////////////////////////////////////// /** .Function.length: ..cat:Input/Output */ template inline void length(TFile & file, FileFormat const & file_format) { SEQAN_CHECKPOINT file_format.length_(file); } ////////////////////////////////////////////////////////////////////////////// /** .Function.Fileformat#write: ..cat:Input/Output ..summary:Writes to stream. ..signature:write(stream, source) ..signature:write(stream, begin, end) ..param.stream: A stream object. ...type:Adaption."std::iostream" ..param.source: Container that is written to $stream$. ..param.begin: Iterator to the first character of the range. ..param.end: Iterator behind the last character of the range. ..remarks:The content of $source$ is written 'as-is' to $stream$. */ template inline void write(TFile & file, TData & data, FileFormat const & file_format) { SEQAN_CHECKPOINT file_format.write_(file, data); } template inline void write(TFile & file, TData & data, TMeta & meta, FileFormat const & file_format) { SEQAN_CHECKPOINT file_format.write_(file, data, meta); } ////////////////////////////////////////////////////////////////////////////// // Comparison of two FileFormat objects ////////////////////////////////////////////////////////////////////////////// template inline bool operator == (FileFormat const & left, FileFormat const & right) { SEQAN_CHECKPOINT return formatID(left) == formatID(right); } template inline bool operator == (FileFormat const & left, Tag const) { SEQAN_CHECKPOINT return formatID(left) == _ClassIdentifier const>::getID(); } template inline bool operator == (Tag const, FileFormat const & right) { SEQAN_CHECKPOINT return _ClassIdentifier const>::getID() == formatID(right); } //____________________________________________________________________________ template inline bool operator != (FileFormat const & left, FileFormat const & right) { SEQAN_CHECKPOINT return formatID(left) != formatID(right); } template inline bool operator != (FileFormat const & left, Tag const) { SEQAN_CHECKPOINT return formatID(left) != _ClassIdentifier const>::getID(); } template inline bool operator != (Tag const, FileFormat const & right) { SEQAN_CHECKPOINT return _ClassIdentifier const>::getID() != formatID(right); } ////////////////////////////////////////////////////////////////////////////// // allgemeine Funktionen fuer Streams ////////////////////////////////////////////////////////////////////////////// //TODO??? Das muss in eine extra Datei /* template inline void write(TStream & target, TIterator begin_, TIterator end_) { while (begin_ != end_) { _streamPut(target, convert(*begin_)); ++begin_; } } //____________________________________________________________________________ template inline void write(TStream & target, TSource const & source) { write(target, begin(source), end(source)); } //TODO???: Spezialisierungen zum blockweise schreiben bei contiguous strings von char //Anmerkungen: write wird nach dem zweiten Argument (source) spezialisiert! //____________________________________________________________________________ template inline void write(TStream & target, TSource const & source, typename Size::Type limit_) { if (length(source) > limit_) { write(target, begin(source), begin(source) + limit_); } else { write(target, begin(source), end(source)); } } */ ////////////////////////////////////////////////////////////////////////////// // Helper function for scanning a stream // c = next character, pass it to the next call of the function template inline void _stream_appendLine(TFile & file, TString & str, TChar & c) { while (true) { if (_streamEOF(file)) break; if (c == '\r') { c = _streamGet(file); if (c == '\n') { c = _streamGet(file); } break; } if (c == '\n') { c = _streamGet(file); break; } appendValue(str, c); c = _streamGet(file); } } //____________________________________________________________________________ template inline void _stream_countLine(TFile & file, TChar & c) { while (true) { if (_streamEOF(file)) break; if (c == '\r') { c = _streamGet(file); if (c == '\n') { c = _streamGet(file); } break; } if (c == '\n') { c = _streamGet(file); break; } c = _streamGet(file); } } //____________________________________________________________________________ template inline typename Size::Type _stream_skipLine(TFile & file, TChar & c) { typename Size::Type count = 0; while (true) { if (_streamEOF(file)) break; if (c == '\r') { c = _streamGet(file); if (c == '\n') { c = _streamGet(file); } break; } if (c == '\n') { c = _streamGet(file); break; } ++count; c = _streamGet(file); } return count; } //////////////////////////////////////////////////////////////////////////// //new ones //new ones for streams template inline void _stream_skipWhitespace(TFile& file, TChar& c) { if ((c!=' ') && (c != '\t')) return; while (!_streamEOF(file)) { c = _streamGet(file); if ((c!=' ') && (c != '\t')) break; } } //////////////////////////////////////////////////////////////////////////// template inline String _stream_readWord(TFile & file, TChar& c) { // Read word String str(c); while (!_streamEOF(file)) { c = _streamGet(file); if (!_stream_isLetter(c)) break; append(str, c); } return str; } //////////////////////////////////////////////////////////////////////////// template inline bool _stream_isLetter(TChar const c) { return ((c == 'a') || (c == 'b') || (c == 'c') || (c == 'd') || (c == 'e') || (c == 'f') || (c == 'g') || (c == 'h') || (c == 'i') || (c == 'j') || (c == 'k') || (c == 'l') || (c == 'm') || (c == 'n') || (c == 'o') || (c == 'p') || (c == 'q') || (c == 'r') || (c == 's') || (c == 't') || (c == 'u') || (c == 'v') || (c == 'w') || (c == 'x') || (c == 'y') || (c == 'z') || (c == 'A') || (c == 'B') || (c == 'C') || (c == 'D') || (c == 'E') || (c == 'F') || (c == 'G') || (c == 'H') || (c == 'I') || (c == 'J') || (c == 'K') || (c == 'L') || (c == 'M') || (c == 'N') || (c == 'O') || (c == 'P') || (c == 'Q') || (c == 'R') || (c == 'S') || (c == 'T') || (c == 'U') || (c == 'V') || (c == 'W') || (c == 'X') || (c == 'Y') || (c == 'Z')); } ////////////////////////////////////////////////////////////////////////////// //new ones for strings template inline typename Size::Type _string_skipLine(TString & str, TIter & it) { typename Size::Type count = 0; typename Iterator::Type end_it = end(str,Standard()); while (true) { if (it == end_it) break; if (*it == '\r') { ++it; if (*it == '\n') { ++it; } break; } if (*it == '\n') { ++it; break; } ++count; ++it; } return count; } ///////////////////////////////////////////////////////////////////////// template inline void _string_appendLine(TString1 & str, TString2 & a_str, TIter & it) { typename Iterator::Type end_it = end(str,Standard()); while (true) { if (it == end_it) break; if (*it == '\r') { ++it; if (*it == '\n') { ++it; } break; } if (*it == '\n') { ++it; break; } appendValue(a_str, getValue(it)); ++it; } } //////////////////////////////////////////////////////////////////////////// template inline void _string_skipWhitespace(TString& str, TIter& it) { typename Iterator::Type end_it = end(str,Standard())-1; while (it != end_it) { if ((*it!=' ') && (*it != '\t')) break; ++it; } } //////////////////////////////////////////////////////////////////////////// template inline int _string_readNumber(TString & str, TIter& it) { // Read number typename Iterator::Type end_it = end(str,Standard())-1; String numstr(getValue(it)); while (it != end_it) { ++it; if (!_parse_isDigit(*it)) break; append(numstr, getValue(it)); } return atoi(toCString(numstr)); } ////////////////////////////////////////////////////////////////////////////// } //namespace SEQAN_NAMESPACE_MAIN ////////////////////////////////////////////////////////////////////////////// #endif //#ifndef SEQAN_HEADER_... ugene-1.9.8/src/plugins_3rdparty/bowtie/src/bowtie/SeqAn-1.1/seqan/file/cstream.h0000644000175000017500000001450411651544326026137 0ustar ilyailya /*========================================================================== SeqAn - The Library for Sequence Analysis http://www.seqan.de ============================================================================ Copyright (C) 2007 This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. ============================================================================ $Id: cstream.h,v 1.2 2009/03/03 18:47:37 langmead Exp $ ==========================================================================*/ #ifndef SEQAN_HEADER_CSTREAM_H #define SEQAN_HEADER_CSTREAM_H #include namespace SEQAN_NAMESPACE_MAIN { ////////////////////////////////////////////////////////////////////////////// /** .Adaption."std::FILE *": ..summary:Standard library C style streams. */ ////////////////////////////////////////////////////////////////////////////// // Position is now defined in file/file_cstyle.h /* template <> struct Position { typedef long Type; }; */ ////////////////////////////////////////////////////////////////////////////// template <> struct Value { typedef char Type; }; ////////////////////////////////////////////////////////////////////////////// /* template <> struct Position { typedef ::std::fpos_t Type; }; */ ////////////////////////////////////////////////////////////////////////////// template struct _IsTellSeekStream; template <> struct _IsTellSeekStream { typedef True Type; }; ////////////////////////////////////////////////////////////////////////////// inline bool _streamOpen(::std::FILE * & me, String path, bool for_read = true) { SEQAN_CHECKPOINT size_t plen = length(path); char *s = new char[plen + 1]; for(size_t i = 0; i < plen; i++) { s[i] = path[i]; } s[plen] = '\0'; if (for_read) { me = fopen(s, "rb"); } else { me = fopen(s, "wb"); } delete[] s; return (me != 0); } ////////////////////////////////////////////////////////////////////////////// inline void _streamClose(::std::FILE * & me) { SEQAN_CHECKPOINT if (me) { fclose(me); me = 0; } } ////////////////////////////////////////////////////////////////////////////// ///.Internal._streamEOF.param.stream.type:Adaption."std::FILE *" inline bool _streamEOF(::std::FILE * me) { SEQAN_CHECKPOINT return feof(me) || ferror(me); } ////////////////////////////////////////////////////////////////////////////// ///.Internal._streamRead.param.stream.type:Adaption."std::FILE *" template inline size_t _streamRead(TValue * target, ::std::FILE * source, size_t limit) { SEQAN_CHECKPOINT return ::std::fread(target, sizeof(TValue), limit, source); } ////////////////////////////////////////////////////////////////////////////// ///.Internal._streamGet.param.stream.type:Adaption."std::FILE *" inline char _streamGet(::std::FILE * source) { SEQAN_CHECKPOINT return getc(source); } ////////////////////////////////////////////////////////////////////////////// ///.Internal._streamPut.param.stream.type:Adaption."std::FILE *" inline void _streamPut(::std::FILE * target, char character) { SEQAN_CHECKPOINT putc(character, target); } ////////////////////////////////////////////////////////////////////////////// ///.Internal._streamPut.param.stream.type:Adaption."std::FILE *" ////////////////////////////////////////////////////////////////////////////// ///.Internal._streamTellG.param.stream.type:Adaption."std::FILE *" inline Position::Type _streamTellG(FILE * me) { SEQAN_CHECKPOINT return ::std::ftell(me); } ////////////////////////////////////////////////////////////////////////////// ///.Internal._streamTellP.param.stream.type:Adaption."std::FILE *" inline Position::Type _streamTellP(FILE * me) { SEQAN_CHECKPOINT return ::std::ftell(me); } ////////////////////////////////////////////////////////////////////////////// ///.Internal._streamSeekG.param.stream.type:Adaption."std::FILE *" inline void _streamSeekG(FILE * me, Position::Type pos) { SEQAN_CHECKPOINT ::std::fseek(me, pos, SEEK_SET); } ////////////////////////////////////////////////////////////////////////////// ///.Internal._streamSeekP.param.stream.type:Adaption."std::FILE *" inline void _streamSeekP(FILE * me, Position::Type pos) { SEQAN_CHECKPOINT ::std::fseek(me, pos, SEEK_SET); } ////////////////////////////////////////////////////////////////////////////// ///.Internal._streamSeek2G.param.stream.type:Adaption."std::FILE *" inline void _streamSeek2G(FILE * me, int off) { SEQAN_CHECKPOINT ::std::fseek(me, off, SEEK_CUR); } ////////////////////////////////////////////////////////////////////////////// ///.Internal._streamUnget.param.stream.type:Adaption."std::FILE *" inline void _streamUnget(::std::FILE * stream) { SEQAN_CHECKPOINT _streamSeek2G(stream, -1); } ////////////////////////////////////////////////////////////////////////////// // Stream operators for FILE * ////////////////////////////////////////////////////////////////////////////// // ISO C++ operators are only allowed for classes, not for pointers /* template inline FILE * operator << (FILE * target, TSource & source) { SEQAN_CHECKPOINT write(target, source); return target; } template inline FILE * operator << (FILE * target, TSource const & source) { SEQAN_CHECKPOINT write(target, source); return target; } //____________________________________________________________________________ template inline FILE * operator >> (FILE * source, TTarget & target) { SEQAN_CHECKPOINT read(source, target); return source; } template inline FILE * operator >> (FILE * source, TTarget const & target) { SEQAN_CHECKPOINT read(source, target); return source; } */ ////////////////////////////////////////////////////////////////////////////// } //namespace SEQAN_NAMESPACE_MAIN #endif //#ifndef SEQAN_HEADER_... ugene-1.9.8/src/plugins_3rdparty/bowtie/src/bowtie/SeqAn-1.1/seqan/basic/0000755000175000017500000000000011651544310024457 5ustar ilyailyaugene-1.9.8/src/plugins_3rdparty/bowtie/src/bowtie/SeqAn-1.1/seqan/basic/basic_forwards.h0000644000175000017500000000440311651544326027630 0ustar ilyailya /*========================================================================== SeqAn - The Library for Sequence Analysis http://www.seqan.de ============================================================================ Copyright (C) 2007 This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. ============================================================================ $Id: basic_forwards.h,v 1.1 2008/08/25 16:20:02 langmead Exp $ ==========================================================================*/ #ifndef SEQAN_HEADER_BASIC_FORWARD2_H #define SEQAN_HEADER_BASIC_FORWARD2_H //forward declarations (make GCC 4.x happy) namespace SEQAN_NAMESPACE_MAIN { ////////////////////////////////////////////////////////////////////////////// // basic_transport.h::assign template inline void assign(TTarget & target, TSource & source); template inline void assign(TTarget & target, TSource const & source); ////////////////////////////////////////////////////////////////////////////// // string_pointer.h::assignValue template inline void assignValue(TValue * me, TPos pos, TValue const & _value); ////////////////////////////////////////////////////////////////////////////// // string_pointer.h::moveValue template inline void moveValue(TValue * me, TPos pos, TValue const & _value); ////////////////////////////////////////////////////////////////////////////// // string_pointer.h::value template inline TValue & value(TValue * me, TPos pos); ////////////////////////////////////////////////////////////////////////////// } //namespace SEQAN_NAMESPACE_MAIN #endif //#ifndef SEQAN_HEADER_... ugene-1.9.8/src/plugins_3rdparty/bowtie/src/bowtie/SeqAn-1.1/seqan/basic/basic_allocator_multipool.h0000644000175000017500000001713211651544326032070 0ustar ilyailya /*========================================================================== SeqAn - The Library for Sequence Analysis http://www.seqan.de ============================================================================ Copyright (C) 2007 This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. ============================================================================ $Id: basic_allocator_multipool.h,v 1.2 2009/02/19 01:51:23 langmead Exp $ ==========================================================================*/ #ifndef SEQAN_HEADER_BASIC_ALLOCATOR_MULTIPOOL_H #define SEQAN_HEADER_BASIC_ALLOCATOR_MULTIPOOL_H namespace SEQAN_NAMESPACE_MAIN { ////////////////////////////////////////////////////////////////////////////// // MultiPool Allocator ////////////////////////////////////////////////////////////////////////////// /** .Spec.Multi Pool Allocator: ..cat:Allocators ..general:Class.Allocator ..summary:Allocator that pools memory blocks. ..signature:Allocator< MultiPool > ..param.ParentAllocator:An allocator that is by the pool allocator used to allocate memory. ...default:@Spec.Simple Allocator@ ...note:The multi pool allocator only supports @Function.clear@ if this function is also implemented for $ParentAllocator$. ..remarks:A pool allocator allocates several memory blocks at once. ..param.BLOCKING_LIMIT:The maximum size for memory blocks to be pooled. ...default:256 Freed blocks are not immediately deallocated but recycled in subsequential allocations. This way, the number of calls to the heap manager is reduced, and that speeds up memory management. ...text:Note that memory blocks larger than $BLOCKING_LIMIT$ are not pooled but immediately allocated and deallocated using $ParentAllocator$. */ template >, unsigned int BLOCKING_LIMIT = 0x100> struct MultiPool; ////////////////////////////////////////////////////////////////////////////// typedef Allocator >, 0x100> > PoolAllocator; template struct Allocator > { enum { BLOCKING_LIMIT = BLOCKING_LIMIT_, GRANULARITY_BITS = 2, BLOCKING_COUNT = BLOCKING_LIMIT >> GRANULARITY_BITS, STORAGE_SIZE = 0xf80 }; char * data_recycled_blocks [BLOCKING_COUNT]; char * data_current_begin [BLOCKING_COUNT]; char * data_current_free [BLOCKING_COUNT]; Holder data_parent_allocator; Allocator() { SEQAN_CHECKPOINT memset(data_recycled_blocks, 0, sizeof(data_recycled_blocks)); memset(data_current_begin, 0, sizeof(data_current_begin)); memset(data_current_free, 0, sizeof(data_current_free)); } Allocator(TParentAllocator & parent_alloc) { SEQAN_CHECKPOINT memset(data_recycled_blocks, 0, sizeof(data_recycled_blocks)); memset(data_current_begin, 0, sizeof(data_current_begin)); memset(data_current_free, 0, sizeof(data_current_free)); setValue(data_parent_allocator, parent_alloc); } //Dummy copy Allocator(Allocator const &) { memset(data_recycled_blocks, 0, sizeof(data_recycled_blocks)); memset(data_current_begin, 0, sizeof(data_current_begin)); memset(data_current_free, 0, sizeof(data_current_free)); } inline Allocator & operator = (Allocator const &) { clear(*this); return *this; } ~Allocator() { SEQAN_CHECKPOINT clear(*this); } }; ////////////////////////////////////////////////////////////////////////////// template inline TParentAllocator & parentAllocator(Allocator > & me) { SEQAN_CHECKPOINT return value(me.data_parent_allocator); } ////////////////////////////////////////////////////////////////////////////// template void clear(Allocator > & me) { SEQAN_CHECKPOINT memset(me.data_recycled_blocks, 0, sizeof(me.data_recycled_blocks)); memset(me.data_current_begin, 0, sizeof(me.data_current_begin)); memset(me.data_current_free, 0, sizeof(me.data_current_free)); clear(parentAllocator(me)); } ////////////////////////////////////////////////////////////////////////////// template inline unsigned int _allocatorBlockNumber(Allocator > &, size_t size_) { SEQAN_CHECKPOINT typedef Allocator > TAllocator; SEQAN_ASSERT(size_) if (size_ < BLOCKING_LIMIT) {//blocks return size_ >> TAllocator::GRANULARITY_BITS; } else {//no blocking return TAllocator::BLOCKING_COUNT; } } ////////////////////////////////////////////////////////////////////////////// template inline void allocate(Allocator > & me, TValue * & data, TSize count, Tag const tag_) { SEQAN_CHECKPOINT typedef Allocator > TAllocator; size_t bytes_needed = count * sizeof(TValue); char * ptr; unsigned int block_number = _allocatorBlockNumber(me, bytes_needed); if (block_number == TAllocator::BLOCKING_COUNT) {//no blocking return allocate(parentAllocator(me), data, count, tag_); } bytes_needed = (block_number + 1) << TAllocator::GRANULARITY_BITS; if (me.data_recycled_blocks[block_number]) {//use recycled ptr = me.data_recycled_blocks[block_number]; me.data_recycled_blocks[block_number] = * reinterpret_cast(ptr); } else {//use new ptr = me.data_current_free[block_number]; if (!ptr || (ptr + bytes_needed > me.data_current_begin[block_number] + TAllocator::STORAGE_SIZE)) {//not enough free space in current storage: allocate new allocate(parentAllocator(me), ptr, (size_t) TAllocator::STORAGE_SIZE, tag_); me.data_current_begin[block_number] = ptr; } me.data_current_free[block_number] = ptr + bytes_needed; } data = reinterpret_cast(ptr); } ////////////////////////////////////////////////////////////////////////////// template inline void deallocate(Allocator > & me, TValue * data, TSize count, Tag const tag_) { SEQAN_CHECKPOINT typedef Allocator > TAllocator; size_t bytes_needed = count * sizeof(TValue); unsigned int block_number = _allocatorBlockNumber(me, bytes_needed); if (block_number == TAllocator::BLOCKING_COUNT) {//no blocking return deallocate(parentAllocator(me), data, count, tag_); } bytes_needed = (block_number + 1) << TAllocator::GRANULARITY_BITS; //link in recycling list *reinterpret_cast(data) = me.data_recycled_blocks[block_number]; me.data_recycled_blocks[block_number] = reinterpret_cast(data); } ////////////////////////////////////////////////////////////////////////////// } //namespace SEQAN_NAMESPACE_MAIN #endif //#ifndef SEQAN_HEADER_... ugene-1.9.8/src/plugins_3rdparty/bowtie/src/bowtie/SeqAn-1.1/seqan/basic/basic_alphabet_interface2.h0000644000175000017500000001260011651544326031661 0ustar ilyailya /*========================================================================== SeqAn - The Library for Sequence Analysis http://www.seqan.de ============================================================================ Copyright (C) 2007 This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. ============================================================================ $Id: basic_alphabet_interface2.h,v 1.1 2008/08/25 16:20:01 langmead Exp $ ==========================================================================*/ #ifndef SEQAN_HEADER_BASIC_ALPHABET_INTERFACE2_H #define SEQAN_HEADER_BASIC_ALPHABET_INTERFACE2_H #include namespace SEQAN_NAMESPACE_MAIN { ////////////////////////////////////////////////////////////////////////////// // gapValue, gapValueImpl ////////////////////////////////////////////////////////////////////////////// /** .Function.gapValueImpl: ..hidefromindex ..cat:Alphabets ..summary:Implements @Function.gapValue@. ..signature:gapValueImpl(value_pointer_tag) ..param.value_pointer_tag:A pointer that is used as a tag to specify the value type. ...remarks:The pointer needs not to point to a valid object, so it is possible to use a null pointer here. ..returns:A gap character. ..remarks.text:This function implements @Function.getValue@. It is recommended to use @Function.gapValue@ rather than $gapValueImpl$. */ template inline T const & gapValueImpl(T *) { SEQAN_CHECKPOINT static T const _gap = T(); return _gap; } /** .Function.gapValue: ..cat:Alphabets ..cat:Alignments ..summary:Returns reference to a value that is used as gap character. ..signature:gapValue() ..param.TValue:Value type. ..returns:A gap character. ..remarks.text:The function is implemented in @Function.gapValueImpl@. Do not specialize $gapValue$, specialize @Function.gapValueImpl@ instead! ..see:Function.gapValueImpl */ template inline T const & gapValue() { SEQAN_CHECKPOINT T * _tag = 0; return gapValueImpl(_tag); } ////////////////////////////////////////////////////////////////////////////// // supremumValue, supremumValueImpl ////////////////////////////////////////////////////////////////////////////// /** .Function.supremumValueImpl: ..hidefromindex ..cat:Alphabets ..summary:Implements @Function.supremumValue@. ..signature:supremumValueImpl(value_pointer_tag) ..param.value_pointer_tag:A pointer that is used as a tag to specify the value type. ...remarks:The pointer needs not to point to a valid object, so it is possible to use a null pointer here. ..returns:A value $inf$ that holds: $inf >= i$ for all values $i$. ..remarks.text:This function implements @Function.supremumValue@. It is recommended to use @Function.supremumValue@ rather than $supremumValueImpl$. */ /* template inline T const & supremumValueImpl(T *) { static T const _value = -1; return _value; } */ /** .Function.supremumValue: ..cat:Alphabets ..summary:Supremum for a given type. ..signature:supremumValue() ..param.T:An ordered type. ..returns:A value $inf$ that holds: $inf >= i$ for all values $i$ of type $T$. ..remarks.text:The function is implemented in @Function.supremumValueImpl@. Do not specialize $supremumValue$, specialize @Function.supremumValueImpl@ instead! ..see:Function.supremumValueImpl */ template inline T const & supremumValue() { SEQAN_CHECKPOINT T * _tag = 0; return supremumValueImpl(_tag); } ////////////////////////////////////////////////////////////////////////////// // infimumValue, infimumValueImpl ////////////////////////////////////////////////////////////////////////////// /** .Function.infimumValueImpl: ..hidefromindex ..cat:Alphabets ..summary:Implements @Function.infimumValue@. ..signature:infimumValueImpl(value_pointer_tag) ..param.value_pointer_tag:A pointer that is used as a tag to specify the value type. ...remarks:The pointer needs not to point to a valid object, so it is possible to use a null pointer here. ..returns:A value $inf$ that holds: $inf <= i$ for all values $i$. ..remarks.text:This function implements @Function.infimumValue@. It is recommended to use @Function.infimumValue@ rather than $infimumValueImpl$. */ /* template inline T const & infimumValueImpl(T *) { static T const _value = -1; return _value; } */ /** .Function.infimumValue: ..cat:Alphabets ..summary:Infimum for a given type. ..signature:infimumValue() ..param.T:An ordered type. ..returns:A value $inf$ that holds: $inf <= i$ for all values $i$ of type $T$. ..remarks.text:The function is implemented in @Function.infimumValueImpl@. Do not specialize $infimumValue$, specialize @Function.infimumValueImpl@ instead! ..see:Function.infimumValueImpl ..see:Function.supremumValue */ template inline T const & infimumValue() { SEQAN_CHECKPOINT T * _tag = 0; return infimumValueImpl(_tag); } ////////////////////////////////////////////////////////////////////////////// }// namespace SEQAN_NAMESPACE_MAIN #endif //#ifndef SEQAN_HEADER_... ugene-1.9.8/src/plugins_3rdparty/bowtie/src/bowtie/SeqAn-1.1/seqan/basic/basic_iterator_adapt_std.h0000644000175000017500000003211311651544326031654 0ustar ilyailya /*========================================================================== SeqAn - The Library for Sequence Analysis http://www.seqan.de ============================================================================ Copyright (C) 2007 This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. ============================================================================ $Id: basic_iterator_adapt_std.h,v 1.1 2008/08/25 16:20:01 langmead Exp $ ==========================================================================*/ #ifndef SEQAN_HEADER_BASIC_ITERATOR_ADAPT_STD_H #define SEQAN_HEADER_BASIC_ITERATOR_ADAPT_STD_H ////////////////////////////////////////////////////////////////////////////// //adapt SeqAn iterator to std namespace std { template struct iterator_traits > { typedef ::seqan::Iter TIter; typedef random_access_iterator_tag iterator_category; typedef typename ::seqan::Value::Type value_type; typedef typename ::seqan::Difference::Type difference_type; typedef typename ::seqan::Value::Type * pointer; typedef typename ::seqan::Reference::Type reference; }; } ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// namespace SEQAN_NAMESPACE_MAIN { //helper Metafunction /* This simple, general implementation cannot be used due to strange VC++ 2003 behavior template struct StdContainerIterator { typedef typename TStdContainer::iterator Type; }; template struct StdContainerIterator { typedef typename TStdContainer::const_iterator Type; }; */ //we use this instead: specialize StdContainerIterator for each std-container template struct StdContainerIterator { typedef void * Type; //dummy, just to make VC++ 2003 happy }; template struct StdContainerIterator< ::std::basic_string > { typedef ::std::basic_string TContainer; typedef typename TContainer::iterator Type; }; template struct StdContainerIterator< ::std::basic_string const> { typedef ::std::basic_string TContainer; typedef typename TContainer::const_iterator Type; }; ////////////////////////////////////////////////////////////////////////////// //adapt std iterator to SeqAn struct StdIteratorAdaptor; template class Iter { public: typedef typename StdContainerIterator::Type TIterator; TIterator data_iterator; Iter() {} Iter(Iter const & other_): data_iterator(other_.data_iterator) {} Iter(TIterator const & iter_): data_iterator(iter_) {} Iter(TContainer const & cont_): data_iterator(begin(cont_)) {} Iter const & operator = (Iter const & other_) { data_iterator = other_.data_iterator; return *this; } Iter const & operator = (TIterator const & iter_) { data_iterator = iter_; return *this; } operator TIterator &() { return data_iterator; } ~Iter() {} }; ////////////////////////////////////////////////////////////////////////////// // hostIterator ////////////////////////////////////////////////////////////////////////////// template inline typename StdContainerIterator::Type & hostIterator(Iter & me) { return me.data_iterator; } template inline typename StdContainerIterator::Type const & hostIterator(Iter const & me) { return me.data_iterator; } ////////////////////////////////////////////////////////////////////////////// // value ////////////////////////////////////////////////////////////////////////////// template inline typename Reference >::Type value(Iter & me) { return *(me.data_iterator); } template inline typename Reference const>::Type value(Iter const & me) { return *(me.data_iterator); } ///////////////////////////////////////////////////////////////////////////// // assignValue ////////////////////////////////////////////////////////////////////////////// template inline void assignValue(Iter & me, TValue & val) { *(me.data_iterator) = val; } template inline void assignValue(Iter & me, TValue const & val) { *(me.data_iterator) = val; } ///////////////////////////////////////////////////////////////////////////// // moveValue ////////////////////////////////////////////////////////////////////////////// template inline void moveValue(Iter & me, TValue & val) { move(*(me.data_iterator), val); } template inline void moveValue(Iter & me, TValue const & val) { move(*(me.data_iterator), val); } ////////////////////////////////////////////////////////////////////////////// // operator == ////////////////////////////////////////////////////////////////////////////// template inline bool operator == (Iter const & left, Iter const & right) { SEQAN_CHECKPOINT return hostIterator(left) == hostIterator(right); } ////////////////////////////////////////////////////////////////////////////// // operator != ////////////////////////////////////////////////////////////////////////////// template inline bool operator != (Iter const & left, Iter const & right) { SEQAN_CHECKPOINT return hostIterator(left) != hostIterator(right); } ////////////////////////////////////////////////////////////////////////////// // operator < ////////////////////////////////////////////////////////////////////////////// template inline bool operator < (Iter const & left, Iter const & right) { SEQAN_CHECKPOINT return hostIterator(left) < hostIterator(right); } ////////////////////////////////////////////////////////////////////////////// // operator > ////////////////////////////////////////////////////////////////////////////// template inline bool operator > (Iter const & left, Iter const & right) { SEQAN_CHECKPOINT return hostIterator(left) > hostIterator(right); } ////////////////////////////////////////////////////////////////////////////// // operator <= ////////////////////////////////////////////////////////////////////////////// template inline bool operator <= (Iter const & left, Iter const & right) { SEQAN_CHECKPOINT return hostIterator(left) <= hostIterator(right); } ////////////////////////////////////////////////////////////////////////////// // operator >= ////////////////////////////////////////////////////////////////////////////// template inline bool operator >= (Iter const & left, Iter const & right) { SEQAN_CHECKPOINT return hostIterator(left) >= hostIterator(right); } ////////////////////////////////////////////////////////////////////////////// // goNext ////////////////////////////////////////////////////////////////////////////// template inline void goNext(Iter & me) { SEQAN_CHECKPOINT goNext(hostIterator(me)); } ////////////////////////////////////////////////////////////////////////////// // goPrevious ////////////////////////////////////////////////////////////////////////////// template inline void goPrevious(Iter & me) { SEQAN_CHECKPOINT goPrevious(hostIterator(me)); } ////////////////////////////////////////////////////////////////////////////// // operator + ////////////////////////////////////////////////////////////////////////////// template inline Iter operator + (Iter const & left, TIntegral right) { SEQAN_CHECKPOINT return Iter(hostIterator(left) + right); } // for types template inline Iter operator + (Iter const & left, int right) { SEQAN_CHECKPOINT return Iter(hostIterator(left) + right); } template inline Iter operator + (TIntegral left, Iter const & right) { SEQAN_CHECKPOINT return Iter(hostIterator(right) + left); } // for types template inline Iter operator + (int left, Iter const & right) { SEQAN_CHECKPOINT return Iter(hostIterator(right) + left); } ////////////////////////////////////////////////////////////////////////////// // operator += ////////////////////////////////////////////////////////////////////////////// template inline Iter & operator += (Iter & left, TIntegral right) { SEQAN_CHECKPOINT hostIterator(left) += right; return left; } // for types template inline Iter & operator += (Iter & left, int right) { SEQAN_CHECKPOINT hostIterator(left) += right; return left; } ////////////////////////////////////////////////////////////////////////////// // operator - ////////////////////////////////////////////////////////////////////////////// template inline Iter operator - (Iter const & left, TIntegral right) { SEQAN_CHECKPOINT return Iter(hostIterator(left) - right); } // for types template inline Iter operator - (Iter const & left, int right) { SEQAN_CHECKPOINT return Iter(hostIterator(left) - right); } //____________________________________________________________________________ template inline typename Difference >::Type operator - (Iter const & left, Iter const & right) { SEQAN_CHECKPOINT return hostIterator(left) - hostIterator(right); } ////////////////////////////////////////////////////////////////////////////// // operator -= ////////////////////////////////////////////////////////////////////////////// template inline Iter & operator -= (Iter & left, TIntegral right) { SEQAN_CHECKPOINT hostIterator(left) -= right; return left; } // for types template inline Iter & operator -= (Iter & left, int right) { SEQAN_CHECKPOINT hostIterator(left) -= right; return left; } ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// // assign (Conversion) ////////////////////////////////////////////////////////////////////////////// template inline void assign(Iter & target, TSource const & source) { SEQAN_CHECKPOINT target.data_iterator = begin(container(source)) + position(source); } ////////////////////////////////////////////////////////////////////////////// } //namespace SEQAN_NAMESPACE_MAIN #endif //#ifndef SEQAN_HEADER_... ugene-1.9.8/src/plugins_3rdparty/bowtie/src/bowtie/SeqAn-1.1/seqan/basic/basic_compare.h0000644000175000017500000000420011651544326027422 0ustar ilyailya /*========================================================================== SeqAn - The Library for Sequence Analysis http://www.seqan.de ============================================================================ Copyright (C) 2007 This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. ============================================================================ $Id: basic_compare.h,v 1.1 2008/08/25 16:20:01 langmead Exp $ ==========================================================================*/ #ifndef SEQAN_HEADER_BASIC_COMPARE_H #define SEQAN_HEADER_BASIC_COMPARE_H namespace SEQAN_NAMESPACE_MAIN { ////////////////////////////////////////////////////////////////////////////// template struct CompareType; template struct CompareType { typedef typename CompareType::Type const Type; }; template struct CompareType { typedef typename CompareType::Type const Type; }; template struct CompareType { typedef typename CompareType::Type const Type; }; ////////////////////////////////////////////////////////////////////////////// template inline bool lexLess(const _T& _Left, const _T& _Right) { // return lexicographical _Left < _Right typedef typename _MakeUnsigned<_T>::Type TUnsigned; return (TUnsigned)_Left < (TUnsigned)_Right; } ////////////////////////////////////////////////////////////////////////////// }// namespace SEQAN_NAMESPACE_MAIN #endif //#ifndef SEQAN_HEADER_... ugene-1.9.8/src/plugins_3rdparty/bowtie/src/bowtie/SeqAn-1.1/seqan/basic/basic_alphabet_interface.h0000644000175000017500000007435411651544326031615 0ustar ilyailya /*========================================================================== SeqAn - The Library for Sequence Analysis http://www.seqan.de ============================================================================ Copyright (C) 2007 This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. ============================================================================ $Id: basic_alphabet_interface.h,v 1.1 2008/08/25 16:20:01 langmead Exp $ ==========================================================================*/ #ifndef SEQAN_HEADER_BASIC_ALPHABET_INTERFACE_H #define SEQAN_HEADER_BASIC_ALPHABET_INTERFACE_H #include namespace SEQAN_NAMESPACE_MAIN { ////////////////////////////////////////////////////////////////////////////// //IsSimple ////////////////////////////////////////////////////////////////////////////// /** .Metafunction.IsSimple: ..summary:Tests type to be simple. ..signature:IsSimple::Type ..param.T:Type that is tested. ..returns.param.Type:@Tag.Logical Values.True@, if $T$ is a simple type, @Tag.Logical Values.False@ otherwise. ...default:@Tag.Logical Values.False@ ..remarks:A simple type is a type that does not need constructors to be created, a destructor to be destroyed, and copy assignment operators or copy constructors to be copied. All POD ("plain old data") types are simple, but some non-POD types could be simple too, e.g. some specializations of @Class.SimpleType@. ..see:Class.SimpleType */ template struct _IsSimple { typedef False Type; }; template struct IsSimple: public _IsSimple {}; template struct IsSimple: public IsSimple {}; ////////////////////////////////////////////////////////////////////////////// //very basic Alphabets typedef char Ascii; typedef unsigned char Byte; typedef wchar_t Unicode; ////////////////////////////////////////////////////////////////////////////// /** .Function.valueConstruct: ..cat:Content Manipulation ..summary:Constructs an object at specified position. ..signature:valueConstruct(iterator [, param [, move_tag] ]) ..param.iterator:Pointer or iterator to position where the object should be constructed. ..param.param:Parameter that is forwarded to constructor. (optional) ..param.move_tag:Instance of the @Tag.Move Switch.move switch tag@. (optional) ...remarks:If the @Tag.Move Switch.move switch tag@ is specified, it is forwarded to the constructor, so the constructed object must support move construction. ..remarks:The type of the destructed object is the @Metafunction.Value.value type@ of $iterator$. */ struct _ValueConstructor { template static inline void construct(TIterator it) { typedef typename Value::Type TValue; new( & value(it) ) TValue; } template static inline void construct(TIterator it, TParam const & param_) { typedef typename Value::Type TValue; new( & value(it) ) TValue(param_); } template static inline void construct(TIterator it, TParam const & param_, Move tag) { typedef typename Value::Type TValue; new( & value(it) ) TValue(param_, tag); } }; struct _ValueConstructorProxy { template static inline void construct(TIterator) {} template static inline void construct(TIterator, TParam const &) {} template static inline void construct(TIterator, TParam const &, Move) {} }; //____________________________________________________________________________ struct _ValueDestructor { template static inline void destruct(TIterator it) { typedef typename Value::Type TValue; value(it).~TValue(); } }; struct _ValueDestructorProxy { template static inline void destruct(TIterator) {} }; //____________________________________________________________________________ template inline void valueConstruct(TIterator it) { SEQAN_CHECKPOINT typedef typename IF< TYPECMP< typename Value::Type &, typename Reference::Type >::VALUE, // THEN _ValueConstructor, // true, types are equal // ELSE _ValueConstructorProxy // false, types differ -> value() returns a proxy >::Type TConstructor; TConstructor::construct(it); } template inline void valueConstruct(TIterator it, TParam const & param_) { SEQAN_CHECKPOINT typedef typename IF< TYPECMP< typename Value::Type &, typename Reference::Type >::VALUE, // THEN _ValueConstructor, // true, types are equal // ELSE _ValueConstructorProxy // false, types differ -> value() returns a proxy >::Type TConstructor; TConstructor::construct(it, param_); } template inline void valueConstruct(TIterator it, TParam const & param_, Move tag) { SEQAN_CHECKPOINT typedef typename IF< TYPECMP< typename Value::Type &, typename Reference::Type >::VALUE, // THEN _ValueConstructor, // true, types are equal // ELSE _ValueConstructorProxy // false, types differ -> value() returns a proxy >::Type TConstructor; TConstructor::construct(it, param_, tag); } ////////////////////////////////////////////////////////////////////////////// /** .Function.valueDestruct: ..cat:Content Manipulation ..summary:Destoys an object at specified position. ..signature:valueDestruct(iterator) ..param.iterator:Pointer or iterator to position where the object should be constructed. ..remarks:The type of the constructed object is the @Metafunction.Value.value type@ of $iterator$. ..see:Function.valueConstruct */ template inline void valueDestruct(TIterator it) { SEQAN_CHECKPOINT typedef typename IF< TYPECMP< typename Value::Type &, typename Reference::Type >::VALUE, // THEN _ValueDestructor, // true, types are equal // ELSE _ValueDestructorProxy // false, types differ -> value() returns a proxy >::Type TDestructor; TDestructor::destruct(it); } ////////////////////////////////////////////////////////////////////////////// /** .Function.valueConstructMove: ..cat:Content Manipulation ..summary:Move constructs an object at specified position. ..signature:valueConstructMove(iterator, param) ..param.iterator:Pointer or iterator to position where the object should be constructed. ..param.param:Parameter that is moved to the new constructed object. ..remarks:The type of the destructed object is the @Metafunction.Value.value type@ of $iterator$. ..remarks:The default implementation just calls @Function.valueConstruct@. */ template inline void valueConstructMove(TIterator it, TValue const & value) { valueConstruct(it, value); } ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// //arrayConstruct ////////////////////////////////////////////////////////////////////////////// /** .Function.arrayConstruct: ..cat:Array Handling ..summary:Construct objects in a given memory buffer. ..signature:arrayConstruct(begin, end [, value]) ..param.begin:Iterator to the begin of the range that is to be constructed. ..param.end:Iterator behind the end of the range. ..param.value:Argument that is forwarded to the constructor. (optional) ...text:An appropriate constructor is required. If $value$ is not specified, the default constructor is used. ..remarks:The type of the constructed Objects is the @Metafunction.Value.value type@ of $begin$ and $end$. ..see:Function.arrayDestruct ..see:Function.arrayConstructCopy ..see:Function.arrayFill ..see:Class.SimpleType ..see:Function.valueConstruct */ template inline void _arrayConstruct_Default(TIterator1 begin_, TIterator2 end_) { SEQAN_CHECKPOINT while (begin_ != end_) { valueConstruct(begin_); ++begin_; } } template inline void arrayConstruct(TIterator1 begin_, TIterator2 end_) { SEQAN_CHECKPOINT _arrayConstruct_Default(begin_, end_); } //____________________________________________________________________________ template inline void _arrayConstruct_Default(TIterator1 begin_, TIterator2 end_, TParam const & param_) { SEQAN_CHECKPOINT while (begin_ != end_) { valueConstruct(begin_, param_); ++begin_; } } template inline void arrayConstruct(TIterator1 begin_, TIterator2 end_, TParam const & param_) { SEQAN_CHECKPOINT _arrayConstruct_Default(begin_, end_, param_); } ////////////////////////////////////////////////////////////////////////////// //arrayConstructCopy ////////////////////////////////////////////////////////////////////////////// /** .Function.arrayConstructCopy: ..cat:Array Handling ..summary:Copy constructs an array of objects into in a given memory buffer. ..signature:arrayConstructCopy(source_begin, source_end, target) ..param.source_begin:Iterator to the first element of the source range. ..param.source_end:Iterator behind the last element of the source range. ...text:$source_end$ should have the same type as $source_begin$. ..param.target:Pointer to the memory block the new objects will be constructed in. ...text:The type of $target$ specifies the type of the constructed objects: If $T*$ is the type of $target$, then the function constructs objects of type $T$. ...text:The memory buffer should be large enough to store $source_end$ - $source_begin$ objects. An appropriate (copy-) constructor that constructs an target objects given a source object is required. ..see:Function.arrayDestruct ..see:Function.arrayCopyForward ..see:Function.arrayCopy ..see:Function.valueConstruct */ template inline void _arrayConstructCopy_Default(TSource1 source_begin, TSource2 source_end, TTarget target_begin) { SEQAN_CHECKPOINT while (source_begin != source_end) { valueConstruct(target_begin, *source_begin); ++source_begin; ++target_begin; } } template inline void arrayConstructCopy(TSource1 source_begin, TSource2 source_end, TTarget target_begin) { SEQAN_CHECKPOINT _arrayConstructCopy_Default(source_begin, source_end, target_begin); } ////////////////////////////////////////////////////////////////////////////// //arrayConstructMove ////////////////////////////////////////////////////////////////////////////// /** .Function.arrayConstructMove: ..cat:Array Handling ..summary:Move constructs an array of objects into in a given memory buffer. ..signature:arrayConstructMove(source_begin, source_end, target) ..param.source_begin:Iterator to the first element of the source range. ..param.source_end:Iterator behind the last element of the source range. ...text:$source_end$ should have the same type as $source_begin$. ..param.target:Pointer to the memory block the new objects will be constructed in. ...text:The type of $target$ specifies the type of the constructed objects: If $T*$ is the type of $target$, then the function constructs objects of type $T$. ...text:The memory buffer should be large enough to store $source_end$ - $source_begin$ objects. An appropriate move constructor that constructs an target objects given a source object is required. ..see:Function.arrayDestruct ..see:Function.arrayConstructCopy ..see:Function.arrayMoveForward ..see:Function.arrayMove ..see:Function.valueConstruct */ template inline void _arrayConstructMove_Default(TSource1 source_begin, TSource2 source_end, TTarget target_begin) { SEQAN_CHECKPOINT while (source_begin < source_end) { valueConstructMove(target_begin, *source_begin); ++source_begin; ++target_begin; } } template inline void arrayConstructMove(TSource1 source_begin, TSource2 source_end, TTarget target_begin) { SEQAN_CHECKPOINT _arrayMoveConstruct_Default(source_begin, source_end, target_begin); } ////////////////////////////////////////////////////////////////////////////// //arrayDestruct ////////////////////////////////////////////////////////////////////////////// /** .Function.arrayDestruct: ..cat:Array Handling ..summary:Destroys an array of objects. ..signature:arrayDestruct(begin, end) ..param.begin:Iterator to the begin of the range that is to be destructed. ..param.end:Iterator behind the end of the range. ..remarks:This function does not deallocates the memory. ..see:Class.SimpleType ..see:Function.valueDestruct */ template inline void _arrayDestruct_Default(TIterator1 begin_, TIterator2 end_) { SEQAN_CHECKPOINT while (begin_ != end_) { valueDestruct(begin_); ++begin_; } } template inline void arrayDestruct(TIterator1 begin_, TIterator2 end_) { SEQAN_CHECKPOINT _arrayDestruct_Default(begin_, end_); } ////////////////////////////////////////////////////////////////////////////// //arrayFill ////////////////////////////////////////////////////////////////////////////// /** .Function.arrayFill: ..cat:Array Handling ..summary:Assigns one object to each element of a range. ..signature:arrayFill(begin, end, value) ..param.begin:Iterator to the begin of the range that is to be filled. ..param.end:Iterator behind the end of the range. ..param.value:Argument that is assigned to all $count$ objects in $array$. ..remarks:All objects $target_begin[0]$ to $target_begin[count-1]$ are set to $value$. ..see:Function.arrayCopy ..see:Function.arrayCopyForward */ template inline void arrayFill(TIterator1 begin_, TIterator2 end_, TValue const & value) { SEQAN_CHECKPOINT ::std::fill_n(begin_, end_ - begin_, value); } ////////////////////////////////////////////////////////////////////////////// //arrayCopyForward ////////////////////////////////////////////////////////////////////////////// /** .Function.arrayCopyForward: ..cat:Array Handling ..summary:Copies a range of objects into another range of objects starting from the first element. ..signature:arrayCopyForward(source_begin, source_end, target) ..param.source_begin:Iterator to the first element of the source array. ..param.source_end:Iterator behind the last element of the source array. ...text:$source_end$ must have the same type as $source_begin$. ..param.target:Iterator to the first element of the target array. ...text:The target capacity should be at least as long as the source range. ..remarks.note:Be careful if source and target range overlap, because in this case some source elements could be accidently overwritten before they are moved. ..remarks:If there is no need for the source elements to persist, consider to use @Function.arrayMoveForward@ instead to improve performance. ..see:Class.SimpleType */ template inline void _arrayCopyForward_Default(TSource1 source_begin, TSource2 source_end, TTarget target_begin) { SEQAN_CHECKPOINT ::std::copy(source_begin, source_end, target_begin); } template inline void arrayCopyForward(TSource1 source_begin, TSource2 source_end, TTarget target_begin) { SEQAN_CHECKPOINT _arrayCopyForward_Default(source_begin, source_end, target_begin); } ////////////////////////////////////////////////////////////////////////////// //arrayCopyBackward ////////////////////////////////////////////////////////////////////////////// /** .Function.arrayCopyBackward: ..cat:Array Handling ..summary:Copies a range of objects into another range of objects starting from the last element. ..signature:arrayCopyBackward(source_begin, source_end, target) ..param.source_begin:Iterator to the first element of the source array. ..param.source_end:Iterator behind the last element of the source array. ...text:$source_end$ must have the same type as $source_begin$. ..param.target:Iterator to the first element of the target array. ...text:The target capacity should be at least as long as the source range. ..remarks.note:Be careful if source and target range overlap, because in this case some source elements could be accidently overwritten before they are moved. ..remarks.text:If source and target do not overlap, consider to use the function @Function.arrayCopyForward@ instead that is faster in some cases. ..remarks:If there is no need for the source elements to persist, consider to use @Function.arrayMoveBackward@ instead to improve performance. ..remarks.note:The semantic of this function's argument $target$ differ from the arguments of $::std::copy_backward$. ..see:Function.arrayCopyForward ..see:Class.SimpleType */ template inline void _arrayCopyBackward_Default(TSource1 source_begin, TSource2 source_end, TTarget target_begin) { SEQAN_CHECKPOINT ::std::copy_backward(source_begin, source_end, target_begin + (source_end - source_begin)); } template inline void arrayCopyBackward(TSource1 source_begin, TSource2 source_end, TTarget target_begin) { SEQAN_CHECKPOINT _arrayCopyBackward_Default(source_begin, source_end, target_begin); } ////////////////////////////////////////////////////////////////////////////// //arrayCopy ////////////////////////////////////////////////////////////////////////////// /** .Function.arrayCopy: ..cat:Array Handling ..summary:Copies a range of objects into another range of objects. ..signature:arrayCopy(source_begin, source_end, target) ..param.source_begin:Iterator to the first element of the source range. ..param.source_end:Iterator behind the last element of the source range. ...text:$source_end$ must have the same type as $source_begin$. ..param.target:Iterator to the first element of the target range. ...text:The target capacity should be at least as long as the source range. ..remarks.text:If source and target range do not overlap, consider to use @Function.arrayCopyForward@ instead to improve performance. ..remarks:If there is no need for the source elements to persist, consider to use @Function.arrayMoveForward@ instead to improve performance. ..DISABLED.remarks.note:Be careful if source and target range overlap and the size of the source elements differ from the size of target elements, because in this case some source elements could be accidently overwritten before they are moved. ..see:Function.arrayCopyForward ..see:Function.arrayCopyBackward ..see:Class.SimpleType */ template inline void arrayCopy(TSource1 source_begin, TSource2 source_end, TTarget target_begin) { if ((void *) source_begin >= (void *) target_begin) { SEQAN_CHECKPOINT arrayCopyForward(source_begin, source_end, target_begin); } else { SEQAN_CHECKPOINT arrayCopyBackward(source_begin, source_end, target_begin); } } ////////////////////////////////////////////////////////////////////////////// //arrayMoveForward ////////////////////////////////////////////////////////////////////////////// /** .Function.arrayMoveForward: ..cat:Array Handling ..summary:Moves a range of objects into another range of objects starting from the first element. ..signature:arrayMoveForward(source_begin, source_end, target) ..param.source_begin:Iterator to the first element of the source array. ..param.source_end:Iterator behind the last element of the source array. ...text:$source_end$ must have the same type as $source_begin$. ..param.target:Iterator to the first element of the target array. ...text:The target capacity should be at least as long as the source range. ..remarks:The function possibly clears (but does not destroy) the source elements. If source elements must persist, consider to use @Function.arrayCopyForward@ instead. ..remarks.note:Be careful if source and target range overlap, because in this case some source elements could be accidently overwritten before they are moved. ..see:Function.arrayCopyForward ..see:Class.SimpleType */ template inline void _arrayMoveForward_Default(TSource1 source_begin, TSource2 source_end, TTarget target_begin) { SEQAN_CHECKPOINT while (source_begin != source_end) { move(*target_begin, *source_begin); ++source_begin; ++target_begin; } } template inline void arrayMoveForward(TSource1 source_begin, TSource2 source_end, TTarget target_begin) { SEQAN_CHECKPOINT _arrayMoveForward_Default(source_begin, source_end, target_begin); } ////////////////////////////////////////////////////////////////////////////// //arrayMoveBackward ////////////////////////////////////////////////////////////////////////////// /** .Function.arrayMoveBackward: ..cat:Array Handling ..summary:Moves a range of objects into another range of objects starting from the last element. ..signature:arrayMoveBackward(source_begin, source_end, target) ..param.source_begin:Iterator to the first element of the source array. ..param.source_end:Iterator behind the last element of the source array. ...text:$source_end$ must have the same type as $source_begin$. ..param.target:Iterator to the first element of the target array. ...text:The target capacity should be at least as long as the source range. ..remarks:The function possibly clears (but does not destroy) the source elements. If source elements must persist, consider to use @Function.arrayCopyBackward@ instead. ..remarks.note:Be careful if source and target range overlap, because in this case some source elements could be accidently overwritten before they are moved. ..remarks.text:If source and target do not overlap, consider to use the function @Function.arrayMoveForward@ instead that is faster in some cases. ..remarks.note:The semantic of this function's argument $target$ differ from the arguments of $::std::copy_backward$. ..see:Function.arrayMoveForward ..see:Function.arrayCopyBackward ..see:Class.SimpleType */ template inline void _arrayMoveBackward_Default(TSource1 source_begin, TSource2 source_end, TTarget target_begin) { SEQAN_CHECKPOINT target_begin += (source_end - source_begin); while (source_end != source_begin) { --source_end; --target_begin; move(*target_begin, *source_end); } } template inline void arrayMoveBackward(TSource1 source_begin, TSource2 source_end, TTarget target_begin) { SEQAN_CHECKPOINT _arrayMoveBackward_Default(source_begin, source_end, target_begin); } ////////////////////////////////////////////////////////////////////////////// //arrayMove ////////////////////////////////////////////////////////////////////////////// /** .Function.arrayMove: ..cat:Array Handling ..summary:Moves a range of objects into another range of objects. ..signature:arrayMove(source_begin, source_end, target) ..param.source_begin:Iterator to the first element of the source range. ..param.source_end:Iterator behind the last element of the source range. ...text:$source_end$ must have the same type as $source_begin$. ..param.target:Iterator to the first element of the target range. ...text:The target capacity should be at least as long as the source range. ..remarks:The function possibly clears (but does not destroy) the source elements. If source elements must persist, consider to use @Function.arrayCopy@ instead. ..remarks.text:If source and target range do not overlap, consider to use @Function.arrayMoveForward@ instead to improve performance. ..DISABLED.remarks.note:Be careful if source and target range overlap and the size of the source elements differ from the size of target elements, because in this case some source elements could be accidently overwritten before they are moved. ..remarks.note:Don't confuse this function with the standard $move$ function that resembles @Function.arrayCopy@. ..see:Function.arrayMoveForward ..see:Function.arrayMoveBackward ..see:Function.arrayCopy ..see:Class.SimpleType */ template inline void arrayMove(TSource1 source_begin, TSource2 source_end, TTarget target_begin) { if ((void *) source_begin >= (void *) target_begin) { SEQAN_CHECKPOINT arrayMoveForward(source_begin, source_end, target_begin); } else { SEQAN_CHECKPOINT arrayMoveBackward(source_begin, source_end, target_begin); } } ////////////////////////////////////////////////////////////////////////////// //arrayClearSpace ////////////////////////////////////////////////////////////////////////////// /** .Function.arrayClearSpace: ..cat:Array Handling ..summary:Destroys the begin of an array and keeps the rest. ..signature:arrayClearSpace(arr_begin, arr_length, keep_from, move_to) ..param.arr_begin:Pointer to the first element of the array. ..param.arr_length:Length of the array. ..param.keep_from:Offset of the first object that will be kept. ..param.move_to:Offset the first kept object will get at the end of the function. ..remarks.text:The objects $arr[keep_from]$ to $arr[arr_length-1]$ are moved to the area beginning at positions $move_to$. All objects in $arr[0]$ to $arr[keep_from-1]$ are destroyed. After this function, the first $move_to$ positions of the array are free and dont contain objects. ..remarks.text:The array must have at least enough space to store $arr_length + move_to - keep_from$ objects. ..see:Function.arrayCopy ..see:Function.arrayDestruct ..see:Function.arrayCopyForward ..see:Class.SimpleType */ template void _arrayClearSpace_Default(TIterator array_begin, size_t array_length, size_t keep_from, size_t move_to) { if (keep_from == array_length) { arrayDestruct(array_begin, array_begin + array_length); return; } SEQAN_ASSERT(keep_from < array_length) if (keep_from == move_to) { arrayDestruct(array_begin, array_begin + move_to); } else if (keep_from < move_to) { if (array_length > move_to) { SEQAN_CHECKPOINT size_t middle = array_length - (move_to - keep_from); arrayConstructMove(array_begin + middle, array_begin + array_length, array_begin + array_length); arrayMove(array_begin + keep_from, array_begin + middle, array_begin + move_to); arrayDestruct(array_begin, array_begin + move_to); } else { SEQAN_CHECKPOINT arrayConstructMove(array_begin + keep_from, array_begin + array_length, array_begin + move_to); arrayDestruct(array_begin, array_begin + array_length); } } else { SEQAN_CHECKPOINT arrayMove(array_begin + keep_from, array_begin + array_length, array_begin + move_to); arrayDestruct(array_begin, array_begin + move_to); arrayDestruct(array_begin + array_length - (keep_from - move_to), array_begin + array_length); } } template void arrayClearSpace(TIterator array_begin, size_t array_length, size_t keep_from, size_t move_to) { _arrayClearSpace_Default(array_begin, array_length, keep_from, move_to); } ////////////////////////////////////////////////////////////////////////////// //BitsPerValue ////////////////////////////////////////////////////////////////////////////// /** .Metafunction.BitsPerValue: ..summary:Number of bits needed to store a value. ..signature:BitsPerValue::VALUE ..param.T:A class. ..returns.param.VALUE:Number of bits needed to store $T$. ...default:$sizeof * 8$ ..see:Metafunction.ValueSize */ template struct BitsPerValue { enum { VALUE = sizeof(TValue) * 8 }; }; template struct BitsPerValue: public BitsPerValue {}; ////////////////////////////////////////////////////////////////////////////// //ValueSize ////////////////////////////////////////////////////////////////////////////// /** .Metafunction.ValueSize: ..summary:Number of different values a value type object can have. ..signature:ValueSize::VALUE ..param.T:A class. ..returns.param.VALUE:Value size of $T$. ..remarks ...text:This function is only defined for integral types like $unsigned int$, $double$ or @Spec.Dna@. ..see:Metafunction.Value */ template struct ValueSize { enum { VALUE = 1 << BitsPerValue::VALUE }; }; template struct ValueSize: public ValueSize {}; template < typename T > struct _SupremumValueUnsigned { static const T VALUE; }; template < typename T > struct _SupremumValueSigned { static const T VALUE; }; template < typename T > struct _InfimumValueUnsigned { static const T VALUE; }; template < typename T > struct _InfimumValueSigned { static const T VALUE; }; template < typename T > const T _SupremumValueUnsigned::VALUE = ~(T)0; template < typename T > const T _SupremumValueSigned::VALUE = ( (((T)1 << (BitsPerValue::VALUE - 2)) - 1) << 1) + 1; template < typename T > const T _InfimumValueUnsigned::VALUE = 0; template < typename T > const T _InfimumValueSigned::VALUE = ~(T)_SupremumValueSigned::VALUE; template < typename T, typename TParent = typename IF< TYPECMP< typename _MakeSigned::Type, T >::VALUE, _SupremumValueSigned, _SupremumValueUnsigned >::Type > struct SupremumValue: public TParent { }; template < typename T, typename TParent = typename IF< TYPECMP< typename _MakeSigned::Type, T >::VALUE, _InfimumValueSigned, _InfimumValueUnsigned >::Type > struct InfimumValue: public TParent { }; ////////////////////////////////////////////////////////////////////////////// }// namespace SEQAN_NAMESPACE_MAIN #endif //#ifndef SEQAN_HEADER_... ugene-1.9.8/src/plugins_3rdparty/bowtie/src/bowtie/SeqAn-1.1/seqan/basic/basic_alphabet_simple.h0000644000175000017500000011374711651544326031146 0ustar ilyailya /*========================================================================== SeqAn - The Library for Sequence Analysis http://www.seqan.de ============================================================================ Copyright (C) 2007 This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. ============================================================================ $Id: basic_alphabet_simple.h,v 1.1 2008/08/25 16:20:02 langmead Exp $ ==========================================================================*/ #ifndef SEQAN_HEADER_BASIC_ALPHABET_SIMPLE_H #define SEQAN_HEADER_BASIC_ALPHABET_SIMPLE_H namespace SEQAN_NAMESPACE_MAIN { ////////////////////////////////////////////////////////////////////////////// //Class that is used for various simple value types ////////////////////////////////////////////////////////////////////////////// /** .Class.SimpleType: ..cat:Basic ..summary:Implementation for "simple" types. ..signature:SimpleType ..param.TValue:Type that stores the values of an instance. ...remarks:TValue must be a simple type. ...metafunction:Metafunction.Value ..param.TSpec:Specialization tag. ...metafunction:Metafunction.Spec ..remarks: ...text:A "simple type" is a C++ type that can be constructed without constructor, destructed without destructor and copied without copy constructor or assignment operator. All basic types (like $char$, $int$ or $float$) are simple. Pointers, references and arrays of simple types are simple. POD types ("plain old data types"), that are - simplified spoken - C++-types that already existed in C, are simple too. ...text:Arrays of simple types can be copied very fast by memory manipulation routines, but the default implementation of functions like @Function.arrayCopyForward@ and @Function.arrayCopy@ are not optimized for simple types this way. But for classes derived from $SimpleType$, optimized variants of array manipulation functions are applied. ...text:Note that simple types need not to be derived or specialized from $SimpleType$, but it could be convenient to do so. ..implements:Concept.Simple Type */ template struct SimpleType { //____________________________________________________________________________ TValue value; //____________________________________________________________________________ SimpleType() { SEQAN_CHECKPOINT } //____________________________________________________________________________ SimpleType(SimpleType const & other) { SEQAN_CHECKPOINT assign(*this, other); } template SimpleType(T const & other) { SEQAN_CHECKPOINT assign(*this, other); } //____________________________________________________________________________ SimpleType & operator=(SimpleType const & other) { SEQAN_CHECKPOINT assign(*this, other); return *this; } template SimpleType & operator=(T const & other) { SEQAN_CHECKPOINT assign(*this, other); return *this; } //____________________________________________________________________________ ~SimpleType() { SEQAN_CHECKPOINT } //____________________________________________________________________________ //this cannot be a template since a template would be in conflict to //the template c'tor operator long() const { SEQAN_CHECKPOINT long c; assign(c, *this); return c; } operator unsigned long() const { SEQAN_CHECKPOINT unsigned long c; assign(c, *this); return c; } operator int() const { SEQAN_CHECKPOINT int c; assign(c, *this); return c; } operator unsigned int() const { SEQAN_CHECKPOINT unsigned int c; assign(c, *this); return c; } operator short() const { SEQAN_CHECKPOINT short c; assign(c, *this); return c; } operator unsigned short() const { SEQAN_CHECKPOINT unsigned short c; assign(c, *this); return c; } operator char() const { SEQAN_CHECKPOINT char c; assign(c, *this); return c; } operator signed char() const { SEQAN_CHECKPOINT signed char c; assign(c, *this); return c; } operator unsigned char() const { SEQAN_CHECKPOINT unsigned char c; assign(c, *this); return c; } //____________________________________________________________________________ }; ////////////////////////////////////////////////////////////////////////////// // METAFUNCTIONS ////////////////////////////////////////////////////////////////////////////// ///.Metafunction.IsSimple.param.T.type:Class.SimpleType template struct IsSimple > { typedef True Type; }; ////////////////////////////////////////////////////////////////////////////// ///.Metafunction.Value.param.T.type:Class.SimpleType template struct Value > { typedef TValue Type; }; template struct Value const > { typedef TValue const Type; }; ////////////////////////////////////////////////////////////////////////////// ///.Metafunction.Spec.param.T.type:Class.SimpleType template struct Spec > { typedef TSpec Type; }; template struct Spec const > { typedef TSpec Type; }; ////////////////////////////////////////////////////////////////////////////// template struct Iterator, Standard> { typedef SimpleType * Type; // typedef Iter, SimpleIterator> * Type; }; template struct Iterator const, Standard> { typedef SimpleType const * Type; // typedef Iter const, SimpleIterator> * Type; }; ////////////////////////////////////////////////////////////////////////////// // FUNCTIONS ////////////////////////////////////////////////////////////////////////////// template inline typename _RemoveConst::Type convertImpl(Convert const, SimpleType const & source_) { SEQAN_CHECKPOINT typename _RemoveConst::Type target_; assign(target_, source_); return target_; } ////////////////////////////////////////////////////////////////////////////// template inline TStream & operator << (TStream & stream, SimpleType const & data) { SEQAN_CHECKPOINT stream << convert(data); return stream; } ////////////////////////////////////////////////////////////////////////////// template inline TStream & operator >> (TStream & stream, SimpleType & data) { SEQAN_CHECKPOINT char c; stream >> c; assign(data, c); return stream; } ////////////////////////////////////////////////////////////////////////////// // assign ////////////////////////////////////////////////////////////////////////////// ///.Function.assign.param.target.type:Class.SimpleType ///.Function.assign.param.source.type:Class.SimpleType template inline void assign(SimpleType & target, SimpleType & source) { SEQAN_CHECKPOINT target.value = source.value; } template inline void assign(SimpleType & target, SimpleType const & source) { SEQAN_CHECKPOINT target.value = source.value; } //____________________________________________________________________________ template inline void assign(SimpleType & target, TSource & source) { SEQAN_CHECKPOINT target.value = source; } template inline void assign(SimpleType & target, TSource const & source) { SEQAN_CHECKPOINT target.value = source; } //____________________________________________________________________________ // Assign Proxy to SimpleType //??? Diese Funktionen wurden noetig wegen eines seltsamen VC++-Verhaltens template inline void assign(SimpleType & target, Proxy & source) { SEQAN_CHECKPOINT target.value = getValue(source); } template inline void assign(SimpleType & target, Proxy const & source) { SEQAN_CHECKPOINT target.value = getValue(source); } //____________________________________________________________________________ //INTEGRAL TYPES //note: it is not possible to write a single function here since "assign" //must be specialized for the first argument at the first place //int template inline void assign(int & c_target, SimpleType & source) { SEQAN_CHECKPOINT c_target = source.value; } template inline void assign(int & c_target, SimpleType const & source) { SEQAN_CHECKPOINT c_target = source.value; } //unsigned int template inline void assign(unsigned int & c_target, SimpleType & source) { SEQAN_CHECKPOINT c_target = source.value; } template inline void assign(unsigned int & c_target, SimpleType const & source) { SEQAN_CHECKPOINT c_target = source.value; } //short template inline void assign(short & c_target, SimpleType & source) { SEQAN_CHECKPOINT c_target = source.value; } template inline void assign(short & c_target, SimpleType const & source) { SEQAN_CHECKPOINT c_target = source.value; } //unsigned short template inline void assign(unsigned short & c_target, SimpleType & source) { SEQAN_CHECKPOINT c_target = source.value; } template inline void assign(unsigned short & c_target, SimpleType const & source) { SEQAN_CHECKPOINT c_target = source.value; } //char template inline void assign(char & c_target, SimpleType & source) { SEQAN_CHECKPOINT c_target = source.value; } template inline void assign(char & c_target, SimpleType const & source) { SEQAN_CHECKPOINT c_target = source.value; } //signed char template inline void assign(signed char & c_target, SimpleType & source) { SEQAN_CHECKPOINT c_target = source.value; } template inline void assign(signed char & c_target, SimpleType const & source) { SEQAN_CHECKPOINT c_target = source.value; } //unsigned char template inline void assign(unsigned char & c_target, SimpleType & source) { SEQAN_CHECKPOINT c_target = source.value; } template inline void assign(unsigned char & c_target, SimpleType const & source) { SEQAN_CHECKPOINT c_target = source.value; } ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// // CompareType ////////////////////////////////////////////////////////////////////////////// /**.Metafunction.CompareType: ..summary:Type to convert other types for comparisons. ..signature:CompareType::Type ..param.TLeft:Type of the left operand of a comparison. ..param.TRight:Type of the right operand of a comparison. ..return.Type:The Type in which the arguments are converted in order to compare them. ..remarks:Comparisons are for example operators like $==$ or $<$. ..remarks.text:Note that there is no rule that guarantees that $CompareType::Type$ is the same as $CompareType::Type$. It is also possible, that only one of these two types is defined. ..remarks.text:This metafunction is used for the implementation of comparisons that involve @Class.SimpleType@. */ //???TODO: muss geprueft werden, ob diese Metafunktion noch ausgeweitet oder aber versteckt wird. template struct CompareType; template struct CompareType { typedef T Type; }; //____________________________________________________________________________ template struct CompareType, TRight> { typedef TRight Type; }; ////////////////////////////////////////////////////////////////////////////// // operator == template inline bool operator == (SimpleType const & left_, TRight const & right_) { SEQAN_CHECKPOINT typedef SimpleType TLeft; typedef typename CompareType::Type TCompareType; return convert(left_) == convert(right_); } template inline bool operator == (TLeft const & left_, SimpleType const & right_) { SEQAN_CHECKPOINT typedef SimpleType TRight; typedef typename CompareType::Type TCompareType; return convert(left_) == convert(right_); } template inline bool operator == (SimpleType const & left_, SimpleType const & right_) { SEQAN_CHECKPOINT typedef SimpleType TLeft; typedef SimpleType TRight; typedef typename CompareType::Type TCompareType; return convert(left_) == convert(right_); } template inline bool operator == (SimpleType const & left_, SimpleType const & right_) { SEQAN_CHECKPOINT return convert(left_) == convert(right_); } template inline bool operator == (Proxy const & left_, SimpleType const & right_) { SEQAN_CHECKPOINT typedef Proxy TLeft; typedef SimpleType TRight; typedef typename CompareType::Type TCompareType; return convert(left_) == convert(right_); } template inline bool operator == (SimpleType const & left_, Proxy const & right_) { SEQAN_CHECKPOINT typedef SimpleType TLeft; typedef Proxy TRight; typedef typename CompareType::Type TCompareType; return convert(left_) == convert(right_); } //____________________________________________________________________________ // operator != template inline bool operator != (SimpleType const & left_, TRight const & right_) { SEQAN_CHECKPOINT typedef SimpleType TLeft; typedef typename CompareType::Type TCompareType; return convert(left_) != convert(right_); } template inline bool operator != (TLeft const & left_, SimpleType const & right_) { SEQAN_CHECKPOINT typedef SimpleType TRight; typedef typename CompareType::Type TCompareType; return convert(left_) != convert(right_); } template inline bool operator != (SimpleType const & left_, SimpleType const & right_) { SEQAN_CHECKPOINT typedef SimpleType TLeft; typedef SimpleType TRight; typedef typename CompareType::Type TCompareType; return convert(left_) != convert(right_); } template inline bool operator != (SimpleType const & left_, SimpleType const & right_) { SEQAN_CHECKPOINT return convert(left_) != convert(right_); } template inline bool operator != (Proxy const & left_, SimpleType const & right_) { SEQAN_CHECKPOINT typedef Proxy TLeft; typedef SimpleType TRight; typedef typename CompareType::Type TCompareType; return convert(left_) != convert(right_); } template inline bool operator != (SimpleType const & left_, Proxy const & right_) { SEQAN_CHECKPOINT typedef SimpleType TLeft; typedef Proxy TRight; typedef typename CompareType::Type TCompareType; return convert(left_) != convert(right_); } //____________________________________________________________________________ // operator < template inline bool operator < (SimpleType const & left_, TRight const & right_) { SEQAN_CHECKPOINT typedef SimpleType TLeft; typedef typename CompareType::Type TCompareType; return convert(left_) < convert(right_); } template inline bool operator < (TLeft const & left_, SimpleType const & right_) { SEQAN_CHECKPOINT typedef SimpleType TRight; typedef typename CompareType::Type TCompareType; return convert(left_) < convert(right_); } template inline bool operator < (SimpleType const & left_, SimpleType const & right_) { SEQAN_CHECKPOINT typedef SimpleType TLeft; typedef SimpleType TRight; typedef typename CompareType::Type TCompareType; return convert(left_) < convert(right_); } template inline bool operator < (SimpleType const & left_, SimpleType const & right_) { SEQAN_CHECKPOINT return convert(left_) < convert(right_); } template inline bool operator < (Proxy const & left_, SimpleType const & right_) { SEQAN_CHECKPOINT typedef Proxy TLeft; typedef SimpleType TRight; typedef typename CompareType::Type TCompareType; return convert(left_) < convert(right_); } template inline bool operator < (SimpleType const & left_, Proxy const & right_) { SEQAN_CHECKPOINT typedef SimpleType TLeft; typedef Proxy TRight; typedef typename CompareType::Type TCompareType; return convert(left_) < convert(right_); } //____________________________________________________________________________ // operator <= template inline bool operator <= (SimpleType const & left_, TRight const & right_) { SEQAN_CHECKPOINT typedef SimpleType TLeft; typedef typename CompareType::Type TCompareType; return convert(left_) <= convert(right_); } template inline bool operator <= (TLeft const & left_, SimpleType const & right_) { SEQAN_CHECKPOINT typedef SimpleType TRight; typedef typename CompareType::Type TCompareType; return convert(left_) <= convert(right_); } template inline bool operator <= (SimpleType const & left_, SimpleType const & right_) { SEQAN_CHECKPOINT typedef SimpleType TLeft; typedef SimpleType TRight; typedef typename CompareType::Type TCompareType; return convert(left_) <= convert(right_); } template inline bool operator <= (SimpleType const & left_, SimpleType const & right_) { SEQAN_CHECKPOINT return convert(left_) <= convert(right_); } template inline bool operator <= (Proxy const & left_, SimpleType const & right_) { SEQAN_CHECKPOINT typedef Proxy TLeft; typedef SimpleType TRight; typedef typename CompareType::Type TCompareType; return convert(left_) <= convert(right_); } template inline bool operator <= (SimpleType const & left_, Proxy const & right_) { SEQAN_CHECKPOINT typedef SimpleType TLeft; typedef Proxy TRight; typedef typename CompareType::Type TCompareType; return convert(left_) <= convert(right_); } //____________________________________________________________________________ // operator > template inline bool operator > (SimpleType const & left_, TRight const & right_) { SEQAN_CHECKPOINT typedef SimpleType TLeft; typedef typename CompareType::Type TCompareType; return convert(left_) > convert(right_); } template inline bool operator > (TLeft const & left_, SimpleType const & right_) { SEQAN_CHECKPOINT typedef SimpleType TRight; typedef typename CompareType::Type TCompareType; return convert(left_) > convert(right_); } template inline bool operator > (SimpleType const & left_, SimpleType const & right_) { SEQAN_CHECKPOINT typedef SimpleType TLeft; typedef SimpleType TRight; typedef typename CompareType::Type TCompareType; return convert(left_) > convert(right_); } template inline bool operator > (SimpleType const & left_, SimpleType const & right_) { SEQAN_CHECKPOINT return convert(left_) > convert(right_); } template inline bool operator > (Proxy const & left_, SimpleType const & right_) { SEQAN_CHECKPOINT typedef Proxy TLeft; typedef SimpleType TRight; typedef typename CompareType::Type TCompareType; return convert(left_) > convert(right_); } template inline bool operator > (SimpleType const & left_, Proxy const & right_) { SEQAN_CHECKPOINT typedef SimpleType TLeft; typedef Proxy TRight; typedef typename CompareType::Type TCompareType; return convert(left_) > convert(right_); } //____________________________________________________________________________ // operator >= template inline bool operator >= (SimpleType const & left_, TRight const & right_) { SEQAN_CHECKPOINT typedef SimpleType TLeft; typedef typename CompareType::Type TCompareType; return convert(left_) >= convert(right_); } template inline bool operator >= (TLeft const & left_, SimpleType const & right_) { SEQAN_CHECKPOINT typedef SimpleType TRight; typedef typename CompareType::Type TCompareType; return convert(left_) >= convert(right_); } template inline bool operator >= (SimpleType const & left_, SimpleType const & right_) { SEQAN_CHECKPOINT typedef SimpleType TLeft; typedef SimpleType TRight; typedef typename CompareType::Type TCompareType; return convert(left_) >= convert(right_); } template inline bool operator >= (SimpleType const & left_, SimpleType const & right_) { SEQAN_CHECKPOINT return convert(left_) >= convert(right_); } template inline bool operator >= (Proxy const & left_, SimpleType const & right_) { SEQAN_CHECKPOINT typedef Proxy TLeft; typedef SimpleType TRight; typedef typename CompareType::Type TCompareType; return convert(left_) >= convert(right_); } template inline bool operator >= (SimpleType const & left_, Proxy const & right_) { SEQAN_CHECKPOINT typedef SimpleType TLeft; typedef Proxy TRight; typedef typename CompareType::Type TCompareType; return convert(left_) >= convert(right_); } ////////////////////////////////////////////////////////////////////////////// template inline bool lexLess(SimpleType<_T, TSpec> const &_Left, SimpleType<_T, TSpec> const &_Right) { // return lexicographical _Left < _Right typedef typename _MakeUnsigned<_T>::Type TUnsigned; return (TUnsigned)(_Left.value) < (TUnsigned)(_Right.value); } ////////////////////////////////////////////////////////////////////////////// template inline SimpleType & operator ++ (SimpleType & me) { ++me.value; return me; } template inline SimpleType operator ++ (SimpleType & me, int) { SimpleType dummy = me; ++me.value; return dummy; } ////////////////////////////////////////////////////////////////////////////// template inline SimpleType & operator -- (SimpleType & me) { --me.value; return me; } template inline SimpleType operator -- (SimpleType & me, int) { SimpleType dummy = me; --me.value; return dummy; } ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// /** .Spec.Dna: ..cat:Alphabets ..summary:Alphabet for DNA. ..general:Class.SimpleType ..signature:Dna ..remarks: ...text:The @Metafunction.ValueSize@ of $Dna$ is 4. The nucleotides are enumerated this way: $'A' = 0, 'C' = 1, 'G' = 2, 'T' = 3$. ...text:Objects of type $Dna$ can be converted to various other types and vice versa. An object that has a value not in ${'A', 'C', 'G', 'T'}$ is converted to $'A'$. ...text:$Dna$ is typedef for $SimpleType$, while $_Dna$ is a helper specialization tag class. ..see:Metafunction.ValueSize ..see:Spec.Dna5 */ struct _Dna {}; typedef SimpleType Dna; template <> struct ValueSize< Dna > { enum { VALUE = 4 }; }; template <> struct BitsPerValue< Dna > { enum { VALUE = 2 }; }; //____________________________________________________________________________ /** .Spec.Dna5: ..cat:Alphabets ..summary:Alphabet for DNA including 'N' character. ..general:Class.SimpleType ..signature:Dna5 ..remarks: ...text:The @Metafunction.ValueSize@ of $Dna5$ is 5. The nucleotides are enumerated this way: $'A' = 0, 'C' = 1, 'G' = 2, 'T' = 3$. The 'N' character ("unkown nucleotide") is encoded by 4. ...text:Objects of type $Dna5$ can be converted to various other types and vice versa. An object that has a value not in ${'A', 'C', 'G', 'T'}$ is converted to $'N'$. ...text:$Dna5$ is typedef for $SimpleType$, while $_Dna5$ is a helper specialization tag class. ..see:Metafunction.ValueSize */ struct _Dna5 {}; typedef SimpleType Dna5; template <> struct ValueSize< Dna5 > { enum { VALUE = 5 }; }; template <> struct BitsPerValue< Dna5 > { enum { VALUE = 3 }; }; //____________________________________________________________________________ /** .Spec.Iupac: ..cat:Alphabets ..summary:Iupac code for DNA. ..general:Class.SimpleType ..signature:Iupac ..remarks: ...text:The @Metafunction.ValueSize@ of $Iupac$ is 16. The nucleotides are enumerated from 0 to 15 in this order: 'U'=0, 'T', 'A', 'W', 'C', 'Y', 'M', 'H', 'G', 'K', 'R', 'D', 'S', 'B', 'V', 'N'=15. ...text:Objects of type $Iupac$ can be converted to various other types and vice versa. Unkown values are converted to $'N'$. ...text:$Iupac$ is typedef for $SimpleType$, while $_Iupac$ is a helper specialization tag class. ..see:Metafunction.ValueSize */ struct _Iupac {}; typedef SimpleType Iupac; template <> struct ValueSize< Iupac > { enum { VALUE = 16 }; }; template <> struct BitsPerValue< Iupac > { enum { VALUE = 4 }; }; //____________________________________________________________________________ /** .Spec.AminoAcid: ..cat:Alphabets ..summary:Iupac code for amino acids. ..general:Class.SimpleType ..signature:AminoAcid ..remarks: ...text:The @Metafunction.ValueSize@ of $AminoAcid$ is 24. ...text:The amino acids are enumerated from 0 to 15 in this order: ...text:'A'=0, 'R', 'N', 'D', 'C', 'Q', 'E', 'G', 'H', 'I', 'L', 'K', 'M', 'F', 'P', 'S', 'T', 'W', 'Y', 'V'=19. ...text:The remaining 4 symbols are: ...text: 'B'=20 (Aspartic Acid, Asparagine), 'Z'=21 (Glutamic Acid, Glutamine), 'X'=22 (unknown), '*'=23 (terminator) ...text:Objects of type $AminoAcid$ can be converted to $char$ and vice versa. Unkown values are converted to $'X'$. ...text:$AminoAcid$ is typedef for $SimpleType$, while $_AminoAcid$ is a helper specialization tag class. ..see:Metafunction.ValueSize */ struct _AminoAcid {}; typedef SimpleType AminoAcid; template <> struct ValueSize< AminoAcid > { enum { VALUE = 24 }; }; template <> struct BitsPerValue< AminoAcid > { enum { VALUE = 5 }; }; ////////////////////////////////////////////////////////////////////////////// //ASCII inline void assign(Ascii & c_target, Dna const & source) { SEQAN_CHECKPOINT c_target = _Translate_Table_Dna5_2_Ascii<>::VALUE[source.value]; } //____________________________________________________________________________ inline void assign(Ascii & c_target, Dna5 const & source) { SEQAN_CHECKPOINT c_target = _Translate_Table_Dna5_2_Ascii<>::VALUE[source.value]; } //____________________________________________________________________________ inline void assign(Ascii & c_target, Iupac const & source) { SEQAN_CHECKPOINT c_target = _Translate_Table_Iupac_2_Ascii<>::VALUE[source.value]; } //____________________________________________________________________________ inline void assign(Ascii & c_target, AminoAcid const & source) { SEQAN_CHECKPOINT c_target = _Translate_Table_AA_2_Ascii<>::VALUE[source.value]; } ////////////////////////////////////////////////////////////////////////////// //DNA (4 letters) template <> struct CompareType { typedef Dna Type; }; inline void assign(Dna & target, Byte c_source) { SEQAN_CHECKPOINT target.value = _Translate_Table_Byte_2_Dna<>::VALUE[c_source]; } //____________________________________________________________________________ template <> struct CompareType { typedef Dna Type; }; inline void assign(Dna & target, Ascii c_source) { SEQAN_CHECKPOINT target.value = _Translate_Table_Ascii_2_Dna<>::VALUE[(unsigned char)c_source]; } //____________________________________________________________________________ template <> struct CompareType { typedef Dna Type; }; inline void assign(Dna & target, Unicode c_source) { SEQAN_CHECKPOINT target.value = _Translate_Table_Ascii_2_Dna<>::VALUE[(unsigned char) c_source]; } //____________________________________________________________________________ template <> struct CompareType { typedef Dna Type; }; inline void assign(Dna & target, Dna5 const & c_source) { SEQAN_CHECKPOINT target.value = c_source.value & 0x03; } //____________________________________________________________________________ template <> struct CompareType { typedef Dna Type; }; inline void assign(Dna & target, Iupac const & source) { SEQAN_CHECKPOINT target.value = _Translate_Table_Iupac_2_Dna<>::VALUE[source.value]; } ////////////////////////////////////////////////////////////////////////////// //DNA (5 letters) template <> struct CompareType { typedef Dna5 Type; }; inline void assign(Dna5 & target, Byte c_source) { SEQAN_CHECKPOINT target.value = _Translate_Table_Byte_2_Dna5<>::VALUE[c_source]; } //____________________________________________________________________________ template <> struct CompareType { typedef Dna5 Type; }; inline void assign(Dna5 & target, Ascii c_source) { SEQAN_CHECKPOINT target.value = _Translate_Table_Ascii_2_Dna5<>::VALUE[(unsigned char) c_source]; } //____________________________________________________________________________ template <> struct CompareType { typedef Dna5 Type; }; inline void assign(Dna5 & target, Unicode c_source) { SEQAN_CHECKPOINT target.value = _Translate_Table_Ascii_2_Dna5<>::VALUE[(unsigned char) c_source]; } //____________________________________________________________________________ template <> struct CompareType { typedef Dna5 Type; }; inline void assign(Dna5 & target, Iupac const & source) { SEQAN_CHECKPOINT target.value = _Translate_Table_Iupac_2_Dna5<>::VALUE[source.value]; } //____________________________________________________________________________ template <> struct CompareType { typedef Dna Type; }; inline void assign(Dna5 & target, Dna const & c_source) { SEQAN_CHECKPOINT target.value = c_source.value; } ////////////////////////////////////////////////////////////////////////////// //IUPAC (4 bits) template <> struct CompareType { typedef Iupac Type; }; inline void assign(Iupac & target, Byte c_source) { SEQAN_CHECKPOINT target.value = _Translate_Table_Byte_2_Iupac<>::VALUE[c_source]; } //____________________________________________________________________________ template <> struct CompareType { typedef Iupac Type; }; inline void assign(Iupac & target, Ascii c_source) { SEQAN_CHECKPOINT target.value = _Translate_Table_Ascii_2_Iupac<>::VALUE[(unsigned char) c_source]; } //____________________________________________________________________________ template <> struct CompareType { typedef Iupac Type; }; inline void assign(Iupac & target, Unicode c_source) { SEQAN_CHECKPOINT target.value = _Translate_Table_Ascii_2_Iupac<>::VALUE[(unsigned char) c_source]; } //____________________________________________________________________________ inline void assign(Iupac & target, Dna const & source) { SEQAN_CHECKPOINT target.value = _Translate_Table_Dna5_2_Iupac<>::VALUE[source.value]; } //____________________________________________________________________________ inline void assign(Iupac & target, Dna5 const & source) { SEQAN_CHECKPOINT target.value = _Translate_Table_Dna5_2_Iupac<>::VALUE[source.value]; } ////////////////////////////////////////////////////////////////////////////// //Amino Acid (5 bits) template <> struct CompareType { typedef AminoAcid Type; }; inline void assign(AminoAcid & target, Byte c_source) { SEQAN_CHECKPOINT target.value = _Translate_Table_Byte_2_AA<>::VALUE[c_source]; } //____________________________________________________________________________ template <> struct CompareType { typedef AminoAcid Type; }; inline void assign(AminoAcid & target, Ascii c_source) { SEQAN_CHECKPOINT target.value = _Translate_Table_Ascii_2_AA<>::VALUE[(unsigned char) c_source]; } //____________________________________________________________________________ template <> struct CompareType { typedef AminoAcid Type; }; inline void assign(AminoAcid & target, Unicode c_source) { SEQAN_CHECKPOINT target.value = _Translate_Table_Ascii_2_AA<>::VALUE[(unsigned char) c_source]; } ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// }// namespace SEQAN_NAMESPACE_MAIN #endif //#ifndef SEQAN_HEADER_... ugene-1.9.8/src/plugins_3rdparty/bowtie/src/bowtie/SeqAn-1.1/seqan/basic/basic_definition.h0000644000175000017500000002117511651544326030136 0ustar ilyailya /*========================================================================== SeqAn - The Library for Sequence Analysis http://www.seqan.de ============================================================================ Copyright (C) 2007 This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. ============================================================================ $Id: basic_definition.h,v 1.1 2008/08/25 16:20:01 langmead Exp $ ==========================================================================*/ #ifndef SEQAN_HEADER_BASIC_DEFINITION_H #define SEQAN_HEADER_BASIC_DEFINITION_H namespace SEQAN_NAMESPACE_MAIN { ////////////////////////////////////////////////////////////////////////////// template struct Tag { }; ////////////////////////////////////////////////////////////////////////////// /** .Tag.Default: ..summary:Tag that specifies default behavior. ..tag.Default:Use default behavior. */ struct Default_; typedef Tag const Default; ////////////////////////////////////////////////////////////////////////////// /** .Tag.Move Switch: ..summary:Switch to force move. ..tag.Move:Move instead of assign. ..remarks.text:The difference between move constructor and copy constructor is that the source object is not copied but moved into the target object. The source object can lose its content and will be empty after this operation in this case. A move constructor can sigificantly faster than a copy constructor. ..example.code:String source("hello"); String target(source, Move()); // source is moved to target std::cout << source; //nothing printed since source lost content std::cout << target; //"hello" ..see:Function.move */ struct Move_; typedef Tag const Move; ////////////////////////////////////////////////////////////////////////////// //Pass to c'tor of iterator to move it to the end struct GoEnd_; typedef Tag const GoEnd; ////////////////////////////////////////////////////////////////////////////// //construct without initializing struct MinimalCtor_; typedef Tag const MinimalCtor; //construct with initializing struct NonMinimalCtor_; typedef Tag const NonMinimalCtor; ////////////////////////////////////////////////////////////////////////////// /** .Tag.Logical Values: ..summary:Tag that represents true and false. ..tag.True:The logical value "true". ..tag.False:The logical value "false". */ struct True { enum { VALUE = true }; }; struct False { enum { VALUE = false }; }; ////////////////////////////////////////////////////////////////////////////// /** .Tag.Nothing: ..summary:Tag that represents an absent parameter or an absent type. ..tag.Nothing:Omit parameter. */ ///Empty Data Class. struct Nothing {}; ////////////////////////////////////////////////////////////////////////////// // returns TTo const, if TFrom is const, TTo otherwise template struct _CopyConst { typedef TTo Type; }; template struct _CopyConst { typedef TTo const Type; }; ////////////////////////////////////////////////////////////////////////////// /** .Internal._RemoveConst: ..signature:_RemoveConst ..returns:$t$ if $T$ is $t const$, otherwise $T$. */ template struct _RemoveConst { typedef T Type; }; template struct _RemoveConst: public _RemoveConst {}; template struct _RemoveConst { typedef typename _RemoveConst::Type & Type; }; template struct _RemoveConst { typedef typename _RemoveConst::Type * Type; }; template struct _RemoveConst { typedef T * Type; }; ////////////////////////////////////////////////////////////////////////////// /** .Internal._MakeUnsigned: ..signature:_MakeUnsigned ..returns:$unsigned t$ if $T$ is not $unsigned t$, otherwise $T$. */ template struct _MakeUnsigned { typedef T Type; }; template struct _MakeUnsigned { typedef typename _MakeUnsigned::Type const Type; }; template <> struct _MakeUnsigned { typedef unsigned char Type; }; template <> struct _MakeUnsigned { typedef unsigned char Type; }; template <> struct _MakeUnsigned { typedef unsigned int Type; }; template <> struct _MakeUnsigned { typedef unsigned short Type; }; template <> struct _MakeUnsigned { typedef unsigned long Type; }; /* template <> struct _MakeUnsigned { typedef unsigned long long Type; }; */ ////////////////////////////////////////////////////////////////////////////// /** .Internal._MakeSigned: ..signature:_MakeSigned ..returns:$signed t$ if $T$ is not $signed t$, otherwise $T$. */ template struct _MakeSigned { typedef T Type; }; template struct _MakeSigned { typedef typename _MakeSigned::Type const Type; }; template <> struct _MakeSigned { typedef signed char Type; }; template <> struct _MakeSigned { typedef signed char Type; }; template <> struct _MakeSigned { typedef signed int Type; }; template <> struct _MakeSigned { typedef signed short Type; }; template <> struct _MakeSigned { typedef signed long Type; }; /* template <> struct _MakeSigned { typedef signed long long Type; }; */ ////////////////////////////////////////////////////////////////////////////// /** .Internal._ClassIdentifier: ..signature:void * _ClassIdentifier::getID() ..returns:A void * that identifies $T$. ...text:The returned values of two calls of $getID$ are equal if and only if the used type $T$ was the same. */ template struct _ClassIdentifier { static inline void * getID() { SEQAN_CHECKPOINT static bool _id_dummy; return &_id_dummy; } }; ////////////////////////////////////////////////////////////////////////////// /** .Function.log2: ..cat:Miscellaneous ..summary:Computes logarithm of base 2 for integer types ..signature:unsigned int log2(i) ..param.i:An integer type. ..returns:The largest integer smaller or equal than the logarithm of $i$. */ #if 0 template struct _Log2_Impl { template static inline unsigned int log2(T val, unsigned int offset) { unsigned int val2 = val >> (BITS_MAX / 2); if (val2) { val = val2; offset += BITS_MAX / 2; } return _Log2_Impl::log2(val, offset); } }; template <> struct _Log2_Impl<1> { template static inline unsigned int log2(T /*val*/, unsigned int offset) { return offset; } }; template inline unsigned int log2(T val) { enum { // BITS_PER_VALUE = BitsPerValue::VALUE //TODO??? BITS_PER_VALUE = sizeof(T) * 8 }; return _Log2_Impl::log2(val, 0); } #endif template inline TValue _intPow(TValue a, TExponent b) { SEQAN_CHECKPOINT TValue ret = 1; while (b != 0) { if (b & 1) ret *= a; a *= a; b >>= 1; } return ret; } ////////////////////////////////////////////////////////////////////////////// // to avoid conflicts with non-standard macros and namespaces // we define our own Min/Max functions template inline const _Tx& _min(const _Tx& _Left, const _Tx& _Right) { // return smaller of _Left and _Right if (_Left < _Right) return _Left; else return _Right; } template inline _Tx _min(const _Tx& _Left, const _Ty& _Right) { // return smaller of _Left and _Right return (_Right < _Left ? _Right : _Left); } template inline const _Ty& _max(const _Ty& _Left, const _Ty& _Right) { // return larger of _Left and _Right if (_Left < _Right) return _Right; else return _Left; } ////////////////////////////////////////////////////////////////////////////// template struct _IsSameType { enum {VALUE = false}; typedef False Type; }; template struct _IsSameType { enum {VALUE = true}; typedef True Type; }; template inline bool _isSameType() { return _IsSameType::VALUE; } ////////////////////////////////////////////////////////////////////////////// } //namespace SEQAN_NAMESPACE_MAIN #endif //#ifndef SEQAN_HEADER_... ugene-1.9.8/src/plugins_3rdparty/bowtie/src/bowtie/SeqAn-1.1/seqan/basic/basic_aggregates.h0000644000175000017500000005615411651544326030124 0ustar ilyailya /*========================================================================== SeqAn - The Library for Sequence Analysis http://www.seqan.de ============================================================================ Copyright (C) 2007 This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. ============================================================================ $Id: basic_aggregates.h,v 1.1 2008/08/25 16:20:01 langmead Exp $ ==========================================================================*/ #ifndef SEQAN_HEADER_BASIC_AGGREGATES_H #define SEQAN_HEADER_BASIC_AGGREGATES_H namespace SEQAN_NAMESPACE_MAIN { //____________________________________________________________________________ struct _Compressed; typedef Tag<_Compressed> Compressed; // for Pairs with small i1-values // store i1 and i2 in one word of type i2 // use the upper bits for i1 and the lower bits for i2 template struct CutCompressed { enum { bitSizeI1 = Log2::VALUE }; }; /** .Class.Pair: ..cat:Aggregates ..summary:Stores two arbitrary objects. ..signature:Pair ..param.T1:The type of the first object. ..param.T2:The type of the second object. ..param.Compression:If $Compressed$, the pair is stored in a more space efficient way (useful for external storage). ...note:When compression is enabled, referring to members is not allowed. ...default:$void$, no compression (faster access). .Memfunc.Pair#Pair: ..class:Class.Pair ..summary:Constructor ..signature:Pair () ..signature:Pair (pair) ..signature:Pair (i1, i2) ..param.pair:Other Pair object. (copy constructor) ..param.i1:T1 object. ..param.i2:T2 object. .Memvar.Pair#i1: ..class:Class.Pair ..summary:T1 object .Memvar.Pair#i2: ..class:Class.Pair ..summary:T2 object */ // standard storage template struct Pair { typedef _T1 T1; typedef _T2 T2; _T1 i1; _T2 i2; inline Pair() {} inline Pair(Pair const &_p): i1(_p.i1), i2(_p.i2) {} inline Pair(_T1 const &_i1, _T2 const &_i2): i1(_i1), i2(_i2) {} template inline Pair(Pair<__T1, __T2, __TCompression> const &_p): i1(getValueI1(_p)), i2(getValueI2(_p)) {} }; // unaligned and unpadded storage (space efficient) #ifdef PLATFORM_WINDOWS #pragma pack(push,1) #endif template struct Pair<_T1, _T2, Compressed> { typedef _T1 T1; typedef _T2 T2; _T1 i1; _T2 i2; inline Pair() {} inline Pair(Pair const &_p): i1(_p.i1), i2(_p.i2) {} inline Pair(_T1 const &_i1, _T2 const &_i2): i1(_i1), i2(_i2) {} template inline Pair(Pair<__T1, __T2, __TCompression> const &_p): i1(getValueI1(_p)), i2(getValueI2(_p)) {} } #ifndef PLATFORM_WINDOWS __attribute__((packed)) #endif ; #ifdef PLATFORM_WINDOWS #pragma pack(pop) #endif #ifdef PLATFORM_WINDOWS #pragma pack(push,1) #endif template struct Pair<_T1, _T2, CutCompressed > { typedef _T1 T1; typedef _T2 T2; typedef _T2 T12; T12 i12; enum { bitSizeI1 = CutCompressed::bitSizeI1 }; enum { bitShiftI1 = BitsPerValue::VALUE - bitSizeI1 }; inline Pair() {} inline Pair(Pair const &_p): i12(_p.i12) {} inline Pair(_T1 const &_i1, _T2 const &_i2): i12(((T12)_i1 << bitShiftI1) + (T12)_i2) {} template inline Pair(Pair<__T1, __T2, __TCompression> const &_p): i12(((T12)getValueI1(_p) << bitShiftI1) + (T12)getValueI2(_p)) {} } #ifndef PLATFORM_WINDOWS __attribute__((packed)) #endif ; #ifdef PLATFORM_WINDOWS #pragma pack(pop) #endif template std::ostream& operator<<(std::ostream &out, Pair<_T1,_T2,TCompression> const &p) { out << "< " << getValueI1(p) << " , " << getValueI2(p) << " >"; return out; } template struct Value< Pair, 1 > { typedef T1 Type; }; template struct Value< Pair, 2 > { typedef T2 Type; }; template struct Spec< Pair > { typedef TCompression Type; }; //____________________________________________________________________________ template struct Key< Pair > { typedef TKey Type; }; template struct Cargo< Pair > { typedef TCargo Type; }; //____________________________________________________________________________ /** .Class.Triple: ..cat:Aggregates ..summary:Stores three arbitrary objects. ..signature:Triple ..param.T1:The type of the first object. ..param.T2:The type of the second object. ..param.T3:The type of the third object. ..param.Compression:If $Compressed$, the triple is stored in a more space efficient way (useful for external storage). ...note:When compression is enabled, referring to members is not allowed. ...default:$void$, no compression (faster access). .Memfunc.Triple#Triple: ..class:Class.Triple ..summary:Constructor ..signature:Triple () ..signature:Triple (triple) ..signature:Triple (i1, i2, i3) ..param.triple:Other Triple object. (copy constructor) ..param.i1:T1 object. ..param.i2:T2 object. ..param.i3:T3 object. .Memvar.Triple#i1: ..class:Class.Triple ..summary:T1 object .Memvar.Triple#i2: ..class:Class.Triple ..summary:T2 object .Memvar.Triple#i3: ..class:Class.Triple ..summary:T3 object */ // standard storage template struct Triple { typedef _T1 T1; typedef _T2 T2; typedef _T3 T3; _T1 i1; _T2 i2; _T3 i3; inline Triple() {} inline Triple(Triple const &_p): i1(_p.i1), i2(_p.i2), i3(_p.i3) {} inline Triple(_T1 const &_i1, _T2 const &_i2, _T3 const &_i3): i1(_i1), i2(_i2), i3(_i3) {} template inline Triple(Triple<__T1, __T2, __T3, __TCompression> const &_p): i1(getValueI1(_p)), i2(getValueI2(_p)), i3(getValueI3(_p)) {} }; // unaligned and unpadded storage (space efficient) #ifdef PLATFORM_WINDOWS #pragma pack(push,1) #endif template struct Triple<_T1, _T2, _T3, Compressed> { typedef _T1 T1; typedef _T2 T2; typedef _T3 T3; _T1 i1; _T2 i2; _T3 i3; inline Triple() {} inline Triple(Triple const &_p): i1(_p.i1), i2(_p.i2), i3(_p.i3) {} inline Triple(_T1 const &_i1, _T2 const &_i2, _T3 const &_i3): i1(_i1), i2(_i2), i3(_i3) {} template inline Triple(Triple<__T1, __T2, __T3, __TCompression> const &_p): i1(getValueI1(_p)), i2(getValueI2(_p)), i3(getValueI3(_p)) {} } #ifndef PLATFORM_WINDOWS __attribute__((packed)) #endif ; #ifdef PLATFORM_WINDOWS #pragma pack(pop) #endif template std::ostream& operator<<(std::ostream &out, Triple<_T1,_T2,_T3,TCompression> const &t) { out << "< " << getValueI1(t) << " , " << getValueI2(t) << " , " << getValueI3(t) << " >"; return out; } template struct Value< Triple, 1 > { typedef T1 Type; }; template struct Value< Triple, 2 > { typedef T2 Type; }; template struct Value< Triple, 3 > { typedef T3 Type; }; template struct Spec< Triple > { typedef TCompression Type; }; //____________________________________________________________________________ /** .Class.Tuple: ..cat:Aggregates ..summary:A plain fixed-length string. ..signature:Tuple ..param.T:The value type, that is the type of characters stored in the tuple. ..param.size:The size/length of the tuple. ...remarks:In contrast to @Class.String@ the length of Tuple is fixed. ..param.compress:Enable/Disable compression. ..param.compress:If $void$, no compression is used. ..param.compress:If $Compressed$, the characters are stored as a bit sequence in an ordinal type (char, ..., __int64) ...remarks:Only useful for small alphabets and small tuple sizes (|Sigma|^size <= 2^64) as for DNA or protein m-grams) ...default:void. ..see:Spec.Sampler */ // standard storage template struct Tuple { typedef _T T; enum { size = _size }; _T i[_size]; template inline _T& operator[](TPos k) { SEQAN_ASSERT(k >= 0 && k < size); return i[k]; } template inline const _T& operator[](TPos k) const { SEQAN_ASSERT(k >= 0 && k < size); return i[k]; } inline _T* operator&() { return i; } inline const _T* operator&() const { return i; } // has to be inline because elements (like this tuple) of packed structs can't be arguments template inline SSS const assignValueAt(TPos k, SSS const source) { return i[k] = source; } }; template < unsigned char _size > struct _BitVector { typedef typename _BitVector<_size + 1>::Type Type; }; template <> struct _BitVector<8> { typedef unsigned char Type; }; template <> struct _BitVector<16> { typedef unsigned short Type; }; template <> struct _BitVector<32> { typedef unsigned int Type; }; template <> struct _BitVector<64> { typedef __int64 Type; }; template <> struct _BitVector<255> { typedef __int64 Type; }; // bit-compressed storage (space efficient) #ifdef PLATFORM_WINDOWS #pragma pack(push,1) #endif template struct Tuple<_T, _size, Compressed> { typedef _T T; enum { size = _size }; enum { bitSize = BitsPerValue<_T>::VALUE }; enum { bitMask = (1 << bitSize) - 1 }; enum { mask = (1 << (size * bitSize)) - 1 }; typedef typename _BitVector< bitSize * size >::Type CT; CT i; /* inline Tuple() { SEQAN_ASSERT(bitSize * size <= sizeof(CT) * 8); } */ template inline const _T operator[](TPos k) const { SEQAN_ASSERT(k >= 0 && k < size); return (i >> (size - 1 - k) * bitSize) & bitMask; } template inline Tuple operator=(Tuple<_T, __size, Compressed> const &_right) { i = _right.i; return *this; } template inline CT operator<<=(TShiftSize shift) { return i = (i << (shift * bitSize)) & mask; } template inline CT operator<<(TShiftSize shift) const { return (i << (shift * bitSize)) & mask; } template inline CT operator>>=(TShiftSize shift) { return i = (i >> (shift * bitSize)); } template inline CT operator>>(TShiftSize shift) const { return i >> (shift * bitSize); } template inline void operator|=(T const &t) { i |= t; } template inline void operator|=(SimpleType const &t) { i |= t.value; } inline CT* operator&() { return &i; } inline const CT* operator&() const { return &i; } // has to be inline because elements (like this tuple) of packed structs can't be arguments template inline SSS const assignValueAt(TPos k, SSS const source) { typedef Tuple<_T, _size, Compressed> Tup; typename Tup::CT mask = Tup::bitMask << ((_size - 1 - k) * bitSize); i = (i & ~mask) | ((CT)source << ((_size - 1 - k) * bitSize)); return source; } } #ifndef PLATFORM_WINDOWS __attribute__((packed)) #endif ; #ifdef PLATFORM_WINDOWS #pragma pack(pop) #endif ////////////////////////////////////////////////////////////////////////////// // length template inline unsigned length(Tuple<_T, _size, TCompression> const &) { return _size; } ///.Metafunction.LENGTH.param.T.type:Class.Tuple template struct LENGTH< Tuple<_T, _size, TCompression> > { enum { VALUE = _size }; }; ////////////////////////////////////////////////////////////////////////////// // assignValueAt template inline TSource & assignValueAt(TObject &me, TPos k, TSource &source) { assign(value(me, k), source); return source; } template inline TSource const & assignValueAt(TObject &me, TPos k, TSource const &source) { assign(value(me, k), source); return source; } template inline SSS const assignValueAt(Tuple &me, TPos k, SSS const source) { return me.i[k] = source; } template inline SSS const assignValueAt(Tuple &me, TPos k, SSS const source) { typedef Tuple Tup; typename Tup::CT mask = Tup::bitMask << ((_size - 1 - k) * me.bitSize); me.i = (me.i & ~mask) | source << ((_size - 1 - k) * me.bitSize); return source; } template inline SimpleType const & assignValueAt(Tuple &me, TPos k, SimpleType const &source) { typedef Tuple Tup; typename Tup::CT mask = Tup::bitMask << ((_size - 1 - k) * me.bitSize); me.i = (me.i & ~mask) | source.value << ((_size - 1 - k) * me.bitSize); return source; } ////////////////////////////////////////////////////////////////////////////// // clear template inline void clear(Tuple &me) { memset(&(me.i)); } template inline void clear(Tuple &me) { me.i = 0; } ////////////////////////////////////////////////////////////////////////////// // optimized compares template inline bool operator<(Tuple const &_left, Tuple const &_right) { return _left.i < _right.i; } template inline bool operator>(Tuple const &_left, Tuple const &_right) { return _left.i > _right.i; } template inline bool operator==(Tuple const &_left, Tuple const &_right) { return _left.i == _right.i; } template inline bool operator!=(Tuple const &_left, Tuple const &_right) { return _left.i != _right.i; } ////////////////////////////////////////////////////////////////////////////// // optimized shifts struct _TupleShiftLeftWorker { template static inline void body(Arg &arg, unsigned I) { arg[I-1] = arg[I]; } }; struct _TupleShiftRightWorker { template static inline void body(Arg &arg, unsigned I) { arg[I] = arg[I-1]; } }; template inline void shiftLeft(Tuple<_T, _size, TCompression> &me) { LOOP<_TupleShiftLeftWorker, _size - 1>::run(me); } template inline void shiftRight(Tuple<_T, _size, TCompression> &me) { LOOP_REVERSE<_TupleShiftRightWorker, _size - 1>::run(me); } template inline void shiftLeft(Tuple<_T, _size, Compressed> &me) { me<<=1; } template inline void shiftRight(Tuple<_T, _size, Compressed> &me) { me>>=1; } ////////////////////////////////////////////////////////////////////////////// // standard output template std::ostream& operator<<(std::ostream& out, Tuple<_T,_size,TCompression> const &a) { out << "["; if (a.size > 0) out << a[0]; for(unsigned j = 1; j < a.size; ++j) out << " " << a[j]; out << "]"; return out; } template struct Value< Tuple<_T, _size, TCompression> > { typedef _T Type; }; template struct Spec< Tuple<_T, _size, TCompression> > { typedef TCompression Type; }; ////////////////////////////////////////////////////////////////////////////// // getValueIx template inline T1 getValueI1(Pair const &pair) { return pair.i1; } template inline T2 getValueI2(Pair const &pair) { return pair.i2; } template inline T1 getValueI1(Pair > const &pair) { typedef Pair > TPair; return pair.i12 >> TPair::bitShiftI1; } template inline T2 getValueI2(Pair > const &pair) { typedef Pair > TPair; return pair.i12 & (((typename TPair::T12)1 << TPair::bitShiftI1) - 1); } //____________________________________________________________________________ template inline T1 getValueI1(Triple const &triple) { return triple.i1; } template inline T2 getValueI2(Triple const &triple) { return triple.i2; } template inline T3 getValueI3(Triple const &triple) { return triple.i3; } ////////////////////////////////////////////////////////////////////////////// // assignValueIx template inline void assignValueI1(Pair &pair, T const &_i) { pair.i1 = _i; } template inline void assignValueI2(Pair &pair, T const &_i) { pair.i2 = _i; } template inline void assignValueI1(Pair > &pair, T const &_i) { typedef Pair > TPair; pair.i12 = ((typename TPair::T12)_i << TPair::bitShiftI1) | (pair.i12 & (((typename TPair::T12)1 << TPair::bitShiftI1) - 1)); } template inline void assignValueI2(Pair > &pair, T const &_i) { typedef Pair > TPair; pair.i12 = (pair.i12 & ~(((typename TPair::T12)1 << TPair::bitShiftI1) - 1)) | _i; } //____________________________________________________________________________ template inline T const assignValueI1(Triple &triple, T const &_i) { return triple.i1 = _i; } template inline T const assignValueI2(Triple &triple, T const &_i) { return triple.i2 = _i; } template inline T const assignValueI3(Triple &triple, T const &_i) { return triple.i3 = _i; } ////////////////////////////////////////////////////////////////////////////// // operator ==/!= for pairs and triples template inline bool operator==(Pair const &_left, Pair const &_right) { return _left.i1 == _right.i1 && _left.i2 == _right.i2; } template inline bool operator!=(Pair const &_left, Pair const &_right) { return _left.i1 != _right.i1 || _left.i2 != _right.i2; } template inline bool operator==(Pair > const &_left, Pair > const &_right) { return _left.i12 == _right.i12; } template inline bool operator!=(Pair > const &_left, Pair > const &_right) { return _left.i12 != _right.i12; } //____________________________________________________________________________ template < typename L1, typename L2, typename L3, typename LCompression, typename R1, typename R2, typename R3, typename RCompression> inline bool operator==(Triple const &_left, Triple const &_right) { return _left.i1 == _right.i1 && _left.i2 == _right.i2 && _left.i3 == _right.i3; } template < typename L1, typename L2, typename L3, typename LCompression, typename R1, typename R2, typename R3, typename RCompression> inline bool operator!=(Triple const &_left, Triple const &_right) { return _left.i1 != _right.i1 || _left.i2 != _right.i2 || _left.i3 != _right.i3; } }// namespace SEQAN_NAMESPACE_MAIN #endif //#ifndef SEQAN_HEADER_... ugene-1.9.8/src/plugins_3rdparty/bowtie/src/bowtie/SeqAn-1.1/seqan/basic/basic_holder.h0000644000175000017500000006454611651544326027274 0ustar ilyailya /*========================================================================== SeqAn - The Library for Sequence Analysis http://www.seqan.de ============================================================================ Copyright (C) 2007 This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. ============================================================================ $Id: basic_holder.h,v 1.1 2008/08/25 16:20:01 langmead Exp $ ==========================================================================*/ #ifndef SEQAN_HEADER_BASIC_HOLDER_H #define SEQAN_HEADER_BASIC_HOLDER_H namespace SEQAN_NAMESPACE_MAIN { ////////////////////////////////////////////////////////////////////////////// // addRef ////////////////////////////////////////////////////////////////////////////// /** .Function.addRef: ..summary:Called when dependency is added. ..cat:Dependent Objects ..signature:addRef(host) ..param.host:The host object. ..remarks.text:A call of this function denotes that a client object is about to become dependent on $host$. ..remarks.text:The default behavior is: Do nothing. ..see:Class.Holder */ template inline void addRef(T & /*me*/) {// general: do nothing SEQAN_CHECKPOINT } template inline void addRef(T const & /*me*/) {// general: do nothing SEQAN_CHECKPOINT } ////////////////////////////////////////////////////////////////////////////// // releaseRef ////////////////////////////////////////////////////////////////////////////// /** .Function.releaseRef: ..summary:Called when dependency is released. ..cat:Dependent Objects ..signature:releaseRef(host) ..param.host:The host object. ..remarks.text:A call of this function denotes that a former dependent client object ceases to be dependent on $host$. ..remarks.text:The default behavior is: Do nothing. ..see:Class.Holder ..see:Function.addRef */ template inline void releaseRef(T & /*me*/) {// general: do nothing SEQAN_CHECKPOINT } template inline void releaseRef(T const & /*me*/) {// general: do nothing SEQAN_CHECKPOINT } ////////////////////////////////////////////////////////////////////////////// // Tags struct Simple; struct Tristate; ////////////////////////////////////////////////////////////////////////////// // Holder ////////////////////////////////////////////////////////////////////////////// /** .Class.Holder: ..cat:Basic ..summary:Manages relationship to another object. ..signature:Holder ..param.TValue:Type of the managed object. ...metafunction:Metafunction.Value ..param.TSpec:The specializing type. ...metafunction:Metafunction.Spec ...default:$Tristate$ ..remarks.text:The main purpose of this class is to facilitate the handling of member objects. If we want class $A$ to be dependent on or the owner of another object of class $B$, then we add a data member of type $Holder$ to $A$. $Holder$ offers some useful access functions, stores the kind of relationship between $A$ and $B$, and executes all needed @Function.addRef@ and @Function.releaseRef@ calls. */ template struct Holder; ////////////////////////////////////////////////////////////////////////////// // METAFUNCTIONS ////////////////////////////////////////////////////////////////////////////// ///.Metafunction.Value.param.T.type:Class.Holder template struct Value< Holder > { typedef typename _RemoveConst::Type Type; }; template struct Value< Holder const> { typedef typename _RemoveConst::Type Type; }; ////////////////////////////////////////////////////////////////////////////// ///.Metafunction.Spec.param.T.type:Class.Holder template struct Spec< Holder > { typedef TSpec Type; }; template struct Spec< Holder const> { typedef TSpec Type; }; ////////////////////////////////////////////////////////////////////////////// ///.Metafunction.Reference.param.T.type:Class.Holder template struct Reference< Holder > { typedef typename Value< Holder >::Type & Type; }; template struct Reference< Holder const> { typedef typename Value< Holder const>::Type & Type; }; ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// // Tristate Holder ////////////////////////////////////////////////////////////////////////////// /** .Spec.Tristate Holder ..cat:Holders ..summary:Holder that can be empty, dependent, or owner. ..signature:Holder ..param.TValue:Type of the managed object. ..general:Class.Holder ..remarks.text:A tristate holder $A$ that holds an object $B$ has one of the following states: ..remarks.text:- owner: $A$ is the owner of $B$. If $A$ is destroyed, $B$ will be destroyed automatically. ..remarks.text:- dependent: $A$ depends on $B$. $B$ should not be destroyed as long as $A$ is used. ..remarks.text:- empty: there is currently no object reference stored in the holder $A$. ..remarks.text:The state of the holder can be determined by @Function.empty@ and @Function.dependent@. */ template struct Holder { public: enum EHolderState { EMPTY = 0, OWNER = 1, DEPENDENT = ~0 }; // typedef typename _RemoveConst::Type TValue_NotConst; typedef typename Value::Type THostValue; typename _Pointer::Type data_value; EHolderState data_state; //____________________________________________________________________________ /** .Memfunc.Holder: ..class:Class.Holder ..summary:Constructor ..signature:Holder () ..signature:Holder (holder) ..signature:Holder (value) ..param.holder:Another holder object. ..param.value:An object of type $TValue$. ..remarks.text: The default constructor creates a holder that is in state 'empty'. If a $value$ is passed to the constructor, the holder will be in state 'dependent'. */ Holder(): data_state(EMPTY) { SEQAN_CHECKPOINT } Holder(Holder const & source_): data_state(EMPTY) { SEQAN_CHECKPOINT assign(*this, source_); } Holder(typename _Parameter::Type value_): data_state(EMPTY) { SEQAN_CHECKPOINT setValue(*this, value_); } Holder(typename _ConstParameter::Type value_): data_state(EMPTY) { SEQAN_CHECKPOINT assignValue(*this, value_); } /** .Memfunc.~Holder: ..class:Class.Holder ..summary:Destructor ..signature:~Holder() ..remarks.text: If the holder is in state 'owner', the holded object will be destoyed too. */ ~Holder() { SEQAN_CHECKPOINT clear(*this); } //____________________________________________________________________________ Holder const & operator = (Holder const & source_) { SEQAN_CHECKPOINT assign(*this, source_); return *this; } Holder const & operator = (typename _ConstParameter::Type value_) { SEQAN_CHECKPOINT assignValue(*this, value_); return *this; } operator typename _Parameter::Type() { SEQAN_CHECKPOINT return *data_value; } //____________________________________________________________________________ }; ////////////////////////////////////////////////////////////////////////////// // FUNCTIONS ////////////////////////////////////////////////////////////////////////////// ///.Function.empty.param.object.type:Class.Holder template inline bool empty(Holder const & me) { SEQAN_CHECKPOINT return (me.data_state == Holder::EMPTY); } ////////////////////////////////////////////////////////////////////////////// ///.Function.dependent.param.object.type:Class.Holder template inline bool dependent(Holder const & me) { SEQAN_CHECKPOINT return (me.data_state == Holder::DEPENDENT); } ////////////////////////////////////////////////////////////////////////////// ///.Function.clear.param.object.type:Class.Holder ///.Function.clear.remarks.text:If $clear$ is applied on a @Class.Holder@ object, ///the state of this object is set to 'empty'. template inline void clear(Holder & me) { switch (me.data_state) { case Holder::EMPTY: break; case Holder::DEPENDENT: { SEQAN_CHECKPOINT releaseRef(_toParameter(me.data_value)); me.data_state = Holder::EMPTY; } break; default: /*Holder::OWNER*/ { SEQAN_CHECKPOINT valueDestruct(me.data_value); deallocate(me, me.data_value, 1); me.data_state = Holder::EMPTY; } break; } } ////////////////////////////////////////////////////////////////////////////// /** .Function.create: ..summary:Makes an object to owner of its content. ..cat:Dependent Objects ..signature:create(holder [, object]) ..param.holder:A holder object. ...type:Class.Holder ..param.object:Object from which a copy is made and stored in $holder$. (optional) ...type:Metafunction.Value.Value::Type ..remarks.text:After this operation, $holder$ will be in state 'owner'. If $object$ is specified, $holder$ will hold a copy of $object$ at the end of this function. If $object$ is not specified, the action depends on the former state of $holder$: ..remarks.text:- If the state of $holder$ was 'empty', a new object is default constructed and stored into $holder$. ..remarks.text:- If the state of $holder$ was 'dependent', a copy of the former object is made and stored into $holder$. ..remarks.text:- If the state of $holder$ was already 'owner', nothing happens. ..see:Class.Holder */ template inline void create(Holder & me) { typedef Holder THolder; switch (me.data_state) { case Holder::EMPTY: { SEQAN_CHECKPOINT allocate(me, me.data_value, 1); valueConstruct(me.data_value); me.data_state = THolder::OWNER; } break; case THolder::DEPENDENT: { SEQAN_CHECKPOINT typename _Parameter::Type old_value = value(me); allocate(me, me.data_value, 1); valueConstruct(me.data_value, old_value); me.data_state = THolder::OWNER; releaseRef(old_value); } break; default:; } } //____________________________________________________________________________ template inline void create(Holder & me, typename _Parameter::Type value_) { SEQAN_CHECKPOINT if (me.data_state == Holder::OWNER) { assign(_toParameter(me.data_value), value_); return; } clear(me); allocate(me, me.data_value, 1); valueConstruct(me.data_value, value_); me.data_state = Holder::OWNER; } ////////////////////////////////////////////////////////////////////////////// /** .Function.detach: ..summary:Makes an object independent from other objects. ..cat:Dependent Objects ..signature:detach(object) ..param.object:An object. ...type:Class.Holder ..remarks: After this function, $object$ does not depends from any other entity outside of $object$, like a @Function.source@ or a @Function.host@, and @Function.dependent.dependent(object)@ returns $false$ ..see:Function.source ..see:Function.host ..see:Function.createSource ..see:Function.create */ template inline void detach(Holder & me) { SEQAN_CHECKPOINT create(me); } ////////////////////////////////////////////////////////////////////////////// /** .Function.setValue: ..cat:Content Manipulation ..summary:Makes holder dependent. ..signature:setValue(holder, object) ..param.holder:A holder object. ...type:Class.Holder ..param.object:Object from which $holder$ will be dependent. ...type:Metafunction.Value.Value::Type ..remarks.text:After this operation, $holder$ will be dependent in state 'dependent'. ..see:Class.Holder */ template inline void setValue(Holder & me, typename _Parameter::Type value_) { SEQAN_CHECKPOINT typedef typename Value >::Type THolderType; clear(me); me.data_value = _toPointer(value_); me.data_state = Holder::DEPENDENT; addRef(_toParameter(me.data_value)); } template inline void setValue(Holder & me, TValue2 const & value_) { SEQAN_CHECKPOINT set(value(me), value_); } ////////////////////////////////////////////////////////////////////////////// ///.Function.value.param.object.type:Class.Holder template inline typename Reference >::Type value(Holder & me) { SEQAN_CHECKPOINT typedef Holder THolder; if (empty(me)) { allocate(me, me.data_value, 1); valueConstruct(me.data_value); me.data_state = THolder::OWNER; } typedef typename Value >::Type THolderType; return _toParameter(me.data_value); } template inline typename Reference const>::Type value(Holder const & me) { SEQAN_CHECKPOINT SEQAN_ASSERT(!empty(me)); typedef typename Value >::Type THolderType; return _toParameter(me.data_value); } ////////////////////////////////////////////////////////////////////////////// ///.Function.assignValue.param.object.type:Class.Holder template inline void assignValue(Holder & me, TSource const & value_) { SEQAN_CHECKPOINT typedef typename Value >::Type THostValue; if (empty(me)) { create(me, value_); } else { assign(_toParameter(me.data_value), value_); } } ////////////////////////////////////////////////////////////////////////////// ///.Function.moveValue.param.object.type:Class.Holder template inline void moveValue(Holder & me, TSource const & value_) { SEQAN_CHECKPOINT if (empty(me)) { create(me, value_); } else { move(value(me), value_); } } ////////////////////////////////////////////////////////////////////////////// ///.Function.assign.param.target.type:Class.Holder ///.Function.assign.param.source.type:Class.Holder template inline void assign(Holder & target_, Holder const & source_) { SEQAN_CHECKPOINT switch(source_.data_state) { case Holder::EMPTY: { clear(target_); } break; case Holder::OWNER: { assignValue(target_, value(source_)); } break; default: /*case Holder::DEPENDENT*/ { setValue(target_, value(source_)); } break; } } ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// // Simple Holder ////////////////////////////////////////////////////////////////////////////// //??? TODO: Documentation of Simple Holder template struct Holder { typedef typename Value::Type THolderValue; typedef typename _Parameter::Type THolderParameter; mutable THolderValue data_value; //____________________________________________________________________________ Holder() { SEQAN_CHECKPOINT } Holder(Holder & source_): data_value(source_.data_value) { SEQAN_CHECKPOINT } Holder(Holder const & source_): data_value(source_.data_value) { SEQAN_CHECKPOINT } template Holder(TSource & value_): data_value(value_) { SEQAN_CHECKPOINT } template Holder(TSource const & value_): data_value(value_) { SEQAN_CHECKPOINT } /* Holder(TValue const & value_): data_value(value_) { SEQAN_CHECKPOINT } */ ~Holder() { SEQAN_CHECKPOINT } //____________________________________________________________________________ Holder const & operator = (Holder const & source_) { SEQAN_CHECKPOINT data_value = source_.data_value; return *this; } Holder const & operator = (THolderValue const & value_) { SEQAN_CHECKPOINT data_value = value_; return *this; } operator THolderParameter() { SEQAN_CHECKPOINT return *data_value; } //____________________________________________________________________________ }; ////////////////////////////////////////////////////////////////////////////// // FUNCTIONS ////////////////////////////////////////////////////////////////////////////// template inline bool empty(Holder const & me) { SEQAN_CHECKPOINT return false; } ////////////////////////////////////////////////////////////////////////////// template inline bool dependent(Holder const & me) { SEQAN_CHECKPOINT return false; } ////////////////////////////////////////////////////////////////////////////// template inline void clear(Holder & me) { SEQAN_CHECKPOINT } ////////////////////////////////////////////////////////////////////////////// template inline void create(Holder & me) { SEQAN_CHECKPOINT } //____________________________________________________________________________ template inline void create(Holder & me, TValue const & value_) { SEQAN_CHECKPOINT me.data_value = value_; } ////////////////////////////////////////////////////////////////////////////// template inline void detach(Holder & me) { SEQAN_CHECKPOINT } ////////////////////////////////////////////////////////////////////////////// template inline void setValue(Holder & me, TValue const & value_) { SEQAN_CHECKPOINT me.data_value = value_; } ////////////////////////////////////////////////////////////////////////////// template inline typename Reference >::Type value(Holder & me) { SEQAN_CHECKPOINT return me.data_value; } template inline typename Reference const>::Type value(Holder const & me) { SEQAN_CHECKPOINT return me.data_value; } ////////////////////////////////////////////////////////////////////////////// template inline void assignValue(Holder & me, TSource const & value_) { SEQAN_CHECKPOINT assignValue(me.data_value, value_); } ////////////////////////////////////////////////////////////////////////////// template inline void moveValue(Holder & me, TSource const & value_) { SEQAN_CHECKPOINT move(me.data_value, value_); } ////////////////////////////////////////////////////////////////////////////// template inline void assign(Holder & target_, Holder const & source_) { SEQAN_CHECKPOINT assignValue(target_, source_); } ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// // New Tristate Holder that works also on pointers ////////////////////////////////////////////////////////////////////////////// struct Tristate2; template struct Holder { public: enum EHolderState { EMPTY = 0, OWNER = 1, DEPENDENT = ~0 }; typedef typename Value::Type THostValue; TValue * data_value; EHolderState data_state; //____________________________________________________________________________ Holder(): data_state(EMPTY) { SEQAN_CHECKPOINT } Holder(Holder const & source_): data_state(EMPTY) { SEQAN_CHECKPOINT assign(*this, source_); } Holder(typename _Parameter::Type value_): data_state(EMPTY) { SEQAN_CHECKPOINT setValue(*this, value_); } Holder(typename _ConstParameter::Type value_): data_state(EMPTY) { SEQAN_CHECKPOINT assignValue(*this, value_); } ~Holder() { SEQAN_CHECKPOINT clear(*this); } //____________________________________________________________________________ Holder const & operator = (Holder const & source_) { SEQAN_CHECKPOINT assign(*this, source_); return *this; } Holder const & operator = (TValue const & value_) { SEQAN_CHECKPOINT assignValue(*this, value_); return *this; } operator TValue &() { SEQAN_CHECKPOINT return *data_value; } //____________________________________________________________________________ }; ////////////////////////////////////////////////////////////////////////////// // FUNCTIONS ////////////////////////////////////////////////////////////////////////////// ///.Function.empty.param.object.type:Class.Holder template inline bool empty(Holder const & me) { SEQAN_CHECKPOINT return (me.data_state == Holder::EMPTY); } ////////////////////////////////////////////////////////////////////////////// ///.Function.dependent.param.object.type:Class.Holder template inline bool dependent(Holder const & me) { SEQAN_CHECKPOINT return (me.data_state == Holder::DEPENDENT); } ////////////////////////////////////////////////////////////////////////////// ///.Function.clear.param.object.type:Class.Holder ///.Function.clear.remarks.text:If $clear$ is applied on a @Class.Holder@ object, ///the state of this object is set to 'empty'. template inline void clear(Holder & me) { switch (me.data_state) { case Holder::EMPTY: break; case Holder::DEPENDENT: { SEQAN_CHECKPOINT releaseRef(*(me.data_value)); me.data_state = Holder::EMPTY; } break; default: /*Holder::OWNER*/ { SEQAN_CHECKPOINT valueDestruct(me.data_value); deallocate(me, me.data_value, 1); me.data_state = Holder::EMPTY; } break; } } ////////////////////////////////////////////////////////////////////////////// template inline void create(Holder & me) { typedef Holder THolder; switch (me.data_state) { case Holder::EMPTY: { SEQAN_CHECKPOINT allocate(me, me.data_value, 1); valueConstruct(me.data_value); me.data_state = THolder::OWNER; } break; case THolder::DEPENDENT: { SEQAN_CHECKPOINT TValue & old_value = value(me); allocate(me, me.data_value, 1); valueConstruct(me.data_value, old_value); me.data_state = THolder::OWNER; releaseRef(old_value); } break; default:; } } //____________________________________________________________________________ template inline void create(Holder & me, TValue const & value_) { SEQAN_CHECKPOINT if (me.data_state == Holder::OWNER) { assign(*(me.data_value), value_); return; } clear(me); allocate(me, me.data_value, 1); valueConstruct(me.data_value, value_); me.data_state = Holder::OWNER; } ////////////////////////////////////////////////////////////////////////////// template inline void detach(Holder & me) { SEQAN_CHECKPOINT create(me); } ////////////////////////////////////////////////////////////////////////////// template inline void setValue(Holder & me, TValue & value_) { SEQAN_CHECKPOINT typedef typename Value >::Type THolderType; clear(me); me.data_value = & value_; me.data_state = Holder::DEPENDENT; addRef(value_); } ////////////////////////////////////////////////////////////////////////////// ///.Function.value.param.object.type:Class.Holder template inline typename Reference >::Type value(Holder & me) { SEQAN_CHECKPOINT typedef Holder THolder; if (empty(me)) { allocate(me, me.data_value, 1); valueConstruct(me.data_value); me.data_state = THolder::OWNER; } typedef typename Value >::Type THolderType; return *(me.data_value); } template inline typename Reference const>::Type value(Holder const & me) { SEQAN_CHECKPOINT SEQAN_ASSERT(!empty(me)); return *(me.data_value); } ////////////////////////////////////////////////////////////////////////////// ///.Function.assignValue.param.object.type:Class.Holder template inline void assignValue(Holder & me, TSource const & value_) { SEQAN_CHECKPOINT typedef typename Value >::Type THostValue; if (empty(me)) { create(me, value_); } else { assign(*(me.data_value), value_); } } ////////////////////////////////////////////////////////////////////////////// ///.Function.moveValue.param.object.type:Class.Holder template inline void moveValue(Holder & me, TSource const & value_) { SEQAN_CHECKPOINT if (empty(me)) { create(me, value_); } else { move(value(me), value_); } } ////////////////////////////////////////////////////////////////////////////// ///.Function.assign.param.target.type:Class.Holder ///.Function.assign.param.source.type:Class.Holder template inline void assign(Holder & target_, Holder const & source_) { SEQAN_CHECKPOINT switch(source_.data_state) { case Holder::EMPTY: { clear(target_); } break; case Holder::OWNER: { assignValue(target_, value(source_)); } break; default: /*case Holder::DEPENDENT*/ { setValue(target_, value(source_)); } break; } } ////////////////////////////////////////////////////////////////////////////// } //namespace SEQAN_NAMESPACE_MAIN #endif //#ifndef SEQAN_HEADER_... ugene-1.9.8/src/plugins_3rdparty/bowtie/src/bowtie/SeqAn-1.1/seqan/basic/basic_allocator_to_std.h0000644000175000017500000001150411651544326031335 0ustar ilyailya /*========================================================================== SeqAn - The Library for Sequence Analysis http://www.seqan.de ============================================================================ Copyright (C) 2007 This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. ============================================================================ $Id: basic_allocator_to_std.h,v 1.1 2008/08/25 16:20:01 langmead Exp $ ==========================================================================*/ #ifndef SEQAN_HEADER_BASIC_ALLOCATOR_TO_STD_H #define SEQAN_HEADER_BASIC_ALLOCATOR_TO_STD_H namespace SEQAN_NAMESPACE_MAIN { ////////////////////////////////////////////////////////////////////////////// //helper caller for calling functions that have same name as member functions template inline void call_allocate(TMe & me, TValue * & data, TSize const count) { allocate(me, data, count); } template inline void call_deallocate(TMe & me, TValue * data, TSize const count) { deallocate(me, data, count); } ////////////////////////////////////////////////////////////////////////////// //Filter that adapts seqan allocator zu std allocator /** .Class.ToStdAllocator: ..summary:Emulates standard conform allocator. ..signature:ToStdAllocator ..param.THost:Type of the host allocator object. ...text:This object is used to call @Function.allocate@ and @Function.deallocate@. ..param.TValue:Type of allocated items. ..remarks:The member functions $allocate$ and $deallocate$ of $ToStdAllocator$ call the (globale) functions @Function.allocate@ and @Function.deallocate@, respectively. The globale functions get an allocator object as their first arguments. This allocator object is not the $ToStdAllocator$ object itself, but the host object that was given to the constructor. ..remarks: ..see:Function.allocate ..see:Function.deallocate */ template struct ToStdAllocator { typedef TValue value_type; typedef value_type * pointer; typedef value_type & reference; typedef value_type const * const_pointer; typedef value_type const & const_reference; // typedef typename THost::Size size_type; // typedef typename THost::Difference difference_type; typedef size_t size_type; typedef ptrdiff_t difference_type; /** .Memfunc.ToStdAllocator: ..summary:Constructor ..signature:ToStdAllocator(host) ..class:Class.ToStdAllocator ..param.host:The host object that is used as allocator for @Function.allocate@ and @Function.deallocate@. */ ToStdAllocator(THost & host): m_host(& host) { } ToStdAllocator(ToStdAllocator const & alloc): m_host(alloc.m_host) { } ToStdAllocator & operator= (ToStdAllocator const & alloc) { m_host = alloc.m_host; } ~ToStdAllocator() { } /** .Function.host: ..summary:The object a given object depends on. ..cat:Dependent Objects ..signature:host(object) ..param.object:An object. ...type:Class.ToStdAllocator ..returns:The host object. */ friend THost & host(ToStdAllocator & me) { return *me.m_host; } pointer allocate(size_type count) { value_type * ptr; call_allocate(*m_host, ptr, count); return pointer(ptr); } pointer allocate(size_type count, const void *) { value_type * ptr; call_allocate(*m_host, ptr, count); return pointer(ptr); } void deallocate(pointer data, size_type count) { call_deallocate(*m_host, data, count); } void construct(pointer ptr, const_reference data) { new(ptr) TValue(data); } void destroy(pointer ptr) { ptr->~TValue(); } pointer address(reference value) const { return (&value); } const_pointer address(const_reference value) const { return (&value); } size_type max_size() const { return ~0UL / sizeof(value_type); } template struct rebind { typedef ToStdAllocator other; }; private: THost * m_host; }; ////////////////////////////////////////////////////////////////////////////// //returns std-allocator type (for allocators) template struct StdAllocator { typedef ToStdAllocator Type; }; ////////////////////////////////////////////////////////////////////////////// } //namespace SEQAN_NAMESPACE_MAIN ////////////////////////////////////////////////////////////////////////////// #endif //#ifndef SEQAN_HEADER_... ugene-1.9.8/src/plugins_3rdparty/bowtie/src/bowtie/SeqAn-1.1/seqan/basic/basic_proxy.h0000644000175000017500000004027211651544326027166 0ustar ilyailya /*========================================================================== SeqAn - The Library for Sequence Analysis http://www.seqan.de ============================================================================ Copyright (C) 2007 This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. ============================================================================ $Id: basic_proxy.h,v 1.1 2008/08/25 16:20:02 langmead Exp $ ==========================================================================*/ #ifndef SEQAN_HEADER_BASIC_PROXY_H #define SEQAN_HEADER_BASIC_PROXY_H namespace SEQAN_NAMESPACE_MAIN { ////////////////////////////////////////////////////////////////////////////// // Proxy ////////////////////////////////////////////////////////////////////////////// /** .Class.Proxy: ..cat:Basic ..summary:Emulates object of another class. ..signature:Proxy ..param.TSpec:The specializing type. ...metafunction:Metafunction.Spec ..remarks.text:Use @Metafunction.Value@ to get the emulated type. An instance of $Proxy$ behaves like an object of its value type. $Proxy$ can be used as reference type (see @Metafunction.Reference@). ..remarks.text:Note that functions that are both general and specialized for the value type should be specialized for $Proxy$ too, since otherwise the general version will be called. */ template struct Proxy; ////////////////////////////////////////////////////////////////////////////// ///.Metafunction.Spec.param.T.type:Class.Proxy template struct Spec< Proxy > { typedef TSpec Type; }; template struct Spec< Proxy const> { typedef TSpec Type; }; ////////////////////////////////////////////////////////////////////////////// // Iterator Proxy ////////////////////////////////////////////////////////////////////////////// /** .Spec.Iterator Proxy: ..cat:Proxies ..general:Class.Proxy ..summary:Proxy that is implemented by an iterator. ..signature:Proxy > ..param.TIterator:Iterator type. ..remarks.text:The value type of an iterator proxy is the value type of the iterator $TIterator$. */ template struct IteratorProxy; //____________________________________________________________________________ template struct Proxy > { public: typedef typename Value::Type TValue; typedef typename GetValue::Type TAccessor; typedef typename _RemoveConst::Type TAccessor_NotConst; private: TIterator data_iterator; public: Proxy(TIterator const _it): data_iterator(_it) { SEQAN_CHECKPOINT } Proxy(Proxy const & _other): data_iterator(_other.data_iterator) { SEQAN_CHECKPOINT } ~Proxy() { SEQAN_CHECKPOINT } Proxy const & operator = (Proxy const & _other) { SEQAN_CHECKPOINT assignValue(data_iterator, getValue(_other.data_iterator)); return *this; } Proxy const & operator = (TValue const & _value) { SEQAN_CHECKPOINT assignValue(data_iterator, _value); return *this; } operator TAccessor_NotConst() { SEQAN_CHECKPOINT return getValue(data_iterator); } //____________________________________________________________________________ //not documented friend inline TIterator & iter(Proxy & me) { return me.data_iterator; } friend inline TIterator const & iter(Proxy const & me) { return me.data_iterator; } //____________________________________________________________________________ }; ////////////////////////////////////////////////////////////////////////////// // Metafunctions ////////////////////////////////////////////////////////////////////////////// ///.Metafunction.Value.param.T.type:Class.Proxy template struct Value< Proxy > >: Value { }; template struct Value< Proxy > const> { typedef typename Value::Type const Type; }; ////////////////////////////////////////////////////////////////////////////// ///.Metafunction.GetValue.param.T.type:Class.Proxy template struct GetValue< Proxy > >: GetValue { }; template struct GetValue< Proxy > const> { typedef typename GetValue::Type Type; }; ////////////////////////////////////////////////////////////////////////////// ///.Metafunction.Reference.param.T.type:Class.Proxy template struct Reference< Proxy > > { typedef Proxy > Type; }; template struct Reference< Proxy > const > { typedef Proxy > const Type; }; ////////////////////////////////////////////////////////////////////////////// ///.Metafunction.Size.param.T.type:Class.Proxy template struct Size< Proxy > >: Size { }; template struct Size< Proxy > const>: Size { }; ////////////////////////////////////////////////////////////////////////////// ///.Metafunction.Difference.param.T.type:Class.Proxy template struct Difference< Proxy > >: Difference { }; template struct Difference< Proxy > const>: Difference { }; ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// template typename GetValue >::Type getValue(Proxy & me) { return getValue(iter(me)); } template typename GetValue const>::Type getValue(Proxy const & me) { return getValue(iter(me)); } ////////////////////////////////////////////////////////////////////////////// // Comparison ////////////////////////////////////////////////////////////////////////////// template struct CompareType , T> { typedef typename Value >::Type TValue; typedef typename _RemoveConst::Type TValue_NoConst; typedef typename CompareType::Type Type; }; //???TODO: Symmetrie von CompareType herstellen //____________________________________________________________________________ template inline typename Convert >::Type convertImpl(Convert const, Proxy & source) { return convert(getValue(source)); } template inline typename Convert const>::Type convertImpl(Convert const, Proxy const & source) { return convert(getValue(source)); } ////////////////////////////////////////////////////////////////////////////// // operator == template inline bool operator == (Proxy const & left_, TRight const & right_) { SEQAN_CHECKPOINT typedef Proxy TLeft; typedef typename CompareType::Type TCompareType; return convert(left_) == convert(right_); } template inline bool operator == (TLeft const & left_, Proxy const & right_) { SEQAN_CHECKPOINT typedef Proxy TRight; typedef typename CompareType::Type TCompareType; return convert(left_) == convert(right_); } template inline bool operator == (Proxy const & left_, Proxy const & right_) { SEQAN_CHECKPOINT typedef Proxy TLeft; typedef Proxy TRight; typedef typename CompareType::Type TCompareType; return convert(left_) == convert(right_); } template inline bool operator == (Proxy const & left_, Proxy const & right_) { SEQAN_CHECKPOINT typedef typename GetValue >::Type TAccessor; return convert(left_) == convert(right_); } //____________________________________________________________________________ // operator != template inline bool operator != (Proxy const & left_, TRight const & right_) { SEQAN_CHECKPOINT typedef Proxy TLeft; typedef typename CompareType::Type TCompareType; return convert(left_) != convert(right_); } template inline bool operator != (TLeft const & left_, Proxy const & right_) { SEQAN_CHECKPOINT typedef Proxy TRight; typedef typename CompareType::Type TCompareType; return convert(left_) != convert(right_); } template inline bool operator != (Proxy const & left_, Proxy const & right_) { SEQAN_CHECKPOINT typedef Proxy TLeft; typedef Proxy TRight; typedef typename CompareType::Type TCompareType; return convert(left_) != convert(right_); } template inline bool operator != (Proxy const & left_, Proxy const & right_) { SEQAN_CHECKPOINT typedef typename GetValue >::Type TAccessor; return convert(left_) != convert(right_); } //____________________________________________________________________________ // operator < template inline bool operator < (Proxy const & left_, TRight const & right_) { SEQAN_CHECKPOINT typedef Proxy TLeft; typedef typename CompareType::Type TCompareType; return convert(left_) < convert(right_); } template inline bool operator < (TLeft const & left_, Proxy const & right_) { SEQAN_CHECKPOINT typedef Proxy TRight; typedef typename CompareType::Type TCompareType; return convert(left_) < convert(right_); } template inline bool operator < (Proxy const & left_, Proxy const & right_) { SEQAN_CHECKPOINT typedef Proxy TLeft; typedef Proxy TRight; typedef typename CompareType::Type TCompareType; return convert(left_) < convert(right_); } template inline bool operator < (Proxy const & left_, Proxy const & right_) { SEQAN_CHECKPOINT typedef typename GetValue >::Type TAccessor; return convert(left_) < convert(right_); } //____________________________________________________________________________ // operator <= template inline bool operator <= (Proxy const & left_, TRight const & right_) { SEQAN_CHECKPOINT typedef Proxy TLeft; typedef typename CompareType::Type TCompareType; return convert(left_) <= convert(right_); } template inline bool operator <= (TLeft const & left_, Proxy const & right_) { SEQAN_CHECKPOINT typedef Proxy TRight; typedef typename CompareType::Type TCompareType; return convert(left_) <= convert(right_); } template inline bool operator <= (Proxy const & left_, Proxy const & right_) { SEQAN_CHECKPOINT typedef Proxy TLeft; typedef Proxy TRight; typedef typename CompareType::Type TCompareType; return convert(left_) <= convert(right_); } template inline bool operator <= (Proxy const & left_, Proxy const & right_) { SEQAN_CHECKPOINT typedef typename GetValue >::Type TAccessor; return convert(left_) <= convert(right_); } //____________________________________________________________________________ // operator > template inline bool operator > (Proxy const & left_, TRight const & right_) { SEQAN_CHECKPOINT typedef Proxy TLeft; typedef typename CompareType::Type TCompareType; return convert(left_) > convert(right_); } template inline bool operator > (TLeft const & left_, Proxy const & right_) { SEQAN_CHECKPOINT typedef Proxy TRight; typedef typename CompareType::Type TCompareType; return convert(left_) > convert(right_); } template inline bool operator > (Proxy const & left_, Proxy const & right_) { SEQAN_CHECKPOINT typedef Proxy TLeft; typedef Proxy TRight; typedef typename CompareType::Type TCompareType; return convert(left_) > convert(right_); } template inline bool operator > (Proxy const & left_, Proxy const & right_) { SEQAN_CHECKPOINT typedef typename GetValue >::Type TAccessor; return convert(left_) > convert(right_); } //____________________________________________________________________________ // operator >= template inline bool operator >= (Proxy const & left_, TRight const & right_) { SEQAN_CHECKPOINT typedef Proxy TLeft; typedef typename CompareType::Type TCompareType; return convert(left_) >= convert(right_); } template inline bool operator >= (TLeft const & left_, Proxy const & right_) { SEQAN_CHECKPOINT typedef Proxy TRight; typedef typename CompareType::Type TCompareType; return convert(left_) >= convert(right_); } template inline bool operator >= (Proxy const & left_, Proxy const & right_) { SEQAN_CHECKPOINT typedef Proxy TLeft; typedef Proxy TRight; typedef typename CompareType::Type TCompareType; return convert(left_) >= convert(right_); } template inline bool operator >= (Proxy const & left_, Proxy const & right_) { SEQAN_CHECKPOINT typedef typename GetValue >::Type TAccessor; return convert(left_) >= convert(right_); } ////////////////////////////////////////////////////////////////////////////// template inline TStream & operator >> (TStream & strm, Proxy & proxy) { typedef Proxy TProxy; typedef typename Value::Type TValue; TValue temp; strm >> temp; assignValue(iter(proxy), temp); return strm; } template inline TStream & operator >> (TStream & strm, Proxy const& proxy) { typedef Proxy TProxy; typedef typename Value::Type TValue; TValue temp; strm >> temp; assignValue(iter(proxy), temp); return strm; } template inline TStream & operator << (TStream & strm, Proxy & proxy) { return strm << getValue(proxy); } template inline TStream & operator << (TStream & strm, Proxy const & proxy) { return strm << getValue(proxy); } ////////////////////////////////////////////////////////////////////////////// } //namespace SEQAN_NAMESPACE_MAIN #endif //#ifndef SEQAN_HEADER_... ugene-1.9.8/src/plugins_3rdparty/bowtie/src/bowtie/SeqAn-1.1/seqan/basic/basic_allocator_simple.h0000644000175000017500000001330711651544326031335 0ustar ilyailya /*========================================================================== SeqAn - The Library for Sequence Analysis http://www.seqan.de ============================================================================ Copyright (C) 2007 This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. ============================================================================ $Id: basic_allocator_simple.h,v 1.1 2008/08/25 16:20:02 langmead Exp $ ==========================================================================*/ #ifndef SEQAN_HEADER_BASIC_ALLOCATOR_SIMPLE_H #define SEQAN_HEADER_BASIC_ALLOCATOR_SIMPLE_H namespace SEQAN_NAMESPACE_MAIN { ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// // SimpleAlloc Allocator ////////////////////////////////////////////////////////////////////////////// /** .Spec.Simple Allocator: ..cat:Allocators ..general:Class.Allocator ..summary:General purpose allocator. ..signature:Allocator< SimpleAlloc > ..param.ParentAllocator:An allocator that is by the simple allocator used to allocate memory. ...default:@Tag.Default@ ...remarks:@Tag.Default@ used as allocator means that the default implementations of @Function.allocate@ and @Function.deallocate@ are used. */ template struct SimpleAlloc; ////////////////////////////////////////////////////////////////////////////// typedef Allocator > SimpleAllocator; template struct Allocator > { struct Header { Header * left; Header * right; size_t size; }; Header * data_storages; Holder data_parent_allocator; Allocator(): data_storages(0) { SEQAN_CHECKPOINT } Allocator(TParentAllocator & parent_alloc): data_storages(0) { SEQAN_CHECKPOINT setValue(data_parent_allocator, parent_alloc); } //Dummy copy Allocator(Allocator const &): data_storages(0) { } inline Allocator & operator = (Allocator const &) { clear(*this); return *this; } ~Allocator() { SEQAN_CHECKPOINT clear(*this); } }; ////////////////////////////////////////////////////////////////////////////// template inline TParentAllocator & parentAllocator(Allocator > & me) { SEQAN_CHECKPOINT return value(me.data_parent_allocator); } ////////////////////////////////////////////////////////////////////////////// /** .Function.Allocator#clear: ..cat:Memory ..summary:Deallocates all memory blocks. ..signature:clear(allocator) ..param.allocator:Allocator object. ...type:Class.Allocator ...concept:Concept.Allocator ..remarks:This function deallocates all memory blocks that was allocated using @Function.allocate@ for $allocator$. The memory is not pooled but directly passed back to the heap manager. ..see:Function.allocate ..see:Function.deallocate */ template void clear(Allocator > & me) { SEQAN_CHECKPOINT typedef Allocator > TAllocator; while (me.data_storages) { typename TAllocator::Header * next_storage = me.data_storages->right; deallocate(parentAllocator(me), reinterpret_cast(me.data_storages), me.data_storages->size); me.data_storages = next_storage; } } ////////////////////////////////////////////////////////////////////////////// template inline void allocate(Allocator > & me, TValue * & data, TSize count, Tag const) { SEQAN_CHECKPOINT typedef Allocator > TAllocator; typedef typename TAllocator::Header THeader; //compute needed bytes size_t bytes_needed = count * sizeof(TValue) + sizeof(THeader); //allocate storage from parent char * ptr; allocate(parentAllocator(me), ptr, bytes_needed, TagAllocateStorage()); THeader * new_block = reinterpret_cast(ptr); new_block->left = 0; new_block->right = me.data_storages; new_block->size = bytes_needed; if (me.data_storages) { me.data_storages->left = new_block; } me.data_storages = new_block; //return data data = reinterpret_cast(ptr + sizeof(THeader)); } ////////////////////////////////////////////////////////////////////////////// template inline void deallocate(Allocator > & me, TValue * data, TSize, Tag const) { SEQAN_CHECKPOINT typedef Allocator > TAllocator; typedef typename TAllocator::Header THeader; //update links THeader & header = *(reinterpret_cast(data) - 1); if (header.left) { header.left->right = header.right; } else { me.data_storages = header.right; } if (header.right) { header.right->left = header.left; } //deallocate storage using parent char * ptr = reinterpret_cast(& header); deallocate(parentAllocator(me), ptr, header.size); } ////////////////////////////////////////////////////////////////////////////// } //namespace SEQAN_NAMESPACE_MAIN #endif //#ifndef SEQAN_HEADER_... ugene-1.9.8/src/plugins_3rdparty/bowtie/src/bowtie/SeqAn-1.1/seqan/basic/basic_transport.h0000644000175000017500000001275511651544326030046 0ustar ilyailya /*========================================================================== SeqAn - The Library for Sequence Analysis http://www.seqan.de ============================================================================ Copyright (C) 2007 This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. ============================================================================ $Id: basic_transport.h,v 1.1 2008/08/25 16:20:01 langmead Exp $ ==========================================================================*/ #ifndef SEQAN_HEADER_BASIC_TRANSPORT_H #define SEQAN_HEADER_BASIC_TRANSPORT_H namespace SEQAN_NAMESPACE_MAIN { ////////////////////////////////////////////////////////////////////////////// //assign ////////////////////////////////////////////////////////////////////////////// /** .Function.assign: ..summary:Assigns one object to another object. ..cat:Content Manipulation ..signature:assign(target, source) ..signature:assign(target, source [, limit] [,resize_tag]) ..param.target: Gets the content of $source$. ..param.source: Is copied to $target$. ..param.limit: The maximal length of $target$ after the operation. (optional) ...remarks:This arguments can be applied if $target$ is a container. ..param.resize_tag: Specifies the strategy that is applied if $target$ has not enough capacity to store the complete content. (optional) ...type:Tag.Overflow Strategy ...default:Specified by @Metafunction.DefaultOverflowImplicit@ of the $target$ type. ...remarks:This arguments can be applied if $target$ is a container. ..remarks:$assign(target, source)$ is semantically equivalent to $target = source$. */ template inline void assign(TTarget & target, TSource & source) { SEQAN_CHECKPOINT target = source; } template inline void assign(TTarget & target, TSource const & source) { SEQAN_CHECKPOINT target = source; } ////////////////////////////////////////////////////////////////////////////// template struct Proxy; template inline void assign(Proxy & target, TSource & source) { SEQAN_CHECKPOINT assignValue(iter(target), source); } template inline void assign(Proxy & target, TSource const & source) { SEQAN_CHECKPOINT assignValue(iter(target), source); } ////////////////////////////////////////////////////////////////////////////// // move ////////////////////////////////////////////////////////////////////////////// /** .Function.move: ..summary:Hands over content from one container to another container. ..cat:Content Manipulation ..signature:move(target, source) ..param.target:A container $source$ is moved to. ..param.source:A container that is moved to $target$. ..remarks:The function tries to hand over the contents of $source$ to $target$. If this is possible, $source$ losts its content and will therefore be empty after this operation. Otherwise, the function behaves like @Function.assign@ and $source$ is copied to $target$. ..see:Function.assign */ template inline void move(TTarget & target, TSource & source) { SEQAN_CHECKPOINT assign(target, source); } template inline void move(TTarget const & target, TSource & source) { SEQAN_CHECKPOINT assign(target, source); } template inline void move(TTarget & target, TSource const & source) { SEQAN_CHECKPOINT assign(target, source); } template inline void move(TTarget const & target, TSource const & source) { SEQAN_CHECKPOINT assign(target, source); } ////////////////////////////////////////////////////////////////////////////// // set ////////////////////////////////////////////////////////////////////////////// /** .Function.set: ..summary:Assigns one object to another object avoiding to copy contents. ..cat:Content Manipulation ..signature:assign(target, source) ..signature:assign(target, source) ..param.target: Gets the content of $source$. ..param.source: Content source. ..remarks:$set(target, source)$ is semantically equivalent to $target = source$. If possible, $set$ copies content references instead of the content itself. */ //TODO: rename set to ... template inline void set(TTarget & target, TSource & source) { SEQAN_CHECKPOINT assign(target, source); } template inline void set(TTarget const & target, TSource & source) { SEQAN_CHECKPOINT assign(target, source); } template inline void set(TTarget & target, TSource const & source) { SEQAN_CHECKPOINT assign(target, source); } template inline void set(TTarget const & target, TSource const & source) { SEQAN_CHECKPOINT assign(target, source); } ////////////////////////////////////////////////////////////////////////////// } //namespace SEQAN_NAMESPACE_MAIN #endif //#ifndef SEQAN_HEADER_... ugene-1.9.8/src/plugins_3rdparty/bowtie/src/bowtie/SeqAn-1.1/seqan/basic/basic_pointer.h0000644000175000017500000000557411651544326027473 0ustar ilyailya /*========================================================================== SeqAn - The Library for Sequence Analysis http://www.seqan.de ============================================================================ Copyright (C) 2007 This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. ============================================================================ $Id: basic_pointer.h,v 1.1 2008/08/25 16:20:01 langmead Exp $ ==========================================================================*/ #ifndef SEQAN_HEADER_BASIC_POINTER_H #define SEQAN_HEADER_BASIC_POINTER_H namespace SEQAN_NAMESPACE_MAIN { ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// ///.Metafunction.Value.param.T.type:Adaption.char array template struct Value< TValue * > { typedef TValue Type; }; template struct Value< TValue * const> { typedef TValue Type; }; //The next two metafunctions dont work in VC++ due to a compiler bug. //(the default implementation in common_type.h is called instead) //work-around: convert arrays to pointers. template struct Value< TValue [SIZE] > { typedef TValue Type; }; template struct Value< TValue const [SIZE] > { typedef TValue const Type; }; ////////////////////////////////////////////////////////////////////////////// ///.Metafunction.Iterator.param.T.type:Adaption.char array template struct Iterator< TValue *, Standard> { typedef TValue * Type; }; template struct Iterator< TValue * const, Standard> { typedef TValue * Type; }; //____________________________________________________________________________ template struct Iterator< TValue [SIZE], Standard>: Iterator { }; template struct Iterator< TValue const [SIZE], Standard>: Iterator { }; template struct Iterator< TValue [SIZE], Rooted>: Iterator { }; template struct Iterator< TValue const [SIZE], Rooted>: Iterator { }; ////////////////////////////////////////////////////////////////////////////// }// namespace SEQAN_NAMESPACE_MAIN #endif //#ifndef SEQAN_HEADER_... ugene-1.9.8/src/plugins_3rdparty/bowtie/src/bowtie/SeqAn-1.1/seqan/basic/basic_converter.h0000644000175000017500000001123711651544326030013 0ustar ilyailya /*========================================================================== SeqAn - The Library for Sequence Analysis http://www.seqan.de ============================================================================ Copyright (C) 2007 This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. ============================================================================ $Id: basic_converter.h,v 1.1 2008/08/25 16:20:01 langmead Exp $ ==========================================================================*/ #ifndef SEQAN_HEADER_BASIC_CONVERTER_H #define SEQAN_HEADER_BASIC_CONVERTER_H namespace SEQAN_NAMESPACE_MAIN { ////////////////////////////////////////////////////////////////////////////// //Convert ////////////////////////////////////////////////////////////////////////////// //gibt den Typ an, in den TSource konvertiert werden kann (TTarget oder TTarget &) /** .Metafunction.Convert: ..summary:Return type of a conversion. ..signature:Convert::Type ..param.Target:Type the object should be converted to. ..param.Source:Type of the object that should be converted to $Target$. ..returns.param.Type:Type that is returned by @Function.convert@. ...remarks:This is either $Target$ or $Target &$: If instances of $Source: /fs/szdevel/src/cvsroot/bowtie/SeqAn-1.1/seqan/basic/basic_converter.h,v $ can be re-interpreted as instances of $Target$, than this metafunction returns a reference, otherwise it returns $Target$, that is @Function.convert@ returns a temporary. ..remarks:A constant instance of $Convert$ is (ab)used as tag argument of @Function.convertImpl@. */ template struct Convert { typedef TTarget Type; }; ////////////////////////////////////////////////////////////////////////////// //convertImpl ////////////////////////////////////////////////////////////////////////////// /** .Function.convertImpl: ..hidefromindex ..cat:Alphabets ..summary:Implements @Function.convert@. ..signature:Convert convertImpl(convert, source) ..param.convert:Object that specifies the conversion. ...type:Metafunction.Convert ...remarks:A constant instance of @Metafunction.Convert@ is used to specify the conversion target. ..param.source:An object that should be converted. ..returns:$source$ converted to the type specified by convert. ...metafunction:Metafunction.Convert ..remarks:This function implements @Function.convert@. It is recommended to use @Function.convert@ rather than $convertImpl$. */ //??? Spezialisiere convertImpl, verwende convert //??? Konversion eines einzelnen Zeichens in ein einzelnes Zeichen. Konversion von Sequenzen in Sequenzen finden wo anders statt. //??? Kann entweder kopieren oder re-interpretieren, je nach Convert::Type template inline typename Convert::Type convertImpl(Convert const, TSource & source) { return source; } template inline typename Convert::Type convertImpl(Convert const, TSource const & source) { return source; } ////////////////////////////////////////////////////////////////////////////// //convert ////////////////////////////////////////////////////////////////////////////// /** .Function.convert: ..cat:Alphabets ..summary:Converts a value into another value. ..signature:Convert convert(source) ..param.Target:The type $source$ is converted to. ..param.source:An object that is converted to $Target$. ..returns:$source$ converted to $Target$. ...remarks:If $source$ can be re-interpreted as instance of $Target$, then a reference is returned. Otherwise the function returns a temporary object. ...metafunction:Metafunction.Convert ..remarks:This function is implemented in @Function.convertImpl@. Do not specialize $convert$, specialize @Function.convertImpl@ instead. ..see:Function.convertImpl */ template inline typename Convert::Type convert(TSource const & source) { return convertImpl(Convert(), source); } ////////////////////////////////////////////////////////////////////////////// }// namespace SEQAN_NAMESPACE_MAIN #endif //#ifndef SEQAN_HEADER_... ugene-1.9.8/src/plugins_3rdparty/bowtie/src/bowtie/SeqAn-1.1/seqan/basic/basic_tag.h0000644000175000017500000001257611651544326026566 0ustar ilyailya /*========================================================================== SeqAn - The Library for Sequence Analysis http://www.seqan.de ============================================================================ Copyright (C) 2007 This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. ============================================================================ $Id: basic_tag.h,v 1.1 2008/08/25 16:20:01 langmead Exp $ ==========================================================================*/ #ifndef SEQAN_HEADER_BASIC_TAG_H #define SEQAN_HEADER_BASIC_TAG_H namespace SEQAN_NAMESPACE_MAIN { ////////////////////////////////////////////////////////////////////////////// /** .Tag.DotDrawing ..summary:Switch to trigger drawing in dot format. ..value.DotDrawing:Graphs in dot format. */ struct DotDrawing_; typedef Tag const DotDrawing; /** .Tag.HammingDistance ..summary:Switch to trigger Hamming distance, which is a measure of character substitutions. */ /** .Tag.LevenshteinDistance ..summary:Switch to trigger Levenshtein distance, which is a measure of edit operations (character substitutions, deletions or insertions). */ struct _HammingDistance; struct _LevenshteinDistance; typedef Tag<_HammingDistance> HammingDistance; typedef Tag<_LevenshteinDistance> LevenshteinDistance; typedef Tag<_LevenshteinDistance> EditDistance; ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// // Alignment: Tags ////////////////////////////////////////////////////////////////////////////// //Sollte eigentlich nach align/, aber da jetzt ja so viele //alignment algorithmen in graph/ gelandet sind... /** .Tag.Global Alignment Algorithms: ..summary:Global alignment algorithm used by globalAlignment. ..see:Function.globalAlignment ..see:Tag.Local Alignment Algorithms */ ////////////////////////////////////////////////////////////////////////////// /** .Tag.Global Alignment Algorithms.value.NeedlemanWunsch: Dynamic programming algorithm for alignments by Needleman and Wunsch. */ struct NeedlemanWunsch_; typedef Tag const NeedlemanWunsch; ////////////////////////////////////////////////////////////////////////////// /** .Tag.Global Alignment Algorithms.value.Gotoh: Gotoh's affine gap cost alignment algorithm. */ struct Gotoh_; typedef Tag const Gotoh; ////////////////////////////////////////////////////////////////////////////// /** .Tag.Global Alignment Algorithms.value.MyersBitVector: Myers' bit vector alignment algorithm for edit distance. Note that this algorithm does not returns the alignment itself, but only computes the score. */ struct MyersBitVector_; typedef Tag const MyersBitVector; ////////////////////////////////////////////////////////////////////////////// /** .Tag.Global Alignment Algorithms.value.MyersHirschberg: Myers' bit vector algorithm for edit distance combined with Hirschberg's linear space alignment algorithm. */ struct MyersHirschberg_; typedef Tag const MyersHirschberg; ////////////////////////////////////////////////////////////////////////////// /** .Tag.Global Alignment Algorithms.value.Hirschberg: Hirschberg's linear space global alignment algorithm. */ struct Hirschberg_; typedef Tag const Hirschberg; ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// /** .Tag.Local Alignment Algorithms: ..summary:Local alignment algorithm used by localAlignment. ..see:Function.localAlignment */ ////////////////////////////////////////////////////////////////////////////// /** .Tag.Local Alignment Algorithms.value.SmithWaterman: Triggers a Smith Waterman local alignment algorithm. */ struct SmithWaterman_; typedef Tag const SmithWaterman; ////////////////////////////////////////////////////////////////////////////// /** .Tag.Local Alignment Algorithms.value.SmithWatermanClump: Local alignment algorithm with "declumping" by Waterman and Eggert. */ struct SmithWatermanClump_; typedef Tag const SmithWatermanClump; ////////////////////////////////////////////////////////////////////////////// /** .Tag.Local Alignment Algorithms.value.SmithWatermanIsland: Local alignment algorithm finding all "islands". */ struct SmithWatermanIsland_; typedef Tag const SmithWatermanIsland; ////////////////////////////////////////////////////////////////////////////// /*DISABLED .Tag.RNA Folding Algorithms.value.Nussinov: Nussinov style RNA folding algorithm */ struct Nussinov_; typedef Tag const Nussinov; ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// }// namespace SEQAN_NAMESPACE_MAIN #endif //#ifndef SEQAN_HEADER_... ugene-1.9.8/src/plugins_3rdparty/bowtie/src/bowtie/SeqAn-1.1/seqan/basic/basic_generated_forwards.h0000644000175000017500000043545611651544326031666 0ustar ilyailya /*========================================================================== SeqAn - The Library for Sequence Analysis http://www.seqan.de ============================================================================ Copyright (C) 2007 This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. ==========================================================================*/ #ifndef SEQAN_HEADER_BASIC_GENERATED_FORWARDS_H #define SEQAN_HEADER_BASIC_GENERATED_FORWARDS_H ////////////////////////////////////////////////////////////////////////////// // NOTE: This file is automatically generated by build_forwards.py // Do not edit this file manually! ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// // CLASSES ////////////////////////////////////////////////////////////////////////////// namespace SEQAN_NAMESPACE_MAIN { namespace debug { //____________________________________________________________________________ // Check class Check; // "projects/library/seqan/basic/basic_debug.h"(238) //____________________________________________________________________________ // Checkpoint struct Checkpoint; // "projects/library/seqan/basic/basic_debug.h"(296) //____________________________________________________________________________ // CheckpointLess struct CheckpointLess; // "projects/library/seqan/basic/basic_debug.h"(302) //____________________________________________________________________________ // CheckpointStore template struct CheckpointStore; // "projects/library/seqan/basic/basic_debug.h"(312) //____________________________________________________________________________ // Report class Report; // "projects/library/seqan/basic/basic_debug.h"(242) } //namespace debug } //namespace SEQAN_NAMESPACE_MAIN ////////////////////////////////////////////////////////////////////////////// namespace SEQAN_NAMESPACE_MAIN { //____________________________________________________________________________ // AdaptorIterator template struct AdaptorIterator; // "projects/library/seqan/basic/basic_iterator_adaptor.h"(31) //____________________________________________________________________________ // Allocator template struct Allocator; // "projects/library/seqan/basic/basic_allocator_interface.h"(50) //____________________________________________________________________________ // BitsPerValue template struct BitsPerValue; // "projects/library/seqan/basic/basic_alphabet_interface.h"(837) //____________________________________________________________________________ // CASE template struct CASE; // "projects/library/seqan/basic/basic_metaprogramming.h"(76) //____________________________________________________________________________ // Cargo template struct Cargo; // "projects/library/seqan/basic/basic_type.h"(290) //____________________________________________________________________________ // ChunkPool #if 0 template struct ChunkPool; // "projects/library/seqan/basic/basic_allocator_chunkpool.h"(56) #endif //____________________________________________________________________________ // ChunkPool2 template struct ChunkPool2; // "projects/library/seqan/basic/basic_allocator_chunkpool.h"(248) //____________________________________________________________________________ // CompareType template struct CompareType; // "projects/library/seqan/basic/basic_alphabet_simple.h"(500) template struct CompareType; // "projects/library/seqan/basic/basic_compare.h"(30) //____________________________________________________________________________ // Container template struct Container; // "projects/library/seqan/basic/basic_iterator_base.h"(106) template struct Container; // "projects/library/seqan/basic/basic_iterator.h"(147) //____________________________________________________________________________ // Convert template struct Convert; // "projects/library/seqan/basic/basic_converter.h"(48) //____________________________________________________________________________ // CountedPtr template struct CountedPtr; // "projects/library/seqan/basic/basic_counted_ptr.h"(34) //____________________________________________________________________________ // CutCompressed template struct CutCompressed; // "projects/library/seqan/basic/basic_aggregates.h"(36) //____________________________________________________________________________ // DeepestSpec template struct DeepestSpec; // "projects/library/seqan/basic/basic_type.h"(229) //____________________________________________________________________________ // DefaultGetIteratorSpec template struct DefaultGetIteratorSpec; // "projects/library/seqan/basic/basic_iterator.h"(94) //____________________________________________________________________________ // DefaultIteratorSpec template struct DefaultIteratorSpec; // "projects/library/seqan/basic/basic_iterator.h"(72) //____________________________________________________________________________ // Default_ struct Default_; // "projects/library/seqan/basic/basic_definition.h"(40) //____________________________________________________________________________ // Difference template struct Difference; // "projects/library/seqan/basic/basic_type.h"(137) //____________________________________________________________________________ // DotDrawing_ struct DotDrawing_; // "projects/library/seqan/basic/basic_tag.h"(36) //____________________________________________________________________________ // False struct False; // "projects/library/seqan/basic/basic_definition.h"(88) //____________________________________________________________________________ // GetValue template struct GetValue; // "projects/library/seqan/basic/basic_type.h"(69) //____________________________________________________________________________ // GoEnd_ struct GoEnd_; // "projects/library/seqan/basic/basic_definition.h"(66) //____________________________________________________________________________ // Gotoh_ struct Gotoh_; // "projects/library/seqan/basic/basic_tag.h"(90) //____________________________________________________________________________ // Hirschberg_ struct Hirschberg_; // "projects/library/seqan/basic/basic_tag.h"(118) //____________________________________________________________________________ // Holder template struct Holder; // "projects/library/seqan/basic/basic_holder.h"(112) //____________________________________________________________________________ // Host template struct Host; // "projects/library/seqan/basic/basic_type.h"(181) //____________________________________________________________________________ // IF template struct IF; // "projects/library/seqan/basic/basic_metaprogramming.h"(35) //____________________________________________________________________________ // Id template struct Id; // "projects/library/seqan/basic/basic_type.h"(335) //____________________________________________________________________________ // InfimumValue template struct InfimumValue; // "projects/library/seqan/basic/basic_alphabet_interface.h"(911) //____________________________________________________________________________ // IsSimple template struct IsSimple; // "projects/library/seqan/basic/basic_alphabet_interface.h"(53) //____________________________________________________________________________ // Iter template class Iter; // "projects/library/seqan/basic/basic_iterator_base.h"(41) //____________________________________________________________________________ // Iterator template struct Iterator; // "projects/library/seqan/basic/basic_iterator.h"(129) //____________________________________________________________________________ // IteratorProxy template struct IteratorProxy; // "projects/library/seqan/basic/basic_proxy.h"(80) //____________________________________________________________________________ // Iterator_Default_Imp template struct Iterator_Default_Imp; // "projects/library/seqan/basic/basic_iterator.h"(119) //____________________________________________________________________________ // Key template struct Key; // "projects/library/seqan/basic/basic_type.h"(358) //____________________________________________________________________________ // LENGTH template struct LENGTH; // "projects/library/seqan/basic/basic_type.h"(586) //____________________________________________________________________________ // LOOP template class LOOP; // "projects/library/seqan/basic/basic_metaprogramming.h"(121) //____________________________________________________________________________ // LOOP_REVERSE template class LOOP_REVERSE; // "projects/library/seqan/basic/basic_metaprogramming.h"(144) //____________________________________________________________________________ // Log2 template <__int64 numerus > struct Log2; // "projects/library/seqan/basic/basic_metaprogramming.h"(166) //____________________________________________________________________________ // Log2Floor template <__int64 numerus > struct Log2Floor; // "projects/library/seqan/basic/basic_metaprogramming.h"(171) //____________________________________________________________________________ // MemsetConstValueWorker template struct MemsetConstValueWorker; // "projects/library/seqan/basic/basic_metaprogramming.h"(251) //____________________________________________________________________________ // MemsetWorker template struct MemsetWorker; // "projects/library/seqan/basic/basic_metaprogramming.h"(205) //____________________________________________________________________________ // MinimalCtor_ struct MinimalCtor_; // "projects/library/seqan/basic/basic_definition.h"(73) //____________________________________________________________________________ // Move_ struct Move_; // "projects/library/seqan/basic/basic_definition.h"(60) //____________________________________________________________________________ // MultiPool template struct MultiPool; // "projects/library/seqan/basic/basic_allocator_multipool.h"(50) //____________________________________________________________________________ // MyersBitVector_ struct MyersBitVector_; // "projects/library/seqan/basic/basic_tag.h"(100) //____________________________________________________________________________ // MyersHirschberg_ struct MyersHirschberg_; // "projects/library/seqan/basic/basic_tag.h"(109) //____________________________________________________________________________ // NeedlemanWunsch_ struct NeedlemanWunsch_; // "projects/library/seqan/basic/basic_tag.h"(81) //____________________________________________________________________________ // NilCase struct NilCase; // "projects/library/seqan/basic/basic_metaprogramming.h"(72) //____________________________________________________________________________ // NonMinimalCtor_ struct NonMinimalCtor_; // "projects/library/seqan/basic/basic_definition.h"(77) //____________________________________________________________________________ // Nothing struct Nothing; // "projects/library/seqan/basic/basic_definition.h"(99) //____________________________________________________________________________ // Nussinov_ struct Nussinov_; // "projects/library/seqan/basic/basic_tag.h"(163) //____________________________________________________________________________ // Object template struct Object; // "projects/library/seqan/basic/basic_type.h"(377) //____________________________________________________________________________ // Pair template struct Pair; // "projects/library/seqan/basic/basic_aggregates.h"(69) //____________________________________________________________________________ // Position template struct Position; // "projects/library/seqan/basic/basic_type.h"(161) //____________________________________________________________________________ // PositionIterator struct PositionIterator; // "projects/library/seqan/basic/basic_iterator_position.h"(29) //____________________________________________________________________________ // Power template <__int64 base, __int64 exponent > struct Power; // "projects/library/seqan/basic/basic_metaprogramming.h"(186) //____________________________________________________________________________ // Proxy template struct Proxy; // "projects/library/seqan/basic/basic_transport.h"(67) template struct Proxy; // "projects/library/seqan/basic/basic_proxy.h"(48) //____________________________________________________________________________ // Reference template struct Reference; // "projects/library/seqan/basic/basic_type.h"(91) //____________________________________________________________________________ // SWITCH template class SWITCH; // "projects/library/seqan/basic/basic_metaprogramming.h"(84) //____________________________________________________________________________ // Simple struct Simple; // "projects/library/seqan/basic/basic_holder.h"(86) //____________________________________________________________________________ // SimpleAlloc template struct SimpleAlloc; // "projects/library/seqan/basic/basic_allocator_simple.h"(46) //____________________________________________________________________________ // SimpleIterator struct SimpleIterator; // "projects/library/seqan/basic/basic_iterator_simple.h"(30) //____________________________________________________________________________ // SimpleType template struct SimpleType; // "projects/library/seqan/basic/basic_alphabet_simple.h"(58) //____________________________________________________________________________ // SinglePool template struct SinglePool; // "projects/library/seqan/basic/basic_allocator_singlepool.h"(50) //____________________________________________________________________________ // SinglePool2 template struct SinglePool2; // "projects/library/seqan/basic/basic_allocator_singlepool.h"(226) //____________________________________________________________________________ // Size template struct Size; // "projects/library/seqan/basic/basic_type.h"(113) //____________________________________________________________________________ // SmithWatermanClump_ struct SmithWatermanClump_; // "projects/library/seqan/basic/basic_tag.h"(145) //____________________________________________________________________________ // SmithWatermanIsland_ struct SmithWatermanIsland_; // "projects/library/seqan/basic/basic_tag.h"(154) //____________________________________________________________________________ // SmithWaterman_ struct SmithWaterman_; // "projects/library/seqan/basic/basic_tag.h"(136) //____________________________________________________________________________ // Source template struct Source; // "projects/library/seqan/basic/basic_type.h"(392) //____________________________________________________________________________ // Spec template struct Spec; // "projects/library/seqan/basic/basic_type.h"(200) //____________________________________________________________________________ // StdAllocator template struct StdAllocator; // "projects/library/seqan/basic/basic_allocator_to_std.h"(166) //____________________________________________________________________________ // StdContainerIterator template struct StdContainerIterator; // "projects/library/seqan/basic/basic_iterator_adapt_std.h"(68) //____________________________________________________________________________ // StdIteratorAdaptor struct StdIteratorAdaptor; // "projects/library/seqan/basic/basic_iterator_adapt_std.h"(89) //____________________________________________________________________________ // SupremumValue template struct SupremumValue; // "projects/library/seqan/basic/basic_alphabet_interface.h"(900) //____________________________________________________________________________ // TYPECMP template struct TYPECMP; // "projects/library/seqan/basic/basic_metaprogramming.h"(54) //____________________________________________________________________________ // Tag template struct Tag; // "projects/library/seqan/basic/basic_definition.h"(31) //____________________________________________________________________________ // TagAllocateStorage_ struct TagAllocateStorage_; // "projects/library/seqan/basic/basic_allocator_interface.h"(84) //____________________________________________________________________________ // TagAllocateTemp_ struct TagAllocateTemp_; // "projects/library/seqan/basic/basic_allocator_interface.h"(81) //____________________________________________________________________________ // TagAllocateUnspecified_ struct TagAllocateUnspecified_; // "projects/library/seqan/basic/basic_allocator_interface.h"(78) //____________________________________________________________________________ // TagRooted_ struct TagRooted_; // "projects/library/seqan/basic/basic_iterator.h"(48) //____________________________________________________________________________ // TagStandard_ struct TagStandard_; // "projects/library/seqan/basic/basic_iterator.h"(51) //____________________________________________________________________________ // ToStdAllocator template struct ToStdAllocator; // "projects/library/seqan/basic/basic_allocator_to_std.h"(61) //____________________________________________________________________________ // Triple template struct Triple; // "projects/library/seqan/basic/basic_aggregates.h"(218) //____________________________________________________________________________ // Tristate struct Tristate; // "projects/library/seqan/basic/basic_holder.h"(87) //____________________________________________________________________________ // Tristate2 struct Tristate2; // "projects/library/seqan/basic/basic_holder.h"(790) //____________________________________________________________________________ // True struct True; // "projects/library/seqan/basic/basic_definition.h"(87) //____________________________________________________________________________ // Tuple template struct Tuple; // "projects/library/seqan/basic/basic_aggregates.h"(313) //____________________________________________________________________________ // Value template struct Value; // "projects/library/seqan/basic/basic_type.h"(43) //____________________________________________________________________________ // ValueSize template struct ValueSize; // "projects/library/seqan/basic/basic_alphabet_interface.h"(859) //____________________________________________________________________________ // VertexDescriptor template struct VertexDescriptor; // "projects/library/seqan/basic/basic_type.h"(313) //____________________________________________________________________________ // VolatilePtr template struct VolatilePtr; // "projects/library/seqan/basic/basic_volatile_ptr.h"(40) //____________________________________________________________________________ // WEIGHT template struct WEIGHT; // "projects/library/seqan/basic/basic_type.h"(608) //____________________________________________________________________________ // WorkerNothing struct WorkerNothing; // "projects/library/seqan/basic/basic_metaprogramming.h"(115) //____________________________________________________________________________ // _AminoAcid struct _AminoAcid; // "projects/library/seqan/basic/basic_alphabet_simple.h"(1085) //____________________________________________________________________________ // _BitVector template struct _BitVector; // "projects/library/seqan/basic/basic_aggregates.h"(340) //____________________________________________________________________________ // _ClassIdentifier template struct _ClassIdentifier; // "projects/library/seqan/basic/basic_definition.h"(269) //____________________________________________________________________________ // _Compressed struct _Compressed; // "projects/library/seqan/basic/basic_aggregates.h"(29) //____________________________________________________________________________ // _ConstParameter template struct _ConstParameter; // "projects/library/seqan/basic/basic_type.h"(474) //____________________________________________________________________________ // _CopyConst template struct _CopyConst; // "projects/library/seqan/basic/basic_definition.h"(108) //____________________________________________________________________________ // _Dna struct _Dna; // "projects/library/seqan/basic/basic_alphabet_simple.h"(1010) //____________________________________________________________________________ // _Dna5 struct _Dna5; // "projects/library/seqan/basic/basic_alphabet_simple.h"(1034) //____________________________________________________________________________ // _HammingDistance struct _HammingDistance; // "projects/library/seqan/basic/basic_tag.h"(50) //____________________________________________________________________________ // _InfimumValueSigned template struct _InfimumValueSigned; // "projects/library/seqan/basic/basic_alphabet_interface.h"(876) //____________________________________________________________________________ // _InfimumValueUnsigned template struct _InfimumValueUnsigned; // "projects/library/seqan/basic/basic_alphabet_interface.h"(874) //____________________________________________________________________________ // _IsSameType template struct _IsSameType; // "projects/library/seqan/basic/basic_definition.h"(378) //____________________________________________________________________________ // _IsSimple template struct _IsSimple; // "projects/library/seqan/basic/basic_alphabet_interface.h"(47) //____________________________________________________________________________ // _Iupac struct _Iupac; // "projects/library/seqan/basic/basic_alphabet_simple.h"(1058) //____________________________________________________________________________ // _LevenshteinDistance struct _LevenshteinDistance; // "projects/library/seqan/basic/basic_tag.h"(51) //____________________________________________________________________________ // _Log2_Impl template struct _Log2_Impl; // "projects/library/seqan/basic/basic_definition.h"(292) //____________________________________________________________________________ // _MakeSigned template struct _MakeSigned; // "projects/library/seqan/basic/basic_definition.h"(212) //____________________________________________________________________________ // _MakeUnsigned template struct _MakeUnsigned; // "projects/library/seqan/basic/basic_definition.h"(157) //____________________________________________________________________________ // _Parameter template struct _Parameter; // "projects/library/seqan/basic/basic_type.h"(416) //____________________________________________________________________________ // _Pointer template struct _Pointer; // "projects/library/seqan/basic/basic_type.h"(519) //____________________________________________________________________________ // _RemoveConst template struct _RemoveConst; // "projects/library/seqan/basic/basic_definition.h"(126) //____________________________________________________________________________ // _SupremumValueSigned template struct _SupremumValueSigned; // "projects/library/seqan/basic/basic_alphabet_interface.h"(871) //____________________________________________________________________________ // _SupremumValueUnsigned template struct _SupremumValueUnsigned; // "projects/library/seqan/basic/basic_alphabet_interface.h"(869) //____________________________________________________________________________ // _Translate_Table_AA_2_Ascii template struct _Translate_Table_AA_2_Ascii; // "projects/library/seqan/basic/basic_alphabet_simple_tabs.h"(337) //____________________________________________________________________________ // _Translate_Table_Ascii_2_AA template struct _Translate_Table_Ascii_2_AA; // "projects/library/seqan/basic/basic_alphabet_simple_tabs.h"(374) //____________________________________________________________________________ // _Translate_Table_Ascii_2_Dna template struct _Translate_Table_Ascii_2_Dna; // "projects/library/seqan/basic/basic_alphabet_simple_tabs.h"(138) //____________________________________________________________________________ // _Translate_Table_Ascii_2_Dna5 template struct _Translate_Table_Ascii_2_Dna5; // "projects/library/seqan/basic/basic_alphabet_simple_tabs.h"(176) //____________________________________________________________________________ // _Translate_Table_Ascii_2_Iupac template struct _Translate_Table_Ascii_2_Iupac; // "projects/library/seqan/basic/basic_alphabet_simple_tabs.h"(214) //____________________________________________________________________________ // _Translate_Table_Byte_2_AA template struct _Translate_Table_Byte_2_AA; // "projects/library/seqan/basic/basic_alphabet_simple_tabs.h"(412) //____________________________________________________________________________ // _Translate_Table_Byte_2_Dna template struct _Translate_Table_Byte_2_Dna; // "projects/library/seqan/basic/basic_alphabet_simple_tabs.h"(251) //____________________________________________________________________________ // _Translate_Table_Byte_2_Dna5 template struct _Translate_Table_Byte_2_Dna5; // "projects/library/seqan/basic/basic_alphabet_simple_tabs.h"(280) //____________________________________________________________________________ // _Translate_Table_Byte_2_Iupac template struct _Translate_Table_Byte_2_Iupac; // "projects/library/seqan/basic/basic_alphabet_simple_tabs.h"(308) //____________________________________________________________________________ // _Translate_Table_Dna5_2_Ascii template struct _Translate_Table_Dna5_2_Ascii; // "projects/library/seqan/basic/basic_alphabet_simple_tabs.h"(33) //____________________________________________________________________________ // _Translate_Table_Dna5_2_Iupac template struct _Translate_Table_Dna5_2_Iupac; // "projects/library/seqan/basic/basic_alphabet_simple_tabs.h"(43) //____________________________________________________________________________ // _Translate_Table_Iupac_2_Ascii template struct _Translate_Table_Iupac_2_Ascii; // "projects/library/seqan/basic/basic_alphabet_simple_tabs.h"(53) //____________________________________________________________________________ // _Translate_Table_Iupac_2_Dna template struct _Translate_Table_Iupac_2_Dna; // "projects/library/seqan/basic/basic_alphabet_simple_tabs.h"(81) //____________________________________________________________________________ // _Translate_Table_Iupac_2_Dna5 template struct _Translate_Table_Iupac_2_Dna5; // "projects/library/seqan/basic/basic_alphabet_simple_tabs.h"(110) //____________________________________________________________________________ // _TupleShiftLeftWorker struct _TupleShiftLeftWorker; // "projects/library/seqan/basic/basic_aggregates.h"(510) //____________________________________________________________________________ // _TupleShiftRightWorker struct _TupleShiftRightWorker; // "projects/library/seqan/basic/basic_aggregates.h"(517) //____________________________________________________________________________ // _ValueConstructor struct _ValueConstructor; // "projects/library/seqan/basic/basic_alphabet_interface.h"(81) //____________________________________________________________________________ // _ValueConstructorProxy struct _ValueConstructorProxy; // "projects/library/seqan/basic/basic_alphabet_interface.h"(111) //____________________________________________________________________________ // _ValueDestructor struct _ValueDestructor; // "projects/library/seqan/basic/basic_alphabet_interface.h"(125) //____________________________________________________________________________ // _ValueDestructorProxy struct _ValueDestructorProxy; // "projects/library/seqan/basic/basic_alphabet_interface.h"(135) } //namespace SEQAN_NAMESPACE_MAIN ////////////////////////////////////////////////////////////////////////////// // TYPEDEFS ////////////////////////////////////////////////////////////////////////////// namespace SEQAN_NAMESPACE_MAIN { //____________________________________________________________________________ // AminoAcid typedef SimpleType AminoAcid; // "projects/library/seqan/basic/basic_alphabet_simple.h"(1086) //____________________________________________________________________________ // Ascii typedef char Ascii; // "projects/library/seqan/basic/basic_alphabet_interface.h"(61) //____________________________________________________________________________ // Byte typedef unsigned char Byte; // "projects/library/seqan/basic/basic_alphabet_interface.h"(62) //____________________________________________________________________________ // Compressed typedef Tag<_Compressed> Compressed; // "projects/library/seqan/basic/basic_aggregates.h"(30) //____________________________________________________________________________ // Default typedef Tag const Default; // "projects/library/seqan/basic/basic_definition.h"(41) //____________________________________________________________________________ // Dna typedef SimpleType Dna; // "projects/library/seqan/basic/basic_alphabet_simple.h"(1011) //____________________________________________________________________________ // Dna5 typedef SimpleType Dna5; // "projects/library/seqan/basic/basic_alphabet_simple.h"(1035) //____________________________________________________________________________ // DotDrawing typedef Tag const DotDrawing; // "projects/library/seqan/basic/basic_tag.h"(37) //____________________________________________________________________________ // EditDistance typedef Tag<_LevenshteinDistance> EditDistance; // "projects/library/seqan/basic/basic_tag.h"(55) //____________________________________________________________________________ // GoEnd typedef Tag const GoEnd; // "projects/library/seqan/basic/basic_definition.h"(67) //____________________________________________________________________________ // Gotoh typedef Tag const Gotoh; // "projects/library/seqan/basic/basic_tag.h"(91) //____________________________________________________________________________ // HammingDistance typedef Tag<_HammingDistance> HammingDistance; // "projects/library/seqan/basic/basic_tag.h"(53) //____________________________________________________________________________ // Hirschberg typedef Tag const Hirschberg; // "projects/library/seqan/basic/basic_tag.h"(119) //____________________________________________________________________________ // Iupac typedef SimpleType Iupac; // "projects/library/seqan/basic/basic_alphabet_simple.h"(1059) //____________________________________________________________________________ // LevenshteinDistance typedef Tag<_LevenshteinDistance> LevenshteinDistance; // "projects/library/seqan/basic/basic_tag.h"(54) //____________________________________________________________________________ // MinimalCtor typedef Tag const MinimalCtor; // "projects/library/seqan/basic/basic_definition.h"(74) //____________________________________________________________________________ // Move typedef Tag const Move; // "projects/library/seqan/basic/basic_definition.h"(61) //____________________________________________________________________________ // MyersBitVector typedef Tag const MyersBitVector; // "projects/library/seqan/basic/basic_tag.h"(101) //____________________________________________________________________________ // MyersHirschberg typedef Tag const MyersHirschberg; // "projects/library/seqan/basic/basic_tag.h"(110) //____________________________________________________________________________ // NeedlemanWunsch typedef Tag const NeedlemanWunsch; // "projects/library/seqan/basic/basic_tag.h"(82) //____________________________________________________________________________ // NonMinimalCtor typedef Tag const NonMinimalCtor; // "projects/library/seqan/basic/basic_definition.h"(78) //____________________________________________________________________________ // Nussinov typedef Tag const Nussinov; // "projects/library/seqan/basic/basic_tag.h"(164) //____________________________________________________________________________ // PoolAllocator typedef Allocator >, 0x100> > PoolAllocator; // "projects/library/seqan/basic/basic_allocator_multipool.h"(54) //____________________________________________________________________________ // Rooted typedef Tag const Rooted; // "projects/library/seqan/basic/basic_iterator.h"(49) //____________________________________________________________________________ // SimpleAllocator typedef Allocator > SimpleAllocator; // "projects/library/seqan/basic/basic_allocator_simple.h"(51) //____________________________________________________________________________ // SmithWaterman typedef Tag const SmithWaterman; // "projects/library/seqan/basic/basic_tag.h"(137) //____________________________________________________________________________ // SmithWatermanClump typedef Tag const SmithWatermanClump; // "projects/library/seqan/basic/basic_tag.h"(146) //____________________________________________________________________________ // SmithWatermanIsland typedef Tag const SmithWatermanIsland; // "projects/library/seqan/basic/basic_tag.h"(155) //____________________________________________________________________________ // Standard typedef Tag const Standard; // "projects/library/seqan/basic/basic_iterator.h"(52) //____________________________________________________________________________ // TagAllocateStorage typedef Tag const TagAllocateStorage; // "projects/library/seqan/basic/basic_allocator_interface.h"(85) //____________________________________________________________________________ // TagAllocateTemp typedef Tag const TagAllocateTemp; // "projects/library/seqan/basic/basic_allocator_interface.h"(82) //____________________________________________________________________________ // TagAllocateUnspecified typedef Tag const TagAllocateUnspecified; // "projects/library/seqan/basic/basic_allocator_interface.h"(79) //____________________________________________________________________________ // Unicode typedef wchar_t Unicode; // "projects/library/seqan/basic/basic_alphabet_interface.h"(63) } //namespace SEQAN_NAMESPACE_MAIN ////////////////////////////////////////////////////////////////////////////// // FUNCTIONS ////////////////////////////////////////////////////////////////////////////// namespace SEQAN_NAMESPACE_MAIN { namespace debug { //____________________________________________________________________________ // Error template void Error(const char * file, int line, const char * comment); // "projects/library/seqan/basic/basic_debug.h"(250) //____________________________________________________________________________ // Message template void Message(const char * file, int line, const char * comment); // "projects/library/seqan/basic/basic_debug.h"(260) //____________________________________________________________________________ // Result template void Result(const char * file, int line, const char * comment); // "projects/library/seqan/basic/basic_debug.h"(269) //____________________________________________________________________________ // checkpoint inline bool checkpoint(unsigned int line, char const* file); // "projects/library/seqan/basic/basic_debug.h"(321) //____________________________________________________________________________ // testCheckpoint inline void testCheckpoint(char const* file, unsigned int line); // "projects/library/seqan/basic/basic_debug.h"(338) //____________________________________________________________________________ // verifyCheckpoints inline void verifyCheckpoints(char const* file); // "projects/library/seqan/basic/basic_debug.h"(346) } //namespace debug } //namespace SEQAN_NAMESPACE_MAIN ////////////////////////////////////////////////////////////////////////////// namespace SEQAN_NAMESPACE_MAIN { //____________________________________________________________________________ // _allocatorBlockNumber template inline unsigned int _allocatorBlockNumber(Allocator > &, size_t size_); // "projects/library/seqan/basic/basic_allocator_multipool.h"(140) //____________________________________________________________________________ // _arrayClearSpace_Default template void _arrayClearSpace_Default(TIterator array_begin, size_t array_length, size_t keep_from, size_t move_to); // "projects/library/seqan/basic/basic_alphabet_interface.h"(774) //____________________________________________________________________________ // _arrayClearSpace_Pointer template inline void _arrayClearSpace_Pointer(TValue * array_begin, size_t array_length, size_t keep_from, size_t move_to, True); // "projects/library/seqan/basic/basic_alphabet_trait_basic.h"(342) template inline void _arrayClearSpace_Pointer(TValue * array_begin, size_t array_length, size_t keep_from, size_t move_to, False); // "projects/library/seqan/basic/basic_alphabet_trait_basic.h"(354) //____________________________________________________________________________ // _arrayConstructCopy_Default template inline void _arrayConstructCopy_Default(TSource1 source_begin, TSource2 source_end, TTarget target_begin); // "projects/library/seqan/basic/basic_alphabet_interface.h"(349) //____________________________________________________________________________ // _arrayConstructCopy_Pointer template inline void _arrayConstructCopy_Pointer(TValue * source_begin, TValue * source_end, TValue * target_begin, True); // "projects/library/seqan/basic/basic_alphabet_trait_basic.h"(100) template inline void _arrayConstructCopy_Pointer(TValue * source_begin, TValue * source_end, TValue * target_begin, False); // "projects/library/seqan/basic/basic_alphabet_trait_basic.h"(110) //____________________________________________________________________________ // _arrayConstructMove_Default template inline void _arrayConstructMove_Default(TSource1 source_begin, TSource2 source_end, TTarget target_begin); // "projects/library/seqan/basic/basic_alphabet_interface.h"(397) //____________________________________________________________________________ // _arrayConstructMove_Pointer template inline void _arrayConstructMove_Pointer(TValue * source_begin, TValue * source_end, TValue * target_begin, True); // "projects/library/seqan/basic/basic_alphabet_trait_basic.h"(134) template inline void _arrayConstructMove_Pointer(TValue * source_begin, TValue * source_end, TValue * target_begin, False); // "projects/library/seqan/basic/basic_alphabet_trait_basic.h"(144) //____________________________________________________________________________ // _arrayConstruct_Default template inline void _arrayConstruct_Default(TIterator1 begin_, TIterator2 end_); // "projects/library/seqan/basic/basic_alphabet_interface.h"(280) template inline void _arrayConstruct_Default(TIterator1 begin_, TIterator2 end_, TParam const & param_); // "projects/library/seqan/basic/basic_alphabet_interface.h"(304) //____________________________________________________________________________ // _arrayConstruct_Pointer template inline void _arrayConstruct_Pointer(TIterator, TIterator, True); // "projects/library/seqan/basic/basic_alphabet_trait_basic.h"(36) template inline void _arrayConstruct_Pointer(TIterator begin_, TIterator end_, False); // "projects/library/seqan/basic/basic_alphabet_trait_basic.h"(45) template inline void _arrayConstruct_Pointer(TIterator begin_, TIterator end_, TParam const & param_, True); // "projects/library/seqan/basic/basic_alphabet_trait_basic.h"(66) template inline void _arrayConstruct_Pointer(TIterator begin_, TIterator end_, TParam const & param_, False); // "projects/library/seqan/basic/basic_alphabet_trait_basic.h"(76) //____________________________________________________________________________ // _arrayCopyBackward_Default template inline void _arrayCopyBackward_Default(TSource1 source_begin, TSource2 source_end, TTarget target_begin); // "projects/library/seqan/basic/basic_alphabet_interface.h"(547) //____________________________________________________________________________ // _arrayCopyBackward_Pointer template inline void _arrayCopyBackward_Pointer(TValue * source_begin, TValue * source_end, TValue * target_begin, True); // "projects/library/seqan/basic/basic_alphabet_trait_basic.h"(239) template inline void _arrayCopyBackward_Pointer(TValue * source_begin, TValue * source_end, TValue * target_begin, False); // "projects/library/seqan/basic/basic_alphabet_trait_basic.h"(249) //____________________________________________________________________________ // _arrayCopyForward_Default template inline void _arrayCopyForward_Default(TSource1 source_begin, TSource2 source_end, TTarget target_begin); // "projects/library/seqan/basic/basic_alphabet_interface.h"(504) //____________________________________________________________________________ // _arrayCopyForward_Pointer template inline void _arrayCopyForward_Pointer(TValue * source_begin, TValue * source_end, TValue * target_begin, True); // "projects/library/seqan/basic/basic_alphabet_trait_basic.h"(205) template inline void _arrayCopyForward_Pointer(TValue * source_begin, TValue * source_end, TValue * target_begin, False); // "projects/library/seqan/basic/basic_alphabet_trait_basic.h"(215) //____________________________________________________________________________ // _arrayDestruct_Default template inline void _arrayDestruct_Default(TIterator1 begin_, TIterator2 end_); // "projects/library/seqan/basic/basic_alphabet_interface.h"(436) //____________________________________________________________________________ // _arrayDestruct_Pointer template inline void _arrayDestruct_Pointer(TValue * , TValue * , True); // "projects/library/seqan/basic/basic_alphabet_trait_basic.h"(167) template inline void _arrayDestruct_Pointer(TValue * begin_, TValue * end_, False); // "projects/library/seqan/basic/basic_alphabet_trait_basic.h"(176) //____________________________________________________________________________ // _arrayMoveBackward_Default template inline void _arrayMoveBackward_Default(TSource1 source_begin, TSource2 source_end, TTarget target_begin); // "projects/library/seqan/basic/basic_alphabet_interface.h"(679) //____________________________________________________________________________ // _arrayMoveBackward_Pointer template inline void _arrayMoveBackward_Pointer(TValue * source_begin, TValue * source_end, TValue * target_begin, True); // "projects/library/seqan/basic/basic_alphabet_trait_basic.h"(307) template inline void _arrayMoveBackward_Pointer(TValue * source_begin, TValue * source_end, TValue * target_begin, False); // "projects/library/seqan/basic/basic_alphabet_trait_basic.h"(317) //____________________________________________________________________________ // _arrayMoveForward_Default template inline void _arrayMoveForward_Default(TSource1 source_begin, TSource2 source_end, TTarget target_begin); // "projects/library/seqan/basic/basic_alphabet_interface.h"(630) //____________________________________________________________________________ // _arrayMoveForward_Pointer template inline void _arrayMoveForward_Pointer(TValue * source_begin, TValue * source_end, TValue * target_begin, True); // "projects/library/seqan/basic/basic_alphabet_trait_basic.h"(273) template inline void _arrayMoveForward_Pointer(TValue * source_begin, TValue * source_end, TValue * target_begin, False); // "projects/library/seqan/basic/basic_alphabet_trait_basic.h"(283) //____________________________________________________________________________ // _intPow template inline TValue _intPow(TValue a, TExponent b); // "projects/library/seqan/basic/basic_definition.h"(334) //____________________________________________________________________________ // _isSameType template inline bool _isSameType(); // "projects/library/seqan/basic/basic_definition.h"(393) //____________________________________________________________________________ // _max template inline const _Ty& _max(const _Ty& _Left, const _Ty& _Right); // "projects/library/seqan/basic/basic_definition.h"(367) //____________________________________________________________________________ // _min template inline const _Tx& _min(const _Tx& _Left, const _Tx& _Right); // "projects/library/seqan/basic/basic_definition.h"(352) template inline _Tx _min(const _Tx& _Left, const _Ty& _Right); // "projects/library/seqan/basic/basic_definition.h"(361) //____________________________________________________________________________ // _toParameter template typename _Parameter::Type _toParameter(T * _object); // "projects/library/seqan/basic/basic_type.h"(447) template typename _Parameter::Type _toParameter(T _object); // "projects/library/seqan/basic/basic_type.h"(454) //____________________________________________________________________________ // _toPointer template typename _Pointer::Type _toPointer(T & _object); // "projects/library/seqan/basic/basic_type.h"(553) template typename _Pointer::Type _toPointer(T const & _object); // "projects/library/seqan/basic/basic_type.h"(560) template typename _Pointer::Type _toPointer(T * _object); // "projects/library/seqan/basic/basic_type.h"(568) //____________________________________________________________________________ // addRef template inline void addRef(T & ); // "projects/library/seqan/basic/basic_holder.h"(45) template inline void addRef(T const & ); // "projects/library/seqan/basic/basic_holder.h"(51) //____________________________________________________________________________ // allocate template inline void allocate(Allocator > & me, TValue * & data, TSize count, Tag const tag_); // "projects/library/seqan/basic/basic_allocator_singlepool.h"(162) template inline void allocate(Allocator > & me, TValue2 * & data, TSize count, Tag const tag_); // "projects/library/seqan/basic/basic_allocator_singlepool.h"(279) template inline void allocate(Allocator > & me, TValue * & data, TSize count, Tag const tag_); // "projects/library/seqan/basic/basic_allocator_multipool.h"(165) template inline void allocate(Allocator > & me, TValue * & data, TSize count, Tag const); // "projects/library/seqan/basic/basic_allocator_simple.h"(146) template inline void allocate(T const & me, TValue * & data, TSize count); // "projects/library/seqan/basic/basic_allocator_interface.h"(129) template inline void allocate(T & me, TValue * & data, TSize count); // "projects/library/seqan/basic/basic_allocator_interface.h"(137) template inline void allocate(T const &, TValue * & data, TSize count, Tag const); // "projects/library/seqan/basic/basic_allocator_interface.h"(147) template inline void allocate(T &, TValue * & data, TSize count, Tag const); // "projects/library/seqan/basic/basic_allocator_interface.h"(158) //template inline void allocate(Allocator > & me, TValue * & data, TSize count, Tag const tag_); // "projects/library/seqan/basic/basic_allocator_chunkpool.h"(173) template inline void allocate(Allocator > & me, TValue2 * & data, TSize count, Tag const tag_); // "projects/library/seqan/basic/basic_allocator_chunkpool.h"(302) //____________________________________________________________________________ // arrayClearSpace template void arrayClearSpace(TIterator array_begin, size_t array_length, size_t keep_from, size_t move_to); // "projects/library/seqan/basic/basic_alphabet_interface.h"(818) template void arrayClearSpace(TValue * array_begin, size_t array_length, size_t keep_from, size_t move_to); // "projects/library/seqan/basic/basic_alphabet_trait_basic.h"(362) //____________________________________________________________________________ // arrayConstruct template inline void arrayConstruct(TIterator1 begin_, TIterator2 end_); // "projects/library/seqan/basic/basic_alphabet_interface.h"(292) template inline void arrayConstruct(TIterator1 begin_, TIterator2 end_, TParam const & param_); // "projects/library/seqan/basic/basic_alphabet_interface.h"(317) template inline void arrayConstruct(TValue * begin_, TValue * end_); // "projects/library/seqan/basic/basic_alphabet_trait_basic.h"(53) template inline void arrayConstruct(TValue * begin_, TValue * end_, TParam const & param_); // "projects/library/seqan/basic/basic_alphabet_trait_basic.h"(85) //____________________________________________________________________________ // arrayConstructCopy template inline void arrayConstructCopy(TSource1 source_begin, TSource2 source_end, TTarget target_begin); // "projects/library/seqan/basic/basic_alphabet_interface.h"(364) template inline void arrayConstructCopy(TValue * source_begin, TValue * source_end, TValue * target_begin); // "projects/library/seqan/basic/basic_alphabet_trait_basic.h"(119) //____________________________________________________________________________ // arrayConstructMove template inline void arrayConstructMove(TSource1 source_begin, TSource2 source_end, TTarget target_begin); // "projects/library/seqan/basic/basic_alphabet_interface.h"(412) template inline void arrayConstructMove(TValue * source_begin, TValue * source_end, TValue * target_begin); // "projects/library/seqan/basic/basic_alphabet_trait_basic.h"(153) //____________________________________________________________________________ // arrayCopy template inline void arrayCopy(TSource1 source_begin, TSource2 source_end, TTarget target_begin); // "projects/library/seqan/basic/basic_alphabet_interface.h"(591) //____________________________________________________________________________ // arrayCopyBackward template inline void arrayCopyBackward(TSource1 source_begin, TSource2 source_end, TTarget target_begin); // "projects/library/seqan/basic/basic_alphabet_interface.h"(556) template inline void arrayCopyBackward(TValue * source_begin, TValue * source_end, TValue * target_begin); // "projects/library/seqan/basic/basic_alphabet_trait_basic.h"(258) //____________________________________________________________________________ // arrayCopyForward template inline void arrayCopyForward(TSource1 source_begin, TSource2 source_end, TTarget target_begin); // "projects/library/seqan/basic/basic_alphabet_interface.h"(513) template inline void arrayCopyForward(TValue * source_begin, TValue * source_end, TValue * target_begin); // "projects/library/seqan/basic/basic_alphabet_trait_basic.h"(224) //____________________________________________________________________________ // arrayDestruct template inline void arrayDestruct(TIterator1 begin_, TIterator2 end_); // "projects/library/seqan/basic/basic_alphabet_interface.h"(448) template inline void arrayDestruct(TValue * begin_, TValue * end_); // "projects/library/seqan/basic/basic_alphabet_trait_basic.h"(184) //____________________________________________________________________________ // arrayFill template inline void arrayFill(TIterator1 begin_, TIterator2 end_, TValue const & value); // "projects/library/seqan/basic/basic_alphabet_interface.h"(474) //____________________________________________________________________________ // arrayMove template inline void arrayMove(TSource1 source_begin, TSource2 source_end, TTarget target_begin); // "projects/library/seqan/basic/basic_alphabet_interface.h"(732) //____________________________________________________________________________ // arrayMoveBackward template inline void arrayMoveBackward(TSource1 source_begin, TSource2 source_end, TTarget target_begin); // "projects/library/seqan/basic/basic_alphabet_interface.h"(694) template inline void arrayMoveBackward(TValue * source_begin, TValue * source_end, TValue * target_begin); // "projects/library/seqan/basic/basic_alphabet_trait_basic.h"(326) //____________________________________________________________________________ // arrayMoveForward template inline void arrayMoveForward(TSource1 source_begin, TSource2 source_end, TTarget target_begin); // "projects/library/seqan/basic/basic_alphabet_interface.h"(644) template inline void arrayMoveForward(TValue * source_begin, TValue * source_end, TValue * target_begin); // "projects/library/seqan/basic/basic_alphabet_trait_basic.h"(292) //____________________________________________________________________________ // assign template inline void assign(SimpleType & target, SimpleType & source); // "projects/library/seqan/basic/basic_alphabet_simple.h"(294) template inline void assign(SimpleType & target, SimpleType const & source); // "projects/library/seqan/basic/basic_alphabet_simple.h"(302) template inline void assign(SimpleType & target, TSource & source); // "projects/library/seqan/basic/basic_alphabet_simple.h"(313) template inline void assign(SimpleType & target, TSource const & source); // "projects/library/seqan/basic/basic_alphabet_simple.h"(321) template inline void assign(SimpleType & target, Proxy & source); // "projects/library/seqan/basic/basic_alphabet_simple.h"(334) template inline void assign(SimpleType & target, Proxy const & source); // "projects/library/seqan/basic/basic_alphabet_simple.h"(343) template inline void assign(int & c_target, SimpleType & source); // "projects/library/seqan/basic/basic_alphabet_simple.h"(358) template inline void assign(int & c_target, SimpleType const & source); // "projects/library/seqan/basic/basic_alphabet_simple.h"(366) template inline void assign(unsigned int & c_target, SimpleType & source); // "projects/library/seqan/basic/basic_alphabet_simple.h"(376) template inline void assign(unsigned int & c_target, SimpleType const & source); // "projects/library/seqan/basic/basic_alphabet_simple.h"(384) template inline void assign(short & c_target, SimpleType & source); // "projects/library/seqan/basic/basic_alphabet_simple.h"(394) template inline void assign(short & c_target, SimpleType const & source); // "projects/library/seqan/basic/basic_alphabet_simple.h"(402) template inline void assign(unsigned short & c_target, SimpleType & source); // "projects/library/seqan/basic/basic_alphabet_simple.h"(412) template inline void assign(unsigned short & c_target, SimpleType const & source); // "projects/library/seqan/basic/basic_alphabet_simple.h"(420) template inline void assign(char & c_target, SimpleType & source); // "projects/library/seqan/basic/basic_alphabet_simple.h"(430) template inline void assign(char & c_target, SimpleType const & source); // "projects/library/seqan/basic/basic_alphabet_simple.h"(438) template inline void assign(signed char & c_target, SimpleType & source); // "projects/library/seqan/basic/basic_alphabet_simple.h"(448) template inline void assign(signed char & c_target, SimpleType const & source); // "projects/library/seqan/basic/basic_alphabet_simple.h"(456) template inline void assign(unsigned char & c_target, SimpleType & source); // "projects/library/seqan/basic/basic_alphabet_simple.h"(466) template inline void assign(unsigned char & c_target, SimpleType const & source); // "projects/library/seqan/basic/basic_alphabet_simple.h"(474) inline void assign(Ascii & c_target, Dna const & source); // "projects/library/seqan/basic/basic_alphabet_simple.h"(1096) inline void assign(Ascii & c_target, Dna5 const & source); // "projects/library/seqan/basic/basic_alphabet_simple.h"(1104) inline void assign(Ascii & c_target, Iupac const & source); // "projects/library/seqan/basic/basic_alphabet_simple.h"(1111) inline void assign(Ascii & c_target, AminoAcid const & source); // "projects/library/seqan/basic/basic_alphabet_simple.h"(1118) inline void assign(Dna & target, Byte c_source); // "projects/library/seqan/basic/basic_alphabet_simple.h"(1129) inline void assign(Dna & target, Ascii c_source); // "projects/library/seqan/basic/basic_alphabet_simple.h"(1138) inline void assign(Dna & target, Unicode c_source); // "projects/library/seqan/basic/basic_alphabet_simple.h"(1147) inline void assign(Dna & target, Dna5 const & c_source); // "projects/library/seqan/basic/basic_alphabet_simple.h"(1156) inline void assign(Dna & target, Iupac const & source); // "projects/library/seqan/basic/basic_alphabet_simple.h"(1165) inline void assign(Dna5 & target, Byte c_source); // "projects/library/seqan/basic/basic_alphabet_simple.h"(1176) inline void assign(Dna5 & target, Ascii c_source); // "projects/library/seqan/basic/basic_alphabet_simple.h"(1185) inline void assign(Dna5 & target, Unicode c_source); // "projects/library/seqan/basic/basic_alphabet_simple.h"(1194) inline void assign(Dna5 & target, Iupac const & source); // "projects/library/seqan/basic/basic_alphabet_simple.h"(1203) inline void assign(Dna5 & target, Dna const & c_source); // "projects/library/seqan/basic/basic_alphabet_simple.h"(1213) inline void assign(Iupac & target, Byte c_source); // "projects/library/seqan/basic/basic_alphabet_simple.h"(1224) inline void assign(Iupac & target, Ascii c_source); // "projects/library/seqan/basic/basic_alphabet_simple.h"(1233) inline void assign(Iupac & target, Unicode c_source); // "projects/library/seqan/basic/basic_alphabet_simple.h"(1242) inline void assign(Iupac & target, Dna const & source); // "projects/library/seqan/basic/basic_alphabet_simple.h"(1249) inline void assign(Iupac & target, Dna5 const & source); // "projects/library/seqan/basic/basic_alphabet_simple.h"(1256) inline void assign(AminoAcid & target, Byte c_source); // "projects/library/seqan/basic/basic_alphabet_simple.h"(1267) inline void assign(AminoAcid & target, Ascii c_source); // "projects/library/seqan/basic/basic_alphabet_simple.h"(1276) inline void assign(AminoAcid & target, Unicode c_source); // "projects/library/seqan/basic/basic_alphabet_simple.h"(1285) template inline void assign(TTarget & target, TSource & source); // "projects/library/seqan/basic/basic_transport.h"(52) template inline void assign(TTarget & target, TSource const & source); // "projects/library/seqan/basic/basic_transport.h"(60) template inline void assign(Proxy & target, TSource & source); // "projects/library/seqan/basic/basic_transport.h"(73) template inline void assign(Proxy & target, TSource const & source); // "projects/library/seqan/basic/basic_transport.h"(82) template inline void assign(Iter & target, TSource const & source); // "projects/library/seqan/basic/basic_iterator_position.h"(440) template inline void assign(Holder & target_, Holder const & source_); // "projects/library/seqan/basic/basic_holder.h"(554) template inline void assign(Holder & target_, Holder const & source_); // "projects/library/seqan/basic/basic_holder.h"(774) template inline void assign(Holder & target_, Holder const & source_); // "projects/library/seqan/basic/basic_holder.h"(1091) template inline void assign(Iter > & target, TSource const & source); // "projects/library/seqan/basic/basic_iterator_adaptor.h"(514) template inline void assign(Iter & target, TSource const & source); // "projects/library/seqan/basic/basic_iterator_adapt_std.h"(427) //____________________________________________________________________________ // assignHost template inline void assignHost(T & me, THost & host_); // "projects/library/seqan/basic/basic_host.h"(135) template inline void assignHost(T & me, THost const & host_); // "projects/library/seqan/basic/basic_host.h"(143) //____________________________________________________________________________ // assignValue template inline void assignValue(Iter & me, TValue _value); // "projects/library/seqan/basic/basic_iterator_position.h"(184) template inline void assignValue(Iter const & me, TValue _value); // "projects/library/seqan/basic/basic_iterator_position.h"(192) template inline void assignValue(Holder & me, TSource const & value_); // "projects/library/seqan/basic/basic_holder.h"(512) template inline void assignValue(Holder & me, TSource const & value_); // "projects/library/seqan/basic/basic_holder.h"(752) template inline void assignValue(Holder & me, TSource const & value_); // "projects/library/seqan/basic/basic_holder.h"(1049) template inline void assignValue(T & me, TValue const & _value); // "projects/library/seqan/basic/basic_iterator.h"(258) template inline void assignValue(T const & me, TValue const & _value); // "projects/library/seqan/basic/basic_iterator.h"(268) template inline void assignValue(Iter > & me, TValue const & _value); // "projects/library/seqan/basic/basic_iterator_adaptor.h"(288) template inline void assignValue(Iter > const & me, TValue const & _value); // "projects/library/seqan/basic/basic_iterator_adaptor.h"(296) template inline void assignValue(Iter & me, TValue & val); // "projects/library/seqan/basic/basic_iterator_adapt_std.h"(165) template inline void assignValue(Iter & me, TValue const & val); // "projects/library/seqan/basic/basic_iterator_adapt_std.h"(172) //____________________________________________________________________________ // assignValueAt template inline TSource & assignValueAt(TObject &me, TPos k, TSource &source); // "projects/library/seqan/basic/basic_aggregates.h"(442) template inline TSource const & assignValueAt(TObject &me, TPos k, TSource const &source); // "projects/library/seqan/basic/basic_aggregates.h"(449) template inline SSS const assignValueAt(Tuple &me, TPos k, SSS const source); // "projects/library/seqan/basic/basic_aggregates.h"(455) template inline SSS const assignValueAt(Tuple &me, TPos k, SSS const source); // "projects/library/seqan/basic/basic_aggregates.h"(460) template inline SimpleType const & assignValueAt(Tuple &me, TPos k, SimpleType const &source); // "projects/library/seqan/basic/basic_aggregates.h"(468) //____________________________________________________________________________ // assignValueI1 template inline void assignValueI1(Pair &pair, T const &_i); // "projects/library/seqan/basic/basic_aggregates.h"(613) template inline void assignValueI1(Pair > &pair, T const &_i); // "projects/library/seqan/basic/basic_aggregates.h"(624) template inline T const assignValueI1(Triple &triple, T const &_i); // "projects/library/seqan/basic/basic_aggregates.h"(638) //____________________________________________________________________________ // assignValueI2 template inline void assignValueI2(Pair &pair, T const &_i); // "projects/library/seqan/basic/basic_aggregates.h"(618) template inline void assignValueI2(Pair > &pair, T const &_i); // "projects/library/seqan/basic/basic_aggregates.h"(631) template inline T const assignValueI2(Triple &triple, T const &_i); // "projects/library/seqan/basic/basic_aggregates.h"(643) //____________________________________________________________________________ // assignValueI3 template inline T const assignValueI3(Triple &triple, T const &_i); // "projects/library/seqan/basic/basic_aggregates.h"(648) //____________________________________________________________________________ // atBegin template inline bool atBegin(T const & it, TContainer const & cont); // "projects/library/seqan/basic/basic_iterator.h"(394) template inline bool atBegin(T const & it); // "projects/library/seqan/basic/basic_iterator.h"(404) //____________________________________________________________________________ // atEnd template inline bool atEnd(T & it, TContainer const & cont); // "projects/library/seqan/basic/basic_iterator.h"(435) template inline bool atEnd(T const & it, TContainer const & cont); // "projects/library/seqan/basic/basic_iterator.h"(443) template inline bool atEnd(T & it); // "projects/library/seqan/basic/basic_iterator.h"(452) template inline bool atEnd(T const & it); // "projects/library/seqan/basic/basic_iterator.h"(459) template inline bool atEnd(Iter > & me); // "projects/library/seqan/basic/basic_iterator_adaptor.h"(501) //____________________________________________________________________________ // atNil template inline bool atNil(TIterator & me); // "projects/library/seqan/basic/basic_iterator.h"(714) template inline bool atNil(TIterator * me); // "projects/library/seqan/basic/basic_iterator.h"(723) //____________________________________________________________________________ // call_allocate template inline void call_allocate(TMe & me, TValue * & data, TSize const count); // "projects/library/seqan/basic/basic_allocator_to_std.h"(33) //____________________________________________________________________________ // call_deallocate template inline void call_deallocate(TMe & me, TValue * data, TSize const count); // "projects/library/seqan/basic/basic_allocator_to_std.h"(38) //____________________________________________________________________________ // clear template void clear(Allocator > & me); // "projects/library/seqan/basic/basic_allocator_singlepool.h"(146) template void clear(Allocator > & me); // "projects/library/seqan/basic/basic_allocator_singlepool.h"(266) template inline void clear(Holder & me); // "projects/library/seqan/basic/basic_holder.h"(314) template inline void clear(Holder & me); // "projects/library/seqan/basic/basic_holder.h"(685) template inline void clear(Holder & me); // "projects/library/seqan/basic/basic_holder.h"(901) template void clear(Allocator > & me); // "projects/library/seqan/basic/basic_allocator_multipool.h"(125) template void clear(Allocator > & me); // "projects/library/seqan/basic/basic_allocator_simple.h"(126) //template void clear(Allocator > & me); // "projects/library/seqan/basic/basic_allocator_chunkpool.h"(157) template void clear(Allocator > & me); // "projects/library/seqan/basic/basic_allocator_chunkpool.h"(289) template inline void clear(Tuple &me); // "projects/library/seqan/basic/basic_aggregates.h"(479) template inline void clear(Tuple &me); // "projects/library/seqan/basic/basic_aggregates.h"(483) //____________________________________________________________________________ // clearHost template inline void clearHost(T & me); // "projects/library/seqan/basic/basic_host.h"(59) //____________________________________________________________________________ // container template inline typename Container::Type container(T me); // "projects/library/seqan/basic/basic_iterator.h"(328) //____________________________________________________________________________ // convert template inline typename Convert::Type convert(TSource const & source); // "projects/library/seqan/basic/basic_converter.h"(110) //____________________________________________________________________________ // convertImpl template inline typename _RemoveConst::Type convertImpl(Convert const, SimpleType const & source_); // "projects/library/seqan/basic/basic_alphabet_simple.h"(247) template inline typename Convert >::Type convertImpl(Convert const, Proxy & source); // "projects/library/seqan/basic/basic_proxy.h"(264) template inline typename Convert const>::Type convertImpl(Convert const, Proxy const & source); // "projects/library/seqan/basic/basic_proxy.h"(271) template inline typename Convert::Type convertImpl(Convert const, TSource & source); // "projects/library/seqan/basic/basic_converter.h"(78) template inline typename Convert::Type convertImpl(Convert const, TSource const & source); // "projects/library/seqan/basic/basic_converter.h"(85) //____________________________________________________________________________ // create template inline void create(Holder & me); // "projects/library/seqan/basic/basic_holder.h"(361) template inline void create(Holder & me, typename _Parameter::Type value_); // "projects/library/seqan/basic/basic_holder.h"(395) template inline void create(Holder & me); // "projects/library/seqan/basic/basic_holder.h"(694) template inline void create(Holder & me, TValue const & value_); // "projects/library/seqan/basic/basic_holder.h"(704) template inline void create(Holder & me); // "projects/library/seqan/basic/basic_holder.h"(932) template inline void create(Holder & me, TValue const & value_); // "projects/library/seqan/basic/basic_holder.h"(966) //____________________________________________________________________________ // createHost template inline void createHost(T & me); // "projects/library/seqan/basic/basic_host.h"(69) template inline void createHost(T & me, THost & host_); // "projects/library/seqan/basic/basic_host.h"(80) template inline void createHost(T & me, THost const & host_); // "projects/library/seqan/basic/basic_host.h"(88) //____________________________________________________________________________ // deallocate template inline void deallocate(Allocator > & me, TValue * data, TSize count, Tag const tag_); // "projects/library/seqan/basic/basic_allocator_singlepool.h"(202) template inline void deallocate(Allocator > & me, TValue2 * data, TSize count, Tag const tag_); // "projects/library/seqan/basic/basic_allocator_singlepool.h"(290) template inline void deallocate(Allocator > & me, TValue * data, TSize count, Tag const tag_); // "projects/library/seqan/basic/basic_allocator_multipool.h"(207) template inline void deallocate(Allocator > & me, TValue * data, TSize, Tag const); // "projects/library/seqan/basic/basic_allocator_simple.h"(181) template inline void deallocate(T const & me, TValue * data, TSize const count); // "projects/library/seqan/basic/basic_allocator_interface.h"(198) template inline void deallocate(T & me, TValue * data, TSize const count); // "projects/library/seqan/basic/basic_allocator_interface.h"(206) template inline void deallocate(T const & , TValue * data, TSize count, Tag const); // "projects/library/seqan/basic/basic_allocator_interface.h"(216) template inline void deallocate(T & , TValue * data, TSize count, Tag const); // "projects/library/seqan/basic/basic_allocator_interface.h"(227) //template inline void deallocate(Allocator > & me, TValue * data, TSize count, Tag const tag_); // "projects/library/seqan/basic/basic_allocator_chunkpool.h"(222) template inline void deallocate(Allocator > & me, TValue2 * data, TSize count, Tag const tag_); // "projects/library/seqan/basic/basic_allocator_chunkpool.h"(313) //____________________________________________________________________________ // dependent template inline bool dependent(Holder const & me); // "projects/library/seqan/basic/basic_holder.h"(300) template inline bool dependent(Holder const & me); // "projects/library/seqan/basic/basic_holder.h"(675) template inline bool dependent(Holder const & me); // "projects/library/seqan/basic/basic_holder.h"(887) //____________________________________________________________________________ // dependentHost template inline bool dependentHost(T const & me); // "projects/library/seqan/basic/basic_host.h"(49) //____________________________________________________________________________ // detach template inline void detach(Holder & me); // "projects/library/seqan/basic/basic_holder.h"(430) template inline void detach(Holder & me); // "projects/library/seqan/basic/basic_holder.h"(714) template inline void detach(Holder & me); // "projects/library/seqan/basic/basic_holder.h"(987) //____________________________________________________________________________ // difference template inline typename Difference::Type difference( TIterator const & begin, TIterator const & end); // "projects/library/seqan/basic/basic_iterator.h"(657) //____________________________________________________________________________ // empty template inline bool empty(Holder const & me); // "projects/library/seqan/basic/basic_holder.h"(288) template inline bool empty(Holder const & me); // "projects/library/seqan/basic/basic_holder.h"(665) template inline bool empty(Holder const & me); // "projects/library/seqan/basic/basic_holder.h"(875) //____________________________________________________________________________ // emptyHost template inline bool emptyHost(T const & me); // "projects/library/seqan/basic/basic_host.h"(39) //____________________________________________________________________________ // gapValue template inline T const & gapValue(); // "projects/library/seqan/basic/basic_alphabet_interface2.h"(71) //____________________________________________________________________________ // gapValueImpl inline char const & gapValueImpl(char *); // "projects/library/seqan/basic/basic_alphabet_trait_basic.h"(400) inline char const & gapValueImpl(char const *); // "projects/library/seqan/basic/basic_alphabet_trait_basic.h"(407) template inline T const & gapValueImpl(T *); // "projects/library/seqan/basic/basic_alphabet_interface2.h"(48) //____________________________________________________________________________ // getValue template typename GetValue >::Type getValue(Proxy & me); // "projects/library/seqan/basic/basic_proxy.h"(235) template typename GetValue const>::Type getValue(Proxy const & me); // "projects/library/seqan/basic/basic_proxy.h"(241) template inline typename GetValue::Type getValue(T & me); // "projects/library/seqan/basic/basic_iterator.h"(210) template inline typename GetValue::Type getValue(T const & me); // "projects/library/seqan/basic/basic_iterator.h"(217) template inline T & getValue(T * me); // "projects/library/seqan/basic/basic_iterator.h"(225) //____________________________________________________________________________ // getValueI1 template inline T1 getValueI1(Pair const &pair); // "projects/library/seqan/basic/basic_aggregates.h"(572) template inline T1 getValueI1(Pair > const &pair); // "projects/library/seqan/basic/basic_aggregates.h"(582) template inline T1 getValueI1(Triple const &triple); // "projects/library/seqan/basic/basic_aggregates.h"(595) //____________________________________________________________________________ // getValueI2 template inline T2 getValueI2(Pair const &pair); // "projects/library/seqan/basic/basic_aggregates.h"(577) template inline T2 getValueI2(Pair > const &pair); // "projects/library/seqan/basic/basic_aggregates.h"(588) template inline T2 getValueI2(Triple const &triple); // "projects/library/seqan/basic/basic_aggregates.h"(600) //____________________________________________________________________________ // getValueI3 template inline T3 getValueI3(Triple const &triple); // "projects/library/seqan/basic/basic_aggregates.h"(605) //____________________________________________________________________________ // goBegin template inline void goBegin(TIterator & it, TContainer & container); // "projects/library/seqan/basic/basic_iterator.h"(488) template inline void goBegin(TIterator & it); // "projects/library/seqan/basic/basic_iterator.h"(506) //____________________________________________________________________________ // goEnd template inline void goEnd(TIterator & it, TContainer & container); // "projects/library/seqan/basic/basic_iterator.h"(536) template inline void goEnd(TIterator & it, TContainer const & container); // "projects/library/seqan/basic/basic_iterator.h"(544) template inline void goEnd(TIterator & it); // "projects/library/seqan/basic/basic_iterator.h"(552) //____________________________________________________________________________ // goFurther template inline void goFurther(TIterator & it, TDiff steps); // "projects/library/seqan/basic/basic_iterator.h"(602) //____________________________________________________________________________ // goNext template inline void goNext(Iter & me); // "projects/library/seqan/basic/basic_iterator_position.h"(295) template inline void goNext(TIterator & it); // "projects/library/seqan/basic/basic_iterator.h"(576) template inline void goNext(Iter > & me); // "projects/library/seqan/basic/basic_iterator_adaptor.h"(355) template inline void goNext(Iter & me); // "projects/library/seqan/basic/basic_iterator_adapt_std.h"(280) //____________________________________________________________________________ // goNil template inline void goNil(TIterator & me); // "projects/library/seqan/basic/basic_iterator.h"(681) template inline void goNil(TIterator * & me); // "projects/library/seqan/basic/basic_iterator.h"(689) //____________________________________________________________________________ // goPrevious template inline void goPrevious(Iter & me); // "projects/library/seqan/basic/basic_iterator_position.h"(307) template inline void goPrevious(TIterator & it); // "projects/library/seqan/basic/basic_iterator.h"(626) template inline void goPrevious(Iter > & me); // "projects/library/seqan/basic/basic_iterator_adaptor.h"(367) template inline void goPrevious(Iter & me); // "projects/library/seqan/basic/basic_iterator_adapt_std.h"(292) //____________________________________________________________________________ // host template inline typename Host::Type & host(T & me); // "projects/library/seqan/basic/basic_host.h"(117) template inline typename Host::Type & host(T const & me); // "projects/library/seqan/basic/basic_host.h"(124) //____________________________________________________________________________ // hostIterator template inline typename StdContainerIterator::Type & hostIterator(Iter & me); // "projects/library/seqan/basic/basic_iterator_adapt_std.h"(129) template inline typename StdContainerIterator::Type const & hostIterator(Iter const & me); // "projects/library/seqan/basic/basic_iterator_adapt_std.h"(135) //____________________________________________________________________________ // infimumValue template inline T const & infimumValue(); // "projects/library/seqan/basic/basic_alphabet_interface2.h"(169) //____________________________________________________________________________ // infimumValueImpl template inline T const & infimumValueImpl(T *); // "projects/library/seqan/basic/basic_alphabet_trait_basic.h"(427) inline float const & infimumValueImpl(float *); // "projects/library/seqan/basic/basic_alphabet_trait_basic.h"(666) inline double const & infimumValueImpl(double *); // "projects/library/seqan/basic/basic_alphabet_trait_basic.h"(693) inline long double const & infimumValueImpl(long double *); // "projects/library/seqan/basic/basic_alphabet_trait_basic.h"(720) //____________________________________________________________________________ // length template inline unsigned length(Tuple const &); // "projects/library/seqan/basic/basic_aggregates.h"(428) //____________________________________________________________________________ // lexLess template inline bool lexLess(SimpleType const &Left, SimpleType const &Right); // "projects/library/seqan/basic/basic_alphabet_simple.h"(948) template inline bool lexLess(const TTT& Left, const TTT& Right); // "projects/library/seqan/basic/basic_compare.h"(52) //____________________________________________________________________________ // log2 // projects/library/seqan/basic/basic_definition.h(322) //template inline unsigned int log2(TTT v); //____________________________________________________________________________ // memset template finline void memset(void* ptr, unsigned char c); // "projects/library/seqan/basic/basic_metaprogramming.h"(241) template finline void memset(void* ptr); // "projects/library/seqan/basic/basic_metaprogramming.h"(287) //____________________________________________________________________________ // move template inline void move(TTarget & target, TSource & source); // "projects/library/seqan/basic/basic_transport.h"(108) template inline void move(TTarget const & target, TSource & source); // "projects/library/seqan/basic/basic_transport.h"(116) template inline void move(TTarget & target, TSource const & source); // "projects/library/seqan/basic/basic_transport.h"(124) template inline void move(TTarget const & target, TSource const & source); // "projects/library/seqan/basic/basic_transport.h"(132) //____________________________________________________________________________ // moveHost template inline void moveHost(T & me, THost & host_); // "projects/library/seqan/basic/basic_host.h"(153) template inline void moveHost(T & me, THost const & host_); // "projects/library/seqan/basic/basic_host.h"(161) //____________________________________________________________________________ // moveValue template inline void moveValue(Iter & me, TValue _value); // "projects/library/seqan/basic/basic_iterator_position.h"(205) template inline void moveValue(Iter const & me, TValue _value); // "projects/library/seqan/basic/basic_iterator_position.h"(213) template inline void moveValue(Holder & me, TSource const & value_); // "projects/library/seqan/basic/basic_holder.h"(533) template inline void moveValue(Holder & me, TSource const & value_); // "projects/library/seqan/basic/basic_holder.h"(763) template inline void moveValue(Holder & me, TSource const & value_); // "projects/library/seqan/basic/basic_holder.h"(1070) template inline void moveValue(T & me, TValue const & _value); // "projects/library/seqan/basic/basic_iterator.h"(297) template inline void moveValue(T const & me, TValue const & _value); // "projects/library/seqan/basic/basic_iterator.h"(306) template inline void moveValue(Iter > & me, TValue const & _value); // "projects/library/seqan/basic/basic_iterator_adaptor.h"(309) template inline void moveValue(Iter > const & me, TValue const & _value); // "projects/library/seqan/basic/basic_iterator_adaptor.h"(317) template inline void moveValue(Iter & me, TValue & val); // "projects/library/seqan/basic/basic_iterator_adapt_std.h"(184) template inline void moveValue(Iter & me, TValue const & val); // "projects/library/seqan/basic/basic_iterator_adapt_std.h"(191) //____________________________________________________________________________ // nukeCopies template inline void nukeCopies(TValue* &); // "projects/library/seqan/basic/basic_volatile_ptr.h"(152) template inline void nukeCopies(VolatilePtr &ptr); // "projects/library/seqan/basic/basic_volatile_ptr.h"(155) //____________________________________________________________________________ // operator!= template inline bool operator!= (SimpleType const & left_, TRight const & right_); // "projects/library/seqan/basic/basic_alphabet_simple.h"(594) template inline bool operator!= (TLeft const & left_, SimpleType const & right_); // "projects/library/seqan/basic/basic_alphabet_simple.h"(605) template inline bool operator!= (SimpleType const & left_, SimpleType const & right_); // "projects/library/seqan/basic/basic_alphabet_simple.h"(616) template inline bool operator!= (SimpleType const & left_, SimpleType const & right_); // "projects/library/seqan/basic/basic_alphabet_simple.h"(628) template inline bool operator!= (Proxy const & left_, SimpleType const & right_); // "projects/library/seqan/basic/basic_alphabet_simple.h"(638) template inline bool operator!= (SimpleType const & left_, Proxy const & right_); // "projects/library/seqan/basic/basic_alphabet_simple.h"(649) template inline bool operator!= (Iter const & left, Iter const & right); // "projects/library/seqan/basic/basic_iterator_position.h"(239) template inline bool operator!= (Proxy const & left_, TRight const & right_); // "projects/library/seqan/basic/basic_proxy.h"(328) template inline bool operator!= (TLeft const & left_, Proxy const & right_); // "projects/library/seqan/basic/basic_proxy.h"(339) template inline bool operator!= (Proxy const & left_, Proxy const & right_); // "projects/library/seqan/basic/basic_proxy.h"(350) template inline bool operator!= (Proxy const & left_, Proxy const & right_); // "projects/library/seqan/basic/basic_proxy.h"(362) template inline bool operator!= (Iter > const & left, Iter > const & right); // "projects/library/seqan/basic/basic_iterator_adaptor.h"(343) template inline bool operator!=(Tuple const &_left, Tuple const &_right); // "projects/library/seqan/basic/basic_aggregates.h"(503) template inline bool operator!=(Pair const &_left, Pair const &_right); // "projects/library/seqan/basic/basic_aggregates.h"(660) template inline bool operator!=(Pair > const &_left, Pair > const &_right); // "projects/library/seqan/basic/basic_aggregates.h"(669) template inline bool operator!=(Triple const &_left, Triple const &_right); // "projects/library/seqan/basic/basic_aggregates.h"(683) template inline bool operator!= (Iter const & left, Iter const & right); // "projects/library/seqan/basic/basic_iterator_adapt_std.h"(216) //____________________________________________________________________________ // operator* template inline typename Reference >::Type operator* (Iter & me); // "projects/library/seqan/basic/basic_iterator_base.h"(143) template inline typename Reference const>::Type operator* (Iter const & me); // "projects/library/seqan/basic/basic_iterator_base.h"(150) //____________________________________________________________________________ // operator+ template inline Iter operator+ (Iter const & left, TIntegral right); // "projects/library/seqan/basic/basic_iterator_position.h"(319) template inline Iter operator+ (Iter const & left, int right); // "projects/library/seqan/basic/basic_iterator_position.h"(328) template inline Iter operator+ (TIntegral left, Iter const & right); // "projects/library/seqan/basic/basic_iterator_position.h"(337) template inline Iter operator+ (int left, Iter const & right); // "projects/library/seqan/basic/basic_iterator_position.h"(346) template inline Iter > operator+ (Iter > const & left, TIntegral right); // "projects/library/seqan/basic/basic_iterator_adaptor.h"(380) template inline Iter > operator+ (Iter > const & left, int right); // "projects/library/seqan/basic/basic_iterator_adaptor.h"(389) template inline Iter > operator+ (TIntegral left, Iter > const & right); // "projects/library/seqan/basic/basic_iterator_adaptor.h"(398) template inline Iter > operator+ (int left, Iter > const & right); // "projects/library/seqan/basic/basic_iterator_adaptor.h"(407) template inline Iter operator+ (Iter const & left, TIntegral right); // "projects/library/seqan/basic/basic_iterator_adapt_std.h"(305) template inline Iter operator+ (Iter const & left, int right); // "projects/library/seqan/basic/basic_iterator_adapt_std.h"(314) template inline Iter operator+ (TIntegral left, Iter const & right); // "projects/library/seqan/basic/basic_iterator_adapt_std.h"(323) template inline Iter operator+ (int left, Iter const & right); // "projects/library/seqan/basic/basic_iterator_adapt_std.h"(332) //____________________________________________________________________________ // operator++ template inline SimpleType & operator++ (SimpleType & me); // "projects/library/seqan/basic/basic_alphabet_simple.h"(958) template inline SimpleType operator++ (SimpleType & me, int); // "projects/library/seqan/basic/basic_alphabet_simple.h"(966) template inline Iter const & operator++ (Iter & me); // "projects/library/seqan/basic/basic_iterator_base.h"(162) template inline Iter const operator++ (Iter & me, int); // "projects/library/seqan/basic/basic_iterator_base.h"(171) //____________________________________________________________________________ // operator+= template inline Iter & operator+= (Iter & left, TIntegral right); // "projects/library/seqan/basic/basic_iterator_position.h"(359) template inline Iter & operator+= (Iter & left, int right); // "projects/library/seqan/basic/basic_iterator_position.h"(369) template inline Iter > & operator+= (Iter > & left, TIntegral right); // "projects/library/seqan/basic/basic_iterator_adaptor.h"(420) template inline Iter > & operator+= (Iter > & left, int right); // "projects/library/seqan/basic/basic_iterator_adaptor.h"(430) template inline Iter & operator+= (Iter & left, TIntegral right); // "projects/library/seqan/basic/basic_iterator_adapt_std.h"(345) template inline Iter & operator+= (Iter & left, int right); // "projects/library/seqan/basic/basic_iterator_adapt_std.h"(355) //____________________________________________________________________________ // operator- template inline Iter operator- (Iter const & left, TIntegral right); // "projects/library/seqan/basic/basic_iterator_position.h"(383) template inline Iter operator- (Iter const & left, int right); // "projects/library/seqan/basic/basic_iterator_position.h"(392) template inline typename Difference::Type operator- (Iter const & left, Iter const & right); // "projects/library/seqan/basic/basic_iterator_position.h"(403) template inline Iter > operator- (Iter > const & left, TIntegral right); // "projects/library/seqan/basic/basic_iterator_adaptor.h"(444) template inline Iter > operator- (Iter > const & left, int right); // "projects/library/seqan/basic/basic_iterator_adaptor.h"(453) template inline typename Difference > >::Type operator- (Iter > const & left, Iter > const & right); // "projects/library/seqan/basic/basic_iterator_adaptor.h"(464) template inline Iter operator- (Iter const & left, TIntegral right); // "projects/library/seqan/basic/basic_iterator_adapt_std.h"(369) template inline Iter operator- (Iter const & left, int right); // "projects/library/seqan/basic/basic_iterator_adapt_std.h"(378) template inline typename Difference >::Type operator- (Iter const & left, Iter const & right); // "projects/library/seqan/basic/basic_iterator_adapt_std.h"(389) //____________________________________________________________________________ // operator-- template inline SimpleType & operator-- (SimpleType & me); // "projects/library/seqan/basic/basic_alphabet_simple.h"(977) template inline SimpleType operator-- (SimpleType & me, int); // "projects/library/seqan/basic/basic_alphabet_simple.h"(985) template inline Iter const & operator-- (Iter & me); // "projects/library/seqan/basic/basic_iterator_base.h"(185) template inline Iter const operator-- (Iter & me, int); // "projects/library/seqan/basic/basic_iterator_base.h"(194) //____________________________________________________________________________ // operator-= template inline Iter & operator-= (Iter & left, TIntegral right); // "projects/library/seqan/basic/basic_iterator_position.h"(416) template inline Iter & operator-= (Iter & left, int right); // "projects/library/seqan/basic/basic_iterator_position.h"(426) template inline Iter > & operator-= (Iter > & left, TIntegral right); // "projects/library/seqan/basic/basic_iterator_adaptor.h"(477) template inline Iter > & operator-= (Iter > & left, int right); // "projects/library/seqan/basic/basic_iterator_adaptor.h"(487) template inline Iter & operator-= (Iter & left, TIntegral right); // "projects/library/seqan/basic/basic_iterator_adapt_std.h"(402) template inline Iter & operator-= (Iter & left, int right); // "projects/library/seqan/basic/basic_iterator_adapt_std.h"(412) //____________________________________________________________________________ // operator< template inline bool operator< (SimpleType const & left_, TRight const & right_); // "projects/library/seqan/basic/basic_alphabet_simple.h"(665) template inline bool operator< (TLeft const & left_, SimpleType const & right_); // "projects/library/seqan/basic/basic_alphabet_simple.h"(676) template inline bool operator< (SimpleType const & left_, SimpleType const & right_); // "projects/library/seqan/basic/basic_alphabet_simple.h"(687) template inline bool operator< (SimpleType const & left_, SimpleType const & right_); // "projects/library/seqan/basic/basic_alphabet_simple.h"(699) template inline bool operator< (Proxy const & left_, SimpleType const & right_); // "projects/library/seqan/basic/basic_alphabet_simple.h"(709) template inline bool operator< (SimpleType const & left_, Proxy const & right_); // "projects/library/seqan/basic/basic_alphabet_simple.h"(720) template inline bool operator< (Iter const & left, Iter const & right); // "projects/library/seqan/basic/basic_iterator_position.h"(252) template inline bool operator< (Proxy const & left_, TRight const & right_); // "projects/library/seqan/basic/basic_proxy.h"(376) template inline bool operator< (TLeft const & left_, Proxy const & right_); // "projects/library/seqan/basic/basic_proxy.h"(387) template inline bool operator< (Proxy const & left_, Proxy const & right_); // "projects/library/seqan/basic/basic_proxy.h"(398) template inline bool operator< (Proxy const & left_, Proxy const & right_); // "projects/library/seqan/basic/basic_proxy.h"(410) template inline bool operator<(Tuple const &_left, Tuple const &_right); // "projects/library/seqan/basic/basic_aggregates.h"(491) template inline bool operator< (Iter const & left, Iter const & right); // "projects/library/seqan/basic/basic_iterator_adapt_std.h"(229) //____________________________________________________________________________ // operator<< template inline TStream & operator<< (TStream & stream, SimpleType const & data); // "projects/library/seqan/basic/basic_alphabet_simple.h"(262) template inline TStream & operator<< (TStream & strm, Proxy & proxy); // "projects/library/seqan/basic/basic_proxy.h"(591) template inline TStream & operator<< (TStream & strm, Proxy const & proxy); // "projects/library/seqan/basic/basic_proxy.h"(598) template std::ostream& operator<<(std::ostream &out, Pair const &p); // "projects/library/seqan/basic/basic_aggregates.h"(148) template std::ostream& operator<<(std::ostream &out, Triple const &t); // "projects/library/seqan/basic/basic_aggregates.h"(267) template std::ostream& operator<<(std::ostream& out, Tuple const &a); // "projects/library/seqan/basic/basic_aggregates.h"(548) //____________________________________________________________________________ // operator<= template inline bool operator<= (SimpleType const & left_, TRight const & right_); // "projects/library/seqan/basic/basic_alphabet_simple.h"(736) template inline bool operator<= (TLeft const & left_, SimpleType const & right_); // "projects/library/seqan/basic/basic_alphabet_simple.h"(747) template inline bool operator<= (SimpleType const & left_, SimpleType const & right_); // "projects/library/seqan/basic/basic_alphabet_simple.h"(758) template inline bool operator<= (SimpleType const & left_, SimpleType const & right_); // "projects/library/seqan/basic/basic_alphabet_simple.h"(770) template inline bool operator<= (Proxy const & left_, SimpleType const & right_); // "projects/library/seqan/basic/basic_alphabet_simple.h"(780) template inline bool operator<= (SimpleType const & left_, Proxy const & right_); // "projects/library/seqan/basic/basic_alphabet_simple.h"(791) template inline bool operator<= (Iter const & left, Iter const & right); // "projects/library/seqan/basic/basic_iterator_position.h"(274) template inline bool operator<= (Proxy const & left_, TRight const & right_); // "projects/library/seqan/basic/basic_proxy.h"(423) template inline bool operator<= (TLeft const & left_, Proxy const & right_); // "projects/library/seqan/basic/basic_proxy.h"(434) template inline bool operator<= (Proxy const & left_, Proxy const & right_); // "projects/library/seqan/basic/basic_proxy.h"(445) template inline bool operator<= (Proxy const & left_, Proxy const & right_); // "projects/library/seqan/basic/basic_proxy.h"(457) template inline bool operator<= (Iter const & left, Iter const & right); // "projects/library/seqan/basic/basic_iterator_adapt_std.h"(255) //____________________________________________________________________________ // operator== template inline bool operator== (SimpleType const & left_, TRight const & right_); // "projects/library/seqan/basic/basic_alphabet_simple.h"(523) template inline bool operator== (TLeft const & left_, SimpleType const & right_); // "projects/library/seqan/basic/basic_alphabet_simple.h"(534) template inline bool operator== (SimpleType const & left_, SimpleType const & right_); // "projects/library/seqan/basic/basic_alphabet_simple.h"(545) template inline bool operator== (SimpleType const & left_, SimpleType const & right_); // "projects/library/seqan/basic/basic_alphabet_simple.h"(557) template inline bool operator== (Proxy const & left_, SimpleType const & right_); // "projects/library/seqan/basic/basic_alphabet_simple.h"(567) template inline bool operator== (SimpleType const & left_, Proxy const & right_); // "projects/library/seqan/basic/basic_alphabet_simple.h"(578) template inline bool operator== (Iter const & left, Iter const & right); // "projects/library/seqan/basic/basic_iterator_position.h"(226) template inline bool operator== (Proxy const & left_, TRight const & right_); // "projects/library/seqan/basic/basic_proxy.h"(281) template inline bool operator== (TLeft const & left_, Proxy const & right_); // "projects/library/seqan/basic/basic_proxy.h"(292) template inline bool operator== (Proxy const & left_, Proxy const & right_); // "projects/library/seqan/basic/basic_proxy.h"(303) template inline bool operator== (Proxy const & left_, Proxy const & right_); // "projects/library/seqan/basic/basic_proxy.h"(315) template inline bool operator== (Iter > const & left, Iter > const & right); // "projects/library/seqan/basic/basic_iterator_adaptor.h"(330) template inline bool operator==(Tuple const &_left, Tuple const &_right); // "projects/library/seqan/basic/basic_aggregates.h"(499) template inline bool operator==(Pair const &_left, Pair const &_right); // "projects/library/seqan/basic/basic_aggregates.h"(656) template inline bool operator==(Pair > const &_left, Pair > const &_right); // "projects/library/seqan/basic/basic_aggregates.h"(665) template inline bool operator==(Triple const &_left, Triple const &_right); // "projects/library/seqan/basic/basic_aggregates.h"(677) template inline bool operator== (Iter const & left, Iter const & right); // "projects/library/seqan/basic/basic_iterator_adapt_std.h"(203) //____________________________________________________________________________ // operator> template inline bool operator> (SimpleType const & left_, TRight const & right_); // "projects/library/seqan/basic/basic_alphabet_simple.h"(808) template inline bool operator> (TLeft const & left_, SimpleType const & right_); // "projects/library/seqan/basic/basic_alphabet_simple.h"(819) template inline bool operator> (SimpleType const & left_, SimpleType const & right_); // "projects/library/seqan/basic/basic_alphabet_simple.h"(830) template inline bool operator> (SimpleType const & left_, SimpleType const & right_); // "projects/library/seqan/basic/basic_alphabet_simple.h"(842) template inline bool operator> (Proxy const & left_, SimpleType const & right_); // "projects/library/seqan/basic/basic_alphabet_simple.h"(852) template inline bool operator> (SimpleType const & left_, Proxy const & right_); // "projects/library/seqan/basic/basic_alphabet_simple.h"(863) template inline bool operator> (Iter const & left, Iter const & right); // "projects/library/seqan/basic/basic_iterator_position.h"(261) template inline bool operator> (Proxy const & left_, TRight const & right_); // "projects/library/seqan/basic/basic_proxy.h"(471) template inline bool operator> (TLeft const & left_, Proxy const & right_); // "projects/library/seqan/basic/basic_proxy.h"(482) template inline bool operator> (Proxy const & left_, Proxy const & right_); // "projects/library/seqan/basic/basic_proxy.h"(493) template inline bool operator> (Proxy const & left_, Proxy const & right_); // "projects/library/seqan/basic/basic_proxy.h"(505) template inline bool operator>(Tuple const &_left, Tuple const &_right); // "projects/library/seqan/basic/basic_aggregates.h"(495) template inline bool operator> (Iter const & left, Iter const & right); // "projects/library/seqan/basic/basic_iterator_adapt_std.h"(242) //____________________________________________________________________________ // operator>= template inline bool operator>= (SimpleType const & left_, TRight const & right_); // "projects/library/seqan/basic/basic_alphabet_simple.h"(879) template inline bool operator>= (TLeft const & left_, SimpleType const & right_); // "projects/library/seqan/basic/basic_alphabet_simple.h"(890) template inline bool operator>= (SimpleType const & left_, SimpleType const & right_); // "projects/library/seqan/basic/basic_alphabet_simple.h"(901) template inline bool operator>= (SimpleType const & left_, SimpleType const & right_); // "projects/library/seqan/basic/basic_alphabet_simple.h"(913) template inline bool operator>= (Proxy const & left_, SimpleType const & right_); // "projects/library/seqan/basic/basic_alphabet_simple.h"(923) template inline bool operator>= (SimpleType const & left_, Proxy const & right_); // "projects/library/seqan/basic/basic_alphabet_simple.h"(934) template inline bool operator>= (Iter const & left, Iter const & right); // "projects/library/seqan/basic/basic_iterator_position.h"(283) template inline bool operator>= (Proxy const & left_, TRight const & right_); // "projects/library/seqan/basic/basic_proxy.h"(519) template inline bool operator>= (TLeft const & left_, Proxy const & right_); // "projects/library/seqan/basic/basic_proxy.h"(530) template inline bool operator>= (Proxy const & left_, Proxy const & right_); // "projects/library/seqan/basic/basic_proxy.h"(541) template inline bool operator>= (Proxy const & left_, Proxy const & right_); // "projects/library/seqan/basic/basic_proxy.h"(553) template inline bool operator>= (Iter const & left, Iter const & right); // "projects/library/seqan/basic/basic_iterator_adapt_std.h"(268) //____________________________________________________________________________ // operator>> template inline TStream & operator>> (TStream & stream, SimpleType & data); // "projects/library/seqan/basic/basic_alphabet_simple.h"(274) template inline TStream & operator>> (TStream & strm, Proxy & proxy); // "projects/library/seqan/basic/basic_proxy.h"(565) template inline TStream & operator>> (TStream & strm, Proxy const& proxy); // "projects/library/seqan/basic/basic_proxy.h"(577) //____________________________________________________________________________ // parentAllocator template inline TParentAllocator & parentAllocator(Allocator > & me); // "projects/library/seqan/basic/basic_allocator_singlepool.h"(136) template inline TParentAllocator & parentAllocator(Allocator > & me); // "projects/library/seqan/basic/basic_allocator_singlepool.h"(256) template inline TParentAllocator & parentAllocator(Allocator > & me); // "projects/library/seqan/basic/basic_allocator_multipool.h"(115) template inline TParentAllocator & parentAllocator(Allocator > & me); // "projects/library/seqan/basic/basic_allocator_simple.h"(103) //template inline TParentAllocator & parentAllocator(Allocator > & me); // "projects/library/seqan/basic/basic_allocator_chunkpool.h"(147) template inline TParentAllocator & parentAllocator(Allocator > & me); // "projects/library/seqan/basic/basic_allocator_chunkpool.h"(279) //____________________________________________________________________________ // position template inline typename Position const>::Type position(Iter const & me, TContainer2 const &); // "projects/library/seqan/basic/basic_iterator_base.h"(211) template inline typename Position::Type position(T * me); // "projects/library/seqan/basic/basic_iterator.h"(354) template inline typename Position::Type position(TIterator const & it, TContainer const & me); // "projects/library/seqan/basic/basic_iterator.h"(363) template inline typename Position const>::Type position(Iter const & me, TContainer2 const & cont); // "projects/library/seqan/basic/basic_iterator_simple.h"(108) template inline typename Position > const>::Type position(Iter > const & me); // "projects/library/seqan/basic/basic_iterator_adaptor.h"(232) template inline typename Position > const>::Type position(Iter > const & me, TContainer2 const &); // "projects/library/seqan/basic/basic_iterator_adaptor.h"(243) //____________________________________________________________________________ // releaseRef template inline void releaseRef(T & ); // "projects/library/seqan/basic/basic_holder.h"(73) template inline void releaseRef(T const & ); // "projects/library/seqan/basic/basic_holder.h"(79) //____________________________________________________________________________ // set template inline void set(TTarget & target, TSource & source); // "projects/library/seqan/basic/basic_transport.h"(160) template inline void set(TTarget const & target, TSource & source); // "projects/library/seqan/basic/basic_transport.h"(168) template inline void set(TTarget & target, TSource const & source); // "projects/library/seqan/basic/basic_transport.h"(176) template inline void set(TTarget const & target, TSource const & source); // "projects/library/seqan/basic/basic_transport.h"(184) //____________________________________________________________________________ // setHost template inline void setHost(T & me, THost & host_); // "projects/library/seqan/basic/basic_host.h"(99) template inline void setHost(T & me, THost const & host_); // "projects/library/seqan/basic/basic_host.h"(107) //____________________________________________________________________________ // setPosition template inline void setPosition(Iter > & me, TPosition pos_); // "projects/library/seqan/basic/basic_iterator_adaptor.h"(256) //____________________________________________________________________________ // setValue template inline void setValue(Holder & me, typename _Parameter::Type value_); // "projects/library/seqan/basic/basic_holder.h"(453) template inline void setValue(Holder & me, TValue2 const & value_); // "projects/library/seqan/basic/basic_holder.h"(467) template inline void setValue(Holder & me, TValue const & value_); // "projects/library/seqan/basic/basic_holder.h"(724) template inline void setValue(Holder & me, TValue & value_); // "projects/library/seqan/basic/basic_holder.h"(999) //____________________________________________________________________________ // shiftLeft template inline void shiftLeft(Tuple &me); // "projects/library/seqan/basic/basic_aggregates.h"(525) template inline void shiftLeft(Tuple &me); // "projects/library/seqan/basic/basic_aggregates.h"(535) //____________________________________________________________________________ // shiftRight template inline void shiftRight(Tuple &me); // "projects/library/seqan/basic/basic_aggregates.h"(530) template inline void shiftRight(Tuple &me); // "projects/library/seqan/basic/basic_aggregates.h"(540) //____________________________________________________________________________ // supremumValue template inline T const & supremumValue(); // "projects/library/seqan/basic/basic_alphabet_interface2.h"(120) //____________________________________________________________________________ // supremumValueImpl template inline T const & supremumValueImpl(T *); // "projects/library/seqan/basic/basic_alphabet_trait_basic.h"(420) inline float const & supremumValueImpl(float *); // "projects/library/seqan/basic/basic_alphabet_trait_basic.h"(655) inline double const & supremumValueImpl(double *); // "projects/library/seqan/basic/basic_alphabet_trait_basic.h"(682) inline long double const & supremumValueImpl(long double *); // "projects/library/seqan/basic/basic_alphabet_trait_basic.h"(709) //____________________________________________________________________________ // value template inline typename Reference >::Type value(Iter & me); // "projects/library/seqan/basic/basic_iterator_position.h"(164) template inline typename Reference >::Type value(Iter const & me); // "projects/library/seqan/basic/basic_iterator_position.h"(171) template inline typename Reference >::Type value(Holder & me); // "projects/library/seqan/basic/basic_holder.h"(479) template inline typename Reference const>::Type value(Holder const & me); // "projects/library/seqan/basic/basic_holder.h"(496) template inline typename Reference >::Type value(Holder & me); // "projects/library/seqan/basic/basic_holder.h"(734) template inline typename Reference const>::Type value(Holder const & me); // "projects/library/seqan/basic/basic_holder.h"(741) template inline typename Reference >::Type value(Holder & me); // "projects/library/seqan/basic/basic_holder.h"(1016) template inline typename Reference const>::Type value(Holder const & me); // "projects/library/seqan/basic/basic_holder.h"(1033) template inline typename Reference::Type value(T & me); // "projects/library/seqan/basic/basic_iterator.h"(171) template inline typename Reference::Type value(T const & me); // "projects/library/seqan/basic/basic_iterator.h"(178) template inline T & value(T * me); // "projects/library/seqan/basic/basic_iterator.h"(187) template inline typename Reference > >::Type value(Iter > & me); // "projects/library/seqan/basic/basic_iterator_adaptor.h"(268) template inline typename Reference > const>::Type value(Iter > const & me); // "projects/library/seqan/basic/basic_iterator_adaptor.h"(275) template inline typename Reference >::Type value(Iter & me); // "projects/library/seqan/basic/basic_iterator_adapt_std.h"(146) template inline typename Reference const>::Type value(Iter const & me); // "projects/library/seqan/basic/basic_iterator_adapt_std.h"(152) //____________________________________________________________________________ // valueConstruct template inline void valueConstruct(TIterator it); // "projects/library/seqan/basic/basic_alphabet_interface.h"(145) template inline void valueConstruct(TIterator it, TParam const & param_); // "projects/library/seqan/basic/basic_alphabet_interface.h"(165) template inline void valueConstruct(TIterator it, TParam const & param_, Move tag); // "projects/library/seqan/basic/basic_alphabet_interface.h"(186) //____________________________________________________________________________ // valueConstructMove template inline void valueConstructMove(TIterator it, TValue const & value); // "projects/library/seqan/basic/basic_alphabet_interface.h"(248) //____________________________________________________________________________ // valueDestruct template inline void valueDestruct(TIterator it); // "projects/library/seqan/basic/basic_alphabet_interface.h"(216) } //namespace SEQAN_NAMESPACE_MAIN //____________________________________________________________________________ // _compareBinaryFiles inline bool _compareBinaryFiles(char * file1, char * file2); // "projects/library/seqan/basic/basic_debug.h"(119) //____________________________________________________________________________ // _compareTextFiles inline bool _compareTextFiles(char * file1, char * file2); // "projects/library/seqan/basic/basic_debug.h"(182) //____________________________________________________________________________ // _compareTextFiles_readChar inline void _compareTextFiles_readChar(FILE * fl, char & c, bool & is_lb, bool & is_eof); // "projects/library/seqan/basic/basic_debug.h"(151) #endif ugene-1.9.8/src/plugins_3rdparty/bowtie/src/bowtie/SeqAn-1.1/seqan/basic/basic_volatile_ptr.h0000644000175000017500000001006211651544326030503 0ustar ilyailya /*========================================================================== SeqAn - The Library for Sequence Analysis http://www.seqan.de ============================================================================ Copyright (C) 2007 This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. ============================================================================ $Id: basic_volatile_ptr.h,v 1.1 2008/08/25 16:20:01 langmead Exp $ ==========================================================================*/ #ifndef SEQAN_HEADER_BASIC_VOLATILE_PTR_H #define SEQAN_HEADER_BASIC_VOLATILE_PTR_H ////////////////////////////////////////////////////////////////////////////// namespace SEQAN_NAMESPACE_MAIN { ////////////////////////////////////////////////////////////////////////////// // volatile pointer // allows you to handle volatile data (used by ext. string during swapping) // // imagine volatile pointers as nodes in an undirected graph // when you assign one to another then they are connected // all pointers in a connection component points to the same value // by calling nukeCopies you can destroy the component and set all pointers to NULL template < typename Type > struct VolatilePtr { typedef VolatilePtr _Self; typedef VolatilePtr* _SelfPtr; typedef VolatilePtr& _SelfRef; typedef Type& reference; typedef const Type& const_reference; typedef Type* pointer; pointer ptr; _SelfPtr next; // prev == NULL means this is the master node _SelfPtr prev; // prev == NULL means this is the master node VolatilePtr() { // volatile pinters behave like normal pointers prev = this; // and are not initialized (ptr) per default next = this; }; VolatilePtr(const pointer _p) { ptr = _p; prev = this; next = this; } VolatilePtr(const _Self& _vp) { ptr = _vp.ptr; prev = this; next = this; } VolatilePtr(_SelfRef _vp) { ptr = _vp.ptr; prev = this; next = this; if (ptr) hangOn(_vp); } ~VolatilePtr() { hangOff(); } template inline reference operator[] (size_type offset) { return ptr[offset]; } template inline const_reference operator[] (size_type offset) const { return ptr[offset]; } inline _Self& operator=(_Self const &_Right) { hangOff(); ptr = _Right.ptr; if (ptr) hangOn(const_cast<_Self&>(_Right)); return *this; } inline _Self& operator=(pointer const _Right) { hangOff(); ptr = _Right; return *this; } inline bool isLonely() { return next == this; } inline void nukeCopies() { _SelfPtr p = next; while (p != this) { _SelfPtr tmp = p->next; p->ptr = NULL; p->prev = p; p->next = p; p = tmp; } prev = this; next = this; } inline bool operator== (const _Self &I) const { return ptr == I.ptr; } inline bool operator!= (const _Self &I) const { return ptr != I.ptr; } inline operator pointer () const { return ptr; } private: inline void hangOn(_SelfRef _prev) { // hang on between _prev and _prev.next prev = &_prev; next = _prev.next; _prev.next = this; next->prev = this; } inline void hangOff() { next->prev = prev; prev->next = next; next = this; prev = this; } }; template inline void nukeCopies(TValue* &) {} template inline void nukeCopies(VolatilePtr &ptr) { ptr.nukeCopies(); } } #endif ugene-1.9.8/src/plugins_3rdparty/bowtie/src/bowtie/SeqAn-1.1/seqan/basic/basic_profile.h0000644000175000017500000003671511651544326027454 0ustar ilyailya /*========================================================================== SeqAn - The Library for Sequence Analysis http://www.seqan.de ============================================================================ Copyright (C) 2007 This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. ============================================================================ $Id: basic_profile.h,v 1.1 2008/08/25 16:20:02 langmead Exp $ ==========================================================================*/ //SEQAN_NO_GENERATED_FORWARDS: no forwards are generated for this file #ifndef SEQAN_HEADER_BASIC_PROFILE_H #define SEQAN_HEADER_BASIC_PROFILE_H // todo: substitute defines with inlines #ifndef SEQAN_PROFILE #define SEQAN_PROSET(i,v) #define SEQAN_PROADD(i,v) #define SEQAN_PROSUB(i,v) #define SEQAN_PROVAL(i) 0 #define SEQAN_PROEXTRAS(i) #define SEQAN_PROMARK(m) #define SEQAN_PROENDMARK(m) #define SEQAN_PRORESET #define SEQAN_PROGETTIME 0 #define SEQAN_PROTIMESTART(a) #define SEQAN_PROTIMEDIFF(a) 0 // replace malloc and free in external tools // with SEQAN_PROMALLOC and SEQAN_PROFREE to profile // their memory usage #define SEQAN_PROMALLOC(s) malloc(s) #define SEQAN_PROFREE(p) free(p) #else #define SEQAN_PROSET(i,v) _proSet(i,v) #define SEQAN_PROADD(i,v) _proAdd(i,v) #define SEQAN_PROSUB(i,v) _proSub(i,v) #define SEQAN_PROVAL(i) (_proData<>::_proValue[i]) #define SEQAN_PROEXTRAS(i) {_proData<>::_proExtraCount = i;} #define SEQAN_PROMARK(m) _proMark(m) #define SEQAN_PROENDMARK(m) _proEndMark(m) #define SEQAN_PRORESET _proReset() #define SEQAN_PROGETTIME sysTime() #define SEQAN_PROTIMESTART(a) _proFloat a = sysTime() #define SEQAN_PROTIMEDIFF(a) (sysTime() - a) #define SEQAN_PROMALLOC(s) _proMalloc(s) #define SEQAN_PROFREE(p) _proFree(p) #endif #ifdef PLATFORM_WINDOWS typedef __int64 _proInt; #else typedef int64_t _proInt; #endif typedef double _proFloat; typedef _proFloat _proTValue; enum _proConsts { SEQAN_PROPAGESIZE = 4096, // B in byte SEQAN_PROFLOAT = 0, SEQAN_PROINT = 1, SEQAN_PROTIME = 2, SEQAN_PROTYPEMASK = 3, SEQAN_PROSTATE = 4 }; enum _proValueIndex { SEQAN_PROSYSTIME = 0, SEQAN_PROCPUTIME = 1, SEQAN_PROMEMORY = 2, // current memory usage (state value) SEQAN_PROIO = 3, // IOs done (measured in Blocks of size B) SEQAN_PROIORANDOM = 4, // IOs calls done (read/write calls done) SEQAN_PROIOVOLUME = 5, // current disk usage (state value) SEQAN_PRODEPTH = 6, // algorithmic rec. depth or loop count SEQAN_PROOPENFILES = 7, // currently opened files SEQAN_PROIWAIT = 8, // waiting time (initiating) SEQAN_PROCWAIT = 9, // waiting time (completing) SEQAN_PROEXTRA1 = 10, SEQAN_PROEXTRA2 = 11, SEQAN_PROEXTRA3 = 12, SEQAN_PROINDEXCOUNT = 13, SEQAN_PROEXTRACOUNT = 3 }; const char _proValueType[] = { SEQAN_PROTIME, SEQAN_PROTIME, SEQAN_PROINT + SEQAN_PROSTATE, SEQAN_PROINT, SEQAN_PROINT, SEQAN_PROINT + SEQAN_PROSTATE, SEQAN_PROINT + SEQAN_PROSTATE, SEQAN_PROINT + SEQAN_PROSTATE, SEQAN_PROFLOAT, SEQAN_PROFLOAT, SEQAN_PROFLOAT + SEQAN_PROSTATE, SEQAN_PROFLOAT + SEQAN_PROSTATE, SEQAN_PROFLOAT + SEQAN_PROSTATE }; typedef _proTValue _proTStates[SEQAN_PROINDEXCOUNT]; typedef _proFloat _proTTimes[SEQAN_PROINDEXCOUNT]; struct _proFile; template struct _proData { static _proTStates _proValue; static _proTTimes _proLastUpdate; static int _proExtraCount; static clock_t _proCpuTimeLast; // clock_t wraps around every 72mins static _proInt _proCpuTimeOffset; // we have to work around this static _proFile* _proPFile; static _proFile* _proPFileStream; }; template _proTStates _proData::_proValue = {}; template _proTStates _proData::_proLastUpdate = {}; template int _proData::_proExtraCount = 0; template clock_t _proData::_proCpuTimeLast = 0; template _proInt _proData::_proCpuTimeOffset = 0; template _proFile* _proData::_proPFile = NULL; template _proFile* _proData::_proPFileStream = NULL; inline _proFile* & _proPFile() { return _proData<>::_proPFile; } inline _proFile* & _proPFileStream() { return _proData<>::_proPFileStream; } // HINT: The unit of all time functions is second. inline _proFloat cpuTime() { clock_t now = clock(); if (_proData<>::_proCpuTimeLast > now) { // test for time wrap _proData<>::_proCpuTimeOffset += (~0u); // got one _proData<>::_proCpuTimeOffset ++; // printf("\n!!WRAP!! old:%d, now:%d ofs:%d\n",_proData<>::_proCpuTimeLast,now,_proData<>::_proCpuTimeOffset); } _proData<>::_proCpuTimeLast = now; return (_proData<>::_proCpuTimeOffset + now) / (_proFloat)CLOCKS_PER_SEC; } #ifdef PLATFORM_WINDOWS // inline _proFloat sysTime() { return GetTickCount() * 1e-3; } inline _proFloat sysTime() { return ( (_proFloat) clock() ) / CLOCKS_PER_SEC; } #else #include #if _POSIX_TIMERS > 0 #ifndef SEQAN_USE_CLOCKGETTIME #define SEQAN_USE_CLOCKGETTIME #endif #endif #ifndef SEQAN_USE_CLOCKGETTIME /* some systems e.g. darwin have no clock_gettime */ #include inline _proFloat sysTime() { struct timeval tp; gettimeofday(&tp, NULL); return tp.tv_sec + tp.tv_usec * 1e-6; } #else inline _proFloat sysTime() { /*struct timespec tp; clock_gettime(CLOCK_MONOTONIC, &tp); return tp.tv_sec + tp.tv_nsec * 1e-9;*/ return 0; // BTL: to compile under cygwin } #endif #endif struct _proFile { FILE *out; bool running; _proFloat dumpStep; // 0 .. manual dump mode, >0 .. live stream _proFloat dumpNext; _proTStates all, last; ::std::string mark; unsigned lines; _proFile() { running = false; } _proFile(char const *fname, _proFloat _dumpStep = 300.0) { // five minutes default dump interval running = false; start(fname, _dumpStep); } ~_proFile() { if (running) stop(); } inline void start(char const *fname, _proFloat _dumpStep = 300.0, bool append = false) { if (append) out = fopen(fname, "a"); else { out = fopen(fname, "w"); dumpHeader(); } if (!out) printf("WARNING: proFile could not be opened.\n"); setTime(_proData<>::_proValue); syncAll(all); syncAll(last); running = true; lines = 0; dumpStep = _dumpStep; dumpNext = sysTime(); dump(last); } inline void stop() { dump(last); maximize(all, last); if (dumpStep == 0) { mark = "Zusammenfassung"; dump(all); } fclose(out); running = false; } inline void syncTime(_proTStates &dst) { memcpy(dst, _proData<>::_proValue, 2 * sizeof(_proTValue)); } inline void sync(_proTStates &dst) { memcpy(&(dst[2]), &(_proData<>::_proValue[2]), sizeof(_proTStates) - 2 * sizeof(_proTValue)); } inline void syncAll(_proTStates &dst) { memcpy(dst, _proData<>::_proValue, sizeof(_proTStates)); } inline static void setTime(_proTStates &dst) { dst[0] = sysTime(); dst[1] = cpuTime(); } inline void maximize(_proTStates &dst, _proTStates const &src) { for(int i = 0; i < SEQAN_PROINDEXCOUNT; ++i) if (((_proValueType[i] & SEQAN_PROSTATE) != 0)) if (dst[i] < src[i]) dst[i] = src[i]; } inline void dumpTab() { if (!bol) fprintf(out, " \t"); bol = false; } inline void dumpEndl() { fprintf(out, "\n"); } inline void dumpHeader() { fprintf(out, "\"Echtzeit\"\t\"CPU-Zeit\"\t\"Speicher\"\t\"I/O-Zugriffe\"\t\"wahlfreie I/Os\"\t\"I/O-Volumen\"\t\"Rekursionstiefe\"\t\"Offene Dateien\"\t\"Idle-Zeit vor I/O\"\t\"Idle-Zeit nach I/O\"\n"); } inline void dumpTime(_proFloat seconds) { if (seconds < 0) { fputc('-', out); seconds = -seconds; } int secs = (int)seconds; int mins = secs/60; secs -= 60*mins; int hours = mins/60; mins -= 60*hours; fprintf(out, "%d:%02d:%02d", hours, mins, secs); } inline void dumpTimeEx(_proFloat seconds) { int milli = (int)(seconds * 1000.0); int secs = (int)seconds; int mins = secs/60; secs -= 60*mins; int hours = mins/60; mins -= 60*hours; fprintf(out, "%d:%02d:%02d.%03d", hours, mins, secs, milli); } inline void dumpValue(_proTStates &stat, int valNum) { _proFloat f = stat[valNum]; if ((_proValueType[valNum] & SEQAN_PROSTATE) == 0) f = _proData<>::_proValue[valNum] - f; switch (_proValueType[valNum] & SEQAN_PROTYPEMASK) { case SEQAN_PROINT: // state value -> print last seen maximum fprintf(out, "%.0f", f); break; case SEQAN_PROFLOAT: fprintf(out, "%f", f); break; case SEQAN_PROTIME: dumpTimeEx(f); } } inline void dumpSysValues(_proTStates &stat) { for(int i = 0; i < SEQAN_PROINDEXCOUNT - SEQAN_PROEXTRACOUNT; ++i) { dumpTab(); dumpValue(stat, i); } } inline void dumpExtraValues(_proTStates &stat) { for(int i = 0; i < _proData<>::_proExtraCount; ++i) { dumpTab(); dumpValue(stat, SEQAN_PROINDEXCOUNT - SEQAN_PROEXTRACOUNT + i); } } inline void dumpMark() { if (!mark.empty()) { dumpTab(); fprintf(out, "\"%s\"", mark.c_str()); mark.erase(); } } inline void dump(_proTStates &stat) { setTime(_proData<>::_proValue); dumpNext += dumpStep; bol = true; bool _flush = ((dumpStep == 0.0)) || ((lines & 16) == 0); dumpSysValues(stat); dumpExtraValues(stat); dumpMark(); dumpEndl(); if (_flush) fflush(out); ++lines; } inline void signalDumpTest(_proFloat now) { if (dumpStep > 0 && now > dumpNext && running) { dump(last); maximize(all, last); sync(last); } } inline void signalNewMax(int valNum) { if (running) if (last[valNum] < _proData<>::_proValue[valNum]) last[valNum] = _proData<>::_proValue[valNum]; } inline void setMark(const char *text) { if (running) { mark = text; if (dumpStep == 0.0) { dump(last); // manual dump; maximize(all, last); sync(last); } } } inline void reset() { syncTime(last); } inline void setEndMark(const char *text) { if (running) { setMark(text); reset(); } } private: bool bol; // begin of line }; /* inline void _proSignalDumpTest(_proFloat now); inline void _proSignalNewMax(int valNum); inline void _proMark(const char *text); inline void _proEndMark(const char *text); inline void _proReset(); inline void _proSet(int valNum, _proFloat value); inline void _proAdd(int valNum, _proFloat value); inline void _proSub(int valNum, _proFloat value); // simple interface for external programs inline void *_proMalloc(size_t size); inline void _proFree(void *_ptr); */ inline void _proSignalDumpTest(_proFloat now) { if (_proData<>::_proPFileStream) _proData<>::_proPFileStream->signalDumpTest(now); } inline void _proSignalNewMax(int valNum) { if (((_proValueType[valNum] & SEQAN_PROSTATE) != 0)) { if (_proData<>::_proPFileStream) _proData<>::_proPFileStream->signalNewMax(valNum); if (_proData<>::_proPFile) _proData<>::_proPFile->signalNewMax(valNum); } } inline void _proMark(const char *text) { if (_proData<>::_proPFileStream) _proData<>::_proPFileStream->setMark(text); if (_proData<>::_proPFile) _proData<>::_proPFile->setMark(text); } inline void _proEndMark(const char *text) { if (_proData<>::_proPFileStream) { _proData<>::_proPFileStream->setEndMark(text); } if (_proData<>::_proPFile) { _proData<>::_proPFile->setEndMark(text); } } inline void _proReset() { if (_proData<>::_proPFileStream) { _proData<>::_proPFileStream->reset(); } if (_proData<>::_proPFile) { _proData<>::_proPFile->reset(); } } inline void _proSet(_proValueIndex valNum, _proFloat value) { _proFloat now = sysTime(); _proData<>::_proLastUpdate[valNum] = now; if (_proData<>::_proValue[valNum] < value) { _proData<>::_proValue[valNum] = value; _proSignalNewMax(valNum); } else _proData<>::_proValue[valNum] = value; _proSignalDumpTest(now); } inline void _proAdd(_proValueIndex valNum, _proFloat value) { _proFloat now = sysTime(); _proData<>::_proValue[valNum] += value; _proData<>::_proLastUpdate[valNum] = now; if (valNum == SEQAN_PROIO) _proAdd(SEQAN_PROIORANDOM, 1); _proSignalNewMax(valNum); _proSignalDumpTest(now); } inline void _proSub(_proValueIndex valNum, _proFloat value) { _proFloat now = sysTime(); _proData<>::_proValue[valNum] -= value; _proData<>::_proLastUpdate[valNum] = now; _proSignalDumpTest(now); } // simple interface for external programs inline void *_proMalloc(size_t size) { size_t *ptr = reinterpret_cast(malloc(size + sizeof(size_t))); if (ptr) { _proAdd(SEQAN_PROMEMORY, *ptr = size); // printf("_proMalloc %x size %d\n", ptr, size); ++ptr; } return ptr; } inline void _proFree(void *_ptr) { size_t *ptr = reinterpret_cast(_ptr); if (ptr) { --ptr; // printf("_proFree %x size %d\n", _ptr, *ptr); _proSub(SEQAN_PROMEMORY, *ptr); } free(ptr); } #endif ugene-1.9.8/src/plugins_3rdparty/bowtie/src/bowtie/SeqAn-1.1/seqan/basic/basic_debug.h0000644000175000017500000002465311651544326027100 0ustar ilyailya /*========================================================================== SeqAn - The Library for Sequence Analysis http://www.seqan.de ============================================================================ Copyright (C) 2007 This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. ============================================================================ $Id: basic_debug.h,v 1.1 2008/08/25 16:20:01 langmead Exp $ ==========================================================================*/ #ifndef SEQAN_HEADER_BASIC_DEBUG_H #define SEQAN_HEADER_BASIC_DEBUG_H #ifndef SEQAN_DEBUG_OR_TEST_ #ifdef SEQAN_DEBUG #define SEQAN_DEBUG_OR_TEST_ #else //#ifdef SEQAN_DEBUG #ifdef SEQAN_TEST #define SEQAN_DEBUG_OR_TEST_ #endif //#ifdef SEQAN_TEST #endif //#ifdef SEQAN_DEBUG #endif //#ifndef SEQAN_DEBUG_OR_TEST_ #ifdef SEQAN_DEBUG_OR_TEST_ #include #endif //#ifdef SEQAN_DEBUG_OR_TEST_ #ifdef SEQAN_DEBUG //throw a fatal debug report if _cond is false #define SEQAN_ASSERT(_cond) { if (!(_cond)) ::SEQAN_NAMESPACE_MAIN::debug::Error< ::SEQAN_NAMESPACE_MAIN::debug::Check >(__FILE__, __LINE__, #_cond " is FALSE"); } #define SEQAN_ASSERT1(_cond) SEQAN_ASSERT(_cond) #define SEQAN_ASSERT2(_cond, _comment) { if (!(_cond)) ::SEQAN_NAMESPACE_MAIN::debug::Error< ::SEQAN_NAMESPACE_MAIN::debug::Check >(__FILE__, __LINE__, _comment); } //throw a debug report if _cond is false #define SEQAN_CHECK(_cond) { if (!(_cond)) ::SEQAN_NAMESPACE_MAIN::debug::Message< ::SEQAN_NAMESPACE_MAIN::debug::Check >(__FILE__, __LINE__, #_cond " is FALSE"); } #define SEQAN_CHECK1(_cond) SEQAN_CHECK(_cond) #define SEQAN_CHECK2(_cond, _comment) { if (!(_cond)) ::SEQAN_NAMESPACE_MAIN::debug::Message< ::SEQAN_NAMESPACE_MAIN::debug::Check >(__FILE__, __LINE__, _comment); } #define SEQAN_DO(_cond) { if (!(_cond)) ::SEQAN_NAMESPACE_MAIN::debug::Message< ::SEQAN_NAMESPACE_MAIN::debug::Check >(__FILE__, __LINE__, #_cond " is FALSE"); } #define SEQAN_DO1(_cond) SEQAN_DO(_cond) #define SEQAN_DO2(_cond, _comment) { if (!(_cond)) ::SEQAN_NAMESPACE_MAIN::debug::Error< ::SEQAN_NAMESPACE_MAIN::debug::Check >(__FILE__, __LINE__, _comment); } //report a message #define SEQAN_ABORT(_comment) { ::SEQAN_NAMESPACE_MAIN::debug::Error< ::SEQAN_NAMESPACE_MAIN::debug::Report >(__FILE__, __LINE__, _comment); } #define SEQAN_REPORT(_comment) { ::SEQAN_NAMESPACE_MAIN::debug::Message< ::SEQAN_NAMESPACE_MAIN::debug::Report >(__FILE__, __LINE__, _comment); } #else //#ifdef SEQAN_DEBUG //disable debug reports in release built #define SEQAN_ASSERT(_cond) {} #define SEQAN_ASSERT1(_cond) {} #define SEQAN_ASSERT2(_cond, _comment) {} #define SEQAN_CHECK(_cond) {} #define SEQAN_CHECK1(_cond) {} #define SEQAN_CHECK2(_cond, _comment) {} #define SEQAN_DO(_cond) { _cond; } #define SEQAN_DO1(_cond) SEQAN_DO(_cond) #define SEQAN_DO2(_cond, _comment) { _cond; } #define SEQAN_ABORT(_comment) {} #define SEQAN_REPORT(_comment) {} #endif //#ifdef SEQAN_DEBUG #ifdef SEQAN_TEST //test a condition and report test result #define SEQAN_TASSERT(_cond) \ { if (!(_cond)) ::SEQAN_NAMESPACE_MAIN::debug::Error< ::SEQAN_NAMESPACE_MAIN::debug::Check >(__FILE__, __LINE__, "(" #_cond ") is FALSE"); } #define SEQAN_TASSERT1(_cond) SEQAN_TASSERT(_cond) #define SEQAN_TASSERT2(_cond, _comment) \ { if (!(_cond)) ::SEQAN_NAMESPACE_MAIN::debug::Error< ::SEQAN_NAMESPACE_MAIN::debug::Check >(__FILE__, __LINE__, _comment); } #define SEQAN_TCHECK(_cond) \ { if (_cond) ::SEQAN_NAMESPACE_MAIN::debug::Result< ::SEQAN_NAMESPACE_MAIN::debug::Check >(__FILE__, __LINE__, "(" #_cond ") is TRUE"); \ else ::SEQAN_NAMESPACE_MAIN::debug::Result< ::SEQAN_NAMESPACE_MAIN::debug::Check >(__FILE__, __LINE__, "(" #_cond ") is FALSE"); } #define SEQAN_TCHECK1(_cond) SEQAN_TCHECK(_cond) #define SEQAN_TCHECK2(_cond, _comment) \ { if (_cond) ::SEQAN_NAMESPACE_MAIN::debug::Result< ::SEQAN_NAMESPACE_MAIN::debug::Check >(__FILE__, __LINE__, _comment); } //report a test result #define SEQAN_TABORT(_comment) { ::SEQAN_NAMESPACE_MAIN::debug::Error< ::SEQAN_NAMESPACE_MAIN::debug::Report >(__FILE__, __LINE__, _comment); } #define SEQAN_TREPORT(_comment) { ::SEQAN_NAMESPACE_MAIN::debug::Result< ::SEQAN_NAMESPACE_MAIN::debug::Report >(__FILE__, __LINE__, _comment); } #else //#ifdef SEQAN_TEST #define SEQAN_TASSERT(_cond) {} #define SEQAN_TASSERT1(_cond) {} #define SEQAN_TASSERT2(_cond, _comment) {} #define SEQAN_TCHECK(_cond) {} #define SEQAN_TABORT(_comment) {} #define SEQAN_TREPORT(_comment) {} #endif //#ifdef SEQAN_TEST //____________________________________________________________________________ #ifdef SEQAN_DEBUG_OR_TEST_ //Test Helper Functions // compare two files, do not translate linebreaks inline bool _compareBinaryFiles(char * file1, char * file2) { bool ret = false; FILE * fl1 = fopen(file1, "rb"); if (!fl1) return ret; FILE * fl2 = fopen(file2, "rb"); if (!fl2) { fclose(fl1); return ret; } while (!feof(fl1) && !feof(fl2)) { if (fgetc(fl1) != fgetc(fl2)) goto End; } ret = feof(fl1) && feof(fl2); End: fclose(fl2); fclose(fl1); return ret; } //____________________________________________________________________________ //one line break is either \r, \n, or \r\n. inline void _compareTextFiles_readChar(FILE * fl, char & c, bool & is_lb, bool & is_eof) { is_lb = false; is_eof = false; c = fgetc(fl); if (c == '\r') { is_lb = true; char c_help = fgetc(fl); if (feof(fl)) is_eof = true; else { if (c_help == '\n') { c = fgetc(fl); if (feof(fl)) is_eof = true; } else c = c_help; } } if (c == '\n') { is_lb = true; c = fgetc(fl); if (feof(fl)) is_eof = true; } } // compare two files, translate linebreaks inline bool _compareTextFiles(char * file1, char * file2) { FILE * fl1 = fopen(file1, "rb"); if (!fl1) return false; FILE * fl2 = fopen(file2, "rb"); if (!fl2) { fclose(fl1); return false; } bool ret = false; bool is_lb1, is_lb2, is_eof1, is_eof2; char c1, c2; while (!feof(fl1) && !feof(fl2)) { _compareTextFiles_readChar(fl1, c1, is_lb1, is_eof1); _compareTextFiles_readChar(fl2, c2, is_lb2, is_eof2); if (is_lb1 ^ is_lb2) { goto End; } if (is_eof1 ^ is_eof2) { goto End; } if (c1 != c2) { goto End; } } ret = feof(fl1) && feof(fl2); End: fclose(fl2); fclose(fl1); return ret; } //____________________________________________________________________________ namespace SEQAN_NAMESPACE_MAIN { namespace debug { //action of SEQAN_ASSERT, SEQAN_TCHECK and SEQAN_CHECK //use as template argument for Error<> and Message<> and Result<> class Check {}; //action of SEQAN_ABORT, SEQAN_TREPORT and SEQAN_REPORT //use as template argument for Error<> and Message<> and Result<> class Report {}; //report fatal error //template argument TAction is the action (Check or Report) //use explicit instatiation for overwriting the default behavior template void Error(const char * file, int line, const char * comment="-") { std::fprintf(stderr, "%s(%i) : SEQAN: %s\nSEQAN: execution aborted\n", file, line, comment); exit(1); } //report debug message //template argument TAction is the action (Check or Report) //use explicit instatiation for overwriting the default behavior template void Message(const char * file, int line, const char * comment="-") { std::fprintf(stderr, "%s(%i) : SEQAN: %s\n", file, line, comment); } //report test result //template argument TAction is the action (Check or Report) //use explicit instatiation for overwriting the default behavior template void Result(const char * file, int line, const char * comment="-") { std::fprintf(stdout, "%s(%i) : %s\n", file, line, comment); } } //namespace debug } //namespace SEQAN_NAMESPACE_MAIN #endif //#ifdef SEQAN_DEBUG_OR_TEST_ //____________________________________________________________________________ //Checkpoint Testing //note: this framework relies on the filenames in the project to be unique #ifdef SEQAN_TEST #include #include #include namespace SEQAN_NAMESPACE_MAIN { namespace debug { struct Checkpoint { char const* file; unsigned int line; }; struct CheckpointLess : public ::std::binary_function { inline bool operator() (Checkpoint const &a, Checkpoint const &b) const { int c = strcmp(a.file, b.file); return c < 0 || (c == 0 && a.line < b.line); } }; template struct CheckpointStore { static ::std::set data; }; template ::std::set CheckpointStore::data; inline bool checkpoint(unsigned int line, char const* file) { char const* file_name = strrchr(file, '/'); char const* file_name_2 = strrchr(file, '\\'); if (file_name_2 > file_name) file_name = file_name_2; if (!file_name) file_name = file; else ++file_name; Checkpoint cp = {file_name, line}; CheckpointStore<>::data.insert(cp); return true; } #define SEQAN_CHECKPOINT \ ::SEQAN_NAMESPACE_MAIN::debug::checkpoint(__LINE__, __FILE__); inline void testCheckpoint(char const* file, unsigned int line) { Checkpoint cp = {file, line}; if (CheckpointStore<>::data.find(cp) == CheckpointStore<>::data.end()) Message< Report >(file, line, "Checkpoint lost"); } inline void verifyCheckpoints(char const* file) { char const* file_name = strrchr(file, '/'); char const* file_name_2 = strrchr(file, '\\'); if (file_name_2 > file_name) file_name = file_name_2; if (!file_name) file_name = file; else ++file_name; FILE * fl = ::std::fopen(file, "r"); if (!fl) { Error< Report >(file, 0, "verifyCheckpoints could not find this file."); } unsigned int line_number = 1; char buf[1<<16]; while (::std::fgets(buf, sizeof(buf), fl)) { if (::std::strstr(buf, "SEQAN_CHECKPOINT")) { testCheckpoint(file_name, line_number); } ++line_number; } ::std::fclose(fl); } } //namespace debug } //namespace SEQAN_NAMESPACE_MAIN #else //#ifdef SEQAN_TEST #define SEQAN_CHECKPOINT #endif //#ifdef SEQAN_TEST //____________________________________________________________________________ #endif //#ifndef SEQAN_HEADER_... ././@LongLink0000000000000000000000000000014600000000000011566 Lustar rootrootugene-1.9.8/src/plugins_3rdparty/bowtie/src/bowtie/SeqAn-1.1/seqan/basic/basic_alphabet_trait_basic.hugene-1.9.8/src/plugins_3rdparty/bowtie/src/bowtie/SeqAn-1.1/seqan/basic/basic_alphabet_trait_basic.0000644000175000017500000004730511651544326031765 0ustar ilyailya /*========================================================================== SeqAn - The Library for Sequence Analysis http://www.seqan.de ============================================================================ Copyright (C) 2007 This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. ============================================================================ $Id: basic_alphabet_trait_basic.h,v 1.2 2009/02/19 01:51:23 langmead Exp $ ==========================================================================*/ #ifndef SEQAN_HEADER_BASIC_ALPHABET_TRAIT_BASIC_H #define SEQAN_HEADER_BASIC_ALPHABET_TRAIT_BASIC_H namespace SEQAN_NAMESPACE_MAIN { ////////////////////////////////////////////////////////////////////////////// //arrayConstruct ////////////////////////////////////////////////////////////////////////////// template inline void _arrayConstruct_Pointer(TIterator, TIterator, True) { SEQAN_CHECKPOINT //nothing to do } template inline void _arrayConstruct_Pointer(TIterator begin_, TIterator end_, False) { SEQAN_CHECKPOINT _arrayConstruct_Default(begin_, end_); } template inline void arrayConstruct(TValue * begin_, TValue * end_) { SEQAN_CHECKPOINT _arrayConstruct_Pointer(begin_, end_, typename IsSimple::Type() ); } //____________________________________________________________________________ template inline void _arrayConstruct_Pointer(TIterator begin_, TIterator end_, TParam const & param_, True) { SEQAN_CHECKPOINT arrayFill(begin_, end_, param_); } template inline void _arrayConstruct_Pointer(TIterator begin_, TIterator end_, TParam const & param_, False) { SEQAN_CHECKPOINT _arrayConstruct_Default(begin_, end_, param_); } template inline void arrayConstruct(TValue * begin_, TValue * end_, TParam const & param_) { SEQAN_CHECKPOINT _arrayConstruct_Pointer(begin_, end_, param_, typename IsSimple::Type() ); } ////////////////////////////////////////////////////////////////////////////// //arrayConstructCopy ////////////////////////////////////////////////////////////////////////////// template inline void _arrayConstructCopy_Pointer(TValue * source_begin, TValue * source_end, TValue * target_begin, True) { SEQAN_CHECKPOINT arrayCopyForward(source_begin, source_end, target_begin); } template inline void _arrayConstructCopy_Pointer(TValue * source_begin, TValue * source_end, TValue * target_begin, False) { SEQAN_CHECKPOINT _arrayConstructCopy_Default(source_begin, source_end, target_begin); } template inline void arrayConstructCopy(TValue * source_begin, TValue * source_end, TValue * target_begin) { SEQAN_CHECKPOINT _arrayConstructCopy_Pointer(source_begin, source_end, target_begin, typename IsSimple::Type() ); } ////////////////////////////////////////////////////////////////////////////// //arrayConstructMove ////////////////////////////////////////////////////////////////////////////// template inline void _arrayConstructMove_Pointer(TValue * source_begin, TValue * source_end, TValue * target_begin, True) { SEQAN_CHECKPOINT arrayMoveForward(source_begin, source_end, target_begin); } template inline void _arrayConstructMove_Pointer(TValue * source_begin, TValue * source_end, TValue * target_begin, False) { SEQAN_CHECKPOINT _arrayConstructMove_Default(source_begin, source_end, target_begin); } template inline void arrayConstructMove(TValue * source_begin, TValue * source_end, TValue * target_begin) { SEQAN_CHECKPOINT _arrayConstructMove_Pointer(source_begin, source_end, target_begin, typename IsSimple::Type() ); } ////////////////////////////////////////////////////////////////////////////// //arrayDestruct ////////////////////////////////////////////////////////////////////////////// template inline void _arrayDestruct_Pointer(TValue * /*begin_*/, TValue * /*end_*/, True) { SEQAN_CHECKPOINT //do nothing } template inline void _arrayDestruct_Pointer(TValue * begin_, TValue * end_, False) { SEQAN_CHECKPOINT _arrayDestruct_Default(begin_, end_); } template inline void arrayDestruct(TValue * begin_, TValue * end_) { SEQAN_CHECKPOINT _arrayDestruct_Pointer(begin_, end_, typename IsSimple::Type() ); } ////////////////////////////////////////////////////////////////////////////// //arrayFill ////////////////////////////////////////////////////////////////////////////// //no specializiation for pointer to simple ////////////////////////////////////////////////////////////////////////////// //arrayCopyForward ////////////////////////////////////////////////////////////////////////////// template inline void _arrayCopyForward_Pointer(TValue * source_begin, TValue * source_end, TValue * target_begin, True) { SEQAN_CHECKPOINT memmove(target_begin, source_begin, (source_end - source_begin) * sizeof(TValue)); } template inline void _arrayCopyForward_Pointer(TValue * source_begin, TValue * source_end, TValue * target_begin, False) { SEQAN_CHECKPOINT _arrayCopyForward_Default(source_begin, source_end, target_begin); } template inline void arrayCopyForward(TValue * source_begin, TValue * source_end, TValue * target_begin) { SEQAN_CHECKPOINT _arrayCopyForward_Pointer(source_begin, source_end, target_begin, typename IsSimple::Type() ); } ////////////////////////////////////////////////////////////////////////////// //arrayCopyBackward ////////////////////////////////////////////////////////////////////////////// template inline void _arrayCopyBackward_Pointer(TValue * source_begin, TValue * source_end, TValue * target_begin, True) { SEQAN_CHECKPOINT memmove(target_begin, source_begin, (source_end - source_begin) * sizeof(TValue)); } template inline void _arrayCopyBackward_Pointer(TValue * source_begin, TValue * source_end, TValue * target_begin, False) { SEQAN_CHECKPOINT _arrayCopyBackward_Default(source_begin, source_end, target_begin); } template inline void arrayCopyBackward(TValue * source_begin, TValue * source_end, TValue * target_begin) { SEQAN_CHECKPOINT _arrayCopyBackward_Pointer(source_begin, source_end, target_begin, typename IsSimple::Type() ); } ////////////////////////////////////////////////////////////////////////////// //arrayMoveForward ////////////////////////////////////////////////////////////////////////////// template inline void _arrayMoveForward_Pointer(TValue * source_begin, TValue * source_end, TValue * target_begin, True) { SEQAN_CHECKPOINT memmove(target_begin, source_begin, (source_end - source_begin) * sizeof(TValue)); } template inline void _arrayMoveForward_Pointer(TValue * source_begin, TValue * source_end, TValue * target_begin, False) { SEQAN_CHECKPOINT _arrayMoveForward_Default(source_begin, source_end, target_begin); } template inline void arrayMoveForward(TValue * source_begin, TValue * source_end, TValue * target_begin) { SEQAN_CHECKPOINT _arrayMoveForward_Pointer(source_begin, source_end, target_begin, typename IsSimple::Type() ); } ////////////////////////////////////////////////////////////////////////////// //arrayMoveBackward ////////////////////////////////////////////////////////////////////////////// template inline void _arrayMoveBackward_Pointer(TValue * source_begin, TValue * source_end, TValue * target_begin, True) { SEQAN_CHECKPOINT memmove(target_begin, source_begin, (source_end - source_begin) * sizeof(TValue)); } template inline void _arrayMoveBackward_Pointer(TValue * source_begin, TValue * source_end, TValue * target_begin, False) { SEQAN_CHECKPOINT _arrayMoveBackward_Default(source_begin, source_end, target_begin); } template inline void arrayMoveBackward(TValue * source_begin, TValue * source_end, TValue * target_begin) { SEQAN_CHECKPOINT _arrayMoveBackward_Pointer(source_begin, source_end, target_begin, typename IsSimple::Type() ); } ////////////////////////////////////////////////////////////////////////////// //arrayClearSpace ////////////////////////////////////////////////////////////////////////////// template inline void _arrayClearSpace_Pointer(TValue * array_begin, size_t array_length, size_t keep_from, size_t move_to, True) { if (keep_from == move_to) return; SEQAN_CHECKPOINT arrayMove(array_begin + keep_from, array_begin + array_length, array_begin + move_to); } template inline void _arrayClearSpace_Pointer(TValue * array_begin, size_t array_length, size_t keep_from, size_t move_to, False) { _arrayClearSpace_Default(array_begin, array_length, keep_from, move_to); } template void arrayClearSpace(TValue * array_begin, size_t array_length, size_t keep_from, size_t move_to) { _arrayClearSpace_Pointer(array_begin, array_length, keep_from, move_to, typename IsSimple::Type() ); } ////////////////////////////////////////////////////////////////////////////// // IsSimple specializations ////////////////////////////////////////////////////////////////////////////// // standard types template <> struct _IsSimple< bool > { typedef True Type; }; template <> struct _IsSimple< char > { typedef True Type; }; template <> struct _IsSimple< unsigned char > { typedef True Type; }; template <> struct _IsSimple< unsigned short > { typedef True Type; }; template <> struct _IsSimple< unsigned int > { typedef True Type; }; template <> struct _IsSimple< unsigned long > { typedef True Type; }; template <> struct _IsSimple< signed char > { typedef True Type; }; template <> struct _IsSimple< signed short > { typedef True Type; }; template <> struct _IsSimple< signed int > { typedef True Type; }; template <> struct _IsSimple< signed long > { typedef True Type; }; template <> struct _IsSimple< float > { typedef True Type; }; template <> struct _IsSimple< double > { typedef True Type; }; template <> struct _IsSimple< long double > { typedef True Type; }; // user defined types (re-specializations are allowed here) template <> struct IsSimple< wchar_t > { typedef True Type; }; template <> struct IsSimple< __int64 > { typedef True Type; }; ////////////////////////////////////////////////////////////////////////////// // gapValue ////////////////////////////////////////////////////////////////////////////// inline char const & gapValueImpl(char *) { SEQAN_CHECKPOINT static char const _gap = '-'; return _gap; } inline char const & gapValueImpl(char const *) { SEQAN_CHECKPOINT static char const _gap = '-'; return _gap; } ////////////////////////////////////////////////////////////////////////////// // generic extreme values ////////////////////////////////////////////////////////////////////////////// template inline T const & supremumValueImpl(T *) { SEQAN_CHECKPOINT return SupremumValue::VALUE; } template inline T const & infimumValueImpl(T *) { SEQAN_CHECKPOINT return InfimumValue::VALUE; } ////////////////////////////////////////////////////////////////////////////// // bool ////////////////////////////////////////////////////////////////////////////// template <> struct BitsPerValue< bool > { enum { VALUE = 1 }; }; /* ////////////////////////////////////////////////////////////////////////////// // char ////////////////////////////////////////////////////////////////////////////// inline char const & supremumValueImpl(char *) { SEQAN_CHECKPOINT static char const _value = (char) 127; return _value; } inline char const & infimumValueImpl(char *) { SEQAN_CHECKPOINT static char const _value = (char) -128; return _value; } ////////////////////////////////////////////////////////////////////////////// // signed char ////////////////////////////////////////////////////////////////////////////// inline signed char const & supremumValueImpl(signed char *) { SEQAN_CHECKPOINT static signed char const _value = 127; return _value; } inline signed char const & infimumValueImpl(signed char *) { SEQAN_CHECKPOINT static signed char const _value = -128; return _value; } ////////////////////////////////////////////////////////////////////////////// // unsigned char ////////////////////////////////////////////////////////////////////////////// inline unsigned char const & supremumValueImpl(unsigned char *) { SEQAN_CHECKPOINT static unsigned char const _value = 255; return _value; } inline unsigned char const & infimumValueImpl(unsigned char *) { SEQAN_CHECKPOINT static unsigned char const _value = 0; return _value; } ////////////////////////////////////////////////////////////////////////////// // wchar_t ////////////////////////////////////////////////////////////////////////////// inline wchar_t const & supremumValueImpl(wchar_t *) { SEQAN_CHECKPOINT static wchar_t const _value = 1UL << (BitsPerValue::VALUE) - 1; return _value; } inline wchar_t const & infimumValueImpl(wchar_t *) { SEQAN_CHECKPOINT static wchar_t const _value = 0; return _value; } ////////////////////////////////////////////////////////////////////////////// // signed short ////////////////////////////////////////////////////////////////////////////// inline signed short const & supremumValueImpl(signed short *) { SEQAN_CHECKPOINT static signed short const _value = (((1 << (BitsPerValue::VALUE - 2)) - 1) << 1) + 1; return _value; } inline signed short const & infimumValueImpl(signed short *dummy) { SEQAN_CHECKPOINT static signed short const _value = -supremumValueImpl(dummy) - 1; return _value; } ////////////////////////////////////////////////////////////////////////////// // unsigned short ////////////////////////////////////////////////////////////////////////////// inline unsigned short const & supremumValueImpl(unsigned short *) { SEQAN_CHECKPOINT static unsigned short const _value = (((1 << (BitsPerValue::VALUE - 1)) - 1) << 1) + 1; return _value; } inline unsigned short const & infimumValueImpl(unsigned short *) { SEQAN_CHECKPOINT static unsigned short const _value = 0; return _value; } ////////////////////////////////////////////////////////////////////////////// // signed int ////////////////////////////////////////////////////////////////////////////// inline signed int const & supremumValueImpl(signed int *) { SEQAN_CHECKPOINT static signed int const _value = (((1 << (BitsPerValue::VALUE - 2)) - 1) << 1) + 1; return _value; } inline signed int const & infimumValueImpl(signed int *dummy) { SEQAN_CHECKPOINT static signed int const _value = -supremumValueImpl(dummy) - 1; return _value; } ////////////////////////////////////////////////////////////////////////////// // unsigned int ////////////////////////////////////////////////////////////////////////////// inline unsigned int const & supremumValueImpl(unsigned int *) { SEQAN_CHECKPOINT static unsigned int const _value = ~0ul; return _value; } inline unsigned int const & infimumValueImpl(unsigned int *) { SEQAN_CHECKPOINT static unsigned int const _value = 0; return _value; } ////////////////////////////////////////////////////////////////////////////// // signed long ////////////////////////////////////////////////////////////////////////////// inline signed long const & supremumValueImpl(signed long *) { SEQAN_CHECKPOINT static signed long const _value = (((1 << (BitsPerValue::VALUE - 2)) - 1) << 1) + 1; return _value; } inline signed long const & infimumValueImpl(signed long *dummy) { SEQAN_CHECKPOINT static signed long const _value = -supremumValueImpl(dummy) - 1; return _value; } ////////////////////////////////////////////////////////////////////////////// // unsigned long ////////////////////////////////////////////////////////////////////////////// inline unsigned long const & supremumValueImpl(unsigned long *) { SEQAN_CHECKPOINT static unsigned long const _value = ~0ul; return _value; } inline unsigned long const & infimumValueImpl(unsigned long *) { SEQAN_CHECKPOINT static unsigned long const _value = 0; return _value; } ////////////////////////////////////////////////////////////////////////////// // signed 64bit int (cannot use long long <- no ISO C++) ////////////////////////////////////////////////////////////////////////////// inline __int64 const & supremumValueImpl(__int64 *) { SEQAN_CHECKPOINT static __int64 const _value = ((((__int64)1 << (BitsPerValue<__int64>::VALUE - 2)) - 1) << 1) + 1; return _value; } inline __int64 const & infimumValueImpl(__int64 *dummy) { SEQAN_CHECKPOINT static __int64 const _value = -supremumValueImpl(dummy) - 1; return _value; } */ ////////////////////////////////////////////////////////////////////////////// // float ////////////////////////////////////////////////////////////////////////////// inline float const & supremumValueImpl(float *) { SEQAN_CHECKPOINT #ifdef PLATFORM_WINDOWS static float const _value = ::std::numeric_limits::infinity( ); #else static float const _value = 3.40282347e+38F; #endif return _value; } inline float const & infimumValueImpl(float *) { SEQAN_CHECKPOINT #ifdef PLATFORM_WINDOWS static float const _value = -::std::numeric_limits::infinity( ); #else static float const _value = -3.40282347e+38F; #endif return _value; } ////////////////////////////////////////////////////////////////////////////// // double ////////////////////////////////////////////////////////////////////////////// inline double const & supremumValueImpl(double *) { SEQAN_CHECKPOINT #ifdef PLATFORM_WINDOWS static double const _value = ::std::numeric_limits::infinity( ); #else static double const _value = 1.7976931348623157e+308; #endif return _value; } inline double const & infimumValueImpl(double *) { SEQAN_CHECKPOINT #ifdef PLATFORM_WINDOWS static double const _value = -::std::numeric_limits::infinity( ); #else static double const _value = -1.7976931348623157e+308; #endif return _value; } ////////////////////////////////////////////////////////////////////////////// // long double ////////////////////////////////////////////////////////////////////////////// inline long double const & supremumValueImpl(long double *) { SEQAN_CHECKPOINT #ifdef PLATFORM_WINDOWS static long double const _value = ::std::numeric_limits::infinity( ); #else static long double const _value = 1.7976931348623157e+308; #endif return _value; } inline long double const & infimumValueImpl(long double *) { SEQAN_CHECKPOINT #ifdef PLATFORM_WINDOWS static long double const _value = -::std::numeric_limits::infinity( ); #else static long double const _value = -1.7976931348623157e+308; #endif return _value; } ////////////////////////////////////////////////////////////////////////////// }// namespace SEQAN_NAMESPACE_MAIN #endif //#ifndef SEQAN_HEADER_... ugene-1.9.8/src/plugins_3rdparty/bowtie/src/bowtie/SeqAn-1.1/seqan/basic/basic_operator.h0000644000175000017500000000225211651544326027634 0ustar ilyailya /*========================================================================== SeqAn - The Library for Sequence Analysis http://www.seqan.de ============================================================================ Copyright (C) 2007 This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. ============================================================================ $Id: basic_operator.h,v 1.1 2008/08/25 16:20:01 langmead Exp $ ==========================================================================*/ #ifndef SEQAN_HEADER_BASIC_OPERATOR_H #define SEQAN_HEADER_BASIC_OPERATOR_H namespace SEQAN_NAMESPACE_MAIN { } //namespace SEQAN_NAMESPACE_MAIN #endif //#ifndef SEQAN_HEADER_... ugene-1.9.8/src/plugins_3rdparty/bowtie/src/bowtie/SeqAn-1.1/seqan/basic/basic_metaprogramming.h0000644000175000017500000002052011651544326031170 0ustar ilyailya /*========================================================================== SeqAn - The Library for Sequence Analysis http://www.seqan.de ============================================================================ Copyright (C) 2007 This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. ============================================================================ $Id: basic_metaprogramming.h,v 1.2 2009/02/19 01:51:23 langmead Exp $ ==========================================================================*/ #ifndef SEQAN_BASIC_METAPROGRAMMING_H #define SEQAN_BASIC_METAPROGRAMMING_H namespace SEQAN_NAMESPACE_MAIN { ////////////////////////////////////////////////////////////////////////////// // generic "if" (using meta-programming) // if Flag is true, the resulting type is Type1 // if Flag is false, the resulting type is Type2 ////////////////////////////////////////////////////////////////////////////// template struct IF { typedef Type1 Type; }; template struct IF { typedef Type2 Type; }; ////////////////////////////////////////////////////////////////////////////// // generic type comparison (using meta-programming) // if Type1 equals Type2, VALUE is true // if Type1 differs from Type2, VALUE is false ////////////////////////////////////////////////////////////////////////////// template struct TYPECMP { typedef False Type; enum { VALUE = false }; }; template struct TYPECMP { typedef True Type; enum { VALUE = true }; }; ////////////////////////////////////////////////////////////////////////////// // generic "switch" (using meta-programming) ////////////////////////////////////////////////////////////////////////////// const int DEFAULT = ~(~0u >> 1); // initialize with the smallest int struct NilCase {}; template struct CASE { enum { tag = tag_ }; typedef Type_ Type; typedef Next_ Next; }; template class SWITCH { typedef typename Case::Next NextCase; enum { caseTag = Case::tag, found = (caseTag == tag || caseTag == DEFAULT) }; public: typedef typename IF< found, typename Case::Type, typename SWITCH::Type >::Type Type; }; template class SWITCH { public: typedef NilCase Type; }; ////////////////////////////////////////////////////////////////////////////// // generic loops (using meta-programming) // corresponds to for(i=1; i<=I; ++i) ... ////////////////////////////////////////////////////////////////////////////// // example of a loop Worker class struct WorkerNothing { template static inline void body(Arg &arg, int I) {} }; template class LOOP { public: template static inline void run(Arg &arg) { LOOP::run(arg); Worker::body(arg, I); } }; template class LOOP { public: // end of loop template static inline void run(Arg &) {} }; ////////////////////////////////////////////////////////////////////////////// // generic reverse loops (using meta-programming) // corresponds to for(i=I; i>0; --i) ... ////////////////////////////////////////////////////////////////////////////// template class LOOP_REVERSE { public: template static inline void run(Arg &arg) { Worker::body(arg, I); LOOP_REVERSE::run(arg); } }; template class LOOP_REVERSE { public: // end of loop template static inline void run(Arg &) {} }; ////////////////////////////////////////////////////////////////////////////// // logarithmus dualis (using meta-programming) ////////////////////////////////////////////////////////////////////////////// template < __int64 numerus > struct Log2 { enum { VALUE = Log2<(numerus + 1) / 2>::VALUE + 1 }; // ceil(log_2(n)) }; template < __int64 numerus > struct Log2Floor { enum { VALUE = Log2Floor::VALUE + 1 }; // floor(log_2(n)) }; template <> struct Log2<1> { enum { VALUE = 0 }; }; template <> struct Log2<0> { enum { VALUE = 0 }; }; template <> struct Log2Floor<1> { enum { VALUE = 0 }; }; template <> struct Log2Floor<0> { enum { VALUE = 0 }; }; ////////////////////////////////////////////////////////////////////////////// // exponentiation (using meta-programming) ////////////////////////////////////////////////////////////////////////////// template < __int64 base, __int64 exponent > struct Power { enum { VALUE = Power::VALUE * Power::VALUE }; }; template < __int64 base > struct Power { enum { VALUE = base }; }; template < __int64 base > struct Power { enum { VALUE = 1 }; }; ////////////////////////////////////////////////////////////////////////////// // memset with fill size (using meta-programming) ////////////////////////////////////////////////////////////////////////////// using ::memset; template struct MemsetWorker { finline static void run(unsigned char* ptr, unsigned char c) { memset(ptr, c, SIZE); } }; template struct MemsetWorker { finline static void run(unsigned char* ptr, unsigned char c) { *((unsigned*)ptr) = ((unsigned)c << 24) + ((unsigned)c << 16) + ((unsigned)c << 8) + (unsigned)c; MemsetWorker::run(ptr + 4, c); } }; template <> struct MemsetWorker<0, true> { finline static void run(unsigned char*, unsigned char) {} }; template <> struct MemsetWorker<1, true> { finline static void run(unsigned char* ptr, unsigned char c) { *ptr = c; } }; template <> struct MemsetWorker<2, true> { finline static void run(unsigned char* ptr, unsigned char c) { *(unsigned short *)ptr = ((unsigned short)c << 8) + (unsigned short)c; } }; template <> struct MemsetWorker<3, true> { finline static void run(unsigned char* ptr, unsigned char c) { MemsetWorker<2, true>::run(ptr, c); MemsetWorker<1, true>::run(ptr + 2, c); } }; template finline void memset(void* ptr, unsigned char c) { MemsetWorker::run((unsigned char*)ptr, c); } ////////////////////////////////////////////////////////////////////////////// // memset with fill value (using meta-programming) ////////////////////////////////////////////////////////////////////////////// template struct MemsetConstValueWorker { finline static void run(unsigned char* ptr) { memset(ptr, c, SIZE); } }; template struct MemsetConstValueWorker { finline static void run(unsigned char* ptr) { *((unsigned*)ptr) = ((unsigned)c << 24) + ((unsigned)c << 16) + ((unsigned)c << 8) + (unsigned)c; MemsetConstValueWorker::run(ptr + 4); } }; template struct MemsetConstValueWorker<0, true, c> { finline static void run(unsigned char* ptr) {} }; template struct MemsetConstValueWorker<1, true, c> { finline static void run(unsigned char* ptr) { *ptr = c; } }; template struct MemsetConstValueWorker<2, true, c> { finline static void run(unsigned char* ptr) { *(unsigned short *)ptr = ((unsigned short)c << 8) + (unsigned short)c; } }; template struct MemsetConstValueWorker<3, true, c> { finline static void run(unsigned char* ptr) { MemsetConstValueWorker<2, true, c>::run(ptr); MemsetConstValueWorker<1, true, c>::run(ptr + 2); } }; template finline void memset(void* ptr) { MemsetConstValueWorker::run((unsigned char*)ptr); } } #endif ugene-1.9.8/src/plugins_3rdparty/bowtie/src/bowtie/SeqAn-1.1/seqan/basic/basic_host.h0000644000175000017500000001015711651544326026761 0ustar ilyailya /*========================================================================== SeqAn - The Library for Sequence Analysis http://www.seqan.de ============================================================================ Copyright (C) 2007 This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. ============================================================================ $Id: basic_host.h,v 1.1 2008/08/25 16:20:01 langmead Exp $ ==========================================================================*/ #ifndef SEQAN_HEADER_BASIC_HOST_H #define SEQAN_HEADER_BASIC_HOST_H namespace SEQAN_NAMESPACE_MAIN { ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// // Host Functions ////////////////////////////////////////////////////////////////////////////// //these functions assume that the hosted object exports a function "_dataHost" //that returns a reference to a holder type of Host::Type & ////////////////////////////////////////////////////////////////////////////// template inline bool emptyHost(T const & me) { SEQAN_CHECKPOINT return empty(_dataHost(me)); } ////////////////////////////////////////////////////////////////////////////// template inline bool dependentHost(T const & me) { SEQAN_CHECKPOINT return dependent(_dataHost(me)); } ////////////////////////////////////////////////////////////////////////////// template inline void clearHost(T & me) { SEQAN_CHECKPOINT clear(_dataHost(me)); } ////////////////////////////////////////////////////////////////////////////// template inline void createHost(T & me) { SEQAN_CHECKPOINT create(_dataHost(me)); } //____________________________________________________________________________ template inline void createHost(T & me, THost & host_) { SEQAN_CHECKPOINT create(_dataHost(me), host_); } template inline void createHost(T & me, THost const & host_) { SEQAN_CHECKPOINT create(_dataHost(me), host_); } ////////////////////////////////////////////////////////////////////////////// template inline void setHost(T & me, THost & host_) { SEQAN_CHECKPOINT setValue(_dataHost(me), host_); } template inline void setHost(T & me, THost const & host_) { SEQAN_CHECKPOINT setValue(_dataHost(me), host_); } ////////////////////////////////////////////////////////////////////////////// template inline typename Host::Type & host(T & me) { SEQAN_CHECKPOINT return value(_dataHost(me)); } template inline typename Host::Type & host(T const & me) { SEQAN_CHECKPOINT return value(_dataHost(me)); } ////////////////////////////////////////////////////////////////////////////// template inline void assignHost(T & me, THost & host_) { SEQAN_CHECKPOINT assignValue(_dataHost(me), host_); } template inline void assignHost(T & me, THost const & host_) { SEQAN_CHECKPOINT assignValue(_dataHost(me), host_); } ////////////////////////////////////////////////////////////////////////////// template inline void moveHost(T & me, THost & host_) { SEQAN_CHECKPOINT moveValue(_dataHost(me), host_); } template inline void moveHost(T & me, THost const & host_) { SEQAN_CHECKPOINT moveValue(_dataHost(me), host_); } ////////////////////////////////////////////////////////////////////////////// } //namespace SEQAN_NAMESPACE_MAIN #endif //#ifndef SEQAN_HEADER_... ugene-1.9.8/src/plugins_3rdparty/bowtie/src/bowtie/SeqAn-1.1/seqan/basic/basic_type.h0000644000175000017500000003644411651544326026774 0ustar ilyailya /*========================================================================== SeqAn - The Library for Sequence Analysis http://www.seqan.de ============================================================================ Copyright (C) 2007 This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. ============================================================================ $Id: basic_type.h,v 1.1 2008/08/25 16:20:01 langmead Exp $ ==========================================================================*/ #ifndef SEQAN_HEADER_BASIC_TYPE_H #define SEQAN_HEADER_BASIC_TYPE_H namespace SEQAN_NAMESPACE_MAIN { ////////////////////////////////////////////////////////////////////////////// /** .Metafunction.Value: ..summary:Type of the items in the container. ..signature:Value::Type ..param.T:Type for which the value type is determined. ..returns.param.Type:Value type of $T$. ..remarks.text:The value type of a container $T$ is the type of the elements in $T$. For example, the value type of a sequence of $int$ is $int$. ..example.code:Value >::Type c; //c has type char */ template struct Value { typedef T Type; }; /* template struct Value { typedef T Type; }; */ //____________________________________________________________________________ /** .Metafunction.GetValue: ..summary:Type for reading values. ..signature:GetValue::Type ..param.T:Type of container that holds a value. ..returns.param.Type:GetValue type of $T$. ..remarks.text:Depending on $T$, the $GetValue$-type can either be $Value::Type &$ or $Value::Type$. ..text:$GetValue$ is the return type of @Function.getValue@ that allows a (read-only) access to objects. Do not confuse it with @Function.value@ that returns a @Metafunction.Reference.reference@ to the value. ..see:Metafunction.Value ..see:Function.getValue */ template struct GetValue { typedef typename Value::Type const & Type; }; template struct GetValue: public GetValue { }; //____________________________________________________________________________ /** .Metafunction.Reference: ..summary:Reference type. ..signature:Reference::Type ..param.T:A Type. ..returns.param.Type:Either $T &$ or a proxy object @Class.Proxy@ for $T$. ..see:Metafunction.Value ..see:Metafunction.GetValue */ template struct Reference { typedef typename Value::Type & Type; }; template struct Reference { typedef typename Value::Type const & Type; }; //____________________________________________________________________________ /** .Metafunction.Size: ..summary:Type of an object that is suitable to hold size information. ..signature:Size::Type ..param.T:Type for which the size type is determined. ..returns.param.Type:Size type of $T$. ..remarks.text:In most cases this type is $size_t$. */ template struct Size { typedef size_t Type; }; template struct Size: Size { }; //____________________________________________________________________________ /** .Metafunction.Difference: ..summary:Type of an object that stores the difference between two iterators. ..signature:Difference::Type ..param.T:Type for which the difference type is determined. ...type:Class.Iter ..returns.param.Type:Difference type of $T$. ..remarks.text:In most cases this type is $ptrdiff_t$. ..see:Metafunction.Size */ template struct Difference { typedef ptrdiff_t Type; }; template struct Difference: Difference { }; //____________________________________________________________________________ /** .Metafunction.Position: ..summary:Type of an object that represents a position in a container. ..signature:Position::Type ..param.T:Type for which the position type is determined. ...type:Class.Iter ...type:Class.String ..returns.param.Type:Position type of $T$. ..see:Metafunction.Iterator */ template struct Position { typedef typename Size::Type Type; }; template struct Position: Position { }; //____________________________________________________________________________ /** .Metafunction.Host: ..summary:Type of the object a given object depends on. ..signature:Host::Type ..param.T:Type for which the host type is determined. ..returns.param.Type:Host type of $T$. */ template struct Host { typedef T Type; }; //____________________________________________________________________________ /** .Metafunction.Spec: ..summary:The spec of a class. ..signature:Spec::Type ..param.T:Type for which the spec is determined. ..returns.param.Type:Spec of $T$. ..remarks:The spec of a SeqAn type is the class that is used in template subclassing to specify the specialization. For example, the spec of $String >$ is $Alloc<>$. */ // default case template struct Spec { typedef void Type; }; // one argument case template